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