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