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