LLVM API Documentation

InstCombineSelect.cpp
Go to the documentation of this file.
00001 //===- InstCombineSelect.cpp ----------------------------------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements the visitSelect function.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "InstCombine.h"
00015 #include "llvm/Analysis/ConstantFolding.h"
00016 #include "llvm/Analysis/InstructionSimplify.h"
00017 #include "llvm/IR/PatternMatch.h"
00018 using namespace llvm;
00019 using namespace PatternMatch;
00020 
00021 #define DEBUG_TYPE "instcombine"
00022 
00023 /// MatchSelectPattern - Pattern match integer [SU]MIN, [SU]MAX, and ABS idioms,
00024 /// returning the kind and providing the out parameter results if we
00025 /// successfully match.
00026 static SelectPatternFlavor
00027 MatchSelectPattern(Value *V, Value *&LHS, Value *&RHS) {
00028   SelectInst *SI = dyn_cast<SelectInst>(V);
00029   if (!SI) return SPF_UNKNOWN;
00030 
00031   ICmpInst *ICI = dyn_cast<ICmpInst>(SI->getCondition());
00032   if (!ICI) return SPF_UNKNOWN;
00033 
00034   ICmpInst::Predicate Pred = ICI->getPredicate();
00035   Value *CmpLHS = ICI->getOperand(0);
00036   Value *CmpRHS = ICI->getOperand(1);
00037   Value *TrueVal = SI->getTrueValue();
00038   Value *FalseVal = SI->getFalseValue();
00039 
00040   LHS = CmpLHS;
00041   RHS = CmpRHS;
00042 
00043   // (icmp X, Y) ? X : Y
00044   if (TrueVal == CmpLHS && FalseVal == CmpRHS) {
00045     switch (Pred) {
00046     default: return SPF_UNKNOWN; // Equality.
00047     case ICmpInst::ICMP_UGT:
00048     case ICmpInst::ICMP_UGE: return SPF_UMAX;
00049     case ICmpInst::ICMP_SGT:
00050     case ICmpInst::ICMP_SGE: return SPF_SMAX;
00051     case ICmpInst::ICMP_ULT:
00052     case ICmpInst::ICMP_ULE: return SPF_UMIN;
00053     case ICmpInst::ICMP_SLT:
00054     case ICmpInst::ICMP_SLE: return SPF_SMIN;
00055     }
00056   }
00057 
00058   // (icmp X, Y) ? Y : X
00059   if (TrueVal == CmpRHS && FalseVal == CmpLHS) {
00060     switch (Pred) {
00061     default: return SPF_UNKNOWN; // Equality.
00062     case ICmpInst::ICMP_UGT:
00063     case ICmpInst::ICMP_UGE: return SPF_UMIN;
00064     case ICmpInst::ICMP_SGT:
00065     case ICmpInst::ICMP_SGE: return SPF_SMIN;
00066     case ICmpInst::ICMP_ULT:
00067     case ICmpInst::ICMP_ULE: return SPF_UMAX;
00068     case ICmpInst::ICMP_SLT:
00069     case ICmpInst::ICMP_SLE: return SPF_SMAX;
00070     }
00071   }
00072 
00073   if (ConstantInt *C1 = dyn_cast<ConstantInt>(CmpRHS)) {
00074     if ((CmpLHS == TrueVal && match(FalseVal, m_Neg(m_Specific(CmpLHS)))) ||
00075         (CmpLHS == FalseVal && match(TrueVal, m_Neg(m_Specific(CmpLHS))))) {
00076 
00077       // ABS(X) ==> (X >s 0) ? X : -X and (X >s -1) ? X : -X
00078       // NABS(X) ==> (X >s 0) ? -X : X and (X >s -1) ? -X : X
00079       if (Pred == ICmpInst::ICMP_SGT && (C1->isZero() || C1->isMinusOne())) {
00080         return (CmpLHS == TrueVal) ? SPF_ABS : SPF_NABS;
00081       }
00082 
00083       // ABS(X) ==> (X <s 0) ? -X : X and (X <s 1) ? -X : X
00084       // NABS(X) ==> (X <s 0) ? X : -X and (X <s 1) ? X : -X
00085       if (Pred == ICmpInst::ICMP_SLT && (C1->isZero() || C1->isOne())) {
00086         return (CmpLHS == FalseVal) ? SPF_ABS : SPF_NABS;
00087       }
00088     }
00089   }
00090 
00091   // TODO: (X > 4) ? X : 5   -->  (X >= 5) ? X : 5  -->  MAX(X, 5)
00092 
00093   return SPF_UNKNOWN;
00094 }
00095 
00096 
00097 /// GetSelectFoldableOperands - We want to turn code that looks like this:
00098 ///   %C = or %A, %B
00099 ///   %D = select %cond, %C, %A
00100 /// into:
00101 ///   %C = select %cond, %B, 0
00102 ///   %D = or %A, %C
00103 ///
00104 /// Assuming that the specified instruction is an operand to the select, return
00105 /// a bitmask indicating which operands of this instruction are foldable if they
00106 /// equal the other incoming value of the select.
00107 ///
00108 static unsigned GetSelectFoldableOperands(Instruction *I) {
00109   switch (I->getOpcode()) {
00110   case Instruction::Add:
00111   case Instruction::Mul:
00112   case Instruction::And:
00113   case Instruction::Or:
00114   case Instruction::Xor:
00115     return 3;              // Can fold through either operand.
00116   case Instruction::Sub:   // Can only fold on the amount subtracted.
00117   case Instruction::Shl:   // Can only fold on the shift amount.
00118   case Instruction::LShr:
00119   case Instruction::AShr:
00120     return 1;
00121   default:
00122     return 0;              // Cannot fold
00123   }
00124 }
00125 
00126 /// GetSelectFoldableConstant - For the same transformation as the previous
00127 /// function, return the identity constant that goes into the select.
00128 static Constant *GetSelectFoldableConstant(Instruction *I) {
00129   switch (I->getOpcode()) {
00130   default: llvm_unreachable("This cannot happen!");
00131   case Instruction::Add:
00132   case Instruction::Sub:
00133   case Instruction::Or:
00134   case Instruction::Xor:
00135   case Instruction::Shl:
00136   case Instruction::LShr:
00137   case Instruction::AShr:
00138     return Constant::getNullValue(I->getType());
00139   case Instruction::And:
00140     return Constant::getAllOnesValue(I->getType());
00141   case Instruction::Mul:
00142     return ConstantInt::get(I->getType(), 1);
00143   }
00144 }
00145 
00146 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
00147 /// have the same opcode and only one use each.  Try to simplify this.
00148 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
00149                                           Instruction *FI) {
00150   if (TI->getNumOperands() == 1) {
00151     // If this is a non-volatile load or a cast from the same type,
00152     // merge.
00153     if (TI->isCast()) {
00154       Type *FIOpndTy = FI->getOperand(0)->getType();
00155       if (TI->getOperand(0)->getType() != FIOpndTy)
00156         return nullptr;
00157       // The select condition may be a vector. We may only change the operand
00158       // type if the vector width remains the same (and matches the condition).
00159       Type *CondTy = SI.getCondition()->getType();
00160       if (CondTy->isVectorTy() && (!FIOpndTy->isVectorTy() ||
00161           CondTy->getVectorNumElements() != FIOpndTy->getVectorNumElements()))
00162         return nullptr;
00163     } else {
00164       return nullptr;  // unknown unary op.
00165     }
00166 
00167     // Fold this by inserting a select from the input values.
00168     Value *NewSI = Builder->CreateSelect(SI.getCondition(), TI->getOperand(0),
00169                                          FI->getOperand(0), SI.getName()+".v");
00170     return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
00171                             TI->getType());
00172   }
00173 
00174   // Only handle binary operators here.
00175   if (!isa<BinaryOperator>(TI))
00176     return nullptr;
00177 
00178   // Figure out if the operations have any operands in common.
00179   Value *MatchOp, *OtherOpT, *OtherOpF;
00180   bool MatchIsOpZero;
00181   if (TI->getOperand(0) == FI->getOperand(0)) {
00182     MatchOp  = TI->getOperand(0);
00183     OtherOpT = TI->getOperand(1);
00184     OtherOpF = FI->getOperand(1);
00185     MatchIsOpZero = true;
00186   } else if (TI->getOperand(1) == FI->getOperand(1)) {
00187     MatchOp  = TI->getOperand(1);
00188     OtherOpT = TI->getOperand(0);
00189     OtherOpF = FI->getOperand(0);
00190     MatchIsOpZero = false;
00191   } else if (!TI->isCommutative()) {
00192     return nullptr;
00193   } else if (TI->getOperand(0) == FI->getOperand(1)) {
00194     MatchOp  = TI->getOperand(0);
00195     OtherOpT = TI->getOperand(1);
00196     OtherOpF = FI->getOperand(0);
00197     MatchIsOpZero = true;
00198   } else if (TI->getOperand(1) == FI->getOperand(0)) {
00199     MatchOp  = TI->getOperand(1);
00200     OtherOpT = TI->getOperand(0);
00201     OtherOpF = FI->getOperand(1);
00202     MatchIsOpZero = true;
00203   } else {
00204     return nullptr;
00205   }
00206 
00207   // If we reach here, they do have operations in common.
00208   Value *NewSI = Builder->CreateSelect(SI.getCondition(), OtherOpT,
00209                                        OtherOpF, SI.getName()+".v");
00210 
00211   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
00212     if (MatchIsOpZero)
00213       return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
00214     else
00215       return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
00216   }
00217   llvm_unreachable("Shouldn't get here");
00218 }
00219 
00220 static bool isSelect01(Constant *C1, Constant *C2) {
00221   ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
00222   if (!C1I)
00223     return false;
00224   ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
00225   if (!C2I)
00226     return false;
00227   if (!C1I->isZero() && !C2I->isZero()) // One side must be zero.
00228     return false;
00229   return C1I->isOne() || C1I->isAllOnesValue() ||
00230          C2I->isOne() || C2I->isAllOnesValue();
00231 }
00232 
00233 /// FoldSelectIntoOp - Try fold the select into one of the operands to
00234 /// facilitate further optimization.
00235 Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
00236                                             Value *FalseVal) {
00237   // See the comment above GetSelectFoldableOperands for a description of the
00238   // transformation we are doing here.
00239   if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
00240     if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
00241         !isa<Constant>(FalseVal)) {
00242       if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
00243         unsigned OpToFold = 0;
00244         if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
00245           OpToFold = 1;
00246         } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
00247           OpToFold = 2;
00248         }
00249 
00250         if (OpToFold) {
00251           Constant *C = GetSelectFoldableConstant(TVI);
00252           Value *OOp = TVI->getOperand(2-OpToFold);
00253           // Avoid creating select between 2 constants unless it's selecting
00254           // between 0, 1 and -1.
00255           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
00256             Value *NewSel = Builder->CreateSelect(SI.getCondition(), OOp, C);
00257             NewSel->takeName(TVI);
00258             BinaryOperator *TVI_BO = cast<BinaryOperator>(TVI);
00259             BinaryOperator *BO = BinaryOperator::Create(TVI_BO->getOpcode(),
00260                                                         FalseVal, NewSel);
00261             if (isa<PossiblyExactOperator>(BO))
00262               BO->setIsExact(TVI_BO->isExact());
00263             if (isa<OverflowingBinaryOperator>(BO)) {
00264               BO->setHasNoUnsignedWrap(TVI_BO->hasNoUnsignedWrap());
00265               BO->setHasNoSignedWrap(TVI_BO->hasNoSignedWrap());
00266             }
00267             return BO;
00268           }
00269         }
00270       }
00271     }
00272   }
00273 
00274   if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
00275     if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
00276         !isa<Constant>(TrueVal)) {
00277       if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
00278         unsigned OpToFold = 0;
00279         if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
00280           OpToFold = 1;
00281         } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
00282           OpToFold = 2;
00283         }
00284 
00285         if (OpToFold) {
00286           Constant *C = GetSelectFoldableConstant(FVI);
00287           Value *OOp = FVI->getOperand(2-OpToFold);
00288           // Avoid creating select between 2 constants unless it's selecting
00289           // between 0, 1 and -1.
00290           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
00291             Value *NewSel = Builder->CreateSelect(SI.getCondition(), C, OOp);
00292             NewSel->takeName(FVI);
00293             BinaryOperator *FVI_BO = cast<BinaryOperator>(FVI);
00294             BinaryOperator *BO = BinaryOperator::Create(FVI_BO->getOpcode(),
00295                                                         TrueVal, NewSel);
00296             if (isa<PossiblyExactOperator>(BO))
00297               BO->setIsExact(FVI_BO->isExact());
00298             if (isa<OverflowingBinaryOperator>(BO)) {
00299               BO->setHasNoUnsignedWrap(FVI_BO->hasNoUnsignedWrap());
00300               BO->setHasNoSignedWrap(FVI_BO->hasNoSignedWrap());
00301             }
00302             return BO;
00303           }
00304         }
00305       }
00306     }
00307   }
00308 
00309   return nullptr;
00310 }
00311 
00312 /// SimplifyWithOpReplaced - See if V simplifies when its operand Op is
00313 /// replaced with RepOp.
00314 static Value *SimplifyWithOpReplaced(Value *V, Value *Op, Value *RepOp,
00315                                      const DataLayout *TD,
00316                                      const TargetLibraryInfo *TLI) {
00317   // Trivial replacement.
00318   if (V == Op)
00319     return RepOp;
00320 
00321   Instruction *I = dyn_cast<Instruction>(V);
00322   if (!I)
00323     return nullptr;
00324 
00325   // If this is a binary operator, try to simplify it with the replaced op.
00326   if (BinaryOperator *B = dyn_cast<BinaryOperator>(I)) {
00327     if (B->getOperand(0) == Op)
00328       return SimplifyBinOp(B->getOpcode(), RepOp, B->getOperand(1), TD, TLI);
00329     if (B->getOperand(1) == Op)
00330       return SimplifyBinOp(B->getOpcode(), B->getOperand(0), RepOp, TD, TLI);
00331   }
00332 
00333   // Same for CmpInsts.
00334   if (CmpInst *C = dyn_cast<CmpInst>(I)) {
00335     if (C->getOperand(0) == Op)
00336       return SimplifyCmpInst(C->getPredicate(), RepOp, C->getOperand(1), TD,
00337                              TLI);
00338     if (C->getOperand(1) == Op)
00339       return SimplifyCmpInst(C->getPredicate(), C->getOperand(0), RepOp, TD,
00340                              TLI);
00341   }
00342 
00343   // TODO: We could hand off more cases to instsimplify here.
00344 
00345   // If all operands are constant after substituting Op for RepOp then we can
00346   // constant fold the instruction.
00347   if (Constant *CRepOp = dyn_cast<Constant>(RepOp)) {
00348     // Build a list of all constant operands.
00349     SmallVector<Constant*, 8> ConstOps;
00350     for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
00351       if (I->getOperand(i) == Op)
00352         ConstOps.push_back(CRepOp);
00353       else if (Constant *COp = dyn_cast<Constant>(I->getOperand(i)))
00354         ConstOps.push_back(COp);
00355       else
00356         break;
00357     }
00358 
00359     // All operands were constants, fold it.
00360     if (ConstOps.size() == I->getNumOperands()) {
00361       if (CmpInst *C = dyn_cast<CmpInst>(I))
00362         return ConstantFoldCompareInstOperands(C->getPredicate(), ConstOps[0],
00363                                                ConstOps[1], TD, TLI);
00364 
00365       if (LoadInst *LI = dyn_cast<LoadInst>(I))
00366         if (!LI->isVolatile())
00367           return ConstantFoldLoadFromConstPtr(ConstOps[0], TD);
00368 
00369       return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
00370                                       ConstOps, TD, TLI);
00371     }
00372   }
00373 
00374   return nullptr;
00375 }
00376 
00377 /// foldSelectICmpAndOr - We want to turn:
00378 ///   (select (icmp eq (and X, C1), 0), Y, (or Y, C2))
00379 /// into:
00380 ///   (or (shl (and X, C1), C3), y)
00381 /// iff:
00382 ///   C1 and C2 are both powers of 2
00383 /// where:
00384 ///   C3 = Log(C2) - Log(C1)
00385 ///
00386 /// This transform handles cases where:
00387 /// 1. The icmp predicate is inverted
00388 /// 2. The select operands are reversed
00389 /// 3. The magnitude of C2 and C1 are flipped
00390 ///
00391 /// This also tries to turn
00392 /// --- Single bit tests:
00393 /// if ((x & C) == 0) x |= C  to  x |= C
00394 /// if ((x & C) != 0) x ^= C  to  x &= ~C
00395 /// if ((x & C) == 0) x ^= C  to  x |= C
00396 /// if ((x & C) != 0) x &= ~C to  x &= ~C
00397 /// if ((x & C) == 0) x &= ~C to  nothing
00398 static Value *foldSelectICmpAndOr(SelectInst &SI, Value *TrueVal,
00399                                   Value *FalseVal,
00400                                   InstCombiner::BuilderTy *Builder) {
00401   const ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition());
00402   if (!IC || !IC->isEquality() || !SI.getType()->isIntegerTy())
00403     return nullptr;
00404 
00405   Value *CmpLHS = IC->getOperand(0);
00406   Value *CmpRHS = IC->getOperand(1);
00407 
00408   if (!match(CmpRHS, m_Zero()))
00409     return nullptr;
00410 
00411   Value *X;
00412   const APInt *C1;
00413   if (!match(CmpLHS, m_And(m_Value(X), m_Power2(C1))))
00414     return nullptr;
00415 
00416   const APInt *C2;
00417   if (match(TrueVal, m_Specific(X))) {
00418     // if ((X & C) != 0) X ^= C becomes X &= ~C
00419     if (match(FalseVal, m_Xor(m_Specific(X), m_APInt(C2))) && C1 == C2)
00420       return Builder->CreateAnd(X, ~(*C1));
00421     // if ((X & C) != 0) X &= ~C becomes X &= ~C
00422     if (match(FalseVal, m_And(m_Specific(X), m_APInt(C2))) && *C1 == ~(*C2))
00423       return FalseVal;
00424   } else if (match(FalseVal, m_Specific(X))) {
00425     // if ((X & C) == 0) X ^= C becomes X |= C
00426     if (match(TrueVal, m_Xor(m_Specific(X), m_APInt(C2))) && C1 == C2)
00427       return Builder->CreateOr(X, *C1);
00428     // if ((X & C) == 0) X &= ~C becomes nothing
00429     if (match(TrueVal, m_And(m_Specific(X), m_APInt(C2))) && *C1 == ~(*C2))
00430       return X;
00431     // if ((X & C) == 0) X |= C becomes X |= C
00432     if (match(TrueVal, m_Or(m_Specific(X), m_APInt(C2))) && C1 == C2)
00433       return TrueVal;
00434   }
00435 
00436   bool OrOnTrueVal = false;
00437   bool OrOnFalseVal = match(FalseVal, m_Or(m_Specific(TrueVal), m_Power2(C2)));
00438   if (!OrOnFalseVal)
00439     OrOnTrueVal = match(TrueVal, m_Or(m_Specific(FalseVal), m_Power2(C2)));
00440 
00441   if (!OrOnFalseVal && !OrOnTrueVal)
00442     return nullptr;
00443 
00444   Value *V = CmpLHS;
00445   Value *Y = OrOnFalseVal ? TrueVal : FalseVal;
00446 
00447   unsigned C1Log = C1->logBase2();
00448   unsigned C2Log = C2->logBase2();
00449   if (C2Log > C1Log) {
00450     V = Builder->CreateZExtOrTrunc(V, Y->getType());
00451     V = Builder->CreateShl(V, C2Log - C1Log);
00452   } else if (C1Log > C2Log) {
00453     V = Builder->CreateLShr(V, C1Log - C2Log);
00454     V = Builder->CreateZExtOrTrunc(V, Y->getType());
00455   } else
00456     V = Builder->CreateZExtOrTrunc(V, Y->getType());
00457 
00458   ICmpInst::Predicate Pred = IC->getPredicate();
00459   if ((Pred == ICmpInst::ICMP_NE && OrOnFalseVal) ||
00460       (Pred == ICmpInst::ICMP_EQ && OrOnTrueVal))
00461     V = Builder->CreateXor(V, *C2);
00462 
00463   return Builder->CreateOr(V, Y);
00464 }
00465 
00466 /// visitSelectInstWithICmp - Visit a SelectInst that has an
00467 /// ICmpInst as its first operand.
00468 ///
00469 Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
00470                                                    ICmpInst *ICI) {
00471   bool Changed = false;
00472   ICmpInst::Predicate Pred = ICI->getPredicate();
00473   Value *CmpLHS = ICI->getOperand(0);
00474   Value *CmpRHS = ICI->getOperand(1);
00475   Value *TrueVal = SI.getTrueValue();
00476   Value *FalseVal = SI.getFalseValue();
00477 
00478   // Check cases where the comparison is with a constant that
00479   // can be adjusted to fit the min/max idiom. We may move or edit ICI
00480   // here, so make sure the select is the only user.
00481   if (ICI->hasOneUse())
00482     if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
00483       // X < MIN ? T : F  -->  F
00484       if ((Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_ULT)
00485           && CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
00486         return ReplaceInstUsesWith(SI, FalseVal);
00487       // X > MAX ? T : F  -->  F
00488       else if ((Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_UGT)
00489                && CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
00490         return ReplaceInstUsesWith(SI, FalseVal);
00491       switch (Pred) {
00492       default: break;
00493       case ICmpInst::ICMP_ULT:
00494       case ICmpInst::ICMP_SLT:
00495       case ICmpInst::ICMP_UGT:
00496       case ICmpInst::ICMP_SGT: {
00497         // These transformations only work for selects over integers.
00498         IntegerType *SelectTy = dyn_cast<IntegerType>(SI.getType());
00499         if (!SelectTy)
00500           break;
00501 
00502         Constant *AdjustedRHS;
00503         if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_SGT)
00504           AdjustedRHS = ConstantInt::get(CI->getContext(), CI->getValue() + 1);
00505         else // (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT)
00506           AdjustedRHS = ConstantInt::get(CI->getContext(), CI->getValue() - 1);
00507 
00508         // X > C ? X : C+1  -->  X < C+1 ? C+1 : X
00509         // X < C ? X : C-1  -->  X > C-1 ? C-1 : X
00510         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
00511             (CmpLHS == FalseVal && AdjustedRHS == TrueVal))
00512           ; // Nothing to do here. Values match without any sign/zero extension.
00513 
00514         // Types do not match. Instead of calculating this with mixed types
00515         // promote all to the larger type. This enables scalar evolution to
00516         // analyze this expression.
00517         else if (CmpRHS->getType()->getScalarSizeInBits()
00518                  < SelectTy->getBitWidth()) {
00519           Constant *sextRHS = ConstantExpr::getSExt(AdjustedRHS, SelectTy);
00520 
00521           // X = sext x; x >s c ? X : C+1 --> X = sext x; X <s C+1 ? C+1 : X
00522           // X = sext x; x <s c ? X : C-1 --> X = sext x; X >s C-1 ? C-1 : X
00523           // X = sext x; x >u c ? X : C+1 --> X = sext x; X <u C+1 ? C+1 : X
00524           // X = sext x; x <u c ? X : C-1 --> X = sext x; X >u C-1 ? C-1 : X
00525           if (match(TrueVal, m_SExt(m_Specific(CmpLHS))) &&
00526                 sextRHS == FalseVal) {
00527             CmpLHS = TrueVal;
00528             AdjustedRHS = sextRHS;
00529           } else if (match(FalseVal, m_SExt(m_Specific(CmpLHS))) &&
00530                      sextRHS == TrueVal) {
00531             CmpLHS = FalseVal;
00532             AdjustedRHS = sextRHS;
00533           } else if (ICI->isUnsigned()) {
00534             Constant *zextRHS = ConstantExpr::getZExt(AdjustedRHS, SelectTy);
00535             // X = zext x; x >u c ? X : C+1 --> X = zext x; X <u C+1 ? C+1 : X
00536             // X = zext x; x <u c ? X : C-1 --> X = zext x; X >u C-1 ? C-1 : X
00537             // zext + signed compare cannot be changed:
00538             //    0xff <s 0x00, but 0x00ff >s 0x0000
00539             if (match(TrueVal, m_ZExt(m_Specific(CmpLHS))) &&
00540                 zextRHS == FalseVal) {
00541               CmpLHS = TrueVal;
00542               AdjustedRHS = zextRHS;
00543             } else if (match(FalseVal, m_ZExt(m_Specific(CmpLHS))) &&
00544                        zextRHS == TrueVal) {
00545               CmpLHS = FalseVal;
00546               AdjustedRHS = zextRHS;
00547             } else
00548               break;
00549           } else
00550             break;
00551         } else
00552           break;
00553 
00554         Pred = ICmpInst::getSwappedPredicate(Pred);
00555         CmpRHS = AdjustedRHS;
00556         std::swap(FalseVal, TrueVal);
00557         ICI->setPredicate(Pred);
00558         ICI->setOperand(0, CmpLHS);
00559         ICI->setOperand(1, CmpRHS);
00560         SI.setOperand(1, TrueVal);
00561         SI.setOperand(2, FalseVal);
00562 
00563         // Move ICI instruction right before the select instruction. Otherwise
00564         // the sext/zext value may be defined after the ICI instruction uses it.
00565         ICI->moveBefore(&SI);
00566 
00567         Changed = true;
00568         break;
00569       }
00570       }
00571     }
00572 
00573   // Transform (X >s -1) ? C1 : C2 --> ((X >>s 31) & (C2 - C1)) + C1
00574   // and       (X <s  0) ? C2 : C1 --> ((X >>s 31) & (C2 - C1)) + C1
00575   // FIXME: Type and constness constraints could be lifted, but we have to
00576   //        watch code size carefully. We should consider xor instead of
00577   //        sub/add when we decide to do that.
00578   if (IntegerType *Ty = dyn_cast<IntegerType>(CmpLHS->getType())) {
00579     if (TrueVal->getType() == Ty) {
00580       if (ConstantInt *Cmp = dyn_cast<ConstantInt>(CmpRHS)) {
00581         ConstantInt *C1 = nullptr, *C2 = nullptr;
00582         if (Pred == ICmpInst::ICMP_SGT && Cmp->isAllOnesValue()) {
00583           C1 = dyn_cast<ConstantInt>(TrueVal);
00584           C2 = dyn_cast<ConstantInt>(FalseVal);
00585         } else if (Pred == ICmpInst::ICMP_SLT && Cmp->isNullValue()) {
00586           C1 = dyn_cast<ConstantInt>(FalseVal);
00587           C2 = dyn_cast<ConstantInt>(TrueVal);
00588         }
00589         if (C1 && C2) {
00590           // This shift results in either -1 or 0.
00591           Value *AShr = Builder->CreateAShr(CmpLHS, Ty->getBitWidth()-1);
00592 
00593           // Check if we can express the operation with a single or.
00594           if (C2->isAllOnesValue())
00595             return ReplaceInstUsesWith(SI, Builder->CreateOr(AShr, C1));
00596 
00597           Value *And = Builder->CreateAnd(AShr, C2->getValue()-C1->getValue());
00598           return ReplaceInstUsesWith(SI, Builder->CreateAdd(And, C1));
00599         }
00600       }
00601     }
00602   }
00603 
00604   // If we have an equality comparison then we know the value in one of the
00605   // arms of the select. See if substituting this value into the arm and
00606   // simplifying the result yields the same value as the other arm.
00607   if (Pred == ICmpInst::ICMP_EQ) {
00608     if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, DL, TLI) == TrueVal ||
00609         SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, DL, TLI) == TrueVal)
00610       return ReplaceInstUsesWith(SI, FalseVal);
00611     if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, DL, TLI) == FalseVal ||
00612         SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, DL, TLI) == FalseVal)
00613       return ReplaceInstUsesWith(SI, FalseVal);
00614   } else if (Pred == ICmpInst::ICMP_NE) {
00615     if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, DL, TLI) == FalseVal ||
00616         SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, DL, TLI) == FalseVal)
00617       return ReplaceInstUsesWith(SI, TrueVal);
00618     if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, DL, TLI) == TrueVal ||
00619         SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, DL, TLI) == TrueVal)
00620       return ReplaceInstUsesWith(SI, TrueVal);
00621   }
00622 
00623   // NOTE: if we wanted to, this is where to detect integer MIN/MAX
00624 
00625   if (CmpRHS != CmpLHS && isa<Constant>(CmpRHS)) {
00626     if (CmpLHS == TrueVal && Pred == ICmpInst::ICMP_EQ) {
00627       // Transform (X == C) ? X : Y -> (X == C) ? C : Y
00628       SI.setOperand(1, CmpRHS);
00629       Changed = true;
00630     } else if (CmpLHS == FalseVal && Pred == ICmpInst::ICMP_NE) {
00631       // Transform (X != C) ? Y : X -> (X != C) ? Y : C
00632       SI.setOperand(2, CmpRHS);
00633       Changed = true;
00634     }
00635   }
00636 
00637   if (Value *V = foldSelectICmpAndOr(SI, TrueVal, FalseVal, Builder))
00638     return ReplaceInstUsesWith(SI, V);
00639 
00640   return Changed ? &SI : nullptr;
00641 }
00642 
00643 
00644 /// CanSelectOperandBeMappingIntoPredBlock - SI is a select whose condition is a
00645 /// PHI node (but the two may be in different blocks).  See if the true/false
00646 /// values (V) are live in all of the predecessor blocks of the PHI.  For
00647 /// example, cases like this cannot be mapped:
00648 ///
00649 ///   X = phi [ C1, BB1], [C2, BB2]
00650 ///   Y = add
00651 ///   Z = select X, Y, 0
00652 ///
00653 /// because Y is not live in BB1/BB2.
00654 ///
00655 static bool CanSelectOperandBeMappingIntoPredBlock(const Value *V,
00656                                                    const SelectInst &SI) {
00657   // If the value is a non-instruction value like a constant or argument, it
00658   // can always be mapped.
00659   const Instruction *I = dyn_cast<Instruction>(V);
00660   if (!I) return true;
00661 
00662   // If V is a PHI node defined in the same block as the condition PHI, we can
00663   // map the arguments.
00664   const PHINode *CondPHI = cast<PHINode>(SI.getCondition());
00665 
00666   if (const PHINode *VP = dyn_cast<PHINode>(I))
00667     if (VP->getParent() == CondPHI->getParent())
00668       return true;
00669 
00670   // Otherwise, if the PHI and select are defined in the same block and if V is
00671   // defined in a different block, then we can transform it.
00672   if (SI.getParent() == CondPHI->getParent() &&
00673       I->getParent() != CondPHI->getParent())
00674     return true;
00675 
00676   // Otherwise we have a 'hard' case and we can't tell without doing more
00677   // detailed dominator based analysis, punt.
00678   return false;
00679 }
00680 
00681 /// FoldSPFofSPF - We have an SPF (e.g. a min or max) of an SPF of the form:
00682 ///   SPF2(SPF1(A, B), C)
00683 Instruction *InstCombiner::FoldSPFofSPF(Instruction *Inner,
00684                                         SelectPatternFlavor SPF1,
00685                                         Value *A, Value *B,
00686                                         Instruction &Outer,
00687                                         SelectPatternFlavor SPF2, Value *C) {
00688   if (C == A || C == B) {
00689     // MAX(MAX(A, B), B) -> MAX(A, B)
00690     // MIN(MIN(a, b), a) -> MIN(a, b)
00691     if (SPF1 == SPF2)
00692       return ReplaceInstUsesWith(Outer, Inner);
00693 
00694     // MAX(MIN(a, b), a) -> a
00695     // MIN(MAX(a, b), a) -> a
00696     if ((SPF1 == SPF_SMIN && SPF2 == SPF_SMAX) ||
00697         (SPF1 == SPF_SMAX && SPF2 == SPF_SMIN) ||
00698         (SPF1 == SPF_UMIN && SPF2 == SPF_UMAX) ||
00699         (SPF1 == SPF_UMAX && SPF2 == SPF_UMIN))
00700       return ReplaceInstUsesWith(Outer, C);
00701   }
00702 
00703   if (SPF1 == SPF2) {
00704     if (ConstantInt *CB = dyn_cast<ConstantInt>(B)) {
00705       if (ConstantInt *CC = dyn_cast<ConstantInt>(C)) {
00706         APInt ACB = CB->getValue();
00707         APInt ACC = CC->getValue();
00708 
00709         // MIN(MIN(A, 23), 97) -> MIN(A, 23)
00710         // MAX(MAX(A, 97), 23) -> MAX(A, 97)
00711         if ((SPF1 == SPF_UMIN && ACB.ule(ACC)) ||
00712             (SPF1 == SPF_SMIN && ACB.sle(ACC)) ||
00713             (SPF1 == SPF_UMAX && ACB.uge(ACC)) ||
00714             (SPF1 == SPF_SMAX && ACB.sge(ACC)))
00715           return ReplaceInstUsesWith(Outer, Inner);
00716 
00717         // MIN(MIN(A, 97), 23) -> MIN(A, 23)
00718         // MAX(MAX(A, 23), 97) -> MAX(A, 97)
00719         if ((SPF1 == SPF_UMIN && ACB.ugt(ACC)) ||
00720             (SPF1 == SPF_SMIN && ACB.sgt(ACC)) ||
00721             (SPF1 == SPF_UMAX && ACB.ult(ACC)) ||
00722             (SPF1 == SPF_SMAX && ACB.slt(ACC))) {
00723           Outer.replaceUsesOfWith(Inner, A);
00724           return &Outer;
00725         }
00726       }
00727     }
00728   }
00729 
00730   // ABS(ABS(X)) -> ABS(X)
00731   // NABS(NABS(X)) -> NABS(X)
00732   if (SPF1 == SPF2 && (SPF1 == SPF_ABS || SPF1 == SPF_NABS)) {
00733     return ReplaceInstUsesWith(Outer, Inner);
00734   }
00735 
00736   // ABS(NABS(X)) -> ABS(X)
00737   // NABS(ABS(X)) -> NABS(X)
00738   if ((SPF1 == SPF_ABS && SPF2 == SPF_NABS) ||
00739       (SPF1 == SPF_NABS && SPF2 == SPF_ABS)) {
00740     SelectInst *SI = cast<SelectInst>(Inner);
00741     Value *NewSI = Builder->CreateSelect(
00742         SI->getCondition(), SI->getFalseValue(), SI->getTrueValue());
00743     return ReplaceInstUsesWith(Outer, NewSI);
00744   }
00745   return nullptr;
00746 }
00747 
00748 /// foldSelectICmpAnd - If one of the constants is zero (we know they can't
00749 /// both be) and we have an icmp instruction with zero, and we have an 'and'
00750 /// with the non-constant value and a power of two we can turn the select
00751 /// into a shift on the result of the 'and'.
00752 static Value *foldSelectICmpAnd(const SelectInst &SI, ConstantInt *TrueVal,
00753                                 ConstantInt *FalseVal,
00754                                 InstCombiner::BuilderTy *Builder) {
00755   const ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition());
00756   if (!IC || !IC->isEquality() || !SI.getType()->isIntegerTy())
00757     return nullptr;
00758 
00759   if (!match(IC->getOperand(1), m_Zero()))
00760     return nullptr;
00761 
00762   ConstantInt *AndRHS;
00763   Value *LHS = IC->getOperand(0);
00764   if (!match(LHS, m_And(m_Value(), m_ConstantInt(AndRHS))))
00765     return nullptr;
00766 
00767   // If both select arms are non-zero see if we have a select of the form
00768   // 'x ? 2^n + C : C'. Then we can offset both arms by C, use the logic
00769   // for 'x ? 2^n : 0' and fix the thing up at the end.
00770   ConstantInt *Offset = nullptr;
00771   if (!TrueVal->isZero() && !FalseVal->isZero()) {
00772     if ((TrueVal->getValue() - FalseVal->getValue()).isPowerOf2())
00773       Offset = FalseVal;
00774     else if ((FalseVal->getValue() - TrueVal->getValue()).isPowerOf2())
00775       Offset = TrueVal;
00776     else
00777       return nullptr;
00778 
00779     // Adjust TrueVal and FalseVal to the offset.
00780     TrueVal = ConstantInt::get(Builder->getContext(),
00781                                TrueVal->getValue() - Offset->getValue());
00782     FalseVal = ConstantInt::get(Builder->getContext(),
00783                                 FalseVal->getValue() - Offset->getValue());
00784   }
00785 
00786   // Make sure the mask in the 'and' and one of the select arms is a power of 2.
00787   if (!AndRHS->getValue().isPowerOf2() ||
00788       (!TrueVal->getValue().isPowerOf2() &&
00789        !FalseVal->getValue().isPowerOf2()))
00790     return nullptr;
00791 
00792   // Determine which shift is needed to transform result of the 'and' into the
00793   // desired result.
00794   ConstantInt *ValC = !TrueVal->isZero() ? TrueVal : FalseVal;
00795   unsigned ValZeros = ValC->getValue().logBase2();
00796   unsigned AndZeros = AndRHS->getValue().logBase2();
00797 
00798   // If types don't match we can still convert the select by introducing a zext
00799   // or a trunc of the 'and'. The trunc case requires that all of the truncated
00800   // bits are zero, we can figure that out by looking at the 'and' mask.
00801   if (AndZeros >= ValC->getBitWidth())
00802     return nullptr;
00803 
00804   Value *V = Builder->CreateZExtOrTrunc(LHS, SI.getType());
00805   if (ValZeros > AndZeros)
00806     V = Builder->CreateShl(V, ValZeros - AndZeros);
00807   else if (ValZeros < AndZeros)
00808     V = Builder->CreateLShr(V, AndZeros - ValZeros);
00809 
00810   // Okay, now we know that everything is set up, we just don't know whether we
00811   // have a icmp_ne or icmp_eq and whether the true or false val is the zero.
00812   bool ShouldNotVal = !TrueVal->isZero();
00813   ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
00814   if (ShouldNotVal)
00815     V = Builder->CreateXor(V, ValC);
00816 
00817   // Apply an offset if needed.
00818   if (Offset)
00819     V = Builder->CreateAdd(V, Offset);
00820   return V;
00821 }
00822 
00823 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
00824   Value *CondVal = SI.getCondition();
00825   Value *TrueVal = SI.getTrueValue();
00826   Value *FalseVal = SI.getFalseValue();
00827 
00828   if (Value *V = SimplifySelectInst(CondVal, TrueVal, FalseVal, DL))
00829     return ReplaceInstUsesWith(SI, V);
00830 
00831   if (SI.getType()->isIntegerTy(1)) {
00832     if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
00833       if (C->getZExtValue()) {
00834         // Change: A = select B, true, C --> A = or B, C
00835         return BinaryOperator::CreateOr(CondVal, FalseVal);
00836       }
00837       // Change: A = select B, false, C --> A = and !B, C
00838       Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName());
00839       return BinaryOperator::CreateAnd(NotCond, FalseVal);
00840     }
00841     if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
00842       if (C->getZExtValue() == false) {
00843         // Change: A = select B, C, false --> A = and B, C
00844         return BinaryOperator::CreateAnd(CondVal, TrueVal);
00845       }
00846       // Change: A = select B, C, true --> A = or !B, C
00847       Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName());
00848       return BinaryOperator::CreateOr(NotCond, TrueVal);
00849     }
00850 
00851     // select a, b, a  -> a&b
00852     // select a, a, b  -> a|b
00853     if (CondVal == TrueVal)
00854       return BinaryOperator::CreateOr(CondVal, FalseVal);
00855     if (CondVal == FalseVal)
00856       return BinaryOperator::CreateAnd(CondVal, TrueVal);
00857 
00858     // select a, ~a, b -> (~a)&b
00859     // select a, b, ~a -> (~a)|b
00860     if (match(TrueVal, m_Not(m_Specific(CondVal))))
00861       return BinaryOperator::CreateAnd(TrueVal, FalseVal);
00862     if (match(FalseVal, m_Not(m_Specific(CondVal))))
00863       return BinaryOperator::CreateOr(TrueVal, FalseVal);
00864   }
00865 
00866   // Selecting between two integer constants?
00867   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
00868     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
00869       // select C, 1, 0 -> zext C to int
00870       if (FalseValC->isZero() && TrueValC->getValue() == 1)
00871         return new ZExtInst(CondVal, SI.getType());
00872 
00873       // select C, -1, 0 -> sext C to int
00874       if (FalseValC->isZero() && TrueValC->isAllOnesValue())
00875         return new SExtInst(CondVal, SI.getType());
00876 
00877       // select C, 0, 1 -> zext !C to int
00878       if (TrueValC->isZero() && FalseValC->getValue() == 1) {
00879         Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName());
00880         return new ZExtInst(NotCond, SI.getType());
00881       }
00882 
00883       // select C, 0, -1 -> sext !C to int
00884       if (TrueValC->isZero() && FalseValC->isAllOnesValue()) {
00885         Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName());
00886         return new SExtInst(NotCond, SI.getType());
00887       }
00888 
00889       if (Value *V = foldSelectICmpAnd(SI, TrueValC, FalseValC, Builder))
00890         return ReplaceInstUsesWith(SI, V);
00891     }
00892 
00893   // See if we are selecting two values based on a comparison of the two values.
00894   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
00895     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
00896       // Transform (X == Y) ? X : Y  -> Y
00897       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
00898         // This is not safe in general for floating point:
00899         // consider X== -0, Y== +0.
00900         // It becomes safe if either operand is a nonzero constant.
00901         ConstantFP *CFPt, *CFPf;
00902         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
00903               !CFPt->getValueAPF().isZero()) ||
00904             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
00905              !CFPf->getValueAPF().isZero()))
00906         return ReplaceInstUsesWith(SI, FalseVal);
00907       }
00908       // Transform (X une Y) ? X : Y  -> X
00909       if (FCI->getPredicate() == FCmpInst::FCMP_UNE) {
00910         // This is not safe in general for floating point:
00911         // consider X== -0, Y== +0.
00912         // It becomes safe if either operand is a nonzero constant.
00913         ConstantFP *CFPt, *CFPf;
00914         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
00915               !CFPt->getValueAPF().isZero()) ||
00916             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
00917              !CFPf->getValueAPF().isZero()))
00918         return ReplaceInstUsesWith(SI, TrueVal);
00919       }
00920       // NOTE: if we wanted to, this is where to detect MIN/MAX
00921 
00922     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
00923       // Transform (X == Y) ? Y : X  -> X
00924       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
00925         // This is not safe in general for floating point:
00926         // consider X== -0, Y== +0.
00927         // It becomes safe if either operand is a nonzero constant.
00928         ConstantFP *CFPt, *CFPf;
00929         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
00930               !CFPt->getValueAPF().isZero()) ||
00931             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
00932              !CFPf->getValueAPF().isZero()))
00933           return ReplaceInstUsesWith(SI, FalseVal);
00934       }
00935       // Transform (X une Y) ? Y : X  -> Y
00936       if (FCI->getPredicate() == FCmpInst::FCMP_UNE) {
00937         // This is not safe in general for floating point:
00938         // consider X== -0, Y== +0.
00939         // It becomes safe if either operand is a nonzero constant.
00940         ConstantFP *CFPt, *CFPf;
00941         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
00942               !CFPt->getValueAPF().isZero()) ||
00943             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
00944              !CFPf->getValueAPF().isZero()))
00945           return ReplaceInstUsesWith(SI, TrueVal);
00946       }
00947       // NOTE: if we wanted to, this is where to detect MIN/MAX
00948     }
00949     // NOTE: if we wanted to, this is where to detect ABS
00950   }
00951 
00952   // See if we are selecting two values based on a comparison of the two values.
00953   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
00954     if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
00955       return Result;
00956 
00957   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
00958     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
00959       if (TI->hasOneUse() && FI->hasOneUse()) {
00960         Instruction *AddOp = nullptr, *SubOp = nullptr;
00961 
00962         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
00963         if (TI->getOpcode() == FI->getOpcode())
00964           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
00965             return IV;
00966 
00967         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
00968         // even legal for FP.
00969         if ((TI->getOpcode() == Instruction::Sub &&
00970              FI->getOpcode() == Instruction::Add) ||
00971             (TI->getOpcode() == Instruction::FSub &&
00972              FI->getOpcode() == Instruction::FAdd)) {
00973           AddOp = FI; SubOp = TI;
00974         } else if ((FI->getOpcode() == Instruction::Sub &&
00975                     TI->getOpcode() == Instruction::Add) ||
00976                    (FI->getOpcode() == Instruction::FSub &&
00977                     TI->getOpcode() == Instruction::FAdd)) {
00978           AddOp = TI; SubOp = FI;
00979         }
00980 
00981         if (AddOp) {
00982           Value *OtherAddOp = nullptr;
00983           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
00984             OtherAddOp = AddOp->getOperand(1);
00985           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
00986             OtherAddOp = AddOp->getOperand(0);
00987           }
00988 
00989           if (OtherAddOp) {
00990             // So at this point we know we have (Y -> OtherAddOp):
00991             //        select C, (add X, Y), (sub X, Z)
00992             Value *NegVal;  // Compute -Z
00993             if (SI.getType()->isFPOrFPVectorTy()) {
00994               NegVal = Builder->CreateFNeg(SubOp->getOperand(1));
00995               if (Instruction *NegInst = dyn_cast<Instruction>(NegVal)) {
00996                 FastMathFlags Flags = AddOp->getFastMathFlags();
00997                 Flags &= SubOp->getFastMathFlags();
00998                 NegInst->setFastMathFlags(Flags);
00999               }
01000             } else {
01001               NegVal = Builder->CreateNeg(SubOp->getOperand(1));
01002             }
01003 
01004             Value *NewTrueOp = OtherAddOp;
01005             Value *NewFalseOp = NegVal;
01006             if (AddOp != TI)
01007               std::swap(NewTrueOp, NewFalseOp);
01008             Value *NewSel =
01009               Builder->CreateSelect(CondVal, NewTrueOp,
01010                                     NewFalseOp, SI.getName() + ".p");
01011 
01012             if (SI.getType()->isFPOrFPVectorTy()) {
01013               Instruction *RI =
01014                 BinaryOperator::CreateFAdd(SubOp->getOperand(0), NewSel);
01015 
01016               FastMathFlags Flags = AddOp->getFastMathFlags();
01017               Flags &= SubOp->getFastMathFlags();
01018               RI->setFastMathFlags(Flags);
01019               return RI;
01020             } else
01021               return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
01022           }
01023         }
01024       }
01025 
01026   // See if we can fold the select into one of our operands.
01027   if (SI.getType()->isIntegerTy()) {
01028     if (Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal))
01029       return FoldI;
01030 
01031     // MAX(MAX(a, b), a) -> MAX(a, b)
01032     // MIN(MIN(a, b), a) -> MIN(a, b)
01033     // MAX(MIN(a, b), a) -> a
01034     // MIN(MAX(a, b), a) -> a
01035     Value *LHS, *RHS, *LHS2, *RHS2;
01036     if (SelectPatternFlavor SPF = MatchSelectPattern(&SI, LHS, RHS)) {
01037       if (SelectPatternFlavor SPF2 = MatchSelectPattern(LHS, LHS2, RHS2))
01038         if (Instruction *R = FoldSPFofSPF(cast<Instruction>(LHS),SPF2,LHS2,RHS2,
01039                                           SI, SPF, RHS))
01040           return R;
01041       if (SelectPatternFlavor SPF2 = MatchSelectPattern(RHS, LHS2, RHS2))
01042         if (Instruction *R = FoldSPFofSPF(cast<Instruction>(RHS),SPF2,LHS2,RHS2,
01043                                           SI, SPF, LHS))
01044           return R;
01045     }
01046 
01047     // TODO.
01048     // ABS(-X) -> ABS(X)
01049   }
01050 
01051   // See if we can fold the select into a phi node if the condition is a select.
01052   if (isa<PHINode>(SI.getCondition()))
01053     // The true/false values have to be live in the PHI predecessor's blocks.
01054     if (CanSelectOperandBeMappingIntoPredBlock(TrueVal, SI) &&
01055         CanSelectOperandBeMappingIntoPredBlock(FalseVal, SI))
01056       if (Instruction *NV = FoldOpIntoPhi(SI))
01057         return NV;
01058 
01059   if (SelectInst *TrueSI = dyn_cast<SelectInst>(TrueVal)) {
01060     if (TrueSI->getCondition() == CondVal) {
01061       if (SI.getTrueValue() == TrueSI->getTrueValue())
01062         return nullptr;
01063       SI.setOperand(1, TrueSI->getTrueValue());
01064       return &SI;
01065     }
01066   }
01067   if (SelectInst *FalseSI = dyn_cast<SelectInst>(FalseVal)) {
01068     if (FalseSI->getCondition() == CondVal) {
01069       if (SI.getFalseValue() == FalseSI->getFalseValue())
01070         return nullptr;
01071       SI.setOperand(2, FalseSI->getFalseValue());
01072       return &SI;
01073     }
01074   }
01075 
01076   if (BinaryOperator::isNot(CondVal)) {
01077     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
01078     SI.setOperand(1, FalseVal);
01079     SI.setOperand(2, TrueVal);
01080     return &SI;
01081   }
01082 
01083   if (VectorType* VecTy = dyn_cast<VectorType>(SI.getType())) {
01084     unsigned VWidth = VecTy->getNumElements();
01085     APInt UndefElts(VWidth, 0);
01086     APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
01087     if (Value *V = SimplifyDemandedVectorElts(&SI, AllOnesEltMask, UndefElts)) {
01088       if (V != &SI)
01089         return ReplaceInstUsesWith(SI, V);
01090       return &SI;
01091     }
01092 
01093     if (isa<ConstantAggregateZero>(CondVal)) {
01094       return ReplaceInstUsesWith(SI, FalseVal);
01095     }
01096   }
01097 
01098   return nullptr;
01099 }