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