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