1 //===- InstCombineSelect.cpp ----------------------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements the visitSelect function. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "InstCombineInternal.h" 14 #include "llvm/ADT/APInt.h" 15 #include "llvm/ADT/Optional.h" 16 #include "llvm/ADT/STLExtras.h" 17 #include "llvm/ADT/SmallVector.h" 18 #include "llvm/Analysis/AssumptionCache.h" 19 #include "llvm/Analysis/CmpInstAnalysis.h" 20 #include "llvm/Analysis/InstructionSimplify.h" 21 #include "llvm/Analysis/ValueTracking.h" 22 #include "llvm/IR/BasicBlock.h" 23 #include "llvm/IR/Constant.h" 24 #include "llvm/IR/Constants.h" 25 #include "llvm/IR/DerivedTypes.h" 26 #include "llvm/IR/IRBuilder.h" 27 #include "llvm/IR/InstrTypes.h" 28 #include "llvm/IR/Instruction.h" 29 #include "llvm/IR/Instructions.h" 30 #include "llvm/IR/IntrinsicInst.h" 31 #include "llvm/IR/Intrinsics.h" 32 #include "llvm/IR/Operator.h" 33 #include "llvm/IR/PatternMatch.h" 34 #include "llvm/IR/Type.h" 35 #include "llvm/IR/User.h" 36 #include "llvm/IR/Value.h" 37 #include "llvm/Support/Casting.h" 38 #include "llvm/Support/ErrorHandling.h" 39 #include "llvm/Support/KnownBits.h" 40 #include "llvm/Transforms/InstCombine/InstCombineWorklist.h" 41 #include <cassert> 42 #include <utility> 43 44 using namespace llvm; 45 using namespace PatternMatch; 46 47 #define DEBUG_TYPE "instcombine" 48 49 static Value *createMinMax(InstCombiner::BuilderTy &Builder, 50 SelectPatternFlavor SPF, Value *A, Value *B) { 51 CmpInst::Predicate Pred = getMinMaxPred(SPF); 52 assert(CmpInst::isIntPredicate(Pred) && "Expected integer predicate"); 53 return Builder.CreateSelect(Builder.CreateICmp(Pred, A, B), A, B); 54 } 55 56 /// Replace a select operand based on an equality comparison with the identity 57 /// constant of a binop. 58 static Instruction *foldSelectBinOpIdentity(SelectInst &Sel, 59 const TargetLibraryInfo &TLI) { 60 // The select condition must be an equality compare with a constant operand. 61 Value *X; 62 Constant *C; 63 CmpInst::Predicate Pred; 64 if (!match(Sel.getCondition(), m_Cmp(Pred, m_Value(X), m_Constant(C)))) 65 return nullptr; 66 67 bool IsEq; 68 if (ICmpInst::isEquality(Pred)) 69 IsEq = Pred == ICmpInst::ICMP_EQ; 70 else if (Pred == FCmpInst::FCMP_OEQ) 71 IsEq = true; 72 else if (Pred == FCmpInst::FCMP_UNE) 73 IsEq = false; 74 else 75 return nullptr; 76 77 // A select operand must be a binop. 78 BinaryOperator *BO; 79 if (!match(Sel.getOperand(IsEq ? 1 : 2), m_BinOp(BO))) 80 return nullptr; 81 82 // The compare constant must be the identity constant for that binop. 83 // If this a floating-point compare with 0.0, any zero constant will do. 84 Type *Ty = BO->getType(); 85 Constant *IdC = ConstantExpr::getBinOpIdentity(BO->getOpcode(), Ty, true); 86 if (IdC != C) { 87 if (!IdC || !CmpInst::isFPPredicate(Pred)) 88 return nullptr; 89 if (!match(IdC, m_AnyZeroFP()) || !match(C, m_AnyZeroFP())) 90 return nullptr; 91 } 92 93 // Last, match the compare variable operand with a binop operand. 94 Value *Y; 95 if (!BO->isCommutative() && !match(BO, m_BinOp(m_Value(Y), m_Specific(X)))) 96 return nullptr; 97 if (!match(BO, m_c_BinOp(m_Value(Y), m_Specific(X)))) 98 return nullptr; 99 100 // +0.0 compares equal to -0.0, and so it does not behave as required for this 101 // transform. Bail out if we can not exclude that possibility. 102 if (isa<FPMathOperator>(BO)) 103 if (!BO->hasNoSignedZeros() && !CannotBeNegativeZero(Y, &TLI)) 104 return nullptr; 105 106 // BO = binop Y, X 107 // S = { select (cmp eq X, C), BO, ? } or { select (cmp ne X, C), ?, BO } 108 // => 109 // S = { select (cmp eq X, C), Y, ? } or { select (cmp ne X, C), ?, Y } 110 Sel.setOperand(IsEq ? 1 : 2, Y); 111 return &Sel; 112 } 113 114 /// This folds: 115 /// select (icmp eq (and X, C1)), TC, FC 116 /// iff C1 is a power 2 and the difference between TC and FC is a power-of-2. 117 /// To something like: 118 /// (shr (and (X, C1)), (log2(C1) - log2(TC-FC))) + FC 119 /// Or: 120 /// (shl (and (X, C1)), (log2(TC-FC) - log2(C1))) + FC 121 /// With some variations depending if FC is larger than TC, or the shift 122 /// isn't needed, or the bit widths don't match. 123 static Value *foldSelectICmpAnd(SelectInst &Sel, ICmpInst *Cmp, 124 InstCombiner::BuilderTy &Builder) { 125 const APInt *SelTC, *SelFC; 126 if (!match(Sel.getTrueValue(), m_APInt(SelTC)) || 127 !match(Sel.getFalseValue(), m_APInt(SelFC))) 128 return nullptr; 129 130 // If this is a vector select, we need a vector compare. 131 Type *SelType = Sel.getType(); 132 if (SelType->isVectorTy() != Cmp->getType()->isVectorTy()) 133 return nullptr; 134 135 Value *V; 136 APInt AndMask; 137 bool CreateAnd = false; 138 ICmpInst::Predicate Pred = Cmp->getPredicate(); 139 if (ICmpInst::isEquality(Pred)) { 140 if (!match(Cmp->getOperand(1), m_Zero())) 141 return nullptr; 142 143 V = Cmp->getOperand(0); 144 const APInt *AndRHS; 145 if (!match(V, m_And(m_Value(), m_Power2(AndRHS)))) 146 return nullptr; 147 148 AndMask = *AndRHS; 149 } else if (decomposeBitTestICmp(Cmp->getOperand(0), Cmp->getOperand(1), 150 Pred, V, AndMask)) { 151 assert(ICmpInst::isEquality(Pred) && "Not equality test?"); 152 if (!AndMask.isPowerOf2()) 153 return nullptr; 154 155 CreateAnd = true; 156 } else { 157 return nullptr; 158 } 159 160 // In general, when both constants are non-zero, we would need an offset to 161 // replace the select. This would require more instructions than we started 162 // with. But there's one special-case that we handle here because it can 163 // simplify/reduce the instructions. 164 APInt TC = *SelTC; 165 APInt FC = *SelFC; 166 if (!TC.isNullValue() && !FC.isNullValue()) { 167 // If the select constants differ by exactly one bit and that's the same 168 // bit that is masked and checked by the select condition, the select can 169 // be replaced by bitwise logic to set/clear one bit of the constant result. 170 if (TC.getBitWidth() != AndMask.getBitWidth() || (TC ^ FC) != AndMask) 171 return nullptr; 172 if (CreateAnd) { 173 // If we have to create an 'and', then we must kill the cmp to not 174 // increase the instruction count. 175 if (!Cmp->hasOneUse()) 176 return nullptr; 177 V = Builder.CreateAnd(V, ConstantInt::get(SelType, AndMask)); 178 } 179 bool ExtraBitInTC = TC.ugt(FC); 180 if (Pred == ICmpInst::ICMP_EQ) { 181 // If the masked bit in V is clear, clear or set the bit in the result: 182 // (V & AndMaskC) == 0 ? TC : FC --> (V & AndMaskC) ^ TC 183 // (V & AndMaskC) == 0 ? TC : FC --> (V & AndMaskC) | TC 184 Constant *C = ConstantInt::get(SelType, TC); 185 return ExtraBitInTC ? Builder.CreateXor(V, C) : Builder.CreateOr(V, C); 186 } 187 if (Pred == ICmpInst::ICMP_NE) { 188 // If the masked bit in V is set, set or clear the bit in the result: 189 // (V & AndMaskC) != 0 ? TC : FC --> (V & AndMaskC) | FC 190 // (V & AndMaskC) != 0 ? TC : FC --> (V & AndMaskC) ^ FC 191 Constant *C = ConstantInt::get(SelType, FC); 192 return ExtraBitInTC ? Builder.CreateOr(V, C) : Builder.CreateXor(V, C); 193 } 194 llvm_unreachable("Only expecting equality predicates"); 195 } 196 197 // Make sure one of the select arms is a power-of-2. 198 if (!TC.isPowerOf2() && !FC.isPowerOf2()) 199 return nullptr; 200 201 // Determine which shift is needed to transform result of the 'and' into the 202 // desired result. 203 const APInt &ValC = !TC.isNullValue() ? TC : FC; 204 unsigned ValZeros = ValC.logBase2(); 205 unsigned AndZeros = AndMask.logBase2(); 206 207 // Insert the 'and' instruction on the input to the truncate. 208 if (CreateAnd) 209 V = Builder.CreateAnd(V, ConstantInt::get(V->getType(), AndMask)); 210 211 // If types don't match, we can still convert the select by introducing a zext 212 // or a trunc of the 'and'. 213 if (ValZeros > AndZeros) { 214 V = Builder.CreateZExtOrTrunc(V, SelType); 215 V = Builder.CreateShl(V, ValZeros - AndZeros); 216 } else if (ValZeros < AndZeros) { 217 V = Builder.CreateLShr(V, AndZeros - ValZeros); 218 V = Builder.CreateZExtOrTrunc(V, SelType); 219 } else { 220 V = Builder.CreateZExtOrTrunc(V, SelType); 221 } 222 223 // Okay, now we know that everything is set up, we just don't know whether we 224 // have a icmp_ne or icmp_eq and whether the true or false val is the zero. 225 bool ShouldNotVal = !TC.isNullValue(); 226 ShouldNotVal ^= Pred == ICmpInst::ICMP_NE; 227 if (ShouldNotVal) 228 V = Builder.CreateXor(V, ValC); 229 230 return V; 231 } 232 233 /// We want to turn code that looks like this: 234 /// %C = or %A, %B 235 /// %D = select %cond, %C, %A 236 /// into: 237 /// %C = select %cond, %B, 0 238 /// %D = or %A, %C 239 /// 240 /// Assuming that the specified instruction is an operand to the select, return 241 /// a bitmask indicating which operands of this instruction are foldable if they 242 /// equal the other incoming value of the select. 243 static unsigned getSelectFoldableOperands(BinaryOperator *I) { 244 switch (I->getOpcode()) { 245 case Instruction::Add: 246 case Instruction::Mul: 247 case Instruction::And: 248 case Instruction::Or: 249 case Instruction::Xor: 250 return 3; // Can fold through either operand. 251 case Instruction::Sub: // Can only fold on the amount subtracted. 252 case Instruction::Shl: // Can only fold on the shift amount. 253 case Instruction::LShr: 254 case Instruction::AShr: 255 return 1; 256 default: 257 return 0; // Cannot fold 258 } 259 } 260 261 /// For the same transformation as the previous function, return the identity 262 /// constant that goes into the select. 263 static APInt getSelectFoldableConstant(BinaryOperator *I) { 264 switch (I->getOpcode()) { 265 default: llvm_unreachable("This cannot happen!"); 266 case Instruction::Add: 267 case Instruction::Sub: 268 case Instruction::Or: 269 case Instruction::Xor: 270 case Instruction::Shl: 271 case Instruction::LShr: 272 case Instruction::AShr: 273 return APInt::getNullValue(I->getType()->getScalarSizeInBits()); 274 case Instruction::And: 275 return APInt::getAllOnesValue(I->getType()->getScalarSizeInBits()); 276 case Instruction::Mul: 277 return APInt(I->getType()->getScalarSizeInBits(), 1); 278 } 279 } 280 281 /// We have (select c, TI, FI), and we know that TI and FI have the same opcode. 282 Instruction *InstCombiner::foldSelectOpOp(SelectInst &SI, Instruction *TI, 283 Instruction *FI) { 284 // Don't break up min/max patterns. The hasOneUse checks below prevent that 285 // for most cases, but vector min/max with bitcasts can be transformed. If the 286 // one-use restrictions are eased for other patterns, we still don't want to 287 // obfuscate min/max. 288 if ((match(&SI, m_SMin(m_Value(), m_Value())) || 289 match(&SI, m_SMax(m_Value(), m_Value())) || 290 match(&SI, m_UMin(m_Value(), m_Value())) || 291 match(&SI, m_UMax(m_Value(), m_Value())))) 292 return nullptr; 293 294 // If this is a cast from the same type, merge. 295 Value *Cond = SI.getCondition(); 296 Type *CondTy = Cond->getType(); 297 if (TI->getNumOperands() == 1 && TI->isCast()) { 298 Type *FIOpndTy = FI->getOperand(0)->getType(); 299 if (TI->getOperand(0)->getType() != FIOpndTy) 300 return nullptr; 301 302 // The select condition may be a vector. We may only change the operand 303 // type if the vector width remains the same (and matches the condition). 304 if (CondTy->isVectorTy()) { 305 if (!FIOpndTy->isVectorTy()) 306 return nullptr; 307 if (CondTy->getVectorNumElements() != FIOpndTy->getVectorNumElements()) 308 return nullptr; 309 310 // TODO: If the backend knew how to deal with casts better, we could 311 // remove this limitation. For now, there's too much potential to create 312 // worse codegen by promoting the select ahead of size-altering casts 313 // (PR28160). 314 // 315 // Note that ValueTracking's matchSelectPattern() looks through casts 316 // without checking 'hasOneUse' when it matches min/max patterns, so this 317 // transform may end up happening anyway. 318 if (TI->getOpcode() != Instruction::BitCast && 319 (!TI->hasOneUse() || !FI->hasOneUse())) 320 return nullptr; 321 } else if (!TI->hasOneUse() || !FI->hasOneUse()) { 322 // TODO: The one-use restrictions for a scalar select could be eased if 323 // the fold of a select in visitLoadInst() was enhanced to match a pattern 324 // that includes a cast. 325 return nullptr; 326 } 327 328 // Fold this by inserting a select from the input values. 329 Value *NewSI = 330 Builder.CreateSelect(Cond, TI->getOperand(0), FI->getOperand(0), 331 SI.getName() + ".v", &SI); 332 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI, 333 TI->getType()); 334 } 335 336 // Cond ? -X : -Y --> -(Cond ? X : Y) 337 Value *X, *Y; 338 if (match(TI, m_FNeg(m_Value(X))) && match(FI, m_FNeg(m_Value(Y))) && 339 (TI->hasOneUse() || FI->hasOneUse())) { 340 Value *NewSel = Builder.CreateSelect(Cond, X, Y, SI.getName() + ".v", &SI); 341 // TODO: Remove the hack for the binop form when the unary op is optimized 342 // properly with all IR passes. 343 if (TI->getOpcode() != Instruction::FNeg) 344 return BinaryOperator::CreateFNegFMF(NewSel, cast<BinaryOperator>(TI)); 345 return UnaryOperator::CreateFNeg(NewSel); 346 } 347 348 // Only handle binary operators (including two-operand getelementptr) with 349 // one-use here. As with the cast case above, it may be possible to relax the 350 // one-use constraint, but that needs be examined carefully since it may not 351 // reduce the total number of instructions. 352 if (TI->getNumOperands() != 2 || FI->getNumOperands() != 2 || 353 (!isa<BinaryOperator>(TI) && !isa<GetElementPtrInst>(TI)) || 354 !TI->hasOneUse() || !FI->hasOneUse()) 355 return nullptr; 356 357 // Figure out if the operations have any operands in common. 358 Value *MatchOp, *OtherOpT, *OtherOpF; 359 bool MatchIsOpZero; 360 if (TI->getOperand(0) == FI->getOperand(0)) { 361 MatchOp = TI->getOperand(0); 362 OtherOpT = TI->getOperand(1); 363 OtherOpF = FI->getOperand(1); 364 MatchIsOpZero = true; 365 } else if (TI->getOperand(1) == FI->getOperand(1)) { 366 MatchOp = TI->getOperand(1); 367 OtherOpT = TI->getOperand(0); 368 OtherOpF = FI->getOperand(0); 369 MatchIsOpZero = false; 370 } else if (!TI->isCommutative()) { 371 return nullptr; 372 } else if (TI->getOperand(0) == FI->getOperand(1)) { 373 MatchOp = TI->getOperand(0); 374 OtherOpT = TI->getOperand(1); 375 OtherOpF = FI->getOperand(0); 376 MatchIsOpZero = true; 377 } else if (TI->getOperand(1) == FI->getOperand(0)) { 378 MatchOp = TI->getOperand(1); 379 OtherOpT = TI->getOperand(0); 380 OtherOpF = FI->getOperand(1); 381 MatchIsOpZero = true; 382 } else { 383 return nullptr; 384 } 385 386 // If the select condition is a vector, the operands of the original select's 387 // operands also must be vectors. This may not be the case for getelementptr 388 // for example. 389 if (CondTy->isVectorTy() && (!OtherOpT->getType()->isVectorTy() || 390 !OtherOpF->getType()->isVectorTy())) 391 return nullptr; 392 393 // If we reach here, they do have operations in common. 394 Value *NewSI = Builder.CreateSelect(Cond, OtherOpT, OtherOpF, 395 SI.getName() + ".v", &SI); 396 Value *Op0 = MatchIsOpZero ? MatchOp : NewSI; 397 Value *Op1 = MatchIsOpZero ? NewSI : MatchOp; 398 if (auto *BO = dyn_cast<BinaryOperator>(TI)) { 399 BinaryOperator *NewBO = BinaryOperator::Create(BO->getOpcode(), Op0, Op1); 400 NewBO->copyIRFlags(TI); 401 NewBO->andIRFlags(FI); 402 return NewBO; 403 } 404 if (auto *TGEP = dyn_cast<GetElementPtrInst>(TI)) { 405 auto *FGEP = cast<GetElementPtrInst>(FI); 406 Type *ElementType = TGEP->getResultElementType(); 407 return TGEP->isInBounds() && FGEP->isInBounds() 408 ? GetElementPtrInst::CreateInBounds(ElementType, Op0, {Op1}) 409 : GetElementPtrInst::Create(ElementType, Op0, {Op1}); 410 } 411 llvm_unreachable("Expected BinaryOperator or GEP"); 412 return nullptr; 413 } 414 415 static bool isSelect01(const APInt &C1I, const APInt &C2I) { 416 if (!C1I.isNullValue() && !C2I.isNullValue()) // One side must be zero. 417 return false; 418 return C1I.isOneValue() || C1I.isAllOnesValue() || 419 C2I.isOneValue() || C2I.isAllOnesValue(); 420 } 421 422 /// Try to fold the select into one of the operands to allow further 423 /// optimization. 424 Instruction *InstCombiner::foldSelectIntoOp(SelectInst &SI, Value *TrueVal, 425 Value *FalseVal) { 426 // See the comment above GetSelectFoldableOperands for a description of the 427 // transformation we are doing here. 428 if (auto *TVI = dyn_cast<BinaryOperator>(TrueVal)) { 429 if (TVI->hasOneUse() && !isa<Constant>(FalseVal)) { 430 if (unsigned SFO = getSelectFoldableOperands(TVI)) { 431 unsigned OpToFold = 0; 432 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) { 433 OpToFold = 1; 434 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) { 435 OpToFold = 2; 436 } 437 438 if (OpToFold) { 439 APInt CI = getSelectFoldableConstant(TVI); 440 Value *OOp = TVI->getOperand(2-OpToFold); 441 // Avoid creating select between 2 constants unless it's selecting 442 // between 0, 1 and -1. 443 const APInt *OOpC; 444 bool OOpIsAPInt = match(OOp, m_APInt(OOpC)); 445 if (!isa<Constant>(OOp) || (OOpIsAPInt && isSelect01(CI, *OOpC))) { 446 Value *C = ConstantInt::get(OOp->getType(), CI); 447 Value *NewSel = Builder.CreateSelect(SI.getCondition(), OOp, C); 448 NewSel->takeName(TVI); 449 BinaryOperator *BO = BinaryOperator::Create(TVI->getOpcode(), 450 FalseVal, NewSel); 451 BO->copyIRFlags(TVI); 452 return BO; 453 } 454 } 455 } 456 } 457 } 458 459 if (auto *FVI = dyn_cast<BinaryOperator>(FalseVal)) { 460 if (FVI->hasOneUse() && !isa<Constant>(TrueVal)) { 461 if (unsigned SFO = getSelectFoldableOperands(FVI)) { 462 unsigned OpToFold = 0; 463 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) { 464 OpToFold = 1; 465 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) { 466 OpToFold = 2; 467 } 468 469 if (OpToFold) { 470 APInt CI = getSelectFoldableConstant(FVI); 471 Value *OOp = FVI->getOperand(2-OpToFold); 472 // Avoid creating select between 2 constants unless it's selecting 473 // between 0, 1 and -1. 474 const APInt *OOpC; 475 bool OOpIsAPInt = match(OOp, m_APInt(OOpC)); 476 if (!isa<Constant>(OOp) || (OOpIsAPInt && isSelect01(CI, *OOpC))) { 477 Value *C = ConstantInt::get(OOp->getType(), CI); 478 Value *NewSel = Builder.CreateSelect(SI.getCondition(), C, OOp); 479 NewSel->takeName(FVI); 480 BinaryOperator *BO = BinaryOperator::Create(FVI->getOpcode(), 481 TrueVal, NewSel); 482 BO->copyIRFlags(FVI); 483 return BO; 484 } 485 } 486 } 487 } 488 } 489 490 return nullptr; 491 } 492 493 /// We want to turn: 494 /// (select (icmp eq (and X, Y), 0), (and (lshr X, Z), 1), 1) 495 /// into: 496 /// zext (icmp ne i32 (and X, (or Y, (shl 1, Z))), 0) 497 /// Note: 498 /// Z may be 0 if lshr is missing. 499 /// Worst-case scenario is that we will replace 5 instructions with 5 different 500 /// instructions, but we got rid of select. 501 static Instruction *foldSelectICmpAndAnd(Type *SelType, const ICmpInst *Cmp, 502 Value *TVal, Value *FVal, 503 InstCombiner::BuilderTy &Builder) { 504 if (!(Cmp->hasOneUse() && Cmp->getOperand(0)->hasOneUse() && 505 Cmp->getPredicate() == ICmpInst::ICMP_EQ && 506 match(Cmp->getOperand(1), m_Zero()) && match(FVal, m_One()))) 507 return nullptr; 508 509 // The TrueVal has general form of: and %B, 1 510 Value *B; 511 if (!match(TVal, m_OneUse(m_And(m_Value(B), m_One())))) 512 return nullptr; 513 514 // Where %B may be optionally shifted: lshr %X, %Z. 515 Value *X, *Z; 516 const bool HasShift = match(B, m_OneUse(m_LShr(m_Value(X), m_Value(Z)))); 517 if (!HasShift) 518 X = B; 519 520 Value *Y; 521 if (!match(Cmp->getOperand(0), m_c_And(m_Specific(X), m_Value(Y)))) 522 return nullptr; 523 524 // ((X & Y) == 0) ? ((X >> Z) & 1) : 1 --> (X & (Y | (1 << Z))) != 0 525 // ((X & Y) == 0) ? (X & 1) : 1 --> (X & (Y | 1)) != 0 526 Constant *One = ConstantInt::get(SelType, 1); 527 Value *MaskB = HasShift ? Builder.CreateShl(One, Z) : One; 528 Value *FullMask = Builder.CreateOr(Y, MaskB); 529 Value *MaskedX = Builder.CreateAnd(X, FullMask); 530 Value *ICmpNeZero = Builder.CreateIsNotNull(MaskedX); 531 return new ZExtInst(ICmpNeZero, SelType); 532 } 533 534 /// We want to turn: 535 /// (select (icmp sgt x, C), lshr (X, Y), ashr (X, Y)); iff C s>= -1 536 /// (select (icmp slt x, C), ashr (X, Y), lshr (X, Y)); iff C s>= 0 537 /// into: 538 /// ashr (X, Y) 539 static Value *foldSelectICmpLshrAshr(const ICmpInst *IC, Value *TrueVal, 540 Value *FalseVal, 541 InstCombiner::BuilderTy &Builder) { 542 ICmpInst::Predicate Pred = IC->getPredicate(); 543 Value *CmpLHS = IC->getOperand(0); 544 Value *CmpRHS = IC->getOperand(1); 545 if (!CmpRHS->getType()->isIntOrIntVectorTy()) 546 return nullptr; 547 548 Value *X, *Y; 549 unsigned Bitwidth = CmpRHS->getType()->getScalarSizeInBits(); 550 if ((Pred != ICmpInst::ICMP_SGT || 551 !match(CmpRHS, 552 m_SpecificInt_ICMP(ICmpInst::ICMP_SGE, APInt(Bitwidth, -1)))) && 553 (Pred != ICmpInst::ICMP_SLT || 554 !match(CmpRHS, 555 m_SpecificInt_ICMP(ICmpInst::ICMP_SGE, APInt(Bitwidth, 0))))) 556 return nullptr; 557 558 // Canonicalize so that ashr is in FalseVal. 559 if (Pred == ICmpInst::ICMP_SLT) 560 std::swap(TrueVal, FalseVal); 561 562 if (match(TrueVal, m_LShr(m_Value(X), m_Value(Y))) && 563 match(FalseVal, m_AShr(m_Specific(X), m_Specific(Y))) && 564 match(CmpLHS, m_Specific(X))) { 565 const auto *Ashr = cast<Instruction>(FalseVal); 566 // if lshr is not exact and ashr is, this new ashr must not be exact. 567 bool IsExact = Ashr->isExact() && cast<Instruction>(TrueVal)->isExact(); 568 return Builder.CreateAShr(X, Y, IC->getName(), IsExact); 569 } 570 571 return nullptr; 572 } 573 574 /// We want to turn: 575 /// (select (icmp eq (and X, C1), 0), Y, (or Y, C2)) 576 /// into: 577 /// (or (shl (and X, C1), C3), Y) 578 /// iff: 579 /// C1 and C2 are both powers of 2 580 /// where: 581 /// C3 = Log(C2) - Log(C1) 582 /// 583 /// This transform handles cases where: 584 /// 1. The icmp predicate is inverted 585 /// 2. The select operands are reversed 586 /// 3. The magnitude of C2 and C1 are flipped 587 static Value *foldSelectICmpAndOr(const ICmpInst *IC, Value *TrueVal, 588 Value *FalseVal, 589 InstCombiner::BuilderTy &Builder) { 590 // Only handle integer compares. Also, if this is a vector select, we need a 591 // vector compare. 592 if (!TrueVal->getType()->isIntOrIntVectorTy() || 593 TrueVal->getType()->isVectorTy() != IC->getType()->isVectorTy()) 594 return nullptr; 595 596 Value *CmpLHS = IC->getOperand(0); 597 Value *CmpRHS = IC->getOperand(1); 598 599 Value *V; 600 unsigned C1Log; 601 bool IsEqualZero; 602 bool NeedAnd = false; 603 if (IC->isEquality()) { 604 if (!match(CmpRHS, m_Zero())) 605 return nullptr; 606 607 const APInt *C1; 608 if (!match(CmpLHS, m_And(m_Value(), m_Power2(C1)))) 609 return nullptr; 610 611 V = CmpLHS; 612 C1Log = C1->logBase2(); 613 IsEqualZero = IC->getPredicate() == ICmpInst::ICMP_EQ; 614 } else if (IC->getPredicate() == ICmpInst::ICMP_SLT || 615 IC->getPredicate() == ICmpInst::ICMP_SGT) { 616 // We also need to recognize (icmp slt (trunc (X)), 0) and 617 // (icmp sgt (trunc (X)), -1). 618 IsEqualZero = IC->getPredicate() == ICmpInst::ICMP_SGT; 619 if ((IsEqualZero && !match(CmpRHS, m_AllOnes())) || 620 (!IsEqualZero && !match(CmpRHS, m_Zero()))) 621 return nullptr; 622 623 if (!match(CmpLHS, m_OneUse(m_Trunc(m_Value(V))))) 624 return nullptr; 625 626 C1Log = CmpLHS->getType()->getScalarSizeInBits() - 1; 627 NeedAnd = true; 628 } else { 629 return nullptr; 630 } 631 632 const APInt *C2; 633 bool OrOnTrueVal = false; 634 bool OrOnFalseVal = match(FalseVal, m_Or(m_Specific(TrueVal), m_Power2(C2))); 635 if (!OrOnFalseVal) 636 OrOnTrueVal = match(TrueVal, m_Or(m_Specific(FalseVal), m_Power2(C2))); 637 638 if (!OrOnFalseVal && !OrOnTrueVal) 639 return nullptr; 640 641 Value *Y = OrOnFalseVal ? TrueVal : FalseVal; 642 643 unsigned C2Log = C2->logBase2(); 644 645 bool NeedXor = (!IsEqualZero && OrOnFalseVal) || (IsEqualZero && OrOnTrueVal); 646 bool NeedShift = C1Log != C2Log; 647 bool NeedZExtTrunc = Y->getType()->getScalarSizeInBits() != 648 V->getType()->getScalarSizeInBits(); 649 650 // Make sure we don't create more instructions than we save. 651 Value *Or = OrOnFalseVal ? FalseVal : TrueVal; 652 if ((NeedShift + NeedXor + NeedZExtTrunc) > 653 (IC->hasOneUse() + Or->hasOneUse())) 654 return nullptr; 655 656 if (NeedAnd) { 657 // Insert the AND instruction on the input to the truncate. 658 APInt C1 = APInt::getOneBitSet(V->getType()->getScalarSizeInBits(), C1Log); 659 V = Builder.CreateAnd(V, ConstantInt::get(V->getType(), C1)); 660 } 661 662 if (C2Log > C1Log) { 663 V = Builder.CreateZExtOrTrunc(V, Y->getType()); 664 V = Builder.CreateShl(V, C2Log - C1Log); 665 } else if (C1Log > C2Log) { 666 V = Builder.CreateLShr(V, C1Log - C2Log); 667 V = Builder.CreateZExtOrTrunc(V, Y->getType()); 668 } else 669 V = Builder.CreateZExtOrTrunc(V, Y->getType()); 670 671 if (NeedXor) 672 V = Builder.CreateXor(V, *C2); 673 674 return Builder.CreateOr(V, Y); 675 } 676 677 /// Transform patterns such as (a > b) ? a - b : 0 into usub.sat(a, b). 678 /// There are 8 commuted/swapped variants of this pattern. 679 /// TODO: Also support a - UMIN(a,b) patterns. 680 static Value *canonicalizeSaturatedSubtract(const ICmpInst *ICI, 681 const Value *TrueVal, 682 const Value *FalseVal, 683 InstCombiner::BuilderTy &Builder) { 684 ICmpInst::Predicate Pred = ICI->getPredicate(); 685 if (!ICmpInst::isUnsigned(Pred)) 686 return nullptr; 687 688 // (b > a) ? 0 : a - b -> (b <= a) ? a - b : 0 689 if (match(TrueVal, m_Zero())) { 690 Pred = ICmpInst::getInversePredicate(Pred); 691 std::swap(TrueVal, FalseVal); 692 } 693 if (!match(FalseVal, m_Zero())) 694 return nullptr; 695 696 Value *A = ICI->getOperand(0); 697 Value *B = ICI->getOperand(1); 698 if (Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_ULT) { 699 // (b < a) ? a - b : 0 -> (a > b) ? a - b : 0 700 std::swap(A, B); 701 Pred = ICmpInst::getSwappedPredicate(Pred); 702 } 703 704 assert((Pred == ICmpInst::ICMP_UGE || Pred == ICmpInst::ICMP_UGT) && 705 "Unexpected isUnsigned predicate!"); 706 707 // Account for swapped form of subtraction: ((a > b) ? b - a : 0). 708 bool IsNegative = false; 709 if (match(TrueVal, m_Sub(m_Specific(B), m_Specific(A)))) 710 IsNegative = true; 711 else if (!match(TrueVal, m_Sub(m_Specific(A), m_Specific(B)))) 712 return nullptr; 713 714 // If sub is used anywhere else, we wouldn't be able to eliminate it 715 // afterwards. 716 if (!TrueVal->hasOneUse()) 717 return nullptr; 718 719 // (a > b) ? a - b : 0 -> usub.sat(a, b) 720 // (a > b) ? b - a : 0 -> -usub.sat(a, b) 721 Value *Result = Builder.CreateBinaryIntrinsic(Intrinsic::usub_sat, A, B); 722 if (IsNegative) 723 Result = Builder.CreateNeg(Result); 724 return Result; 725 } 726 727 static Value *canonicalizeSaturatedAdd(ICmpInst *Cmp, Value *TVal, Value *FVal, 728 InstCombiner::BuilderTy &Builder) { 729 if (!Cmp->hasOneUse()) 730 return nullptr; 731 732 // Match unsigned saturated add with constant. 733 Value *Cmp0 = Cmp->getOperand(0); 734 Value *Cmp1 = Cmp->getOperand(1); 735 ICmpInst::Predicate Pred = Cmp->getPredicate(); 736 Value *X; 737 const APInt *C, *CmpC; 738 if (Pred == ICmpInst::ICMP_ULT && 739 match(TVal, m_Add(m_Value(X), m_APInt(C))) && X == Cmp0 && 740 match(FVal, m_AllOnes()) && match(Cmp1, m_APInt(CmpC)) && *CmpC == ~*C) { 741 // (X u< ~C) ? (X + C) : -1 --> uadd.sat(X, C) 742 return Builder.CreateBinaryIntrinsic( 743 Intrinsic::uadd_sat, X, ConstantInt::get(X->getType(), *C)); 744 } 745 746 // Match unsigned saturated add of 2 variables with an unnecessary 'not'. 747 // There are 8 commuted variants. 748 // Canonicalize -1 (saturated result) to true value of the select. Just 749 // swapping the compare operands is legal, because the selected value is the 750 // same in case of equality, so we can interchange u< and u<=. 751 if (match(FVal, m_AllOnes())) { 752 std::swap(TVal, FVal); 753 std::swap(Cmp0, Cmp1); 754 } 755 if (!match(TVal, m_AllOnes())) 756 return nullptr; 757 758 // Canonicalize predicate to 'ULT'. 759 if (Pred == ICmpInst::ICMP_UGT) { 760 Pred = ICmpInst::ICMP_ULT; 761 std::swap(Cmp0, Cmp1); 762 } 763 if (Pred != ICmpInst::ICMP_ULT) 764 return nullptr; 765 766 // Match unsigned saturated add of 2 variables with an unnecessary 'not'. 767 Value *Y; 768 if (match(Cmp0, m_Not(m_Value(X))) && 769 match(FVal, m_c_Add(m_Specific(X), m_Value(Y))) && Y == Cmp1) { 770 // (~X u< Y) ? -1 : (X + Y) --> uadd.sat(X, Y) 771 // (~X u< Y) ? -1 : (Y + X) --> uadd.sat(X, Y) 772 return Builder.CreateBinaryIntrinsic(Intrinsic::uadd_sat, X, Y); 773 } 774 // The 'not' op may be included in the sum but not the compare. 775 X = Cmp0; 776 Y = Cmp1; 777 if (match(FVal, m_c_Add(m_Not(m_Specific(X)), m_Specific(Y)))) { 778 // (X u< Y) ? -1 : (~X + Y) --> uadd.sat(~X, Y) 779 // (X u< Y) ? -1 : (Y + ~X) --> uadd.sat(Y, ~X) 780 BinaryOperator *BO = cast<BinaryOperator>(FVal); 781 return Builder.CreateBinaryIntrinsic( 782 Intrinsic::uadd_sat, BO->getOperand(0), BO->getOperand(1)); 783 } 784 785 return nullptr; 786 } 787 788 /// Attempt to fold a cttz/ctlz followed by a icmp plus select into a single 789 /// call to cttz/ctlz with flag 'is_zero_undef' cleared. 790 /// 791 /// For example, we can fold the following code sequence: 792 /// \code 793 /// %0 = tail call i32 @llvm.cttz.i32(i32 %x, i1 true) 794 /// %1 = icmp ne i32 %x, 0 795 /// %2 = select i1 %1, i32 %0, i32 32 796 /// \code 797 /// 798 /// into: 799 /// %0 = tail call i32 @llvm.cttz.i32(i32 %x, i1 false) 800 static Value *foldSelectCttzCtlz(ICmpInst *ICI, Value *TrueVal, Value *FalseVal, 801 InstCombiner::BuilderTy &Builder) { 802 ICmpInst::Predicate Pred = ICI->getPredicate(); 803 Value *CmpLHS = ICI->getOperand(0); 804 Value *CmpRHS = ICI->getOperand(1); 805 806 // Check if the condition value compares a value for equality against zero. 807 if (!ICI->isEquality() || !match(CmpRHS, m_Zero())) 808 return nullptr; 809 810 Value *Count = FalseVal; 811 Value *ValueOnZero = TrueVal; 812 if (Pred == ICmpInst::ICMP_NE) 813 std::swap(Count, ValueOnZero); 814 815 // Skip zero extend/truncate. 816 Value *V = nullptr; 817 if (match(Count, m_ZExt(m_Value(V))) || 818 match(Count, m_Trunc(m_Value(V)))) 819 Count = V; 820 821 // Check that 'Count' is a call to intrinsic cttz/ctlz. Also check that the 822 // input to the cttz/ctlz is used as LHS for the compare instruction. 823 if (!match(Count, m_Intrinsic<Intrinsic::cttz>(m_Specific(CmpLHS))) && 824 !match(Count, m_Intrinsic<Intrinsic::ctlz>(m_Specific(CmpLHS)))) 825 return nullptr; 826 827 IntrinsicInst *II = cast<IntrinsicInst>(Count); 828 829 // Check if the value propagated on zero is a constant number equal to the 830 // sizeof in bits of 'Count'. 831 unsigned SizeOfInBits = Count->getType()->getScalarSizeInBits(); 832 if (match(ValueOnZero, m_SpecificInt(SizeOfInBits))) { 833 // Explicitly clear the 'undef_on_zero' flag. 834 IntrinsicInst *NewI = cast<IntrinsicInst>(II->clone()); 835 NewI->setArgOperand(1, ConstantInt::getFalse(NewI->getContext())); 836 Builder.Insert(NewI); 837 return Builder.CreateZExtOrTrunc(NewI, ValueOnZero->getType()); 838 } 839 840 // If the ValueOnZero is not the bitwidth, we can at least make use of the 841 // fact that the cttz/ctlz result will not be used if the input is zero, so 842 // it's okay to relax it to undef for that case. 843 if (II->hasOneUse() && !match(II->getArgOperand(1), m_One())) 844 II->setArgOperand(1, ConstantInt::getTrue(II->getContext())); 845 846 return nullptr; 847 } 848 849 /// Return true if we find and adjust an icmp+select pattern where the compare 850 /// is with a constant that can be incremented or decremented to match the 851 /// minimum or maximum idiom. 852 static bool adjustMinMax(SelectInst &Sel, ICmpInst &Cmp) { 853 ICmpInst::Predicate Pred = Cmp.getPredicate(); 854 Value *CmpLHS = Cmp.getOperand(0); 855 Value *CmpRHS = Cmp.getOperand(1); 856 Value *TrueVal = Sel.getTrueValue(); 857 Value *FalseVal = Sel.getFalseValue(); 858 859 // We may move or edit the compare, so make sure the select is the only user. 860 const APInt *CmpC; 861 if (!Cmp.hasOneUse() || !match(CmpRHS, m_APInt(CmpC))) 862 return false; 863 864 // These transforms only work for selects of integers or vector selects of 865 // integer vectors. 866 Type *SelTy = Sel.getType(); 867 auto *SelEltTy = dyn_cast<IntegerType>(SelTy->getScalarType()); 868 if (!SelEltTy || SelTy->isVectorTy() != Cmp.getType()->isVectorTy()) 869 return false; 870 871 Constant *AdjustedRHS; 872 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_SGT) 873 AdjustedRHS = ConstantInt::get(CmpRHS->getType(), *CmpC + 1); 874 else if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT) 875 AdjustedRHS = ConstantInt::get(CmpRHS->getType(), *CmpC - 1); 876 else 877 return false; 878 879 // X > C ? X : C+1 --> X < C+1 ? C+1 : X 880 // X < C ? X : C-1 --> X > C-1 ? C-1 : X 881 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) || 882 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) { 883 ; // Nothing to do here. Values match without any sign/zero extension. 884 } 885 // Types do not match. Instead of calculating this with mixed types, promote 886 // all to the larger type. This enables scalar evolution to analyze this 887 // expression. 888 else if (CmpRHS->getType()->getScalarSizeInBits() < SelEltTy->getBitWidth()) { 889 Constant *SextRHS = ConstantExpr::getSExt(AdjustedRHS, SelTy); 890 891 // X = sext x; x >s c ? X : C+1 --> X = sext x; X <s C+1 ? C+1 : X 892 // X = sext x; x <s c ? X : C-1 --> X = sext x; X >s C-1 ? C-1 : X 893 // X = sext x; x >u c ? X : C+1 --> X = sext x; X <u C+1 ? C+1 : X 894 // X = sext x; x <u c ? X : C-1 --> X = sext x; X >u C-1 ? C-1 : X 895 if (match(TrueVal, m_SExt(m_Specific(CmpLHS))) && SextRHS == FalseVal) { 896 CmpLHS = TrueVal; 897 AdjustedRHS = SextRHS; 898 } else if (match(FalseVal, m_SExt(m_Specific(CmpLHS))) && 899 SextRHS == TrueVal) { 900 CmpLHS = FalseVal; 901 AdjustedRHS = SextRHS; 902 } else if (Cmp.isUnsigned()) { 903 Constant *ZextRHS = ConstantExpr::getZExt(AdjustedRHS, SelTy); 904 // X = zext x; x >u c ? X : C+1 --> X = zext x; X <u C+1 ? C+1 : X 905 // X = zext x; x <u c ? X : C-1 --> X = zext x; X >u C-1 ? C-1 : X 906 // zext + signed compare cannot be changed: 907 // 0xff <s 0x00, but 0x00ff >s 0x0000 908 if (match(TrueVal, m_ZExt(m_Specific(CmpLHS))) && ZextRHS == FalseVal) { 909 CmpLHS = TrueVal; 910 AdjustedRHS = ZextRHS; 911 } else if (match(FalseVal, m_ZExt(m_Specific(CmpLHS))) && 912 ZextRHS == TrueVal) { 913 CmpLHS = FalseVal; 914 AdjustedRHS = ZextRHS; 915 } else { 916 return false; 917 } 918 } else { 919 return false; 920 } 921 } else { 922 return false; 923 } 924 925 Pred = ICmpInst::getSwappedPredicate(Pred); 926 CmpRHS = AdjustedRHS; 927 std::swap(FalseVal, TrueVal); 928 Cmp.setPredicate(Pred); 929 Cmp.setOperand(0, CmpLHS); 930 Cmp.setOperand(1, CmpRHS); 931 Sel.setOperand(1, TrueVal); 932 Sel.setOperand(2, FalseVal); 933 Sel.swapProfMetadata(); 934 935 // Move the compare instruction right before the select instruction. Otherwise 936 // the sext/zext value may be defined after the compare instruction uses it. 937 Cmp.moveBefore(&Sel); 938 939 return true; 940 } 941 942 /// If this is an integer min/max (icmp + select) with a constant operand, 943 /// create the canonical icmp for the min/max operation and canonicalize the 944 /// constant to the 'false' operand of the select: 945 /// select (icmp Pred X, C1), C2, X --> select (icmp Pred' X, C2), X, C2 946 /// Note: if C1 != C2, this will change the icmp constant to the existing 947 /// constant operand of the select. 948 static Instruction * 949 canonicalizeMinMaxWithConstant(SelectInst &Sel, ICmpInst &Cmp, 950 InstCombiner::BuilderTy &Builder) { 951 if (!Cmp.hasOneUse() || !isa<Constant>(Cmp.getOperand(1))) 952 return nullptr; 953 954 // Canonicalize the compare predicate based on whether we have min or max. 955 Value *LHS, *RHS; 956 SelectPatternResult SPR = matchSelectPattern(&Sel, LHS, RHS); 957 if (!SelectPatternResult::isMinOrMax(SPR.Flavor)) 958 return nullptr; 959 960 // Is this already canonical? 961 ICmpInst::Predicate CanonicalPred = getMinMaxPred(SPR.Flavor); 962 if (Cmp.getOperand(0) == LHS && Cmp.getOperand(1) == RHS && 963 Cmp.getPredicate() == CanonicalPred) 964 return nullptr; 965 966 // Create the canonical compare and plug it into the select. 967 Sel.setCondition(Builder.CreateICmp(CanonicalPred, LHS, RHS)); 968 969 // If the select operands did not change, we're done. 970 if (Sel.getTrueValue() == LHS && Sel.getFalseValue() == RHS) 971 return &Sel; 972 973 // If we are swapping the select operands, swap the metadata too. 974 assert(Sel.getTrueValue() == RHS && Sel.getFalseValue() == LHS && 975 "Unexpected results from matchSelectPattern"); 976 Sel.swapValues(); 977 Sel.swapProfMetadata(); 978 return &Sel; 979 } 980 981 /// There are many select variants for each of ABS/NABS. 982 /// In matchSelectPattern(), there are different compare constants, compare 983 /// predicates/operands and select operands. 984 /// In isKnownNegation(), there are different formats of negated operands. 985 /// Canonicalize all these variants to 1 pattern. 986 /// This makes CSE more likely. 987 static Instruction *canonicalizeAbsNabs(SelectInst &Sel, ICmpInst &Cmp, 988 InstCombiner::BuilderTy &Builder) { 989 if (!Cmp.hasOneUse() || !isa<Constant>(Cmp.getOperand(1))) 990 return nullptr; 991 992 // Choose a sign-bit check for the compare (likely simpler for codegen). 993 // ABS: (X <s 0) ? -X : X 994 // NABS: (X <s 0) ? X : -X 995 Value *LHS, *RHS; 996 SelectPatternFlavor SPF = matchSelectPattern(&Sel, LHS, RHS).Flavor; 997 if (SPF != SelectPatternFlavor::SPF_ABS && 998 SPF != SelectPatternFlavor::SPF_NABS) 999 return nullptr; 1000 1001 Value *TVal = Sel.getTrueValue(); 1002 Value *FVal = Sel.getFalseValue(); 1003 assert(isKnownNegation(TVal, FVal) && 1004 "Unexpected result from matchSelectPattern"); 1005 1006 // The compare may use the negated abs()/nabs() operand, or it may use 1007 // negation in non-canonical form such as: sub A, B. 1008 bool CmpUsesNegatedOp = match(Cmp.getOperand(0), m_Neg(m_Specific(TVal))) || 1009 match(Cmp.getOperand(0), m_Neg(m_Specific(FVal))); 1010 1011 bool CmpCanonicalized = !CmpUsesNegatedOp && 1012 match(Cmp.getOperand(1), m_ZeroInt()) && 1013 Cmp.getPredicate() == ICmpInst::ICMP_SLT; 1014 bool RHSCanonicalized = match(RHS, m_Neg(m_Specific(LHS))); 1015 1016 // Is this already canonical? 1017 if (CmpCanonicalized && RHSCanonicalized) 1018 return nullptr; 1019 1020 // If RHS is used by other instructions except compare and select, don't 1021 // canonicalize it to not increase the instruction count. 1022 if (!(RHS->hasOneUse() || (RHS->hasNUses(2) && CmpUsesNegatedOp))) 1023 return nullptr; 1024 1025 // Create the canonical compare: icmp slt LHS 0. 1026 if (!CmpCanonicalized) { 1027 Cmp.setPredicate(ICmpInst::ICMP_SLT); 1028 Cmp.setOperand(1, ConstantInt::getNullValue(Cmp.getOperand(0)->getType())); 1029 if (CmpUsesNegatedOp) 1030 Cmp.setOperand(0, LHS); 1031 } 1032 1033 // Create the canonical RHS: RHS = sub (0, LHS). 1034 if (!RHSCanonicalized) { 1035 assert(RHS->hasOneUse() && "RHS use number is not right"); 1036 RHS = Builder.CreateNeg(LHS); 1037 if (TVal == LHS) { 1038 Sel.setFalseValue(RHS); 1039 FVal = RHS; 1040 } else { 1041 Sel.setTrueValue(RHS); 1042 TVal = RHS; 1043 } 1044 } 1045 1046 // If the select operands do not change, we're done. 1047 if (SPF == SelectPatternFlavor::SPF_NABS) { 1048 if (TVal == LHS) 1049 return &Sel; 1050 assert(FVal == LHS && "Unexpected results from matchSelectPattern"); 1051 } else { 1052 if (FVal == LHS) 1053 return &Sel; 1054 assert(TVal == LHS && "Unexpected results from matchSelectPattern"); 1055 } 1056 1057 // We are swapping the select operands, so swap the metadata too. 1058 Sel.swapValues(); 1059 Sel.swapProfMetadata(); 1060 return &Sel; 1061 } 1062 1063 static Value *simplifyWithOpReplaced(Value *V, Value *Op, Value *ReplaceOp, 1064 const SimplifyQuery &Q) { 1065 // If this is a binary operator, try to simplify it with the replaced op 1066 // because we know Op and ReplaceOp are equivalant. 1067 // For example: V = X + 1, Op = X, ReplaceOp = 42 1068 // Simplifies as: add(42, 1) --> 43 1069 if (auto *BO = dyn_cast<BinaryOperator>(V)) { 1070 if (BO->getOperand(0) == Op) 1071 return SimplifyBinOp(BO->getOpcode(), ReplaceOp, BO->getOperand(1), Q); 1072 if (BO->getOperand(1) == Op) 1073 return SimplifyBinOp(BO->getOpcode(), BO->getOperand(0), ReplaceOp, Q); 1074 } 1075 1076 return nullptr; 1077 } 1078 1079 /// If we have a select with an equality comparison, then we know the value in 1080 /// one of the arms of the select. See if substituting this value into an arm 1081 /// and simplifying the result yields the same value as the other arm. 1082 /// 1083 /// To make this transform safe, we must drop poison-generating flags 1084 /// (nsw, etc) if we simplified to a binop because the select may be guarding 1085 /// that poison from propagating. If the existing binop already had no 1086 /// poison-generating flags, then this transform can be done by instsimplify. 1087 /// 1088 /// Consider: 1089 /// %cmp = icmp eq i32 %x, 2147483647 1090 /// %add = add nsw i32 %x, 1 1091 /// %sel = select i1 %cmp, i32 -2147483648, i32 %add 1092 /// 1093 /// We can't replace %sel with %add unless we strip away the flags. 1094 static Value *foldSelectValueEquivalence(SelectInst &Sel, ICmpInst &Cmp, 1095 const SimplifyQuery &Q) { 1096 if (!Cmp.isEquality()) 1097 return nullptr; 1098 1099 // Canonicalize the pattern to ICMP_EQ by swapping the select operands. 1100 Value *TrueVal = Sel.getTrueValue(), *FalseVal = Sel.getFalseValue(); 1101 if (Cmp.getPredicate() == ICmpInst::ICMP_NE) 1102 std::swap(TrueVal, FalseVal); 1103 1104 // Try each equivalence substitution possibility. 1105 // We have an 'EQ' comparison, so the select's false value will propagate. 1106 // Example: 1107 // (X == 42) ? 43 : (X + 1) --> (X == 42) ? (X + 1) : (X + 1) --> X + 1 1108 // (X == 42) ? (X + 1) : 43 --> (X == 42) ? (42 + 1) : 43 --> 43 1109 Value *CmpLHS = Cmp.getOperand(0), *CmpRHS = Cmp.getOperand(1); 1110 if (simplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, Q) == TrueVal || 1111 simplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, Q) == TrueVal || 1112 simplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, Q) == FalseVal || 1113 simplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, Q) == FalseVal) { 1114 if (auto *FalseInst = dyn_cast<Instruction>(FalseVal)) 1115 FalseInst->dropPoisonGeneratingFlags(); 1116 return FalseVal; 1117 } 1118 return nullptr; 1119 } 1120 1121 /// Visit a SelectInst that has an ICmpInst as its first operand. 1122 Instruction *InstCombiner::foldSelectInstWithICmp(SelectInst &SI, 1123 ICmpInst *ICI) { 1124 if (Value *V = foldSelectValueEquivalence(SI, *ICI, SQ)) 1125 return replaceInstUsesWith(SI, V); 1126 1127 if (Instruction *NewSel = canonicalizeMinMaxWithConstant(SI, *ICI, Builder)) 1128 return NewSel; 1129 1130 if (Instruction *NewAbs = canonicalizeAbsNabs(SI, *ICI, Builder)) 1131 return NewAbs; 1132 1133 bool Changed = adjustMinMax(SI, *ICI); 1134 1135 if (Value *V = foldSelectICmpAnd(SI, ICI, Builder)) 1136 return replaceInstUsesWith(SI, V); 1137 1138 // NOTE: if we wanted to, this is where to detect integer MIN/MAX 1139 Value *TrueVal = SI.getTrueValue(); 1140 Value *FalseVal = SI.getFalseValue(); 1141 ICmpInst::Predicate Pred = ICI->getPredicate(); 1142 Value *CmpLHS = ICI->getOperand(0); 1143 Value *CmpRHS = ICI->getOperand(1); 1144 if (CmpRHS != CmpLHS && isa<Constant>(CmpRHS)) { 1145 if (CmpLHS == TrueVal && Pred == ICmpInst::ICMP_EQ) { 1146 // Transform (X == C) ? X : Y -> (X == C) ? C : Y 1147 SI.setOperand(1, CmpRHS); 1148 Changed = true; 1149 } else if (CmpLHS == FalseVal && Pred == ICmpInst::ICMP_NE) { 1150 // Transform (X != C) ? Y : X -> (X != C) ? Y : C 1151 SI.setOperand(2, CmpRHS); 1152 Changed = true; 1153 } 1154 } 1155 1156 // FIXME: This code is nearly duplicated in InstSimplify. Using/refactoring 1157 // decomposeBitTestICmp() might help. 1158 { 1159 unsigned BitWidth = 1160 DL.getTypeSizeInBits(TrueVal->getType()->getScalarType()); 1161 APInt MinSignedValue = APInt::getSignedMinValue(BitWidth); 1162 Value *X; 1163 const APInt *Y, *C; 1164 bool TrueWhenUnset; 1165 bool IsBitTest = false; 1166 if (ICmpInst::isEquality(Pred) && 1167 match(CmpLHS, m_And(m_Value(X), m_Power2(Y))) && 1168 match(CmpRHS, m_Zero())) { 1169 IsBitTest = true; 1170 TrueWhenUnset = Pred == ICmpInst::ICMP_EQ; 1171 } else if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, m_Zero())) { 1172 X = CmpLHS; 1173 Y = &MinSignedValue; 1174 IsBitTest = true; 1175 TrueWhenUnset = false; 1176 } else if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, m_AllOnes())) { 1177 X = CmpLHS; 1178 Y = &MinSignedValue; 1179 IsBitTest = true; 1180 TrueWhenUnset = true; 1181 } 1182 if (IsBitTest) { 1183 Value *V = nullptr; 1184 // (X & Y) == 0 ? X : X ^ Y --> X & ~Y 1185 if (TrueWhenUnset && TrueVal == X && 1186 match(FalseVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C) 1187 V = Builder.CreateAnd(X, ~(*Y)); 1188 // (X & Y) != 0 ? X ^ Y : X --> X & ~Y 1189 else if (!TrueWhenUnset && FalseVal == X && 1190 match(TrueVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C) 1191 V = Builder.CreateAnd(X, ~(*Y)); 1192 // (X & Y) == 0 ? X ^ Y : X --> X | Y 1193 else if (TrueWhenUnset && FalseVal == X && 1194 match(TrueVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C) 1195 V = Builder.CreateOr(X, *Y); 1196 // (X & Y) != 0 ? X : X ^ Y --> X | Y 1197 else if (!TrueWhenUnset && TrueVal == X && 1198 match(FalseVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C) 1199 V = Builder.CreateOr(X, *Y); 1200 1201 if (V) 1202 return replaceInstUsesWith(SI, V); 1203 } 1204 } 1205 1206 if (Instruction *V = 1207 foldSelectICmpAndAnd(SI.getType(), ICI, TrueVal, FalseVal, Builder)) 1208 return V; 1209 1210 if (Value *V = foldSelectICmpAndOr(ICI, TrueVal, FalseVal, Builder)) 1211 return replaceInstUsesWith(SI, V); 1212 1213 if (Value *V = foldSelectICmpLshrAshr(ICI, TrueVal, FalseVal, Builder)) 1214 return replaceInstUsesWith(SI, V); 1215 1216 if (Value *V = foldSelectCttzCtlz(ICI, TrueVal, FalseVal, Builder)) 1217 return replaceInstUsesWith(SI, V); 1218 1219 if (Value *V = canonicalizeSaturatedSubtract(ICI, TrueVal, FalseVal, Builder)) 1220 return replaceInstUsesWith(SI, V); 1221 1222 if (Value *V = canonicalizeSaturatedAdd(ICI, TrueVal, FalseVal, Builder)) 1223 return replaceInstUsesWith(SI, V); 1224 1225 return Changed ? &SI : nullptr; 1226 } 1227 1228 /// SI is a select whose condition is a PHI node (but the two may be in 1229 /// different blocks). See if the true/false values (V) are live in all of the 1230 /// predecessor blocks of the PHI. For example, cases like this can't be mapped: 1231 /// 1232 /// X = phi [ C1, BB1], [C2, BB2] 1233 /// Y = add 1234 /// Z = select X, Y, 0 1235 /// 1236 /// because Y is not live in BB1/BB2. 1237 static bool canSelectOperandBeMappingIntoPredBlock(const Value *V, 1238 const SelectInst &SI) { 1239 // If the value is a non-instruction value like a constant or argument, it 1240 // can always be mapped. 1241 const Instruction *I = dyn_cast<Instruction>(V); 1242 if (!I) return true; 1243 1244 // If V is a PHI node defined in the same block as the condition PHI, we can 1245 // map the arguments. 1246 const PHINode *CondPHI = cast<PHINode>(SI.getCondition()); 1247 1248 if (const PHINode *VP = dyn_cast<PHINode>(I)) 1249 if (VP->getParent() == CondPHI->getParent()) 1250 return true; 1251 1252 // Otherwise, if the PHI and select are defined in the same block and if V is 1253 // defined in a different block, then we can transform it. 1254 if (SI.getParent() == CondPHI->getParent() && 1255 I->getParent() != CondPHI->getParent()) 1256 return true; 1257 1258 // Otherwise we have a 'hard' case and we can't tell without doing more 1259 // detailed dominator based analysis, punt. 1260 return false; 1261 } 1262 1263 /// We have an SPF (e.g. a min or max) of an SPF of the form: 1264 /// SPF2(SPF1(A, B), C) 1265 Instruction *InstCombiner::foldSPFofSPF(Instruction *Inner, 1266 SelectPatternFlavor SPF1, 1267 Value *A, Value *B, 1268 Instruction &Outer, 1269 SelectPatternFlavor SPF2, Value *C) { 1270 if (Outer.getType() != Inner->getType()) 1271 return nullptr; 1272 1273 if (C == A || C == B) { 1274 // MAX(MAX(A, B), B) -> MAX(A, B) 1275 // MIN(MIN(a, b), a) -> MIN(a, b) 1276 // TODO: This could be done in instsimplify. 1277 if (SPF1 == SPF2 && SelectPatternResult::isMinOrMax(SPF1)) 1278 return replaceInstUsesWith(Outer, Inner); 1279 1280 // MAX(MIN(a, b), a) -> a 1281 // MIN(MAX(a, b), a) -> a 1282 // TODO: This could be done in instsimplify. 1283 if ((SPF1 == SPF_SMIN && SPF2 == SPF_SMAX) || 1284 (SPF1 == SPF_SMAX && SPF2 == SPF_SMIN) || 1285 (SPF1 == SPF_UMIN && SPF2 == SPF_UMAX) || 1286 (SPF1 == SPF_UMAX && SPF2 == SPF_UMIN)) 1287 return replaceInstUsesWith(Outer, C); 1288 } 1289 1290 if (SPF1 == SPF2) { 1291 const APInt *CB, *CC; 1292 if (match(B, m_APInt(CB)) && match(C, m_APInt(CC))) { 1293 // MIN(MIN(A, 23), 97) -> MIN(A, 23) 1294 // MAX(MAX(A, 97), 23) -> MAX(A, 97) 1295 // TODO: This could be done in instsimplify. 1296 if ((SPF1 == SPF_UMIN && CB->ule(*CC)) || 1297 (SPF1 == SPF_SMIN && CB->sle(*CC)) || 1298 (SPF1 == SPF_UMAX && CB->uge(*CC)) || 1299 (SPF1 == SPF_SMAX && CB->sge(*CC))) 1300 return replaceInstUsesWith(Outer, Inner); 1301 1302 // MIN(MIN(A, 97), 23) -> MIN(A, 23) 1303 // MAX(MAX(A, 23), 97) -> MAX(A, 97) 1304 if ((SPF1 == SPF_UMIN && CB->ugt(*CC)) || 1305 (SPF1 == SPF_SMIN && CB->sgt(*CC)) || 1306 (SPF1 == SPF_UMAX && CB->ult(*CC)) || 1307 (SPF1 == SPF_SMAX && CB->slt(*CC))) { 1308 Outer.replaceUsesOfWith(Inner, A); 1309 return &Outer; 1310 } 1311 } 1312 } 1313 1314 // ABS(ABS(X)) -> ABS(X) 1315 // NABS(NABS(X)) -> NABS(X) 1316 // TODO: This could be done in instsimplify. 1317 if (SPF1 == SPF2 && (SPF1 == SPF_ABS || SPF1 == SPF_NABS)) { 1318 return replaceInstUsesWith(Outer, Inner); 1319 } 1320 1321 // ABS(NABS(X)) -> ABS(X) 1322 // NABS(ABS(X)) -> NABS(X) 1323 if ((SPF1 == SPF_ABS && SPF2 == SPF_NABS) || 1324 (SPF1 == SPF_NABS && SPF2 == SPF_ABS)) { 1325 SelectInst *SI = cast<SelectInst>(Inner); 1326 Value *NewSI = 1327 Builder.CreateSelect(SI->getCondition(), SI->getFalseValue(), 1328 SI->getTrueValue(), SI->getName(), SI); 1329 return replaceInstUsesWith(Outer, NewSI); 1330 } 1331 1332 auto IsFreeOrProfitableToInvert = 1333 [&](Value *V, Value *&NotV, bool &ElidesXor) { 1334 if (match(V, m_Not(m_Value(NotV)))) { 1335 // If V has at most 2 uses then we can get rid of the xor operation 1336 // entirely. 1337 ElidesXor |= !V->hasNUsesOrMore(3); 1338 return true; 1339 } 1340 1341 if (IsFreeToInvert(V, !V->hasNUsesOrMore(3))) { 1342 NotV = nullptr; 1343 return true; 1344 } 1345 1346 return false; 1347 }; 1348 1349 Value *NotA, *NotB, *NotC; 1350 bool ElidesXor = false; 1351 1352 // MIN(MIN(~A, ~B), ~C) == ~MAX(MAX(A, B), C) 1353 // MIN(MAX(~A, ~B), ~C) == ~MAX(MIN(A, B), C) 1354 // MAX(MIN(~A, ~B), ~C) == ~MIN(MAX(A, B), C) 1355 // MAX(MAX(~A, ~B), ~C) == ~MIN(MIN(A, B), C) 1356 // 1357 // This transform is performance neutral if we can elide at least one xor from 1358 // the set of three operands, since we'll be tacking on an xor at the very 1359 // end. 1360 if (SelectPatternResult::isMinOrMax(SPF1) && 1361 SelectPatternResult::isMinOrMax(SPF2) && 1362 IsFreeOrProfitableToInvert(A, NotA, ElidesXor) && 1363 IsFreeOrProfitableToInvert(B, NotB, ElidesXor) && 1364 IsFreeOrProfitableToInvert(C, NotC, ElidesXor) && ElidesXor) { 1365 if (!NotA) 1366 NotA = Builder.CreateNot(A); 1367 if (!NotB) 1368 NotB = Builder.CreateNot(B); 1369 if (!NotC) 1370 NotC = Builder.CreateNot(C); 1371 1372 Value *NewInner = createMinMax(Builder, getInverseMinMaxFlavor(SPF1), NotA, 1373 NotB); 1374 Value *NewOuter = Builder.CreateNot( 1375 createMinMax(Builder, getInverseMinMaxFlavor(SPF2), NewInner, NotC)); 1376 return replaceInstUsesWith(Outer, NewOuter); 1377 } 1378 1379 return nullptr; 1380 } 1381 1382 /// Turn select C, (X + Y), (X - Y) --> (X + (select C, Y, (-Y))). 1383 /// This is even legal for FP. 1384 static Instruction *foldAddSubSelect(SelectInst &SI, 1385 InstCombiner::BuilderTy &Builder) { 1386 Value *CondVal = SI.getCondition(); 1387 Value *TrueVal = SI.getTrueValue(); 1388 Value *FalseVal = SI.getFalseValue(); 1389 auto *TI = dyn_cast<Instruction>(TrueVal); 1390 auto *FI = dyn_cast<Instruction>(FalseVal); 1391 if (!TI || !FI || !TI->hasOneUse() || !FI->hasOneUse()) 1392 return nullptr; 1393 1394 Instruction *AddOp = nullptr, *SubOp = nullptr; 1395 if ((TI->getOpcode() == Instruction::Sub && 1396 FI->getOpcode() == Instruction::Add) || 1397 (TI->getOpcode() == Instruction::FSub && 1398 FI->getOpcode() == Instruction::FAdd)) { 1399 AddOp = FI; 1400 SubOp = TI; 1401 } else if ((FI->getOpcode() == Instruction::Sub && 1402 TI->getOpcode() == Instruction::Add) || 1403 (FI->getOpcode() == Instruction::FSub && 1404 TI->getOpcode() == Instruction::FAdd)) { 1405 AddOp = TI; 1406 SubOp = FI; 1407 } 1408 1409 if (AddOp) { 1410 Value *OtherAddOp = nullptr; 1411 if (SubOp->getOperand(0) == AddOp->getOperand(0)) { 1412 OtherAddOp = AddOp->getOperand(1); 1413 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) { 1414 OtherAddOp = AddOp->getOperand(0); 1415 } 1416 1417 if (OtherAddOp) { 1418 // So at this point we know we have (Y -> OtherAddOp): 1419 // select C, (add X, Y), (sub X, Z) 1420 Value *NegVal; // Compute -Z 1421 if (SI.getType()->isFPOrFPVectorTy()) { 1422 NegVal = Builder.CreateFNeg(SubOp->getOperand(1)); 1423 if (Instruction *NegInst = dyn_cast<Instruction>(NegVal)) { 1424 FastMathFlags Flags = AddOp->getFastMathFlags(); 1425 Flags &= SubOp->getFastMathFlags(); 1426 NegInst->setFastMathFlags(Flags); 1427 } 1428 } else { 1429 NegVal = Builder.CreateNeg(SubOp->getOperand(1)); 1430 } 1431 1432 Value *NewTrueOp = OtherAddOp; 1433 Value *NewFalseOp = NegVal; 1434 if (AddOp != TI) 1435 std::swap(NewTrueOp, NewFalseOp); 1436 Value *NewSel = Builder.CreateSelect(CondVal, NewTrueOp, NewFalseOp, 1437 SI.getName() + ".p", &SI); 1438 1439 if (SI.getType()->isFPOrFPVectorTy()) { 1440 Instruction *RI = 1441 BinaryOperator::CreateFAdd(SubOp->getOperand(0), NewSel); 1442 1443 FastMathFlags Flags = AddOp->getFastMathFlags(); 1444 Flags &= SubOp->getFastMathFlags(); 1445 RI->setFastMathFlags(Flags); 1446 return RI; 1447 } else 1448 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel); 1449 } 1450 } 1451 return nullptr; 1452 } 1453 1454 Instruction *InstCombiner::foldSelectExtConst(SelectInst &Sel) { 1455 Constant *C; 1456 if (!match(Sel.getTrueValue(), m_Constant(C)) && 1457 !match(Sel.getFalseValue(), m_Constant(C))) 1458 return nullptr; 1459 1460 Instruction *ExtInst; 1461 if (!match(Sel.getTrueValue(), m_Instruction(ExtInst)) && 1462 !match(Sel.getFalseValue(), m_Instruction(ExtInst))) 1463 return nullptr; 1464 1465 auto ExtOpcode = ExtInst->getOpcode(); 1466 if (ExtOpcode != Instruction::ZExt && ExtOpcode != Instruction::SExt) 1467 return nullptr; 1468 1469 // If we are extending from a boolean type or if we can create a select that 1470 // has the same size operands as its condition, try to narrow the select. 1471 Value *X = ExtInst->getOperand(0); 1472 Type *SmallType = X->getType(); 1473 Value *Cond = Sel.getCondition(); 1474 auto *Cmp = dyn_cast<CmpInst>(Cond); 1475 if (!SmallType->isIntOrIntVectorTy(1) && 1476 (!Cmp || Cmp->getOperand(0)->getType() != SmallType)) 1477 return nullptr; 1478 1479 // If the constant is the same after truncation to the smaller type and 1480 // extension to the original type, we can narrow the select. 1481 Type *SelType = Sel.getType(); 1482 Constant *TruncC = ConstantExpr::getTrunc(C, SmallType); 1483 Constant *ExtC = ConstantExpr::getCast(ExtOpcode, TruncC, SelType); 1484 if (ExtC == C) { 1485 Value *TruncCVal = cast<Value>(TruncC); 1486 if (ExtInst == Sel.getFalseValue()) 1487 std::swap(X, TruncCVal); 1488 1489 // select Cond, (ext X), C --> ext(select Cond, X, C') 1490 // select Cond, C, (ext X) --> ext(select Cond, C', X) 1491 Value *NewSel = Builder.CreateSelect(Cond, X, TruncCVal, "narrow", &Sel); 1492 return CastInst::Create(Instruction::CastOps(ExtOpcode), NewSel, SelType); 1493 } 1494 1495 // If one arm of the select is the extend of the condition, replace that arm 1496 // with the extension of the appropriate known bool value. 1497 if (Cond == X) { 1498 if (ExtInst == Sel.getTrueValue()) { 1499 // select X, (sext X), C --> select X, -1, C 1500 // select X, (zext X), C --> select X, 1, C 1501 Constant *One = ConstantInt::getTrue(SmallType); 1502 Constant *AllOnesOrOne = ConstantExpr::getCast(ExtOpcode, One, SelType); 1503 return SelectInst::Create(Cond, AllOnesOrOne, C, "", nullptr, &Sel); 1504 } else { 1505 // select X, C, (sext X) --> select X, C, 0 1506 // select X, C, (zext X) --> select X, C, 0 1507 Constant *Zero = ConstantInt::getNullValue(SelType); 1508 return SelectInst::Create(Cond, C, Zero, "", nullptr, &Sel); 1509 } 1510 } 1511 1512 return nullptr; 1513 } 1514 1515 /// Try to transform a vector select with a constant condition vector into a 1516 /// shuffle for easier combining with other shuffles and insert/extract. 1517 static Instruction *canonicalizeSelectToShuffle(SelectInst &SI) { 1518 Value *CondVal = SI.getCondition(); 1519 Constant *CondC; 1520 if (!CondVal->getType()->isVectorTy() || !match(CondVal, m_Constant(CondC))) 1521 return nullptr; 1522 1523 unsigned NumElts = CondVal->getType()->getVectorNumElements(); 1524 SmallVector<Constant *, 16> Mask; 1525 Mask.reserve(NumElts); 1526 Type *Int32Ty = Type::getInt32Ty(CondVal->getContext()); 1527 for (unsigned i = 0; i != NumElts; ++i) { 1528 Constant *Elt = CondC->getAggregateElement(i); 1529 if (!Elt) 1530 return nullptr; 1531 1532 if (Elt->isOneValue()) { 1533 // If the select condition element is true, choose from the 1st vector. 1534 Mask.push_back(ConstantInt::get(Int32Ty, i)); 1535 } else if (Elt->isNullValue()) { 1536 // If the select condition element is false, choose from the 2nd vector. 1537 Mask.push_back(ConstantInt::get(Int32Ty, i + NumElts)); 1538 } else if (isa<UndefValue>(Elt)) { 1539 // Undef in a select condition (choose one of the operands) does not mean 1540 // the same thing as undef in a shuffle mask (any value is acceptable), so 1541 // give up. 1542 return nullptr; 1543 } else { 1544 // Bail out on a constant expression. 1545 return nullptr; 1546 } 1547 } 1548 1549 return new ShuffleVectorInst(SI.getTrueValue(), SI.getFalseValue(), 1550 ConstantVector::get(Mask)); 1551 } 1552 1553 /// Reuse bitcasted operands between a compare and select: 1554 /// select (cmp (bitcast C), (bitcast D)), (bitcast' C), (bitcast' D) --> 1555 /// bitcast (select (cmp (bitcast C), (bitcast D)), (bitcast C), (bitcast D)) 1556 static Instruction *foldSelectCmpBitcasts(SelectInst &Sel, 1557 InstCombiner::BuilderTy &Builder) { 1558 Value *Cond = Sel.getCondition(); 1559 Value *TVal = Sel.getTrueValue(); 1560 Value *FVal = Sel.getFalseValue(); 1561 1562 CmpInst::Predicate Pred; 1563 Value *A, *B; 1564 if (!match(Cond, m_Cmp(Pred, m_Value(A), m_Value(B)))) 1565 return nullptr; 1566 1567 // The select condition is a compare instruction. If the select's true/false 1568 // values are already the same as the compare operands, there's nothing to do. 1569 if (TVal == A || TVal == B || FVal == A || FVal == B) 1570 return nullptr; 1571 1572 Value *C, *D; 1573 if (!match(A, m_BitCast(m_Value(C))) || !match(B, m_BitCast(m_Value(D)))) 1574 return nullptr; 1575 1576 // select (cmp (bitcast C), (bitcast D)), (bitcast TSrc), (bitcast FSrc) 1577 Value *TSrc, *FSrc; 1578 if (!match(TVal, m_BitCast(m_Value(TSrc))) || 1579 !match(FVal, m_BitCast(m_Value(FSrc)))) 1580 return nullptr; 1581 1582 // If the select true/false values are *different bitcasts* of the same source 1583 // operands, make the select operands the same as the compare operands and 1584 // cast the result. This is the canonical select form for min/max. 1585 Value *NewSel; 1586 if (TSrc == C && FSrc == D) { 1587 // select (cmp (bitcast C), (bitcast D)), (bitcast' C), (bitcast' D) --> 1588 // bitcast (select (cmp A, B), A, B) 1589 NewSel = Builder.CreateSelect(Cond, A, B, "", &Sel); 1590 } else if (TSrc == D && FSrc == C) { 1591 // select (cmp (bitcast C), (bitcast D)), (bitcast' D), (bitcast' C) --> 1592 // bitcast (select (cmp A, B), B, A) 1593 NewSel = Builder.CreateSelect(Cond, B, A, "", &Sel); 1594 } else { 1595 return nullptr; 1596 } 1597 return CastInst::CreateBitOrPointerCast(NewSel, Sel.getType()); 1598 } 1599 1600 /// Try to eliminate select instructions that test the returned flag of cmpxchg 1601 /// instructions. 1602 /// 1603 /// If a select instruction tests the returned flag of a cmpxchg instruction and 1604 /// selects between the returned value of the cmpxchg instruction its compare 1605 /// operand, the result of the select will always be equal to its false value. 1606 /// For example: 1607 /// 1608 /// %0 = cmpxchg i64* %ptr, i64 %compare, i64 %new_value seq_cst seq_cst 1609 /// %1 = extractvalue { i64, i1 } %0, 1 1610 /// %2 = extractvalue { i64, i1 } %0, 0 1611 /// %3 = select i1 %1, i64 %compare, i64 %2 1612 /// ret i64 %3 1613 /// 1614 /// The returned value of the cmpxchg instruction (%2) is the original value 1615 /// located at %ptr prior to any update. If the cmpxchg operation succeeds, %2 1616 /// must have been equal to %compare. Thus, the result of the select is always 1617 /// equal to %2, and the code can be simplified to: 1618 /// 1619 /// %0 = cmpxchg i64* %ptr, i64 %compare, i64 %new_value seq_cst seq_cst 1620 /// %1 = extractvalue { i64, i1 } %0, 0 1621 /// ret i64 %1 1622 /// 1623 static Instruction *foldSelectCmpXchg(SelectInst &SI) { 1624 // A helper that determines if V is an extractvalue instruction whose 1625 // aggregate operand is a cmpxchg instruction and whose single index is equal 1626 // to I. If such conditions are true, the helper returns the cmpxchg 1627 // instruction; otherwise, a nullptr is returned. 1628 auto isExtractFromCmpXchg = [](Value *V, unsigned I) -> AtomicCmpXchgInst * { 1629 auto *Extract = dyn_cast<ExtractValueInst>(V); 1630 if (!Extract) 1631 return nullptr; 1632 if (Extract->getIndices()[0] != I) 1633 return nullptr; 1634 return dyn_cast<AtomicCmpXchgInst>(Extract->getAggregateOperand()); 1635 }; 1636 1637 // If the select has a single user, and this user is a select instruction that 1638 // we can simplify, skip the cmpxchg simplification for now. 1639 if (SI.hasOneUse()) 1640 if (auto *Select = dyn_cast<SelectInst>(SI.user_back())) 1641 if (Select->getCondition() == SI.getCondition()) 1642 if (Select->getFalseValue() == SI.getTrueValue() || 1643 Select->getTrueValue() == SI.getFalseValue()) 1644 return nullptr; 1645 1646 // Ensure the select condition is the returned flag of a cmpxchg instruction. 1647 auto *CmpXchg = isExtractFromCmpXchg(SI.getCondition(), 1); 1648 if (!CmpXchg) 1649 return nullptr; 1650 1651 // Check the true value case: The true value of the select is the returned 1652 // value of the same cmpxchg used by the condition, and the false value is the 1653 // cmpxchg instruction's compare operand. 1654 if (auto *X = isExtractFromCmpXchg(SI.getTrueValue(), 0)) 1655 if (X == CmpXchg && X->getCompareOperand() == SI.getFalseValue()) { 1656 SI.setTrueValue(SI.getFalseValue()); 1657 return &SI; 1658 } 1659 1660 // Check the false value case: The false value of the select is the returned 1661 // value of the same cmpxchg used by the condition, and the true value is the 1662 // cmpxchg instruction's compare operand. 1663 if (auto *X = isExtractFromCmpXchg(SI.getFalseValue(), 0)) 1664 if (X == CmpXchg && X->getCompareOperand() == SI.getTrueValue()) { 1665 SI.setTrueValue(SI.getFalseValue()); 1666 return &SI; 1667 } 1668 1669 return nullptr; 1670 } 1671 1672 static Instruction *moveAddAfterMinMax(SelectPatternFlavor SPF, Value *X, 1673 Value *Y, 1674 InstCombiner::BuilderTy &Builder) { 1675 assert(SelectPatternResult::isMinOrMax(SPF) && "Expected min/max pattern"); 1676 bool IsUnsigned = SPF == SelectPatternFlavor::SPF_UMIN || 1677 SPF == SelectPatternFlavor::SPF_UMAX; 1678 // TODO: If InstSimplify could fold all cases where C2 <= C1, we could change 1679 // the constant value check to an assert. 1680 Value *A; 1681 const APInt *C1, *C2; 1682 if (IsUnsigned && match(X, m_NUWAdd(m_Value(A), m_APInt(C1))) && 1683 match(Y, m_APInt(C2)) && C2->uge(*C1) && X->hasNUses(2)) { 1684 // umin (add nuw A, C1), C2 --> add nuw (umin A, C2 - C1), C1 1685 // umax (add nuw A, C1), C2 --> add nuw (umax A, C2 - C1), C1 1686 Value *NewMinMax = createMinMax(Builder, SPF, A, 1687 ConstantInt::get(X->getType(), *C2 - *C1)); 1688 return BinaryOperator::CreateNUW(BinaryOperator::Add, NewMinMax, 1689 ConstantInt::get(X->getType(), *C1)); 1690 } 1691 1692 if (!IsUnsigned && match(X, m_NSWAdd(m_Value(A), m_APInt(C1))) && 1693 match(Y, m_APInt(C2)) && X->hasNUses(2)) { 1694 bool Overflow; 1695 APInt Diff = C2->ssub_ov(*C1, Overflow); 1696 if (!Overflow) { 1697 // smin (add nsw A, C1), C2 --> add nsw (smin A, C2 - C1), C1 1698 // smax (add nsw A, C1), C2 --> add nsw (smax A, C2 - C1), C1 1699 Value *NewMinMax = createMinMax(Builder, SPF, A, 1700 ConstantInt::get(X->getType(), Diff)); 1701 return BinaryOperator::CreateNSW(BinaryOperator::Add, NewMinMax, 1702 ConstantInt::get(X->getType(), *C1)); 1703 } 1704 } 1705 1706 return nullptr; 1707 } 1708 1709 /// Reduce a sequence of min/max with a common operand. 1710 static Instruction *factorizeMinMaxTree(SelectPatternFlavor SPF, Value *LHS, 1711 Value *RHS, 1712 InstCombiner::BuilderTy &Builder) { 1713 assert(SelectPatternResult::isMinOrMax(SPF) && "Expected a min/max"); 1714 // TODO: Allow FP min/max with nnan/nsz. 1715 if (!LHS->getType()->isIntOrIntVectorTy()) 1716 return nullptr; 1717 1718 // Match 3 of the same min/max ops. Example: umin(umin(), umin()). 1719 Value *A, *B, *C, *D; 1720 SelectPatternResult L = matchSelectPattern(LHS, A, B); 1721 SelectPatternResult R = matchSelectPattern(RHS, C, D); 1722 if (SPF != L.Flavor || L.Flavor != R.Flavor) 1723 return nullptr; 1724 1725 // Look for a common operand. The use checks are different than usual because 1726 // a min/max pattern typically has 2 uses of each op: 1 by the cmp and 1 by 1727 // the select. 1728 Value *MinMaxOp = nullptr; 1729 Value *ThirdOp = nullptr; 1730 if (!LHS->hasNUsesOrMore(3) && RHS->hasNUsesOrMore(3)) { 1731 // If the LHS is only used in this chain and the RHS is used outside of it, 1732 // reuse the RHS min/max because that will eliminate the LHS. 1733 if (D == A || C == A) { 1734 // min(min(a, b), min(c, a)) --> min(min(c, a), b) 1735 // min(min(a, b), min(a, d)) --> min(min(a, d), b) 1736 MinMaxOp = RHS; 1737 ThirdOp = B; 1738 } else if (D == B || C == B) { 1739 // min(min(a, b), min(c, b)) --> min(min(c, b), a) 1740 // min(min(a, b), min(b, d)) --> min(min(b, d), a) 1741 MinMaxOp = RHS; 1742 ThirdOp = A; 1743 } 1744 } else if (!RHS->hasNUsesOrMore(3)) { 1745 // Reuse the LHS. This will eliminate the RHS. 1746 if (D == A || D == B) { 1747 // min(min(a, b), min(c, a)) --> min(min(a, b), c) 1748 // min(min(a, b), min(c, b)) --> min(min(a, b), c) 1749 MinMaxOp = LHS; 1750 ThirdOp = C; 1751 } else if (C == A || C == B) { 1752 // min(min(a, b), min(b, d)) --> min(min(a, b), d) 1753 // min(min(a, b), min(c, b)) --> min(min(a, b), d) 1754 MinMaxOp = LHS; 1755 ThirdOp = D; 1756 } 1757 } 1758 if (!MinMaxOp || !ThirdOp) 1759 return nullptr; 1760 1761 CmpInst::Predicate P = getMinMaxPred(SPF); 1762 Value *CmpABC = Builder.CreateICmp(P, MinMaxOp, ThirdOp); 1763 return SelectInst::Create(CmpABC, MinMaxOp, ThirdOp); 1764 } 1765 1766 /// Try to reduce a rotate pattern that includes a compare and select into a 1767 /// funnel shift intrinsic. Example: 1768 /// rotl32(a, b) --> (b == 0 ? a : ((a >> (32 - b)) | (a << b))) 1769 /// --> call llvm.fshl.i32(a, a, b) 1770 static Instruction *foldSelectRotate(SelectInst &Sel) { 1771 // The false value of the select must be a rotate of the true value. 1772 Value *Or0, *Or1; 1773 if (!match(Sel.getFalseValue(), m_OneUse(m_Or(m_Value(Or0), m_Value(Or1))))) 1774 return nullptr; 1775 1776 Value *TVal = Sel.getTrueValue(); 1777 Value *SA0, *SA1; 1778 if (!match(Or0, m_OneUse(m_LogicalShift(m_Specific(TVal), m_Value(SA0)))) || 1779 !match(Or1, m_OneUse(m_LogicalShift(m_Specific(TVal), m_Value(SA1))))) 1780 return nullptr; 1781 1782 auto ShiftOpcode0 = cast<BinaryOperator>(Or0)->getOpcode(); 1783 auto ShiftOpcode1 = cast<BinaryOperator>(Or1)->getOpcode(); 1784 if (ShiftOpcode0 == ShiftOpcode1) 1785 return nullptr; 1786 1787 // We have one of these patterns so far: 1788 // select ?, TVal, (or (lshr TVal, SA0), (shl TVal, SA1)) 1789 // select ?, TVal, (or (shl TVal, SA0), (lshr TVal, SA1)) 1790 // This must be a power-of-2 rotate for a bitmasking transform to be valid. 1791 unsigned Width = Sel.getType()->getScalarSizeInBits(); 1792 if (!isPowerOf2_32(Width)) 1793 return nullptr; 1794 1795 // Check the shift amounts to see if they are an opposite pair. 1796 Value *ShAmt; 1797 if (match(SA1, m_OneUse(m_Sub(m_SpecificInt(Width), m_Specific(SA0))))) 1798 ShAmt = SA0; 1799 else if (match(SA0, m_OneUse(m_Sub(m_SpecificInt(Width), m_Specific(SA1))))) 1800 ShAmt = SA1; 1801 else 1802 return nullptr; 1803 1804 // Finally, see if the select is filtering out a shift-by-zero. 1805 Value *Cond = Sel.getCondition(); 1806 ICmpInst::Predicate Pred; 1807 if (!match(Cond, m_OneUse(m_ICmp(Pred, m_Specific(ShAmt), m_ZeroInt()))) || 1808 Pred != ICmpInst::ICMP_EQ) 1809 return nullptr; 1810 1811 // This is a rotate that avoids shift-by-bitwidth UB in a suboptimal way. 1812 // Convert to funnel shift intrinsic. 1813 bool IsFshl = (ShAmt == SA0 && ShiftOpcode0 == BinaryOperator::Shl) || 1814 (ShAmt == SA1 && ShiftOpcode1 == BinaryOperator::Shl); 1815 Intrinsic::ID IID = IsFshl ? Intrinsic::fshl : Intrinsic::fshr; 1816 Function *F = Intrinsic::getDeclaration(Sel.getModule(), IID, Sel.getType()); 1817 return IntrinsicInst::Create(F, { TVal, TVal, ShAmt }); 1818 } 1819 1820 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) { 1821 Value *CondVal = SI.getCondition(); 1822 Value *TrueVal = SI.getTrueValue(); 1823 Value *FalseVal = SI.getFalseValue(); 1824 Type *SelType = SI.getType(); 1825 1826 // FIXME: Remove this workaround when freeze related patches are done. 1827 // For select with undef operand which feeds into an equality comparison, 1828 // don't simplify it so loop unswitch can know the equality comparison 1829 // may have an undef operand. This is a workaround for PR31652 caused by 1830 // descrepancy about branch on undef between LoopUnswitch and GVN. 1831 if (isa<UndefValue>(TrueVal) || isa<UndefValue>(FalseVal)) { 1832 if (llvm::any_of(SI.users(), [&](User *U) { 1833 ICmpInst *CI = dyn_cast<ICmpInst>(U); 1834 if (CI && CI->isEquality()) 1835 return true; 1836 return false; 1837 })) { 1838 return nullptr; 1839 } 1840 } 1841 1842 if (Value *V = SimplifySelectInst(CondVal, TrueVal, FalseVal, 1843 SQ.getWithInstruction(&SI))) 1844 return replaceInstUsesWith(SI, V); 1845 1846 if (Instruction *I = canonicalizeSelectToShuffle(SI)) 1847 return I; 1848 1849 // Canonicalize a one-use integer compare with a non-canonical predicate by 1850 // inverting the predicate and swapping the select operands. This matches a 1851 // compare canonicalization for conditional branches. 1852 // TODO: Should we do the same for FP compares? 1853 CmpInst::Predicate Pred; 1854 if (match(CondVal, m_OneUse(m_ICmp(Pred, m_Value(), m_Value()))) && 1855 !isCanonicalPredicate(Pred)) { 1856 // Swap true/false values and condition. 1857 CmpInst *Cond = cast<CmpInst>(CondVal); 1858 Cond->setPredicate(CmpInst::getInversePredicate(Pred)); 1859 SI.setOperand(1, FalseVal); 1860 SI.setOperand(2, TrueVal); 1861 SI.swapProfMetadata(); 1862 Worklist.Add(Cond); 1863 return &SI; 1864 } 1865 1866 if (SelType->isIntOrIntVectorTy(1) && 1867 TrueVal->getType() == CondVal->getType()) { 1868 if (match(TrueVal, m_One())) { 1869 // Change: A = select B, true, C --> A = or B, C 1870 return BinaryOperator::CreateOr(CondVal, FalseVal); 1871 } 1872 if (match(TrueVal, m_Zero())) { 1873 // Change: A = select B, false, C --> A = and !B, C 1874 Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName()); 1875 return BinaryOperator::CreateAnd(NotCond, FalseVal); 1876 } 1877 if (match(FalseVal, m_Zero())) { 1878 // Change: A = select B, C, false --> A = and B, C 1879 return BinaryOperator::CreateAnd(CondVal, TrueVal); 1880 } 1881 if (match(FalseVal, m_One())) { 1882 // Change: A = select B, C, true --> A = or !B, C 1883 Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName()); 1884 return BinaryOperator::CreateOr(NotCond, TrueVal); 1885 } 1886 1887 // select a, a, b -> a | b 1888 // select a, b, a -> a & b 1889 if (CondVal == TrueVal) 1890 return BinaryOperator::CreateOr(CondVal, FalseVal); 1891 if (CondVal == FalseVal) 1892 return BinaryOperator::CreateAnd(CondVal, TrueVal); 1893 1894 // select a, ~a, b -> (~a) & b 1895 // select a, b, ~a -> (~a) | b 1896 if (match(TrueVal, m_Not(m_Specific(CondVal)))) 1897 return BinaryOperator::CreateAnd(TrueVal, FalseVal); 1898 if (match(FalseVal, m_Not(m_Specific(CondVal)))) 1899 return BinaryOperator::CreateOr(TrueVal, FalseVal); 1900 } 1901 1902 // Selecting between two integer or vector splat integer constants? 1903 // 1904 // Note that we don't handle a scalar select of vectors: 1905 // select i1 %c, <2 x i8> <1, 1>, <2 x i8> <0, 0> 1906 // because that may need 3 instructions to splat the condition value: 1907 // extend, insertelement, shufflevector. 1908 if (SelType->isIntOrIntVectorTy() && 1909 CondVal->getType()->isVectorTy() == SelType->isVectorTy()) { 1910 // select C, 1, 0 -> zext C to int 1911 if (match(TrueVal, m_One()) && match(FalseVal, m_Zero())) 1912 return new ZExtInst(CondVal, SelType); 1913 1914 // select C, -1, 0 -> sext C to int 1915 if (match(TrueVal, m_AllOnes()) && match(FalseVal, m_Zero())) 1916 return new SExtInst(CondVal, SelType); 1917 1918 // select C, 0, 1 -> zext !C to int 1919 if (match(TrueVal, m_Zero()) && match(FalseVal, m_One())) { 1920 Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName()); 1921 return new ZExtInst(NotCond, SelType); 1922 } 1923 1924 // select C, 0, -1 -> sext !C to int 1925 if (match(TrueVal, m_Zero()) && match(FalseVal, m_AllOnes())) { 1926 Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName()); 1927 return new SExtInst(NotCond, SelType); 1928 } 1929 } 1930 1931 // See if we are selecting two values based on a comparison of the two values. 1932 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) { 1933 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) { 1934 // Canonicalize to use ordered comparisons by swapping the select 1935 // operands. 1936 // 1937 // e.g. 1938 // (X ugt Y) ? X : Y -> (X ole Y) ? Y : X 1939 if (FCI->hasOneUse() && FCmpInst::isUnordered(FCI->getPredicate())) { 1940 FCmpInst::Predicate InvPred = FCI->getInversePredicate(); 1941 IRBuilder<>::FastMathFlagGuard FMFG(Builder); 1942 Builder.setFastMathFlags(FCI->getFastMathFlags()); 1943 Value *NewCond = Builder.CreateFCmp(InvPred, TrueVal, FalseVal, 1944 FCI->getName() + ".inv"); 1945 1946 return SelectInst::Create(NewCond, FalseVal, TrueVal, 1947 SI.getName() + ".p"); 1948 } 1949 1950 // NOTE: if we wanted to, this is where to detect MIN/MAX 1951 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){ 1952 // Canonicalize to use ordered comparisons by swapping the select 1953 // operands. 1954 // 1955 // e.g. 1956 // (X ugt Y) ? X : Y -> (X ole Y) ? X : Y 1957 if (FCI->hasOneUse() && FCmpInst::isUnordered(FCI->getPredicate())) { 1958 FCmpInst::Predicate InvPred = FCI->getInversePredicate(); 1959 IRBuilder<>::FastMathFlagGuard FMFG(Builder); 1960 Builder.setFastMathFlags(FCI->getFastMathFlags()); 1961 Value *NewCond = Builder.CreateFCmp(InvPred, FalseVal, TrueVal, 1962 FCI->getName() + ".inv"); 1963 1964 return SelectInst::Create(NewCond, FalseVal, TrueVal, 1965 SI.getName() + ".p"); 1966 } 1967 1968 // NOTE: if we wanted to, this is where to detect MIN/MAX 1969 } 1970 } 1971 1972 // Canonicalize select with fcmp to fabs(). -0.0 makes this tricky. We need 1973 // fast-math-flags (nsz) or fsub with +0.0 (not fneg) for this to work. We 1974 // also require nnan because we do not want to unintentionally change the 1975 // sign of a NaN value. 1976 // FIXME: These folds should test/propagate FMF from the select, not the 1977 // fsub or fneg. 1978 // (X <= +/-0.0) ? (0.0 - X) : X --> fabs(X) 1979 Instruction *FSub; 1980 if (match(CondVal, m_FCmp(Pred, m_Specific(FalseVal), m_AnyZeroFP())) && 1981 match(TrueVal, m_FSub(m_PosZeroFP(), m_Specific(FalseVal))) && 1982 match(TrueVal, m_Instruction(FSub)) && FSub->hasNoNaNs() && 1983 (Pred == FCmpInst::FCMP_OLE || Pred == FCmpInst::FCMP_ULE)) { 1984 Value *Fabs = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, FalseVal, FSub); 1985 return replaceInstUsesWith(SI, Fabs); 1986 } 1987 // (X > +/-0.0) ? X : (0.0 - X) --> fabs(X) 1988 if (match(CondVal, m_FCmp(Pred, m_Specific(TrueVal), m_AnyZeroFP())) && 1989 match(FalseVal, m_FSub(m_PosZeroFP(), m_Specific(TrueVal))) && 1990 match(FalseVal, m_Instruction(FSub)) && FSub->hasNoNaNs() && 1991 (Pred == FCmpInst::FCMP_OGT || Pred == FCmpInst::FCMP_UGT)) { 1992 Value *Fabs = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, TrueVal, FSub); 1993 return replaceInstUsesWith(SI, Fabs); 1994 } 1995 // With nnan and nsz: 1996 // (X < +/-0.0) ? -X : X --> fabs(X) 1997 // (X <= +/-0.0) ? -X : X --> fabs(X) 1998 Instruction *FNeg; 1999 if (match(CondVal, m_FCmp(Pred, m_Specific(FalseVal), m_AnyZeroFP())) && 2000 match(TrueVal, m_FNeg(m_Specific(FalseVal))) && 2001 match(TrueVal, m_Instruction(FNeg)) && 2002 FNeg->hasNoNaNs() && FNeg->hasNoSignedZeros() && 2003 (Pred == FCmpInst::FCMP_OLT || Pred == FCmpInst::FCMP_OLE || 2004 Pred == FCmpInst::FCMP_ULT || Pred == FCmpInst::FCMP_ULE)) { 2005 Value *Fabs = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, FalseVal, FNeg); 2006 return replaceInstUsesWith(SI, Fabs); 2007 } 2008 // With nnan and nsz: 2009 // (X > +/-0.0) ? X : -X --> fabs(X) 2010 // (X >= +/-0.0) ? X : -X --> fabs(X) 2011 if (match(CondVal, m_FCmp(Pred, m_Specific(TrueVal), m_AnyZeroFP())) && 2012 match(FalseVal, m_FNeg(m_Specific(TrueVal))) && 2013 match(FalseVal, m_Instruction(FNeg)) && 2014 FNeg->hasNoNaNs() && FNeg->hasNoSignedZeros() && 2015 (Pred == FCmpInst::FCMP_OGT || Pred == FCmpInst::FCMP_OGE || 2016 Pred == FCmpInst::FCMP_UGT || Pred == FCmpInst::FCMP_UGE)) { 2017 Value *Fabs = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, TrueVal, FNeg); 2018 return replaceInstUsesWith(SI, Fabs); 2019 } 2020 2021 // See if we are selecting two values based on a comparison of the two values. 2022 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) 2023 if (Instruction *Result = foldSelectInstWithICmp(SI, ICI)) 2024 return Result; 2025 2026 if (Instruction *Add = foldAddSubSelect(SI, Builder)) 2027 return Add; 2028 2029 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z)) 2030 auto *TI = dyn_cast<Instruction>(TrueVal); 2031 auto *FI = dyn_cast<Instruction>(FalseVal); 2032 if (TI && FI && TI->getOpcode() == FI->getOpcode()) 2033 if (Instruction *IV = foldSelectOpOp(SI, TI, FI)) 2034 return IV; 2035 2036 if (Instruction *I = foldSelectExtConst(SI)) 2037 return I; 2038 2039 // See if we can fold the select into one of our operands. 2040 if (SelType->isIntOrIntVectorTy() || SelType->isFPOrFPVectorTy()) { 2041 if (Instruction *FoldI = foldSelectIntoOp(SI, TrueVal, FalseVal)) 2042 return FoldI; 2043 2044 Value *LHS, *RHS; 2045 Instruction::CastOps CastOp; 2046 SelectPatternResult SPR = matchSelectPattern(&SI, LHS, RHS, &CastOp); 2047 auto SPF = SPR.Flavor; 2048 if (SPF) { 2049 Value *LHS2, *RHS2; 2050 if (SelectPatternFlavor SPF2 = matchSelectPattern(LHS, LHS2, RHS2).Flavor) 2051 if (Instruction *R = foldSPFofSPF(cast<Instruction>(LHS), SPF2, LHS2, 2052 RHS2, SI, SPF, RHS)) 2053 return R; 2054 if (SelectPatternFlavor SPF2 = matchSelectPattern(RHS, LHS2, RHS2).Flavor) 2055 if (Instruction *R = foldSPFofSPF(cast<Instruction>(RHS), SPF2, LHS2, 2056 RHS2, SI, SPF, LHS)) 2057 return R; 2058 // TODO. 2059 // ABS(-X) -> ABS(X) 2060 } 2061 2062 if (SelectPatternResult::isMinOrMax(SPF)) { 2063 // Canonicalize so that 2064 // - type casts are outside select patterns. 2065 // - float clamp is transformed to min/max pattern 2066 2067 bool IsCastNeeded = LHS->getType() != SelType; 2068 Value *CmpLHS = cast<CmpInst>(CondVal)->getOperand(0); 2069 Value *CmpRHS = cast<CmpInst>(CondVal)->getOperand(1); 2070 if (IsCastNeeded || 2071 (LHS->getType()->isFPOrFPVectorTy() && 2072 ((CmpLHS != LHS && CmpLHS != RHS) || 2073 (CmpRHS != LHS && CmpRHS != RHS)))) { 2074 CmpInst::Predicate Pred = getMinMaxPred(SPF, SPR.Ordered); 2075 2076 Value *Cmp; 2077 if (CmpInst::isIntPredicate(Pred)) { 2078 Cmp = Builder.CreateICmp(Pred, LHS, RHS); 2079 } else { 2080 IRBuilder<>::FastMathFlagGuard FMFG(Builder); 2081 auto FMF = cast<FPMathOperator>(SI.getCondition())->getFastMathFlags(); 2082 Builder.setFastMathFlags(FMF); 2083 Cmp = Builder.CreateFCmp(Pred, LHS, RHS); 2084 } 2085 2086 Value *NewSI = Builder.CreateSelect(Cmp, LHS, RHS, SI.getName(), &SI); 2087 if (!IsCastNeeded) 2088 return replaceInstUsesWith(SI, NewSI); 2089 2090 Value *NewCast = Builder.CreateCast(CastOp, NewSI, SelType); 2091 return replaceInstUsesWith(SI, NewCast); 2092 } 2093 2094 // MAX(~a, ~b) -> ~MIN(a, b) 2095 // MAX(~a, C) -> ~MIN(a, ~C) 2096 // MIN(~a, ~b) -> ~MAX(a, b) 2097 // MIN(~a, C) -> ~MAX(a, ~C) 2098 auto moveNotAfterMinMax = [&](Value *X, Value *Y) -> Instruction * { 2099 Value *A; 2100 if (match(X, m_Not(m_Value(A))) && !X->hasNUsesOrMore(3) && 2101 !IsFreeToInvert(A, A->hasOneUse()) && 2102 // Passing false to only consider m_Not and constants. 2103 IsFreeToInvert(Y, false)) { 2104 Value *B = Builder.CreateNot(Y); 2105 Value *NewMinMax = createMinMax(Builder, getInverseMinMaxFlavor(SPF), 2106 A, B); 2107 // Copy the profile metadata. 2108 if (MDNode *MD = SI.getMetadata(LLVMContext::MD_prof)) { 2109 cast<SelectInst>(NewMinMax)->setMetadata(LLVMContext::MD_prof, MD); 2110 // Swap the metadata if the operands are swapped. 2111 if (X == SI.getFalseValue() && Y == SI.getTrueValue()) 2112 cast<SelectInst>(NewMinMax)->swapProfMetadata(); 2113 } 2114 2115 return BinaryOperator::CreateNot(NewMinMax); 2116 } 2117 2118 return nullptr; 2119 }; 2120 2121 if (Instruction *I = moveNotAfterMinMax(LHS, RHS)) 2122 return I; 2123 if (Instruction *I = moveNotAfterMinMax(RHS, LHS)) 2124 return I; 2125 2126 if (Instruction *I = moveAddAfterMinMax(SPF, LHS, RHS, Builder)) 2127 return I; 2128 2129 if (Instruction *I = factorizeMinMaxTree(SPF, LHS, RHS, Builder)) 2130 return I; 2131 } 2132 } 2133 2134 // Canonicalize select of FP values where NaN and -0.0 are not valid as 2135 // minnum/maxnum intrinsics. 2136 if (isa<FPMathOperator>(SI) && SI.hasNoNaNs() && SI.hasNoSignedZeros()) { 2137 Value *X, *Y; 2138 if (match(&SI, m_OrdFMax(m_Value(X), m_Value(Y)))) 2139 return replaceInstUsesWith( 2140 SI, Builder.CreateBinaryIntrinsic(Intrinsic::maxnum, X, Y, &SI)); 2141 2142 if (match(&SI, m_OrdFMin(m_Value(X), m_Value(Y)))) 2143 return replaceInstUsesWith( 2144 SI, Builder.CreateBinaryIntrinsic(Intrinsic::minnum, X, Y, &SI)); 2145 } 2146 2147 // See if we can fold the select into a phi node if the condition is a select. 2148 if (auto *PN = dyn_cast<PHINode>(SI.getCondition())) 2149 // The true/false values have to be live in the PHI predecessor's blocks. 2150 if (canSelectOperandBeMappingIntoPredBlock(TrueVal, SI) && 2151 canSelectOperandBeMappingIntoPredBlock(FalseVal, SI)) 2152 if (Instruction *NV = foldOpIntoPhi(SI, PN)) 2153 return NV; 2154 2155 if (SelectInst *TrueSI = dyn_cast<SelectInst>(TrueVal)) { 2156 if (TrueSI->getCondition()->getType() == CondVal->getType()) { 2157 // select(C, select(C, a, b), c) -> select(C, a, c) 2158 if (TrueSI->getCondition() == CondVal) { 2159 if (SI.getTrueValue() == TrueSI->getTrueValue()) 2160 return nullptr; 2161 SI.setOperand(1, TrueSI->getTrueValue()); 2162 return &SI; 2163 } 2164 // select(C0, select(C1, a, b), b) -> select(C0&C1, a, b) 2165 // We choose this as normal form to enable folding on the And and shortening 2166 // paths for the values (this helps GetUnderlyingObjects() for example). 2167 if (TrueSI->getFalseValue() == FalseVal && TrueSI->hasOneUse()) { 2168 Value *And = Builder.CreateAnd(CondVal, TrueSI->getCondition()); 2169 SI.setOperand(0, And); 2170 SI.setOperand(1, TrueSI->getTrueValue()); 2171 return &SI; 2172 } 2173 } 2174 } 2175 if (SelectInst *FalseSI = dyn_cast<SelectInst>(FalseVal)) { 2176 if (FalseSI->getCondition()->getType() == CondVal->getType()) { 2177 // select(C, a, select(C, b, c)) -> select(C, a, c) 2178 if (FalseSI->getCondition() == CondVal) { 2179 if (SI.getFalseValue() == FalseSI->getFalseValue()) 2180 return nullptr; 2181 SI.setOperand(2, FalseSI->getFalseValue()); 2182 return &SI; 2183 } 2184 // select(C0, a, select(C1, a, b)) -> select(C0|C1, a, b) 2185 if (FalseSI->getTrueValue() == TrueVal && FalseSI->hasOneUse()) { 2186 Value *Or = Builder.CreateOr(CondVal, FalseSI->getCondition()); 2187 SI.setOperand(0, Or); 2188 SI.setOperand(2, FalseSI->getFalseValue()); 2189 return &SI; 2190 } 2191 } 2192 } 2193 2194 auto canMergeSelectThroughBinop = [](BinaryOperator *BO) { 2195 // The select might be preventing a division by 0. 2196 switch (BO->getOpcode()) { 2197 default: 2198 return true; 2199 case Instruction::SRem: 2200 case Instruction::URem: 2201 case Instruction::SDiv: 2202 case Instruction::UDiv: 2203 return false; 2204 } 2205 }; 2206 2207 // Try to simplify a binop sandwiched between 2 selects with the same 2208 // condition. 2209 // select(C, binop(select(C, X, Y), W), Z) -> select(C, binop(X, W), Z) 2210 BinaryOperator *TrueBO; 2211 if (match(TrueVal, m_OneUse(m_BinOp(TrueBO))) && 2212 canMergeSelectThroughBinop(TrueBO)) { 2213 if (auto *TrueBOSI = dyn_cast<SelectInst>(TrueBO->getOperand(0))) { 2214 if (TrueBOSI->getCondition() == CondVal) { 2215 TrueBO->setOperand(0, TrueBOSI->getTrueValue()); 2216 Worklist.Add(TrueBO); 2217 return &SI; 2218 } 2219 } 2220 if (auto *TrueBOSI = dyn_cast<SelectInst>(TrueBO->getOperand(1))) { 2221 if (TrueBOSI->getCondition() == CondVal) { 2222 TrueBO->setOperand(1, TrueBOSI->getTrueValue()); 2223 Worklist.Add(TrueBO); 2224 return &SI; 2225 } 2226 } 2227 } 2228 2229 // select(C, Z, binop(select(C, X, Y), W)) -> select(C, Z, binop(Y, W)) 2230 BinaryOperator *FalseBO; 2231 if (match(FalseVal, m_OneUse(m_BinOp(FalseBO))) && 2232 canMergeSelectThroughBinop(FalseBO)) { 2233 if (auto *FalseBOSI = dyn_cast<SelectInst>(FalseBO->getOperand(0))) { 2234 if (FalseBOSI->getCondition() == CondVal) { 2235 FalseBO->setOperand(0, FalseBOSI->getFalseValue()); 2236 Worklist.Add(FalseBO); 2237 return &SI; 2238 } 2239 } 2240 if (auto *FalseBOSI = dyn_cast<SelectInst>(FalseBO->getOperand(1))) { 2241 if (FalseBOSI->getCondition() == CondVal) { 2242 FalseBO->setOperand(1, FalseBOSI->getFalseValue()); 2243 Worklist.Add(FalseBO); 2244 return &SI; 2245 } 2246 } 2247 } 2248 2249 Value *NotCond; 2250 if (match(CondVal, m_Not(m_Value(NotCond)))) { 2251 SI.setOperand(0, NotCond); 2252 SI.setOperand(1, FalseVal); 2253 SI.setOperand(2, TrueVal); 2254 SI.swapProfMetadata(); 2255 return &SI; 2256 } 2257 2258 if (VectorType *VecTy = dyn_cast<VectorType>(SelType)) { 2259 unsigned VWidth = VecTy->getNumElements(); 2260 APInt UndefElts(VWidth, 0); 2261 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth)); 2262 if (Value *V = SimplifyDemandedVectorElts(&SI, AllOnesEltMask, UndefElts)) { 2263 if (V != &SI) 2264 return replaceInstUsesWith(SI, V); 2265 return &SI; 2266 } 2267 } 2268 2269 // If we can compute the condition, there's no need for a select. 2270 // Like the above fold, we are attempting to reduce compile-time cost by 2271 // putting this fold here with limitations rather than in InstSimplify. 2272 // The motivation for this call into value tracking is to take advantage of 2273 // the assumption cache, so make sure that is populated. 2274 if (!CondVal->getType()->isVectorTy() && !AC.assumptions().empty()) { 2275 KnownBits Known(1); 2276 computeKnownBits(CondVal, Known, 0, &SI); 2277 if (Known.One.isOneValue()) 2278 return replaceInstUsesWith(SI, TrueVal); 2279 if (Known.Zero.isOneValue()) 2280 return replaceInstUsesWith(SI, FalseVal); 2281 } 2282 2283 if (Instruction *BitCastSel = foldSelectCmpBitcasts(SI, Builder)) 2284 return BitCastSel; 2285 2286 // Simplify selects that test the returned flag of cmpxchg instructions. 2287 if (Instruction *Select = foldSelectCmpXchg(SI)) 2288 return Select; 2289 2290 if (Instruction *Select = foldSelectBinOpIdentity(SI, TLI)) 2291 return Select; 2292 2293 if (Instruction *Rot = foldSelectRotate(SI)) 2294 return Rot; 2295 2296 return nullptr; 2297 } 2298