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