1 //===- InstCombineSelect.cpp ----------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the visitSelect function.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "InstCombineInternal.h"
14 #include "llvm/ADT/APInt.h"
15 #include "llvm/ADT/Optional.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/Analysis/AssumptionCache.h"
19 #include "llvm/Analysis/CmpInstAnalysis.h"
20 #include "llvm/Analysis/InstructionSimplify.h"
21 #include "llvm/Analysis/ValueTracking.h"
22 #include "llvm/IR/BasicBlock.h"
23 #include "llvm/IR/Constant.h"
24 #include "llvm/IR/Constants.h"
25 #include "llvm/IR/DerivedTypes.h"
26 #include "llvm/IR/IRBuilder.h"
27 #include "llvm/IR/InstrTypes.h"
28 #include "llvm/IR/Instruction.h"
29 #include "llvm/IR/Instructions.h"
30 #include "llvm/IR/IntrinsicInst.h"
31 #include "llvm/IR/Intrinsics.h"
32 #include "llvm/IR/Operator.h"
33 #include "llvm/IR/PatternMatch.h"
34 #include "llvm/IR/Type.h"
35 #include "llvm/IR/User.h"
36 #include "llvm/IR/Value.h"
37 #include "llvm/Support/Casting.h"
38 #include "llvm/Support/ErrorHandling.h"
39 #include "llvm/Support/KnownBits.h"
40 #include "llvm/Transforms/InstCombine/InstCombineWorklist.h"
41 #include <cassert>
42 #include <utility>
43 
44 using namespace llvm;
45 using namespace PatternMatch;
46 
47 #define DEBUG_TYPE "instcombine"
48 
createMinMax(InstCombiner::BuilderTy & Builder,SelectPatternFlavor SPF,Value * A,Value * B)49 static Value *createMinMax(InstCombiner::BuilderTy &Builder,
50                            SelectPatternFlavor SPF, Value *A, Value *B) {
51   CmpInst::Predicate Pred = getMinMaxPred(SPF);
52   assert(CmpInst::isIntPredicate(Pred) && "Expected integer predicate");
53   return Builder.CreateSelect(Builder.CreateICmp(Pred, A, B), A, B);
54 }
55 
56 /// Replace a select operand based on an equality comparison with the identity
57 /// constant of a binop.
foldSelectBinOpIdentity(SelectInst & Sel,const TargetLibraryInfo & TLI,InstCombiner & IC)58 static Instruction *foldSelectBinOpIdentity(SelectInst &Sel,
59                                             const TargetLibraryInfo &TLI,
60                                             InstCombiner &IC) {
61   // The select condition must be an equality compare with a constant operand.
62   Value *X;
63   Constant *C;
64   CmpInst::Predicate Pred;
65   if (!match(Sel.getCondition(), m_Cmp(Pred, m_Value(X), m_Constant(C))))
66     return nullptr;
67 
68   bool IsEq;
69   if (ICmpInst::isEquality(Pred))
70     IsEq = Pred == ICmpInst::ICMP_EQ;
71   else if (Pred == FCmpInst::FCMP_OEQ)
72     IsEq = true;
73   else if (Pred == FCmpInst::FCMP_UNE)
74     IsEq = false;
75   else
76     return nullptr;
77 
78   // A select operand must be a binop.
79   BinaryOperator *BO;
80   if (!match(Sel.getOperand(IsEq ? 1 : 2), m_BinOp(BO)))
81     return nullptr;
82 
83   // The compare constant must be the identity constant for that binop.
84   // If this a floating-point compare with 0.0, any zero constant will do.
85   Type *Ty = BO->getType();
86   Constant *IdC = ConstantExpr::getBinOpIdentity(BO->getOpcode(), Ty, true);
87   if (IdC != C) {
88     if (!IdC || !CmpInst::isFPPredicate(Pred))
89       return nullptr;
90     if (!match(IdC, m_AnyZeroFP()) || !match(C, m_AnyZeroFP()))
91       return nullptr;
92   }
93 
94   // Last, match the compare variable operand with a binop operand.
95   Value *Y;
96   if (!BO->isCommutative() && !match(BO, m_BinOp(m_Value(Y), m_Specific(X))))
97     return nullptr;
98   if (!match(BO, m_c_BinOp(m_Value(Y), m_Specific(X))))
99     return nullptr;
100 
101   // +0.0 compares equal to -0.0, and so it does not behave as required for this
102   // transform. Bail out if we can not exclude that possibility.
103   if (isa<FPMathOperator>(BO))
104     if (!BO->hasNoSignedZeros() && !CannotBeNegativeZero(Y, &TLI))
105       return nullptr;
106 
107   // BO = binop Y, X
108   // S = { select (cmp eq X, C), BO, ? } or { select (cmp ne X, C), ?, BO }
109   // =>
110   // S = { select (cmp eq X, C),  Y, ? } or { select (cmp ne X, C), ?,  Y }
111   return IC.replaceOperand(Sel, IsEq ? 1 : 2, Y);
112 }
113 
114 /// This folds:
115 ///  select (icmp eq (and X, C1)), TC, FC
116 ///    iff C1 is a power 2 and the difference between TC and FC is a power-of-2.
117 /// To something like:
118 ///  (shr (and (X, C1)), (log2(C1) - log2(TC-FC))) + FC
119 /// Or:
120 ///  (shl (and (X, C1)), (log2(TC-FC) - log2(C1))) + FC
121 /// With some variations depending if FC is larger than TC, or the shift
122 /// isn't needed, or the bit widths don't match.
foldSelectICmpAnd(SelectInst & Sel,ICmpInst * Cmp,InstCombiner::BuilderTy & Builder)123 static Value *foldSelectICmpAnd(SelectInst &Sel, ICmpInst *Cmp,
124                                 InstCombiner::BuilderTy &Builder) {
125   const APInt *SelTC, *SelFC;
126   if (!match(Sel.getTrueValue(), m_APInt(SelTC)) ||
127       !match(Sel.getFalseValue(), m_APInt(SelFC)))
128     return nullptr;
129 
130   // If this is a vector select, we need a vector compare.
131   Type *SelType = Sel.getType();
132   if (SelType->isVectorTy() != Cmp->getType()->isVectorTy())
133     return nullptr;
134 
135   Value *V;
136   APInt AndMask;
137   bool CreateAnd = false;
138   ICmpInst::Predicate Pred = Cmp->getPredicate();
139   if (ICmpInst::isEquality(Pred)) {
140     if (!match(Cmp->getOperand(1), m_Zero()))
141       return nullptr;
142 
143     V = Cmp->getOperand(0);
144     const APInt *AndRHS;
145     if (!match(V, m_And(m_Value(), m_Power2(AndRHS))))
146       return nullptr;
147 
148     AndMask = *AndRHS;
149   } else if (decomposeBitTestICmp(Cmp->getOperand(0), Cmp->getOperand(1),
150                                   Pred, V, AndMask)) {
151     assert(ICmpInst::isEquality(Pred) && "Not equality test?");
152     if (!AndMask.isPowerOf2())
153       return nullptr;
154 
155     CreateAnd = true;
156   } else {
157     return nullptr;
158   }
159 
160   // In general, when both constants are non-zero, we would need an offset to
161   // replace the select. This would require more instructions than we started
162   // with. But there's one special-case that we handle here because it can
163   // simplify/reduce the instructions.
164   APInt TC = *SelTC;
165   APInt FC = *SelFC;
166   if (!TC.isNullValue() && !FC.isNullValue()) {
167     // If the select constants differ by exactly one bit and that's the same
168     // bit that is masked and checked by the select condition, the select can
169     // be replaced by bitwise logic to set/clear one bit of the constant result.
170     if (TC.getBitWidth() != AndMask.getBitWidth() || (TC ^ FC) != AndMask)
171       return nullptr;
172     if (CreateAnd) {
173       // If we have to create an 'and', then we must kill the cmp to not
174       // increase the instruction count.
175       if (!Cmp->hasOneUse())
176         return nullptr;
177       V = Builder.CreateAnd(V, ConstantInt::get(SelType, AndMask));
178     }
179     bool ExtraBitInTC = TC.ugt(FC);
180     if (Pred == ICmpInst::ICMP_EQ) {
181       // If the masked bit in V is clear, clear or set the bit in the result:
182       // (V & AndMaskC) == 0 ? TC : FC --> (V & AndMaskC) ^ TC
183       // (V & AndMaskC) == 0 ? TC : FC --> (V & AndMaskC) | TC
184       Constant *C = ConstantInt::get(SelType, TC);
185       return ExtraBitInTC ? Builder.CreateXor(V, C) : Builder.CreateOr(V, C);
186     }
187     if (Pred == ICmpInst::ICMP_NE) {
188       // If the masked bit in V is set, set or clear the bit in the result:
189       // (V & AndMaskC) != 0 ? TC : FC --> (V & AndMaskC) | FC
190       // (V & AndMaskC) != 0 ? TC : FC --> (V & AndMaskC) ^ FC
191       Constant *C = ConstantInt::get(SelType, FC);
192       return ExtraBitInTC ? Builder.CreateOr(V, C) : Builder.CreateXor(V, C);
193     }
194     llvm_unreachable("Only expecting equality predicates");
195   }
196 
197   // Make sure one of the select arms is a power-of-2.
198   if (!TC.isPowerOf2() && !FC.isPowerOf2())
199     return nullptr;
200 
201   // Determine which shift is needed to transform result of the 'and' into the
202   // desired result.
203   const APInt &ValC = !TC.isNullValue() ? TC : FC;
204   unsigned ValZeros = ValC.logBase2();
205   unsigned AndZeros = AndMask.logBase2();
206 
207   // Insert the 'and' instruction on the input to the truncate.
208   if (CreateAnd)
209     V = Builder.CreateAnd(V, ConstantInt::get(V->getType(), AndMask));
210 
211   // If types don't match, we can still convert the select by introducing a zext
212   // or a trunc of the 'and'.
213   if (ValZeros > AndZeros) {
214     V = Builder.CreateZExtOrTrunc(V, SelType);
215     V = Builder.CreateShl(V, ValZeros - AndZeros);
216   } else if (ValZeros < AndZeros) {
217     V = Builder.CreateLShr(V, AndZeros - ValZeros);
218     V = Builder.CreateZExtOrTrunc(V, SelType);
219   } else {
220     V = Builder.CreateZExtOrTrunc(V, SelType);
221   }
222 
223   // Okay, now we know that everything is set up, we just don't know whether we
224   // have a icmp_ne or icmp_eq and whether the true or false val is the zero.
225   bool ShouldNotVal = !TC.isNullValue();
226   ShouldNotVal ^= Pred == ICmpInst::ICMP_NE;
227   if (ShouldNotVal)
228     V = Builder.CreateXor(V, ValC);
229 
230   return V;
231 }
232 
233 /// We want to turn code that looks like this:
234 ///   %C = or %A, %B
235 ///   %D = select %cond, %C, %A
236 /// into:
237 ///   %C = select %cond, %B, 0
238 ///   %D = or %A, %C
239 ///
240 /// Assuming that the specified instruction is an operand to the select, return
241 /// a bitmask indicating which operands of this instruction are foldable if they
242 /// equal the other incoming value of the select.
getSelectFoldableOperands(BinaryOperator * I)243 static unsigned getSelectFoldableOperands(BinaryOperator *I) {
244   switch (I->getOpcode()) {
245   case Instruction::Add:
246   case Instruction::Mul:
247   case Instruction::And:
248   case Instruction::Or:
249   case Instruction::Xor:
250     return 3;              // Can fold through either operand.
251   case Instruction::Sub:   // Can only fold on the amount subtracted.
252   case Instruction::Shl:   // Can only fold on the shift amount.
253   case Instruction::LShr:
254   case Instruction::AShr:
255     return 1;
256   default:
257     return 0;              // Cannot fold
258   }
259 }
260 
261 /// For the same transformation as the previous function, return the identity
262 /// constant that goes into the select.
getSelectFoldableConstant(BinaryOperator * I)263 static APInt getSelectFoldableConstant(BinaryOperator *I) {
264   switch (I->getOpcode()) {
265   default: llvm_unreachable("This cannot happen!");
266   case Instruction::Add:
267   case Instruction::Sub:
268   case Instruction::Or:
269   case Instruction::Xor:
270   case Instruction::Shl:
271   case Instruction::LShr:
272   case Instruction::AShr:
273     return APInt::getNullValue(I->getType()->getScalarSizeInBits());
274   case Instruction::And:
275     return APInt::getAllOnesValue(I->getType()->getScalarSizeInBits());
276   case Instruction::Mul:
277     return APInt(I->getType()->getScalarSizeInBits(), 1);
278   }
279 }
280 
281 /// We have (select c, TI, FI), and we know that TI and FI have the same opcode.
foldSelectOpOp(SelectInst & SI,Instruction * TI,Instruction * FI)282 Instruction *InstCombiner::foldSelectOpOp(SelectInst &SI, Instruction *TI,
283                                           Instruction *FI) {
284   // Don't break up min/max patterns. The hasOneUse checks below prevent that
285   // for most cases, but vector min/max with bitcasts can be transformed. If the
286   // one-use restrictions are eased for other patterns, we still don't want to
287   // obfuscate min/max.
288   if ((match(&SI, m_SMin(m_Value(), m_Value())) ||
289        match(&SI, m_SMax(m_Value(), m_Value())) ||
290        match(&SI, m_UMin(m_Value(), m_Value())) ||
291        match(&SI, m_UMax(m_Value(), m_Value()))))
292     return nullptr;
293 
294   // If this is a cast from the same type, merge.
295   Value *Cond = SI.getCondition();
296   Type *CondTy = Cond->getType();
297   if (TI->getNumOperands() == 1 && TI->isCast()) {
298     Type *FIOpndTy = FI->getOperand(0)->getType();
299     if (TI->getOperand(0)->getType() != FIOpndTy)
300       return nullptr;
301 
302     // The select condition may be a vector. We may only change the operand
303     // type if the vector width remains the same (and matches the condition).
304     if (auto *CondVTy = dyn_cast<VectorType>(CondTy)) {
305       if (!FIOpndTy->isVectorTy())
306         return nullptr;
307       if (CondVTy->getNumElements() !=
308           cast<VectorType>(FIOpndTy)->getNumElements())
309         return nullptr;
310 
311       // TODO: If the backend knew how to deal with casts better, we could
312       // remove this limitation. For now, there's too much potential to create
313       // worse codegen by promoting the select ahead of size-altering casts
314       // (PR28160).
315       //
316       // Note that ValueTracking's matchSelectPattern() looks through casts
317       // without checking 'hasOneUse' when it matches min/max patterns, so this
318       // transform may end up happening anyway.
319       if (TI->getOpcode() != Instruction::BitCast &&
320           (!TI->hasOneUse() || !FI->hasOneUse()))
321         return nullptr;
322     } else if (!TI->hasOneUse() || !FI->hasOneUse()) {
323       // TODO: The one-use restrictions for a scalar select could be eased if
324       // the fold of a select in visitLoadInst() was enhanced to match a pattern
325       // that includes a cast.
326       return nullptr;
327     }
328 
329     // Fold this by inserting a select from the input values.
330     Value *NewSI =
331         Builder.CreateSelect(Cond, TI->getOperand(0), FI->getOperand(0),
332                              SI.getName() + ".v", &SI);
333     return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
334                             TI->getType());
335   }
336 
337   // Cond ? -X : -Y --> -(Cond ? X : Y)
338   Value *X, *Y;
339   if (match(TI, m_FNeg(m_Value(X))) && match(FI, m_FNeg(m_Value(Y))) &&
340       (TI->hasOneUse() || FI->hasOneUse())) {
341     Value *NewSel = Builder.CreateSelect(Cond, X, Y, SI.getName() + ".v", &SI);
342     return UnaryOperator::CreateFNegFMF(NewSel, TI);
343   }
344 
345   // Only handle binary operators (including two-operand getelementptr) with
346   // one-use here. As with the cast case above, it may be possible to relax the
347   // one-use constraint, but that needs be examined carefully since it may not
348   // reduce the total number of instructions.
349   if (TI->getNumOperands() != 2 || FI->getNumOperands() != 2 ||
350       (!isa<BinaryOperator>(TI) && !isa<GetElementPtrInst>(TI)) ||
351       !TI->hasOneUse() || !FI->hasOneUse())
352     return nullptr;
353 
354   // Figure out if the operations have any operands in common.
355   Value *MatchOp, *OtherOpT, *OtherOpF;
356   bool MatchIsOpZero;
357   if (TI->getOperand(0) == FI->getOperand(0)) {
358     MatchOp  = TI->getOperand(0);
359     OtherOpT = TI->getOperand(1);
360     OtherOpF = FI->getOperand(1);
361     MatchIsOpZero = true;
362   } else if (TI->getOperand(1) == FI->getOperand(1)) {
363     MatchOp  = TI->getOperand(1);
364     OtherOpT = TI->getOperand(0);
365     OtherOpF = FI->getOperand(0);
366     MatchIsOpZero = false;
367   } else if (!TI->isCommutative()) {
368     return nullptr;
369   } else if (TI->getOperand(0) == FI->getOperand(1)) {
370     MatchOp  = TI->getOperand(0);
371     OtherOpT = TI->getOperand(1);
372     OtherOpF = FI->getOperand(0);
373     MatchIsOpZero = true;
374   } else if (TI->getOperand(1) == FI->getOperand(0)) {
375     MatchOp  = TI->getOperand(1);
376     OtherOpT = TI->getOperand(0);
377     OtherOpF = FI->getOperand(1);
378     MatchIsOpZero = true;
379   } else {
380     return nullptr;
381   }
382 
383   // If the select condition is a vector, the operands of the original select's
384   // operands also must be vectors. This may not be the case for getelementptr
385   // for example.
386   if (CondTy->isVectorTy() && (!OtherOpT->getType()->isVectorTy() ||
387                                !OtherOpF->getType()->isVectorTy()))
388     return nullptr;
389 
390   // If we reach here, they do have operations in common.
391   Value *NewSI = Builder.CreateSelect(Cond, OtherOpT, OtherOpF,
392                                       SI.getName() + ".v", &SI);
393   Value *Op0 = MatchIsOpZero ? MatchOp : NewSI;
394   Value *Op1 = MatchIsOpZero ? NewSI : MatchOp;
395   if (auto *BO = dyn_cast<BinaryOperator>(TI)) {
396     BinaryOperator *NewBO = BinaryOperator::Create(BO->getOpcode(), Op0, Op1);
397     NewBO->copyIRFlags(TI);
398     NewBO->andIRFlags(FI);
399     return NewBO;
400   }
401   if (auto *TGEP = dyn_cast<GetElementPtrInst>(TI)) {
402     auto *FGEP = cast<GetElementPtrInst>(FI);
403     Type *ElementType = TGEP->getResultElementType();
404     return TGEP->isInBounds() && FGEP->isInBounds()
405                ? GetElementPtrInst::CreateInBounds(ElementType, Op0, {Op1})
406                : GetElementPtrInst::Create(ElementType, Op0, {Op1});
407   }
408   llvm_unreachable("Expected BinaryOperator or GEP");
409   return nullptr;
410 }
411 
isSelect01(const APInt & C1I,const APInt & C2I)412 static bool isSelect01(const APInt &C1I, const APInt &C2I) {
413   if (!C1I.isNullValue() && !C2I.isNullValue()) // One side must be zero.
414     return false;
415   return C1I.isOneValue() || C1I.isAllOnesValue() ||
416          C2I.isOneValue() || C2I.isAllOnesValue();
417 }
418 
419 /// Try to fold the select into one of the operands to allow further
420 /// optimization.
foldSelectIntoOp(SelectInst & SI,Value * TrueVal,Value * FalseVal)421 Instruction *InstCombiner::foldSelectIntoOp(SelectInst &SI, Value *TrueVal,
422                                             Value *FalseVal) {
423   // See the comment above GetSelectFoldableOperands for a description of the
424   // transformation we are doing here.
425   if (auto *TVI = dyn_cast<BinaryOperator>(TrueVal)) {
426     if (TVI->hasOneUse() && !isa<Constant>(FalseVal)) {
427       if (unsigned SFO = getSelectFoldableOperands(TVI)) {
428         unsigned OpToFold = 0;
429         if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
430           OpToFold = 1;
431         } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
432           OpToFold = 2;
433         }
434 
435         if (OpToFold) {
436           APInt CI = getSelectFoldableConstant(TVI);
437           Value *OOp = TVI->getOperand(2-OpToFold);
438           // Avoid creating select between 2 constants unless it's selecting
439           // between 0, 1 and -1.
440           const APInt *OOpC;
441           bool OOpIsAPInt = match(OOp, m_APInt(OOpC));
442           if (!isa<Constant>(OOp) || (OOpIsAPInt && isSelect01(CI, *OOpC))) {
443             Value *C = ConstantInt::get(OOp->getType(), CI);
444             Value *NewSel = Builder.CreateSelect(SI.getCondition(), OOp, C);
445             NewSel->takeName(TVI);
446             BinaryOperator *BO = BinaryOperator::Create(TVI->getOpcode(),
447                                                         FalseVal, NewSel);
448             BO->copyIRFlags(TVI);
449             return BO;
450           }
451         }
452       }
453     }
454   }
455 
456   if (auto *FVI = dyn_cast<BinaryOperator>(FalseVal)) {
457     if (FVI->hasOneUse() && !isa<Constant>(TrueVal)) {
458       if (unsigned SFO = getSelectFoldableOperands(FVI)) {
459         unsigned OpToFold = 0;
460         if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
461           OpToFold = 1;
462         } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
463           OpToFold = 2;
464         }
465 
466         if (OpToFold) {
467           APInt CI = getSelectFoldableConstant(FVI);
468           Value *OOp = FVI->getOperand(2-OpToFold);
469           // Avoid creating select between 2 constants unless it's selecting
470           // between 0, 1 and -1.
471           const APInt *OOpC;
472           bool OOpIsAPInt = match(OOp, m_APInt(OOpC));
473           if (!isa<Constant>(OOp) || (OOpIsAPInt && isSelect01(CI, *OOpC))) {
474             Value *C = ConstantInt::get(OOp->getType(), CI);
475             Value *NewSel = Builder.CreateSelect(SI.getCondition(), C, OOp);
476             NewSel->takeName(FVI);
477             BinaryOperator *BO = BinaryOperator::Create(FVI->getOpcode(),
478                                                         TrueVal, NewSel);
479             BO->copyIRFlags(FVI);
480             return BO;
481           }
482         }
483       }
484     }
485   }
486 
487   return nullptr;
488 }
489 
490 /// We want to turn:
491 ///   (select (icmp eq (and X, Y), 0), (and (lshr X, Z), 1), 1)
492 /// into:
493 ///   zext (icmp ne i32 (and X, (or Y, (shl 1, Z))), 0)
494 /// Note:
495 ///   Z may be 0 if lshr is missing.
496 /// Worst-case scenario is that we will replace 5 instructions with 5 different
497 /// instructions, but we got rid of select.
foldSelectICmpAndAnd(Type * SelType,const ICmpInst * Cmp,Value * TVal,Value * FVal,InstCombiner::BuilderTy & Builder)498 static Instruction *foldSelectICmpAndAnd(Type *SelType, const ICmpInst *Cmp,
499                                          Value *TVal, Value *FVal,
500                                          InstCombiner::BuilderTy &Builder) {
501   if (!(Cmp->hasOneUse() && Cmp->getOperand(0)->hasOneUse() &&
502         Cmp->getPredicate() == ICmpInst::ICMP_EQ &&
503         match(Cmp->getOperand(1), m_Zero()) && match(FVal, m_One())))
504     return nullptr;
505 
506   // The TrueVal has general form of:  and %B, 1
507   Value *B;
508   if (!match(TVal, m_OneUse(m_And(m_Value(B), m_One()))))
509     return nullptr;
510 
511   // Where %B may be optionally shifted:  lshr %X, %Z.
512   Value *X, *Z;
513   const bool HasShift = match(B, m_OneUse(m_LShr(m_Value(X), m_Value(Z))));
514   if (!HasShift)
515     X = B;
516 
517   Value *Y;
518   if (!match(Cmp->getOperand(0), m_c_And(m_Specific(X), m_Value(Y))))
519     return nullptr;
520 
521   // ((X & Y) == 0) ? ((X >> Z) & 1) : 1 --> (X & (Y | (1 << Z))) != 0
522   // ((X & Y) == 0) ? (X & 1) : 1 --> (X & (Y | 1)) != 0
523   Constant *One = ConstantInt::get(SelType, 1);
524   Value *MaskB = HasShift ? Builder.CreateShl(One, Z) : One;
525   Value *FullMask = Builder.CreateOr(Y, MaskB);
526   Value *MaskedX = Builder.CreateAnd(X, FullMask);
527   Value *ICmpNeZero = Builder.CreateIsNotNull(MaskedX);
528   return new ZExtInst(ICmpNeZero, SelType);
529 }
530 
531 /// We want to turn:
532 ///   (select (icmp sgt x, C), lshr (X, Y), ashr (X, Y)); iff C s>= -1
533 ///   (select (icmp slt x, C), ashr (X, Y), lshr (X, Y)); iff C s>= 0
534 /// into:
535 ///   ashr (X, Y)
foldSelectICmpLshrAshr(const ICmpInst * IC,Value * TrueVal,Value * FalseVal,InstCombiner::BuilderTy & Builder)536 static Value *foldSelectICmpLshrAshr(const ICmpInst *IC, Value *TrueVal,
537                                      Value *FalseVal,
538                                      InstCombiner::BuilderTy &Builder) {
539   ICmpInst::Predicate Pred = IC->getPredicate();
540   Value *CmpLHS = IC->getOperand(0);
541   Value *CmpRHS = IC->getOperand(1);
542   if (!CmpRHS->getType()->isIntOrIntVectorTy())
543     return nullptr;
544 
545   Value *X, *Y;
546   unsigned Bitwidth = CmpRHS->getType()->getScalarSizeInBits();
547   if ((Pred != ICmpInst::ICMP_SGT ||
548        !match(CmpRHS,
549               m_SpecificInt_ICMP(ICmpInst::ICMP_SGE, APInt(Bitwidth, -1)))) &&
550       (Pred != ICmpInst::ICMP_SLT ||
551        !match(CmpRHS,
552               m_SpecificInt_ICMP(ICmpInst::ICMP_SGE, APInt(Bitwidth, 0)))))
553     return nullptr;
554 
555   // Canonicalize so that ashr is in FalseVal.
556   if (Pred == ICmpInst::ICMP_SLT)
557     std::swap(TrueVal, FalseVal);
558 
559   if (match(TrueVal, m_LShr(m_Value(X), m_Value(Y))) &&
560       match(FalseVal, m_AShr(m_Specific(X), m_Specific(Y))) &&
561       match(CmpLHS, m_Specific(X))) {
562     const auto *Ashr = cast<Instruction>(FalseVal);
563     // if lshr is not exact and ashr is, this new ashr must not be exact.
564     bool IsExact = Ashr->isExact() && cast<Instruction>(TrueVal)->isExact();
565     return Builder.CreateAShr(X, Y, IC->getName(), IsExact);
566   }
567 
568   return nullptr;
569 }
570 
571 /// We want to turn:
572 ///   (select (icmp eq (and X, C1), 0), Y, (or Y, C2))
573 /// into:
574 ///   (or (shl (and X, C1), C3), Y)
575 /// iff:
576 ///   C1 and C2 are both powers of 2
577 /// where:
578 ///   C3 = Log(C2) - Log(C1)
579 ///
580 /// This transform handles cases where:
581 /// 1. The icmp predicate is inverted
582 /// 2. The select operands are reversed
583 /// 3. The magnitude of C2 and C1 are flipped
foldSelectICmpAndOr(const ICmpInst * IC,Value * TrueVal,Value * FalseVal,InstCombiner::BuilderTy & Builder)584 static Value *foldSelectICmpAndOr(const ICmpInst *IC, Value *TrueVal,
585                                   Value *FalseVal,
586                                   InstCombiner::BuilderTy &Builder) {
587   // Only handle integer compares. Also, if this is a vector select, we need a
588   // vector compare.
589   if (!TrueVal->getType()->isIntOrIntVectorTy() ||
590       TrueVal->getType()->isVectorTy() != IC->getType()->isVectorTy())
591     return nullptr;
592 
593   Value *CmpLHS = IC->getOperand(0);
594   Value *CmpRHS = IC->getOperand(1);
595 
596   Value *V;
597   unsigned C1Log;
598   bool IsEqualZero;
599   bool NeedAnd = false;
600   if (IC->isEquality()) {
601     if (!match(CmpRHS, m_Zero()))
602       return nullptr;
603 
604     const APInt *C1;
605     if (!match(CmpLHS, m_And(m_Value(), m_Power2(C1))))
606       return nullptr;
607 
608     V = CmpLHS;
609     C1Log = C1->logBase2();
610     IsEqualZero = IC->getPredicate() == ICmpInst::ICMP_EQ;
611   } else if (IC->getPredicate() == ICmpInst::ICMP_SLT ||
612              IC->getPredicate() == ICmpInst::ICMP_SGT) {
613     // We also need to recognize (icmp slt (trunc (X)), 0) and
614     // (icmp sgt (trunc (X)), -1).
615     IsEqualZero = IC->getPredicate() == ICmpInst::ICMP_SGT;
616     if ((IsEqualZero && !match(CmpRHS, m_AllOnes())) ||
617         (!IsEqualZero && !match(CmpRHS, m_Zero())))
618       return nullptr;
619 
620     if (!match(CmpLHS, m_OneUse(m_Trunc(m_Value(V)))))
621       return nullptr;
622 
623     C1Log = CmpLHS->getType()->getScalarSizeInBits() - 1;
624     NeedAnd = true;
625   } else {
626     return nullptr;
627   }
628 
629   const APInt *C2;
630   bool OrOnTrueVal = false;
631   bool OrOnFalseVal = match(FalseVal, m_Or(m_Specific(TrueVal), m_Power2(C2)));
632   if (!OrOnFalseVal)
633     OrOnTrueVal = match(TrueVal, m_Or(m_Specific(FalseVal), m_Power2(C2)));
634 
635   if (!OrOnFalseVal && !OrOnTrueVal)
636     return nullptr;
637 
638   Value *Y = OrOnFalseVal ? TrueVal : FalseVal;
639 
640   unsigned C2Log = C2->logBase2();
641 
642   bool NeedXor = (!IsEqualZero && OrOnFalseVal) || (IsEqualZero && OrOnTrueVal);
643   bool NeedShift = C1Log != C2Log;
644   bool NeedZExtTrunc = Y->getType()->getScalarSizeInBits() !=
645                        V->getType()->getScalarSizeInBits();
646 
647   // Make sure we don't create more instructions than we save.
648   Value *Or = OrOnFalseVal ? FalseVal : TrueVal;
649   if ((NeedShift + NeedXor + NeedZExtTrunc) >
650       (IC->hasOneUse() + Or->hasOneUse()))
651     return nullptr;
652 
653   if (NeedAnd) {
654     // Insert the AND instruction on the input to the truncate.
655     APInt C1 = APInt::getOneBitSet(V->getType()->getScalarSizeInBits(), C1Log);
656     V = Builder.CreateAnd(V, ConstantInt::get(V->getType(), C1));
657   }
658 
659   if (C2Log > C1Log) {
660     V = Builder.CreateZExtOrTrunc(V, Y->getType());
661     V = Builder.CreateShl(V, C2Log - C1Log);
662   } else if (C1Log > C2Log) {
663     V = Builder.CreateLShr(V, C1Log - C2Log);
664     V = Builder.CreateZExtOrTrunc(V, Y->getType());
665   } else
666     V = Builder.CreateZExtOrTrunc(V, Y->getType());
667 
668   if (NeedXor)
669     V = Builder.CreateXor(V, *C2);
670 
671   return Builder.CreateOr(V, Y);
672 }
673 
674 /// Canonicalize a set or clear of a masked set of constant bits to
675 /// select-of-constants form.
foldSetClearBits(SelectInst & Sel,InstCombiner::BuilderTy & Builder)676 static Instruction *foldSetClearBits(SelectInst &Sel,
677                                      InstCombiner::BuilderTy &Builder) {
678   Value *Cond = Sel.getCondition();
679   Value *T = Sel.getTrueValue();
680   Value *F = Sel.getFalseValue();
681   Type *Ty = Sel.getType();
682   Value *X;
683   const APInt *NotC, *C;
684 
685   // Cond ? (X & ~C) : (X | C) --> (X & ~C) | (Cond ? 0 : C)
686   if (match(T, m_And(m_Value(X), m_APInt(NotC))) &&
687       match(F, m_OneUse(m_Or(m_Specific(X), m_APInt(C)))) && *NotC == ~(*C)) {
688     Constant *Zero = ConstantInt::getNullValue(Ty);
689     Constant *OrC = ConstantInt::get(Ty, *C);
690     Value *NewSel = Builder.CreateSelect(Cond, Zero, OrC, "masksel", &Sel);
691     return BinaryOperator::CreateOr(T, NewSel);
692   }
693 
694   // Cond ? (X | C) : (X & ~C) --> (X & ~C) | (Cond ? C : 0)
695   if (match(F, m_And(m_Value(X), m_APInt(NotC))) &&
696       match(T, m_OneUse(m_Or(m_Specific(X), m_APInt(C)))) && *NotC == ~(*C)) {
697     Constant *Zero = ConstantInt::getNullValue(Ty);
698     Constant *OrC = ConstantInt::get(Ty, *C);
699     Value *NewSel = Builder.CreateSelect(Cond, OrC, Zero, "masksel", &Sel);
700     return BinaryOperator::CreateOr(F, NewSel);
701   }
702 
703   return nullptr;
704 }
705 
706 /// Transform patterns such as (a > b) ? a - b : 0 into usub.sat(a, b).
707 /// There are 8 commuted/swapped variants of this pattern.
708 /// TODO: Also support a - UMIN(a,b) patterns.
canonicalizeSaturatedSubtract(const ICmpInst * ICI,const Value * TrueVal,const Value * FalseVal,InstCombiner::BuilderTy & Builder)709 static Value *canonicalizeSaturatedSubtract(const ICmpInst *ICI,
710                                             const Value *TrueVal,
711                                             const Value *FalseVal,
712                                             InstCombiner::BuilderTy &Builder) {
713   ICmpInst::Predicate Pred = ICI->getPredicate();
714   if (!ICmpInst::isUnsigned(Pred))
715     return nullptr;
716 
717   // (b > a) ? 0 : a - b -> (b <= a) ? a - b : 0
718   if (match(TrueVal, m_Zero())) {
719     Pred = ICmpInst::getInversePredicate(Pred);
720     std::swap(TrueVal, FalseVal);
721   }
722   if (!match(FalseVal, m_Zero()))
723     return nullptr;
724 
725   Value *A = ICI->getOperand(0);
726   Value *B = ICI->getOperand(1);
727   if (Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_ULT) {
728     // (b < a) ? a - b : 0 -> (a > b) ? a - b : 0
729     std::swap(A, B);
730     Pred = ICmpInst::getSwappedPredicate(Pred);
731   }
732 
733   assert((Pred == ICmpInst::ICMP_UGE || Pred == ICmpInst::ICMP_UGT) &&
734          "Unexpected isUnsigned predicate!");
735 
736   // Ensure the sub is of the form:
737   //  (a > b) ? a - b : 0 -> usub.sat(a, b)
738   //  (a > b) ? b - a : 0 -> -usub.sat(a, b)
739   // Checking for both a-b and a+(-b) as a constant.
740   bool IsNegative = false;
741   const APInt *C;
742   if (match(TrueVal, m_Sub(m_Specific(B), m_Specific(A))) ||
743       (match(A, m_APInt(C)) &&
744        match(TrueVal, m_Add(m_Specific(B), m_SpecificInt(-*C)))))
745     IsNegative = true;
746   else if (!match(TrueVal, m_Sub(m_Specific(A), m_Specific(B))) &&
747            !(match(B, m_APInt(C)) &&
748              match(TrueVal, m_Add(m_Specific(A), m_SpecificInt(-*C)))))
749     return nullptr;
750 
751   // If we are adding a negate and the sub and icmp are used anywhere else, we
752   // would end up with more instructions.
753   if (IsNegative && !TrueVal->hasOneUse() && !ICI->hasOneUse())
754     return nullptr;
755 
756   // (a > b) ? a - b : 0 -> usub.sat(a, b)
757   // (a > b) ? b - a : 0 -> -usub.sat(a, b)
758   Value *Result = Builder.CreateBinaryIntrinsic(Intrinsic::usub_sat, A, B);
759   if (IsNegative)
760     Result = Builder.CreateNeg(Result);
761   return Result;
762 }
763 
canonicalizeSaturatedAdd(ICmpInst * Cmp,Value * TVal,Value * FVal,InstCombiner::BuilderTy & Builder)764 static Value *canonicalizeSaturatedAdd(ICmpInst *Cmp, Value *TVal, Value *FVal,
765                                        InstCombiner::BuilderTy &Builder) {
766   if (!Cmp->hasOneUse())
767     return nullptr;
768 
769   // Match unsigned saturated add with constant.
770   Value *Cmp0 = Cmp->getOperand(0);
771   Value *Cmp1 = Cmp->getOperand(1);
772   ICmpInst::Predicate Pred = Cmp->getPredicate();
773   Value *X;
774   const APInt *C, *CmpC;
775   if (Pred == ICmpInst::ICMP_ULT &&
776       match(TVal, m_Add(m_Value(X), m_APInt(C))) && X == Cmp0 &&
777       match(FVal, m_AllOnes()) && match(Cmp1, m_APInt(CmpC)) && *CmpC == ~*C) {
778     // (X u< ~C) ? (X + C) : -1 --> uadd.sat(X, C)
779     return Builder.CreateBinaryIntrinsic(
780         Intrinsic::uadd_sat, X, ConstantInt::get(X->getType(), *C));
781   }
782 
783   // Match unsigned saturated add of 2 variables with an unnecessary 'not'.
784   // There are 8 commuted variants.
785   // Canonicalize -1 (saturated result) to true value of the select. Just
786   // swapping the compare operands is legal, because the selected value is the
787   // same in case of equality, so we can interchange u< and u<=.
788   if (match(FVal, m_AllOnes())) {
789     std::swap(TVal, FVal);
790     std::swap(Cmp0, Cmp1);
791   }
792   if (!match(TVal, m_AllOnes()))
793     return nullptr;
794 
795   // Canonicalize predicate to 'ULT'.
796   if (Pred == ICmpInst::ICMP_UGT) {
797     Pred = ICmpInst::ICMP_ULT;
798     std::swap(Cmp0, Cmp1);
799   }
800   if (Pred != ICmpInst::ICMP_ULT)
801     return nullptr;
802 
803   // Match unsigned saturated add of 2 variables with an unnecessary 'not'.
804   Value *Y;
805   if (match(Cmp0, m_Not(m_Value(X))) &&
806       match(FVal, m_c_Add(m_Specific(X), m_Value(Y))) && Y == Cmp1) {
807     // (~X u< Y) ? -1 : (X + Y) --> uadd.sat(X, Y)
808     // (~X u< Y) ? -1 : (Y + X) --> uadd.sat(X, Y)
809     return Builder.CreateBinaryIntrinsic(Intrinsic::uadd_sat, X, Y);
810   }
811   // The 'not' op may be included in the sum but not the compare.
812   X = Cmp0;
813   Y = Cmp1;
814   if (match(FVal, m_c_Add(m_Not(m_Specific(X)), m_Specific(Y)))) {
815     // (X u< Y) ? -1 : (~X + Y) --> uadd.sat(~X, Y)
816     // (X u< Y) ? -1 : (Y + ~X) --> uadd.sat(Y, ~X)
817     BinaryOperator *BO = cast<BinaryOperator>(FVal);
818     return Builder.CreateBinaryIntrinsic(
819         Intrinsic::uadd_sat, BO->getOperand(0), BO->getOperand(1));
820   }
821   // The overflow may be detected via the add wrapping round.
822   if (match(Cmp0, m_c_Add(m_Specific(Cmp1), m_Value(Y))) &&
823       match(FVal, m_c_Add(m_Specific(Cmp1), m_Specific(Y)))) {
824     // ((X + Y) u< X) ? -1 : (X + Y) --> uadd.sat(X, Y)
825     // ((X + Y) u< Y) ? -1 : (X + Y) --> uadd.sat(X, Y)
826     return Builder.CreateBinaryIntrinsic(Intrinsic::uadd_sat, Cmp1, Y);
827   }
828 
829   return nullptr;
830 }
831 
832 /// Fold the following code sequence:
833 /// \code
834 ///   int a = ctlz(x & -x);
835 //    x ? 31 - a : a;
836 /// \code
837 ///
838 /// into:
839 ///   cttz(x)
foldSelectCtlzToCttz(ICmpInst * ICI,Value * TrueVal,Value * FalseVal,InstCombiner::BuilderTy & Builder)840 static Instruction *foldSelectCtlzToCttz(ICmpInst *ICI, Value *TrueVal,
841                                          Value *FalseVal,
842                                          InstCombiner::BuilderTy &Builder) {
843   unsigned BitWidth = TrueVal->getType()->getScalarSizeInBits();
844   if (!ICI->isEquality() || !match(ICI->getOperand(1), m_Zero()))
845     return nullptr;
846 
847   if (ICI->getPredicate() == ICmpInst::ICMP_NE)
848     std::swap(TrueVal, FalseVal);
849 
850   if (!match(FalseVal,
851              m_Xor(m_Deferred(TrueVal), m_SpecificInt(BitWidth - 1))))
852     return nullptr;
853 
854   if (!match(TrueVal, m_Intrinsic<Intrinsic::ctlz>()))
855     return nullptr;
856 
857   Value *X = ICI->getOperand(0);
858   auto *II = cast<IntrinsicInst>(TrueVal);
859   if (!match(II->getOperand(0), m_c_And(m_Specific(X), m_Neg(m_Specific(X)))))
860     return nullptr;
861 
862   Function *F = Intrinsic::getDeclaration(II->getModule(), Intrinsic::cttz,
863                                           II->getType());
864   return CallInst::Create(F, {X, II->getArgOperand(1)});
865 }
866 
867 /// Attempt to fold a cttz/ctlz followed by a icmp plus select into a single
868 /// call to cttz/ctlz with flag 'is_zero_undef' cleared.
869 ///
870 /// For example, we can fold the following code sequence:
871 /// \code
872 ///   %0 = tail call i32 @llvm.cttz.i32(i32 %x, i1 true)
873 ///   %1 = icmp ne i32 %x, 0
874 ///   %2 = select i1 %1, i32 %0, i32 32
875 /// \code
876 ///
877 /// into:
878 ///   %0 = tail call i32 @llvm.cttz.i32(i32 %x, i1 false)
foldSelectCttzCtlz(ICmpInst * ICI,Value * TrueVal,Value * FalseVal,InstCombiner::BuilderTy & Builder)879 static Value *foldSelectCttzCtlz(ICmpInst *ICI, Value *TrueVal, Value *FalseVal,
880                                  InstCombiner::BuilderTy &Builder) {
881   ICmpInst::Predicate Pred = ICI->getPredicate();
882   Value *CmpLHS = ICI->getOperand(0);
883   Value *CmpRHS = ICI->getOperand(1);
884 
885   // Check if the condition value compares a value for equality against zero.
886   if (!ICI->isEquality() || !match(CmpRHS, m_Zero()))
887     return nullptr;
888 
889   Value *SelectArg = FalseVal;
890   Value *ValueOnZero = TrueVal;
891   if (Pred == ICmpInst::ICMP_NE)
892     std::swap(SelectArg, ValueOnZero);
893 
894   // Skip zero extend/truncate.
895   Value *Count = nullptr;
896   if (!match(SelectArg, m_ZExt(m_Value(Count))) &&
897       !match(SelectArg, m_Trunc(m_Value(Count))))
898     Count = SelectArg;
899 
900   // Check that 'Count' is a call to intrinsic cttz/ctlz. Also check that the
901   // input to the cttz/ctlz is used as LHS for the compare instruction.
902   if (!match(Count, m_Intrinsic<Intrinsic::cttz>(m_Specific(CmpLHS))) &&
903       !match(Count, m_Intrinsic<Intrinsic::ctlz>(m_Specific(CmpLHS))))
904     return nullptr;
905 
906   IntrinsicInst *II = cast<IntrinsicInst>(Count);
907 
908   // Check if the value propagated on zero is a constant number equal to the
909   // sizeof in bits of 'Count'.
910   unsigned SizeOfInBits = Count->getType()->getScalarSizeInBits();
911   if (match(ValueOnZero, m_SpecificInt(SizeOfInBits))) {
912     // Explicitly clear the 'undef_on_zero' flag. It's always valid to go from
913     // true to false on this flag, so we can replace it for all users.
914     II->setArgOperand(1, ConstantInt::getFalse(II->getContext()));
915     return SelectArg;
916   }
917 
918   // The ValueOnZero is not the bitwidth. But if the cttz/ctlz (and optional
919   // zext/trunc) have one use (ending at the select), the cttz/ctlz result will
920   // not be used if the input is zero. Relax to 'undef_on_zero' for that case.
921   if (II->hasOneUse() && SelectArg->hasOneUse() &&
922       !match(II->getArgOperand(1), m_One()))
923     II->setArgOperand(1, ConstantInt::getTrue(II->getContext()));
924 
925   return nullptr;
926 }
927 
928 /// Return true if we find and adjust an icmp+select pattern where the compare
929 /// is with a constant that can be incremented or decremented to match the
930 /// minimum or maximum idiom.
adjustMinMax(SelectInst & Sel,ICmpInst & Cmp)931 static bool adjustMinMax(SelectInst &Sel, ICmpInst &Cmp) {
932   ICmpInst::Predicate Pred = Cmp.getPredicate();
933   Value *CmpLHS = Cmp.getOperand(0);
934   Value *CmpRHS = Cmp.getOperand(1);
935   Value *TrueVal = Sel.getTrueValue();
936   Value *FalseVal = Sel.getFalseValue();
937 
938   // We may move or edit the compare, so make sure the select is the only user.
939   const APInt *CmpC;
940   if (!Cmp.hasOneUse() || !match(CmpRHS, m_APInt(CmpC)))
941     return false;
942 
943   // These transforms only work for selects of integers or vector selects of
944   // integer vectors.
945   Type *SelTy = Sel.getType();
946   auto *SelEltTy = dyn_cast<IntegerType>(SelTy->getScalarType());
947   if (!SelEltTy || SelTy->isVectorTy() != Cmp.getType()->isVectorTy())
948     return false;
949 
950   Constant *AdjustedRHS;
951   if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_SGT)
952     AdjustedRHS = ConstantInt::get(CmpRHS->getType(), *CmpC + 1);
953   else if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT)
954     AdjustedRHS = ConstantInt::get(CmpRHS->getType(), *CmpC - 1);
955   else
956     return false;
957 
958   // X > C ? X : C+1  -->  X < C+1 ? C+1 : X
959   // X < C ? X : C-1  -->  X > C-1 ? C-1 : X
960   if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
961       (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
962     ; // Nothing to do here. Values match without any sign/zero extension.
963   }
964   // Types do not match. Instead of calculating this with mixed types, promote
965   // all to the larger type. This enables scalar evolution to analyze this
966   // expression.
967   else if (CmpRHS->getType()->getScalarSizeInBits() < SelEltTy->getBitWidth()) {
968     Constant *SextRHS = ConstantExpr::getSExt(AdjustedRHS, SelTy);
969 
970     // X = sext x; x >s c ? X : C+1 --> X = sext x; X <s C+1 ? C+1 : X
971     // X = sext x; x <s c ? X : C-1 --> X = sext x; X >s C-1 ? C-1 : X
972     // X = sext x; x >u c ? X : C+1 --> X = sext x; X <u C+1 ? C+1 : X
973     // X = sext x; x <u c ? X : C-1 --> X = sext x; X >u C-1 ? C-1 : X
974     if (match(TrueVal, m_SExt(m_Specific(CmpLHS))) && SextRHS == FalseVal) {
975       CmpLHS = TrueVal;
976       AdjustedRHS = SextRHS;
977     } else if (match(FalseVal, m_SExt(m_Specific(CmpLHS))) &&
978                SextRHS == TrueVal) {
979       CmpLHS = FalseVal;
980       AdjustedRHS = SextRHS;
981     } else if (Cmp.isUnsigned()) {
982       Constant *ZextRHS = ConstantExpr::getZExt(AdjustedRHS, SelTy);
983       // X = zext x; x >u c ? X : C+1 --> X = zext x; X <u C+1 ? C+1 : X
984       // X = zext x; x <u c ? X : C-1 --> X = zext x; X >u C-1 ? C-1 : X
985       // zext + signed compare cannot be changed:
986       //    0xff <s 0x00, but 0x00ff >s 0x0000
987       if (match(TrueVal, m_ZExt(m_Specific(CmpLHS))) && ZextRHS == FalseVal) {
988         CmpLHS = TrueVal;
989         AdjustedRHS = ZextRHS;
990       } else if (match(FalseVal, m_ZExt(m_Specific(CmpLHS))) &&
991                  ZextRHS == TrueVal) {
992         CmpLHS = FalseVal;
993         AdjustedRHS = ZextRHS;
994       } else {
995         return false;
996       }
997     } else {
998       return false;
999     }
1000   } else {
1001     return false;
1002   }
1003 
1004   Pred = ICmpInst::getSwappedPredicate(Pred);
1005   CmpRHS = AdjustedRHS;
1006   std::swap(FalseVal, TrueVal);
1007   Cmp.setPredicate(Pred);
1008   Cmp.setOperand(0, CmpLHS);
1009   Cmp.setOperand(1, CmpRHS);
1010   Sel.setOperand(1, TrueVal);
1011   Sel.setOperand(2, FalseVal);
1012   Sel.swapProfMetadata();
1013 
1014   // Move the compare instruction right before the select instruction. Otherwise
1015   // the sext/zext value may be defined after the compare instruction uses it.
1016   Cmp.moveBefore(&Sel);
1017 
1018   return true;
1019 }
1020 
1021 /// If this is an integer min/max (icmp + select) with a constant operand,
1022 /// create the canonical icmp for the min/max operation and canonicalize the
1023 /// constant to the 'false' operand of the select:
1024 /// select (icmp Pred X, C1), C2, X --> select (icmp Pred' X, C2), X, C2
1025 /// Note: if C1 != C2, this will change the icmp constant to the existing
1026 /// constant operand of the select.
1027 static Instruction *
canonicalizeMinMaxWithConstant(SelectInst & Sel,ICmpInst & Cmp,InstCombiner & IC)1028 canonicalizeMinMaxWithConstant(SelectInst &Sel, ICmpInst &Cmp,
1029                                InstCombiner &IC) {
1030   if (!Cmp.hasOneUse() || !isa<Constant>(Cmp.getOperand(1)))
1031     return nullptr;
1032 
1033   // Canonicalize the compare predicate based on whether we have min or max.
1034   Value *LHS, *RHS;
1035   SelectPatternResult SPR = matchSelectPattern(&Sel, LHS, RHS);
1036   if (!SelectPatternResult::isMinOrMax(SPR.Flavor))
1037     return nullptr;
1038 
1039   // Is this already canonical?
1040   ICmpInst::Predicate CanonicalPred = getMinMaxPred(SPR.Flavor);
1041   if (Cmp.getOperand(0) == LHS && Cmp.getOperand(1) == RHS &&
1042       Cmp.getPredicate() == CanonicalPred)
1043     return nullptr;
1044 
1045   // Bail out on unsimplified X-0 operand (due to some worklist management bug),
1046   // as this may cause an infinite combine loop. Let the sub be folded first.
1047   if (match(LHS, m_Sub(m_Value(), m_Zero())) ||
1048       match(RHS, m_Sub(m_Value(), m_Zero())))
1049     return nullptr;
1050 
1051   // Create the canonical compare and plug it into the select.
1052   IC.replaceOperand(Sel, 0, IC.Builder.CreateICmp(CanonicalPred, LHS, RHS));
1053 
1054   // If the select operands did not change, we're done.
1055   if (Sel.getTrueValue() == LHS && Sel.getFalseValue() == RHS)
1056     return &Sel;
1057 
1058   // If we are swapping the select operands, swap the metadata too.
1059   assert(Sel.getTrueValue() == RHS && Sel.getFalseValue() == LHS &&
1060          "Unexpected results from matchSelectPattern");
1061   Sel.swapValues();
1062   Sel.swapProfMetadata();
1063   return &Sel;
1064 }
1065 
1066 /// There are many select variants for each of ABS/NABS.
1067 /// In matchSelectPattern(), there are different compare constants, compare
1068 /// predicates/operands and select operands.
1069 /// In isKnownNegation(), there are different formats of negated operands.
1070 /// Canonicalize all these variants to 1 pattern.
1071 /// This makes CSE more likely.
canonicalizeAbsNabs(SelectInst & Sel,ICmpInst & Cmp,InstCombiner & IC)1072 static Instruction *canonicalizeAbsNabs(SelectInst &Sel, ICmpInst &Cmp,
1073                                         InstCombiner &IC) {
1074   if (!Cmp.hasOneUse() || !isa<Constant>(Cmp.getOperand(1)))
1075     return nullptr;
1076 
1077   // Choose a sign-bit check for the compare (likely simpler for codegen).
1078   // ABS:  (X <s 0) ? -X : X
1079   // NABS: (X <s 0) ? X : -X
1080   Value *LHS, *RHS;
1081   SelectPatternFlavor SPF = matchSelectPattern(&Sel, LHS, RHS).Flavor;
1082   if (SPF != SelectPatternFlavor::SPF_ABS &&
1083       SPF != SelectPatternFlavor::SPF_NABS)
1084     return nullptr;
1085 
1086   Value *TVal = Sel.getTrueValue();
1087   Value *FVal = Sel.getFalseValue();
1088   assert(isKnownNegation(TVal, FVal) &&
1089          "Unexpected result from matchSelectPattern");
1090 
1091   // The compare may use the negated abs()/nabs() operand, or it may use
1092   // negation in non-canonical form such as: sub A, B.
1093   bool CmpUsesNegatedOp = match(Cmp.getOperand(0), m_Neg(m_Specific(TVal))) ||
1094                           match(Cmp.getOperand(0), m_Neg(m_Specific(FVal)));
1095 
1096   bool CmpCanonicalized = !CmpUsesNegatedOp &&
1097                           match(Cmp.getOperand(1), m_ZeroInt()) &&
1098                           Cmp.getPredicate() == ICmpInst::ICMP_SLT;
1099   bool RHSCanonicalized = match(RHS, m_Neg(m_Specific(LHS)));
1100 
1101   // Is this already canonical?
1102   if (CmpCanonicalized && RHSCanonicalized)
1103     return nullptr;
1104 
1105   // If RHS is not canonical but is used by other instructions, don't
1106   // canonicalize it and potentially increase the instruction count.
1107   if (!RHSCanonicalized)
1108     if (!(RHS->hasOneUse() || (RHS->hasNUses(2) && CmpUsesNegatedOp)))
1109       return nullptr;
1110 
1111   // Create the canonical compare: icmp slt LHS 0.
1112   if (!CmpCanonicalized) {
1113     Cmp.setPredicate(ICmpInst::ICMP_SLT);
1114     Cmp.setOperand(1, ConstantInt::getNullValue(Cmp.getOperand(0)->getType()));
1115     if (CmpUsesNegatedOp)
1116       Cmp.setOperand(0, LHS);
1117   }
1118 
1119   // Create the canonical RHS: RHS = sub (0, LHS).
1120   if (!RHSCanonicalized) {
1121     assert(RHS->hasOneUse() && "RHS use number is not right");
1122     RHS = IC.Builder.CreateNeg(LHS);
1123     if (TVal == LHS) {
1124       // Replace false value.
1125       IC.replaceOperand(Sel, 2, RHS);
1126       FVal = RHS;
1127     } else {
1128       // Replace true value.
1129       IC.replaceOperand(Sel, 1, RHS);
1130       TVal = RHS;
1131     }
1132   }
1133 
1134   // If the select operands do not change, we're done.
1135   if (SPF == SelectPatternFlavor::SPF_NABS) {
1136     if (TVal == LHS)
1137       return &Sel;
1138     assert(FVal == LHS && "Unexpected results from matchSelectPattern");
1139   } else {
1140     if (FVal == LHS)
1141       return &Sel;
1142     assert(TVal == LHS && "Unexpected results from matchSelectPattern");
1143   }
1144 
1145   // We are swapping the select operands, so swap the metadata too.
1146   Sel.swapValues();
1147   Sel.swapProfMetadata();
1148   return &Sel;
1149 }
1150 
simplifyWithOpReplaced(Value * V,Value * Op,Value * ReplaceOp,const SimplifyQuery & Q)1151 static Value *simplifyWithOpReplaced(Value *V, Value *Op, Value *ReplaceOp,
1152                                      const SimplifyQuery &Q) {
1153   // If this is a binary operator, try to simplify it with the replaced op
1154   // because we know Op and ReplaceOp are equivalant.
1155   // For example: V = X + 1, Op = X, ReplaceOp = 42
1156   // Simplifies as: add(42, 1) --> 43
1157   if (auto *BO = dyn_cast<BinaryOperator>(V)) {
1158     if (BO->getOperand(0) == Op)
1159       return SimplifyBinOp(BO->getOpcode(), ReplaceOp, BO->getOperand(1), Q);
1160     if (BO->getOperand(1) == Op)
1161       return SimplifyBinOp(BO->getOpcode(), BO->getOperand(0), ReplaceOp, Q);
1162   }
1163 
1164   return nullptr;
1165 }
1166 
1167 /// If we have a select with an equality comparison, then we know the value in
1168 /// one of the arms of the select. See if substituting this value into an arm
1169 /// and simplifying the result yields the same value as the other arm.
1170 ///
1171 /// To make this transform safe, we must drop poison-generating flags
1172 /// (nsw, etc) if we simplified to a binop because the select may be guarding
1173 /// that poison from propagating. If the existing binop already had no
1174 /// poison-generating flags, then this transform can be done by instsimplify.
1175 ///
1176 /// Consider:
1177 ///   %cmp = icmp eq i32 %x, 2147483647
1178 ///   %add = add nsw i32 %x, 1
1179 ///   %sel = select i1 %cmp, i32 -2147483648, i32 %add
1180 ///
1181 /// We can't replace %sel with %add unless we strip away the flags.
1182 /// TODO: Wrapping flags could be preserved in some cases with better analysis.
foldSelectValueEquivalence(SelectInst & Sel,ICmpInst & Cmp,const SimplifyQuery & Q)1183 static Value *foldSelectValueEquivalence(SelectInst &Sel, ICmpInst &Cmp,
1184                                          const SimplifyQuery &Q) {
1185   if (!Cmp.isEquality())
1186     return nullptr;
1187 
1188   // Canonicalize the pattern to ICMP_EQ by swapping the select operands.
1189   Value *TrueVal = Sel.getTrueValue(), *FalseVal = Sel.getFalseValue();
1190   if (Cmp.getPredicate() == ICmpInst::ICMP_NE)
1191     std::swap(TrueVal, FalseVal);
1192 
1193   // Try each equivalence substitution possibility.
1194   // We have an 'EQ' comparison, so the select's false value will propagate.
1195   // Example:
1196   // (X == 42) ? 43 : (X + 1) --> (X == 42) ? (X + 1) : (X + 1) --> X + 1
1197   // (X == 42) ? (X + 1) : 43 --> (X == 42) ? (42 + 1) : 43 --> 43
1198   Value *CmpLHS = Cmp.getOperand(0), *CmpRHS = Cmp.getOperand(1);
1199   if (simplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, Q) == TrueVal ||
1200       simplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, Q) == TrueVal ||
1201       simplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, Q) == FalseVal ||
1202       simplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, Q) == FalseVal) {
1203     if (auto *FalseInst = dyn_cast<Instruction>(FalseVal))
1204       FalseInst->dropPoisonGeneratingFlags();
1205     return FalseVal;
1206   }
1207   return nullptr;
1208 }
1209 
1210 // See if this is a pattern like:
1211 //   %old_cmp1 = icmp slt i32 %x, C2
1212 //   %old_replacement = select i1 %old_cmp1, i32 %target_low, i32 %target_high
1213 //   %old_x_offseted = add i32 %x, C1
1214 //   %old_cmp0 = icmp ult i32 %old_x_offseted, C0
1215 //   %r = select i1 %old_cmp0, i32 %x, i32 %old_replacement
1216 // This can be rewritten as more canonical pattern:
1217 //   %new_cmp1 = icmp slt i32 %x, -C1
1218 //   %new_cmp2 = icmp sge i32 %x, C0-C1
1219 //   %new_clamped_low = select i1 %new_cmp1, i32 %target_low, i32 %x
1220 //   %r = select i1 %new_cmp2, i32 %target_high, i32 %new_clamped_low
1221 // Iff -C1 s<= C2 s<= C0-C1
1222 // Also ULT predicate can also be UGT iff C0 != -1 (+invert result)
1223 //      SLT predicate can also be SGT iff C2 != INT_MAX (+invert res.)
canonicalizeClampLike(SelectInst & Sel0,ICmpInst & Cmp0,InstCombiner::BuilderTy & Builder)1224 static Instruction *canonicalizeClampLike(SelectInst &Sel0, ICmpInst &Cmp0,
1225                                           InstCombiner::BuilderTy &Builder) {
1226   Value *X = Sel0.getTrueValue();
1227   Value *Sel1 = Sel0.getFalseValue();
1228 
1229   // First match the condition of the outermost select.
1230   // Said condition must be one-use.
1231   if (!Cmp0.hasOneUse())
1232     return nullptr;
1233   Value *Cmp00 = Cmp0.getOperand(0);
1234   Constant *C0;
1235   if (!match(Cmp0.getOperand(1),
1236              m_CombineAnd(m_AnyIntegralConstant(), m_Constant(C0))))
1237     return nullptr;
1238   // Canonicalize Cmp0 into the form we expect.
1239   // FIXME: we shouldn't care about lanes that are 'undef' in the end?
1240   switch (Cmp0.getPredicate()) {
1241   case ICmpInst::Predicate::ICMP_ULT:
1242     break; // Great!
1243   case ICmpInst::Predicate::ICMP_ULE:
1244     // We'd have to increment C0 by one, and for that it must not have all-ones
1245     // element, but then it would have been canonicalized to 'ult' before
1246     // we get here. So we can't do anything useful with 'ule'.
1247     return nullptr;
1248   case ICmpInst::Predicate::ICMP_UGT:
1249     // We want to canonicalize it to 'ult', so we'll need to increment C0,
1250     // which again means it must not have any all-ones elements.
1251     if (!match(C0,
1252                m_SpecificInt_ICMP(ICmpInst::Predicate::ICMP_NE,
1253                                   APInt::getAllOnesValue(
1254                                       C0->getType()->getScalarSizeInBits()))))
1255       return nullptr; // Can't do, have all-ones element[s].
1256     C0 = AddOne(C0);
1257     std::swap(X, Sel1);
1258     break;
1259   case ICmpInst::Predicate::ICMP_UGE:
1260     // The only way we'd get this predicate if this `icmp` has extra uses,
1261     // but then we won't be able to do this fold.
1262     return nullptr;
1263   default:
1264     return nullptr; // Unknown predicate.
1265   }
1266 
1267   // Now that we've canonicalized the ICmp, we know the X we expect;
1268   // the select in other hand should be one-use.
1269   if (!Sel1->hasOneUse())
1270     return nullptr;
1271 
1272   // We now can finish matching the condition of the outermost select:
1273   // it should either be the X itself, or an addition of some constant to X.
1274   Constant *C1;
1275   if (Cmp00 == X)
1276     C1 = ConstantInt::getNullValue(Sel0.getType());
1277   else if (!match(Cmp00,
1278                   m_Add(m_Specific(X),
1279                         m_CombineAnd(m_AnyIntegralConstant(), m_Constant(C1)))))
1280     return nullptr;
1281 
1282   Value *Cmp1;
1283   ICmpInst::Predicate Pred1;
1284   Constant *C2;
1285   Value *ReplacementLow, *ReplacementHigh;
1286   if (!match(Sel1, m_Select(m_Value(Cmp1), m_Value(ReplacementLow),
1287                             m_Value(ReplacementHigh))) ||
1288       !match(Cmp1,
1289              m_ICmp(Pred1, m_Specific(X),
1290                     m_CombineAnd(m_AnyIntegralConstant(), m_Constant(C2)))))
1291     return nullptr;
1292 
1293   if (!Cmp1->hasOneUse() && (Cmp00 == X || !Cmp00->hasOneUse()))
1294     return nullptr; // Not enough one-use instructions for the fold.
1295   // FIXME: this restriction could be relaxed if Cmp1 can be reused as one of
1296   //        two comparisons we'll need to build.
1297 
1298   // Canonicalize Cmp1 into the form we expect.
1299   // FIXME: we shouldn't care about lanes that are 'undef' in the end?
1300   switch (Pred1) {
1301   case ICmpInst::Predicate::ICMP_SLT:
1302     break;
1303   case ICmpInst::Predicate::ICMP_SLE:
1304     // We'd have to increment C2 by one, and for that it must not have signed
1305     // max element, but then it would have been canonicalized to 'slt' before
1306     // we get here. So we can't do anything useful with 'sle'.
1307     return nullptr;
1308   case ICmpInst::Predicate::ICMP_SGT:
1309     // We want to canonicalize it to 'slt', so we'll need to increment C2,
1310     // which again means it must not have any signed max elements.
1311     if (!match(C2,
1312                m_SpecificInt_ICMP(ICmpInst::Predicate::ICMP_NE,
1313                                   APInt::getSignedMaxValue(
1314                                       C2->getType()->getScalarSizeInBits()))))
1315       return nullptr; // Can't do, have signed max element[s].
1316     C2 = AddOne(C2);
1317     LLVM_FALLTHROUGH;
1318   case ICmpInst::Predicate::ICMP_SGE:
1319     // Also non-canonical, but here we don't need to change C2,
1320     // so we don't have any restrictions on C2, so we can just handle it.
1321     std::swap(ReplacementLow, ReplacementHigh);
1322     break;
1323   default:
1324     return nullptr; // Unknown predicate.
1325   }
1326 
1327   // The thresholds of this clamp-like pattern.
1328   auto *ThresholdLowIncl = ConstantExpr::getNeg(C1);
1329   auto *ThresholdHighExcl = ConstantExpr::getSub(C0, C1);
1330 
1331   // The fold has a precondition 1: C2 s>= ThresholdLow
1332   auto *Precond1 = ConstantExpr::getICmp(ICmpInst::Predicate::ICMP_SGE, C2,
1333                                          ThresholdLowIncl);
1334   if (!match(Precond1, m_One()))
1335     return nullptr;
1336   // The fold has a precondition 2: C2 s<= ThresholdHigh
1337   auto *Precond2 = ConstantExpr::getICmp(ICmpInst::Predicate::ICMP_SLE, C2,
1338                                          ThresholdHighExcl);
1339   if (!match(Precond2, m_One()))
1340     return nullptr;
1341 
1342   // All good, finally emit the new pattern.
1343   Value *ShouldReplaceLow = Builder.CreateICmpSLT(X, ThresholdLowIncl);
1344   Value *ShouldReplaceHigh = Builder.CreateICmpSGE(X, ThresholdHighExcl);
1345   Value *MaybeReplacedLow =
1346       Builder.CreateSelect(ShouldReplaceLow, ReplacementLow, X);
1347   Instruction *MaybeReplacedHigh =
1348       SelectInst::Create(ShouldReplaceHigh, ReplacementHigh, MaybeReplacedLow);
1349 
1350   return MaybeReplacedHigh;
1351 }
1352 
1353 // If we have
1354 //  %cmp = icmp [canonical predicate] i32 %x, C0
1355 //  %r = select i1 %cmp, i32 %y, i32 C1
1356 // Where C0 != C1 and %x may be different from %y, see if the constant that we
1357 // will have if we flip the strictness of the predicate (i.e. without changing
1358 // the result) is identical to the C1 in select. If it matches we can change
1359 // original comparison to one with swapped predicate, reuse the constant,
1360 // and swap the hands of select.
1361 static Instruction *
tryToReuseConstantFromSelectInComparison(SelectInst & Sel,ICmpInst & Cmp,InstCombiner & IC)1362 tryToReuseConstantFromSelectInComparison(SelectInst &Sel, ICmpInst &Cmp,
1363                                          InstCombiner &IC) {
1364   ICmpInst::Predicate Pred;
1365   Value *X;
1366   Constant *C0;
1367   if (!match(&Cmp, m_OneUse(m_ICmp(
1368                        Pred, m_Value(X),
1369                        m_CombineAnd(m_AnyIntegralConstant(), m_Constant(C0))))))
1370     return nullptr;
1371 
1372   // If comparison predicate is non-relational, we won't be able to do anything.
1373   if (ICmpInst::isEquality(Pred))
1374     return nullptr;
1375 
1376   // If comparison predicate is non-canonical, then we certainly won't be able
1377   // to make it canonical; canonicalizeCmpWithConstant() already tried.
1378   if (!isCanonicalPredicate(Pred))
1379     return nullptr;
1380 
1381   // If the [input] type of comparison and select type are different, lets abort
1382   // for now. We could try to compare constants with trunc/[zs]ext though.
1383   if (C0->getType() != Sel.getType())
1384     return nullptr;
1385 
1386   // FIXME: are there any magic icmp predicate+constant pairs we must not touch?
1387 
1388   Value *SelVal0, *SelVal1; // We do not care which one is from where.
1389   match(&Sel, m_Select(m_Value(), m_Value(SelVal0), m_Value(SelVal1)));
1390   // At least one of these values we are selecting between must be a constant
1391   // else we'll never succeed.
1392   if (!match(SelVal0, m_AnyIntegralConstant()) &&
1393       !match(SelVal1, m_AnyIntegralConstant()))
1394     return nullptr;
1395 
1396   // Does this constant C match any of the `select` values?
1397   auto MatchesSelectValue = [SelVal0, SelVal1](Constant *C) {
1398     return C->isElementWiseEqual(SelVal0) || C->isElementWiseEqual(SelVal1);
1399   };
1400 
1401   // If C0 *already* matches true/false value of select, we are done.
1402   if (MatchesSelectValue(C0))
1403     return nullptr;
1404 
1405   // Check the constant we'd have with flipped-strictness predicate.
1406   auto FlippedStrictness = getFlippedStrictnessPredicateAndConstant(Pred, C0);
1407   if (!FlippedStrictness)
1408     return nullptr;
1409 
1410   // If said constant doesn't match either, then there is no hope,
1411   if (!MatchesSelectValue(FlippedStrictness->second))
1412     return nullptr;
1413 
1414   // It matched! Lets insert the new comparison just before select.
1415   InstCombiner::BuilderTy::InsertPointGuard Guard(IC.Builder);
1416   IC.Builder.SetInsertPoint(&Sel);
1417 
1418   Pred = ICmpInst::getSwappedPredicate(Pred); // Yes, swapped.
1419   Value *NewCmp = IC.Builder.CreateICmp(Pred, X, FlippedStrictness->second,
1420                                         Cmp.getName() + ".inv");
1421   IC.replaceOperand(Sel, 0, NewCmp);
1422   Sel.swapValues();
1423   Sel.swapProfMetadata();
1424 
1425   return &Sel;
1426 }
1427 
1428 /// Visit a SelectInst that has an ICmpInst as its first operand.
foldSelectInstWithICmp(SelectInst & SI,ICmpInst * ICI)1429 Instruction *InstCombiner::foldSelectInstWithICmp(SelectInst &SI,
1430                                                   ICmpInst *ICI) {
1431   if (Value *V = foldSelectValueEquivalence(SI, *ICI, SQ))
1432     return replaceInstUsesWith(SI, V);
1433 
1434   if (Instruction *NewSel = canonicalizeMinMaxWithConstant(SI, *ICI, *this))
1435     return NewSel;
1436 
1437   if (Instruction *NewAbs = canonicalizeAbsNabs(SI, *ICI, *this))
1438     return NewAbs;
1439 
1440   if (Instruction *NewAbs = canonicalizeClampLike(SI, *ICI, Builder))
1441     return NewAbs;
1442 
1443   if (Instruction *NewSel =
1444           tryToReuseConstantFromSelectInComparison(SI, *ICI, *this))
1445     return NewSel;
1446 
1447   bool Changed = adjustMinMax(SI, *ICI);
1448 
1449   if (Value *V = foldSelectICmpAnd(SI, ICI, Builder))
1450     return replaceInstUsesWith(SI, V);
1451 
1452   // NOTE: if we wanted to, this is where to detect integer MIN/MAX
1453   Value *TrueVal = SI.getTrueValue();
1454   Value *FalseVal = SI.getFalseValue();
1455   ICmpInst::Predicate Pred = ICI->getPredicate();
1456   Value *CmpLHS = ICI->getOperand(0);
1457   Value *CmpRHS = ICI->getOperand(1);
1458   if (CmpRHS != CmpLHS && isa<Constant>(CmpRHS)) {
1459     if (CmpLHS == TrueVal && Pred == ICmpInst::ICMP_EQ) {
1460       // Transform (X == C) ? X : Y -> (X == C) ? C : Y
1461       SI.setOperand(1, CmpRHS);
1462       Changed = true;
1463     } else if (CmpLHS == FalseVal && Pred == ICmpInst::ICMP_NE) {
1464       // Transform (X != C) ? Y : X -> (X != C) ? Y : C
1465       SI.setOperand(2, CmpRHS);
1466       Changed = true;
1467     }
1468   }
1469 
1470   // FIXME: This code is nearly duplicated in InstSimplify. Using/refactoring
1471   // decomposeBitTestICmp() might help.
1472   {
1473     unsigned BitWidth =
1474         DL.getTypeSizeInBits(TrueVal->getType()->getScalarType());
1475     APInt MinSignedValue = APInt::getSignedMinValue(BitWidth);
1476     Value *X;
1477     const APInt *Y, *C;
1478     bool TrueWhenUnset;
1479     bool IsBitTest = false;
1480     if (ICmpInst::isEquality(Pred) &&
1481         match(CmpLHS, m_And(m_Value(X), m_Power2(Y))) &&
1482         match(CmpRHS, m_Zero())) {
1483       IsBitTest = true;
1484       TrueWhenUnset = Pred == ICmpInst::ICMP_EQ;
1485     } else if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, m_Zero())) {
1486       X = CmpLHS;
1487       Y = &MinSignedValue;
1488       IsBitTest = true;
1489       TrueWhenUnset = false;
1490     } else if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, m_AllOnes())) {
1491       X = CmpLHS;
1492       Y = &MinSignedValue;
1493       IsBitTest = true;
1494       TrueWhenUnset = true;
1495     }
1496     if (IsBitTest) {
1497       Value *V = nullptr;
1498       // (X & Y) == 0 ? X : X ^ Y  --> X & ~Y
1499       if (TrueWhenUnset && TrueVal == X &&
1500           match(FalseVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
1501         V = Builder.CreateAnd(X, ~(*Y));
1502       // (X & Y) != 0 ? X ^ Y : X  --> X & ~Y
1503       else if (!TrueWhenUnset && FalseVal == X &&
1504                match(TrueVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
1505         V = Builder.CreateAnd(X, ~(*Y));
1506       // (X & Y) == 0 ? X ^ Y : X  --> X | Y
1507       else if (TrueWhenUnset && FalseVal == X &&
1508                match(TrueVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
1509         V = Builder.CreateOr(X, *Y);
1510       // (X & Y) != 0 ? X : X ^ Y  --> X | Y
1511       else if (!TrueWhenUnset && TrueVal == X &&
1512                match(FalseVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
1513         V = Builder.CreateOr(X, *Y);
1514 
1515       if (V)
1516         return replaceInstUsesWith(SI, V);
1517     }
1518   }
1519 
1520   if (Instruction *V =
1521           foldSelectICmpAndAnd(SI.getType(), ICI, TrueVal, FalseVal, Builder))
1522     return V;
1523 
1524   if (Instruction *V = foldSelectCtlzToCttz(ICI, TrueVal, FalseVal, Builder))
1525     return V;
1526 
1527   if (Value *V = foldSelectICmpAndOr(ICI, TrueVal, FalseVal, Builder))
1528     return replaceInstUsesWith(SI, V);
1529 
1530   if (Value *V = foldSelectICmpLshrAshr(ICI, TrueVal, FalseVal, Builder))
1531     return replaceInstUsesWith(SI, V);
1532 
1533   if (Value *V = foldSelectCttzCtlz(ICI, TrueVal, FalseVal, Builder))
1534     return replaceInstUsesWith(SI, V);
1535 
1536   if (Value *V = canonicalizeSaturatedSubtract(ICI, TrueVal, FalseVal, Builder))
1537     return replaceInstUsesWith(SI, V);
1538 
1539   if (Value *V = canonicalizeSaturatedAdd(ICI, TrueVal, FalseVal, Builder))
1540     return replaceInstUsesWith(SI, V);
1541 
1542   return Changed ? &SI : nullptr;
1543 }
1544 
1545 /// SI is a select whose condition is a PHI node (but the two may be in
1546 /// different blocks). See if the true/false values (V) are live in all of the
1547 /// predecessor blocks of the PHI. For example, cases like this can't be mapped:
1548 ///
1549 ///   X = phi [ C1, BB1], [C2, BB2]
1550 ///   Y = add
1551 ///   Z = select X, Y, 0
1552 ///
1553 /// because Y is not live in BB1/BB2.
canSelectOperandBeMappingIntoPredBlock(const Value * V,const SelectInst & SI)1554 static bool canSelectOperandBeMappingIntoPredBlock(const Value *V,
1555                                                    const SelectInst &SI) {
1556   // If the value is a non-instruction value like a constant or argument, it
1557   // can always be mapped.
1558   const Instruction *I = dyn_cast<Instruction>(V);
1559   if (!I) return true;
1560 
1561   // If V is a PHI node defined in the same block as the condition PHI, we can
1562   // map the arguments.
1563   const PHINode *CondPHI = cast<PHINode>(SI.getCondition());
1564 
1565   if (const PHINode *VP = dyn_cast<PHINode>(I))
1566     if (VP->getParent() == CondPHI->getParent())
1567       return true;
1568 
1569   // Otherwise, if the PHI and select are defined in the same block and if V is
1570   // defined in a different block, then we can transform it.
1571   if (SI.getParent() == CondPHI->getParent() &&
1572       I->getParent() != CondPHI->getParent())
1573     return true;
1574 
1575   // Otherwise we have a 'hard' case and we can't tell without doing more
1576   // detailed dominator based analysis, punt.
1577   return false;
1578 }
1579 
1580 /// We have an SPF (e.g. a min or max) of an SPF of the form:
1581 ///   SPF2(SPF1(A, B), C)
foldSPFofSPF(Instruction * Inner,SelectPatternFlavor SPF1,Value * A,Value * B,Instruction & Outer,SelectPatternFlavor SPF2,Value * C)1582 Instruction *InstCombiner::foldSPFofSPF(Instruction *Inner,
1583                                         SelectPatternFlavor SPF1,
1584                                         Value *A, Value *B,
1585                                         Instruction &Outer,
1586                                         SelectPatternFlavor SPF2, Value *C) {
1587   if (Outer.getType() != Inner->getType())
1588     return nullptr;
1589 
1590   if (C == A || C == B) {
1591     // MAX(MAX(A, B), B) -> MAX(A, B)
1592     // MIN(MIN(a, b), a) -> MIN(a, b)
1593     // TODO: This could be done in instsimplify.
1594     if (SPF1 == SPF2 && SelectPatternResult::isMinOrMax(SPF1))
1595       return replaceInstUsesWith(Outer, Inner);
1596 
1597     // MAX(MIN(a, b), a) -> a
1598     // MIN(MAX(a, b), a) -> a
1599     // TODO: This could be done in instsimplify.
1600     if ((SPF1 == SPF_SMIN && SPF2 == SPF_SMAX) ||
1601         (SPF1 == SPF_SMAX && SPF2 == SPF_SMIN) ||
1602         (SPF1 == SPF_UMIN && SPF2 == SPF_UMAX) ||
1603         (SPF1 == SPF_UMAX && SPF2 == SPF_UMIN))
1604       return replaceInstUsesWith(Outer, C);
1605   }
1606 
1607   if (SPF1 == SPF2) {
1608     const APInt *CB, *CC;
1609     if (match(B, m_APInt(CB)) && match(C, m_APInt(CC))) {
1610       // MIN(MIN(A, 23), 97) -> MIN(A, 23)
1611       // MAX(MAX(A, 97), 23) -> MAX(A, 97)
1612       // TODO: This could be done in instsimplify.
1613       if ((SPF1 == SPF_UMIN && CB->ule(*CC)) ||
1614           (SPF1 == SPF_SMIN && CB->sle(*CC)) ||
1615           (SPF1 == SPF_UMAX && CB->uge(*CC)) ||
1616           (SPF1 == SPF_SMAX && CB->sge(*CC)))
1617         return replaceInstUsesWith(Outer, Inner);
1618 
1619       // MIN(MIN(A, 97), 23) -> MIN(A, 23)
1620       // MAX(MAX(A, 23), 97) -> MAX(A, 97)
1621       if ((SPF1 == SPF_UMIN && CB->ugt(*CC)) ||
1622           (SPF1 == SPF_SMIN && CB->sgt(*CC)) ||
1623           (SPF1 == SPF_UMAX && CB->ult(*CC)) ||
1624           (SPF1 == SPF_SMAX && CB->slt(*CC))) {
1625         Outer.replaceUsesOfWith(Inner, A);
1626         return &Outer;
1627       }
1628     }
1629   }
1630 
1631   // max(max(A, B), min(A, B)) --> max(A, B)
1632   // min(min(A, B), max(A, B)) --> min(A, B)
1633   // TODO: This could be done in instsimplify.
1634   if (SPF1 == SPF2 &&
1635       ((SPF1 == SPF_UMIN && match(C, m_c_UMax(m_Specific(A), m_Specific(B)))) ||
1636        (SPF1 == SPF_SMIN && match(C, m_c_SMax(m_Specific(A), m_Specific(B)))) ||
1637        (SPF1 == SPF_UMAX && match(C, m_c_UMin(m_Specific(A), m_Specific(B)))) ||
1638        (SPF1 == SPF_SMAX && match(C, m_c_SMin(m_Specific(A), m_Specific(B))))))
1639     return replaceInstUsesWith(Outer, Inner);
1640 
1641   // ABS(ABS(X)) -> ABS(X)
1642   // NABS(NABS(X)) -> NABS(X)
1643   // TODO: This could be done in instsimplify.
1644   if (SPF1 == SPF2 && (SPF1 == SPF_ABS || SPF1 == SPF_NABS)) {
1645     return replaceInstUsesWith(Outer, Inner);
1646   }
1647 
1648   // ABS(NABS(X)) -> ABS(X)
1649   // NABS(ABS(X)) -> NABS(X)
1650   if ((SPF1 == SPF_ABS && SPF2 == SPF_NABS) ||
1651       (SPF1 == SPF_NABS && SPF2 == SPF_ABS)) {
1652     SelectInst *SI = cast<SelectInst>(Inner);
1653     Value *NewSI =
1654         Builder.CreateSelect(SI->getCondition(), SI->getFalseValue(),
1655                              SI->getTrueValue(), SI->getName(), SI);
1656     return replaceInstUsesWith(Outer, NewSI);
1657   }
1658 
1659   auto IsFreeOrProfitableToInvert =
1660       [&](Value *V, Value *&NotV, bool &ElidesXor) {
1661     if (match(V, m_Not(m_Value(NotV)))) {
1662       // If V has at most 2 uses then we can get rid of the xor operation
1663       // entirely.
1664       ElidesXor |= !V->hasNUsesOrMore(3);
1665       return true;
1666     }
1667 
1668     if (isFreeToInvert(V, !V->hasNUsesOrMore(3))) {
1669       NotV = nullptr;
1670       return true;
1671     }
1672 
1673     return false;
1674   };
1675 
1676   Value *NotA, *NotB, *NotC;
1677   bool ElidesXor = false;
1678 
1679   // MIN(MIN(~A, ~B), ~C) == ~MAX(MAX(A, B), C)
1680   // MIN(MAX(~A, ~B), ~C) == ~MAX(MIN(A, B), C)
1681   // MAX(MIN(~A, ~B), ~C) == ~MIN(MAX(A, B), C)
1682   // MAX(MAX(~A, ~B), ~C) == ~MIN(MIN(A, B), C)
1683   //
1684   // This transform is performance neutral if we can elide at least one xor from
1685   // the set of three operands, since we'll be tacking on an xor at the very
1686   // end.
1687   if (SelectPatternResult::isMinOrMax(SPF1) &&
1688       SelectPatternResult::isMinOrMax(SPF2) &&
1689       IsFreeOrProfitableToInvert(A, NotA, ElidesXor) &&
1690       IsFreeOrProfitableToInvert(B, NotB, ElidesXor) &&
1691       IsFreeOrProfitableToInvert(C, NotC, ElidesXor) && ElidesXor) {
1692     if (!NotA)
1693       NotA = Builder.CreateNot(A);
1694     if (!NotB)
1695       NotB = Builder.CreateNot(B);
1696     if (!NotC)
1697       NotC = Builder.CreateNot(C);
1698 
1699     Value *NewInner = createMinMax(Builder, getInverseMinMaxFlavor(SPF1), NotA,
1700                                    NotB);
1701     Value *NewOuter = Builder.CreateNot(
1702         createMinMax(Builder, getInverseMinMaxFlavor(SPF2), NewInner, NotC));
1703     return replaceInstUsesWith(Outer, NewOuter);
1704   }
1705 
1706   return nullptr;
1707 }
1708 
1709 /// Turn select C, (X + Y), (X - Y) --> (X + (select C, Y, (-Y))).
1710 /// This is even legal for FP.
foldAddSubSelect(SelectInst & SI,InstCombiner::BuilderTy & Builder)1711 static Instruction *foldAddSubSelect(SelectInst &SI,
1712                                      InstCombiner::BuilderTy &Builder) {
1713   Value *CondVal = SI.getCondition();
1714   Value *TrueVal = SI.getTrueValue();
1715   Value *FalseVal = SI.getFalseValue();
1716   auto *TI = dyn_cast<Instruction>(TrueVal);
1717   auto *FI = dyn_cast<Instruction>(FalseVal);
1718   if (!TI || !FI || !TI->hasOneUse() || !FI->hasOneUse())
1719     return nullptr;
1720 
1721   Instruction *AddOp = nullptr, *SubOp = nullptr;
1722   if ((TI->getOpcode() == Instruction::Sub &&
1723        FI->getOpcode() == Instruction::Add) ||
1724       (TI->getOpcode() == Instruction::FSub &&
1725        FI->getOpcode() == Instruction::FAdd)) {
1726     AddOp = FI;
1727     SubOp = TI;
1728   } else if ((FI->getOpcode() == Instruction::Sub &&
1729               TI->getOpcode() == Instruction::Add) ||
1730              (FI->getOpcode() == Instruction::FSub &&
1731               TI->getOpcode() == Instruction::FAdd)) {
1732     AddOp = TI;
1733     SubOp = FI;
1734   }
1735 
1736   if (AddOp) {
1737     Value *OtherAddOp = nullptr;
1738     if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
1739       OtherAddOp = AddOp->getOperand(1);
1740     } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
1741       OtherAddOp = AddOp->getOperand(0);
1742     }
1743 
1744     if (OtherAddOp) {
1745       // So at this point we know we have (Y -> OtherAddOp):
1746       //        select C, (add X, Y), (sub X, Z)
1747       Value *NegVal; // Compute -Z
1748       if (SI.getType()->isFPOrFPVectorTy()) {
1749         NegVal = Builder.CreateFNeg(SubOp->getOperand(1));
1750         if (Instruction *NegInst = dyn_cast<Instruction>(NegVal)) {
1751           FastMathFlags Flags = AddOp->getFastMathFlags();
1752           Flags &= SubOp->getFastMathFlags();
1753           NegInst->setFastMathFlags(Flags);
1754         }
1755       } else {
1756         NegVal = Builder.CreateNeg(SubOp->getOperand(1));
1757       }
1758 
1759       Value *NewTrueOp = OtherAddOp;
1760       Value *NewFalseOp = NegVal;
1761       if (AddOp != TI)
1762         std::swap(NewTrueOp, NewFalseOp);
1763       Value *NewSel = Builder.CreateSelect(CondVal, NewTrueOp, NewFalseOp,
1764                                            SI.getName() + ".p", &SI);
1765 
1766       if (SI.getType()->isFPOrFPVectorTy()) {
1767         Instruction *RI =
1768             BinaryOperator::CreateFAdd(SubOp->getOperand(0), NewSel);
1769 
1770         FastMathFlags Flags = AddOp->getFastMathFlags();
1771         Flags &= SubOp->getFastMathFlags();
1772         RI->setFastMathFlags(Flags);
1773         return RI;
1774       } else
1775         return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
1776     }
1777   }
1778   return nullptr;
1779 }
1780 
1781 /// Turn X + Y overflows ? -1 : X + Y -> uadd_sat X, Y
1782 /// And X - Y overflows ? 0 : X - Y -> usub_sat X, Y
1783 /// Along with a number of patterns similar to:
1784 /// X + Y overflows ? (X < 0 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y
1785 /// X - Y overflows ? (X > 0 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y
1786 static Instruction *
foldOverflowingAddSubSelect(SelectInst & SI,InstCombiner::BuilderTy & Builder)1787 foldOverflowingAddSubSelect(SelectInst &SI, InstCombiner::BuilderTy &Builder) {
1788   Value *CondVal = SI.getCondition();
1789   Value *TrueVal = SI.getTrueValue();
1790   Value *FalseVal = SI.getFalseValue();
1791 
1792   WithOverflowInst *II;
1793   if (!match(CondVal, m_ExtractValue<1>(m_WithOverflowInst(II))) ||
1794       !match(FalseVal, m_ExtractValue<0>(m_Specific(II))))
1795     return nullptr;
1796 
1797   Value *X = II->getLHS();
1798   Value *Y = II->getRHS();
1799 
1800   auto IsSignedSaturateLimit = [&](Value *Limit, bool IsAdd) {
1801     Type *Ty = Limit->getType();
1802 
1803     ICmpInst::Predicate Pred;
1804     Value *TrueVal, *FalseVal, *Op;
1805     const APInt *C;
1806     if (!match(Limit, m_Select(m_ICmp(Pred, m_Value(Op), m_APInt(C)),
1807                                m_Value(TrueVal), m_Value(FalseVal))))
1808       return false;
1809 
1810     auto IsZeroOrOne = [](const APInt &C) {
1811       return C.isNullValue() || C.isOneValue();
1812     };
1813     auto IsMinMax = [&](Value *Min, Value *Max) {
1814       APInt MinVal = APInt::getSignedMinValue(Ty->getScalarSizeInBits());
1815       APInt MaxVal = APInt::getSignedMaxValue(Ty->getScalarSizeInBits());
1816       return match(Min, m_SpecificInt(MinVal)) &&
1817              match(Max, m_SpecificInt(MaxVal));
1818     };
1819 
1820     if (Op != X && Op != Y)
1821       return false;
1822 
1823     if (IsAdd) {
1824       // X + Y overflows ? (X <s 0 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y
1825       // X + Y overflows ? (X <s 1 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y
1826       // X + Y overflows ? (Y <s 0 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y
1827       // X + Y overflows ? (Y <s 1 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y
1828       if (Pred == ICmpInst::ICMP_SLT && IsZeroOrOne(*C) &&
1829           IsMinMax(TrueVal, FalseVal))
1830         return true;
1831       // X + Y overflows ? (X >s 0 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y
1832       // X + Y overflows ? (X >s -1 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y
1833       // X + Y overflows ? (Y >s 0 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y
1834       // X + Y overflows ? (Y >s -1 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y
1835       if (Pred == ICmpInst::ICMP_SGT && IsZeroOrOne(*C + 1) &&
1836           IsMinMax(FalseVal, TrueVal))
1837         return true;
1838     } else {
1839       // X - Y overflows ? (X <s 0 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y
1840       // X - Y overflows ? (X <s -1 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y
1841       if (Op == X && Pred == ICmpInst::ICMP_SLT && IsZeroOrOne(*C + 1) &&
1842           IsMinMax(TrueVal, FalseVal))
1843         return true;
1844       // X - Y overflows ? (X >s -1 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y
1845       // X - Y overflows ? (X >s -2 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y
1846       if (Op == X && Pred == ICmpInst::ICMP_SGT && IsZeroOrOne(*C + 2) &&
1847           IsMinMax(FalseVal, TrueVal))
1848         return true;
1849       // X - Y overflows ? (Y <s 0 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y
1850       // X - Y overflows ? (Y <s 1 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y
1851       if (Op == Y && Pred == ICmpInst::ICMP_SLT && IsZeroOrOne(*C) &&
1852           IsMinMax(FalseVal, TrueVal))
1853         return true;
1854       // X - Y overflows ? (Y >s 0 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y
1855       // X - Y overflows ? (Y >s -1 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y
1856       if (Op == Y && Pred == ICmpInst::ICMP_SGT && IsZeroOrOne(*C + 1) &&
1857           IsMinMax(TrueVal, FalseVal))
1858         return true;
1859     }
1860 
1861     return false;
1862   };
1863 
1864   Intrinsic::ID NewIntrinsicID;
1865   if (II->getIntrinsicID() == Intrinsic::uadd_with_overflow &&
1866       match(TrueVal, m_AllOnes()))
1867     // X + Y overflows ? -1 : X + Y -> uadd_sat X, Y
1868     NewIntrinsicID = Intrinsic::uadd_sat;
1869   else if (II->getIntrinsicID() == Intrinsic::usub_with_overflow &&
1870            match(TrueVal, m_Zero()))
1871     // X - Y overflows ? 0 : X - Y -> usub_sat X, Y
1872     NewIntrinsicID = Intrinsic::usub_sat;
1873   else if (II->getIntrinsicID() == Intrinsic::sadd_with_overflow &&
1874            IsSignedSaturateLimit(TrueVal, /*IsAdd=*/true))
1875     // X + Y overflows ? (X <s 0 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y
1876     // X + Y overflows ? (X <s 1 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y
1877     // X + Y overflows ? (X >s 0 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y
1878     // X + Y overflows ? (X >s -1 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y
1879     // X + Y overflows ? (Y <s 0 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y
1880     // X + Y overflows ? (Y <s 1 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y
1881     // X + Y overflows ? (Y >s 0 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y
1882     // X + Y overflows ? (Y >s -1 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y
1883     NewIntrinsicID = Intrinsic::sadd_sat;
1884   else if (II->getIntrinsicID() == Intrinsic::ssub_with_overflow &&
1885            IsSignedSaturateLimit(TrueVal, /*IsAdd=*/false))
1886     // X - Y overflows ? (X <s 0 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y
1887     // X - Y overflows ? (X <s -1 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y
1888     // X - Y overflows ? (X >s -1 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y
1889     // X - Y overflows ? (X >s -2 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y
1890     // X - Y overflows ? (Y <s 0 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y
1891     // X - Y overflows ? (Y <s 1 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y
1892     // X - Y overflows ? (Y >s 0 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y
1893     // X - Y overflows ? (Y >s -1 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y
1894     NewIntrinsicID = Intrinsic::ssub_sat;
1895   else
1896     return nullptr;
1897 
1898   Function *F =
1899       Intrinsic::getDeclaration(SI.getModule(), NewIntrinsicID, SI.getType());
1900   return CallInst::Create(F, {X, Y});
1901 }
1902 
foldSelectExtConst(SelectInst & Sel)1903 Instruction *InstCombiner::foldSelectExtConst(SelectInst &Sel) {
1904   Constant *C;
1905   if (!match(Sel.getTrueValue(), m_Constant(C)) &&
1906       !match(Sel.getFalseValue(), m_Constant(C)))
1907     return nullptr;
1908 
1909   Instruction *ExtInst;
1910   if (!match(Sel.getTrueValue(), m_Instruction(ExtInst)) &&
1911       !match(Sel.getFalseValue(), m_Instruction(ExtInst)))
1912     return nullptr;
1913 
1914   auto ExtOpcode = ExtInst->getOpcode();
1915   if (ExtOpcode != Instruction::ZExt && ExtOpcode != Instruction::SExt)
1916     return nullptr;
1917 
1918   // If we are extending from a boolean type or if we can create a select that
1919   // has the same size operands as its condition, try to narrow the select.
1920   Value *X = ExtInst->getOperand(0);
1921   Type *SmallType = X->getType();
1922   Value *Cond = Sel.getCondition();
1923   auto *Cmp = dyn_cast<CmpInst>(Cond);
1924   if (!SmallType->isIntOrIntVectorTy(1) &&
1925       (!Cmp || Cmp->getOperand(0)->getType() != SmallType))
1926     return nullptr;
1927 
1928   // If the constant is the same after truncation to the smaller type and
1929   // extension to the original type, we can narrow the select.
1930   Type *SelType = Sel.getType();
1931   Constant *TruncC = ConstantExpr::getTrunc(C, SmallType);
1932   Constant *ExtC = ConstantExpr::getCast(ExtOpcode, TruncC, SelType);
1933   if (ExtC == C && ExtInst->hasOneUse()) {
1934     Value *TruncCVal = cast<Value>(TruncC);
1935     if (ExtInst == Sel.getFalseValue())
1936       std::swap(X, TruncCVal);
1937 
1938     // select Cond, (ext X), C --> ext(select Cond, X, C')
1939     // select Cond, C, (ext X) --> ext(select Cond, C', X)
1940     Value *NewSel = Builder.CreateSelect(Cond, X, TruncCVal, "narrow", &Sel);
1941     return CastInst::Create(Instruction::CastOps(ExtOpcode), NewSel, SelType);
1942   }
1943 
1944   // If one arm of the select is the extend of the condition, replace that arm
1945   // with the extension of the appropriate known bool value.
1946   if (Cond == X) {
1947     if (ExtInst == Sel.getTrueValue()) {
1948       // select X, (sext X), C --> select X, -1, C
1949       // select X, (zext X), C --> select X,  1, C
1950       Constant *One = ConstantInt::getTrue(SmallType);
1951       Constant *AllOnesOrOne = ConstantExpr::getCast(ExtOpcode, One, SelType);
1952       return SelectInst::Create(Cond, AllOnesOrOne, C, "", nullptr, &Sel);
1953     } else {
1954       // select X, C, (sext X) --> select X, C, 0
1955       // select X, C, (zext X) --> select X, C, 0
1956       Constant *Zero = ConstantInt::getNullValue(SelType);
1957       return SelectInst::Create(Cond, C, Zero, "", nullptr, &Sel);
1958     }
1959   }
1960 
1961   return nullptr;
1962 }
1963 
1964 /// Try to transform a vector select with a constant condition vector into a
1965 /// shuffle for easier combining with other shuffles and insert/extract.
canonicalizeSelectToShuffle(SelectInst & SI)1966 static Instruction *canonicalizeSelectToShuffle(SelectInst &SI) {
1967   Value *CondVal = SI.getCondition();
1968   Constant *CondC;
1969   if (!CondVal->getType()->isVectorTy() || !match(CondVal, m_Constant(CondC)))
1970     return nullptr;
1971 
1972   unsigned NumElts = cast<VectorType>(CondVal->getType())->getNumElements();
1973   SmallVector<int, 16> Mask;
1974   Mask.reserve(NumElts);
1975   for (unsigned i = 0; i != NumElts; ++i) {
1976     Constant *Elt = CondC->getAggregateElement(i);
1977     if (!Elt)
1978       return nullptr;
1979 
1980     if (Elt->isOneValue()) {
1981       // If the select condition element is true, choose from the 1st vector.
1982       Mask.push_back(i);
1983     } else if (Elt->isNullValue()) {
1984       // If the select condition element is false, choose from the 2nd vector.
1985       Mask.push_back(i + NumElts);
1986     } else if (isa<UndefValue>(Elt)) {
1987       // Undef in a select condition (choose one of the operands) does not mean
1988       // the same thing as undef in a shuffle mask (any value is acceptable), so
1989       // give up.
1990       return nullptr;
1991     } else {
1992       // Bail out on a constant expression.
1993       return nullptr;
1994     }
1995   }
1996 
1997   return new ShuffleVectorInst(SI.getTrueValue(), SI.getFalseValue(), Mask);
1998 }
1999 
2000 /// If we have a select of vectors with a scalar condition, try to convert that
2001 /// to a vector select by splatting the condition. A splat may get folded with
2002 /// other operations in IR and having all operands of a select be vector types
2003 /// is likely better for vector codegen.
canonicalizeScalarSelectOfVecs(SelectInst & Sel,InstCombiner & IC)2004 static Instruction *canonicalizeScalarSelectOfVecs(
2005     SelectInst &Sel, InstCombiner &IC) {
2006   auto *Ty = dyn_cast<VectorType>(Sel.getType());
2007   if (!Ty)
2008     return nullptr;
2009 
2010   // We can replace a single-use extract with constant index.
2011   Value *Cond = Sel.getCondition();
2012   if (!match(Cond, m_OneUse(m_ExtractElt(m_Value(), m_ConstantInt()))))
2013     return nullptr;
2014 
2015   // select (extelt V, Index), T, F --> select (splat V, Index), T, F
2016   // Splatting the extracted condition reduces code (we could directly create a
2017   // splat shuffle of the source vector to eliminate the intermediate step).
2018   unsigned NumElts = Ty->getNumElements();
2019   return IC.replaceOperand(Sel, 0, IC.Builder.CreateVectorSplat(NumElts, Cond));
2020 }
2021 
2022 /// Reuse bitcasted operands between a compare and select:
2023 /// select (cmp (bitcast C), (bitcast D)), (bitcast' C), (bitcast' D) -->
2024 /// bitcast (select (cmp (bitcast C), (bitcast D)), (bitcast C), (bitcast D))
foldSelectCmpBitcasts(SelectInst & Sel,InstCombiner::BuilderTy & Builder)2025 static Instruction *foldSelectCmpBitcasts(SelectInst &Sel,
2026                                           InstCombiner::BuilderTy &Builder) {
2027   Value *Cond = Sel.getCondition();
2028   Value *TVal = Sel.getTrueValue();
2029   Value *FVal = Sel.getFalseValue();
2030 
2031   CmpInst::Predicate Pred;
2032   Value *A, *B;
2033   if (!match(Cond, m_Cmp(Pred, m_Value(A), m_Value(B))))
2034     return nullptr;
2035 
2036   // The select condition is a compare instruction. If the select's true/false
2037   // values are already the same as the compare operands, there's nothing to do.
2038   if (TVal == A || TVal == B || FVal == A || FVal == B)
2039     return nullptr;
2040 
2041   Value *C, *D;
2042   if (!match(A, m_BitCast(m_Value(C))) || !match(B, m_BitCast(m_Value(D))))
2043     return nullptr;
2044 
2045   // select (cmp (bitcast C), (bitcast D)), (bitcast TSrc), (bitcast FSrc)
2046   Value *TSrc, *FSrc;
2047   if (!match(TVal, m_BitCast(m_Value(TSrc))) ||
2048       !match(FVal, m_BitCast(m_Value(FSrc))))
2049     return nullptr;
2050 
2051   // If the select true/false values are *different bitcasts* of the same source
2052   // operands, make the select operands the same as the compare operands and
2053   // cast the result. This is the canonical select form for min/max.
2054   Value *NewSel;
2055   if (TSrc == C && FSrc == D) {
2056     // select (cmp (bitcast C), (bitcast D)), (bitcast' C), (bitcast' D) -->
2057     // bitcast (select (cmp A, B), A, B)
2058     NewSel = Builder.CreateSelect(Cond, A, B, "", &Sel);
2059   } else if (TSrc == D && FSrc == C) {
2060     // select (cmp (bitcast C), (bitcast D)), (bitcast' D), (bitcast' C) -->
2061     // bitcast (select (cmp A, B), B, A)
2062     NewSel = Builder.CreateSelect(Cond, B, A, "", &Sel);
2063   } else {
2064     return nullptr;
2065   }
2066   return CastInst::CreateBitOrPointerCast(NewSel, Sel.getType());
2067 }
2068 
2069 /// Try to eliminate select instructions that test the returned flag of cmpxchg
2070 /// instructions.
2071 ///
2072 /// If a select instruction tests the returned flag of a cmpxchg instruction and
2073 /// selects between the returned value of the cmpxchg instruction its compare
2074 /// operand, the result of the select will always be equal to its false value.
2075 /// For example:
2076 ///
2077 ///   %0 = cmpxchg i64* %ptr, i64 %compare, i64 %new_value seq_cst seq_cst
2078 ///   %1 = extractvalue { i64, i1 } %0, 1
2079 ///   %2 = extractvalue { i64, i1 } %0, 0
2080 ///   %3 = select i1 %1, i64 %compare, i64 %2
2081 ///   ret i64 %3
2082 ///
2083 /// The returned value of the cmpxchg instruction (%2) is the original value
2084 /// located at %ptr prior to any update. If the cmpxchg operation succeeds, %2
2085 /// must have been equal to %compare. Thus, the result of the select is always
2086 /// equal to %2, and the code can be simplified to:
2087 ///
2088 ///   %0 = cmpxchg i64* %ptr, i64 %compare, i64 %new_value seq_cst seq_cst
2089 ///   %1 = extractvalue { i64, i1 } %0, 0
2090 ///   ret i64 %1
2091 ///
foldSelectCmpXchg(SelectInst & SI)2092 static Value *foldSelectCmpXchg(SelectInst &SI) {
2093   // A helper that determines if V is an extractvalue instruction whose
2094   // aggregate operand is a cmpxchg instruction and whose single index is equal
2095   // to I. If such conditions are true, the helper returns the cmpxchg
2096   // instruction; otherwise, a nullptr is returned.
2097   auto isExtractFromCmpXchg = [](Value *V, unsigned I) -> AtomicCmpXchgInst * {
2098     auto *Extract = dyn_cast<ExtractValueInst>(V);
2099     if (!Extract)
2100       return nullptr;
2101     if (Extract->getIndices()[0] != I)
2102       return nullptr;
2103     return dyn_cast<AtomicCmpXchgInst>(Extract->getAggregateOperand());
2104   };
2105 
2106   // If the select has a single user, and this user is a select instruction that
2107   // we can simplify, skip the cmpxchg simplification for now.
2108   if (SI.hasOneUse())
2109     if (auto *Select = dyn_cast<SelectInst>(SI.user_back()))
2110       if (Select->getCondition() == SI.getCondition())
2111         if (Select->getFalseValue() == SI.getTrueValue() ||
2112             Select->getTrueValue() == SI.getFalseValue())
2113           return nullptr;
2114 
2115   // Ensure the select condition is the returned flag of a cmpxchg instruction.
2116   auto *CmpXchg = isExtractFromCmpXchg(SI.getCondition(), 1);
2117   if (!CmpXchg)
2118     return nullptr;
2119 
2120   // Check the true value case: The true value of the select is the returned
2121   // value of the same cmpxchg used by the condition, and the false value is the
2122   // cmpxchg instruction's compare operand.
2123   if (auto *X = isExtractFromCmpXchg(SI.getTrueValue(), 0))
2124     if (X == CmpXchg && X->getCompareOperand() == SI.getFalseValue())
2125       return SI.getFalseValue();
2126 
2127   // Check the false value case: The false value of the select is the returned
2128   // value of the same cmpxchg used by the condition, and the true value is the
2129   // cmpxchg instruction's compare operand.
2130   if (auto *X = isExtractFromCmpXchg(SI.getFalseValue(), 0))
2131     if (X == CmpXchg && X->getCompareOperand() == SI.getTrueValue())
2132       return SI.getFalseValue();
2133 
2134   return nullptr;
2135 }
2136 
moveAddAfterMinMax(SelectPatternFlavor SPF,Value * X,Value * Y,InstCombiner::BuilderTy & Builder)2137 static Instruction *moveAddAfterMinMax(SelectPatternFlavor SPF, Value *X,
2138                                        Value *Y,
2139                                        InstCombiner::BuilderTy &Builder) {
2140   assert(SelectPatternResult::isMinOrMax(SPF) && "Expected min/max pattern");
2141   bool IsUnsigned = SPF == SelectPatternFlavor::SPF_UMIN ||
2142                     SPF == SelectPatternFlavor::SPF_UMAX;
2143   // TODO: If InstSimplify could fold all cases where C2 <= C1, we could change
2144   // the constant value check to an assert.
2145   Value *A;
2146   const APInt *C1, *C2;
2147   if (IsUnsigned && match(X, m_NUWAdd(m_Value(A), m_APInt(C1))) &&
2148       match(Y, m_APInt(C2)) && C2->uge(*C1) && X->hasNUses(2)) {
2149     // umin (add nuw A, C1), C2 --> add nuw (umin A, C2 - C1), C1
2150     // umax (add nuw A, C1), C2 --> add nuw (umax A, C2 - C1), C1
2151     Value *NewMinMax = createMinMax(Builder, SPF, A,
2152                                     ConstantInt::get(X->getType(), *C2 - *C1));
2153     return BinaryOperator::CreateNUW(BinaryOperator::Add, NewMinMax,
2154                                      ConstantInt::get(X->getType(), *C1));
2155   }
2156 
2157   if (!IsUnsigned && match(X, m_NSWAdd(m_Value(A), m_APInt(C1))) &&
2158       match(Y, m_APInt(C2)) && X->hasNUses(2)) {
2159     bool Overflow;
2160     APInt Diff = C2->ssub_ov(*C1, Overflow);
2161     if (!Overflow) {
2162       // smin (add nsw A, C1), C2 --> add nsw (smin A, C2 - C1), C1
2163       // smax (add nsw A, C1), C2 --> add nsw (smax A, C2 - C1), C1
2164       Value *NewMinMax = createMinMax(Builder, SPF, A,
2165                                       ConstantInt::get(X->getType(), Diff));
2166       return BinaryOperator::CreateNSW(BinaryOperator::Add, NewMinMax,
2167                                        ConstantInt::get(X->getType(), *C1));
2168     }
2169   }
2170 
2171   return nullptr;
2172 }
2173 
2174 /// Match a sadd_sat or ssub_sat which is using min/max to clamp the value.
matchSAddSubSat(SelectInst & MinMax1)2175 Instruction *InstCombiner::matchSAddSubSat(SelectInst &MinMax1) {
2176   Type *Ty = MinMax1.getType();
2177 
2178   // We are looking for a tree of:
2179   // max(INT_MIN, min(INT_MAX, add(sext(A), sext(B))))
2180   // Where the min and max could be reversed
2181   Instruction *MinMax2;
2182   BinaryOperator *AddSub;
2183   const APInt *MinValue, *MaxValue;
2184   if (match(&MinMax1, m_SMin(m_Instruction(MinMax2), m_APInt(MaxValue)))) {
2185     if (!match(MinMax2, m_SMax(m_BinOp(AddSub), m_APInt(MinValue))))
2186       return nullptr;
2187   } else if (match(&MinMax1,
2188                    m_SMax(m_Instruction(MinMax2), m_APInt(MinValue)))) {
2189     if (!match(MinMax2, m_SMin(m_BinOp(AddSub), m_APInt(MaxValue))))
2190       return nullptr;
2191   } else
2192     return nullptr;
2193 
2194   // Check that the constants clamp a saturate, and that the new type would be
2195   // sensible to convert to.
2196   if (!(*MaxValue + 1).isPowerOf2() || -*MinValue != *MaxValue + 1)
2197     return nullptr;
2198   // In what bitwidth can this be treated as saturating arithmetics?
2199   unsigned NewBitWidth = (*MaxValue + 1).logBase2() + 1;
2200   // FIXME: This isn't quite right for vectors, but using the scalar type is a
2201   // good first approximation for what should be done there.
2202   if (!shouldChangeType(Ty->getScalarType()->getIntegerBitWidth(), NewBitWidth))
2203     return nullptr;
2204 
2205   // Also make sure that the number of uses is as expected. The "3"s are for the
2206   // the two items of min/max (the compare and the select).
2207   if (MinMax2->hasNUsesOrMore(3) || AddSub->hasNUsesOrMore(3))
2208     return nullptr;
2209 
2210   // Create the new type (which can be a vector type)
2211   Type *NewTy = Ty->getWithNewBitWidth(NewBitWidth);
2212   // Match the two extends from the add/sub
2213   Value *A, *B;
2214   if(!match(AddSub, m_BinOp(m_SExt(m_Value(A)), m_SExt(m_Value(B)))))
2215     return nullptr;
2216   // And check the incoming values are of a type smaller than or equal to the
2217   // size of the saturation. Otherwise the higher bits can cause different
2218   // results.
2219   if (A->getType()->getScalarSizeInBits() > NewBitWidth ||
2220       B->getType()->getScalarSizeInBits() > NewBitWidth)
2221     return nullptr;
2222 
2223   Intrinsic::ID IntrinsicID;
2224   if (AddSub->getOpcode() == Instruction::Add)
2225     IntrinsicID = Intrinsic::sadd_sat;
2226   else if (AddSub->getOpcode() == Instruction::Sub)
2227     IntrinsicID = Intrinsic::ssub_sat;
2228   else
2229     return nullptr;
2230 
2231   // Finally create and return the sat intrinsic, truncated to the new type
2232   Function *F = Intrinsic::getDeclaration(MinMax1.getModule(), IntrinsicID, NewTy);
2233   Value *AT = Builder.CreateSExt(A, NewTy);
2234   Value *BT = Builder.CreateSExt(B, NewTy);
2235   Value *Sat = Builder.CreateCall(F, {AT, BT});
2236   return CastInst::Create(Instruction::SExt, Sat, Ty);
2237 }
2238 
2239 /// Reduce a sequence of min/max with a common operand.
factorizeMinMaxTree(SelectPatternFlavor SPF,Value * LHS,Value * RHS,InstCombiner::BuilderTy & Builder)2240 static Instruction *factorizeMinMaxTree(SelectPatternFlavor SPF, Value *LHS,
2241                                         Value *RHS,
2242                                         InstCombiner::BuilderTy &Builder) {
2243   assert(SelectPatternResult::isMinOrMax(SPF) && "Expected a min/max");
2244   // TODO: Allow FP min/max with nnan/nsz.
2245   if (!LHS->getType()->isIntOrIntVectorTy())
2246     return nullptr;
2247 
2248   // Match 3 of the same min/max ops. Example: umin(umin(), umin()).
2249   Value *A, *B, *C, *D;
2250   SelectPatternResult L = matchSelectPattern(LHS, A, B);
2251   SelectPatternResult R = matchSelectPattern(RHS, C, D);
2252   if (SPF != L.Flavor || L.Flavor != R.Flavor)
2253     return nullptr;
2254 
2255   // Look for a common operand. The use checks are different than usual because
2256   // a min/max pattern typically has 2 uses of each op: 1 by the cmp and 1 by
2257   // the select.
2258   Value *MinMaxOp = nullptr;
2259   Value *ThirdOp = nullptr;
2260   if (!LHS->hasNUsesOrMore(3) && RHS->hasNUsesOrMore(3)) {
2261     // If the LHS is only used in this chain and the RHS is used outside of it,
2262     // reuse the RHS min/max because that will eliminate the LHS.
2263     if (D == A || C == A) {
2264       // min(min(a, b), min(c, a)) --> min(min(c, a), b)
2265       // min(min(a, b), min(a, d)) --> min(min(a, d), b)
2266       MinMaxOp = RHS;
2267       ThirdOp = B;
2268     } else if (D == B || C == B) {
2269       // min(min(a, b), min(c, b)) --> min(min(c, b), a)
2270       // min(min(a, b), min(b, d)) --> min(min(b, d), a)
2271       MinMaxOp = RHS;
2272       ThirdOp = A;
2273     }
2274   } else if (!RHS->hasNUsesOrMore(3)) {
2275     // Reuse the LHS. This will eliminate the RHS.
2276     if (D == A || D == B) {
2277       // min(min(a, b), min(c, a)) --> min(min(a, b), c)
2278       // min(min(a, b), min(c, b)) --> min(min(a, b), c)
2279       MinMaxOp = LHS;
2280       ThirdOp = C;
2281     } else if (C == A || C == B) {
2282       // min(min(a, b), min(b, d)) --> min(min(a, b), d)
2283       // min(min(a, b), min(c, b)) --> min(min(a, b), d)
2284       MinMaxOp = LHS;
2285       ThirdOp = D;
2286     }
2287   }
2288   if (!MinMaxOp || !ThirdOp)
2289     return nullptr;
2290 
2291   CmpInst::Predicate P = getMinMaxPred(SPF);
2292   Value *CmpABC = Builder.CreateICmp(P, MinMaxOp, ThirdOp);
2293   return SelectInst::Create(CmpABC, MinMaxOp, ThirdOp);
2294 }
2295 
2296 /// Try to reduce a rotate pattern that includes a compare and select into a
2297 /// funnel shift intrinsic. Example:
2298 /// rotl32(a, b) --> (b == 0 ? a : ((a >> (32 - b)) | (a << b)))
2299 ///              --> call llvm.fshl.i32(a, a, b)
foldSelectRotate(SelectInst & Sel)2300 static Instruction *foldSelectRotate(SelectInst &Sel) {
2301   // The false value of the select must be a rotate of the true value.
2302   Value *Or0, *Or1;
2303   if (!match(Sel.getFalseValue(), m_OneUse(m_Or(m_Value(Or0), m_Value(Or1)))))
2304     return nullptr;
2305 
2306   Value *TVal = Sel.getTrueValue();
2307   Value *SA0, *SA1;
2308   if (!match(Or0, m_OneUse(m_LogicalShift(m_Specific(TVal), m_Value(SA0)))) ||
2309       !match(Or1, m_OneUse(m_LogicalShift(m_Specific(TVal), m_Value(SA1)))))
2310     return nullptr;
2311 
2312   auto ShiftOpcode0 = cast<BinaryOperator>(Or0)->getOpcode();
2313   auto ShiftOpcode1 = cast<BinaryOperator>(Or1)->getOpcode();
2314   if (ShiftOpcode0 == ShiftOpcode1)
2315     return nullptr;
2316 
2317   // We have one of these patterns so far:
2318   // select ?, TVal, (or (lshr TVal, SA0), (shl TVal, SA1))
2319   // select ?, TVal, (or (shl TVal, SA0), (lshr TVal, SA1))
2320   // This must be a power-of-2 rotate for a bitmasking transform to be valid.
2321   unsigned Width = Sel.getType()->getScalarSizeInBits();
2322   if (!isPowerOf2_32(Width))
2323     return nullptr;
2324 
2325   // Check the shift amounts to see if they are an opposite pair.
2326   Value *ShAmt;
2327   if (match(SA1, m_OneUse(m_Sub(m_SpecificInt(Width), m_Specific(SA0)))))
2328     ShAmt = SA0;
2329   else if (match(SA0, m_OneUse(m_Sub(m_SpecificInt(Width), m_Specific(SA1)))))
2330     ShAmt = SA1;
2331   else
2332     return nullptr;
2333 
2334   // Finally, see if the select is filtering out a shift-by-zero.
2335   Value *Cond = Sel.getCondition();
2336   ICmpInst::Predicate Pred;
2337   if (!match(Cond, m_OneUse(m_ICmp(Pred, m_Specific(ShAmt), m_ZeroInt()))) ||
2338       Pred != ICmpInst::ICMP_EQ)
2339     return nullptr;
2340 
2341   // This is a rotate that avoids shift-by-bitwidth UB in a suboptimal way.
2342   // Convert to funnel shift intrinsic.
2343   bool IsFshl = (ShAmt == SA0 && ShiftOpcode0 == BinaryOperator::Shl) ||
2344                 (ShAmt == SA1 && ShiftOpcode1 == BinaryOperator::Shl);
2345   Intrinsic::ID IID = IsFshl ? Intrinsic::fshl : Intrinsic::fshr;
2346   Function *F = Intrinsic::getDeclaration(Sel.getModule(), IID, Sel.getType());
2347   return IntrinsicInst::Create(F, { TVal, TVal, ShAmt });
2348 }
2349 
foldSelectToCopysign(SelectInst & Sel,InstCombiner::BuilderTy & Builder)2350 static Instruction *foldSelectToCopysign(SelectInst &Sel,
2351                                          InstCombiner::BuilderTy &Builder) {
2352   Value *Cond = Sel.getCondition();
2353   Value *TVal = Sel.getTrueValue();
2354   Value *FVal = Sel.getFalseValue();
2355   Type *SelType = Sel.getType();
2356 
2357   // Match select ?, TC, FC where the constants are equal but negated.
2358   // TODO: Generalize to handle a negated variable operand?
2359   const APFloat *TC, *FC;
2360   if (!match(TVal, m_APFloat(TC)) || !match(FVal, m_APFloat(FC)) ||
2361       !abs(*TC).bitwiseIsEqual(abs(*FC)))
2362     return nullptr;
2363 
2364   assert(TC != FC && "Expected equal select arms to simplify");
2365 
2366   Value *X;
2367   const APInt *C;
2368   bool IsTrueIfSignSet;
2369   ICmpInst::Predicate Pred;
2370   if (!match(Cond, m_OneUse(m_ICmp(Pred, m_BitCast(m_Value(X)), m_APInt(C)))) ||
2371       !isSignBitCheck(Pred, *C, IsTrueIfSignSet) || X->getType() != SelType)
2372     return nullptr;
2373 
2374   // If needed, negate the value that will be the sign argument of the copysign:
2375   // (bitcast X) <  0 ? -TC :  TC --> copysign(TC,  X)
2376   // (bitcast X) <  0 ?  TC : -TC --> copysign(TC, -X)
2377   // (bitcast X) >= 0 ? -TC :  TC --> copysign(TC, -X)
2378   // (bitcast X) >= 0 ?  TC : -TC --> copysign(TC,  X)
2379   if (IsTrueIfSignSet ^ TC->isNegative())
2380     X = Builder.CreateFNegFMF(X, &Sel);
2381 
2382   // Canonicalize the magnitude argument as the positive constant since we do
2383   // not care about its sign.
2384   Value *MagArg = TC->isNegative() ? FVal : TVal;
2385   Function *F = Intrinsic::getDeclaration(Sel.getModule(), Intrinsic::copysign,
2386                                           Sel.getType());
2387   Instruction *CopySign = IntrinsicInst::Create(F, { MagArg, X });
2388   CopySign->setFastMathFlags(Sel.getFastMathFlags());
2389   return CopySign;
2390 }
2391 
foldVectorSelect(SelectInst & Sel)2392 Instruction *InstCombiner::foldVectorSelect(SelectInst &Sel) {
2393   auto *VecTy = dyn_cast<FixedVectorType>(Sel.getType());
2394   if (!VecTy)
2395     return nullptr;
2396 
2397   unsigned NumElts = VecTy->getNumElements();
2398   APInt UndefElts(NumElts, 0);
2399   APInt AllOnesEltMask(APInt::getAllOnesValue(NumElts));
2400   if (Value *V = SimplifyDemandedVectorElts(&Sel, AllOnesEltMask, UndefElts)) {
2401     if (V != &Sel)
2402       return replaceInstUsesWith(Sel, V);
2403     return &Sel;
2404   }
2405 
2406   // A select of a "select shuffle" with a common operand can be rearranged
2407   // to select followed by "select shuffle". Because of poison, this only works
2408   // in the case of a shuffle with no undefined mask elements.
2409   Value *Cond = Sel.getCondition();
2410   Value *TVal = Sel.getTrueValue();
2411   Value *FVal = Sel.getFalseValue();
2412   Value *X, *Y;
2413   ArrayRef<int> Mask;
2414   if (match(TVal, m_OneUse(m_Shuffle(m_Value(X), m_Value(Y), m_Mask(Mask)))) &&
2415       !is_contained(Mask, UndefMaskElem) &&
2416       cast<ShuffleVectorInst>(TVal)->isSelect()) {
2417     if (X == FVal) {
2418       // select Cond, (shuf_sel X, Y), X --> shuf_sel X, (select Cond, Y, X)
2419       Value *NewSel = Builder.CreateSelect(Cond, Y, X, "sel", &Sel);
2420       return new ShuffleVectorInst(X, NewSel, Mask);
2421     }
2422     if (Y == FVal) {
2423       // select Cond, (shuf_sel X, Y), Y --> shuf_sel (select Cond, X, Y), Y
2424       Value *NewSel = Builder.CreateSelect(Cond, X, Y, "sel", &Sel);
2425       return new ShuffleVectorInst(NewSel, Y, Mask);
2426     }
2427   }
2428   if (match(FVal, m_OneUse(m_Shuffle(m_Value(X), m_Value(Y), m_Mask(Mask)))) &&
2429       !is_contained(Mask, UndefMaskElem) &&
2430       cast<ShuffleVectorInst>(FVal)->isSelect()) {
2431     if (X == TVal) {
2432       // select Cond, X, (shuf_sel X, Y) --> shuf_sel X, (select Cond, X, Y)
2433       Value *NewSel = Builder.CreateSelect(Cond, X, Y, "sel", &Sel);
2434       return new ShuffleVectorInst(X, NewSel, Mask);
2435     }
2436     if (Y == TVal) {
2437       // select Cond, Y, (shuf_sel X, Y) --> shuf_sel (select Cond, Y, X), Y
2438       Value *NewSel = Builder.CreateSelect(Cond, Y, X, "sel", &Sel);
2439       return new ShuffleVectorInst(NewSel, Y, Mask);
2440     }
2441   }
2442 
2443   return nullptr;
2444 }
2445 
foldSelectToPhiImpl(SelectInst & Sel,BasicBlock * BB,const DominatorTree & DT,InstCombiner::BuilderTy & Builder)2446 static Instruction *foldSelectToPhiImpl(SelectInst &Sel, BasicBlock *BB,
2447                                         const DominatorTree &DT,
2448                                         InstCombiner::BuilderTy &Builder) {
2449   // Find the block's immediate dominator that ends with a conditional branch
2450   // that matches select's condition (maybe inverted).
2451   auto *IDomNode = DT[BB]->getIDom();
2452   if (!IDomNode)
2453     return nullptr;
2454   BasicBlock *IDom = IDomNode->getBlock();
2455 
2456   Value *Cond = Sel.getCondition();
2457   Value *IfTrue, *IfFalse;
2458   BasicBlock *TrueSucc, *FalseSucc;
2459   if (match(IDom->getTerminator(),
2460             m_Br(m_Specific(Cond), m_BasicBlock(TrueSucc),
2461                  m_BasicBlock(FalseSucc)))) {
2462     IfTrue = Sel.getTrueValue();
2463     IfFalse = Sel.getFalseValue();
2464   } else if (match(IDom->getTerminator(),
2465                    m_Br(m_Not(m_Specific(Cond)), m_BasicBlock(TrueSucc),
2466                         m_BasicBlock(FalseSucc)))) {
2467     IfTrue = Sel.getFalseValue();
2468     IfFalse = Sel.getTrueValue();
2469   } else
2470     return nullptr;
2471 
2472   // We want to replace select %cond, %a, %b with a phi that takes value %a
2473   // for all incoming edges that are dominated by condition `%cond == true`,
2474   // and value %b for edges dominated by condition `%cond == false`. If %a
2475   // or %b are also phis from the same basic block, we can go further and take
2476   // their incoming values from the corresponding blocks.
2477   BasicBlockEdge TrueEdge(IDom, TrueSucc);
2478   BasicBlockEdge FalseEdge(IDom, FalseSucc);
2479   DenseMap<BasicBlock *, Value *> Inputs;
2480   for (auto *Pred : predecessors(BB)) {
2481     // Check implication.
2482     BasicBlockEdge Incoming(Pred, BB);
2483     if (DT.dominates(TrueEdge, Incoming))
2484       Inputs[Pred] = IfTrue->DoPHITranslation(BB, Pred);
2485     else if (DT.dominates(FalseEdge, Incoming))
2486       Inputs[Pred] = IfFalse->DoPHITranslation(BB, Pred);
2487     else
2488       return nullptr;
2489     // Check availability.
2490     if (auto *Insn = dyn_cast<Instruction>(Inputs[Pred]))
2491       if (!DT.dominates(Insn, Pred->getTerminator()))
2492         return nullptr;
2493   }
2494 
2495   Builder.SetInsertPoint(&*BB->begin());
2496   auto *PN = Builder.CreatePHI(Sel.getType(), Inputs.size());
2497   for (auto *Pred : predecessors(BB))
2498     PN->addIncoming(Inputs[Pred], Pred);
2499   PN->takeName(&Sel);
2500   return PN;
2501 }
2502 
foldSelectToPhi(SelectInst & Sel,const DominatorTree & DT,InstCombiner::BuilderTy & Builder)2503 static Instruction *foldSelectToPhi(SelectInst &Sel, const DominatorTree &DT,
2504                                     InstCombiner::BuilderTy &Builder) {
2505   // Try to replace this select with Phi in one of these blocks.
2506   SmallSetVector<BasicBlock *, 4> CandidateBlocks;
2507   CandidateBlocks.insert(Sel.getParent());
2508   for (Value *V : Sel.operands())
2509     if (auto *I = dyn_cast<Instruction>(V))
2510       CandidateBlocks.insert(I->getParent());
2511 
2512   for (BasicBlock *BB : CandidateBlocks)
2513     if (auto *PN = foldSelectToPhiImpl(Sel, BB, DT, Builder))
2514       return PN;
2515   return nullptr;
2516 }
2517 
visitSelectInst(SelectInst & SI)2518 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
2519   Value *CondVal = SI.getCondition();
2520   Value *TrueVal = SI.getTrueValue();
2521   Value *FalseVal = SI.getFalseValue();
2522   Type *SelType = SI.getType();
2523 
2524   // FIXME: Remove this workaround when freeze related patches are done.
2525   // For select with undef operand which feeds into an equality comparison,
2526   // don't simplify it so loop unswitch can know the equality comparison
2527   // may have an undef operand. This is a workaround for PR31652 caused by
2528   // descrepancy about branch on undef between LoopUnswitch and GVN.
2529   if (isa<UndefValue>(TrueVal) || isa<UndefValue>(FalseVal)) {
2530     if (llvm::any_of(SI.users(), [&](User *U) {
2531           ICmpInst *CI = dyn_cast<ICmpInst>(U);
2532           if (CI && CI->isEquality())
2533             return true;
2534           return false;
2535         })) {
2536       return nullptr;
2537     }
2538   }
2539 
2540   if (Value *V = SimplifySelectInst(CondVal, TrueVal, FalseVal,
2541                                     SQ.getWithInstruction(&SI)))
2542     return replaceInstUsesWith(SI, V);
2543 
2544   if (Instruction *I = canonicalizeSelectToShuffle(SI))
2545     return I;
2546 
2547   if (Instruction *I = canonicalizeScalarSelectOfVecs(SI, *this))
2548     return I;
2549 
2550   CmpInst::Predicate Pred;
2551 
2552   if (SelType->isIntOrIntVectorTy(1) &&
2553       TrueVal->getType() == CondVal->getType()) {
2554     if (match(TrueVal, m_One())) {
2555       // Change: A = select B, true, C --> A = or B, C
2556       return BinaryOperator::CreateOr(CondVal, FalseVal);
2557     }
2558     if (match(TrueVal, m_Zero())) {
2559       // Change: A = select B, false, C --> A = and !B, C
2560       Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName());
2561       return BinaryOperator::CreateAnd(NotCond, FalseVal);
2562     }
2563     if (match(FalseVal, m_Zero())) {
2564       // Change: A = select B, C, false --> A = and B, C
2565       return BinaryOperator::CreateAnd(CondVal, TrueVal);
2566     }
2567     if (match(FalseVal, m_One())) {
2568       // Change: A = select B, C, true --> A = or !B, C
2569       Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName());
2570       return BinaryOperator::CreateOr(NotCond, TrueVal);
2571     }
2572 
2573     // select a, a, b  -> a | b
2574     // select a, b, a  -> a & b
2575     if (CondVal == TrueVal)
2576       return BinaryOperator::CreateOr(CondVal, FalseVal);
2577     if (CondVal == FalseVal)
2578       return BinaryOperator::CreateAnd(CondVal, TrueVal);
2579 
2580     // select a, ~a, b -> (~a) & b
2581     // select a, b, ~a -> (~a) | b
2582     if (match(TrueVal, m_Not(m_Specific(CondVal))))
2583       return BinaryOperator::CreateAnd(TrueVal, FalseVal);
2584     if (match(FalseVal, m_Not(m_Specific(CondVal))))
2585       return BinaryOperator::CreateOr(TrueVal, FalseVal);
2586   }
2587 
2588   // Selecting between two integer or vector splat integer constants?
2589   //
2590   // Note that we don't handle a scalar select of vectors:
2591   // select i1 %c, <2 x i8> <1, 1>, <2 x i8> <0, 0>
2592   // because that may need 3 instructions to splat the condition value:
2593   // extend, insertelement, shufflevector.
2594   if (SelType->isIntOrIntVectorTy() &&
2595       CondVal->getType()->isVectorTy() == SelType->isVectorTy()) {
2596     // select C, 1, 0 -> zext C to int
2597     if (match(TrueVal, m_One()) && match(FalseVal, m_Zero()))
2598       return new ZExtInst(CondVal, SelType);
2599 
2600     // select C, -1, 0 -> sext C to int
2601     if (match(TrueVal, m_AllOnes()) && match(FalseVal, m_Zero()))
2602       return new SExtInst(CondVal, SelType);
2603 
2604     // select C, 0, 1 -> zext !C to int
2605     if (match(TrueVal, m_Zero()) && match(FalseVal, m_One())) {
2606       Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName());
2607       return new ZExtInst(NotCond, SelType);
2608     }
2609 
2610     // select C, 0, -1 -> sext !C to int
2611     if (match(TrueVal, m_Zero()) && match(FalseVal, m_AllOnes())) {
2612       Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName());
2613       return new SExtInst(NotCond, SelType);
2614     }
2615   }
2616 
2617   // See if we are selecting two values based on a comparison of the two values.
2618   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
2619     Value *Cmp0 = FCI->getOperand(0), *Cmp1 = FCI->getOperand(1);
2620     if ((Cmp0 == TrueVal && Cmp1 == FalseVal) ||
2621         (Cmp0 == FalseVal && Cmp1 == TrueVal)) {
2622       // Canonicalize to use ordered comparisons by swapping the select
2623       // operands.
2624       //
2625       // e.g.
2626       // (X ugt Y) ? X : Y -> (X ole Y) ? Y : X
2627       if (FCI->hasOneUse() && FCmpInst::isUnordered(FCI->getPredicate())) {
2628         FCmpInst::Predicate InvPred = FCI->getInversePredicate();
2629         IRBuilder<>::FastMathFlagGuard FMFG(Builder);
2630         // FIXME: The FMF should propagate from the select, not the fcmp.
2631         Builder.setFastMathFlags(FCI->getFastMathFlags());
2632         Value *NewCond = Builder.CreateFCmp(InvPred, Cmp0, Cmp1,
2633                                             FCI->getName() + ".inv");
2634         Value *NewSel = Builder.CreateSelect(NewCond, FalseVal, TrueVal);
2635         return replaceInstUsesWith(SI, NewSel);
2636       }
2637 
2638       // NOTE: if we wanted to, this is where to detect MIN/MAX
2639     }
2640   }
2641 
2642   // Canonicalize select with fcmp to fabs(). -0.0 makes this tricky. We need
2643   // fast-math-flags (nsz) or fsub with +0.0 (not fneg) for this to work. We
2644   // also require nnan because we do not want to unintentionally change the
2645   // sign of a NaN value.
2646   // FIXME: These folds should test/propagate FMF from the select, not the
2647   //        fsub or fneg.
2648   // (X <= +/-0.0) ? (0.0 - X) : X --> fabs(X)
2649   Instruction *FSub;
2650   if (match(CondVal, m_FCmp(Pred, m_Specific(FalseVal), m_AnyZeroFP())) &&
2651       match(TrueVal, m_FSub(m_PosZeroFP(), m_Specific(FalseVal))) &&
2652       match(TrueVal, m_Instruction(FSub)) && FSub->hasNoNaNs() &&
2653       (Pred == FCmpInst::FCMP_OLE || Pred == FCmpInst::FCMP_ULE)) {
2654     Value *Fabs = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, FalseVal, FSub);
2655     return replaceInstUsesWith(SI, Fabs);
2656   }
2657   // (X >  +/-0.0) ? X : (0.0 - X) --> fabs(X)
2658   if (match(CondVal, m_FCmp(Pred, m_Specific(TrueVal), m_AnyZeroFP())) &&
2659       match(FalseVal, m_FSub(m_PosZeroFP(), m_Specific(TrueVal))) &&
2660       match(FalseVal, m_Instruction(FSub)) && FSub->hasNoNaNs() &&
2661       (Pred == FCmpInst::FCMP_OGT || Pred == FCmpInst::FCMP_UGT)) {
2662     Value *Fabs = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, TrueVal, FSub);
2663     return replaceInstUsesWith(SI, Fabs);
2664   }
2665   // With nnan and nsz:
2666   // (X <  +/-0.0) ? -X : X --> fabs(X)
2667   // (X <= +/-0.0) ? -X : X --> fabs(X)
2668   Instruction *FNeg;
2669   if (match(CondVal, m_FCmp(Pred, m_Specific(FalseVal), m_AnyZeroFP())) &&
2670       match(TrueVal, m_FNeg(m_Specific(FalseVal))) &&
2671       match(TrueVal, m_Instruction(FNeg)) &&
2672       FNeg->hasNoNaNs() && FNeg->hasNoSignedZeros() &&
2673       (Pred == FCmpInst::FCMP_OLT || Pred == FCmpInst::FCMP_OLE ||
2674        Pred == FCmpInst::FCMP_ULT || Pred == FCmpInst::FCMP_ULE)) {
2675     Value *Fabs = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, FalseVal, FNeg);
2676     return replaceInstUsesWith(SI, Fabs);
2677   }
2678   // With nnan and nsz:
2679   // (X >  +/-0.0) ? X : -X --> fabs(X)
2680   // (X >= +/-0.0) ? X : -X --> fabs(X)
2681   if (match(CondVal, m_FCmp(Pred, m_Specific(TrueVal), m_AnyZeroFP())) &&
2682       match(FalseVal, m_FNeg(m_Specific(TrueVal))) &&
2683       match(FalseVal, m_Instruction(FNeg)) &&
2684       FNeg->hasNoNaNs() && FNeg->hasNoSignedZeros() &&
2685       (Pred == FCmpInst::FCMP_OGT || Pred == FCmpInst::FCMP_OGE ||
2686        Pred == FCmpInst::FCMP_UGT || Pred == FCmpInst::FCMP_UGE)) {
2687     Value *Fabs = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, TrueVal, FNeg);
2688     return replaceInstUsesWith(SI, Fabs);
2689   }
2690 
2691   // See if we are selecting two values based on a comparison of the two values.
2692   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
2693     if (Instruction *Result = foldSelectInstWithICmp(SI, ICI))
2694       return Result;
2695 
2696   if (Instruction *Add = foldAddSubSelect(SI, Builder))
2697     return Add;
2698   if (Instruction *Add = foldOverflowingAddSubSelect(SI, Builder))
2699     return Add;
2700   if (Instruction *Or = foldSetClearBits(SI, Builder))
2701     return Or;
2702 
2703   // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
2704   auto *TI = dyn_cast<Instruction>(TrueVal);
2705   auto *FI = dyn_cast<Instruction>(FalseVal);
2706   if (TI && FI && TI->getOpcode() == FI->getOpcode())
2707     if (Instruction *IV = foldSelectOpOp(SI, TI, FI))
2708       return IV;
2709 
2710   if (Instruction *I = foldSelectExtConst(SI))
2711     return I;
2712 
2713   // See if we can fold the select into one of our operands.
2714   if (SelType->isIntOrIntVectorTy() || SelType->isFPOrFPVectorTy()) {
2715     if (Instruction *FoldI = foldSelectIntoOp(SI, TrueVal, FalseVal))
2716       return FoldI;
2717 
2718     Value *LHS, *RHS;
2719     Instruction::CastOps CastOp;
2720     SelectPatternResult SPR = matchSelectPattern(&SI, LHS, RHS, &CastOp);
2721     auto SPF = SPR.Flavor;
2722     if (SPF) {
2723       Value *LHS2, *RHS2;
2724       if (SelectPatternFlavor SPF2 = matchSelectPattern(LHS, LHS2, RHS2).Flavor)
2725         if (Instruction *R = foldSPFofSPF(cast<Instruction>(LHS), SPF2, LHS2,
2726                                           RHS2, SI, SPF, RHS))
2727           return R;
2728       if (SelectPatternFlavor SPF2 = matchSelectPattern(RHS, LHS2, RHS2).Flavor)
2729         if (Instruction *R = foldSPFofSPF(cast<Instruction>(RHS), SPF2, LHS2,
2730                                           RHS2, SI, SPF, LHS))
2731           return R;
2732       // TODO.
2733       // ABS(-X) -> ABS(X)
2734     }
2735 
2736     if (SelectPatternResult::isMinOrMax(SPF)) {
2737       // Canonicalize so that
2738       // - type casts are outside select patterns.
2739       // - float clamp is transformed to min/max pattern
2740 
2741       bool IsCastNeeded = LHS->getType() != SelType;
2742       Value *CmpLHS = cast<CmpInst>(CondVal)->getOperand(0);
2743       Value *CmpRHS = cast<CmpInst>(CondVal)->getOperand(1);
2744       if (IsCastNeeded ||
2745           (LHS->getType()->isFPOrFPVectorTy() &&
2746            ((CmpLHS != LHS && CmpLHS != RHS) ||
2747             (CmpRHS != LHS && CmpRHS != RHS)))) {
2748         CmpInst::Predicate MinMaxPred = getMinMaxPred(SPF, SPR.Ordered);
2749 
2750         Value *Cmp;
2751         if (CmpInst::isIntPredicate(MinMaxPred)) {
2752           Cmp = Builder.CreateICmp(MinMaxPred, LHS, RHS);
2753         } else {
2754           IRBuilder<>::FastMathFlagGuard FMFG(Builder);
2755           auto FMF =
2756               cast<FPMathOperator>(SI.getCondition())->getFastMathFlags();
2757           Builder.setFastMathFlags(FMF);
2758           Cmp = Builder.CreateFCmp(MinMaxPred, LHS, RHS);
2759         }
2760 
2761         Value *NewSI = Builder.CreateSelect(Cmp, LHS, RHS, SI.getName(), &SI);
2762         if (!IsCastNeeded)
2763           return replaceInstUsesWith(SI, NewSI);
2764 
2765         Value *NewCast = Builder.CreateCast(CastOp, NewSI, SelType);
2766         return replaceInstUsesWith(SI, NewCast);
2767       }
2768 
2769       // MAX(~a, ~b) -> ~MIN(a, b)
2770       // MAX(~a, C)  -> ~MIN(a, ~C)
2771       // MIN(~a, ~b) -> ~MAX(a, b)
2772       // MIN(~a, C)  -> ~MAX(a, ~C)
2773       auto moveNotAfterMinMax = [&](Value *X, Value *Y) -> Instruction * {
2774         Value *A;
2775         if (match(X, m_Not(m_Value(A))) && !X->hasNUsesOrMore(3) &&
2776             !isFreeToInvert(A, A->hasOneUse()) &&
2777             // Passing false to only consider m_Not and constants.
2778             isFreeToInvert(Y, false)) {
2779           Value *B = Builder.CreateNot(Y);
2780           Value *NewMinMax = createMinMax(Builder, getInverseMinMaxFlavor(SPF),
2781                                           A, B);
2782           // Copy the profile metadata.
2783           if (MDNode *MD = SI.getMetadata(LLVMContext::MD_prof)) {
2784             cast<SelectInst>(NewMinMax)->setMetadata(LLVMContext::MD_prof, MD);
2785             // Swap the metadata if the operands are swapped.
2786             if (X == SI.getFalseValue() && Y == SI.getTrueValue())
2787               cast<SelectInst>(NewMinMax)->swapProfMetadata();
2788           }
2789 
2790           return BinaryOperator::CreateNot(NewMinMax);
2791         }
2792 
2793         return nullptr;
2794       };
2795 
2796       if (Instruction *I = moveNotAfterMinMax(LHS, RHS))
2797         return I;
2798       if (Instruction *I = moveNotAfterMinMax(RHS, LHS))
2799         return I;
2800 
2801       if (Instruction *I = moveAddAfterMinMax(SPF, LHS, RHS, Builder))
2802         return I;
2803 
2804       if (Instruction *I = factorizeMinMaxTree(SPF, LHS, RHS, Builder))
2805         return I;
2806       if (Instruction *I = matchSAddSubSat(SI))
2807         return I;
2808     }
2809   }
2810 
2811   // Canonicalize select of FP values where NaN and -0.0 are not valid as
2812   // minnum/maxnum intrinsics.
2813   if (isa<FPMathOperator>(SI) && SI.hasNoNaNs() && SI.hasNoSignedZeros()) {
2814     Value *X, *Y;
2815     if (match(&SI, m_OrdFMax(m_Value(X), m_Value(Y))))
2816       return replaceInstUsesWith(
2817           SI, Builder.CreateBinaryIntrinsic(Intrinsic::maxnum, X, Y, &SI));
2818 
2819     if (match(&SI, m_OrdFMin(m_Value(X), m_Value(Y))))
2820       return replaceInstUsesWith(
2821           SI, Builder.CreateBinaryIntrinsic(Intrinsic::minnum, X, Y, &SI));
2822   }
2823 
2824   // See if we can fold the select into a phi node if the condition is a select.
2825   if (auto *PN = dyn_cast<PHINode>(SI.getCondition()))
2826     // The true/false values have to be live in the PHI predecessor's blocks.
2827     if (canSelectOperandBeMappingIntoPredBlock(TrueVal, SI) &&
2828         canSelectOperandBeMappingIntoPredBlock(FalseVal, SI))
2829       if (Instruction *NV = foldOpIntoPhi(SI, PN))
2830         return NV;
2831 
2832   if (SelectInst *TrueSI = dyn_cast<SelectInst>(TrueVal)) {
2833     if (TrueSI->getCondition()->getType() == CondVal->getType()) {
2834       // select(C, select(C, a, b), c) -> select(C, a, c)
2835       if (TrueSI->getCondition() == CondVal) {
2836         if (SI.getTrueValue() == TrueSI->getTrueValue())
2837           return nullptr;
2838         return replaceOperand(SI, 1, TrueSI->getTrueValue());
2839       }
2840       // select(C0, select(C1, a, b), b) -> select(C0&C1, a, b)
2841       // We choose this as normal form to enable folding on the And and shortening
2842       // paths for the values (this helps GetUnderlyingObjects() for example).
2843       if (TrueSI->getFalseValue() == FalseVal && TrueSI->hasOneUse()) {
2844         Value *And = Builder.CreateAnd(CondVal, TrueSI->getCondition());
2845         replaceOperand(SI, 0, And);
2846         replaceOperand(SI, 1, TrueSI->getTrueValue());
2847         return &SI;
2848       }
2849     }
2850   }
2851   if (SelectInst *FalseSI = dyn_cast<SelectInst>(FalseVal)) {
2852     if (FalseSI->getCondition()->getType() == CondVal->getType()) {
2853       // select(C, a, select(C, b, c)) -> select(C, a, c)
2854       if (FalseSI->getCondition() == CondVal) {
2855         if (SI.getFalseValue() == FalseSI->getFalseValue())
2856           return nullptr;
2857         return replaceOperand(SI, 2, FalseSI->getFalseValue());
2858       }
2859       // select(C0, a, select(C1, a, b)) -> select(C0|C1, a, b)
2860       if (FalseSI->getTrueValue() == TrueVal && FalseSI->hasOneUse()) {
2861         Value *Or = Builder.CreateOr(CondVal, FalseSI->getCondition());
2862         replaceOperand(SI, 0, Or);
2863         replaceOperand(SI, 2, FalseSI->getFalseValue());
2864         return &SI;
2865       }
2866     }
2867   }
2868 
2869   auto canMergeSelectThroughBinop = [](BinaryOperator *BO) {
2870     // The select might be preventing a division by 0.
2871     switch (BO->getOpcode()) {
2872     default:
2873       return true;
2874     case Instruction::SRem:
2875     case Instruction::URem:
2876     case Instruction::SDiv:
2877     case Instruction::UDiv:
2878       return false;
2879     }
2880   };
2881 
2882   // Try to simplify a binop sandwiched between 2 selects with the same
2883   // condition.
2884   // select(C, binop(select(C, X, Y), W), Z) -> select(C, binop(X, W), Z)
2885   BinaryOperator *TrueBO;
2886   if (match(TrueVal, m_OneUse(m_BinOp(TrueBO))) &&
2887       canMergeSelectThroughBinop(TrueBO)) {
2888     if (auto *TrueBOSI = dyn_cast<SelectInst>(TrueBO->getOperand(0))) {
2889       if (TrueBOSI->getCondition() == CondVal) {
2890         replaceOperand(*TrueBO, 0, TrueBOSI->getTrueValue());
2891         Worklist.push(TrueBO);
2892         return &SI;
2893       }
2894     }
2895     if (auto *TrueBOSI = dyn_cast<SelectInst>(TrueBO->getOperand(1))) {
2896       if (TrueBOSI->getCondition() == CondVal) {
2897         replaceOperand(*TrueBO, 1, TrueBOSI->getTrueValue());
2898         Worklist.push(TrueBO);
2899         return &SI;
2900       }
2901     }
2902   }
2903 
2904   // select(C, Z, binop(select(C, X, Y), W)) -> select(C, Z, binop(Y, W))
2905   BinaryOperator *FalseBO;
2906   if (match(FalseVal, m_OneUse(m_BinOp(FalseBO))) &&
2907       canMergeSelectThroughBinop(FalseBO)) {
2908     if (auto *FalseBOSI = dyn_cast<SelectInst>(FalseBO->getOperand(0))) {
2909       if (FalseBOSI->getCondition() == CondVal) {
2910         replaceOperand(*FalseBO, 0, FalseBOSI->getFalseValue());
2911         Worklist.push(FalseBO);
2912         return &SI;
2913       }
2914     }
2915     if (auto *FalseBOSI = dyn_cast<SelectInst>(FalseBO->getOperand(1))) {
2916       if (FalseBOSI->getCondition() == CondVal) {
2917         replaceOperand(*FalseBO, 1, FalseBOSI->getFalseValue());
2918         Worklist.push(FalseBO);
2919         return &SI;
2920       }
2921     }
2922   }
2923 
2924   Value *NotCond;
2925   if (match(CondVal, m_Not(m_Value(NotCond)))) {
2926     replaceOperand(SI, 0, NotCond);
2927     SI.swapValues();
2928     SI.swapProfMetadata();
2929     return &SI;
2930   }
2931 
2932   if (Instruction *I = foldVectorSelect(SI))
2933     return I;
2934 
2935   // If we can compute the condition, there's no need for a select.
2936   // Like the above fold, we are attempting to reduce compile-time cost by
2937   // putting this fold here with limitations rather than in InstSimplify.
2938   // The motivation for this call into value tracking is to take advantage of
2939   // the assumption cache, so make sure that is populated.
2940   if (!CondVal->getType()->isVectorTy() && !AC.assumptions().empty()) {
2941     KnownBits Known(1);
2942     computeKnownBits(CondVal, Known, 0, &SI);
2943     if (Known.One.isOneValue())
2944       return replaceInstUsesWith(SI, TrueVal);
2945     if (Known.Zero.isOneValue())
2946       return replaceInstUsesWith(SI, FalseVal);
2947   }
2948 
2949   if (Instruction *BitCastSel = foldSelectCmpBitcasts(SI, Builder))
2950     return BitCastSel;
2951 
2952   // Simplify selects that test the returned flag of cmpxchg instructions.
2953   if (Value *V = foldSelectCmpXchg(SI))
2954     return replaceInstUsesWith(SI, V);
2955 
2956   if (Instruction *Select = foldSelectBinOpIdentity(SI, TLI, *this))
2957     return Select;
2958 
2959   if (Instruction *Rot = foldSelectRotate(SI))
2960     return Rot;
2961 
2962   if (Instruction *Copysign = foldSelectToCopysign(SI, Builder))
2963     return Copysign;
2964 
2965   if (Instruction *PN = foldSelectToPhi(SI, DT, Builder))
2966     return replaceInstUsesWith(SI, PN);
2967 
2968   return nullptr;
2969 }
2970