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