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