LLVM 20.0.0git
InstCombineSelect.cpp
Go to the documentation of this file.
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/STLExtras.h"
23#include "llvm/IR/BasicBlock.h"
24#include "llvm/IR/Constant.h"
26#include "llvm/IR/Constants.h"
28#include "llvm/IR/IRBuilder.h"
29#include "llvm/IR/InstrTypes.h"
30#include "llvm/IR/Instruction.h"
33#include "llvm/IR/Intrinsics.h"
34#include "llvm/IR/Operator.h"
36#include "llvm/IR/Type.h"
37#include "llvm/IR/User.h"
38#include "llvm/IR/Value.h"
43#include <cassert>
44#include <utility>
45
46#define DEBUG_TYPE "instcombine"
48
49using namespace llvm;
50using namespace PatternMatch;
51
52
53/// Replace a select operand based on an equality comparison with the identity
54/// constant of a binop.
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 CmpPredicate 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.
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();
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() &&
104 return nullptr;
105
106 // BO = binop Y, X
107 // S = { select (cmp eq X, C), BO, ? } or { select (cmp ne X, C), ?, BO }
108 // =>
109 // S = { select (cmp eq X, C), Y, ? } or { select (cmp ne X, C), ?, Y }
110 return IC.replaceOperand(Sel, IsEq ? 1 : 2, Y);
111}
112
113/// This folds:
114/// select (icmp eq (and X, C1)), TC, FC
115/// iff C1 is a power 2 and the difference between TC and FC is a power-of-2.
116/// To something like:
117/// (shr (and (X, C1)), (log2(C1) - log2(TC-FC))) + FC
118/// Or:
119/// (shl (and (X, C1)), (log2(TC-FC) - log2(C1))) + FC
120/// With some variations depending if FC is larger than TC, or the shift
121/// isn't needed, or the bit widths don't match.
123 InstCombiner::BuilderTy &Builder) {
124 const APInt *SelTC, *SelFC;
125 if (!match(Sel.getTrueValue(), m_APInt(SelTC)) ||
126 !match(Sel.getFalseValue(), m_APInt(SelFC)))
127 return nullptr;
128
129 // If this is a vector select, we need a vector compare.
130 Type *SelType = Sel.getType();
131 if (SelType->isVectorTy() != Cmp->getType()->isVectorTy())
132 return nullptr;
133
134 Value *V;
135 APInt AndMask;
136 bool CreateAnd = false;
137 ICmpInst::Predicate Pred = Cmp->getPredicate();
138 if (ICmpInst::isEquality(Pred)) {
139 if (!match(Cmp->getOperand(1), m_Zero()))
140 return nullptr;
141
142 V = Cmp->getOperand(0);
143 const APInt *AndRHS;
144 if (!match(V, m_And(m_Value(), m_Power2(AndRHS))))
145 return nullptr;
146
147 AndMask = *AndRHS;
148 } else if (auto Res = decomposeBitTestICmp(Cmp->getOperand(0),
149 Cmp->getOperand(1), Pred)) {
150 assert(ICmpInst::isEquality(Res->Pred) && "Not equality test?");
151 if (!Res->Mask.isPowerOf2())
152 return nullptr;
153
154 V = Res->X;
155 AndMask = Res->Mask;
156 Pred = Res->Pred;
157 CreateAnd = true;
158 } else {
159 return nullptr;
160 }
161 if (Pred == ICmpInst::ICMP_NE)
162 std::swap(SelTC, SelFC);
163
164 // In general, when both constants are non-zero, we would need an offset to
165 // replace the select. This would require more instructions than we started
166 // with. But there's one special-case that we handle here because it can
167 // simplify/reduce the instructions.
168 const APInt &TC = *SelTC;
169 const APInt &FC = *SelFC;
170 if (!TC.isZero() && !FC.isZero()) {
171 if (TC.getBitWidth() != AndMask.getBitWidth())
172 return nullptr;
173 // If we have to create an 'and', then we must kill the cmp to not
174 // increase the instruction count.
175 if (CreateAnd && !Cmp->hasOneUse())
176 return nullptr;
177
178 // (V & AndMaskC) == 0 ? TC : FC --> TC | (V & AndMaskC)
179 // (V & AndMaskC) == 0 ? TC : FC --> TC ^ (V & AndMaskC)
180 // (V & AndMaskC) == 0 ? TC : FC --> TC + (V & AndMaskC)
181 // (V & AndMaskC) == 0 ? TC : FC --> TC - (V & AndMaskC)
182 Constant *TCC = ConstantInt::get(SelType, TC);
183 Constant *FCC = ConstantInt::get(SelType, FC);
184 Constant *MaskC = ConstantInt::get(SelType, AndMask);
185 for (auto Opc : {Instruction::Or, Instruction::Xor, Instruction::Add,
186 Instruction::Sub}) {
187 if (ConstantFoldBinaryOpOperands(Opc, TCC, MaskC, Sel.getDataLayout()) ==
188 FCC) {
189 if (CreateAnd)
190 V = Builder.CreateAnd(V, MaskC);
191 return Builder.CreateBinOp(Opc, TCC, V);
192 }
193 }
194
195 return nullptr;
196 }
197
198 // Make sure one of the select arms is a power-of-2.
199 if (!TC.isPowerOf2() && !FC.isPowerOf2())
200 return nullptr;
201
202 // Determine which shift is needed to transform result of the 'and' into the
203 // desired result.
204 const APInt &ValC = !TC.isZero() ? TC : FC;
205 unsigned ValZeros = ValC.logBase2();
206 unsigned AndZeros = AndMask.logBase2();
207 bool ShouldNotVal = !TC.isZero();
208
209 // If we would need to create an 'and' + 'shift' + 'xor' to replace a 'select'
210 // + 'icmp', then this transformation would result in more instructions and
211 // potentially interfere with other folding.
212 if (CreateAnd && ShouldNotVal && ValZeros != AndZeros)
213 return nullptr;
214
215 // Insert the 'and' instruction on the input to the truncate.
216 if (CreateAnd)
217 V = Builder.CreateAnd(V, ConstantInt::get(V->getType(), AndMask));
218
219 // If types don't match, we can still convert the select by introducing a zext
220 // or a trunc of the 'and'.
221 if (ValZeros > AndZeros) {
222 V = Builder.CreateZExtOrTrunc(V, SelType);
223 V = Builder.CreateShl(V, ValZeros - AndZeros);
224 } else if (ValZeros < AndZeros) {
225 V = Builder.CreateLShr(V, AndZeros - ValZeros);
226 V = Builder.CreateZExtOrTrunc(V, SelType);
227 } else {
228 V = Builder.CreateZExtOrTrunc(V, SelType);
229 }
230
231 // Okay, now we know that everything is set up, we just don't know whether we
232 // have a icmp_ne or icmp_eq and whether the true or false val is the zero.
233 if (ShouldNotVal)
234 V = Builder.CreateXor(V, ValC);
235
236 return V;
237}
238
239/// We want to turn code that looks like this:
240/// %C = or %A, %B
241/// %D = select %cond, %C, %A
242/// into:
243/// %C = select %cond, %B, 0
244/// %D = or %A, %C
245///
246/// Assuming that the specified instruction is an operand to the select, return
247/// a bitmask indicating which operands of this instruction are foldable if they
248/// equal the other incoming value of the select.
250 switch (I->getOpcode()) {
251 case Instruction::Add:
252 case Instruction::FAdd:
253 case Instruction::Mul:
254 case Instruction::FMul:
255 case Instruction::And:
256 case Instruction::Or:
257 case Instruction::Xor:
258 return 3; // Can fold through either operand.
259 case Instruction::Sub: // Can only fold on the amount subtracted.
260 case Instruction::FSub:
261 case Instruction::FDiv: // Can only fold on the divisor amount.
262 case Instruction::Shl: // Can only fold on the shift amount.
263 case Instruction::LShr:
264 case Instruction::AShr:
265 return 1;
266 default:
267 return 0; // Cannot fold
268 }
269}
270
271/// We have (select c, TI, FI), and we know that TI and FI have the same opcode.
273 Instruction *FI) {
274 // Don't break up min/max patterns. The hasOneUse checks below prevent that
275 // for most cases, but vector min/max with bitcasts can be transformed. If the
276 // one-use restrictions are eased for other patterns, we still don't want to
277 // obfuscate min/max.
278 if ((match(&SI, m_SMin(m_Value(), m_Value())) ||
279 match(&SI, m_SMax(m_Value(), m_Value())) ||
280 match(&SI, m_UMin(m_Value(), m_Value())) ||
281 match(&SI, m_UMax(m_Value(), m_Value()))))
282 return nullptr;
283
284 // If this is a cast from the same type, merge.
285 Value *Cond = SI.getCondition();
286 Type *CondTy = Cond->getType();
287 if (TI->getNumOperands() == 1 && TI->isCast()) {
288 Type *FIOpndTy = FI->getOperand(0)->getType();
289 if (TI->getOperand(0)->getType() != FIOpndTy)
290 return nullptr;
291
292 // The select condition may be a vector. We may only change the operand
293 // type if the vector width remains the same (and matches the condition).
294 if (auto *CondVTy = dyn_cast<VectorType>(CondTy)) {
295 if (!FIOpndTy->isVectorTy() ||
296 CondVTy->getElementCount() !=
297 cast<VectorType>(FIOpndTy)->getElementCount())
298 return nullptr;
299
300 // TODO: If the backend knew how to deal with casts better, we could
301 // remove this limitation. For now, there's too much potential to create
302 // worse codegen by promoting the select ahead of size-altering casts
303 // (PR28160).
304 //
305 // Note that ValueTracking's matchSelectPattern() looks through casts
306 // without checking 'hasOneUse' when it matches min/max patterns, so this
307 // transform may end up happening anyway.
308 if (TI->getOpcode() != Instruction::BitCast &&
309 (!TI->hasOneUse() || !FI->hasOneUse()))
310 return nullptr;
311 } else if (!TI->hasOneUse() || !FI->hasOneUse()) {
312 // TODO: The one-use restrictions for a scalar select could be eased if
313 // the fold of a select in visitLoadInst() was enhanced to match a pattern
314 // that includes a cast.
315 return nullptr;
316 }
317
318 // Fold this by inserting a select from the input values.
319 Value *NewSI =
321 SI.getName() + ".v", &SI);
323 TI->getType());
324 }
325
326 Value *OtherOpT, *OtherOpF;
327 bool MatchIsOpZero;
328 auto getCommonOp = [&](Instruction *TI, Instruction *FI, bool Commute,
329 bool Swapped = false) -> Value * {
330 assert(!(Commute && Swapped) &&
331 "Commute and Swapped can't set at the same time");
332 if (!Swapped) {
333 if (TI->getOperand(0) == FI->getOperand(0)) {
334 OtherOpT = TI->getOperand(1);
335 OtherOpF = FI->getOperand(1);
336 MatchIsOpZero = true;
337 return TI->getOperand(0);
338 } else if (TI->getOperand(1) == FI->getOperand(1)) {
339 OtherOpT = TI->getOperand(0);
340 OtherOpF = FI->getOperand(0);
341 MatchIsOpZero = false;
342 return TI->getOperand(1);
343 }
344 }
345
346 if (!Commute && !Swapped)
347 return nullptr;
348
349 // If we are allowing commute or swap of operands, then
350 // allow a cross-operand match. In that case, MatchIsOpZero
351 // means that TI's operand 0 (FI's operand 1) is the common op.
352 if (TI->getOperand(0) == FI->getOperand(1)) {
353 OtherOpT = TI->getOperand(1);
354 OtherOpF = FI->getOperand(0);
355 MatchIsOpZero = true;
356 return TI->getOperand(0);
357 } else if (TI->getOperand(1) == FI->getOperand(0)) {
358 OtherOpT = TI->getOperand(0);
359 OtherOpF = FI->getOperand(1);
360 MatchIsOpZero = false;
361 return TI->getOperand(1);
362 }
363 return nullptr;
364 };
365
366 if (TI->hasOneUse() || FI->hasOneUse()) {
367 // Cond ? -X : -Y --> -(Cond ? X : Y)
368 Value *X, *Y;
369 if (match(TI, m_FNeg(m_Value(X))) && match(FI, m_FNeg(m_Value(Y)))) {
370 // Intersect FMF from the fneg instructions and union those with the
371 // select.
373 FMF &= FI->getFastMathFlags();
374 FMF |= SI.getFastMathFlags();
375 Value *NewSel =
376 Builder.CreateSelect(Cond, X, Y, SI.getName() + ".v", &SI);
377 if (auto *NewSelI = dyn_cast<Instruction>(NewSel))
378 NewSelI->setFastMathFlags(FMF);
379 Instruction *NewFNeg = UnaryOperator::CreateFNeg(NewSel);
380 NewFNeg->setFastMathFlags(FMF);
381 return NewFNeg;
382 }
383
384 // Min/max intrinsic with a common operand can have the common operand
385 // pulled after the select. This is the same transform as below for binops,
386 // but specialized for intrinsic matching and without the restrictive uses
387 // clause.
388 auto *TII = dyn_cast<IntrinsicInst>(TI);
389 auto *FII = dyn_cast<IntrinsicInst>(FI);
390 if (TII && FII && TII->getIntrinsicID() == FII->getIntrinsicID()) {
391 if (match(TII, m_MaxOrMin(m_Value(), m_Value()))) {
392 if (Value *MatchOp = getCommonOp(TI, FI, true)) {
393 Value *NewSel =
394 Builder.CreateSelect(Cond, OtherOpT, OtherOpF, "minmaxop", &SI);
395 return CallInst::Create(TII->getCalledFunction(), {NewSel, MatchOp});
396 }
397 }
398
399 // select c, (ldexp v, e0), (ldexp v, e1) -> ldexp v, (select c, e0, e1)
400 // select c, (ldexp v0, e), (ldexp v1, e) -> ldexp (select c, v0, v1), e
401 //
402 // select c, (ldexp v0, e0), (ldexp v1, e1) ->
403 // ldexp (select c, v0, v1), (select c, e0, e1)
404 if (TII->getIntrinsicID() == Intrinsic::ldexp) {
405 Value *LdexpVal0 = TII->getArgOperand(0);
406 Value *LdexpExp0 = TII->getArgOperand(1);
407 Value *LdexpVal1 = FII->getArgOperand(0);
408 Value *LdexpExp1 = FII->getArgOperand(1);
409 if (LdexpExp0->getType() == LdexpExp1->getType()) {
410 FPMathOperator *SelectFPOp = cast<FPMathOperator>(&SI);
411 FastMathFlags FMF = cast<FPMathOperator>(TII)->getFastMathFlags();
412 FMF &= cast<FPMathOperator>(FII)->getFastMathFlags();
413 FMF |= SelectFPOp->getFastMathFlags();
414
415 Value *SelectVal = Builder.CreateSelect(Cond, LdexpVal0, LdexpVal1);
416 Value *SelectExp = Builder.CreateSelect(Cond, LdexpExp0, LdexpExp1);
417
418 CallInst *NewLdexp = Builder.CreateIntrinsic(
419 TII->getType(), Intrinsic::ldexp, {SelectVal, SelectExp});
420 NewLdexp->setFastMathFlags(FMF);
421 return replaceInstUsesWith(SI, NewLdexp);
422 }
423 }
424 }
425
426 // icmp with a common operand also can have the common operand
427 // pulled after the select.
428 CmpPredicate TPred, FPred;
429 if (match(TI, m_ICmp(TPred, m_Value(), m_Value())) &&
430 match(FI, m_ICmp(FPred, m_Value(), m_Value()))) {
431 // FIXME: Use CmpPredicate::getMatching here.
432 CmpInst::Predicate T = TPred, F = FPred;
433 if (T == F || T == ICmpInst::getSwappedCmpPredicate(F)) {
434 bool Swapped = T != F;
435 if (Value *MatchOp =
436 getCommonOp(TI, FI, ICmpInst::isEquality(TPred), Swapped)) {
437 Value *NewSel = Builder.CreateSelect(Cond, OtherOpT, OtherOpF,
438 SI.getName() + ".v", &SI);
439 return new ICmpInst(
440 MatchIsOpZero ? TPred : ICmpInst::getSwappedCmpPredicate(TPred),
441 MatchOp, NewSel);
442 }
443 }
444 }
445 }
446
447 // Only handle binary operators (including two-operand getelementptr) with
448 // one-use here. As with the cast case above, it may be possible to relax the
449 // one-use constraint, but that needs be examined carefully since it may not
450 // reduce the total number of instructions.
451 if (TI->getNumOperands() != 2 || FI->getNumOperands() != 2 ||
452 !TI->isSameOperationAs(FI) ||
453 (!isa<BinaryOperator>(TI) && !isa<GetElementPtrInst>(TI)) ||
454 !TI->hasOneUse() || !FI->hasOneUse())
455 return nullptr;
456
457 // Figure out if the operations have any operands in common.
458 Value *MatchOp = getCommonOp(TI, FI, TI->isCommutative());
459 if (!MatchOp)
460 return nullptr;
461
462 // If the select condition is a vector, the operands of the original select's
463 // operands also must be vectors. This may not be the case for getelementptr
464 // for example.
465 if (CondTy->isVectorTy() && (!OtherOpT->getType()->isVectorTy() ||
466 !OtherOpF->getType()->isVectorTy()))
467 return nullptr;
468
469 // If we are sinking div/rem after a select, we may need to freeze the
470 // condition because div/rem may induce immediate UB with a poison operand.
471 // For example, the following transform is not safe if Cond can ever be poison
472 // because we can replace poison with zero and then we have div-by-zero that
473 // didn't exist in the original code:
474 // Cond ? x/y : x/z --> x / (Cond ? y : z)
475 auto *BO = dyn_cast<BinaryOperator>(TI);
476 if (BO && BO->isIntDivRem() && !isGuaranteedNotToBePoison(Cond)) {
477 // A udiv/urem with a common divisor is safe because UB can only occur with
478 // div-by-zero, and that would be present in the original code.
479 if (BO->getOpcode() == Instruction::SDiv ||
480 BO->getOpcode() == Instruction::SRem || MatchIsOpZero)
482 }
483
484 // If we reach here, they do have operations in common.
485 Value *NewSI = Builder.CreateSelect(Cond, OtherOpT, OtherOpF,
486 SI.getName() + ".v", &SI);
487 Value *Op0 = MatchIsOpZero ? MatchOp : NewSI;
488 Value *Op1 = MatchIsOpZero ? NewSI : MatchOp;
489 if (auto *BO = dyn_cast<BinaryOperator>(TI)) {
490 BinaryOperator *NewBO = BinaryOperator::Create(BO->getOpcode(), Op0, Op1);
491 NewBO->copyIRFlags(TI);
492 NewBO->andIRFlags(FI);
493 return NewBO;
494 }
495 if (auto *TGEP = dyn_cast<GetElementPtrInst>(TI)) {
496 auto *FGEP = cast<GetElementPtrInst>(FI);
497 Type *ElementType = TGEP->getSourceElementType();
499 ElementType, Op0, Op1, TGEP->getNoWrapFlags() & FGEP->getNoWrapFlags());
500 }
501 llvm_unreachable("Expected BinaryOperator or GEP");
502 return nullptr;
503}
504
505static bool isSelect01(const APInt &C1I, const APInt &C2I) {
506 if (!C1I.isZero() && !C2I.isZero()) // One side must be zero.
507 return false;
508 return C1I.isOne() || C1I.isAllOnes() || C2I.isOne() || C2I.isAllOnes();
509}
510
511/// Try to fold the select into one of the operands to allow further
512/// optimization.
514 Value *FalseVal) {
515 // See the comment above getSelectFoldableOperands for a description of the
516 // transformation we are doing here.
517 auto TryFoldSelectIntoOp = [&](SelectInst &SI, Value *TrueVal,
518 Value *FalseVal,
519 bool Swapped) -> Instruction * {
520 auto *TVI = dyn_cast<BinaryOperator>(TrueVal);
521 if (!TVI || !TVI->hasOneUse() || isa<Constant>(FalseVal))
522 return nullptr;
523
524 unsigned SFO = getSelectFoldableOperands(TVI);
525 unsigned OpToFold = 0;
526 if ((SFO & 1) && FalseVal == TVI->getOperand(0))
527 OpToFold = 1;
528 else if ((SFO & 2) && FalseVal == TVI->getOperand(1))
529 OpToFold = 2;
530
531 if (!OpToFold)
532 return nullptr;
533
534 FastMathFlags FMF;
535 if (isa<FPMathOperator>(&SI))
536 FMF = SI.getFastMathFlags();
538 TVI->getOpcode(), TVI->getType(), true, FMF.noSignedZeros());
539 Value *OOp = TVI->getOperand(2 - OpToFold);
540 // Avoid creating select between 2 constants unless it's selecting
541 // between 0, 1 and -1.
542 const APInt *OOpC;
543 bool OOpIsAPInt = match(OOp, m_APInt(OOpC));
544 if (isa<Constant>(OOp) &&
545 (!OOpIsAPInt || !isSelect01(C->getUniqueInteger(), *OOpC)))
546 return nullptr;
547
548 // If the false value is a NaN then we have that the floating point math
549 // operation in the transformed code may not preserve the exact NaN
550 // bit-pattern -- e.g. `fadd sNaN, 0.0 -> qNaN`.
551 // This makes the transformation incorrect since the original program would
552 // have preserved the exact NaN bit-pattern.
553 // Avoid the folding if the false value might be a NaN.
554 if (isa<FPMathOperator>(&SI) &&
555 !computeKnownFPClass(FalseVal, FMF, fcNan, &SI).isKnownNeverNaN())
556 return nullptr;
557
558 Value *NewSel = Builder.CreateSelect(SI.getCondition(), Swapped ? C : OOp,
559 Swapped ? OOp : C, "", &SI);
560 if (isa<FPMathOperator>(&SI))
561 cast<Instruction>(NewSel)->setFastMathFlags(FMF);
562 NewSel->takeName(TVI);
563 BinaryOperator *BO =
564 BinaryOperator::Create(TVI->getOpcode(), FalseVal, NewSel);
565 BO->copyIRFlags(TVI);
566 if (isa<FPMathOperator>(&SI)) {
567 // Merge poison generating flags from the select.
568 BO->setHasNoNaNs(BO->hasNoNaNs() && FMF.noNaNs());
569 BO->setHasNoInfs(BO->hasNoInfs() && FMF.noInfs());
570 // Merge no-signed-zeros flag from the select.
571 // Otherwise we may produce zeros with different sign.
573 }
574 return BO;
575 };
576
577 if (Instruction *R = TryFoldSelectIntoOp(SI, TrueVal, FalseVal, false))
578 return R;
579
580 if (Instruction *R = TryFoldSelectIntoOp(SI, FalseVal, TrueVal, true))
581 return R;
582
583 return nullptr;
584}
585
586/// We want to turn:
587/// (select (icmp eq (and X, Y), 0), (and (lshr X, Z), 1), 1)
588/// into:
589/// zext (icmp ne i32 (and X, (or Y, (shl 1, Z))), 0)
590/// Note:
591/// Z may be 0 if lshr is missing.
592/// Worst-case scenario is that we will replace 5 instructions with 5 different
593/// instructions, but we got rid of select.
594static Instruction *foldSelectICmpAndAnd(Type *SelType, const ICmpInst *Cmp,
595 Value *TVal, Value *FVal,
596 InstCombiner::BuilderTy &Builder) {
597 if (!(Cmp->hasOneUse() && Cmp->getOperand(0)->hasOneUse() &&
598 Cmp->getPredicate() == ICmpInst::ICMP_EQ &&
599 match(Cmp->getOperand(1), m_Zero()) && match(FVal, m_One())))
600 return nullptr;
601
602 // The TrueVal has general form of: and %B, 1
603 Value *B;
604 if (!match(TVal, m_OneUse(m_And(m_Value(B), m_One()))))
605 return nullptr;
606
607 // Where %B may be optionally shifted: lshr %X, %Z.
608 Value *X, *Z;
609 const bool HasShift = match(B, m_OneUse(m_LShr(m_Value(X), m_Value(Z))));
610
611 // The shift must be valid.
612 // TODO: This restricts the fold to constant shift amounts. Is there a way to
613 // handle variable shifts safely? PR47012
614 if (HasShift &&
616 APInt(SelType->getScalarSizeInBits(),
617 SelType->getScalarSizeInBits()))))
618 return nullptr;
619
620 if (!HasShift)
621 X = B;
622
623 Value *Y;
624 if (!match(Cmp->getOperand(0), m_c_And(m_Specific(X), m_Value(Y))))
625 return nullptr;
626
627 // ((X & Y) == 0) ? ((X >> Z) & 1) : 1 --> (X & (Y | (1 << Z))) != 0
628 // ((X & Y) == 0) ? (X & 1) : 1 --> (X & (Y | 1)) != 0
629 Constant *One = ConstantInt::get(SelType, 1);
630 Value *MaskB = HasShift ? Builder.CreateShl(One, Z) : One;
631 Value *FullMask = Builder.CreateOr(Y, MaskB);
632 Value *MaskedX = Builder.CreateAnd(X, FullMask);
633 Value *ICmpNeZero = Builder.CreateIsNotNull(MaskedX);
634 return new ZExtInst(ICmpNeZero, SelType);
635}
636
637/// We want to turn:
638/// (select (icmp eq (and X, C1), 0), 0, (shl [nsw/nuw] X, C2));
639/// iff C1 is a mask and the number of its leading zeros is equal to C2
640/// into:
641/// shl X, C2
643 Value *FVal,
644 InstCombiner::BuilderTy &Builder) {
645 CmpPredicate Pred;
646 Value *AndVal;
647 if (!match(Cmp, m_ICmp(Pred, m_Value(AndVal), m_Zero())))
648 return nullptr;
649
650 if (Pred == ICmpInst::ICMP_NE) {
651 Pred = ICmpInst::ICMP_EQ;
652 std::swap(TVal, FVal);
653 }
654
655 Value *X;
656 const APInt *C2, *C1;
657 if (Pred != ICmpInst::ICMP_EQ ||
658 !match(AndVal, m_And(m_Value(X), m_APInt(C1))) ||
659 !match(TVal, m_Zero()) || !match(FVal, m_Shl(m_Specific(X), m_APInt(C2))))
660 return nullptr;
661
662 if (!C1->isMask() ||
663 C1->countLeadingZeros() != static_cast<unsigned>(C2->getZExtValue()))
664 return nullptr;
665
666 auto *FI = dyn_cast<Instruction>(FVal);
667 if (!FI)
668 return nullptr;
669
670 FI->setHasNoSignedWrap(false);
671 FI->setHasNoUnsignedWrap(false);
672 return FVal;
673}
674
675/// We want to turn:
676/// (select (icmp sgt x, C), lshr (X, Y), ashr (X, Y)); iff C s>= -1
677/// (select (icmp slt x, C), ashr (X, Y), lshr (X, Y)); iff C s>= 0
678/// into:
679/// ashr (X, Y)
680static Value *foldSelectICmpLshrAshr(const ICmpInst *IC, Value *TrueVal,
681 Value *FalseVal,
682 InstCombiner::BuilderTy &Builder) {
684 Value *CmpLHS = IC->getOperand(0);
685 Value *CmpRHS = IC->getOperand(1);
686 if (!CmpRHS->getType()->isIntOrIntVectorTy())
687 return nullptr;
688
689 Value *X, *Y;
690 unsigned Bitwidth = CmpRHS->getType()->getScalarSizeInBits();
691 if ((Pred != ICmpInst::ICMP_SGT ||
693 APInt::getAllOnes(Bitwidth)))) &&
694 (Pred != ICmpInst::ICMP_SLT ||
696 APInt::getZero(Bitwidth)))))
697 return nullptr;
698
699 // Canonicalize so that ashr is in FalseVal.
700 if (Pred == ICmpInst::ICMP_SLT)
701 std::swap(TrueVal, FalseVal);
702
703 if (match(TrueVal, m_LShr(m_Value(X), m_Value(Y))) &&
704 match(FalseVal, m_AShr(m_Specific(X), m_Specific(Y))) &&
705 match(CmpLHS, m_Specific(X))) {
706 const auto *Ashr = cast<Instruction>(FalseVal);
707 // if lshr is not exact and ashr is, this new ashr must not be exact.
708 bool IsExact = Ashr->isExact() && cast<Instruction>(TrueVal)->isExact();
709 return Builder.CreateAShr(X, Y, IC->getName(), IsExact);
710 }
711
712 return nullptr;
713}
714
715/// We want to turn:
716/// (select (icmp eq (and X, C1), 0), Y, (BinOp Y, C2))
717/// into:
718/// IF C2 u>= C1
719/// (BinOp Y, (shl (and X, C1), C3))
720/// ELSE
721/// (BinOp Y, (lshr (and X, C1), C3))
722/// iff:
723/// 0 on the RHS is the identity value (i.e add, xor, shl, etc...)
724/// C1 and C2 are both powers of 2
725/// where:
726/// IF C2 u>= C1
727/// C3 = Log(C2) - Log(C1)
728/// ELSE
729/// C3 = Log(C1) - Log(C2)
730///
731/// This transform handles cases where:
732/// 1. The icmp predicate is inverted
733/// 2. The select operands are reversed
734/// 3. The magnitude of C2 and C1 are flipped
735static Value *foldSelectICmpAndBinOp(const ICmpInst *IC, Value *TrueVal,
736 Value *FalseVal,
737 InstCombiner::BuilderTy &Builder) {
738 // Only handle integer compares. Also, if this is a vector select, we need a
739 // vector compare.
740 if (!TrueVal->getType()->isIntOrIntVectorTy() ||
741 TrueVal->getType()->isVectorTy() != IC->getType()->isVectorTy())
742 return nullptr;
743
744 Value *CmpLHS = IC->getOperand(0);
745 Value *CmpRHS = IC->getOperand(1);
746
747 unsigned C1Log;
748 bool NeedAnd = false;
749 CmpInst::Predicate Pred = IC->getPredicate();
750 if (IC->isEquality()) {
751 if (!match(CmpRHS, m_Zero()))
752 return nullptr;
753
754 const APInt *C1;
755 if (!match(CmpLHS, m_And(m_Value(), m_Power2(C1))))
756 return nullptr;
757
758 C1Log = C1->logBase2();
759 } else {
760 auto Res = decomposeBitTestICmp(CmpLHS, CmpRHS, Pred);
761 if (!Res || !Res->Mask.isPowerOf2())
762 return nullptr;
763
764 CmpLHS = Res->X;
765 Pred = Res->Pred;
766 C1Log = Res->Mask.logBase2();
767 NeedAnd = true;
768 }
769
770 Value *Y, *V = CmpLHS;
771 BinaryOperator *BinOp;
772 const APInt *C2;
773 bool NeedXor;
774 if (match(FalseVal, m_BinOp(m_Specific(TrueVal), m_Power2(C2)))) {
775 Y = TrueVal;
776 BinOp = cast<BinaryOperator>(FalseVal);
777 NeedXor = Pred == ICmpInst::ICMP_NE;
778 } else if (match(TrueVal, m_BinOp(m_Specific(FalseVal), m_Power2(C2)))) {
779 Y = FalseVal;
780 BinOp = cast<BinaryOperator>(TrueVal);
781 NeedXor = Pred == ICmpInst::ICMP_EQ;
782 } else {
783 return nullptr;
784 }
785
786 // Check that 0 on RHS is identity value for this binop.
787 auto *IdentityC =
789 /*AllowRHSConstant*/ true);
790 if (IdentityC == nullptr || !IdentityC->isNullValue())
791 return nullptr;
792
793 unsigned C2Log = C2->logBase2();
794
795 bool NeedShift = C1Log != C2Log;
796 bool NeedZExtTrunc = Y->getType()->getScalarSizeInBits() !=
797 V->getType()->getScalarSizeInBits();
798
799 // Make sure we don't create more instructions than we save.
800 if ((NeedShift + NeedXor + NeedZExtTrunc + NeedAnd) >
801 (IC->hasOneUse() + BinOp->hasOneUse()))
802 return nullptr;
803
804 if (NeedAnd) {
805 // Insert the AND instruction on the input to the truncate.
806 APInt C1 = APInt::getOneBitSet(V->getType()->getScalarSizeInBits(), C1Log);
807 V = Builder.CreateAnd(V, ConstantInt::get(V->getType(), C1));
808 }
809
810 if (C2Log > C1Log) {
811 V = Builder.CreateZExtOrTrunc(V, Y->getType());
812 V = Builder.CreateShl(V, C2Log - C1Log);
813 } else if (C1Log > C2Log) {
814 V = Builder.CreateLShr(V, C1Log - C2Log);
815 V = Builder.CreateZExtOrTrunc(V, Y->getType());
816 } else
817 V = Builder.CreateZExtOrTrunc(V, Y->getType());
818
819 if (NeedXor)
820 V = Builder.CreateXor(V, *C2);
821
822 return Builder.CreateBinOp(BinOp->getOpcode(), Y, V);
823}
824
825/// Canonicalize a set or clear of a masked set of constant bits to
826/// select-of-constants form.
828 InstCombiner::BuilderTy &Builder) {
829 Value *Cond = Sel.getCondition();
830 Value *T = Sel.getTrueValue();
831 Value *F = Sel.getFalseValue();
832 Type *Ty = Sel.getType();
833 Value *X;
834 const APInt *NotC, *C;
835
836 // Cond ? (X & ~C) : (X | C) --> (X & ~C) | (Cond ? 0 : C)
837 if (match(T, m_And(m_Value(X), m_APInt(NotC))) &&
838 match(F, m_OneUse(m_Or(m_Specific(X), m_APInt(C)))) && *NotC == ~(*C)) {
840 Constant *OrC = ConstantInt::get(Ty, *C);
841 Value *NewSel = Builder.CreateSelect(Cond, Zero, OrC, "masksel", &Sel);
842 return BinaryOperator::CreateOr(T, NewSel);
843 }
844
845 // Cond ? (X | C) : (X & ~C) --> (X & ~C) | (Cond ? C : 0)
846 if (match(F, m_And(m_Value(X), m_APInt(NotC))) &&
847 match(T, m_OneUse(m_Or(m_Specific(X), m_APInt(C)))) && *NotC == ~(*C)) {
849 Constant *OrC = ConstantInt::get(Ty, *C);
850 Value *NewSel = Builder.CreateSelect(Cond, OrC, Zero, "masksel", &Sel);
851 return BinaryOperator::CreateOr(F, NewSel);
852 }
853
854 return nullptr;
855}
856
857// select (x == 0), 0, x * y --> freeze(y) * x
858// select (y == 0), 0, x * y --> freeze(x) * y
859// select (x == 0), undef, x * y --> freeze(y) * x
860// select (x == undef), 0, x * y --> freeze(y) * x
861// Usage of mul instead of 0 will make the result more poisonous,
862// so the operand that was not checked in the condition should be frozen.
863// The latter folding is applied only when a constant compared with x is
864// is a vector consisting of 0 and undefs. If a constant compared with x
865// is a scalar undefined value or undefined vector then an expression
866// should be already folded into a constant.
868 auto *CondVal = SI.getCondition();
869 auto *TrueVal = SI.getTrueValue();
870 auto *FalseVal = SI.getFalseValue();
871 Value *X, *Y;
872 CmpPredicate Predicate;
873
874 // Assuming that constant compared with zero is not undef (but it may be
875 // a vector with some undef elements). Otherwise (when a constant is undef)
876 // the select expression should be already simplified.
877 if (!match(CondVal, m_ICmp(Predicate, m_Value(X), m_Zero())) ||
878 !ICmpInst::isEquality(Predicate))
879 return nullptr;
880
881 if (Predicate == ICmpInst::ICMP_NE)
882 std::swap(TrueVal, FalseVal);
883
884 // Check that TrueVal is a constant instead of matching it with m_Zero()
885 // to handle the case when it is a scalar undef value or a vector containing
886 // non-zero elements that are masked by undef elements in the compare
887 // constant.
888 auto *TrueValC = dyn_cast<Constant>(TrueVal);
889 if (TrueValC == nullptr ||
890 !match(FalseVal, m_c_Mul(m_Specific(X), m_Value(Y))) ||
891 !isa<Instruction>(FalseVal))
892 return nullptr;
893
894 auto *ZeroC = cast<Constant>(cast<Instruction>(CondVal)->getOperand(1));
895 auto *MergedC = Constant::mergeUndefsWith(TrueValC, ZeroC);
896 // If X is compared with 0 then TrueVal could be either zero or undef.
897 // m_Zero match vectors containing some undef elements, but for scalars
898 // m_Undef should be used explicitly.
899 if (!match(MergedC, m_Zero()) && !match(MergedC, m_Undef()))
900 return nullptr;
901
902 auto *FalseValI = cast<Instruction>(FalseVal);
903 auto *FrY = IC.InsertNewInstBefore(new FreezeInst(Y, Y->getName() + ".fr"),
904 FalseValI->getIterator());
905 IC.replaceOperand(*FalseValI, FalseValI->getOperand(0) == Y ? 0 : 1, FrY);
906 return IC.replaceInstUsesWith(SI, FalseValI);
907}
908
909/// Transform patterns such as (a > b) ? a - b : 0 into usub.sat(a, b).
910/// There are 8 commuted/swapped variants of this pattern.
912 const Value *TrueVal,
913 const Value *FalseVal,
914 InstCombiner::BuilderTy &Builder) {
915 ICmpInst::Predicate Pred = ICI->getPredicate();
916 Value *A = ICI->getOperand(0);
917 Value *B = ICI->getOperand(1);
918
919 // (b > a) ? 0 : a - b -> (b <= a) ? a - b : 0
920 // (a == 0) ? 0 : a - 1 -> (a != 0) ? a - 1 : 0
921 if (match(TrueVal, m_Zero())) {
923 std::swap(TrueVal, FalseVal);
924 }
925
926 if (!match(FalseVal, m_Zero()))
927 return nullptr;
928
929 // ugt 0 is canonicalized to ne 0 and requires special handling
930 // (a != 0) ? a + -1 : 0 -> usub.sat(a, 1)
931 if (Pred == ICmpInst::ICMP_NE) {
932 if (match(B, m_Zero()) && match(TrueVal, m_Add(m_Specific(A), m_AllOnes())))
933 return Builder.CreateBinaryIntrinsic(Intrinsic::usub_sat, A,
934 ConstantInt::get(A->getType(), 1));
935 return nullptr;
936 }
937
938 if (!ICmpInst::isUnsigned(Pred))
939 return nullptr;
940
941 if (Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_ULT) {
942 // (b < a) ? a - b : 0 -> (a > b) ? a - b : 0
943 std::swap(A, B);
945 }
946
947 assert((Pred == ICmpInst::ICMP_UGE || Pred == ICmpInst::ICMP_UGT) &&
948 "Unexpected isUnsigned predicate!");
949
950 // Ensure the sub is of the form:
951 // (a > b) ? a - b : 0 -> usub.sat(a, b)
952 // (a > b) ? b - a : 0 -> -usub.sat(a, b)
953 // Checking for both a-b and a+(-b) as a constant.
954 bool IsNegative = false;
955 const APInt *C;
956 if (match(TrueVal, m_Sub(m_Specific(B), m_Specific(A))) ||
957 (match(A, m_APInt(C)) &&
958 match(TrueVal, m_Add(m_Specific(B), m_SpecificInt(-*C)))))
959 IsNegative = true;
960 else if (!match(TrueVal, m_Sub(m_Specific(A), m_Specific(B))) &&
961 !(match(B, m_APInt(C)) &&
962 match(TrueVal, m_Add(m_Specific(A), m_SpecificInt(-*C)))))
963 return nullptr;
964
965 // If we are adding a negate and the sub and icmp are used anywhere else, we
966 // would end up with more instructions.
967 if (IsNegative && !TrueVal->hasOneUse() && !ICI->hasOneUse())
968 return nullptr;
969
970 // (a > b) ? a - b : 0 -> usub.sat(a, b)
971 // (a > b) ? b - a : 0 -> -usub.sat(a, b)
972 Value *Result = Builder.CreateBinaryIntrinsic(Intrinsic::usub_sat, A, B);
973 if (IsNegative)
974 Result = Builder.CreateNeg(Result);
975 return Result;
976}
977
979 InstCombiner::BuilderTy &Builder) {
980 if (!Cmp->hasOneUse())
981 return nullptr;
982
983 // Match unsigned saturated add with constant.
984 Value *Cmp0 = Cmp->getOperand(0);
985 Value *Cmp1 = Cmp->getOperand(1);
986 ICmpInst::Predicate Pred = Cmp->getPredicate();
987 Value *X;
988 const APInt *C;
989
990 // Match unsigned saturated add of 2 variables with an unnecessary 'not'.
991 // There are 8 commuted variants.
992 // Canonicalize -1 (saturated result) to true value of the select.
993 if (match(FVal, m_AllOnes())) {
994 std::swap(TVal, FVal);
995 Pred = CmpInst::getInversePredicate(Pred);
996 }
997 if (!match(TVal, m_AllOnes()))
998 return nullptr;
999
1000 // uge -1 is canonicalized to eq -1 and requires special handling
1001 // (a == -1) ? -1 : a + 1 -> uadd.sat(a, 1)
1002 if (Pred == ICmpInst::ICMP_EQ) {
1003 if (match(FVal, m_Add(m_Specific(Cmp0), m_One())) &&
1004 match(Cmp1, m_AllOnes())) {
1005 return Builder.CreateBinaryIntrinsic(
1006 Intrinsic::uadd_sat, Cmp0, ConstantInt::get(Cmp0->getType(), 1));
1007 }
1008 return nullptr;
1009 }
1010
1011 if ((Pred == ICmpInst::ICMP_UGE || Pred == ICmpInst::ICMP_UGT) &&
1012 match(FVal, m_Add(m_Specific(Cmp0), m_APIntAllowPoison(C))) &&
1013 match(Cmp1, m_SpecificIntAllowPoison(~*C))) {
1014 // (X u> ~C) ? -1 : (X + C) --> uadd.sat(X, C)
1015 // (X u>= ~C)? -1 : (X + C) --> uadd.sat(X, C)
1016 return Builder.CreateBinaryIntrinsic(Intrinsic::uadd_sat, Cmp0,
1017 ConstantInt::get(Cmp0->getType(), *C));
1018 }
1019
1020 // Negative one does not work here because X u> -1 ? -1, X + -1 is not a
1021 // saturated add.
1022 if (Pred == ICmpInst::ICMP_UGT &&
1023 match(FVal, m_Add(m_Specific(Cmp0), m_APIntAllowPoison(C))) &&
1024 match(Cmp1, m_SpecificIntAllowPoison(~*C - 1)) && !C->isAllOnes()) {
1025 // (X u> ~C - 1) ? -1 : (X + C) --> uadd.sat(X, C)
1026 return Builder.CreateBinaryIntrinsic(Intrinsic::uadd_sat, Cmp0,
1027 ConstantInt::get(Cmp0->getType(), *C));
1028 }
1029
1030 // Zero does not work here because X u>= 0 ? -1 : X -> is always -1, which is
1031 // not a saturated add.
1032 if (Pred == ICmpInst::ICMP_UGE &&
1033 match(FVal, m_Add(m_Specific(Cmp0), m_APIntAllowPoison(C))) &&
1034 match(Cmp1, m_SpecificIntAllowPoison(-*C)) && !C->isZero()) {
1035 // (X u >= -C) ? -1 : (X + C) --> uadd.sat(X, C)
1036 return Builder.CreateBinaryIntrinsic(Intrinsic::uadd_sat, Cmp0,
1037 ConstantInt::get(Cmp0->getType(), *C));
1038 }
1039
1040 // Canonicalize predicate to less-than or less-or-equal-than.
1041 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE) {
1042 std::swap(Cmp0, Cmp1);
1043 Pred = CmpInst::getSwappedPredicate(Pred);
1044 }
1045 if (Pred != ICmpInst::ICMP_ULT && Pred != ICmpInst::ICMP_ULE)
1046 return nullptr;
1047
1048 // Match unsigned saturated add of 2 variables with an unnecessary 'not'.
1049 // Strictness of the comparison is irrelevant.
1050 Value *Y;
1051 if (match(Cmp0, m_Not(m_Value(X))) &&
1052 match(FVal, m_c_Add(m_Specific(X), m_Value(Y))) && Y == Cmp1) {
1053 // (~X u< Y) ? -1 : (X + Y) --> uadd.sat(X, Y)
1054 // (~X u< Y) ? -1 : (Y + X) --> uadd.sat(X, Y)
1055 return Builder.CreateBinaryIntrinsic(Intrinsic::uadd_sat, X, Y);
1056 }
1057 // The 'not' op may be included in the sum but not the compare.
1058 // Strictness of the comparison is irrelevant.
1059 X = Cmp0;
1060 Y = Cmp1;
1062 // (X u< Y) ? -1 : (~X + Y) --> uadd.sat(~X, Y)
1063 // (X u< Y) ? -1 : (Y + ~X) --> uadd.sat(Y, ~X)
1064 BinaryOperator *BO = cast<BinaryOperator>(FVal);
1065 return Builder.CreateBinaryIntrinsic(
1066 Intrinsic::uadd_sat, BO->getOperand(0), BO->getOperand(1));
1067 }
1068 // The overflow may be detected via the add wrapping round.
1069 // This is only valid for strict comparison!
1070 if (Pred == ICmpInst::ICMP_ULT &&
1071 match(Cmp0, m_c_Add(m_Specific(Cmp1), m_Value(Y))) &&
1072 match(FVal, m_c_Add(m_Specific(Cmp1), m_Specific(Y)))) {
1073 // ((X + Y) u< X) ? -1 : (X + Y) --> uadd.sat(X, Y)
1074 // ((X + Y) u< Y) ? -1 : (X + Y) --> uadd.sat(X, Y)
1075 return Builder.CreateBinaryIntrinsic(Intrinsic::uadd_sat, Cmp1, Y);
1076 }
1077
1078 return nullptr;
1079}
1080
1081/// Try to match patterns with select and subtract as absolute difference.
1082static Value *foldAbsDiff(ICmpInst *Cmp, Value *TVal, Value *FVal,
1083 InstCombiner::BuilderTy &Builder) {
1084 auto *TI = dyn_cast<Instruction>(TVal);
1085 auto *FI = dyn_cast<Instruction>(FVal);
1086 if (!TI || !FI)
1087 return nullptr;
1088
1089 // Normalize predicate to gt/lt rather than ge/le.
1090 ICmpInst::Predicate Pred = Cmp->getStrictPredicate();
1091 Value *A = Cmp->getOperand(0);
1092 Value *B = Cmp->getOperand(1);
1093
1094 // Normalize "A - B" as the true value of the select.
1095 if (match(FI, m_Sub(m_Specific(A), m_Specific(B)))) {
1096 std::swap(FI, TI);
1097 Pred = ICmpInst::getSwappedPredicate(Pred);
1098 }
1099
1100 // With any pair of no-wrap subtracts:
1101 // (A > B) ? (A - B) : (B - A) --> abs(A - B)
1102 if (Pred == CmpInst::ICMP_SGT &&
1103 match(TI, m_Sub(m_Specific(A), m_Specific(B))) &&
1104 match(FI, m_Sub(m_Specific(B), m_Specific(A))) &&
1105 (TI->hasNoSignedWrap() || TI->hasNoUnsignedWrap()) &&
1106 (FI->hasNoSignedWrap() || FI->hasNoUnsignedWrap())) {
1107 // The remaining subtract is not "nuw" any more.
1108 // If there's one use of the subtract (no other use than the use we are
1109 // about to replace), then we know that the sub is "nsw" in this context
1110 // even if it was only "nuw" before. If there's another use, then we can't
1111 // add "nsw" to the existing instruction because it may not be safe in the
1112 // other user's context.
1113 TI->setHasNoUnsignedWrap(false);
1114 if (!TI->hasNoSignedWrap())
1115 TI->setHasNoSignedWrap(TI->hasOneUse());
1116 return Builder.CreateBinaryIntrinsic(Intrinsic::abs, TI, Builder.getTrue());
1117 }
1118
1119 return nullptr;
1120}
1121
1122/// Fold the following code sequence:
1123/// \code
1124/// int a = ctlz(x & -x);
1125// x ? 31 - a : a;
1126// // or
1127// x ? 31 - a : 32;
1128/// \code
1129///
1130/// into:
1131/// cttz(x)
1132static Instruction *foldSelectCtlzToCttz(ICmpInst *ICI, Value *TrueVal,
1133 Value *FalseVal,
1134 InstCombiner::BuilderTy &Builder) {
1135 unsigned BitWidth = TrueVal->getType()->getScalarSizeInBits();
1136 if (!ICI->isEquality() || !match(ICI->getOperand(1), m_Zero()))
1137 return nullptr;
1138
1139 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
1140 std::swap(TrueVal, FalseVal);
1141
1142 Value *Ctlz;
1143 if (!match(FalseVal,
1144 m_Xor(m_Value(Ctlz), m_SpecificInt(BitWidth - 1))))
1145 return nullptr;
1146
1147 if (!match(Ctlz, m_Intrinsic<Intrinsic::ctlz>()))
1148 return nullptr;
1149
1150 if (TrueVal != Ctlz && !match(TrueVal, m_SpecificInt(BitWidth)))
1151 return nullptr;
1152
1153 Value *X = ICI->getOperand(0);
1154 auto *II = cast<IntrinsicInst>(Ctlz);
1155 if (!match(II->getOperand(0), m_c_And(m_Specific(X), m_Neg(m_Specific(X)))))
1156 return nullptr;
1157
1159 II->getModule(), Intrinsic::cttz, II->getType());
1160 return CallInst::Create(F, {X, II->getArgOperand(1)});
1161}
1162
1163/// Attempt to fold a cttz/ctlz followed by a icmp plus select into a single
1164/// call to cttz/ctlz with flag 'is_zero_poison' cleared.
1165///
1166/// For example, we can fold the following code sequence:
1167/// \code
1168/// %0 = tail call i32 @llvm.cttz.i32(i32 %x, i1 true)
1169/// %1 = icmp ne i32 %x, 0
1170/// %2 = select i1 %1, i32 %0, i32 32
1171/// \code
1172///
1173/// into:
1174/// %0 = tail call i32 @llvm.cttz.i32(i32 %x, i1 false)
1175static Value *foldSelectCttzCtlz(ICmpInst *ICI, Value *TrueVal, Value *FalseVal,
1176 InstCombinerImpl &IC) {
1177 ICmpInst::Predicate Pred = ICI->getPredicate();
1178 Value *CmpLHS = ICI->getOperand(0);
1179 Value *CmpRHS = ICI->getOperand(1);
1180
1181 // Check if the select condition compares a value for equality.
1182 if (!ICI->isEquality())
1183 return nullptr;
1184
1185 Value *SelectArg = FalseVal;
1186 Value *ValueOnZero = TrueVal;
1187 if (Pred == ICmpInst::ICMP_NE)
1188 std::swap(SelectArg, ValueOnZero);
1189
1190 // Skip zero extend/truncate.
1191 Value *Count = nullptr;
1192 if (!match(SelectArg, m_ZExt(m_Value(Count))) &&
1193 !match(SelectArg, m_Trunc(m_Value(Count))))
1194 Count = SelectArg;
1195
1196 // Check that 'Count' is a call to intrinsic cttz/ctlz. Also check that the
1197 // input to the cttz/ctlz is used as LHS for the compare instruction.
1198 Value *X;
1199 if (!match(Count, m_Intrinsic<Intrinsic::cttz>(m_Value(X))) &&
1200 !match(Count, m_Intrinsic<Intrinsic::ctlz>(m_Value(X))))
1201 return nullptr;
1202
1203 // (X == 0) ? BitWidth : ctz(X)
1204 // (X == -1) ? BitWidth : ctz(~X)
1205 if ((X != CmpLHS || !match(CmpRHS, m_Zero())) &&
1206 (!match(X, m_Not(m_Specific(CmpLHS))) || !match(CmpRHS, m_AllOnes())))
1207 return nullptr;
1208
1209 IntrinsicInst *II = cast<IntrinsicInst>(Count);
1210
1211 // Check if the value propagated on zero is a constant number equal to the
1212 // sizeof in bits of 'Count'.
1213 unsigned SizeOfInBits = Count->getType()->getScalarSizeInBits();
1214 if (match(ValueOnZero, m_SpecificInt(SizeOfInBits))) {
1215 // Explicitly clear the 'is_zero_poison' flag. It's always valid to go from
1216 // true to false on this flag, so we can replace it for all users.
1217 II->setArgOperand(1, ConstantInt::getFalse(II->getContext()));
1218 // A range annotation on the intrinsic may no longer be valid.
1219 II->dropPoisonGeneratingAnnotations();
1220 IC.addToWorklist(II);
1221 return SelectArg;
1222 }
1223
1224 // The ValueOnZero is not the bitwidth. But if the cttz/ctlz (and optional
1225 // zext/trunc) have one use (ending at the select), the cttz/ctlz result will
1226 // not be used if the input is zero. Relax to 'zero is poison' for that case.
1227 if (II->hasOneUse() && SelectArg->hasOneUse() &&
1228 !match(II->getArgOperand(1), m_One()))
1229 II->setArgOperand(1, ConstantInt::getTrue(II->getContext()));
1230
1231 return nullptr;
1232}
1233
1234static Value *canonicalizeSPF(ICmpInst &Cmp, Value *TrueVal, Value *FalseVal,
1235 InstCombinerImpl &IC) {
1236 Value *LHS, *RHS;
1237 // TODO: What to do with pointer min/max patterns?
1238 if (!TrueVal->getType()->isIntOrIntVectorTy())
1239 return nullptr;
1240
1242 matchDecomposedSelectPattern(&Cmp, TrueVal, FalseVal, LHS, RHS).Flavor;
1243 if (SPF == SelectPatternFlavor::SPF_ABS ||
1245 if (!Cmp.hasOneUse() && !RHS->hasOneUse())
1246 return nullptr; // TODO: Relax this restriction.
1247
1248 // Note that NSW flag can only be propagated for normal, non-negated abs!
1249 bool IntMinIsPoison = SPF == SelectPatternFlavor::SPF_ABS &&
1250 match(RHS, m_NSWNeg(m_Specific(LHS)));
1251 Constant *IntMinIsPoisonC =
1252 ConstantInt::get(Type::getInt1Ty(Cmp.getContext()), IntMinIsPoison);
1253 Value *Abs =
1254 IC.Builder.CreateBinaryIntrinsic(Intrinsic::abs, LHS, IntMinIsPoisonC);
1255
1257 return IC.Builder.CreateNeg(Abs); // Always without NSW flag!
1258 return Abs;
1259 }
1260
1262 Intrinsic::ID IntrinsicID = getMinMaxIntrinsic(SPF);
1263 return IC.Builder.CreateBinaryIntrinsic(IntrinsicID, LHS, RHS);
1264 }
1265
1266 return nullptr;
1267}
1268
1270 unsigned Depth) {
1271 // Conservatively limit replacement to two instructions upwards.
1272 if (Depth == 2)
1273 return false;
1274
1275 assert(!isa<Constant>(Old) && "Only replace non-constant values");
1276
1277 auto *I = dyn_cast<Instruction>(V);
1278 if (!I || !I->hasOneUse() ||
1280 return false;
1281
1282 // Forbid potentially lane-crossing instructions.
1283 if (Old->getType()->isVectorTy() && !isNotCrossLaneOperation(I))
1284 return false;
1285
1286 bool Changed = false;
1287 for (Use &U : I->operands()) {
1288 if (U == Old) {
1289 replaceUse(U, New);
1290 Worklist.add(I);
1291 Changed = true;
1292 } else {
1293 Changed |= replaceInInstruction(U, Old, New, Depth + 1);
1294 }
1295 }
1296 return Changed;
1297}
1298
1299/// If we have a select with an equality comparison, then we know the value in
1300/// one of the arms of the select. See if substituting this value into an arm
1301/// and simplifying the result yields the same value as the other arm.
1302///
1303/// To make this transform safe, we must drop poison-generating flags
1304/// (nsw, etc) if we simplified to a binop because the select may be guarding
1305/// that poison from propagating. If the existing binop already had no
1306/// poison-generating flags, then this transform can be done by instsimplify.
1307///
1308/// Consider:
1309/// %cmp = icmp eq i32 %x, 2147483647
1310/// %add = add nsw i32 %x, 1
1311/// %sel = select i1 %cmp, i32 -2147483648, i32 %add
1312///
1313/// We can't replace %sel with %add unless we strip away the flags.
1314/// TODO: Wrapping flags could be preserved in some cases with better analysis.
1316 CmpInst &Cmp) {
1317 // Canonicalize the pattern to an equivalence on the predicate by swapping the
1318 // select operands.
1319 Value *TrueVal = Sel.getTrueValue(), *FalseVal = Sel.getFalseValue();
1320 bool Swapped = false;
1321 if (Cmp.isEquivalence(/*Invert=*/true)) {
1322 std::swap(TrueVal, FalseVal);
1323 Swapped = true;
1324 } else if (!Cmp.isEquivalence()) {
1325 return nullptr;
1326 }
1327
1328 Value *CmpLHS = Cmp.getOperand(0), *CmpRHS = Cmp.getOperand(1);
1329 auto ReplaceOldOpWithNewOp = [&](Value *OldOp,
1330 Value *NewOp) -> Instruction * {
1331 // In X == Y ? f(X) : Z, try to evaluate f(Y) and replace the operand.
1332 // Take care to avoid replacing X == Y ? X : Z with X == Y ? Y : Z, as that
1333 // would lead to an infinite replacement cycle.
1334 // If we will be able to evaluate f(Y) to a constant, we can allow undef,
1335 // otherwise Y cannot be undef as we might pick different values for undef
1336 // in the cmp and in f(Y).
1337 if (TrueVal == OldOp && (isa<Constant>(OldOp) || !isa<Constant>(NewOp)))
1338 return nullptr;
1339
1340 if (Value *V = simplifyWithOpReplaced(TrueVal, OldOp, NewOp, SQ,
1341 /* AllowRefinement=*/true)) {
1342 // Need some guarantees about the new simplified op to ensure we don't inf
1343 // loop.
1344 // If we simplify to a constant, replace if we aren't creating new undef.
1345 if (match(V, m_ImmConstant()) &&
1346 isGuaranteedNotToBeUndef(V, SQ.AC, &Sel, &DT))
1347 return replaceOperand(Sel, Swapped ? 2 : 1, V);
1348
1349 // If NewOp is a constant and OldOp is not replace iff NewOp doesn't
1350 // contain and undef elements.
1351 if (match(NewOp, m_ImmConstant()) || NewOp == V) {
1352 if (isGuaranteedNotToBeUndef(NewOp, SQ.AC, &Sel, &DT))
1353 return replaceOperand(Sel, Swapped ? 2 : 1, V);
1354 return nullptr;
1355 }
1356 }
1357
1358 // Even if TrueVal does not simplify, we can directly replace a use of
1359 // CmpLHS with CmpRHS, as long as the instruction is not used anywhere
1360 // else and is safe to speculatively execute (we may end up executing it
1361 // with different operands, which should not cause side-effects or trigger
1362 // undefined behavior). Only do this if CmpRHS is a constant, as
1363 // profitability is not clear for other cases.
1364 if (OldOp == CmpLHS && match(NewOp, m_ImmConstant()) &&
1365 !match(OldOp, m_Constant()) &&
1366 isGuaranteedNotToBeUndef(NewOp, SQ.AC, &Sel, &DT))
1367 if (replaceInInstruction(TrueVal, OldOp, NewOp))
1368 return &Sel;
1369 return nullptr;
1370 };
1371
1372 if (Instruction *R = ReplaceOldOpWithNewOp(CmpLHS, CmpRHS))
1373 return R;
1374 if (Instruction *R = ReplaceOldOpWithNewOp(CmpRHS, CmpLHS))
1375 return R;
1376
1377 auto *FalseInst = dyn_cast<Instruction>(FalseVal);
1378 if (!FalseInst)
1379 return nullptr;
1380
1381 // InstSimplify already performed this fold if it was possible subject to
1382 // current poison-generating flags. Check whether dropping poison-generating
1383 // flags enables the transform.
1384
1385 // Try each equivalence substitution possibility.
1386 // We have an 'EQ' comparison, so the select's false value will propagate.
1387 // Example:
1388 // (X == 42) ? 43 : (X + 1) --> (X == 42) ? (X + 1) : (X + 1) --> X + 1
1390 if (simplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, SQ,
1391 /* AllowRefinement */ false,
1392 &DropFlags) == TrueVal ||
1393 simplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, SQ,
1394 /* AllowRefinement */ false,
1395 &DropFlags) == TrueVal) {
1396 for (Instruction *I : DropFlags) {
1397 I->dropPoisonGeneratingAnnotations();
1398 Worklist.add(I);
1399 }
1400
1401 return replaceInstUsesWith(Sel, FalseVal);
1402 }
1403
1404 return nullptr;
1405}
1406
1407/// Fold the following code sequence:
1408/// \code
1409/// %XeqZ = icmp eq i64 %X, %Z
1410/// %YeqZ = icmp eq i64 %Y, %Z
1411/// %XeqY = icmp eq i64 %X, %Y
1412/// %not.YeqZ = xor i1 %YeqZ, true
1413/// %and = select i1 %not.YeqZ, i1 %XeqY, i1 false
1414/// %equal = select i1 %XeqZ, i1 %YeqZ, i1 %and
1415/// \code
1416///
1417/// into:
1418/// %equal = icmp eq i64 %X, %Y
1420 Value *X, *Y, *Z;
1421 Value *XeqY, *XeqZ = Sel.getCondition(), *YeqZ = Sel.getTrueValue();
1422
1424 return nullptr;
1425
1426 if (!match(YeqZ,
1428 std::swap(X, Z);
1429
1430 if (!match(YeqZ,
1432 return nullptr;
1433
1434 if (!match(Sel.getFalseValue(),
1435 m_c_LogicalAnd(m_Not(m_Specific(YeqZ)), m_Value(XeqY))))
1436 return nullptr;
1437
1438 if (!match(XeqY,
1440 return nullptr;
1441
1442 cast<ICmpInst>(XeqY)->setSameSign(false);
1443 return replaceInstUsesWith(Sel, XeqY);
1444}
1445
1446// See if this is a pattern like:
1447// %old_cmp1 = icmp slt i32 %x, C2
1448// %old_replacement = select i1 %old_cmp1, i32 %target_low, i32 %target_high
1449// %old_x_offseted = add i32 %x, C1
1450// %old_cmp0 = icmp ult i32 %old_x_offseted, C0
1451// %r = select i1 %old_cmp0, i32 %x, i32 %old_replacement
1452// This can be rewritten as more canonical pattern:
1453// %new_cmp1 = icmp slt i32 %x, -C1
1454// %new_cmp2 = icmp sge i32 %x, C0-C1
1455// %new_clamped_low = select i1 %new_cmp1, i32 %target_low, i32 %x
1456// %r = select i1 %new_cmp2, i32 %target_high, i32 %new_clamped_low
1457// Iff -C1 s<= C2 s<= C0-C1
1458// Also ULT predicate can also be UGT iff C0 != -1 (+invert result)
1459// SLT predicate can also be SGT iff C2 != INT_MAX (+invert res.)
1460static Value *canonicalizeClampLike(SelectInst &Sel0, ICmpInst &Cmp0,
1461 InstCombiner::BuilderTy &Builder,
1462 InstCombiner &IC) {
1463 Value *X = Sel0.getTrueValue();
1464 Value *Sel1 = Sel0.getFalseValue();
1465
1466 // First match the condition of the outermost select.
1467 // Said condition must be one-use.
1468 if (!Cmp0.hasOneUse())
1469 return nullptr;
1470 ICmpInst::Predicate Pred0 = Cmp0.getPredicate();
1471 Value *Cmp00 = Cmp0.getOperand(0);
1472 Constant *C0;
1473 if (!match(Cmp0.getOperand(1),
1475 return nullptr;
1476
1477 if (!isa<SelectInst>(Sel1)) {
1478 Pred0 = ICmpInst::getInversePredicate(Pred0);
1479 std::swap(X, Sel1);
1480 }
1481
1482 // Canonicalize Cmp0 into ult or uge.
1483 // FIXME: we shouldn't care about lanes that are 'undef' in the end?
1484 switch (Pred0) {
1487 // Although icmp ult %x, 0 is an unusual thing to try and should generally
1488 // have been simplified, it does not verify with undef inputs so ensure we
1489 // are not in a strange state.
1490 if (!match(C0, m_SpecificInt_ICMP(
1493 return nullptr;
1494 break; // Great!
1497 // We want to canonicalize it to 'ult' or 'uge', so we'll need to increment
1498 // C0, which again means it must not have any all-ones elements.
1499 if (!match(C0,
1503 return nullptr; // Can't do, have all-ones element[s].
1505 C0 = InstCombiner::AddOne(C0);
1506 break;
1507 default:
1508 return nullptr; // Unknown predicate.
1509 }
1510
1511 // Now that we've canonicalized the ICmp, we know the X we expect;
1512 // the select in other hand should be one-use.
1513 if (!Sel1->hasOneUse())
1514 return nullptr;
1515
1516 // If the types do not match, look through any truncs to the underlying
1517 // instruction.
1518 if (Cmp00->getType() != X->getType() && X->hasOneUse())
1520
1521 // We now can finish matching the condition of the outermost select:
1522 // it should either be the X itself, or an addition of some constant to X.
1523 Constant *C1;
1524 if (Cmp00 == X)
1525 C1 = ConstantInt::getNullValue(X->getType());
1526 else if (!match(Cmp00,
1529 return nullptr;
1530
1531 Value *Cmp1;
1532 CmpPredicate Pred1;
1533 Constant *C2;
1534 Value *ReplacementLow, *ReplacementHigh;
1535 if (!match(Sel1, m_Select(m_Value(Cmp1), m_Value(ReplacementLow),
1536 m_Value(ReplacementHigh))) ||
1537 !match(Cmp1,
1538 m_ICmp(Pred1, m_Specific(X),
1540 return nullptr;
1541
1542 if (!Cmp1->hasOneUse() && (Cmp00 == X || !Cmp00->hasOneUse()))
1543 return nullptr; // Not enough one-use instructions for the fold.
1544 // FIXME: this restriction could be relaxed if Cmp1 can be reused as one of
1545 // two comparisons we'll need to build.
1546
1547 // Canonicalize Cmp1 into the form we expect.
1548 // FIXME: we shouldn't care about lanes that are 'undef' in the end?
1549 switch (Pred1) {
1551 break;
1553 // We'd have to increment C2 by one, and for that it must not have signed
1554 // max element, but then it would have been canonicalized to 'slt' before
1555 // we get here. So we can't do anything useful with 'sle'.
1556 return nullptr;
1558 // We want to canonicalize it to 'slt', so we'll need to increment C2,
1559 // which again means it must not have any signed max elements.
1560 if (!match(C2,
1563 C2->getType()->getScalarSizeInBits()))))
1564 return nullptr; // Can't do, have signed max element[s].
1565 C2 = InstCombiner::AddOne(C2);
1566 [[fallthrough]];
1568 // Also non-canonical, but here we don't need to change C2,
1569 // so we don't have any restrictions on C2, so we can just handle it.
1571 std::swap(ReplacementLow, ReplacementHigh);
1572 break;
1573 default:
1574 return nullptr; // Unknown predicate.
1575 }
1577 "Unexpected predicate type.");
1578
1579 // The thresholds of this clamp-like pattern.
1580 auto *ThresholdLowIncl = ConstantExpr::getNeg(C1);
1581 auto *ThresholdHighExcl = ConstantExpr::getSub(C0, C1);
1582
1585 "Unexpected predicate type.");
1586 if (Pred0 == ICmpInst::Predicate::ICMP_UGE)
1587 std::swap(ThresholdLowIncl, ThresholdHighExcl);
1588
1589 // The fold has a precondition 1: C2 s>= ThresholdLow
1590 auto *Precond1 = ConstantFoldCompareInstOperands(
1591 ICmpInst::Predicate::ICMP_SGE, C2, ThresholdLowIncl, IC.getDataLayout());
1592 if (!Precond1 || !match(Precond1, m_One()))
1593 return nullptr;
1594 // The fold has a precondition 2: C2 s<= ThresholdHigh
1595 auto *Precond2 = ConstantFoldCompareInstOperands(
1596 ICmpInst::Predicate::ICMP_SLE, C2, ThresholdHighExcl, IC.getDataLayout());
1597 if (!Precond2 || !match(Precond2, m_One()))
1598 return nullptr;
1599
1600 // If we are matching from a truncated input, we need to sext the
1601 // ReplacementLow and ReplacementHigh values. Only do the transform if they
1602 // are free to extend due to being constants.
1603 if (X->getType() != Sel0.getType()) {
1604 Constant *LowC, *HighC;
1605 if (!match(ReplacementLow, m_ImmConstant(LowC)) ||
1606 !match(ReplacementHigh, m_ImmConstant(HighC)))
1607 return nullptr;
1608 const DataLayout &DL = Sel0.getDataLayout();
1609 ReplacementLow =
1610 ConstantFoldCastOperand(Instruction::SExt, LowC, X->getType(), DL);
1611 ReplacementHigh =
1612 ConstantFoldCastOperand(Instruction::SExt, HighC, X->getType(), DL);
1613 assert(ReplacementLow && ReplacementHigh &&
1614 "Constant folding of ImmConstant cannot fail");
1615 }
1616
1617 // All good, finally emit the new pattern.
1618 Value *ShouldReplaceLow = Builder.CreateICmpSLT(X, ThresholdLowIncl);
1619 Value *ShouldReplaceHigh = Builder.CreateICmpSGE(X, ThresholdHighExcl);
1620 Value *MaybeReplacedLow =
1621 Builder.CreateSelect(ShouldReplaceLow, ReplacementLow, X);
1622
1623 // Create the final select. If we looked through a truncate above, we will
1624 // need to retruncate the result.
1625 Value *MaybeReplacedHigh = Builder.CreateSelect(
1626 ShouldReplaceHigh, ReplacementHigh, MaybeReplacedLow);
1627 return Builder.CreateTrunc(MaybeReplacedHigh, Sel0.getType());
1628}
1629
1630// If we have
1631// %cmp = icmp [canonical predicate] i32 %x, C0
1632// %r = select i1 %cmp, i32 %y, i32 C1
1633// Where C0 != C1 and %x may be different from %y, see if the constant that we
1634// will have if we flip the strictness of the predicate (i.e. without changing
1635// the result) is identical to the C1 in select. If it matches we can change
1636// original comparison to one with swapped predicate, reuse the constant,
1637// and swap the hands of select.
1638static Instruction *
1639tryToReuseConstantFromSelectInComparison(SelectInst &Sel, ICmpInst &Cmp,
1640 InstCombinerImpl &IC) {
1641 CmpPredicate Pred;
1642 Value *X;
1643 Constant *C0;
1644 if (!match(&Cmp, m_OneUse(m_ICmp(
1645 Pred, m_Value(X),
1647 return nullptr;
1648
1649 // If comparison predicate is non-relational, we won't be able to do anything.
1650 if (ICmpInst::isEquality(Pred))
1651 return nullptr;
1652
1653 // If comparison predicate is non-canonical, then we certainly won't be able
1654 // to make it canonical; canonicalizeCmpWithConstant() already tried.
1656 return nullptr;
1657
1658 // If the [input] type of comparison and select type are different, lets abort
1659 // for now. We could try to compare constants with trunc/[zs]ext though.
1660 if (C0->getType() != Sel.getType())
1661 return nullptr;
1662
1663 // ULT with 'add' of a constant is canonical. See foldICmpAddConstant().
1664 // FIXME: Are there more magic icmp predicate+constant pairs we must avoid?
1665 // Or should we just abandon this transform entirely?
1666 if (Pred == CmpInst::ICMP_ULT && match(X, m_Add(m_Value(), m_Constant())))
1667 return nullptr;
1668
1669
1670 Value *SelVal0, *SelVal1; // We do not care which one is from where.
1671 match(&Sel, m_Select(m_Value(), m_Value(SelVal0), m_Value(SelVal1)));
1672 // At least one of these values we are selecting between must be a constant
1673 // else we'll never succeed.
1674 if (!match(SelVal0, m_AnyIntegralConstant()) &&
1675 !match(SelVal1, m_AnyIntegralConstant()))
1676 return nullptr;
1677
1678 // Does this constant C match any of the `select` values?
1679 auto MatchesSelectValue = [SelVal0, SelVal1](Constant *C) {
1680 return C->isElementWiseEqual(SelVal0) || C->isElementWiseEqual(SelVal1);
1681 };
1682
1683 // If C0 *already* matches true/false value of select, we are done.
1684 if (MatchesSelectValue(C0))
1685 return nullptr;
1686
1687 // Check the constant we'd have with flipped-strictness predicate.
1688 auto FlippedStrictness =
1690 if (!FlippedStrictness)
1691 return nullptr;
1692
1693 // If said constant doesn't match either, then there is no hope,
1694 if (!MatchesSelectValue(FlippedStrictness->second))
1695 return nullptr;
1696
1697 // It matched! Lets insert the new comparison just before select.
1699 IC.Builder.SetInsertPoint(&Sel);
1700
1701 Pred = ICmpInst::getSwappedPredicate(Pred); // Yes, swapped.
1702 Value *NewCmp = IC.Builder.CreateICmp(Pred, X, FlippedStrictness->second,
1703 Cmp.getName() + ".inv");
1704 IC.replaceOperand(Sel, 0, NewCmp);
1705 Sel.swapValues();
1706 Sel.swapProfMetadata();
1707
1708 return &Sel;
1709}
1710
1711static Instruction *foldSelectZeroOrOnes(ICmpInst *Cmp, Value *TVal,
1712 Value *FVal,
1713 InstCombiner::BuilderTy &Builder) {
1714 if (!Cmp->hasOneUse())
1715 return nullptr;
1716
1717 const APInt *CmpC;
1718 if (!match(Cmp->getOperand(1), m_APIntAllowPoison(CmpC)))
1719 return nullptr;
1720
1721 // (X u< 2) ? -X : -1 --> sext (X != 0)
1722 Value *X = Cmp->getOperand(0);
1723 if (Cmp->getPredicate() == ICmpInst::ICMP_ULT && *CmpC == 2 &&
1724 match(TVal, m_Neg(m_Specific(X))) && match(FVal, m_AllOnes()))
1725 return new SExtInst(Builder.CreateIsNotNull(X), TVal->getType());
1726
1727 // (X u> 1) ? -1 : -X --> sext (X != 0)
1728 if (Cmp->getPredicate() == ICmpInst::ICMP_UGT && *CmpC == 1 &&
1729 match(FVal, m_Neg(m_Specific(X))) && match(TVal, m_AllOnes()))
1730 return new SExtInst(Builder.CreateIsNotNull(X), TVal->getType());
1731
1732 return nullptr;
1733}
1734
1735static Value *foldSelectInstWithICmpConst(SelectInst &SI, ICmpInst *ICI,
1736 InstCombiner::BuilderTy &Builder) {
1737 const APInt *CmpC;
1738 Value *V;
1739 CmpPredicate Pred;
1740 if (!match(ICI, m_ICmp(Pred, m_Value(V), m_APInt(CmpC))))
1741 return nullptr;
1742
1743 // Match clamp away from min/max value as a max/min operation.
1744 Value *TVal = SI.getTrueValue();
1745 Value *FVal = SI.getFalseValue();
1746 if (Pred == ICmpInst::ICMP_EQ && V == FVal) {
1747 // (V == UMIN) ? UMIN+1 : V --> umax(V, UMIN+1)
1748 if (CmpC->isMinValue() && match(TVal, m_SpecificInt(*CmpC + 1)))
1749 return Builder.CreateBinaryIntrinsic(Intrinsic::umax, V, TVal);
1750 // (V == UMAX) ? UMAX-1 : V --> umin(V, UMAX-1)
1751 if (CmpC->isMaxValue() && match(TVal, m_SpecificInt(*CmpC - 1)))
1752 return Builder.CreateBinaryIntrinsic(Intrinsic::umin, V, TVal);
1753 // (V == SMIN) ? SMIN+1 : V --> smax(V, SMIN+1)
1754 if (CmpC->isMinSignedValue() && match(TVal, m_SpecificInt(*CmpC + 1)))
1755 return Builder.CreateBinaryIntrinsic(Intrinsic::smax, V, TVal);
1756 // (V == SMAX) ? SMAX-1 : V --> smin(V, SMAX-1)
1757 if (CmpC->isMaxSignedValue() && match(TVal, m_SpecificInt(*CmpC - 1)))
1758 return Builder.CreateBinaryIntrinsic(Intrinsic::smin, V, TVal);
1759 }
1760
1761 BinaryOperator *BO;
1762 const APInt *C;
1763 CmpInst::Predicate CPred;
1764 if (match(&SI, m_Select(m_Specific(ICI), m_APInt(C), m_BinOp(BO))))
1765 CPred = ICI->getPredicate();
1766 else if (match(&SI, m_Select(m_Specific(ICI), m_BinOp(BO), m_APInt(C))))
1767 CPred = ICI->getInversePredicate();
1768 else
1769 return nullptr;
1770
1771 const APInt *BinOpC;
1772 if (!match(BO, m_BinOp(m_Specific(V), m_APInt(BinOpC))))
1773 return nullptr;
1774
1776 .binaryOp(BO->getOpcode(), *BinOpC);
1777 if (R == *C) {
1779 return BO;
1780 }
1781 return nullptr;
1782}
1783
1784/// `A == MIN_INT ? B != MIN_INT : A < B` --> `A < B`
1785/// `A == MAX_INT ? B != MAX_INT : A > B` --> `A > B`
1786static Instruction *foldSelectWithExtremeEqCond(Value *CmpLHS, Value *CmpRHS,
1787 Value *TrueVal,
1788 Value *FalseVal) {
1789 Type *Ty = CmpLHS->getType();
1790
1791 if (Ty->isPtrOrPtrVectorTy())
1792 return nullptr;
1793
1794 CmpPredicate Pred;
1795 Value *B;
1796
1797 if (!match(FalseVal, m_c_ICmp(Pred, m_Specific(CmpLHS), m_Value(B))))
1798 return nullptr;
1799
1800 Value *TValRHS;
1802 m_Value(TValRHS))))
1803 return nullptr;
1804
1805 APInt C;
1806 unsigned BitWidth = Ty->getScalarSizeInBits();
1807
1808 if (ICmpInst::isLT(Pred)) {
1811 } else if (ICmpInst::isGT(Pred)) {
1814 } else {
1815 return nullptr;
1816 }
1817
1818 if (!match(CmpRHS, m_SpecificInt(C)) || !match(TValRHS, m_SpecificInt(C)))
1819 return nullptr;
1820
1821 return new ICmpInst(Pred, CmpLHS, B);
1822}
1823
1824static Instruction *foldSelectICmpEq(SelectInst &SI, ICmpInst *ICI,
1825 InstCombinerImpl &IC) {
1826 ICmpInst::Predicate Pred = ICI->getPredicate();
1827 if (!ICmpInst::isEquality(Pred))
1828 return nullptr;
1829
1830 Value *TrueVal = SI.getTrueValue();
1831 Value *FalseVal = SI.getFalseValue();
1832 Value *CmpLHS = ICI->getOperand(0);
1833 Value *CmpRHS = ICI->getOperand(1);
1834
1835 if (Pred == ICmpInst::ICMP_NE)
1836 std::swap(TrueVal, FalseVal);
1837
1838 if (Instruction *Res =
1839 foldSelectWithExtremeEqCond(CmpLHS, CmpRHS, TrueVal, FalseVal))
1840 return Res;
1841
1842 // Transform (X == C) ? X : Y -> (X == C) ? C : Y
1843 // specific handling for Bitwise operation.
1844 // x&y -> (x|y) ^ (x^y) or (x|y) & ~(x^y)
1845 // x|y -> (x&y) | (x^y) or (x&y) ^ (x^y)
1846 // x^y -> (x|y) ^ (x&y) or (x|y) & ~(x&y)
1847 Value *X, *Y;
1848 if (!match(CmpLHS, m_BitwiseLogic(m_Value(X), m_Value(Y))) ||
1850 return nullptr;
1851
1852 const unsigned AndOps = Instruction::And, OrOps = Instruction::Or,
1853 XorOps = Instruction::Xor, NoOps = 0;
1854 enum NotMask { None = 0, NotInner, NotRHS };
1855
1856 auto matchFalseVal = [&](unsigned OuterOpc, unsigned InnerOpc,
1857 unsigned NotMask) {
1858 auto matchInner = m_c_BinOp(InnerOpc, m_Specific(X), m_Specific(Y));
1859 if (OuterOpc == NoOps)
1860 return match(CmpRHS, m_Zero()) && match(FalseVal, matchInner);
1861
1862 if (NotMask == NotInner) {
1863 return match(FalseVal, m_c_BinOp(OuterOpc, m_NotForbidPoison(matchInner),
1864 m_Specific(CmpRHS)));
1865 } else if (NotMask == NotRHS) {
1866 return match(FalseVal, m_c_BinOp(OuterOpc, matchInner,
1867 m_NotForbidPoison(m_Specific(CmpRHS))));
1868 } else {
1869 return match(FalseVal,
1870 m_c_BinOp(OuterOpc, matchInner, m_Specific(CmpRHS)));
1871 }
1872 };
1873
1874 // (X&Y)==C ? X|Y : X^Y -> (X^Y)|C : X^Y or (X^Y)^ C : X^Y
1875 // (X&Y)==C ? X^Y : X|Y -> (X|Y)^C : X|Y or (X|Y)&~C : X|Y
1876 if (match(CmpLHS, m_And(m_Value(X), m_Value(Y)))) {
1877 if (match(TrueVal, m_c_Or(m_Specific(X), m_Specific(Y)))) {
1878 // (X&Y)==C ? X|Y : (X^Y)|C -> (X^Y)|C : (X^Y)|C -> (X^Y)|C
1879 // (X&Y)==C ? X|Y : (X^Y)^C -> (X^Y)^C : (X^Y)^C -> (X^Y)^C
1880 if (matchFalseVal(OrOps, XorOps, None) ||
1881 matchFalseVal(XorOps, XorOps, None))
1882 return IC.replaceInstUsesWith(SI, FalseVal);
1883 } else if (match(TrueVal, m_c_Xor(m_Specific(X), m_Specific(Y)))) {
1884 // (X&Y)==C ? X^Y : (X|Y)^ C -> (X|Y)^ C : (X|Y)^ C -> (X|Y)^ C
1885 // (X&Y)==C ? X^Y : (X|Y)&~C -> (X|Y)&~C : (X|Y)&~C -> (X|Y)&~C
1886 if (matchFalseVal(XorOps, OrOps, None) ||
1887 matchFalseVal(AndOps, OrOps, NotRHS))
1888 return IC.replaceInstUsesWith(SI, FalseVal);
1889 }
1890 }
1891
1892 // (X|Y)==C ? X&Y : X^Y -> (X^Y)^C : X^Y or ~(X^Y)&C : X^Y
1893 // (X|Y)==C ? X^Y : X&Y -> (X&Y)^C : X&Y or ~(X&Y)&C : X&Y
1894 if (match(CmpLHS, m_Or(m_Value(X), m_Value(Y)))) {
1895 if (match(TrueVal, m_c_And(m_Specific(X), m_Specific(Y)))) {
1896 // (X|Y)==C ? X&Y: (X^Y)^C -> (X^Y)^C: (X^Y)^C -> (X^Y)^C
1897 // (X|Y)==C ? X&Y:~(X^Y)&C ->~(X^Y)&C:~(X^Y)&C -> ~(X^Y)&C
1898 if (matchFalseVal(XorOps, XorOps, None) ||
1899 matchFalseVal(AndOps, XorOps, NotInner))
1900 return IC.replaceInstUsesWith(SI, FalseVal);
1901 } else if (match(TrueVal, m_c_Xor(m_Specific(X), m_Specific(Y)))) {
1902 // (X|Y)==C ? X^Y : (X&Y)^C -> (X&Y)^C : (X&Y)^C -> (X&Y)^C
1903 // (X|Y)==C ? X^Y :~(X&Y)&C -> ~(X&Y)&C :~(X&Y)&C -> ~(X&Y)&C
1904 if (matchFalseVal(XorOps, AndOps, None) ||
1905 matchFalseVal(AndOps, AndOps, NotInner))
1906 return IC.replaceInstUsesWith(SI, FalseVal);
1907 }
1908 }
1909
1910 // (X^Y)==C ? X&Y : X|Y -> (X|Y)^C : X|Y or (X|Y)&~C : X|Y
1911 // (X^Y)==C ? X|Y : X&Y -> (X&Y)|C : X&Y or (X&Y)^ C : X&Y
1912 if (match(CmpLHS, m_Xor(m_Value(X), m_Value(Y)))) {
1913 if ((match(TrueVal, m_c_And(m_Specific(X), m_Specific(Y))))) {
1914 // (X^Y)==C ? X&Y : (X|Y)^C -> (X|Y)^C
1915 // (X^Y)==C ? X&Y : (X|Y)&~C -> (X|Y)&~C
1916 if (matchFalseVal(XorOps, OrOps, None) ||
1917 matchFalseVal(AndOps, OrOps, NotRHS))
1918 return IC.replaceInstUsesWith(SI, FalseVal);
1919 } else if (match(TrueVal, m_c_Or(m_Specific(X), m_Specific(Y)))) {
1920 // (X^Y)==C ? (X|Y) : (X&Y)|C -> (X&Y)|C
1921 // (X^Y)==C ? (X|Y) : (X&Y)^C -> (X&Y)^C
1922 if (matchFalseVal(OrOps, AndOps, None) ||
1923 matchFalseVal(XorOps, AndOps, None))
1924 return IC.replaceInstUsesWith(SI, FalseVal);
1925 }
1926 }
1927
1928 return nullptr;
1929}
1930
1931/// Fold `X Pred C1 ? X BOp C2 : C1 BOp C2` to `min/max(X, C1) BOp C2`.
1932/// This allows for better canonicalization.
1933static Value *foldSelectWithConstOpToBinOp(ICmpInst *Cmp, Value *TrueVal,
1934 Value *FalseVal,
1935 IRBuilderBase &Builder) {
1936 BinaryOperator *BOp;
1937 Constant *C1, *C2, *C3;
1938 Value *X;
1940
1941 if (!match(Cmp, m_ICmp(Predicate, m_Value(X), m_Constant(C1))))
1942 return nullptr;
1943
1944 if (!ICmpInst::isRelational(Predicate))
1945 return nullptr;
1946
1947 if (match(TrueVal, m_Constant())) {
1948 std::swap(FalseVal, TrueVal);
1950 }
1951
1952 if (!match(TrueVal, m_BinOp(BOp)) || !match(FalseVal, m_Constant(C3)))
1953 return nullptr;
1954
1955 unsigned Opcode = BOp->getOpcode();
1956
1957 // This fold causes some regressions and is primarily intended for
1958 // add and sub. So we early exit for div and rem to minimize the
1959 // regressions.
1960 if (Instruction::isIntDivRem(Opcode))
1961 return nullptr;
1962
1963 if (!match(BOp, m_OneUse(m_BinOp(m_Specific(X), m_Constant(C2)))))
1964 return nullptr;
1965
1966 Value *RHS;
1968 const DataLayout &DL = BOp->getDataLayout();
1969 auto Flipped =
1971
1972 if (C3 == ConstantFoldBinaryOpOperands(Opcode, C1, C2, DL)) {
1973 SPF = getSelectPattern(Predicate).Flavor;
1974 RHS = C1;
1975 } else if (Flipped && C3 == ConstantFoldBinaryOpOperands(
1976 Opcode, Flipped->second, C2, DL)) {
1977 SPF = getSelectPattern(Flipped->first).Flavor;
1978 RHS = Flipped->second;
1979 } else {
1980 return nullptr;
1981 }
1982
1983 Intrinsic::ID IntrinsicID = getMinMaxIntrinsic(SPF);
1984 Value *Intrinsic = Builder.CreateBinaryIntrinsic(IntrinsicID, X, RHS);
1985 return Builder.CreateBinOp(BOp->getOpcode(), Intrinsic, C2);
1986}
1987
1988/// Visit a SelectInst that has an ICmpInst as its first operand.
1990 ICmpInst *ICI) {
1991 if (Value *V =
1992 canonicalizeSPF(*ICI, SI.getTrueValue(), SI.getFalseValue(), *this))
1993 return replaceInstUsesWith(SI, V);
1994
1995 if (Value *V = foldSelectInstWithICmpConst(SI, ICI, Builder))
1996 return replaceInstUsesWith(SI, V);
1997
1998 if (Value *V = canonicalizeClampLike(SI, *ICI, Builder, *this))
1999 return replaceInstUsesWith(SI, V);
2000
2001 if (Instruction *NewSel =
2002 tryToReuseConstantFromSelectInComparison(SI, *ICI, *this))
2003 return NewSel;
2004
2005 if (Value *V = foldSelectICmpAnd(SI, ICI, Builder))
2006 return replaceInstUsesWith(SI, V);
2007
2008 // NOTE: if we wanted to, this is where to detect integer MIN/MAX
2009 bool Changed = false;
2010 Value *TrueVal = SI.getTrueValue();
2011 Value *FalseVal = SI.getFalseValue();
2012 ICmpInst::Predicate Pred = ICI->getPredicate();
2013 Value *CmpLHS = ICI->getOperand(0);
2014 Value *CmpRHS = ICI->getOperand(1);
2015
2016 if (Instruction *NewSel = foldSelectICmpEq(SI, ICI, *this))
2017 return NewSel;
2018
2019 // Canonicalize a signbit condition to use zero constant by swapping:
2020 // (CmpLHS > -1) ? TV : FV --> (CmpLHS < 0) ? FV : TV
2021 // To avoid conflicts (infinite loops) with other canonicalizations, this is
2022 // not applied with any constant select arm.
2023 if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, m_AllOnes()) &&
2024 !match(TrueVal, m_Constant()) && !match(FalseVal, m_Constant()) &&
2025 ICI->hasOneUse()) {
2028 Value *IsNeg = Builder.CreateIsNeg(CmpLHS, ICI->getName());
2029 replaceOperand(SI, 0, IsNeg);
2030 SI.swapValues();
2031 SI.swapProfMetadata();
2032 return &SI;
2033 }
2034
2035 if (Instruction *V =
2036 foldSelectICmpAndAnd(SI.getType(), ICI, TrueVal, FalseVal, Builder))
2037 return V;
2038
2039 if (Value *V = foldSelectICmpAndZeroShl(ICI, TrueVal, FalseVal, Builder))
2040 return replaceInstUsesWith(SI, V);
2041
2042 if (Instruction *V = foldSelectCtlzToCttz(ICI, TrueVal, FalseVal, Builder))
2043 return V;
2044
2045 if (Instruction *V = foldSelectZeroOrOnes(ICI, TrueVal, FalseVal, Builder))
2046 return V;
2047
2048 if (Value *V = foldSelectICmpAndBinOp(ICI, TrueVal, FalseVal, Builder))
2049 return replaceInstUsesWith(SI, V);
2050
2051 if (Value *V = foldSelectICmpLshrAshr(ICI, TrueVal, FalseVal, Builder))
2052 return replaceInstUsesWith(SI, V);
2053
2054 if (Value *V = foldSelectCttzCtlz(ICI, TrueVal, FalseVal, *this))
2055 return replaceInstUsesWith(SI, V);
2056
2057 if (Value *V = canonicalizeSaturatedSubtract(ICI, TrueVal, FalseVal, Builder))
2058 return replaceInstUsesWith(SI, V);
2059
2060 if (Value *V = canonicalizeSaturatedAdd(ICI, TrueVal, FalseVal, Builder))
2061 return replaceInstUsesWith(SI, V);
2062
2063 if (Value *V = foldAbsDiff(ICI, TrueVal, FalseVal, Builder))
2064 return replaceInstUsesWith(SI, V);
2065
2066 if (Value *V = foldSelectWithConstOpToBinOp(ICI, TrueVal, FalseVal, Builder))
2067 return replaceInstUsesWith(SI, V);
2068
2069 return Changed ? &SI : nullptr;
2070}
2071
2072/// We have an SPF (e.g. a min or max) of an SPF of the form:
2073/// SPF2(SPF1(A, B), C)
2076 Value *B, Instruction &Outer,
2078 Value *C) {
2079 if (Outer.getType() != Inner->getType())
2080 return nullptr;
2081
2082 if (C == A || C == B) {
2083 // MAX(MAX(A, B), B) -> MAX(A, B)
2084 // MIN(MIN(a, b), a) -> MIN(a, b)
2085 // TODO: This could be done in instsimplify.
2086 if (SPF1 == SPF2 && SelectPatternResult::isMinOrMax(SPF1))
2087 return replaceInstUsesWith(Outer, Inner);
2088 }
2089
2090 return nullptr;
2091}
2092
2093/// Turn select C, (X + Y), (X - Y) --> (X + (select C, Y, (-Y))).
2094/// This is even legal for FP.
2095static Instruction *foldAddSubSelect(SelectInst &SI,
2096 InstCombiner::BuilderTy &Builder) {
2097 Value *CondVal = SI.getCondition();
2098 Value *TrueVal = SI.getTrueValue();
2099 Value *FalseVal = SI.getFalseValue();
2100 auto *TI = dyn_cast<Instruction>(TrueVal);
2101 auto *FI = dyn_cast<Instruction>(FalseVal);
2102 if (!TI || !FI || !TI->hasOneUse() || !FI->hasOneUse())
2103 return nullptr;
2104
2105 Instruction *AddOp = nullptr, *SubOp = nullptr;
2106 if ((TI->getOpcode() == Instruction::Sub &&
2107 FI->getOpcode() == Instruction::Add) ||
2108 (TI->getOpcode() == Instruction::FSub &&
2109 FI->getOpcode() == Instruction::FAdd)) {
2110 AddOp = FI;
2111 SubOp = TI;
2112 } else if ((FI->getOpcode() == Instruction::Sub &&
2113 TI->getOpcode() == Instruction::Add) ||
2114 (FI->getOpcode() == Instruction::FSub &&
2115 TI->getOpcode() == Instruction::FAdd)) {
2116 AddOp = TI;
2117 SubOp = FI;
2118 }
2119
2120 if (AddOp) {
2121 Value *OtherAddOp = nullptr;
2122 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
2123 OtherAddOp = AddOp->getOperand(1);
2124 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
2125 OtherAddOp = AddOp->getOperand(0);
2126 }
2127
2128 if (OtherAddOp) {
2129 // So at this point we know we have (Y -> OtherAddOp):
2130 // select C, (add X, Y), (sub X, Z)
2131 Value *NegVal; // Compute -Z
2132 if (SI.getType()->isFPOrFPVectorTy()) {
2133 NegVal = Builder.CreateFNeg(SubOp->getOperand(1));
2134 if (Instruction *NegInst = dyn_cast<Instruction>(NegVal)) {
2136 Flags &= SubOp->getFastMathFlags();
2137 NegInst->setFastMathFlags(Flags);
2138 }
2139 } else {
2140 NegVal = Builder.CreateNeg(SubOp->getOperand(1));
2141 }
2142
2143 Value *NewTrueOp = OtherAddOp;
2144 Value *NewFalseOp = NegVal;
2145 if (AddOp != TI)
2146 std::swap(NewTrueOp, NewFalseOp);
2147 Value *NewSel = Builder.CreateSelect(CondVal, NewTrueOp, NewFalseOp,
2148 SI.getName() + ".p", &SI);
2149
2150 if (SI.getType()->isFPOrFPVectorTy()) {
2151 Instruction *RI =
2152 BinaryOperator::CreateFAdd(SubOp->getOperand(0), NewSel);
2153
2155 Flags &= SubOp->getFastMathFlags();
2156 RI->setFastMathFlags(Flags);
2157 return RI;
2158 } else
2159 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
2160 }
2161 }
2162 return nullptr;
2163}
2164
2165/// Turn X + Y overflows ? -1 : X + Y -> uadd_sat X, Y
2166/// And X - Y overflows ? 0 : X - Y -> usub_sat X, Y
2167/// Along with a number of patterns similar to:
2168/// X + Y overflows ? (X < 0 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y
2169/// X - Y overflows ? (X > 0 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y
2170static Instruction *
2171foldOverflowingAddSubSelect(SelectInst &SI, InstCombiner::BuilderTy &Builder) {
2172 Value *CondVal = SI.getCondition();
2173 Value *TrueVal = SI.getTrueValue();
2174 Value *FalseVal = SI.getFalseValue();
2175
2177 if (!match(CondVal, m_ExtractValue<1>(m_WithOverflowInst(II))) ||
2178 !match(FalseVal, m_ExtractValue<0>(m_Specific(II))))
2179 return nullptr;
2180
2181 Value *X = II->getLHS();
2182 Value *Y = II->getRHS();
2183
2184 auto IsSignedSaturateLimit = [&](Value *Limit, bool IsAdd) {
2185 Type *Ty = Limit->getType();
2186
2187 CmpPredicate Pred;
2188 Value *TrueVal, *FalseVal, *Op;
2189 const APInt *C;
2190 if (!match(Limit, m_Select(m_ICmp(Pred, m_Value(Op), m_APInt(C)),
2191 m_Value(TrueVal), m_Value(FalseVal))))
2192 return false;
2193
2194 auto IsZeroOrOne = [](const APInt &C) { return C.isZero() || C.isOne(); };
2195 auto IsMinMax = [&](Value *Min, Value *Max) {
2198 return match(Min, m_SpecificInt(MinVal)) &&
2199 match(Max, m_SpecificInt(MaxVal));
2200 };
2201
2202 if (Op != X && Op != Y)
2203 return false;
2204
2205 if (IsAdd) {
2206 // X + Y overflows ? (X <s 0 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y
2207 // X + Y overflows ? (X <s 1 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y
2208 // X + Y overflows ? (Y <s 0 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y
2209 // X + Y overflows ? (Y <s 1 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y
2210 if (Pred == ICmpInst::ICMP_SLT && IsZeroOrOne(*C) &&
2211 IsMinMax(TrueVal, FalseVal))
2212 return true;
2213 // X + Y overflows ? (X >s 0 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y
2214 // X + Y overflows ? (X >s -1 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y
2215 // X + Y overflows ? (Y >s 0 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y
2216 // X + Y overflows ? (Y >s -1 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y
2217 if (Pred == ICmpInst::ICMP_SGT && IsZeroOrOne(*C + 1) &&
2218 IsMinMax(FalseVal, TrueVal))
2219 return true;
2220 } else {
2221 // X - Y overflows ? (X <s 0 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y
2222 // X - Y overflows ? (X <s -1 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y
2223 if (Op == X && Pred == ICmpInst::ICMP_SLT && IsZeroOrOne(*C + 1) &&
2224 IsMinMax(TrueVal, FalseVal))
2225 return true;
2226 // X - Y overflows ? (X >s -1 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y
2227 // X - Y overflows ? (X >s -2 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y
2228 if (Op == X && Pred == ICmpInst::ICMP_SGT && IsZeroOrOne(*C + 2) &&
2229 IsMinMax(FalseVal, TrueVal))
2230 return true;
2231 // X - Y overflows ? (Y <s 0 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y
2232 // X - Y overflows ? (Y <s 1 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y
2233 if (Op == Y && Pred == ICmpInst::ICMP_SLT && IsZeroOrOne(*C) &&
2234 IsMinMax(FalseVal, TrueVal))
2235 return true;
2236 // X - Y overflows ? (Y >s 0 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y
2237 // X - Y overflows ? (Y >s -1 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y
2238 if (Op == Y && Pred == ICmpInst::ICMP_SGT && IsZeroOrOne(*C + 1) &&
2239 IsMinMax(TrueVal, FalseVal))
2240 return true;
2241 }
2242
2243 return false;
2244 };
2245
2246 Intrinsic::ID NewIntrinsicID;
2247 if (II->getIntrinsicID() == Intrinsic::uadd_with_overflow &&
2248 match(TrueVal, m_AllOnes()))
2249 // X + Y overflows ? -1 : X + Y -> uadd_sat X, Y
2250 NewIntrinsicID = Intrinsic::uadd_sat;
2251 else if (II->getIntrinsicID() == Intrinsic::usub_with_overflow &&
2252 match(TrueVal, m_Zero()))
2253 // X - Y overflows ? 0 : X - Y -> usub_sat X, Y
2254 NewIntrinsicID = Intrinsic::usub_sat;
2255 else if (II->getIntrinsicID() == Intrinsic::sadd_with_overflow &&
2256 IsSignedSaturateLimit(TrueVal, /*IsAdd=*/true))
2257 // X + Y overflows ? (X <s 0 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y
2258 // X + Y overflows ? (X <s 1 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y
2259 // X + Y overflows ? (X >s 0 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y
2260 // X + Y overflows ? (X >s -1 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y
2261 // X + Y overflows ? (Y <s 0 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y
2262 // X + Y overflows ? (Y <s 1 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y
2263 // X + Y overflows ? (Y >s 0 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y
2264 // X + Y overflows ? (Y >s -1 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y
2265 NewIntrinsicID = Intrinsic::sadd_sat;
2266 else if (II->getIntrinsicID() == Intrinsic::ssub_with_overflow &&
2267 IsSignedSaturateLimit(TrueVal, /*IsAdd=*/false))
2268 // X - Y overflows ? (X <s 0 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y
2269 // X - Y overflows ? (X <s -1 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y
2270 // X - Y overflows ? (X >s -1 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y
2271 // X - Y overflows ? (X >s -2 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y
2272 // X - Y overflows ? (Y <s 0 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y
2273 // X - Y overflows ? (Y <s 1 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y
2274 // X - Y overflows ? (Y >s 0 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y
2275 // X - Y overflows ? (Y >s -1 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y
2276 NewIntrinsicID = Intrinsic::ssub_sat;
2277 else
2278 return nullptr;
2279
2281 NewIntrinsicID, SI.getType());
2282 return CallInst::Create(F, {X, Y});
2283}
2284
2286 Constant *C;
2287 if (!match(Sel.getTrueValue(), m_Constant(C)) &&
2288 !match(Sel.getFalseValue(), m_Constant(C)))
2289 return nullptr;
2290
2291 Instruction *ExtInst;
2292 if (!match(Sel.getTrueValue(), m_Instruction(ExtInst)) &&
2293 !match(Sel.getFalseValue(), m_Instruction(ExtInst)))
2294 return nullptr;
2295
2296 auto ExtOpcode = ExtInst->getOpcode();
2297 if (ExtOpcode != Instruction::ZExt && ExtOpcode != Instruction::SExt)
2298 return nullptr;
2299
2300 // If we are extending from a boolean type or if we can create a select that
2301 // has the same size operands as its condition, try to narrow the select.
2302 Value *X = ExtInst->getOperand(0);
2303 Type *SmallType = X->getType();
2304 Value *Cond = Sel.getCondition();
2305 auto *Cmp = dyn_cast<CmpInst>(Cond);
2306 if (!SmallType->isIntOrIntVectorTy(1) &&
2307 (!Cmp || Cmp->getOperand(0)->getType() != SmallType))
2308 return nullptr;
2309
2310 // If the constant is the same after truncation to the smaller type and
2311 // extension to the original type, we can narrow the select.
2312 Type *SelType = Sel.getType();
2313 Constant *TruncC = getLosslessTrunc(C, SmallType, ExtOpcode);
2314 if (TruncC && ExtInst->hasOneUse()) {
2315 Value *TruncCVal = cast<Value>(TruncC);
2316 if (ExtInst == Sel.getFalseValue())
2317 std::swap(X, TruncCVal);
2318
2319 // select Cond, (ext X), C --> ext(select Cond, X, C')
2320 // select Cond, C, (ext X) --> ext(select Cond, C', X)
2321 Value *NewSel = Builder.CreateSelect(Cond, X, TruncCVal, "narrow", &Sel);
2322 return CastInst::Create(Instruction::CastOps(ExtOpcode), NewSel, SelType);
2323 }
2324
2325 return nullptr;
2326}
2327
2328/// Try to transform a vector select with a constant condition vector into a
2329/// shuffle for easier combining with other shuffles and insert/extract.
2330static Instruction *canonicalizeSelectToShuffle(SelectInst &SI) {
2331 Value *CondVal = SI.getCondition();
2332 Constant *CondC;
2333 auto *CondValTy = dyn_cast<FixedVectorType>(CondVal->getType());
2334 if (!CondValTy || !match(CondVal, m_Constant(CondC)))
2335 return nullptr;
2336
2337 unsigned NumElts = CondValTy->getNumElements();
2339 Mask.reserve(NumElts);
2340 for (unsigned i = 0; i != NumElts; ++i) {
2341 Constant *Elt = CondC->getAggregateElement(i);
2342 if (!Elt)
2343 return nullptr;
2344
2345 if (Elt->isOneValue()) {
2346 // If the select condition element is true, choose from the 1st vector.
2347 Mask.push_back(i);
2348 } else if (Elt->isNullValue()) {
2349 // If the select condition element is false, choose from the 2nd vector.
2350 Mask.push_back(i + NumElts);
2351 } else if (isa<UndefValue>(Elt)) {
2352 // Undef in a select condition (choose one of the operands) does not mean
2353 // the same thing as undef in a shuffle mask (any value is acceptable), so
2354 // give up.
2355 return nullptr;
2356 } else {
2357 // Bail out on a constant expression.
2358 return nullptr;
2359 }
2360 }
2361
2362 return new ShuffleVectorInst(SI.getTrueValue(), SI.getFalseValue(), Mask);
2363}
2364
2365/// If we have a select of vectors with a scalar condition, try to convert that
2366/// to a vector select by splatting the condition. A splat may get folded with
2367/// other operations in IR and having all operands of a select be vector types
2368/// is likely better for vector codegen.
2369static Instruction *canonicalizeScalarSelectOfVecs(SelectInst &Sel,
2370 InstCombinerImpl &IC) {
2371 auto *Ty = dyn_cast<VectorType>(Sel.getType());
2372 if (!Ty)
2373 return nullptr;
2374
2375 // We can replace a single-use extract with constant index.
2376 Value *Cond = Sel.getCondition();
2378 return nullptr;
2379
2380 // select (extelt V, Index), T, F --> select (splat V, Index), T, F
2381 // Splatting the extracted condition reduces code (we could directly create a
2382 // splat shuffle of the source vector to eliminate the intermediate step).
2383 return IC.replaceOperand(
2384 Sel, 0, IC.Builder.CreateVectorSplat(Ty->getElementCount(), Cond));
2385}
2386
2387/// Reuse bitcasted operands between a compare and select:
2388/// select (cmp (bitcast C), (bitcast D)), (bitcast' C), (bitcast' D) -->
2389/// bitcast (select (cmp (bitcast C), (bitcast D)), (bitcast C), (bitcast D))
2390static Instruction *foldSelectCmpBitcasts(SelectInst &Sel,
2391 InstCombiner::BuilderTy &Builder) {
2392 Value *Cond = Sel.getCondition();
2393 Value *TVal = Sel.getTrueValue();
2394 Value *FVal = Sel.getFalseValue();
2395
2396 CmpPredicate Pred;
2397 Value *A, *B;
2398 if (!match(Cond, m_Cmp(Pred, m_Value(A), m_Value(B))))
2399 return nullptr;
2400
2401 // The select condition is a compare instruction. If the select's true/false
2402 // values are already the same as the compare operands, there's nothing to do.
2403 if (TVal == A || TVal == B || FVal == A || FVal == B)
2404 return nullptr;
2405
2406 Value *C, *D;
2407 if (!match(A, m_BitCast(m_Value(C))) || !match(B, m_BitCast(m_Value(D))))
2408 return nullptr;
2409
2410 // select (cmp (bitcast C), (bitcast D)), (bitcast TSrc), (bitcast FSrc)
2411 Value *TSrc, *FSrc;
2412 if (!match(TVal, m_BitCast(m_Value(TSrc))) ||
2413 !match(FVal, m_BitCast(m_Value(FSrc))))
2414 return nullptr;
2415
2416 // If the select true/false values are *different bitcasts* of the same source
2417 // operands, make the select operands the same as the compare operands and
2418 // cast the result. This is the canonical select form for min/max.
2419 Value *NewSel;
2420 if (TSrc == C && FSrc == D) {
2421 // select (cmp (bitcast C), (bitcast D)), (bitcast' C), (bitcast' D) -->
2422 // bitcast (select (cmp A, B), A, B)
2423 NewSel = Builder.CreateSelect(Cond, A, B, "", &Sel);
2424 } else if (TSrc == D && FSrc == C) {
2425 // select (cmp (bitcast C), (bitcast D)), (bitcast' D), (bitcast' C) -->
2426 // bitcast (select (cmp A, B), B, A)
2427 NewSel = Builder.CreateSelect(Cond, B, A, "", &Sel);
2428 } else {
2429 return nullptr;
2430 }
2431 return new BitCastInst(NewSel, Sel.getType());
2432}
2433
2434/// Try to eliminate select instructions that test the returned flag of cmpxchg
2435/// instructions.
2436///
2437/// If a select instruction tests the returned flag of a cmpxchg instruction and
2438/// selects between the returned value of the cmpxchg instruction its compare
2439/// operand, the result of the select will always be equal to its false value.
2440/// For example:
2441///
2442/// %cmpxchg = cmpxchg ptr %ptr, i64 %compare, i64 %new_value seq_cst seq_cst
2443/// %val = extractvalue { i64, i1 } %cmpxchg, 0
2444/// %success = extractvalue { i64, i1 } %cmpxchg, 1
2445/// %sel = select i1 %success, i64 %compare, i64 %val
2446/// ret i64 %sel
2447///
2448/// The returned value of the cmpxchg instruction (%val) is the original value
2449/// located at %ptr prior to any update. If the cmpxchg operation succeeds, %val
2450/// must have been equal to %compare. Thus, the result of the select is always
2451/// equal to %val, and the code can be simplified to:
2452///
2453/// %cmpxchg = cmpxchg ptr %ptr, i64 %compare, i64 %new_value seq_cst seq_cst
2454/// %val = extractvalue { i64, i1 } %cmpxchg, 0
2455/// ret i64 %val
2456///
2457static Value *foldSelectCmpXchg(SelectInst &SI) {
2458 // A helper that determines if V is an extractvalue instruction whose
2459 // aggregate operand is a cmpxchg instruction and whose single index is equal
2460 // to I. If such conditions are true, the helper returns the cmpxchg
2461 // instruction; otherwise, a nullptr is returned.
2462 auto isExtractFromCmpXchg = [](Value *V, unsigned I) -> AtomicCmpXchgInst * {
2463 auto *Extract = dyn_cast<ExtractValueInst>(V);
2464 if (!Extract)
2465 return nullptr;
2466 if (Extract->getIndices()[0] != I)
2467 return nullptr;
2468 return dyn_cast<AtomicCmpXchgInst>(Extract->getAggregateOperand());
2469 };
2470
2471 // If the select has a single user, and this user is a select instruction that
2472 // we can simplify, skip the cmpxchg simplification for now.
2473 if (SI.hasOneUse())
2474 if (auto *Select = dyn_cast<SelectInst>(SI.user_back()))
2475 if (Select->getCondition() == SI.getCondition())
2476 if (Select->getFalseValue() == SI.getTrueValue() ||
2477 Select->getTrueValue() == SI.getFalseValue())
2478 return nullptr;
2479
2480 // Ensure the select condition is the returned flag of a cmpxchg instruction.
2481 auto *CmpXchg = isExtractFromCmpXchg(SI.getCondition(), 1);
2482 if (!CmpXchg)
2483 return nullptr;
2484
2485 // Check the true value case: The true value of the select is the returned
2486 // value of the same cmpxchg used by the condition, and the false value is the
2487 // cmpxchg instruction's compare operand.
2488 if (auto *X = isExtractFromCmpXchg(SI.getTrueValue(), 0))
2489 if (X == CmpXchg && X->getCompareOperand() == SI.getFalseValue())
2490 return SI.getFalseValue();
2491
2492 // Check the false value case: The false value of the select is the returned
2493 // value of the same cmpxchg used by the condition, and the true value is the
2494 // cmpxchg instruction's compare operand.
2495 if (auto *X = isExtractFromCmpXchg(SI.getFalseValue(), 0))
2496 if (X == CmpXchg && X->getCompareOperand() == SI.getTrueValue())
2497 return SI.getFalseValue();
2498
2499 return nullptr;
2500}
2501
2502/// Try to reduce a funnel/rotate pattern that includes a compare and select
2503/// into a funnel shift intrinsic. Example:
2504/// rotl32(a, b) --> (b == 0 ? a : ((a >> (32 - b)) | (a << b)))
2505/// --> call llvm.fshl.i32(a, a, b)
2506/// fshl32(a, b, c) --> (c == 0 ? a : ((b >> (32 - c)) | (a << c)))
2507/// --> call llvm.fshl.i32(a, b, c)
2508/// fshr32(a, b, c) --> (c == 0 ? b : ((a >> (32 - c)) | (b << c)))
2509/// --> call llvm.fshr.i32(a, b, c)
2510static Instruction *foldSelectFunnelShift(SelectInst &Sel,
2511 InstCombiner::BuilderTy &Builder) {
2512 // This must be a power-of-2 type for a bitmasking transform to be valid.
2513 unsigned Width = Sel.getType()->getScalarSizeInBits();
2514 if (!isPowerOf2_32(Width))
2515 return nullptr;
2516
2517 BinaryOperator *Or0, *Or1;
2518 if (!match(Sel.getFalseValue(), m_OneUse(m_Or(m_BinOp(Or0), m_BinOp(Or1)))))
2519 return nullptr;
2520
2521 Value *SV0, *SV1, *SA0, *SA1;
2522 if (!match(Or0, m_OneUse(m_LogicalShift(m_Value(SV0),
2523 m_ZExtOrSelf(m_Value(SA0))))) ||
2525 m_ZExtOrSelf(m_Value(SA1))))) ||
2526 Or0->getOpcode() == Or1->getOpcode())
2527 return nullptr;
2528
2529 // Canonicalize to or(shl(SV0, SA0), lshr(SV1, SA1)).
2530 if (Or0->getOpcode() == BinaryOperator::LShr) {
2531 std::swap(Or0, Or1);
2532 std::swap(SV0, SV1);
2533 std::swap(SA0, SA1);
2534 }
2535 assert(Or0->getOpcode() == BinaryOperator::Shl &&
2536 Or1->getOpcode() == BinaryOperator::LShr &&
2537 "Illegal or(shift,shift) pair");
2538
2539 // Check the shift amounts to see if they are an opposite pair.
2540 Value *ShAmt;
2541 if (match(SA1, m_OneUse(m_Sub(m_SpecificInt(Width), m_Specific(SA0)))))
2542 ShAmt = SA0;
2543 else if (match(SA0, m_OneUse(m_Sub(m_SpecificInt(Width), m_Specific(SA1)))))
2544 ShAmt = SA1;
2545 else
2546 return nullptr;
2547
2548 // We should now have this pattern:
2549 // select ?, TVal, (or (shl SV0, SA0), (lshr SV1, SA1))
2550 // The false value of the select must be a funnel-shift of the true value:
2551 // IsFShl -> TVal must be SV0 else TVal must be SV1.
2552 bool IsFshl = (ShAmt == SA0);
2553 Value *TVal = Sel.getTrueValue();
2554 if ((IsFshl && TVal != SV0) || (!IsFshl && TVal != SV1))
2555 return nullptr;
2556
2557 // Finally, see if the select is filtering out a shift-by-zero.
2558 Value *Cond = Sel.getCondition();
2560 m_ZeroInt()))))
2561 return nullptr;
2562
2563 // If this is not a rotate then the select was blocking poison from the
2564 // 'shift-by-zero' non-TVal, but a funnel shift won't - so freeze it.
2565 if (SV0 != SV1) {
2566 if (IsFshl && !llvm::isGuaranteedNotToBePoison(SV1))
2567 SV1 = Builder.CreateFreeze(SV1);
2568 else if (!IsFshl && !llvm::isGuaranteedNotToBePoison(SV0))
2569 SV0 = Builder.CreateFreeze(SV0);
2570 }
2571
2572 // This is a funnel/rotate that avoids shift-by-bitwidth UB in a suboptimal way.
2573 // Convert to funnel shift intrinsic.
2574 Intrinsic::ID IID = IsFshl ? Intrinsic::fshl : Intrinsic::fshr;
2575 Function *F =
2577 ShAmt = Builder.CreateZExt(ShAmt, Sel.getType());
2578 return CallInst::Create(F, { SV0, SV1, ShAmt });
2579}
2580
2581static Instruction *foldSelectToCopysign(SelectInst &Sel,
2582 InstCombiner::BuilderTy &Builder) {
2583 Value *Cond = Sel.getCondition();
2584 Value *TVal = Sel.getTrueValue();
2585 Value *FVal = Sel.getFalseValue();
2586 Type *SelType = Sel.getType();
2587
2588 // Match select ?, TC, FC where the constants are equal but negated.
2589 // TODO: Generalize to handle a negated variable operand?
2590 const APFloat *TC, *FC;
2591 if (!match(TVal, m_APFloatAllowPoison(TC)) ||
2592 !match(FVal, m_APFloatAllowPoison(FC)) ||
2593 !abs(*TC).bitwiseIsEqual(abs(*FC)))
2594 return nullptr;
2595
2596 assert(TC != FC && "Expected equal select arms to simplify");
2597
2598 Value *X;
2599 const APInt *C;
2600 bool IsTrueIfSignSet;
2601 CmpPredicate Pred;
2603 m_APInt(C)))) ||
2604 !isSignBitCheck(Pred, *C, IsTrueIfSignSet) || X->getType() != SelType)
2605 return nullptr;
2606
2607 // If needed, negate the value that will be the sign argument of the copysign:
2608 // (bitcast X) < 0 ? -TC : TC --> copysign(TC, X)
2609 // (bitcast X) < 0 ? TC : -TC --> copysign(TC, -X)
2610 // (bitcast X) >= 0 ? -TC : TC --> copysign(TC, -X)
2611 // (bitcast X) >= 0 ? TC : -TC --> copysign(TC, X)
2612 // Note: FMF from the select can not be propagated to the new instructions.
2613 if (IsTrueIfSignSet ^ TC->isNegative())
2614 X = Builder.CreateFNeg(X);
2615
2616 // Canonicalize the magnitude argument as the positive constant since we do
2617 // not care about its sign.
2618 Value *MagArg = ConstantFP::get(SelType, abs(*TC));
2620 Sel.getModule(), Intrinsic::copysign, Sel.getType());
2621 return CallInst::Create(F, { MagArg, X });
2622}
2623
2625 if (!isa<VectorType>(Sel.getType()))
2626 return nullptr;
2627
2628 Value *Cond = Sel.getCondition();
2629 Value *TVal = Sel.getTrueValue();
2630 Value *FVal = Sel.getFalseValue();
2631 Value *C, *X, *Y;
2632
2633 if (match(Cond, m_VecReverse(m_Value(C)))) {
2634 auto createSelReverse = [&](Value *C, Value *X, Value *Y) {
2635 Value *V = Builder.CreateSelect(C, X, Y, Sel.getName(), &Sel);
2636 if (auto *I = dyn_cast<Instruction>(V))
2637 I->copyIRFlags(&Sel);
2638 Module *M = Sel.getModule();
2640 M, Intrinsic::vector_reverse, V->getType());
2641 return CallInst::Create(F, V);
2642 };
2643
2644 if (match(TVal, m_VecReverse(m_Value(X)))) {
2645 // select rev(C), rev(X), rev(Y) --> rev(select C, X, Y)
2646 if (match(FVal, m_VecReverse(m_Value(Y))) &&
2647 (Cond->hasOneUse() || TVal->hasOneUse() || FVal->hasOneUse()))
2648 return createSelReverse(C, X, Y);
2649
2650 // select rev(C), rev(X), FValSplat --> rev(select C, X, FValSplat)
2651 if ((Cond->hasOneUse() || TVal->hasOneUse()) && isSplatValue(FVal))
2652 return createSelReverse(C, X, FVal);
2653 }
2654 // select rev(C), TValSplat, rev(Y) --> rev(select C, TValSplat, Y)
2655 else if (isSplatValue(TVal) && match(FVal, m_VecReverse(m_Value(Y))) &&
2656 (Cond->hasOneUse() || FVal->hasOneUse()))
2657 return createSelReverse(C, TVal, Y);
2658 }
2659
2660 auto *VecTy = dyn_cast<FixedVectorType>(Sel.getType());
2661 if (!VecTy)
2662 return nullptr;
2663
2664 unsigned NumElts = VecTy->getNumElements();
2665 APInt PoisonElts(NumElts, 0);
2666 APInt AllOnesEltMask(APInt::getAllOnes(NumElts));
2667 if (Value *V = SimplifyDemandedVectorElts(&Sel, AllOnesEltMask, PoisonElts)) {
2668 if (V != &Sel)
2669 return replaceInstUsesWith(Sel, V);
2670 return &Sel;
2671 }
2672
2673 // A select of a "select shuffle" with a common operand can be rearranged
2674 // to select followed by "select shuffle". Because of poison, this only works
2675 // in the case of a shuffle with no undefined mask elements.
2677 if (match(TVal, m_OneUse(m_Shuffle(m_Value(X), m_Value(Y), m_Mask(Mask)))) &&
2678 !is_contained(Mask, PoisonMaskElem) &&
2679 cast<ShuffleVectorInst>(TVal)->isSelect()) {
2680 if (X == FVal) {
2681 // select Cond, (shuf_sel X, Y), X --> shuf_sel X, (select Cond, Y, X)
2682 Value *NewSel = Builder.CreateSelect(Cond, Y, X, "sel", &Sel);
2683 return new ShuffleVectorInst(X, NewSel, Mask);
2684 }
2685 if (Y == FVal) {
2686 // select Cond, (shuf_sel X, Y), Y --> shuf_sel (select Cond, X, Y), Y
2687 Value *NewSel = Builder.CreateSelect(Cond, X, Y, "sel", &Sel);
2688 return new ShuffleVectorInst(NewSel, Y, Mask);
2689 }
2690 }
2691 if (match(FVal, m_OneUse(m_Shuffle(m_Value(X), m_Value(Y), m_Mask(Mask)))) &&
2692 !is_contained(Mask, PoisonMaskElem) &&
2693 cast<ShuffleVectorInst>(FVal)->isSelect()) {
2694 if (X == TVal) {
2695 // select Cond, X, (shuf_sel X, Y) --> shuf_sel X, (select Cond, X, Y)
2696 Value *NewSel = Builder.CreateSelect(Cond, X, Y, "sel", &Sel);
2697 return new ShuffleVectorInst(X, NewSel, Mask);
2698 }
2699 if (Y == TVal) {
2700 // select Cond, Y, (shuf_sel X, Y) --> shuf_sel (select Cond, Y, X), Y
2701 Value *NewSel = Builder.CreateSelect(Cond, Y, X, "sel", &Sel);
2702 return new ShuffleVectorInst(NewSel, Y, Mask);
2703 }
2704 }
2705
2706 return nullptr;
2707}
2708
2709static Instruction *foldSelectToPhiImpl(SelectInst &Sel, BasicBlock *BB,
2710 const DominatorTree &DT,
2711 InstCombiner::BuilderTy &Builder) {
2712 // Find the block's immediate dominator that ends with a conditional branch
2713 // that matches select's condition (maybe inverted).
2714 auto *IDomNode = DT[BB]->getIDom();
2715 if (!IDomNode)
2716 return nullptr;
2717 BasicBlock *IDom = IDomNode->getBlock();
2718
2719 Value *Cond = Sel.getCondition();
2720 Value *IfTrue, *IfFalse;
2721 BasicBlock *TrueSucc, *FalseSucc;
2722 if (match(IDom->getTerminator(),
2723 m_Br(m_Specific(Cond), m_BasicBlock(TrueSucc),
2724 m_BasicBlock(FalseSucc)))) {
2725 IfTrue = Sel.getTrueValue();
2726 IfFalse = Sel.getFalseValue();
2727 } else if (match(IDom->getTerminator(),
2728 m_Br(m_Not(m_Specific(Cond)), m_BasicBlock(TrueSucc),
2729 m_BasicBlock(FalseSucc)))) {
2730 IfTrue = Sel.getFalseValue();
2731 IfFalse = Sel.getTrueValue();
2732 } else
2733 return nullptr;
2734
2735 // Make sure the branches are actually different.
2736 if (TrueSucc == FalseSucc)
2737 return nullptr;
2738
2739 // We want to replace select %cond, %a, %b with a phi that takes value %a
2740 // for all incoming edges that are dominated by condition `%cond == true`,
2741 // and value %b for edges dominated by condition `%cond == false`. If %a
2742 // or %b are also phis from the same basic block, we can go further and take
2743 // their incoming values from the corresponding blocks.
2744 BasicBlockEdge TrueEdge(IDom, TrueSucc);
2745 BasicBlockEdge FalseEdge(IDom, FalseSucc);
2747 for (auto *Pred : predecessors(BB)) {
2748 // Check implication.
2749 BasicBlockEdge Incoming(Pred, BB);
2750 if (DT.dominates(TrueEdge, Incoming))
2751 Inputs[Pred] = IfTrue->DoPHITranslation(BB, Pred);
2752 else if (DT.dominates(FalseEdge, Incoming))
2753 Inputs[Pred] = IfFalse->DoPHITranslation(BB, Pred);
2754 else
2755 return nullptr;
2756 // Check availability.
2757 if (auto *Insn = dyn_cast<Instruction>(Inputs[Pred]))
2758 if (!DT.dominates(Insn, Pred->getTerminator()))
2759 return nullptr;
2760 }
2761
2762 Builder.SetInsertPoint(BB, BB->begin());
2763 auto *PN = Builder.CreatePHI(Sel.getType(), Inputs.size());
2764 for (auto *Pred : predecessors(BB))
2765 PN->addIncoming(Inputs[Pred], Pred);
2766 PN->takeName(&Sel);
2767 return PN;
2768}
2769
2770static Instruction *foldSelectToPhi(SelectInst &Sel, const DominatorTree &DT,
2771 InstCombiner::BuilderTy &Builder) {
2772 // Try to replace this select with Phi in one of these blocks.
2773 SmallSetVector<BasicBlock *, 4> CandidateBlocks;
2774 CandidateBlocks.insert(Sel.getParent());
2775 for (Value *V : Sel.operands())
2776 if (auto *I = dyn_cast<Instruction>(V))
2777 CandidateBlocks.insert(I->getParent());
2778
2779 for (BasicBlock *BB : CandidateBlocks)
2780 if (auto *PN = foldSelectToPhiImpl(Sel, BB, DT, Builder))
2781 return PN;
2782 return nullptr;
2783}
2784
2785/// Tries to reduce a pattern that arises when calculating the remainder of the
2786/// Euclidean division. When the divisor is a power of two and is guaranteed not
2787/// to be negative, a signed remainder can be folded with a bitwise and.
2788///
2789/// (x % n) < 0 ? (x % n) + n : (x % n)
2790/// -> x & (n - 1)
2791static Instruction *foldSelectWithSRem(SelectInst &SI, InstCombinerImpl &IC,
2792 IRBuilderBase &Builder) {
2793 Value *CondVal = SI.getCondition();
2794 Value *TrueVal = SI.getTrueValue();
2795 Value *FalseVal = SI.getFalseValue();
2796
2797 CmpPredicate Pred;
2798 Value *Op, *RemRes, *Remainder;
2799 const APInt *C;
2800 bool TrueIfSigned = false;
2801
2802 if (!(match(CondVal, m_ICmp(Pred, m_Value(RemRes), m_APInt(C))) &&
2803 isSignBitCheck(Pred, *C, TrueIfSigned)))
2804 return nullptr;
2805
2806 // If the sign bit is not set, we have a SGE/SGT comparison, and the operands
2807 // of the select are inverted.
2808 if (!TrueIfSigned)
2809 std::swap(TrueVal, FalseVal);
2810
2811 auto FoldToBitwiseAnd = [&](Value *Remainder) -> Instruction * {
2812 Value *Add = Builder.CreateAdd(
2813 Remainder, Constant::getAllOnesValue(RemRes->getType()));
2814 return BinaryOperator::CreateAnd(Op, Add);
2815 };
2816
2817 // Match the general case:
2818 // %rem = srem i32 %x, %n
2819 // %cnd = icmp slt i32 %rem, 0
2820 // %add = add i32 %rem, %n
2821 // %sel = select i1 %cnd, i32 %add, i32 %rem
2822 if (match(TrueVal, m_Add(m_Specific(RemRes), m_Value(Remainder))) &&
2823 match(RemRes, m_SRem(m_Value(Op), m_Specific(Remainder))) &&
2824 IC.isKnownToBeAPowerOfTwo(Remainder, /*OrZero*/ true) &&
2825 FalseVal == RemRes)
2826 return FoldToBitwiseAnd(Remainder);
2827
2828 // Match the case where the one arm has been replaced by constant 1:
2829 // %rem = srem i32 %n, 2
2830 // %cnd = icmp slt i32 %rem, 0
2831 // %sel = select i1 %cnd, i32 1, i32 %rem
2832 if (match(TrueVal, m_One()) &&
2833 match(RemRes, m_SRem(m_Value(Op), m_SpecificInt(2))) &&
2834 FalseVal == RemRes)
2835 return FoldToBitwiseAnd(ConstantInt::get(RemRes->getType(), 2));
2836
2837 return nullptr;
2838}
2839
2840static Value *foldSelectWithFrozenICmp(SelectInst &Sel, InstCombiner::BuilderTy &Builder) {
2841 FreezeInst *FI = dyn_cast<FreezeInst>(Sel.getCondition());
2842 if (!FI)
2843 return nullptr;
2844
2845 Value *Cond = FI->getOperand(0);
2846 Value *TrueVal = Sel.getTrueValue(), *FalseVal = Sel.getFalseValue();
2847
2848 // select (freeze(x == y)), x, y --> y
2849 // select (freeze(x != y)), x, y --> x
2850 // The freeze should be only used by this select. Otherwise, remaining uses of
2851 // the freeze can observe a contradictory value.
2852 // c = freeze(x == y) ; Let's assume that y = poison & x = 42; c is 0 or 1
2853 // a = select c, x, y ;
2854 // f(a, c) ; f(poison, 1) cannot happen, but if a is folded
2855 // ; to y, this can happen.
2856 CmpPredicate Pred;
2857 if (FI->hasOneUse() &&
2858 match(Cond, m_c_ICmp(Pred, m_Specific(TrueVal), m_Specific(FalseVal))) &&
2859 (Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE)) {
2860 return Pred == ICmpInst::ICMP_EQ ? FalseVal : TrueVal;
2861 }
2862
2863 return nullptr;
2864}
2865
2866/// Given that \p CondVal is known to be \p CondIsTrue, try to simplify \p SI.
2867static Value *simplifyNestedSelectsUsingImpliedCond(SelectInst &SI,
2868 Value *CondVal,
2869 bool CondIsTrue,
2870 const DataLayout &DL) {
2871 Value *InnerCondVal = SI.getCondition();
2872 Value *InnerTrueVal = SI.getTrueValue();
2873 Value *InnerFalseVal = SI.getFalseValue();
2874 assert(CondVal->getType() == InnerCondVal->getType() &&
2875 "The type of inner condition must match with the outer.");
2876 if (auto Implied = isImpliedCondition(CondVal, InnerCondVal, DL, CondIsTrue))
2877 return *Implied ? InnerTrueVal : InnerFalseVal;
2878 return nullptr;
2879}
2880
2881Instruction *InstCombinerImpl::foldAndOrOfSelectUsingImpliedCond(Value *Op,
2882 SelectInst &SI,
2883 bool IsAnd) {
2884 assert(Op->getType()->isIntOrIntVectorTy(1) &&
2885 "Op must be either i1 or vector of i1.");
2886 if (SI.getCondition()->getType() != Op->getType())
2887 return nullptr;
2888 if (Value *V = simplifyNestedSelectsUsingImpliedCond(SI, Op, IsAnd, DL))
2889 return SelectInst::Create(Op,
2890 IsAnd ? V : ConstantInt::getTrue(Op->getType()),
2891 IsAnd ? ConstantInt::getFalse(Op->getType()) : V);
2892 return nullptr;
2893}
2894
2895// Canonicalize select with fcmp to fabs(). -0.0 makes this tricky. We need
2896// fast-math-flags (nsz) or fsub with +0.0 (not fneg) for this to work.
2897static Instruction *foldSelectWithFCmpToFabs(SelectInst &SI,
2898 InstCombinerImpl &IC) {
2899 Value *CondVal = SI.getCondition();
2900
2901 bool ChangedFMF = false;
2902 for (bool Swap : {false, true}) {
2903 Value *TrueVal = SI.getTrueValue();
2904 Value *X = SI.getFalseValue();
2905 CmpPredicate Pred;
2906
2907 if (Swap)
2908 std::swap(TrueVal, X);
2909
2910 if (!match(CondVal, m_FCmp(Pred, m_Specific(X), m_AnyZeroFP())))
2911 continue;
2912
2913 // fold (X <= +/-0.0) ? (0.0 - X) : X to fabs(X), when 'Swap' is false
2914 // fold (X > +/-0.0) ? X : (0.0 - X) to fabs(X), when 'Swap' is true
2915 if (match(TrueVal, m_FSub(m_PosZeroFP(), m_Specific(X)))) {
2916 if (!Swap && (Pred == FCmpInst::FCMP_OLE || Pred == FCmpInst::FCMP_ULE)) {
2917 Value *Fabs = IC.Builder.CreateUnaryIntrinsic(Intrinsic::fabs, X, &SI);
2918 return IC.replaceInstUsesWith(SI, Fabs);
2919 }
2920 if (Swap && (Pred == FCmpInst::FCMP_OGT || Pred == FCmpInst::FCMP_UGT)) {
2921 Value *Fabs = IC.Builder.CreateUnaryIntrinsic(Intrinsic::fabs, X, &SI);
2922 return IC.replaceInstUsesWith(SI, Fabs);
2923 }
2924 }
2925
2926 if (!match(TrueVal, m_FNeg(m_Specific(X))))
2927 return nullptr;
2928
2929 // Forward-propagate nnan and ninf from the fneg to the select.
2930 // If all inputs are not those values, then the select is not either.
2931 // Note: nsz is defined differently, so it may not be correct to propagate.
2932 FastMathFlags FMF = cast<FPMathOperator>(TrueVal)->getFastMathFlags();
2933 if (FMF.noNaNs() && !SI.hasNoNaNs()) {
2934 SI.setHasNoNaNs(true);
2935 ChangedFMF = true;
2936 }
2937 if (FMF.noInfs() && !SI.hasNoInfs()) {
2938 SI.setHasNoInfs(true);
2939 ChangedFMF = true;
2940 }
2941
2942 // With nsz, when 'Swap' is false:
2943 // fold (X < +/-0.0) ? -X : X or (X <= +/-0.0) ? -X : X to fabs(X)
2944 // fold (X > +/-0.0) ? -X : X or (X >= +/-0.0) ? -X : X to -fabs(x)
2945 // when 'Swap' is true:
2946 // fold (X > +/-0.0) ? X : -X or (X >= +/-0.0) ? X : -X to fabs(X)
2947 // fold (X < +/-0.0) ? X : -X or (X <= +/-0.0) ? X : -X to -fabs(X)
2948 //
2949 // Note: We require "nnan" for this fold because fcmp ignores the signbit
2950 // of NAN, but IEEE-754 specifies the signbit of NAN values with
2951 // fneg/fabs operations.
2952 if (!SI.hasNoSignedZeros() || !SI.hasNoNaNs())
2953 return nullptr;
2954
2955 if (Swap)
2956 Pred = FCmpInst::getSwappedPredicate(Pred);
2957
2958 bool IsLTOrLE = Pred == FCmpInst::FCMP_OLT || Pred == FCmpInst::FCMP_OLE ||
2959 Pred == FCmpInst::FCMP_ULT || Pred == FCmpInst::FCMP_ULE;
2960 bool IsGTOrGE = Pred == FCmpInst::FCMP_OGT || Pred == FCmpInst::FCMP_OGE ||
2961 Pred == FCmpInst::FCMP_UGT || Pred == FCmpInst::FCMP_UGE;
2962
2963 if (IsLTOrLE) {
2964 Value *Fabs = IC.Builder.CreateUnaryIntrinsic(Intrinsic::fabs, X, &SI);
2965 return IC.replaceInstUsesWith(SI, Fabs);
2966 }
2967 if (IsGTOrGE) {
2968 Value *Fabs = IC.Builder.CreateUnaryIntrinsic(Intrinsic::fabs, X, &SI);
2969 Instruction *NewFNeg = UnaryOperator::CreateFNeg(Fabs);
2970 NewFNeg->setFastMathFlags(SI.getFastMathFlags());
2971 return NewFNeg;
2972 }
2973 }
2974
2975 // Match select with (icmp slt (bitcast X to int), 0)
2976 // or (icmp sgt (bitcast X to int), -1)
2977
2978 for (bool Swap : {false, true}) {
2979 Value *TrueVal = SI.getTrueValue();
2980 Value *X = SI.getFalseValue();
2981
2982 if (Swap)
2983 std::swap(TrueVal, X);
2984
2985 CmpPredicate Pred;
2986 const APInt *C;
2987 bool TrueIfSigned;
2988 if (!match(CondVal,
2990 !isSignBitCheck(Pred, *C, TrueIfSigned))
2991 continue;
2992 if (!match(TrueVal, m_FNeg(m_Specific(X))))
2993 return nullptr;
2994 if (Swap == TrueIfSigned && !CondVal->hasOneUse() && !TrueVal->hasOneUse())
2995 return nullptr;
2996
2997 // Fold (IsNeg ? -X : X) or (!IsNeg ? X : -X) to fabs(X)
2998 // Fold (IsNeg ? X : -X) or (!IsNeg ? -X : X) to -fabs(X)
2999 Value *Fabs = IC.Builder.CreateUnaryIntrinsic(Intrinsic::fabs, X, &SI);
3000 if (Swap != TrueIfSigned)
3001 return IC.replaceInstUsesWith(SI, Fabs);
3002 return UnaryOperator::CreateFNegFMF(Fabs, &SI);
3003 }
3004
3005 return ChangedFMF ? &SI : nullptr;
3006}
3007
3008// Match the following IR pattern:
3009// %x.lowbits = and i8 %x, %lowbitmask
3010// %x.lowbits.are.zero = icmp eq i8 %x.lowbits, 0
3011// %x.biased = add i8 %x, %bias
3012// %x.biased.highbits = and i8 %x.biased, %highbitmask
3013// %x.roundedup = select i1 %x.lowbits.are.zero, i8 %x, i8 %x.biased.highbits
3014// Define:
3015// %alignment = add i8 %lowbitmask, 1
3016// Iff 1. an %alignment is a power-of-two (aka, %lowbitmask is a low bit mask)
3017// and 2. %bias is equal to either %lowbitmask or %alignment,
3018// and 3. %highbitmask is equal to ~%lowbitmask (aka, to -%alignment)
3019// then this pattern can be transformed into:
3020// %x.offset = add i8 %x, %lowbitmask
3021// %x.roundedup = and i8 %x.offset, %highbitmask
3022static Value *
3023foldRoundUpIntegerWithPow2Alignment(SelectInst &SI,
3024 InstCombiner::BuilderTy &Builder) {
3025 Value *Cond = SI.getCondition();
3026 Value *X = SI.getTrueValue();
3027 Value *XBiasedHighBits = SI.getFalseValue();
3028
3029 CmpPredicate Pred;
3030 Value *XLowBits;
3031 if (!match(Cond, m_ICmp(Pred, m_Value(XLowBits), m_ZeroInt())) ||
3032 !ICmpInst::isEquality(Pred))
3033 return nullptr;
3034
3035 if (Pred == ICmpInst::Predicate::ICMP_NE)
3036 std::swap(X, XBiasedHighBits);
3037
3038 // FIXME: we could support non non-splats here.
3039
3040 const APInt *LowBitMaskCst;
3041 if (!match(XLowBits, m_And(m_Specific(X), m_APIntAllowPoison(LowBitMaskCst))))
3042 return nullptr;
3043
3044 // Match even if the AND and ADD are swapped.
3045 const APInt *BiasCst, *HighBitMaskCst;
3046 if (!match(XBiasedHighBits,
3048 m_APIntAllowPoison(HighBitMaskCst))) &&
3049 !match(XBiasedHighBits,
3050 m_Add(m_And(m_Specific(X), m_APIntAllowPoison(HighBitMaskCst)),
3051 m_APIntAllowPoison(BiasCst))))
3052 return nullptr;
3053
3054 if (!LowBitMaskCst->isMask())
3055 return nullptr;
3056
3057 APInt InvertedLowBitMaskCst = ~*LowBitMaskCst;
3058 if (InvertedLowBitMaskCst != *HighBitMaskCst)
3059 return nullptr;
3060
3061 APInt AlignmentCst = *LowBitMaskCst + 1;
3062
3063 if (*BiasCst != AlignmentCst && *BiasCst != *LowBitMaskCst)
3064 return nullptr;
3065
3066 if (!XBiasedHighBits->hasOneUse()) {
3067 // We can't directly return XBiasedHighBits if it is more poisonous.
3068 if (*BiasCst == *LowBitMaskCst && impliesPoison(XBiasedHighBits, X))
3069 return XBiasedHighBits;
3070 return nullptr;
3071 }
3072
3073 // FIXME: could we preserve undef's here?
3074 Type *Ty = X->getType();
3075 Value *XOffset = Builder.CreateAdd(X, ConstantInt::get(Ty, *LowBitMaskCst),
3076 X->getName() + ".biased");
3077 Value *R = Builder.CreateAnd(XOffset, ConstantInt::get(Ty, *HighBitMaskCst));
3078 R->takeName(&SI);
3079 return R;
3080}
3081
3082namespace {
3083struct DecomposedSelect {
3084 Value *Cond = nullptr;
3085 Value *TrueVal = nullptr;
3086 Value *FalseVal = nullptr;
3087};
3088} // namespace
3089
3090/// Folds patterns like:
3091/// select c2 (select c1 a b) (select c1 b a)
3092/// into:
3093/// select (xor c1 c2) b a
3094static Instruction *
3095foldSelectOfSymmetricSelect(SelectInst &OuterSelVal,
3096 InstCombiner::BuilderTy &Builder) {
3097
3098 Value *OuterCond, *InnerCond, *InnerTrueVal, *InnerFalseVal;
3099 if (!match(
3100 &OuterSelVal,
3101 m_Select(m_Value(OuterCond),
3102 m_OneUse(m_Select(m_Value(InnerCond), m_Value(InnerTrueVal),
3103 m_Value(InnerFalseVal))),
3104 m_OneUse(m_Select(m_Deferred(InnerCond),
3105 m_Deferred(InnerFalseVal),
3106 m_Deferred(InnerTrueVal))))))
3107 return nullptr;
3108
3109 if (OuterCond->getType() != InnerCond->getType())
3110 return nullptr;
3111
3112 Value *Xor = Builder.CreateXor(InnerCond, OuterCond);
3113 return SelectInst::Create(Xor, InnerFalseVal, InnerTrueVal);
3114}
3115
3116/// Look for patterns like
3117/// %outer.cond = select i1 %inner.cond, i1 %alt.cond, i1 false
3118/// %inner.sel = select i1 %inner.cond, i8 %inner.sel.t, i8 %inner.sel.f
3119/// %outer.sel = select i1 %outer.cond, i8 %outer.sel.t, i8 %inner.sel
3120/// and rewrite it as
3121/// %inner.sel = select i1 %cond.alternative, i8 %sel.outer.t, i8 %sel.inner.t
3122/// %sel.outer = select i1 %cond.inner, i8 %inner.sel, i8 %sel.inner.f
3123static Instruction *foldNestedSelects(SelectInst &OuterSelVal,
3124 InstCombiner::BuilderTy &Builder) {
3125 // We must start with a `select`.
3126 DecomposedSelect OuterSel;
3127 match(&OuterSelVal,
3128 m_Select(m_Value(OuterSel.Cond), m_Value(OuterSel.TrueVal),
3129 m_Value(OuterSel.FalseVal)));
3130
3131 // Canonicalize inversion of the outermost `select`'s condition.
3132 if (match(OuterSel.Cond, m_Not(m_Value(OuterSel.Cond))))
3133 std::swap(OuterSel.TrueVal, OuterSel.FalseVal);
3134
3135 // The condition of the outermost select must be an `and`/`or`.
3136 if (!match(OuterSel.Cond, m_c_LogicalOp(m_Value(), m_Value())))
3137 return nullptr;
3138
3139 // Depending on the logical op, inner select might be in different hand.
3140 bool IsAndVariant = match(OuterSel.Cond, m_LogicalAnd());
3141 Value *InnerSelVal = IsAndVariant ? OuterSel.FalseVal : OuterSel.TrueVal;
3142
3143 // Profitability check - avoid increasing instruction count.
3144 if (none_of(ArrayRef<Value *>({OuterSelVal.getCondition(), InnerSelVal}),
3145 [](Value *V) { return V->hasOneUse(); }))
3146 return nullptr;
3147
3148 // The appropriate hand of the outermost `select` must be a select itself.
3149 DecomposedSelect InnerSel;
3150 if (!match(InnerSelVal,
3151 m_Select(m_Value(InnerSel.Cond), m_Value(InnerSel.TrueVal),
3152 m_Value(InnerSel.FalseVal))))
3153 return nullptr;
3154
3155 // Canonicalize inversion of the innermost `select`'s condition.
3156 if (match(InnerSel.Cond, m_Not(m_Value(InnerSel.Cond))))
3157 std::swap(InnerSel.TrueVal, InnerSel.FalseVal);
3158
3159 Value *AltCond = nullptr;
3160 auto matchOuterCond = [OuterSel, IsAndVariant, &AltCond](auto m_InnerCond) {
3161 // An unsimplified select condition can match both LogicalAnd and LogicalOr
3162 // (select true, true, false). Since below we assume that LogicalAnd implies
3163 // InnerSel match the FVal and vice versa for LogicalOr, we can't match the
3164 // alternative pattern here.
3165 return IsAndVariant ? match(OuterSel.Cond,
3166 m_c_LogicalAnd(m_InnerCond, m_Value(AltCond)))
3167 : match(OuterSel.Cond,
3168 m_c_LogicalOr(m_InnerCond, m_Value(AltCond)));
3169 };
3170
3171 // Finally, match the condition that was driving the outermost `select`,
3172 // it should be a logical operation between the condition that was driving
3173 // the innermost `select` (after accounting for the possible inversions
3174 // of the condition), and some other condition.
3175 if (matchOuterCond(m_Specific(InnerSel.Cond))) {
3176 // Done!
3177 } else if (Value * NotInnerCond; matchOuterCond(m_CombineAnd(
3178 m_Not(m_Specific(InnerSel.Cond)), m_Value(NotInnerCond)))) {
3179 // Done!
3180 std::swap(InnerSel.TrueVal, InnerSel.FalseVal);
3181 InnerSel.Cond = NotInnerCond;
3182 } else // Not the pattern we were looking for.
3183 return nullptr;
3184
3185 Value *SelInner = Builder.CreateSelect(
3186 AltCond, IsAndVariant ? OuterSel.TrueVal : InnerSel.FalseVal,
3187 IsAndVariant ? InnerSel.TrueVal : OuterSel.FalseVal);
3188 SelInner->takeName(InnerSelVal);
3189 return SelectInst::Create(InnerSel.Cond,
3190 IsAndVariant ? SelInner : InnerSel.TrueVal,
3191 !IsAndVariant ? SelInner : InnerSel.FalseVal);
3192}
3193
3194/// Return true if V is poison or \p Expected given that ValAssumedPoison is
3195/// already poison. For example, if ValAssumedPoison is `icmp samesign X, 10`
3196/// and V is `icmp ne X, 5`, impliesPoisonOrCond returns true.
3197static bool impliesPoisonOrCond(const Value *ValAssumedPoison, const Value *V,
3198 bool Expected) {
3199 if (impliesPoison(ValAssumedPoison, V))
3200 return true;
3201
3202 // Handle the case that ValAssumedPoison is `icmp samesign pred X, C1` and V
3203 // is `icmp pred X, C2`, where C1 is well-defined.
3204 if (auto *ICmp = dyn_cast<ICmpInst>(ValAssumedPoison)) {
3205 Value *LHS = ICmp->getOperand(0);
3206 const APInt *RHSC1;
3207 const APInt *RHSC2;
3208 CmpPredicate Pred;
3209 if (ICmp->hasSameSign() &&
3210 match(ICmp->getOperand(1), m_APIntForbidPoison(RHSC1)) &&
3211 match(V, m_ICmp(Pred, m_Specific(LHS), m_APIntAllowPoison(RHSC2)))) {
3212 unsigned BitWidth = RHSC1->getBitWidth();
3213 ConstantRange CRX =
3214 RHSC1->isNonNegative()
3217 : ConstantRange(APInt::getZero(BitWidth),
3218 APInt::getSignedMinValue(BitWidth));
3219 return CRX.icmp(Expected ? Pred : ICmpInst::getInverseCmpPredicate(Pred),
3220 *RHSC2);
3221 }
3222 }
3223
3224 return false;
3225}
3226
3228 Value *CondVal = SI.getCondition();
3229 Value *TrueVal = SI.getTrueValue();
3230 Value *FalseVal = SI.getFalseValue();
3231 Type *SelType = SI.getType();
3232
3233 // Avoid potential infinite loops by checking for non-constant condition.
3234 // TODO: Can we assert instead by improving canonicalizeSelectToShuffle()?
3235 // Scalar select must have simplified?
3236 if (!SelType->isIntOrIntVectorTy(1) || isa<Constant>(CondVal) ||
3237 TrueVal->getType() != CondVal->getType())
3238 return nullptr;
3239
3240 auto *One = ConstantInt::getTrue(SelType);
3241 auto *Zero = ConstantInt::getFalse(SelType);
3242 Value *A, *B, *C, *D;
3243
3244 // Folding select to and/or i1 isn't poison safe in general. impliesPoison
3245 // checks whether folding it does not convert a well-defined value into
3246 // poison.
3247 if (match(TrueVal, m_One())) {
3248 if (impliesPoisonOrCond(FalseVal, CondVal, /*Expected=*/false)) {
3249 // Change: A = select B, true, C --> A = or B, C
3250 return BinaryOperator::CreateOr(CondVal, FalseVal);
3251 }
3252
3253 if (match(CondVal, m_OneUse(m_Select(m_Value(A), m_One(), m_Value(B)))) &&
3254 impliesPoisonOrCond(FalseVal, B, /*Expected=*/false)) {
3255 // (A || B) || C --> A || (B | C)
3256 return replaceInstUsesWith(
3257 SI, Builder.CreateLogicalOr(A, Builder.CreateOr(B, FalseVal)));
3258 }
3259
3260 // (A && B) || (C && B) --> (A || C) && B
3261 if (match(CondVal, m_LogicalAnd(m_Value(A), m_Value(B))) &&
3262 match(FalseVal, m_LogicalAnd(m_Value(C), m_Value(D))) &&
3263 (CondVal->hasOneUse() || FalseVal->hasOneUse())) {
3264 bool CondLogicAnd = isa<SelectInst>(CondVal);
3265 bool FalseLogicAnd = isa<SelectInst>(FalseVal);
3266 auto AndFactorization = [&](Value *Common, Value *InnerCond,
3267 Value *InnerVal,
3268 bool SelFirst = false) -> Instruction * {
3269 Value *InnerSel = Builder.CreateSelect(InnerCond, One, InnerVal);
3270 if (SelFirst)
3271 std::swap(Common, InnerSel);
3272 if (FalseLogicAnd || (CondLogicAnd && Common == A))
3273 return SelectInst::Create(Common, InnerSel, Zero);
3274 else
3275 return BinaryOperator::CreateAnd(Common, InnerSel);
3276 };
3277
3278 if (A == C)
3279 return AndFactorization(A, B, D);
3280 if (A == D)
3281 return AndFactorization(A, B, C);
3282 if (B == C)
3283 return AndFactorization(B, A, D);
3284 if (B == D)
3285 return AndFactorization(B, A, C, CondLogicAnd && FalseLogicAnd);
3286 }
3287 }
3288
3289 if (match(FalseVal, m_Zero())) {
3290 if (impliesPoisonOrCond(TrueVal, CondVal, /*Expected=*/true)) {
3291 // Change: A = select B, C, false --> A = and B, C
3292 return BinaryOperator::CreateAnd(CondVal, TrueVal);
3293 }
3294
3295 if (match(CondVal, m_OneUse(m_Select(m_Value(A), m_Value(B), m_Zero()))) &&
3296 impliesPoisonOrCond(TrueVal, B, /*Expected=*/true)) {
3297 // (A && B) && C --> A && (B & C)
3298 return replaceInstUsesWith(
3299 SI, Builder.CreateLogicalAnd(A, Builder.CreateAnd(B, TrueVal)));
3300 }
3301
3302 // (A || B) && (C || B) --> (A && C) || B
3303 if (match(CondVal, m_LogicalOr(m_Value(A), m_Value(B))) &&
3304 match(TrueVal, m_LogicalOr(m_Value(C), m_Value(D))) &&
3305 (CondVal->hasOneUse() || TrueVal->hasOneUse())) {
3306 bool CondLogicOr = isa<SelectInst>(CondVal);
3307 bool TrueLogicOr = isa<SelectInst>(TrueVal);
3308 auto OrFactorization = [&](Value *Common, Value *InnerCond,
3309 Value *InnerVal,
3310 bool SelFirst = false) -> Instruction * {
3311 Value *InnerSel = Builder.CreateSelect(InnerCond, InnerVal, Zero);
3312 if (SelFirst)
3313 std::swap(Common, InnerSel);
3314 if (TrueLogicOr || (CondLogicOr && Common == A))
3315 return SelectInst::Create(Common, One, InnerSel);
3316 else
3317 return BinaryOperator::CreateOr(Common, InnerSel);
3318 };
3319
3320 if (A == C)
3321 return OrFactorization(A, B, D);
3322 if (A == D)
3323 return OrFactorization(A, B, C);
3324 if (B == C)
3325 return OrFactorization(B, A, D);
3326 if (B == D)
3327 return OrFactorization(B, A, C, CondLogicOr && TrueLogicOr);
3328 }
3329 }
3330
3331 // We match the "full" 0 or 1 constant here to avoid a potential infinite
3332 // loop with vectors that may have undefined/poison elements.
3333 // select a, false, b -> select !a, b, false
3334 if (match(TrueVal, m_Specific(Zero))) {
3335 Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName());
3336 return SelectInst::Create(NotCond, FalseVal, Zero);
3337 }
3338 // select a, b, true -> select !a, true, b
3339 if (match(FalseVal, m_Specific(One))) {
3340 Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName());
3341 return SelectInst::Create(NotCond, One, TrueVal);
3342 }
3343
3344 // DeMorgan in select form: !a && !b --> !(a || b)
3345 // select !a, !b, false --> not (select a, true, b)
3346 if (match(&SI, m_LogicalAnd(m_Not(m_Value(A)), m_Not(m_Value(B)))) &&
3347 (CondVal->hasOneUse() || TrueVal->hasOneUse()) &&
3350
3351 // DeMorgan in select form: !a || !b --> !(a && b)
3352 // select !a, true, !b --> not (select a, b, false)
3353 if (match(&SI, m_LogicalOr(m_Not(m_Value(A)), m_Not(m_Value(B)))) &&
3354 (CondVal->hasOneUse() || FalseVal->hasOneUse()) &&
3357
3358 // select (select a, true, b), true, b -> select a, true, b
3359 if (match(CondVal, m_Select(m_Value(A), m_One(), m_Value(B))) &&
3360 match(TrueVal, m_One()) && match(FalseVal, m_Specific(B)))
3361 return replaceOperand(SI, 0, A);
3362 // select (select a, b, false), b, false -> select a, b, false
3363 if (match(CondVal, m_Select(m_Value(A), m_Value(B), m_Zero())) &&
3364 match(TrueVal, m_Specific(B)) && match(FalseVal, m_Zero()))
3365 return replaceOperand(SI, 0, A);
3366
3367 // ~(A & B) & (A | B) --> A ^ B
3370 return BinaryOperator::CreateXor(A, B);
3371
3372 // select (~a | c), a, b -> select a, (select c, true, b), false
3373 if (match(CondVal,
3374 m_OneUse(m_c_Or(m_Not(m_Specific(TrueVal)), m_Value(C))))) {
3375 Value *OrV = Builder.CreateSelect(C, One, FalseVal);
3376 return SelectInst::Create(TrueVal, OrV, Zero);
3377 }
3378 // select (c & b), a, b -> select b, (select ~c, true, a), false
3379 if (match(CondVal, m_OneUse(m_c_And(m_Value(C), m_Specific(FalseVal))))) {
3380 if (Value *NotC = getFreelyInverted(C, C->hasOneUse(), &Builder)) {
3381 Value *OrV = Builder.CreateSelect(NotC, One, TrueVal);
3382 return SelectInst::Create(FalseVal, OrV, Zero);
3383 }
3384 }
3385 // select (a | c), a, b -> select a, true, (select ~c, b, false)
3386 if (match(CondVal, m_OneUse(m_c_Or(m_Specific(TrueVal), m_Value(C))))) {
3387 if (Value *NotC = getFreelyInverted(C, C->hasOneUse(), &Builder)) {
3388 Value *AndV = Builder.CreateSelect(NotC, FalseVal, Zero);
3389 return SelectInst::Create(TrueVal, One, AndV);
3390 }
3391 }
3392 // select (c & ~b), a, b -> select b, true, (select c, a, false)
3393 if (match(CondVal,
3394 m_OneUse(m_c_And(m_Value(C), m_Not(m_Specific(FalseVal)))))) {
3395 Value *AndV = Builder.CreateSelect(C, TrueVal, Zero);
3396 return SelectInst::Create(FalseVal, One, AndV);
3397 }
3398
3399 if (match(FalseVal, m_Zero()) || match(TrueVal, m_One())) {
3400 Use *Y = nullptr;
3401 bool IsAnd = match(FalseVal, m_Zero()) ? true : false;
3402 Value *Op1 = IsAnd ? TrueVal : FalseVal;
3403 if (isCheckForZeroAndMulWithOverflow(CondVal, Op1, IsAnd, Y)) {
3404 auto *FI = new FreezeInst(*Y, (*Y)->getName() + ".fr");
3405 InsertNewInstBefore(FI, cast<Instruction>(Y->getUser())->getIterator());
3406 replaceUse(*Y, FI);
3407 return replaceInstUsesWith(SI, Op1);
3408 }
3409
3410 if (auto *V = foldBooleanAndOr(CondVal, Op1, SI, IsAnd,
3411 /*IsLogical=*/true))
3412 return replaceInstUsesWith(SI, V);
3413 }
3414
3415 // select (a || b), c, false -> select a, c, false
3416 // select c, (a || b), false -> select c, a, false
3417 // if c implies that b is false.
3418 if (match(CondVal, m_LogicalOr(m_Value(A), m_Value(B))) &&
3419 match(FalseVal, m_Zero())) {
3420 std::optional<bool> Res = isImpliedCondition(TrueVal, B, DL);
3421 if (Res && *Res == false)
3422 return replaceOperand(SI, 0, A);
3423 }
3424 if (match(TrueVal, m_LogicalOr(m_Value(A), m_Value(B))) &&
3425 match(FalseVal, m_Zero())) {
3426 std::optional<bool> Res = isImpliedCondition(CondVal, B, DL);
3427 if (Res && *Res == false)
3428 return replaceOperand(SI, 1, A);
3429 }
3430 // select c, true, (a && b) -> select c, true, a
3431 // select (a && b), true, c -> select a, true, c
3432 // if c = false implies that b = true
3433 if (match(TrueVal, m_One()) &&
3434 match(FalseVal, m_LogicalAnd(m_Value(A), m_Value(B)))) {
3435 std::optional<bool> Res = isImpliedCondition(CondVal, B, DL, false);
3436 if (Res && *Res == true)
3437 return replaceOperand(SI, 2, A);
3438 }
3439 if (match(CondVal, m_LogicalAnd(m_Value(A), m_Value(B))) &&
3440 match(TrueVal, m_One())) {
3441 std::optional<bool> Res = isImpliedCondition(FalseVal, B, DL, false);
3442 if (Res && *Res == true)
3443 return replaceOperand(SI, 0, A);
3444 }
3445
3446 if (match(TrueVal, m_One())) {
3447 Value *C;
3448
3449 // (C && A) || (!C && B) --> sel C, A, B
3450 // (A && C) || (!C && B) --> sel C, A, B
3451 // (C && A) || (B && !C) --> sel C, A, B
3452 // (A && C) || (B && !C) --> sel C, A, B (may require freeze)
3453 if (match(FalseVal, m_c_LogicalAnd(m_Not(m_Value(C)), m_Value(B))) &&
3454 match(CondVal, m_c_LogicalAnd(m_Specific(C), m_Value(A)))) {
3455 auto *SelCond = dyn_cast<SelectInst>(CondVal);
3456 auto *SelFVal = dyn_cast<SelectInst>(FalseVal);
3457 bool MayNeedFreeze = SelCond && SelFVal &&
3458 match(SelFVal->getTrueValue(),
3459 m_Not(m_Specific(SelCond->getTrueValue())));
3460 if (MayNeedFreeze)
3462 return SelectInst::Create(C, A, B);
3463 }
3464
3465 // (!C && A) || (C && B) --> sel C, B, A
3466 // (A && !C) || (C && B) --> sel C, B, A
3467 // (!C && A) || (B && C) --> sel C, B, A
3468 // (A && !C) || (B && C) --> sel C, B, A (may require freeze)
3469 if (match(CondVal, m_c_LogicalAnd(m_Not(m_Value(C)), m_Value(A))) &&
3470 match(FalseVal, m_c_LogicalAnd(m_Specific(C), m_Value(B)))) {
3471 auto *SelCond = dyn_cast<SelectInst>(CondVal);
3472 auto *SelFVal = dyn_cast<SelectInst>(FalseVal);
3473 bool MayNeedFreeze = SelCond && SelFVal &&
3474 match(SelCond->getTrueValue(),
3475 m_Not(m_Specific(SelFVal->getTrueValue())));
3476 if (MayNeedFreeze)
3478 return SelectInst::Create(C, B, A);
3479 }
3480 }
3481
3482 return nullptr;
3483}
3484
3485// Return true if we can safely remove the select instruction for std::bit_ceil
3486// pattern.
3487static bool isSafeToRemoveBitCeilSelect(ICmpInst::Predicate Pred, Value *Cond0,
3488 const APInt *Cond1, Value *CtlzOp,
3489 unsigned BitWidth,
3490 bool &ShouldDropNUW) {
3491 // The challenge in recognizing std::bit_ceil(X) is that the operand is used
3492 // for the CTLZ proper and select condition, each possibly with some
3493 // operation like add and sub.
3494 //
3495 // Our aim is to make sure that -ctlz & (BitWidth - 1) == 0 even when the
3496 // select instruction would select 1, which allows us to get rid of the select
3497 // instruction.
3498 //
3499 // To see if we can do so, we do some symbolic execution with ConstantRange.
3500 // Specifically, we compute the range of values that Cond0 could take when
3501 // Cond == false. Then we successively transform the range until we obtain
3502 // the range of values that CtlzOp could take.
3503 //
3504 // Conceptually, we follow the def-use chain backward from Cond0 while
3505 // transforming the range for Cond0 until we meet the common ancestor of Cond0
3506 // and CtlzOp. Then we follow the def-use chain forward until we obtain the
3507 // range for CtlzOp. That said, we only follow at most one ancestor from
3508 // Cond0. Likewise, we only follow at most one ancestor from CtrlOp.
3509
3511 CmpInst::getInversePredicate(Pred), *Cond1);
3512
3513 ShouldDropNUW = false;
3514
3515 // Match the operation that's used to compute CtlzOp from CommonAncestor. If
3516 // CtlzOp == CommonAncestor, return true as no operation is needed. If a
3517 // match is found, execute the operation on CR, update CR, and return true.
3518 // Otherwise, return false.
3519 auto MatchForward = [&](Value *CommonAncestor) {
3520 const APInt *C = nullptr;
3521 if (CtlzOp == CommonAncestor)
3522 return true;
3523 if (match(CtlzOp, m_Add(m_Specific(CommonAncestor), m_APInt(C)))) {
3524 CR = CR.add(*C);
3525 return true;
3526 }
3527 if (match(CtlzOp, m_Sub(m_APInt(C), m_Specific(CommonAncestor)))) {
3528 ShouldDropNUW = true;
3529 CR = ConstantRange(*C).sub(CR);
3530 return true;
3531 }
3532 if (match(CtlzOp, m_Not(m_Specific(CommonAncestor)))) {
3533 CR = CR.binaryNot();
3534 return true;
3535 }
3536 return false;
3537 };
3538
3539 const APInt *C = nullptr;
3540 Value *CommonAncestor;
3541 if (MatchForward(Cond0)) {
3542 // Cond0 is either CtlzOp or CtlzOp's parent. CR has been updated.
3543 } else if (match(Cond0, m_Add(m_Value(CommonAncestor), m_APInt(C)))) {
3544 CR = CR.sub(*C);
3545 if (!MatchForward(CommonAncestor))
3546 return false;
3547 // Cond0's parent is either CtlzOp or CtlzOp's parent. CR has been updated.
3548 } else {
3549 return false;
3550 }
3551
3552 // Return true if all the values in the range are either 0 or negative (if
3553 // treated as signed). We do so by evaluating:
3554 //
3555 // CR - 1 u>= (1 << BitWidth) - 1.
3556 APInt IntMax = APInt::getSignMask(BitWidth) - 1;
3557 CR = CR.sub(APInt(BitWidth, 1));
3558 return CR.icmp(ICmpInst::ICMP_UGE, IntMax);
3559}
3560
3561// Transform the std::bit_ceil(X) pattern like:
3562//
3563// %dec = add i32 %x, -1
3564// %ctlz = tail call i32 @llvm.ctlz.i32(i32 %dec, i1 false)
3565// %sub = sub i32 32, %ctlz
3566// %shl = shl i32 1, %sub
3567// %ugt = icmp ugt i32 %x, 1
3568// %sel = select i1 %ugt, i32 %shl, i32 1
3569//
3570// into:
3571//
3572// %dec = add i32 %x, -1
3573// %ctlz = tail call i32 @llvm.ctlz.i32(i32 %dec, i1 false)
3574// %neg = sub i32 0, %ctlz
3575// %masked = and i32 %ctlz, 31
3576// %shl = shl i32 1, %sub
3577//
3578// Note that the select is optimized away while the shift count is masked with
3579// 31. We handle some variations of the input operand like std::bit_ceil(X +
3580// 1).
3581static Instruction *foldBitCeil(SelectInst &SI, IRBuilderBase &Builder,
3582 InstCombinerImpl &IC) {
3583 Type *SelType = SI.getType();
3584 unsigned BitWidth = SelType->getScalarSizeInBits();
3585
3586 Value *FalseVal = SI.getFalseValue();
3587 Value *TrueVal = SI.getTrueValue();
3588 CmpPredicate Pred;
3589 const APInt *Cond1;
3590 Value *Cond0, *Ctlz, *CtlzOp;
3591 if (!match(SI.getCondition(), m_ICmp(Pred, m_Value(Cond0), m_APInt(Cond1))))
3592 return nullptr;
3593
3594 if (match(TrueVal, m_One())) {
3595 std::swap(FalseVal, TrueVal);
3596 Pred = CmpInst::getInversePredicate(Pred);
3597 }
3598
3599 bool ShouldDropNUW;
3600
3601 if (!match(FalseVal, m_One()) ||
3602 !match(TrueVal,
3604 m_Value(Ctlz)))))) ||
3605 !match(Ctlz, m_Intrinsic<Intrinsic::ctlz>(m_Value(CtlzOp), m_Zero())) ||
3606 !isSafeToRemoveBitCeilSelect(Pred, Cond0, Cond1, CtlzOp, BitWidth,
3607 ShouldDropNUW))
3608 return nullptr;
3609
3610 if (ShouldDropNUW)
3611 cast<Instruction>(CtlzOp)->setHasNoUnsignedWrap(false);
3612
3613 // Build 1 << (-CTLZ & (BitWidth-1)). The negation likely corresponds to a
3614 // single hardware instruction as opposed to BitWidth - CTLZ, where BitWidth
3615 // is an integer constant. Masking with BitWidth-1 comes free on some
3616 // hardware as part of the shift instruction.
3617
3618 // Drop range attributes and re-infer them in the next iteration.
3619 cast<Instruction>(Ctlz)->dropPoisonGeneratingAnnotations();
3620 IC.addToWorklist(cast<Instruction>(Ctlz));
3621 Value *Neg = Builder.CreateNeg(Ctlz);
3622 Value *Masked =
3623 Builder.CreateAnd(Neg, ConstantInt::get(SelType, BitWidth - 1));
3624 return BinaryOperator::Create(Instruction::Shl, ConstantInt::get(SelType, 1),
3625 Masked);
3626}
3627
3628// This function tries to fold the following operations:
3629// (x < y) ? -1 : zext(x != y)
3630// (x < y) ? -1 : zext(x > y)
3631// (x > y) ? 1 : sext(x != y)
3632// (x > y) ? 1 : sext(x < y)
3633// Into ucmp/scmp(x, y), where signedness is determined by the signedness
3634// of the comparison in the original sequence.
3636 Value *TV = SI.getTrueValue();
3637 Value *FV = SI.getFalseValue();
3638
3639 CmpPredicate Pred;
3640 Value *LHS, *RHS;
3641 if (!match(SI.getCondition(), m_ICmp(Pred, m_Value(LHS), m_Value(RHS))))
3642 return nullptr;
3643
3644 if (!LHS->getType()->isIntOrIntVectorTy())
3645 return nullptr;
3646
3647 // Try to swap operands and the predicate. We need to be careful when doing
3648 // so because two of the patterns have opposite predicates, so use the
3649 // constant inside select to determine if swapping operands would be
3650 // beneficial to us.
3651 if ((ICmpInst::isGT(Pred) && match(TV, m_AllOnes())) ||
3652 (ICmpInst::isLT(Pred) && match(TV, m_One()))) {
3653 Pred = ICmpInst::getSwappedPredicate(Pred);
3654 std::swap(LHS, RHS);
3655 }
3656 bool IsSigned = ICmpInst::isSigned(Pred);
3657
3658 bool Replace = false;
3659 CmpPredicate ExtendedCmpPredicate;
3660 // (x < y) ? -1 : zext(x != y)
3661 // (x < y) ? -1 : zext(x > y)
3662 if (ICmpInst::isLT(Pred) && match(TV, m_AllOnes()) &&
3663 match(FV, m_ZExt(m_c_ICmp(ExtendedCmpPredicate, m_Specific(LHS),
3664 m_Specific(RHS)))) &&
3665 (ExtendedCmpPredicate == ICmpInst::ICMP_NE ||
3666 ICmpInst::getSwappedPredicate(ExtendedCmpPredicate) == Pred))
3667 Replace = true;
3668
3669 // (x > y) ? 1 : sext(x != y)
3670 // (x > y) ? 1 : sext(x < y)
3671 if (ICmpInst::isGT(Pred) && match(TV, m_One()) &&
3672 match(FV, m_SExt(m_c_ICmp(ExtendedCmpPredicate, m_Specific(LHS),
3673 m_Specific(RHS)))) &&
3674 (ExtendedCmpPredicate == ICmpInst::ICMP_NE ||
3675 ICmpInst::getSwappedPredicate(ExtendedCmpPredicate) == Pred))
3676 Replace = true;
3677
3678 // (x == y) ? 0 : (x > y ? 1 : -1)
3679 CmpPredicate FalseBranchSelectPredicate;
3680 const APInt *InnerTV, *InnerFV;
3681 if (Pred == ICmpInst::ICMP_EQ && match(TV, m_Zero()) &&
3682 match(FV, m_Select(m_c_ICmp(FalseBranchSelectPredicate, m_Specific(LHS),
3683 m_Specific(RHS)),
3684 m_APInt(InnerTV), m_APInt(InnerFV)))) {
3685 if (!ICmpInst::isGT(FalseBranchSelectPredicate)) {
3686 FalseBranchSelectPredicate =
3687 ICmpInst::getSwappedPredicate(FalseBranchSelectPredicate);
3688 std::swap(LHS, RHS);
3689 }
3690
3691 if (!InnerTV->isOne()) {
3692 std::swap(InnerTV, InnerFV);
3693 std::swap(LHS, RHS);
3694 }
3695
3696 if (ICmpInst::isGT(FalseBranchSelectPredicate) && InnerTV->isOne() &&
3697 InnerFV->isAllOnes()) {
3698 IsSigned = ICmpInst::isSigned(FalseBranchSelectPredicate);
3699 Replace = true;
3700 }
3701 }
3702
3703 Intrinsic::ID IID = IsSigned ? Intrinsic::scmp : Intrinsic::ucmp;
3704 if (Replace)
3705 return replaceInstUsesWith(
3706 SI, Builder.CreateIntrinsic(SI.getType(), IID, {LHS, RHS}));
3707 return nullptr;
3708}
3709
3711 const Instruction *CtxI) const {
3712 KnownFPClass Known = computeKnownFPClass(MulVal, FMF, fcNegative, CtxI);
3713
3714 return Known.isKnownNeverNaN() && Known.isKnownNeverInfinity() &&
3715 (FMF.noSignedZeros() || Known.signBitIsZeroOrNaN());
3716}
3717
3718static bool matchFMulByZeroIfResultEqZero(InstCombinerImpl &IC, Value *Cmp0,
3719 Value *Cmp1, Value *TrueVal,
3720 Value *FalseVal, Instruction &CtxI,
3721 bool SelectIsNSZ) {
3722 Value *MulRHS;
3723 if (match(Cmp1, m_PosZeroFP()) &&
3724 match(TrueVal, m_c_FMul(m_Specific(Cmp0), m_Value(MulRHS)))) {
3725 FastMathFlags FMF = cast<FPMathOperator>(TrueVal)->getFastMathFlags();
3726 // nsz must be on the select, it must be ignored on the multiply. We
3727 // need nnan and ninf on the multiply for the other value.
3728 FMF.setNoSignedZeros(SelectIsNSZ);
3729 return IC.fmulByZeroIsZero(MulRHS, FMF, &CtxI);
3730 }
3731
3732 return false;
3733}
3734
3735/// Check whether the KnownBits of a select arm may be affected by the
3736/// select condition.
3737static bool hasAffectedValue(Value *V, SmallPtrSetImpl<Value *> &Affected,
3738 unsigned Depth) {
3740 return false;
3741
3742 // Ignore the case where the select arm itself is affected. These cases
3743 // are handled more efficiently by other optimizations.
3744 if (Depth != 0 && Affected.contains(V))
3745 return true;
3746
3747 if (auto *I = dyn_cast<Instruction>(V)) {
3748 if (isa<PHINode>(I)) {
3750 return false;
3752 }
3753 return any_of(I->operands(), [&](Value *Op) {
3754 return Op->getType()->isIntOrIntVectorTy() &&
3755 hasAffectedValue(Op, Affected, Depth + 1);
3756 });
3757 }
3758
3759 return false;
3760}
3761
3762// This transformation enables the possibility of transforming fcmp + sel into
3763// a fmaxnum/fminnum intrinsic.
3764static Value *foldSelectIntoAddConstant(SelectInst &SI,
3765 InstCombiner::BuilderTy &Builder) {
3766 // Do this transformation only when select instruction gives NaN and NSZ
3767 // guarantee.
3768 auto *SIFOp = dyn_cast<FPMathOperator>(&SI);
3769 if (!SIFOp || !SIFOp->hasNoSignedZeros() || !SIFOp->hasNoNaNs())
3770 return nullptr;
3771
3772 auto TryFoldIntoAddConstant =
3773 [&Builder, &SI](CmpInst::Predicate Pred, Value *X, Value *Z,
3774 Instruction *FAdd, Constant *C, bool Swapped) -> Value * {
3775 // Only these relational predicates can be transformed into maxnum/minnum
3776 // intrinsic.
3777 if (!CmpInst::isRelational(Pred) || !match(Z, m_AnyZeroFP()))
3778 return nullptr;
3779
3781 return nullptr;
3782
3783 Value *NewSelect = Builder.CreateSelect(SI.getCondition(), Swapped ? Z : X,
3784 Swapped ? X : Z, "", &SI);
3785 NewSelect->takeName(&SI);
3786
3787 Value *NewFAdd = Builder.CreateFAdd(NewSelect, C);
3788 NewFAdd->takeName(FAdd);
3789
3790 // Propagate FastMath flags
3791 FastMathFlags SelectFMF = SI.getFastMathFlags();
3792 FastMathFlags FAddFMF = FAdd->getFastMathFlags();
3793 FastMathFlags NewFMF = FastMathFlags::intersectRewrite(SelectFMF, FAddFMF) |
3794 FastMathFlags::unionValue(SelectFMF, FAddFMF);
3795 cast<Instruction>(NewFAdd)->setFastMathFlags(NewFMF);
3796 cast<Instruction>(NewSelect)->setFastMathFlags(NewFMF);
3797
3798 return NewFAdd;
3799 };
3800
3801 // select((fcmp Pred, X, 0), (fadd X, C), C)
3802 // => fadd((select (fcmp Pred, X, 0), X, 0), C)
3803 //
3804 // Pred := OGT, OGE, OLT, OLE, UGT, UGE, ULT, and ULE
3806 Constant *C;
3807 Value *X, *Z;
3808 CmpPredicate Pred;
3809
3810 // Note: OneUse check for `Cmp` is necessary because it makes sure that other
3811 // InstCombine folds don't undo this transformation and cause an infinite
3812 // loop. Furthermore, it could also increase the operation count.
3813 if (match(&SI, m_Select(m_OneUse(m_FCmp(Pred, m_Value(X), m_Value(Z))),
3815 return TryFoldIntoAddConstant(Pred, X, Z, FAdd, C, /*Swapped=*/false);
3816
3817 if (match(&SI, m_Select(m_OneUse(m_FCmp(Pred, m_Value(X), m_Value(Z))),
3819 return TryFoldIntoAddConstant(Pred, X, Z, FAdd, C, /*Swapped=*/true);
3820
3821 return nullptr;
3822}
3823
3825 Value *CondVal = SI.getCondition();
3826 Value *TrueVal = SI.getTrueValue();
3827 Value *FalseVal = SI.getFalseValue();
3828 Type *SelType = SI.getType();
3829
3830 if (Value *V = simplifySelectInst(CondVal, TrueVal, FalseVal,
3831 SQ.getWithInstruction(&SI)))
3832 return replaceInstUsesWith(SI, V);
3833
3834 if (Instruction *I = canonicalizeSelectToShuffle(SI))
3835 return I;
3836
3837 if (Instruction *I = canonicalizeScalarSelectOfVecs(SI, *this))
3838 return I;
3839
3840 // If the type of select is not an integer type or if the condition and
3841 // the selection type are not both scalar nor both vector types, there is no
3842 // point in attempting to match these patterns.
3843 Type *CondType = CondVal->getType();
3844 if (!isa<Constant>(CondVal) && SelType->isIntOrIntVectorTy() &&
3845 CondType->isVectorTy() == SelType->isVectorTy()) {
3846 if (Value *S = simplifyWithOpReplaced(TrueVal, CondVal,
3847 ConstantInt::getTrue(CondType), SQ,
3848 /* AllowRefinement */ true))
3849 return replaceOperand(SI, 1, S);
3850
3851 if (Value *S = simplifyWithOpReplaced(FalseVal, CondVal,
3852 ConstantInt::getFalse(CondType), SQ,
3853 /* AllowRefinement */ true))
3854 return replaceOperand(SI, 2, S);
3855
3856 if (replaceInInstruction(TrueVal, CondVal,
3857 ConstantInt::getTrue(CondType)) ||
3858 replaceInInstruction(FalseVal, CondVal,
3859 ConstantInt::getFalse(CondType)))
3860 return &SI;
3861 }
3862
3863 if (Instruction *R = foldSelectOfBools(SI))
3864 return R;
3865
3866 // Selecting between two integer or vector splat integer constants?
3867 //
3868 // Note that we don't handle a scalar select of vectors:
3869 // select i1 %c, <2 x i8> <1, 1>, <2 x i8> <0, 0>
3870 // because that may need 3 instructions to splat the condition value:
3871 // extend, insertelement, shufflevector.
3872 //
3873 // Do not handle i1 TrueVal and FalseVal otherwise would result in
3874 // zext/sext i1 to i1.
3875 if (SelType->isIntOrIntVectorTy() && !SelType->isIntOrIntVectorTy(1) &&
3876 CondVal->getType()->isVectorTy() == SelType->isVectorTy()) {
3877 // select C, 1, 0 -> zext C to int
3878 if (match(TrueVal, m_One()) && match(FalseVal, m_Zero()))
3879 return new ZExtInst(CondVal, SelType);
3880
3881 // select C, -1, 0 -> sext C to int
3882 if (match(TrueVal, m_AllOnes()) && match(FalseVal, m_Zero()))
3883 return new SExtInst(CondVal, SelType);
3884
3885 // select C, 0, 1 -> zext !C to int
3886 if (match(TrueVal, m_Zero()) && match(FalseVal, m_One())) {
3887 Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName());
3888 return new ZExtInst(NotCond, SelType);
3889 }
3890
3891 // select C, 0, -1 -> sext !C to int
3892 if (match(TrueVal, m_Zero()) && match(FalseVal, m_AllOnes())) {
3893 Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName());
3894 return new SExtInst(NotCond, SelType);
3895 }
3896 }
3897
3898 auto *SIFPOp = dyn_cast<FPMathOperator>(&SI);
3899
3900 if (auto *FCmp = dyn_cast<FCmpInst>(CondVal)) {
3901 FCmpInst::Predicate Pred = FCmp->getPredicate();
3902 Value *Cmp0 = FCmp->getOperand(0), *Cmp1 = FCmp->getOperand(1);
3903 // Are we selecting a value based on a comparison of the two values?
3904 if ((Cmp0 == TrueVal && Cmp1 == FalseVal) ||
3905 (Cmp0 == FalseVal && Cmp1 == TrueVal)) {
3906 // Canonicalize to use ordered comparisons by swapping the select
3907 // operands.
3908 //
3909 // e.g.
3910 // (X ugt Y) ? X : Y -> (X ole Y) ? Y : X
3911 if (FCmp->hasOneUse() && FCmpInst::isUnordered(Pred)) {
3912 FCmpInst::Predicate InvPred = FCmp->getInversePredicate();
3914 // FIXME: The FMF should propagate from the select, not the fcmp.
3915 Builder.setFastMathFlags(FCmp->getFastMathFlags());
3916 Value *NewCond = Builder.CreateFCmp(InvPred, Cmp0, Cmp1,
3917 FCmp->getName() + ".inv");
3918 Value *NewSel = Builder.CreateSelect(NewCond, FalseVal, TrueVal);
3919 return replaceInstUsesWith(SI, NewSel);
3920 }
3921 }
3922
3923 if (SIFPOp) {
3924 // Fold out scale-if-equals-zero pattern.
3925 //
3926 // This pattern appears in code with denormal range checks after it's
3927 // assumed denormals are treated as zero. This drops a canonicalization.
3928
3929 // TODO: Could relax the signed zero logic. We just need to know the sign
3930 // of the result matches (fmul x, y has the same sign as x).
3931 //
3932 // TODO: Handle always-canonicalizing variant that selects some value or 1
3933 // scaling factor in the fmul visitor.
3934
3935 // TODO: Handle ldexp too
3936
3937 Value *MatchCmp0 = nullptr;
3938 Value *MatchCmp1 = nullptr;
3939
3940 // (select (fcmp [ou]eq x, 0.0), (fmul x, K), x => x
3941 // (select (fcmp [ou]ne x, 0.0), x, (fmul x, K) => x
3942 if (Pred == CmpInst::FCMP_OEQ || Pred == CmpInst::FCMP_UEQ) {
3943 MatchCmp0 = FalseVal;
3944 MatchCmp1 = TrueVal;
3945 } else if (Pred == CmpInst::FCMP_ONE || Pred == CmpInst::FCMP_UNE) {
3946 MatchCmp0 = TrueVal;
3947 MatchCmp1 = FalseVal;
3948 }
3949
3950 if (Cmp0 == MatchCmp0 &&
3951 matchFMulByZeroIfResultEqZero(*this, Cmp0, Cmp1, MatchCmp1, MatchCmp0,
3952 SI, SIFPOp->hasNoSignedZeros()))
3953 return replaceInstUsesWith(SI, Cmp0);
3954 }
3955 }
3956
3957 if (SIFPOp) {
3958 // TODO: Try to forward-propagate FMF from select arms to the select.
3959
3960 auto *FCmp = dyn_cast<FCmpInst>(CondVal);
3961
3962 // Canonicalize select of FP values where NaN and -0.0 are not valid as
3963 // minnum/maxnum intrinsics.
3964 if (SIFPOp->hasNoNaNs() && SIFPOp->hasNoSignedZeros()) {
3965 Value *X, *Y;
3966 if (match(&SI, m_OrdOrUnordFMax(m_Value(X), m_Value(Y)))) {
3967 Value *BinIntr =
3968 Builder.CreateBinaryIntrinsic(Intrinsic::maxnum, X, Y, &SI);
3969 if (auto *BinIntrInst = dyn_cast<Instruction>(BinIntr))
3970 BinIntrInst->setHasNoNaNs(FCmp->hasNoNaNs());
3971 return replaceInstUsesWith(SI, BinIntr);
3972 }
3973
3974 if (match(&SI, m_OrdOrUnordFMin(m_Value(X), m_Value(Y)))) {
3975 Value *BinIntr =
3976 Builder.CreateBinaryIntrinsic(Intrinsic::minnum, X, Y, &SI);
3977 if (auto *BinIntrInst = dyn_cast<Instruction>(BinIntr))
3978 BinIntrInst->setHasNoNaNs(FCmp->hasNoNaNs());
3979 return replaceInstUsesWith(SI, BinIntr);
3980 }
3981 }
3982 }
3983
3984 // Fold selecting to fabs.
3985 if (Instruction *Fabs = foldSelectWithFCmpToFabs(SI, *this))
3986 return Fabs;
3987
3988 // See if we are selecting two values based on a comparison of the two values.
3989 if (CmpInst *CI = dyn_cast<CmpInst>(CondVal))
3990 if (Instruction *NewSel = foldSelectValueEquivalence(SI, *CI))
3991 return NewSel;
3992
3993 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
3994 if (Instruction *Result = foldSelectInstWithICmp(SI, ICI))
3995 return Result;
3996
3997 if (Instruction *Add = foldAddSubSelect(SI, Builder))
3998 return Add;
3999 if (Instruction *Add = foldOverflowingAddSubSelect(SI, Builder))
4000 return Add;
4002 return Or;
4003 if (Instruction *Mul = foldSelectZeroOrMul(SI, *this))
4004 return Mul;
4005
4006 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
4007 auto *TI = dyn_cast<Instruction>(TrueVal);
4008 auto *FI = dyn_cast<Instruction>(FalseVal);
4009 if (TI && FI && TI->getOpcode() == FI->getOpcode())
4010 if (Instruction *IV = foldSelectOpOp(SI, TI, FI))
4011 return IV;
4012
4013 if (Instruction *I = foldSelectExtConst(SI))
4014 return I;
4015
4016 if (Instruction *I = foldSelectWithSRem(SI, *this, Builder))
4017 return I;
4018
4019 // Fold (select C, (gep Ptr, Idx), Ptr) -> (gep Ptr, (select C, Idx, 0))
4020 // Fold (select C, Ptr, (gep Ptr, Idx)) -> (gep Ptr, (select C, 0, Idx))
4021 auto SelectGepWithBase = [&](GetElementPtrInst *Gep, Value *Base,
4022 bool Swap) -> GetElementPtrInst * {
4023 Value *Ptr = Gep->getPointerOperand();
4024 if (Gep->getNumOperands() != 2 || Gep->getPointerOperand() != Base ||
4025 !Gep->hasOneUse())
4026 return nullptr;
4027 Value *Idx = Gep->getOperand(1);
4028 if (isa<VectorType>(CondVal->getType()) && !isa<VectorType>(Idx->getType()))
4029 return nullptr;
4031 Value *NewT = Idx;
4032 Value *NewF = Constant::getNullValue(Idx->getType());
4033 if (Swap)
4034 std::swap(NewT, NewF);
4035 Value *NewSI =
4036 Builder.CreateSelect(CondVal, NewT, NewF, SI.getName() + ".idx", &SI);
4037 return GetElementPtrInst::Create(ElementType, Ptr, NewSI,
4038 Gep->getNoWrapFlags());
4039 };
4040 if (auto *TrueGep = dyn_cast<GetElementPtrInst>(TrueVal))
4041 if (auto *NewGep = SelectGepWithBase(TrueGep, FalseVal, false))
4042 return NewGep;
4043 if (auto *FalseGep = dyn_cast<GetElementPtrInst>(FalseVal))
4044 if (auto *NewGep = SelectGepWithBase(FalseGep, TrueVal, true))
4045 return NewGep;
4046
4047 // See if we can fold the select into one of our operands.
4048 if (SelType->isIntOrIntVectorTy() || SelType->isFPOrFPVectorTy()) {
4049 if (Instruction *FoldI = foldSelectIntoOp(SI, TrueVal, FalseVal))
4050 return FoldI;
4051
4052 Value *LHS, *RHS;
4053 Instruction::CastOps CastOp;
4054 SelectPatternResult SPR = matchSelectPattern(&SI, LHS, RHS, &CastOp);
4055 auto SPF = SPR.Flavor;
4056 if (SPF) {
4057 Value *LHS2, *RHS2;
4058 if (SelectPatternFlavor SPF2 = matchSelectPattern(LHS, LHS2, RHS2).Flavor)
4059 if (Instruction *R = foldSPFofSPF(cast<Instruction>(LHS), SPF2, LHS2,
4060 RHS2, SI, SPF, RHS))
4061 return R;
4062 if (SelectPatternFlavor SPF2 = matchSelectPattern(RHS, LHS2, RHS2).Flavor)
4063 if (Instruction *R = foldSPFofSPF(cast<Instruction>(RHS), SPF2, LHS2,
4064 RHS2, SI, SPF, LHS))
4065 return R;
4066 }
4067
4069 // Canonicalize so that
4070 // - type casts are outside select patterns.
4071 // - float clamp is transformed to min/max pattern
4072
4073 bool IsCastNeeded = LHS->getType() != SelType;
4074 Value *CmpLHS = cast<CmpInst>(CondVal)->getOperand(0);
4075 Value *CmpRHS = cast<CmpInst>(CondVal)->getOperand(1);
4076 if (IsCastNeeded ||
4077 (LHS->getType()->isFPOrFPVectorTy() &&
4078 ((CmpLHS != LHS && CmpLHS != RHS) ||
4079 (CmpRHS != LHS && CmpRHS != RHS)))) {
4080 CmpInst::Predicate MinMaxPred = getMinMaxPred(SPF, SPR.Ordered);
4081
4082 Value *Cmp;
4083 if (CmpInst::isIntPredicate(MinMaxPred)) {
4084 Cmp = Builder.CreateICmp(MinMaxPred, LHS, RHS);
4085 } else {
4087 auto FMF =
4088 cast<FPMathOperator>(SI.getCondition())->getFastMathFlags();
4090 Cmp = Builder.CreateFCmp(MinMaxPred, LHS, RHS);
4091 }
4092
4093 Value *NewSI = Builder.CreateSelect(Cmp, LHS, RHS, SI.getName(), &SI);
4094 if (!IsCastNeeded)
4095 return replaceInstUsesWith(SI, NewSI);
4096
4097 Value *NewCast = Builder.CreateCast(CastOp, NewSI, SelType);
4098 return replaceInstUsesWith(SI, NewCast);
4099 }
4100 }
4101 }
4102
4103 // See if we can fold the select into a phi node if the condition is a select.
4104 if (auto *PN = dyn_cast<PHINode>(SI.getCondition()))
4105 if (Instruction *NV = foldOpIntoPhi(SI, PN))
4106 return NV;
4107
4108 if (SelectInst *TrueSI = dyn_cast<SelectInst>(TrueVal)) {
4109 if (TrueSI->getCondition()->getType() == CondVal->getType()) {
4110 // Fold nested selects if the inner condition can be implied by the outer
4111 // condition.
4112 if (Value *V = simplifyNestedSelectsUsingImpliedCond(
4113 *TrueSI, CondVal, /*CondIsTrue=*/true, DL))
4114 return replaceOperand(SI, 1, V);
4115
4116 // select(C0, select(C1, a, b), b) -> select(C0&C1, a, b)
4117 // We choose this as normal form to enable folding on the And and
4118 // shortening paths for the values (this helps getUnderlyingObjects() for
4119 // example).
4120 if (TrueSI->getFalseValue() == FalseVal && TrueSI->hasOneUse()) {
4121 Value *And = Builder.CreateLogicalAnd(CondVal, TrueSI->getCondition());
4122 replaceOperand(SI, 0, And);
4123 replaceOperand(SI, 1, TrueSI->getTrueValue());
4124 return &SI;
4125 }
4126 }
4127 }
4128 if (SelectInst *FalseSI = dyn_cast<SelectInst>(FalseVal)) {
4129 if (FalseSI->getCondition()->getType() == CondVal->getType()) {
4130 // Fold nested selects if the inner condition can be implied by the outer
4131 // condition.
4132 if (Value *V = simplifyNestedSelectsUsingImpliedCond(
4133 *FalseSI, CondVal, /*CondIsTrue=*/false, DL))
4134 return replaceOperand(SI, 2, V);
4135
4136 // select(C0, a, select(C1, a, b)) -> select(C0|C1, a, b)
4137 if (FalseSI->getTrueValue() == TrueVal && FalseSI->hasOneUse()) {
4138 Value *Or = Builder.CreateLogicalOr(CondVal, FalseSI->getCondition());
4139 replaceOperand(SI, 0, Or);
4140 replaceOperand(SI, 2, FalseSI->getFalseValue());
4141 return &SI;
4142 }
4143 }
4144 }
4145
4146 // Try to simplify a binop sandwiched between 2 selects with the same
4147 // condition. This is not valid for div/rem because the select might be
4148 // preventing a division-by-zero.
4149 // TODO: A div/rem restriction is conservative; use something like
4150 // isSafeToSpeculativelyExecute().
4151 // select(C, binop(select(C, X, Y), W), Z) -> select(C, binop(X, W), Z)
4152 BinaryOperator *TrueBO;
4153 if (match(TrueVal, m_OneUse(m_BinOp(TrueBO))) && !TrueBO->isIntDivRem()) {
4154 if (auto *TrueBOSI = dyn_cast<SelectInst>(TrueBO->getOperand(0))) {
4155 if (TrueBOSI->getCondition() == CondVal) {
4156 replaceOperand(*TrueBO, 0, TrueBOSI->getTrueValue());
4157 Worklist.push(TrueBO);
4158 return &SI;
4159 }
4160 }
4161 if (auto *TrueBOSI = dyn_cast<SelectInst>(TrueBO->getOperand(1))) {
4162 if (TrueBOSI->getCondition() == CondVal) {
4163 replaceOperand(*TrueBO, 1, TrueBOSI->getTrueValue());
4164 Worklist.push(TrueBO);
4165 return &SI;
4166 }
4167 }
4168 }
4169
4170 // select(C, Z, binop(select(C, X, Y), W)) -> select(C, Z, binop(Y, W))
4171 BinaryOperator *FalseBO;
4172 if (match(FalseVal, m_OneUse(m_BinOp(FalseBO))) && !FalseBO->isIntDivRem()) {
4173 if (auto *FalseBOSI = dyn_cast<SelectInst>(FalseBO->getOperand(0))) {
4174 if (FalseBOSI->getCondition() == CondVal) {
4175 replaceOperand(*FalseBO, 0, FalseBOSI->getFalseValue());
4176 Worklist.push(FalseBO);
4177 return &SI;
4178 }
4179 }
4180 if (auto *FalseBOSI = dyn_cast<SelectInst>(FalseBO->getOperand(1))) {
4181 if (FalseBOSI->getCondition() == CondVal) {
4182 replaceOperand(*FalseBO, 1, FalseBOSI->getFalseValue());
4183 Worklist.push(FalseBO);
4184 return &SI;
4185 }
4186 }
4187 }
4188
4189 Value *NotCond;
4190 if (match(CondVal, m_Not(m_Value(NotCond))) &&
4192 replaceOperand(SI, 0, NotCond);
4193 SI.swapValues();
4194 SI.swapProfMetadata();
4195 return &SI;
4196 }
4197
4198 if (Instruction *I = foldVectorSelect(SI))
4199 return I;
4200
4201 // If we can compute the condition, there's no need for a select.
4202 // Like the above fold, we are attempting to reduce compile-time cost by
4203 // putting this fold here with limitations rather than in InstSimplify.
4204 // The motivation for this call into value tracking is to take advantage of
4205 // the assumption cache, so make sure that is populated.
4206 if (!CondVal->getType()->isVectorTy() && !AC.assumptions().empty()) {
4207 KnownBits Known(1);
4208 computeKnownBits(CondVal, Known, 0, &SI);
4209 if (Known.One.isOne())
4210 return replaceInstUsesWith(SI, TrueVal);
4211 if (Known.Zero.isOne())
4212 return replaceInstUsesWith(SI, FalseVal);
4213 }
4214
4215 if (Instruction *BitCastSel = foldSelectCmpBitcasts(SI, Builder))
4216 return BitCastSel;
4217
4218 // Simplify selects that test the returned flag of cmpxchg instructions.
4219 if (Value *V = foldSelectCmpXchg(SI))
4220 return replaceInstUsesWith(SI, V);
4221
4222 if (Instruction *Select = foldSelectBinOpIdentity(SI, TLI, *this))
4223 return Select;
4224
4225 if (Instruction *Funnel = foldSelectFunnelShift(SI, Builder))
4226 return Funnel;
4227
4228 if (Instruction *Copysign = foldSelectToCopysign(SI, Builder))
4229 return Copysign;
4230
4231 if (Instruction *PN = foldSelectToPhi(SI, DT, Builder))
4232 return replaceInstUsesWith(SI, PN);
4233
4234 if (Value *Fr = foldSelectWithFrozenICmp(SI, Builder))
4235 return replaceInstUsesWith(SI, Fr);
4236
4237 if (Value *V = foldRoundUpIntegerWithPow2Alignment(SI, Builder))
4238 return replaceInstUsesWith(SI, V);
4239
4240 if (Value *V = foldSelectIntoAddConstant(SI, Builder))
4241 return replaceInstUsesWith(SI, V);
4242
4243 // select(mask, mload(,,mask,0), 0) -> mload(,,mask,0)
4244 // Load inst is intentionally not checked for hasOneUse()
4245 if (match(FalseVal, m_Zero()) &&
4246 (match(TrueVal, m_MaskedLoad(m_Value(), m_Value(), m_Specific(CondVal),
4247 m_CombineOr(m_Undef(), m_Zero()))) ||
4248 match(TrueVal, m_MaskedGather(m_Value(), m_Value(), m_Specific(CondVal),
4249 m_CombineOr(m_Undef(), m_Zero()))))) {
4250 auto *MaskedInst = cast<IntrinsicInst>(TrueVal);
4251 if (isa<UndefValue>(MaskedInst->getArgOperand(3)))
4252 MaskedInst->setArgOperand(3, FalseVal /* Zero */);
4253 return