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