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