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