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 "InstCombine.h" 15 #include "llvm/Analysis/ConstantFolding.h" 16 #include "llvm/Analysis/InstructionSimplify.h" 17 #include "llvm/IR/PatternMatch.h" 18 using namespace llvm; 19 using namespace PatternMatch; 20 21 #define DEBUG_TYPE "instcombine" 22 23 /// MatchSelectPattern - Pattern match integer [SU]MIN, [SU]MAX, and ABS idioms, 24 /// returning the kind and providing the out parameter results if we 25 /// successfully match. 26 static SelectPatternFlavor 27 MatchSelectPattern(Value *V, Value *&LHS, Value *&RHS) { 28 SelectInst *SI = dyn_cast<SelectInst>(V); 29 if (SI == 0) return SPF_UNKNOWN; 30 31 ICmpInst *ICI = dyn_cast<ICmpInst>(SI->getCondition()); 32 if (ICI == 0) return SPF_UNKNOWN; 33 34 LHS = ICI->getOperand(0); 35 RHS = ICI->getOperand(1); 36 37 // (icmp X, Y) ? X : Y 38 if (SI->getTrueValue() == ICI->getOperand(0) && 39 SI->getFalseValue() == ICI->getOperand(1)) { 40 switch (ICI->getPredicate()) { 41 default: return SPF_UNKNOWN; // Equality. 42 case ICmpInst::ICMP_UGT: 43 case ICmpInst::ICMP_UGE: return SPF_UMAX; 44 case ICmpInst::ICMP_SGT: 45 case ICmpInst::ICMP_SGE: return SPF_SMAX; 46 case ICmpInst::ICMP_ULT: 47 case ICmpInst::ICMP_ULE: return SPF_UMIN; 48 case ICmpInst::ICMP_SLT: 49 case ICmpInst::ICMP_SLE: return SPF_SMIN; 50 } 51 } 52 53 // (icmp X, Y) ? Y : X 54 if (SI->getTrueValue() == ICI->getOperand(1) && 55 SI->getFalseValue() == ICI->getOperand(0)) { 56 switch (ICI->getPredicate()) { 57 default: return SPF_UNKNOWN; // Equality. 58 case ICmpInst::ICMP_UGT: 59 case ICmpInst::ICMP_UGE: return SPF_UMIN; 60 case ICmpInst::ICMP_SGT: 61 case ICmpInst::ICMP_SGE: return SPF_SMIN; 62 case ICmpInst::ICMP_ULT: 63 case ICmpInst::ICMP_ULE: return SPF_UMAX; 64 case ICmpInst::ICMP_SLT: 65 case ICmpInst::ICMP_SLE: return SPF_SMAX; 66 } 67 } 68 69 // TODO: (X > 4) ? X : 5 --> (X >= 5) ? X : 5 --> MAX(X, 5) 70 71 return SPF_UNKNOWN; 72 } 73 74 75 /// GetSelectFoldableOperands - We want to turn code that looks like this: 76 /// %C = or %A, %B 77 /// %D = select %cond, %C, %A 78 /// into: 79 /// %C = select %cond, %B, 0 80 /// %D = or %A, %C 81 /// 82 /// Assuming that the specified instruction is an operand to the select, return 83 /// a bitmask indicating which operands of this instruction are foldable if they 84 /// equal the other incoming value of the select. 85 /// 86 static unsigned GetSelectFoldableOperands(Instruction *I) { 87 switch (I->getOpcode()) { 88 case Instruction::Add: 89 case Instruction::Mul: 90 case Instruction::And: 91 case Instruction::Or: 92 case Instruction::Xor: 93 return 3; // Can fold through either operand. 94 case Instruction::Sub: // Can only fold on the amount subtracted. 95 case Instruction::Shl: // Can only fold on the shift amount. 96 case Instruction::LShr: 97 case Instruction::AShr: 98 return 1; 99 default: 100 return 0; // Cannot fold 101 } 102 } 103 104 /// GetSelectFoldableConstant - For the same transformation as the previous 105 /// function, return the identity constant that goes into the select. 106 static Constant *GetSelectFoldableConstant(Instruction *I) { 107 switch (I->getOpcode()) { 108 default: llvm_unreachable("This cannot happen!"); 109 case Instruction::Add: 110 case Instruction::Sub: 111 case Instruction::Or: 112 case Instruction::Xor: 113 case Instruction::Shl: 114 case Instruction::LShr: 115 case Instruction::AShr: 116 return Constant::getNullValue(I->getType()); 117 case Instruction::And: 118 return Constant::getAllOnesValue(I->getType()); 119 case Instruction::Mul: 120 return ConstantInt::get(I->getType(), 1); 121 } 122 } 123 124 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI 125 /// have the same opcode and only one use each. Try to simplify this. 126 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI, 127 Instruction *FI) { 128 if (TI->getNumOperands() == 1) { 129 // If this is a non-volatile load or a cast from the same type, 130 // merge. 131 if (TI->isCast()) { 132 Type *FIOpndTy = FI->getOperand(0)->getType(); 133 if (TI->getOperand(0)->getType() != FIOpndTy) 134 return 0; 135 // The select condition may be a vector. We may only change the operand 136 // type if the vector width remains the same (and matches the condition). 137 Type *CondTy = SI.getCondition()->getType(); 138 if (CondTy->isVectorTy() && (!FIOpndTy->isVectorTy() || 139 CondTy->getVectorNumElements() != FIOpndTy->getVectorNumElements())) 140 return 0; 141 } else { 142 return 0; // unknown unary op. 143 } 144 145 // Fold this by inserting a select from the input values. 146 Value *NewSI = Builder->CreateSelect(SI.getCondition(), TI->getOperand(0), 147 FI->getOperand(0), SI.getName()+".v"); 148 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI, 149 TI->getType()); 150 } 151 152 // Only handle binary operators here. 153 if (!isa<BinaryOperator>(TI)) 154 return 0; 155 156 // Figure out if the operations have any operands in common. 157 Value *MatchOp, *OtherOpT, *OtherOpF; 158 bool MatchIsOpZero; 159 if (TI->getOperand(0) == FI->getOperand(0)) { 160 MatchOp = TI->getOperand(0); 161 OtherOpT = TI->getOperand(1); 162 OtherOpF = FI->getOperand(1); 163 MatchIsOpZero = true; 164 } else if (TI->getOperand(1) == FI->getOperand(1)) { 165 MatchOp = TI->getOperand(1); 166 OtherOpT = TI->getOperand(0); 167 OtherOpF = FI->getOperand(0); 168 MatchIsOpZero = false; 169 } else if (!TI->isCommutative()) { 170 return 0; 171 } else if (TI->getOperand(0) == FI->getOperand(1)) { 172 MatchOp = TI->getOperand(0); 173 OtherOpT = TI->getOperand(1); 174 OtherOpF = FI->getOperand(0); 175 MatchIsOpZero = true; 176 } else if (TI->getOperand(1) == FI->getOperand(0)) { 177 MatchOp = TI->getOperand(1); 178 OtherOpT = TI->getOperand(0); 179 OtherOpF = FI->getOperand(1); 180 MatchIsOpZero = true; 181 } else { 182 return 0; 183 } 184 185 // If we reach here, they do have operations in common. 186 Value *NewSI = Builder->CreateSelect(SI.getCondition(), OtherOpT, 187 OtherOpF, SI.getName()+".v"); 188 189 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) { 190 if (MatchIsOpZero) 191 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI); 192 else 193 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp); 194 } 195 llvm_unreachable("Shouldn't get here"); 196 } 197 198 static bool isSelect01(Constant *C1, Constant *C2) { 199 ConstantInt *C1I = dyn_cast<ConstantInt>(C1); 200 if (!C1I) 201 return false; 202 ConstantInt *C2I = dyn_cast<ConstantInt>(C2); 203 if (!C2I) 204 return false; 205 if (!C1I->isZero() && !C2I->isZero()) // One side must be zero. 206 return false; 207 return C1I->isOne() || C1I->isAllOnesValue() || 208 C2I->isOne() || C2I->isAllOnesValue(); 209 } 210 211 /// FoldSelectIntoOp - Try fold the select into one of the operands to 212 /// facilitate further optimization. 213 Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal, 214 Value *FalseVal) { 215 // See the comment above GetSelectFoldableOperands for a description of the 216 // transformation we are doing here. 217 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) { 218 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 && 219 !isa<Constant>(FalseVal)) { 220 if (unsigned SFO = GetSelectFoldableOperands(TVI)) { 221 unsigned OpToFold = 0; 222 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) { 223 OpToFold = 1; 224 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) { 225 OpToFold = 2; 226 } 227 228 if (OpToFold) { 229 Constant *C = GetSelectFoldableConstant(TVI); 230 Value *OOp = TVI->getOperand(2-OpToFold); 231 // Avoid creating select between 2 constants unless it's selecting 232 // between 0, 1 and -1. 233 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) { 234 Value *NewSel = Builder->CreateSelect(SI.getCondition(), OOp, C); 235 NewSel->takeName(TVI); 236 BinaryOperator *TVI_BO = cast<BinaryOperator>(TVI); 237 BinaryOperator *BO = BinaryOperator::Create(TVI_BO->getOpcode(), 238 FalseVal, NewSel); 239 if (isa<PossiblyExactOperator>(BO)) 240 BO->setIsExact(TVI_BO->isExact()); 241 if (isa<OverflowingBinaryOperator>(BO)) { 242 BO->setHasNoUnsignedWrap(TVI_BO->hasNoUnsignedWrap()); 243 BO->setHasNoSignedWrap(TVI_BO->hasNoSignedWrap()); 244 } 245 return BO; 246 } 247 } 248 } 249 } 250 } 251 252 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) { 253 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 && 254 !isa<Constant>(TrueVal)) { 255 if (unsigned SFO = GetSelectFoldableOperands(FVI)) { 256 unsigned OpToFold = 0; 257 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) { 258 OpToFold = 1; 259 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) { 260 OpToFold = 2; 261 } 262 263 if (OpToFold) { 264 Constant *C = GetSelectFoldableConstant(FVI); 265 Value *OOp = FVI->getOperand(2-OpToFold); 266 // Avoid creating select between 2 constants unless it's selecting 267 // between 0, 1 and -1. 268 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) { 269 Value *NewSel = Builder->CreateSelect(SI.getCondition(), C, OOp); 270 NewSel->takeName(FVI); 271 BinaryOperator *FVI_BO = cast<BinaryOperator>(FVI); 272 BinaryOperator *BO = BinaryOperator::Create(FVI_BO->getOpcode(), 273 TrueVal, NewSel); 274 if (isa<PossiblyExactOperator>(BO)) 275 BO->setIsExact(FVI_BO->isExact()); 276 if (isa<OverflowingBinaryOperator>(BO)) { 277 BO->setHasNoUnsignedWrap(FVI_BO->hasNoUnsignedWrap()); 278 BO->setHasNoSignedWrap(FVI_BO->hasNoSignedWrap()); 279 } 280 return BO; 281 } 282 } 283 } 284 } 285 } 286 287 return 0; 288 } 289 290 /// SimplifyWithOpReplaced - See if V simplifies when its operand Op is 291 /// replaced with RepOp. 292 static Value *SimplifyWithOpReplaced(Value *V, Value *Op, Value *RepOp, 293 const DataLayout *TD, 294 const TargetLibraryInfo *TLI) { 295 // Trivial replacement. 296 if (V == Op) 297 return RepOp; 298 299 Instruction *I = dyn_cast<Instruction>(V); 300 if (!I) 301 return 0; 302 303 // If this is a binary operator, try to simplify it with the replaced op. 304 if (BinaryOperator *B = dyn_cast<BinaryOperator>(I)) { 305 if (B->getOperand(0) == Op) 306 return SimplifyBinOp(B->getOpcode(), RepOp, B->getOperand(1), TD, TLI); 307 if (B->getOperand(1) == Op) 308 return SimplifyBinOp(B->getOpcode(), B->getOperand(0), RepOp, TD, TLI); 309 } 310 311 // Same for CmpInsts. 312 if (CmpInst *C = dyn_cast<CmpInst>(I)) { 313 if (C->getOperand(0) == Op) 314 return SimplifyCmpInst(C->getPredicate(), RepOp, C->getOperand(1), TD, 315 TLI); 316 if (C->getOperand(1) == Op) 317 return SimplifyCmpInst(C->getPredicate(), C->getOperand(0), RepOp, TD, 318 TLI); 319 } 320 321 // TODO: We could hand off more cases to instsimplify here. 322 323 // If all operands are constant after substituting Op for RepOp then we can 324 // constant fold the instruction. 325 if (Constant *CRepOp = dyn_cast<Constant>(RepOp)) { 326 // Build a list of all constant operands. 327 SmallVector<Constant*, 8> ConstOps; 328 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { 329 if (I->getOperand(i) == Op) 330 ConstOps.push_back(CRepOp); 331 else if (Constant *COp = dyn_cast<Constant>(I->getOperand(i))) 332 ConstOps.push_back(COp); 333 else 334 break; 335 } 336 337 // All operands were constants, fold it. 338 if (ConstOps.size() == I->getNumOperands()) { 339 if (CmpInst *C = dyn_cast<CmpInst>(I)) 340 return ConstantFoldCompareInstOperands(C->getPredicate(), ConstOps[0], 341 ConstOps[1], TD, TLI); 342 343 if (LoadInst *LI = dyn_cast<LoadInst>(I)) 344 if (!LI->isVolatile()) 345 return ConstantFoldLoadFromConstPtr(ConstOps[0], TD); 346 347 return ConstantFoldInstOperands(I->getOpcode(), I->getType(), 348 ConstOps, TD, TLI); 349 } 350 } 351 352 return 0; 353 } 354 355 /// foldSelectICmpAndOr - We want to turn: 356 /// (select (icmp eq (and X, C1), 0), Y, (or Y, C2)) 357 /// into: 358 /// (or (shl (and X, C1), C3), y) 359 /// iff: 360 /// C1 and C2 are both powers of 2 361 /// where: 362 /// C3 = Log(C2) - Log(C1) 363 /// 364 /// This transform handles cases where: 365 /// 1. The icmp predicate is inverted 366 /// 2. The select operands are reversed 367 /// 3. The magnitude of C2 and C1 are flipped 368 static Value *foldSelectICmpAndOr(const SelectInst &SI, Value *TrueVal, 369 Value *FalseVal, 370 InstCombiner::BuilderTy *Builder) { 371 const ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition()); 372 if (!IC || !IC->isEquality() || !SI.getType()->isIntegerTy()) 373 return 0; 374 375 Value *CmpLHS = IC->getOperand(0); 376 Value *CmpRHS = IC->getOperand(1); 377 378 if (!match(CmpRHS, m_Zero())) 379 return 0; 380 381 Value *X; 382 const APInt *C1; 383 if (!match(CmpLHS, m_And(m_Value(X), m_Power2(C1)))) 384 return 0; 385 386 const APInt *C2; 387 bool OrOnTrueVal = false; 388 bool OrOnFalseVal = match(FalseVal, m_Or(m_Specific(TrueVal), m_Power2(C2))); 389 if (!OrOnFalseVal) 390 OrOnTrueVal = match(TrueVal, m_Or(m_Specific(FalseVal), m_Power2(C2))); 391 392 if (!OrOnFalseVal && !OrOnTrueVal) 393 return 0; 394 395 Value *V = CmpLHS; 396 Value *Y = OrOnFalseVal ? TrueVal : FalseVal; 397 398 unsigned C1Log = C1->logBase2(); 399 unsigned C2Log = C2->logBase2(); 400 if (C2Log > C1Log) { 401 V = Builder->CreateZExtOrTrunc(V, Y->getType()); 402 V = Builder->CreateShl(V, C2Log - C1Log); 403 } else if (C1Log > C2Log) { 404 V = Builder->CreateLShr(V, C1Log - C2Log); 405 V = Builder->CreateZExtOrTrunc(V, Y->getType()); 406 } else 407 V = Builder->CreateZExtOrTrunc(V, Y->getType()); 408 409 ICmpInst::Predicate Pred = IC->getPredicate(); 410 if ((Pred == ICmpInst::ICMP_NE && OrOnFalseVal) || 411 (Pred == ICmpInst::ICMP_EQ && OrOnTrueVal)) 412 V = Builder->CreateXor(V, *C2); 413 414 return Builder->CreateOr(V, Y); 415 } 416 417 /// visitSelectInstWithICmp - Visit a SelectInst that has an 418 /// ICmpInst as its first operand. 419 /// 420 Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI, 421 ICmpInst *ICI) { 422 bool Changed = false; 423 ICmpInst::Predicate Pred = ICI->getPredicate(); 424 Value *CmpLHS = ICI->getOperand(0); 425 Value *CmpRHS = ICI->getOperand(1); 426 Value *TrueVal = SI.getTrueValue(); 427 Value *FalseVal = SI.getFalseValue(); 428 429 // Check cases where the comparison is with a constant that 430 // can be adjusted to fit the min/max idiom. We may move or edit ICI 431 // here, so make sure the select is the only user. 432 if (ICI->hasOneUse()) 433 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) { 434 // X < MIN ? T : F --> F 435 if ((Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_ULT) 436 && CI->isMinValue(Pred == ICmpInst::ICMP_SLT)) 437 return ReplaceInstUsesWith(SI, FalseVal); 438 // X > MAX ? T : F --> F 439 else if ((Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_UGT) 440 && CI->isMaxValue(Pred == ICmpInst::ICMP_SGT)) 441 return ReplaceInstUsesWith(SI, FalseVal); 442 switch (Pred) { 443 default: break; 444 case ICmpInst::ICMP_ULT: 445 case ICmpInst::ICMP_SLT: 446 case ICmpInst::ICMP_UGT: 447 case ICmpInst::ICMP_SGT: { 448 // These transformations only work for selects over integers. 449 IntegerType *SelectTy = dyn_cast<IntegerType>(SI.getType()); 450 if (!SelectTy) 451 break; 452 453 Constant *AdjustedRHS; 454 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_SGT) 455 AdjustedRHS = ConstantInt::get(CI->getContext(), CI->getValue() + 1); 456 else // (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT) 457 AdjustedRHS = ConstantInt::get(CI->getContext(), CI->getValue() - 1); 458 459 // X > C ? X : C+1 --> X < C+1 ? C+1 : X 460 // X < C ? X : C-1 --> X > C-1 ? C-1 : X 461 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) || 462 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) 463 ; // Nothing to do here. Values match without any sign/zero extension. 464 465 // Types do not match. Instead of calculating this with mixed types 466 // promote all to the larger type. This enables scalar evolution to 467 // analyze this expression. 468 else if (CmpRHS->getType()->getScalarSizeInBits() 469 < SelectTy->getBitWidth()) { 470 Constant *sextRHS = ConstantExpr::getSExt(AdjustedRHS, SelectTy); 471 472 // X = sext x; x >s c ? X : C+1 --> X = sext x; X <s C+1 ? C+1 : X 473 // X = sext x; x <s c ? X : C-1 --> X = sext x; X >s C-1 ? C-1 : X 474 // X = sext x; x >u c ? X : C+1 --> X = sext x; X <u C+1 ? C+1 : X 475 // X = sext x; x <u c ? X : C-1 --> X = sext x; X >u C-1 ? C-1 : X 476 if (match(TrueVal, m_SExt(m_Specific(CmpLHS))) && 477 sextRHS == FalseVal) { 478 CmpLHS = TrueVal; 479 AdjustedRHS = sextRHS; 480 } else if (match(FalseVal, m_SExt(m_Specific(CmpLHS))) && 481 sextRHS == TrueVal) { 482 CmpLHS = FalseVal; 483 AdjustedRHS = sextRHS; 484 } else if (ICI->isUnsigned()) { 485 Constant *zextRHS = ConstantExpr::getZExt(AdjustedRHS, SelectTy); 486 // X = zext x; x >u c ? X : C+1 --> X = zext x; X <u C+1 ? C+1 : X 487 // X = zext x; x <u c ? X : C-1 --> X = zext x; X >u C-1 ? C-1 : X 488 // zext + signed compare cannot be changed: 489 // 0xff <s 0x00, but 0x00ff >s 0x0000 490 if (match(TrueVal, m_ZExt(m_Specific(CmpLHS))) && 491 zextRHS == FalseVal) { 492 CmpLHS = TrueVal; 493 AdjustedRHS = zextRHS; 494 } else if (match(FalseVal, m_ZExt(m_Specific(CmpLHS))) && 495 zextRHS == TrueVal) { 496 CmpLHS = FalseVal; 497 AdjustedRHS = zextRHS; 498 } else 499 break; 500 } else 501 break; 502 } else 503 break; 504 505 Pred = ICmpInst::getSwappedPredicate(Pred); 506 CmpRHS = AdjustedRHS; 507 std::swap(FalseVal, TrueVal); 508 ICI->setPredicate(Pred); 509 ICI->setOperand(0, CmpLHS); 510 ICI->setOperand(1, CmpRHS); 511 SI.setOperand(1, TrueVal); 512 SI.setOperand(2, FalseVal); 513 514 // Move ICI instruction right before the select instruction. Otherwise 515 // the sext/zext value may be defined after the ICI instruction uses it. 516 ICI->moveBefore(&SI); 517 518 Changed = true; 519 break; 520 } 521 } 522 } 523 524 // Transform (X >s -1) ? C1 : C2 --> ((X >>s 31) & (C2 - C1)) + C1 525 // and (X <s 0) ? C2 : C1 --> ((X >>s 31) & (C2 - C1)) + C1 526 // FIXME: Type and constness constraints could be lifted, but we have to 527 // watch code size carefully. We should consider xor instead of 528 // sub/add when we decide to do that. 529 if (IntegerType *Ty = dyn_cast<IntegerType>(CmpLHS->getType())) { 530 if (TrueVal->getType() == Ty) { 531 if (ConstantInt *Cmp = dyn_cast<ConstantInt>(CmpRHS)) { 532 ConstantInt *C1 = NULL, *C2 = NULL; 533 if (Pred == ICmpInst::ICMP_SGT && Cmp->isAllOnesValue()) { 534 C1 = dyn_cast<ConstantInt>(TrueVal); 535 C2 = dyn_cast<ConstantInt>(FalseVal); 536 } else if (Pred == ICmpInst::ICMP_SLT && Cmp->isNullValue()) { 537 C1 = dyn_cast<ConstantInt>(FalseVal); 538 C2 = dyn_cast<ConstantInt>(TrueVal); 539 } 540 if (C1 && C2) { 541 // This shift results in either -1 or 0. 542 Value *AShr = Builder->CreateAShr(CmpLHS, Ty->getBitWidth()-1); 543 544 // Check if we can express the operation with a single or. 545 if (C2->isAllOnesValue()) 546 return ReplaceInstUsesWith(SI, Builder->CreateOr(AShr, C1)); 547 548 Value *And = Builder->CreateAnd(AShr, C2->getValue()-C1->getValue()); 549 return ReplaceInstUsesWith(SI, Builder->CreateAdd(And, C1)); 550 } 551 } 552 } 553 } 554 555 // If we have an equality comparison then we know the value in one of the 556 // arms of the select. See if substituting this value into the arm and 557 // simplifying the result yields the same value as the other arm. 558 if (Pred == ICmpInst::ICMP_EQ) { 559 if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, DL, TLI) == TrueVal || 560 SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, DL, TLI) == TrueVal) 561 return ReplaceInstUsesWith(SI, FalseVal); 562 if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, DL, TLI) == FalseVal || 563 SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, DL, TLI) == FalseVal) 564 return ReplaceInstUsesWith(SI, FalseVal); 565 } else if (Pred == ICmpInst::ICMP_NE) { 566 if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, DL, TLI) == FalseVal || 567 SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, DL, TLI) == FalseVal) 568 return ReplaceInstUsesWith(SI, TrueVal); 569 if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, DL, TLI) == TrueVal || 570 SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, DL, TLI) == TrueVal) 571 return ReplaceInstUsesWith(SI, TrueVal); 572 } 573 574 // NOTE: if we wanted to, this is where to detect integer MIN/MAX 575 576 if (CmpRHS != CmpLHS && isa<Constant>(CmpRHS)) { 577 if (CmpLHS == TrueVal && Pred == ICmpInst::ICMP_EQ) { 578 // Transform (X == C) ? X : Y -> (X == C) ? C : Y 579 SI.setOperand(1, CmpRHS); 580 Changed = true; 581 } else if (CmpLHS == FalseVal && Pred == ICmpInst::ICMP_NE) { 582 // Transform (X != C) ? Y : X -> (X != C) ? Y : C 583 SI.setOperand(2, CmpRHS); 584 Changed = true; 585 } 586 } 587 588 if (Value *V = foldSelectICmpAndOr(SI, TrueVal, FalseVal, Builder)) 589 return ReplaceInstUsesWith(SI, V); 590 591 return Changed ? &SI : 0; 592 } 593 594 595 /// CanSelectOperandBeMappingIntoPredBlock - SI is a select whose condition is a 596 /// PHI node (but the two may be in different blocks). See if the true/false 597 /// values (V) are live in all of the predecessor blocks of the PHI. For 598 /// example, cases like this cannot be mapped: 599 /// 600 /// X = phi [ C1, BB1], [C2, BB2] 601 /// Y = add 602 /// Z = select X, Y, 0 603 /// 604 /// because Y is not live in BB1/BB2. 605 /// 606 static bool CanSelectOperandBeMappingIntoPredBlock(const Value *V, 607 const SelectInst &SI) { 608 // If the value is a non-instruction value like a constant or argument, it 609 // can always be mapped. 610 const Instruction *I = dyn_cast<Instruction>(V); 611 if (I == 0) return true; 612 613 // If V is a PHI node defined in the same block as the condition PHI, we can 614 // map the arguments. 615 const PHINode *CondPHI = cast<PHINode>(SI.getCondition()); 616 617 if (const PHINode *VP = dyn_cast<PHINode>(I)) 618 if (VP->getParent() == CondPHI->getParent()) 619 return true; 620 621 // Otherwise, if the PHI and select are defined in the same block and if V is 622 // defined in a different block, then we can transform it. 623 if (SI.getParent() == CondPHI->getParent() && 624 I->getParent() != CondPHI->getParent()) 625 return true; 626 627 // Otherwise we have a 'hard' case and we can't tell without doing more 628 // detailed dominator based analysis, punt. 629 return false; 630 } 631 632 /// FoldSPFofSPF - We have an SPF (e.g. a min or max) of an SPF of the form: 633 /// SPF2(SPF1(A, B), C) 634 Instruction *InstCombiner::FoldSPFofSPF(Instruction *Inner, 635 SelectPatternFlavor SPF1, 636 Value *A, Value *B, 637 Instruction &Outer, 638 SelectPatternFlavor SPF2, Value *C) { 639 if (C == A || C == B) { 640 // MAX(MAX(A, B), B) -> MAX(A, B) 641 // MIN(MIN(a, b), a) -> MIN(a, b) 642 if (SPF1 == SPF2) 643 return ReplaceInstUsesWith(Outer, Inner); 644 645 // MAX(MIN(a, b), a) -> a 646 // MIN(MAX(a, b), a) -> a 647 if ((SPF1 == SPF_SMIN && SPF2 == SPF_SMAX) || 648 (SPF1 == SPF_SMAX && SPF2 == SPF_SMIN) || 649 (SPF1 == SPF_UMIN && SPF2 == SPF_UMAX) || 650 (SPF1 == SPF_UMAX && SPF2 == SPF_UMIN)) 651 return ReplaceInstUsesWith(Outer, C); 652 } 653 654 // TODO: MIN(MIN(A, 23), 97) 655 return 0; 656 } 657 658 659 /// foldSelectICmpAnd - If one of the constants is zero (we know they can't 660 /// both be) and we have an icmp instruction with zero, and we have an 'and' 661 /// with the non-constant value and a power of two we can turn the select 662 /// into a shift on the result of the 'and'. 663 static Value *foldSelectICmpAnd(const SelectInst &SI, ConstantInt *TrueVal, 664 ConstantInt *FalseVal, 665 InstCombiner::BuilderTy *Builder) { 666 const ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition()); 667 if (!IC || !IC->isEquality() || !SI.getType()->isIntegerTy()) 668 return 0; 669 670 if (!match(IC->getOperand(1), m_Zero())) 671 return 0; 672 673 ConstantInt *AndRHS; 674 Value *LHS = IC->getOperand(0); 675 if (!match(LHS, m_And(m_Value(), m_ConstantInt(AndRHS)))) 676 return 0; 677 678 // If both select arms are non-zero see if we have a select of the form 679 // 'x ? 2^n + C : C'. Then we can offset both arms by C, use the logic 680 // for 'x ? 2^n : 0' and fix the thing up at the end. 681 ConstantInt *Offset = 0; 682 if (!TrueVal->isZero() && !FalseVal->isZero()) { 683 if ((TrueVal->getValue() - FalseVal->getValue()).isPowerOf2()) 684 Offset = FalseVal; 685 else if ((FalseVal->getValue() - TrueVal->getValue()).isPowerOf2()) 686 Offset = TrueVal; 687 else 688 return 0; 689 690 // Adjust TrueVal and FalseVal to the offset. 691 TrueVal = ConstantInt::get(Builder->getContext(), 692 TrueVal->getValue() - Offset->getValue()); 693 FalseVal = ConstantInt::get(Builder->getContext(), 694 FalseVal->getValue() - Offset->getValue()); 695 } 696 697 // Make sure the mask in the 'and' and one of the select arms is a power of 2. 698 if (!AndRHS->getValue().isPowerOf2() || 699 (!TrueVal->getValue().isPowerOf2() && 700 !FalseVal->getValue().isPowerOf2())) 701 return 0; 702 703 // Determine which shift is needed to transform result of the 'and' into the 704 // desired result. 705 ConstantInt *ValC = !TrueVal->isZero() ? TrueVal : FalseVal; 706 unsigned ValZeros = ValC->getValue().logBase2(); 707 unsigned AndZeros = AndRHS->getValue().logBase2(); 708 709 // If types don't match we can still convert the select by introducing a zext 710 // or a trunc of the 'and'. The trunc case requires that all of the truncated 711 // bits are zero, we can figure that out by looking at the 'and' mask. 712 if (AndZeros >= ValC->getBitWidth()) 713 return 0; 714 715 Value *V = Builder->CreateZExtOrTrunc(LHS, SI.getType()); 716 if (ValZeros > AndZeros) 717 V = Builder->CreateShl(V, ValZeros - AndZeros); 718 else if (ValZeros < AndZeros) 719 V = Builder->CreateLShr(V, AndZeros - ValZeros); 720 721 // Okay, now we know that everything is set up, we just don't know whether we 722 // have a icmp_ne or icmp_eq and whether the true or false val is the zero. 723 bool ShouldNotVal = !TrueVal->isZero(); 724 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE; 725 if (ShouldNotVal) 726 V = Builder->CreateXor(V, ValC); 727 728 // Apply an offset if needed. 729 if (Offset) 730 V = Builder->CreateAdd(V, Offset); 731 return V; 732 } 733 734 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) { 735 Value *CondVal = SI.getCondition(); 736 Value *TrueVal = SI.getTrueValue(); 737 Value *FalseVal = SI.getFalseValue(); 738 739 if (Value *V = SimplifySelectInst(CondVal, TrueVal, FalseVal, DL)) 740 return ReplaceInstUsesWith(SI, V); 741 742 if (SI.getType()->isIntegerTy(1)) { 743 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) { 744 if (C->getZExtValue()) { 745 // Change: A = select B, true, C --> A = or B, C 746 return BinaryOperator::CreateOr(CondVal, FalseVal); 747 } 748 // Change: A = select B, false, C --> A = and !B, C 749 Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName()); 750 return BinaryOperator::CreateAnd(NotCond, FalseVal); 751 } 752 if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) { 753 if (C->getZExtValue() == false) { 754 // Change: A = select B, C, false --> A = and B, C 755 return BinaryOperator::CreateAnd(CondVal, TrueVal); 756 } 757 // Change: A = select B, C, true --> A = or !B, C 758 Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName()); 759 return BinaryOperator::CreateOr(NotCond, TrueVal); 760 } 761 762 // select a, b, a -> a&b 763 // select a, a, b -> a|b 764 if (CondVal == TrueVal) 765 return BinaryOperator::CreateOr(CondVal, FalseVal); 766 if (CondVal == FalseVal) 767 return BinaryOperator::CreateAnd(CondVal, TrueVal); 768 769 // select a, ~a, b -> (~a)&b 770 // select a, b, ~a -> (~a)|b 771 if (match(TrueVal, m_Not(m_Specific(CondVal)))) 772 return BinaryOperator::CreateAnd(TrueVal, FalseVal); 773 if (match(FalseVal, m_Not(m_Specific(CondVal)))) 774 return BinaryOperator::CreateOr(TrueVal, FalseVal); 775 } 776 777 // Selecting between two integer constants? 778 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal)) 779 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) { 780 // select C, 1, 0 -> zext C to int 781 if (FalseValC->isZero() && TrueValC->getValue() == 1) 782 return new ZExtInst(CondVal, SI.getType()); 783 784 // select C, -1, 0 -> sext C to int 785 if (FalseValC->isZero() && TrueValC->isAllOnesValue()) 786 return new SExtInst(CondVal, SI.getType()); 787 788 // select C, 0, 1 -> zext !C to int 789 if (TrueValC->isZero() && FalseValC->getValue() == 1) { 790 Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName()); 791 return new ZExtInst(NotCond, SI.getType()); 792 } 793 794 // select C, 0, -1 -> sext !C to int 795 if (TrueValC->isZero() && FalseValC->isAllOnesValue()) { 796 Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName()); 797 return new SExtInst(NotCond, SI.getType()); 798 } 799 800 if (Value *V = foldSelectICmpAnd(SI, TrueValC, FalseValC, Builder)) 801 return ReplaceInstUsesWith(SI, V); 802 } 803 804 // See if we are selecting two values based on a comparison of the two values. 805 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) { 806 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) { 807 // Transform (X == Y) ? X : Y -> Y 808 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) { 809 // This is not safe in general for floating point: 810 // consider X== -0, Y== +0. 811 // It becomes safe if either operand is a nonzero constant. 812 ConstantFP *CFPt, *CFPf; 813 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) && 814 !CFPt->getValueAPF().isZero()) || 815 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) && 816 !CFPf->getValueAPF().isZero())) 817 return ReplaceInstUsesWith(SI, FalseVal); 818 } 819 // Transform (X une Y) ? X : Y -> X 820 if (FCI->getPredicate() == FCmpInst::FCMP_UNE) { 821 // This is not safe in general for floating point: 822 // consider X== -0, Y== +0. 823 // It becomes safe if either operand is a nonzero constant. 824 ConstantFP *CFPt, *CFPf; 825 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) && 826 !CFPt->getValueAPF().isZero()) || 827 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) && 828 !CFPf->getValueAPF().isZero())) 829 return ReplaceInstUsesWith(SI, TrueVal); 830 } 831 // NOTE: if we wanted to, this is where to detect MIN/MAX 832 833 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){ 834 // Transform (X == Y) ? Y : X -> X 835 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) { 836 // This is not safe in general for floating point: 837 // consider X== -0, Y== +0. 838 // It becomes safe if either operand is a nonzero constant. 839 ConstantFP *CFPt, *CFPf; 840 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) && 841 !CFPt->getValueAPF().isZero()) || 842 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) && 843 !CFPf->getValueAPF().isZero())) 844 return ReplaceInstUsesWith(SI, FalseVal); 845 } 846 // Transform (X une Y) ? Y : X -> Y 847 if (FCI->getPredicate() == FCmpInst::FCMP_UNE) { 848 // This is not safe in general for floating point: 849 // consider X== -0, Y== +0. 850 // It becomes safe if either operand is a nonzero constant. 851 ConstantFP *CFPt, *CFPf; 852 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) && 853 !CFPt->getValueAPF().isZero()) || 854 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) && 855 !CFPf->getValueAPF().isZero())) 856 return ReplaceInstUsesWith(SI, TrueVal); 857 } 858 // NOTE: if we wanted to, this is where to detect MIN/MAX 859 } 860 // NOTE: if we wanted to, this is where to detect ABS 861 } 862 863 // See if we are selecting two values based on a comparison of the two values. 864 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) 865 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI)) 866 return Result; 867 868 if (Instruction *TI = dyn_cast<Instruction>(TrueVal)) 869 if (Instruction *FI = dyn_cast<Instruction>(FalseVal)) 870 if (TI->hasOneUse() && FI->hasOneUse()) { 871 Instruction *AddOp = 0, *SubOp = 0; 872 873 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z)) 874 if (TI->getOpcode() == FI->getOpcode()) 875 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI)) 876 return IV; 877 878 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is 879 // even legal for FP. 880 if ((TI->getOpcode() == Instruction::Sub && 881 FI->getOpcode() == Instruction::Add) || 882 (TI->getOpcode() == Instruction::FSub && 883 FI->getOpcode() == Instruction::FAdd)) { 884 AddOp = FI; SubOp = TI; 885 } else if ((FI->getOpcode() == Instruction::Sub && 886 TI->getOpcode() == Instruction::Add) || 887 (FI->getOpcode() == Instruction::FSub && 888 TI->getOpcode() == Instruction::FAdd)) { 889 AddOp = TI; SubOp = FI; 890 } 891 892 if (AddOp) { 893 Value *OtherAddOp = 0; 894 if (SubOp->getOperand(0) == AddOp->getOperand(0)) { 895 OtherAddOp = AddOp->getOperand(1); 896 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) { 897 OtherAddOp = AddOp->getOperand(0); 898 } 899 900 if (OtherAddOp) { 901 // So at this point we know we have (Y -> OtherAddOp): 902 // select C, (add X, Y), (sub X, Z) 903 Value *NegVal; // Compute -Z 904 if (SI.getType()->isFPOrFPVectorTy()) { 905 NegVal = Builder->CreateFNeg(SubOp->getOperand(1)); 906 if (Instruction *NegInst = dyn_cast<Instruction>(NegVal)) { 907 FastMathFlags Flags = AddOp->getFastMathFlags(); 908 Flags &= SubOp->getFastMathFlags(); 909 NegInst->setFastMathFlags(Flags); 910 } 911 } else { 912 NegVal = Builder->CreateNeg(SubOp->getOperand(1)); 913 } 914 915 Value *NewTrueOp = OtherAddOp; 916 Value *NewFalseOp = NegVal; 917 if (AddOp != TI) 918 std::swap(NewTrueOp, NewFalseOp); 919 Value *NewSel = 920 Builder->CreateSelect(CondVal, NewTrueOp, 921 NewFalseOp, SI.getName() + ".p"); 922 923 if (SI.getType()->isFPOrFPVectorTy()) { 924 Instruction *RI = 925 BinaryOperator::CreateFAdd(SubOp->getOperand(0), NewSel); 926 927 FastMathFlags Flags = AddOp->getFastMathFlags(); 928 Flags &= SubOp->getFastMathFlags(); 929 RI->setFastMathFlags(Flags); 930 return RI; 931 } else 932 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel); 933 } 934 } 935 } 936 937 // See if we can fold the select into one of our operands. 938 if (SI.getType()->isIntegerTy()) { 939 if (Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal)) 940 return FoldI; 941 942 // MAX(MAX(a, b), a) -> MAX(a, b) 943 // MIN(MIN(a, b), a) -> MIN(a, b) 944 // MAX(MIN(a, b), a) -> a 945 // MIN(MAX(a, b), a) -> a 946 Value *LHS, *RHS, *LHS2, *RHS2; 947 if (SelectPatternFlavor SPF = MatchSelectPattern(&SI, LHS, RHS)) { 948 if (SelectPatternFlavor SPF2 = MatchSelectPattern(LHS, LHS2, RHS2)) 949 if (Instruction *R = FoldSPFofSPF(cast<Instruction>(LHS),SPF2,LHS2,RHS2, 950 SI, SPF, RHS)) 951 return R; 952 if (SelectPatternFlavor SPF2 = MatchSelectPattern(RHS, LHS2, RHS2)) 953 if (Instruction *R = FoldSPFofSPF(cast<Instruction>(RHS),SPF2,LHS2,RHS2, 954 SI, SPF, LHS)) 955 return R; 956 } 957 958 // TODO. 959 // ABS(-X) -> ABS(X) 960 // ABS(ABS(X)) -> ABS(X) 961 } 962 963 // See if we can fold the select into a phi node if the condition is a select. 964 if (isa<PHINode>(SI.getCondition())) 965 // The true/false values have to be live in the PHI predecessor's blocks. 966 if (CanSelectOperandBeMappingIntoPredBlock(TrueVal, SI) && 967 CanSelectOperandBeMappingIntoPredBlock(FalseVal, SI)) 968 if (Instruction *NV = FoldOpIntoPhi(SI)) 969 return NV; 970 971 if (SelectInst *TrueSI = dyn_cast<SelectInst>(TrueVal)) { 972 if (TrueSI->getCondition() == CondVal) { 973 if (SI.getTrueValue() == TrueSI->getTrueValue()) 974 return 0; 975 SI.setOperand(1, TrueSI->getTrueValue()); 976 return &SI; 977 } 978 } 979 if (SelectInst *FalseSI = dyn_cast<SelectInst>(FalseVal)) { 980 if (FalseSI->getCondition() == CondVal) { 981 if (SI.getFalseValue() == FalseSI->getFalseValue()) 982 return 0; 983 SI.setOperand(2, FalseSI->getFalseValue()); 984 return &SI; 985 } 986 } 987 988 if (BinaryOperator::isNot(CondVal)) { 989 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal)); 990 SI.setOperand(1, FalseVal); 991 SI.setOperand(2, TrueVal); 992 return &SI; 993 } 994 995 if (VectorType* VecTy = dyn_cast<VectorType>(SI.getType())) { 996 unsigned VWidth = VecTy->getNumElements(); 997 APInt UndefElts(VWidth, 0); 998 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth)); 999 if (Value *V = SimplifyDemandedVectorElts(&SI, AllOnesEltMask, UndefElts)) { 1000 if (V != &SI) 1001 return ReplaceInstUsesWith(SI, V); 1002 return &SI; 1003 } 1004 1005 if (isa<ConstantAggregateZero>(CondVal)) { 1006 return ReplaceInstUsesWith(SI, FalseVal); 1007 } 1008 } 1009 1010 return 0; 1011 } 1012