xref: /freebsd/contrib/llvm-project/llvm/lib/Transforms/InstCombine/InstCombineSelect.cpp (revision 0ad011ececb978e22a9bff2acf76633b094f1ff6)
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/STLExtras.h"
16 #include "llvm/ADT/SmallVector.h"
17 #include "llvm/Analysis/AssumptionCache.h"
18 #include "llvm/Analysis/CmpInstAnalysis.h"
19 #include "llvm/Analysis/InstructionSimplify.h"
20 #include "llvm/Analysis/OverflowInstAnalysis.h"
21 #include "llvm/Analysis/ValueTracking.h"
22 #include "llvm/Analysis/VectorUtils.h"
23 #include "llvm/IR/BasicBlock.h"
24 #include "llvm/IR/Constant.h"
25 #include "llvm/IR/ConstantRange.h"
26 #include "llvm/IR/Constants.h"
27 #include "llvm/IR/DerivedTypes.h"
28 #include "llvm/IR/IRBuilder.h"
29 #include "llvm/IR/InstrTypes.h"
30 #include "llvm/IR/Instruction.h"
31 #include "llvm/IR/Instructions.h"
32 #include "llvm/IR/IntrinsicInst.h"
33 #include "llvm/IR/Intrinsics.h"
34 #include "llvm/IR/Operator.h"
35 #include "llvm/IR/PatternMatch.h"
36 #include "llvm/IR/Type.h"
37 #include "llvm/IR/User.h"
38 #include "llvm/IR/Value.h"
39 #include "llvm/Support/Casting.h"
40 #include "llvm/Support/ErrorHandling.h"
41 #include "llvm/Support/KnownBits.h"
42 #include "llvm/Transforms/InstCombine/InstCombiner.h"
43 #include <cassert>
44 #include <utility>
45 
46 #define DEBUG_TYPE "instcombine"
47 #include "llvm/Transforms/Utils/InstructionWorklist.h"
48 
49 using namespace llvm;
50 using namespace PatternMatch;
51 
52 
53 /// Replace a select operand based on an equality comparison with the identity
54 /// constant of a binop.
55 static Instruction *foldSelectBinOpIdentity(SelectInst &Sel,
56                                             const TargetLibraryInfo &TLI,
57                                             InstCombinerImpl &IC) {
58   // The select condition must be an equality compare with a constant operand.
59   Value *X;
60   Constant *C;
61   CmpInst::Predicate Pred;
62   if (!match(Sel.getCondition(), m_Cmp(Pred, m_Value(X), m_Constant(C))))
63     return nullptr;
64 
65   bool IsEq;
66   if (ICmpInst::isEquality(Pred))
67     IsEq = Pred == ICmpInst::ICMP_EQ;
68   else if (Pred == FCmpInst::FCMP_OEQ)
69     IsEq = true;
70   else if (Pred == FCmpInst::FCMP_UNE)
71     IsEq = false;
72   else
73     return nullptr;
74 
75   // A select operand must be a binop.
76   BinaryOperator *BO;
77   if (!match(Sel.getOperand(IsEq ? 1 : 2), m_BinOp(BO)))
78     return nullptr;
79 
80   // The compare constant must be the identity constant for that binop.
81   // If this a floating-point compare with 0.0, any zero constant will do.
82   Type *Ty = BO->getType();
83   Constant *IdC = ConstantExpr::getBinOpIdentity(BO->getOpcode(), Ty, true);
84   if (IdC != C) {
85     if (!IdC || !CmpInst::isFPPredicate(Pred))
86       return nullptr;
87     if (!match(IdC, m_AnyZeroFP()) || !match(C, m_AnyZeroFP()))
88       return nullptr;
89   }
90 
91   // Last, match the compare variable operand with a binop operand.
92   Value *Y;
93   if (!BO->isCommutative() && !match(BO, m_BinOp(m_Value(Y), m_Specific(X))))
94     return nullptr;
95   if (!match(BO, m_c_BinOp(m_Value(Y), m_Specific(X))))
96     return nullptr;
97 
98   // +0.0 compares equal to -0.0, and so it does not behave as required for this
99   // transform. Bail out if we can not exclude that possibility.
100   if (isa<FPMathOperator>(BO))
101     if (!BO->hasNoSignedZeros() &&
102         !cannotBeNegativeZero(Y, IC.getDataLayout(), &TLI))
103       return nullptr;
104 
105   // BO = binop Y, X
106   // S = { select (cmp eq X, C), BO, ? } or { select (cmp ne X, C), ?, BO }
107   // =>
108   // S = { select (cmp eq X, C),  Y, ? } or { select (cmp ne X, C), ?,  Y }
109   return IC.replaceOperand(Sel, IsEq ? 1 : 2, Y);
110 }
111 
112 /// This folds:
113 ///  select (icmp eq (and X, C1)), TC, FC
114 ///    iff C1 is a power 2 and the difference between TC and FC is a power-of-2.
115 /// To something like:
116 ///  (shr (and (X, C1)), (log2(C1) - log2(TC-FC))) + FC
117 /// Or:
118 ///  (shl (and (X, C1)), (log2(TC-FC) - log2(C1))) + FC
119 /// With some variations depending if FC is larger than TC, or the shift
120 /// isn't needed, or the bit widths don't match.
121 static Value *foldSelectICmpAnd(SelectInst &Sel, ICmpInst *Cmp,
122                                 InstCombiner::BuilderTy &Builder) {
123   const APInt *SelTC, *SelFC;
124   if (!match(Sel.getTrueValue(), m_APInt(SelTC)) ||
125       !match(Sel.getFalseValue(), m_APInt(SelFC)))
126     return nullptr;
127 
128   // If this is a vector select, we need a vector compare.
129   Type *SelType = Sel.getType();
130   if (SelType->isVectorTy() != Cmp->getType()->isVectorTy())
131     return nullptr;
132 
133   Value *V;
134   APInt AndMask;
135   bool CreateAnd = false;
136   ICmpInst::Predicate Pred = Cmp->getPredicate();
137   if (ICmpInst::isEquality(Pred)) {
138     if (!match(Cmp->getOperand(1), m_Zero()))
139       return nullptr;
140 
141     V = Cmp->getOperand(0);
142     const APInt *AndRHS;
143     if (!match(V, m_And(m_Value(), m_Power2(AndRHS))))
144       return nullptr;
145 
146     AndMask = *AndRHS;
147   } else if (decomposeBitTestICmp(Cmp->getOperand(0), Cmp->getOperand(1),
148                                   Pred, V, AndMask)) {
149     assert(ICmpInst::isEquality(Pred) && "Not equality test?");
150     if (!AndMask.isPowerOf2())
151       return nullptr;
152 
153     CreateAnd = true;
154   } else {
155     return nullptr;
156   }
157 
158   // In general, when both constants are non-zero, we would need an offset to
159   // replace the select. This would require more instructions than we started
160   // with. But there's one special-case that we handle here because it can
161   // simplify/reduce the instructions.
162   APInt TC = *SelTC;
163   APInt FC = *SelFC;
164   if (!TC.isZero() && !FC.isZero()) {
165     // If the select constants differ by exactly one bit and that's the same
166     // bit that is masked and checked by the select condition, the select can
167     // be replaced by bitwise logic to set/clear one bit of the constant result.
168     if (TC.getBitWidth() != AndMask.getBitWidth() || (TC ^ FC) != AndMask)
169       return nullptr;
170     if (CreateAnd) {
171       // If we have to create an 'and', then we must kill the cmp to not
172       // increase the instruction count.
173       if (!Cmp->hasOneUse())
174         return nullptr;
175       V = Builder.CreateAnd(V, ConstantInt::get(SelType, AndMask));
176     }
177     bool ExtraBitInTC = TC.ugt(FC);
178     if (Pred == ICmpInst::ICMP_EQ) {
179       // If the masked bit in V is clear, clear or set the bit in the result:
180       // (V & AndMaskC) == 0 ? TC : FC --> (V & AndMaskC) ^ TC
181       // (V & AndMaskC) == 0 ? TC : FC --> (V & AndMaskC) | TC
182       Constant *C = ConstantInt::get(SelType, TC);
183       return ExtraBitInTC ? Builder.CreateXor(V, C) : Builder.CreateOr(V, C);
184     }
185     if (Pred == ICmpInst::ICMP_NE) {
186       // If the masked bit in V is set, set or clear the bit in the result:
187       // (V & AndMaskC) != 0 ? TC : FC --> (V & AndMaskC) | FC
188       // (V & AndMaskC) != 0 ? TC : FC --> (V & AndMaskC) ^ FC
189       Constant *C = ConstantInt::get(SelType, FC);
190       return ExtraBitInTC ? Builder.CreateOr(V, C) : Builder.CreateXor(V, C);
191     }
192     llvm_unreachable("Only expecting equality predicates");
193   }
194 
195   // Make sure one of the select arms is a power-of-2.
196   if (!TC.isPowerOf2() && !FC.isPowerOf2())
197     return nullptr;
198 
199   // Determine which shift is needed to transform result of the 'and' into the
200   // desired result.
201   const APInt &ValC = !TC.isZero() ? TC : FC;
202   unsigned ValZeros = ValC.logBase2();
203   unsigned AndZeros = AndMask.logBase2();
204 
205   // Insert the 'and' instruction on the input to the truncate.
206   if (CreateAnd)
207     V = Builder.CreateAnd(V, ConstantInt::get(V->getType(), AndMask));
208 
209   // If types don't match, we can still convert the select by introducing a zext
210   // or a trunc of the 'and'.
211   if (ValZeros > AndZeros) {
212     V = Builder.CreateZExtOrTrunc(V, SelType);
213     V = Builder.CreateShl(V, ValZeros - AndZeros);
214   } else if (ValZeros < AndZeros) {
215     V = Builder.CreateLShr(V, AndZeros - ValZeros);
216     V = Builder.CreateZExtOrTrunc(V, SelType);
217   } else {
218     V = Builder.CreateZExtOrTrunc(V, SelType);
219   }
220 
221   // Okay, now we know that everything is set up, we just don't know whether we
222   // have a icmp_ne or icmp_eq and whether the true or false val is the zero.
223   bool ShouldNotVal = !TC.isZero();
224   ShouldNotVal ^= Pred == ICmpInst::ICMP_NE;
225   if (ShouldNotVal)
226     V = Builder.CreateXor(V, ValC);
227 
228   return V;
229 }
230 
231 /// We want to turn code that looks like this:
232 ///   %C = or %A, %B
233 ///   %D = select %cond, %C, %A
234 /// into:
235 ///   %C = select %cond, %B, 0
236 ///   %D = or %A, %C
237 ///
238 /// Assuming that the specified instruction is an operand to the select, return
239 /// a bitmask indicating which operands of this instruction are foldable if they
240 /// equal the other incoming value of the select.
241 static unsigned getSelectFoldableOperands(BinaryOperator *I) {
242   switch (I->getOpcode()) {
243   case Instruction::Add:
244   case Instruction::FAdd:
245   case Instruction::Mul:
246   case Instruction::FMul:
247   case Instruction::And:
248   case Instruction::Or:
249   case Instruction::Xor:
250     return 3;              // Can fold through either operand.
251   case Instruction::Sub:   // Can only fold on the amount subtracted.
252   case Instruction::FSub:
253   case Instruction::FDiv:  // Can only fold on the divisor amount.
254   case Instruction::Shl:   // Can only fold on the shift amount.
255   case Instruction::LShr:
256   case Instruction::AShr:
257     return 1;
258   default:
259     return 0;              // Cannot fold
260   }
261 }
262 
263 /// We have (select c, TI, FI), and we know that TI and FI have the same opcode.
264 Instruction *InstCombinerImpl::foldSelectOpOp(SelectInst &SI, Instruction *TI,
265                                               Instruction *FI) {
266   // Don't break up min/max patterns. The hasOneUse checks below prevent that
267   // for most cases, but vector min/max with bitcasts can be transformed. If the
268   // one-use restrictions are eased for other patterns, we still don't want to
269   // obfuscate min/max.
270   if ((match(&SI, m_SMin(m_Value(), m_Value())) ||
271        match(&SI, m_SMax(m_Value(), m_Value())) ||
272        match(&SI, m_UMin(m_Value(), m_Value())) ||
273        match(&SI, m_UMax(m_Value(), m_Value()))))
274     return nullptr;
275 
276   // If this is a cast from the same type, merge.
277   Value *Cond = SI.getCondition();
278   Type *CondTy = Cond->getType();
279   if (TI->getNumOperands() == 1 && TI->isCast()) {
280     Type *FIOpndTy = FI->getOperand(0)->getType();
281     if (TI->getOperand(0)->getType() != FIOpndTy)
282       return nullptr;
283 
284     // The select condition may be a vector. We may only change the operand
285     // type if the vector width remains the same (and matches the condition).
286     if (auto *CondVTy = dyn_cast<VectorType>(CondTy)) {
287       if (!FIOpndTy->isVectorTy() ||
288           CondVTy->getElementCount() !=
289               cast<VectorType>(FIOpndTy)->getElementCount())
290         return nullptr;
291 
292       // TODO: If the backend knew how to deal with casts better, we could
293       // remove this limitation. For now, there's too much potential to create
294       // worse codegen by promoting the select ahead of size-altering casts
295       // (PR28160).
296       //
297       // Note that ValueTracking's matchSelectPattern() looks through casts
298       // without checking 'hasOneUse' when it matches min/max patterns, so this
299       // transform may end up happening anyway.
300       if (TI->getOpcode() != Instruction::BitCast &&
301           (!TI->hasOneUse() || !FI->hasOneUse()))
302         return nullptr;
303     } else if (!TI->hasOneUse() || !FI->hasOneUse()) {
304       // TODO: The one-use restrictions for a scalar select could be eased if
305       // the fold of a select in visitLoadInst() was enhanced to match a pattern
306       // that includes a cast.
307       return nullptr;
308     }
309 
310     // Fold this by inserting a select from the input values.
311     Value *NewSI =
312         Builder.CreateSelect(Cond, TI->getOperand(0), FI->getOperand(0),
313                              SI.getName() + ".v", &SI);
314     return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
315                             TI->getType());
316   }
317 
318   Value *OtherOpT, *OtherOpF;
319   bool MatchIsOpZero;
320   auto getCommonOp = [&](Instruction *TI, Instruction *FI, bool Commute,
321                          bool Swapped = false) -> Value * {
322     assert(!(Commute && Swapped) &&
323            "Commute and Swapped can't set at the same time");
324     if (!Swapped) {
325       if (TI->getOperand(0) == FI->getOperand(0)) {
326         OtherOpT = TI->getOperand(1);
327         OtherOpF = FI->getOperand(1);
328         MatchIsOpZero = true;
329         return TI->getOperand(0);
330       } else if (TI->getOperand(1) == FI->getOperand(1)) {
331         OtherOpT = TI->getOperand(0);
332         OtherOpF = FI->getOperand(0);
333         MatchIsOpZero = false;
334         return TI->getOperand(1);
335       }
336     }
337 
338     if (!Commute && !Swapped)
339       return nullptr;
340 
341     // If we are allowing commute or swap of operands, then
342     // allow a cross-operand match. In that case, MatchIsOpZero
343     // means that TI's operand 0 (FI's operand 1) is the common op.
344     if (TI->getOperand(0) == FI->getOperand(1)) {
345       OtherOpT = TI->getOperand(1);
346       OtherOpF = FI->getOperand(0);
347       MatchIsOpZero = true;
348       return TI->getOperand(0);
349     } else if (TI->getOperand(1) == FI->getOperand(0)) {
350       OtherOpT = TI->getOperand(0);
351       OtherOpF = FI->getOperand(1);
352       MatchIsOpZero = false;
353       return TI->getOperand(1);
354     }
355     return nullptr;
356   };
357 
358   if (TI->hasOneUse() || FI->hasOneUse()) {
359     // Cond ? -X : -Y --> -(Cond ? X : Y)
360     Value *X, *Y;
361     if (match(TI, m_FNeg(m_Value(X))) && match(FI, m_FNeg(m_Value(Y)))) {
362       // Intersect FMF from the fneg instructions and union those with the
363       // select.
364       FastMathFlags FMF = TI->getFastMathFlags();
365       FMF &= FI->getFastMathFlags();
366       FMF |= SI.getFastMathFlags();
367       Value *NewSel =
368           Builder.CreateSelect(Cond, X, Y, SI.getName() + ".v", &SI);
369       if (auto *NewSelI = dyn_cast<Instruction>(NewSel))
370         NewSelI->setFastMathFlags(FMF);
371       Instruction *NewFNeg = UnaryOperator::CreateFNeg(NewSel);
372       NewFNeg->setFastMathFlags(FMF);
373       return NewFNeg;
374     }
375 
376     // Min/max intrinsic with a common operand can have the common operand
377     // pulled after the select. This is the same transform as below for binops,
378     // but specialized for intrinsic matching and without the restrictive uses
379     // clause.
380     auto *TII = dyn_cast<IntrinsicInst>(TI);
381     auto *FII = dyn_cast<IntrinsicInst>(FI);
382     if (TII && FII && TII->getIntrinsicID() == FII->getIntrinsicID()) {
383       if (match(TII, m_MaxOrMin(m_Value(), m_Value()))) {
384         if (Value *MatchOp = getCommonOp(TI, FI, true)) {
385           Value *NewSel =
386               Builder.CreateSelect(Cond, OtherOpT, OtherOpF, "minmaxop", &SI);
387           return CallInst::Create(TII->getCalledFunction(), {NewSel, MatchOp});
388         }
389       }
390 
391       // select c, (ldexp v, e0), (ldexp v, e1) -> ldexp v, (select c, e0, e1)
392       // select c, (ldexp v0, e), (ldexp v1, e) -> ldexp (select c, v0, v1), e
393       //
394       // select c, (ldexp v0, e0), (ldexp v1, e1) ->
395       //     ldexp (select c, v0, v1), (select c, e0, e1)
396       if (TII->getIntrinsicID() == Intrinsic::ldexp) {
397         Value *LdexpVal0 = TII->getArgOperand(0);
398         Value *LdexpExp0 = TII->getArgOperand(1);
399         Value *LdexpVal1 = FII->getArgOperand(0);
400         Value *LdexpExp1 = FII->getArgOperand(1);
401         if (LdexpExp0->getType() == LdexpExp1->getType()) {
402           FPMathOperator *SelectFPOp = cast<FPMathOperator>(&SI);
403           FastMathFlags FMF = cast<FPMathOperator>(TII)->getFastMathFlags();
404           FMF &= cast<FPMathOperator>(FII)->getFastMathFlags();
405           FMF |= SelectFPOp->getFastMathFlags();
406 
407           Value *SelectVal = Builder.CreateSelect(Cond, LdexpVal0, LdexpVal1);
408           Value *SelectExp = Builder.CreateSelect(Cond, LdexpExp0, LdexpExp1);
409 
410           CallInst *NewLdexp = Builder.CreateIntrinsic(
411               TII->getType(), Intrinsic::ldexp, {SelectVal, SelectExp});
412           NewLdexp->setFastMathFlags(FMF);
413           return replaceInstUsesWith(SI, NewLdexp);
414         }
415       }
416     }
417 
418     // icmp with a common operand also can have the common operand
419     // pulled after the select.
420     ICmpInst::Predicate TPred, FPred;
421     if (match(TI, m_ICmp(TPred, m_Value(), m_Value())) &&
422         match(FI, m_ICmp(FPred, m_Value(), m_Value()))) {
423       if (TPred == FPred || TPred == CmpInst::getSwappedPredicate(FPred)) {
424         bool Swapped = TPred != FPred;
425         if (Value *MatchOp =
426                 getCommonOp(TI, FI, ICmpInst::isEquality(TPred), Swapped)) {
427           Value *NewSel = Builder.CreateSelect(Cond, OtherOpT, OtherOpF,
428                                                SI.getName() + ".v", &SI);
429           return new ICmpInst(
430               MatchIsOpZero ? TPred : CmpInst::getSwappedPredicate(TPred),
431               MatchOp, NewSel);
432         }
433       }
434     }
435   }
436 
437   // Only handle binary operators (including two-operand getelementptr) with
438   // one-use here. As with the cast case above, it may be possible to relax the
439   // one-use constraint, but that needs be examined carefully since it may not
440   // reduce the total number of instructions.
441   if (TI->getNumOperands() != 2 || FI->getNumOperands() != 2 ||
442       !TI->isSameOperationAs(FI) ||
443       (!isa<BinaryOperator>(TI) && !isa<GetElementPtrInst>(TI)) ||
444       !TI->hasOneUse() || !FI->hasOneUse())
445     return nullptr;
446 
447   // Figure out if the operations have any operands in common.
448   Value *MatchOp = getCommonOp(TI, FI, TI->isCommutative());
449   if (!MatchOp)
450     return nullptr;
451 
452   // If the select condition is a vector, the operands of the original select's
453   // operands also must be vectors. This may not be the case for getelementptr
454   // for example.
455   if (CondTy->isVectorTy() && (!OtherOpT->getType()->isVectorTy() ||
456                                !OtherOpF->getType()->isVectorTy()))
457     return nullptr;
458 
459   // If we are sinking div/rem after a select, we may need to freeze the
460   // condition because div/rem may induce immediate UB with a poison operand.
461   // For example, the following transform is not safe if Cond can ever be poison
462   // because we can replace poison with zero and then we have div-by-zero that
463   // didn't exist in the original code:
464   // Cond ? x/y : x/z --> x / (Cond ? y : z)
465   auto *BO = dyn_cast<BinaryOperator>(TI);
466   if (BO && BO->isIntDivRem() && !isGuaranteedNotToBePoison(Cond)) {
467     // A udiv/urem with a common divisor is safe because UB can only occur with
468     // div-by-zero, and that would be present in the original code.
469     if (BO->getOpcode() == Instruction::SDiv ||
470         BO->getOpcode() == Instruction::SRem || MatchIsOpZero)
471       Cond = Builder.CreateFreeze(Cond);
472   }
473 
474   // If we reach here, they do have operations in common.
475   Value *NewSI = Builder.CreateSelect(Cond, OtherOpT, OtherOpF,
476                                       SI.getName() + ".v", &SI);
477   Value *Op0 = MatchIsOpZero ? MatchOp : NewSI;
478   Value *Op1 = MatchIsOpZero ? NewSI : MatchOp;
479   if (auto *BO = dyn_cast<BinaryOperator>(TI)) {
480     BinaryOperator *NewBO = BinaryOperator::Create(BO->getOpcode(), Op0, Op1);
481     NewBO->copyIRFlags(TI);
482     NewBO->andIRFlags(FI);
483     return NewBO;
484   }
485   if (auto *TGEP = dyn_cast<GetElementPtrInst>(TI)) {
486     auto *FGEP = cast<GetElementPtrInst>(FI);
487     Type *ElementType = TGEP->getResultElementType();
488     return TGEP->isInBounds() && FGEP->isInBounds()
489                ? GetElementPtrInst::CreateInBounds(ElementType, Op0, {Op1})
490                : GetElementPtrInst::Create(ElementType, Op0, {Op1});
491   }
492   llvm_unreachable("Expected BinaryOperator or GEP");
493   return nullptr;
494 }
495 
496 static bool isSelect01(const APInt &C1I, const APInt &C2I) {
497   if (!C1I.isZero() && !C2I.isZero()) // One side must be zero.
498     return false;
499   return C1I.isOne() || C1I.isAllOnes() || C2I.isOne() || C2I.isAllOnes();
500 }
501 
502 /// Try to fold the select into one of the operands to allow further
503 /// optimization.
504 Instruction *InstCombinerImpl::foldSelectIntoOp(SelectInst &SI, Value *TrueVal,
505                                                 Value *FalseVal) {
506   // See the comment above getSelectFoldableOperands for a description of the
507   // transformation we are doing here.
508   auto TryFoldSelectIntoOp = [&](SelectInst &SI, Value *TrueVal,
509                                  Value *FalseVal,
510                                  bool Swapped) -> Instruction * {
511     auto *TVI = dyn_cast<BinaryOperator>(TrueVal);
512     if (!TVI || !TVI->hasOneUse() || isa<Constant>(FalseVal))
513       return nullptr;
514 
515     unsigned SFO = getSelectFoldableOperands(TVI);
516     unsigned OpToFold = 0;
517     if ((SFO & 1) && FalseVal == TVI->getOperand(0))
518       OpToFold = 1;
519     else if ((SFO & 2) && FalseVal == TVI->getOperand(1))
520       OpToFold = 2;
521 
522     if (!OpToFold)
523       return nullptr;
524 
525     // TODO: We probably ought to revisit cases where the select and FP
526     // instructions have different flags and add tests to ensure the
527     // behaviour is correct.
528     FastMathFlags FMF;
529     if (isa<FPMathOperator>(&SI))
530       FMF = SI.getFastMathFlags();
531     Constant *C = ConstantExpr::getBinOpIdentity(
532         TVI->getOpcode(), TVI->getType(), true, FMF.noSignedZeros());
533     Value *OOp = TVI->getOperand(2 - OpToFold);
534     // Avoid creating select between 2 constants unless it's selecting
535     // between 0, 1 and -1.
536     const APInt *OOpC;
537     bool OOpIsAPInt = match(OOp, m_APInt(OOpC));
538     if (!isa<Constant>(OOp) ||
539         (OOpIsAPInt && isSelect01(C->getUniqueInteger(), *OOpC))) {
540       Value *NewSel = Builder.CreateSelect(SI.getCondition(), Swapped ? C : OOp,
541                                            Swapped ? OOp : C, "", &SI);
542       if (isa<FPMathOperator>(&SI))
543         cast<Instruction>(NewSel)->setFastMathFlags(FMF);
544       NewSel->takeName(TVI);
545       BinaryOperator *BO =
546           BinaryOperator::Create(TVI->getOpcode(), FalseVal, NewSel);
547       BO->copyIRFlags(TVI);
548       return BO;
549     }
550     return nullptr;
551   };
552 
553   if (Instruction *R = TryFoldSelectIntoOp(SI, TrueVal, FalseVal, false))
554     return R;
555 
556   if (Instruction *R = TryFoldSelectIntoOp(SI, FalseVal, TrueVal, true))
557     return R;
558 
559   return nullptr;
560 }
561 
562 /// We want to turn:
563 ///   (select (icmp eq (and X, Y), 0), (and (lshr X, Z), 1), 1)
564 /// into:
565 ///   zext (icmp ne i32 (and X, (or Y, (shl 1, Z))), 0)
566 /// Note:
567 ///   Z may be 0 if lshr is missing.
568 /// Worst-case scenario is that we will replace 5 instructions with 5 different
569 /// instructions, but we got rid of select.
570 static Instruction *foldSelectICmpAndAnd(Type *SelType, const ICmpInst *Cmp,
571                                          Value *TVal, Value *FVal,
572                                          InstCombiner::BuilderTy &Builder) {
573   if (!(Cmp->hasOneUse() && Cmp->getOperand(0)->hasOneUse() &&
574         Cmp->getPredicate() == ICmpInst::ICMP_EQ &&
575         match(Cmp->getOperand(1), m_Zero()) && match(FVal, m_One())))
576     return nullptr;
577 
578   // The TrueVal has general form of:  and %B, 1
579   Value *B;
580   if (!match(TVal, m_OneUse(m_And(m_Value(B), m_One()))))
581     return nullptr;
582 
583   // Where %B may be optionally shifted:  lshr %X, %Z.
584   Value *X, *Z;
585   const bool HasShift = match(B, m_OneUse(m_LShr(m_Value(X), m_Value(Z))));
586 
587   // The shift must be valid.
588   // TODO: This restricts the fold to constant shift amounts. Is there a way to
589   //       handle variable shifts safely? PR47012
590   if (HasShift &&
591       !match(Z, m_SpecificInt_ICMP(CmpInst::ICMP_ULT,
592                                    APInt(SelType->getScalarSizeInBits(),
593                                          SelType->getScalarSizeInBits()))))
594     return nullptr;
595 
596   if (!HasShift)
597     X = B;
598 
599   Value *Y;
600   if (!match(Cmp->getOperand(0), m_c_And(m_Specific(X), m_Value(Y))))
601     return nullptr;
602 
603   // ((X & Y) == 0) ? ((X >> Z) & 1) : 1 --> (X & (Y | (1 << Z))) != 0
604   // ((X & Y) == 0) ? (X & 1) : 1 --> (X & (Y | 1)) != 0
605   Constant *One = ConstantInt::get(SelType, 1);
606   Value *MaskB = HasShift ? Builder.CreateShl(One, Z) : One;
607   Value *FullMask = Builder.CreateOr(Y, MaskB);
608   Value *MaskedX = Builder.CreateAnd(X, FullMask);
609   Value *ICmpNeZero = Builder.CreateIsNotNull(MaskedX);
610   return new ZExtInst(ICmpNeZero, SelType);
611 }
612 
613 /// We want to turn:
614 ///   (select (icmp eq (and X, C1), 0), 0, (shl [nsw/nuw] X, C2));
615 ///   iff C1 is a mask and the number of its leading zeros is equal to C2
616 /// into:
617 ///   shl X, C2
618 static Value *foldSelectICmpAndZeroShl(const ICmpInst *Cmp, Value *TVal,
619                                        Value *FVal,
620                                        InstCombiner::BuilderTy &Builder) {
621   ICmpInst::Predicate Pred;
622   Value *AndVal;
623   if (!match(Cmp, m_ICmp(Pred, m_Value(AndVal), m_Zero())))
624     return nullptr;
625 
626   if (Pred == ICmpInst::ICMP_NE) {
627     Pred = ICmpInst::ICMP_EQ;
628     std::swap(TVal, FVal);
629   }
630 
631   Value *X;
632   const APInt *C2, *C1;
633   if (Pred != ICmpInst::ICMP_EQ ||
634       !match(AndVal, m_And(m_Value(X), m_APInt(C1))) ||
635       !match(TVal, m_Zero()) || !match(FVal, m_Shl(m_Specific(X), m_APInt(C2))))
636     return nullptr;
637 
638   if (!C1->isMask() ||
639       C1->countLeadingZeros() != static_cast<unsigned>(C2->getZExtValue()))
640     return nullptr;
641 
642   auto *FI = dyn_cast<Instruction>(FVal);
643   if (!FI)
644     return nullptr;
645 
646   FI->setHasNoSignedWrap(false);
647   FI->setHasNoUnsignedWrap(false);
648   return FVal;
649 }
650 
651 /// We want to turn:
652 ///   (select (icmp sgt x, C), lshr (X, Y), ashr (X, Y)); iff C s>= -1
653 ///   (select (icmp slt x, C), ashr (X, Y), lshr (X, Y)); iff C s>= 0
654 /// into:
655 ///   ashr (X, Y)
656 static Value *foldSelectICmpLshrAshr(const ICmpInst *IC, Value *TrueVal,
657                                      Value *FalseVal,
658                                      InstCombiner::BuilderTy &Builder) {
659   ICmpInst::Predicate Pred = IC->getPredicate();
660   Value *CmpLHS = IC->getOperand(0);
661   Value *CmpRHS = IC->getOperand(1);
662   if (!CmpRHS->getType()->isIntOrIntVectorTy())
663     return nullptr;
664 
665   Value *X, *Y;
666   unsigned Bitwidth = CmpRHS->getType()->getScalarSizeInBits();
667   if ((Pred != ICmpInst::ICMP_SGT ||
668        !match(CmpRHS,
669               m_SpecificInt_ICMP(ICmpInst::ICMP_SGE, APInt(Bitwidth, -1)))) &&
670       (Pred != ICmpInst::ICMP_SLT ||
671        !match(CmpRHS,
672               m_SpecificInt_ICMP(ICmpInst::ICMP_SGE, APInt(Bitwidth, 0)))))
673     return nullptr;
674 
675   // Canonicalize so that ashr is in FalseVal.
676   if (Pred == ICmpInst::ICMP_SLT)
677     std::swap(TrueVal, FalseVal);
678 
679   if (match(TrueVal, m_LShr(m_Value(X), m_Value(Y))) &&
680       match(FalseVal, m_AShr(m_Specific(X), m_Specific(Y))) &&
681       match(CmpLHS, m_Specific(X))) {
682     const auto *Ashr = cast<Instruction>(FalseVal);
683     // if lshr is not exact and ashr is, this new ashr must not be exact.
684     bool IsExact = Ashr->isExact() && cast<Instruction>(TrueVal)->isExact();
685     return Builder.CreateAShr(X, Y, IC->getName(), IsExact);
686   }
687 
688   return nullptr;
689 }
690 
691 /// We want to turn:
692 ///   (select (icmp eq (and X, C1), 0), Y, (or Y, C2))
693 /// into:
694 ///   (or (shl (and X, C1), C3), Y)
695 /// iff:
696 ///   C1 and C2 are both powers of 2
697 /// where:
698 ///   C3 = Log(C2) - Log(C1)
699 ///
700 /// This transform handles cases where:
701 /// 1. The icmp predicate is inverted
702 /// 2. The select operands are reversed
703 /// 3. The magnitude of C2 and C1 are flipped
704 static Value *foldSelectICmpAndOr(const ICmpInst *IC, Value *TrueVal,
705                                   Value *FalseVal,
706                                   InstCombiner::BuilderTy &Builder) {
707   // Only handle integer compares. Also, if this is a vector select, we need a
708   // vector compare.
709   if (!TrueVal->getType()->isIntOrIntVectorTy() ||
710       TrueVal->getType()->isVectorTy() != IC->getType()->isVectorTy())
711     return nullptr;
712 
713   Value *CmpLHS = IC->getOperand(0);
714   Value *CmpRHS = IC->getOperand(1);
715 
716   Value *V;
717   unsigned C1Log;
718   bool IsEqualZero;
719   bool NeedAnd = false;
720   if (IC->isEquality()) {
721     if (!match(CmpRHS, m_Zero()))
722       return nullptr;
723 
724     const APInt *C1;
725     if (!match(CmpLHS, m_And(m_Value(), m_Power2(C1))))
726       return nullptr;
727 
728     V = CmpLHS;
729     C1Log = C1->logBase2();
730     IsEqualZero = IC->getPredicate() == ICmpInst::ICMP_EQ;
731   } else if (IC->getPredicate() == ICmpInst::ICMP_SLT ||
732              IC->getPredicate() == ICmpInst::ICMP_SGT) {
733     // We also need to recognize (icmp slt (trunc (X)), 0) and
734     // (icmp sgt (trunc (X)), -1).
735     IsEqualZero = IC->getPredicate() == ICmpInst::ICMP_SGT;
736     if ((IsEqualZero && !match(CmpRHS, m_AllOnes())) ||
737         (!IsEqualZero && !match(CmpRHS, m_Zero())))
738       return nullptr;
739 
740     if (!match(CmpLHS, m_OneUse(m_Trunc(m_Value(V)))))
741       return nullptr;
742 
743     C1Log = CmpLHS->getType()->getScalarSizeInBits() - 1;
744     NeedAnd = true;
745   } else {
746     return nullptr;
747   }
748 
749   const APInt *C2;
750   bool OrOnTrueVal = false;
751   bool OrOnFalseVal = match(FalseVal, m_Or(m_Specific(TrueVal), m_Power2(C2)));
752   if (!OrOnFalseVal)
753     OrOnTrueVal = match(TrueVal, m_Or(m_Specific(FalseVal), m_Power2(C2)));
754 
755   if (!OrOnFalseVal && !OrOnTrueVal)
756     return nullptr;
757 
758   Value *Y = OrOnFalseVal ? TrueVal : FalseVal;
759 
760   unsigned C2Log = C2->logBase2();
761 
762   bool NeedXor = (!IsEqualZero && OrOnFalseVal) || (IsEqualZero && OrOnTrueVal);
763   bool NeedShift = C1Log != C2Log;
764   bool NeedZExtTrunc = Y->getType()->getScalarSizeInBits() !=
765                        V->getType()->getScalarSizeInBits();
766 
767   // Make sure we don't create more instructions than we save.
768   Value *Or = OrOnFalseVal ? FalseVal : TrueVal;
769   if ((NeedShift + NeedXor + NeedZExtTrunc) >
770       (IC->hasOneUse() + Or->hasOneUse()))
771     return nullptr;
772 
773   if (NeedAnd) {
774     // Insert the AND instruction on the input to the truncate.
775     APInt C1 = APInt::getOneBitSet(V->getType()->getScalarSizeInBits(), C1Log);
776     V = Builder.CreateAnd(V, ConstantInt::get(V->getType(), C1));
777   }
778 
779   if (C2Log > C1Log) {
780     V = Builder.CreateZExtOrTrunc(V, Y->getType());
781     V = Builder.CreateShl(V, C2Log - C1Log);
782   } else if (C1Log > C2Log) {
783     V = Builder.CreateLShr(V, C1Log - C2Log);
784     V = Builder.CreateZExtOrTrunc(V, Y->getType());
785   } else
786     V = Builder.CreateZExtOrTrunc(V, Y->getType());
787 
788   if (NeedXor)
789     V = Builder.CreateXor(V, *C2);
790 
791   return Builder.CreateOr(V, Y);
792 }
793 
794 /// Canonicalize a set or clear of a masked set of constant bits to
795 /// select-of-constants form.
796 static Instruction *foldSetClearBits(SelectInst &Sel,
797                                      InstCombiner::BuilderTy &Builder) {
798   Value *Cond = Sel.getCondition();
799   Value *T = Sel.getTrueValue();
800   Value *F = Sel.getFalseValue();
801   Type *Ty = Sel.getType();
802   Value *X;
803   const APInt *NotC, *C;
804 
805   // Cond ? (X & ~C) : (X | C) --> (X & ~C) | (Cond ? 0 : C)
806   if (match(T, m_And(m_Value(X), m_APInt(NotC))) &&
807       match(F, m_OneUse(m_Or(m_Specific(X), m_APInt(C)))) && *NotC == ~(*C)) {
808     Constant *Zero = ConstantInt::getNullValue(Ty);
809     Constant *OrC = ConstantInt::get(Ty, *C);
810     Value *NewSel = Builder.CreateSelect(Cond, Zero, OrC, "masksel", &Sel);
811     return BinaryOperator::CreateOr(T, NewSel);
812   }
813 
814   // Cond ? (X | C) : (X & ~C) --> (X & ~C) | (Cond ? C : 0)
815   if (match(F, m_And(m_Value(X), m_APInt(NotC))) &&
816       match(T, m_OneUse(m_Or(m_Specific(X), m_APInt(C)))) && *NotC == ~(*C)) {
817     Constant *Zero = ConstantInt::getNullValue(Ty);
818     Constant *OrC = ConstantInt::get(Ty, *C);
819     Value *NewSel = Builder.CreateSelect(Cond, OrC, Zero, "masksel", &Sel);
820     return BinaryOperator::CreateOr(F, NewSel);
821   }
822 
823   return nullptr;
824 }
825 
826 //   select (x == 0), 0, x * y --> freeze(y) * x
827 //   select (y == 0), 0, x * y --> freeze(x) * y
828 //   select (x == 0), undef, x * y --> freeze(y) * x
829 //   select (x == undef), 0, x * y --> freeze(y) * x
830 // Usage of mul instead of 0 will make the result more poisonous,
831 // so the operand that was not checked in the condition should be frozen.
832 // The latter folding is applied only when a constant compared with x is
833 // is a vector consisting of 0 and undefs. If a constant compared with x
834 // is a scalar undefined value or undefined vector then an expression
835 // should be already folded into a constant.
836 static Instruction *foldSelectZeroOrMul(SelectInst &SI, InstCombinerImpl &IC) {
837   auto *CondVal = SI.getCondition();
838   auto *TrueVal = SI.getTrueValue();
839   auto *FalseVal = SI.getFalseValue();
840   Value *X, *Y;
841   ICmpInst::Predicate Predicate;
842 
843   // Assuming that constant compared with zero is not undef (but it may be
844   // a vector with some undef elements). Otherwise (when a constant is undef)
845   // the select expression should be already simplified.
846   if (!match(CondVal, m_ICmp(Predicate, m_Value(X), m_Zero())) ||
847       !ICmpInst::isEquality(Predicate))
848     return nullptr;
849 
850   if (Predicate == ICmpInst::ICMP_NE)
851     std::swap(TrueVal, FalseVal);
852 
853   // Check that TrueVal is a constant instead of matching it with m_Zero()
854   // to handle the case when it is a scalar undef value or a vector containing
855   // non-zero elements that are masked by undef elements in the compare
856   // constant.
857   auto *TrueValC = dyn_cast<Constant>(TrueVal);
858   if (TrueValC == nullptr ||
859       !match(FalseVal, m_c_Mul(m_Specific(X), m_Value(Y))) ||
860       !isa<Instruction>(FalseVal))
861     return nullptr;
862 
863   auto *ZeroC = cast<Constant>(cast<Instruction>(CondVal)->getOperand(1));
864   auto *MergedC = Constant::mergeUndefsWith(TrueValC, ZeroC);
865   // If X is compared with 0 then TrueVal could be either zero or undef.
866   // m_Zero match vectors containing some undef elements, but for scalars
867   // m_Undef should be used explicitly.
868   if (!match(MergedC, m_Zero()) && !match(MergedC, m_Undef()))
869     return nullptr;
870 
871   auto *FalseValI = cast<Instruction>(FalseVal);
872   auto *FrY = IC.InsertNewInstBefore(new FreezeInst(Y, Y->getName() + ".fr"),
873                                      *FalseValI);
874   IC.replaceOperand(*FalseValI, FalseValI->getOperand(0) == Y ? 0 : 1, FrY);
875   return IC.replaceInstUsesWith(SI, FalseValI);
876 }
877 
878 /// Transform patterns such as (a > b) ? a - b : 0 into usub.sat(a, b).
879 /// There are 8 commuted/swapped variants of this pattern.
880 /// TODO: Also support a - UMIN(a,b) patterns.
881 static Value *canonicalizeSaturatedSubtract(const ICmpInst *ICI,
882                                             const Value *TrueVal,
883                                             const Value *FalseVal,
884                                             InstCombiner::BuilderTy &Builder) {
885   ICmpInst::Predicate Pred = ICI->getPredicate();
886   Value *A = ICI->getOperand(0);
887   Value *B = ICI->getOperand(1);
888 
889   // (b > a) ? 0 : a - b -> (b <= a) ? a - b : 0
890   // (a == 0) ? 0 : a - 1 -> (a != 0) ? a - 1 : 0
891   if (match(TrueVal, m_Zero())) {
892     Pred = ICmpInst::getInversePredicate(Pred);
893     std::swap(TrueVal, FalseVal);
894   }
895 
896   if (!match(FalseVal, m_Zero()))
897     return nullptr;
898 
899   // ugt 0 is canonicalized to ne 0 and requires special handling
900   // (a != 0) ? a + -1 : 0 -> usub.sat(a, 1)
901   if (Pred == ICmpInst::ICMP_NE) {
902     if (match(B, m_Zero()) && match(TrueVal, m_Add(m_Specific(A), m_AllOnes())))
903       return Builder.CreateBinaryIntrinsic(Intrinsic::usub_sat, A,
904                                            ConstantInt::get(A->getType(), 1));
905     return nullptr;
906   }
907 
908   if (!ICmpInst::isUnsigned(Pred))
909     return nullptr;
910 
911   if (Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_ULT) {
912     // (b < a) ? a - b : 0 -> (a > b) ? a - b : 0
913     std::swap(A, B);
914     Pred = ICmpInst::getSwappedPredicate(Pred);
915   }
916 
917   assert((Pred == ICmpInst::ICMP_UGE || Pred == ICmpInst::ICMP_UGT) &&
918          "Unexpected isUnsigned predicate!");
919 
920   // Ensure the sub is of the form:
921   //  (a > b) ? a - b : 0 -> usub.sat(a, b)
922   //  (a > b) ? b - a : 0 -> -usub.sat(a, b)
923   // Checking for both a-b and a+(-b) as a constant.
924   bool IsNegative = false;
925   const APInt *C;
926   if (match(TrueVal, m_Sub(m_Specific(B), m_Specific(A))) ||
927       (match(A, m_APInt(C)) &&
928        match(TrueVal, m_Add(m_Specific(B), m_SpecificInt(-*C)))))
929     IsNegative = true;
930   else if (!match(TrueVal, m_Sub(m_Specific(A), m_Specific(B))) &&
931            !(match(B, m_APInt(C)) &&
932              match(TrueVal, m_Add(m_Specific(A), m_SpecificInt(-*C)))))
933     return nullptr;
934 
935   // If we are adding a negate and the sub and icmp are used anywhere else, we
936   // would end up with more instructions.
937   if (IsNegative && !TrueVal->hasOneUse() && !ICI->hasOneUse())
938     return nullptr;
939 
940   // (a > b) ? a - b : 0 -> usub.sat(a, b)
941   // (a > b) ? b - a : 0 -> -usub.sat(a, b)
942   Value *Result = Builder.CreateBinaryIntrinsic(Intrinsic::usub_sat, A, B);
943   if (IsNegative)
944     Result = Builder.CreateNeg(Result);
945   return Result;
946 }
947 
948 static Value *canonicalizeSaturatedAdd(ICmpInst *Cmp, Value *TVal, Value *FVal,
949                                        InstCombiner::BuilderTy &Builder) {
950   if (!Cmp->hasOneUse())
951     return nullptr;
952 
953   // Match unsigned saturated add with constant.
954   Value *Cmp0 = Cmp->getOperand(0);
955   Value *Cmp1 = Cmp->getOperand(1);
956   ICmpInst::Predicate Pred = Cmp->getPredicate();
957   Value *X;
958   const APInt *C, *CmpC;
959   if (Pred == ICmpInst::ICMP_ULT &&
960       match(TVal, m_Add(m_Value(X), m_APInt(C))) && X == Cmp0 &&
961       match(FVal, m_AllOnes()) && match(Cmp1, m_APInt(CmpC)) && *CmpC == ~*C) {
962     // (X u< ~C) ? (X + C) : -1 --> uadd.sat(X, C)
963     return Builder.CreateBinaryIntrinsic(
964         Intrinsic::uadd_sat, X, ConstantInt::get(X->getType(), *C));
965   }
966 
967   // Match unsigned saturated add of 2 variables with an unnecessary 'not'.
968   // There are 8 commuted variants.
969   // Canonicalize -1 (saturated result) to true value of the select.
970   if (match(FVal, m_AllOnes())) {
971     std::swap(TVal, FVal);
972     Pred = CmpInst::getInversePredicate(Pred);
973   }
974   if (!match(TVal, m_AllOnes()))
975     return nullptr;
976 
977   // Canonicalize predicate to less-than or less-or-equal-than.
978   if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE) {
979     std::swap(Cmp0, Cmp1);
980     Pred = CmpInst::getSwappedPredicate(Pred);
981   }
982   if (Pred != ICmpInst::ICMP_ULT && Pred != ICmpInst::ICMP_ULE)
983     return nullptr;
984 
985   // Match unsigned saturated add of 2 variables with an unnecessary 'not'.
986   // Strictness of the comparison is irrelevant.
987   Value *Y;
988   if (match(Cmp0, m_Not(m_Value(X))) &&
989       match(FVal, m_c_Add(m_Specific(X), m_Value(Y))) && Y == Cmp1) {
990     // (~X u< Y) ? -1 : (X + Y) --> uadd.sat(X, Y)
991     // (~X u< Y) ? -1 : (Y + X) --> uadd.sat(X, Y)
992     return Builder.CreateBinaryIntrinsic(Intrinsic::uadd_sat, X, Y);
993   }
994   // The 'not' op may be included in the sum but not the compare.
995   // Strictness of the comparison is irrelevant.
996   X = Cmp0;
997   Y = Cmp1;
998   if (match(FVal, m_c_Add(m_Not(m_Specific(X)), m_Specific(Y)))) {
999     // (X u< Y) ? -1 : (~X + Y) --> uadd.sat(~X, Y)
1000     // (X u< Y) ? -1 : (Y + ~X) --> uadd.sat(Y, ~X)
1001     BinaryOperator *BO = cast<BinaryOperator>(FVal);
1002     return Builder.CreateBinaryIntrinsic(
1003         Intrinsic::uadd_sat, BO->getOperand(0), BO->getOperand(1));
1004   }
1005   // The overflow may be detected via the add wrapping round.
1006   // This is only valid for strict comparison!
1007   if (Pred == ICmpInst::ICMP_ULT &&
1008       match(Cmp0, m_c_Add(m_Specific(Cmp1), m_Value(Y))) &&
1009       match(FVal, m_c_Add(m_Specific(Cmp1), m_Specific(Y)))) {
1010     // ((X + Y) u< X) ? -1 : (X + Y) --> uadd.sat(X, Y)
1011     // ((X + Y) u< Y) ? -1 : (X + Y) --> uadd.sat(X, Y)
1012     return Builder.CreateBinaryIntrinsic(Intrinsic::uadd_sat, Cmp1, Y);
1013   }
1014 
1015   return nullptr;
1016 }
1017 
1018 /// Try to match patterns with select and subtract as absolute difference.
1019 static Value *foldAbsDiff(ICmpInst *Cmp, Value *TVal, Value *FVal,
1020                           InstCombiner::BuilderTy &Builder) {
1021   auto *TI = dyn_cast<Instruction>(TVal);
1022   auto *FI = dyn_cast<Instruction>(FVal);
1023   if (!TI || !FI)
1024     return nullptr;
1025 
1026   // Normalize predicate to gt/lt rather than ge/le.
1027   ICmpInst::Predicate Pred = Cmp->getStrictPredicate();
1028   Value *A = Cmp->getOperand(0);
1029   Value *B = Cmp->getOperand(1);
1030 
1031   // Normalize "A - B" as the true value of the select.
1032   if (match(FI, m_Sub(m_Specific(A), m_Specific(B)))) {
1033     std::swap(FI, TI);
1034     Pred = ICmpInst::getSwappedPredicate(Pred);
1035   }
1036 
1037   // With any pair of no-wrap subtracts:
1038   // (A > B) ? (A - B) : (B - A) --> abs(A - B)
1039   if (Pred == CmpInst::ICMP_SGT &&
1040       match(TI, m_Sub(m_Specific(A), m_Specific(B))) &&
1041       match(FI, m_Sub(m_Specific(B), m_Specific(A))) &&
1042       (TI->hasNoSignedWrap() || TI->hasNoUnsignedWrap()) &&
1043       (FI->hasNoSignedWrap() || FI->hasNoUnsignedWrap())) {
1044     // The remaining subtract is not "nuw" any more.
1045     // If there's one use of the subtract (no other use than the use we are
1046     // about to replace), then we know that the sub is "nsw" in this context
1047     // even if it was only "nuw" before. If there's another use, then we can't
1048     // add "nsw" to the existing instruction because it may not be safe in the
1049     // other user's context.
1050     TI->setHasNoUnsignedWrap(false);
1051     if (!TI->hasNoSignedWrap())
1052       TI->setHasNoSignedWrap(TI->hasOneUse());
1053     return Builder.CreateBinaryIntrinsic(Intrinsic::abs, TI, Builder.getTrue());
1054   }
1055 
1056   return nullptr;
1057 }
1058 
1059 /// Fold the following code sequence:
1060 /// \code
1061 ///   int a = ctlz(x & -x);
1062 //    x ? 31 - a : a;
1063 //    // or
1064 //    x ? 31 - a : 32;
1065 /// \code
1066 ///
1067 /// into:
1068 ///   cttz(x)
1069 static Instruction *foldSelectCtlzToCttz(ICmpInst *ICI, Value *TrueVal,
1070                                          Value *FalseVal,
1071                                          InstCombiner::BuilderTy &Builder) {
1072   unsigned BitWidth = TrueVal->getType()->getScalarSizeInBits();
1073   if (!ICI->isEquality() || !match(ICI->getOperand(1), m_Zero()))
1074     return nullptr;
1075 
1076   if (ICI->getPredicate() == ICmpInst::ICMP_NE)
1077     std::swap(TrueVal, FalseVal);
1078 
1079   Value *Ctlz;
1080   if (!match(FalseVal,
1081              m_Xor(m_Value(Ctlz), m_SpecificInt(BitWidth - 1))))
1082     return nullptr;
1083 
1084   if (!match(Ctlz, m_Intrinsic<Intrinsic::ctlz>()))
1085     return nullptr;
1086 
1087   if (TrueVal != Ctlz && !match(TrueVal, m_SpecificInt(BitWidth)))
1088     return nullptr;
1089 
1090   Value *X = ICI->getOperand(0);
1091   auto *II = cast<IntrinsicInst>(Ctlz);
1092   if (!match(II->getOperand(0), m_c_And(m_Specific(X), m_Neg(m_Specific(X)))))
1093     return nullptr;
1094 
1095   Function *F = Intrinsic::getDeclaration(II->getModule(), Intrinsic::cttz,
1096                                           II->getType());
1097   return CallInst::Create(F, {X, II->getArgOperand(1)});
1098 }
1099 
1100 /// Attempt to fold a cttz/ctlz followed by a icmp plus select into a single
1101 /// call to cttz/ctlz with flag 'is_zero_poison' cleared.
1102 ///
1103 /// For example, we can fold the following code sequence:
1104 /// \code
1105 ///   %0 = tail call i32 @llvm.cttz.i32(i32 %x, i1 true)
1106 ///   %1 = icmp ne i32 %x, 0
1107 ///   %2 = select i1 %1, i32 %0, i32 32
1108 /// \code
1109 ///
1110 /// into:
1111 ///   %0 = tail call i32 @llvm.cttz.i32(i32 %x, i1 false)
1112 static Value *foldSelectCttzCtlz(ICmpInst *ICI, Value *TrueVal, Value *FalseVal,
1113                                  InstCombiner::BuilderTy &Builder) {
1114   ICmpInst::Predicate Pred = ICI->getPredicate();
1115   Value *CmpLHS = ICI->getOperand(0);
1116   Value *CmpRHS = ICI->getOperand(1);
1117 
1118   // Check if the select condition compares a value for equality.
1119   if (!ICI->isEquality())
1120     return nullptr;
1121 
1122   Value *SelectArg = FalseVal;
1123   Value *ValueOnZero = TrueVal;
1124   if (Pred == ICmpInst::ICMP_NE)
1125     std::swap(SelectArg, ValueOnZero);
1126 
1127   // Skip zero extend/truncate.
1128   Value *Count = nullptr;
1129   if (!match(SelectArg, m_ZExt(m_Value(Count))) &&
1130       !match(SelectArg, m_Trunc(m_Value(Count))))
1131     Count = SelectArg;
1132 
1133   // Check that 'Count' is a call to intrinsic cttz/ctlz. Also check that the
1134   // input to the cttz/ctlz is used as LHS for the compare instruction.
1135   Value *X;
1136   if (!match(Count, m_Intrinsic<Intrinsic::cttz>(m_Value(X))) &&
1137       !match(Count, m_Intrinsic<Intrinsic::ctlz>(m_Value(X))))
1138     return nullptr;
1139 
1140   // (X == 0) ? BitWidth : ctz(X)
1141   // (X == -1) ? BitWidth : ctz(~X)
1142   if ((X != CmpLHS || !match(CmpRHS, m_Zero())) &&
1143       (!match(X, m_Not(m_Specific(CmpLHS))) || !match(CmpRHS, m_AllOnes())))
1144     return nullptr;
1145 
1146   IntrinsicInst *II = cast<IntrinsicInst>(Count);
1147 
1148   // Check if the value propagated on zero is a constant number equal to the
1149   // sizeof in bits of 'Count'.
1150   unsigned SizeOfInBits = Count->getType()->getScalarSizeInBits();
1151   if (match(ValueOnZero, m_SpecificInt(SizeOfInBits))) {
1152     // Explicitly clear the 'is_zero_poison' flag. It's always valid to go from
1153     // true to false on this flag, so we can replace it for all users.
1154     II->setArgOperand(1, ConstantInt::getFalse(II->getContext()));
1155     return SelectArg;
1156   }
1157 
1158   // The ValueOnZero is not the bitwidth. But if the cttz/ctlz (and optional
1159   // zext/trunc) have one use (ending at the select), the cttz/ctlz result will
1160   // not be used if the input is zero. Relax to 'zero is poison' for that case.
1161   if (II->hasOneUse() && SelectArg->hasOneUse() &&
1162       !match(II->getArgOperand(1), m_One()))
1163     II->setArgOperand(1, ConstantInt::getTrue(II->getContext()));
1164 
1165   return nullptr;
1166 }
1167 
1168 static Instruction *canonicalizeSPF(SelectInst &Sel, ICmpInst &Cmp,
1169                                     InstCombinerImpl &IC) {
1170   Value *LHS, *RHS;
1171   // TODO: What to do with pointer min/max patterns?
1172   if (!Sel.getType()->isIntOrIntVectorTy())
1173     return nullptr;
1174 
1175   SelectPatternFlavor SPF = matchSelectPattern(&Sel, LHS, RHS).Flavor;
1176   if (SPF == SelectPatternFlavor::SPF_ABS ||
1177       SPF == SelectPatternFlavor::SPF_NABS) {
1178     if (!Cmp.hasOneUse() && !RHS->hasOneUse())
1179       return nullptr; // TODO: Relax this restriction.
1180 
1181     // Note that NSW flag can only be propagated for normal, non-negated abs!
1182     bool IntMinIsPoison = SPF == SelectPatternFlavor::SPF_ABS &&
1183                           match(RHS, m_NSWNeg(m_Specific(LHS)));
1184     Constant *IntMinIsPoisonC =
1185         ConstantInt::get(Type::getInt1Ty(Sel.getContext()), IntMinIsPoison);
1186     Instruction *Abs =
1187         IC.Builder.CreateBinaryIntrinsic(Intrinsic::abs, LHS, IntMinIsPoisonC);
1188 
1189     if (SPF == SelectPatternFlavor::SPF_NABS)
1190       return BinaryOperator::CreateNeg(Abs); // Always without NSW flag!
1191     return IC.replaceInstUsesWith(Sel, Abs);
1192   }
1193 
1194   if (SelectPatternResult::isMinOrMax(SPF)) {
1195     Intrinsic::ID IntrinsicID;
1196     switch (SPF) {
1197     case SelectPatternFlavor::SPF_UMIN:
1198       IntrinsicID = Intrinsic::umin;
1199       break;
1200     case SelectPatternFlavor::SPF_UMAX:
1201       IntrinsicID = Intrinsic::umax;
1202       break;
1203     case SelectPatternFlavor::SPF_SMIN:
1204       IntrinsicID = Intrinsic::smin;
1205       break;
1206     case SelectPatternFlavor::SPF_SMAX:
1207       IntrinsicID = Intrinsic::smax;
1208       break;
1209     default:
1210       llvm_unreachable("Unexpected SPF");
1211     }
1212     return IC.replaceInstUsesWith(
1213         Sel, IC.Builder.CreateBinaryIntrinsic(IntrinsicID, LHS, RHS));
1214   }
1215 
1216   return nullptr;
1217 }
1218 
1219 bool InstCombinerImpl::replaceInInstruction(Value *V, Value *Old, Value *New,
1220                                             unsigned Depth) {
1221   // Conservatively limit replacement to two instructions upwards.
1222   if (Depth == 2)
1223     return false;
1224 
1225   auto *I = dyn_cast<Instruction>(V);
1226   if (!I || !I->hasOneUse() || !isSafeToSpeculativelyExecute(I))
1227     return false;
1228 
1229   bool Changed = false;
1230   for (Use &U : I->operands()) {
1231     if (U == Old) {
1232       replaceUse(U, New);
1233       Worklist.add(I);
1234       Changed = true;
1235     } else {
1236       Changed |= replaceInInstruction(U, Old, New, Depth + 1);
1237     }
1238   }
1239   return Changed;
1240 }
1241 
1242 /// If we have a select with an equality comparison, then we know the value in
1243 /// one of the arms of the select. See if substituting this value into an arm
1244 /// and simplifying the result yields the same value as the other arm.
1245 ///
1246 /// To make this transform safe, we must drop poison-generating flags
1247 /// (nsw, etc) if we simplified to a binop because the select may be guarding
1248 /// that poison from propagating. If the existing binop already had no
1249 /// poison-generating flags, then this transform can be done by instsimplify.
1250 ///
1251 /// Consider:
1252 ///   %cmp = icmp eq i32 %x, 2147483647
1253 ///   %add = add nsw i32 %x, 1
1254 ///   %sel = select i1 %cmp, i32 -2147483648, i32 %add
1255 ///
1256 /// We can't replace %sel with %add unless we strip away the flags.
1257 /// TODO: Wrapping flags could be preserved in some cases with better analysis.
1258 Instruction *InstCombinerImpl::foldSelectValueEquivalence(SelectInst &Sel,
1259                                                           ICmpInst &Cmp) {
1260   if (!Cmp.isEquality())
1261     return nullptr;
1262 
1263   // Canonicalize the pattern to ICMP_EQ by swapping the select operands.
1264   Value *TrueVal = Sel.getTrueValue(), *FalseVal = Sel.getFalseValue();
1265   bool Swapped = false;
1266   if (Cmp.getPredicate() == ICmpInst::ICMP_NE) {
1267     std::swap(TrueVal, FalseVal);
1268     Swapped = true;
1269   }
1270 
1271   // In X == Y ? f(X) : Z, try to evaluate f(Y) and replace the operand.
1272   // Make sure Y cannot be undef though, as we might pick different values for
1273   // undef in the icmp and in f(Y). Additionally, take care to avoid replacing
1274   // X == Y ? X : Z with X == Y ? Y : Z, as that would lead to an infinite
1275   // replacement cycle.
1276   Value *CmpLHS = Cmp.getOperand(0), *CmpRHS = Cmp.getOperand(1);
1277   if (TrueVal != CmpLHS &&
1278       isGuaranteedNotToBeUndefOrPoison(CmpRHS, SQ.AC, &Sel, &DT)) {
1279     if (Value *V = simplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, SQ,
1280                                           /* AllowRefinement */ true))
1281       return replaceOperand(Sel, Swapped ? 2 : 1, V);
1282 
1283     // Even if TrueVal does not simplify, we can directly replace a use of
1284     // CmpLHS with CmpRHS, as long as the instruction is not used anywhere
1285     // else and is safe to speculatively execute (we may end up executing it
1286     // with different operands, which should not cause side-effects or trigger
1287     // undefined behavior). Only do this if CmpRHS is a constant, as
1288     // profitability is not clear for other cases.
1289     // FIXME: Support vectors.
1290     if (match(CmpRHS, m_ImmConstant()) && !match(CmpLHS, m_ImmConstant()) &&
1291         !Cmp.getType()->isVectorTy())
1292       if (replaceInInstruction(TrueVal, CmpLHS, CmpRHS))
1293         return &Sel;
1294   }
1295   if (TrueVal != CmpRHS &&
1296       isGuaranteedNotToBeUndefOrPoison(CmpLHS, SQ.AC, &Sel, &DT))
1297     if (Value *V = simplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, SQ,
1298                                           /* AllowRefinement */ true))
1299       return replaceOperand(Sel, Swapped ? 2 : 1, V);
1300 
1301   auto *FalseInst = dyn_cast<Instruction>(FalseVal);
1302   if (!FalseInst)
1303     return nullptr;
1304 
1305   // InstSimplify already performed this fold if it was possible subject to
1306   // current poison-generating flags. Try the transform again with
1307   // poison-generating flags temporarily dropped.
1308   bool WasNUW = false, WasNSW = false, WasExact = false, WasInBounds = false;
1309   if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(FalseVal)) {
1310     WasNUW = OBO->hasNoUnsignedWrap();
1311     WasNSW = OBO->hasNoSignedWrap();
1312     FalseInst->setHasNoUnsignedWrap(false);
1313     FalseInst->setHasNoSignedWrap(false);
1314   }
1315   if (auto *PEO = dyn_cast<PossiblyExactOperator>(FalseVal)) {
1316     WasExact = PEO->isExact();
1317     FalseInst->setIsExact(false);
1318   }
1319   if (auto *GEP = dyn_cast<GetElementPtrInst>(FalseVal)) {
1320     WasInBounds = GEP->isInBounds();
1321     GEP->setIsInBounds(false);
1322   }
1323 
1324   // Try each equivalence substitution possibility.
1325   // We have an 'EQ' comparison, so the select's false value will propagate.
1326   // Example:
1327   // (X == 42) ? 43 : (X + 1) --> (X == 42) ? (X + 1) : (X + 1) --> X + 1
1328   if (simplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, SQ,
1329                              /* AllowRefinement */ false) == TrueVal ||
1330       simplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, SQ,
1331                              /* AllowRefinement */ false) == TrueVal) {
1332     return replaceInstUsesWith(Sel, FalseVal);
1333   }
1334 
1335   // Restore poison-generating flags if the transform did not apply.
1336   if (WasNUW)
1337     FalseInst->setHasNoUnsignedWrap();
1338   if (WasNSW)
1339     FalseInst->setHasNoSignedWrap();
1340   if (WasExact)
1341     FalseInst->setIsExact();
1342   if (WasInBounds)
1343     cast<GetElementPtrInst>(FalseInst)->setIsInBounds();
1344 
1345   return nullptr;
1346 }
1347 
1348 // See if this is a pattern like:
1349 //   %old_cmp1 = icmp slt i32 %x, C2
1350 //   %old_replacement = select i1 %old_cmp1, i32 %target_low, i32 %target_high
1351 //   %old_x_offseted = add i32 %x, C1
1352 //   %old_cmp0 = icmp ult i32 %old_x_offseted, C0
1353 //   %r = select i1 %old_cmp0, i32 %x, i32 %old_replacement
1354 // This can be rewritten as more canonical pattern:
1355 //   %new_cmp1 = icmp slt i32 %x, -C1
1356 //   %new_cmp2 = icmp sge i32 %x, C0-C1
1357 //   %new_clamped_low = select i1 %new_cmp1, i32 %target_low, i32 %x
1358 //   %r = select i1 %new_cmp2, i32 %target_high, i32 %new_clamped_low
1359 // Iff -C1 s<= C2 s<= C0-C1
1360 // Also ULT predicate can also be UGT iff C0 != -1 (+invert result)
1361 //      SLT predicate can also be SGT iff C2 != INT_MAX (+invert res.)
1362 static Value *canonicalizeClampLike(SelectInst &Sel0, ICmpInst &Cmp0,
1363                                     InstCombiner::BuilderTy &Builder) {
1364   Value *X = Sel0.getTrueValue();
1365   Value *Sel1 = Sel0.getFalseValue();
1366 
1367   // First match the condition of the outermost select.
1368   // Said condition must be one-use.
1369   if (!Cmp0.hasOneUse())
1370     return nullptr;
1371   ICmpInst::Predicate Pred0 = Cmp0.getPredicate();
1372   Value *Cmp00 = Cmp0.getOperand(0);
1373   Constant *C0;
1374   if (!match(Cmp0.getOperand(1),
1375              m_CombineAnd(m_AnyIntegralConstant(), m_Constant(C0))))
1376     return nullptr;
1377 
1378   if (!isa<SelectInst>(Sel1)) {
1379     Pred0 = ICmpInst::getInversePredicate(Pred0);
1380     std::swap(X, Sel1);
1381   }
1382 
1383   // Canonicalize Cmp0 into ult or uge.
1384   // FIXME: we shouldn't care about lanes that are 'undef' in the end?
1385   switch (Pred0) {
1386   case ICmpInst::Predicate::ICMP_ULT:
1387   case ICmpInst::Predicate::ICMP_UGE:
1388     // Although icmp ult %x, 0 is an unusual thing to try and should generally
1389     // have been simplified, it does not verify with undef inputs so ensure we
1390     // are not in a strange state.
1391     if (!match(C0, m_SpecificInt_ICMP(
1392                        ICmpInst::Predicate::ICMP_NE,
1393                        APInt::getZero(C0->getType()->getScalarSizeInBits()))))
1394       return nullptr;
1395     break; // Great!
1396   case ICmpInst::Predicate::ICMP_ULE:
1397   case ICmpInst::Predicate::ICMP_UGT:
1398     // We want to canonicalize it to 'ult' or 'uge', so we'll need to increment
1399     // C0, which again means it must not have any all-ones elements.
1400     if (!match(C0,
1401                m_SpecificInt_ICMP(
1402                    ICmpInst::Predicate::ICMP_NE,
1403                    APInt::getAllOnes(C0->getType()->getScalarSizeInBits()))))
1404       return nullptr; // Can't do, have all-ones element[s].
1405     Pred0 = ICmpInst::getFlippedStrictnessPredicate(Pred0);
1406     C0 = InstCombiner::AddOne(C0);
1407     break;
1408   default:
1409     return nullptr; // Unknown predicate.
1410   }
1411 
1412   // Now that we've canonicalized the ICmp, we know the X we expect;
1413   // the select in other hand should be one-use.
1414   if (!Sel1->hasOneUse())
1415     return nullptr;
1416 
1417   // If the types do not match, look through any truncs to the underlying
1418   // instruction.
1419   if (Cmp00->getType() != X->getType() && X->hasOneUse())
1420     match(X, m_TruncOrSelf(m_Value(X)));
1421 
1422   // We now can finish matching the condition of the outermost select:
1423   // it should either be the X itself, or an addition of some constant to X.
1424   Constant *C1;
1425   if (Cmp00 == X)
1426     C1 = ConstantInt::getNullValue(X->getType());
1427   else if (!match(Cmp00,
1428                   m_Add(m_Specific(X),
1429                         m_CombineAnd(m_AnyIntegralConstant(), m_Constant(C1)))))
1430     return nullptr;
1431 
1432   Value *Cmp1;
1433   ICmpInst::Predicate Pred1;
1434   Constant *C2;
1435   Value *ReplacementLow, *ReplacementHigh;
1436   if (!match(Sel1, m_Select(m_Value(Cmp1), m_Value(ReplacementLow),
1437                             m_Value(ReplacementHigh))) ||
1438       !match(Cmp1,
1439              m_ICmp(Pred1, m_Specific(X),
1440                     m_CombineAnd(m_AnyIntegralConstant(), m_Constant(C2)))))
1441     return nullptr;
1442 
1443   if (!Cmp1->hasOneUse() && (Cmp00 == X || !Cmp00->hasOneUse()))
1444     return nullptr; // Not enough one-use instructions for the fold.
1445   // FIXME: this restriction could be relaxed if Cmp1 can be reused as one of
1446   //        two comparisons we'll need to build.
1447 
1448   // Canonicalize Cmp1 into the form we expect.
1449   // FIXME: we shouldn't care about lanes that are 'undef' in the end?
1450   switch (Pred1) {
1451   case ICmpInst::Predicate::ICMP_SLT:
1452     break;
1453   case ICmpInst::Predicate::ICMP_SLE:
1454     // We'd have to increment C2 by one, and for that it must not have signed
1455     // max element, but then it would have been canonicalized to 'slt' before
1456     // we get here. So we can't do anything useful with 'sle'.
1457     return nullptr;
1458   case ICmpInst::Predicate::ICMP_SGT:
1459     // We want to canonicalize it to 'slt', so we'll need to increment C2,
1460     // which again means it must not have any signed max elements.
1461     if (!match(C2,
1462                m_SpecificInt_ICMP(ICmpInst::Predicate::ICMP_NE,
1463                                   APInt::getSignedMaxValue(
1464                                       C2->getType()->getScalarSizeInBits()))))
1465       return nullptr; // Can't do, have signed max element[s].
1466     C2 = InstCombiner::AddOne(C2);
1467     [[fallthrough]];
1468   case ICmpInst::Predicate::ICMP_SGE:
1469     // Also non-canonical, but here we don't need to change C2,
1470     // so we don't have any restrictions on C2, so we can just handle it.
1471     Pred1 = ICmpInst::Predicate::ICMP_SLT;
1472     std::swap(ReplacementLow, ReplacementHigh);
1473     break;
1474   default:
1475     return nullptr; // Unknown predicate.
1476   }
1477   assert(Pred1 == ICmpInst::Predicate::ICMP_SLT &&
1478          "Unexpected predicate type.");
1479 
1480   // The thresholds of this clamp-like pattern.
1481   auto *ThresholdLowIncl = ConstantExpr::getNeg(C1);
1482   auto *ThresholdHighExcl = ConstantExpr::getSub(C0, C1);
1483 
1484   assert((Pred0 == ICmpInst::Predicate::ICMP_ULT ||
1485           Pred0 == ICmpInst::Predicate::ICMP_UGE) &&
1486          "Unexpected predicate type.");
1487   if (Pred0 == ICmpInst::Predicate::ICMP_UGE)
1488     std::swap(ThresholdLowIncl, ThresholdHighExcl);
1489 
1490   // The fold has a precondition 1: C2 s>= ThresholdLow
1491   auto *Precond1 = ConstantExpr::getICmp(ICmpInst::Predicate::ICMP_SGE, C2,
1492                                          ThresholdLowIncl);
1493   if (!match(Precond1, m_One()))
1494     return nullptr;
1495   // The fold has a precondition 2: C2 s<= ThresholdHigh
1496   auto *Precond2 = ConstantExpr::getICmp(ICmpInst::Predicate::ICMP_SLE, C2,
1497                                          ThresholdHighExcl);
1498   if (!match(Precond2, m_One()))
1499     return nullptr;
1500 
1501   // If we are matching from a truncated input, we need to sext the
1502   // ReplacementLow and ReplacementHigh values. Only do the transform if they
1503   // are free to extend due to being constants.
1504   if (X->getType() != Sel0.getType()) {
1505     Constant *LowC, *HighC;
1506     if (!match(ReplacementLow, m_ImmConstant(LowC)) ||
1507         !match(ReplacementHigh, m_ImmConstant(HighC)))
1508       return nullptr;
1509     ReplacementLow = ConstantExpr::getSExt(LowC, X->getType());
1510     ReplacementHigh = ConstantExpr::getSExt(HighC, X->getType());
1511   }
1512 
1513   // All good, finally emit the new pattern.
1514   Value *ShouldReplaceLow = Builder.CreateICmpSLT(X, ThresholdLowIncl);
1515   Value *ShouldReplaceHigh = Builder.CreateICmpSGE(X, ThresholdHighExcl);
1516   Value *MaybeReplacedLow =
1517       Builder.CreateSelect(ShouldReplaceLow, ReplacementLow, X);
1518 
1519   // Create the final select. If we looked through a truncate above, we will
1520   // need to retruncate the result.
1521   Value *MaybeReplacedHigh = Builder.CreateSelect(
1522       ShouldReplaceHigh, ReplacementHigh, MaybeReplacedLow);
1523   return Builder.CreateTrunc(MaybeReplacedHigh, Sel0.getType());
1524 }
1525 
1526 // If we have
1527 //  %cmp = icmp [canonical predicate] i32 %x, C0
1528 //  %r = select i1 %cmp, i32 %y, i32 C1
1529 // Where C0 != C1 and %x may be different from %y, see if the constant that we
1530 // will have if we flip the strictness of the predicate (i.e. without changing
1531 // the result) is identical to the C1 in select. If it matches we can change
1532 // original comparison to one with swapped predicate, reuse the constant,
1533 // and swap the hands of select.
1534 static Instruction *
1535 tryToReuseConstantFromSelectInComparison(SelectInst &Sel, ICmpInst &Cmp,
1536                                          InstCombinerImpl &IC) {
1537   ICmpInst::Predicate Pred;
1538   Value *X;
1539   Constant *C0;
1540   if (!match(&Cmp, m_OneUse(m_ICmp(
1541                        Pred, m_Value(X),
1542                        m_CombineAnd(m_AnyIntegralConstant(), m_Constant(C0))))))
1543     return nullptr;
1544 
1545   // If comparison predicate is non-relational, we won't be able to do anything.
1546   if (ICmpInst::isEquality(Pred))
1547     return nullptr;
1548 
1549   // If comparison predicate is non-canonical, then we certainly won't be able
1550   // to make it canonical; canonicalizeCmpWithConstant() already tried.
1551   if (!InstCombiner::isCanonicalPredicate(Pred))
1552     return nullptr;
1553 
1554   // If the [input] type of comparison and select type are different, lets abort
1555   // for now. We could try to compare constants with trunc/[zs]ext though.
1556   if (C0->getType() != Sel.getType())
1557     return nullptr;
1558 
1559   // ULT with 'add' of a constant is canonical. See foldICmpAddConstant().
1560   // FIXME: Are there more magic icmp predicate+constant pairs we must avoid?
1561   //        Or should we just abandon this transform entirely?
1562   if (Pred == CmpInst::ICMP_ULT && match(X, m_Add(m_Value(), m_Constant())))
1563     return nullptr;
1564 
1565 
1566   Value *SelVal0, *SelVal1; // We do not care which one is from where.
1567   match(&Sel, m_Select(m_Value(), m_Value(SelVal0), m_Value(SelVal1)));
1568   // At least one of these values we are selecting between must be a constant
1569   // else we'll never succeed.
1570   if (!match(SelVal0, m_AnyIntegralConstant()) &&
1571       !match(SelVal1, m_AnyIntegralConstant()))
1572     return nullptr;
1573 
1574   // Does this constant C match any of the `select` values?
1575   auto MatchesSelectValue = [SelVal0, SelVal1](Constant *C) {
1576     return C->isElementWiseEqual(SelVal0) || C->isElementWiseEqual(SelVal1);
1577   };
1578 
1579   // If C0 *already* matches true/false value of select, we are done.
1580   if (MatchesSelectValue(C0))
1581     return nullptr;
1582 
1583   // Check the constant we'd have with flipped-strictness predicate.
1584   auto FlippedStrictness =
1585       InstCombiner::getFlippedStrictnessPredicateAndConstant(Pred, C0);
1586   if (!FlippedStrictness)
1587     return nullptr;
1588 
1589   // If said constant doesn't match either, then there is no hope,
1590   if (!MatchesSelectValue(FlippedStrictness->second))
1591     return nullptr;
1592 
1593   // It matched! Lets insert the new comparison just before select.
1594   InstCombiner::BuilderTy::InsertPointGuard Guard(IC.Builder);
1595   IC.Builder.SetInsertPoint(&Sel);
1596 
1597   Pred = ICmpInst::getSwappedPredicate(Pred); // Yes, swapped.
1598   Value *NewCmp = IC.Builder.CreateICmp(Pred, X, FlippedStrictness->second,
1599                                         Cmp.getName() + ".inv");
1600   IC.replaceOperand(Sel, 0, NewCmp);
1601   Sel.swapValues();
1602   Sel.swapProfMetadata();
1603 
1604   return &Sel;
1605 }
1606 
1607 static Instruction *foldSelectZeroOrOnes(ICmpInst *Cmp, Value *TVal,
1608                                          Value *FVal,
1609                                          InstCombiner::BuilderTy &Builder) {
1610   if (!Cmp->hasOneUse())
1611     return nullptr;
1612 
1613   const APInt *CmpC;
1614   if (!match(Cmp->getOperand(1), m_APIntAllowUndef(CmpC)))
1615     return nullptr;
1616 
1617   // (X u< 2) ? -X : -1 --> sext (X != 0)
1618   Value *X = Cmp->getOperand(0);
1619   if (Cmp->getPredicate() == ICmpInst::ICMP_ULT && *CmpC == 2 &&
1620       match(TVal, m_Neg(m_Specific(X))) && match(FVal, m_AllOnes()))
1621     return new SExtInst(Builder.CreateIsNotNull(X), TVal->getType());
1622 
1623   // (X u> 1) ? -1 : -X --> sext (X != 0)
1624   if (Cmp->getPredicate() == ICmpInst::ICMP_UGT && *CmpC == 1 &&
1625       match(FVal, m_Neg(m_Specific(X))) && match(TVal, m_AllOnes()))
1626     return new SExtInst(Builder.CreateIsNotNull(X), TVal->getType());
1627 
1628   return nullptr;
1629 }
1630 
1631 static Value *foldSelectInstWithICmpConst(SelectInst &SI, ICmpInst *ICI,
1632                                           InstCombiner::BuilderTy &Builder) {
1633   const APInt *CmpC;
1634   Value *V;
1635   CmpInst::Predicate Pred;
1636   if (!match(ICI, m_ICmp(Pred, m_Value(V), m_APInt(CmpC))))
1637     return nullptr;
1638 
1639   // Match clamp away from min/max value as a max/min operation.
1640   Value *TVal = SI.getTrueValue();
1641   Value *FVal = SI.getFalseValue();
1642   if (Pred == ICmpInst::ICMP_EQ && V == FVal) {
1643     // (V == UMIN) ? UMIN+1 : V --> umax(V, UMIN+1)
1644     if (CmpC->isMinValue() && match(TVal, m_SpecificInt(*CmpC + 1)))
1645       return Builder.CreateBinaryIntrinsic(Intrinsic::umax, V, TVal);
1646     // (V == UMAX) ? UMAX-1 : V --> umin(V, UMAX-1)
1647     if (CmpC->isMaxValue() && match(TVal, m_SpecificInt(*CmpC - 1)))
1648       return Builder.CreateBinaryIntrinsic(Intrinsic::umin, V, TVal);
1649     // (V == SMIN) ? SMIN+1 : V --> smax(V, SMIN+1)
1650     if (CmpC->isMinSignedValue() && match(TVal, m_SpecificInt(*CmpC + 1)))
1651       return Builder.CreateBinaryIntrinsic(Intrinsic::smax, V, TVal);
1652     // (V == SMAX) ? SMAX-1 : V --> smin(V, SMAX-1)
1653     if (CmpC->isMaxSignedValue() && match(TVal, m_SpecificInt(*CmpC - 1)))
1654       return Builder.CreateBinaryIntrinsic(Intrinsic::smin, V, TVal);
1655   }
1656 
1657   BinaryOperator *BO;
1658   const APInt *C;
1659   CmpInst::Predicate CPred;
1660   if (match(&SI, m_Select(m_Specific(ICI), m_APInt(C), m_BinOp(BO))))
1661     CPred = ICI->getPredicate();
1662   else if (match(&SI, m_Select(m_Specific(ICI), m_BinOp(BO), m_APInt(C))))
1663     CPred = ICI->getInversePredicate();
1664   else
1665     return nullptr;
1666 
1667   const APInt *BinOpC;
1668   if (!match(BO, m_BinOp(m_Specific(V), m_APInt(BinOpC))))
1669     return nullptr;
1670 
1671   ConstantRange R = ConstantRange::makeExactICmpRegion(CPred, *CmpC)
1672                         .binaryOp(BO->getOpcode(), *BinOpC);
1673   if (R == *C) {
1674     BO->dropPoisonGeneratingFlags();
1675     return BO;
1676   }
1677   return nullptr;
1678 }
1679 
1680 /// Visit a SelectInst that has an ICmpInst as its first operand.
1681 Instruction *InstCombinerImpl::foldSelectInstWithICmp(SelectInst &SI,
1682                                                       ICmpInst *ICI) {
1683   if (Instruction *NewSel = foldSelectValueEquivalence(SI, *ICI))
1684     return NewSel;
1685 
1686   if (Instruction *NewSPF = canonicalizeSPF(SI, *ICI, *this))
1687     return NewSPF;
1688 
1689   if (Value *V = foldSelectInstWithICmpConst(SI, ICI, Builder))
1690     return replaceInstUsesWith(SI, V);
1691 
1692   if (Value *V = canonicalizeClampLike(SI, *ICI, Builder))
1693     return replaceInstUsesWith(SI, V);
1694 
1695   if (Instruction *NewSel =
1696           tryToReuseConstantFromSelectInComparison(SI, *ICI, *this))
1697     return NewSel;
1698 
1699   if (Value *V = foldSelectICmpAnd(SI, ICI, Builder))
1700     return replaceInstUsesWith(SI, V);
1701 
1702   // NOTE: if we wanted to, this is where to detect integer MIN/MAX
1703   bool Changed = false;
1704   Value *TrueVal = SI.getTrueValue();
1705   Value *FalseVal = SI.getFalseValue();
1706   ICmpInst::Predicate Pred = ICI->getPredicate();
1707   Value *CmpLHS = ICI->getOperand(0);
1708   Value *CmpRHS = ICI->getOperand(1);
1709   if (CmpRHS != CmpLHS && isa<Constant>(CmpRHS) && !isa<Constant>(CmpLHS)) {
1710     if (CmpLHS == TrueVal && Pred == ICmpInst::ICMP_EQ) {
1711       // Transform (X == C) ? X : Y -> (X == C) ? C : Y
1712       SI.setOperand(1, CmpRHS);
1713       Changed = true;
1714     } else if (CmpLHS == FalseVal && Pred == ICmpInst::ICMP_NE) {
1715       // Transform (X != C) ? Y : X -> (X != C) ? Y : C
1716       SI.setOperand(2, CmpRHS);
1717       Changed = true;
1718     }
1719   }
1720 
1721   // Canonicalize a signbit condition to use zero constant by swapping:
1722   // (CmpLHS > -1) ? TV : FV --> (CmpLHS < 0) ? FV : TV
1723   // To avoid conflicts (infinite loops) with other canonicalizations, this is
1724   // not applied with any constant select arm.
1725   if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, m_AllOnes()) &&
1726       !match(TrueVal, m_Constant()) && !match(FalseVal, m_Constant()) &&
1727       ICI->hasOneUse()) {
1728     InstCombiner::BuilderTy::InsertPointGuard Guard(Builder);
1729     Builder.SetInsertPoint(&SI);
1730     Value *IsNeg = Builder.CreateIsNeg(CmpLHS, ICI->getName());
1731     replaceOperand(SI, 0, IsNeg);
1732     SI.swapValues();
1733     SI.swapProfMetadata();
1734     return &SI;
1735   }
1736 
1737   // FIXME: This code is nearly duplicated in InstSimplify. Using/refactoring
1738   // decomposeBitTestICmp() might help.
1739   if (TrueVal->getType()->isIntOrIntVectorTy()) {
1740     unsigned BitWidth =
1741         DL.getTypeSizeInBits(TrueVal->getType()->getScalarType());
1742     APInt MinSignedValue = APInt::getSignedMinValue(BitWidth);
1743     Value *X;
1744     const APInt *Y, *C;
1745     bool TrueWhenUnset;
1746     bool IsBitTest = false;
1747     if (ICmpInst::isEquality(Pred) &&
1748         match(CmpLHS, m_And(m_Value(X), m_Power2(Y))) &&
1749         match(CmpRHS, m_Zero())) {
1750       IsBitTest = true;
1751       TrueWhenUnset = Pred == ICmpInst::ICMP_EQ;
1752     } else if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, m_Zero())) {
1753       X = CmpLHS;
1754       Y = &MinSignedValue;
1755       IsBitTest = true;
1756       TrueWhenUnset = false;
1757     } else if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, m_AllOnes())) {
1758       X = CmpLHS;
1759       Y = &MinSignedValue;
1760       IsBitTest = true;
1761       TrueWhenUnset = true;
1762     }
1763     if (IsBitTest) {
1764       Value *V = nullptr;
1765       // (X & Y) == 0 ? X : X ^ Y  --> X & ~Y
1766       if (TrueWhenUnset && TrueVal == X &&
1767           match(FalseVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
1768         V = Builder.CreateAnd(X, ~(*Y));
1769       // (X & Y) != 0 ? X ^ Y : X  --> X & ~Y
1770       else if (!TrueWhenUnset && FalseVal == X &&
1771                match(TrueVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
1772         V = Builder.CreateAnd(X, ~(*Y));
1773       // (X & Y) == 0 ? X ^ Y : X  --> X | Y
1774       else if (TrueWhenUnset && FalseVal == X &&
1775                match(TrueVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
1776         V = Builder.CreateOr(X, *Y);
1777       // (X & Y) != 0 ? X : X ^ Y  --> X | Y
1778       else if (!TrueWhenUnset && TrueVal == X &&
1779                match(FalseVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
1780         V = Builder.CreateOr(X, *Y);
1781 
1782       if (V)
1783         return replaceInstUsesWith(SI, V);
1784     }
1785   }
1786 
1787   if (Instruction *V =
1788           foldSelectICmpAndAnd(SI.getType(), ICI, TrueVal, FalseVal, Builder))
1789     return V;
1790 
1791   if (Value *V = foldSelectICmpAndZeroShl(ICI, TrueVal, FalseVal, Builder))
1792     return replaceInstUsesWith(SI, V);
1793 
1794   if (Instruction *V = foldSelectCtlzToCttz(ICI, TrueVal, FalseVal, Builder))
1795     return V;
1796 
1797   if (Instruction *V = foldSelectZeroOrOnes(ICI, TrueVal, FalseVal, Builder))
1798     return V;
1799 
1800   if (Value *V = foldSelectICmpAndOr(ICI, TrueVal, FalseVal, Builder))
1801     return replaceInstUsesWith(SI, V);
1802 
1803   if (Value *V = foldSelectICmpLshrAshr(ICI, TrueVal, FalseVal, Builder))
1804     return replaceInstUsesWith(SI, V);
1805 
1806   if (Value *V = foldSelectCttzCtlz(ICI, TrueVal, FalseVal, Builder))
1807     return replaceInstUsesWith(SI, V);
1808 
1809   if (Value *V = canonicalizeSaturatedSubtract(ICI, TrueVal, FalseVal, Builder))
1810     return replaceInstUsesWith(SI, V);
1811 
1812   if (Value *V = canonicalizeSaturatedAdd(ICI, TrueVal, FalseVal, Builder))
1813     return replaceInstUsesWith(SI, V);
1814 
1815   if (Value *V = foldAbsDiff(ICI, TrueVal, FalseVal, Builder))
1816     return replaceInstUsesWith(SI, V);
1817 
1818   return Changed ? &SI : nullptr;
1819 }
1820 
1821 /// SI is a select whose condition is a PHI node (but the two may be in
1822 /// different blocks). See if the true/false values (V) are live in all of the
1823 /// predecessor blocks of the PHI. For example, cases like this can't be mapped:
1824 ///
1825 ///   X = phi [ C1, BB1], [C2, BB2]
1826 ///   Y = add
1827 ///   Z = select X, Y, 0
1828 ///
1829 /// because Y is not live in BB1/BB2.
1830 static bool canSelectOperandBeMappingIntoPredBlock(const Value *V,
1831                                                    const SelectInst &SI) {
1832   // If the value is a non-instruction value like a constant or argument, it
1833   // can always be mapped.
1834   const Instruction *I = dyn_cast<Instruction>(V);
1835   if (!I) return true;
1836 
1837   // If V is a PHI node defined in the same block as the condition PHI, we can
1838   // map the arguments.
1839   const PHINode *CondPHI = cast<PHINode>(SI.getCondition());
1840 
1841   if (const PHINode *VP = dyn_cast<PHINode>(I))
1842     if (VP->getParent() == CondPHI->getParent())
1843       return true;
1844 
1845   // Otherwise, if the PHI and select are defined in the same block and if V is
1846   // defined in a different block, then we can transform it.
1847   if (SI.getParent() == CondPHI->getParent() &&
1848       I->getParent() != CondPHI->getParent())
1849     return true;
1850 
1851   // Otherwise we have a 'hard' case and we can't tell without doing more
1852   // detailed dominator based analysis, punt.
1853   return false;
1854 }
1855 
1856 /// We have an SPF (e.g. a min or max) of an SPF of the form:
1857 ///   SPF2(SPF1(A, B), C)
1858 Instruction *InstCombinerImpl::foldSPFofSPF(Instruction *Inner,
1859                                             SelectPatternFlavor SPF1, Value *A,
1860                                             Value *B, Instruction &Outer,
1861                                             SelectPatternFlavor SPF2,
1862                                             Value *C) {
1863   if (Outer.getType() != Inner->getType())
1864     return nullptr;
1865 
1866   if (C == A || C == B) {
1867     // MAX(MAX(A, B), B) -> MAX(A, B)
1868     // MIN(MIN(a, b), a) -> MIN(a, b)
1869     // TODO: This could be done in instsimplify.
1870     if (SPF1 == SPF2 && SelectPatternResult::isMinOrMax(SPF1))
1871       return replaceInstUsesWith(Outer, Inner);
1872   }
1873 
1874   return nullptr;
1875 }
1876 
1877 /// Turn select C, (X + Y), (X - Y) --> (X + (select C, Y, (-Y))).
1878 /// This is even legal for FP.
1879 static Instruction *foldAddSubSelect(SelectInst &SI,
1880                                      InstCombiner::BuilderTy &Builder) {
1881   Value *CondVal = SI.getCondition();
1882   Value *TrueVal = SI.getTrueValue();
1883   Value *FalseVal = SI.getFalseValue();
1884   auto *TI = dyn_cast<Instruction>(TrueVal);
1885   auto *FI = dyn_cast<Instruction>(FalseVal);
1886   if (!TI || !FI || !TI->hasOneUse() || !FI->hasOneUse())
1887     return nullptr;
1888 
1889   Instruction *AddOp = nullptr, *SubOp = nullptr;
1890   if ((TI->getOpcode() == Instruction::Sub &&
1891        FI->getOpcode() == Instruction::Add) ||
1892       (TI->getOpcode() == Instruction::FSub &&
1893        FI->getOpcode() == Instruction::FAdd)) {
1894     AddOp = FI;
1895     SubOp = TI;
1896   } else if ((FI->getOpcode() == Instruction::Sub &&
1897               TI->getOpcode() == Instruction::Add) ||
1898              (FI->getOpcode() == Instruction::FSub &&
1899               TI->getOpcode() == Instruction::FAdd)) {
1900     AddOp = TI;
1901     SubOp = FI;
1902   }
1903 
1904   if (AddOp) {
1905     Value *OtherAddOp = nullptr;
1906     if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
1907       OtherAddOp = AddOp->getOperand(1);
1908     } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
1909       OtherAddOp = AddOp->getOperand(0);
1910     }
1911 
1912     if (OtherAddOp) {
1913       // So at this point we know we have (Y -> OtherAddOp):
1914       //        select C, (add X, Y), (sub X, Z)
1915       Value *NegVal; // Compute -Z
1916       if (SI.getType()->isFPOrFPVectorTy()) {
1917         NegVal = Builder.CreateFNeg(SubOp->getOperand(1));
1918         if (Instruction *NegInst = dyn_cast<Instruction>(NegVal)) {
1919           FastMathFlags Flags = AddOp->getFastMathFlags();
1920           Flags &= SubOp->getFastMathFlags();
1921           NegInst->setFastMathFlags(Flags);
1922         }
1923       } else {
1924         NegVal = Builder.CreateNeg(SubOp->getOperand(1));
1925       }
1926 
1927       Value *NewTrueOp = OtherAddOp;
1928       Value *NewFalseOp = NegVal;
1929       if (AddOp != TI)
1930         std::swap(NewTrueOp, NewFalseOp);
1931       Value *NewSel = Builder.CreateSelect(CondVal, NewTrueOp, NewFalseOp,
1932                                            SI.getName() + ".p", &SI);
1933 
1934       if (SI.getType()->isFPOrFPVectorTy()) {
1935         Instruction *RI =
1936             BinaryOperator::CreateFAdd(SubOp->getOperand(0), NewSel);
1937 
1938         FastMathFlags Flags = AddOp->getFastMathFlags();
1939         Flags &= SubOp->getFastMathFlags();
1940         RI->setFastMathFlags(Flags);
1941         return RI;
1942       } else
1943         return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
1944     }
1945   }
1946   return nullptr;
1947 }
1948 
1949 /// Turn X + Y overflows ? -1 : X + Y -> uadd_sat X, Y
1950 /// And X - Y overflows ? 0 : X - Y -> usub_sat X, Y
1951 /// Along with a number of patterns similar to:
1952 /// X + Y overflows ? (X < 0 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y
1953 /// X - Y overflows ? (X > 0 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y
1954 static Instruction *
1955 foldOverflowingAddSubSelect(SelectInst &SI, InstCombiner::BuilderTy &Builder) {
1956   Value *CondVal = SI.getCondition();
1957   Value *TrueVal = SI.getTrueValue();
1958   Value *FalseVal = SI.getFalseValue();
1959 
1960   WithOverflowInst *II;
1961   if (!match(CondVal, m_ExtractValue<1>(m_WithOverflowInst(II))) ||
1962       !match(FalseVal, m_ExtractValue<0>(m_Specific(II))))
1963     return nullptr;
1964 
1965   Value *X = II->getLHS();
1966   Value *Y = II->getRHS();
1967 
1968   auto IsSignedSaturateLimit = [&](Value *Limit, bool IsAdd) {
1969     Type *Ty = Limit->getType();
1970 
1971     ICmpInst::Predicate Pred;
1972     Value *TrueVal, *FalseVal, *Op;
1973     const APInt *C;
1974     if (!match(Limit, m_Select(m_ICmp(Pred, m_Value(Op), m_APInt(C)),
1975                                m_Value(TrueVal), m_Value(FalseVal))))
1976       return false;
1977 
1978     auto IsZeroOrOne = [](const APInt &C) { return C.isZero() || C.isOne(); };
1979     auto IsMinMax = [&](Value *Min, Value *Max) {
1980       APInt MinVal = APInt::getSignedMinValue(Ty->getScalarSizeInBits());
1981       APInt MaxVal = APInt::getSignedMaxValue(Ty->getScalarSizeInBits());
1982       return match(Min, m_SpecificInt(MinVal)) &&
1983              match(Max, m_SpecificInt(MaxVal));
1984     };
1985 
1986     if (Op != X && Op != Y)
1987       return false;
1988 
1989     if (IsAdd) {
1990       // X + Y overflows ? (X <s 0 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y
1991       // X + Y overflows ? (X <s 1 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y
1992       // X + Y overflows ? (Y <s 0 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y
1993       // X + Y overflows ? (Y <s 1 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y
1994       if (Pred == ICmpInst::ICMP_SLT && IsZeroOrOne(*C) &&
1995           IsMinMax(TrueVal, FalseVal))
1996         return true;
1997       // X + Y overflows ? (X >s 0 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y
1998       // X + Y overflows ? (X >s -1 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y
1999       // X + Y overflows ? (Y >s 0 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y
2000       // X + Y overflows ? (Y >s -1 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y
2001       if (Pred == ICmpInst::ICMP_SGT && IsZeroOrOne(*C + 1) &&
2002           IsMinMax(FalseVal, TrueVal))
2003         return true;
2004     } else {
2005       // X - Y overflows ? (X <s 0 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y
2006       // X - Y overflows ? (X <s -1 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y
2007       if (Op == X && Pred == ICmpInst::ICMP_SLT && IsZeroOrOne(*C + 1) &&
2008           IsMinMax(TrueVal, FalseVal))
2009         return true;
2010       // X - Y overflows ? (X >s -1 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y
2011       // X - Y overflows ? (X >s -2 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y
2012       if (Op == X && Pred == ICmpInst::ICMP_SGT && IsZeroOrOne(*C + 2) &&
2013           IsMinMax(FalseVal, TrueVal))
2014         return true;
2015       // X - Y overflows ? (Y <s 0 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y
2016       // X - Y overflows ? (Y <s 1 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y
2017       if (Op == Y && Pred == ICmpInst::ICMP_SLT && IsZeroOrOne(*C) &&
2018           IsMinMax(FalseVal, TrueVal))
2019         return true;
2020       // X - Y overflows ? (Y >s 0 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y
2021       // X - Y overflows ? (Y >s -1 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y
2022       if (Op == Y && Pred == ICmpInst::ICMP_SGT && IsZeroOrOne(*C + 1) &&
2023           IsMinMax(TrueVal, FalseVal))
2024         return true;
2025     }
2026 
2027     return false;
2028   };
2029 
2030   Intrinsic::ID NewIntrinsicID;
2031   if (II->getIntrinsicID() == Intrinsic::uadd_with_overflow &&
2032       match(TrueVal, m_AllOnes()))
2033     // X + Y overflows ? -1 : X + Y -> uadd_sat X, Y
2034     NewIntrinsicID = Intrinsic::uadd_sat;
2035   else if (II->getIntrinsicID() == Intrinsic::usub_with_overflow &&
2036            match(TrueVal, m_Zero()))
2037     // X - Y overflows ? 0 : X - Y -> usub_sat X, Y
2038     NewIntrinsicID = Intrinsic::usub_sat;
2039   else if (II->getIntrinsicID() == Intrinsic::sadd_with_overflow &&
2040            IsSignedSaturateLimit(TrueVal, /*IsAdd=*/true))
2041     // X + Y overflows ? (X <s 0 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y
2042     // X + Y overflows ? (X <s 1 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y
2043     // X + Y overflows ? (X >s 0 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y
2044     // X + Y overflows ? (X >s -1 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y
2045     // X + Y overflows ? (Y <s 0 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y
2046     // X + Y overflows ? (Y <s 1 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y
2047     // X + Y overflows ? (Y >s 0 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y
2048     // X + Y overflows ? (Y >s -1 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y
2049     NewIntrinsicID = Intrinsic::sadd_sat;
2050   else if (II->getIntrinsicID() == Intrinsic::ssub_with_overflow &&
2051            IsSignedSaturateLimit(TrueVal, /*IsAdd=*/false))
2052     // X - Y overflows ? (X <s 0 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y
2053     // X - Y overflows ? (X <s -1 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y
2054     // X - Y overflows ? (X >s -1 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y
2055     // X - Y overflows ? (X >s -2 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y
2056     // X - Y overflows ? (Y <s 0 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y
2057     // X - Y overflows ? (Y <s 1 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y
2058     // X - Y overflows ? (Y >s 0 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y
2059     // X - Y overflows ? (Y >s -1 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y
2060     NewIntrinsicID = Intrinsic::ssub_sat;
2061   else
2062     return nullptr;
2063 
2064   Function *F =
2065       Intrinsic::getDeclaration(SI.getModule(), NewIntrinsicID, SI.getType());
2066   return CallInst::Create(F, {X, Y});
2067 }
2068 
2069 Instruction *InstCombinerImpl::foldSelectExtConst(SelectInst &Sel) {
2070   Constant *C;
2071   if (!match(Sel.getTrueValue(), m_Constant(C)) &&
2072       !match(Sel.getFalseValue(), m_Constant(C)))
2073     return nullptr;
2074 
2075   Instruction *ExtInst;
2076   if (!match(Sel.getTrueValue(), m_Instruction(ExtInst)) &&
2077       !match(Sel.getFalseValue(), m_Instruction(ExtInst)))
2078     return nullptr;
2079 
2080   auto ExtOpcode = ExtInst->getOpcode();
2081   if (ExtOpcode != Instruction::ZExt && ExtOpcode != Instruction::SExt)
2082     return nullptr;
2083 
2084   // If we are extending from a boolean type or if we can create a select that
2085   // has the same size operands as its condition, try to narrow the select.
2086   Value *X = ExtInst->getOperand(0);
2087   Type *SmallType = X->getType();
2088   Value *Cond = Sel.getCondition();
2089   auto *Cmp = dyn_cast<CmpInst>(Cond);
2090   if (!SmallType->isIntOrIntVectorTy(1) &&
2091       (!Cmp || Cmp->getOperand(0)->getType() != SmallType))
2092     return nullptr;
2093 
2094   // If the constant is the same after truncation to the smaller type and
2095   // extension to the original type, we can narrow the select.
2096   Type *SelType = Sel.getType();
2097   Constant *TruncC = ConstantExpr::getTrunc(C, SmallType);
2098   Constant *ExtC = ConstantExpr::getCast(ExtOpcode, TruncC, SelType);
2099   if (ExtC == C && ExtInst->hasOneUse()) {
2100     Value *TruncCVal = cast<Value>(TruncC);
2101     if (ExtInst == Sel.getFalseValue())
2102       std::swap(X, TruncCVal);
2103 
2104     // select Cond, (ext X), C --> ext(select Cond, X, C')
2105     // select Cond, C, (ext X) --> ext(select Cond, C', X)
2106     Value *NewSel = Builder.CreateSelect(Cond, X, TruncCVal, "narrow", &Sel);
2107     return CastInst::Create(Instruction::CastOps(ExtOpcode), NewSel, SelType);
2108   }
2109 
2110   // If one arm of the select is the extend of the condition, replace that arm
2111   // with the extension of the appropriate known bool value.
2112   if (Cond == X) {
2113     if (ExtInst == Sel.getTrueValue()) {
2114       // select X, (sext X), C --> select X, -1, C
2115       // select X, (zext X), C --> select X,  1, C
2116       Constant *One = ConstantInt::getTrue(SmallType);
2117       Constant *AllOnesOrOne = ConstantExpr::getCast(ExtOpcode, One, SelType);
2118       return SelectInst::Create(Cond, AllOnesOrOne, C, "", nullptr, &Sel);
2119     } else {
2120       // select X, C, (sext X) --> select X, C, 0
2121       // select X, C, (zext X) --> select X, C, 0
2122       Constant *Zero = ConstantInt::getNullValue(SelType);
2123       return SelectInst::Create(Cond, C, Zero, "", nullptr, &Sel);
2124     }
2125   }
2126 
2127   return nullptr;
2128 }
2129 
2130 /// Try to transform a vector select with a constant condition vector into a
2131 /// shuffle for easier combining with other shuffles and insert/extract.
2132 static Instruction *canonicalizeSelectToShuffle(SelectInst &SI) {
2133   Value *CondVal = SI.getCondition();
2134   Constant *CondC;
2135   auto *CondValTy = dyn_cast<FixedVectorType>(CondVal->getType());
2136   if (!CondValTy || !match(CondVal, m_Constant(CondC)))
2137     return nullptr;
2138 
2139   unsigned NumElts = CondValTy->getNumElements();
2140   SmallVector<int, 16> Mask;
2141   Mask.reserve(NumElts);
2142   for (unsigned i = 0; i != NumElts; ++i) {
2143     Constant *Elt = CondC->getAggregateElement(i);
2144     if (!Elt)
2145       return nullptr;
2146 
2147     if (Elt->isOneValue()) {
2148       // If the select condition element is true, choose from the 1st vector.
2149       Mask.push_back(i);
2150     } else if (Elt->isNullValue()) {
2151       // If the select condition element is false, choose from the 2nd vector.
2152       Mask.push_back(i + NumElts);
2153     } else if (isa<UndefValue>(Elt)) {
2154       // Undef in a select condition (choose one of the operands) does not mean
2155       // the same thing as undef in a shuffle mask (any value is acceptable), so
2156       // give up.
2157       return nullptr;
2158     } else {
2159       // Bail out on a constant expression.
2160       return nullptr;
2161     }
2162   }
2163 
2164   return new ShuffleVectorInst(SI.getTrueValue(), SI.getFalseValue(), Mask);
2165 }
2166 
2167 /// If we have a select of vectors with a scalar condition, try to convert that
2168 /// to a vector select by splatting the condition. A splat may get folded with
2169 /// other operations in IR and having all operands of a select be vector types
2170 /// is likely better for vector codegen.
2171 static Instruction *canonicalizeScalarSelectOfVecs(SelectInst &Sel,
2172                                                    InstCombinerImpl &IC) {
2173   auto *Ty = dyn_cast<VectorType>(Sel.getType());
2174   if (!Ty)
2175     return nullptr;
2176 
2177   // We can replace a single-use extract with constant index.
2178   Value *Cond = Sel.getCondition();
2179   if (!match(Cond, m_OneUse(m_ExtractElt(m_Value(), m_ConstantInt()))))
2180     return nullptr;
2181 
2182   // select (extelt V, Index), T, F --> select (splat V, Index), T, F
2183   // Splatting the extracted condition reduces code (we could directly create a
2184   // splat shuffle of the source vector to eliminate the intermediate step).
2185   return IC.replaceOperand(
2186       Sel, 0, IC.Builder.CreateVectorSplat(Ty->getElementCount(), Cond));
2187 }
2188 
2189 /// Reuse bitcasted operands between a compare and select:
2190 /// select (cmp (bitcast C), (bitcast D)), (bitcast' C), (bitcast' D) -->
2191 /// bitcast (select (cmp (bitcast C), (bitcast D)), (bitcast C), (bitcast D))
2192 static Instruction *foldSelectCmpBitcasts(SelectInst &Sel,
2193                                           InstCombiner::BuilderTy &Builder) {
2194   Value *Cond = Sel.getCondition();
2195   Value *TVal = Sel.getTrueValue();
2196   Value *FVal = Sel.getFalseValue();
2197 
2198   CmpInst::Predicate Pred;
2199   Value *A, *B;
2200   if (!match(Cond, m_Cmp(Pred, m_Value(A), m_Value(B))))
2201     return nullptr;
2202 
2203   // The select condition is a compare instruction. If the select's true/false
2204   // values are already the same as the compare operands, there's nothing to do.
2205   if (TVal == A || TVal == B || FVal == A || FVal == B)
2206     return nullptr;
2207 
2208   Value *C, *D;
2209   if (!match(A, m_BitCast(m_Value(C))) || !match(B, m_BitCast(m_Value(D))))
2210     return nullptr;
2211 
2212   // select (cmp (bitcast C), (bitcast D)), (bitcast TSrc), (bitcast FSrc)
2213   Value *TSrc, *FSrc;
2214   if (!match(TVal, m_BitCast(m_Value(TSrc))) ||
2215       !match(FVal, m_BitCast(m_Value(FSrc))))
2216     return nullptr;
2217 
2218   // If the select true/false values are *different bitcasts* of the same source
2219   // operands, make the select operands the same as the compare operands and
2220   // cast the result. This is the canonical select form for min/max.
2221   Value *NewSel;
2222   if (TSrc == C && FSrc == D) {
2223     // select (cmp (bitcast C), (bitcast D)), (bitcast' C), (bitcast' D) -->
2224     // bitcast (select (cmp A, B), A, B)
2225     NewSel = Builder.CreateSelect(Cond, A, B, "", &Sel);
2226   } else if (TSrc == D && FSrc == C) {
2227     // select (cmp (bitcast C), (bitcast D)), (bitcast' D), (bitcast' C) -->
2228     // bitcast (select (cmp A, B), B, A)
2229     NewSel = Builder.CreateSelect(Cond, B, A, "", &Sel);
2230   } else {
2231     return nullptr;
2232   }
2233   return CastInst::CreateBitOrPointerCast(NewSel, Sel.getType());
2234 }
2235 
2236 /// Try to eliminate select instructions that test the returned flag of cmpxchg
2237 /// instructions.
2238 ///
2239 /// If a select instruction tests the returned flag of a cmpxchg instruction and
2240 /// selects between the returned value of the cmpxchg instruction its compare
2241 /// operand, the result of the select will always be equal to its false value.
2242 /// For example:
2243 ///
2244 ///   %0 = cmpxchg i64* %ptr, i64 %compare, i64 %new_value seq_cst seq_cst
2245 ///   %1 = extractvalue { i64, i1 } %0, 1
2246 ///   %2 = extractvalue { i64, i1 } %0, 0
2247 ///   %3 = select i1 %1, i64 %compare, i64 %2
2248 ///   ret i64 %3
2249 ///
2250 /// The returned value of the cmpxchg instruction (%2) is the original value
2251 /// located at %ptr prior to any update. If the cmpxchg operation succeeds, %2
2252 /// must have been equal to %compare. Thus, the result of the select is always
2253 /// equal to %2, and the code can be simplified to:
2254 ///
2255 ///   %0 = cmpxchg i64* %ptr, i64 %compare, i64 %new_value seq_cst seq_cst
2256 ///   %1 = extractvalue { i64, i1 } %0, 0
2257 ///   ret i64 %1
2258 ///
2259 static Value *foldSelectCmpXchg(SelectInst &SI) {
2260   // A helper that determines if V is an extractvalue instruction whose
2261   // aggregate operand is a cmpxchg instruction and whose single index is equal
2262   // to I. If such conditions are true, the helper returns the cmpxchg
2263   // instruction; otherwise, a nullptr is returned.
2264   auto isExtractFromCmpXchg = [](Value *V, unsigned I) -> AtomicCmpXchgInst * {
2265     auto *Extract = dyn_cast<ExtractValueInst>(V);
2266     if (!Extract)
2267       return nullptr;
2268     if (Extract->getIndices()[0] != I)
2269       return nullptr;
2270     return dyn_cast<AtomicCmpXchgInst>(Extract->getAggregateOperand());
2271   };
2272 
2273   // If the select has a single user, and this user is a select instruction that
2274   // we can simplify, skip the cmpxchg simplification for now.
2275   if (SI.hasOneUse())
2276     if (auto *Select = dyn_cast<SelectInst>(SI.user_back()))
2277       if (Select->getCondition() == SI.getCondition())
2278         if (Select->getFalseValue() == SI.getTrueValue() ||
2279             Select->getTrueValue() == SI.getFalseValue())
2280           return nullptr;
2281 
2282   // Ensure the select condition is the returned flag of a cmpxchg instruction.
2283   auto *CmpXchg = isExtractFromCmpXchg(SI.getCondition(), 1);
2284   if (!CmpXchg)
2285     return nullptr;
2286 
2287   // Check the true value case: The true value of the select is the returned
2288   // value of the same cmpxchg used by the condition, and the false value is the
2289   // cmpxchg instruction's compare operand.
2290   if (auto *X = isExtractFromCmpXchg(SI.getTrueValue(), 0))
2291     if (X == CmpXchg && X->getCompareOperand() == SI.getFalseValue())
2292       return SI.getFalseValue();
2293 
2294   // Check the false value case: The false value of the select is the returned
2295   // value of the same cmpxchg used by the condition, and the true value is the
2296   // cmpxchg instruction's compare operand.
2297   if (auto *X = isExtractFromCmpXchg(SI.getFalseValue(), 0))
2298     if (X == CmpXchg && X->getCompareOperand() == SI.getTrueValue())
2299       return SI.getFalseValue();
2300 
2301   return nullptr;
2302 }
2303 
2304 /// Try to reduce a funnel/rotate pattern that includes a compare and select
2305 /// into a funnel shift intrinsic. Example:
2306 /// rotl32(a, b) --> (b == 0 ? a : ((a >> (32 - b)) | (a << b)))
2307 ///              --> call llvm.fshl.i32(a, a, b)
2308 /// fshl32(a, b, c) --> (c == 0 ? a : ((b >> (32 - c)) | (a << c)))
2309 ///                 --> call llvm.fshl.i32(a, b, c)
2310 /// fshr32(a, b, c) --> (c == 0 ? b : ((a >> (32 - c)) | (b << c)))
2311 ///                 --> call llvm.fshr.i32(a, b, c)
2312 static Instruction *foldSelectFunnelShift(SelectInst &Sel,
2313                                           InstCombiner::BuilderTy &Builder) {
2314   // This must be a power-of-2 type for a bitmasking transform to be valid.
2315   unsigned Width = Sel.getType()->getScalarSizeInBits();
2316   if (!isPowerOf2_32(Width))
2317     return nullptr;
2318 
2319   BinaryOperator *Or0, *Or1;
2320   if (!match(Sel.getFalseValue(), m_OneUse(m_Or(m_BinOp(Or0), m_BinOp(Or1)))))
2321     return nullptr;
2322 
2323   Value *SV0, *SV1, *SA0, *SA1;
2324   if (!match(Or0, m_OneUse(m_LogicalShift(m_Value(SV0),
2325                                           m_ZExtOrSelf(m_Value(SA0))))) ||
2326       !match(Or1, m_OneUse(m_LogicalShift(m_Value(SV1),
2327                                           m_ZExtOrSelf(m_Value(SA1))))) ||
2328       Or0->getOpcode() == Or1->getOpcode())
2329     return nullptr;
2330 
2331   // Canonicalize to or(shl(SV0, SA0), lshr(SV1, SA1)).
2332   if (Or0->getOpcode() == BinaryOperator::LShr) {
2333     std::swap(Or0, Or1);
2334     std::swap(SV0, SV1);
2335     std::swap(SA0, SA1);
2336   }
2337   assert(Or0->getOpcode() == BinaryOperator::Shl &&
2338          Or1->getOpcode() == BinaryOperator::LShr &&
2339          "Illegal or(shift,shift) pair");
2340 
2341   // Check the shift amounts to see if they are an opposite pair.
2342   Value *ShAmt;
2343   if (match(SA1, m_OneUse(m_Sub(m_SpecificInt(Width), m_Specific(SA0)))))
2344     ShAmt = SA0;
2345   else if (match(SA0, m_OneUse(m_Sub(m_SpecificInt(Width), m_Specific(SA1)))))
2346     ShAmt = SA1;
2347   else
2348     return nullptr;
2349 
2350   // We should now have this pattern:
2351   // select ?, TVal, (or (shl SV0, SA0), (lshr SV1, SA1))
2352   // The false value of the select must be a funnel-shift of the true value:
2353   // IsFShl -> TVal must be SV0 else TVal must be SV1.
2354   bool IsFshl = (ShAmt == SA0);
2355   Value *TVal = Sel.getTrueValue();
2356   if ((IsFshl && TVal != SV0) || (!IsFshl && TVal != SV1))
2357     return nullptr;
2358 
2359   // Finally, see if the select is filtering out a shift-by-zero.
2360   Value *Cond = Sel.getCondition();
2361   ICmpInst::Predicate Pred;
2362   if (!match(Cond, m_OneUse(m_ICmp(Pred, m_Specific(ShAmt), m_ZeroInt()))) ||
2363       Pred != ICmpInst::ICMP_EQ)
2364     return nullptr;
2365 
2366   // If this is not a rotate then the select was blocking poison from the
2367   // 'shift-by-zero' non-TVal, but a funnel shift won't - so freeze it.
2368   if (SV0 != SV1) {
2369     if (IsFshl && !llvm::isGuaranteedNotToBePoison(SV1))
2370       SV1 = Builder.CreateFreeze(SV1);
2371     else if (!IsFshl && !llvm::isGuaranteedNotToBePoison(SV0))
2372       SV0 = Builder.CreateFreeze(SV0);
2373   }
2374 
2375   // This is a funnel/rotate that avoids shift-by-bitwidth UB in a suboptimal way.
2376   // Convert to funnel shift intrinsic.
2377   Intrinsic::ID IID = IsFshl ? Intrinsic::fshl : Intrinsic::fshr;
2378   Function *F = Intrinsic::getDeclaration(Sel.getModule(), IID, Sel.getType());
2379   ShAmt = Builder.CreateZExt(ShAmt, Sel.getType());
2380   return CallInst::Create(F, { SV0, SV1, ShAmt });
2381 }
2382 
2383 static Instruction *foldSelectToCopysign(SelectInst &Sel,
2384                                          InstCombiner::BuilderTy &Builder) {
2385   Value *Cond = Sel.getCondition();
2386   Value *TVal = Sel.getTrueValue();
2387   Value *FVal = Sel.getFalseValue();
2388   Type *SelType = Sel.getType();
2389 
2390   // Match select ?, TC, FC where the constants are equal but negated.
2391   // TODO: Generalize to handle a negated variable operand?
2392   const APFloat *TC, *FC;
2393   if (!match(TVal, m_APFloatAllowUndef(TC)) ||
2394       !match(FVal, m_APFloatAllowUndef(FC)) ||
2395       !abs(*TC).bitwiseIsEqual(abs(*FC)))
2396     return nullptr;
2397 
2398   assert(TC != FC && "Expected equal select arms to simplify");
2399 
2400   Value *X;
2401   const APInt *C;
2402   bool IsTrueIfSignSet;
2403   ICmpInst::Predicate Pred;
2404   if (!match(Cond, m_OneUse(m_ICmp(Pred, m_BitCast(m_Value(X)), m_APInt(C)))) ||
2405       !InstCombiner::isSignBitCheck(Pred, *C, IsTrueIfSignSet) ||
2406       X->getType() != SelType)
2407     return nullptr;
2408 
2409   // If needed, negate the value that will be the sign argument of the copysign:
2410   // (bitcast X) <  0 ? -TC :  TC --> copysign(TC,  X)
2411   // (bitcast X) <  0 ?  TC : -TC --> copysign(TC, -X)
2412   // (bitcast X) >= 0 ? -TC :  TC --> copysign(TC, -X)
2413   // (bitcast X) >= 0 ?  TC : -TC --> copysign(TC,  X)
2414   // Note: FMF from the select can not be propagated to the new instructions.
2415   if (IsTrueIfSignSet ^ TC->isNegative())
2416     X = Builder.CreateFNeg(X);
2417 
2418   // Canonicalize the magnitude argument as the positive constant since we do
2419   // not care about its sign.
2420   Value *MagArg = ConstantFP::get(SelType, abs(*TC));
2421   Function *F = Intrinsic::getDeclaration(Sel.getModule(), Intrinsic::copysign,
2422                                           Sel.getType());
2423   return CallInst::Create(F, { MagArg, X });
2424 }
2425 
2426 Instruction *InstCombinerImpl::foldVectorSelect(SelectInst &Sel) {
2427   if (!isa<VectorType>(Sel.getType()))
2428     return nullptr;
2429 
2430   Value *Cond = Sel.getCondition();
2431   Value *TVal = Sel.getTrueValue();
2432   Value *FVal = Sel.getFalseValue();
2433   Value *C, *X, *Y;
2434 
2435   if (match(Cond, m_VecReverse(m_Value(C)))) {
2436     auto createSelReverse = [&](Value *C, Value *X, Value *Y) {
2437       Value *V = Builder.CreateSelect(C, X, Y, Sel.getName(), &Sel);
2438       if (auto *I = dyn_cast<Instruction>(V))
2439         I->copyIRFlags(&Sel);
2440       Module *M = Sel.getModule();
2441       Function *F = Intrinsic::getDeclaration(
2442           M, Intrinsic::experimental_vector_reverse, V->getType());
2443       return CallInst::Create(F, V);
2444     };
2445 
2446     if (match(TVal, m_VecReverse(m_Value(X)))) {
2447       // select rev(C), rev(X), rev(Y) --> rev(select C, X, Y)
2448       if (match(FVal, m_VecReverse(m_Value(Y))) &&
2449           (Cond->hasOneUse() || TVal->hasOneUse() || FVal->hasOneUse()))
2450         return createSelReverse(C, X, Y);
2451 
2452       // select rev(C), rev(X), FValSplat --> rev(select C, X, FValSplat)
2453       if ((Cond->hasOneUse() || TVal->hasOneUse()) && isSplatValue(FVal))
2454         return createSelReverse(C, X, FVal);
2455     }
2456     // select rev(C), TValSplat, rev(Y) --> rev(select C, TValSplat, Y)
2457     else if (isSplatValue(TVal) && match(FVal, m_VecReverse(m_Value(Y))) &&
2458              (Cond->hasOneUse() || FVal->hasOneUse()))
2459       return createSelReverse(C, TVal, Y);
2460   }
2461 
2462   auto *VecTy = dyn_cast<FixedVectorType>(Sel.getType());
2463   if (!VecTy)
2464     return nullptr;
2465 
2466   unsigned NumElts = VecTy->getNumElements();
2467   APInt UndefElts(NumElts, 0);
2468   APInt AllOnesEltMask(APInt::getAllOnes(NumElts));
2469   if (Value *V = SimplifyDemandedVectorElts(&Sel, AllOnesEltMask, UndefElts)) {
2470     if (V != &Sel)
2471       return replaceInstUsesWith(Sel, V);
2472     return &Sel;
2473   }
2474 
2475   // A select of a "select shuffle" with a common operand can be rearranged
2476   // to select followed by "select shuffle". Because of poison, this only works
2477   // in the case of a shuffle with no undefined mask elements.
2478   ArrayRef<int> Mask;
2479   if (match(TVal, m_OneUse(m_Shuffle(m_Value(X), m_Value(Y), m_Mask(Mask)))) &&
2480       !is_contained(Mask, PoisonMaskElem) &&
2481       cast<ShuffleVectorInst>(TVal)->isSelect()) {
2482     if (X == FVal) {
2483       // select Cond, (shuf_sel X, Y), X --> shuf_sel X, (select Cond, Y, X)
2484       Value *NewSel = Builder.CreateSelect(Cond, Y, X, "sel", &Sel);
2485       return new ShuffleVectorInst(X, NewSel, Mask);
2486     }
2487     if (Y == FVal) {
2488       // select Cond, (shuf_sel X, Y), Y --> shuf_sel (select Cond, X, Y), Y
2489       Value *NewSel = Builder.CreateSelect(Cond, X, Y, "sel", &Sel);
2490       return new ShuffleVectorInst(NewSel, Y, Mask);
2491     }
2492   }
2493   if (match(FVal, m_OneUse(m_Shuffle(m_Value(X), m_Value(Y), m_Mask(Mask)))) &&
2494       !is_contained(Mask, PoisonMaskElem) &&
2495       cast<ShuffleVectorInst>(FVal)->isSelect()) {
2496     if (X == TVal) {
2497       // select Cond, X, (shuf_sel X, Y) --> shuf_sel X, (select Cond, X, Y)
2498       Value *NewSel = Builder.CreateSelect(Cond, X, Y, "sel", &Sel);
2499       return new ShuffleVectorInst(X, NewSel, Mask);
2500     }
2501     if (Y == TVal) {
2502       // select Cond, Y, (shuf_sel X, Y) --> shuf_sel (select Cond, Y, X), Y
2503       Value *NewSel = Builder.CreateSelect(Cond, Y, X, "sel", &Sel);
2504       return new ShuffleVectorInst(NewSel, Y, Mask);
2505     }
2506   }
2507 
2508   return nullptr;
2509 }
2510 
2511 static Instruction *foldSelectToPhiImpl(SelectInst &Sel, BasicBlock *BB,
2512                                         const DominatorTree &DT,
2513                                         InstCombiner::BuilderTy &Builder) {
2514   // Find the block's immediate dominator that ends with a conditional branch
2515   // that matches select's condition (maybe inverted).
2516   auto *IDomNode = DT[BB]->getIDom();
2517   if (!IDomNode)
2518     return nullptr;
2519   BasicBlock *IDom = IDomNode->getBlock();
2520 
2521   Value *Cond = Sel.getCondition();
2522   Value *IfTrue, *IfFalse;
2523   BasicBlock *TrueSucc, *FalseSucc;
2524   if (match(IDom->getTerminator(),
2525             m_Br(m_Specific(Cond), m_BasicBlock(TrueSucc),
2526                  m_BasicBlock(FalseSucc)))) {
2527     IfTrue = Sel.getTrueValue();
2528     IfFalse = Sel.getFalseValue();
2529   } else if (match(IDom->getTerminator(),
2530                    m_Br(m_Not(m_Specific(Cond)), m_BasicBlock(TrueSucc),
2531                         m_BasicBlock(FalseSucc)))) {
2532     IfTrue = Sel.getFalseValue();
2533     IfFalse = Sel.getTrueValue();
2534   } else
2535     return nullptr;
2536 
2537   // Make sure the branches are actually different.
2538   if (TrueSucc == FalseSucc)
2539     return nullptr;
2540 
2541   // We want to replace select %cond, %a, %b with a phi that takes value %a
2542   // for all incoming edges that are dominated by condition `%cond == true`,
2543   // and value %b for edges dominated by condition `%cond == false`. If %a
2544   // or %b are also phis from the same basic block, we can go further and take
2545   // their incoming values from the corresponding blocks.
2546   BasicBlockEdge TrueEdge(IDom, TrueSucc);
2547   BasicBlockEdge FalseEdge(IDom, FalseSucc);
2548   DenseMap<BasicBlock *, Value *> Inputs;
2549   for (auto *Pred : predecessors(BB)) {
2550     // Check implication.
2551     BasicBlockEdge Incoming(Pred, BB);
2552     if (DT.dominates(TrueEdge, Incoming))
2553       Inputs[Pred] = IfTrue->DoPHITranslation(BB, Pred);
2554     else if (DT.dominates(FalseEdge, Incoming))
2555       Inputs[Pred] = IfFalse->DoPHITranslation(BB, Pred);
2556     else
2557       return nullptr;
2558     // Check availability.
2559     if (auto *Insn = dyn_cast<Instruction>(Inputs[Pred]))
2560       if (!DT.dominates(Insn, Pred->getTerminator()))
2561         return nullptr;
2562   }
2563 
2564   Builder.SetInsertPoint(&*BB->begin());
2565   auto *PN = Builder.CreatePHI(Sel.getType(), Inputs.size());
2566   for (auto *Pred : predecessors(BB))
2567     PN->addIncoming(Inputs[Pred], Pred);
2568   PN->takeName(&Sel);
2569   return PN;
2570 }
2571 
2572 static Instruction *foldSelectToPhi(SelectInst &Sel, const DominatorTree &DT,
2573                                     InstCombiner::BuilderTy &Builder) {
2574   // Try to replace this select with Phi in one of these blocks.
2575   SmallSetVector<BasicBlock *, 4> CandidateBlocks;
2576   CandidateBlocks.insert(Sel.getParent());
2577   for (Value *V : Sel.operands())
2578     if (auto *I = dyn_cast<Instruction>(V))
2579       CandidateBlocks.insert(I->getParent());
2580 
2581   for (BasicBlock *BB : CandidateBlocks)
2582     if (auto *PN = foldSelectToPhiImpl(Sel, BB, DT, Builder))
2583       return PN;
2584   return nullptr;
2585 }
2586 
2587 static Value *foldSelectWithFrozenICmp(SelectInst &Sel, InstCombiner::BuilderTy &Builder) {
2588   FreezeInst *FI = dyn_cast<FreezeInst>(Sel.getCondition());
2589   if (!FI)
2590     return nullptr;
2591 
2592   Value *Cond = FI->getOperand(0);
2593   Value *TrueVal = Sel.getTrueValue(), *FalseVal = Sel.getFalseValue();
2594 
2595   //   select (freeze(x == y)), x, y --> y
2596   //   select (freeze(x != y)), x, y --> x
2597   // The freeze should be only used by this select. Otherwise, remaining uses of
2598   // the freeze can observe a contradictory value.
2599   //   c = freeze(x == y)   ; Let's assume that y = poison & x = 42; c is 0 or 1
2600   //   a = select c, x, y   ;
2601   //   f(a, c)              ; f(poison, 1) cannot happen, but if a is folded
2602   //                        ; to y, this can happen.
2603   CmpInst::Predicate Pred;
2604   if (FI->hasOneUse() &&
2605       match(Cond, m_c_ICmp(Pred, m_Specific(TrueVal), m_Specific(FalseVal))) &&
2606       (Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE)) {
2607     return Pred == ICmpInst::ICMP_EQ ? FalseVal : TrueVal;
2608   }
2609 
2610   return nullptr;
2611 }
2612 
2613 Instruction *InstCombinerImpl::foldAndOrOfSelectUsingImpliedCond(Value *Op,
2614                                                                  SelectInst &SI,
2615                                                                  bool IsAnd) {
2616   Value *CondVal = SI.getCondition();
2617   Value *A = SI.getTrueValue();
2618   Value *B = SI.getFalseValue();
2619 
2620   assert(Op->getType()->isIntOrIntVectorTy(1) &&
2621          "Op must be either i1 or vector of i1.");
2622 
2623   std::optional<bool> Res = isImpliedCondition(Op, CondVal, DL, IsAnd);
2624   if (!Res)
2625     return nullptr;
2626 
2627   Value *Zero = Constant::getNullValue(A->getType());
2628   Value *One = Constant::getAllOnesValue(A->getType());
2629 
2630   if (*Res == true) {
2631     if (IsAnd)
2632       // select op, (select cond, A, B), false => select op, A, false
2633       // and    op, (select cond, A, B)        => select op, A, false
2634       //   if op = true implies condval = true.
2635       return SelectInst::Create(Op, A, Zero);
2636     else
2637       // select op, true, (select cond, A, B) => select op, true, A
2638       // or     op, (select cond, A, B)       => select op, true, A
2639       //   if op = false implies condval = true.
2640       return SelectInst::Create(Op, One, A);
2641   } else {
2642     if (IsAnd)
2643       // select op, (select cond, A, B), false => select op, B, false
2644       // and    op, (select cond, A, B)        => select op, B, false
2645       //   if op = true implies condval = false.
2646       return SelectInst::Create(Op, B, Zero);
2647     else
2648       // select op, true, (select cond, A, B) => select op, true, B
2649       // or     op, (select cond, A, B)       => select op, true, B
2650       //   if op = false implies condval = false.
2651       return SelectInst::Create(Op, One, B);
2652   }
2653 }
2654 
2655 // Canonicalize select with fcmp to fabs(). -0.0 makes this tricky. We need
2656 // fast-math-flags (nsz) or fsub with +0.0 (not fneg) for this to work.
2657 static Instruction *foldSelectWithFCmpToFabs(SelectInst &SI,
2658                                              InstCombinerImpl &IC) {
2659   Value *CondVal = SI.getCondition();
2660 
2661   bool ChangedFMF = false;
2662   for (bool Swap : {false, true}) {
2663     Value *TrueVal = SI.getTrueValue();
2664     Value *X = SI.getFalseValue();
2665     CmpInst::Predicate Pred;
2666 
2667     if (Swap)
2668       std::swap(TrueVal, X);
2669 
2670     if (!match(CondVal, m_FCmp(Pred, m_Specific(X), m_AnyZeroFP())))
2671       continue;
2672 
2673     // fold (X <= +/-0.0) ? (0.0 - X) : X to fabs(X), when 'Swap' is false
2674     // fold (X >  +/-0.0) ? X : (0.0 - X) to fabs(X), when 'Swap' is true
2675     if (match(TrueVal, m_FSub(m_PosZeroFP(), m_Specific(X)))) {
2676       if (!Swap && (Pred == FCmpInst::FCMP_OLE || Pred == FCmpInst::FCMP_ULE)) {
2677         Value *Fabs = IC.Builder.CreateUnaryIntrinsic(Intrinsic::fabs, X, &SI);
2678         return IC.replaceInstUsesWith(SI, Fabs);
2679       }
2680       if (Swap && (Pred == FCmpInst::FCMP_OGT || Pred == FCmpInst::FCMP_UGT)) {
2681         Value *Fabs = IC.Builder.CreateUnaryIntrinsic(Intrinsic::fabs, X, &SI);
2682         return IC.replaceInstUsesWith(SI, Fabs);
2683       }
2684     }
2685 
2686     if (!match(TrueVal, m_FNeg(m_Specific(X))))
2687       return nullptr;
2688 
2689     // Forward-propagate nnan and ninf from the fneg to the select.
2690     // If all inputs are not those values, then the select is not either.
2691     // Note: nsz is defined differently, so it may not be correct to propagate.
2692     FastMathFlags FMF = cast<FPMathOperator>(TrueVal)->getFastMathFlags();
2693     if (FMF.noNaNs() && !SI.hasNoNaNs()) {
2694       SI.setHasNoNaNs(true);
2695       ChangedFMF = true;
2696     }
2697     if (FMF.noInfs() && !SI.hasNoInfs()) {
2698       SI.setHasNoInfs(true);
2699       ChangedFMF = true;
2700     }
2701 
2702     // With nsz, when 'Swap' is false:
2703     // fold (X < +/-0.0) ? -X : X or (X <= +/-0.0) ? -X : X to fabs(X)
2704     // fold (X > +/-0.0) ? -X : X or (X >= +/-0.0) ? -X : X to -fabs(x)
2705     // when 'Swap' is true:
2706     // fold (X > +/-0.0) ? X : -X or (X >= +/-0.0) ? X : -X to fabs(X)
2707     // fold (X < +/-0.0) ? X : -X or (X <= +/-0.0) ? X : -X to -fabs(X)
2708     //
2709     // Note: We require "nnan" for this fold because fcmp ignores the signbit
2710     //       of NAN, but IEEE-754 specifies the signbit of NAN values with
2711     //       fneg/fabs operations.
2712     if (!SI.hasNoSignedZeros() || !SI.hasNoNaNs())
2713       return nullptr;
2714 
2715     if (Swap)
2716       Pred = FCmpInst::getSwappedPredicate(Pred);
2717 
2718     bool IsLTOrLE = Pred == FCmpInst::FCMP_OLT || Pred == FCmpInst::FCMP_OLE ||
2719                     Pred == FCmpInst::FCMP_ULT || Pred == FCmpInst::FCMP_ULE;
2720     bool IsGTOrGE = Pred == FCmpInst::FCMP_OGT || Pred == FCmpInst::FCMP_OGE ||
2721                     Pred == FCmpInst::FCMP_UGT || Pred == FCmpInst::FCMP_UGE;
2722 
2723     if (IsLTOrLE) {
2724       Value *Fabs = IC.Builder.CreateUnaryIntrinsic(Intrinsic::fabs, X, &SI);
2725       return IC.replaceInstUsesWith(SI, Fabs);
2726     }
2727     if (IsGTOrGE) {
2728       Value *Fabs = IC.Builder.CreateUnaryIntrinsic(Intrinsic::fabs, X, &SI);
2729       Instruction *NewFNeg = UnaryOperator::CreateFNeg(Fabs);
2730       NewFNeg->setFastMathFlags(SI.getFastMathFlags());
2731       return NewFNeg;
2732     }
2733   }
2734 
2735   return ChangedFMF ? &SI : nullptr;
2736 }
2737 
2738 // Match the following IR pattern:
2739 //   %x.lowbits = and i8 %x, %lowbitmask
2740 //   %x.lowbits.are.zero = icmp eq i8 %x.lowbits, 0
2741 //   %x.biased = add i8 %x, %bias
2742 //   %x.biased.highbits = and i8 %x.biased, %highbitmask
2743 //   %x.roundedup = select i1 %x.lowbits.are.zero, i8 %x, i8 %x.biased.highbits
2744 // Define:
2745 //   %alignment = add i8 %lowbitmask, 1
2746 // Iff 1. an %alignment is a power-of-two (aka, %lowbitmask is a low bit mask)
2747 // and 2. %bias is equal to either %lowbitmask or %alignment,
2748 // and 3. %highbitmask is equal to ~%lowbitmask (aka, to -%alignment)
2749 // then this pattern can be transformed into:
2750 //   %x.offset = add i8 %x, %lowbitmask
2751 //   %x.roundedup = and i8 %x.offset, %highbitmask
2752 static Value *
2753 foldRoundUpIntegerWithPow2Alignment(SelectInst &SI,
2754                                     InstCombiner::BuilderTy &Builder) {
2755   Value *Cond = SI.getCondition();
2756   Value *X = SI.getTrueValue();
2757   Value *XBiasedHighBits = SI.getFalseValue();
2758 
2759   ICmpInst::Predicate Pred;
2760   Value *XLowBits;
2761   if (!match(Cond, m_ICmp(Pred, m_Value(XLowBits), m_ZeroInt())) ||
2762       !ICmpInst::isEquality(Pred))
2763     return nullptr;
2764 
2765   if (Pred == ICmpInst::Predicate::ICMP_NE)
2766     std::swap(X, XBiasedHighBits);
2767 
2768   // FIXME: we could support non non-splats here.
2769 
2770   const APInt *LowBitMaskCst;
2771   if (!match(XLowBits, m_And(m_Specific(X), m_APIntAllowUndef(LowBitMaskCst))))
2772     return nullptr;
2773 
2774   // Match even if the AND and ADD are swapped.
2775   const APInt *BiasCst, *HighBitMaskCst;
2776   if (!match(XBiasedHighBits,
2777              m_And(m_Add(m_Specific(X), m_APIntAllowUndef(BiasCst)),
2778                    m_APIntAllowUndef(HighBitMaskCst))) &&
2779       !match(XBiasedHighBits,
2780              m_Add(m_And(m_Specific(X), m_APIntAllowUndef(HighBitMaskCst)),
2781                    m_APIntAllowUndef(BiasCst))))
2782     return nullptr;
2783 
2784   if (!LowBitMaskCst->isMask())
2785     return nullptr;
2786 
2787   APInt InvertedLowBitMaskCst = ~*LowBitMaskCst;
2788   if (InvertedLowBitMaskCst != *HighBitMaskCst)
2789     return nullptr;
2790 
2791   APInt AlignmentCst = *LowBitMaskCst + 1;
2792 
2793   if (*BiasCst != AlignmentCst && *BiasCst != *LowBitMaskCst)
2794     return nullptr;
2795 
2796   if (!XBiasedHighBits->hasOneUse()) {
2797     if (*BiasCst == *LowBitMaskCst)
2798       return XBiasedHighBits;
2799     return nullptr;
2800   }
2801 
2802   // FIXME: could we preserve undef's here?
2803   Type *Ty = X->getType();
2804   Value *XOffset = Builder.CreateAdd(X, ConstantInt::get(Ty, *LowBitMaskCst),
2805                                      X->getName() + ".biased");
2806   Value *R = Builder.CreateAnd(XOffset, ConstantInt::get(Ty, *HighBitMaskCst));
2807   R->takeName(&SI);
2808   return R;
2809 }
2810 
2811 namespace {
2812 struct DecomposedSelect {
2813   Value *Cond = nullptr;
2814   Value *TrueVal = nullptr;
2815   Value *FalseVal = nullptr;
2816 };
2817 } // namespace
2818 
2819 /// Look for patterns like
2820 ///   %outer.cond = select i1 %inner.cond, i1 %alt.cond, i1 false
2821 ///   %inner.sel = select i1 %inner.cond, i8 %inner.sel.t, i8 %inner.sel.f
2822 ///   %outer.sel = select i1 %outer.cond, i8 %outer.sel.t, i8 %inner.sel
2823 /// and rewrite it as
2824 ///   %inner.sel = select i1 %cond.alternative, i8 %sel.outer.t, i8 %sel.inner.t
2825 ///   %sel.outer = select i1 %cond.inner, i8 %inner.sel, i8 %sel.inner.f
2826 static Instruction *foldNestedSelects(SelectInst &OuterSelVal,
2827                                       InstCombiner::BuilderTy &Builder) {
2828   // We must start with a `select`.
2829   DecomposedSelect OuterSel;
2830   match(&OuterSelVal,
2831         m_Select(m_Value(OuterSel.Cond), m_Value(OuterSel.TrueVal),
2832                  m_Value(OuterSel.FalseVal)));
2833 
2834   // Canonicalize inversion of the outermost `select`'s condition.
2835   if (match(OuterSel.Cond, m_Not(m_Value(OuterSel.Cond))))
2836     std::swap(OuterSel.TrueVal, OuterSel.FalseVal);
2837 
2838   // The condition of the outermost select must be an `and`/`or`.
2839   if (!match(OuterSel.Cond, m_c_LogicalOp(m_Value(), m_Value())))
2840     return nullptr;
2841 
2842   // Depending on the logical op, inner select might be in different hand.
2843   bool IsAndVariant = match(OuterSel.Cond, m_LogicalAnd());
2844   Value *InnerSelVal = IsAndVariant ? OuterSel.FalseVal : OuterSel.TrueVal;
2845 
2846   // Profitability check - avoid increasing instruction count.
2847   if (none_of(ArrayRef<Value *>({OuterSelVal.getCondition(), InnerSelVal}),
2848               [](Value *V) { return V->hasOneUse(); }))
2849     return nullptr;
2850 
2851   // The appropriate hand of the outermost `select` must be a select itself.
2852   DecomposedSelect InnerSel;
2853   if (!match(InnerSelVal,
2854              m_Select(m_Value(InnerSel.Cond), m_Value(InnerSel.TrueVal),
2855                       m_Value(InnerSel.FalseVal))))
2856     return nullptr;
2857 
2858   // Canonicalize inversion of the innermost `select`'s condition.
2859   if (match(InnerSel.Cond, m_Not(m_Value(InnerSel.Cond))))
2860     std::swap(InnerSel.TrueVal, InnerSel.FalseVal);
2861 
2862   Value *AltCond = nullptr;
2863   auto matchOuterCond = [OuterSel, &AltCond](auto m_InnerCond) {
2864     return match(OuterSel.Cond, m_c_LogicalOp(m_InnerCond, m_Value(AltCond)));
2865   };
2866 
2867   // Finally, match the condition that was driving the outermost `select`,
2868   // it should be a logical operation between the condition that was driving
2869   // the innermost `select` (after accounting for the possible inversions
2870   // of the condition), and some other condition.
2871   if (matchOuterCond(m_Specific(InnerSel.Cond))) {
2872     // Done!
2873   } else if (Value * NotInnerCond; matchOuterCond(m_CombineAnd(
2874                  m_Not(m_Specific(InnerSel.Cond)), m_Value(NotInnerCond)))) {
2875     // Done!
2876     std::swap(InnerSel.TrueVal, InnerSel.FalseVal);
2877     InnerSel.Cond = NotInnerCond;
2878   } else // Not the pattern we were looking for.
2879     return nullptr;
2880 
2881   Value *SelInner = Builder.CreateSelect(
2882       AltCond, IsAndVariant ? OuterSel.TrueVal : InnerSel.FalseVal,
2883       IsAndVariant ? InnerSel.TrueVal : OuterSel.FalseVal);
2884   SelInner->takeName(InnerSelVal);
2885   return SelectInst::Create(InnerSel.Cond,
2886                             IsAndVariant ? SelInner : InnerSel.TrueVal,
2887                             !IsAndVariant ? SelInner : InnerSel.FalseVal);
2888 }
2889 
2890 Instruction *InstCombinerImpl::foldSelectOfBools(SelectInst &SI) {
2891   Value *CondVal = SI.getCondition();
2892   Value *TrueVal = SI.getTrueValue();
2893   Value *FalseVal = SI.getFalseValue();
2894   Type *SelType = SI.getType();
2895 
2896   // Avoid potential infinite loops by checking for non-constant condition.
2897   // TODO: Can we assert instead by improving canonicalizeSelectToShuffle()?
2898   //       Scalar select must have simplified?
2899   if (!SelType->isIntOrIntVectorTy(1) || isa<Constant>(CondVal) ||
2900       TrueVal->getType() != CondVal->getType())
2901     return nullptr;
2902 
2903   auto *One = ConstantInt::getTrue(SelType);
2904   auto *Zero = ConstantInt::getFalse(SelType);
2905   Value *A, *B, *C, *D;
2906 
2907   // Folding select to and/or i1 isn't poison safe in general. impliesPoison
2908   // checks whether folding it does not convert a well-defined value into
2909   // poison.
2910   if (match(TrueVal, m_One())) {
2911     if (impliesPoison(FalseVal, CondVal)) {
2912       // Change: A = select B, true, C --> A = or B, C
2913       return BinaryOperator::CreateOr(CondVal, FalseVal);
2914     }
2915 
2916     if (auto *LHS = dyn_cast<FCmpInst>(CondVal))
2917       if (auto *RHS = dyn_cast<FCmpInst>(FalseVal))
2918         if (Value *V = foldLogicOfFCmps(LHS, RHS, /*IsAnd*/ false,
2919                                         /*IsSelectLogical*/ true))
2920           return replaceInstUsesWith(SI, V);
2921 
2922     // (A && B) || (C && B) --> (A || C) && B
2923     if (match(CondVal, m_LogicalAnd(m_Value(A), m_Value(B))) &&
2924         match(FalseVal, m_LogicalAnd(m_Value(C), m_Value(D))) &&
2925         (CondVal->hasOneUse() || FalseVal->hasOneUse())) {
2926       bool CondLogicAnd = isa<SelectInst>(CondVal);
2927       bool FalseLogicAnd = isa<SelectInst>(FalseVal);
2928       auto AndFactorization = [&](Value *Common, Value *InnerCond,
2929                                   Value *InnerVal,
2930                                   bool SelFirst = false) -> Instruction * {
2931         Value *InnerSel = Builder.CreateSelect(InnerCond, One, InnerVal);
2932         if (SelFirst)
2933           std::swap(Common, InnerSel);
2934         if (FalseLogicAnd || (CondLogicAnd && Common == A))
2935           return SelectInst::Create(Common, InnerSel, Zero);
2936         else
2937           return BinaryOperator::CreateAnd(Common, InnerSel);
2938       };
2939 
2940       if (A == C)
2941         return AndFactorization(A, B, D);
2942       if (A == D)
2943         return AndFactorization(A, B, C);
2944       if (B == C)
2945         return AndFactorization(B, A, D);
2946       if (B == D)
2947         return AndFactorization(B, A, C, CondLogicAnd && FalseLogicAnd);
2948     }
2949   }
2950 
2951   if (match(FalseVal, m_Zero())) {
2952     if (impliesPoison(TrueVal, CondVal)) {
2953       // Change: A = select B, C, false --> A = and B, C
2954       return BinaryOperator::CreateAnd(CondVal, TrueVal);
2955     }
2956 
2957     if (auto *LHS = dyn_cast<FCmpInst>(CondVal))
2958       if (auto *RHS = dyn_cast<FCmpInst>(TrueVal))
2959         if (Value *V = foldLogicOfFCmps(LHS, RHS, /*IsAnd*/ true,
2960                                         /*IsSelectLogical*/ true))
2961           return replaceInstUsesWith(SI, V);
2962 
2963     // (A || B) && (C || B) --> (A && C) || B
2964     if (match(CondVal, m_LogicalOr(m_Value(A), m_Value(B))) &&
2965         match(TrueVal, m_LogicalOr(m_Value(C), m_Value(D))) &&
2966         (CondVal->hasOneUse() || TrueVal->hasOneUse())) {
2967       bool CondLogicOr = isa<SelectInst>(CondVal);
2968       bool TrueLogicOr = isa<SelectInst>(TrueVal);
2969       auto OrFactorization = [&](Value *Common, Value *InnerCond,
2970                                  Value *InnerVal,
2971                                  bool SelFirst = false) -> Instruction * {
2972         Value *InnerSel = Builder.CreateSelect(InnerCond, InnerVal, Zero);
2973         if (SelFirst)
2974           std::swap(Common, InnerSel);
2975         if (TrueLogicOr || (CondLogicOr && Common == A))
2976           return SelectInst::Create(Common, One, InnerSel);
2977         else
2978           return BinaryOperator::CreateOr(Common, InnerSel);
2979       };
2980 
2981       if (A == C)
2982         return OrFactorization(A, B, D);
2983       if (A == D)
2984         return OrFactorization(A, B, C);
2985       if (B == C)
2986         return OrFactorization(B, A, D);
2987       if (B == D)
2988         return OrFactorization(B, A, C, CondLogicOr && TrueLogicOr);
2989     }
2990   }
2991 
2992   // We match the "full" 0 or 1 constant here to avoid a potential infinite
2993   // loop with vectors that may have undefined/poison elements.
2994   // select a, false, b -> select !a, b, false
2995   if (match(TrueVal, m_Specific(Zero))) {
2996     Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName());
2997     return SelectInst::Create(NotCond, FalseVal, Zero);
2998   }
2999   // select a, b, true -> select !a, true, b
3000   if (match(FalseVal, m_Specific(One))) {
3001     Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName());
3002     return SelectInst::Create(NotCond, One, TrueVal);
3003   }
3004 
3005   // DeMorgan in select form: !a && !b --> !(a || b)
3006   // select !a, !b, false --> not (select a, true, b)
3007   if (match(&SI, m_LogicalAnd(m_Not(m_Value(A)), m_Not(m_Value(B)))) &&
3008       (CondVal->hasOneUse() || TrueVal->hasOneUse()) &&
3009       !match(A, m_ConstantExpr()) && !match(B, m_ConstantExpr()))
3010     return BinaryOperator::CreateNot(Builder.CreateSelect(A, One, B));
3011 
3012   // DeMorgan in select form: !a || !b --> !(a && b)
3013   // select !a, true, !b --> not (select a, b, false)
3014   if (match(&SI, m_LogicalOr(m_Not(m_Value(A)), m_Not(m_Value(B)))) &&
3015       (CondVal->hasOneUse() || FalseVal->hasOneUse()) &&
3016       !match(A, m_ConstantExpr()) && !match(B, m_ConstantExpr()))
3017     return BinaryOperator::CreateNot(Builder.CreateSelect(A, B, Zero));
3018 
3019   // select (select a, true, b), true, b -> select a, true, b
3020   if (match(CondVal, m_Select(m_Value(A), m_One(), m_Value(B))) &&
3021       match(TrueVal, m_One()) && match(FalseVal, m_Specific(B)))
3022     return replaceOperand(SI, 0, A);
3023   // select (select a, b, false), b, false -> select a, b, false
3024   if (match(CondVal, m_Select(m_Value(A), m_Value(B), m_Zero())) &&
3025       match(TrueVal, m_Specific(B)) && match(FalseVal, m_Zero()))
3026     return replaceOperand(SI, 0, A);
3027   // select a, (select ~a, true, b), false -> select a, b, false
3028   if (match(TrueVal, m_c_LogicalOr(m_Not(m_Specific(CondVal)), m_Value(B))) &&
3029       match(FalseVal, m_Zero()))
3030     return replaceOperand(SI, 1, B);
3031   // select a, true, (select ~a, b, false) -> select a, true, b
3032   if (match(FalseVal, m_c_LogicalAnd(m_Not(m_Specific(CondVal)), m_Value(B))) &&
3033       match(TrueVal, m_One()))
3034     return replaceOperand(SI, 2, B);
3035 
3036   // ~(A & B) & (A | B) --> A ^ B
3037   if (match(&SI, m_c_LogicalAnd(m_Not(m_LogicalAnd(m_Value(A), m_Value(B))),
3038                                 m_c_LogicalOr(m_Deferred(A), m_Deferred(B)))))
3039     return BinaryOperator::CreateXor(A, B);
3040 
3041   // select (~a | c), a, b -> and a, (or c, freeze(b))
3042   if (match(CondVal, m_c_Or(m_Not(m_Specific(TrueVal)), m_Value(C))) &&
3043       CondVal->hasOneUse()) {
3044     FalseVal = Builder.CreateFreeze(FalseVal);
3045     return BinaryOperator::CreateAnd(TrueVal, Builder.CreateOr(C, FalseVal));
3046   }
3047   // select (~c & b), a, b -> and b, (or freeze(a), c)
3048   if (match(CondVal, m_c_And(m_Not(m_Value(C)), m_Specific(FalseVal))) &&
3049       CondVal->hasOneUse()) {
3050     TrueVal = Builder.CreateFreeze(TrueVal);
3051     return BinaryOperator::CreateAnd(FalseVal, Builder.CreateOr(C, TrueVal));
3052   }
3053 
3054   if (match(FalseVal, m_Zero()) || match(TrueVal, m_One())) {
3055     Use *Y = nullptr;
3056     bool IsAnd = match(FalseVal, m_Zero()) ? true : false;
3057     Value *Op1 = IsAnd ? TrueVal : FalseVal;
3058     if (isCheckForZeroAndMulWithOverflow(CondVal, Op1, IsAnd, Y)) {
3059       auto *FI = new FreezeInst(*Y, (*Y)->getName() + ".fr");
3060       InsertNewInstBefore(FI, *cast<Instruction>(Y->getUser()));
3061       replaceUse(*Y, FI);
3062       return replaceInstUsesWith(SI, Op1);
3063     }
3064 
3065     if (auto *Op1SI = dyn_cast<SelectInst>(Op1))
3066       if (auto *I = foldAndOrOfSelectUsingImpliedCond(CondVal, *Op1SI,
3067                                                       /* IsAnd */ IsAnd))
3068         return I;
3069 
3070     if (auto *ICmp0 = dyn_cast<ICmpInst>(CondVal))
3071       if (auto *ICmp1 = dyn_cast<ICmpInst>(Op1))
3072         if (auto *V = foldAndOrOfICmps(ICmp0, ICmp1, SI, IsAnd,
3073                                        /* IsLogical */ true))
3074           return replaceInstUsesWith(SI, V);
3075   }
3076 
3077   // select (a || b), c, false -> select a, c, false
3078   // select c, (a || b), false -> select c, a, false
3079   //   if c implies that b is false.
3080   if (match(CondVal, m_LogicalOr(m_Value(A), m_Value(B))) &&
3081       match(FalseVal, m_Zero())) {
3082     std::optional<bool> Res = isImpliedCondition(TrueVal, B, DL);
3083     if (Res && *Res == false)
3084       return replaceOperand(SI, 0, A);
3085   }
3086   if (match(TrueVal, m_LogicalOr(m_Value(A), m_Value(B))) &&
3087       match(FalseVal, m_Zero())) {
3088     std::optional<bool> Res = isImpliedCondition(CondVal, B, DL);
3089     if (Res && *Res == false)
3090       return replaceOperand(SI, 1, A);
3091   }
3092   // select c, true, (a && b)  -> select c, true, a
3093   // select (a && b), true, c  -> select a, true, c
3094   //   if c = false implies that b = true
3095   if (match(TrueVal, m_One()) &&
3096       match(FalseVal, m_LogicalAnd(m_Value(A), m_Value(B)))) {
3097     std::optional<bool> Res = isImpliedCondition(CondVal, B, DL, false);
3098     if (Res && *Res == true)
3099       return replaceOperand(SI, 2, A);
3100   }
3101   if (match(CondVal, m_LogicalAnd(m_Value(A), m_Value(B))) &&
3102       match(TrueVal, m_One())) {
3103     std::optional<bool> Res = isImpliedCondition(FalseVal, B, DL, false);
3104     if (Res && *Res == true)
3105       return replaceOperand(SI, 0, A);
3106   }
3107 
3108   if (match(TrueVal, m_One())) {
3109     Value *C;
3110 
3111     // (C && A) || (!C && B) --> sel C, A, B
3112     // (A && C) || (!C && B) --> sel C, A, B
3113     // (C && A) || (B && !C) --> sel C, A, B
3114     // (A && C) || (B && !C) --> sel C, A, B (may require freeze)
3115     if (match(FalseVal, m_c_LogicalAnd(m_Not(m_Value(C)), m_Value(B))) &&
3116         match(CondVal, m_c_LogicalAnd(m_Specific(C), m_Value(A)))) {
3117       auto *SelCond = dyn_cast<SelectInst>(CondVal);
3118       auto *SelFVal = dyn_cast<SelectInst>(FalseVal);
3119       bool MayNeedFreeze = SelCond && SelFVal &&
3120                            match(SelFVal->getTrueValue(),
3121                                  m_Not(m_Specific(SelCond->getTrueValue())));
3122       if (MayNeedFreeze)
3123         C = Builder.CreateFreeze(C);
3124       return SelectInst::Create(C, A, B);
3125     }
3126 
3127     // (!C && A) || (C && B) --> sel C, B, A
3128     // (A && !C) || (C && B) --> sel C, B, A
3129     // (!C && A) || (B && C) --> sel C, B, A
3130     // (A && !C) || (B && C) --> sel C, B, A (may require freeze)
3131     if (match(CondVal, m_c_LogicalAnd(m_Not(m_Value(C)), m_Value(A))) &&
3132         match(FalseVal, m_c_LogicalAnd(m_Specific(C), m_Value(B)))) {
3133       auto *SelCond = dyn_cast<SelectInst>(CondVal);
3134       auto *SelFVal = dyn_cast<SelectInst>(FalseVal);
3135       bool MayNeedFreeze = SelCond && SelFVal &&
3136                            match(SelCond->getTrueValue(),
3137                                  m_Not(m_Specific(SelFVal->getTrueValue())));
3138       if (MayNeedFreeze)
3139         C = Builder.CreateFreeze(C);
3140       return SelectInst::Create(C, B, A);
3141     }
3142   }
3143 
3144   return nullptr;
3145 }
3146 
3147 // Return true if we can safely remove the select instruction for std::bit_ceil
3148 // pattern.
3149 static bool isSafeToRemoveBitCeilSelect(ICmpInst::Predicate Pred, Value *Cond0,
3150                                         const APInt *Cond1, Value *CtlzOp,
3151                                         unsigned BitWidth) {
3152   // The challenge in recognizing std::bit_ceil(X) is that the operand is used
3153   // for the CTLZ proper and select condition, each possibly with some
3154   // operation like add and sub.
3155   //
3156   // Our aim is to make sure that -ctlz & (BitWidth - 1) == 0 even when the
3157   // select instruction would select 1, which allows us to get rid of the select
3158   // instruction.
3159   //
3160   // To see if we can do so, we do some symbolic execution with ConstantRange.
3161   // Specifically, we compute the range of values that Cond0 could take when
3162   // Cond == false.  Then we successively transform the range until we obtain
3163   // the range of values that CtlzOp could take.
3164   //
3165   // Conceptually, we follow the def-use chain backward from Cond0 while
3166   // transforming the range for Cond0 until we meet the common ancestor of Cond0
3167   // and CtlzOp.  Then we follow the def-use chain forward until we obtain the
3168   // range for CtlzOp.  That said, we only follow at most one ancestor from
3169   // Cond0.  Likewise, we only follow at most one ancestor from CtrlOp.
3170 
3171   ConstantRange CR = ConstantRange::makeExactICmpRegion(
3172       CmpInst::getInversePredicate(Pred), *Cond1);
3173 
3174   // Match the operation that's used to compute CtlzOp from CommonAncestor.  If
3175   // CtlzOp == CommonAncestor, return true as no operation is needed.  If a
3176   // match is found, execute the operation on CR, update CR, and return true.
3177   // Otherwise, return false.
3178   auto MatchForward = [&](Value *CommonAncestor) {
3179     const APInt *C = nullptr;
3180     if (CtlzOp == CommonAncestor)
3181       return true;
3182     if (match(CtlzOp, m_Add(m_Specific(CommonAncestor), m_APInt(C)))) {
3183       CR = CR.add(*C);
3184       return true;
3185     }
3186     if (match(CtlzOp, m_Sub(m_APInt(C), m_Specific(CommonAncestor)))) {
3187       CR = ConstantRange(*C).sub(CR);
3188       return true;
3189     }
3190     if (match(CtlzOp, m_Not(m_Specific(CommonAncestor)))) {
3191       CR = CR.binaryNot();
3192       return true;
3193     }
3194     return false;
3195   };
3196 
3197   const APInt *C = nullptr;
3198   Value *CommonAncestor;
3199   if (MatchForward(Cond0)) {
3200     // Cond0 is either CtlzOp or CtlzOp's parent.  CR has been updated.
3201   } else if (match(Cond0, m_Add(m_Value(CommonAncestor), m_APInt(C)))) {
3202     CR = CR.sub(*C);
3203     if (!MatchForward(CommonAncestor))
3204       return false;
3205     // Cond0's parent is either CtlzOp or CtlzOp's parent.  CR has been updated.
3206   } else {
3207     return false;
3208   }
3209 
3210   // Return true if all the values in the range are either 0 or negative (if
3211   // treated as signed).  We do so by evaluating:
3212   //
3213   //   CR - 1 u>= (1 << BitWidth) - 1.
3214   APInt IntMax = APInt::getSignMask(BitWidth) - 1;
3215   CR = CR.sub(APInt(BitWidth, 1));
3216   return CR.icmp(ICmpInst::ICMP_UGE, IntMax);
3217 }
3218 
3219 // Transform the std::bit_ceil(X) pattern like:
3220 //
3221 //   %dec = add i32 %x, -1
3222 //   %ctlz = tail call i32 @llvm.ctlz.i32(i32 %dec, i1 false)
3223 //   %sub = sub i32 32, %ctlz
3224 //   %shl = shl i32 1, %sub
3225 //   %ugt = icmp ugt i32 %x, 1
3226 //   %sel = select i1 %ugt, i32 %shl, i32 1
3227 //
3228 // into:
3229 //
3230 //   %dec = add i32 %x, -1
3231 //   %ctlz = tail call i32 @llvm.ctlz.i32(i32 %dec, i1 false)
3232 //   %neg = sub i32 0, %ctlz
3233 //   %masked = and i32 %ctlz, 31
3234 //   %shl = shl i32 1, %sub
3235 //
3236 // Note that the select is optimized away while the shift count is masked with
3237 // 31.  We handle some variations of the input operand like std::bit_ceil(X +
3238 // 1).
3239 static Instruction *foldBitCeil(SelectInst &SI, IRBuilderBase &Builder) {
3240   Type *SelType = SI.getType();
3241   unsigned BitWidth = SelType->getScalarSizeInBits();
3242 
3243   Value *FalseVal = SI.getFalseValue();
3244   Value *TrueVal = SI.getTrueValue();
3245   ICmpInst::Predicate Pred;
3246   const APInt *Cond1;
3247   Value *Cond0, *Ctlz, *CtlzOp;
3248   if (!match(SI.getCondition(), m_ICmp(Pred, m_Value(Cond0), m_APInt(Cond1))))
3249     return nullptr;
3250 
3251   if (match(TrueVal, m_One())) {
3252     std::swap(FalseVal, TrueVal);
3253     Pred = CmpInst::getInversePredicate(Pred);
3254   }
3255 
3256   if (!match(FalseVal, m_One()) ||
3257       !match(TrueVal,
3258              m_OneUse(m_Shl(m_One(), m_OneUse(m_Sub(m_SpecificInt(BitWidth),
3259                                                     m_Value(Ctlz)))))) ||
3260       !match(Ctlz, m_Intrinsic<Intrinsic::ctlz>(m_Value(CtlzOp), m_Zero())) ||
3261       !isSafeToRemoveBitCeilSelect(Pred, Cond0, Cond1, CtlzOp, BitWidth))
3262     return nullptr;
3263 
3264   // Build 1 << (-CTLZ & (BitWidth-1)).  The negation likely corresponds to a
3265   // single hardware instruction as opposed to BitWidth - CTLZ, where BitWidth
3266   // is an integer constant.  Masking with BitWidth-1 comes free on some
3267   // hardware as part of the shift instruction.
3268   Value *Neg = Builder.CreateNeg(Ctlz);
3269   Value *Masked =
3270       Builder.CreateAnd(Neg, ConstantInt::get(SelType, BitWidth - 1));
3271   return BinaryOperator::Create(Instruction::Shl, ConstantInt::get(SelType, 1),
3272                                 Masked);
3273 }
3274 
3275 Instruction *InstCombinerImpl::visitSelectInst(SelectInst &SI) {
3276   Value *CondVal = SI.getCondition();
3277   Value *TrueVal = SI.getTrueValue();
3278   Value *FalseVal = SI.getFalseValue();
3279   Type *SelType = SI.getType();
3280 
3281   if (Value *V = simplifySelectInst(CondVal, TrueVal, FalseVal,
3282                                     SQ.getWithInstruction(&SI)))
3283     return replaceInstUsesWith(SI, V);
3284 
3285   if (Instruction *I = canonicalizeSelectToShuffle(SI))
3286     return I;
3287 
3288   if (Instruction *I = canonicalizeScalarSelectOfVecs(SI, *this))
3289     return I;
3290 
3291   // If the type of select is not an integer type or if the condition and
3292   // the selection type are not both scalar nor both vector types, there is no
3293   // point in attempting to match these patterns.
3294   Type *CondType = CondVal->getType();
3295   if (!isa<Constant>(CondVal) && SelType->isIntOrIntVectorTy() &&
3296       CondType->isVectorTy() == SelType->isVectorTy()) {
3297     if (Value *S = simplifyWithOpReplaced(TrueVal, CondVal,
3298                                           ConstantInt::getTrue(CondType), SQ,
3299                                           /* AllowRefinement */ true))
3300       return replaceOperand(SI, 1, S);
3301 
3302     if (Value *S = simplifyWithOpReplaced(FalseVal, CondVal,
3303                                           ConstantInt::getFalse(CondType), SQ,
3304                                           /* AllowRefinement */ true))
3305       return replaceOperand(SI, 2, S);
3306 
3307     // Handle patterns involving sext/zext + not explicitly,
3308     // as simplifyWithOpReplaced() only looks past one instruction.
3309     Value *NotCond;
3310 
3311     // select a, sext(!a), b -> select !a, b, 0
3312     // select a, zext(!a), b -> select !a, b, 0
3313     if (match(TrueVal, m_ZExtOrSExt(m_CombineAnd(m_Value(NotCond),
3314                                                  m_Not(m_Specific(CondVal))))))
3315       return SelectInst::Create(NotCond, FalseVal,
3316                                 Constant::getNullValue(SelType));
3317 
3318     // select a, b, zext(!a) -> select !a, 1, b
3319     if (match(FalseVal, m_ZExt(m_CombineAnd(m_Value(NotCond),
3320                                             m_Not(m_Specific(CondVal))))))
3321       return SelectInst::Create(NotCond, ConstantInt::get(SelType, 1), TrueVal);
3322 
3323     // select a, b, sext(!a) -> select !a, -1, b
3324     if (match(FalseVal, m_SExt(m_CombineAnd(m_Value(NotCond),
3325                                             m_Not(m_Specific(CondVal))))))
3326       return SelectInst::Create(NotCond, Constant::getAllOnesValue(SelType),
3327                                 TrueVal);
3328   }
3329 
3330   if (Instruction *R = foldSelectOfBools(SI))
3331     return R;
3332 
3333   // Selecting between two integer or vector splat integer constants?
3334   //
3335   // Note that we don't handle a scalar select of vectors:
3336   // select i1 %c, <2 x i8> <1, 1>, <2 x i8> <0, 0>
3337   // because that may need 3 instructions to splat the condition value:
3338   // extend, insertelement, shufflevector.
3339   //
3340   // Do not handle i1 TrueVal and FalseVal otherwise would result in
3341   // zext/sext i1 to i1.
3342   if (SelType->isIntOrIntVectorTy() && !SelType->isIntOrIntVectorTy(1) &&
3343       CondVal->getType()->isVectorTy() == SelType->isVectorTy()) {
3344     // select C, 1, 0 -> zext C to int
3345     if (match(TrueVal, m_One()) && match(FalseVal, m_Zero()))
3346       return new ZExtInst(CondVal, SelType);
3347 
3348     // select C, -1, 0 -> sext C to int
3349     if (match(TrueVal, m_AllOnes()) && match(FalseVal, m_Zero()))
3350       return new SExtInst(CondVal, SelType);
3351 
3352     // select C, 0, 1 -> zext !C to int
3353     if (match(TrueVal, m_Zero()) && match(FalseVal, m_One())) {
3354       Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName());
3355       return new ZExtInst(NotCond, SelType);
3356     }
3357 
3358     // select C, 0, -1 -> sext !C to int
3359     if (match(TrueVal, m_Zero()) && match(FalseVal, m_AllOnes())) {
3360       Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName());
3361       return new SExtInst(NotCond, SelType);
3362     }
3363   }
3364 
3365   if (auto *FCmp = dyn_cast<FCmpInst>(CondVal)) {
3366     Value *Cmp0 = FCmp->getOperand(0), *Cmp1 = FCmp->getOperand(1);
3367     // Are we selecting a value based on a comparison of the two values?
3368     if ((Cmp0 == TrueVal && Cmp1 == FalseVal) ||
3369         (Cmp0 == FalseVal && Cmp1 == TrueVal)) {
3370       // Canonicalize to use ordered comparisons by swapping the select
3371       // operands.
3372       //
3373       // e.g.
3374       // (X ugt Y) ? X : Y -> (X ole Y) ? Y : X
3375       if (FCmp->hasOneUse() && FCmpInst::isUnordered(FCmp->getPredicate())) {
3376         FCmpInst::Predicate InvPred = FCmp->getInversePredicate();
3377         IRBuilder<>::FastMathFlagGuard FMFG(Builder);
3378         // FIXME: The FMF should propagate from the select, not the fcmp.
3379         Builder.setFastMathFlags(FCmp->getFastMathFlags());
3380         Value *NewCond = Builder.CreateFCmp(InvPred, Cmp0, Cmp1,
3381                                             FCmp->getName() + ".inv");
3382         Value *NewSel = Builder.CreateSelect(NewCond, FalseVal, TrueVal);
3383         return replaceInstUsesWith(SI, NewSel);
3384       }
3385     }
3386   }
3387 
3388   if (isa<FPMathOperator>(SI)) {
3389     // TODO: Try to forward-propagate FMF from select arms to the select.
3390 
3391     // Canonicalize select of FP values where NaN and -0.0 are not valid as
3392     // minnum/maxnum intrinsics.
3393     if (SI.hasNoNaNs() && SI.hasNoSignedZeros()) {
3394       Value *X, *Y;
3395       if (match(&SI, m_OrdFMax(m_Value(X), m_Value(Y))))
3396         return replaceInstUsesWith(
3397             SI, Builder.CreateBinaryIntrinsic(Intrinsic::maxnum, X, Y, &SI));
3398 
3399       if (match(&SI, m_OrdFMin(m_Value(X), m_Value(Y))))
3400         return replaceInstUsesWith(
3401             SI, Builder.CreateBinaryIntrinsic(Intrinsic::minnum, X, Y, &SI));
3402     }
3403   }
3404 
3405   // Fold selecting to fabs.
3406   if (Instruction *Fabs = foldSelectWithFCmpToFabs(SI, *this))
3407     return Fabs;
3408 
3409   // See if we are selecting two values based on a comparison of the two values.
3410   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
3411     if (Instruction *Result = foldSelectInstWithICmp(SI, ICI))
3412       return Result;
3413 
3414   if (Instruction *Add = foldAddSubSelect(SI, Builder))
3415     return Add;
3416   if (Instruction *Add = foldOverflowingAddSubSelect(SI, Builder))
3417     return Add;
3418   if (Instruction *Or = foldSetClearBits(SI, Builder))
3419     return Or;
3420   if (Instruction *Mul = foldSelectZeroOrMul(SI, *this))
3421     return Mul;
3422 
3423   // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
3424   auto *TI = dyn_cast<Instruction>(TrueVal);
3425   auto *FI = dyn_cast<Instruction>(FalseVal);
3426   if (TI && FI && TI->getOpcode() == FI->getOpcode())
3427     if (Instruction *IV = foldSelectOpOp(SI, TI, FI))
3428       return IV;
3429 
3430   if (Instruction *I = foldSelectExtConst(SI))
3431     return I;
3432 
3433   // Fold (select C, (gep Ptr, Idx), Ptr) -> (gep Ptr, (select C, Idx, 0))
3434   // Fold (select C, Ptr, (gep Ptr, Idx)) -> (gep Ptr, (select C, 0, Idx))
3435   auto SelectGepWithBase = [&](GetElementPtrInst *Gep, Value *Base,
3436                                bool Swap) -> GetElementPtrInst * {
3437     Value *Ptr = Gep->getPointerOperand();
3438     if (Gep->getNumOperands() != 2 || Gep->getPointerOperand() != Base ||
3439         !Gep->hasOneUse())
3440       return nullptr;
3441     Value *Idx = Gep->getOperand(1);
3442     if (isa<VectorType>(CondVal->getType()) && !isa<VectorType>(Idx->getType()))
3443       return nullptr;
3444     Type *ElementType = Gep->getResultElementType();
3445     Value *NewT = Idx;
3446     Value *NewF = Constant::getNullValue(Idx->getType());
3447     if (Swap)
3448       std::swap(NewT, NewF);
3449     Value *NewSI =
3450         Builder.CreateSelect(CondVal, NewT, NewF, SI.getName() + ".idx", &SI);
3451     if (Gep->isInBounds())
3452       return GetElementPtrInst::CreateInBounds(ElementType, Ptr, {NewSI});
3453     return GetElementPtrInst::Create(ElementType, Ptr, {NewSI});
3454   };
3455   if (auto *TrueGep = dyn_cast<GetElementPtrInst>(TrueVal))
3456     if (auto *NewGep = SelectGepWithBase(TrueGep, FalseVal, false))
3457       return NewGep;
3458   if (auto *FalseGep = dyn_cast<GetElementPtrInst>(FalseVal))
3459     if (auto *NewGep = SelectGepWithBase(FalseGep, TrueVal, true))
3460       return NewGep;
3461 
3462   // See if we can fold the select into one of our operands.
3463   if (SelType->isIntOrIntVectorTy() || SelType->isFPOrFPVectorTy()) {
3464     if (Instruction *FoldI = foldSelectIntoOp(SI, TrueVal, FalseVal))
3465       return FoldI;
3466 
3467     Value *LHS, *RHS;
3468     Instruction::CastOps CastOp;
3469     SelectPatternResult SPR = matchSelectPattern(&SI, LHS, RHS, &CastOp);
3470     auto SPF = SPR.Flavor;
3471     if (SPF) {
3472       Value *LHS2, *RHS2;
3473       if (SelectPatternFlavor SPF2 = matchSelectPattern(LHS, LHS2, RHS2).Flavor)
3474         if (Instruction *R = foldSPFofSPF(cast<Instruction>(LHS), SPF2, LHS2,
3475                                           RHS2, SI, SPF, RHS))
3476           return R;
3477       if (SelectPatternFlavor SPF2 = matchSelectPattern(RHS, LHS2, RHS2).Flavor)
3478         if (Instruction *R = foldSPFofSPF(cast<Instruction>(RHS), SPF2, LHS2,
3479                                           RHS2, SI, SPF, LHS))
3480           return R;
3481     }
3482 
3483     if (SelectPatternResult::isMinOrMax(SPF)) {
3484       // Canonicalize so that
3485       // - type casts are outside select patterns.
3486       // - float clamp is transformed to min/max pattern
3487 
3488       bool IsCastNeeded = LHS->getType() != SelType;
3489       Value *CmpLHS = cast<CmpInst>(CondVal)->getOperand(0);
3490       Value *CmpRHS = cast<CmpInst>(CondVal)->getOperand(1);
3491       if (IsCastNeeded ||
3492           (LHS->getType()->isFPOrFPVectorTy() &&
3493            ((CmpLHS != LHS && CmpLHS != RHS) ||
3494             (CmpRHS != LHS && CmpRHS != RHS)))) {
3495         CmpInst::Predicate MinMaxPred = getMinMaxPred(SPF, SPR.Ordered);
3496 
3497         Value *Cmp;
3498         if (CmpInst::isIntPredicate(MinMaxPred)) {
3499           Cmp = Builder.CreateICmp(MinMaxPred, LHS, RHS);
3500         } else {
3501           IRBuilder<>::FastMathFlagGuard FMFG(Builder);
3502           auto FMF =
3503               cast<FPMathOperator>(SI.getCondition())->getFastMathFlags();
3504           Builder.setFastMathFlags(FMF);
3505           Cmp = Builder.CreateFCmp(MinMaxPred, LHS, RHS);
3506         }
3507 
3508         Value *NewSI = Builder.CreateSelect(Cmp, LHS, RHS, SI.getName(), &SI);
3509         if (!IsCastNeeded)
3510           return replaceInstUsesWith(SI, NewSI);
3511 
3512         Value *NewCast = Builder.CreateCast(CastOp, NewSI, SelType);
3513         return replaceInstUsesWith(SI, NewCast);
3514       }
3515     }
3516   }
3517 
3518   // See if we can fold the select into a phi node if the condition is a select.
3519   if (auto *PN = dyn_cast<PHINode>(SI.getCondition()))
3520     // The true/false values have to be live in the PHI predecessor's blocks.
3521     if (canSelectOperandBeMappingIntoPredBlock(TrueVal, SI) &&
3522         canSelectOperandBeMappingIntoPredBlock(FalseVal, SI))
3523       if (Instruction *NV = foldOpIntoPhi(SI, PN))
3524         return NV;
3525 
3526   if (SelectInst *TrueSI = dyn_cast<SelectInst>(TrueVal)) {
3527     if (TrueSI->getCondition()->getType() == CondVal->getType()) {
3528       // select(C, select(C, a, b), c) -> select(C, a, c)
3529       if (TrueSI->getCondition() == CondVal) {
3530         if (SI.getTrueValue() == TrueSI->getTrueValue())
3531           return nullptr;
3532         return replaceOperand(SI, 1, TrueSI->getTrueValue());
3533       }
3534       // select(C0, select(C1, a, b), b) -> select(C0&C1, a, b)
3535       // We choose this as normal form to enable folding on the And and
3536       // shortening paths for the values (this helps getUnderlyingObjects() for
3537       // example).
3538       if (TrueSI->getFalseValue() == FalseVal && TrueSI->hasOneUse()) {
3539         Value *And = Builder.CreateLogicalAnd(CondVal, TrueSI->getCondition());
3540         replaceOperand(SI, 0, And);
3541         replaceOperand(SI, 1, TrueSI->getTrueValue());
3542         return &SI;
3543       }
3544     }
3545   }
3546   if (SelectInst *FalseSI = dyn_cast<SelectInst>(FalseVal)) {
3547     if (FalseSI->getCondition()->getType() == CondVal->getType()) {
3548       // select(C, a, select(C, b, c)) -> select(C, a, c)
3549       if (FalseSI->getCondition() == CondVal) {
3550         if (SI.getFalseValue() == FalseSI->getFalseValue())
3551           return nullptr;
3552         return replaceOperand(SI, 2, FalseSI->getFalseValue());
3553       }
3554       // select(C0, a, select(C1, a, b)) -> select(C0|C1, a, b)
3555       if (FalseSI->getTrueValue() == TrueVal && FalseSI->hasOneUse()) {
3556         Value *Or = Builder.CreateLogicalOr(CondVal, FalseSI->getCondition());
3557         replaceOperand(SI, 0, Or);
3558         replaceOperand(SI, 2, FalseSI->getFalseValue());
3559         return &SI;
3560       }
3561     }
3562   }
3563 
3564   // Try to simplify a binop sandwiched between 2 selects with the same
3565   // condition. This is not valid for div/rem because the select might be
3566   // preventing a division-by-zero.
3567   // TODO: A div/rem restriction is conservative; use something like
3568   //       isSafeToSpeculativelyExecute().
3569   // select(C, binop(select(C, X, Y), W), Z) -> select(C, binop(X, W), Z)
3570   BinaryOperator *TrueBO;
3571   if (match(TrueVal, m_OneUse(m_BinOp(TrueBO))) && !TrueBO->isIntDivRem()) {
3572     if (auto *TrueBOSI = dyn_cast<SelectInst>(TrueBO->getOperand(0))) {
3573       if (TrueBOSI->getCondition() == CondVal) {
3574         replaceOperand(*TrueBO, 0, TrueBOSI->getTrueValue());
3575         Worklist.push(TrueBO);
3576         return &SI;
3577       }
3578     }
3579     if (auto *TrueBOSI = dyn_cast<SelectInst>(TrueBO->getOperand(1))) {
3580       if (TrueBOSI->getCondition() == CondVal) {
3581         replaceOperand(*TrueBO, 1, TrueBOSI->getTrueValue());
3582         Worklist.push(TrueBO);
3583         return &SI;
3584       }
3585     }
3586   }
3587 
3588   // select(C, Z, binop(select(C, X, Y), W)) -> select(C, Z, binop(Y, W))
3589   BinaryOperator *FalseBO;
3590   if (match(FalseVal, m_OneUse(m_BinOp(FalseBO))) && !FalseBO->isIntDivRem()) {
3591     if (auto *FalseBOSI = dyn_cast<SelectInst>(FalseBO->getOperand(0))) {
3592       if (FalseBOSI->getCondition() == CondVal) {
3593         replaceOperand(*FalseBO, 0, FalseBOSI->getFalseValue());
3594         Worklist.push(FalseBO);
3595         return &SI;
3596       }
3597     }
3598     if (auto *FalseBOSI = dyn_cast<SelectInst>(FalseBO->getOperand(1))) {
3599       if (FalseBOSI->getCondition() == CondVal) {
3600         replaceOperand(*FalseBO, 1, FalseBOSI->getFalseValue());
3601         Worklist.push(FalseBO);
3602         return &SI;
3603       }
3604     }
3605   }
3606 
3607   Value *NotCond;
3608   if (match(CondVal, m_Not(m_Value(NotCond))) &&
3609       !InstCombiner::shouldAvoidAbsorbingNotIntoSelect(SI)) {
3610     replaceOperand(SI, 0, NotCond);
3611     SI.swapValues();
3612     SI.swapProfMetadata();
3613     return &SI;
3614   }
3615 
3616   if (Instruction *I = foldVectorSelect(SI))
3617     return I;
3618 
3619   // If we can compute the condition, there's no need for a select.
3620   // Like the above fold, we are attempting to reduce compile-time cost by
3621   // putting this fold here with limitations rather than in InstSimplify.
3622   // The motivation for this call into value tracking is to take advantage of
3623   // the assumption cache, so make sure that is populated.
3624   if (!CondVal->getType()->isVectorTy() && !AC.assumptions().empty()) {
3625     KnownBits Known(1);
3626     computeKnownBits(CondVal, Known, 0, &SI);
3627     if (Known.One.isOne())
3628       return replaceInstUsesWith(SI, TrueVal);
3629     if (Known.Zero.isOne())
3630       return replaceInstUsesWith(SI, FalseVal);
3631   }
3632 
3633   if (Instruction *BitCastSel = foldSelectCmpBitcasts(SI, Builder))
3634     return BitCastSel;
3635 
3636   // Simplify selects that test the returned flag of cmpxchg instructions.
3637   if (Value *V = foldSelectCmpXchg(SI))
3638     return replaceInstUsesWith(SI, V);
3639 
3640   if (Instruction *Select = foldSelectBinOpIdentity(SI, TLI, *this))
3641     return Select;
3642 
3643   if (Instruction *Funnel = foldSelectFunnelShift(SI, Builder))
3644     return Funnel;
3645 
3646   if (Instruction *Copysign = foldSelectToCopysign(SI, Builder))
3647     return Copysign;
3648 
3649   if (Instruction *PN = foldSelectToPhi(SI, DT, Builder))
3650     return replaceInstUsesWith(SI, PN);
3651 
3652   if (Value *Fr = foldSelectWithFrozenICmp(SI, Builder))
3653     return replaceInstUsesWith(SI, Fr);
3654 
3655   if (Value *V = foldRoundUpIntegerWithPow2Alignment(SI, Builder))
3656     return replaceInstUsesWith(SI, V);
3657 
3658   // select(mask, mload(,,mask,0), 0) -> mload(,,mask,0)
3659   // Load inst is intentionally not checked for hasOneUse()
3660   if (match(FalseVal, m_Zero()) &&
3661       (match(TrueVal, m_MaskedLoad(m_Value(), m_Value(), m_Specific(CondVal),
3662                                    m_CombineOr(m_Undef(), m_Zero()))) ||
3663        match(TrueVal, m_MaskedGather(m_Value(), m_Value(), m_Specific(CondVal),
3664                                      m_CombineOr(m_Undef(), m_Zero()))))) {
3665     auto *MaskedInst = cast<IntrinsicInst>(TrueVal);
3666     if (isa<UndefValue>(MaskedInst->getArgOperand(3)))
3667       MaskedInst->setArgOperand(3, FalseVal /* Zero */);
3668     return replaceInstUsesWith(SI, MaskedInst);
3669   }
3670 
3671   Value *Mask;
3672   if (match(TrueVal, m_Zero()) &&
3673       (match(FalseVal, m_MaskedLoad(m_Value(), m_Value(), m_Value(Mask),
3674                                     m_CombineOr(m_Undef(), m_Zero()))) ||
3675        match(FalseVal, m_MaskedGather(m_Value(), m_Value(), m_Value(Mask),
3676                                       m_CombineOr(m_Undef(), m_Zero())))) &&
3677       (CondVal->getType() == Mask->getType())) {
3678     // We can remove the select by ensuring the load zeros all lanes the
3679     // select would have.  We determine this by proving there is no overlap
3680     // between the load and select masks.
3681     // (i.e (load_mask & select_mask) == 0 == no overlap)
3682     bool CanMergeSelectIntoLoad = false;
3683     if (Value *V = simplifyAndInst(CondVal, Mask, SQ.getWithInstruction(&SI)))
3684       CanMergeSelectIntoLoad = match(V, m_Zero());
3685 
3686     if (CanMergeSelectIntoLoad) {
3687       auto *MaskedInst = cast<IntrinsicInst>(FalseVal);
3688       if (isa<UndefValue>(MaskedInst->getArgOperand(3)))
3689         MaskedInst->setArgOperand(3, TrueVal /* Zero */);
3690       return replaceInstUsesWith(SI, MaskedInst);
3691     }
3692   }
3693 
3694   if (Instruction *I = foldNestedSelects(SI, Builder))
3695     return I;
3696 
3697   // Match logical variants of the pattern,
3698   // and transform them iff that gets rid of inversions.
3699   //   (~x) | y  -->  ~(x & (~y))
3700   //   (~x) & y  -->  ~(x | (~y))
3701   if (sinkNotIntoOtherHandOfLogicalOp(SI))
3702     return &SI;
3703 
3704   if (Instruction *I = foldBitCeil(SI, Builder))
3705     return I;
3706 
3707   return nullptr;
3708 }
3709