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/Analysis/CmpInstAnalysis.h"
16 #include "llvm/Analysis/ConstantFolding.h"
17 #include "llvm/Analysis/InstructionSimplify.h"
18 #include "llvm/Analysis/ValueTracking.h"
19 #include "llvm/IR/MDBuilder.h"
20 #include "llvm/IR/PatternMatch.h"
21 #include "llvm/Support/KnownBits.h"
22 using namespace llvm;
23 using namespace PatternMatch;
24 
25 #define DEBUG_TYPE "instcombine"
26 
27 static SelectPatternFlavor
28 getInverseMinMaxSelectPattern(SelectPatternFlavor SPF) {
29   switch (SPF) {
30   default:
31     llvm_unreachable("unhandled!");
32 
33   case SPF_SMIN:
34     return SPF_SMAX;
35   case SPF_UMIN:
36     return SPF_UMAX;
37   case SPF_SMAX:
38     return SPF_SMIN;
39   case SPF_UMAX:
40     return SPF_UMIN;
41   }
42 }
43 
44 static CmpInst::Predicate getCmpPredicateForMinMax(SelectPatternFlavor SPF,
45                                                    bool Ordered=false) {
46   switch (SPF) {
47   default:
48     llvm_unreachable("unhandled!");
49 
50   case SPF_SMIN:
51     return ICmpInst::ICMP_SLT;
52   case SPF_UMIN:
53     return ICmpInst::ICMP_ULT;
54   case SPF_SMAX:
55     return ICmpInst::ICMP_SGT;
56   case SPF_UMAX:
57     return ICmpInst::ICMP_UGT;
58   case SPF_FMINNUM:
59     return Ordered ? FCmpInst::FCMP_OLT : FCmpInst::FCMP_ULT;
60   case SPF_FMAXNUM:
61     return Ordered ? FCmpInst::FCMP_OGT : FCmpInst::FCMP_UGT;
62   }
63 }
64 
65 static Value *generateMinMaxSelectPattern(InstCombiner::BuilderTy &Builder,
66                                           SelectPatternFlavor SPF, Value *A,
67                                           Value *B) {
68   CmpInst::Predicate Pred = getCmpPredicateForMinMax(SPF);
69   assert(CmpInst::isIntPredicate(Pred));
70   return Builder.CreateSelect(Builder.CreateICmp(Pred, A, B), A, B);
71 }
72 
73 /// We want to turn code that looks like this:
74 ///   %C = or %A, %B
75 ///   %D = select %cond, %C, %A
76 /// into:
77 ///   %C = select %cond, %B, 0
78 ///   %D = or %A, %C
79 ///
80 /// Assuming that the specified instruction is an operand to the select, return
81 /// a bitmask indicating which operands of this instruction are foldable if they
82 /// equal the other incoming value of the select.
83 ///
84 static unsigned getSelectFoldableOperands(BinaryOperator *I) {
85   switch (I->getOpcode()) {
86   case Instruction::Add:
87   case Instruction::Mul:
88   case Instruction::And:
89   case Instruction::Or:
90   case Instruction::Xor:
91     return 3;              // Can fold through either operand.
92   case Instruction::Sub:   // Can only fold on the amount subtracted.
93   case Instruction::Shl:   // Can only fold on the shift amount.
94   case Instruction::LShr:
95   case Instruction::AShr:
96     return 1;
97   default:
98     return 0;              // Cannot fold
99   }
100 }
101 
102 /// For the same transformation as the previous function, return the identity
103 /// constant that goes into the select.
104 static Constant *getSelectFoldableConstant(BinaryOperator *I) {
105   switch (I->getOpcode()) {
106   default: llvm_unreachable("This cannot happen!");
107   case Instruction::Add:
108   case Instruction::Sub:
109   case Instruction::Or:
110   case Instruction::Xor:
111   case Instruction::Shl:
112   case Instruction::LShr:
113   case Instruction::AShr:
114     return Constant::getNullValue(I->getType());
115   case Instruction::And:
116     return Constant::getAllOnesValue(I->getType());
117   case Instruction::Mul:
118     return ConstantInt::get(I->getType(), 1);
119   }
120 }
121 
122 /// We have (select c, TI, FI), and we know that TI and FI have the same opcode.
123 Instruction *InstCombiner::foldSelectOpOp(SelectInst &SI, Instruction *TI,
124                                           Instruction *FI) {
125   // Don't break up min/max patterns. The hasOneUse checks below prevent that
126   // for most cases, but vector min/max with bitcasts can be transformed. If the
127   // one-use restrictions are eased for other patterns, we still don't want to
128   // obfuscate min/max.
129   if ((match(&SI, m_SMin(m_Value(), m_Value())) ||
130        match(&SI, m_SMax(m_Value(), m_Value())) ||
131        match(&SI, m_UMin(m_Value(), m_Value())) ||
132        match(&SI, m_UMax(m_Value(), m_Value()))))
133     return nullptr;
134 
135   // If this is a cast from the same type, merge.
136   if (TI->getNumOperands() == 1 && TI->isCast()) {
137     Type *FIOpndTy = FI->getOperand(0)->getType();
138     if (TI->getOperand(0)->getType() != FIOpndTy)
139       return nullptr;
140 
141     // The select condition may be a vector. We may only change the operand
142     // type if the vector width remains the same (and matches the condition).
143     Type *CondTy = SI.getCondition()->getType();
144     if (CondTy->isVectorTy()) {
145       if (!FIOpndTy->isVectorTy())
146         return nullptr;
147       if (CondTy->getVectorNumElements() != FIOpndTy->getVectorNumElements())
148         return nullptr;
149 
150       // TODO: If the backend knew how to deal with casts better, we could
151       // remove this limitation. For now, there's too much potential to create
152       // worse codegen by promoting the select ahead of size-altering casts
153       // (PR28160).
154       //
155       // Note that ValueTracking's matchSelectPattern() looks through casts
156       // without checking 'hasOneUse' when it matches min/max patterns, so this
157       // transform may end up happening anyway.
158       if (TI->getOpcode() != Instruction::BitCast &&
159           (!TI->hasOneUse() || !FI->hasOneUse()))
160         return nullptr;
161 
162     } else if (!TI->hasOneUse() || !FI->hasOneUse()) {
163       // TODO: The one-use restrictions for a scalar select could be eased if
164       // the fold of a select in visitLoadInst() was enhanced to match a pattern
165       // that includes a cast.
166       return nullptr;
167     }
168 
169     // Fold this by inserting a select from the input values.
170     Value *NewSI =
171         Builder.CreateSelect(SI.getCondition(), TI->getOperand(0),
172                              FI->getOperand(0), SI.getName() + ".v", &SI);
173     return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
174                             TI->getType());
175   }
176 
177   // Only handle binary operators with one-use here. As with the cast case
178   // above, it may be possible to relax the one-use constraint, but that needs
179   // be examined carefully since it may not reduce the total number of
180   // instructions.
181   BinaryOperator *BO = dyn_cast<BinaryOperator>(TI);
182   if (!BO || !TI->hasOneUse() || !FI->hasOneUse())
183     return nullptr;
184 
185   // Figure out if the operations have any operands in common.
186   Value *MatchOp, *OtherOpT, *OtherOpF;
187   bool MatchIsOpZero;
188   if (TI->getOperand(0) == FI->getOperand(0)) {
189     MatchOp  = TI->getOperand(0);
190     OtherOpT = TI->getOperand(1);
191     OtherOpF = FI->getOperand(1);
192     MatchIsOpZero = true;
193   } else if (TI->getOperand(1) == FI->getOperand(1)) {
194     MatchOp  = TI->getOperand(1);
195     OtherOpT = TI->getOperand(0);
196     OtherOpF = FI->getOperand(0);
197     MatchIsOpZero = false;
198   } else if (!TI->isCommutative()) {
199     return nullptr;
200   } else if (TI->getOperand(0) == FI->getOperand(1)) {
201     MatchOp  = TI->getOperand(0);
202     OtherOpT = TI->getOperand(1);
203     OtherOpF = FI->getOperand(0);
204     MatchIsOpZero = true;
205   } else if (TI->getOperand(1) == FI->getOperand(0)) {
206     MatchOp  = TI->getOperand(1);
207     OtherOpT = TI->getOperand(0);
208     OtherOpF = FI->getOperand(1);
209     MatchIsOpZero = true;
210   } else {
211     return nullptr;
212   }
213 
214   // If we reach here, they do have operations in common.
215   Value *NewSI = Builder.CreateSelect(SI.getCondition(), OtherOpT, OtherOpF,
216                                       SI.getName() + ".v", &SI);
217   Value *Op0 = MatchIsOpZero ? MatchOp : NewSI;
218   Value *Op1 = MatchIsOpZero ? NewSI : MatchOp;
219   return BinaryOperator::Create(BO->getOpcode(), Op0, Op1);
220 }
221 
222 static bool isSelect01(Constant *C1, Constant *C2) {
223   ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
224   if (!C1I)
225     return false;
226   ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
227   if (!C2I)
228     return false;
229   if (!C1I->isZero() && !C2I->isZero()) // One side must be zero.
230     return false;
231   return C1I->isOne() || C1I->isMinusOne() ||
232          C2I->isOne() || C2I->isMinusOne();
233 }
234 
235 /// Try to fold the select into one of the operands to allow further
236 /// optimization.
237 Instruction *InstCombiner::foldSelectIntoOp(SelectInst &SI, Value *TrueVal,
238                                             Value *FalseVal) {
239   // See the comment above GetSelectFoldableOperands for a description of the
240   // transformation we are doing here.
241   if (auto *TVI = dyn_cast<BinaryOperator>(TrueVal)) {
242     if (TVI->hasOneUse() && !isa<Constant>(FalseVal)) {
243       if (unsigned SFO = getSelectFoldableOperands(TVI)) {
244         unsigned OpToFold = 0;
245         if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
246           OpToFold = 1;
247         } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
248           OpToFold = 2;
249         }
250 
251         if (OpToFold) {
252           Constant *C = getSelectFoldableConstant(TVI);
253           Value *OOp = TVI->getOperand(2-OpToFold);
254           // Avoid creating select between 2 constants unless it's selecting
255           // between 0, 1 and -1.
256           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
257             Value *NewSel = Builder.CreateSelect(SI.getCondition(), OOp, C);
258             NewSel->takeName(TVI);
259             BinaryOperator *BO = BinaryOperator::Create(TVI->getOpcode(),
260                                                         FalseVal, NewSel);
261             BO->copyIRFlags(TVI);
262             return BO;
263           }
264         }
265       }
266     }
267   }
268 
269   if (auto *FVI = dyn_cast<BinaryOperator>(FalseVal)) {
270     if (FVI->hasOneUse() && !isa<Constant>(TrueVal)) {
271       if (unsigned SFO = getSelectFoldableOperands(FVI)) {
272         unsigned OpToFold = 0;
273         if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
274           OpToFold = 1;
275         } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
276           OpToFold = 2;
277         }
278 
279         if (OpToFold) {
280           Constant *C = getSelectFoldableConstant(FVI);
281           Value *OOp = FVI->getOperand(2-OpToFold);
282           // Avoid creating select between 2 constants unless it's selecting
283           // between 0, 1 and -1.
284           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
285             Value *NewSel = Builder.CreateSelect(SI.getCondition(), C, OOp);
286             NewSel->takeName(FVI);
287             BinaryOperator *BO = BinaryOperator::Create(FVI->getOpcode(),
288                                                         TrueVal, NewSel);
289             BO->copyIRFlags(FVI);
290             return BO;
291           }
292         }
293       }
294     }
295   }
296 
297   return nullptr;
298 }
299 
300 /// We want to turn:
301 ///   (select (icmp eq (and X, C1), 0), Y, (or Y, C2))
302 /// into:
303 ///   (or (shl (and X, C1), C3), Y)
304 /// iff:
305 ///   C1 and C2 are both powers of 2
306 /// where:
307 ///   C3 = Log(C2) - Log(C1)
308 ///
309 /// This transform handles cases where:
310 /// 1. The icmp predicate is inverted
311 /// 2. The select operands are reversed
312 /// 3. The magnitude of C2 and C1 are flipped
313 static Value *foldSelectICmpAndOr(const SelectInst &SI, Value *TrueVal,
314                                   Value *FalseVal,
315                                   InstCombiner::BuilderTy &Builder) {
316   const ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition());
317   if (!IC || !SI.getType()->isIntegerTy())
318     return nullptr;
319 
320   Value *CmpLHS = IC->getOperand(0);
321   Value *CmpRHS = IC->getOperand(1);
322 
323   Value *V;
324   unsigned C1Log;
325   bool IsEqualZero;
326   bool NeedAnd = false;
327   if (IC->isEquality()) {
328     if (!match(CmpRHS, m_Zero()))
329       return nullptr;
330 
331     const APInt *C1;
332     if (!match(CmpLHS, m_And(m_Value(), m_Power2(C1))))
333       return nullptr;
334 
335     V = CmpLHS;
336     C1Log = C1->logBase2();
337     IsEqualZero = IC->getPredicate() == ICmpInst::ICMP_EQ;
338   } else if (IC->getPredicate() == ICmpInst::ICMP_SLT ||
339              IC->getPredicate() == ICmpInst::ICMP_SGT) {
340     // We also need to recognize (icmp slt (trunc (X)), 0) and
341     // (icmp sgt (trunc (X)), -1).
342     IsEqualZero = IC->getPredicate() == ICmpInst::ICMP_SGT;
343     if ((IsEqualZero && !match(CmpRHS, m_AllOnes())) ||
344         (!IsEqualZero && !match(CmpRHS, m_Zero())))
345       return nullptr;
346 
347     if (!match(CmpLHS, m_OneUse(m_Trunc(m_Value(V)))))
348       return nullptr;
349 
350     C1Log = CmpLHS->getType()->getScalarSizeInBits() - 1;
351     NeedAnd = true;
352   } else {
353     return nullptr;
354   }
355 
356   const APInt *C2;
357   bool OrOnTrueVal = false;
358   bool OrOnFalseVal = match(FalseVal, m_Or(m_Specific(TrueVal), m_Power2(C2)));
359   if (!OrOnFalseVal)
360     OrOnTrueVal = match(TrueVal, m_Or(m_Specific(FalseVal), m_Power2(C2)));
361 
362   if (!OrOnFalseVal && !OrOnTrueVal)
363     return nullptr;
364 
365   Value *Y = OrOnFalseVal ? TrueVal : FalseVal;
366 
367   unsigned C2Log = C2->logBase2();
368 
369   bool NeedXor = (!IsEqualZero && OrOnFalseVal) || (IsEqualZero && OrOnTrueVal);
370   bool NeedShift = C1Log != C2Log;
371   bool NeedZExtTrunc = Y->getType()->getIntegerBitWidth() !=
372                        V->getType()->getIntegerBitWidth();
373 
374   // Make sure we don't create more instructions than we save.
375   Value *Or = OrOnFalseVal ? FalseVal : TrueVal;
376   if ((NeedShift + NeedXor + NeedZExtTrunc) >
377       (IC->hasOneUse() + Or->hasOneUse()))
378     return nullptr;
379 
380   if (NeedAnd) {
381     // Insert the AND instruction on the input to the truncate.
382     APInt C1 = APInt::getOneBitSet(V->getType()->getScalarSizeInBits(), C1Log);
383     V = Builder.CreateAnd(V, ConstantInt::get(V->getType(), C1));
384   }
385 
386   if (C2Log > C1Log) {
387     V = Builder.CreateZExtOrTrunc(V, Y->getType());
388     V = Builder.CreateShl(V, C2Log - C1Log);
389   } else if (C1Log > C2Log) {
390     V = Builder.CreateLShr(V, C1Log - C2Log);
391     V = Builder.CreateZExtOrTrunc(V, Y->getType());
392   } else
393     V = Builder.CreateZExtOrTrunc(V, Y->getType());
394 
395   if (NeedXor)
396     V = Builder.CreateXor(V, *C2);
397 
398   return Builder.CreateOr(V, Y);
399 }
400 
401 /// Attempt to fold a cttz/ctlz followed by a icmp plus select into a single
402 /// call to cttz/ctlz with flag 'is_zero_undef' cleared.
403 ///
404 /// For example, we can fold the following code sequence:
405 /// \code
406 ///   %0 = tail call i32 @llvm.cttz.i32(i32 %x, i1 true)
407 ///   %1 = icmp ne i32 %x, 0
408 ///   %2 = select i1 %1, i32 %0, i32 32
409 /// \code
410 ///
411 /// into:
412 ///   %0 = tail call i32 @llvm.cttz.i32(i32 %x, i1 false)
413 static Value *foldSelectCttzCtlz(ICmpInst *ICI, Value *TrueVal, Value *FalseVal,
414                                  InstCombiner::BuilderTy &Builder) {
415   ICmpInst::Predicate Pred = ICI->getPredicate();
416   Value *CmpLHS = ICI->getOperand(0);
417   Value *CmpRHS = ICI->getOperand(1);
418 
419   // Check if the condition value compares a value for equality against zero.
420   if (!ICI->isEquality() || !match(CmpRHS, m_Zero()))
421     return nullptr;
422 
423   Value *Count = FalseVal;
424   Value *ValueOnZero = TrueVal;
425   if (Pred == ICmpInst::ICMP_NE)
426     std::swap(Count, ValueOnZero);
427 
428   // Skip zero extend/truncate.
429   Value *V = nullptr;
430   if (match(Count, m_ZExt(m_Value(V))) ||
431       match(Count, m_Trunc(m_Value(V))))
432     Count = V;
433 
434   // Check if the value propagated on zero is a constant number equal to the
435   // sizeof in bits of 'Count'.
436   unsigned SizeOfInBits = Count->getType()->getScalarSizeInBits();
437   if (!match(ValueOnZero, m_SpecificInt(SizeOfInBits)))
438     return nullptr;
439 
440   // Check that 'Count' is a call to intrinsic cttz/ctlz. Also check that the
441   // input to the cttz/ctlz is used as LHS for the compare instruction.
442   if (match(Count, m_Intrinsic<Intrinsic::cttz>(m_Specific(CmpLHS))) ||
443       match(Count, m_Intrinsic<Intrinsic::ctlz>(m_Specific(CmpLHS)))) {
444     IntrinsicInst *II = cast<IntrinsicInst>(Count);
445     // Explicitly clear the 'undef_on_zero' flag.
446     IntrinsicInst *NewI = cast<IntrinsicInst>(II->clone());
447     NewI->setArgOperand(1, ConstantInt::getFalse(NewI->getContext()));
448     Builder.Insert(NewI);
449     return Builder.CreateZExtOrTrunc(NewI, ValueOnZero->getType());
450   }
451 
452   return nullptr;
453 }
454 
455 /// Return true if we find and adjust an icmp+select pattern where the compare
456 /// is with a constant that can be incremented or decremented to match the
457 /// minimum or maximum idiom.
458 static bool adjustMinMax(SelectInst &Sel, ICmpInst &Cmp) {
459   ICmpInst::Predicate Pred = Cmp.getPredicate();
460   Value *CmpLHS = Cmp.getOperand(0);
461   Value *CmpRHS = Cmp.getOperand(1);
462   Value *TrueVal = Sel.getTrueValue();
463   Value *FalseVal = Sel.getFalseValue();
464 
465   // We may move or edit the compare, so make sure the select is the only user.
466   const APInt *CmpC;
467   if (!Cmp.hasOneUse() || !match(CmpRHS, m_APInt(CmpC)))
468     return false;
469 
470   // These transforms only work for selects of integers or vector selects of
471   // integer vectors.
472   Type *SelTy = Sel.getType();
473   auto *SelEltTy = dyn_cast<IntegerType>(SelTy->getScalarType());
474   if (!SelEltTy || SelTy->isVectorTy() != Cmp.getType()->isVectorTy())
475     return false;
476 
477   Constant *AdjustedRHS;
478   if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_SGT)
479     AdjustedRHS = ConstantInt::get(CmpRHS->getType(), *CmpC + 1);
480   else if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT)
481     AdjustedRHS = ConstantInt::get(CmpRHS->getType(), *CmpC - 1);
482   else
483     return false;
484 
485   // X > C ? X : C+1  -->  X < C+1 ? C+1 : X
486   // X < C ? X : C-1  -->  X > C-1 ? C-1 : X
487   if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
488       (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
489     ; // Nothing to do here. Values match without any sign/zero extension.
490   }
491   // Types do not match. Instead of calculating this with mixed types, promote
492   // all to the larger type. This enables scalar evolution to analyze this
493   // expression.
494   else if (CmpRHS->getType()->getScalarSizeInBits() < SelEltTy->getBitWidth()) {
495     Constant *SextRHS = ConstantExpr::getSExt(AdjustedRHS, SelTy);
496 
497     // X = sext x; x >s c ? X : C+1 --> X = sext x; X <s C+1 ? C+1 : X
498     // X = sext x; x <s c ? X : C-1 --> X = sext x; X >s C-1 ? C-1 : X
499     // X = sext x; x >u c ? X : C+1 --> X = sext x; X <u C+1 ? C+1 : X
500     // X = sext x; x <u c ? X : C-1 --> X = sext x; X >u C-1 ? C-1 : X
501     if (match(TrueVal, m_SExt(m_Specific(CmpLHS))) && SextRHS == FalseVal) {
502       CmpLHS = TrueVal;
503       AdjustedRHS = SextRHS;
504     } else if (match(FalseVal, m_SExt(m_Specific(CmpLHS))) &&
505                SextRHS == TrueVal) {
506       CmpLHS = FalseVal;
507       AdjustedRHS = SextRHS;
508     } else if (Cmp.isUnsigned()) {
509       Constant *ZextRHS = ConstantExpr::getZExt(AdjustedRHS, SelTy);
510       // X = zext x; x >u c ? X : C+1 --> X = zext x; X <u C+1 ? C+1 : X
511       // X = zext x; x <u c ? X : C-1 --> X = zext x; X >u C-1 ? C-1 : X
512       // zext + signed compare cannot be changed:
513       //    0xff <s 0x00, but 0x00ff >s 0x0000
514       if (match(TrueVal, m_ZExt(m_Specific(CmpLHS))) && ZextRHS == FalseVal) {
515         CmpLHS = TrueVal;
516         AdjustedRHS = ZextRHS;
517       } else if (match(FalseVal, m_ZExt(m_Specific(CmpLHS))) &&
518                  ZextRHS == TrueVal) {
519         CmpLHS = FalseVal;
520         AdjustedRHS = ZextRHS;
521       } else {
522         return false;
523       }
524     } else {
525       return false;
526     }
527   } else {
528     return false;
529   }
530 
531   Pred = ICmpInst::getSwappedPredicate(Pred);
532   CmpRHS = AdjustedRHS;
533   std::swap(FalseVal, TrueVal);
534   Cmp.setPredicate(Pred);
535   Cmp.setOperand(0, CmpLHS);
536   Cmp.setOperand(1, CmpRHS);
537   Sel.setOperand(1, TrueVal);
538   Sel.setOperand(2, FalseVal);
539   Sel.swapProfMetadata();
540 
541   // Move the compare instruction right before the select instruction. Otherwise
542   // the sext/zext value may be defined after the compare instruction uses it.
543   Cmp.moveBefore(&Sel);
544 
545   return true;
546 }
547 
548 /// If this is an integer min/max (icmp + select) with a constant operand,
549 /// create the canonical icmp for the min/max operation and canonicalize the
550 /// constant to the 'false' operand of the select:
551 /// select (icmp Pred X, C1), C2, X --> select (icmp Pred' X, C2), X, C2
552 /// Note: if C1 != C2, this will change the icmp constant to the existing
553 /// constant operand of the select.
554 static Instruction *
555 canonicalizeMinMaxWithConstant(SelectInst &Sel, ICmpInst &Cmp,
556                                InstCombiner::BuilderTy &Builder) {
557   if (!Cmp.hasOneUse() || !isa<Constant>(Cmp.getOperand(1)))
558     return nullptr;
559 
560   // Canonicalize the compare predicate based on whether we have min or max.
561   Value *LHS, *RHS;
562   ICmpInst::Predicate NewPred;
563   SelectPatternResult SPR = matchSelectPattern(&Sel, LHS, RHS);
564   switch (SPR.Flavor) {
565   case SPF_SMIN: NewPred = ICmpInst::ICMP_SLT; break;
566   case SPF_UMIN: NewPred = ICmpInst::ICMP_ULT; break;
567   case SPF_SMAX: NewPred = ICmpInst::ICMP_SGT; break;
568   case SPF_UMAX: NewPred = ICmpInst::ICMP_UGT; break;
569   default: return nullptr;
570   }
571 
572   // Is this already canonical?
573   if (Cmp.getOperand(0) == LHS && Cmp.getOperand(1) == RHS &&
574       Cmp.getPredicate() == NewPred)
575     return nullptr;
576 
577   // Create the canonical compare and plug it into the select.
578   Sel.setCondition(Builder.CreateICmp(NewPred, LHS, RHS));
579 
580   // If the select operands did not change, we're done.
581   if (Sel.getTrueValue() == LHS && Sel.getFalseValue() == RHS)
582     return &Sel;
583 
584   // If we are swapping the select operands, swap the metadata too.
585   assert(Sel.getTrueValue() == RHS && Sel.getFalseValue() == LHS &&
586          "Unexpected results from matchSelectPattern");
587   Sel.setTrueValue(LHS);
588   Sel.setFalseValue(RHS);
589   Sel.swapProfMetadata();
590   return &Sel;
591 }
592 
593 /// If one of the constants is zero (we know they can't both be) and we have an
594 /// icmp instruction with zero, and we have an 'and' with the non-constant value
595 /// and a power of two we can turn the select into a shift on the result of the
596 /// 'and'.
597 /// This folds:
598 ///  select (icmp eq (and X, C1)), C2, C3
599 ///    iff C1 is a power 2 and the difference between C2 and C3 is a power of 2.
600 /// To something like:
601 ///  (shr (and (X, C1)), (log2(C1) - log2(C2-C3))) + C3
602 /// Or:
603 ///  (shl (and (X, C1)), (log2(C2-C3) - log2(C1))) + C3
604 /// With some variations depending if C3 is larger than C2, or the shift
605 /// isn't needed, or the bit widths don't match.
606 static Value *foldSelectICmpAnd(Type *SelType, const ICmpInst *IC,
607                                 APInt TrueVal, APInt FalseVal,
608                                 InstCombiner::BuilderTy &Builder) {
609   assert(SelType->isIntOrIntVectorTy() && "Not an integer select?");
610 
611   // If this is a vector select, we need a vector compare.
612   if (SelType->isVectorTy() != IC->getType()->isVectorTy())
613     return nullptr;
614 
615   Value *V;
616   APInt AndMask;
617   bool CreateAnd = false;
618   ICmpInst::Predicate Pred = IC->getPredicate();
619   if (ICmpInst::isEquality(Pred)) {
620     if (!match(IC->getOperand(1), m_Zero()))
621       return nullptr;
622 
623     V = IC->getOperand(0);
624 
625     const APInt *AndRHS;
626     if (!match(V, m_And(m_Value(), m_Power2(AndRHS))))
627       return nullptr;
628 
629     AndMask = *AndRHS;
630   } else if (decomposeBitTestICmp(IC->getOperand(0), IC->getOperand(1),
631                                   Pred, V, AndMask)) {
632     assert(ICmpInst::isEquality(Pred) && "Not equality test?");
633 
634     if (!AndMask.isPowerOf2())
635       return nullptr;
636 
637     CreateAnd = true;
638   } else {
639     return nullptr;
640   }
641 
642   // If both select arms are non-zero see if we have a select of the form
643   // 'x ? 2^n + C : C'. Then we can offset both arms by C, use the logic
644   // for 'x ? 2^n : 0' and fix the thing up at the end.
645   APInt Offset(TrueVal.getBitWidth(), 0);
646   if (!TrueVal.isNullValue() && !FalseVal.isNullValue()) {
647     if ((TrueVal - FalseVal).isPowerOf2())
648       Offset = FalseVal;
649     else if ((FalseVal - TrueVal).isPowerOf2())
650       Offset = TrueVal;
651     else
652       return nullptr;
653 
654     // Adjust TrueVal and FalseVal to the offset.
655     TrueVal -= Offset;
656     FalseVal -= Offset;
657   }
658 
659   // Make sure one of the select arms is a power of 2.
660   if (!TrueVal.isPowerOf2() && !FalseVal.isPowerOf2())
661     return nullptr;
662 
663   // Determine which shift is needed to transform result of the 'and' into the
664   // desired result.
665   const APInt &ValC = !TrueVal.isNullValue() ? TrueVal : FalseVal;
666   unsigned ValZeros = ValC.logBase2();
667   unsigned AndZeros = AndMask.logBase2();
668 
669   if (CreateAnd) {
670     // Insert the AND instruction on the input to the truncate.
671     V = Builder.CreateAnd(V, ConstantInt::get(V->getType(), AndMask));
672   }
673 
674   // If types don't match we can still convert the select by introducing a zext
675   // or a trunc of the 'and'.
676   if (ValZeros > AndZeros) {
677     V = Builder.CreateZExtOrTrunc(V, SelType);
678     V = Builder.CreateShl(V, ValZeros - AndZeros);
679   } else if (ValZeros < AndZeros) {
680     V = Builder.CreateLShr(V, AndZeros - ValZeros);
681     V = Builder.CreateZExtOrTrunc(V, SelType);
682   } else
683     V = Builder.CreateZExtOrTrunc(V, SelType);
684 
685   // Okay, now we know that everything is set up, we just don't know whether we
686   // have a icmp_ne or icmp_eq and whether the true or false val is the zero.
687   bool ShouldNotVal = !TrueVal.isNullValue();
688   ShouldNotVal ^= Pred == ICmpInst::ICMP_NE;
689   if (ShouldNotVal)
690     V = Builder.CreateXor(V, ValC);
691 
692   // Apply an offset if needed.
693   if (!Offset.isNullValue())
694     V = Builder.CreateAdd(V, ConstantInt::get(V->getType(), Offset));
695   return V;
696 }
697 
698 /// Visit a SelectInst that has an ICmpInst as its first operand.
699 Instruction *InstCombiner::foldSelectInstWithICmp(SelectInst &SI,
700                                                   ICmpInst *ICI) {
701   Value *TrueVal = SI.getTrueValue();
702   Value *FalseVal = SI.getFalseValue();
703 
704   if (Instruction *NewSel = canonicalizeMinMaxWithConstant(SI, *ICI, Builder))
705     return NewSel;
706 
707   bool Changed = adjustMinMax(SI, *ICI);
708 
709   ICmpInst::Predicate Pred = ICI->getPredicate();
710   Value *CmpLHS = ICI->getOperand(0);
711   Value *CmpRHS = ICI->getOperand(1);
712 
713   // Transform (X >s -1) ? C1 : C2 --> ((X >>s 31) & (C2 - C1)) + C1
714   // and       (X <s  0) ? C2 : C1 --> ((X >>s 31) & (C2 - C1)) + C1
715   // FIXME: Type and constness constraints could be lifted, but we have to
716   //        watch code size carefully. We should consider xor instead of
717   //        sub/add when we decide to do that.
718   // TODO: Merge this with foldSelectICmpAnd somehow.
719   if (CmpLHS->getType()->isIntOrIntVectorTy() &&
720       CmpLHS->getType() == TrueVal->getType()) {
721     const APInt *C1, *C2;
722     if (match(TrueVal, m_APInt(C1)) && match(FalseVal, m_APInt(C2))) {
723       ICmpInst::Predicate Pred = ICI->getPredicate();
724       Value *X;
725       APInt Mask;
726       if (decomposeBitTestICmp(CmpLHS, CmpRHS, Pred, X, Mask)) {
727         if (Mask.isSignMask()) {
728           assert(X == CmpLHS && "Expected to use the compare input directly");
729           assert(ICmpInst::isEquality(Pred) && "Expected equality predicate");
730 
731           if (Pred == ICmpInst::ICMP_NE)
732             std::swap(C1, C2);
733 
734           // This shift results in either -1 or 0.
735           Value *AShr = Builder.CreateAShr(X, Mask.getBitWidth() - 1);
736 
737           // Check if we can express the operation with a single or.
738           if (C2->isAllOnesValue())
739             return replaceInstUsesWith(SI, Builder.CreateOr(AShr, *C1));
740 
741           Value *And = Builder.CreateAnd(AShr, *C2 - *C1);
742           return replaceInstUsesWith(SI, Builder.CreateAdd(And,
743                                         ConstantInt::get(And->getType(), *C1)));
744         }
745       }
746     }
747   }
748 
749   {
750     const APInt *TrueValC, *FalseValC;
751     if (match(TrueVal, m_APInt(TrueValC)) &&
752         match(FalseVal, m_APInt(FalseValC)))
753       if (Value *V = foldSelectICmpAnd(SI.getType(), ICI, *TrueValC,
754                                        *FalseValC, Builder))
755         return replaceInstUsesWith(SI, V);
756   }
757 
758   // NOTE: if we wanted to, this is where to detect integer MIN/MAX
759 
760   if (CmpRHS != CmpLHS && isa<Constant>(CmpRHS)) {
761     if (CmpLHS == TrueVal && Pred == ICmpInst::ICMP_EQ) {
762       // Transform (X == C) ? X : Y -> (X == C) ? C : Y
763       SI.setOperand(1, CmpRHS);
764       Changed = true;
765     } else if (CmpLHS == FalseVal && Pred == ICmpInst::ICMP_NE) {
766       // Transform (X != C) ? Y : X -> (X != C) ? Y : C
767       SI.setOperand(2, CmpRHS);
768       Changed = true;
769     }
770   }
771 
772   // FIXME: This code is nearly duplicated in InstSimplify. Using/refactoring
773   // decomposeBitTestICmp() might help.
774   {
775     unsigned BitWidth =
776         DL.getTypeSizeInBits(TrueVal->getType()->getScalarType());
777     APInt MinSignedValue = APInt::getSignedMinValue(BitWidth);
778     Value *X;
779     const APInt *Y, *C;
780     bool TrueWhenUnset;
781     bool IsBitTest = false;
782     if (ICmpInst::isEquality(Pred) &&
783         match(CmpLHS, m_And(m_Value(X), m_Power2(Y))) &&
784         match(CmpRHS, m_Zero())) {
785       IsBitTest = true;
786       TrueWhenUnset = Pred == ICmpInst::ICMP_EQ;
787     } else if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, m_Zero())) {
788       X = CmpLHS;
789       Y = &MinSignedValue;
790       IsBitTest = true;
791       TrueWhenUnset = false;
792     } else if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, m_AllOnes())) {
793       X = CmpLHS;
794       Y = &MinSignedValue;
795       IsBitTest = true;
796       TrueWhenUnset = true;
797     }
798     if (IsBitTest) {
799       Value *V = nullptr;
800       // (X & Y) == 0 ? X : X ^ Y  --> X & ~Y
801       if (TrueWhenUnset && TrueVal == X &&
802           match(FalseVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
803         V = Builder.CreateAnd(X, ~(*Y));
804       // (X & Y) != 0 ? X ^ Y : X  --> X & ~Y
805       else if (!TrueWhenUnset && FalseVal == X &&
806                match(TrueVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
807         V = Builder.CreateAnd(X, ~(*Y));
808       // (X & Y) == 0 ? X ^ Y : X  --> X | Y
809       else if (TrueWhenUnset && FalseVal == X &&
810                match(TrueVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
811         V = Builder.CreateOr(X, *Y);
812       // (X & Y) != 0 ? X : X ^ Y  --> X | Y
813       else if (!TrueWhenUnset && TrueVal == X &&
814                match(FalseVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
815         V = Builder.CreateOr(X, *Y);
816 
817       if (V)
818         return replaceInstUsesWith(SI, V);
819     }
820   }
821 
822   if (Value *V = foldSelectICmpAndOr(SI, TrueVal, FalseVal, Builder))
823     return replaceInstUsesWith(SI, V);
824 
825   if (Value *V = foldSelectCttzCtlz(ICI, TrueVal, FalseVal, Builder))
826     return replaceInstUsesWith(SI, V);
827 
828   return Changed ? &SI : nullptr;
829 }
830 
831 
832 /// SI is a select whose condition is a PHI node (but the two may be in
833 /// different blocks). See if the true/false values (V) are live in all of the
834 /// predecessor blocks of the PHI. For example, cases like this can't be mapped:
835 ///
836 ///   X = phi [ C1, BB1], [C2, BB2]
837 ///   Y = add
838 ///   Z = select X, Y, 0
839 ///
840 /// because Y is not live in BB1/BB2.
841 ///
842 static bool canSelectOperandBeMappingIntoPredBlock(const Value *V,
843                                                    const SelectInst &SI) {
844   // If the value is a non-instruction value like a constant or argument, it
845   // can always be mapped.
846   const Instruction *I = dyn_cast<Instruction>(V);
847   if (!I) return true;
848 
849   // If V is a PHI node defined in the same block as the condition PHI, we can
850   // map the arguments.
851   const PHINode *CondPHI = cast<PHINode>(SI.getCondition());
852 
853   if (const PHINode *VP = dyn_cast<PHINode>(I))
854     if (VP->getParent() == CondPHI->getParent())
855       return true;
856 
857   // Otherwise, if the PHI and select are defined in the same block and if V is
858   // defined in a different block, then we can transform it.
859   if (SI.getParent() == CondPHI->getParent() &&
860       I->getParent() != CondPHI->getParent())
861     return true;
862 
863   // Otherwise we have a 'hard' case and we can't tell without doing more
864   // detailed dominator based analysis, punt.
865   return false;
866 }
867 
868 /// We have an SPF (e.g. a min or max) of an SPF of the form:
869 ///   SPF2(SPF1(A, B), C)
870 Instruction *InstCombiner::foldSPFofSPF(Instruction *Inner,
871                                         SelectPatternFlavor SPF1,
872                                         Value *A, Value *B,
873                                         Instruction &Outer,
874                                         SelectPatternFlavor SPF2, Value *C) {
875   if (Outer.getType() != Inner->getType())
876     return nullptr;
877 
878   if (C == A || C == B) {
879     // MAX(MAX(A, B), B) -> MAX(A, B)
880     // MIN(MIN(a, b), a) -> MIN(a, b)
881     if (SPF1 == SPF2)
882       return replaceInstUsesWith(Outer, Inner);
883 
884     // MAX(MIN(a, b), a) -> a
885     // MIN(MAX(a, b), a) -> a
886     if ((SPF1 == SPF_SMIN && SPF2 == SPF_SMAX) ||
887         (SPF1 == SPF_SMAX && SPF2 == SPF_SMIN) ||
888         (SPF1 == SPF_UMIN && SPF2 == SPF_UMAX) ||
889         (SPF1 == SPF_UMAX && SPF2 == SPF_UMIN))
890       return replaceInstUsesWith(Outer, C);
891   }
892 
893   if (SPF1 == SPF2) {
894     const APInt *CB, *CC;
895     if (match(B, m_APInt(CB)) && match(C, m_APInt(CC))) {
896       // MIN(MIN(A, 23), 97) -> MIN(A, 23)
897       // MAX(MAX(A, 97), 23) -> MAX(A, 97)
898       if ((SPF1 == SPF_UMIN && CB->ule(*CC)) ||
899           (SPF1 == SPF_SMIN && CB->sle(*CC)) ||
900           (SPF1 == SPF_UMAX && CB->uge(*CC)) ||
901           (SPF1 == SPF_SMAX && CB->sge(*CC)))
902         return replaceInstUsesWith(Outer, Inner);
903 
904       // MIN(MIN(A, 97), 23) -> MIN(A, 23)
905       // MAX(MAX(A, 23), 97) -> MAX(A, 97)
906       if ((SPF1 == SPF_UMIN && CB->ugt(*CC)) ||
907           (SPF1 == SPF_SMIN && CB->sgt(*CC)) ||
908           (SPF1 == SPF_UMAX && CB->ult(*CC)) ||
909           (SPF1 == SPF_SMAX && CB->slt(*CC))) {
910         Outer.replaceUsesOfWith(Inner, A);
911         return &Outer;
912       }
913     }
914   }
915 
916   // ABS(ABS(X)) -> ABS(X)
917   // NABS(NABS(X)) -> NABS(X)
918   if (SPF1 == SPF2 && (SPF1 == SPF_ABS || SPF1 == SPF_NABS)) {
919     return replaceInstUsesWith(Outer, Inner);
920   }
921 
922   // ABS(NABS(X)) -> ABS(X)
923   // NABS(ABS(X)) -> NABS(X)
924   if ((SPF1 == SPF_ABS && SPF2 == SPF_NABS) ||
925       (SPF1 == SPF_NABS && SPF2 == SPF_ABS)) {
926     SelectInst *SI = cast<SelectInst>(Inner);
927     Value *NewSI =
928         Builder.CreateSelect(SI->getCondition(), SI->getFalseValue(),
929                              SI->getTrueValue(), SI->getName(), SI);
930     return replaceInstUsesWith(Outer, NewSI);
931   }
932 
933   auto IsFreeOrProfitableToInvert =
934       [&](Value *V, Value *&NotV, bool &ElidesXor) {
935     if (match(V, m_Not(m_Value(NotV)))) {
936       // If V has at most 2 uses then we can get rid of the xor operation
937       // entirely.
938       ElidesXor |= !V->hasNUsesOrMore(3);
939       return true;
940     }
941 
942     if (IsFreeToInvert(V, !V->hasNUsesOrMore(3))) {
943       NotV = nullptr;
944       return true;
945     }
946 
947     return false;
948   };
949 
950   Value *NotA, *NotB, *NotC;
951   bool ElidesXor = false;
952 
953   // MIN(MIN(~A, ~B), ~C) == ~MAX(MAX(A, B), C)
954   // MIN(MAX(~A, ~B), ~C) == ~MAX(MIN(A, B), C)
955   // MAX(MIN(~A, ~B), ~C) == ~MIN(MAX(A, B), C)
956   // MAX(MAX(~A, ~B), ~C) == ~MIN(MIN(A, B), C)
957   //
958   // This transform is performance neutral if we can elide at least one xor from
959   // the set of three operands, since we'll be tacking on an xor at the very
960   // end.
961   if (SelectPatternResult::isMinOrMax(SPF1) &&
962       SelectPatternResult::isMinOrMax(SPF2) &&
963       IsFreeOrProfitableToInvert(A, NotA, ElidesXor) &&
964       IsFreeOrProfitableToInvert(B, NotB, ElidesXor) &&
965       IsFreeOrProfitableToInvert(C, NotC, ElidesXor) && ElidesXor) {
966     if (!NotA)
967       NotA = Builder.CreateNot(A);
968     if (!NotB)
969       NotB = Builder.CreateNot(B);
970     if (!NotC)
971       NotC = Builder.CreateNot(C);
972 
973     Value *NewInner = generateMinMaxSelectPattern(
974         Builder, getInverseMinMaxSelectPattern(SPF1), NotA, NotB);
975     Value *NewOuter = Builder.CreateNot(generateMinMaxSelectPattern(
976         Builder, getInverseMinMaxSelectPattern(SPF2), NewInner, NotC));
977     return replaceInstUsesWith(Outer, NewOuter);
978   }
979 
980   return nullptr;
981 }
982 
983 /// Turn select C, (X + Y), (X - Y) --> (X + (select C, Y, (-Y))).
984 /// This is even legal for FP.
985 static Instruction *foldAddSubSelect(SelectInst &SI,
986                                      InstCombiner::BuilderTy &Builder) {
987   Value *CondVal = SI.getCondition();
988   Value *TrueVal = SI.getTrueValue();
989   Value *FalseVal = SI.getFalseValue();
990   auto *TI = dyn_cast<Instruction>(TrueVal);
991   auto *FI = dyn_cast<Instruction>(FalseVal);
992   if (!TI || !FI || !TI->hasOneUse() || !FI->hasOneUse())
993     return nullptr;
994 
995   Instruction *AddOp = nullptr, *SubOp = nullptr;
996   if ((TI->getOpcode() == Instruction::Sub &&
997        FI->getOpcode() == Instruction::Add) ||
998       (TI->getOpcode() == Instruction::FSub &&
999        FI->getOpcode() == Instruction::FAdd)) {
1000     AddOp = FI;
1001     SubOp = TI;
1002   } else if ((FI->getOpcode() == Instruction::Sub &&
1003               TI->getOpcode() == Instruction::Add) ||
1004              (FI->getOpcode() == Instruction::FSub &&
1005               TI->getOpcode() == Instruction::FAdd)) {
1006     AddOp = TI;
1007     SubOp = FI;
1008   }
1009 
1010   if (AddOp) {
1011     Value *OtherAddOp = nullptr;
1012     if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
1013       OtherAddOp = AddOp->getOperand(1);
1014     } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
1015       OtherAddOp = AddOp->getOperand(0);
1016     }
1017 
1018     if (OtherAddOp) {
1019       // So at this point we know we have (Y -> OtherAddOp):
1020       //        select C, (add X, Y), (sub X, Z)
1021       Value *NegVal; // Compute -Z
1022       if (SI.getType()->isFPOrFPVectorTy()) {
1023         NegVal = Builder.CreateFNeg(SubOp->getOperand(1));
1024         if (Instruction *NegInst = dyn_cast<Instruction>(NegVal)) {
1025           FastMathFlags Flags = AddOp->getFastMathFlags();
1026           Flags &= SubOp->getFastMathFlags();
1027           NegInst->setFastMathFlags(Flags);
1028         }
1029       } else {
1030         NegVal = Builder.CreateNeg(SubOp->getOperand(1));
1031       }
1032 
1033       Value *NewTrueOp = OtherAddOp;
1034       Value *NewFalseOp = NegVal;
1035       if (AddOp != TI)
1036         std::swap(NewTrueOp, NewFalseOp);
1037       Value *NewSel = Builder.CreateSelect(CondVal, NewTrueOp, NewFalseOp,
1038                                            SI.getName() + ".p", &SI);
1039 
1040       if (SI.getType()->isFPOrFPVectorTy()) {
1041         Instruction *RI =
1042             BinaryOperator::CreateFAdd(SubOp->getOperand(0), NewSel);
1043 
1044         FastMathFlags Flags = AddOp->getFastMathFlags();
1045         Flags &= SubOp->getFastMathFlags();
1046         RI->setFastMathFlags(Flags);
1047         return RI;
1048       } else
1049         return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
1050     }
1051   }
1052   return nullptr;
1053 }
1054 
1055 Instruction *InstCombiner::foldSelectExtConst(SelectInst &Sel) {
1056   Instruction *ExtInst;
1057   if (!match(Sel.getTrueValue(), m_Instruction(ExtInst)) &&
1058       !match(Sel.getFalseValue(), m_Instruction(ExtInst)))
1059     return nullptr;
1060 
1061   auto ExtOpcode = ExtInst->getOpcode();
1062   if (ExtOpcode != Instruction::ZExt && ExtOpcode != Instruction::SExt)
1063     return nullptr;
1064 
1065   // TODO: Handle larger types? That requires adjusting FoldOpIntoSelect too.
1066   Value *X = ExtInst->getOperand(0);
1067   Type *SmallType = X->getType();
1068   if (!SmallType->isIntOrIntVectorTy(1))
1069     return nullptr;
1070 
1071   Constant *C;
1072   if (!match(Sel.getTrueValue(), m_Constant(C)) &&
1073       !match(Sel.getFalseValue(), m_Constant(C)))
1074     return nullptr;
1075 
1076   // If the constant is the same after truncation to the smaller type and
1077   // extension to the original type, we can narrow the select.
1078   Value *Cond = Sel.getCondition();
1079   Type *SelType = Sel.getType();
1080   Constant *TruncC = ConstantExpr::getTrunc(C, SmallType);
1081   Constant *ExtC = ConstantExpr::getCast(ExtOpcode, TruncC, SelType);
1082   if (ExtC == C) {
1083     Value *TruncCVal = cast<Value>(TruncC);
1084     if (ExtInst == Sel.getFalseValue())
1085       std::swap(X, TruncCVal);
1086 
1087     // select Cond, (ext X), C --> ext(select Cond, X, C')
1088     // select Cond, C, (ext X) --> ext(select Cond, C', X)
1089     Value *NewSel = Builder.CreateSelect(Cond, X, TruncCVal, "narrow", &Sel);
1090     return CastInst::Create(Instruction::CastOps(ExtOpcode), NewSel, SelType);
1091   }
1092 
1093   // If one arm of the select is the extend of the condition, replace that arm
1094   // with the extension of the appropriate known bool value.
1095   if (Cond == X) {
1096     if (ExtInst == Sel.getTrueValue()) {
1097       // select X, (sext X), C --> select X, -1, C
1098       // select X, (zext X), C --> select X,  1, C
1099       Constant *One = ConstantInt::getTrue(SmallType);
1100       Constant *AllOnesOrOne = ConstantExpr::getCast(ExtOpcode, One, SelType);
1101       return SelectInst::Create(Cond, AllOnesOrOne, C, "", nullptr, &Sel);
1102     } else {
1103       // select X, C, (sext X) --> select X, C, 0
1104       // select X, C, (zext X) --> select X, C, 0
1105       Constant *Zero = ConstantInt::getNullValue(SelType);
1106       return SelectInst::Create(Cond, C, Zero, "", nullptr, &Sel);
1107     }
1108   }
1109 
1110   return nullptr;
1111 }
1112 
1113 /// Try to transform a vector select with a constant condition vector into a
1114 /// shuffle for easier combining with other shuffles and insert/extract.
1115 static Instruction *canonicalizeSelectToShuffle(SelectInst &SI) {
1116   Value *CondVal = SI.getCondition();
1117   Constant *CondC;
1118   if (!CondVal->getType()->isVectorTy() || !match(CondVal, m_Constant(CondC)))
1119     return nullptr;
1120 
1121   unsigned NumElts = CondVal->getType()->getVectorNumElements();
1122   SmallVector<Constant *, 16> Mask;
1123   Mask.reserve(NumElts);
1124   Type *Int32Ty = Type::getInt32Ty(CondVal->getContext());
1125   for (unsigned i = 0; i != NumElts; ++i) {
1126     Constant *Elt = CondC->getAggregateElement(i);
1127     if (!Elt)
1128       return nullptr;
1129 
1130     if (Elt->isOneValue()) {
1131       // If the select condition element is true, choose from the 1st vector.
1132       Mask.push_back(ConstantInt::get(Int32Ty, i));
1133     } else if (Elt->isNullValue()) {
1134       // If the select condition element is false, choose from the 2nd vector.
1135       Mask.push_back(ConstantInt::get(Int32Ty, i + NumElts));
1136     } else if (isa<UndefValue>(Elt)) {
1137       // Undef in a select condition (choose one of the operands) does not mean
1138       // the same thing as undef in a shuffle mask (any value is acceptable), so
1139       // give up.
1140       return nullptr;
1141     } else {
1142       // Bail out on a constant expression.
1143       return nullptr;
1144     }
1145   }
1146 
1147   return new ShuffleVectorInst(SI.getTrueValue(), SI.getFalseValue(),
1148                                ConstantVector::get(Mask));
1149 }
1150 
1151 /// Reuse bitcasted operands between a compare and select:
1152 /// select (cmp (bitcast C), (bitcast D)), (bitcast' C), (bitcast' D) -->
1153 /// bitcast (select (cmp (bitcast C), (bitcast D)), (bitcast C), (bitcast D))
1154 static Instruction *foldSelectCmpBitcasts(SelectInst &Sel,
1155                                           InstCombiner::BuilderTy &Builder) {
1156   Value *Cond = Sel.getCondition();
1157   Value *TVal = Sel.getTrueValue();
1158   Value *FVal = Sel.getFalseValue();
1159 
1160   CmpInst::Predicate Pred;
1161   Value *A, *B;
1162   if (!match(Cond, m_Cmp(Pred, m_Value(A), m_Value(B))))
1163     return nullptr;
1164 
1165   // The select condition is a compare instruction. If the select's true/false
1166   // values are already the same as the compare operands, there's nothing to do.
1167   if (TVal == A || TVal == B || FVal == A || FVal == B)
1168     return nullptr;
1169 
1170   Value *C, *D;
1171   if (!match(A, m_BitCast(m_Value(C))) || !match(B, m_BitCast(m_Value(D))))
1172     return nullptr;
1173 
1174   // select (cmp (bitcast C), (bitcast D)), (bitcast TSrc), (bitcast FSrc)
1175   Value *TSrc, *FSrc;
1176   if (!match(TVal, m_BitCast(m_Value(TSrc))) ||
1177       !match(FVal, m_BitCast(m_Value(FSrc))))
1178     return nullptr;
1179 
1180   // If the select true/false values are *different bitcasts* of the same source
1181   // operands, make the select operands the same as the compare operands and
1182   // cast the result. This is the canonical select form for min/max.
1183   Value *NewSel;
1184   if (TSrc == C && FSrc == D) {
1185     // select (cmp (bitcast C), (bitcast D)), (bitcast' C), (bitcast' D) -->
1186     // bitcast (select (cmp A, B), A, B)
1187     NewSel = Builder.CreateSelect(Cond, A, B, "", &Sel);
1188   } else if (TSrc == D && FSrc == C) {
1189     // select (cmp (bitcast C), (bitcast D)), (bitcast' D), (bitcast' C) -->
1190     // bitcast (select (cmp A, B), B, A)
1191     NewSel = Builder.CreateSelect(Cond, B, A, "", &Sel);
1192   } else {
1193     return nullptr;
1194   }
1195   return CastInst::CreateBitOrPointerCast(NewSel, Sel.getType());
1196 }
1197 
1198 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
1199   Value *CondVal = SI.getCondition();
1200   Value *TrueVal = SI.getTrueValue();
1201   Value *FalseVal = SI.getFalseValue();
1202   Type *SelType = SI.getType();
1203 
1204   // FIXME: Remove this workaround when freeze related patches are done.
1205   // For select with undef operand which feeds into an equality comparison,
1206   // don't simplify it so loop unswitch can know the equality comparison
1207   // may have an undef operand. This is a workaround for PR31652 caused by
1208   // descrepancy about branch on undef between LoopUnswitch and GVN.
1209   if (isa<UndefValue>(TrueVal) || isa<UndefValue>(FalseVal)) {
1210     if (any_of(SI.users(), [&](User *U) {
1211           ICmpInst *CI = dyn_cast<ICmpInst>(U);
1212           if (CI && CI->isEquality())
1213             return true;
1214           return false;
1215         })) {
1216       return nullptr;
1217     }
1218   }
1219 
1220   if (Value *V = SimplifySelectInst(CondVal, TrueVal, FalseVal,
1221                                     SQ.getWithInstruction(&SI)))
1222     return replaceInstUsesWith(SI, V);
1223 
1224   if (Instruction *I = canonicalizeSelectToShuffle(SI))
1225     return I;
1226 
1227   // Canonicalize a one-use integer compare with a non-canonical predicate by
1228   // inverting the predicate and swapping the select operands. This matches a
1229   // compare canonicalization for conditional branches.
1230   // TODO: Should we do the same for FP compares?
1231   CmpInst::Predicate Pred;
1232   if (match(CondVal, m_OneUse(m_ICmp(Pred, m_Value(), m_Value()))) &&
1233       !isCanonicalPredicate(Pred)) {
1234     // Swap true/false values and condition.
1235     CmpInst *Cond = cast<CmpInst>(CondVal);
1236     Cond->setPredicate(CmpInst::getInversePredicate(Pred));
1237     SI.setOperand(1, FalseVal);
1238     SI.setOperand(2, TrueVal);
1239     SI.swapProfMetadata();
1240     Worklist.Add(Cond);
1241     return &SI;
1242   }
1243 
1244   if (SelType->isIntOrIntVectorTy(1) &&
1245       TrueVal->getType() == CondVal->getType()) {
1246     if (match(TrueVal, m_One())) {
1247       // Change: A = select B, true, C --> A = or B, C
1248       return BinaryOperator::CreateOr(CondVal, FalseVal);
1249     }
1250     if (match(TrueVal, m_Zero())) {
1251       // Change: A = select B, false, C --> A = and !B, C
1252       Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName());
1253       return BinaryOperator::CreateAnd(NotCond, FalseVal);
1254     }
1255     if (match(FalseVal, m_Zero())) {
1256       // Change: A = select B, C, false --> A = and B, C
1257       return BinaryOperator::CreateAnd(CondVal, TrueVal);
1258     }
1259     if (match(FalseVal, m_One())) {
1260       // Change: A = select B, C, true --> A = or !B, C
1261       Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName());
1262       return BinaryOperator::CreateOr(NotCond, TrueVal);
1263     }
1264 
1265     // select a, a, b  -> a | b
1266     // select a, b, a  -> a & b
1267     if (CondVal == TrueVal)
1268       return BinaryOperator::CreateOr(CondVal, FalseVal);
1269     if (CondVal == FalseVal)
1270       return BinaryOperator::CreateAnd(CondVal, TrueVal);
1271 
1272     // select a, ~a, b -> (~a) & b
1273     // select a, b, ~a -> (~a) | b
1274     if (match(TrueVal, m_Not(m_Specific(CondVal))))
1275       return BinaryOperator::CreateAnd(TrueVal, FalseVal);
1276     if (match(FalseVal, m_Not(m_Specific(CondVal))))
1277       return BinaryOperator::CreateOr(TrueVal, FalseVal);
1278   }
1279 
1280   // Selecting between two integer or vector splat integer constants?
1281   //
1282   // Note that we don't handle a scalar select of vectors:
1283   // select i1 %c, <2 x i8> <1, 1>, <2 x i8> <0, 0>
1284   // because that may need 3 instructions to splat the condition value:
1285   // extend, insertelement, shufflevector.
1286   if (SelType->isIntOrIntVectorTy() &&
1287       CondVal->getType()->isVectorTy() == SelType->isVectorTy()) {
1288     // select C, 1, 0 -> zext C to int
1289     if (match(TrueVal, m_One()) && match(FalseVal, m_Zero()))
1290       return new ZExtInst(CondVal, SelType);
1291 
1292     // select C, -1, 0 -> sext C to int
1293     if (match(TrueVal, m_AllOnes()) && match(FalseVal, m_Zero()))
1294       return new SExtInst(CondVal, SelType);
1295 
1296     // select C, 0, 1 -> zext !C to int
1297     if (match(TrueVal, m_Zero()) && match(FalseVal, m_One())) {
1298       Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName());
1299       return new ZExtInst(NotCond, SelType);
1300     }
1301 
1302     // select C, 0, -1 -> sext !C to int
1303     if (match(TrueVal, m_Zero()) && match(FalseVal, m_AllOnes())) {
1304       Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName());
1305       return new SExtInst(NotCond, SelType);
1306     }
1307   }
1308 
1309   // See if we are selecting two values based on a comparison of the two values.
1310   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
1311     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
1312       // Transform (X == Y) ? X : Y  -> Y
1313       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
1314         // This is not safe in general for floating point:
1315         // consider X== -0, Y== +0.
1316         // It becomes safe if either operand is a nonzero constant.
1317         ConstantFP *CFPt, *CFPf;
1318         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
1319               !CFPt->getValueAPF().isZero()) ||
1320             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
1321              !CFPf->getValueAPF().isZero()))
1322         return replaceInstUsesWith(SI, FalseVal);
1323       }
1324       // Transform (X une Y) ? X : Y  -> X
1325       if (FCI->getPredicate() == FCmpInst::FCMP_UNE) {
1326         // This is not safe in general for floating point:
1327         // consider X== -0, Y== +0.
1328         // It becomes safe if either operand is a nonzero constant.
1329         ConstantFP *CFPt, *CFPf;
1330         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
1331               !CFPt->getValueAPF().isZero()) ||
1332             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
1333              !CFPf->getValueAPF().isZero()))
1334         return replaceInstUsesWith(SI, TrueVal);
1335       }
1336 
1337       // Canonicalize to use ordered comparisons by swapping the select
1338       // operands.
1339       //
1340       // e.g.
1341       // (X ugt Y) ? X : Y -> (X ole Y) ? Y : X
1342       if (FCI->hasOneUse() && FCmpInst::isUnordered(FCI->getPredicate())) {
1343         FCmpInst::Predicate InvPred = FCI->getInversePredicate();
1344         IRBuilder<>::FastMathFlagGuard FMFG(Builder);
1345         Builder.setFastMathFlags(FCI->getFastMathFlags());
1346         Value *NewCond = Builder.CreateFCmp(InvPred, TrueVal, FalseVal,
1347                                             FCI->getName() + ".inv");
1348 
1349         return SelectInst::Create(NewCond, FalseVal, TrueVal,
1350                                   SI.getName() + ".p");
1351       }
1352 
1353       // NOTE: if we wanted to, this is where to detect MIN/MAX
1354     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
1355       // Transform (X == Y) ? Y : X  -> X
1356       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
1357         // This is not safe in general for floating point:
1358         // consider X== -0, Y== +0.
1359         // It becomes safe if either operand is a nonzero constant.
1360         ConstantFP *CFPt, *CFPf;
1361         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
1362               !CFPt->getValueAPF().isZero()) ||
1363             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
1364              !CFPf->getValueAPF().isZero()))
1365           return replaceInstUsesWith(SI, FalseVal);
1366       }
1367       // Transform (X une Y) ? Y : X  -> Y
1368       if (FCI->getPredicate() == FCmpInst::FCMP_UNE) {
1369         // This is not safe in general for floating point:
1370         // consider X== -0, Y== +0.
1371         // It becomes safe if either operand is a nonzero constant.
1372         ConstantFP *CFPt, *CFPf;
1373         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
1374               !CFPt->getValueAPF().isZero()) ||
1375             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
1376              !CFPf->getValueAPF().isZero()))
1377           return replaceInstUsesWith(SI, TrueVal);
1378       }
1379 
1380       // Canonicalize to use ordered comparisons by swapping the select
1381       // operands.
1382       //
1383       // e.g.
1384       // (X ugt Y) ? X : Y -> (X ole Y) ? X : Y
1385       if (FCI->hasOneUse() && FCmpInst::isUnordered(FCI->getPredicate())) {
1386         FCmpInst::Predicate InvPred = FCI->getInversePredicate();
1387         IRBuilder<>::FastMathFlagGuard FMFG(Builder);
1388         Builder.setFastMathFlags(FCI->getFastMathFlags());
1389         Value *NewCond = Builder.CreateFCmp(InvPred, FalseVal, TrueVal,
1390                                             FCI->getName() + ".inv");
1391 
1392         return SelectInst::Create(NewCond, FalseVal, TrueVal,
1393                                   SI.getName() + ".p");
1394       }
1395 
1396       // NOTE: if we wanted to, this is where to detect MIN/MAX
1397     }
1398     // NOTE: if we wanted to, this is where to detect ABS
1399   }
1400 
1401   // See if we are selecting two values based on a comparison of the two values.
1402   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
1403     if (Instruction *Result = foldSelectInstWithICmp(SI, ICI))
1404       return Result;
1405 
1406   if (Instruction *Add = foldAddSubSelect(SI, Builder))
1407     return Add;
1408 
1409   // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
1410   auto *TI = dyn_cast<Instruction>(TrueVal);
1411   auto *FI = dyn_cast<Instruction>(FalseVal);
1412   if (TI && FI && TI->getOpcode() == FI->getOpcode())
1413     if (Instruction *IV = foldSelectOpOp(SI, TI, FI))
1414       return IV;
1415 
1416   if (Instruction *I = foldSelectExtConst(SI))
1417     return I;
1418 
1419   // See if we can fold the select into one of our operands.
1420   if (SelType->isIntOrIntVectorTy() || SelType->isFPOrFPVectorTy()) {
1421     if (Instruction *FoldI = foldSelectIntoOp(SI, TrueVal, FalseVal))
1422       return FoldI;
1423 
1424     Value *LHS, *RHS, *LHS2, *RHS2;
1425     Instruction::CastOps CastOp;
1426     SelectPatternResult SPR = matchSelectPattern(&SI, LHS, RHS, &CastOp);
1427     auto SPF = SPR.Flavor;
1428 
1429     if (SelectPatternResult::isMinOrMax(SPF)) {
1430       // Canonicalize so that
1431       // - type casts are outside select patterns.
1432       // - float clamp is transformed to min/max pattern
1433 
1434       bool IsCastNeeded = LHS->getType() != SelType;
1435       Value *CmpLHS = cast<CmpInst>(CondVal)->getOperand(0);
1436       Value *CmpRHS = cast<CmpInst>(CondVal)->getOperand(1);
1437       if (IsCastNeeded ||
1438           (LHS->getType()->isFPOrFPVectorTy() &&
1439            ((CmpLHS != LHS && CmpLHS != RHS) ||
1440             (CmpRHS != LHS && CmpRHS != RHS)))) {
1441         CmpInst::Predicate Pred = getCmpPredicateForMinMax(SPF, SPR.Ordered);
1442 
1443         Value *Cmp;
1444         if (CmpInst::isIntPredicate(Pred)) {
1445           Cmp = Builder.CreateICmp(Pred, LHS, RHS);
1446         } else {
1447           IRBuilder<>::FastMathFlagGuard FMFG(Builder);
1448           auto FMF = cast<FPMathOperator>(SI.getCondition())->getFastMathFlags();
1449           Builder.setFastMathFlags(FMF);
1450           Cmp = Builder.CreateFCmp(Pred, LHS, RHS);
1451         }
1452 
1453         Value *NewSI = Builder.CreateSelect(Cmp, LHS, RHS, SI.getName(), &SI);
1454         if (!IsCastNeeded)
1455           return replaceInstUsesWith(SI, NewSI);
1456 
1457         Value *NewCast = Builder.CreateCast(CastOp, NewSI, SelType);
1458         return replaceInstUsesWith(SI, NewCast);
1459       }
1460     }
1461 
1462     if (SPF) {
1463       // MAX(MAX(a, b), a) -> MAX(a, b)
1464       // MIN(MIN(a, b), a) -> MIN(a, b)
1465       // MAX(MIN(a, b), a) -> a
1466       // MIN(MAX(a, b), a) -> a
1467       // ABS(ABS(a)) -> ABS(a)
1468       // NABS(NABS(a)) -> NABS(a)
1469       if (SelectPatternFlavor SPF2 = matchSelectPattern(LHS, LHS2, RHS2).Flavor)
1470         if (Instruction *R = foldSPFofSPF(cast<Instruction>(LHS),SPF2,LHS2,RHS2,
1471                                           SI, SPF, RHS))
1472           return R;
1473       if (SelectPatternFlavor SPF2 = matchSelectPattern(RHS, LHS2, RHS2).Flavor)
1474         if (Instruction *R = foldSPFofSPF(cast<Instruction>(RHS),SPF2,LHS2,RHS2,
1475                                           SI, SPF, LHS))
1476           return R;
1477     }
1478 
1479     // MAX(~a, ~b) -> ~MIN(a, b)
1480     if ((SPF == SPF_SMAX || SPF == SPF_UMAX) &&
1481         IsFreeToInvert(LHS, LHS->hasNUses(2)) &&
1482         IsFreeToInvert(RHS, RHS->hasNUses(2))) {
1483       // For this transform to be profitable, we need to eliminate at least two
1484       // 'not' instructions if we're going to add one 'not' instruction.
1485       int NumberOfNots =
1486           (LHS->hasNUses(2) && match(LHS, m_Not(m_Value()))) +
1487           (RHS->hasNUses(2) && match(RHS, m_Not(m_Value()))) +
1488           (SI.hasOneUse() && match(*SI.user_begin(), m_Not(m_Value())));
1489 
1490       if (NumberOfNots >= 2) {
1491         Value *NewLHS = Builder.CreateNot(LHS);
1492         Value *NewRHS = Builder.CreateNot(RHS);
1493         Value *NewCmp = SPF == SPF_SMAX ? Builder.CreateICmpSLT(NewLHS, NewRHS)
1494                                         : Builder.CreateICmpULT(NewLHS, NewRHS);
1495         Value *NewSI =
1496             Builder.CreateNot(Builder.CreateSelect(NewCmp, NewLHS, NewRHS));
1497         return replaceInstUsesWith(SI, NewSI);
1498       }
1499     }
1500 
1501     // TODO.
1502     // ABS(-X) -> ABS(X)
1503   }
1504 
1505   // See if we can fold the select into a phi node if the condition is a select.
1506   if (auto *PN = dyn_cast<PHINode>(SI.getCondition()))
1507     // The true/false values have to be live in the PHI predecessor's blocks.
1508     if (canSelectOperandBeMappingIntoPredBlock(TrueVal, SI) &&
1509         canSelectOperandBeMappingIntoPredBlock(FalseVal, SI))
1510       if (Instruction *NV = foldOpIntoPhi(SI, PN))
1511         return NV;
1512 
1513   if (SelectInst *TrueSI = dyn_cast<SelectInst>(TrueVal)) {
1514     if (TrueSI->getCondition()->getType() == CondVal->getType()) {
1515       // select(C, select(C, a, b), c) -> select(C, a, c)
1516       if (TrueSI->getCondition() == CondVal) {
1517         if (SI.getTrueValue() == TrueSI->getTrueValue())
1518           return nullptr;
1519         SI.setOperand(1, TrueSI->getTrueValue());
1520         return &SI;
1521       }
1522       // select(C0, select(C1, a, b), b) -> select(C0&C1, a, b)
1523       // We choose this as normal form to enable folding on the And and shortening
1524       // paths for the values (this helps GetUnderlyingObjects() for example).
1525       if (TrueSI->getFalseValue() == FalseVal && TrueSI->hasOneUse()) {
1526         Value *And = Builder.CreateAnd(CondVal, TrueSI->getCondition());
1527         SI.setOperand(0, And);
1528         SI.setOperand(1, TrueSI->getTrueValue());
1529         return &SI;
1530       }
1531     }
1532   }
1533   if (SelectInst *FalseSI = dyn_cast<SelectInst>(FalseVal)) {
1534     if (FalseSI->getCondition()->getType() == CondVal->getType()) {
1535       // select(C, a, select(C, b, c)) -> select(C, a, c)
1536       if (FalseSI->getCondition() == CondVal) {
1537         if (SI.getFalseValue() == FalseSI->getFalseValue())
1538           return nullptr;
1539         SI.setOperand(2, FalseSI->getFalseValue());
1540         return &SI;
1541       }
1542       // select(C0, a, select(C1, a, b)) -> select(C0|C1, a, b)
1543       if (FalseSI->getTrueValue() == TrueVal && FalseSI->hasOneUse()) {
1544         Value *Or = Builder.CreateOr(CondVal, FalseSI->getCondition());
1545         SI.setOperand(0, Or);
1546         SI.setOperand(2, FalseSI->getFalseValue());
1547         return &SI;
1548       }
1549     }
1550   }
1551 
1552   if (BinaryOperator::isNot(CondVal)) {
1553     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
1554     SI.setOperand(1, FalseVal);
1555     SI.setOperand(2, TrueVal);
1556     return &SI;
1557   }
1558 
1559   if (VectorType *VecTy = dyn_cast<VectorType>(SelType)) {
1560     unsigned VWidth = VecTy->getNumElements();
1561     APInt UndefElts(VWidth, 0);
1562     APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
1563     if (Value *V = SimplifyDemandedVectorElts(&SI, AllOnesEltMask, UndefElts)) {
1564       if (V != &SI)
1565         return replaceInstUsesWith(SI, V);
1566       return &SI;
1567     }
1568 
1569     if (isa<ConstantAggregateZero>(CondVal)) {
1570       return replaceInstUsesWith(SI, FalseVal);
1571     }
1572   }
1573 
1574   // See if we can determine the result of this select based on a dominating
1575   // condition.
1576   BasicBlock *Parent = SI.getParent();
1577   if (BasicBlock *Dom = Parent->getSinglePredecessor()) {
1578     auto *PBI = dyn_cast_or_null<BranchInst>(Dom->getTerminator());
1579     if (PBI && PBI->isConditional() &&
1580         PBI->getSuccessor(0) != PBI->getSuccessor(1) &&
1581         (PBI->getSuccessor(0) == Parent || PBI->getSuccessor(1) == Parent)) {
1582       bool CondIsTrue = PBI->getSuccessor(0) == Parent;
1583       Optional<bool> Implication = isImpliedCondition(
1584           PBI->getCondition(), SI.getCondition(), DL, CondIsTrue);
1585       if (Implication) {
1586         Value *V = *Implication ? TrueVal : FalseVal;
1587         return replaceInstUsesWith(SI, V);
1588       }
1589     }
1590   }
1591 
1592   // If we can compute the condition, there's no need for a select.
1593   // Like the above fold, we are attempting to reduce compile-time cost by
1594   // putting this fold here with limitations rather than in InstSimplify.
1595   // The motivation for this call into value tracking is to take advantage of
1596   // the assumption cache, so make sure that is populated.
1597   if (!CondVal->getType()->isVectorTy() && !AC.assumptions().empty()) {
1598     KnownBits Known(1);
1599     computeKnownBits(CondVal, Known, 0, &SI);
1600     if (Known.One.isOneValue())
1601       return replaceInstUsesWith(SI, TrueVal);
1602     if (Known.Zero.isOneValue())
1603       return replaceInstUsesWith(SI, FalseVal);
1604   }
1605 
1606   if (Instruction *BitCastSel = foldSelectCmpBitcasts(SI, Builder))
1607     return BitCastSel;
1608 
1609   return nullptr;
1610 }
1611