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 InstCombiner &IC) { 61 // The select condition must be an equality compare with a constant operand. 62 Value *X; 63 Constant *C; 64 CmpInst::Predicate Pred; 65 if (!match(Sel.getCondition(), m_Cmp(Pred, m_Value(X), m_Constant(C)))) 66 return nullptr; 67 68 bool IsEq; 69 if (ICmpInst::isEquality(Pred)) 70 IsEq = Pred == ICmpInst::ICMP_EQ; 71 else if (Pred == FCmpInst::FCMP_OEQ) 72 IsEq = true; 73 else if (Pred == FCmpInst::FCMP_UNE) 74 IsEq = false; 75 else 76 return nullptr; 77 78 // A select operand must be a binop. 79 BinaryOperator *BO; 80 if (!match(Sel.getOperand(IsEq ? 1 : 2), m_BinOp(BO))) 81 return nullptr; 82 83 // The compare constant must be the identity constant for that binop. 84 // If this a floating-point compare with 0.0, any zero constant will do. 85 Type *Ty = BO->getType(); 86 Constant *IdC = ConstantExpr::getBinOpIdentity(BO->getOpcode(), Ty, true); 87 if (IdC != C) { 88 if (!IdC || !CmpInst::isFPPredicate(Pred)) 89 return nullptr; 90 if (!match(IdC, m_AnyZeroFP()) || !match(C, m_AnyZeroFP())) 91 return nullptr; 92 } 93 94 // Last, match the compare variable operand with a binop operand. 95 Value *Y; 96 if (!BO->isCommutative() && !match(BO, m_BinOp(m_Value(Y), m_Specific(X)))) 97 return nullptr; 98 if (!match(BO, m_c_BinOp(m_Value(Y), m_Specific(X)))) 99 return nullptr; 100 101 // +0.0 compares equal to -0.0, and so it does not behave as required for this 102 // transform. Bail out if we can not exclude that possibility. 103 if (isa<FPMathOperator>(BO)) 104 if (!BO->hasNoSignedZeros() && !CannotBeNegativeZero(Y, &TLI)) 105 return nullptr; 106 107 // BO = binop Y, X 108 // S = { select (cmp eq X, C), BO, ? } or { select (cmp ne X, C), ?, BO } 109 // => 110 // S = { select (cmp eq X, C), Y, ? } or { select (cmp ne X, C), ?, Y } 111 return IC.replaceOperand(Sel, IsEq ? 1 : 2, Y); 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 // Ensure the sub is of the form: 708 // (a > b) ? a - b : 0 -> usub.sat(a, b) 709 // (a > b) ? b - a : 0 -> -usub.sat(a, b) 710 // Checking for both a-b and a+(-b) as a constant. 711 bool IsNegative = false; 712 const APInt *C; 713 if (match(TrueVal, m_Sub(m_Specific(B), m_Specific(A))) || 714 (match(A, m_APInt(C)) && 715 match(TrueVal, m_Add(m_Specific(B), m_SpecificInt(-*C))))) 716 IsNegative = true; 717 else if (!match(TrueVal, m_Sub(m_Specific(A), m_Specific(B))) && 718 !(match(B, m_APInt(C)) && 719 match(TrueVal, m_Add(m_Specific(A), m_SpecificInt(-*C))))) 720 return nullptr; 721 722 // If we are adding a negate and the sub and icmp are used anywhere else, we 723 // would end up with more instructions. 724 if (IsNegative && !TrueVal->hasOneUse() && !ICI->hasOneUse()) 725 return nullptr; 726 727 // (a > b) ? a - b : 0 -> usub.sat(a, b) 728 // (a > b) ? b - a : 0 -> -usub.sat(a, b) 729 Value *Result = Builder.CreateBinaryIntrinsic(Intrinsic::usub_sat, A, B); 730 if (IsNegative) 731 Result = Builder.CreateNeg(Result); 732 return Result; 733 } 734 735 static Value *canonicalizeSaturatedAdd(ICmpInst *Cmp, Value *TVal, Value *FVal, 736 InstCombiner::BuilderTy &Builder) { 737 if (!Cmp->hasOneUse()) 738 return nullptr; 739 740 // Match unsigned saturated add with constant. 741 Value *Cmp0 = Cmp->getOperand(0); 742 Value *Cmp1 = Cmp->getOperand(1); 743 ICmpInst::Predicate Pred = Cmp->getPredicate(); 744 Value *X; 745 const APInt *C, *CmpC; 746 if (Pred == ICmpInst::ICMP_ULT && 747 match(TVal, m_Add(m_Value(X), m_APInt(C))) && X == Cmp0 && 748 match(FVal, m_AllOnes()) && match(Cmp1, m_APInt(CmpC)) && *CmpC == ~*C) { 749 // (X u< ~C) ? (X + C) : -1 --> uadd.sat(X, C) 750 return Builder.CreateBinaryIntrinsic( 751 Intrinsic::uadd_sat, X, ConstantInt::get(X->getType(), *C)); 752 } 753 754 // Match unsigned saturated add of 2 variables with an unnecessary 'not'. 755 // There are 8 commuted variants. 756 // Canonicalize -1 (saturated result) to true value of the select. Just 757 // swapping the compare operands is legal, because the selected value is the 758 // same in case of equality, so we can interchange u< and u<=. 759 if (match(FVal, m_AllOnes())) { 760 std::swap(TVal, FVal); 761 std::swap(Cmp0, Cmp1); 762 } 763 if (!match(TVal, m_AllOnes())) 764 return nullptr; 765 766 // Canonicalize predicate to 'ULT'. 767 if (Pred == ICmpInst::ICMP_UGT) { 768 Pred = ICmpInst::ICMP_ULT; 769 std::swap(Cmp0, Cmp1); 770 } 771 if (Pred != ICmpInst::ICMP_ULT) 772 return nullptr; 773 774 // Match unsigned saturated add of 2 variables with an unnecessary 'not'. 775 Value *Y; 776 if (match(Cmp0, m_Not(m_Value(X))) && 777 match(FVal, m_c_Add(m_Specific(X), m_Value(Y))) && Y == Cmp1) { 778 // (~X u< Y) ? -1 : (X + Y) --> uadd.sat(X, Y) 779 // (~X u< Y) ? -1 : (Y + X) --> uadd.sat(X, Y) 780 return Builder.CreateBinaryIntrinsic(Intrinsic::uadd_sat, X, Y); 781 } 782 // The 'not' op may be included in the sum but not the compare. 783 X = Cmp0; 784 Y = Cmp1; 785 if (match(FVal, m_c_Add(m_Not(m_Specific(X)), m_Specific(Y)))) { 786 // (X u< Y) ? -1 : (~X + Y) --> uadd.sat(~X, Y) 787 // (X u< Y) ? -1 : (Y + ~X) --> uadd.sat(Y, ~X) 788 BinaryOperator *BO = cast<BinaryOperator>(FVal); 789 return Builder.CreateBinaryIntrinsic( 790 Intrinsic::uadd_sat, BO->getOperand(0), BO->getOperand(1)); 791 } 792 // The overflow may be detected via the add wrapping round. 793 if (match(Cmp0, m_c_Add(m_Specific(Cmp1), m_Value(Y))) && 794 match(FVal, m_c_Add(m_Specific(Cmp1), m_Specific(Y)))) { 795 // ((X + Y) u< X) ? -1 : (X + Y) --> uadd.sat(X, Y) 796 // ((X + Y) u< Y) ? -1 : (X + Y) --> uadd.sat(X, Y) 797 return Builder.CreateBinaryIntrinsic(Intrinsic::uadd_sat, Cmp1, Y); 798 } 799 800 return nullptr; 801 } 802 803 /// Fold the following code sequence: 804 /// \code 805 /// int a = ctlz(x & -x); 806 // x ? 31 - a : a; 807 /// \code 808 /// 809 /// into: 810 /// cttz(x) 811 static Instruction *foldSelectCtlzToCttz(ICmpInst *ICI, Value *TrueVal, 812 Value *FalseVal, 813 InstCombiner::BuilderTy &Builder) { 814 unsigned BitWidth = TrueVal->getType()->getScalarSizeInBits(); 815 if (!ICI->isEquality() || !match(ICI->getOperand(1), m_Zero())) 816 return nullptr; 817 818 if (ICI->getPredicate() == ICmpInst::ICMP_NE) 819 std::swap(TrueVal, FalseVal); 820 821 if (!match(FalseVal, 822 m_Xor(m_Deferred(TrueVal), m_SpecificInt(BitWidth - 1)))) 823 return nullptr; 824 825 if (!match(TrueVal, m_Intrinsic<Intrinsic::ctlz>())) 826 return nullptr; 827 828 Value *X = ICI->getOperand(0); 829 auto *II = cast<IntrinsicInst>(TrueVal); 830 if (!match(II->getOperand(0), m_c_And(m_Specific(X), m_Neg(m_Specific(X))))) 831 return nullptr; 832 833 Function *F = Intrinsic::getDeclaration(II->getModule(), Intrinsic::cttz, 834 II->getType()); 835 return CallInst::Create(F, {X, II->getArgOperand(1)}); 836 } 837 838 /// Attempt to fold a cttz/ctlz followed by a icmp plus select into a single 839 /// call to cttz/ctlz with flag 'is_zero_undef' cleared. 840 /// 841 /// For example, we can fold the following code sequence: 842 /// \code 843 /// %0 = tail call i32 @llvm.cttz.i32(i32 %x, i1 true) 844 /// %1 = icmp ne i32 %x, 0 845 /// %2 = select i1 %1, i32 %0, i32 32 846 /// \code 847 /// 848 /// into: 849 /// %0 = tail call i32 @llvm.cttz.i32(i32 %x, i1 false) 850 static Value *foldSelectCttzCtlz(ICmpInst *ICI, Value *TrueVal, Value *FalseVal, 851 InstCombiner::BuilderTy &Builder) { 852 ICmpInst::Predicate Pred = ICI->getPredicate(); 853 Value *CmpLHS = ICI->getOperand(0); 854 Value *CmpRHS = ICI->getOperand(1); 855 856 // Check if the condition value compares a value for equality against zero. 857 if (!ICI->isEquality() || !match(CmpRHS, m_Zero())) 858 return nullptr; 859 860 Value *Count = FalseVal; 861 Value *ValueOnZero = TrueVal; 862 if (Pred == ICmpInst::ICMP_NE) 863 std::swap(Count, ValueOnZero); 864 865 // Skip zero extend/truncate. 866 Value *V = nullptr; 867 if (match(Count, m_ZExt(m_Value(V))) || 868 match(Count, m_Trunc(m_Value(V)))) 869 Count = V; 870 871 // Check that 'Count' is a call to intrinsic cttz/ctlz. Also check that the 872 // input to the cttz/ctlz is used as LHS for the compare instruction. 873 if (!match(Count, m_Intrinsic<Intrinsic::cttz>(m_Specific(CmpLHS))) && 874 !match(Count, m_Intrinsic<Intrinsic::ctlz>(m_Specific(CmpLHS)))) 875 return nullptr; 876 877 IntrinsicInst *II = cast<IntrinsicInst>(Count); 878 879 // Check if the value propagated on zero is a constant number equal to the 880 // sizeof in bits of 'Count'. 881 unsigned SizeOfInBits = Count->getType()->getScalarSizeInBits(); 882 if (match(ValueOnZero, m_SpecificInt(SizeOfInBits))) { 883 // Explicitly clear the 'undef_on_zero' flag. 884 IntrinsicInst *NewI = cast<IntrinsicInst>(II->clone()); 885 NewI->setArgOperand(1, ConstantInt::getFalse(NewI->getContext())); 886 Builder.Insert(NewI); 887 return Builder.CreateZExtOrTrunc(NewI, ValueOnZero->getType()); 888 } 889 890 // If the ValueOnZero is not the bitwidth, we can at least make use of the 891 // fact that the cttz/ctlz result will not be used if the input is zero, so 892 // it's okay to relax it to undef for that case. 893 if (II->hasOneUse() && !match(II->getArgOperand(1), m_One())) 894 II->setArgOperand(1, ConstantInt::getTrue(II->getContext())); 895 896 return nullptr; 897 } 898 899 /// Return true if we find and adjust an icmp+select pattern where the compare 900 /// is with a constant that can be incremented or decremented to match the 901 /// minimum or maximum idiom. 902 static bool adjustMinMax(SelectInst &Sel, ICmpInst &Cmp) { 903 ICmpInst::Predicate Pred = Cmp.getPredicate(); 904 Value *CmpLHS = Cmp.getOperand(0); 905 Value *CmpRHS = Cmp.getOperand(1); 906 Value *TrueVal = Sel.getTrueValue(); 907 Value *FalseVal = Sel.getFalseValue(); 908 909 // We may move or edit the compare, so make sure the select is the only user. 910 const APInt *CmpC; 911 if (!Cmp.hasOneUse() || !match(CmpRHS, m_APInt(CmpC))) 912 return false; 913 914 // These transforms only work for selects of integers or vector selects of 915 // integer vectors. 916 Type *SelTy = Sel.getType(); 917 auto *SelEltTy = dyn_cast<IntegerType>(SelTy->getScalarType()); 918 if (!SelEltTy || SelTy->isVectorTy() != Cmp.getType()->isVectorTy()) 919 return false; 920 921 Constant *AdjustedRHS; 922 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_SGT) 923 AdjustedRHS = ConstantInt::get(CmpRHS->getType(), *CmpC + 1); 924 else if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT) 925 AdjustedRHS = ConstantInt::get(CmpRHS->getType(), *CmpC - 1); 926 else 927 return false; 928 929 // X > C ? X : C+1 --> X < C+1 ? C+1 : X 930 // X < C ? X : C-1 --> X > C-1 ? C-1 : X 931 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) || 932 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) { 933 ; // Nothing to do here. Values match without any sign/zero extension. 934 } 935 // Types do not match. Instead of calculating this with mixed types, promote 936 // all to the larger type. This enables scalar evolution to analyze this 937 // expression. 938 else if (CmpRHS->getType()->getScalarSizeInBits() < SelEltTy->getBitWidth()) { 939 Constant *SextRHS = ConstantExpr::getSExt(AdjustedRHS, SelTy); 940 941 // X = sext x; x >s c ? X : C+1 --> X = sext x; X <s C+1 ? C+1 : X 942 // X = sext x; x <s c ? X : C-1 --> X = sext x; X >s C-1 ? C-1 : X 943 // X = sext x; x >u c ? X : C+1 --> X = sext x; X <u C+1 ? C+1 : X 944 // X = sext x; x <u c ? X : C-1 --> X = sext x; X >u C-1 ? C-1 : X 945 if (match(TrueVal, m_SExt(m_Specific(CmpLHS))) && SextRHS == FalseVal) { 946 CmpLHS = TrueVal; 947 AdjustedRHS = SextRHS; 948 } else if (match(FalseVal, m_SExt(m_Specific(CmpLHS))) && 949 SextRHS == TrueVal) { 950 CmpLHS = FalseVal; 951 AdjustedRHS = SextRHS; 952 } else if (Cmp.isUnsigned()) { 953 Constant *ZextRHS = ConstantExpr::getZExt(AdjustedRHS, SelTy); 954 // X = zext x; x >u c ? X : C+1 --> X = zext x; X <u C+1 ? C+1 : X 955 // X = zext x; x <u c ? X : C-1 --> X = zext x; X >u C-1 ? C-1 : X 956 // zext + signed compare cannot be changed: 957 // 0xff <s 0x00, but 0x00ff >s 0x0000 958 if (match(TrueVal, m_ZExt(m_Specific(CmpLHS))) && ZextRHS == FalseVal) { 959 CmpLHS = TrueVal; 960 AdjustedRHS = ZextRHS; 961 } else if (match(FalseVal, m_ZExt(m_Specific(CmpLHS))) && 962 ZextRHS == TrueVal) { 963 CmpLHS = FalseVal; 964 AdjustedRHS = ZextRHS; 965 } else { 966 return false; 967 } 968 } else { 969 return false; 970 } 971 } else { 972 return false; 973 } 974 975 Pred = ICmpInst::getSwappedPredicate(Pred); 976 CmpRHS = AdjustedRHS; 977 std::swap(FalseVal, TrueVal); 978 Cmp.setPredicate(Pred); 979 Cmp.setOperand(0, CmpLHS); 980 Cmp.setOperand(1, CmpRHS); 981 Sel.setOperand(1, TrueVal); 982 Sel.setOperand(2, FalseVal); 983 Sel.swapProfMetadata(); 984 985 // Move the compare instruction right before the select instruction. Otherwise 986 // the sext/zext value may be defined after the compare instruction uses it. 987 Cmp.moveBefore(&Sel); 988 989 return true; 990 } 991 992 /// If this is an integer min/max (icmp + select) with a constant operand, 993 /// create the canonical icmp for the min/max operation and canonicalize the 994 /// constant to the 'false' operand of the select: 995 /// select (icmp Pred X, C1), C2, X --> select (icmp Pred' X, C2), X, C2 996 /// Note: if C1 != C2, this will change the icmp constant to the existing 997 /// constant operand of the select. 998 static Instruction * 999 canonicalizeMinMaxWithConstant(SelectInst &Sel, ICmpInst &Cmp, 1000 InstCombiner &IC) { 1001 if (!Cmp.hasOneUse() || !isa<Constant>(Cmp.getOperand(1))) 1002 return nullptr; 1003 1004 // Canonicalize the compare predicate based on whether we have min or max. 1005 Value *LHS, *RHS; 1006 SelectPatternResult SPR = matchSelectPattern(&Sel, LHS, RHS); 1007 if (!SelectPatternResult::isMinOrMax(SPR.Flavor)) 1008 return nullptr; 1009 1010 // Is this already canonical? 1011 ICmpInst::Predicate CanonicalPred = getMinMaxPred(SPR.Flavor); 1012 if (Cmp.getOperand(0) == LHS && Cmp.getOperand(1) == RHS && 1013 Cmp.getPredicate() == CanonicalPred) 1014 return nullptr; 1015 1016 // Bail out on unsimplified X-0 operand (due to some worklist management bug), 1017 // as this may cause an infinite combine loop. Let the sub be folded first. 1018 if (match(LHS, m_Sub(m_Value(), m_Zero())) || 1019 match(RHS, m_Sub(m_Value(), m_Zero()))) 1020 return nullptr; 1021 1022 // Create the canonical compare and plug it into the select. 1023 IC.replaceOperand(Sel, 0, IC.Builder.CreateICmp(CanonicalPred, LHS, RHS)); 1024 1025 // If the select operands did not change, we're done. 1026 if (Sel.getTrueValue() == LHS && Sel.getFalseValue() == RHS) 1027 return &Sel; 1028 1029 // If we are swapping the select operands, swap the metadata too. 1030 assert(Sel.getTrueValue() == RHS && Sel.getFalseValue() == LHS && 1031 "Unexpected results from matchSelectPattern"); 1032 Sel.swapValues(); 1033 Sel.swapProfMetadata(); 1034 return &Sel; 1035 } 1036 1037 /// There are many select variants for each of ABS/NABS. 1038 /// In matchSelectPattern(), there are different compare constants, compare 1039 /// predicates/operands and select operands. 1040 /// In isKnownNegation(), there are different formats of negated operands. 1041 /// Canonicalize all these variants to 1 pattern. 1042 /// This makes CSE more likely. 1043 static Instruction *canonicalizeAbsNabs(SelectInst &Sel, ICmpInst &Cmp, 1044 InstCombiner::BuilderTy &Builder) { 1045 if (!Cmp.hasOneUse() || !isa<Constant>(Cmp.getOperand(1))) 1046 return nullptr; 1047 1048 // Choose a sign-bit check for the compare (likely simpler for codegen). 1049 // ABS: (X <s 0) ? -X : X 1050 // NABS: (X <s 0) ? X : -X 1051 Value *LHS, *RHS; 1052 SelectPatternFlavor SPF = matchSelectPattern(&Sel, LHS, RHS).Flavor; 1053 if (SPF != SelectPatternFlavor::SPF_ABS && 1054 SPF != SelectPatternFlavor::SPF_NABS) 1055 return nullptr; 1056 1057 Value *TVal = Sel.getTrueValue(); 1058 Value *FVal = Sel.getFalseValue(); 1059 assert(isKnownNegation(TVal, FVal) && 1060 "Unexpected result from matchSelectPattern"); 1061 1062 // The compare may use the negated abs()/nabs() operand, or it may use 1063 // negation in non-canonical form such as: sub A, B. 1064 bool CmpUsesNegatedOp = match(Cmp.getOperand(0), m_Neg(m_Specific(TVal))) || 1065 match(Cmp.getOperand(0), m_Neg(m_Specific(FVal))); 1066 1067 bool CmpCanonicalized = !CmpUsesNegatedOp && 1068 match(Cmp.getOperand(1), m_ZeroInt()) && 1069 Cmp.getPredicate() == ICmpInst::ICMP_SLT; 1070 bool RHSCanonicalized = match(RHS, m_Neg(m_Specific(LHS))); 1071 1072 // Is this already canonical? 1073 if (CmpCanonicalized && RHSCanonicalized) 1074 return nullptr; 1075 1076 // If RHS is not canonical but is used by other instructions, don't 1077 // canonicalize it and potentially increase the instruction count. 1078 if (!RHSCanonicalized) 1079 if (!(RHS->hasOneUse() || (RHS->hasNUses(2) && CmpUsesNegatedOp))) 1080 return nullptr; 1081 1082 // Create the canonical compare: icmp slt LHS 0. 1083 if (!CmpCanonicalized) { 1084 Cmp.setPredicate(ICmpInst::ICMP_SLT); 1085 Cmp.setOperand(1, ConstantInt::getNullValue(Cmp.getOperand(0)->getType())); 1086 if (CmpUsesNegatedOp) 1087 Cmp.setOperand(0, LHS); 1088 } 1089 1090 // Create the canonical RHS: RHS = sub (0, LHS). 1091 if (!RHSCanonicalized) { 1092 assert(RHS->hasOneUse() && "RHS use number is not right"); 1093 RHS = Builder.CreateNeg(LHS); 1094 if (TVal == LHS) { 1095 Sel.setFalseValue(RHS); 1096 FVal = RHS; 1097 } else { 1098 Sel.setTrueValue(RHS); 1099 TVal = RHS; 1100 } 1101 } 1102 1103 // If the select operands do not change, we're done. 1104 if (SPF == SelectPatternFlavor::SPF_NABS) { 1105 if (TVal == LHS) 1106 return &Sel; 1107 assert(FVal == LHS && "Unexpected results from matchSelectPattern"); 1108 } else { 1109 if (FVal == LHS) 1110 return &Sel; 1111 assert(TVal == LHS && "Unexpected results from matchSelectPattern"); 1112 } 1113 1114 // We are swapping the select operands, so swap the metadata too. 1115 Sel.swapValues(); 1116 Sel.swapProfMetadata(); 1117 return &Sel; 1118 } 1119 1120 static Value *simplifyWithOpReplaced(Value *V, Value *Op, Value *ReplaceOp, 1121 const SimplifyQuery &Q) { 1122 // If this is a binary operator, try to simplify it with the replaced op 1123 // because we know Op and ReplaceOp are equivalant. 1124 // For example: V = X + 1, Op = X, ReplaceOp = 42 1125 // Simplifies as: add(42, 1) --> 43 1126 if (auto *BO = dyn_cast<BinaryOperator>(V)) { 1127 if (BO->getOperand(0) == Op) 1128 return SimplifyBinOp(BO->getOpcode(), ReplaceOp, BO->getOperand(1), Q); 1129 if (BO->getOperand(1) == Op) 1130 return SimplifyBinOp(BO->getOpcode(), BO->getOperand(0), ReplaceOp, Q); 1131 } 1132 1133 return nullptr; 1134 } 1135 1136 /// If we have a select with an equality comparison, then we know the value in 1137 /// one of the arms of the select. See if substituting this value into an arm 1138 /// and simplifying the result yields the same value as the other arm. 1139 /// 1140 /// To make this transform safe, we must drop poison-generating flags 1141 /// (nsw, etc) if we simplified to a binop because the select may be guarding 1142 /// that poison from propagating. If the existing binop already had no 1143 /// poison-generating flags, then this transform can be done by instsimplify. 1144 /// 1145 /// Consider: 1146 /// %cmp = icmp eq i32 %x, 2147483647 1147 /// %add = add nsw i32 %x, 1 1148 /// %sel = select i1 %cmp, i32 -2147483648, i32 %add 1149 /// 1150 /// We can't replace %sel with %add unless we strip away the flags. 1151 /// TODO: Wrapping flags could be preserved in some cases with better analysis. 1152 static Value *foldSelectValueEquivalence(SelectInst &Sel, ICmpInst &Cmp, 1153 const SimplifyQuery &Q) { 1154 if (!Cmp.isEquality()) 1155 return nullptr; 1156 1157 // Canonicalize the pattern to ICMP_EQ by swapping the select operands. 1158 Value *TrueVal = Sel.getTrueValue(), *FalseVal = Sel.getFalseValue(); 1159 if (Cmp.getPredicate() == ICmpInst::ICMP_NE) 1160 std::swap(TrueVal, FalseVal); 1161 1162 // Try each equivalence substitution possibility. 1163 // We have an 'EQ' comparison, so the select's false value will propagate. 1164 // Example: 1165 // (X == 42) ? 43 : (X + 1) --> (X == 42) ? (X + 1) : (X + 1) --> X + 1 1166 // (X == 42) ? (X + 1) : 43 --> (X == 42) ? (42 + 1) : 43 --> 43 1167 Value *CmpLHS = Cmp.getOperand(0), *CmpRHS = Cmp.getOperand(1); 1168 if (simplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, Q) == TrueVal || 1169 simplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, Q) == TrueVal || 1170 simplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, Q) == FalseVal || 1171 simplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, Q) == FalseVal) { 1172 if (auto *FalseInst = dyn_cast<Instruction>(FalseVal)) 1173 FalseInst->dropPoisonGeneratingFlags(); 1174 return FalseVal; 1175 } 1176 return nullptr; 1177 } 1178 1179 // See if this is a pattern like: 1180 // %old_cmp1 = icmp slt i32 %x, C2 1181 // %old_replacement = select i1 %old_cmp1, i32 %target_low, i32 %target_high 1182 // %old_x_offseted = add i32 %x, C1 1183 // %old_cmp0 = icmp ult i32 %old_x_offseted, C0 1184 // %r = select i1 %old_cmp0, i32 %x, i32 %old_replacement 1185 // This can be rewritten as more canonical pattern: 1186 // %new_cmp1 = icmp slt i32 %x, -C1 1187 // %new_cmp2 = icmp sge i32 %x, C0-C1 1188 // %new_clamped_low = select i1 %new_cmp1, i32 %target_low, i32 %x 1189 // %r = select i1 %new_cmp2, i32 %target_high, i32 %new_clamped_low 1190 // Iff -C1 s<= C2 s<= C0-C1 1191 // Also ULT predicate can also be UGT iff C0 != -1 (+invert result) 1192 // SLT predicate can also be SGT iff C2 != INT_MAX (+invert res.) 1193 static Instruction *canonicalizeClampLike(SelectInst &Sel0, ICmpInst &Cmp0, 1194 InstCombiner::BuilderTy &Builder) { 1195 Value *X = Sel0.getTrueValue(); 1196 Value *Sel1 = Sel0.getFalseValue(); 1197 1198 // First match the condition of the outermost select. 1199 // Said condition must be one-use. 1200 if (!Cmp0.hasOneUse()) 1201 return nullptr; 1202 Value *Cmp00 = Cmp0.getOperand(0); 1203 Constant *C0; 1204 if (!match(Cmp0.getOperand(1), 1205 m_CombineAnd(m_AnyIntegralConstant(), m_Constant(C0)))) 1206 return nullptr; 1207 // Canonicalize Cmp0 into the form we expect. 1208 // FIXME: we shouldn't care about lanes that are 'undef' in the end? 1209 switch (Cmp0.getPredicate()) { 1210 case ICmpInst::Predicate::ICMP_ULT: 1211 break; // Great! 1212 case ICmpInst::Predicate::ICMP_ULE: 1213 // We'd have to increment C0 by one, and for that it must not have all-ones 1214 // element, but then it would have been canonicalized to 'ult' before 1215 // we get here. So we can't do anything useful with 'ule'. 1216 return nullptr; 1217 case ICmpInst::Predicate::ICMP_UGT: 1218 // We want to canonicalize it to 'ult', so we'll need to increment C0, 1219 // which again means it must not have any all-ones elements. 1220 if (!match(C0, 1221 m_SpecificInt_ICMP(ICmpInst::Predicate::ICMP_NE, 1222 APInt::getAllOnesValue( 1223 C0->getType()->getScalarSizeInBits())))) 1224 return nullptr; // Can't do, have all-ones element[s]. 1225 C0 = AddOne(C0); 1226 std::swap(X, Sel1); 1227 break; 1228 case ICmpInst::Predicate::ICMP_UGE: 1229 // The only way we'd get this predicate if this `icmp` has extra uses, 1230 // but then we won't be able to do this fold. 1231 return nullptr; 1232 default: 1233 return nullptr; // Unknown predicate. 1234 } 1235 1236 // Now that we've canonicalized the ICmp, we know the X we expect; 1237 // the select in other hand should be one-use. 1238 if (!Sel1->hasOneUse()) 1239 return nullptr; 1240 1241 // We now can finish matching the condition of the outermost select: 1242 // it should either be the X itself, or an addition of some constant to X. 1243 Constant *C1; 1244 if (Cmp00 == X) 1245 C1 = ConstantInt::getNullValue(Sel0.getType()); 1246 else if (!match(Cmp00, 1247 m_Add(m_Specific(X), 1248 m_CombineAnd(m_AnyIntegralConstant(), m_Constant(C1))))) 1249 return nullptr; 1250 1251 Value *Cmp1; 1252 ICmpInst::Predicate Pred1; 1253 Constant *C2; 1254 Value *ReplacementLow, *ReplacementHigh; 1255 if (!match(Sel1, m_Select(m_Value(Cmp1), m_Value(ReplacementLow), 1256 m_Value(ReplacementHigh))) || 1257 !match(Cmp1, 1258 m_ICmp(Pred1, m_Specific(X), 1259 m_CombineAnd(m_AnyIntegralConstant(), m_Constant(C2))))) 1260 return nullptr; 1261 1262 if (!Cmp1->hasOneUse() && (Cmp00 == X || !Cmp00->hasOneUse())) 1263 return nullptr; // Not enough one-use instructions for the fold. 1264 // FIXME: this restriction could be relaxed if Cmp1 can be reused as one of 1265 // two comparisons we'll need to build. 1266 1267 // Canonicalize Cmp1 into the form we expect. 1268 // FIXME: we shouldn't care about lanes that are 'undef' in the end? 1269 switch (Pred1) { 1270 case ICmpInst::Predicate::ICMP_SLT: 1271 break; 1272 case ICmpInst::Predicate::ICMP_SLE: 1273 // We'd have to increment C2 by one, and for that it must not have signed 1274 // max element, but then it would have been canonicalized to 'slt' before 1275 // we get here. So we can't do anything useful with 'sle'. 1276 return nullptr; 1277 case ICmpInst::Predicate::ICMP_SGT: 1278 // We want to canonicalize it to 'slt', so we'll need to increment C2, 1279 // which again means it must not have any signed max elements. 1280 if (!match(C2, 1281 m_SpecificInt_ICMP(ICmpInst::Predicate::ICMP_NE, 1282 APInt::getSignedMaxValue( 1283 C2->getType()->getScalarSizeInBits())))) 1284 return nullptr; // Can't do, have signed max element[s]. 1285 C2 = AddOne(C2); 1286 LLVM_FALLTHROUGH; 1287 case ICmpInst::Predicate::ICMP_SGE: 1288 // Also non-canonical, but here we don't need to change C2, 1289 // so we don't have any restrictions on C2, so we can just handle it. 1290 std::swap(ReplacementLow, ReplacementHigh); 1291 break; 1292 default: 1293 return nullptr; // Unknown predicate. 1294 } 1295 1296 // The thresholds of this clamp-like pattern. 1297 auto *ThresholdLowIncl = ConstantExpr::getNeg(C1); 1298 auto *ThresholdHighExcl = ConstantExpr::getSub(C0, C1); 1299 1300 // The fold has a precondition 1: C2 s>= ThresholdLow 1301 auto *Precond1 = ConstantExpr::getICmp(ICmpInst::Predicate::ICMP_SGE, C2, 1302 ThresholdLowIncl); 1303 if (!match(Precond1, m_One())) 1304 return nullptr; 1305 // The fold has a precondition 2: C2 s<= ThresholdHigh 1306 auto *Precond2 = ConstantExpr::getICmp(ICmpInst::Predicate::ICMP_SLE, C2, 1307 ThresholdHighExcl); 1308 if (!match(Precond2, m_One())) 1309 return nullptr; 1310 1311 // All good, finally emit the new pattern. 1312 Value *ShouldReplaceLow = Builder.CreateICmpSLT(X, ThresholdLowIncl); 1313 Value *ShouldReplaceHigh = Builder.CreateICmpSGE(X, ThresholdHighExcl); 1314 Value *MaybeReplacedLow = 1315 Builder.CreateSelect(ShouldReplaceLow, ReplacementLow, X); 1316 Instruction *MaybeReplacedHigh = 1317 SelectInst::Create(ShouldReplaceHigh, ReplacementHigh, MaybeReplacedLow); 1318 1319 return MaybeReplacedHigh; 1320 } 1321 1322 // If we have 1323 // %cmp = icmp [canonical predicate] i32 %x, C0 1324 // %r = select i1 %cmp, i32 %y, i32 C1 1325 // Where C0 != C1 and %x may be different from %y, see if the constant that we 1326 // will have if we flip the strictness of the predicate (i.e. without changing 1327 // the result) is identical to the C1 in select. If it matches we can change 1328 // original comparison to one with swapped predicate, reuse the constant, 1329 // and swap the hands of select. 1330 static Instruction * 1331 tryToReuseConstantFromSelectInComparison(SelectInst &Sel, ICmpInst &Cmp, 1332 InstCombiner &IC) { 1333 ICmpInst::Predicate Pred; 1334 Value *X; 1335 Constant *C0; 1336 if (!match(&Cmp, m_OneUse(m_ICmp( 1337 Pred, m_Value(X), 1338 m_CombineAnd(m_AnyIntegralConstant(), m_Constant(C0)))))) 1339 return nullptr; 1340 1341 // If comparison predicate is non-relational, we won't be able to do anything. 1342 if (ICmpInst::isEquality(Pred)) 1343 return nullptr; 1344 1345 // If comparison predicate is non-canonical, then we certainly won't be able 1346 // to make it canonical; canonicalizeCmpWithConstant() already tried. 1347 if (!isCanonicalPredicate(Pred)) 1348 return nullptr; 1349 1350 // If the [input] type of comparison and select type are different, lets abort 1351 // for now. We could try to compare constants with trunc/[zs]ext though. 1352 if (C0->getType() != Sel.getType()) 1353 return nullptr; 1354 1355 // FIXME: are there any magic icmp predicate+constant pairs we must not touch? 1356 1357 Value *SelVal0, *SelVal1; // We do not care which one is from where. 1358 match(&Sel, m_Select(m_Value(), m_Value(SelVal0), m_Value(SelVal1))); 1359 // At least one of these values we are selecting between must be a constant 1360 // else we'll never succeed. 1361 if (!match(SelVal0, m_AnyIntegralConstant()) && 1362 !match(SelVal1, m_AnyIntegralConstant())) 1363 return nullptr; 1364 1365 // Does this constant C match any of the `select` values? 1366 auto MatchesSelectValue = [SelVal0, SelVal1](Constant *C) { 1367 return C->isElementWiseEqual(SelVal0) || C->isElementWiseEqual(SelVal1); 1368 }; 1369 1370 // If C0 *already* matches true/false value of select, we are done. 1371 if (MatchesSelectValue(C0)) 1372 return nullptr; 1373 1374 // Check the constant we'd have with flipped-strictness predicate. 1375 auto FlippedStrictness = getFlippedStrictnessPredicateAndConstant(Pred, C0); 1376 if (!FlippedStrictness) 1377 return nullptr; 1378 1379 // If said constant doesn't match either, then there is no hope, 1380 if (!MatchesSelectValue(FlippedStrictness->second)) 1381 return nullptr; 1382 1383 // It matched! Lets insert the new comparison just before select. 1384 InstCombiner::BuilderTy::InsertPointGuard Guard(IC.Builder); 1385 IC.Builder.SetInsertPoint(&Sel); 1386 1387 Pred = ICmpInst::getSwappedPredicate(Pred); // Yes, swapped. 1388 Value *NewCmp = IC.Builder.CreateICmp(Pred, X, FlippedStrictness->second, 1389 Cmp.getName() + ".inv"); 1390 IC.replaceOperand(Sel, 0, NewCmp); 1391 Sel.swapValues(); 1392 Sel.swapProfMetadata(); 1393 1394 return &Sel; 1395 } 1396 1397 /// Visit a SelectInst that has an ICmpInst as its first operand. 1398 Instruction *InstCombiner::foldSelectInstWithICmp(SelectInst &SI, 1399 ICmpInst *ICI) { 1400 if (Value *V = foldSelectValueEquivalence(SI, *ICI, SQ)) 1401 return replaceInstUsesWith(SI, V); 1402 1403 if (Instruction *NewSel = canonicalizeMinMaxWithConstant(SI, *ICI, *this)) 1404 return NewSel; 1405 1406 if (Instruction *NewAbs = canonicalizeAbsNabs(SI, *ICI, Builder)) 1407 return NewAbs; 1408 1409 if (Instruction *NewAbs = canonicalizeClampLike(SI, *ICI, Builder)) 1410 return NewAbs; 1411 1412 if (Instruction *NewSel = 1413 tryToReuseConstantFromSelectInComparison(SI, *ICI, *this)) 1414 return NewSel; 1415 1416 bool Changed = adjustMinMax(SI, *ICI); 1417 1418 if (Value *V = foldSelectICmpAnd(SI, ICI, Builder)) 1419 return replaceInstUsesWith(SI, V); 1420 1421 // NOTE: if we wanted to, this is where to detect integer MIN/MAX 1422 Value *TrueVal = SI.getTrueValue(); 1423 Value *FalseVal = SI.getFalseValue(); 1424 ICmpInst::Predicate Pred = ICI->getPredicate(); 1425 Value *CmpLHS = ICI->getOperand(0); 1426 Value *CmpRHS = ICI->getOperand(1); 1427 if (CmpRHS != CmpLHS && isa<Constant>(CmpRHS)) { 1428 if (CmpLHS == TrueVal && Pred == ICmpInst::ICMP_EQ) { 1429 // Transform (X == C) ? X : Y -> (X == C) ? C : Y 1430 SI.setOperand(1, CmpRHS); 1431 Changed = true; 1432 } else if (CmpLHS == FalseVal && Pred == ICmpInst::ICMP_NE) { 1433 // Transform (X != C) ? Y : X -> (X != C) ? Y : C 1434 SI.setOperand(2, CmpRHS); 1435 Changed = true; 1436 } 1437 } 1438 1439 // FIXME: This code is nearly duplicated in InstSimplify. Using/refactoring 1440 // decomposeBitTestICmp() might help. 1441 { 1442 unsigned BitWidth = 1443 DL.getTypeSizeInBits(TrueVal->getType()->getScalarType()); 1444 APInt MinSignedValue = APInt::getSignedMinValue(BitWidth); 1445 Value *X; 1446 const APInt *Y, *C; 1447 bool TrueWhenUnset; 1448 bool IsBitTest = false; 1449 if (ICmpInst::isEquality(Pred) && 1450 match(CmpLHS, m_And(m_Value(X), m_Power2(Y))) && 1451 match(CmpRHS, m_Zero())) { 1452 IsBitTest = true; 1453 TrueWhenUnset = Pred == ICmpInst::ICMP_EQ; 1454 } else if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, m_Zero())) { 1455 X = CmpLHS; 1456 Y = &MinSignedValue; 1457 IsBitTest = true; 1458 TrueWhenUnset = false; 1459 } else if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, m_AllOnes())) { 1460 X = CmpLHS; 1461 Y = &MinSignedValue; 1462 IsBitTest = true; 1463 TrueWhenUnset = true; 1464 } 1465 if (IsBitTest) { 1466 Value *V = nullptr; 1467 // (X & Y) == 0 ? X : X ^ Y --> X & ~Y 1468 if (TrueWhenUnset && TrueVal == X && 1469 match(FalseVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C) 1470 V = Builder.CreateAnd(X, ~(*Y)); 1471 // (X & Y) != 0 ? X ^ Y : X --> X & ~Y 1472 else if (!TrueWhenUnset && FalseVal == X && 1473 match(TrueVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C) 1474 V = Builder.CreateAnd(X, ~(*Y)); 1475 // (X & Y) == 0 ? X ^ Y : X --> X | Y 1476 else if (TrueWhenUnset && FalseVal == X && 1477 match(TrueVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C) 1478 V = Builder.CreateOr(X, *Y); 1479 // (X & Y) != 0 ? X : X ^ Y --> X | Y 1480 else if (!TrueWhenUnset && TrueVal == X && 1481 match(FalseVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C) 1482 V = Builder.CreateOr(X, *Y); 1483 1484 if (V) 1485 return replaceInstUsesWith(SI, V); 1486 } 1487 } 1488 1489 if (Instruction *V = 1490 foldSelectICmpAndAnd(SI.getType(), ICI, TrueVal, FalseVal, Builder)) 1491 return V; 1492 1493 if (Instruction *V = foldSelectCtlzToCttz(ICI, TrueVal, FalseVal, Builder)) 1494 return V; 1495 1496 if (Value *V = foldSelectICmpAndOr(ICI, TrueVal, FalseVal, Builder)) 1497 return replaceInstUsesWith(SI, V); 1498 1499 if (Value *V = foldSelectICmpLshrAshr(ICI, TrueVal, FalseVal, Builder)) 1500 return replaceInstUsesWith(SI, V); 1501 1502 if (Value *V = foldSelectCttzCtlz(ICI, TrueVal, FalseVal, Builder)) 1503 return replaceInstUsesWith(SI, V); 1504 1505 if (Value *V = canonicalizeSaturatedSubtract(ICI, TrueVal, FalseVal, Builder)) 1506 return replaceInstUsesWith(SI, V); 1507 1508 if (Value *V = canonicalizeSaturatedAdd(ICI, TrueVal, FalseVal, Builder)) 1509 return replaceInstUsesWith(SI, V); 1510 1511 return Changed ? &SI : nullptr; 1512 } 1513 1514 /// SI is a select whose condition is a PHI node (but the two may be in 1515 /// different blocks). See if the true/false values (V) are live in all of the 1516 /// predecessor blocks of the PHI. For example, cases like this can't be mapped: 1517 /// 1518 /// X = phi [ C1, BB1], [C2, BB2] 1519 /// Y = add 1520 /// Z = select X, Y, 0 1521 /// 1522 /// because Y is not live in BB1/BB2. 1523 static bool canSelectOperandBeMappingIntoPredBlock(const Value *V, 1524 const SelectInst &SI) { 1525 // If the value is a non-instruction value like a constant or argument, it 1526 // can always be mapped. 1527 const Instruction *I = dyn_cast<Instruction>(V); 1528 if (!I) return true; 1529 1530 // If V is a PHI node defined in the same block as the condition PHI, we can 1531 // map the arguments. 1532 const PHINode *CondPHI = cast<PHINode>(SI.getCondition()); 1533 1534 if (const PHINode *VP = dyn_cast<PHINode>(I)) 1535 if (VP->getParent() == CondPHI->getParent()) 1536 return true; 1537 1538 // Otherwise, if the PHI and select are defined in the same block and if V is 1539 // defined in a different block, then we can transform it. 1540 if (SI.getParent() == CondPHI->getParent() && 1541 I->getParent() != CondPHI->getParent()) 1542 return true; 1543 1544 // Otherwise we have a 'hard' case and we can't tell without doing more 1545 // detailed dominator based analysis, punt. 1546 return false; 1547 } 1548 1549 /// We have an SPF (e.g. a min or max) of an SPF of the form: 1550 /// SPF2(SPF1(A, B), C) 1551 Instruction *InstCombiner::foldSPFofSPF(Instruction *Inner, 1552 SelectPatternFlavor SPF1, 1553 Value *A, Value *B, 1554 Instruction &Outer, 1555 SelectPatternFlavor SPF2, Value *C) { 1556 if (Outer.getType() != Inner->getType()) 1557 return nullptr; 1558 1559 if (C == A || C == B) { 1560 // MAX(MAX(A, B), B) -> MAX(A, B) 1561 // MIN(MIN(a, b), a) -> MIN(a, b) 1562 // TODO: This could be done in instsimplify. 1563 if (SPF1 == SPF2 && SelectPatternResult::isMinOrMax(SPF1)) 1564 return replaceInstUsesWith(Outer, Inner); 1565 1566 // MAX(MIN(a, b), a) -> a 1567 // MIN(MAX(a, b), a) -> a 1568 // TODO: This could be done in instsimplify. 1569 if ((SPF1 == SPF_SMIN && SPF2 == SPF_SMAX) || 1570 (SPF1 == SPF_SMAX && SPF2 == SPF_SMIN) || 1571 (SPF1 == SPF_UMIN && SPF2 == SPF_UMAX) || 1572 (SPF1 == SPF_UMAX && SPF2 == SPF_UMIN)) 1573 return replaceInstUsesWith(Outer, C); 1574 } 1575 1576 if (SPF1 == SPF2) { 1577 const APInt *CB, *CC; 1578 if (match(B, m_APInt(CB)) && match(C, m_APInt(CC))) { 1579 // MIN(MIN(A, 23), 97) -> MIN(A, 23) 1580 // MAX(MAX(A, 97), 23) -> MAX(A, 97) 1581 // TODO: This could be done in instsimplify. 1582 if ((SPF1 == SPF_UMIN && CB->ule(*CC)) || 1583 (SPF1 == SPF_SMIN && CB->sle(*CC)) || 1584 (SPF1 == SPF_UMAX && CB->uge(*CC)) || 1585 (SPF1 == SPF_SMAX && CB->sge(*CC))) 1586 return replaceInstUsesWith(Outer, Inner); 1587 1588 // MIN(MIN(A, 97), 23) -> MIN(A, 23) 1589 // MAX(MAX(A, 23), 97) -> MAX(A, 97) 1590 if ((SPF1 == SPF_UMIN && CB->ugt(*CC)) || 1591 (SPF1 == SPF_SMIN && CB->sgt(*CC)) || 1592 (SPF1 == SPF_UMAX && CB->ult(*CC)) || 1593 (SPF1 == SPF_SMAX && CB->slt(*CC))) { 1594 Outer.replaceUsesOfWith(Inner, A); 1595 return &Outer; 1596 } 1597 } 1598 } 1599 1600 // max(max(A, B), min(A, B)) --> max(A, B) 1601 // min(min(A, B), max(A, B)) --> min(A, B) 1602 // TODO: This could be done in instsimplify. 1603 if (SPF1 == SPF2 && 1604 ((SPF1 == SPF_UMIN && match(C, m_c_UMax(m_Specific(A), m_Specific(B)))) || 1605 (SPF1 == SPF_SMIN && match(C, m_c_SMax(m_Specific(A), m_Specific(B)))) || 1606 (SPF1 == SPF_UMAX && match(C, m_c_UMin(m_Specific(A), m_Specific(B)))) || 1607 (SPF1 == SPF_SMAX && match(C, m_c_SMin(m_Specific(A), m_Specific(B)))))) 1608 return replaceInstUsesWith(Outer, Inner); 1609 1610 // ABS(ABS(X)) -> ABS(X) 1611 // NABS(NABS(X)) -> NABS(X) 1612 // TODO: This could be done in instsimplify. 1613 if (SPF1 == SPF2 && (SPF1 == SPF_ABS || SPF1 == SPF_NABS)) { 1614 return replaceInstUsesWith(Outer, Inner); 1615 } 1616 1617 // ABS(NABS(X)) -> ABS(X) 1618 // NABS(ABS(X)) -> NABS(X) 1619 if ((SPF1 == SPF_ABS && SPF2 == SPF_NABS) || 1620 (SPF1 == SPF_NABS && SPF2 == SPF_ABS)) { 1621 SelectInst *SI = cast<SelectInst>(Inner); 1622 Value *NewSI = 1623 Builder.CreateSelect(SI->getCondition(), SI->getFalseValue(), 1624 SI->getTrueValue(), SI->getName(), SI); 1625 return replaceInstUsesWith(Outer, NewSI); 1626 } 1627 1628 auto IsFreeOrProfitableToInvert = 1629 [&](Value *V, Value *&NotV, bool &ElidesXor) { 1630 if (match(V, m_Not(m_Value(NotV)))) { 1631 // If V has at most 2 uses then we can get rid of the xor operation 1632 // entirely. 1633 ElidesXor |= !V->hasNUsesOrMore(3); 1634 return true; 1635 } 1636 1637 if (isFreeToInvert(V, !V->hasNUsesOrMore(3))) { 1638 NotV = nullptr; 1639 return true; 1640 } 1641 1642 return false; 1643 }; 1644 1645 Value *NotA, *NotB, *NotC; 1646 bool ElidesXor = false; 1647 1648 // MIN(MIN(~A, ~B), ~C) == ~MAX(MAX(A, B), C) 1649 // MIN(MAX(~A, ~B), ~C) == ~MAX(MIN(A, B), C) 1650 // MAX(MIN(~A, ~B), ~C) == ~MIN(MAX(A, B), C) 1651 // MAX(MAX(~A, ~B), ~C) == ~MIN(MIN(A, B), C) 1652 // 1653 // This transform is performance neutral if we can elide at least one xor from 1654 // the set of three operands, since we'll be tacking on an xor at the very 1655 // end. 1656 if (SelectPatternResult::isMinOrMax(SPF1) && 1657 SelectPatternResult::isMinOrMax(SPF2) && 1658 IsFreeOrProfitableToInvert(A, NotA, ElidesXor) && 1659 IsFreeOrProfitableToInvert(B, NotB, ElidesXor) && 1660 IsFreeOrProfitableToInvert(C, NotC, ElidesXor) && ElidesXor) { 1661 if (!NotA) 1662 NotA = Builder.CreateNot(A); 1663 if (!NotB) 1664 NotB = Builder.CreateNot(B); 1665 if (!NotC) 1666 NotC = Builder.CreateNot(C); 1667 1668 Value *NewInner = createMinMax(Builder, getInverseMinMaxFlavor(SPF1), NotA, 1669 NotB); 1670 Value *NewOuter = Builder.CreateNot( 1671 createMinMax(Builder, getInverseMinMaxFlavor(SPF2), NewInner, NotC)); 1672 return replaceInstUsesWith(Outer, NewOuter); 1673 } 1674 1675 return nullptr; 1676 } 1677 1678 /// Turn select C, (X + Y), (X - Y) --> (X + (select C, Y, (-Y))). 1679 /// This is even legal for FP. 1680 static Instruction *foldAddSubSelect(SelectInst &SI, 1681 InstCombiner::BuilderTy &Builder) { 1682 Value *CondVal = SI.getCondition(); 1683 Value *TrueVal = SI.getTrueValue(); 1684 Value *FalseVal = SI.getFalseValue(); 1685 auto *TI = dyn_cast<Instruction>(TrueVal); 1686 auto *FI = dyn_cast<Instruction>(FalseVal); 1687 if (!TI || !FI || !TI->hasOneUse() || !FI->hasOneUse()) 1688 return nullptr; 1689 1690 Instruction *AddOp = nullptr, *SubOp = nullptr; 1691 if ((TI->getOpcode() == Instruction::Sub && 1692 FI->getOpcode() == Instruction::Add) || 1693 (TI->getOpcode() == Instruction::FSub && 1694 FI->getOpcode() == Instruction::FAdd)) { 1695 AddOp = FI; 1696 SubOp = TI; 1697 } else if ((FI->getOpcode() == Instruction::Sub && 1698 TI->getOpcode() == Instruction::Add) || 1699 (FI->getOpcode() == Instruction::FSub && 1700 TI->getOpcode() == Instruction::FAdd)) { 1701 AddOp = TI; 1702 SubOp = FI; 1703 } 1704 1705 if (AddOp) { 1706 Value *OtherAddOp = nullptr; 1707 if (SubOp->getOperand(0) == AddOp->getOperand(0)) { 1708 OtherAddOp = AddOp->getOperand(1); 1709 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) { 1710 OtherAddOp = AddOp->getOperand(0); 1711 } 1712 1713 if (OtherAddOp) { 1714 // So at this point we know we have (Y -> OtherAddOp): 1715 // select C, (add X, Y), (sub X, Z) 1716 Value *NegVal; // Compute -Z 1717 if (SI.getType()->isFPOrFPVectorTy()) { 1718 NegVal = Builder.CreateFNeg(SubOp->getOperand(1)); 1719 if (Instruction *NegInst = dyn_cast<Instruction>(NegVal)) { 1720 FastMathFlags Flags = AddOp->getFastMathFlags(); 1721 Flags &= SubOp->getFastMathFlags(); 1722 NegInst->setFastMathFlags(Flags); 1723 } 1724 } else { 1725 NegVal = Builder.CreateNeg(SubOp->getOperand(1)); 1726 } 1727 1728 Value *NewTrueOp = OtherAddOp; 1729 Value *NewFalseOp = NegVal; 1730 if (AddOp != TI) 1731 std::swap(NewTrueOp, NewFalseOp); 1732 Value *NewSel = Builder.CreateSelect(CondVal, NewTrueOp, NewFalseOp, 1733 SI.getName() + ".p", &SI); 1734 1735 if (SI.getType()->isFPOrFPVectorTy()) { 1736 Instruction *RI = 1737 BinaryOperator::CreateFAdd(SubOp->getOperand(0), NewSel); 1738 1739 FastMathFlags Flags = AddOp->getFastMathFlags(); 1740 Flags &= SubOp->getFastMathFlags(); 1741 RI->setFastMathFlags(Flags); 1742 return RI; 1743 } else 1744 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel); 1745 } 1746 } 1747 return nullptr; 1748 } 1749 1750 /// Turn X + Y overflows ? -1 : X + Y -> uadd_sat X, Y 1751 /// And X - Y overflows ? 0 : X - Y -> usub_sat X, Y 1752 /// Along with a number of patterns similar to: 1753 /// X + Y overflows ? (X < 0 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y 1754 /// X - Y overflows ? (X > 0 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y 1755 static Instruction * 1756 foldOverflowingAddSubSelect(SelectInst &SI, InstCombiner::BuilderTy &Builder) { 1757 Value *CondVal = SI.getCondition(); 1758 Value *TrueVal = SI.getTrueValue(); 1759 Value *FalseVal = SI.getFalseValue(); 1760 1761 WithOverflowInst *II; 1762 if (!match(CondVal, m_ExtractValue<1>(m_WithOverflowInst(II))) || 1763 !match(FalseVal, m_ExtractValue<0>(m_Specific(II)))) 1764 return nullptr; 1765 1766 Value *X = II->getLHS(); 1767 Value *Y = II->getRHS(); 1768 1769 auto IsSignedSaturateLimit = [&](Value *Limit, bool IsAdd) { 1770 Type *Ty = Limit->getType(); 1771 1772 ICmpInst::Predicate Pred; 1773 Value *TrueVal, *FalseVal, *Op; 1774 const APInt *C; 1775 if (!match(Limit, m_Select(m_ICmp(Pred, m_Value(Op), m_APInt(C)), 1776 m_Value(TrueVal), m_Value(FalseVal)))) 1777 return false; 1778 1779 auto IsZeroOrOne = [](const APInt &C) { 1780 return C.isNullValue() || C.isOneValue(); 1781 }; 1782 auto IsMinMax = [&](Value *Min, Value *Max) { 1783 APInt MinVal = APInt::getSignedMinValue(Ty->getScalarSizeInBits()); 1784 APInt MaxVal = APInt::getSignedMaxValue(Ty->getScalarSizeInBits()); 1785 return match(Min, m_SpecificInt(MinVal)) && 1786 match(Max, m_SpecificInt(MaxVal)); 1787 }; 1788 1789 if (Op != X && Op != Y) 1790 return false; 1791 1792 if (IsAdd) { 1793 // X + Y overflows ? (X <s 0 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y 1794 // X + Y overflows ? (X <s 1 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y 1795 // X + Y overflows ? (Y <s 0 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y 1796 // X + Y overflows ? (Y <s 1 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y 1797 if (Pred == ICmpInst::ICMP_SLT && IsZeroOrOne(*C) && 1798 IsMinMax(TrueVal, FalseVal)) 1799 return true; 1800 // X + Y overflows ? (X >s 0 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y 1801 // X + Y overflows ? (X >s -1 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y 1802 // X + Y overflows ? (Y >s 0 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y 1803 // X + Y overflows ? (Y >s -1 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y 1804 if (Pred == ICmpInst::ICMP_SGT && IsZeroOrOne(*C + 1) && 1805 IsMinMax(FalseVal, TrueVal)) 1806 return true; 1807 } else { 1808 // X - Y overflows ? (X <s 0 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y 1809 // X - Y overflows ? (X <s -1 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y 1810 if (Op == X && Pred == ICmpInst::ICMP_SLT && IsZeroOrOne(*C + 1) && 1811 IsMinMax(TrueVal, FalseVal)) 1812 return true; 1813 // X - Y overflows ? (X >s -1 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y 1814 // X - Y overflows ? (X >s -2 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y 1815 if (Op == X && Pred == ICmpInst::ICMP_SGT && IsZeroOrOne(*C + 2) && 1816 IsMinMax(FalseVal, TrueVal)) 1817 return true; 1818 // X - Y overflows ? (Y <s 0 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y 1819 // X - Y overflows ? (Y <s 1 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y 1820 if (Op == Y && Pred == ICmpInst::ICMP_SLT && IsZeroOrOne(*C) && 1821 IsMinMax(FalseVal, TrueVal)) 1822 return true; 1823 // X - Y overflows ? (Y >s 0 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y 1824 // X - Y overflows ? (Y >s -1 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y 1825 if (Op == Y && Pred == ICmpInst::ICMP_SGT && IsZeroOrOne(*C + 1) && 1826 IsMinMax(TrueVal, FalseVal)) 1827 return true; 1828 } 1829 1830 return false; 1831 }; 1832 1833 Intrinsic::ID NewIntrinsicID; 1834 if (II->getIntrinsicID() == Intrinsic::uadd_with_overflow && 1835 match(TrueVal, m_AllOnes())) 1836 // X + Y overflows ? -1 : X + Y -> uadd_sat X, Y 1837 NewIntrinsicID = Intrinsic::uadd_sat; 1838 else if (II->getIntrinsicID() == Intrinsic::usub_with_overflow && 1839 match(TrueVal, m_Zero())) 1840 // X - Y overflows ? 0 : X - Y -> usub_sat X, Y 1841 NewIntrinsicID = Intrinsic::usub_sat; 1842 else if (II->getIntrinsicID() == Intrinsic::sadd_with_overflow && 1843 IsSignedSaturateLimit(TrueVal, /*IsAdd=*/true)) 1844 // X + Y overflows ? (X <s 0 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y 1845 // X + Y overflows ? (X <s 1 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y 1846 // X + Y overflows ? (X >s 0 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y 1847 // X + Y overflows ? (X >s -1 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y 1848 // X + Y overflows ? (Y <s 0 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y 1849 // X + Y overflows ? (Y <s 1 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y 1850 // X + Y overflows ? (Y >s 0 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y 1851 // X + Y overflows ? (Y >s -1 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y 1852 NewIntrinsicID = Intrinsic::sadd_sat; 1853 else if (II->getIntrinsicID() == Intrinsic::ssub_with_overflow && 1854 IsSignedSaturateLimit(TrueVal, /*IsAdd=*/false)) 1855 // X - Y overflows ? (X <s 0 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y 1856 // X - Y overflows ? (X <s -1 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y 1857 // X - Y overflows ? (X >s -1 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y 1858 // X - Y overflows ? (X >s -2 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y 1859 // X - Y overflows ? (Y <s 0 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y 1860 // X - Y overflows ? (Y <s 1 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y 1861 // X - Y overflows ? (Y >s 0 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y 1862 // X - Y overflows ? (Y >s -1 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y 1863 NewIntrinsicID = Intrinsic::ssub_sat; 1864 else 1865 return nullptr; 1866 1867 Function *F = 1868 Intrinsic::getDeclaration(SI.getModule(), NewIntrinsicID, SI.getType()); 1869 return CallInst::Create(F, {X, Y}); 1870 } 1871 1872 Instruction *InstCombiner::foldSelectExtConst(SelectInst &Sel) { 1873 Constant *C; 1874 if (!match(Sel.getTrueValue(), m_Constant(C)) && 1875 !match(Sel.getFalseValue(), m_Constant(C))) 1876 return nullptr; 1877 1878 Instruction *ExtInst; 1879 if (!match(Sel.getTrueValue(), m_Instruction(ExtInst)) && 1880 !match(Sel.getFalseValue(), m_Instruction(ExtInst))) 1881 return nullptr; 1882 1883 auto ExtOpcode = ExtInst->getOpcode(); 1884 if (ExtOpcode != Instruction::ZExt && ExtOpcode != Instruction::SExt) 1885 return nullptr; 1886 1887 // If we are extending from a boolean type or if we can create a select that 1888 // has the same size operands as its condition, try to narrow the select. 1889 Value *X = ExtInst->getOperand(0); 1890 Type *SmallType = X->getType(); 1891 Value *Cond = Sel.getCondition(); 1892 auto *Cmp = dyn_cast<CmpInst>(Cond); 1893 if (!SmallType->isIntOrIntVectorTy(1) && 1894 (!Cmp || Cmp->getOperand(0)->getType() != SmallType)) 1895 return nullptr; 1896 1897 // If the constant is the same after truncation to the smaller type and 1898 // extension to the original type, we can narrow the select. 1899 Type *SelType = Sel.getType(); 1900 Constant *TruncC = ConstantExpr::getTrunc(C, SmallType); 1901 Constant *ExtC = ConstantExpr::getCast(ExtOpcode, TruncC, SelType); 1902 if (ExtC == C) { 1903 Value *TruncCVal = cast<Value>(TruncC); 1904 if (ExtInst == Sel.getFalseValue()) 1905 std::swap(X, TruncCVal); 1906 1907 // select Cond, (ext X), C --> ext(select Cond, X, C') 1908 // select Cond, C, (ext X) --> ext(select Cond, C', X) 1909 Value *NewSel = Builder.CreateSelect(Cond, X, TruncCVal, "narrow", &Sel); 1910 return CastInst::Create(Instruction::CastOps(ExtOpcode), NewSel, SelType); 1911 } 1912 1913 // If one arm of the select is the extend of the condition, replace that arm 1914 // with the extension of the appropriate known bool value. 1915 if (Cond == X) { 1916 if (ExtInst == Sel.getTrueValue()) { 1917 // select X, (sext X), C --> select X, -1, C 1918 // select X, (zext X), C --> select X, 1, C 1919 Constant *One = ConstantInt::getTrue(SmallType); 1920 Constant *AllOnesOrOne = ConstantExpr::getCast(ExtOpcode, One, SelType); 1921 return SelectInst::Create(Cond, AllOnesOrOne, C, "", nullptr, &Sel); 1922 } else { 1923 // select X, C, (sext X) --> select X, C, 0 1924 // select X, C, (zext X) --> select X, C, 0 1925 Constant *Zero = ConstantInt::getNullValue(SelType); 1926 return SelectInst::Create(Cond, C, Zero, "", nullptr, &Sel); 1927 } 1928 } 1929 1930 return nullptr; 1931 } 1932 1933 /// Try to transform a vector select with a constant condition vector into a 1934 /// shuffle for easier combining with other shuffles and insert/extract. 1935 static Instruction *canonicalizeSelectToShuffle(SelectInst &SI) { 1936 Value *CondVal = SI.getCondition(); 1937 Constant *CondC; 1938 if (!CondVal->getType()->isVectorTy() || !match(CondVal, m_Constant(CondC))) 1939 return nullptr; 1940 1941 unsigned NumElts = CondVal->getType()->getVectorNumElements(); 1942 SmallVector<Constant *, 16> Mask; 1943 Mask.reserve(NumElts); 1944 Type *Int32Ty = Type::getInt32Ty(CondVal->getContext()); 1945 for (unsigned i = 0; i != NumElts; ++i) { 1946 Constant *Elt = CondC->getAggregateElement(i); 1947 if (!Elt) 1948 return nullptr; 1949 1950 if (Elt->isOneValue()) { 1951 // If the select condition element is true, choose from the 1st vector. 1952 Mask.push_back(ConstantInt::get(Int32Ty, i)); 1953 } else if (Elt->isNullValue()) { 1954 // If the select condition element is false, choose from the 2nd vector. 1955 Mask.push_back(ConstantInt::get(Int32Ty, i + NumElts)); 1956 } else if (isa<UndefValue>(Elt)) { 1957 // Undef in a select condition (choose one of the operands) does not mean 1958 // the same thing as undef in a shuffle mask (any value is acceptable), so 1959 // give up. 1960 return nullptr; 1961 } else { 1962 // Bail out on a constant expression. 1963 return nullptr; 1964 } 1965 } 1966 1967 return new ShuffleVectorInst(SI.getTrueValue(), SI.getFalseValue(), 1968 ConstantVector::get(Mask)); 1969 } 1970 1971 /// If we have a select of vectors with a scalar condition, try to convert that 1972 /// to a vector select by splatting the condition. A splat may get folded with 1973 /// other operations in IR and having all operands of a select be vector types 1974 /// is likely better for vector codegen. 1975 static Instruction *canonicalizeScalarSelectOfVecs( 1976 SelectInst &Sel, InstCombiner &IC) { 1977 Type *Ty = Sel.getType(); 1978 if (!Ty->isVectorTy()) 1979 return nullptr; 1980 1981 // We can replace a single-use extract with constant index. 1982 Value *Cond = Sel.getCondition(); 1983 if (!match(Cond, m_OneUse(m_ExtractElement(m_Value(), m_ConstantInt())))) 1984 return nullptr; 1985 1986 // select (extelt V, Index), T, F --> select (splat V, Index), T, F 1987 // Splatting the extracted condition reduces code (we could directly create a 1988 // splat shuffle of the source vector to eliminate the intermediate step). 1989 unsigned NumElts = Ty->getVectorNumElements(); 1990 return IC.replaceOperand(Sel, 0, IC.Builder.CreateVectorSplat(NumElts, Cond)); 1991 } 1992 1993 /// Reuse bitcasted operands between a compare and select: 1994 /// select (cmp (bitcast C), (bitcast D)), (bitcast' C), (bitcast' D) --> 1995 /// bitcast (select (cmp (bitcast C), (bitcast D)), (bitcast C), (bitcast D)) 1996 static Instruction *foldSelectCmpBitcasts(SelectInst &Sel, 1997 InstCombiner::BuilderTy &Builder) { 1998 Value *Cond = Sel.getCondition(); 1999 Value *TVal = Sel.getTrueValue(); 2000 Value *FVal = Sel.getFalseValue(); 2001 2002 CmpInst::Predicate Pred; 2003 Value *A, *B; 2004 if (!match(Cond, m_Cmp(Pred, m_Value(A), m_Value(B)))) 2005 return nullptr; 2006 2007 // The select condition is a compare instruction. If the select's true/false 2008 // values are already the same as the compare operands, there's nothing to do. 2009 if (TVal == A || TVal == B || FVal == A || FVal == B) 2010 return nullptr; 2011 2012 Value *C, *D; 2013 if (!match(A, m_BitCast(m_Value(C))) || !match(B, m_BitCast(m_Value(D)))) 2014 return nullptr; 2015 2016 // select (cmp (bitcast C), (bitcast D)), (bitcast TSrc), (bitcast FSrc) 2017 Value *TSrc, *FSrc; 2018 if (!match(TVal, m_BitCast(m_Value(TSrc))) || 2019 !match(FVal, m_BitCast(m_Value(FSrc)))) 2020 return nullptr; 2021 2022 // If the select true/false values are *different bitcasts* of the same source 2023 // operands, make the select operands the same as the compare operands and 2024 // cast the result. This is the canonical select form for min/max. 2025 Value *NewSel; 2026 if (TSrc == C && FSrc == D) { 2027 // select (cmp (bitcast C), (bitcast D)), (bitcast' C), (bitcast' D) --> 2028 // bitcast (select (cmp A, B), A, B) 2029 NewSel = Builder.CreateSelect(Cond, A, B, "", &Sel); 2030 } else if (TSrc == D && FSrc == C) { 2031 // select (cmp (bitcast C), (bitcast D)), (bitcast' D), (bitcast' C) --> 2032 // bitcast (select (cmp A, B), B, A) 2033 NewSel = Builder.CreateSelect(Cond, B, A, "", &Sel); 2034 } else { 2035 return nullptr; 2036 } 2037 return CastInst::CreateBitOrPointerCast(NewSel, Sel.getType()); 2038 } 2039 2040 /// Try to eliminate select instructions that test the returned flag of cmpxchg 2041 /// instructions. 2042 /// 2043 /// If a select instruction tests the returned flag of a cmpxchg instruction and 2044 /// selects between the returned value of the cmpxchg instruction its compare 2045 /// operand, the result of the select will always be equal to its false value. 2046 /// For example: 2047 /// 2048 /// %0 = cmpxchg i64* %ptr, i64 %compare, i64 %new_value seq_cst seq_cst 2049 /// %1 = extractvalue { i64, i1 } %0, 1 2050 /// %2 = extractvalue { i64, i1 } %0, 0 2051 /// %3 = select i1 %1, i64 %compare, i64 %2 2052 /// ret i64 %3 2053 /// 2054 /// The returned value of the cmpxchg instruction (%2) is the original value 2055 /// located at %ptr prior to any update. If the cmpxchg operation succeeds, %2 2056 /// must have been equal to %compare. Thus, the result of the select is always 2057 /// equal to %2, and the code can be simplified to: 2058 /// 2059 /// %0 = cmpxchg i64* %ptr, i64 %compare, i64 %new_value seq_cst seq_cst 2060 /// %1 = extractvalue { i64, i1 } %0, 0 2061 /// ret i64 %1 2062 /// 2063 static Instruction *foldSelectCmpXchg(SelectInst &SI) { 2064 // A helper that determines if V is an extractvalue instruction whose 2065 // aggregate operand is a cmpxchg instruction and whose single index is equal 2066 // to I. If such conditions are true, the helper returns the cmpxchg 2067 // instruction; otherwise, a nullptr is returned. 2068 auto isExtractFromCmpXchg = [](Value *V, unsigned I) -> AtomicCmpXchgInst * { 2069 auto *Extract = dyn_cast<ExtractValueInst>(V); 2070 if (!Extract) 2071 return nullptr; 2072 if (Extract->getIndices()[0] != I) 2073 return nullptr; 2074 return dyn_cast<AtomicCmpXchgInst>(Extract->getAggregateOperand()); 2075 }; 2076 2077 // If the select has a single user, and this user is a select instruction that 2078 // we can simplify, skip the cmpxchg simplification for now. 2079 if (SI.hasOneUse()) 2080 if (auto *Select = dyn_cast<SelectInst>(SI.user_back())) 2081 if (Select->getCondition() == SI.getCondition()) 2082 if (Select->getFalseValue() == SI.getTrueValue() || 2083 Select->getTrueValue() == SI.getFalseValue()) 2084 return nullptr; 2085 2086 // Ensure the select condition is the returned flag of a cmpxchg instruction. 2087 auto *CmpXchg = isExtractFromCmpXchg(SI.getCondition(), 1); 2088 if (!CmpXchg) 2089 return nullptr; 2090 2091 // Check the true value case: The true value of the select is the returned 2092 // value of the same cmpxchg used by the condition, and the false value is the 2093 // cmpxchg instruction's compare operand. 2094 if (auto *X = isExtractFromCmpXchg(SI.getTrueValue(), 0)) 2095 if (X == CmpXchg && X->getCompareOperand() == SI.getFalseValue()) { 2096 SI.setTrueValue(SI.getFalseValue()); 2097 return &SI; 2098 } 2099 2100 // Check the false value case: The false value of the select is the returned 2101 // value of the same cmpxchg used by the condition, and the true value is the 2102 // cmpxchg instruction's compare operand. 2103 if (auto *X = isExtractFromCmpXchg(SI.getFalseValue(), 0)) 2104 if (X == CmpXchg && X->getCompareOperand() == SI.getTrueValue()) { 2105 SI.setTrueValue(SI.getFalseValue()); 2106 return &SI; 2107 } 2108 2109 return nullptr; 2110 } 2111 2112 static Instruction *moveAddAfterMinMax(SelectPatternFlavor SPF, Value *X, 2113 Value *Y, 2114 InstCombiner::BuilderTy &Builder) { 2115 assert(SelectPatternResult::isMinOrMax(SPF) && "Expected min/max pattern"); 2116 bool IsUnsigned = SPF == SelectPatternFlavor::SPF_UMIN || 2117 SPF == SelectPatternFlavor::SPF_UMAX; 2118 // TODO: If InstSimplify could fold all cases where C2 <= C1, we could change 2119 // the constant value check to an assert. 2120 Value *A; 2121 const APInt *C1, *C2; 2122 if (IsUnsigned && match(X, m_NUWAdd(m_Value(A), m_APInt(C1))) && 2123 match(Y, m_APInt(C2)) && C2->uge(*C1) && X->hasNUses(2)) { 2124 // umin (add nuw A, C1), C2 --> add nuw (umin A, C2 - C1), C1 2125 // umax (add nuw A, C1), C2 --> add nuw (umax A, C2 - C1), C1 2126 Value *NewMinMax = createMinMax(Builder, SPF, A, 2127 ConstantInt::get(X->getType(), *C2 - *C1)); 2128 return BinaryOperator::CreateNUW(BinaryOperator::Add, NewMinMax, 2129 ConstantInt::get(X->getType(), *C1)); 2130 } 2131 2132 if (!IsUnsigned && match(X, m_NSWAdd(m_Value(A), m_APInt(C1))) && 2133 match(Y, m_APInt(C2)) && X->hasNUses(2)) { 2134 bool Overflow; 2135 APInt Diff = C2->ssub_ov(*C1, Overflow); 2136 if (!Overflow) { 2137 // smin (add nsw A, C1), C2 --> add nsw (smin A, C2 - C1), C1 2138 // smax (add nsw A, C1), C2 --> add nsw (smax A, C2 - C1), C1 2139 Value *NewMinMax = createMinMax(Builder, SPF, A, 2140 ConstantInt::get(X->getType(), Diff)); 2141 return BinaryOperator::CreateNSW(BinaryOperator::Add, NewMinMax, 2142 ConstantInt::get(X->getType(), *C1)); 2143 } 2144 } 2145 2146 return nullptr; 2147 } 2148 2149 /// Match a sadd_sat or ssub_sat which is using min/max to clamp the value. 2150 Instruction *InstCombiner::matchSAddSubSat(SelectInst &MinMax1) { 2151 Type *Ty = MinMax1.getType(); 2152 2153 // We are looking for a tree of: 2154 // max(INT_MIN, min(INT_MAX, add(sext(A), sext(B)))) 2155 // Where the min and max could be reversed 2156 Instruction *MinMax2; 2157 BinaryOperator *AddSub; 2158 const APInt *MinValue, *MaxValue; 2159 if (match(&MinMax1, m_SMin(m_Instruction(MinMax2), m_APInt(MaxValue)))) { 2160 if (!match(MinMax2, m_SMax(m_BinOp(AddSub), m_APInt(MinValue)))) 2161 return nullptr; 2162 } else if (match(&MinMax1, 2163 m_SMax(m_Instruction(MinMax2), m_APInt(MinValue)))) { 2164 if (!match(MinMax2, m_SMin(m_BinOp(AddSub), m_APInt(MaxValue)))) 2165 return nullptr; 2166 } else 2167 return nullptr; 2168 2169 // Check that the constants clamp a saturate, and that the new type would be 2170 // sensible to convert to. 2171 if (!(*MaxValue + 1).isPowerOf2() || -*MinValue != *MaxValue + 1) 2172 return nullptr; 2173 // In what bitwidth can this be treated as saturating arithmetics? 2174 unsigned NewBitWidth = (*MaxValue + 1).logBase2() + 1; 2175 // FIXME: This isn't quite right for vectors, but using the scalar type is a 2176 // good first approximation for what should be done there. 2177 if (!shouldChangeType(Ty->getScalarType()->getIntegerBitWidth(), NewBitWidth)) 2178 return nullptr; 2179 2180 // Also make sure that the number of uses is as expected. The "3"s are for the 2181 // the two items of min/max (the compare and the select). 2182 if (MinMax2->hasNUsesOrMore(3) || AddSub->hasNUsesOrMore(3)) 2183 return nullptr; 2184 2185 // Create the new type (which can be a vector type) 2186 Type *NewTy = Ty->getWithNewBitWidth(NewBitWidth); 2187 // Match the two extends from the add/sub 2188 Value *A, *B; 2189 if(!match(AddSub, m_BinOp(m_SExt(m_Value(A)), m_SExt(m_Value(B))))) 2190 return nullptr; 2191 // And check the incoming values are of a type smaller than or equal to the 2192 // size of the saturation. Otherwise the higher bits can cause different 2193 // results. 2194 if (A->getType()->getScalarSizeInBits() > NewBitWidth || 2195 B->getType()->getScalarSizeInBits() > NewBitWidth) 2196 return nullptr; 2197 2198 Intrinsic::ID IntrinsicID; 2199 if (AddSub->getOpcode() == Instruction::Add) 2200 IntrinsicID = Intrinsic::sadd_sat; 2201 else if (AddSub->getOpcode() == Instruction::Sub) 2202 IntrinsicID = Intrinsic::ssub_sat; 2203 else 2204 return nullptr; 2205 2206 // Finally create and return the sat intrinsic, truncated to the new type 2207 Function *F = Intrinsic::getDeclaration(MinMax1.getModule(), IntrinsicID, NewTy); 2208 Value *AT = Builder.CreateSExt(A, NewTy); 2209 Value *BT = Builder.CreateSExt(B, NewTy); 2210 Value *Sat = Builder.CreateCall(F, {AT, BT}); 2211 return CastInst::Create(Instruction::SExt, Sat, Ty); 2212 } 2213 2214 /// Reduce a sequence of min/max with a common operand. 2215 static Instruction *factorizeMinMaxTree(SelectPatternFlavor SPF, Value *LHS, 2216 Value *RHS, 2217 InstCombiner::BuilderTy &Builder) { 2218 assert(SelectPatternResult::isMinOrMax(SPF) && "Expected a min/max"); 2219 // TODO: Allow FP min/max with nnan/nsz. 2220 if (!LHS->getType()->isIntOrIntVectorTy()) 2221 return nullptr; 2222 2223 // Match 3 of the same min/max ops. Example: umin(umin(), umin()). 2224 Value *A, *B, *C, *D; 2225 SelectPatternResult L = matchSelectPattern(LHS, A, B); 2226 SelectPatternResult R = matchSelectPattern(RHS, C, D); 2227 if (SPF != L.Flavor || L.Flavor != R.Flavor) 2228 return nullptr; 2229 2230 // Look for a common operand. The use checks are different than usual because 2231 // a min/max pattern typically has 2 uses of each op: 1 by the cmp and 1 by 2232 // the select. 2233 Value *MinMaxOp = nullptr; 2234 Value *ThirdOp = nullptr; 2235 if (!LHS->hasNUsesOrMore(3) && RHS->hasNUsesOrMore(3)) { 2236 // If the LHS is only used in this chain and the RHS is used outside of it, 2237 // reuse the RHS min/max because that will eliminate the LHS. 2238 if (D == A || C == A) { 2239 // min(min(a, b), min(c, a)) --> min(min(c, a), b) 2240 // min(min(a, b), min(a, d)) --> min(min(a, d), b) 2241 MinMaxOp = RHS; 2242 ThirdOp = B; 2243 } else if (D == B || C == B) { 2244 // min(min(a, b), min(c, b)) --> min(min(c, b), a) 2245 // min(min(a, b), min(b, d)) --> min(min(b, d), a) 2246 MinMaxOp = RHS; 2247 ThirdOp = A; 2248 } 2249 } else if (!RHS->hasNUsesOrMore(3)) { 2250 // Reuse the LHS. This will eliminate the RHS. 2251 if (D == A || D == B) { 2252 // min(min(a, b), min(c, a)) --> min(min(a, b), c) 2253 // min(min(a, b), min(c, b)) --> min(min(a, b), c) 2254 MinMaxOp = LHS; 2255 ThirdOp = C; 2256 } else if (C == A || C == B) { 2257 // min(min(a, b), min(b, d)) --> min(min(a, b), d) 2258 // min(min(a, b), min(c, b)) --> min(min(a, b), d) 2259 MinMaxOp = LHS; 2260 ThirdOp = D; 2261 } 2262 } 2263 if (!MinMaxOp || !ThirdOp) 2264 return nullptr; 2265 2266 CmpInst::Predicate P = getMinMaxPred(SPF); 2267 Value *CmpABC = Builder.CreateICmp(P, MinMaxOp, ThirdOp); 2268 return SelectInst::Create(CmpABC, MinMaxOp, ThirdOp); 2269 } 2270 2271 /// Try to reduce a rotate pattern that includes a compare and select into a 2272 /// funnel shift intrinsic. Example: 2273 /// rotl32(a, b) --> (b == 0 ? a : ((a >> (32 - b)) | (a << b))) 2274 /// --> call llvm.fshl.i32(a, a, b) 2275 static Instruction *foldSelectRotate(SelectInst &Sel) { 2276 // The false value of the select must be a rotate of the true value. 2277 Value *Or0, *Or1; 2278 if (!match(Sel.getFalseValue(), m_OneUse(m_Or(m_Value(Or0), m_Value(Or1))))) 2279 return nullptr; 2280 2281 Value *TVal = Sel.getTrueValue(); 2282 Value *SA0, *SA1; 2283 if (!match(Or0, m_OneUse(m_LogicalShift(m_Specific(TVal), m_Value(SA0)))) || 2284 !match(Or1, m_OneUse(m_LogicalShift(m_Specific(TVal), m_Value(SA1))))) 2285 return nullptr; 2286 2287 auto ShiftOpcode0 = cast<BinaryOperator>(Or0)->getOpcode(); 2288 auto ShiftOpcode1 = cast<BinaryOperator>(Or1)->getOpcode(); 2289 if (ShiftOpcode0 == ShiftOpcode1) 2290 return nullptr; 2291 2292 // We have one of these patterns so far: 2293 // select ?, TVal, (or (lshr TVal, SA0), (shl TVal, SA1)) 2294 // select ?, TVal, (or (shl TVal, SA0), (lshr TVal, SA1)) 2295 // This must be a power-of-2 rotate for a bitmasking transform to be valid. 2296 unsigned Width = Sel.getType()->getScalarSizeInBits(); 2297 if (!isPowerOf2_32(Width)) 2298 return nullptr; 2299 2300 // Check the shift amounts to see if they are an opposite pair. 2301 Value *ShAmt; 2302 if (match(SA1, m_OneUse(m_Sub(m_SpecificInt(Width), m_Specific(SA0))))) 2303 ShAmt = SA0; 2304 else if (match(SA0, m_OneUse(m_Sub(m_SpecificInt(Width), m_Specific(SA1))))) 2305 ShAmt = SA1; 2306 else 2307 return nullptr; 2308 2309 // Finally, see if the select is filtering out a shift-by-zero. 2310 Value *Cond = Sel.getCondition(); 2311 ICmpInst::Predicate Pred; 2312 if (!match(Cond, m_OneUse(m_ICmp(Pred, m_Specific(ShAmt), m_ZeroInt()))) || 2313 Pred != ICmpInst::ICMP_EQ) 2314 return nullptr; 2315 2316 // This is a rotate that avoids shift-by-bitwidth UB in a suboptimal way. 2317 // Convert to funnel shift intrinsic. 2318 bool IsFshl = (ShAmt == SA0 && ShiftOpcode0 == BinaryOperator::Shl) || 2319 (ShAmt == SA1 && ShiftOpcode1 == BinaryOperator::Shl); 2320 Intrinsic::ID IID = IsFshl ? Intrinsic::fshl : Intrinsic::fshr; 2321 Function *F = Intrinsic::getDeclaration(Sel.getModule(), IID, Sel.getType()); 2322 return IntrinsicInst::Create(F, { TVal, TVal, ShAmt }); 2323 } 2324 2325 static Instruction *foldSelectToCopysign(SelectInst &Sel, 2326 InstCombiner::BuilderTy &Builder) { 2327 Value *Cond = Sel.getCondition(); 2328 Value *TVal = Sel.getTrueValue(); 2329 Value *FVal = Sel.getFalseValue(); 2330 Type *SelType = Sel.getType(); 2331 2332 // Match select ?, TC, FC where the constants are equal but negated. 2333 // TODO: Generalize to handle a negated variable operand? 2334 const APFloat *TC, *FC; 2335 if (!match(TVal, m_APFloat(TC)) || !match(FVal, m_APFloat(FC)) || 2336 !abs(*TC).bitwiseIsEqual(abs(*FC))) 2337 return nullptr; 2338 2339 assert(TC != FC && "Expected equal select arms to simplify"); 2340 2341 Value *X; 2342 const APInt *C; 2343 bool IsTrueIfSignSet; 2344 ICmpInst::Predicate Pred; 2345 if (!match(Cond, m_OneUse(m_ICmp(Pred, m_BitCast(m_Value(X)), m_APInt(C)))) || 2346 !isSignBitCheck(Pred, *C, IsTrueIfSignSet) || X->getType() != SelType) 2347 return nullptr; 2348 2349 // If needed, negate the value that will be the sign argument of the copysign: 2350 // (bitcast X) < 0 ? -TC : TC --> copysign(TC, X) 2351 // (bitcast X) < 0 ? TC : -TC --> copysign(TC, -X) 2352 // (bitcast X) >= 0 ? -TC : TC --> copysign(TC, -X) 2353 // (bitcast X) >= 0 ? TC : -TC --> copysign(TC, X) 2354 if (IsTrueIfSignSet ^ TC->isNegative()) 2355 X = Builder.CreateFNegFMF(X, &Sel); 2356 2357 // Canonicalize the magnitude argument as the positive constant since we do 2358 // not care about its sign. 2359 Value *MagArg = TC->isNegative() ? FVal : TVal; 2360 Function *F = Intrinsic::getDeclaration(Sel.getModule(), Intrinsic::copysign, 2361 Sel.getType()); 2362 Instruction *CopySign = IntrinsicInst::Create(F, { MagArg, X }); 2363 CopySign->setFastMathFlags(Sel.getFastMathFlags()); 2364 return CopySign; 2365 } 2366 2367 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) { 2368 Value *CondVal = SI.getCondition(); 2369 Value *TrueVal = SI.getTrueValue(); 2370 Value *FalseVal = SI.getFalseValue(); 2371 Type *SelType = SI.getType(); 2372 2373 // FIXME: Remove this workaround when freeze related patches are done. 2374 // For select with undef operand which feeds into an equality comparison, 2375 // don't simplify it so loop unswitch can know the equality comparison 2376 // may have an undef operand. This is a workaround for PR31652 caused by 2377 // descrepancy about branch on undef between LoopUnswitch and GVN. 2378 if (isa<UndefValue>(TrueVal) || isa<UndefValue>(FalseVal)) { 2379 if (llvm::any_of(SI.users(), [&](User *U) { 2380 ICmpInst *CI = dyn_cast<ICmpInst>(U); 2381 if (CI && CI->isEquality()) 2382 return true; 2383 return false; 2384 })) { 2385 return nullptr; 2386 } 2387 } 2388 2389 if (Value *V = SimplifySelectInst(CondVal, TrueVal, FalseVal, 2390 SQ.getWithInstruction(&SI))) 2391 return replaceInstUsesWith(SI, V); 2392 2393 if (Instruction *I = canonicalizeSelectToShuffle(SI)) 2394 return I; 2395 2396 if (Instruction *I = canonicalizeScalarSelectOfVecs(SI, *this)) 2397 return I; 2398 2399 // Canonicalize a one-use integer compare with a non-canonical predicate by 2400 // inverting the predicate and swapping the select operands. This matches a 2401 // compare canonicalization for conditional branches. 2402 // TODO: Should we do the same for FP compares? 2403 CmpInst::Predicate Pred; 2404 if (match(CondVal, m_OneUse(m_ICmp(Pred, m_Value(), m_Value()))) && 2405 !isCanonicalPredicate(Pred)) { 2406 // Swap true/false values and condition. 2407 CmpInst *Cond = cast<CmpInst>(CondVal); 2408 Cond->setPredicate(CmpInst::getInversePredicate(Pred)); 2409 SI.swapValues(); 2410 SI.swapProfMetadata(); 2411 Worklist.push(Cond); 2412 return &SI; 2413 } 2414 2415 if (SelType->isIntOrIntVectorTy(1) && 2416 TrueVal->getType() == CondVal->getType()) { 2417 if (match(TrueVal, m_One())) { 2418 // Change: A = select B, true, C --> A = or B, C 2419 return BinaryOperator::CreateOr(CondVal, FalseVal); 2420 } 2421 if (match(TrueVal, m_Zero())) { 2422 // Change: A = select B, false, C --> A = and !B, C 2423 Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName()); 2424 return BinaryOperator::CreateAnd(NotCond, FalseVal); 2425 } 2426 if (match(FalseVal, m_Zero())) { 2427 // Change: A = select B, C, false --> A = and B, C 2428 return BinaryOperator::CreateAnd(CondVal, TrueVal); 2429 } 2430 if (match(FalseVal, m_One())) { 2431 // Change: A = select B, C, true --> A = or !B, C 2432 Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName()); 2433 return BinaryOperator::CreateOr(NotCond, TrueVal); 2434 } 2435 2436 // select a, a, b -> a | b 2437 // select a, b, a -> a & b 2438 if (CondVal == TrueVal) 2439 return BinaryOperator::CreateOr(CondVal, FalseVal); 2440 if (CondVal == FalseVal) 2441 return BinaryOperator::CreateAnd(CondVal, TrueVal); 2442 2443 // select a, ~a, b -> (~a) & b 2444 // select a, b, ~a -> (~a) | b 2445 if (match(TrueVal, m_Not(m_Specific(CondVal)))) 2446 return BinaryOperator::CreateAnd(TrueVal, FalseVal); 2447 if (match(FalseVal, m_Not(m_Specific(CondVal)))) 2448 return BinaryOperator::CreateOr(TrueVal, FalseVal); 2449 } 2450 2451 // Selecting between two integer or vector splat integer constants? 2452 // 2453 // Note that we don't handle a scalar select of vectors: 2454 // select i1 %c, <2 x i8> <1, 1>, <2 x i8> <0, 0> 2455 // because that may need 3 instructions to splat the condition value: 2456 // extend, insertelement, shufflevector. 2457 if (SelType->isIntOrIntVectorTy() && 2458 CondVal->getType()->isVectorTy() == SelType->isVectorTy()) { 2459 // select C, 1, 0 -> zext C to int 2460 if (match(TrueVal, m_One()) && match(FalseVal, m_Zero())) 2461 return new ZExtInst(CondVal, SelType); 2462 2463 // select C, -1, 0 -> sext C to int 2464 if (match(TrueVal, m_AllOnes()) && match(FalseVal, m_Zero())) 2465 return new SExtInst(CondVal, SelType); 2466 2467 // select C, 0, 1 -> zext !C to int 2468 if (match(TrueVal, m_Zero()) && match(FalseVal, m_One())) { 2469 Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName()); 2470 return new ZExtInst(NotCond, SelType); 2471 } 2472 2473 // select C, 0, -1 -> sext !C to int 2474 if (match(TrueVal, m_Zero()) && match(FalseVal, m_AllOnes())) { 2475 Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName()); 2476 return new SExtInst(NotCond, SelType); 2477 } 2478 } 2479 2480 // See if we are selecting two values based on a comparison of the two values. 2481 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) { 2482 Value *Cmp0 = FCI->getOperand(0), *Cmp1 = FCI->getOperand(1); 2483 if ((Cmp0 == TrueVal && Cmp1 == FalseVal) || 2484 (Cmp0 == FalseVal && Cmp1 == TrueVal)) { 2485 // Canonicalize to use ordered comparisons by swapping the select 2486 // operands. 2487 // 2488 // e.g. 2489 // (X ugt Y) ? X : Y -> (X ole Y) ? Y : X 2490 if (FCI->hasOneUse() && FCmpInst::isUnordered(FCI->getPredicate())) { 2491 FCmpInst::Predicate InvPred = FCI->getInversePredicate(); 2492 IRBuilder<>::FastMathFlagGuard FMFG(Builder); 2493 // FIXME: The FMF should propagate from the select, not the fcmp. 2494 Builder.setFastMathFlags(FCI->getFastMathFlags()); 2495 Value *NewCond = Builder.CreateFCmp(InvPred, Cmp0, Cmp1, 2496 FCI->getName() + ".inv"); 2497 Value *NewSel = Builder.CreateSelect(NewCond, FalseVal, TrueVal); 2498 return replaceInstUsesWith(SI, NewSel); 2499 } 2500 2501 // NOTE: if we wanted to, this is where to detect MIN/MAX 2502 } 2503 } 2504 2505 // Canonicalize select with fcmp to fabs(). -0.0 makes this tricky. We need 2506 // fast-math-flags (nsz) or fsub with +0.0 (not fneg) for this to work. We 2507 // also require nnan because we do not want to unintentionally change the 2508 // sign of a NaN value. 2509 // FIXME: These folds should test/propagate FMF from the select, not the 2510 // fsub or fneg. 2511 // (X <= +/-0.0) ? (0.0 - X) : X --> fabs(X) 2512 Instruction *FSub; 2513 if (match(CondVal, m_FCmp(Pred, m_Specific(FalseVal), m_AnyZeroFP())) && 2514 match(TrueVal, m_FSub(m_PosZeroFP(), m_Specific(FalseVal))) && 2515 match(TrueVal, m_Instruction(FSub)) && FSub->hasNoNaNs() && 2516 (Pred == FCmpInst::FCMP_OLE || Pred == FCmpInst::FCMP_ULE)) { 2517 Value *Fabs = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, FalseVal, FSub); 2518 return replaceInstUsesWith(SI, Fabs); 2519 } 2520 // (X > +/-0.0) ? X : (0.0 - X) --> fabs(X) 2521 if (match(CondVal, m_FCmp(Pred, m_Specific(TrueVal), m_AnyZeroFP())) && 2522 match(FalseVal, m_FSub(m_PosZeroFP(), m_Specific(TrueVal))) && 2523 match(FalseVal, m_Instruction(FSub)) && FSub->hasNoNaNs() && 2524 (Pred == FCmpInst::FCMP_OGT || Pred == FCmpInst::FCMP_UGT)) { 2525 Value *Fabs = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, TrueVal, FSub); 2526 return replaceInstUsesWith(SI, Fabs); 2527 } 2528 // With nnan and nsz: 2529 // (X < +/-0.0) ? -X : X --> fabs(X) 2530 // (X <= +/-0.0) ? -X : X --> fabs(X) 2531 Instruction *FNeg; 2532 if (match(CondVal, m_FCmp(Pred, m_Specific(FalseVal), m_AnyZeroFP())) && 2533 match(TrueVal, m_FNeg(m_Specific(FalseVal))) && 2534 match(TrueVal, m_Instruction(FNeg)) && 2535 FNeg->hasNoNaNs() && FNeg->hasNoSignedZeros() && 2536 (Pred == FCmpInst::FCMP_OLT || Pred == FCmpInst::FCMP_OLE || 2537 Pred == FCmpInst::FCMP_ULT || Pred == FCmpInst::FCMP_ULE)) { 2538 Value *Fabs = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, FalseVal, FNeg); 2539 return replaceInstUsesWith(SI, Fabs); 2540 } 2541 // With nnan and nsz: 2542 // (X > +/-0.0) ? X : -X --> fabs(X) 2543 // (X >= +/-0.0) ? X : -X --> fabs(X) 2544 if (match(CondVal, m_FCmp(Pred, m_Specific(TrueVal), m_AnyZeroFP())) && 2545 match(FalseVal, m_FNeg(m_Specific(TrueVal))) && 2546 match(FalseVal, m_Instruction(FNeg)) && 2547 FNeg->hasNoNaNs() && FNeg->hasNoSignedZeros() && 2548 (Pred == FCmpInst::FCMP_OGT || Pred == FCmpInst::FCMP_OGE || 2549 Pred == FCmpInst::FCMP_UGT || Pred == FCmpInst::FCMP_UGE)) { 2550 Value *Fabs = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, TrueVal, FNeg); 2551 return replaceInstUsesWith(SI, Fabs); 2552 } 2553 2554 // See if we are selecting two values based on a comparison of the two values. 2555 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) 2556 if (Instruction *Result = foldSelectInstWithICmp(SI, ICI)) 2557 return Result; 2558 2559 if (Instruction *Add = foldAddSubSelect(SI, Builder)) 2560 return Add; 2561 if (Instruction *Add = foldOverflowingAddSubSelect(SI, Builder)) 2562 return Add; 2563 2564 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z)) 2565 auto *TI = dyn_cast<Instruction>(TrueVal); 2566 auto *FI = dyn_cast<Instruction>(FalseVal); 2567 if (TI && FI && TI->getOpcode() == FI->getOpcode()) 2568 if (Instruction *IV = foldSelectOpOp(SI, TI, FI)) 2569 return IV; 2570 2571 if (Instruction *I = foldSelectExtConst(SI)) 2572 return I; 2573 2574 // See if we can fold the select into one of our operands. 2575 if (SelType->isIntOrIntVectorTy() || SelType->isFPOrFPVectorTy()) { 2576 if (Instruction *FoldI = foldSelectIntoOp(SI, TrueVal, FalseVal)) 2577 return FoldI; 2578 2579 Value *LHS, *RHS; 2580 Instruction::CastOps CastOp; 2581 SelectPatternResult SPR = matchSelectPattern(&SI, LHS, RHS, &CastOp); 2582 auto SPF = SPR.Flavor; 2583 if (SPF) { 2584 Value *LHS2, *RHS2; 2585 if (SelectPatternFlavor SPF2 = matchSelectPattern(LHS, LHS2, RHS2).Flavor) 2586 if (Instruction *R = foldSPFofSPF(cast<Instruction>(LHS), SPF2, LHS2, 2587 RHS2, SI, SPF, RHS)) 2588 return R; 2589 if (SelectPatternFlavor SPF2 = matchSelectPattern(RHS, LHS2, RHS2).Flavor) 2590 if (Instruction *R = foldSPFofSPF(cast<Instruction>(RHS), SPF2, LHS2, 2591 RHS2, SI, SPF, LHS)) 2592 return R; 2593 // TODO. 2594 // ABS(-X) -> ABS(X) 2595 } 2596 2597 if (SelectPatternResult::isMinOrMax(SPF)) { 2598 // Canonicalize so that 2599 // - type casts are outside select patterns. 2600 // - float clamp is transformed to min/max pattern 2601 2602 bool IsCastNeeded = LHS->getType() != SelType; 2603 Value *CmpLHS = cast<CmpInst>(CondVal)->getOperand(0); 2604 Value *CmpRHS = cast<CmpInst>(CondVal)->getOperand(1); 2605 if (IsCastNeeded || 2606 (LHS->getType()->isFPOrFPVectorTy() && 2607 ((CmpLHS != LHS && CmpLHS != RHS) || 2608 (CmpRHS != LHS && CmpRHS != RHS)))) { 2609 CmpInst::Predicate MinMaxPred = getMinMaxPred(SPF, SPR.Ordered); 2610 2611 Value *Cmp; 2612 if (CmpInst::isIntPredicate(MinMaxPred)) { 2613 Cmp = Builder.CreateICmp(MinMaxPred, LHS, RHS); 2614 } else { 2615 IRBuilder<>::FastMathFlagGuard FMFG(Builder); 2616 auto FMF = 2617 cast<FPMathOperator>(SI.getCondition())->getFastMathFlags(); 2618 Builder.setFastMathFlags(FMF); 2619 Cmp = Builder.CreateFCmp(MinMaxPred, LHS, RHS); 2620 } 2621 2622 Value *NewSI = Builder.CreateSelect(Cmp, LHS, RHS, SI.getName(), &SI); 2623 if (!IsCastNeeded) 2624 return replaceInstUsesWith(SI, NewSI); 2625 2626 Value *NewCast = Builder.CreateCast(CastOp, NewSI, SelType); 2627 return replaceInstUsesWith(SI, NewCast); 2628 } 2629 2630 // MAX(~a, ~b) -> ~MIN(a, b) 2631 // MAX(~a, C) -> ~MIN(a, ~C) 2632 // MIN(~a, ~b) -> ~MAX(a, b) 2633 // MIN(~a, C) -> ~MAX(a, ~C) 2634 auto moveNotAfterMinMax = [&](Value *X, Value *Y) -> Instruction * { 2635 Value *A; 2636 if (match(X, m_Not(m_Value(A))) && !X->hasNUsesOrMore(3) && 2637 !isFreeToInvert(A, A->hasOneUse()) && 2638 // Passing false to only consider m_Not and constants. 2639 isFreeToInvert(Y, false)) { 2640 Value *B = Builder.CreateNot(Y); 2641 Value *NewMinMax = createMinMax(Builder, getInverseMinMaxFlavor(SPF), 2642 A, B); 2643 // Copy the profile metadata. 2644 if (MDNode *MD = SI.getMetadata(LLVMContext::MD_prof)) { 2645 cast<SelectInst>(NewMinMax)->setMetadata(LLVMContext::MD_prof, MD); 2646 // Swap the metadata if the operands are swapped. 2647 if (X == SI.getFalseValue() && Y == SI.getTrueValue()) 2648 cast<SelectInst>(NewMinMax)->swapProfMetadata(); 2649 } 2650 2651 return BinaryOperator::CreateNot(NewMinMax); 2652 } 2653 2654 return nullptr; 2655 }; 2656 2657 if (Instruction *I = moveNotAfterMinMax(LHS, RHS)) 2658 return I; 2659 if (Instruction *I = moveNotAfterMinMax(RHS, LHS)) 2660 return I; 2661 2662 if (Instruction *I = moveAddAfterMinMax(SPF, LHS, RHS, Builder)) 2663 return I; 2664 2665 if (Instruction *I = factorizeMinMaxTree(SPF, LHS, RHS, Builder)) 2666 return I; 2667 if (Instruction *I = matchSAddSubSat(SI)) 2668 return I; 2669 } 2670 } 2671 2672 // Canonicalize select of FP values where NaN and -0.0 are not valid as 2673 // minnum/maxnum intrinsics. 2674 if (isa<FPMathOperator>(SI) && SI.hasNoNaNs() && SI.hasNoSignedZeros()) { 2675 Value *X, *Y; 2676 if (match(&SI, m_OrdFMax(m_Value(X), m_Value(Y)))) 2677 return replaceInstUsesWith( 2678 SI, Builder.CreateBinaryIntrinsic(Intrinsic::maxnum, X, Y, &SI)); 2679 2680 if (match(&SI, m_OrdFMin(m_Value(X), m_Value(Y)))) 2681 return replaceInstUsesWith( 2682 SI, Builder.CreateBinaryIntrinsic(Intrinsic::minnum, X, Y, &SI)); 2683 } 2684 2685 // See if we can fold the select into a phi node if the condition is a select. 2686 if (auto *PN = dyn_cast<PHINode>(SI.getCondition())) 2687 // The true/false values have to be live in the PHI predecessor's blocks. 2688 if (canSelectOperandBeMappingIntoPredBlock(TrueVal, SI) && 2689 canSelectOperandBeMappingIntoPredBlock(FalseVal, SI)) 2690 if (Instruction *NV = foldOpIntoPhi(SI, PN)) 2691 return NV; 2692 2693 if (SelectInst *TrueSI = dyn_cast<SelectInst>(TrueVal)) { 2694 if (TrueSI->getCondition()->getType() == CondVal->getType()) { 2695 // select(C, select(C, a, b), c) -> select(C, a, c) 2696 if (TrueSI->getCondition() == CondVal) { 2697 if (SI.getTrueValue() == TrueSI->getTrueValue()) 2698 return nullptr; 2699 return replaceOperand(SI, 1, TrueSI->getTrueValue()); 2700 } 2701 // select(C0, select(C1, a, b), b) -> select(C0&C1, a, b) 2702 // We choose this as normal form to enable folding on the And and shortening 2703 // paths for the values (this helps GetUnderlyingObjects() for example). 2704 if (TrueSI->getFalseValue() == FalseVal && TrueSI->hasOneUse()) { 2705 Value *And = Builder.CreateAnd(CondVal, TrueSI->getCondition()); 2706 SI.setOperand(0, And); 2707 SI.setOperand(1, TrueSI->getTrueValue()); 2708 return &SI; 2709 } 2710 } 2711 } 2712 if (SelectInst *FalseSI = dyn_cast<SelectInst>(FalseVal)) { 2713 if (FalseSI->getCondition()->getType() == CondVal->getType()) { 2714 // select(C, a, select(C, b, c)) -> select(C, a, c) 2715 if (FalseSI->getCondition() == CondVal) { 2716 if (SI.getFalseValue() == FalseSI->getFalseValue()) 2717 return nullptr; 2718 return replaceOperand(SI, 2, FalseSI->getFalseValue()); 2719 } 2720 // select(C0, a, select(C1, a, b)) -> select(C0|C1, a, b) 2721 if (FalseSI->getTrueValue() == TrueVal && FalseSI->hasOneUse()) { 2722 Value *Or = Builder.CreateOr(CondVal, FalseSI->getCondition()); 2723 SI.setOperand(0, Or); 2724 SI.setOperand(2, FalseSI->getFalseValue()); 2725 return &SI; 2726 } 2727 } 2728 } 2729 2730 auto canMergeSelectThroughBinop = [](BinaryOperator *BO) { 2731 // The select might be preventing a division by 0. 2732 switch (BO->getOpcode()) { 2733 default: 2734 return true; 2735 case Instruction::SRem: 2736 case Instruction::URem: 2737 case Instruction::SDiv: 2738 case Instruction::UDiv: 2739 return false; 2740 } 2741 }; 2742 2743 // Try to simplify a binop sandwiched between 2 selects with the same 2744 // condition. 2745 // select(C, binop(select(C, X, Y), W), Z) -> select(C, binop(X, W), Z) 2746 BinaryOperator *TrueBO; 2747 if (match(TrueVal, m_OneUse(m_BinOp(TrueBO))) && 2748 canMergeSelectThroughBinop(TrueBO)) { 2749 if (auto *TrueBOSI = dyn_cast<SelectInst>(TrueBO->getOperand(0))) { 2750 if (TrueBOSI->getCondition() == CondVal) { 2751 TrueBO->setOperand(0, TrueBOSI->getTrueValue()); 2752 Worklist.push(TrueBO); 2753 return &SI; 2754 } 2755 } 2756 if (auto *TrueBOSI = dyn_cast<SelectInst>(TrueBO->getOperand(1))) { 2757 if (TrueBOSI->getCondition() == CondVal) { 2758 TrueBO->setOperand(1, TrueBOSI->getTrueValue()); 2759 Worklist.push(TrueBO); 2760 return &SI; 2761 } 2762 } 2763 } 2764 2765 // select(C, Z, binop(select(C, X, Y), W)) -> select(C, Z, binop(Y, W)) 2766 BinaryOperator *FalseBO; 2767 if (match(FalseVal, m_OneUse(m_BinOp(FalseBO))) && 2768 canMergeSelectThroughBinop(FalseBO)) { 2769 if (auto *FalseBOSI = dyn_cast<SelectInst>(FalseBO->getOperand(0))) { 2770 if (FalseBOSI->getCondition() == CondVal) { 2771 FalseBO->setOperand(0, FalseBOSI->getFalseValue()); 2772 Worklist.push(FalseBO); 2773 return &SI; 2774 } 2775 } 2776 if (auto *FalseBOSI = dyn_cast<SelectInst>(FalseBO->getOperand(1))) { 2777 if (FalseBOSI->getCondition() == CondVal) { 2778 FalseBO->setOperand(1, FalseBOSI->getFalseValue()); 2779 Worklist.push(FalseBO); 2780 return &SI; 2781 } 2782 } 2783 } 2784 2785 Value *NotCond; 2786 if (match(CondVal, m_Not(m_Value(NotCond)))) { 2787 replaceOperand(SI, 0, NotCond); 2788 SI.swapValues(); 2789 SI.swapProfMetadata(); 2790 return &SI; 2791 } 2792 2793 if (VectorType *VecTy = dyn_cast<VectorType>(SelType)) { 2794 unsigned VWidth = VecTy->getNumElements(); 2795 APInt UndefElts(VWidth, 0); 2796 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth)); 2797 if (Value *V = SimplifyDemandedVectorElts(&SI, AllOnesEltMask, UndefElts)) { 2798 if (V != &SI) 2799 return replaceInstUsesWith(SI, V); 2800 return &SI; 2801 } 2802 } 2803 2804 // If we can compute the condition, there's no need for a select. 2805 // Like the above fold, we are attempting to reduce compile-time cost by 2806 // putting this fold here with limitations rather than in InstSimplify. 2807 // The motivation for this call into value tracking is to take advantage of 2808 // the assumption cache, so make sure that is populated. 2809 if (!CondVal->getType()->isVectorTy() && !AC.assumptions().empty()) { 2810 KnownBits Known(1); 2811 computeKnownBits(CondVal, Known, 0, &SI); 2812 if (Known.One.isOneValue()) 2813 return replaceInstUsesWith(SI, TrueVal); 2814 if (Known.Zero.isOneValue()) 2815 return replaceInstUsesWith(SI, FalseVal); 2816 } 2817 2818 if (Instruction *BitCastSel = foldSelectCmpBitcasts(SI, Builder)) 2819 return BitCastSel; 2820 2821 // Simplify selects that test the returned flag of cmpxchg instructions. 2822 if (Instruction *Select = foldSelectCmpXchg(SI)) 2823 return Select; 2824 2825 if (Instruction *Select = foldSelectBinOpIdentity(SI, TLI, *this)) 2826 return Select; 2827 2828 if (Instruction *Rot = foldSelectRotate(SI)) 2829 return Rot; 2830 2831 if (Instruction *Copysign = foldSelectToCopysign(SI, Builder)) 2832 return Copysign; 2833 2834 return nullptr; 2835 } 2836