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/OverflowInstAnalysis.h" 22 #include "llvm/Analysis/ValueTracking.h" 23 #include "llvm/IR/BasicBlock.h" 24 #include "llvm/IR/Constant.h" 25 #include "llvm/IR/Constants.h" 26 #include "llvm/IR/DerivedTypes.h" 27 #include "llvm/IR/IRBuilder.h" 28 #include "llvm/IR/InstrTypes.h" 29 #include "llvm/IR/Instruction.h" 30 #include "llvm/IR/Instructions.h" 31 #include "llvm/IR/IntrinsicInst.h" 32 #include "llvm/IR/Intrinsics.h" 33 #include "llvm/IR/Operator.h" 34 #include "llvm/IR/PatternMatch.h" 35 #include "llvm/IR/Type.h" 36 #include "llvm/IR/User.h" 37 #include "llvm/IR/Value.h" 38 #include "llvm/Support/Casting.h" 39 #include "llvm/Support/ErrorHandling.h" 40 #include "llvm/Support/KnownBits.h" 41 #include "llvm/Transforms/InstCombine/InstCombiner.h" 42 #include <cassert> 43 #include <utility> 44 45 #define DEBUG_TYPE "instcombine" 46 #include "llvm/Transforms/Utils/InstructionWorklist.h" 47 48 using namespace llvm; 49 using namespace PatternMatch; 50 51 52 /// Replace a select operand based on an equality comparison with the identity 53 /// constant of a binop. 54 static Instruction *foldSelectBinOpIdentity(SelectInst &Sel, 55 const TargetLibraryInfo &TLI, 56 InstCombinerImpl &IC) { 57 // The select condition must be an equality compare with a constant operand. 58 Value *X; 59 Constant *C; 60 CmpInst::Predicate Pred; 61 if (!match(Sel.getCondition(), m_Cmp(Pred, m_Value(X), m_Constant(C)))) 62 return nullptr; 63 64 bool IsEq; 65 if (ICmpInst::isEquality(Pred)) 66 IsEq = Pred == ICmpInst::ICMP_EQ; 67 else if (Pred == FCmpInst::FCMP_OEQ) 68 IsEq = true; 69 else if (Pred == FCmpInst::FCMP_UNE) 70 IsEq = false; 71 else 72 return nullptr; 73 74 // A select operand must be a binop. 75 BinaryOperator *BO; 76 if (!match(Sel.getOperand(IsEq ? 1 : 2), m_BinOp(BO))) 77 return nullptr; 78 79 // The compare constant must be the identity constant for that binop. 80 // If this a floating-point compare with 0.0, any zero constant will do. 81 Type *Ty = BO->getType(); 82 Constant *IdC = ConstantExpr::getBinOpIdentity(BO->getOpcode(), Ty, true); 83 if (IdC != C) { 84 if (!IdC || !CmpInst::isFPPredicate(Pred)) 85 return nullptr; 86 if (!match(IdC, m_AnyZeroFP()) || !match(C, m_AnyZeroFP())) 87 return nullptr; 88 } 89 90 // Last, match the compare variable operand with a binop operand. 91 Value *Y; 92 if (!BO->isCommutative() && !match(BO, m_BinOp(m_Value(Y), m_Specific(X)))) 93 return nullptr; 94 if (!match(BO, m_c_BinOp(m_Value(Y), m_Specific(X)))) 95 return nullptr; 96 97 // +0.0 compares equal to -0.0, and so it does not behave as required for this 98 // transform. Bail out if we can not exclude that possibility. 99 if (isa<FPMathOperator>(BO)) 100 if (!BO->hasNoSignedZeros() && !CannotBeNegativeZero(Y, &TLI)) 101 return nullptr; 102 103 // BO = binop Y, X 104 // S = { select (cmp eq X, C), BO, ? } or { select (cmp ne X, C), ?, BO } 105 // => 106 // S = { select (cmp eq X, C), Y, ? } or { select (cmp ne X, C), ?, Y } 107 return IC.replaceOperand(Sel, IsEq ? 1 : 2, Y); 108 } 109 110 /// This folds: 111 /// select (icmp eq (and X, C1)), TC, FC 112 /// iff C1 is a power 2 and the difference between TC and FC is a power-of-2. 113 /// To something like: 114 /// (shr (and (X, C1)), (log2(C1) - log2(TC-FC))) + FC 115 /// Or: 116 /// (shl (and (X, C1)), (log2(TC-FC) - log2(C1))) + FC 117 /// With some variations depending if FC is larger than TC, or the shift 118 /// isn't needed, or the bit widths don't match. 119 static Value *foldSelectICmpAnd(SelectInst &Sel, ICmpInst *Cmp, 120 InstCombiner::BuilderTy &Builder) { 121 const APInt *SelTC, *SelFC; 122 if (!match(Sel.getTrueValue(), m_APInt(SelTC)) || 123 !match(Sel.getFalseValue(), m_APInt(SelFC))) 124 return nullptr; 125 126 // If this is a vector select, we need a vector compare. 127 Type *SelType = Sel.getType(); 128 if (SelType->isVectorTy() != Cmp->getType()->isVectorTy()) 129 return nullptr; 130 131 Value *V; 132 APInt AndMask; 133 bool CreateAnd = false; 134 ICmpInst::Predicate Pred = Cmp->getPredicate(); 135 if (ICmpInst::isEquality(Pred)) { 136 if (!match(Cmp->getOperand(1), m_Zero())) 137 return nullptr; 138 139 V = Cmp->getOperand(0); 140 const APInt *AndRHS; 141 if (!match(V, m_And(m_Value(), m_Power2(AndRHS)))) 142 return nullptr; 143 144 AndMask = *AndRHS; 145 } else if (decomposeBitTestICmp(Cmp->getOperand(0), Cmp->getOperand(1), 146 Pred, V, AndMask)) { 147 assert(ICmpInst::isEquality(Pred) && "Not equality test?"); 148 if (!AndMask.isPowerOf2()) 149 return nullptr; 150 151 CreateAnd = true; 152 } else { 153 return nullptr; 154 } 155 156 // In general, when both constants are non-zero, we would need an offset to 157 // replace the select. This would require more instructions than we started 158 // with. But there's one special-case that we handle here because it can 159 // simplify/reduce the instructions. 160 APInt TC = *SelTC; 161 APInt FC = *SelFC; 162 if (!TC.isZero() && !FC.isZero()) { 163 // If the select constants differ by exactly one bit and that's the same 164 // bit that is masked and checked by the select condition, the select can 165 // be replaced by bitwise logic to set/clear one bit of the constant result. 166 if (TC.getBitWidth() != AndMask.getBitWidth() || (TC ^ FC) != AndMask) 167 return nullptr; 168 if (CreateAnd) { 169 // If we have to create an 'and', then we must kill the cmp to not 170 // increase the instruction count. 171 if (!Cmp->hasOneUse()) 172 return nullptr; 173 V = Builder.CreateAnd(V, ConstantInt::get(SelType, AndMask)); 174 } 175 bool ExtraBitInTC = TC.ugt(FC); 176 if (Pred == ICmpInst::ICMP_EQ) { 177 // If the masked bit in V is clear, clear or set the bit in the result: 178 // (V & AndMaskC) == 0 ? TC : FC --> (V & AndMaskC) ^ TC 179 // (V & AndMaskC) == 0 ? TC : FC --> (V & AndMaskC) | TC 180 Constant *C = ConstantInt::get(SelType, TC); 181 return ExtraBitInTC ? Builder.CreateXor(V, C) : Builder.CreateOr(V, C); 182 } 183 if (Pred == ICmpInst::ICMP_NE) { 184 // If the masked bit in V is set, set or clear the bit in the result: 185 // (V & AndMaskC) != 0 ? TC : FC --> (V & AndMaskC) | FC 186 // (V & AndMaskC) != 0 ? TC : FC --> (V & AndMaskC) ^ FC 187 Constant *C = ConstantInt::get(SelType, FC); 188 return ExtraBitInTC ? Builder.CreateOr(V, C) : Builder.CreateXor(V, C); 189 } 190 llvm_unreachable("Only expecting equality predicates"); 191 } 192 193 // Make sure one of the select arms is a power-of-2. 194 if (!TC.isPowerOf2() && !FC.isPowerOf2()) 195 return nullptr; 196 197 // Determine which shift is needed to transform result of the 'and' into the 198 // desired result. 199 const APInt &ValC = !TC.isZero() ? TC : FC; 200 unsigned ValZeros = ValC.logBase2(); 201 unsigned AndZeros = AndMask.logBase2(); 202 203 // Insert the 'and' instruction on the input to the truncate. 204 if (CreateAnd) 205 V = Builder.CreateAnd(V, ConstantInt::get(V->getType(), AndMask)); 206 207 // If types don't match, we can still convert the select by introducing a zext 208 // or a trunc of the 'and'. 209 if (ValZeros > AndZeros) { 210 V = Builder.CreateZExtOrTrunc(V, SelType); 211 V = Builder.CreateShl(V, ValZeros - AndZeros); 212 } else if (ValZeros < AndZeros) { 213 V = Builder.CreateLShr(V, AndZeros - ValZeros); 214 V = Builder.CreateZExtOrTrunc(V, SelType); 215 } else { 216 V = Builder.CreateZExtOrTrunc(V, SelType); 217 } 218 219 // Okay, now we know that everything is set up, we just don't know whether we 220 // have a icmp_ne or icmp_eq and whether the true or false val is the zero. 221 bool ShouldNotVal = !TC.isZero(); 222 ShouldNotVal ^= Pred == ICmpInst::ICMP_NE; 223 if (ShouldNotVal) 224 V = Builder.CreateXor(V, ValC); 225 226 return V; 227 } 228 229 /// We want to turn code that looks like this: 230 /// %C = or %A, %B 231 /// %D = select %cond, %C, %A 232 /// into: 233 /// %C = select %cond, %B, 0 234 /// %D = or %A, %C 235 /// 236 /// Assuming that the specified instruction is an operand to the select, return 237 /// a bitmask indicating which operands of this instruction are foldable if they 238 /// equal the other incoming value of the select. 239 static unsigned getSelectFoldableOperands(BinaryOperator *I) { 240 switch (I->getOpcode()) { 241 case Instruction::Add: 242 case Instruction::FAdd: 243 case Instruction::Mul: 244 case Instruction::FMul: 245 case Instruction::And: 246 case Instruction::Or: 247 case Instruction::Xor: 248 return 3; // Can fold through either operand. 249 case Instruction::Sub: // Can only fold on the amount subtracted. 250 case Instruction::FSub: 251 case Instruction::FDiv: // Can only fold on the divisor amount. 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 /// We have (select c, TI, FI), and we know that TI and FI have the same opcode. 262 Instruction *InstCombinerImpl::foldSelectOpOp(SelectInst &SI, Instruction *TI, 263 Instruction *FI) { 264 // Don't break up min/max patterns. The hasOneUse checks below prevent that 265 // for most cases, but vector min/max with bitcasts can be transformed. If the 266 // one-use restrictions are eased for other patterns, we still don't want to 267 // obfuscate min/max. 268 if ((match(&SI, m_SMin(m_Value(), m_Value())) || 269 match(&SI, m_SMax(m_Value(), m_Value())) || 270 match(&SI, m_UMin(m_Value(), m_Value())) || 271 match(&SI, m_UMax(m_Value(), m_Value())))) 272 return nullptr; 273 274 // If this is a cast from the same type, merge. 275 Value *Cond = SI.getCondition(); 276 Type *CondTy = Cond->getType(); 277 if (TI->getNumOperands() == 1 && TI->isCast()) { 278 Type *FIOpndTy = FI->getOperand(0)->getType(); 279 if (TI->getOperand(0)->getType() != FIOpndTy) 280 return nullptr; 281 282 // The select condition may be a vector. We may only change the operand 283 // type if the vector width remains the same (and matches the condition). 284 if (auto *CondVTy = dyn_cast<VectorType>(CondTy)) { 285 if (!FIOpndTy->isVectorTy() || 286 CondVTy->getElementCount() != 287 cast<VectorType>(FIOpndTy)->getElementCount()) 288 return nullptr; 289 290 // TODO: If the backend knew how to deal with casts better, we could 291 // remove this limitation. For now, there's too much potential to create 292 // worse codegen by promoting the select ahead of size-altering casts 293 // (PR28160). 294 // 295 // Note that ValueTracking's matchSelectPattern() looks through casts 296 // without checking 'hasOneUse' when it matches min/max patterns, so this 297 // transform may end up happening anyway. 298 if (TI->getOpcode() != Instruction::BitCast && 299 (!TI->hasOneUse() || !FI->hasOneUse())) 300 return nullptr; 301 } else if (!TI->hasOneUse() || !FI->hasOneUse()) { 302 // TODO: The one-use restrictions for a scalar select could be eased if 303 // the fold of a select in visitLoadInst() was enhanced to match a pattern 304 // that includes a cast. 305 return nullptr; 306 } 307 308 // Fold this by inserting a select from the input values. 309 Value *NewSI = 310 Builder.CreateSelect(Cond, TI->getOperand(0), FI->getOperand(0), 311 SI.getName() + ".v", &SI); 312 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI, 313 TI->getType()); 314 } 315 316 // Cond ? -X : -Y --> -(Cond ? X : Y) 317 Value *X, *Y; 318 if (match(TI, m_FNeg(m_Value(X))) && match(FI, m_FNeg(m_Value(Y))) && 319 (TI->hasOneUse() || FI->hasOneUse())) { 320 // Intersect FMF from the fneg instructions and union those with the select. 321 FastMathFlags FMF = TI->getFastMathFlags(); 322 FMF &= FI->getFastMathFlags(); 323 FMF |= SI.getFastMathFlags(); 324 Value *NewSel = Builder.CreateSelect(Cond, X, Y, SI.getName() + ".v", &SI); 325 if (auto *NewSelI = dyn_cast<Instruction>(NewSel)) 326 NewSelI->setFastMathFlags(FMF); 327 Instruction *NewFNeg = UnaryOperator::CreateFNeg(NewSel); 328 NewFNeg->setFastMathFlags(FMF); 329 return NewFNeg; 330 } 331 332 // Min/max intrinsic with a common operand can have the common operand pulled 333 // after the select. This is the same transform as below for binops, but 334 // specialized for intrinsic matching and without the restrictive uses clause. 335 auto *TII = dyn_cast<IntrinsicInst>(TI); 336 auto *FII = dyn_cast<IntrinsicInst>(FI); 337 if (TII && FII && TII->getIntrinsicID() == FII->getIntrinsicID() && 338 (TII->hasOneUse() || FII->hasOneUse())) { 339 Value *T0, *T1, *F0, *F1; 340 if (match(TII, m_MaxOrMin(m_Value(T0), m_Value(T1))) && 341 match(FII, m_MaxOrMin(m_Value(F0), m_Value(F1)))) { 342 if (T0 == F0) { 343 Value *NewSel = Builder.CreateSelect(Cond, T1, F1, "minmaxop", &SI); 344 return CallInst::Create(TII->getCalledFunction(), {NewSel, T0}); 345 } 346 if (T0 == F1) { 347 Value *NewSel = Builder.CreateSelect(Cond, T1, F0, "minmaxop", &SI); 348 return CallInst::Create(TII->getCalledFunction(), {NewSel, T0}); 349 } 350 if (T1 == F0) { 351 Value *NewSel = Builder.CreateSelect(Cond, T0, F1, "minmaxop", &SI); 352 return CallInst::Create(TII->getCalledFunction(), {NewSel, T1}); 353 } 354 if (T1 == F1) { 355 Value *NewSel = Builder.CreateSelect(Cond, T0, F0, "minmaxop", &SI); 356 return CallInst::Create(TII->getCalledFunction(), {NewSel, T1}); 357 } 358 } 359 } 360 361 // Only handle binary operators (including two-operand getelementptr) with 362 // one-use here. As with the cast case above, it may be possible to relax the 363 // one-use constraint, but that needs be examined carefully since it may not 364 // reduce the total number of instructions. 365 if (TI->getNumOperands() != 2 || FI->getNumOperands() != 2 || 366 !TI->isSameOperationAs(FI) || 367 (!isa<BinaryOperator>(TI) && !isa<GetElementPtrInst>(TI)) || 368 !TI->hasOneUse() || !FI->hasOneUse()) 369 return nullptr; 370 371 // Figure out if the operations have any operands in common. 372 Value *MatchOp, *OtherOpT, *OtherOpF; 373 bool MatchIsOpZero; 374 if (TI->getOperand(0) == FI->getOperand(0)) { 375 MatchOp = TI->getOperand(0); 376 OtherOpT = TI->getOperand(1); 377 OtherOpF = FI->getOperand(1); 378 MatchIsOpZero = true; 379 } else if (TI->getOperand(1) == FI->getOperand(1)) { 380 MatchOp = TI->getOperand(1); 381 OtherOpT = TI->getOperand(0); 382 OtherOpF = FI->getOperand(0); 383 MatchIsOpZero = false; 384 } else if (!TI->isCommutative()) { 385 return nullptr; 386 } else if (TI->getOperand(0) == FI->getOperand(1)) { 387 MatchOp = TI->getOperand(0); 388 OtherOpT = TI->getOperand(1); 389 OtherOpF = FI->getOperand(0); 390 MatchIsOpZero = true; 391 } else if (TI->getOperand(1) == FI->getOperand(0)) { 392 MatchOp = TI->getOperand(1); 393 OtherOpT = TI->getOperand(0); 394 OtherOpF = FI->getOperand(1); 395 MatchIsOpZero = true; 396 } else { 397 return nullptr; 398 } 399 400 // If the select condition is a vector, the operands of the original select's 401 // operands also must be vectors. This may not be the case for getelementptr 402 // for example. 403 if (CondTy->isVectorTy() && (!OtherOpT->getType()->isVectorTy() || 404 !OtherOpF->getType()->isVectorTy())) 405 return nullptr; 406 407 // If we reach here, they do have operations in common. 408 Value *NewSI = Builder.CreateSelect(Cond, OtherOpT, OtherOpF, 409 SI.getName() + ".v", &SI); 410 Value *Op0 = MatchIsOpZero ? MatchOp : NewSI; 411 Value *Op1 = MatchIsOpZero ? NewSI : MatchOp; 412 if (auto *BO = dyn_cast<BinaryOperator>(TI)) { 413 BinaryOperator *NewBO = BinaryOperator::Create(BO->getOpcode(), Op0, Op1); 414 NewBO->copyIRFlags(TI); 415 NewBO->andIRFlags(FI); 416 return NewBO; 417 } 418 if (auto *TGEP = dyn_cast<GetElementPtrInst>(TI)) { 419 auto *FGEP = cast<GetElementPtrInst>(FI); 420 Type *ElementType = TGEP->getResultElementType(); 421 return TGEP->isInBounds() && FGEP->isInBounds() 422 ? GetElementPtrInst::CreateInBounds(ElementType, Op0, {Op1}) 423 : GetElementPtrInst::Create(ElementType, Op0, {Op1}); 424 } 425 llvm_unreachable("Expected BinaryOperator or GEP"); 426 return nullptr; 427 } 428 429 static bool isSelect01(const APInt &C1I, const APInt &C2I) { 430 if (!C1I.isZero() && !C2I.isZero()) // One side must be zero. 431 return false; 432 return C1I.isOne() || C1I.isAllOnes() || C2I.isOne() || C2I.isAllOnes(); 433 } 434 435 /// Try to fold the select into one of the operands to allow further 436 /// optimization. 437 Instruction *InstCombinerImpl::foldSelectIntoOp(SelectInst &SI, Value *TrueVal, 438 Value *FalseVal) { 439 // See the comment above GetSelectFoldableOperands for a description of the 440 // transformation we are doing here. 441 if (auto *TVI = dyn_cast<BinaryOperator>(TrueVal)) { 442 if (TVI->hasOneUse() && !isa<Constant>(FalseVal)) { 443 if (unsigned SFO = getSelectFoldableOperands(TVI)) { 444 unsigned OpToFold = 0; 445 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) { 446 OpToFold = 1; 447 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) { 448 OpToFold = 2; 449 } 450 451 if (OpToFold) { 452 Constant *C = ConstantExpr::getBinOpIdentity(TVI->getOpcode(), 453 TVI->getType(), true); 454 Value *OOp = TVI->getOperand(2-OpToFold); 455 // Avoid creating select between 2 constants unless it's selecting 456 // between 0, 1 and -1. 457 const APInt *OOpC; 458 bool OOpIsAPInt = match(OOp, m_APInt(OOpC)); 459 if (!isa<Constant>(OOp) || 460 (OOpIsAPInt && isSelect01(C->getUniqueInteger(), *OOpC))) { 461 Value *NewSel = Builder.CreateSelect(SI.getCondition(), OOp, C); 462 NewSel->takeName(TVI); 463 BinaryOperator *BO = BinaryOperator::Create(TVI->getOpcode(), 464 FalseVal, NewSel); 465 BO->copyIRFlags(TVI); 466 return BO; 467 } 468 } 469 } 470 } 471 } 472 473 if (auto *FVI = dyn_cast<BinaryOperator>(FalseVal)) { 474 if (FVI->hasOneUse() && !isa<Constant>(TrueVal)) { 475 if (unsigned SFO = getSelectFoldableOperands(FVI)) { 476 unsigned OpToFold = 0; 477 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) { 478 OpToFold = 1; 479 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) { 480 OpToFold = 2; 481 } 482 483 if (OpToFold) { 484 Constant *C = ConstantExpr::getBinOpIdentity(FVI->getOpcode(), 485 FVI->getType(), true); 486 Value *OOp = FVI->getOperand(2-OpToFold); 487 // Avoid creating select between 2 constants unless it's selecting 488 // between 0, 1 and -1. 489 const APInt *OOpC; 490 bool OOpIsAPInt = match(OOp, m_APInt(OOpC)); 491 if (!isa<Constant>(OOp) || 492 (OOpIsAPInt && isSelect01(C->getUniqueInteger(), *OOpC))) { 493 Value *NewSel = Builder.CreateSelect(SI.getCondition(), C, OOp); 494 NewSel->takeName(FVI); 495 BinaryOperator *BO = BinaryOperator::Create(FVI->getOpcode(), 496 TrueVal, NewSel); 497 BO->copyIRFlags(FVI); 498 return BO; 499 } 500 } 501 } 502 } 503 } 504 505 return nullptr; 506 } 507 508 /// We want to turn: 509 /// (select (icmp eq (and X, Y), 0), (and (lshr X, Z), 1), 1) 510 /// into: 511 /// zext (icmp ne i32 (and X, (or Y, (shl 1, Z))), 0) 512 /// Note: 513 /// Z may be 0 if lshr is missing. 514 /// Worst-case scenario is that we will replace 5 instructions with 5 different 515 /// instructions, but we got rid of select. 516 static Instruction *foldSelectICmpAndAnd(Type *SelType, const ICmpInst *Cmp, 517 Value *TVal, Value *FVal, 518 InstCombiner::BuilderTy &Builder) { 519 if (!(Cmp->hasOneUse() && Cmp->getOperand(0)->hasOneUse() && 520 Cmp->getPredicate() == ICmpInst::ICMP_EQ && 521 match(Cmp->getOperand(1), m_Zero()) && match(FVal, m_One()))) 522 return nullptr; 523 524 // The TrueVal has general form of: and %B, 1 525 Value *B; 526 if (!match(TVal, m_OneUse(m_And(m_Value(B), m_One())))) 527 return nullptr; 528 529 // Where %B may be optionally shifted: lshr %X, %Z. 530 Value *X, *Z; 531 const bool HasShift = match(B, m_OneUse(m_LShr(m_Value(X), m_Value(Z)))); 532 if (!HasShift) 533 X = B; 534 535 Value *Y; 536 if (!match(Cmp->getOperand(0), m_c_And(m_Specific(X), m_Value(Y)))) 537 return nullptr; 538 539 // ((X & Y) == 0) ? ((X >> Z) & 1) : 1 --> (X & (Y | (1 << Z))) != 0 540 // ((X & Y) == 0) ? (X & 1) : 1 --> (X & (Y | 1)) != 0 541 Constant *One = ConstantInt::get(SelType, 1); 542 Value *MaskB = HasShift ? Builder.CreateShl(One, Z) : One; 543 Value *FullMask = Builder.CreateOr(Y, MaskB); 544 Value *MaskedX = Builder.CreateAnd(X, FullMask); 545 Value *ICmpNeZero = Builder.CreateIsNotNull(MaskedX); 546 return new ZExtInst(ICmpNeZero, SelType); 547 } 548 549 /// We want to turn: 550 /// (select (icmp sgt x, C), lshr (X, Y), ashr (X, Y)); iff C s>= -1 551 /// (select (icmp slt x, C), ashr (X, Y), lshr (X, Y)); iff C s>= 0 552 /// into: 553 /// ashr (X, Y) 554 static Value *foldSelectICmpLshrAshr(const ICmpInst *IC, Value *TrueVal, 555 Value *FalseVal, 556 InstCombiner::BuilderTy &Builder) { 557 ICmpInst::Predicate Pred = IC->getPredicate(); 558 Value *CmpLHS = IC->getOperand(0); 559 Value *CmpRHS = IC->getOperand(1); 560 if (!CmpRHS->getType()->isIntOrIntVectorTy()) 561 return nullptr; 562 563 Value *X, *Y; 564 unsigned Bitwidth = CmpRHS->getType()->getScalarSizeInBits(); 565 if ((Pred != ICmpInst::ICMP_SGT || 566 !match(CmpRHS, 567 m_SpecificInt_ICMP(ICmpInst::ICMP_SGE, APInt(Bitwidth, -1)))) && 568 (Pred != ICmpInst::ICMP_SLT || 569 !match(CmpRHS, 570 m_SpecificInt_ICMP(ICmpInst::ICMP_SGE, APInt(Bitwidth, 0))))) 571 return nullptr; 572 573 // Canonicalize so that ashr is in FalseVal. 574 if (Pred == ICmpInst::ICMP_SLT) 575 std::swap(TrueVal, FalseVal); 576 577 if (match(TrueVal, m_LShr(m_Value(X), m_Value(Y))) && 578 match(FalseVal, m_AShr(m_Specific(X), m_Specific(Y))) && 579 match(CmpLHS, m_Specific(X))) { 580 const auto *Ashr = cast<Instruction>(FalseVal); 581 // if lshr is not exact and ashr is, this new ashr must not be exact. 582 bool IsExact = Ashr->isExact() && cast<Instruction>(TrueVal)->isExact(); 583 return Builder.CreateAShr(X, Y, IC->getName(), IsExact); 584 } 585 586 return nullptr; 587 } 588 589 /// We want to turn: 590 /// (select (icmp eq (and X, C1), 0), Y, (or Y, C2)) 591 /// into: 592 /// (or (shl (and X, C1), C3), Y) 593 /// iff: 594 /// C1 and C2 are both powers of 2 595 /// where: 596 /// C3 = Log(C2) - Log(C1) 597 /// 598 /// This transform handles cases where: 599 /// 1. The icmp predicate is inverted 600 /// 2. The select operands are reversed 601 /// 3. The magnitude of C2 and C1 are flipped 602 static Value *foldSelectICmpAndOr(const ICmpInst *IC, Value *TrueVal, 603 Value *FalseVal, 604 InstCombiner::BuilderTy &Builder) { 605 // Only handle integer compares. Also, if this is a vector select, we need a 606 // vector compare. 607 if (!TrueVal->getType()->isIntOrIntVectorTy() || 608 TrueVal->getType()->isVectorTy() != IC->getType()->isVectorTy()) 609 return nullptr; 610 611 Value *CmpLHS = IC->getOperand(0); 612 Value *CmpRHS = IC->getOperand(1); 613 614 Value *V; 615 unsigned C1Log; 616 bool IsEqualZero; 617 bool NeedAnd = false; 618 if (IC->isEquality()) { 619 if (!match(CmpRHS, m_Zero())) 620 return nullptr; 621 622 const APInt *C1; 623 if (!match(CmpLHS, m_And(m_Value(), m_Power2(C1)))) 624 return nullptr; 625 626 V = CmpLHS; 627 C1Log = C1->logBase2(); 628 IsEqualZero = IC->getPredicate() == ICmpInst::ICMP_EQ; 629 } else if (IC->getPredicate() == ICmpInst::ICMP_SLT || 630 IC->getPredicate() == ICmpInst::ICMP_SGT) { 631 // We also need to recognize (icmp slt (trunc (X)), 0) and 632 // (icmp sgt (trunc (X)), -1). 633 IsEqualZero = IC->getPredicate() == ICmpInst::ICMP_SGT; 634 if ((IsEqualZero && !match(CmpRHS, m_AllOnes())) || 635 (!IsEqualZero && !match(CmpRHS, m_Zero()))) 636 return nullptr; 637 638 if (!match(CmpLHS, m_OneUse(m_Trunc(m_Value(V))))) 639 return nullptr; 640 641 C1Log = CmpLHS->getType()->getScalarSizeInBits() - 1; 642 NeedAnd = true; 643 } else { 644 return nullptr; 645 } 646 647 const APInt *C2; 648 bool OrOnTrueVal = false; 649 bool OrOnFalseVal = match(FalseVal, m_Or(m_Specific(TrueVal), m_Power2(C2))); 650 if (!OrOnFalseVal) 651 OrOnTrueVal = match(TrueVal, m_Or(m_Specific(FalseVal), m_Power2(C2))); 652 653 if (!OrOnFalseVal && !OrOnTrueVal) 654 return nullptr; 655 656 Value *Y = OrOnFalseVal ? TrueVal : FalseVal; 657 658 unsigned C2Log = C2->logBase2(); 659 660 bool NeedXor = (!IsEqualZero && OrOnFalseVal) || (IsEqualZero && OrOnTrueVal); 661 bool NeedShift = C1Log != C2Log; 662 bool NeedZExtTrunc = Y->getType()->getScalarSizeInBits() != 663 V->getType()->getScalarSizeInBits(); 664 665 // Make sure we don't create more instructions than we save. 666 Value *Or = OrOnFalseVal ? FalseVal : TrueVal; 667 if ((NeedShift + NeedXor + NeedZExtTrunc) > 668 (IC->hasOneUse() + Or->hasOneUse())) 669 return nullptr; 670 671 if (NeedAnd) { 672 // Insert the AND instruction on the input to the truncate. 673 APInt C1 = APInt::getOneBitSet(V->getType()->getScalarSizeInBits(), C1Log); 674 V = Builder.CreateAnd(V, ConstantInt::get(V->getType(), C1)); 675 } 676 677 if (C2Log > C1Log) { 678 V = Builder.CreateZExtOrTrunc(V, Y->getType()); 679 V = Builder.CreateShl(V, C2Log - C1Log); 680 } else if (C1Log > C2Log) { 681 V = Builder.CreateLShr(V, C1Log - C2Log); 682 V = Builder.CreateZExtOrTrunc(V, Y->getType()); 683 } else 684 V = Builder.CreateZExtOrTrunc(V, Y->getType()); 685 686 if (NeedXor) 687 V = Builder.CreateXor(V, *C2); 688 689 return Builder.CreateOr(V, Y); 690 } 691 692 /// Canonicalize a set or clear of a masked set of constant bits to 693 /// select-of-constants form. 694 static Instruction *foldSetClearBits(SelectInst &Sel, 695 InstCombiner::BuilderTy &Builder) { 696 Value *Cond = Sel.getCondition(); 697 Value *T = Sel.getTrueValue(); 698 Value *F = Sel.getFalseValue(); 699 Type *Ty = Sel.getType(); 700 Value *X; 701 const APInt *NotC, *C; 702 703 // Cond ? (X & ~C) : (X | C) --> (X & ~C) | (Cond ? 0 : C) 704 if (match(T, m_And(m_Value(X), m_APInt(NotC))) && 705 match(F, m_OneUse(m_Or(m_Specific(X), m_APInt(C)))) && *NotC == ~(*C)) { 706 Constant *Zero = ConstantInt::getNullValue(Ty); 707 Constant *OrC = ConstantInt::get(Ty, *C); 708 Value *NewSel = Builder.CreateSelect(Cond, Zero, OrC, "masksel", &Sel); 709 return BinaryOperator::CreateOr(T, NewSel); 710 } 711 712 // Cond ? (X | C) : (X & ~C) --> (X & ~C) | (Cond ? C : 0) 713 if (match(F, m_And(m_Value(X), m_APInt(NotC))) && 714 match(T, m_OneUse(m_Or(m_Specific(X), m_APInt(C)))) && *NotC == ~(*C)) { 715 Constant *Zero = ConstantInt::getNullValue(Ty); 716 Constant *OrC = ConstantInt::get(Ty, *C); 717 Value *NewSel = Builder.CreateSelect(Cond, OrC, Zero, "masksel", &Sel); 718 return BinaryOperator::CreateOr(F, NewSel); 719 } 720 721 return nullptr; 722 } 723 724 // select (x == 0), 0, x * y --> freeze(y) * x 725 // select (y == 0), 0, x * y --> freeze(x) * y 726 // select (x == 0), undef, x * y --> freeze(y) * x 727 // select (x == undef), 0, x * y --> freeze(y) * x 728 // Usage of mul instead of 0 will make the result more poisonous, 729 // so the operand that was not checked in the condition should be frozen. 730 // The latter folding is applied only when a constant compared with x is 731 // is a vector consisting of 0 and undefs. If a constant compared with x 732 // is a scalar undefined value or undefined vector then an expression 733 // should be already folded into a constant. 734 static Instruction *foldSelectZeroOrMul(SelectInst &SI, InstCombinerImpl &IC) { 735 auto *CondVal = SI.getCondition(); 736 auto *TrueVal = SI.getTrueValue(); 737 auto *FalseVal = SI.getFalseValue(); 738 Value *X, *Y; 739 ICmpInst::Predicate Predicate; 740 741 // Assuming that constant compared with zero is not undef (but it may be 742 // a vector with some undef elements). Otherwise (when a constant is undef) 743 // the select expression should be already simplified. 744 if (!match(CondVal, m_ICmp(Predicate, m_Value(X), m_Zero())) || 745 !ICmpInst::isEquality(Predicate)) 746 return nullptr; 747 748 if (Predicate == ICmpInst::ICMP_NE) 749 std::swap(TrueVal, FalseVal); 750 751 // Check that TrueVal is a constant instead of matching it with m_Zero() 752 // to handle the case when it is a scalar undef value or a vector containing 753 // non-zero elements that are masked by undef elements in the compare 754 // constant. 755 auto *TrueValC = dyn_cast<Constant>(TrueVal); 756 if (TrueValC == nullptr || 757 !match(FalseVal, m_c_Mul(m_Specific(X), m_Value(Y))) || 758 !isa<Instruction>(FalseVal)) 759 return nullptr; 760 761 auto *ZeroC = cast<Constant>(cast<Instruction>(CondVal)->getOperand(1)); 762 auto *MergedC = Constant::mergeUndefsWith(TrueValC, ZeroC); 763 // If X is compared with 0 then TrueVal could be either zero or undef. 764 // m_Zero match vectors containing some undef elements, but for scalars 765 // m_Undef should be used explicitly. 766 if (!match(MergedC, m_Zero()) && !match(MergedC, m_Undef())) 767 return nullptr; 768 769 auto *FalseValI = cast<Instruction>(FalseVal); 770 auto *FrY = IC.InsertNewInstBefore(new FreezeInst(Y, Y->getName() + ".fr"), 771 *FalseValI); 772 IC.replaceOperand(*FalseValI, FalseValI->getOperand(0) == Y ? 0 : 1, FrY); 773 return IC.replaceInstUsesWith(SI, FalseValI); 774 } 775 776 /// Transform patterns such as (a > b) ? a - b : 0 into usub.sat(a, b). 777 /// There are 8 commuted/swapped variants of this pattern. 778 /// TODO: Also support a - UMIN(a,b) patterns. 779 static Value *canonicalizeSaturatedSubtract(const ICmpInst *ICI, 780 const Value *TrueVal, 781 const Value *FalseVal, 782 InstCombiner::BuilderTy &Builder) { 783 ICmpInst::Predicate Pred = ICI->getPredicate(); 784 if (!ICmpInst::isUnsigned(Pred)) 785 return nullptr; 786 787 // (b > a) ? 0 : a - b -> (b <= a) ? a - b : 0 788 if (match(TrueVal, m_Zero())) { 789 Pred = ICmpInst::getInversePredicate(Pred); 790 std::swap(TrueVal, FalseVal); 791 } 792 if (!match(FalseVal, m_Zero())) 793 return nullptr; 794 795 Value *A = ICI->getOperand(0); 796 Value *B = ICI->getOperand(1); 797 if (Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_ULT) { 798 // (b < a) ? a - b : 0 -> (a > b) ? a - b : 0 799 std::swap(A, B); 800 Pred = ICmpInst::getSwappedPredicate(Pred); 801 } 802 803 assert((Pred == ICmpInst::ICMP_UGE || Pred == ICmpInst::ICMP_UGT) && 804 "Unexpected isUnsigned predicate!"); 805 806 // Ensure the sub is of the form: 807 // (a > b) ? a - b : 0 -> usub.sat(a, b) 808 // (a > b) ? b - a : 0 -> -usub.sat(a, b) 809 // Checking for both a-b and a+(-b) as a constant. 810 bool IsNegative = false; 811 const APInt *C; 812 if (match(TrueVal, m_Sub(m_Specific(B), m_Specific(A))) || 813 (match(A, m_APInt(C)) && 814 match(TrueVal, m_Add(m_Specific(B), m_SpecificInt(-*C))))) 815 IsNegative = true; 816 else if (!match(TrueVal, m_Sub(m_Specific(A), m_Specific(B))) && 817 !(match(B, m_APInt(C)) && 818 match(TrueVal, m_Add(m_Specific(A), m_SpecificInt(-*C))))) 819 return nullptr; 820 821 // If we are adding a negate and the sub and icmp are used anywhere else, we 822 // would end up with more instructions. 823 if (IsNegative && !TrueVal->hasOneUse() && !ICI->hasOneUse()) 824 return nullptr; 825 826 // (a > b) ? a - b : 0 -> usub.sat(a, b) 827 // (a > b) ? b - a : 0 -> -usub.sat(a, b) 828 Value *Result = Builder.CreateBinaryIntrinsic(Intrinsic::usub_sat, A, B); 829 if (IsNegative) 830 Result = Builder.CreateNeg(Result); 831 return Result; 832 } 833 834 static Value *canonicalizeSaturatedAdd(ICmpInst *Cmp, Value *TVal, Value *FVal, 835 InstCombiner::BuilderTy &Builder) { 836 if (!Cmp->hasOneUse()) 837 return nullptr; 838 839 // Match unsigned saturated add with constant. 840 Value *Cmp0 = Cmp->getOperand(0); 841 Value *Cmp1 = Cmp->getOperand(1); 842 ICmpInst::Predicate Pred = Cmp->getPredicate(); 843 Value *X; 844 const APInt *C, *CmpC; 845 if (Pred == ICmpInst::ICMP_ULT && 846 match(TVal, m_Add(m_Value(X), m_APInt(C))) && X == Cmp0 && 847 match(FVal, m_AllOnes()) && match(Cmp1, m_APInt(CmpC)) && *CmpC == ~*C) { 848 // (X u< ~C) ? (X + C) : -1 --> uadd.sat(X, C) 849 return Builder.CreateBinaryIntrinsic( 850 Intrinsic::uadd_sat, X, ConstantInt::get(X->getType(), *C)); 851 } 852 853 // Match unsigned saturated add of 2 variables with an unnecessary 'not'. 854 // There are 8 commuted variants. 855 // Canonicalize -1 (saturated result) to true value of the select. 856 if (match(FVal, m_AllOnes())) { 857 std::swap(TVal, FVal); 858 Pred = CmpInst::getInversePredicate(Pred); 859 } 860 if (!match(TVal, m_AllOnes())) 861 return nullptr; 862 863 // Canonicalize predicate to less-than or less-or-equal-than. 864 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE) { 865 std::swap(Cmp0, Cmp1); 866 Pred = CmpInst::getSwappedPredicate(Pred); 867 } 868 if (Pred != ICmpInst::ICMP_ULT && Pred != ICmpInst::ICMP_ULE) 869 return nullptr; 870 871 // Match unsigned saturated add of 2 variables with an unnecessary 'not'. 872 // Strictness of the comparison is irrelevant. 873 Value *Y; 874 if (match(Cmp0, m_Not(m_Value(X))) && 875 match(FVal, m_c_Add(m_Specific(X), m_Value(Y))) && Y == Cmp1) { 876 // (~X u< Y) ? -1 : (X + Y) --> uadd.sat(X, Y) 877 // (~X u< Y) ? -1 : (Y + X) --> uadd.sat(X, Y) 878 return Builder.CreateBinaryIntrinsic(Intrinsic::uadd_sat, X, Y); 879 } 880 // The 'not' op may be included in the sum but not the compare. 881 // Strictness of the comparison is irrelevant. 882 X = Cmp0; 883 Y = Cmp1; 884 if (match(FVal, m_c_Add(m_Not(m_Specific(X)), m_Specific(Y)))) { 885 // (X u< Y) ? -1 : (~X + Y) --> uadd.sat(~X, Y) 886 // (X u< Y) ? -1 : (Y + ~X) --> uadd.sat(Y, ~X) 887 BinaryOperator *BO = cast<BinaryOperator>(FVal); 888 return Builder.CreateBinaryIntrinsic( 889 Intrinsic::uadd_sat, BO->getOperand(0), BO->getOperand(1)); 890 } 891 // The overflow may be detected via the add wrapping round. 892 // This is only valid for strict comparison! 893 if (Pred == ICmpInst::ICMP_ULT && 894 match(Cmp0, m_c_Add(m_Specific(Cmp1), m_Value(Y))) && 895 match(FVal, m_c_Add(m_Specific(Cmp1), m_Specific(Y)))) { 896 // ((X + Y) u< X) ? -1 : (X + Y) --> uadd.sat(X, Y) 897 // ((X + Y) u< Y) ? -1 : (X + Y) --> uadd.sat(X, Y) 898 return Builder.CreateBinaryIntrinsic(Intrinsic::uadd_sat, Cmp1, Y); 899 } 900 901 return nullptr; 902 } 903 904 /// Fold the following code sequence: 905 /// \code 906 /// int a = ctlz(x & -x); 907 // x ? 31 - a : a; 908 /// \code 909 /// 910 /// into: 911 /// cttz(x) 912 static Instruction *foldSelectCtlzToCttz(ICmpInst *ICI, Value *TrueVal, 913 Value *FalseVal, 914 InstCombiner::BuilderTy &Builder) { 915 unsigned BitWidth = TrueVal->getType()->getScalarSizeInBits(); 916 if (!ICI->isEquality() || !match(ICI->getOperand(1), m_Zero())) 917 return nullptr; 918 919 if (ICI->getPredicate() == ICmpInst::ICMP_NE) 920 std::swap(TrueVal, FalseVal); 921 922 if (!match(FalseVal, 923 m_Xor(m_Deferred(TrueVal), m_SpecificInt(BitWidth - 1)))) 924 return nullptr; 925 926 if (!match(TrueVal, m_Intrinsic<Intrinsic::ctlz>())) 927 return nullptr; 928 929 Value *X = ICI->getOperand(0); 930 auto *II = cast<IntrinsicInst>(TrueVal); 931 if (!match(II->getOperand(0), m_c_And(m_Specific(X), m_Neg(m_Specific(X))))) 932 return nullptr; 933 934 Function *F = Intrinsic::getDeclaration(II->getModule(), Intrinsic::cttz, 935 II->getType()); 936 return CallInst::Create(F, {X, II->getArgOperand(1)}); 937 } 938 939 /// Attempt to fold a cttz/ctlz followed by a icmp plus select into a single 940 /// call to cttz/ctlz with flag 'is_zero_poison' cleared. 941 /// 942 /// For example, we can fold the following code sequence: 943 /// \code 944 /// %0 = tail call i32 @llvm.cttz.i32(i32 %x, i1 true) 945 /// %1 = icmp ne i32 %x, 0 946 /// %2 = select i1 %1, i32 %0, i32 32 947 /// \code 948 /// 949 /// into: 950 /// %0 = tail call i32 @llvm.cttz.i32(i32 %x, i1 false) 951 static Value *foldSelectCttzCtlz(ICmpInst *ICI, Value *TrueVal, Value *FalseVal, 952 InstCombiner::BuilderTy &Builder) { 953 ICmpInst::Predicate Pred = ICI->getPredicate(); 954 Value *CmpLHS = ICI->getOperand(0); 955 Value *CmpRHS = ICI->getOperand(1); 956 957 // Check if the condition value compares a value for equality against zero. 958 if (!ICI->isEquality() || !match(CmpRHS, m_Zero())) 959 return nullptr; 960 961 Value *SelectArg = FalseVal; 962 Value *ValueOnZero = TrueVal; 963 if (Pred == ICmpInst::ICMP_NE) 964 std::swap(SelectArg, ValueOnZero); 965 966 // Skip zero extend/truncate. 967 Value *Count = nullptr; 968 if (!match(SelectArg, m_ZExt(m_Value(Count))) && 969 !match(SelectArg, m_Trunc(m_Value(Count)))) 970 Count = SelectArg; 971 972 // Check that 'Count' is a call to intrinsic cttz/ctlz. Also check that the 973 // input to the cttz/ctlz is used as LHS for the compare instruction. 974 if (!match(Count, m_Intrinsic<Intrinsic::cttz>(m_Specific(CmpLHS))) && 975 !match(Count, m_Intrinsic<Intrinsic::ctlz>(m_Specific(CmpLHS)))) 976 return nullptr; 977 978 IntrinsicInst *II = cast<IntrinsicInst>(Count); 979 980 // Check if the value propagated on zero is a constant number equal to the 981 // sizeof in bits of 'Count'. 982 unsigned SizeOfInBits = Count->getType()->getScalarSizeInBits(); 983 if (match(ValueOnZero, m_SpecificInt(SizeOfInBits))) { 984 // Explicitly clear the 'is_zero_poison' flag. It's always valid to go from 985 // true to false on this flag, so we can replace it for all users. 986 II->setArgOperand(1, ConstantInt::getFalse(II->getContext())); 987 return SelectArg; 988 } 989 990 // The ValueOnZero is not the bitwidth. But if the cttz/ctlz (and optional 991 // zext/trunc) have one use (ending at the select), the cttz/ctlz result will 992 // not be used if the input is zero. Relax to 'zero is poison' for that case. 993 if (II->hasOneUse() && SelectArg->hasOneUse() && 994 !match(II->getArgOperand(1), m_One())) 995 II->setArgOperand(1, ConstantInt::getTrue(II->getContext())); 996 997 return nullptr; 998 } 999 1000 /// Return true if we find and adjust an icmp+select pattern where the compare 1001 /// is with a constant that can be incremented or decremented to match the 1002 /// minimum or maximum idiom. 1003 static bool adjustMinMax(SelectInst &Sel, ICmpInst &Cmp) { 1004 ICmpInst::Predicate Pred = Cmp.getPredicate(); 1005 Value *CmpLHS = Cmp.getOperand(0); 1006 Value *CmpRHS = Cmp.getOperand(1); 1007 Value *TrueVal = Sel.getTrueValue(); 1008 Value *FalseVal = Sel.getFalseValue(); 1009 1010 // We may move or edit the compare, so make sure the select is the only user. 1011 const APInt *CmpC; 1012 if (!Cmp.hasOneUse() || !match(CmpRHS, m_APInt(CmpC))) 1013 return false; 1014 1015 // These transforms only work for selects of integers or vector selects of 1016 // integer vectors. 1017 Type *SelTy = Sel.getType(); 1018 auto *SelEltTy = dyn_cast<IntegerType>(SelTy->getScalarType()); 1019 if (!SelEltTy || SelTy->isVectorTy() != Cmp.getType()->isVectorTy()) 1020 return false; 1021 1022 Constant *AdjustedRHS; 1023 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_SGT) 1024 AdjustedRHS = ConstantInt::get(CmpRHS->getType(), *CmpC + 1); 1025 else if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT) 1026 AdjustedRHS = ConstantInt::get(CmpRHS->getType(), *CmpC - 1); 1027 else 1028 return false; 1029 1030 // X > C ? X : C+1 --> X < C+1 ? C+1 : X 1031 // X < C ? X : C-1 --> X > C-1 ? C-1 : X 1032 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) || 1033 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) { 1034 ; // Nothing to do here. Values match without any sign/zero extension. 1035 } 1036 // Types do not match. Instead of calculating this with mixed types, promote 1037 // all to the larger type. This enables scalar evolution to analyze this 1038 // expression. 1039 else if (CmpRHS->getType()->getScalarSizeInBits() < SelEltTy->getBitWidth()) { 1040 Constant *SextRHS = ConstantExpr::getSExt(AdjustedRHS, SelTy); 1041 1042 // X = sext x; x >s c ? X : C+1 --> X = sext x; X <s C+1 ? C+1 : X 1043 // X = sext x; x <s c ? X : C-1 --> X = sext x; X >s C-1 ? C-1 : X 1044 // X = sext x; x >u c ? X : C+1 --> X = sext x; X <u C+1 ? C+1 : X 1045 // X = sext x; x <u c ? X : C-1 --> X = sext x; X >u C-1 ? C-1 : X 1046 if (match(TrueVal, m_SExt(m_Specific(CmpLHS))) && SextRHS == FalseVal) { 1047 CmpLHS = TrueVal; 1048 AdjustedRHS = SextRHS; 1049 } else if (match(FalseVal, m_SExt(m_Specific(CmpLHS))) && 1050 SextRHS == TrueVal) { 1051 CmpLHS = FalseVal; 1052 AdjustedRHS = SextRHS; 1053 } else if (Cmp.isUnsigned()) { 1054 Constant *ZextRHS = ConstantExpr::getZExt(AdjustedRHS, SelTy); 1055 // X = zext x; x >u c ? X : C+1 --> X = zext x; X <u C+1 ? C+1 : X 1056 // X = zext x; x <u c ? X : C-1 --> X = zext x; X >u C-1 ? C-1 : X 1057 // zext + signed compare cannot be changed: 1058 // 0xff <s 0x00, but 0x00ff >s 0x0000 1059 if (match(TrueVal, m_ZExt(m_Specific(CmpLHS))) && ZextRHS == FalseVal) { 1060 CmpLHS = TrueVal; 1061 AdjustedRHS = ZextRHS; 1062 } else if (match(FalseVal, m_ZExt(m_Specific(CmpLHS))) && 1063 ZextRHS == TrueVal) { 1064 CmpLHS = FalseVal; 1065 AdjustedRHS = ZextRHS; 1066 } else { 1067 return false; 1068 } 1069 } else { 1070 return false; 1071 } 1072 } else { 1073 return false; 1074 } 1075 1076 Pred = ICmpInst::getSwappedPredicate(Pred); 1077 CmpRHS = AdjustedRHS; 1078 std::swap(FalseVal, TrueVal); 1079 Cmp.setPredicate(Pred); 1080 Cmp.setOperand(0, CmpLHS); 1081 Cmp.setOperand(1, CmpRHS); 1082 Sel.setOperand(1, TrueVal); 1083 Sel.setOperand(2, FalseVal); 1084 Sel.swapProfMetadata(); 1085 1086 // Move the compare instruction right before the select instruction. Otherwise 1087 // the sext/zext value may be defined after the compare instruction uses it. 1088 Cmp.moveBefore(&Sel); 1089 1090 return true; 1091 } 1092 1093 static Instruction *canonicalizeSPF(SelectInst &Sel, ICmpInst &Cmp, 1094 InstCombinerImpl &IC) { 1095 Value *LHS, *RHS; 1096 // TODO: What to do with pointer min/max patterns? 1097 if (!Sel.getType()->isIntOrIntVectorTy()) 1098 return nullptr; 1099 1100 SelectPatternFlavor SPF = matchSelectPattern(&Sel, LHS, RHS).Flavor; 1101 if (SPF == SelectPatternFlavor::SPF_ABS || 1102 SPF == SelectPatternFlavor::SPF_NABS) { 1103 if (!Cmp.hasOneUse() && !RHS->hasOneUse()) 1104 return nullptr; // TODO: Relax this restriction. 1105 1106 // Note that NSW flag can only be propagated for normal, non-negated abs! 1107 bool IntMinIsPoison = SPF == SelectPatternFlavor::SPF_ABS && 1108 match(RHS, m_NSWNeg(m_Specific(LHS))); 1109 Constant *IntMinIsPoisonC = 1110 ConstantInt::get(Type::getInt1Ty(Sel.getContext()), IntMinIsPoison); 1111 Instruction *Abs = 1112 IC.Builder.CreateBinaryIntrinsic(Intrinsic::abs, LHS, IntMinIsPoisonC); 1113 1114 if (SPF == SelectPatternFlavor::SPF_NABS) 1115 return BinaryOperator::CreateNeg(Abs); // Always without NSW flag! 1116 return IC.replaceInstUsesWith(Sel, Abs); 1117 } 1118 1119 if (SelectPatternResult::isMinOrMax(SPF)) { 1120 Intrinsic::ID IntrinsicID; 1121 switch (SPF) { 1122 case SelectPatternFlavor::SPF_UMIN: 1123 IntrinsicID = Intrinsic::umin; 1124 break; 1125 case SelectPatternFlavor::SPF_UMAX: 1126 IntrinsicID = Intrinsic::umax; 1127 break; 1128 case SelectPatternFlavor::SPF_SMIN: 1129 IntrinsicID = Intrinsic::smin; 1130 break; 1131 case SelectPatternFlavor::SPF_SMAX: 1132 IntrinsicID = Intrinsic::smax; 1133 break; 1134 default: 1135 llvm_unreachable("Unexpected SPF"); 1136 } 1137 return IC.replaceInstUsesWith( 1138 Sel, IC.Builder.CreateBinaryIntrinsic(IntrinsicID, LHS, RHS)); 1139 } 1140 1141 return nullptr; 1142 } 1143 1144 /// If we have a select with an equality comparison, then we know the value in 1145 /// one of the arms of the select. See if substituting this value into an arm 1146 /// and simplifying the result yields the same value as the other arm. 1147 /// 1148 /// To make this transform safe, we must drop poison-generating flags 1149 /// (nsw, etc) if we simplified to a binop because the select may be guarding 1150 /// that poison from propagating. If the existing binop already had no 1151 /// poison-generating flags, then this transform can be done by instsimplify. 1152 /// 1153 /// Consider: 1154 /// %cmp = icmp eq i32 %x, 2147483647 1155 /// %add = add nsw i32 %x, 1 1156 /// %sel = select i1 %cmp, i32 -2147483648, i32 %add 1157 /// 1158 /// We can't replace %sel with %add unless we strip away the flags. 1159 /// TODO: Wrapping flags could be preserved in some cases with better analysis. 1160 Instruction *InstCombinerImpl::foldSelectValueEquivalence(SelectInst &Sel, 1161 ICmpInst &Cmp) { 1162 // Value equivalence substitution requires an all-or-nothing replacement. 1163 // It does not make sense for a vector compare where each lane is chosen 1164 // independently. 1165 if (!Cmp.isEquality() || Cmp.getType()->isVectorTy()) 1166 return nullptr; 1167 1168 // Canonicalize the pattern to ICMP_EQ by swapping the select operands. 1169 Value *TrueVal = Sel.getTrueValue(), *FalseVal = Sel.getFalseValue(); 1170 bool Swapped = false; 1171 if (Cmp.getPredicate() == ICmpInst::ICMP_NE) { 1172 std::swap(TrueVal, FalseVal); 1173 Swapped = true; 1174 } 1175 1176 // In X == Y ? f(X) : Z, try to evaluate f(Y) and replace the operand. 1177 // Make sure Y cannot be undef though, as we might pick different values for 1178 // undef in the icmp and in f(Y). Additionally, take care to avoid replacing 1179 // X == Y ? X : Z with X == Y ? Y : Z, as that would lead to an infinite 1180 // replacement cycle. 1181 Value *CmpLHS = Cmp.getOperand(0), *CmpRHS = Cmp.getOperand(1); 1182 if (TrueVal != CmpLHS && 1183 isGuaranteedNotToBeUndefOrPoison(CmpRHS, SQ.AC, &Sel, &DT)) { 1184 if (Value *V = simplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, SQ, 1185 /* AllowRefinement */ true)) 1186 return replaceOperand(Sel, Swapped ? 2 : 1, V); 1187 1188 // Even if TrueVal does not simplify, we can directly replace a use of 1189 // CmpLHS with CmpRHS, as long as the instruction is not used anywhere 1190 // else and is safe to speculatively execute (we may end up executing it 1191 // with different operands, which should not cause side-effects or trigger 1192 // undefined behavior). Only do this if CmpRHS is a constant, as 1193 // profitability is not clear for other cases. 1194 // FIXME: The replacement could be performed recursively. 1195 if (match(CmpRHS, m_ImmConstant()) && !match(CmpLHS, m_ImmConstant())) 1196 if (auto *I = dyn_cast<Instruction>(TrueVal)) 1197 if (I->hasOneUse() && isSafeToSpeculativelyExecute(I)) 1198 for (Use &U : I->operands()) 1199 if (U == CmpLHS) { 1200 replaceUse(U, CmpRHS); 1201 return &Sel; 1202 } 1203 } 1204 if (TrueVal != CmpRHS && 1205 isGuaranteedNotToBeUndefOrPoison(CmpLHS, SQ.AC, &Sel, &DT)) 1206 if (Value *V = simplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, SQ, 1207 /* AllowRefinement */ true)) 1208 return replaceOperand(Sel, Swapped ? 2 : 1, V); 1209 1210 auto *FalseInst = dyn_cast<Instruction>(FalseVal); 1211 if (!FalseInst) 1212 return nullptr; 1213 1214 // InstSimplify already performed this fold if it was possible subject to 1215 // current poison-generating flags. Try the transform again with 1216 // poison-generating flags temporarily dropped. 1217 bool WasNUW = false, WasNSW = false, WasExact = false, WasInBounds = false; 1218 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(FalseVal)) { 1219 WasNUW = OBO->hasNoUnsignedWrap(); 1220 WasNSW = OBO->hasNoSignedWrap(); 1221 FalseInst->setHasNoUnsignedWrap(false); 1222 FalseInst->setHasNoSignedWrap(false); 1223 } 1224 if (auto *PEO = dyn_cast<PossiblyExactOperator>(FalseVal)) { 1225 WasExact = PEO->isExact(); 1226 FalseInst->setIsExact(false); 1227 } 1228 if (auto *GEP = dyn_cast<GetElementPtrInst>(FalseVal)) { 1229 WasInBounds = GEP->isInBounds(); 1230 GEP->setIsInBounds(false); 1231 } 1232 1233 // Try each equivalence substitution possibility. 1234 // We have an 'EQ' comparison, so the select's false value will propagate. 1235 // Example: 1236 // (X == 42) ? 43 : (X + 1) --> (X == 42) ? (X + 1) : (X + 1) --> X + 1 1237 if (simplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, SQ, 1238 /* AllowRefinement */ false) == TrueVal || 1239 simplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, SQ, 1240 /* AllowRefinement */ false) == TrueVal) { 1241 return replaceInstUsesWith(Sel, FalseVal); 1242 } 1243 1244 // Restore poison-generating flags if the transform did not apply. 1245 if (WasNUW) 1246 FalseInst->setHasNoUnsignedWrap(); 1247 if (WasNSW) 1248 FalseInst->setHasNoSignedWrap(); 1249 if (WasExact) 1250 FalseInst->setIsExact(); 1251 if (WasInBounds) 1252 cast<GetElementPtrInst>(FalseInst)->setIsInBounds(); 1253 1254 return nullptr; 1255 } 1256 1257 // See if this is a pattern like: 1258 // %old_cmp1 = icmp slt i32 %x, C2 1259 // %old_replacement = select i1 %old_cmp1, i32 %target_low, i32 %target_high 1260 // %old_x_offseted = add i32 %x, C1 1261 // %old_cmp0 = icmp ult i32 %old_x_offseted, C0 1262 // %r = select i1 %old_cmp0, i32 %x, i32 %old_replacement 1263 // This can be rewritten as more canonical pattern: 1264 // %new_cmp1 = icmp slt i32 %x, -C1 1265 // %new_cmp2 = icmp sge i32 %x, C0-C1 1266 // %new_clamped_low = select i1 %new_cmp1, i32 %target_low, i32 %x 1267 // %r = select i1 %new_cmp2, i32 %target_high, i32 %new_clamped_low 1268 // Iff -C1 s<= C2 s<= C0-C1 1269 // Also ULT predicate can also be UGT iff C0 != -1 (+invert result) 1270 // SLT predicate can also be SGT iff C2 != INT_MAX (+invert res.) 1271 static Value *canonicalizeClampLike(SelectInst &Sel0, ICmpInst &Cmp0, 1272 InstCombiner::BuilderTy &Builder) { 1273 Value *X = Sel0.getTrueValue(); 1274 Value *Sel1 = Sel0.getFalseValue(); 1275 1276 // First match the condition of the outermost select. 1277 // Said condition must be one-use. 1278 if (!Cmp0.hasOneUse()) 1279 return nullptr; 1280 ICmpInst::Predicate Pred0 = Cmp0.getPredicate(); 1281 Value *Cmp00 = Cmp0.getOperand(0); 1282 Constant *C0; 1283 if (!match(Cmp0.getOperand(1), 1284 m_CombineAnd(m_AnyIntegralConstant(), m_Constant(C0)))) 1285 return nullptr; 1286 1287 if (!isa<SelectInst>(Sel1)) { 1288 Pred0 = ICmpInst::getInversePredicate(Pred0); 1289 std::swap(X, Sel1); 1290 } 1291 1292 // Canonicalize Cmp0 into ult or uge. 1293 // FIXME: we shouldn't care about lanes that are 'undef' in the end? 1294 switch (Pred0) { 1295 case ICmpInst::Predicate::ICMP_ULT: 1296 case ICmpInst::Predicate::ICMP_UGE: 1297 // Although icmp ult %x, 0 is an unusual thing to try and should generally 1298 // have been simplified, it does not verify with undef inputs so ensure we 1299 // are not in a strange state. 1300 if (!match(C0, m_SpecificInt_ICMP( 1301 ICmpInst::Predicate::ICMP_NE, 1302 APInt::getZero(C0->getType()->getScalarSizeInBits())))) 1303 return nullptr; 1304 break; // Great! 1305 case ICmpInst::Predicate::ICMP_ULE: 1306 case ICmpInst::Predicate::ICMP_UGT: 1307 // We want to canonicalize it to 'ult' or 'uge', so we'll need to increment 1308 // C0, which again means it must not have any all-ones elements. 1309 if (!match(C0, 1310 m_SpecificInt_ICMP( 1311 ICmpInst::Predicate::ICMP_NE, 1312 APInt::getAllOnes(C0->getType()->getScalarSizeInBits())))) 1313 return nullptr; // Can't do, have all-ones element[s]. 1314 C0 = InstCombiner::AddOne(C0); 1315 break; 1316 default: 1317 return nullptr; // Unknown predicate. 1318 } 1319 1320 // Now that we've canonicalized the ICmp, we know the X we expect; 1321 // the select in other hand should be one-use. 1322 if (!Sel1->hasOneUse()) 1323 return nullptr; 1324 1325 // If the types do not match, look through any truncs to the underlying 1326 // instruction. 1327 if (Cmp00->getType() != X->getType() && X->hasOneUse()) 1328 match(X, m_TruncOrSelf(m_Value(X))); 1329 1330 // We now can finish matching the condition of the outermost select: 1331 // it should either be the X itself, or an addition of some constant to X. 1332 Constant *C1; 1333 if (Cmp00 == X) 1334 C1 = ConstantInt::getNullValue(X->getType()); 1335 else if (!match(Cmp00, 1336 m_Add(m_Specific(X), 1337 m_CombineAnd(m_AnyIntegralConstant(), m_Constant(C1))))) 1338 return nullptr; 1339 1340 Value *Cmp1; 1341 ICmpInst::Predicate Pred1; 1342 Constant *C2; 1343 Value *ReplacementLow, *ReplacementHigh; 1344 if (!match(Sel1, m_Select(m_Value(Cmp1), m_Value(ReplacementLow), 1345 m_Value(ReplacementHigh))) || 1346 !match(Cmp1, 1347 m_ICmp(Pred1, m_Specific(X), 1348 m_CombineAnd(m_AnyIntegralConstant(), m_Constant(C2))))) 1349 return nullptr; 1350 1351 if (!Cmp1->hasOneUse() && (Cmp00 == X || !Cmp00->hasOneUse())) 1352 return nullptr; // Not enough one-use instructions for the fold. 1353 // FIXME: this restriction could be relaxed if Cmp1 can be reused as one of 1354 // two comparisons we'll need to build. 1355 1356 // Canonicalize Cmp1 into the form we expect. 1357 // FIXME: we shouldn't care about lanes that are 'undef' in the end? 1358 switch (Pred1) { 1359 case ICmpInst::Predicate::ICMP_SLT: 1360 break; 1361 case ICmpInst::Predicate::ICMP_SLE: 1362 // We'd have to increment C2 by one, and for that it must not have signed 1363 // max element, but then it would have been canonicalized to 'slt' before 1364 // we get here. So we can't do anything useful with 'sle'. 1365 return nullptr; 1366 case ICmpInst::Predicate::ICMP_SGT: 1367 // We want to canonicalize it to 'slt', so we'll need to increment C2, 1368 // which again means it must not have any signed max elements. 1369 if (!match(C2, 1370 m_SpecificInt_ICMP(ICmpInst::Predicate::ICMP_NE, 1371 APInt::getSignedMaxValue( 1372 C2->getType()->getScalarSizeInBits())))) 1373 return nullptr; // Can't do, have signed max element[s]. 1374 C2 = InstCombiner::AddOne(C2); 1375 LLVM_FALLTHROUGH; 1376 case ICmpInst::Predicate::ICMP_SGE: 1377 // Also non-canonical, but here we don't need to change C2, 1378 // so we don't have any restrictions on C2, so we can just handle it. 1379 std::swap(ReplacementLow, ReplacementHigh); 1380 break; 1381 default: 1382 return nullptr; // Unknown predicate. 1383 } 1384 1385 // The thresholds of this clamp-like pattern. 1386 auto *ThresholdLowIncl = ConstantExpr::getNeg(C1); 1387 auto *ThresholdHighExcl = ConstantExpr::getSub(C0, C1); 1388 if (Pred0 == ICmpInst::Predicate::ICMP_UGE) 1389 std::swap(ThresholdLowIncl, ThresholdHighExcl); 1390 1391 // The fold has a precondition 1: C2 s>= ThresholdLow 1392 auto *Precond1 = ConstantExpr::getICmp(ICmpInst::Predicate::ICMP_SGE, C2, 1393 ThresholdLowIncl); 1394 if (!match(Precond1, m_One())) 1395 return nullptr; 1396 // The fold has a precondition 2: C2 s<= ThresholdHigh 1397 auto *Precond2 = ConstantExpr::getICmp(ICmpInst::Predicate::ICMP_SLE, C2, 1398 ThresholdHighExcl); 1399 if (!match(Precond2, m_One())) 1400 return nullptr; 1401 1402 // If we are matching from a truncated input, we need to sext the 1403 // ReplacementLow and ReplacementHigh values. Only do the transform if they 1404 // are free to extend due to being constants. 1405 if (X->getType() != Sel0.getType()) { 1406 Constant *LowC, *HighC; 1407 if (!match(ReplacementLow, m_ImmConstant(LowC)) || 1408 !match(ReplacementHigh, m_ImmConstant(HighC))) 1409 return nullptr; 1410 ReplacementLow = ConstantExpr::getSExt(LowC, X->getType()); 1411 ReplacementHigh = ConstantExpr::getSExt(HighC, X->getType()); 1412 } 1413 1414 // All good, finally emit the new pattern. 1415 Value *ShouldReplaceLow = Builder.CreateICmpSLT(X, ThresholdLowIncl); 1416 Value *ShouldReplaceHigh = Builder.CreateICmpSGE(X, ThresholdHighExcl); 1417 Value *MaybeReplacedLow = 1418 Builder.CreateSelect(ShouldReplaceLow, ReplacementLow, X); 1419 1420 // Create the final select. If we looked through a truncate above, we will 1421 // need to retruncate the result. 1422 Value *MaybeReplacedHigh = Builder.CreateSelect( 1423 ShouldReplaceHigh, ReplacementHigh, MaybeReplacedLow); 1424 return Builder.CreateTrunc(MaybeReplacedHigh, Sel0.getType()); 1425 } 1426 1427 // If we have 1428 // %cmp = icmp [canonical predicate] i32 %x, C0 1429 // %r = select i1 %cmp, i32 %y, i32 C1 1430 // Where C0 != C1 and %x may be different from %y, see if the constant that we 1431 // will have if we flip the strictness of the predicate (i.e. without changing 1432 // the result) is identical to the C1 in select. If it matches we can change 1433 // original comparison to one with swapped predicate, reuse the constant, 1434 // and swap the hands of select. 1435 static Instruction * 1436 tryToReuseConstantFromSelectInComparison(SelectInst &Sel, ICmpInst &Cmp, 1437 InstCombinerImpl &IC) { 1438 ICmpInst::Predicate Pred; 1439 Value *X; 1440 Constant *C0; 1441 if (!match(&Cmp, m_OneUse(m_ICmp( 1442 Pred, m_Value(X), 1443 m_CombineAnd(m_AnyIntegralConstant(), m_Constant(C0)))))) 1444 return nullptr; 1445 1446 // If comparison predicate is non-relational, we won't be able to do anything. 1447 if (ICmpInst::isEquality(Pred)) 1448 return nullptr; 1449 1450 // If comparison predicate is non-canonical, then we certainly won't be able 1451 // to make it canonical; canonicalizeCmpWithConstant() already tried. 1452 if (!InstCombiner::isCanonicalPredicate(Pred)) 1453 return nullptr; 1454 1455 // If the [input] type of comparison and select type are different, lets abort 1456 // for now. We could try to compare constants with trunc/[zs]ext though. 1457 if (C0->getType() != Sel.getType()) 1458 return nullptr; 1459 1460 // ULT with 'add' of a constant is canonical. See foldICmpAddConstant(). 1461 // FIXME: Are there more magic icmp predicate+constant pairs we must avoid? 1462 // Or should we just abandon this transform entirely? 1463 if (Pred == CmpInst::ICMP_ULT && match(X, m_Add(m_Value(), m_Constant()))) 1464 return nullptr; 1465 1466 1467 Value *SelVal0, *SelVal1; // We do not care which one is from where. 1468 match(&Sel, m_Select(m_Value(), m_Value(SelVal0), m_Value(SelVal1))); 1469 // At least one of these values we are selecting between must be a constant 1470 // else we'll never succeed. 1471 if (!match(SelVal0, m_AnyIntegralConstant()) && 1472 !match(SelVal1, m_AnyIntegralConstant())) 1473 return nullptr; 1474 1475 // Does this constant C match any of the `select` values? 1476 auto MatchesSelectValue = [SelVal0, SelVal1](Constant *C) { 1477 return C->isElementWiseEqual(SelVal0) || C->isElementWiseEqual(SelVal1); 1478 }; 1479 1480 // If C0 *already* matches true/false value of select, we are done. 1481 if (MatchesSelectValue(C0)) 1482 return nullptr; 1483 1484 // Check the constant we'd have with flipped-strictness predicate. 1485 auto FlippedStrictness = 1486 InstCombiner::getFlippedStrictnessPredicateAndConstant(Pred, C0); 1487 if (!FlippedStrictness) 1488 return nullptr; 1489 1490 // If said constant doesn't match either, then there is no hope, 1491 if (!MatchesSelectValue(FlippedStrictness->second)) 1492 return nullptr; 1493 1494 // It matched! Lets insert the new comparison just before select. 1495 InstCombiner::BuilderTy::InsertPointGuard Guard(IC.Builder); 1496 IC.Builder.SetInsertPoint(&Sel); 1497 1498 Pred = ICmpInst::getSwappedPredicate(Pred); // Yes, swapped. 1499 Value *NewCmp = IC.Builder.CreateICmp(Pred, X, FlippedStrictness->second, 1500 Cmp.getName() + ".inv"); 1501 IC.replaceOperand(Sel, 0, NewCmp); 1502 Sel.swapValues(); 1503 Sel.swapProfMetadata(); 1504 1505 return &Sel; 1506 } 1507 1508 static Instruction *foldSelectZeroOrOnes(ICmpInst *Cmp, Value *TVal, 1509 Value *FVal, 1510 InstCombiner::BuilderTy &Builder) { 1511 if (!Cmp->hasOneUse()) 1512 return nullptr; 1513 1514 const APInt *CmpC; 1515 if (!match(Cmp->getOperand(1), m_APIntAllowUndef(CmpC))) 1516 return nullptr; 1517 1518 // (X u< 2) ? -X : -1 --> sext (X != 0) 1519 Value *X = Cmp->getOperand(0); 1520 if (Cmp->getPredicate() == ICmpInst::ICMP_ULT && *CmpC == 2 && 1521 match(TVal, m_Neg(m_Specific(X))) && match(FVal, m_AllOnes())) 1522 return new SExtInst(Builder.CreateIsNotNull(X), TVal->getType()); 1523 1524 // (X u> 1) ? -1 : -X --> sext (X != 0) 1525 if (Cmp->getPredicate() == ICmpInst::ICMP_UGT && *CmpC == 1 && 1526 match(FVal, m_Neg(m_Specific(X))) && match(TVal, m_AllOnes())) 1527 return new SExtInst(Builder.CreateIsNotNull(X), TVal->getType()); 1528 1529 return nullptr; 1530 } 1531 1532 /// Visit a SelectInst that has an ICmpInst as its first operand. 1533 Instruction *InstCombinerImpl::foldSelectInstWithICmp(SelectInst &SI, 1534 ICmpInst *ICI) { 1535 if (Instruction *NewSel = foldSelectValueEquivalence(SI, *ICI)) 1536 return NewSel; 1537 1538 if (Instruction *NewSPF = canonicalizeSPF(SI, *ICI, *this)) 1539 return NewSPF; 1540 1541 if (Value *V = canonicalizeClampLike(SI, *ICI, Builder)) 1542 return replaceInstUsesWith(SI, V); 1543 1544 if (Instruction *NewSel = 1545 tryToReuseConstantFromSelectInComparison(SI, *ICI, *this)) 1546 return NewSel; 1547 1548 bool Changed = adjustMinMax(SI, *ICI); 1549 1550 if (Value *V = foldSelectICmpAnd(SI, ICI, Builder)) 1551 return replaceInstUsesWith(SI, V); 1552 1553 // NOTE: if we wanted to, this is where to detect integer MIN/MAX 1554 Value *TrueVal = SI.getTrueValue(); 1555 Value *FalseVal = SI.getFalseValue(); 1556 ICmpInst::Predicate Pred = ICI->getPredicate(); 1557 Value *CmpLHS = ICI->getOperand(0); 1558 Value *CmpRHS = ICI->getOperand(1); 1559 if (CmpRHS != CmpLHS && isa<Constant>(CmpRHS)) { 1560 if (CmpLHS == TrueVal && Pred == ICmpInst::ICMP_EQ) { 1561 // Transform (X == C) ? X : Y -> (X == C) ? C : Y 1562 SI.setOperand(1, CmpRHS); 1563 Changed = true; 1564 } else if (CmpLHS == FalseVal && Pred == ICmpInst::ICMP_NE) { 1565 // Transform (X != C) ? Y : X -> (X != C) ? Y : C 1566 SI.setOperand(2, CmpRHS); 1567 Changed = true; 1568 } 1569 } 1570 1571 // FIXME: This code is nearly duplicated in InstSimplify. Using/refactoring 1572 // decomposeBitTestICmp() might help. 1573 { 1574 unsigned BitWidth = 1575 DL.getTypeSizeInBits(TrueVal->getType()->getScalarType()); 1576 APInt MinSignedValue = APInt::getSignedMinValue(BitWidth); 1577 Value *X; 1578 const APInt *Y, *C; 1579 bool TrueWhenUnset; 1580 bool IsBitTest = false; 1581 if (ICmpInst::isEquality(Pred) && 1582 match(CmpLHS, m_And(m_Value(X), m_Power2(Y))) && 1583 match(CmpRHS, m_Zero())) { 1584 IsBitTest = true; 1585 TrueWhenUnset = Pred == ICmpInst::ICMP_EQ; 1586 } else if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, m_Zero())) { 1587 X = CmpLHS; 1588 Y = &MinSignedValue; 1589 IsBitTest = true; 1590 TrueWhenUnset = false; 1591 } else if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, m_AllOnes())) { 1592 X = CmpLHS; 1593 Y = &MinSignedValue; 1594 IsBitTest = true; 1595 TrueWhenUnset = true; 1596 } 1597 if (IsBitTest) { 1598 Value *V = nullptr; 1599 // (X & Y) == 0 ? X : X ^ Y --> X & ~Y 1600 if (TrueWhenUnset && TrueVal == X && 1601 match(FalseVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C) 1602 V = Builder.CreateAnd(X, ~(*Y)); 1603 // (X & Y) != 0 ? X ^ Y : X --> X & ~Y 1604 else if (!TrueWhenUnset && FalseVal == X && 1605 match(TrueVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C) 1606 V = Builder.CreateAnd(X, ~(*Y)); 1607 // (X & Y) == 0 ? X ^ Y : X --> X | Y 1608 else if (TrueWhenUnset && FalseVal == X && 1609 match(TrueVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C) 1610 V = Builder.CreateOr(X, *Y); 1611 // (X & Y) != 0 ? X : X ^ Y --> X | Y 1612 else if (!TrueWhenUnset && TrueVal == X && 1613 match(FalseVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C) 1614 V = Builder.CreateOr(X, *Y); 1615 1616 if (V) 1617 return replaceInstUsesWith(SI, V); 1618 } 1619 } 1620 1621 if (Instruction *V = 1622 foldSelectICmpAndAnd(SI.getType(), ICI, TrueVal, FalseVal, Builder)) 1623 return V; 1624 1625 if (Instruction *V = foldSelectCtlzToCttz(ICI, TrueVal, FalseVal, Builder)) 1626 return V; 1627 1628 if (Instruction *V = foldSelectZeroOrOnes(ICI, TrueVal, FalseVal, Builder)) 1629 return V; 1630 1631 if (Value *V = foldSelectICmpAndOr(ICI, TrueVal, FalseVal, Builder)) 1632 return replaceInstUsesWith(SI, V); 1633 1634 if (Value *V = foldSelectICmpLshrAshr(ICI, TrueVal, FalseVal, Builder)) 1635 return replaceInstUsesWith(SI, V); 1636 1637 if (Value *V = foldSelectCttzCtlz(ICI, TrueVal, FalseVal, Builder)) 1638 return replaceInstUsesWith(SI, V); 1639 1640 if (Value *V = canonicalizeSaturatedSubtract(ICI, TrueVal, FalseVal, Builder)) 1641 return replaceInstUsesWith(SI, V); 1642 1643 if (Value *V = canonicalizeSaturatedAdd(ICI, TrueVal, FalseVal, Builder)) 1644 return replaceInstUsesWith(SI, V); 1645 1646 return Changed ? &SI : nullptr; 1647 } 1648 1649 /// SI is a select whose condition is a PHI node (but the two may be in 1650 /// different blocks). See if the true/false values (V) are live in all of the 1651 /// predecessor blocks of the PHI. For example, cases like this can't be mapped: 1652 /// 1653 /// X = phi [ C1, BB1], [C2, BB2] 1654 /// Y = add 1655 /// Z = select X, Y, 0 1656 /// 1657 /// because Y is not live in BB1/BB2. 1658 static bool canSelectOperandBeMappingIntoPredBlock(const Value *V, 1659 const SelectInst &SI) { 1660 // If the value is a non-instruction value like a constant or argument, it 1661 // can always be mapped. 1662 const Instruction *I = dyn_cast<Instruction>(V); 1663 if (!I) return true; 1664 1665 // If V is a PHI node defined in the same block as the condition PHI, we can 1666 // map the arguments. 1667 const PHINode *CondPHI = cast<PHINode>(SI.getCondition()); 1668 1669 if (const PHINode *VP = dyn_cast<PHINode>(I)) 1670 if (VP->getParent() == CondPHI->getParent()) 1671 return true; 1672 1673 // Otherwise, if the PHI and select are defined in the same block and if V is 1674 // defined in a different block, then we can transform it. 1675 if (SI.getParent() == CondPHI->getParent() && 1676 I->getParent() != CondPHI->getParent()) 1677 return true; 1678 1679 // Otherwise we have a 'hard' case and we can't tell without doing more 1680 // detailed dominator based analysis, punt. 1681 return false; 1682 } 1683 1684 /// We have an SPF (e.g. a min or max) of an SPF of the form: 1685 /// SPF2(SPF1(A, B), C) 1686 Instruction *InstCombinerImpl::foldSPFofSPF(Instruction *Inner, 1687 SelectPatternFlavor SPF1, Value *A, 1688 Value *B, Instruction &Outer, 1689 SelectPatternFlavor SPF2, 1690 Value *C) { 1691 if (Outer.getType() != Inner->getType()) 1692 return nullptr; 1693 1694 if (C == A || C == B) { 1695 // MAX(MAX(A, B), B) -> MAX(A, B) 1696 // MIN(MIN(a, b), a) -> MIN(a, b) 1697 // TODO: This could be done in instsimplify. 1698 if (SPF1 == SPF2 && SelectPatternResult::isMinOrMax(SPF1)) 1699 return replaceInstUsesWith(Outer, Inner); 1700 } 1701 1702 return nullptr; 1703 } 1704 1705 /// Turn select C, (X + Y), (X - Y) --> (X + (select C, Y, (-Y))). 1706 /// This is even legal for FP. 1707 static Instruction *foldAddSubSelect(SelectInst &SI, 1708 InstCombiner::BuilderTy &Builder) { 1709 Value *CondVal = SI.getCondition(); 1710 Value *TrueVal = SI.getTrueValue(); 1711 Value *FalseVal = SI.getFalseValue(); 1712 auto *TI = dyn_cast<Instruction>(TrueVal); 1713 auto *FI = dyn_cast<Instruction>(FalseVal); 1714 if (!TI || !FI || !TI->hasOneUse() || !FI->hasOneUse()) 1715 return nullptr; 1716 1717 Instruction *AddOp = nullptr, *SubOp = nullptr; 1718 if ((TI->getOpcode() == Instruction::Sub && 1719 FI->getOpcode() == Instruction::Add) || 1720 (TI->getOpcode() == Instruction::FSub && 1721 FI->getOpcode() == Instruction::FAdd)) { 1722 AddOp = FI; 1723 SubOp = TI; 1724 } else if ((FI->getOpcode() == Instruction::Sub && 1725 TI->getOpcode() == Instruction::Add) || 1726 (FI->getOpcode() == Instruction::FSub && 1727 TI->getOpcode() == Instruction::FAdd)) { 1728 AddOp = TI; 1729 SubOp = FI; 1730 } 1731 1732 if (AddOp) { 1733 Value *OtherAddOp = nullptr; 1734 if (SubOp->getOperand(0) == AddOp->getOperand(0)) { 1735 OtherAddOp = AddOp->getOperand(1); 1736 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) { 1737 OtherAddOp = AddOp->getOperand(0); 1738 } 1739 1740 if (OtherAddOp) { 1741 // So at this point we know we have (Y -> OtherAddOp): 1742 // select C, (add X, Y), (sub X, Z) 1743 Value *NegVal; // Compute -Z 1744 if (SI.getType()->isFPOrFPVectorTy()) { 1745 NegVal = Builder.CreateFNeg(SubOp->getOperand(1)); 1746 if (Instruction *NegInst = dyn_cast<Instruction>(NegVal)) { 1747 FastMathFlags Flags = AddOp->getFastMathFlags(); 1748 Flags &= SubOp->getFastMathFlags(); 1749 NegInst->setFastMathFlags(Flags); 1750 } 1751 } else { 1752 NegVal = Builder.CreateNeg(SubOp->getOperand(1)); 1753 } 1754 1755 Value *NewTrueOp = OtherAddOp; 1756 Value *NewFalseOp = NegVal; 1757 if (AddOp != TI) 1758 std::swap(NewTrueOp, NewFalseOp); 1759 Value *NewSel = Builder.CreateSelect(CondVal, NewTrueOp, NewFalseOp, 1760 SI.getName() + ".p", &SI); 1761 1762 if (SI.getType()->isFPOrFPVectorTy()) { 1763 Instruction *RI = 1764 BinaryOperator::CreateFAdd(SubOp->getOperand(0), NewSel); 1765 1766 FastMathFlags Flags = AddOp->getFastMathFlags(); 1767 Flags &= SubOp->getFastMathFlags(); 1768 RI->setFastMathFlags(Flags); 1769 return RI; 1770 } else 1771 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel); 1772 } 1773 } 1774 return nullptr; 1775 } 1776 1777 /// Turn X + Y overflows ? -1 : X + Y -> uadd_sat X, Y 1778 /// And X - Y overflows ? 0 : X - Y -> usub_sat X, Y 1779 /// Along with a number of patterns similar to: 1780 /// X + Y overflows ? (X < 0 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y 1781 /// X - Y overflows ? (X > 0 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y 1782 static Instruction * 1783 foldOverflowingAddSubSelect(SelectInst &SI, InstCombiner::BuilderTy &Builder) { 1784 Value *CondVal = SI.getCondition(); 1785 Value *TrueVal = SI.getTrueValue(); 1786 Value *FalseVal = SI.getFalseValue(); 1787 1788 WithOverflowInst *II; 1789 if (!match(CondVal, m_ExtractValue<1>(m_WithOverflowInst(II))) || 1790 !match(FalseVal, m_ExtractValue<0>(m_Specific(II)))) 1791 return nullptr; 1792 1793 Value *X = II->getLHS(); 1794 Value *Y = II->getRHS(); 1795 1796 auto IsSignedSaturateLimit = [&](Value *Limit, bool IsAdd) { 1797 Type *Ty = Limit->getType(); 1798 1799 ICmpInst::Predicate Pred; 1800 Value *TrueVal, *FalseVal, *Op; 1801 const APInt *C; 1802 if (!match(Limit, m_Select(m_ICmp(Pred, m_Value(Op), m_APInt(C)), 1803 m_Value(TrueVal), m_Value(FalseVal)))) 1804 return false; 1805 1806 auto IsZeroOrOne = [](const APInt &C) { return C.isZero() || C.isOne(); }; 1807 auto IsMinMax = [&](Value *Min, Value *Max) { 1808 APInt MinVal = APInt::getSignedMinValue(Ty->getScalarSizeInBits()); 1809 APInt MaxVal = APInt::getSignedMaxValue(Ty->getScalarSizeInBits()); 1810 return match(Min, m_SpecificInt(MinVal)) && 1811 match(Max, m_SpecificInt(MaxVal)); 1812 }; 1813 1814 if (Op != X && Op != Y) 1815 return false; 1816 1817 if (IsAdd) { 1818 // X + Y overflows ? (X <s 0 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y 1819 // X + Y overflows ? (X <s 1 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y 1820 // X + Y overflows ? (Y <s 0 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y 1821 // X + Y overflows ? (Y <s 1 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y 1822 if (Pred == ICmpInst::ICMP_SLT && IsZeroOrOne(*C) && 1823 IsMinMax(TrueVal, FalseVal)) 1824 return true; 1825 // X + Y overflows ? (X >s 0 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y 1826 // X + Y overflows ? (X >s -1 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y 1827 // X + Y overflows ? (Y >s 0 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y 1828 // X + Y overflows ? (Y >s -1 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y 1829 if (Pred == ICmpInst::ICMP_SGT && IsZeroOrOne(*C + 1) && 1830 IsMinMax(FalseVal, TrueVal)) 1831 return true; 1832 } else { 1833 // X - Y overflows ? (X <s 0 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y 1834 // X - Y overflows ? (X <s -1 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y 1835 if (Op == X && Pred == ICmpInst::ICMP_SLT && IsZeroOrOne(*C + 1) && 1836 IsMinMax(TrueVal, FalseVal)) 1837 return true; 1838 // X - Y overflows ? (X >s -1 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y 1839 // X - Y overflows ? (X >s -2 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y 1840 if (Op == X && Pred == ICmpInst::ICMP_SGT && IsZeroOrOne(*C + 2) && 1841 IsMinMax(FalseVal, TrueVal)) 1842 return true; 1843 // X - Y overflows ? (Y <s 0 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y 1844 // X - Y overflows ? (Y <s 1 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y 1845 if (Op == Y && Pred == ICmpInst::ICMP_SLT && IsZeroOrOne(*C) && 1846 IsMinMax(FalseVal, TrueVal)) 1847 return true; 1848 // X - Y overflows ? (Y >s 0 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y 1849 // X - Y overflows ? (Y >s -1 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y 1850 if (Op == Y && Pred == ICmpInst::ICMP_SGT && IsZeroOrOne(*C + 1) && 1851 IsMinMax(TrueVal, FalseVal)) 1852 return true; 1853 } 1854 1855 return false; 1856 }; 1857 1858 Intrinsic::ID NewIntrinsicID; 1859 if (II->getIntrinsicID() == Intrinsic::uadd_with_overflow && 1860 match(TrueVal, m_AllOnes())) 1861 // X + Y overflows ? -1 : X + Y -> uadd_sat X, Y 1862 NewIntrinsicID = Intrinsic::uadd_sat; 1863 else if (II->getIntrinsicID() == Intrinsic::usub_with_overflow && 1864 match(TrueVal, m_Zero())) 1865 // X - Y overflows ? 0 : X - Y -> usub_sat X, Y 1866 NewIntrinsicID = Intrinsic::usub_sat; 1867 else if (II->getIntrinsicID() == Intrinsic::sadd_with_overflow && 1868 IsSignedSaturateLimit(TrueVal, /*IsAdd=*/true)) 1869 // X + Y overflows ? (X <s 0 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y 1870 // X + Y overflows ? (X <s 1 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y 1871 // X + Y overflows ? (X >s 0 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y 1872 // X + Y overflows ? (X >s -1 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y 1873 // X + Y overflows ? (Y <s 0 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y 1874 // X + Y overflows ? (Y <s 1 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y 1875 // X + Y overflows ? (Y >s 0 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y 1876 // X + Y overflows ? (Y >s -1 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y 1877 NewIntrinsicID = Intrinsic::sadd_sat; 1878 else if (II->getIntrinsicID() == Intrinsic::ssub_with_overflow && 1879 IsSignedSaturateLimit(TrueVal, /*IsAdd=*/false)) 1880 // X - Y overflows ? (X <s 0 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y 1881 // X - Y overflows ? (X <s -1 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y 1882 // X - Y overflows ? (X >s -1 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y 1883 // X - Y overflows ? (X >s -2 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y 1884 // X - Y overflows ? (Y <s 0 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y 1885 // X - Y overflows ? (Y <s 1 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y 1886 // X - Y overflows ? (Y >s 0 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y 1887 // X - Y overflows ? (Y >s -1 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y 1888 NewIntrinsicID = Intrinsic::ssub_sat; 1889 else 1890 return nullptr; 1891 1892 Function *F = 1893 Intrinsic::getDeclaration(SI.getModule(), NewIntrinsicID, SI.getType()); 1894 return CallInst::Create(F, {X, Y}); 1895 } 1896 1897 Instruction *InstCombinerImpl::foldSelectExtConst(SelectInst &Sel) { 1898 Constant *C; 1899 if (!match(Sel.getTrueValue(), m_Constant(C)) && 1900 !match(Sel.getFalseValue(), m_Constant(C))) 1901 return nullptr; 1902 1903 Instruction *ExtInst; 1904 if (!match(Sel.getTrueValue(), m_Instruction(ExtInst)) && 1905 !match(Sel.getFalseValue(), m_Instruction(ExtInst))) 1906 return nullptr; 1907 1908 auto ExtOpcode = ExtInst->getOpcode(); 1909 if (ExtOpcode != Instruction::ZExt && ExtOpcode != Instruction::SExt) 1910 return nullptr; 1911 1912 // If we are extending from a boolean type or if we can create a select that 1913 // has the same size operands as its condition, try to narrow the select. 1914 Value *X = ExtInst->getOperand(0); 1915 Type *SmallType = X->getType(); 1916 Value *Cond = Sel.getCondition(); 1917 auto *Cmp = dyn_cast<CmpInst>(Cond); 1918 if (!SmallType->isIntOrIntVectorTy(1) && 1919 (!Cmp || Cmp->getOperand(0)->getType() != SmallType)) 1920 return nullptr; 1921 1922 // If the constant is the same after truncation to the smaller type and 1923 // extension to the original type, we can narrow the select. 1924 Type *SelType = Sel.getType(); 1925 Constant *TruncC = ConstantExpr::getTrunc(C, SmallType); 1926 Constant *ExtC = ConstantExpr::getCast(ExtOpcode, TruncC, SelType); 1927 if (ExtC == C && ExtInst->hasOneUse()) { 1928 Value *TruncCVal = cast<Value>(TruncC); 1929 if (ExtInst == Sel.getFalseValue()) 1930 std::swap(X, TruncCVal); 1931 1932 // select Cond, (ext X), C --> ext(select Cond, X, C') 1933 // select Cond, C, (ext X) --> ext(select Cond, C', X) 1934 Value *NewSel = Builder.CreateSelect(Cond, X, TruncCVal, "narrow", &Sel); 1935 return CastInst::Create(Instruction::CastOps(ExtOpcode), NewSel, SelType); 1936 } 1937 1938 // If one arm of the select is the extend of the condition, replace that arm 1939 // with the extension of the appropriate known bool value. 1940 if (Cond == X) { 1941 if (ExtInst == Sel.getTrueValue()) { 1942 // select X, (sext X), C --> select X, -1, C 1943 // select X, (zext X), C --> select X, 1, C 1944 Constant *One = ConstantInt::getTrue(SmallType); 1945 Constant *AllOnesOrOne = ConstantExpr::getCast(ExtOpcode, One, SelType); 1946 return SelectInst::Create(Cond, AllOnesOrOne, C, "", nullptr, &Sel); 1947 } else { 1948 // select X, C, (sext X) --> select X, C, 0 1949 // select X, C, (zext X) --> select X, C, 0 1950 Constant *Zero = ConstantInt::getNullValue(SelType); 1951 return SelectInst::Create(Cond, C, Zero, "", nullptr, &Sel); 1952 } 1953 } 1954 1955 return nullptr; 1956 } 1957 1958 /// Try to transform a vector select with a constant condition vector into a 1959 /// shuffle for easier combining with other shuffles and insert/extract. 1960 static Instruction *canonicalizeSelectToShuffle(SelectInst &SI) { 1961 Value *CondVal = SI.getCondition(); 1962 Constant *CondC; 1963 auto *CondValTy = dyn_cast<FixedVectorType>(CondVal->getType()); 1964 if (!CondValTy || !match(CondVal, m_Constant(CondC))) 1965 return nullptr; 1966 1967 unsigned NumElts = CondValTy->getNumElements(); 1968 SmallVector<int, 16> Mask; 1969 Mask.reserve(NumElts); 1970 for (unsigned i = 0; i != NumElts; ++i) { 1971 Constant *Elt = CondC->getAggregateElement(i); 1972 if (!Elt) 1973 return nullptr; 1974 1975 if (Elt->isOneValue()) { 1976 // If the select condition element is true, choose from the 1st vector. 1977 Mask.push_back(i); 1978 } else if (Elt->isNullValue()) { 1979 // If the select condition element is false, choose from the 2nd vector. 1980 Mask.push_back(i + NumElts); 1981 } else if (isa<UndefValue>(Elt)) { 1982 // Undef in a select condition (choose one of the operands) does not mean 1983 // the same thing as undef in a shuffle mask (any value is acceptable), so 1984 // give up. 1985 return nullptr; 1986 } else { 1987 // Bail out on a constant expression. 1988 return nullptr; 1989 } 1990 } 1991 1992 return new ShuffleVectorInst(SI.getTrueValue(), SI.getFalseValue(), Mask); 1993 } 1994 1995 /// If we have a select of vectors with a scalar condition, try to convert that 1996 /// to a vector select by splatting the condition. A splat may get folded with 1997 /// other operations in IR and having all operands of a select be vector types 1998 /// is likely better for vector codegen. 1999 static Instruction *canonicalizeScalarSelectOfVecs(SelectInst &Sel, 2000 InstCombinerImpl &IC) { 2001 auto *Ty = dyn_cast<VectorType>(Sel.getType()); 2002 if (!Ty) 2003 return nullptr; 2004 2005 // We can replace a single-use extract with constant index. 2006 Value *Cond = Sel.getCondition(); 2007 if (!match(Cond, m_OneUse(m_ExtractElt(m_Value(), m_ConstantInt())))) 2008 return nullptr; 2009 2010 // select (extelt V, Index), T, F --> select (splat V, Index), T, F 2011 // Splatting the extracted condition reduces code (we could directly create a 2012 // splat shuffle of the source vector to eliminate the intermediate step). 2013 return IC.replaceOperand( 2014 Sel, 0, IC.Builder.CreateVectorSplat(Ty->getElementCount(), Cond)); 2015 } 2016 2017 /// Reuse bitcasted operands between a compare and select: 2018 /// select (cmp (bitcast C), (bitcast D)), (bitcast' C), (bitcast' D) --> 2019 /// bitcast (select (cmp (bitcast C), (bitcast D)), (bitcast C), (bitcast D)) 2020 static Instruction *foldSelectCmpBitcasts(SelectInst &Sel, 2021 InstCombiner::BuilderTy &Builder) { 2022 Value *Cond = Sel.getCondition(); 2023 Value *TVal = Sel.getTrueValue(); 2024 Value *FVal = Sel.getFalseValue(); 2025 2026 CmpInst::Predicate Pred; 2027 Value *A, *B; 2028 if (!match(Cond, m_Cmp(Pred, m_Value(A), m_Value(B)))) 2029 return nullptr; 2030 2031 // The select condition is a compare instruction. If the select's true/false 2032 // values are already the same as the compare operands, there's nothing to do. 2033 if (TVal == A || TVal == B || FVal == A || FVal == B) 2034 return nullptr; 2035 2036 Value *C, *D; 2037 if (!match(A, m_BitCast(m_Value(C))) || !match(B, m_BitCast(m_Value(D)))) 2038 return nullptr; 2039 2040 // select (cmp (bitcast C), (bitcast D)), (bitcast TSrc), (bitcast FSrc) 2041 Value *TSrc, *FSrc; 2042 if (!match(TVal, m_BitCast(m_Value(TSrc))) || 2043 !match(FVal, m_BitCast(m_Value(FSrc)))) 2044 return nullptr; 2045 2046 // If the select true/false values are *different bitcasts* of the same source 2047 // operands, make the select operands the same as the compare operands and 2048 // cast the result. This is the canonical select form for min/max. 2049 Value *NewSel; 2050 if (TSrc == C && FSrc == D) { 2051 // select (cmp (bitcast C), (bitcast D)), (bitcast' C), (bitcast' D) --> 2052 // bitcast (select (cmp A, B), A, B) 2053 NewSel = Builder.CreateSelect(Cond, A, B, "", &Sel); 2054 } else if (TSrc == D && FSrc == C) { 2055 // select (cmp (bitcast C), (bitcast D)), (bitcast' D), (bitcast' C) --> 2056 // bitcast (select (cmp A, B), B, A) 2057 NewSel = Builder.CreateSelect(Cond, B, A, "", &Sel); 2058 } else { 2059 return nullptr; 2060 } 2061 return CastInst::CreateBitOrPointerCast(NewSel, Sel.getType()); 2062 } 2063 2064 /// Try to eliminate select instructions that test the returned flag of cmpxchg 2065 /// instructions. 2066 /// 2067 /// If a select instruction tests the returned flag of a cmpxchg instruction and 2068 /// selects between the returned value of the cmpxchg instruction its compare 2069 /// operand, the result of the select will always be equal to its false value. 2070 /// For example: 2071 /// 2072 /// %0 = cmpxchg i64* %ptr, i64 %compare, i64 %new_value seq_cst seq_cst 2073 /// %1 = extractvalue { i64, i1 } %0, 1 2074 /// %2 = extractvalue { i64, i1 } %0, 0 2075 /// %3 = select i1 %1, i64 %compare, i64 %2 2076 /// ret i64 %3 2077 /// 2078 /// The returned value of the cmpxchg instruction (%2) is the original value 2079 /// located at %ptr prior to any update. If the cmpxchg operation succeeds, %2 2080 /// must have been equal to %compare. Thus, the result of the select is always 2081 /// equal to %2, and the code can be simplified to: 2082 /// 2083 /// %0 = cmpxchg i64* %ptr, i64 %compare, i64 %new_value seq_cst seq_cst 2084 /// %1 = extractvalue { i64, i1 } %0, 0 2085 /// ret i64 %1 2086 /// 2087 static Value *foldSelectCmpXchg(SelectInst &SI) { 2088 // A helper that determines if V is an extractvalue instruction whose 2089 // aggregate operand is a cmpxchg instruction and whose single index is equal 2090 // to I. If such conditions are true, the helper returns the cmpxchg 2091 // instruction; otherwise, a nullptr is returned. 2092 auto isExtractFromCmpXchg = [](Value *V, unsigned I) -> AtomicCmpXchgInst * { 2093 auto *Extract = dyn_cast<ExtractValueInst>(V); 2094 if (!Extract) 2095 return nullptr; 2096 if (Extract->getIndices()[0] != I) 2097 return nullptr; 2098 return dyn_cast<AtomicCmpXchgInst>(Extract->getAggregateOperand()); 2099 }; 2100 2101 // If the select has a single user, and this user is a select instruction that 2102 // we can simplify, skip the cmpxchg simplification for now. 2103 if (SI.hasOneUse()) 2104 if (auto *Select = dyn_cast<SelectInst>(SI.user_back())) 2105 if (Select->getCondition() == SI.getCondition()) 2106 if (Select->getFalseValue() == SI.getTrueValue() || 2107 Select->getTrueValue() == SI.getFalseValue()) 2108 return nullptr; 2109 2110 // Ensure the select condition is the returned flag of a cmpxchg instruction. 2111 auto *CmpXchg = isExtractFromCmpXchg(SI.getCondition(), 1); 2112 if (!CmpXchg) 2113 return nullptr; 2114 2115 // Check the true value case: The true value of the select is the returned 2116 // value of the same cmpxchg used by the condition, and the false value is the 2117 // cmpxchg instruction's compare operand. 2118 if (auto *X = isExtractFromCmpXchg(SI.getTrueValue(), 0)) 2119 if (X == CmpXchg && X->getCompareOperand() == SI.getFalseValue()) 2120 return SI.getFalseValue(); 2121 2122 // Check the false value case: The false value of the select is the returned 2123 // value of the same cmpxchg used by the condition, and the true value is the 2124 // cmpxchg instruction's compare operand. 2125 if (auto *X = isExtractFromCmpXchg(SI.getFalseValue(), 0)) 2126 if (X == CmpXchg && X->getCompareOperand() == SI.getTrueValue()) 2127 return SI.getFalseValue(); 2128 2129 return nullptr; 2130 } 2131 2132 /// Try to reduce a funnel/rotate pattern that includes a compare and select 2133 /// into a funnel shift intrinsic. Example: 2134 /// rotl32(a, b) --> (b == 0 ? a : ((a >> (32 - b)) | (a << b))) 2135 /// --> call llvm.fshl.i32(a, a, b) 2136 /// fshl32(a, b, c) --> (c == 0 ? a : ((b >> (32 - c)) | (a << c))) 2137 /// --> call llvm.fshl.i32(a, b, c) 2138 /// fshr32(a, b, c) --> (c == 0 ? b : ((a >> (32 - c)) | (b << c))) 2139 /// --> call llvm.fshr.i32(a, b, c) 2140 static Instruction *foldSelectFunnelShift(SelectInst &Sel, 2141 InstCombiner::BuilderTy &Builder) { 2142 // This must be a power-of-2 type for a bitmasking transform to be valid. 2143 unsigned Width = Sel.getType()->getScalarSizeInBits(); 2144 if (!isPowerOf2_32(Width)) 2145 return nullptr; 2146 2147 BinaryOperator *Or0, *Or1; 2148 if (!match(Sel.getFalseValue(), m_OneUse(m_Or(m_BinOp(Or0), m_BinOp(Or1))))) 2149 return nullptr; 2150 2151 Value *SV0, *SV1, *SA0, *SA1; 2152 if (!match(Or0, m_OneUse(m_LogicalShift(m_Value(SV0), 2153 m_ZExtOrSelf(m_Value(SA0))))) || 2154 !match(Or1, m_OneUse(m_LogicalShift(m_Value(SV1), 2155 m_ZExtOrSelf(m_Value(SA1))))) || 2156 Or0->getOpcode() == Or1->getOpcode()) 2157 return nullptr; 2158 2159 // Canonicalize to or(shl(SV0, SA0), lshr(SV1, SA1)). 2160 if (Or0->getOpcode() == BinaryOperator::LShr) { 2161 std::swap(Or0, Or1); 2162 std::swap(SV0, SV1); 2163 std::swap(SA0, SA1); 2164 } 2165 assert(Or0->getOpcode() == BinaryOperator::Shl && 2166 Or1->getOpcode() == BinaryOperator::LShr && 2167 "Illegal or(shift,shift) pair"); 2168 2169 // Check the shift amounts to see if they are an opposite pair. 2170 Value *ShAmt; 2171 if (match(SA1, m_OneUse(m_Sub(m_SpecificInt(Width), m_Specific(SA0))))) 2172 ShAmt = SA0; 2173 else if (match(SA0, m_OneUse(m_Sub(m_SpecificInt(Width), m_Specific(SA1))))) 2174 ShAmt = SA1; 2175 else 2176 return nullptr; 2177 2178 // We should now have this pattern: 2179 // select ?, TVal, (or (shl SV0, SA0), (lshr SV1, SA1)) 2180 // The false value of the select must be a funnel-shift of the true value: 2181 // IsFShl -> TVal must be SV0 else TVal must be SV1. 2182 bool IsFshl = (ShAmt == SA0); 2183 Value *TVal = Sel.getTrueValue(); 2184 if ((IsFshl && TVal != SV0) || (!IsFshl && TVal != SV1)) 2185 return nullptr; 2186 2187 // Finally, see if the select is filtering out a shift-by-zero. 2188 Value *Cond = Sel.getCondition(); 2189 ICmpInst::Predicate Pred; 2190 if (!match(Cond, m_OneUse(m_ICmp(Pred, m_Specific(ShAmt), m_ZeroInt()))) || 2191 Pred != ICmpInst::ICMP_EQ) 2192 return nullptr; 2193 2194 // If this is not a rotate then the select was blocking poison from the 2195 // 'shift-by-zero' non-TVal, but a funnel shift won't - so freeze it. 2196 if (SV0 != SV1) { 2197 if (IsFshl && !llvm::isGuaranteedNotToBePoison(SV1)) 2198 SV1 = Builder.CreateFreeze(SV1); 2199 else if (!IsFshl && !llvm::isGuaranteedNotToBePoison(SV0)) 2200 SV0 = Builder.CreateFreeze(SV0); 2201 } 2202 2203 // This is a funnel/rotate that avoids shift-by-bitwidth UB in a suboptimal way. 2204 // Convert to funnel shift intrinsic. 2205 Intrinsic::ID IID = IsFshl ? Intrinsic::fshl : Intrinsic::fshr; 2206 Function *F = Intrinsic::getDeclaration(Sel.getModule(), IID, Sel.getType()); 2207 ShAmt = Builder.CreateZExt(ShAmt, Sel.getType()); 2208 return CallInst::Create(F, { SV0, SV1, ShAmt }); 2209 } 2210 2211 static Instruction *foldSelectToCopysign(SelectInst &Sel, 2212 InstCombiner::BuilderTy &Builder) { 2213 Value *Cond = Sel.getCondition(); 2214 Value *TVal = Sel.getTrueValue(); 2215 Value *FVal = Sel.getFalseValue(); 2216 Type *SelType = Sel.getType(); 2217 2218 // Match select ?, TC, FC where the constants are equal but negated. 2219 // TODO: Generalize to handle a negated variable operand? 2220 const APFloat *TC, *FC; 2221 if (!match(TVal, m_APFloat(TC)) || !match(FVal, m_APFloat(FC)) || 2222 !abs(*TC).bitwiseIsEqual(abs(*FC))) 2223 return nullptr; 2224 2225 assert(TC != FC && "Expected equal select arms to simplify"); 2226 2227 Value *X; 2228 const APInt *C; 2229 bool IsTrueIfSignSet; 2230 ICmpInst::Predicate Pred; 2231 if (!match(Cond, m_OneUse(m_ICmp(Pred, m_BitCast(m_Value(X)), m_APInt(C)))) || 2232 !InstCombiner::isSignBitCheck(Pred, *C, IsTrueIfSignSet) || 2233 X->getType() != SelType) 2234 return nullptr; 2235 2236 // If needed, negate the value that will be the sign argument of the copysign: 2237 // (bitcast X) < 0 ? -TC : TC --> copysign(TC, X) 2238 // (bitcast X) < 0 ? TC : -TC --> copysign(TC, -X) 2239 // (bitcast X) >= 0 ? -TC : TC --> copysign(TC, -X) 2240 // (bitcast X) >= 0 ? TC : -TC --> copysign(TC, X) 2241 // Note: FMF from the select can not be propagated to the new instructions. 2242 if (IsTrueIfSignSet ^ TC->isNegative()) 2243 X = Builder.CreateFNeg(X); 2244 2245 // Canonicalize the magnitude argument as the positive constant since we do 2246 // not care about its sign. 2247 Value *MagArg = TC->isNegative() ? FVal : TVal; 2248 Function *F = Intrinsic::getDeclaration(Sel.getModule(), Intrinsic::copysign, 2249 Sel.getType()); 2250 return CallInst::Create(F, { MagArg, X }); 2251 } 2252 2253 Instruction *InstCombinerImpl::foldVectorSelect(SelectInst &Sel) { 2254 auto *VecTy = dyn_cast<FixedVectorType>(Sel.getType()); 2255 if (!VecTy) 2256 return nullptr; 2257 2258 unsigned NumElts = VecTy->getNumElements(); 2259 APInt UndefElts(NumElts, 0); 2260 APInt AllOnesEltMask(APInt::getAllOnes(NumElts)); 2261 if (Value *V = SimplifyDemandedVectorElts(&Sel, AllOnesEltMask, UndefElts)) { 2262 if (V != &Sel) 2263 return replaceInstUsesWith(Sel, V); 2264 return &Sel; 2265 } 2266 2267 // A select of a "select shuffle" with a common operand can be rearranged 2268 // to select followed by "select shuffle". Because of poison, this only works 2269 // in the case of a shuffle with no undefined mask elements. 2270 Value *Cond = Sel.getCondition(); 2271 Value *TVal = Sel.getTrueValue(); 2272 Value *FVal = Sel.getFalseValue(); 2273 Value *X, *Y; 2274 ArrayRef<int> Mask; 2275 if (match(TVal, m_OneUse(m_Shuffle(m_Value(X), m_Value(Y), m_Mask(Mask)))) && 2276 !is_contained(Mask, UndefMaskElem) && 2277 cast<ShuffleVectorInst>(TVal)->isSelect()) { 2278 if (X == FVal) { 2279 // select Cond, (shuf_sel X, Y), X --> shuf_sel X, (select Cond, Y, X) 2280 Value *NewSel = Builder.CreateSelect(Cond, Y, X, "sel", &Sel); 2281 return new ShuffleVectorInst(X, NewSel, Mask); 2282 } 2283 if (Y == FVal) { 2284 // select Cond, (shuf_sel X, Y), Y --> shuf_sel (select Cond, X, Y), Y 2285 Value *NewSel = Builder.CreateSelect(Cond, X, Y, "sel", &Sel); 2286 return new ShuffleVectorInst(NewSel, Y, Mask); 2287 } 2288 } 2289 if (match(FVal, m_OneUse(m_Shuffle(m_Value(X), m_Value(Y), m_Mask(Mask)))) && 2290 !is_contained(Mask, UndefMaskElem) && 2291 cast<ShuffleVectorInst>(FVal)->isSelect()) { 2292 if (X == TVal) { 2293 // select Cond, X, (shuf_sel X, Y) --> shuf_sel X, (select Cond, X, Y) 2294 Value *NewSel = Builder.CreateSelect(Cond, X, Y, "sel", &Sel); 2295 return new ShuffleVectorInst(X, NewSel, Mask); 2296 } 2297 if (Y == TVal) { 2298 // select Cond, Y, (shuf_sel X, Y) --> shuf_sel (select Cond, Y, X), Y 2299 Value *NewSel = Builder.CreateSelect(Cond, Y, X, "sel", &Sel); 2300 return new ShuffleVectorInst(NewSel, Y, Mask); 2301 } 2302 } 2303 2304 return nullptr; 2305 } 2306 2307 static Instruction *foldSelectToPhiImpl(SelectInst &Sel, BasicBlock *BB, 2308 const DominatorTree &DT, 2309 InstCombiner::BuilderTy &Builder) { 2310 // Find the block's immediate dominator that ends with a conditional branch 2311 // that matches select's condition (maybe inverted). 2312 auto *IDomNode = DT[BB]->getIDom(); 2313 if (!IDomNode) 2314 return nullptr; 2315 BasicBlock *IDom = IDomNode->getBlock(); 2316 2317 Value *Cond = Sel.getCondition(); 2318 Value *IfTrue, *IfFalse; 2319 BasicBlock *TrueSucc, *FalseSucc; 2320 if (match(IDom->getTerminator(), 2321 m_Br(m_Specific(Cond), m_BasicBlock(TrueSucc), 2322 m_BasicBlock(FalseSucc)))) { 2323 IfTrue = Sel.getTrueValue(); 2324 IfFalse = Sel.getFalseValue(); 2325 } else if (match(IDom->getTerminator(), 2326 m_Br(m_Not(m_Specific(Cond)), m_BasicBlock(TrueSucc), 2327 m_BasicBlock(FalseSucc)))) { 2328 IfTrue = Sel.getFalseValue(); 2329 IfFalse = Sel.getTrueValue(); 2330 } else 2331 return nullptr; 2332 2333 // Make sure the branches are actually different. 2334 if (TrueSucc == FalseSucc) 2335 return nullptr; 2336 2337 // We want to replace select %cond, %a, %b with a phi that takes value %a 2338 // for all incoming edges that are dominated by condition `%cond == true`, 2339 // and value %b for edges dominated by condition `%cond == false`. If %a 2340 // or %b are also phis from the same basic block, we can go further and take 2341 // their incoming values from the corresponding blocks. 2342 BasicBlockEdge TrueEdge(IDom, TrueSucc); 2343 BasicBlockEdge FalseEdge(IDom, FalseSucc); 2344 DenseMap<BasicBlock *, Value *> Inputs; 2345 for (auto *Pred : predecessors(BB)) { 2346 // Check implication. 2347 BasicBlockEdge Incoming(Pred, BB); 2348 if (DT.dominates(TrueEdge, Incoming)) 2349 Inputs[Pred] = IfTrue->DoPHITranslation(BB, Pred); 2350 else if (DT.dominates(FalseEdge, Incoming)) 2351 Inputs[Pred] = IfFalse->DoPHITranslation(BB, Pred); 2352 else 2353 return nullptr; 2354 // Check availability. 2355 if (auto *Insn = dyn_cast<Instruction>(Inputs[Pred])) 2356 if (!DT.dominates(Insn, Pred->getTerminator())) 2357 return nullptr; 2358 } 2359 2360 Builder.SetInsertPoint(&*BB->begin()); 2361 auto *PN = Builder.CreatePHI(Sel.getType(), Inputs.size()); 2362 for (auto *Pred : predecessors(BB)) 2363 PN->addIncoming(Inputs[Pred], Pred); 2364 PN->takeName(&Sel); 2365 return PN; 2366 } 2367 2368 static Instruction *foldSelectToPhi(SelectInst &Sel, const DominatorTree &DT, 2369 InstCombiner::BuilderTy &Builder) { 2370 // Try to replace this select with Phi in one of these blocks. 2371 SmallSetVector<BasicBlock *, 4> CandidateBlocks; 2372 CandidateBlocks.insert(Sel.getParent()); 2373 for (Value *V : Sel.operands()) 2374 if (auto *I = dyn_cast<Instruction>(V)) 2375 CandidateBlocks.insert(I->getParent()); 2376 2377 for (BasicBlock *BB : CandidateBlocks) 2378 if (auto *PN = foldSelectToPhiImpl(Sel, BB, DT, Builder)) 2379 return PN; 2380 return nullptr; 2381 } 2382 2383 static Value *foldSelectWithFrozenICmp(SelectInst &Sel, InstCombiner::BuilderTy &Builder) { 2384 FreezeInst *FI = dyn_cast<FreezeInst>(Sel.getCondition()); 2385 if (!FI) 2386 return nullptr; 2387 2388 Value *Cond = FI->getOperand(0); 2389 Value *TrueVal = Sel.getTrueValue(), *FalseVal = Sel.getFalseValue(); 2390 2391 // select (freeze(x == y)), x, y --> y 2392 // select (freeze(x != y)), x, y --> x 2393 // The freeze should be only used by this select. Otherwise, remaining uses of 2394 // the freeze can observe a contradictory value. 2395 // c = freeze(x == y) ; Let's assume that y = poison & x = 42; c is 0 or 1 2396 // a = select c, x, y ; 2397 // f(a, c) ; f(poison, 1) cannot happen, but if a is folded 2398 // ; to y, this can happen. 2399 CmpInst::Predicate Pred; 2400 if (FI->hasOneUse() && 2401 match(Cond, m_c_ICmp(Pred, m_Specific(TrueVal), m_Specific(FalseVal))) && 2402 (Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE)) { 2403 return Pred == ICmpInst::ICMP_EQ ? FalseVal : TrueVal; 2404 } 2405 2406 return nullptr; 2407 } 2408 2409 Instruction *InstCombinerImpl::foldAndOrOfSelectUsingImpliedCond(Value *Op, 2410 SelectInst &SI, 2411 bool IsAnd) { 2412 Value *CondVal = SI.getCondition(); 2413 Value *A = SI.getTrueValue(); 2414 Value *B = SI.getFalseValue(); 2415 2416 assert(Op->getType()->isIntOrIntVectorTy(1) && 2417 "Op must be either i1 or vector of i1."); 2418 2419 Optional<bool> Res = isImpliedCondition(Op, CondVal, DL, IsAnd); 2420 if (!Res) 2421 return nullptr; 2422 2423 Value *Zero = Constant::getNullValue(A->getType()); 2424 Value *One = Constant::getAllOnesValue(A->getType()); 2425 2426 if (*Res == true) { 2427 if (IsAnd) 2428 // select op, (select cond, A, B), false => select op, A, false 2429 // and op, (select cond, A, B) => select op, A, false 2430 // if op = true implies condval = true. 2431 return SelectInst::Create(Op, A, Zero); 2432 else 2433 // select op, true, (select cond, A, B) => select op, true, A 2434 // or op, (select cond, A, B) => select op, true, A 2435 // if op = false implies condval = true. 2436 return SelectInst::Create(Op, One, A); 2437 } else { 2438 if (IsAnd) 2439 // select op, (select cond, A, B), false => select op, B, false 2440 // and op, (select cond, A, B) => select op, B, false 2441 // if op = true implies condval = false. 2442 return SelectInst::Create(Op, B, Zero); 2443 else 2444 // select op, true, (select cond, A, B) => select op, true, B 2445 // or op, (select cond, A, B) => select op, true, B 2446 // if op = false implies condval = false. 2447 return SelectInst::Create(Op, One, B); 2448 } 2449 } 2450 2451 Instruction *InstCombinerImpl::visitSelectInst(SelectInst &SI) { 2452 Value *CondVal = SI.getCondition(); 2453 Value *TrueVal = SI.getTrueValue(); 2454 Value *FalseVal = SI.getFalseValue(); 2455 Type *SelType = SI.getType(); 2456 2457 // FIXME: Remove this workaround when freeze related patches are done. 2458 // For select with undef operand which feeds into an equality comparison, 2459 // don't simplify it so loop unswitch can know the equality comparison 2460 // may have an undef operand. This is a workaround for PR31652 caused by 2461 // descrepancy about branch on undef between LoopUnswitch and GVN. 2462 if (match(TrueVal, m_Undef()) || match(FalseVal, m_Undef())) { 2463 if (llvm::any_of(SI.users(), [&](User *U) { 2464 ICmpInst *CI = dyn_cast<ICmpInst>(U); 2465 if (CI && CI->isEquality()) 2466 return true; 2467 return false; 2468 })) { 2469 return nullptr; 2470 } 2471 } 2472 2473 if (Value *V = SimplifySelectInst(CondVal, TrueVal, FalseVal, 2474 SQ.getWithInstruction(&SI))) 2475 return replaceInstUsesWith(SI, V); 2476 2477 if (Instruction *I = canonicalizeSelectToShuffle(SI)) 2478 return I; 2479 2480 if (Instruction *I = canonicalizeScalarSelectOfVecs(SI, *this)) 2481 return I; 2482 2483 CmpInst::Predicate Pred; 2484 2485 // Avoid potential infinite loops by checking for non-constant condition. 2486 // TODO: Can we assert instead by improving canonicalizeSelectToShuffle()? 2487 // Scalar select must have simplified? 2488 if (SelType->isIntOrIntVectorTy(1) && !isa<Constant>(CondVal) && 2489 TrueVal->getType() == CondVal->getType()) { 2490 // Folding select to and/or i1 isn't poison safe in general. impliesPoison 2491 // checks whether folding it does not convert a well-defined value into 2492 // poison. 2493 if (match(TrueVal, m_One())) { 2494 if (impliesPoison(FalseVal, CondVal)) { 2495 // Change: A = select B, true, C --> A = or B, C 2496 return BinaryOperator::CreateOr(CondVal, FalseVal); 2497 } 2498 2499 if (auto *LHS = dyn_cast<FCmpInst>(CondVal)) 2500 if (auto *RHS = dyn_cast<FCmpInst>(FalseVal)) 2501 if (Value *V = foldLogicOfFCmps(LHS, RHS, /*IsAnd*/ false, 2502 /*IsSelectLogical*/ true)) 2503 return replaceInstUsesWith(SI, V); 2504 } 2505 if (match(FalseVal, m_Zero())) { 2506 if (impliesPoison(TrueVal, CondVal)) { 2507 // Change: A = select B, C, false --> A = and B, C 2508 return BinaryOperator::CreateAnd(CondVal, TrueVal); 2509 } 2510 2511 if (auto *LHS = dyn_cast<FCmpInst>(CondVal)) 2512 if (auto *RHS = dyn_cast<FCmpInst>(TrueVal)) 2513 if (Value *V = foldLogicOfFCmps(LHS, RHS, /*IsAnd*/ true, 2514 /*IsSelectLogical*/ true)) 2515 return replaceInstUsesWith(SI, V); 2516 } 2517 2518 auto *One = ConstantInt::getTrue(SelType); 2519 auto *Zero = ConstantInt::getFalse(SelType); 2520 2521 // We match the "full" 0 or 1 constant here to avoid a potential infinite 2522 // loop with vectors that may have undefined/poison elements. 2523 // select a, false, b -> select !a, b, false 2524 if (match(TrueVal, m_Specific(Zero))) { 2525 Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName()); 2526 return SelectInst::Create(NotCond, FalseVal, Zero); 2527 } 2528 // select a, b, true -> select !a, true, b 2529 if (match(FalseVal, m_Specific(One))) { 2530 Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName()); 2531 return SelectInst::Create(NotCond, One, TrueVal); 2532 } 2533 2534 // select a, a, b -> select a, true, b 2535 if (CondVal == TrueVal) 2536 return replaceOperand(SI, 1, One); 2537 // select a, b, a -> select a, b, false 2538 if (CondVal == FalseVal) 2539 return replaceOperand(SI, 2, Zero); 2540 2541 // select a, !a, b -> select !a, b, false 2542 if (match(TrueVal, m_Not(m_Specific(CondVal)))) 2543 return SelectInst::Create(TrueVal, FalseVal, Zero); 2544 // select a, b, !a -> select !a, true, b 2545 if (match(FalseVal, m_Not(m_Specific(CondVal)))) 2546 return SelectInst::Create(FalseVal, One, TrueVal); 2547 2548 Value *A, *B; 2549 2550 // DeMorgan in select form: !a && !b --> !(a || b) 2551 // select !a, !b, false --> not (select a, true, b) 2552 if (match(&SI, m_LogicalAnd(m_Not(m_Value(A)), m_Not(m_Value(B)))) && 2553 (CondVal->hasOneUse() || TrueVal->hasOneUse()) && 2554 !match(A, m_ConstantExpr()) && !match(B, m_ConstantExpr())) 2555 return BinaryOperator::CreateNot(Builder.CreateSelect(A, One, B)); 2556 2557 // DeMorgan in select form: !a || !b --> !(a && b) 2558 // select !a, true, !b --> not (select a, b, false) 2559 if (match(&SI, m_LogicalOr(m_Not(m_Value(A)), m_Not(m_Value(B)))) && 2560 (CondVal->hasOneUse() || FalseVal->hasOneUse()) && 2561 !match(A, m_ConstantExpr()) && !match(B, m_ConstantExpr())) 2562 return BinaryOperator::CreateNot(Builder.CreateSelect(A, B, Zero)); 2563 2564 // select (select a, true, b), true, b -> select a, true, b 2565 if (match(CondVal, m_Select(m_Value(A), m_One(), m_Value(B))) && 2566 match(TrueVal, m_One()) && match(FalseVal, m_Specific(B))) 2567 return replaceOperand(SI, 0, A); 2568 // select (select a, b, false), b, false -> select a, b, false 2569 if (match(CondVal, m_Select(m_Value(A), m_Value(B), m_Zero())) && 2570 match(TrueVal, m_Specific(B)) && match(FalseVal, m_Zero())) 2571 return replaceOperand(SI, 0, A); 2572 2573 Value *C; 2574 // select (~a | c), a, b -> and a, (or c, freeze(b)) 2575 if (match(CondVal, m_c_Or(m_Not(m_Specific(TrueVal)), m_Value(C))) && 2576 CondVal->hasOneUse()) { 2577 FalseVal = Builder.CreateFreeze(FalseVal); 2578 return BinaryOperator::CreateAnd(TrueVal, Builder.CreateOr(C, FalseVal)); 2579 } 2580 // select (~c & b), a, b -> and b, (or freeze(a), c) 2581 if (match(CondVal, m_c_And(m_Not(m_Value(C)), m_Specific(FalseVal))) && 2582 CondVal->hasOneUse()) { 2583 TrueVal = Builder.CreateFreeze(TrueVal); 2584 return BinaryOperator::CreateAnd(FalseVal, Builder.CreateOr(C, TrueVal)); 2585 } 2586 2587 if (!SelType->isVectorTy()) { 2588 if (Value *S = simplifyWithOpReplaced(TrueVal, CondVal, One, SQ, 2589 /* AllowRefinement */ true)) 2590 return replaceOperand(SI, 1, S); 2591 if (Value *S = simplifyWithOpReplaced(FalseVal, CondVal, Zero, SQ, 2592 /* AllowRefinement */ true)) 2593 return replaceOperand(SI, 2, S); 2594 } 2595 2596 if (match(FalseVal, m_Zero()) || match(TrueVal, m_One())) { 2597 Use *Y = nullptr; 2598 bool IsAnd = match(FalseVal, m_Zero()) ? true : false; 2599 Value *Op1 = IsAnd ? TrueVal : FalseVal; 2600 if (isCheckForZeroAndMulWithOverflow(CondVal, Op1, IsAnd, Y)) { 2601 auto *FI = new FreezeInst(*Y, (*Y)->getName() + ".fr"); 2602 InsertNewInstBefore(FI, *cast<Instruction>(Y->getUser())); 2603 replaceUse(*Y, FI); 2604 return replaceInstUsesWith(SI, Op1); 2605 } 2606 2607 if (auto *Op1SI = dyn_cast<SelectInst>(Op1)) 2608 if (auto *I = foldAndOrOfSelectUsingImpliedCond(CondVal, *Op1SI, 2609 /* IsAnd */ IsAnd)) 2610 return I; 2611 2612 if (auto *ICmp0 = dyn_cast<ICmpInst>(CondVal)) { 2613 if (auto *ICmp1 = dyn_cast<ICmpInst>(Op1)) { 2614 if (auto *V = foldAndOrOfICmpsOfAndWithPow2(ICmp0, ICmp1, &SI, IsAnd, 2615 /* IsLogical */ true)) 2616 return replaceInstUsesWith(SI, V); 2617 2618 if (auto *V = foldEqOfParts(ICmp0, ICmp1, IsAnd)) 2619 return replaceInstUsesWith(SI, V); 2620 } 2621 } 2622 } 2623 2624 // select (select a, true, b), c, false -> select a, c, false 2625 // select c, (select a, true, b), false -> select c, a, false 2626 // if c implies that b is false. 2627 if (match(CondVal, m_Select(m_Value(A), m_One(), m_Value(B))) && 2628 match(FalseVal, m_Zero())) { 2629 Optional<bool> Res = isImpliedCondition(TrueVal, B, DL); 2630 if (Res && *Res == false) 2631 return replaceOperand(SI, 0, A); 2632 } 2633 if (match(TrueVal, m_Select(m_Value(A), m_One(), m_Value(B))) && 2634 match(FalseVal, m_Zero())) { 2635 Optional<bool> Res = isImpliedCondition(CondVal, B, DL); 2636 if (Res && *Res == false) 2637 return replaceOperand(SI, 1, A); 2638 } 2639 // select c, true, (select a, b, false) -> select c, true, a 2640 // select (select a, b, false), true, c -> select a, true, c 2641 // if c = false implies that b = true 2642 if (match(TrueVal, m_One()) && 2643 match(FalseVal, m_Select(m_Value(A), m_Value(B), m_Zero()))) { 2644 Optional<bool> Res = isImpliedCondition(CondVal, B, DL, false); 2645 if (Res && *Res == true) 2646 return replaceOperand(SI, 2, A); 2647 } 2648 if (match(CondVal, m_Select(m_Value(A), m_Value(B), m_Zero())) && 2649 match(TrueVal, m_One())) { 2650 Optional<bool> Res = isImpliedCondition(FalseVal, B, DL, false); 2651 if (Res && *Res == true) 2652 return replaceOperand(SI, 0, A); 2653 } 2654 2655 // sel (sel c, a, false), true, (sel !c, b, false) -> sel c, a, b 2656 // sel (sel !c, a, false), true, (sel c, b, false) -> sel c, b, a 2657 Value *C1, *C2; 2658 if (match(CondVal, m_Select(m_Value(C1), m_Value(A), m_Zero())) && 2659 match(TrueVal, m_One()) && 2660 match(FalseVal, m_Select(m_Value(C2), m_Value(B), m_Zero()))) { 2661 if (match(C2, m_Not(m_Specific(C1)))) // first case 2662 return SelectInst::Create(C1, A, B); 2663 else if (match(C1, m_Not(m_Specific(C2)))) // second case 2664 return SelectInst::Create(C2, B, A); 2665 } 2666 } 2667 2668 // Selecting between two integer or vector splat integer constants? 2669 // 2670 // Note that we don't handle a scalar select of vectors: 2671 // select i1 %c, <2 x i8> <1, 1>, <2 x i8> <0, 0> 2672 // because that may need 3 instructions to splat the condition value: 2673 // extend, insertelement, shufflevector. 2674 // 2675 // Do not handle i1 TrueVal and FalseVal otherwise would result in 2676 // zext/sext i1 to i1. 2677 if (SelType->isIntOrIntVectorTy() && !SelType->isIntOrIntVectorTy(1) && 2678 CondVal->getType()->isVectorTy() == SelType->isVectorTy()) { 2679 // select C, 1, 0 -> zext C to int 2680 if (match(TrueVal, m_One()) && match(FalseVal, m_Zero())) 2681 return new ZExtInst(CondVal, SelType); 2682 2683 // select C, -1, 0 -> sext C to int 2684 if (match(TrueVal, m_AllOnes()) && match(FalseVal, m_Zero())) 2685 return new SExtInst(CondVal, SelType); 2686 2687 // select C, 0, 1 -> zext !C to int 2688 if (match(TrueVal, m_Zero()) && match(FalseVal, m_One())) { 2689 Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName()); 2690 return new ZExtInst(NotCond, SelType); 2691 } 2692 2693 // select C, 0, -1 -> sext !C to int 2694 if (match(TrueVal, m_Zero()) && match(FalseVal, m_AllOnes())) { 2695 Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName()); 2696 return new SExtInst(NotCond, SelType); 2697 } 2698 } 2699 2700 if (auto *FCmp = dyn_cast<FCmpInst>(CondVal)) { 2701 Value *Cmp0 = FCmp->getOperand(0), *Cmp1 = FCmp->getOperand(1); 2702 // Are we selecting a value based on a comparison of the two values? 2703 if ((Cmp0 == TrueVal && Cmp1 == FalseVal) || 2704 (Cmp0 == FalseVal && Cmp1 == TrueVal)) { 2705 // Canonicalize to use ordered comparisons by swapping the select 2706 // operands. 2707 // 2708 // e.g. 2709 // (X ugt Y) ? X : Y -> (X ole Y) ? Y : X 2710 if (FCmp->hasOneUse() && FCmpInst::isUnordered(FCmp->getPredicate())) { 2711 FCmpInst::Predicate InvPred = FCmp->getInversePredicate(); 2712 IRBuilder<>::FastMathFlagGuard FMFG(Builder); 2713 // FIXME: The FMF should propagate from the select, not the fcmp. 2714 Builder.setFastMathFlags(FCmp->getFastMathFlags()); 2715 Value *NewCond = Builder.CreateFCmp(InvPred, Cmp0, Cmp1, 2716 FCmp->getName() + ".inv"); 2717 Value *NewSel = Builder.CreateSelect(NewCond, FalseVal, TrueVal); 2718 return replaceInstUsesWith(SI, NewSel); 2719 } 2720 2721 // NOTE: if we wanted to, this is where to detect MIN/MAX 2722 } 2723 } 2724 2725 // Canonicalize select with fcmp to fabs(). -0.0 makes this tricky. We need 2726 // fast-math-flags (nsz) or fsub with +0.0 (not fneg) for this to work. 2727 // (X <= +/-0.0) ? (0.0 - X) : X --> fabs(X) 2728 if (match(CondVal, m_FCmp(Pred, m_Specific(FalseVal), m_AnyZeroFP())) && 2729 match(TrueVal, m_FSub(m_PosZeroFP(), m_Specific(FalseVal))) && 2730 (Pred == FCmpInst::FCMP_OLE || Pred == FCmpInst::FCMP_ULE)) { 2731 Value *Fabs = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, FalseVal, &SI); 2732 return replaceInstUsesWith(SI, Fabs); 2733 } 2734 // (X > +/-0.0) ? X : (0.0 - X) --> fabs(X) 2735 if (match(CondVal, m_FCmp(Pred, m_Specific(TrueVal), m_AnyZeroFP())) && 2736 match(FalseVal, m_FSub(m_PosZeroFP(), m_Specific(TrueVal))) && 2737 (Pred == FCmpInst::FCMP_OGT || Pred == FCmpInst::FCMP_UGT)) { 2738 Value *Fabs = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, TrueVal, &SI); 2739 return replaceInstUsesWith(SI, Fabs); 2740 } 2741 // With nnan and nsz: 2742 // (X < +/-0.0) ? -X : X --> fabs(X) 2743 // (X <= +/-0.0) ? -X : X --> fabs(X) 2744 if (match(CondVal, m_FCmp(Pred, m_Specific(FalseVal), m_AnyZeroFP())) && 2745 match(TrueVal, m_FNeg(m_Specific(FalseVal))) && SI.hasNoSignedZeros() && 2746 (Pred == FCmpInst::FCMP_OLT || Pred == FCmpInst::FCMP_OLE || 2747 Pred == FCmpInst::FCMP_ULT || Pred == FCmpInst::FCMP_ULE)) { 2748 Value *Fabs = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, FalseVal, &SI); 2749 return replaceInstUsesWith(SI, Fabs); 2750 } 2751 // With nnan and nsz: 2752 // (X > +/-0.0) ? X : -X --> fabs(X) 2753 // (X >= +/-0.0) ? X : -X --> fabs(X) 2754 if (match(CondVal, m_FCmp(Pred, m_Specific(TrueVal), m_AnyZeroFP())) && 2755 match(FalseVal, m_FNeg(m_Specific(TrueVal))) && SI.hasNoSignedZeros() && 2756 (Pred == FCmpInst::FCMP_OGT || Pred == FCmpInst::FCMP_OGE || 2757 Pred == FCmpInst::FCMP_UGT || Pred == FCmpInst::FCMP_UGE)) { 2758 Value *Fabs = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, TrueVal, &SI); 2759 return replaceInstUsesWith(SI, Fabs); 2760 } 2761 2762 // See if we are selecting two values based on a comparison of the two values. 2763 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) 2764 if (Instruction *Result = foldSelectInstWithICmp(SI, ICI)) 2765 return Result; 2766 2767 if (Instruction *Add = foldAddSubSelect(SI, Builder)) 2768 return Add; 2769 if (Instruction *Add = foldOverflowingAddSubSelect(SI, Builder)) 2770 return Add; 2771 if (Instruction *Or = foldSetClearBits(SI, Builder)) 2772 return Or; 2773 if (Instruction *Mul = foldSelectZeroOrMul(SI, *this)) 2774 return Mul; 2775 2776 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z)) 2777 auto *TI = dyn_cast<Instruction>(TrueVal); 2778 auto *FI = dyn_cast<Instruction>(FalseVal); 2779 if (TI && FI && TI->getOpcode() == FI->getOpcode()) 2780 if (Instruction *IV = foldSelectOpOp(SI, TI, FI)) 2781 return IV; 2782 2783 if (Instruction *I = foldSelectExtConst(SI)) 2784 return I; 2785 2786 // Fold (select C, (gep Ptr, Idx), Ptr) -> (gep Ptr, (select C, Idx, 0)) 2787 // Fold (select C, Ptr, (gep Ptr, Idx)) -> (gep Ptr, (select C, 0, Idx)) 2788 auto SelectGepWithBase = [&](GetElementPtrInst *Gep, Value *Base, 2789 bool Swap) -> GetElementPtrInst * { 2790 Value *Ptr = Gep->getPointerOperand(); 2791 if (Gep->getNumOperands() != 2 || Gep->getPointerOperand() != Base || 2792 !Gep->hasOneUse()) 2793 return nullptr; 2794 Value *Idx = Gep->getOperand(1); 2795 if (isa<VectorType>(CondVal->getType()) && !isa<VectorType>(Idx->getType())) 2796 return nullptr; 2797 Type *ElementType = Gep->getResultElementType(); 2798 Value *NewT = Idx; 2799 Value *NewF = Constant::getNullValue(Idx->getType()); 2800 if (Swap) 2801 std::swap(NewT, NewF); 2802 Value *NewSI = 2803 Builder.CreateSelect(CondVal, NewT, NewF, SI.getName() + ".idx", &SI); 2804 return GetElementPtrInst::Create(ElementType, Ptr, {NewSI}); 2805 }; 2806 if (auto *TrueGep = dyn_cast<GetElementPtrInst>(TrueVal)) 2807 if (auto *NewGep = SelectGepWithBase(TrueGep, FalseVal, false)) 2808 return NewGep; 2809 if (auto *FalseGep = dyn_cast<GetElementPtrInst>(FalseVal)) 2810 if (auto *NewGep = SelectGepWithBase(FalseGep, TrueVal, true)) 2811 return NewGep; 2812 2813 // See if we can fold the select into one of our operands. 2814 if (SelType->isIntOrIntVectorTy() || SelType->isFPOrFPVectorTy()) { 2815 if (Instruction *FoldI = foldSelectIntoOp(SI, TrueVal, FalseVal)) 2816 return FoldI; 2817 2818 Value *LHS, *RHS; 2819 Instruction::CastOps CastOp; 2820 SelectPatternResult SPR = matchSelectPattern(&SI, LHS, RHS, &CastOp); 2821 auto SPF = SPR.Flavor; 2822 if (SPF) { 2823 Value *LHS2, *RHS2; 2824 if (SelectPatternFlavor SPF2 = matchSelectPattern(LHS, LHS2, RHS2).Flavor) 2825 if (Instruction *R = foldSPFofSPF(cast<Instruction>(LHS), SPF2, LHS2, 2826 RHS2, SI, SPF, RHS)) 2827 return R; 2828 if (SelectPatternFlavor SPF2 = matchSelectPattern(RHS, LHS2, RHS2).Flavor) 2829 if (Instruction *R = foldSPFofSPF(cast<Instruction>(RHS), SPF2, LHS2, 2830 RHS2, SI, SPF, LHS)) 2831 return R; 2832 } 2833 2834 if (SelectPatternResult::isMinOrMax(SPF)) { 2835 // Canonicalize so that 2836 // - type casts are outside select patterns. 2837 // - float clamp is transformed to min/max pattern 2838 2839 bool IsCastNeeded = LHS->getType() != SelType; 2840 Value *CmpLHS = cast<CmpInst>(CondVal)->getOperand(0); 2841 Value *CmpRHS = cast<CmpInst>(CondVal)->getOperand(1); 2842 if (IsCastNeeded || 2843 (LHS->getType()->isFPOrFPVectorTy() && 2844 ((CmpLHS != LHS && CmpLHS != RHS) || 2845 (CmpRHS != LHS && CmpRHS != RHS)))) { 2846 CmpInst::Predicate MinMaxPred = getMinMaxPred(SPF, SPR.Ordered); 2847 2848 Value *Cmp; 2849 if (CmpInst::isIntPredicate(MinMaxPred)) { 2850 Cmp = Builder.CreateICmp(MinMaxPred, LHS, RHS); 2851 } else { 2852 IRBuilder<>::FastMathFlagGuard FMFG(Builder); 2853 auto FMF = 2854 cast<FPMathOperator>(SI.getCondition())->getFastMathFlags(); 2855 Builder.setFastMathFlags(FMF); 2856 Cmp = Builder.CreateFCmp(MinMaxPred, LHS, RHS); 2857 } 2858 2859 Value *NewSI = Builder.CreateSelect(Cmp, LHS, RHS, SI.getName(), &SI); 2860 if (!IsCastNeeded) 2861 return replaceInstUsesWith(SI, NewSI); 2862 2863 Value *NewCast = Builder.CreateCast(CastOp, NewSI, SelType); 2864 return replaceInstUsesWith(SI, NewCast); 2865 } 2866 } 2867 } 2868 2869 // Canonicalize select of FP values where NaN and -0.0 are not valid as 2870 // minnum/maxnum intrinsics. 2871 if (isa<FPMathOperator>(SI) && SI.hasNoNaNs() && SI.hasNoSignedZeros()) { 2872 Value *X, *Y; 2873 if (match(&SI, m_OrdFMax(m_Value(X), m_Value(Y)))) 2874 return replaceInstUsesWith( 2875 SI, Builder.CreateBinaryIntrinsic(Intrinsic::maxnum, X, Y, &SI)); 2876 2877 if (match(&SI, m_OrdFMin(m_Value(X), m_Value(Y)))) 2878 return replaceInstUsesWith( 2879 SI, Builder.CreateBinaryIntrinsic(Intrinsic::minnum, X, Y, &SI)); 2880 } 2881 2882 // See if we can fold the select into a phi node if the condition is a select. 2883 if (auto *PN = dyn_cast<PHINode>(SI.getCondition())) 2884 // The true/false values have to be live in the PHI predecessor's blocks. 2885 if (canSelectOperandBeMappingIntoPredBlock(TrueVal, SI) && 2886 canSelectOperandBeMappingIntoPredBlock(FalseVal, SI)) 2887 if (Instruction *NV = foldOpIntoPhi(SI, PN)) 2888 return NV; 2889 2890 if (SelectInst *TrueSI = dyn_cast<SelectInst>(TrueVal)) { 2891 if (TrueSI->getCondition()->getType() == CondVal->getType()) { 2892 // select(C, select(C, a, b), c) -> select(C, a, c) 2893 if (TrueSI->getCondition() == CondVal) { 2894 if (SI.getTrueValue() == TrueSI->getTrueValue()) 2895 return nullptr; 2896 return replaceOperand(SI, 1, TrueSI->getTrueValue()); 2897 } 2898 // select(C0, select(C1, a, b), b) -> select(C0&C1, a, b) 2899 // We choose this as normal form to enable folding on the And and 2900 // shortening paths for the values (this helps getUnderlyingObjects() for 2901 // example). 2902 if (TrueSI->getFalseValue() == FalseVal && TrueSI->hasOneUse()) { 2903 Value *And = Builder.CreateLogicalAnd(CondVal, TrueSI->getCondition()); 2904 replaceOperand(SI, 0, And); 2905 replaceOperand(SI, 1, TrueSI->getTrueValue()); 2906 return &SI; 2907 } 2908 } 2909 } 2910 if (SelectInst *FalseSI = dyn_cast<SelectInst>(FalseVal)) { 2911 if (FalseSI->getCondition()->getType() == CondVal->getType()) { 2912 // select(C, a, select(C, b, c)) -> select(C, a, c) 2913 if (FalseSI->getCondition() == CondVal) { 2914 if (SI.getFalseValue() == FalseSI->getFalseValue()) 2915 return nullptr; 2916 return replaceOperand(SI, 2, FalseSI->getFalseValue()); 2917 } 2918 // select(C0, a, select(C1, a, b)) -> select(C0|C1, a, b) 2919 if (FalseSI->getTrueValue() == TrueVal && FalseSI->hasOneUse()) { 2920 Value *Or = Builder.CreateLogicalOr(CondVal, FalseSI->getCondition()); 2921 replaceOperand(SI, 0, Or); 2922 replaceOperand(SI, 2, FalseSI->getFalseValue()); 2923 return &SI; 2924 } 2925 } 2926 } 2927 2928 auto canMergeSelectThroughBinop = [](BinaryOperator *BO) { 2929 // The select might be preventing a division by 0. 2930 switch (BO->getOpcode()) { 2931 default: 2932 return true; 2933 case Instruction::SRem: 2934 case Instruction::URem: 2935 case Instruction::SDiv: 2936 case Instruction::UDiv: 2937 return false; 2938 } 2939 }; 2940 2941 // Try to simplify a binop sandwiched between 2 selects with the same 2942 // condition. 2943 // select(C, binop(select(C, X, Y), W), Z) -> select(C, binop(X, W), Z) 2944 BinaryOperator *TrueBO; 2945 if (match(TrueVal, m_OneUse(m_BinOp(TrueBO))) && 2946 canMergeSelectThroughBinop(TrueBO)) { 2947 if (auto *TrueBOSI = dyn_cast<SelectInst>(TrueBO->getOperand(0))) { 2948 if (TrueBOSI->getCondition() == CondVal) { 2949 replaceOperand(*TrueBO, 0, TrueBOSI->getTrueValue()); 2950 Worklist.push(TrueBO); 2951 return &SI; 2952 } 2953 } 2954 if (auto *TrueBOSI = dyn_cast<SelectInst>(TrueBO->getOperand(1))) { 2955 if (TrueBOSI->getCondition() == CondVal) { 2956 replaceOperand(*TrueBO, 1, TrueBOSI->getTrueValue()); 2957 Worklist.push(TrueBO); 2958 return &SI; 2959 } 2960 } 2961 } 2962 2963 // select(C, Z, binop(select(C, X, Y), W)) -> select(C, Z, binop(Y, W)) 2964 BinaryOperator *FalseBO; 2965 if (match(FalseVal, m_OneUse(m_BinOp(FalseBO))) && 2966 canMergeSelectThroughBinop(FalseBO)) { 2967 if (auto *FalseBOSI = dyn_cast<SelectInst>(FalseBO->getOperand(0))) { 2968 if (FalseBOSI->getCondition() == CondVal) { 2969 replaceOperand(*FalseBO, 0, FalseBOSI->getFalseValue()); 2970 Worklist.push(FalseBO); 2971 return &SI; 2972 } 2973 } 2974 if (auto *FalseBOSI = dyn_cast<SelectInst>(FalseBO->getOperand(1))) { 2975 if (FalseBOSI->getCondition() == CondVal) { 2976 replaceOperand(*FalseBO, 1, FalseBOSI->getFalseValue()); 2977 Worklist.push(FalseBO); 2978 return &SI; 2979 } 2980 } 2981 } 2982 2983 Value *NotCond; 2984 if (match(CondVal, m_Not(m_Value(NotCond))) && 2985 !InstCombiner::shouldAvoidAbsorbingNotIntoSelect(SI)) { 2986 replaceOperand(SI, 0, NotCond); 2987 SI.swapValues(); 2988 SI.swapProfMetadata(); 2989 return &SI; 2990 } 2991 2992 if (Instruction *I = foldVectorSelect(SI)) 2993 return I; 2994 2995 // If we can compute the condition, there's no need for a select. 2996 // Like the above fold, we are attempting to reduce compile-time cost by 2997 // putting this fold here with limitations rather than in InstSimplify. 2998 // The motivation for this call into value tracking is to take advantage of 2999 // the assumption cache, so make sure that is populated. 3000 if (!CondVal->getType()->isVectorTy() && !AC.assumptions().empty()) { 3001 KnownBits Known(1); 3002 computeKnownBits(CondVal, Known, 0, &SI); 3003 if (Known.One.isOne()) 3004 return replaceInstUsesWith(SI, TrueVal); 3005 if (Known.Zero.isOne()) 3006 return replaceInstUsesWith(SI, FalseVal); 3007 } 3008 3009 if (Instruction *BitCastSel = foldSelectCmpBitcasts(SI, Builder)) 3010 return BitCastSel; 3011 3012 // Simplify selects that test the returned flag of cmpxchg instructions. 3013 if (Value *V = foldSelectCmpXchg(SI)) 3014 return replaceInstUsesWith(SI, V); 3015 3016 if (Instruction *Select = foldSelectBinOpIdentity(SI, TLI, *this)) 3017 return Select; 3018 3019 if (Instruction *Funnel = foldSelectFunnelShift(SI, Builder)) 3020 return Funnel; 3021 3022 if (Instruction *Copysign = foldSelectToCopysign(SI, Builder)) 3023 return Copysign; 3024 3025 if (Instruction *PN = foldSelectToPhi(SI, DT, Builder)) 3026 return replaceInstUsesWith(SI, PN); 3027 3028 if (Value *Fr = foldSelectWithFrozenICmp(SI, Builder)) 3029 return replaceInstUsesWith(SI, Fr); 3030 3031 // select(mask, mload(,,mask,0), 0) -> mload(,,mask,0) 3032 // Load inst is intentionally not checked for hasOneUse() 3033 if (match(FalseVal, m_Zero()) && 3034 (match(TrueVal, m_MaskedLoad(m_Value(), m_Value(), m_Specific(CondVal), 3035 m_CombineOr(m_Undef(), m_Zero()))) || 3036 match(TrueVal, m_MaskedGather(m_Value(), m_Value(), m_Specific(CondVal), 3037 m_CombineOr(m_Undef(), m_Zero()))))) { 3038 auto *MaskedInst = cast<IntrinsicInst>(TrueVal); 3039 if (isa<UndefValue>(MaskedInst->getArgOperand(3))) 3040 MaskedInst->setArgOperand(3, FalseVal /* Zero */); 3041 return replaceInstUsesWith(SI, MaskedInst); 3042 } 3043 3044 Value *Mask; 3045 if (match(TrueVal, m_Zero()) && 3046 (match(FalseVal, m_MaskedLoad(m_Value(), m_Value(), m_Value(Mask), 3047 m_CombineOr(m_Undef(), m_Zero()))) || 3048 match(FalseVal, m_MaskedGather(m_Value(), m_Value(), m_Value(Mask), 3049 m_CombineOr(m_Undef(), m_Zero())))) && 3050 (CondVal->getType() == Mask->getType())) { 3051 // We can remove the select by ensuring the load zeros all lanes the 3052 // select would have. We determine this by proving there is no overlap 3053 // between the load and select masks. 3054 // (i.e (load_mask & select_mask) == 0 == no overlap) 3055 bool CanMergeSelectIntoLoad = false; 3056 if (Value *V = SimplifyAndInst(CondVal, Mask, SQ.getWithInstruction(&SI))) 3057 CanMergeSelectIntoLoad = match(V, m_Zero()); 3058 3059 if (CanMergeSelectIntoLoad) { 3060 auto *MaskedInst = cast<IntrinsicInst>(FalseVal); 3061 if (isa<UndefValue>(MaskedInst->getArgOperand(3))) 3062 MaskedInst->setArgOperand(3, TrueVal /* Zero */); 3063 return replaceInstUsesWith(SI, MaskedInst); 3064 } 3065 } 3066 3067 return nullptr; 3068 } 3069