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