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"
16#include "llvm/ADT/SmallVector.h"
17#include "llvm/Analysis/AssumptionCache.h"
18#include "llvm/Analysis/CmpInstAnalysis.h"
19#include "llvm/Analysis/InstructionSimplify.h"
20#include "llvm/Analysis/Loads.h"
21#include "llvm/Analysis/OverflowInstAnalysis.h"
22#include "llvm/Analysis/ValueTracking.h"
23#include "llvm/Analysis/VectorUtils.h"
24#include "llvm/IR/BasicBlock.h"
25#include "llvm/IR/Constant.h"
26#include "llvm/IR/ConstantRange.h"
27#include "llvm/IR/Constants.h"
28#include "llvm/IR/DerivedTypes.h"
29#include "llvm/IR/FMF.h"
30#include "llvm/IR/IRBuilder.h"
31#include "llvm/IR/InstrTypes.h"
32#include "llvm/IR/Instruction.h"
33#include "llvm/IR/Instructions.h"
34#include "llvm/IR/IntrinsicInst.h"
35#include "llvm/IR/Intrinsics.h"
36#include "llvm/IR/Operator.h"
37#include "llvm/IR/PatternMatch.h"
38#include "llvm/IR/ProfDataUtils.h"
39#include "llvm/IR/Type.h"
40#include "llvm/IR/User.h"
41#include "llvm/IR/Value.h"
42#include "llvm/Support/Casting.h"
43#include "llvm/Support/ErrorHandling.h"
44#include "llvm/Support/KnownBits.h"
45#include "llvm/Support/MathExtras.h"
46#include "llvm/Transforms/InstCombine/InstCombiner.h"
47#include <cassert>
48#include <optional>
49#include <utility>
50
51#define DEBUG_TYPE "instcombine"
52#include "llvm/Transforms/Utils/InstructionWorklist.h"
53
54using namespace llvm;
55using namespace PatternMatch;
56
57namespace llvm {
58extern cl::opt<bool> ProfcheckDisableMetadataFixes;
59}
60
61/// Replace a select operand based on an equality comparison with the identity
62/// constant of a binop.
63static Instruction *foldSelectBinOpIdentity(SelectInst &Sel,
64 const TargetLibraryInfo &TLI,
65 InstCombinerImpl &IC) {
66 // The select condition must be an equality compare with a constant operand.
67 Value *X;
68 Constant *C;
69 CmpPredicate Pred;
70 if (!match(V: Sel.getCondition(), P: m_Cmp(Pred, L: m_Value(V&: X), R: m_Constant(C))))
71 return nullptr;
72
73 bool IsEq;
74 if (ICmpInst::isEquality(P: Pred))
75 IsEq = Pred == ICmpInst::ICMP_EQ;
76 else if (Pred == FCmpInst::FCMP_OEQ)
77 IsEq = true;
78 else if (Pred == FCmpInst::FCMP_UNE)
79 IsEq = false;
80 else
81 return nullptr;
82
83 // A select operand must be a binop.
84 BinaryOperator *BO;
85 if (!match(V: Sel.getOperand(i_nocapture: IsEq ? 1 : 2), P: m_BinOp(I&: BO)))
86 return nullptr;
87
88 // For absorbing values, we can fold to the compared value.
89 bool IsAbsorbingValue = false;
90
91 // Last, match the compare variable operand with a binop operand.
92 Value *Y;
93 if (BO->isCommutative()) {
94 // Recognized 0 as an absorbing value for fmul, but we need to be careful
95 // about the sign. This could be more aggressive, by handling arbitrary sign
96 // bit operations as long as we know the fmul sign matches (and handling
97 // arbitrary opcodes).
98 if (match(V: BO, P: m_c_FMul(L: m_FAbs(Op0: m_Specific(V: X)), R: m_Value(V&: Y))) &&
99 match(V: C, P: m_AnyZeroFP()) &&
100 IC.fmulByZeroIsZero(MulVal: Y, FMF: BO->getFastMathFlags(), CtxI: &Sel))
101 IsAbsorbingValue = true;
102 else if (!match(V: BO, P: m_c_BinOp(L: m_Value(V&: Y), R: m_Specific(V: X))))
103 return nullptr;
104 } else {
105 if (!match(V: BO, P: m_BinOp(L: m_Value(V&: Y), R: m_Specific(V: X))))
106 return nullptr;
107 }
108
109 // The compare constant must be the identity constant for that binop.
110 // If this a floating-point compare with 0.0, any zero constant will do.
111 Type *Ty = BO->getType();
112
113 Value *FoldedVal;
114 if (IsAbsorbingValue) {
115 FoldedVal = C;
116 } else {
117 Constant *IdC = ConstantExpr::getBinOpIdentity(Opcode: BO->getOpcode(), Ty, AllowRHSConstant: true);
118 if (IdC != C) {
119 if (!IdC || !CmpInst::isFPPredicate(P: Pred))
120 return nullptr;
121
122 if (!match(V: IdC, P: m_AnyZeroFP()) || !match(V: C, P: m_AnyZeroFP()))
123 return nullptr;
124 }
125
126 // +0.0 compares equal to -0.0, and so it does not behave as required for
127 // this transform. Bail out if we can not exclude that possibility.
128 if (const auto *FPO = dyn_cast<FPMathOperator>(Val: BO))
129 if (!FPO->hasNoSignedZeros() &&
130 !cannotBeNegativeZero(V: Y,
131 SQ: IC.getSimplifyQuery().getWithInstruction(I: &Sel)))
132 return nullptr;
133
134 FoldedVal = Y;
135 }
136
137 // BO = binop Y, X
138 // S = { select (cmp eq X, C), BO, ? } or { select (cmp ne X, C), ?, BO }
139 // =>
140 // S = { select (cmp eq X, C), Y, ? } or { select (cmp ne X, C), ?, Y }
141 return IC.replaceOperand(I&: Sel, OpNum: IsEq ? 1 : 2, V: FoldedVal);
142}
143
144/// This folds:
145/// select (icmp eq (and X, C1)), TC, FC
146/// iff C1 is a power 2 and the difference between TC and FC is a power-of-2.
147/// To something like:
148/// (shr (and (X, C1)), (log2(C1) - log2(TC-FC))) + FC
149/// Or:
150/// (shl (and (X, C1)), (log2(TC-FC) - log2(C1))) + FC
151/// With some variations depending if FC is larger than TC, or the shift
152/// isn't needed, or the bit widths don't match.
153static Value *foldSelectICmpAnd(SelectInst &Sel, Value *CondVal, Value *TrueVal,
154 Value *FalseVal, Value *V, const APInt &AndMask,
155 bool CreateAnd,
156 InstCombiner::BuilderTy &Builder) {
157 const APInt *SelTC, *SelFC;
158 if (!match(V: TrueVal, P: m_APInt(Res&: SelTC)) || !match(V: FalseVal, P: m_APInt(Res&: SelFC)))
159 return nullptr;
160
161 Type *SelType = Sel.getType();
162 // In general, when both constants are non-zero, we would need an offset to
163 // replace the select. This would require more instructions than we started
164 // with. But there's one special-case that we handle here because it can
165 // simplify/reduce the instructions.
166 const APInt &TC = *SelTC;
167 const APInt &FC = *SelFC;
168 if (!TC.isZero() && !FC.isZero()) {
169 if (TC.getBitWidth() != AndMask.getBitWidth())
170 return nullptr;
171 // If we have to create an 'and', then we must kill the cmp to not
172 // increase the instruction count.
173 if (CreateAnd && !CondVal->hasOneUse())
174 return nullptr;
175
176 // (V & AndMaskC) == 0 ? TC : FC --> TC | (V & AndMaskC)
177 // (V & AndMaskC) == 0 ? TC : FC --> TC ^ (V & AndMaskC)
178 // (V & AndMaskC) == 0 ? TC : FC --> TC + (V & AndMaskC)
179 // (V & AndMaskC) == 0 ? TC : FC --> TC - (V & AndMaskC)
180 Constant *TCC = ConstantInt::get(Ty: SelType, V: TC);
181 Constant *FCC = ConstantInt::get(Ty: SelType, V: FC);
182 Constant *MaskC = ConstantInt::get(Ty: SelType, V: AndMask);
183 for (auto Opc : {Instruction::Or, Instruction::Xor, Instruction::Add,
184 Instruction::Sub}) {
185 if (ConstantFoldBinaryOpOperands(Opcode: Opc, LHS: TCC, RHS: MaskC, DL: Sel.getDataLayout()) ==
186 FCC) {
187 if (CreateAnd)
188 V = Builder.CreateAnd(LHS: V, RHS: MaskC);
189 return Builder.CreateBinOp(Opc, LHS: TCC, RHS: V);
190 }
191 }
192
193 return nullptr;
194 }
195
196 // Make sure one of the select arms is a power-of-2.
197 if (!TC.isPowerOf2() && !FC.isPowerOf2())
198 return nullptr;
199
200 // Determine which shift is needed to transform result of the 'and' into the
201 // desired result.
202 const APInt &ValC = !TC.isZero() ? TC : FC;
203 unsigned ValZeros = ValC.logBase2();
204 unsigned AndZeros = AndMask.logBase2();
205 bool ShouldNotVal = !TC.isZero();
206 bool NeedShift = ValZeros != AndZeros;
207 bool NeedZExtTrunc =
208 SelType->getScalarSizeInBits() != V->getType()->getScalarSizeInBits();
209
210 // If we would need to create an 'and' + 'shift' + 'xor' + cast to replace
211 // a 'select' + 'icmp', then this transformation would result in more
212 // instructions and potentially interfere with other folding.
213 if (CreateAnd + ShouldNotVal + NeedShift + NeedZExtTrunc >
214 1 + CondVal->hasOneUse())
215 return nullptr;
216
217 // Insert the 'and' instruction on the input to the truncate.
218 if (CreateAnd)
219 V = Builder.CreateAnd(LHS: V, RHS: ConstantInt::get(Ty: V->getType(), V: AndMask));
220
221 // If types don't match, we can still convert the select by introducing a zext
222 // or a trunc of the 'and'.
223 if (ValZeros > AndZeros) {
224 V = Builder.CreateZExtOrTrunc(V, DestTy: SelType);
225 V = Builder.CreateShl(LHS: V, RHS: ValZeros - AndZeros);
226 } else if (ValZeros < AndZeros) {
227 V = Builder.CreateLShr(LHS: V, RHS: AndZeros - ValZeros);
228 V = Builder.CreateZExtOrTrunc(V, DestTy: SelType);
229 } else {
230 V = Builder.CreateZExtOrTrunc(V, DestTy: SelType);
231 }
232
233 // Okay, now we know that everything is set up, we just don't know whether we
234 // have a icmp_ne or icmp_eq and whether the true or false val is the zero.
235 if (ShouldNotVal)
236 V = Builder.CreateXor(LHS: V, RHS: ValC);
237
238 return V;
239}
240
241/// We want to turn code that looks like this:
242/// %C = or %A, %B
243/// %D = select %cond, %C, %A
244/// into:
245/// %C = select %cond, %B, 0
246/// %D = or %A, %C
247///
248/// Assuming that the specified instruction is an operand to the select, return
249/// a bitmask indicating which operands of this instruction are foldable if they
250/// equal the other incoming value of the select.
251static unsigned getSelectFoldableOperands(BinaryOperator *I) {
252 switch (I->getOpcode()) {
253 case Instruction::Add:
254 case Instruction::FAdd:
255 case Instruction::Mul:
256 case Instruction::FMul:
257 case Instruction::And:
258 case Instruction::Or:
259 case Instruction::Xor:
260 return 3; // Can fold through either operand.
261 case Instruction::Sub: // Can only fold on the amount subtracted.
262 case Instruction::FSub:
263 case Instruction::FDiv: // Can only fold on the divisor amount.
264 case Instruction::Shl: // Can only fold on the shift amount.
265 case Instruction::LShr:
266 case Instruction::AShr:
267 return 1;
268 default:
269 return 0; // Cannot fold
270 }
271}
272
273/// We have (select c, TI, FI), and we know that TI and FI have the same opcode.
274Instruction *InstCombinerImpl::foldSelectOpOp(SelectInst &SI, Instruction *TI,
275 Instruction *FI) {
276 // If this is a cast from the same type, merge.
277 Value *Cond = SI.getCondition();
278 Type *CondTy = Cond->getType();
279 if (TI->getNumOperands() == 1 && TI->isCast()) {
280 Type *FIOpndTy = FI->getOperand(i: 0)->getType();
281 if (TI->getOperand(i: 0)->getType() != FIOpndTy)
282 return nullptr;
283
284 // The select condition may be a vector. We may only change the operand
285 // type if the vector width remains the same (and matches the condition).
286 if (auto *CondVTy = dyn_cast<VectorType>(Val: CondTy)) {
287 if (!FIOpndTy->isVectorTy() ||
288 CondVTy->getElementCount() !=
289 cast<VectorType>(Val: FIOpndTy)->getElementCount())
290 return nullptr;
291
292 // TODO: If the backend knew how to deal with casts better, we could
293 // remove this limitation. For now, there's too much potential to create
294 // worse codegen by promoting the select ahead of size-altering casts
295 // (PR28160).
296 //
297 // Note that ValueTracking's matchSelectPattern() looks through casts
298 // without checking 'hasOneUse' when it matches min/max patterns, so this
299 // transform may end up happening anyway.
300 if (TI->getOpcode() != Instruction::BitCast &&
301 (!TI->hasOneUse() || !FI->hasOneUse()))
302 return nullptr;
303 } else if (!TI->hasOneUse() || !FI->hasOneUse()) {
304 // TODO: The one-use restrictions for a scalar select could be eased if
305 // the fold of a select in visitLoadInst() was enhanced to match a pattern
306 // that includes a cast.
307 return nullptr;
308 }
309
310 // Fold this by inserting a select from the input values.
311 Value *NewSI =
312 Builder.CreateSelect(C: Cond, True: TI->getOperand(i: 0), False: FI->getOperand(i: 0),
313 Name: SI.getName() + ".v", MDFrom: &SI);
314 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), S: NewSI,
315 Ty: TI->getType());
316 }
317
318 Value *OtherOpT, *OtherOpF;
319 bool MatchIsOpZero;
320 auto getCommonOp = [&](Instruction *TI, Instruction *FI, bool Commute,
321 bool Swapped = false) -> Value * {
322 assert(!(Commute && Swapped) &&
323 "Commute and Swapped can't set at the same time");
324 if (!Swapped) {
325 if (TI->getOperand(i: 0) == FI->getOperand(i: 0)) {
326 OtherOpT = TI->getOperand(i: 1);
327 OtherOpF = FI->getOperand(i: 1);
328 MatchIsOpZero = true;
329 return TI->getOperand(i: 0);
330 } else if (TI->getOperand(i: 1) == FI->getOperand(i: 1)) {
331 OtherOpT = TI->getOperand(i: 0);
332 OtherOpF = FI->getOperand(i: 0);
333 MatchIsOpZero = false;
334 return TI->getOperand(i: 1);
335 }
336 }
337
338 if (!Commute && !Swapped)
339 return nullptr;
340
341 // If we are allowing commute or swap of operands, then
342 // allow a cross-operand match. In that case, MatchIsOpZero
343 // means that TI's operand 0 (FI's operand 1) is the common op.
344 if (TI->getOperand(i: 0) == FI->getOperand(i: 1)) {
345 OtherOpT = TI->getOperand(i: 1);
346 OtherOpF = FI->getOperand(i: 0);
347 MatchIsOpZero = true;
348 return TI->getOperand(i: 0);
349 } else if (TI->getOperand(i: 1) == FI->getOperand(i: 0)) {
350 OtherOpT = TI->getOperand(i: 0);
351 OtherOpF = FI->getOperand(i: 1);
352 MatchIsOpZero = false;
353 return TI->getOperand(i: 1);
354 }
355 return nullptr;
356 };
357
358 if (TI->hasOneUse() || FI->hasOneUse()) {
359 // Cond ? -X : -Y --> -(Cond ? X : Y)
360 Value *X, *Y;
361 if (match(V: TI, P: m_FNeg(X: m_Value(V&: X))) && match(V: FI, P: m_FNeg(X: m_Value(V&: Y)))) {
362 // Intersect FMF from the fneg instructions and union those with the
363 // select.
364 FastMathFlags FMF = TI->getFastMathFlags();
365 FMF &= FI->getFastMathFlags();
366 FMF |= SI.getFastMathFlags();
367 Value *NewSel =
368 Builder.CreateSelect(C: Cond, True: X, False: Y, Name: SI.getName() + ".v", MDFrom: &SI);
369 if (auto *NewSelI = dyn_cast<Instruction>(Val: NewSel))
370 NewSelI->setFastMathFlags(FMF);
371 Instruction *NewFNeg = UnaryOperator::CreateFNeg(V: NewSel);
372 NewFNeg->setFastMathFlags(FMF);
373 return NewFNeg;
374 }
375
376 // Min/max intrinsic with a common operand can have the common operand
377 // pulled after the select. This is the same transform as below for binops,
378 // but specialized for intrinsic matching and without the restrictive uses
379 // clause.
380 auto *TII = dyn_cast<IntrinsicInst>(Val: TI);
381 auto *FII = dyn_cast<IntrinsicInst>(Val: FI);
382 if (TII && FII && TII->getIntrinsicID() == FII->getIntrinsicID()) {
383 if (match(V: TII, P: m_MaxOrMin(Op0: m_Value(), Op1: m_Value()))) {
384 if (Value *MatchOp = getCommonOp(TI, FI, true)) {
385 Value *NewSel =
386 Builder.CreateSelect(C: Cond, True: OtherOpT, False: OtherOpF, Name: "minmaxop", MDFrom: &SI);
387 return CallInst::Create(Func: TII->getCalledFunction(), Args: {NewSel, MatchOp});
388 }
389 }
390
391 // select c, (ldexp v, e0), (ldexp v, e1) -> ldexp v, (select c, e0, e1)
392 // select c, (ldexp v0, e), (ldexp v1, e) -> ldexp (select c, v0, v1), e
393 //
394 // select c, (ldexp v0, e0), (ldexp v1, e1) ->
395 // ldexp (select c, v0, v1), (select c, e0, e1)
396 if (TII->getIntrinsicID() == Intrinsic::ldexp) {
397 Value *LdexpVal0 = TII->getArgOperand(i: 0);
398 Value *LdexpExp0 = TII->getArgOperand(i: 1);
399 Value *LdexpVal1 = FII->getArgOperand(i: 0);
400 Value *LdexpExp1 = FII->getArgOperand(i: 1);
401 if (LdexpExp0->getType() == LdexpExp1->getType()) {
402 FPMathOperator *SelectFPOp = cast<FPMathOperator>(Val: &SI);
403 FastMathFlags FMF = cast<FPMathOperator>(Val: TII)->getFastMathFlags();
404 FMF &= cast<FPMathOperator>(Val: FII)->getFastMathFlags();
405 FMF |= SelectFPOp->getFastMathFlags();
406
407 Value *SelectVal = Builder.CreateSelect(
408 C: Cond, True: LdexpVal0, False: LdexpVal1, Name: "",
409 MDFrom: ProfcheckDisableMetadataFixes ? nullptr : &SI);
410 Value *SelectExp = Builder.CreateSelect(
411 C: Cond, True: LdexpExp0, False: LdexpExp1, Name: "",
412 MDFrom: ProfcheckDisableMetadataFixes ? nullptr : &SI);
413
414 Value *NewLdexp = Builder.CreateIntrinsic(
415 RetTy: TII->getType(), ID: Intrinsic::ldexp, Args: {SelectVal, SelectExp}, FMFSource: FMF);
416 return replaceInstUsesWith(I&: SI, V: NewLdexp);
417 }
418 }
419 }
420
421 auto CreateCmpSel = [&](std::optional<CmpPredicate> P,
422 bool Swapped) -> CmpInst * {
423 if (!P)
424 return nullptr;
425 auto *MatchOp = getCommonOp(TI, FI, ICmpInst::isEquality(P: *P),
426 ICmpInst::isRelational(P: *P) && Swapped);
427 if (!MatchOp)
428 return nullptr;
429 Value *NewSel = Builder.CreateSelect(C: Cond, True: OtherOpT, False: OtherOpF,
430 Name: SI.getName() + ".v", MDFrom: &SI);
431 return new ICmpInst(MatchIsOpZero ? *P
432 : ICmpInst::getSwappedCmpPredicate(Pred: *P),
433 MatchOp, NewSel);
434 };
435
436 // icmp with a common operand also can have the common operand
437 // pulled after the select.
438 CmpPredicate TPred, FPred;
439 if (match(V: TI, P: m_ICmp(Pred&: TPred, L: m_Value(), R: m_Value())) &&
440 match(V: FI, P: m_ICmp(Pred&: FPred, L: m_Value(), R: m_Value()))) {
441 if (auto *R =
442 CreateCmpSel(CmpPredicate::getMatching(A: TPred, B: FPred), false))
443 return R;
444 if (auto *R =
445 CreateCmpSel(CmpPredicate::getMatching(
446 A: TPred, B: ICmpInst::getSwappedCmpPredicate(Pred: FPred)),
447 true))
448 return R;
449 }
450 }
451
452 // Only handle binary operators (including two-operand getelementptr) with
453 // one-use here. As with the cast case above, it may be possible to relax the
454 // one-use constraint, but that needs be examined carefully since it may not
455 // reduce the total number of instructions.
456 if (TI->getNumOperands() != 2 || FI->getNumOperands() != 2 ||
457 !TI->isSameOperationAs(I: FI) ||
458 (!isa<BinaryOperator>(Val: TI) && !isa<GetElementPtrInst>(Val: TI)) ||
459 !TI->hasOneUse() || !FI->hasOneUse())
460 return nullptr;
461
462 // Figure out if the operations have any operands in common.
463 Value *MatchOp = getCommonOp(TI, FI, TI->isCommutative());
464 if (!MatchOp)
465 return nullptr;
466
467 // If the select condition is a vector, the operands of the original select's
468 // operands also must be vectors. This may not be the case for getelementptr
469 // for example.
470 if (CondTy->isVectorTy() && (!OtherOpT->getType()->isVectorTy() ||
471 !OtherOpF->getType()->isVectorTy()))
472 return nullptr;
473
474 // If we are sinking div/rem after a select, we may need to freeze the
475 // condition because div/rem may induce immediate UB with a poison operand.
476 // For example, the following transform is not safe if Cond can ever be poison
477 // because we can replace poison with zero and then we have div-by-zero that
478 // didn't exist in the original code:
479 // Cond ? x/y : x/z --> x / (Cond ? y : z)
480 auto *BO = dyn_cast<BinaryOperator>(Val: TI);
481 if (BO && BO->isIntDivRem() && !isGuaranteedNotToBePoison(V: Cond)) {
482 // A udiv/urem with a common divisor is safe because UB can only occur with
483 // div-by-zero, and that would be present in the original code.
484 if (BO->getOpcode() == Instruction::SDiv ||
485 BO->getOpcode() == Instruction::SRem || MatchIsOpZero)
486 Cond = Builder.CreateFreeze(V: Cond);
487 }
488
489 // If we reach here, they do have operations in common.
490 Value *NewSI = Builder.CreateSelect(C: Cond, True: OtherOpT, False: OtherOpF,
491 Name: SI.getName() + ".v", MDFrom: &SI);
492 Value *Op0 = MatchIsOpZero ? MatchOp : NewSI;
493 Value *Op1 = MatchIsOpZero ? NewSI : MatchOp;
494 if (auto *BO = dyn_cast<BinaryOperator>(Val: TI)) {
495 BinaryOperator *NewBO = BinaryOperator::Create(Op: BO->getOpcode(), S1: Op0, S2: Op1);
496 NewBO->copyIRFlags(V: TI);
497 NewBO->andIRFlags(V: FI);
498 return NewBO;
499 }
500 if (auto *TGEP = dyn_cast<GetElementPtrInst>(Val: TI)) {
501 auto *FGEP = cast<GetElementPtrInst>(Val: FI);
502 Type *ElementType = TGEP->getSourceElementType();
503 return GetElementPtrInst::Create(
504 PointeeType: ElementType, Ptr: Op0, IdxList: Op1, NW: TGEP->getNoWrapFlags() & FGEP->getNoWrapFlags());
505 }
506 llvm_unreachable("Expected BinaryOperator or GEP");
507 return nullptr;
508}
509
510/// select C, f(..., X, ...), f(..., Y, ...) --> f(..., select C, X, Y, ...)
511static Instruction *
512foldSelectIntoIntrinsicArg(SelectInst &SI, IntrinsicInst *TII,
513 IntrinsicInst *FII,
514 InstCombiner::BuilderTy &Builder) {
515 if (TII->getCalledFunction() != FII->getCalledFunction())
516 return nullptr;
517
518 std::optional<unsigned> DiffArgNo;
519 for (unsigned I = 0, E = TII->arg_size(); I != E; ++I) {
520 if (TII->getArgOperand(i: I) == FII->getArgOperand(i: I))
521 continue;
522 if (DiffArgNo)
523 return nullptr;
524 DiffArgNo = I;
525 }
526 if (!DiffArgNo)
527 return nullptr;
528
529 if (!canReplaceOperandWithVariable(I: TII, OpIdx: *DiffArgNo))
530 return nullptr;
531
532 Value *TV = TII->getArgOperand(i: *DiffArgNo);
533 Value *FV = FII->getArgOperand(i: *DiffArgNo);
534 // powi keeps a scalar exponent even in its vector form.
535 if (SI.getCondition()->getType()->isVectorTy() &&
536 !TV->getType()->isVectorTy())
537 return nullptr;
538 // Constant args may enable cheaper lowering, e.g. pow(X, 2.0) -> X * X.
539 if (isa<Constant>(Val: TV) || isa<Constant>(Val: FV))
540 return nullptr;
541
542 SmallVector<Value *> Args(TII->args());
543 Args[*DiffArgNo] =
544 Builder.CreateSelect(C: SI.getCondition(), True: TV, False: FV, Name: SI.getName() + ".v", MDFrom: &SI);
545 auto *NewCall = CallInst::Create(Func: TII->getCalledFunction(), Args);
546 NewCall->copyIRFlags(V: TII);
547 NewCall->andIRFlags(V: FII);
548 return NewCall;
549}
550
551/// This transforms patterns of the form:
552/// select cond, intrinsic(x, ...), intrinsic(y, ...)
553/// into:
554/// intrinsic(select cond, x, y, ...)
555Instruction *InstCombinerImpl::foldSelectIntrinsic(SelectInst &SI) {
556 auto *LHSIntrinsic = dyn_cast<IntrinsicInst>(Val: SI.getTrueValue());
557 if (!LHSIntrinsic)
558 return nullptr;
559 auto *RHSIntrinsic = dyn_cast<IntrinsicInst>(Val: SI.getFalseValue());
560 if (!RHSIntrinsic ||
561 LHSIntrinsic->getIntrinsicID() != RHSIntrinsic->getIntrinsicID() ||
562 !LHSIntrinsic->hasOneUse() || !RHSIntrinsic->hasOneUse())
563 return nullptr;
564
565 const Intrinsic::ID IID = LHSIntrinsic->getIntrinsicID();
566 switch (IID) {
567 case Intrinsic::abs:
568 case Intrinsic::cttz:
569 case Intrinsic::ctlz: {
570 auto *TZ = cast<ConstantInt>(Val: LHSIntrinsic->getArgOperand(i: 1));
571 auto *FZ = cast<ConstantInt>(Val: RHSIntrinsic->getArgOperand(i: 1));
572
573 Value *TV = LHSIntrinsic->getArgOperand(i: 0);
574 Value *FV = RHSIntrinsic->getArgOperand(i: 0);
575
576 Value *NewSel = Builder.CreateSelect(C: SI.getCondition(), True: TV, False: FV, Name: "", MDFrom: &SI);
577 Value *NewPoisonFlag = Builder.CreateAnd(LHS: TZ, RHS: FZ);
578 Value *NewCall = Builder.CreateBinaryIntrinsic(ID: IID, LHS: NewSel, RHS: NewPoisonFlag);
579
580 return replaceInstUsesWith(I&: SI, V: NewCall);
581 }
582 default:
583 if (isTriviallyVectorizable(ID: IID))
584 return foldSelectIntoIntrinsicArg(SI, TII: LHSIntrinsic, FII: RHSIntrinsic,
585 Builder);
586 return nullptr;
587 }
588}
589
590static bool isSelect01(const APInt &C1I, const APInt &C2I) {
591 if (!C1I.isZero() && !C2I.isZero()) // One side must be zero.
592 return false;
593 return C1I.isOne() || C1I.isAllOnes() || C2I.isOne() || C2I.isAllOnes();
594}
595
596/// Try to fold the select into one of the operands to allow further
597/// optimization.
598Instruction *InstCombinerImpl::foldSelectIntoOp(SelectInst &SI, Value *TrueVal,
599 Value *FalseVal) {
600 // See the comment above getSelectFoldableOperands for a description of the
601 // transformation we are doing here.
602 auto TryFoldSelectIntoOp = [&](SelectInst &SI, Value *TrueVal,
603 Value *FalseVal,
604 bool Swapped) -> Instruction * {
605 auto *TVI = dyn_cast<BinaryOperator>(Val: TrueVal);
606 if (!TVI || !TVI->hasOneUse() || isa<Constant>(Val: FalseVal))
607 return nullptr;
608
609 unsigned SFO = getSelectFoldableOperands(I: TVI);
610 unsigned OpToFold = 0;
611 if ((SFO & 1) && FalseVal == TVI->getOperand(i_nocapture: 0))
612 OpToFold = 1;
613 else if ((SFO & 2) && FalseVal == TVI->getOperand(i_nocapture: 1))
614 OpToFold = 2;
615
616 if (!OpToFold)
617 return nullptr;
618
619 FastMathFlags FMF;
620 if (const auto *FPO = dyn_cast<FPMathOperator>(Val: &SI))
621 FMF = FPO->getFastMathFlags();
622 Constant *C = ConstantExpr::getBinOpIdentity(
623 Opcode: TVI->getOpcode(), Ty: TVI->getType(), AllowRHSConstant: true, NSZ: FMF.noSignedZeros());
624 Value *OOp = TVI->getOperand(i_nocapture: 2 - OpToFold);
625 // Avoid creating select between 2 constants unless it's selecting
626 // between 0, 1 and -1.
627 const APInt *OOpC;
628 bool OOpIsAPInt = match(V: OOp, P: m_APInt(Res&: OOpC));
629 if (isa<Constant>(Val: OOp) &&
630 (!OOpIsAPInt || !isSelect01(C1I: C->getUniqueInteger(), C2I: *OOpC)))
631 return nullptr;
632
633 // If the false value is a NaN then we have that the floating point math
634 // operation in the transformed code may not preserve the exact NaN
635 // bit-pattern -- e.g. `fadd sNaN, 0.0 -> qNaN`.
636 // This makes the transformation incorrect since the original program would
637 // have preserved the exact NaN bit-pattern.
638 // Avoid the folding if the false value might be a NaN.
639 if (isa<FPMathOperator>(Val: &SI) &&
640 !computeKnownFPClass(V: FalseVal, FMF, InterestedClasses: fcNan, SQ: SQ.getWithInstruction(I: &SI))
641 .isKnownNeverNaN())
642 return nullptr;
643
644 Value *NewSel = Builder.CreateSelect(C: SI.getCondition(), True: Swapped ? C : OOp,
645 False: Swapped ? OOp : C, Name: "", MDFrom: &SI);
646 if (isa<FPMathOperator>(Val: &SI)) {
647 FastMathFlags NewSelFMF = FMF;
648 // We cannot propagate ninf from the original select, because OOp may be
649 // inf and the flag only guarantees that FalseVal (op OOp) is never
650 // infinity.
651 // Examples: -inf + +inf = NaN, -inf - -inf = NaN, 0 * inf = NaN
652 // Specifically, if the original select has both ninf and nnan, we can
653 // safely propagate the flag.
654 // Note: This property holds for fadd, fsub, and fmul, but does not
655 // hold for fdiv (e.g. A / Inf == 0.0).
656 bool CanInferFiniteOperandsFromResult =
657 TVI->getOpcode() == Instruction::FAdd ||
658 TVI->getOpcode() == Instruction::FSub ||
659 TVI->getOpcode() == Instruction::FMul;
660 NewSelFMF.setNoInfs(TVI->hasNoInfs() ||
661 (CanInferFiniteOperandsFromResult &&
662 NewSelFMF.noInfs() && NewSelFMF.noNaNs()));
663 cast<Instruction>(Val: NewSel)->setFastMathFlags(NewSelFMF);
664 }
665 NewSel->takeName(V: TVI);
666 BinaryOperator *BO =
667 BinaryOperator::Create(Op: TVI->getOpcode(), S1: FalseVal, S2: NewSel);
668 BO->copyIRFlags(V: TVI);
669 if (isa<FPMathOperator>(Val: &SI)) {
670 // Merge poison generating flags from the select.
671 BO->setHasNoNaNs(BO->hasNoNaNs() && FMF.noNaNs());
672 BO->setHasNoInfs(BO->hasNoInfs() && FMF.noInfs());
673 // Merge no-signed-zeros flag from the select.
674 // Otherwise we may produce zeros with different sign.
675 BO->setHasNoSignedZeros(BO->hasNoSignedZeros() && FMF.noSignedZeros());
676 }
677 return BO;
678 };
679
680 if (Instruction *R = TryFoldSelectIntoOp(SI, TrueVal, FalseVal, false))
681 return R;
682
683 if (Instruction *R = TryFoldSelectIntoOp(SI, FalseVal, TrueVal, true))
684 return R;
685
686 return nullptr;
687}
688
689static Value *canoncalizeSelectICmpMinMax(const ICmpInst *Cmp, Value *TVal,
690 Value *FVal,
691 InstCombiner::BuilderTy &Builder,
692 const SimplifyQuery &SQ) {
693 Value *CmpLHS = Cmp->getOperand(i_nocapture: 0);
694 Value *CmpRHS = Cmp->getOperand(i_nocapture: 1);
695 ICmpInst::Predicate Pred = Cmp->getPredicate();
696 if (match(V: FVal, P: m_Zero())) {
697 std::swap(a&: TVal, b&: FVal);
698 Pred = ICmpInst::getInversePredicate(pred: Pred);
699 }
700 if (!match(V: TVal, P: m_Zero()))
701 return nullptr;
702
703 if (Pred == CmpInst::ICMP_SGT || Pred == CmpInst::ICMP_SGE) {
704 std::swap(a&: CmpLHS, b&: CmpRHS);
705 Pred = ICmpInst::getSwappedPredicate(pred: Pred);
706 }
707
708 // Handles:
709 // (X <= Y) ? 0 : (X - Y)
710 // (X <= Y) ? (Y - X) : 0
711 // (X >= Y) ? 0 : (Y - X)
712 // (X >= Y) ? (X - Y) : 0
713 if ((Pred == CmpInst::ICMP_SLT || Pred == CmpInst::ICMP_SLE) &&
714 match(V: FVal, P: m_NSWSub(L: m_Specific(V: CmpLHS), R: m_Specific(V: CmpRHS))) &&
715 isGuaranteedNotToBeUndef(V: CmpLHS, AC: SQ.AC, CtxI: SQ.CtxI, DT: SQ.DT)) {
716 Value *SMin =
717 Builder.CreateBinaryIntrinsic(ID: Intrinsic::smin, LHS: CmpRHS, RHS: CmpLHS);
718 return Builder.CreateNSWSub(LHS: CmpLHS, RHS: SMin);
719 }
720
721 return nullptr;
722}
723
724/// Try to fold a select to a min/max intrinsic. Many cases are already handled
725/// by matchDecomposedSelectPattern but here we handle the cases where more
726/// extensive modification of the IR is required.
727static Value *foldSelectICmpMinMax(const ICmpInst *Cmp, Value *TVal,
728 Value *FVal,
729 InstCombiner::BuilderTy &Builder,
730 const SimplifyQuery &SQ) {
731 Value *CmpLHS = Cmp->getOperand(i_nocapture: 0);
732 Value *CmpRHS = Cmp->getOperand(i_nocapture: 1);
733 ICmpInst::Predicate Pred = Cmp->getPredicate();
734
735 if (Value *V = canoncalizeSelectICmpMinMax(Cmp, TVal, FVal, Builder, SQ))
736 return V;
737
738 // (X > Y) ? X : (Y - 1) ==> MIN(X, Y - 1)
739 // (X < Y) ? X : (Y + 1) ==> MAX(X, Y + 1)
740 // This transformation is valid when overflow corresponding to the sign of
741 // the comparison is poison and we must drop the non-matching overflow flag.
742 if (CmpRHS == TVal) {
743 std::swap(a&: CmpLHS, b&: CmpRHS);
744 Pred = CmpInst::getSwappedPredicate(pred: Pred);
745 }
746
747 // TODO: consider handling 'or disjoint' as well, though these would need to
748 // be converted to 'add' instructions.
749 if (!(CmpLHS == TVal && isa<Instruction>(Val: FVal)))
750 return nullptr;
751
752 if (Pred == CmpInst::ICMP_SGT &&
753 match(V: FVal, P: m_NSWAdd(L: m_Specific(V: CmpRHS), R: m_One()))) {
754 cast<Instruction>(Val: FVal)->setHasNoUnsignedWrap(false);
755 return Builder.CreateBinaryIntrinsic(ID: Intrinsic::smax, LHS: TVal, RHS: FVal);
756 }
757
758 if (Pred == CmpInst::ICMP_SLT &&
759 match(V: FVal, P: m_NSWAdd(L: m_Specific(V: CmpRHS), R: m_AllOnes()))) {
760 cast<Instruction>(Val: FVal)->setHasNoUnsignedWrap(false);
761 return Builder.CreateBinaryIntrinsic(ID: Intrinsic::smin, LHS: TVal, RHS: FVal);
762 }
763
764 if (Pred == CmpInst::ICMP_UGT &&
765 match(V: FVal, P: m_NUWAdd(L: m_Specific(V: CmpRHS), R: m_One()))) {
766 cast<Instruction>(Val: FVal)->setHasNoSignedWrap(false);
767 return Builder.CreateBinaryIntrinsic(ID: Intrinsic::umax, LHS: TVal, RHS: FVal);
768 }
769
770 // Note: We must use isKnownNonZero here because "sub nuw %x, 1" will be
771 // canonicalized to "add %x, -1" discarding the nuw flag.
772 if (Pred == CmpInst::ICMP_ULT &&
773 match(V: FVal, P: m_Add(L: m_Specific(V: CmpRHS), R: m_AllOnes())) &&
774 isKnownNonZero(V: CmpRHS, Q: SQ)) {
775 cast<Instruction>(Val: FVal)->setHasNoSignedWrap(false);
776 cast<Instruction>(Val: FVal)->setHasNoUnsignedWrap(false);
777 return Builder.CreateBinaryIntrinsic(ID: Intrinsic::umin, LHS: TVal, RHS: FVal);
778 }
779
780 return nullptr;
781}
782
783/// We want to turn:
784/// (select (icmp eq (and X, Y), 0), (and (lshr X, Z), 1), 1)
785/// into:
786/// zext (icmp ne i32 (and X, (or Y, (shl 1, Z))), 0)
787/// Note:
788/// Z may be 0 if lshr is missing.
789/// Worst-case scenario is that we will replace 5 instructions with 5 different
790/// instructions, but we got rid of select.
791static Instruction *foldSelectICmpAndAnd(Type *SelType, const Value *Cond,
792 Value *TVal, Value *FVal,
793 InstCombiner::BuilderTy &Builder) {
794 Value *A, *X, *Y, *Z;
795 CmpPredicate Pred;
796 unsigned NumReplaced = 1 + Cond->hasOneUse();
797 if (match(V: Cond, P: m_Trunc(Op: m_Value(V&: X)))) {
798 Y = ConstantInt::get(Ty: X->getType(), V: 1);
799 Pred = ICmpInst::ICMP_NE;
800 } else if (match(V: Cond,
801 P: m_ICmp(Pred, L: m_And(L: m_Value(V&: X), R: m_Value(V&: Y)), R: m_Zero())) &&
802 ICmpInst::isEquality(P: Pred)) {
803 NumReplaced +=
804 Cond->hasOneUse() && cast<ICmpInst>(Val: Cond)->getOperand(i_nocapture: 0)->hasOneUse();
805 } else
806 return nullptr;
807
808 if (Pred == ICmpInst::ICMP_NE)
809 std::swap(a&: TVal, b&: FVal);
810
811 if (!match(V: FVal, P: m_One()))
812 return nullptr;
813
814 // The TrueVal has general form of: and %B, 1
815 if (!match(V: TVal, P: m_And(L: m_Value(V&: A), R: m_One())))
816 return nullptr;
817
818 APInt BitWidth(SelType->getScalarSizeInBits(),
819 SelType->getScalarSizeInBits());
820 auto TValPattern = m_CombineOr(
821 Ps: m_Deferred(V: X),
822 Ps: m_LShr(L: m_Deferred(V: X), R: m_Value(V&: Z, P: m_SpecificInt_ICMP_ForbidPoison(
823 Predicate: CmpInst::ICMP_ULT, Threshold: BitWidth))));
824
825 if (!match(V: A, P: TValPattern)) {
826 std::swap(a&: X, b&: Y);
827 if (!match(V: A, P: TValPattern))
828 return nullptr;
829 }
830
831 bool HasShift = A != X;
832 if (TVal->hasOneUse())
833 NumReplaced += 1 + (HasShift && A->hasOneUse());
834
835 if (NumReplaced < (4u - isa<Constant>(Val: Y)))
836 return nullptr;
837
838 // ((X & Y) == 0) ? ((X >> Z) & 1) : 1 --> (X & (Y | (1 << Z))) != 0
839 // ((X & Y) == 0) ? (X & 1) : 1 --> (X & (Y | 1)) != 0
840 Constant *One = ConstantInt::get(Ty: SelType, V: 1);
841 Value *MaskB = HasShift ? Builder.CreateShl(LHS: One, RHS: Z) : One;
842 Value *FullMask = Builder.CreateOr(LHS: Y, RHS: MaskB);
843 Value *MaskedX = Builder.CreateAnd(LHS: X, RHS: FullMask);
844 Value *ICmpNeZero = Builder.CreateIsNotNull(Arg: MaskedX);
845 return new ZExtInst(ICmpNeZero, SelType);
846}
847
848/// We want to turn:
849/// (select (icmp eq (and X, C1), 0), 0, (shl [nsw/nuw] X, C2));
850/// iff C1 is a mask and the number of its leading zeros is equal to C2
851/// into:
852/// shl X, C2
853static Value *foldSelectICmpAndZeroShl(const ICmpInst *Cmp, Value *TVal,
854 Value *FVal,
855 InstCombiner::BuilderTy &Builder) {
856 CmpPredicate Pred;
857 Value *AndVal;
858 if (!match(V: Cmp, P: m_ICmp(Pred, L: m_Value(V&: AndVal), R: m_Zero())))
859 return nullptr;
860
861 if (Pred == ICmpInst::ICMP_NE) {
862 Pred = ICmpInst::ICMP_EQ;
863 std::swap(a&: TVal, b&: FVal);
864 }
865
866 Value *X;
867 const APInt *C2, *C1;
868 if (Pred != ICmpInst::ICMP_EQ ||
869 !match(V: AndVal, P: m_And(L: m_Value(V&: X), R: m_APInt(Res&: C1))) ||
870 !match(V: TVal, P: m_Zero()) || !match(V: FVal, P: m_Shl(L: m_Specific(V: X), R: m_APInt(Res&: C2))))
871 return nullptr;
872
873 if (!C1->isMask() ||
874 C1->countLeadingZeros() != static_cast<unsigned>(C2->getZExtValue()))
875 return nullptr;
876
877 auto *FI = dyn_cast<Instruction>(Val: FVal);
878 if (!FI)
879 return nullptr;
880
881 FI->setHasNoSignedWrap(false);
882 FI->setHasNoUnsignedWrap(false);
883 return FVal;
884}
885
886/// We want to turn:
887/// (select (icmp sgt x, C), lshr (X, Y), ashr (X, Y)); iff C s>= -1
888/// (select (icmp slt x, C), ashr (X, Y), lshr (X, Y)); iff C s>= 0
889/// into:
890/// ashr (X, Y)
891static Value *foldSelectICmpLshrAshr(const ICmpInst *IC, Value *TrueVal,
892 Value *FalseVal,
893 InstCombiner::BuilderTy &Builder) {
894 ICmpInst::Predicate Pred = IC->getPredicate();
895 Value *CmpLHS = IC->getOperand(i_nocapture: 0);
896 Value *CmpRHS = IC->getOperand(i_nocapture: 1);
897 if (!CmpRHS->getType()->isIntOrIntVectorTy())
898 return nullptr;
899
900 Value *X, *Y;
901 unsigned Bitwidth = CmpRHS->getType()->getScalarSizeInBits();
902 if ((Pred != ICmpInst::ICMP_SGT ||
903 !match(V: CmpRHS, P: m_SpecificInt_ICMP(Predicate: ICmpInst::ICMP_SGE,
904 Threshold: APInt::getAllOnes(numBits: Bitwidth)))) &&
905 (Pred != ICmpInst::ICMP_SLT ||
906 !match(V: CmpRHS, P: m_SpecificInt_ICMP(Predicate: ICmpInst::ICMP_SGE,
907 Threshold: APInt::getZero(numBits: Bitwidth)))))
908 return nullptr;
909
910 // Canonicalize so that ashr is in FalseVal.
911 if (Pred == ICmpInst::ICMP_SLT)
912 std::swap(a&: TrueVal, b&: FalseVal);
913
914 if (match(V: TrueVal, P: m_LShr(L: m_Value(V&: X), R: m_Value(V&: Y))) &&
915 match(V: FalseVal, P: m_AShr(L: m_Specific(V: X), R: m_Specific(V: Y))) &&
916 match(V: CmpLHS, P: m_Specific(V: X))) {
917 const auto *Ashr = cast<Instruction>(Val: FalseVal);
918 // if lshr is not exact and ashr is, this new ashr must not be exact.
919 bool IsExact = Ashr->isExact() && cast<Instruction>(Val: TrueVal)->isExact();
920 return Builder.CreateAShr(LHS: X, RHS: Y, Name: IC->getName(), isExact: IsExact);
921 }
922
923 return nullptr;
924}
925
926/// We want to turn:
927/// (select (icmp eq (and X, C1), 0), Y, (BinOp Y, C2))
928/// into:
929/// IF C2 u>= C1
930/// (BinOp Y, (shl (and X, C1), C3))
931/// ELSE
932/// (BinOp Y, (lshr (and X, C1), C3))
933/// iff:
934/// 0 on the RHS is the identity value (i.e add, xor, shl, etc...)
935/// C1 and C2 are both powers of 2
936/// where:
937/// IF C2 u>= C1
938/// C3 = Log(C2) - Log(C1)
939/// ELSE
940/// C3 = Log(C1) - Log(C2)
941///
942/// This transform handles cases where:
943/// 1. The icmp predicate is inverted
944/// 2. The select operands are reversed
945/// 3. The magnitude of C2 and C1 are flipped
946static Value *foldSelectICmpAndBinOp(Value *CondVal, Value *TrueVal,
947 Value *FalseVal, Value *V,
948 const APInt &AndMask, bool CreateAnd,
949 InstCombiner::BuilderTy &Builder) {
950 // Only handle integer compares.
951 if (!TrueVal->getType()->isIntOrIntVectorTy())
952 return nullptr;
953
954 unsigned C1Log = AndMask.logBase2();
955 Value *Y;
956 BinaryOperator *BinOp;
957 const APInt *C2;
958 bool NeedXor;
959 if (match(V: FalseVal, P: m_BinOp(L: m_Specific(V: TrueVal), R: m_Power2(V&: C2)))) {
960 Y = TrueVal;
961 BinOp = cast<BinaryOperator>(Val: FalseVal);
962 NeedXor = false;
963 } else if (match(V: TrueVal, P: m_BinOp(L: m_Specific(V: FalseVal), R: m_Power2(V&: C2)))) {
964 Y = FalseVal;
965 BinOp = cast<BinaryOperator>(Val: TrueVal);
966 NeedXor = true;
967 } else {
968 return nullptr;
969 }
970
971 // Check that 0 on RHS is identity value for this binop.
972 auto *IdentityC =
973 ConstantExpr::getBinOpIdentity(Opcode: BinOp->getOpcode(), Ty: BinOp->getType(),
974 /*AllowRHSConstant*/ true);
975 if (IdentityC == nullptr || !IdentityC->isNullValue())
976 return nullptr;
977
978 unsigned C2Log = C2->logBase2();
979
980 bool NeedShift = C1Log != C2Log;
981 bool NeedZExtTrunc = Y->getType()->getScalarSizeInBits() !=
982 V->getType()->getScalarSizeInBits();
983
984 // the demanded bits for the created shl make the and redundant
985 if (AndMask.isOne() && C2->isSignBitSet())
986 CreateAnd = false;
987
988 // Make sure we don't create more instructions than we save.
989 if ((NeedShift + NeedXor + NeedZExtTrunc + CreateAnd) >
990 (CondVal->hasOneUse() + BinOp->hasOneUse()))
991 return nullptr;
992
993 if (CreateAnd) {
994 // Insert the AND instruction on the input to the truncate.
995 V = Builder.CreateAnd(LHS: V, RHS: ConstantInt::get(Ty: V->getType(), V: AndMask));
996 }
997
998 if (C2Log > C1Log) {
999 V = Builder.CreateZExtOrTrunc(V, DestTy: Y->getType());
1000 V = Builder.CreateShl(LHS: V, RHS: C2Log - C1Log);
1001 } else if (C1Log > C2Log) {
1002 V = Builder.CreateLShr(LHS: V, RHS: C1Log - C2Log);
1003 V = Builder.CreateZExtOrTrunc(V, DestTy: Y->getType());
1004 } else
1005 V = Builder.CreateZExtOrTrunc(V, DestTy: Y->getType());
1006
1007 if (NeedXor)
1008 V = Builder.CreateXor(LHS: V, RHS: *C2);
1009
1010 auto *Res = Builder.CreateBinOp(Opc: BinOp->getOpcode(), LHS: Y, RHS: V);
1011 if (auto *BO = dyn_cast<BinaryOperator>(Val: Res))
1012 BO->copyIRFlags(V: BinOp);
1013 return Res;
1014}
1015
1016/// Canonicalize a set or clear of a masked set of constant bits to
1017/// select-of-constants form.
1018static Instruction *foldSetClearBits(SelectInst &Sel,
1019 InstCombiner::BuilderTy &Builder) {
1020 Value *Cond = Sel.getCondition();
1021 Value *T = Sel.getTrueValue();
1022 Value *F = Sel.getFalseValue();
1023 Type *Ty = Sel.getType();
1024 Value *X;
1025 const APInt *NotC, *C;
1026
1027 // Cond ? (X & ~C) : (X | C) --> (X & ~C) | (Cond ? 0 : C)
1028 if (match(V: T, P: m_And(L: m_Value(V&: X), R: m_APInt(Res&: NotC))) &&
1029 match(V: F, P: m_OneUse(SubPattern: m_Or(L: m_Specific(V: X), R: m_APInt(Res&: C)))) && *NotC == ~(*C)) {
1030 Constant *Zero = ConstantInt::getNullValue(Ty);
1031 Constant *OrC = ConstantInt::get(Ty, V: *C);
1032 Value *NewSel = Builder.CreateSelect(C: Cond, True: Zero, False: OrC, Name: "masksel", MDFrom: &Sel);
1033 return BinaryOperator::CreateOr(V1: T, V2: NewSel);
1034 }
1035
1036 // Cond ? (X | C) : (X & ~C) --> (X & ~C) | (Cond ? C : 0)
1037 if (match(V: F, P: m_And(L: m_Value(V&: X), R: m_APInt(Res&: NotC))) &&
1038 match(V: T, P: m_OneUse(SubPattern: m_Or(L: m_Specific(V: X), R: m_APInt(Res&: C)))) && *NotC == ~(*C)) {
1039 Constant *Zero = ConstantInt::getNullValue(Ty);
1040 Constant *OrC = ConstantInt::get(Ty, V: *C);
1041 Value *NewSel = Builder.CreateSelect(C: Cond, True: OrC, False: Zero, Name: "masksel", MDFrom: &Sel);
1042 return BinaryOperator::CreateOr(V1: F, V2: NewSel);
1043 }
1044
1045 return nullptr;
1046}
1047
1048// select (x == 0), 0, x * y --> freeze(y) * x
1049// select (y == 0), 0, x * y --> freeze(x) * y
1050// select (x == 0), undef, x * y --> freeze(y) * x
1051// select (x == undef), 0, x * y --> freeze(y) * x
1052// Usage of mul instead of 0 will make the result more poisonous,
1053// so the operand that was not checked in the condition should be frozen.
1054// The latter folding is applied only when a constant compared with x is
1055// is a vector consisting of 0 and undefs. If a constant compared with x
1056// is a scalar undefined value or undefined vector then an expression
1057// should be already folded into a constant.
1058//
1059// This also holds all operations such that Op(0) == 0
1060// e.g. Shl, Umin, etc
1061static Instruction *foldSelectZeroOrFixedOp(SelectInst &SI,
1062 InstCombinerImpl &IC) {
1063 auto *CondVal = SI.getCondition();
1064 auto *TrueVal = SI.getTrueValue();
1065 auto *FalseVal = SI.getFalseValue();
1066 Value *X, *Y;
1067 CmpPredicate Predicate;
1068
1069 // Assuming that constant compared with zero is not undef (but it may be
1070 // a vector with some undef elements). Otherwise (when a constant is undef)
1071 // the select expression should be already simplified.
1072 if (!match(V: CondVal, P: m_ICmp(Pred&: Predicate, L: m_Value(V&: X), R: m_Zero())) ||
1073 !ICmpInst::isEquality(P: Predicate))
1074 return nullptr;
1075
1076 if (Predicate == ICmpInst::ICMP_NE)
1077 std::swap(a&: TrueVal, b&: FalseVal);
1078
1079 // Check that TrueVal is a constant instead of matching it with m_Zero()
1080 // to handle the case when it is a scalar undef value or a vector containing
1081 // non-zero elements that are masked by undef elements in the compare
1082 // constant.
1083 auto *TrueValC = dyn_cast<Constant>(Val: TrueVal);
1084 if (TrueValC == nullptr || !isa<Instruction>(Val: FalseVal))
1085 return nullptr;
1086
1087 bool FreezeY;
1088 if (match(V: FalseVal, P: m_c_Mul(L: m_Specific(V: X), R: m_Value(V&: Y))) ||
1089 match(V: FalseVal, P: m_c_And(L: m_Specific(V: X), R: m_Value(V&: Y))) ||
1090 match(V: FalseVal, P: m_FShl(Op0: m_Specific(V: X), Op1: m_Specific(V: X), Op2: m_Value(V&: Y))) ||
1091 match(V: FalseVal, P: m_FShr(Op0: m_Specific(V: X), Op1: m_Specific(V: X), Op2: m_Value(V&: Y))) ||
1092 match(V: FalseVal,
1093 P: m_c_Intrinsic<Intrinsic::umin>(Op0: m_Specific(V: X), Op1: m_Value(V&: Y)))) {
1094 FreezeY = true;
1095 } else if (match(V: FalseVal, P: m_IDiv(L: m_Specific(V: X), R: m_Value(V&: Y))) ||
1096 match(V: FalseVal, P: m_IRem(L: m_Specific(V: X), R: m_Value(V&: Y)))) {
1097 FreezeY = false;
1098 } else {
1099 return nullptr;
1100 }
1101
1102 auto *ZeroC = cast<Constant>(Val: cast<Instruction>(Val: CondVal)->getOperand(i: 1));
1103 auto *MergedC = Constant::mergeUndefsWith(C: TrueValC, Other: ZeroC);
1104 // If X is compared with 0 then TrueVal could be either zero or undef.
1105 // m_Zero match vectors containing some undef elements, but for scalars
1106 // m_Undef should be used explicitly.
1107 if (!match(V: MergedC, P: m_Zero()) && !match(V: MergedC, P: m_Undef()))
1108 return nullptr;
1109
1110 auto *FalseValI = cast<Instruction>(Val: FalseVal);
1111 if (FreezeY) {
1112 auto *FrY = IC.InsertNewInstBefore(New: new FreezeInst(Y, Y->getName() + ".fr"),
1113 Old: FalseValI->getIterator());
1114 IC.replaceOperand(I&: *FalseValI,
1115 OpNum: FalseValI->getOperand(i: 0) == Y
1116 ? 0
1117 : (FalseValI->getOperand(i: 1) == Y ? 1 : 2),
1118 V: FrY);
1119 }
1120 return IC.replaceInstUsesWith(I&: SI, V: FalseValI);
1121}
1122
1123/// Transform patterns such as (a > b) ? a - b : 0 into usub.sat(a, b).
1124/// There are 8 commuted/swapped variants of this pattern.
1125static Value *
1126canonicalizeSaturatedSubtractUnsigned(const ICmpInst *ICI, const Value *TrueVal,
1127 const Value *FalseVal,
1128 InstCombiner::BuilderTy &Builder) {
1129 ICmpInst::Predicate Pred = ICI->getPredicate();
1130 Value *A = ICI->getOperand(i_nocapture: 0);
1131 Value *B = ICI->getOperand(i_nocapture: 1);
1132
1133 // (b > a) ? 0 : a - b -> (b <= a) ? a - b : 0
1134 // (a == 0) ? 0 : a - 1 -> (a != 0) ? a - 1 : 0
1135 if (match(V: TrueVal, P: m_Zero())) {
1136 Pred = ICmpInst::getInversePredicate(pred: Pred);
1137 std::swap(a&: TrueVal, b&: FalseVal);
1138 }
1139
1140 if (!match(V: FalseVal, P: m_Zero()))
1141 return nullptr;
1142
1143 // ugt 0 is canonicalized to ne 0 and requires special handling
1144 // (a != 0) ? a + -1 : 0 -> usub.sat(a, 1)
1145 if (Pred == ICmpInst::ICMP_NE) {
1146 if (match(V: B, P: m_Zero()) && match(V: TrueVal, P: m_Add(L: m_Specific(V: A), R: m_AllOnes())))
1147 return Builder.CreateBinaryIntrinsic(ID: Intrinsic::usub_sat, LHS: A,
1148 RHS: ConstantInt::get(Ty: A->getType(), V: 1));
1149 return nullptr;
1150 }
1151
1152 if (!ICmpInst::isUnsigned(Pred))
1153 return nullptr;
1154
1155 if (Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_ULT) {
1156 // (b < a) ? a - b : 0 -> (a > b) ? a - b : 0
1157 std::swap(a&: A, b&: B);
1158 Pred = ICmpInst::getSwappedPredicate(pred: Pred);
1159 }
1160
1161 assert((Pred == ICmpInst::ICMP_UGE || Pred == ICmpInst::ICMP_UGT) &&
1162 "Unexpected isUnsigned predicate!");
1163
1164 // Ensure the sub is of the form:
1165 // (a > b) ? a - b : 0 -> usub.sat(a, b)
1166 // (a > b) ? b - a : 0 -> -usub.sat(a, b)
1167 // Checking for both a-b and a+(-b) as a constant.
1168 bool IsNegative = false;
1169 const APInt *C;
1170 if (match(V: TrueVal, P: m_Sub(L: m_Specific(V: B), R: m_Specific(V: A))) ||
1171 (match(V: A, P: m_APInt(Res&: C)) &&
1172 match(V: TrueVal, P: m_Add(L: m_Specific(V: B), R: m_SpecificInt(V: -*C)))))
1173 IsNegative = true;
1174 else if (!match(V: TrueVal, P: m_Sub(L: m_Specific(V: A), R: m_Specific(V: B))) &&
1175 !(match(V: B, P: m_APInt(Res&: C)) &&
1176 match(V: TrueVal, P: m_Add(L: m_Specific(V: A), R: m_SpecificInt(V: -*C)))))
1177 return nullptr;
1178
1179 // If we are adding a negate and the sub and icmp are used anywhere else, we
1180 // would end up with more instructions.
1181 if (IsNegative && !TrueVal->hasOneUse() && !ICI->hasOneUse())
1182 return nullptr;
1183
1184 // (a > b) ? a - b : 0 -> usub.sat(a, b)
1185 // (a > b) ? b - a : 0 -> -usub.sat(a, b)
1186 Value *Result = Builder.CreateBinaryIntrinsic(ID: Intrinsic::usub_sat, LHS: A, RHS: B);
1187 if (IsNegative)
1188 Result = Builder.CreateNeg(V: Result);
1189 return Result;
1190}
1191
1192static Value *
1193canonicalizeSaturatedSubtractSigned(const ICmpInst *ICI, const Value *TrueVal,
1194 const Value *FalseVal,
1195 InstCombiner::BuilderTy &Builder) {
1196 ICmpInst::Predicate Pred = ICI->getPredicate();
1197 Value *CmpLHS = ICI->getOperand(i_nocapture: 0);
1198 Value *CmpRHS = ICI->getOperand(i_nocapture: 1);
1199
1200 // `A != B ? X : Y` --> `A == B ? Y : X`
1201 // This canonicalization allows us to handle more patterns with fewer checks.
1202 if (Pred == ICmpInst::ICMP_NE) {
1203 Pred = ICmpInst::ICMP_EQ;
1204 std::swap(a&: TrueVal, b&: FalseVal);
1205 }
1206
1207 // `A == MIN_INT ? MAX_INT : 0 - A` --> `ssub_sat 0, A`
1208 if (Pred == ICmpInst::ICMP_EQ && match(V: CmpRHS, P: m_SignMask()) &&
1209 match(V: TrueVal, P: m_MaxSignedValue()) &&
1210 match(V: FalseVal, P: m_Neg(V: m_Specific(V: CmpLHS)))) {
1211 return Builder.CreateBinaryIntrinsic(
1212 ID: Intrinsic::ssub_sat, LHS: ConstantInt::getNullValue(Ty: CmpLHS->getType()),
1213 RHS: CmpLHS);
1214 }
1215
1216 return nullptr;
1217}
1218
1219static Value *canonicalizeSaturatedSubtract(const ICmpInst *ICI,
1220 const Value *TrueVal,
1221 const Value *FalseVal,
1222 InstCombiner::BuilderTy &Builder) {
1223 if (Value *V = canonicalizeSaturatedSubtractUnsigned(ICI, TrueVal, FalseVal,
1224 Builder))
1225 return V;
1226
1227 if (Value *V =
1228 canonicalizeSaturatedSubtractSigned(ICI, TrueVal, FalseVal, Builder))
1229 return V;
1230
1231 return nullptr;
1232}
1233
1234static Value *
1235canonicalizeSaturatedAddUnsigned(ICmpInst *Cmp, Value *TVal, Value *FVal,
1236 InstCombiner::BuilderTy &Builder) {
1237
1238 // Match unsigned saturated add with constant.
1239 Value *Cmp0 = Cmp->getOperand(i_nocapture: 0);
1240 Value *Cmp1 = Cmp->getOperand(i_nocapture: 1);
1241 ICmpInst::Predicate Pred = Cmp->getPredicate();
1242 Value *X;
1243 const APInt *C;
1244
1245 // Match unsigned saturated add of 2 variables with an unnecessary 'not'.
1246 // There are 8 commuted variants.
1247 // Canonicalize -1 (saturated result) to true value of the select.
1248 if (match(V: FVal, P: m_AllOnes())) {
1249 std::swap(a&: TVal, b&: FVal);
1250 Pred = CmpInst::getInversePredicate(pred: Pred);
1251 }
1252 if (!match(V: TVal, P: m_AllOnes()))
1253 return nullptr;
1254
1255 // uge -1 is canonicalized to eq -1 and requires special handling
1256 // (a == -1) ? -1 : a + 1 -> uadd.sat(a, 1)
1257 if (Pred == ICmpInst::ICMP_EQ) {
1258 if (match(V: FVal, P: m_Add(L: m_Specific(V: Cmp0), R: m_One())) &&
1259 match(V: Cmp1, P: m_AllOnes())) {
1260 return Builder.CreateBinaryIntrinsic(
1261 ID: Intrinsic::uadd_sat, LHS: Cmp0, RHS: ConstantInt::get(Ty: Cmp0->getType(), V: 1));
1262 }
1263 return nullptr;
1264 }
1265
1266 if ((Pred == ICmpInst::ICMP_UGE || Pred == ICmpInst::ICMP_UGT) &&
1267 match(V: FVal, P: m_Add(L: m_Specific(V: Cmp0), R: m_APIntAllowPoison(Res&: C))) &&
1268 match(V: Cmp1, P: m_SpecificIntAllowPoison(V: ~*C))) {
1269 // (X u> ~C) ? -1 : (X + C) --> uadd.sat(X, C)
1270 // (X u>= ~C)? -1 : (X + C) --> uadd.sat(X, C)
1271 return Builder.CreateBinaryIntrinsic(ID: Intrinsic::uadd_sat, LHS: Cmp0,
1272 RHS: ConstantInt::get(Ty: Cmp0->getType(), V: *C));
1273 }
1274
1275 // Negative one does not work here because X u> -1 ? -1, X + -1 is not a
1276 // saturated add.
1277 if (Pred == ICmpInst::ICMP_UGT &&
1278 match(V: FVal, P: m_Add(L: m_Specific(V: Cmp0), R: m_APIntAllowPoison(Res&: C))) &&
1279 match(V: Cmp1, P: m_SpecificIntAllowPoison(V: ~*C - 1)) && !C->isAllOnes()) {
1280 // (X u> ~C - 1) ? -1 : (X + C) --> uadd.sat(X, C)
1281 return Builder.CreateBinaryIntrinsic(ID: Intrinsic::uadd_sat, LHS: Cmp0,
1282 RHS: ConstantInt::get(Ty: Cmp0->getType(), V: *C));
1283 }
1284
1285 // Zero does not work here because X u>= 0 ? -1 : X -> is always -1, which is
1286 // not a saturated add.
1287 if (Pred == ICmpInst::ICMP_UGE &&
1288 match(V: FVal, P: m_Add(L: m_Specific(V: Cmp0), R: m_APIntAllowPoison(Res&: C))) &&
1289 match(V: Cmp1, P: m_SpecificIntAllowPoison(V: -*C)) && !C->isZero()) {
1290 // (X u >= -C) ? -1 : (X + C) --> uadd.sat(X, C)
1291 return Builder.CreateBinaryIntrinsic(ID: Intrinsic::uadd_sat, LHS: Cmp0,
1292 RHS: ConstantInt::get(Ty: Cmp0->getType(), V: *C));
1293 }
1294
1295 // Canonicalize predicate to less-than or less-or-equal-than.
1296 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE) {
1297 std::swap(a&: Cmp0, b&: Cmp1);
1298 Pred = CmpInst::getSwappedPredicate(pred: Pred);
1299 }
1300 if (Pred != ICmpInst::ICMP_ULT && Pred != ICmpInst::ICMP_ULE)
1301 return nullptr;
1302
1303 // Match unsigned saturated add of 2 variables with an unnecessary 'not'.
1304 // Strictness of the comparison is irrelevant.
1305 Value *Y;
1306 if (match(V: Cmp0, P: m_Not(V: m_Value(V&: X))) &&
1307 match(V: FVal, P: m_c_Add(L: m_Specific(V: X), R: m_Value(V&: Y))) && Y == Cmp1) {
1308 // (~X u< Y) ? -1 : (X + Y) --> uadd.sat(X, Y)
1309 // (~X u< Y) ? -1 : (Y + X) --> uadd.sat(X, Y)
1310 return Builder.CreateBinaryIntrinsic(ID: Intrinsic::uadd_sat, LHS: X, RHS: Y);
1311 }
1312 // The 'not' op may be included in the sum but not the compare.
1313 // Strictness of the comparison is irrelevant.
1314 X = Cmp0;
1315 Y = Cmp1;
1316 if (match(V: FVal, P: m_c_Add(L: m_NotForbidPoison(V: m_Specific(V: X)), R: m_Specific(V: Y)))) {
1317 // (X u< Y) ? -1 : (~X + Y) --> uadd.sat(~X, Y)
1318 // (X u< Y) ? -1 : (Y + ~X) --> uadd.sat(Y, ~X)
1319 BinaryOperator *BO = cast<BinaryOperator>(Val: FVal);
1320 return Builder.CreateBinaryIntrinsic(
1321 ID: Intrinsic::uadd_sat, LHS: BO->getOperand(i_nocapture: 0), RHS: BO->getOperand(i_nocapture: 1));
1322 }
1323 // The overflow may be detected via the add wrapping round.
1324 // This is only valid for strict comparison!
1325 if (Pred == ICmpInst::ICMP_ULT &&
1326 match(V: Cmp0, P: m_c_Add(L: m_Specific(V: Cmp1), R: m_Value(V&: Y))) &&
1327 match(V: FVal, P: m_c_Add(L: m_Specific(V: Cmp1), R: m_Specific(V: Y)))) {
1328 // ((X + Y) u< X) ? -1 : (X + Y) --> uadd.sat(X, Y)
1329 // ((X + Y) u< Y) ? -1 : (X + Y) --> uadd.sat(X, Y)
1330 return Builder.CreateBinaryIntrinsic(ID: Intrinsic::uadd_sat, LHS: Cmp1, RHS: Y);
1331 }
1332
1333 return nullptr;
1334}
1335
1336static Value *canonicalizeSaturatedAddSigned(ICmpInst *Cmp, Value *TVal,
1337 Value *FVal,
1338 InstCombiner::BuilderTy &Builder) {
1339 // Match saturated add with constant.
1340 Value *Cmp0 = Cmp->getOperand(i_nocapture: 0);
1341 Value *Cmp1 = Cmp->getOperand(i_nocapture: 1);
1342 ICmpInst::Predicate Pred = Cmp->getPredicate();
1343
1344 // Canonicalize TVal to be the saturation constant.
1345 if (match(V: FVal, P: m_MaxSignedValue()) || match(V: FVal, P: m_SignMask())) {
1346 std::swap(a&: TVal, b&: FVal);
1347 Pred = CmpInst::getInversePredicate(pred: Pred);
1348 }
1349
1350 const APInt *SatC;
1351 if (!match(V: TVal, P: m_APInt(Res&: SatC)) ||
1352 !(SatC->isMaxSignedValue() || SatC->isSignMask()))
1353 return nullptr;
1354
1355 bool IsMax = SatC->isMaxSignedValue();
1356
1357 // sge maximum signed value is canonicalized to eq maximum signed value and
1358 // requires special handling. sle minimum signed value is similarly
1359 // canonicalized to eq minimum signed value.
1360 if (Pred == ICmpInst::ICMP_EQ && Cmp1 == TVal) {
1361 // (a == INT_MAX) ? INT_MAX : a + 1 -> sadd.sat(a, 1)
1362 if (IsMax && match(V: FVal, P: m_Add(L: m_Specific(V: Cmp0), R: m_One()))) {
1363 return Builder.CreateBinaryIntrinsic(
1364 ID: Intrinsic::sadd_sat, LHS: Cmp0, RHS: ConstantInt::get(Ty: Cmp0->getType(), V: 1));
1365 }
1366
1367 // (a == INT_MIN) ? INT_MIN : a + -1 -> sadd.sat(a, -1)
1368 if (!IsMax && match(V: FVal, P: m_Add(L: m_Specific(V: Cmp0), R: m_AllOnes()))) {
1369 return Builder.CreateBinaryIntrinsic(
1370 ID: Intrinsic::sadd_sat, LHS: Cmp0,
1371 RHS: ConstantInt::getAllOnesValue(Ty: Cmp0->getType()));
1372 }
1373 return nullptr;
1374 }
1375
1376 const APInt *C;
1377
1378 // (X > Y) ? INT_MAX : (X + C) --> sadd.sat(X, C)
1379 // (X >= Y) ? INT_MAX : (X + C) --> sadd.sat(X, C)
1380 // where C > 0 and Y is INT_MAX - C or INT_MAX - C - 1
1381 if (IsMax && (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE) &&
1382 isa<Constant>(Val: Cmp1) &&
1383 match(V: FVal, P: m_Add(L: m_Specific(V: Cmp0), R: m_StrictlyPositive(V&: C)))) {
1384 // Normalize SGE to SGT for threshold comparison.
1385 if (Pred == ICmpInst::ICMP_SGE) {
1386 if (auto Flipped = getFlippedStrictnessPredicateAndConstant(
1387 Pred, C: cast<Constant>(Val: Cmp1))) {
1388 Pred = Flipped->first;
1389 Cmp1 = Flipped->second;
1390 }
1391 }
1392 // Check: X > INT_MAX - C or X > INT_MAX - C - 1
1393 APInt Threshold = *SatC - *C;
1394 if (Pred == ICmpInst::ICMP_SGT &&
1395 (match(V: Cmp1, P: m_SpecificIntAllowPoison(V: Threshold)) ||
1396 match(V: Cmp1, P: m_SpecificIntAllowPoison(V: Threshold - 1))))
1397 return Builder.CreateBinaryIntrinsic(
1398 ID: Intrinsic::sadd_sat, LHS: Cmp0, RHS: ConstantInt::get(Ty: Cmp0->getType(), V: *C));
1399 }
1400
1401 // (X < Y) ? INT_MIN : (X + C) --> sadd.sat(X, C)
1402 // (X <= Y) ? INT_MIN : (X + C) --> sadd.sat(X, C)
1403 // where C < 0 and Y is INT_MIN - C or INT_MIN - C + 1
1404 if (!IsMax && (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE) &&
1405 isa<Constant>(Val: Cmp1) &&
1406 match(V: FVal, P: m_Add(L: m_Specific(V: Cmp0), R: m_Negative(V&: C)))) {
1407 // Normalize SLE to SLT for threshold comparison.
1408 if (Pred == ICmpInst::ICMP_SLE) {
1409 if (auto Flipped = getFlippedStrictnessPredicateAndConstant(
1410 Pred, C: cast<Constant>(Val: Cmp1))) {
1411 Pred = Flipped->first;
1412 Cmp1 = Flipped->second;
1413 }
1414 }
1415 // Check: X < INT_MIN - C or X < INT_MIN - C + 1
1416 // INT_MIN - C for negative C is like INT_MIN + |C|
1417 APInt Threshold = *SatC - *C;
1418 if (Pred == ICmpInst::ICMP_SLT &&
1419 (match(V: Cmp1, P: m_SpecificIntAllowPoison(V: Threshold)) ||
1420 match(V: Cmp1, P: m_SpecificIntAllowPoison(V: Threshold + 1))))
1421 return Builder.CreateBinaryIntrinsic(
1422 ID: Intrinsic::sadd_sat, LHS: Cmp0, RHS: ConstantInt::get(Ty: Cmp0->getType(), V: *C));
1423 }
1424
1425 // Canonicalize predicate to less-than or less-or-equal-than.
1426 if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE) {
1427 std::swap(a&: Cmp0, b&: Cmp1);
1428 Pred = CmpInst::getSwappedPredicate(pred: Pred);
1429 }
1430
1431 if (Pred != ICmpInst::ICMP_SLT && Pred != ICmpInst::ICMP_SLE)
1432 return nullptr;
1433
1434 Value *X;
1435
1436 // (INT_MAX - X s< Y) ? INT_MAX : (X + Y) --> sadd.sat(X, Y)
1437 // (INT_MAX - X s< Y) ? INT_MAX : (Y + X) --> sadd.sat(X, Y)
1438 if (IsMax && match(V: Cmp0, P: m_NSWSub(L: m_SpecificInt(V: *SatC), R: m_Value(V&: X))) &&
1439 match(V: FVal, P: m_c_Add(L: m_Specific(V: X), R: m_Specific(V: Cmp1)))) {
1440 return Builder.CreateBinaryIntrinsic(ID: Intrinsic::sadd_sat, LHS: X, RHS: Cmp1);
1441 }
1442
1443 // (INT_MIN - X s> Y) ? INT_MIN : (X + Y) --> sadd.sat(X, Y)
1444 // (INT_MIN - X s> Y) ? INT_MIN : (Y + X) --> sadd.sat(X, Y)
1445 // After swapping operands from the SGT/SGE canonicalization above,
1446 // this becomes (Y s< INT_MIN - X).
1447 if (!IsMax && match(V: Cmp1, P: m_NSWSub(L: m_SpecificInt(V: *SatC), R: m_Value(V&: X))) &&
1448 match(V: FVal, P: m_c_Add(L: m_Specific(V: X), R: m_Specific(V: Cmp0)))) {
1449 return Builder.CreateBinaryIntrinsic(ID: Intrinsic::sadd_sat, LHS: X, RHS: Cmp0);
1450 }
1451
1452 return nullptr;
1453}
1454
1455static Value *canonicalizeSaturatedAdd(ICmpInst *Cmp, Value *TVal, Value *FVal,
1456 InstCombiner::BuilderTy &Builder) {
1457 if (!Cmp->hasOneUse())
1458 return nullptr;
1459
1460 if (Value *V = canonicalizeSaturatedAddUnsigned(Cmp, TVal, FVal, Builder))
1461 return V;
1462
1463 if (Value *V = canonicalizeSaturatedAddSigned(Cmp, TVal, FVal, Builder))
1464 return V;
1465
1466 return nullptr;
1467}
1468
1469/// Try to match patterns with select and subtract as absolute difference.
1470static Value *foldAbsDiff(ICmpInst *Cmp, Value *TVal, Value *FVal,
1471 InstCombiner::BuilderTy &Builder) {
1472 auto *TI = dyn_cast<Instruction>(Val: TVal);
1473 auto *FI = dyn_cast<Instruction>(Val: FVal);
1474 if (!TI || !FI)
1475 return nullptr;
1476
1477 // Normalize predicate to gt/lt rather than ge/le.
1478 ICmpInst::Predicate Pred = Cmp->getStrictPredicate();
1479 Value *A = Cmp->getOperand(i_nocapture: 0);
1480 Value *B = Cmp->getOperand(i_nocapture: 1);
1481
1482 // Normalize "A - B" as the true value of the select.
1483 if (match(V: FI, P: m_Sub(L: m_Specific(V: A), R: m_Specific(V: B)))) {
1484 std::swap(a&: FI, b&: TI);
1485 Pred = ICmpInst::getSwappedPredicate(pred: Pred);
1486 }
1487
1488 // With any pair of no-wrap subtracts:
1489 // (A > B) ? (A - B) : (B - A) --> abs(A - B)
1490 if (Pred == CmpInst::ICMP_SGT &&
1491 match(V: TI, P: m_Sub(L: m_Specific(V: A), R: m_Specific(V: B))) &&
1492 match(V: FI, P: m_Sub(L: m_Specific(V: B), R: m_Specific(V: A))) &&
1493 (TI->hasNoSignedWrap() || TI->hasNoUnsignedWrap()) &&
1494 (FI->hasNoSignedWrap() || FI->hasNoUnsignedWrap())) {
1495 // The remaining subtract is not "nuw" any more.
1496 // If there's one use of the subtract (no other use than the use we are
1497 // about to replace), then we know that the sub is "nsw" in this context
1498 // even if it was only "nuw" before. If there's another use, then we can't
1499 // add "nsw" to the existing instruction because it may not be safe in the
1500 // other user's context.
1501 TI->setHasNoUnsignedWrap(false);
1502 if (!TI->hasNoSignedWrap())
1503 TI->setHasNoSignedWrap(TI->hasOneUse());
1504 return Builder.CreateBinaryIntrinsic(ID: Intrinsic::abs, LHS: TI, RHS: Builder.getTrue());
1505 }
1506
1507 // Match: (A > B) ? (A - B) : (0 - (A - B)) --> abs(A - B)
1508 if (Pred == CmpInst::ICMP_SGT &&
1509 match(V: TI, P: m_NSWSub(L: m_Specific(V: A), R: m_Specific(V: B))) &&
1510 match(V: FI, P: m_Neg(V: m_Specific(V: TI)))) {
1511 return Builder.CreateBinaryIntrinsic(ID: Intrinsic::abs, LHS: TI,
1512 RHS: Builder.getFalse());
1513 }
1514
1515 // Match: (A < B) ? (0 - (A - B)) : (A - B) --> abs(A - B)
1516 if (Pred == CmpInst::ICMP_SLT &&
1517 match(V: FI, P: m_NSWSub(L: m_Specific(V: A), R: m_Specific(V: B))) &&
1518 match(V: TI, P: m_Neg(V: m_Specific(V: FI)))) {
1519 return Builder.CreateBinaryIntrinsic(ID: Intrinsic::abs, LHS: FI,
1520 RHS: Builder.getFalse());
1521 }
1522
1523 // Match: (A > B) ? (0 - (B - A)) : (B - A) --> abs(B - A)
1524 if (Pred == CmpInst::ICMP_SGT &&
1525 match(V: FI, P: m_NSWSub(L: m_Specific(V: B), R: m_Specific(V: A))) &&
1526 match(V: TI, P: m_Neg(V: m_Specific(V: FI)))) {
1527 return Builder.CreateBinaryIntrinsic(ID: Intrinsic::abs, LHS: FI,
1528 RHS: Builder.getFalse());
1529 }
1530
1531 // Match: (A < B) ? (B - A) : (0 - (B - A)) --> abs(B - A)
1532 if (Pred == CmpInst::ICMP_SLT &&
1533 match(V: TI, P: m_NSWSub(L: m_Specific(V: B), R: m_Specific(V: A))) &&
1534 match(V: FI, P: m_Neg(V: m_Specific(V: TI)))) {
1535 return Builder.CreateBinaryIntrinsic(ID: Intrinsic::abs, LHS: TI,
1536 RHS: Builder.getFalse());
1537 }
1538
1539 return nullptr;
1540}
1541
1542/// Fold the following code sequence:
1543/// \code
1544/// int a = ctlz(x & -x);
1545// x ? 31 - a : 32;
1546/// \code
1547///
1548/// into:
1549/// cttz(x)
1550static Instruction *foldSelectCtlzToCttz(ICmpInst *ICI, Value *TrueVal,
1551 Value *FalseVal,
1552 InstCombiner::BuilderTy &Builder) {
1553 unsigned BitWidth = TrueVal->getType()->getScalarSizeInBits();
1554 if (!ICI->isEquality() || !match(V: ICI->getOperand(i_nocapture: 1), P: m_Zero()))
1555 return nullptr;
1556
1557 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
1558 std::swap(a&: TrueVal, b&: FalseVal);
1559
1560 Value *Ctlz;
1561 if (match(V: FalseVal,
1562 P: m_Xor(L: m_Value(V&: Ctlz), R: m_SpecificIntAllowPoison(V: BitWidth - 1)))) {
1563 if (!isPowerOf2_32(Value: BitWidth))
1564 return nullptr;
1565 } else if (!match(V: FalseVal, P: m_Sub(L: m_SpecificIntAllowPoison(V: BitWidth - 1),
1566 R: m_Value(V&: Ctlz)))) {
1567 return nullptr;
1568 }
1569
1570 if (!match(V: Ctlz, P: m_Ctlz(Op0: m_Value(), Op1: m_Value())))
1571 return nullptr;
1572
1573 if (!match(V: TrueVal, P: m_SpecificInt(V: BitWidth)))
1574 return nullptr;
1575
1576 Value *X = ICI->getOperand(i_nocapture: 0);
1577 auto *II = cast<IntrinsicInst>(Val: Ctlz);
1578 if (!match(V: II->getOperand(i_nocapture: 0), P: m_c_And(L: m_Specific(V: X), R: m_Neg(V: m_Specific(V: X)))))
1579 return nullptr;
1580
1581 // The original select returns the constant bitwidth when x == 0, so the
1582 // result is defined there; the cttz must use is_zero_poison = false.
1583 Function *F = Intrinsic::getOrInsertDeclaration(
1584 M: II->getModule(), id: Intrinsic::cttz, OverloadTys: II->getType());
1585 return CallInst::Create(Func: F, Args: {X, Builder.getFalse()});
1586}
1587
1588/// Attempt to fold a cttz/ctlz followed by a icmp plus select into a single
1589/// call to cttz/ctlz with flag 'is_zero_poison' cleared.
1590///
1591/// For example, we can fold the following code sequence:
1592/// \code
1593/// %0 = tail call i32 @llvm.cttz.i32(i32 %x, i1 true)
1594/// %1 = icmp ne i32 %x, 0
1595/// %2 = select i1 %1, i32 %0, i32 32
1596/// \code
1597///
1598/// into:
1599/// %0 = tail call i32 @llvm.cttz.i32(i32 %x, i1 false)
1600static Value *foldSelectCttzCtlz(ICmpInst *ICI, Value *TrueVal, Value *FalseVal,
1601 InstCombinerImpl &IC) {
1602 ICmpInst::Predicate Pred = ICI->getPredicate();
1603 Value *CmpLHS = ICI->getOperand(i_nocapture: 0);
1604 Value *CmpRHS = ICI->getOperand(i_nocapture: 1);
1605
1606 // Check if the select condition compares a value for equality.
1607 if (!ICI->isEquality())
1608 return nullptr;
1609
1610 Value *SelectArg = FalseVal;
1611 Value *ValueOnZero = TrueVal;
1612 if (Pred == ICmpInst::ICMP_NE)
1613 std::swap(a&: SelectArg, b&: ValueOnZero);
1614
1615 // Skip zero extend/truncate.
1616 Value *Count = nullptr;
1617 if (!match(V: SelectArg, P: m_ZExt(Op: m_Value(V&: Count))) &&
1618 !match(V: SelectArg, P: m_Trunc(Op: m_Value(V&: Count))))
1619 Count = SelectArg;
1620
1621 // Check that 'Count' is a call to intrinsic cttz/ctlz. Also check that the
1622 // input to the cttz/ctlz is used as LHS for the compare instruction.
1623 Value *X;
1624 if (!match(V: Count, P: m_Cttz(Op0: m_Value(V&: X), Op1: m_Value())) &&
1625 !match(V: Count, P: m_Ctlz(Op0: m_Value(V&: X), Op1: m_Value())))
1626 return nullptr;
1627
1628 // (X == 0) ? BitWidth : ctz(X)
1629 // (X == -1) ? BitWidth : ctz(~X)
1630 // (X == Y) ? BitWidth : ctz(X ^ Y)
1631 if ((X != CmpLHS || !match(V: CmpRHS, P: m_Zero())) &&
1632 (!match(V: X, P: m_Not(V: m_Specific(V: CmpLHS))) || !match(V: CmpRHS, P: m_AllOnes())) &&
1633 !match(V: X, P: m_c_Xor(L: m_Specific(V: CmpLHS), R: m_Specific(V: CmpRHS))))
1634 return nullptr;
1635
1636 IntrinsicInst *II = cast<IntrinsicInst>(Val: Count);
1637
1638 // Check if the value propagated on zero is a constant number equal to the
1639 // sizeof in bits of 'Count'.
1640 unsigned SizeOfInBits = Count->getType()->getScalarSizeInBits();
1641 if (match(V: ValueOnZero, P: m_SpecificInt(V: SizeOfInBits))) {
1642 // A range annotation on the intrinsic may no longer be valid.
1643 II->dropPoisonGeneratingAnnotations();
1644 IC.addToWorklist(I: II);
1645 return SelectArg;
1646 }
1647
1648 // The ValueOnZero is not the bitwidth. But if the cttz/ctlz (and optional
1649 // zext/trunc) have one use (ending at the select), the cttz/ctlz result will
1650 // not be used if the input is zero. Relax to 'zero is poison' for that case.
1651 if (II->hasOneUse() && SelectArg->hasOneUse() &&
1652 !match(V: II->getArgOperand(i: 1), P: m_One())) {
1653 II->setArgOperand(i: 1, v: ConstantInt::getTrue(Context&: II->getContext()));
1654 // noundef attribute on the intrinsic may no longer be valid.
1655 II->dropUBImplyingAttrsAndMetadata();
1656 IC.addToWorklist(I: II);
1657 }
1658
1659 return nullptr;
1660}
1661
1662/// SPF can match patterns like:
1663/// (X <u C1) ? C1 : UMIN(X, C2) ==> UMAX(UMIN(X, C2), C1)
1664/// However, if the UMIN has poison-generating annotations, the result may
1665/// be more poisonous, because the poison is propagated unconditionally after
1666/// the transform. Drop annotations in this case.
1667/// FIXME: This is something of a hack that relies on details of patterns
1668// supported by SPF.
1669static void dropPoisonGeneratingAnnotationsForSPFCanonicalization(Value *Cond,
1670 Value *LHS,
1671 Value *RHS) {
1672 if (!impliesPoison(ValAssumedPoison: LHS, V: Cond))
1673 if (auto *I = dyn_cast<Instruction>(Val: LHS))
1674 I->dropPoisonGeneratingAnnotations();
1675 if (!impliesPoison(ValAssumedPoison: RHS, V: Cond))
1676 if (auto *I = dyn_cast<Instruction>(Val: RHS))
1677 I->dropPoisonGeneratingAnnotations();
1678}
1679
1680static Value *canonicalizeSPF(ICmpInst &Cmp, Value *TrueVal, Value *FalseVal,
1681 InstCombinerImpl &IC) {
1682 Value *LHS, *RHS;
1683 // TODO: What to do with pointer min/max patterns?
1684 if (!TrueVal->getType()->isIntOrIntVectorTy())
1685 return nullptr;
1686
1687 SelectPatternFlavor SPF =
1688 matchDecomposedSelectPattern(CmpI: &Cmp, TrueVal, FalseVal, LHS, RHS).Flavor;
1689 if (SPF == SelectPatternFlavor::SPF_ABS ||
1690 SPF == SelectPatternFlavor::SPF_NABS) {
1691 if (!Cmp.hasOneUse() && !RHS->hasOneUse())
1692 return nullptr; // TODO: Relax this restriction.
1693
1694 // Note that NSW flag can only be propagated for normal, non-negated abs!
1695 bool IntMinIsPoison = SPF == SelectPatternFlavor::SPF_ABS &&
1696 match(V: RHS, P: m_NSWNeg(V: m_Specific(V: LHS)));
1697 Constant *IntMinIsPoisonC =
1698 ConstantInt::get(Ty: Type::getInt1Ty(C&: Cmp.getContext()), V: IntMinIsPoison);
1699 Value *Abs =
1700 IC.Builder.CreateBinaryIntrinsic(ID: Intrinsic::abs, LHS, RHS: IntMinIsPoisonC);
1701
1702 if (SPF == SelectPatternFlavor::SPF_NABS)
1703 return IC.Builder.CreateNeg(V: Abs); // Always without NSW flag!
1704 return Abs;
1705 }
1706
1707 if (SelectPatternResult::isMinOrMax(SPF)) {
1708 Intrinsic::ID IntrinsicID = getMinMaxIntrinsic(SPF);
1709 dropPoisonGeneratingAnnotationsForSPFCanonicalization(Cond: &Cmp, LHS, RHS);
1710 return IC.Builder.CreateBinaryIntrinsic(ID: IntrinsicID, LHS, RHS);
1711 }
1712
1713 return nullptr;
1714}
1715
1716bool InstCombinerImpl::replaceInInstruction(Value *V, Value *Old, Value *New,
1717 unsigned Depth) {
1718 // Conservatively limit replacement to two instructions upwards.
1719 if (Depth == 2)
1720 return false;
1721
1722 assert(!isa<Constant>(Old) && "Only replace non-constant values");
1723
1724 auto *I = dyn_cast<Instruction>(Val: V);
1725 if (!I || !I->hasOneUse() ||
1726 !isSafeToSpeculativelyExecuteWithVariableReplaced(I))
1727 return false;
1728
1729 // Forbid potentially lane-crossing instructions.
1730 if (Old->getType()->isVectorTy() && !isNotCrossLaneOperation(I))
1731 return false;
1732
1733 bool Changed = false;
1734 for (Use &U : I->operands()) {
1735 if (U == Old) {
1736 replaceUse(U, NewValue: New);
1737 Worklist.add(I);
1738 Changed = true;
1739 } else {
1740 Changed |= replaceInInstruction(V: U, Old, New, Depth: Depth + 1);
1741 }
1742 }
1743 return Changed;
1744}
1745
1746/// If we have a select with an equality comparison, then we know the value in
1747/// one of the arms of the select. See if substituting this value into an arm
1748/// and simplifying the result yields the same value as the other arm.
1749///
1750/// To make this transform safe, we must drop poison-generating flags
1751/// (nsw, etc) if we simplified to a binop because the select may be guarding
1752/// that poison from propagating. If the existing binop already had no
1753/// poison-generating flags, then this transform can be done by instsimplify.
1754///
1755/// Consider:
1756/// %cmp = icmp eq i32 %x, 2147483647
1757/// %add = add nsw i32 %x, 1
1758/// %sel = select i1 %cmp, i32 -2147483648, i32 %add
1759///
1760/// We can't replace %sel with %add unless we strip away the flags.
1761/// TODO: Wrapping flags could be preserved in some cases with better analysis.
1762Instruction *InstCombinerImpl::foldSelectValueEquivalence(SelectInst &Sel,
1763 CmpInst &Cmp) {
1764 // Canonicalize the pattern to an equivalence on the predicate by swapping the
1765 // select operands.
1766 Value *TrueVal = Sel.getTrueValue(), *FalseVal = Sel.getFalseValue();
1767 bool Swapped = false;
1768 if (Cmp.isEquivalence(/*Invert=*/true)) {
1769 std::swap(a&: TrueVal, b&: FalseVal);
1770 Swapped = true;
1771 } else if (!Cmp.isEquivalence()) {
1772 return nullptr;
1773 }
1774
1775 Value *CmpLHS = Cmp.getOperand(i_nocapture: 0), *CmpRHS = Cmp.getOperand(i_nocapture: 1);
1776 auto ReplaceOldOpWithNewOp = [&](Value *OldOp,
1777 Value *NewOp) -> Instruction * {
1778 // In X == Y ? f(X) : Z, try to evaluate f(Y) and replace the operand.
1779 // Take care to avoid replacing X == Y ? X : Z with X == Y ? Y : Z, as that
1780 // would lead to an infinite replacement cycle.
1781 // If we will be able to evaluate f(Y) to a constant, we can allow undef,
1782 // otherwise Y cannot be undef as we might pick different values for undef
1783 // in the cmp and in f(Y).
1784 if (TrueVal == OldOp && (isa<Constant>(Val: OldOp) || !isa<Constant>(Val: NewOp)))
1785 return nullptr;
1786
1787 if (Value *V = simplifyWithOpReplaced(V: TrueVal, Op: OldOp, RepOp: NewOp, Q: SQ,
1788 /* AllowRefinement=*/true)) {
1789 // Need some guarantees about the new simplified op to ensure we don't inf
1790 // loop.
1791 // If we simplify to a constant, replace if we aren't creating new undef.
1792 if (match(V, P: m_ImmConstant()) &&
1793 isGuaranteedNotToBeUndef(V, AC: SQ.AC, CtxI: &Sel, DT: &DT))
1794 return replaceOperand(I&: Sel, OpNum: Swapped ? 2 : 1, V);
1795
1796 // If NewOp is a constant and OldOp is not replace iff NewOp doesn't
1797 // contain and undef elements.
1798 // Make sure that V is always simpler than TrueVal, otherwise we might
1799 // end up in an infinite loop.
1800 if (match(V: NewOp, P: m_ImmConstant()) ||
1801 (isa<Instruction>(Val: TrueVal) &&
1802 is_contained(Range: cast<Instruction>(Val: TrueVal)->operands(), Element: V))) {
1803 if (isGuaranteedNotToBeUndef(V: NewOp, AC: SQ.AC, CtxI: &Sel, DT: &DT))
1804 return replaceOperand(I&: Sel, OpNum: Swapped ? 2 : 1, V);
1805 return nullptr;
1806 }
1807 }
1808
1809 // Even if TrueVal does not simplify, we can directly replace a use of
1810 // CmpLHS with CmpRHS, as long as the instruction is not used anywhere
1811 // else and is safe to speculatively execute (we may end up executing it
1812 // with different operands, which should not cause side-effects or trigger
1813 // undefined behavior). Only do this if CmpRHS is a constant, as
1814 // profitability is not clear for other cases.
1815 if (OldOp == CmpLHS && match(V: NewOp, P: m_ImmConstant()) &&
1816 !match(V: OldOp, P: m_Constant()) &&
1817 isGuaranteedNotToBeUndef(V: NewOp, AC: SQ.AC, CtxI: &Sel, DT: &DT))
1818 if (replaceInInstruction(V: TrueVal, Old: OldOp, New: NewOp))
1819 return &Sel;
1820 return nullptr;
1821 };
1822
1823 bool CanReplaceCmpLHSWithRHS = canReplacePointersIfEqual(From: CmpLHS, To: CmpRHS, DL);
1824 if (CanReplaceCmpLHSWithRHS) {
1825 if (Instruction *R = ReplaceOldOpWithNewOp(CmpLHS, CmpRHS))
1826 return R;
1827 }
1828 bool CanReplaceCmpRHSWithLHS = canReplacePointersIfEqual(From: CmpRHS, To: CmpLHS, DL);
1829 if (CanReplaceCmpRHSWithLHS) {
1830 if (Instruction *R = ReplaceOldOpWithNewOp(CmpRHS, CmpLHS))
1831 return R;
1832 }
1833
1834 auto *FalseInst = dyn_cast<Instruction>(Val: FalseVal);
1835 if (!FalseInst)
1836 return nullptr;
1837
1838 // InstSimplify already performed this fold if it was possible subject to
1839 // current poison-generating flags. Check whether dropping poison-generating
1840 // flags enables the transform.
1841
1842 // Try each equivalence substitution possibility.
1843 // We have an 'EQ' comparison, so the select's false value will propagate.
1844 // Example:
1845 // (X == 42) ? 43 : (X + 1) --> (X == 42) ? (X + 1) : (X + 1) --> X + 1
1846 SmallVector<Instruction *> DropFlags;
1847 if ((CanReplaceCmpLHSWithRHS &&
1848 simplifyWithOpReplaced(V: FalseVal, Op: CmpLHS, RepOp: CmpRHS, Q: SQ,
1849 /* AllowRefinement */ false,
1850 DropFlags: &DropFlags) == TrueVal) ||
1851 (CanReplaceCmpRHSWithLHS &&
1852 simplifyWithOpReplaced(V: FalseVal, Op: CmpRHS, RepOp: CmpLHS, Q: SQ,
1853 /* AllowRefinement */ false,
1854 DropFlags: &DropFlags) == TrueVal)) {
1855 for (Instruction *I : DropFlags) {
1856 I->dropPoisonGeneratingAnnotations();
1857 Worklist.add(I);
1858 }
1859
1860 return replaceInstUsesWith(I&: Sel, V: FalseVal);
1861 }
1862
1863 Constant *CmpC;
1864 if (FalseVal->getType()->isIntOrIntVectorTy(BitWidth: 1) &&
1865 match(V: FalseVal, P: m_NUWTrunc(Op: m_Specific(V: CmpLHS))) &&
1866 match(V: CmpRHS, P: m_ImmConstant(C&: CmpC)) &&
1867 ConstantFoldCompareInstOperands(
1868 Predicate: ICmpInst::Predicate::ICMP_NE, LHS: CmpC,
1869 RHS: ConstantInt::getNullValue(Ty: CmpLHS->getType()), DL) == TrueVal) {
1870 return new ICmpInst(CmpInst::Predicate::ICMP_NE, CmpLHS,
1871 ConstantInt::getNullValue(Ty: CmpLHS->getType()));
1872 }
1873
1874 return nullptr;
1875}
1876
1877/// Fold the following code sequence:
1878/// \code
1879/// %XeqZ = icmp eq i64 %X, %Z
1880/// %YeqZ = icmp eq i64 %Y, %Z
1881/// %XeqY = icmp eq i64 %X, %Y
1882/// %not.YeqZ = xor i1 %YeqZ, true
1883/// %and = select i1 %not.YeqZ, i1 %XeqY, i1 false
1884/// %equal = select i1 %XeqZ, i1 %YeqZ, i1 %and
1885/// \code
1886///
1887/// into:
1888/// %equal = icmp eq i64 %X, %Y
1889Instruction *InstCombinerImpl::foldSelectEqualityTest(SelectInst &Sel) {
1890 Value *X, *Y, *Z;
1891 Value *XeqY, *XeqZ = Sel.getCondition(), *YeqZ = Sel.getTrueValue();
1892
1893 if (!match(V: XeqZ, P: m_SpecificICmp(MatchPred: ICmpInst::ICMP_EQ, L: m_Value(V&: X), R: m_Value(V&: Z))))
1894 return nullptr;
1895
1896 if (!match(V: YeqZ,
1897 P: m_c_SpecificICmp(MatchPred: ICmpInst::ICMP_EQ, L: m_Value(V&: Y), R: m_Specific(V: Z))))
1898 std::swap(a&: X, b&: Z);
1899
1900 if (!match(V: YeqZ,
1901 P: m_c_SpecificICmp(MatchPred: ICmpInst::ICMP_EQ, L: m_Value(V&: Y), R: m_Specific(V: Z))))
1902 return nullptr;
1903
1904 if (!match(V: Sel.getFalseValue(),
1905 P: m_c_LogicalAnd(L: m_Not(V: m_Specific(V: YeqZ)), R: m_Value(V&: XeqY))))
1906 return nullptr;
1907
1908 if (!match(V: XeqY,
1909 P: m_c_SpecificICmp(MatchPred: ICmpInst::ICMP_EQ, L: m_Specific(V: X), R: m_Specific(V: Y))))
1910 return nullptr;
1911
1912 cast<ICmpInst>(Val: XeqY)->setSameSign(false);
1913 return replaceInstUsesWith(I&: Sel, V: XeqY);
1914}
1915
1916// See if this is a pattern like:
1917// %old_cmp1 = icmp slt i32 %x, C2
1918// %old_replacement = select i1 %old_cmp1, i32 %target_low, i32 %target_high
1919// %old_x_offseted = add i32 %x, C1
1920// %old_cmp0 = icmp ult i32 %old_x_offseted, C0
1921// %r = select i1 %old_cmp0, i32 %x, i32 %old_replacement
1922// This can be rewritten as more canonical pattern:
1923// %new_cmp1 = icmp slt i32 %x, -C1
1924// %new_cmp2 = icmp sge i32 %x, C0-C1
1925// %new_clamped_low = select i1 %new_cmp1, i32 %target_low, i32 %x
1926// %r = select i1 %new_cmp2, i32 %target_high, i32 %new_clamped_low
1927// Iff -C1 s<= C2 s<= C0-C1
1928// Also ULT predicate can also be UGT iff C0 != -1 (+invert result)
1929// SLT predicate can also be SGT iff C2 != INT_MAX (+invert res.)
1930static Value *canonicalizeClampLike(SelectInst &Sel0, ICmpInst &Cmp0,
1931 InstCombiner::BuilderTy &Builder,
1932 InstCombiner &IC) {
1933 Value *X = Sel0.getTrueValue();
1934 Value *Sel1 = Sel0.getFalseValue();
1935
1936 // First match the condition of the outermost select.
1937 // Said condition must be one-use.
1938 if (!Cmp0.hasOneUse())
1939 return nullptr;
1940 ICmpInst::Predicate Pred0 = Cmp0.getPredicate();
1941 Value *Cmp00 = Cmp0.getOperand(i_nocapture: 0);
1942 Constant *C0;
1943 if (!match(V: Cmp0.getOperand(i_nocapture: 1),
1944 P: m_CombineAnd(Ps: m_AnyIntegralConstant(), Ps: m_Constant(C&: C0))))
1945 return nullptr;
1946
1947 if (!match(V: Sel1, P: m_SelectLike(C: m_Value(), TrueC: m_Value(), FalseC: m_Value()))) {
1948 Pred0 = ICmpInst::getInversePredicate(pred: Pred0);
1949 std::swap(a&: X, b&: Sel1);
1950 }
1951
1952 // Canonicalize Cmp0 into ult or uge.
1953 // FIXME: we shouldn't care about lanes that are 'undef' in the end?
1954 switch (Pred0) {
1955 case ICmpInst::Predicate::ICMP_ULT:
1956 case ICmpInst::Predicate::ICMP_UGE:
1957 // Although icmp ult %x, 0 is an unusual thing to try and should generally
1958 // have been simplified, it does not verify with undef inputs so ensure we
1959 // are not in a strange state.
1960 if (!match(V: C0, P: m_SpecificInt_ICMP(
1961 Predicate: ICmpInst::Predicate::ICMP_NE,
1962 Threshold: APInt::getZero(numBits: C0->getType()->getScalarSizeInBits()))))
1963 return nullptr;
1964 break; // Great!
1965 case ICmpInst::Predicate::ICMP_ULE:
1966 case ICmpInst::Predicate::ICMP_UGT:
1967 // We want to canonicalize it to 'ult' or 'uge', so we'll need to increment
1968 // C0, which again means it must not have any all-ones elements.
1969 if (!match(V: C0,
1970 P: m_SpecificInt_ICMP(
1971 Predicate: ICmpInst::Predicate::ICMP_NE,
1972 Threshold: APInt::getAllOnes(numBits: C0->getType()->getScalarSizeInBits()))))
1973 return nullptr; // Can't do, have all-ones element[s].
1974 Pred0 = ICmpInst::getFlippedStrictnessPredicate(pred: Pred0);
1975 C0 = InstCombiner::AddOne(C: C0);
1976 break;
1977 default:
1978 return nullptr; // Unknown predicate.
1979 }
1980
1981 // Now that we've canonicalized the ICmp, we know the X we expect;
1982 // the select in other hand should be one-use.
1983 if (!Sel1->hasOneUse())
1984 return nullptr;
1985
1986 // If the types do not match, look through any truncs to the underlying
1987 // instruction.
1988 if (Cmp00->getType() != X->getType() && X->hasOneUse())
1989 match(V: X, P: m_TruncOrSelf(Op: m_Value(V&: X)));
1990
1991 // We now can finish matching the condition of the outermost select:
1992 // it should either be the X itself, or an addition of some constant to X.
1993 Constant *C1;
1994 if (Cmp00 == X)
1995 C1 = ConstantInt::getNullValue(Ty: X->getType());
1996 else if (!match(V: Cmp00,
1997 P: m_Add(L: m_Specific(V: X),
1998 R: m_CombineAnd(Ps: m_AnyIntegralConstant(), Ps: m_Constant(C&: C1)))))
1999 return nullptr;
2000
2001 Value *Cmp1;
2002 CmpPredicate Pred1;
2003 Constant *C2;
2004 Value *ReplacementLow, *ReplacementHigh;
2005 if (!match(V: Sel1, P: m_SelectLike(C: m_Value(V&: Cmp1), TrueC: m_Value(V&: ReplacementLow),
2006 FalseC: m_Value(V&: ReplacementHigh))) ||
2007 !match(V: Cmp1,
2008 P: m_ICmp(Pred&: Pred1, L: m_Specific(V: X),
2009 R: m_CombineAnd(Ps: m_AnyIntegralConstant(), Ps: m_Constant(C&: C2)))))
2010 return nullptr;
2011
2012 if (!Cmp1->hasOneUse() && (Cmp00 == X || !Cmp00->hasOneUse()))
2013 return nullptr; // Not enough one-use instructions for the fold.
2014 // FIXME: this restriction could be relaxed if Cmp1 can be reused as one of
2015 // two comparisons we'll need to build.
2016
2017 // Canonicalize Cmp1 into the form we expect.
2018 // FIXME: we shouldn't care about lanes that are 'undef' in the end?
2019 switch (Pred1) {
2020 case ICmpInst::Predicate::ICMP_SLT:
2021 break;
2022 case ICmpInst::Predicate::ICMP_SLE:
2023 // We'd have to increment C2 by one, and for that it must not have signed
2024 // max element, but then it would have been canonicalized to 'slt' before
2025 // we get here. So we can't do anything useful with 'sle'.
2026 return nullptr;
2027 case ICmpInst::Predicate::ICMP_SGT:
2028 // We want to canonicalize it to 'slt', so we'll need to increment C2,
2029 // which again means it must not have any signed max elements.
2030 if (!match(V: C2,
2031 P: m_SpecificInt_ICMP(Predicate: ICmpInst::Predicate::ICMP_NE,
2032 Threshold: APInt::getSignedMaxValue(
2033 numBits: C2->getType()->getScalarSizeInBits()))))
2034 return nullptr; // Can't do, have signed max element[s].
2035 C2 = InstCombiner::AddOne(C: C2);
2036 [[fallthrough]];
2037 case ICmpInst::Predicate::ICMP_SGE:
2038 // Also non-canonical, but here we don't need to change C2,
2039 // so we don't have any restrictions on C2, so we can just handle it.
2040 Pred1 = ICmpInst::Predicate::ICMP_SLT;
2041 std::swap(a&: ReplacementLow, b&: ReplacementHigh);
2042 break;
2043 default:
2044 return nullptr; // Unknown predicate.
2045 }
2046 assert(Pred1 == ICmpInst::Predicate::ICMP_SLT &&
2047 "Unexpected predicate type.");
2048
2049 // The thresholds of this clamp-like pattern.
2050 auto *ThresholdLowIncl = ConstantExpr::getNeg(C: C1);
2051 auto *ThresholdHighExcl = ConstantExpr::getSub(C1: C0, C2: C1);
2052
2053 assert((Pred0 == ICmpInst::Predicate::ICMP_ULT ||
2054 Pred0 == ICmpInst::Predicate::ICMP_UGE) &&
2055 "Unexpected predicate type.");
2056 if (Pred0 == ICmpInst::Predicate::ICMP_UGE)
2057 std::swap(a&: ThresholdLowIncl, b&: ThresholdHighExcl);
2058
2059 // The fold has a precondition 1: C2 s>= ThresholdLow
2060 auto *Precond1 = ConstantFoldCompareInstOperands(
2061 Predicate: ICmpInst::Predicate::ICMP_SGE, LHS: C2, RHS: ThresholdLowIncl, DL: IC.getDataLayout());
2062 if (!Precond1 || !match(V: Precond1, P: m_One()))
2063 return nullptr;
2064 // The fold has a precondition 2: C2 s<= ThresholdHigh
2065 auto *Precond2 = ConstantFoldCompareInstOperands(
2066 Predicate: ICmpInst::Predicate::ICMP_SLE, LHS: C2, RHS: ThresholdHighExcl, DL: IC.getDataLayout());
2067 if (!Precond2 || !match(V: Precond2, P: m_One()))
2068 return nullptr;
2069
2070 // If we are matching from a truncated input, we need to sext the
2071 // ReplacementLow and ReplacementHigh values. Only do the transform if they
2072 // are free to extend due to being constants.
2073 if (X->getType() != Sel0.getType()) {
2074 Constant *LowC, *HighC;
2075 if (!match(V: ReplacementLow, P: m_ImmConstant(C&: LowC)) ||
2076 !match(V: ReplacementHigh, P: m_ImmConstant(C&: HighC)))
2077 return nullptr;
2078 const DataLayout &DL = Sel0.getDataLayout();
2079 ReplacementLow =
2080 ConstantFoldCastOperand(Opcode: Instruction::SExt, C: LowC, DestTy: X->getType(), DL);
2081 ReplacementHigh =
2082 ConstantFoldCastOperand(Opcode: Instruction::SExt, C: HighC, DestTy: X->getType(), DL);
2083 assert(ReplacementLow && ReplacementHigh &&
2084 "Constant folding of ImmConstant cannot fail");
2085 }
2086
2087 // We mark the select instructions below as having an unknown profile as it is
2088 // not possible to recover profile information from the original selects in
2089 // the general case. From them we can only know the probability that we clamp
2090 // whereas we need the probabilities for clamping specific to the low end/high
2091 // end.
2092
2093 // All good, finally emit the new pattern.
2094 Value *ShouldReplaceLow = Builder.CreateICmpSLT(LHS: X, RHS: ThresholdLowIncl);
2095 Value *ShouldReplaceHigh = Builder.CreateICmpSGE(LHS: X, RHS: ThresholdHighExcl);
2096 Value *MaybeReplacedLow = Builder.CreateSelectWithUnknownProfile(
2097 C: ShouldReplaceLow, True: ReplacementLow, False: X, DEBUG_TYPE);
2098
2099 // Create the final select. If we looked through a truncate above, we will
2100 // need to retruncate the result.
2101 Value *MaybeReplacedHigh = Builder.CreateSelectWithUnknownProfile(
2102 C: ShouldReplaceHigh, True: ReplacementHigh, False: MaybeReplacedLow, DEBUG_TYPE);
2103 return Builder.CreateTrunc(V: MaybeReplacedHigh, DestTy: Sel0.getType());
2104}
2105
2106// If we have
2107// %cmp = icmp [canonical predicate] i32 %x, C0
2108// %r = select i1 %cmp, i32 %y, i32 C1
2109// Where C0 != C1 and %x may be different from %y, see if the constant that we
2110// will have if we flip the strictness of the predicate (i.e. without changing
2111// the result) is identical to the C1 in select. If it matches we can change
2112// original comparison to one with swapped predicate, reuse the constant,
2113// and swap the hands of select.
2114static Instruction *
2115tryToReuseConstantFromSelectInComparison(SelectInst &Sel, ICmpInst &Cmp,
2116 InstCombinerImpl &IC) {
2117 CmpPredicate Pred;
2118 Value *X;
2119 Constant *C0;
2120 if (!match(V: &Cmp, P: m_OneUse(SubPattern: m_ICmp(
2121 Pred, L: m_Value(V&: X),
2122 R: m_CombineAnd(Ps: m_AnyIntegralConstant(), Ps: m_Constant(C&: C0))))))
2123 return nullptr;
2124
2125 // If comparison predicate is non-relational, we won't be able to do anything.
2126 if (ICmpInst::isEquality(P: Pred))
2127 return nullptr;
2128
2129 // If comparison predicate is non-canonical, then we certainly won't be able
2130 // to make it canonical; canonicalizeCmpWithConstant() already tried.
2131 if (!InstCombiner::isCanonicalPredicate(Pred))
2132 return nullptr;
2133
2134 // If the [input] type of comparison and select type are different, lets abort
2135 // for now. We could try to compare constants with trunc/[zs]ext though.
2136 if (C0->getType() != Sel.getType())
2137 return nullptr;
2138
2139 // ULT with 'add' of a constant is canonical. See foldICmpAddConstant().
2140 // FIXME: Are there more magic icmp predicate+constant pairs we must avoid?
2141 // Or should we just abandon this transform entirely?
2142 if (Pred == CmpInst::ICMP_ULT && match(V: X, P: m_Add(L: m_Value(), R: m_Constant())))
2143 return nullptr;
2144
2145
2146 Value *SelVal0, *SelVal1; // We do not care which one is from where.
2147 match(V: &Sel, P: m_Select(C: m_Value(), L: m_Value(V&: SelVal0), R: m_Value(V&: SelVal1)));
2148 // At least one of these values we are selecting between must be a constant
2149 // else we'll never succeed.
2150 if (!match(V: SelVal0, P: m_AnyIntegralConstant()) &&
2151 !match(V: SelVal1, P: m_AnyIntegralConstant()))
2152 return nullptr;
2153
2154 // Does this constant C match any of the `select` values?
2155 auto MatchesSelectValue = [SelVal0, SelVal1](Constant *C) {
2156 return C->isElementWiseEqual(Y: SelVal0) || C->isElementWiseEqual(Y: SelVal1);
2157 };
2158
2159 // If C0 *already* matches true/false value of select, we are done.
2160 if (MatchesSelectValue(C0))
2161 return nullptr;
2162
2163 // Check the constant we'd have with flipped-strictness predicate.
2164 auto FlippedStrictness = getFlippedStrictnessPredicateAndConstant(Pred, C: C0);
2165 if (!FlippedStrictness)
2166 return nullptr;
2167
2168 // If said constant doesn't match either, then there is no hope,
2169 if (!MatchesSelectValue(FlippedStrictness->second))
2170 return nullptr;
2171
2172 // It matched! Lets insert the new comparison just before select.
2173 InstCombiner::BuilderTy::InsertPointGuard Guard(IC.Builder);
2174 IC.Builder.SetInsertPoint(&Sel);
2175
2176 Pred = ICmpInst::getSwappedPredicate(pred: Pred); // Yes, swapped.
2177 Value *NewCmp = IC.Builder.CreateICmp(P: Pred, LHS: X, RHS: FlippedStrictness->second,
2178 Name: Cmp.getName() + ".inv");
2179 IC.replaceOperand(I&: Sel, OpNum: 0, V: NewCmp);
2180 Sel.swapValues();
2181 Sel.swapProfMetadata();
2182
2183 return &Sel;
2184}
2185
2186static Instruction *foldSelectZeroOrOnes(ICmpInst *Cmp, Value *TVal,
2187 Value *FVal,
2188 InstCombiner::BuilderTy &Builder) {
2189 if (!Cmp->hasOneUse())
2190 return nullptr;
2191
2192 const APInt *CmpC;
2193 if (!match(V: Cmp->getOperand(i_nocapture: 1), P: m_APIntAllowPoison(Res&: CmpC)))
2194 return nullptr;
2195
2196 // (X u< 2) ? -X : -1 --> sext (X != 0)
2197 Value *X = Cmp->getOperand(i_nocapture: 0);
2198 if (Cmp->getPredicate() == ICmpInst::ICMP_ULT && *CmpC == 2 &&
2199 match(V: TVal, P: m_Neg(V: m_Specific(V: X))) && match(V: FVal, P: m_AllOnes()))
2200 return new SExtInst(Builder.CreateIsNotNull(Arg: X), TVal->getType());
2201
2202 // (X u> 1) ? -1 : -X --> sext (X != 0)
2203 if (Cmp->getPredicate() == ICmpInst::ICMP_UGT && *CmpC == 1 &&
2204 match(V: FVal, P: m_Neg(V: m_Specific(V: X))) && match(V: TVal, P: m_AllOnes()))
2205 return new SExtInst(Builder.CreateIsNotNull(Arg: X), TVal->getType());
2206
2207 return nullptr;
2208}
2209
2210static Value *foldSelectInstWithICmpConst(SelectInst &SI, ICmpInst *ICI,
2211 InstCombiner::BuilderTy &Builder) {
2212 const APInt *CmpC;
2213 Value *V;
2214 CmpPredicate Pred;
2215 if (!match(V: ICI, P: m_ICmp(Pred, L: m_Value(V), R: m_APInt(Res&: CmpC))))
2216 return nullptr;
2217
2218 // Match clamp away from min/max value as a max/min operation.
2219 Value *TVal = SI.getTrueValue();
2220 Value *FVal = SI.getFalseValue();
2221 if (Pred == ICmpInst::ICMP_EQ && V == FVal) {
2222 // (V == UMIN) ? UMIN+1 : V --> umax(V, UMIN+1)
2223 if (CmpC->isMinValue() && match(V: TVal, P: m_SpecificInt(V: *CmpC + 1)))
2224 return Builder.CreateBinaryIntrinsic(ID: Intrinsic::umax, LHS: V, RHS: TVal);
2225 // (V == UMAX) ? UMAX-1 : V --> umin(V, UMAX-1)
2226 if (CmpC->isMaxValue() && match(V: TVal, P: m_SpecificInt(V: *CmpC - 1)))
2227 return Builder.CreateBinaryIntrinsic(ID: Intrinsic::umin, LHS: V, RHS: TVal);
2228 // (V == SMIN) ? SMIN+1 : V --> smax(V, SMIN+1)
2229 if (CmpC->isMinSignedValue() && match(V: TVal, P: m_SpecificInt(V: *CmpC + 1)))
2230 return Builder.CreateBinaryIntrinsic(ID: Intrinsic::smax, LHS: V, RHS: TVal);
2231 // (V == SMAX) ? SMAX-1 : V --> smin(V, SMAX-1)
2232 if (CmpC->isMaxSignedValue() && match(V: TVal, P: m_SpecificInt(V: *CmpC - 1)))
2233 return Builder.CreateBinaryIntrinsic(ID: Intrinsic::smin, LHS: V, RHS: TVal);
2234 }
2235
2236 // Fold icmp(X) ? f(X) : C to f(X) when f(X) is guaranteed to be equal to C
2237 // for all X in the exact range of the inverse predicate.
2238 Instruction *Op;
2239 const APInt *C;
2240 CmpInst::Predicate CPred;
2241 if (match(V: &SI, P: m_Select(C: m_Specific(V: ICI), L: m_APInt(Res&: C), R: m_Instruction(I&: Op))))
2242 CPred = ICI->getPredicate();
2243 else if (match(V: &SI, P: m_Select(C: m_Specific(V: ICI), L: m_Instruction(I&: Op), R: m_APInt(Res&: C))))
2244 CPred = ICI->getInversePredicate();
2245 else
2246 return nullptr;
2247
2248 ConstantRange InvDomCR = ConstantRange::makeExactICmpRegion(Pred: CPred, Other: *CmpC);
2249 const APInt *OpC;
2250 if (match(V: Op, P: m_BinOp(L: m_Specific(V), R: m_APInt(Res&: OpC)))) {
2251 ConstantRange R = InvDomCR.binaryOp(
2252 BinOp: static_cast<Instruction::BinaryOps>(Op->getOpcode()), Other: *OpC);
2253 if (R == *C) {
2254 Op->dropPoisonGeneratingFlags();
2255 return Op;
2256 }
2257 }
2258 if (auto *MMI = dyn_cast<MinMaxIntrinsic>(Val: Op);
2259 MMI && MMI->getLHS() == V && match(V: MMI->getRHS(), P: m_APInt(Res&: OpC))) {
2260 ConstantRange R = ConstantRange::intrinsic(IntrinsicID: MMI->getIntrinsicID(),
2261 Ops: {InvDomCR, ConstantRange(*OpC)});
2262 if (R == *C) {
2263 MMI->dropPoisonGeneratingAnnotations();
2264 return MMI;
2265 }
2266 }
2267
2268 return nullptr;
2269}
2270
2271/// `A == MIN_INT ? B != MIN_INT : A < B` --> `A < B`
2272/// `A == MAX_INT ? B != MAX_INT : A > B` --> `A > B`
2273static Instruction *foldSelectWithExtremeEqCond(Value *CmpLHS, Value *CmpRHS,
2274 Value *TrueVal,
2275 Value *FalseVal) {
2276 Type *Ty = CmpLHS->getType();
2277
2278 if (Ty->isPtrOrPtrVectorTy())
2279 return nullptr;
2280
2281 CmpPredicate Pred;
2282 Value *B;
2283
2284 if (!match(V: FalseVal, P: m_c_ICmp(Pred, L: m_Specific(V: CmpLHS), R: m_Value(V&: B))))
2285 return nullptr;
2286
2287 Value *TValRHS;
2288 if (!match(V: TrueVal, P: m_SpecificICmp(MatchPred: ICmpInst::ICMP_NE, L: m_Specific(V: B),
2289 R: m_Value(V&: TValRHS))))
2290 return nullptr;
2291
2292 APInt C;
2293 unsigned BitWidth = Ty->getScalarSizeInBits();
2294
2295 if (ICmpInst::isLT(P: Pred)) {
2296 C = CmpInst::isSigned(Pred) ? APInt::getSignedMinValue(numBits: BitWidth)
2297 : APInt::getMinValue(numBits: BitWidth);
2298 } else if (ICmpInst::isGT(P: Pred)) {
2299 C = CmpInst::isSigned(Pred) ? APInt::getSignedMaxValue(numBits: BitWidth)
2300 : APInt::getMaxValue(numBits: BitWidth);
2301 } else {
2302 return nullptr;
2303 }
2304
2305 if (!match(V: CmpRHS, P: m_SpecificInt(V: C)) || !match(V: TValRHS, P: m_SpecificInt(V: C)))
2306 return nullptr;
2307
2308 return new ICmpInst(Pred, CmpLHS, B);
2309}
2310
2311static Instruction *foldSelectICmpEq(SelectInst &SI, ICmpInst *ICI,
2312 InstCombinerImpl &IC) {
2313 ICmpInst::Predicate Pred = ICI->getPredicate();
2314 if (!ICmpInst::isEquality(P: Pred))
2315 return nullptr;
2316
2317 Value *TrueVal = SI.getTrueValue();
2318 Value *FalseVal = SI.getFalseValue();
2319 Value *CmpLHS = ICI->getOperand(i_nocapture: 0);
2320 Value *CmpRHS = ICI->getOperand(i_nocapture: 1);
2321
2322 if (Pred == ICmpInst::ICMP_NE)
2323 std::swap(a&: TrueVal, b&: FalseVal);
2324
2325 if (Instruction *Res =
2326 foldSelectWithExtremeEqCond(CmpLHS, CmpRHS, TrueVal, FalseVal))
2327 return Res;
2328
2329 return nullptr;
2330}
2331
2332/// Fold `X Pred C1 ? X BOp C2 : C1 BOp C2` to `min/max(X, C1) BOp C2`.
2333/// This allows for better canonicalization.
2334Value *InstCombinerImpl::foldSelectWithConstOpToBinOp(ICmpInst *Cmp,
2335 Value *TrueVal,
2336 Value *FalseVal) {
2337 Constant *C1, *C2, *C3;
2338 Value *X;
2339 CmpPredicate Predicate;
2340
2341 if (!match(V: Cmp, P: m_ICmp(Pred&: Predicate, L: m_Value(V&: X), R: m_Constant(C&: C1))))
2342 return nullptr;
2343
2344 if (!ICmpInst::isRelational(P: Predicate))
2345 return nullptr;
2346
2347 if (match(V: TrueVal, P: m_Constant())) {
2348 std::swap(a&: FalseVal, b&: TrueVal);
2349 Predicate = ICmpInst::getInversePredicate(pred: Predicate);
2350 }
2351
2352 if (!match(V: FalseVal, P: m_Constant(C&: C3)) || !TrueVal->hasOneUse())
2353 return nullptr;
2354
2355 bool IsIntrinsic;
2356 unsigned Opcode;
2357 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(Val: TrueVal)) {
2358 Opcode = BOp->getOpcode();
2359 IsIntrinsic = false;
2360
2361 // This fold causes some regressions and is primarily intended for
2362 // add and sub. So we early exit for div and rem to minimize the
2363 // regressions.
2364 if (Instruction::isIntDivRem(Opcode))
2365 return nullptr;
2366
2367 if (!match(V: BOp, P: m_BinOp(L: m_Specific(V: X), R: m_Constant(C&: C2))))
2368 return nullptr;
2369
2370 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Val: TrueVal)) {
2371 if (!match(V: II, P: m_MaxOrMin(Op0: m_Specific(V: X), Op1: m_Constant(C&: C2))))
2372 return nullptr;
2373 Opcode = II->getIntrinsicID();
2374 IsIntrinsic = true;
2375 } else {
2376 return nullptr;
2377 }
2378
2379 Value *RHS;
2380 SelectPatternFlavor SPF;
2381 const DataLayout &DL = Cmp->getDataLayout();
2382 auto Flipped = getFlippedStrictnessPredicateAndConstant(Pred: Predicate, C: C1);
2383
2384 auto FoldBinaryOpOrIntrinsic = [&](Constant *LHS, Constant *RHS) {
2385 return IsIntrinsic
2386 ? ConstantFoldIntrinsic(ID: Opcode, Ops: {LHS, RHS}, Ty: LHS->getType(), DL)
2387 : ConstantFoldBinaryOpOperands(Opcode, LHS, RHS, DL);
2388 };
2389
2390 if (C3 == FoldBinaryOpOrIntrinsic(C1, C2)) {
2391 SPF = getSelectPattern(Pred: Predicate).Flavor;
2392 RHS = C1;
2393 } else if (Flipped && C3 == FoldBinaryOpOrIntrinsic(Flipped->second, C2)) {
2394 SPF = getSelectPattern(Pred: Flipped->first).Flavor;
2395 RHS = Flipped->second;
2396 } else {
2397 return nullptr;
2398 }
2399
2400 Intrinsic::ID MinMaxID = getMinMaxIntrinsic(SPF);
2401 Value *MinMax = Builder.CreateBinaryIntrinsic(ID: MinMaxID, LHS: X, RHS);
2402 if (IsIntrinsic)
2403 return Builder.CreateBinaryIntrinsic(ID: Opcode, LHS: MinMax, RHS: C2);
2404
2405 const auto BinOpc = Instruction::BinaryOps(Opcode);
2406 Value *BinOp = Builder.CreateBinOp(Opc: BinOpc, LHS: MinMax, RHS: C2);
2407
2408 // If we can attach no-wrap flags to the new instruction, do so if the
2409 // old instruction had them and C1 BinOp C2 does not overflow.
2410 if (Instruction *BinOpInst = dyn_cast<Instruction>(Val: BinOp)) {
2411 if (BinOpc == Instruction::Add || BinOpc == Instruction::Sub ||
2412 BinOpc == Instruction::Mul) {
2413 Instruction *OldBinOp = cast<BinaryOperator>(Val: TrueVal);
2414 if (OldBinOp->hasNoSignedWrap() &&
2415 willNotOverflow(Opcode: BinOpc, LHS: RHS, RHS: C2, CtxI: *BinOpInst, /*IsSigned=*/true))
2416 BinOpInst->setHasNoSignedWrap();
2417 if (OldBinOp->hasNoUnsignedWrap() &&
2418 willNotOverflow(Opcode: BinOpc, LHS: RHS, RHS: C2, CtxI: *BinOpInst, /*IsSigned=*/false))
2419 BinOpInst->setHasNoUnsignedWrap();
2420 }
2421 }
2422 return BinOp;
2423}
2424
2425/// Folds:
2426/// %a_sub = call @llvm.usub.sat(x, IntConst1)
2427/// %b_sub = call @llvm.usub.sat(y, IntConst2)
2428/// %or = or %a_sub, %b_sub
2429/// %cmp = icmp eq %or, 0
2430/// %sel = select %cmp, 0, MostSignificantBit
2431/// into:
2432/// %a_sub' = usub.sat(x, IntConst1 - MostSignificantBit)
2433/// %b_sub' = usub.sat(y, IntConst2 - MostSignificantBit)
2434/// %or = or %a_sub', %b_sub'
2435/// %and = and %or, MostSignificantBit
2436/// Likewise, for vector arguments as well.
2437static Instruction *foldICmpUSubSatWithAndForMostSignificantBitCmp(
2438 SelectInst &SI, ICmpInst *ICI, InstCombiner::BuilderTy &Builder) {
2439 if (!SI.hasOneUse() || !ICI->hasOneUse())
2440 return nullptr;
2441 CmpPredicate Pred;
2442 Value *A, *B;
2443 const APInt *Constant1, *Constant2;
2444 if (!match(V: SI.getCondition(),
2445 P: m_ICmp(Pred,
2446 L: m_OneUse(SubPattern: m_Or(L: m_OneUse(SubPattern: m_Intrinsic<Intrinsic::usub_sat>(
2447 Ops: m_Value(V&: A), Ops: m_APInt(Res&: Constant1))),
2448 R: m_OneUse(SubPattern: m_Intrinsic<Intrinsic::usub_sat>(
2449 Ops: m_Value(V&: B), Ops: m_APInt(Res&: Constant2))))),
2450 R: m_Zero())))
2451 return nullptr;
2452
2453 Value *TrueVal = SI.getTrueValue();
2454 Value *FalseVal = SI.getFalseValue();
2455 if (!((Pred == ICmpInst::ICMP_EQ && match(V: TrueVal, P: m_Zero()) &&
2456 match(V: FalseVal, P: m_SignMask())) ||
2457 (Pred == ICmpInst::ICMP_NE && match(V: TrueVal, P: m_SignMask()) &&
2458 match(V: FalseVal, P: m_Zero()))))
2459 return nullptr;
2460
2461 auto *Ty = A->getType();
2462 unsigned BW = Constant1->getBitWidth();
2463 APInt MostSignificantBit = APInt::getSignMask(BitWidth: BW);
2464
2465 // Anything over MSB is negative
2466 if (Constant1->isNonNegative() || Constant2->isNonNegative())
2467 return nullptr;
2468
2469 APInt AdjAP1 = *Constant1 - MostSignificantBit + 1;
2470 APInt AdjAP2 = *Constant2 - MostSignificantBit + 1;
2471
2472 auto *Adj1 = ConstantInt::get(Ty, V: AdjAP1);
2473 auto *Adj2 = ConstantInt::get(Ty, V: AdjAP2);
2474
2475 Value *NewA = Builder.CreateBinaryIntrinsic(ID: Intrinsic::usub_sat, LHS: A, RHS: Adj1);
2476 Value *NewB = Builder.CreateBinaryIntrinsic(ID: Intrinsic::usub_sat, LHS: B, RHS: Adj2);
2477 Value *Or = Builder.CreateOr(LHS: NewA, RHS: NewB);
2478 Constant *MSBConst = ConstantInt::get(Ty, V: MostSignificantBit);
2479 return BinaryOperator::CreateAnd(V1: Or, V2: MSBConst);
2480}
2481
2482/// Visit a SelectInst that has an ICmpInst as its first operand.
2483Instruction *InstCombinerImpl::foldSelectInstWithICmp(SelectInst &SI,
2484 ICmpInst *ICI) {
2485 if (Value *V =
2486 canonicalizeSPF(Cmp&: *ICI, TrueVal: SI.getTrueValue(), FalseVal: SI.getFalseValue(), IC&: *this))
2487 return replaceInstUsesWith(I&: SI, V);
2488
2489 if (Value *V = foldSelectInstWithICmpConst(SI, ICI, Builder))
2490 return replaceInstUsesWith(I&: SI, V);
2491
2492 if (Value *V = canonicalizeClampLike(Sel0&: SI, Cmp0&: *ICI, Builder, IC&: *this))
2493 return replaceInstUsesWith(I&: SI, V);
2494
2495 if (Instruction *NewSel =
2496 tryToReuseConstantFromSelectInComparison(Sel&: SI, Cmp&: *ICI, IC&: *this))
2497 return NewSel;
2498 if (Instruction *Folded =
2499 foldICmpUSubSatWithAndForMostSignificantBitCmp(SI, ICI, Builder))
2500 return Folded;
2501
2502 // NOTE: if we wanted to, this is where to detect integer MIN/MAX
2503 bool Changed = false;
2504 Value *TrueVal = SI.getTrueValue();
2505 Value *FalseVal = SI.getFalseValue();
2506 ICmpInst::Predicate Pred = ICI->getPredicate();
2507 Value *CmpLHS = ICI->getOperand(i_nocapture: 0);
2508 Value *CmpRHS = ICI->getOperand(i_nocapture: 1);
2509
2510 if (Instruction *NewSel = foldSelectICmpEq(SI, ICI, IC&: *this))
2511 return NewSel;
2512
2513 // Canonicalize a signbit condition to use zero constant by swapping:
2514 // (CmpLHS > -1) ? TV : FV --> (CmpLHS < 0) ? FV : TV
2515 // To avoid conflicts (infinite loops) with other canonicalizations, this is
2516 // not applied with any constant select arm.
2517 if (Pred == ICmpInst::ICMP_SGT && match(V: CmpRHS, P: m_AllOnes()) &&
2518 !match(V: TrueVal, P: m_Constant()) && !match(V: FalseVal, P: m_Constant()) &&
2519 ICI->hasOneUse()) {
2520 InstCombiner::BuilderTy::InsertPointGuard Guard(Builder);
2521 Builder.SetInsertPoint(&SI);
2522 Value *IsNeg = Builder.CreateIsNeg(Arg: CmpLHS, Name: ICI->getName());
2523 replaceOperand(I&: SI, OpNum: 0, V: IsNeg);
2524 SI.swapValues();
2525 SI.swapProfMetadata();
2526 return &SI;
2527 }
2528
2529 if (Value *V = foldSelectICmpMinMax(Cmp: ICI, TVal: TrueVal, FVal: FalseVal, Builder,
2530 SQ: SQ.getWithInstruction(I: &SI)))
2531 return replaceInstUsesWith(I&: SI, V);
2532
2533 if (Value *V = foldSelectICmpAndZeroShl(Cmp: ICI, TVal: TrueVal, FVal: FalseVal, Builder))
2534 return replaceInstUsesWith(I&: SI, V);
2535
2536 if (Instruction *V = foldSelectCtlzToCttz(ICI, TrueVal, FalseVal, Builder))
2537 return V;
2538
2539 if (Instruction *V = foldSelectZeroOrOnes(Cmp: ICI, TVal: TrueVal, FVal: FalseVal, Builder))
2540 return V;
2541
2542 if (Value *V = foldSelectICmpLshrAshr(IC: ICI, TrueVal, FalseVal, Builder))
2543 return replaceInstUsesWith(I&: SI, V);
2544
2545 if (Value *V = foldSelectCttzCtlz(ICI, TrueVal, FalseVal, IC&: *this))
2546 return replaceInstUsesWith(I&: SI, V);
2547
2548 if (Value *V = canonicalizeSaturatedSubtract(ICI, TrueVal, FalseVal, Builder))
2549 return replaceInstUsesWith(I&: SI, V);
2550
2551 if (Value *V = canonicalizeSaturatedAdd(Cmp: ICI, TVal: TrueVal, FVal: FalseVal, Builder))
2552 return replaceInstUsesWith(I&: SI, V);
2553
2554 if (Value *V = foldAbsDiff(Cmp: ICI, TVal: TrueVal, FVal: FalseVal, Builder))
2555 return replaceInstUsesWith(I&: SI, V);
2556
2557 if (Value *V = foldSelectWithConstOpToBinOp(Cmp: ICI, TrueVal, FalseVal))
2558 return replaceInstUsesWith(I&: SI, V);
2559
2560 return Changed ? &SI : nullptr;
2561}
2562
2563/// We have an SPF (e.g. a min or max) of an SPF of the form:
2564/// SPF2(SPF1(A, B), C)
2565Instruction *InstCombinerImpl::foldSPFofSPF(Instruction *Inner,
2566 SelectPatternFlavor SPF1, Value *A,
2567 Value *B, Instruction &Outer,
2568 SelectPatternFlavor SPF2,
2569 Value *C) {
2570 if (Outer.getType() != Inner->getType())
2571 return nullptr;
2572
2573 if (C == A || C == B) {
2574 // MAX(MAX(A, B), B) -> MAX(A, B)
2575 // MIN(MIN(a, b), a) -> MIN(a, b)
2576 // TODO: This could be done in instsimplify.
2577 if (SPF1 == SPF2 && SelectPatternResult::isMinOrMax(SPF: SPF1))
2578 return replaceInstUsesWith(I&: Outer, V: Inner);
2579 }
2580
2581 return nullptr;
2582}
2583
2584/// Turn select C, (X + Y), (X - Y) --> (X + (select C, Y, (-Y))).
2585/// This is even legal for FP.
2586static Instruction *foldAddSubSelect(SelectInst &SI,
2587 InstCombiner::BuilderTy &Builder) {
2588 Value *CondVal = SI.getCondition();
2589 Value *TrueVal = SI.getTrueValue();
2590 Value *FalseVal = SI.getFalseValue();
2591 auto *TI = dyn_cast<Instruction>(Val: TrueVal);
2592 auto *FI = dyn_cast<Instruction>(Val: FalseVal);
2593 if (!TI || !FI || !TI->hasOneUse() || !FI->hasOneUse())
2594 return nullptr;
2595
2596 Instruction *AddOp = nullptr, *SubOp = nullptr;
2597 if ((TI->getOpcode() == Instruction::Sub &&
2598 FI->getOpcode() == Instruction::Add) ||
2599 (TI->getOpcode() == Instruction::FSub &&
2600 FI->getOpcode() == Instruction::FAdd)) {
2601 AddOp = FI;
2602 SubOp = TI;
2603 } else if ((FI->getOpcode() == Instruction::Sub &&
2604 TI->getOpcode() == Instruction::Add) ||
2605 (FI->getOpcode() == Instruction::FSub &&
2606 TI->getOpcode() == Instruction::FAdd)) {
2607 AddOp = TI;
2608 SubOp = FI;
2609 }
2610
2611 if (AddOp) {
2612 Value *OtherAddOp = nullptr;
2613 if (SubOp->getOperand(i: 0) == AddOp->getOperand(i: 0)) {
2614 OtherAddOp = AddOp->getOperand(i: 1);
2615 } else if (SubOp->getOperand(i: 0) == AddOp->getOperand(i: 1)) {
2616 OtherAddOp = AddOp->getOperand(i: 0);
2617 }
2618
2619 if (OtherAddOp) {
2620 // So at this point we know we have (Y -> OtherAddOp):
2621 // select C, (add X, Y), (sub X, Z)
2622 Value *NegVal; // Compute -Z
2623 if (SI.getType()->isFPOrFPVectorTy()) {
2624 NegVal = Builder.CreateFNeg(V: SubOp->getOperand(i: 1));
2625 if (Instruction *NegInst = dyn_cast<Instruction>(Val: NegVal)) {
2626 FastMathFlags Flags = AddOp->getFastMathFlags();
2627 Flags &= SubOp->getFastMathFlags();
2628 NegInst->setFastMathFlags(Flags);
2629 }
2630 } else {
2631 NegVal = Builder.CreateNeg(V: SubOp->getOperand(i: 1));
2632 }
2633
2634 Value *NewTrueOp = OtherAddOp;
2635 Value *NewFalseOp = NegVal;
2636 if (AddOp != TI)
2637 std::swap(a&: NewTrueOp, b&: NewFalseOp);
2638 Value *NewSel = Builder.CreateSelect(C: CondVal, True: NewTrueOp, False: NewFalseOp,
2639 Name: SI.getName() + ".p", MDFrom: &SI);
2640
2641 if (SI.getType()->isFPOrFPVectorTy()) {
2642 Instruction *RI =
2643 BinaryOperator::CreateFAdd(V1: SubOp->getOperand(i: 0), V2: NewSel);
2644
2645 FastMathFlags Flags = AddOp->getFastMathFlags();
2646 Flags &= SubOp->getFastMathFlags();
2647 RI->setFastMathFlags(Flags);
2648 return RI;
2649 } else
2650 return BinaryOperator::CreateAdd(V1: SubOp->getOperand(i: 0), V2: NewSel);
2651 }
2652 }
2653 return nullptr;
2654}
2655
2656/// Turn X + Y overflows ? -1 : X + Y -> uadd_sat X, Y
2657/// And X - Y overflows ? 0 : X - Y -> usub_sat X, Y
2658/// Along with a number of patterns similar to:
2659/// X + Y overflows ? (X < 0 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y
2660/// X - Y overflows ? (X > 0 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y
2661static Instruction *
2662foldOverflowingAddSubSelect(SelectInst &SI, InstCombiner::BuilderTy &Builder) {
2663 Value *CondVal = SI.getCondition();
2664 Value *TrueVal = SI.getTrueValue();
2665 Value *FalseVal = SI.getFalseValue();
2666
2667 WithOverflowInst *II;
2668 if (!match(V: CondVal, P: m_ExtractValue<1>(V: m_WithOverflowInst(I&: II))) ||
2669 !match(V: FalseVal, P: m_ExtractValue<0>(V: m_Specific(V: II))))
2670 return nullptr;
2671
2672 Value *X = II->getLHS();
2673 Value *Y = II->getRHS();
2674
2675 auto IsSignedSaturateLimit = [&](Value *Limit, bool IsAdd) {
2676 Type *Ty = Limit->getType();
2677
2678 CmpPredicate Pred;
2679 Value *TrueVal, *FalseVal, *Op;
2680 const APInt *C;
2681 if (!match(V: Limit, P: m_Select(C: m_ICmp(Pred, L: m_Value(V&: Op), R: m_APInt(Res&: C)),
2682 L: m_Value(V&: TrueVal), R: m_Value(V&: FalseVal))))
2683 return false;
2684
2685 auto IsZeroOrOne = [](const APInt &C) { return C.isZero() || C.isOne(); };
2686 auto IsMinMax = [&](Value *Min, Value *Max) {
2687 APInt MinVal = APInt::getSignedMinValue(numBits: Ty->getScalarSizeInBits());
2688 APInt MaxVal = APInt::getSignedMaxValue(numBits: Ty->getScalarSizeInBits());
2689 return match(V: Min, P: m_SpecificInt(V: MinVal)) &&
2690 match(V: Max, P: m_SpecificInt(V: MaxVal));
2691 };
2692
2693 if (Op != X && Op != Y)
2694 return false;
2695
2696 if (IsAdd) {
2697 // X + Y overflows ? (X <s 0 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y
2698 // X + Y overflows ? (X <s 1 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y
2699 // X + Y overflows ? (Y <s 0 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y
2700 // X + Y overflows ? (Y <s 1 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y
2701 if (Pred == ICmpInst::ICMP_SLT && IsZeroOrOne(*C) &&
2702 IsMinMax(TrueVal, FalseVal))
2703 return true;
2704 // X + Y overflows ? (X >s 0 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y
2705 // X + Y overflows ? (X >s -1 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y
2706 // X + Y overflows ? (Y >s 0 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y
2707 // X + Y overflows ? (Y >s -1 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y
2708 if (Pred == ICmpInst::ICMP_SGT && IsZeroOrOne(*C + 1) &&
2709 IsMinMax(FalseVal, TrueVal))
2710 return true;
2711 } else {
2712 // X - Y overflows ? (X <s 0 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y
2713 // X - Y overflows ? (X <s -1 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y
2714 if (Op == X && Pred == ICmpInst::ICMP_SLT && IsZeroOrOne(*C + 1) &&
2715 IsMinMax(TrueVal, FalseVal))
2716 return true;
2717 // X - Y overflows ? (X >s -1 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y
2718 // X - Y overflows ? (X >s -2 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y
2719 if (Op == X && Pred == ICmpInst::ICMP_SGT && IsZeroOrOne(*C + 2) &&
2720 IsMinMax(FalseVal, TrueVal))
2721 return true;
2722 // X - Y overflows ? (Y <s 0 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y
2723 // X - Y overflows ? (Y <s 1 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y
2724 if (Op == Y && Pred == ICmpInst::ICMP_SLT && IsZeroOrOne(*C) &&
2725 IsMinMax(FalseVal, TrueVal))
2726 return true;
2727 // X - Y overflows ? (Y >s 0 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y
2728 // X - Y overflows ? (Y >s -1 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y
2729 if (Op == Y && Pred == ICmpInst::ICMP_SGT && IsZeroOrOne(*C + 1) &&
2730 IsMinMax(TrueVal, FalseVal))
2731 return true;
2732 }
2733
2734 return false;
2735 };
2736
2737 Intrinsic::ID NewIntrinsicID;
2738 if (II->getIntrinsicID() == Intrinsic::uadd_with_overflow &&
2739 match(V: TrueVal, P: m_AllOnes()))
2740 // X + Y overflows ? -1 : X + Y -> uadd_sat X, Y
2741 NewIntrinsicID = Intrinsic::uadd_sat;
2742 else if (II->getIntrinsicID() == Intrinsic::usub_with_overflow &&
2743 match(V: TrueVal, P: m_Zero()))
2744 // X - Y overflows ? 0 : X - Y -> usub_sat X, Y
2745 NewIntrinsicID = Intrinsic::usub_sat;
2746 else if (II->getIntrinsicID() == Intrinsic::sadd_with_overflow &&
2747 IsSignedSaturateLimit(TrueVal, /*IsAdd=*/true))
2748 // X + Y overflows ? (X <s 0 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y
2749 // X + Y overflows ? (X <s 1 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y
2750 // X + Y overflows ? (X >s 0 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y
2751 // X + Y overflows ? (X >s -1 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y
2752 // X + Y overflows ? (Y <s 0 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y
2753 // X + Y overflows ? (Y <s 1 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y
2754 // X + Y overflows ? (Y >s 0 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y
2755 // X + Y overflows ? (Y >s -1 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y
2756 NewIntrinsicID = Intrinsic::sadd_sat;
2757 else if (II->getIntrinsicID() == Intrinsic::ssub_with_overflow &&
2758 IsSignedSaturateLimit(TrueVal, /*IsAdd=*/false))
2759 // X - Y overflows ? (X <s 0 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y
2760 // X - Y overflows ? (X <s -1 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y
2761 // X - Y overflows ? (X >s -1 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y
2762 // X - Y overflows ? (X >s -2 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y
2763 // X - Y overflows ? (Y <s 0 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y
2764 // X - Y overflows ? (Y <s 1 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y
2765 // X - Y overflows ? (Y >s 0 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y
2766 // X - Y overflows ? (Y >s -1 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y
2767 NewIntrinsicID = Intrinsic::ssub_sat;
2768 else
2769 return nullptr;
2770
2771 Function *F = Intrinsic::getOrInsertDeclaration(M: SI.getModule(),
2772 id: NewIntrinsicID, OverloadTys: SI.getType());
2773 return CallInst::Create(Func: F, Args: {X, Y});
2774}
2775
2776Instruction *InstCombinerImpl::foldSelectExtConst(SelectInst &Sel) {
2777 Constant *C;
2778 if (!match(V: Sel.getTrueValue(), P: m_Constant(C)) &&
2779 !match(V: Sel.getFalseValue(), P: m_Constant(C)))
2780 return nullptr;
2781
2782 Instruction *ExtInst;
2783 if (!match(V: Sel.getTrueValue(), P: m_Instruction(I&: ExtInst)) &&
2784 !match(V: Sel.getFalseValue(), P: m_Instruction(I&: ExtInst)))
2785 return nullptr;
2786
2787 auto ExtOpcode = ExtInst->getOpcode();
2788 if (ExtOpcode != Instruction::ZExt && ExtOpcode != Instruction::SExt)
2789 return nullptr;
2790
2791 // If we are extending from a boolean type or if we can create a select that
2792 // has the same size operands as its condition, try to narrow the select.
2793 Value *X = ExtInst->getOperand(i: 0);
2794 Type *SmallType = X->getType();
2795 Value *Cond = Sel.getCondition();
2796 if (!SmallType->isIntOrIntVectorTy(BitWidth: 1) &&
2797 (!isa<CmpInst, TruncInst>(Val: Cond) ||
2798 cast<Instruction>(Val: Cond)->getOperand(i: 0)->getType() != SmallType))
2799 return nullptr;
2800
2801 // If the constant is the same after truncation to the smaller type and
2802 // extension to the original type, we can narrow the select.
2803 Type *SelType = Sel.getType();
2804 Constant *TruncC = getLosslessInvCast(C, InvCastTo: SmallType, CastOp: ExtOpcode, DL);
2805 if (TruncC && ExtInst->hasOneUse()) {
2806 Value *TruncCVal = cast<Value>(Val: TruncC);
2807 if (ExtInst == Sel.getFalseValue())
2808 std::swap(a&: X, b&: TruncCVal);
2809
2810 // select Cond, (ext X), C --> ext(select Cond, X, C')
2811 // select Cond, C, (ext X) --> ext(select Cond, C', X)
2812 Value *NewSel = Builder.CreateSelect(C: Cond, True: X, False: TruncCVal, Name: "narrow", MDFrom: &Sel);
2813 return CastInst::Create(Instruction::CastOps(ExtOpcode), S: NewSel, Ty: SelType);
2814 }
2815
2816 return nullptr;
2817}
2818
2819/// Try to transform a vector select with a constant condition vector into a
2820/// shuffle for easier combining with other shuffles and insert/extract.
2821static Instruction *canonicalizeSelectToShuffle(SelectInst &SI) {
2822 Value *CondVal = SI.getCondition();
2823 Constant *CondC;
2824 auto *CondValTy = dyn_cast<FixedVectorType>(Val: CondVal->getType());
2825 if (!CondValTy || !match(V: CondVal, P: m_Constant(C&: CondC)))
2826 return nullptr;
2827
2828 unsigned NumElts = CondValTy->getNumElements();
2829 SmallVector<int, 16> Mask;
2830 Mask.reserve(N: NumElts);
2831 for (unsigned i = 0; i != NumElts; ++i) {
2832 Constant *Elt = CondC->getAggregateElement(Elt: i);
2833 if (!Elt)
2834 return nullptr;
2835
2836 if (Elt->isOneValue()) {
2837 // If the select condition element is true, choose from the 1st vector.
2838 Mask.push_back(Elt: i);
2839 } else if (Elt->isNullValue()) {
2840 // If the select condition element is false, choose from the 2nd vector.
2841 Mask.push_back(Elt: i + NumElts);
2842 } else if (isa<UndefValue>(Val: Elt)) {
2843 // Undef in a select condition (choose one of the operands) does not mean
2844 // the same thing as undef in a shuffle mask (any value is acceptable), so
2845 // give up.
2846 return nullptr;
2847 } else {
2848 // Bail out on a constant expression.
2849 return nullptr;
2850 }
2851 }
2852
2853 return new ShuffleVectorInst(SI.getTrueValue(), SI.getFalseValue(), Mask);
2854}
2855
2856/// If we have a select of vectors with a scalar condition, try to convert that
2857/// to a vector select by splatting the condition. A splat may get folded with
2858/// other operations in IR and having all operands of a select be vector types
2859/// is likely better for vector codegen.
2860static Instruction *canonicalizeScalarSelectOfVecs(SelectInst &Sel,
2861 InstCombinerImpl &IC) {
2862 auto *Ty = dyn_cast<VectorType>(Val: Sel.getType());
2863 if (!Ty)
2864 return nullptr;
2865
2866 // We can replace a single-use extract with constant index.
2867 Value *Cond = Sel.getCondition();
2868 if (!match(V: Cond, P: m_OneUse(SubPattern: m_ExtractElt(Val: m_Value(), Idx: m_ConstantInt()))))
2869 return nullptr;
2870
2871 // select (extelt V, Index), T, F --> select (splat V, Index), T, F
2872 // Splatting the extracted condition reduces code (we could directly create a
2873 // splat shuffle of the source vector to eliminate the intermediate step).
2874 return IC.replaceOperand(
2875 I&: Sel, OpNum: 0, V: IC.Builder.CreateVectorSplat(EC: Ty->getElementCount(), V: Cond));
2876}
2877
2878/// Reuse bitcasted operands between a compare and select:
2879/// select (cmp (bitcast C), (bitcast D)), (bitcast' C), (bitcast' D) -->
2880/// bitcast (select (cmp (bitcast C), (bitcast D)), (bitcast C), (bitcast D))
2881static Instruction *foldSelectCmpBitcasts(SelectInst &Sel,
2882 InstCombiner::BuilderTy &Builder) {
2883 Value *Cond = Sel.getCondition();
2884 Value *TVal = Sel.getTrueValue();
2885 Value *FVal = Sel.getFalseValue();
2886
2887 CmpPredicate Pred;
2888 Value *A, *B;
2889 if (!match(V: Cond, P: m_Cmp(Pred, L: m_Value(V&: A), R: m_Value(V&: B))))
2890 return nullptr;
2891
2892 // The select condition is a compare instruction. If the select's true/false
2893 // values are already the same as the compare operands, there's nothing to do.
2894 if (TVal == A || TVal == B || FVal == A || FVal == B)
2895 return nullptr;
2896
2897 Value *C, *D;
2898 if (!match(V: A, P: m_BitCast(Op: m_Value(V&: C))) || !match(V: B, P: m_BitCast(Op: m_Value(V&: D))))
2899 return nullptr;
2900
2901 // select (cmp (bitcast C), (bitcast D)), (bitcast TSrc), (bitcast FSrc)
2902 Value *TSrc, *FSrc;
2903 if (!match(V: TVal, P: m_BitCast(Op: m_Value(V&: TSrc))) ||
2904 !match(V: FVal, P: m_BitCast(Op: m_Value(V&: FSrc))))
2905 return nullptr;
2906
2907 // If the select true/false values are *different bitcasts* of the same source
2908 // operands, make the select operands the same as the compare operands and
2909 // cast the result. This is the canonical select form for min/max.
2910 Value *NewSel;
2911 if (TSrc == C && FSrc == D) {
2912 // select (cmp (bitcast C), (bitcast D)), (bitcast' C), (bitcast' D) -->
2913 // bitcast (select (cmp A, B), A, B)
2914 NewSel = Builder.CreateSelect(C: Cond, True: A, False: B, Name: "", MDFrom: &Sel);
2915 } else if (TSrc == D && FSrc == C) {
2916 // select (cmp (bitcast C), (bitcast D)), (bitcast' D), (bitcast' C) -->
2917 // bitcast (select (cmp A, B), B, A)
2918 NewSel = Builder.CreateSelect(C: Cond, True: B, False: A, Name: "", MDFrom: &Sel);
2919 } else {
2920 return nullptr;
2921 }
2922 return new BitCastInst(NewSel, Sel.getType());
2923}
2924
2925/// Try to eliminate select instructions that test the returned flag of cmpxchg
2926/// instructions.
2927///
2928/// If a select instruction tests the returned flag of a cmpxchg instruction and
2929/// selects between the returned value of the cmpxchg instruction its compare
2930/// operand, the result of the select will always be equal to its false value.
2931/// For example:
2932///
2933/// %cmpxchg = cmpxchg ptr %ptr, i64 %compare, i64 %new_value seq_cst seq_cst
2934/// %val = extractvalue { i64, i1 } %cmpxchg, 0
2935/// %success = extractvalue { i64, i1 } %cmpxchg, 1
2936/// %sel = select i1 %success, i64 %compare, i64 %val
2937/// ret i64 %sel
2938///
2939/// The returned value of the cmpxchg instruction (%val) is the original value
2940/// located at %ptr prior to any update. If the cmpxchg operation succeeds, %val
2941/// must have been equal to %compare. Thus, the result of the select is always
2942/// equal to %val, and the code can be simplified to:
2943///
2944/// %cmpxchg = cmpxchg ptr %ptr, i64 %compare, i64 %new_value seq_cst seq_cst
2945/// %val = extractvalue { i64, i1 } %cmpxchg, 0
2946/// ret i64 %val
2947///
2948static Value *foldSelectCmpXchg(SelectInst &SI) {
2949 // A helper that determines if V is an extractvalue instruction whose
2950 // aggregate operand is a cmpxchg instruction and whose single index is equal
2951 // to I. If such conditions are true, the helper returns the cmpxchg
2952 // instruction; otherwise, a nullptr is returned.
2953 auto isExtractFromCmpXchg = [](Value *V, unsigned I) -> AtomicCmpXchgInst * {
2954 // When extracting the value loaded by a cmpxchg, allow peeking through a
2955 // bitcast. These are inserted for floating-point cmpxchg, for example:
2956 // %bc = bitcast float %compare to i32
2957 // %cmpxchg = cmpxchg ptr %ptr, i32 %bc, i32 %new_value seq_cst seq_cst
2958 // %val = extractvalue { i32, i1 } %cmpxchg, 0
2959 // %success = extractvalue { i32, i1 } %cmpxchg, 1
2960 // %val.bc = bitcast i32 %val to float
2961 // %sel = select i1 %success, float %compare, float %val.bc
2962 if (auto *BI = dyn_cast<BitCastInst>(Val: V); BI && I == 0)
2963 V = BI->getOperand(i_nocapture: 0);
2964 auto *Extract = dyn_cast<ExtractValueInst>(Val: V);
2965 if (!Extract)
2966 return nullptr;
2967 if (Extract->getIndices()[0] != I)
2968 return nullptr;
2969 return dyn_cast<AtomicCmpXchgInst>(Val: Extract->getAggregateOperand());
2970 };
2971
2972 // Check if the compare value of a cmpxchg matches another value.
2973 auto isCompareSameAsValue = [](Value *CmpVal, Value *SelVal) {
2974 // The values match if they are the same or %CmpVal = bitcast %SelVal (see
2975 // above).
2976 if (CmpVal == SelVal || match(V: CmpVal, P: m_BitCast(Op: m_Specific(V: SelVal))))
2977 return true;
2978 // For FP constants, the value may have been bitcast to Int directly.
2979 auto *IntC = dyn_cast<ConstantInt>(Val: CmpVal);
2980 auto *FpC = dyn_cast<ConstantFP>(Val: SelVal);
2981 return IntC && FpC && IntC->getValue() == FpC->getValue().bitcastToAPInt();
2982 };
2983
2984 // If the select has a single user, and this user is a select instruction that
2985 // we can simplify, skip the cmpxchg simplification for now.
2986 if (SI.hasOneUse())
2987 if (auto *Select = dyn_cast<SelectInst>(Val: SI.user_back()))
2988 if (Select->getCondition() == SI.getCondition())
2989 if (Select->getFalseValue() == SI.getTrueValue() ||
2990 Select->getTrueValue() == SI.getFalseValue())
2991 return nullptr;
2992
2993 // Ensure the select condition is the returned flag of a cmpxchg instruction.
2994 auto *CmpXchg = isExtractFromCmpXchg(SI.getCondition(), 1);
2995 if (!CmpXchg)
2996 return nullptr;
2997
2998 // Check the true value case: The true value of the select is the returned
2999 // value of the same cmpxchg used by the condition, and the false value is the
3000 // cmpxchg instruction's compare operand.
3001 if (auto *X = isExtractFromCmpXchg(SI.getTrueValue(), 0))
3002 if (X == CmpXchg &&
3003 isCompareSameAsValue(X->getCompareOperand(), SI.getFalseValue()))
3004 return SI.getFalseValue();
3005
3006 // Check the false value case: The false value of the select is the returned
3007 // value of the same cmpxchg used by the condition, and the true value is the
3008 // cmpxchg instruction's compare operand.
3009 if (auto *X = isExtractFromCmpXchg(SI.getFalseValue(), 0))
3010 if (X == CmpXchg &&
3011 isCompareSameAsValue(X->getCompareOperand(), SI.getTrueValue()))
3012 return SI.getFalseValue();
3013
3014 return nullptr;
3015}
3016
3017/// Try to reduce a funnel/rotate pattern that includes a compare and select
3018/// into a funnel shift intrinsic. Example:
3019/// rotl32(a, b) --> (b == 0 ? a : ((a >> (32 - b)) | (a << b)))
3020/// --> call llvm.fshl.i32(a, a, b)
3021/// fshl32(a, b, c) --> (c == 0 ? a : ((b >> (32 - c)) | (a << c)))
3022/// --> call llvm.fshl.i32(a, b, c)
3023/// fshr32(a, b, c) --> (c == 0 ? b : ((a >> (32 - c)) | (b << c)))
3024/// --> call llvm.fshr.i32(a, b, c)
3025static Instruction *foldSelectFunnelShift(SelectInst &Sel,
3026 InstCombiner::BuilderTy &Builder) {
3027 // This must be a power-of-2 type for a bitmasking transform to be valid.
3028 unsigned Width = Sel.getType()->getScalarSizeInBits();
3029 if (!isPowerOf2_32(Value: Width))
3030 return nullptr;
3031
3032 BinaryOperator *Or0, *Or1;
3033 if (!match(V: Sel.getFalseValue(), P: m_OneUse(SubPattern: m_Or(L: m_BinOp(I&: Or0), R: m_BinOp(I&: Or1)))))
3034 return nullptr;
3035
3036 Value *SV0, *SV1, *SA0, *SA1;
3037 if (!match(V: Or0, P: m_OneUse(SubPattern: m_LogicalShift(L: m_Value(V&: SV0),
3038 R: m_ZExtOrSelf(Op: m_Value(V&: SA0))))) ||
3039 !match(V: Or1, P: m_OneUse(SubPattern: m_LogicalShift(L: m_Value(V&: SV1),
3040 R: m_ZExtOrSelf(Op: m_Value(V&: SA1))))) ||
3041 Or0->getOpcode() == Or1->getOpcode())
3042 return nullptr;
3043
3044 // Canonicalize to or(shl(SV0, SA0), lshr(SV1, SA1)).
3045 if (Or0->getOpcode() == BinaryOperator::LShr) {
3046 std::swap(a&: Or0, b&: Or1);
3047 std::swap(a&: SV0, b&: SV1);
3048 std::swap(a&: SA0, b&: SA1);
3049 }
3050 assert(Or0->getOpcode() == BinaryOperator::Shl &&
3051 Or1->getOpcode() == BinaryOperator::LShr &&
3052 "Illegal or(shift,shift) pair");
3053
3054 // Check the shift amounts to see if they are an opposite pair.
3055 Value *ShAmt;
3056 if (match(V: SA1, P: m_OneUse(SubPattern: m_Sub(L: m_SpecificInt(V: Width), R: m_Specific(V: SA0)))))
3057 ShAmt = SA0;
3058 else if (match(V: SA0, P: m_OneUse(SubPattern: m_Sub(L: m_SpecificInt(V: Width), R: m_Specific(V: SA1)))))
3059 ShAmt = SA1;
3060 else
3061 return nullptr;
3062
3063 // We should now have this pattern:
3064 // select ?, TVal, (or (shl SV0, SA0), (lshr SV1, SA1))
3065 // The false value of the select must be a funnel-shift of the true value:
3066 // IsFShl -> TVal must be SV0 else TVal must be SV1.
3067 bool IsFshl = (ShAmt == SA0);
3068 Value *TVal = Sel.getTrueValue();
3069 if ((IsFshl && TVal != SV0) || (!IsFshl && TVal != SV1))
3070 return nullptr;
3071
3072 // Finally, see if the select is filtering out a shift-by-zero.
3073 Value *Cond = Sel.getCondition();
3074 if (!match(V: Cond, P: m_OneUse(SubPattern: m_SpecificICmp(MatchPred: ICmpInst::ICMP_EQ, L: m_Specific(V: ShAmt),
3075 R: m_ZeroInt()))))
3076 return nullptr;
3077
3078 // If this is not a rotate then the select was blocking poison from the
3079 // 'shift-by-zero' non-TVal, but a funnel shift won't - so freeze it.
3080 if (SV0 != SV1) {
3081 if (IsFshl && !llvm::isGuaranteedNotToBePoison(V: SV1))
3082 SV1 = Builder.CreateFreeze(V: SV1);
3083 else if (!IsFshl && !llvm::isGuaranteedNotToBePoison(V: SV0))
3084 SV0 = Builder.CreateFreeze(V: SV0);
3085 }
3086
3087 // This is a funnel/rotate that avoids shift-by-bitwidth UB in a suboptimal way.
3088 // Convert to funnel shift intrinsic.
3089 Intrinsic::ID IID = IsFshl ? Intrinsic::fshl : Intrinsic::fshr;
3090 Function *F =
3091 Intrinsic::getOrInsertDeclaration(M: Sel.getModule(), id: IID, OverloadTys: Sel.getType());
3092 ShAmt = Builder.CreateZExt(V: ShAmt, DestTy: Sel.getType());
3093 return CallInst::Create(Func: F, Args: { SV0, SV1, ShAmt });
3094}
3095
3096static Instruction *foldSelectToCopysign(SelectInst &Sel,
3097 InstCombiner::BuilderTy &Builder) {
3098 Value *Cond = Sel.getCondition();
3099 Value *TVal = Sel.getTrueValue();
3100 Value *FVal = Sel.getFalseValue();
3101 Type *SelType = Sel.getType();
3102
3103 // Match select ?, TC, FC where the constants are equal but negated.
3104 // TODO: Generalize to handle a negated variable operand?
3105 const APFloat *TC, *FC;
3106 if (!match(V: TVal, P: m_APFloatAllowPoison(Res&: TC)) ||
3107 !match(V: FVal, P: m_APFloatAllowPoison(Res&: FC)) ||
3108 !abs(X: *TC).bitwiseIsEqual(RHS: abs(X: *FC)))
3109 return nullptr;
3110
3111 assert(TC != FC && "Expected equal select arms to simplify");
3112
3113 Value *X;
3114 const APInt *C;
3115 bool IsTrueIfSignSet;
3116 CmpPredicate Pred;
3117 if (!match(V: Cond, P: m_OneUse(SubPattern: m_ICmp(Pred, L: m_ElementWiseBitCast(Op: m_Value(V&: X)),
3118 R: m_APInt(Res&: C)))) ||
3119 !isSignBitCheck(Pred, RHS: *C, TrueIfSigned&: IsTrueIfSignSet) || X->getType() != SelType)
3120 return nullptr;
3121
3122 // If needed, negate the value that will be the sign argument of the copysign:
3123 // (bitcast X) < 0 ? -TC : TC --> copysign(TC, X)
3124 // (bitcast X) < 0 ? TC : -TC --> copysign(TC, -X)
3125 // (bitcast X) >= 0 ? -TC : TC --> copysign(TC, -X)
3126 // (bitcast X) >= 0 ? TC : -TC --> copysign(TC, X)
3127 // Note: FMF from the select can not be propagated to the new instructions.
3128 if (IsTrueIfSignSet ^ TC->isNegative())
3129 X = Builder.CreateFNeg(V: X);
3130
3131 // Canonicalize the magnitude argument as the positive constant since we do
3132 // not care about its sign.
3133 Value *MagArg = ConstantFP::get(Ty: SelType, V: abs(X: *TC));
3134 Function *F = Intrinsic::getOrInsertDeclaration(
3135 M: Sel.getModule(), id: Intrinsic::copysign, OverloadTys: Sel.getType());
3136 return CallInst::Create(Func: F, Args: { MagArg, X });
3137}
3138
3139Instruction *InstCombinerImpl::foldVectorSelect(SelectInst &Sel) {
3140 if (!isa<VectorType>(Val: Sel.getType()))
3141 return nullptr;
3142
3143 Value *Cond = Sel.getCondition();
3144 Value *TVal = Sel.getTrueValue();
3145 Value *FVal = Sel.getFalseValue();
3146 Value *C, *X, *Y;
3147
3148 if (match(V: Cond, P: m_VecReverse(Op0: m_Value(V&: C)))) {
3149 auto createSelReverse = [&](Value *C, Value *X, Value *Y) {
3150 Value *V = Builder.CreateSelect(C, True: X, False: Y, Name: Sel.getName(), MDFrom: &Sel);
3151 if (auto *I = dyn_cast<Instruction>(Val: V))
3152 I->copyIRFlags(V: &Sel);
3153 Module *M = Sel.getModule();
3154 Function *F = Intrinsic::getOrInsertDeclaration(
3155 M, id: Intrinsic::vector_reverse, OverloadTys: V->getType());
3156 return CallInst::Create(Func: F, Args: V);
3157 };
3158
3159 if (match(V: TVal, P: m_VecReverse(Op0: m_Value(V&: X)))) {
3160 // select rev(C), rev(X), rev(Y) --> rev(select C, X, Y)
3161 if (match(V: FVal, P: m_VecReverse(Op0: m_Value(V&: Y))) &&
3162 (Cond->hasOneUse() || TVal->hasOneUse() || FVal->hasOneUse()))
3163 return createSelReverse(C, X, Y);
3164
3165 // select rev(C), rev(X), FValSplat --> rev(select C, X, FValSplat)
3166 if ((Cond->hasOneUse() || TVal->hasOneUse()) && isSplatValue(V: FVal))
3167 return createSelReverse(C, X, FVal);
3168 }
3169 // select rev(C), TValSplat, rev(Y) --> rev(select C, TValSplat, Y)
3170 else if (isSplatValue(V: TVal) && match(V: FVal, P: m_VecReverse(Op0: m_Value(V&: Y))) &&
3171 (Cond->hasOneUse() || FVal->hasOneUse()))
3172 return createSelReverse(C, TVal, Y);
3173 }
3174
3175 auto *VecTy = dyn_cast<FixedVectorType>(Val: Sel.getType());
3176 if (!VecTy)
3177 return nullptr;
3178
3179 unsigned NumElts = VecTy->getNumElements();
3180 APInt PoisonElts(NumElts, 0);
3181 APInt AllOnesEltMask(APInt::getAllOnes(numBits: NumElts));
3182 if (Value *V = SimplifyDemandedVectorElts(V: &Sel, DemandedElts: AllOnesEltMask, PoisonElts)) {
3183 if (V != &Sel)
3184 return replaceInstUsesWith(I&: Sel, V);
3185 return &Sel;
3186 }
3187
3188 // A select of a "select shuffle" with a common operand can be rearranged
3189 // to select followed by "select shuffle". Because of poison, this only works
3190 // in the case of a shuffle with no undefined mask elements.
3191 ArrayRef<int> Mask;
3192 if (match(V: TVal, P: m_OneUse(SubPattern: m_Shuffle(v1: m_Value(V&: X), v2: m_Value(V&: Y), mask: m_Mask(Mask)))) &&
3193 !is_contained(Range&: Mask, Element: PoisonMaskElem) &&
3194 cast<ShuffleVectorInst>(Val: TVal)->isSelect()) {
3195 if (X == FVal) {
3196 // select Cond, (shuf_sel X, Y), X --> shuf_sel X, (select Cond, Y, X)
3197 Value *NewSel = Builder.CreateSelect(C: Cond, True: Y, False: X, Name: "sel", MDFrom: &Sel);
3198 return new ShuffleVectorInst(X, NewSel, Mask);
3199 }
3200 if (Y == FVal) {
3201 // select Cond, (shuf_sel X, Y), Y --> shuf_sel (select Cond, X, Y), Y
3202 Value *NewSel = Builder.CreateSelect(C: Cond, True: X, False: Y, Name: "sel", MDFrom: &Sel);
3203 return new ShuffleVectorInst(NewSel, Y, Mask);
3204 }
3205 }
3206 if (match(V: FVal, P: m_OneUse(SubPattern: m_Shuffle(v1: m_Value(V&: X), v2: m_Value(V&: Y), mask: m_Mask(Mask)))) &&
3207 !is_contained(Range&: Mask, Element: PoisonMaskElem) &&
3208 cast<ShuffleVectorInst>(Val: FVal)->isSelect()) {
3209 if (X == TVal) {
3210 // select Cond, X, (shuf_sel X, Y) --> shuf_sel X, (select Cond, X, Y)
3211 Value *NewSel = Builder.CreateSelect(C: Cond, True: X, False: Y, Name: "sel", MDFrom: &Sel);
3212 return new ShuffleVectorInst(X, NewSel, Mask);
3213 }
3214 if (Y == TVal) {
3215 // select Cond, Y, (shuf_sel X, Y) --> shuf_sel (select Cond, Y, X), Y
3216 Value *NewSel = Builder.CreateSelect(C: Cond, True: Y, False: X, Name: "sel", MDFrom: &Sel);
3217 return new ShuffleVectorInst(NewSel, Y, Mask);
3218 }
3219 }
3220
3221 return nullptr;
3222}
3223
3224static Instruction *foldSelectToPhiImpl(SelectInst &Sel, BasicBlock *BB,
3225 const DominatorTree &DT,
3226 InstCombiner::BuilderTy &Builder) {
3227 // Find the block's immediate dominator that ends with a conditional branch
3228 // that matches select's condition (maybe inverted).
3229 auto *IDomNode = DT[BB]->getIDom();
3230 if (!IDomNode)
3231 return nullptr;
3232 BasicBlock *IDom = IDomNode->getBlock();
3233
3234 Value *Cond = Sel.getCondition();
3235 Value *IfTrue, *IfFalse;
3236 BasicBlock *TrueSucc, *FalseSucc;
3237 if (match(V: IDom->getTerminator(),
3238 P: m_Br(C: m_Specific(V: Cond), T: m_BasicBlock(V&: TrueSucc),
3239 F: m_BasicBlock(V&: FalseSucc)))) {
3240 IfTrue = Sel.getTrueValue();
3241 IfFalse = Sel.getFalseValue();
3242 } else if (match(V: IDom->getTerminator(),
3243 P: m_Br(C: m_Not(V: m_Specific(V: Cond)), T: m_BasicBlock(V&: TrueSucc),
3244 F: m_BasicBlock(V&: FalseSucc)))) {
3245 IfTrue = Sel.getFalseValue();
3246 IfFalse = Sel.getTrueValue();
3247 } else
3248 return nullptr;
3249
3250 // Make sure the branches are actually different.
3251 if (TrueSucc == FalseSucc)
3252 return nullptr;
3253
3254 // We want to replace select %cond, %a, %b with a phi that takes value %a
3255 // for all incoming edges that are dominated by condition `%cond == true`,
3256 // and value %b for edges dominated by condition `%cond == false`. If %a
3257 // or %b are also phis from the same basic block, we can go further and take
3258 // their incoming values from the corresponding blocks.
3259 BasicBlockEdge TrueEdge(IDom, TrueSucc);
3260 BasicBlockEdge FalseEdge(IDom, FalseSucc);
3261 DenseMap<BasicBlock *, Value *> Inputs;
3262 for (auto *Pred : predecessors(BB)) {
3263 // Check implication.
3264 BasicBlockEdge Incoming(Pred, BB);
3265 if (DT.dominates(BBE1: TrueEdge, BBE2: Incoming))
3266 Inputs[Pred] = IfTrue->DoPHITranslation(CurBB: BB, PredBB: Pred);
3267 else if (DT.dominates(BBE1: FalseEdge, BBE2: Incoming))
3268 Inputs[Pred] = IfFalse->DoPHITranslation(CurBB: BB, PredBB: Pred);
3269 else
3270 return nullptr;
3271 // Check availability.
3272 if (auto *Insn = dyn_cast<Instruction>(Val: Inputs[Pred]))
3273 if (!DT.dominates(Def: Insn, User: Pred->getTerminator()))
3274 return nullptr;
3275 }
3276
3277 Builder.SetInsertPoint(BB->begin());
3278 auto *PN = Builder.CreatePHI(Ty: Sel.getType(), NumReservedValues: Inputs.size());
3279 for (auto *Pred : predecessors(BB))
3280 PN->addIncoming(V: Inputs[Pred], BB: Pred);
3281 PN->takeName(V: &Sel);
3282 return PN;
3283}
3284
3285static Instruction *foldSelectToPhi(SelectInst &Sel, const DominatorTree &DT,
3286 InstCombiner::BuilderTy &Builder) {
3287 // Try to replace this select with Phi in one of these blocks.
3288 SmallSetVector<BasicBlock *, 4> CandidateBlocks;
3289 CandidateBlocks.insert(X: Sel.getParent());
3290 for (Value *V : Sel.operands())
3291 if (auto *I = dyn_cast<Instruction>(Val: V))
3292 CandidateBlocks.insert(X: I->getParent());
3293
3294 for (BasicBlock *BB : CandidateBlocks)
3295 if (auto *PN = foldSelectToPhiImpl(Sel, BB, DT, Builder))
3296 return PN;
3297 return nullptr;
3298}
3299
3300/// Tries to reduce a pattern that arises when calculating the remainder of the
3301/// Euclidean division. When the divisor is a power of two and is guaranteed not
3302/// to be negative, a signed remainder can be folded with a bitwise and.
3303///
3304/// (x % n) < 0 ? (x % n) + n : (x % n)
3305/// -> x & (n - 1)
3306static Instruction *foldSelectWithSRem(SelectInst &SI, InstCombinerImpl &IC,
3307 IRBuilderBase &Builder) {
3308 Value *CondVal = SI.getCondition();
3309 Value *TrueVal = SI.getTrueValue();
3310 Value *FalseVal = SI.getFalseValue();
3311
3312 CmpPredicate Pred;
3313 Value *Op, *RemRes, *Remainder;
3314 const APInt *C;
3315 bool TrueIfSigned = false;
3316
3317 if (!(match(V: CondVal, P: m_ICmp(Pred, L: m_Value(V&: RemRes), R: m_APInt(Res&: C))) &&
3318 isSignBitCheck(Pred, RHS: *C, TrueIfSigned)))
3319 return nullptr;
3320
3321 // If the sign bit is not set, we have a SGE/SGT comparison, and the operands
3322 // of the select are inverted.
3323 if (!TrueIfSigned)
3324 std::swap(a&: TrueVal, b&: FalseVal);
3325
3326 auto FoldToBitwiseAnd = [&](Value *Remainder) -> Instruction * {
3327 Value *Add = Builder.CreateAdd(
3328 LHS: Remainder, RHS: Constant::getAllOnesValue(Ty: RemRes->getType()));
3329 return BinaryOperator::CreateAnd(V1: Op, V2: Add);
3330 };
3331
3332 // Match the general case:
3333 // %rem = srem i32 %x, %n
3334 // %cnd = icmp slt i32 %rem, 0
3335 // %add = add i32 %rem, %n
3336 // %sel = select i1 %cnd, i32 %add, i32 %rem
3337 if (match(V: TrueVal, P: m_c_Add(L: m_Specific(V: RemRes), R: m_Value(V&: Remainder))) &&
3338 match(V: RemRes, P: m_SRem(L: m_Value(V&: Op), R: m_Specific(V: Remainder))) &&
3339 IC.isKnownToBeAPowerOfTwo(V: Remainder, /*OrZero=*/true) &&
3340 FalseVal == RemRes)
3341 return FoldToBitwiseAnd(Remainder);
3342
3343 // Match the case where the one arm has been replaced by constant 1:
3344 // %rem = srem i32 %n, 2
3345 // %cnd = icmp slt i32 %rem, 0
3346 // %sel = select i1 %cnd, i32 1, i32 %rem
3347 if (match(V: TrueVal, P: m_One()) &&
3348 match(V: RemRes, P: m_SRem(L: m_Value(V&: Op), R: m_SpecificInt(V: 2))) &&
3349 FalseVal == RemRes)
3350 return FoldToBitwiseAnd(ConstantInt::get(Ty: RemRes->getType(), V: 2));
3351
3352 return nullptr;
3353}
3354
3355/// Given that \p CondVal is known to be \p CondIsTrue, try to simplify \p SI.
3356static Value *simplifyNestedSelectsUsingImpliedCond(SelectInst &SI,
3357 Value *CondVal,
3358 bool CondIsTrue,
3359 const DataLayout &DL) {
3360 Value *InnerCondVal = SI.getCondition();
3361 Value *InnerTrueVal = SI.getTrueValue();
3362 Value *InnerFalseVal = SI.getFalseValue();
3363 assert(CondVal->getType() == InnerCondVal->getType() &&
3364 "The type of inner condition must match with the outer.");
3365 if (auto Implied = isImpliedCondition(LHS: CondVal, RHS: InnerCondVal, DL, LHSIsTrue: CondIsTrue))
3366 return *Implied ? InnerTrueVal : InnerFalseVal;
3367 return nullptr;
3368}
3369
3370Instruction *InstCombinerImpl::foldAndOrOfSelectUsingImpliedCond(Value *Op,
3371 SelectInst &SI,
3372 bool IsAnd) {
3373 assert(Op->getType()->isIntOrIntVectorTy(1) &&
3374 "Op must be either i1 or vector of i1.");
3375 if (SI.getCondition()->getType() != Op->getType())
3376 return nullptr;
3377 if (Value *V = simplifyNestedSelectsUsingImpliedCond(SI, CondVal: Op, CondIsTrue: IsAnd, DL))
3378 return createSelectInstWithUnknownProfile(
3379 C: Op, S1: IsAnd ? V : ConstantInt::getTrue(Ty: Op->getType()),
3380 S2: IsAnd ? ConstantInt::getFalse(Ty: Op->getType()) : V);
3381 return nullptr;
3382}
3383
3384// Canonicalize select with fcmp to fabs(). -0.0 makes this tricky. We need
3385// fast-math-flags (nsz) or fsub with +0.0 (not fneg) for this to work.
3386static Instruction *foldSelectWithFCmpToFabs(SelectInst &SI,
3387 InstCombinerImpl &IC) {
3388 Value *CondVal = SI.getCondition();
3389
3390 bool ChangedFMF = false;
3391 for (bool Swap : {false, true}) {
3392 Value *TrueVal = SI.getTrueValue();
3393 Value *X = SI.getFalseValue();
3394 CmpPredicate Pred;
3395
3396 if (Swap)
3397 std::swap(a&: TrueVal, b&: X);
3398
3399 if (!match(V: CondVal, P: m_FCmp(Pred, L: m_Specific(V: X), R: m_AnyZeroFP())))
3400 continue;
3401
3402 // fold (X <= +/-0.0) ? (0.0 - X) : X to fabs(X), when 'Swap' is false
3403 // fold (X > +/-0.0) ? X : (0.0 - X) to fabs(X), when 'Swap' is true
3404 // Note: We require "nnan" for this fold because fcmp ignores the signbit
3405 // of NAN, but IEEE-754 specifies the signbit of NAN values with
3406 // fneg/fabs operations.
3407 if (match(V: TrueVal, P: m_FSub(L: m_PosZeroFP(), R: m_Specific(V: X))) &&
3408 (cast<FPMathOperator>(Val: CondVal)->hasNoNaNs() || SI.hasNoNaNs() ||
3409 (SI.hasOneUse() && canIgnoreSignBitOfNaN(U: *SI.use_begin())) ||
3410 isKnownNeverNaN(V: X, SQ: IC.getSimplifyQuery().getWithInstruction(
3411 I: cast<Instruction>(Val: CondVal))))) {
3412 if (!Swap && (Pred == FCmpInst::FCMP_OLE || Pred == FCmpInst::FCMP_ULE)) {
3413 Value *Fabs = IC.Builder.CreateFAbs(V: X, FMFSource: &SI);
3414 return IC.replaceInstUsesWith(I&: SI, V: Fabs);
3415 }
3416 if (Swap && (Pred == FCmpInst::FCMP_OGT || Pred == FCmpInst::FCMP_UGT)) {
3417 Value *Fabs = IC.Builder.CreateFAbs(V: X, FMFSource: &SI);
3418 return IC.replaceInstUsesWith(I&: SI, V: Fabs);
3419 }
3420 }
3421
3422 if (!match(V: TrueVal, P: m_FNeg(X: m_Specific(V: X))))
3423 return nullptr;
3424
3425 // Forward-propagate nnan and ninf from the fcmp to the select.
3426 // If all inputs are not those values, then the select is not either.
3427 // Note: nsz is defined differently, so it may not be correct to propagate.
3428 FastMathFlags FMF = cast<FPMathOperator>(Val: CondVal)->getFastMathFlags();
3429 if (FMF.noNaNs() && !SI.hasNoNaNs()) {
3430 SI.setHasNoNaNs(true);
3431 ChangedFMF = true;
3432 }
3433 if (FMF.noInfs() && !SI.hasNoInfs()) {
3434 SI.setHasNoInfs(true);
3435 ChangedFMF = true;
3436 }
3437 // Forward-propagate nnan from the fneg to the select.
3438 // The nnan flag can be propagated iff fneg is selected when X is NaN.
3439 if (!SI.hasNoNaNs() && cast<FPMathOperator>(Val: TrueVal)->hasNoNaNs() &&
3440 (Swap ? FCmpInst::isOrdered(predicate: Pred) : FCmpInst::isUnordered(predicate: Pred))) {
3441 SI.setHasNoNaNs(true);
3442 ChangedFMF = true;
3443 }
3444
3445 // With nsz, when 'Swap' is false:
3446 // fold (X < +/-0.0) ? -X : X or (X <= +/-0.0) ? -X : X to fabs(X)
3447 // fold (X > +/-0.0) ? -X : X or (X >= +/-0.0) ? -X : X to -fabs(x)
3448 // when 'Swap' is true:
3449 // fold (X > +/-0.0) ? X : -X or (X >= +/-0.0) ? X : -X to fabs(X)
3450 // fold (X < +/-0.0) ? X : -X or (X <= +/-0.0) ? X : -X to -fabs(X)
3451 //
3452 // Note: We require "nnan" for this fold because fcmp ignores the signbit
3453 // of NAN, but IEEE-754 specifies the signbit of NAN values with
3454 // fneg/fabs operations.
3455 if (!SI.hasNoSignedZeros() &&
3456 (!SI.hasOneUse() || !canIgnoreSignBitOfZero(U: *SI.use_begin())))
3457 return nullptr;
3458 if (!SI.hasNoNaNs() &&
3459 (!SI.hasOneUse() || !canIgnoreSignBitOfNaN(U: *SI.use_begin())))
3460 return nullptr;
3461
3462 if (Swap)
3463 Pred = FCmpInst::getSwappedPredicate(pred: Pred);
3464
3465 bool IsLTOrLE = Pred == FCmpInst::FCMP_OLT || Pred == FCmpInst::FCMP_OLE ||
3466 Pred == FCmpInst::FCMP_ULT || Pred == FCmpInst::FCMP_ULE;
3467 bool IsGTOrGE = Pred == FCmpInst::FCMP_OGT || Pred == FCmpInst::FCMP_OGE ||
3468 Pred == FCmpInst::FCMP_UGT || Pred == FCmpInst::FCMP_UGE;
3469
3470 if (IsLTOrLE) {
3471 Value *Fabs = IC.Builder.CreateFAbs(V: X, FMFSource: &SI);
3472 return IC.replaceInstUsesWith(I&: SI, V: Fabs);
3473 }
3474 if (IsGTOrGE) {
3475 Value *Fabs = IC.Builder.CreateFAbs(V: X, FMFSource: &SI);
3476 Instruction *NewFNeg = UnaryOperator::CreateFNeg(V: Fabs);
3477 NewFNeg->setFastMathFlags(SI.getFastMathFlags());
3478 return NewFNeg;
3479 }
3480 }
3481
3482 // Match select with (icmp slt (bitcast X to int), 0)
3483 // or (icmp sgt (bitcast X to int), -1)
3484
3485 for (bool Swap : {false, true}) {
3486 Value *TrueVal = SI.getTrueValue();
3487 Value *X = SI.getFalseValue();
3488
3489 if (Swap)
3490 std::swap(a&: TrueVal, b&: X);
3491
3492 CmpPredicate Pred;
3493 const APInt *C;
3494 bool TrueIfSigned;
3495 if (!match(V: CondVal,
3496 P: m_ICmp(Pred, L: m_ElementWiseBitCast(Op: m_Specific(V: X)), R: m_APInt(Res&: C))) ||
3497 !isSignBitCheck(Pred, RHS: *C, TrueIfSigned))
3498 continue;
3499 if (!match(V: TrueVal, P: m_FNeg(X: m_Specific(V: X))))
3500 return nullptr;
3501 if (Swap == TrueIfSigned && !CondVal->hasOneUse() && !TrueVal->hasOneUse())
3502 return nullptr;
3503
3504 // Fold (IsNeg ? -X : X) or (!IsNeg ? X : -X) to fabs(X)
3505 // Fold (IsNeg ? X : -X) or (!IsNeg ? -X : X) to -fabs(X)
3506 Value *Fabs = IC.Builder.CreateFAbs(V: X, FMFSource: &SI);
3507 if (Swap != TrueIfSigned)
3508 return IC.replaceInstUsesWith(I&: SI, V: Fabs);
3509 return UnaryOperator::CreateFNegFMF(Op: Fabs, FMFSource: &SI);
3510 }
3511
3512 return ChangedFMF ? &SI : nullptr;
3513}
3514
3515// Fold a select of an ordered fcmp using fabs of a NaN-scrubbed value:
3516// %s = select i1 (isnotnan T %x), T %x, T %y
3517// %a = call T @llvm.fabs.T(T %s)
3518// %c = fcmp <ordered-pred> T %a, %k
3519// %r = select i1 %c, T %s, T %y
3520// =>
3521// %a2 = call T @llvm.fabs.T(T %x)
3522// %c2 = fcmp <ordered-pred> T %a2, %k
3523// %r2 = select i1 %c2, T %x, T %y
3524static Instruction *
3525foldSelectOfOrderedFAbsCmpOfNaNScrubbedValue(SelectInst &SI,
3526 InstCombinerImpl &IC) {
3527 Instruction *OuterCmpI;
3528 Value *Cmp0, *Cmp1;
3529 if (!match(V: SI.getCondition(),
3530 P: m_OneUse(SubPattern: m_Instruction(I&: OuterCmpI,
3531 P: m_FCmp(L: m_Value(V&: Cmp0), R: m_Value(V&: Cmp1))))))
3532 return nullptr;
3533
3534 auto *OuterCmp = cast<FCmpInst>(Val: OuterCmpI);
3535 CmpInst::Predicate Pred = OuterCmp->getPredicate();
3536 if (!FCmpInst::isOrdered(predicate: Pred))
3537 return nullptr;
3538
3539 Value *Y = SI.getFalseValue();
3540 Value *InnerSel = SI.getTrueValue();
3541
3542 // Match a select that returns X when X is not NaN, and Y otherwise:
3543 // select (fcmp ord X, 0.0), X, Y
3544 Value *X;
3545 if (!match(V: InnerSel,
3546 P: m_Select(C: m_OneUse(SubPattern: m_SpecificFCmp(MatchPred: FCmpInst::FCMP_ORD, L: m_Value(V&: X),
3547 R: m_AnyZeroFP())),
3548 L: m_Deferred(V: X), R: m_Specific(V: Y))))
3549 return nullptr;
3550
3551 Instruction *FAbsI;
3552 auto MatchFAbsOfInnerSel = [&](Value *V) {
3553 return match(V,
3554 P: m_OneUse(SubPattern: m_Instruction(I&: FAbsI, P: m_FAbs(Op0: m_Specific(V: InnerSel)))));
3555 };
3556
3557 if (!MatchFAbsOfInnerSel(Cmp0)) {
3558 if (!MatchFAbsOfInnerSel(Cmp1))
3559 return nullptr;
3560
3561 std::swap(a&: Cmp0, b&: Cmp1);
3562 Pred = CmpInst::getSwappedPredicate(pred: Pred);
3563 }
3564
3565 FastMathFlags FAbsFMF = FAbsI->getFastMathFlags();
3566 FastMathFlags CmpFMF = OuterCmp->getFastMathFlags();
3567
3568 FastMathFlags CommonRewriteFMF =
3569 FastMathFlags::intersectRewrite(LHS: FAbsFMF, RHS: CmpFMF);
3570
3571 // unionValue with FastMathFlags() drops all rewriter based flags
3572 FastMathFlags NewFAbsFMF =
3573 CommonRewriteFMF | FastMathFlags::unionValue(LHS: FAbsFMF, RHS: FastMathFlags());
3574 FastMathFlags NewCmpFMF =
3575 CommonRewriteFMF | FastMathFlags::unionValue(LHS: CmpFMF, RHS: FastMathFlags());
3576
3577 // When X is NaN, the old code evaluated fabs(Y), while the new code evaluates
3578 // fabs(X). Do not preserve nnan on either newly-created instruction.
3579 NewFAbsFMF.setNoNaNs(false);
3580 NewCmpFMF.setNoNaNs(false);
3581
3582 Value *NewAbs = IC.Builder.CreateFAbs(V: X, FMFSource: FMFSource(NewFAbsFMF));
3583 Value *NewCmp =
3584 IC.Builder.CreateFCmpFMF(P: Pred, LHS: NewAbs, RHS: Cmp1, FMFSource: FMFSource(NewCmpFMF));
3585 Value *NewSel = IC.Builder.CreateSelectFMF(C: NewCmp, True: X, False: Y, FMFSource: &SI);
3586
3587 Instruction *NewSelUsesReplaced = IC.replaceInstUsesWith(I&: SI, V: NewSel);
3588
3589 uint64_t WeightNotNaN, WeightNaN, WeightComparisonTrue,
3590 WeightComparisonFalse = 0;
3591 bool HasProfile = extractBranchWeights(I: *cast<SelectInst>(Val: InnerSel),
3592 TrueVal&: WeightNotNaN, FalseVal&: WeightNaN);
3593 HasProfile &=
3594 extractBranchWeights(I: SI, TrueVal&: WeightComparisonTrue, FalseVal&: WeightComparisonFalse);
3595 if (!HasProfile || !isa<SelectInst>(Val: NewSel))
3596 return NewSelUsesReplaced;
3597 // The branch weights for the new select will be the same as before, except
3598 // they will additionally account for the probability of NaN values which was
3599 // previously handled with the inner select. For the true arm the new
3600 // probability is P(not Nan) * P(fcmp true). For the false arm, the new
3601 // probability is P(NaN) + (P(not NaN) * P(fcmp false)). We can assume the
3602 // probabilities are independent given the first select only checks for NaNs
3603 // and the second select's condition will never see NaNs because of the first
3604 // select. The code below uses some algebraic simplifications on top of those
3605 // formulas.
3606 uint64_t WeightNewSelTrue = WeightNotNaN * WeightComparisonTrue;
3607 uint64_t WeightNewSelFalse =
3608 WeightNaN * (WeightComparisonTrue + WeightComparisonFalse) +
3609 WeightNotNaN * WeightComparisonFalse;
3610 if (!ProfcheckDisableMetadataFixes)
3611 setFittedBranchWeights(I&: *cast<SelectInst>(Val: NewSel),
3612 Weights: {WeightNewSelTrue, WeightNewSelFalse},
3613 /*IsExpected*/ false);
3614 return NewSelUsesReplaced;
3615}
3616
3617// Match the following IR pattern:
3618// %x.lowbits = and i8 %x, %lowbitmask
3619// %x.lowbits.are.zero = icmp eq i8 %x.lowbits, 0
3620// %x.biased = add i8 %x, %bias
3621// %x.biased.highbits = and i8 %x.biased, %highbitmask
3622// %x.roundedup = select i1 %x.lowbits.are.zero, i8 %x, i8 %x.biased.highbits
3623// Define:
3624// %alignment = add i8 %lowbitmask, 1
3625// Iff 1. an %alignment is a power-of-two (aka, %lowbitmask is a low bit mask)
3626// and 2. %bias is equal to either %lowbitmask or %alignment,
3627// and 3. %highbitmask is equal to ~%lowbitmask (aka, to -%alignment)
3628// then this pattern can be transformed into:
3629// %x.offset = add i8 %x, %lowbitmask
3630// %x.roundedup = and i8 %x.offset, %highbitmask
3631static Value *
3632foldRoundUpIntegerWithPow2Alignment(SelectInst &SI,
3633 InstCombiner::BuilderTy &Builder) {
3634 Value *Cond = SI.getCondition();
3635 Value *X = SI.getTrueValue();
3636 Value *XBiasedHighBits = SI.getFalseValue();
3637
3638 CmpPredicate Pred;
3639 Value *XLowBits;
3640 if (!match(V: Cond, P: m_ICmp(Pred, L: m_Value(V&: XLowBits), R: m_ZeroInt())) ||
3641 !ICmpInst::isEquality(P: Pred))
3642 return nullptr;
3643
3644 if (Pred == ICmpInst::Predicate::ICMP_NE)
3645 std::swap(a&: X, b&: XBiasedHighBits);
3646
3647 // FIXME: we could support non non-splats here.
3648
3649 const APInt *LowBitMaskCst;
3650 if (!match(V: XLowBits, P: m_And(L: m_Specific(V: X), R: m_APIntAllowPoison(Res&: LowBitMaskCst))))
3651 return nullptr;
3652
3653 // Match even if the AND and ADD are swapped.
3654 const APInt *BiasCst, *HighBitMaskCst;
3655 if (!match(V: XBiasedHighBits,
3656 P: m_And(L: m_Add(L: m_Specific(V: X), R: m_APIntAllowPoison(Res&: BiasCst)),
3657 R: m_APIntAllowPoison(Res&: HighBitMaskCst))) &&
3658 !match(V: XBiasedHighBits,
3659 P: m_Add(L: m_And(L: m_Specific(V: X), R: m_APIntAllowPoison(Res&: HighBitMaskCst)),
3660 R: m_APIntAllowPoison(Res&: BiasCst))))
3661 return nullptr;
3662
3663 if (!LowBitMaskCst->isMask())
3664 return nullptr;
3665
3666 APInt InvertedLowBitMaskCst = ~*LowBitMaskCst;
3667 if (InvertedLowBitMaskCst != *HighBitMaskCst)
3668 return nullptr;
3669
3670 APInt AlignmentCst = *LowBitMaskCst + 1;
3671
3672 if (*BiasCst != AlignmentCst && *BiasCst != *LowBitMaskCst)
3673 return nullptr;
3674
3675 if (!XBiasedHighBits->hasOneUse()) {
3676 // We can't directly return XBiasedHighBits if it is more poisonous.
3677 if (*BiasCst == *LowBitMaskCst && impliesPoison(ValAssumedPoison: XBiasedHighBits, V: X))
3678 return XBiasedHighBits;
3679 return nullptr;
3680 }
3681
3682 // FIXME: could we preserve undef's here?
3683 Type *Ty = X->getType();
3684 Value *XOffset = Builder.CreateAdd(LHS: X, RHS: ConstantInt::get(Ty, V: *LowBitMaskCst),
3685 Name: X->getName() + ".biased");
3686 Value *R = Builder.CreateAnd(LHS: XOffset, RHS: ConstantInt::get(Ty, V: *HighBitMaskCst));
3687 R->takeName(V: &SI);
3688 return R;
3689}
3690
3691namespace {
3692struct DecomposedSelect {
3693 Value *Cond = nullptr;
3694 Value *TrueVal = nullptr;
3695 Value *FalseVal = nullptr;
3696};
3697} // namespace
3698
3699/// Folds patterns like:
3700/// select c2 (select c1 a b) (select c1 b a)
3701/// into:
3702/// select (xor c1 c2) b a
3703static Instruction *
3704foldSelectOfSymmetricSelect(SelectInst &OuterSelVal,
3705 InstCombiner::BuilderTy &Builder) {
3706
3707 Value *OuterCond, *InnerCond, *InnerTrueVal, *InnerFalseVal;
3708 if (!match(
3709 V: &OuterSelVal,
3710 P: m_Select(C: m_Value(V&: OuterCond),
3711 L: m_OneUse(SubPattern: m_Select(C: m_Value(V&: InnerCond), L: m_Value(V&: InnerTrueVal),
3712 R: m_Value(V&: InnerFalseVal))),
3713 R: m_OneUse(SubPattern: m_Select(C: m_Deferred(V: InnerCond),
3714 L: m_Deferred(V: InnerFalseVal),
3715 R: m_Deferred(V: InnerTrueVal))))))
3716 return nullptr;
3717
3718 if (OuterCond->getType() != InnerCond->getType())
3719 return nullptr;
3720
3721 Value *Xor = Builder.CreateXor(LHS: InnerCond, RHS: OuterCond);
3722 SelectInst *SI = SelectInst::Create(C: Xor, S1: InnerFalseVal, S2: InnerTrueVal);
3723 // We cannot construct branch weights without assuming that the distributions
3724 // of the two conditions are independent, so mark the branch weights as
3725 // unknown.
3726 setExplicitlyUnknownBranchWeightsIfProfiled(I&: *SI, DEBUG_TYPE,
3727 F: OuterSelVal.getFunction());
3728 return SI;
3729}
3730
3731/// Look for patterns like
3732/// %outer.cond = select i1 %inner.cond, i1 %alt.cond, i1 false
3733/// %inner.sel = select i1 %inner.cond, i8 %inner.sel.t, i8 %inner.sel.f
3734/// %outer.sel = select i1 %outer.cond, i8 %outer.sel.t, i8 %inner.sel
3735/// and rewrite it as
3736/// %inner.sel = select i1 %cond.alternative, i8 %sel.outer.t, i8 %sel.inner.t
3737/// %sel.outer = select i1 %cond.inner, i8 %inner.sel, i8 %sel.inner.f
3738static Instruction *foldNestedSelects(SelectInst &OuterSelVal,
3739 InstCombiner::BuilderTy &Builder) {
3740 // We must start with a `select`.
3741 DecomposedSelect OuterSel;
3742 match(V: &OuterSelVal,
3743 P: m_Select(C: m_Value(V&: OuterSel.Cond), L: m_Value(V&: OuterSel.TrueVal),
3744 R: m_Value(V&: OuterSel.FalseVal)));
3745
3746 // Canonicalize inversion of the outermost `select`'s condition.
3747 if (match(V: OuterSel.Cond, P: m_Not(V: m_Value(V&: OuterSel.Cond))))
3748 std::swap(a&: OuterSel.TrueVal, b&: OuterSel.FalseVal);
3749
3750 // The condition of the outermost select must be an `and`/`or`.
3751 if (!match(V: OuterSel.Cond, P: m_c_LogicalOp(L: m_Value(), R: m_Value())))
3752 return nullptr;
3753
3754 // Depending on the logical op, inner select might be in different hand.
3755 bool IsAndVariant = match(V: OuterSel.Cond, P: m_LogicalAnd());
3756 Value *InnerSelVal = IsAndVariant ? OuterSel.FalseVal : OuterSel.TrueVal;
3757
3758 // Profitability check - avoid increasing instruction count.
3759 if (none_of(Range: ArrayRef<Value *>({OuterSelVal.getCondition(), InnerSelVal}),
3760 P: match_fn(P: m_OneUse(SubPattern: m_Value()))))
3761 return nullptr;
3762
3763 // The appropriate hand of the outermost `select` must be a select itself.
3764 DecomposedSelect InnerSel;
3765 if (!match(V: InnerSelVal,
3766 P: m_Select(C: m_Value(V&: InnerSel.Cond), L: m_Value(V&: InnerSel.TrueVal),
3767 R: m_Value(V&: InnerSel.FalseVal))))
3768 return nullptr;
3769
3770 // Canonicalize inversion of the innermost `select`'s condition.
3771 bool SwapInnerSelCond = false;
3772 if (match(V: InnerSel.Cond, P: m_Not(V: m_Value(V&: InnerSel.Cond)))) {
3773 std::swap(a&: InnerSel.TrueVal, b&: InnerSel.FalseVal);
3774 SwapInnerSelCond = !SwapInnerSelCond;
3775 }
3776
3777 Value *AltCond = nullptr;
3778 auto matchOuterCond = [OuterSel, IsAndVariant, &AltCond](auto m_InnerCond) {
3779 // An unsimplified select condition can match both LogicalAnd and LogicalOr
3780 // (select true, true, false). Since below we assume that LogicalAnd implies
3781 // InnerSel match the FVal and vice versa for LogicalOr, we can't match the
3782 // alternative pattern here.
3783 return IsAndVariant ? match(OuterSel.Cond,
3784 m_c_LogicalAnd(m_InnerCond, m_Value(V&: AltCond)))
3785 : match(OuterSel.Cond,
3786 m_c_LogicalOr(m_InnerCond, m_Value(V&: AltCond)));
3787 };
3788
3789 // Finally, match the condition that was driving the outermost `select`,
3790 // it should be a logical operation between the condition that was driving
3791 // the innermost `select` (after accounting for the possible inversions
3792 // of the condition), and some other condition.
3793 if (matchOuterCond(m_Specific(V: InnerSel.Cond))) {
3794 // Done!
3795 } else if (Value * NotInnerCond; matchOuterCond(m_CombineAnd(
3796 Ps: m_Not(V: m_Specific(V: InnerSel.Cond)), Ps: m_Value(V&: NotInnerCond)))) {
3797 // Done!
3798 std::swap(a&: InnerSel.TrueVal, b&: InnerSel.FalseVal);
3799 InnerSel.Cond = NotInnerCond;
3800 SwapInnerSelCond = !SwapInnerSelCond;
3801 } else // Not the pattern we were looking for.
3802 return nullptr;
3803
3804 // We mark the select with AltCond as having an unknown profile given the
3805 // condition is derived from an and/or. We might have profile information on
3806 // the operands of the and/or, but there is no guarantee that they are
3807 // independent.
3808 Value *SelInner = Builder.CreateSelectWithUnknownProfile(
3809 C: AltCond, True: IsAndVariant ? OuterSel.TrueVal : InnerSel.FalseVal,
3810 False: IsAndVariant ? InnerSel.TrueVal : OuterSel.FalseVal, DEBUG_TYPE);
3811 SelInner->takeName(V: InnerSelVal);
3812 SelectInst *SI = SelectInst::Create(
3813 C: InnerSel.Cond, S1: IsAndVariant ? SelInner : InnerSel.TrueVal,
3814 S2: !IsAndVariant ? SelInner : InnerSel.FalseVal, NameStr: "", InsertBefore: nullptr,
3815 MDFrom: ProfcheckDisableMetadataFixes ? nullptr : cast<Instruction>(Val: InnerSelVal));
3816 if (SwapInnerSelCond)
3817 SI->swapProfMetadata();
3818 return SI;
3819}
3820
3821/// Return true if V is poison or \p Expected given that ValAssumedPoison is
3822/// already poison. For example, if ValAssumedPoison is `icmp samesign X, 10`
3823/// and V is `icmp ne X, 5`, impliesPoisonOrCond returns true.
3824static bool impliesPoisonOrCond(const Value *ValAssumedPoison, const Value *V,
3825 bool Expected, const SimplifyQuery &SQ) {
3826 if (impliesPoison(ValAssumedPoison, V))
3827 return true;
3828
3829 // Handle the case that ValAssumedPoison is `icmp samesign pred X, C1` and V
3830 // is `icmp pred X, C2`, where C1 is well-defined.
3831 if (auto *ICmp = dyn_cast<ICmpInst>(Val: ValAssumedPoison)) {
3832 Value *LHS = ICmp->getOperand(i_nocapture: 0);
3833 const APInt *RHSC1;
3834 const APInt *RHSC2;
3835 CmpPredicate Pred;
3836 if (ICmp->hasSameSign() &&
3837 match(V: ICmp->getOperand(i_nocapture: 1), P: m_APIntForbidPoison(Res&: RHSC1)) &&
3838 match(V, P: m_ICmp(Pred, L: m_Specific(V: LHS), R: m_APIntAllowPoison(Res&: RHSC2)))) {
3839 unsigned BitWidth = RHSC1->getBitWidth();
3840 ConstantRange CRX =
3841 RHSC1->isNonNegative()
3842 ? ConstantRange(APInt::getSignedMinValue(numBits: BitWidth),
3843 APInt::getZero(numBits: BitWidth))
3844 : ConstantRange(APInt::getZero(numBits: BitWidth),
3845 APInt::getSignedMinValue(numBits: BitWidth));
3846 return CRX.icmp(Pred: Expected ? Pred : ICmpInst::getInverseCmpPredicate(Pred),
3847 Other: *RHSC2);
3848 }
3849 }
3850 // For non-poison X in [0, 1], `trunc nuw X to i1` is not poison, but an
3851 // additional `nsw` flag makes it poison for X == 1.
3852 Value *A;
3853 if (match(V: ValAssumedPoison, P: m_NUWTrunc(Op: m_Value(V&: A))) &&
3854 !cast<TruncInst>(Val: ValAssumedPoison)->hasNoSignedWrap() &&
3855 isGuaranteedNotToBePoison(V: A)) {
3856 assert(ValAssumedPoison->getType()->isIntOrIntVectorTy(1));
3857 return computeKnownBits(
3858 V: A, Q: SQ.getWithInstruction(I: cast<Instruction>(Val: ValAssumedPoison)))
3859 .getMaxValue() == 1;
3860 }
3861
3862 return false;
3863}
3864
3865Instruction *InstCombinerImpl::foldSelectOfBools(SelectInst &SI) {
3866 Value *CondVal = SI.getCondition();
3867 Value *TrueVal = SI.getTrueValue();
3868 Value *FalseVal = SI.getFalseValue();
3869 Type *SelType = SI.getType();
3870
3871 // Avoid potential infinite loops by checking for non-constant condition.
3872 // TODO: Can we assert instead by improving canonicalizeSelectToShuffle()?
3873 // Scalar select must have simplified?
3874 if (!SelType->isIntOrIntVectorTy(BitWidth: 1) || isa<Constant>(Val: CondVal) ||
3875 TrueVal->getType() != CondVal->getType())
3876 return nullptr;
3877
3878 auto *One = ConstantInt::getTrue(Ty: SelType);
3879 auto *Zero = ConstantInt::getFalse(Ty: SelType);
3880 Value *A, *B, *C, *D;
3881
3882 // Folding select to and/or i1 isn't poison safe in general. impliesPoison
3883 // checks whether folding it does not convert a well-defined value into
3884 // poison.
3885 if (match(V: TrueVal, P: m_One())) {
3886 if (impliesPoisonOrCond(ValAssumedPoison: FalseVal, V: CondVal, /*Expected=*/false, SQ)) {
3887 // Change: A = select B, true, C --> A = or B, C
3888 return BinaryOperator::CreateOr(V1: CondVal, V2: FalseVal);
3889 }
3890
3891 if (match(V: CondVal, P: m_OneUse(SubPattern: m_Select(C: m_Value(V&: A), L: m_One(), R: m_Value(V&: B)))) &&
3892 impliesPoisonOrCond(ValAssumedPoison: FalseVal, V: B, /*Expected=*/false, SQ)) {
3893 // (A || B) || C --> A || (B | C)
3894 Value *LOr = Builder.CreateLogicalOr(Cond1: A, Cond2: Builder.CreateOr(LHS: B, RHS: FalseVal));
3895 if (auto *I = dyn_cast<Instruction>(Val: LOr)) {
3896 setExplicitlyUnknownBranchWeightsIfProfiled(I&: *I, DEBUG_TYPE);
3897 }
3898 return replaceInstUsesWith(I&: SI, V: LOr);
3899 }
3900
3901 // (A && B) || (C && B) --> (A || C) && B
3902 if (match(V: CondVal, P: m_LogicalAnd(L: m_Value(V&: A), R: m_Value(V&: B))) &&
3903 match(V: FalseVal, P: m_LogicalAnd(L: m_Value(V&: C), R: m_Value(V&: D))) &&
3904 (CondVal->hasOneUse() || FalseVal->hasOneUse())) {
3905 bool CondLogicAnd = isa<SelectInst>(Val: CondVal);
3906 bool FalseLogicAnd = isa<SelectInst>(Val: FalseVal);
3907 auto AndFactorization = [&](Value *Common, Value *InnerCond,
3908 Value *InnerVal,
3909 bool SelFirst = false) -> Instruction * {
3910 Value *InnerSel = Builder.CreateSelectWithUnknownProfile(
3911 C: InnerCond, True: One, False: InnerVal, DEBUG_TYPE);
3912 if (SelFirst)
3913 std::swap(a&: Common, b&: InnerSel);
3914 if (FalseLogicAnd || (CondLogicAnd && Common == A))
3915 return createSelectInstWithUnknownProfile(C: Common, S1: InnerSel, S2: Zero);
3916 else
3917 return BinaryOperator::CreateAnd(V1: Common, V2: InnerSel);
3918 };
3919
3920 if (A == C)
3921 return AndFactorization(A, B, D);
3922 if (A == D)
3923 return AndFactorization(A, B, C);
3924 if (B == C)
3925 return AndFactorization(B, A, D);
3926 if (B == D)
3927 return AndFactorization(B, A, C, CondLogicAnd && FalseLogicAnd);
3928 }
3929 }
3930
3931 if (match(V: FalseVal, P: m_Zero())) {
3932 if (impliesPoisonOrCond(ValAssumedPoison: TrueVal, V: CondVal, /*Expected=*/true, SQ)) {
3933 // Change: A = select B, C, false --> A = and B, C
3934 return BinaryOperator::CreateAnd(V1: CondVal, V2: TrueVal);
3935 }
3936
3937 if (match(V: CondVal, P: m_OneUse(SubPattern: m_Select(C: m_Value(V&: A), L: m_Value(V&: B), R: m_Zero()))) &&
3938 impliesPoisonOrCond(ValAssumedPoison: TrueVal, V: B, /*Expected=*/true, SQ)) {
3939 // (A && B) && C --> A && (B & C)
3940 Value *LAnd = Builder.CreateLogicalAnd(Cond1: A, Cond2: Builder.CreateAnd(LHS: B, RHS: TrueVal));
3941 if (auto *I = dyn_cast<Instruction>(Val: LAnd)) {
3942 setExplicitlyUnknownBranchWeightsIfProfiled(I&: *I, DEBUG_TYPE);
3943 }
3944 return replaceInstUsesWith(I&: SI, V: LAnd);
3945 }
3946
3947 // (A || B) && (C || B) --> (A && C) || B
3948 if (match(V: CondVal, P: m_LogicalOr(L: m_Value(V&: A), R: m_Value(V&: B))) &&
3949 match(V: TrueVal, P: m_LogicalOr(L: m_Value(V&: C), R: m_Value(V&: D))) &&
3950 (CondVal->hasOneUse() || TrueVal->hasOneUse())) {
3951 bool CondLogicOr = isa<SelectInst>(Val: CondVal);
3952 bool TrueLogicOr = isa<SelectInst>(Val: TrueVal);
3953 auto OrFactorization = [&](Value *Common, Value *InnerCond,
3954 Value *InnerVal,
3955 bool SelFirst = false) -> Instruction * {
3956 Value *InnerSel = Builder.CreateSelectWithUnknownProfile(
3957 C: InnerCond, True: InnerVal, False: Zero, DEBUG_TYPE);
3958 if (SelFirst)
3959 std::swap(a&: Common, b&: InnerSel);
3960 if (TrueLogicOr || (CondLogicOr && Common == A))
3961 return createSelectInstWithUnknownProfile(C: Common, S1: One, S2: InnerSel);
3962 else
3963 return BinaryOperator::CreateOr(V1: Common, V2: InnerSel);
3964 };
3965
3966 if (A == C)
3967 return OrFactorization(A, B, D);
3968 if (A == D)
3969 return OrFactorization(A, B, C);
3970 if (B == C)
3971 return OrFactorization(B, A, D);
3972 if (B == D)
3973 return OrFactorization(B, A, C, CondLogicOr && TrueLogicOr);
3974 }
3975 }
3976
3977 // We match the "full" 0 or 1 constant here to avoid a potential infinite
3978 // loop with vectors that may have undefined/poison elements.
3979 // select a, false, b -> select !a, b, false
3980 if (match(V: TrueVal, P: m_Specific(V: Zero))) {
3981 Value *NotCond = Builder.CreateNot(V: CondVal, Name: "not." + CondVal->getName());
3982 SelectInst *NewSI = SelectInst::Create(C: NotCond, S1: FalseVal, S2: Zero, NameStr: "", InsertBefore: nullptr,
3983 /*MDFrom=*/&SI);
3984 NewSI->swapProfMetadata();
3985 return NewSI;
3986 }
3987 // select a, b, true -> select !a, true, b
3988 if (match(V: FalseVal, P: m_Specific(V: One))) {
3989 Value *NotCond = Builder.CreateNot(V: CondVal, Name: "not." + CondVal->getName());
3990 SelectInst *NewSI =
3991 SelectInst::Create(C: NotCond, S1: One, S2: TrueVal, NameStr: "", InsertBefore: nullptr, /*MDFrom=*/&SI);
3992 NewSI->swapProfMetadata();
3993 return NewSI;
3994 }
3995
3996 // DeMorgan in select form: !a && !b --> !(a || b)
3997 // select !a, !b, false --> not (select a, true, b)
3998 if (match(V: &SI, P: m_LogicalAnd(L: m_Not(V: m_Value(V&: A)), R: m_Not(V: m_Value(V&: B)))) &&
3999 (CondVal->hasOneUse() || TrueVal->hasOneUse()) &&
4000 !match(V: A, P: m_ConstantExpr()) && !match(V: B, P: m_ConstantExpr())) {
4001 SelectInst *NewSI =
4002 cast<SelectInst>(Val: Builder.CreateSelect(C: A, True: One, False: B, Name: "", /*MDFrom=*/&SI));
4003 NewSI->swapProfMetadata();
4004 return BinaryOperator::CreateNot(Op: NewSI);
4005 }
4006
4007 // DeMorgan in select form: !a || !b --> !(a && b)
4008 // select !a, true, !b --> not (select a, b, false)
4009 if (match(V: &SI, P: m_LogicalOr(L: m_Not(V: m_Value(V&: A)), R: m_Not(V: m_Value(V&: B)))) &&
4010 (CondVal->hasOneUse() || FalseVal->hasOneUse()) &&
4011 !match(V: A, P: m_ConstantExpr()) && !match(V: B, P: m_ConstantExpr())) {
4012 SelectInst *NewSI =
4013 cast<SelectInst>(Val: Builder.CreateSelect(C: A, True: B, False: Zero, Name: "", /*MDFrom=*/&SI));
4014 NewSI->swapProfMetadata();
4015 return BinaryOperator::CreateNot(Op: NewSI);
4016 }
4017
4018 // select (select a, true, b), true, b -> select a, true, b
4019 if (match(V: CondVal, P: m_Select(C: m_Value(V&: A), L: m_One(), R: m_Value(V&: B))) &&
4020 match(V: TrueVal, P: m_One()) && match(V: FalseVal, P: m_Specific(V: B)))
4021 return replaceOperand(I&: SI, OpNum: 0, V: A);
4022 // select (select a, b, false), b, false -> select a, b, false
4023 if (match(V: CondVal, P: m_Select(C: m_Value(V&: A), L: m_Value(V&: B), R: m_Zero())) &&
4024 match(V: TrueVal, P: m_Specific(V: B)) && match(V: FalseVal, P: m_Zero()))
4025 return replaceOperand(I&: SI, OpNum: 0, V: A);
4026
4027 // ~(A & B) & (A | B) --> A ^ B
4028 if (match(V: &SI, P: m_c_LogicalAnd(L: m_Not(V: m_LogicalAnd(L: m_Value(V&: A), R: m_Value(V&: B))),
4029 R: m_c_LogicalOr(L: m_Deferred(V: A), R: m_Deferred(V: B)))))
4030 return BinaryOperator::CreateXor(V1: A, V2: B);
4031
4032 // select (~a | c), a, b -> select a, (select c, true, b), false
4033 if (match(V: CondVal,
4034 P: m_OneUse(SubPattern: m_c_Or(L: m_Not(V: m_Specific(V: TrueVal)), R: m_Value(V&: C))))) {
4035 // TODO(#183864): We could improve the profile if P(~a | c) < 0.5, which
4036 // implies strong bounds on both operands (P(a) is high, P(c) is low).
4037 Value *OrV =
4038 Builder.CreateSelectWithUnknownProfile(C, True: One, False: FalseVal, DEBUG_TYPE);
4039 return createSelectInstWithUnknownProfile(C: TrueVal, S1: OrV, S2: Zero);
4040 }
4041 // select (c & b), a, b -> select b, (select ~c, true, a), false
4042 if (match(V: CondVal, P: m_OneUse(SubPattern: m_c_And(L: m_Value(V&: C), R: m_Specific(V: FalseVal))))) {
4043 if (Value *NotC = getFreelyInverted(V: C, WillInvertAllUses: C->hasOneUse(), Builder: &Builder)) {
4044 Value *OrV = Builder.CreateSelectWithUnknownProfile(C: NotC, True: One, False: TrueVal,
4045 DEBUG_TYPE);
4046 return createSelectInstWithUnknownProfile(C: FalseVal, S1: OrV, S2: Zero);
4047 }
4048 }
4049 // select (a | c), a, b -> select a, true, (select ~c, b, false)
4050 if (match(V: CondVal, P: m_OneUse(SubPattern: m_c_Or(L: m_Specific(V: TrueVal), R: m_Value(V&: C))))) {
4051 if (Value *NotC = getFreelyInverted(V: C, WillInvertAllUses: C->hasOneUse(), Builder: &Builder)) {
4052 // TODO(#183864): We could improve the profile if P(a | c) < 0.5, which
4053 // implies strong bounds on both operands (both P(a) and P(c) are low).
4054 Value *AndV = Builder.CreateSelectWithUnknownProfile(C: NotC, True: FalseVal, False: Zero,
4055 DEBUG_TYPE);
4056 return createSelectInstWithUnknownProfile(C: TrueVal, S1: One, S2: AndV);
4057 }
4058 }
4059 // select (c & ~b), a, b -> select b, true, (select c, a, false)
4060 if (match(V: CondVal,
4061 P: m_OneUse(SubPattern: m_c_And(L: m_Value(V&: C), R: m_Not(V: m_Specific(V: FalseVal)))))) {
4062 Value *AndV =
4063 Builder.CreateSelectWithUnknownProfile(C, True: TrueVal, False: Zero, DEBUG_TYPE);
4064 return createSelectInstWithUnknownProfile(C: FalseVal, S1: One, S2: AndV);
4065 }
4066
4067 if (match(V: FalseVal, P: m_Zero()) || match(V: TrueVal, P: m_One())) {
4068 Use *Y = nullptr;
4069 bool IsAnd = match(V: FalseVal, P: m_Zero()) ? true : false;
4070 Value *Op1 = IsAnd ? TrueVal : FalseVal;
4071 if (isCheckForZeroAndMulWithOverflow(Op0: CondVal, Op1, IsAnd, Y)) {
4072 auto *FI = new FreezeInst(*Y, (*Y)->getName() + ".fr");
4073 InsertNewInstBefore(New: FI, Old: cast<Instruction>(Val: Y->getUser())->getIterator());
4074 replaceUse(U&: *Y, NewValue: FI);
4075 return replaceInstUsesWith(I&: SI, V: Op1);
4076 }
4077
4078 if (auto *V = foldBooleanAndOr(LHS: CondVal, RHS: Op1, I&: SI, IsAnd,
4079 /*IsLogical=*/true))
4080 return replaceInstUsesWith(I&: SI, V);
4081 }
4082
4083 // select (a || b), c, false -> select a, c, false
4084 // select c, (a || b), false -> select c, a, false
4085 // if c implies that b is false.
4086 if (match(V: CondVal, P: m_LogicalOr(L: m_Value(V&: A), R: m_Value(V&: B))) &&
4087 match(V: FalseVal, P: m_Zero())) {
4088 std::optional<bool> Res = isImpliedCondition(LHS: TrueVal, RHS: B, DL);
4089 if (Res && *Res == false)
4090 return replaceOperand(I&: SI, OpNum: 0, V: A);
4091 }
4092 if (match(V: TrueVal, P: m_LogicalOr(L: m_Value(V&: A), R: m_Value(V&: B))) &&
4093 match(V: FalseVal, P: m_Zero())) {
4094 std::optional<bool> Res = isImpliedCondition(LHS: CondVal, RHS: B, DL);
4095 if (Res && *Res == false)
4096 return replaceOperand(I&: SI, OpNum: 1, V: A);
4097 }
4098 // select c, true, (a && b) -> select c, true, a
4099 // select (a && b), true, c -> select a, true, c
4100 // if c = false implies that b = true
4101 if (match(V: TrueVal, P: m_One()) &&
4102 match(V: FalseVal, P: m_LogicalAnd(L: m_Value(V&: A), R: m_Value(V&: B)))) {
4103 std::optional<bool> Res = isImpliedCondition(LHS: CondVal, RHS: B, DL, LHSIsTrue: false);
4104 if (Res && *Res == true)
4105 return replaceOperand(I&: SI, OpNum: 2, V: A);
4106 }
4107 if (match(V: CondVal, P: m_LogicalAnd(L: m_Value(V&: A), R: m_Value(V&: B))) &&
4108 match(V: TrueVal, P: m_One())) {
4109 std::optional<bool> Res = isImpliedCondition(LHS: FalseVal, RHS: B, DL, LHSIsTrue: false);
4110 if (Res && *Res == true)
4111 return replaceOperand(I&: SI, OpNum: 0, V: A);
4112 }
4113
4114 if (match(V: TrueVal, P: m_One())) {
4115 // (C && A) || (!C && B) --> select C, A, B (and similar cases)
4116 if (auto *V = FoldOrOfLogicalAnds(Op0: CondVal, Op1: FalseVal)) {
4117 return V;
4118 }
4119 }
4120
4121 return nullptr;
4122}
4123
4124// Return true if we can safely remove the select instruction for std::bit_ceil
4125// pattern.
4126static bool isSafeToRemoveBitCeilSelect(ICmpInst::Predicate Pred, Value *Cond0,
4127 const APInt *Cond1, Value *CtlzOp,
4128 unsigned BitWidth,
4129 bool &ShouldDropNoWrap) {
4130 // The challenge in recognizing std::bit_ceil(X) is that the operand is used
4131 // for the CTLZ proper and select condition, each possibly with some
4132 // operation like add and sub.
4133 //
4134 // Our aim is to make sure that -ctlz & (BitWidth - 1) == 0 even when the
4135 // select instruction would select 1, which allows us to get rid of the select
4136 // instruction.
4137 //
4138 // To see if we can do so, we do some symbolic execution with ConstantRange.
4139 // Specifically, we compute the range of values that Cond0 could take when
4140 // Cond == false. Then we successively transform the range until we obtain
4141 // the range of values that CtlzOp could take.
4142 //
4143 // Conceptually, we follow the def-use chain backward from Cond0 while
4144 // transforming the range for Cond0 until we meet the common ancestor of Cond0
4145 // and CtlzOp. Then we follow the def-use chain forward until we obtain the
4146 // range for CtlzOp. That said, we only follow at most one ancestor from
4147 // Cond0. Likewise, we only follow at most one ancestor from CtrlOp.
4148
4149 ConstantRange CR = ConstantRange::makeExactICmpRegion(
4150 Pred: CmpInst::getInversePredicate(pred: Pred), Other: *Cond1);
4151
4152 ShouldDropNoWrap = false;
4153
4154 // Match the operation that's used to compute CtlzOp from CommonAncestor. If
4155 // CtlzOp == CommonAncestor, return true as no operation is needed. If a
4156 // match is found, execute the operation on CR, update CR, and return true.
4157 // Otherwise, return false.
4158 auto MatchForward = [&](Value *CommonAncestor) {
4159 const APInt *C = nullptr;
4160 if (CtlzOp == CommonAncestor)
4161 return true;
4162 if (match(V: CtlzOp, P: m_Add(L: m_Specific(V: CommonAncestor), R: m_APInt(Res&: C)))) {
4163 ShouldDropNoWrap = true;
4164 CR = CR.add(Other: *C);
4165 return true;
4166 }
4167 if (match(V: CtlzOp, P: m_Sub(L: m_APInt(Res&: C), R: m_Specific(V: CommonAncestor)))) {
4168 ShouldDropNoWrap = true;
4169 CR = ConstantRange(*C).sub(Other: CR);
4170 return true;
4171 }
4172 if (match(V: CtlzOp, P: m_Not(V: m_Specific(V: CommonAncestor)))) {
4173 CR = CR.binaryNot();
4174 return true;
4175 }
4176 return false;
4177 };
4178
4179 const APInt *C = nullptr;
4180 Value *CommonAncestor;
4181 if (MatchForward(Cond0)) {
4182 // Cond0 is either CtlzOp or CtlzOp's parent. CR has been updated.
4183 } else if (match(V: Cond0, P: m_Add(L: m_Value(V&: CommonAncestor), R: m_APInt(Res&: C)))) {
4184 CR = CR.sub(Other: *C);
4185 if (!MatchForward(CommonAncestor))
4186 return false;
4187 // Cond0's parent is either CtlzOp or CtlzOp's parent. CR has been updated.
4188 } else {
4189 return false;
4190 }
4191
4192 // Return true if all the values in the range are either 0 or negative (if
4193 // treated as signed). We do so by evaluating:
4194 //
4195 // CR - 1 u>= (1 << BitWidth) - 1.
4196 APInt IntMax = APInt::getSignMask(BitWidth) - 1;
4197 CR = CR.sub(Other: APInt(BitWidth, 1));
4198 return CR.icmp(Pred: ICmpInst::ICMP_UGE, Other: IntMax);
4199}
4200
4201// Transform the std::bit_ceil(X) pattern like:
4202//
4203// %dec = add i32 %x, -1
4204// %ctlz = tail call i32 @llvm.ctlz.i32(i32 %dec, i1 false)
4205// %sub = sub i32 32, %ctlz
4206// %shl = shl i32 1, %sub
4207// %ugt = icmp ugt i32 %x, 1
4208// %sel = select i1 %ugt, i32 %shl, i32 1
4209//
4210// into:
4211//
4212// %dec = add i32 %x, -1
4213// %ctlz = tail call i32 @llvm.ctlz.i32(i32 %dec, i1 false)
4214// %neg = sub i32 0, %ctlz
4215// %masked = and i32 %ctlz, 31
4216// %shl = shl i32 1, %sub
4217//
4218// Note that the select is optimized away while the shift count is masked with
4219// 31. We handle some variations of the input operand like std::bit_ceil(X +
4220// 1).
4221static Instruction *foldBitCeil(SelectInst &SI, IRBuilderBase &Builder,
4222 InstCombinerImpl &IC) {
4223 Type *SelType = SI.getType();
4224 unsigned BitWidth = SelType->getScalarSizeInBits();
4225 if (!isPowerOf2_32(Value: BitWidth))
4226 return nullptr;
4227
4228 Value *FalseVal = SI.getFalseValue();
4229 Value *TrueVal = SI.getTrueValue();
4230 CmpPredicate Pred;
4231 const APInt *Cond1;
4232 Value *Cond0, *Ctlz, *CtlzOp;
4233 if (!match(V: SI.getCondition(), P: m_ICmp(Pred, L: m_Value(V&: Cond0), R: m_APInt(Res&: Cond1))))
4234 return nullptr;
4235
4236 if (match(V: TrueVal, P: m_One())) {
4237 std::swap(a&: FalseVal, b&: TrueVal);
4238 Pred = CmpInst::getInversePredicate(pred: Pred);
4239 }
4240
4241 bool ShouldDropNoWrap;
4242
4243 if (!match(V: FalseVal, P: m_One()) ||
4244 !match(V: TrueVal,
4245 P: m_OneUse(SubPattern: m_Shl(L: m_One(), R: m_OneUse(SubPattern: m_Sub(L: m_SpecificInt(V: BitWidth),
4246 R: m_Value(V&: Ctlz)))))) ||
4247 !match(V: Ctlz, P: m_Ctlz(Op0: m_Value(V&: CtlzOp), Op1: m_Value())) ||
4248 !isSafeToRemoveBitCeilSelect(Pred, Cond0, Cond1, CtlzOp, BitWidth,
4249 ShouldDropNoWrap))
4250 return nullptr;
4251
4252 if (ShouldDropNoWrap) {
4253 cast<Instruction>(Val: CtlzOp)->setHasNoUnsignedWrap(false);
4254 cast<Instruction>(Val: CtlzOp)->setHasNoSignedWrap(false);
4255 }
4256
4257 // Build 1 << (-CTLZ & (BitWidth-1)). The negation likely corresponds to a
4258 // single hardware instruction as opposed to BitWidth - CTLZ, where BitWidth
4259 // is an integer constant. Masking with BitWidth-1 comes free on some
4260 // hardware as part of the shift instruction.
4261
4262 // Drop range attributes and re-infer them in the next iteration.
4263 cast<Instruction>(Val: Ctlz)->dropPoisonGeneratingAnnotations();
4264 IC.addToWorklist(I: cast<Instruction>(Val: Ctlz));
4265 Value *Neg = Builder.CreateNeg(V: Ctlz);
4266 Value *Masked =
4267 Builder.CreateAnd(LHS: Neg, RHS: ConstantInt::get(Ty: SelType, V: BitWidth - 1));
4268 return BinaryOperator::Create(Op: Instruction::Shl, S1: ConstantInt::get(Ty: SelType, V: 1),
4269 S2: Masked);
4270}
4271
4272// This function tries to fold the following operations:
4273// (x < y) ? -1 : zext(x != y)
4274// (x < y) ? -1 : zext(x > y)
4275// (x > y) ? 1 : sext(x != y)
4276// (x > y) ? 1 : sext(x < y)
4277// (x == y) ? 0 : (x > y ? 1 : -1)
4278// (x == y) ? 0 : (x < y ? -1 : 1)
4279// Special case: x == C ? 0 : (x > C - 1 ? 1 : -1)
4280// Special case: x == C ? 0 : (x < C + 1 ? -1 : 1)
4281// Into ucmp/scmp(x, y), where signedness is determined by the signedness
4282// of the comparison in the original sequence.
4283Instruction *InstCombinerImpl::foldSelectToCmp(SelectInst &SI) {
4284 Value *TV = SI.getTrueValue();
4285 Value *FV = SI.getFalseValue();
4286
4287 CmpPredicate Pred;
4288 Value *LHS, *RHS;
4289 if (!match(V: SI.getCondition(), P: m_ICmp(Pred, L: m_Value(V&: LHS), R: m_Value(V&: RHS))))
4290 return nullptr;
4291
4292 if (!LHS->getType()->isIntOrIntVectorTy())
4293 return nullptr;
4294
4295 // If there is no -1, 0 or 1 at TV, then invert the select statement and try
4296 // to canonicalize to one of the forms above
4297 if (!isa<Constant>(Val: TV)) {
4298 if (!isa<Constant>(Val: FV))
4299 return nullptr;
4300 Pred = ICmpInst::getInverseCmpPredicate(Pred);
4301 std::swap(a&: TV, b&: FV);
4302 }
4303
4304 if (ICmpInst::isNonStrictPredicate(predicate: Pred)) {
4305 if (Constant *C = dyn_cast<Constant>(Val: RHS)) {
4306 auto FlippedPredAndConst =
4307 getFlippedStrictnessPredicateAndConstant(Pred, C);
4308 if (!FlippedPredAndConst)
4309 return nullptr;
4310 Pred = FlippedPredAndConst->first;
4311 RHS = FlippedPredAndConst->second;
4312 } else {
4313 return nullptr;
4314 }
4315 }
4316
4317 // Try to swap operands and the predicate. We need to be careful when doing
4318 // so because two of the patterns have opposite predicates, so use the
4319 // constant inside select to determine if swapping operands would be
4320 // beneficial to us.
4321 if ((ICmpInst::isGT(P: Pred) && match(V: TV, P: m_AllOnes())) ||
4322 (ICmpInst::isLT(P: Pred) && match(V: TV, P: m_One()))) {
4323 Pred = ICmpInst::getSwappedPredicate(pred: Pred);
4324 std::swap(a&: LHS, b&: RHS);
4325 }
4326 bool IsSigned = ICmpInst::isSigned(Pred);
4327
4328 bool Replace = false;
4329 CmpPredicate ExtendedCmpPredicate;
4330 // (x < y) ? -1 : zext(x != y)
4331 // (x < y) ? -1 : zext(x > y)
4332 if (ICmpInst::isLT(P: Pred) && match(V: TV, P: m_AllOnes()) &&
4333 match(V: FV, P: m_ZExt(Op: m_c_ICmp(Pred&: ExtendedCmpPredicate, L: m_Specific(V: LHS),
4334 R: m_Specific(V: RHS)))) &&
4335 (ExtendedCmpPredicate == ICmpInst::ICMP_NE ||
4336 ICmpInst::getSwappedPredicate(pred: ExtendedCmpPredicate) == Pred))
4337 Replace = true;
4338
4339 // (x > y) ? 1 : sext(x != y)
4340 // (x > y) ? 1 : sext(x < y)
4341 if (ICmpInst::isGT(P: Pred) && match(V: TV, P: m_One()) &&
4342 match(V: FV, P: m_SExt(Op: m_c_ICmp(Pred&: ExtendedCmpPredicate, L: m_Specific(V: LHS),
4343 R: m_Specific(V: RHS)))) &&
4344 (ExtendedCmpPredicate == ICmpInst::ICMP_NE ||
4345 ICmpInst::getSwappedPredicate(pred: ExtendedCmpPredicate) == Pred))
4346 Replace = true;
4347
4348 // (x == y) ? 0 : (x > y ? 1 : -1)
4349 CmpPredicate FalseBranchSelectPredicate;
4350 const APInt *InnerTV, *InnerFV;
4351 if (Pred == ICmpInst::ICMP_EQ && match(V: TV, P: m_Zero()) &&
4352 match(V: FV, P: m_Select(C: m_c_ICmp(Pred&: FalseBranchSelectPredicate, L: m_Specific(V: LHS),
4353 R: m_Specific(V: RHS)),
4354 L: m_APInt(Res&: InnerTV), R: m_APInt(Res&: InnerFV)))) {
4355 if (!ICmpInst::isGT(P: FalseBranchSelectPredicate)) {
4356 FalseBranchSelectPredicate =
4357 ICmpInst::getSwappedPredicate(pred: FalseBranchSelectPredicate);
4358 std::swap(a&: LHS, b&: RHS);
4359 }
4360
4361 if (!InnerTV->isOne()) {
4362 std::swap(a&: InnerTV, b&: InnerFV);
4363 std::swap(a&: LHS, b&: RHS);
4364 }
4365
4366 if (ICmpInst::isGT(P: FalseBranchSelectPredicate) && InnerTV->isOne() &&
4367 InnerFV->isAllOnes()) {
4368 IsSigned = ICmpInst::isSigned(Pred: FalseBranchSelectPredicate);
4369 Replace = true;
4370 }
4371 }
4372
4373 // Special cases with constants: x == C ? 0 : (x > C-1 ? 1 : -1)
4374 if (Pred == ICmpInst::ICMP_EQ && match(V: TV, P: m_Zero())) {
4375 const APInt *C;
4376 if (match(V: RHS, P: m_APInt(Res&: C))) {
4377 CmpPredicate InnerPred;
4378 Value *InnerRHS;
4379 const APInt *InnerTV, *InnerFV;
4380 if (match(V: FV,
4381 P: m_Select(C: m_ICmp(Pred&: InnerPred, L: m_Specific(V: LHS), R: m_Value(V&: InnerRHS)),
4382 L: m_APInt(Res&: InnerTV), R: m_APInt(Res&: InnerFV)))) {
4383
4384 // x == C ? 0 : (x > C-1 ? 1 : -1)
4385 if (ICmpInst::isGT(P: InnerPred) && InnerTV->isOne() &&
4386 InnerFV->isAllOnes()) {
4387 IsSigned = ICmpInst::isSigned(Pred: InnerPred);
4388 bool CanSubOne = IsSigned ? !C->isMinSignedValue() : !C->isMinValue();
4389 if (CanSubOne) {
4390 APInt Cminus1 = *C - 1;
4391 if (match(V: InnerRHS, P: m_SpecificInt(V: Cminus1)))
4392 Replace = true;
4393 }
4394 }
4395
4396 // x == C ? 0 : (x < C+1 ? -1 : 1)
4397 if (ICmpInst::isLT(P: InnerPred) && InnerTV->isAllOnes() &&
4398 InnerFV->isOne()) {
4399 IsSigned = ICmpInst::isSigned(Pred: InnerPred);
4400 bool CanAddOne = IsSigned ? !C->isMaxSignedValue() : !C->isMaxValue();
4401 if (CanAddOne) {
4402 APInt Cplus1 = *C + 1;
4403 if (match(V: InnerRHS, P: m_SpecificInt(V: Cplus1)))
4404 Replace = true;
4405 }
4406 }
4407 }
4408 }
4409 }
4410
4411 Intrinsic::ID IID = IsSigned ? Intrinsic::scmp : Intrinsic::ucmp;
4412 if (Replace)
4413 return replaceInstUsesWith(
4414 I&: SI, V: Builder.CreateIntrinsic(RetTy: SI.getType(), ID: IID, Args: {LHS, RHS}));
4415 return nullptr;
4416}
4417
4418bool InstCombinerImpl::fmulByZeroIsZero(Value *MulVal, FastMathFlags FMF,
4419 const Instruction *CtxI) const {
4420 KnownFPClass Known =
4421 computeKnownFPClass(V: MulVal, FMF, InterestedClasses: fcNegative, SQ: SQ.getWithInstruction(I: CtxI));
4422
4423 return Known.isKnownNeverNaN() && Known.isKnownNeverInfinity() &&
4424 (FMF.noSignedZeros() || Known.signBitIsZeroOrNaN());
4425}
4426
4427static bool matchFMulByZeroIfResultEqZero(InstCombinerImpl &IC, Value *Cmp0,
4428 Value *Cmp1, Value *TrueVal,
4429 Value *FalseVal, Instruction &CtxI,
4430 bool SelectIsNSZ) {
4431 Value *MulRHS;
4432 if (match(V: Cmp1, P: m_PosZeroFP()) &&
4433 match(V: TrueVal, P: m_c_FMul(L: m_Specific(V: Cmp0), R: m_Value(V&: MulRHS)))) {
4434 FastMathFlags FMF = cast<FPMathOperator>(Val: TrueVal)->getFastMathFlags();
4435 // nsz must be on the select, it must be ignored on the multiply. We
4436 // need nnan and ninf on the multiply for the other value.
4437 FMF.setNoSignedZeros(SelectIsNSZ);
4438 return IC.fmulByZeroIsZero(MulVal: MulRHS, FMF, CtxI: &CtxI);
4439 }
4440
4441 return false;
4442}
4443
4444/// Check whether the KnownBits of a select arm may be affected by the
4445/// select condition.
4446static bool hasAffectedValue(Value *V, SmallPtrSetImpl<Value *> &Affected,
4447 unsigned Depth) {
4448 if (Depth == MaxAnalysisRecursionDepth)
4449 return false;
4450
4451 // Ignore the case where the select arm itself is affected. These cases
4452 // are handled more efficiently by other optimizations.
4453 if (Depth != 0 && Affected.contains(Ptr: V))
4454 return true;
4455
4456 if (auto *I = dyn_cast<Instruction>(Val: V)) {
4457 if (isa<PHINode>(Val: I)) {
4458 if (Depth == MaxAnalysisRecursionDepth - 1)
4459 return false;
4460 Depth = MaxAnalysisRecursionDepth - 2;
4461 }
4462 return any_of(Range: I->operands(), P: [&](Value *Op) {
4463 return Op->getType()->isIntOrIntVectorTy() &&
4464 hasAffectedValue(V: Op, Affected, Depth: Depth + 1);
4465 });
4466 }
4467
4468 return false;
4469}
4470
4471// This transformation enables the possibility of transforming fcmp + sel into
4472// a fmaxnum/fminnum intrinsic.
4473static Value *foldSelectIntoAddConstant(SelectInst &SI,
4474 InstCombiner::BuilderTy &Builder) {
4475 // Do this transformation only when select instruction gives NaN and NSZ
4476 // guarantee.
4477 auto *SIFOp = dyn_cast<FPMathOperator>(Val: &SI);
4478 if (!SIFOp || !SIFOp->hasNoSignedZeros() || !SIFOp->hasNoNaNs())
4479 return nullptr;
4480
4481 auto TryFoldIntoAddConstant =
4482 [&Builder, &SI](CmpInst::Predicate Pred, Value *X, Value *Z,
4483 Instruction *FAdd, Constant *C, bool Swapped) -> Value * {
4484 // Only these relational predicates can be transformed into maxnum/minnum
4485 // intrinsic.
4486 if (!CmpInst::isRelational(P: Pred) || !match(V: Z, P: m_AnyZeroFP()))
4487 return nullptr;
4488
4489 if (!match(V: FAdd, P: m_FAdd(L: m_Specific(V: X), R: m_Specific(V: C))))
4490 return nullptr;
4491
4492 Value *NewSelect = Builder.CreateSelect(C: SI.getCondition(), True: Swapped ? Z : X,
4493 False: Swapped ? X : Z, Name: "", MDFrom: &SI);
4494 NewSelect->takeName(V: &SI);
4495
4496 Value *NewFAdd = Builder.CreateFAdd(L: NewSelect, R: C);
4497 NewFAdd->takeName(V: FAdd);
4498
4499 // Propagate FastMath flags
4500 FastMathFlags SelectFMF = SI.getFastMathFlags();
4501 FastMathFlags FAddFMF = FAdd->getFastMathFlags();
4502 FastMathFlags NewFMF = FastMathFlags::intersectRewrite(LHS: SelectFMF, RHS: FAddFMF) |
4503 FastMathFlags::unionValue(LHS: SelectFMF, RHS: FAddFMF);
4504 cast<Instruction>(Val: NewFAdd)->setFastMathFlags(NewFMF);
4505 cast<Instruction>(Val: NewSelect)->setFastMathFlags(NewFMF);
4506
4507 return NewFAdd;
4508 };
4509
4510 // select((fcmp Pred, X, 0), (fadd X, C), C)
4511 // => fadd((select (fcmp Pred, X, 0), X, 0), C)
4512 //
4513 // Pred := OGT, OGE, OLT, OLE, UGT, UGE, ULT, and ULE
4514 Instruction *FAdd;
4515 Constant *C;
4516 Value *X, *Z;
4517 CmpPredicate Pred;
4518
4519 // Note: OneUse check for `Cmp` is necessary because it makes sure that other
4520 // InstCombine folds don't undo this transformation and cause an infinite
4521 // loop. Furthermore, it could also increase the operation count.
4522 if (match(V: &SI, P: m_Select(C: m_OneUse(SubPattern: m_FCmp(Pred, L: m_Value(V&: X), R: m_Value(V&: Z))),
4523 L: m_OneUse(SubPattern: m_Instruction(I&: FAdd)), R: m_Constant(C))))
4524 return TryFoldIntoAddConstant(Pred, X, Z, FAdd, C, /*Swapped=*/false);
4525
4526 if (match(V: &SI, P: m_Select(C: m_OneUse(SubPattern: m_FCmp(Pred, L: m_Value(V&: X), R: m_Value(V&: Z))),
4527 L: m_Constant(C), R: m_OneUse(SubPattern: m_Instruction(I&: FAdd)))))
4528 return TryFoldIntoAddConstant(Pred, X, Z, FAdd, C, /*Swapped=*/true);
4529
4530 return nullptr;
4531}
4532
4533static Value *foldSelectBitTest(SelectInst &Sel, Value *CondVal, Value *TrueVal,
4534 Value *FalseVal,
4535 InstCombiner::BuilderTy &Builder,
4536 const SimplifyQuery &SQ) {
4537 // If this is a vector select, we need a vector compare.
4538 Type *SelType = Sel.getType();
4539 if (SelType->isVectorTy() != CondVal->getType()->isVectorTy())
4540 return nullptr;
4541
4542 Value *V;
4543 APInt AndMask;
4544 bool CreateAnd = false;
4545 CmpPredicate Pred;
4546 Value *CmpLHS, *CmpRHS;
4547
4548 if (match(V: CondVal, P: m_ICmp(Pred, L: m_Value(V&: CmpLHS), R: m_Value(V&: CmpRHS)))) {
4549 if (ICmpInst::isEquality(P: Pred)) {
4550 if (!match(V: CmpRHS, P: m_Zero()))
4551 return nullptr;
4552
4553 V = CmpLHS;
4554 const APInt *AndRHS;
4555 if (!match(V: CmpLHS, P: m_And(L: m_Value(), R: m_Power2(V&: AndRHS))))
4556 return nullptr;
4557
4558 AndMask = *AndRHS;
4559 } else if (auto Res = decomposeBitTestICmp(LHS: CmpLHS, RHS: CmpRHS, Pred)) {
4560 assert(ICmpInst::isEquality(Res->Pred) && "Not equality test?");
4561 AndMask = Res->Mask;
4562 V = Res->X;
4563 KnownBits Known = computeKnownBits(V, Q: SQ.getWithInstruction(I: &Sel));
4564 AndMask &= Known.getMaxValue();
4565 if (!AndMask.isPowerOf2())
4566 return nullptr;
4567
4568 Pred = Res->Pred;
4569 CreateAnd = true;
4570 } else {
4571 return nullptr;
4572 }
4573 } else if (auto *Trunc = dyn_cast<TruncInst>(Val: CondVal)) {
4574 V = Trunc->getOperand(i_nocapture: 0);
4575 AndMask = APInt(V->getType()->getScalarSizeInBits(), 1);
4576 Pred = ICmpInst::ICMP_NE;
4577 CreateAnd = !Trunc->hasNoUnsignedWrap();
4578 } else {
4579 return nullptr;
4580 }
4581
4582 if (Pred == ICmpInst::ICMP_NE)
4583 std::swap(a&: TrueVal, b&: FalseVal);
4584
4585 if (Value *X = foldSelectICmpAnd(Sel, CondVal, TrueVal, FalseVal, V, AndMask,
4586 CreateAnd, Builder))
4587 return X;
4588
4589 if (Value *X = foldSelectICmpAndBinOp(CondVal, TrueVal, FalseVal, V, AndMask,
4590 CreateAnd, Builder))
4591 return X;
4592
4593 return nullptr;
4594}
4595
4596/// This function makes the following folds:
4597/// select C, (sub 0, X), (xor X, -1)
4598/// -> sub (sext !C), X
4599/// select C, (xor X, -1), (sub 0, X)
4600/// -> sub (sext C), X
4601static Instruction *foldSelectNegNot(SelectInst &SI,
4602 InstCombiner::BuilderTy &Builder) {
4603 auto *CondVal = SI.getCondition();
4604 auto *TrueVal = SI.getTrueValue();
4605 auto *FalseVal = SI.getFalseValue();
4606 auto *SelTy = SI.getType();
4607
4608 if (!SelTy->isIntOrIntVectorTy() || SelTy->isIntOrIntVectorTy(BitWidth: 1))
4609 return nullptr;
4610
4611 if (CondVal->getType()->isVectorTy() != SelTy->isVectorTy())
4612 return nullptr;
4613
4614 auto matchNegNot = [&](Value *Neg, Value *Not, Value *&X) -> bool {
4615 return match(V: Neg, P: m_OneUse(SubPattern: m_Neg(V: m_Value(V&: X)))) &&
4616 match(V: Not, P: m_OneUse(SubPattern: m_Not(V: m_Specific(V: X))));
4617 };
4618
4619 Value *X;
4620 Value *Mask;
4621
4622 // select C, (sub 0, X), (xor X, -1) -> sub (sext !C), X
4623 if (matchNegNot(TrueVal, FalseVal, X)) {
4624 Value *NotCond = Builder.CreateNot(V: CondVal, Name: "not." + CondVal->getName());
4625 Mask = Builder.CreateSExt(V: NotCond, DestTy: SelTy);
4626 return BinaryOperator::CreateSub(V1: Mask, V2: X);
4627 }
4628
4629 // select C, (xor X, -1), (sub 0, X) -> sub (sext C), X
4630 if (matchNegNot(FalseVal, TrueVal, X)) {
4631 Mask = Builder.CreateSExt(V: CondVal, DestTy: SelTy);
4632 return BinaryOperator::CreateSub(V1: Mask, V2: X);
4633 }
4634
4635 return nullptr;
4636}
4637
4638/// Fold select (A & Shift == 0 | B & Shift == 0), 0, Shift -> Shift & A & B
4639/// where Shift is known to be a power of two.
4640static Instruction *foldSelectAndOrPowerOfTwo(SelectInst &SI,
4641 InstCombiner::BuilderTy &Builder,
4642 const SimplifyQuery &SQ) {
4643 Value *Cond = SI.getCondition();
4644
4645 if (!Cond->hasOneUse())
4646 return nullptr;
4647
4648 Value *TrueVal = SI.getTrueValue();
4649 Value *FalseVal = SI.getFalseValue();
4650
4651 Value *A, *B, *Shift;
4652
4653 bool Case1 =
4654 match(V: TrueVal, P: m_Zero()) && match(V: FalseVal, P: m_Value(V&: Shift)) &&
4655 match(V: Cond, P: m_Or(L: m_SpecificICmp(MatchPred: ICmpInst::ICMP_EQ,
4656 L: m_c_And(L: m_Specific(V: Shift), R: m_Value(V&: A)),
4657 R: m_Zero()),
4658 R: m_SpecificICmp(MatchPred: ICmpInst::ICMP_EQ,
4659 L: m_c_And(L: m_Specific(V: Shift), R: m_Value(V&: B)),
4660 R: m_Zero())));
4661
4662 bool Case2 =
4663 match(V: FalseVal, P: m_Zero()) && match(V: TrueVal, P: m_Value(V&: Shift)) &&
4664 match(V: Cond, P: m_And(L: m_SpecificICmp(MatchPred: ICmpInst::ICMP_NE,
4665 L: m_c_And(L: m_Specific(V: Shift), R: m_Value(V&: A)),
4666 R: m_Zero()),
4667 R: m_SpecificICmp(MatchPred: ICmpInst::ICMP_NE,
4668 L: m_c_And(L: m_Specific(V: Shift), R: m_Value(V&: B)),
4669 R: m_Zero())));
4670
4671 if ((Case1 || Case2) && isKnownToBeAPowerOfTwo(V: Shift, /*OrZero=*/true,
4672 Q: SQ.getWithInstruction(I: &SI))) {
4673 Value *And1 = Builder.CreateAnd(LHS: Shift, RHS: A);
4674 return BinaryOperator::CreateAnd(V1: And1, V2: B);
4675 }
4676
4677 return nullptr;
4678}
4679
4680// Return true if no use can observe the sign of zero of the select result,
4681// looking through phis, selects and the loop back edge to the select itself.
4682static bool isSelectZeroSignInsignificant(SelectInst &SI) {
4683 // Bound the number of uses to look through to keep the compile time in
4684 // check.
4685 constexpr unsigned MaxUsesToLookThrough = 16;
4686 unsigned NumUses = 0;
4687 SmallPtrSet<Instruction *, 4> Visited;
4688 SmallVector<Instruction *> Worklist(1, &SI);
4689 while (!Worklist.empty()) {
4690 for (Use &U : Worklist.pop_back_val()->uses()) {
4691 if (++NumUses > MaxUsesToLookThrough)
4692 return false;
4693 auto *User = cast<Instruction>(Val: U.getUser());
4694 if (User == &SI)
4695 continue;
4696 if (canIgnoreSignBitOfZero(U))
4697 continue;
4698 if (isa<PHINode, SelectInst>(Val: User)) {
4699 if (Visited.insert(Ptr: User).second)
4700 Worklist.push_back(Elt: User);
4701 continue;
4702 }
4703 return false;
4704 }
4705 }
4706 return true;
4707}
4708
4709Instruction *InstCombinerImpl::visitSelectInst(SelectInst &SI) {
4710 Value *CondVal = SI.getCondition();
4711 Value *TrueVal = SI.getTrueValue();
4712 Value *FalseVal = SI.getFalseValue();
4713 Type *SelType = SI.getType();
4714
4715 FastMathFlags FMF;
4716 if (auto *FPMO = dyn_cast_if_present<FPMathOperator>(Val: &SI))
4717 FMF = FPMO->getFastMathFlags();
4718
4719 if (Value *V = simplifySelectInst(Cond: CondVal, TrueVal, FalseVal, FMF,
4720 Q: SQ.getWithInstruction(I: &SI)))
4721 return replaceInstUsesWith(I&: SI, V);
4722
4723 if (Instruction *I = canonicalizeSelectToShuffle(SI))
4724 return I;
4725
4726 if (Instruction *I = canonicalizeScalarSelectOfVecs(Sel&: SI, IC&: *this))
4727 return I;
4728
4729 // Fold: select (icmp ult X, 2), X, ctpop(X) --> ctpop(X)
4730 // ctpop(0)==0 and ctpop(1)==1, so the guard is always redundant.
4731 if (match(V: FalseVal, P: m_Ctpop(Op0: m_Specific(V: TrueVal))) &&
4732 match(V: CondVal, P: m_SpecificICmp(MatchPred: ICmpInst::ICMP_ULT, L: m_Specific(V: TrueVal),
4733 R: m_SpecificInt(V: 2)))) {
4734 cast<Instruction>(Val: FalseVal)->dropPoisonGeneratingAnnotations();
4735 addToWorklist(I: cast<Instruction>(Val: FalseVal));
4736 return replaceInstUsesWith(I&: SI, V: FalseVal);
4737 }
4738
4739 // If the type of select is not an integer type or if the condition and
4740 // the selection type are not both scalar nor both vector types, there is no
4741 // point in attempting to match these patterns.
4742 Type *CondType = CondVal->getType();
4743 if (!isa<Constant>(Val: CondVal) && SelType->isIntOrIntVectorTy() &&
4744 CondType->isVectorTy() == SelType->isVectorTy()) {
4745 if (Value *S = simplifyWithOpReplaced(V: TrueVal, Op: CondVal,
4746 RepOp: ConstantInt::getTrue(Ty: CondType), Q: SQ,
4747 /* AllowRefinement */ true))
4748 return replaceOperand(I&: SI, OpNum: 1, V: S);
4749
4750 if (Value *S = simplifyWithOpReplaced(V: FalseVal, Op: CondVal,
4751 RepOp: ConstantInt::getFalse(Ty: CondType), Q: SQ,
4752 /* AllowRefinement */ true))
4753 return replaceOperand(I&: SI, OpNum: 2, V: S);
4754
4755 if (replaceInInstruction(V: TrueVal, Old: CondVal,
4756 New: ConstantInt::getTrue(Ty: CondType)) ||
4757 replaceInInstruction(V: FalseVal, Old: CondVal,
4758 New: ConstantInt::getFalse(Ty: CondType)))
4759 return &SI;
4760 }
4761
4762 if (Instruction *R = foldSelectOfBools(SI))
4763 return R;
4764
4765 // Selecting between two integer or vector splat integer constants?
4766 //
4767 // Note that we don't handle a scalar select of vectors:
4768 // select i1 %c, <2 x i8> <1, 1>, <2 x i8> <0, 0>
4769 // because that may need 3 instructions to splat the condition value:
4770 // extend, insertelement, shufflevector.
4771 //
4772 // Do not handle i1 TrueVal and FalseVal otherwise would result in
4773 // zext/sext i1 to i1.
4774 if (SelType->isIntOrIntVectorTy() && !SelType->isIntOrIntVectorTy(BitWidth: 1) &&
4775 CondVal->getType()->isVectorTy() == SelType->isVectorTy()) {
4776 // select C, 1, 0 -> zext C to int
4777 if (match(V: TrueVal, P: m_One()) && match(V: FalseVal, P: m_Zero()))
4778 return new ZExtInst(CondVal, SelType);
4779
4780 // select C, -1, 0 -> sext C to int
4781 if (match(V: TrueVal, P: m_AllOnes()) && match(V: FalseVal, P: m_Zero()))
4782 return new SExtInst(CondVal, SelType);
4783
4784 // select C, 0, 1 -> zext !C to int
4785 if (match(V: TrueVal, P: m_Zero()) && match(V: FalseVal, P: m_One())) {
4786 Value *NotCond = Builder.CreateNot(V: CondVal, Name: "not." + CondVal->getName());
4787 return new ZExtInst(NotCond, SelType);
4788 }
4789
4790 // select C, 0, -1 -> sext !C to int
4791 if (match(V: TrueVal, P: m_Zero()) && match(V: FalseVal, P: m_AllOnes())) {
4792 Value *NotCond = Builder.CreateNot(V: CondVal, Name: "not." + CondVal->getName());
4793 return new SExtInst(NotCond, SelType);
4794 }
4795 }
4796
4797 if (Instruction *I = foldSelectNegNot(SI, Builder))
4798 return I;
4799
4800 if (Instruction *I = foldSelectAndOrPowerOfTwo(SI, Builder, SQ))
4801 return I;
4802
4803 auto *SIFPOp = dyn_cast<FPMathOperator>(Val: &SI);
4804
4805 if (auto *FCmp = dyn_cast<FCmpInst>(Val: CondVal)) {
4806 FCmpInst::Predicate Pred = FCmp->getPredicate();
4807 Value *Cmp0 = FCmp->getOperand(i_nocapture: 0), *Cmp1 = FCmp->getOperand(i_nocapture: 1);
4808 // Are we selecting a value based on a comparison of the two values?
4809 if ((Cmp0 == TrueVal && Cmp1 == FalseVal) ||
4810 (Cmp0 == FalseVal && Cmp1 == TrueVal)) {
4811 // Canonicalize to use ordered comparisons by swapping the select
4812 // operands.
4813 //
4814 // e.g.
4815 // (X ugt Y) ? X : Y -> (X ole Y) ? Y : X
4816 if (FCmp->hasOneUse() && FCmpInst::isUnordered(predicate: Pred)) {
4817 FCmpInst::Predicate InvPred = FCmp->getInversePredicate();
4818 Value *NewCond = Builder.CreateFCmpFMF(P: InvPred, LHS: Cmp0, RHS: Cmp1, FMFSource: FCmp,
4819 Name: FCmp->getName() + ".inv");
4820 // Propagate ninf/nnan from fcmp to select.
4821 FastMathFlags FMF = SI.getFastMathFlags();
4822 if (FCmp->hasNoNaNs())
4823 FMF.setNoNaNs(true);
4824 if (FCmp->hasNoInfs())
4825 FMF.setNoInfs(true);
4826 Value *NewSel = Builder.CreateSelectFMF(
4827 C: NewCond, True: FalseVal, False: TrueVal, FMFSource: FMF, Name: "",
4828 MDFrom: ProfcheckDisableMetadataFixes ? nullptr : &SI);
4829 if (auto *NewSI = dyn_cast<SelectInst>(Val: NewSel))
4830 NewSI->swapProfMetadata();
4831 return replaceInstUsesWith(I&: SI, V: NewSel);
4832 }
4833 }
4834
4835 if (SIFPOp) {
4836 // Fold out scale-if-equals-zero pattern.
4837 //
4838 // This pattern appears in code with denormal range checks after it's
4839 // assumed denormals are treated as zero. This drops a canonicalization.
4840
4841 // TODO: Could relax the signed zero logic. We just need to know the sign
4842 // of the result matches (fmul x, y has the same sign as x).
4843 //
4844 // TODO: Handle always-canonicalizing variant that selects some value or 1
4845 // scaling factor in the fmul visitor.
4846
4847 // TODO: Handle ldexp too
4848
4849 Value *MatchCmp0 = nullptr;
4850 Value *MatchCmp1 = nullptr;
4851
4852 // (select (fcmp [ou]eq x, 0.0), (fmul x, K), x => x
4853 // (select (fcmp [ou]ne x, 0.0), x, (fmul x, K) => x
4854 if (Pred == CmpInst::FCMP_OEQ || Pred == CmpInst::FCMP_UEQ) {
4855 MatchCmp0 = FalseVal;
4856 MatchCmp1 = TrueVal;
4857 } else if (Pred == CmpInst::FCMP_ONE || Pred == CmpInst::FCMP_UNE) {
4858 MatchCmp0 = TrueVal;
4859 MatchCmp1 = FalseVal;
4860 }
4861
4862 if (Cmp0 == MatchCmp0 &&
4863 matchFMulByZeroIfResultEqZero(IC&: *this, Cmp0, Cmp1, TrueVal: MatchCmp1, FalseVal: MatchCmp0,
4864 CtxI&: SI, SelectIsNSZ: SIFPOp->hasNoSignedZeros()))
4865 return replaceInstUsesWith(I&: SI, V: Cmp0);
4866
4867 Type *EltTy = SelType->getScalarType();
4868
4869 // TODO: Generalize to any ordered / unordered compare.
4870 if ((Pred == CmpInst::FCMP_ORD || Pred == CmpInst::FCMP_UNO) &&
4871 match(V: Cmp1, P: m_PosZeroFP()) && EltTy->isIEEELikeFPTy()) {
4872 // Fold out only-canonicalize-non-nans pattern. This implements a
4873 // wrapper around llvm.canonicalize which is not required to quiet
4874 // signaling nans or preserve nan payload bits.
4875 //
4876 // %hard.canonical = call @llvm.canonicalize(%x)
4877 // %soft.canonical = fdiv 1.0, %x
4878 // %ord = fcmp ord %x, 0.0
4879 // %x.canon = select i1 %ord, %hard.canonical, %soft.canonical
4880 //
4881 // With known IEEE handling:
4882 // => %x
4883 //
4884 // With other denormal behaviors:
4885 // => llvm.canonicalize(%x)
4886 //
4887 // Note the fdiv could be any value preserving, potentially
4888 // canonicalizing floating-point operation such as fmul by 1.0. However,
4889 // since in the llvm model canonicalization is not mandatory, the fmul
4890 // would have been dropped by the time we reached here. The trick here
4891 // is to use a reciprocal fdiv. It's not a droppable no-op, as it could
4892 // return an infinity if %x were sufficiently small, but in this pattern
4893 // we're only using the output for nan values.
4894
4895 if (Pred == CmpInst::FCMP_ORD) {
4896 MatchCmp0 = TrueVal;
4897 MatchCmp1 = FalseVal;
4898 } else {
4899 MatchCmp0 = FalseVal;
4900 MatchCmp1 = TrueVal;
4901 }
4902
4903 bool RcpIfNan = match(V: MatchCmp1, P: m_FDiv(L: m_FPOne(), R: m_Specific(V: Cmp0)));
4904 bool CanonicalizeIfNotNan =
4905 match(V: MatchCmp0, P: m_FCanonicalize(Op0: m_Specific(V: Cmp0)));
4906
4907 if (RcpIfNan || CanonicalizeIfNotNan) {
4908 const fltSemantics &FPSem = EltTy->getFltSemantics();
4909 DenormalMode Mode = F.getDenormalMode(FPType: FPSem);
4910
4911 if (RcpIfNan) {
4912 if (Mode == DenormalMode::getIEEE()) {
4913 // Special case for the other select operand. Otherwise, we may
4914 // need to insert freeze on Cmp0 in the compare and select.
4915 if (CanonicalizeIfNotNan)
4916 return replaceInstUsesWith(I&: SI, V: Cmp0);
4917
4918 if (isGuaranteedNotToBeUndef(V: Cmp0, AC: &AC, CtxI: &SI, DT: &DT)) {
4919 // select (fcmp ord x, 0), y, (fdiv 1, x)
4920 // => select (fcmp ord x, 0), y, x
4921 //
4922 // select (fcmp uno x, 0), (fdiv 1, x), y
4923 // => select (fcmp uno x, 0), x, y
4924 replaceOperand(I&: SI, OpNum: Pred == CmpInst::FCMP_ORD ? 2 : 1, V: Cmp0);
4925 return &SI;
4926 }
4927
4928 auto *FrCmp0 = InsertNewInstBefore(
4929 New: new FreezeInst(Cmp0, Cmp0->getName() + ".fr"),
4930 Old: FCmp->getIterator());
4931
4932 replaceOperand(I&: *FCmp, OpNum: 0, V: FrCmp0);
4933 return replaceOperand(I&: SI, OpNum: Pred == CmpInst::FCMP_ORD ? 2 : 1,
4934 V: FrCmp0);
4935 }
4936 }
4937
4938 if (CanonicalizeIfNotNan) {
4939 // IEEE handling does not have non-canonical values, so the
4940 // canonicalize can be dropped for direct replacement without
4941 // looking for the intermediate maybe-canonicalizing operation.
4942 if (Mode == DenormalMode::getIEEE()) {
4943 // select (fcmp ord x, 0), canonicalize(x), y
4944 // => select (fcmp ord x, 0), x, y
4945
4946 replaceOperand(I&: SI, OpNum: Pred == CmpInst::FCMP_ORD ? 1 : 2, V: Cmp0);
4947 return &SI;
4948 }
4949
4950 // If denormals may be flushed, we need to retain the canonicalize
4951 // call. This introduces a canonicalization on the nan path, which
4952 // we are not free to do as that could change the sign bit or
4953 // payload bits. We can only do this if there were a no-op like
4954 // floating-point instruction which may have changed the nan bits
4955 // anyway.
4956
4957 // Leave the dynamic mode case alone. This would introduce new
4958 // constraints if the mode may be refined later.
4959 if (RcpIfNan && (Mode.inputsAreZero() || Mode.outputsAreZero()))
4960 return replaceInstUsesWith(I&: SI, V: MatchCmp0);
4961 assert(RcpIfNan || Mode != DenormalMode::getIEEE());
4962 }
4963 }
4964 }
4965 }
4966 }
4967
4968 if (SIFPOp) {
4969 // TODO: Try to forward-propagate FMF from select arms to the select.
4970
4971 auto *FCmp = dyn_cast<FCmpInst>(Val: CondVal);
4972
4973 // Canonicalize select of FP values where NaN and -0.0 are not valid as
4974 // minnum/maxnum intrinsics.
4975 //
4976 // Note that the `nnan` flag is propagated from the comparison, not from the
4977 // select. While it's technically possible to transform a `fcmp` + `select
4978 // nnan` to a `minnum`/`maxnum` call *without* an `nnan`, that would be a
4979 // pessimization in practice. Many targets can't map `minnum`/`maxnum` to a
4980 // single instruction, and if they cannot prove the absence of NaN, must
4981 // lower it to a routine or a libcall. There are additional reasons besides
4982 // performance to avoid introducing libcalls where none existed before
4983 // (https://github.com/llvm/llvm-project/issues/54554).
4984 //
4985 // As such, we want to ensure that the generated `minnum`/`maxnum` intrinsic
4986 // has the `nnan nsz` flags, which allow it to be lowered *back* to a
4987 // fcmp+select if that's the best way to express it on the target.
4988 if (FCmp && FCmp->hasNoNaNs() &&
4989 (SIFPOp->hasNoSignedZeros() || isSelectZeroSignInsignificant(SI))) {
4990 Value *X, *Y;
4991 if (match(V: &SI, P: m_OrdOrUnordFMax(L: m_Value(V&: X), R: m_Value(V&: Y)))) {
4992 Value *BinIntr =
4993 Builder.CreateBinaryIntrinsic(ID: Intrinsic::maxnum, LHS: X, RHS: Y, FMFSource: &SI);
4994 if (auto *BinIntrInst = dyn_cast<Instruction>(Val: BinIntr)) {
4995 // `ninf` must be propagated from the comparison too, rather than the
4996 // select: https://github.com/llvm/llvm-project/pull/136433
4997 BinIntrInst->setHasNoInfs(FCmp->hasNoInfs());
4998 // The `nsz` flag is a precondition, so let's ensure it's always added
4999 // to the min/max operation, even if it wasn't on the select. This
5000 // could happen if the select doesn't have `nsz`, but no use of the
5001 // result can observe the sign of zero.
5002 BinIntrInst->setHasNoSignedZeros(true);
5003 // As mentioned above, `nnan` is also a precondition, so we always set
5004 // the flag.
5005 BinIntrInst->setHasNoNaNs(true);
5006 }
5007 return replaceInstUsesWith(I&: SI, V: BinIntr);
5008 }
5009
5010 if (match(V: &SI, P: m_OrdOrUnordFMin(L: m_Value(V&: X), R: m_Value(V&: Y)))) {
5011 Value *BinIntr =
5012 Builder.CreateBinaryIntrinsic(ID: Intrinsic::minnum, LHS: X, RHS: Y, FMFSource: &SI);
5013 if (auto *BinIntrInst = dyn_cast<Instruction>(Val: BinIntr)) {
5014 BinIntrInst->setHasNoInfs(FCmp->hasNoInfs());
5015 BinIntrInst->setHasNoSignedZeros(true);
5016 BinIntrInst->setHasNoNaNs(true);
5017 }
5018 return replaceInstUsesWith(I&: SI, V: BinIntr);
5019 }
5020 }
5021 }
5022
5023 // Fold selecting to fabs.
5024 if (Instruction *Fabs = foldSelectWithFCmpToFabs(SI, IC&: *this))
5025 return Fabs;
5026
5027 if (Instruction *I = foldSelectOfOrderedFAbsCmpOfNaNScrubbedValue(SI, IC&: *this))
5028 return I;
5029
5030 // See if we are selecting two values based on a comparison of the two values.
5031 if (CmpInst *CI = dyn_cast<CmpInst>(Val: CondVal))
5032 if (Instruction *NewSel = foldSelectValueEquivalence(Sel&: SI, Cmp&: *CI))
5033 return NewSel;
5034
5035 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Val: CondVal))
5036 if (Instruction *Result = foldSelectInstWithICmp(SI, ICI))
5037 return Result;
5038
5039 if (Instruction *V =
5040 foldSelectICmpAndAnd(SelType, Cond: CondVal, TVal: TrueVal, FVal: FalseVal, Builder))
5041 return V;
5042
5043 if (Value *V = foldSelectBitTest(Sel&: SI, CondVal, TrueVal, FalseVal, Builder, SQ))
5044 return replaceInstUsesWith(I&: SI, V);
5045
5046 if (Instruction *Add = foldAddSubSelect(SI, Builder))
5047 return Add;
5048 if (Instruction *Add = foldOverflowingAddSubSelect(SI, Builder))
5049 return Add;
5050 if (Instruction *Or = foldSetClearBits(Sel&: SI, Builder))
5051 return Or;
5052 if (Instruction *Mul = foldSelectZeroOrFixedOp(SI, IC&: *this))
5053 return Mul;
5054
5055 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
5056 auto *TI = dyn_cast<Instruction>(Val: TrueVal);
5057 auto *FI = dyn_cast<Instruction>(Val: FalseVal);
5058 if (TI && FI && TI->getOpcode() == FI->getOpcode())
5059 if (Instruction *IV = foldSelectOpOp(SI, TI, FI))
5060 return IV;
5061
5062 if (Instruction *I = foldSelectIntrinsic(SI))
5063 return I;
5064
5065 if (Instruction *I = foldSelectExtConst(Sel&: SI))
5066 return I;
5067
5068 if (Instruction *I = foldSelectWithSRem(SI, IC&: *this, Builder))
5069 return I;
5070
5071 // Fold (select C, (gep Ptr, Idx), Ptr) -> (gep Ptr, (select C, Idx, 0))
5072 // Fold (select C, Ptr, (gep Ptr, Idx)) -> (gep Ptr, (select C, 0, Idx))
5073 auto SelectGepWithBase = [&](GetElementPtrInst *Gep, Value *Base,
5074 bool Swap) -> GetElementPtrInst * {
5075 Value *Ptr = Gep->getPointerOperand();
5076 if (Gep->getNumOperands() != 2 || Gep->getPointerOperand() != Base ||
5077 !Gep->hasOneUse())
5078 return nullptr;
5079 Value *Idx = Gep->getOperand(i_nocapture: 1);
5080 if (isa<VectorType>(Val: CondVal->getType()) && !isa<VectorType>(Val: Idx->getType()))
5081 return nullptr;
5082 Type *ElementType = Gep->getSourceElementType();
5083 Value *NewT = Idx;
5084 Value *NewF = Constant::getNullValue(Ty: Idx->getType());
5085 if (Swap)
5086 std::swap(a&: NewT, b&: NewF);
5087 Value *NewSI =
5088 Builder.CreateSelect(C: CondVal, True: NewT, False: NewF, Name: SI.getName() + ".idx", MDFrom: &SI);
5089 return GetElementPtrInst::Create(PointeeType: ElementType, Ptr, IdxList: NewSI,
5090 NW: Gep->getNoWrapFlags());
5091 };
5092 if (auto *TrueGep = dyn_cast<GetElementPtrInst>(Val: TrueVal))
5093 if (auto *NewGep = SelectGepWithBase(TrueGep, FalseVal, false))
5094 return NewGep;
5095 if (auto *FalseGep = dyn_cast<GetElementPtrInst>(Val: FalseVal))
5096 if (auto *NewGep = SelectGepWithBase(FalseGep, TrueVal, true))
5097 return NewGep;
5098
5099 // See if we can fold the select into one of our operands.
5100 if (SelType->isIntOrIntVectorTy() || SelType->isFPOrFPVectorTy()) {
5101 if (Instruction *FoldI = foldSelectIntoOp(SI, TrueVal, FalseVal))
5102 return FoldI;
5103
5104 Value *LHS, *RHS;
5105 Instruction::CastOps CastOp;
5106 SelectPatternResult SPR = matchSelectPattern(V: &SI, LHS, RHS, CastOp: &CastOp);
5107 auto SPF = SPR.Flavor;
5108 if (SPF) {
5109 Value *LHS2, *RHS2;
5110 if (SelectPatternFlavor SPF2 = matchSelectPattern(V: LHS, LHS&: LHS2, RHS&: RHS2).Flavor)
5111 if (Instruction *R = foldSPFofSPF(Inner: cast<Instruction>(Val: LHS), SPF1: SPF2, A: LHS2,
5112 B: RHS2, Outer&: SI, SPF2: SPF, C: RHS))
5113 return R;
5114 if (SelectPatternFlavor SPF2 = matchSelectPattern(V: RHS, LHS&: LHS2, RHS&: RHS2).Flavor)
5115 if (Instruction *R = foldSPFofSPF(Inner: cast<Instruction>(Val: RHS), SPF1: SPF2, A: LHS2,
5116 B: RHS2, Outer&: SI, SPF2: SPF, C: LHS))
5117 return R;
5118 }
5119
5120 if (SelectPatternResult::isMinOrMax(SPF)) {
5121 // Canonicalize so that
5122 // - type casts are outside select patterns.
5123 // - float clamp is transformed to min/max pattern
5124
5125 bool IsCastNeeded = LHS->getType() != SelType;
5126 Value *CmpLHS = cast<CmpInst>(Val: CondVal)->getOperand(i_nocapture: 0);
5127 Value *CmpRHS = cast<CmpInst>(Val: CondVal)->getOperand(i_nocapture: 1);
5128 if (IsCastNeeded ||
5129 (LHS->getType()->isFPOrFPVectorTy() &&
5130 ((CmpLHS != LHS && CmpLHS != RHS) ||
5131 (CmpRHS != LHS && CmpRHS != RHS)))) {
5132 CmpInst::Predicate MinMaxPred = getMinMaxPred(SPF, Ordered: SPR.Ordered);
5133
5134 Value *Cmp;
5135 if (CmpInst::isIntPredicate(P: MinMaxPred)) {
5136 dropPoisonGeneratingAnnotationsForSPFCanonicalization(Cond: CondVal, LHS,
5137 RHS);
5138 Cmp = Builder.CreateICmp(P: MinMaxPred, LHS, RHS);
5139 } else
5140 Cmp = Builder.CreateFCmpFMF(P: MinMaxPred, LHS, RHS,
5141 FMFSource: cast<Instruction>(Val: SI.getCondition()));
5142
5143 Value *NewSI = Builder.CreateSelect(C: Cmp, True: LHS, False: RHS, Name: SI.getName(), MDFrom: &SI);
5144 if (!IsCastNeeded)
5145 return replaceInstUsesWith(I&: SI, V: NewSI);
5146
5147 Value *NewCast = Builder.CreateCast(Op: CastOp, V: NewSI, DestTy: SelType);
5148 return replaceInstUsesWith(I&: SI, V: NewCast);
5149 }
5150 }
5151 }
5152
5153 // See if we can fold the select into a phi node if the condition is a select.
5154 if (auto *PN = dyn_cast<PHINode>(Val: SI.getCondition()))
5155 if (Instruction *NV = foldOpIntoPhi(I&: SI, PN))
5156 return NV;
5157
5158 if (SelectInst *TrueSI = dyn_cast<SelectInst>(Val: TrueVal)) {
5159 if (TrueSI->getCondition()->getType() == CondVal->getType()) {
5160 // Fold nested selects if the inner condition can be implied by the outer
5161 // condition.
5162 if (Value *V = simplifyNestedSelectsUsingImpliedCond(
5163 SI&: *TrueSI, CondVal, /*CondIsTrue=*/true, DL))
5164 return replaceOperand(I&: SI, OpNum: 1, V);
5165
5166 // We choose this as normal form to enable folding on the And and
5167 // shortening paths for the values (this helps getUnderlyingObjects() for
5168 // example).
5169 if (TrueSI->hasOneUse()) {
5170 Value *And = nullptr, *OtherVal = nullptr;
5171 // select(C0, select(C1, a, b), b) -> select(C0&&C1, a, b)
5172 if (TrueSI->getFalseValue() == FalseVal) {
5173 And = Builder.CreateLogicalAnd(Cond1: CondVal, Cond2: TrueSI->getCondition(), Name: "",
5174 MDFrom: &SI);
5175 OtherVal = TrueSI->getTrueValue();
5176 }
5177 // select(C0, select(C1, b, a), b) -> select(C0&&!C1, a, b)
5178 else if (TrueSI->getTrueValue() == FalseVal) {
5179 Value *InvertedCond = Builder.CreateNot(V: TrueSI->getCondition());
5180 And = Builder.CreateLogicalAnd(Cond1: CondVal, Cond2: InvertedCond, Name: "", MDFrom: &SI);
5181 OtherVal = TrueSI->getFalseValue();
5182 }
5183 if (And && OtherVal) {
5184 replaceOperand(I&: SI, OpNum: 0, V: And);
5185 replaceOperand(I&: SI, OpNum: 1, V: OtherVal);
5186 setExplicitlyUnknownBranchWeightsIfProfiled(I&: SI, DEBUG_TYPE);
5187 return &SI;
5188 }
5189 }
5190 }
5191 }
5192 if (SelectInst *FalseSI = dyn_cast<SelectInst>(Val: FalseVal)) {
5193 if (FalseSI->getCondition()->getType() == CondVal->getType()) {
5194 // Fold nested selects if the inner condition can be implied by the outer
5195 // condition.
5196 if (Value *V = simplifyNestedSelectsUsingImpliedCond(
5197 SI&: *FalseSI, CondVal, /*CondIsTrue=*/false, DL))
5198 return replaceOperand(I&: SI, OpNum: 2, V);
5199
5200 if (FalseSI->hasOneUse()) {
5201 Value *Or = nullptr, *OtherVal = nullptr;
5202 // select(C0, a, select(C1, a, b)) -> select(C0||C1, a, b)
5203 if (FalseSI->getTrueValue() == TrueVal) {
5204 Or = Builder.CreateLogicalOr(Cond1: CondVal, Cond2: FalseSI->getCondition(), Name: "",
5205 MDFrom: &SI);
5206 OtherVal = FalseSI->getFalseValue();
5207 }
5208 // select(C0, a, select(C1, b, a)) -> select(C0||!C1, a, b)
5209 else if (FalseSI->getFalseValue() == TrueVal) {
5210 Value *InvertedCond = Builder.CreateNot(V: FalseSI->getCondition());
5211 Or = Builder.CreateLogicalOr(Cond1: CondVal, Cond2: InvertedCond, Name: "", MDFrom: &SI);
5212 OtherVal = FalseSI->getTrueValue();
5213 }
5214 if (Or && OtherVal) {
5215 replaceOperand(I&: SI, OpNum: 0, V: Or);
5216 replaceOperand(I&: SI, OpNum: 2, V: OtherVal);
5217 setExplicitlyUnknownBranchWeightsIfProfiled(I&: SI, DEBUG_TYPE);
5218 return &SI;
5219 }
5220 }
5221 }
5222 }
5223
5224 // Try to simplify a binop sandwiched between 2 selects with the same
5225 // condition. This is not valid for div/rem because the select might be
5226 // preventing a division-by-zero.
5227 // TODO: A div/rem restriction is conservative; use something like
5228 // isSafeToSpeculativelyExecute().
5229 // select(C, binop(select(C, X, Y), W), Z) -> select(C, binop(X, W), Z)
5230 BinaryOperator *TrueBO;
5231 if (match(V: TrueVal, P: m_OneUse(SubPattern: m_BinOp(I&: TrueBO))) && !TrueBO->isIntDivRem()) {
5232 if (auto *TrueBOSI = dyn_cast<SelectInst>(Val: TrueBO->getOperand(i_nocapture: 0))) {
5233 if (TrueBOSI->getCondition() == CondVal) {
5234 replaceOperand(I&: *TrueBO, OpNum: 0, V: TrueBOSI->getTrueValue());
5235 Worklist.push(I: TrueBO);
5236 return &SI;
5237 }
5238 }
5239 if (auto *TrueBOSI = dyn_cast<SelectInst>(Val: TrueBO->getOperand(i_nocapture: 1))) {
5240 if (TrueBOSI->getCondition() == CondVal) {
5241 replaceOperand(I&: *TrueBO, OpNum: 1, V: TrueBOSI->getTrueValue());
5242 Worklist.push(I: TrueBO);
5243 return &SI;
5244 }
5245 }
5246 }
5247
5248 // select(C, Z, binop(select(C, X, Y), W)) -> select(C, Z, binop(Y, W))
5249 BinaryOperator *FalseBO;
5250 if (match(V: FalseVal, P: m_OneUse(SubPattern: m_BinOp(I&: FalseBO))) && !FalseBO->isIntDivRem()) {
5251 if (auto *FalseBOSI = dyn_cast<SelectInst>(Val: FalseBO->getOperand(i_nocapture: 0))) {
5252 if (FalseBOSI->getCondition() == CondVal) {
5253 replaceOperand(I&: *FalseBO, OpNum: 0, V: FalseBOSI->getFalseValue());
5254 Worklist.push(I: FalseBO);
5255 return &SI;
5256 }
5257 }
5258 if (auto *FalseBOSI = dyn_cast<SelectInst>(Val: FalseBO->getOperand(i_nocapture: 1))) {
5259 if (FalseBOSI->getCondition() == CondVal) {
5260 replaceOperand(I&: *FalseBO, OpNum: 1, V: FalseBOSI->getFalseValue());
5261 Worklist.push(I: FalseBO);
5262 return &SI;
5263 }
5264 }
5265 }
5266
5267 Value *NotCond;
5268 if (match(V: CondVal, P: m_Not(V: m_Value(V&: NotCond))) &&
5269 !InstCombiner::shouldAvoidAbsorbingNotIntoSelect(SI)) {
5270 replaceOperand(I&: SI, OpNum: 0, V: NotCond);
5271 SI.swapValues();
5272 SI.swapProfMetadata();
5273 return &SI;
5274 }
5275
5276 if (Instruction *I = foldVectorSelect(Sel&: SI))
5277 return I;
5278
5279 // If we can compute the condition, there's no need for a select.
5280 // Like the above fold, we are attempting to reduce compile-time cost by
5281 // putting this fold here with limitations rather than in InstSimplify.
5282 // The motivation for this call into value tracking is to take advantage of
5283 // the assumption cache, so make sure that is populated.
5284 if (!CondVal->getType()->isVectorTy() && !AC.assumptions().empty()) {
5285 KnownBits Known(1);
5286 computeKnownBits(V: CondVal, Known, CtxI: &SI);
5287 if (Known.One.isOne())
5288 return replaceInstUsesWith(I&: SI, V: TrueVal);
5289 if (Known.Zero.isOne())
5290 return replaceInstUsesWith(I&: SI, V: FalseVal);
5291 }
5292
5293 if (Instruction *BitCastSel = foldSelectCmpBitcasts(Sel&: SI, Builder))
5294 return BitCastSel;
5295
5296 // Simplify selects that test the returned flag of cmpxchg instructions.
5297 if (Value *V = foldSelectCmpXchg(SI))
5298 return replaceInstUsesWith(I&: SI, V);
5299
5300 if (Instruction *Select = foldSelectBinOpIdentity(Sel&: SI, TLI, IC&: *this))
5301 return Select;
5302
5303 if (Instruction *Funnel = foldSelectFunnelShift(Sel&: SI, Builder))
5304 return Funnel;
5305
5306 if (Instruction *Copysign = foldSelectToCopysign(Sel&: SI, Builder))
5307 return Copysign;
5308
5309 if (Instruction *PN = foldSelectToPhi(Sel&: SI, DT, Builder))
5310 return replaceInstUsesWith(I&: SI, V: PN);
5311
5312 if (Value *V = foldRoundUpIntegerWithPow2Alignment(SI, Builder))
5313 return replaceInstUsesWith(I&: SI, V);
5314
5315 if (Value *V = foldSelectIntoAddConstant(SI, Builder))
5316 return replaceInstUsesWith(I&: SI, V);
5317
5318 // select(mask, mload(ptr,mask,0), 0) -> mload(ptr,mask,0)
5319 // Load inst is intentionally not checked for hasOneUse()
5320 if (match(V: FalseVal, P: m_Zero()) &&
5321 (match(V: TrueVal, P: m_MaskedLoad(Op0: m_Value(), Op1: m_Specific(V: CondVal),
5322 Op2: m_CombineOr(Ps: m_Undef(), Ps: m_Zero()))) ||
5323 match(V: TrueVal, P: m_MaskedGather(Op0: m_Value(), Op1: m_Specific(V: CondVal),
5324 Op2: m_CombineOr(Ps: m_Undef(), Ps: m_Zero()))))) {
5325 auto *MaskedInst = cast<IntrinsicInst>(Val: TrueVal);
5326 if (isa<UndefValue>(Val: MaskedInst->getArgOperand(i: 2)))
5327 MaskedInst->setArgOperand(i: 2, v: FalseVal /* Zero */);
5328 return replaceInstUsesWith(I&: SI, V: MaskedInst);
5329 }
5330
5331 Value *Mask;
5332 if (match(V: TrueVal, P: m_Zero()) &&
5333 (match(V: FalseVal, P: m_MaskedLoad(Op0: m_Value(), Op1: m_Value(V&: Mask),
5334 Op2: m_CombineOr(Ps: m_Undef(), Ps: m_Zero()))) ||
5335 match(V: FalseVal, P: m_MaskedGather(Op0: m_Value(), Op1: m_Value(V&: Mask),
5336 Op2: m_CombineOr(Ps: m_Undef(), Ps: m_Zero())))) &&
5337 (CondVal->getType() == Mask->getType())) {
5338 // We can remove the select by ensuring the load zeros all lanes the
5339 // select would have. We determine this by proving there is no overlap
5340 // between the load and select masks.
5341 // (i.e (load_mask & select_mask) == 0 == no overlap)
5342 bool CanMergeSelectIntoLoad = false;
5343 if (Value *V = simplifyAndInst(LHS: CondVal, RHS: Mask, Q: SQ.getWithInstruction(I: &SI)))
5344 CanMergeSelectIntoLoad = match(V, P: m_Zero());
5345
5346 if (CanMergeSelectIntoLoad) {
5347 auto *MaskedInst = cast<IntrinsicInst>(Val: FalseVal);
5348 if (isa<UndefValue>(Val: MaskedInst->getArgOperand(i: 2)))
5349 MaskedInst->setArgOperand(i: 2, v: TrueVal /* Zero */);
5350 return replaceInstUsesWith(I&: SI, V: MaskedInst);
5351 }
5352 }
5353
5354 if (Instruction *I = foldSelectOfSymmetricSelect(OuterSelVal&: SI, Builder))
5355 return I;
5356
5357 if (Instruction *I = foldNestedSelects(OuterSelVal&: SI, Builder))
5358 return I;
5359
5360 // Match logical variants of the pattern,
5361 // and transform them iff that gets rid of inversions.
5362 // (~x) | y --> ~(x & (~y))
5363 // (~x) & y --> ~(x | (~y))
5364 if (sinkNotIntoOtherHandOfLogicalOp(I&: SI))
5365 return &SI;
5366
5367 if (Instruction *I = foldBitCeil(SI, Builder, IC&: *this))
5368 return I;
5369
5370 if (Instruction *I = foldSelectToCmp(SI))
5371 return I;
5372
5373 if (Instruction *I = foldSelectEqualityTest(Sel&: SI))
5374 return I;
5375
5376 // Fold:
5377 // (select A && B, T, F) -> (select A, (select B, T, F), F)
5378 // (select A || B, T, F) -> (select A, T, (select B, T, F))
5379 // if (select B, T, F) is foldable.
5380 // TODO: preserve FMF flags
5381 auto FoldSelectWithAndOrCond = [&](bool IsAnd, Value *A,
5382 Value *B) -> Instruction * {
5383 Instruction *MDFrom = nullptr;
5384 // If the and/or is logical, we can propagate branch weights from that
5385 // select. Otherwise, we cannot infer the branch weights in the
5386 // general case.
5387 if (auto *NestedSI = dyn_cast<SelectInst>(Val: SI.getCondition()))
5388 if (NestedSI->getCondition() == A)
5389 MDFrom = NestedSI;
5390
5391 if (Value *V = simplifySelectInst(Cond: B, TrueVal, FalseVal, FMF,
5392 Q: SQ.getWithInstruction(I: &SI))) {
5393 SelectInst *NewSI = SelectInst::Create(
5394 C: A, S1: IsAnd ? V : TrueVal, S2: IsAnd ? FalseVal : V, NameStr: "", InsertBefore: nullptr,
5395 MDFrom: ProfcheckDisableMetadataFixes ? nullptr : MDFrom);
5396 if (!MDFrom)
5397 setExplicitlyUnknownBranchWeightsIfProfiled(I&: *NewSI, DEBUG_TYPE, F: &F);
5398 return NewSI;
5399 }
5400
5401 // Is (select B, T, F) a SPF?
5402 if (CondVal->hasOneUse() && SelType->isIntOrIntVectorTy()) {
5403 if (ICmpInst *Cmp = dyn_cast<ICmpInst>(Val: B))
5404 if (Value *V = canonicalizeSPF(Cmp&: *Cmp, TrueVal, FalseVal, IC&: *this)) {
5405 SelectInst *NewSI = SelectInst::Create(
5406 C: A, S1: IsAnd ? V : TrueVal, S2: IsAnd ? FalseVal : V, NameStr: "", InsertBefore: nullptr,
5407 MDFrom: ProfcheckDisableMetadataFixes ? nullptr : MDFrom);
5408 if (!MDFrom)
5409 setExplicitlyUnknownBranchWeightsIfProfiled(I&: *NewSI, DEBUG_TYPE, F: &F);
5410 return NewSI;
5411 }
5412 }
5413
5414 return nullptr;
5415 };
5416
5417 Value *LHS, *RHS;
5418 if (match(V: CondVal, P: m_And(L: m_Value(V&: LHS), R: m_Value(V&: RHS)))) {
5419 if (Instruction *I = FoldSelectWithAndOrCond(/*IsAnd*/ true, LHS, RHS))
5420 return I;
5421 if (Instruction *I = FoldSelectWithAndOrCond(/*IsAnd*/ true, RHS, LHS))
5422 return I;
5423 } else if (match(V: CondVal, P: m_Or(L: m_Value(V&: LHS), R: m_Value(V&: RHS)))) {
5424 if (Instruction *I = FoldSelectWithAndOrCond(/*IsAnd*/ false, LHS, RHS))
5425 return I;
5426 if (Instruction *I = FoldSelectWithAndOrCond(/*IsAnd*/ false, RHS, LHS))
5427 return I;
5428 } else {
5429 // We cannot swap the operands of logical and/or.
5430 // TODO: Can we swap the operands by inserting a freeze?
5431 if (match(V: CondVal, P: m_LogicalAnd(L: m_Value(V&: LHS), R: m_Value(V&: RHS)))) {
5432 if (Instruction *I = FoldSelectWithAndOrCond(/*IsAnd*/ true, LHS, RHS))
5433 return I;
5434 } else if (match(V: CondVal, P: m_LogicalOr(L: m_Value(V&: LHS), R: m_Value(V&: RHS)))) {
5435 if (Instruction *I = FoldSelectWithAndOrCond(/*IsAnd*/ false, LHS, RHS))
5436 return I;
5437 }
5438 }
5439
5440 // select Cond, !X, X -> xor Cond, X
5441 if (CondVal->getType() == SI.getType() && isKnownInversion(X: FalseVal, Y: TrueVal))
5442 return BinaryOperator::CreateXor(V1: CondVal, V2: FalseVal);
5443
5444 // For vectors, this transform is only safe if the simplification does not
5445 // look through any lane-crossing operations. For now, limit to scalars only.
5446 if (SelType->isIntegerTy() &&
5447 (!isa<Constant>(Val: TrueVal) || !isa<Constant>(Val: FalseVal))) {
5448 // Try to simplify select arms based on KnownBits implied by the condition.
5449 CondContext CC(CondVal);
5450 findValuesAffectedByCondition(Cond: CondVal, /*IsAssume=*/false, InsertAffected: [&](Value *V) {
5451 CC.AffectedValues.insert(Ptr: V);
5452 });
5453 SimplifyQuery Q = SQ.getWithInstruction(I: &SI).getWithCondContext(CC);
5454 if (!CC.AffectedValues.empty()) {
5455 if (!isa<Constant>(Val: TrueVal) &&
5456 hasAffectedValue(V: TrueVal, Affected&: CC.AffectedValues, /*Depth=*/0)) {
5457 KnownBits Known = llvm::computeKnownBits(V: TrueVal, Q);
5458 if (Known.isConstant())
5459 return replaceOperand(I&: SI, OpNum: 1,
5460 V: ConstantInt::get(Ty: SelType, V: Known.getConstant()));
5461 }
5462
5463 CC.Invert = true;
5464 if (!isa<Constant>(Val: FalseVal) &&
5465 hasAffectedValue(V: FalseVal, Affected&: CC.AffectedValues, /*Depth=*/0)) {
5466 KnownBits Known = llvm::computeKnownBits(V: FalseVal, Q);
5467 if (Known.isConstant())
5468 return replaceOperand(I&: SI, OpNum: 2,
5469 V: ConstantInt::get(Ty: SelType, V: Known.getConstant()));
5470 }
5471 }
5472 }
5473
5474 // select (trunc nuw X to i1), X, Y --> select (trunc nuw X to i1), 1, Y
5475 // select (trunc nuw X to i1), Y, X --> select (trunc nuw X to i1), Y, 0
5476 // select (trunc nsw X to i1), X, Y --> select (trunc nsw X to i1), -1, Y
5477 // select (trunc nsw X to i1), Y, X --> select (trunc nsw X to i1), Y, 0
5478 Value *Trunc;
5479 if (match(V: CondVal, P: m_NUWTrunc(Op: m_Value(V&: Trunc))) && !isa<Constant>(Val: Trunc)) {
5480 if (TrueVal == Trunc)
5481 return replaceOperand(I&: SI, OpNum: 1, V: ConstantInt::get(Ty: TrueVal->getType(), V: 1));
5482 if (FalseVal == Trunc)
5483 return replaceOperand(I&: SI, OpNum: 2, V: ConstantInt::get(Ty: FalseVal->getType(), V: 0));
5484 }
5485 if (match(V: CondVal, P: m_NSWTrunc(Op: m_Value(V&: Trunc))) && !isa<Constant>(Val: Trunc)) {
5486 if (TrueVal == Trunc)
5487 return replaceOperand(I&: SI, OpNum: 1,
5488 V: Constant::getAllOnesValue(Ty: TrueVal->getType()));
5489 if (FalseVal == Trunc)
5490 return replaceOperand(I&: SI, OpNum: 2, V: ConstantInt::get(Ty: FalseVal->getType(), V: 0));
5491 }
5492
5493 if (match(V: CondVal, P: m_Trunc(Op: m_Value(V&: Trunc))) && Trunc->getType() == SelType) {
5494 if (match(V: FalseVal, P: m_Zero()) && impliesPoison(ValAssumedPoison: TrueVal, V: CondVal) &&
5495 llvm::computeKnownBits(V: TrueVal, Q: SQ.getWithInstruction(I: &SI))
5496 .countMaxActiveBits() == 1)
5497 return BinaryOperator::CreateAnd(V1: Trunc, V2: TrueVal);
5498
5499 if (cast<TruncInst>(Val: CondVal)->hasNoUnsignedWrap() &&
5500 match(V: TrueVal, P: m_One()) && impliesPoison(ValAssumedPoison: FalseVal, V: CondVal) &&
5501 llvm::computeKnownBits(V: FalseVal, Q: SQ.getWithInstruction(I: &SI))
5502 .countMaxActiveBits() == 1) {
5503 return BinaryOperator::CreateOr(V1: Trunc, V2: FalseVal);
5504 }
5505 }
5506
5507 Value *MaskedLoadPtr;
5508 if (match(V: TrueVal, P: m_OneUse(SubPattern: m_MaskedLoad(Op0: m_Value(V&: MaskedLoadPtr),
5509 Op1: m_Specific(V: CondVal), Op2: m_Value())))) {
5510 auto *LoadInst = cast<IntrinsicInst>(Val: TrueVal);
5511 // Keep the load at its original position to avoid crossing writes. The new
5512 // passthrough must therefore be available there.
5513 if (DT.dominates(Def: FalseVal, User: LoadInst)) {
5514 Builder.SetInsertPoint(LoadInst);
5515 Instruction *In = Builder.CreateMaskedLoad(
5516 Ty: TrueVal->getType(), Ptr: MaskedLoadPtr,
5517 Alignment: LoadInst->getParamAlign(ArgNo: 0).valueOrOne(), Mask: CondVal, PassThru: FalseVal);
5518 In->setAAMetadata(LoadInst->getAAMetadata());
5519 return replaceInstUsesWith(I&: SI, V: In);
5520 }
5521 }
5522
5523 // Canonicalize sign function ashr pattern: select (icmp slt X, 1), ashr X,
5524 // bitwidth-1, 1 -> scmp(X, 0)
5525 // Also handles: select (icmp sgt X, 0), 1, ashr X, bitwidth-1 -> scmp(X, 0)
5526 unsigned BitWidth = SI.getType()->getScalarSizeInBits();
5527 CmpPredicate Pred;
5528 Value *CmpLHS, *CmpRHS;
5529
5530 // Canonicalize sign function ashr patterns:
5531 // select (icmp slt X, 1), ashr X, bitwidth-1, 1 -> scmp(X, 0)
5532 // select (icmp sgt X, 0), 1, ashr X, bitwidth-1 -> scmp(X, 0)
5533 if (match(V: &SI, P: m_Select(C: m_ICmp(Pred, L: m_Value(V&: CmpLHS), R: m_Value(V&: CmpRHS)),
5534 L: m_Value(V&: TrueVal), R: m_Value(V&: FalseVal))) &&
5535 ((Pred == ICmpInst::ICMP_SLT && match(V: CmpRHS, P: m_One()) &&
5536 match(V: TrueVal,
5537 P: m_AShr(L: m_Specific(V: CmpLHS), R: m_SpecificInt(V: BitWidth - 1))) &&
5538 match(V: FalseVal, P: m_One())) ||
5539 (Pred == ICmpInst::ICMP_SGT && match(V: CmpRHS, P: m_Zero()) &&
5540 match(V: TrueVal, P: m_One()) &&
5541 match(V: FalseVal,
5542 P: m_AShr(L: m_Specific(V: CmpLHS), R: m_SpecificInt(V: BitWidth - 1)))))) {
5543
5544 Function *Scmp = Intrinsic::getOrInsertDeclaration(
5545 M: SI.getModule(), id: Intrinsic::scmp, OverloadTys: {SI.getType(), SI.getType()});
5546 return CallInst::Create(Func: Scmp, Args: {CmpLHS, ConstantInt::get(Ty: SI.getType(), V: 0)});
5547 }
5548
5549 return nullptr;
5550}
5551