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 "InstCombine.h"
15 #include "llvm/Analysis/ConstantFolding.h"
16 #include "llvm/Analysis/InstructionSimplify.h"
17 #include "llvm/IR/PatternMatch.h"
18 using namespace llvm;
19 using namespace PatternMatch;
20 
21 #define DEBUG_TYPE "instcombine"
22 
23 /// MatchSelectPattern - Pattern match integer [SU]MIN, [SU]MAX, and ABS idioms,
24 /// returning the kind and providing the out parameter results if we
25 /// successfully match.
26 static SelectPatternFlavor
27 MatchSelectPattern(Value *V, Value *&LHS, Value *&RHS) {
28   SelectInst *SI = dyn_cast<SelectInst>(V);
29   if (!SI) return SPF_UNKNOWN;
30 
31   ICmpInst *ICI = dyn_cast<ICmpInst>(SI->getCondition());
32   if (!ICI) return SPF_UNKNOWN;
33 
34   ICmpInst::Predicate Pred = ICI->getPredicate();
35   Value *CmpLHS = ICI->getOperand(0);
36   Value *CmpRHS = ICI->getOperand(1);
37   Value *TrueVal = SI->getTrueValue();
38   Value *FalseVal = SI->getFalseValue();
39 
40   LHS = CmpLHS;
41   RHS = CmpRHS;
42 
43   // (icmp X, Y) ? X : Y
44   if (TrueVal == CmpLHS && FalseVal == CmpRHS) {
45     switch (Pred) {
46     default: return SPF_UNKNOWN; // Equality.
47     case ICmpInst::ICMP_UGT:
48     case ICmpInst::ICMP_UGE: return SPF_UMAX;
49     case ICmpInst::ICMP_SGT:
50     case ICmpInst::ICMP_SGE: return SPF_SMAX;
51     case ICmpInst::ICMP_ULT:
52     case ICmpInst::ICMP_ULE: return SPF_UMIN;
53     case ICmpInst::ICMP_SLT:
54     case ICmpInst::ICMP_SLE: return SPF_SMIN;
55     }
56   }
57 
58   // (icmp X, Y) ? Y : X
59   if (TrueVal == CmpRHS && FalseVal == CmpLHS) {
60     switch (Pred) {
61     default: return SPF_UNKNOWN; // Equality.
62     case ICmpInst::ICMP_UGT:
63     case ICmpInst::ICMP_UGE: return SPF_UMIN;
64     case ICmpInst::ICMP_SGT:
65     case ICmpInst::ICMP_SGE: return SPF_SMIN;
66     case ICmpInst::ICMP_ULT:
67     case ICmpInst::ICMP_ULE: return SPF_UMAX;
68     case ICmpInst::ICMP_SLT:
69     case ICmpInst::ICMP_SLE: return SPF_SMAX;
70     }
71   }
72 
73   if (ConstantInt *C1 = dyn_cast<ConstantInt>(CmpRHS)) {
74     if ((CmpLHS == TrueVal && match(FalseVal, m_Neg(m_Specific(CmpLHS)))) ||
75         (CmpLHS == FalseVal && match(TrueVal, m_Neg(m_Specific(CmpLHS))))) {
76 
77       // ABS(X) ==> (X >s 0) ? X : -X and (X >s -1) ? X : -X
78       // NABS(X) ==> (X >s 0) ? -X : X and (X >s -1) ? -X : X
79       if (Pred == ICmpInst::ICMP_SGT && (C1->isZero() || C1->isMinusOne())) {
80         return (CmpLHS == TrueVal) ? SPF_ABS : SPF_NABS;
81       }
82 
83       // ABS(X) ==> (X <s 0) ? -X : X and (X <s 1) ? -X : X
84       // NABS(X) ==> (X <s 0) ? X : -X and (X <s 1) ? X : -X
85       if (Pred == ICmpInst::ICMP_SLT && (C1->isZero() || C1->isOne())) {
86         return (CmpLHS == FalseVal) ? SPF_ABS : SPF_NABS;
87       }
88     }
89   }
90 
91   // TODO: (X > 4) ? X : 5   -->  (X >= 5) ? X : 5  -->  MAX(X, 5)
92 
93   return SPF_UNKNOWN;
94 }
95 
96 
97 /// GetSelectFoldableOperands - We want to turn code that looks like this:
98 ///   %C = or %A, %B
99 ///   %D = select %cond, %C, %A
100 /// into:
101 ///   %C = select %cond, %B, 0
102 ///   %D = or %A, %C
103 ///
104 /// Assuming that the specified instruction is an operand to the select, return
105 /// a bitmask indicating which operands of this instruction are foldable if they
106 /// equal the other incoming value of the select.
107 ///
108 static unsigned GetSelectFoldableOperands(Instruction *I) {
109   switch (I->getOpcode()) {
110   case Instruction::Add:
111   case Instruction::Mul:
112   case Instruction::And:
113   case Instruction::Or:
114   case Instruction::Xor:
115     return 3;              // Can fold through either operand.
116   case Instruction::Sub:   // Can only fold on the amount subtracted.
117   case Instruction::Shl:   // Can only fold on the shift amount.
118   case Instruction::LShr:
119   case Instruction::AShr:
120     return 1;
121   default:
122     return 0;              // Cannot fold
123   }
124 }
125 
126 /// GetSelectFoldableConstant - For the same transformation as the previous
127 /// function, return the identity constant that goes into the select.
128 static Constant *GetSelectFoldableConstant(Instruction *I) {
129   switch (I->getOpcode()) {
130   default: llvm_unreachable("This cannot happen!");
131   case Instruction::Add:
132   case Instruction::Sub:
133   case Instruction::Or:
134   case Instruction::Xor:
135   case Instruction::Shl:
136   case Instruction::LShr:
137   case Instruction::AShr:
138     return Constant::getNullValue(I->getType());
139   case Instruction::And:
140     return Constant::getAllOnesValue(I->getType());
141   case Instruction::Mul:
142     return ConstantInt::get(I->getType(), 1);
143   }
144 }
145 
146 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
147 /// have the same opcode and only one use each.  Try to simplify this.
148 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
149                                           Instruction *FI) {
150   if (TI->getNumOperands() == 1) {
151     // If this is a non-volatile load or a cast from the same type,
152     // merge.
153     if (TI->isCast()) {
154       Type *FIOpndTy = FI->getOperand(0)->getType();
155       if (TI->getOperand(0)->getType() != FIOpndTy)
156         return nullptr;
157       // The select condition may be a vector. We may only change the operand
158       // type if the vector width remains the same (and matches the condition).
159       Type *CondTy = SI.getCondition()->getType();
160       if (CondTy->isVectorTy() && (!FIOpndTy->isVectorTy() ||
161           CondTy->getVectorNumElements() != FIOpndTy->getVectorNumElements()))
162         return nullptr;
163     } else {
164       return nullptr;  // unknown unary op.
165     }
166 
167     // Fold this by inserting a select from the input values.
168     Value *NewSI = Builder->CreateSelect(SI.getCondition(), TI->getOperand(0),
169                                          FI->getOperand(0), SI.getName()+".v");
170     return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
171                             TI->getType());
172   }
173 
174   // Only handle binary operators here.
175   if (!isa<BinaryOperator>(TI))
176     return nullptr;
177 
178   // Figure out if the operations have any operands in common.
179   Value *MatchOp, *OtherOpT, *OtherOpF;
180   bool MatchIsOpZero;
181   if (TI->getOperand(0) == FI->getOperand(0)) {
182     MatchOp  = TI->getOperand(0);
183     OtherOpT = TI->getOperand(1);
184     OtherOpF = FI->getOperand(1);
185     MatchIsOpZero = true;
186   } else if (TI->getOperand(1) == FI->getOperand(1)) {
187     MatchOp  = TI->getOperand(1);
188     OtherOpT = TI->getOperand(0);
189     OtherOpF = FI->getOperand(0);
190     MatchIsOpZero = false;
191   } else if (!TI->isCommutative()) {
192     return nullptr;
193   } else if (TI->getOperand(0) == FI->getOperand(1)) {
194     MatchOp  = TI->getOperand(0);
195     OtherOpT = TI->getOperand(1);
196     OtherOpF = FI->getOperand(0);
197     MatchIsOpZero = true;
198   } else if (TI->getOperand(1) == FI->getOperand(0)) {
199     MatchOp  = TI->getOperand(1);
200     OtherOpT = TI->getOperand(0);
201     OtherOpF = FI->getOperand(1);
202     MatchIsOpZero = true;
203   } else {
204     return nullptr;
205   }
206 
207   // If we reach here, they do have operations in common.
208   Value *NewSI = Builder->CreateSelect(SI.getCondition(), OtherOpT,
209                                        OtherOpF, SI.getName()+".v");
210 
211   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
212     if (MatchIsOpZero)
213       return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
214     else
215       return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
216   }
217   llvm_unreachable("Shouldn't get here");
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 /// FoldSelectIntoOp - Try fold the select into one of the operands to
234 /// facilitate further 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             if (isa<PossiblyExactOperator>(BO))
262               BO->setIsExact(TVI_BO->isExact());
263             if (isa<OverflowingBinaryOperator>(BO)) {
264               BO->setHasNoUnsignedWrap(TVI_BO->hasNoUnsignedWrap());
265               BO->setHasNoSignedWrap(TVI_BO->hasNoSignedWrap());
266             }
267             return BO;
268           }
269         }
270       }
271     }
272   }
273 
274   if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
275     if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
276         !isa<Constant>(TrueVal)) {
277       if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
278         unsigned OpToFold = 0;
279         if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
280           OpToFold = 1;
281         } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
282           OpToFold = 2;
283         }
284 
285         if (OpToFold) {
286           Constant *C = GetSelectFoldableConstant(FVI);
287           Value *OOp = FVI->getOperand(2-OpToFold);
288           // Avoid creating select between 2 constants unless it's selecting
289           // between 0, 1 and -1.
290           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
291             Value *NewSel = Builder->CreateSelect(SI.getCondition(), C, OOp);
292             NewSel->takeName(FVI);
293             BinaryOperator *FVI_BO = cast<BinaryOperator>(FVI);
294             BinaryOperator *BO = BinaryOperator::Create(FVI_BO->getOpcode(),
295                                                         TrueVal, NewSel);
296             if (isa<PossiblyExactOperator>(BO))
297               BO->setIsExact(FVI_BO->isExact());
298             if (isa<OverflowingBinaryOperator>(BO)) {
299               BO->setHasNoUnsignedWrap(FVI_BO->hasNoUnsignedWrap());
300               BO->setHasNoSignedWrap(FVI_BO->hasNoSignedWrap());
301             }
302             return BO;
303           }
304         }
305       }
306     }
307   }
308 
309   return nullptr;
310 }
311 
312 /// SimplifyWithOpReplaced - See if V simplifies when its operand Op is
313 /// replaced with RepOp.
314 static Value *SimplifyWithOpReplaced(Value *V, Value *Op, Value *RepOp,
315                                      const DataLayout *TD,
316                                      const TargetLibraryInfo *TLI) {
317   // Trivial replacement.
318   if (V == Op)
319     return RepOp;
320 
321   Instruction *I = dyn_cast<Instruction>(V);
322   if (!I)
323     return nullptr;
324 
325   // If this is a binary operator, try to simplify it with the replaced op.
326   if (BinaryOperator *B = dyn_cast<BinaryOperator>(I)) {
327     if (B->getOperand(0) == Op)
328       return SimplifyBinOp(B->getOpcode(), RepOp, B->getOperand(1), TD, TLI);
329     if (B->getOperand(1) == Op)
330       return SimplifyBinOp(B->getOpcode(), B->getOperand(0), RepOp, TD, TLI);
331   }
332 
333   // Same for CmpInsts.
334   if (CmpInst *C = dyn_cast<CmpInst>(I)) {
335     if (C->getOperand(0) == Op)
336       return SimplifyCmpInst(C->getPredicate(), RepOp, C->getOperand(1), TD,
337                              TLI);
338     if (C->getOperand(1) == Op)
339       return SimplifyCmpInst(C->getPredicate(), C->getOperand(0), RepOp, TD,
340                              TLI);
341   }
342 
343   // TODO: We could hand off more cases to instsimplify here.
344 
345   // If all operands are constant after substituting Op for RepOp then we can
346   // constant fold the instruction.
347   if (Constant *CRepOp = dyn_cast<Constant>(RepOp)) {
348     // Build a list of all constant operands.
349     SmallVector<Constant*, 8> ConstOps;
350     for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
351       if (I->getOperand(i) == Op)
352         ConstOps.push_back(CRepOp);
353       else if (Constant *COp = dyn_cast<Constant>(I->getOperand(i)))
354         ConstOps.push_back(COp);
355       else
356         break;
357     }
358 
359     // All operands were constants, fold it.
360     if (ConstOps.size() == I->getNumOperands()) {
361       if (CmpInst *C = dyn_cast<CmpInst>(I))
362         return ConstantFoldCompareInstOperands(C->getPredicate(), ConstOps[0],
363                                                ConstOps[1], TD, TLI);
364 
365       if (LoadInst *LI = dyn_cast<LoadInst>(I))
366         if (!LI->isVolatile())
367           return ConstantFoldLoadFromConstPtr(ConstOps[0], TD);
368 
369       return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
370                                       ConstOps, TD, TLI);
371     }
372   }
373 
374   return nullptr;
375 }
376 
377 /// foldSelectICmpAndOr - We want to turn:
378 ///   (select (icmp eq (and X, C1), 0), Y, (or Y, C2))
379 /// into:
380 ///   (or (shl (and X, C1), C3), y)
381 /// iff:
382 ///   C1 and C2 are both powers of 2
383 /// where:
384 ///   C3 = Log(C2) - Log(C1)
385 ///
386 /// This transform handles cases where:
387 /// 1. The icmp predicate is inverted
388 /// 2. The select operands are reversed
389 /// 3. The magnitude of C2 and C1 are flipped
390 static Value *foldSelectICmpAndOr(const SelectInst &SI, Value *TrueVal,
391                                   Value *FalseVal,
392                                   InstCombiner::BuilderTy *Builder) {
393   const ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition());
394   if (!IC || !IC->isEquality() || !SI.getType()->isIntegerTy())
395     return nullptr;
396 
397   Value *CmpLHS = IC->getOperand(0);
398   Value *CmpRHS = IC->getOperand(1);
399 
400   if (!match(CmpRHS, m_Zero()))
401     return nullptr;
402 
403   Value *X;
404   const APInt *C1;
405   if (!match(CmpLHS, m_And(m_Value(X), m_Power2(C1))))
406     return nullptr;
407 
408   const APInt *C2;
409   bool OrOnTrueVal = false;
410   bool OrOnFalseVal = match(FalseVal, m_Or(m_Specific(TrueVal), m_Power2(C2)));
411   if (!OrOnFalseVal)
412     OrOnTrueVal = match(TrueVal, m_Or(m_Specific(FalseVal), m_Power2(C2)));
413 
414   if (!OrOnFalseVal && !OrOnTrueVal)
415     return nullptr;
416 
417   Value *V = CmpLHS;
418   Value *Y = OrOnFalseVal ? TrueVal : FalseVal;
419 
420   unsigned C1Log = C1->logBase2();
421   unsigned C2Log = C2->logBase2();
422   if (C2Log > C1Log) {
423     V = Builder->CreateZExtOrTrunc(V, Y->getType());
424     V = Builder->CreateShl(V, C2Log - C1Log);
425   } else if (C1Log > C2Log) {
426     V = Builder->CreateLShr(V, C1Log - C2Log);
427     V = Builder->CreateZExtOrTrunc(V, Y->getType());
428   } else
429     V = Builder->CreateZExtOrTrunc(V, Y->getType());
430 
431   ICmpInst::Predicate Pred = IC->getPredicate();
432   if ((Pred == ICmpInst::ICMP_NE && OrOnFalseVal) ||
433       (Pred == ICmpInst::ICMP_EQ && OrOnTrueVal))
434     V = Builder->CreateXor(V, *C2);
435 
436   return Builder->CreateOr(V, Y);
437 }
438 
439 /// visitSelectInstWithICmp - Visit a SelectInst that has an
440 /// ICmpInst as its first operand.
441 ///
442 Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
443                                                    ICmpInst *ICI) {
444   bool Changed = false;
445   ICmpInst::Predicate Pred = ICI->getPredicate();
446   Value *CmpLHS = ICI->getOperand(0);
447   Value *CmpRHS = ICI->getOperand(1);
448   Value *TrueVal = SI.getTrueValue();
449   Value *FalseVal = SI.getFalseValue();
450 
451   // Check cases where the comparison is with a constant that
452   // can be adjusted to fit the min/max idiom. We may move or edit ICI
453   // here, so make sure the select is the only user.
454   if (ICI->hasOneUse())
455     if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
456       // X < MIN ? T : F  -->  F
457       if ((Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_ULT)
458           && CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
459         return ReplaceInstUsesWith(SI, FalseVal);
460       // X > MAX ? T : F  -->  F
461       else if ((Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_UGT)
462                && CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
463         return ReplaceInstUsesWith(SI, FalseVal);
464       switch (Pred) {
465       default: break;
466       case ICmpInst::ICMP_ULT:
467       case ICmpInst::ICMP_SLT:
468       case ICmpInst::ICMP_UGT:
469       case ICmpInst::ICMP_SGT: {
470         // These transformations only work for selects over integers.
471         IntegerType *SelectTy = dyn_cast<IntegerType>(SI.getType());
472         if (!SelectTy)
473           break;
474 
475         Constant *AdjustedRHS;
476         if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_SGT)
477           AdjustedRHS = ConstantInt::get(CI->getContext(), CI->getValue() + 1);
478         else // (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT)
479           AdjustedRHS = ConstantInt::get(CI->getContext(), CI->getValue() - 1);
480 
481         // X > C ? X : C+1  -->  X < C+1 ? C+1 : X
482         // X < C ? X : C-1  -->  X > C-1 ? C-1 : X
483         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
484             (CmpLHS == FalseVal && AdjustedRHS == TrueVal))
485           ; // Nothing to do here. Values match without any sign/zero extension.
486 
487         // Types do not match. Instead of calculating this with mixed types
488         // promote all to the larger type. This enables scalar evolution to
489         // analyze this expression.
490         else if (CmpRHS->getType()->getScalarSizeInBits()
491                  < SelectTy->getBitWidth()) {
492           Constant *sextRHS = ConstantExpr::getSExt(AdjustedRHS, SelectTy);
493 
494           // X = sext x; x >s c ? X : C+1 --> X = sext x; X <s C+1 ? C+1 : X
495           // X = sext x; x <s c ? X : C-1 --> X = sext x; X >s C-1 ? C-1 : X
496           // X = sext x; x >u c ? X : C+1 --> X = sext x; X <u C+1 ? C+1 : X
497           // X = sext x; x <u c ? X : C-1 --> X = sext x; X >u C-1 ? C-1 : X
498           if (match(TrueVal, m_SExt(m_Specific(CmpLHS))) &&
499                 sextRHS == FalseVal) {
500             CmpLHS = TrueVal;
501             AdjustedRHS = sextRHS;
502           } else if (match(FalseVal, m_SExt(m_Specific(CmpLHS))) &&
503                      sextRHS == TrueVal) {
504             CmpLHS = FalseVal;
505             AdjustedRHS = sextRHS;
506           } else if (ICI->isUnsigned()) {
507             Constant *zextRHS = ConstantExpr::getZExt(AdjustedRHS, SelectTy);
508             // X = zext x; x >u c ? X : C+1 --> X = zext x; X <u C+1 ? C+1 : X
509             // X = zext x; x <u c ? X : C-1 --> X = zext x; X >u C-1 ? C-1 : X
510             // zext + signed compare cannot be changed:
511             //    0xff <s 0x00, but 0x00ff >s 0x0000
512             if (match(TrueVal, m_ZExt(m_Specific(CmpLHS))) &&
513                 zextRHS == FalseVal) {
514               CmpLHS = TrueVal;
515               AdjustedRHS = zextRHS;
516             } else if (match(FalseVal, m_ZExt(m_Specific(CmpLHS))) &&
517                        zextRHS == TrueVal) {
518               CmpLHS = FalseVal;
519               AdjustedRHS = zextRHS;
520             } else
521               break;
522           } else
523             break;
524         } else
525           break;
526 
527         Pred = ICmpInst::getSwappedPredicate(Pred);
528         CmpRHS = AdjustedRHS;
529         std::swap(FalseVal, TrueVal);
530         ICI->setPredicate(Pred);
531         ICI->setOperand(0, CmpLHS);
532         ICI->setOperand(1, CmpRHS);
533         SI.setOperand(1, TrueVal);
534         SI.setOperand(2, FalseVal);
535 
536         // Move ICI instruction right before the select instruction. Otherwise
537         // the sext/zext value may be defined after the ICI instruction uses it.
538         ICI->moveBefore(&SI);
539 
540         Changed = true;
541         break;
542       }
543       }
544     }
545 
546   // Transform (X >s -1) ? C1 : C2 --> ((X >>s 31) & (C2 - C1)) + C1
547   // and       (X <s  0) ? C2 : C1 --> ((X >>s 31) & (C2 - C1)) + C1
548   // FIXME: Type and constness constraints could be lifted, but we have to
549   //        watch code size carefully. We should consider xor instead of
550   //        sub/add when we decide to do that.
551   if (IntegerType *Ty = dyn_cast<IntegerType>(CmpLHS->getType())) {
552     if (TrueVal->getType() == Ty) {
553       if (ConstantInt *Cmp = dyn_cast<ConstantInt>(CmpRHS)) {
554         ConstantInt *C1 = nullptr, *C2 = nullptr;
555         if (Pred == ICmpInst::ICMP_SGT && Cmp->isAllOnesValue()) {
556           C1 = dyn_cast<ConstantInt>(TrueVal);
557           C2 = dyn_cast<ConstantInt>(FalseVal);
558         } else if (Pred == ICmpInst::ICMP_SLT && Cmp->isNullValue()) {
559           C1 = dyn_cast<ConstantInt>(FalseVal);
560           C2 = dyn_cast<ConstantInt>(TrueVal);
561         }
562         if (C1 && C2) {
563           // This shift results in either -1 or 0.
564           Value *AShr = Builder->CreateAShr(CmpLHS, Ty->getBitWidth()-1);
565 
566           // Check if we can express the operation with a single or.
567           if (C2->isAllOnesValue())
568             return ReplaceInstUsesWith(SI, Builder->CreateOr(AShr, C1));
569 
570           Value *And = Builder->CreateAnd(AShr, C2->getValue()-C1->getValue());
571           return ReplaceInstUsesWith(SI, Builder->CreateAdd(And, C1));
572         }
573       }
574     }
575   }
576 
577   // If we have an equality comparison then we know the value in one of the
578   // arms of the select. See if substituting this value into the arm and
579   // simplifying the result yields the same value as the other arm.
580   if (Pred == ICmpInst::ICMP_EQ) {
581     if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, DL, TLI) == TrueVal ||
582         SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, DL, TLI) == TrueVal)
583       return ReplaceInstUsesWith(SI, FalseVal);
584     if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, DL, TLI) == FalseVal ||
585         SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, DL, TLI) == FalseVal)
586       return ReplaceInstUsesWith(SI, FalseVal);
587   } else if (Pred == ICmpInst::ICMP_NE) {
588     if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, DL, TLI) == FalseVal ||
589         SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, DL, TLI) == FalseVal)
590       return ReplaceInstUsesWith(SI, TrueVal);
591     if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, DL, TLI) == TrueVal ||
592         SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, DL, TLI) == TrueVal)
593       return ReplaceInstUsesWith(SI, TrueVal);
594   }
595 
596   // NOTE: if we wanted to, this is where to detect integer MIN/MAX
597 
598   if (CmpRHS != CmpLHS && isa<Constant>(CmpRHS)) {
599     if (CmpLHS == TrueVal && Pred == ICmpInst::ICMP_EQ) {
600       // Transform (X == C) ? X : Y -> (X == C) ? C : Y
601       SI.setOperand(1, CmpRHS);
602       Changed = true;
603     } else if (CmpLHS == FalseVal && Pred == ICmpInst::ICMP_NE) {
604       // Transform (X != C) ? Y : X -> (X != C) ? Y : C
605       SI.setOperand(2, CmpRHS);
606       Changed = true;
607     }
608   }
609 
610   if (Value *V = foldSelectICmpAndOr(SI, TrueVal, FalseVal, Builder))
611     return ReplaceInstUsesWith(SI, V);
612 
613   return Changed ? &SI : nullptr;
614 }
615 
616 
617 /// CanSelectOperandBeMappingIntoPredBlock - SI is a select whose condition is a
618 /// PHI node (but the two may be in different blocks).  See if the true/false
619 /// values (V) are live in all of the predecessor blocks of the PHI.  For
620 /// example, cases like this cannot be mapped:
621 ///
622 ///   X = phi [ C1, BB1], [C2, BB2]
623 ///   Y = add
624 ///   Z = select X, Y, 0
625 ///
626 /// because Y is not live in BB1/BB2.
627 ///
628 static bool CanSelectOperandBeMappingIntoPredBlock(const Value *V,
629                                                    const SelectInst &SI) {
630   // If the value is a non-instruction value like a constant or argument, it
631   // can always be mapped.
632   const Instruction *I = dyn_cast<Instruction>(V);
633   if (!I) return true;
634 
635   // If V is a PHI node defined in the same block as the condition PHI, we can
636   // map the arguments.
637   const PHINode *CondPHI = cast<PHINode>(SI.getCondition());
638 
639   if (const PHINode *VP = dyn_cast<PHINode>(I))
640     if (VP->getParent() == CondPHI->getParent())
641       return true;
642 
643   // Otherwise, if the PHI and select are defined in the same block and if V is
644   // defined in a different block, then we can transform it.
645   if (SI.getParent() == CondPHI->getParent() &&
646       I->getParent() != CondPHI->getParent())
647     return true;
648 
649   // Otherwise we have a 'hard' case and we can't tell without doing more
650   // detailed dominator based analysis, punt.
651   return false;
652 }
653 
654 /// FoldSPFofSPF - We have an SPF (e.g. a min or max) of an SPF of the form:
655 ///   SPF2(SPF1(A, B), C)
656 Instruction *InstCombiner::FoldSPFofSPF(Instruction *Inner,
657                                         SelectPatternFlavor SPF1,
658                                         Value *A, Value *B,
659                                         Instruction &Outer,
660                                         SelectPatternFlavor SPF2, Value *C) {
661   if (C == A || C == B) {
662     // MAX(MAX(A, B), B) -> MAX(A, B)
663     // MIN(MIN(a, b), a) -> MIN(a, b)
664     if (SPF1 == SPF2)
665       return ReplaceInstUsesWith(Outer, Inner);
666 
667     // MAX(MIN(a, b), a) -> a
668     // MIN(MAX(a, b), a) -> a
669     if ((SPF1 == SPF_SMIN && SPF2 == SPF_SMAX) ||
670         (SPF1 == SPF_SMAX && SPF2 == SPF_SMIN) ||
671         (SPF1 == SPF_UMIN && SPF2 == SPF_UMAX) ||
672         (SPF1 == SPF_UMAX && SPF2 == SPF_UMIN))
673       return ReplaceInstUsesWith(Outer, C);
674   }
675 
676   if (SPF1 == SPF2) {
677     if (ConstantInt *CB = dyn_cast<ConstantInt>(B)) {
678       if (ConstantInt *CC = dyn_cast<ConstantInt>(C)) {
679         APInt ACB = CB->getValue();
680         APInt ACC = CC->getValue();
681 
682         // MIN(MIN(A, 23), 97) -> MIN(A, 23)
683         // MAX(MAX(A, 97), 23) -> MAX(A, 97)
684         if ((SPF1 == SPF_UMIN && ACB.ule(ACC)) ||
685             (SPF1 == SPF_SMIN && ACB.sle(ACC)) ||
686             (SPF1 == SPF_UMAX && ACB.uge(ACC)) ||
687             (SPF1 == SPF_SMAX && ACB.sge(ACC)))
688           return ReplaceInstUsesWith(Outer, Inner);
689 
690         // MIN(MIN(A, 97), 23) -> MIN(A, 23)
691         // MAX(MAX(A, 23), 97) -> MAX(A, 97)
692         if ((SPF1 == SPF_UMIN && ACB.ugt(ACC)) ||
693             (SPF1 == SPF_SMIN && ACB.sgt(ACC)) ||
694             (SPF1 == SPF_UMAX && ACB.ult(ACC)) ||
695             (SPF1 == SPF_SMAX && ACB.slt(ACC))) {
696           Outer.replaceUsesOfWith(Inner, A);
697           return &Outer;
698         }
699       }
700     }
701   }
702 
703   // ABS(ABS(X)) -> ABS(X)
704   // NABS(NABS(X)) -> NABS(X)
705   if (SPF1 == SPF2 && (SPF1 == SPF_ABS || SPF1 == SPF_NABS)) {
706     return ReplaceInstUsesWith(Outer, Inner);
707   }
708 
709   // ABS(NABS(X)) -> ABS(X)
710   // NABS(ABS(X)) -> NABS(X)
711   if ((SPF1 == SPF_ABS && SPF2 == SPF_NABS) ||
712       (SPF1 == SPF_NABS && SPF2 == SPF_ABS)) {
713     SelectInst *SI = cast<SelectInst>(Inner);
714     Value *NewSI = Builder->CreateSelect(
715         SI->getCondition(), SI->getFalseValue(), SI->getTrueValue());
716     return ReplaceInstUsesWith(Outer, NewSI);
717   }
718   return nullptr;
719 }
720 
721 /// foldSelectICmpAnd - If one of the constants is zero (we know they can't
722 /// both be) and we have an icmp instruction with zero, and we have an 'and'
723 /// with the non-constant value and a power of two we can turn the select
724 /// into a shift on the result of the 'and'.
725 static Value *foldSelectICmpAnd(const SelectInst &SI, ConstantInt *TrueVal,
726                                 ConstantInt *FalseVal,
727                                 InstCombiner::BuilderTy *Builder) {
728   const ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition());
729   if (!IC || !IC->isEquality() || !SI.getType()->isIntegerTy())
730     return nullptr;
731 
732   if (!match(IC->getOperand(1), m_Zero()))
733     return nullptr;
734 
735   ConstantInt *AndRHS;
736   Value *LHS = IC->getOperand(0);
737   if (!match(LHS, m_And(m_Value(), m_ConstantInt(AndRHS))))
738     return nullptr;
739 
740   // If both select arms are non-zero see if we have a select of the form
741   // 'x ? 2^n + C : C'. Then we can offset both arms by C, use the logic
742   // for 'x ? 2^n : 0' and fix the thing up at the end.
743   ConstantInt *Offset = nullptr;
744   if (!TrueVal->isZero() && !FalseVal->isZero()) {
745     if ((TrueVal->getValue() - FalseVal->getValue()).isPowerOf2())
746       Offset = FalseVal;
747     else if ((FalseVal->getValue() - TrueVal->getValue()).isPowerOf2())
748       Offset = TrueVal;
749     else
750       return nullptr;
751 
752     // Adjust TrueVal and FalseVal to the offset.
753     TrueVal = ConstantInt::get(Builder->getContext(),
754                                TrueVal->getValue() - Offset->getValue());
755     FalseVal = ConstantInt::get(Builder->getContext(),
756                                 FalseVal->getValue() - Offset->getValue());
757   }
758 
759   // Make sure the mask in the 'and' and one of the select arms is a power of 2.
760   if (!AndRHS->getValue().isPowerOf2() ||
761       (!TrueVal->getValue().isPowerOf2() &&
762        !FalseVal->getValue().isPowerOf2()))
763     return nullptr;
764 
765   // Determine which shift is needed to transform result of the 'and' into the
766   // desired result.
767   ConstantInt *ValC = !TrueVal->isZero() ? TrueVal : FalseVal;
768   unsigned ValZeros = ValC->getValue().logBase2();
769   unsigned AndZeros = AndRHS->getValue().logBase2();
770 
771   // If types don't match we can still convert the select by introducing a zext
772   // or a trunc of the 'and'. The trunc case requires that all of the truncated
773   // bits are zero, we can figure that out by looking at the 'and' mask.
774   if (AndZeros >= ValC->getBitWidth())
775     return nullptr;
776 
777   Value *V = Builder->CreateZExtOrTrunc(LHS, SI.getType());
778   if (ValZeros > AndZeros)
779     V = Builder->CreateShl(V, ValZeros - AndZeros);
780   else if (ValZeros < AndZeros)
781     V = Builder->CreateLShr(V, AndZeros - ValZeros);
782 
783   // Okay, now we know that everything is set up, we just don't know whether we
784   // have a icmp_ne or icmp_eq and whether the true or false val is the zero.
785   bool ShouldNotVal = !TrueVal->isZero();
786   ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
787   if (ShouldNotVal)
788     V = Builder->CreateXor(V, ValC);
789 
790   // Apply an offset if needed.
791   if (Offset)
792     V = Builder->CreateAdd(V, Offset);
793   return V;
794 }
795 
796 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
797   Value *CondVal = SI.getCondition();
798   Value *TrueVal = SI.getTrueValue();
799   Value *FalseVal = SI.getFalseValue();
800 
801   if (Value *V = SimplifySelectInst(CondVal, TrueVal, FalseVal, DL))
802     return ReplaceInstUsesWith(SI, V);
803 
804   if (SI.getType()->isIntegerTy(1)) {
805     if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
806       if (C->getZExtValue()) {
807         // Change: A = select B, true, C --> A = or B, C
808         return BinaryOperator::CreateOr(CondVal, FalseVal);
809       }
810       // Change: A = select B, false, C --> A = and !B, C
811       Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName());
812       return BinaryOperator::CreateAnd(NotCond, FalseVal);
813     }
814     if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
815       if (C->getZExtValue() == false) {
816         // Change: A = select B, C, false --> A = and B, C
817         return BinaryOperator::CreateAnd(CondVal, TrueVal);
818       }
819       // Change: A = select B, C, true --> A = or !B, C
820       Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName());
821       return BinaryOperator::CreateOr(NotCond, TrueVal);
822     }
823 
824     // select a, b, a  -> a&b
825     // select a, a, b  -> a|b
826     if (CondVal == TrueVal)
827       return BinaryOperator::CreateOr(CondVal, FalseVal);
828     if (CondVal == FalseVal)
829       return BinaryOperator::CreateAnd(CondVal, TrueVal);
830 
831     // select a, ~a, b -> (~a)&b
832     // select a, b, ~a -> (~a)|b
833     if (match(TrueVal, m_Not(m_Specific(CondVal))))
834       return BinaryOperator::CreateAnd(TrueVal, FalseVal);
835     if (match(FalseVal, m_Not(m_Specific(CondVal))))
836       return BinaryOperator::CreateOr(TrueVal, FalseVal);
837   }
838 
839   // Selecting between two integer constants?
840   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
841     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
842       // select C, 1, 0 -> zext C to int
843       if (FalseValC->isZero() && TrueValC->getValue() == 1)
844         return new ZExtInst(CondVal, SI.getType());
845 
846       // select C, -1, 0 -> sext C to int
847       if (FalseValC->isZero() && TrueValC->isAllOnesValue())
848         return new SExtInst(CondVal, SI.getType());
849 
850       // select C, 0, 1 -> zext !C to int
851       if (TrueValC->isZero() && FalseValC->getValue() == 1) {
852         Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName());
853         return new ZExtInst(NotCond, SI.getType());
854       }
855 
856       // select C, 0, -1 -> sext !C to int
857       if (TrueValC->isZero() && FalseValC->isAllOnesValue()) {
858         Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName());
859         return new SExtInst(NotCond, SI.getType());
860       }
861 
862       if (Value *V = foldSelectICmpAnd(SI, TrueValC, FalseValC, Builder))
863         return ReplaceInstUsesWith(SI, V);
864     }
865 
866   // See if we are selecting two values based on a comparison of the two values.
867   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
868     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
869       // Transform (X == Y) ? X : Y  -> Y
870       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
871         // This is not safe in general for floating point:
872         // consider X== -0, Y== +0.
873         // It becomes safe if either operand is a nonzero constant.
874         ConstantFP *CFPt, *CFPf;
875         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
876               !CFPt->getValueAPF().isZero()) ||
877             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
878              !CFPf->getValueAPF().isZero()))
879         return ReplaceInstUsesWith(SI, FalseVal);
880       }
881       // Transform (X une Y) ? X : Y  -> X
882       if (FCI->getPredicate() == FCmpInst::FCMP_UNE) {
883         // This is not safe in general for floating point:
884         // consider X== -0, Y== +0.
885         // It becomes safe if either operand is a nonzero constant.
886         ConstantFP *CFPt, *CFPf;
887         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
888               !CFPt->getValueAPF().isZero()) ||
889             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
890              !CFPf->getValueAPF().isZero()))
891         return ReplaceInstUsesWith(SI, TrueVal);
892       }
893       // NOTE: if we wanted to, this is where to detect MIN/MAX
894 
895     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
896       // Transform (X == Y) ? Y : X  -> X
897       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
898         // This is not safe in general for floating point:
899         // consider X== -0, Y== +0.
900         // It becomes safe if either operand is a nonzero constant.
901         ConstantFP *CFPt, *CFPf;
902         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
903               !CFPt->getValueAPF().isZero()) ||
904             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
905              !CFPf->getValueAPF().isZero()))
906           return ReplaceInstUsesWith(SI, FalseVal);
907       }
908       // Transform (X une Y) ? Y : X  -> Y
909       if (FCI->getPredicate() == FCmpInst::FCMP_UNE) {
910         // This is not safe in general for floating point:
911         // consider X== -0, Y== +0.
912         // It becomes safe if either operand is a nonzero constant.
913         ConstantFP *CFPt, *CFPf;
914         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
915               !CFPt->getValueAPF().isZero()) ||
916             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
917              !CFPf->getValueAPF().isZero()))
918           return ReplaceInstUsesWith(SI, TrueVal);
919       }
920       // NOTE: if we wanted to, this is where to detect MIN/MAX
921     }
922     // NOTE: if we wanted to, this is where to detect ABS
923   }
924 
925   // See if we are selecting two values based on a comparison of the two values.
926   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
927     if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
928       return Result;
929 
930   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
931     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
932       if (TI->hasOneUse() && FI->hasOneUse()) {
933         Instruction *AddOp = nullptr, *SubOp = nullptr;
934 
935         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
936         if (TI->getOpcode() == FI->getOpcode())
937           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
938             return IV;
939 
940         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
941         // even legal for FP.
942         if ((TI->getOpcode() == Instruction::Sub &&
943              FI->getOpcode() == Instruction::Add) ||
944             (TI->getOpcode() == Instruction::FSub &&
945              FI->getOpcode() == Instruction::FAdd)) {
946           AddOp = FI; SubOp = TI;
947         } else if ((FI->getOpcode() == Instruction::Sub &&
948                     TI->getOpcode() == Instruction::Add) ||
949                    (FI->getOpcode() == Instruction::FSub &&
950                     TI->getOpcode() == Instruction::FAdd)) {
951           AddOp = TI; SubOp = FI;
952         }
953 
954         if (AddOp) {
955           Value *OtherAddOp = nullptr;
956           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
957             OtherAddOp = AddOp->getOperand(1);
958           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
959             OtherAddOp = AddOp->getOperand(0);
960           }
961 
962           if (OtherAddOp) {
963             // So at this point we know we have (Y -> OtherAddOp):
964             //        select C, (add X, Y), (sub X, Z)
965             Value *NegVal;  // Compute -Z
966             if (SI.getType()->isFPOrFPVectorTy()) {
967               NegVal = Builder->CreateFNeg(SubOp->getOperand(1));
968               if (Instruction *NegInst = dyn_cast<Instruction>(NegVal)) {
969                 FastMathFlags Flags = AddOp->getFastMathFlags();
970                 Flags &= SubOp->getFastMathFlags();
971                 NegInst->setFastMathFlags(Flags);
972               }
973             } else {
974               NegVal = Builder->CreateNeg(SubOp->getOperand(1));
975             }
976 
977             Value *NewTrueOp = OtherAddOp;
978             Value *NewFalseOp = NegVal;
979             if (AddOp != TI)
980               std::swap(NewTrueOp, NewFalseOp);
981             Value *NewSel =
982               Builder->CreateSelect(CondVal, NewTrueOp,
983                                     NewFalseOp, SI.getName() + ".p");
984 
985             if (SI.getType()->isFPOrFPVectorTy()) {
986               Instruction *RI =
987                 BinaryOperator::CreateFAdd(SubOp->getOperand(0), NewSel);
988 
989               FastMathFlags Flags = AddOp->getFastMathFlags();
990               Flags &= SubOp->getFastMathFlags();
991               RI->setFastMathFlags(Flags);
992               return RI;
993             } else
994               return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
995           }
996         }
997       }
998 
999   // See if we can fold the select into one of our operands.
1000   if (SI.getType()->isIntegerTy()) {
1001     if (Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal))
1002       return FoldI;
1003 
1004     // MAX(MAX(a, b), a) -> MAX(a, b)
1005     // MIN(MIN(a, b), a) -> MIN(a, b)
1006     // MAX(MIN(a, b), a) -> a
1007     // MIN(MAX(a, b), a) -> a
1008     Value *LHS, *RHS, *LHS2, *RHS2;
1009     if (SelectPatternFlavor SPF = MatchSelectPattern(&SI, LHS, RHS)) {
1010       if (SelectPatternFlavor SPF2 = MatchSelectPattern(LHS, LHS2, RHS2))
1011         if (Instruction *R = FoldSPFofSPF(cast<Instruction>(LHS),SPF2,LHS2,RHS2,
1012                                           SI, SPF, RHS))
1013           return R;
1014       if (SelectPatternFlavor SPF2 = MatchSelectPattern(RHS, LHS2, RHS2))
1015         if (Instruction *R = FoldSPFofSPF(cast<Instruction>(RHS),SPF2,LHS2,RHS2,
1016                                           SI, SPF, LHS))
1017           return R;
1018     }
1019 
1020     // TODO.
1021     // ABS(-X) -> ABS(X)
1022   }
1023 
1024   // See if we can fold the select into a phi node if the condition is a select.
1025   if (isa<PHINode>(SI.getCondition()))
1026     // The true/false values have to be live in the PHI predecessor's blocks.
1027     if (CanSelectOperandBeMappingIntoPredBlock(TrueVal, SI) &&
1028         CanSelectOperandBeMappingIntoPredBlock(FalseVal, SI))
1029       if (Instruction *NV = FoldOpIntoPhi(SI))
1030         return NV;
1031 
1032   if (SelectInst *TrueSI = dyn_cast<SelectInst>(TrueVal)) {
1033     if (TrueSI->getCondition() == CondVal) {
1034       if (SI.getTrueValue() == TrueSI->getTrueValue())
1035         return nullptr;
1036       SI.setOperand(1, TrueSI->getTrueValue());
1037       return &SI;
1038     }
1039   }
1040   if (SelectInst *FalseSI = dyn_cast<SelectInst>(FalseVal)) {
1041     if (FalseSI->getCondition() == CondVal) {
1042       if (SI.getFalseValue() == FalseSI->getFalseValue())
1043         return nullptr;
1044       SI.setOperand(2, FalseSI->getFalseValue());
1045       return &SI;
1046     }
1047   }
1048 
1049   if (BinaryOperator::isNot(CondVal)) {
1050     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
1051     SI.setOperand(1, FalseVal);
1052     SI.setOperand(2, TrueVal);
1053     return &SI;
1054   }
1055 
1056   if (VectorType* VecTy = dyn_cast<VectorType>(SI.getType())) {
1057     unsigned VWidth = VecTy->getNumElements();
1058     APInt UndefElts(VWidth, 0);
1059     APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
1060     if (Value *V = SimplifyDemandedVectorElts(&SI, AllOnesEltMask, UndefElts)) {
1061       if (V != &SI)
1062         return ReplaceInstUsesWith(SI, V);
1063       return &SI;
1064     }
1065 
1066     if (isa<ConstantAggregateZero>(CondVal)) {
1067       return ReplaceInstUsesWith(SI, FalseVal);
1068     }
1069   }
1070 
1071   return nullptr;
1072 }
1073