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