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