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