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