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