LLVM 24.0.0git
SelectionDAG.cpp
Go to the documentation of this file.
1//===- SelectionDAG.cpp - Implement the SelectionDAG data structures ------===//
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 implements the SelectionDAG class.
10//
11//===----------------------------------------------------------------------===//
12
14#include "SDNodeDbgValue.h"
15#include "llvm/ADT/APFloat.h"
16#include "llvm/ADT/APInt.h"
17#include "llvm/ADT/APSInt.h"
18#include "llvm/ADT/ArrayRef.h"
19#include "llvm/ADT/BitVector.h"
20#include "llvm/ADT/DenseSet.h"
21#include "llvm/ADT/FoldingSet.h"
22#include "llvm/ADT/STLExtras.h"
25#include "llvm/ADT/Twine.h"
52#include "llvm/IR/Constant.h"
53#include "llvm/IR/Constants.h"
54#include "llvm/IR/DataLayout.h"
56#include "llvm/IR/DebugLoc.h"
58#include "llvm/IR/Function.h"
59#include "llvm/IR/GlobalValue.h"
60#include "llvm/IR/Metadata.h"
61#include "llvm/IR/Type.h"
65#include "llvm/Support/Debug.h"
75#include <algorithm>
76#include <cassert>
77#include <cstdint>
78#include <cstdlib>
79#include <limits>
80#include <optional>
81#include <string>
82#include <utility>
83#include <vector>
84
85using namespace llvm;
86using namespace llvm::SDPatternMatch;
87
88/// makeVTList - Return an instance of the SDVTList struct initialized with the
89/// specified members.
90static SDVTList makeVTList(const EVT *VTs, unsigned NumVTs) {
91 SDVTList Res = {VTs, NumVTs};
92 return Res;
93}
94
95// Default null implementations of the callbacks.
99
100void SelectionDAG::DAGNodeDeletedListener::anchor() {}
101void SelectionDAG::DAGNodeInsertedListener::anchor() {}
102
103#define DEBUG_TYPE "selectiondag"
104
105static cl::opt<bool> EnableMemCpyDAGOpt("enable-memcpy-dag-opt",
106 cl::Hidden, cl::init(true),
107 cl::desc("Gang up loads and stores generated by inlining of memcpy"));
108
109static cl::opt<int> MaxLdStGlue("ldstmemcpy-glue-max",
110 cl::desc("Number limit for gluing ld/st of memcpy."),
111 cl::Hidden, cl::init(0));
112
114 MaxSteps("has-predecessor-max-steps", cl::Hidden, cl::init(8192),
115 cl::desc("DAG combiner limit number of steps when searching DAG "
116 "for predecessor nodes"));
117
119 LLVM_DEBUG(dbgs() << Msg; V.getNode()->dump(G););
120}
121
123
124//===----------------------------------------------------------------------===//
125// ConstantFPSDNode Class
126//===----------------------------------------------------------------------===//
127
128/// isExactlyValue - We don't rely on operator== working on double values, as
129/// it returns true for things that are clearly not equal, like -0.0 and 0.0.
130/// As such, this method can be used to do an exact bit-for-bit comparison of
131/// two floating point values.
133 return getValueAPF().bitwiseIsEqual(V);
134}
135
137 const APFloat& Val) {
138 assert(VT.isFloatingPoint() && "Can only convert between FP types");
139
140 // convert modifies in place, so make a copy.
141 APFloat Val2 = APFloat(Val);
142 bool losesInfo;
144 &losesInfo);
145 return !losesInfo;
146}
147
148//===----------------------------------------------------------------------===//
149// ISD Namespace
150//===----------------------------------------------------------------------===//
151
152bool ISD::isConstantSplatVector(const SDNode *N, APInt &SplatVal) {
153 if (N->getOpcode() == ISD::SPLAT_VECTOR) {
154 if (auto OptAPInt = N->getOperand(0)->bitcastToAPInt()) {
155 unsigned EltSize =
156 N->getValueType(0).getVectorElementType().getSizeInBits();
157 SplatVal = OptAPInt->trunc(EltSize);
158 return true;
159 }
160 }
161
162 auto *BV = dyn_cast<BuildVectorSDNode>(N);
163 if (!BV)
164 return false;
165
166 APInt SplatUndef;
167 unsigned SplatBitSize;
168 bool HasUndefs;
169 unsigned EltSize = N->getValueType(0).getVectorElementType().getSizeInBits();
170 // Endianness does not matter here. We are checking for a splat given the
171 // element size of the vector, and if we find such a splat for little endian
172 // layout, then that should be valid also for big endian (as the full vector
173 // size is known to be a multiple of the element size).
174 const bool IsBigEndian = false;
175 return BV->isConstantSplat(SplatVal, SplatUndef, SplatBitSize, HasUndefs,
176 EltSize, IsBigEndian) &&
177 EltSize == SplatBitSize;
178}
179
180// FIXME: AllOnes and AllZeros duplicate a lot of code. Could these be
181// specializations of the more general isConstantSplatVector()?
182
183bool ISD::isConstantSplatVectorAllOnes(const SDNode *N, bool BuildVectorOnly) {
184 // Look through a bit convert.
185 while (N->getOpcode() == ISD::BITCAST)
186 N = N->getOperand(0).getNode();
187
188 if (!BuildVectorOnly && N->getOpcode() == ISD::SPLAT_VECTOR) {
189 APInt SplatVal;
190 return isConstantSplatVector(N, SplatVal) && SplatVal.isAllOnes();
191 }
192
193 if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
194
195 unsigned i = 0, e = N->getNumOperands();
196
197 // Skip over all of the undef values.
198 while (i != e && N->getOperand(i).isUndef())
199 ++i;
200
201 // Do not accept an all-undef vector.
202 if (i == e) return false;
203
204 // Do not accept build_vectors that aren't all constants or which have non-~0
205 // elements. We have to be a bit careful here, as the type of the constant
206 // may not be the same as the type of the vector elements due to type
207 // legalization (the elements are promoted to a legal type for the target and
208 // a vector of a type may be legal when the base element type is not).
209 // We only want to check enough bits to cover the vector elements, because
210 // we care if the resultant vector is all ones, not whether the individual
211 // constants are.
212 SDValue NotZero = N->getOperand(i);
213 if (auto OptAPInt = NotZero->bitcastToAPInt()) {
214 unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
215 if (OptAPInt->countr_one() < EltSize)
216 return false;
217 } else
218 return false;
219
220 // Okay, we have at least one ~0 value, check to see if the rest match or are
221 // undefs. Even with the above element type twiddling, this should be OK, as
222 // the same type legalization should have applied to all the elements.
223 for (++i; i != e; ++i)
224 if (N->getOperand(i) != NotZero && !N->getOperand(i).isUndef())
225 return false;
226 return true;
227}
228
229bool ISD::isConstantSplatVectorAllZeros(const SDNode *N, bool BuildVectorOnly) {
230 // Look through a bit convert.
231 while (N->getOpcode() == ISD::BITCAST)
232 N = N->getOperand(0).getNode();
233
234 if (!BuildVectorOnly && N->getOpcode() == ISD::SPLAT_VECTOR) {
235 APInt SplatVal;
236 return isConstantSplatVector(N, SplatVal) && SplatVal.isZero();
237 }
238
239 if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
240
241 bool IsAllUndef = true;
242 for (const SDValue &Op : N->op_values()) {
243 if (Op.isUndef())
244 continue;
245 IsAllUndef = false;
246 // Do not accept build_vectors that aren't all constants or which have non-0
247 // elements. We have to be a bit careful here, as the type of the constant
248 // may not be the same as the type of the vector elements due to type
249 // legalization (the elements are promoted to a legal type for the target
250 // and a vector of a type may be legal when the base element type is not).
251 // We only want to check enough bits to cover the vector elements, because
252 // we care if the resultant vector is all zeros, not whether the individual
253 // constants are.
254 if (auto OptAPInt = Op->bitcastToAPInt()) {
255 unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
256 if (OptAPInt->countr_zero() < EltSize)
257 return false;
258 } else
259 return false;
260 }
261
262 // Do not accept an all-undef vector.
263 if (IsAllUndef)
264 return false;
265 return true;
266}
267
269 return isConstantSplatVectorAllOnes(N, /*BuildVectorOnly*/ true);
270}
271
273 return isConstantSplatVectorAllZeros(N, /*BuildVectorOnly*/ true);
274}
275
277 if (N->getOpcode() != ISD::BUILD_VECTOR)
278 return false;
279
280 for (const SDValue &Op : N->op_values()) {
281 if (Op.isUndef())
282 continue;
284 return false;
285 }
286 return true;
287}
288
290 if (N->getOpcode() != ISD::BUILD_VECTOR)
291 return false;
292
293 for (const SDValue &Op : N->op_values()) {
294 if (Op.isUndef())
295 continue;
297 return false;
298 }
299 return true;
300}
301
302bool ISD::isVectorShrinkable(const SDNode *N, unsigned NewEltSize,
303 bool Signed) {
304 assert(N->getValueType(0).isVector() && "Expected a vector!");
305
306 unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
307 if (EltSize <= NewEltSize)
308 return false;
309
310 if (N->getOpcode() == ISD::ZERO_EXTEND) {
311 return (N->getOperand(0).getValueType().getScalarSizeInBits() <=
312 NewEltSize) &&
313 !Signed;
314 }
315 if (N->getOpcode() == ISD::SIGN_EXTEND) {
316 return (N->getOperand(0).getValueType().getScalarSizeInBits() <=
317 NewEltSize) &&
318 Signed;
319 }
320 if (N->getOpcode() != ISD::BUILD_VECTOR)
321 return false;
322
323 for (const SDValue &Op : N->op_values()) {
324 if (Op.isUndef())
325 continue;
327 return false;
328
329 APInt C = Op->getAsAPIntVal().trunc(EltSize);
330 if (Signed && C.trunc(NewEltSize).sext(EltSize) != C)
331 return false;
332 if (!Signed && C.trunc(NewEltSize).zext(EltSize) != C)
333 return false;
334 }
335
336 return true;
337}
338
340 // Return false if the node has no operands.
341 // This is "logically inconsistent" with the definition of "all" but
342 // is probably the desired behavior.
343 if (N->getNumOperands() == 0)
344 return false;
345 return all_of(N->op_values(), [](SDValue Op) { return Op.isUndef(); });
346}
347
349 return N->getOpcode() == ISD::FREEZE && N->getOperand(0).isUndef();
350}
351
352template <typename ConstNodeType>
354 std::function<bool(ConstNodeType *)> Match,
355 bool AllowUndefs, bool AllowTruncation) {
356 // FIXME: Add support for scalar UNDEF cases?
357 if (auto *C = dyn_cast<ConstNodeType>(Op))
358 return Match(C);
359
360 // FIXME: Add support for vector UNDEF cases?
361 if (ISD::BUILD_VECTOR != Op.getOpcode() &&
362 ISD::SPLAT_VECTOR != Op.getOpcode())
363 return false;
364
365 if (ISD::SPLAT_VECTOR == Op.getOpcode() && !DemandedElts)
366 return true;
367
368 EVT SVT = Op.getValueType().getScalarType();
369 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
370 if (ISD::SPLAT_VECTOR != Op.getOpcode() && !DemandedElts[i])
371 continue;
372
373 if (AllowUndefs && Op.getOperand(i).isUndef()) {
374 if (!Match(nullptr))
375 return false;
376 continue;
377 }
378
379 auto *Cst = dyn_cast<ConstNodeType>(Op.getOperand(i));
380 if (!Cst || (!AllowTruncation && Cst->getValueType(0) != SVT) ||
381 !Match(Cst))
382 return false;
383 }
384 return true;
385}
386// Build used template types.
388 SDValue, const APInt &, std::function<bool(ConstantSDNode *)>, bool, bool);
390 SDValue, const APInt &, std::function<bool(ConstantFPSDNode *)>, bool,
391 bool);
392
394 SDValue LHS, SDValue RHS, const APInt &DemandedElts,
395 std::function<bool(ConstantSDNode *, ConstantSDNode *)> Match,
396 bool AllowUndefs, bool AllowTypeMismatch) {
397 if (!AllowTypeMismatch && LHS.getValueType() != RHS.getValueType())
398 return false;
399
400 // TODO: Add support for scalar UNDEF cases?
401 if (auto *LHSCst = dyn_cast<ConstantSDNode>(LHS))
402 if (auto *RHSCst = dyn_cast<ConstantSDNode>(RHS))
403 return Match(LHSCst, RHSCst);
404
405 // TODO: Add support for vector UNDEF cases?
406 if (LHS.getOpcode() != RHS.getOpcode() ||
407 (LHS.getOpcode() != ISD::BUILD_VECTOR &&
408 LHS.getOpcode() != ISD::SPLAT_VECTOR))
409 return false;
410
411 if (ISD::SPLAT_VECTOR == LHS.getOpcode() && !DemandedElts)
412 return true;
413
414 EVT SVT = LHS.getValueType().getScalarType();
415 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
416 if (ISD::SPLAT_VECTOR != LHS.getOpcode() && !DemandedElts[i])
417 continue;
418 SDValue LHSOp = LHS.getOperand(i);
419 SDValue RHSOp = RHS.getOperand(i);
420 bool LHSUndef = AllowUndefs && LHSOp.isUndef();
421 bool RHSUndef = AllowUndefs && RHSOp.isUndef();
422 auto *LHSCst = dyn_cast<ConstantSDNode>(LHSOp);
423 auto *RHSCst = dyn_cast<ConstantSDNode>(RHSOp);
424 if ((!LHSCst && !LHSUndef) || (!RHSCst && !RHSUndef))
425 return false;
426 if (!AllowTypeMismatch && (LHSOp.getValueType() != SVT ||
427 LHSOp.getValueType() != RHSOp.getValueType()))
428 return false;
429 if (!Match(LHSCst, RHSCst))
430 return false;
431 }
432 return true;
433}
434
436 switch (MinMaxOpc) {
437 default:
438 llvm_unreachable("unrecognized opcode");
439 case ISD::UMIN:
440 return ISD::UMAX;
441 case ISD::UMAX:
442 return ISD::UMIN;
443 case ISD::SMIN:
444 return ISD::SMAX;
445 case ISD::SMAX:
446 return ISD::SMIN;
447 }
448}
449
451 switch (MinMaxOpc) {
452 default:
453 llvm_unreachable("unrecognized min/max opcode");
454 case ISD::SMIN:
455 return ISD::UMIN;
456 case ISD::SMAX:
457 return ISD::UMAX;
458 case ISD::UMIN:
459 return ISD::SMIN;
460 case ISD::UMAX:
461 return ISD::SMAX;
462 }
463}
464
466 switch (VecReduceOpcode) {
467 default:
468 llvm_unreachable("Expected VECREDUCE opcode");
471 case ISD::VP_REDUCE_FADD:
472 case ISD::VP_REDUCE_SEQ_FADD:
473 return ISD::FADD;
476 case ISD::VP_REDUCE_FMUL:
477 case ISD::VP_REDUCE_SEQ_FMUL:
478 return ISD::FMUL;
480 case ISD::VP_REDUCE_ADD:
481 return ISD::ADD;
483 case ISD::VP_REDUCE_MUL:
484 return ISD::MUL;
486 case ISD::VP_REDUCE_AND:
487 return ISD::AND;
489 case ISD::VP_REDUCE_OR:
490 return ISD::OR;
492 case ISD::VP_REDUCE_XOR:
493 return ISD::XOR;
495 case ISD::VP_REDUCE_SMAX:
496 return ISD::SMAX;
498 case ISD::VP_REDUCE_SMIN:
499 return ISD::SMIN;
501 case ISD::VP_REDUCE_UMAX:
502 return ISD::UMAX;
504 case ISD::VP_REDUCE_UMIN:
505 return ISD::UMIN;
507 case ISD::VP_REDUCE_FMAX:
508 return ISD::FMAXNUM;
510 case ISD::VP_REDUCE_FMIN:
511 return ISD::FMINNUM;
513 case ISD::VP_REDUCE_FMAXIMUM:
514 return ISD::FMAXIMUM;
516 case ISD::VP_REDUCE_FMINIMUM:
517 return ISD::FMINIMUM;
519 return ISD::FMAXIMUMNUM;
521 return ISD::FMINIMUMNUM;
522 }
523}
524
526 switch (MaskedOpc) {
527 case ISD::MASKED_UDIV:
528 return ISD::UDIV;
529 case ISD::MASKED_SDIV:
530 return ISD::SDIV;
531 case ISD::MASKED_UREM:
532 return ISD::UREM;
533 case ISD::MASKED_SREM:
534 return ISD::SREM;
535 default:
536 llvm_unreachable("Expected masked binop opcode");
537 }
538}
539
540bool ISD::isVPOpcode(unsigned Opcode) {
541 switch (Opcode) {
542 default:
543 return false;
544#define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) \
545 case ISD::VPSD: \
546 return true;
547#include "llvm/IR/VPIntrinsics.def"
548 }
549}
550
551bool ISD::isVPBinaryOp(unsigned Opcode) {
552 switch (Opcode) {
553 default:
554 break;
555#define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) case ISD::VPSD:
556#define VP_PROPERTY_BINARYOP return true;
557#define END_REGISTER_VP_SDNODE(VPSD) break;
558#include "llvm/IR/VPIntrinsics.def"
559 }
560 return false;
561}
562
563bool ISD::isVPReduction(unsigned Opcode) {
564 switch (Opcode) {
565 default:
566 return false;
567 case ISD::VP_REDUCE_ADD:
568 case ISD::VP_REDUCE_MUL:
569 case ISD::VP_REDUCE_AND:
570 case ISD::VP_REDUCE_OR:
571 case ISD::VP_REDUCE_XOR:
572 case ISD::VP_REDUCE_SMAX:
573 case ISD::VP_REDUCE_SMIN:
574 case ISD::VP_REDUCE_UMAX:
575 case ISD::VP_REDUCE_UMIN:
576 case ISD::VP_REDUCE_FMAX:
577 case ISD::VP_REDUCE_FMIN:
578 case ISD::VP_REDUCE_FMAXIMUM:
579 case ISD::VP_REDUCE_FMINIMUM:
580 case ISD::VP_REDUCE_FADD:
581 case ISD::VP_REDUCE_FMUL:
582 case ISD::VP_REDUCE_SEQ_FADD:
583 case ISD::VP_REDUCE_SEQ_FMUL:
584 return true;
585 }
586}
587
588/// The operand position of the vector mask.
589std::optional<unsigned> ISD::getVPMaskIdx(unsigned Opcode) {
590 switch (Opcode) {
591 default:
592 return std::nullopt;
593#define BEGIN_REGISTER_VP_SDNODE(VPSD, LEGALPOS, TDNAME, MASKPOS, ...) \
594 case ISD::VPSD: \
595 return MASKPOS;
596#include "llvm/IR/VPIntrinsics.def"
597 }
598}
599
600/// The operand position of the explicit vector length parameter.
601std::optional<unsigned> ISD::getVPExplicitVectorLengthIdx(unsigned Opcode) {
602 switch (Opcode) {
603 default:
604 return std::nullopt;
605#define BEGIN_REGISTER_VP_SDNODE(VPSD, LEGALPOS, TDNAME, MASKPOS, EVLPOS) \
606 case ISD::VPSD: \
607 return EVLPOS;
608#include "llvm/IR/VPIntrinsics.def"
609 }
610}
611
612std::optional<unsigned> ISD::getBaseOpcodeForVP(unsigned VPOpcode,
613 bool hasFPExcept) {
614 // FIXME: Return strict opcodes in case of fp exceptions.
615 switch (VPOpcode) {
616 default:
617 return std::nullopt;
618#define BEGIN_REGISTER_VP_SDNODE(VPOPC, ...) case ISD::VPOPC:
619#define VP_PROPERTY_FUNCTIONAL_SDOPC(SDOPC) return ISD::SDOPC;
620#define END_REGISTER_VP_SDNODE(VPOPC) break;
621#include "llvm/IR/VPIntrinsics.def"
622 }
623 return std::nullopt;
624}
625
626std::optional<unsigned> ISD::getVPForBaseOpcode(unsigned Opcode) {
627 switch (Opcode) {
628 default:
629 return std::nullopt;
630#define BEGIN_REGISTER_VP_SDNODE(VPOPC, ...) break;
631#define VP_PROPERTY_FUNCTIONAL_SDOPC(SDOPC) case ISD::SDOPC:
632#define END_REGISTER_VP_SDNODE(VPOPC) return ISD::VPOPC;
633#include "llvm/IR/VPIntrinsics.def"
634 }
635}
636
638 switch (ExtType) {
639 case ISD::EXTLOAD:
640 return IsFP ? ISD::FP_EXTEND : ISD::ANY_EXTEND;
641 case ISD::SEXTLOAD:
642 return ISD::SIGN_EXTEND;
643 case ISD::ZEXTLOAD:
644 return ISD::ZERO_EXTEND;
645 default:
646 break;
647 }
648
649 llvm_unreachable("Invalid LoadExtType");
650}
651
653 // To perform this operation, we just need to swap the L and G bits of the
654 // operation.
655 unsigned OldL = (Operation >> 2) & 1;
656 unsigned OldG = (Operation >> 1) & 1;
657 return ISD::CondCode((Operation & ~6) | // Keep the N, U, E bits
658 (OldL << 1) | // New G bit
659 (OldG << 2)); // New L bit.
660}
661
663 unsigned Operation = Op;
664 if (isIntegerLike)
665 Operation ^= 7; // Flip L, G, E bits, but not U.
666 else
667 Operation ^= 15; // Flip all of the condition bits.
668
670 Operation &= ~8; // Don't let N and U bits get set.
671
672 return ISD::CondCode(Operation);
673}
674
678
680 bool isIntegerLike) {
681 return getSetCCInverseImpl(Op, isIntegerLike);
682}
683
684/// For an integer comparison, return 1 if the comparison is a signed operation
685/// and 2 if the result is an unsigned comparison. Return zero if the operation
686/// does not depend on the sign of the input (setne and seteq).
687static int isSignedOp(ISD::CondCode Opcode) {
688 switch (Opcode) {
689 default: llvm_unreachable("Illegal integer setcc operation!");
690 case ISD::SETEQ:
691 case ISD::SETNE: return 0;
692 case ISD::SETLT:
693 case ISD::SETLE:
694 case ISD::SETGT:
695 case ISD::SETGE: return 1;
696 case ISD::SETULT:
697 case ISD::SETULE:
698 case ISD::SETUGT:
699 case ISD::SETUGE: return 2;
700 }
701}
702
704 EVT Type) {
705 bool IsInteger = Type.isInteger();
706 if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
707 // Cannot fold a signed integer setcc with an unsigned integer setcc.
708 return ISD::SETCC_INVALID;
709
710 unsigned Op = Op1 | Op2; // Combine all of the condition bits.
711
712 // If the N and U bits get set, then the resultant comparison DOES suddenly
713 // care about orderedness, and it is true when ordered.
714 if (Op > ISD::SETTRUE2)
715 Op &= ~16; // Clear the U bit if the N bit is set.
716
717 // Canonicalize illegal integer setcc's.
718 if (IsInteger && Op == ISD::SETUNE) // e.g. SETUGT | SETULT
719 Op = ISD::SETNE;
720
721 return ISD::CondCode(Op);
722}
723
725 EVT Type) {
726 bool IsInteger = Type.isInteger();
727 if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
728 // Cannot fold a signed setcc with an unsigned setcc.
729 return ISD::SETCC_INVALID;
730
731 // Combine all of the condition bits.
732 ISD::CondCode Result = ISD::CondCode(Op1 & Op2);
733
734 // Canonicalize illegal integer setcc's.
735 if (IsInteger) {
736 switch (Result) {
737 default: break;
738 case ISD::SETUO : Result = ISD::SETFALSE; break; // SETUGT & SETULT
739 case ISD::SETOEQ: // SETEQ & SETU[LG]E
740 case ISD::SETUEQ: Result = ISD::SETEQ ; break; // SETUGE & SETULE
741 case ISD::SETOLT: Result = ISD::SETULT ; break; // SETULT & SETNE
742 case ISD::SETOGT: Result = ISD::SETUGT ; break; // SETUGT & SETNE
743 }
744 }
745
746 return Result;
747}
748
749//===----------------------------------------------------------------------===//
750// SDNode Profile Support
751//===----------------------------------------------------------------------===//
752
753/// AddNodeIDOpcode - Add the node opcode to the NodeID data.
754static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC) {
755 ID.AddInteger(OpC);
756}
757
758/// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them
759/// solely with their pointer.
761 ID.AddPointer(VTList.VTs);
762}
763
764/// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
767 for (const auto &Op : Ops) {
768 ID.AddPointer(Op.getNode());
769 ID.AddInteger(Op.getResNo());
770 }
771}
772
773/// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
776 for (const auto &Op : Ops) {
777 ID.AddPointer(Op.getNode());
778 ID.AddInteger(Op.getResNo());
779 }
780}
781
782static void AddNodeIDNode(FoldingSetNodeID &ID, unsigned OpC,
783 SDVTList VTList, ArrayRef<SDValue> OpList) {
784 AddNodeIDOpcode(ID, OpC);
785 AddNodeIDValueTypes(ID, VTList);
786 AddNodeIDOperands(ID, OpList);
787}
788
789/// If this is an SDNode with special info, add this info to the NodeID data.
790static void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N) {
791 switch (N->getOpcode()) {
794 case ISD::MCSymbol:
795 llvm_unreachable("Should only be used on nodes with operands");
796 default: break; // Normal nodes don't need extra info.
798 case ISD::Constant: {
800 ID.AddPointer(C->getConstantIntValue());
801 ID.AddBoolean(C->isOpaque());
802 break;
803 }
805 case ISD::ConstantFP:
806 ID.AddPointer(cast<ConstantFPSDNode>(N)->getConstantFPValue());
807 break;
813 ID.AddPointer(GA->getGlobal());
814 ID.AddInteger(GA->getOffset());
815 ID.AddInteger(GA->getTargetFlags());
816 break;
817 }
818 case ISD::BasicBlock:
819 ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock());
820 break;
821 case ISD::Register:
822 ID.AddInteger(cast<RegisterSDNode>(N)->getReg().id());
823 break;
825 ID.AddPointer(cast<RegisterMaskSDNode>(N)->getRegMask());
826 break;
827 case ISD::SRCVALUE:
828 ID.AddPointer(cast<SrcValueSDNode>(N)->getValue());
829 break;
830 case ISD::FrameIndex:
832 ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex());
833 break;
835 ID.AddInteger(cast<PseudoProbeSDNode>(N)->getGuid());
836 ID.AddInteger(cast<PseudoProbeSDNode>(N)->getIndex());
837 ID.AddInteger(cast<PseudoProbeSDNode>(N)->getAttributes());
838 break;
839 case ISD::JumpTable:
841 ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex());
842 ID.AddInteger(cast<JumpTableSDNode>(N)->getTargetFlags());
843 break;
847 ID.AddInteger(CP->getAlign().value());
848 ID.AddInteger(CP->getOffset());
851 else
852 ID.AddPointer(CP->getConstVal());
853 ID.AddInteger(CP->getTargetFlags());
854 break;
855 }
856 case ISD::TargetIndex: {
858 ID.AddInteger(TI->getIndex());
859 ID.AddInteger(TI->getOffset());
860 ID.AddInteger(TI->getTargetFlags());
861 break;
862 }
863 case ISD::LOAD: {
864 const LoadSDNode *LD = cast<LoadSDNode>(N);
865 ID.AddInteger(LD->getMemoryVT().getRawBits());
866 ID.AddInteger(LD->getRawSubclassData());
867 ID.AddInteger(LD->getPointerInfo().getAddrSpace());
868 ID.AddInteger(LD->getMemOperand()->getFlags());
869 break;
870 }
871 case ISD::STORE: {
872 const StoreSDNode *ST = cast<StoreSDNode>(N);
873 ID.AddInteger(ST->getMemoryVT().getRawBits());
874 ID.AddInteger(ST->getRawSubclassData());
875 ID.AddInteger(ST->getPointerInfo().getAddrSpace());
876 ID.AddInteger(ST->getMemOperand()->getFlags());
877 break;
878 }
879 case ISD::VP_LOAD: {
880 const VPLoadSDNode *ELD = cast<VPLoadSDNode>(N);
881 ID.AddInteger(ELD->getMemoryVT().getRawBits());
882 ID.AddInteger(ELD->getRawSubclassData());
883 ID.AddInteger(ELD->getPointerInfo().getAddrSpace());
884 ID.AddInteger(ELD->getMemOperand()->getFlags());
885 break;
886 }
887 case ISD::VP_LOAD_FF: {
888 const auto *LD = cast<VPLoadFFSDNode>(N);
889 ID.AddInteger(LD->getMemoryVT().getRawBits());
890 ID.AddInteger(LD->getRawSubclassData());
891 ID.AddInteger(LD->getPointerInfo().getAddrSpace());
892 ID.AddInteger(LD->getMemOperand()->getFlags());
893 break;
894 }
895 case ISD::VP_STORE: {
896 const VPStoreSDNode *EST = cast<VPStoreSDNode>(N);
897 ID.AddInteger(EST->getMemoryVT().getRawBits());
898 ID.AddInteger(EST->getRawSubclassData());
899 ID.AddInteger(EST->getPointerInfo().getAddrSpace());
900 ID.AddInteger(EST->getMemOperand()->getFlags());
901 break;
902 }
903 case ISD::EXPERIMENTAL_VP_STRIDED_LOAD: {
905 ID.AddInteger(SLD->getMemoryVT().getRawBits());
906 ID.AddInteger(SLD->getRawSubclassData());
907 ID.AddInteger(SLD->getPointerInfo().getAddrSpace());
908 break;
909 }
910 case ISD::EXPERIMENTAL_VP_STRIDED_STORE: {
912 ID.AddInteger(SST->getMemoryVT().getRawBits());
913 ID.AddInteger(SST->getRawSubclassData());
914 ID.AddInteger(SST->getPointerInfo().getAddrSpace());
915 break;
916 }
917 case ISD::VP_GATHER: {
919 ID.AddInteger(EG->getMemoryVT().getRawBits());
920 ID.AddInteger(EG->getRawSubclassData());
921 ID.AddInteger(EG->getPointerInfo().getAddrSpace());
922 ID.AddInteger(EG->getMemOperand()->getFlags());
923 break;
924 }
925 case ISD::VP_SCATTER: {
927 ID.AddInteger(ES->getMemoryVT().getRawBits());
928 ID.AddInteger(ES->getRawSubclassData());
929 ID.AddInteger(ES->getPointerInfo().getAddrSpace());
930 ID.AddInteger(ES->getMemOperand()->getFlags());
931 break;
932 }
933 case ISD::MLOAD: {
935 ID.AddInteger(MLD->getMemoryVT().getRawBits());
936 ID.AddInteger(MLD->getRawSubclassData());
937 ID.AddInteger(MLD->getPointerInfo().getAddrSpace());
938 ID.AddInteger(MLD->getMemOperand()->getFlags());
939 break;
940 }
941 case ISD::MSTORE: {
943 ID.AddInteger(MST->getMemoryVT().getRawBits());
944 ID.AddInteger(MST->getRawSubclassData());
945 ID.AddInteger(MST->getPointerInfo().getAddrSpace());
946 ID.AddInteger(MST->getMemOperand()->getFlags());
947 break;
948 }
949 case ISD::MGATHER: {
951 ID.AddInteger(MG->getMemoryVT().getRawBits());
952 ID.AddInteger(MG->getRawSubclassData());
953 ID.AddInteger(MG->getPointerInfo().getAddrSpace());
954 ID.AddInteger(MG->getMemOperand()->getFlags());
955 break;
956 }
957 case ISD::MSCATTER: {
959 ID.AddInteger(MS->getMemoryVT().getRawBits());
960 ID.AddInteger(MS->getRawSubclassData());
961 ID.AddInteger(MS->getPointerInfo().getAddrSpace());
962 ID.AddInteger(MS->getMemOperand()->getFlags());
963 break;
964 }
967 case ISD::ATOMIC_SWAP:
979 case ISD::ATOMIC_LOAD:
980 case ISD::ATOMIC_STORE: {
981 const AtomicSDNode *AT = cast<AtomicSDNode>(N);
982 ID.AddInteger(AT->getMemoryVT().getRawBits());
983 ID.AddInteger(AT->getRawSubclassData());
984 ID.AddInteger(AT->getPointerInfo().getAddrSpace());
985 ID.AddInteger(AT->getMemOperand()->getFlags());
986 break;
987 }
988 case ISD::VECTOR_SHUFFLE: {
989 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(N)->getMask();
990 for (int M : Mask)
991 ID.AddInteger(M);
992 break;
993 }
994 case ISD::ADDRSPACECAST: {
996 ID.AddInteger(ASC->getSrcAddressSpace());
997 ID.AddInteger(ASC->getDestAddressSpace());
998 break;
999 }
1001 case ISD::BlockAddress: {
1003 ID.AddPointer(BA->getBlockAddress());
1004 ID.AddInteger(BA->getOffset());
1005 ID.AddInteger(BA->getTargetFlags());
1006 break;
1007 }
1008 case ISD::AssertAlign:
1009 ID.AddInteger(cast<AssertAlignSDNode>(N)->getAlign().value());
1010 break;
1011 case ISD::PREFETCH:
1014 // Handled by MemIntrinsicSDNode check after the switch.
1015 break;
1016 case ISD::MDNODE_SDNODE:
1017 ID.AddPointer(cast<MDNodeSDNode>(N)->getMD());
1018 break;
1019 } // end switch (N->getOpcode())
1020
1021 // MemIntrinsic nodes could also have subclass data, address spaces, and flags
1022 // to check.
1023 if (auto *MN = dyn_cast<MemIntrinsicSDNode>(N)) {
1024 ID.AddInteger(MN->getRawSubclassData());
1025 ID.AddInteger(MN->getMemoryVT().getRawBits());
1026 for (const MachineMemOperand *MMO : MN->memoperands()) {
1027 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
1028 ID.AddInteger(MMO->getFlags());
1029 }
1030 }
1031}
1032
1033/// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID
1034/// data.
1035static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) {
1036 AddNodeIDOpcode(ID, N->getOpcode());
1037 // Add the return value info.
1038 AddNodeIDValueTypes(ID, N->getVTList());
1039 // Add the operand info.
1040 AddNodeIDOperands(ID, N->ops());
1041
1042 // Handle SDNode leafs with special info.
1043 AddNodeIDCustom(ID, N);
1044}
1045
1046//===----------------------------------------------------------------------===//
1047// SelectionDAG Class
1048//===----------------------------------------------------------------------===//
1049
1050/// doNotCSE - Return true if CSE should not be performed for this node.
1051static bool doNotCSE(SDNode *N) {
1052 if (N->getValueType(0) == MVT::Glue)
1053 return true; // Never CSE anything that produces a glue result.
1054
1055 switch (N->getOpcode()) {
1056 default: break;
1057 case ISD::HANDLENODE:
1058 case ISD::EH_LABEL:
1059 return true; // Never CSE these nodes.
1060 }
1061
1062 // Check that remaining values produced are not flags.
1063 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
1064 if (N->getValueType(i) == MVT::Glue)
1065 return true; // Never CSE anything that produces a glue result.
1066
1067 return false;
1068}
1069
1070/// Construct a DemandedElts mask which demands all elements of \p V.
1071/// If \p V is not a fixed-length vector, then this will return a single bit.
1073 EVT VT = V.getValueType();
1074 // Since the number of lanes in a scalable vector is unknown at compile time,
1075 // we track one bit which is implicitly broadcast to all lanes. This means
1076 // that all lanes in a scalable vector are considered demanded.
1078 : APInt(1, 1);
1079}
1080
1081/// RemoveDeadNodes - This method deletes all unreachable nodes in the
1082/// SelectionDAG.
1084 // Create a dummy node (which is not added to allnodes), that adds a reference
1085 // to the root node, preventing it from being deleted.
1086 HandleSDNode Dummy(getRoot());
1087
1088 SmallVector<SDNode*, 128> DeadNodes;
1089
1090 // Add all obviously-dead nodes to the DeadNodes worklist.
1091 for (SDNode &Node : allnodes())
1092 if (Node.use_empty())
1093 DeadNodes.push_back(&Node);
1094
1095 RemoveDeadNodes(DeadNodes);
1096
1097 // If the root changed (e.g. it was a dead load, update the root).
1098 setRoot(Dummy.getValue());
1099}
1100
1101/// RemoveDeadNodes - This method deletes the unreachable nodes in the
1102/// given list, and any nodes that become unreachable as a result.
1104
1105 // Process the worklist, deleting the nodes and adding their uses to the
1106 // worklist.
1107 while (!DeadNodes.empty()) {
1108 SDNode *N = DeadNodes.pop_back_val();
1109 // Skip to next node if we've already managed to delete the node. This could
1110 // happen if replacing a node causes a node previously added to the node to
1111 // be deleted.
1112 if (N->getOpcode() == ISD::DELETED_NODE)
1113 continue;
1114
1115 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1116 DUL->NodeDeleted(N, nullptr);
1117
1118 // Take the node out of the appropriate CSE map.
1119 RemoveNodeFromCSEMaps(N);
1120
1121 // Next, brutally remove the operand list. This is safe to do, as there are
1122 // no cycles in the graph.
1123 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
1124 SDUse &Use = *I++;
1125 SDNode *Operand = Use.getNode();
1126 Use.set(SDValue());
1127
1128 // Now that we removed this operand, see if there are no uses of it left.
1129 if (Operand->use_empty())
1130 DeadNodes.push_back(Operand);
1131 }
1132
1133 DeallocateNode(N);
1134 }
1135}
1136
1138 SmallVector<SDNode*, 16> DeadNodes(1, N);
1139
1140 // Create a dummy node that adds a reference to the root node, preventing
1141 // it from being deleted. (This matters if the root is an operand of the
1142 // dead node.)
1143 HandleSDNode Dummy(getRoot());
1144
1145 RemoveDeadNodes(DeadNodes);
1146}
1147
1149 // First take this out of the appropriate CSE map.
1150 RemoveNodeFromCSEMaps(N);
1151
1152 // Finally, remove uses due to operands of this node, remove from the
1153 // AllNodes list, and delete the node.
1154 DeleteNodeNotInCSEMaps(N);
1155}
1156
1157void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
1158 assert(N->getIterator() != AllNodes.begin() &&
1159 "Cannot delete the entry node!");
1160 assert(N->use_empty() && "Cannot delete a node that is not dead!");
1161
1162 // Drop all of the operands and decrement used node's use counts.
1163 N->DropOperands();
1164
1165 DeallocateNode(N);
1166}
1167
1168void SDDbgInfo::add(SDDbgValue *V, bool isParameter) {
1169 assert(!(V->isVariadic() && isParameter));
1170 if (isParameter)
1171 ByvalParmDbgValues.push_back(V);
1172 else
1173 DbgValues.push_back(V);
1174 for (const SDNode *Node : V->getSDNodes())
1175 if (Node)
1176 DbgValMap[Node].push_back(V);
1177}
1178
1180 DbgValMapType::iterator I = DbgValMap.find(Node);
1181 if (I == DbgValMap.end())
1182 return;
1183 for (auto &Val: I->second)
1184 Val->setIsInvalidated();
1185 DbgValMap.erase(I);
1186}
1187
1188void SelectionDAG::DeallocateNode(SDNode *N) {
1189 // If we have operands, deallocate them.
1191
1192 NodeAllocator.Deallocate(AllNodes.remove(N));
1193
1194 // Set the opcode to DELETED_NODE to help catch bugs when node
1195 // memory is reallocated.
1196 // FIXME: There are places in SDag that have grown a dependency on the opcode
1197 // value in the released node.
1198 __asan_unpoison_memory_region(&N->NodeType, sizeof(N->NodeType));
1199 N->NodeType = ISD::DELETED_NODE;
1200
1201 // If any of the SDDbgValue nodes refer to this SDNode, invalidate
1202 // them and forget about that node.
1203 DbgInfo->erase(N);
1204
1205 // Invalidate extra info.
1206 SDEI.erase(N);
1207}
1208
1209#ifndef NDEBUG
1210/// VerifySDNode - Check the given SDNode. Aborts if it is invalid.
1211void SelectionDAG::verifyNode(SDNode *N) const {
1212 switch (N->getOpcode()) {
1213 default:
1214 if (N->isTargetOpcode())
1216 break;
1217 case ISD::BUILD_PAIR: {
1218 EVT VT = N->getValueType(0);
1219 assert(N->getNumValues() == 1 && "Too many results!");
1220 assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) &&
1221 "Wrong return type!");
1222 assert(N->getNumOperands() == 2 && "Wrong number of operands!");
1223 assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() &&
1224 "Mismatched operand types!");
1225 assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() &&
1226 "Wrong operand type!");
1227 assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() &&
1228 "Wrong return type size");
1229 break;
1230 }
1231 case ISD::BUILD_VECTOR: {
1232 assert(N->getNumValues() == 1 && "Too many results!");
1233 assert(N->getValueType(0).isVector() && "Wrong return type!");
1234 assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() &&
1235 "Wrong number of operands!");
1236 EVT EltVT = N->getValueType(0).getVectorElementType();
1237 for (const SDUse &Op : N->ops()) {
1238 assert((Op.getValueType() == EltVT ||
1239 (EltVT.isInteger() && Op.getValueType().isInteger() &&
1240 EltVT.bitsLE(Op.getValueType()))) &&
1241 "Wrong operand type!");
1242 assert(Op.getValueType() == N->getOperand(0).getValueType() &&
1243 "Operands must all have the same type");
1244 }
1245 break;
1246 }
1247 case ISD::SADDO:
1248 case ISD::UADDO:
1249 case ISD::SSUBO:
1250 case ISD::USUBO:
1251 assert(N->getNumValues() == 2 && "Wrong number of results!");
1252 assert(N->getVTList().NumVTs == 2 && N->getNumOperands() == 2 &&
1253 "Invalid add/sub overflow op!");
1254 assert(N->getVTList().VTs[0].isInteger() &&
1255 N->getVTList().VTs[1].isInteger() &&
1256 N->getOperand(0).getValueType() == N->getOperand(1).getValueType() &&
1257 N->getOperand(0).getValueType() == N->getVTList().VTs[0] &&
1258 "Binary operator types must match!");
1259 break;
1260 }
1261}
1262#endif // NDEBUG
1263
1264/// Insert a newly allocated node into the DAG.
1265///
1266/// Handles insertion into the all nodes list and CSE map, as well as
1267/// verification and other common operations when a new node is allocated.
1268void SelectionDAG::InsertNode(SDNode *N) {
1269 AllNodes.push_back(N);
1270#ifndef NDEBUG
1271 N->PersistentId = NextPersistentId++;
1272 verifyNode(N);
1273#endif
1274 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1275 DUL->NodeInserted(N);
1276}
1277
1278/// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
1279/// correspond to it. This is useful when we're about to delete or repurpose
1280/// the node. We don't want future request for structurally identical nodes
1281/// to return N anymore.
1282bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
1283 bool Erased = false;
1284 switch (N->getOpcode()) {
1285 case ISD::HANDLENODE: return false; // noop.
1286 case ISD::CONDCODE:
1287 assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
1288 "Cond code doesn't exist!");
1289 Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != nullptr;
1290 CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = nullptr;
1291 break;
1293 Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
1294 break;
1296 ExternalSymbolSDNode *ESN = cast<ExternalSymbolSDNode>(N);
1297 Erased = TargetExternalSymbols.erase(std::pair<std::string, unsigned>(
1298 ESN->getSymbol(), ESN->getTargetFlags()));
1299 break;
1300 }
1301 case ISD::MCSymbol: {
1302 auto *MCSN = cast<MCSymbolSDNode>(N);
1303 Erased = MCSymbols.erase(MCSN->getMCSymbol());
1304 break;
1305 }
1306 case ISD::VALUETYPE: {
1307 EVT VT = cast<VTSDNode>(N)->getVT();
1308 if (VT.isExtended()) {
1309 Erased = ExtendedValueTypeNodes.erase(VT);
1310 } else {
1311 Erased = ValueTypeNodes[VT.getSimpleVT().SimpleTy] != nullptr;
1312 ValueTypeNodes[VT.getSimpleVT().SimpleTy] = nullptr;
1313 }
1314 break;
1315 }
1316 default:
1317 // Remove it from the CSE Map.
1318 assert(N->getOpcode() != ISD::DELETED_NODE && "DELETED_NODE in CSEMap!");
1319 assert(N->getOpcode() != ISD::EntryToken && "EntryToken in CSEMap!");
1320 Erased = CSEMap.RemoveNode(N);
1321 break;
1322 }
1323#ifndef NDEBUG
1324 // Verify that the node was actually in one of the CSE maps, unless it has a
1325 // glue result (which cannot be CSE'd) or is one of the special cases that are
1326 // not subject to CSE.
1327 if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Glue &&
1328 !N->isMachineOpcode() && !doNotCSE(N)) {
1329 N->dump(this);
1330 dbgs() << "\n";
1331 llvm_unreachable("Node is not in map!");
1332 }
1333#endif
1334 return Erased;
1335}
1336
1337/// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE
1338/// maps and modified in place. Add it back to the CSE maps, unless an identical
1339/// node already exists, in which case transfer all its users to the existing
1340/// node. This transfer can potentially trigger recursive merging.
1341void
1342SelectionDAG::AddModifiedNodeToCSEMaps(SDNode *N) {
1343 // For node types that aren't CSE'd, just act as if no identical node
1344 // already exists.
1345 if (!doNotCSE(N)) {
1346 SDNode *Existing = CSEMap.GetOrInsertNode(N);
1347 if (Existing != N) {
1348 // If there was already an existing matching node, use ReplaceAllUsesWith
1349 // to replace the dead one with the existing one. This can cause
1350 // recursive merging of other unrelated nodes down the line.
1351 Existing->intersectFlagsWith(N->getFlags());
1352 if (auto *MemNode = dyn_cast<MemSDNode>(Existing)) {
1354 cast<MemSDNode>(N)->memoperands();
1355 // Range and cache hint metadata are not part of the DAG CSE key because
1356 // we prefer to CSE even when metadata does not match. Merge potentially
1357 // differing metadata conservatively.
1358 MemNode->refineMMOMetadata(NewMMOs);
1359 }
1360 ReplaceAllUsesWith(N, Existing);
1361
1362 // N is now dead. Inform the listeners and delete it.
1363 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1364 DUL->NodeDeleted(N, Existing);
1365 DeleteNodeNotInCSEMaps(N);
1366 return;
1367 }
1368 }
1369
1370 // If the node doesn't already exist, we updated it. Inform listeners.
1371 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1372 DUL->NodeUpdated(N);
1373}
1374
1375/// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1376/// were replaced with those specified. If this node is never memoized,
1377/// return null, otherwise return a pointer to the slot it would take. If a
1378/// node already exists with these operands, the slot will be non-null.
1379SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op,
1380 void *&InsertPos) {
1381 if (doNotCSE(N))
1382 return nullptr;
1383
1384 SDValue Ops[] = { Op };
1385 FoldingSetNodeID ID;
1386 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1387 AddNodeIDCustom(ID, N);
1388 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1389 if (Node)
1390 Node->intersectFlagsWith(N->getFlags());
1391 return Node;
1392}
1393
1394/// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1395/// were replaced with those specified. If this node is never memoized,
1396/// return null, otherwise return a pointer to the slot it would take. If a
1397/// node already exists with these operands, the slot will be non-null.
1398SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
1399 SDValue Op1, SDValue Op2,
1400 void *&InsertPos) {
1401 if (doNotCSE(N))
1402 return nullptr;
1403
1404 SDValue Ops[] = { Op1, Op2 };
1405 FoldingSetNodeID ID;
1406 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1407 AddNodeIDCustom(ID, N);
1408 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1409 if (Node)
1410 Node->intersectFlagsWith(N->getFlags());
1411 return Node;
1412}
1413
1414/// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1415/// were replaced with those specified. If this node is never memoized,
1416/// return null, otherwise return a pointer to the slot it would take. If a
1417/// node already exists with these operands, the slot will be non-null.
1418SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, ArrayRef<SDValue> Ops,
1419 void *&InsertPos) {
1420 if (doNotCSE(N))
1421 return nullptr;
1422
1423 FoldingSetNodeID ID;
1424 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1425 AddNodeIDCustom(ID, N);
1426 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1427 if (Node)
1428 Node->intersectFlagsWith(N->getFlags());
1429 return Node;
1430}
1431
1433 Type *Ty = VT == MVT::iPTR ? PointerType::get(*getContext(), 0)
1434 : VT.getTypeForEVT(*getContext());
1435
1436 return getDataLayout().getABITypeAlign(Ty);
1437}
1438
1439// EntryNode could meaningfully have debug info if we can find it...
1441 : TM(tm), OptLevel(OL), EntryNode(ISD::EntryToken, 0, DebugLoc(),
1442 getVTList(MVT::Other, MVT::Glue)),
1443 Root(getEntryNode()) {
1444 InsertNode(&EntryNode);
1445 DbgInfo = new SDDbgInfo();
1446}
1447
1449 OptimizationRemarkEmitter &NewORE, Pass *PassPtr,
1450 const TargetLibraryInfo *LibraryInfo,
1451 const LibcallLoweringInfo *LibcallsInfo,
1452 UniformityInfo *NewUA, ProfileSummaryInfo *PSIin,
1454 FunctionVarLocs const *VarLocs) {
1455 MF = &NewMF;
1456 SDAGISelPass = PassPtr;
1457 ORE = &NewORE;
1460 LibInfo = LibraryInfo;
1461 Libcalls = LibcallsInfo;
1462 Context = &MF->getFunction().getContext();
1463 UA = NewUA;
1464 PSI = PSIin;
1465 BFI = BFIin;
1466 MMI = &MMIin;
1467 FnVarLocs = VarLocs;
1468}
1469
1471 assert(!UpdateListeners && "Dangling registered DAGUpdateListeners");
1472 allnodes_clear();
1473 OperandRecycler.clear(OperandAllocator);
1474 delete DbgInfo;
1475}
1476
1478 return llvm::shouldOptimizeForSize(FLI->MBB->getBasicBlock(), PSI, BFI);
1479}
1480
1481void SelectionDAG::allnodes_clear() {
1482 assert(&*AllNodes.begin() == &EntryNode);
1483 AllNodes.remove(AllNodes.begin());
1484 while (!AllNodes.empty())
1485 DeallocateNode(&AllNodes.front());
1486#ifndef NDEBUG
1487 NextPersistentId = 0;
1488#endif
1489}
1490
1491SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
1492 void *&InsertPos) {
1493 SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
1494 if (N) {
1495 switch (N->getOpcode()) {
1496 default: break;
1497 case ISD::Constant:
1498 case ISD::ConstantFP:
1499 llvm_unreachable("Querying for Constant and ConstantFP nodes requires "
1500 "debug location. Use another overload.");
1501 }
1502 }
1503 return N;
1504}
1505
1506SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
1507 const SDLoc &DL, void *&InsertPos) {
1508 SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
1509 if (N) {
1510 switch (N->getOpcode()) {
1511 case ISD::Constant:
1512 case ISD::ConstantFP:
1513 // Erase debug location from the node if the node is used at several
1514 // different places. Do not propagate one location to all uses as it
1515 // will cause a worse single stepping debugging experience.
1516 if (N->getDebugLoc() != DL.getDebugLoc())
1517 N->setDebugLoc(DebugLoc());
1518 break;
1519 default:
1520 // When the node's point of use is located earlier in the instruction
1521 // sequence than its prior point of use, update its debug info to the
1522 // earlier location.
1523 if (DL.getIROrder() && DL.getIROrder() < N->getIROrder())
1524 N->setDebugLoc(DL.getDebugLoc());
1525 break;
1526 }
1527 }
1528 return N;
1529}
1530
1532 allnodes_clear();
1533 OperandRecycler.clear(OperandAllocator);
1534 OperandAllocator.Reset();
1535 CSEMap.clear();
1536
1537 ExtendedValueTypeNodes.clear();
1538 ExternalSymbols.clear();
1539 TargetExternalSymbols.clear();
1540 MCSymbols.clear();
1541 SDEI.clear();
1542 llvm::fill(CondCodeNodes, nullptr);
1543 llvm::fill(ValueTypeNodes, nullptr);
1544
1545 EntryNode.UseList = nullptr;
1546 InsertNode(&EntryNode);
1547 Root = getEntryNode();
1548 DbgInfo->clear();
1549}
1550
1552 return VT.bitsGT(Op.getValueType())
1553 ? getNode(ISD::FP_EXTEND, DL, VT, Op)
1554 : getNode(ISD::FP_ROUND, DL, VT, Op,
1555 getIntPtrConstant(0, DL, /*isTarget=*/true));
1556}
1557
1558std::pair<SDValue, SDValue>
1560 const SDLoc &DL, EVT VT) {
1561 assert(!VT.bitsEq(Op.getValueType()) &&
1562 "Strict no-op FP extend/round not allowed.");
1563 SDValue Res =
1564 VT.bitsGT(Op.getValueType())
1565 ? getNode(ISD::STRICT_FP_EXTEND, DL, {VT, MVT::Other}, {Chain, Op})
1566 : getNode(ISD::STRICT_FP_ROUND, DL, {VT, MVT::Other},
1567 {Chain, Op, getIntPtrConstant(0, DL, /*isTarget=*/true)});
1568
1569 return std::pair<SDValue, SDValue>(Res, SDValue(Res.getNode(), 1));
1570}
1571
1573 return VT.bitsGT(Op.getValueType()) ?
1574 getNode(ISD::ANY_EXTEND, DL, VT, Op) :
1575 getNode(ISD::TRUNCATE, DL, VT, Op);
1576}
1577
1579 return VT.bitsGT(Op.getValueType()) ?
1580 getNode(ISD::SIGN_EXTEND, DL, VT, Op) :
1581 getNode(ISD::TRUNCATE, DL, VT, Op);
1582}
1583
1585 return VT.bitsGT(Op.getValueType()) ?
1586 getNode(ISD::ZERO_EXTEND, DL, VT, Op) :
1587 getNode(ISD::TRUNCATE, DL, VT, Op);
1588}
1589
1591 EVT VT) {
1592 assert(!VT.isVector());
1593 auto Type = Op.getValueType();
1594 SDValue DestOp;
1595 if (Type == VT)
1596 return Op;
1597 auto Size = Op.getValueSizeInBits();
1598 DestOp = getBitcast(EVT::getIntegerVT(*Context, Size), Op);
1599 if (DestOp.getValueType() == VT)
1600 return DestOp;
1601
1602 return getAnyExtOrTrunc(DestOp, DL, VT);
1603}
1604
1606 EVT VT) {
1607 assert(!VT.isVector());
1608 auto Type = Op.getValueType();
1609 SDValue DestOp;
1610 if (Type == VT)
1611 return Op;
1612 auto Size = Op.getValueSizeInBits();
1613 DestOp = getBitcast(MVT::getIntegerVT(Size), Op);
1614 if (DestOp.getValueType() == VT)
1615 return DestOp;
1616
1617 return getSExtOrTrunc(DestOp, DL, VT);
1618}
1619
1621 EVT VT) {
1622 assert(!VT.isVector());
1623 auto Type = Op.getValueType();
1624 SDValue DestOp;
1625 if (Type == VT)
1626 return Op;
1627 auto Size = Op.getValueSizeInBits();
1628 DestOp = getBitcast(MVT::getIntegerVT(Size), Op);
1629 if (DestOp.getValueType() == VT)
1630 return DestOp;
1631
1632 return getZExtOrTrunc(DestOp, DL, VT);
1633}
1634
1636 EVT OpVT) {
1637 if (VT.bitsLE(Op.getValueType()))
1638 return getNode(ISD::TRUNCATE, SL, VT, Op);
1639
1640 TargetLowering::BooleanContent BType = TLI->getBooleanContents(OpVT);
1641 return getNode(TLI->getExtendForContent(BType), SL, VT, Op);
1642}
1643
1645 EVT OpVT = Op.getValueType();
1646 assert(VT.isInteger() && OpVT.isInteger() &&
1647 "Cannot getZeroExtendInReg FP types");
1648 assert(VT.isVector() == OpVT.isVector() &&
1649 "getZeroExtendInReg type should be vector iff the operand "
1650 "type is vector!");
1651 assert((!VT.isVector() ||
1653 "Vector element counts must match in getZeroExtendInReg");
1654 assert(VT.getScalarType().bitsLE(OpVT.getScalarType()) && "Not extending!");
1655 if (OpVT == VT)
1656 return Op;
1657 // TODO: Use computeKnownBits instead of AssertZext.
1658 if (Op.getOpcode() == ISD::AssertZext && cast<VTSDNode>(Op.getOperand(1))
1659 ->getVT()
1660 .getScalarType()
1661 .bitsLE(VT.getScalarType()))
1662 return Op;
1664 VT.getScalarSizeInBits());
1665 return getNode(ISD::AND, DL, OpVT, Op, getConstant(Imm, DL, OpVT));
1666}
1667
1669 // Only unsigned pointer semantics are supported right now. In the future this
1670 // might delegate to TLI to check pointer signedness.
1671 return getZExtOrTrunc(Op, DL, VT);
1672}
1673
1675 // Only unsigned pointer semantics are supported right now. In the future this
1676 // might delegate to TLI to check pointer signedness.
1677 return getZeroExtendInReg(Op, DL, VT);
1678}
1679
1681 return getNode(ISD::SUB, DL, VT, getConstant(0, DL, VT), Val);
1682}
1683
1684/// getNOT - Create a bitwise NOT operation as (XOR Val, -1).
1686 return getNode(ISD::XOR, DL, VT, Val, getAllOnesConstant(DL, VT));
1687}
1688
1690 SDValue TrueValue = getBoolConstant(true, DL, VT, VT);
1691 return getNode(ISD::XOR, DL, VT, Val, TrueValue);
1692}
1693
1695 EVT OpVT) {
1696 if (!V)
1697 return getConstant(0, DL, VT);
1698
1699 switch (TLI->getBooleanContents(OpVT)) {
1702 return getConstant(1, DL, VT);
1704 return getAllOnesConstant(DL, VT);
1705 }
1706 llvm_unreachable("Unexpected boolean content enum!");
1707}
1708
1710 bool isT, bool isO) {
1711 return getConstant(APInt(VT.getScalarSizeInBits(), Val, /*isSigned=*/false),
1712 DL, VT, isT, isO);
1713}
1714
1716 bool isT, bool isO) {
1717 return getConstant(*ConstantInt::get(*Context, Val), DL, VT, isT, isO);
1718}
1719
1721 EVT VT, bool isT, bool isO) {
1722 assert(VT.isInteger() && "Cannot create FP integer constant!");
1723
1724 EVT EltVT = VT.getScalarType();
1725 const ConstantInt *Elt = &Val;
1726
1727 // Vector splats are explicit within the DAG, with ConstantSDNode holding the
1728 // to-be-splatted scalar ConstantInt.
1729 if (isa<VectorType>(Elt->getType()))
1730 Elt = ConstantInt::get(*getContext(), Elt->getValue());
1731
1732 // In some cases the vector type is legal but the element type is illegal and
1733 // needs to be promoted, for example v8i8 on ARM. In this case, promote the
1734 // inserted value (the type does not need to match the vector element type).
1735 // Any extra bits introduced will be truncated away.
1736 if (VT.isVector() && TLI->getTypeAction(*getContext(), EltVT) ==
1738 EltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1739 APInt NewVal;
1740 if (TLI->isSExtCheaperThanZExt(VT.getScalarType(), EltVT))
1741 NewVal = Elt->getValue().sextOrTrunc(EltVT.getSizeInBits());
1742 else
1743 NewVal = Elt->getValue().zextOrTrunc(EltVT.getSizeInBits());
1744 Elt = ConstantInt::get(*getContext(), NewVal);
1745 }
1746 // In other cases the element type is illegal and needs to be expanded, for
1747 // example v2i64 on MIPS32. In this case, find the nearest legal type, split
1748 // the value into n parts and use a vector type with n-times the elements.
1749 // Then bitcast to the type requested.
1750 // Legalizing constants too early makes the DAGCombiner's job harder so we
1751 // only legalize if the DAG tells us we must produce legal types.
1752 else if (NewNodesMustHaveLegalTypes && VT.isVector() &&
1753 TLI->getTypeAction(*getContext(), EltVT) ==
1755 const APInt &NewVal = Elt->getValue();
1756 EVT ViaEltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1757 unsigned ViaEltSizeInBits = ViaEltVT.getSizeInBits();
1758
1759 // For scalable vectors, try to use a SPLAT_VECTOR_PARTS node.
1760 if (VT.isScalableVector() ||
1761 TLI->isOperationLegal(ISD::SPLAT_VECTOR, VT)) {
1762 assert(EltVT.getSizeInBits() % ViaEltSizeInBits == 0 &&
1763 "Can only handle an even split!");
1764 unsigned Parts = EltVT.getSizeInBits() / ViaEltSizeInBits;
1765
1766 SmallVector<SDValue, 2> ScalarParts;
1767 for (unsigned i = 0; i != Parts; ++i)
1768 ScalarParts.push_back(getConstant(
1769 NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL,
1770 ViaEltVT, isT, isO));
1771
1772 return getNode(ISD::SPLAT_VECTOR_PARTS, DL, VT, ScalarParts);
1773 }
1774
1775 unsigned ViaVecNumElts = VT.getSizeInBits() / ViaEltSizeInBits;
1776 EVT ViaVecVT = EVT::getVectorVT(*getContext(), ViaEltVT, ViaVecNumElts);
1777
1778 // Check the temporary vector is the correct size. If this fails then
1779 // getTypeToTransformTo() probably returned a type whose size (in bits)
1780 // isn't a power-of-2 factor of the requested type size.
1781 assert(ViaVecVT.getSizeInBits() == VT.getSizeInBits());
1782
1783 SmallVector<SDValue, 2> EltParts;
1784 for (unsigned i = 0; i < ViaVecNumElts / VT.getVectorNumElements(); ++i)
1785 EltParts.push_back(getConstant(
1786 NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL,
1787 ViaEltVT, isT, isO));
1788
1789 // EltParts is currently in little endian order. If we actually want
1790 // big-endian order then reverse it now.
1791 if (getDataLayout().isBigEndian())
1792 std::reverse(EltParts.begin(), EltParts.end());
1793
1794 // The elements must be reversed when the element order is different
1795 // to the endianness of the elements (because the BITCAST is itself a
1796 // vector shuffle in this situation). However, we do not need any code to
1797 // perform this reversal because getConstant() is producing a vector
1798 // splat.
1799 // This situation occurs in MIPS MSA.
1800
1802 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
1803 llvm::append_range(Ops, EltParts);
1804
1805 SDValue V =
1806 getNode(ISD::BITCAST, DL, VT, getBuildVector(ViaVecVT, DL, Ops));
1807 return V;
1808 }
1809
1810 assert(Elt->getBitWidth() == EltVT.getSizeInBits() &&
1811 "APInt size does not match type size!");
1812 unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
1813 SDVTList VTs = getVTList(EltVT);
1815 AddNodeIDNode(ID, Opc, VTs, {});
1816 ID.AddPointer(Elt);
1817 ID.AddBoolean(isO);
1818 void *IP = nullptr;
1819 SDNode *N = nullptr;
1820 if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1821 if (!VT.isVector())
1822 return SDValue(N, 0);
1823
1824 if (!N) {
1825 N = newSDNode<ConstantSDNode>(isT, isO, Elt, VTs);
1826 if (!isT)
1827 N->setDebugLoc(DL.getDebugLoc());
1828 CSEMap.InsertNode(N, IP);
1829 InsertNode(N);
1830 NewSDValueDbgMsg(SDValue(N, 0), "Creating constant: ", this);
1831 }
1832
1833 SDValue Result(N, 0);
1834 if (VT.isVector())
1835 Result = getSplat(VT, DL, Result);
1836 return Result;
1837}
1838
1840 bool isT, bool isO) {
1841 unsigned Size = VT.getScalarSizeInBits();
1842 return getConstant(APInt(Size, Val, /*isSigned=*/true), DL, VT, isT, isO);
1843}
1844
1846 bool IsOpaque) {
1848 IsTarget, IsOpaque);
1849}
1850
1852 bool isTarget) {
1853 return getConstant(Val, DL, TLI->getPointerTy(getDataLayout()), isTarget);
1854}
1855
1857 const SDLoc &DL) {
1858 assert(VT.isInteger() && "Shift amount is not an integer type!");
1859 EVT ShiftVT = TLI->getShiftAmountTy(VT, getDataLayout());
1860 return getConstant(Val, DL, ShiftVT);
1861}
1862
1864 const SDLoc &DL) {
1865 assert(Val.ult(VT.getScalarSizeInBits()) && "Out of range shift");
1866 return getShiftAmountConstant(Val.getZExtValue(), VT, DL);
1867}
1868
1870 bool isTarget) {
1871 return getConstant(Val, DL, TLI->getVectorIdxTy(getDataLayout()), isTarget);
1872}
1873
1875 bool isTarget) {
1876 return getConstantFP(*ConstantFP::get(*getContext(), V), DL, VT, isTarget);
1877}
1878
1880 EVT VT, bool isTarget) {
1881 assert(VT.isFloatingPoint() && "Cannot create integer FP constant!");
1882
1883 EVT EltVT = VT.getScalarType();
1884 const ConstantFP *Elt = &V;
1885
1886 // Vector splats are explicit within the DAG, with ConstantFPSDNode holding
1887 // the to-be-splatted scalar ConstantFP.
1888 if (isa<VectorType>(Elt->getType()))
1889 Elt = ConstantFP::get(*getContext(), Elt->getValue());
1890
1891 // Do the map lookup using the actual bit pattern for the floating point
1892 // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
1893 // we don't have issues with SNANs.
1894 unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
1895 SDVTList VTs = getVTList(EltVT);
1897 AddNodeIDNode(ID, Opc, VTs, {});
1898 ID.AddPointer(Elt);
1899 void *IP = nullptr;
1900 SDNode *N = nullptr;
1901 if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1902 if (!VT.isVector())
1903 return SDValue(N, 0);
1904
1905 if (!N) {
1906 N = newSDNode<ConstantFPSDNode>(isTarget, Elt, VTs);
1907 CSEMap.InsertNode(N, IP);
1908 InsertNode(N);
1909 }
1910
1911 SDValue Result(N, 0);
1912 if (VT.isVector())
1913 Result = getSplat(VT, DL, Result);
1914 NewSDValueDbgMsg(Result, "Creating fp constant: ", this);
1915 return Result;
1916}
1917
1919 bool isTarget) {
1920 EVT EltVT = VT.getScalarType();
1921 if (EltVT == MVT::f32)
1922 return getConstantFP(APFloat((float)Val), DL, VT, isTarget);
1923 if (EltVT == MVT::f64)
1924 return getConstantFP(APFloat(Val), DL, VT, isTarget);
1925 if (EltVT == MVT::f80 || EltVT == MVT::f128 || EltVT == MVT::ppcf128 ||
1926 EltVT == MVT::f16 || EltVT == MVT::bf16) {
1927 bool Ignored;
1928 APFloat APF = APFloat(Val);
1930 &Ignored);
1931 return getConstantFP(APF, DL, VT, isTarget);
1932 }
1933 llvm_unreachable("Unsupported type in getConstantFP");
1934}
1935
1937 EVT VT, int64_t Offset, bool isTargetGA,
1938 unsigned TargetFlags) {
1939 assert((TargetFlags == 0 || isTargetGA) &&
1940 "Cannot set target flags on target-independent globals");
1941
1942 // Truncate (with sign-extension) the offset value to the pointer size.
1944 if (BitWidth < 64)
1946
1947 unsigned Opc;
1948 if (GV->isThreadLocal())
1950 else
1952
1953 SDVTList VTs = getVTList(VT);
1955 AddNodeIDNode(ID, Opc, VTs, {});
1956 ID.AddPointer(GV);
1957 ID.AddInteger(Offset);
1958 ID.AddInteger(TargetFlags);
1959 void *IP = nullptr;
1960 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
1961 return SDValue(E, 0);
1962
1963 auto *N = newSDNode<GlobalAddressSDNode>(
1964 Opc, DL.getIROrder(), DL.getDebugLoc(), GV, VTs, Offset, TargetFlags);
1965 CSEMap.InsertNode(N, IP);
1966 InsertNode(N);
1967 return SDValue(N, 0);
1968}
1969
1971 SDVTList VTs = getVTList(MVT::Untyped);
1974 ID.AddPointer(GV);
1975 void *IP = nullptr;
1976 if (SDNode *E = FindNodeOrInsertPos(ID, SDLoc(), IP))
1977 return SDValue(E, 0);
1978
1979 auto *N = newSDNode<DeactivationSymbolSDNode>(GV, VTs);
1980 CSEMap.InsertNode(N, IP);
1981 InsertNode(N);
1982 return SDValue(N, 0);
1983}
1984
1985SDValue SelectionDAG::getFrameIndex(int FI, EVT VT, bool isTarget) {
1986 unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
1987 SDVTList VTs = getVTList(VT);
1989 AddNodeIDNode(ID, Opc, VTs, {});
1990 ID.AddInteger(FI);
1991 void *IP = nullptr;
1992 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1993 return SDValue(E, 0);
1994
1995 auto *N = newSDNode<FrameIndexSDNode>(FI, VTs, isTarget);
1996 CSEMap.InsertNode(N, IP);
1997 InsertNode(N);
1998 return SDValue(N, 0);
1999}
2000
2001SDValue SelectionDAG::getJumpTable(int JTI, EVT VT, bool isTarget,
2002 unsigned TargetFlags) {
2003 assert((TargetFlags == 0 || isTarget) &&
2004 "Cannot set target flags on target-independent jump tables");
2005 unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
2006 SDVTList VTs = getVTList(VT);
2008 AddNodeIDNode(ID, Opc, VTs, {});
2009 ID.AddInteger(JTI);
2010 ID.AddInteger(TargetFlags);
2011 void *IP = nullptr;
2012 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2013 return SDValue(E, 0);
2014
2015 auto *N = newSDNode<JumpTableSDNode>(JTI, VTs, isTarget, TargetFlags);
2016 CSEMap.InsertNode(N, IP);
2017 InsertNode(N);
2018 return SDValue(N, 0);
2019}
2020
2022 const SDLoc &DL) {
2024 return getNode(ISD::JUMP_TABLE_DEBUG_INFO, DL, MVT::Other, Chain,
2025 getTargetConstant(static_cast<uint64_t>(JTI), DL, PTy, true));
2026}
2027
2029 MaybeAlign Alignment, int Offset,
2030 bool isTarget, unsigned TargetFlags) {
2031 assert((TargetFlags == 0 || isTarget) &&
2032 "Cannot set target flags on target-independent globals");
2033 if (!Alignment)
2034 Alignment = shouldOptForSize()
2035 ? getDataLayout().getABITypeAlign(C->getType())
2036 : getDataLayout().getPrefTypeAlign(C->getType());
2037 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
2038 SDVTList VTs = getVTList(VT);
2040 AddNodeIDNode(ID, Opc, VTs, {});
2041 ID.AddInteger(Alignment->value());
2042 ID.AddInteger(Offset);
2043 ID.AddPointer(C);
2044 ID.AddInteger(TargetFlags);
2045 void *IP = nullptr;
2046 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2047 return SDValue(E, 0);
2048
2049 auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VTs, Offset, *Alignment,
2050 TargetFlags);
2051 CSEMap.InsertNode(N, IP);
2052 InsertNode(N);
2053 SDValue V = SDValue(N, 0);
2054 NewSDValueDbgMsg(V, "Creating new constant pool: ", this);
2055 return V;
2056}
2057
2059 MaybeAlign Alignment, int Offset,
2060 bool isTarget, unsigned TargetFlags) {
2061 assert((TargetFlags == 0 || isTarget) &&
2062 "Cannot set target flags on target-independent globals");
2063 if (!Alignment)
2064 Alignment = getDataLayout().getPrefTypeAlign(C->getType());
2065 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
2066 SDVTList VTs = getVTList(VT);
2068 AddNodeIDNode(ID, Opc, VTs, {});
2069 ID.AddInteger(Alignment->value());
2070 ID.AddInteger(Offset);
2071 C->addSelectionDAGCSEId(ID);
2072 ID.AddInteger(TargetFlags);
2073 void *IP = nullptr;
2074 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2075 return SDValue(E, 0);
2076
2077 auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VTs, Offset, *Alignment,
2078 TargetFlags);
2079 CSEMap.InsertNode(N, IP);
2080 InsertNode(N);
2081 return SDValue(N, 0);
2082}
2083
2086 AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), {});
2087 ID.AddPointer(MBB);
2088 void *IP = nullptr;
2089 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2090 return SDValue(E, 0);
2091
2092 auto *N = newSDNode<BasicBlockSDNode>(MBB);
2093 CSEMap.InsertNode(N, IP);
2094 InsertNode(N);
2095 return SDValue(N, 0);
2096}
2097
2099 if (VT.isSimple() && (unsigned)VT.getSimpleVT().SimpleTy >=
2100 ValueTypeNodes.size())
2101 ValueTypeNodes.resize(VT.getSimpleVT().SimpleTy+1);
2102
2103 SDNode *&N = VT.isExtended() ?
2104 ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT().SimpleTy];
2105
2106 if (N) return SDValue(N, 0);
2107 N = newSDNode<VTSDNode>(VT);
2108 InsertNode(N);
2109 return SDValue(N, 0);
2110}
2111
2113 SDNode *&N = ExternalSymbols[Sym];
2114 if (N) return SDValue(N, 0);
2115 N = newSDNode<ExternalSymbolSDNode>(false, Sym, 0, getVTList(VT));
2116 InsertNode(N);
2117 return SDValue(N, 0);
2118}
2119
2120SDValue SelectionDAG::getExternalSymbol(RTLIB::LibcallImpl Libcall, EVT VT) {
2122 return getExternalSymbol(SymName.data(), VT);
2123}
2124
2126 SDNode *&N = MCSymbols[Sym];
2127 if (N)
2128 return SDValue(N, 0);
2129 N = newSDNode<MCSymbolSDNode>(Sym, getVTList(VT));
2130 InsertNode(N);
2131 return SDValue(N, 0);
2132}
2133
2135 unsigned TargetFlags) {
2136 SDNode *&N =
2137 TargetExternalSymbols[std::pair<std::string, unsigned>(Sym, TargetFlags)];
2138 if (N) return SDValue(N, 0);
2139 N = newSDNode<ExternalSymbolSDNode>(true, Sym, TargetFlags, getVTList(VT));
2140 InsertNode(N);
2141 return SDValue(N, 0);
2142}
2143
2145 EVT VT, unsigned TargetFlags) {
2147 return getTargetExternalSymbol(SymName.data(), VT, TargetFlags);
2148}
2149
2151 if ((unsigned)Cond >= CondCodeNodes.size())
2152 CondCodeNodes.resize(Cond+1);
2153
2154 if (!CondCodeNodes[Cond]) {
2155 auto *N = newSDNode<CondCodeSDNode>(Cond);
2156 CondCodeNodes[Cond] = N;
2157 InsertNode(N);
2158 }
2159
2160 return SDValue(CondCodeNodes[Cond], 0);
2161}
2162
2164 assert(MulImm.getBitWidth() == VT.getSizeInBits() &&
2165 "APInt size does not match type size!");
2166
2167 if (MulImm == 0)
2168 return getConstant(0, DL, VT);
2169
2170 const MachineFunction &MF = getMachineFunction();
2171 const Function &F = MF.getFunction();
2172 ConstantRange CR = getVScaleRange(&F, 64);
2173 if (const APInt *C = CR.getSingleElement())
2174 return getConstant(MulImm * C->getZExtValue(), DL, VT);
2175
2176 return getNode(ISD::VSCALE, DL, VT, getConstant(MulImm, DL, VT));
2177}
2178
2179/// \returns a value of type \p VT that represents the runtime value of \p
2180/// Quantity, i.e. scaled by vscale if it's scalable, or a fixed constant
2181/// otherwise. Quantity should be a FixedOrScalableQuantity, i.e. ElementCount
2182/// or TypeSize.
2183template <typename Ty>
2185 EVT VT, Ty Quantity) {
2186 if (Quantity.isScalable())
2187 return DAG.getVScale(
2188 DL, VT, APInt(VT.getSizeInBits(), Quantity.getKnownMinValue()));
2189
2190 return DAG.getConstant(Quantity.getKnownMinValue(), DL, VT);
2191}
2192
2194 ElementCount EC) {
2195 return getFixedOrScalableQuantity(*this, DL, VT, EC);
2196}
2197
2199 return getFixedOrScalableQuantity(*this, DL, VT, TS);
2200}
2201
2203 ElementCount EC) {
2204 EVT IdxVT = TLI->getVectorIdxTy(getDataLayout());
2205 EVT MaskVT = TLI->getSetCCResultType(getDataLayout(), *getContext(), DataVT);
2206 return getNode(ISD::GET_ACTIVE_LANE_MASK, DL, MaskVT,
2207 getConstant(0, DL, IdxVT), getElementCount(DL, IdxVT, EC));
2208}
2209
2211 APInt One(ResVT.getScalarSizeInBits(), 1);
2212 return getStepVector(DL, ResVT, One);
2213}
2214
2216 const APInt &StepVal) {
2217 assert(ResVT.getScalarSizeInBits() == StepVal.getBitWidth());
2218 if (ResVT.isScalableVector())
2219 return getNode(
2220 ISD::STEP_VECTOR, DL, ResVT,
2221 getTargetConstant(StepVal, DL, ResVT.getVectorElementType()));
2222
2223 SmallVector<SDValue, 16> OpsStepConstants;
2224 for (uint64_t i = 0; i < ResVT.getVectorNumElements(); i++)
2225 OpsStepConstants.push_back(
2226 getConstant(StepVal * i, DL, ResVT.getVectorElementType()));
2227 return getBuildVector(ResVT, DL, OpsStepConstants);
2228}
2229
2230/// Swaps the values of N1 and N2. Swaps all indices in the shuffle mask M that
2231/// point at N1 to point at N2 and indices that point at N2 to point at N1.
2236
2238 SDValue N2, ArrayRef<int> Mask) {
2239 assert(VT.getVectorNumElements() == Mask.size() &&
2240 "Must have the same number of vector elements as mask elements!");
2241 assert(VT == N1.getValueType() && VT == N2.getValueType() &&
2242 "Invalid VECTOR_SHUFFLE");
2243
2244 // Canonicalize shuffle undef, undef -> undef
2245 if (N1.isUndef() && N2.isUndef()) {
2246 if (N1.getOpcode() == ISD::POISON && N2.getOpcode() == ISD::POISON)
2247 return getPOISON(VT);
2248 return getUNDEF(VT);
2249 }
2250
2251 // Validate that all indices in Mask are within the range of the elements
2252 // input to the shuffle.
2253 int NElts = Mask.size();
2254 assert(llvm::all_of(Mask,
2255 [&](int M) { return M < (NElts * 2) && M >= -1; }) &&
2256 "Index out of range");
2257
2258 // Copy the mask so we can do any needed cleanup.
2259 SmallVector<int, 8> MaskVec(Mask);
2260
2261 // Canonicalize shuffle v, v -> v, poison
2262 if (N1 == N2) {
2263 N2 = getPOISON(VT);
2264 for (int i = 0; i != NElts; ++i)
2265 if (MaskVec[i] >= NElts) MaskVec[i] -= NElts;
2266 }
2267
2268 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
2269 if (N1.isUndef())
2270 commuteShuffle(N1, N2, MaskVec);
2271
2272 if (TLI->hasVectorBlend()) {
2273 // If shuffling a splat, try to blend the splat instead. We do this here so
2274 // that even when this arises during lowering we don't have to re-handle it.
2275 auto BlendSplat = [&](BuildVectorSDNode *BV, int Offset) {
2276 BitVector UndefElements;
2277 SDValue Splat = BV->getSplatValue(&UndefElements);
2278 if (!Splat)
2279 return;
2280
2281 for (int i = 0; i < NElts; ++i) {
2282 if (MaskVec[i] < Offset || MaskVec[i] >= (Offset + NElts))
2283 continue;
2284
2285 // If this input comes from undef, mark it as such.
2286 if (UndefElements[MaskVec[i] - Offset]) {
2287 MaskVec[i] = -1;
2288 continue;
2289 }
2290
2291 // If we can blend a non-undef lane, use that instead.
2292 if (!UndefElements[i])
2293 MaskVec[i] = i + Offset;
2294 }
2295 };
2296 if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
2297 BlendSplat(N1BV, 0);
2298 if (auto *N2BV = dyn_cast<BuildVectorSDNode>(N2))
2299 BlendSplat(N2BV, NElts);
2300 }
2301
2302 // Canonicalize all index into lhs, -> shuffle lhs, poison
2303 // Canonicalize all index into rhs, -> shuffle rhs, poison
2304 bool AllLHS = true, AllRHS = true;
2305 bool N2Undef = N2.isUndef();
2306 for (int i = 0; i != NElts; ++i) {
2307 if (MaskVec[i] >= NElts) {
2308 if (N2Undef)
2309 MaskVec[i] = -1;
2310 else
2311 AllLHS = false;
2312 } else if (MaskVec[i] >= 0) {
2313 AllRHS = false;
2314 }
2315 }
2316 if (AllLHS && AllRHS)
2317 return getPOISON(VT);
2318 if (AllLHS && !N2Undef)
2319 N2 = getPOISON(VT);
2320 if (AllRHS) {
2321 N1 = getPOISON(VT);
2322 commuteShuffle(N1, N2, MaskVec);
2323 }
2324 // Reset our undef status after accounting for the mask.
2325 N2Undef = N2.isUndef();
2326 // Re-check whether both sides ended up undef.
2327 if (N1.isUndef() && N2Undef) {
2328 if (N1.getOpcode() == ISD::POISON && N2.getOpcode() == ISD::POISON)
2329 return getPOISON(VT);
2330 return getUNDEF(VT);
2331 }
2332
2333 // If Identity shuffle return that node.
2334 bool Identity = true, AllSame = true;
2335 for (int i = 0; i != NElts; ++i) {
2336 if (MaskVec[i] >= 0 && MaskVec[i] != i) Identity = false;
2337 if (MaskVec[i] != MaskVec[0]) AllSame = false;
2338 }
2339 if (Identity && NElts)
2340 return N1;
2341
2342 // Shuffling a constant splat doesn't change the result.
2343 if (N2Undef) {
2344 SDValue V = N1;
2345
2346 // Look through any bitcasts. We check that these don't change the number
2347 // (and size) of elements and just changes their types.
2348 while (V.getOpcode() == ISD::BITCAST)
2349 V = V->getOperand(0);
2350
2351 // A splat should always show up as a build vector node.
2352 if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) {
2353 BitVector UndefElements;
2354 SDValue Splat = BV->getSplatValue(&UndefElements);
2355 // If this is a splat of an undef, shuffling it is also undef.
2356 if (Splat && Splat.isUndef())
2357 return Splat.getOpcode() == ISD::POISON ? getPOISON(VT) : getUNDEF(VT);
2358
2359 bool SameNumElts =
2360 V.getValueType().getVectorNumElements() == VT.getVectorNumElements();
2361
2362 // We only have a splat which can skip shuffles if there is a splatted
2363 // value and no undef lanes rearranged by the shuffle.
2364 if (Splat && UndefElements.none()) {
2365 // Splat of <x, x, ..., x>, return <x, x, ..., x>, provided that the
2366 // number of elements match or the value splatted is a zero constant.
2367 if (SameNumElts || isNullConstant(Splat))
2368 return N1;
2369 }
2370
2371 // If the shuffle itself creates a splat, build the vector directly.
2372 if (AllSame && SameNumElts) {
2373 EVT BuildVT = BV->getValueType(0);
2374 const SDValue &Splatted = BV->getOperand(MaskVec[0]);
2375 SDValue NewBV = getSplatBuildVector(BuildVT, dl, Splatted);
2376
2377 // We may have jumped through bitcasts, so the type of the
2378 // BUILD_VECTOR may not match the type of the shuffle.
2379 if (BuildVT != VT)
2380 NewBV = getNode(ISD::BITCAST, dl, VT, NewBV);
2381 return NewBV;
2382 }
2383 }
2384 }
2385
2386 SDVTList VTs = getVTList(VT);
2388 SDValue Ops[2] = { N1, N2 };
2390 for (int i = 0; i != NElts; ++i)
2391 ID.AddInteger(MaskVec[i]);
2392
2393 void* IP = nullptr;
2394 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
2395 return SDValue(E, 0);
2396
2397 // Allocate the mask array for the node out of the BumpPtrAllocator, since
2398 // SDNode doesn't have access to it. This memory will be "leaked" when
2399 // the node is deallocated, but recovered when the NodeAllocator is released.
2400 int *MaskAlloc = OperandAllocator.Allocate<int>(NElts);
2401 llvm::copy(MaskVec, MaskAlloc);
2402
2403 auto *N = newSDNode<ShuffleVectorSDNode>(VTs, dl.getIROrder(),
2404 dl.getDebugLoc(), MaskAlloc);
2405 createOperands(N, Ops);
2406
2407 CSEMap.InsertNode(N, IP);
2408 InsertNode(N);
2409 SDValue V = SDValue(N, 0);
2410 NewSDValueDbgMsg(V, "Creating new node: ", this);
2411 return V;
2412}
2413
2415 EVT VT = SV.getValueType(0);
2416 SmallVector<int, 8> MaskVec(SV.getMask());
2418
2419 SDValue Op0 = SV.getOperand(0);
2420 SDValue Op1 = SV.getOperand(1);
2421 return getVectorShuffle(VT, SDLoc(&SV), Op1, Op0, MaskVec);
2422}
2423
2425 SDVTList VTs = getVTList(VT);
2427 AddNodeIDNode(ID, ISD::Register, VTs, {});
2428 ID.AddInteger(Reg.id());
2429 void *IP = nullptr;
2430 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2431 return SDValue(E, 0);
2432
2433 auto *N = newSDNode<RegisterSDNode>(Reg, VTs);
2434 N->SDNodeBits.IsDivergent = TLI->isSDNodeSourceOfDivergence(N, FLI, UA);
2435 CSEMap.InsertNode(N, IP);
2436 InsertNode(N);
2437 return SDValue(N, 0);
2438}
2439
2442 AddNodeIDNode(ID, ISD::RegisterMask, getVTList(MVT::Untyped), {});
2443 ID.AddPointer(RegMask);
2444 void *IP = nullptr;
2445 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2446 return SDValue(E, 0);
2447
2448 auto *N = newSDNode<RegisterMaskSDNode>(RegMask);
2449 CSEMap.InsertNode(N, IP);
2450 InsertNode(N);
2451 return SDValue(N, 0);
2452}
2453
2455 MCSymbol *Label) {
2456 return getLabelNode(ISD::EH_LABEL, dl, Root, Label);
2457}
2458
2459SDValue SelectionDAG::getLabelNode(unsigned Opcode, const SDLoc &dl,
2460 SDValue Root, MCSymbol *Label) {
2462 SDValue Ops[] = { Root };
2463 AddNodeIDNode(ID, Opcode, getVTList(MVT::Other), Ops);
2464 ID.AddPointer(Label);
2465 void *IP = nullptr;
2466 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2467 return SDValue(E, 0);
2468
2469 auto *N =
2470 newSDNode<LabelSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), Label);
2471 createOperands(N, Ops);
2472
2473 CSEMap.InsertNode(N, IP);
2474 InsertNode(N);
2475 return SDValue(N, 0);
2476}
2477
2479 int64_t Offset, bool isTarget,
2480 unsigned TargetFlags) {
2481 unsigned Opc = isTarget ? ISD::TargetBlockAddress : ISD::BlockAddress;
2482 SDVTList VTs = getVTList(VT);
2483
2485 AddNodeIDNode(ID, Opc, VTs, {});
2486 ID.AddPointer(BA);
2487 ID.AddInteger(Offset);
2488 ID.AddInteger(TargetFlags);
2489 void *IP = nullptr;
2490 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2491 return SDValue(E, 0);
2492
2493 auto *N = newSDNode<BlockAddressSDNode>(Opc, VTs, BA, Offset, TargetFlags);
2494 CSEMap.InsertNode(N, IP);
2495 InsertNode(N);
2496 return SDValue(N, 0);
2497}
2498
2501 AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), {});
2502 ID.AddPointer(V);
2503
2504 void *IP = nullptr;
2505 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2506 return SDValue(E, 0);
2507
2508 auto *N = newSDNode<SrcValueSDNode>(V);
2509 CSEMap.InsertNode(N, IP);
2510 InsertNode(N);
2511 return SDValue(N, 0);
2512}
2513
2516 AddNodeIDNode(ID, ISD::MDNODE_SDNODE, getVTList(MVT::Other), {});
2517 ID.AddPointer(MD);
2518
2519 void *IP = nullptr;
2520 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2521 return SDValue(E, 0);
2522
2523 auto *N = newSDNode<MDNodeSDNode>(MD);
2524 CSEMap.InsertNode(N, IP);
2525 InsertNode(N);
2526 return SDValue(N, 0);
2527}
2528
2530 if (VT == V.getValueType())
2531 return V;
2532
2533 return getNode(ISD::BITCAST, SDLoc(V), VT, V);
2534}
2535
2537 unsigned SrcAS, unsigned DestAS) {
2538 SDVTList VTs = getVTList(VT);
2539 SDValue Ops[] = {Ptr};
2542 ID.AddInteger(SrcAS);
2543 ID.AddInteger(DestAS);
2544
2545 void *IP = nullptr;
2546 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
2547 return SDValue(E, 0);
2548
2549 auto *N = newSDNode<AddrSpaceCastSDNode>(dl.getIROrder(), dl.getDebugLoc(),
2550 VTs, SrcAS, DestAS);
2551 createOperands(N, Ops);
2552
2553 CSEMap.InsertNode(N, IP);
2554 InsertNode(N);
2555 return SDValue(N, 0);
2556}
2557
2559 return getNode(ISD::FREEZE, SDLoc(V), V.getValueType(), V);
2560}
2561
2563 UndefPoisonKind Kind) {
2564 if (isGuaranteedNotToBeUndefOrPoison(V, DemandedElts, Kind))
2565 return V;
2566 return getFreeze(V);
2567}
2568
2569/// getShiftAmountOperand - Return the specified value casted to
2570/// the target's desired shift amount type.
2572 EVT OpTy = Op.getValueType();
2573 EVT ShTy = TLI->getShiftAmountTy(LHSTy, getDataLayout());
2574 if (OpTy == ShTy || OpTy.isVector()) return Op;
2575
2576 return getZExtOrTrunc(Op, SDLoc(Op), ShTy);
2577}
2578
2580 SDLoc dl(Node);
2582 const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2583 EVT VT = Node->getValueType(0);
2584 SDValue Tmp1 = Node->getOperand(0);
2585 SDValue Tmp2 = Node->getOperand(1);
2586 const MaybeAlign MA(Node->getConstantOperandVal(3));
2587
2588 SDValue VAListLoad = getLoad(TLI.getPointerTy(getDataLayout()), dl, Tmp1,
2589 Tmp2, MachinePointerInfo(V));
2590 SDValue VAList = VAListLoad;
2591
2592 if (MA && *MA > TLI.getMinStackArgumentAlignment()) {
2593 VAList = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
2594 getConstant(MA->value() - 1, dl, VAList.getValueType()));
2595
2596 VAList = getNode(
2597 ISD::AND, dl, VAList.getValueType(), VAList,
2598 getSignedConstant(-(int64_t)MA->value(), dl, VAList.getValueType()));
2599 }
2600
2601 // Increment the pointer, VAList, to the next vaarg
2602 Tmp1 = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
2603 getConstant(getDataLayout().getTypeAllocSize(
2604 VT.getTypeForEVT(*getContext())),
2605 dl, VAList.getValueType()));
2606 // Store the incremented VAList to the legalized pointer
2607 Tmp1 =
2608 getStore(VAListLoad.getValue(1), dl, Tmp1, Tmp2, MachinePointerInfo(V));
2609 // Load the actual argument out of the pointer VAList
2610 return getLoad(VT, dl, Tmp1, VAList, MachinePointerInfo());
2611}
2612
2614 SDLoc dl(Node);
2616 // This defaults to loading a pointer from the input and storing it to the
2617 // output, returning the chain.
2618 const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue();
2619 const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue();
2620 SDValue Tmp1 =
2621 getLoad(TLI.getPointerTy(getDataLayout()), dl, Node->getOperand(0),
2622 Node->getOperand(2), MachinePointerInfo(VS));
2623 return getStore(Tmp1.getValue(1), dl, Tmp1, Node->getOperand(1),
2624 MachinePointerInfo(VD));
2625}
2626
2628 const DataLayout &DL = getDataLayout();
2629 Type *Ty = VT.getTypeForEVT(*getContext());
2630 Align RedAlign = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty);
2631
2632 if (TLI->isTypeLegal(VT) || !VT.isVector())
2633 return RedAlign;
2634
2635 const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
2636 const Align StackAlign = TFI->getStackAlign();
2637
2638 // See if we can choose a smaller ABI alignment in cases where it's an
2639 // illegal vector type that will get broken down.
2640 if (RedAlign > StackAlign) {
2641 EVT IntermediateVT;
2642 MVT RegisterVT;
2643 unsigned NumIntermediates;
2644 TLI->getVectorTypeBreakdown(*getContext(), VT, IntermediateVT,
2645 NumIntermediates, RegisterVT);
2646 Ty = IntermediateVT.getTypeForEVT(*getContext());
2647 Align RedAlign2 = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty);
2648 if (RedAlign2 < RedAlign)
2649 RedAlign = RedAlign2;
2650
2651 if (!getMachineFunction().getFrameInfo().isStackRealignable())
2652 // If the stack is not realignable, the alignment should be limited to the
2653 // StackAlignment
2654 RedAlign = std::min(RedAlign, StackAlign);
2655 }
2656
2657 return RedAlign;
2658}
2659
2661 MachineFrameInfo &MFI = MF->getFrameInfo();
2662 const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
2663 int StackID = 0;
2664 if (Bytes.isScalable())
2665 StackID = TFI->getStackIDForScalableVectors();
2666 // The stack id gives an indication of whether the object is scalable or
2667 // not, so it's safe to pass in the minimum size here.
2668 int FrameIdx = MFI.CreateStackObject(Bytes.getKnownMinValue(), Alignment,
2669 false, nullptr, StackID);
2670 return getFrameIndex(FrameIdx, TLI->getFrameIndexTy(getDataLayout()));
2671}
2672
2674 Type *Ty = VT.getTypeForEVT(*getContext());
2675 Align StackAlign =
2676 std::max(getDataLayout().getPrefTypeAlign(Ty), Align(minAlign));
2677 return CreateStackTemporary(VT.getStoreSize(), StackAlign);
2678}
2679
2681 TypeSize VT1Size = VT1.getStoreSize();
2682 TypeSize VT2Size = VT2.getStoreSize();
2683 assert(VT1Size.isScalable() == VT2Size.isScalable() &&
2684 "Don't know how to choose the maximum size when creating a stack "
2685 "temporary");
2686 TypeSize Bytes = VT1Size.getKnownMinValue() > VT2Size.getKnownMinValue()
2687 ? VT1Size
2688 : VT2Size;
2689
2690 Type *Ty1 = VT1.getTypeForEVT(*getContext());
2691 Type *Ty2 = VT2.getTypeForEVT(*getContext());
2692 const DataLayout &DL = getDataLayout();
2693 Align Align = std::max(DL.getPrefTypeAlign(Ty1), DL.getPrefTypeAlign(Ty2));
2694 return CreateStackTemporary(Bytes, Align);
2695}
2696
2698 ISD::CondCode Cond, const SDLoc &dl,
2699 SDNodeFlags Flags) {
2700 EVT OpVT = N1.getValueType();
2701
2702 auto GetUndefBooleanConstant = [&]() {
2703 if (VT.getScalarType() == MVT::i1 ||
2704 TLI->getBooleanContents(OpVT) ==
2706 return getUNDEF(VT);
2707 // ZeroOrOne / ZeroOrNegative require specific values for the high bits,
2708 // so we cannot use getUNDEF(). Return zero instead.
2709 return getConstant(0, dl, VT);
2710 };
2711
2712 // These setcc operations always fold.
2713 switch (Cond) {
2714 default: break;
2715 case ISD::SETFALSE:
2716 case ISD::SETFALSE2: return getBoolConstant(false, dl, VT, OpVT);
2717 case ISD::SETTRUE:
2718 case ISD::SETTRUE2: return getBoolConstant(true, dl, VT, OpVT);
2719
2720 case ISD::SETOEQ:
2721 case ISD::SETOGT:
2722 case ISD::SETOGE:
2723 case ISD::SETOLT:
2724 case ISD::SETOLE:
2725 case ISD::SETONE:
2726 case ISD::SETO:
2727 case ISD::SETUO:
2728 case ISD::SETUEQ:
2729 case ISD::SETUNE:
2730 assert(!OpVT.isInteger() && "Illegal setcc for integer!");
2731 break;
2732 }
2733
2734 if (OpVT.isInteger()) {
2735 // For EQ and NE, we can always pick a value for the undef to make the
2736 // predicate pass or fail, so we can return undef.
2737 // Matches behavior in llvm::ConstantFoldCompareInstruction.
2738 // icmp eq/ne X, undef -> undef.
2739 if ((N1.isUndef() || N2.isUndef()) &&
2740 (Cond == ISD::SETEQ || Cond == ISD::SETNE))
2741 return GetUndefBooleanConstant();
2742
2743 // If both operands are undef, we can return undef for int comparison.
2744 // icmp undef, undef -> undef.
2745 if (N1.isUndef() && N2.isUndef())
2746 return GetUndefBooleanConstant();
2747
2748 // icmp X, X -> true/false
2749 // icmp X, undef -> true/false because undef could be X.
2750 if (N1.isUndef() || N2.isUndef() || N1 == N2)
2751 return getBoolConstant(ISD::isTrueWhenEqual(Cond), dl, VT, OpVT);
2752 }
2753
2755 const APInt &C2 = N2C->getAPIntValue();
2757 const APInt &C1 = N1C->getAPIntValue();
2758
2760 dl, VT, OpVT);
2761 }
2762 }
2763
2764 auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
2765 auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
2766
2767 if (N1CFP && N2CFP) {
2768 APFloat::cmpResult R = N1CFP->getValueAPF().compare(N2CFP->getValueAPF());
2769 switch (Cond) {
2770 default: break;
2771 case ISD::SETEQ: if (R==APFloat::cmpUnordered)
2772 return GetUndefBooleanConstant();
2773 [[fallthrough]];
2774 case ISD::SETOEQ: return getBoolConstant(R==APFloat::cmpEqual, dl, VT,
2775 OpVT);
2776 case ISD::SETNE: if (R==APFloat::cmpUnordered)
2777 return GetUndefBooleanConstant();
2778 [[fallthrough]];
2780 R==APFloat::cmpLessThan, dl, VT,
2781 OpVT);
2782 case ISD::SETLT: if (R==APFloat::cmpUnordered)
2783 return GetUndefBooleanConstant();
2784 [[fallthrough]];
2785 case ISD::SETOLT: return getBoolConstant(R==APFloat::cmpLessThan, dl, VT,
2786 OpVT);
2787 case ISD::SETGT: if (R==APFloat::cmpUnordered)
2788 return GetUndefBooleanConstant();
2789 [[fallthrough]];
2791 VT, OpVT);
2792 case ISD::SETLE: if (R==APFloat::cmpUnordered)
2793 return GetUndefBooleanConstant();
2794 [[fallthrough]];
2796 R==APFloat::cmpEqual, dl, VT,
2797 OpVT);
2798 case ISD::SETGE: if (R==APFloat::cmpUnordered)
2799 return GetUndefBooleanConstant();
2800 [[fallthrough]];
2802 R==APFloat::cmpEqual, dl, VT, OpVT);
2803 case ISD::SETO: return getBoolConstant(R!=APFloat::cmpUnordered, dl, VT,
2804 OpVT);
2805 case ISD::SETUO: return getBoolConstant(R==APFloat::cmpUnordered, dl, VT,
2806 OpVT);
2808 R==APFloat::cmpEqual, dl, VT,
2809 OpVT);
2810 case ISD::SETUNE: return getBoolConstant(R!=APFloat::cmpEqual, dl, VT,
2811 OpVT);
2813 R==APFloat::cmpLessThan, dl, VT,
2814 OpVT);
2816 R==APFloat::cmpUnordered, dl, VT,
2817 OpVT);
2819 VT, OpVT);
2820 case ISD::SETUGE: return getBoolConstant(R!=APFloat::cmpLessThan, dl, VT,
2821 OpVT);
2822 }
2823 } else if (N1CFP && OpVT.isSimple() && !N2.isUndef()) {
2824 // Ensure that the constant occurs on the RHS.
2826 if (!TLI->isCondCodeLegal(SwappedCond, OpVT.getSimpleVT()))
2827 return SDValue();
2828 return getSetCC(dl, VT, N2, N1, SwappedCond, /*Chain=*/{},
2829 /*IsSignaling=*/false, Flags);
2830 } else if ((N2CFP && N2CFP->getValueAPF().isNaN()) ||
2831 (OpVT.isFloatingPoint() && (N1.isUndef() || N2.isUndef()))) {
2832 // If an operand is known to be a nan (or undef that could be a nan), we can
2833 // fold it.
2834 // Choosing NaN for the undef will always make unordered comparison succeed
2835 // and ordered comparison fails.
2836 // Matches behavior in llvm::ConstantFoldCompareInstruction.
2837 switch (ISD::getUnorderedFlavor(Cond)) {
2838 default:
2839 llvm_unreachable("Unknown flavor!");
2840 case 0: // Known false.
2841 return getBoolConstant(false, dl, VT, OpVT);
2842 case 1: // Known true.
2843 return getBoolConstant(true, dl, VT, OpVT);
2844 case 2: // Undefined.
2845 return GetUndefBooleanConstant();
2846 }
2847 }
2848
2849 // Could not fold it.
2850 return SDValue();
2851}
2852
2853/// SignBitIsZero - Return true if the sign bit of Op is known to be zero. We
2854/// use this predicate to simplify operations downstream.
2856 unsigned BitWidth = Op.getScalarValueSizeInBits();
2858}
2859
2860// TODO: Should have argument to specify if sign bit of nan is ignorable.
2862 if (Depth >= MaxRecursionDepth)
2863 return false; // Limit search depth.
2864
2865 unsigned Opc = Op.getOpcode();
2866 switch (Opc) {
2867 case ISD::FABS:
2868 return true;
2869 case ISD::AssertNoFPClass: {
2870 FPClassTest NoFPClass =
2871 static_cast<FPClassTest>(Op.getConstantOperandVal(1));
2872
2873 const FPClassTest TestMask = fcNan | fcNegative;
2874 return (NoFPClass & TestMask) == TestMask;
2875 }
2876 case ISD::ARITH_FENCE:
2877 return SignBitIsZeroFP(Op.getOperand(0), Depth + 1);
2878 case ISD::FEXP:
2879 case ISD::FEXP2:
2880 case ISD::FEXP10:
2881 return Op->getFlags().hasNoNaNs();
2882 case ISD::FMINNUM:
2883 case ISD::FMINNUM_IEEE:
2884 case ISD::FMINIMUM:
2885 case ISD::FMINIMUMNUM:
2886 return SignBitIsZeroFP(Op.getOperand(1), Depth + 1) &&
2887 SignBitIsZeroFP(Op.getOperand(0), Depth + 1);
2888 case ISD::FMAXNUM:
2889 case ISD::FMAXNUM_IEEE:
2890 case ISD::FMAXIMUM:
2891 case ISD::FMAXIMUMNUM:
2892 // TODO: If we can ignore the sign bit of nans, only one side being known 0
2893 // is sufficient.
2894 return SignBitIsZeroFP(Op.getOperand(1), Depth + 1) &&
2895 SignBitIsZeroFP(Op.getOperand(0), Depth + 1);
2896 default:
2897 return false;
2898 }
2899
2900 llvm_unreachable("covered opcode switch");
2901}
2902
2903/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
2904/// this predicate to simplify operations downstream. Mask is known to be zero
2905/// for bits that V cannot have.
2907 unsigned Depth) const {
2908 return Mask.isSubsetOf(computeKnownBits(V, Depth).Zero);
2909}
2910
2911/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero in
2912/// DemandedElts. We use this predicate to simplify operations downstream.
2913/// Mask is known to be zero for bits that V cannot have.
2915 const APInt &DemandedElts,
2916 unsigned Depth) const {
2917 return Mask.isSubsetOf(computeKnownBits(V, DemandedElts, Depth).Zero);
2918}
2919
2920/// MaskedVectorIsZero - Return true if 'Op' is known to be zero in
2921/// DemandedElts. We use this predicate to simplify operations downstream.
2923 unsigned Depth /* = 0 */) const {
2924 return computeKnownBits(V, DemandedElts, Depth).isZero();
2925}
2926
2927/// MaskedValueIsAllOnes - Return true if '(Op & Mask) == Mask'.
2929 unsigned Depth) const {
2930 return Mask.isSubsetOf(computeKnownBits(V, Depth).One);
2931}
2932
2934 const APInt &DemandedElts,
2935 unsigned Depth) const {
2936 EVT VT = Op.getValueType();
2937 assert(VT.isVector() && !VT.isScalableVector() && "Only for fixed vectors!");
2938
2939 unsigned NumElts = VT.getVectorNumElements();
2940 assert(DemandedElts.getBitWidth() == NumElts && "Unexpected demanded mask.");
2941
2942 APInt KnownZeroElements = APInt::getZero(NumElts);
2943 for (unsigned EltIdx = 0; EltIdx != NumElts; ++EltIdx) {
2944 if (!DemandedElts[EltIdx])
2945 continue; // Don't query elements that are not demanded.
2946 APInt Mask = APInt::getOneBitSet(NumElts, EltIdx);
2947 if (MaskedVectorIsZero(Op, Mask, Depth))
2948 KnownZeroElements.setBit(EltIdx);
2949 }
2950 return KnownZeroElements;
2951}
2952
2953/// isSplatValue - Return true if the vector V has the same value
2954/// across all DemandedElts. For scalable vectors, we don't know the
2955/// number of lanes at compile time. Instead, we use a 1 bit APInt
2956/// to represent a conservative value for all lanes; that is, that
2957/// one bit value is implicitly splatted across all lanes.
2958bool SelectionDAG::isSplatValue(SDValue V, const APInt &DemandedElts,
2959 APInt &UndefElts, unsigned Depth) const {
2960 unsigned Opcode = V.getOpcode();
2961 EVT VT = V.getValueType();
2962 assert(VT.isVector() && "Vector type expected");
2963 assert((!VT.isScalableVector() || DemandedElts.getBitWidth() == 1) &&
2964 "scalable demanded bits are ignored");
2965
2966 if (!DemandedElts)
2967 return false; // No demanded elts, better to assume we don't know anything.
2968
2969 if (Depth >= MaxRecursionDepth)
2970 return false; // Limit search depth.
2971
2972 // Deal with some common cases here that work for both fixed and scalable
2973 // vector types.
2974 switch (Opcode) {
2975 case ISD::SPLAT_VECTOR:
2976 UndefElts = V.getOperand(0).isUndef()
2977 ? APInt::getAllOnes(DemandedElts.getBitWidth())
2978 : APInt(DemandedElts.getBitWidth(), 0);
2979 return true;
2980 case ISD::ADD:
2981 case ISD::SUB:
2982 case ISD::AND:
2983 case ISD::XOR:
2984 case ISD::OR: {
2985 APInt UndefLHS, UndefRHS;
2986 SDValue LHS = V.getOperand(0);
2987 SDValue RHS = V.getOperand(1);
2988 // Only recognize splats with the same demanded undef elements for both
2989 // operands, otherwise we might fail to handle binop-specific undef
2990 // handling.
2991 // e.g. (and undef, 0) -> 0 etc.
2992 if (isSplatValue(LHS, DemandedElts, UndefLHS, Depth + 1) &&
2993 isSplatValue(RHS, DemandedElts, UndefRHS, Depth + 1) &&
2994 (DemandedElts & UndefLHS) == (DemandedElts & UndefRHS)) {
2995 UndefElts = UndefLHS | UndefRHS;
2996 return true;
2997 }
2998 return false;
2999 }
3000 case ISD::ABS:
3002 case ISD::TRUNCATE:
3003 case ISD::SIGN_EXTEND:
3004 case ISD::ZERO_EXTEND:
3005 return isSplatValue(V.getOperand(0), DemandedElts, UndefElts, Depth + 1);
3006 default:
3007 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
3008 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID)
3009 return TLI->isSplatValueForTargetNode(V, DemandedElts, UndefElts, *this,
3010 Depth);
3011 break;
3012 }
3013
3014 // We don't support other cases than those above for scalable vectors at
3015 // the moment.
3016 if (VT.isScalableVector())
3017 return false;
3018
3019 unsigned NumElts = VT.getVectorNumElements();
3020 assert(NumElts == DemandedElts.getBitWidth() && "Vector size mismatch");
3021 UndefElts = APInt::getZero(NumElts);
3022
3023 switch (Opcode) {
3024 case ISD::BUILD_VECTOR: {
3025 SDValue Scl;
3026 for (unsigned i = 0; i != NumElts; ++i) {
3027 SDValue Op = V.getOperand(i);
3028 if (Op.isUndef()) {
3029 UndefElts.setBit(i);
3030 continue;
3031 }
3032 if (!DemandedElts[i])
3033 continue;
3034 if (Scl && Scl != Op)
3035 return false;
3036 Scl = Op;
3037 }
3038 return true;
3039 }
3040 case ISD::VECTOR_SHUFFLE: {
3041 // Check if this is a shuffle node doing a splat or a shuffle of a splat.
3042 APInt DemandedLHS = APInt::getZero(NumElts);
3043 APInt DemandedRHS = APInt::getZero(NumElts);
3044 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(V)->getMask();
3045 for (int i = 0; i != (int)NumElts; ++i) {
3046 int M = Mask[i];
3047 if (M < 0) {
3048 UndefElts.setBit(i);
3049 continue;
3050 }
3051 if (!DemandedElts[i])
3052 continue;
3053 if (M < (int)NumElts)
3054 DemandedLHS.setBit(M);
3055 else
3056 DemandedRHS.setBit(M - NumElts);
3057 }
3058
3059 // If we aren't demanding either op, assume there's no splat.
3060 // If we are demanding both ops, assume there's no splat.
3061 if ((DemandedLHS.isZero() && DemandedRHS.isZero()) ||
3062 (!DemandedLHS.isZero() && !DemandedRHS.isZero()))
3063 return false;
3064
3065 // See if the demanded elts of the source op is a splat or we only demand
3066 // one element, which should always be a splat.
3067 // TODO: Handle source ops splats with undefs.
3068 auto CheckSplatSrc = [&](SDValue Src, const APInt &SrcElts) {
3069 APInt SrcUndefs;
3070 return (SrcElts.popcount() == 1) ||
3071 (isSplatValue(Src, SrcElts, SrcUndefs, Depth + 1) &&
3072 (SrcElts & SrcUndefs).isZero());
3073 };
3074 if (!DemandedLHS.isZero())
3075 return CheckSplatSrc(V.getOperand(0), DemandedLHS);
3076 return CheckSplatSrc(V.getOperand(1), DemandedRHS);
3077 }
3079 // Offset the demanded elts by the subvector index.
3080 SDValue Src = V.getOperand(0);
3081 // We don't support scalable vectors at the moment.
3082 if (Src.getValueType().isScalableVector())
3083 return false;
3084 uint64_t Idx = V.getConstantOperandVal(1);
3085 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
3086 APInt UndefSrcElts;
3087 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
3088 if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) {
3089 UndefElts = UndefSrcElts.extractBits(NumElts, Idx);
3090 return true;
3091 }
3092 break;
3093 }
3097 // Widen the demanded elts by the src element count.
3098 SDValue Src = V.getOperand(0);
3099 // We don't support scalable vectors at the moment.
3100 if (Src.getValueType().isScalableVector())
3101 return false;
3102 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
3103 APInt UndefSrcElts;
3104 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts);
3105 if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) {
3106 UndefElts = UndefSrcElts.trunc(NumElts);
3107 return true;
3108 }
3109 break;
3110 }
3111 case ISD::BITCAST: {
3112 SDValue Src = V.getOperand(0);
3113 EVT SrcVT = Src.getValueType();
3114 unsigned SrcBitWidth = SrcVT.getScalarSizeInBits();
3115 unsigned BitWidth = VT.getScalarSizeInBits();
3116
3117 // Ignore bitcasts from unsupported types.
3118 // TODO: Add fp support?
3119 if (!SrcVT.isVector() || !SrcVT.isInteger() || !VT.isInteger())
3120 break;
3121
3122 // Bitcast 'small element' vector to 'large element' vector.
3123 if ((BitWidth % SrcBitWidth) == 0) {
3124 // See if each sub element is a splat.
3125 unsigned Scale = BitWidth / SrcBitWidth;
3126 unsigned NumSrcElts = SrcVT.getVectorNumElements();
3127 APInt ScaledDemandedElts =
3128 APIntOps::ScaleBitMask(DemandedElts, NumSrcElts);
3129 for (unsigned I = 0; I != Scale; ++I) {
3130 APInt SubUndefElts;
3131 APInt SubDemandedElt = APInt::getOneBitSet(Scale, I);
3132 APInt SubDemandedElts = APInt::getSplat(NumSrcElts, SubDemandedElt);
3133 SubDemandedElts &= ScaledDemandedElts;
3134 if (!isSplatValue(Src, SubDemandedElts, SubUndefElts, Depth + 1))
3135 return false;
3136 // TODO: Add support for merging sub undef elements.
3137 if (!SubUndefElts.isZero())
3138 return false;
3139 }
3140 return true;
3141 }
3142 break;
3143 }
3144 }
3145
3146 return false;
3147}
3148
3149/// Helper wrapper to main isSplatValue function.
3150bool SelectionDAG::isSplatValue(SDValue V, bool AllowUndefs) const {
3151 EVT VT = V.getValueType();
3152 assert(VT.isVector() && "Vector type expected");
3153
3154 APInt UndefElts;
3155 // Since the number of lanes in a scalable vector is unknown at compile time,
3156 // we track one bit which is implicitly broadcast to all lanes. This means
3157 // that all lanes in a scalable vector are considered demanded.
3158 APInt DemandedElts
3160 return isSplatValue(V, DemandedElts, UndefElts) &&
3161 (AllowUndefs || !UndefElts);
3162}
3163
3166
3167 EVT VT = V.getValueType();
3168 unsigned Opcode = V.getOpcode();
3169 switch (Opcode) {
3170 default: {
3171 APInt UndefElts;
3172 // Since the number of lanes in a scalable vector is unknown at compile time,
3173 // we track one bit which is implicitly broadcast to all lanes. This means
3174 // that all lanes in a scalable vector are considered demanded.
3175 APInt DemandedElts
3177
3178 if (isSplatValue(V, DemandedElts, UndefElts)) {
3179 if (VT.isScalableVector()) {
3180 // DemandedElts and UndefElts are ignored for scalable vectors, since
3181 // the only supported cases are SPLAT_VECTOR nodes.
3182 SplatIdx = 0;
3183 } else {
3184 // Handle case where all demanded elements are UNDEF.
3185 if (DemandedElts.isSubsetOf(UndefElts)) {
3186 SplatIdx = 0;
3187 return getUNDEF(VT);
3188 }
3189 SplatIdx = (UndefElts & DemandedElts).countr_one();
3190 }
3191 return V;
3192 }
3193 break;
3194 }
3195 case ISD::SPLAT_VECTOR:
3196 SplatIdx = 0;
3197 return V;
3198 case ISD::VECTOR_SHUFFLE: {
3199 assert(!VT.isScalableVector());
3200 // Check if this is a shuffle node doing a splat.
3201 // TODO - remove this and rely purely on SelectionDAG::isSplatValue,
3202 // getTargetVShiftNode currently struggles without the splat source.
3203 auto *SVN = cast<ShuffleVectorSDNode>(V);
3204 if (!SVN->isSplat())
3205 break;
3206 int Idx = SVN->getSplatIndex();
3207 int NumElts = V.getValueType().getVectorNumElements();
3208 SplatIdx = Idx % NumElts;
3209 return V.getOperand(Idx / NumElts);
3210 }
3211 }
3212
3213 return SDValue();
3214}
3215
3217 int SplatIdx;
3218 if (SDValue SrcVector = getSplatSourceVector(V, SplatIdx)) {
3219 EVT SVT = SrcVector.getValueType().getScalarType();
3220 EVT LegalSVT = SVT;
3221 if (LegalTypes && !TLI->isTypeLegal(SVT)) {
3222 if (!SVT.isInteger())
3223 return SDValue();
3224 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
3225 if (LegalSVT.bitsLT(SVT))
3226 return SDValue();
3227 }
3228 return getExtractVectorElt(SDLoc(V), LegalSVT, SrcVector, SplatIdx);
3229 }
3230 return SDValue();
3231}
3232
3233std::optional<ConstantRange>
3235 unsigned Depth) const {
3236 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
3237 V.getOpcode() == ISD::SRA) &&
3238 "Unknown shift node");
3239 // Shifting more than the bitwidth is not valid.
3240 unsigned BitWidth = V.getScalarValueSizeInBits();
3241
3242 if (auto *Cst = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
3243 const APInt &ShAmt = Cst->getAPIntValue();
3244 if (ShAmt.uge(BitWidth))
3245 return std::nullopt;
3246 return ConstantRange(ShAmt);
3247 }
3248
3249 if (auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1))) {
3250 const APInt *MinAmt = nullptr, *MaxAmt = nullptr;
3251 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
3252 if (!DemandedElts[i])
3253 continue;
3254 auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i));
3255 if (!SA) {
3256 MinAmt = MaxAmt = nullptr;
3257 break;
3258 }
3259 const APInt &ShAmt = SA->getAPIntValue();
3260 if (ShAmt.uge(BitWidth))
3261 return std::nullopt;
3262 if (!MinAmt || MinAmt->ugt(ShAmt))
3263 MinAmt = &ShAmt;
3264 if (!MaxAmt || MaxAmt->ult(ShAmt))
3265 MaxAmt = &ShAmt;
3266 }
3267 assert(((!MinAmt && !MaxAmt) || (MinAmt && MaxAmt)) &&
3268 "Failed to find matching min/max shift amounts");
3269 if (MinAmt && MaxAmt)
3270 return ConstantRange(*MinAmt, *MaxAmt + 1);
3271 }
3272
3273 // Use computeKnownBits to find a hidden constant/knownbits (usually type
3274 // legalized). e.g. Hidden behind multiple bitcasts/build_vector/casts etc.
3275 KnownBits KnownAmt = computeKnownBits(V.getOperand(1), DemandedElts, Depth);
3276 if (KnownAmt.getMaxValue().ult(BitWidth))
3277 return ConstantRange::fromKnownBits(KnownAmt, /*IsSigned=*/false);
3278
3279 return std::nullopt;
3280}
3281
3282std::optional<unsigned>
3284 unsigned Depth) const {
3285 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
3286 V.getOpcode() == ISD::SRA) &&
3287 "Unknown shift node");
3288 if (std::optional<ConstantRange> AmtRange =
3289 getValidShiftAmountRange(V, DemandedElts, Depth))
3290 if (const APInt *ShAmt = AmtRange->getSingleElement())
3291 return ShAmt->getZExtValue();
3292 return std::nullopt;
3293}
3294
3295std::optional<unsigned>
3297 APInt DemandedElts = getDemandAllEltsMask(V);
3298 return getValidShiftAmount(V, DemandedElts, Depth);
3299}
3300
3301std::optional<unsigned>
3303 unsigned Depth) const {
3304 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
3305 V.getOpcode() == ISD::SRA) &&
3306 "Unknown shift node");
3307 if (std::optional<ConstantRange> AmtRange =
3308 getValidShiftAmountRange(V, DemandedElts, Depth))
3309 return AmtRange->getUnsignedMin().getZExtValue();
3310 return std::nullopt;
3311}
3312
3313std::optional<unsigned>
3315 APInt DemandedElts = getDemandAllEltsMask(V);
3316 return getValidMinimumShiftAmount(V, DemandedElts, Depth);
3317}
3318
3319std::optional<unsigned>
3321 unsigned Depth) const {
3322 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
3323 V.getOpcode() == ISD::SRA) &&
3324 "Unknown shift node");
3325 if (std::optional<ConstantRange> AmtRange =
3326 getValidShiftAmountRange(V, DemandedElts, Depth))
3327 return AmtRange->getUnsignedMax().getZExtValue();
3328 return std::nullopt;
3329}
3330
3331std::optional<unsigned>
3333 APInt DemandedElts = getDemandAllEltsMask(V);
3334 return getValidMaximumShiftAmount(V, DemandedElts, Depth);
3335}
3336
3337/// Determine which bits of Op are known to be either zero or one and return
3338/// them in Known. For vectors, the known bits are those that are shared by
3339/// every vector element.
3341 APInt DemandedElts = getDemandAllEltsMask(Op);
3342 return computeKnownBits(Op, DemandedElts, Depth);
3343}
3344
3345/// Determine which bits of Op are known to be either zero or one and return
3346/// them in Known. The DemandedElts argument allows us to only collect the known
3347/// bits that are shared by the requested vector elements.
3349 unsigned Depth) const {
3350 unsigned BitWidth = Op.getScalarValueSizeInBits();
3351
3352 KnownBits Known(BitWidth); // Don't know anything.
3353
3354 if (auto OptAPInt = Op->bitcastToAPInt()) {
3355 // We know all of the bits for a constant!
3356 return KnownBits::makeConstant(*std::move(OptAPInt));
3357 }
3358
3359 if (Depth >= MaxRecursionDepth)
3360 return Known; // Limit search depth.
3361
3362 KnownBits Known2;
3363 unsigned NumElts = DemandedElts.getBitWidth();
3364 assert((!Op.getValueType().isScalableVector() || NumElts == 1) &&
3365 "DemandedElts for scalable vectors must be 1 to represent all lanes");
3366 assert((!Op.getValueType().isFixedLengthVector() ||
3367 NumElts == Op.getValueType().getVectorNumElements()) &&
3368 "Unexpected vector size");
3369
3370 if (!DemandedElts)
3371 return Known; // No demanded elts, better to assume we don't know anything.
3372
3373 unsigned Opcode = Op.getOpcode();
3374 switch (Opcode) {
3375 case ISD::FREEZE: {
3376 if (isGuaranteedNotToBeUndefOrPoison(Op.getOperand(0), DemandedElts,
3378 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3379 break;
3380 }
3381 case ISD::MERGE_VALUES:
3382 return computeKnownBits(Op.getOperand(Op.getResNo()), DemandedElts,
3383 Depth + 1);
3384 case ISD::SPLAT_VECTOR: {
3385 SDValue SrcOp = Op.getOperand(0);
3386 assert(SrcOp.getValueSizeInBits() >= BitWidth &&
3387 "Expected SPLAT_VECTOR implicit truncation");
3388 // Implicitly truncate the bits to match the official semantics of
3389 // SPLAT_VECTOR.
3391 break;
3392 }
3394 unsigned ScalarSize = Op.getOperand(0).getScalarValueSizeInBits();
3395 assert(ScalarSize * Op.getNumOperands() == BitWidth &&
3396 "Expected SPLAT_VECTOR_PARTS scalars to cover element width");
3397 for (auto [I, SrcOp] : enumerate(Op->ops())) {
3398 Known.insertBits(computeKnownBits(SrcOp, Depth + 1), ScalarSize * I);
3399 }
3400 break;
3401 }
3402 case ISD::STEP_VECTOR: {
3403 const APInt &Step = Op.getConstantOperandAPInt(0);
3404
3405 if (Step.isPowerOf2())
3406 Known.Zero.setLowBits(Step.logBase2());
3407
3409
3410 if (!isUIntN(BitWidth, Op.getValueType().getVectorMinNumElements()))
3411 break;
3412 const APInt MinNumElts =
3413 APInt(BitWidth, Op.getValueType().getVectorMinNumElements());
3414
3415 bool Overflow;
3416 const APInt MaxNumElts = getVScaleRange(&F, BitWidth)
3418 .umul_ov(MinNumElts, Overflow);
3419 if (Overflow)
3420 break;
3421
3422 const APInt MaxValue = (MaxNumElts - 1).umul_ov(Step, Overflow);
3423 if (Overflow)
3424 break;
3425
3426 Known.Zero.setHighBits(MaxValue.countl_zero());
3427 break;
3428 }
3429 case ISD::BUILD_VECTOR:
3430 assert(!Op.getValueType().isScalableVector());
3431 // Collect the known bits that are shared by every demanded vector element.
3432 Known.setAllConflict();
3433 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
3434 if (!DemandedElts[i])
3435 continue;
3436
3437 SDValue SrcOp = Op.getOperand(i);
3438 if (SrcOp.getOpcode() == ISD::POISON)
3439 continue;
3440
3441 Known2 = computeKnownBits(SrcOp, Depth + 1);
3442
3443 // BUILD_VECTOR can implicitly truncate sources, we must handle this.
3444 if (SrcOp.getValueSizeInBits() != BitWidth) {
3445 assert(SrcOp.getValueSizeInBits() > BitWidth &&
3446 "Expected BUILD_VECTOR implicit truncation");
3447 Known2 = Known2.trunc(BitWidth);
3448 }
3449
3450 // Known bits are the values that are shared by every demanded element.
3451 Known = Known.intersectWith(Known2);
3452
3453 // If we don't know any bits, early out.
3454 if (Known.isUnknown())
3455 break;
3456 }
3457
3458 // If every demanded element was poison, we know nothing.
3459 if (Known.hasConflict())
3460 Known.resetAll();
3461 break;
3462 case ISD::VECTOR_COMPRESS: {
3463 SDValue Vec = Op.getOperand(0);
3464 SDValue PassThru = Op.getOperand(2);
3465 Known = computeKnownBits(PassThru, DemandedElts, Depth + 1);
3466 // If we don't know any bits, early out.
3467 if (Known.isUnknown())
3468 break;
3469 Known2 = computeKnownBits(Vec, Depth + 1);
3470 Known = Known.intersectWith(Known2);
3471 break;
3472 }
3473 case ISD::VECTOR_SHUFFLE: {
3474 assert(!Op.getValueType().isScalableVector());
3475 // Collect the known bits that are shared by every vector element referenced
3476 // by the shuffle.
3477 APInt DemandedLHS, DemandedRHS;
3479 assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
3480 if (!getShuffleDemandedElts(NumElts, SVN->getMask(), DemandedElts,
3481 DemandedLHS, DemandedRHS))
3482 break;
3483
3484 // Known bits are the values that are shared by every demanded element.
3485 Known.setAllConflict();
3486 if (!!DemandedLHS) {
3487 SDValue LHS = Op.getOperand(0);
3488 Known2 = computeKnownBits(LHS, DemandedLHS, Depth + 1);
3489 Known = Known.intersectWith(Known2);
3490 }
3491 // If we don't know any bits, early out.
3492 if (Known.isUnknown())
3493 break;
3494 if (!!DemandedRHS) {
3495 SDValue RHS = Op.getOperand(1);
3496 Known2 = computeKnownBits(RHS, DemandedRHS, Depth + 1);
3497 Known = Known.intersectWith(Known2);
3498 }
3499 break;
3500 }
3501 case ISD::VSCALE: {
3503 const APInt &Multiplier = Op.getConstantOperandAPInt(0);
3505 break;
3506 }
3507 case ISD::CONCAT_VECTORS: {
3508 if (Op.getValueType().isScalableVector())
3509 break;
3510 // Split DemandedElts and test each of the demanded subvectors.
3511 Known.setAllConflict();
3512 EVT SubVectorVT = Op.getOperand(0).getValueType();
3513 unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
3514 unsigned NumSubVectors = Op.getNumOperands();
3515 for (unsigned i = 0; i != NumSubVectors; ++i) {
3516 APInt DemandedSub =
3517 DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts);
3518 if (!!DemandedSub) {
3519 SDValue Sub = Op.getOperand(i);
3520 Known2 = computeKnownBits(Sub, DemandedSub, Depth + 1);
3521 Known = Known.intersectWith(Known2);
3522 }
3523 // If we don't know any bits, early out.
3524 if (Known.isUnknown())
3525 break;
3526 }
3527 break;
3528 }
3529 case ISD::INSERT_SUBVECTOR: {
3530 if (Op.getValueType().isScalableVector())
3531 break;
3532 // Demand any elements from the subvector and the remainder from the src its
3533 // inserted into.
3534 SDValue Src = Op.getOperand(0);
3535 SDValue Sub = Op.getOperand(1);
3536 uint64_t Idx = Op.getConstantOperandVal(2);
3537 unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
3538 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
3539 APInt DemandedSrcElts = DemandedElts;
3540 DemandedSrcElts.clearBits(Idx, Idx + NumSubElts);
3541
3542 Known.setAllConflict();
3543 if (!!DemandedSubElts) {
3544 Known = computeKnownBits(Sub, DemandedSubElts, Depth + 1);
3545 if (Known.isUnknown())
3546 break; // early-out.
3547 }
3548 if (!!DemandedSrcElts) {
3549 Known2 = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
3550 Known = Known.intersectWith(Known2);
3551 }
3552 break;
3553 }
3555 // Offset the demanded elts by the subvector index.
3556 SDValue Src = Op.getOperand(0);
3557
3558 APInt DemandedSrcElts;
3559 if (Src.getValueType().isScalableVector())
3560 DemandedSrcElts = APInt(1, 1); // <=> 'demand all elements'
3561 else {
3562 uint64_t Idx = Op.getConstantOperandVal(1);
3563 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
3564 DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
3565 }
3566 Known = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
3567 break;
3568 }
3569 case ISD::SCALAR_TO_VECTOR: {
3570 if (Op.getValueType().isScalableVector())
3571 break;
3572 // We know about scalar_to_vector as much as we know about it source,
3573 // which becomes the first element of otherwise unknown vector.
3574 if (DemandedElts != 1)
3575 break;
3576
3577 SDValue N0 = Op.getOperand(0);
3578 Known = computeKnownBits(N0, Depth + 1);
3579 if (N0.getValueSizeInBits() != BitWidth)
3580 Known = Known.trunc(BitWidth);
3581
3582 break;
3583 }
3584 case ISD::BITCAST: {
3585 if (Op.getValueType().isScalableVector())
3586 break;
3587
3588 SDValue N0 = Op.getOperand(0);
3589 EVT SubVT = N0.getValueType();
3590 unsigned SubBitWidth = SubVT.getScalarSizeInBits();
3591
3592 // Ignore bitcasts from unsupported types.
3593 if (!(SubVT.isInteger() || SubVT.isFloatingPoint()))
3594 break;
3595
3596 // Fast handling of 'identity' bitcasts.
3597 if (BitWidth == SubBitWidth) {
3598 Known = computeKnownBits(N0, DemandedElts, Depth + 1);
3599 break;
3600 }
3601
3602 bool IsLE = getDataLayout().isLittleEndian();
3603
3604 // Bitcast 'small element' vector to 'large element' scalar/vector.
3605 if ((BitWidth % SubBitWidth) == 0) {
3606 assert(N0.getValueType().isVector() && "Expected bitcast from vector");
3607
3608 // Collect known bits for the (larger) output by collecting the known
3609 // bits from each set of sub elements and shift these into place.
3610 // We need to separately call computeKnownBits for each set of
3611 // sub elements as the knownbits for each is likely to be different.
3612 unsigned SubScale = BitWidth / SubBitWidth;
3613 APInt SubDemandedElts(NumElts * SubScale, 0);
3614 for (unsigned i = 0; i != NumElts; ++i)
3615 if (DemandedElts[i])
3616 SubDemandedElts.setBit(i * SubScale);
3617
3618 for (unsigned i = 0; i != SubScale; ++i) {
3619 Known2 = computeKnownBits(N0, SubDemandedElts.shl(i),
3620 Depth + 1);
3621 unsigned Shifts = IsLE ? i : SubScale - 1 - i;
3622 Known.insertBits(Known2, SubBitWidth * Shifts);
3623 }
3624 }
3625
3626 // Bitcast 'large element' scalar/vector to 'small element' vector.
3627 if ((SubBitWidth % BitWidth) == 0) {
3628 assert(Op.getValueType().isVector() && "Expected bitcast to vector");
3629
3630 // Collect known bits for the (smaller) output by collecting the known
3631 // bits from the overlapping larger input elements and extracting the
3632 // sub sections we actually care about.
3633 unsigned SubScale = SubBitWidth / BitWidth;
3634 APInt SubDemandedElts =
3635 APIntOps::ScaleBitMask(DemandedElts, NumElts / SubScale);
3636 Known2 = computeKnownBits(N0, SubDemandedElts, Depth + 1);
3637
3638 Known.setAllConflict();
3639 for (unsigned i = 0; i != NumElts; ++i)
3640 if (DemandedElts[i]) {
3641 unsigned Shifts = IsLE ? i : NumElts - 1 - i;
3642 unsigned Offset = (Shifts % SubScale) * BitWidth;
3643 Known = Known.intersectWith(Known2.extractBits(BitWidth, Offset));
3644 // If we don't know any bits, early out.
3645 if (Known.isUnknown())
3646 break;
3647 }
3648 }
3649 break;
3650 }
3651 case ISD::AND:
3652 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3653 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3654
3655 Known &= Known2;
3656 break;
3657 case ISD::OR:
3658 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3659 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3660
3661 Known |= Known2;
3662 break;
3663 case ISD::XOR:
3664 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3665 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3666
3667 Known ^= Known2;
3668 break;
3669 case ISD::MUL: {
3670 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3671 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3672 bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1);
3673 // TODO: SelfMultiply can be poison, but not undef.
3674 if (SelfMultiply)
3675 SelfMultiply &= isGuaranteedNotToBeUndefOrPoison(
3676 Op.getOperand(0), DemandedElts, UndefPoisonKind::UndefOrPoison,
3677 Depth + 1);
3678 Known = KnownBits::mul(Known, Known2, SelfMultiply);
3679
3680 // If the multiplication is known not to overflow, the product of a number
3681 // with itself is non-negative. Only do this if we didn't already computed
3682 // the opposite value for the sign bit.
3683 if (Op->getFlags().hasNoSignedWrap() &&
3684 Op.getOperand(0) == Op.getOperand(1) &&
3685 !Known.isNegative())
3686 Known.makeNonNegative();
3687 break;
3688 }
3689 case ISD::MULHU: {
3690 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3691 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3692 Known = KnownBits::mulhu(Known, Known2);
3693 break;
3694 }
3695 case ISD::MULHS: {
3696 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3697 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3698 Known = KnownBits::mulhs(Known, Known2);
3699 break;
3700 }
3701 case ISD::ABDU: {
3702 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3703 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3704 Known = KnownBits::abdu(Known, Known2);
3705 break;
3706 }
3707 case ISD::ABDS: {
3708 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3709 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3710 Known = KnownBits::abds(Known, Known2);
3711 unsigned SignBits1 =
3712 ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
3713 if (SignBits1 == 1)
3714 break;
3715 unsigned SignBits0 =
3716 ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3717 Known.Zero.setHighBits(std::min(SignBits0, SignBits1) - 1);
3718 break;
3719 }
3720 case ISD::UMUL_LOHI: {
3721 assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3722 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3723 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3724 bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1);
3725 if (Op.getResNo() == 0)
3726 Known = KnownBits::mul(Known, Known2, SelfMultiply);
3727 else
3728 Known = KnownBits::mulhu(Known, Known2);
3729 break;
3730 }
3731 case ISD::SMUL_LOHI: {
3732 assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3733 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3734 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3735 bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1);
3736 if (Op.getResNo() == 0)
3737 Known = KnownBits::mul(Known, Known2, SelfMultiply);
3738 else
3739 Known = KnownBits::mulhs(Known, Known2);
3740 break;
3741 }
3742 case ISD::AVGFLOORU: {
3743 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3744 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3745 Known = KnownBits::avgFloorU(Known, Known2);
3746 break;
3747 }
3748 case ISD::AVGCEILU: {
3749 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3750 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3751 Known = KnownBits::avgCeilU(Known, Known2);
3752 break;
3753 }
3754 case ISD::AVGFLOORS: {
3755 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3756 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3757 Known = KnownBits::avgFloorS(Known, Known2);
3758 break;
3759 }
3760 case ISD::AVGCEILS: {
3761 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3762 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3763 Known = KnownBits::avgCeilS(Known, Known2);
3764 break;
3765 }
3766 case ISD::SELECT:
3767 case ISD::VSELECT:
3768 Known = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
3769 // If we don't know any bits, early out.
3770 if (Known.isUnknown())
3771 break;
3772 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth+1);
3773
3774 // Only known if known in both the LHS and RHS.
3775 Known = Known.intersectWith(Known2);
3776 break;
3777 case ISD::SELECT_CC:
3778 Known = computeKnownBits(Op.getOperand(3), DemandedElts, Depth+1);
3779 // If we don't know any bits, early out.
3780 if (Known.isUnknown())
3781 break;
3782 Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
3783
3784 // Only known if known in both the LHS and RHS.
3785 Known = Known.intersectWith(Known2);
3786 break;
3787 case ISD::SMULO:
3788 case ISD::UMULO:
3789 if (Op.getResNo() != 1)
3790 break;
3791 // The boolean result conforms to getBooleanContents.
3792 // If we know the result of a setcc has the top bits zero, use this info.
3793 // We know that we have an integer-based boolean since these operations
3794 // are only available for integer.
3795 if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
3797 BitWidth > 1)
3798 Known.Zero.setBitsFrom(1);
3799 break;
3800 case ISD::SETCC:
3801 case ISD::SETCCCARRY:
3802 case ISD::STRICT_FSETCC:
3803 case ISD::STRICT_FSETCCS: {
3804 unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
3805 // If we know the result of a setcc has the top bits zero, use this info.
3806 if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
3808 BitWidth > 1)
3809 Known.Zero.setBitsFrom(1);
3810 break;
3811 }
3812 case ISD::SHL: {
3813 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3814 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3815
3816 bool NUW = Op->getFlags().hasNoUnsignedWrap();
3817 bool NSW = Op->getFlags().hasNoSignedWrap();
3818
3819 bool ShAmtNonZero = Known2.isNonZero();
3820
3821 Known = KnownBits::shl(Known, Known2, NUW, NSW, ShAmtNonZero);
3822
3823 // Minimum shift low bits are known zero.
3824 if (std::optional<unsigned> ShMinAmt =
3825 getValidMinimumShiftAmount(Op, DemandedElts, Depth + 1))
3826 Known.Zero.setLowBits(*ShMinAmt);
3827 break;
3828 }
3829 case ISD::SRL:
3830 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3831 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3832 Known = KnownBits::lshr(Known, Known2, /*ShAmtNonZero=*/false,
3833 Op->getFlags().hasExact());
3834
3835 // Minimum shift high bits are known zero.
3836 if (std::optional<unsigned> ShMinAmt =
3837 getValidMinimumShiftAmount(Op, DemandedElts, Depth + 1))
3838 Known.Zero.setHighBits(*ShMinAmt);
3839 break;
3840 case ISD::SRA:
3841 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3842 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3843 Known = KnownBits::ashr(Known, Known2, /*ShAmtNonZero=*/false,
3844 Op->getFlags().hasExact());
3845 break;
3846 case ISD::ROTL:
3847 case ISD::ROTR:
3848 if (ConstantSDNode *C =
3849 isConstOrConstSplat(Op.getOperand(1), DemandedElts)) {
3850 unsigned Amt = C->getAPIntValue().urem(BitWidth);
3851
3852 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3853
3854 // Canonicalize to ROTR.
3855 if (Opcode == ISD::ROTL && Amt != 0)
3856 Amt = BitWidth - Amt;
3857
3858 Known.Zero = Known.Zero.rotr(Amt);
3859 Known.One = Known.One.rotr(Amt);
3860 }
3861 break;
3862 case ISD::FSHL:
3863 case ISD::FSHR:
3864 if (ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(2), DemandedElts)) {
3865 unsigned Amt = C->getAPIntValue().urem(BitWidth);
3866
3867 // For fshl, 0-shift returns the 1st arg.
3868 // For fshr, 0-shift returns the 2nd arg.
3869 if (Amt == 0) {
3870 Known = computeKnownBits(Op.getOperand(Opcode == ISD::FSHL ? 0 : 1),
3871 DemandedElts, Depth + 1);
3872 break;
3873 }
3874
3875 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
3876 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
3877 const APInt ShAmt(BitWidth, Amt);
3878 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3879 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3880 Known = Opcode == ISD::FSHL ? KnownBits::fshl(Known, Known2, ShAmt)
3881 : KnownBits::fshr(Known, Known2, ShAmt);
3882 }
3883 break;
3884 case ISD::SHL_PARTS:
3885 case ISD::SRA_PARTS:
3886 case ISD::SRL_PARTS: {
3887 assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3888
3889 // Collect lo/hi source values and concatenate.
3890 unsigned LoBits = Op.getOperand(0).getScalarValueSizeInBits();
3891 unsigned HiBits = Op.getOperand(1).getScalarValueSizeInBits();
3892 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3893 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3894 Known = Known2.concat(Known);
3895
3896 // Collect shift amount.
3897 Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1);
3898
3899 if (Opcode == ISD::SHL_PARTS)
3900 Known = KnownBits::shl(Known, Known2);
3901 else if (Opcode == ISD::SRA_PARTS)
3902 Known = KnownBits::ashr(Known, Known2);
3903 else // if (Opcode == ISD::SRL_PARTS)
3904 Known = KnownBits::lshr(Known, Known2);
3905
3906 // TODO: Minimum shift low/high bits are known zero.
3907
3908 if (Op.getResNo() == 0)
3909 Known = Known.extractBits(LoBits, 0);
3910 else
3911 Known = Known.extractBits(HiBits, LoBits);
3912 break;
3913 }
3915 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3916 EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3917 Known = Known.sextInReg(EVT.getScalarSizeInBits());
3918 break;
3919 }
3920 case ISD::CTTZ:
3921 case ISD::CTTZ_ZERO_POISON: {
3922 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3923 // If we have a known 1, its position is our upper bound.
3924 unsigned PossibleTZ = Known2.countMaxTrailingZeros();
3925 unsigned LowBits = llvm::bit_width(PossibleTZ);
3926 Known.Zero.setBitsFrom(LowBits);
3927 break;
3928 }
3929 case ISD::CTLZ:
3930 case ISD::CTLZ_ZERO_POISON: {
3931 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3932 // If we have a known 1, its position is our upper bound.
3933 unsigned PossibleLZ = Known2.countMaxLeadingZeros();
3934 unsigned LowBits = llvm::bit_width(PossibleLZ);
3935 Known.Zero.setBitsFrom(LowBits);
3936 break;
3937 }
3938 case ISD::CTLS: {
3939 unsigned MinRedundantSignBits =
3940 ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1) - 1;
3941 ConstantRange Range(APInt(BitWidth, MinRedundantSignBits),
3943 Known = Range.toKnownBits();
3944 break;
3945 }
3946 case ISD::CTPOP: {
3947 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3948 // If we know some of the bits are zero, they can't be one.
3949 unsigned PossibleOnes = Known2.countMaxPopulation();
3950 Known.Zero.setBitsFrom(llvm::bit_width(PossibleOnes));
3951 break;
3952 }
3953 case ISD::PARITY: {
3954 // Parity returns 0 everywhere but the LSB.
3955 Known.Zero.setBitsFrom(1);
3956 break;
3957 }
3958 case ISD::PDEP: {
3959 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3960 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3961 Known = KnownBits::pdep(Known2, Known);
3962 break;
3963 }
3964 case ISD::PEXT: {
3965 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3966 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3967 Known = KnownBits::pext(Known2, Known);
3968 break;
3969 }
3970 case ISD::CLMUL: {
3971 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3972 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3973 Known = KnownBits::clmul(Known, Known2);
3974 break;
3975 }
3976 case ISD::MGATHER:
3977 case ISD::MLOAD: {
3978 ISD::LoadExtType ETy =
3979 (Opcode == ISD::MGATHER)
3980 ? cast<MaskedGatherSDNode>(Op)->getExtensionType()
3981 : cast<MaskedLoadSDNode>(Op)->getExtensionType();
3982 if (ETy == ISD::ZEXTLOAD) {
3983 EVT MemVT = cast<MemSDNode>(Op)->getMemoryVT();
3984 KnownBits Known0(MemVT.getScalarSizeInBits());
3985 return Known0.zext(BitWidth);
3986 }
3987 break;
3988 }
3989 case ISD::LOAD: {
3991 const Constant *Cst = TLI->getTargetConstantFromLoad(LD);
3992 if (ISD::isNON_EXTLoad(LD) && Cst) {
3993 // Determine any common known bits from the loaded constant pool value.
3994 Type *CstTy = Cst->getType();
3995 if ((NumElts * BitWidth) == CstTy->getPrimitiveSizeInBits() &&
3996 !Op.getValueType().isScalableVector()) {
3997 // If its a vector splat, then we can (quickly) reuse the scalar path.
3998 // NOTE: We assume all elements match and none are UNDEF.
3999 if (CstTy->isVectorTy()) {
4000 if (const Constant *Splat = Cst->getSplatValue()) {
4001 Cst = Splat;
4002 CstTy = Cst->getType();
4003 }
4004 }
4005 // TODO - do we need to handle different bitwidths?
4006 if (CstTy->isVectorTy() && BitWidth == CstTy->getScalarSizeInBits()) {
4007 // Iterate across all vector elements finding common known bits.
4008 Known.setAllConflict();
4009 for (unsigned i = 0; i != NumElts; ++i) {
4010 if (!DemandedElts[i])
4011 continue;
4012 if (Constant *Elt = Cst->getAggregateElement(i)) {
4013 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
4014 const APInt &Value = CInt->getValue();
4015 Known.One &= Value;
4016 Known.Zero &= ~Value;
4017 continue;
4018 }
4019 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
4020 APInt Value = CFP->getValueAPF().bitcastToAPInt();
4021 Known.One &= Value;
4022 Known.Zero &= ~Value;
4023 continue;
4024 }
4025 }
4026 Known.One.clearAllBits();
4027 Known.Zero.clearAllBits();
4028 break;
4029 }
4030 } else if (BitWidth == CstTy->getPrimitiveSizeInBits()) {
4031 if (auto *CInt = dyn_cast<ConstantInt>(Cst)) {
4032 Known = KnownBits::makeConstant(CInt->getValue());
4033 } else if (auto *CFP = dyn_cast<ConstantFP>(Cst)) {
4034 Known =
4035 KnownBits::makeConstant(CFP->getValueAPF().bitcastToAPInt());
4036 }
4037 }
4038 }
4039 } else if (Op.getResNo() == 0) {
4040 unsigned ScalarMemorySize = LD->getMemoryVT().getScalarSizeInBits();
4041 KnownBits KnownScalarMemory(ScalarMemorySize);
4042 if (const MDNode *MD = LD->getRanges())
4043 computeKnownBitsFromRangeMetadata(*MD, KnownScalarMemory);
4044
4045 // Extend the Known bits from memory to the size of the scalar result.
4046 if (ISD::isZEXTLoad(Op.getNode()))
4047 Known = KnownScalarMemory.zext(BitWidth);
4048 else if (ISD::isSEXTLoad(Op.getNode()))
4049 Known = KnownScalarMemory.sext(BitWidth);
4050 else if (ISD::isEXTLoad(Op.getNode()))
4051 Known = KnownScalarMemory.anyext(BitWidth);
4052 else
4053 Known = KnownScalarMemory;
4054 assert(Known.getBitWidth() == BitWidth);
4055 return Known;
4056 }
4057 break;
4058 }
4060 if (Op.getValueType().isScalableVector())
4061 break;
4062 EVT InVT = Op.getOperand(0).getValueType();
4063 APInt InDemandedElts = DemandedElts.zext(InVT.getVectorNumElements());
4064 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
4065 Known = Known.zext(BitWidth);
4066 break;
4067 }
4068 case ISD::ZERO_EXTEND: {
4069 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4070 Known = Known.zext(BitWidth);
4071 break;
4072 }
4074 if (Op.getValueType().isScalableVector())
4075 break;
4076 EVT InVT = Op.getOperand(0).getValueType();
4077 APInt InDemandedElts = DemandedElts.zext(InVT.getVectorNumElements());
4078 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
4079 // If the sign bit is known to be zero or one, then sext will extend
4080 // it to the top bits, else it will just zext.
4081 Known = Known.sext(BitWidth);
4082 break;
4083 }
4084 case ISD::SIGN_EXTEND: {
4085 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4086 // If the sign bit is known to be zero or one, then sext will extend
4087 // it to the top bits, else it will just zext.
4088 Known = Known.sext(BitWidth);
4089 break;
4090 }
4092 if (Op.getValueType().isScalableVector())
4093 break;
4094 EVT InVT = Op.getOperand(0).getValueType();
4095 APInt InDemandedElts = DemandedElts.zext(InVT.getVectorNumElements());
4096 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
4097 Known = Known.anyext(BitWidth);
4098 break;
4099 }
4100 case ISD::ANY_EXTEND: {
4101 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4102 Known = Known.anyext(BitWidth);
4103 break;
4104 }
4105 case ISD::TRUNCATE: {
4106 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4107 Known = Known.trunc(BitWidth);
4108 break;
4109 }
4110 case ISD::TRUNCATE_SSAT_S: {
4111 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4112 Known = Known.truncSSat(BitWidth);
4113 break;
4114 }
4115 case ISD::TRUNCATE_SSAT_U: {
4116 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4117 Known = Known.truncSSatU(BitWidth);
4118 break;
4119 }
4120 case ISD::TRUNCATE_USAT_U: {
4121 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4122 Known = Known.truncUSat(BitWidth);
4123 break;
4124 }
4125 case ISD::AssertZext: {
4126 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
4128 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4129 Known.Zero |= (~InMask);
4130 Known.One &= (~Known.Zero);
4131 break;
4132 }
4133 case ISD::AssertAlign: {
4134 unsigned LogOfAlign = Log2(cast<AssertAlignSDNode>(Op)->getAlign());
4135 assert(LogOfAlign != 0);
4136
4137 // TODO: Should use maximum with source
4138 // If a node is guaranteed to be aligned, set low zero bits accordingly as
4139 // well as clearing one bits.
4140 Known.Zero.setLowBits(LogOfAlign);
4141 Known.One.clearLowBits(LogOfAlign);
4142 break;
4143 }
4144 case ISD::AssertNoFPClass: {
4145 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4146
4147 FPClassTest NoFPClass =
4148 static_cast<FPClassTest>(Op.getConstantOperandVal(1));
4149 const FPClassTest NegativeTestMask = fcNan | fcNegative;
4150 if ((NoFPClass & NegativeTestMask) == NegativeTestMask) {
4151 // Cannot be negative.
4152 Known.makeNonNegative();
4153 }
4154
4155 const FPClassTest PositiveTestMask = fcNan | fcPositive;
4156 if ((NoFPClass & PositiveTestMask) == PositiveTestMask) {
4157 // Cannot be positive.
4158 Known.makeNegative();
4159 }
4160
4161 break;
4162 }
4163 case ISD::FABS:
4164 // fabs clears the sign bit
4165 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4166 Known.makeNonNegative();
4167 break;
4168 case ISD::FGETSIGN:
4169 // All bits are zero except the low bit.
4170 Known.Zero.setBitsFrom(1);
4171 break;
4172 case ISD::ADD: {
4173 SDNodeFlags Flags = Op.getNode()->getFlags();
4174 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4175 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4176 bool SelfAdd = Op.getOperand(0) == Op.getOperand(1) &&
4178 Op.getOperand(0), DemandedElts,
4180 Known = KnownBits::add(Known, Known2, Flags.hasNoSignedWrap(),
4181 Flags.hasNoUnsignedWrap(), SelfAdd);
4182 break;
4183 }
4184 case ISD::SUB: {
4185 SDNodeFlags Flags = Op.getNode()->getFlags();
4186 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4187 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4188 Known = KnownBits::sub(Known, Known2, Flags.hasNoSignedWrap(),
4189 Flags.hasNoUnsignedWrap());
4190 break;
4191 }
4192 case ISD::USUBO:
4193 case ISD::SSUBO:
4194 case ISD::USUBO_CARRY:
4195 case ISD::SSUBO_CARRY:
4196 if (Op.getResNo() == 1) {
4197 // If we know the result of a setcc has the top bits zero, use this info.
4198 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
4200 BitWidth > 1)
4201 Known.Zero.setBitsFrom(1);
4202 break;
4203 }
4204 [[fallthrough]];
4205 case ISD::SUBC: {
4206 assert(Op.getResNo() == 0 &&
4207 "We only compute knownbits for the difference here.");
4208
4209 // With USUBO_CARRY and SSUBO_CARRY a borrow bit may be added in.
4210 KnownBits Borrow(1);
4211 if (Opcode == ISD::USUBO_CARRY || Opcode == ISD::SSUBO_CARRY) {
4212 Borrow = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1);
4213 // Borrow has bit width 1
4214 Borrow = Borrow.trunc(1);
4215 } else {
4216 Borrow.setAllZero();
4217 }
4218
4219 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4220 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4221 Known = KnownBits::computeForSubBorrow(Known, Known2, Borrow);
4222 break;
4223 }
4224 case ISD::UADDO:
4225 case ISD::SADDO:
4226 case ISD::UADDO_CARRY:
4227 case ISD::SADDO_CARRY:
4228 if (Op.getResNo() == 1) {
4229 // If we know the result of a setcc has the top bits zero, use this info.
4230 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
4232 BitWidth > 1)
4233 Known.Zero.setBitsFrom(1);
4234 break;
4235 }
4236 [[fallthrough]];
4237 case ISD::ADDC:
4238 case ISD::ADDE: {
4239 assert(Op.getResNo() == 0 && "We only compute knownbits for the sum here.");
4240
4241 // With ADDE and UADDO_CARRY, a carry bit may be added in.
4242 KnownBits Carry(1);
4243 if (Opcode == ISD::ADDE)
4244 // Can't track carry from glue, set carry to unknown.
4245 Carry.resetAll();
4246 else if (Opcode == ISD::UADDO_CARRY || Opcode == ISD::SADDO_CARRY) {
4247 Carry = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1);
4248 // Carry has bit width 1
4249 Carry = Carry.trunc(1);
4250 } else {
4251 Carry.setAllZero();
4252 }
4253
4254 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4255 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4256 Known = KnownBits::computeForAddCarry(Known, Known2, Carry);
4257 break;
4258 }
4259 case ISD::UDIV: {
4260 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4261 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4262 Known = KnownBits::udiv(Known, Known2, Op->getFlags().hasExact());
4263 break;
4264 }
4265 case ISD::SDIV: {
4266 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4267 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4268 Known = KnownBits::sdiv(Known, Known2, Op->getFlags().hasExact());
4269 break;
4270 }
4271 case ISD::SREM: {
4272 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4273 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4274 Known = KnownBits::srem(Known, Known2);
4275 break;
4276 }
4277 case ISD::UREM: {
4278 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4279 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4280 Known = KnownBits::urem(Known, Known2);
4281 break;
4282 }
4283 case ISD::EXTRACT_ELEMENT: {
4284 Known = computeKnownBits(Op.getOperand(0), Depth+1);
4285 const unsigned Index = Op.getConstantOperandVal(1);
4286 const unsigned EltBitWidth = Op.getValueSizeInBits();
4287
4288 // Remove low part of known bits mask
4289 Known.Zero = Known.Zero.getHiBits(Known.getBitWidth() - Index * EltBitWidth);
4290 Known.One = Known.One.getHiBits(Known.getBitWidth() - Index * EltBitWidth);
4291
4292 // Remove high part of known bit mask
4293 Known = Known.trunc(EltBitWidth);
4294 break;
4295 }
4297 SDValue InVec = Op.getOperand(0);
4298 SDValue EltNo = Op.getOperand(1);
4299 EVT VecVT = InVec.getValueType();
4300 // computeKnownBits not yet implemented for scalable vectors.
4301 if (VecVT.isScalableVector())
4302 break;
4303 const unsigned EltBitWidth = VecVT.getScalarSizeInBits();
4304 const unsigned NumSrcElts = VecVT.getVectorNumElements();
4305
4306 // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know
4307 // anything about the extended bits.
4308 if (BitWidth > EltBitWidth)
4309 Known = Known.trunc(EltBitWidth);
4310
4311 // If we know the element index, just demand that vector element, else for
4312 // an unknown element index, ignore DemandedElts and demand them all.
4313 APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
4314 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
4315 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
4316 DemandedSrcElts =
4317 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
4318
4319 Known = computeKnownBits(InVec, DemandedSrcElts, Depth + 1);
4320 if (BitWidth > EltBitWidth)
4321 Known = Known.anyext(BitWidth);
4322 break;
4323 }
4325 if (Op.getValueType().isScalableVector())
4326 break;
4327
4328 // If we know the element index, split the demand between the
4329 // source vector and the inserted element, otherwise assume we need
4330 // the original demanded vector elements and the value.
4331 SDValue InVec = Op.getOperand(0);
4332 SDValue InVal = Op.getOperand(1);
4333 SDValue EltNo = Op.getOperand(2);
4334 bool DemandedVal = true;
4335 APInt DemandedVecElts = DemandedElts;
4336 auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
4337 if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
4338 unsigned EltIdx = CEltNo->getZExtValue();
4339 DemandedVal = !!DemandedElts[EltIdx];
4340 DemandedVecElts.clearBit(EltIdx);
4341 }
4342 Known.setAllConflict();
4343 if (DemandedVal) {
4344 Known2 = computeKnownBits(InVal, Depth + 1);
4345 Known = Known.intersectWith(Known2.zextOrTrunc(BitWidth));
4346 }
4347 if (!!DemandedVecElts) {
4348 Known2 = computeKnownBits(InVec, DemandedVecElts, Depth + 1);
4349 Known = Known.intersectWith(Known2);
4350 }
4351 break;
4352 }
4353 case ISD::BITREVERSE: {
4354 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4355 Known = Known2.reverseBits();
4356 break;
4357 }
4358 case ISD::BSWAP: {
4359 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4360 Known = Known2.byteSwap();
4361 break;
4362 }
4363 case ISD::ABS:
4364 case ISD::ABS_MIN_POISON: {
4365 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4366 Known = Known2.abs();
4367 Known.Zero.setHighBits(
4368 ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1) - 1);
4369 break;
4370 }
4371 case ISD::USUBSAT: {
4372 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4373 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4374 Known = KnownBits::usub_sat(Known, Known2);
4375 break;
4376 }
4377 case ISD::UMIN: {
4378 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4379 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4380 Known = KnownBits::umin(Known, Known2);
4381 break;
4382 }
4383 case ISD::UMAX: {
4384 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4385 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4386 Known = KnownBits::umax(Known, Known2);
4387 break;
4388 }
4389 case ISD::SMIN:
4390 case ISD::SMAX: {
4391 // If we have a clamp pattern, we know that the number of sign bits will be
4392 // the minimum of the clamp min/max range.
4393 bool IsMax = (Opcode == ISD::SMAX);
4394 ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
4395 if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
4396 if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
4397 CstHigh =
4398 isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
4399 if (CstLow && CstHigh) {
4400 if (!IsMax)
4401 std::swap(CstLow, CstHigh);
4402
4403 const APInt &ValueLow = CstLow->getAPIntValue();
4404 const APInt &ValueHigh = CstHigh->getAPIntValue();
4405 if (ValueLow.sle(ValueHigh)) {
4406 unsigned LowSignBits = ValueLow.getNumSignBits();
4407 unsigned HighSignBits = ValueHigh.getNumSignBits();
4408 unsigned MinSignBits = std::min(LowSignBits, HighSignBits);
4409 if (ValueLow.isNegative() && ValueHigh.isNegative()) {
4410 Known.One.setHighBits(MinSignBits);
4411 break;
4412 }
4413 if (ValueLow.isNonNegative() && ValueHigh.isNonNegative()) {
4414 Known.Zero.setHighBits(MinSignBits);
4415 break;
4416 }
4417 }
4418 }
4419
4420 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4421 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4422 if (IsMax)
4423 Known = KnownBits::smax(Known, Known2);
4424 else
4425 Known = KnownBits::smin(Known, Known2);
4426
4427 // For SMAX, if CstLow is non-negative we know the result will be
4428 // non-negative and thus all sign bits are 0.
4429 // TODO: There's an equivalent of this for smin with negative constant for
4430 // known ones.
4431 if (IsMax && CstLow) {
4432 const APInt &ValueLow = CstLow->getAPIntValue();
4433 if (ValueLow.isNonNegative()) {
4434 unsigned SignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
4435 Known.Zero.setHighBits(std::min(SignBits, ValueLow.getNumSignBits()));
4436 }
4437 }
4438
4439 break;
4440 }
4441 case ISD::UINT_TO_FP: {
4442 Known.makeNonNegative();
4443 break;
4444 }
4445 case ISD::SINT_TO_FP: {
4446 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4447 if (Known2.isNonNegative())
4448 Known.makeNonNegative();
4449 else if (Known2.isNegative())
4450 Known.makeNegative();
4451 break;
4452 }
4453 case ISD::FP_TO_UINT_SAT: {
4454 // FP_TO_UINT_SAT produces an unsigned value that fits in the saturating VT.
4455 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
4457 break;
4458 }
4459 case ISD::ATOMIC_LOAD: {
4460 // If we are looking at the loaded value.
4461 if (Op.getResNo() == 0) {
4462 auto *AT = cast<AtomicSDNode>(Op);
4463 unsigned ScalarMemorySize = AT->getMemoryVT().getScalarSizeInBits();
4464 KnownBits KnownScalarMemory(ScalarMemorySize);
4465 if (const MDNode *MD = AT->getRanges())
4466 computeKnownBitsFromRangeMetadata(*MD, KnownScalarMemory);
4467
4468 switch (AT->getExtensionType()) {
4469 case ISD::ZEXTLOAD:
4470 Known = KnownScalarMemory.zext(BitWidth);
4471 break;
4472 case ISD::SEXTLOAD:
4473 Known = KnownScalarMemory.sext(BitWidth);
4474 break;
4475 case ISD::EXTLOAD:
4476 switch (TLI->getExtendForAtomicOps()) {
4477 case ISD::ZERO_EXTEND:
4478 Known = KnownScalarMemory.zext(BitWidth);
4479 break;
4480 case ISD::SIGN_EXTEND:
4481 Known = KnownScalarMemory.sext(BitWidth);
4482 break;
4483 default:
4484 Known = KnownScalarMemory.anyext(BitWidth);
4485 break;
4486 }
4487 break;
4488 case ISD::NON_EXTLOAD:
4489 Known = KnownScalarMemory;
4490 break;
4491 }
4492 assert(Known.getBitWidth() == BitWidth);
4493 }
4494 break;
4495 }
4497 if (Op.getResNo() == 1) {
4498 // The boolean result conforms to getBooleanContents.
4499 // If we know the result of a setcc has the top bits zero, use this info.
4500 // We know that we have an integer-based boolean since these operations
4501 // are only available for integer.
4502 if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
4504 BitWidth > 1)
4505 Known.Zero.setBitsFrom(1);
4506 break;
4507 }
4508 [[fallthrough]];
4510 case ISD::ATOMIC_SWAP:
4521 case ISD::ATOMIC_LOAD_UMAX: {
4522 // If we are looking at the loaded value.
4523 if (Op.getResNo() == 0) {
4524 auto *AT = cast<AtomicSDNode>(Op);
4525 unsigned MemBits = AT->getMemoryVT().getScalarSizeInBits();
4526
4527 if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND)
4528 Known.Zero.setBitsFrom(MemBits);
4529 }
4530 break;
4531 }
4532 case ISD::FrameIndex:
4533 case ISD::TargetFrameIndex: {
4534 const MachineFunction &MF = getMachineFunction();
4535 int FrameIdx = cast<FrameIndexSDNode>(Op)->getIndex();
4536 TLI->computeKnownBitsForStackObjectPointer(
4537 Known, MF, MF.getFrameInfo().getObjectAlign(FrameIdx));
4538 break;
4539 }
4540
4541 default:
4542 if (Opcode < ISD::BUILTIN_OP_END)
4543 break;
4544 [[fallthrough]];
4548 // Allow the target to implement this method for its nodes.
4549 TLI->computeKnownBitsForTargetNode(Op, Known, DemandedElts, *this, Depth);
4550 break;
4551 }
4552
4553 return Known;
4554}
4555
4556/// Convert ConstantRange OverflowResult into SelectionDAG::OverflowKind.
4569
4572 // X + 0 never overflow
4573 if (isNullConstant(N1))
4574 return OFK_Never;
4575
4576 // If both operands each have at least two sign bits, the addition
4577 // cannot overflow.
4578 if (ComputeNumSignBits(N0) > 1 && ComputeNumSignBits(N1) > 1)
4579 return OFK_Never;
4580
4581 // TODO: Add ConstantRange::signedAddMayOverflow handling.
4582 return OFK_Sometime;
4583}
4584
4587 // X + 0 never overflow
4588 if (isNullConstant(N1))
4589 return OFK_Never;
4590
4591 // mulhi + 1 never overflow
4592 KnownBits N1Known = computeKnownBits(N1);
4593 if (N0.getOpcode() == ISD::UMUL_LOHI && N0.getResNo() == 1 &&
4594 N1Known.getMaxValue().ult(2))
4595 return OFK_Never;
4596
4597 KnownBits N0Known = computeKnownBits(N0);
4598 if (N1.getOpcode() == ISD::UMUL_LOHI && N1.getResNo() == 1 &&
4599 N0Known.getMaxValue().ult(2))
4600 return OFK_Never;
4601
4602 // Fallback to ConstantRange::unsignedAddMayOverflow handling.
4603 ConstantRange N0Range = ConstantRange::fromKnownBits(N0Known, false);
4604 ConstantRange N1Range = ConstantRange::fromKnownBits(N1Known, false);
4605 return mapOverflowResult(N0Range.unsignedAddMayOverflow(N1Range));
4606}
4607
4610 // X - 0 never overflow
4611 if (isNullConstant(N1))
4612 return OFK_Never;
4613
4614 // If both operands each have at least two sign bits, the subtraction
4615 // cannot overflow.
4616 if (ComputeNumSignBits(N0) > 1 && ComputeNumSignBits(N1) > 1)
4617 return OFK_Never;
4618
4619 KnownBits N0Known = computeKnownBits(N0);
4620 KnownBits N1Known = computeKnownBits(N1);
4621 ConstantRange N0Range = ConstantRange::fromKnownBits(N0Known, true);
4622 ConstantRange N1Range = ConstantRange::fromKnownBits(N1Known, true);
4623 return mapOverflowResult(N0Range.signedSubMayOverflow(N1Range));
4624}
4625
4628 // X - 0 never overflow
4629 if (isNullConstant(N1))
4630 return OFK_Never;
4631
4632 ConstantRange N0Range =
4633 computeConstantRangeIncludingKnownBits(N0, /*ForSigned=*/false);
4634 ConstantRange N1Range =
4635 computeConstantRangeIncludingKnownBits(N1, /*ForSigned=*/false);
4636 return mapOverflowResult(N0Range.unsignedSubMayOverflow(N1Range));
4637}
4638
4641 // X * 0 and X * 1 never overflow.
4642 if (isNullConstant(N1) || isOneConstant(N1))
4643 return OFK_Never;
4644
4647 return mapOverflowResult(N0Range.unsignedMulMayOverflow(N1Range));
4648}
4649
4652 // X * 0 and X * 1 never overflow.
4653 if (isNullConstant(N1) || isOneConstant(N1))
4654 return OFK_Never;
4655
4656 // Get the size of the result.
4657 unsigned BitWidth = N0.getScalarValueSizeInBits();
4658
4659 // Sum of the sign bits.
4660 unsigned SignBits = ComputeNumSignBits(N0) + ComputeNumSignBits(N1);
4661
4662 // If we have enough sign bits, then there's no overflow.
4663 if (SignBits > BitWidth + 1)
4664 return OFK_Never;
4665
4666 if (SignBits == BitWidth + 1) {
4667 // The overflow occurs when the true multiplication of the
4668 // the operands is the minimum negative number.
4669 KnownBits N0Known = computeKnownBits(N0);
4670 KnownBits N1Known = computeKnownBits(N1);
4671 // If one of the operands is non-negative, then there's no
4672 // overflow.
4673 if (N0Known.isNonNegative() || N1Known.isNonNegative())
4674 return OFK_Never;
4675 }
4676
4677 return OFK_Sometime;
4678}
4679
4681 unsigned Depth) const {
4682 APInt DemandedElts = getDemandAllEltsMask(Op);
4683 return computeConstantRange(Op, DemandedElts, ForSigned, Depth);
4684}
4685
4687 const APInt &DemandedElts,
4688 bool ForSigned,
4689 unsigned Depth) const {
4690 EVT VT = Op.getValueType();
4691 unsigned BitWidth = VT.getScalarSizeInBits();
4692
4693 if (Depth >= MaxRecursionDepth)
4694 return ConstantRange::getFull(BitWidth);
4695
4696 if (ConstantSDNode *C = isConstOrConstSplat(Op, DemandedElts))
4697 return ConstantRange(C->getAPIntValue());
4698
4699 unsigned Opcode = Op.getOpcode();
4700 switch (Opcode) {
4701 case ISD::VSCALE: {
4703 const APInt &Multiplier = Op.getConstantOperandAPInt(0);
4704 return getVScaleRange(&F, BitWidth).multiply(Multiplier);
4705 }
4706 default:
4707 break;
4708 }
4709
4710 return ConstantRange::getFull(BitWidth);
4711}
4712
4715 unsigned Depth) const {
4716 APInt DemandedElts = getDemandAllEltsMask(Op);
4717 return computeConstantRangeIncludingKnownBits(Op, DemandedElts, ForSigned,
4718 Depth);
4719}
4720
4722 SDValue Op, const APInt &DemandedElts, bool ForSigned,
4723 unsigned Depth) const {
4724 KnownBits Known = computeKnownBits(Op, DemandedElts, Depth);
4726 ConstantRange CR2 = computeConstantRange(Op, DemandedElts, ForSigned, Depth);
4729 return CR1.intersectWith(CR2, RangeType);
4730}
4731
4733 unsigned Depth) const {
4734 APInt DemandedElts = getDemandAllEltsMask(Val);
4735 return isKnownToBeAPowerOfTwo(Val, DemandedElts, OrZero, Depth);
4736}
4737
4739 const APInt &DemandedElts,
4740 bool OrZero, unsigned Depth) const {
4741 if (Depth >= MaxRecursionDepth)
4742 return false; // Limit search depth.
4743
4744 EVT OpVT = Val.getValueType();
4745 unsigned BitWidth = OpVT.getScalarSizeInBits();
4746 [[maybe_unused]] unsigned NumElts = DemandedElts.getBitWidth();
4747 assert((!OpVT.isScalableVector() || NumElts == 1) &&
4748 "DemandedElts for scalable vectors must be 1 to represent all lanes");
4749 assert(
4750 (!OpVT.isFixedLengthVector() || NumElts == OpVT.getVectorNumElements()) &&
4751 "Unexpected vector size");
4752
4753 auto IsPowerOfTwoOrZero = [BitWidth, OrZero](const ConstantSDNode *C) {
4754 APInt V = C->getAPIntValue().zextOrTrunc(BitWidth);
4755 return (OrZero && V.isZero()) || V.isPowerOf2();
4756 };
4757
4758 // Is the constant a known power of 2 or zero?
4759 if (ISD::matchUnaryPredicate(Val, DemandedElts, IsPowerOfTwoOrZero,
4760 /*AllowUndefs=*/false, /*AllowTruncation=*/true))
4761 return true;
4762
4763 switch (Val.getOpcode()) {
4765 SDValue InVec = Val.getOperand(0);
4766 SDValue EltNo = Val.getOperand(1);
4767 EVT VecVT = InVec.getValueType();
4768
4769 // Skip scalable vectors or implicit extensions.
4770 if (VecVT.isScalableVector() ||
4771 OpVT.getScalarSizeInBits() != VecVT.getScalarSizeInBits())
4772 break;
4773
4774 // If we know the element index, just demand that vector element, else for
4775 // an unknown element index, ignore DemandedElts and demand them all.
4776 const unsigned NumSrcElts = VecVT.getVectorNumElements();
4777 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
4778 APInt DemandedSrcElts =
4779 ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts)
4780 ? APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue())
4781 : APInt::getAllOnes(NumSrcElts);
4782 return isKnownToBeAPowerOfTwo(InVec, DemandedSrcElts, OrZero, Depth + 1);
4783 }
4784
4785 case ISD::AND: {
4786 // Looking for `x & -x` pattern:
4787 // If x == 0:
4788 // x & -x -> 0
4789 // If x != 0:
4790 // x & -x -> non-zero pow2
4791 // so if we find the pattern return whether we know `x` is non-zero.
4792 SDValue X, Z;
4793 if (sd_match(Val, m_And(m_Value(X), m_Neg(m_Deferred(X)))) ||
4794 (sd_match(Val, m_And(m_Value(X), m_Sub(m_Value(Z), m_Deferred(X)))) &&
4795 MaskedVectorIsZero(Z, DemandedElts, Depth + 1)))
4796 return OrZero || isKnownNeverZero(X, DemandedElts, Depth);
4797 break;
4798 }
4799
4800 case ISD::SHL: {
4801 // A left-shift of a constant one will have exactly one bit set because
4802 // shifting the bit off the end is undefined.
4803 auto *C = isConstOrConstSplat(Val.getOperand(0), DemandedElts);
4804 if (C && C->getAPIntValue() == 1)
4805 return true;
4806 return (OrZero || isKnownNeverZero(Val, DemandedElts, Depth)) &&
4807 isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedElts, OrZero,
4808 Depth + 1);
4809 }
4810
4811 case ISD::SRL: {
4812 // A logical right-shift of a constant sign-bit will have exactly
4813 // one bit set.
4814 auto *C = isConstOrConstSplat(Val.getOperand(0), DemandedElts);
4815 if (C && C->getAPIntValue().isSignMask())
4816 return true;
4817 return (OrZero || isKnownNeverZero(Val, DemandedElts, Depth)) &&
4818 isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedElts, OrZero,
4819 Depth + 1);
4820 }
4821
4822 case ISD::TRUNCATE:
4823 return (OrZero || isKnownNeverZero(Val, DemandedElts, Depth)) &&
4824 isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedElts, OrZero,
4825 Depth + 1);
4826
4827 case ISD::ROTL:
4828 case ISD::ROTR:
4829 return isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedElts, OrZero,
4830 Depth + 1);
4831 case ISD::BSWAP:
4832 case ISD::BITREVERSE:
4833 return isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedElts, OrZero,
4834 Depth + 1);
4835
4836 case ISD::SMIN:
4837 case ISD::SMAX:
4838 case ISD::UMIN:
4839 case ISD::UMAX:
4840 return isKnownToBeAPowerOfTwo(Val.getOperand(1), DemandedElts, OrZero,
4841 Depth + 1) &&
4842 isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedElts, OrZero,
4843 Depth + 1);
4844
4845 case ISD::SELECT:
4846 case ISD::VSELECT:
4847 return isKnownToBeAPowerOfTwo(Val.getOperand(2), DemandedElts, OrZero,
4848 Depth + 1) &&
4849 isKnownToBeAPowerOfTwo(Val.getOperand(1), DemandedElts, OrZero,
4850 Depth + 1);
4851
4852 case ISD::ZERO_EXTEND:
4853 return isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedElts, OrZero,
4854 Depth + 1);
4855
4856 case ISD::VSCALE:
4857 // vscale(power-of-two) is a power-of-two
4858 return isKnownToBeAPowerOfTwo(Val.getOperand(0), /*OrZero=*/false,
4859 Depth + 1);
4860
4861 case ISD::VECTOR_SHUFFLE: {
4863 // Demanded elements with undef shuffle mask elements are unknown
4864 // - we cannot guarantee they are a power of two, so return false.
4865 APInt DemandedLHS, DemandedRHS;
4867 assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
4868 if (!getShuffleDemandedElts(NumElts, SVN->getMask(), DemandedElts,
4869 DemandedLHS, DemandedRHS))
4870 return false;
4871
4872 // All demanded elements from LHS must be known power of two.
4873 if (!!DemandedLHS && !isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedLHS,
4874 OrZero, Depth + 1))
4875 return false;
4876
4877 // All demanded elements from RHS must be known power of two.
4878 if (!!DemandedRHS && !isKnownToBeAPowerOfTwo(Val.getOperand(1), DemandedRHS,
4879 OrZero, Depth + 1))
4880 return false;
4881
4882 return true;
4883 }
4884 }
4885
4886 // More could be done here, though the above checks are enough
4887 // to handle some common cases.
4888 return false;
4889}
4890
4892 if (ConstantFPSDNode *C1 = isConstOrConstSplatFP(Val, true))
4893 return C1->getValueAPF().getExactLog2Abs() >= 0;
4894
4895 if (Val.getOpcode() == ISD::UINT_TO_FP || Val.getOpcode() == ISD::SINT_TO_FP)
4896 return isKnownToBeAPowerOfTwo(Val.getOperand(0), Depth + 1);
4897
4898 return false;
4899}
4900
4902 APInt DemandedElts = getDemandAllEltsMask(Op);
4903 return ComputeNumSignBits(Op, DemandedElts, Depth);
4904}
4905
4906unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, const APInt &DemandedElts,
4907 unsigned Depth) const {
4908 EVT VT = Op.getValueType();
4909 assert((VT.isInteger() || VT.isFloatingPoint()) && "Invalid VT!");
4910 unsigned VTBits = VT.getScalarSizeInBits();
4911 unsigned NumElts = DemandedElts.getBitWidth();
4912 unsigned Tmp, Tmp2;
4913 unsigned FirstAnswer = 1;
4914
4915 assert((!VT.isScalableVector() || NumElts == 1) &&
4916 "DemandedElts for scalable vectors must be 1 to represent all lanes");
4917
4918 if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
4919 const APInt &Val = C->getAPIntValue();
4920 return Val.getNumSignBits();
4921 }
4922
4923 if (Depth >= MaxRecursionDepth)
4924 return 1; // Limit search depth.
4925
4926 if (!DemandedElts)
4927 return 1; // No demanded elts, better to assume we don't know anything.
4928
4929 unsigned Opcode = Op.getOpcode();
4930 switch (Opcode) {
4931 default: break;
4932 case ISD::AssertSext:
4933 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
4934 return VTBits-Tmp+1;
4935 case ISD::AssertZext:
4936 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
4937 return VTBits-Tmp;
4938 case ISD::FREEZE:
4939 if (isGuaranteedNotToBeUndefOrPoison(Op.getOperand(0), DemandedElts,
4941 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4942 break;
4943 case ISD::MERGE_VALUES:
4944 return ComputeNumSignBits(Op.getOperand(Op.getResNo()), DemandedElts,
4945 Depth + 1);
4946 case ISD::SPLAT_VECTOR: {
4947 // Check if the sign bits of source go down as far as the truncated value.
4948 unsigned NumSrcBits = Op.getOperand(0).getValueSizeInBits();
4949 unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
4950 if (NumSrcSignBits > (NumSrcBits - VTBits))
4951 return NumSrcSignBits - (NumSrcBits - VTBits);
4952 break;
4953 }
4954 case ISD::BUILD_VECTOR:
4955 assert(!VT.isScalableVector());
4956 Tmp = VTBits;
4957 for (unsigned i = 0, e = Op.getNumOperands(); (i < e) && (Tmp > 1); ++i) {
4958 if (!DemandedElts[i])
4959 continue;
4960
4961 SDValue SrcOp = Op.getOperand(i);
4962 // BUILD_VECTOR can implicitly truncate sources, we handle this specially
4963 // for constant nodes to ensure we only look at the sign bits.
4965 APInt T = C->getAPIntValue().trunc(VTBits);
4966 Tmp2 = T.getNumSignBits();
4967 } else {
4968 Tmp2 = ComputeNumSignBits(SrcOp, Depth + 1);
4969
4970 if (SrcOp.getValueSizeInBits() != VTBits) {
4971 assert(SrcOp.getValueSizeInBits() > VTBits &&
4972 "Expected BUILD_VECTOR implicit truncation");
4973 unsigned ExtraBits = SrcOp.getValueSizeInBits() - VTBits;
4974 Tmp2 = (Tmp2 > ExtraBits ? Tmp2 - ExtraBits : 1);
4975 }
4976 }
4977 Tmp = std::min(Tmp, Tmp2);
4978 }
4979 return Tmp;
4980
4981 case ISD::VECTOR_COMPRESS: {
4982 SDValue Vec = Op.getOperand(0);
4983 SDValue PassThru = Op.getOperand(2);
4984 Tmp = ComputeNumSignBits(PassThru, DemandedElts, Depth + 1);
4985 if (Tmp == 1)
4986 return 1;
4987 Tmp2 = ComputeNumSignBits(Vec, Depth + 1);
4988 Tmp = std::min(Tmp, Tmp2);
4989 return Tmp;
4990 }
4991
4992 case ISD::VECTOR_SHUFFLE: {
4993 // Collect the minimum number of sign bits that are shared by every vector
4994 // element referenced by the shuffle.
4995 APInt DemandedLHS, DemandedRHS;
4997 assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
4998 if (!getShuffleDemandedElts(NumElts, SVN->getMask(), DemandedElts,
4999 DemandedLHS, DemandedRHS))
5000 return 1;
5001
5002 Tmp = std::numeric_limits<unsigned>::max();
5003 if (!!DemandedLHS)
5004 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedLHS, Depth + 1);
5005 if (!!DemandedRHS) {
5006 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedRHS, Depth + 1);
5007 Tmp = std::min(Tmp, Tmp2);
5008 }
5009 // If we don't know anything, early out and try computeKnownBits fall-back.
5010 if (Tmp == 1)
5011 break;
5012 assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
5013 return Tmp;
5014 }
5015
5016 case ISD::BITCAST: {
5017 if (VT.isScalableVector())
5018 break;
5019 SDValue N0 = Op.getOperand(0);
5020 EVT SrcVT = N0.getValueType();
5021 unsigned SrcBits = SrcVT.getScalarSizeInBits();
5022
5023 // Ignore bitcasts from unsupported types..
5024 if (!(SrcVT.isInteger() || SrcVT.isFloatingPoint()))
5025 break;
5026
5027 // Fast handling of 'identity' bitcasts.
5028 if (VTBits == SrcBits)
5029 return ComputeNumSignBits(N0, DemandedElts, Depth + 1);
5030
5031 bool IsLE = getDataLayout().isLittleEndian();
5032
5033 // Bitcast 'large element' scalar/vector to 'small element' vector.
5034 if ((SrcBits % VTBits) == 0) {
5035 assert(VT.isVector() && "Expected bitcast to vector");
5036
5037 unsigned Scale = SrcBits / VTBits;
5038 APInt SrcDemandedElts =
5039 APIntOps::ScaleBitMask(DemandedElts, NumElts / Scale);
5040
5041 // Fast case - sign splat can be simply split across the small elements.
5042 Tmp = ComputeNumSignBits(N0, SrcDemandedElts, Depth + 1);
5043 if (Tmp == SrcBits)
5044 return VTBits;
5045
5046 // Slow case - determine how far the sign extends into each sub-element.
5047 Tmp2 = VTBits;
5048 for (unsigned i = 0; i != NumElts; ++i)
5049 if (DemandedElts[i]) {
5050 unsigned SubOffset = i % Scale;
5051 SubOffset = (IsLE ? ((Scale - 1) - SubOffset) : SubOffset);
5052 SubOffset = SubOffset * VTBits;
5053 if (Tmp <= SubOffset)
5054 return 1;
5055 Tmp2 = std::min(Tmp2, Tmp - SubOffset);
5056 }
5057 return Tmp2;
5058 }
5059 break;
5060 }
5061
5063 // FP_TO_SINT_SAT produces a signed value that fits in the saturating VT.
5064 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
5065 return VTBits - Tmp + 1;
5066 case ISD::SIGN_EXTEND:
5067 Tmp = VTBits - Op.getOperand(0).getScalarValueSizeInBits();
5068 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1) + Tmp;
5070 // Max of the input and what this extends.
5071 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
5072 Tmp = VTBits-Tmp+1;
5073 Tmp2 = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
5074 return std::max(Tmp, Tmp2);
5076 if (VT.isScalableVector())
5077 break;
5078 SDValue Src = Op.getOperand(0);
5079 EVT SrcVT = Src.getValueType();
5080 APInt DemandedSrcElts = DemandedElts.zext(SrcVT.getVectorNumElements());
5081 Tmp = VTBits - SrcVT.getScalarSizeInBits();
5082 return ComputeNumSignBits(Src, DemandedSrcElts, Depth+1) + Tmp;
5083 }
5084 case ISD::SRA:
5085 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5086 // SRA X, C -> adds C sign bits.
5087 if (std::optional<unsigned> ShAmt =
5088 getValidMinimumShiftAmount(Op, DemandedElts, Depth + 1))
5089 Tmp = std::min(Tmp + *ShAmt, VTBits);
5090 return Tmp;
5091 case ISD::SHL:
5092 if (std::optional<ConstantRange> ShAmtRange =
5093 getValidShiftAmountRange(Op, DemandedElts, Depth + 1)) {
5094 unsigned MaxShAmt = ShAmtRange->getUnsignedMax().getZExtValue();
5095 unsigned MinShAmt = ShAmtRange->getUnsignedMin().getZExtValue();
5096 // Try to look through ZERO/SIGN/ANY_EXTEND. If all extended bits are
5097 // shifted out, then we can compute the number of sign bits for the
5098 // operand being extended. A future improvement could be to pass along the
5099 // "shifted left by" information in the recursive calls to
5100 // ComputeKnownSignBits. Allowing us to handle this more generically.
5101 if (ISD::isExtOpcode(Op.getOperand(0).getOpcode())) {
5102 SDValue Ext = Op.getOperand(0);
5103 EVT ExtVT = Ext.getValueType();
5104 SDValue Extendee = Ext.getOperand(0);
5105 EVT ExtendeeVT = Extendee.getValueType();
5106 unsigned SizeDifference =
5107 ExtVT.getScalarSizeInBits() - ExtendeeVT.getScalarSizeInBits();
5108 if (SizeDifference <= MinShAmt) {
5109 Tmp = SizeDifference +
5110 ComputeNumSignBits(Extendee, DemandedElts, Depth + 1);
5111 if (MaxShAmt < Tmp)
5112 return Tmp - MaxShAmt;
5113 }
5114 }
5115 // shl destroys sign bits, ensure it doesn't shift out all sign bits.
5116 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5117 if (MaxShAmt < Tmp)
5118 return Tmp - MaxShAmt;
5119 }
5120 break;
5121 case ISD::AND:
5122 case ISD::OR:
5123 case ISD::XOR: // NOT is handled here.
5124 // Logical binary ops preserve the number of sign bits at the worst.
5125 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
5126 if (Tmp != 1) {
5127 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
5128 FirstAnswer = std::min(Tmp, Tmp2);
5129 // We computed what we know about the sign bits as our first
5130 // answer. Now proceed to the generic code that uses
5131 // computeKnownBits, and pick whichever answer is better.
5132 }
5133 break;
5134
5135 case ISD::SELECT:
5136 case ISD::VSELECT:
5137 Tmp = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
5138 if (Tmp == 1) return 1; // Early out.
5139 Tmp2 = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
5140 return std::min(Tmp, Tmp2);
5141 case ISD::SELECT_CC:
5142 Tmp = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
5143 if (Tmp == 1) return 1; // Early out.
5144 Tmp2 = ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth+1);
5145 return std::min(Tmp, Tmp2);
5146
5147 case ISD::SMIN:
5148 case ISD::SMAX: {
5149 // If we have a clamp pattern, we know that the number of sign bits will be
5150 // the minimum of the clamp min/max range.
5151 bool IsMax = (Opcode == ISD::SMAX);
5152 ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
5153 if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
5154 if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
5155 CstHigh =
5156 isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
5157 if (CstLow && CstHigh) {
5158 if (!IsMax)
5159 std::swap(CstLow, CstHigh);
5160 if (CstLow->getAPIntValue().sle(CstHigh->getAPIntValue())) {
5161 Tmp = CstLow->getAPIntValue().getNumSignBits();
5162 Tmp2 = CstHigh->getAPIntValue().getNumSignBits();
5163 return std::min(Tmp, Tmp2);
5164 }
5165 }
5166
5167 // Fallback - just get the minimum number of sign bits of the operands.
5168 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5169 if (Tmp == 1)
5170 return 1; // Early out.
5171 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
5172 return std::min(Tmp, Tmp2);
5173 }
5174 case ISD::UMIN:
5175 case ISD::UMAX:
5176 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5177 if (Tmp == 1)
5178 return 1; // Early out.
5179 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
5180 return std::min(Tmp, Tmp2);
5181 case ISD::SSUBO_CARRY:
5182 case ISD::USUBO_CARRY:
5183 // sub_carry(x,x,c) -> 0/-1 (sext carry)
5184 if (Op.getResNo() == 0 && Op.getOperand(0) == Op.getOperand(1))
5185 return VTBits;
5186 [[fallthrough]];
5187 case ISD::SADDO:
5188 case ISD::UADDO:
5189 case ISD::SADDO_CARRY:
5190 case ISD::UADDO_CARRY:
5191 case ISD::SSUBO:
5192 case ISD::USUBO:
5193 case ISD::SMULO:
5194 case ISD::UMULO:
5195 if (Op.getResNo() != 1)
5196 break;
5197 // The boolean result conforms to getBooleanContents. Fall through.
5198 // If setcc returns 0/-1, all bits are sign bits.
5199 // We know that we have an integer-based boolean since these operations
5200 // are only available for integer.
5201 if (TLI->getBooleanContents(VT.isVector(), false) ==
5203 return VTBits;
5204 break;
5205 case ISD::SETCC:
5206 case ISD::SETCCCARRY:
5207 case ISD::STRICT_FSETCC:
5208 case ISD::STRICT_FSETCCS: {
5209 unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
5210 // If setcc returns 0/-1, all bits are sign bits.
5211 if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
5213 return VTBits;
5214 break;
5215 }
5217 // Semantically similar to icmp ult.
5218 if (TLI->getBooleanContents(VT.isVector(), /*isFloat=*/false) ==
5220 return VTBits;
5221 break;
5222 case ISD::ROTL:
5223 case ISD::ROTR: {
5224 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5225 ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(1), DemandedElts);
5226 FirstAnswer = SignBitsOps::rot(
5227 Tmp, VTBits, C ? std::optional(C->getAPIntValue()) : std::nullopt,
5228 Opcode == ISD::ROTR);
5229 break;
5230 }
5231 case ISD::ADD:
5232 case ISD::ADDC:
5233 // TODO: Move Operand 1 check before Operand 0 check
5234 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5235 if (Tmp == 1) return 1; // Early out.
5236
5237 // Special case decrementing a value (ADD X, -1):
5238 if (ConstantSDNode *CRHS =
5239 isConstOrConstSplat(Op.getOperand(1), DemandedElts))
5240 if (CRHS->isAllOnes()) {
5242 computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
5243
5244 // If the input is known to be 0 or 1, the output is 0/-1, which is all
5245 // sign bits set.
5246 if ((Known.Zero | 1).isAllOnes())
5247 return VTBits;
5248
5249 // If we are subtracting one from a positive number, there is no carry
5250 // out of the result.
5251 if (Known.isNonNegative())
5252 return Tmp;
5253 }
5254
5255 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
5256 if (Tmp2 == 1) return 1; // Early out.
5257
5258 // Add can have at most one carry bit. Thus we know that the output
5259 // is, at worst, one more bit than the inputs.
5260 return std::min(Tmp, Tmp2) - 1;
5261 case ISD::SUB:
5262 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
5263 if (Tmp2 == 1) return 1; // Early out.
5264
5265 // Handle NEG.
5266 if (ConstantSDNode *CLHS =
5267 isConstOrConstSplat(Op.getOperand(0), DemandedElts))
5268 if (CLHS->isZero()) {
5270 computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
5271 // If the input is known to be 0 or 1, the output is 0/-1, which is all
5272 // sign bits set.
5273 if ((Known.Zero | 1).isAllOnes())
5274 return VTBits;
5275
5276 // If the input is known to be positive (the sign bit is known clear),
5277 // the output of the NEG has the same number of sign bits as the input.
5278 if (Known.isNonNegative())
5279 return Tmp2;
5280
5281 // Otherwise, we treat this like a SUB.
5282 }
5283
5284 // Sub can have at most one carry bit. Thus we know that the output
5285 // is, at worst, one more bit than the inputs.
5286 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5287 if (Tmp == 1) return 1; // Early out.
5288 return std::min(Tmp, Tmp2) - 1;
5289 case ISD::MUL: {
5290 // The output of the Mul can be at most twice the valid bits in the inputs.
5291 unsigned SignBitsOp0 = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
5292 if (SignBitsOp0 == 1)
5293 break;
5294 unsigned SignBitsOp1 = ComputeNumSignBits(Op.getOperand(1), Depth + 1);
5295 if (SignBitsOp1 == 1)
5296 break;
5297 unsigned OutValidBits =
5298 (VTBits - SignBitsOp0 + 1) + (VTBits - SignBitsOp1 + 1);
5299 return OutValidBits > VTBits ? 1 : VTBits - OutValidBits + 1;
5300 }
5301 case ISD::AVGCEILS:
5302 case ISD::AVGFLOORS:
5303 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5304 if (Tmp == 1)
5305 return 1; // Early out.
5306 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
5307 return std::min(Tmp, Tmp2);
5308 case ISD::SREM:
5309 // The sign bit is the LHS's sign bit, except when the result of the
5310 // remainder is zero. The magnitude of the result should be less than or
5311 // equal to the magnitude of the LHS. Therefore, the result should have
5312 // at least as many sign bits as the left hand side.
5313 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5314 case ISD::TRUNCATE: {
5315 // Check if the sign bits of source go down as far as the truncated value.
5316 unsigned NumSrcBits = Op.getOperand(0).getScalarValueSizeInBits();
5317 unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
5318 if (NumSrcSignBits > (NumSrcBits - VTBits))
5319 return NumSrcSignBits - (NumSrcBits - VTBits);
5320 break;
5321 }
5322 case ISD::EXTRACT_ELEMENT: {
5323 if (VT.isScalableVector())
5324 break;
5325 const int KnownSign = ComputeNumSignBits(Op.getOperand(0), Depth+1);
5326 const int BitWidth = Op.getValueSizeInBits();
5327 const int Items = Op.getOperand(0).getValueSizeInBits() / BitWidth;
5328
5329 // Get reverse index (starting from 1), Op1 value indexes elements from
5330 // little end. Sign starts at big end.
5331 const int rIndex = Items - 1 - Op.getConstantOperandVal(1);
5332
5333 // If the sign portion ends in our element the subtraction gives correct
5334 // result. Otherwise it gives either negative or > bitwidth result
5335 return std::clamp(KnownSign - rIndex * BitWidth, 1, BitWidth);
5336 }
5338 if (VT.isScalableVector())
5339 break;
5340 // If we know the element index, split the demand between the
5341 // source vector and the inserted element, otherwise assume we need
5342 // the original demanded vector elements and the value.
5343 SDValue InVec = Op.getOperand(0);
5344 SDValue InVal = Op.getOperand(1);
5345 SDValue EltNo = Op.getOperand(2);
5346 bool DemandedVal = true;
5347 APInt DemandedVecElts = DemandedElts;
5348 auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
5349 if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
5350 unsigned EltIdx = CEltNo->getZExtValue();
5351 DemandedVal = !!DemandedElts[EltIdx];
5352 DemandedVecElts.clearBit(EltIdx);
5353 }
5354 Tmp = std::numeric_limits<unsigned>::max();
5355 if (DemandedVal) {
5356 // TODO - handle implicit truncation of inserted elements.
5357 if (InVal.getScalarValueSizeInBits() != VTBits)
5358 break;
5359 Tmp2 = ComputeNumSignBits(InVal, Depth + 1);
5360 Tmp = std::min(Tmp, Tmp2);
5361 }
5362 if (!!DemandedVecElts) {
5363 Tmp2 = ComputeNumSignBits(InVec, DemandedVecElts, Depth + 1);
5364 Tmp = std::min(Tmp, Tmp2);
5365 }
5366 assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
5367 return Tmp;
5368 }
5370 SDValue InVec = Op.getOperand(0);
5371 SDValue EltNo = Op.getOperand(1);
5372 EVT VecVT = InVec.getValueType();
5373 // ComputeNumSignBits not yet implemented for scalable vectors.
5374 if (VecVT.isScalableVector())
5375 break;
5376 const unsigned BitWidth = Op.getValueSizeInBits();
5377 const unsigned EltBitWidth = Op.getOperand(0).getScalarValueSizeInBits();
5378 const unsigned NumSrcElts = VecVT.getVectorNumElements();
5379
5380 // If BitWidth > EltBitWidth the value is anyext:ed, and we do not know
5381 // anything about sign bits. But if the sizes match we can derive knowledge
5382 // about sign bits from the vector operand.
5383 if (BitWidth != EltBitWidth)
5384 break;
5385
5386 // If we know the element index, just demand that vector element, else for
5387 // an unknown element index, ignore DemandedElts and demand them all.
5388 APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
5389 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
5390 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
5391 DemandedSrcElts =
5392 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
5393
5394 return ComputeNumSignBits(InVec, DemandedSrcElts, Depth + 1);
5395 }
5397 // Offset the demanded elts by the subvector index.
5398 SDValue Src = Op.getOperand(0);
5399
5400 APInt DemandedSrcElts;
5401 if (Src.getValueType().isScalableVector())
5402 DemandedSrcElts = APInt(1, 1);
5403 else {
5404 uint64_t Idx = Op.getConstantOperandVal(1);
5405 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
5406 DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
5407 }
5408 return ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
5409 }
5410 case ISD::CONCAT_VECTORS: {
5411 if (VT.isScalableVector())
5412 break;
5413 // Determine the minimum number of sign bits across all demanded
5414 // elts of the input vectors. Early out if the result is already 1.
5415 Tmp = std::numeric_limits<unsigned>::max();
5416 EVT SubVectorVT = Op.getOperand(0).getValueType();
5417 unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
5418 unsigned NumSubVectors = Op.getNumOperands();
5419 for (unsigned i = 0; (i < NumSubVectors) && (Tmp > 1); ++i) {
5420 APInt DemandedSub =
5421 DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts);
5422 if (!DemandedSub)
5423 continue;
5424 Tmp2 = ComputeNumSignBits(Op.getOperand(i), DemandedSub, Depth + 1);
5425 Tmp = std::min(Tmp, Tmp2);
5426 }
5427 assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
5428 return Tmp;
5429 }
5430 case ISD::INSERT_SUBVECTOR: {
5431 if (VT.isScalableVector())
5432 break;
5433 // Demand any elements from the subvector and the remainder from the src its
5434 // inserted into.
5435 SDValue Src = Op.getOperand(0);
5436 SDValue Sub = Op.getOperand(1);
5437 uint64_t Idx = Op.getConstantOperandVal(2);
5438 unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
5439 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
5440 APInt DemandedSrcElts = DemandedElts;
5441 DemandedSrcElts.clearBits(Idx, Idx + NumSubElts);
5442
5443 Tmp = std::numeric_limits<unsigned>::max();
5444 if (!!DemandedSubElts) {
5445 Tmp = ComputeNumSignBits(Sub, DemandedSubElts, Depth + 1);
5446 if (Tmp == 1)
5447 return 1; // early-out
5448 }
5449 if (!!DemandedSrcElts) {
5450 Tmp2 = ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
5451 Tmp = std::min(Tmp, Tmp2);
5452 }
5453 assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
5454 return Tmp;
5455 }
5456 case ISD::LOAD: {
5457 // If we are looking at the loaded value of the SDNode.
5458 if (Op.getResNo() != 0)
5459 break;
5460
5462 if (const MDNode *Ranges = LD->getRanges()) {
5463 if (DemandedElts != 1)
5464 break;
5465
5467 if (VTBits > CR.getBitWidth()) {
5468 switch (LD->getExtensionType()) {
5469 case ISD::SEXTLOAD:
5470 CR = CR.signExtend(VTBits);
5471 break;
5472 case ISD::ZEXTLOAD:
5473 CR = CR.zeroExtend(VTBits);
5474 break;
5475 default:
5476 break;
5477 }
5478 }
5479
5480 if (VTBits != CR.getBitWidth())
5481 break;
5482 return std::min(CR.getSignedMin().getNumSignBits(),
5484 }
5485
5486 unsigned ExtType = LD->getExtensionType();
5487 switch (ExtType) {
5488 default:
5489 break;
5490 case ISD::SEXTLOAD: // e.g. i16->i32 = '17' bits known.
5491 Tmp = LD->getMemoryVT().getScalarSizeInBits();
5492 return VTBits - Tmp + 1;
5493 case ISD::ZEXTLOAD: // e.g. i16->i32 = '16' bits known.
5494 Tmp = LD->getMemoryVT().getScalarSizeInBits();
5495 return VTBits - Tmp;
5496 case ISD::NON_EXTLOAD:
5497 if (const Constant *Cst = TLI->getTargetConstantFromLoad(LD)) {
5498 // We only need to handle vectors - computeKnownBits should handle
5499 // scalar cases.
5500 Type *CstTy = Cst->getType();
5501 if (CstTy->isVectorTy() && !VT.isScalableVector() &&
5502 (NumElts * VTBits) == CstTy->getPrimitiveSizeInBits() &&
5503 VTBits == CstTy->getScalarSizeInBits()) {
5504 Tmp = VTBits;
5505 for (unsigned i = 0; i != NumElts; ++i) {
5506 if (!DemandedElts[i])
5507 continue;
5508 if (Constant *Elt = Cst->getAggregateElement(i)) {
5509 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
5510 const APInt &Value = CInt->getValue();
5511 Tmp = std::min(Tmp, Value.getNumSignBits());
5512 continue;
5513 }
5514 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
5515 APInt Value = CFP->getValueAPF().bitcastToAPInt();
5516 Tmp = std::min(Tmp, Value.getNumSignBits());
5517 continue;
5518 }
5519 }
5520 // Unknown type. Conservatively assume no bits match sign bit.
5521 return 1;
5522 }
5523 return Tmp;
5524 }
5525 }
5526 break;
5527 }
5528
5529 break;
5530 }
5533 case ISD::ATOMIC_SWAP:
5545 case ISD::ATOMIC_LOAD: {
5546 auto *AT = cast<AtomicSDNode>(Op);
5547 // If we are looking at the loaded value.
5548 if (Op.getResNo() == 0) {
5549 Tmp = AT->getMemoryVT().getScalarSizeInBits();
5550 if (Tmp == VTBits)
5551 return 1; // early-out
5552
5553 // For atomic_load, prefer to use the extension type.
5554 if (Op->getOpcode() == ISD::ATOMIC_LOAD) {
5555 switch (AT->getExtensionType()) {
5556 default:
5557 break;
5558 case ISD::SEXTLOAD:
5559 return VTBits - Tmp + 1;
5560 case ISD::ZEXTLOAD:
5561 return VTBits - Tmp;
5562 }
5563 }
5564
5565 if (TLI->getExtendForAtomicOps() == ISD::SIGN_EXTEND)
5566 return VTBits - Tmp + 1;
5567 if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND)
5568 return VTBits - Tmp;
5569 }
5570 break;
5571 }
5572 }
5573
5574 // Allow the target to implement this method for its nodes.
5575 if (Opcode >= ISD::BUILTIN_OP_END ||
5576 Opcode == ISD::INTRINSIC_WO_CHAIN ||
5577 Opcode == ISD::INTRINSIC_W_CHAIN ||
5578 Opcode == ISD::INTRINSIC_VOID) {
5579 // TODO: This can probably be removed once target code is audited. This
5580 // is here purely to reduce patch size and review complexity.
5581 if (!VT.isScalableVector()) {
5582 unsigned NumBits =
5583 TLI->ComputeNumSignBitsForTargetNode(Op, DemandedElts, *this, Depth);
5584 if (NumBits > 1)
5585 FirstAnswer = std::max(FirstAnswer, NumBits);
5586 }
5587 }
5588
5589 // Finally, if we can prove that the top bits of the result are 0's or 1's,
5590 // use this information.
5591 KnownBits Known = computeKnownBits(Op, DemandedElts, Depth);
5592 return std::max(FirstAnswer, Known.countMinSignBits());
5593}
5594
5596 unsigned Depth) const {
5597 unsigned SignBits = ComputeNumSignBits(Op, Depth);
5598 return Op.getScalarValueSizeInBits() - SignBits + 1;
5599}
5600
5602 const APInt &DemandedElts,
5603 unsigned Depth) const {
5604 unsigned SignBits = ComputeNumSignBits(Op, DemandedElts, Depth);
5605 return Op.getScalarValueSizeInBits() - SignBits + 1;
5606}
5607
5609 UndefPoisonKind Kind,
5610 unsigned Depth) const {
5611 // Early out for FREEZE.
5612 if (Op.getOpcode() == ISD::FREEZE)
5613 return true;
5614
5615 APInt DemandedElts = getDemandAllEltsMask(Op);
5616 return isGuaranteedNotToBeUndefOrPoison(Op, DemandedElts, Kind, Depth);
5617}
5618
5620 const APInt &DemandedElts,
5621 UndefPoisonKind Kind,
5622 unsigned Depth) const {
5623 unsigned Opcode = Op.getOpcode();
5624
5625 // Early out for FREEZE.
5626 if (Opcode == ISD::FREEZE)
5627 return true;
5628
5629 if (Depth >= MaxRecursionDepth)
5630 return false; // Limit search depth.
5631
5632 if (isIntOrFPConstant(Op))
5633 return true;
5634
5635 switch (Opcode) {
5636 case ISD::CONDCODE:
5637 case ISD::VALUETYPE:
5638 case ISD::FrameIndex:
5640 case ISD::CopyFromReg:
5641 return true;
5642
5643 case ISD::POISON:
5644 return !includesPoison(Kind);
5645
5646 case ISD::UNDEF:
5647 return !includesUndef(Kind);
5648
5649 case ISD::BITCAST: {
5650 SDValue Src = Op.getOperand(0);
5651 EVT SrcVT = Src.getValueType();
5652 EVT DstVT = Op.getValueType();
5653
5654 if (!SrcVT.isVector() || !DstVT.isVector())
5655 return isGuaranteedNotToBeUndefOrPoison(Src, Kind, Depth + 1);
5656
5657 unsigned SrcEltBits = SrcVT.getScalarSizeInBits();
5658 unsigned DstEltBits = DstVT.getScalarSizeInBits();
5659 ElementCount NumSrcElts = SrcVT.getVectorElementCount();
5660 [[maybe_unused]] ElementCount NumDstElts = DstVT.getVectorElementCount();
5661
5662 if (SrcEltBits == DstEltBits)
5663 return isGuaranteedNotToBeUndefOrPoison(Src, DemandedElts, Kind,
5664 Depth + 1);
5665
5666 if (SrcEltBits < DstEltBits) {
5667 if (DstEltBits % SrcEltBits != 0)
5668 return isGuaranteedNotToBeUndefOrPoison(Src, Kind, Depth + 1);
5669
5670 assert(NumSrcElts == NumDstElts * (DstEltBits / SrcEltBits) &&
5671 "Unexpected vector bitcast");
5672 APInt DemandedSrcElts =
5673 APIntOps::ScaleBitMask(DemandedElts, NumSrcElts.getKnownMinValue());
5674 return isGuaranteedNotToBeUndefOrPoison(Src, DemandedSrcElts, Kind,
5675 Depth + 1);
5676 }
5677
5678 if (SrcEltBits % DstEltBits != 0)
5679 return isGuaranteedNotToBeUndefOrPoison(Src, Kind, Depth + 1);
5680
5681 assert(NumDstElts == NumSrcElts * (SrcEltBits / DstEltBits) &&
5682 "Unexpected vector bitcast");
5683 APInt DemandedSrcElts =
5684 APIntOps::ScaleBitMask(DemandedElts, NumSrcElts.getKnownMinValue());
5685 return isGuaranteedNotToBeUndefOrPoison(Src, DemandedSrcElts, Kind,
5686 Depth + 1);
5687 }
5688
5689 case ISD::BUILD_VECTOR:
5690 // NOTE: BUILD_VECTOR has implicit truncation of wider scalar elements -
5691 // this shouldn't affect the result.
5692 for (unsigned i = 0, e = Op.getNumOperands(); i < e; ++i) {
5693 if (!DemandedElts[i])
5694 continue;
5695 if (!isGuaranteedNotToBeUndefOrPoison(Op.getOperand(i), Kind, Depth + 1))
5696 return false;
5697 }
5698 return true;
5699
5700 case ISD::CONCAT_VECTORS: {
5701 EVT VT = Op.getValueType();
5702 if (!VT.isFixedLengthVector())
5703 break;
5704
5705 EVT SubVT = Op.getOperand(0).getValueType();
5706 unsigned NumSubElts = SubVT.getVectorNumElements();
5707 for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) {
5708 APInt DemandedSubElts =
5709 DemandedElts.extractBits(NumSubElts, I * NumSubElts);
5710 if (!!DemandedSubElts &&
5711 !isGuaranteedNotToBeUndefOrPoison(Op.getOperand(I), DemandedSubElts,
5712 Kind, Depth + 1))
5713 return false;
5714 }
5715 return true;
5716 }
5717
5719 SDValue Src = Op.getOperand(0);
5720 if (Src.getValueType().isScalableVector())
5721 break;
5722 uint64_t Idx = Op.getConstantOperandVal(1);
5723 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
5724 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
5725 return isGuaranteedNotToBeUndefOrPoison(Src, DemandedSrcElts, Kind,
5726 Depth + 1);
5727 }
5728
5729 case ISD::INSERT_SUBVECTOR: {
5730 if (Op.getValueType().isScalableVector())
5731 break;
5732 SDValue Src = Op.getOperand(0);
5733 SDValue Sub = Op.getOperand(1);
5734 uint64_t Idx = Op.getConstantOperandVal(2);
5735 unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
5736 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
5737 APInt DemandedSrcElts = DemandedElts;
5738 DemandedSrcElts.clearBits(Idx, Idx + NumSubElts);
5739
5740 if (!!DemandedSubElts && !isGuaranteedNotToBeUndefOrPoison(
5741 Sub, DemandedSubElts, Kind, Depth + 1))
5742 return false;
5743 if (!!DemandedSrcElts && !isGuaranteedNotToBeUndefOrPoison(
5744 Src, DemandedSrcElts, Kind, Depth + 1))
5745 return false;
5746 return true;
5747 }
5748
5750 SDValue Src = Op.getOperand(0);
5751 auto *IndexC = dyn_cast<ConstantSDNode>(Op.getOperand(1));
5752 EVT SrcVT = Src.getValueType();
5753 if (SrcVT.isFixedLengthVector() && IndexC &&
5754 IndexC->getAPIntValue().ult(SrcVT.getVectorNumElements())) {
5755 APInt DemandedSrcElts = APInt::getOneBitSet(SrcVT.getVectorNumElements(),
5756 IndexC->getZExtValue());
5757 return isGuaranteedNotToBeUndefOrPoison(Src, DemandedSrcElts, Kind,
5758 Depth + 1);
5759 }
5760 break;
5761 }
5762
5764 SDValue InVec = Op.getOperand(0);
5765 SDValue InVal = Op.getOperand(1);
5766 SDValue EltNo = Op.getOperand(2);
5767 EVT VT = InVec.getValueType();
5768 auto *IndexC = dyn_cast<ConstantSDNode>(EltNo);
5769 if (IndexC && VT.isFixedLengthVector() &&
5770 IndexC->getAPIntValue().ult(VT.getVectorNumElements())) {
5771 if (DemandedElts[IndexC->getZExtValue()] &&
5772 !isGuaranteedNotToBeUndefOrPoison(InVal, Kind, Depth + 1))
5773 return false;
5774 APInt InVecDemandedElts = DemandedElts;
5775 InVecDemandedElts.clearBit(IndexC->getZExtValue());
5776 if (!!InVecDemandedElts &&
5778 peekThroughInsertVectorElt(InVec, InVecDemandedElts),
5779 InVecDemandedElts, Kind, Depth + 1))
5780 return false;
5781 return true;
5782 }
5783 break;
5784 }
5785
5787 // Check upper (known undef) elements.
5788 if (DemandedElts.ugt(1) && includesUndef(Kind))
5789 return false;
5790 // Check element zero.
5791 if (DemandedElts[0] &&
5792 !isGuaranteedNotToBeUndefOrPoison(Op.getOperand(0), Kind, Depth + 1))
5793 return false;
5794 return true;
5795
5796 case ISD::SPLAT_VECTOR:
5797 return isGuaranteedNotToBeUndefOrPoison(Op.getOperand(0), Kind, Depth + 1);
5798
5799 case ISD::SELECT: {
5800 return !canCreateUndefOrPoison(Op, DemandedElts, Kind,
5801 /*ConsiderFlags*/ true, Depth) &&
5802 isGuaranteedNotToBeUndefOrPoison(Op.getOperand(0), Kind,
5803 Depth + 1) &&
5804 isGuaranteedNotToBeUndefOrPoison(Op.getOperand(1), DemandedElts,
5805 Kind, Depth + 1) &&
5806 isGuaranteedNotToBeUndefOrPoison(Op.getOperand(2), DemandedElts,
5807 Kind, Depth + 1);
5808 }
5809
5810 case ISD::VECTOR_SHUFFLE: {
5811 APInt DemandedLHS, DemandedRHS;
5812 auto *SVN = cast<ShuffleVectorSDNode>(Op);
5813 if (!getShuffleDemandedElts(DemandedElts.getBitWidth(), SVN->getMask(),
5814 DemandedElts, DemandedLHS, DemandedRHS,
5815 /*AllowUndefElts=*/false))
5816 return false;
5817 if (!DemandedLHS.isZero() &&
5818 !isGuaranteedNotToBeUndefOrPoison(Op.getOperand(0), DemandedLHS, Kind,
5819 Depth + 1))
5820 return false;
5821 if (!DemandedRHS.isZero() &&
5822 !isGuaranteedNotToBeUndefOrPoison(Op.getOperand(1), DemandedRHS, Kind,
5823 Depth + 1))
5824 return false;
5825 return true;
5826 }
5827
5828 case ISD::SHL:
5829 case ISD::SRL:
5830 case ISD::SRA:
5831 // Shift amount operand is checked by canCreateUndefOrPoison. So it is
5832 // enough to check operand 0 if Op can't create undef/poison.
5833 return !canCreateUndefOrPoison(Op, DemandedElts, Kind,
5834 /*ConsiderFlags*/ true, Depth) &&
5835 isGuaranteedNotToBeUndefOrPoison(Op.getOperand(0), DemandedElts,
5836 Kind, Depth + 1);
5837
5838 case ISD::BSWAP:
5839 case ISD::CTPOP:
5840 case ISD::BITREVERSE:
5841 case ISD::AND:
5842 case ISD::OR:
5843 case ISD::XOR:
5844 case ISD::ADD:
5845 case ISD::SUB:
5846 case ISD::MUL:
5847 case ISD::SADDSAT:
5848 case ISD::UADDSAT:
5849 case ISD::SSUBSAT:
5850 case ISD::USUBSAT:
5851 case ISD::SSHLSAT:
5852 case ISD::USHLSAT:
5853 case ISD::SMIN:
5854 case ISD::SMAX:
5855 case ISD::UMIN:
5856 case ISD::UMAX:
5857 case ISD::ZERO_EXTEND:
5858 case ISD::SIGN_EXTEND:
5859 case ISD::ANY_EXTEND:
5860 case ISD::TRUNCATE:
5861 case ISD::VSELECT: {
5862 // If Op can't create undef/poison and none of its operands are undef/poison
5863 // then Op is never undef/poison. A difference from the more common check
5864 // below, outside the switch, is that we handle elementwise operations for
5865 // which the DemandedElts mask is valid for all operands here.
5866 return !canCreateUndefOrPoison(Op, DemandedElts, Kind,
5867 /*ConsiderFlags*/ true, Depth) &&
5868 all_of(Op->ops(), [&](SDValue V) {
5869 return isGuaranteedNotToBeUndefOrPoison(V, DemandedElts, Kind,
5870 Depth + 1);
5871 });
5872 }
5873
5874 // TODO: Search for noundef attributes from library functions.
5875
5876 // TODO: Pointers dereferenced by ISD::LOAD/STORE ops are noundef.
5877
5878 default:
5879 // Allow the target to implement this method for its nodes.
5880 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
5881 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID)
5882 return TLI->isGuaranteedNotToBeUndefOrPoisonForTargetNode(
5883 Op, DemandedElts, *this, Kind, Depth);
5884 break;
5885 }
5886
5887 // If Op can't create undef/poison and none of its operands are undef/poison
5888 // then Op is never undef/poison.
5889 // NOTE: TargetNodes can handle this in themselves in
5890 // isGuaranteedNotToBeUndefOrPoisonForTargetNode or let
5891 // TargetLowering::isGuaranteedNotToBeUndefOrPoisonForTargetNode handle it.
5892 return !canCreateUndefOrPoison(Op, Kind, /*ConsiderFlags*/ true, Depth) &&
5893 all_of(Op->ops(), [&](SDValue V) {
5894 return isGuaranteedNotToBeUndefOrPoison(V, Kind, Depth + 1);
5895 });
5896}
5897
5899 bool ConsiderFlags,
5900 unsigned Depth) const {
5901 APInt DemandedElts = getDemandAllEltsMask(Op);
5902 return canCreateUndefOrPoison(Op, DemandedElts, Kind, ConsiderFlags, Depth);
5903}
5904
5906 UndefPoisonKind Kind,
5907 bool ConsiderFlags,
5908 unsigned Depth) const {
5909 if (ConsiderFlags && includesPoison(Kind) && Op->hasPoisonGeneratingFlags())
5910 return true;
5911
5912 unsigned Opcode = Op.getOpcode();
5913 switch (Opcode) {
5914 case ISD::AssertSext:
5915 case ISD::AssertZext:
5916 case ISD::AssertAlign:
5918 // Assertion nodes can create poison if the assertion fails.
5919 return includesPoison(Kind);
5920
5921 case ISD::FREEZE:
5925 case ISD::SADDSAT:
5926 case ISD::UADDSAT:
5927 case ISD::SSUBSAT:
5928 case ISD::USUBSAT:
5929 case ISD::MULHU:
5930 case ISD::MULHS:
5931 case ISD::AVGFLOORS:
5932 case ISD::AVGFLOORU:
5933 case ISD::AVGCEILS:
5934 case ISD::AVGCEILU:
5935 case ISD::ABDU:
5936 case ISD::ABDS:
5937 case ISD::SMIN:
5938 case ISD::SMAX:
5939 case ISD::SCMP:
5940 case ISD::UMIN:
5941 case ISD::UMAX:
5942 case ISD::UCMP:
5943 case ISD::AND:
5944 case ISD::XOR:
5945 case ISD::ROTL:
5946 case ISD::ROTR:
5947 case ISD::FSHL:
5948 case ISD::FSHR:
5949 case ISD::BSWAP:
5950 case ISD::CTTZ:
5951 case ISD::CTLZ:
5952 case ISD::CTLS:
5953 case ISD::CTPOP:
5954 case ISD::BITREVERSE:
5955 case ISD::PARITY:
5956 case ISD::SIGN_EXTEND:
5957 case ISD::TRUNCATE:
5961 case ISD::BITCAST:
5962 case ISD::BUILD_VECTOR:
5963 case ISD::BUILD_PAIR:
5964 case ISD::SPLAT_VECTOR:
5965 case ISD::FABS:
5966 case ISD::FCEIL:
5967 case ISD::FFLOOR:
5968 case ISD::FTRUNC:
5969 case ISD::FRINT:
5970 case ISD::FNEARBYINT:
5971 case ISD::FROUND:
5972 case ISD::FROUNDEVEN:
5973 return false;
5974
5975 case ISD::ABS:
5976 // ISD::ABS defines abs(INT_MIN) -> INT_MIN and never generates poison.
5977 // Different to Intrinsic::abs.
5978 return false;
5980 // ABS_MIN_POISON may produce poison if the input is INT_MIN.
5981 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1) <= 1;
5982
5983 case ISD::ADDC:
5984 case ISD::SUBC:
5985 case ISD::ADDE:
5986 case ISD::SUBE:
5987 case ISD::SADDO:
5988 case ISD::SSUBO:
5989 case ISD::SMULO:
5990 case ISD::SADDO_CARRY:
5991 case ISD::SSUBO_CARRY:
5992 case ISD::UADDO:
5993 case ISD::USUBO:
5994 case ISD::UMULO:
5995 case ISD::UADDO_CARRY:
5996 case ISD::USUBO_CARRY:
5997 // No poison on result or overflow flags.
5998 return false;
5999
6000 case ISD::SELECT_CC:
6001 case ISD::SETCC: {
6002 // Integer setcc cannot create undef or poison.
6003 if (Op.getOperand(0).getValueType().isInteger())
6004 return false;
6005
6006 // FP compares are more complicated. They can create poison for nan/infinity
6007 // based on options and flags. The options and flags also cause special
6008 // nonan condition codes to be used. Those condition codes may be preserved
6009 // even if the nonan flag is dropped somewhere.
6010 unsigned CCOp = Opcode == ISD::SETCC ? 2 : 4;
6011 ISD::CondCode CCCode = cast<CondCodeSDNode>(Op.getOperand(CCOp))->get();
6012 return (unsigned)CCCode & 0x10U;
6013 }
6014
6015 case ISD::OR:
6016 case ISD::ZERO_EXTEND:
6017 case ISD::SELECT:
6018 case ISD::VSELECT:
6019 case ISD::ADD:
6020 case ISD::SUB:
6021 case ISD::MUL:
6022 case ISD::FNEG:
6023 case ISD::FADD:
6024 case ISD::FSUB:
6025 case ISD::FMUL:
6026 case ISD::FDIV:
6027 case ISD::FREM:
6028 case ISD::FCOPYSIGN:
6029 case ISD::FMA:
6030 case ISD::FMAD:
6031 case ISD::FMULADD:
6032 case ISD::FP_EXTEND:
6033 case ISD::FMINNUM:
6034 case ISD::FMAXNUM:
6035 case ISD::FMINNUM_IEEE:
6036 case ISD::FMAXNUM_IEEE:
6037 case ISD::FMINIMUM:
6038 case ISD::FMAXIMUM:
6039 case ISD::FMINIMUMNUM:
6040 case ISD::FMAXIMUMNUM:
6046 // No poison except from flags (which is handled above)
6047 return false;
6048
6049 case ISD::SHL:
6050 case ISD::SRL:
6051 case ISD::SRA:
6052 // If the max shift amount isn't in range, then the shift can
6053 // create poison.
6054 return includesPoison(Kind) &&
6055 !getValidMaximumShiftAmount(Op, DemandedElts, Depth + 1);
6056
6059 // If the amount is zero then the result will be poison.
6060 // TODO: Add isKnownNeverZero DemandedElts handling.
6061 return includesPoison(Kind) &&
6062 !isKnownNeverZero(Op.getOperand(0), Depth + 1);
6063
6065 // Check if we demand any upper (undef) elements.
6066 return includesUndef(Kind) && DemandedElts.ugt(1);
6067
6070 // Ensure that the element index is in bounds.
6071 if (includesPoison(Kind)) {
6072 EVT VecVT = Op.getOperand(0).getValueType();
6073 SDValue Idx = Op.getOperand(Opcode == ISD::INSERT_VECTOR_ELT ? 2 : 1);
6074 KnownBits KnownIdx = computeKnownBits(Idx, Depth + 1);
6075 return KnownIdx.getMaxValue().uge(VecVT.getVectorMinNumElements());
6076 }
6077 return false;
6078 }
6079
6080 case ISD::VECTOR_SHUFFLE: {
6081 // Check for any demanded shuffle element that is undef.
6082 auto *SVN = cast<ShuffleVectorSDNode>(Op);
6083 for (auto [Idx, Elt] : enumerate(SVN->getMask()))
6084 if (Elt < 0 && DemandedElts[Idx])
6085 return true;
6086 return false;
6087 }
6088
6090 return false;
6091
6092 default:
6093 // Allow the target to implement this method for its nodes.
6094 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
6095 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID)
6096 return TLI->canCreateUndefOrPoisonForTargetNode(
6097 Op, DemandedElts, *this, Kind, ConsiderFlags, Depth);
6098 break;
6099 }
6100
6101 // Be conservative and return true.
6102 return true;
6103}
6104
6105bool SelectionDAG::isADDLike(SDValue Op, bool NoWrap) const {
6106 unsigned Opcode = Op.getOpcode();
6107 if (Opcode == ISD::OR)
6108 return Op->getFlags().hasDisjoint() ||
6109 haveNoCommonBitsSet(Op.getOperand(0), Op.getOperand(1));
6110 if (Opcode == ISD::XOR)
6111 return !NoWrap && isMinSignedConstant(Op.getOperand(1));
6112 return false;
6113}
6114
6116 return Op.getNumOperands() == 2 && isa<ConstantSDNode>(Op.getOperand(1)) &&
6117 (Op.isAnyAdd() || isADDLike(Op));
6118}
6119
6121 FPClassTest InterestedClasses,
6122 unsigned Depth) const {
6123 APInt DemandedElts = getDemandAllEltsMask(Op);
6124 return computeKnownFPClass(Op, DemandedElts, InterestedClasses, Depth);
6125}
6126
6128 const APInt &DemandedElts,
6129 FPClassTest InterestedClasses,
6130 unsigned Depth) const {
6132
6133 if (const auto *CFP = dyn_cast<ConstantFPSDNode>(Op))
6134 return KnownFPClass(CFP->getValueAPF());
6135
6136 if (Depth >= MaxRecursionDepth)
6137 return Known;
6138
6139 if (Op.getOpcode() == ISD::UNDEF)
6140 return Known;
6141
6142 EVT VT = Op.getValueType();
6143 assert(VT.isFloatingPoint() && "Computing KnownFPClass on non-FP op!");
6144 assert((!VT.isFixedLengthVector() ||
6145 DemandedElts.getBitWidth() == VT.getVectorNumElements()) &&
6146 "Unexpected vector size");
6147
6148 if (!DemandedElts)
6149 return Known;
6150
6151 unsigned Opcode = Op.getOpcode();
6152 switch (Opcode) {
6153 case ISD::POISON: {
6154 Known.KnownFPClasses = fcNone;
6155 Known.SignBit = false;
6156 break;
6157 }
6158 case ISD::FNEG: {
6159 Known = computeKnownFPClass(Op.getOperand(0), DemandedElts,
6160 InterestedClasses, Depth + 1);
6161 Known.fneg();
6162 break;
6163 }
6164 case ISD::BUILD_VECTOR: {
6165 assert(!VT.isScalableVector());
6166 bool First = true;
6167 for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) {
6168 if (!DemandedElts[I])
6169 continue;
6170
6171 if (First) {
6172 Known =
6173 computeKnownFPClass(Op.getOperand(I), InterestedClasses, Depth + 1);
6174 First = false;
6175 } else {
6176 Known |=
6177 computeKnownFPClass(Op.getOperand(I), InterestedClasses, Depth + 1);
6178 }
6179
6180 if (Known.isUnknown())
6181 break;
6182 }
6183 break;
6184 }
6186 SDValue Src = Op.getOperand(0);
6187 auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6188 EVT SrcVT = Src.getValueType();
6189 if (SrcVT.isFixedLengthVector() && CIdx) {
6190 if (CIdx->getAPIntValue().ult(SrcVT.getVectorNumElements())) {
6191 APInt DemandedSrcElts = APInt::getOneBitSet(
6192 SrcVT.getVectorNumElements(), CIdx->getZExtValue());
6193 Known = computeKnownFPClass(Src, DemandedSrcElts, InterestedClasses,
6194 Depth + 1);
6195 } else {
6196 // Out of bounds index is poison.
6197 Known.KnownFPClasses = fcNone;
6198 }
6199 } else {
6200 Known = computeKnownFPClass(Src, InterestedClasses, Depth + 1);
6201 }
6202 break;
6203 }
6204 case ISD::SPLAT_VECTOR: {
6205 Known = computeKnownFPClass(Op.getOperand(0), InterestedClasses, Depth + 1);
6206 break;
6207 }
6208 case ISD::BITCAST: {
6209 // FIXME: It should not be necessary to check for an elementwise bitcast.
6210 // If a bitcast is not elementwise between vector / scalar types,
6211 // computeKnownBits already splices the known bits of the source elements
6212 // appropriately so as to line up with the bits of the result's demanded
6213 // elements.
6214 EVT SrcVT = Op.getOperand(0).getValueType();
6215 if (VT.isScalableVector() || SrcVT.isScalableVector())
6216 break;
6217 unsigned VTNumElts = VT.isVector() ? VT.getVectorNumElements() : 1;
6218 unsigned SrcVTNumElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1;
6219 if (VTNumElts != SrcVTNumElts)
6220 break;
6221
6222 KnownBits Bits = computeKnownBits(Op, DemandedElts, Depth + 1);
6224 break;
6225 }
6226 case ISD::FABS: {
6227 Known = computeKnownFPClass(Op.getOperand(0), DemandedElts,
6228 InterestedClasses, Depth + 1);
6229 Known.fabs();
6230 break;
6231 }
6232 case ISD::FCOPYSIGN: {
6233 Known = computeKnownFPClass(Op.getOperand(0), DemandedElts,
6234 InterestedClasses, Depth + 1);
6235 KnownFPClass KnownSign = computeKnownFPClass(Op.getOperand(1), DemandedElts,
6236 InterestedClasses, Depth + 1);
6237 Known.copysign(KnownSign);
6238 break;
6239 }
6240 case ISD::AssertNoFPClass: {
6241 Known = computeKnownFPClass(Op.getOperand(0), DemandedElts,
6242 InterestedClasses, Depth + 1);
6243 FPClassTest AssertedClasses =
6244 static_cast<FPClassTest>(Op->getConstantOperandVal(1));
6245 Known.KnownFPClasses &= ~AssertedClasses;
6246 break;
6247 }
6249 SDValue Src = Op.getOperand(0);
6250 EVT SrcVT = Src.getValueType();
6251 if (SrcVT.isFixedLengthVector()) {
6252 unsigned Idx = Op.getConstantOperandVal(1);
6253 unsigned NumSrcElts = SrcVT.getVectorNumElements();
6254
6255 APInt DemandedSrcElts = DemandedElts.zextOrTrunc(NumSrcElts).shl(Idx);
6256 Known = computeKnownFPClass(Src, DemandedSrcElts, InterestedClasses,
6257 Depth + 1);
6258 } else {
6259 Known = computeKnownFPClass(Src, InterestedClasses, Depth + 1);
6260 }
6261 break;
6262 }
6263 case ISD::INSERT_SUBVECTOR: {
6264 SDValue BaseVector = Op.getOperand(0);
6265 SDValue SubVector = Op.getOperand(1);
6266 EVT BaseVT = BaseVector.getValueType();
6267 if (BaseVT.isFixedLengthVector()) {
6268 unsigned Idx = Op.getConstantOperandVal(2);
6269 unsigned NumBaseElts = BaseVT.getVectorNumElements();
6270 unsigned NumSubElts = SubVector.getValueType().getVectorNumElements();
6271
6272 APInt DemandedMask =
6273 APInt::getBitsSet(NumBaseElts, Idx, Idx + NumSubElts);
6274 APInt DemandedSrcElts = DemandedElts & ~DemandedMask;
6275 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
6276
6277 if (!DemandedSrcElts.isZero())
6278 Known = computeKnownFPClass(BaseVector, DemandedSrcElts,
6279 InterestedClasses, Depth + 1);
6280 if (!DemandedSubElts.isZero()) {
6282 SubVector, DemandedSubElts, InterestedClasses, Depth + 1);
6283 Known = DemandedSrcElts.isZero() ? SubKnown : (Known | SubKnown);
6284 }
6285 } else {
6286 Known = computeKnownFPClass(SubVector, InterestedClasses, Depth + 1);
6287 if (!Known.isUnknown())
6288 Known |= computeKnownFPClass(BaseVector, InterestedClasses, Depth + 1);
6289 }
6290 break;
6291 }
6292 case ISD::SELECT:
6293 case ISD::VSELECT: {
6294 // TODO: Add adjustKnownFPClassForSelectArm clamp recognition as in
6295 // IR-level ValueTracking.
6296 KnownFPClass KnownFalseClass = computeKnownFPClass(
6297 Op.getOperand(2), DemandedElts, InterestedClasses, Depth + 1);
6298 if (KnownFalseClass.isUnknown())
6299 break;
6300 KnownFPClass KnownTrueClass = computeKnownFPClass(
6301 Op.getOperand(1), DemandedElts, InterestedClasses, Depth + 1);
6302 Known = KnownTrueClass.intersectWith(KnownFalseClass);
6303 break;
6304 }
6305 default:
6306 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
6307 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID) {
6308 TLI->computeKnownFPClassForTargetNode(Op, Known, DemandedElts, *this,
6309 Depth);
6310 }
6311 break;
6312 }
6313
6314 return Known;
6315}
6316
6318 unsigned Depth) const {
6319 APInt DemandedElts = getDemandAllEltsMask(Op);
6320 return isKnownNeverNaN(Op, DemandedElts, SNaN, Depth);
6321}
6322
6324 bool SNaN, unsigned Depth) const {
6325 assert(!DemandedElts.isZero() && "No demanded elements");
6326
6327 // If we're told that NaNs won't happen, assume they won't.
6328 if (Op->getFlags().hasNoNaNs())
6329 return true;
6330
6331 if (Depth >= MaxRecursionDepth)
6332 return false; // Limit search depth.
6333
6334 unsigned Opcode = Op.getOpcode();
6335 switch (Opcode) {
6336 case ISD::FADD:
6337 case ISD::FSUB:
6338 case ISD::FMUL:
6339 case ISD::FDIV:
6340 case ISD::FREM:
6341 case ISD::FSIN:
6342 case ISD::FCOS:
6343 case ISD::FTAN:
6344 case ISD::FASIN:
6345 case ISD::FACOS:
6346 case ISD::FATAN:
6347 case ISD::FATAN2:
6348 case ISD::FSINH:
6349 case ISD::FCOSH:
6350 case ISD::FTANH:
6351 case ISD::FMA:
6352 case ISD::FMULADD:
6353 case ISD::FMAD: {
6354 if (SNaN)
6355 return true;
6356 // TODO: Need isKnownNeverInfinity
6357 return false;
6358 }
6359 case ISD::FCANONICALIZE:
6360 case ISD::FEXP:
6361 case ISD::FEXP2:
6362 case ISD::FEXP10:
6363 case ISD::FTRUNC:
6364 case ISD::FFLOOR:
6365 case ISD::FCEIL:
6366 case ISD::FROUND:
6367 case ISD::FROUNDEVEN:
6368 case ISD::LROUND:
6369 case ISD::LLROUND:
6370 case ISD::FRINT:
6371 case ISD::LRINT:
6372 case ISD::LLRINT:
6373 case ISD::FNEARBYINT:
6374 case ISD::FLDEXP: {
6375 if (SNaN)
6376 return true;
6377 return isKnownNeverNaN(Op.getOperand(0), DemandedElts, SNaN, Depth + 1);
6378 }
6379 case ISD::FABS:
6380 case ISD::FNEG:
6381 case ISD::FCOPYSIGN: {
6382 return isKnownNeverNaN(Op.getOperand(0), DemandedElts, SNaN, Depth + 1);
6383 }
6384 case ISD::SELECT:
6385 return isKnownNeverNaN(Op.getOperand(1), DemandedElts, SNaN, Depth + 1) &&
6386 isKnownNeverNaN(Op.getOperand(2), DemandedElts, SNaN, Depth + 1);
6387 case ISD::FP_EXTEND:
6388 case ISD::FP_ROUND: {
6389 if (SNaN)
6390 return true;
6391 return isKnownNeverNaN(Op.getOperand(0), DemandedElts, SNaN, Depth + 1);
6392 }
6393 case ISD::SINT_TO_FP:
6394 case ISD::UINT_TO_FP:
6395 return true;
6396 case ISD::FSQRT: // Need is known positive
6397 case ISD::FLOG:
6398 case ISD::FLOG2:
6399 case ISD::FLOG10:
6400 case ISD::FPOWI:
6401 case ISD::FPOW: {
6402 if (SNaN)
6403 return true;
6404 // TODO: Refine on operand
6405 return false;
6406 }
6407 case ISD::FMINNUM:
6408 case ISD::FMAXNUM:
6409 case ISD::FMINIMUMNUM:
6410 case ISD::FMAXIMUMNUM: {
6411 // Only one needs to be known not-nan, since it will be returned if the
6412 // other ends up being one.
6413 return isKnownNeverNaN(Op.getOperand(0), DemandedElts, SNaN, Depth + 1) ||
6414 isKnownNeverNaN(Op.getOperand(1), DemandedElts, SNaN, Depth + 1);
6415 }
6416 case ISD::FMINNUM_IEEE:
6417 case ISD::FMAXNUM_IEEE: {
6418 if (SNaN)
6419 return true;
6420 // This can return a NaN if either operand is an sNaN, or if both operands
6421 // are NaN.
6422 return (isKnownNeverNaN(Op.getOperand(0), DemandedElts, false, Depth + 1) &&
6423 isKnownNeverSNaN(Op.getOperand(1), DemandedElts, Depth + 1)) ||
6424 (isKnownNeverNaN(Op.getOperand(1), DemandedElts, false, Depth + 1) &&
6425 isKnownNeverSNaN(Op.getOperand(0), DemandedElts, Depth + 1));
6426 }
6427 case ISD::FMINIMUM:
6428 case ISD::FMAXIMUM: {
6429 // TODO: Does this quiet or return the origina NaN as-is?
6430 return isKnownNeverNaN(Op.getOperand(0), DemandedElts, SNaN, Depth + 1) &&
6431 isKnownNeverNaN(Op.getOperand(1), DemandedElts, SNaN, Depth + 1);
6432 }
6434 SDValue Src = Op.getOperand(0);
6435 auto *Idx = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6436 EVT SrcVT = Src.getValueType();
6437 if (SrcVT.isFixedLengthVector() && Idx &&
6438 Idx->getAPIntValue().ult(SrcVT.getVectorNumElements())) {
6439 APInt DemandedSrcElts = APInt::getOneBitSet(SrcVT.getVectorNumElements(),
6440 Idx->getZExtValue());
6441 return isKnownNeverNaN(Src, DemandedSrcElts, SNaN, Depth + 1);
6442 }
6443 return isKnownNeverNaN(Src, SNaN, Depth + 1);
6444 }
6446 SDValue Src = Op.getOperand(0);
6447 if (Src.getValueType().isFixedLengthVector()) {
6448 unsigned Idx = Op.getConstantOperandVal(1);
6449 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
6450 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
6451 return isKnownNeverNaN(Src, DemandedSrcElts, SNaN, Depth + 1);
6452 }
6453 return isKnownNeverNaN(Src, SNaN, Depth + 1);
6454 }
6455 case ISD::INSERT_SUBVECTOR: {
6456 SDValue BaseVector = Op.getOperand(0);
6457 SDValue SubVector = Op.getOperand(1);
6458 EVT BaseVectorVT = BaseVector.getValueType();
6459 if (BaseVectorVT.isFixedLengthVector()) {
6460 unsigned Idx = Op.getConstantOperandVal(2);
6461 unsigned NumBaseElts = BaseVectorVT.getVectorNumElements();
6462 unsigned NumSubElts = SubVector.getValueType().getVectorNumElements();
6463
6464 // Clear/Extract the bits at the position where the subvector will be
6465 // inserted.
6466 APInt DemandedMask =
6467 APInt::getBitsSet(NumBaseElts, Idx, Idx + NumSubElts);
6468 APInt DemandedSrcElts = DemandedElts & ~DemandedMask;
6469 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
6470
6471 bool NeverNaN = true;
6472 if (!DemandedSrcElts.isZero())
6473 NeverNaN &=
6474 isKnownNeverNaN(BaseVector, DemandedSrcElts, SNaN, Depth + 1);
6475 if (NeverNaN && !DemandedSubElts.isZero())
6476 NeverNaN &=
6477 isKnownNeverNaN(SubVector, DemandedSubElts, SNaN, Depth + 1);
6478 return NeverNaN;
6479 }
6480 return isKnownNeverNaN(BaseVector, SNaN, Depth + 1) &&
6481 isKnownNeverNaN(SubVector, SNaN, Depth + 1);
6482 }
6483 case ISD::BUILD_VECTOR: {
6484 unsigned NumElts = Op.getNumOperands();
6485 for (unsigned I = 0; I != NumElts; ++I)
6486 if (DemandedElts[I] &&
6487 !isKnownNeverNaN(Op.getOperand(I), SNaN, Depth + 1))
6488 return false;
6489 return true;
6490 }
6491 case ISD::SPLAT_VECTOR:
6492 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
6493 case ISD::AssertNoFPClass: {
6494 FPClassTest NoFPClass =
6495 static_cast<FPClassTest>(Op.getConstantOperandVal(1));
6496 if ((NoFPClass & fcNan) == fcNan)
6497 return true;
6498 if (SNaN && (NoFPClass & fcSNan) == fcSNan)
6499 return true;
6500 return isKnownNeverNaN(Op.getOperand(0), DemandedElts, SNaN, Depth + 1);
6501 }
6502 default:
6503 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
6504 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID) {
6505 return TLI->isKnownNeverNaNForTargetNode(Op, DemandedElts, *this, SNaN,
6506 Depth);
6507 }
6508 break;
6509 }
6510
6511 FPClassTest NanMask = SNaN ? fcSNan : fcNan;
6512 KnownFPClass Known = computeKnownFPClass(Op, DemandedElts, NanMask, Depth);
6513 return Known.isKnownNever(NanMask);
6514}
6515
6517 APInt DemandedElts = getDemandAllEltsMask(Op);
6518 return isKnownNeverLogicalZero(Op, DemandedElts, Depth);
6519}
6520
6522 const APInt &DemandedElts,
6523 unsigned Depth) const {
6524 assert(!DemandedElts.isZero() && "No demanded elements");
6525 EVT VT = Op.getValueType();
6527 computeKnownFPClass(Op, DemandedElts, fcZero | fcSubnormal, Depth);
6528 return Known.isKnownNeverLogicalZero(getDenormalMode(VT));
6529}
6530
6532 APInt DemandedElts = getDemandAllEltsMask(Op);
6533 return isKnownNeverZero(Op, DemandedElts, Depth);
6534}
6535
6537 unsigned Depth) const {
6538 if (Depth >= MaxRecursionDepth)
6539 return false; // Limit search depth.
6540
6541 EVT OpVT = Op.getValueType();
6542 unsigned BitWidth = OpVT.getScalarSizeInBits();
6543
6544 assert(!Op.getValueType().isFloatingPoint() &&
6545 "Floating point types unsupported - use isKnownNeverLogicalZero");
6546
6547 // If the value is a constant, we can obviously see if it is a zero or not.
6548 auto IsNeverZero = [BitWidth](const ConstantSDNode *C) {
6549 APInt V = C->getAPIntValue().zextOrTrunc(BitWidth);
6550 return !V.isZero();
6551 };
6552
6553 if (ISD::matchUnaryPredicate(Op, DemandedElts, IsNeverZero,
6554 /*AllowUndefs=*/false, /*AllowTruncation=*/true))
6555 return true;
6556
6557 // TODO: Recognize more cases here. Most of the cases are also incomplete to
6558 // some degree.
6559 switch (Op.getOpcode()) {
6560 default:
6561 break;
6562
6564 SDValue InVec = Op.getOperand(0);
6565 SDValue EltNo = Op.getOperand(1);
6566 EVT VecVT = InVec.getValueType();
6567
6568 // Skip scalable vectors or implicit extensions.
6569 if (VecVT.isScalableVector() ||
6570 OpVT.getScalarSizeInBits() != VecVT.getScalarSizeInBits())
6571 break;
6572
6573 // If we know the element index, just demand that vector element, else for
6574 // an unknown element index, ignore DemandedElts and demand them all.
6575 const unsigned NumSrcElts = VecVT.getVectorNumElements();
6576 APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
6577 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
6578 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
6579 DemandedSrcElts =
6580 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
6581
6582 return isKnownNeverZero(InVec, DemandedSrcElts, Depth + 1);
6583 }
6584
6585 case ISD::OR:
6586 return isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1) ||
6587 isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6588
6589 case ISD::VSELECT:
6590 case ISD::SELECT:
6591 return isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1) &&
6592 isKnownNeverZero(Op.getOperand(2), DemandedElts, Depth + 1);
6593
6594 case ISD::SHL: {
6595 if (Op->getFlags().hasNoSignedWrap() || Op->getFlags().hasNoUnsignedWrap())
6596 return isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6597 KnownBits ValKnown =
6598 computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
6599 // 1 << X is never zero.
6600 if (ValKnown.One[0])
6601 return true;
6602 // If max shift cnt of known ones is non-zero, result is non-zero.
6603 APInt MaxCnt = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1)
6604 .getMaxValue();
6605 if (MaxCnt.ult(ValKnown.getBitWidth()) &&
6606 !ValKnown.One.shl(MaxCnt).isZero())
6607 return true;
6608 break;
6609 }
6610
6611 case ISD::VECTOR_SHUFFLE: {
6612 if (Op.getValueType().isScalableVector())
6613 return false;
6614
6615 unsigned NumElts = DemandedElts.getBitWidth();
6616
6617 // All demanded elements from LHS and RHS must be known non-zero.
6618 // Demanded elements with undef shuffle mask elements are unknown.
6619
6620 APInt DemandedLHS, DemandedRHS;
6621 auto *SVN = cast<ShuffleVectorSDNode>(Op);
6622 assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
6623 if (!getShuffleDemandedElts(NumElts, SVN->getMask(), DemandedElts,
6624 DemandedLHS, DemandedRHS))
6625 return false;
6626
6627 return (!DemandedLHS ||
6628 isKnownNeverZero(Op.getOperand(0), DemandedLHS, Depth + 1)) &&
6629 (!DemandedRHS ||
6630 isKnownNeverZero(Op.getOperand(1), DemandedRHS, Depth + 1));
6631 }
6632
6633 case ISD::UADDSAT:
6634 case ISD::UMAX:
6635 return isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1) ||
6636 isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6637
6638 case ISD::UMIN:
6639 return isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1) &&
6640 isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6641
6642 // For smin/smax: If either operand is known negative/positive
6643 // respectively we don't need the other to be known at all.
6644 case ISD::SMAX: {
6645 KnownBits Op1 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
6646 if (Op1.isStrictlyPositive())
6647 return true;
6648
6649 KnownBits Op0 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
6650 if (Op0.isStrictlyPositive())
6651 return true;
6652
6653 if (Op1.isNonZero() && Op0.isNonZero())
6654 return true;
6655
6656 return isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1) &&
6657 isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6658 }
6659 case ISD::SMIN: {
6660 KnownBits Op1 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
6661 if (Op1.isNegative())
6662 return true;
6663
6664 KnownBits Op0 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
6665 if (Op0.isNegative())
6666 return true;
6667
6668 if (Op1.isNonZero() && Op0.isNonZero())
6669 return true;
6670
6671 return isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1) &&
6672 isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6673 }
6674
6675 case ISD::ROTL:
6676 case ISD::ROTR:
6677 case ISD::BITREVERSE:
6678 case ISD::BSWAP:
6679 case ISD::CTPOP:
6680 case ISD::ABS:
6682 return isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6683
6684 case ISD::SRA:
6685 case ISD::SRL: {
6686 if (Op->getFlags().hasExact())
6687 return isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6688 KnownBits ValKnown =
6689 computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
6690 if (ValKnown.isNegative())
6691 return true;
6692 // If max shift cnt of known ones is non-zero, result is non-zero.
6693 APInt MaxCnt = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1)
6694 .getMaxValue();
6695 if (MaxCnt.ult(ValKnown.getBitWidth()) &&
6696 !ValKnown.One.lshr(MaxCnt).isZero())
6697 return true;
6698 break;
6699 }
6700 case ISD::UDIV:
6701 case ISD::SDIV:
6702 // div exact can only produce a zero if the dividend is zero.
6703 // TODO: For udiv this is also true if Op1 u<= Op0
6704 if (Op->getFlags().hasExact())
6705 return isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6706 break;
6707
6708 case ISD::ADD:
6709 if (Op->getFlags().hasNoUnsignedWrap())
6710 if (isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1) ||
6711 isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1))
6712 return true;
6713 // TODO: There are a lot more cases we can prove for add.
6714 break;
6715
6716 case ISD::SUB: {
6717 if (isNullConstant(Op.getOperand(0)))
6718 return isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1);
6719
6720 std::optional<bool> ne = KnownBits::ne(
6721 computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1),
6722 computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1));
6723 return ne && *ne;
6724 }
6725
6726 case ISD::MUL:
6727 if (Op->getFlags().hasNoSignedWrap() || Op->getFlags().hasNoUnsignedWrap())
6728 if (isKnownNeverZero(Op.getOperand(1), Depth + 1) &&
6729 isKnownNeverZero(Op.getOperand(0), Depth + 1))
6730 return true;
6731 break;
6732
6733 case ISD::ZERO_EXTEND:
6734 case ISD::SIGN_EXTEND:
6735 return isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6736 case ISD::VSCALE: {
6738 const APInt &Multiplier = Op.getConstantOperandAPInt(0);
6739 ConstantRange CR =
6740 getVScaleRange(&F, Op.getScalarValueSizeInBits()).multiply(Multiplier);
6741 if (!CR.contains(APInt(CR.getBitWidth(), 0)))
6742 return true;
6743 break;
6744 }
6745 }
6746
6747 return computeKnownBits(Op, DemandedElts, Depth).isNonZero();
6748}
6749
6751 if (ConstantFPSDNode *C1 = isConstOrConstSplatFP(Op, true))
6752 return !C1->isNegative();
6753
6754 switch (Op.getOpcode()) {
6755 case ISD::FABS:
6756 case ISD::FEXP:
6757 case ISD::FEXP2:
6758 case ISD::FEXP10:
6759 return true;
6760 default:
6761 return false;
6762 }
6763
6764 llvm_unreachable("covered opcode switch");
6765}
6766
6768 assert(Use.getValueType().isFloatingPoint());
6769 const SDNode *User = Use.getUser();
6770 if (User->getFlags().hasNoSignedZeros())
6771 return true;
6772
6773 unsigned OperandNo = Use.getOperandNo();
6774 // Check if this use is insensitive to the sign of zero
6775 switch (User->getOpcode()) {
6776 case ISD::SETCC:
6777 // Comparisons: IEEE-754 specifies +0.0 == -0.0.
6778 case ISD::FABS:
6779 // fabs always produces +0.0.
6780 return true;
6781 case ISD::FCOPYSIGN:
6782 // copysign overwrites the sign bit of the first operand.
6783 return OperandNo == 0;
6784 case ISD::FADD:
6785 case ISD::FSUB: {
6786 // Arithmetic with non-zero constants fixes the uncertainty around the
6787 // sign bit.
6788 SDValue Other = User->getOperand(1 - OperandNo);
6790 }
6791 case ISD::FP_TO_SINT:
6792 case ISD::FP_TO_UINT:
6793 // fp-to-int conversions normalize signed zeros.
6794 return true;
6795 default:
6796 return false;
6797 }
6798}
6799
6801 if (Op->getFlags().hasNoSignedZeros())
6802 return true;
6803 // FIXME: Limit the amount of checked uses to not introduce a compile-time
6804 // regression. Ideally, this should be implemented as a demanded-bits
6805 // optimization that stems from the users.
6806 if (Op->use_size() > 2)
6807 return false;
6808 return all_of(Op->uses(),
6809 [&](const SDUse &Use) { return canIgnoreSignBitOfZero(Use); });
6810}
6811
6813 // Check the obvious case.
6814 if (A == B) return true;
6815
6816 // For negative and positive zero.
6819 if (CA->isZero() && CB->isZero()) return true;
6820
6821 // Otherwise they may not be equal.
6822 return false;
6823}
6824
6825// Only bits set in Mask must be negated, other bits may be arbitrary.
6827 if (isBitwiseNot(V, AllowUndefs))
6828 return V.getOperand(0);
6829
6830 // Handle any_extend (not (truncate X)) pattern, where Mask only sets
6831 // bits in the non-extended part.
6832 ConstantSDNode *MaskC = isConstOrConstSplat(Mask);
6833 if (!MaskC || V.getOpcode() != ISD::ANY_EXTEND)
6834 return SDValue();
6835 SDValue ExtArg = V.getOperand(0);
6836 if (ExtArg.getScalarValueSizeInBits() >=
6837 MaskC->getAPIntValue().getActiveBits() &&
6838 isBitwiseNot(ExtArg, AllowUndefs) &&
6839 ExtArg.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6840 ExtArg.getOperand(0).getOperand(0).getValueType() == V.getValueType())
6841 return ExtArg.getOperand(0).getOperand(0);
6842 return SDValue();
6843}
6844
6846 // Match masked merge pattern (X & ~M) op (Y & M)
6847 // Including degenerate case (X & ~M) op M
6848 auto MatchNoCommonBitsPattern = [&](SDValue Not, SDValue Mask,
6849 SDValue Other) {
6850 if (SDValue NotOperand =
6851 getBitwiseNotOperand(Not, Mask, /* AllowUndefs */ true)) {
6852 if (NotOperand->getOpcode() == ISD::ZERO_EXTEND ||
6853 NotOperand->getOpcode() == ISD::TRUNCATE)
6854 NotOperand = NotOperand->getOperand(0);
6855
6856 if (Other == NotOperand)
6857 return true;
6858 if (Other->getOpcode() == ISD::AND)
6859 return NotOperand == Other->getOperand(0) ||
6860 NotOperand == Other->getOperand(1);
6861 }
6862 return false;
6863 };
6864
6865 if (A->getOpcode() == ISD::ZERO_EXTEND || A->getOpcode() == ISD::TRUNCATE)
6866 A = A->getOperand(0);
6867
6868 if (B->getOpcode() == ISD::ZERO_EXTEND || B->getOpcode() == ISD::TRUNCATE)
6869 B = B->getOperand(0);
6870
6871 if (A->getOpcode() == ISD::AND)
6872 return MatchNoCommonBitsPattern(A->getOperand(0), A->getOperand(1), B) ||
6873 MatchNoCommonBitsPattern(A->getOperand(1), A->getOperand(0), B);
6874 return false;
6875}
6876
6877// FIXME: unify with llvm::haveNoCommonBitsSet.
6879 assert(A.getValueType() == B.getValueType() &&
6880 "Values must have the same type");
6883 return true;
6886}
6887
6888static SDValue FoldSTEP_VECTOR(const SDLoc &DL, EVT VT, SDValue Step,
6889 SelectionDAG &DAG) {
6890 if (cast<ConstantSDNode>(Step)->isZero())
6891 return DAG.getConstant(0, DL, VT);
6892
6893 return SDValue();
6894}
6895
6898 SelectionDAG &DAG) {
6899 int NumOps = Ops.size();
6900 assert(NumOps != 0 && "Can't build an empty vector!");
6901 assert(!VT.isScalableVector() &&
6902 "BUILD_VECTOR cannot be used with scalable types");
6903 assert(VT.getVectorNumElements() == (unsigned)NumOps &&
6904 "Incorrect element count in BUILD_VECTOR!");
6905
6906 // BUILD_VECTOR of UNDEFs is UNDEF.
6907 bool AllPoison = true;
6908 if (llvm::all_of(Ops, [&AllPoison](SDValue Op) {
6909 AllPoison &= Op.getOpcode() == ISD::POISON;
6910 return Op.isUndef();
6911 }))
6912 return AllPoison ? DAG.getPOISON(VT) : DAG.getUNDEF(VT);
6913
6914 // BUILD_VECTOR of seq extract/insert from the same vector + type is Identity.
6915 SDValue IdentitySrc;
6916 bool IsIdentity = true;
6917 for (int i = 0; i != NumOps; ++i) {
6918 if (Ops[i].getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6919 Ops[i].getOperand(0).getValueType() != VT ||
6920 (IdentitySrc && Ops[i].getOperand(0) != IdentitySrc) ||
6921 !isa<ConstantSDNode>(Ops[i].getOperand(1)) ||
6922 Ops[i].getConstantOperandAPInt(1) != i) {
6923 IsIdentity = false;
6924 break;
6925 }
6926 IdentitySrc = Ops[i].getOperand(0);
6927 }
6928 if (IsIdentity)
6929 return IdentitySrc;
6930
6931 return SDValue();
6932}
6933
6934/// Try to simplify vector concatenation to an input value, undef, or build
6935/// vector.
6938 SelectionDAG &DAG) {
6939 assert(!Ops.empty() && "Can't concatenate an empty list of vectors!");
6941 [Ops](SDValue Op) {
6942 return Ops[0].getValueType() == Op.getValueType();
6943 }) &&
6944 "Concatenation of vectors with inconsistent value types!");
6945 assert((Ops[0].getValueType().getVectorElementCount() * Ops.size()) ==
6946 VT.getVectorElementCount() &&
6947 "Incorrect element count in vector concatenation!");
6948
6949 if (Ops.size() == 1)
6950 return Ops[0];
6951
6952 // Concat of UNDEFs is UNDEF.
6953 bool AllPoison = true;
6954 if (llvm::all_of(Ops, [&AllPoison](SDValue Op) {
6955 AllPoison &= Op.getOpcode() == ISD::POISON;
6956 return Op.isUndef();
6957 }))
6958 return AllPoison ? DAG.getPOISON(VT) : DAG.getUNDEF(VT);
6959
6960 // Scan the operands and look for extract operations from a single source
6961 // that correspond to insertion at the same location via this concatenation:
6962 // concat (extract X, 0*subvec_elts), (extract X, 1*subvec_elts), ...
6963 SDValue IdentitySrc;
6964 bool IsIdentity = true;
6965 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
6966 SDValue Op = Ops[i];
6967 unsigned IdentityIndex = i * Op.getValueType().getVectorMinNumElements();
6968 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
6969 Op.getOperand(0).getValueType() != VT ||
6970 (IdentitySrc && Op.getOperand(0) != IdentitySrc) ||
6971 Op.getConstantOperandVal(1) != IdentityIndex) {
6972 IsIdentity = false;
6973 break;
6974 }
6975 assert((!IdentitySrc || IdentitySrc == Op.getOperand(0)) &&
6976 "Unexpected identity source vector for concat of extracts");
6977 IdentitySrc = Op.getOperand(0);
6978 }
6979 if (IsIdentity) {
6980 assert(IdentitySrc && "Failed to set source vector of extracts");
6981 return IdentitySrc;
6982 }
6983
6984 // The code below this point is only designed to work for fixed width
6985 // vectors, so we bail out for now.
6986 if (VT.isScalableVector())
6987 return SDValue();
6988
6989 // A CONCAT_VECTOR of scalar sources, such as UNDEF, BUILD_VECTOR and
6990 // single-element INSERT_VECTOR_ELT operands can be simplified to one big
6991 // BUILD_VECTOR.
6992 // FIXME: Add support for SCALAR_TO_VECTOR as well.
6993 EVT SVT = VT.getScalarType();
6995 for (SDValue Op : Ops) {
6996 EVT OpVT = Op.getValueType();
6997 if (Op.getOpcode() == ISD::POISON)
6998 Elts.append(OpVT.getVectorNumElements(), DAG.getPOISON(SVT));
6999 else if (Op.getOpcode() == ISD::UNDEF)
7000 Elts.append(OpVT.getVectorNumElements(), DAG.getUNDEF(SVT));
7001 else if (Op.getOpcode() == ISD::BUILD_VECTOR)
7002 Elts.append(Op->op_begin(), Op->op_end());
7003 else if (Op.getOpcode() == ISD::INSERT_VECTOR_ELT &&
7004 OpVT.getVectorNumElements() == 1 &&
7005 isNullConstant(Op.getOperand(2)))
7006 Elts.push_back(Op.getOperand(1));
7007 else
7008 return SDValue();
7009 }
7010
7011 // BUILD_VECTOR requires all inputs to be of the same type, find the
7012 // maximum type and extend them all.
7013 for (SDValue Op : Elts)
7014 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
7015
7016 if (SVT.bitsGT(VT.getScalarType())) {
7017 for (SDValue &Op : Elts) {
7018 if (Op.getOpcode() == ISD::POISON)
7019 Op = DAG.getPOISON(SVT);
7020 else if (Op.getOpcode() == ISD::UNDEF)
7021 Op = DAG.getUNDEF(SVT);
7022 else
7023 Op = DAG.getTargetLoweringInfo().isZExtFree(Op.getValueType(), SVT)
7024 ? DAG.getZExtOrTrunc(Op, DL, SVT)
7025 : DAG.getSExtOrTrunc(Op, DL, SVT);
7026 }
7027 }
7028
7029 SDValue V = DAG.getBuildVector(VT, DL, Elts);
7030 NewSDValueDbgMsg(V, "New node fold concat vectors: ", &DAG);
7031 return V;
7032}
7033
7034/// Gets or creates the specified node.
7035SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT) {
7036 SDVTList VTs = getVTList(VT);
7038 AddNodeIDNode(ID, Opcode, VTs, {});
7039 void *IP = nullptr;
7040 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
7041 return SDValue(E, 0);
7042
7043 auto *N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
7044 CSEMap.InsertNode(N, IP);
7045
7046 InsertNode(N);
7047 SDValue V = SDValue(N, 0);
7048 NewSDValueDbgMsg(V, "Creating new node: ", this);
7049 return V;
7050}
7051
7052SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
7053 SDValue N1) {
7054 SDNodeFlags Flags;
7055 if (Inserter)
7056 Flags = Inserter->getFlags();
7057 return getNode(Opcode, DL, VT, N1, Flags);
7058}
7059
7060SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
7061 SDValue N1, const SDNodeFlags Flags) {
7062 assert(N1.getOpcode() != ISD::DELETED_NODE && "Operand is DELETED_NODE!");
7063
7064 // Constant fold unary operations with a vector integer or float operand.
7065 switch (Opcode) {
7066 default:
7067 // FIXME: Entirely reasonable to perform folding of other unary
7068 // operations here as the need arises.
7069 break;
7070 case ISD::FNEG:
7071 case ISD::FABS:
7072 case ISD::FCEIL:
7073 case ISD::FTRUNC:
7074 case ISD::FFLOOR:
7075 case ISD::FP_EXTEND:
7076 case ISD::FP_TO_SINT:
7077 case ISD::FP_TO_UINT:
7078 case ISD::FP_TO_FP16:
7079 case ISD::FP_TO_BF16:
7080 case ISD::TRUNCATE:
7081 case ISD::ANY_EXTEND:
7082 case ISD::ZERO_EXTEND:
7083 case ISD::SIGN_EXTEND:
7084 case ISD::UINT_TO_FP:
7085 case ISD::SINT_TO_FP:
7086 case ISD::FP16_TO_FP:
7087 case ISD::BF16_TO_FP:
7088 case ISD::BITCAST:
7089 case ISD::ABS:
7091 case ISD::BITREVERSE:
7092 case ISD::BSWAP:
7093 case ISD::CTLZ:
7095 case ISD::CTTZ:
7097 case ISD::CTPOP:
7098 case ISD::CTLS:
7099 case ISD::VECREDUCE_ADD:
7104 case ISD::VECREDUCE_MUL:
7105 case ISD::VECREDUCE_AND:
7106 case ISD::VECREDUCE_OR:
7107 case ISD::VECREDUCE_XOR:
7108 case ISD::STEP_VECTOR: {
7109 SDValue Ops = {N1};
7110 if (SDValue Fold = FoldConstantArithmetic(Opcode, DL, VT, Ops))
7111 return Fold;
7112 }
7113 }
7114
7115 unsigned OpOpcode = N1.getNode()->getOpcode();
7116 switch (Opcode) {
7117 case ISD::STEP_VECTOR:
7118 assert(VT.isScalableVector() &&
7119 "STEP_VECTOR can only be used with scalable types");
7120 assert(OpOpcode == ISD::TargetConstant &&
7121 VT.getVectorElementType() == N1.getValueType() &&
7122 "Unexpected step operand");
7123 break;
7124 case ISD::FREEZE:
7125 assert(VT == N1.getValueType() && "Unexpected VT!");
7127 return N1;
7128 break;
7129 case ISD::TokenFactor:
7130 case ISD::MERGE_VALUES:
7132 return N1; // Factor, merge or concat of one node? No need.
7133 case ISD::BUILD_VECTOR: {
7134 // Attempt to simplify BUILD_VECTOR.
7135 SDValue Ops[] = {N1};
7136 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
7137 return V;
7138 break;
7139 }
7140 case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node");
7141 case ISD::FP_EXTEND:
7143 "Invalid FP cast!");
7144 if (N1.getValueType() == VT) return N1; // noop conversion.
7145 assert((!VT.isVector() || VT.getVectorElementCount() ==
7147 "Vector element count mismatch!");
7148 assert(N1.getValueType().bitsLT(VT) && "Invalid fpext node, dst < src!");
7149 if (N1.isUndef())
7150 return getUNDEF(VT);
7151 break;
7152 case ISD::FP_TO_SINT:
7153 case ISD::FP_TO_UINT:
7154 if (N1.isUndef())
7155 return getUNDEF(VT);
7156 break;
7157 case ISD::SINT_TO_FP:
7158 case ISD::UINT_TO_FP:
7159 // [us]itofp(undef) = 0, because the result value is bounded.
7160 if (N1.isUndef())
7161 return getConstantFP(0.0, DL, VT);
7162 break;
7163 case ISD::SIGN_EXTEND:
7164 assert(VT.isInteger() && N1.getValueType().isInteger() &&
7165 "Invalid SIGN_EXTEND!");
7166 assert(VT.isVector() == N1.getValueType().isVector() &&
7167 "SIGN_EXTEND result type type should be vector iff the operand "
7168 "type is vector!");
7169 if (N1.getValueType() == VT) return N1; // noop extension
7170 assert((!VT.isVector() || VT.getVectorElementCount() ==
7172 "Vector element count mismatch!");
7173 assert(N1.getValueType().bitsLT(VT) && "Invalid sext node, dst < src!");
7174 if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND) {
7175 SDNodeFlags Flags;
7176 if (OpOpcode == ISD::ZERO_EXTEND)
7177 Flags.setNonNeg(N1->getFlags().hasNonNeg());
7178 SDValue NewVal = getNode(OpOpcode, DL, VT, N1.getOperand(0), Flags);
7179 transferDbgValues(N1, NewVal);
7180 return NewVal;
7181 }
7182
7183 if (OpOpcode == ISD::POISON)
7184 return getPOISON(VT);
7185
7186 if (N1.isUndef())
7187 // sext(undef) = 0, because the top bits will all be the same.
7188 return getConstant(0, DL, VT);
7189
7190 // Skip unnecessary sext_inreg pattern:
7191 // (sext (trunc x)) -> x iff the upper bits are all signbits.
7192 if (OpOpcode == ISD::TRUNCATE) {
7193 SDValue OpOp = N1.getOperand(0);
7194 if (OpOp.getValueType() == VT) {
7195 unsigned NumSignExtBits =
7197 if (ComputeNumSignBits(OpOp) > NumSignExtBits) {
7198 transferDbgValues(N1, OpOp);
7199 return OpOp;
7200 }
7201 }
7202 }
7203 break;
7204 case ISD::ZERO_EXTEND:
7205 assert(VT.isInteger() && N1.getValueType().isInteger() &&
7206 "Invalid ZERO_EXTEND!");
7207 assert(VT.isVector() == N1.getValueType().isVector() &&
7208 "ZERO_EXTEND result type type should be vector iff the operand "
7209 "type is vector!");
7210 if (N1.getValueType() == VT) return N1; // noop extension
7211 assert((!VT.isVector() || VT.getVectorElementCount() ==
7213 "Vector element count mismatch!");
7214 assert(N1.getValueType().bitsLT(VT) && "Invalid zext node, dst < src!");
7215 if (OpOpcode == ISD::ZERO_EXTEND) { // (zext (zext x)) -> (zext x)
7216 SDNodeFlags Flags;
7217 Flags.setNonNeg(N1->getFlags().hasNonNeg());
7218 SDValue NewVal =
7219 getNode(ISD::ZERO_EXTEND, DL, VT, N1.getOperand(0), Flags);
7220 transferDbgValues(N1, NewVal);
7221 return NewVal;
7222 }
7223
7224 if (OpOpcode == ISD::POISON)
7225 return getPOISON(VT);
7226
7227 if (N1.isUndef())
7228 // zext(undef) = 0, because the top bits will be zero.
7229 return getConstant(0, DL, VT);
7230
7231 // Skip unnecessary zext_inreg pattern:
7232 // (zext (trunc x)) -> x iff the upper bits are known zero.
7233 // TODO: Remove (zext (trunc (and x, c))) exception which some targets
7234 // use to recognise zext_inreg patterns.
7235 if (OpOpcode == ISD::TRUNCATE) {
7236 SDValue OpOp = N1.getOperand(0);
7237 if (OpOp.getValueType() == VT) {
7238 if (OpOp.getOpcode() != ISD::AND) {
7241 if (MaskedValueIsZero(OpOp, HiBits)) {
7242 transferDbgValues(N1, OpOp);
7243 return OpOp;
7244 }
7245 }
7246 }
7247 }
7248 break;
7249 case ISD::ANY_EXTEND:
7250 assert(VT.isInteger() && N1.getValueType().isInteger() &&
7251 "Invalid ANY_EXTEND!");
7252 assert(VT.isVector() == N1.getValueType().isVector() &&
7253 "ANY_EXTEND result type type should be vector iff the operand "
7254 "type is vector!");
7255 if (N1.getValueType() == VT) return N1; // noop extension
7256 assert((!VT.isVector() || VT.getVectorElementCount() ==
7258 "Vector element count mismatch!");
7259 assert(N1.getValueType().bitsLT(VT) && "Invalid anyext node, dst < src!");
7260
7261 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
7262 OpOpcode == ISD::ANY_EXTEND) {
7263 SDNodeFlags Flags;
7264 if (OpOpcode == ISD::ZERO_EXTEND)
7265 Flags.setNonNeg(N1->getFlags().hasNonNeg());
7266 // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x)
7267 return getNode(OpOpcode, DL, VT, N1.getOperand(0), Flags);
7268 }
7269 if (N1.isUndef())
7270 return getUNDEF(VT);
7271
7272 // (ext (trunc x)) -> x
7273 if (OpOpcode == ISD::TRUNCATE) {
7274 SDValue OpOp = N1.getOperand(0);
7275 if (OpOp.getValueType() == VT) {
7276 transferDbgValues(N1, OpOp);
7277 return OpOp;
7278 }
7279 }
7280 break;
7281 case ISD::TRUNCATE:
7282 assert(VT.isInteger() && N1.getValueType().isInteger() &&
7283 "Invalid TRUNCATE!");
7284 assert(VT.isVector() == N1.getValueType().isVector() &&
7285 "TRUNCATE result type type should be vector iff the operand "
7286 "type is vector!");
7287 if (N1.getValueType() == VT) return N1; // noop truncate
7288 assert((!VT.isVector() || VT.getVectorElementCount() ==
7290 "Vector element count mismatch!");
7291 assert(N1.getValueType().bitsGT(VT) && "Invalid truncate node, src < dst!");
7292 if (OpOpcode == ISD::TRUNCATE)
7293 return getNode(ISD::TRUNCATE, DL, VT, N1.getOperand(0));
7294 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
7295 OpOpcode == ISD::ANY_EXTEND) {
7296 // If the source is smaller than the dest, we still need an extend.
7298 VT.getScalarType())) {
7299 SDNodeFlags Flags;
7300 if (OpOpcode == ISD::ZERO_EXTEND)
7301 Flags.setNonNeg(N1->getFlags().hasNonNeg());
7302 return getNode(OpOpcode, DL, VT, N1.getOperand(0), Flags);
7303 }
7304 if (N1.getOperand(0).getValueType().bitsGT(VT))
7305 return getNode(ISD::TRUNCATE, DL, VT, N1.getOperand(0));
7306 return N1.getOperand(0);
7307 }
7308 if (N1.isUndef())
7309 return getUNDEF(VT);
7310 if (OpOpcode == ISD::VSCALE && !NewNodesMustHaveLegalTypes)
7311 return getVScale(DL, VT,
7313 break;
7317 assert(VT.isVector() && "This DAG node is restricted to vector types.");
7318 assert(N1.getValueType().bitsLE(VT) &&
7319 "The input must be the same size or smaller than the result.");
7322 "The destination vector type must have fewer lanes than the input.");
7323 break;
7324 case ISD::ABS:
7325 assert(VT.isInteger() && VT == N1.getValueType() && "Invalid ABS!");
7326 if (N1.isUndef())
7327 return getConstant(0, DL, VT);
7328 break;
7330 assert(VT.isInteger() && VT == N1.getValueType() &&
7331 "Invalid ABS_MIN_POISON!");
7332 if (N1.isUndef())
7333 return getConstant(0, DL, VT);
7334 break;
7335 case ISD::BSWAP:
7336 assert(VT.isInteger() && VT == N1.getValueType() && "Invalid BSWAP!");
7337 assert((VT.getScalarSizeInBits() % 16 == 0) &&
7338 "BSWAP types must be a multiple of 16 bits!");
7339 if (N1.isUndef())
7340 return getUNDEF(VT);
7341 // bswap(bswap(X)) -> X.
7342 if (OpOpcode == ISD::BSWAP)
7343 return N1.getOperand(0);
7344 break;
7345 case ISD::BITREVERSE:
7346 assert(VT.isInteger() && VT == N1.getValueType() && "Invalid BITREVERSE!");
7347 if (N1.isUndef())
7348 return getUNDEF(VT);
7349 break;
7350 case ISD::BITCAST:
7352 "Cannot BITCAST between types of different sizes!");
7353 if (VT == N1.getValueType()) return N1; // noop conversion.
7354 if (OpOpcode == ISD::BITCAST) // bitconv(bitconv(x)) -> bitconv(x)
7355 return getNode(ISD::BITCAST, DL, VT, N1.getOperand(0));
7356 if (N1.isUndef())
7357 return getUNDEF(VT);
7358 break;
7360 assert(VT.isVector() && !N1.getValueType().isVector() &&
7361 (VT.getVectorElementType() == N1.getValueType() ||
7363 N1.getValueType().isInteger() &&
7365 "Illegal SCALAR_TO_VECTOR node!");
7366 if (N1.isUndef())
7367 return getUNDEF(VT);
7368 // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
7369 if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
7371 N1.getConstantOperandVal(1) == 0 &&
7372 N1.getOperand(0).getValueType() == VT)
7373 return N1.getOperand(0);
7374 break;
7375 case ISD::FNEG:
7376 // Negation of an unknown bag of bits is still completely undefined.
7377 if (N1.isUndef())
7378 return getUNDEF(VT);
7379
7380 if (OpOpcode == ISD::FNEG) // --X -> X
7381 return N1.getOperand(0);
7382 break;
7383 case ISD::FABS:
7384 if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X)
7385 return getNode(ISD::FABS, DL, VT, N1.getOperand(0));
7386 break;
7387 case ISD::VSCALE:
7388 assert(VT == N1.getValueType() && "Unexpected VT!");
7389 break;
7390 case ISD::CTPOP:
7391 if (N1.getValueType().getScalarType() == MVT::i1)
7392 return N1;
7393 break;
7394 case ISD::CTLZ:
7395 case ISD::CTTZ:
7396 if (N1.getValueType().getScalarType() == MVT::i1)
7397 return getNOT(DL, N1, N1.getValueType());
7398 break;
7399 case ISD::CTLS:
7400 if (N1.getValueType().getScalarType() == MVT::i1)
7401 return getConstant(0, DL, VT);
7402 break;
7403 case ISD::VECREDUCE_ADD:
7404 if (N1.getValueType().getScalarType() == MVT::i1)
7405 return getNode(ISD::VECREDUCE_XOR, DL, VT, N1);
7406 break;
7409 if (N1.getValueType().getScalarType() == MVT::i1)
7410 return getNode(ISD::VECREDUCE_OR, DL, VT, N1);
7411 break;
7414 if (N1.getValueType().getScalarType() == MVT::i1)
7415 return getNode(ISD::VECREDUCE_AND, DL, VT, N1);
7416 break;
7417 case ISD::SPLAT_VECTOR:
7418 assert(VT.isVector() && "Wrong return type!");
7419 // FIXME: Hexagon uses i32 scalar for a floating point zero vector so allow
7420 // that for now.
7422 (VT.isFloatingPoint() && N1.getValueType() == MVT::i32) ||
7424 N1.getValueType().isInteger() &&
7426 "Wrong operand type!");
7427 break;
7428 }
7429
7430 SDNode *N;
7431 SDVTList VTs = getVTList(VT);
7432 SDValue Ops[] = {N1};
7433 if (VT != MVT::Glue) { // Don't CSE glue producing nodes
7435 AddNodeIDNode(ID, Opcode, VTs, Ops);
7436 void *IP = nullptr;
7437 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
7438 E->intersectFlagsWith(Flags);
7439 return SDValue(E, 0);
7440 }
7441
7442 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
7443 N->setFlags(Flags);
7444 createOperands(N, Ops);
7445 CSEMap.InsertNode(N, IP);
7446 } else {
7447 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
7448 createOperands(N, Ops);
7449 }
7450
7451 InsertNode(N);
7452 SDValue V = SDValue(N, 0);
7453 NewSDValueDbgMsg(V, "Creating new node: ", this);
7454 return V;
7455}
7456
7457static APInt getIntegerIdentity(unsigned Opcode, unsigned BitWidth) {
7458 switch (Opcode) {
7459 default:
7460 llvm_unreachable("Unexpected integer identity opcode");
7461 case ISD::ADD:
7462 case ISD::OR:
7463 case ISD::XOR:
7464 case ISD::UMAX:
7465 return APInt::getZero(BitWidth);
7466 case ISD::MUL:
7467 return APInt(BitWidth, 1);
7468 case ISD::AND:
7469 case ISD::UMIN:
7471 case ISD::SMAX:
7473 case ISD::SMIN:
7475 }
7476}
7477
7478static std::optional<APInt> FoldValue(unsigned Opcode, const APInt &C1,
7479 const APInt &C2) {
7480 switch (Opcode) {
7481 case ISD::ADD: return C1 + C2;
7482 case ISD::SUB: return C1 - C2;
7483 case ISD::MUL: return C1 * C2;
7484 case ISD::AND: return C1 & C2;
7485 case ISD::OR: return C1 | C2;
7486 case ISD::XOR: return C1 ^ C2;
7487 case ISD::SHL: return C1 << C2;
7488 case ISD::SRL: return C1.lshr(C2);
7489 case ISD::SRA: return C1.ashr(C2);
7490 case ISD::ROTL: return C1.rotl(C2);
7491 case ISD::ROTR: return C1.rotr(C2);
7492 case ISD::SMIN: return C1.sle(C2) ? C1 : C2;
7493 case ISD::SMAX: return C1.sge(C2) ? C1 : C2;
7494 case ISD::UMIN: return C1.ule(C2) ? C1 : C2;
7495 case ISD::UMAX: return C1.uge(C2) ? C1 : C2;
7496 case ISD::SADDSAT: return C1.sadd_sat(C2);
7497 case ISD::UADDSAT: return C1.uadd_sat(C2);
7498 case ISD::SSUBSAT: return C1.ssub_sat(C2);
7499 case ISD::USUBSAT: return C1.usub_sat(C2);
7500 case ISD::SSHLSAT: return C1.sshl_sat(C2);
7501 case ISD::USHLSAT: return C1.ushl_sat(C2);
7502 case ISD::UDIV:
7503 if (!C2.getBoolValue())
7504 break;
7505 return C1.udiv(C2);
7506 case ISD::UREM:
7507 if (!C2.getBoolValue())
7508 break;
7509 return C1.urem(C2);
7510 case ISD::SDIV:
7511 if (!C2.getBoolValue())
7512 break;
7513 return C1.sdiv(C2);
7514 case ISD::SREM:
7515 if (!C2.getBoolValue())
7516 break;
7517 return C1.srem(C2);
7518 case ISD::AVGFLOORS:
7519 return APIntOps::avgFloorS(C1, C2);
7520 case ISD::AVGFLOORU:
7521 return APIntOps::avgFloorU(C1, C2);
7522 case ISD::AVGCEILS:
7523 return APIntOps::avgCeilS(C1, C2);
7524 case ISD::AVGCEILU:
7525 return APIntOps::avgCeilU(C1, C2);
7526 case ISD::ABDS:
7527 return APIntOps::abds(C1, C2);
7528 case ISD::ABDU:
7529 return APIntOps::abdu(C1, C2);
7530 case ISD::MULHS:
7531 return APIntOps::mulhs(C1, C2);
7532 case ISD::MULHU:
7533 return APIntOps::mulhu(C1, C2);
7534 case ISD::CLMUL:
7535 return APIntOps::clmul(C1, C2);
7536 case ISD::CLMULR:
7537 return APIntOps::clmulr(C1, C2);
7538 case ISD::CLMULH:
7539 return APIntOps::clmulh(C1, C2);
7540 case ISD::PEXT:
7541 return APIntOps::pext(C1, C2);
7542 case ISD::PDEP:
7543 return APIntOps::pdep(C1, C2);
7544 }
7545 return std::nullopt;
7546}
7547// Handle constant folding with UNDEF.
7548// TODO: Handle more cases.
7549static std::optional<APInt> FoldValueWithUndef(unsigned Opcode, const APInt &C1,
7550 bool IsUndef1, const APInt &C2,
7551 bool IsUndef2) {
7552 if (!(IsUndef1 || IsUndef2))
7553 return FoldValue(Opcode, C1, C2);
7554
7555 // Fold and(x, undef) -> 0
7556 // Fold mul(x, undef) -> 0
7557 if (Opcode == ISD::AND || Opcode == ISD::MUL)
7558 return APInt::getZero(C1.getBitWidth());
7559
7560 return std::nullopt;
7561}
7562
7564 const GlobalAddressSDNode *GA,
7565 const SDNode *N2) {
7566 if (GA->getOpcode() != ISD::GlobalAddress)
7567 return SDValue();
7568 if (!TLI->isOffsetFoldingLegal(GA))
7569 return SDValue();
7570 auto *C2 = dyn_cast<ConstantSDNode>(N2);
7571 if (!C2)
7572 return SDValue();
7573 int64_t Offset = C2->getSExtValue();
7574 switch (Opcode) {
7575 case ISD::ADD:
7576 case ISD::PTRADD:
7577 break;
7578 case ISD::SUB: Offset = -uint64_t(Offset); break;
7579 default: return SDValue();
7580 }
7581 return getGlobalAddress(GA->getGlobal(), SDLoc(C2), VT,
7582 GA->getOffset() + uint64_t(Offset));
7583}
7584
7586 switch (Opcode) {
7587 case ISD::SDIV:
7588 case ISD::UDIV:
7589 case ISD::SREM:
7590 case ISD::UREM: {
7591 // If a divisor is zero/undef or any element of a divisor vector is
7592 // zero/undef, the whole op is undef.
7593 assert(Ops.size() == 2 && "Div/rem should have 2 operands");
7594 SDValue Divisor = Ops[1];
7595 if (Divisor.isUndef() || isNullConstant(Divisor))
7596 return true;
7597
7598 return ISD::isBuildVectorOfConstantSDNodes(Divisor.getNode()) &&
7599 llvm::any_of(Divisor->op_values(),
7600 [](SDValue V) { return V.isUndef() ||
7601 isNullConstant(V); });
7602 // TODO: Handle signed overflow.
7603 }
7604 // TODO: Handle oversized shifts.
7605 default:
7606 return false;
7607 }
7608}
7609
7612 SDNodeFlags Flags) {
7613 // If the opcode is a target-specific ISD node, there's nothing we can
7614 // do here and the operand rules may not line up with the below, so
7615 // bail early.
7616 // We can't create a scalar CONCAT_VECTORS so skip it. It will break
7617 // for concats involving SPLAT_VECTOR. Concats of BUILD_VECTORS are handled by
7618 // foldCONCAT_VECTORS in getNode before this is called.
7619 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::CONCAT_VECTORS)
7620 return SDValue();
7621
7622 unsigned NumOps = Ops.size();
7623 if (NumOps == 0)
7624 return SDValue();
7625
7626 if (isUndef(Opcode, Ops))
7627 return getUNDEF(VT);
7628
7629 // Handle unary special cases.
7630 if (NumOps == 1) {
7631 SDValue N1 = Ops[0];
7632
7633 // Constant fold unary operations with an integer constant operand. Even
7634 // opaque constant will be folded, because the folding of unary operations
7635 // doesn't create new constants with different values. Nevertheless, the
7636 // opaque flag is preserved during folding to prevent future folding with
7637 // other constants.
7638 if (auto *C = dyn_cast<ConstantSDNode>(N1)) {
7639 const APInt &Val = C->getAPIntValue();
7640 switch (Opcode) {
7641 case ISD::SIGN_EXTEND:
7642 return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
7643 C->isTargetOpcode(), C->isOpaque());
7644 case ISD::TRUNCATE:
7645 if (C->isOpaque())
7646 break;
7647 [[fallthrough]];
7648 case ISD::ZERO_EXTEND:
7649 return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
7650 C->isTargetOpcode(), C->isOpaque());
7651 case ISD::ANY_EXTEND:
7652 // Some targets like RISCV prefer to sign extend some types.
7653 if (TLI->isSExtCheaperThanZExt(N1.getValueType(), VT))
7654 return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
7655 C->isTargetOpcode(), C->isOpaque());
7656 return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
7657 C->isTargetOpcode(), C->isOpaque());
7658 case ISD::ABS:
7659 return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(),
7660 C->isOpaque());
7662 if (Val.isMinSignedValue())
7663 return getPOISON(VT);
7664 return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(),
7665 C->isOpaque());
7666 case ISD::BITREVERSE:
7667 return getConstant(Val.reverseBits(), DL, VT, C->isTargetOpcode(),
7668 C->isOpaque());
7669 case ISD::BSWAP:
7670 return getConstant(Val.byteSwap(), DL, VT, C->isTargetOpcode(),
7671 C->isOpaque());
7672 case ISD::CTPOP:
7673 return getConstant(Val.popcount(), DL, VT, C->isTargetOpcode(),
7674 C->isOpaque());
7675 case ISD::CTLZ:
7677 return getConstant(Val.countl_zero(), DL, VT, C->isTargetOpcode(),
7678 C->isOpaque());
7679 case ISD::CTTZ:
7681 return getConstant(Val.countr_zero(), DL, VT, C->isTargetOpcode(),
7682 C->isOpaque());
7683 case ISD::CTLS:
7684 // CTLS returns the number of extra sign bits so subtract one.
7685 return getConstant(Val.getNumSignBits() - 1, DL, VT,
7686 C->isTargetOpcode(), C->isOpaque());
7687 case ISD::UINT_TO_FP:
7688 case ISD::SINT_TO_FP: {
7690 (void)FPV.convertFromAPInt(Val, Opcode == ISD::SINT_TO_FP,
7692 return getConstantFP(FPV, DL, VT);
7693 }
7694 case ISD::FP16_TO_FP:
7695 case ISD::BF16_TO_FP: {
7696 bool Ignored;
7697 APFloat FPV(Opcode == ISD::FP16_TO_FP ? APFloat::IEEEhalf()
7698 : APFloat::BFloat(),
7699 (Val.getBitWidth() == 16) ? Val : Val.trunc(16));
7700
7701 // This can return overflow, underflow, or inexact; we don't care.
7702 // FIXME need to be more flexible about rounding mode.
7704 &Ignored);
7705 return getConstantFP(FPV, DL, VT);
7706 }
7707 case ISD::STEP_VECTOR:
7708 if (SDValue V = FoldSTEP_VECTOR(DL, VT, N1, *this))
7709 return V;
7710 break;
7711 case ISD::BITCAST:
7712 if (VT == MVT::f16 && C->getValueType(0) == MVT::i16)
7713 return getConstantFP(APFloat(APFloat::IEEEhalf(), Val), DL, VT);
7714 if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
7715 return getConstantFP(APFloat(APFloat::IEEEsingle(), Val), DL, VT);
7716 if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
7717 return getConstantFP(APFloat(APFloat::IEEEdouble(), Val), DL, VT);
7718 if (VT == MVT::f128 && C->getValueType(0) == MVT::i128)
7719 return getConstantFP(APFloat(APFloat::IEEEquad(), Val), DL, VT);
7720 break;
7721 }
7722 }
7723
7724 // Constant fold unary operations with a floating point constant operand.
7725 if (auto *C = dyn_cast<ConstantFPSDNode>(N1)) {
7726 APFloat V = C->getValueAPF(); // make copy
7727 switch (Opcode) {
7728 case ISD::FNEG:
7729 V.changeSign();
7730 return getConstantFP(V, DL, VT);
7731 case ISD::FABS:
7732 V.clearSign();
7733 return getConstantFP(V, DL, VT);
7734 case ISD::FCEIL: {
7735 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardPositive);
7737 return getConstantFP(V, DL, VT);
7738 return SDValue();
7739 }
7740 case ISD::FTRUNC: {
7741 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardZero);
7743 return getConstantFP(V, DL, VT);
7744 return SDValue();
7745 }
7746 case ISD::FFLOOR: {
7747 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardNegative);
7749 return getConstantFP(V, DL, VT);
7750 return SDValue();
7751 }
7752 case ISD::FP_EXTEND: {
7753 bool ignored;
7754 // This can return overflow, underflow, or inexact; we don't care.
7755 // FIXME need to be more flexible about rounding mode.
7756 (void)V.convert(VT.getFltSemantics(), APFloat::rmNearestTiesToEven,
7757 &ignored);
7758 return getConstantFP(V, DL, VT);
7759 }
7760 case ISD::FP_TO_SINT:
7761 case ISD::FP_TO_UINT: {
7762 bool ignored;
7763 APSInt IntVal(VT.getSizeInBits(), Opcode == ISD::FP_TO_UINT);
7764 // FIXME need to be more flexible about rounding mode.
7766 V.convertToInteger(IntVal, APFloat::rmTowardZero, &ignored);
7767 if (s == APFloat::opInvalidOp) // inexact is OK, in fact usual
7768 break;
7769 return getConstant(IntVal, DL, VT);
7770 }
7771 case ISD::FP_TO_FP16:
7772 case ISD::FP_TO_BF16: {
7773 bool Ignored;
7774 // This can return overflow, underflow, or inexact; we don't care.
7775 // FIXME need to be more flexible about rounding mode.
7776 (void)V.convert(Opcode == ISD::FP_TO_FP16 ? APFloat::IEEEhalf()
7777 : APFloat::BFloat(),
7779 return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
7780 }
7781 case ISD::BITCAST:
7782 if (VT == MVT::i16 && C->getValueType(0) == MVT::f16)
7783 return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL,
7784 VT);
7785 if (VT == MVT::i16 && C->getValueType(0) == MVT::bf16)
7786 return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL,
7787 VT);
7788 if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
7789 return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), DL,
7790 VT);
7791 if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
7792 return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
7793 break;
7794 }
7795 }
7796
7797 // Early-out if we failed to constant fold a bitcast.
7798 if (Opcode == ISD::BITCAST)
7799 return SDValue();
7800
7801 // Constant fold integer vector reductions with constant BUILD_VECTORs.
7802 if ((Opcode == ISD::VECREDUCE_ADD || Opcode == ISD::VECREDUCE_SMAX ||
7803 Opcode == ISD::VECREDUCE_SMIN || Opcode == ISD::VECREDUCE_UMAX ||
7804 Opcode == ISD::VECREDUCE_UMIN || Opcode == ISD::VECREDUCE_MUL ||
7805 Opcode == ISD::VECREDUCE_OR || Opcode == ISD::VECREDUCE_XOR ||
7806 Opcode == ISD::VECREDUCE_AND) &&
7808 unsigned EltBits = N1.getValueType().getScalarSizeInBits();
7809 unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Opcode);
7810 APInt Acc = getIntegerIdentity(BaseOpcode, EltBits);
7811 for (SDValue Elt : N1->op_values()) {
7812 if (Elt.getOpcode() == ISD::POISON)
7813 return getPOISON(VT);
7814 if (Elt.isUndef() || cast<ConstantSDNode>(Elt)->isOpaque())
7815 return SDValue();
7816 APInt Value = cast<ConstantSDNode>(Elt)->getAPIntValue().trunc(EltBits);
7817 std::optional<APInt> Folded = FoldValue(BaseOpcode, Acc, Value);
7818 assert(Folded &&
7819 "Expected vector reduction base opcode to be foldable");
7820 Acc = *Folded;
7821 }
7822 EVT EltVT = N1.getValueType().getScalarType();
7823 return getAnyExtOrTrunc(getConstant(Acc, DL, EltVT), DL, VT);
7824 }
7825 }
7826
7827 // Handle binops special cases.
7828 if (NumOps == 2) {
7829 if (SDValue CFP = foldConstantFPMath(Opcode, DL, VT, Ops))
7830 return CFP;
7831
7832 if (auto *C1 = dyn_cast<ConstantSDNode>(Ops[0])) {
7833 if (auto *C2 = dyn_cast<ConstantSDNode>(Ops[1])) {
7834 if (C1->isOpaque() || C2->isOpaque())
7835 return SDValue();
7836
7837 std::optional<APInt> FoldAttempt =
7838 FoldValue(Opcode, C1->getAPIntValue(), C2->getAPIntValue());
7839 if (!FoldAttempt)
7840 return SDValue();
7841
7842 SDValue Folded = getConstant(*FoldAttempt, DL, VT);
7843 assert((!Folded || !VT.isVector()) &&
7844 "Can't fold vectors ops with scalar operands");
7845 return Folded;
7846 }
7847 }
7848
7849 // fold (add Sym, c) -> Sym+c
7851 return FoldSymbolOffset(Opcode, VT, GA, Ops[1].getNode());
7852 if (TLI->isCommutativeBinOp(Opcode))
7854 return FoldSymbolOffset(Opcode, VT, GA, Ops[0].getNode());
7855
7856 // fold (sext_in_reg c1) -> c2
7857 if (Opcode == ISD::SIGN_EXTEND_INREG) {
7858 EVT EVT = cast<VTSDNode>(Ops[1])->getVT();
7859
7860 auto SignExtendInReg = [&](APInt Val, llvm::EVT ConstantVT) {
7861 unsigned FromBits = EVT.getScalarSizeInBits();
7862 Val <<= Val.getBitWidth() - FromBits;
7863 Val.ashrInPlace(Val.getBitWidth() - FromBits);
7864 return getConstant(Val, DL, ConstantVT);
7865 };
7866
7867 if (auto *C1 = dyn_cast<ConstantSDNode>(Ops[0])) {
7868 const APInt &Val = C1->getAPIntValue();
7869 return SignExtendInReg(Val, VT);
7870 }
7871
7873 SmallVector<SDValue, 8> ScalarOps;
7874 llvm::EVT OpVT = Ops[0].getOperand(0).getValueType();
7875 for (int I = 0, E = VT.getVectorNumElements(); I != E; ++I) {
7876 SDValue Op = Ops[0].getOperand(I);
7877 if (Op.isUndef()) {
7878 ScalarOps.push_back(getUNDEF(OpVT));
7879 continue;
7880 }
7881 const APInt &Val = cast<ConstantSDNode>(Op)->getAPIntValue();
7882 ScalarOps.push_back(SignExtendInReg(Val, OpVT));
7883 }
7884 return getBuildVector(VT, DL, ScalarOps);
7885 }
7886
7887 if (Ops[0].getOpcode() == ISD::SPLAT_VECTOR &&
7888 isa<ConstantSDNode>(Ops[0].getOperand(0)))
7889 return getNode(ISD::SPLAT_VECTOR, DL, VT,
7890 SignExtendInReg(Ops[0].getConstantOperandAPInt(0),
7891 Ops[0].getOperand(0).getValueType()));
7892 }
7893 }
7894
7895 // Handle fshl/fshr special cases.
7896 if (Opcode == ISD::FSHL || Opcode == ISD::FSHR) {
7897 auto *C1 = dyn_cast<ConstantSDNode>(Ops[0]);
7898 auto *C2 = dyn_cast<ConstantSDNode>(Ops[1]);
7899 auto *C3 = dyn_cast<ConstantSDNode>(Ops[2]);
7900
7901 if (C1 && C2 && C3) {
7902 if (C1->isOpaque() || C2->isOpaque() || C3->isOpaque())
7903 return SDValue();
7904 const APInt &V1 = C1->getAPIntValue(), &V2 = C2->getAPIntValue(),
7905 &V3 = C3->getAPIntValue();
7906
7907 APInt FoldedVal = Opcode == ISD::FSHL ? APIntOps::fshl(V1, V2, V3)
7908 : APIntOps::fshr(V1, V2, V3);
7909 return getConstant(FoldedVal, DL, VT);
7910 }
7911 }
7912
7913 // Handle fma/fmad special cases.
7914 if (Opcode == ISD::FMA || Opcode == ISD::FMAD || Opcode == ISD::FMULADD) {
7915 assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
7916 assert(Ops[0].getValueType() == VT && Ops[1].getValueType() == VT &&
7917 Ops[2].getValueType() == VT && "FMA types must match!");
7921 if (C1 && C2 && C3) {
7922 APFloat V1 = C1->getValueAPF();
7923 const APFloat &V2 = C2->getValueAPF();
7924 const APFloat &V3 = C3->getValueAPF();
7925 if (Opcode == ISD::FMAD || Opcode == ISD::FMULADD) {
7926 V1.multiply(V2, APFloat::rmNearestTiesToEven);
7928 } else
7929 V1.fusedMultiplyAdd(V2, V3, APFloat::rmNearestTiesToEven);
7930 return getConstantFP(V1, DL, VT);
7931 }
7932 }
7933
7934 // This is for vector folding only from here on.
7935 if (!VT.isVector())
7936 return SDValue();
7937
7938 // Constant fold integer partial reductions with constant BUILD_VECTOR
7939 // operands. The reduction order is deliberately unspecified. Use the same
7940 // subvector layout as TargetLowering::expandPartialReduceMLA(), where input
7941 // lane I contributes to accumulator lane I % NumAccElts.
7942 if (Opcode == ISD::PARTIAL_REDUCE_SMLA ||
7943 Opcode == ISD::PARTIAL_REDUCE_UMLA ||
7944 Opcode == ISD::PARTIAL_REDUCE_SUMLA) {
7945 // These nodes have no scalar form, so unsupported cases must not fall
7946 // through to generic per-lane vector folding.
7947 if (!llvm::all_of(Ops, [](SDValue Op) {
7948 return ISD::isBuildVectorOfConstantSDNodes(Op.getNode());
7949 }))
7950 return SDValue();
7951
7952 unsigned AccEltBits = VT.getScalarSizeInBits();
7953 unsigned InputEltBits = Ops[1].getScalarValueSizeInBits();
7954 unsigned NumAccElts = VT.getVectorNumElements();
7955 unsigned NumInputElts = Ops[1].getValueType().getVectorNumElements();
7956 SmallVector<APInt, 8> Results(NumAccElts, APInt::getZero(AccEltBits));
7957 BitVector PoisonElts(NumAccElts);
7958
7959 for (unsigned I = 0; I != NumAccElts; ++I) {
7960 SDValue Elt = Ops[0].getOperand(I);
7961 if (Elt.getOpcode() == ISD::POISON) {
7962 PoisonElts.set(I);
7963 continue;
7964 }
7965 auto *C = dyn_cast<ConstantSDNode>(Elt);
7966 if (!C || C->isOpaque())
7967 return SDValue();
7968 Results[I] = C->getAPIntValue().trunc(AccEltBits);
7969 }
7970
7971 bool IsLHSSigned = Opcode != ISD::PARTIAL_REDUCE_UMLA;
7972 bool IsRHSSigned = Opcode == ISD::PARTIAL_REDUCE_SMLA;
7973 for (unsigned I = 0; I != NumInputElts; ++I) {
7974 const unsigned AccIdx = I % NumAccElts;
7975 SDValue LHSElt = Ops[1].getOperand(I);
7976 SDValue RHSElt = Ops[2].getOperand(I);
7977 if (LHSElt.getOpcode() == ISD::POISON ||
7978 RHSElt.getOpcode() == ISD::POISON) {
7979 PoisonElts.set(AccIdx);
7980 continue;
7981 }
7982
7983 auto *LHS = dyn_cast<ConstantSDNode>(LHSElt);
7984 auto *RHS = dyn_cast<ConstantSDNode>(RHSElt);
7985 if (!LHS || !RHS || LHS->isOpaque() || RHS->isOpaque())
7986 return SDValue();
7987
7988 APInt LHSVal = LHS->getAPIntValue().trunc(InputEltBits);
7989 APInt RHSVal = RHS->getAPIntValue().trunc(InputEltBits);
7990 LHSVal = IsLHSSigned ? LHSVal.sext(AccEltBits) : LHSVal.zext(AccEltBits);
7991 RHSVal = IsRHSSigned ? RHSVal.sext(AccEltBits) : RHSVal.zext(AccEltBits);
7992 Results[AccIdx] += LHSVal * RHSVal;
7993 }
7994
7995 // After type legalization the vector element type may not be a legal
7996 // scalar type (e.g. i16 on AArch64). Create the folded constants in the
7997 // promoted legal scalar type instead, matching the generic per-lane path
7998 // below. Bail out if legalization would narrow the type, since the lane
7999 // value would not fit.
8000 EVT AccEltVT = VT.getVectorElementType();
8001 EVT LegalSVT = AccEltVT;
8002 if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
8003 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
8004 if (LegalSVT.bitsLT(AccEltVT))
8005 return SDValue();
8006 }
8007
8008 SmallVector<SDValue, 8> ResultOps;
8009 for (unsigned I = 0; I != NumAccElts; ++I)
8010 ResultOps.push_back(
8011 PoisonElts[I] ? getPOISON(LegalSVT)
8012 : getConstant(Results[I].sext(LegalSVT.getSizeInBits()),
8013 DL, LegalSVT));
8014 return getBuildVector(VT, DL, ResultOps);
8015 }
8016
8017 ElementCount NumElts = VT.getVectorElementCount();
8018
8019 // See if we can fold through any bitcasted integer ops.
8020 if (NumOps == 2 && VT.isFixedLengthVector() && VT.isInteger() &&
8021 Ops[0].getValueType() == VT && Ops[1].getValueType() == VT &&
8022 (Ops[0].getOpcode() == ISD::BITCAST ||
8023 Ops[1].getOpcode() == ISD::BITCAST)) {
8026 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
8027 auto *BV2 = dyn_cast<BuildVectorSDNode>(N2);
8028 if (BV1 && BV2 && N1.getValueType().isInteger() &&
8029 N2.getValueType().isInteger()) {
8030 bool IsLE = getDataLayout().isLittleEndian();
8031 unsigned EltBits = VT.getScalarSizeInBits();
8032 SmallVector<APInt> RawBits1, RawBits2;
8033 BitVector UndefElts1, UndefElts2;
8034 if (BV1->getConstantRawBits(IsLE, EltBits, RawBits1, UndefElts1) &&
8035 BV2->getConstantRawBits(IsLE, EltBits, RawBits2, UndefElts2)) {
8036 SmallVector<APInt> RawBits;
8037 for (unsigned I = 0, E = NumElts.getFixedValue(); I != E; ++I) {
8038 std::optional<APInt> Fold = FoldValueWithUndef(
8039 Opcode, RawBits1[I], UndefElts1[I], RawBits2[I], UndefElts2[I]);
8040 if (!Fold)
8041 break;
8042 RawBits.push_back(*Fold);
8043 }
8044 if (RawBits.size() == NumElts.getFixedValue()) {
8045 // We have constant folded, but we might need to cast this again back
8046 // to the original (possibly legalized) type.
8047 EVT BVVT, BVEltVT;
8048 if (N1.getValueType() == VT) {
8049 BVVT = N1.getValueType();
8050 BVEltVT = BV1->getOperand(0).getValueType();
8051 } else {
8052 BVVT = N2.getValueType();
8053 BVEltVT = BV2->getOperand(0).getValueType();
8054 }
8055 unsigned BVEltBits = BVEltVT.getSizeInBits();
8056 SmallVector<APInt> DstBits;
8057 BitVector DstUndefs;
8059 DstBits, RawBits, DstUndefs,
8060 BitVector(RawBits.size(), false));
8061 SmallVector<SDValue> Ops(DstBits.size(), getUNDEF(BVEltVT));
8062 for (unsigned I = 0, E = DstBits.size(); I != E; ++I) {
8063 if (DstUndefs[I])
8064 continue;
8065 Ops[I] = getConstant(DstBits[I].sext(BVEltBits), DL, BVEltVT);
8066 }
8067 return getBitcast(VT, getBuildVector(BVVT, DL, Ops));
8068 }
8069 }
8070 }
8071 // Logic ops can be folded from raw integer bits - mainly for AVX512 masks.
8072 if (ISD::isBitwiseLogicOp(Opcode) && isa<ConstantSDNode>(N1) &&
8073 isa<ConstantSDNode>(N2)) {
8074 if (SDValue Res = FoldConstantArithmetic(Opcode, DL, N1.getValueType(),
8075 {N1, N2}, Flags))
8076 return getBitcast(VT, Res);
8077 }
8078 }
8079
8080 // Fold (mul step_vector(C0), C1) to (step_vector(C0 * C1)).
8081 // (shl step_vector(C0), C1) -> (step_vector(C0 << C1))
8082 if ((Opcode == ISD::MUL || Opcode == ISD::SHL) &&
8083 Ops[0].getOpcode() == ISD::STEP_VECTOR) {
8084 APInt RHSVal;
8085 if (ISD::isConstantSplatVector(Ops[1].getNode(), RHSVal)) {
8086 APInt NewStep = Opcode == ISD::MUL
8087 ? Ops[0].getConstantOperandAPInt(0) * RHSVal
8088 : Ops[0].getConstantOperandAPInt(0) << RHSVal;
8089 return getStepVector(DL, VT, NewStep);
8090 }
8091 }
8092
8093 auto IsScalarOrSameVectorSize = [NumElts](const SDValue &Op) {
8094 return !Op.getValueType().isVector() ||
8095 Op.getValueType().getVectorElementCount() == NumElts;
8096 };
8097
8098 auto IsBuildVectorSplatVectorOrUndef = [](const SDValue &Op) {
8099 return Op.isUndef() || Op.getOpcode() == ISD::CONDCODE ||
8100 Op.getOpcode() == ISD::BUILD_VECTOR ||
8101 Op.getOpcode() == ISD::SPLAT_VECTOR;
8102 };
8103
8104 // All operands must be vector types with the same number of elements as
8105 // the result type and must be either UNDEF or a build/splat vector
8106 // or UNDEF scalars.
8107 if (!llvm::all_of(Ops, IsBuildVectorSplatVectorOrUndef) ||
8108 !llvm::all_of(Ops, IsScalarOrSameVectorSize))
8109 return SDValue();
8110
8111 // If we are comparing vectors, then the result needs to be a i1 boolean that
8112 // is then extended back to the legal result type depending on how booleans
8113 // are represented.
8114 EVT SVT = (Opcode == ISD::SETCC ? MVT::i1 : VT.getScalarType());
8115 ISD::NodeType ExtendCode =
8116 (Opcode == ISD::SETCC && SVT != VT.getScalarType())
8117 ? TargetLowering::getExtendForContent(TLI->getBooleanContents(VT))
8119
8120 // Find legal integer scalar type for constant promotion and
8121 // ensure that its scalar size is at least as large as source.
8122 EVT LegalSVT = VT.getScalarType();
8123 if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
8124 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
8125 if (LegalSVT.bitsLT(VT.getScalarType()))
8126 return SDValue();
8127 }
8128
8129 // For scalable vector types we know we're dealing with SPLAT_VECTORs. We
8130 // only have one operand to check. For fixed-length vector types we may have
8131 // a combination of BUILD_VECTOR and SPLAT_VECTOR.
8132 unsigned NumVectorElts = NumElts.isScalable() ? 1 : NumElts.getFixedValue();
8133
8134 // Constant fold each scalar lane separately.
8135 SmallVector<SDValue, 4> ScalarResults;
8136 for (unsigned I = 0; I != NumVectorElts; I++) {
8137 SmallVector<SDValue, 4> ScalarOps;
8138 for (SDValue Op : Ops) {
8139 EVT InSVT = Op.getValueType().getScalarType();
8140 if (Op.getOpcode() != ISD::BUILD_VECTOR &&
8141 Op.getOpcode() != ISD::SPLAT_VECTOR) {
8142 if (Op.isUndef())
8143 ScalarOps.push_back(getUNDEF(InSVT));
8144 else
8145 ScalarOps.push_back(Op);
8146 continue;
8147 }
8148
8149 SDValue ScalarOp =
8150 Op.getOperand(Op.getOpcode() == ISD::SPLAT_VECTOR ? 0 : I);
8151 EVT ScalarVT = ScalarOp.getValueType();
8152
8153 // Build vector (integer) scalar operands may need implicit
8154 // truncation - do this before constant folding.
8155 if (ScalarVT.isInteger() && ScalarVT.bitsGT(InSVT)) {
8156 // Don't create illegally-typed nodes unless they're constants or undef
8157 // - if we fail to constant fold we can't guarantee the (dead) nodes
8158 // we're creating will be cleaned up before being visited for
8159 // legalization.
8160 if (NewNodesMustHaveLegalTypes && !ScalarOp.isUndef() &&
8161 !isa<ConstantSDNode>(ScalarOp) &&
8162 TLI->getTypeAction(*getContext(), InSVT) !=
8164 return SDValue();
8165 ScalarOp = getNode(ISD::TRUNCATE, DL, InSVT, ScalarOp);
8166 }
8167
8168 ScalarOps.push_back(ScalarOp);
8169 }
8170
8171 // Constant fold the scalar operands.
8172 SDValue ScalarResult = getNode(Opcode, DL, SVT, ScalarOps, Flags);
8173
8174 // Scalar folding only succeeded if the result is a constant or UNDEF.
8175 if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant &&
8176 ScalarResult.getOpcode() != ISD::ConstantFP)
8177 return SDValue();
8178
8179 // Legalize the (integer) scalar constant if necessary. We only do
8180 // this once we know the folding succeeded, since otherwise we would
8181 // get a node with illegal type which has a user.
8182 if (LegalSVT != SVT)
8183 ScalarResult = getNode(ExtendCode, DL, LegalSVT, ScalarResult);
8184
8185 ScalarResults.push_back(ScalarResult);
8186 }
8187
8188 SDValue V = NumElts.isScalable() ? getSplatVector(VT, DL, ScalarResults[0])
8189 : getBuildVector(VT, DL, ScalarResults);
8190 NewSDValueDbgMsg(V, "New node fold constant vector: ", this);
8191 return V;
8192}
8193
8196 // TODO: Add support for unary/ternary fp opcodes.
8197 if (Ops.size() != 2)
8198 return SDValue();
8199
8200 // TODO: We don't do any constant folding for strict FP opcodes here, but we
8201 // should. That will require dealing with a potentially non-default
8202 // rounding mode, checking the "opStatus" return value from the APFloat
8203 // math calculations, and possibly other variations.
8204 SDValue N1 = Ops[0];
8205 SDValue N2 = Ops[1];
8206 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1, /*AllowUndefs*/ false);
8207 ConstantFPSDNode *N2CFP = isConstOrConstSplatFP(N2, /*AllowUndefs*/ false);
8208 if (N1CFP && N2CFP) {
8209 APFloat C1 = N1CFP->getValueAPF(); // make copy
8210 const APFloat &C2 = N2CFP->getValueAPF();
8211 switch (Opcode) {
8212 case ISD::FADD:
8214 return getConstantFP(C1, DL, VT);
8215 case ISD::FSUB:
8217 return getConstantFP(C1, DL, VT);
8218 case ISD::FMUL:
8220 return getConstantFP(C1, DL, VT);
8221 case ISD::FDIV:
8223 return getConstantFP(C1, DL, VT);
8224 case ISD::FREM:
8225 C1.mod(C2);
8226 return getConstantFP(C1, DL, VT);
8227 case ISD::FCOPYSIGN:
8228 C1.copySign(C2);
8229 return getConstantFP(C1, DL, VT);
8230 case ISD::FMINNUM:
8231 return getConstantFP(minnum(C1, C2), DL, VT);
8232 case ISD::FMAXNUM:
8233 return getConstantFP(maxnum(C1, C2), DL, VT);
8234 case ISD::FMINIMUM:
8235 return getConstantFP(minimum(C1, C2), DL, VT);
8236 case ISD::FMAXIMUM:
8237 return getConstantFP(maximum(C1, C2), DL, VT);
8238 case ISD::FMINIMUMNUM:
8239 return getConstantFP(minimumnum(C1, C2), DL, VT);
8240 case ISD::FMAXIMUMNUM:
8241 return getConstantFP(maximumnum(C1, C2), DL, VT);
8242 default: break;
8243 }
8244 }
8245 if (N1CFP && Opcode == ISD::FP_ROUND) {
8246 APFloat C1 = N1CFP->getValueAPF(); // make copy
8247 bool Unused;
8248 // This can return overflow, underflow, or inexact; we don't care.
8249 // FIXME need to be more flexible about rounding mode.
8251 &Unused);
8252 return getConstantFP(C1, DL, VT);
8253 }
8254
8255 switch (Opcode) {
8256 case ISD::FSUB:
8257 // -0.0 - undef --> undef (consistent with "fneg undef")
8258 if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1, /*AllowUndefs*/ true))
8259 if (N1C && N1C->getValueAPF().isNegZero() && N2.isUndef())
8260 return getUNDEF(VT);
8261 [[fallthrough]];
8262
8263 case ISD::FADD:
8264 case ISD::FMUL:
8265 case ISD::FDIV:
8266 case ISD::FREM:
8267 // If both operands are undef, the result is undef. If 1 operand is undef,
8268 // the result is NaN. This should match the behavior of the IR optimizer.
8269 if (N1.isUndef() && N2.isUndef())
8270 return getUNDEF(VT);
8271 if (N1.isUndef() || N2.isUndef())
8273 }
8274 return SDValue();
8275}
8276
8278 const SDLoc &DL, EVT DstEltVT) {
8279 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
8280
8281 // If this is already the right type, we're done.
8282 if (SrcEltVT == DstEltVT)
8283 return SDValue(BV, 0);
8284
8285 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
8286 unsigned DstBitSize = DstEltVT.getSizeInBits();
8287
8288 // If this is a conversion of N elements of one type to N elements of another
8289 // type, convert each element. This handles FP<->INT cases.
8290 if (SrcBitSize == DstBitSize) {
8292 for (SDValue Op : BV->op_values()) {
8293 // If the vector element type is not legal, the BUILD_VECTOR operands
8294 // are promoted and implicitly truncated. Make that explicit here.
8295 if (Op.getValueType() != SrcEltVT)
8296 Op = getNode(ISD::TRUNCATE, DL, SrcEltVT, Op);
8297 Ops.push_back(getBitcast(DstEltVT, Op));
8298 }
8299 EVT VT = EVT::getVectorVT(*getContext(), DstEltVT,
8301 return getBuildVector(VT, DL, Ops);
8302 }
8303
8304 // Otherwise, we're growing or shrinking the elements. To avoid having to
8305 // handle annoying details of growing/shrinking FP values, we convert them to
8306 // int first.
8307 if (SrcEltVT.isFloatingPoint()) {
8308 // Convert the input float vector to a int vector where the elements are the
8309 // same sizes.
8310 EVT IntEltVT = EVT::getIntegerVT(*getContext(), SrcEltVT.getSizeInBits());
8311 if (SDValue Tmp = FoldConstantBuildVector(BV,