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 "vscale-unroll-limit",
120 cl::desc("Maximum vscale for which vector unrolling is allowed."),
121 cl::Hidden, cl::init(64));
122
124 LLVM_DEBUG(dbgs() << Msg; V.getNode()->dump(G););
125}
126
128
129//===----------------------------------------------------------------------===//
130// ConstantFPSDNode Class
131//===----------------------------------------------------------------------===//
132
133/// isExactlyValue - We don't rely on operator== working on double values, as
134/// it returns true for things that are clearly not equal, like -0.0 and 0.0.
135/// As such, this method can be used to do an exact bit-for-bit comparison of
136/// two floating point values.
138 return getValueAPF().bitwiseIsEqual(V);
139}
140
142 const APFloat& Val) {
143 assert(VT.isFloatingPoint() && "Can only convert between FP types");
144
145 // convert modifies in place, so make a copy.
146 APFloat Val2 = APFloat(Val);
147 bool losesInfo;
149 &losesInfo);
150 return !losesInfo;
151}
152
153//===----------------------------------------------------------------------===//
154// ISD Namespace
155//===----------------------------------------------------------------------===//
156
157bool ISD::isConstantSplatVector(const SDNode *N, APInt &SplatVal) {
158 if (N->getOpcode() == ISD::SPLAT_VECTOR) {
159 if (auto OptAPInt = N->getOperand(0)->bitcastToAPInt()) {
160 unsigned EltSize =
161 N->getValueType(0).getVectorElementType().getSizeInBits();
162 SplatVal = OptAPInt->trunc(EltSize);
163 return true;
164 }
165 }
166
167 auto *BV = dyn_cast<BuildVectorSDNode>(N);
168 if (!BV)
169 return false;
170
171 APInt SplatUndef;
172 unsigned SplatBitSize;
173 bool HasUndefs;
174 unsigned EltSize = N->getValueType(0).getVectorElementType().getSizeInBits();
175 // Endianness does not matter here. We are checking for a splat given the
176 // element size of the vector, and if we find such a splat for little endian
177 // layout, then that should be valid also for big endian (as the full vector
178 // size is known to be a multiple of the element size).
179 const bool IsBigEndian = false;
180 return BV->isConstantSplat(SplatVal, SplatUndef, SplatBitSize, HasUndefs,
181 EltSize, IsBigEndian) &&
182 EltSize == SplatBitSize;
183}
184
185// FIXME: AllOnes and AllZeros duplicate a lot of code. Could these be
186// specializations of the more general isConstantSplatVector()?
187
188bool ISD::isConstantSplatVectorAllOnes(const SDNode *N, bool BuildVectorOnly) {
189 // Look through a bit convert.
190 while (N->getOpcode() == ISD::BITCAST)
191 N = N->getOperand(0).getNode();
192
193 if (!BuildVectorOnly && N->getOpcode() == ISD::SPLAT_VECTOR) {
194 APInt SplatVal;
195 return isConstantSplatVector(N, SplatVal) && SplatVal.isAllOnes();
196 }
197
198 if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
199
200 unsigned i = 0, e = N->getNumOperands();
201
202 // Skip over all of the undef values.
203 while (i != e && N->getOperand(i).isUndef())
204 ++i;
205
206 // Do not accept an all-undef vector.
207 if (i == e) return false;
208
209 // Do not accept build_vectors that aren't all constants or which have non-~0
210 // elements. We have to be a bit careful here, as the type of the constant
211 // may not be the same as the type of the vector elements due to type
212 // legalization (the elements are promoted to a legal type for the target and
213 // a vector of a type may be legal when the base element type is not).
214 // We only want to check enough bits to cover the vector elements, because
215 // we care if the resultant vector is all ones, not whether the individual
216 // constants are.
217 SDValue NotZero = N->getOperand(i);
218 if (auto OptAPInt = NotZero->bitcastToAPInt()) {
219 unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
220 if (OptAPInt->countr_one() < EltSize)
221 return false;
222 } else
223 return false;
224
225 // Okay, we have at least one ~0 value, check to see if the rest match or are
226 // undefs. Even with the above element type twiddling, this should be OK, as
227 // the same type legalization should have applied to all the elements.
228 for (++i; i != e; ++i)
229 if (N->getOperand(i) != NotZero && !N->getOperand(i).isUndef())
230 return false;
231 return true;
232}
233
234bool ISD::isConstantSplatVectorAllZeros(const SDNode *N, bool BuildVectorOnly) {
235 // Look through a bit convert.
236 while (N->getOpcode() == ISD::BITCAST)
237 N = N->getOperand(0).getNode();
238
239 if (!BuildVectorOnly && N->getOpcode() == ISD::SPLAT_VECTOR) {
240 APInt SplatVal;
241 return isConstantSplatVector(N, SplatVal) && SplatVal.isZero();
242 }
243
244 if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
245
246 bool IsAllUndef = true;
247 for (const SDValue &Op : N->op_values()) {
248 if (Op.isUndef())
249 continue;
250 IsAllUndef = false;
251 // Do not accept build_vectors that aren't all constants or which have non-0
252 // elements. We have to be a bit careful here, as the type of the constant
253 // may not be the same as the type of the vector elements due to type
254 // legalization (the elements are promoted to a legal type for the target
255 // and a vector of a type may be legal when the base element type is not).
256 // We only want to check enough bits to cover the vector elements, because
257 // we care if the resultant vector is all zeros, not whether the individual
258 // constants are.
259 if (auto OptAPInt = Op->bitcastToAPInt()) {
260 unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
261 if (OptAPInt->countr_zero() < EltSize)
262 return false;
263 } else
264 return false;
265 }
266
267 // Do not accept an all-undef vector.
268 if (IsAllUndef)
269 return false;
270 return true;
271}
272
274 return isConstantSplatVectorAllOnes(N, /*BuildVectorOnly*/ true);
275}
276
278 return isConstantSplatVectorAllZeros(N, /*BuildVectorOnly*/ true);
279}
280
282 if (N->getOpcode() != ISD::BUILD_VECTOR)
283 return false;
284
285 for (const SDValue &Op : N->op_values()) {
286 if (Op.isUndef())
287 continue;
289 return false;
290 }
291 return true;
292}
293
295 if (N->getOpcode() != ISD::BUILD_VECTOR)
296 return false;
297
298 for (const SDValue &Op : N->op_values()) {
299 if (Op.isUndef())
300 continue;
302 return false;
303 }
304 return true;
305}
306
307bool ISD::isVectorShrinkable(const SDNode *N, unsigned NewEltSize,
308 bool Signed) {
309 assert(N->getValueType(0).isVector() && "Expected a vector!");
310
311 unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
312 if (EltSize <= NewEltSize)
313 return false;
314
315 if (N->getOpcode() == ISD::ZERO_EXTEND) {
316 return (N->getOperand(0).getValueType().getScalarSizeInBits() <=
317 NewEltSize) &&
318 !Signed;
319 }
320 if (N->getOpcode() == ISD::SIGN_EXTEND) {
321 return (N->getOperand(0).getValueType().getScalarSizeInBits() <=
322 NewEltSize) &&
323 Signed;
324 }
325 if (N->getOpcode() != ISD::BUILD_VECTOR)
326 return false;
327
328 for (const SDValue &Op : N->op_values()) {
329 if (Op.isUndef())
330 continue;
332 return false;
333
334 APInt C = Op->getAsAPIntVal().trunc(EltSize);
335 if (Signed && C.trunc(NewEltSize).sext(EltSize) != C)
336 return false;
337 if (!Signed && C.trunc(NewEltSize).zext(EltSize) != C)
338 return false;
339 }
340
341 return true;
342}
343
345 // Return false if the node has no operands.
346 // This is "logically inconsistent" with the definition of "all" but
347 // is probably the desired behavior.
348 if (N->getNumOperands() == 0)
349 return false;
350 return all_of(N->op_values(), [](SDValue Op) { return Op.isUndef(); });
351}
352
354 return N->getOpcode() == ISD::FREEZE && N->getOperand(0).isUndef();
355}
356
357template <typename ConstNodeType>
359 std::function<bool(ConstNodeType *)> Match,
360 bool AllowUndefs, bool AllowTruncation) {
361 // FIXME: Add support for scalar UNDEF cases?
362 if (auto *C = dyn_cast<ConstNodeType>(Op))
363 return Match(C);
364
365 // FIXME: Add support for vector UNDEF cases?
366 if (ISD::BUILD_VECTOR != Op.getOpcode() &&
367 ISD::SPLAT_VECTOR != Op.getOpcode())
368 return false;
369
370 if (ISD::SPLAT_VECTOR == Op.getOpcode() && !DemandedElts)
371 return true;
372
373 EVT SVT = Op.getValueType().getScalarType();
374 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
375 if (ISD::SPLAT_VECTOR != Op.getOpcode() && !DemandedElts[i])
376 continue;
377
378 if (AllowUndefs && Op.getOperand(i).isUndef()) {
379 if (!Match(nullptr))
380 return false;
381 continue;
382 }
383
384 auto *Cst = dyn_cast<ConstNodeType>(Op.getOperand(i));
385 if (!Cst || (!AllowTruncation && Cst->getValueType(0) != SVT) ||
386 !Match(Cst))
387 return false;
388 }
389 return true;
390}
391// Build used template types.
393 SDValue, const APInt &, std::function<bool(ConstantSDNode *)>, bool, bool);
395 SDValue, const APInt &, std::function<bool(ConstantFPSDNode *)>, bool,
396 bool);
397
399 SDValue LHS, SDValue RHS, const APInt &DemandedElts,
400 std::function<bool(ConstantSDNode *, ConstantSDNode *)> Match,
401 bool AllowUndefs, bool AllowTypeMismatch) {
402 if (!AllowTypeMismatch && LHS.getValueType() != RHS.getValueType())
403 return false;
404
405 // TODO: Add support for scalar UNDEF cases?
406 if (auto *LHSCst = dyn_cast<ConstantSDNode>(LHS))
407 if (auto *RHSCst = dyn_cast<ConstantSDNode>(RHS))
408 return Match(LHSCst, RHSCst);
409
410 // TODO: Add support for vector UNDEF cases?
411 if (LHS.getOpcode() != RHS.getOpcode() ||
412 (LHS.getOpcode() != ISD::BUILD_VECTOR &&
413 LHS.getOpcode() != ISD::SPLAT_VECTOR))
414 return false;
415
416 if (ISD::SPLAT_VECTOR == LHS.getOpcode() && !DemandedElts)
417 return true;
418
419 EVT SVT = LHS.getValueType().getScalarType();
420 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
421 if (ISD::SPLAT_VECTOR != LHS.getOpcode() && !DemandedElts[i])
422 continue;
423 SDValue LHSOp = LHS.getOperand(i);
424 SDValue RHSOp = RHS.getOperand(i);
425 bool LHSUndef = AllowUndefs && LHSOp.isUndef();
426 bool RHSUndef = AllowUndefs && RHSOp.isUndef();
427 auto *LHSCst = dyn_cast<ConstantSDNode>(LHSOp);
428 auto *RHSCst = dyn_cast<ConstantSDNode>(RHSOp);
429 if ((!LHSCst && !LHSUndef) || (!RHSCst && !RHSUndef))
430 return false;
431 if (!AllowTypeMismatch && (LHSOp.getValueType() != SVT ||
432 LHSOp.getValueType() != RHSOp.getValueType()))
433 return false;
434 if (!Match(LHSCst, RHSCst))
435 return false;
436 }
437 return true;
438}
439
441 switch (MinMaxOpc) {
442 default:
443 llvm_unreachable("unrecognized opcode");
444 case ISD::UMIN:
445 return ISD::UMAX;
446 case ISD::UMAX:
447 return ISD::UMIN;
448 case ISD::SMIN:
449 return ISD::SMAX;
450 case ISD::SMAX:
451 return ISD::SMIN;
452 }
453}
454
456 switch (MinMaxOpc) {
457 default:
458 llvm_unreachable("unrecognized min/max opcode");
459 case ISD::SMIN:
460 return ISD::UMIN;
461 case ISD::SMAX:
462 return ISD::UMAX;
463 case ISD::UMIN:
464 return ISD::SMIN;
465 case ISD::UMAX:
466 return ISD::SMAX;
467 }
468}
469
471 switch (VecReduceOpcode) {
472 default:
473 llvm_unreachable("Expected VECREDUCE opcode");
476 case ISD::VP_REDUCE_FADD:
477 case ISD::VP_REDUCE_SEQ_FADD:
478 return ISD::FADD;
481 case ISD::VP_REDUCE_FMUL:
482 case ISD::VP_REDUCE_SEQ_FMUL:
483 return ISD::FMUL;
485 case ISD::VP_REDUCE_ADD:
486 return ISD::ADD;
488 case ISD::VP_REDUCE_MUL:
489 return ISD::MUL;
491 case ISD::VP_REDUCE_AND:
492 return ISD::AND;
494 case ISD::VP_REDUCE_OR:
495 return ISD::OR;
497 case ISD::VP_REDUCE_XOR:
498 return ISD::XOR;
500 case ISD::VP_REDUCE_SMAX:
501 return ISD::SMAX;
503 case ISD::VP_REDUCE_SMIN:
504 return ISD::SMIN;
506 case ISD::VP_REDUCE_UMAX:
507 return ISD::UMAX;
509 case ISD::VP_REDUCE_UMIN:
510 return ISD::UMIN;
512 case ISD::VP_REDUCE_FMAX:
513 return ISD::FMAXNUM;
515 case ISD::VP_REDUCE_FMIN:
516 return ISD::FMINNUM;
518 case ISD::VP_REDUCE_FMAXIMUM:
519 return ISD::FMAXIMUM;
521 case ISD::VP_REDUCE_FMINIMUM:
522 return ISD::FMINIMUM;
524 return ISD::FMAXIMUMNUM;
526 return ISD::FMINIMUMNUM;
527 }
528}
529
531 switch (MaskedOpc) {
532 case ISD::MASKED_UDIV:
533 return ISD::UDIV;
534 case ISD::MASKED_SDIV:
535 return ISD::SDIV;
536 case ISD::MASKED_UREM:
537 return ISD::UREM;
538 case ISD::MASKED_SREM:
539 return ISD::SREM;
540 default:
541 llvm_unreachable("Expected masked binop opcode");
542 }
543}
544
545bool ISD::isVPOpcode(unsigned Opcode) {
546 switch (Opcode) {
547 default:
548 return false;
549#define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) \
550 case ISD::VPSD: \
551 return true;
552#include "llvm/IR/VPIntrinsics.def"
553 }
554}
555
556bool ISD::isVPBinaryOp(unsigned Opcode) {
557 switch (Opcode) {
558 default:
559 break;
560#define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) case ISD::VPSD:
561#define VP_PROPERTY_BINARYOP return true;
562#define END_REGISTER_VP_SDNODE(VPSD) break;
563#include "llvm/IR/VPIntrinsics.def"
564 }
565 return false;
566}
567
568bool ISD::isVPReduction(unsigned Opcode) {
569 switch (Opcode) {
570 default:
571 return false;
572 case ISD::VP_REDUCE_ADD:
573 case ISD::VP_REDUCE_MUL:
574 case ISD::VP_REDUCE_AND:
575 case ISD::VP_REDUCE_OR:
576 case ISD::VP_REDUCE_XOR:
577 case ISD::VP_REDUCE_SMAX:
578 case ISD::VP_REDUCE_SMIN:
579 case ISD::VP_REDUCE_UMAX:
580 case ISD::VP_REDUCE_UMIN:
581 case ISD::VP_REDUCE_FMAX:
582 case ISD::VP_REDUCE_FMIN:
583 case ISD::VP_REDUCE_FMAXIMUM:
584 case ISD::VP_REDUCE_FMINIMUM:
585 case ISD::VP_REDUCE_FADD:
586 case ISD::VP_REDUCE_FMUL:
587 case ISD::VP_REDUCE_SEQ_FADD:
588 case ISD::VP_REDUCE_SEQ_FMUL:
589 return true;
590 }
591}
592
593/// The operand position of the vector mask.
594std::optional<unsigned> ISD::getVPMaskIdx(unsigned Opcode) {
595 switch (Opcode) {
596 default:
597 return std::nullopt;
598#define BEGIN_REGISTER_VP_SDNODE(VPSD, LEGALPOS, TDNAME, MASKPOS, ...) \
599 case ISD::VPSD: \
600 return MASKPOS;
601#include "llvm/IR/VPIntrinsics.def"
602 }
603}
604
605/// The operand position of the explicit vector length parameter.
606std::optional<unsigned> ISD::getVPExplicitVectorLengthIdx(unsigned Opcode) {
607 switch (Opcode) {
608 default:
609 return std::nullopt;
610#define BEGIN_REGISTER_VP_SDNODE(VPSD, LEGALPOS, TDNAME, MASKPOS, EVLPOS) \
611 case ISD::VPSD: \
612 return EVLPOS;
613#include "llvm/IR/VPIntrinsics.def"
614 }
615}
616
617std::optional<unsigned> ISD::getBaseOpcodeForVP(unsigned VPOpcode,
618 bool hasFPExcept) {
619 // FIXME: Return strict opcodes in case of fp exceptions.
620 switch (VPOpcode) {
621 default:
622 return std::nullopt;
623#define BEGIN_REGISTER_VP_SDNODE(VPOPC, ...) case ISD::VPOPC:
624#define VP_PROPERTY_FUNCTIONAL_SDOPC(SDOPC) return ISD::SDOPC;
625#define END_REGISTER_VP_SDNODE(VPOPC) break;
626#include "llvm/IR/VPIntrinsics.def"
627 }
628 return std::nullopt;
629}
630
631std::optional<unsigned> ISD::getVPForBaseOpcode(unsigned Opcode) {
632 switch (Opcode) {
633 default:
634 return std::nullopt;
635#define BEGIN_REGISTER_VP_SDNODE(VPOPC, ...) break;
636#define VP_PROPERTY_FUNCTIONAL_SDOPC(SDOPC) case ISD::SDOPC:
637#define END_REGISTER_VP_SDNODE(VPOPC) return ISD::VPOPC;
638#include "llvm/IR/VPIntrinsics.def"
639 }
640}
641
643 switch (ExtType) {
644 case ISD::EXTLOAD:
645 return IsFP ? ISD::FP_EXTEND : ISD::ANY_EXTEND;
646 case ISD::SEXTLOAD:
647 return ISD::SIGN_EXTEND;
648 case ISD::ZEXTLOAD:
649 return ISD::ZERO_EXTEND;
650 default:
651 break;
652 }
653
654 llvm_unreachable("Invalid LoadExtType");
655}
656
658 // To perform this operation, we just need to swap the L and G bits of the
659 // operation.
660 unsigned OldL = (Operation >> 2) & 1;
661 unsigned OldG = (Operation >> 1) & 1;
662 return ISD::CondCode((Operation & ~6) | // Keep the N, U, E bits
663 (OldL << 1) | // New G bit
664 (OldG << 2)); // New L bit.
665}
666
668 unsigned Operation = Op;
669 if (isIntegerLike)
670 Operation ^= 7; // Flip L, G, E bits, but not U.
671 else
672 Operation ^= 15; // Flip all of the condition bits.
673
675 Operation &= ~8; // Don't let N and U bits get set.
676
677 return ISD::CondCode(Operation);
678}
679
683
685 bool isIntegerLike) {
686 return getSetCCInverseImpl(Op, isIntegerLike);
687}
688
689/// For an integer comparison, return 1 if the comparison is a signed operation
690/// and 2 if the result is an unsigned comparison. Return zero if the operation
691/// does not depend on the sign of the input (setne and seteq).
692static int isSignedOp(ISD::CondCode Opcode) {
693 switch (Opcode) {
694 default: llvm_unreachable("Illegal integer setcc operation!");
695 case ISD::SETEQ:
696 case ISD::SETNE: return 0;
697 case ISD::SETLT:
698 case ISD::SETLE:
699 case ISD::SETGT:
700 case ISD::SETGE: return 1;
701 case ISD::SETULT:
702 case ISD::SETULE:
703 case ISD::SETUGT:
704 case ISD::SETUGE: return 2;
705 }
706}
707
709 EVT Type) {
710 bool IsInteger = Type.isInteger();
711 if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
712 // Cannot fold a signed integer setcc with an unsigned integer setcc.
713 return ISD::SETCC_INVALID;
714
715 unsigned Op = Op1 | Op2; // Combine all of the condition bits.
716
717 // If the N and U bits get set, then the resultant comparison DOES suddenly
718 // care about orderedness, and it is true when ordered.
719 if (Op > ISD::SETTRUE2)
720 Op &= ~16; // Clear the U bit if the N bit is set.
721
722 // Canonicalize illegal integer setcc's.
723 if (IsInteger && Op == ISD::SETUNE) // e.g. SETUGT | SETULT
724 Op = ISD::SETNE;
725
726 return ISD::CondCode(Op);
727}
728
730 EVT Type) {
731 bool IsInteger = Type.isInteger();
732 if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
733 // Cannot fold a signed setcc with an unsigned setcc.
734 return ISD::SETCC_INVALID;
735
736 // Combine all of the condition bits.
737 ISD::CondCode Result = ISD::CondCode(Op1 & Op2);
738
739 // Canonicalize illegal integer setcc's.
740 if (IsInteger) {
741 switch (Result) {
742 default: break;
743 case ISD::SETUO : Result = ISD::SETFALSE; break; // SETUGT & SETULT
744 case ISD::SETOEQ: // SETEQ & SETU[LG]E
745 case ISD::SETUEQ: Result = ISD::SETEQ ; break; // SETUGE & SETULE
746 case ISD::SETOLT: Result = ISD::SETULT ; break; // SETULT & SETNE
747 case ISD::SETOGT: Result = ISD::SETUGT ; break; // SETUGT & SETNE
748 }
749 }
750
751 return Result;
752}
753
754//===----------------------------------------------------------------------===//
755// SDNode Key Support
756//===----------------------------------------------------------------------===//
757
758/// If this is an SDNode with special info, add this info to the NodeID data.
759/// MorphNodeTo passes the opcode \p N is becoming, so \p Opc may differ from
760/// N->getOpcode() and a case may only cast to a class \p N already is.
761static void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N,
762 unsigned Opc) {
763 // Machine nodes are uniqued by opcode, value types and operands alone, as in
764 // getMachineNode; MorphNodeTo's clearMemRefs overwrites the fields below.
766 return;
767
768 switch (Opc) {
771 case ISD::MCSymbol:
772 llvm_unreachable("Should only be used on nodes with operands");
773 default: break; // Normal nodes don't need extra info.
775 case ISD::Constant: {
777 ID.AddPointer(C->getConstantIntValue());
778 ID.AddBoolean(C->isOpaque());
779 break;
780 }
782 case ISD::ConstantFP:
783 ID.AddPointer(cast<ConstantFPSDNode>(N)->getConstantFPValue());
784 break;
790 ID.AddPointer(GA->getGlobal());
791 ID.AddInteger(GA->getOffset());
792 ID.AddInteger(GA->getTargetFlags());
793 break;
794 }
795 case ISD::BasicBlock:
796 ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock());
797 break;
798 case ISD::EH_LABEL:
800 ID.AddPointer(cast<LabelSDNode>(N)->getLabel());
801 break;
803 ID.AddPointer(cast<DeactivationSymbolSDNode>(N)->getGlobal());
804 break;
805 case ISD::Register:
806 ID.AddInteger(cast<RegisterSDNode>(N)->getReg().id());
807 break;
809 ID.AddPointer(cast<RegisterMaskSDNode>(N)->getRegMask());
810 break;
811 case ISD::SRCVALUE:
812 ID.AddPointer(cast<SrcValueSDNode>(N)->getValue());
813 break;
814 case ISD::FrameIndex:
816 ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex());
817 break;
819 ID.AddInteger(cast<PseudoProbeSDNode>(N)->getGuid());
820 ID.AddInteger(cast<PseudoProbeSDNode>(N)->getIndex());
821 ID.AddInteger(cast<PseudoProbeSDNode>(N)->getAttributes());
822 break;
823 case ISD::JumpTable:
825 ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex());
826 ID.AddInteger(cast<JumpTableSDNode>(N)->getTargetFlags());
827 break;
831 ID.AddInteger(CP->getAlign().value());
832 ID.AddInteger(CP->getOffset());
835 else
836 ID.AddPointer(CP->getConstVal());
837 ID.AddInteger(CP->getTargetFlags());
838 break;
839 }
840 case ISD::TargetIndex: {
842 ID.AddInteger(TI->getIndex());
843 ID.AddInteger(TI->getOffset());
844 ID.AddInteger(TI->getTargetFlags());
845 break;
846 }
847 case ISD::LOAD: {
848 const LoadSDNode *LD = cast<LoadSDNode>(N);
849 ID.AddInteger(LD->getMemoryVT().getRawBits());
850 ID.AddInteger(LD->getRawSubclassData());
851 ID.AddInteger(LD->getPointerInfo().getAddrSpace());
852 ID.AddInteger(LD->getMemOperand()->getFlags());
853 break;
854 }
855 case ISD::STORE: {
856 const StoreSDNode *ST = cast<StoreSDNode>(N);
857 ID.AddInteger(ST->getMemoryVT().getRawBits());
858 ID.AddInteger(ST->getRawSubclassData());
859 ID.AddInteger(ST->getPointerInfo().getAddrSpace());
860 ID.AddInteger(ST->getMemOperand()->getFlags());
861 break;
862 }
863 case ISD::VP_LOAD: {
864 const VPLoadSDNode *ELD = cast<VPLoadSDNode>(N);
865 ID.AddInteger(ELD->getMemoryVT().getRawBits());
866 ID.AddInteger(ELD->getRawSubclassData());
867 ID.AddInteger(ELD->getPointerInfo().getAddrSpace());
868 ID.AddInteger(ELD->getMemOperand()->getFlags());
869 break;
870 }
871 case ISD::VP_LOAD_FF: {
872 const auto *LD = cast<VPLoadFFSDNode>(N);
873 ID.AddInteger(LD->getMemoryVT().getRawBits());
874 ID.AddInteger(LD->getRawSubclassData());
875 ID.AddInteger(LD->getPointerInfo().getAddrSpace());
876 ID.AddInteger(LD->getMemOperand()->getFlags());
877 break;
878 }
879 case ISD::VP_STORE: {
880 const VPStoreSDNode *EST = cast<VPStoreSDNode>(N);
881 ID.AddInteger(EST->getMemoryVT().getRawBits());
882 ID.AddInteger(EST->getRawSubclassData());
883 ID.AddInteger(EST->getPointerInfo().getAddrSpace());
884 ID.AddInteger(EST->getMemOperand()->getFlags());
885 break;
886 }
887 case ISD::EXPERIMENTAL_VP_STRIDED_LOAD: {
889 ID.AddInteger(SLD->getMemoryVT().getRawBits());
890 ID.AddInteger(SLD->getRawSubclassData());
891 ID.AddInteger(SLD->getPointerInfo().getAddrSpace());
892 break;
893 }
894 case ISD::EXPERIMENTAL_VP_STRIDED_STORE: {
896 ID.AddInteger(SST->getMemoryVT().getRawBits());
897 ID.AddInteger(SST->getRawSubclassData());
898 ID.AddInteger(SST->getPointerInfo().getAddrSpace());
899 break;
900 }
901 case ISD::VP_GATHER: {
903 ID.AddInteger(EG->getMemoryVT().getRawBits());
904 ID.AddInteger(EG->getRawSubclassData());
905 ID.AddInteger(EG->getPointerInfo().getAddrSpace());
906 ID.AddInteger(EG->getMemOperand()->getFlags());
907 break;
908 }
909 case ISD::VP_SCATTER: {
911 ID.AddInteger(ES->getMemoryVT().getRawBits());
912 ID.AddInteger(ES->getRawSubclassData());
913 ID.AddInteger(ES->getPointerInfo().getAddrSpace());
914 ID.AddInteger(ES->getMemOperand()->getFlags());
915 break;
916 }
917 case ISD::MLOAD: {
919 ID.AddInteger(MLD->getMemoryVT().getRawBits());
920 ID.AddInteger(MLD->getRawSubclassData());
921 ID.AddInteger(MLD->getPointerInfo().getAddrSpace());
922 ID.AddInteger(MLD->getMemOperand()->getFlags());
923 break;
924 }
925 case ISD::MSTORE: {
927 ID.AddInteger(MST->getMemoryVT().getRawBits());
928 ID.AddInteger(MST->getRawSubclassData());
929 ID.AddInteger(MST->getPointerInfo().getAddrSpace());
930 ID.AddInteger(MST->getMemOperand()->getFlags());
931 break;
932 }
933 case ISD::MGATHER: {
935 ID.AddInteger(MG->getMemoryVT().getRawBits());
936 ID.AddInteger(MG->getRawSubclassData());
937 ID.AddInteger(MG->getPointerInfo().getAddrSpace());
938 ID.AddInteger(MG->getMemOperand()->getFlags());
939 break;
940 }
941 case ISD::MSCATTER:
945 const MemSDNode *M = cast<MemSDNode>(N);
946 ID.AddInteger(M->getMemoryVT().getRawBits());
947 ID.AddInteger(M->getRawSubclassData());
948 ID.AddInteger(M->getPointerInfo().getAddrSpace());
949 ID.AddInteger(M->getMemOperand()->getFlags());
950 break;
951 }
952 case ISD::VECTOR_SHUFFLE: {
953 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(N)->getMask();
954 for (int M : Mask)
955 ID.AddInteger(M);
956 break;
957 }
958 case ISD::ADDRSPACECAST: {
960 ID.AddInteger(ASC->getSrcAddressSpace());
961 ID.AddInteger(ASC->getDestAddressSpace());
962 break;
963 }
965 case ISD::BlockAddress: {
967 ID.AddPointer(BA->getBlockAddress());
968 ID.AddInteger(BA->getOffset());
969 ID.AddInteger(BA->getTargetFlags());
970 break;
971 }
972 case ISD::AssertAlign:
973 ID.AddInteger(cast<AssertAlignSDNode>(N)->getAlign().value());
974 break;
975 case ISD::PREFETCH:
978 // Handled by MemIntrinsicSDNode check after the switch.
979 break;
981 ID.AddPointer(cast<MDNodeSDNode>(N)->getMD());
982 break;
983 } // end switch (Opc)
984
985 if (auto *AT = dyn_cast<AtomicSDNode>(N)) {
986 ID.AddInteger(AT->getMemoryVT().getRawBits());
987 ID.AddInteger(AT->getRawSubclassData());
988 ID.AddInteger(AT->getPointerInfo().getAddrSpace());
989 ID.AddInteger(AT->getMemOperand()->getFlags());
990 }
991
992 // MemIntrinsic nodes could also have subclass data, address spaces, and flags
993 // to check.
994 if (auto *MN = dyn_cast<MemIntrinsicSDNode>(N)) {
995 ID.AddInteger(MN->getRawSubclassData());
996 ID.AddInteger(MN->getMemoryVT().getRawBits());
997 for (const MachineMemOperand *MMO : MN->memoperands()) {
998 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
999 ID.AddInteger(MMO->getFlags());
1000 }
1001 }
1002}
1003
1005 : Opcode(N.getOpcode()), VTs(N.getVTList().VTs),
1006 OpStorage(N.op_begin(), N.op_end()) {
1007 Ops = OpStorage;
1008 AddNodeIDCustom(Tail, &N, N.getOpcode());
1009}
1010
1011#ifndef NDEBUG
1012/// Serialize a node the way SDNodes were uniqued before SDNodeKey, to
1013/// cross-check the typed comparison against. Deliberately reads the node
1014/// rather than going through SDNodeKey, so the key constructor is checked too
1015/// and not used as its own oracle.
1016static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) {
1017 ID.AddInteger(N->getOpcode());
1018 ID.AddPointer(N->getVTList().VTs);
1019 for (const SDUse &Op : N->ops()) {
1020 ID.AddPointer(Op.getNode());
1021 ID.AddInteger(Op.getResNo());
1022 }
1023 AddNodeIDCustom(ID, N, N->getOpcode());
1024}
1025
1027 ID.AddInteger(Key.Opcode);
1028 ID.AddPointer(Key.VTs);
1029 for (const SDValue &Op : Key.Ops) {
1030 ID.AddPointer(Op.getNode());
1031 ID.AddInteger(Op.getResNo());
1032 }
1033 ID.AddNodeID(Key.Tail);
1034}
1035#endif
1036
1037static bool keyMatches(const SDNodeKey &Key, const SDNode &N) {
1038 if (N.getOpcode() != Key.Opcode || N.getVTList().VTs != Key.VTs)
1039 return false;
1040 if (!llvm::equal(N.ops(), Key.Ops))
1041 return false;
1042 // Build only what AddNodeIDCustom would have added, which is nothing for
1043 // most opcodes, rather than the whole profile.
1044 FoldingSetNodeID Tail;
1045 AddNodeIDCustom(Tail, &N, N.getOpcode());
1046 return Tail == Key.Tail;
1047}
1048
1050 bool Result = keyMatches(Key, N);
1051
1052#ifndef NDEBUG
1053 FoldingSetNodeID NodeProfile, KeyProfile;
1054 AddNodeIDNode(NodeProfile, &N);
1055 AddNodeIDNode(KeyProfile, Key);
1056 assert((NodeProfile == KeyProfile) == Result &&
1057 "SDNodeKey equality disagrees with profile");
1058#endif
1059 return Result;
1060}
1061
1062//===----------------------------------------------------------------------===//
1063// SelectionDAG Class
1064//===----------------------------------------------------------------------===//
1065
1066/// doNotCSE - Return true if CSE should not be performed for this node.
1067static bool doNotCSE(SDNode *N) {
1068 if (N->getValueType(0) == MVT::Glue)
1069 return true; // Never CSE anything that produces a glue result.
1070
1071 switch (N->getOpcode()) {
1072 default: break;
1073 case ISD::HANDLENODE:
1074 case ISD::EH_LABEL:
1075 return true; // Never CSE these nodes.
1076 }
1077
1078 // Check that remaining values produced are not flags.
1079 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
1080 if (N->getValueType(i) == MVT::Glue)
1081 return true; // Never CSE anything that produces a glue result.
1082
1083 return false;
1084}
1085
1086/// Construct a DemandedElts mask which demands all elements of \p V.
1087/// If \p V is not a fixed-length vector, then this will return a single bit.
1089 EVT VT = V.getValueType();
1090 // Since the number of lanes in a scalable vector is unknown at compile time,
1091 // we track one bit which is implicitly broadcast to all lanes. This means
1092 // that all lanes in a scalable vector are considered demanded.
1094 : APInt(1, 1);
1095}
1096
1097/// RemoveDeadNodes - This method deletes all unreachable nodes in the
1098/// SelectionDAG.
1100 // Create a dummy node (which is not added to allnodes), that adds a reference
1101 // to the root node, preventing it from being deleted.
1102 HandleSDNode Dummy(getRoot());
1103
1104 SmallVector<SDNode*, 128> DeadNodes;
1105
1106 // Add all obviously-dead nodes to the DeadNodes worklist.
1107 for (SDNode &Node : allnodes())
1108 if (Node.use_empty())
1109 DeadNodes.push_back(&Node);
1110
1111 RemoveDeadNodes(DeadNodes);
1112
1113 // If the root changed (e.g. it was a dead load, update the root).
1114 setRoot(Dummy.getValue());
1115}
1116
1117/// RemoveDeadNodes - This method deletes the unreachable nodes in the
1118/// given list, and any nodes that become unreachable as a result.
1120
1121 // Process the worklist, deleting the nodes and adding their uses to the
1122 // worklist.
1123 while (!DeadNodes.empty()) {
1124 SDNode *N = DeadNodes.pop_back_val();
1125 // Skip to next node if we've already managed to delete the node. This could
1126 // happen if replacing a node causes a node previously added to the node to
1127 // be deleted.
1128 if (N->getOpcode() == ISD::DELETED_NODE)
1129 continue;
1130
1131 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1132 DUL->NodeDeleted(N, nullptr);
1133
1134 // Take the node out of the appropriate CSE map.
1135 RemoveNodeFromCSEMaps(N);
1136
1137 // Next, brutally remove the operand list. This is safe to do, as there are
1138 // no cycles in the graph.
1139 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
1140 SDUse &Use = *I++;
1141 SDNode *Operand = Use.getNode();
1142 Use.set(SDValue());
1143
1144 // Now that we removed this operand, see if there are no uses of it left.
1145 if (Operand->use_empty())
1146 DeadNodes.push_back(Operand);
1147 }
1148
1149 DeallocateNode(N);
1150 }
1151}
1152
1154 SmallVector<SDNode*, 16> DeadNodes(1, N);
1155
1156 // Create a dummy node that adds a reference to the root node, preventing
1157 // it from being deleted. (This matters if the root is an operand of the
1158 // dead node.)
1159 HandleSDNode Dummy(getRoot());
1160
1161 RemoveDeadNodes(DeadNodes);
1162}
1163
1165 // First take this out of the appropriate CSE map.
1166 RemoveNodeFromCSEMaps(N);
1167
1168 // Finally, remove uses due to operands of this node, remove from the
1169 // AllNodes list, and delete the node.
1170 DeleteNodeNotInCSEMaps(N);
1171}
1172
1173void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
1174 assert(N->getIterator() != AllNodes.begin() &&
1175 "Cannot delete the entry node!");
1176 assert(N->use_empty() && "Cannot delete a node that is not dead!");
1177
1178 // Drop all of the operands and decrement used node's use counts.
1179 N->DropOperands();
1180
1181 DeallocateNode(N);
1182}
1183
1184void SDDbgInfo::add(SDDbgValue *V, bool isParameter) {
1185 assert(!(V->isVariadic() && isParameter));
1186 if (isParameter)
1187 ByvalParmDbgValues.push_back(V);
1188 else
1189 DbgValues.push_back(V);
1190 for (const SDNode *Node : V->getSDNodes())
1191 if (Node)
1192 DbgValMap[Node].push_back(V);
1193}
1194
1196 DbgValMapType::iterator I = DbgValMap.find(Node);
1197 if (I == DbgValMap.end())
1198 return;
1199 for (auto &Val: I->second)
1200 Val->setIsInvalidated();
1201 DbgValMap.erase(I);
1202}
1203
1204void SelectionDAG::DeallocateNode(SDNode *N) {
1205 // If we have operands, deallocate them.
1207
1208 NodeAllocator.Deallocate(AllNodes.remove(N));
1209
1210 // Set the opcode to DELETED_NODE to help catch bugs when node
1211 // memory is reallocated.
1212 // FIXME: There are places in SDag that have grown a dependency on the opcode
1213 // value in the released node.
1214 __asan_unpoison_memory_region(&N->NodeType, sizeof(N->NodeType));
1215 N->NodeType = ISD::DELETED_NODE;
1216
1217 // If any of the SDDbgValue nodes refer to this SDNode, invalidate
1218 // them and forget about that node.
1219 DbgInfo->erase(N);
1220
1221 // Invalidate extra info.
1222 SDEI.erase(N);
1223}
1224
1225#ifndef NDEBUG
1226/// VerifySDNode - Check the given SDNode. Aborts if it is invalid.
1227void SelectionDAG::verifyNode(SDNode *N) const {
1228 switch (N->getOpcode()) {
1229 default:
1230 if (N->isTargetOpcode())
1232 break;
1233 case ISD::BUILD_PAIR: {
1234 EVT VT = N->getValueType(0);
1235 assert(N->getNumValues() == 1 && "Too many results!");
1236 assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) &&
1237 "Wrong return type!");
1238 assert(N->getNumOperands() == 2 && "Wrong number of operands!");
1239 assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() &&
1240 "Mismatched operand types!");
1241 assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() &&
1242 "Wrong operand type!");
1243 assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() &&
1244 "Wrong return type size");
1245 break;
1246 }
1247 case ISD::BUILD_VECTOR: {
1248 assert(N->getNumValues() == 1 && "Too many results!");
1249 assert(N->getValueType(0).isVector() && "Wrong return type!");
1250 assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() &&
1251 "Wrong number of operands!");
1252 EVT EltVT = N->getValueType(0).getVectorElementType();
1253 for (const SDUse &Op : N->ops()) {
1254 assert((Op.getValueType() == EltVT ||
1255 (EltVT.isInteger() && Op.getValueType().isInteger() &&
1256 EltVT.bitsLE(Op.getValueType()))) &&
1257 "Wrong operand type!");
1258 assert(Op.getValueType() == N->getOperand(0).getValueType() &&
1259 "Operands must all have the same type");
1260 }
1261 break;
1262 }
1263 case ISD::SADDO:
1264 case ISD::UADDO:
1265 case ISD::SSUBO:
1266 case ISD::USUBO:
1267 assert(N->getNumValues() == 2 && "Wrong number of results!");
1268 assert(N->getVTList().NumVTs == 2 && N->getNumOperands() == 2 &&
1269 "Invalid add/sub overflow op!");
1270 assert(N->getVTList().VTs[0].isInteger() &&
1271 N->getVTList().VTs[1].isInteger() &&
1272 N->getOperand(0).getValueType() == N->getOperand(1).getValueType() &&
1273 N->getOperand(0).getValueType() == N->getVTList().VTs[0] &&
1274 "Binary operator types must match!");
1275 break;
1276 }
1277}
1278#endif // NDEBUG
1279
1280/// Insert a newly allocated node into the DAG.
1281///
1282/// Handles insertion into the all nodes list and CSE map, as well as
1283/// verification and other common operations when a new node is allocated.
1284void SelectionDAG::InsertNode(SDNode *N) {
1285 AllNodes.push_back(N);
1286#ifndef NDEBUG
1287 N->PersistentId = NextPersistentId++;
1288 verifyNode(N);
1289#endif
1290 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1291 DUL->NodeInserted(N);
1292}
1293
1294/// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
1295/// correspond to it. This is useful when we're about to delete or repurpose
1296/// the node. We don't want future request for structurally identical nodes
1297/// to return N anymore.
1298bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
1299 bool Erased = false;
1300 switch (N->getOpcode()) {
1301 case ISD::HANDLENODE: return false; // noop.
1302 case ISD::CONDCODE:
1303 assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
1304 "Cond code doesn't exist!");
1305 Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != nullptr;
1306 CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = nullptr;
1307 break;
1309 Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
1310 break;
1312 ExternalSymbolSDNode *ESN = cast<ExternalSymbolSDNode>(N);
1313 Erased = TargetExternalSymbols.erase(std::pair<std::string, unsigned>(
1314 ESN->getSymbol(), ESN->getTargetFlags()));
1315 break;
1316 }
1317 case ISD::MCSymbol: {
1318 auto *MCSN = cast<MCSymbolSDNode>(N);
1319 Erased = MCSymbols.erase(MCSN->getMCSymbol());
1320 break;
1321 }
1322 case ISD::VALUETYPE: {
1323 EVT VT = cast<VTSDNode>(N)->getVT();
1324 if (VT.isExtended()) {
1325 Erased = ExtendedValueTypeNodes.erase(VT);
1326 } else {
1327 Erased = ValueTypeNodes[VT.getSimpleVT().SimpleTy] != nullptr;
1328 ValueTypeNodes[VT.getSimpleVT().SimpleTy] = nullptr;
1329 }
1330 break;
1331 }
1332 default:
1333 // Remove it from the CSE Map.
1334 assert(N->getOpcode() != ISD::DELETED_NODE && "DELETED_NODE in CSEMap!");
1335 assert(N->getOpcode() != ISD::EntryToken && "EntryToken in CSEMap!");
1336 Erased = CSEMap.erase(N);
1337 break;
1338 }
1339#ifndef NDEBUG
1340 // Verify that the node was actually in one of the CSE maps, unless it has a
1341 // glue result (which cannot be CSE'd) or is one of the special cases that are
1342 // not subject to CSE.
1343 if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Glue &&
1344 !N->isMachineOpcode() && !doNotCSE(N)) {
1345 N->dump(this);
1346 dbgs() << "\n";
1347 llvm_unreachable("Node is not in map!");
1348 }
1349#endif
1350 return Erased;
1351}
1352
1353/// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE
1354/// maps and modified in place. Add it back to the CSE maps, unless an identical
1355/// node already exists, in which case transfer all its users to the existing
1356/// node. This transfer can potentially trigger recursive merging.
1357void
1358SelectionDAG::AddModifiedNodeToCSEMaps(SDNode *N) {
1359 // For node types that aren't CSE'd, just act as if no identical node
1360 // already exists.
1361 if (!doNotCSE(N)) {
1362 SDNode *Existing = CSEMap.getOrInsert(N);
1363 if (Existing != N) {
1364 // If there was already an existing matching node, use ReplaceAllUsesWith
1365 // to replace the dead one with the existing one. This can cause
1366 // recursive merging of other unrelated nodes down the line.
1367 Existing->intersectFlagsWith(N->getFlags());
1368 if (auto *MemNode = dyn_cast<MemSDNode>(Existing)) {
1370 cast<MemSDNode>(N)->memoperands();
1371 // Range and cache hint metadata are not part of the DAG CSE key because
1372 // we prefer to CSE even when metadata does not match. Merge potentially
1373 // differing metadata conservatively.
1374 MemNode->refineMMOMetadata(NewMMOs);
1375 }
1376 ReplaceAllUsesWith(N, Existing);
1377
1378 // N is now dead. Inform the listeners and delete it.
1379 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1380 DUL->NodeDeleted(N, Existing);
1381 DeleteNodeNotInCSEMaps(N);
1382 return;
1383 }
1384 }
1385
1386 // If the node doesn't already exist, we updated it. Inform listeners.
1387 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1388 DUL->NodeUpdated(N);
1389}
1390
1391/// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1392/// were replaced with those specified. If this node is never memoized,
1393/// return null, otherwise return a pointer to the slot it would take. If a
1394/// node already exists with these operands, the slot will be non-null.
1395SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op,
1396 FoldingSetInsertToken &InsertToken) {
1397 if (doNotCSE(N))
1398 return nullptr;
1399
1400 SDValue Ops[] = { Op };
1401 SDNodeKey ID(N->getOpcode(), N->getVTList(), Ops);
1402 AddNodeIDCustom(ID.Tail, N, N->getOpcode());
1403 SDNode *Node = lookupNode(ID, SDLoc(N), InsertToken);
1404 if (Node)
1405 Node->intersectFlagsWith(N->getFlags());
1406 return Node;
1407}
1408
1409/// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1410/// were replaced with those specified. If this node is never memoized,
1411/// return null, otherwise return a pointer to the slot it would take. If a
1412/// node already exists with these operands, the slot will be non-null.
1413SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op1, SDValue Op2,
1414 FoldingSetInsertToken &InsertToken) {
1415 if (doNotCSE(N))
1416 return nullptr;
1417
1418 SDValue Ops[] = { Op1, Op2 };
1419 SDNodeKey ID(N->getOpcode(), N->getVTList(), Ops);
1420 AddNodeIDCustom(ID.Tail, N, N->getOpcode());
1421 SDNode *Node = lookupNode(ID, SDLoc(N), InsertToken);
1422 if (Node)
1423 Node->intersectFlagsWith(N->getFlags());
1424 return Node;
1425}
1426
1427/// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1428/// were replaced with those specified. If this node is never memoized,
1429/// return null, otherwise return a pointer to the slot it would take. If a
1430/// node already exists with these operands, the slot will be non-null.
1431SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, ArrayRef<SDValue> Ops,
1432 FoldingSetInsertToken &InsertToken) {
1433 if (doNotCSE(N))
1434 return nullptr;
1435
1436 SDNodeKey ID(N->getOpcode(), N->getVTList(), Ops);
1437 AddNodeIDCustom(ID.Tail, N, N->getOpcode());
1438 SDNode *Node = lookupNode(ID, SDLoc(N), InsertToken);
1439 if (Node)
1440 Node->intersectFlagsWith(N->getFlags());
1441 return Node;
1442}
1443
1445 Type *Ty = VT == MVT::iPTR ? PointerType::get(*getContext(), 0)
1446 : VT.getTypeForEVT(*getContext());
1447
1448 return getDataLayout().getABITypeAlign(Ty);
1449}
1450
1451// EntryNode could meaningfully have debug info if we can find it...
1453 : TM(tm), OptLevel(OL), EntryNode(ISD::EntryToken, 0, DebugLoc(),
1454 getVTList(MVT::Other, MVT::Glue)),
1455 Root(getEntryNode()) {
1456 InsertNode(&EntryNode);
1457 DbgInfo = new SDDbgInfo();
1458}
1459
1461 const TargetLibraryInfo *LibraryInfo,
1462 const LibcallLoweringInfo *LibcallsInfo,
1463 UniformityInfo *NewUA, ProfileSummaryInfo *PSIin,
1464 BlockFrequencyInfo *BFIin,
1465 FunctionVarLocs const *VarLocs) {
1466 MF = &NewMF;
1469 LibInfo = LibraryInfo;
1470 Libcalls = LibcallsInfo;
1471 Context = &MF->getFunction().getContext();
1472 UA = NewUA;
1473 PSI = PSIin;
1474 BFI = BFIin;
1475 FnVarLocs = VarLocs;
1476}
1477
1479 assert(!UpdateListeners && "Dangling registered DAGUpdateListeners");
1480 allnodes_clear();
1481 OperandRecycler.clear(OperandAllocator);
1482 delete DbgInfo;
1483}
1484
1486 return llvm::shouldOptimizeForSize(FLI->MBB->getBasicBlock(), PSI, BFI);
1487}
1488
1489void SelectionDAG::allnodes_clear() {
1490 assert(&*AllNodes.begin() == &EntryNode);
1491 AllNodes.remove(AllNodes.begin());
1492 while (!AllNodes.empty())
1493 DeallocateNode(&AllNodes.front());
1494#ifndef NDEBUG
1495 NextPersistentId = 0;
1496#endif
1497}
1498
1499SDNode *SelectionDAG::lookupNode(const SDNodeKey &Key,
1500 FoldingSetInsertToken &InsertToken) {
1501 SDNode *N = CSEMap.lookup(Key, InsertToken);
1502 if (N) {
1503 switch (N->getOpcode()) {
1504 default: break;
1505 case ISD::Constant:
1506 case ISD::ConstantFP:
1507 llvm_unreachable("Querying for Constant and ConstantFP nodes requires "
1508 "debug location. Use another overload.");
1509 }
1510 }
1511 return N;
1512}
1513
1514SDNode *SelectionDAG::lookupNode(const SDNodeKey &Key, const SDLoc &DL,
1515 FoldingSetInsertToken &InsertToken) {
1516 SDNode *N = CSEMap.lookup(Key, InsertToken);
1517 if (N) {
1518 switch (N->getOpcode()) {
1519 case ISD::Constant:
1520 case ISD::ConstantFP:
1521 // Erase debug location from the node if the node is used at several
1522 // different places. Do not propagate one location to all uses as it
1523 // will cause a worse single stepping debugging experience.
1524 if (N->getDebugLoc() != DL.getDebugLoc())
1525 N->setDebugLoc(DebugLoc());
1526 break;
1527 default:
1528 // When the node's point of use is located earlier in the instruction
1529 // sequence than its prior point of use, update its debug info to the
1530 // earlier location.
1531 if (DL.getIROrder() && DL.getIROrder() < N->getIROrder())
1532 N->setDebugLoc(DL.getDebugLoc());
1533 break;
1534 }
1535 }
1536 return N;
1537}
1538
1540 allnodes_clear();
1541 OperandRecycler.clear(OperandAllocator);
1542 OperandAllocator.Reset();
1543 CSEMap.clear();
1544
1545 ExtendedValueTypeNodes.clear();
1546 ExternalSymbols.clear();
1547 TargetExternalSymbols.clear();
1548 MCSymbols.clear();
1549 SDEI.clear();
1550 llvm::fill(CondCodeNodes, nullptr);
1551 llvm::fill(ValueTypeNodes, nullptr);
1552
1553 EntryNode.UseList = nullptr;
1554 InsertNode(&EntryNode);
1555 Root = getEntryNode();
1556 DbgInfo->clear();
1557}
1558
1560 return VT.bitsGT(Op.getValueType())
1561 ? getNode(ISD::FP_EXTEND, DL, VT, Op)
1562 : getNode(ISD::FP_ROUND, DL, VT, Op,
1563 getIntPtrConstant(0, DL, /*isTarget=*/true));
1564}
1565
1566std::pair<SDValue, SDValue>
1568 const SDLoc &DL, EVT VT) {
1569 assert(!VT.bitsEq(Op.getValueType()) &&
1570 "Strict no-op FP extend/round not allowed.");
1571 SDValue Res =
1572 VT.bitsGT(Op.getValueType())
1573 ? getNode(ISD::STRICT_FP_EXTEND, DL, {VT, MVT::Other}, {Chain, Op})
1574 : getNode(ISD::STRICT_FP_ROUND, DL, {VT, MVT::Other},
1575 {Chain, Op, getIntPtrConstant(0, DL, /*isTarget=*/true)});
1576
1577 return std::pair<SDValue, SDValue>(Res, SDValue(Res.getNode(), 1));
1578}
1579
1581 return VT.bitsGT(Op.getValueType()) ?
1582 getNode(ISD::ANY_EXTEND, DL, VT, Op) :
1583 getNode(ISD::TRUNCATE, DL, VT, Op);
1584}
1585
1587 return VT.bitsGT(Op.getValueType()) ?
1588 getNode(ISD::SIGN_EXTEND, DL, VT, Op) :
1589 getNode(ISD::TRUNCATE, DL, VT, Op);
1590}
1591
1593 return VT.bitsGT(Op.getValueType()) ?
1594 getNode(ISD::ZERO_EXTEND, DL, VT, Op) :
1595 getNode(ISD::TRUNCATE, DL, VT, Op);
1596}
1597
1599 EVT VT) {
1600 assert(!VT.isVector());
1601 auto Type = Op.getValueType();
1602 SDValue DestOp;
1603 if (Type == VT)
1604 return Op;
1605 auto Size = Op.getValueSizeInBits();
1606 DestOp = getBitcast(EVT::getIntegerVT(*Context, Size), Op);
1607 if (DestOp.getValueType() == VT)
1608 return DestOp;
1609
1610 return getAnyExtOrTrunc(DestOp, DL, VT);
1611}
1612
1614 EVT OpVT) {
1615 if (VT.bitsLE(Op.getValueType()))
1616 return getNode(ISD::TRUNCATE, SL, VT, Op);
1617
1618 TargetLowering::BooleanContent BType = TLI->getBooleanContents(OpVT);
1619 return getNode(TLI->getExtendForContent(BType), SL, VT, Op);
1620}
1621
1623 EVT OpVT = Op.getValueType();
1624 assert(VT.isInteger() && OpVT.isInteger() &&
1625 "Cannot getZeroExtendInReg FP types");
1626 assert(VT.isVector() == OpVT.isVector() &&
1627 "getZeroExtendInReg type should be vector iff the operand "
1628 "type is vector!");
1629 assert((!VT.isVector() ||
1631 "Vector element counts must match in getZeroExtendInReg");
1632 assert(VT.getScalarType().bitsLE(OpVT.getScalarType()) && "Not extending!");
1633 if (OpVT == VT)
1634 return Op;
1635 // TODO: Use computeKnownBits instead of AssertZext.
1636 if (Op.getOpcode() == ISD::AssertZext && cast<VTSDNode>(Op.getOperand(1))
1637 ->getVT()
1638 .getScalarType()
1639 .bitsLE(VT.getScalarType()))
1640 return Op;
1642 VT.getScalarSizeInBits());
1643 return getNode(ISD::AND, DL, OpVT, Op, getConstant(Imm, DL, OpVT));
1644}
1645
1647 // Only unsigned pointer semantics are supported right now. In the future this
1648 // might delegate to TLI to check pointer signedness.
1649 return getZExtOrTrunc(Op, DL, VT);
1650}
1651
1653 // Only unsigned pointer semantics are supported right now. In the future this
1654 // might delegate to TLI to check pointer signedness.
1655 return getZeroExtendInReg(Op, DL, VT);
1656}
1657
1659 return getNode(ISD::SUB, DL, VT, getConstant(0, DL, VT), Val);
1660}
1661
1662/// getNOT - Create a bitwise NOT operation as (XOR Val, -1).
1664 return getNode(ISD::XOR, DL, VT, Val, getAllOnesConstant(DL, VT));
1665}
1666
1668 SDValue TrueValue = getBoolConstant(true, DL, VT, VT);
1669 return getNode(ISD::XOR, DL, VT, Val, TrueValue);
1670}
1671
1673 EVT OpVT) {
1674 if (!V)
1675 return getConstant(0, DL, VT);
1676
1677 switch (TLI->getBooleanContents(OpVT)) {
1680 return getConstant(1, DL, VT);
1682 return getAllOnesConstant(DL, VT);
1683 }
1684 llvm_unreachable("Unexpected boolean content enum!");
1685}
1686
1688 bool isT, bool isO) {
1689 return getConstant(APInt(VT.getScalarSizeInBits(), Val, /*isSigned=*/false),
1690 DL, VT, isT, isO);
1691}
1692
1694 bool isT, bool isO) {
1695 return getConstant(*ConstantInt::get(*Context, Val), DL, VT, isT, isO);
1696}
1697
1699 EVT VT, bool isT, bool isO) {
1700 assert(VT.isInteger() && "Cannot create FP integer constant!");
1701
1702 EVT EltVT = VT.getScalarType();
1703 const ConstantInt *Elt = &Val;
1704
1705 // Vector splats are explicit within the DAG, with ConstantSDNode holding the
1706 // to-be-splatted scalar ConstantInt.
1707 if (isa<VectorType>(Elt->getType()))
1708 Elt = ConstantInt::get(*getContext(), Elt->getValue());
1709
1710 // In some cases the vector type is legal but the element type is illegal and
1711 // needs to be promoted, for example v8i8 on ARM. In this case, promote the
1712 // inserted value (the type does not need to match the vector element type).
1713 // Any extra bits introduced will be truncated away.
1714 if (VT.isVector() && TLI->getTypeAction(*getContext(), EltVT) ==
1716 EltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1717 APInt NewVal;
1718 if (TLI->isSExtCheaperThanZExt(VT.getScalarType(), EltVT))
1719 NewVal = Elt->getValue().sextOrTrunc(EltVT.getSizeInBits());
1720 else
1721 NewVal = Elt->getValue().zextOrTrunc(EltVT.getSizeInBits());
1722 Elt = ConstantInt::get(*getContext(), NewVal);
1723 }
1724 // In other cases the element type is illegal and needs to be expanded, for
1725 // example v2i64 on MIPS32. In this case, find the nearest legal type, split
1726 // the value into n parts and use a vector type with n-times the elements.
1727 // Then bitcast to the type requested.
1728 // Legalizing constants too early makes the DAGCombiner's job harder so we
1729 // only legalize if the DAG tells us we must produce legal types.
1730 else if (NewNodesMustHaveLegalTypes && VT.isVector() &&
1731 TLI->getTypeAction(*getContext(), EltVT) ==
1733 const APInt &NewVal = Elt->getValue();
1734 EVT ViaEltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1735 unsigned ViaEltSizeInBits = ViaEltVT.getSizeInBits();
1736
1737 // For scalable vectors, try to use a SPLAT_VECTOR_PARTS node.
1738 if (VT.isScalableVector() ||
1739 TLI->isOperationLegal(ISD::SPLAT_VECTOR, VT)) {
1740 assert(EltVT.getSizeInBits() % ViaEltSizeInBits == 0 &&
1741 "Can only handle an even split!");
1742 unsigned Parts = EltVT.getSizeInBits() / ViaEltSizeInBits;
1743
1744 SmallVector<SDValue, 2> ScalarParts;
1745 for (unsigned i = 0; i != Parts; ++i)
1746 ScalarParts.push_back(getConstant(
1747 NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL,
1748 ViaEltVT, isT, isO));
1749
1750 return getNode(ISD::SPLAT_VECTOR_PARTS, DL, VT, ScalarParts);
1751 }
1752
1753 unsigned ViaVecNumElts = VT.getSizeInBits() / ViaEltSizeInBits;
1754 EVT ViaVecVT = EVT::getVectorVT(*getContext(), ViaEltVT, ViaVecNumElts);
1755
1756 // Check the temporary vector is the correct size. If this fails then
1757 // getTypeToTransformTo() probably returned a type whose size (in bits)
1758 // isn't a power-of-2 factor of the requested type size.
1759 assert(ViaVecVT.getSizeInBits() == VT.getSizeInBits());
1760
1761 SmallVector<SDValue, 2> EltParts;
1762 for (unsigned i = 0; i < ViaVecNumElts / VT.getVectorNumElements(); ++i)
1763 EltParts.push_back(getConstant(
1764 NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL,
1765 ViaEltVT, isT, isO));
1766
1767 // EltParts is currently in little endian order. If we actually want
1768 // big-endian order then reverse it now.
1769 if (getDataLayout().isBigEndian())
1770 std::reverse(EltParts.begin(), EltParts.end());
1771
1772 // The elements must be reversed when the element order is different
1773 // to the endianness of the elements (because the BITCAST is itself a
1774 // vector shuffle in this situation). However, we do not need any code to
1775 // perform this reversal because getConstant() is producing a vector
1776 // splat.
1777 // This situation occurs in MIPS MSA.
1778
1780 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
1781 llvm::append_range(Ops, EltParts);
1782
1783 SDValue V =
1784 getNode(ISD::BITCAST, DL, VT, getBuildVector(ViaVecVT, DL, Ops));
1785 return V;
1786 }
1787
1788 assert(Elt->getBitWidth() == EltVT.getSizeInBits() &&
1789 "APInt size does not match type size!");
1790 unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
1791 SDVTList VTs = getVTList(EltVT);
1792 SDNodeKey ID(Opc, VTs, {});
1793 ID.AddPointer(Elt);
1794 ID.AddBoolean(isO);
1795 FoldingSetInsertToken InsertToken;
1796 SDNode *N = nullptr;
1797 if ((N = lookupNode(ID, DL, InsertToken)))
1798 if (!VT.isVector())
1799 return SDValue(N, 0);
1800
1801 if (!N) {
1802 N = newSDNode<ConstantSDNode>(isT, isO, Elt, VTs);
1803 if (!isT)
1804 N->setDebugLoc(DL.getDebugLoc());
1805 CSEMap.insert(N, InsertToken);
1806 InsertNode(N);
1807 NewSDValueDbgMsg(SDValue(N, 0), "Creating constant: ", this);
1808 }
1809
1810 SDValue Result(N, 0);
1811 if (VT.isVector())
1812 Result = getSplat(VT, DL, Result);
1813 return Result;
1814}
1815
1817 bool isT, bool isO) {
1818 unsigned Size = VT.getScalarSizeInBits();
1819 return getConstant(APInt(Size, Val, /*isSigned=*/true), DL, VT, isT, isO);
1820}
1821
1823 bool IsOpaque) {
1825 IsTarget, IsOpaque);
1826}
1827
1829 bool isTarget) {
1830 return getConstant(Val, DL, TLI->getPointerTy(getDataLayout()), isTarget);
1831}
1832
1834 const SDLoc &DL) {
1835 assert(VT.isInteger() && "Shift amount is not an integer type!");
1836 EVT ShiftVT = TLI->getShiftAmountTy(VT, getDataLayout());
1837 return getConstant(Val, DL, ShiftVT);
1838}
1839
1841 const SDLoc &DL) {
1842 assert(Val.ult(VT.getScalarSizeInBits()) && "Out of range shift");
1843 return getShiftAmountConstant(Val.getZExtValue(), VT, DL);
1844}
1845
1847 bool isTarget) {
1848 return getConstant(Val, DL, TLI->getVectorIdxTy(getDataLayout()), isTarget);
1849}
1850
1852 bool isTarget) {
1853 return getConstantFP(*ConstantFP::get(*getContext(), V), DL, VT, isTarget);
1854}
1855
1857 EVT VT, bool isTarget) {
1858 assert(VT.isFloatingPoint() && "Cannot create integer FP constant!");
1859
1860 EVT EltVT = VT.getScalarType();
1861 const ConstantFP *Elt = &V;
1862
1863 // Vector splats are explicit within the DAG, with ConstantFPSDNode holding
1864 // the to-be-splatted scalar ConstantFP.
1865 if (isa<VectorType>(Elt->getType()))
1866 Elt = ConstantFP::get(*getContext(), Elt->getValue());
1867
1868 // Do the map lookup using the actual bit pattern for the floating point
1869 // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
1870 // we don't have issues with SNANs.
1871 unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
1872 SDVTList VTs = getVTList(EltVT);
1873 SDNodeKey ID(Opc, VTs, {});
1874 ID.AddPointer(Elt);
1875 FoldingSetInsertToken InsertToken;
1876 SDNode *N = nullptr;
1877 if ((N = lookupNode(ID, DL, InsertToken)))
1878 if (!VT.isVector())
1879 return SDValue(N, 0);
1880
1881 if (!N) {
1882 N = newSDNode<ConstantFPSDNode>(isTarget, Elt, VTs);
1883 CSEMap.insert(N, InsertToken);
1884 InsertNode(N);
1885 }
1886
1887 SDValue Result(N, 0);
1888 if (VT.isVector())
1889 Result = getSplat(VT, DL, Result);
1890 NewSDValueDbgMsg(Result, "Creating fp constant: ", this);
1891 return Result;
1892}
1893
1895 bool isTarget) {
1896 EVT EltVT = VT.getScalarType();
1897 if (EltVT == MVT::f32)
1898 return getConstantFP(APFloat((float)Val), DL, VT, isTarget);
1899 if (EltVT == MVT::f64)
1900 return getConstantFP(APFloat(Val), DL, VT, isTarget);
1901 if (EltVT == MVT::f80 || EltVT == MVT::f128 || EltVT == MVT::ppcf128 ||
1902 EltVT == MVT::f16 || EltVT == MVT::bf16) {
1903 bool Ignored;
1904 APFloat APF = APFloat(Val);
1906 &Ignored);
1907 return getConstantFP(APF, DL, VT, isTarget);
1908 }
1909 llvm_unreachable("Unsupported type in getConstantFP");
1910}
1911
1913 EVT VT, int64_t Offset, bool isTargetGA,
1914 unsigned TargetFlags) {
1915 assert((TargetFlags == 0 || isTargetGA) &&
1916 "Cannot set target flags on target-independent globals");
1917
1918 // Truncate (with sign-extension) the offset value to the pointer size.
1920 if (BitWidth < 64)
1922
1923 unsigned Opc;
1924 if (GV->isThreadLocal())
1926 else
1928
1929 SDVTList VTs = getVTList(VT);
1930 SDNodeKey ID(Opc, VTs, {});
1931 ID.AddPointer(GV);
1932 ID.AddInteger(Offset);
1933 ID.AddInteger(TargetFlags);
1934 FoldingSetInsertToken InsertToken;
1935 if (SDNode *E = lookupNode(ID, DL, InsertToken))
1936 return SDValue(E, 0);
1937
1938 auto *N = newSDNode<GlobalAddressSDNode>(
1939 Opc, DL.getIROrder(), DL.getDebugLoc(), GV, VTs, Offset, TargetFlags);
1940 CSEMap.insert(N, InsertToken);
1941 InsertNode(N);
1942 return SDValue(N, 0);
1943}
1944
1946 SDVTList VTs = getVTList(MVT::Untyped);
1948 ID.AddPointer(GV);
1949 FoldingSetInsertToken InsertToken;
1950 if (SDNode *E = lookupNode(ID, SDLoc(), InsertToken))
1951 return SDValue(E, 0);
1952
1953 auto *N = newSDNode<DeactivationSymbolSDNode>(GV, VTs);
1954 CSEMap.insert(N, InsertToken);
1955 InsertNode(N);
1956 return SDValue(N, 0);
1957}
1958
1959SDValue SelectionDAG::getFrameIndex(int FI, EVT VT, bool isTarget) {
1960 unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
1961 SDVTList VTs = getVTList(VT);
1962 SDNodeKey ID(Opc, VTs, {});
1963 ID.AddInteger(FI);
1964 FoldingSetInsertToken InsertToken;
1965 if (SDNode *E = lookupNode(ID, InsertToken))
1966 return SDValue(E, 0);
1967
1968 auto *N = newSDNode<FrameIndexSDNode>(FI, VTs, isTarget);
1969 CSEMap.insert(N, InsertToken);
1970 InsertNode(N);
1971 return SDValue(N, 0);
1972}
1973
1974SDValue SelectionDAG::getJumpTable(int JTI, EVT VT, bool isTarget,
1975 unsigned TargetFlags) {
1976 assert((TargetFlags == 0 || isTarget) &&
1977 "Cannot set target flags on target-independent jump tables");
1978 unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
1979 SDVTList VTs = getVTList(VT);
1980 SDNodeKey ID(Opc, VTs, {});
1981 ID.AddInteger(JTI);
1982 ID.AddInteger(TargetFlags);
1983 FoldingSetInsertToken InsertToken;
1984 if (SDNode *E = lookupNode(ID, InsertToken))
1985 return SDValue(E, 0);
1986
1987 auto *N = newSDNode<JumpTableSDNode>(JTI, VTs, isTarget, TargetFlags);
1988 CSEMap.insert(N, InsertToken);
1989 InsertNode(N);
1990 return SDValue(N, 0);
1991}
1992
1994 const SDLoc &DL) {
1996 return getNode(ISD::JUMP_TABLE_DEBUG_INFO, DL, MVT::Other, Chain,
1997 getTargetConstant(static_cast<uint64_t>(JTI), DL, PTy, true));
1998}
1999
2001 MaybeAlign Alignment, int Offset,
2002 bool isTarget, unsigned TargetFlags) {
2003 assert((TargetFlags == 0 || isTarget) &&
2004 "Cannot set target flags on target-independent globals");
2005 if (!Alignment)
2006 Alignment = shouldOptForSize()
2007 ? getDataLayout().getABITypeAlign(C->getType())
2008 : getDataLayout().getPrefTypeAlign(C->getType());
2009 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
2010 SDVTList VTs = getVTList(VT);
2011 SDNodeKey ID(Opc, VTs, {});
2012 ID.AddInteger(Alignment->value());
2013 ID.AddInteger(Offset);
2014 ID.AddPointer(C);
2015 ID.AddInteger(TargetFlags);
2016 FoldingSetInsertToken InsertToken;
2017 if (SDNode *E = lookupNode(ID, InsertToken))
2018 return SDValue(E, 0);
2019
2020 auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VTs, Offset, *Alignment,
2021 TargetFlags);
2022 CSEMap.insert(N, InsertToken);
2023 InsertNode(N);
2024 SDValue V = SDValue(N, 0);
2025 NewSDValueDbgMsg(V, "Creating new constant pool: ", this);
2026 return V;
2027}
2028
2030 MaybeAlign Alignment, int Offset,
2031 bool isTarget, unsigned TargetFlags) {
2032 assert((TargetFlags == 0 || isTarget) &&
2033 "Cannot set target flags on target-independent globals");
2034 if (!Alignment)
2035 Alignment = getDataLayout().getPrefTypeAlign(C->getType());
2036 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
2037 SDVTList VTs = getVTList(VT);
2038 SDNodeKey ID(Opc, VTs, {});
2039 ID.AddInteger(Alignment->value());
2040 ID.AddInteger(Offset);
2041 C->addSelectionDAGCSEId(ID.Tail);
2042 ID.AddInteger(TargetFlags);
2043 FoldingSetInsertToken InsertToken;
2044 if (SDNode *E = lookupNode(ID, InsertToken))
2045 return SDValue(E, 0);
2046
2047 auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VTs, Offset, *Alignment,
2048 TargetFlags);
2049 CSEMap.insert(N, InsertToken);
2050 InsertNode(N);
2051 return SDValue(N, 0);
2052}
2053
2055 SDNodeKey ID(ISD::BasicBlock, getVTList(MVT::Other), {});
2056 ID.AddPointer(MBB);
2057 FoldingSetInsertToken InsertToken;
2058 if (SDNode *E = lookupNode(ID, InsertToken))
2059 return SDValue(E, 0);
2060
2061 auto *N = newSDNode<BasicBlockSDNode>(MBB);
2062 CSEMap.insert(N, InsertToken);
2063 InsertNode(N);
2064 return SDValue(N, 0);
2065}
2066
2068 if (VT.isSimple() && (unsigned)VT.getSimpleVT().SimpleTy >=
2069 ValueTypeNodes.size())
2070 ValueTypeNodes.resize(VT.getSimpleVT().SimpleTy+1);
2071
2072 SDNode *&N = VT.isExtended() ?
2073 ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT().SimpleTy];
2074
2075 if (N) return SDValue(N, 0);
2076 N = newSDNode<VTSDNode>(VT);
2077 InsertNode(N);
2078 return SDValue(N, 0);
2079}
2080
2082 SDNode *&N = ExternalSymbols[Sym];
2083 if (N) return SDValue(N, 0);
2084 N = newSDNode<ExternalSymbolSDNode>(false, Sym, 0, getVTList(VT));
2085 InsertNode(N);
2086 return SDValue(N, 0);
2087}
2088
2089SDValue SelectionDAG::getExternalSymbol(RTLIB::LibcallImpl Libcall, EVT VT) {
2091 return getExternalSymbol(SymName.data(), VT);
2092}
2093
2095 SDNode *&N = MCSymbols[Sym];
2096 if (N)
2097 return SDValue(N, 0);
2098 N = newSDNode<MCSymbolSDNode>(Sym, getVTList(VT));
2099 InsertNode(N);
2100 return SDValue(N, 0);
2101}
2102
2104 unsigned TargetFlags) {
2105 SDNode *&N =
2106 TargetExternalSymbols[std::pair<std::string, unsigned>(Sym, TargetFlags)];
2107 if (N) return SDValue(N, 0);
2108 N = newSDNode<ExternalSymbolSDNode>(true, Sym, TargetFlags, getVTList(VT));
2109 InsertNode(N);
2110 return SDValue(N, 0);
2111}
2112
2114 EVT VT, unsigned TargetFlags) {
2116 return getTargetExternalSymbol(SymName.data(), VT, TargetFlags);
2117}
2118
2120 if ((unsigned)Cond >= CondCodeNodes.size())
2121 CondCodeNodes.resize(Cond+1);
2122
2123 if (!CondCodeNodes[Cond]) {
2124 auto *N = newSDNode<CondCodeSDNode>(Cond);
2125 CondCodeNodes[Cond] = N;
2126 InsertNode(N);
2127 }
2128
2129 return SDValue(CondCodeNodes[Cond], 0);
2130}
2131
2133 assert(MulImm.getBitWidth() == VT.getSizeInBits() &&
2134 "APInt size does not match type size!");
2135
2136 if (MulImm == 0)
2137 return getConstant(0, DL, VT);
2138
2139 const MachineFunction &MF = getMachineFunction();
2140 const Function &F = MF.getFunction();
2141 ConstantRange CR = getVScaleRange(&F, 64);
2142 if (const APInt *C = CR.getSingleElement())
2143 return getConstant(MulImm * C->getZExtValue(), DL, VT);
2144
2145 return getNode(ISD::VSCALE, DL, VT, getConstant(MulImm, DL, VT));
2146}
2147
2148/// \returns a value of type \p VT that represents the runtime value of \p
2149/// Quantity, i.e. scaled by vscale if it's scalable, or a fixed constant
2150/// otherwise. Quantity should be a FixedOrScalableQuantity, i.e. ElementCount
2151/// or TypeSize.
2152template <typename Ty>
2154 EVT VT, Ty Quantity) {
2155 if (Quantity.isScalable())
2156 return DAG.getVScale(
2157 DL, VT, APInt(VT.getSizeInBits(), Quantity.getKnownMinValue()));
2158
2159 return DAG.getConstant(Quantity.getKnownMinValue(), DL, VT);
2160}
2161
2163 ElementCount EC) {
2164 return getFixedOrScalableQuantity(*this, DL, VT, EC);
2165}
2166
2168 return getFixedOrScalableQuantity(*this, DL, VT, TS);
2169}
2170
2172 ElementCount EC) {
2173 EVT IdxVT = TLI->getVectorIdxTy(getDataLayout());
2174 EVT MaskVT = TLI->getSetCCResultType(getDataLayout(), *getContext(), DataVT);
2175 return getNode(ISD::GET_ACTIVE_LANE_MASK, DL, MaskVT,
2176 getConstant(0, DL, IdxVT), getElementCount(DL, IdxVT, EC));
2177}
2178
2180 APInt One(ResVT.getScalarSizeInBits(), 1);
2181 return getStepVector(DL, ResVT, One);
2182}
2183
2185 const APInt &StepVal) {
2186 assert(ResVT.getScalarSizeInBits() == StepVal.getBitWidth());
2187 if (ResVT.isScalableVector())
2188 return getNode(
2189 ISD::STEP_VECTOR, DL, ResVT,
2190 getTargetConstant(StepVal, DL, ResVT.getVectorElementType()));
2191
2192 SmallVector<SDValue, 16> OpsStepConstants;
2193 for (uint64_t i = 0; i < ResVT.getVectorNumElements(); i++)
2194 OpsStepConstants.push_back(
2195 getConstant(StepVal * i, DL, ResVT.getVectorElementType()));
2196 return getBuildVector(ResVT, DL, OpsStepConstants);
2197}
2198
2199/// Swaps the values of N1 and N2. Swaps all indices in the shuffle mask M that
2200/// point at N1 to point at N2 and indices that point at N2 to point at N1.
2205
2207 SDValue N2, ArrayRef<int> Mask) {
2208 assert(VT.getVectorNumElements() == Mask.size() &&
2209 "Must have the same number of vector elements as mask elements!");
2210 assert(VT == N1.getValueType() && VT == N2.getValueType() &&
2211 "Invalid VECTOR_SHUFFLE");
2212
2213 // Canonicalize shuffle undef, undef -> undef
2214 if (N1.isUndef() && N2.isUndef()) {
2215 if (N1.getOpcode() == ISD::POISON && N2.getOpcode() == ISD::POISON)
2216 return getPOISON(VT);
2217 return getUNDEF(VT);
2218 }
2219
2220 // Validate that all indices in Mask are within the range of the elements
2221 // input to the shuffle.
2222 int NElts = Mask.size();
2223 assert(llvm::all_of(Mask,
2224 [&](int M) { return M < (NElts * 2) && M >= -1; }) &&
2225 "Index out of range");
2226
2227 // Copy the mask so we can do any needed cleanup.
2228 SmallVector<int, 8> MaskVec(Mask);
2229
2230 // Canonicalize shuffle v, v -> v, poison
2231 if (N1 == N2) {
2232 N2 = getPOISON(VT);
2233 for (int i = 0; i != NElts; ++i)
2234 if (MaskVec[i] >= NElts) MaskVec[i] -= NElts;
2235 }
2236
2237 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
2238 if (N1.isUndef())
2239 commuteShuffle(N1, N2, MaskVec);
2240
2241 if (TLI->hasVectorBlend()) {
2242 // If shuffling a splat, try to blend the splat instead. We do this here so
2243 // that even when this arises during lowering we don't have to re-handle it.
2244 auto BlendSplat = [&](BuildVectorSDNode *BV, int Offset) {
2245 BitVector UndefElements;
2246 SDValue Splat = BV->getSplatValue(&UndefElements);
2247 if (!Splat)
2248 return;
2249
2250 for (int i = 0; i < NElts; ++i) {
2251 if (MaskVec[i] < Offset || MaskVec[i] >= (Offset + NElts))
2252 continue;
2253
2254 // If this input comes from undef, mark it as such.
2255 if (UndefElements[MaskVec[i] - Offset]) {
2256 MaskVec[i] = -1;
2257 continue;
2258 }
2259
2260 // If we can blend a non-undef lane, use that instead.
2261 if (!UndefElements[i])
2262 MaskVec[i] = i + Offset;
2263 }
2264 };
2265 if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
2266 BlendSplat(N1BV, 0);
2267 if (auto *N2BV = dyn_cast<BuildVectorSDNode>(N2))
2268 BlendSplat(N2BV, NElts);
2269 }
2270
2271 // Canonicalize all index into lhs, -> shuffle lhs, poison
2272 // Canonicalize all index into rhs, -> shuffle rhs, poison
2273 bool AllLHS = true, AllRHS = true;
2274 bool N2Undef = N2.isUndef();
2275 for (int i = 0; i != NElts; ++i) {
2276 if (MaskVec[i] >= NElts) {
2277 if (N2Undef)
2278 MaskVec[i] = -1;
2279 else
2280 AllLHS = false;
2281 } else if (MaskVec[i] >= 0) {
2282 AllRHS = false;
2283 }
2284 }
2285 if (AllLHS && AllRHS)
2286 return getPOISON(VT);
2287 if (AllLHS && !N2Undef)
2288 N2 = getPOISON(VT);
2289 if (AllRHS) {
2290 N1 = getPOISON(VT);
2291 commuteShuffle(N1, N2, MaskVec);
2292 }
2293 // Reset our undef status after accounting for the mask.
2294 N2Undef = N2.isUndef();
2295 // Re-check whether both sides ended up undef.
2296 if (N1.isUndef() && N2Undef) {
2297 if (N1.getOpcode() == ISD::POISON && N2.getOpcode() == ISD::POISON)
2298 return getPOISON(VT);
2299 return getUNDEF(VT);
2300 }
2301
2302 // If Identity shuffle return that node.
2303 bool Identity = true, AllSame = true;
2304 for (int i = 0; i != NElts; ++i) {
2305 if (MaskVec[i] >= 0 && MaskVec[i] != i) Identity = false;
2306 if (MaskVec[i] != MaskVec[0]) AllSame = false;
2307 }
2308 if (Identity && NElts)
2309 return N1;
2310
2311 // Shuffling a constant splat doesn't change the result.
2312 if (N2Undef) {
2313 SDValue V = N1;
2314
2315 // Look through any bitcasts. We check that these don't change the number
2316 // (and size) of elements and just changes their types.
2317 while (V.getOpcode() == ISD::BITCAST)
2318 V = V->getOperand(0);
2319
2320 // A splat should always show up as a build vector node.
2321 if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) {
2322 BitVector UndefElements;
2323 SDValue Splat = BV->getSplatValue(&UndefElements);
2324 // If this is a splat of an undef, shuffling it is also undef.
2325 if (Splat && Splat.isUndef())
2326 return Splat.getOpcode() == ISD::POISON ? getPOISON(VT) : getUNDEF(VT);
2327
2328 bool SameNumElts =
2329 V.getValueType().getVectorNumElements() == VT.getVectorNumElements();
2330
2331 // We only have a splat which can skip shuffles if there is a splatted
2332 // value and no undef lanes rearranged by the shuffle.
2333 if (Splat && UndefElements.none()) {
2334 // Splat of <x, x, ..., x>, return <x, x, ..., x>, provided that the
2335 // number of elements match or the value splatted is a zero constant.
2336 if (SameNumElts || isNullConstant(Splat))
2337 return N1;
2338 }
2339
2340 // If the shuffle itself creates a splat, build the vector directly.
2341 if (AllSame && SameNumElts) {
2342 EVT BuildVT = BV->getValueType(0);
2343 const SDValue &Splatted = BV->getOperand(MaskVec[0]);
2344 SDValue NewBV = getSplatBuildVector(BuildVT, dl, Splatted);
2345
2346 // We may have jumped through bitcasts, so the type of the
2347 // BUILD_VECTOR may not match the type of the shuffle.
2348 if (BuildVT != VT)
2349 NewBV = getNode(ISD::BITCAST, dl, VT, NewBV);
2350 return NewBV;
2351 }
2352 }
2353 }
2354
2355 SDVTList VTs = getVTList(VT);
2356 SDValue Ops[2] = { N1, N2 };
2358 for (int i = 0; i != NElts; ++i)
2359 ID.AddInteger(MaskVec[i]);
2360
2361 FoldingSetInsertToken InsertToken;
2362 if (SDNode *E = lookupNode(ID, dl, InsertToken))
2363 return SDValue(E, 0);
2364
2365 // Allocate the mask array for the node out of the BumpPtrAllocator, since
2366 // SDNode doesn't have access to it. This memory will be "leaked" when
2367 // the node is deallocated, but recovered when the NodeAllocator is released.
2368 int *MaskAlloc = OperandAllocator.Allocate<int>(NElts);
2369 llvm::copy(MaskVec, MaskAlloc);
2370
2371 auto *N = newSDNode<ShuffleVectorSDNode>(VTs, dl.getIROrder(),
2372 dl.getDebugLoc(), MaskAlloc);
2373 createOperands(N, Ops);
2374
2375 CSEMap.insert(N, InsertToken);
2376 InsertNode(N);
2377 SDValue V = SDValue(N, 0);
2378 NewSDValueDbgMsg(V, "Creating new node: ", this);
2379 return V;
2380}
2381
2383 EVT VT = SV.getValueType(0);
2384 SmallVector<int, 8> MaskVec(SV.getMask());
2386
2387 SDValue Op0 = SV.getOperand(0);
2388 SDValue Op1 = SV.getOperand(1);
2389 return getVectorShuffle(VT, SDLoc(&SV), Op1, Op0, MaskVec);
2390}
2391
2393 SDVTList VTs = getVTList(VT);
2394 SDNodeKey ID(ISD::Register, VTs, {});
2395 ID.AddInteger(Reg.id());
2396 FoldingSetInsertToken InsertToken;
2397 if (SDNode *E = lookupNode(ID, InsertToken))
2398 return SDValue(E, 0);
2399
2400 auto *N = newSDNode<RegisterSDNode>(Reg, VTs);
2401 N->SDNodeBits.IsDivergent = TLI->isSDNodeSourceOfDivergence(N, FLI, UA);
2402 CSEMap.insert(N, InsertToken);
2403 InsertNode(N);
2404 return SDValue(N, 0);
2405}
2406
2408 SDNodeKey ID(ISD::RegisterMask, getVTList(MVT::Untyped), {});
2409 ID.AddPointer(RegMask);
2410 FoldingSetInsertToken InsertToken;
2411 if (SDNode *E = lookupNode(ID, InsertToken))
2412 return SDValue(E, 0);
2413
2414 auto *N = newSDNode<RegisterMaskSDNode>(RegMask);
2415 CSEMap.insert(N, InsertToken);
2416 InsertNode(N);
2417 return SDValue(N, 0);
2418}
2419
2421 MCSymbol *Label) {
2422 return getLabelNode(ISD::EH_LABEL, dl, Root, Label);
2423}
2424
2425SDValue SelectionDAG::getLabelNode(unsigned Opcode, const SDLoc &dl,
2426 SDValue Root, MCSymbol *Label) {
2427 SDValue Ops[] = { Root };
2428 SDNodeKey ID(Opcode, getVTList(MVT::Other), Ops);
2429 ID.AddPointer(Label);
2430 FoldingSetInsertToken InsertToken;
2431 if (SDNode *E = lookupNode(ID, InsertToken))
2432 return SDValue(E, 0);
2433
2434 auto *N =
2435 newSDNode<LabelSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), Label);
2436 createOperands(N, Ops);
2437
2438 CSEMap.insert(N, InsertToken);
2439 InsertNode(N);
2440 return SDValue(N, 0);
2441}
2442
2444 int64_t Offset, bool isTarget,
2445 unsigned TargetFlags) {
2446 unsigned Opc = isTarget ? ISD::TargetBlockAddress : ISD::BlockAddress;
2447 SDVTList VTs = getVTList(VT);
2448
2449 SDNodeKey ID(Opc, VTs, {});
2450 ID.AddPointer(BA);
2451 ID.AddInteger(Offset);
2452 ID.AddInteger(TargetFlags);
2453 FoldingSetInsertToken InsertToken;
2454 if (SDNode *E = lookupNode(ID, InsertToken))
2455 return SDValue(E, 0);
2456
2457 auto *N = newSDNode<BlockAddressSDNode>(Opc, VTs, BA, Offset, TargetFlags);
2458 CSEMap.insert(N, InsertToken);
2459 InsertNode(N);
2460 return SDValue(N, 0);
2461}
2462
2464 SDNodeKey ID(ISD::SRCVALUE, getVTList(MVT::Other), {});
2465 ID.AddPointer(V);
2466
2467 FoldingSetInsertToken InsertToken;
2468 if (SDNode *E = lookupNode(ID, InsertToken))
2469 return SDValue(E, 0);
2470
2471 auto *N = newSDNode<SrcValueSDNode>(V);
2472 CSEMap.insert(N, InsertToken);
2473 InsertNode(N);
2474 return SDValue(N, 0);
2475}
2476
2478 SDNodeKey ID(ISD::MDNODE_SDNODE, getVTList(MVT::Other), {});
2479 ID.AddPointer(MD);
2480
2481 FoldingSetInsertToken InsertToken;
2482 if (SDNode *E = lookupNode(ID, InsertToken))
2483 return SDValue(E, 0);
2484
2485 auto *N = newSDNode<MDNodeSDNode>(MD);
2486 CSEMap.insert(N, InsertToken);
2487 InsertNode(N);
2488 return SDValue(N, 0);
2489}
2490
2492 if (VT == V.getValueType())
2493 return V;
2494
2495 return getNode(ISD::BITCAST, SDLoc(V), VT, V);
2496}
2497
2499 unsigned SrcAS, unsigned DestAS,
2500 const SDNodeFlags Flags) {
2501 SDVTList VTs = getVTList(VT);
2502 SDValue Ops[] = {Ptr};
2504 ID.AddInteger(SrcAS);
2505 ID.AddInteger(DestAS);
2506
2507 FoldingSetInsertToken InsertToken;
2508 if (SDNode *E = lookupNode(ID, dl, InsertToken)) {
2509 E->intersectFlagsWith(Flags);
2510 return SDValue(E, 0);
2511 }
2512
2513 auto *N = newSDNode<AddrSpaceCastSDNode>(dl.getIROrder(), dl.getDebugLoc(),
2514 VTs, SrcAS, DestAS);
2515 N->setFlags(Flags);
2516 createOperands(N, Ops);
2517
2518 CSEMap.insert(N, InsertToken);
2519 InsertNode(N);
2520 return SDValue(N, 0);
2521}
2522
2524 return getNode(ISD::FREEZE, SDLoc(V), V.getValueType(), V);
2525}
2526
2528 UndefPoisonKind Kind) {
2529 if (isGuaranteedNotToBeUndefOrPoison(V, DemandedElts, Kind))
2530 return V;
2531 return getFreeze(V);
2532}
2533
2534/// getShiftAmountOperand - Return the specified value casted to
2535/// the target's desired shift amount type.
2537 EVT OpTy = Op.getValueType();
2538 EVT ShTy = TLI->getShiftAmountTy(LHSTy, getDataLayout());
2539 if (OpTy == ShTy || OpTy.isVector()) return Op;
2540
2541 return getZExtOrTrunc(Op, SDLoc(Op), ShTy);
2542}
2543
2545 SDLoc dl(Node);
2547 const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2548 EVT VT = Node->getValueType(0);
2549 SDValue Tmp1 = Node->getOperand(0);
2550 SDValue Tmp2 = Node->getOperand(1);
2551 const MaybeAlign MA(Node->getConstantOperandVal(3));
2552
2553 SDValue VAListLoad = getLoad(TLI.getPointerTy(getDataLayout()), dl, Tmp1,
2554 Tmp2, MachinePointerInfo(V));
2555 SDValue VAList = VAListLoad;
2556
2557 if (MA && *MA > TLI.getMinStackArgumentAlignment()) {
2558 VAList = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
2559 getConstant(MA->value() - 1, dl, VAList.getValueType()));
2560
2561 VAList = getNode(
2562 ISD::AND, dl, VAList.getValueType(), VAList,
2563 getSignedConstant(-(int64_t)MA->value(), dl, VAList.getValueType()));
2564 }
2565
2566 // Increment the pointer, VAList, to the next vaarg
2567 Tmp1 = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
2568 getConstant(getDataLayout().getTypeAllocSize(
2569 VT.getTypeForEVT(*getContext())),
2570 dl, VAList.getValueType()));
2571 // Store the incremented VAList to the legalized pointer
2572 Tmp1 =
2573 getStore(VAListLoad.getValue(1), dl, Tmp1, Tmp2, MachinePointerInfo(V));
2574 // Load the actual argument out of the pointer VAList
2575 return getLoad(VT, dl, Tmp1, VAList, MachinePointerInfo());
2576}
2577
2579 SDLoc dl(Node);
2581 // This defaults to loading a pointer from the input and storing it to the
2582 // output, returning the chain.
2583 const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue();
2584 const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue();
2585 SDValue Tmp1 =
2586 getLoad(TLI.getPointerTy(getDataLayout()), dl, Node->getOperand(0),
2587 Node->getOperand(2), MachinePointerInfo(VS));
2588 return getStore(Tmp1.getValue(1), dl, Tmp1, Node->getOperand(1),
2589 MachinePointerInfo(VD));
2590}
2591
2593 const DataLayout &DL = getDataLayout();
2594 Type *Ty = VT.getTypeForEVT(*getContext());
2595 Align RedAlign = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty);
2596
2597 if (TLI->isTypeLegal(VT) || !VT.isVector())
2598 return RedAlign;
2599
2600 const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
2601 const Align StackAlign = TFI->getStackAlign();
2602
2603 // See if we can choose a smaller ABI alignment in cases where it's an
2604 // illegal vector type that will get broken down.
2605 if (RedAlign > StackAlign) {
2606 EVT IntermediateVT;
2607 MVT RegisterVT;
2608 unsigned NumIntermediates;
2609 TLI->getVectorTypeBreakdown(*getContext(), VT, IntermediateVT,
2610 NumIntermediates, RegisterVT);
2611 Ty = IntermediateVT.getTypeForEVT(*getContext());
2612 Align RedAlign2 = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty);
2613 if (RedAlign2 < RedAlign)
2614 RedAlign = RedAlign2;
2615
2616 if (!getMachineFunction().getFrameInfo().isStackRealignable())
2617 // If the stack is not realignable, the alignment should be limited to the
2618 // StackAlignment
2619 RedAlign = std::min(RedAlign, StackAlign);
2620 }
2621
2622 return RedAlign;
2623}
2624
2626 MachineFrameInfo &MFI = MF->getFrameInfo();
2627 const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
2628 int StackID = 0;
2629 if (Bytes.isScalable())
2630 StackID = TFI->getStackIDForScalableVectors();
2631 // The stack id gives an indication of whether the object is scalable or
2632 // not, so it's safe to pass in the minimum size here.
2633 int FrameIdx = MFI.CreateStackObject(Bytes.getKnownMinValue(), Alignment,
2634 false, nullptr, StackID);
2635 return getFrameIndex(FrameIdx, TLI->getFrameIndexTy(getDataLayout()));
2636}
2637
2639 Type *Ty = VT.getTypeForEVT(*getContext());
2640 Align StackAlign =
2641 std::max(getDataLayout().getPrefTypeAlign(Ty), Align(minAlign));
2642 return CreateStackTemporary(VT.getStoreSize(), StackAlign);
2643}
2644
2646 TypeSize VT1Size = VT1.getStoreSize();
2647 TypeSize VT2Size = VT2.getStoreSize();
2648 assert(VT1Size.isScalable() == VT2Size.isScalable() &&
2649 "Don't know how to choose the maximum size when creating a stack "
2650 "temporary");
2651 TypeSize Bytes = VT1Size.getKnownMinValue() > VT2Size.getKnownMinValue()
2652 ? VT1Size
2653 : VT2Size;
2654
2655 Type *Ty1 = VT1.getTypeForEVT(*getContext());
2656 Type *Ty2 = VT2.getTypeForEVT(*getContext());
2657 const DataLayout &DL = getDataLayout();
2658 Align Align = std::max(DL.getPrefTypeAlign(Ty1), DL.getPrefTypeAlign(Ty2));
2659 return CreateStackTemporary(Bytes, Align);
2660}
2661
2663 const SDLoc &DL, SDValue Chain) {
2664 EVT SrcVT = SrcOp.getValueType();
2665 Type *DestType = DestVT.getTypeForEVT(*getContext());
2666 Align DestAlign = getDataLayout().getPrefTypeAlign(DestType);
2667
2668 // Create the stack frame object.
2669 Align SrcAlign =
2671 SDValue FIPtr = CreateStackTemporary(SlotVT.getStoreSize(), SrcAlign);
2672
2673 FrameIndexSDNode *StackPtrFI = cast<FrameIndexSDNode>(FIPtr);
2674 int SPFI = StackPtrFI->getIndex();
2675 MachinePointerInfo PtrInfo =
2677
2678 // Emit a store to the stack slot. Use a truncstore if the input value is
2679 // later than DestVT.
2680 SDValue Store;
2681
2682 if (SrcVT.bitsGT(SlotVT))
2683 Store = getTruncStore(Chain, DL, SrcOp, FIPtr, PtrInfo, SlotVT, SrcAlign);
2684 else {
2685 assert(SrcVT.bitsEq(SlotVT) && "Invalid store");
2686 Store = getStore(Chain, DL, SrcOp, FIPtr, PtrInfo, SrcAlign);
2687 }
2688
2689 // Result is a load from the stack slot.
2690 if (SlotVT.bitsEq(DestVT))
2691 return getLoad(DestVT, DL, Store, FIPtr, PtrInfo, DestAlign);
2692
2693 assert(SlotVT.bitsLT(DestVT) && "Unknown extension!");
2694 return getExtLoad(ISD::EXTLOAD, DL, DestVT, Store, FIPtr, PtrInfo, SlotVT,
2695 DestAlign);
2696}
2697
2699 ISD::CondCode Cond, const SDLoc &dl,
2700 SDNodeFlags Flags) {
2701 EVT OpVT = N1.getValueType();
2702
2703 auto GetUndefBooleanConstant = [&]() {
2704 if (VT.getScalarType() == MVT::i1 ||
2705 TLI->getBooleanContents(OpVT) ==
2707 return getUNDEF(VT);
2708 // ZeroOrOne / ZeroOrNegative require specific values for the high bits,
2709 // so we cannot use getUNDEF(). Return zero instead.
2710 return getConstant(0, dl, VT);
2711 };
2712
2713 // These setcc operations always fold.
2714 switch (Cond) {
2715 default: break;
2716 case ISD::SETFALSE:
2717 case ISD::SETFALSE2: return getBoolConstant(false, dl, VT, OpVT);
2718 case ISD::SETTRUE:
2719 case ISD::SETTRUE2: return getBoolConstant(true, dl, VT, OpVT);
2720
2721 case ISD::SETOEQ:
2722 case ISD::SETOGT:
2723 case ISD::SETOGE:
2724 case ISD::SETOLT:
2725 case ISD::SETOLE:
2726 case ISD::SETONE:
2727 case ISD::SETO:
2728 case ISD::SETUO:
2729 case ISD::SETUEQ:
2730 case ISD::SETUNE:
2731 assert(!OpVT.isInteger() && "Illegal setcc for integer!");
2732 break;
2733 }
2734
2735 if (OpVT.isInteger()) {
2736 // For EQ and NE, we can always pick a value for the undef to make the
2737 // predicate pass or fail, so we can return undef.
2738 // Matches behavior in llvm::ConstantFoldCompareInstruction.
2739 // icmp eq/ne X, undef -> undef.
2740 if ((N1.isUndef() || N2.isUndef()) &&
2741 (Cond == ISD::SETEQ || Cond == ISD::SETNE))
2742 return GetUndefBooleanConstant();
2743
2744 // If both operands are undef, we can return undef for int comparison.
2745 // icmp undef, undef -> undef.
2746 if (N1.isUndef() && N2.isUndef())
2747 return GetUndefBooleanConstant();
2748
2749 // icmp X, X -> true/false
2750 // icmp X, undef -> true/false because undef could be X.
2751 if (N1.isUndef() || N2.isUndef() || N1 == N2)
2752 return getBoolConstant(ISD::isTrueWhenEqual(Cond), dl, VT, OpVT);
2753 }
2754
2756 const APInt &C2 = N2C->getAPIntValue();
2758 const APInt &C1 = N1C->getAPIntValue();
2759
2761 dl, VT, OpVT);
2762 }
2763 }
2764
2765 auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
2766 auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
2767
2768 if (N1CFP && N2CFP) {
2769 APFloat::cmpResult R = N1CFP->getValueAPF().compare(N2CFP->getValueAPF());
2770 switch (Cond) {
2771 default: break;
2772 case ISD::SETEQ: if (R==APFloat::cmpUnordered)
2773 return GetUndefBooleanConstant();
2774 [[fallthrough]];
2775 case ISD::SETOEQ: return getBoolConstant(R==APFloat::cmpEqual, dl, VT,
2776 OpVT);
2777 case ISD::SETNE: if (R==APFloat::cmpUnordered)
2778 return GetUndefBooleanConstant();
2779 [[fallthrough]];
2781 R==APFloat::cmpLessThan, dl, VT,
2782 OpVT);
2783 case ISD::SETLT: if (R==APFloat::cmpUnordered)
2784 return GetUndefBooleanConstant();
2785 [[fallthrough]];
2786 case ISD::SETOLT: return getBoolConstant(R==APFloat::cmpLessThan, dl, VT,
2787 OpVT);
2788 case ISD::SETGT: if (R==APFloat::cmpUnordered)
2789 return GetUndefBooleanConstant();
2790 [[fallthrough]];
2792 VT, OpVT);
2793 case ISD::SETLE: if (R==APFloat::cmpUnordered)
2794 return GetUndefBooleanConstant();
2795 [[fallthrough]];
2797 R==APFloat::cmpEqual, dl, VT,
2798 OpVT);
2799 case ISD::SETGE: if (R==APFloat::cmpUnordered)
2800 return GetUndefBooleanConstant();
2801 [[fallthrough]];
2803 R==APFloat::cmpEqual, dl, VT, OpVT);
2804 case ISD::SETO: return getBoolConstant(R!=APFloat::cmpUnordered, dl, VT,
2805 OpVT);
2806 case ISD::SETUO: return getBoolConstant(R==APFloat::cmpUnordered, dl, VT,
2807 OpVT);
2809 R==APFloat::cmpEqual, dl, VT,
2810 OpVT);
2811 case ISD::SETUNE: return getBoolConstant(R!=APFloat::cmpEqual, dl, VT,
2812 OpVT);
2814 R==APFloat::cmpLessThan, dl, VT,
2815 OpVT);
2817 R==APFloat::cmpUnordered, dl, VT,
2818 OpVT);
2820 VT, OpVT);
2821 case ISD::SETUGE: return getBoolConstant(R!=APFloat::cmpLessThan, dl, VT,
2822 OpVT);
2823 }
2824 } else if (N1CFP && OpVT.isSimple() && !N2.isUndef()) {
2825 // Ensure that the constant occurs on the RHS.
2827 if (!TLI->isCondCodeLegal(SwappedCond, OpVT.getSimpleVT()))
2828 return SDValue();
2829 return getSetCC(dl, VT, N2, N1, SwappedCond, /*Chain=*/{},
2830 /*IsSignaling=*/false, Flags);
2831 } else if ((N2CFP && N2CFP->getValueAPF().isNaN()) ||
2832 (OpVT.isFloatingPoint() && (N1.isUndef() || N2.isUndef()))) {
2833 // If an operand is known to be a nan (or undef that could be a nan), we can
2834 // fold it.
2835 // Choosing NaN for the undef will always make unordered comparison succeed
2836 // and ordered comparison fails.
2837 // Matches behavior in llvm::ConstantFoldCompareInstruction.
2838 switch (ISD::getUnorderedFlavor(Cond)) {
2839 default:
2840 llvm_unreachable("Unknown flavor!");
2841 case 0: // Known false.
2842 return getBoolConstant(false, dl, VT, OpVT);
2843 case 1: // Known true.
2844 return getBoolConstant(true, dl, VT, OpVT);
2845 case 2: // Undefined.
2846 return GetUndefBooleanConstant();
2847 }
2848 }
2849
2850 // Could not fold it.
2851 return SDValue();
2852}
2853
2854/// SignBitIsZero - Return true if the sign bit of Op is known to be zero. We
2855/// use this predicate to simplify operations downstream.
2857 unsigned BitWidth = Op.getScalarValueSizeInBits();
2859}
2860
2861// TODO: Should have argument to specify if sign bit of nan is ignorable.
2863 if (Depth >= MaxRecursionDepth)
2864 return false; // Limit search depth.
2865
2866 unsigned Opc = Op.getOpcode();
2867 switch (Opc) {
2868 case ISD::FABS:
2869 return true;
2870 case ISD::AssertNoFPClass: {
2871 FPClassTest NoFPClass =
2872 static_cast<FPClassTest>(Op.getConstantOperandVal(1));
2873
2874 const FPClassTest TestMask = fcNan | fcNegative;
2875 return (NoFPClass & TestMask) == TestMask;
2876 }
2877 case ISD::ARITH_FENCE:
2878 return SignBitIsZeroFP(Op.getOperand(0), Depth + 1);
2879 case ISD::FEXP:
2880 case ISD::FEXP2:
2881 case ISD::FEXP10:
2882 return Op->getFlags().hasNoNaNs();
2883 case ISD::FMINNUM:
2884 case ISD::FMINNUM_IEEE:
2885 case ISD::FMINIMUM:
2886 case ISD::FMINIMUMNUM:
2887 return SignBitIsZeroFP(Op.getOperand(1), Depth + 1) &&
2888 SignBitIsZeroFP(Op.getOperand(0), Depth + 1);
2889 case ISD::FMAXNUM:
2890 case ISD::FMAXNUM_IEEE:
2891 case ISD::FMAXIMUM:
2892 case ISD::FMAXIMUMNUM:
2893 // TODO: If we can ignore the sign bit of nans, only one side being known 0
2894 // is sufficient.
2895 return SignBitIsZeroFP(Op.getOperand(1), Depth + 1) &&
2896 SignBitIsZeroFP(Op.getOperand(0), Depth + 1);
2897 default:
2898 return false;
2899 }
2900
2901 llvm_unreachable("covered opcode switch");
2902}
2903
2904/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
2905/// this predicate to simplify operations downstream. Mask is known to be zero
2906/// for bits that V cannot have.
2908 unsigned Depth) const {
2909 return Mask.isSubsetOf(computeKnownBits(V, Depth).Zero);
2910}
2911
2912/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero in
2913/// DemandedElts. We use this predicate to simplify operations downstream.
2914/// Mask is known to be zero for bits that V cannot have.
2916 const APInt &DemandedElts,
2917 unsigned Depth) const {
2918 return Mask.isSubsetOf(computeKnownBits(V, DemandedElts, Depth).Zero);
2919}
2920
2921/// MaskedVectorIsZero - Return true if 'Op' is known to be zero in
2922/// DemandedElts. We use this predicate to simplify operations downstream.
2924 unsigned Depth /* = 0 */) const {
2925 return computeKnownBits(V, DemandedElts, Depth).isZero();
2926}
2927
2928/// MaskedValueIsAllOnes - Return true if '(Op & Mask) == Mask'.
2930 unsigned Depth) const {
2931 return Mask.isSubsetOf(computeKnownBits(V, Depth).One);
2932}
2933
2935 const APInt &DemandedElts,
2936 unsigned Depth) const {
2937 EVT VT = Op.getValueType();
2938 assert(VT.isVector() && !VT.isScalableVector() && "Only for fixed vectors!");
2939
2940 unsigned NumElts = VT.getVectorNumElements();
2941 assert(DemandedElts.getBitWidth() == NumElts && "Unexpected demanded mask.");
2942
2943 APInt KnownZeroElements = APInt::getZero(NumElts);
2944 for (unsigned EltIdx = 0; EltIdx != NumElts; ++EltIdx) {
2945 if (!DemandedElts[EltIdx])
2946 continue; // Don't query elements that are not demanded.
2947 APInt Mask = APInt::getOneBitSet(NumElts, EltIdx);
2948 if (MaskedVectorIsZero(Op, Mask, Depth))
2949 KnownZeroElements.setBit(EltIdx);
2950 }
2951 return KnownZeroElements;
2952}
2953
2954/// isSplatValue - Return true if the vector V has the same value
2955/// across all DemandedElts. For scalable vectors, we don't know the
2956/// number of lanes at compile time. Instead, we use a 1 bit APInt
2957/// to represent a conservative value for all lanes; that is, that
2958/// one bit value is implicitly splatted across all lanes.
2959bool SelectionDAG::isSplatValue(SDValue V, const APInt &DemandedElts,
2960 APInt &UndefElts, unsigned Depth) const {
2961 unsigned Opcode = V.getOpcode();
2962 EVT VT = V.getValueType();
2963 assert(VT.isVector() && "Vector type expected");
2964 assert((!VT.isScalableVector() || DemandedElts.getBitWidth() == 1) &&
2965 "scalable demanded bits are ignored");
2966
2967 if (!DemandedElts)
2968 return false; // No demanded elts, better to assume we don't know anything.
2969
2970 if (Depth >= MaxRecursionDepth)
2971 return false; // Limit search depth.
2972
2973 // Deal with some common cases here that work for both fixed and scalable
2974 // vector types.
2975 switch (Opcode) {
2976 case ISD::SPLAT_VECTOR:
2977 UndefElts = V.getOperand(0).isUndef()
2978 ? APInt::getAllOnes(DemandedElts.getBitWidth())
2979 : APInt(DemandedElts.getBitWidth(), 0);
2980 return true;
2981 case ISD::ADD:
2982 case ISD::SUB:
2983 case ISD::AND:
2984 case ISD::XOR:
2985 case ISD::OR: {
2986 APInt UndefLHS, UndefRHS;
2987 SDValue LHS = V.getOperand(0);
2988 SDValue RHS = V.getOperand(1);
2989 // Only recognize splats with the same demanded undef elements for both
2990 // operands, otherwise we might fail to handle binop-specific undef
2991 // handling.
2992 // e.g. (and undef, 0) -> 0 etc.
2993 if (isSplatValue(LHS, DemandedElts, UndefLHS, Depth + 1) &&
2994 isSplatValue(RHS, DemandedElts, UndefRHS, Depth + 1) &&
2995 (DemandedElts & UndefLHS) == (DemandedElts & UndefRHS)) {
2996 UndefElts = UndefLHS | UndefRHS;
2997 return true;
2998 }
2999 return false;
3000 }
3001 case ISD::ABS:
3003 case ISD::TRUNCATE:
3004 case ISD::SIGN_EXTEND:
3005 case ISD::ZERO_EXTEND:
3006 return isSplatValue(V.getOperand(0), DemandedElts, UndefElts, Depth + 1);
3007 default:
3008 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
3009 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID)
3010 return TLI->isSplatValueForTargetNode(V, DemandedElts, UndefElts, *this,
3011 Depth);
3012 break;
3013 }
3014
3015 // We don't support other cases than those above for scalable vectors at
3016 // the moment.
3017 if (VT.isScalableVector())
3018 return false;
3019
3020 unsigned NumElts = VT.getVectorNumElements();
3021 assert(NumElts == DemandedElts.getBitWidth() && "Vector size mismatch");
3022 UndefElts = APInt::getZero(NumElts);
3023
3024 switch (Opcode) {
3025 case ISD::BUILD_VECTOR: {
3026 SDValue Scl;
3027 for (unsigned i = 0; i != NumElts; ++i) {
3028 SDValue Op = V.getOperand(i);
3029 if (Op.isUndef()) {
3030 UndefElts.setBit(i);
3031 continue;
3032 }
3033 if (!DemandedElts[i])
3034 continue;
3035 if (Scl && Scl != Op)
3036 return false;
3037 Scl = Op;
3038 }
3039 return true;
3040 }
3041 case ISD::VECTOR_SHUFFLE: {
3042 // Check if this is a shuffle node doing a splat or a shuffle of a splat.
3043 APInt DemandedLHS = APInt::getZero(NumElts);
3044 APInt DemandedRHS = APInt::getZero(NumElts);
3045 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(V)->getMask();
3046 for (int i = 0; i != (int)NumElts; ++i) {
3047 int M = Mask[i];
3048 if (M < 0) {
3049 UndefElts.setBit(i);
3050 continue;
3051 }
3052 if (!DemandedElts[i])
3053 continue;
3054 if (M < (int)NumElts)
3055 DemandedLHS.setBit(M);
3056 else
3057 DemandedRHS.setBit(M - NumElts);
3058 }
3059
3060 // If we aren't demanding either op, assume there's no splat.
3061 // If we are demanding both ops, assume there's no splat.
3062 if ((DemandedLHS.isZero() && DemandedRHS.isZero()) ||
3063 (!DemandedLHS.isZero() && !DemandedRHS.isZero()))
3064 return false;
3065
3066 // See if the demanded elts of the source op is a splat or we only demand
3067 // one element, which should always be a splat.
3068 // TODO: Handle source ops splats with undefs.
3069 auto CheckSplatSrc = [&](SDValue Src, const APInt &SrcElts) {
3070 APInt SrcUndefs;
3071 return (SrcElts.popcount() == 1) ||
3072 (isSplatValue(Src, SrcElts, SrcUndefs, Depth + 1) &&
3073 (SrcElts & SrcUndefs).isZero());
3074 };
3075 if (!DemandedLHS.isZero())
3076 return CheckSplatSrc(V.getOperand(0), DemandedLHS);
3077 return CheckSplatSrc(V.getOperand(1), DemandedRHS);
3078 }
3080 // Offset the demanded elts by the subvector index.
3081 SDValue Src = V.getOperand(0);
3082 // We don't support scalable vectors at the moment.
3083 if (Src.getValueType().isScalableVector())
3084 return false;
3085 uint64_t Idx = V.getConstantOperandVal(1);
3086 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
3087 APInt UndefSrcElts;
3088 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
3089 if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) {
3090 UndefElts = UndefSrcElts.extractBits(NumElts, Idx);
3091 return true;
3092 }
3093 break;
3094 }
3098 // Widen the demanded elts by the src element count.
3099 SDValue Src = V.getOperand(0);
3100 // We don't support scalable vectors at the moment.
3101 if (Src.getValueType().isScalableVector())
3102 return false;
3103 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
3104 APInt UndefSrcElts;
3105 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts);
3106 if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) {
3107 UndefElts = UndefSrcElts.trunc(NumElts);
3108 return true;
3109 }
3110 break;
3111 }
3112 case ISD::BITCAST: {
3113 SDValue Src = V.getOperand(0);
3114 EVT SrcVT = Src.getValueType();
3115 unsigned SrcBitWidth = SrcVT.getScalarSizeInBits();
3116 unsigned BitWidth = VT.getScalarSizeInBits();
3117
3118 // Ignore bitcasts from unsupported types.
3119 // TODO: Add fp support?
3120 if (!SrcVT.isVector() || !SrcVT.isInteger() || !VT.isInteger())
3121 break;
3122
3123 // Bitcast 'small element' vector to 'large element' vector.
3124 if ((BitWidth % SrcBitWidth) == 0) {
3125 // See if each sub element is a splat.
3126 unsigned Scale = BitWidth / SrcBitWidth;
3127 unsigned NumSrcElts = SrcVT.getVectorNumElements();
3128 APInt ScaledDemandedElts =
3129 APIntOps::ScaleBitMask(DemandedElts, NumSrcElts);
3130 for (unsigned I = 0; I != Scale; ++I) {
3131 APInt SubUndefElts;
3132 APInt SubDemandedElt = APInt::getOneBitSet(Scale, I);
3133 APInt SubDemandedElts = APInt::getSplat(NumSrcElts, SubDemandedElt);
3134 SubDemandedElts &= ScaledDemandedElts;
3135 if (!isSplatValue(Src, SubDemandedElts, SubUndefElts, Depth + 1))
3136 return false;
3137 // TODO: Add support for merging sub undef elements.
3138 if (!SubUndefElts.isZero())
3139 return false;
3140 }
3141 return true;
3142 }
3143 break;
3144 }
3145 }
3146
3147 return false;
3148}
3149
3150/// Helper wrapper to main isSplatValue function.
3151bool SelectionDAG::isSplatValue(SDValue V, bool AllowUndefs) const {
3152 EVT VT = V.getValueType();
3153 assert(VT.isVector() && "Vector type expected");
3154
3155 APInt UndefElts;
3156 // Since the number of lanes in a scalable vector is unknown at compile time,
3157 // we track one bit which is implicitly broadcast to all lanes. This means
3158 // that all lanes in a scalable vector are considered demanded.
3159 APInt DemandedElts
3161 return isSplatValue(V, DemandedElts, UndefElts) &&
3162 (AllowUndefs || !UndefElts);
3163}
3164
3167
3168 EVT VT = V.getValueType();
3169 unsigned Opcode = V.getOpcode();
3170 switch (Opcode) {
3171 default: {
3172 APInt UndefElts;
3173 // Since the number of lanes in a scalable vector is unknown at compile time,
3174 // we track one bit which is implicitly broadcast to all lanes. This means
3175 // that all lanes in a scalable vector are considered demanded.
3176 APInt DemandedElts
3178
3179 if (isSplatValue(V, DemandedElts, UndefElts)) {
3180 if (VT.isScalableVector()) {
3181 // DemandedElts and UndefElts are ignored for scalable vectors, since
3182 // the only supported cases are SPLAT_VECTOR nodes.
3183 SplatIdx = 0;
3184 } else {
3185 // Handle case where all demanded elements are UNDEF.
3186 if (DemandedElts.isSubsetOf(UndefElts)) {
3187 SplatIdx = 0;
3188 return getUNDEF(VT);
3189 }
3190 SplatIdx = (UndefElts & DemandedElts).countr_one();
3191 }
3192 return V;
3193 }
3194 break;
3195 }
3196 case ISD::SPLAT_VECTOR:
3197 SplatIdx = 0;
3198 return V;
3199 case ISD::VECTOR_SHUFFLE: {
3200 assert(!VT.isScalableVector());
3201 // Check if this is a shuffle node doing a splat.
3202 // TODO - remove this and rely purely on SelectionDAG::isSplatValue,
3203 // getTargetVShiftNode currently struggles without the splat source.
3204 auto *SVN = cast<ShuffleVectorSDNode>(V);
3205 if (!SVN->isSplat())
3206 break;
3207 int Idx = SVN->getSplatIndex();
3208 int NumElts = V.getValueType().getVectorNumElements();
3209 SplatIdx = Idx % NumElts;
3210 return V.getOperand(Idx / NumElts);
3211 }
3212 }
3213
3214 return SDValue();
3215}
3216
3218 int SplatIdx;
3219 if (SDValue SrcVector = getSplatSourceVector(V, SplatIdx)) {
3220 EVT SVT = SrcVector.getValueType().getScalarType();
3221 EVT LegalSVT = SVT;
3222 if (LegalTypes && !TLI->isTypeLegal(SVT)) {
3223 if (!SVT.isInteger())
3224 return SDValue();
3225 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
3226 if (LegalSVT.bitsLT(SVT))
3227 return SDValue();
3228 }
3229 return getExtractVectorElt(SDLoc(V), LegalSVT, SrcVector, SplatIdx);
3230 }
3231 return SDValue();
3232}
3233
3234std::optional<ConstantRange>
3236 unsigned Depth) const {
3237 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
3238 V.getOpcode() == ISD::SRA) &&
3239 "Unknown shift node");
3240 // Shifting more than the bitwidth is not valid.
3241 unsigned BitWidth = V.getScalarValueSizeInBits();
3242
3243 if (auto *Cst = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
3244 const APInt &ShAmt = Cst->getAPIntValue();
3245 if (ShAmt.uge(BitWidth))
3246 return std::nullopt;
3247 return ConstantRange(ShAmt);
3248 }
3249
3250 if (auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1))) {
3251 const APInt *MinAmt = nullptr, *MaxAmt = nullptr;
3252 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
3253 if (!DemandedElts[i])
3254 continue;
3255 auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i));
3256 if (!SA) {
3257 MinAmt = MaxAmt = nullptr;
3258 break;
3259 }
3260 const APInt &ShAmt = SA->getAPIntValue();
3261 if (ShAmt.uge(BitWidth))
3262 return std::nullopt;
3263 if (!MinAmt || MinAmt->ugt(ShAmt))
3264 MinAmt = &ShAmt;
3265 if (!MaxAmt || MaxAmt->ult(ShAmt))
3266 MaxAmt = &ShAmt;
3267 }
3268 assert(((!MinAmt && !MaxAmt) || (MinAmt && MaxAmt)) &&
3269 "Failed to find matching min/max shift amounts");
3270 if (MinAmt && MaxAmt)
3271 return ConstantRange(*MinAmt, *MaxAmt + 1);
3272 }
3273
3274 // Use computeKnownBits to find a hidden constant/knownbits (usually type
3275 // legalized). e.g. Hidden behind multiple bitcasts/build_vector/casts etc.
3276 KnownBits KnownAmt = computeKnownBits(V.getOperand(1), DemandedElts, Depth);
3277 if (KnownAmt.getMaxValue().ult(BitWidth))
3278 return ConstantRange::fromKnownBits(KnownAmt, /*IsSigned=*/false);
3279
3280 return std::nullopt;
3281}
3282
3283std::optional<unsigned>
3285 unsigned Depth) const {
3286 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
3287 V.getOpcode() == ISD::SRA) &&
3288 "Unknown shift node");
3289 if (std::optional<ConstantRange> AmtRange =
3290 getValidShiftAmountRange(V, DemandedElts, Depth))
3291 if (const APInt *ShAmt = AmtRange->getSingleElement())
3292 return ShAmt->getZExtValue();
3293 return std::nullopt;
3294}
3295
3296std::optional<unsigned>
3298 APInt DemandedElts = getDemandAllEltsMask(V);
3299 return getValidShiftAmount(V, DemandedElts, Depth);
3300}
3301
3302std::optional<unsigned>
3304 unsigned Depth) const {
3305 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
3306 V.getOpcode() == ISD::SRA) &&
3307 "Unknown shift node");
3308 if (std::optional<ConstantRange> AmtRange =
3309 getValidShiftAmountRange(V, DemandedElts, Depth))
3310 return AmtRange->getUnsignedMin().getZExtValue();
3311 return std::nullopt;
3312}
3313
3314std::optional<unsigned>
3316 APInt DemandedElts = getDemandAllEltsMask(V);
3317 return getValidMinimumShiftAmount(V, DemandedElts, Depth);
3318}
3319
3320std::optional<unsigned>
3322 unsigned Depth) const {
3323 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
3324 V.getOpcode() == ISD::SRA) &&
3325 "Unknown shift node");
3326 if (std::optional<ConstantRange> AmtRange =
3327 getValidShiftAmountRange(V, DemandedElts, Depth))
3328 return AmtRange->getUnsignedMax().getZExtValue();
3329 return std::nullopt;
3330}
3331
3332std::optional<unsigned>
3334 APInt DemandedElts = getDemandAllEltsMask(V);
3335 return getValidMaximumShiftAmount(V, DemandedElts, Depth);
3336}
3337
3338/// Determine which bits of Op are known to be either zero or one and return
3339/// them in Known. For vectors, the known bits are those that are shared by
3340/// every vector element.
3342 APInt DemandedElts = getDemandAllEltsMask(Op);
3343 return computeKnownBits(Op, DemandedElts, Depth);
3344}
3345
3346/// Determine which bits of Op are known to be either zero or one and return
3347/// them in Known. The DemandedElts argument allows us to only collect the known
3348/// bits that are shared by the requested vector elements.
3350 unsigned Depth) const {
3351 unsigned BitWidth = Op.getScalarValueSizeInBits();
3352
3353 KnownBits Known(BitWidth); // Don't know anything.
3354
3355 if (auto OptAPInt = Op->bitcastToAPInt()) {
3356 // We know all of the bits for a constant!
3357 APInt V = *std::move(OptAPInt);
3358
3359 // Swap the low-order and high-order double of a ppc_fp128 when casting to
3360 // i128, see #44482.
3361 //
3362 // A ppc_fp128 is two doubles, with the high-order double stored at the
3363 // lower address. Reading that as an integer therefore puts the high-order
3364 // double in the high 64 bits on big-endian targets and in the low 64 bits
3365 // on little-endian targets.
3366 //
3367 // But APFloat::bitcastToAPInt is endianness-agnostic and always places the
3368 // high-order double in the low 64 bits. Hence the two doubles must be
3369 // flipped on big-endian targets.
3370 if (getDataLayout().isBigEndian() && Op.getValueType() == MVT::ppcf128)
3371 V = V.rotl(64);
3372
3373 return KnownBits::makeConstant(V);
3374 }
3375
3376 if (Depth >= MaxRecursionDepth)
3377 return Known; // Limit search depth.
3378
3379 KnownBits Known2;
3380 unsigned NumElts = DemandedElts.getBitWidth();
3381 assert((!Op.getValueType().isScalableVector() || NumElts == 1) &&
3382 "DemandedElts for scalable vectors must be 1 to represent all lanes");
3383 assert((!Op.getValueType().isFixedLengthVector() ||
3384 NumElts == Op.getValueType().getVectorNumElements()) &&
3385 "Unexpected vector size");
3386
3387 if (!DemandedElts)
3388 return Known; // No demanded elts, better to assume we don't know anything.
3389
3390 unsigned Opcode = Op.getOpcode();
3391 switch (Opcode) {
3392 case ISD::FREEZE: {
3393 if (isGuaranteedNotToBeUndefOrPoison(Op.getOperand(0), DemandedElts,
3395 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3396 break;
3397 }
3398 case ISD::MERGE_VALUES:
3399 return computeKnownBits(Op.getOperand(Op.getResNo()), DemandedElts,
3400 Depth + 1);
3401 case ISD::SPLAT_VECTOR: {
3402 SDValue SrcOp = Op.getOperand(0);
3403 assert(SrcOp.getValueSizeInBits() >= BitWidth &&
3404 "Expected SPLAT_VECTOR implicit truncation");
3405 // Implicitly truncate the bits to match the official semantics of
3406 // SPLAT_VECTOR.
3408 break;
3409 }
3411 unsigned ScalarSize = Op.getOperand(0).getScalarValueSizeInBits();
3412 assert(ScalarSize * Op.getNumOperands() == BitWidth &&
3413 "Expected SPLAT_VECTOR_PARTS scalars to cover element width");
3414 for (auto [I, SrcOp] : enumerate(Op->ops())) {
3415 Known.insertBits(computeKnownBits(SrcOp, Depth + 1), ScalarSize * I);
3416 }
3417 break;
3418 }
3419 case ISD::STEP_VECTOR: {
3420 const APInt &Step = Op.getConstantOperandAPInt(0);
3421
3422 if (Step.isPowerOf2())
3423 Known.Zero.setLowBits(Step.logBase2());
3424
3426
3427 if (!isUIntN(BitWidth, Op.getValueType().getVectorMinNumElements()))
3428 break;
3429 const APInt MinNumElts =
3430 APInt(BitWidth, Op.getValueType().getVectorMinNumElements());
3431
3432 bool Overflow;
3433 const APInt MaxNumElts = getVScaleRange(&F, BitWidth)
3435 .umul_ov(MinNumElts, Overflow);
3436 if (Overflow)
3437 break;
3438
3439 const APInt MaxValue = (MaxNumElts - 1).umul_ov(Step, Overflow);
3440 if (Overflow)
3441 break;
3442
3443 Known.Zero.setHighBits(MaxValue.countl_zero());
3444 break;
3445 }
3446 case ISD::BUILD_VECTOR:
3447 assert(!Op.getValueType().isScalableVector());
3448 // Collect the known bits that are shared by every demanded vector element.
3449 Known.setAllConflict();
3450 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
3451 if (!DemandedElts[i])
3452 continue;
3453
3454 SDValue SrcOp = Op.getOperand(i);
3455 if (SrcOp.getOpcode() == ISD::POISON)
3456 continue;
3457
3458 Known2 = computeKnownBits(SrcOp, Depth + 1);
3459
3460 // BUILD_VECTOR can implicitly truncate sources, we must handle this.
3461 if (SrcOp.getValueSizeInBits() != BitWidth) {
3462 assert(SrcOp.getValueSizeInBits() > BitWidth &&
3463 "Expected BUILD_VECTOR implicit truncation");
3464 Known2 = Known2.trunc(BitWidth);
3465 }
3466
3467 // Known bits are the values that are shared by every demanded element.
3468 Known = Known.intersectWith(Known2);
3469
3470 // If we don't know any bits, early out.
3471 if (Known.isUnknown())
3472 break;
3473 }
3474
3475 // If every demanded element was poison, we know nothing.
3476 if (Known.hasConflict())
3477 Known.resetAll();
3478 break;
3479 case ISD::VECTOR_COMPRESS: {
3480 SDValue Vec = Op.getOperand(0);
3481 SDValue PassThru = Op.getOperand(2);
3482 Known = computeKnownBits(PassThru, DemandedElts, Depth + 1);
3483 // If we don't know any bits, early out.
3484 if (Known.isUnknown())
3485 break;
3486 Known2 = computeKnownBits(Vec, Depth + 1);
3487 Known = Known.intersectWith(Known2);
3488 break;
3489 }
3490 case ISD::VECTOR_SHUFFLE: {
3491 assert(!Op.getValueType().isScalableVector());
3492 // Collect the known bits that are shared by every vector element referenced
3493 // by the shuffle.
3494 APInt DemandedLHS, DemandedRHS;
3496 assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
3497 if (!getShuffleDemandedElts(NumElts, SVN->getMask(), DemandedElts,
3498 DemandedLHS, DemandedRHS))
3499 break;
3500
3501 // Known bits are the values that are shared by every demanded element.
3502 Known.setAllConflict();
3503 if (!!DemandedLHS) {
3504 SDValue LHS = Op.getOperand(0);
3505 Known2 = computeKnownBits(LHS, DemandedLHS, Depth + 1);
3506 Known = Known.intersectWith(Known2);
3507 }
3508 // If we don't know any bits, early out.
3509 if (Known.isUnknown())
3510 break;
3511 if (!!DemandedRHS) {
3512 SDValue RHS = Op.getOperand(1);
3513 Known2 = computeKnownBits(RHS, DemandedRHS, Depth + 1);
3514 Known = Known.intersectWith(Known2);
3515 }
3516 break;
3517 }
3518 case ISD::VSCALE: {
3520 const APInt &Multiplier = Op.getConstantOperandAPInt(0);
3522 break;
3523 }
3524 case ISD::CONCAT_VECTORS: {
3525 if (Op.getValueType().isScalableVector())
3526 break;
3527 // Split DemandedElts and test each of the demanded subvectors.
3528 Known.setAllConflict();
3529 EVT SubVectorVT = Op.getOperand(0).getValueType();
3530 unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
3531 unsigned NumSubVectors = Op.getNumOperands();
3532 for (unsigned i = 0; i != NumSubVectors; ++i) {
3533 APInt DemandedSub =
3534 DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts);
3535 if (!!DemandedSub) {
3536 SDValue Sub = Op.getOperand(i);
3537 Known2 = computeKnownBits(Sub, DemandedSub, Depth + 1);
3538 Known = Known.intersectWith(Known2);
3539 }
3540 // If we don't know any bits, early out.
3541 if (Known.isUnknown())
3542 break;
3543 }
3544 break;
3545 }
3546 case ISD::INSERT_SUBVECTOR: {
3547 if (Op.getValueType().isScalableVector())
3548 break;
3549 // Demand any elements from the subvector and the remainder from the src its
3550 // inserted into.
3551 SDValue Src = Op.getOperand(0);
3552 SDValue Sub = Op.getOperand(1);
3553 uint64_t Idx = Op.getConstantOperandVal(2);
3554 unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
3555 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
3556 APInt DemandedSrcElts = DemandedElts;
3557 DemandedSrcElts.clearBits(Idx, Idx + NumSubElts);
3558
3559 Known.setAllConflict();
3560 if (!!DemandedSubElts) {
3561 Known = computeKnownBits(Sub, DemandedSubElts, Depth + 1);
3562 if (Known.isUnknown())
3563 break; // early-out.
3564 }
3565 if (!!DemandedSrcElts) {
3566 Known2 = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
3567 Known = Known.intersectWith(Known2);
3568 }
3569 break;
3570 }
3572 // Offset the demanded elts by the subvector index.
3573 SDValue Src = Op.getOperand(0);
3574
3575 APInt DemandedSrcElts;
3576 if (Src.getValueType().isScalableVector())
3577 DemandedSrcElts = APInt(1, 1); // <=> 'demand all elements'
3578 else {
3579 uint64_t Idx = Op.getConstantOperandVal(1);
3580 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
3581 DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
3582 }
3583 Known = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
3584 break;
3585 }
3586 case ISD::SCALAR_TO_VECTOR: {
3587 if (Op.getValueType().isScalableVector())
3588 break;
3589 // We know about scalar_to_vector as much as we know about it source,
3590 // which becomes the first element of otherwise unknown vector.
3591 if (DemandedElts != 1)
3592 break;
3593
3594 SDValue N0 = Op.getOperand(0);
3595 Known = computeKnownBits(N0, Depth + 1);
3596 if (N0.getValueSizeInBits() != BitWidth)
3597 Known = Known.trunc(BitWidth);
3598
3599 break;
3600 }
3601 case ISD::BITCAST: {
3602 if (Op.getValueType().isScalableVector())
3603 break;
3604
3605 SDValue N0 = Op.getOperand(0);
3606 EVT SubVT = N0.getValueType();
3607 unsigned SubBitWidth = SubVT.getScalarSizeInBits();
3608
3609 // Ignore bitcasts from unsupported types.
3610 if (!(SubVT.isInteger() || SubVT.isFloatingPoint()))
3611 break;
3612
3613 // Fast handling of 'identity' bitcasts.
3614 if (BitWidth == SubBitWidth) {
3615 Known = computeKnownBits(N0, DemandedElts, Depth + 1);
3616 break;
3617 }
3618
3619 bool IsLE = getDataLayout().isLittleEndian();
3620
3621 // Bitcast 'small element' vector to 'large element' scalar/vector.
3622 if ((BitWidth % SubBitWidth) == 0) {
3623 assert(N0.getValueType().isVector() && "Expected bitcast from vector");
3624
3625 // Collect known bits for the (larger) output by collecting the known
3626 // bits from each set of sub elements and shift these into place.
3627 // We need to separately call computeKnownBits for each set of
3628 // sub elements as the knownbits for each is likely to be different.
3629 unsigned SubScale = BitWidth / SubBitWidth;
3630 APInt SubDemandedElts(NumElts * SubScale, 0);
3631 for (unsigned i = 0; i != NumElts; ++i)
3632 if (DemandedElts[i])
3633 SubDemandedElts.setBit(i * SubScale);
3634
3635 for (unsigned i = 0; i != SubScale; ++i) {
3636 Known2 = computeKnownBits(N0, SubDemandedElts.shl(i),
3637 Depth + 1);
3638 unsigned Shifts = IsLE ? i : SubScale - 1 - i;
3639 Known.insertBits(Known2, SubBitWidth * Shifts);
3640 }
3641 }
3642
3643 // Bitcast 'large element' scalar/vector to 'small element' vector.
3644 if ((SubBitWidth % BitWidth) == 0) {
3645 assert(Op.getValueType().isVector() && "Expected bitcast to vector");
3646
3647 // Collect known bits for the (smaller) output by collecting the known
3648 // bits from the overlapping larger input elements and extracting the
3649 // sub sections we actually care about.
3650 unsigned SubScale = SubBitWidth / BitWidth;
3651 APInt SubDemandedElts =
3652 APIntOps::ScaleBitMask(DemandedElts, NumElts / SubScale);
3653 Known2 = computeKnownBits(N0, SubDemandedElts, Depth + 1);
3654
3655 Known.setAllConflict();
3656 for (unsigned i = 0; i != NumElts; ++i)
3657 if (DemandedElts[i]) {
3658 unsigned Shifts = IsLE ? i : NumElts - 1 - i;
3659 unsigned Offset = (Shifts % SubScale) * BitWidth;
3660 Known = Known.intersectWith(Known2.extractBits(BitWidth, Offset));
3661 // If we don't know any bits, early out.
3662 if (Known.isUnknown())
3663 break;
3664 }
3665 }
3666 break;
3667 }
3668 case ISD::AND:
3669 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3670 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3671
3672 Known &= Known2;
3673 break;
3674 case ISD::OR:
3675 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3676 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3677
3678 Known |= Known2;
3679 break;
3680 case ISD::XOR:
3681 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3682 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3683
3684 Known ^= Known2;
3685 break;
3686 case ISD::MUL: {
3687 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3688 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3689 bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1);
3690 // TODO: SelfMultiply can be poison, but not undef.
3691 if (SelfMultiply)
3692 SelfMultiply &= isGuaranteedNotToBeUndefOrPoison(
3693 Op.getOperand(0), DemandedElts, UndefPoisonKind::UndefOrPoison,
3694 Depth + 1);
3695 Known = KnownBits::mul(Known, Known2, SelfMultiply);
3696
3697 // If the multiplication is known not to overflow, the product of a number
3698 // with itself is non-negative. Only do this if we didn't already computed
3699 // the opposite value for the sign bit.
3700 if (Op->getFlags().hasNoSignedWrap() &&
3701 Op.getOperand(0) == Op.getOperand(1) &&
3702 !Known.isNegative())
3703 Known.makeNonNegative();
3704 break;
3705 }
3706 case ISD::MULHU: {
3707 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3708 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3709 Known = KnownBits::mulhu(Known, Known2);
3710 break;
3711 }
3712 case ISD::MULHS: {
3713 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3714 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3715 Known = KnownBits::mulhs(Known, Known2);
3716 break;
3717 }
3718 case ISD::ABDU: {
3719 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3720 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3721 Known = KnownBits::abdu(Known, Known2);
3722 break;
3723 }
3724 case ISD::ABDS: {
3725 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3726 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3727 Known = KnownBits::abds(Known, Known2);
3728 unsigned SignBits1 =
3729 ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
3730 if (SignBits1 == 1)
3731 break;
3732 unsigned SignBits0 =
3733 ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3734 Known.Zero.setHighBits(std::min(SignBits0, SignBits1) - 1);
3735 break;
3736 }
3737 case ISD::UMUL_LOHI: {
3738 assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3739 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3740 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3741 bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1);
3742 if (Op.getResNo() == 0)
3743 Known = KnownBits::mul(Known, Known2, SelfMultiply);
3744 else
3745 Known = KnownBits::mulhu(Known, Known2);
3746 break;
3747 }
3748 case ISD::SMUL_LOHI: {
3749 assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3750 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3751 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3752 bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1);
3753 if (Op.getResNo() == 0)
3754 Known = KnownBits::mul(Known, Known2, SelfMultiply);
3755 else
3756 Known = KnownBits::mulhs(Known, Known2);
3757 break;
3758 }
3759 case ISD::AVGFLOORU: {
3760 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3761 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3762 Known = KnownBits::avgFloorU(Known, Known2);
3763 break;
3764 }
3765 case ISD::AVGCEILU: {
3766 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3767 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3768 Known = KnownBits::avgCeilU(Known, Known2);
3769 break;
3770 }
3771 case ISD::AVGFLOORS: {
3772 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3773 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3774 Known = KnownBits::avgFloorS(Known, Known2);
3775 break;
3776 }
3777 case ISD::AVGCEILS: {
3778 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3779 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3780 Known = KnownBits::avgCeilS(Known, Known2);
3781 break;
3782 }
3783 case ISD::SELECT:
3784 case ISD::VSELECT:
3785 Known = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
3786 // If we don't know any bits, early out.
3787 if (Known.isUnknown())
3788 break;
3789 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth+1);
3790
3791 // Only known if known in both the LHS and RHS.
3792 Known = Known.intersectWith(Known2);
3793 break;
3794 case ISD::SELECT_CC:
3795 Known = computeKnownBits(Op.getOperand(3), DemandedElts, Depth+1);
3796 // If we don't know any bits, early out.
3797 if (Known.isUnknown())
3798 break;
3799 Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
3800
3801 // Only known if known in both the LHS and RHS.
3802 Known = Known.intersectWith(Known2);
3803 break;
3804 case ISD::SMULO:
3805 case ISD::UMULO:
3806 if (Op.getResNo() != 1)
3807 break;
3808 // The boolean result conforms to getBooleanContents.
3809 // If we know the result of a setcc has the top bits zero, use this info.
3810 // We know that we have an integer-based boolean since these operations
3811 // are only available for integer.
3812 if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
3814 BitWidth > 1)
3815 Known.Zero.setBitsFrom(1);
3816 break;
3817 case ISD::SETCC:
3818 case ISD::SETCCCARRY:
3819 case ISD::STRICT_FSETCC:
3820 case ISD::STRICT_FSETCCS: {
3821 unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
3822 // If we know the result of a setcc has the top bits zero, use this info.
3823 if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
3825 BitWidth > 1)
3826 Known.Zero.setBitsFrom(1);
3827 break;
3828 }
3829 case ISD::SHL: {
3830 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3831 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3832
3833 bool NUW = Op->getFlags().hasNoUnsignedWrap();
3834 bool NSW = Op->getFlags().hasNoSignedWrap();
3835
3836 bool ShAmtNonZero = Known2.isNonZero();
3837
3838 Known = KnownBits::shl(Known, Known2, NUW, NSW, ShAmtNonZero);
3839
3840 // Minimum shift low bits are known zero.
3841 if (std::optional<unsigned> ShMinAmt =
3842 getValidMinimumShiftAmount(Op, DemandedElts, Depth + 1))
3843 Known.Zero.setLowBits(*ShMinAmt);
3844 break;
3845 }
3846 case ISD::SRL:
3847 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3848 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3849 Known = KnownBits::lshr(Known, Known2, /*ShAmtNonZero=*/false,
3850 Op->getFlags().hasExact());
3851
3852 // Minimum shift high bits are known zero.
3853 if (std::optional<unsigned> ShMinAmt =
3854 getValidMinimumShiftAmount(Op, DemandedElts, Depth + 1))
3855 Known.Zero.setHighBits(*ShMinAmt);
3856 break;
3857 case ISD::SRA:
3858 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3859 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3860 Known = KnownBits::ashr(Known, Known2, /*ShAmtNonZero=*/false,
3861 Op->getFlags().hasExact());
3862 break;
3863 case ISD::ROTL:
3864 case ISD::ROTR:
3865 if (ConstantSDNode *C =
3866 isConstOrConstSplat(Op.getOperand(1), DemandedElts)) {
3867 unsigned Amt = C->getAPIntValue().urem(BitWidth);
3868
3869 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3870
3871 // Canonicalize to ROTR.
3872 if (Opcode == ISD::ROTL && Amt != 0)
3873 Amt = BitWidth - Amt;
3874
3875 Known.Zero = Known.Zero.rotr(Amt);
3876 Known.One = Known.One.rotr(Amt);
3877 }
3878 break;
3879 case ISD::FSHL:
3880 case ISD::FSHR:
3881 if (ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(2), DemandedElts)) {
3882 unsigned Amt = C->getAPIntValue().urem(BitWidth);
3883
3884 // For fshl, 0-shift returns the 1st arg.
3885 // For fshr, 0-shift returns the 2nd arg.
3886 if (Amt == 0) {
3887 Known = computeKnownBits(Op.getOperand(Opcode == ISD::FSHL ? 0 : 1),
3888 DemandedElts, Depth + 1);
3889 break;
3890 }
3891
3892 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
3893 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
3894 const APInt ShAmt(BitWidth, Amt);
3895 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3896 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3897 Known = Opcode == ISD::FSHL ? KnownBits::fshl(Known, Known2, ShAmt)
3898 : KnownBits::fshr(Known, Known2, ShAmt);
3899 }
3900 break;
3901 case ISD::SHL_PARTS:
3902 case ISD::SRA_PARTS:
3903 case ISD::SRL_PARTS: {
3904 assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3905
3906 // Collect lo/hi source values and concatenate.
3907 unsigned LoBits = Op.getOperand(0).getScalarValueSizeInBits();
3908 unsigned HiBits = Op.getOperand(1).getScalarValueSizeInBits();
3909 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3910 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3911 Known = Known2.concat(Known);
3912
3913 // Collect shift amount.
3914 Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1);
3915
3916 if (Opcode == ISD::SHL_PARTS)
3917 Known = KnownBits::shl(Known, Known2);
3918 else if (Opcode == ISD::SRA_PARTS)
3919 Known = KnownBits::ashr(Known, Known2);
3920 else // if (Opcode == ISD::SRL_PARTS)
3921 Known = KnownBits::lshr(Known, Known2);
3922
3923 // TODO: Minimum shift low/high bits are known zero.
3924
3925 if (Op.getResNo() == 0)
3926 Known = Known.extractBits(LoBits, 0);
3927 else
3928 Known = Known.extractBits(HiBits, LoBits);
3929 break;
3930 }
3932 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3933 EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3934 Known = Known.sextInReg(EVT.getScalarSizeInBits());
3935 break;
3936 }
3937 case ISD::CTTZ:
3938 case ISD::CTTZ_ZERO_POISON: {
3939 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3940 // If we have a known 1, its position is our upper bound.
3941 unsigned PossibleTZ = Known2.countMaxTrailingZeros();
3942 unsigned LowBits = llvm::bit_width(PossibleTZ);
3943 Known.Zero.setBitsFrom(LowBits);
3944 break;
3945 }
3946 case ISD::CTLZ:
3947 case ISD::CTLZ_ZERO_POISON: {
3948 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3949 // If we have a known 1, its position is our upper bound.
3950 unsigned PossibleLZ = Known2.countMaxLeadingZeros();
3951 unsigned LowBits = llvm::bit_width(PossibleLZ);
3952 Known.Zero.setBitsFrom(LowBits);
3953 break;
3954 }
3955 case ISD::CTLS: {
3956 unsigned MinRedundantSignBits =
3957 ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1) - 1;
3958 ConstantRange Range(APInt(BitWidth, MinRedundantSignBits),
3960 Known = Range.toKnownBits();
3961 break;
3962 }
3963 case ISD::CTPOP: {
3964 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3965 // If we know some of the bits are zero, they can't be one.
3966 unsigned PossibleOnes = Known2.countMaxPopulation();
3967 Known.Zero.setBitsFrom(llvm::bit_width(PossibleOnes));
3968 break;
3969 }
3970 case ISD::PARITY: {
3971 // Parity returns 0 everywhere but the LSB.
3972 Known.Zero.setBitsFrom(1);
3973 break;
3974 }
3975 case ISD::PDEP: {
3976 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3977 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3978 Known = KnownBits::pdep(Known2, Known);
3979 break;
3980 }
3981 case ISD::PEXT: {
3982 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3983 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3984 Known = KnownBits::pext(Known2, Known);
3985 break;
3986 }
3987 case ISD::CLMUL: {
3988 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3989 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3990 Known = KnownBits::clmul(Known, Known2);
3991 break;
3992 }
3993 case ISD::MGATHER:
3994 case ISD::MLOAD: {
3995 ISD::LoadExtType ETy =
3996 (Opcode == ISD::MGATHER)
3997 ? cast<MaskedGatherSDNode>(Op)->getExtensionType()
3998 : cast<MaskedLoadSDNode>(Op)->getExtensionType();
3999 if (ETy == ISD::ZEXTLOAD) {
4000 EVT MemVT = cast<MemSDNode>(Op)->getMemoryVT();
4001 KnownBits Known0(MemVT.getScalarSizeInBits());
4002 return Known0.zext(BitWidth);
4003 }
4004 break;
4005 }
4006 case ISD::LOAD: {
4008 const Constant *Cst = TLI->getTargetConstantFromLoad(LD);
4009 if (ISD::isNON_EXTLoad(LD) && Cst) {
4010 // Determine any common known bits from the loaded constant pool value.
4011 Type *CstTy = Cst->getType();
4012 if ((NumElts * BitWidth) == CstTy->getPrimitiveSizeInBits() &&
4013 !Op.getValueType().isScalableVector()) {
4014 // If its a vector splat, then we can (quickly) reuse the scalar path.
4015 // NOTE: We assume all elements match and none are UNDEF.
4016 if (CstTy->isVectorTy()) {
4017 if (const Constant *Splat = Cst->getSplatValue()) {
4018 Cst = Splat;
4019 CstTy = Cst->getType();
4020 }
4021 }
4022 // TODO - do we need to handle different bitwidths?
4023 if (CstTy->isVectorTy() && BitWidth == CstTy->getScalarSizeInBits()) {
4024 // Iterate across all vector elements finding common known bits.
4025 Known.setAllConflict();
4026 for (unsigned i = 0; i != NumElts; ++i) {
4027 if (!DemandedElts[i])
4028 continue;
4029 if (Constant *Elt = Cst->getAggregateElement(i)) {
4030 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
4031 const APInt &Value = CInt->getValue();
4032 Known.One &= Value;
4033 Known.Zero &= ~Value;
4034 continue;
4035 }
4036 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
4037 APInt Value = CFP->getValueAPF().bitcastToAPInt();
4038 Known.One &= Value;
4039 Known.Zero &= ~Value;
4040 continue;
4041 }
4042 }
4043 Known.One.clearAllBits();
4044 Known.Zero.clearAllBits();
4045 break;
4046 }
4047 } else if (BitWidth == CstTy->getPrimitiveSizeInBits()) {
4048 if (auto *CInt = dyn_cast<ConstantInt>(Cst)) {
4049 Known = KnownBits::makeConstant(CInt->getValue());
4050 } else if (auto *CFP = dyn_cast<ConstantFP>(Cst)) {
4051 Known =
4052 KnownBits::makeConstant(CFP->getValueAPF().bitcastToAPInt());
4053 }
4054 }
4055 }
4056 } else if (Op.getResNo() == 0) {
4057 unsigned ScalarMemorySize = LD->getMemoryVT().getScalarSizeInBits();
4058 KnownBits KnownScalarMemory(ScalarMemorySize);
4059 if (const MDNode *MD = LD->getRanges())
4060 computeKnownBitsFromRangeMetadata(*MD, KnownScalarMemory);
4061
4062 // Extend the Known bits from memory to the size of the scalar result.
4063 if (ISD::isZEXTLoad(Op.getNode()))
4064 Known = KnownScalarMemory.zext(BitWidth);
4065 else if (ISD::isSEXTLoad(Op.getNode()))
4066 Known = KnownScalarMemory.sext(BitWidth);
4067 else if (ISD::isEXTLoad(Op.getNode()))
4068 Known = KnownScalarMemory.anyext(BitWidth);
4069 else
4070 Known = KnownScalarMemory;
4071 assert(Known.getBitWidth() == BitWidth);
4072 return Known;
4073 }
4074 break;
4075 }
4077 if (Op.getValueType().isScalableVector())
4078 break;
4079 EVT InVT = Op.getOperand(0).getValueType();
4080 APInt InDemandedElts = DemandedElts.zext(InVT.getVectorNumElements());
4081 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
4082 Known = Known.zext(BitWidth);
4083 break;
4084 }
4085 case ISD::ZERO_EXTEND: {
4086 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4087 Known = Known.zext(BitWidth);
4088 break;
4089 }
4091 if (Op.getValueType().isScalableVector())
4092 break;
4093 EVT InVT = Op.getOperand(0).getValueType();
4094 APInt InDemandedElts = DemandedElts.zext(InVT.getVectorNumElements());
4095 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
4096 // If the sign bit is known to be zero or one, then sext will extend
4097 // it to the top bits, else it will just zext.
4098 Known = Known.sext(BitWidth);
4099 break;
4100 }
4101 case ISD::SIGN_EXTEND: {
4102 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4103 // If the sign bit is known to be zero or one, then sext will extend
4104 // it to the top bits, else it will just zext.
4105 Known = Known.sext(BitWidth);
4106 break;
4107 }
4109 if (Op.getValueType().isScalableVector())
4110 break;
4111 EVT InVT = Op.getOperand(0).getValueType();
4112 APInt InDemandedElts = DemandedElts.zext(InVT.getVectorNumElements());
4113 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
4114 Known = Known.anyext(BitWidth);
4115 break;
4116 }
4117 case ISD::ANY_EXTEND: {
4118 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4119 Known = Known.anyext(BitWidth);
4120 break;
4121 }
4122 case ISD::TRUNCATE: {
4123 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4124 Known = Known.trunc(BitWidth);
4125 break;
4126 }
4127 case ISD::TRUNCATE_SSAT_S: {
4128 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4129 Known = Known.truncSSat(BitWidth);
4130 break;
4131 }
4132 case ISD::TRUNCATE_SSAT_U: {
4133 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4134 Known = Known.truncSSatU(BitWidth);
4135 break;
4136 }
4137 case ISD::TRUNCATE_USAT_U: {
4138 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4139 Known = Known.truncUSat(BitWidth);
4140 break;
4141 }
4142 case ISD::AssertZext: {
4143 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
4145 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4146 Known.Zero |= (~InMask);
4147 Known.One &= (~Known.Zero);
4148 break;
4149 }
4150 case ISD::AssertAlign: {
4151 unsigned LogOfAlign = Log2(cast<AssertAlignSDNode>(Op)->getAlign());
4152 assert(LogOfAlign != 0);
4153
4154 // TODO: Should use maximum with source
4155 // If a node is guaranteed to be aligned, set low zero bits accordingly as
4156 // well as clearing one bits.
4157 Known.Zero.setLowBits(LogOfAlign);
4158 Known.One.clearLowBits(LogOfAlign);
4159 break;
4160 }
4161 case ISD::AssertNoFPClass: {
4162 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4163
4164 FPClassTest NoFPClass =
4165 static_cast<FPClassTest>(Op.getConstantOperandVal(1));
4166 const FPClassTest NegativeTestMask = fcNan | fcNegative;
4167 if ((NoFPClass & NegativeTestMask) == NegativeTestMask) {
4168 // Cannot be negative.
4169 Known.makeNonNegative();
4170 }
4171
4172 const FPClassTest PositiveTestMask = fcNan | fcPositive;
4173 if ((NoFPClass & PositiveTestMask) == PositiveTestMask) {
4174 // Cannot be positive.
4175 Known.makeNegative();
4176 }
4177
4178 break;
4179 }
4180 case ISD::FABS:
4181 // fabs clears the sign bit
4182 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4183 Known.Zero.setSignBit();
4184 Known.One.clearSignBit();
4185 break;
4186 case ISD::FGETSIGN:
4187 // All bits are zero except the low bit.
4188 Known.Zero.setBitsFrom(1);
4189 break;
4190 case ISD::ADD: {
4191 SDNodeFlags Flags = Op.getNode()->getFlags();
4192 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4193 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4194 bool SelfAdd = Op.getOperand(0) == Op.getOperand(1) &&
4196 Op.getOperand(0), DemandedElts,
4198 Known = KnownBits::add(Known, Known2, Flags.hasNoSignedWrap(),
4199 Flags.hasNoUnsignedWrap(), SelfAdd);
4200 break;
4201 }
4202 case ISD::SUB: {
4203 SDNodeFlags Flags = Op.getNode()->getFlags();
4204 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4205 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4206 Known = KnownBits::sub(Known, Known2, Flags.hasNoSignedWrap(),
4207 Flags.hasNoUnsignedWrap());
4208 break;
4209 }
4210 case ISD::USUBO:
4211 case ISD::SSUBO:
4212 case ISD::USUBO_CARRY:
4213 case ISD::SSUBO_CARRY:
4214 if (Op.getResNo() == 1) {
4215 // If we know the result of a setcc has the top bits zero, use this info.
4216 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
4218 BitWidth > 1)
4219 Known.Zero.setBitsFrom(1);
4220 break;
4221 }
4222 [[fallthrough]];
4223 case ISD::SUBC: {
4224 assert(Op.getResNo() == 0 &&
4225 "We only compute knownbits for the difference here.");
4226
4227 // With USUBO_CARRY and SSUBO_CARRY a borrow bit may be added in.
4228 KnownBits Borrow(1);
4229 if (Opcode == ISD::USUBO_CARRY || Opcode == ISD::SSUBO_CARRY) {
4230 Borrow = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1);
4231 // Borrow has bit width 1
4232 Borrow = Borrow.trunc(1);
4233 } else {
4234 Borrow.setAllZero();
4235 }
4236
4237 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4238 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4239 Known = KnownBits::computeForSubBorrow(Known, Known2, Borrow);
4240 break;
4241 }
4242 case ISD::UADDO:
4243 case ISD::SADDO:
4244 case ISD::UADDO_CARRY:
4245 case ISD::SADDO_CARRY:
4246 if (Op.getResNo() == 1) {
4247 // If we know the result of a setcc has the top bits zero, use this info.
4248 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
4250 BitWidth > 1)
4251 Known.Zero.setBitsFrom(1);
4252 break;
4253 }
4254 [[fallthrough]];
4255 case ISD::ADDC:
4256 case ISD::ADDE: {
4257 assert(Op.getResNo() == 0 && "We only compute knownbits for the sum here.");
4258
4259 // With ADDE and UADDO_CARRY, a carry bit may be added in.
4260 KnownBits Carry(1);
4261 if (Opcode == ISD::ADDE)
4262 // Can't track carry from glue, set carry to unknown.
4263 Carry.resetAll();
4264 else if (Opcode == ISD::UADDO_CARRY || Opcode == ISD::SADDO_CARRY) {
4265 Carry = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1);
4266 // Carry has bit width 1
4267 Carry = Carry.trunc(1);
4268 } else {
4269 Carry.setAllZero();
4270 }
4271
4272 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4273 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4274 Known = KnownBits::computeForAddCarry(Known, Known2, Carry);
4275 break;
4276 }
4277 case ISD::UDIV: {
4278 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4279 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4280 Known = KnownBits::udiv(Known, Known2, Op->getFlags().hasExact());
4281 break;
4282 }
4283 case ISD::SDIV: {
4284 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4285 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4286 Known = KnownBits::sdiv(Known, Known2, Op->getFlags().hasExact());
4287 break;
4288 }
4289 case ISD::SREM: {
4290 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4291 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4292 Known = KnownBits::srem(Known, Known2);
4293 break;
4294 }
4295 case ISD::UREM: {
4296 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4297 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4298 Known = KnownBits::urem(Known, Known2);
4299 break;
4300 }
4301 case ISD::EXTRACT_ELEMENT: {
4302 Known = computeKnownBits(Op.getOperand(0), Depth+1);
4303 const unsigned Index = Op.getConstantOperandVal(1);
4304 const unsigned EltBitWidth = Op.getValueSizeInBits();
4305
4306 Known = Known.extractBits(EltBitWidth, Index * EltBitWidth);
4307 break;
4308 }
4310 SDValue InVec = Op.getOperand(0);
4311 SDValue EltNo = Op.getOperand(1);
4312 EVT VecVT = InVec.getValueType();
4313 // computeKnownBits not yet implemented for scalable vectors.
4314 if (VecVT.isScalableVector())
4315 break;
4316 const unsigned EltBitWidth = VecVT.getScalarSizeInBits();
4317 const unsigned NumSrcElts = VecVT.getVectorNumElements();
4318
4319 // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know
4320 // anything about the extended bits.
4321 if (BitWidth > EltBitWidth)
4322 Known = Known.trunc(EltBitWidth);
4323
4324 // If we know the element index, just demand that vector element, else for
4325 // an unknown element index, ignore DemandedElts and demand them all.
4326 APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
4327 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
4328 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
4329 DemandedSrcElts =
4330 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
4331
4332 Known = computeKnownBits(InVec, DemandedSrcElts, Depth + 1);
4333 if (BitWidth > EltBitWidth)
4334 Known = Known.anyext(BitWidth);
4335 break;
4336 }
4337 case ISD::BUILD_PAIR: {
4338 // Operand 0 is the low half and operand 1 the high half,
4339 // KnownBits::concat places its argument in the low bits.
4340 Known = computeKnownBits(Op.getOperand(0), Depth + 1);
4341 Known2 = computeKnownBits(Op.getOperand(1), Depth + 1);
4342 Known = Known2.concat(Known);
4343 break;
4344 }
4346 if (Op.getValueType().isScalableVector())
4347 break;
4348
4349 // If we know the element index, split the demand between the
4350 // source vector and the inserted element, otherwise assume we need
4351 // the original demanded vector elements and the value.
4352 SDValue InVec = Op.getOperand(0);
4353 SDValue InVal = Op.getOperand(1);
4354 SDValue EltNo = Op.getOperand(2);
4355 bool DemandedVal = true;
4356 APInt DemandedVecElts = DemandedElts;
4357 auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
4358 if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
4359 unsigned EltIdx = CEltNo->getZExtValue();
4360 DemandedVal = !!DemandedElts[EltIdx];
4361 DemandedVecElts.clearBit(EltIdx);
4362 }
4363 Known.setAllConflict();
4364 if (DemandedVal) {
4365 Known2 = computeKnownBits(InVal, Depth + 1);
4366 Known = Known.intersectWith(Known2.zextOrTrunc(BitWidth));
4367 }
4368 if (!!DemandedVecElts) {
4369 Known2 = computeKnownBits(InVec, DemandedVecElts, Depth + 1);
4370 Known = Known.intersectWith(Known2);
4371 }
4372 break;
4373 }
4374 case ISD::BITREVERSE: {
4375 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4376 Known = Known2.reverseBits();
4377 break;
4378 }
4379 case ISD::BSWAP: {
4380 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4381 Known = Known2.byteSwap();
4382 break;
4383 }
4384 case ISD::ABS:
4385 case ISD::ABS_MIN_POISON: {
4386 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4387 Known = Known2.abs();
4388 Known.Zero.setHighBits(
4389 ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1) - 1);
4390 break;
4391 }
4392 case ISD::USUBSAT: {
4393 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4394 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4395 Known = KnownBits::usub_sat(Known, Known2);
4396 break;
4397 }
4398 case ISD::UMIN: {
4399 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4400 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4401 Known = KnownBits::umin(Known, Known2);
4402 break;
4403 }
4404 case ISD::UMAX: {
4405 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4406 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4407 Known = KnownBits::umax(Known, Known2);
4408 break;
4409 }
4410 case ISD::SMIN:
4411 case ISD::SMAX: {
4412 // If we have a clamp pattern, we know that the number of sign bits will be
4413 // the minimum of the clamp min/max range.
4414 bool IsMax = (Opcode == ISD::SMAX);
4415 ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
4416 if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
4417 if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
4418 CstHigh =
4419 isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
4420 if (CstLow && CstHigh) {
4421 if (!IsMax)
4422 std::swap(CstLow, CstHigh);
4423
4424 const APInt &ValueLow = CstLow->getAPIntValue();
4425 const APInt &ValueHigh = CstHigh->getAPIntValue();
4426 if (ValueLow.sle(ValueHigh)) {
4427 unsigned LowSignBits = ValueLow.getNumSignBits();
4428 unsigned HighSignBits = ValueHigh.getNumSignBits();
4429 unsigned MinSignBits = std::min(LowSignBits, HighSignBits);
4430 if (ValueLow.isNegative() && ValueHigh.isNegative()) {
4431 Known.One.setHighBits(MinSignBits);
4432 break;
4433 }
4434 if (ValueLow.isNonNegative() && ValueHigh.isNonNegative()) {
4435 Known.Zero.setHighBits(MinSignBits);
4436 break;
4437 }
4438 }
4439 }
4440
4441 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4442 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4443 if (IsMax)
4444 Known = KnownBits::smax(Known, Known2);
4445 else
4446 Known = KnownBits::smin(Known, Known2);
4447
4448 // For SMAX, if CstLow is non-negative we know the result will be
4449 // non-negative and thus all sign bits are 0.
4450 // TODO: There's an equivalent of this for smin with negative constant for
4451 // known ones.
4452 if (IsMax && CstLow) {
4453 const APInt &ValueLow = CstLow->getAPIntValue();
4454 if (ValueLow.isNonNegative()) {
4455 unsigned SignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
4456 Known.Zero.setHighBits(std::min(SignBits, ValueLow.getNumSignBits()));
4457 }
4458 }
4459
4460 break;
4461 }
4462 case ISD::UINT_TO_FP: {
4463 Known.makeNonNegative();
4464 break;
4465 }
4466 case ISD::SINT_TO_FP: {
4467 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4468 if (Known2.isNonNegative())
4469 Known.makeNonNegative();
4470 else if (Known2.isNegative())
4471 Known.makeNegative();
4472 break;
4473 }
4474 case ISD::FP_TO_UINT_SAT: {
4475 // FP_TO_UINT_SAT produces an unsigned value that fits in the saturating VT.
4476 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
4478 break;
4479 }
4480 case ISD::ATOMIC_LOAD: {
4481 // If we are looking at the loaded value.
4482 if (Op.getResNo() == 0) {
4483 auto *AT = cast<AtomicSDNode>(Op);
4484 unsigned ScalarMemorySize = AT->getMemoryVT().getScalarSizeInBits();
4485 KnownBits KnownScalarMemory(ScalarMemorySize);
4486 if (const MDNode *MD = AT->getRanges())
4487 computeKnownBitsFromRangeMetadata(*MD, KnownScalarMemory);
4488
4489 switch (AT->getExtensionType()) {
4490 case ISD::ZEXTLOAD:
4491 Known = KnownScalarMemory.zext(BitWidth);
4492 break;
4493 case ISD::SEXTLOAD:
4494 Known = KnownScalarMemory.sext(BitWidth);
4495 break;
4496 case ISD::EXTLOAD:
4497 switch (TLI->getExtendForAtomicOps()) {
4498 case ISD::ZERO_EXTEND:
4499 Known = KnownScalarMemory.zext(BitWidth);
4500 break;
4501 case ISD::SIGN_EXTEND:
4502 Known = KnownScalarMemory.sext(BitWidth);
4503 break;
4504 default:
4505 Known = KnownScalarMemory.anyext(BitWidth);
4506 break;
4507 }
4508 break;
4509 case ISD::NON_EXTLOAD:
4510 Known = KnownScalarMemory;
4511 break;
4512 }
4513 assert(Known.getBitWidth() == BitWidth);
4514 }
4515 break;
4516 }
4518 if (Op.getResNo() == 1) {
4519 // The boolean result conforms to getBooleanContents.
4520 // If we know the result of a setcc has the top bits zero, use this info.
4521 // We know that we have an integer-based boolean since these operations
4522 // are only available for integer.
4523 if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
4525 BitWidth > 1)
4526 Known.Zero.setBitsFrom(1);
4527 break;
4528 }
4529 [[fallthrough]];
4531 case ISD::ATOMIC_SWAP:
4542 case ISD::ATOMIC_LOAD_UMAX: {
4543 // If we are looking at the loaded value.
4544 if (Op.getResNo() == 0) {
4545 auto *AT = cast<AtomicSDNode>(Op);
4546 unsigned MemBits = AT->getMemoryVT().getScalarSizeInBits();
4547
4548 if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND)
4549 Known.Zero.setBitsFrom(MemBits);
4550 }
4551 break;
4552 }
4553 case ISD::FrameIndex:
4554 case ISD::TargetFrameIndex: {
4555 const MachineFunction &MF = getMachineFunction();
4556 int FrameIdx = cast<FrameIndexSDNode>(Op)->getIndex();
4557 TLI->computeKnownBitsForStackObjectPointer(
4558 Known, MF, MF.getFrameInfo().getObjectAlign(FrameIdx));
4559 break;
4560 }
4561 case ISD::VP_LOAD_FF: {
4562 if (Op.getResNo() != 1)
4563 break;
4564 // The second result of vp.load.ff is an unsigned value that is less than or
4565 // equal to the EVL operand.
4566 KnownBits VLKB =
4567 computeKnownBits(Op.getOperand(3), DemandedElts, Depth + 1);
4568 // The new VL is also bounded by the largest vector length.
4569 EVT ResVT = Op->getValueType(0);
4570 auto ResKB = KnownBits::makeConstant(
4572 if (ResVT.isScalableVector()) {
4574 ResKB = KnownBits::mul(getVScaleRange(&F, BitWidth).toKnownBits(), ResKB);
4575 }
4576 Known.Zero.setHighBits(KnownBits::umin(VLKB, ResKB).countMinLeadingZeros());
4577 break;
4578 }
4579
4580 default:
4581 if (Opcode < ISD::BUILTIN_OP_END)
4582 break;
4583 [[fallthrough]];
4587 // Allow the target to implement this method for its nodes.
4588 TLI->computeKnownBitsForTargetNode(Op, Known, DemandedElts, *this, Depth);
4589 break;
4590 }
4591
4592 return Known;
4593}
4594
4595/// Convert ConstantRange OverflowResult into SelectionDAG::OverflowKind.
4608
4611 // X + 0 never overflow
4612 if (isNullConstant(N1))
4613 return OFK_Never;
4614
4615 // If both operands each have at least two sign bits, the addition
4616 // cannot overflow.
4617 if (ComputeNumSignBits(N0) > 1 && ComputeNumSignBits(N1) > 1)
4618 return OFK_Never;
4619
4620 // TODO: Add ConstantRange::signedAddMayOverflow handling.
4621 return OFK_Sometime;
4622}
4623
4626 // X + 0 never overflow
4627 if (isNullConstant(N1))
4628 return OFK_Never;
4629
4630 // mulhi + 1 never overflow
4631 KnownBits N1Known = computeKnownBits(N1);
4632 if (N0.getOpcode() == ISD::UMUL_LOHI && N0.getResNo() == 1 &&
4633 N1Known.getMaxValue().ult(2))
4634 return OFK_Never;
4635
4636 KnownBits N0Known = computeKnownBits(N0);
4637 if (N1.getOpcode() == ISD::UMUL_LOHI && N1.getResNo() == 1 &&
4638 N0Known.getMaxValue().ult(2))
4639 return OFK_Never;
4640
4641 // Fallback to ConstantRange::unsignedAddMayOverflow handling.
4642 ConstantRange N0Range = ConstantRange::fromKnownBits(N0Known, false);
4643 ConstantRange N1Range = ConstantRange::fromKnownBits(N1Known, false);
4644 return mapOverflowResult(N0Range.unsignedAddMayOverflow(N1Range));
4645}
4646
4649 // X - 0 never overflow
4650 if (isNullConstant(N1))
4651 return OFK_Never;
4652
4653 // If both operands each have at least two sign bits, the subtraction
4654 // cannot overflow.
4655 if (ComputeNumSignBits(N0) > 1 && ComputeNumSignBits(N1) > 1)
4656 return OFK_Never;
4657
4658 KnownBits N0Known = computeKnownBits(N0);
4659 KnownBits N1Known = computeKnownBits(N1);
4660 ConstantRange N0Range = ConstantRange::fromKnownBits(N0Known, true);
4661 ConstantRange N1Range = ConstantRange::fromKnownBits(N1Known, true);
4662 return mapOverflowResult(N0Range.signedSubMayOverflow(N1Range));
4663}
4664
4667 // X - 0 never overflow
4668 if (isNullConstant(N1))
4669 return OFK_Never;
4670
4671 ConstantRange N0Range =
4672 computeConstantRangeIncludingKnownBits(N0, /*ForSigned=*/false);
4673 ConstantRange N1Range =
4674 computeConstantRangeIncludingKnownBits(N1, /*ForSigned=*/false);
4675 return mapOverflowResult(N0Range.unsignedSubMayOverflow(N1Range));
4676}
4677
4680 // X * 0 and X * 1 never overflow.
4681 if (isNullConstant(N1) || isOneConstant(N1))
4682 return OFK_Never;
4683
4686 return mapOverflowResult(N0Range.unsignedMulMayOverflow(N1Range));
4687}
4688
4691 // X * 0 and X * 1 never overflow.
4692 if (isNullConstant(N1) || isOneConstant(N1))
4693 return OFK_Never;
4694
4695 // Get the size of the result.
4696 unsigned BitWidth = N0.getScalarValueSizeInBits();
4697
4698 // Sum of the sign bits.
4699 unsigned SignBits = ComputeNumSignBits(N0) + ComputeNumSignBits(N1);
4700
4701 // If we have enough sign bits, then there's no overflow.
4702 if (SignBits > BitWidth + 1)
4703 return OFK_Never;
4704
4705 if (SignBits == BitWidth + 1) {
4706 // The overflow occurs when the true multiplication of the
4707 // the operands is the minimum negative number.
4708 KnownBits N0Known = computeKnownBits(N0);
4709 KnownBits N1Known = computeKnownBits(N1);
4710 // If one of the operands is non-negative, then there's no
4711 // overflow.
4712 if (N0Known.isNonNegative() || N1Known.isNonNegative())
4713 return OFK_Never;
4714 }
4715
4716 return OFK_Sometime;
4717}
4718
4720 unsigned Depth) const {
4721 APInt DemandedElts = getDemandAllEltsMask(Op);
4722 return computeConstantRange(Op, DemandedElts, ForSigned, Depth);
4723}
4724
4726 const APInt &DemandedElts,
4727 bool ForSigned,
4728 unsigned Depth) const {
4729 EVT VT = Op.getValueType();
4730 unsigned BitWidth = VT.getScalarSizeInBits();
4731
4732 if (Depth >= MaxRecursionDepth)
4733 return ConstantRange::getFull(BitWidth);
4734
4735 if (ConstantSDNode *C = isConstOrConstSplat(Op, DemandedElts))
4736 return ConstantRange(C->getAPIntValue());
4737
4738 unsigned Opcode = Op.getOpcode();
4739 switch (Opcode) {
4740 case ISD::VSCALE: {
4742 const APInt &Multiplier = Op.getConstantOperandAPInt(0);
4743 return getVScaleRange(&F, BitWidth).multiply(Multiplier);
4744 }
4745 default:
4746 break;
4747 }
4748
4749 return ConstantRange::getFull(BitWidth);
4750}
4751
4754 unsigned Depth) const {
4755 APInt DemandedElts = getDemandAllEltsMask(Op);
4756 return computeConstantRangeIncludingKnownBits(Op, DemandedElts, ForSigned,
4757 Depth);
4758}
4759
4761 SDValue Op, const APInt &DemandedElts, bool ForSigned,
4762 unsigned Depth) const {
4763 KnownBits Known = computeKnownBits(Op, DemandedElts, Depth);
4765 ConstantRange CR2 = computeConstantRange(Op, DemandedElts, ForSigned, Depth);
4768 return CR1.intersectWith(CR2, RangeType);
4769}
4770
4772 unsigned Depth) const {
4773 APInt DemandedElts = getDemandAllEltsMask(Val);
4774 return isKnownToBeAPowerOfTwo(Val, DemandedElts, OrZero, Depth);
4775}
4776
4778 const APInt &DemandedElts,
4779 bool OrZero, unsigned Depth) const {
4780 if (Depth >= MaxRecursionDepth)
4781 return false; // Limit search depth.
4782
4783 EVT OpVT = Val.getValueType();
4784 unsigned BitWidth = OpVT.getScalarSizeInBits();
4785 [[maybe_unused]] unsigned NumElts = DemandedElts.getBitWidth();
4786 assert((!OpVT.isScalableVector() || NumElts == 1) &&
4787 "DemandedElts for scalable vectors must be 1 to represent all lanes");
4788 assert(
4789 (!OpVT.isFixedLengthVector() || NumElts == OpVT.getVectorNumElements()) &&
4790 "Unexpected vector size");
4791
4792 auto IsPowerOfTwoOrZero = [BitWidth, OrZero](const ConstantSDNode *C) {
4793 APInt V = C->getAPIntValue().zextOrTrunc(BitWidth);
4794 return (OrZero && V.isZero()) || V.isPowerOf2();
4795 };
4796
4797 // Is the constant a known power of 2 or zero?
4798 if (ISD::matchUnaryPredicate(Val, DemandedElts, IsPowerOfTwoOrZero,
4799 /*AllowUndefs=*/false, /*AllowTruncation=*/true))
4800 return true;
4801
4802 switch (Val.getOpcode()) {
4804 SDValue InVec = Val.getOperand(0);
4805 SDValue EltNo = Val.getOperand(1);
4806 EVT VecVT = InVec.getValueType();
4807
4808 // Skip scalable vectors or implicit extensions.
4809 if (VecVT.isScalableVector() ||
4810 OpVT.getScalarSizeInBits() != VecVT.getScalarSizeInBits())
4811 break;
4812
4813 // If we know the element index, just demand that vector element, else for
4814 // an unknown element index, ignore DemandedElts and demand them all.
4815 const unsigned NumSrcElts = VecVT.getVectorNumElements();
4816 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
4817 APInt DemandedSrcElts =
4818 ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts)
4819 ? APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue())
4820 : APInt::getAllOnes(NumSrcElts);
4821 return isKnownToBeAPowerOfTwo(InVec, DemandedSrcElts, OrZero, Depth + 1);
4822 }
4823
4824 case ISD::AND: {
4825 // Looking for `x & -x` pattern:
4826 // If x == 0:
4827 // x & -x -> 0
4828 // If x != 0:
4829 // x & -x -> non-zero pow2
4830 // so if we find the pattern return whether we know `x` is non-zero.
4831 SDValue X, Z;
4832 if (sd_match(Val, m_And(m_Value(X), m_Neg(m_Deferred(X)))) ||
4833 (sd_match(Val, m_And(m_Value(X), m_Sub(m_Value(Z), m_Deferred(X)))) &&
4834 MaskedVectorIsZero(Z, DemandedElts, Depth + 1)))
4835 return OrZero || isKnownNeverZero(X, DemandedElts, Depth);
4836 break;
4837 }
4838
4839 case ISD::SHL: {
4840 // A left-shift of a constant one will have exactly one bit set because
4841 // shifting the bit off the end is undefined.
4842 auto *C = isConstOrConstSplat(Val.getOperand(0), DemandedElts);
4843 if (C && C->getAPIntValue() == 1)
4844 return true;
4845 return (OrZero || isKnownNeverZero(Val, DemandedElts, Depth)) &&
4846 isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedElts, OrZero,
4847 Depth + 1);
4848 }
4849
4850 case ISD::SRL: {
4851 // A logical right-shift of a constant sign-bit will have exactly
4852 // one bit set.
4853 auto *C = isConstOrConstSplat(Val.getOperand(0), DemandedElts);
4854 if (C && C->getAPIntValue().isSignMask())
4855 return true;
4856 return (OrZero || isKnownNeverZero(Val, DemandedElts, Depth)) &&
4857 isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedElts, OrZero,
4858 Depth + 1);
4859 }
4860
4861 case ISD::TRUNCATE:
4862 return (OrZero || isKnownNeverZero(Val, DemandedElts, Depth)) &&
4863 isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedElts, OrZero,
4864 Depth + 1);
4865
4866 case ISD::ROTL:
4867 case ISD::ROTR:
4868 return isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedElts, OrZero,
4869 Depth + 1);
4870 case ISD::BSWAP:
4871 case ISD::BITREVERSE:
4872 return isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedElts, OrZero,
4873 Depth + 1);
4874
4875 case ISD::SMIN:
4876 case ISD::SMAX:
4877 case ISD::UMIN:
4878 case ISD::UMAX:
4879 return isKnownToBeAPowerOfTwo(Val.getOperand(1), DemandedElts, OrZero,
4880 Depth + 1) &&
4881 isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedElts, OrZero,
4882 Depth + 1);
4883
4884 case ISD::SELECT:
4885 case ISD::VSELECT:
4886 return isKnownToBeAPowerOfTwo(Val.getOperand(2), DemandedElts, OrZero,
4887 Depth + 1) &&
4888 isKnownToBeAPowerOfTwo(Val.getOperand(1), DemandedElts, OrZero,
4889 Depth + 1);
4890
4891 case ISD::ZERO_EXTEND:
4892 return isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedElts, OrZero,
4893 Depth + 1);
4894
4895 case ISD::VSCALE:
4896 // vscale(power-of-two) is a power-of-two
4897 return isKnownToBeAPowerOfTwo(Val.getOperand(0), /*OrZero=*/false,
4898 Depth + 1);
4899
4900 case ISD::VECTOR_SHUFFLE: {
4902 // Demanded elements with undef shuffle mask elements are unknown
4903 // - we cannot guarantee they are a power of two, so return false.
4904 APInt DemandedLHS, DemandedRHS;
4906 assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
4907 if (!getShuffleDemandedElts(NumElts, SVN->getMask(), DemandedElts,
4908 DemandedLHS, DemandedRHS))
4909 return false;
4910
4911 // All demanded elements from LHS must be known power of two.
4912 if (!!DemandedLHS && !isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedLHS,
4913 OrZero, Depth + 1))
4914 return false;
4915
4916 // All demanded elements from RHS must be known power of two.
4917 if (!!DemandedRHS && !isKnownToBeAPowerOfTwo(Val.getOperand(1), DemandedRHS,
4918 OrZero, Depth + 1))
4919 return false;
4920
4921 return true;
4922 }
4923 }
4924
4925 // More could be done here, though the above checks are enough
4926 // to handle some common cases.
4927 return false;
4928}
4929
4931 if (ConstantFPSDNode *C1 = isConstOrConstSplatFP(Val, true))
4932 return C1->getValueAPF().getExactLog2Abs() >= 0;
4933
4934 if (Val.getOpcode() == ISD::UINT_TO_FP || Val.getOpcode() == ISD::SINT_TO_FP)
4935 return isKnownToBeAPowerOfTwo(Val.getOperand(0), Depth + 1);
4936
4937 return false;
4938}
4939
4941 APInt DemandedElts = getDemandAllEltsMask(Op);
4942 return ComputeNumSignBits(Op, DemandedElts, Depth);
4943}
4944
4945unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, const APInt &DemandedElts,
4946 unsigned Depth) const {
4947 EVT VT = Op.getValueType();
4948 assert((VT.isInteger() || VT.isFloatingPoint()) && "Invalid VT!");
4949 unsigned VTBits = VT.getScalarSizeInBits();
4950 unsigned NumElts = DemandedElts.getBitWidth();
4951 unsigned Tmp, Tmp2;
4952 unsigned FirstAnswer = 1;
4953
4954 assert((!VT.isScalableVector() || NumElts == 1) &&
4955 "DemandedElts for scalable vectors must be 1 to represent all lanes");
4956
4957 if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
4958 const APInt &Val = C->getAPIntValue();
4959 return Val.getNumSignBits();
4960 }
4961
4962 if (Depth >= MaxRecursionDepth)
4963 return 1; // Limit search depth.
4964
4965 if (!DemandedElts)
4966 return 1; // No demanded elts, better to assume we don't know anything.
4967
4968 unsigned Opcode = Op.getOpcode();
4969 switch (Opcode) {
4970 default: break;
4971 case ISD::AssertSext:
4972 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
4973 return VTBits-Tmp+1;
4974 case ISD::AssertZext:
4975 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
4976 return VTBits-Tmp;
4977 case ISD::FREEZE:
4978 if (isGuaranteedNotToBeUndefOrPoison(Op.getOperand(0), DemandedElts,
4980 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4981 break;
4982 case ISD::MERGE_VALUES:
4983 return ComputeNumSignBits(Op.getOperand(Op.getResNo()), DemandedElts,
4984 Depth + 1);
4985 case ISD::SPLAT_VECTOR: {
4986 // Check if the sign bits of source go down as far as the truncated value.
4987 unsigned NumSrcBits = Op.getOperand(0).getValueSizeInBits();
4988 unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
4989 if (NumSrcSignBits > (NumSrcBits - VTBits))
4990 return NumSrcSignBits - (NumSrcBits - VTBits);
4991 break;
4992 }
4993 case ISD::BUILD_VECTOR:
4994 assert(!VT.isScalableVector());
4995 Tmp = VTBits;
4996 for (unsigned i = 0, e = Op.getNumOperands(); (i < e) && (Tmp > 1); ++i) {
4997 if (!DemandedElts[i])
4998 continue;
4999
5000 SDValue SrcOp = Op.getOperand(i);
5001 // BUILD_VECTOR can implicitly truncate sources, we handle this specially
5002 // for constant nodes to ensure we only look at the sign bits.
5004 APInt T = C->getAPIntValue().trunc(VTBits);
5005 Tmp2 = T.getNumSignBits();
5006 } else if (SrcOp.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5007 SrcOp.getOperand(0).getScalarValueSizeInBits() >= VTBits) {
5008 // EXTRACT_VECTOR_ELT can extend the value with high bits undefined. If
5009 // this BUILD_VECTOR truncates those undefined bits we can just look
5010 // through the SrcOp and query the vector directly.
5011 SDValue InVec = SrcOp.getOperand(0);
5012 EVT InVecVT = InVec.getValueType();
5013
5014 APInt DemandedSrcElts;
5015 if (InVecVT.isScalableVector())
5016 // Demand all elements.
5017 DemandedSrcElts = APInt(1, 1);
5018 else {
5019 unsigned NumSrcElts = InVecVT.getVectorNumElements();
5020 auto *ConstEltNo = dyn_cast<ConstantSDNode>(SrcOp.getOperand(1));
5021 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
5022 DemandedSrcElts =
5023 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
5024 else
5025 DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
5026 }
5027
5028 Tmp2 = ComputeNumSignBits(InVec, DemandedSrcElts, Depth + 1);
5029 unsigned ExtraBits = InVec.getScalarValueSizeInBits() - VTBits;
5030 if (ExtraBits)
5031 Tmp2 = (Tmp2 > ExtraBits ? Tmp2 - ExtraBits : 1);
5032 } else {
5033 Tmp2 = ComputeNumSignBits(SrcOp, Depth + 1);
5034
5035 if (SrcOp.getValueSizeInBits() != VTBits) {
5036 assert(SrcOp.getValueSizeInBits() > VTBits &&
5037 "Expected BUILD_VECTOR implicit truncation");
5038 unsigned ExtraBits = SrcOp.getValueSizeInBits() - VTBits;
5039 Tmp2 = (Tmp2 > ExtraBits ? Tmp2 - ExtraBits : 1);
5040 }
5041 }
5042 Tmp = std::min(Tmp, Tmp2);
5043 }
5044 return Tmp;
5045
5046 case ISD::VECTOR_COMPRESS: {
5047 SDValue Vec = Op.getOperand(0);
5048 SDValue PassThru = Op.getOperand(2);
5049 Tmp = ComputeNumSignBits(PassThru, DemandedElts, Depth + 1);
5050 if (Tmp == 1)
5051 return 1;
5052 Tmp2 = ComputeNumSignBits(Vec, Depth + 1);
5053 Tmp = std::min(Tmp, Tmp2);
5054 return Tmp;
5055 }
5056
5057 case ISD::VECTOR_SHUFFLE: {
5058 // Collect the minimum number of sign bits that are shared by every vector
5059 // element referenced by the shuffle.
5060 APInt DemandedLHS, DemandedRHS;
5062 assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
5063 if (!getShuffleDemandedElts(NumElts, SVN->getMask(), DemandedElts,
5064 DemandedLHS, DemandedRHS))
5065 return 1;
5066
5067 Tmp = std::numeric_limits<unsigned>::max();
5068 if (!!DemandedLHS)
5069 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedLHS, Depth + 1);
5070 if (!!DemandedRHS) {
5071 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedRHS, Depth + 1);
5072 Tmp = std::min(Tmp, Tmp2);
5073 }
5074 // If we don't know anything, early out and try computeKnownBits fall-back.
5075 if (Tmp == 1)
5076 break;
5077 assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
5078 return Tmp;
5079 }
5080
5081 case ISD::BITCAST: {
5082 if (VT.isScalableVector())
5083 break;
5084 SDValue N0 = Op.getOperand(0);
5085 EVT SrcVT = N0.getValueType();
5086 unsigned SrcBits = SrcVT.getScalarSizeInBits();
5087
5088 // Ignore bitcasts from unsupported types..
5089 if (!(SrcVT.isInteger() || SrcVT.isFloatingPoint()))
5090 break;
5091
5092 // Fast handling of 'identity' bitcasts.
5093 if (VTBits == SrcBits)
5094 return ComputeNumSignBits(N0, DemandedElts, Depth + 1);
5095
5096 bool IsLE = getDataLayout().isLittleEndian();
5097
5098 // Bitcast 'large element' scalar/vector to 'small element' vector.
5099 if ((SrcBits % VTBits) == 0) {
5100 assert(VT.isVector() && "Expected bitcast to vector");
5101
5102 unsigned Scale = SrcBits / VTBits;
5103 APInt SrcDemandedElts =
5104 APIntOps::ScaleBitMask(DemandedElts, NumElts / Scale);
5105
5106 // Fast case - sign splat can be simply split across the small elements.
5107 Tmp = ComputeNumSignBits(N0, SrcDemandedElts, Depth + 1);
5108 if (Tmp == SrcBits)
5109 return VTBits;
5110
5111 // Slow case - determine how far the sign extends into each sub-element.
5112 Tmp2 = VTBits;
5113 for (unsigned i = 0; i != NumElts; ++i)
5114 if (DemandedElts[i]) {
5115 unsigned SubOffset = i % Scale;
5116 SubOffset = (IsLE ? ((Scale - 1) - SubOffset) : SubOffset);
5117 SubOffset = SubOffset * VTBits;
5118 if (Tmp <= SubOffset)
5119 return 1;
5120 Tmp2 = std::min(Tmp2, Tmp - SubOffset);
5121 }
5122 return Tmp2;
5123 }
5124 break;
5125 }
5126
5128 // FP_TO_SINT_SAT produces a signed value that fits in the saturating VT.
5129 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
5130 return VTBits - Tmp + 1;
5131 case ISD::SIGN_EXTEND:
5132 Tmp = VTBits - Op.getOperand(0).getScalarValueSizeInBits();
5133 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1) + Tmp;
5135 // Max of the input and what this extends.
5136 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
5137 Tmp = VTBits-Tmp+1;
5138 Tmp2 = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
5139 return std::max(Tmp, Tmp2);
5141 if (VT.isScalableVector())
5142 break;
5143 SDValue Src = Op.getOperand(0);
5144 EVT SrcVT = Src.getValueType();
5145 APInt DemandedSrcElts = DemandedElts.zext(SrcVT.getVectorNumElements());
5146 Tmp = VTBits - SrcVT.getScalarSizeInBits();
5147 return ComputeNumSignBits(Src, DemandedSrcElts, Depth+1) + Tmp;
5148 }
5149 case ISD::SRA:
5150 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5151 // SRA X, C -> adds C sign bits.
5152 if (std::optional<unsigned> ShAmt =
5153 getValidMinimumShiftAmount(Op, DemandedElts, Depth + 1))
5154 Tmp = std::min(Tmp + *ShAmt, VTBits);
5155 return Tmp;
5156 case ISD::SHL:
5157 if (std::optional<ConstantRange> ShAmtRange =
5158 getValidShiftAmountRange(Op, DemandedElts, Depth + 1)) {
5159 unsigned MaxShAmt = ShAmtRange->getUnsignedMax().getZExtValue();
5160 unsigned MinShAmt = ShAmtRange->getUnsignedMin().getZExtValue();
5161 // Try to look through ZERO/SIGN/ANY_EXTEND. If all extended bits are
5162 // shifted out, then we can compute the number of sign bits for the
5163 // operand being extended. A future improvement could be to pass along the
5164 // "shifted left by" information in the recursive calls to
5165 // ComputeKnownSignBits. Allowing us to handle this more generically.
5166 if (ISD::isExtOpcode(Op.getOperand(0).getOpcode())) {
5167 SDValue Ext = Op.getOperand(0);
5168 EVT ExtVT = Ext.getValueType();
5169 SDValue Extendee = Ext.getOperand(0);
5170 EVT ExtendeeVT = Extendee.getValueType();
5171 unsigned SizeDifference =
5172 ExtVT.getScalarSizeInBits() - ExtendeeVT.getScalarSizeInBits();
5173 if (SizeDifference <= MinShAmt) {
5174 Tmp = SizeDifference +
5175 ComputeNumSignBits(Extendee, DemandedElts, Depth + 1);
5176 if (MaxShAmt < Tmp)
5177 return Tmp - MaxShAmt;
5178 }
5179 }
5180 // shl destroys sign bits, ensure it doesn't shift out all sign bits.
5181 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5182 if (MaxShAmt < Tmp)
5183 return Tmp - MaxShAmt;
5184 }
5185 break;
5186 case ISD::AND:
5187 case ISD::OR:
5188 case ISD::XOR: // NOT is handled here.
5189 // Logical binary ops preserve the number of sign bits at the worst.
5190 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
5191 if (Tmp != 1) {
5192 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
5193 FirstAnswer = std::min(Tmp, Tmp2);
5194 // We computed what we know about the sign bits as our first
5195 // answer. Now proceed to the generic code that uses
5196 // computeKnownBits, and pick whichever answer is better.
5197 }
5198 break;
5199
5200 case ISD::SELECT:
5201 case ISD::VSELECT:
5202 Tmp = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
5203 if (Tmp == 1) return 1; // Early out.
5204 Tmp2 = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
5205 return std::min(Tmp, Tmp2);
5206 case ISD::SELECT_CC:
5207 Tmp = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
5208 if (Tmp == 1) return 1; // Early out.
5209 Tmp2 = ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth+1);
5210 return std::min(Tmp, Tmp2);
5211
5212 case ISD::SMIN:
5213 case ISD::SMAX: {
5214 // If we have a clamp pattern, we know that the number of sign bits will be
5215 // the minimum of the clamp min/max range.
5216 bool IsMax = (Opcode == ISD::SMAX);
5217 ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
5218 if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
5219 if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
5220 CstHigh =
5221 isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
5222 if (CstLow && CstHigh) {
5223 if (!IsMax)
5224 std::swap(CstLow, CstHigh);
5225 if (CstLow->getAPIntValue().sle(CstHigh->getAPIntValue())) {
5226 Tmp = CstLow->getAPIntValue().getNumSignBits();
5227 Tmp2 = CstHigh->getAPIntValue().getNumSignBits();
5228 return std::min(Tmp, Tmp2);
5229 }
5230 }
5231
5232 // Fallback - just get the minimum number of sign bits of the operands.
5233 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5234 if (Tmp == 1)
5235 return 1; // Early out.
5236 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
5237 return std::min(Tmp, Tmp2);
5238 }
5239 case ISD::UMIN:
5240 case ISD::UMAX:
5241 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5242 if (Tmp == 1)
5243 return 1; // Early out.
5244 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
5245 return std::min(Tmp, Tmp2);
5246 case ISD::SSUBO_CARRY:
5247 case ISD::USUBO_CARRY:
5248 // sub_carry(x,x,c) -> 0/-1 (sext carry)
5249 if (Op.getResNo() == 0 && Op.getOperand(0) == Op.getOperand(1))
5250 return VTBits;
5251 [[fallthrough]];
5252 case ISD::SADDO:
5253 case ISD::UADDO:
5254 case ISD::SADDO_CARRY:
5255 case ISD::UADDO_CARRY:
5256 case ISD::SSUBO:
5257 case ISD::USUBO:
5258 case ISD::SMULO:
5259 case ISD::UMULO:
5260 if (Op.getResNo() != 1)
5261 break;
5262 // The boolean result conforms to getBooleanContents. Fall through.
5263 // If setcc returns 0/-1, all bits are sign bits.
5264 // We know that we have an integer-based boolean since these operations
5265 // are only available for integer.
5266 if (TLI->getBooleanContents(VT.isVector(), false) ==
5268 return VTBits;
5269 break;
5270 case ISD::SETCC:
5271 case ISD::SETCCCARRY:
5272 case ISD::STRICT_FSETCC:
5273 case ISD::STRICT_FSETCCS: {
5274 unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
5275 // If setcc returns 0/-1, all bits are sign bits.
5276 if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
5278 return VTBits;
5279 break;
5280 }
5282 // Semantically similar to icmp ult.
5283 if (TLI->getBooleanContents(VT.isVector(), /*isFloat=*/false) ==
5285 return VTBits;
5286 break;
5287 case ISD::ROTL:
5288 case ISD::ROTR: {
5289 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5290 ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(1), DemandedElts);
5291 FirstAnswer = SignBitsOps::rot(
5292 Tmp, VTBits, C ? std::optional(C->getAPIntValue()) : std::nullopt,
5293 Opcode == ISD::ROTR);
5294 break;
5295 }
5296 case ISD::ADD:
5297 case ISD::ADDC:
5298 // TODO: Move Operand 1 check before Operand 0 check
5299 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5300 if (Tmp == 1) return 1; // Early out.
5301
5302 // Special case decrementing a value (ADD X, -1):
5303 if (ConstantSDNode *CRHS =
5304 isConstOrConstSplat(Op.getOperand(1), DemandedElts))
5305 if (CRHS->isAllOnes()) {
5307 computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
5308
5309 // If the input is known to be 0 or 1, the output is 0/-1, which is all
5310 // sign bits set.
5311 if ((Known.Zero | 1).isAllOnes())
5312 return VTBits;
5313
5314 // If we are subtracting one from a positive number, there is no carry
5315 // out of the result.
5316 if (Known.isNonNegative())
5317 return Tmp;
5318 }
5319
5320 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
5321 if (Tmp2 == 1) return 1; // Early out.
5322
5323 // Add can have at most one carry bit. Thus we know that the output
5324 // is, at worst, one more bit than the inputs.
5325 return std::min(Tmp, Tmp2) - 1;
5326 case ISD::SUB:
5327 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
5328 if (Tmp2 == 1) return 1; // Early out.
5329
5330 // Handle NEG.
5331 if (ConstantSDNode *CLHS =
5332 isConstOrConstSplat(Op.getOperand(0), DemandedElts))
5333 if (CLHS->isZero()) {
5335 computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
5336 // If the input is known to be 0 or 1, the output is 0/-1, which is all
5337 // sign bits set.
5338 if ((Known.Zero | 1).isAllOnes())
5339 return VTBits;
5340
5341 // If the input is known to be positive (the sign bit is known clear),
5342 // the output of the NEG has the same number of sign bits as the input.
5343 if (Known.isNonNegative())
5344 return Tmp2;
5345
5346 // Otherwise, we treat this like a SUB.
5347 }
5348
5349 // Sub can have at most one carry bit. Thus we know that the output
5350 // is, at worst, one more bit than the inputs.
5351 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5352 if (Tmp == 1) return 1; // Early out.
5353 return std::min(Tmp, Tmp2) - 1;
5354 case ISD::MUL: {
5355 // The output of the Mul can be at most twice the valid bits in the inputs.
5356 unsigned SignBitsOp0 =
5357 ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5358 if (SignBitsOp0 == 1)
5359 break;
5360 unsigned SignBitsOp1 =
5361 ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
5362 if (SignBitsOp1 == 1)
5363 break;
5364 unsigned OutValidBits =
5365 (VTBits - SignBitsOp0 + 1) + (VTBits - SignBitsOp1 + 1);
5366 return OutValidBits > VTBits ? 1 : VTBits - OutValidBits + 1;
5367 }
5368 case ISD::AVGCEILS:
5369 case ISD::AVGFLOORS:
5370 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5371 if (Tmp == 1)
5372 return 1; // Early out.
5373 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
5374 return std::min(Tmp, Tmp2);
5375 case ISD::SREM:
5376 // The sign bit is the LHS's sign bit, except when the result of the
5377 // remainder is zero. The magnitude of the result should be less than or
5378 // equal to the magnitude of the LHS. Therefore, the result should have
5379 // at least as many sign bits as the left hand side.
5380 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5381 case ISD::TRUNCATE: {
5382 // Check if the sign bits of source go down as far as the truncated value.
5383 unsigned NumSrcBits = Op.getOperand(0).getScalarValueSizeInBits();
5384 unsigned NumSrcSignBits =
5385 ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5386 if (NumSrcSignBits > (NumSrcBits - VTBits))
5387 return NumSrcSignBits - (NumSrcBits - VTBits);
5388 break;
5389 }
5390 case ISD::EXTRACT_ELEMENT: {
5391 if (VT.isScalableVector())
5392 break;
5393 const int KnownSign = ComputeNumSignBits(Op.getOperand(0), Depth+1);
5394 const int BitWidth = Op.getValueSizeInBits();
5395 const int Items = Op.getOperand(0).getValueSizeInBits() / BitWidth;
5396
5397 // Get reverse index (starting from 1), Op1 value indexes elements from
5398 // little end. Sign starts at big end.
5399 const int rIndex = Items - 1 - Op.getConstantOperandVal(1);
5400
5401 // If the sign portion ends in our element the subtraction gives correct
5402 // result. Otherwise it gives either negative or > bitwidth result
5403 return std::clamp(KnownSign - rIndex * BitWidth, 1, BitWidth);
5404 }
5406 if (VT.isScalableVector())
5407 break;
5408 // If we know the element index, split the demand between the
5409 // source vector and the inserted element, otherwise assume we need
5410 // the original demanded vector elements and the value.
5411 SDValue InVec = Op.getOperand(0);
5412 SDValue InVal = Op.getOperand(1);
5413 SDValue EltNo = Op.getOperand(2);
5414 bool DemandedVal = true;
5415 APInt DemandedVecElts = DemandedElts;
5416 auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
5417 if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
5418 unsigned EltIdx = CEltNo->getZExtValue();
5419 DemandedVal = !!DemandedElts[EltIdx];
5420 DemandedVecElts.clearBit(EltIdx);
5421 }
5422 Tmp = std::numeric_limits<unsigned>::max();
5423 if (DemandedVal) {
5424 // TODO - handle implicit truncation of inserted elements.
5425 if (InVal.getScalarValueSizeInBits() != VTBits)
5426 break;
5427 Tmp2 = ComputeNumSignBits(InVal, Depth + 1);
5428 Tmp = std::min(Tmp, Tmp2);
5429 }
5430 if (!!DemandedVecElts) {
5431 Tmp2 = ComputeNumSignBits(InVec, DemandedVecElts, Depth + 1);
5432 Tmp = std::min(Tmp, Tmp2);
5433 }
5434 assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
5435 return Tmp;
5436 }
5438 SDValue InVec = Op.getOperand(0);
5439 SDValue EltNo = Op.getOperand(1);
5440 EVT VecVT = InVec.getValueType();
5441 // ComputeNumSignBits not yet implemented for scalable vectors.
5442 if (VecVT.isScalableVector())
5443 break;
5444 const unsigned BitWidth = Op.getValueSizeInBits();
5445 const unsigned EltBitWidth = Op.getOperand(0).getScalarValueSizeInBits();
5446 const unsigned NumSrcElts = VecVT.getVectorNumElements();
5447
5448 // If BitWidth > EltBitWidth the value is anyext:ed, and we do not know
5449 // anything about sign bits. But if the sizes match we can derive knowledge
5450 // about sign bits from the vector operand.
5451 if (BitWidth != EltBitWidth)
5452 break;
5453
5454 // If we know the element index, just demand that vector element, else for
5455 // an unknown element index, ignore DemandedElts and demand them all.
5456 APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
5457 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
5458 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
5459 DemandedSrcElts =
5460 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
5461
5462 return ComputeNumSignBits(InVec, DemandedSrcElts, Depth + 1);
5463 }
5465 // Offset the demanded elts by the subvector index.
5466 SDValue Src = Op.getOperand(0);
5467
5468 APInt DemandedSrcElts;
5469 if (Src.getValueType().isScalableVector())
5470 DemandedSrcElts = APInt(1, 1);
5471 else {
5472 uint64_t Idx = Op.getConstantOperandVal(1);
5473 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
5474 DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
5475 }
5476 return ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
5477 }
5478 case ISD::CONCAT_VECTORS: {
5479 if (VT.isScalableVector())
5480 break;
5481 // Determine the minimum number of sign bits across all demanded
5482 // elts of the input vectors. Early out if the result is already 1.
5483 Tmp = std::numeric_limits<unsigned>::max();
5484 EVT SubVectorVT = Op.getOperand(0).getValueType();
5485 unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
5486 unsigned NumSubVectors = Op.getNumOperands();
5487 for (unsigned i = 0; (i < NumSubVectors) && (Tmp > 1); ++i) {
5488 APInt DemandedSub =
5489 DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts);
5490 if (!DemandedSub)
5491 continue;
5492 Tmp2 = ComputeNumSignBits(Op.getOperand(i), DemandedSub, Depth + 1);
5493 Tmp = std::min(Tmp, Tmp2);
5494 }
5495 assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
5496 return Tmp;
5497 }
5498 case ISD::INSERT_SUBVECTOR: {
5499 SDValue Src = Op.getOperand(0);
5500 SDValue Sub = Op.getOperand(1);
5501 if (VT.isScalableVector()) {
5502 Tmp = ComputeNumSignBits(Sub, Depth + 1);
5503 Tmp = std::min(Tmp, ComputeNumSignBits(Src, Depth + 1));
5504 return Tmp;
5505 }
5506 // Demand any elements from the subvector and the remainder from the src its
5507 // inserted into.
5508 uint64_t Idx = Op.getConstantOperandVal(2);
5509 unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
5510 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
5511 APInt DemandedSrcElts = DemandedElts;
5512 DemandedSrcElts.clearBits(Idx, Idx + NumSubElts);
5513
5514 Tmp = std::numeric_limits<unsigned>::max();
5515 if (!!DemandedSubElts) {
5516 Tmp = ComputeNumSignBits(Sub, DemandedSubElts, Depth + 1);
5517 if (Tmp == 1)
5518 return 1; // early-out
5519 }
5520 if (!!DemandedSrcElts) {
5521 Tmp2 = ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
5522 Tmp = std::min(Tmp, Tmp2);
5523 }
5524 assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
5525 return Tmp;
5526 }
5527 case ISD::LOAD: {
5528 // If we are looking at the loaded value of the SDNode.
5529 if (Op.getResNo() != 0)
5530 break;
5531
5533 if (const MDNode *Ranges = LD->getRanges()) {
5534 if (DemandedElts != 1)
5535 break;
5536
5538 if (VTBits > CR.getBitWidth()) {
5539 switch (LD->getExtensionType()) {
5540 case ISD::SEXTLOAD:
5541 CR = CR.signExtend(VTBits);
5542 break;
5543 case ISD::ZEXTLOAD:
5544 CR = CR.zeroExtend(VTBits);
5545 break;
5546 default:
5547 break;
5548 }
5549 }
5550
5551 if (VTBits != CR.getBitWidth())
5552 break;
5553 return std::min(CR.getSignedMin().getNumSignBits(),
5555 }
5556
5557 unsigned ExtType = LD->getExtensionType();
5558 switch (ExtType) {
5559 default:
5560 break;
5561 case ISD::SEXTLOAD: // e.g. i16->i32 = '17' bits known.
5562 Tmp = LD->getMemoryVT().getScalarSizeInBits();
5563 return VTBits - Tmp + 1;
5564 case ISD::ZEXTLOAD: // e.g. i16->i32 = '16' bits known.
5565 Tmp = LD->getMemoryVT().getScalarSizeInBits();
5566 return VTBits - Tmp;
5567 case ISD::NON_EXTLOAD:
5568 if (const Constant *Cst = TLI->getTargetConstantFromLoad(LD)) {
5569 // We only need to handle vectors - computeKnownBits should handle
5570 // scalar cases.
5571 Type *CstTy = Cst->getType();
5572 if (CstTy->isVectorTy() && !VT.isScalableVector() &&
5573 (NumElts * VTBits) == CstTy->getPrimitiveSizeInBits() &&
5574 VTBits == CstTy->getScalarSizeInBits()) {
5575 Tmp = VTBits;
5576 for (unsigned i = 0; i != NumElts; ++i) {
5577 if (!DemandedElts[i])
5578 continue;
5579 if (Constant *Elt = Cst->getAggregateElement(i)) {
5580 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
5581 const APInt &Value = CInt->getValue();
5582 Tmp = std::min(Tmp, Value.getNumSignBits());
5583 continue;
5584 }
5585 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
5586 APInt Value = CFP->getValueAPF().bitcastToAPInt();
5587 Tmp = std::min(Tmp, Value.getNumSignBits());
5588 continue;
5589 }
5590 }
5591 // Unknown type. Conservatively assume no bits match sign bit.
5592 return 1;
5593 }
5594 return Tmp;
5595 }
5596 }
5597 break;
5598 }
5599
5600 break;
5601 }
5604 case ISD::ATOMIC_SWAP:
5616 case ISD::ATOMIC_LOAD: {
5617 auto *AT = cast<AtomicSDNode>(Op);
5618 // If we are looking at the loaded value.
5619 if (Op.getResNo() == 0) {
5620 Tmp = AT->getMemoryVT().getScalarSizeInBits();
5621 if (Tmp == VTBits)
5622 return 1; // early-out
5623
5624 // For atomic_load, prefer to use the extension type.
5625 if (Op->getOpcode() == ISD::ATOMIC_LOAD) {
5626 switch (AT->getExtensionType()) {
5627 default:
5628 break;
5629 case ISD::SEXTLOAD:
5630 return VTBits - Tmp + 1;
5631 case ISD::ZEXTLOAD:
5632 return VTBits - Tmp;
5633 }
5634 }
5635
5636 if (TLI->getExtendForAtomicOps() == ISD::SIGN_EXTEND)
5637 return VTBits - Tmp + 1;
5638 if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND)
5639 return VTBits - Tmp;
5640 }
5641 break;
5642 }
5643 }
5644
5645 // Allow the target to implement this method for its nodes.
5646 if (Opcode >= ISD::BUILTIN_OP_END ||
5647 Opcode == ISD::INTRINSIC_WO_CHAIN ||
5648 Opcode == ISD::INTRINSIC_W_CHAIN ||
5649 Opcode == ISD::INTRINSIC_VOID) {
5650 // TODO: This can probably be removed once target code is audited. This
5651 // is here purely to reduce patch size and review complexity.
5652 if (!VT.isScalableVector()) {
5653 unsigned NumBits =
5654 TLI->ComputeNumSignBitsForTargetNode(Op, DemandedElts, *this, Depth);
5655 if (NumBits > 1)
5656 FirstAnswer = std::max(FirstAnswer, NumBits);
5657 }
5658 }
5659
5660 // Finally, if we can prove that the top bits of the result are 0's or 1's,
5661 // use this information.
5662 KnownBits Known = computeKnownBits(Op, DemandedElts, Depth);
5663 return std::max(FirstAnswer, Known.countMinSignBits());
5664}
5665
5667 unsigned Depth) const {
5668 unsigned SignBits = ComputeNumSignBits(Op, Depth);
5669 return Op.getScalarValueSizeInBits() - SignBits + 1;
5670}
5671
5673 const APInt &DemandedElts,
5674 unsigned Depth) const {
5675 unsigned SignBits = ComputeNumSignBits(Op, DemandedElts, Depth);
5676 return Op.getScalarValueSizeInBits() - SignBits + 1;
5677}
5678
5680 UndefPoisonKind Kind,
5681 unsigned Depth) const {
5682 // Early out for FREEZE.
5683 if (Op.getOpcode() == ISD::FREEZE)
5684 return true;
5685
5686 APInt DemandedElts = getDemandAllEltsMask(Op);
5687 return isGuaranteedNotToBeUndefOrPoison(Op, DemandedElts, Kind, Depth);
5688}
5689
5691 const APInt &DemandedElts,
5692 UndefPoisonKind Kind,
5693 unsigned Depth) const {
5694 unsigned Opcode = Op.getOpcode();
5695
5696 // Early out for FREEZE.
5697 if (Opcode == ISD::FREEZE)
5698 return true;
5699
5700 if (Depth >= MaxRecursionDepth)
5701 return false; // Limit search depth.
5702
5703 if (isIntOrFPConstant(Op))
5704 return true;
5705
5706 switch (Opcode) {
5707 case ISD::CONDCODE:
5708 case ISD::VALUETYPE:
5709 case ISD::FrameIndex:
5711 case ISD::CopyFromReg:
5712 return true;
5713
5714 case ISD::POISON:
5715 return !includesPoison(Kind);
5716
5717 case ISD::UNDEF:
5718 return !includesUndef(Kind);
5719
5720 case ISD::BITCAST: {
5721 SDValue Src = Op.getOperand(0);
5722 EVT SrcVT = Src.getValueType();
5723 EVT DstVT = Op.getValueType();
5724
5725 if (!SrcVT.isVector() || !DstVT.isVector())
5726 return isGuaranteedNotToBeUndefOrPoison(Src, Kind, Depth + 1);
5727
5728 unsigned SrcEltBits = SrcVT.getScalarSizeInBits();
5729 unsigned DstEltBits = DstVT.getScalarSizeInBits();
5730 ElementCount NumSrcElts = SrcVT.getVectorElementCount();
5731 [[maybe_unused]] ElementCount NumDstElts = DstVT.getVectorElementCount();
5732
5733 if (SrcEltBits == DstEltBits)
5734 return isGuaranteedNotToBeUndefOrPoison(Src, DemandedElts, Kind,
5735 Depth + 1);
5736
5737 if (SrcEltBits < DstEltBits) {
5738 if (DstEltBits % SrcEltBits != 0)
5739 return isGuaranteedNotToBeUndefOrPoison(Src, Kind, Depth + 1);
5740
5741 assert(NumSrcElts == NumDstElts * (DstEltBits / SrcEltBits) &&
5742 "Unexpected vector bitcast");
5743 APInt DemandedSrcElts =
5744 APIntOps::ScaleBitMask(DemandedElts, NumSrcElts.getKnownMinValue());
5745 return isGuaranteedNotToBeUndefOrPoison(Src, DemandedSrcElts, Kind,
5746 Depth + 1);
5747 }
5748
5749 if (SrcEltBits % DstEltBits != 0)
5750 return isGuaranteedNotToBeUndefOrPoison(Src, Kind, Depth + 1);
5751
5752 assert(NumDstElts == NumSrcElts * (SrcEltBits / DstEltBits) &&
5753 "Unexpected vector bitcast");
5754 APInt DemandedSrcElts =
5755 APIntOps::ScaleBitMask(DemandedElts, NumSrcElts.getKnownMinValue());
5756 return isGuaranteedNotToBeUndefOrPoison(Src, DemandedSrcElts, Kind,
5757 Depth + 1);
5758 }
5759
5760 case ISD::BUILD_VECTOR:
5761 // NOTE: BUILD_VECTOR has implicit truncation of wider scalar elements -
5762 // this shouldn't affect the result.
5763 for (unsigned i = 0, e = Op.getNumOperands(); i < e; ++i) {
5764 if (!DemandedElts[i])
5765 continue;
5766 if (!isGuaranteedNotToBeUndefOrPoison(Op.getOperand(i), Kind, Depth + 1))
5767 return false;
5768 }
5769 return true;
5770
5771 case ISD::CONCAT_VECTORS: {
5772 EVT VT = Op.getValueType();
5773 if (!VT.isFixedLengthVector())
5774 break;
5775
5776 EVT SubVT = Op.getOperand(0).getValueType();
5777 unsigned NumSubElts = SubVT.getVectorNumElements();
5778 for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) {
5779 APInt DemandedSubElts =
5780 DemandedElts.extractBits(NumSubElts, I * NumSubElts);
5781 if (!!DemandedSubElts &&
5782 !isGuaranteedNotToBeUndefOrPoison(Op.getOperand(I), DemandedSubElts,
5783 Kind, Depth + 1))
5784 return false;
5785 }
5786 return true;
5787 }
5788
5790 SDValue Src = Op.getOperand(0);
5791 if (Src.getValueType().isScalableVector())
5792 break;
5793 uint64_t Idx = Op.getConstantOperandVal(1);
5794 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
5795 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
5796 return isGuaranteedNotToBeUndefOrPoison(Src, DemandedSrcElts, Kind,
5797 Depth + 1);
5798 }
5799
5800 case ISD::INSERT_SUBVECTOR: {
5801 if (Op.getValueType().isScalableVector())
5802 break;
5803 SDValue Src = Op.getOperand(0);
5804 SDValue Sub = Op.getOperand(1);
5805 uint64_t Idx = Op.getConstantOperandVal(2);
5806 unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
5807 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
5808 APInt DemandedSrcElts = DemandedElts;
5809 DemandedSrcElts.clearBits(Idx, Idx + NumSubElts);
5810
5811 if (!!DemandedSubElts && !isGuaranteedNotToBeUndefOrPoison(
5812 Sub, DemandedSubElts, Kind, Depth + 1))
5813 return false;
5814 if (!!DemandedSrcElts && !isGuaranteedNotToBeUndefOrPoison(
5815 Src, DemandedSrcElts, Kind, Depth + 1))
5816 return false;
5817 return true;
5818 }
5819
5821 SDValue Src = Op.getOperand(0);
5822 auto *IndexC = dyn_cast<ConstantSDNode>(Op.getOperand(1));
5823 EVT SrcVT = Src.getValueType();
5824 if (SrcVT.isFixedLengthVector() && IndexC &&
5825 IndexC->getAPIntValue().ult(SrcVT.getVectorNumElements())) {
5826 APInt DemandedSrcElts = APInt::getOneBitSet(SrcVT.getVectorNumElements(),
5827 IndexC->getZExtValue());
5828 return isGuaranteedNotToBeUndefOrPoison(Src, DemandedSrcElts, Kind,
5829 Depth + 1);
5830 }
5831 break;
5832 }
5833
5835 SDValue InVec = Op.getOperand(0);
5836 SDValue InVal = Op.getOperand(1);
5837 SDValue EltNo = Op.getOperand(2);
5838 EVT VT = InVec.getValueType();
5839 auto *IndexC = dyn_cast<ConstantSDNode>(EltNo);
5840 if (IndexC && VT.isFixedLengthVector() &&
5841 IndexC->getAPIntValue().ult(VT.getVectorNumElements())) {
5842 if (DemandedElts[IndexC->getZExtValue()] &&
5843 !isGuaranteedNotToBeUndefOrPoison(InVal, Kind, Depth + 1))
5844 return false;
5845 APInt InVecDemandedElts = DemandedElts;
5846 InVecDemandedElts.clearBit(IndexC->getZExtValue());
5847 if (!!InVecDemandedElts &&
5849 peekThroughInsertVectorElt(InVec, InVecDemandedElts),
5850 InVecDemandedElts, Kind, Depth + 1))
5851 return false;
5852 return true;
5853 }
5854 break;
5855 }
5856
5858 // Check upper (known poison) elements.
5859 if (DemandedElts.ugt(1) && includesPoison(Kind))
5860 return false;
5861 // Check element zero.
5862 if (DemandedElts[0] &&
5863 !isGuaranteedNotToBeUndefOrPoison(Op.getOperand(0), Kind, Depth + 1))
5864 return false;
5865 return true;
5866
5867 case ISD::SPLAT_VECTOR:
5868 return isGuaranteedNotToBeUndefOrPoison(Op.getOperand(0), Kind, Depth + 1);
5869
5870 case ISD::SELECT: {
5871 return !canCreateUndefOrPoison(Op, DemandedElts, Kind,
5872 /*ConsiderFlags*/ true, Depth) &&
5873 isGuaranteedNotToBeUndefOrPoison(Op.getOperand(0), Kind,
5874 Depth + 1) &&
5875 isGuaranteedNotToBeUndefOrPoison(Op.getOperand(1), DemandedElts,
5876 Kind, Depth + 1) &&
5877 isGuaranteedNotToBeUndefOrPoison(Op.getOperand(2), DemandedElts,
5878 Kind, Depth + 1);
5879 }
5880
5881 case ISD::VECTOR_SHUFFLE: {
5882 APInt DemandedLHS, DemandedRHS;
5883 auto *SVN = cast<ShuffleVectorSDNode>(Op);
5884 if (!getShuffleDemandedElts(DemandedElts.getBitWidth(), SVN->getMask(),
5885 DemandedElts, DemandedLHS, DemandedRHS,
5886 /*AllowUndefElts=*/false))
5887 return false;
5888 if (!DemandedLHS.isZero() &&
5889 !isGuaranteedNotToBeUndefOrPoison(Op.getOperand(0), DemandedLHS, Kind,
5890 Depth + 1))
5891 return false;
5892 if (!DemandedRHS.isZero() &&
5893 !isGuaranteedNotToBeUndefOrPoison(Op.getOperand(1), DemandedRHS, Kind,
5894 Depth + 1))
5895 return false;
5896 return true;
5897 }
5898
5899 case ISD::SHL:
5900 case ISD::SRL:
5901 case ISD::SRA:
5902 // Shift amount operand is checked by canCreateUndefOrPoison. So it is
5903 // enough to check operand 0 if Op can't create undef/poison.
5904 return !canCreateUndefOrPoison(Op, DemandedElts, Kind,
5905 /*ConsiderFlags*/ true, Depth) &&
5906 isGuaranteedNotToBeUndefOrPoison(Op.getOperand(0), DemandedElts,
5907 Kind, Depth + 1);
5908
5909 case ISD::BSWAP:
5910 case ISD::CTPOP:
5911 case ISD::BITREVERSE:
5912 case ISD::AND:
5913 case ISD::OR:
5914 case ISD::XOR:
5915 case ISD::ADD:
5916 case ISD::SUB:
5917 case ISD::MUL:
5918 case ISD::SADDSAT:
5919 case ISD::UADDSAT:
5920 case ISD::SSUBSAT:
5921 case ISD::USUBSAT:
5922 case ISD::SSHLSAT:
5923 case ISD::USHLSAT:
5924 case ISD::SMIN:
5925 case ISD::SMAX:
5926 case ISD::UMIN:
5927 case ISD::UMAX:
5928 case ISD::ZERO_EXTEND:
5929 case ISD::SIGN_EXTEND:
5930 case ISD::ANY_EXTEND:
5931 case ISD::TRUNCATE:
5932 case ISD::VSELECT: {
5933 // If Op can't create undef/poison and none of its operands are undef/poison
5934 // then Op is never undef/poison. A difference from the more common check
5935 // below, outside the switch, is that we handle elementwise operations for
5936 // which the DemandedElts mask is valid for all operands here.
5937 return !canCreateUndefOrPoison(Op, DemandedElts, Kind,
5938 /*ConsiderFlags*/ true, Depth) &&
5939 all_of(Op->ops(), [&](SDValue V) {
5940 return isGuaranteedNotToBeUndefOrPoison(V, DemandedElts, Kind,
5941 Depth + 1);
5942 });
5943 }
5944
5945 // TODO: Search for noundef attributes from library functions.
5946
5947 // TODO: Pointers dereferenced by ISD::LOAD/STORE ops are noundef.
5948
5949 default:
5950 // Allow the target to implement this method for its nodes.
5951 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
5952 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID)
5953 return TLI->isGuaranteedNotToBeUndefOrPoisonForTargetNode(
5954 Op, DemandedElts, *this, Kind, Depth);
5955 break;
5956 }
5957
5958 // If Op can't create undef/poison and none of its operands are undef/poison
5959 // then Op is never undef/poison.
5960 // NOTE: TargetNodes can handle this in themselves in
5961 // isGuaranteedNotToBeUndefOrPoisonForTargetNode or let
5962 // TargetLowering::isGuaranteedNotToBeUndefOrPoisonForTargetNode handle it.
5963 return !canCreateUndefOrPoison(Op, Kind, /*ConsiderFlags*/ true, Depth) &&
5964 all_of(Op->ops(), [&](SDValue V) {
5965 return isGuaranteedNotToBeUndefOrPoison(V, Kind, Depth + 1);
5966 });
5967}
5968
5970 bool ConsiderFlags,
5971 unsigned Depth) const {
5972 APInt DemandedElts = getDemandAllEltsMask(Op);
5973 return canCreateUndefOrPoison(Op, DemandedElts, Kind, ConsiderFlags, Depth);
5974}
5975
5977 UndefPoisonKind Kind,
5978 bool ConsiderFlags,
5979 unsigned Depth) const {
5980 if (ConsiderFlags && includesPoison(Kind) && Op->hasPoisonGeneratingFlags())
5981 return true;
5982
5983 unsigned Opcode = Op.getOpcode();
5984 switch (Opcode) {
5985 case ISD::AssertSext:
5986 case ISD::AssertZext:
5987 case ISD::AssertAlign:
5989 // Assertion nodes can create poison if the assertion fails.
5990 return includesPoison(Kind);
5991
5992 case ISD::FREEZE:
5996 case ISD::SADDSAT:
5997 case ISD::UADDSAT:
5998 case ISD::SSUBSAT:
5999 case ISD::USUBSAT:
6000 case ISD::MULHU:
6001 case ISD::MULHS:
6002 case ISD::AVGFLOORS:
6003 case ISD::AVGFLOORU:
6004 case ISD::AVGCEILS:
6005 case ISD::AVGCEILU:
6006 case ISD::ABDU:
6007 case ISD::ABDS:
6008 case ISD::SMIN:
6009 case ISD::SMAX:
6010 case ISD::SCMP:
6011 case ISD::UMIN:
6012 case ISD::UMAX:
6013 case ISD::UCMP:
6014 case ISD::AND:
6015 case ISD::XOR:
6016 case ISD::ROTL:
6017 case ISD::ROTR:
6018 case ISD::FSHL:
6019 case ISD::FSHR:
6020 case ISD::BSWAP:
6021 case ISD::CTTZ:
6022 case ISD::CTLZ:
6023 case ISD::CTLS:
6024 case ISD::CTPOP:
6025 case ISD::BITREVERSE:
6026 case ISD::PARITY:
6027 case ISD::SIGN_EXTEND:
6028 case ISD::TRUNCATE:
6032 case ISD::BITCAST:
6033 case ISD::BUILD_VECTOR:
6034 case ISD::BUILD_PAIR:
6035 case ISD::SPLAT_VECTOR:
6036 case ISD::FABS:
6037 case ISD::FCEIL:
6038 case ISD::FFLOOR:
6039 case ISD::FTRUNC:
6040 case ISD::FRINT:
6041 case ISD::FNEARBYINT:
6042 case ISD::FROUND:
6043 case ISD::FROUNDEVEN:
6044 return false;
6045
6046 case ISD::ABS:
6047 // ISD::ABS defines abs(INT_MIN) -> INT_MIN and never generates poison.
6048 // Different to Intrinsic::abs.
6049 return false;
6051 // ABS_MIN_POISON may produce poison if the input is INT_MIN.
6052 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1) <= 1;
6053
6054 case ISD::ADDC:
6055 case ISD::SUBC:
6056 case ISD::ADDE:
6057 case ISD::SUBE:
6058 case ISD::SADDO:
6059 case ISD::SSUBO:
6060 case ISD::SMULO:
6061 case ISD::SADDO_CARRY:
6062 case ISD::SSUBO_CARRY:
6063 case ISD::UADDO:
6064 case ISD::USUBO:
6065 case ISD::UMULO:
6066 case ISD::UADDO_CARRY:
6067 case ISD::USUBO_CARRY:
6068 // No poison on result or overflow flags.
6069 return false;
6070
6071 case ISD::SELECT_CC:
6072 case ISD::SETCC: {
6073 // Integer setcc cannot create undef or poison.
6074 if (Op.getOperand(0).getValueType().isInteger())
6075 return false;
6076
6077 // FP compares are more complicated. They can create poison for nan/infinity
6078 // based on options and flags. The options and flags also cause special
6079 // nonan condition codes to be used. Those condition codes may be preserved
6080 // even if the nonan flag is dropped somewhere.
6081 unsigned CCOp = Opcode == ISD::SETCC ? 2 : 4;
6082 ISD::CondCode CCCode = cast<CondCodeSDNode>(Op.getOperand(CCOp))->get();
6083 return (unsigned)CCCode & 0x10U;
6084 }
6085
6086 case ISD::OR:
6087 case ISD::ZERO_EXTEND:
6088 case ISD::SELECT:
6089 case ISD::VSELECT:
6090 case ISD::ADD:
6091 case ISD::SUB:
6092 case ISD::MUL:
6093 case ISD::FNEG:
6094 case ISD::FADD:
6095 case ISD::FSUB:
6096 case ISD::FMUL:
6097 case ISD::FDIV:
6098 case ISD::FREM:
6099 case ISD::FCOPYSIGN:
6100 case ISD::FMA:
6101 case ISD::FMAD:
6102 case ISD::FMULADD:
6103 case ISD::FP_EXTEND:
6104 case ISD::FMINNUM:
6105 case ISD::FMAXNUM:
6106 case ISD::FMINNUM_IEEE:
6107 case ISD::FMAXNUM_IEEE:
6108 case ISD::FMINIMUM:
6109 case ISD::FMAXIMUM:
6110 case ISD::FMINIMUMNUM:
6111 case ISD::FMAXIMUMNUM:
6117 // No poison except from flags (which is handled above)
6118 return false;
6119
6120 case ISD::SHL:
6121 case ISD::SRL:
6122 case ISD::SRA:
6123 // If the max shift amount isn't in range, then the shift can
6124 // create poison.
6125 return includesPoison(Kind) &&
6126 !getValidMaximumShiftAmount(Op, DemandedElts, Depth + 1);
6127
6130 // If the amount is zero then the result will be poison.
6131 // TODO: Add isKnownNeverZero DemandedElts handling.
6132 return includesPoison(Kind) &&
6133 !isKnownNeverZero(Op.getOperand(0), Depth + 1);
6134
6136 // Check if we demand any upper (poison) elements.
6137 return includesPoison(Kind) && DemandedElts.ugt(1);
6138
6141 // Ensure that the element index is in bounds.
6142 if (includesPoison(Kind)) {
6143 EVT VecVT = Op.getOperand(0).getValueType();
6144 SDValue Idx = Op.getOperand(Opcode == ISD::INSERT_VECTOR_ELT ? 2 : 1);
6145 KnownBits KnownIdx = computeKnownBits(Idx, Depth + 1);
6146 return KnownIdx.getMaxValue().uge(VecVT.getVectorMinNumElements());
6147 }
6148 return false;
6149 }
6150
6151 case ISD::VECTOR_SHUFFLE: {
6152 // Check for any demanded shuffle element that is undef.
6153 auto *SVN = cast<ShuffleVectorSDNode>(Op);
6154 for (auto [Idx, Elt] : enumerate(SVN->getMask()))
6155 if (Elt < 0 && DemandedElts[Idx])
6156 return true;
6157 return false;
6158 }
6159
6161 return false;
6162
6163 default:
6164 // Allow the target to implement this method for its nodes.
6165 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
6166 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID)
6167 return TLI->canCreateUndefOrPoisonForTargetNode(
6168 Op, DemandedElts, *this, Kind, ConsiderFlags, Depth);
6169 break;
6170 }
6171
6172 // Be conservative and return true.
6173 return true;
6174}
6175
6176bool SelectionDAG::isADDLike(SDValue Op, bool NoWrap) const {
6177 unsigned Opcode = Op.getOpcode();
6178 if (Opcode == ISD::OR)
6179 return Op->getFlags().hasDisjoint() ||
6180 haveNoCommonBitsSet(Op.getOperand(0), Op.getOperand(1));
6181 if (Opcode == ISD::XOR)
6182 return !NoWrap && isMinSignedConstant(Op.getOperand(1));
6183 return false;
6184}
6185
6187 return Op.getNumOperands() == 2 && isa<ConstantSDNode>(Op.getOperand(1)) &&
6188 (Op.isAnyAdd() || isADDLike(Op));
6189}
6190
6192 FPClassTest InterestedClasses,
6193 unsigned Depth) const {
6194 APInt DemandedElts = getDemandAllEltsMask(Op);
6195 return computeKnownFPClass(Op, DemandedElts, InterestedClasses, Depth);
6196}
6197
6199 const APInt &DemandedElts,
6200 FPClassTest InterestedClasses,
6201 unsigned Depth) const {
6203
6204 if (const auto *CFP = dyn_cast<ConstantFPSDNode>(Op))
6205 return KnownFPClass(CFP->getValueAPF());
6206
6207 if (Depth >= MaxRecursionDepth)
6208 return Known;
6209
6210 if (Op.getOpcode() == ISD::UNDEF)
6211 return Known;
6212
6213 EVT VT = Op.getValueType();
6214 assert(VT.isFloatingPoint() && "Computing KnownFPClass on non-FP op!");
6215 assert((!VT.isFixedLengthVector() ||
6216 DemandedElts.getBitWidth() == VT.getVectorNumElements()) &&
6217 "Unexpected vector size");
6218
6219 if (!DemandedElts)
6220 return Known;
6221
6222 unsigned Opcode = Op.getOpcode();
6223 switch (Opcode) {
6224 case ISD::POISON: {
6225 Known.setKnownFPClasses(fcNone);
6226 Known.setSignBit(false);
6227 break;
6228 }
6229 case ISD::FNEG: {
6230 Known = computeKnownFPClass(Op.getOperand(0), DemandedElts,
6231 InterestedClasses, Depth + 1);
6232 Known.fneg();
6233 break;
6234 }
6235 case ISD::BUILD_VECTOR: {
6236 assert(!VT.isScalableVector());
6237 bool First = true;
6238 for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) {
6239 if (!DemandedElts[I])
6240 continue;
6241
6242 if (First) {
6243 Known =
6244 computeKnownFPClass(Op.getOperand(I), InterestedClasses, Depth + 1);
6245 First = false;
6246 } else {
6247 Known |=
6248 computeKnownFPClass(Op.getOperand(I), InterestedClasses, Depth + 1);
6249 }
6250
6251 if (Known.isUnknown())
6252 break;
6253 }
6254 break;
6255 }
6257 SDValue Src = Op.getOperand(0);
6258 auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6259 EVT SrcVT = Src.getValueType();
6260 if (SrcVT.isFixedLengthVector() && CIdx) {
6261 if (CIdx->getAPIntValue().ult(SrcVT.getVectorNumElements())) {
6262 APInt DemandedSrcElts = APInt::getOneBitSet(
6263 SrcVT.getVectorNumElements(), CIdx->getZExtValue());
6264 Known = computeKnownFPClass(Src, DemandedSrcElts, InterestedClasses,
6265 Depth + 1);
6266 } else {
6267 // Out of bounds index is poison.
6268 Known.setKnownFPClasses(fcNone);
6269 }
6270 } else {
6271 Known = computeKnownFPClass(Src, InterestedClasses, Depth + 1);
6272 }
6273 break;
6274 }
6275 case ISD::SPLAT_VECTOR: {
6276 Known = computeKnownFPClass(Op.getOperand(0), InterestedClasses, Depth + 1);
6277 break;
6278 }
6279 case ISD::BITCAST: {
6280 // FIXME: It should not be necessary to check for an elementwise bitcast.
6281 // If a bitcast is not elementwise between vector / scalar types,
6282 // computeKnownBits already splices the known bits of the source elements
6283 // appropriately so as to line up with the bits of the result's demanded
6284 // elements.
6285 EVT SrcVT = Op.getOperand(0).getValueType();
6286 if (VT.isScalableVector() || SrcVT.isScalableVector())
6287 break;
6288 unsigned VTNumElts = VT.isVector() ? VT.getVectorNumElements() : 1;
6289 unsigned SrcVTNumElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1;
6290 if (VTNumElts != SrcVTNumElts)
6291 break;
6292
6293 KnownBits Bits = computeKnownBits(Op, DemandedElts, Depth + 1);
6295 break;
6296 }
6297 case ISD::FABS: {
6298 Known = computeKnownFPClass(Op.getOperand(0), DemandedElts,
6299 InterestedClasses, Depth + 1);
6300 Known.fabs();
6301 break;
6302 }
6303 case ISD::FCOPYSIGN: {
6304 Known = computeKnownFPClass(Op.getOperand(0), DemandedElts,
6305 InterestedClasses, Depth + 1);
6306 KnownFPClass KnownSign = computeKnownFPClass(Op.getOperand(1), DemandedElts,
6307 InterestedClasses, Depth + 1);
6308 Known.copysign(KnownSign);
6309 break;
6310 }
6311 case ISD::AssertNoFPClass: {
6312 Known = computeKnownFPClass(Op.getOperand(0), DemandedElts,
6313 InterestedClasses, Depth + 1);
6314 FPClassTest AssertedClasses =
6315 static_cast<FPClassTest>(Op->getConstantOperandVal(1));
6316 Known.setKnownFPClasses(Known.getKnownFPClasses() & ~AssertedClasses);
6317 break;
6318 }
6320 SDValue Src = Op.getOperand(0);
6321 EVT SrcVT = Src.getValueType();
6322 if (SrcVT.isFixedLengthVector()) {
6323 unsigned Idx = Op.getConstantOperandVal(1);
6324 unsigned NumSrcElts = SrcVT.getVectorNumElements();
6325
6326 APInt DemandedSrcElts = DemandedElts.zextOrTrunc(NumSrcElts).shl(Idx);
6327 Known = computeKnownFPClass(Src, DemandedSrcElts, InterestedClasses,
6328 Depth + 1);
6329 } else {
6330 Known = computeKnownFPClass(Src, InterestedClasses, Depth + 1);
6331 }
6332 break;
6333 }
6334 case ISD::INSERT_SUBVECTOR: {
6335 SDValue BaseVector = Op.getOperand(0);
6336 SDValue SubVector = Op.getOperand(1);
6337 EVT BaseVT = BaseVector.getValueType();
6338 if (BaseVT.isFixedLengthVector()) {
6339 unsigned Idx = Op.getConstantOperandVal(2);
6340 unsigned NumBaseElts = BaseVT.getVectorNumElements();
6341 unsigned NumSubElts = SubVector.getValueType().getVectorNumElements();
6342
6343 APInt DemandedMask =
6344 APInt::getBitsSet(NumBaseElts, Idx, Idx + NumSubElts);
6345 APInt DemandedSrcElts = DemandedElts & ~DemandedMask;
6346 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
6347
6348 if (!DemandedSrcElts.isZero())
6349 Known = computeKnownFPClass(BaseVector, DemandedSrcElts,
6350 InterestedClasses, Depth + 1);
6351 if (!DemandedSubElts.isZero()) {
6353 SubVector, DemandedSubElts, InterestedClasses, Depth + 1);
6354 Known = DemandedSrcElts.isZero() ? SubKnown : (Known | SubKnown);
6355 }
6356 } else {
6357 Known = computeKnownFPClass(SubVector, InterestedClasses, Depth + 1);
6358 if (!Known.isUnknown())
6359 Known |= computeKnownFPClass(BaseVector, InterestedClasses, Depth + 1);
6360 }
6361 break;
6362 }
6363 case ISD::SELECT:
6364 case ISD::VSELECT: {
6365 // TODO: Add adjustKnownFPClassForSelectArm clamp recognition as in
6366 // IR-level ValueTracking.
6367 KnownFPClass KnownFalseClass = computeKnownFPClass(
6368 Op.getOperand(2), DemandedElts, InterestedClasses, Depth + 1);
6369 if (KnownFalseClass.isUnknown())
6370 break;
6371 KnownFPClass KnownTrueClass = computeKnownFPClass(
6372 Op.getOperand(1), DemandedElts, InterestedClasses, Depth + 1);
6373 Known = KnownTrueClass.intersectWith(KnownFalseClass);
6374 break;
6375 }
6376 default:
6377 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
6378 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID) {
6379 TLI->computeKnownFPClassForTargetNode(Op, Known, DemandedElts, *this,
6380 Depth);
6381 }
6382 break;
6383 }
6384
6385 return Known;
6386}
6387
6389 unsigned Depth) const {
6390 APInt DemandedElts = getDemandAllEltsMask(Op);
6391 return isKnownNeverNaN(Op, DemandedElts, SNaN, Depth);
6392}
6393
6395 bool SNaN, unsigned Depth) const {
6396 assert(!DemandedElts.isZero() && "No demanded elements");
6397
6398 // If we're told that NaNs won't happen, assume they won't.
6399 if (Op->getFlags().hasNoNaNs())
6400 return true;
6401
6402 if (Depth >= MaxRecursionDepth)
6403 return false; // Limit search depth.
6404
6405 unsigned Opcode = Op.getOpcode();
6406 switch (Opcode) {
6407 case ISD::FADD:
6408 case ISD::FSUB:
6409 case ISD::FMUL:
6410 case ISD::FDIV:
6411 case ISD::FREM:
6412 case ISD::FSIN:
6413 case ISD::FCOS:
6414 case ISD::FTAN:
6415 case ISD::FASIN:
6416 case ISD::FACOS:
6417 case ISD::FATAN:
6418 case ISD::FATAN2:
6419 case ISD::FSINH:
6420 case ISD::FCOSH:
6421 case ISD::FTANH:
6422 case ISD::FMA:
6423 case ISD::FMULADD:
6424 case ISD::FMAD: {
6425 if (SNaN)
6426 return true;
6427 // TODO: Need isKnownNeverInfinity
6428 return false;
6429 }
6430 case ISD::FCANONICALIZE:
6431 case ISD::FEXP:
6432 case ISD::FEXP2:
6433 case ISD::FEXP10:
6434 case ISD::FTRUNC:
6435 case ISD::FFLOOR:
6436 case ISD::FCEIL:
6437 case ISD::FROUND:
6438 case ISD::FROUNDEVEN:
6439 case ISD::LROUND:
6440 case ISD::LLROUND:
6441 case ISD::FRINT:
6442 case ISD::LRINT:
6443 case ISD::LLRINT:
6444 case ISD::FNEARBYINT:
6445 case ISD::FLDEXP: {
6446 if (SNaN)
6447 return true;
6448 return isKnownNeverNaN(Op.getOperand(0), DemandedElts, SNaN, Depth + 1);
6449 }
6450 case ISD::FABS:
6451 case ISD::FNEG:
6452 case ISD::FCOPYSIGN: {
6453 return isKnownNeverNaN(Op.getOperand(0), DemandedElts, SNaN, Depth + 1);
6454 }
6455 case ISD::SELECT:
6456 return isKnownNeverNaN(Op.getOperand(1), DemandedElts, SNaN, Depth + 1) &&
6457 isKnownNeverNaN(Op.getOperand(2), DemandedElts, SNaN, Depth + 1);
6458 case ISD::FP_EXTEND:
6459 case ISD::FP_ROUND: {
6460 if (SNaN)
6461 return true;
6462 return isKnownNeverNaN(Op.getOperand(0), DemandedElts, SNaN, Depth + 1);
6463 }
6464 case ISD::SINT_TO_FP:
6465 case ISD::UINT_TO_FP:
6466 return true;
6467 case ISD::FSQRT: // Need is known positive
6468 case ISD::FLOG:
6469 case ISD::FLOG2:
6470 case ISD::FLOG10:
6471 case ISD::FPOWI:
6472 case ISD::FPOW: {
6473 if (SNaN)
6474 return true;
6475 // TODO: Refine on operand
6476 return false;
6477 }
6478 case ISD::FMINNUM:
6479 case ISD::FMAXNUM:
6480 case ISD::FMINIMUMNUM:
6481 case ISD::FMAXIMUMNUM: {
6482 // Only one needs to be known not-nan, since it will be returned if the
6483 // other ends up being one.
6484 return isKnownNeverNaN(Op.getOperand(0), DemandedElts, SNaN, Depth + 1) ||
6485 isKnownNeverNaN(Op.getOperand(1), DemandedElts, SNaN, Depth + 1);
6486 }
6487 case ISD::FMINNUM_IEEE:
6488 case ISD::FMAXNUM_IEEE: {
6489 if (SNaN)
6490 return true;
6491 // This can return a NaN if either operand is an sNaN, or if both operands
6492 // are NaN.
6493 return (isKnownNeverNaN(Op.getOperand(0), DemandedElts, false, Depth + 1) &&
6494 isKnownNeverSNaN(Op.getOperand(1), DemandedElts, Depth + 1)) ||
6495 (isKnownNeverNaN(Op.getOperand(1), DemandedElts, false, Depth + 1) &&
6496 isKnownNeverSNaN(Op.getOperand(0), DemandedElts, Depth + 1));
6497 }
6498 case ISD::FMINIMUM:
6499 case ISD::FMAXIMUM: {
6500 // TODO: Does this quiet or return the origina NaN as-is?
6501 return isKnownNeverNaN(Op.getOperand(0), DemandedElts, SNaN, Depth + 1) &&
6502 isKnownNeverNaN(Op.getOperand(1), DemandedElts, SNaN, Depth + 1);
6503 }
6505 SDValue Src = Op.getOperand(0);
6506 auto *Idx = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6507 EVT SrcVT = Src.getValueType();
6508 if (SrcVT.isFixedLengthVector() && Idx &&
6509 Idx->getAPIntValue().ult(SrcVT.getVectorNumElements())) {
6510 APInt DemandedSrcElts = APInt::getOneBitSet(SrcVT.getVectorNumElements(),
6511 Idx->getZExtValue());
6512 return isKnownNeverNaN(Src, DemandedSrcElts, SNaN, Depth + 1);
6513 }
6514 return isKnownNeverNaN(Src, SNaN, Depth + 1);
6515 }
6517 SDValue Src = Op.getOperand(0);
6518 if (Src.getValueType().isFixedLengthVector()) {
6519 unsigned Idx = Op.getConstantOperandVal(1);
6520 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
6521 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
6522 return isKnownNeverNaN(Src, DemandedSrcElts, SNaN, Depth + 1);
6523 }
6524 return isKnownNeverNaN(Src, SNaN, Depth + 1);
6525 }
6526 case ISD::INSERT_SUBVECTOR: {
6527 SDValue BaseVector = Op.getOperand(0);
6528 SDValue SubVector = Op.getOperand(1);
6529 EVT BaseVectorVT = BaseVector.getValueType();
6530 if (BaseVectorVT.isFixedLengthVector()) {
6531 unsigned Idx = Op.getConstantOperandVal(2);
6532 unsigned NumBaseElts = BaseVectorVT.getVectorNumElements();
6533 unsigned NumSubElts = SubVector.getValueType().getVectorNumElements();
6534
6535 // Clear/Extract the bits at the position where the subvector will be
6536 // inserted.
6537 APInt DemandedMask =
6538 APInt::getBitsSet(NumBaseElts, Idx, Idx + NumSubElts);
6539 APInt DemandedSrcElts = DemandedElts & ~DemandedMask;
6540 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
6541
6542 bool NeverNaN = true;
6543 if (!DemandedSrcElts.isZero())
6544 NeverNaN &=
6545 isKnownNeverNaN(BaseVector, DemandedSrcElts, SNaN, Depth + 1);
6546 if (NeverNaN && !DemandedSubElts.isZero())
6547 NeverNaN &=
6548 isKnownNeverNaN(SubVector, DemandedSubElts, SNaN, Depth + 1);
6549 return NeverNaN;
6550 }
6551 return isKnownNeverNaN(BaseVector, SNaN, Depth + 1) &&
6552 isKnownNeverNaN(SubVector, SNaN, Depth + 1);
6553 }
6554 case ISD::BUILD_VECTOR: {
6555 unsigned NumElts = Op.getNumOperands();
6556 for (unsigned I = 0; I != NumElts; ++I)
6557 if (DemandedElts[I] &&
6558 !isKnownNeverNaN(Op.getOperand(I), SNaN, Depth + 1))
6559 return false;
6560 return true;
6561 }
6562 case ISD::SPLAT_VECTOR:
6563 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
6564 case ISD::AssertNoFPClass: {
6565 FPClassTest NoFPClass =
6566 static_cast<FPClassTest>(Op.getConstantOperandVal(1));
6567 if ((NoFPClass & fcNan) == fcNan)
6568 return true;
6569 if (SNaN && (NoFPClass & fcSNan) == fcSNan)
6570 return true;
6571 return isKnownNeverNaN(Op.getOperand(0), DemandedElts, SNaN, Depth + 1);
6572 }
6573 default:
6574 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
6575 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID) {
6576 return TLI->isKnownNeverNaNForTargetNode(Op, DemandedElts, *this, SNaN,
6577 Depth);
6578 }
6579 break;
6580 }
6581
6582 FPClassTest NanMask = SNaN ? fcSNan : fcNan;
6583 KnownFPClass Known = computeKnownFPClass(Op, DemandedElts, NanMask, Depth);
6584 return Known.isKnownNever(NanMask);
6585}
6586
6588 APInt DemandedElts = getDemandAllEltsMask(Op);
6589 return isKnownNeverLogicalZero(Op, DemandedElts, Depth);
6590}
6591
6593 const APInt &DemandedElts,
6594 unsigned Depth) const {
6595 assert(!DemandedElts.isZero() && "No demanded elements");
6596 EVT VT = Op.getValueType();
6598 computeKnownFPClass(Op, DemandedElts, fcZero | fcSubnormal, Depth);
6599 return Known.isKnownNeverLogicalZero(getDenormalMode(VT));
6600}
6601
6603 APInt DemandedElts = getDemandAllEltsMask(Op);
6604 return isKnownNeverZero(Op, DemandedElts, Depth);
6605}
6606
6608 unsigned Depth) const {
6609 if (Depth >= MaxRecursionDepth)
6610 return false; // Limit search depth.
6611
6612 EVT OpVT = Op.getValueType();
6613 unsigned BitWidth = OpVT.getScalarSizeInBits();
6614
6615 assert(!Op.getValueType().isFloatingPoint() &&
6616 "Floating point types unsupported - use isKnownNeverLogicalZero");
6617
6618 // If the value is a constant, we can obviously see if it is a zero or not.
6619 auto IsNeverZero = [BitWidth](const ConstantSDNode *C) {
6620 APInt V = C->getAPIntValue().zextOrTrunc(BitWidth);
6621 return !V.isZero();
6622 };
6623
6624 if (ISD::matchUnaryPredicate(Op, DemandedElts, IsNeverZero,
6625 /*AllowUndefs=*/false, /*AllowTruncation=*/true))
6626 return true;
6627
6628 // TODO: Recognize more cases here. Most of the cases are also incomplete to
6629 // some degree.
6630 switch (Op.getOpcode()) {
6631 default:
6632 break;
6633
6635 SDValue InVec = Op.getOperand(0);
6636 SDValue EltNo = Op.getOperand(1);
6637 EVT VecVT = InVec.getValueType();
6638
6639 // Skip scalable vectors or implicit extensions.
6640 if (VecVT.isScalableVector() ||
6641 OpVT.getScalarSizeInBits() != VecVT.getScalarSizeInBits())
6642 break;
6643
6644 // If we know the element index, just demand that vector element, else for
6645 // an unknown element index, ignore DemandedElts and demand them all.
6646 const unsigned NumSrcElts = VecVT.getVectorNumElements();
6647 APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
6648 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
6649 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
6650 DemandedSrcElts =
6651 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
6652
6653 return isKnownNeverZero(InVec, DemandedSrcElts, Depth + 1);
6654 }
6655
6656 case ISD::OR:
6657 return isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1) ||
6658 isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6659
6660 case ISD::VSELECT:
6661 case ISD::SELECT:
6662 return isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1) &&
6663 isKnownNeverZero(Op.getOperand(2), DemandedElts, Depth + 1);
6664
6665 case ISD::SHL: {
6666 if (Op->getFlags().hasNoSignedWrap() || Op->getFlags().hasNoUnsignedWrap())
6667 return isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6668 KnownBits ValKnown =
6669 computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
6670 // 1 << X is never zero.
6671 if (ValKnown.One[0])
6672 return true;
6673 // If max shift cnt of known ones is non-zero, result is non-zero.
6674 APInt MaxCnt = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1)
6675 .getMaxValue();
6676 if (MaxCnt.ult(ValKnown.getBitWidth()) &&
6677 !ValKnown.One.shl(MaxCnt).isZero())
6678 return true;
6679 break;
6680 }
6681
6682 case ISD::VECTOR_SHUFFLE: {
6683 if (Op.getValueType().isScalableVector())
6684 return false;
6685
6686 unsigned NumElts = DemandedElts.getBitWidth();
6687
6688 // All demanded elements from LHS and RHS must be known non-zero.
6689 // Demanded elements with undef shuffle mask elements are unknown.
6690
6691 APInt DemandedLHS, DemandedRHS;
6692 auto *SVN = cast<ShuffleVectorSDNode>(Op);
6693 assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
6694 if (!getShuffleDemandedElts(NumElts, SVN->getMask(), DemandedElts,
6695 DemandedLHS, DemandedRHS))
6696 return false;
6697
6698 return (!DemandedLHS ||
6699 isKnownNeverZero(Op.getOperand(0), DemandedLHS, Depth + 1)) &&
6700 (!DemandedRHS ||
6701 isKnownNeverZero(Op.getOperand(1), DemandedRHS, Depth + 1));
6702 }
6703
6704 case ISD::UADDSAT:
6705 case ISD::UMAX:
6706 return isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1) ||
6707 isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6708
6709 case ISD::UMIN:
6710 return isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1) &&
6711 isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6712
6713 // For smin/smax: If either operand is known negative/positive
6714 // respectively we don't need the other to be known at all.
6715 case ISD::SMAX: {
6716 KnownBits Op1 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
6717 if (Op1.isStrictlyPositive())
6718 return true;
6719
6720 KnownBits Op0 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
6721 if (Op0.isStrictlyPositive())
6722 return true;
6723
6724 if (Op1.isNonZero() && Op0.isNonZero())
6725 return true;
6726
6727 return isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1) &&
6728 isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6729 }
6730 case ISD::SMIN: {
6731 KnownBits Op1 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
6732 if (Op1.isNegative())
6733 return true;
6734
6735 KnownBits Op0 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
6736 if (Op0.isNegative())
6737 return true;
6738
6739 if (Op1.isNonZero() && Op0.isNonZero())
6740 return true;
6741
6742 return isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1) &&
6743 isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6744 }
6745
6746 case ISD::ROTL:
6747 case ISD::ROTR:
6748 case ISD::BITREVERSE:
6749 case ISD::BSWAP:
6750 case ISD::CTPOP:
6751 case ISD::ABS:
6753 return isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6754
6755 case ISD::SRA:
6756 case ISD::SRL: {
6757 if (Op->getFlags().hasExact())
6758 return isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6759 KnownBits ValKnown =
6760 computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
6761 if (ValKnown.isNegative())
6762 return true;
6763 // If max shift cnt of known ones is non-zero, result is non-zero.
6764 APInt MaxCnt = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1)
6765 .getMaxValue();
6766 if (MaxCnt.ult(ValKnown.getBitWidth()) &&
6767 !ValKnown.One.lshr(MaxCnt).isZero())
6768 return true;
6769 break;
6770 }
6771 case ISD::UDIV:
6772 case ISD::SDIV:
6773 // div exact can only produce a zero if the dividend is zero.
6774 // TODO: For udiv this is also true if Op1 u<= Op0
6775 if (Op->getFlags().hasExact())
6776 return isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6777 break;
6778
6779 case ISD::ADD:
6780 if (Op->getFlags().hasNoUnsignedWrap())
6781 if (isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1) ||
6782 isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1))
6783 return true;
6784 // TODO: There are a lot more cases we can prove for add.
6785 break;
6786
6787 case ISD::SUB: {
6788 if (isNullConstant(Op.getOperand(0)))
6789 return isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1);
6790
6791 std::optional<bool> ne = KnownBits::ne(
6792 computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1),
6793 computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1));
6794 return ne && *ne;
6795 }
6796
6797 case ISD::MUL:
6798 if (Op->getFlags().hasNoSignedWrap() || Op->getFlags().hasNoUnsignedWrap())
6799 if (isKnownNeverZero(Op.getOperand(1), Depth + 1) &&
6800 isKnownNeverZero(Op.getOperand(0), Depth + 1))
6801 return true;
6802 break;
6803
6804 case ISD::ZERO_EXTEND:
6805 case ISD::SIGN_EXTEND:
6806 return isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6807 case ISD::VSCALE: {
6809 const APInt &Multiplier = Op.getConstantOperandAPInt(0);
6810 ConstantRange CR =
6811 getVScaleRange(&F, Op.getScalarValueSizeInBits()).multiply(Multiplier);
6812 if (!CR.contains(APInt(CR.getBitWidth(), 0)))
6813 return true;
6814 break;
6815 }
6816 }
6817
6818 return computeKnownBits(Op, DemandedElts, Depth).isNonZero();
6819}
6820
6822 if (ConstantFPSDNode *C1 = isConstOrConstSplatFP(Op, true))
6823 return !C1->isNegative();
6824
6825 switch (Op.getOpcode()) {
6826 case ISD::FABS:
6827 case ISD::FEXP:
6828 case ISD::FEXP2:
6829 case ISD::FEXP10:
6830 return true;
6831 default:
6832 return false;
6833 }
6834
6835 llvm_unreachable("covered opcode switch");
6836}
6837
6839 assert(Use.getValueType().isFloatingPoint());
6840 const SDNode *User = Use.getUser();
6841 if (User->getFlags().hasNoSignedZeros())
6842 return true;
6843
6844 unsigned OperandNo = Use.getOperandNo();
6845 // Check if this use is insensitive to the sign of zero
6846 switch (User->getOpcode()) {
6847 case ISD::SETCC:
6848 // Comparisons: IEEE-754 specifies +0.0 == -0.0.
6849 case ISD::FABS:
6850 // fabs always produces +0.0.
6851 return true;
6852 case ISD::FCOPYSIGN:
6853 // copysign overwrites the sign bit of the first operand.
6854 return OperandNo == 0;
6855 case ISD::FADD:
6856 case ISD::FSUB: {
6857 // Arithmetic with non-zero constants fixes the uncertainty around the
6858 // sign bit.
6859 SDValue Other = User->getOperand(1 - OperandNo);
6861 }
6862 case ISD::FP_TO_SINT:
6863 case ISD::FP_TO_UINT:
6864 // fp-to-int conversions normalize signed zeros.
6865 return true;
6866 default:
6867 return false;
6868 }
6869}
6870
6872 if (Op->getFlags().hasNoSignedZeros())
6873 return true;
6874 // FIXME: Limit the amount of checked uses to not introduce a compile-time
6875 // regression. Ideally, this should be implemented as a demanded-bits
6876 // optimization that stems from the users.
6877 if (Op->use_size() > 2)
6878 return false;
6879 return all_of(Op->uses(),
6880 [&](const SDUse &Use) { return canIgnoreSignBitOfZero(Use); });
6881}
6882
6884 // Check the obvious case.
6885 if (A == B) return true;
6886
6887 // For negative and positive zero.
6890 if (CA->isZero() && CB->isZero()) return true;
6891
6892 // Otherwise they may not be equal.
6893 return false;
6894}
6895
6896// Only bits set in Mask must be negated, other bits may be arbitrary.
6898 if (isBitwiseNot(V, AllowUndefs))
6899 return V.getOperand(0);
6900
6901 // Handle any_extend (not (truncate X)) pattern, where Mask only sets
6902 // bits in the non-extended part.
6903 ConstantSDNode *MaskC = isConstOrConstSplat(Mask);
6904 if (!MaskC || V.getOpcode() != ISD::ANY_EXTEND)
6905 return SDValue();
6906 SDValue ExtArg = V.getOperand(0);
6907 if (ExtArg.getScalarValueSizeInBits() >=
6908 MaskC->getAPIntValue().getActiveBits() &&
6909 isBitwiseNot(ExtArg, AllowUndefs) &&
6910 ExtArg.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6911 ExtArg.getOperand(0).getOperand(0).getValueType() == V.getValueType())
6912 return ExtArg.getOperand(0).getOperand(0);
6913 return SDValue();
6914}
6915
6917 // Match masked merge pattern (X & ~M) op (Y & M)
6918 // Including degenerate case (X & ~M) op M
6919 auto MatchNoCommonBitsPattern = [&](SDValue Not, SDValue Mask,
6920 SDValue Other) {
6921 if (SDValue NotOperand =
6922 getBitwiseNotOperand(Not, Mask, /* AllowUndefs */ true)) {
6923 if (NotOperand->getOpcode() == ISD::ZERO_EXTEND ||
6924 NotOperand->getOpcode() == ISD::TRUNCATE)
6925 NotOperand = NotOperand->getOperand(0);
6926
6927 if (Other == NotOperand)
6928 return true;
6929 if (Other->getOpcode() == ISD::AND)
6930 return NotOperand == Other->getOperand(0) ||
6931 NotOperand == Other->getOperand(1);
6932 }
6933 return false;
6934 };
6935
6936 if (A->getOpcode() == ISD::ZERO_EXTEND || A->getOpcode() == ISD::TRUNCATE)
6937 A = A->getOperand(0);
6938
6939 if (B->getOpcode() == ISD::ZERO_EXTEND || B->getOpcode() == ISD::TRUNCATE)
6940 B = B->getOperand(0);
6941
6942 if (A->getOpcode() == ISD::AND)
6943 return MatchNoCommonBitsPattern(A->getOperand(0), A->getOperand(1), B) ||
6944 MatchNoCommonBitsPattern(A->getOperand(1), A->getOperand(0), B);
6945 return false;
6946}
6947
6948// FIXME: unify with llvm::haveNoCommonBitsSet.
6950 assert(A.getValueType() == B.getValueType() &&
6951 "Values must have the same type");
6954 return true;
6957}
6958
6959static SDValue FoldSTEP_VECTOR(const SDLoc &DL, EVT VT, SDValue Step,
6960 SelectionDAG &DAG) {
6961 if (cast<ConstantSDNode>(Step)->isZero())
6962 return DAG.getConstant(0, DL, VT);
6963
6964 return SDValue();
6965}
6966
6969 SelectionDAG &DAG) {
6970 int NumOps = Ops.size();
6971 assert(NumOps != 0 && "Can't build an empty vector!");
6972 assert(!VT.isScalableVector() &&
6973 "BUILD_VECTOR cannot be used with scalable types");
6974 assert(VT.getVectorNumElements() == (unsigned)NumOps &&
6975 "Incorrect element count in BUILD_VECTOR!");
6976
6977 // BUILD_VECTOR of UNDEFs is UNDEF.
6978 bool AllPoison = true;
6979 if (llvm::all_of(Ops, [&AllPoison](SDValue Op) {
6980 AllPoison &= Op.getOpcode() == ISD::POISON;
6981 return Op.isUndef();
6982 }))
6983 return AllPoison ? DAG.getPOISON(VT) : DAG.getUNDEF(VT);
6984
6985 // BUILD_VECTOR of seq extract/insert from the same vector + type is Identity.
6986 SDValue IdentitySrc;
6987 bool IsIdentity = true;
6988 for (int i = 0; i != NumOps; ++i) {
6989 if (Ops[i].getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6990 Ops[i].getOperand(0).getValueType() != VT ||
6991 (IdentitySrc && Ops[i].getOperand(0) != IdentitySrc) ||
6992 !isa<ConstantSDNode>(Ops[i].getOperand(1)) ||
6993 Ops[i].getConstantOperandAPInt(1) != i) {
6994 IsIdentity = false;
6995 break;
6996 }
6997 IdentitySrc = Ops[i].getOperand(0);
6998 }
6999 if (IsIdentity)
7000 return IdentitySrc;
7001
7002 return SDValue();
7003}
7004
7005/// Try to simplify vector concatenation to an input value, undef, or build
7006/// vector.
7009 SelectionDAG &DAG) {
7010 assert(!Ops.empty() && "Can't concatenate an empty list of vectors!");
7012 [Ops](SDValue Op) {
7013 return Ops[0].getValueType() == Op.getValueType();
7014 }) &&
7015 "Concatenation of vectors with inconsistent value types!");
7016 assert((Ops[0].getValueType().getVectorElementCount() * Ops.size()) ==
7017 VT.getVectorElementCount() &&
7018 "Incorrect element count in vector concatenation!");
7019
7020 if (Ops.size() == 1)
7021 return Ops[0];
7022
7023 // Concat of UNDEFs is UNDEF.
7024 bool AllPoison = true;
7025 if (llvm::all_of(Ops, [&AllPoison](SDValue Op) {
7026 AllPoison &= Op.getOpcode() == ISD::POISON;
7027 return Op.isUndef();
7028 }))
7029 return AllPoison ? DAG.getPOISON(VT) : DAG.getUNDEF(VT);
7030
7031 // Scan the operands and look for extract operations from a single source
7032 // that correspond to insertion at the same location via this concatenation:
7033 // concat (extract X, 0*subvec_elts), (extract X, 1*subvec_elts), ...
7034 SDValue IdentitySrc;
7035 bool IsIdentity = true;
7036 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
7037 SDValue Op = Ops[i];
7038 unsigned IdentityIndex = i * Op.getValueType().getVectorMinNumElements();
7039 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
7040 Op.getOperand(0).getValueType() != VT ||
7041 (IdentitySrc && Op.getOperand(0) != IdentitySrc) ||
7042 Op.getConstantOperandVal(1) != IdentityIndex) {
7043 IsIdentity = false;
7044 break;
7045 }
7046 assert((!IdentitySrc || IdentitySrc == Op.getOperand(0)) &&
7047 "Unexpected identity source vector for concat of extracts");
7048 IdentitySrc = Op.getOperand(0);
7049 }
7050 if (IsIdentity) {
7051 assert(IdentitySrc && "Failed to set source vector of extracts");
7052 return IdentitySrc;
7053 }
7054
7055 // The code below this point is only designed to work for fixed width
7056 // vectors, so we bail out for now.
7057 if (VT.isScalableVector())
7058 return SDValue();
7059
7060 // A CONCAT_VECTOR of scalar sources, such as UNDEF, BUILD_VECTOR and
7061 // single-element INSERT_VECTOR_ELT operands can be simplified to one big
7062 // BUILD_VECTOR.
7063 // FIXME: Add support for SCALAR_TO_VECTOR as well.
7064 EVT SVT = VT.getScalarType();
7066 for (SDValue Op : Ops) {
7067 EVT OpVT = Op.getValueType();
7068 if (Op.getOpcode() == ISD::POISON)
7069 Elts.append(OpVT.getVectorNumElements(), DAG.getPOISON(SVT));
7070 else if (Op.getOpcode() == ISD::UNDEF)
7071 Elts.append(OpVT.getVectorNumElements(), DAG.getUNDEF(SVT));
7072 else if (Op.getOpcode() == ISD::BUILD_VECTOR)
7073 Elts.append(Op->op_begin(), Op->op_end());
7074 else if (Op.getOpcode() == ISD::INSERT_VECTOR_ELT &&
7075 OpVT.getVectorNumElements() == 1 &&
7076 isNullConstant(Op.getOperand(2)))
7077 Elts.push_back(Op.getOperand(1));
7078 else
7079 return SDValue();
7080 }
7081
7082 // BUILD_VECTOR requires all inputs to be of the same type, find the
7083 // maximum type and extend them all.
7084 for (SDValue Op : Elts)
7085 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
7086
7087 if (SVT.bitsGT(VT.getScalarType())) {
7088 for (SDValue &Op : Elts) {
7089 if (Op.getOpcode() == ISD::POISON)
7090 Op = DAG.getPOISON(SVT);
7091 else if (Op.getOpcode() == ISD::UNDEF)
7092 Op = DAG.getUNDEF(SVT);
7093 else
7094 Op = DAG.getTargetLoweringInfo().isZExtFree(Op.getValueType(), SVT)
7095 ? DAG.getZExtOrTrunc(Op, DL, SVT)
7096 : DAG.getSExtOrTrunc(Op, DL, SVT);
7097 }
7098 }
7099
7100 SDValue V = DAG.getBuildVector(VT, DL, Elts);
7101 NewSDValueDbgMsg(V, "New node fold concat vectors: ", &DAG);
7102 return V;
7103}
7104
7105/// Gets or creates the specified node.
7106SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT) {
7107 SDVTList VTs = getVTList(VT);
7108 SDNodeKey ID(Opcode, VTs, {});
7109 FoldingSetInsertToken InsertToken;
7110 if (SDNode *E = lookupNode(ID, DL, InsertToken))
7111 return SDValue(E, 0);
7112
7113 auto *N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
7114 CSEMap.insert(N, InsertToken);
7115
7116 InsertNode(N);
7117 SDValue V = SDValue(N, 0);
7118 NewSDValueDbgMsg(V, "Creating new node: ", this);
7119 return V;
7120}
7121
7122SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
7123 SDValue N1) {
7124 SDNodeFlags Flags;
7125 if (Inserter)
7126 Flags = Inserter->getFlags();
7127 return getNode(Opcode, DL, VT, N1, Flags);
7128}
7129
7130SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
7131 SDValue N1, const SDNodeFlags Flags) {
7132 assert(N1.getOpcode() != ISD::DELETED_NODE && "Operand is DELETED_NODE!");
7133
7134 // Constant fold unary operations with a vector integer or float operand.
7135 switch (Opcode) {
7136 default:
7137 // FIXME: Entirely reasonable to perform folding of other unary
7138 // operations here as the need arises.
7139 break;
7140 case ISD::FNEG:
7141 case ISD::FABS:
7142 case ISD::FCEIL:
7143 case ISD::FTRUNC:
7144 case ISD::FFLOOR:
7145 case ISD::FP_EXTEND:
7146 case ISD::FP_TO_SINT:
7147 case ISD::FP_TO_UINT:
7148 case ISD::FP_TO_FP16:
7149 case ISD::FP_TO_BF16:
7150 case ISD::TRUNCATE:
7151 case ISD::ANY_EXTEND:
7152 case ISD::ZERO_EXTEND:
7153 case ISD::SIGN_EXTEND:
7154 case ISD::UINT_TO_FP:
7155 case ISD::SINT_TO_FP:
7156 case ISD::FP16_TO_FP:
7157 case ISD::BF16_TO_FP:
7158 case ISD::BITCAST:
7159 case ISD::ABS:
7161 case ISD::BITREVERSE:
7162 case ISD::BSWAP:
7163 case ISD::CTLZ:
7165 case ISD::CTTZ:
7167 case ISD::CTPOP:
7168 case ISD::PARITY:
7169 case ISD::CTLS:
7170 case ISD::VECREDUCE_ADD:
7175 case ISD::VECREDUCE_MUL:
7176 case ISD::VECREDUCE_AND:
7177 case ISD::VECREDUCE_OR:
7178 case ISD::VECREDUCE_XOR:
7179 case ISD::STEP_VECTOR: {
7180 SDValue Ops = {N1};
7181 if (SDValue Fold = FoldConstantArithmetic(Opcode, DL, VT, Ops))
7182 return Fold;
7183 }
7184 }
7185
7186 unsigned OpOpcode = N1.getNode()->getOpcode();
7187 switch (Opcode) {
7188 case ISD::STEP_VECTOR:
7189 assert(VT.isScalableVector() &&
7190 "STEP_VECTOR can only be used with scalable types");
7191 assert(OpOpcode == ISD::TargetConstant &&
7192 VT.getVectorElementType() == N1.getValueType() &&
7193 "Unexpected step operand");
7194 break;
7195 case ISD::FREEZE:
7196 assert(VT == N1.getValueType() && "Unexpected VT!");
7198 return N1;
7199 break;
7200 case ISD::TokenFactor:
7201 case ISD::MERGE_VALUES:
7203 return N1; // Factor, merge or concat of one node? No need.
7204 case ISD::BUILD_VECTOR: {
7205 // Attempt to simplify BUILD_VECTOR.
7206 SDValue Ops[] = {N1};
7207 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
7208 return V;
7209 break;
7210 }
7211 case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node");
7212 case ISD::FP_EXTEND:
7214 "Invalid FP cast!");
7215 if (N1.getValueType() == VT) return N1; // noop conversion.
7216 assert((!VT.isVector() || VT.getVectorElementCount() ==
7218 "Vector element count mismatch!");
7219 assert(N1.getValueType().bitsLT(VT) && "Invalid fpext node, dst < src!");
7220 if (N1.isUndef())
7221 return getUNDEF(VT);
7222 break;
7223 case ISD::FP_TO_SINT:
7224 case ISD::FP_TO_UINT:
7225 if (N1.isUndef())
7226 return getUNDEF(VT);
7227 break;
7228 case ISD::SINT_TO_FP:
7229 case ISD::UINT_TO_FP:
7230 // [us]itofp(undef) = 0, because the result value is bounded.
7231 if (N1.isUndef())
7232 return getConstantFP(0.0, DL, VT);
7233 break;
7234 case ISD::SIGN_EXTEND:
7235 assert(VT.isInteger() && N1.getValueType().isInteger() &&
7236 "Invalid SIGN_EXTEND!");
7237 assert(VT.isVector() == N1.getValueType().isVector() &&
7238 "SIGN_EXTEND result type type should be vector iff the operand "
7239 "type is vector!");
7240 if (N1.getValueType() == VT) return N1; // noop extension
7241 assert((!VT.isVector() || VT.getVectorElementCount() ==
7243 "Vector element count mismatch!");
7244 assert(N1.getValueType().bitsLT(VT) && "Invalid sext node, dst < src!");
7245 if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND) {
7246 SDNodeFlags Flags;
7247 if (OpOpcode == ISD::ZERO_EXTEND)
7248 Flags.setNonNeg(N1->getFlags().hasNonNeg());
7249 SDValue NewVal = getNode(OpOpcode, DL, VT, N1.getOperand(0), Flags);
7250 transferDbgValues(N1, NewVal);
7251 return NewVal;
7252 }
7253
7254 if (OpOpcode == ISD::POISON)
7255 return getPOISON(VT);
7256
7257 if (N1.isUndef())
7258 // sext(undef) = 0, because the top bits will all be the same.
7259 return getConstant(0, DL, VT);
7260
7261 // Skip unnecessary sext_inreg pattern:
7262 // (sext (trunc x)) -> x iff the upper bits are all signbits.
7263 if (OpOpcode == ISD::TRUNCATE) {
7264 SDValue OpOp = N1.getOperand(0);
7265 if (OpOp.getValueType() == VT) {
7266 unsigned NumSignExtBits =
7268 if (ComputeNumSignBits(OpOp) > NumSignExtBits) {
7269 transferDbgValues(N1, OpOp);
7270 return OpOp;
7271 }
7272 }
7273 }
7274 break;
7275 case ISD::ZERO_EXTEND:
7276 assert(VT.isInteger() && N1.getValueType().isInteger() &&
7277 "Invalid ZERO_EXTEND!");
7278 assert(VT.isVector() == N1.getValueType().isVector() &&
7279 "ZERO_EXTEND result type type should be vector iff the operand "
7280 "type is vector!");
7281 if (N1.getValueType() == VT) return N1; // noop extension
7282 assert((!VT.isVector() || VT.getVectorElementCount() ==
7284 "Vector element count mismatch!");
7285 assert(N1.getValueType().bitsLT(VT) && "Invalid zext node, dst < src!");
7286 if (OpOpcode == ISD::ZERO_EXTEND) { // (zext (zext x)) -> (zext x)
7287 SDNodeFlags Flags;
7288 Flags.setNonNeg(N1->getFlags().hasNonNeg());
7289 SDValue NewVal =
7290 getNode(ISD::ZERO_EXTEND, DL, VT, N1.getOperand(0), Flags);
7291 transferDbgValues(N1, NewVal);
7292 return NewVal;
7293 }
7294
7295 if (OpOpcode == ISD::POISON)
7296 return getPOISON(VT);
7297
7298 if (N1.isUndef())
7299 // zext(undef) = 0, because the top bits will be zero.
7300 return getConstant(0, DL, VT);
7301
7302 // Skip unnecessary zext_inreg pattern:
7303 // (zext (trunc x)) -> x iff the upper bits are known zero.
7304 // TODO: Remove (zext (trunc (and x, c))) exception which some targets
7305 // use to recognise zext_inreg patterns.
7306 if (OpOpcode == ISD::TRUNCATE) {
7307 SDValue OpOp = N1.getOperand(0);
7308 if (OpOp.getValueType() == VT) {
7309 if (OpOp.getOpcode() != ISD::AND) {
7312 if (MaskedValueIsZero(OpOp, HiBits)) {
7313 transferDbgValues(N1, OpOp);
7314 return OpOp;
7315 }
7316 }
7317 }
7318 }
7319 break;
7320 case ISD::ANY_EXTEND:
7321 assert(VT.isInteger() && N1.getValueType().isInteger() &&
7322 "Invalid ANY_EXTEND!");
7323 assert(VT.isVector() == N1.getValueType().isVector() &&
7324 "ANY_EXTEND result type type should be vector iff the operand "
7325 "type is vector!");
7326 if (N1.getValueType() == VT) return N1; // noop extension
7327 assert((!VT.isVector() || VT.getVectorElementCount() ==
7329 "Vector element count mismatch!");
7330 assert(N1.getValueType().bitsLT(VT) && "Invalid anyext node, dst < src!");
7331
7332 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
7333 OpOpcode == ISD::ANY_EXTEND) {
7334 SDNodeFlags Flags;
7335 if (OpOpcode == ISD::ZERO_EXTEND)
7336 Flags.setNonNeg(N1->getFlags().hasNonNeg());
7337 // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x)
7338 return getNode(OpOpcode, DL, VT, N1.getOperand(0), Flags);
7339 }
7340 if (N1.isUndef())
7341 return getUNDEF(VT);
7342
7343 // (ext (trunc x)) -> x
7344 if (OpOpcode == ISD::TRUNCATE) {
7345 SDValue OpOp = N1.getOperand(0);
7346 if (OpOp.getValueType() == VT) {
7347 transferDbgValues(N1, OpOp);
7348 return OpOp;
7349 }
7350 }
7351 break;
7352 case ISD::TRUNCATE:
7353 assert(VT.isInteger() && N1.getValueType().isInteger() &&
7354 "Invalid TRUNCATE!");
7355 assert(VT.isVector() == N1.getValueType().isVector() &&
7356 "TRUNCATE result type type should be vector iff the operand "
7357 "type is vector!");
7358 if (N1.getValueType() == VT) return N1; // noop truncate
7359 assert((!VT.isVector() || VT.getVectorElementCount() ==
7361 "Vector element count mismatch!");
7362 assert(N1.getValueType().bitsGT(VT) && "Invalid truncate node, src < dst!");
7363 if (OpOpcode == ISD::TRUNCATE)
7364 return getNode(ISD::TRUNCATE, DL, VT, N1.getOperand(0));
7365 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
7366 OpOpcode == ISD::ANY_EXTEND) {
7367 // If the source is smaller than the dest, we still need an extend.
7369 VT.getScalarType())) {
7370 SDNodeFlags Flags;
7371 if (OpOpcode == ISD::ZERO_EXTEND)
7372 Flags.setNonNeg(N1->getFlags().hasNonNeg());
7373 return getNode(OpOpcode, DL, VT, N1.getOperand(0), Flags);
7374 }
7375 if (N1.getOperand(0).getValueType().bitsGT(VT))
7376 return getNode(ISD::TRUNCATE, DL, VT, N1.getOperand(0));
7377 return N1.getOperand(0);
7378 }
7379 if (N1.isUndef())
7380 return getUNDEF(VT);
7381 if (OpOpcode == ISD::VSCALE && !NewNodesMustHaveLegalTypes)
7382 return getVScale(DL, VT,
7384 break;
7388 assert(VT.isVector() && "This DAG node is restricted to vector types.");
7389 assert(N1.getValueType().bitsLE(VT) &&
7390 "The input must be the same size or smaller than the result.");
7393 "The destination vector type must have fewer lanes than the input.");
7394 break;
7395 case ISD::ABS:
7396 assert(VT.isInteger() && VT == N1.getValueType() && "Invalid ABS!");
7397 if (N1.isUndef())
7398 return getConstant(0, DL, VT);
7399 break;
7401 assert(VT.isInteger() && VT == N1.getValueType() &&
7402 "Invalid ABS_MIN_POISON!");
7403 if (N1.isUndef())
7404 return getConstant(0, DL, VT);
7405 break;
7406 case ISD::BSWAP:
7407 assert(VT.isInteger() && VT == N1.getValueType() && "Invalid BSWAP!");
7408 assert((VT.getScalarSizeInBits() % 16 == 0) &&
7409 "BSWAP types must be a multiple of 16 bits!");
7410 if (N1.isUndef())
7411 return getUNDEF(VT);
7412 // bswap(bswap(X)) -> X.
7413 if (OpOpcode == ISD::BSWAP)
7414 return N1.getOperand(0);
7415 break;
7416 case ISD::BITREVERSE:
7417 assert(VT.isInteger() && VT == N1.getValueType() && "Invalid BITREVERSE!");
7418 if (N1.isUndef())
7419 return getUNDEF(VT);
7420 break;
7421 case ISD::BITCAST:
7423 "Cannot BITCAST between types of different sizes!");
7424 if (VT == N1.getValueType()) return N1; // noop conversion.
7425 if (OpOpcode == ISD::BITCAST) // bitconv(bitconv(x)) -> bitconv(x)
7426 return getNode(ISD::BITCAST, DL, VT, N1.getOperand(0));
7427 if (N1.isUndef())
7428 return getUNDEF(VT);
7429 break;
7431 assert(VT.isVector() && !N1.getValueType().isVector() &&
7432 (VT.getVectorElementType() == N1.getValueType() ||
7434 N1.getValueType().isInteger() &&
7436 "Illegal SCALAR_TO_VECTOR node!");
7437 if (N1.isUndef())
7438 return getUNDEF(VT);
7439 // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
7440 if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
7442 N1.getConstantOperandVal(1) == 0 &&
7443 N1.getOperand(0).getValueType() == VT)
7444 return N1.getOperand(0);
7445 break;
7446 case ISD::FNEG:
7447 // Negation of an unknown bag of bits is still completely undefined.
7448 if (N1.isUndef())
7449 return getUNDEF(VT);
7450
7451 if (OpOpcode == ISD::FNEG) // --X -> X
7452 return N1.getOperand(0);
7453 break;
7454 case ISD::FABS:
7455 if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X)
7456 return getNode(ISD::FABS, DL, VT, N1.getOperand(0));
7457 break;
7458 case ISD::VSCALE:
7459 assert(VT == N1.getValueType() && "Unexpected VT!");
7460 break;
7461 case ISD::CTPOP:
7462 if (N1.getValueType().getScalarType() == MVT::i1)
7463 return N1;
7464 break;
7465 case ISD::CTLZ:
7466 case ISD::CTTZ:
7467 if (N1.getValueType().getScalarType() == MVT::i1)
7468 return getNOT(DL, N1, N1.getValueType());
7469 break;
7470 case ISD::CTLS:
7471 if (N1.getValueType().getScalarType() == MVT::i1)
7472 return getConstant(0, DL, VT);
7473 break;
7474 case ISD::VECREDUCE_ADD:
7475 if (N1.getValueType().getScalarType() == MVT::i1)
7476 return getNode(ISD::VECREDUCE_XOR, DL, VT, N1);
7477 break;
7480 if (N1.getValueType().getScalarType() == MVT::i1)
7481 return getNode(ISD::VECREDUCE_OR, DL, VT, N1);
7482 break;
7485 if (N1.getValueType().getScalarType() == MVT::i1)
7486 return getNode(ISD::VECREDUCE_AND, DL, VT, N1);
7487 break;
7489 // With a single lane, the result is true iff that lane is false.
7491 return getLogicalNOT(DL, N1, VT);
7492 break;
7493 case ISD::VECTOR_REPEAT:
7495 "VECTOR_REPEAT requires a fixed-length vector operand");
7496 assert(VT.isScalableVector() &&
7497 "VECTOR_REPEAT requires a scalable vector result");
7500 "VECTOR_REPEAT operand and result element counts must match");
7501 if (VT.getVectorMinNumElements() == 1)
7502 return getSplatVector(
7503 VT, DL, getExtractVectorElt(DL, VT.getVectorElementType(), N1, 0));
7504 break;
7505 case ISD::SPLAT_VECTOR:
7506 assert(VT.isVector() && "Wrong return type!");
7507 // FIXME: Hexagon uses i32 scalar for a floating point zero vector so allow
7508 // that for now.
7510 (VT.isFloatingPoint() && N1.getValueType() == MVT::i32) ||
7512 N1.getValueType().isInteger() &&
7514 "Wrong operand type!");
7515 break;
7516 }
7517
7518 SDNode *N;
7519 SDVTList VTs = getVTList(VT);
7520 SDValue Ops[] = {N1};
7521 if (VT != MVT::Glue) { // Don't CSE glue producing nodes
7522 SDNodeKey ID(Opcode, VTs, Ops);
7523 FoldingSetInsertToken InsertToken;
7524 if (SDNode *E = lookupNode(ID, DL, InsertToken)) {
7525 E->intersectFlagsWith(Flags);
7526 return SDValue(E, 0);
7527 }
7528
7529 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
7530 N->setFlags(Flags);
7531 createOperands(N, Ops);
7532 CSEMap.insert(N, InsertToken);
7533 } else {
7534 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
7535 createOperands(N, Ops);
7536 }
7537
7538 InsertNode(N);
7539 SDValue V = SDValue(N, 0);
7540 NewSDValueDbgMsg(V, "Creating new node: ", this);
7541 return V;
7542}
7543
7544static APInt getIntegerIdentity(unsigned Opcode, unsigned BitWidth) {
7545 switch (Opcode) {
7546 default:
7547 llvm_unreachable("Unexpected integer identity opcode");
7548 case ISD::ADD:
7549 case ISD::OR:
7550 case ISD::XOR:
7551 case ISD::UMAX:
7552 return APInt::getZero(BitWidth);
7553 case ISD::MUL:
7554 return APInt(BitWidth, 1);
7555 case ISD::AND:
7556 case ISD::UMIN:
7558 case ISD::SMAX:
7560 case ISD::SMIN:
7562 }
7563}
7564
7565static std::optional<APInt> FoldValue(unsigned Opcode, const APInt &C1,
7566 const APInt &C2) {
7567 switch (Opcode) {
7568 case ISD::ADD: return C1 + C2;
7569 case ISD::SUB: return C1 - C2;
7570 case ISD::MUL: return C1 * C2;
7571 case ISD::AND: return C1 & C2;
7572 case ISD::OR: return C1 | C2;
7573 case ISD::XOR: return C1 ^ C2;
7574 case ISD::SHL: return C1 << C2;
7575 case ISD::SRL: return C1.lshr(C2);
7576 case ISD::SRA: return C1.ashr(C2);
7577 case ISD::ROTL: return C1.rotl(C2);
7578 case ISD::ROTR: return C1.rotr(C2);
7579 case ISD::SMIN: return C1.sle(C2) ? C1 : C2;
7580 case ISD::SMAX: return C1.sge(C2) ? C1 : C2;
7581 case ISD::UMIN: return C1.ule(C2) ? C1 : C2;
7582 case ISD::UMAX: return C1.uge(C2) ? C1 : C2;
7583 case ISD::SADDSAT: return C1.sadd_sat(C2);
7584 case ISD::UADDSAT: return C1.uadd_sat(C2);
7585 case ISD::SSUBSAT: return C1.ssub_sat(C2);
7586 case ISD::USUBSAT: return C1.usub_sat(C2);
7587 case ISD::SSHLSAT: return C1.sshl_sat(C2);
7588 case ISD::USHLSAT: return C1.ushl_sat(C2);
7589 case ISD::UDIV:
7590 if (!C2.getBoolValue())
7591 break;
7592 return C1.udiv(C2);
7593 case ISD::UREM:
7594 if (!C2.getBoolValue())
7595 break;
7596 return C1.urem(C2);
7597 case ISD::SDIV:
7598 if (!C2.getBoolValue())
7599 break;
7600 return C1.sdiv(C2);
7601 case ISD::SREM:
7602 if (!C2.getBoolValue())
7603 break;
7604 return C1.srem(C2);
7605 case ISD::AVGFLOORS:
7606 return APIntOps::avgFloorS(C1, C2);
7607 case ISD::AVGFLOORU:
7608 return APIntOps::avgFloorU(C1, C2);
7609 case ISD::AVGCEILS:
7610 return APIntOps::avgCeilS(C1, C2);
7611 case ISD::AVGCEILU:
7612 return APIntOps::avgCeilU(C1, C2);
7613 case ISD::ABDS:
7614 return APIntOps::abds(C1, C2);
7615 case ISD::ABDU:
7616 return APIntOps::abdu(C1, C2);
7617 case ISD::MULHS:
7618 return APIntOps::mulhs(C1, C2);
7619 case ISD::MULHU:
7620 return APIntOps::mulhu(C1, C2);
7621 case ISD::CLMUL:
7622 return APIntOps::clmul(C1, C2);
7623 case ISD::CLMULR:
7624 return APIntOps::clmulr(C1, C2);
7625 case ISD::CLMULH:
7626 return APIntOps::clmulh(C1, C2);
7627 case ISD::PEXT:
7628 return APIntOps::pext(C1, C2);
7629 case ISD::PDEP:
7630 return APIntOps::pdep(C1, C2);
7631 }
7632 return std::nullopt;
7633}
7634// Handle constant folding with UNDEF.
7635// TODO: Handle more cases.
7636static std::optional<APInt> FoldValueWithUndef(unsigned Opcode, const APInt &C1,
7637 bool IsUndef1, const APInt &C2,
7638 bool IsUndef2) {
7639 if (!(IsUndef1 || IsUndef2))
7640 return FoldValue(Opcode, C1, C2);
7641
7642 // Fold and(x, undef) -> 0
7643 // Fold mul(x, undef) -> 0
7644 if (Opcode == ISD::AND || Opcode == ISD::MUL)
7645 return APInt::getZero(C1.getBitWidth());
7646
7647 return std::nullopt;
7648}
7649
7651 const GlobalAddressSDNode *GA,
7652 const SDNode *N2) {
7653 if (GA->getOpcode() != ISD::GlobalAddress)
7654 return SDValue();
7655 if (!TLI->isOffsetFoldingLegal(GA))
7656 return SDValue();
7657 auto *C2 = dyn_cast<ConstantSDNode>(N2);
7658 if (!C2)
7659 return SDValue();
7660 int64_t Offset = C2->getSExtValue();
7661 switch (Opcode) {
7662 case ISD::ADD:
7663 case ISD::PTRADD:
7664 break;
7665 case ISD::SUB: Offset = -uint64_t(Offset); break;
7666 default: return SDValue();
7667 }
7668 return getGlobalAddress(GA->getGlobal(), SDLoc(C2), VT,
7669 GA->getOffset() + uint64_t(Offset));
7670}
7671
7673 switch (Opcode) {
7674 case ISD::SDIV:
7675 case ISD::UDIV:
7676 case ISD::SREM:
7677 case ISD::UREM: {
7678 // If a divisor is zero/undef or any element of a divisor vector is
7679 // zero/undef, the whole op is undef.
7680 assert(Ops.size() == 2 && "Div/rem should have 2 operands");
7681 SDValue Divisor = Ops[1];
7682 if (Divisor.isUndef() || isNullConstant(Divisor))
7683 return true;
7684
7685 return ISD::isBuildVectorOfConstantSDNodes(Divisor.getNode()) &&
7686 llvm::any_of(Divisor->op_values(),
7687 [](SDValue V) { return V.isUndef() ||
7688 isNullConstant(V); });
7689 // TODO: Handle signed overflow.
7690 }
7691 // TODO: Handle oversized shifts.
7692 default:
7693 return false;
7694 }
7695}
7696
7699 SDNodeFlags Flags) {
7700 // If the opcode is a target-specific ISD node, there's nothing we can
7701 // do here and the operand rules may not line up with the below, so
7702 // bail early.
7703 // We can't create a scalar CONCAT_VECTORS so skip it. It will break
7704 // for concats involving SPLAT_VECTOR. Concats of BUILD_VECTORS are handled by
7705 // foldCONCAT_VECTORS in getNode before this is called.
7706 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::CONCAT_VECTORS)
7707 return SDValue();
7708
7709 unsigned NumOps = Ops.size();
7710 if (NumOps == 0)
7711 return SDValue();
7712
7713 if (isUndef(Opcode, Ops))
7714 return getUNDEF(VT);
7715
7716 // Handle unary special cases.
7717 if (NumOps == 1) {
7718 SDValue N1 = Ops[0];
7719
7720 // Constant fold unary operations with an integer constant operand. Even
7721 // opaque constant will be folded, because the folding of unary operations
7722 // doesn't create new constants with different values. Nevertheless, the
7723 // opaque flag is preserved during folding to prevent future folding with
7724 // other constants.
7725 if (auto *C = dyn_cast<ConstantSDNode>(N1)) {
7726 const APInt &Val = C->getAPIntValue();
7727 switch (Opcode) {
7728 case ISD::SIGN_EXTEND:
7729 return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
7730 C->isTargetOpcode(), C->isOpaque());
7731 case ISD::TRUNCATE:
7732 if (C->isOpaque())
7733 break;
7734 [[fallthrough]];
7735 case ISD::ZERO_EXTEND:
7736 return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
7737 C->isTargetOpcode(), C->isOpaque());
7738 case ISD::ANY_EXTEND:
7739 // Some targets like RISCV prefer to sign extend some types.
7740 if (TLI->isSExtCheaperThanZExt(N1.getValueType(), VT))
7741 return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
7742 C->isTargetOpcode(), C->isOpaque());
7743 return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
7744 C->isTargetOpcode(), C->isOpaque());
7745 case ISD::ABS:
7746 return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(),
7747 C->isOpaque());
7749 if (Val.isMinSignedValue())
7750 return getPOISON(VT);
7751 return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(),
7752 C->isOpaque());
7753 case ISD::BITREVERSE:
7754 return getConstant(Val.reverseBits(), DL, VT, C->isTargetOpcode(),
7755 C->isOpaque());
7756 case ISD::BSWAP:
7757 return getConstant(Val.byteSwap(), DL, VT, C->isTargetOpcode(),
7758 C->isOpaque());
7759 case ISD::CTPOP:
7760 return getConstant(Val.popcount(), DL, VT, C->isTargetOpcode(),
7761 C->isOpaque());
7762 case ISD::PARITY:
7763 return getConstant(Val.popcount() & 1, DL, VT, C->isTargetOpcode(),
7764 C->isOpaque());
7765 case ISD::CTLZ:
7767 return getConstant(Val.countl_zero(), DL, VT, C->isTargetOpcode(),
7768 C->isOpaque());
7769 case ISD::CTTZ:
7771 return getConstant(Val.countr_zero(), DL, VT, C->isTargetOpcode(),
7772 C->isOpaque());
7773 case ISD::CTLS:
7774 // CTLS returns the number of extra sign bits so subtract one.
7775 return getConstant(Val.getNumSignBits() - 1, DL, VT,
7776 C->isTargetOpcode(), C->isOpaque());
7777 case ISD::UINT_TO_FP:
7778 case ISD::SINT_TO_FP: {
7780 (void)FPV.convertFromAPInt(Val, Opcode == ISD::SINT_TO_FP,
7782 return getConstantFP(FPV, DL, VT);
7783 }
7784 case ISD::FP16_TO_FP:
7785 case ISD::BF16_TO_FP: {
7786 bool Ignored;
7787 APFloat FPV(Opcode == ISD::FP16_TO_FP ? APFloat::IEEEhalf()
7788 : APFloat::BFloat(),
7789 (Val.getBitWidth() == 16) ? Val : Val.trunc(16));
7790
7791 // This can return overflow, underflow, or inexact; we don't care.
7792 // FIXME need to be more flexible about rounding mode.
7794 &Ignored);
7795 return getConstantFP(FPV, DL, VT);
7796 }
7797 case ISD::STEP_VECTOR:
7798 if (SDValue V = FoldSTEP_VECTOR(DL, VT, N1, *this))
7799 return V;
7800 break;
7801 case ISD::BITCAST:
7802 if (VT == MVT::f16 && C->getValueType(0) == MVT::i16)
7803 return getConstantFP(APFloat(APFloat::IEEEhalf(), Val), DL, VT);
7804 if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
7805 return getConstantFP(APFloat(APFloat::IEEEsingle(), Val), DL, VT);
7806 if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
7807 return getConstantFP(APFloat(APFloat::IEEEdouble(), Val), DL, VT);
7808 if (VT == MVT::f128 && C->getValueType(0) == MVT::i128)
7809 return getConstantFP(APFloat(APFloat::IEEEquad(), Val), DL, VT);
7810 break;
7811 }
7812 }
7813
7814 // Constant fold unary operations with a floating point constant operand.
7815 if (auto *C = dyn_cast<ConstantFPSDNode>(N1)) {
7816 APFloat V = C->getValueAPF(); // make copy
7817 switch (Opcode) {
7818 case ISD::FNEG:
7819 V.changeSign();
7820 return getConstantFP(V, DL, VT);
7821 case ISD::FABS:
7822 V.clearSign();
7823 return getConstantFP(V, DL, VT);
7824 case ISD::FCEIL: {
7825 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardPositive);
7827 return getConstantFP(V, DL, VT);
7828 return SDValue();
7829 }
7830 case ISD::FTRUNC: {
7831 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardZero);
7833 return getConstantFP(V, DL, VT);
7834 return SDValue();
7835 }
7836 case ISD::FFLOOR: {
7837 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardNegative);
7839 return getConstantFP(V, DL, VT);
7840 return SDValue();
7841 }
7842 case ISD::FP_EXTEND: {
7843 bool ignored;
7844 // This can return overflow, underflow, or inexact; we don't care.
7845 // FIXME need to be more flexible about rounding mode.
7846 (void)V.convert(VT.getFltSemantics(), APFloat::rmNearestTiesToEven,
7847 &ignored);
7848 return getConstantFP(V, DL, VT);
7849 }
7850 case ISD::FP_TO_SINT:
7851 case ISD::FP_TO_UINT: {
7852 bool ignored;
7853 APSInt IntVal(VT.getSizeInBits(), Opcode == ISD::FP_TO_UINT);
7854 // FIXME need to be more flexible about rounding mode.
7856 V.convertToInteger(IntVal, APFloat::rmTowardZero, &ignored);
7857 if (s == APFloat::opInvalidOp) // inexact is OK, in fact usual
7858 break;
7859 return getConstant(IntVal, DL, VT);
7860 }
7861 case ISD::FP_TO_FP16:
7862 case ISD::FP_TO_BF16: {
7863 bool Ignored;
7864 // This can return overflow, underflow, or inexact; we don't care.
7865 // FIXME need to be more flexible about rounding mode.
7866 (void)V.convert(Opcode == ISD::FP_TO_FP16 ? APFloat::IEEEhalf()
7867 : APFloat::BFloat(),
7869 return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
7870 }
7871 case ISD::BITCAST:
7872 if (VT == MVT::i16 && C->getValueType(0) == MVT::f16)
7873 return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL,
7874 VT);
7875 if (VT == MVT::i16 && C->getValueType(0) == MVT::bf16)
7876 return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL,
7877 VT);
7878 if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
7879 return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), DL,
7880 VT);
7881 if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
7882 return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
7883 break;
7884 }
7885 }
7886
7887 // Early-out if we failed to constant fold a bitcast.
7888 if (Opcode == ISD::BITCAST)
7889 return SDValue();
7890
7891 // Constant fold integer vector reductions with constant BUILD_VECTORs.
7892 if ((Opcode == ISD::VECREDUCE_ADD || Opcode == ISD::VECREDUCE_SMAX ||
7893 Opcode == ISD::VECREDUCE_SMIN || Opcode == ISD::VECREDUCE_UMAX ||
7894 Opcode == ISD::VECREDUCE_UMIN || Opcode == ISD::VECREDUCE_MUL ||
7895 Opcode == ISD::VECREDUCE_OR || Opcode == ISD::VECREDUCE_XOR ||
7896 Opcode == ISD::VECREDUCE_AND) &&
7898 unsigned EltBits = N1.getValueType().getScalarSizeInBits();
7899 unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Opcode);
7900 APInt Acc = getIntegerIdentity(BaseOpcode, EltBits);
7901 for (SDValue Elt : N1->op_values()) {
7902 if (Elt.getOpcode() == ISD::POISON)
7903 return getPOISON(VT);
7904 if (Elt.isUndef() || cast<ConstantSDNode>(Elt)->isOpaque())
7905 return SDValue();
7906 APInt Value = cast<ConstantSDNode>(Elt)->getAPIntValue().trunc(EltBits);
7907 std::optional<APInt> Folded = FoldValue(BaseOpcode, Acc, Value);
7908 assert(Folded &&
7909 "Expected vector reduction base opcode to be foldable");
7910 Acc = *Folded;
7911 }
7912 EVT EltVT = N1.getValueType().getScalarType();
7913 return getAnyExtOrTrunc(getConstant(Acc, DL, EltVT), DL, VT);
7914 }
7915 }
7916
7917 // Handle binops special cases.
7918 if (NumOps == 2) {
7919 if (SDValue CFP = foldConstantFPMath(Opcode, DL, VT, Ops))
7920 return CFP;
7921
7922 if (auto *C1 = dyn_cast<ConstantSDNode>(Ops[0])) {
7923 if (auto *C2 = dyn_cast<ConstantSDNode>(Ops[1])) {
7924 if (C1->isOpaque() || C2->isOpaque())
7925 return SDValue();
7926
7927 std::optional<APInt> FoldAttempt =
7928 FoldValue(Opcode, C1->getAPIntValue(), C2->getAPIntValue());
7929 if (!FoldAttempt)
7930 return SDValue();
7931
7932 SDValue Folded = getConstant(*FoldAttempt, DL, VT);
7933 assert((!Folded || !VT.isVector()) &&
7934 "Can't fold vectors ops with scalar operands");
7935 return Folded;
7936 }
7937 }
7938
7939 // fold (add Sym, c) -> Sym+c
7941 return FoldSymbolOffset(Opcode, VT, GA, Ops[1].getNode());
7942 if (TLI->isCommutativeBinOp(Opcode))
7944 return FoldSymbolOffset(Opcode, VT, GA, Ops[0].getNode());
7945
7946 // fold (sext_in_reg c1) -> c2
7947 if (Opcode == ISD::SIGN_EXTEND_INREG) {
7948 EVT EVT = cast<VTSDNode>(Ops[1])->getVT();
7949
7950 auto SignExtendInReg = [&](APInt Val, llvm::EVT ConstantVT) {
7951 unsigned FromBits = EVT.getScalarSizeInBits();
7952 Val <<= Val.getBitWidth() - FromBits;
7953 Val.ashrInPlace(Val.getBitWidth() - FromBits);
7954 return getConstant(Val, DL, ConstantVT);
7955 };
7956
7957 if (auto *C1 = dyn_cast<ConstantSDNode>(Ops[0])) {
7958 const APInt &Val = C1->getAPIntValue();
7959 return SignExtendInReg(Val, VT);
7960 }
7961
7963 SmallVector<SDValue, 8> ScalarOps;
7964 llvm::EVT OpVT = Ops[0].getOperand(0).getValueType();
7965 for (int I = 0, E = VT.getVectorNumElements(); I != E; ++I) {
7966 SDValue Op = Ops[0].getOperand(I);
7967 if (Op.isUndef()) {
7968 ScalarOps.push_back(getUNDEF(OpVT));
7969 continue;
7970 }
7971 const APInt &Val = cast<ConstantSDNode>(Op)->getAPIntValue();
7972 ScalarOps.push_back(SignExtendInReg(Val, OpVT));
7973 }
7974 return getBuildVector(VT, DL, ScalarOps);
7975 }
7976
7977 if (Ops[0].getOpcode() == ISD::SPLAT_VECTOR &&
7978 isa<ConstantSDNode>(Ops[0].getOperand(0)))
7979 return getNode(ISD::SPLAT_VECTOR, DL, VT,
7980 SignExtendInReg(Ops[0].getConstantOperandAPInt(0),
7981 Ops[0].getOperand(0).getValueType()));
7982 }
7983 }
7984
7985 // Handle fshl/fshr special cases.
7986 if (Opcode == ISD::FSHL || Opcode == ISD::FSHR) {
7987 auto *C1 = dyn_cast<ConstantSDNode>(Ops[0]);
7988 auto *C2 = dyn_cast<ConstantSDNode>(Ops[1]);
7989 auto *C3 = dyn_cast<ConstantSDNode>(Ops[2]);
7990
7991 if (C1 && C2 && C3) {
7992 if (C1->isOpaque() || C2->isOpaque() || C3->isOpaque())
7993 return SDValue();
7994 const APInt &V1 = C1->getAPIntValue(), &V2 = C2->getAPIntValue(),
7995 &V3 = C3->getAPIntValue();
7996
7997 APInt FoldedVal = Opcode == ISD::FSHL ? APIntOps::fshl(V1, V2, V3)
7998 : APIntOps::fshr(V1, V2, V3);
7999 return getConstant(FoldedVal, DL, VT);
8000 }
8001 }
8002
8003 // Handle fma/fmad special cases.
8004 if (Opcode == ISD::FMA || Opcode == ISD::FMAD || Opcode == ISD::FMULADD) {
8005 assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
8006 assert(Ops[0].getValueType() == VT && Ops[1].getValueType() == VT &&
8007 Ops[2].getValueType() == VT && "FMA types must match!");
8011 if (C1 && C2 && C3) {
8012 APFloat V1 = C1->getValueAPF();
8013 const APFloat &V2 = C2->getValueAPF();
8014 const APFloat &V3 = C3->getValueAPF();
8015 if (Opcode == ISD::FMAD || Opcode == ISD::FMULADD) {
8016 V1.multiply(V2, APFloat::rmNearestTiesToEven);
8018 } else
8019 V1.fusedMultiplyAdd(V2, V3, APFloat::rmNearestTiesToEven);
8020 return getConstantFP(V1, DL, VT);
8021 }
8022 }
8023
8024 // This is for vector folding only from here on.
8025 if (!VT.isVector())
8026 return SDValue();
8027
8028 // Constant fold integer partial reductions with constant BUILD_VECTOR
8029 // operands. The reduction order is deliberately unspecified. Use the same
8030 // subvector layout as TargetLowering::expandPartialReduceMLA(), where input
8031 // lane I contributes to accumulator lane I % NumAccElts.
8032 if (Opcode == ISD::PARTIAL_REDUCE_SMLA ||
8033 Opcode == ISD::PARTIAL_REDUCE_UMLA ||
8034 Opcode == ISD::PARTIAL_REDUCE_SUMLA) {
8035 // These nodes have no scalar form, so unsupported cases must not fall
8036 // through to generic per-lane vector folding.
8037 if (!llvm::all_of(Ops, [](SDValue Op) {
8038 return ISD::isBuildVectorOfConstantSDNodes(Op.getNode());
8039 }))
8040 return SDValue();
8041
8042 unsigned AccEltBits = VT.getScalarSizeInBits();
8043 unsigned InputEltBits = Ops[1].getScalarValueSizeInBits();
8044 unsigned NumAccElts = VT.getVectorNumElements();
8045 unsigned NumInputElts = Ops[1].getValueType().getVectorNumElements();
8046 SmallVector<APInt, 8> Results(NumAccElts, APInt::getZero(AccEltBits));
8047 BitVector PoisonElts(NumAccElts);
8048
8049 for (unsigned I = 0; I != NumAccElts; ++I) {
8050 SDValue Elt = Ops[0].getOperand(I);
8051 if (Elt.getOpcode() == ISD::POISON) {
8052 PoisonElts.set(I);
8053 continue;
8054 }
8055 auto *C = dyn_cast<ConstantSDNode>(Elt);
8056 if (!C || C->isOpaque())
8057 return SDValue();
8058 Results[I] = C->getAPIntValue().trunc(AccEltBits);
8059 }
8060
8061 bool IsLHSSigned = Opcode != ISD::PARTIAL_REDUCE_UMLA;
8062 bool IsRHSSigned = Opcode == ISD::PARTIAL_REDUCE_SMLA;
8063 for (unsigned I = 0; I != NumInputElts; ++I) {
8064 const unsigned AccIdx = I % NumAccElts;
8065 SDValue LHSElt = Ops[1].getOperand(I);
8066 SDValue RHSElt = Ops[2].getOperand(I);
8067 if (LHSElt.getOpcode() == ISD::POISON ||
8068 RHSElt.getOpcode() == ISD::POISON) {
8069 PoisonElts.set(AccIdx);
8070 continue;
8071 }
8072
8073 auto *LHS = dyn_cast<ConstantSDNode>(LHSElt);
8074 auto *RHS = dyn_cast<ConstantSDNode>(RHSElt);
8075 if (!LHS || !RHS || LHS->isOpaque() || RHS->isOpaque())
8076 return SDValue();
8077
8078 APInt LHSVal = LHS->getAPIntValue().trunc(InputEltBits);
8079 APInt RHSVal = RHS->getAPIntValue().trunc(InputEltBits);
8080 LHSVal = IsLHSSigned ? LHSVal.sext(AccEltBits) : LHSVal.zext(AccEltBits);
8081 RHSVal = IsRHSSigned ? RHSVal.sext(AccEltBits) : RHSVal.zext(AccEltBits);
8082 Results[AccIdx] += LHSVal * RHSVal;
8083 }
8084
8085 // After type legalization the vector element type may not be a legal
8086 // scalar type (e.g. i16 on AArch64). Create the folded constants in the
8087 // promoted legal scalar type instead, matching the generic per-lane path
8088 // below. Bail out if legalization would narrow the type, since the lane
8089 // value would not fit.
8090 EVT AccEltVT = VT.getVectorElementType();
8091 EVT LegalSVT = AccEltVT;
8092 if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
8093 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
8094 if (LegalSVT.bitsLT(AccEltVT))
8095 return SDValue();
8096 }
8097
8098 SmallVector<SDValue, 8> ResultOps;
8099 for (unsigned I = 0; I != NumAccElts; ++I)
8100 ResultOps.push_back(
8101 PoisonElts[I] ? getPOISON(LegalSVT)
8102 : getConstant(Results[I].sext(LegalSVT.getSizeInBits()),
8103 DL, LegalSVT));
8104 return getBuildVector(VT, DL, ResultOps);
8105 }
8106
8107 ElementCount NumElts = VT.getVectorElementCount();
8108
8109 // See if we can fold through any bitcasted integer ops.
8110 if (NumOps == 2 && VT.isFixedLengthVector() && VT.isInteger() &&
8111 Ops[0].getValueType() == VT && Ops[1].getValueType() == VT &&
8112 (Ops[0].getOpcode() == ISD::BITCAST ||
8113 Ops[1].getOpcode() == ISD::BITCAST)) {
8116 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
8117 auto *BV2 = dyn_cast<BuildVectorSDNode>(N2);
8118 if (BV1 && BV2 && N1.getValueType().isInteger() &&
8119 N2.getValueType().isInteger()) {
8120 bool IsLE = getDataLayout().isLittleEndian();
8121 unsigned EltBits = VT.getScalarSizeInBits();
8122 SmallVector<APInt> RawBits1, RawBits2;
8123 BitVector UndefElts1, UndefElts2;
8124 if (BV1->getConstantRawBits(IsLE, EltBits, RawBits1, UndefElts1) &&
8125 BV2->getConstantRawBits(IsLE, EltBits, RawBits2, UndefElts2)) {
8126 SmallVector<APInt> RawBits;
8127 for (unsigned I = 0, E = NumElts.getFixedValue(); I != E; ++I) {
8128 std::optional<APInt> Fold = FoldValueWithUndef(
8129 Opcode, RawBits1[I], UndefElts1[I], RawBits2[I], UndefElts2[I]);
8130 if (!Fold)
8131 break;
8132 RawBits.push_back(*Fold);
8133 }
8134 if (RawBits.size() == NumElts.getFixedValue()) {
8135 // We have constant folded, but we might need to cast this again back
8136 // to the original (possibly legalized) type.
8137 EVT BVVT, BVEltVT;
8138 if (N1.getValueType() == VT) {
8139 BVVT = N1.getValueType();
8140 BVEltVT = BV1->getOperand(0).getValueType();
8141 } else {
8142 BVVT = N2.getValueType();
8143 BVEltVT = BV2->getOperand(0).getValueType();
8144 }
8145 unsigned BVEltBits = BVEltVT.getSizeInBits();
8146 SmallVector<APInt> DstBits;
8147 BitVector DstUndefs;
8149 DstBits, RawBits, DstUndefs,
8150 BitVector(RawBits.size(), false));
8151 SmallVector<SDValue> Ops(DstBits.size(), getUNDEF(BVEltVT));
8152 for (unsigned I = 0, E = DstBits.size(); I != E; ++I) {
8153 if (DstUndefs[I])
8154 continue;
8155 Ops[I] = getConstant(DstBits[I].sext(BVEltBits), DL, BVEltVT);
8156 }
8157 return getBitcast(VT, getBuildVector(BVVT, DL, Ops));
8158 }
8159 }
8160 }
8161 // Logic ops can be folded from raw integer bits - mainly for AVX512 masks.
8162 if (ISD::isBitwiseLogicOp(Opcode) && isa<ConstantSDNode>(N1) &&
8163 isa<ConstantSDNode>(N2)) {
8164 if (SDValue Res = FoldConstantArithmetic(Opcode, DL, N1.getValueType(),
8165 {N1, N2}, Flags))
8166 return getBitcast(VT, Res);
8167 }
8168 }
8169
8170 // Fold (mul step_vector(C0), C1) to (step_vector(C0 * C1)).
8171 // (shl step_vector(C0), C1) -> (step_vector(C0 << C1))
8172 if ((Opcode == ISD::MUL || Opcode == ISD::SHL) &&
8173 Ops[0].getOpcode() == ISD::STEP_VECTOR) {
8174 APInt RHSVal;
8175 if (ISD::isConstantSplatVector(Ops[1].getNode(), RHSVal)) {
8176 APInt NewStep = Opcode == ISD::MUL
8177 ? Ops[0].getConstantOperandAPInt(0) * RHSVal
8178 : Ops[0].getConstantOperandAPInt(0) << RHSVal;
8179 return getStepVector(DL, VT, NewStep);
8180 }
8181 }
8182
8183 auto IsScalarOrSameVectorSize = [NumElts](const SDValue &Op) {
8184 return !Op.getValueType().isVector() ||
8185 Op.getValueType().getVectorElementCount() == NumElts;
8186 };
8187
8188 auto IsBuildVectorSplatVectorOrUndef = [](const SDValue &Op) {
8189 return Op.isUndef() || Op.getOpcode() == ISD::CONDCODE ||
8190 Op.getOpcode() == ISD::BUILD_VECTOR ||
8191 Op.getOpcode() == ISD::SPLAT_VECTOR;
8192 };
8193
8194 // All operands must be vector types with the same number of elements as
8195 // the result type and must be either UNDEF or a build/splat vector
8196 // or UNDEF scalars.
8197 if (!llvm::all_of(Ops, IsBuildVectorSplatVectorOrUndef) ||
8198 !llvm::all_of(Ops, IsScalarOrSameVectorSize))
8199 return SDValue();
8200
8201 // If we are comparing vectors, then the result needs to be a i1 boolean that
8202 // is then extended back to the legal result type depending on how booleans
8203 // are represented.
8204 EVT SVT = (Opcode == ISD::SETCC ? MVT::i1 : VT.getScalarType());
8205 ISD::NodeType ExtendCode =
8206 (Opcode == ISD::SETCC && SVT != VT.getScalarType())
8207 ? TargetLowering::getExtendForContent(TLI->getBooleanContents(VT))
8209
8210 // Find legal integer scalar type for constant promotion and
8211 // ensure that its scalar size is at least as large as source.
8212 EVT LegalSVT = VT.getScalarType();
8213 if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
8214 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
8215 if (LegalSVT.bitsLT(VT.getScalarType()))
8216 return SDValue();
8217 }
8218
8219 // For scalable vector types we know we're dealing with SPLAT_VECTORs. We
8220 // only have one operand to check. For fixed-length vector types we may have
8221 // a combination of BUILD_VECTOR and SPLAT_VECTOR.
8222 unsigned NumVectorElts = NumElts.isScalable() ? 1 : NumElts.getFixedValue();
8223
8224 // Constant fold each scalar lane separately.
8225 SmallVector<SDValue, 4> ScalarResults;
8226 for (unsigned I = 0; I != NumVectorElts; I++) {
8227 SmallVector<SDValue, 4> ScalarOps;
8228 for (SDValue Op : Ops) {
8229 EVT InSVT = Op.getValueType().getScalarType();
8230 if (Op.getOpcode() != ISD::BUILD_VECTOR &&
8231 Op.getOpcode() != ISD::SPLAT_VECTOR) {
8232 if (Op.isUndef())
8233 ScalarOps.push_back(getUNDEF(InSVT));
8234 else
8235 ScalarOps.push_back(Op);
8236 continue;
8237 }
8238
8239 SDValue ScalarOp =
8240 Op.getOperand(Op.getOpcode() == ISD::SPLAT_VECTOR ? 0 : I);
8241 EVT ScalarVT = ScalarOp.getValueType();
8242
8243 // Build vector (integer) scalar operands may need implicit
8244 // truncation - do this before constant folding.
8245 if (ScalarVT.isInteger() && ScalarVT.bitsGT(InSVT)) {
8246 // Don't create illegally-typed nodes unless they're constants or undef
8247 // - if we fail to constant fold we can't guarantee the (dead) nodes
8248 // we're creating will be cleaned up before being visited for
8249 // legalization.
8250 if (NewNodesMustHaveLegalTypes && !ScalarOp.isUndef() &&
8251 !isa<ConstantSDNode>(ScalarOp) &&
8252 TLI->getTypeAction(*getContext(), InSVT) !=
8254 return SDValue();
8255 ScalarOp = getNode(ISD::TRUNCATE, DL, InSVT, ScalarOp);
8256 }
8257
8258 ScalarOps.push_back(ScalarOp);
8259 }
8260
8261 // Constant fold the scalar operands.
8262 SDValue ScalarResult = getNode(Opcode, DL, SVT, ScalarOps, Flags);
8263
8264 // Scalar folding only succeeded if the result is a constant or UNDEF.
8265 if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant &&
8266 ScalarResult.getOpcode() != ISD::ConstantFP)
8267 return SDValue();
8268
8269 // Legalize the (integer) scalar constant if necessary. We only do
8270 // this once we know the folding succeeded, since otherwise we would
8271 // get a node with illegal type which has a user.
8272 if (LegalSVT != SVT)
8273 ScalarResult = getNode(ExtendCode, DL, LegalSVT, ScalarResult);
8274
8275 ScalarResults.push_back(ScalarResult);
8276 }
8277
8278 SDValue V = NumElts.isScalable() ? getSplatVector(VT, DL, ScalarResults[0])
8279 : getBuildVector(VT, DL, ScalarResults);
8280 NewSDValueDbgMsg(V, "New node fold constant vector: ", this);
8281 return V;
8282}
8283
8285 SDVTList VTList,
8287 SDNodeFlags Flags) {
8288 if (VTList.NumVTs == 1)
8289 return FoldConstantArithmetic(Opcode, DL, VTList.VTs[0], Ops, Flags);
8290
8291 switch (Opcode) {
8292 case ISD::SADDO:
8293 case ISD::UADDO:
8294 case ISD::SSUBO:
8295 case ISD::USUBO:
8296 case ISD::SMULO:
8297 case ISD::UMULO: {
8298 // TODO: Support non-splat vector constants.
8301 if (!C1 || !C2 || C1->isOpaque() || C2->isOpaque())
8302 return SDValue();
8303
8304 const APInt &V1 = C1->getAPIntValue(), &V2 = C2->getAPIntValue();
8305 bool Overflow;
8306 APInt Result;
8307 switch (Opcode) {
8308 default:
8309 llvm_unreachable("Unexpected overflow opcode");
8310 case ISD::SADDO:
8311 Result = V1.sadd_ov(V2, Overflow);
8312 break;
8313 case ISD::UADDO:
8314 Result = V1.uadd_ov(V2, Overflow);
8315 break;
8316 case ISD::SSUBO:
8317 Result = V1.ssub_ov(V2, Overflow);
8318 break;
8319 case ISD::USUBO:
8320 Result = V1.usub_ov(V2, Overflow);
8321 break;
8322 case ISD::SMULO:
8323 Result = V1.smul_ov(V2, Overflow);
8324 break;
8325 case ISD::UMULO:
8326 Result = V1.umul_ov(V2, Overflow);
8327 break;
8328 }
8329
8330 EVT VT = VTList.VTs[0];
8331 return getNode(ISD::MERGE_VALUES, DL, VTList,
8332 {getConstant(Result, DL, VT),
8333 getBoolConstant(Overflow, DL, VTList.VTs[1], VT)},
8334 Flags);
8335 }
8336 }
8337 return SDValue();
8338}
8339
8342 // TODO: Add support for unary/ternary fp opcodes.
8343 if (Ops.size() != 2)
8344 return SDValue();
8345
8346 // TODO: We don't do any constant folding for strict FP opcodes here, but we
8347 // should. That will require dealing with a potentially non-default
8348 // rounding mode, checking the "opStatus" return value from the APFloat
8349 // math calculations, and possibly other variations.
8350 SDValue N1 = Ops[0];
8351 SDValue N2 = Ops[1];
8352 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1, /*AllowUndefs*/ false);
8353 ConstantFPSDNode *N2CFP = isConstOrConstSplatFP(N2, /*AllowUndefs*/ false);
8354 if (N1CFP && N2CFP) {
8355 APFloat C1 = N1CFP->getValueAPF(); // make copy
8356 const APFloat &C2 = N2CFP->getValueAPF();
8357 switch (Opcode) {
8358 case ISD::FADD:
8360 return getConstantFP(C1, DL, VT);
8361 case ISD::FSUB:
8363 return getConstantFP(C1, DL, VT);
8364 case ISD::FMUL:
8366 return getConstantFP(C1, DL, VT);
8367 case ISD::FDIV:
8369 return getConstantFP(C1, DL, VT);
8370 case ISD::FREM:
8371 C1.mod(C2);
8372 return getConstantFP(C1, DL, VT);
8373 case ISD::FCOPYSIGN:
8374 C1.copySign(C2);
8375 return getConstantFP(C1, DL, VT);
8376 case ISD::FMINNUM:
8377 return getConstantFP(minnum(C1, C2), DL, VT);
8378 case ISD::FMAXNUM:
8379 return getConstantFP(maxnum(C1, C2), DL, VT);
8380 case ISD::FMINIMUM:
8381 return getConstantFP(minimum(C1, C2), DL, VT);
8382 case ISD::FMAXIMUM:
8383 return getConstantFP(maximum(C1, C2), DL, VT);
8384 case ISD::FMINIMUMNUM:
8385 return getConstantFP(minimumnum(C1, C2), DL, VT);
8386 case ISD::FMAXIMUMNUM:
8387 return getConstantFP(maximumnum(C1, C2), DL, VT);
8388 default: break;
8389 }
8390 }
8391 if (N1CFP && Opcode == ISD::FP_ROUND) {
8392 APFloat C1 = N1CFP->getValueAPF(); // make copy
8393 bool Unused;
8394 // This can return overflow, underflow, or inexact; we don't care.
8395 // FIXME need to be more flexible about rounding mode.
8397 &Unused);
8398 return getConstantFP(C1, DL, VT);
8399 }
8400
8401 switch (Opcode) {
8402 case ISD::FSUB:
8403 // -0.0 - undef --> undef (consistent with "fneg undef")
8404 if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1, /*AllowUndefs*/ true))
8405 if (N1C && N1C->getValueAPF().isNegZero() && N2.isUndef())
8406 return getUNDEF(VT);
8407 [[fallthrough]];
8408
8409 case ISD::FADD:
8410 case ISD::FMUL:
8411 case ISD::FDIV:
8412 case ISD::FREM:
8413 // If both operands are undef, the result is undef. If 1 operand is undef,
8414 // the result is NaN. This should match the behavior of the IR optimizer.
8415 if (N1.isUndef() && N2.isUndef())
8416 return getUNDEF(VT);
8417 if (N1.isUndef() || N2.isUndef())
8419 }
8420 return SDValue();
8421}
8422
8424 const SDLoc &DL, EVT DstEltVT) {
8425 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
8426
8427 // If this is already the right type, we're done.
8428 if (SrcEltVT == DstEltVT)
8429 return SDValue(BV, 0);
8430
8431 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
8432 unsigned DstBitSize = DstEltVT.getSizeInBits();
8433
8434 // If this is a conversion of N elements of one type to N elements of another
8435 // type, convert each element. This handles FP<->INT cases.
8436 if (SrcBitSize == DstBitSize) {
8438 for (SDValue Op : BV->op_values()) {
8439 // If the vector element type is not legal, the BUILD_VECTOR operands
8440 // are promoted and implicitly truncated. Make that explicit here.
8441 if (Op.getValueType() != SrcEltVT)
8442 Op = getNode(ISD::TRUNCATE, DL, SrcEltVT, Op);
8443 Ops.push_back(getBitcast(DstEltVT, Op));
8444 }
8445 EVT VT = EVT::getVectorVT(*getContext(), DstEltVT,
8447 return getBuildVector(VT, DL, Ops);
8448 }
8449
8450 // Otherwise, we're growing or shrinking the elements. To avoid having to
8451 // handle annoying details of growing/shrinking FP values, we convert them to
8452 // int first.
8453 if (SrcEltVT.isFloatingPoint()) {
8454 // Convert the input float vector to a int vector where the elements are the
8455 // same sizes.
8456 EVT IntEltVT = EVT::getIntegerVT(*getContext(), SrcEltVT.getSizeInBits());
8457 if (SDValue Tmp = FoldConstantBuildVector(BV, DL, IntEltVT))
8459 DstEltVT);
8460 return SDValue();
8461 }
8462
8463 // Now we know the input is an integer vector. If the output is a FP type,
8464 // convert to integer first, then to FP of the right size.
8465 if (DstEltVT.isFloatingPoint()) {
8466 EVT IntEltVT = EVT::getIntegerVT(*getContext(), DstEltVT.getSizeInBits());
8467 if (SDValue Tmp = FoldConstantBuildVector(BV, DL, IntEltVT))
8469 DstEltVT);
8470 return SDValue();
8471 }
8472
8473 // Okay, we know the src/dst types are both integers of differing types.
8474 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
8475
8476 // Extract the constant raw bit data.
8477 BitVector UndefElements;
8478 SmallVector<APInt> RawBits;
8479 bool IsLE = getDataLayout().isLittleEndian();
8480 if (!BV->getConstantRawBits(IsLE, DstBitSize, RawBits, UndefElements))
8481 return SDValue();
8482
8484 for (unsigned I = 0, E = RawBits.size(); I != E; ++I) {
8485 if (UndefElements[I])
8486 Ops.push_back(getUNDEF(DstEltVT));
8487 else
8488 Ops.push_back(getConstant(RawBits[I], DL, DstEltVT));
8489 }
8490
8491 EVT VT = EVT::getVectorVT(*getContext(), DstEltVT, Ops.size());
8492 return getBuildVector(VT, DL, Ops);
8493}
8494
8496 assert(Val.getValueType().isInteger() && "Invalid AssertAlign!");
8497
8498 // There's no need to assert on a byte-aligned pointer. All pointers are at
8499 // least byte aligned.
8500 if (A == Align(1))
8501 return Val;
8502
8503 SDVTList VTs = getVTList(Val.getValueType());
8504 SDValue Ops[] = {Val};
8505 SDNodeKey ID(ISD::AssertAlign, VTs, Ops);
8506 ID.AddInteger(A.value());
8507
8508 FoldingSetInsertToken InsertToken;
8509 if (SDNode *E = lookupNode(ID, DL, InsertToken))
8510 return SDValue(E, 0);
8511
8512 auto *N =
8513 newSDNode<AssertAlignSDNode>(DL.getIROrder(), DL.getDebugLoc(), VTs, A);
8514 createOperands(N, {Val});
8515
8516 CSEMap.insert(N, InsertToken);
8517 InsertNode(N);
8518
8519 SDValue V(N, 0);
8520 NewSDValueDbgMsg(V, "Creating new node: ", this);
8521 return V;
8522}
8523
8524SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8525 SDValue N1, SDValue N2) {
8526 SDNodeFlags Flags;
8527 if (Inserter)
8528 Flags = Inserter->getFlags();
8529 return getNode(Opcode, DL, VT, N1, N2, Flags);
8530}
8531
8533 SDValue &N2) const {
8534 if (!TLI->isCommutativeBinOp(Opcode))
8535 return;
8536
8537 // Canonicalize:
8538 // binop(const, nonconst) -> binop(nonconst, const)
8541 bool N1CFP = isConstantFPBuildVectorOrConstantFP(N1);
8542 bool N2CFP = isConstantFPBuildVectorOrConstantFP(N2);
8543 if ((N1C && !N2C) || (N1CFP && !N2CFP))
8544 std::swap(N1, N2);
8545
8546 // Canonicalize:
8547 // binop(splat(x), step_vector) -> binop(step_vector, splat(x))
8548 else if (N1.getOpcode() == ISD::SPLAT_VECTOR &&
8550 std::swap(N1, N2);
8551}
8552
8553SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8554 SDValue N1, SDValue N2, const SDNodeFlags Flags) {
8556 N2.getOpcode() != ISD::DELETED_NODE &&
8557 "Operand is DELETED_NODE!");
8558
8559 canonicalizeCommutativeBinop(Opcode, N1, N2);
8560
8561 auto *N1C = dyn_cast<ConstantSDNode>(N1);
8562 auto *N2C = dyn_cast<ConstantSDNode>(N2);
8563
8564 // Don't allow undefs in vector splats - we might be returning N2 when folding
8565 // to zero etc.
8566 ConstantSDNode *N2CV =
8567 isConstOrConstSplat(N2, /*AllowUndefs*/ false, /*AllowTruncation*/ true);
8568
8569 switch (Opcode) {
8570 default: break;
8571 case ISD::TokenFactor:
8572 assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
8573 N2.getValueType() == MVT::Other && "Invalid token factor!");
8574 // Fold trivial token factors.
8575 if (N1.getOpcode() == ISD::EntryToken) return N2;
8576 if (N2.getOpcode() == ISD::EntryToken) return N1;
8577 if (N1 == N2) return N1;
8578 break;
8579 case ISD::BUILD_VECTOR: {
8580 // Attempt to simplify BUILD_VECTOR.
8581 SDValue Ops[] = {N1, N2};
8582 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
8583 return V;
8584 break;
8585 }
8586 case ISD::CONCAT_VECTORS: {
8587 SDValue Ops[] = {N1, N2};
8588 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
8589 return V;
8590 break;
8591 }
8592 case ISD::AND:
8593 assert(VT.isInteger() && "This operator does not apply to FP types!");
8594 assert(N1.getValueType() == N2.getValueType() &&
8595 N1.getValueType() == VT && "Binary operator types must match!");
8596 // (X & 0) -> 0. This commonly occurs when legalizing i64 values, so it's
8597 // worth handling here.
8598 if (N2CV && N2CV->isZero())
8599 return N2;
8600 if (N2CV && N2CV->isAllOnes()) // X & -1 -> X
8601 return N1;
8602 break;
8603 case ISD::OR:
8604 case ISD::XOR:
8605 case ISD::ADD:
8606 case ISD::PTRADD:
8607 case ISD::SUB:
8608 assert(VT.isInteger() && "This operator does not apply to FP types!");
8609 assert(N1.getValueType() == N2.getValueType() &&
8610 N1.getValueType() == VT && "Binary operator types must match!");
8611 // The equal operand types requirement is unnecessarily strong for PTRADD.
8612 // However, the SelectionDAGBuilder does not generate PTRADDs with different
8613 // operand types, and we'd need to re-implement GEP's non-standard wrapping
8614 // logic everywhere where PTRADDs may be folded or combined to properly
8615 // support them. If/when we introduce pointer types to the SDAG, we will
8616 // need to relax this constraint.
8617
8618 // (X ^|+- 0) -> X. This commonly occurs when legalizing i64 values, so
8619 // it's worth handling here.
8620 if (N2CV && N2CV->isZero())
8621 return N1;
8622 if ((Opcode == ISD::ADD || Opcode == ISD::SUB) &&
8623 VT.getScalarType() == MVT::i1)
8624 return getNode(ISD::XOR, DL, VT, N1, N2);
8625 // Fold (add (vscale * C0), (vscale * C1)) to (vscale * (C0 + C1)).
8626 if (Opcode == ISD::ADD && N1.getOpcode() == ISD::VSCALE &&
8627 N2.getOpcode() == ISD::VSCALE) {
8628 const APInt &C1 = N1->getConstantOperandAPInt(0);
8629 const APInt &C2 = N2->getConstantOperandAPInt(0);
8630 return getVScale(DL, VT, C1 + C2);
8631 }
8632 break;
8633 case ISD::MUL:
8634 assert(VT.isInteger() && "This operator does not apply to FP types!");
8635 assert(N1.getValueType() == N2.getValueType() &&
8636 N1.getValueType() == VT && "Binary operator types must match!");
8637 if (VT.getScalarType() == MVT::i1)
8638 return getNode(ISD::AND, DL, VT, N1, N2);
8639 if (N2CV && N2CV->isZero())
8640 return N2;
8641 if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
8642 const APInt &MulImm = N1->getConstantOperandAPInt(0);
8643 const APInt &N2CImm = N2C->getAPIntValue();
8644 return getVScale(DL, VT, MulImm * N2CImm);
8645 }
8646 break;
8647 case ISD::UDIV:
8648 case ISD::UREM:
8649 case ISD::MULHU:
8650 case ISD::MULHS:
8651 case ISD::SDIV:
8652 case ISD::SREM:
8653 case ISD::SADDSAT:
8654 case ISD::SSUBSAT:
8655 case ISD::UADDSAT:
8656 case ISD::USUBSAT:
8657 assert(VT.isInteger() && "This operator does not apply to FP types!");
8658 assert(N1.getValueType() == N2.getValueType() &&
8659 N1.getValueType() == VT && "Binary operator types must match!");
8660 if (VT.getScalarType() == MVT::i1) {
8661 // fold (add_sat x, y) -> (or x, y) for bool types.
8662 if (Opcode == ISD::SADDSAT || Opcode == ISD::UADDSAT)
8663 return getNode(ISD::OR, DL, VT, N1, N2);
8664 // fold (sub_sat x, y) -> (and x, ~y) for bool types.
8665 if (Opcode == ISD::SSUBSAT || Opcode == ISD::USUBSAT)
8666 return getNode(ISD::AND, DL, VT, N1, getNOT(DL, N2, VT));
8667 }
8668 break;
8669 case ISD::SCMP:
8670 case ISD::UCMP:
8671 assert(N1.getValueType() == N2.getValueType() &&
8672 "Types of operands of UCMP/SCMP must match");
8673 assert(N1.getValueType().isVector() == VT.isVector() &&
8674 "Operands and return type of must both be scalars or vectors");
8675 if (VT.isVector())
8678 "Result and operands must have the same number of elements");
8679 break;
8680 case ISD::AVGFLOORS:
8681 case ISD::AVGFLOORU:
8682 case ISD::AVGCEILS:
8683 case ISD::AVGCEILU:
8684 assert(VT.isInteger() && "This operator does not apply to FP types!");
8685 assert(N1.getValueType() == N2.getValueType() &&
8686 N1.getValueType() == VT && "Binary operator types must match!");
8687 break;
8688 case ISD::ABDS:
8689 case ISD::ABDU:
8690 assert(VT.isInteger() && "This operator does not apply to FP types!");
8691 assert(N1.getValueType() == N2.getValueType() &&
8692 N1.getValueType() == VT && "Binary operator types must match!");
8693 if (VT.getScalarType() == MVT::i1)
8694 return getNode(ISD::XOR, DL, VT, N1, N2);
8695 break;
8696 case ISD::SMIN:
8697 case ISD::UMAX:
8698 assert(VT.isInteger() && "This operator does not apply to FP types!");
8699 assert(N1.getValueType() == N2.getValueType() &&
8700 N1.getValueType() == VT && "Binary operator types must match!");
8701 if (VT.getScalarType() == MVT::i1)
8702 return getNode(ISD::OR, DL, VT, N1, N2);
8703 break;
8704 case ISD::SMAX:
8705 case ISD::UMIN:
8706 assert(VT.isInteger() && "This operator does not apply to FP types!");
8707 assert(N1.getValueType() == N2.getValueType() &&
8708 N1.getValueType() == VT && "Binary operator types must match!");
8709 if (VT.getScalarType() == MVT::i1)
8710 return getNode(ISD::AND, DL, VT, N1, N2);
8711 break;
8712 case ISD::FADD:
8713 case ISD::FSUB:
8714 case ISD::FMUL:
8715 case ISD::FDIV:
8716 case ISD::FREM:
8717 assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
8718 assert(N1.getValueType() == N2.getValueType() &&
8719 N1.getValueType() == VT && "Binary operator types must match!");
8720 if (SDValue V = simplifyFPBinop(Opcode, N1, N2, Flags))
8721 return V;
8722 break;
8723 case ISD::FCOPYSIGN: // N1 and result must match. N1/N2 need not match.
8724 assert(N1.getValueType() == VT &&
8727 "Invalid FCOPYSIGN!");
8728 break;
8729 case ISD::SHL:
8730 if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
8731 const APInt &MulImm = N1->getConstantOperandAPInt(0);
8732 const APInt &ShiftImm = N2C->getAPIntValue();
8733 return getVScale(DL, VT, MulImm << ShiftImm);
8734 }
8735 [[fallthrough]];
8736 case ISD::SRA:
8737 case ISD::SRL:
8738 if (SDValue V = simplifyShift(N1, N2))
8739 return V;
8740 [[fallthrough]];
8741 case ISD::ROTL:
8742 case ISD::ROTR:
8743 case ISD::SSHLSAT:
8744 case ISD::USHLSAT:
8745 assert(VT == N1.getValueType() &&
8746 "Shift operators return type must be the same as their first arg");
8747 assert(VT.isInteger() && N2.getValueType().isInteger() &&
8748 "Shifts only work on integers");
8749 assert((!VT.isVector() || VT == N2.getValueType()) &&
8750 "Vector shift amounts must be in the same as their first arg");
8751 // Verify that the shift amount VT is big enough to hold valid shift
8752 // amounts. This catches things like trying to shift an i1024 value by an
8753 // i8, which is easy to fall into in generic code that uses
8754 // TLI.getShiftAmount().
8757 "Invalid use of small shift amount with oversized value!");
8758
8759 // Always fold shifts of i1 values so the code generator doesn't need to
8760 // handle them. Since we know the size of the shift has to be less than the
8761 // size of the value, the shift/rotate count is guaranteed to be zero.
8762 if (VT == MVT::i1)
8763 return N1;
8764 if (N2CV && N2CV->isZero())
8765 return N1;
8766 break;
8767 case ISD::FP_ROUND:
8769 VT.bitsLE(N1.getValueType()) && N2C &&
8770 (N2C->getZExtValue() == 0 || N2C->getZExtValue() == 1) &&
8771 N2.getOpcode() == ISD::TargetConstant && "Invalid FP_ROUND!");
8772 if (N1.getValueType() == VT) return N1; // noop conversion.
8773 break;
8774 case ISD::IS_FPCLASS: {
8776 "IS_FPCLASS is used for a non-floating type");
8777 assert(isa<ConstantSDNode>(N2) && "FPClassTest is not Constant");
8778 // is.fpclass(poison, mask) -> poison
8779 if (N1.getOpcode() == ISD::POISON)
8780 return getPOISON(VT);
8781 FPClassTest Mask = static_cast<FPClassTest>(N2->getAsZExtVal());
8782 // If all tests are made, it doesn't matter what the value is.
8783 if ((Mask & fcAllFlags) == fcAllFlags)
8784 return getBoolConstant(true, DL, VT, N1.getValueType());
8785 if ((Mask & fcAllFlags) == 0)
8786 return getBoolConstant(false, DL, VT, N1.getValueType());
8787 break;
8788 }
8789 case ISD::AssertNoFPClass: {
8791 "AssertNoFPClass is used for a non-floating type");
8792 assert(isa<ConstantSDNode>(N2) && "NoFPClass is not Constant");
8793 FPClassTest NoFPClass = static_cast<FPClassTest>(N2->getAsZExtVal());
8794 assert(llvm::to_underlying(NoFPClass) <=
8796 "FPClassTest value too large");
8797 (void)NoFPClass;
8798 break;
8799 }
8800 case ISD::AssertSext:
8801 case ISD::AssertZext: {
8802 EVT EVT = cast<VTSDNode>(N2)->getVT();
8803 assert(VT == N1.getValueType() && "Not an inreg extend!");
8804 assert(VT.isInteger() && EVT.isInteger() &&
8805 "Cannot *_EXTEND_INREG FP types");
8806 assert(!EVT.isVector() &&
8807 "AssertSExt/AssertZExt type should be the vector element type "
8808 "rather than the vector type!");
8809 assert(EVT.bitsLE(VT.getScalarType()) && "Not extending!");
8810 if (VT.getScalarType() == EVT) return N1; // noop assertion.
8811 break;
8812 }
8814 EVT EVT = cast<VTSDNode>(N2)->getVT();
8815 assert(VT == N1.getValueType() && "Not an inreg extend!");
8816 assert(VT.isInteger() && EVT.isInteger() &&
8817 "Cannot *_EXTEND_INREG FP types");
8818 assert(EVT.isVector() == VT.isVector() &&
8819 "SIGN_EXTEND_INREG type should be vector iff the operand "
8820 "type is vector!");
8821 assert((!EVT.isVector() ||
8823 "Vector element counts must match in SIGN_EXTEND_INREG");
8824 assert(EVT.getScalarType().bitsLE(VT.getScalarType()) && "Not extending!");
8825 if (EVT == VT) return N1; // Not actually extending
8826 break;
8827 }
8829 case ISD::FP_TO_UINT_SAT: {
8830 assert(VT.isInteger() && cast<VTSDNode>(N2)->getVT().isInteger() &&
8831 N1.getValueType().isFloatingPoint() && "Invalid FP_TO_*INT_SAT");
8832 assert(N1.getValueType().isVector() == VT.isVector() &&
8833 "FP_TO_*INT_SAT type should be vector iff the operand type is "
8834 "vector!");
8835 assert((!VT.isVector() || VT.getVectorElementCount() ==
8837 "Vector element counts must match in FP_TO_*INT_SAT");
8838 assert(!cast<VTSDNode>(N2)->getVT().isVector() &&
8839 "Type to saturate to must be a scalar.");
8840 assert(cast<VTSDNode>(N2)->getVT().bitsLE(VT.getScalarType()) &&
8841 "Not extending!");
8842 break;
8843 }
8846 "The result of EXTRACT_VECTOR_ELT must be at least as wide as the \
8847 element type of the vector.");
8848
8849 // Extract from an undefined value or using an undefined index is undefined.
8850 if (N1.isUndef() || N2.isUndef())
8851 return getUNDEF(VT);
8852
8853 // EXTRACT_VECTOR_ELT of out-of-bounds element is POISON for fixed length
8854 // vectors. For scalable vectors we will provide appropriate support for
8855 // dealing with arbitrary indices.
8856 if (N2C && N1.getValueType().isFixedLengthVector() &&
8857 N2C->getAPIntValue().uge(N1.getValueType().getVectorNumElements()))
8858 return getPOISON(VT);
8859
8860 // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
8861 // expanding copies of large vectors from registers. This only works for
8862 // fixed length vectors, since we need to know the exact number of
8863 // elements.
8864 if (N2C && N1.getOpcode() == ISD::CONCAT_VECTORS &&
8866 unsigned Factor = N1.getOperand(0).getValueType().getVectorNumElements();
8867 return getExtractVectorElt(DL, VT,
8868 N1.getOperand(N2C->getZExtValue() / Factor),
8869 N2C->getZExtValue() % Factor);
8870 }
8871
8872 // EXTRACT_VECTOR_ELT of BUILD_VECTOR or SPLAT_VECTOR is often formed while
8873 // lowering is expanding large vector constants.
8874 if (N2C && (N1.getOpcode() == ISD::BUILD_VECTOR ||
8875 N1.getOpcode() == ISD::SPLAT_VECTOR)) {
8878 "BUILD_VECTOR used for scalable vectors");
8879 unsigned Index =
8880 N1.getOpcode() == ISD::BUILD_VECTOR ? N2C->getZExtValue() : 0;
8881 SDValue Elt = N1.getOperand(Index);
8882
8883 if (VT != Elt.getValueType())
8884 // If the vector element type is not legal, the BUILD_VECTOR operands
8885 // are promoted and implicitly truncated, and the result implicitly
8886 // extended. Make that explicit here.
8887 Elt = getAnyExtOrTrunc(Elt, DL, VT);
8888
8889 return Elt;
8890 }
8891
8892 // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
8893 // operations are lowered to scalars.
8894 if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) {
8895 // If the indices are the same, return the inserted element else
8896 // if the indices are known different, extract the element from
8897 // the original vector.
8898 SDValue N1Op2 = N1.getOperand(2);
8900
8901 if (N1Op2C && N2C) {
8902 if (N1Op2C->getZExtValue() == N2C->getZExtValue()) {
8903 if (VT == N1.getOperand(1).getValueType())
8904 return N1.getOperand(1);
8905 if (VT.isFloatingPoint()) {
8907 return getFPExtendOrRound(N1.getOperand(1), DL, VT);
8908 }
8909 return getSExtOrTrunc(N1.getOperand(1), DL, VT);
8910 }
8911 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2);
8912 }
8913 }
8914
8915 // EXTRACT_VECTOR_ELT of v1iX EXTRACT_SUBVECTOR could be formed
8916 // when vector types are scalarized and v1iX is legal.
8917 // vextract (v1iX extract_subvector(vNiX, Idx)) -> vextract(vNiX,Idx).
8918 // Here we are completely ignoring the extract element index (N2),
8919 // which is fine for fixed width vectors, since any index other than 0
8920 // is undefined anyway. However, this cannot be ignored for scalable
8921 // vectors - in theory we could support this, but we don't want to do this
8922 // without a profitability check.
8923 if (N1.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
8925 N1.getValueType().getVectorNumElements() == 1) {
8926 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0),
8927 N1.getOperand(1));
8928 }
8929 break;
8931 assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!");
8932 assert(!N1.getValueType().isVector() && !VT.isVector() &&
8933 (N1.getValueType().isInteger() == VT.isInteger()) &&
8934 N1.getValueType() != VT &&
8935 "Wrong types for EXTRACT_ELEMENT!");
8936
8937 // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
8938 // 64-bit integers into 32-bit parts. Instead of building the extract of
8939 // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
8940 if (N1.getOpcode() == ISD::BUILD_PAIR)
8941 return N1.getOperand(N2C->getZExtValue());
8942
8943 // EXTRACT_ELEMENT of a constant int is also very common.
8944 if (N1C) {
8945 unsigned ElementSize = VT.getSizeInBits();
8946 unsigned Shift = ElementSize * N2C->getZExtValue();
8947 const APInt &Val = N1C->getAPIntValue();
8948 return getConstant(Val.extractBits(ElementSize, Shift), DL, VT);
8949 }
8950 break;
8952 EVT N1VT = N1.getValueType();
8953 assert(VT.isVector() && N1VT.isVector() &&
8954 "Extract subvector VTs must be vectors!");
8956 "Extract subvector VTs must have the same element type!");
8957 assert((VT.isFixedLengthVector() || N1VT.isScalableVector()) &&
8958 "Cannot extract a scalable vector from a fixed length vector!");
8959 assert((VT.isScalableVector() != N1VT.isScalableVector() ||
8961 "Extract subvector must be from larger vector to smaller vector!");
8962 assert(N2C && "Extract subvector index must be a constant");
8963 assert((VT.isScalableVector() != N1VT.isScalableVector() ||
8964 (VT.getVectorMinNumElements() + N2C->getZExtValue()) <=
8965 N1VT.getVectorMinNumElements()) &&
8966 "Extract subvector overflow!");
8967 assert(N2C->getAPIntValue().getBitWidth() ==
8968 TLI->getVectorIdxWidth(getDataLayout()) &&
8969 "Constant index for EXTRACT_SUBVECTOR has an invalid size");
8970 assert(N2C->getZExtValue() % VT.getVectorMinNumElements() == 0 &&
8971 "Extract index is not a multiple of the output vector length");
8972
8973 // Trivial extraction.
8974 if (VT == N1VT)
8975 return N1;
8976
8977 // EXTRACT_SUBVECTOR of an UNDEF is an UNDEF.
8978 if (N1.isUndef())
8979 return getUNDEF(VT);
8980
8981 // EXTRACT_SUBVECTOR of CONCAT_VECTOR can be simplified if the pieces of
8982 // the concat have the same type as the extract.
8983 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
8984 VT == N1.getOperand(0).getValueType()) {
8985 unsigned Factor = VT.getVectorMinNumElements();
8986 return N1.getOperand(N2C->getZExtValue() / Factor);
8987 }
8988
8989 // EXTRACT_SUBVECTOR of INSERT_SUBVECTOR is often created
8990 // during shuffle legalization.
8991 if (N1.getOpcode() == ISD::INSERT_SUBVECTOR && N2 == N1.getOperand(2) &&
8992 VT == N1.getOperand(1).getValueType())
8993 return N1.getOperand(1);
8994 break;
8995 }
8996 }
8997
8998 if (N1.getOpcode() == ISD::POISON || N2.getOpcode() == ISD::POISON) {
8999 switch (Opcode) {
9000 case ISD::XOR:
9001 case ISD::ADD:
9002 case ISD::PTRADD:
9003 case ISD::SUB:
9005 case ISD::UDIV:
9006 case ISD::SDIV:
9007 case ISD::UREM:
9008 case ISD::SREM:
9009 case ISD::MUL:
9010 case ISD::AND:
9011 case ISD::SSUBSAT:
9012 case ISD::USUBSAT:
9013 case ISD::UMIN:
9014 case ISD::OR:
9015 case ISD::SADDSAT:
9016 case ISD::UADDSAT:
9017 case ISD::UMAX:
9018 case ISD::SMAX:
9019 case ISD::SMIN:
9020 // fold op(arg1, poison) -> poison, fold op(poison, arg2) -> poison.
9021 return N2.getOpcode() == ISD::POISON ? N2 : N1;
9022 }
9023 }
9024
9025 // Canonicalize an UNDEF to the RHS, even over a constant.
9026 if (N1.getOpcode() == ISD::UNDEF && N2.getOpcode() != ISD::UNDEF) {
9027 if (TLI->isCommutativeBinOp(Opcode)) {
9028 std::swap(N1, N2);
9029 } else {
9030 switch (Opcode) {
9031 case ISD::PTRADD:
9032 case ISD::SUB:
9033 // fold op(undef, non_undef_arg2) -> undef.
9034 return N1;
9036 case ISD::UDIV:
9037 case ISD::SDIV:
9038 case ISD::UREM:
9039 case ISD::SREM:
9040 case ISD::SSUBSAT:
9041 case ISD::USUBSAT:
9042 // fold op(undef, non_undef_arg2) -> 0.
9043 return getConstant(0, DL, VT);
9044 }
9045 }
9046 }
9047
9048 // Fold a bunch of operators when the RHS is undef.
9049 if (N2.getOpcode() == ISD::UNDEF) {
9050 switch (Opcode) {
9051 case ISD::XOR:
9052 if (N1.getOpcode() == ISD::UNDEF)
9053 // Handle undef ^ undef -> 0 special case. This is a common
9054 // idiom (misuse).
9055 return getConstant(0, DL, VT);
9056 [[fallthrough]];
9057 case ISD::ADD:
9058 case ISD::PTRADD:
9059 case ISD::SUB:
9060 // fold op(arg1, undef) -> undef.
9061 return N2;
9062 case ISD::UDIV:
9063 case ISD::SDIV:
9064 case ISD::UREM:
9065 case ISD::SREM:
9066 // fold op(arg1, undef) -> poison.
9067 return getPOISON(VT);
9068 case ISD::MUL:
9069 case ISD::AND:
9070 case ISD::SSUBSAT:
9071 case ISD::USUBSAT:
9072 case ISD::UMIN:
9073 // fold op(undef, undef) -> undef, fold op(arg1, undef) -> 0.
9074 return N1.getOpcode() == ISD::UNDEF ? N2 : getConstant(0, DL, VT);
9075 case ISD::OR:
9076 case ISD::SADDSAT:
9077 case ISD::UADDSAT:
9078 case ISD::UMAX:
9079 // fold op(undef, undef) -> undef, fold op(arg1, undef) -> -1.
9080 return N1.getOpcode() == ISD::UNDEF ? N2 : getAllOnesConstant(DL, VT);
9081 case ISD::SMAX:
9082 // fold op(undef, undef) -> undef, fold op(arg1, undef) -> MAX_INT.
9083 return N1.getOpcode() == ISD::UNDEF
9084 ? N2
9085 : getConstant(
9087 VT);
9088 case ISD::SMIN:
9089 // fold op(undef, undef) -> undef, fold op(arg1, undef) -> MIN_INT.
9090 return N1.getOpcode() == ISD::UNDEF
9091 ? N2
9092 : getConstant(
9094 VT);
9095 }
9096 }
9097
9098 // Perform trivial constant folding.
9099 if (SDValue SV = FoldConstantArithmetic(Opcode, DL, VT, {N1, N2}, Flags))
9100 return SV;
9101
9102 // Memoize this node if possible.
9103 SDNode *N;
9104 SDVTList VTs = getVTList(VT);
9105 SDValue Ops[] = {N1, N2};
9106 if (VT != MVT::Glue) {
9107 SDNodeKey ID(Opcode, VTs, Ops);
9108 FoldingSetInsertToken InsertToken;
9109 if (SDNode *E = lookupNode(ID, DL, InsertToken)) {
9110 E->intersectFlagsWith(Flags);
9111 return SDValue(E, 0);
9112 }
9113
9114 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
9115 N->setFlags(Flags);
9116 createOperands(N, Ops);
9117 CSEMap.insert(N, InsertToken);
9118 } else {
9119 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
9120 createOperands(N, Ops);
9121 }
9122
9123 InsertNode(N);
9124 SDValue V = SDValue(N, 0);
9125 NewSDValueDbgMsg(V, "Creating new node: ", this);
9126 return V;
9127}
9128
9129SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
9130 SDValue N1, SDValue N2, SDValue N3) {
9131 SDNodeFlags Flags;
9132 if (Inserter)
9133 Flags = Inserter->getFlags();
9134 return getNode(Opcode, DL, VT, N1, N2, N3, Flags);
9135}
9136
9137SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
9138 SDValue N1, SDValue N2, SDValue N3,
9139 const SDNodeFlags Flags) {
9141 N2.getOpcode() != ISD::DELETED_NODE &&
9142 N3.getOpcode() != ISD::DELETED_NODE &&
9143 "Operand is DELETED_NODE!");
9144 // Perform various simplifications.
9145 switch (Opcode) {
9146 case ISD::BUILD_VECTOR: {
9147 // Attempt to simplify BUILD_VECTOR.
9148 SDValue Ops[] = {N1, N2, N3};
9149 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
9150 return V;
9151 break;
9152 }
9153 case ISD::CONCAT_VECTORS: {
9154 SDValue Ops[] = {N1, N2, N3};
9155 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
9156 return V;
9157 break;
9158 }
9159 case ISD::SETCC: {
9160 assert(VT.isInteger() && "SETCC result type must be an integer!");
9161 assert(N1.getValueType() == N2.getValueType() &&
9162 "SETCC operands must have the same type!");
9163 assert(VT.isVector() == N1.getValueType().isVector() &&
9164 "SETCC type should be vector iff the operand type is vector!");
9165 assert((!VT.isVector() || VT.getVectorElementCount() ==
9167 "SETCC vector element counts must match!");
9168 // Use FoldSetCC to simplify SETCC's.
9169 if (SDValue V =
9170 FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL, Flags))
9171 return V;
9172 break;
9173 }
9174 case ISD::SELECT:
9175 case ISD::VSELECT:
9176 if (SDValue V = simplifySelect(N1, N2, N3))
9177 return V;
9178 break;
9180 llvm_unreachable("should use getVectorShuffle constructor!");
9182 if (isNullConstant(N3))
9183 return N1;
9184 break;
9186 if (isNullConstant(N3))
9187 return N2;
9188 break;
9190 assert(VT.isVector() && VT == N1.getValueType() &&
9191 "INSERT_VECTOR_ELT vector type mismatch");
9193 "INSERT_VECTOR_ELT scalar fp/int mismatch");
9194 assert((!VT.isFloatingPoint() ||
9195 VT.getVectorElementType() == N2.getValueType()) &&
9196 "INSERT_VECTOR_ELT fp scalar type mismatch");
9197 assert((!VT.isInteger() ||
9199 "INSERT_VECTOR_ELT int scalar size mismatch");
9200
9201 auto *N3C = dyn_cast<ConstantSDNode>(N3);
9202 // INSERT_VECTOR_ELT into out-of-bounds element is an UNDEF, except
9203 // for scalable vectors where we will generate appropriate code to
9204 // deal with out-of-bounds cases correctly.
9205 if (N3C && VT.isFixedLengthVector() &&
9206 N3C->getZExtValue() >= VT.getVectorNumElements())
9207 return getUNDEF(VT);
9208
9209 // Undefined index can be assumed out-of-bounds, so that's UNDEF too.
9210 if (N3.isUndef())
9211 return getUNDEF(VT);
9212
9213 // If inserting poison, just use the input vector.
9214 if (N2.getOpcode() == ISD::POISON)
9215 return N1;
9216
9217 // Inserting undef into undef/poison is still undef.
9218 if (N2.getOpcode() == ISD::UNDEF && N1.isUndef())
9219 return getUNDEF(VT);
9220
9221 // If the inserted element is an UNDEF, just use the input vector.
9222 // But not if skipping the insert could make the result more poisonous.
9223 if (N2.isUndef()) {
9224 if (N3C && VT.isFixedLengthVector()) {
9225 APInt EltMask =
9226 APInt::getOneBitSet(VT.getVectorNumElements(), N3C->getZExtValue());
9227 if (isGuaranteedNotToBePoison(N1, EltMask))
9228 return N1;
9229 } else if (isGuaranteedNotToBePoison(N1))
9230 return N1;
9231 }
9232 break;
9233 }
9234 case ISD::INSERT_SUBVECTOR: {
9235 // If inserting poison, just use the input vector,
9236 if (N2.getOpcode() == ISD::POISON)
9237 return N1;
9238
9239 // Inserting undef into undef/poison is still undef.
9240 if (N2.getOpcode() == ISD::UNDEF && N1.isUndef())
9241 return getUNDEF(VT);
9242
9243 EVT N2VT = N2.getValueType();
9244 assert(VT == N1.getValueType() &&
9245 "Dest and insert subvector source types must match!");
9246 assert(VT.isVector() && N2VT.isVector() &&
9247 "Insert subvector VTs must be vectors!");
9249 "Insert subvector VTs must have the same element type!");
9250 assert((VT.isScalableVector() || N2VT.isFixedLengthVector()) &&
9251 "Cannot insert a scalable vector into a fixed length vector!");
9252 assert((VT.isScalableVector() != N2VT.isScalableVector() ||
9254 "Insert subvector must be from smaller vector to larger vector!");
9256 "Insert subvector index must be constant");
9257 assert((VT.isScalableVector() != N2VT.isScalableVector() ||
9258 (N2VT.getVectorMinNumElements() + N3->getAsZExtVal()) <=
9260 "Insert subvector overflow!");
9262 TLI->getVectorIdxWidth(getDataLayout()) &&
9263 "Constant index for INSERT_SUBVECTOR has an invalid size");
9264
9265 // Trivial insertion.
9266 if (VT == N2VT)
9267 return N2;
9268
9269 // If this is an insert of an extracted vector into an undef/poison vector,
9270 // we can just use the input to the extract. But not if skipping the
9271 // extract+insert could make the result more poisonous.
9272 if (N1.isUndef() && N2.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
9273 N2.getOperand(1) == N3 && N2.getOperand(0).getValueType() == VT) {
9274 if (N1.getOpcode() == ISD::POISON)
9275 return N2.getOperand(0);
9276 if (VT.isFixedLengthVector() && N2VT.isFixedLengthVector()) {
9277 unsigned LoBit = N3->getAsZExtVal();
9278 unsigned HiBit = LoBit + N2VT.getVectorNumElements();
9279 APInt EltMask =
9280 APInt::getBitsSet(VT.getVectorNumElements(), LoBit, HiBit);
9281 if (isGuaranteedNotToBePoison(N2.getOperand(0), ~EltMask))
9282 return N2.getOperand(0);
9283 } else if (isGuaranteedNotToBePoison(N2.getOperand(0)))
9284 return N2.getOperand(0);
9285 }
9286
9287 // If the inserted subvector is UNDEF, just use the input vector.
9288 // But not if skipping the insert could make the result more poisonous.
9289 if (N2.isUndef()) {
9290 if (VT.isFixedLengthVector()) {
9291 unsigned LoBit = N3->getAsZExtVal();
9292 unsigned HiBit = LoBit + N2VT.getVectorNumElements();
9293 APInt EltMask =
9294 APInt::getBitsSet(VT.getVectorNumElements(), LoBit, HiBit);
9295 if (isGuaranteedNotToBePoison(N1, EltMask))
9296 return N1;
9297 } else if (isGuaranteedNotToBePoison(N1))
9298 return N1;
9299 }
9300 break;
9301 }
9302 case ISD::BITCAST:
9303 // Fold bit_convert nodes from a type to themselves.
9304 if (N1.getValueType() == VT)
9305 return N1;
9306 break;
9307 case ISD::VECTOR_COMPRESS: {
9308 [[maybe_unused]] EVT VecVT = N1.getValueType();
9309 [[maybe_unused]] EVT MaskVT = N2.getValueType();
9310 [[maybe_unused]] EVT PassthruVT = N3.getValueType();
9311 assert(VT == VecVT && "Vector and result type don't match.");
9312 assert(VecVT.isVector() && MaskVT.isVector() && PassthruVT.isVector() &&
9313 "All inputs must be vectors.");
9314 assert(VecVT == PassthruVT && "Vector and passthru types don't match.");
9316 "Vector and mask must have same number of elements.");
9317
9318 if (N1.isUndef() || N2.isUndef())
9319 return N3;
9320
9321 break;
9322 }
9327 [[maybe_unused]] EVT AccVT = N1.getValueType();
9328 [[maybe_unused]] EVT Input1VT = N2.getValueType();
9329 [[maybe_unused]] EVT Input2VT = N3.getValueType();
9330 assert(Input1VT.isVector() && Input1VT == Input2VT &&
9331 "Expected the second and third operands of the PARTIAL_REDUCE_MLA "
9332 "node to have the same type!");
9333 assert(VT.isVector() && VT == AccVT &&
9334 "Expected the first operand of the PARTIAL_REDUCE_MLA node to have "
9335 "the same type as its result!");
9337 AccVT.getVectorElementCount()) &&
9338 "Expected the element count of the second and third operands of the "
9339 "PARTIAL_REDUCE_MLA node to be a positive integer multiple of the "
9340 "element count of the first operand and the result!");
9342 "Expected the second and third operands of the PARTIAL_REDUCE_MLA "
9343 "node to have an element type which is the same as or smaller than "
9344 "the element type of the first operand and result!");
9345 break;
9346 }
9347 }
9348
9349 // Perform trivial constant folding for arithmetic operators.
9350 switch (Opcode) {
9354 case ISD::FMA:
9355 case ISD::FMAD:
9356 case ISD::SETCC:
9357 case ISD::FSHL:
9358 case ISD::FSHR:
9359 if (SDValue SV =
9360 FoldConstantArithmetic(Opcode, DL, VT, {N1, N2, N3}, Flags))
9361 return SV;
9362 break;
9363 }
9364
9365 // Memoize node if it doesn't produce a glue result.
9366 SDNode *N;
9367 SDVTList VTs = getVTList(VT);
9368 SDValue Ops[] = {N1, N2, N3};
9369 if (VT != MVT::Glue) {
9370 SDNodeKey ID(Opcode, VTs, Ops);
9371 FoldingSetInsertToken InsertToken;
9372 if (SDNode *E = lookupNode(ID, DL, InsertToken)) {
9373 E->intersectFlagsWith(Flags);
9374 return SDValue(E, 0);
9375 }
9376
9377 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
9378 N->setFlags(Flags);
9379 createOperands(N, Ops);
9380 CSEMap.insert(N, InsertToken);
9381 } else {
9382 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
9383 createOperands(N, Ops);
9384 }
9385
9386 InsertNode(N);
9387 SDValue V = SDValue(N, 0);
9388 NewSDValueDbgMsg(V, "Creating new node: ", this);
9389 return V;
9390}
9391
9392SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
9393 SDValue N1, SDValue N2, SDValue N3, SDValue N4,
9394 const SDNodeFlags Flags) {
9395 SDValue Ops[] = { N1, N2, N3, N4 };
9396 return getNode(Opcode, DL, VT, Ops, Flags);
9397}
9398
9399SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
9400 SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
9401 SDNodeFlags Flags;
9402 if (Inserter)
9403 Flags = Inserter->getFlags();
9404 return getNode(Opcode, DL, VT, N1, N2, N3, N4, Flags);
9405}
9406
9407SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
9408 SDValue N1, SDValue N2, SDValue N3, SDValue N4,
9409 SDValue N5, const SDNodeFlags Flags) {
9410 SDValue Ops[] = { N1, N2, N3, N4, N5 };
9411 return getNode(Opcode, DL, VT, Ops, Flags);
9412}
9413
9414SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
9415 SDValue N1, SDValue N2, SDValue N3, SDValue N4,
9416 SDValue N5) {
9417 SDNodeFlags Flags;
9418 if (Inserter)
9419 Flags = Inserter->getFlags();
9420 return getNode(Opcode, DL, VT, N1, N2, N3, N4, N5, Flags);
9421}
9422
9423/// getStackArgumentTokenFactor - Compute a TokenFactor to force all
9424/// the incoming stack arguments to be loaded from the stack.
9426 SmallVector<SDValue, 8> ArgChains;
9427
9428 // Include the original chain at the beginning of the list. When this is
9429 // used by target LowerCall hooks, this helps legalize find the
9430 // CALLSEQ_BEGIN node.
9431 ArgChains.push_back(Chain);
9432
9433 // Add a chain value for each stack argument.
9434 for (SDNode *U : getEntryNode().getNode()->users())
9435 if (LoadSDNode *L = dyn_cast<LoadSDNode>(U))
9436 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
9437 if (FI->getIndex() < 0)
9438 ArgChains.push_back(SDValue(L, 1));
9439
9440 // Build a tokenfactor for all the chains.
9441 return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
9442}
9443
9444/// getMemsetValue - Vectorized representation of the memset value
9445/// operand.
9447 const SDLoc &dl) {
9448 assert(!Value.isUndef());
9449
9450 unsigned NumBits = VT.getScalarSizeInBits();
9452 assert(C->getAPIntValue().getBitWidth() == 8);
9453 APInt Val = APInt::getSplat(NumBits, C->getAPIntValue());
9454 if (VT.isInteger()) {
9455 bool IsOpaque = VT.getSizeInBits() > 64 ||
9456 !DAG.getTargetLoweringInfo().isLegalStoreImmediate(C->getSExtValue());
9457 return DAG.getConstant(Val, dl, VT, false, IsOpaque);
9458 }
9459 return DAG.getConstantFP(APFloat(VT.getFltSemantics(), Val), dl, VT);
9460 }
9461
9462 assert(Value.getValueType() == MVT::i8 && "memset with non-byte fill value?");
9463 EVT IntVT = VT.getScalarType();
9464 if (!IntVT.isInteger())
9465 IntVT = EVT::getIntegerVT(*DAG.getContext(), IntVT.getSizeInBits());
9466
9467 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, Value);
9468 if (NumBits > 8) {
9469 // Use a multiplication with 0x010101... to extend the input to the
9470 // required length.
9471 APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01));
9472 Value = DAG.getNode(ISD::MUL, dl, IntVT, Value,
9473 DAG.getConstant(Magic, dl, IntVT));
9474 }
9475
9476 if (VT != Value.getValueType() && !VT.isInteger())
9477 Value = DAG.getBitcast(VT.getScalarType(), Value);
9478 if (VT != Value.getValueType())
9479 Value = DAG.getSplatBuildVector(VT, dl, Value);
9480
9481 return Value;
9482}
9483
9484/// getMemsetStringVal - Similar to getMemsetValue. Except this is only
9485/// used when a memcpy is turned into a memset when the source is a constant
9486/// string ptr.
9488 const TargetLowering &TLI,
9489 const ConstantDataArraySlice &Slice) {
9490 // Handle vector with all elements zero.
9491 if (Slice.Array == nullptr) {
9492 if (VT.isInteger())
9493 return DAG.getConstant(0, dl, VT);
9494 return DAG.getNode(ISD::BITCAST, dl, VT,
9495 DAG.getConstant(0, dl, VT.changeTypeToInteger()));
9496 }
9497
9498 assert(!VT.isVector() && "Can't handle vector type here!");
9499 unsigned NumVTBits = VT.getSizeInBits();
9500 unsigned NumVTBytes = NumVTBits / 8;
9501 unsigned NumBytes = std::min(NumVTBytes, unsigned(Slice.Length));
9502
9503 APInt Val(NumVTBits, 0);
9504 if (DAG.getDataLayout().isLittleEndian()) {
9505 for (unsigned i = 0; i != NumBytes; ++i)
9506 Val |= (uint64_t)(unsigned char)Slice[i] << i*8;
9507 } else {
9508 for (unsigned i = 0; i != NumBytes; ++i)
9509 Val |= (uint64_t)(unsigned char)Slice[i] << (NumVTBytes-i-1)*8;
9510 }
9511
9512 // If the "cost" of materializing the integer immediate is less than the cost
9513 // of a load, then it is cost effective to turn the load into the immediate.
9514 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
9515 if (TLI.shouldConvertConstantLoadToIntImm(Val, Ty))
9516 return DAG.getConstant(Val, dl, VT);
9517 return SDValue();
9518}
9519
9521 const SDLoc &DL,
9522 const SDNodeFlags Flags) {
9523 SDValue Index = getTypeSize(DL, Base.getValueType(), Offset);
9524 return getMemBasePlusOffset(Base, Index, DL, Flags);
9525}
9526
9528 const SDLoc &DL,
9529 const SDNodeFlags Flags) {
9530 assert(Offset.getValueType().isInteger());
9531 EVT BasePtrVT = Ptr.getValueType();
9532 if (TLI->shouldPreservePtrArith(this->getMachineFunction().getFunction(),
9533 BasePtrVT))
9534 return getNode(ISD::PTRADD, DL, BasePtrVT, Ptr, Offset, Flags);
9535 // InBounds only applies to PTRADD, don't set it if we generate ADD.
9536 SDNodeFlags AddFlags = Flags;
9537 AddFlags.setInBounds(false);
9538 return getNode(ISD::ADD, DL, BasePtrVT, Ptr, Offset, AddFlags);
9539}
9540
9541/// Returns true if memcpy source is constant data.
9543 uint64_t SrcDelta = 0;
9544 GlobalAddressSDNode *G = nullptr;
9545 if (Src.getOpcode() == ISD::GlobalAddress)
9547 else if (Src->isAnyAdd() &&
9548 Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
9549 Src.getOperand(1).getOpcode() == ISD::Constant) {
9550 G = cast<GlobalAddressSDNode>(Src.getOperand(0));
9551 SrcDelta = Src.getConstantOperandVal(1);
9552 }
9553 if (!G)
9554 return false;
9555
9556 return getConstantDataArrayInfo(G->getGlobal(), Slice, 8,
9557 SrcDelta + G->getOffset());
9558}
9559
9561 SelectionDAG &DAG) {
9562 // On Darwin, -Os means optimize for size without hurting performance, so
9563 // only really optimize for size when -Oz (MinSize) is used.
9565 return MF.getFunction().hasMinSize();
9566 return DAG.shouldOptForSize();
9567}
9568
9570 SmallVector<SDValue, 32> &OutChains, unsigned From,
9571 unsigned To, SmallVector<SDValue, 16> &OutLoadChains,
9572 SmallVector<SDValue, 16> &OutStoreChains) {
9573 assert(OutLoadChains.size() && "Missing loads in memcpy inlining");
9574 assert(OutStoreChains.size() && "Missing stores in memcpy inlining");
9575 SmallVector<SDValue, 16> GluedLoadChains;
9576 for (unsigned i = From; i < To; ++i) {
9577 OutChains.push_back(OutLoadChains[i]);
9578 GluedLoadChains.push_back(OutLoadChains[i]);
9579 }
9580
9581 // Chain for all loads.
9582 SDValue LoadToken = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
9583 GluedLoadChains);
9584
9585 for (unsigned i = From; i < To; ++i) {
9586 StoreSDNode *ST = dyn_cast<StoreSDNode>(OutStoreChains[i]);
9587 SDValue NewStore = DAG.getTruncStore(LoadToken, dl, ST->getValue(),
9588 ST->getBasePtr(), ST->getMemoryVT(),
9589 ST->getMemOperand());
9590 OutChains.push_back(NewStore);
9591 }
9592}
9593
9594static SDValue
9596 SDValue Dst, SDValue Src, uint64_t Size, Align DstAlign,
9597 Align SrcAlign, bool isVol, bool AlwaysInline,
9598 MachinePointerInfo DstPtrInfo,
9599 MachinePointerInfo SrcPtrInfo, const AAMDNodes &AAInfo,
9600 BatchAAResults *BatchAA, const MDNode *DstMemCacheHint,
9601 const MDNode *SrcMemCacheHint) {
9602 // Turn a memcpy of undef to nop.
9603 // FIXME: We need to honor volatile even is Src is undef.
9604 if (Src.isUndef())
9605 return Chain;
9606
9607 // Expand memcpy to a series of load and store ops if the size operand falls
9608 // below a certain threshold.
9609 // TODO: In the AlwaysInline case, if the size is big then generate a loop
9610 // rather than maybe a humongous number of loads and stores.
9611 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9612 const DataLayout &DL = DAG.getDataLayout();
9613 LLVMContext &C = *DAG.getContext();
9614 std::vector<EVT> MemOps;
9615 bool DstAlignCanChange = false;
9617 MachineFrameInfo &MFI = MF.getFrameInfo();
9618 bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
9620 if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
9621 DstAlignCanChange = true;
9622 SrcAlign = std::max(SrcAlign, DAG.InferPtrAlign(Src).valueOrOne());
9624 // If marked as volatile, perform a copy even when marked as constant.
9625 bool CopyFromConstant = !isVol && isMemSrcFromConstant(Src, Slice);
9626 bool isZeroConstant = CopyFromConstant && Slice.Array == nullptr;
9627 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize);
9628 const MemOp Op = isZeroConstant
9629 ? MemOp::Set(Size, DstAlignCanChange, DstAlign,
9630 /*IsZeroMemset*/ true, isVol)
9631 : MemOp::Copy(Size, DstAlignCanChange, DstAlign,
9632 SrcAlign, isVol, CopyFromConstant);
9633 if (!TLI.findOptimalMemOpLowering(
9634 C, MemOps, Limit, Op, DstPtrInfo.getAddrSpace(),
9635 SrcPtrInfo.getAddrSpace(), MF.getFunction().getAttributes(), nullptr))
9636 return SDValue();
9637
9638 if (DstAlignCanChange) {
9639 Type *Ty = MemOps[0].getTypeForEVT(C);
9640 Align NewDstAlign = DL.getABITypeAlign(Ty);
9641
9642 // Don't promote to an alignment that would require dynamic stack
9643 // realignment which may conflict with optimizations such as tail call
9644 // optimization.
9646 if (!TRI->hasStackRealignment(MF))
9647 if (MaybeAlign StackAlign = DL.getStackAlignment())
9648 NewDstAlign = std::min(NewDstAlign, *StackAlign);
9649
9650 if (NewDstAlign > DstAlign) {
9651 // Give the stack frame object a larger alignment if needed.
9652 if (MFI.getObjectAlign(FI->getIndex()) < NewDstAlign)
9653 MFI.setObjectAlignment(FI->getIndex(), NewDstAlign);
9654 DstAlign = NewDstAlign;
9655 }
9656 }
9657
9658 // Prepare AAInfo for loads/stores after lowering this memcpy.
9659 AAMDNodes NewAAInfo = AAInfo;
9660 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
9661
9662 const Value *SrcVal = dyn_cast_if_present<const Value *>(SrcPtrInfo.V);
9663 bool isConstant =
9664 BatchAA && SrcVal &&
9665 BatchAA->pointsToConstantMemory(MemoryLocation(SrcVal, Size, AAInfo));
9666
9667 MachineMemOperand::Flags MMOFlags =
9669 SmallVector<SDValue, 16> OutLoadChains;
9670 SmallVector<SDValue, 16> OutStoreChains;
9671 SmallVector<SDValue, 32> OutChains;
9672 unsigned NumMemOps = MemOps.size();
9673 uint64_t SrcOff = 0, DstOff = 0;
9674 for (unsigned i = 0; i != NumMemOps; ++i) {
9675 EVT VT = MemOps[i];
9676 unsigned VTSize = VT.getSizeInBits() / 8;
9678
9679 if (VTSize > Size) {
9680 // Issuing an unaligned load / store pair that overlaps with the previous
9681 // pair. Adjust the offset accordingly.
9682 assert(i == NumMemOps-1 && i != 0);
9683 SrcOff -= VTSize - Size;
9684 DstOff -= VTSize - Size;
9685 }
9686
9687 if (CopyFromConstant &&
9688 (isZeroConstant || (VT.isInteger() && !VT.isVector()))) {
9689 // It's unlikely a store of a vector immediate can be done in a single
9690 // instruction. It would require a load from a constantpool first.
9691 // We only handle zero vectors here.
9692 // FIXME: Handle other cases where store of vector immediate is done in
9693 // a single instruction.
9694 ConstantDataArraySlice SubSlice;
9695 if (SrcOff < Slice.Length) {
9696 SubSlice = Slice;
9697 SubSlice.move(SrcOff);
9698 } else {
9699 // This is an out-of-bounds access and hence UB. Pretend we read zero.
9700 SubSlice.Array = nullptr;
9701 SubSlice.Offset = 0;
9702 SubSlice.Length = VTSize;
9703 }
9704 Value = getMemsetStringVal(VT, dl, DAG, TLI, SubSlice);
9705 if (Value.getNode()) {
9706 Store = DAG.getStore(
9707 Chain, dl, Value,
9708 DAG.getObjectPtrOffset(dl, Dst, TypeSize::getFixed(DstOff)),
9709 DstPtrInfo.getWithOffset(DstOff), DstAlign, MMOFlags,
9710 MMOMetadata(NewAAInfo, /*Ranges=*/nullptr, DstMemCacheHint));
9711 OutChains.push_back(Store);
9712 }
9713 }
9714
9715 if (!Store.getNode()) {
9716 // The type might not be legal for the target. This should only happen
9717 // if the type is smaller than a legal type, as on PPC, so the right
9718 // thing to do is generate a LoadExt/StoreTrunc pair. These simplify
9719 // to Load/Store if NVT==VT.
9720 // FIXME does the case above also need this?
9721 EVT NVT = TLI.getTypeToTransformTo(C, VT);
9722 assert(NVT.bitsGE(VT));
9723
9724 bool isDereferenceable =
9725 SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
9726 MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
9727 if (isDereferenceable)
9729 if (isConstant)
9730 SrcMMOFlags |= MachineMemOperand::MOInvariant;
9731
9732 Value = DAG.getExtLoad(
9733 ISD::EXTLOAD, dl, NVT, Chain,
9734 DAG.getObjectPtrOffset(dl, Src, TypeSize::getFixed(SrcOff)),
9735 SrcPtrInfo.getWithOffset(SrcOff), VT,
9736 commonAlignment(SrcAlign, SrcOff), SrcMMOFlags,
9737 MMOMetadata(NewAAInfo, /*Ranges=*/nullptr, SrcMemCacheHint));
9738 OutLoadChains.push_back(Value.getValue(1));
9739
9740 Store = DAG.getTruncStore(
9741 Chain, dl, Value,
9742 DAG.getObjectPtrOffset(dl, Dst, TypeSize::getFixed(DstOff)),
9743 DstPtrInfo.getWithOffset(DstOff), VT, DstAlign, MMOFlags,
9744 MMOMetadata(NewAAInfo, /*Ranges=*/nullptr, DstMemCacheHint));
9745 OutStoreChains.push_back(Store);
9746 }
9747 SrcOff += VTSize;
9748 DstOff += VTSize;
9749 Size -= VTSize;
9750 }
9751
9752 unsigned GluedLdStLimit = MaxLdStGlue == 0 ?
9754 unsigned NumLdStInMemcpy = OutStoreChains.size();
9755
9756 if (NumLdStInMemcpy) {
9757 // It may be that memcpy might be converted to memset if it's memcpy
9758 // of constants. In such a case, we won't have loads and stores, but
9759 // just stores. In the absence of loads, there is nothing to gang up.
9760 if ((GluedLdStLimit <= 1) || !EnableMemCpyDAGOpt) {
9761 // If target does not care, just leave as it.
9762 for (unsigned i = 0; i < NumLdStInMemcpy; ++i) {
9763 OutChains.push_back(OutLoadChains[i]);
9764 OutChains.push_back(OutStoreChains[i]);
9765 }
9766 } else {
9767 // Ld/St less than/equal limit set by target.
9768 if (NumLdStInMemcpy <= GluedLdStLimit) {
9769 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
9770 NumLdStInMemcpy, OutLoadChains,
9771 OutStoreChains);
9772 } else {
9773 unsigned NumberLdChain = NumLdStInMemcpy / GluedLdStLimit;
9774 unsigned RemainingLdStInMemcpy = NumLdStInMemcpy % GluedLdStLimit;
9775 unsigned GlueIter = 0;
9776
9777 // Residual ld/st.
9778 if (RemainingLdStInMemcpy) {
9780 DAG, dl, OutChains, NumLdStInMemcpy - RemainingLdStInMemcpy,
9781 NumLdStInMemcpy, OutLoadChains, OutStoreChains);
9782 }
9783
9784 for (unsigned cnt = 0; cnt < NumberLdChain; ++cnt) {
9785 unsigned IndexFrom = NumLdStInMemcpy - RemainingLdStInMemcpy -
9786 GlueIter - GluedLdStLimit;
9787 unsigned IndexTo = NumLdStInMemcpy - RemainingLdStInMemcpy - GlueIter;
9788 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, IndexFrom, IndexTo,
9789 OutLoadChains, OutStoreChains);
9790 GlueIter += GluedLdStLimit;
9791 }
9792 }
9793 }
9794 }
9795 return DAG.getTokenFactor(dl, OutChains);
9796}
9797
9799 SelectionDAG &DAG, const SDLoc &dl, SDValue Chain, SDValue Dst, SDValue Src,
9800 uint64_t Size, Align DstAlign, Align SrcAlign, bool isVol,
9801 bool AlwaysInline, MachinePointerInfo DstPtrInfo,
9802 MachinePointerInfo SrcPtrInfo, const AAMDNodes &AAInfo) {
9803 // Turn a memmove of undef to nop.
9804 // FIXME: We need to honor volatile even is Src is undef.
9805 if (Src.isUndef())
9806 return Chain;
9807
9808 // Expand memmove to a series of load and store ops if the size operand falls
9809 // below a certain threshold.
9810 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9811 const DataLayout &DL = DAG.getDataLayout();
9812 LLVMContext &C = *DAG.getContext();
9813 std::vector<EVT> MemOps;
9814 bool DstAlignCanChange = false;
9816 MachineFrameInfo &MFI = MF.getFrameInfo();
9817 bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
9819 if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
9820 DstAlignCanChange = true;
9821 SrcAlign = std::max(SrcAlign, DAG.InferPtrAlign(Src).valueOrOne());
9822 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize);
9823 if (!TLI.findOptimalMemOpLowering(
9824 C, MemOps, Limit,
9825 MemOp::Move(Size, DstAlignCanChange, DstAlign, SrcAlign, isVol),
9826 DstPtrInfo.getAddrSpace(), SrcPtrInfo.getAddrSpace(),
9827 MF.getFunction().getAttributes(), nullptr))
9828 return SDValue();
9829
9830 if (DstAlignCanChange) {
9831 Type *Ty = MemOps[0].getTypeForEVT(C);
9832 Align NewDstAlign = DL.getABITypeAlign(Ty);
9833
9834 // Don't promote to an alignment that would require dynamic stack
9835 // realignment which may conflict with optimizations such as tail call
9836 // optimization.
9838 if (!TRI->hasStackRealignment(MF))
9839 if (MaybeAlign StackAlign = DL.getStackAlignment())
9840 NewDstAlign = std::min(NewDstAlign, *StackAlign);
9841
9842 if (NewDstAlign > DstAlign) {
9843 // Give the stack frame object a larger alignment if needed.
9844 if (MFI.getObjectAlign(FI->getIndex()) < NewDstAlign)
9845 MFI.setObjectAlignment(FI->getIndex(), NewDstAlign);
9846 DstAlign = NewDstAlign;
9847 }
9848 }
9849
9850 // Prepare AAInfo for loads/stores after lowering this memmove.
9851 AAMDNodes NewAAInfo = AAInfo;
9852 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
9853
9854 MachineMemOperand::Flags MMOFlags =
9856 uint64_t SrcOff = 0;
9857 SmallVector<SDValue, 8> LoadValues;
9858 SmallVector<SDValue, 8> LoadChains;
9859 SmallVector<SDValue, 8> OutChains;
9860 unsigned NumMemOps = MemOps.size();
9861 for (unsigned i = 0; i < NumMemOps; i++) {
9862 EVT VT = MemOps[i];
9863 unsigned VTSize = VT.getSizeInBits() / 8;
9864 SDValue Value;
9865 bool IsOverlapping = false;
9866
9867 if (i == NumMemOps - 1 && i != 0 && VTSize > Size - SrcOff) {
9868 // Issuing an unaligned load / store pair that overlaps with the previous
9869 // pair. Adjust the offset accordingly.
9870 SrcOff = Size - VTSize;
9871 IsOverlapping = true;
9872 }
9873
9874 // Calculate the actual alignment at the current offset. The alignment at
9875 // SrcOff may be lower than the base alignment, especially when using
9876 // overlapping loads.
9877 Align SrcAlignAtOffset = commonAlignment(SrcAlign, SrcOff);
9878 if (IsOverlapping) {
9879 // Verify that the target allows misaligned memory accesses at the
9880 // adjusted offset when using overlapping loads.
9881 unsigned Fast;
9882 if (!TLI.allowsMisalignedMemoryAccesses(VT, SrcPtrInfo.getAddrSpace(),
9883 SrcAlignAtOffset, MMOFlags,
9884 &Fast) ||
9885 !Fast) {
9886 // This should have been caught by findOptimalMemOpLowering, but verify
9887 // here for safety.
9888 return SDValue();
9889 }
9890 }
9891
9892 bool isDereferenceable =
9893 SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
9894 MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
9895 if (isDereferenceable)
9897 Value =
9898 DAG.getLoad(VT, dl, Chain,
9899 DAG.getObjectPtrOffset(dl, Src, TypeSize::getFixed(SrcOff)),
9900 SrcPtrInfo.getWithOffset(SrcOff), SrcAlignAtOffset,
9901 SrcMMOFlags, NewAAInfo);
9902 LoadValues.push_back(Value);
9903 LoadChains.push_back(Value.getValue(1));
9904 SrcOff += VTSize;
9905 }
9906 Chain = DAG.getTokenFactor(dl, LoadChains);
9907 OutChains.clear();
9908 uint64_t DstOff = 0;
9909 for (unsigned i = 0; i < NumMemOps; i++) {
9910 EVT VT = MemOps[i];
9911 unsigned VTSize = VT.getSizeInBits() / 8;
9912 SDValue Store;
9913 bool IsOverlapping = false;
9914
9915 if (i == NumMemOps - 1 && i != 0 && VTSize > Size - DstOff) {
9916 // Issuing an unaligned load / store pair that overlaps with the previous
9917 // pair. Adjust the offset accordingly.
9918 DstOff = Size - VTSize;
9919 IsOverlapping = true;
9920 }
9921
9922 // Calculate the actual alignment at the current offset. The alignment at
9923 // DstOff may be lower than the base alignment, especially when using
9924 // overlapping stores.
9925 Align DstAlignAtOffset = commonAlignment(DstAlign, DstOff);
9926 if (IsOverlapping) {
9927 // Verify that the target allows misaligned memory accesses at the
9928 // adjusted offset when using overlapping stores.
9929 unsigned Fast;
9930 if (!TLI.allowsMisalignedMemoryAccesses(VT, DstPtrInfo.getAddrSpace(),
9931 DstAlignAtOffset, MMOFlags,
9932 &Fast) ||
9933 !Fast) {
9934 // This should have been caught by findOptimalMemOpLowering, but verify
9935 // here for safety.
9936 return SDValue();
9937 }
9938 }
9939 Store = DAG.getStore(
9940 Chain, dl, LoadValues[i],
9941 DAG.getObjectPtrOffset(dl, Dst, TypeSize::getFixed(DstOff)),
9942 DstPtrInfo.getWithOffset(DstOff), DstAlignAtOffset, MMOFlags,
9943 NewAAInfo);
9944 OutChains.push_back(Store);
9945 DstOff += VTSize;
9946 }
9947
9948 return DAG.getTokenFactor(dl, OutChains);
9949}
9950
9951/// Lower the call to 'memset' intrinsic function into a series of store
9952/// operations.
9953///
9954/// \param DAG Selection DAG where lowered code is placed.
9955/// \param dl Link to corresponding IR location.
9956/// \param Chain Control flow dependency.
9957/// \param Dst Pointer to destination memory location.
9958/// \param Src Value of byte to write into the memory.
9959/// \param Size Number of bytes to write.
9960/// \param Alignment Alignment of the destination in bytes.
9961/// \param isVol True if destination is volatile.
9962/// \param AlwaysInline Makes sure no function call is generated.
9963/// \param DstPtrInfo IR information on the memory pointer.
9964/// \returns New head in the control flow, if lowering was successful, empty
9965/// SDValue otherwise.
9966///
9967/// The function tries to replace 'llvm.memset' intrinsic with several store
9968/// operations and value calculation code. This is usually profitable for small
9969/// memory size or when the semantic requires inlining.
9971 SDValue Chain, SDValue Dst, SDValue Src,
9972 uint64_t Size, Align Alignment, bool isVol,
9973 bool AlwaysInline, MachinePointerInfo DstPtrInfo,
9974 const AAMDNodes &AAInfo) {
9975 // Turn a memset of undef to nop.
9976 // FIXME: We need to honor volatile even is Src is undef.
9977 if (Src.isUndef())
9978 return Chain;
9979
9980 // Expand memset to a series of load/store ops if the size operand
9981 // falls below a certain threshold.
9982 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9983 std::vector<EVT> MemOps;
9984 bool DstAlignCanChange = false;
9985 LLVMContext &C = *DAG.getContext();
9987 MachineFrameInfo &MFI = MF.getFrameInfo();
9988 bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
9990 if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
9991 DstAlignCanChange = true;
9992 bool IsZeroVal = isNullConstant(Src);
9993 unsigned Limit = AlwaysInline ? ~0 : TLI.getMaxStoresPerMemset(OptSize);
9994
9995 EVT LargestVT;
9996 if (!TLI.findOptimalMemOpLowering(
9997 C, MemOps, Limit,
9998 MemOp::Set(Size, DstAlignCanChange, Alignment, IsZeroVal, isVol),
9999 DstPtrInfo.getAddrSpace(), ~0u, MF.getFunction().getAttributes(),
10000 &LargestVT))
10001 return SDValue();
10002
10003 if (DstAlignCanChange) {
10004 Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
10005 const DataLayout &DL = DAG.getDataLayout();
10006 Align NewAlign = DL.getABITypeAlign(Ty);
10007
10008 // Don't promote to an alignment that would require dynamic stack
10009 // realignment which may conflict with optimizations such as tail call
10010 // optimization.
10012 if (!TRI->hasStackRealignment(MF))
10013 if (MaybeAlign StackAlign = DL.getStackAlignment())
10014 NewAlign = std::min(NewAlign, *StackAlign);
10015
10016 if (NewAlign > Alignment) {
10017 // Give the stack frame object a larger alignment if needed.
10018 if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
10019 MFI.setObjectAlignment(FI->getIndex(), NewAlign);
10020 Alignment = NewAlign;
10021 }
10022 }
10023
10024 SmallVector<SDValue, 8> OutChains;
10025 uint64_t DstOff = 0;
10026 unsigned NumMemOps = MemOps.size();
10027
10028 // Find the largest store and generate the bit pattern for it.
10029 // If target didn't set LargestVT, compute it from MemOps.
10030 if (!LargestVT.isSimple()) {
10031 LargestVT = MemOps[0];
10032 for (unsigned i = 1; i < NumMemOps; i++)
10033 if (MemOps[i].bitsGT(LargestVT))
10034 LargestVT = MemOps[i];
10035 }
10036 SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl);
10037
10038 // Prepare AAInfo for loads/stores after lowering this memset.
10039 AAMDNodes NewAAInfo = AAInfo;
10040 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
10041
10042 for (unsigned i = 0; i < NumMemOps; i++) {
10043 EVT VT = MemOps[i];
10044 unsigned VTSize = VT.getSizeInBits() / 8;
10045 // The target should specify store types that exactly cover the memset size
10046 // (with the last store potentially being oversized for overlapping stores).
10047 assert(Size > 0 && "Target specified more stores than needed in "
10048 "findOptimalMemOpLowering");
10049 if (VTSize > Size) {
10050 // Issuing an unaligned load / store pair that overlaps with the previous
10051 // pair. Adjust the offset accordingly.
10052 assert(i == NumMemOps-1 && i != 0);
10053 DstOff -= VTSize - Size;
10054 }
10055
10056 // If this store is smaller than the largest store see whether we can get
10057 // the smaller value for free with a truncate or extract vector element and
10058 // then store.
10059 SDValue Value = MemSetValue;
10060 if (VT.bitsLT(LargestVT)) {
10061 unsigned Index;
10062 unsigned NElts = LargestVT.getSizeInBits() / VT.getSizeInBits();
10063 EVT SVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), NElts);
10064 if (!LargestVT.isVector() && !VT.isVector() &&
10065 TLI.isTruncateFree(LargestVT, VT))
10066 Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue);
10067 else if (LargestVT.isVector() && !VT.isVector() &&
10069 LargestVT.getTypeForEVT(*DAG.getContext()),
10070 VT.getSizeInBits(), Index) &&
10071 TLI.isTypeLegal(SVT) &&
10072 LargestVT.getSizeInBits() == SVT.getSizeInBits()) {
10073 // Target which can combine store(extractelement VectorTy, Idx) can get
10074 // the smaller value for free.
10075 SDValue TailValue = DAG.getNode(ISD::BITCAST, dl, SVT, MemSetValue);
10076 Value = DAG.getExtractVectorElt(dl, VT, TailValue, Index);
10077 } else
10078 Value = getMemsetValue(Src, VT, DAG, dl);
10079 }
10080 assert(Value.getValueType() == VT && "Value with wrong type.");
10081 SDValue Store = DAG.getStore(
10082 Chain, dl, Value,
10083 DAG.getObjectPtrOffset(dl, Dst, TypeSize::getFixed(DstOff)),
10084 DstPtrInfo.getWithOffset(DstOff), Alignment,
10086 NewAAInfo);
10087 OutChains.push_back(Store);
10088 DstOff += VT.getSizeInBits() / 8;
10089 // For oversized overlapping stores, only subtract the remaining bytes.
10090 // For normal stores, subtract the full store size.
10091 if (VTSize > Size) {
10092 Size = 0;
10093 } else {
10094 Size -= VTSize;
10095 }
10096 }
10097
10098 // After processing all stores, Size should be exactly 0. Any remaining bytes
10099 // indicate a bug in the target's findOptimalMemOpLowering implementation.
10100 assert(Size == 0 && "Target's findOptimalMemOpLowering did not specify "
10101 "stores that exactly cover the memset size");
10102
10103 return DAG.getTokenFactor(dl, OutChains);
10104}
10105
10107 const DataLayout &DL, unsigned AS) {
10108 // Lowering memcpy / memset / memmove intrinsics to calls is only valid if all
10109 // pointer operands can be losslessly bitcasted to pointers of address space 0
10110 if (AS != 0 && !TLI->getTargetMachine().isNoopAddrSpaceCast(DL, AS, 0)) {
10111 report_fatal_error("cannot lower memory intrinsic in address space " +
10112 Twine(AS));
10113 }
10114}
10115
10116/// The length of a memory intrinsic (e.g. number of bytes to copy) is unsigned
10117/// and may have any integer type. We zero-extend or truncate it to the pointer
10118/// type of the narrower address space being accessed.
10120 SDValue Size, unsigned DstAS,
10121 unsigned SrcAS) {
10122 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10123 MVT DstVT = TLI.getPointerTy(DAG.getDataLayout(), DstAS);
10124 MVT SrcVT = TLI.getPointerTy(DAG.getDataLayout(), SrcAS);
10125 return DAG.getZExtOrTrunc(Size, dl, DstVT.bitsLT(SrcVT) ? DstVT : SrcVT);
10126}
10127
10129 const SelectionDAG *SelDAG,
10130 bool AllowReturnsFirstArg) {
10131 if (!CI || !CI->isTailCall())
10132 return false;
10133 // TODO: Fix "returns-first-arg" determination so it doesn't depend on which
10134 // helper symbol we lower to.
10135 return isInTailCallPosition(*CI, SelDAG->getTarget(),
10136 AllowReturnsFirstArg &&
10138}
10139
10140static std::pair<SDValue, SDValue>
10143 const CallInst *CI, RTLIB::Libcall Call,
10144 SelectionDAG *DAG, const TargetLowering *TLI) {
10145 RTLIB::LibcallImpl LCImpl = DAG->getLibcalls().getLibcallImpl(Call);
10146
10147 if (LCImpl == RTLIB::Unsupported)
10148 return {};
10149
10151 bool IsTailCall =
10152 isInTailCallPositionWrapper(CI, DAG, /*AllowReturnsFirstArg=*/true) &&
10153 // Lowering doesn't support tail calling inside a function with
10154 // a swifterror argument yet.
10155 !DAG->hasSwiftErrorArg();
10156 SDValue Callee =
10157 DAG->getExternalSymbol(LCImpl, TLI->getPointerTy(DAG->getDataLayout()));
10158
10159 CLI.setDebugLoc(dl)
10160 .setChain(Chain)
10162 CI->getType(), Callee, std::move(Args))
10163 .setTailCall(IsTailCall);
10164
10165 return TLI->LowerCallTo(CLI);
10166}
10167
10168std::pair<SDValue, SDValue> SelectionDAG::getStrcmp(SDValue Chain,
10169 const SDLoc &dl, SDValue S1,
10170 SDValue S2,
10171 const CallInst *CI) {
10173 TargetLowering::ArgListTy Args = {{S1, PT}, {S2, PT}};
10174 return getRuntimeCallSDValueHelper(Chain, dl, std::move(Args), CI,
10175 RTLIB::STRCMP, this, TLI);
10176}
10177
10178std::pair<SDValue, SDValue> SelectionDAG::getStrstr(SDValue Chain,
10179 const SDLoc &dl, SDValue S1,
10180 SDValue S2,
10181 const CallInst *CI) {
10183 TargetLowering::ArgListTy Args = {{S1, PT}, {S2, PT}};
10184 return getRuntimeCallSDValueHelper(Chain, dl, std::move(Args), CI,
10185 RTLIB::STRSTR, this, TLI);
10186}
10187
10188std::pair<SDValue, SDValue> SelectionDAG::getMemccpy(SDValue Chain,
10189 const SDLoc &dl,
10190 SDValue Dst, SDValue Src,
10192 const CallInst *CI) {
10194
10196 {Dst, PT},
10197 {Src, PT},
10200 return getRuntimeCallSDValueHelper(Chain, dl, std::move(Args), CI,
10201 RTLIB::MEMCCPY, this, TLI);
10202}
10203
10204std::pair<SDValue, SDValue>
10206 SDValue Mem1, SDValue Size, const CallInst *CI) {
10209 {Mem0, PT},
10210 {Mem1, PT},
10212 return getRuntimeCallSDValueHelper(Chain, dl, std::move(Args), CI,
10213 RTLIB::MEMCMP, this, TLI);
10214}
10215
10216std::pair<SDValue, SDValue> SelectionDAG::getStrcpy(SDValue Chain,
10217 const SDLoc &dl,
10218 SDValue Dst, SDValue Src,
10219 const CallInst *CI) {
10221 TargetLowering::ArgListTy Args = {{Dst, PT}, {Src, PT}};
10222 return getRuntimeCallSDValueHelper(Chain, dl, std::move(Args), CI,
10223 RTLIB::STRCPY, this, TLI);
10224}
10225
10226std::pair<SDValue, SDValue> SelectionDAG::getStrlen(SDValue Chain,
10227 const SDLoc &dl,
10228 SDValue Src,
10229 const CallInst *CI) {
10230 // Emit a library call.
10233 return getRuntimeCallSDValueHelper(Chain, dl, std::move(Args), CI,
10234 RTLIB::STRLEN, this, TLI);
10235}
10236
10238 return TLI->supportSwiftError() &&
10239 MF->getFunction().getAttributes().hasAttrSomewhere(
10240 Attribute::SwiftError);
10241}
10242
10244 SDValue Chain, const SDLoc &dl, SDValue Dst, SDValue Src, SDValue Size,
10245 Align DstAlign, Align SrcAlign, bool isVol, bool AlwaysInline,
10246 const CallInst *CI, std::optional<bool> OverrideTailCall,
10247 MachinePointerInfo DstPtrInfo, MachinePointerInfo SrcPtrInfo,
10248 const AAMDNodes &AAInfo, BatchAAResults *BatchAA) {
10249 Size = getMemIntrinsicSize(*this, dl, Size, DstPtrInfo.getAddrSpace(),
10250 SrcPtrInfo.getAddrSpace());
10251 // Check to see if we should lower the memcpy to loads and stores first.
10252 // For cases within the target-specified limits, this is the best choice.
10253 const MDNode *DstMemCacheHint =
10254 CI ? getMemCacheHintMetadata(*CI, /*OperandNo=*/0) : nullptr;
10255 const MDNode *SrcMemCacheHint =
10256 CI ? getMemCacheHintMetadata(*CI, /*OperandNo=*/1) : nullptr;
10257
10259 if (ConstantSize) {
10260 // Memcpy with size zero? Just return the original chain.
10261 if (ConstantSize->isZero())
10262 return Chain;
10263
10265 *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), DstAlign,
10266 SrcAlign, isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo, BatchAA,
10267 DstMemCacheHint, SrcMemCacheHint);
10268 if (Result.getNode())
10269 return Result;
10270 }
10271
10272 // Then check to see if we should lower the memcpy with target-specific
10273 // code. If the target chooses to do this, this is the next best.
10274 if (TSI) {
10275 SDValue Result = TSI->EmitTargetCodeForMemcpy(
10276 *this, dl, Chain, Dst, Src, Size, DstAlign, SrcAlign, isVol,
10277 AlwaysInline, DstPtrInfo, SrcPtrInfo);
10278 if (Result.getNode())
10279 return Result;
10280 }
10281
10282 // If we really need inline code and the target declined to provide it,
10283 // use a (potentially long) sequence of loads and stores.
10284 if (AlwaysInline) {
10285 assert(ConstantSize && "AlwaysInline requires a constant size!");
10287 *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), DstAlign,
10288 SrcAlign, isVol, true, DstPtrInfo, SrcPtrInfo, AAInfo, BatchAA,
10289 DstMemCacheHint, SrcMemCacheHint);
10290 }
10291
10293 DstPtrInfo.getAddrSpace());
10295 SrcPtrInfo.getAddrSpace());
10296
10297 // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc
10298 // memcpy is not guaranteed to be safe. libc memcpys aren't required to
10299 // respect volatile, so they may do things like read or write memory
10300 // beyond the given memory regions. But fixing this isn't easy, and most
10301 // people don't care.
10302
10303 // Emit a library call.
10306 Args.emplace_back(Dst, PtrTy);
10307 Args.emplace_back(Src, PtrTy);
10308 Args.emplace_back(Size, getDataLayout().getIntPtrType(*getContext()));
10309 // FIXME: pass in SDLoc
10311 bool IsTailCall = false;
10312 RTLIB::LibcallImpl MemCpyImpl = TLI->getMemcpyImpl();
10313
10314 if (OverrideTailCall.has_value()) {
10315 IsTailCall = *OverrideTailCall;
10316 } else {
10317 bool LowersToMemcpy = MemCpyImpl == RTLIB::impl_memcpy;
10318 IsTailCall = isInTailCallPositionWrapper(CI, this, LowersToMemcpy);
10319 }
10320 // Lowering doesn't support tail calling inside a function with a
10321 // swifterror argument yet.
10322 IsTailCall &= !hasSwiftErrorArg();
10323
10324 CLI.setDebugLoc(dl)
10325 .setChain(Chain)
10326 .setLibCallee(
10327 Libcalls->getLibcallImplCallingConv(MemCpyImpl),
10328 Dst.getValueType().getTypeForEVT(*getContext()),
10329 getExternalSymbol(MemCpyImpl, TLI->getPointerTy(getDataLayout())),
10330 std::move(Args))
10332 .setTailCall(IsTailCall);
10333
10334 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
10335 return CallResult.second;
10336}
10337
10339 SDValue Dst, SDValue Src, SDValue Size,
10340 Type *SizeTy, unsigned ElemSz,
10341 bool isTailCall,
10342 MachinePointerInfo DstPtrInfo,
10343 MachinePointerInfo SrcPtrInfo) {
10344 // Lowering doesn't support tail calling inside a function with a
10345 // swifterror argument yet.
10346 isTailCall &= !hasSwiftErrorArg();
10347
10348 // Emit a library call.
10351 Args.emplace_back(Dst, ArgTy);
10352 Args.emplace_back(Src, ArgTy);
10353 Args.emplace_back(Size, SizeTy);
10354
10355 RTLIB::Libcall LibraryCall =
10357 RTLIB::LibcallImpl LibcallImpl = Libcalls->getLibcallImpl(LibraryCall);
10358 if (LibcallImpl == RTLIB::Unsupported)
10359 report_fatal_error("Unsupported element size");
10360
10362 CLI.setDebugLoc(dl)
10363 .setChain(Chain)
10364 .setLibCallee(
10365 Libcalls->getLibcallImplCallingConv(LibcallImpl),
10367 getExternalSymbol(LibcallImpl, TLI->getPointerTy(getDataLayout())),
10368 std::move(Args))
10370 .setTailCall(isTailCall);
10371
10372 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
10373 return CallResult.second;
10374}
10375
10377 SDValue Src, SDValue Size, Align DstAlign,
10378 Align SrcAlign, bool isVol, const CallInst *CI,
10379 std::optional<bool> OverrideTailCall,
10380 MachinePointerInfo DstPtrInfo,
10381 MachinePointerInfo SrcPtrInfo,
10382 const AAMDNodes &AAInfo,
10383 BatchAAResults *BatchAA) {
10384 Size = getMemIntrinsicSize(*this, dl, Size, DstPtrInfo.getAddrSpace(),
10385 SrcPtrInfo.getAddrSpace());
10386 // Check to see if we should lower the memmove to loads and stores first.
10387 // For cases within the target-specified limits, this is the best choice.
10389 if (ConstantSize) {
10390 // Memmove with size zero? Just return the original chain.
10391 if (ConstantSize->isZero())
10392 return Chain;
10393
10395 *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), DstAlign,
10396 SrcAlign, isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo);
10397 if (Result.getNode())
10398 return Result;
10399 }
10400
10401 // Then check to see if we should lower the memmove with target-specific
10402 // code. If the target chooses to do this, this is the next best.
10403 if (TSI) {
10404 SDValue Result = TSI->EmitTargetCodeForMemmove(
10405 *this, dl, Chain, Dst, Src, Size, DstAlign, SrcAlign, isVol, DstPtrInfo,
10406 SrcPtrInfo);
10407 if (Result.getNode())
10408 return Result;
10409 }
10410
10412 DstPtrInfo.getAddrSpace());
10414 SrcPtrInfo.getAddrSpace());
10415
10416 // FIXME: If the memmove is volatile, lowering it to plain libc memmove may
10417 // not be safe. See memcpy above for more details.
10418
10419 // Emit a library call.
10422 Args.emplace_back(Dst, PtrTy);
10423 Args.emplace_back(Src, PtrTy);
10424 Args.emplace_back(Size, getDataLayout().getIntPtrType(*getContext()));
10425 // FIXME: pass in SDLoc
10427
10428 RTLIB::LibcallImpl MemmoveImpl = Libcalls->getLibcallImpl(RTLIB::MEMMOVE);
10429
10430 bool IsTailCall = false;
10431 if (OverrideTailCall.has_value()) {
10432 IsTailCall = *OverrideTailCall;
10433 } else {
10434 bool LowersToMemmove = MemmoveImpl == RTLIB::impl_memmove;
10435 IsTailCall = isInTailCallPositionWrapper(CI, this, LowersToMemmove);
10436 }
10437 // Lowering doesn't support tail calling inside a function with a
10438 // swifterror argument yet.
10439 IsTailCall &= !hasSwiftErrorArg();
10440
10441 CLI.setDebugLoc(dl)
10442 .setChain(Chain)
10443 .setLibCallee(
10444 Libcalls->getLibcallImplCallingConv(MemmoveImpl),
10445 Dst.getValueType().getTypeForEVT(*getContext()),
10446 getExternalSymbol(MemmoveImpl, TLI->getPointerTy(getDataLayout())),
10447 std::move(Args))
10449 .setTailCall(IsTailCall);
10450
10451 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
10452 return CallResult.second;
10453}
10454
10456 SDValue Dst, SDValue Src, SDValue Size,
10457 Type *SizeTy, unsigned ElemSz,
10458 bool isTailCall,
10459 MachinePointerInfo DstPtrInfo,
10460 MachinePointerInfo SrcPtrInfo) {
10461 // Lowering doesn't support tail calling inside a function with a
10462 // swifterror argument yet.
10463 isTailCall &= !hasSwiftErrorArg();
10464
10465 // Emit a library call.
10468 Args.emplace_back(Dst, IntPtrTy);
10469 Args.emplace_back(Src, IntPtrTy);
10470 Args.emplace_back(Size, SizeTy);
10471
10472 RTLIB::Libcall LibraryCall =
10474 RTLIB::LibcallImpl LibcallImpl = Libcalls->getLibcallImpl(LibraryCall);
10475 if (LibcallImpl == RTLIB::Unsupported)
10476 report_fatal_error("Unsupported element size");
10477
10479 CLI.setDebugLoc(dl)
10480 .setChain(Chain)
10481 .setLibCallee(
10482 Libcalls->getLibcallImplCallingConv(LibcallImpl),
10484 getExternalSymbol(LibcallImpl, TLI->getPointerTy(getDataLayout())),
10485 std::move(Args))
10487 .setTailCall(isTailCall);
10488
10489 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
10490 return CallResult.second;
10491}
10492
10494 SDValue Src, SDValue Size, Align Alignment,
10495 bool isVol, bool AlwaysInline,
10496 const CallInst *CI,
10497 MachinePointerInfo DstPtrInfo,
10498 const AAMDNodes &AAInfo) {
10499 Size = getMemIntrinsicSize(*this, dl, Size, DstPtrInfo.getAddrSpace(),
10500 DstPtrInfo.getAddrSpace());
10501 // Check to see if we should lower the memset to stores first.
10502 // For cases within the target-specified limits, this is the best choice.
10504 if (ConstantSize) {
10505 // Memset with size zero? Just return the original chain.
10506 if (ConstantSize->isZero())
10507 return Chain;
10508
10509 SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src,
10510 ConstantSize->getZExtValue(), Alignment,
10511 isVol, false, DstPtrInfo, AAInfo);
10512
10513 if (Result.getNode())
10514 return Result;
10515 }
10516
10517 // Then check to see if we should lower the memset with target-specific
10518 // code. If the target chooses to do this, this is the next best.
10519 if (TSI) {
10520 SDValue Result = TSI->EmitTargetCodeForMemset(
10521 *this, dl, Chain, Dst, Src, Size, Alignment, isVol, AlwaysInline, DstPtrInfo);
10522 if (Result.getNode())
10523 return Result;
10524 }
10525
10526 // If we really need inline code and the target declined to provide it,
10527 // use a (potentially long) sequence of loads and stores.
10528 if (AlwaysInline) {
10529 assert(ConstantSize && "AlwaysInline requires a constant size!");
10530 SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src,
10531 ConstantSize->getZExtValue(), Alignment,
10532 isVol, true, DstPtrInfo, AAInfo);
10533 assert(Result &&
10534 "getMemsetStores must return a valid sequence when AlwaysInline");
10535 return Result;
10536 }
10537
10539 DstPtrInfo.getAddrSpace());
10540
10541 // Emit a library call.
10542 auto &Ctx = *getContext();
10543 const auto& DL = getDataLayout();
10544
10546 // FIXME: pass in SDLoc
10547 CLI.setDebugLoc(dl).setChain(Chain);
10548
10549 RTLIB::LibcallImpl BzeroImpl = Libcalls->getLibcallImpl(RTLIB::BZERO);
10550 bool UseBZero = BzeroImpl != RTLIB::Unsupported && isNullConstant(Src);
10551
10552 // If zeroing out and bzero is present, use it.
10553 if (UseBZero) {
10555 Args.emplace_back(Dst, PointerType::getUnqual(Ctx));
10556 Args.emplace_back(Size, DL.getIntPtrType(Ctx));
10557 CLI.setLibCallee(
10558 Libcalls->getLibcallImplCallingConv(BzeroImpl), Type::getVoidTy(Ctx),
10559 getExternalSymbol(BzeroImpl, TLI->getPointerTy(DL)), std::move(Args));
10560 } else {
10561 RTLIB::LibcallImpl MemsetImpl = Libcalls->getLibcallImpl(RTLIB::MEMSET);
10562
10563 MVT IntVT = MVT::getIntegerVT(LibInfo->getIntSize());
10565 Args.emplace_back(Dst, PointerType::getUnqual(Ctx));
10566 Args.emplace_back(getAnyExtOrTrunc(Src, dl, IntVT),
10567 Type::getIntNTy(Ctx, LibInfo->getIntSize()),
10568 LibInfo->getExtAttrForI32Param());
10569 Args.emplace_back(Size, DL.getIntPtrType(Ctx));
10570
10571 CLI.setLibCallee(Libcalls->getLibcallImplCallingConv(MemsetImpl),
10572 Dst.getValueType().getTypeForEVT(Ctx),
10573 getExternalSymbol(MemsetImpl, TLI->getPointerTy(DL)),
10574 std::move(Args));
10575 }
10576
10577 RTLIB::LibcallImpl MemsetImpl = Libcalls->getLibcallImpl(RTLIB::MEMSET);
10578 bool LowersToMemset = MemsetImpl == RTLIB::impl_memset;
10579
10580 // If we're going to use bzero, make sure not to tail call unless the
10581 // subsequent return doesn't need a value, as bzero doesn't return the first
10582 // arg unlike memset.
10583 bool ReturnsFirstArg = CI && funcReturnsFirstArgOfCall(*CI) && !UseBZero;
10584 bool IsTailCall = CI && CI->isTailCall() &&
10586 ReturnsFirstArg && LowersToMemset) &&
10587 // Lowering doesn't support tail calling inside a function
10588 // with a swifterror argument yet.
10590 CLI.setDiscardResult().setTailCall(IsTailCall);
10591
10592 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
10593 return CallResult.second;
10594}
10595
10598 Type *SizeTy, unsigned ElemSz,
10599 bool isTailCall,
10600 MachinePointerInfo DstPtrInfo) {
10601 // Lowering doesn't support tail calling inside a function with a
10602 // swifterror argument yet.
10603 isTailCall &= !hasSwiftErrorArg();
10604
10605 // Emit a library call.
10607 Args.emplace_back(Dst, getDataLayout().getIntPtrType(*getContext()));
10608 Args.emplace_back(Value, Type::getInt8Ty(*getContext()));
10609 Args.emplace_back(Size, SizeTy);
10610
10611 RTLIB::Libcall LibraryCall =
10613 RTLIB::LibcallImpl LibcallImpl = Libcalls->getLibcallImpl(LibraryCall);
10614 if (LibcallImpl == RTLIB::Unsupported)
10615 report_fatal_error("Unsupported element size");
10616
10618 CLI.setDebugLoc(dl)
10619 .setChain(Chain)
10620 .setLibCallee(
10621 Libcalls->getLibcallImplCallingConv(LibcallImpl),
10623 getExternalSymbol(LibcallImpl, TLI->getPointerTy(getDataLayout())),
10624 std::move(Args))
10626 .setTailCall(isTailCall);
10627
10628 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
10629 return CallResult.second;
10630}
10631
10632SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
10634 MachineMemOperand *MMO,
10635 ISD::LoadExtType ExtType) {
10636 SDNodeKey ID(Opcode, VTList, Ops);
10637 ID.AddInteger(MemVT.getRawBits());
10638 ID.AddInteger(getSyntheticNodeSubclassData<AtomicSDNode>(
10639 dl.getIROrder(), Opcode, VTList, MemVT, MMO, ExtType));
10640 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
10641 ID.AddInteger(MMO->getFlags());
10642 FoldingSetInsertToken InsertToken;
10643 if (auto *E = cast_or_null<AtomicSDNode>(lookupNode(ID, dl, InsertToken))) {
10644 E->refineAlignment(MMO);
10645 E->refineMMOMetadata(MMO);
10646 return SDValue(E, 0);
10647 }
10648
10649 auto *N = newSDNode<AtomicSDNode>(dl.getIROrder(), dl.getDebugLoc(), Opcode,
10650 VTList, MemVT, MMO, ExtType);
10651 createOperands(N, Ops);
10652
10653 CSEMap.insert(N, InsertToken);
10654 InsertNode(N);
10655 SDValue V(N, 0);
10656 NewSDValueDbgMsg(V, "Creating new node: ", this);
10657 return V;
10658}
10659
10661 EVT MemVT, SDVTList VTs, SDValue Chain,
10662 SDValue Ptr, SDValue Cmp, SDValue Swp,
10663 MachineMemOperand *MMO) {
10664 assert(Opcode == ISD::ATOMIC_CMP_SWAP ||
10666 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
10667
10668 SDValue Ops[] = {Chain, Ptr, Cmp, Swp};
10669 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
10670}
10671
10672SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
10673 SDValue Chain, SDValue Ptr, SDValue Val,
10674 MachineMemOperand *MMO) {
10675 assert((Opcode == ISD::ATOMIC_LOAD_ADD || Opcode == ISD::ATOMIC_LOAD_SUB ||
10676 Opcode == ISD::ATOMIC_LOAD_AND || Opcode == ISD::ATOMIC_LOAD_CLR ||
10677 Opcode == ISD::ATOMIC_LOAD_OR || Opcode == ISD::ATOMIC_LOAD_XOR ||
10678 Opcode == ISD::ATOMIC_LOAD_NAND || Opcode == ISD::ATOMIC_LOAD_MIN ||
10679 Opcode == ISD::ATOMIC_LOAD_MAX || Opcode == ISD::ATOMIC_LOAD_UMIN ||
10680 Opcode == ISD::ATOMIC_LOAD_UMAX || Opcode == ISD::ATOMIC_LOAD_FADD ||
10681 Opcode == ISD::ATOMIC_LOAD_FSUB || Opcode == ISD::ATOMIC_LOAD_FMAX ||
10682 Opcode == ISD::ATOMIC_LOAD_FMIN ||
10683 Opcode == ISD::ATOMIC_LOAD_FMINIMUM ||
10684 Opcode == ISD::ATOMIC_LOAD_FMAXIMUM ||
10685 Opcode == ISD::ATOMIC_LOAD_UINC_WRAP ||
10686 Opcode == ISD::ATOMIC_LOAD_UDEC_WRAP ||
10687 Opcode == ISD::ATOMIC_LOAD_USUB_COND ||
10688 Opcode == ISD::ATOMIC_LOAD_USUB_SAT || Opcode == ISD::ATOMIC_SWAP ||
10689 Opcode == ISD::ATOMIC_STORE) &&
10690 "Invalid Atomic Op");
10691
10692 EVT VT = Val.getValueType();
10693
10694 SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) :
10695 getVTList(VT, MVT::Other);
10696 SDValue Ops[] = {Chain, Ptr, Val};
10697 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
10698}
10699
10701 EVT MemVT, EVT VT, SDValue Chain,
10702 SDValue Ptr, MachineMemOperand *MMO) {
10703 SDVTList VTs = getVTList(VT, MVT::Other);
10704 SDValue Ops[] = {Chain, Ptr};
10705 return getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, VTs, Ops, MMO, ExtType);
10706}
10707
10708/// getMergeValues - Create a MERGE_VALUES node from the given operands.
10710 if (Ops.size() == 1)
10711 return Ops[0];
10712
10714 VTs.reserve(Ops.size());
10715 for (const SDValue &Op : Ops)
10716 VTs.push_back(Op.getValueType());
10717 return getNode(ISD::MERGE_VALUES, dl, getVTList(VTs), Ops);
10718}
10719
10721 SDValue Chain, const SDLoc &dl) {
10722 SmallVector<SDValue, 4> RetValues;
10723 RetValues.reserve(ResultTypes.size());
10724 for (EVT VT : ResultTypes)
10725 RetValues.push_back(VT == MVT::Other ? Chain : getPOISON(VT));
10726 return getMergeValues(RetValues, dl);
10727}
10728
10730 unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef<SDValue> Ops,
10731 EVT MemVT, MachinePointerInfo PtrInfo, Align Alignment,
10733 const AAMDNodes &AAInfo) {
10734 if (Size.hasValue() && !Size.getValue())
10736
10738 MachineMemOperand *MMO =
10739 MF.getMachineMemOperand(PtrInfo, Flags, Size, Alignment, AAInfo);
10740
10741 return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, MMO);
10742}
10743
10745 SDVTList VTList,
10746 ArrayRef<SDValue> Ops, EVT MemVT,
10747 MachineMemOperand *MMO) {
10748 return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, ArrayRef(MMO));
10749}
10750
10752 SDVTList VTList,
10753 ArrayRef<SDValue> Ops, EVT MemVT,
10755 assert(!MMOs.empty() && "Must have at least one MMO");
10756 assert(
10757 (Opcode == ISD::INTRINSIC_VOID || Opcode == ISD::INTRINSIC_W_CHAIN ||
10758 Opcode == ISD::PREFETCH ||
10759 (Opcode <= (unsigned)std::numeric_limits<int>::max() &&
10760 Opcode >= ISD::BUILTIN_OP_END && TSI->isTargetMemoryOpcode(Opcode))) &&
10761 "Opcode is not a memory-accessing opcode!");
10762
10764 if (MMOs.size() == 1) {
10765 MemRefs = MMOs[0];
10766 } else {
10767 // Allocate: [size_t count][MMO*][MMO*]...
10768 size_t AllocSize =
10769 sizeof(size_t) + MMOs.size() * sizeof(MachineMemOperand *);
10770 void *Buffer = Allocator.Allocate(AllocSize, alignof(size_t));
10771 size_t *CountPtr = static_cast<size_t *>(Buffer);
10772 *CountPtr = MMOs.size();
10773 MachineMemOperand **Array =
10774 reinterpret_cast<MachineMemOperand **>(CountPtr + 1);
10775 llvm::copy(MMOs, Array);
10776 MemRefs = Array;
10777 }
10778
10779 // Memoize the node unless it returns a glue result.
10781 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
10782 SDNodeKey ID(Opcode, VTList, Ops);
10783 ID.AddInteger(getSyntheticNodeSubclassData<MemIntrinsicSDNode>(
10784 Opcode, dl.getIROrder(), VTList, MemVT, MemRefs));
10785 ID.AddInteger(MemVT.getRawBits());
10786 for (const MachineMemOperand *MMO : MMOs) {
10787 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
10788 ID.AddInteger(MMO->getFlags());
10789 }
10790 FoldingSetInsertToken InsertToken;
10791 if (SDNode *E = lookupNode(ID, dl, InsertToken)) {
10792 cast<MemIntrinsicSDNode>(E)->refineAlignment(MMOs);
10793 return SDValue(E, 0);
10794 }
10795
10796 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
10797 VTList, MemVT, MemRefs);
10798 createOperands(N, Ops);
10799 CSEMap.insert(N, InsertToken);
10800 } else {
10801 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
10802 VTList, MemVT, MemRefs);
10803 createOperands(N, Ops);
10804 }
10805 InsertNode(N);
10806 SDValue V(N, 0);
10807 NewSDValueDbgMsg(V, "Creating new node: ", this);
10808 return V;
10809}
10810
10812 SDValue Chain, int FrameIndex) {
10813 const unsigned Opcode = IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END;
10814 const auto VTs = getVTList(MVT::Other);
10815 SDValue Ops[2] = {
10816 Chain,
10817 getFrameIndex(FrameIndex,
10818 getTargetLoweringInfo().getFrameIndexTy(getDataLayout()),
10819 true)};
10820
10821 SDNodeKey ID(Opcode, VTs, Ops);
10822 FoldingSetInsertToken InsertToken;
10823 if (SDNode *E = lookupNode(ID, dl, InsertToken))
10824 return SDValue(E, 0);
10825
10826 LifetimeSDNode *N =
10827 newSDNode<LifetimeSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), VTs);
10828 createOperands(N, Ops);
10829 CSEMap.insert(N, InsertToken);
10830 InsertNode(N);
10831 SDValue V(N, 0);
10832 NewSDValueDbgMsg(V, "Creating new node: ", this);
10833 return V;
10834}
10835
10837 uint64_t Guid, uint64_t Index,
10838 uint32_t Attr) {
10839 const unsigned Opcode = ISD::PSEUDO_PROBE;
10840 const auto VTs = getVTList(MVT::Other);
10841 SDValue Ops[] = {Chain};
10842 SDNodeKey ID(Opcode, VTs, Ops);
10843 ID.AddInteger(Guid);
10844 ID.AddInteger(Index);
10845 ID.AddInteger(Attr);
10846 FoldingSetInsertToken InsertToken;
10847 if (SDNode *E = lookupNode(ID, Dl, InsertToken))
10848 return SDValue(E, 0);
10849
10850 auto *N = newSDNode<PseudoProbeSDNode>(
10851 Opcode, Dl.getIROrder(), Dl.getDebugLoc(), VTs, Guid, Index, Attr);
10852 createOperands(N, Ops);
10853 CSEMap.insert(N, InsertToken);
10854 InsertNode(N);
10855 SDValue V(N, 0);
10856 NewSDValueDbgMsg(V, "Creating new node: ", this);
10857 return V;
10858}
10859
10860/// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
10861/// MachinePointerInfo record from it. This is particularly useful because the
10862/// code generator has many cases where it doesn't bother passing in a
10863/// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
10865 SelectionDAG &DAG, SDValue Ptr,
10866 int64_t Offset = 0) {
10867 // If this is FI+Offset, we can model it.
10868 if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr))
10870 FI->getIndex(), Offset);
10871
10872 // If this is (FI+Offset1)+Offset2, we can model it.
10873 if (Ptr.getOpcode() != ISD::ADD ||
10876 return Info;
10877
10878 int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
10880 DAG.getMachineFunction(), FI,
10881 Offset + cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue());
10882}
10883
10884/// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
10885/// MachinePointerInfo record from it. This is particularly useful because the
10886/// code generator has many cases where it doesn't bother passing in a
10887/// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
10889 SelectionDAG &DAG, SDValue Ptr,
10890 SDValue OffsetOp) {
10891 // If the 'Offset' value isn't a constant, we can't handle this.
10893 return InferPointerInfo(Info, DAG, Ptr, OffsetNode->getSExtValue());
10894 if (OffsetOp.isUndef())
10895 return InferPointerInfo(Info, DAG, Ptr);
10896 return Info;
10897}
10898
10900 EVT VT, const SDLoc &dl, SDValue Chain,
10901 SDValue Ptr, SDValue Offset,
10902 MachinePointerInfo PtrInfo, EVT MemVT,
10903 Align Alignment,
10904 MachineMemOperand::Flags MMOFlags,
10905 const MMOMetadata &Metadata) {
10906 assert(Chain.getValueType() == MVT::Other &&
10907 "Invalid chain type");
10908
10909 MMOFlags |= MachineMemOperand::MOLoad;
10910 assert((MMOFlags & MachineMemOperand::MOStore) == 0);
10911 // If we don't have a PtrInfo, infer the trivial frame index case to simplify
10912 // clients.
10913 if (PtrInfo.V.isNull())
10914 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
10915
10916 TypeSize Size = MemVT.getStoreSize();
10918 MachineMemOperand *MMO =
10919 MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, Alignment, Metadata);
10920 return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO);
10921}
10922
10924 EVT VT, const SDLoc &dl, SDValue Chain,
10925 SDValue Ptr, SDValue Offset, EVT MemVT,
10926 MachineMemOperand *MMO) {
10927 if (VT == MemVT) {
10928 ExtType = ISD::NON_EXTLOAD;
10929 } else if (ExtType == ISD::NON_EXTLOAD) {
10930 assert(VT == MemVT && "Non-extending load from different memory type!");
10931 } else {
10932 // Extending load.
10933 assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) &&
10934 "Should only be an extending load, not truncating!");
10935 assert(VT.isInteger() == MemVT.isInteger() &&
10936 "Cannot convert from FP to Int or Int -> FP!");
10937 assert(VT.isVector() == MemVT.isVector() &&
10938 "Cannot use an ext load to convert to or from a vector!");
10939 assert((!VT.isVector() ||
10941 "Cannot use an ext load to change the number of vector elements!");
10942 }
10943
10944 assert((!MMO->getRanges() ||
10946 ->getBitWidth() == MemVT.getScalarSizeInBits() &&
10947 MemVT.isInteger())) &&
10948 "Range metadata and load type must match!");
10949
10950 bool Indexed = AM != ISD::UNINDEXED;
10951 assert((Indexed || Offset.getOpcode() == ISD::POISON) &&
10952 "Unindexed load with an offset!");
10953
10954 SDVTList VTs = Indexed ?
10955 getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
10956 SDValue Ops[] = { Chain, Ptr, Offset };
10957 SDNodeKey ID(ISD::LOAD, VTs, Ops);
10958 ID.AddInteger(MemVT.getRawBits());
10959 ID.AddInteger(getSyntheticNodeSubclassData<LoadSDNode>(
10960 dl.getIROrder(), VTs, AM, ExtType, MemVT, MMO));
10961 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
10962 ID.AddInteger(MMO->getFlags());
10963 FoldingSetInsertToken InsertToken;
10964 if (auto *E = cast_or_null<LoadSDNode>(lookupNode(ID, dl, InsertToken))) {
10965 E->refineAlignment(MMO);
10966 E->refineMMOMetadata(MMO);
10967 return SDValue(E, 0);
10968 }
10969 auto *N = newSDNode<LoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
10970 ExtType, MemVT, MMO);
10971 createOperands(N, Ops);
10972
10973 CSEMap.insert(N, InsertToken);
10974 InsertNode(N);
10975 SDValue V(N, 0);
10976 NewSDValueDbgMsg(V, "Creating new node: ", this);
10977 return V;
10978}
10979
10981 SDValue Ptr, MachinePointerInfo PtrInfo,
10982 MaybeAlign Alignment,
10983 MachineMemOperand::Flags MMOFlags,
10984 const MMOMetadata &Metadata) {
10986 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
10987 PtrInfo, VT, Alignment, MMOFlags, Metadata);
10988}
10989
10991 SDValue Ptr, MachineMemOperand *MMO) {
10993 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
10994 VT, MMO);
10995}
10996
10998 EVT VT, SDValue Chain, SDValue Ptr,
10999 MachinePointerInfo PtrInfo, EVT MemVT,
11000 MaybeAlign Alignment,
11001 MachineMemOperand::Flags MMOFlags,
11002 const MMOMetadata &Metadata) {
11004 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, PtrInfo,
11005 MemVT, Alignment, MMOFlags, Metadata);
11006}
11007
11009 EVT VT, SDValue Chain, SDValue Ptr, EVT MemVT,
11010 MachineMemOperand *MMO) {
11012 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef,
11013 MemVT, MMO);
11014}
11015
11019 LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
11020 assert(LD->getOffset().getOpcode() == ISD::POISON &&
11021 "Load is already a indexed load!");
11022 // Don't propagate the invariant or dereferenceable flags.
11023 auto MMOFlags =
11024 LD->getMemOperand()->getFlags() &
11026 return getLoad(
11027 AM, LD->getExtensionType(), OrigLoad.getValueType(), dl, LD->getChain(),
11028 Base, Offset, LD->getPointerInfo(), LD->getMemoryVT(), LD->getAlign(),
11029 MMOFlags,
11030 MMOMetadata(LD->getAAInfo(), LD->getRanges(), LD->getMemCacheHint()));
11031}
11032
11034 SDValue Ptr, MachinePointerInfo PtrInfo,
11035 Align Alignment,
11036 MachineMemOperand::Flags MMOFlags,
11037 const MMOMetadata &Metadata) {
11038 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
11039
11040 MMOFlags |= MachineMemOperand::MOStore;
11041 assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
11042 assert(!Metadata.Ranges && "range metadata is invalid for stores");
11043
11044 if (PtrInfo.V.isNull())
11045 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
11046
11049 MachineMemOperand *MMO =
11050 MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, Alignment, Metadata);
11051 return getStore(Chain, dl, Val, Ptr, MMO);
11052}
11053
11055 SDValue Ptr, MachineMemOperand *MMO) {
11057 return getStore(Chain, dl, Val, Ptr, Undef, Val.getValueType(), MMO,
11059}
11060
11062 SDValue Ptr, SDValue Offset, EVT SVT,
11064 bool IsTruncating) {
11065 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
11066 EVT VT = Val.getValueType();
11067 if (VT == SVT) {
11068 IsTruncating = false;
11069 } else if (!IsTruncating) {
11070 assert(VT == SVT && "No-truncating store from different memory type!");
11071 } else {
11073 "Should only be a truncating store, not extending!");
11074 assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!");
11075 assert(VT.isVector() == SVT.isVector() &&
11076 "Cannot use trunc store to convert to or from a vector!");
11077 assert((!VT.isVector() ||
11079 "Cannot use trunc store to change the number of vector elements!");
11080 }
11081
11082 bool Indexed = AM != ISD::UNINDEXED;
11083 assert((Indexed || Offset.getOpcode() == ISD::POISON) &&
11084 "Unindexed store with an offset!");
11085 SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other)
11086 : getVTList(MVT::Other);
11087 SDValue Ops[] = {Chain, Val, Ptr, Offset};
11088 SDNodeKey ID(ISD::STORE, VTs, Ops);
11089 ID.AddInteger(SVT.getRawBits());
11090 ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
11091 dl.getIROrder(), VTs, AM, IsTruncating, SVT, MMO));
11092 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11093 ID.AddInteger(MMO->getFlags());
11094 FoldingSetInsertToken InsertToken;
11095 if (SDNode *E = lookupNode(ID, dl, InsertToken)) {
11096 cast<StoreSDNode>(E)->refineAlignment(MMO);
11097 cast<StoreSDNode>(E)->refineMMOMetadata(MMO);
11098 return SDValue(E, 0);
11099 }
11100 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
11101 IsTruncating, SVT, MMO);
11102 createOperands(N, Ops);
11103
11104 CSEMap.insert(N, InsertToken);
11105 InsertNode(N);
11106 SDValue V(N, 0);
11107 NewSDValueDbgMsg(V, "Creating new node: ", this);
11108 return V;
11109}
11110
11112 SDValue Ptr, SDValue Offset,
11113 MachinePointerInfo PtrInfo, EVT SVT,
11114 Align Alignment,
11115 MachineMemOperand::Flags MMOFlags,
11116 const MMOMetadata &Metadata) {
11117 assert(Chain.getValueType() == MVT::Other &&
11118 "Invalid chain type");
11119
11120 MMOFlags |= MachineMemOperand::MOStore;
11121 assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
11122 assert(!Metadata.Ranges && "range metadata is invalid for stores");
11123
11124 if (PtrInfo.V.isNull())
11125 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
11126
11128 MachineMemOperand *MMO = MF.getMachineMemOperand(
11129 PtrInfo, MMOFlags, SVT.getStoreSize(), Alignment, Metadata);
11130 return getTruncStore(Chain, dl, Val, Ptr, Offset, SVT, MMO);
11131}
11132
11134 SDValue Ptr, MachinePointerInfo PtrInfo,
11135 EVT SVT, Align Alignment,
11136 MachineMemOperand::Flags MMOFlags,
11137 const MMOMetadata &Metadata) {
11138 return getTruncStore(Chain, dl, Val, Ptr, getPOISON(Ptr.getValueType()),
11139 PtrInfo, SVT, Alignment, MMOFlags, Metadata);
11140}
11141
11143 SDValue Ptr, SDValue Offset, EVT SVT,
11144 MachineMemOperand *MMO) {
11145 return getStore(Chain, dl, Val, Ptr, Offset, SVT, MMO, ISD::UNINDEXED, true);
11146}
11147
11149 SDValue Ptr, EVT SVT,
11150 MachineMemOperand *MMO) {
11151 return getStore(Chain, dl, Val, Ptr, getPOISON(Ptr.getValueType()), SVT, MMO,
11152 ISD::UNINDEXED, true);
11153}
11154
11158 StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
11159 assert(ST->getOffset().getOpcode() == ISD::POISON &&
11160 "Store is already a indexed store!");
11161 return getStore(ST->getChain(), dl, ST->getValue(), Base, Offset,
11162 ST->getMemoryVT(), ST->getMemOperand(), AM,
11163 ST->isTruncatingStore());
11164}
11165
11167 ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &dl,
11168 SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Mask, SDValue EVL,
11169 MachinePointerInfo PtrInfo, EVT MemVT, Align Alignment,
11170 MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
11171 const MDNode *Ranges, bool IsExpanding) {
11172 MMOFlags |= MachineMemOperand::MOLoad;
11173 assert((MMOFlags & MachineMemOperand::MOStore) == 0);
11174 // If we don't have a PtrInfo, infer the trivial frame index case to simplify
11175 // clients.
11176 if (PtrInfo.V.isNull())
11177 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
11178
11179 TypeSize Size = MemVT.getStoreSize();
11181 MachineMemOperand *MMO = MF.getMachineMemOperand(
11182 PtrInfo, MMOFlags, Size, Alignment, MMOMetadata(AAInfo, Ranges));
11183 return getLoadVP(AM, ExtType, VT, dl, Chain, Ptr, Offset, Mask, EVL, MemVT,
11184 MMO, IsExpanding);
11185}
11186
11188 ISD::LoadExtType ExtType, EVT VT,
11189 const SDLoc &dl, SDValue Chain, SDValue Ptr,
11190 SDValue Offset, SDValue Mask, SDValue EVL,
11191 EVT MemVT, MachineMemOperand *MMO,
11192 bool IsExpanding) {
11193 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
11194 assert(Mask.getValueType().getVectorElementCount() ==
11195 VT.getVectorElementCount() &&
11196 "Vector width mismatch between mask and data");
11197
11198 bool Indexed = AM != ISD::UNINDEXED;
11199 assert((Indexed || Offset.getOpcode() == ISD::POISON) &&
11200 "Unindexed load with an offset!");
11201
11202 SDVTList VTs = Indexed ? getVTList(VT, Ptr.getValueType(), MVT::Other)
11203 : getVTList(VT, MVT::Other);
11204 SDValue Ops[] = {Chain, Ptr, Offset, Mask, EVL};
11205 SDNodeKey ID(ISD::VP_LOAD, VTs, Ops);
11206 ID.AddInteger(MemVT.getRawBits());
11207 ID.AddInteger(getSyntheticNodeSubclassData<VPLoadSDNode>(
11208 dl.getIROrder(), VTs, AM, ExtType, IsExpanding, MemVT, MMO));
11209 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11210 ID.AddInteger(MMO->getFlags());
11211 FoldingSetInsertToken InsertToken;
11212 if (auto *E = cast_or_null<VPLoadSDNode>(lookupNode(ID, dl, InsertToken))) {
11213 E->refineAlignment(MMO);
11214 E->refineMMOMetadata(MMO);
11215 return SDValue(E, 0);
11216 }
11217 auto *N = newSDNode<VPLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
11218 ExtType, IsExpanding, MemVT, MMO);
11219 createOperands(N, Ops);
11220
11221 CSEMap.insert(N, InsertToken);
11222 InsertNode(N);
11223 SDValue V(N, 0);
11224 NewSDValueDbgMsg(V, "Creating new node: ", this);
11225 return V;
11226}
11227
11229 SDValue Ptr, SDValue Mask, SDValue EVL,
11230 MachinePointerInfo PtrInfo,
11231 MaybeAlign Alignment,
11232 MachineMemOperand::Flags MMOFlags,
11233 const AAMDNodes &AAInfo, const MDNode *Ranges,
11234 bool IsExpanding) {
11236 return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
11237 Mask, EVL, PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges,
11238 IsExpanding);
11239}
11240
11242 SDValue Ptr, SDValue Mask, SDValue EVL,
11243 MachineMemOperand *MMO, bool IsExpanding) {
11245 return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
11246 Mask, EVL, VT, MMO, IsExpanding);
11247}
11248
11250 EVT VT, SDValue Chain, SDValue Ptr,
11251 SDValue Mask, SDValue EVL,
11252 MachinePointerInfo PtrInfo, EVT MemVT,
11253 MaybeAlign Alignment,
11254 MachineMemOperand::Flags MMOFlags,
11255 const AAMDNodes &AAInfo, bool IsExpanding) {
11257 return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask,
11258 EVL, PtrInfo, MemVT, Alignment, MMOFlags, AAInfo, nullptr,
11259 IsExpanding);
11260}
11261
11263 EVT VT, SDValue Chain, SDValue Ptr,
11264 SDValue Mask, SDValue EVL, EVT MemVT,
11265 MachineMemOperand *MMO, bool IsExpanding) {
11267 return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask,
11268 EVL, MemVT, MMO, IsExpanding);
11269}
11270
11272 SDValue Ptr, SDValue Offset, SDValue Mask,
11273 SDValue EVL, EVT MemVT, MachineMemOperand *MMO,
11274 ISD::MemIndexedMode AM, bool IsTruncating,
11275 bool IsCompressing) {
11276 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
11277 assert(Mask.getValueType().getVectorElementCount() ==
11279 "Vector width mismatch between mask and data");
11280
11281 bool Indexed = AM != ISD::UNINDEXED;
11282 assert((Indexed || Offset.getOpcode() == ISD::POISON) &&
11283 "Unindexed vp_store with an offset!");
11284 SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other)
11285 : getVTList(MVT::Other);
11286 SDValue Ops[] = {Chain, Val, Ptr, Offset, Mask, EVL};
11287 SDNodeKey ID(ISD::VP_STORE, VTs, Ops);
11288 ID.AddInteger(MemVT.getRawBits());
11289 ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>(
11290 dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
11291 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11292 ID.AddInteger(MMO->getFlags());
11293 FoldingSetInsertToken InsertToken;
11294 if (SDNode *E = lookupNode(ID, dl, InsertToken)) {
11295 cast<VPStoreSDNode>(E)->refineAlignment(MMO);
11296 return SDValue(E, 0);
11297 }
11298 auto *N = newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
11299 IsTruncating, IsCompressing, MemVT, MMO);
11300 createOperands(N, Ops);
11301
11302 CSEMap.insert(N, InsertToken);
11303 InsertNode(N);
11304 SDValue V(N, 0);
11305 NewSDValueDbgMsg(V, "Creating new node: ", this);
11306 return V;
11307}
11308
11310 SDValue Val, SDValue Ptr, SDValue Mask,
11311 SDValue EVL, MachinePointerInfo PtrInfo,
11312 EVT SVT, Align Alignment,
11313 MachineMemOperand::Flags MMOFlags,
11314 const AAMDNodes &AAInfo,
11315 bool IsCompressing) {
11316 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
11317
11318 MMOFlags |= MachineMemOperand::MOStore;
11319 assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
11320
11321 if (PtrInfo.V.isNull())
11322 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
11323
11325 MachineMemOperand *MMO = MF.getMachineMemOperand(
11326 PtrInfo, MMOFlags, SVT.getStoreSize(), Alignment, AAInfo);
11327 return getTruncStoreVP(Chain, dl, Val, Ptr, Mask, EVL, SVT, MMO,
11328 IsCompressing);
11329}
11330
11332 SDValue Val, SDValue Ptr, SDValue Mask,
11333 SDValue EVL, EVT SVT,
11334 MachineMemOperand *MMO,
11335 bool IsCompressing) {
11336 EVT VT = Val.getValueType();
11337
11338 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
11339 if (VT == SVT)
11340 return getStoreVP(Chain, dl, Val, Ptr, getPOISON(Ptr.getValueType()), Mask,
11341 EVL, VT, MMO, ISD::UNINDEXED,
11342 /*IsTruncating*/ false, IsCompressing);
11343
11345 "Should only be a truncating store, not extending!");
11346 assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!");
11347 assert(VT.isVector() == SVT.isVector() &&
11348 "Cannot use trunc store to convert to or from a vector!");
11349 assert((!VT.isVector() ||
11351 "Cannot use trunc store to change the number of vector elements!");
11352
11353 SDVTList VTs = getVTList(MVT::Other);
11355 SDValue Ops[] = {Chain, Val, Ptr, Undef, Mask, EVL};
11356 SDNodeKey ID(ISD::VP_STORE, VTs, Ops);
11357 ID.AddInteger(SVT.getRawBits());
11358 ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>(
11359 dl.getIROrder(), VTs, ISD::UNINDEXED, true, IsCompressing, SVT, MMO));
11360 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11361 ID.AddInteger(MMO->getFlags());
11362 FoldingSetInsertToken InsertToken;
11363 if (SDNode *E = lookupNode(ID, dl, InsertToken)) {
11364 cast<VPStoreSDNode>(E)->refineAlignment(MMO);
11365 return SDValue(E, 0);
11366 }
11367 auto *N =
11368 newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
11369 ISD::UNINDEXED, true, IsCompressing, SVT, MMO);
11370 createOperands(N, Ops);
11371
11372 CSEMap.insert(N, InsertToken);
11373 InsertNode(N);
11374 SDValue V(N, 0);
11375 NewSDValueDbgMsg(V, "Creating new node: ", this);
11376 return V;
11377}
11378
11380 ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &DL,
11381 SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Stride, SDValue Mask,
11382 SDValue EVL, EVT MemVT, MachineMemOperand *MMO, bool IsExpanding) {
11383 bool Indexed = AM != ISD::UNINDEXED;
11384 assert((Indexed || Offset.getOpcode() == ISD::POISON) &&
11385 "Unindexed load with an offset!");
11386
11387 SDValue Ops[] = {Chain, Ptr, Offset, Stride, Mask, EVL};
11388 SDVTList VTs = Indexed ? getVTList(VT, Ptr.getValueType(), MVT::Other)
11389 : getVTList(VT, MVT::Other);
11390 SDNodeKey ID(ISD::EXPERIMENTAL_VP_STRIDED_LOAD, VTs, Ops);
11391 ID.AddInteger(MemVT.getRawBits());
11392 ID.AddInteger(getSyntheticNodeSubclassData<VPStridedLoadSDNode>(
11393 DL.getIROrder(), VTs, AM, ExtType, IsExpanding, MemVT, MMO));
11394 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11395
11396 FoldingSetInsertToken InsertToken;
11397 if (SDNode *E = lookupNode(ID, DL, InsertToken)) {
11398 cast<VPStridedLoadSDNode>(E)->refineAlignment(MMO);
11399 return SDValue(E, 0);
11400 }
11401
11402 auto *N =
11403 newSDNode<VPStridedLoadSDNode>(DL.getIROrder(), DL.getDebugLoc(), VTs, AM,
11404 ExtType, IsExpanding, MemVT, MMO);
11405 createOperands(N, Ops);
11406 CSEMap.insert(N, InsertToken);
11407 InsertNode(N);
11408 SDValue V(N, 0);
11409 NewSDValueDbgMsg(V, "Creating new node: ", this);
11410 return V;
11411}
11412
11414 SDValue Ptr, SDValue Stride,
11415 SDValue Mask, SDValue EVL,
11416 MachineMemOperand *MMO,
11417 bool IsExpanding) {
11419 return getStridedLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, DL, Chain, Ptr,
11420 Undef, Stride, Mask, EVL, VT, MMO, IsExpanding);
11421}
11422
11424 ISD::LoadExtType ExtType, const SDLoc &DL, EVT VT, SDValue Chain,
11425 SDValue Ptr, SDValue Stride, SDValue Mask, SDValue EVL, EVT MemVT,
11426 MachineMemOperand *MMO, bool IsExpanding) {
11428 return getStridedLoadVP(ISD::UNINDEXED, ExtType, VT, DL, Chain, Ptr, Undef,
11429 Stride, Mask, EVL, MemVT, MMO, IsExpanding);
11430}
11431
11433 SDValue Val, SDValue Ptr,
11434 SDValue Offset, SDValue Stride,
11435 SDValue Mask, SDValue EVL, EVT MemVT,
11436 MachineMemOperand *MMO,
11438 bool IsTruncating, bool IsCompressing) {
11439 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
11440 bool Indexed = AM != ISD::UNINDEXED;
11441 assert((Indexed || Offset.getOpcode() == ISD::POISON) &&
11442 "Unindexed vp_store with an offset!");
11443 SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other)
11444 : getVTList(MVT::Other);
11445 SDValue Ops[] = {Chain, Val, Ptr, Offset, Stride, Mask, EVL};
11446 SDNodeKey ID(ISD::EXPERIMENTAL_VP_STRIDED_STORE, VTs, Ops);
11447 ID.AddInteger(MemVT.getRawBits());
11448 ID.AddInteger(getSyntheticNodeSubclassData<VPStridedStoreSDNode>(
11449 DL.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
11450 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11451 FoldingSetInsertToken InsertToken;
11452 if (SDNode *E = lookupNode(ID, DL, InsertToken)) {
11453 cast<VPStridedStoreSDNode>(E)->refineAlignment(MMO);
11454 return SDValue(E, 0);
11455 }
11456 auto *N = newSDNode<VPStridedStoreSDNode>(DL.getIROrder(), DL.getDebugLoc(),
11457 VTs, AM, IsTruncating,
11458 IsCompressing, MemVT, MMO);
11459 createOperands(N, Ops);
11460
11461 CSEMap.insert(N, InsertToken);
11462 InsertNode(N);
11463 SDValue V(N, 0);
11464 NewSDValueDbgMsg(V, "Creating new node: ", this);
11465 return V;
11466}
11467
11470 ISD::MemIndexType IndexType) {
11471 assert(Ops.size() == 6 && "Incompatible number of operands");
11472
11473 SDNodeKey ID(ISD::VP_GATHER, VTs, Ops);
11474 ID.AddInteger(VT.getRawBits());
11475 ID.AddInteger(getSyntheticNodeSubclassData<VPGatherSDNode>(
11476 dl.getIROrder(), VTs, VT, MMO, IndexType));
11477 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11478 ID.AddInteger(MMO->getFlags());
11479 FoldingSetInsertToken InsertToken;
11480 if (SDNode *E = lookupNode(ID, dl, InsertToken)) {
11481 cast<VPGatherSDNode>(E)->refineAlignment(MMO);
11482 return SDValue(E, 0);
11483 }
11484
11485 auto *N = newSDNode<VPGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
11486 VT, MMO, IndexType);
11487 createOperands(N, Ops);
11488
11489 assert(N->getMask().getValueType().getVectorElementCount() ==
11490 N->getValueType(0).getVectorElementCount() &&
11491 "Vector width mismatch between mask and data");
11492 assert(N->getIndex().getValueType().getVectorElementCount().isScalable() ==
11493 N->getValueType(0).getVectorElementCount().isScalable() &&
11494 "Scalable flags of index and data do not match");
11496 N->getIndex().getValueType().getVectorElementCount(),
11497 N->getValueType(0).getVectorElementCount()) &&
11498 "Vector width mismatch between index and data");
11499 assert(isa<ConstantSDNode>(N->getScale()) &&
11500 N->getScale()->getAsAPIntVal().isPowerOf2() &&
11501 "Scale should be a constant power of 2");
11502
11503 CSEMap.insert(N, InsertToken);
11504 InsertNode(N);
11505 SDValue V(N, 0);
11506 NewSDValueDbgMsg(V, "Creating new node: ", this);
11507 return V;
11508}
11509
11512 MachineMemOperand *MMO,
11513 ISD::MemIndexType IndexType) {
11514 assert(Ops.size() == 7 && "Incompatible number of operands");
11515
11516 SDNodeKey ID(ISD::VP_SCATTER, VTs, Ops);
11517 ID.AddInteger(VT.getRawBits());
11518 ID.AddInteger(getSyntheticNodeSubclassData<VPScatterSDNode>(
11519 dl.getIROrder(), VTs, VT, MMO, IndexType));
11520 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11521 ID.AddInteger(MMO->getFlags());
11522 FoldingSetInsertToken InsertToken;
11523 if (SDNode *E = lookupNode(ID, dl, InsertToken)) {
11524 cast<VPScatterSDNode>(E)->refineAlignment(MMO);
11525 return SDValue(E, 0);
11526 }
11527 auto *N = newSDNode<VPScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
11528 VT, MMO, IndexType);
11529 createOperands(N, Ops);
11530
11531 assert(N->getMask().getValueType().getVectorElementCount() ==
11532 N->getValue().getValueType().getVectorElementCount() &&
11533 "Vector width mismatch between mask and data");
11534 assert(
11535 N->getIndex().getValueType().getVectorElementCount().isScalable() ==
11536 N->getValue().getValueType().getVectorElementCount().isScalable() &&
11537 "Scalable flags of index and data do not match");
11539 N->getIndex().getValueType().getVectorElementCount(),
11540 N->getValue().getValueType().getVectorElementCount()) &&
11541 "Vector width mismatch between index and data");
11542 assert(isa<ConstantSDNode>(N->getScale()) &&
11543 N->getScale()->getAsAPIntVal().isPowerOf2() &&
11544 "Scale should be a constant power of 2");
11545
11546 CSEMap.insert(N, InsertToken);
11547 InsertNode(N);
11548 SDValue V(N, 0);
11549 NewSDValueDbgMsg(V, "Creating new node: ", this);
11550 return V;
11551}
11552
11555 SDValue PassThru, EVT MemVT,
11556 MachineMemOperand *MMO,
11558 ISD::LoadExtType ExtTy, bool isExpanding) {
11559 bool Indexed = AM != ISD::UNINDEXED;
11560 assert((Indexed || Offset.getOpcode() == ISD::POISON) &&
11561 "Unindexed masked load with an offset!");
11562 SDVTList VTs = Indexed ? getVTList(VT, Base.getValueType(), MVT::Other)
11563 : getVTList(VT, MVT::Other);
11564 SDValue Ops[] = {Chain, Base, Offset, Mask, PassThru};
11565 SDNodeKey ID(ISD::MLOAD, VTs, Ops);
11566 ID.AddInteger(MemVT.getRawBits());
11567 ID.AddInteger(getSyntheticNodeSubclassData<MaskedLoadSDNode>(
11568 dl.getIROrder(), VTs, AM, ExtTy, isExpanding, MemVT, MMO));
11569 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11570 ID.AddInteger(MMO->getFlags());
11571 FoldingSetInsertToken InsertToken;
11572 if (SDNode *E = lookupNode(ID, dl, InsertToken)) {
11573 cast<MaskedLoadSDNode>(E)->refineAlignment(MMO);
11574 return SDValue(E, 0);
11575 }
11576 auto *N = newSDNode<MaskedLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
11577 AM, ExtTy, isExpanding, MemVT, MMO);
11578 createOperands(N, Ops);
11579
11580 CSEMap.insert(N, InsertToken);
11581 InsertNode(N);
11582 SDValue V(N, 0);
11583 NewSDValueDbgMsg(V, "Creating new node: ", this);
11584 return V;
11585}
11586
11591 assert(LD->getOffset().getOpcode() == ISD::POISON &&
11592 "Masked load is already a indexed load!");
11593 return getMaskedLoad(OrigLoad.getValueType(), dl, LD->getChain(), Base,
11594 Offset, LD->getMask(), LD->getPassThru(),
11595 LD->getMemoryVT(), LD->getMemOperand(), AM,
11596 LD->getExtensionType(), LD->isExpandingLoad());
11597}
11598
11601 SDValue Mask, EVT MemVT,
11602 MachineMemOperand *MMO,
11603 ISD::MemIndexedMode AM, bool IsTruncating,
11604 bool IsCompressing) {
11605 assert(Chain.getValueType() == MVT::Other &&
11606 "Invalid chain type");
11607 bool Indexed = AM != ISD::UNINDEXED;
11608 assert((Indexed || Offset.getOpcode() == ISD::POISON) &&
11609 "Unindexed masked store with an offset!");
11610 SDVTList VTs = Indexed ? getVTList(Base.getValueType(), MVT::Other)
11611 : getVTList(MVT::Other);
11612 SDValue Ops[] = {Chain, Val, Base, Offset, Mask};
11613 SDNodeKey ID(ISD::MSTORE, VTs, Ops);
11614 ID.AddInteger(MemVT.getRawBits());
11615 ID.AddInteger(getSyntheticNodeSubclassData<MaskedStoreSDNode>(
11616 dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
11617 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11618 ID.AddInteger(MMO->getFlags());
11619 FoldingSetInsertToken InsertToken;
11620 if (SDNode *E = lookupNode(ID, dl, InsertToken)) {
11621 cast<MaskedStoreSDNode>(E)->refineAlignment(MMO);
11622 return SDValue(E, 0);
11623 }
11624 auto *N =
11625 newSDNode<MaskedStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
11626 IsTruncating, IsCompressing, MemVT, MMO);
11627 createOperands(N, Ops);
11628
11629 CSEMap.insert(N, InsertToken);
11630 InsertNode(N);
11631 SDValue V(N, 0);
11632 NewSDValueDbgMsg(V, "Creating new node: ", this);
11633 return V;
11634}
11635
11640 assert(ST->getOffset().getOpcode() == ISD::POISON &&
11641 "Masked store is already a indexed store!");
11642 return getMaskedStore(ST->getChain(), dl, ST->getValue(), Base, Offset,
11643 ST->getMask(), ST->getMemoryVT(), ST->getMemOperand(),
11644 AM, ST->isTruncatingStore(), ST->isCompressingStore());
11645}
11646
11649 MachineMemOperand *MMO,
11650 ISD::MemIndexType IndexType,
11651 ISD::LoadExtType ExtTy) {
11652 assert(Ops.size() == 6 && "Incompatible number of operands");
11653
11654 SDNodeKey ID(ISD::MGATHER, VTs, Ops);
11655 ID.AddInteger(MemVT.getRawBits());
11656 ID.AddInteger(getSyntheticNodeSubclassData<MaskedGatherSDNode>(
11657 dl.getIROrder(), VTs, MemVT, MMO, IndexType, ExtTy));
11658 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11659 ID.AddInteger(MMO->getFlags());
11660 FoldingSetInsertToken InsertToken;
11661 if (SDNode *E = lookupNode(ID, dl, InsertToken)) {
11662 cast<MaskedGatherSDNode>(E)->refineAlignment(MMO);
11663 return SDValue(E, 0);
11664 }
11665
11666 auto *N = newSDNode<MaskedGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(),
11667 VTs, MemVT, MMO, IndexType, ExtTy);
11668 createOperands(N, Ops);
11669
11670 assert(N->getPassThru().getValueType() == N->getValueType(0) &&
11671 "Incompatible type of the PassThru value in MaskedGatherSDNode");
11672 assert(N->getMask().getValueType().getVectorElementCount() ==
11673 N->getValueType(0).getVectorElementCount() &&
11674 "Vector width mismatch between mask and data");
11675 assert(N->getIndex().getValueType().getVectorElementCount().isScalable() ==
11676 N->getValueType(0).getVectorElementCount().isScalable() &&
11677 "Scalable flags of index and data do not match");
11679 N->getIndex().getValueType().getVectorElementCount(),
11680 N->getValueType(0).getVectorElementCount()) &&
11681 "Vector width mismatch between index and data");
11682 assert(isa<ConstantSDNode>(N->getScale()) &&
11683 N->getScale()->getAsAPIntVal().isPowerOf2() &&
11684 "Scale should be a constant power of 2");
11685
11686 CSEMap.insert(N, InsertToken);
11687 InsertNode(N);
11688 SDValue V(N, 0);
11689 NewSDValueDbgMsg(V, "Creating new node: ", this);
11690 return V;
11691}
11692
11695 MachineMemOperand *MMO,
11696 ISD::MemIndexType IndexType,
11697 bool IsTrunc) {
11698 assert(Ops.size() == 6 && "Incompatible number of operands");
11699
11700 SDNodeKey ID(ISD::MSCATTER, VTs, Ops);
11701 ID.AddInteger(MemVT.getRawBits());
11702 ID.AddInteger(getSyntheticNodeSubclassData<MaskedScatterSDNode>(
11703 dl.getIROrder(), VTs, MemVT, MMO, IndexType, IsTrunc));
11704 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11705 ID.AddInteger(MMO->getFlags());
11706 FoldingSetInsertToken InsertToken;
11707 if (SDNode *E = lookupNode(ID, dl, InsertToken)) {
11708 cast<MaskedScatterSDNode>(E)->refineAlignment(MMO);
11709 return SDValue(E, 0);
11710 }
11711
11712 auto *N = newSDNode<MaskedScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(),
11713 VTs, MemVT, MMO, IndexType, IsTrunc);
11714 createOperands(N, Ops);
11715
11716 assert(N->getMask().getValueType().getVectorElementCount() ==
11717 N->getValue().getValueType().getVectorElementCount() &&
11718 "Vector width mismatch between mask and data");
11719 assert(
11720 N->getIndex().getValueType().getVectorElementCount().isScalable() ==
11721 N->getValue().getValueType().getVectorElementCount().isScalable() &&
11722 "Scalable flags of index and data do not match");
11724 N->getIndex().getValueType().getVectorElementCount(),
11725 N->getValue().getValueType().getVectorElementCount()) &&
11726 "Vector width mismatch between index and data");
11727 assert(isa<ConstantSDNode>(N->getScale()) &&
11728 N->getScale()->getAsAPIntVal().isPowerOf2() &&
11729 "Scale should be a constant power of 2");
11730
11731 CSEMap.insert(N, InsertToken);
11732 InsertNode(N);
11733 SDValue V(N, 0);
11734 NewSDValueDbgMsg(V, "Creating new node: ", this);
11735 return V;
11736}
11737
11739 const SDLoc &dl, ArrayRef<SDValue> Ops,
11740 MachineMemOperand *MMO,
11741 ISD::MemIndexType IndexType) {
11742 assert(Ops.size() == 7 && "Incompatible number of operands");
11743
11745 ID.AddInteger(MemVT.getRawBits());
11746 ID.AddInteger(getSyntheticNodeSubclassData<MaskedHistogramSDNode>(
11747 dl.getIROrder(), VTs, MemVT, MMO, IndexType));
11748 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11749 ID.AddInteger(MMO->getFlags());
11750 FoldingSetInsertToken InsertToken;
11751 if (SDNode *E = lookupNode(ID, dl, InsertToken)) {
11752 cast<MaskedGatherSDNode>(E)->refineAlignment(MMO);
11753 return SDValue(E, 0);
11754 }
11755
11756 auto *N = newSDNode<MaskedHistogramSDNode>(dl.getIROrder(), dl.getDebugLoc(),
11757 VTs, MemVT, MMO, IndexType);
11758 createOperands(N, Ops);
11759
11760 assert(N->getMask().getValueType().getVectorElementCount() ==
11761 N->getIndex().getValueType().getVectorElementCount() &&
11762 "Vector width mismatch between mask and data");
11763 assert(isa<ConstantSDNode>(N->getScale()) &&
11764 N->getScale()->getAsAPIntVal().isPowerOf2() &&
11765 "Scale should be a constant power of 2");
11766 assert(N->getInc().getValueType().isInteger() && "Non integer update value");
11767
11768 CSEMap.insert(N, InsertToken);
11769 InsertNode(N);
11770 SDValue V(N, 0);
11771 NewSDValueDbgMsg(V, "Creating new node: ", this);
11772 return V;
11773}
11774
11776 SDValue Ptr, SDValue Mask, SDValue EVL,
11777 MachineMemOperand *MMO) {
11778 SDVTList VTs = getVTList(VT, EVL.getValueType(), MVT::Other);
11779 SDValue Ops[] = {Chain, Ptr, Mask, EVL};
11780 SDNodeKey ID(ISD::VP_LOAD_FF, VTs, Ops);
11781 ID.AddInteger(VT.getRawBits());
11782 ID.AddInteger(getSyntheticNodeSubclassData<VPLoadFFSDNode>(DL.getIROrder(),
11783 VTs, VT, MMO));
11784 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11785 ID.AddInteger(MMO->getFlags());
11786 FoldingSetInsertToken InsertToken;
11787 if (SDNode *E = lookupNode(ID, DL, InsertToken)) {
11788 cast<VPLoadFFSDNode>(E)->refineAlignment(MMO);
11789 return SDValue(E, 0);
11790 }
11791 auto *N = newSDNode<VPLoadFFSDNode>(DL.getIROrder(), DL.getDebugLoc(), VTs,
11792 VT, MMO);
11793 createOperands(N, Ops);
11794
11795 CSEMap.insert(N, InsertToken);
11796 InsertNode(N);
11797 SDValue V(N, 0);
11798 NewSDValueDbgMsg(V, "Creating new node: ", this);
11799 return V;
11800}
11801
11803 EVT MemVT, MachineMemOperand *MMO) {
11804 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
11805 SDVTList VTs = getVTList(MVT::Other);
11806 SDValue Ops[] = {Chain, Ptr};
11808 ID.AddInteger(MemVT.getRawBits());
11809 ID.AddInteger(getSyntheticNodeSubclassData<FPStateAccessSDNode>(
11810 ISD::GET_FPENV_MEM, dl.getIROrder(), VTs, MemVT, MMO));
11811 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11812 ID.AddInteger(MMO->getFlags());
11813 FoldingSetInsertToken InsertToken;
11814 if (SDNode *E = lookupNode(ID, dl, InsertToken))
11815 return SDValue(E, 0);
11816
11817 auto *N = newSDNode<FPStateAccessSDNode>(ISD::GET_FPENV_MEM, dl.getIROrder(),
11818 dl.getDebugLoc(), VTs, MemVT, MMO);
11819 createOperands(N, Ops);
11820
11821 CSEMap.insert(N, InsertToken);
11822 InsertNode(N);
11823 SDValue V(N, 0);
11824 NewSDValueDbgMsg(V, "Creating new node: ", this);
11825 return V;
11826}
11827
11829 EVT MemVT, MachineMemOperand *MMO) {
11830 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
11831 SDVTList VTs = getVTList(MVT::Other);
11832 SDValue Ops[] = {Chain, Ptr};
11834 ID.AddInteger(MemVT.getRawBits());
11835 ID.AddInteger(getSyntheticNodeSubclassData<FPStateAccessSDNode>(
11836 ISD::SET_FPENV_MEM, dl.getIROrder(), VTs, MemVT, MMO));
11837 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11838 ID.AddInteger(MMO->getFlags());
11839 FoldingSetInsertToken InsertToken;
11840 if (SDNode *E = lookupNode(ID, dl, InsertToken))
11841 return SDValue(E, 0);
11842
11843 auto *N = newSDNode<FPStateAccessSDNode>(ISD::SET_FPENV_MEM, dl.getIROrder(),
11844 dl.getDebugLoc(), VTs, MemVT, MMO);
11845 createOperands(N, Ops);
11846
11847 CSEMap.insert(N, InsertToken);
11848 InsertNode(N);
11849 SDValue V(N, 0);
11850 NewSDValueDbgMsg(V, "Creating new node: ", this);
11851 return V;
11852}
11853
11855 // select undef, T, F --> T (if T is a constant), otherwise F
11856 // select, ?, undef, F --> F
11857 // select, ?, T, undef --> T
11858 if (Cond.isUndef())
11859 return isConstantValueOfAnyType(T) ? T : F;
11860 if (T.isUndef())
11862 if (F.isUndef())
11864
11865 // select true, T, F --> T
11866 // select false, T, F --> F
11867 if (auto C = isBoolConstant(Cond))
11868 return *C ? T : F;
11869
11870 // select ?, T, T --> T
11871 if (T == F)
11872 return T;
11873
11874 return SDValue();
11875}
11876
11878 // shift undef, Y --> 0 (can always assume that the undef value is 0)
11879 if (X.isUndef())
11880 return getConstant(0, SDLoc(X.getNode()), X.getValueType());
11881 // shift X, undef --> undef (because it may shift by the bitwidth)
11882 if (Y.isUndef())
11883 return getUNDEF(X.getValueType());
11884
11885 // shift 0, Y --> 0
11886 // shift X, 0 --> X
11888 return X;
11889
11890 // shift X, C >= bitwidth(X) --> undef
11891 // All vector elements must be too big (or undef) to avoid partial undefs.
11892 auto isShiftTooBig = [X](ConstantSDNode *Val) {
11893 return !Val || Val->getAPIntValue().uge(X.getScalarValueSizeInBits());
11894 };
11895 if (ISD::matchUnaryPredicate(Y, isShiftTooBig, true))
11896 return getUNDEF(X.getValueType());
11897
11898 // shift i1/vXi1 X, Y --> X (any non-zero shift amount is undefined).
11899 if (X.getValueType().getScalarType() == MVT::i1)
11900 return X;
11901
11902 return SDValue();
11903}
11904
11906 SDNodeFlags Flags) {
11907 // If this operation has 'nnan' or 'ninf' and at least 1 disallowed operand
11908 // (an undef operand can be chosen to be Nan/Inf), then the result of this
11909 // operation is poison. That result can be relaxed to undef.
11910 ConstantFPSDNode *XC = isConstOrConstSplatFP(X, /* AllowUndefs */ true);
11911 ConstantFPSDNode *YC = isConstOrConstSplatFP(Y, /* AllowUndefs */ true);
11912 bool HasNan = (XC && XC->getValueAPF().isNaN()) ||
11913 (YC && YC->getValueAPF().isNaN());
11914 bool HasInf = (XC && XC->getValueAPF().isInfinity()) ||
11915 (YC && YC->getValueAPF().isInfinity());
11916
11917 if (Flags.hasNoNaNs() && (HasNan || X.isUndef() || Y.isUndef()))
11918 return getUNDEF(X.getValueType());
11919
11920 if (Flags.hasNoInfs() && (HasInf || X.isUndef() || Y.isUndef()))
11921 return getUNDEF(X.getValueType());
11922
11923 if (!YC)
11924 return SDValue();
11925
11926 // X + -0.0 --> X
11927 if (Opcode == ISD::FADD)
11928 if (YC->getValueAPF().isNegZero())
11929 return X;
11930
11931 // X - +0.0 --> X
11932 if (Opcode == ISD::FSUB)
11933 if (YC->getValueAPF().isPosZero())
11934 return X;
11935
11936 // X * 1.0 --> X
11937 // X / 1.0 --> X
11938 if (Opcode == ISD::FMUL || Opcode == ISD::FDIV)
11939 if (YC->getValueAPF().isOne())
11940 return X;
11941
11942 // X * 0.0 --> 0.0
11943 if (Opcode == ISD::FMUL && Flags.hasNoNaNs() && Flags.hasNoSignedZeros())
11944 if (YC->getValueAPF().isZero())
11945 return getConstantFP(0.0, SDLoc(Y), Y.getValueType());
11946
11947 return SDValue();
11948}
11949
11951 SDValue Ptr, SDValue SV, unsigned Align) {
11952 SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, dl, MVT::i32) };
11953 return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops);
11954}
11955
11956SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
11958 switch (Ops.size()) {
11959 case 0: return getNode(Opcode, DL, VT);
11960 case 1: return getNode(Opcode, DL, VT, Ops[0].get());
11961 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
11962 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
11963 default: break;
11964 }
11965
11966 // Copy from an SDUse array into an SDValue array for use with
11967 // the regular getNode logic.
11969 return getNode(Opcode, DL, VT, NewOps);
11970}
11971
11972SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
11974 SDNodeFlags Flags;
11975 if (Inserter)
11976 Flags = Inserter->getFlags();
11977 return getNode(Opcode, DL, VT, Ops, Flags);
11978}
11979
11980SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
11981 ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
11982 unsigned NumOps = Ops.size();
11983 switch (NumOps) {
11984 case 0: return getNode(Opcode, DL, VT);
11985 case 1: return getNode(Opcode, DL, VT, Ops[0], Flags);
11986 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Flags);
11987 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2], Flags);
11988 default: break;
11989 }
11990
11991#ifndef NDEBUG
11992 for (const auto &Op : Ops)
11993 assert(Op.getOpcode() != ISD::DELETED_NODE &&
11994 "Operand is DELETED_NODE!");
11995#endif
11996
11997 switch (Opcode) {
11998 default: break;
11999 case ISD::BUILD_VECTOR:
12000 // Attempt to simplify BUILD_VECTOR.
12001 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
12002 return V;
12003 break;
12005 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
12006 return V;
12007 break;
12008 case ISD::SELECT_CC:
12009 assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
12010 assert(Ops[0].getValueType() == Ops[1].getValueType() &&
12011 "LHS and RHS of condition must have same type!");
12012 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
12013 "True and False arms of SelectCC must have same type!");
12014 assert(Ops[2].getValueType() == VT &&
12015 "select_cc node must be of same type as true and false value!");
12016 assert((!Ops[0].getValueType().isVector() ||
12017 Ops[0].getValueType().getVectorElementCount() ==
12018 VT.getVectorElementCount()) &&
12019 "Expected select_cc with vector result to have the same sized "
12020 "comparison type!");
12021 break;
12022 case ISD::BR_CC:
12023 assert(NumOps == 5 && "BR_CC takes 5 operands!");
12024 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
12025 "LHS/RHS of comparison should match types!");
12026 break;
12027 case ISD::VP_REDUCE_MUL:
12028 // If it is VP_REDUCE_MUL mask operation then turn it to VP_REDUCE_AND
12029 if (VT == MVT::i1)
12030 Opcode = ISD::VP_REDUCE_AND;
12031 break;
12032 case ISD::VP_REDUCE_ADD:
12033 // If it is VP_REDUCE_ADD mask operation then turn it to VP_REDUCE_XOR
12034 if (VT == MVT::i1)
12035 Opcode = ISD::VP_REDUCE_XOR;
12036 break;
12037 case ISD::VP_REDUCE_SMAX:
12038 case ISD::VP_REDUCE_UMIN:
12039 // If it is VP_REDUCE_SMAX/VP_REDUCE_UMIN mask operation then turn it to
12040 // VP_REDUCE_AND.
12041 if (VT == MVT::i1)
12042 Opcode = ISD::VP_REDUCE_AND;
12043 break;
12044 case ISD::VP_REDUCE_SMIN:
12045 case ISD::VP_REDUCE_UMAX:
12046 // If it is VP_REDUCE_SMIN/VP_REDUCE_UMAX mask operation then turn it to
12047 // VP_REDUCE_OR.
12048 if (VT == MVT::i1)
12049 Opcode = ISD::VP_REDUCE_OR;
12050 break;
12051 }
12052
12053 // Memoize nodes.
12054 SDNode *N;
12055 SDVTList VTs = getVTList(VT);
12056
12057 if (VT != MVT::Glue) {
12058 SDNodeKey ID(Opcode, VTs, Ops);
12059 FoldingSetInsertToken InsertToken;
12060
12061 if (SDNode *E = lookupNode(ID, DL, InsertToken)) {
12062 E->intersectFlagsWith(Flags);
12063 return SDValue(E, 0);
12064 }
12065
12066 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
12067 createOperands(N, Ops);
12068
12069 CSEMap.insert(N, InsertToken);
12070 } else {
12071 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
12072 createOperands(N, Ops);
12073 }
12074
12075 N->setFlags(Flags);
12076 InsertNode(N);
12077 SDValue V(N, 0);
12078 NewSDValueDbgMsg(V, "Creating new node: ", this);
12079 return V;
12080}
12081
12082SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
12083 ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) {
12084 SDNodeFlags Flags;
12085 if (Inserter)
12086 Flags = Inserter->getFlags();
12087 return getNode(Opcode, DL, getVTList(ResultTys), Ops, Flags);
12088}
12089
12090SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
12092 const SDNodeFlags Flags) {
12093 return getNode(Opcode, DL, getVTList(ResultTys), Ops, Flags);
12094}
12095
12096SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
12098 SDNodeFlags Flags;
12099 if (Inserter)
12100 Flags = Inserter->getFlags();
12101 return getNode(Opcode, DL, VTList, Ops, Flags);
12102}
12103
12104SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
12105 ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
12106 if (VTList.NumVTs == 1)
12107 return getNode(Opcode, DL, VTList.VTs[0], Ops, Flags);
12108
12109#ifndef NDEBUG
12110 for (const auto &Op : Ops)
12111 assert(Op.getOpcode() != ISD::DELETED_NODE &&
12112 "Operand is DELETED_NODE!");
12113#endif
12114
12115 if (SDValue V = FoldConstantArithmetic(Opcode, DL, VTList, Ops, Flags))
12116 return V;
12117
12118 switch (Opcode) {
12119 case ISD::SADDO:
12120 case ISD::UADDO:
12121 case ISD::SSUBO:
12122 case ISD::USUBO: {
12123 assert(VTList.NumVTs == 2 && Ops.size() == 2 &&
12124 "Invalid add/sub overflow op!");
12125 assert(VTList.VTs[0].isInteger() && VTList.VTs[1].isInteger() &&
12126 Ops[0].getValueType() == Ops[1].getValueType() &&
12127 Ops[0].getValueType() == VTList.VTs[0] &&
12128 "Binary operator types must match!");
12129 SDValue N1 = Ops[0], N2 = Ops[1];
12130 canonicalizeCommutativeBinop(Opcode, N1, N2);
12131
12132 // (X +- 0) -> X with zero-overflow.
12133 ConstantSDNode *N2CV = isConstOrConstSplat(N2, /*AllowUndefs*/ false,
12134 /*AllowTruncation*/ true);
12135 if (N2CV && N2CV->isZero()) {
12136 SDValue ZeroOverFlow = getConstant(0, DL, VTList.VTs[1]);
12137 return getNode(ISD::MERGE_VALUES, DL, VTList, {N1, ZeroOverFlow}, Flags);
12138 }
12139
12140 if (VTList.VTs[0].getScalarType() == MVT::i1 &&
12141 VTList.VTs[1].getScalarType() == MVT::i1) {
12142 SDValue F1 = getFreeze(N1);
12143 SDValue F2 = getFreeze(N2);
12144 // {vXi1,vXi1} (u/s)addo(vXi1 x, vXi1y) -> {xor(x,y),and(x,y)}
12145 if (Opcode == ISD::UADDO || Opcode == ISD::SADDO)
12146 return getNode(ISD::MERGE_VALUES, DL, VTList,
12147 {getNode(ISD::XOR, DL, VTList.VTs[0], F1, F2),
12148 getNode(ISD::AND, DL, VTList.VTs[1], F1, F2)},
12149 Flags);
12150 // {vXi1,vXi1} (u/s)subo(vXi1 x, vXi1y) -> {xor(x,y),and(~x,y)}
12151 if (Opcode == ISD::USUBO || Opcode == ISD::SSUBO) {
12152 SDValue NotF1 = getNOT(DL, F1, VTList.VTs[0]);
12153 return getNode(ISD::MERGE_VALUES, DL, VTList,
12154 {getNode(ISD::XOR, DL, VTList.VTs[0], F1, F2),
12155 getNode(ISD::AND, DL, VTList.VTs[1], NotF1, F2)},
12156 Flags);
12157 }
12158 }
12159 break;
12160 }
12161 case ISD::SADDO_CARRY:
12162 case ISD::UADDO_CARRY:
12163 case ISD::SSUBO_CARRY:
12164 case ISD::USUBO_CARRY:
12165 assert(VTList.NumVTs == 2 && Ops.size() == 3 &&
12166 "Invalid add/sub overflow op!");
12167 assert(VTList.VTs[0].isInteger() && VTList.VTs[1].isInteger() &&
12168 Ops[0].getValueType() == Ops[1].getValueType() &&
12169 Ops[0].getValueType() == VTList.VTs[0] &&
12170 Ops[2].getValueType() == VTList.VTs[1] &&
12171 "Binary operator types must match!");
12172 break;
12173 case ISD::SMUL_LOHI:
12174 case ISD::UMUL_LOHI: {
12175 assert(VTList.NumVTs == 2 && Ops.size() == 2 && "Invalid mul lo/hi op!");
12176 assert(VTList.VTs[0].isInteger() && VTList.VTs[0] == VTList.VTs[1] &&
12177 VTList.VTs[0] == Ops[0].getValueType() &&
12178 VTList.VTs[0] == Ops[1].getValueType() &&
12179 "Binary operator types must match!");
12180 // Constant fold.
12183 if (LHS && RHS) {
12184 unsigned Width = VTList.VTs[0].getScalarSizeInBits();
12185 unsigned OutWidth = Width * 2;
12186 APInt Val = LHS->getAPIntValue();
12187 APInt Mul = RHS->getAPIntValue();
12188 if (Opcode == ISD::SMUL_LOHI) {
12189 Val = Val.sext(OutWidth);
12190 Mul = Mul.sext(OutWidth);
12191 } else {
12192 Val = Val.zext(OutWidth);
12193 Mul = Mul.zext(OutWidth);
12194 }
12195 Val *= Mul;
12196
12197 SDValue Hi =
12198 getConstant(Val.extractBits(Width, Width), DL, VTList.VTs[0]);
12199 SDValue Lo = getConstant(Val.trunc(Width), DL, VTList.VTs[0]);
12200 return getNode(ISD::MERGE_VALUES, DL, VTList, {Lo, Hi}, Flags);
12201 }
12202 break;
12203 }
12204 case ISD::FFREXP: {
12205 assert(VTList.NumVTs == 2 && Ops.size() == 1 && "Invalid ffrexp op!");
12206 assert(VTList.VTs[0].isFloatingPoint() && VTList.VTs[1].isInteger() &&
12207 VTList.VTs[0] == Ops[0].getValueType() && "frexp type mismatch");
12208
12210 int FrexpExp;
12211 APFloat FrexpMant =
12212 frexp(C->getValueAPF(), FrexpExp, APFloat::rmNearestTiesToEven);
12213 SDValue Result0 = getConstantFP(FrexpMant, DL, VTList.VTs[0]);
12214 SDValue Result1 = getSignedConstant(FrexpMant.isFinite() ? FrexpExp : 0,
12215 DL, VTList.VTs[1]);
12216 return getNode(ISD::MERGE_VALUES, DL, VTList, {Result0, Result1}, Flags);
12217 }
12218
12219 break;
12220 }
12222 assert(VTList.NumVTs == 2 && Ops.size() == 2 &&
12223 "Invalid STRICT_FP_EXTEND!");
12224 assert(VTList.VTs[0].isFloatingPoint() &&
12225 Ops[1].getValueType().isFloatingPoint() && "Invalid FP cast!");
12226 assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
12227 "STRICT_FP_EXTEND result type should be vector iff the operand "
12228 "type is vector!");
12229 assert((!VTList.VTs[0].isVector() ||
12230 VTList.VTs[0].getVectorElementCount() ==
12231 Ops[1].getValueType().getVectorElementCount()) &&
12232 "Vector element count mismatch!");
12233 assert(Ops[1].getValueType().bitsLT(VTList.VTs[0]) &&
12234 "Invalid fpext node, dst <= src!");
12235 break;
12237 assert(VTList.NumVTs == 2 && Ops.size() == 3 && "Invalid STRICT_FP_ROUND!");
12238 assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
12239 "STRICT_FP_ROUND result type should be vector iff the operand "
12240 "type is vector!");
12241 assert((!VTList.VTs[0].isVector() ||
12242 VTList.VTs[0].getVectorElementCount() ==
12243 Ops[1].getValueType().getVectorElementCount()) &&
12244 "Vector element count mismatch!");
12245 assert(VTList.VTs[0].isFloatingPoint() &&
12246 Ops[1].getValueType().isFloatingPoint() &&
12247 VTList.VTs[0].bitsLT(Ops[1].getValueType()) &&
12248 Ops[2].getOpcode() == ISD::TargetConstant &&
12249 (Ops[2]->getAsZExtVal() == 0 || Ops[2]->getAsZExtVal() == 1) &&
12250 "Invalid STRICT_FP_ROUND!");
12251 break;
12252 }
12253
12254 // Memoize the node unless it returns a glue result.
12255 SDNode *N;
12256 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
12257 SDNodeKey ID(Opcode, VTList, Ops);
12258 FoldingSetInsertToken InsertToken;
12259 if (SDNode *E = lookupNode(ID, DL, InsertToken)) {
12260 E->intersectFlagsWith(Flags);
12261 return SDValue(E, 0);
12262 }
12263
12264 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
12265 createOperands(N, Ops);
12266 CSEMap.insert(N, InsertToken);
12267 } else {
12268 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
12269 createOperands(N, Ops);
12270 }
12271
12272 N->setFlags(Flags);
12273 InsertNode(N);
12274 SDValue V(N, 0);
12275 NewSDValueDbgMsg(V, "Creating new node: ", this);
12276 return V;
12277}
12278
12279SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
12280 SDVTList VTList) {
12281 return getNode(Opcode, DL, VTList, ArrayRef<SDValue>());
12282}
12283
12284SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
12285 SDValue N1) {
12286 SDValue Ops[] = { N1 };
12287 return getNode(Opcode, DL, VTList, Ops);
12288}
12289
12290SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
12291 SDValue N1, SDValue N2) {
12292 SDValue Ops[] = { N1, N2 };
12293 return getNode(Opcode, DL, VTList, Ops);
12294}
12295
12296SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
12297 SDValue N1, SDValue N2, SDValue N3) {
12298 SDValue Ops[] = { N1, N2, N3 };
12299 return getNode(Opcode, DL, VTList, Ops);
12300}
12301
12302SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
12303 SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
12304 SDValue Ops[] = { N1, N2, N3, N4 };
12305 return getNode(Opcode, DL, VTList, Ops);
12306}
12307
12308SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
12309 SDValue N1, SDValue N2, SDValue N3, SDValue N4,
12310 SDValue N5) {
12311 SDValue Ops[] = { N1, N2, N3, N4, N5 };
12312 return getNode(Opcode, DL, VTList, Ops);
12313}
12314
12316 if (!VT.isExtended())
12317 return makeVTList(SDNode::getValueTypeList(VT.getSimpleVT()), 1);
12318
12319 EVT VTs[] = {VT};
12320 return getVTList(VTs);
12321}
12322
12324 EVT VTs[] = {VT1, VT2};
12325 return getVTList(VTs);
12326}
12327
12329 EVT VTs[] = {VT1, VT2, VT3};
12330 return getVTList(VTs);
12331}
12332
12334 EVT VTs[] = {VT1, VT2, VT3, VT4};
12335 return getVTList(VTs);
12336}
12337
12339 auto It = VTLists.find(VTs);
12340 if (It == VTLists.end()) {
12341 EVT *Array = Allocator.Allocate<EVT>(VTs.size());
12342 llvm::copy(VTs, Array);
12343 It = VTLists.insert(ArrayRef(Array, VTs.size())).first;
12344 }
12345 return makeVTList(It->data(), It->size());
12346}
12347
12348/// UpdateNodeOperands - *Mutate* the specified node in-place to have the
12349/// specified operands. If the resultant node already exists in the DAG,
12350/// this does not modify the specified node, instead it returns the node that
12351/// already exists. If the resultant node does not exist in the DAG, the
12352/// input node is returned. As a degenerate case, if you specify the same
12353/// input operands as the node already has, the input node is returned.
12355 assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
12356
12357 // Check to see if there is no change.
12358 if (Op == N->getOperand(0)) return N;
12359
12360 // See if the modified node already exists.
12361 FoldingSetInsertToken InsertToken;
12362 if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertToken))
12363 return Existing;
12364
12365 // Nope it doesn't. Remove the node from its current place in the maps.
12366 if (InsertToken)
12367 if (!RemoveNodeFromCSEMaps(N))
12368 InsertToken = {};
12369
12370 // Now we update the operands.
12371 N->OperandList[0].set(Op);
12372
12374 // If this gets put into a CSE map, add it.
12375 if (InsertToken)
12376 CSEMap.insert(N, InsertToken);
12377 return N;
12378}
12379
12381 assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
12382
12383 // Check to see if there is no change.
12384 if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
12385 return N; // No operands changed, just return the input node.
12386
12387 // See if the modified node already exists.
12388 FoldingSetInsertToken InsertToken;
12389 if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertToken))
12390 return Existing;
12391
12392 // Nope it doesn't. Remove the node from its current place in the maps.
12393 if (InsertToken)
12394 if (!RemoveNodeFromCSEMaps(N))
12395 InsertToken = {};
12396
12397 // Now we update the operands.
12398 if (N->OperandList[0] != Op1)
12399 N->OperandList[0].set(Op1);
12400 if (N->OperandList[1] != Op2)
12401 N->OperandList[1].set(Op2);
12402
12404 // If this gets put into a CSE map, add it.
12405 if (InsertToken)
12406 CSEMap.insert(N, InsertToken);
12407 return N;
12408}
12409
12412 SDValue Ops[] = { Op1, Op2, Op3 };
12413 return UpdateNodeOperands(N, Ops);
12414}
12415
12418 SDValue Op3, SDValue Op4) {
12419 SDValue Ops[] = { Op1, Op2, Op3, Op4 };
12420 return UpdateNodeOperands(N, Ops);
12421}
12422
12425 SDValue Op3, SDValue Op4, SDValue Op5) {
12426 SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 };
12427 return UpdateNodeOperands(N, Ops);
12428}
12429
12432 unsigned NumOps = Ops.size();
12433 assert(N->getNumOperands() == NumOps &&
12434 "Update with wrong number of operands");
12435
12436 // If no operands changed just return the input node.
12437 if (std::equal(Ops.begin(), Ops.end(), N->op_begin()))
12438 return N;
12439
12440 // See if the modified node already exists.
12441 FoldingSetInsertToken InsertToken;
12442 if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertToken))
12443 return Existing;
12444
12445 // Nope it doesn't. Remove the node from its current place in the maps.
12446 if (InsertToken)
12447 if (!RemoveNodeFromCSEMaps(N))
12448 InsertToken = {};
12449
12450 // Now we update the operands.
12451 for (unsigned i = 0; i != NumOps; ++i)
12452 if (N->OperandList[i] != Ops[i])
12453 N->OperandList[i].set(Ops[i]);
12454
12456 // If this gets put into a CSE map, add it.
12457 if (InsertToken)
12458 CSEMap.insert(N, InsertToken);
12459 return N;
12460}
12461
12462/// DropOperands - Release the operands and set this node to have
12463/// zero operands.
12465 // Unlike the code in MorphNodeTo that does this, we don't need to
12466 // watch for dead nodes here.
12467 for (op_iterator I = op_begin(), E = op_end(); I != E; ) {
12468 SDUse &Use = *I++;
12469 Use.set(SDValue());
12470 }
12471}
12472
12474 ArrayRef<MachineMemOperand *> NewMemRefs) {
12475 if (NewMemRefs.empty()) {
12476 N->clearMemRefs();
12477 return;
12478 }
12479
12480 // Check if we can avoid allocating by storing a single reference directly.
12481 if (NewMemRefs.size() == 1) {
12482 N->MemRefs = NewMemRefs[0];
12483 N->NumMemRefs = 1;
12484 return;
12485 }
12486
12487 MachineMemOperand **MemRefsBuffer =
12488 Allocator.template Allocate<MachineMemOperand *>(NewMemRefs.size());
12489 llvm::copy(NewMemRefs, MemRefsBuffer);
12490 N->MemRefs = MemRefsBuffer;
12491 N->NumMemRefs = static_cast<int>(NewMemRefs.size());
12492}
12493
12494/// SelectNodeTo - These are wrappers around MorphNodeTo that accept a
12495/// machine opcode.
12496///
12498 EVT VT) {
12499 SDVTList VTs = getVTList(VT);
12500 return SelectNodeTo(N, MachineOpc, VTs, {});
12501}
12502
12504 EVT VT, SDValue Op1) {
12505 SDVTList VTs = getVTList(VT);
12506 SDValue Ops[] = { Op1 };
12507 return SelectNodeTo(N, MachineOpc, VTs, Ops);
12508}
12509
12511 EVT VT, SDValue Op1,
12512 SDValue Op2) {
12513 SDVTList VTs = getVTList(VT);
12514 SDValue Ops[] = { Op1, Op2 };
12515 return SelectNodeTo(N, MachineOpc, VTs, Ops);
12516}
12517
12519 EVT VT, SDValue Op1,
12520 SDValue Op2, SDValue Op3) {
12521 SDVTList VTs = getVTList(VT);
12522 SDValue Ops[] = { Op1, Op2, Op3 };
12523 return SelectNodeTo(N, MachineOpc, VTs, Ops);
12524}
12525
12528 SDVTList VTs = getVTList(VT);
12529 return SelectNodeTo(N, MachineOpc, VTs, Ops);
12530}
12531
12533 EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) {
12534 SDVTList VTs = getVTList(VT1, VT2);
12535 return SelectNodeTo(N, MachineOpc, VTs, Ops);
12536}
12537
12539 EVT VT1, EVT VT2) {
12540 SDVTList VTs = getVTList(VT1, VT2);
12541 return SelectNodeTo(N, MachineOpc, VTs, {});
12542}
12543
12545 EVT VT1, EVT VT2, EVT VT3,
12547 SDVTList VTs = getVTList(VT1, VT2, VT3);
12548 return SelectNodeTo(N, MachineOpc, VTs, Ops);
12549}
12550
12552 EVT VT1, EVT VT2,
12553 SDValue Op1, SDValue Op2) {
12554 SDVTList VTs = getVTList(VT1, VT2);
12555 SDValue Ops[] = { Op1, Op2 };
12556 return SelectNodeTo(N, MachineOpc, VTs, Ops);
12557}
12558
12561 SDNode *New = MorphNodeTo(N, ~MachineOpc, VTs, Ops);
12562 // Reset the NodeID to -1.
12563 New->setNodeId(-1);
12564 if (New != N) {
12565 ReplaceAllUsesWith(N, New);
12567 }
12568 return New;
12569}
12570
12571/// UpdateSDLocOnMergeSDNode - If the opt level is -O0 then it throws away
12572/// the line number information on the merged node since it is not possible to
12573/// preserve the information that operation is associated with multiple lines.
12574/// This will make the debugger working better at -O0, were there is a higher
12575/// probability having other instructions associated with that line.
12576///
12577/// For IROrder, we keep the smaller of the two
12578SDNode *SelectionDAG::UpdateSDLocOnMergeSDNode(SDNode *N, const SDLoc &OLoc) {
12579 DebugLoc NLoc = N->getDebugLoc();
12580 if (NLoc && OptLevel == CodeGenOptLevel::None && OLoc.getDebugLoc() != NLoc) {
12581 N->setDebugLoc(DebugLoc());
12582 }
12583 unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder());
12584 N->setIROrder(Order);
12585 return N;
12586}
12587
12588/// MorphNodeTo - This *mutates* the specified node to have the specified
12589/// return type, opcode, and operands.
12590///
12591/// Note that MorphNodeTo returns the resultant node. If there is already a
12592/// node of the specified opcode and operands, it returns that node instead of
12593/// the current one. Note that the SDLoc need not be the same.
12594///
12595/// Using MorphNodeTo is faster than creating a new node and swapping it in
12596/// with ReplaceAllUsesWith both because it often avoids allocating a new
12597/// node, and because it doesn't require CSE recalculation for any of
12598/// the node's users.
12599///
12600/// However, note that MorphNodeTo recursively deletes dead nodes from the DAG.
12601/// As a consequence it isn't appropriate to use from within the DAG combiner or
12602/// the legalizer which maintain worklists that would need to be updated when
12603/// deleting things.
12606 // If an identical node already exists, use it.
12607 FoldingSetInsertToken InsertToken;
12608 if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) {
12609 SDNodeKey ID(Opc, VTs, Ops);
12610 AddNodeIDCustom(ID.Tail, N, Opc);
12611 if (SDNode *ON = lookupNode(ID, SDLoc(N), InsertToken))
12612 return UpdateSDLocOnMergeSDNode(ON, SDLoc(N));
12613 }
12614
12615 if (!RemoveNodeFromCSEMaps(N))
12616 InsertToken = {};
12617
12618 // Start the morphing.
12619 N->NodeType = Opc;
12620 N->ValueList = VTs.VTs;
12621 N->NumValues = VTs.NumVTs;
12622
12623 // Clear the operands list, updating used nodes to remove this from their
12624 // use list. Keep track of any operands that become dead as a result.
12625 SmallPtrSet<SDNode*, 16> DeadNodeSet;
12626 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
12627 SDUse &Use = *I++;
12628 SDNode *Used = Use.getNode();
12629 Use.set(SDValue());
12630 if (Used->use_empty())
12631 DeadNodeSet.insert(Used);
12632 }
12633
12634 // For MachineNode, initialize the memory references information.
12636 MN->clearMemRefs();
12637
12638 // Swap for an appropriately sized array from the recycler.
12639 removeOperands(N);
12640 createOperands(N, Ops);
12641
12642 // Delete any nodes that are still dead after adding the uses for the
12643 // new operands.
12644 if (!DeadNodeSet.empty()) {
12645 SmallVector<SDNode *, 16> DeadNodes;
12646 for (SDNode *N : DeadNodeSet)
12647 if (N->use_empty())
12648 DeadNodes.push_back(N);
12649 RemoveDeadNodes(DeadNodes);
12650 }
12651
12652 if (InsertToken)
12653 CSEMap.insert(N, InsertToken); // Memoize the new node.
12654 return N;
12655}
12656
12658 unsigned OrigOpc = Node->getOpcode();
12659 unsigned NewOpc;
12660 switch (OrigOpc) {
12661 default:
12662 llvm_unreachable("mutateStrictFPToFP called with unexpected opcode!");
12663#define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \
12664 case ISD::STRICT_##DAGN: NewOpc = ISD::DAGN; break;
12665#define CMP_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \
12666 case ISD::STRICT_##DAGN: NewOpc = ISD::SETCC; break;
12667#include "llvm/IR/ConstrainedOps.def"
12668 }
12669
12670 assert(Node->getNumValues() == 2 && "Unexpected number of results!");
12671
12672 // We're taking this node out of the chain, so we need to re-link things.
12673 SDValue InputChain = Node->getOperand(0);
12674 SDValue OutputChain = SDValue(Node, 1);
12675 ReplaceAllUsesOfValueWith(OutputChain, InputChain);
12676
12678 for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
12679 Ops.push_back(Node->getOperand(i));
12680
12681 SDVTList VTs = getVTList(Node->getValueType(0));
12682 SDNode *Res = MorphNodeTo(Node, NewOpc, VTs, Ops);
12683
12684 // MorphNodeTo can operate in two ways: if an existing node with the
12685 // specified operands exists, it can just return it. Otherwise, it
12686 // updates the node in place to have the requested operands.
12687 if (Res == Node) {
12688 // If we updated the node in place, reset the node ID. To the isel,
12689 // this should be just like a newly allocated machine node.
12690 Res->setNodeId(-1);
12691 } else {
12694 }
12695
12696 return Res;
12697}
12698
12699/// getMachineNode - These are used for target selectors to create a new node
12700/// with specified return type(s), MachineInstr opcode, and operands.
12701///
12702/// Note that getMachineNode returns the resultant node. If there is already a
12703/// node of the specified opcode and operands, it returns that node instead of
12704/// the current one.
12706 EVT VT) {
12707 SDVTList VTs = getVTList(VT);
12708 return getMachineNode(Opcode, dl, VTs, {});
12709}
12710
12712 EVT VT, SDValue Op1) {
12713 SDVTList VTs = getVTList(VT);
12714 SDValue Ops[] = { Op1 };
12715 return getMachineNode(Opcode, dl, VTs, Ops);
12716}
12717
12719 EVT VT, SDValue Op1, SDValue Op2) {
12720 SDVTList VTs = getVTList(VT);
12721 SDValue Ops[] = { Op1, Op2 };
12722 return getMachineNode(Opcode, dl, VTs, Ops);
12723}
12724
12726 EVT VT, SDValue Op1, SDValue Op2,
12727 SDValue Op3) {
12728 SDVTList VTs = getVTList(VT);
12729 SDValue Ops[] = { Op1, Op2, Op3 };
12730 return getMachineNode(Opcode, dl, VTs, Ops);
12731}
12732
12735 SDVTList VTs = getVTList(VT);
12736 return getMachineNode(Opcode, dl, VTs, Ops);
12737}
12738
12740 EVT VT1, EVT VT2, SDValue Op1,
12741 SDValue Op2) {
12742 SDVTList VTs = getVTList(VT1, VT2);
12743 SDValue Ops[] = { Op1, Op2 };
12744 return getMachineNode(Opcode, dl, VTs, Ops);
12745}
12746
12748 EVT VT1, EVT VT2, SDValue Op1,
12749 SDValue Op2, SDValue Op3) {
12750 SDVTList VTs = getVTList(VT1, VT2);
12751 SDValue Ops[] = { Op1, Op2, Op3 };
12752 return getMachineNode(Opcode, dl, VTs, Ops);
12753}
12754
12756 EVT VT1, EVT VT2,
12758 SDVTList VTs = getVTList(VT1, VT2);
12759 return getMachineNode(Opcode, dl, VTs, Ops);
12760}
12761
12763 EVT VT1, EVT VT2, EVT VT3,
12764 SDValue Op1, SDValue Op2) {
12765 SDVTList VTs = getVTList(VT1, VT2, VT3);
12766 SDValue Ops[] = { Op1, Op2 };
12767 return getMachineNode(Opcode, dl, VTs, Ops);
12768}
12769
12771 EVT VT1, EVT VT2, EVT VT3,
12772 SDValue Op1, SDValue Op2,
12773 SDValue Op3) {
12774 SDVTList VTs = getVTList(VT1, VT2, VT3);
12775 SDValue Ops[] = { Op1, Op2, Op3 };
12776 return getMachineNode(Opcode, dl, VTs, Ops);
12777}
12778
12780 EVT VT1, EVT VT2, EVT VT3,
12782 SDVTList VTs = getVTList(VT1, VT2, VT3);
12783 return getMachineNode(Opcode, dl, VTs, Ops);
12784}
12785
12787 ArrayRef<EVT> ResultTys,
12789 SDVTList VTs = getVTList(ResultTys);
12790 return getMachineNode(Opcode, dl, VTs, Ops);
12791}
12792
12794 SDVTList VTs,
12796 bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue;
12798 FoldingSetInsertToken InsertToken;
12799
12800 if (DoCSE) {
12801 SDNodeKey ID(~Opcode, VTs, Ops);
12802 if (SDNode *E = lookupNode(ID, DL, InsertToken)) {
12803 return cast<MachineSDNode>(UpdateSDLocOnMergeSDNode(E, DL));
12804 }
12805 }
12806
12807 // Allocate a new MachineSDNode.
12808 N = newSDNode<MachineSDNode>(~Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
12809 createOperands(N, Ops);
12810
12811 if (DoCSE)
12812 CSEMap.insert(N, InsertToken);
12813
12814 InsertNode(N);
12815 NewSDValueDbgMsg(SDValue(N, 0), "Creating new machine node: ", this);
12816 return N;
12817}
12818
12819/// getTargetExtractSubreg - A convenience function for creating
12820/// TargetOpcode::EXTRACT_SUBREG nodes.
12822 SDValue Operand) {
12823 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
12824 SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,
12825 VT, Operand, SRIdxVal);
12826 return SDValue(Subreg, 0);
12827}
12828
12829/// getTargetInsertSubreg - A convenience function for creating
12830/// TargetOpcode::INSERT_SUBREG nodes.
12832 SDValue Operand, SDValue Subreg) {
12833 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
12834 SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL,
12835 VT, Operand, Subreg, SRIdxVal);
12836 return SDValue(Result, 0);
12837}
12838
12839/// getNodeIfExists - Get the specified node if it's already available, or
12840/// else return NULL.
12843 bool AllowCommute) {
12844 SDNodeFlags Flags;
12845 if (Inserter)
12846 Flags = Inserter->getFlags();
12847 return getNodeIfExists(Opcode, VTList, Ops, Flags, AllowCommute);
12848}
12849
12852 const SDNodeFlags Flags,
12853 bool AllowCommute) {
12854 if (VTList.VTs[VTList.NumVTs - 1] == MVT::Glue)
12855 return nullptr;
12856
12857 auto Lookup = [&](ArrayRef<SDValue> LookupOps) -> SDNode * {
12858 SDNodeKey ID(Opcode, VTList, LookupOps);
12859 FoldingSetInsertToken InsertToken;
12860 if (SDNode *E = lookupNode(ID, InsertToken)) {
12861 E->intersectFlagsWith(Flags);
12862 return E;
12863 }
12864 return nullptr;
12865 };
12866
12867 if (SDNode *Existing = Lookup(Ops))
12868 return Existing;
12869
12870 if (AllowCommute && TLI->isCommutativeBinOp(Opcode))
12871 return Lookup({Ops[1], Ops[0]});
12872
12873 return nullptr;
12874}
12875
12876/// doesNodeExist - Check if a node exists without modifying its flags.
12877bool SelectionDAG::doesNodeExist(unsigned Opcode, SDVTList VTList,
12879 if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
12880 SDNodeKey ID(Opcode, VTList, Ops);
12881 FoldingSetInsertToken InsertToken;
12882 if (lookupNode(ID, SDLoc(), InsertToken))
12883 return true;
12884 }
12885 return false;
12886}
12887
12888/// getDbgValue - Creates a SDDbgValue node.
12889///
12890/// SDNode
12892 SDNode *N, unsigned R, bool IsIndirect,
12893 const DebugLoc &DL, unsigned O) {
12894 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
12895 "Expected inlined-at fields to agree");
12896 return new (DbgInfo->getAlloc())
12897 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromNode(N, R),
12898 {}, IsIndirect, DL, O,
12899 /*IsVariadic=*/false);
12900}
12901
12902/// Constant
12904 DIExpression *Expr,
12905 const Value *C,
12906 const DebugLoc &DL, unsigned O) {
12907 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
12908 "Expected inlined-at fields to agree");
12909 return new (DbgInfo->getAlloc())
12910 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromConst(C), {},
12911 /*IsIndirect=*/false, DL, O,
12912 /*IsVariadic=*/false);
12913}
12914
12915/// FrameIndex
12917 DIExpression *Expr, unsigned FI,
12918 bool IsIndirect,
12919 const DebugLoc &DL,
12920 unsigned O) {
12921 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
12922 "Expected inlined-at fields to agree");
12923 return getFrameIndexDbgValue(Var, Expr, FI, {}, IsIndirect, DL, O);
12924}
12925
12926/// FrameIndex with dependencies
12928 DIExpression *Expr, unsigned FI,
12929 ArrayRef<SDNode *> Dependencies,
12930 bool IsIndirect,
12931 const DebugLoc &DL,
12932 unsigned O) {
12933 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
12934 "Expected inlined-at fields to agree");
12935 return new (DbgInfo->getAlloc())
12936 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromFrameIdx(FI),
12937 Dependencies, IsIndirect, DL, O,
12938 /*IsVariadic=*/false);
12939}
12940
12941/// VReg
12943 Register VReg, bool IsIndirect,
12944 const DebugLoc &DL, unsigned O) {
12945 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
12946 "Expected inlined-at fields to agree");
12947 return new (DbgInfo->getAlloc())
12948 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromVReg(VReg),
12949 {}, IsIndirect, DL, O,
12950 /*IsVariadic=*/false);
12951}
12952
12955 ArrayRef<SDNode *> Dependencies,
12956 bool IsIndirect, const DebugLoc &DL,
12957 unsigned O, bool IsVariadic) {
12958 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
12959 "Expected inlined-at fields to agree");
12960 return new (DbgInfo->getAlloc())
12961 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, Locs, Dependencies, IsIndirect,
12962 DL, O, IsVariadic);
12963}
12964
12966 unsigned OffsetInBits, unsigned SizeInBits,
12967 bool InvalidateDbg) {
12968 SDNode *FromNode = From.getNode();
12969 SDNode *ToNode = To.getNode();
12970 assert(FromNode && ToNode && "Can't modify dbg values");
12971
12972 // PR35338
12973 // TODO: assert(From != To && "Redundant dbg value transfer");
12974 // TODO: assert(FromNode != ToNode && "Intranode dbg value transfer");
12975 if (From == To || FromNode == ToNode)
12976 return;
12977
12978 if (!FromNode->getHasDebugValue())
12979 return;
12980
12981 SDDbgOperand FromLocOp =
12982 SDDbgOperand::fromNode(From.getNode(), From.getResNo());
12984
12986 for (SDDbgValue *Dbg : GetDbgValues(FromNode)) {
12987 if (Dbg->isInvalidated())
12988 continue;
12989
12990 // TODO: assert(!Dbg->isInvalidated() && "Transfer of invalid dbg value");
12991
12992 // Create a new location ops vector that is equal to the old vector, but
12993 // with each instance of FromLocOp replaced with ToLocOp.
12994 bool Changed = false;
12995 auto NewLocOps = Dbg->copyLocationOps();
12996 std::replace_if(
12997 NewLocOps.begin(), NewLocOps.end(),
12998 [&Changed, FromLocOp](const SDDbgOperand &Op) {
12999 bool Match = Op == FromLocOp;
13000 Changed |= Match;
13001 return Match;
13002 },
13003 ToLocOp);
13004 // Ignore this SDDbgValue if we didn't find a matching location.
13005 if (!Changed)
13006 continue;
13007
13008 DIVariable *Var = Dbg->getVariable();
13009 auto *Expr = Dbg->getExpression();
13010 // If a fragment is requested, update the expression.
13011 if (SizeInBits) {
13012 // When splitting a larger (e.g., sign-extended) value whose
13013 // lower bits are described with an SDDbgValue, do not attempt
13014 // to transfer the SDDbgValue to the upper bits.
13015 if (auto FI = Expr->getFragmentInfo())
13016 if (OffsetInBits + SizeInBits > FI->SizeInBits)
13017 continue;
13018 auto Fragment = DIExpression::createFragmentExpression(Expr, OffsetInBits,
13019 SizeInBits);
13020 if (!Fragment)
13021 continue;
13022 Expr = *Fragment;
13023 }
13024
13025 auto AdditionalDependencies = Dbg->getAdditionalDependencies();
13026 // Clone the SDDbgValue and move it to To.
13027 SDDbgValue *Clone = getDbgValueList(
13028 Var, Expr, NewLocOps, AdditionalDependencies, Dbg->isIndirect(),
13029 Dbg->getDebugLoc(), std::max(ToNode->getIROrder(), Dbg->getOrder()),
13030 Dbg->isVariadic());
13031 ClonedDVs.push_back(Clone);
13032
13033 if (InvalidateDbg) {
13034 // Invalidate value and indicate the SDDbgValue should not be emitted.
13035 Dbg->setIsInvalidated();
13036 Dbg->setIsEmitted();
13037 }
13038 }
13039
13040 for (SDDbgValue *Dbg : ClonedDVs) {
13041 assert(is_contained(Dbg->getSDNodes(), ToNode) &&
13042 "Transferred DbgValues should depend on the new SDNode");
13043 AddDbgValue(Dbg, false);
13044 }
13045}
13046
13048 if (!N.getHasDebugValue())
13049 return;
13050
13051 auto GetLocationOperand = [](SDNode *Node, unsigned ResNo) {
13052 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(Node))
13053 return SDDbgOperand::fromFrameIdx(FISDN->getIndex());
13054 return SDDbgOperand::fromNode(Node, ResNo);
13055 };
13056
13058 for (auto *DV : GetDbgValues(&N)) {
13059 if (DV->isInvalidated())
13060 continue;
13061 switch (N.getOpcode()) {
13062 default:
13063 break;
13064 case ISD::ADD: {
13065 SDValue N0 = N.getOperand(0);
13066 SDValue N1 = N.getOperand(1);
13067 if (!isa<ConstantSDNode>(N0)) {
13068 bool RHSConstant = isa<ConstantSDNode>(N1);
13069 uint64_t Offset;
13070 if (RHSConstant)
13071 Offset = N.getConstantOperandVal(1);
13072 // We are not allowed to turn indirect debug values variadic, so
13073 // don't salvage those.
13074 if (!RHSConstant && DV->isIndirect())
13075 continue;
13076
13077 // Rewrite an ADD constant node into a DIExpression. Since we are
13078 // performing arithmetic to compute the variable's *value* in the
13079 // DIExpression, we need to mark the expression with a
13080 // DW_OP_stack_value.
13081 auto *DIExpr = DV->getExpression();
13082 auto NewLocOps = DV->copyLocationOps();
13083 bool Changed = false;
13084 size_t OrigLocOpsSize = NewLocOps.size();
13085 for (size_t i = 0; i < OrigLocOpsSize; ++i) {
13086 // We're not given a ResNo to compare against because the whole
13087 // node is going away. We know that any ISD::ADD only has one
13088 // result, so we can assume any node match is using the result.
13089 if (NewLocOps[i].getKind() != SDDbgOperand::SDNODE ||
13090 NewLocOps[i].getSDNode() != &N)
13091 continue;
13092 NewLocOps[i] = GetLocationOperand(N0.getNode(), N0.getResNo());
13093 if (RHSConstant) {
13096 DIExpr = DIExpression::appendOpsToArg(DIExpr, ExprOps, i, true);
13097 } else {
13098 // Convert to a variadic expression (if not already).
13099 // convertToVariadicExpression() returns a const pointer, so we use
13100 // a temporary const variable here.
13101 const auto *TmpDIExpr =
13105 ExprOps.push_back(NewLocOps.size());
13106 ExprOps.push_back(dwarf::DW_OP_plus);
13107 SDDbgOperand RHS =
13109 NewLocOps.push_back(RHS);
13110 DIExpr = DIExpression::appendOpsToArg(TmpDIExpr, ExprOps, i, true);
13111 }
13112 Changed = true;
13113 }
13114 (void)Changed;
13115 assert(Changed && "Salvage target doesn't use N");
13116
13117 bool IsVariadic =
13118 DV->isVariadic() || OrigLocOpsSize != NewLocOps.size();
13119
13120 auto AdditionalDependencies = DV->getAdditionalDependencies();
13121 SDDbgValue *Clone = getDbgValueList(
13122 DV->getVariable(), DIExpr, NewLocOps, AdditionalDependencies,
13123 DV->isIndirect(), DV->getDebugLoc(), DV->getOrder(), IsVariadic);
13124 ClonedDVs.push_back(Clone);
13125 DV->setIsInvalidated();
13126 DV->setIsEmitted();
13127 LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting";
13128 N0.getNode()->dumprFull(this);
13129 dbgs() << " into " << *DIExpr << '\n');
13130 }
13131 break;
13132 }
13133 case ISD::TRUNCATE: {
13134 SDValue N0 = N.getOperand(0);
13135 TypeSize FromSize = N0.getValueSizeInBits();
13136 TypeSize ToSize = N.getValueSizeInBits(0);
13137
13138 DIExpression *DbgExpression = DV->getExpression();
13139 auto ExtOps = DIExpression::getExtOps(FromSize, ToSize, false);
13140 auto NewLocOps = DV->copyLocationOps();
13141 bool Changed = false;
13142 for (size_t i = 0; i < NewLocOps.size(); ++i) {
13143 if (NewLocOps[i].getKind() != SDDbgOperand::SDNODE ||
13144 NewLocOps[i].getSDNode() != &N)
13145 continue;
13146
13147 NewLocOps[i] = GetLocationOperand(N0.getNode(), N0.getResNo());
13148 DbgExpression = DIExpression::appendOpsToArg(DbgExpression, ExtOps, i);
13149 Changed = true;
13150 }
13151 assert(Changed && "Salvage target doesn't use N");
13152 (void)Changed;
13153
13154 SDDbgValue *Clone =
13155 getDbgValueList(DV->getVariable(), DbgExpression, NewLocOps,
13156 DV->getAdditionalDependencies(), DV->isIndirect(),
13157 DV->getDebugLoc(), DV->getOrder(), DV->isVariadic());
13158
13159 ClonedDVs.push_back(Clone);
13160 DV->setIsInvalidated();
13161 DV->setIsEmitted();
13162 LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting"; N0.getNode()->dumprFull(this);
13163 dbgs() << " into " << *DbgExpression << '\n');
13164 break;
13165 }
13166 }
13167 }
13168
13169 for (SDDbgValue *Dbg : ClonedDVs) {
13170 assert((!Dbg->getSDNodes().empty() ||
13171 llvm::any_of(Dbg->getLocationOps(),
13172 [&](const SDDbgOperand &Op) {
13173 return Op.getKind() == SDDbgOperand::FRAMEIX;
13174 })) &&
13175 "Salvaged DbgValue should depend on a new SDNode");
13176 AddDbgValue(Dbg, false);
13177 }
13178}
13179
13180/// Creates a SDDbgLabel node.
13182 const DebugLoc &DL, unsigned O) {
13183 assert(cast<DILabel>(Label)->isValidLocationForIntrinsic(DL) &&
13184 "Expected inlined-at fields to agree");
13185 return new (DbgInfo->getAlloc()) SDDbgLabel(Label, DL, O);
13186}
13187
13188namespace {
13189
13190/// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node
13191/// pointed to by a use iterator is deleted, increment the use iterator
13192/// so that it doesn't dangle.
13193///
13194class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener {
13197
13198 void NodeDeleted(SDNode *N, SDNode *E) override {
13199 // Increment the iterator as needed.
13200 while (UI != UE && N == UI->getUser())
13201 ++UI;
13202 }
13203
13204public:
13205 RAUWUpdateListener(SelectionDAG &d,
13208 : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {}
13209};
13210
13211} // end anonymous namespace
13212
13213/// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
13214/// This can cause recursive merging of nodes in the DAG.
13215///
13216/// This version assumes From has a single result value.
13217///
13219 SDNode *From = FromN.getNode();
13220 assert(From->getNumValues() == 1 && FromN.getResNo() == 0 &&
13221 "Cannot replace with this method!");
13222 assert(From != To.getNode() && "Cannot replace uses of with self");
13223
13224 // Preserve Debug Values
13225 transferDbgValues(FromN, To);
13226 // Preserve extra info.
13227 copyExtraInfo(From, To.getNode());
13228
13229 // Iterate over all the existing uses of From. New uses will be added
13230 // to the beginning of the use list, which we avoid visiting.
13231 // This specifically avoids visiting uses of From that arise while the
13232 // replacement is happening, because any such uses would be the result
13233 // of CSE: If an existing node looks like From after one of its operands
13234 // is replaced by To, we don't want to replace of all its users with To
13235 // too. See PR3018 for more info.
13236 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
13237 RAUWUpdateListener Listener(*this, UI, UE);
13238 while (UI != UE) {
13239 SDNode *User = UI->getUser();
13240
13241 // This node is about to morph, remove its old self from the CSE maps.
13242 RemoveNodeFromCSEMaps(User);
13243
13244 // A user can appear in a use list multiple times, and when this
13245 // happens the uses are usually next to each other in the list.
13246 // To help reduce the number of CSE recomputations, process all
13247 // the uses of this user that we can find this way.
13248 do {
13249 SDUse &Use = *UI;
13250 ++UI;
13251 Use.set(To);
13252 if (To->isDivergent() != From->isDivergent())
13254 } while (UI != UE && UI->getUser() == User);
13255 // Now that we have modified User, add it back to the CSE maps. If it
13256 // already exists there, recursively merge the results together.
13257 AddModifiedNodeToCSEMaps(User);
13258 }
13259
13260 // If we just RAUW'd the root, take note.
13261 if (FromN == getRoot())
13262 setRoot(To);
13263}
13264
13265/// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
13266/// This can cause recursive merging of nodes in the DAG.
13267///
13268/// This version assumes that for each value of From, there is a
13269/// corresponding value in To in the same position with the same type.
13270///
13272#ifndef NDEBUG
13273 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
13274 assert((!From->hasAnyUseOfValue(i) ||
13275 From->getValueType(i) == To->getValueType(i)) &&
13276 "Cannot use this version of ReplaceAllUsesWith!");
13277#endif
13278
13279 // Handle the trivial case.
13280 if (From == To)
13281 return;
13282
13283 // Preserve Debug Info. Only do this if there's a use.
13284 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
13285 if (From->hasAnyUseOfValue(i)) {
13286 assert((i < To->getNumValues()) && "Invalid To location");
13287 transferDbgValues(SDValue(From, i), SDValue(To, i));
13288 }
13289 // Preserve extra info.
13290 copyExtraInfo(From, To);
13291
13292 // Iterate over just the existing users of From. See the comments in
13293 // the ReplaceAllUsesWith above.
13294 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
13295 RAUWUpdateListener Listener(*this, UI, UE);
13296 while (UI != UE) {
13297 SDNode *User = UI->getUser();
13298
13299 // This node is about to morph, remove its old self from the CSE maps.
13300 RemoveNodeFromCSEMaps(User);
13301
13302 // A user can appear in a use list multiple times, and when this
13303 // happens the uses are usually next to each other in the list.
13304 // To help reduce the number of CSE recomputations, process all
13305 // the uses of this user that we can find this way.
13306 do {
13307 SDUse &Use = *UI;
13308 ++UI;
13309 Use.setNode(To);
13310 if (To->isDivergent() != From->isDivergent())
13312 } while (UI != UE && UI->getUser() == User);
13313
13314 // Now that we have modified User, add it back to the CSE maps. If it
13315 // already exists there, recursively merge the results together.
13316 AddModifiedNodeToCSEMaps(User);
13317 }
13318
13319 // If we just RAUW'd the root, take note.
13320 if (From == getRoot().getNode())
13321 setRoot(SDValue(To, getRoot().getResNo()));
13322}
13323
13324/// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
13325/// This can cause recursive merging of nodes in the DAG.
13326///
13327/// This version can replace From with any result values. To must match the
13328/// number and types of values returned by From.
13330 if (From->getNumValues() == 1) // Handle the simple case efficiently.
13331 return ReplaceAllUsesWith(SDValue(From, 0), To[0]);
13332
13333 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) {
13334 // Preserve Debug Info.
13335 transferDbgValues(SDValue(From, i), To[i]);
13336 // Preserve extra info.
13337 copyExtraInfo(From, To[i].getNode());
13338 }
13339
13340 // Iterate over just the existing users of From. See the comments in
13341 // the ReplaceAllUsesWith above.
13342 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
13343 RAUWUpdateListener Listener(*this, UI, UE);
13344 while (UI != UE) {
13345 SDNode *User = UI->getUser();
13346
13347 // This node is about to morph, remove its old self from the CSE maps.
13348 RemoveNodeFromCSEMaps(User);
13349
13350 // A user can appear in a use list multiple times, and when this happens the
13351 // uses are usually next to each other in the list. To help reduce the
13352 // number of CSE and divergence recomputations, process all the uses of this
13353 // user that we can find this way.
13354 bool To_IsDivergent = false;
13355 do {
13356 SDUse &Use = *UI;
13357 const SDValue &ToOp = To[Use.getResNo()];
13358 ++UI;
13359 Use.set(ToOp);
13360 if (ToOp.getValueType() != MVT::Other)
13361 To_IsDivergent |= ToOp->isDivergent();
13362 } while (UI != UE && UI->getUser() == User);
13363
13364 if (To_IsDivergent != From->isDivergent())
13366
13367 // Now that we have modified User, add it back to the CSE maps. If it
13368 // already exists there, recursively merge the results together.
13369 AddModifiedNodeToCSEMaps(User);
13370 }
13371
13372 // If we just RAUW'd the root, take note.
13373 if (From == getRoot().getNode())
13374 setRoot(SDValue(To[getRoot().getResNo()]));
13375}
13376
13377/// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
13378/// uses of other values produced by From.getNode() alone. The Deleted
13379/// vector is handled the same way as for ReplaceAllUsesWith.
13381 // Handle the really simple, really trivial case efficiently.
13382 if (From == To) return;
13383
13384 // Handle the simple, trivial, case efficiently.
13385 if (From.getNode()->getNumValues() == 1) {
13386 ReplaceAllUsesWith(From, To);
13387 return;
13388 }
13389
13390 // Preserve Debug Info.
13391 transferDbgValues(From, To);
13392 copyExtraInfo(From.getNode(), To.getNode());
13393
13394 // Iterate over just the existing users of From. See the comments in
13395 // the ReplaceAllUsesWith above.
13396 SDNode::use_iterator UI = From.getNode()->use_begin(),
13397 UE = From.getNode()->use_end();
13398 RAUWUpdateListener Listener(*this, UI, UE);
13399 while (UI != UE) {
13400 SDNode *User = UI->getUser();
13401 bool UserRemovedFromCSEMaps = false;
13402
13403 // A user can appear in a use list multiple times, and when this
13404 // happens the uses are usually next to each other in the list.
13405 // To help reduce the number of CSE recomputations, process all
13406 // the uses of this user that we can find this way.
13407 do {
13408 SDUse &Use = *UI;
13409
13410 // Skip uses of different values from the same node.
13411 if (Use.getResNo() != From.getResNo()) {
13412 ++UI;
13413 continue;
13414 }
13415
13416 // If this node hasn't been modified yet, it's still in the CSE maps,
13417 // so remove its old self from the CSE maps.
13418 if (!UserRemovedFromCSEMaps) {
13419 RemoveNodeFromCSEMaps(User);
13420 UserRemovedFromCSEMaps = true;
13421 }
13422
13423 ++UI;
13424 Use.set(To);
13425 if (To->isDivergent() != From->isDivergent())
13427 } while (UI != UE && UI->getUser() == User);
13428 // We are iterating over all uses of the From node, so if a use
13429 // doesn't use the specific value, no changes are made.
13430 if (!UserRemovedFromCSEMaps)
13431 continue;
13432
13433 // Now that we have modified User, add it back to the CSE maps. If it
13434 // already exists there, recursively merge the results together.
13435 AddModifiedNodeToCSEMaps(User);
13436 }
13437
13438 // If we just RAUW'd the root, take note.
13439 if (From == getRoot())
13440 setRoot(To);
13441}
13442
13443namespace {
13444
13445/// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith
13446/// to record information about a use.
13447struct UseMemo {
13448 SDNode *User;
13449 unsigned Index;
13450 SDUse *Use;
13451};
13452
13453/// operator< - Sort Memos by User.
13454bool operator<(const UseMemo &L, const UseMemo &R) {
13455 return (intptr_t)L.User < (intptr_t)R.User;
13456}
13457
13458/// RAUOVWUpdateListener - Helper for ReplaceAllUsesOfValuesWith - When the node
13459/// pointed to by a UseMemo is deleted, set the User to nullptr to indicate that
13460/// the node already has been taken care of recursively.
13461class RAUOVWUpdateListener : public SelectionDAG::DAGUpdateListener {
13462 SmallVectorImpl<UseMemo> &Uses;
13463
13464 void NodeDeleted(SDNode *N, SDNode *E) override {
13465 for (UseMemo &Memo : Uses)
13466 if (Memo.User == N)
13467 Memo.User = nullptr;
13468 }
13469
13470public:
13471 RAUOVWUpdateListener(SelectionDAG &d, SmallVectorImpl<UseMemo> &uses)
13472 : SelectionDAG::DAGUpdateListener(d), Uses(uses) {}
13473};
13474
13475} // end anonymous namespace
13476
13477/// Return true if a glue output should propagate divergence information.
13479 switch (Node->getOpcode()) {
13480 case ISD::CopyFromReg:
13481 case ISD::CopyToReg:
13482 return false;
13483 default:
13484 return true;
13485 }
13486
13487 llvm_unreachable("covered opcode switch");
13488}
13489
13491 if (TLI->isSDNodeAlwaysUniform(N)) {
13492 assert(!TLI->isSDNodeSourceOfDivergence(N, FLI, UA) &&
13493 "Conflicting divergence information!");
13494 return false;
13495 }
13496 if (TLI->isSDNodeSourceOfDivergence(N, FLI, UA))
13497 return true;
13498 for (const auto &Op : N->ops()) {
13499 EVT VT = Op.getValueType();
13500
13501 // Skip Chain. It does not carry divergence.
13502 if (VT != MVT::Other && Op.getNode()->isDivergent() &&
13503 (VT != MVT::Glue || gluePropagatesDivergence(Op.getNode())))
13504 return true;
13505 }
13506 return false;
13507}
13508
13510 SmallVector<SDNode *, 16> Worklist(1, N);
13511 do {
13512 N = Worklist.pop_back_val();
13513 bool IsDivergent = calculateDivergence(N);
13514 if (N->SDNodeBits.IsDivergent != IsDivergent) {
13515 N->SDNodeBits.IsDivergent = IsDivergent;
13516 llvm::append_range(Worklist, N->users());
13517 }
13518 } while (!Worklist.empty());
13519}
13520
13521void SelectionDAG::CreateTopologicalOrder(std::vector<SDNode *> &Order) {
13523 Order.reserve(AllNodes.size());
13524 for (auto &N : allnodes()) {
13525 unsigned NOps = N.getNumOperands();
13526 Degree[&N] = NOps;
13527 if (0 == NOps)
13528 Order.push_back(&N);
13529 }
13530 for (size_t I = 0; I != Order.size(); ++I) {
13531 SDNode *N = Order[I];
13532 for (auto *U : N->users()) {
13533 unsigned &UnsortedOps = Degree[U];
13534 if (0 == --UnsortedOps)
13535 Order.push_back(U);
13536 }
13537 }
13538}
13539
13540#if !defined(NDEBUG) && LLVM_ENABLE_ABI_BREAKING_CHECKS
13541void SelectionDAG::VerifyDAGDivergence() {
13542 std::vector<SDNode *> TopoOrder;
13543 CreateTopologicalOrder(TopoOrder);
13544 for (auto *N : TopoOrder) {
13545 assert(calculateDivergence(N) == N->isDivergent() &&
13546 "Divergence bit inconsistency detected");
13547 }
13548}
13549#endif
13550
13551/// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving
13552/// uses of other values produced by From.getNode() alone. The same value
13553/// may appear in both the From and To list. The Deleted vector is
13554/// handled the same way as for ReplaceAllUsesWith.
13556 const SDValue *To,
13557 unsigned Num){
13558 // Handle the simple, trivial case efficiently.
13559 if (Num == 1)
13560 return ReplaceAllUsesOfValueWith(*From, *To);
13561
13562 transferDbgValues(*From, *To);
13563 copyExtraInfo(From->getNode(), To->getNode());
13564
13565 // Read up all the uses and make records of them. This helps
13566 // processing new uses that are introduced during the
13567 // replacement process.
13569 for (unsigned i = 0; i != Num; ++i) {
13570 unsigned FromResNo = From[i].getResNo();
13571 SDNode *FromNode = From[i].getNode();
13572 for (SDUse &Use : FromNode->uses()) {
13573 if (Use.getResNo() == FromResNo) {
13574 UseMemo Memo = {Use.getUser(), i, &Use};
13575 Uses.push_back(Memo);
13576 }
13577 }
13578 }
13579
13580 // Sort the uses, so that all the uses from a given User are together.
13582 RAUOVWUpdateListener Listener(*this, Uses);
13583
13584 for (unsigned UseIndex = 0, UseIndexEnd = Uses.size();
13585 UseIndex != UseIndexEnd; ) {
13586 // We know that this user uses some value of From. If it is the right
13587 // value, update it.
13588 SDNode *User = Uses[UseIndex].User;
13589 // If the node has been deleted by recursive CSE updates when updating
13590 // another node, then just skip this entry.
13591 if (User == nullptr) {
13592 ++UseIndex;
13593 continue;
13594 }
13595
13596 // This node is about to morph, remove its old self from the CSE maps.
13597 RemoveNodeFromCSEMaps(User);
13598
13599 // The Uses array is sorted, so all the uses for a given User
13600 // are next to each other in the list.
13601 // To help reduce the number of CSE recomputations, process all
13602 // the uses of this user that we can find this way.
13603 do {
13604 unsigned i = Uses[UseIndex].Index;
13605 SDUse &Use = *Uses[UseIndex].Use;
13606 ++UseIndex;
13607
13608 Use.set(To[i]);
13609 } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User);
13610
13611 // Now that we have modified User, add it back to the CSE maps. If it
13612 // already exists there, recursively merge the results together.
13613 AddModifiedNodeToCSEMaps(User);
13614 }
13615}
13616
13617/// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
13618/// based on their topological order. It returns the maximum id and a vector
13619/// of the SDNodes* in assigned order by reference.
13621 unsigned DAGSize = 0;
13622
13623 // SortedPos tracks the progress of the algorithm. Nodes before it are
13624 // sorted, nodes after it are unsorted. When the algorithm completes
13625 // it is at the end of the list.
13626 allnodes_iterator SortedPos = allnodes_begin();
13627
13628 // Visit all the nodes. Move nodes with no operands to the front of
13629 // the list immediately. Annotate nodes that do have operands with their
13630 // operand count. Before we do this, the Node Id fields of the nodes
13631 // may contain arbitrary values. After, the Node Id fields for nodes
13632 // before SortedPos will contain the topological sort index, and the
13633 // Node Id fields for nodes At SortedPos and after will contain the
13634 // count of outstanding operands.
13636 checkForCycles(&N, this);
13637 unsigned Degree = N.getNumOperands();
13638 if (Degree == 0) {
13639 // A node with no uses, add it to the result array immediately.
13640 N.setNodeId(DAGSize++);
13641 allnodes_iterator Q(&N);
13642 if (Q != SortedPos)
13643 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q));
13644 assert(SortedPos != AllNodes.end() && "Overran node list");
13645 ++SortedPos;
13646 } else {
13647 // Temporarily use the Node Id as scratch space for the degree count.
13648 N.setNodeId(Degree);
13649 }
13650 }
13651
13652 // Visit all the nodes. As we iterate, move nodes into sorted order,
13653 // such that by the time the end is reached all nodes will be sorted.
13654 for (SDNode &Node : allnodes()) {
13655 SDNode *N = &Node;
13656 checkForCycles(N, this);
13657 // N is in sorted position, so all its uses have one less operand
13658 // that needs to be sorted.
13659 for (SDNode *P : N->users()) {
13660 unsigned Degree = P->getNodeId();
13661 assert(Degree != 0 && "Invalid node degree");
13662 --Degree;
13663 if (Degree == 0) {
13664 // All of P's operands are sorted, so P may sorted now.
13665 P->setNodeId(DAGSize++);
13666 if (P->getIterator() != SortedPos)
13667 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P));
13668 assert(SortedPos != AllNodes.end() && "Overran node list");
13669 ++SortedPos;
13670 } else {
13671 // Update P's outstanding operand count.
13672 P->setNodeId(Degree);
13673 }
13674 }
13675 if (Node.getIterator() == SortedPos) {
13676#ifndef NDEBUG
13678 SDNode *S = &*++I;
13679 dbgs() << "Overran sorted position:\n";
13680 S->dumprFull(this); dbgs() << "\n";
13681 dbgs() << "Checking if this is due to cycles\n";
13682 checkForCycles(this, true);
13683#endif
13684 llvm_unreachable(nullptr);
13685 }
13686 }
13687
13688 assert(SortedPos == AllNodes.end() &&
13689 "Topological sort incomplete!");
13690 assert(AllNodes.front().getOpcode() == ISD::EntryToken &&
13691 "First node in topological sort is not the entry token!");
13692 assert(AllNodes.front().getNodeId() == 0 &&
13693 "First node in topological sort has non-zero id!");
13694 assert(AllNodes.front().getNumOperands() == 0 &&
13695 "First node in topological sort has operands!");
13696 assert(AllNodes.back().getNodeId() == (int)DAGSize-1 &&
13697 "Last node in topologic sort has unexpected id!");
13698 assert(AllNodes.back().use_empty() &&
13699 "Last node in topologic sort has users!");
13700 assert(DAGSize == allnodes_size() && "Node count mismatch!");
13701 return DAGSize;
13702}
13703
13705 SmallVectorImpl<const SDNode *> &SortedNodes) const {
13706 SortedNodes.clear();
13707 // Node -> remaining number of outstanding operands.
13708 DenseMap<const SDNode *, unsigned> RemainingOperands;
13709
13710 // Put nodes without any operands into SortedNodes first.
13711 for (const SDNode &N : allnodes()) {
13712 checkForCycles(&N, this);
13713 unsigned NumOperands = N.getNumOperands();
13714 if (NumOperands == 0)
13715 SortedNodes.push_back(&N);
13716 else
13717 // Record their total number of outstanding operands.
13718 RemainingOperands[&N] = NumOperands;
13719 }
13720
13721 // A node is pushed into SortedNodes when all of its operands (predecessors in
13722 // the graph) are also in SortedNodes.
13723 for (unsigned i = 0U; i < SortedNodes.size(); ++i) {
13724 const SDNode *N = SortedNodes[i];
13725 for (const SDNode *U : N->users()) {
13726 // HandleSDNode is never part of a DAG and therefore has no entry in
13727 // RemainingOperands.
13728 if (U->getOpcode() == ISD::HANDLENODE)
13729 continue;
13730 unsigned &NumRemOperands = RemainingOperands[U];
13731 assert(NumRemOperands && "Invalid number of remaining operands");
13732 --NumRemOperands;
13733 if (!NumRemOperands)
13734 SortedNodes.push_back(U);
13735 }
13736 }
13737
13738 assert(SortedNodes.size() == AllNodes.size() && "Node count mismatch");
13739 assert(SortedNodes.front()->getOpcode() == ISD::EntryToken &&
13740 "First node in topological sort is not the entry token");
13741 assert(SortedNodes.front()->getNumOperands() == 0 &&
13742 "First node in topological sort has operands");
13743}
13744
13745/// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the
13746/// value is produced by SD.
13747void SelectionDAG::AddDbgValue(SDDbgValue *DB, bool isParameter) {
13748 for (SDNode *SD : DB->getSDNodes()) {
13749 if (!SD)
13750 continue;
13751 assert(DbgInfo->getSDDbgValues(SD).empty() || SD->getHasDebugValue());
13752 SD->setHasDebugValue(true);
13753 }
13754 DbgInfo->add(DB, isParameter);
13755}
13756
13757void SelectionDAG::AddDbgLabel(SDDbgLabel *DB) { DbgInfo->add(DB); }
13758
13760 SDValue NewMemOpChain) {
13761 assert(isa<MemSDNode>(NewMemOpChain) && "Expected a memop node");
13762 assert(NewMemOpChain.getValueType() == MVT::Other && "Expected a token VT");
13763 // The new memory operation must have the same position as the old load in
13764 // terms of memory dependency. Create a TokenFactor for the old load and new
13765 // memory operation and update uses of the old load's output chain to use that
13766 // TokenFactor.
13767 if (OldChain == NewMemOpChain || OldChain.use_empty())
13768 return NewMemOpChain;
13769
13770 SDValue TokenFactor = getNode(ISD::TokenFactor, SDLoc(OldChain), MVT::Other,
13771 OldChain, NewMemOpChain);
13772 ReplaceAllUsesOfValueWith(OldChain, TokenFactor);
13773 UpdateNodeOperands(TokenFactor.getNode(), OldChain, NewMemOpChain);
13774 return TokenFactor;
13775}
13776
13778 SDValue NewMemOp) {
13779 assert(isa<MemSDNode>(NewMemOp.getNode()) && "Expected a memop node");
13780 SDValue OldChain = SDValue(OldLoad, 1);
13781 SDValue NewMemOpChain = NewMemOp.getValue(1);
13782 return makeEquivalentMemoryOrdering(OldChain, NewMemOpChain);
13783}
13784
13786 Function **OutFunction) {
13787 assert(isa<ExternalSymbolSDNode>(Op) && "Node should be an ExternalSymbol");
13788
13789 auto *Symbol = cast<ExternalSymbolSDNode>(Op)->getSymbol();
13790 auto *Module = MF->getFunction().getParent();
13791 auto *Function = Module->getFunction(Symbol);
13792
13793 if (OutFunction != nullptr)
13794 *OutFunction = Function;
13795
13796 if (Function != nullptr) {
13797 auto PtrTy = TLI->getPointerTy(getDataLayout(), Function->getAddressSpace());
13798 return getGlobalAddress(Function, SDLoc(Op), PtrTy);
13799 }
13800
13801 std::string ErrorStr;
13802 raw_string_ostream ErrorFormatter(ErrorStr);
13803 ErrorFormatter << "Undefined external symbol ";
13804 ErrorFormatter << '"' << Symbol << '"';
13805 report_fatal_error(Twine(ErrorStr));
13806}
13807
13808//===----------------------------------------------------------------------===//
13809// SDNode Class
13810//===----------------------------------------------------------------------===//
13811
13814 return Const != nullptr && Const->isZero();
13815}
13816
13818 return V.isUndef() || isNullConstant(V);
13819}
13820
13823 return Const != nullptr && Const->isZero() && !Const->isNegative();
13824}
13825
13828 return Const != nullptr && Const->isAllOnes();
13829}
13830
13833 return Const != nullptr && Const->isOne();
13834}
13835
13838 return Const != nullptr && Const->isMinSignedValue();
13839}
13840
13842 SDValue V, unsigned OperandNo,
13843 unsigned Depth) const {
13844 APInt DemandedElts = getDemandAllEltsMask(V);
13845 return isIdentityElement(Opcode, Flags, V, DemandedElts, OperandNo, Depth);
13846}
13847
13849 SDValue V, const APInt &DemandedElts,
13850 unsigned OperandNo, unsigned Depth) const {
13851 // NOTE: The cases should match with IR's ConstantExpr::getBinOpIdentity().
13852 // TODO: Target-specific opcodes could be added.
13853 if (V.getValueType().isInteger()) {
13854 KnownBits Known = computeKnownBits(V, DemandedElts, Depth);
13855 if (Known.isConstant()) {
13856 const APInt &Const = Known.getConstant();
13857 switch (Opcode) {
13858 case ISD::ADD:
13859 case ISD::OR:
13860 case ISD::XOR:
13861 case ISD::UMAX:
13862 return Const.isZero();
13863 case ISD::MUL:
13864 return Const.isOne();
13865 case ISD::AND:
13866 case ISD::UMIN:
13867 return Const.isAllOnes();
13868 case ISD::SMAX:
13869 return Const.isMinSignedValue();
13870 case ISD::SMIN:
13871 return Const.isMaxSignedValue();
13872 case ISD::SUB:
13873 case ISD::SHL:
13874 case ISD::SRA:
13875 case ISD::SRL:
13876 return OperandNo == 1 && Const.isZero();
13877 case ISD::UDIV:
13878 case ISD::SDIV:
13879 return OperandNo == 1 && Const.isOne();
13880 }
13881 }
13882 } else if (auto *ConstFP = isConstOrConstSplatFP(V, DemandedElts)) {
13883 switch (Opcode) {
13884 case ISD::FADD:
13885 return ConstFP->isZero() &&
13886 (Flags.hasNoSignedZeros() || ConstFP->isNegative());
13887 case ISD::FSUB:
13888 return OperandNo == 1 && ConstFP->isZero() &&
13889 (Flags.hasNoSignedZeros() || !ConstFP->isNegative());
13890 case ISD::FMUL:
13891 return ConstFP->isOne();
13892 case ISD::FDIV:
13893 return OperandNo == 1 && ConstFP->isOne();
13894 case ISD::FMINNUM:
13895 case ISD::FMAXNUM:
13896 case ISD::FMINIMUMNUM:
13897 case ISD::FMAXIMUMNUM: {
13898 // Neutral element for fminnum/fminimumnum is NaN, Inf or FLT_MAX,
13899 // depending on fast-math flags (FMF).
13900 EVT VT = V.getValueType();
13901 const fltSemantics &Semantics = VT.getFltSemantics();
13902 APFloat NeutralAF = !Flags.hasNoNaNs() ? APFloat::getQNaN(Semantics)
13903 : !Flags.hasNoInfs() ? APFloat::getInf(Semantics)
13904 : APFloat::getLargest(Semantics);
13905 if (Opcode == ISD::FMAXNUM || Opcode == ISD::FMAXIMUMNUM)
13906 NeutralAF.changeSign();
13907
13908 return ConstFP->isExactlyValue(NeutralAF);
13909 }
13910 case ISD::FMINIMUM:
13911 case ISD::FMAXIMUM: {
13912 // Neutral element for fminimum is Inf or FLT_MAX, depending on FMF.
13913 const APFloat &VAPF = ConstFP->getValueAPF();
13914 bool NeutralNegative = (Opcode == ISD::FMAXIMUM);
13915 if (Flags.hasNoInfs())
13916 return VAPF.isLargest() && VAPF.isNegative() == NeutralNegative;
13917 return VAPF.isInfinity() && VAPF.isNegative() == NeutralNegative;
13918 }
13919 }
13920 }
13921 return false;
13922}
13923
13925 while (V.getOpcode() == ISD::BITCAST)
13926 V = V.getOperand(0);
13927 return V;
13928}
13929
13931 while (V.getOpcode() == ISD::BITCAST && V.getOperand(0).hasOneUse())
13932 V = V.getOperand(0);
13933 return V;
13934}
13935
13937 while (V.getOpcode() == ISD::EXTRACT_SUBVECTOR)
13938 V = V.getOperand(0);
13939 return V;
13940}
13941
13943 while (V.getOpcode() == ISD::INSERT_VECTOR_ELT) {
13944 SDValue InVec = V.getOperand(0);
13945 SDValue EltNo = V.getOperand(2);
13946 EVT VT = InVec.getValueType();
13947 auto *IndexC = dyn_cast<ConstantSDNode>(EltNo);
13948 if (IndexC && VT.isFixedLengthVector() &&
13949 IndexC->getAPIntValue().ult(VT.getVectorNumElements()) &&
13950 !DemandedElts[IndexC->getZExtValue()]) {
13951 V = InVec;
13952 continue;
13953 }
13954 break;
13955 }
13956 return V;
13957}
13958
13960 while (V.getOpcode() == ISD::TRUNCATE)
13961 V = V.getOperand(0);
13962 return V;
13963}
13964
13965bool llvm::isBitwiseNot(SDValue V, bool AllowUndefs) {
13966 if (V.getOpcode() != ISD::XOR)
13967 return false;
13968 V = peekThroughBitcasts(V.getOperand(1));
13969 unsigned NumBits = V.getScalarValueSizeInBits();
13970 ConstantSDNode *C =
13971 isConstOrConstSplat(V, AllowUndefs, /*AllowTruncation*/ true);
13972 return C && (C->getAPIntValue().countr_one() >= NumBits);
13973}
13974
13976 bool AllowTruncation) {
13977 APInt DemandedElts = getDemandAllEltsMask(N);
13978 return isConstOrConstSplat(N, DemandedElts, AllowUndefs, AllowTruncation);
13979}
13980
13982 bool AllowUndefs,
13983 bool AllowTruncation) {
13985 return CN;
13986
13987 // SplatVectors can truncate their operands. Ignore that case here unless
13988 // AllowTruncation is set.
13989 if (N->getOpcode() == ISD::SPLAT_VECTOR) {
13990 EVT VecEltVT = N->getValueType(0).getVectorElementType();
13991 if (auto *CN = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
13992 EVT CVT = CN->getValueType(0);
13993 assert(CVT.bitsGE(VecEltVT) && "Illegal splat_vector element extension");
13994 if (AllowTruncation || CVT == VecEltVT)
13995 return CN;
13996 }
13997 }
13998
14000 BitVector UndefElements;
14001 ConstantSDNode *CN = BV->getConstantSplatNode(DemandedElts, &UndefElements);
14002
14003 // BuildVectors can truncate their operands. Ignore that case here unless
14004 // AllowTruncation is set.
14005 // TODO: Look into whether we should allow UndefElements in non-DemandedElts
14006 if (CN && (UndefElements.none() || AllowUndefs)) {
14007 EVT CVT = CN->getValueType(0);
14008 EVT NSVT = N.getValueType().getScalarType();
14009 assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension");
14010 if (AllowTruncation || (CVT == NSVT))
14011 return CN;
14012 }
14013 }
14014
14015 if (N.getOpcode() == ISD::MERGE_VALUES)
14016 return isConstOrConstSplat(N.getOperand(N.getResNo()), DemandedElts,
14017 AllowUndefs, AllowTruncation);
14018
14019 return nullptr;
14020}
14021
14023 APInt DemandedElts = getDemandAllEltsMask(N);
14024 return isConstOrConstSplatFP(N, DemandedElts, AllowUndefs);
14025}
14026
14028 const APInt &DemandedElts,
14029 bool AllowUndefs) {
14031 return CN;
14032
14034 BitVector UndefElements;
14035 ConstantFPSDNode *CN =
14036 BV->getConstantFPSplatNode(DemandedElts, &UndefElements);
14037 // TODO: Look into whether we should allow UndefElements in non-DemandedElts
14038 if (CN && (UndefElements.none() || AllowUndefs))
14039 return CN;
14040 }
14041
14042 if (N.getOpcode() == ISD::SPLAT_VECTOR)
14043 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N.getOperand(0)))
14044 return CN;
14045
14046 return nullptr;
14047}
14048
14049bool llvm::isNullOrNullSplat(SDValue N, bool AllowUndefs) {
14050 // TODO: may want to use peekThroughBitcast() here.
14051 ConstantSDNode *C =
14052 isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation=*/true);
14053 return C && C->isZero();
14054}
14055
14056bool llvm::isOneOrOneSplat(SDValue N, bool AllowUndefs) {
14057 ConstantSDNode *C =
14058 isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation*/ true);
14059 return C && C->isOne();
14060}
14061
14062bool llvm::isOneOrOneSplatFP(SDValue N, bool AllowUndefs) {
14063 ConstantFPSDNode *C = isConstOrConstSplatFP(N, AllowUndefs);
14064 return C && C->isOne();
14065}
14066
14067bool llvm::isAllOnesOrAllOnesSplat(SDValue N, bool AllowUndefs) {
14069 unsigned BitWidth = N.getScalarValueSizeInBits();
14070 ConstantSDNode *C =
14071 isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation=*/true);
14072 return C && C->getAPIntValue().countTrailingOnes() >= BitWidth;
14073}
14074
14075bool llvm::isOnesOrOnesSplat(SDValue N, bool AllowUndefs) {
14076 ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs);
14077 return C && APInt::isSameValue(C->getAPIntValue(),
14078 APInt(C->getAPIntValue().getBitWidth(), 1));
14079}
14080
14081bool llvm::isZeroOrZeroSplat(SDValue N, bool AllowUndefs) {
14083 ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs, true);
14084 return C && C->isZero();
14085}
14086
14087bool llvm::isZeroOrZeroSplatFP(SDValue N, bool AllowUndefs) {
14088 ConstantFPSDNode *C = isConstOrConstSplatFP(N, AllowUndefs);
14089 return C && C->isZero();
14090}
14091
14095
14097 unsigned Opc, unsigned Order, const DebugLoc &dl, SDVTList VTs, EVT memvt,
14099 : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MemRefs(memrefs) {
14100 bool IsVolatile = false;
14101 bool IsNonTemporal = false;
14102 bool IsDereferenceable = true;
14103 bool IsInvariant = true;
14104 for (const MachineMemOperand *MMO : memoperands()) {
14105 IsVolatile |= MMO->isVolatile();
14106 IsNonTemporal |= MMO->isNonTemporal();
14107 IsDereferenceable &= MMO->isDereferenceable();
14108 IsInvariant &= MMO->isInvariant();
14109 }
14110 MemSDNodeBits.IsVolatile = IsVolatile;
14111 MemSDNodeBits.IsNonTemporal = IsNonTemporal;
14112 MemSDNodeBits.IsDereferenceable = IsDereferenceable;
14113 MemSDNodeBits.IsInvariant = IsInvariant;
14114
14115 // For the single-MMO case, we check here that the size of the memory operand
14116 // fits within the size of the MMO. This is because the MMO might indicate
14117 // only a possible address range instead of specifying the affected memory
14118 // addresses precisely.
14121 getMemOperand()->getSize().getValue())) &&
14122 "Size mismatch!");
14123}
14124
14125namespace {
14126
14127 struct EVTArray {
14128 std::vector<EVT> VTs;
14129
14130 EVTArray() {
14131 VTs.reserve(MVT::VALUETYPE_SIZE);
14132 for (unsigned i = 0; i < MVT::VALUETYPE_SIZE; ++i)
14133 VTs.push_back(MVT((MVT::SimpleValueType)i));
14134 }
14135 };
14136
14137} // end anonymous namespace
14138
14139/// getValueTypeList - Return a pointer to the specified value type.
14140///
14141const EVT *SDNode::getValueTypeList(MVT VT) {
14142 static EVTArray SimpleVTArray;
14143
14144 assert(VT < MVT::VALUETYPE_SIZE && "Value type out of range!");
14145 return &SimpleVTArray.VTs[VT.SimpleTy];
14146}
14147
14148/// hasAnyUseOfValue - Return true if there are any use of the indicated
14149/// value. This method ignores uses of other values defined by this operation.
14150bool SDNode::hasAnyUseOfValue(unsigned Value) const {
14151 assert(Value < getNumValues() && "Bad value!");
14152
14153 for (SDUse &U : uses())
14154 if (U.getResNo() == Value)
14155 return true;
14156
14157 return false;
14158}
14159
14160/// isOnlyUserOf - Return true if this node is the only use of N.
14161bool SDNode::isOnlyUserOf(const SDNode *N) const {
14162 bool Seen = false;
14163 for (const SDNode *User : N->users()) {
14164 if (User == this)
14165 Seen = true;
14166 else
14167 return false;
14168 }
14169
14170 return Seen;
14171}
14172
14173/// Return true if the only users of N are contained in Nodes.
14175 bool Seen = false;
14176 for (const SDNode *User : N->users()) {
14177 if (llvm::is_contained(Nodes, User))
14178 Seen = true;
14179 else
14180 return false;
14181 }
14182
14183 return Seen;
14184}
14185
14186/// Return true if the referenced return value is an operand of N.
14187bool SDValue::isOperandOf(const SDNode *N) const {
14188 return is_contained(N->op_values(), *this);
14189}
14190
14191bool SDNode::isOperandOf(const SDNode *N) const {
14192 return any_of(N->op_values(),
14193 [this](SDValue Op) { return this == Op.getNode(); });
14194}
14195
14196/// reachesChainWithoutSideEffects - Return true if this operand (which must
14197/// be a chain) reaches the specified operand without crossing any
14198/// side-effecting instructions on any chain path. In practice, this looks
14199/// through token factors and non-volatile loads. In order to remain efficient,
14200/// this only looks a couple of nodes in, it does not do an exhaustive search.
14201///
14202/// Note that we only need to examine chains when we're searching for
14203/// side-effects; SelectionDAG requires that all side-effects are represented
14204/// by chains, even if another operand would force a specific ordering. This
14205/// constraint is necessary to allow transformations like splitting loads.
14207 unsigned Depth) const {
14208 if (*this == Dest) return true;
14209
14210 // Don't search too deeply, we just want to be able to see through
14211 // TokenFactor's etc.
14212 if (Depth == 0) return false;
14213
14214 // If this is a token factor, all inputs to the TF happen in parallel.
14215 if (getOpcode() == ISD::TokenFactor) {
14216 // First, try a shallow search.
14217 if (is_contained((*this)->ops(), Dest)) {
14218 // We found the chain we want as an operand of this TokenFactor.
14219 // Essentially, we reach the chain without side-effects if we could
14220 // serialize the TokenFactor into a simple chain of operations with
14221 // Dest as the last operation. This is automatically true if the
14222 // chain has one use: there are no other ordering constraints.
14223 // If the chain has more than one use, we give up: some other
14224 // use of Dest might force a side-effect between Dest and the current
14225 // node.
14226 if (Dest.hasOneUse())
14227 return true;
14228 }
14229 // Next, try a deep search: check whether every operand of the TokenFactor
14230 // reaches Dest.
14231 return llvm::all_of((*this)->ops(), [=](SDValue Op) {
14232 return Op.reachesChainWithoutSideEffects(Dest, Depth - 1);
14233 });
14234 }
14235
14236 // Loads don't have side effects, look through them.
14237 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
14238 if (Ld->isUnordered())
14239 return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
14240 }
14241 return false;
14242}
14243
14244bool SDNode::hasPredecessor(const SDNode *N) const {
14247 Worklist.push_back(this);
14248 return hasPredecessorHelper(N, Visited, Worklist);
14249}
14250
14252 this->Flags &= Flags;
14253}
14254
14255SDValue
14257 ArrayRef<ISD::NodeType> CandidateBinOps,
14258 bool AllowPartials) {
14259 // The pattern must end in an extract from index 0.
14260 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
14261 !isNullConstant(Extract->getOperand(1)))
14262 return SDValue();
14263
14264 // Match against one of the candidate binary ops.
14265 SDValue Op = Extract->getOperand(0);
14266 if (llvm::none_of(CandidateBinOps, [Op](ISD::NodeType BinOp) {
14267 return Op.getOpcode() == unsigned(BinOp);
14268 }))
14269 return SDValue();
14270
14271 // Floating-point reductions may require relaxed constraints on the final step
14272 // of the reduction because they may reorder intermediate operations.
14273 unsigned CandidateBinOp = Op.getOpcode();
14274 if (Op.getValueType().isFloatingPoint()) {
14275 SDNodeFlags Flags = Op->getFlags();
14276 switch (CandidateBinOp) {
14277 case ISD::FADD:
14278 if (!Flags.hasNoSignedZeros() || !Flags.hasAllowReassociation())
14279 return SDValue();
14280 break;
14281 default:
14282 llvm_unreachable("Unhandled FP opcode for binop reduction");
14283 }
14284 }
14285
14286 // Matching failed - attempt to see if we did enough stages that a partial
14287 // reduction from a subvector is possible.
14288 auto PartialReduction = [&](SDValue Op, unsigned NumSubElts) {
14289 if (!AllowPartials || !Op)
14290 return SDValue();
14291 EVT OpVT = Op.getValueType();
14292 EVT OpSVT = OpVT.getScalarType();
14293 EVT SubVT = EVT::getVectorVT(*getContext(), OpSVT, NumSubElts);
14294 if (TLI->getExtractSubvectorCost(SubVT, OpVT, 0) >
14296 return SDValue();
14297 BinOp = (ISD::NodeType)CandidateBinOp;
14298 return getExtractSubvector(SDLoc(Op), SubVT, Op, 0);
14299 };
14300
14301 // At each stage, we're looking for something that looks like:
14302 // %s = shufflevector <8 x i32> %op, <8 x i32> undef,
14303 // <8 x i32> <i32 2, i32 3, i32 undef, i32 undef,
14304 // i32 undef, i32 undef, i32 undef, i32 undef>
14305 // %a = binop <8 x i32> %op, %s
14306 // Where the mask changes according to the stage. E.g. for a 3-stage pyramid,
14307 // we expect something like:
14308 // <4,5,6,7,u,u,u,u>
14309 // <2,3,u,u,u,u,u,u>
14310 // <1,u,u,u,u,u,u,u>
14311 // While a partial reduction match would be:
14312 // <2,3,u,u,u,u,u,u>
14313 // <1,u,u,u,u,u,u,u>
14314 unsigned Stages = Log2_32(Op.getValueType().getVectorNumElements());
14315 SDValue PrevOp;
14316 for (unsigned i = 0; i < Stages; ++i) {
14317 unsigned MaskEnd = (1 << i);
14318
14319 if (Op.getOpcode() != CandidateBinOp)
14320 return PartialReduction(PrevOp, MaskEnd);
14321
14322 SDValue Op0 = Op.getOperand(0);
14323 SDValue Op1 = Op.getOperand(1);
14324
14326 if (Shuffle) {
14327 Op = Op1;
14328 } else {
14329 Shuffle = dyn_cast<ShuffleVectorSDNode>(Op1);
14330 Op = Op0;
14331 }
14332
14333 // The first operand of the shuffle should be the same as the other operand
14334 // of the binop.
14335 if (!Shuffle || Shuffle->getOperand(0) != Op)
14336 return PartialReduction(PrevOp, MaskEnd);
14337
14338 // Verify the shuffle has the expected (at this stage of the pyramid) mask.
14339 for (int Index = 0; Index < (int)MaskEnd; ++Index)
14340 if (Shuffle->getMaskElt(Index) != (int)(MaskEnd + Index))
14341 return PartialReduction(PrevOp, MaskEnd);
14342
14343 PrevOp = Op;
14344 }
14345
14346 // Handle subvector reductions, which tend to appear after the shuffle
14347 // reduction stages.
14348 while (Op.getOpcode() == CandidateBinOp) {
14349 unsigned NumElts = Op.getValueType().getVectorNumElements();
14350 SDValue Op0 = Op.getOperand(0);
14351 SDValue Op1 = Op.getOperand(1);
14352 if (Op0.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
14354 Op0.getOperand(0) != Op1.getOperand(0))
14355 break;
14356 SDValue Src = Op0.getOperand(0);
14357 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
14358 if (NumSrcElts != (2 * NumElts))
14359 break;
14360 if (!(Op0.getConstantOperandAPInt(1) == 0 &&
14361 Op1.getConstantOperandAPInt(1) == NumElts) &&
14362 !(Op1.getConstantOperandAPInt(1) == 0 &&
14363 Op0.getConstantOperandAPInt(1) == NumElts))
14364 break;
14365 Op = Src;
14366 }
14367
14368 BinOp = (ISD::NodeType)CandidateBinOp;
14369 return Op;
14370}
14371
14373 EVT VT = N->getValueType(0);
14374 EVT EltVT = VT.getVectorElementType();
14375 unsigned NE = getMaxRuntimeNumElements(VT);
14376
14377 if (VT.isScalableVector() && (NE == 0 || ResNE != 0))
14378 reportFatalUsageError("Cannot unroll scalable vector!");
14379
14380 assert(NE && "Nothing to unroll!");
14381 SDLoc dl(N);
14382
14383 // If ResNE is 0, fully unroll the vector op.
14384 if (ResNE == 0)
14385 ResNE = NE;
14386 else if (NE > ResNE)
14387 NE = ResNE;
14388
14389 if (N->getNumValues() == 2) {
14390 SmallVector<SDValue, 8> Scalars0, Scalars1;
14391 SmallVector<SDValue, 4> Operands(N->getNumOperands());
14392 EVT VT1 = N->getValueType(1);
14393 EVT EltVT1 = VT1.getVectorElementType();
14394
14395 unsigned i;
14396 for (i = 0; i != NE; ++i) {
14397 for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) {
14398 SDValue Operand = N->getOperand(j);
14399 EVT OperandVT = Operand.getValueType();
14400
14401 // A vector operand; extract a single element.
14402 EVT OperandEltVT = OperandVT.getVectorElementType();
14403 Operands[j] = getExtractVectorElt(dl, OperandEltVT, Operand, i);
14404 }
14405
14406 SDValue EltOp = getNode(N->getOpcode(), dl, {EltVT, EltVT1}, Operands);
14407 Scalars0.push_back(EltOp);
14408 Scalars1.push_back(EltOp.getValue(1));
14409 }
14410
14411 for (; i < ResNE; ++i) {
14412 Scalars0.push_back(getUNDEF(EltVT));
14413 Scalars1.push_back(getUNDEF(EltVT1));
14414 }
14415
14417 : ElementCount::getFixed(ResNE);
14418 EVT VecVT = EVT::getVectorVT(*getContext(), EltVT, ResEC);
14419 EVT VecVT1 = EVT::getVectorVT(*getContext(), EltVT1, ResEC);
14420 SDValue Vec0 = buildVectorFromUnrolledParts(VecVT, dl, Scalars0);
14421 SDValue Vec1 = buildVectorFromUnrolledParts(VecVT1, dl, Scalars1);
14422 return getMergeValues({Vec0, Vec1}, dl);
14423 }
14424
14425 assert(N->getNumValues() == 1 &&
14426 "Can't unroll a vector with multiple results!");
14427
14429 SmallVector<SDValue, 4> Operands(N->getNumOperands());
14430
14431 unsigned i;
14432 for (i= 0; i != NE; ++i) {
14433 for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) {
14434 SDValue Operand = N->getOperand(j);
14435 EVT OperandVT = Operand.getValueType();
14436 if (OperandVT.isVector()) {
14437 // A vector operand; extract a single element.
14438 EVT OperandEltVT = OperandVT.getVectorElementType();
14439 Operands[j] = getExtractVectorElt(dl, OperandEltVT, Operand, i);
14440 } else {
14441 // A scalar operand; just use it as is.
14442 Operands[j] = Operand;
14443 }
14444 }
14445
14446 switch (N->getOpcode()) {
14447 default: {
14448 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands,
14449 N->getFlags()));
14450 break;
14451 }
14452 case ISD::VSELECT:
14453 Scalars.push_back(
14454 getNode(ISD::SELECT, dl, EltVT, Operands, N->getFlags()));
14455 break;
14456 case ISD::SHL:
14457 case ISD::SRA:
14458 case ISD::SRL:
14459 case ISD::ROTL:
14460 case ISD::ROTR:
14461 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0],
14463 Operands[1])));
14464 break;
14466 EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType();
14467 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT,
14468 Operands[0],
14469 getValueType(ExtVT)));
14470 break;
14471 }
14472 case ISD::ADDRSPACECAST: {
14473 const auto *ASC = cast<AddrSpaceCastSDNode>(N);
14474 Scalars.push_back(
14475 getAddrSpaceCast(dl, EltVT, Operands[0], ASC->getSrcAddressSpace(),
14476 ASC->getDestAddressSpace(), ASC->getFlags()));
14477 break;
14478 }
14479 }
14480 }
14481
14482 for (; i < ResNE; ++i)
14483 Scalars.push_back(getUNDEF(EltVT));
14484
14485 EVT VecVT = VT.isScalableVector()
14486 ? VT
14487 : EVT::getVectorVT(*getContext(), EltVT, ResNE);
14488 return buildVectorFromUnrolledParts(VecVT, dl, Scalars);
14489}
14490
14491std::pair<SDValue, SDValue> SelectionDAG::UnrollVectorOverflowOp(
14492 SDNode *N, unsigned ResNE) {
14493 unsigned Opcode = N->getOpcode();
14494 assert((Opcode == ISD::UADDO || Opcode == ISD::SADDO ||
14495 Opcode == ISD::USUBO || Opcode == ISD::SSUBO ||
14496 Opcode == ISD::UMULO || Opcode == ISD::SMULO) &&
14497 "Expected an overflow opcode");
14498
14499 EVT ResVT = N->getValueType(0);
14500 EVT OvVT = N->getValueType(1);
14501 EVT ResEltVT = ResVT.getVectorElementType();
14502 EVT OvEltVT = OvVT.getVectorElementType();
14503 SDLoc dl(N);
14504
14505 // If ResNE is 0, fully unroll the vector op.
14506 unsigned NE = ResVT.getVectorNumElements();
14507 if (ResNE == 0)
14508 ResNE = NE;
14509 else if (NE > ResNE)
14510 NE = ResNE;
14511
14512 SmallVector<SDValue, 8> LHSScalars;
14513 SmallVector<SDValue, 8> RHSScalars;
14514 ExtractVectorElements(N->getOperand(0), LHSScalars, 0, NE);
14515 ExtractVectorElements(N->getOperand(1), RHSScalars, 0, NE);
14516
14517 EVT SVT = TLI->getSetCCResultType(getDataLayout(), *getContext(), ResEltVT);
14518 SDVTList VTs = getVTList(ResEltVT, SVT);
14519 SmallVector<SDValue, 8> ResScalars;
14520 SmallVector<SDValue, 8> OvScalars;
14521 for (unsigned i = 0; i < NE; ++i) {
14522 SDValue Res = getNode(Opcode, dl, VTs, LHSScalars[i], RHSScalars[i]);
14523 SDValue Ov =
14524 getSelect(dl, OvEltVT, Res.getValue(1),
14525 getBoolConstant(true, dl, OvEltVT, ResVT),
14526 getConstant(0, dl, OvEltVT));
14527
14528 ResScalars.push_back(Res);
14529 OvScalars.push_back(Ov);
14530 }
14531
14532 ResScalars.append(ResNE - NE, getUNDEF(ResEltVT));
14533 OvScalars.append(ResNE - NE, getUNDEF(OvEltVT));
14534
14535 EVT NewResVT = EVT::getVectorVT(*getContext(), ResEltVT, ResNE);
14536 EVT NewOvVT = EVT::getVectorVT(*getContext(), OvEltVT, ResNE);
14537 return std::make_pair(getBuildVector(NewResVT, dl, ResScalars),
14538 getBuildVector(NewOvVT, dl, OvScalars));
14539}
14540
14543 unsigned Bytes, int Dist,
14544 const SelectionDAG &DAG) {
14545 if (LS->isVolatile() || Base->isVolatile())
14546 return false;
14547 // TODO: probably too restrictive for atomics, revisit
14548 if (!LS->isSimple())
14549 return false;
14550 if (LS->isIndexed() || Base->isIndexed())
14551 return false;
14552 if (LS->getChain() != Base->getChain())
14553 return false;
14554 EVT VT = LS->getMemoryVT();
14555 if (VT.getSizeInBits() / 8 != Bytes)
14556 return false;
14557
14558 auto BaseLocDecomp = BaseIndexOffset::match(Base, DAG);
14559 auto LocDecomp = BaseIndexOffset::match(LS, DAG);
14560
14561 int64_t Offset = 0;
14562 if (BaseLocDecomp.equalBaseIndex(LocDecomp, DAG, Offset))
14563 return (Dist * (int64_t)Bytes == Offset);
14564 return false;
14565}
14566
14569 unsigned Bytes,
14570 int Dist) const {
14571 return areNonVolatileConsecutiveLoadsOrStores(LD, Base, Bytes, Dist, *this);
14572}
14573
14576 unsigned Bytes,
14577 int Dist) const {
14578 return areNonVolatileConsecutiveLoadsOrStores(ST, Base, Bytes, Dist, *this);
14579}
14580
14581/// InferPtrAlignment - Infer alignment of a load / store address. Return
14582/// std::nullopt if it cannot be inferred.
14584 // If this is a GlobalAddress + cst, return the alignment.
14585 const GlobalValue *GV = nullptr;
14586 int64_t GVOffset = 0;
14587 if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) {
14588 unsigned PtrWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
14589 KnownBits Known(PtrWidth);
14591 unsigned AlignBits = Known.countMinTrailingZeros();
14592 if (AlignBits)
14593 return commonAlignment(Align::fromLog2(std::min(31U, AlignBits)),
14594 GVOffset);
14595 }
14596
14597 // If this is a direct reference to a stack slot, use information about the
14598 // stack slot's alignment.
14599 int FrameIdx = INT_MIN;
14600 int64_t FrameOffset = 0;
14602 FrameIdx = FI->getIndex();
14603 } else if (isBaseWithConstantOffset(Ptr) &&
14605 // Handle FI+Cst
14606 FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
14607 FrameOffset = Ptr.getConstantOperandVal(1);
14608 }
14609
14610 if (FrameIdx != INT_MIN) {
14612 return commonAlignment(MFI.getObjectAlign(FrameIdx), FrameOffset);
14613 }
14614
14615 return std::nullopt;
14616}
14617
14618/// Split the scalar node with EXTRACT_ELEMENT using the provided
14619/// VTs and return the low/high part.
14620std::pair<SDValue, SDValue> SelectionDAG::SplitScalar(const SDValue &N,
14621 const SDLoc &DL,
14622 const EVT &LoVT,
14623 const EVT &HiVT) {
14624 assert(!LoVT.isVector() && !HiVT.isVector() && !N.getValueType().isVector() &&
14625 "Split node must be a scalar type");
14626 SDValue Lo =
14628 SDValue Hi =
14630 return std::make_pair(Lo, Hi);
14631}
14632
14633/// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type
14634/// which is split (or expanded) into two not necessarily identical pieces.
14635std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const {
14636 // Currently all types are split in half.
14637 EVT LoVT, HiVT;
14638 if (!VT.isVector())
14639 LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT);
14640 else
14641 LoVT = HiVT = VT.getHalfNumVectorElementsVT(*getContext());
14642
14643 return std::make_pair(LoVT, HiVT);
14644}
14645
14646/// GetDependentSplitDestVTs - Compute the VTs needed for the low/hi parts of a
14647/// type, dependent on an enveloping VT that has been split into two identical
14648/// pieces. Sets the HiIsEmpty flag when hi type has zero storage size.
14649std::pair<EVT, EVT>
14651 bool *HiIsEmpty) const {
14652 EVT EltTp = VT.getVectorElementType();
14653 // Examples:
14654 // custom VL=8 with enveloping VL=8/8 yields 8/0 (hi empty)
14655 // custom VL=9 with enveloping VL=8/8 yields 8/1
14656 // custom VL=10 with enveloping VL=8/8 yields 8/2
14657 // etc.
14658 ElementCount VTNumElts = VT.getVectorElementCount();
14659 ElementCount EnvNumElts = EnvVT.getVectorElementCount();
14660 assert(VTNumElts.isScalable() == EnvNumElts.isScalable() &&
14661 "Mixing fixed width and scalable vectors when enveloping a type");
14662 EVT LoVT, HiVT;
14663 if (VTNumElts.getKnownMinValue() > EnvNumElts.getKnownMinValue()) {
14664 LoVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts);
14665 HiVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts - EnvNumElts);
14666 *HiIsEmpty = false;
14667 } else {
14668 // Flag that hi type has zero storage size, but return split envelop type
14669 // (this would be easier if vector types with zero elements were allowed).
14670 LoVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts);
14671 HiVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts);
14672 *HiIsEmpty = true;
14673 }
14674 return std::make_pair(LoVT, HiVT);
14675}
14676
14677/// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the
14678/// low/high part.
14679std::pair<SDValue, SDValue>
14680SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT,
14681 const EVT &HiVT) {
14682 assert(LoVT.isScalableVector() == HiVT.isScalableVector() &&
14683 LoVT.isScalableVector() == N.getValueType().isScalableVector() &&
14684 "Splitting vector with an invalid mixture of fixed and scalable "
14685 "vector types");
14687 N.getValueType().getVectorMinNumElements() &&
14688 "More vector elements requested than available!");
14689 SDValue Lo, Hi;
14690 Lo = getExtractSubvector(DL, LoVT, N, 0);
14691 // For scalable vectors it is safe to use LoVT.getVectorMinNumElements()
14692 // (rather than having to use ElementCount), because EXTRACT_SUBVECTOR scales
14693 // IDX with the runtime scaling factor of the result vector type. For
14694 // fixed-width result vectors, that runtime scaling factor is 1.
14696 return std::make_pair(Lo, Hi);
14697}
14698
14699std::pair<SDValue, SDValue> SelectionDAG::SplitEVL(SDValue N, EVT VecVT,
14700 const SDLoc &DL) {
14701 // Split the vector length parameter.
14702 // %evl -> umin(%evl, %halfnumelts) and usubsat(%evl - %halfnumelts).
14703 EVT VT = N.getValueType();
14705 "Expecting the mask to be an evenly-sized vector");
14706 SDValue HalfNumElts = getElementCount(
14708 SDValue Lo = getNode(ISD::UMIN, DL, VT, N, HalfNumElts);
14709 SDValue Hi = getNode(ISD::USUBSAT, DL, VT, N, HalfNumElts);
14710 return std::make_pair(Lo, Hi);
14711}
14712
14713/// Widen the vector up to the next power of two using INSERT_SUBVECTOR.
14715 EVT VT = N.getValueType();
14718 return getInsertSubvector(DL, getPOISON(WideVT), N, 0);
14719}
14720
14723 unsigned Start, unsigned Count,
14724 EVT EltVT) {
14725 EVT VT = Op.getValueType();
14726 if (Count == 0)
14728 if (EltVT == EVT())
14729 EltVT = VT.getVectorElementType();
14730 SDLoc SL(Op);
14731 for (unsigned i = Start, e = Start + Count; i != e; ++i) {
14732 Args.push_back(getExtractVectorElt(SL, EltVT, Op, i));
14733 }
14734}
14735
14736// getAddressSpace - Return the address space this GlobalAddress belongs to.
14738 return getGlobal()->getType()->getAddressSpace();
14739}
14740
14743 return Val.MachineCPVal->getType();
14744 return Val.ConstVal->getType();
14745}
14746
14747bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue, APInt &SplatUndef,
14748 unsigned &SplatBitSize,
14749 bool &HasAnyUndefs,
14750 unsigned MinSplatBits,
14751 bool IsBigEndian) const {
14752 EVT VT = getValueType(0);
14753 assert(VT.isVector() && "Expected a vector type");
14754 unsigned VecWidth = VT.getSizeInBits();
14755 if (MinSplatBits > VecWidth)
14756 return false;
14757
14758 // FIXME: The widths are based on this node's type, but build vectors can
14759 // truncate their operands.
14760 SplatValue = APInt(VecWidth, 0);
14761 SplatUndef = APInt(VecWidth, 0);
14762
14763 // Get the bits. Bits with undefined values (when the corresponding element
14764 // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared
14765 // in SplatValue. If any of the values are not constant, give up and return
14766 // false.
14767 unsigned int NumOps = getNumOperands();
14768 assert(NumOps > 0 && "isConstantSplat has 0-size build vector");
14769 unsigned EltWidth = VT.getScalarSizeInBits();
14770
14771 for (unsigned j = 0; j < NumOps; ++j) {
14772 unsigned i = IsBigEndian ? NumOps - 1 - j : j;
14773 SDValue OpVal = getOperand(i);
14774 unsigned BitPos = j * EltWidth;
14775
14776 if (OpVal.isUndef())
14777 SplatUndef.setBits(BitPos, BitPos + EltWidth);
14778 else if (auto *CN = dyn_cast<ConstantSDNode>(OpVal))
14779 SplatValue.insertBits(CN->getAPIntValue().zextOrTrunc(EltWidth), BitPos);
14780 else if (auto *CN = dyn_cast<ConstantFPSDNode>(OpVal))
14781 SplatValue.insertBits(CN->getValueAPF().bitcastToAPInt(), BitPos);
14782 else
14783 return false;
14784 }
14785
14786 // The build_vector is all constants or undefs. Find the smallest element
14787 // size that splats the vector.
14788 HasAnyUndefs = (SplatUndef != 0);
14789
14790 // FIXME: This does not work for vectors with elements less than 8 bits.
14791 while (VecWidth > 8) {
14792 // If we can't split in half, stop here.
14793 if (VecWidth & 1)
14794 break;
14795
14796 unsigned HalfSize = VecWidth / 2;
14797 APInt HighValue = SplatValue.extractBits(HalfSize, HalfSize);
14798 APInt LowValue = SplatValue.extractBits(HalfSize, 0);
14799 APInt HighUndef = SplatUndef.extractBits(HalfSize, HalfSize);
14800 APInt LowUndef = SplatUndef.extractBits(HalfSize, 0);
14801
14802 // If the two halves do not match (ignoring undef bits), stop here.
14803 if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) ||
14804 MinSplatBits > HalfSize)
14805 break;
14806
14807 SplatValue = HighValue | LowValue;
14808 SplatUndef = HighUndef & LowUndef;
14809
14810 VecWidth = HalfSize;
14811 }
14812
14813 // FIXME: The loop above only tries to split in halves. But if the input
14814 // vector for example is <3 x i16> it wouldn't be able to detect a
14815 // SplatBitSize of 16. No idea if that is a design flaw currently limiting
14816 // optimizations. I guess that back in the days when this helper was created
14817 // vectors normally was power-of-2 sized.
14818
14819 SplatBitSize = VecWidth;
14820 return true;
14821}
14822
14824 BitVector *UndefElements) const {
14825 unsigned NumOps = getNumOperands();
14826 if (UndefElements) {
14827 UndefElements->clear();
14828 UndefElements->resize(NumOps);
14829 }
14830 assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size");
14831 if (!DemandedElts)
14832 return SDValue();
14833 SDValue Splatted;
14834 for (unsigned i = 0; i != NumOps; ++i) {
14835 if (!DemandedElts[i])
14836 continue;
14837 SDValue Op = getOperand(i);
14838 if (Op.isUndef()) {
14839 if (UndefElements)
14840 (*UndefElements)[i] = true;
14841 } else if (!Splatted) {
14842 Splatted = Op;
14843 } else if (Splatted != Op) {
14844 return SDValue();
14845 }
14846 }
14847
14848 if (!Splatted) {
14849 unsigned FirstDemandedIdx = DemandedElts.countr_zero();
14850 assert(getOperand(FirstDemandedIdx).isUndef() &&
14851 "Can only have a splat without a constant for all undefs.");
14852 return getOperand(FirstDemandedIdx);
14853 }
14854
14855 return Splatted;
14856}
14857
14859 APInt DemandedElts = APInt::getAllOnes(getNumOperands());
14860 return getSplatValue(DemandedElts, UndefElements);
14861}
14862
14864 SmallVectorImpl<SDValue> &Sequence,
14865 BitVector *UndefElements) const {
14866 unsigned NumOps = getNumOperands();
14867 Sequence.clear();
14868 if (UndefElements) {
14869 UndefElements->clear();
14870 UndefElements->resize(NumOps);
14871 }
14872 assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size");
14873 if (!DemandedElts || NumOps < 2 || !isPowerOf2_32(NumOps))
14874 return false;
14875
14876 // Set the undefs even if we don't find a sequence (like getSplatValue).
14877 if (UndefElements)
14878 for (unsigned I = 0; I != NumOps; ++I)
14879 if (DemandedElts[I] && getOperand(I).isUndef())
14880 (*UndefElements)[I] = true;
14881
14882 // Iteratively widen the sequence length looking for repetitions.
14883 for (unsigned SeqLen = 1; SeqLen < NumOps; SeqLen *= 2) {
14884 Sequence.append(SeqLen, SDValue());
14885 for (unsigned I = 0; I != NumOps; ++I) {
14886 if (!DemandedElts[I])
14887 continue;
14888 SDValue &SeqOp = Sequence[I % SeqLen];
14890 if (Op.isUndef()) {
14891 if (!SeqOp)
14892 SeqOp = Op;
14893 continue;
14894 }
14895 if (SeqOp && !SeqOp.isUndef() && SeqOp != Op) {
14896 Sequence.clear();
14897 break;
14898 }
14899 SeqOp = Op;
14900 }
14901 if (!Sequence.empty())
14902 return true;
14903 }
14904
14905 assert(Sequence.empty() && "Failed to empty non-repeating sequence pattern");
14906 return false;
14907}
14908
14910 BitVector *UndefElements) const {
14911 APInt DemandedElts = APInt::getAllOnes(getNumOperands());
14912 return getRepeatedSequence(DemandedElts, Sequence, UndefElements);
14913}
14914
14917 BitVector *UndefElements) const {
14919 getSplatValue(DemandedElts, UndefElements));
14920}
14921
14924 return dyn_cast_or_null<ConstantSDNode>(getSplatValue(UndefElements));
14925}
14926
14929 BitVector *UndefElements) const {
14931 getSplatValue(DemandedElts, UndefElements));
14932}
14933
14938
14939int32_t
14941 uint32_t BitWidth) const {
14942 if (ConstantFPSDNode *CN =
14944 bool IsExact;
14945 APSInt IntVal(BitWidth);
14946 const APFloat &APF = CN->getValueAPF();
14947 if (APF.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) !=
14948 APFloat::opOK ||
14949 !IsExact)
14950 return -1;
14951
14952 return IntVal.exactLogBase2();
14953 }
14954 return -1;
14955}
14956
14958 bool IsLittleEndian, unsigned DstEltSizeInBits,
14959 SmallVectorImpl<APInt> &RawBitElements, BitVector &UndefElements) const {
14960 // Early-out if this contains anything but Undef/Constant/ConstantFP.
14961 if (!isConstant())
14962 return false;
14963
14964 unsigned NumSrcOps = getNumOperands();
14965 unsigned SrcEltSizeInBits = getValueType(0).getScalarSizeInBits();
14966 assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 &&
14967 "Invalid bitcast scale");
14968
14969 // Extract raw src bits.
14970 SmallVector<APInt> SrcBitElements(NumSrcOps,
14971 APInt::getZero(SrcEltSizeInBits));
14972 BitVector SrcUndeElements(NumSrcOps, false);
14973
14974 for (unsigned I = 0; I != NumSrcOps; ++I) {
14976 if (Op.isUndef()) {
14977 SrcUndeElements.set(I);
14978 continue;
14979 }
14980 auto *CInt = dyn_cast<ConstantSDNode>(Op);
14981 auto *CFP = dyn_cast<ConstantFPSDNode>(Op);
14982 assert((CInt || CFP) && "Unknown constant");
14983 SrcBitElements[I] = CInt ? CInt->getAPIntValue().trunc(SrcEltSizeInBits)
14984 : CFP->getValueAPF().bitcastToAPInt();
14985 }
14986
14987 // Recast to dst width.
14988 recastRawBits(IsLittleEndian, DstEltSizeInBits, RawBitElements,
14989 SrcBitElements, UndefElements, SrcUndeElements);
14990 return true;
14991}
14992
14993void BuildVectorSDNode::recastRawBits(bool IsLittleEndian,
14994 unsigned DstEltSizeInBits,
14995 SmallVectorImpl<APInt> &DstBitElements,
14996 ArrayRef<APInt> SrcBitElements,
14997 BitVector &DstUndefElements,
14998 const BitVector &SrcUndefElements) {
14999 unsigned NumSrcOps = SrcBitElements.size();
15000 unsigned SrcEltSizeInBits = SrcBitElements[0].getBitWidth();
15001 assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 &&
15002 "Invalid bitcast scale");
15003 assert(NumSrcOps == SrcUndefElements.size() &&
15004 "Vector size mismatch");
15005
15006 unsigned NumDstOps = (NumSrcOps * SrcEltSizeInBits) / DstEltSizeInBits;
15007 DstUndefElements.clear();
15008 DstUndefElements.resize(NumDstOps, false);
15009 DstBitElements.assign(NumDstOps, APInt::getZero(DstEltSizeInBits));
15010
15011 // Concatenate src elements constant bits together into dst element.
15012 if (SrcEltSizeInBits <= DstEltSizeInBits) {
15013 unsigned Scale = DstEltSizeInBits / SrcEltSizeInBits;
15014 for (unsigned I = 0; I != NumDstOps; ++I) {
15015 DstUndefElements.set(I);
15016 APInt &DstBits = DstBitElements[I];
15017 for (unsigned J = 0; J != Scale; ++J) {
15018 unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1));
15019 if (SrcUndefElements[Idx])
15020 continue;
15021 DstUndefElements.reset(I);
15022 const APInt &SrcBits = SrcBitElements[Idx];
15023 assert(SrcBits.getBitWidth() == SrcEltSizeInBits &&
15024 "Illegal constant bitwidths");
15025 DstBits.insertBits(SrcBits, J * SrcEltSizeInBits);
15026 }
15027 }
15028 return;
15029 }
15030
15031 // Split src element constant bits into dst elements.
15032 unsigned Scale = SrcEltSizeInBits / DstEltSizeInBits;
15033 for (unsigned I = 0; I != NumSrcOps; ++I) {
15034 if (SrcUndefElements[I]) {
15035 DstUndefElements.set(I * Scale, (I + 1) * Scale);
15036 continue;
15037 }
15038 const APInt &SrcBits = SrcBitElements[I];
15039 for (unsigned J = 0; J != Scale; ++J) {
15040 unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1));
15041 APInt &DstBits = DstBitElements[Idx];
15042 DstBits = SrcBits.extractBits(DstEltSizeInBits, J * DstEltSizeInBits);
15043 }
15044 }
15045}
15046
15048 for (const SDValue &Op : op_values()) {
15049 unsigned Opc = Op.getOpcode();
15050 if (!Op.isUndef() && Opc != ISD::Constant && Opc != ISD::ConstantFP)
15051 return false;
15052 }
15053 return true;
15054}
15055
15056std::optional<std::pair<APInt, APInt>>
15058 unsigned NumOps = getNumOperands();
15059 if (NumOps < 2)
15060 return std::nullopt;
15061
15062 unsigned EltSize = getValueType(0).getScalarSizeInBits();
15063 APInt Start, Stride;
15064 int FirstIdx = -1, SecondIdx = -1;
15065
15066 // Find the first two non-undef constant elements to determine Start and
15067 // Stride, then verify all remaining elements match the sequence.
15068 for (unsigned I = 0; I < NumOps; ++I) {
15070 if (Op->isUndef())
15071 continue;
15072 if (!isa<ConstantSDNode>(Op))
15073 return std::nullopt;
15074
15075 APInt Val = getConstantOperandAPInt(I).trunc(EltSize);
15076 if (FirstIdx < 0) {
15077 FirstIdx = I;
15078 Start = Val;
15079 } else if (SecondIdx < 0) {
15080 SecondIdx = I;
15081 // Compute stride using modular arithmetic. Simple division would handle
15082 // common strides (1, 2, -1, etc.), but modular inverse maximizes matches.
15083 // Example: <0, poison, poison, 0xFF> has stride 0x55 since 3*0x55 = 0xFF
15084 // Note that modular arithmetic is agnostic to signed/unsigned.
15085 unsigned IdxDiff = I - FirstIdx;
15086 APInt ValDiff = Val - Start;
15087
15088 // Step 1: Factor out common powers of 2 from IdxDiff and ValDiff.
15089 unsigned CommonPow2Bits = llvm::countr_zero(IdxDiff);
15090 if (ValDiff.countr_zero() < CommonPow2Bits)
15091 return std::nullopt; // ValDiff not divisible by 2^CommonPow2Bits
15092 IdxDiff >>= CommonPow2Bits;
15093 ValDiff.lshrInPlace(CommonPow2Bits);
15094
15095 // Step 2: IdxDiff is now odd, so its inverse mod 2^EltSize exists.
15096 // TODO: There are 2^CommonPow2Bits valid strides; currently we only try
15097 // one, but we could try all candidates to handle more cases.
15098 Stride = ValDiff * APInt(EltSize, IdxDiff).multiplicativeInverse();
15099 if (Stride.isZero())
15100 return std::nullopt;
15101
15102 // Step 3: Adjust Start based on the first defined element's index.
15103 Start -= Stride * FirstIdx;
15104 } else {
15105 // Verify this element matches the sequence.
15106 if (Val != Start + Stride * I)
15107 return std::nullopt;
15108 }
15109 }
15110
15111 // Need at least two defined elements.
15112 if (SecondIdx < 0)
15113 return std::nullopt;
15114
15115 return std::make_pair(Start, Stride);
15116}
15117
15119 // Find the first non-undef value in the shuffle mask.
15120 unsigned i, e;
15121 for (i = 0, e = Mask.size(); i != e && Mask[i] < 0; ++i)
15122 /* search */;
15123
15124 // If all elements are undefined, this shuffle can be considered a splat
15125 // (although it should eventually get simplified away completely).
15126 if (i == e)
15127 return true;
15128
15129 // Make sure all remaining elements are either undef or the same as the first
15130 // non-undef value.
15131 for (int Idx = Mask[i]; i != e; ++i)
15132 if (Mask[i] >= 0 && Mask[i] != Idx)
15133 return false;
15134 return true;
15135}
15136
15137// Returns true if it is a constant integer BuildVector or constant integer,
15138// possibly hidden by a bitcast.
15140 SDValue N, bool AllowOpaques) const {
15142
15143 if (auto *C = dyn_cast<ConstantSDNode>(N))
15144 return AllowOpaques || !C->isOpaque();
15145
15147 return true;
15148
15149 // Treat a GlobalAddress supporting constant offset folding as a
15150 // constant integer.
15151 if (auto *GA = dyn_cast<GlobalAddressSDNode>(N))
15152 if (GA->getOpcode() == ISD::GlobalAddress &&
15153 TLI->isOffsetFoldingLegal(GA))
15154 return true;
15155
15156 if ((N.getOpcode() == ISD::SPLAT_VECTOR) &&
15157 isa<ConstantSDNode>(N.getOperand(0)))
15158 return true;
15159 return false;
15160}
15161
15162// Returns true if it is a constant float BuildVector or constant float.
15165 return true;
15166
15168 return true;
15169
15170 if ((N.getOpcode() == ISD::SPLAT_VECTOR) &&
15171 isa<ConstantFPSDNode>(N.getOperand(0)))
15172 return true;
15173
15174 return false;
15175}
15176
15177std::optional<bool> SelectionDAG::isBoolConstant(SDValue N) const {
15178 ConstantSDNode *Const =
15179 isConstOrConstSplat(N, false, /*AllowTruncation=*/true);
15180 if (!Const)
15181 return std::nullopt;
15182
15183 EVT VT = N.getValueType();
15184 const APInt CVal = Const->getAPIntValue().trunc(VT.getScalarSizeInBits());
15185 switch (TLI->getBooleanContents(VT)) {
15187 if (CVal.isOne())
15188 return true;
15189 if (CVal.isZero())
15190 return false;
15191 return std::nullopt;
15193 if (CVal.isAllOnes())
15194 return true;
15195 if (CVal.isZero())
15196 return false;
15197 return std::nullopt;
15199 return CVal[0];
15200 }
15201 llvm_unreachable("Unknown BooleanContent enum");
15202}
15203
15204void SelectionDAG::createOperands(SDNode *Node, ArrayRef<SDValue> Vals) {
15205 assert(!Node->OperandList && "Node already has operands");
15207 "too many operands to fit into SDNode");
15208 SDUse *Ops = OperandRecycler.allocate(
15209 ArrayRecycler<SDUse>::Capacity::get(Vals.size()), OperandAllocator);
15210
15211 bool IsDivergent = false;
15212 for (unsigned I = 0; I != Vals.size(); ++I) {
15213 Ops[I].setUser(Node);
15214 Ops[I].setInitial(Vals[I]);
15215 EVT VT = Ops[I].getValueType();
15216
15217 // Skip Chain. It does not carry divergence.
15218 if (VT != MVT::Other &&
15219 (VT != MVT::Glue || gluePropagatesDivergence(Ops[I].getNode())) &&
15220 Ops[I].getNode()->isDivergent()) {
15221 IsDivergent = true;
15222 }
15223 }
15224 Node->NumOperands = Vals.size();
15225 Node->OperandList = Ops;
15226 if (!TLI->isSDNodeAlwaysUniform(Node)) {
15227 IsDivergent |= TLI->isSDNodeSourceOfDivergence(Node, FLI, UA);
15228 Node->SDNodeBits.IsDivergent = IsDivergent;
15229 }
15230 checkForCycles(Node);
15231}
15232
15235 size_t Limit = SDNode::getMaxNumOperands();
15236 while (Vals.size() > Limit) {
15237 unsigned SliceIdx = Vals.size() - Limit;
15238 auto ExtractedTFs = ArrayRef<SDValue>(Vals).slice(SliceIdx, Limit);
15239 SDValue NewTF = getNode(ISD::TokenFactor, DL, MVT::Other, ExtractedTFs);
15240 Vals.erase(Vals.begin() + SliceIdx, Vals.end());
15241 Vals.emplace_back(NewTF);
15242 }
15243 return getNode(ISD::TokenFactor, DL, MVT::Other, Vals);
15244}
15245
15247 EVT VT, SDNodeFlags Flags) {
15248 switch (Opcode) {
15249 default:
15250 return SDValue();
15251 case ISD::ADD:
15252 case ISD::OR:
15253 case ISD::XOR:
15254 case ISD::UMAX:
15255 case ISD::MUL:
15256 case ISD::AND:
15257 case ISD::UMIN:
15258 case ISD::SMAX:
15259 case ISD::SMIN:
15261 VT);
15262 case ISD::FADD:
15263 // If flags allow, prefer positive zero since it's generally cheaper
15264 // to materialize on most targets.
15265 return getConstantFP(Flags.hasNoSignedZeros() ? 0.0 : -0.0, DL, VT);
15266 case ISD::FMUL:
15267 return getConstantFP(1.0, DL, VT);
15268 case ISD::FMINNUM:
15269 case ISD::FMAXNUM:
15270 case ISD::FMINIMUMNUM:
15271 case ISD::FMAXIMUMNUM: {
15272 // Neutral element for fminnum/fminimumnum is NaN, Inf or FLT_MAX,
15273 // depending on fast-math flags (FMF).
15274 const fltSemantics &Semantics = VT.getFltSemantics();
15275 APFloat NeutralAF = !Flags.hasNoNaNs() ? APFloat::getQNaN(Semantics) :
15276 !Flags.hasNoInfs() ? APFloat::getInf(Semantics) :
15277 APFloat::getLargest(Semantics);
15278 if (Opcode == ISD::FMAXNUM || Opcode == ISD::FMAXIMUMNUM)
15279 NeutralAF.changeSign();
15280
15281 return getConstantFP(NeutralAF, DL, VT);
15282 }
15283 case ISD::FMINIMUM:
15284 case ISD::FMAXIMUM: {
15285 // Neutral element for fminimum is Inf or FLT_MAX, depending on FMF.
15286 const fltSemantics &Semantics = VT.getFltSemantics();
15287 APFloat NeutralAF = !Flags.hasNoInfs() ? APFloat::getInf(Semantics)
15288 : APFloat::getLargest(Semantics);
15289 if (Opcode == ISD::FMAXIMUM)
15290 NeutralAF.changeSign();
15291
15292 return getConstantFP(NeutralAF, DL, VT);
15293 }
15294
15295 }
15296}
15297
15299 SDValue Acc, SDValue LHS,
15300 SDValue RHS) {
15301 EVT AccVT = Acc.getValueType();
15302 if (AccVT.isFloatingPoint()) {
15303 assert(Opc == ISD::PARTIAL_REDUCE_FMLA && "Unexpected opcode");
15304 SDValue NegRHS = getNode(ISD::FNEG, DL, RHS.getValueType(), RHS);
15305 return getNode(Opc, DL, AccVT, Acc, LHS, NegRHS);
15306 }
15309 "Unexpected opcode");
15310 SDValue NegAcc = getNegative(Acc, DL, AccVT);
15311 SDValue MLA = getNode(Opc, DL, AccVT, NegAcc, LHS, RHS);
15312 return getNegative(MLA, DL, AccVT);
15313}
15314
15315/// Helper used to make a call to a library function that has one argument of
15316/// pointer type.
15317///
15318/// Such functions include 'fegetmode', 'fesetenv' and some others, which are
15319/// used to get or set floating-point state. They have one argument of pointer
15320/// type, which points to the memory region containing bits of the
15321/// floating-point state. The value returned by such function is ignored in the
15322/// created call.
15323///
15324/// \param LibFunc Reference to library function (value of RTLIB::Libcall).
15325/// \param Ptr Pointer used to save/load state.
15326/// \param InChain Ingoing token chain.
15327/// \param Node Node being legalized
15328/// \returns Outgoing chain token.
15330 SDValue InChain, SDNode *Node) {
15331 assert(InChain.getValueType() == MVT::Other && "Expected token chain");
15332 RTLIB::LibcallImpl LibcallImpl =
15333 Libcalls->getLibcallImpl(static_cast<RTLIB::Libcall>(LibFunc));
15334 if (LibcallImpl == RTLIB::Unsupported) {
15335 getContext()->emitError(Twine("no libcall available for ") +
15336 Node->getOperationName(this));
15337 return InChain;
15338 }
15339
15341 Args.emplace_back(Ptr, Ptr.getValueType().getTypeForEVT(*getContext()));
15342 SDValue Callee =
15343 getExternalSymbol(LibcallImpl, TLI->getPointerTy(getDataLayout()));
15345 CLI.setDebugLoc(SDLoc(Node))
15346 .setChain(InChain)
15347 .setLibCallee(Libcalls->getLibcallImplCallingConv(LibcallImpl),
15348 Type::getVoidTy(*getContext()), Callee, std::move(Args));
15349 return TLI->LowerCallTo(CLI).second;
15350}
15351
15353 assert(From && To && "Invalid SDNode; empty source SDValue?");
15354 auto I = SDEI.find(From);
15355 if (I == SDEI.end())
15356 return;
15357
15358 // Use of operator[] on the DenseMap may cause an insertion, which invalidates
15359 // the iterator, hence the need to make a copy to prevent a use-after-free.
15360 NodeExtraInfo NEI = I->second;
15361 if (LLVM_LIKELY(!NEI.PCSections)) {
15362 // No deep copy required for the types of extra info set.
15363 //
15364 // FIXME: Investigate if other types of extra info also need deep copy. This
15365 // depends on the types of nodes they can be attached to: if some extra info
15366 // is only ever attached to nodes where a replacement To node is always the
15367 // node where later use and propagation of the extra info has the intended
15368 // semantics, no deep copy is required.
15369 SDEI[To] = std::move(NEI);
15370 return;
15371 }
15372
15373 const SDNode *EntrySDN = getEntryNode().getNode();
15374
15375 // We need to copy NodeExtraInfo to all _new_ nodes that are being introduced
15376 // through the replacement of From with To. Otherwise, replacements of a node
15377 // (From) with more complex nodes (To and its operands) may result in lost
15378 // extra info where the root node (To) is insignificant in further propagating
15379 // and using extra info when further lowering to MIR.
15380 //
15381 // In the first step pre-populate the visited set with the nodes reachable
15382 // from the old From node. This avoids copying NodeExtraInfo to parts of the
15383 // DAG that is not new and should be left untouched.
15384 SmallVector<const SDNode *> Leafs{From}; // Leafs reachable with VisitFrom.
15385 DenseSet<const SDNode *> FromReach; // The set of nodes reachable from From.
15386 auto VisitFrom = [&](auto &&Self, const SDNode *N, int MaxDepth) {
15387 if (MaxDepth == 0) {
15388 // Remember this node in case we need to increase MaxDepth and continue
15389 // populating FromReach from this node.
15390 Leafs.emplace_back(N);
15391 return;
15392 }
15393 if (!FromReach.insert(N).second)
15394 return;
15395 for (const SDValue &Op : N->op_values())
15396 Self(Self, Op.getNode(), MaxDepth - 1);
15397 };
15398
15399 // Copy extra info to To and all its transitive operands (that are new).
15401 auto DeepCopyTo = [&](auto &&Self, const SDNode *N) {
15402 if (FromReach.contains(N))
15403 return true;
15404 if (!Visited.insert(N).second)
15405 return true;
15406 if (EntrySDN == N)
15407 return false;
15408 for (const SDValue &Op : N->op_values()) {
15409 if (N == To && Op.getNode() == EntrySDN) {
15410 // Special case: New node's operand is the entry node; just need to
15411 // copy extra info to new node.
15412 break;
15413 }
15414 if (!Self(Self, Op.getNode()))
15415 return false;
15416 }
15417 // Copy only if entry node was not reached.
15418 SDEI[N] = std::move(NEI);
15419 return true;
15420 };
15421
15422 // We first try with a lower MaxDepth, assuming that the path to common
15423 // operands between From and To is relatively short. This significantly
15424 // improves performance in the common case. The initial MaxDepth is big
15425 // enough to avoid retry in the common case; the last MaxDepth is large
15426 // enough to avoid having to use the fallback below (and protects from
15427 // potential stack exhaustion from recursion).
15428 for (int PrevDepth = 0, MaxDepth = 16; MaxDepth <= 1024;
15429 PrevDepth = MaxDepth, MaxDepth *= 2, Visited.clear()) {
15430 // StartFrom is the previous (or initial) set of leafs reachable at the
15431 // previous maximum depth.
15433 std::swap(StartFrom, Leafs);
15434 for (const SDNode *N : StartFrom)
15435 VisitFrom(VisitFrom, N, MaxDepth - PrevDepth);
15436 if (LLVM_LIKELY(DeepCopyTo(DeepCopyTo, To)))
15437 return;
15438 // This should happen very rarely (reached the entry node).
15439 LLVM_DEBUG(dbgs() << __func__ << ": MaxDepth=" << MaxDepth << " too low\n");
15440 assert(!Leafs.empty());
15441 }
15442
15443 // This should not happen - but if it did, that means the subgraph reachable
15444 // from From has depth greater or equal to maximum MaxDepth, and VisitFrom()
15445 // could not visit all reachable common operands. Consequently, we were able
15446 // to reach the entry node.
15447 errs() << "warning: incomplete propagation of SelectionDAG::NodeExtraInfo\n";
15448 assert(false && "From subgraph too complex - increase max. MaxDepth?");
15449 // Best-effort fallback if assertions disabled.
15450 SDEI[To] = std::move(NEI);
15451}
15452
15454 assert(VT.isVector() && "Can only unroll vector types!");
15455 if (VT.isFixedLengthVector())
15456 return VT.getVectorNumElements();
15457
15458 const MachineFunction &MF = getMachineFunction();
15459 const Function &F = MF.getFunction();
15460
15461 APInt MaxVScale = getVScaleRange(&F, sizeof(unsigned) * 8).getUnsignedMax();
15462 if (MaxVScale.ugt(VScaleUnrollLimit))
15463 return 0;
15464
15465 bool Overflow;
15466 APInt MinNElts(sizeof(unsigned) * 8, VT.getVectorMinNumElements());
15467 APInt MaxNElts = MinNElts.umul_ov(MaxVScale, Overflow);
15468 if (Overflow)
15469 return 0;
15470
15471 return MaxNElts.getZExtValue();
15472}
15473
15475 ArrayRef<SDValue> Scalars) {
15476 assert(Scalars.size() == getMaxRuntimeNumElements(VT) &&
15477 "Element count mismatch!");
15478 if (VT.isFixedLengthVector())
15479 return getBuildVector(VT, DL, Scalars);
15480
15481 SDValue Vec = getPOISON(VT);
15482 // Iterate in reverse so result remains poison until we encounter a lane that
15483 // exists, after which all lower-numbered lanes must also exist.
15484 for (unsigned IdxVal : reverse(seq(Scalars.size())))
15485 Vec = getInsertVectorElt(DL, Vec, Scalars[IdxVal], IdxVal);
15486
15487 return Vec;
15488}
15489
15490#ifndef NDEBUG
15491static void checkForCyclesHelper(const SDNode *N,
15494 const llvm::SelectionDAG *DAG) {
15495 // If this node has already been checked, don't check it again.
15496 if (Checked.count(N))
15497 return;
15498
15499 // If a node has already been visited on this depth-first walk, reject it as
15500 // a cycle.
15501 if (!Visited.insert(N).second) {
15502 errs() << "Detected cycle in SelectionDAG\n";
15503 dbgs() << "Offending node:\n";
15504 N->dumprFull(DAG); dbgs() << "\n";
15505 abort();
15506 }
15507
15508 for (const SDValue &Op : N->op_values())
15509 checkForCyclesHelper(Op.getNode(), Visited, Checked, DAG);
15510
15511 Checked.insert(N);
15512 Visited.erase(N);
15513}
15514#endif
15515
15517 const llvm::SelectionDAG *DAG,
15518 bool force) {
15519#ifndef NDEBUG
15520 bool check = force;
15521#ifdef EXPENSIVE_CHECKS
15522 check = true;
15523#endif // EXPENSIVE_CHECKS
15524 if (check) {
15525 assert(N && "Checking nonexistent SDNode");
15528 checkForCyclesHelper(N, visited, checked, DAG);
15529 }
15530#endif // !NDEBUG
15531}
15532
15533void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) {
15534 checkForCycles(DAG->getRoot().getNode(), DAG, force);
15535}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
unsigned Imm
unsigned uint64_t
static bool isConstant(const MachineInstr &MI)
constexpr LLT S1
This file declares a class to represent arbitrary precision floating point values and provide a varie...
This file implements a class to represent arbitrary precision integral constant values and operations...
This file implements the APSInt class, which is a simple class that represents an arbitrary sized int...
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Function Alias Analysis Results
#define X(NUM, ENUM, NAME)
Definition ELF.h:857
This file implements the BitVector class.
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static std::optional< bool > isBigEndian(const SmallDenseMap< int64_t, int64_t, 8 > &MemOffset2Idx, int64_t LowestIdx)
Given a map from byte offsets in memory to indices in a load/store, determine if that map corresponds...
#define __asan_unpoison_memory_region(p, size)
Definition Compiler.h:617
#define LLVM_LIKELY(EXPR)
Definition Compiler.h:351
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file defines the DenseSet and SmallDenseSet classes.
This file contains constants used for implementing Dwarf debug support.
This file defines a hash set that can be used to remove duplication of nodes in a graph.
static MaybeAlign getAlign(Value *Ptr)
iv users
Definition IVUsers.cpp:48
std::pair< Instruction::BinaryOps, Value * > OffsetOp
Find all possible pairs (BinOp, RHS) that BinOp V, RHS can be simplified.
static constexpr Value * getValue(Ty &ValueOrUse)
const size_t AbstractManglingParser< Derived, Alloc >::NumOps
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
static Register getMemsetValue(Register Val, LLT Ty, MachineIRBuilder &MIB)
static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT, AssumptionCache *AC)
Definition Lint.cpp:540
static Align getPrefTypeAlign(EVT VT, SelectionDAG &DAG)
static bool isConstantSplatVector(SDValue N, APInt &SplatValue, unsigned MinSizeInBits)
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define G(x, y, z)
Definition MD5.cpp:55
This file declares the MachineConstantPool class which is an abstract constant pool to keep track of ...
Register const TargetRegisterInfo * TRI
This file provides utility analysis objects describing memory locations.
This file contains the declarations for metadata subclasses.
#define T
static MCRegister getReg(const MCDisassembler *D, unsigned RC, unsigned RegNo)
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
#define P(N)
PowerPC Reduce CR logical Operation
const SmallVectorImpl< MachineOperand > & Cond
Remove Loads Into Fake Uses
static bool isValid(const char C)
Returns true if C is a valid mangled character: <0-9a-zA-Z_>.
Contains matchers for matching SelectionDAG nodes and values.
SI Fold Operands
const char * Msg
This file contains some templates that are useful if you are working with the STL at all.
static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow)
static bool shouldLowerMemFuncForSize(const MachineFunction &MF, SelectionDAG &DAG)
static SDValue getFixedOrScalableQuantity(SelectionDAG &DAG, const SDLoc &DL, EVT VT, Ty Quantity)
static std::pair< SDValue, SDValue > getRuntimeCallSDValueHelper(SDValue Chain, const SDLoc &dl, TargetLowering::ArgListTy &&Args, const CallInst *CI, RTLIB::Libcall Call, SelectionDAG *DAG, const TargetLowering *TLI)
static SDValue getMemsetStores(SelectionDAG &DAG, const SDLoc &dl, SDValue Chain, SDValue Dst, SDValue Src, uint64_t Size, Align Alignment, bool isVol, bool AlwaysInline, MachinePointerInfo DstPtrInfo, const AAMDNodes &AAInfo)
Lower the call to 'memset' intrinsic function into a series of store operations.
static std::optional< APInt > FoldValueWithUndef(unsigned Opcode, const APInt &C1, bool IsUndef1, const APInt &C2, bool IsUndef2)
static SDValue FoldSTEP_VECTOR(const SDLoc &DL, EVT VT, SDValue Step, SelectionDAG &DAG)
static cl::opt< int > VScaleUnrollLimit("vscale-unroll-limit", cl::desc("Maximum vscale for which vector unrolling is allowed."), cl::Hidden, cl::init(64))
static SDValue getMemsetStringVal(EVT VT, const SDLoc &dl, SelectionDAG &DAG, const TargetLowering &TLI, const ConstantDataArraySlice &Slice)
getMemsetStringVal - Similar to getMemsetValue.
static cl::opt< bool > EnableMemCpyDAGOpt("enable-memcpy-dag-opt", cl::Hidden, cl::init(true), cl::desc("Gang up loads and stores generated by inlining of memcpy"))
static bool haveNoCommonBitsSetCommutative(SDValue A, SDValue B)
static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N)
Serialize a node the way SDNodes were uniqued before SDNodeKey, to cross-check the typed comparison a...
static void commuteShuffle(SDValue &N1, SDValue &N2, MutableArrayRef< int > M)
Swaps the values of N1 and N2.
static bool isMemSrcFromConstant(SDValue Src, ConstantDataArraySlice &Slice)
Returns true if memcpy source is constant data.
static ISD::CondCode getSetCCInverseImpl(ISD::CondCode Op, bool isIntegerLike)
static bool doNotCSE(SDNode *N)
doNotCSE - Return true if CSE should not be performed for this node.
static cl::opt< int > MaxLdStGlue("ldstmemcpy-glue-max", cl::desc("Number limit for gluing ld/st of memcpy."), cl::Hidden, cl::init(0))
static APInt getIntegerIdentity(unsigned Opcode, unsigned BitWidth)
static SDValue getMemIntrinsicSize(SelectionDAG &DAG, const SDLoc &dl, SDValue Size, unsigned DstAS, unsigned SrcAS)
The length of a memory intrinsic (e.g.
static void checkAddrSpaceIsValidForLibcall(const TargetLowering *TLI, const DataLayout &DL, unsigned AS)
static SDValue foldCONCAT_VECTORS(const SDLoc &DL, EVT VT, ArrayRef< SDValue > Ops, SelectionDAG &DAG)
Try to simplify vector concatenation to an input value, undef, or build vector.
static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info, SelectionDAG &DAG, SDValue Ptr, int64_t Offset=0)
InferPointerInfo - If the specified ptr/offset is a frame index, infer a MachinePointerInfo record fr...
static bool isInTailCallPositionWrapper(const CallInst *CI, const SelectionDAG *SelDAG, bool AllowReturnsFirstArg)
static bool keyMatches(const SDNodeKey &Key, const SDNode &N)
static bool areNonVolatileConsecutiveLoadsOrStores(LSBaseSDNode *LS, LSBaseSDNode *Base, unsigned Bytes, int Dist, const SelectionDAG &DAG)
static bool gluePropagatesDivergence(const SDNode *Node)
Return true if a glue output should propagate divergence information.
static void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N, unsigned Opc)
If this is an SDNode with special info, add this info to the NodeID data.
static void NewSDValueDbgMsg(SDValue V, StringRef Msg, SelectionDAG *G)
static SDVTList makeVTList(const EVT *VTs, unsigned NumVTs)
makeVTList - Return an instance of the SDVTList struct initialized with the specified members.
static void checkForCyclesHelper(const SDNode *N, SmallPtrSetImpl< const SDNode * > &Visited, SmallPtrSetImpl< const SDNode * > &Checked, const llvm::SelectionDAG *DAG)
static void chainLoadsAndStoresForMemcpy(SelectionDAG &DAG, const SDLoc &dl, SmallVector< SDValue, 32 > &OutChains, unsigned From, unsigned To, SmallVector< SDValue, 16 > &OutLoadChains, SmallVector< SDValue, 16 > &OutStoreChains)
static int isSignedOp(ISD::CondCode Opcode)
For an integer comparison, return 1 if the comparison is a signed operation and 2 if the result is an...
static std::optional< APInt > FoldValue(unsigned Opcode, const APInt &C1, const APInt &C2)
static SDValue FoldBUILD_VECTOR(const SDLoc &DL, EVT VT, ArrayRef< SDValue > Ops, SelectionDAG &DAG)
static cl::opt< unsigned > MaxSteps("has-predecessor-max-steps", cl::Hidden, cl::init(8192), cl::desc("DAG combiner limit number of steps when searching DAG " "for predecessor nodes"))
static APInt getDemandAllEltsMask(SDValue V)
Construct a DemandedElts mask which demands all elements of V.
static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl, SDValue Chain, SDValue Dst, SDValue Src, uint64_t Size, Align DstAlign, Align SrcAlign, bool isVol, bool AlwaysInline, MachinePointerInfo DstPtrInfo, MachinePointerInfo SrcPtrInfo, const AAMDNodes &AAInfo, BatchAAResults *BatchAA, const MDNode *DstMemCacheHint, const MDNode *SrcMemCacheHint)
static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl, SDValue Chain, SDValue Dst, SDValue Src, uint64_t Size, Align DstAlign, Align SrcAlign, bool isVol, bool AlwaysInline, MachinePointerInfo DstPtrInfo, MachinePointerInfo SrcPtrInfo, const AAMDNodes &AAInfo)
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
#define LLVM_DEBUG(...)
Definition Debug.h:119
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
This file describes how to lower LLVM code to machine code.
static void removeOperands(MachineInstr &MI, unsigned i)
static OverflowResult mapOverflowResult(ConstantRange::OverflowResult OR)
Convert ConstantRange OverflowResult into ValueTracking OverflowResult.
static int Lookup(ArrayRef< TableEntry > Table, unsigned Opcode)
static unsigned getSize(unsigned Kind)
static const fltSemantics & IEEEsingle()
Definition APFloat.h:304
cmpResult
IEEE-754R 5.11: Floating Point Comparison Relations.
Definition APFloat.h:351
static constexpr roundingMode rmTowardZero
Definition APFloat.h:365
static const fltSemantics & BFloat()
Definition APFloat.h:303
static const fltSemantics & IEEEquad()
Definition APFloat.h:306
static const fltSemantics & IEEEdouble()
Definition APFloat.h:305
static constexpr roundingMode rmTowardNegative
Definition APFloat.h:364
static constexpr roundingMode rmNearestTiesToEven
Definition APFloat.h:361
static constexpr roundingMode rmTowardPositive
Definition APFloat.h:363
static const fltSemantics & IEEEhalf()
Definition APFloat.h:302
opStatus
IEEE-754R 7: Default exception handling.
Definition APFloat.h:377
static APFloat getQNaN(const fltSemantics &Sem, bool Negative=false, const APInt *payload=nullptr)
Factory for QNaN values.
Definition APFloat.h:1224
opStatus divide(const APFloat &RHS, roundingMode RM)
Definition APFloat.h:1312
void copySign(const APFloat &RHS)
Definition APFloat.h:1406
LLVM_ABI opStatus convert(const fltSemantics &ToSemantics, roundingMode RM, bool *losesInfo)
Definition APFloat.cpp:6034
opStatus subtract(const APFloat &RHS, roundingMode RM)
Definition APFloat.h:1294
bool isNegative() const
Definition APFloat.h:1583
opStatus add(const APFloat &RHS, roundingMode RM)
Definition APFloat.h:1285
bool isFinite() const
Definition APFloat.h:1588
opStatus convertFromAPInt(const APInt &Input, bool IsSigned, roundingMode RM)
Definition APFloat.h:1451
opStatus multiply(const APFloat &RHS, roundingMode RM)
Definition APFloat.h:1303
bool isZero() const
Definition APFloat.h:1579
LLVM_READONLY bool isOne() const
Definition APFloat.h:1661
bool isLargest() const
Definition APFloat.h:1599
static APFloat getLargest(const fltSemantics &Sem, bool Negative=false)
Returns the largest finite number in the given semantics.
Definition APFloat.h:1242
opStatus convertToInteger(MutableArrayRef< integerPart > Input, unsigned int Width, bool IsSigned, roundingMode RM, bool *IsExact) const
Definition APFloat.h:1436
static APFloat getInf(const fltSemantics &Sem, bool Negative=false)
Factory for Positive and Negative Infinity.
Definition APFloat.h:1202
opStatus mod(const APFloat &RHS)
Definition APFloat.h:1330
bool isPosZero() const
Definition APFloat.h:1594
bool isNegZero() const
Definition APFloat.h:1595
void changeSign()
Definition APFloat.h:1401
static APFloat getNaN(const fltSemantics &Sem, bool Negative=false, uint64_t payload=0)
Factory for NaN values.
Definition APFloat.h:1213
bool isInfinity() const
Definition APFloat.h:1580
Class for arbitrary precision integers.
Definition APInt.h:78
LLVM_ABI APInt umul_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:2009
LLVM_ABI APInt usub_sat(const APInt &RHS) const
Definition APInt.cpp:2093
LLVM_ABI APInt udiv(const APInt &RHS) const
Unsigned division operation.
Definition APInt.cpp:1602
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
Definition APInt.h:230
void clearBit(unsigned BitPosition)
Set a given bit to 0.
Definition APInt.h:1426
LLVM_ABI APInt zext(unsigned width) const
Zero extend to a new width.
Definition APInt.cpp:1057
static APInt getSignMask(unsigned BitWidth)
Get the SignMask for a specific bit width.
Definition APInt.h:225
bool isMinSignedValue() const
Determine if this is the smallest signed value.
Definition APInt.h:419
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1560
unsigned popcount() const
Count the number of bits set.
Definition APInt.h:1690
LLVM_ABI APInt zextOrTrunc(unsigned width) const
Zero extend or truncate to width.
Definition APInt.cpp:1078
unsigned getActiveBits() const
Compute the number of active bits in the value.
Definition APInt.h:1532
LLVM_ABI APInt trunc(unsigned width) const
Truncate to new width.
Definition APInt.cpp:970
void setBit(unsigned BitPosition)
Set the given bit to 1 whose position is given as "bitPosition".
Definition APInt.h:1350
APInt abs() const
Get the absolute value.
Definition APInt.h:1815
LLVM_ABI APInt sadd_sat(const APInt &RHS) const
Definition APInt.cpp:2064
bool isAllOnes() const
Determine if all bits are set. This is true for zero-width values.
Definition APInt.h:367
bool ugt(const APInt &RHS) const
Unsigned greater than comparison.
Definition APInt.h:1186
static APInt getBitsSet(unsigned numBits, unsigned loBit, unsigned hiBit)
Get a value with a block of bits set.
Definition APInt.h:254
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition APInt.h:376
LLVM_ABI APInt urem(const APInt &RHS) const
Unsigned remainder operation.
Definition APInt.cpp:1695
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1508
bool ult(const APInt &RHS) const
Unsigned less than comparison.
Definition APInt.h:1115
static APInt getSignedMaxValue(unsigned numBits)
Gets maximum signed value of APInt for a specific bit width.
Definition APInt.h:205
bool isNegative() const
Determine sign of this APInt.
Definition APInt.h:325
LLVM_ABI APInt sdiv(const APInt &RHS) const
Signed division function for APInt.
Definition APInt.cpp:1673
LLVM_ABI APInt rotr(unsigned rotateAmt) const
Rotate right by rotateAmt.
Definition APInt.cpp:1199
LLVM_ABI APInt reverseBits() const
Definition APInt.cpp:786
void ashrInPlace(unsigned ShiftAmt)
Arithmetic right-shift this APInt by ShiftAmt in place.
Definition APInt.h:836
bool sle(const APInt &RHS) const
Signed less or equal comparison.
Definition APInt.h:1170
unsigned countr_zero() const
Count the number of trailing zero bits.
Definition APInt.h:1659
unsigned getNumSignBits() const
Computes the number of leading bits of this APInt that are equal to its sign bit.
Definition APInt.h:1648
unsigned countl_zero() const
The APInt version of std::countl_zero.
Definition APInt.h:1618
static LLVM_ABI APInt getSplat(unsigned NewLen, const APInt &V)
Return a value containing V broadcasted over NewLen bits.
Definition APInt.cpp:648
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
Definition APInt.h:215
LLVM_ABI APInt sshl_sat(const APInt &RHS) const
Definition APInt.cpp:2124
LLVM_ABI APInt ushl_sat(const APInt &RHS) const
Definition APInt.cpp:2138
LLVM_ABI APInt sextOrTrunc(unsigned width) const
Sign extend or truncate to width.
Definition APInt.cpp:1086
static bool isSameValue(const APInt &I1, const APInt &I2, bool SignedCompare=false)
Determine if two APInts have the same value, after zero-extending or sign-extending (if SignedCompare...
Definition APInt.h:550
LLVM_ABI APInt rotl(unsigned rotateAmt) const
Rotate left by rotateAmt.
Definition APInt.cpp:1186
LLVM_ABI void insertBits(const APInt &SubBits, unsigned bitPosition)
Insert the bits from a smaller APInt starting at bitPosition.
Definition APInt.cpp:393
unsigned logBase2() const
Definition APInt.h:1781
LLVM_ABI APInt uadd_sat(const APInt &RHS) const
Definition APInt.cpp:2074
APInt ashr(unsigned ShiftAmt) const
Arithmetic right-shift function.
Definition APInt.h:829
LLVM_ABI APInt multiplicativeInverse() const
Definition APInt.cpp:1303
LLVM_ABI APInt srem(const APInt &RHS) const
Function for signed remainder operation.
Definition APInt.cpp:1774
bool isNonNegative() const
Determine if this APInt Value is non-negative (>= 0)
Definition APInt.h:330
bool ule(const APInt &RHS) const
Unsigned less or equal comparison.
Definition APInt.h:1154
LLVM_ABI APInt sext(unsigned width) const
Sign extend to a new width.
Definition APInt.cpp:1030
void setBits(unsigned loBit, unsigned hiBit)
Set the bits from loBit (inclusive) to hiBit (exclusive) to 1.
Definition APInt.h:1387
APInt shl(unsigned shiftAmt) const
Left-shift function.
Definition APInt.h:875
LLVM_ABI APInt byteSwap() const
Definition APInt.cpp:764
bool isSubsetOf(const APInt &RHS) const
This operation checks that all bits set in this APInt are also set in RHS.
Definition APInt.h:1261
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
Definition APInt.h:436
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Constructs an APInt value that has the bottom loBitsSet bits set.
Definition APInt.h:302
void clearBits(unsigned LoBit, unsigned HiBit)
Clear the bits from LoBit (inclusive) to HiBit (exclusive) to 0.
Definition APInt.h:1437
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition APInt.h:196
LLVM_ABI APInt extractBits(unsigned numBits, unsigned bitPosition) const
Return an APInt with the extracted bits [bitPosition,bitPosition+numBits).
Definition APInt.cpp:478
bool sge(const APInt &RHS) const
Signed greater or equal comparison.
Definition APInt.h:1241
bool isOne() const
Determine if this is a value of 1.
Definition APInt.h:385
static APInt getBitsSetFrom(unsigned numBits, unsigned loBit)
Constructs an APInt value that has a contiguous range of bits set.
Definition APInt.h:282
static APInt getOneBitSet(unsigned numBits, unsigned BitNo)
Return an APInt with exactly one bit set in the result.
Definition APInt.h:235
void lshrInPlace(unsigned ShiftAmt)
Logical right-shift this APInt by ShiftAmt in place.
Definition APInt.h:860
APInt lshr(unsigned shiftAmt) const
Logical right-shift function.
Definition APInt.h:853
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
Definition APInt.h:1225
LLVM_ABI APInt ssub_sat(const APInt &RHS) const
Definition APInt.cpp:2083
An arbitrary precision integer that knows its signedness.
Definition APSInt.h:24
unsigned getSrcAddressSpace() const
unsigned getDestAddressSpace() const
static Capacity get(size_t N)
Get the capacity of an array that can hold at least N elements.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
Get the array size.
Definition ArrayRef.h:141
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
static LLVM_ABI BaseIndexOffset match(const SDNode *N, const SelectionDAG &DAG)
Parses tree in N for base, index, offset addresses.
This class is a wrapper over an AAResults, and it is intended to be used only when there are no IR ch...
bool pointsToConstantMemory(const MemoryLocation &Loc, bool OrLocal=false)
BitVector & reset()
Reset all bits in the bitvector.
Definition BitVector.h:409
void resize(unsigned N, bool t=false)
Grow or shrink the bitvector.
Definition BitVector.h:355
void clear()
Removes all bits from the bitvector.
Definition BitVector.h:349
BitVector & set()
Set all bits in the bitvector.
Definition BitVector.h:366
bool none() const
Returns true if none of the bits are set.
Definition BitVector.h:207
size_type size() const
Returns the number of bits in this bitvector.
Definition BitVector.h:178
const BlockAddress * getBlockAddress() const
The address of a basic block.
Definition Constants.h:1088
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
A "pseudo-class" with methods for operating on BUILD_VECTORs.
LLVM_ABI bool getConstantRawBits(bool IsLittleEndian, unsigned DstEltSizeInBits, SmallVectorImpl< APInt > &RawBitElements, BitVector &UndefElements) const
Extract the raw bit data from a build vector of Undef, Constant or ConstantFP node elements.
static LLVM_ABI void recastRawBits(bool IsLittleEndian, unsigned DstEltSizeInBits, SmallVectorImpl< APInt > &DstBitElements, ArrayRef< APInt > SrcBitElements, BitVector &DstUndefElements, const BitVector &SrcUndefElements)
Recast bit data SrcBitElements to DstEltSizeInBits wide elements.
LLVM_ABI bool getRepeatedSequence(const APInt &DemandedElts, SmallVectorImpl< SDValue > &Sequence, BitVector *UndefElements=nullptr) const
Find the shortest repeating sequence of values in the build vector.
LLVM_ABI ConstantFPSDNode * getConstantFPSplatNode(const APInt &DemandedElts, BitVector *UndefElements=nullptr) const
Returns the demanded splatted constant FP or null if this is not a constant FP splat.
LLVM_ABI SDValue getSplatValue(const APInt &DemandedElts, BitVector *UndefElements=nullptr) const
Returns the demanded splatted value or a null value if this is not a splat.
LLVM_ABI bool isConstantSplat(APInt &SplatValue, APInt &SplatUndef, unsigned &SplatBitSize, bool &HasAnyUndefs, unsigned MinSplatBits=0, bool isBigEndian=false) const
Check if this is a constant splat, and if so, find the smallest element size that splats the vector.
LLVM_ABI ConstantSDNode * getConstantSplatNode(const APInt &DemandedElts, BitVector *UndefElements=nullptr) const
Returns the demanded splatted constant or null if this is not a constant splat.
LLVM_ABI int32_t getConstantFPSplatPow2ToLog2Int(BitVector *UndefElements, uint32_t BitWidth) const
If this is a constant FP splat and the splatted constant FP is an exact power or 2,...
LLVM_ABI std::optional< std::pair< APInt, APInt > > isArithmeticSequence() const
If this BuildVector is constant and represents an arithmetic sequence "<a, a+n, a+2n,...
LLVM_ABI bool isConstant() const
This class represents a function call, abstracting a target machine's calling convention.
bool isTailCall() const
static LLVM_ABI bool isValueValidForType(EVT VT, const APFloat &Val)
const APFloat & getValueAPF() const
bool isExactlyValue(double V) const
We don't rely on operator== working on double values, as it returns true for things that are clearly ...
ConstantFP - Floating Point Values [float, double].
Definition Constants.h:420
const APFloat & getValue() const
Definition Constants.h:464
This is the shared class of boolean and integer constants.
Definition Constants.h:87
unsigned getBitWidth() const
getBitWidth - Return the scalar bitwidth of this constant.
Definition Constants.h:162
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition Constants.h:159
MachineConstantPoolValue * getMachineCPVal() const
const Constant * getConstVal() const
LLVM_ABI Type * getType() const
This class represents a range of values.
PreferredRangeType
If represented precisely, the result of some range operations may consist of multiple disjoint ranges...
const APInt * getSingleElement() const
If this set contains a single element, return it, otherwise return null.
static LLVM_ABI ConstantRange fromKnownBits(const KnownBits &Known, bool IsSigned)
Initialize a range based on a known bits constraint.
LLVM_ABI OverflowResult unsignedSubMayOverflow(const ConstantRange &Other) const
Return whether unsigned sub of the two ranges always/never overflows.
LLVM_ABI OverflowResult unsignedAddMayOverflow(const ConstantRange &Other) const
Return whether unsigned add of the two ranges always/never overflows.
LLVM_ABI KnownBits toKnownBits() const
Return known bits for values in this range.
LLVM_ABI ConstantRange zeroExtend(uint32_t BitWidth) const
Return a new range in the specified integer type, which must be strictly larger than the current type...
LLVM_ABI APInt getSignedMin() const
Return the smallest signed value contained in the ConstantRange.
LLVM_ABI OverflowResult unsignedMulMayOverflow(const ConstantRange &Other) const
Return whether unsigned mul of the two ranges always/never overflows.
LLVM_ABI ConstantRange signExtend(uint32_t BitWidth) const
Return a new range in the specified integer type, which must be strictly larger than the current type...
LLVM_ABI ConstantRange multiply(const ConstantRange &Other, unsigned NoWrapKind=0) const
Return a new range representing the possible values resulting from a multiplication of a value in thi...
LLVM_ABI bool contains(const APInt &Val) const
Return true if the specified value is in the set.
LLVM_ABI APInt getUnsignedMax() const
Return the largest unsigned value contained in the ConstantRange.
LLVM_ABI ConstantRange intersectWith(const ConstantRange &CR, PreferredRangeType Type=Smallest) const
Return the range that results from the intersection of this range with another range.
LLVM_ABI APInt getSignedMax() const
Return the largest signed value contained in the ConstantRange.
OverflowResult
Represents whether an operation on the given constant range is known to always or never overflow.
@ AlwaysOverflowsHigh
Always overflows in the direction of signed/unsigned max value.
@ AlwaysOverflowsLow
Always overflows in the direction of signed/unsigned min value.
@ MayOverflow
May or may not overflow.
uint32_t getBitWidth() const
Get the bit width of this ConstantRange.
LLVM_ABI OverflowResult signedSubMayOverflow(const ConstantRange &Other) const
Return whether signed sub of the two ranges always/never overflows.
uint64_t getZExtValue() const
const APInt & getAPIntValue() const
This is an important base class in LLVM.
Definition Constant.h:43
LLVM_ABI Constant * getSplatValue(bool AllowPoison=false) const
If all elements of the vector constant have the same value, return that value.
LLVM_ABI Constant * getAggregateElement(unsigned Elt) const
For aggregates (struct/array/vector) return the constant that corresponds to the specified element if...
DWARF expression.
static LLVM_ABI ExtOps getExtOps(unsigned FromSize, unsigned ToSize, bool Signed)
Returns the ops for a zero- or sign-extension in a DIExpression.
static LLVM_ABI void appendOffset(SmallVectorImpl< uint64_t > &Ops, int64_t Offset)
Append Ops with operations to apply the Offset.
static LLVM_ABI DIExpression * appendOpsToArg(const DIExpression *Expr, ArrayRef< uint64_t > Ops, unsigned ArgNo, bool StackValue=false)
Create a copy of Expr by appending the given list of Ops to each instance of the operand DW_OP_LLVM_a...
static LLVM_ABI const DIExpression * convertToVariadicExpression(const DIExpression *Expr)
If Expr is a non-variadic expression (i.e.
static LLVM_ABI std::optional< DIExpression * > createFragmentExpression(const DIExpression *Expr, unsigned OffsetInBits, unsigned SizeInBits)
Create a DIExpression to describe one part of an aggregate variable that is fragmented across multipl...
Base class for variables.
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
bool isLittleEndian() const
Layout endianness...
Definition DataLayout.h:217
LLVM_ABI IntegerType * getIntPtrType(LLVMContext &C, unsigned AddressSpace=0) const
Returns an integer type with size at least as big as that of a pointer in the given address space.
LLVM_ABI Align getABITypeAlign(Type *Ty) const
Returns the minimum ABI-required alignment for the specified type.
LLVM_ABI unsigned getPointerTypeSizeInBits(Type *) const
The pointer representation size in bits for this type.
LLVM_ABI Align getPrefTypeAlign(Type *Ty) const
Returns the preferred stack/global alignment for the specified type.
A debug info location.
Definition DebugLoc.h:126
Implements a dense probed hash-table based set.
Definition DenseSet.h:281
static constexpr ElementCount getFixed(ScalarTy MinVal)
Definition TypeSize.h:305
constexpr bool isScalar() const
Exactly one element.
Definition TypeSize.h:316
const char * getSymbol() const
Insertion token: a failed lookup fills it in, the matching insert consumes it.
Definition FoldingSet.h:284
This class is used to gather all the unique data bits of a node.
Definition FoldingSet.h:162
Data structure describing the variable locations in a function.
bool hasMinSize() const
Optimize this function for minimum size (-Oz).
Definition Function.h:696
AttributeList getAttributes() const
Return the attribute list for this Function.
Definition Function.h:329
LLVM_ABI unsigned getAddressSpace() const
const GlobalValue * getGlobal() const
bool isThreadLocal() const
If the value is "Thread Local", its value isn't shared by the threads.
unsigned getAddressSpace() const
Module * getParent()
Get the module that this global value is contained inside of...
PointerType * getType() const
Global values are always pointers.
This class is used to form a handle around another node that is persistent and is updated across invo...
const SDValue & getValue() const
static LLVM_ABI bool compare(const APInt &LHS, const APInt &RHS, ICmpInst::Predicate Pred)
Return result of LHS Pred RHS comparison.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
LLVM_ABI void emitError(const Instruction *I, const Twine &ErrorStr)
emitError - Emit an error message to the currently installed error handler with optional location inf...
Base class for LoadSDNode and StoreSDNode.
Tracks which library functions to use for a particular subtarget or function.
CallingConv::ID getLibcallImplCallingConv(RTLIB::LibcallImpl Call) const
Get the CallingConv that should be used for the specified libcall.
RTLIB::LibcallImpl getLibcallImpl(RTLIB::Libcall Call) const
Return the lowering's selection of implementation call for Call.
This SDNode is used for LIFETIME_START/LIFETIME_END values.
This class is used to represent ISD::LOAD nodes.
static LocationSize precise(uint64_t Value)
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition MCSymbol.h:42
Metadata node.
Definition Metadata.h:1081
const MDOperand & getOperand(unsigned I) const
Definition Metadata.h:1437
Machine Value Type.
SimpleValueType SimpleTy
bool bitsLT(MVT VT) const
Return true if this has less bits than VT.
static MVT getIntegerVT(unsigned BitWidth)
Abstract base class for all machine specific constantpool value subclasses.
virtual void addSelectionDAGCSEId(FoldingSetNodeID &ID)=0
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted.
LLVM_ABI int CreateStackObject(uint64_t Size, Align Alignment, bool isSpillSlot, const AllocaInst *Alloca=nullptr, uint8_t ID=0)
Create a new statically sized stack object, returning a nonnegative identifier to represent it.
Align getObjectAlign(int ObjectIdx) const
Return the alignment of the specified stack object.
bool isFixedObjectIndex(int ObjectIdx) const
Returns true if the specified index corresponds to a fixed stack object.
void setObjectAlignment(int ObjectIdx, Align Alignment)
setObjectAlignment - Change the alignment of the specified stack object.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
Function & getFunction()
Return the LLVM function that this machine code represents.
const TargetMachine & getTarget() const
getTarget - Return the target machine this machine code is compiled with
A description of a memory reference used in the backend.
const MDNode * getRanges() const
Return the range tag for the memory reference.
Flags
Flags values. These may be or'd together.
@ MOVolatile
The memory access is volatile.
@ MODereferenceable
The memory access is dereferenceable (i.e., doesn't trap).
@ MOLoad
The memory access reads data.
@ MOInvariant
The memory access always returns the same value (or traps).
@ MOStore
The memory access writes data.
const MachinePointerInfo & getPointerInfo() const
Flags getFlags() const
Return the raw flags of the source value,.
An SDNode that represents everything that will be needed to construct a MachineInstr.
This class is used to represent an MGATHER node.
This class is used to represent an MLOAD node.
This class is used to represent an MSTORE node.
This SDNode is used for target intrinsics that touch memory and need an associated MachineMemOperand.
This is an abstract virtual class for memory operations.
size_t getNumMemOperands() const
Return the number of memory operands.
LLVM_ABI MemSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl, SDVTList VTs, EVT memvt, PointerUnion< MachineMemOperand *, MachineMemOperand ** > memrefs)
Constructor that supports single or multiple MMOs.
PointerUnion< MachineMemOperand *, MachineMemOperand ** > MemRefs
Memory reference information.
MachineMemOperand * getMemOperand() const
Return the unique MachineMemOperand object describing the memory reference performed by operation.
const MachinePointerInfo & getPointerInfo() const
ArrayRef< MachineMemOperand * > memoperands() const
Return the memory operands for this node.
unsigned getRawSubclassData() const
Return the SubclassData value, without HasDebugValue.
EVT getMemoryVT() const
Return the type of the in-memory value.
Representation for a specific memory location.
Root of the metadata hierarchy.
Definition Metadata.h:64
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
Function * getFunction(StringRef Name) const
Look up the specified function in the module symbol table.
Definition Module.cpp:235
Represent a mutable reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:294
Class to represent pointers.
static PointerType * getUnqual(LLVMContext &C)
This constructs an opaque pointer to an object in the default address space (address space zero).
static LLVM_ABI PointerType * get(LLVMContext &C, unsigned AddressSpace)
This constructs an opaque pointer to an object in a numbered address space.
Definition Type.cpp:887
unsigned getAddressSpace() const
Return the address space of the Pointer type.
A discriminated union of two or more pointer types, with the discriminator in the low bits of the poi...
bool isNull() const
Test if the pointer held in the union is null, regardless of which type it is.
Analysis providing profile information.
void Deallocate(SubClass *E)
Deallocate - Release storage for the pointed-to object.
Wrapper class representing virtual and physical registers.
Definition Register.h:20
Keeps track of dbg_value information through SDISel.
LLVM_ABI void add(SDDbgValue *V, bool isParameter)
LLVM_ABI void erase(const SDNode *Node)
Invalidate all DbgValues attached to the node and remove it from the Node-to-DbgValues map.
Holds the information from a dbg_label node through SDISel.
Holds the information for a single machine location through SDISel; either an SDNode,...
static SDDbgOperand fromNode(SDNode *Node, unsigned ResNo)
static SDDbgOperand fromFrameIdx(unsigned FrameIdx)
static SDDbgOperand fromVReg(Register VReg)
static SDDbgOperand fromConst(const Value *Const)
@ SDNODE
Value is the result of an expression.
Holds the information from a dbg_value node through SDISel.
Wrapper class for IR location info (IR ordering and DebugLoc) to be passed into SDNode creation funct...
const DebugLoc & getDebugLoc() const
unsigned getIROrder() const
This class provides iterator support for SDUse operands that use a specific SDNode.
Represents one node in the SelectionDAG.
const APInt & getAsAPIntVal() const
Helper method returns the APInt value of a ConstantSDNode.
bool isMachineOpcode() const
Test if this node has a post-isel opcode, directly corresponding to a MachineInstr opcode.
LLVM_ABI void dumprFull(const SelectionDAG *G=nullptr) const
printrFull to dbgs().
unsigned getOpcode() const
Return the SelectionDAG opcode value for this node.
bool isDivergent() const
LLVM_ABI bool isOnlyUserOf(const SDNode *N) const
Return true if this node is the only use of N.
iterator_range< value_op_iterator > op_values() const
unsigned getIROrder() const
Return the node ordering.
static constexpr size_t getMaxNumOperands()
Return the maximum number of operands that a SDNode can hold.
iterator_range< use_iterator > uses()
MemSDNodeBitfields MemSDNodeBits
bool getHasDebugValue() const
SDNodeFlags getFlags() const
void setNodeId(int Id)
Set unique node id.
LLVM_ABI void intersectFlagsWith(const SDNodeFlags Flags)
Clear any flags in this node that aren't also set in Flags.
static bool hasPredecessorHelper(const SDNode *N, SmallPtrSetImpl< const SDNode * > &Visited, SmallVectorImpl< const SDNode * > &Worklist, unsigned int MaxSteps=0, bool TopologicalPrune=false)
Returns true if N is a predecessor of any node in Worklist.
uint64_t getAsZExtVal() const
Helper method returns the zero-extended integer value of a ConstantSDNode.
bool use_empty() const
Return true if there are no uses of this node.
unsigned getNumValues() const
Return the number of values defined/returned by this operator.
unsigned getNumOperands() const
Return the number of values used by this operation.
const SDValue & getOperand(unsigned Num) const
static LLVM_ABI bool areOnlyUsersOf(ArrayRef< const SDNode * > Nodes, const SDNode *N)
Return true if all the users of N are contained in Nodes.
use_iterator use_begin() const
Provide iteration support to walk over all uses of an SDNode.
LLVM_ABI bool isOperandOf(const SDNode *N) const
Return true if this node is an operand of N.
const APInt & getConstantOperandAPInt(unsigned Num) const
Helper method returns the APInt of a ConstantSDNode operand.
std::optional< APInt > bitcastToAPInt() const
LLVM_ABI bool hasPredecessor(const SDNode *N) const
Return true if N is a predecessor of this node.
LLVM_ABI bool hasAnyUseOfValue(unsigned Value) const
Return true if there are any use of the indicated value.
EVT getValueType(unsigned ResNo) const
Return the type of a specified result.
bool isUndef() const
Returns true if the node type is UNDEF or POISON.
op_iterator op_end() const
op_iterator op_begin() const
static use_iterator use_end()
LLVM_ABI void DropOperands()
Release the operands and set this node to have zero operands.
SDNode(unsigned Opc, unsigned Order, DebugLoc dl, SDVTList VTs)
Create an SDNode.
Represents a use of a SDNode.
SDNode * getUser()
This returns the SDNode that contains this Use.
Unlike LLVM values, Selection DAG nodes may return multiple values as the result of a computation.
bool isUndef() const
SDNode * getNode() const
get the SDNode which holds the desired result
bool hasOneUse() const
Return true if there is exactly one node using value ResNo of Node, in exactly one operand.
LLVM_ABI bool isOperandOf(const SDNode *N) const
Return true if the referenced return value is an operand of N.
SDValue()=default
LLVM_ABI bool reachesChainWithoutSideEffects(SDValue Dest, unsigned Depth=2) const
Return true if this operand (which must be a chain) reaches the specified operand without crossing an...
SDValue getValue(unsigned R) const
EVT getValueType() const
Return the ValueType of the referenced return value.
TypeSize getValueSizeInBits() const
Returns the size of the value in bits.
const SDValue & getOperand(unsigned i) const
bool use_empty() const
Return true if there are no nodes using value ResNo of Node.
const APInt & getConstantOperandAPInt(unsigned i) const
uint64_t getScalarValueSizeInBits() const
unsigned getResNo() const
get the index which selects a specific result in the SDNode
uint64_t getConstantOperandVal(unsigned i) const
unsigned getOpcode() const
virtual void verifyTargetNode(const SelectionDAG &DAG, const SDNode *N) const
Checks that the given target-specific node is valid. Aborts if it is not.
This is used to represent a portion of an LLVM function in a low-level Data Dependence DAG representa...
LLVM_ABI SDValue getElementCount(const SDLoc &DL, EVT VT, ElementCount EC)
LLVM_ABI Align getReducedAlign(EVT VT, bool UseABI)
In most cases this function returns the ABI alignment for a given type, except for illegal vector typ...
LLVM_ABI SDValue getShiftAmountOperand(EVT LHSTy, SDValue Op)
Return the specified value casted to the target's desired shift amount type.
LLVM_ABI std::pair< SDValue, SDValue > getMemccpy(SDValue Chain, const SDLoc &dl, SDValue Dst, SDValue Src, SDValue C, SDValue Size, const CallInst *CI)
Lower a memccpy operation into a target library call and return the resulting chain and call result a...
LLVM_ABI SDValue emitStackConvert(SDValue SrcOp, EVT SlotVT, EVT DestVT, const SDLoc &DL, SDValue Chain)
Emit a store/load combination to the stack.
LLVM_ABI bool isKnownNeverLogicalZero(SDValue Op, const APInt &DemandedElts, unsigned Depth=0) const
Test whether the given floating point SDValue (or all elements of it, if it is a vector) is known to ...
LLVM_ABI SDValue getExtLoadVP(ISD::LoadExtType ExtType, const SDLoc &dl, EVT VT, SDValue Chain, SDValue Ptr, SDValue Mask, SDValue EVL, MachinePointerInfo PtrInfo, EVT MemVT, MaybeAlign Alignment, MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo, bool IsExpanding=false)
SDValue getExtractVectorElt(const SDLoc &DL, EVT VT, SDValue Vec, unsigned Idx)
Extract element at Idx from Vec.
LLVM_ABI SDValue getSplatSourceVector(SDValue V, int &SplatIndex)
If V is a splatted value, return the source vector and its splat index.
LLVM_ABI SDValue getLabelNode(unsigned Opcode, const SDLoc &dl, SDValue Root, MCSymbol *Label)
LLVM_ABI OverflowKind computeOverflowForUnsignedSub(SDValue N0, SDValue N1) const
Determine if the result of the unsigned sub of 2 nodes can overflow.
LLVM_ABI unsigned ComputeMaxSignificantBits(SDValue Op, unsigned Depth=0) const
Get the upper bound on bit size for this Value Op as a signed integer.
const SDValue & getRoot() const
Return the root tag of the SelectionDAG.
LLVM_ABI std::pair< SDValue, SDValue > getStrlen(SDValue Chain, const SDLoc &dl, SDValue Src, const CallInst *CI)
Lower a strlen operation into a target library call and return the resulting chain and call result as...
LLVM_ABI SDValue getMaskedGather(SDVTList VTs, EVT MemVT, const SDLoc &dl, ArrayRef< SDValue > Ops, MachineMemOperand *MMO, ISD::MemIndexType IndexType, ISD::LoadExtType ExtTy)
LLVM_ABI SDValue FoldSetCC(EVT VT, SDValue N1, SDValue N2, ISD::CondCode Cond, const SDLoc &dl, SDNodeFlags Flags={})
Constant fold a setcc to true or false.
bool isKnownNeverSNaN(SDValue Op, const APInt &DemandedElts, unsigned Depth=0) const
LLVM_ABI SDValue makeStateFunctionCall(unsigned LibFunc, SDValue Ptr, SDValue InChain, SDNode *Node)
Helper used to make a call to a library function that has one argument of pointer type.
LLVM_ABI std::optional< bool > isBoolConstant(SDValue N) const
Check if a value \op N is a constant using the target's BooleanContent for its type.
LLVM_ABI SDValue getStackArgumentTokenFactor(SDValue Chain)
Compute a TokenFactor to force all the incoming stack arguments to be loaded from the stack.
const TargetSubtargetInfo & getSubtarget() const
LLVM_ABI ConstantRange computeConstantRange(SDValue Op, bool ForSigned, unsigned Depth=0) const
Determine the possible constant range of an integer or vector of integers.
LLVM_ABI SDValue getMergeValues(ArrayRef< SDValue > Ops, const SDLoc &dl)
Create a MERGE_VALUES node from the given operands.
LLVM_ABI SDVTList getVTList(EVT VT)
Return an SDVTList that represents the list of values specified.
LLVM_ABI SDValue getShiftAmountConstant(uint64_t Val, EVT VT, const SDLoc &DL)
LLVM_ABI void updateDivergence(SDNode *N)
LLVM_ABI SDValue getSplatValue(SDValue V, bool LegalTypes=false)
If V is a splat vector, return its scalar source operand by extracting that element from the source v...
LLVM_ABI SDValue getAllOnesConstant(const SDLoc &DL, EVT VT, bool IsTarget=false, bool IsOpaque=false)
LLVM_ABI MachineSDNode * getMachineNode(unsigned Opcode, const SDLoc &dl, EVT VT)
These are used for target selectors to create a new node with specified return type(s),...
LLVM_ABI void ExtractVectorElements(SDValue Op, SmallVectorImpl< SDValue > &Args, unsigned Start=0, unsigned Count=0, EVT EltVT=EVT())
Append the extracted elements from Start to Count out of the vector Op in Args.
LLVM_ABI SDValue getAtomicMemset(SDValue Chain, const SDLoc &dl, SDValue Dst, SDValue Value, SDValue Size, Type *SizeTy, unsigned ElemSz, bool isTailCall, MachinePointerInfo DstPtrInfo)
LLVM_ABI SDValue getAtomicLoad(ISD::LoadExtType ExtType, const SDLoc &dl, EVT MemVT, EVT VT, SDValue Chain, SDValue Ptr, MachineMemOperand *MMO)
LLVM_ABI SDNode * getNodeIfExists(unsigned Opcode, SDVTList VTList, ArrayRef< SDValue > Ops, const SDNodeFlags Flags, bool AllowCommute=false)
Get the specified node if it's already available, or else return NULL.
LLVM_ABI SDValue getPseudoProbeNode(const SDLoc &Dl, SDValue Chain, uint64_t Guid, uint64_t Index, uint32_t Attr)
Creates a PseudoProbeSDNode with function GUID Guid and the index of the block Index it is probing,...
LLVM_ABI SDValue getFreeze(SDValue V)
Return a freeze using the SDLoc of the value operand.
LLVM_ABI SDNode * SelectNodeTo(SDNode *N, unsigned MachineOpc, EVT VT)
These are used for target selectors to mutate the specified node to have the specified return type,...
LLVM_ABI SelectionDAG(const TargetMachine &TM, CodeGenOptLevel)
LLVM_ABI SDValue getMemset(SDValue Chain, const SDLoc &dl, SDValue Dst, SDValue Src, SDValue Size, Align Alignment, bool isVol, bool AlwaysInline, const CallInst *CI, MachinePointerInfo DstPtrInfo, const AAMDNodes &AAInfo=AAMDNodes())
LLVM_ABI SDValue getConstantPool(const Constant *C, EVT VT, MaybeAlign Align=std::nullopt, int Offs=0, bool isT=false, unsigned TargetFlags=0)
LLVM_ABI SDValue getStridedLoadVP(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &DL, SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Stride, SDValue Mask, SDValue EVL, EVT MemVT, MachineMemOperand *MMO, bool IsExpanding=false)
LLVM_ABI SDValue getAtomicCmpSwap(unsigned Opcode, const SDLoc &dl, EVT MemVT, SDVTList VTs, SDValue Chain, SDValue Ptr, SDValue Cmp, SDValue Swp, MachineMemOperand *MMO)
Gets a node for an atomic cmpxchg op.
LLVM_ABI SDValue makeEquivalentMemoryOrdering(SDValue OldChain, SDValue NewMemOpChain)
If an existing load has uses of its chain, create a token factor node with that chain and the new mem...
LLVM_ABI bool isConstantIntBuildVectorOrConstantInt(SDValue N, bool AllowOpaques=true) const
Test whether the given value is a constant int or similar node.
LLVM_ABI void ReplaceAllUsesOfValuesWith(const SDValue *From, const SDValue *To, unsigned Num)
Like ReplaceAllUsesOfValueWith, but for multiple values at once.
LLVM_ABI SDValue getJumpTableDebugInfo(int JTI, SDValue Chain, const SDLoc &DL)
LLVM_ABI SDValue getSymbolFunctionGlobalAddress(SDValue Op, Function **TargetFunction=nullptr)
Return a GlobalAddress of the function from the current module with name matching the given ExternalS...
LLVM_ABI std::optional< unsigned > getValidMaximumShiftAmount(SDValue V, const APInt &DemandedElts, unsigned Depth=0) const
If a SHL/SRA/SRL node V has shift amounts that are all less than the element bit-width of the shift n...
LLVM_ABI SDValue UnrollVectorOp(SDNode *N, unsigned ResNE=0)
Utility function used by legalize and lowering to "unroll" a vector operation by splitting out the sc...
LLVM_ABI SDValue getVScale(const SDLoc &DL, EVT VT, APInt MulImm)
Return a node that represents the runtime scaling 'MulImm * RuntimeVL'.
LLVM_ABI SDValue getConstantFP(double Val, const SDLoc &DL, EVT VT, bool isTarget=false)
Create a ConstantFPSDNode wrapping a constant value.
OverflowKind
Used to represent the possible overflow behavior of an operation.
static LLVM_ABI unsigned getHasPredecessorMaxSteps()
LLVM_ABI bool haveNoCommonBitsSet(SDValue A, SDValue B) const
Return true if A and B have no common bits set.
LLVM_ABI SDValue getAddrSpaceCast(const SDLoc &dl, EVT VT, SDValue Ptr, unsigned SrcAS, unsigned DestAS, const SDNodeFlags Flags=SDNodeFlags())
Return an AddrSpaceCastSDNode.
SDValue getExtractSubvector(const SDLoc &DL, EVT VT, SDValue Vec, unsigned Idx)
Return the VT typed sub-vector of Vec at Idx.
LLVM_ABI bool cannotBeOrderedNegativeFP(SDValue Op) const
Test whether the given float value is known to be positive.
LLVM_ABI SDValue getRegister(Register Reg, EVT VT)
LLVM_ABI bool calculateDivergence(SDNode *N)
LLVM_ABI std::pair< SDValue, SDValue > getStrcmp(SDValue Chain, const SDLoc &dl, SDValue S0, SDValue S1, const CallInst *CI)
Lower a strcmp operation into a target library call and return the resulting chain and call result as...
LLVM_ABI SDValue getGetFPEnv(SDValue Chain, const SDLoc &dl, SDValue Ptr, EVT MemVT, MachineMemOperand *MMO)
LLVM_ABI SDValue getAssertAlign(const SDLoc &DL, SDValue V, Align A)
Return an AssertAlignSDNode.
LLVM_ABI SDNode * mutateStrictFPToFP(SDNode *Node)
Mutate the specified strict FP node to its non-strict equivalent, unlinking the node from its chain a...
LLVM_ABI bool canIgnoreSignBitOfZero(const SDUse &Use) const
Check if a use of a float value is insensitive to signed zeros.
LLVM_ABI bool SignBitIsZeroFP(SDValue Op, unsigned Depth=0) const
Return true if the sign bit of Op is known to be zero, for a floating-point value.
LLVM_ABI SDValue getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef< SDValue > Ops, EVT MemVT, MachinePointerInfo PtrInfo, Align Alignment, MachineMemOperand::Flags Flags=MachineMemOperand::MOLoad|MachineMemOperand::MOStore, LocationSize Size=LocationSize::precise(0), const AAMDNodes &AAInfo=AAMDNodes())
Creates a MemIntrinsicNode that may produce a result and takes a list of operands.
SDValue getInsertSubvector(const SDLoc &DL, SDValue Vec, SDValue SubVec, unsigned Idx)
Insert SubVec at the Idx element of Vec.
LLVM_ABI SDValue getStepVector(const SDLoc &DL, EVT ResVT, const APInt &StepVal)
Returns a vector of type ResVT whose elements contain the linear sequence <0, Step,...
SDValue getSetCC(const SDLoc &DL, EVT VT, SDValue LHS, SDValue RHS, ISD::CondCode Cond, SDValue Chain=SDValue(), bool IsSignaling=false, SDNodeFlags Flags={})
Helper function to make it easier to build SetCC's if you just have an ISD::CondCode instead of an SD...
LLVM_ABI SDValue getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, SDValue Chain, SDValue Ptr, SDValue Val, MachineMemOperand *MMO)
Gets a node for an atomic op, produces result (if relevant) and chain and takes 2 operands.
LLVM_ABI Align getEVTAlign(EVT MemoryVT) const
Compute the default alignment value for the given type.
LLVM_ABI bool shouldOptForSize() const
LLVM_ABI bool hasSwiftErrorArg() const
LLVM_ABI SDValue buildVectorFromUnrolledParts(EVT VT, const SDLoc &DL, ArrayRef< SDValue > Scalars)
Returns a vector constructed from the scalar values in order.
LLVM_ABI SDValue getNOT(const SDLoc &DL, SDValue Val, EVT VT)
Create a bitwise NOT operation as (XOR Val, -1).
LLVM_ABI SDValue getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst, SDValue Src, SDValue Size, Align DstAlign, Align SrcAlign, bool isVol, bool AlwaysInline, const CallInst *CI, std::optional< bool > OverrideTailCall, MachinePointerInfo DstPtrInfo, MachinePointerInfo SrcPtrInfo, const AAMDNodes &AAInfo=AAMDNodes(), BatchAAResults *BatchAA=nullptr)
const TargetLowering & getTargetLoweringInfo() const
LLVM_ABI bool isEqualTo(SDValue A, SDValue B) const
Test whether two SDValues are known to compare equal.
static constexpr unsigned MaxRecursionDepth
LLVM_ABI unsigned getMaxRuntimeNumElements(EVT VT) const
Returns the maximum runtime number of elements in VT if known, or 0 otherwise.
LLVM_ABI SDValue getStridedStoreVP(SDValue Chain, const SDLoc &DL, SDValue Val, SDValue Ptr, SDValue Offset, SDValue Stride, SDValue Mask, SDValue EVL, EVT MemVT, MachineMemOperand *MMO, ISD::MemIndexedMode AM, bool IsTruncating=false, bool IsCompressing=false)
bool isGuaranteedNotToBePoison(SDValue Op, unsigned Depth=0) const
Return true if this function can prove that Op is never poison.
LLVM_ABI SDValue getIdentityElement(unsigned Opcode, const SDLoc &DL, EVT VT, SDNodeFlags Flags)
Get the (commutative) identity element for the given opcode, if it exists.
LLVM_ABI SDValue expandVACopy(SDNode *Node)
Expand the specified ISD::VACOPY node as the Legalize pass would.
LLVM_ABI SDValue getIndexedMaskedLoad(SDValue OrigLoad, const SDLoc &dl, SDValue Base, SDValue Offset, ISD::MemIndexedMode AM)
LLVM_ABI APInt computeVectorKnownZeroElements(SDValue Op, const APInt &DemandedElts, unsigned Depth=0) const
For each demanded element of a vector, see if it is known to be zero.
LLVM_ABI void AddDbgValue(SDDbgValue *DB, bool isParameter)
Add a dbg_value SDNode.
bool NewNodesMustHaveLegalTypes
When true, additional steps are taken to ensure that getConstant() and similar functions return DAG n...
LLVM_ABI std::pair< EVT, EVT > GetSplitDestVTs(const EVT &VT) const
Compute the VTs needed for the low/hi parts of a type which is split (or expanded) into two not neces...
LLVM_ABI void salvageDebugInfo(SDNode &N)
To be invoked on an SDNode that is slated to be erased.
LLVM_ABI SDNode * MorphNodeTo(SDNode *N, unsigned Opc, SDVTList VTs, ArrayRef< SDValue > Ops)
This mutates the specified node to have the specified return type, opcode, and operands.
LLVM_ABI std::pair< SDValue, SDValue > UnrollVectorOverflowOp(SDNode *N, unsigned ResNE=0)
Like UnrollVectorOp(), but for the [US](ADD|SUB|MUL)O family of opcodes.
allnodes_const_iterator allnodes_begin() const
SDValue getUNDEF(EVT VT)
Return an UNDEF node. UNDEF does not have a useful SDLoc.
LLVM_ABI SDValue getGatherVP(SDVTList VTs, EVT VT, const SDLoc &dl, ArrayRef< SDValue > Ops, MachineMemOperand *MMO, ISD::MemIndexType IndexType)
SDValue getBuildVector(EVT VT, const SDLoc &DL, ArrayRef< SDValue > Ops)
Return an ISD::BUILD_VECTOR node.
LLVM_ABI SDValue getBitcastedAnyExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of integer type, to the integer type VT, by first bitcasting (from potentia...
LLVM_ABI bool isSplatValue(SDValue V, const APInt &DemandedElts, APInt &UndefElts, unsigned Depth=0) const
Test whether V has a splatted value for all the demanded elements.
LLVM_ABI void DeleteNode(SDNode *N)
Remove the specified node from the system.
LLVM_ABI SDValue getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val, SDValue Ptr, SDValue Offset, MachinePointerInfo PtrInfo, EVT SVT, Align Alignment, MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const MMOMetadata &Metadata=MMOMetadata())
LLVM_ABI SDValue getBitcast(EVT VT, SDValue V)
Return a bitcast using the SDLoc of the value operand, and casting to the provided type.
LLVM_ABI SDDbgValue * getDbgValueList(DIVariable *Var, DIExpression *Expr, ArrayRef< SDDbgOperand > Locs, ArrayRef< SDNode * > Dependencies, bool IsIndirect, const DebugLoc &DL, unsigned O, bool IsVariadic)
Creates a SDDbgValue node from a list of locations.
LLVM_ABI std::pair< SDValue, SDValue > getStrcpy(SDValue Chain, const SDLoc &dl, SDValue Dst, SDValue Src, const CallInst *CI)
Lower a strcpy operation into a target library call and return the resulting chain and call result as...
SDValue getSelect(const SDLoc &DL, EVT VT, SDValue Cond, SDValue LHS, SDValue RHS, SDNodeFlags Flags=SDNodeFlags())
Helper function to make it easier to build Select's if you just have operands and don't want to check...
LLVM_ABI SDValue getNegative(SDValue Val, const SDLoc &DL, EVT VT)
Create negative operation as (SUB 0, Val).
LLVM_ABI std::optional< unsigned > getValidShiftAmount(SDValue V, const APInt &DemandedElts, unsigned Depth=0) const
If a SHL/SRA/SRL node V has a uniform shift amount that is less than the element bit-width of the shi...
LLVM_ABI void setNodeMemRefs(MachineSDNode *N, ArrayRef< MachineMemOperand * > NewMemRefs)
Mutate the specified machine node's memory references to the provided list.
LLVM_ABI SDValue simplifySelect(SDValue Cond, SDValue TVal, SDValue FVal)
Try to simplify a select/vselect into 1 of its operands or a constant.
LLVM_ABI SDValue getZeroExtendInReg(SDValue Op, const SDLoc &DL, EVT VT)
Return the expression required to zero extend the Op value assuming it was the smaller SrcTy value.
LLVM_ABI bool isConstantFPBuildVectorOrConstantFP(SDValue N) const
Test whether the given value is a constant FP or similar node.
const DataLayout & getDataLayout() const
LLVM_ABI SDValue getPartialReduceMLS(unsigned Opc, const SDLoc &DL, SDValue Acc, SDValue LHS, SDValue RHS)
Get an expression that implements a partial multiply-subtract reduction.
LLVM_ABI SDValue expandVAArg(SDNode *Node)
Expand the specified ISD::VAARG node as the Legalize pass would.
LLVM_ABI SDValue getTokenFactor(const SDLoc &DL, SmallVectorImpl< SDValue > &Vals)
Creates a new TokenFactor containing Vals.
LLVM_ABI SDValue getStore(SDValue Chain, const SDLoc &dl, SDValue Val, SDValue Ptr, MachinePointerInfo PtrInfo, Align Alignment, MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const MMOMetadata &Metadata=MMOMetadata())
Helper function to build ISD::STORE nodes.
LLVM_ABI bool doesNodeExist(unsigned Opcode, SDVTList VTList, ArrayRef< SDValue > Ops)
Check if a node exists without modifying its flags.
LLVM_ABI ConstantRange computeConstantRangeIncludingKnownBits(SDValue Op, bool ForSigned, unsigned Depth=0) const
Combine constant ranges from computeConstantRange() and computeKnownBits().
const SelectionDAGTargetInfo & getSelectionDAGInfo() const
LLVM_ABI bool areNonVolatileConsecutiveLoads(LoadSDNode *LD, LoadSDNode *Base, unsigned Bytes, int Dist) const
Return true if loads are next to each other and can be merged.
LLVM_ABI SDValue getMaskedHistogram(SDVTList VTs, EVT MemVT, const SDLoc &dl, ArrayRef< SDValue > Ops, MachineMemOperand *MMO, ISD::MemIndexType IndexType)
LLVM_ABI SDDbgLabel * getDbgLabel(DILabel *Label, const DebugLoc &DL, unsigned O)
Creates a SDDbgLabel node.
LLVM_ABI SDValue getStoreVP(SDValue Chain, const SDLoc &dl, SDValue Val, SDValue Ptr, SDValue Offset, SDValue Mask, SDValue EVL, EVT MemVT, MachineMemOperand *MMO, ISD::MemIndexedMode AM, bool IsTruncating=false, bool IsCompressing=false)
LLVM_ABI OverflowKind computeOverflowForUnsignedMul(SDValue N0, SDValue N1) const
Determine if the result of the unsigned mul of 2 nodes can overflow.
LLVM_ABI void copyExtraInfo(SDNode *From, SDNode *To)
Copy extra info associated with one node to another.
LLVM_ABI SDValue getConstant(uint64_t Val, const SDLoc &DL, EVT VT, bool isTarget=false, bool isOpaque=false)
Create a ConstantSDNode wrapping a constant value.
LLVM_ABI SDValue getMemBasePlusOffset(SDValue Base, TypeSize Offset, const SDLoc &DL, const SDNodeFlags Flags=SDNodeFlags())
Returns sum of the base pointer and offset.
LLVM_ABI SDValue getGlobalAddress(const GlobalValue *GV, const SDLoc &DL, EVT VT, int64_t offset=0, bool isTargetGA=false, unsigned TargetFlags=0)
LLVM_ABI SDValue getVAArg(EVT VT, const SDLoc &dl, SDValue Chain, SDValue Ptr, SDValue SV, unsigned Align)
VAArg produces a result and token chain, and takes a pointer and a source value as input.
LLVM_ABI SDValue getLoadFFVP(EVT VT, const SDLoc &DL, SDValue Chain, SDValue Ptr, SDValue Mask, SDValue EVL, MachineMemOperand *MMO)
LLVM_ABI SDValue getTypeSize(const SDLoc &DL, EVT VT, TypeSize TS)
LLVM_ABI SDValue getMDNode(const MDNode *MD)
Return an MDNodeSDNode which holds an MDNode.
LLVM_ABI void clear()
Clear state and free memory necessary to make this SelectionDAG ready to process a new block.
LLVM_ABI std::pair< SDValue, SDValue > getMemcmp(SDValue Chain, const SDLoc &dl, SDValue Dst, SDValue Src, SDValue Size, const CallInst *CI)
Lower a memcmp operation into a target library call and return the resulting chain and call result as...
LLVM_ABI void ReplaceAllUsesWith(SDValue From, SDValue To)
Modify anything using 'From' to use 'To' instead.
LLVM_ABI SDValue getCommutedVectorShuffle(const ShuffleVectorSDNode &SV)
Returns an ISD::VECTOR_SHUFFLE node semantically equivalent to the shuffle node in input but with swa...
LLVM_ABI SDValue getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl, EVT VT, SDValue Chain, SDValue Ptr, MachinePointerInfo PtrInfo, EVT MemVT, MaybeAlign Alignment=MaybeAlign(), MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const MMOMetadata &Metadata=MMOMetadata())
LLVM_ABI std::pair< SDValue, SDValue > SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT, const EVT &HiVT)
Split the vector with EXTRACT_SUBVECTOR using the provided VTs and return the low/high part.
LLVM_ABI SDValue getSignedConstant(int64_t Val, const SDLoc &DL, EVT VT, bool isTarget=false, bool isOpaque=false)
LLVM_ABI SDValue getSrcValue(const Value *v)
Construct a node to track a Value* through the backend.
SDValue getSplatVector(EVT VT, const SDLoc &DL, SDValue Op)
LLVM_ABI SDValue getAtomicMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst, SDValue Src, SDValue Size, Type *SizeTy, unsigned ElemSz, bool isTailCall, MachinePointerInfo DstPtrInfo, MachinePointerInfo SrcPtrInfo)
LLVM_ABI OverflowKind computeOverflowForSignedMul(SDValue N0, SDValue N1) const
Determine if the result of the signed mul of 2 nodes can overflow.
LLVM_ABI MaybeAlign InferPtrAlign(SDValue Ptr) const
Infer alignment of a load / store address.
LLVM_ABI void dump() const
Dump the textual format of this DAG.
LLVM_ABI bool MaskedValueIsAllOnes(SDValue Op, const APInt &Mask, unsigned Depth=0) const
Return true if '(Op & Mask) == Mask'.
LLVM_ABI bool SignBitIsZero(SDValue Op, unsigned Depth=0) const
Return true if the sign bit of Op is known to be zero.
LLVM_ABI void RemoveDeadNodes()
This method deletes all unreachable nodes in the SelectionDAG.
LLVM_ABI void RemoveDeadNode(SDNode *N)
Remove the specified node from the system.
LLVM_ABI void AddDbgLabel(SDDbgLabel *DB)
Add a dbg_label SDNode.
bool isConstantValueOfAnyType(SDValue N) const
LLVM_ABI bool canCreateUndefOrPoison(SDValue Op, const APInt &DemandedElts, UndefPoisonKind Kind=UndefPoisonKind::UndefOrPoison, bool ConsiderFlags=true, unsigned Depth=0) const
Return true if Op can create undef or poison from non-undef & non-poison operands.
SDValue getInsertVectorElt(const SDLoc &DL, SDValue Vec, SDValue Elt, unsigned Idx)
Insert Elt into Vec at offset Idx.
LLVM_ABI SDValue getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT, SDValue Operand)
A convenience function for creating TargetInstrInfo::EXTRACT_SUBREG nodes.
LLVM_ABI SDValue getBasicBlock(MachineBasicBlock *MBB)
LLVM_ABI SDValue getSExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of integer type, to the integer type VT, by either sign-extending or trunca...
LLVM_ABI SDDbgValue * getVRegDbgValue(DIVariable *Var, DIExpression *Expr, Register VReg, bool IsIndirect, const DebugLoc &DL, unsigned O)
Creates a VReg SDDbgValue node.
LLVM_ABI SDValue getLoad(EVT VT, const SDLoc &dl, SDValue Chain, SDValue Ptr, MachinePointerInfo PtrInfo, MaybeAlign Alignment=MaybeAlign(), MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const MMOMetadata &Metadata=MMOMetadata())
Loads are not normal binary operators: their result type is not determined by their operands,...
LLVM_ABI KnownFPClass computeKnownFPClass(SDValue Op, FPClassTest InterestedClasses, unsigned Depth=0) const
Determine floating-point class information about Op.
LLVM_ABI bool isIdentityElement(unsigned Opc, SDNodeFlags Flags, SDValue V, unsigned OperandNo, unsigned Depth=0) const
Returns true if V is an identity element of Opc with Flags.
LLVM_ABI SDValue getEHLabel(const SDLoc &dl, SDValue Root, MCSymbol *Label)
LLVM_ABI bool isGuaranteedNotToBeUndefOrPoison(SDValue Op, UndefPoisonKind Kind=UndefPoisonKind::UndefOrPoison, unsigned Depth=0) const
Return true if this function can prove that Op is never poison and, Kind can be used to track poison ...
LLVM_ABI bool isKnownNeverZero(SDValue Op, unsigned Depth=0) const
Test whether the given SDValue is known to contain non-zero value(s).
LLVM_ABI SDValue getIndexedStore(SDValue OrigStore, const SDLoc &dl, SDValue Base, SDValue Offset, ISD::MemIndexedMode AM)
LLVM_ABI SDValue FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL, EVT VT, ArrayRef< SDValue > Ops, SDNodeFlags Flags=SDNodeFlags())
LLVM_ABI std::optional< unsigned > getValidMinimumShiftAmount(SDValue V, const APInt &DemandedElts, unsigned Depth=0) const
If a SHL/SRA/SRL node V has shift amounts that are all less than the element bit-width of the shift n...
LLVM_ABI SDValue getSetFPEnv(SDValue Chain, const SDLoc &dl, SDValue Ptr, EVT MemVT, MachineMemOperand *MMO)
LLVM_ABI SDValue getBoolExtOrTrunc(SDValue Op, const SDLoc &SL, EVT VT, EVT OpVT)
Convert Op, which must be of integer type, to the integer type VT, by using an extension appropriate ...
LLVM_ABI SDValue getMaskedStore(SDValue Chain, const SDLoc &dl, SDValue Val, SDValue Base, SDValue Offset, SDValue Mask, EVT MemVT, MachineMemOperand *MMO, ISD::MemIndexedMode AM, bool IsTruncating=false, bool IsCompressing=false)
LLVM_ABI SDValue getExternalSymbol(const char *Sym, EVT VT)
const TargetMachine & getTarget() const
LLVM_ABI std::pair< SDValue, SDValue > getStrictFPExtendOrRound(SDValue Op, SDValue Chain, const SDLoc &DL, EVT VT)
Convert Op, which must be a STRICT operation of float type, to the float type VT, by either extending...
LLVM_ABI std::pair< SDValue, SDValue > SplitEVL(SDValue N, EVT VecVT, const SDLoc &DL)
Split the explicit vector length parameter of a VP operation.
LLVM_ABI SDValue getPtrExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of integer type, to the integer type VT, by either truncating it or perform...
LLVM_ABI SDValue getMaskFromElementCount(const SDLoc &DL, EVT VT, ElementCount Len)
Return a vector with the first 'Len' lanes set to true and remaining lanes set to false.
LLVM_ABI SDValue getAnyExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of integer type, to the integer type VT, by either any-extending or truncat...
iterator_range< allnodes_iterator > allnodes()
LLVM_ABI SDValue getBlockAddress(const BlockAddress *BA, EVT VT, int64_t Offset=0, bool isTarget=false, unsigned TargetFlags=0)
LLVM_ABI SDValue WidenVector(const SDValue &N, const SDLoc &DL)
Widen the vector up to the next power of two using INSERT_SUBVECTOR.
const LibcallLoweringInfo & getLibcalls() const
LLVM_ABI SDValue getLoadVP(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &dl, SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Mask, SDValue EVL, MachinePointerInfo PtrInfo, EVT MemVT, Align Alignment, MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo, const MDNode *Ranges=nullptr, bool IsExpanding=false)
LLVM_ABI SDValue getIntPtrConstant(uint64_t Val, const SDLoc &DL, bool isTarget=false)
LLVM_ABI SDDbgValue * getConstantDbgValue(DIVariable *Var, DIExpression *Expr, const Value *C, const DebugLoc &DL, unsigned O)
Creates a constant SDDbgValue node.
LLVM_ABI SDValue getScatterVP(SDVTList VTs, EVT VT, const SDLoc &dl, ArrayRef< SDValue > Ops, MachineMemOperand *MMO, ISD::MemIndexType IndexType)
LLVM_ABI SDValue getValueType(EVT)
LLVM_ABI SDValue getLifetimeNode(bool IsStart, const SDLoc &dl, SDValue Chain, int FrameIndex)
Creates a LifetimeSDNode that starts (IsStart==true) or ends (IsStart==false) the lifetime of the Fra...
ArrayRef< SDDbgValue * > GetDbgValues(const SDNode *SD) const
Get the debug values which reference the given SDNode.
LLVM_ABI SDValue getNode(unsigned Opcode, const SDLoc &DL, EVT VT, ArrayRef< SDUse > Ops)
Gets or creates the specified node.
LLVM_ABI OverflowKind computeOverflowForSignedAdd(SDValue N0, SDValue N1) const
Determine if the result of the signed addition of 2 nodes can overflow.
LLVM_ABI SDValue getFPExtendOrRound(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of float type, to the float type VT, by either extending or rounding (by tr...
LLVM_ABI unsigned AssignTopologicalOrder()
Topological-sort the AllNodes list and a assign a unique node id for each node in the DAG based on th...
ilist< SDNode >::size_type allnodes_size() const
LLVM_ABI bool isKnownNeverNaN(SDValue Op, const APInt &DemandedElts, bool SNaN=false, unsigned Depth=0) const
Test whether the given SDValue (or all elements of it, if it is a vector) is known to never be NaN in...
LLVM_ABI SDValue FoldConstantBuildVector(BuildVectorSDNode *BV, const SDLoc &DL, EVT DstEltVT)
Fold BUILD_VECTOR of constants/undefs to the destination type BUILD_VECTOR of constants/undefs elemen...
LLVM_ABI SDValue getAtomicMemmove(SDValue Chain, const SDLoc &dl, SDValue Dst, SDValue Src, SDValue Size, Type *SizeTy, unsigned ElemSz, bool isTailCall, MachinePointerInfo DstPtrInfo, MachinePointerInfo SrcPtrInfo)
LLVM_ABI SDValue getIndexedMaskedStore(SDValue OrigStore, const SDLoc &dl, SDValue Base, SDValue Offset, ISD::MemIndexedMode AM)
LLVM_ABI SDValue getTruncStoreVP(SDValue Chain, const SDLoc &dl, SDValue Val, SDValue Ptr, SDValue Mask, SDValue EVL, MachinePointerInfo PtrInfo, EVT SVT, Align Alignment, MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo, bool IsCompressing=false)
SDValue getTargetConstant(uint64_t Val, const SDLoc &DL, EVT VT, bool isOpaque=false)
LLVM_ABI unsigned ComputeNumSignBits(SDValue Op, unsigned Depth=0) const
Return the number of times the sign bit of the register is replicated into the other bits.
LLVM_ABI bool MaskedVectorIsZero(SDValue Op, const APInt &DemandedElts, unsigned Depth=0) const
Return true if 'Op' is known to be zero in DemandedElts.
LLVM_ABI SDValue getBoolConstant(bool V, const SDLoc &DL, EVT VT, EVT OpVT)
Create a true or false constant of type VT using the target's BooleanContent for type OpVT.
LLVM_ABI SDDbgValue * getFrameIndexDbgValue(DIVariable *Var, DIExpression *Expr, unsigned FI, bool IsIndirect, const DebugLoc &DL, unsigned O)
Creates a FrameIndex SDDbgValue node.
LLVM_ABI SDValue getExtStridedLoadVP(ISD::LoadExtType ExtType, const SDLoc &DL, EVT VT, SDValue Chain, SDValue Ptr, SDValue Stride, SDValue Mask, SDValue EVL, EVT MemVT, MachineMemOperand *MMO, bool IsExpanding=false)
LLVM_ABI SDValue getMemmove(SDValue Chain, const SDLoc &dl, SDValue Dst, SDValue Src, SDValue Size, Align DstAlign, Align SrcAlign, bool isVol, const CallInst *CI, std::optional< bool > OverrideTailCall, MachinePointerInfo DstPtrInfo, MachinePointerInfo SrcPtrInfo, const AAMDNodes &AAInfo=AAMDNodes(), BatchAAResults *BatchAA=nullptr)
LLVM_ABI SDValue getJumpTable(int JTI, EVT VT, bool isTarget=false, unsigned TargetFlags=0)
LLVM_ABI bool isBaseWithConstantOffset(SDValue Op) const
Return true if the specified operand is an ISD::ADD with a ConstantSDNode on the right-hand side,...
LLVM_ABI SDValue getVectorIdxConstant(uint64_t Val, const SDLoc &DL, bool isTarget=false)
LLVM_ABI void getTopologicallyOrderedNodes(SmallVectorImpl< const SDNode * > &SortedNodes) const
Get all the nodes in their topological order without modifying any states.
LLVM_ABI void ReplaceAllUsesOfValueWith(SDValue From, SDValue To)
Replace any uses of From with To, leaving uses of other values produced by From.getNode() alone.
MachineFunction & getMachineFunction() const
LLVM_ABI std::pair< SDValue, SDValue > getStrstr(SDValue Chain, const SDLoc &dl, SDValue S0, SDValue S1, const CallInst *CI)
Lower a strstr operation into a target library call and return the resulting chain and call result as...
LLVM_ABI SDValue getPtrExtendInReg(SDValue Op, const SDLoc &DL, EVT VT)
Return the expression required to extend the Op as a pointer value assuming it was the smaller SrcTy ...
LLVM_ABI OverflowKind computeOverflowForUnsignedAdd(SDValue N0, SDValue N1) const
Determine if the result of the unsigned addition of 2 nodes can overflow.
SDValue getPOISON(EVT VT)
Return a POISON node. POISON does not have a useful SDLoc.
SDValue getSplatBuildVector(EVT VT, const SDLoc &DL, SDValue Op)
Return a splat ISD::BUILD_VECTOR node, consisting of Op splatted to all elements.
LLVM_ABI SDValue getErrorMergeValues(ArrayRef< EVT > ResultTypes, SDValue Chain, const SDLoc &dl)
Return poison values for each of ResultTypes, substituting Chain for any result of type MVT::Other,...
LLVM_ABI SDValue getFrameIndex(int FI, EVT VT, bool isTarget=false)
LLVM_ABI void canonicalizeCommutativeBinop(unsigned Opcode, SDValue &N1, SDValue &N2) const
Swap N1 and N2 if Opcode is a commutative binary opcode and the canonical form expects the opposite o...
LLVM_ABI KnownBits computeKnownBits(SDValue Op, unsigned Depth=0) const
Determine which bits of Op are known to be either zero or one and return them in Known.
LLVM_ABI SDValue getRegisterMask(const uint32_t *RegMask)
LLVM_ABI SDValue getZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of integer type, to the integer type VT, by either zero-extending or trunca...
LLVM_ABI SDValue getCondCode(ISD::CondCode Cond)
LLVM_ABI bool MaskedValueIsZero(SDValue Op, const APInt &Mask, unsigned Depth=0) const
Return true if 'Op & Mask' is known to be zero.
LLVM_ABI bool isKnownToBeAPowerOfTwoFP(SDValue Val, unsigned Depth=0) const
Test if the given fp value is known to be an integer power-of-2, either positive or negative.
LLVM_ABI OverflowKind computeOverflowForSignedSub(SDValue N0, SDValue N1) const
Determine if the result of the signed sub of 2 nodes can overflow.
LLVM_ABI void init(MachineFunction &NewMF, const TargetLibraryInfo *LibraryInfo, const LibcallLoweringInfo *LibcallsInfo, UniformityInfo *UA, ProfileSummaryInfo *PSIin, BlockFrequencyInfo *BFIin, FunctionVarLocs const *FnVarLocs)
Prepare this SelectionDAG to process code in the given MachineFunction.
SDValue getObjectPtrOffset(const SDLoc &SL, SDValue Ptr, TypeSize Offset)
Create an add instruction with appropriate flags when used for addressing some offset of an object.
LLVMContext * getContext() const
LLVM_ABI SDValue simplifyFPBinop(unsigned Opcode, SDValue X, SDValue Y, SDNodeFlags Flags)
Try to simplify a floating-point binary operation into 1 of its operands or a constant.
const SDValue & setRoot(SDValue N)
Set the current root tag of the SelectionDAG.
LLVM_ABI bool isKnownToBeAPowerOfTwo(SDValue Val, bool OrZero=false, unsigned Depth=0) const
Test if the given value is known to have exactly one bit set.
LLVM_ABI SDValue getDeactivationSymbol(const GlobalValue *GV)
LLVM_ABI SDValue getTargetExternalSymbol(const char *Sym, EVT VT, unsigned TargetFlags=0)
LLVM_ABI SDValue getMCSymbol(MCSymbol *Sym, EVT VT)
LLVM_ABI bool isUndef(unsigned Opcode, ArrayRef< SDValue > Ops)
Return true if the result of this operation is always undefined.
LLVM_ABI SDValue CreateStackTemporary(TypeSize Bytes, Align Alignment)
Create a stack temporary based on the size in bytes and the alignment.
LLVM_ABI SDNode * UpdateNodeOperands(SDNode *N, SDValue Op)
Mutate the specified node in-place to have the specified operands.
LLVM_ABI std::pair< EVT, EVT > GetDependentSplitDestVTs(const EVT &VT, const EVT &EnvVT, bool *HiIsEmpty) const
Compute the VTs needed for the low/hi parts of a type, dependent on an enveloping VT that has been sp...
LLVM_ABI SDValue foldConstantFPMath(unsigned Opcode, const SDLoc &DL, EVT VT, ArrayRef< SDValue > Ops)
Fold floating-point operations when all operands are constants and/or undefined.
LLVM_ABI std::optional< ConstantRange > getValidShiftAmountRange(SDValue V, const APInt &DemandedElts, unsigned Depth) const
If a SHL/SRA/SRL node V has shift amounts that are all less than the element bit-width of the shift n...
LLVM_ABI SDValue FoldSymbolOffset(unsigned Opcode, EVT VT, const GlobalAddressSDNode *GA, const SDNode *N2)
LLVM_ABI SDValue getIndexedLoad(SDValue OrigLoad, const SDLoc &dl, SDValue Base, SDValue Offset, ISD::MemIndexedMode AM)
LLVM_ABI SDValue getTargetInsertSubreg(int SRIdx, const SDLoc &DL, EVT VT, SDValue Operand, SDValue Subreg)
A convenience function for creating TargetInstrInfo::INSERT_SUBREG nodes.
SDValue getEntryNode() const
Return the token chain corresponding to the entry of the function.
LLVM_ABI SDDbgValue * getDbgValue(DIVariable *Var, DIExpression *Expr, SDNode *N, unsigned R, bool IsIndirect, const DebugLoc &DL, unsigned O)
Creates a SDDbgValue node.
LLVM_ABI SDValue getMaskedLoad(EVT VT, const SDLoc &dl, SDValue Chain, SDValue Base, SDValue Offset, SDValue Mask, SDValue Src0, EVT MemVT, MachineMemOperand *MMO, ISD::MemIndexedMode AM, ISD::LoadExtType, bool IsExpanding=false)
DenormalMode getDenormalMode(EVT VT) const
Return the current function's default denormal handling kind for the given floating point type.
SDValue getSplat(EVT VT, const SDLoc &DL, SDValue Op)
Returns a node representing a splat of one value into all lanes of the provided vector type.
LLVM_ABI std::pair< SDValue, SDValue > SplitScalar(const SDValue &N, const SDLoc &DL, const EVT &LoVT, const EVT &HiVT)
Split the scalar node with EXTRACT_ELEMENT using the provided VTs and return the low/high part.
LLVM_ABI SDValue matchBinOpReduction(SDNode *Extract, ISD::NodeType &BinOp, ArrayRef< ISD::NodeType > CandidateBinOps, bool AllowPartials=false)
Match a binop + shuffle pyramid that represents a horizontal reduction over the elements of a vector ...
LLVM_ABI bool isADDLike(SDValue Op, bool NoWrap=false) const
Return true if the specified operand is an ISD::OR or ISD::XOR node that can be treated as an ISD::AD...
LLVM_ABI SDValue getVectorShuffle(EVT VT, const SDLoc &dl, SDValue N1, SDValue N2, ArrayRef< int > Mask)
Return an ISD::VECTOR_SHUFFLE node.
LLVM_ABI SDValue simplifyShift(SDValue X, SDValue Y)
Try to simplify a shift into 1 of its operands or a constant.
LLVM_ABI bool areNonVolatileConsecutiveStores(StoreSDNode *ST, StoreSDNode *Base, unsigned Bytes, int Dist) const
Return true if stores are next to each other and can be merged.
LLVM_ABI void transferDbgValues(SDValue From, SDValue To, unsigned OffsetInBits=0, unsigned SizeInBits=0, bool InvalidateDbg=true)
Transfer debug values from one node to another, while optionally generating fragment expressions for ...
LLVM_ABI SDValue getLogicalNOT(const SDLoc &DL, SDValue Val, EVT VT)
Create a logical NOT operation as (XOR Val, BooleanOne).
LLVM_ABI SDValue getMaskedScatter(SDVTList VTs, EVT MemVT, const SDLoc &dl, ArrayRef< SDValue > Ops, MachineMemOperand *MMO, ISD::MemIndexType IndexType, bool IsTruncating=false)
ilist< SDNode >::iterator allnodes_iterator
This SDNode is used to implement the code generator support for the llvm IR shufflevector instruction...
int getMaskElt(unsigned Idx) const
ArrayRef< int > getMask() const
static void commuteMask(MutableArrayRef< int > Mask)
Change values in a shuffle permute mask assuming the two vector operands have swapped position.
static LLVM_ABI bool isSplatMask(ArrayRef< int > Mask)
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
bool erase(PtrType Ptr)
Remove pointer from the set.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void assign(size_type NumElts, ValueParamT Elt)
reference emplace_back(ArgTypes &&... Args)
void reserve(size_type N)
iterator erase(const_iterator CI)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
This class is used to represent ISD::STORE nodes.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
constexpr const char * data() const
Get a pointer to the start of the string (which may not be null terminated).
Definition StringRef.h:138
Information about stack frame layout on the target.
virtual TargetStackID::Value getStackIDForScalableVectors() const
Returns the StackID that scalable vectors should be associated with.
Align getStackAlign() const
getStackAlignment - This method returns the number of bytes to which the stack pointer must be aligne...
Completely target-dependent object reference.
unsigned getTargetFlags() const
Provides information about what library functions are available for the current target.
virtual bool shouldConvertConstantLoadToIntImm(const APInt &Imm, Type *Ty) const
Return true if it is beneficial to convert a load of a constant to just the constant itself.
const TargetMachine & getTargetMachine() const
virtual bool isZExtFree(Type *FromTy, Type *ToTy) const
Return true if any actual instruction that defines a value of type FromTy implicitly zero-extends the...
unsigned getMaxStoresPerMemcpy(bool OptSize) const
Get maximum # of store operations permitted for llvm.memcpy.
unsigned getMaxStoresPerMemset(bool OptSize) const
Get maximum # of store operations permitted for llvm.memset.
virtual bool allowsMisalignedMemoryAccesses(EVT, unsigned AddrSpace=0, Align Alignment=Align(1), MachineMemOperand::Flags Flags=MachineMemOperand::MONone, unsigned *=nullptr) const
Determine if the target supports unaligned memory accesses.
virtual bool shallExtractConstSplatVectorElementToStore(Type *VectorTy, unsigned ElemSizeInBits, unsigned &Index) const
Return true if the target shall perform extract vector element and store given that the vector is kno...
virtual bool isTruncateFree(Type *FromTy, Type *ToTy) const
Return true if it's free to truncate a value of type FromTy to type ToTy.
virtual EVT getTypeToTransformTo(LLVMContext &Context, EVT VT) const
For types supported by the target, this is an identity function.
bool isTypeLegal(EVT VT) const
Return true if the target has native support for the specified value type.
virtual MVT getPointerTy(const DataLayout &DL, uint32_t AS=0) const
Return the pointer type for the given address space, defaults to the pointer type from the data layou...
BooleanContent
Enum that describes how the target represents true/false values.
virtual unsigned getMaxGluedStoresPerMemcpy() const
Get maximum # of store operations to be glued together.
std::vector< ArgListEntry > ArgListTy
unsigned getMaxStoresPerMemmove(bool OptSize) const
Get maximum # of store operations permitted for llvm.memmove.
virtual bool isLegalStoreImmediate(int64_t Value) const
Return true if the specified immediate is legal for the value input of a store instruction.
static ISD::NodeType getExtendForContent(BooleanContent Content)
This class defines information used to lower LLVM code to legal SelectionDAG operators that the targe...
virtual bool findOptimalMemOpLowering(LLVMContext &Context, std::vector< EVT > &MemOps, unsigned Limit, const MemOp &Op, unsigned DstAS, unsigned SrcAS, const AttributeList &FuncAttributes, EVT *LargestVT=nullptr) const
Determines the optimal series of memory ops to replace the memset / memcpy.
std::pair< SDValue, SDValue > LowerCallTo(CallLoweringInfo &CLI) const
This function lowers an abstract call to a function into an actual call.
Primary interface to the complete machine description for the target machine.
const Triple & getTargetTriple() const
virtual bool isNoopAddrSpaceCast(const DataLayout &DL, unsigned SrcAS, unsigned DestAS) const
Returns true if a cast between SrcAS and DestAS is a noop.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
virtual const SelectionDAGTargetInfo * getSelectionDAGInfo() const
virtual const TargetRegisterInfo * getRegisterInfo() const =0
Return the target's register information.
virtual const TargetLowering * getTargetLowering() const
bool isOSDarwin() const
Is this a "Darwin" OS (macOS, iOS, tvOS, watchOS, DriverKit, XROS, or bridgeOS).
Definition Triple.h:724
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
static constexpr TypeSize getFixed(ScalarTy ExactSize)
Definition TypeSize.h:339
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:283
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:299
static LLVM_ABI Type * getVoidTy(LLVMContext &C)
Definition Type.cpp:272
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
Definition Type.cpp:297
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:187
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.cpp:222
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Definition Type.cpp:303
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
LLVM_ABI unsigned getOperandNo() const
Return the operand # of this use in its User.
Definition Use.cpp:35
LLVM_ABI void set(Value *Val)
Definition Value.h:876
User * getUser() const
Returns the User that contains this Use.
Definition Use.h:61
Value * getOperand(unsigned i) const
Definition User.h:207
This class is used to represent an VP_GATHER node.
This class is used to represent a VP_LOAD node.
This class is used to represent an VP_SCATTER node.
This class is used to represent a VP_STORE node.
This class is used to represent an EXPERIMENTAL_VP_STRIDED_LOAD node.
This class is used to represent an EXPERIMENTAL_VP_STRIDED_STORE node.
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:209
bool contains(const_arg_type_t< ValueT > V) const
Check if the set contains the given element.
Definition DenseSet.h:182
constexpr bool hasKnownScalarFactor(const FixedOrScalableQuantity &RHS) const
Returns true if there exists a value X where RHS*X will result in a value whose quantity matches our ...
Definition TypeSize.h:265
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:200
static constexpr bool isKnownLE(const FixedOrScalableQuantity &LHS, const FixedOrScalableQuantity &RHS)
Definition TypeSize.h:230
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:168
constexpr bool isKnownEven() const
A return value of true indicates we know at compile time that the number of elements (vscale * Min) i...
Definition TypeSize.h:176
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
Definition TypeSize.h:165
constexpr LeafTy divideCoefficientBy(ScalarTy RHS) const
We do not provide the '/' operator here because division for polynomial types does not work in the sa...
Definition TypeSize.h:252
static constexpr bool isKnownGE(const FixedOrScalableQuantity &LHS, const FixedOrScalableQuantity &RHS)
Definition TypeSize.h:237
A raw_ostream that writes to an std::string.
CallInst * Call
Changed
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
LLVM_ABI APInt clmulr(const APInt &LHS, const APInt &RHS)
Perform a reversed carry-less multiply.
Definition APInt.cpp:3235
LLVM_ABI APInt mulhu(const APInt &C1, const APInt &C2)
Performs (2*N)-bit multiplication on zero-extended operands.
Definition APInt.cpp:3165
LLVM_ABI APInt avgCeilU(const APInt &C1, const APInt &C2)
Compute the ceil of the unsigned average of C1 and C2.
Definition APInt.cpp:3152
LLVM_ABI APInt avgFloorU(const APInt &C1, const APInt &C2)
Compute the floor of the unsigned average of C1 and C2.
Definition APInt.cpp:3142
LLVM_ABI APInt pext(const APInt &Val, const APInt &Mask)
Perform a "compress" operation, also known as pext or bext.
Definition APInt.cpp:3245
LLVM_ABI APInt fshr(const APInt &Hi, const APInt &Lo, const APInt &Shift)
Perform a funnel shift right.
Definition APInt.cpp:3216
LLVM_ABI APInt mulhs(const APInt &C1, const APInt &C2)
Performs (2*N)-bit multiplication on sign-extended operands.
Definition APInt.cpp:3157
LLVM_ABI APInt clmul(const APInt &LHS, const APInt &RHS)
Perform a carry-less multiply, also known as XOR multiplication, and return low-bits.
Definition APInt.cpp:3225
LLVM_ABI APInt pdep(const APInt &Val, const APInt &Mask)
Perform an "expand" operation, also known as pdep or bdep.
Definition APInt.cpp:3255
APInt abds(const APInt &A, const APInt &B)
Determine the absolute difference of two APInts considered to be signed.
Definition APInt.h:2294
LLVM_ABI APInt fshl(const APInt &Hi, const APInt &Lo, const APInt &Shift)
Perform a funnel shift left.
Definition APInt.cpp:3207
LLVM_ABI APInt ScaleBitMask(const APInt &A, unsigned NewBitWidth, bool MatchAllBits=false)
Splat/Merge neighboring bits to widen/narrow the bitmask represented by.
Definition APInt.cpp:3043
LLVM_ABI APInt clmulh(const APInt &LHS, const APInt &RHS)
Perform a carry-less multiply, and return high-bits.
Definition APInt.cpp:3240
APInt abdu(const APInt &A, const APInt &B)
Determine the absolute difference of two APInts considered to be unsigned.
Definition APInt.h:2299
LLVM_ABI APInt avgFloorS(const APInt &C1, const APInt &C2)
Compute the floor of the signed average of C1 and C2.
Definition APInt.cpp:3137
LLVM_ABI APInt avgCeilS(const APInt &C1, const APInt &C2)
Compute the ceil of the signed average of C1 and C2.
Definition APInt.cpp:3147
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
LLVM_ABI CondCode getSetCCInverse(CondCode Operation, bool isIntegerLike)
Return the operation corresponding to !(X op Y), where 'op' is a valid SetCC operation.
ISD namespace - This namespace contains an enum which represents all of the SelectionDAG node types a...
Definition ISDOpcodes.h:26
LLVM_ABI CondCode getSetCCAndOperation(CondCode Op1, CondCode Op2, EVT Type)
Return the result of a logical AND between different comparisons of identical values: ((X op1 Y) & (X...
LLVM_ABI bool isConstantSplatVectorAllOnes(const SDNode *N, bool BuildVectorOnly=false)
Return true if the specified node is a BUILD_VECTOR or SPLAT_VECTOR where all of the elements are ~0 ...
bool isNON_EXTLoad(const SDNode *N)
Returns true if the specified node is a non-extending load.
bool matchUnaryPredicateImpl(SDValue Op, const APInt &DemandedElts, std::function< bool(ConstNodeType *)> Match, bool AllowUndefs=false, bool AllowTruncation=false)
Attempt to match a unary predicate against a scalar/splat constant or every element of a constant BUI...
NodeType
ISD::NodeType enum - This enum defines the target-independent operators for a SelectionDAG.
Definition ISDOpcodes.h:43
@ SETCC
SetCC operator - This evaluates to a true value iff the condition is true.
Definition ISDOpcodes.h:837
@ MERGE_VALUES
MERGE_VALUES - This node takes multiple discrete operands and returns them all as its individual resu...
Definition ISDOpcodes.h:263
@ TargetConstantPool
Definition ISDOpcodes.h:191
@ MDNODE_SDNODE
MDNODE_SDNODE - This is a node that holdes an MDNode*, which is used to reference metadata in the IR.
@ STRICT_FSETCC
STRICT_FSETCC/STRICT_FSETCCS - Constrained versions of SETCC, used for floating-point operands only.
Definition ISDOpcodes.h:516
@ PTRADD
PTRADD represents pointer arithmetic semantics, for targets that opt in using shouldPreservePtrArith(...
@ DELETED_NODE
DELETED_NODE - This is an illegal value that is used to catch errors.
Definition ISDOpcodes.h:47
@ POISON
POISON - A poison node.
Definition ISDOpcodes.h:238
@ PARTIAL_REDUCE_SMLA
PARTIAL_REDUCE_[U|S]MLA(Accumulator, Input1, Input2) The partial reduction nodes sign or zero extend ...
@ MASK_BEFOREFIRST
Has one mask vector operand.
@ VECREDUCE_SEQ_FADD
Generic reduction nodes.
@ MLOAD
Masked load and store - consecutive vector load and store operations with additional mask operand tha...
@ VECREDUCE_FMINIMUMNUM
@ FGETSIGN
INT = FGETSIGN(FP) - Return the sign bit of the specified floating point value as an integer 0/1 valu...
Definition ISDOpcodes.h:543
@ SMUL_LOHI
SMUL_LOHI/UMUL_LOHI - Multiply two integers of type iN, producing a signed/unsigned value of type i[2...
Definition ISDOpcodes.h:277
@ INSERT_SUBVECTOR
INSERT_SUBVECTOR(VECTOR1, VECTOR2, IDX) - Returns a vector with VECTOR2 inserted into VECTOR1.
Definition ISDOpcodes.h:605
@ JUMP_TABLE_DEBUG_INFO
JUMP_TABLE_DEBUG_INFO - Jumptable debug info.
@ BSWAP
Byte Swap and Counting operators.
Definition ISDOpcodes.h:797
@ TargetBlockAddress
Definition ISDOpcodes.h:193
@ DEACTIVATION_SYMBOL
Untyped node storing deactivation symbol reference (DeactivationSymbolSDNode).
@ ATOMIC_STORE
OUTCHAIN = ATOMIC_STORE(INCHAIN, val, ptr) This corresponds to "store atomic" instruction.
@ ADDC
Carry-setting nodes for multiple precision addition and subtraction.
Definition ISDOpcodes.h:296
@ FMAD
FMAD - Perform a * b + c, while getting the same result as the separately rounded operations.
Definition ISDOpcodes.h:527
@ ADD
Simple integer binary arithmetic operators.
Definition ISDOpcodes.h:266
@ LOAD
LOAD and STORE have token chains as their first operand, then the same operands as an LLVM load/store...
@ ANY_EXTEND
ANY_EXTEND - Used for integer types. The high bits are undefined.
Definition ISDOpcodes.h:871
@ ATOMIC_LOAD_USUB_COND
@ FMA
FMA - Perform a * b + c with no intermediate rounding step.
Definition ISDOpcodes.h:523
@ FATAN2
FATAN2 - atan2, inspired by libm.
@ INTRINSIC_VOID
OUTCHAIN = INTRINSIC_VOID(INCHAIN, INTRINSICID, arg1, arg2, ...) This node represents a target intrin...
Definition ISDOpcodes.h:222
@ GlobalAddress
Definition ISDOpcodes.h:90
@ ATOMIC_CMP_SWAP_WITH_SUCCESS
Val, Success, OUTCHAIN = ATOMIC_CMP_SWAP_WITH_SUCCESS(INCHAIN, ptr, cmp, swap) N.b.
@ SINT_TO_FP
[SU]INT_TO_FP - These operators convert integers (whose interpreted sign depends on the first letter)...
Definition ISDOpcodes.h:898
@ CONCAT_VECTORS
CONCAT_VECTORS(VECTOR0, VECTOR1, ...) - Given a number of values of vector type with the same length ...
Definition ISDOpcodes.h:589
@ VECREDUCE_FMAX
FMIN/FMAX nodes can have flags, for NaN/NoNaN variants.
@ FADD
Simple binary floating point operators.
Definition ISDOpcodes.h:420
@ VECREDUCE_FMAXIMUM
FMINIMUM/FMAXIMUM nodes propatate NaNs and signed zeroes using the llvm.minimum and llvm....
@ ABS
ABS - Determine the unsigned absolute value of a signed integer value of the same bitwidth.
Definition ISDOpcodes.h:757
@ SIGN_EXTEND_VECTOR_INREG
SIGN_EXTEND_VECTOR_INREG(Vector) - This operator represents an in-register sign-extension of the low ...
Definition ISDOpcodes.h:928
@ FP16_TO_FP
FP16_TO_FP, FP_TO_FP16 - These operators are used to perform promotions and truncation for half-preci...
@ FMULADD
FMULADD - Performs a * b + c, with, or without, intermediate rounding.
Definition ISDOpcodes.h:533
@ BITCAST
BITCAST - This operator converts between integer, vector and FP values, as if the value was stored to...
@ BUILD_PAIR
BUILD_PAIR - This is the opposite of EXTRACT_ELEMENT in some ways.
Definition ISDOpcodes.h:256
@ CLMUL
Carry-less multiplication operations.
Definition ISDOpcodes.h:788
@ FLDEXP
FLDEXP - ldexp, inspired by libm (op0 * 2**op1).
@ BUILTIN_OP_END
BUILTIN_OP_END - This must be the last enum value in this list.
@ GlobalTLSAddress
Definition ISDOpcodes.h:91
@ SRCVALUE
SRCVALUE - This is a node type that holds a Value* that is used to make reference to a value in the L...
@ EH_LABEL
EH_LABEL - Represents a label in mid basic block used to track locations needed for debug and excepti...
@ ATOMIC_LOAD_USUB_SAT
@ CTLZ_ZERO_POISON
Definition ISDOpcodes.h:806
@ ANNOTATION_LABEL
ANNOTATION_LABEL - Represents a mid basic block label used by annotations.
@ PARTIAL_REDUCE_UMLA
@ SIGN_EXTEND
Conversion operators.
Definition ISDOpcodes.h:862
@ AVGCEILS
AVGCEILS/AVGCEILU - Rounding averaging add - Add two integers using an integer of type i[N+2],...
Definition ISDOpcodes.h:725
@ SCALAR_TO_VECTOR
SCALAR_TO_VECTOR(VAL) - This represents the operation of loading a scalar value into element 0 of the...
Definition ISDOpcodes.h:675
@ TargetExternalSymbol
Definition ISDOpcodes.h:192
@ VECREDUCE_FADD
These reductions have relaxed evaluation order semantics, and have a single vector operand.
@ TargetJumpTable
Definition ISDOpcodes.h:190
@ TargetIndex
TargetIndex - Like a constant pool entry, but with completely target-dependent semantics.
Definition ISDOpcodes.h:200
@ PARTIAL_REDUCE_FMLA
@ PREFETCH
PREFETCH - This corresponds to a prefetch intrinsic.
@ TRUNCATE_SSAT_U
Definition ISDOpcodes.h:891
@ VECREDUCE_FMAXIMUMNUM
FMINIMUMNUM/FMAXIMUMNUM nodes do not propagate NaNs and order signed zeroes using the llvm....
@ SETCCCARRY
Like SetCC, ops #0 and #1 are the LHS and RHS operands to compare, but op #2 is a boolean indicating ...
Definition ISDOpcodes.h:845
@ FNEG
Perform various unary floating-point operations inspired by libm.
@ BR_CC
BR_CC - Conditional branch.
@ SSUBO
Same for subtraction.
Definition ISDOpcodes.h:355
@ STEP_VECTOR
STEP_VECTOR(IMM) - Returns a scalable vector whose lanes are comprised of a linear sequence of unsign...
Definition ISDOpcodes.h:701
@ FCANONICALIZE
Returns platform specific canonical encoding of a floating point number.
Definition ISDOpcodes.h:546
@ IS_FPCLASS
Performs a check of floating point class property, defined by IEEE-754.
Definition ISDOpcodes.h:553
@ SSUBSAT
RESULT = [US]SUBSAT(LHS, RHS) - Perform saturation subtraction on 2 integers with the same bit width ...
Definition ISDOpcodes.h:377
@ SELECT
Select(COND, TRUEVAL, FALSEVAL).
Definition ISDOpcodes.h:814
@ ATOMIC_LOAD
Val, OUTCHAIN = ATOMIC_LOAD(INCHAIN, ptr) This corresponds to "load atomic" instruction.
@ UNDEF
UNDEF - An undefined node.
Definition ISDOpcodes.h:235
@ EXTRACT_ELEMENT
EXTRACT_ELEMENT - This is used to get the lower or upper (determined by a Constant,...
Definition ISDOpcodes.h:249
@ SPLAT_VECTOR
SPLAT_VECTOR(VAL) - Returns a vector with the scalar value VAL duplicated in all lanes.
Definition ISDOpcodes.h:682
@ AssertAlign
AssertAlign - These nodes record if a register contains a value that has a known alignment and the tr...
Definition ISDOpcodes.h:71
@ GET_ACTIVE_LANE_MASK
GET_ACTIVE_LANE_MASK - this corrosponds to the llvm.get.active.lane.mask intrinsic.
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
@ CopyFromReg
CopyFromReg - This node indicates that the input value is a virtual or physical register that is defi...
Definition ISDOpcodes.h:232
@ SADDO
RESULT, BOOL = [SU]ADDO(LHS, RHS) - Overflow-aware nodes for addition.
Definition ISDOpcodes.h:351
@ TargetGlobalAddress
TargetGlobalAddress - Like GlobalAddress, but the DAG does no folding or anything else with this node...
Definition ISDOpcodes.h:187
@ ARITH_FENCE
ARITH_FENCE - This corresponds to a arithmetic fence intrinsic.
@ CTLS
Count leading redundant sign bits.
Definition ISDOpcodes.h:810
@ VECREDUCE_ADD
Integer reductions may have a result type larger than the vector element type.
@ MULHU
MULHU/MULHS - Multiply high - Multiply two integers of type iN, producing an unsigned/signed value of...
Definition ISDOpcodes.h:714
@ ATOMIC_LOAD_FMAXIMUM
@ SHL
Shift and rotation operations.
Definition ISDOpcodes.h:779
@ AssertNoFPClass
AssertNoFPClass - These nodes record if a register contains a float value that is known to be not som...
Definition ISDOpcodes.h:80
@ VECTOR_SHUFFLE
VECTOR_SHUFFLE(VEC1, VEC2) - Returns a vector, of the same type as VEC1/VEC2.
Definition ISDOpcodes.h:659
@ EXTRACT_SUBVECTOR
EXTRACT_SUBVECTOR(VECTOR, IDX) - Returns a subvector from VECTOR.
Definition ISDOpcodes.h:619
@ FMINNUM_IEEE
FMINNUM_IEEE/FMAXNUM_IEEE - Perform floating-point minimumNumber or maximumNumber on two values,...
@ EntryToken
EntryToken - This is the marker used to indicate the start of a region.
Definition ISDOpcodes.h:50
@ EXTRACT_VECTOR_ELT
EXTRACT_VECTOR_ELT(VECTOR, IDX) - Returns a single element from VECTOR identified by the (potentially...
Definition ISDOpcodes.h:581
@ CopyToReg
CopyToReg - This node has three operands: a chain, a register number to set to this value,...
Definition ISDOpcodes.h:226
@ ZERO_EXTEND
ZERO_EXTEND - Used for integer types, zeroing the new bits.
Definition ISDOpcodes.h:868
@ TargetConstantFP
Definition ISDOpcodes.h:182
@ SELECT_CC
Select with condition operator - This selects between a true value and a false value (ops #2 and #3) ...
Definition ISDOpcodes.h:829
@ VSCALE
VSCALE(IMM) - Returns the runtime scaling factor used to calculate the number of elements within a sc...
@ ATOMIC_CMP_SWAP
Val, OUTCHAIN = ATOMIC_CMP_SWAP(INCHAIN, ptr, cmp, swap) For double-word atomic operations: ValLo,...
@ FMINNUM
FMINNUM/FMAXNUM - Perform floating-point minimum maximum on two values, following IEEE-754 definition...
@ SSHLSAT
RESULT = [US]SHLSAT(LHS, RHS) - Perform saturation left shift.
Definition ISDOpcodes.h:389
@ SMULO
Same for multiplication.
Definition ISDOpcodes.h:359
@ ATOMIC_LOAD_FMINIMUM
@ TargetFrameIndex
Definition ISDOpcodes.h:189
@ VECTOR_SPLICE_LEFT
VECTOR_SPLICE_LEFT(VEC1, VEC2, OFFSET) - Shifts CONCAT_VECTORS(VEC1, VEC2) left by OFFSET elements an...
Definition ISDOpcodes.h:663
@ ANY_EXTEND_VECTOR_INREG
ANY_EXTEND_VECTOR_INREG(Vector) - This operator represents an in-register any-extension of the low la...
Definition ISDOpcodes.h:917
@ SIGN_EXTEND_INREG
SIGN_EXTEND_INREG - This operator atomically performs a SHL/SRA pair to sign extend a small value in ...
Definition ISDOpcodes.h:906
@ SMIN
[US]{MIN/MAX} - Binary minimum or maximum of signed or unsigned integers.
Definition ISDOpcodes.h:737
@ MASKED_UDIV
Masked vector arithmetic that returns poison on disabled lanes.
@ LIFETIME_START
This corresponds to the llvm.lifetime.
@ FP_EXTEND
X = FP_EXTEND(Y) - Extend a smaller FP type into a larger FP type.
Definition ISDOpcodes.h:996
@ VSELECT
Select with a vector condition (op #0) and two vector operands (ops #1 and #2), returning a vector re...
Definition ISDOpcodes.h:823
@ UADDO_CARRY
Carry-using nodes for multiple precision addition and subtraction.
Definition ISDOpcodes.h:331
@ MGATHER
Masked gather and scatter - load and store operations for a vector of random addresses with additiona...
@ HANDLENODE
HANDLENODE node - Used as a handle for various purposes.
@ BF16_TO_FP
BF16_TO_FP, FP_TO_BF16 - These operators are used to perform promotions and truncation for bfloat16.
@ ATOMIC_LOAD_UDEC_WRAP
@ PEXT
Parallel bit extract (compress) and parallel bit deposit (expand).
Definition ISDOpcodes.h:793
@ STRICT_FP_ROUND
X = STRICT_FP_ROUND(Y, TRUNC) - Rounding 'Y' from a larger floating point type down to the precision ...
Definition ISDOpcodes.h:505
@ FMINIMUM
FMINIMUM/FMAXIMUM - NaN-propagating minimum/maximum that also treat -0.0 as less than 0....
@ FP_TO_SINT
FP_TO_[US]INT - Convert a floating point value to a signed or unsigned integer.
Definition ISDOpcodes.h:944
@ TargetConstant
TargetConstant* - Like Constant*, but the DAG does not do any folding, simplification,...
Definition ISDOpcodes.h:181
@ STRICT_FP_EXTEND
X = STRICT_FP_EXTEND(Y) - Extend a smaller FP type into a larger FP type.
Definition ISDOpcodes.h:510
@ AND
Bitwise operators - logical and, logical or, logical xor.
Definition ISDOpcodes.h:749
@ INTRINSIC_WO_CHAIN
RESULT = INTRINSIC_WO_CHAIN(INTRINSICID, arg1, arg2, ...) This node represents a target intrinsic fun...
Definition ISDOpcodes.h:207
@ GET_FPENV_MEM
Gets the current floating-point environment.
@ PSEUDO_PROBE
Pseudo probe for AutoFDO, as a place holder in a basic block to improve the sample counts quality.
@ SCMP
[US]CMP - 3-way comparison of signed or unsigned integers.
Definition ISDOpcodes.h:745
@ AVGFLOORS
AVGFLOORS/AVGFLOORU - Averaging add - Add two integers using an integer of type i[N+1],...
Definition ISDOpcodes.h:720
@ VECTOR_SPLICE_RIGHT
VECTOR_SPLICE_RIGHT(VEC1, VEC2, OFFSET) - Shifts CONCAT_VECTORS(VEC1,VEC2) right by OFFSET elements a...
Definition ISDOpcodes.h:667
@ ADDE
Carry-using nodes for multiple precision addition and subtraction.
Definition ISDOpcodes.h:306
@ SPLAT_VECTOR_PARTS
SPLAT_VECTOR_PARTS(SCALAR1, SCALAR2, ...) - Returns a vector with the scalar values joined together a...
Definition ISDOpcodes.h:691
@ FREEZE
FREEZE - FREEZE(VAL) returns an arbitrary value if VAL is UNDEF (or is evaluated to UNDEF),...
Definition ISDOpcodes.h:243
@ INSERT_VECTOR_ELT
INSERT_VECTOR_ELT(VECTOR, VAL, IDX) - Returns VECTOR with the element at IDX replaced with VAL.
Definition ISDOpcodes.h:570
@ TokenFactor
TokenFactor - This node takes multiple tokens as input and produces a single token result.
Definition ISDOpcodes.h:55
@ ATOMIC_SWAP
Val, OUTCHAIN = ATOMIC_SWAP(INCHAIN, ptr, amt) Val, OUTCHAIN = ATOMIC_LOAD_[OpName](INCHAIN,...
@ CTTZ_ZERO_POISON
Bit counting operators with a poisoned result for zero inputs.
Definition ISDOpcodes.h:805
@ ExternalSymbol
Definition ISDOpcodes.h:95
@ FFREXP
FFREXP - frexp, extract fractional and exponent component of a floating-point value.
@ FP_ROUND
X = FP_ROUND(Y, TRUNC) - Rounding 'Y' from a larger floating point type down to the precision of the ...
Definition ISDOpcodes.h:977
@ VECTOR_COMPRESS
VECTOR_COMPRESS(Vec, Mask, Passthru) consecutively place vector elements based on mask e....
Definition ISDOpcodes.h:709
@ ZERO_EXTEND_VECTOR_INREG
ZERO_EXTEND_VECTOR_INREG(Vector) - This operator represents an in-register zero-extension of the low ...
Definition ISDOpcodes.h:939
@ ADDRSPACECAST
ADDRSPACECAST - This operator converts between pointers of different address spaces.
@ EXPERIMENTAL_VECTOR_HISTOGRAM
Experimental vector histogram intrinsic Operands: Input Chain, Inc, Mask, Base, Index,...
@ FP_TO_SINT_SAT
FP_TO_[US]INT_SAT - Convert floating point value in operand 0 to a signed or unsigned scalar integer ...
Definition ISDOpcodes.h:963
@ VECREDUCE_FMINIMUM
@ TRUNCATE
TRUNCATE - Completely drop the high bits.
Definition ISDOpcodes.h:874
@ VAARG
VAARG - VAARG has four operands: an input chain, a pointer, a SRCVALUE, and the alignment.
@ VECREDUCE_SEQ_FMUL
@ SHL_PARTS
SHL_PARTS/SRA_PARTS/SRL_PARTS - These operators are used for expanded integer shift operations.
Definition ISDOpcodes.h:851
@ AssertSext
AssertSext, AssertZext - These nodes record if a register contains a value that has already been zero...
Definition ISDOpcodes.h:64
@ ATOMIC_LOAD_UINC_WRAP
@ FCOPYSIGN
FCOPYSIGN(X, Y) - Return the value of X with the sign of Y.
Definition ISDOpcodes.h:539
@ PARTIAL_REDUCE_SUMLA
@ SADDSAT
RESULT = [US]ADDSAT(LHS, RHS) - Perform saturation addition on 2 integers with the same bit width (W)...
Definition ISDOpcodes.h:368
@ VECTOR_REPEAT
VECTOR_REPEAT(FIXED_LENGTH_VECTOR) Repeatedly copies the elements of the source fixed-length vector t...
Definition ISDOpcodes.h:645
@ SET_FPENV_MEM
Sets the current floating point environment.
@ FMINIMUMNUM
FMINIMUMNUM/FMAXIMUMNUM - minimumnum/maximumnum that is same with FMINNUM_IEEE and FMAXNUM_IEEE besid...
@ TRUNCATE_SSAT_S
TRUNCATE_[SU]SAT_[SU] - Truncate for saturated operand [SU] located in middle, prefix for SAT means i...
Definition ISDOpcodes.h:889
@ ABDS
ABDS/ABDU - Absolute difference - Return the absolute difference between two numbers interpreted as s...
Definition ISDOpcodes.h:732
@ TRUNCATE_USAT_U
Definition ISDOpcodes.h:893
@ SADDO_CARRY
Carry-using overflow-aware nodes for multiple precision addition and subtraction.
Definition ISDOpcodes.h:341
@ INTRINSIC_W_CHAIN
RESULT,OUTCHAIN = INTRINSIC_W_CHAIN(INCHAIN, INTRINSICID, arg1, ...) This node represents a target in...
Definition ISDOpcodes.h:215
@ TargetGlobalTLSAddress
Definition ISDOpcodes.h:188
@ ABS_MIN_POISON
ABS with a poison result for INT_MIN.
Definition ISDOpcodes.h:761
@ BUILD_VECTOR
BUILD_VECTOR(ELT0, ELT1, ELT2, ELT3,...) - Return a fixed-width vector with the specified,...
Definition ISDOpcodes.h:561
LLVM_ABI NodeType getOppositeSignednessMinMaxOpcode(unsigned MinMaxOpc)
Given a MinMaxOpc of ISD::(U|S)MIN or ISD::(U|S)MAX, returns the corresponding opcode with the opposi...
LLVM_ABI bool isBuildVectorOfConstantSDNodes(const SDNode *N)
Return true if the specified node is a BUILD_VECTOR node of all ConstantSDNode or undef.
LLVM_ABI NodeType getExtForLoadExtType(bool IsFP, LoadExtType)
bool isZEXTLoad(const SDNode *N)
Returns true if the specified node is a ZEXTLOAD.
bool isExtOpcode(unsigned Opcode)
LLVM_ABI bool isConstantSplatVectorAllZeros(const SDNode *N, bool BuildVectorOnly=false)
Return true if the specified node is a BUILD_VECTOR or SPLAT_VECTOR where all of the elements are 0 o...
LLVM_ABI NodeType getUnmaskedBinOpOpcode(unsigned MaskedOpc)
Given a MaskedOpc of ISD::MASKED_(U|S)(DIV|REM), returns the unmasked ISD::(U|S)(DIV|REM).
LLVM_ABI bool isVectorShrinkable(const SDNode *N, unsigned NewEltSize, bool Signed)
Returns true if the specified node is a vector where all elements can be truncated to the specified e...
LLVM_ABI bool isVPBinaryOp(unsigned Opcode)
Whether this is a vector-predicated binary operation opcode.
LLVM_ABI CondCode getSetCCInverse(CondCode Operation, EVT Type)
Return the operation corresponding to !(X op Y), where 'op' is a valid SetCC operation.
LLVM_ABI std::optional< unsigned > getBaseOpcodeForVP(unsigned Opcode, bool hasFPExcept)
Translate this VP Opcode to its corresponding non-VP Opcode.
bool isBitwiseLogicOp(unsigned Opcode)
Whether this is bitwise logic opcode.
bool isTrueWhenEqual(CondCode Cond)
Return true if the specified condition returns true if the two operands to the condition are equal.
LLVM_ABI std::optional< unsigned > getVPMaskIdx(unsigned Opcode)
The operand position of the vector mask.
unsigned getUnorderedFlavor(CondCode Cond)
This function returns 0 if the condition is always false if an operand is a NaN, 1 if the condition i...
LLVM_ABI std::optional< unsigned > getVPExplicitVectorLengthIdx(unsigned Opcode)
The operand position of the explicit vector length parameter.
LLVM_ABI bool matchBinaryPredicate(SDValue LHS, SDValue RHS, const APInt &DemandedElts, std::function< bool(ConstantSDNode *, ConstantSDNode *)> Match, bool AllowUndefs=false, bool AllowTypeMismatch=false)
Attempt to match a binary predicate against a pair of scalar/splat constants or every element of a pa...
bool isEXTLoad(const SDNode *N)
Returns true if the specified node is a EXTLOAD.
LLVM_ABI bool allOperandsUndef(const SDNode *N)
Return true if the node has at least one operand and all operands of the specified node are ISD::UNDE...
LLVM_ABI bool isFreezeUndef(const SDNode *N)
Return true if the specified node is FREEZE(UNDEF).
LLVM_ABI CondCode getSetCCSwappedOperands(CondCode Operation)
Return the operation corresponding to (Y op X) when given the operation for (X op Y).
LLVM_ABI std::optional< unsigned > getVPForBaseOpcode(unsigned Opcode)
Translate this non-VP Opcode to its corresponding VP Opcode.
MemIndexType
MemIndexType enum - This enum defines how to interpret MGATHER/SCATTER's index parameter when calcula...
LLVM_ABI bool isBuildVectorAllZeros(const SDNode *N)
Return true if the specified node is a BUILD_VECTOR where all of the elements are 0 or undef.
LLVM_ABI bool isConstantSplatVector(const SDNode *N, APInt &SplatValue)
Node predicates.
LLVM_ABI NodeType getInverseMinMaxOpcode(unsigned MinMaxOpc)
Given a MinMaxOpc of ISD::(U|S)MIN or ISD::(U|S)MAX, returns ISD::(U|S)MAX and ISD::(U|S)MIN,...
LLVM_ABI bool isVPReduction(unsigned Opcode)
Whether this is a vector-predicated reduction opcode.
MemIndexedMode
MemIndexedMode enum - This enum defines the load / store indexed addressing modes.
LLVM_ABI bool isBuildVectorOfConstantFPSDNodes(const SDNode *N)
Return true if the specified node is a BUILD_VECTOR node of all ConstantFPSDNode or undef.
bool isSEXTLoad(const SDNode *N)
Returns true if the specified node is a SEXTLOAD.
CondCode
ISD::CondCode enum - These are ordered carefully to make the bitfields below work out,...
LLVM_ABI bool isBuildVectorAllOnes(const SDNode *N)
Return true if the specified node is a BUILD_VECTOR where all of the elements are ~0 or undef.
LLVM_ABI NodeType getVecReduceBaseOpcode(unsigned VecReduceOpcode)
Get underlying scalar opcode for VECREDUCE opcode.
LoadExtType
LoadExtType enum - This enum defines the three variants of LOADEXT (load with extension).
LLVM_ABI bool isVPOpcode(unsigned Opcode)
Whether this is a vector-predicated Opcode.
bool matchUnaryPredicate(SDValue Op, const APInt &DemandedElts, std::function< bool(ConstantSDNode *)> Match, bool AllowUndefs=false, bool AllowTruncation=false)
Hook for matching ConstantSDNode predicate.
LLVM_ABI CondCode getSetCCOrOperation(CondCode Op1, CondCode Op2, EVT Type)
Return the result of a logical OR between different comparisons of identical values: ((X op1 Y) | (X ...
BinaryOp_match< SpecificConstantMatch, SrcTy, TargetOpcode::G_SUB > m_Neg(const SrcTy &&Src)
Matches a register negated by a G_SUB.
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
match_deferred< Value > m_Deferred(Value *const &V)
Like m_Specific(), but works if the specific value to match is determined as part of the same match()...
auto m_Value()
Match an arbitrary value and ignore it.
BinaryOp_match< LHS, RHS, Instruction::Sub > m_Sub(const LHS &L, const RHS &R)
LLVM_ABI Libcall getMEMCPY_ELEMENT_UNORDERED_ATOMIC(uint64_t ElementSize)
getMEMCPY_ELEMENT_UNORDERED_ATOMIC - Return MEMCPY_ELEMENT_UNORDERED_ATOMIC_* value for the given ele...
LLVM_ABI Libcall getMEMSET_ELEMENT_UNORDERED_ATOMIC(uint64_t ElementSize)
getMEMSET_ELEMENT_UNORDERED_ATOMIC - Return MEMSET_ELEMENT_UNORDERED_ATOMIC_* value for the given ele...
LLVM_ABI Libcall getMEMMOVE_ELEMENT_UNORDERED_ATOMIC(uint64_t ElementSize)
getMEMMOVE_ELEMENT_UNORDERED_ATOMIC - Return MEMMOVE_ELEMENT_UNORDERED_ATOMIC_* value for the given e...
bool sd_match(SDValue N, Pattern &&P)
LLVM_ABI unsigned rot(unsigned SrcSignBits, unsigned BitWidth, std::optional< APInt > RotAmt, bool IsRotateRight)
Compute the number of sign bits after rotating a value.
initializer< Ty > init(const Ty &Val)
@ DW_OP_LLVM_arg
Only used in LLVM metadata.
Definition Dwarf.h:149
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract(Y &&MD)
Extract a Value from Metadata.
Definition Metadata.h:679
NodeAddr< NodeBase * > Node
Definition RDFGraph.h:381
This is an optimization pass for GlobalISel generic memory operations.
GenericUniformityInfo< SSAContext > UniformityInfo
unsigned Log2_32_Ceil(uint32_t Value)
Return the ceil log base 2 of the specified value, 32 if the value is zero.
Definition MathExtras.h:339
@ Offset
Definition DWP.cpp:577
bool operator<(int64_t V1, const APSInt &V2)
Definition APSInt.h:360
LLVM_ABI ISD::CondCode getICmpCondCode(ICmpInst::Predicate Pred)
getICmpCondCode - Return the ISD condition code corresponding to the given LLVM IR integer condition ...
Definition Analysis.cpp:248
void fill(R &&Range, T &&Value)
Provide wrappers to std::fill which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1775
LLVM_ABI SDValue peekThroughExtractSubvectors(SDValue V)
Return the non-extracted vector source operand of V if it exists.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
LLVM_ABI bool isNullConstant(SDValue V)
Returns true if V is a constant integer zero.
LLVM_ABI bool isAllOnesOrAllOnesSplat(const MachineInstr &MI, const MachineRegisterInfo &MRI, bool AllowUndefs=false)
Return true if the value is a constant -1 integer or a splatted vector of a constant -1 integer (with...
Definition Utils.cpp:1557
LLVM_ABI SDValue getBitwiseNotOperand(SDValue V, SDValue Mask, bool AllowUndefs)
If V is a bitwise not, returns the inverted operand.
@ Known
Known to have no common set bits.
@ Undef
Value of the register doesn't matter.
LLVM_ABI SDValue peekThroughBitcasts(SDValue V)
Return the non-bitcasted source operand of V if it exists.
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2570
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
int countr_one(T Value)
Count the number of ones from the least significant bit to the first zero bit.
Definition bit.h:315
@ Store
The extracted value is stored (ExtractElement only).
bool isIntOrFPConstant(SDValue V)
Return true if V is either a integer or FP constant.
auto dyn_cast_if_present(const Y &Val)
dyn_cast_if_present<X> - Functionally identical to dyn_cast, except that a null (or none in the case ...
Definition Casting.h:732
LLVM_ABI bool getConstantDataArrayInfo(const Value *V, ConstantDataArraySlice &Slice, unsigned ElementSize, uint64_t Offset=0)
Returns true if the value V is a pointer into a ConstantDataArray.
LLVM_ABI bool isOneOrOneSplatFP(SDValue V, bool AllowUndefs=false)
Return true if the value is a constant floating-point value, or a splatted vector of a constant float...
int bit_width(T Value)
Returns the number of bits needed to represent Value if Value is nonzero.
Definition bit.h:325
LLVM_READONLY APFloat maximum(const APFloat &A, const APFloat &B)
Implements IEEE 754-2019 maximum semantics.
Definition APFloat.h:1801
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2224
constexpr bool isUIntN(unsigned N, uint64_t x)
Checks if an unsigned integer fits into the given (dynamic) bit width.
Definition MathExtras.h:244
LLVM_ABI bool shouldOptimizeForSize(const MachineFunction *MF, ProfileSummaryInfo *PSI, const MachineBlockFrequencyInfo *BFI, PGSOQueryType QueryType=PGSOQueryType::Other)
Returns true if machine function MF is suggested to be size-optimized based on the profile.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:649
LLVM_ABI void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
auto cast_or_null(const Y &Val)
Definition Casting.h:714
LLVM_ABI bool isNullOrNullSplat(const MachineInstr &MI, const MachineRegisterInfo &MRI, bool AllowUndefs=false)
Return true if the value is a constant 0 integer or a splatted vector of a constant 0 integer (with n...
Definition Utils.cpp:1539
LLVM_ABI bool isMinSignedConstant(SDValue V)
Returns true if V is a constant min signed integer value.
LLVM_ABI ConstantFPSDNode * isConstOrConstSplatFP(SDValue N, bool AllowUndefs=false)
Returns the SDNode if it is a constant splat BuildVector or constant float.
LLVM_ABI ConstantRange getConstantRangeFromMetadata(const MDNode &RangeMD)
Parse out a conservative ConstantRange from !range metadata.
APFloat frexp(const APFloat &X, int &Exp, APFloat::roundingMode RM)
Equivalent of C standard library function.
Definition APFloat.h:1713
int countr_zero(T Val)
Count number of 0's from the least significant bit to the most stopping at the first 1.
Definition bit.h:204
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
LLVM_ABI bool getShuffleDemandedElts(int SrcWidth, ArrayRef< int > Mask, const APInt &DemandedElts, APInt &DemandedLHS, APInt &DemandedRHS, bool AllowUndefElts=false)
Transform a shuffle mask's output demanded element mask into demanded element masks for the 2 operand...
LLVM_READONLY APFloat maxnum(const APFloat &A, const APFloat &B)
Implements IEEE-754 2008 maxNum semantics.
Definition APFloat.h:1756
unsigned Log2_32(uint32_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
Definition MathExtras.h:326
LLVM_ABI bool isBitwiseNot(SDValue V, bool AllowUndefs=false)
Returns true if V is a bitwise not operation.
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
LLVM_ABI SDValue peekThroughInsertVectorElt(SDValue V, const APInt &DemandedElts)
Recursively peek through INSERT_VECTOR_ELT nodes, returning the source vector operand of V,...
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition MathExtras.h:280
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
LLVM_ABI void checkForCycles(const SelectionDAG *DAG, bool force=false)
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
LLVM_READONLY APFloat minimumnum(const APFloat &A, const APFloat &B)
Implements IEEE 754-2019 minimumNumber semantics.
Definition APFloat.h:1787
FPClassTest
Floating-point class tests, supported by 'is_fpclass' intrinsic.
LLVM_ABI const MDNode * getMemCacheHintMetadata(const Instruction &I, unsigned OperandNo=0)
Return the cache hint metadata node for memory operand OperandNo on I, or nullptr when the instructio...
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI SDValue peekThroughTruncates(SDValue V)
Return the non-truncated source operand of V if it exists.
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1769
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
constexpr std::underlying_type_t< Enum > to_underlying(Enum E)
Returns underlying integer value of an enum.
LLVM_ABI ConstantRange getVScaleRange(const Function *F, unsigned BitWidth)
Determine the possible constant range of vscale with the given bit width, based on the vscale_range f...
LLVM_ABI SDValue peekThroughOneUseBitcasts(SDValue V)
Return the non-bitcasted and one-use source operand of V if it exists.
CodeGenOptLevel
Code generation optimization level.
Definition CodeGen.h:227
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
bool includesPoison(UndefPoisonKind Kind)
Returns true if Kind includes the Poison bit.
Definition UndefPoison.h:27
LLVM_ABI bool isOneOrOneSplat(SDValue V, bool AllowUndefs=false)
Return true if the value is a constant 1 integer or a splatted vector of a constant 1 integer (with n...
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
@ Other
Any other memory.
Definition ModRef.h:68
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
Definition ModRef.h:74
bool includesUndef(UndefPoisonKind Kind)
Returns true if Kind includes the Undef bit.
Definition UndefPoison.h:33
LLVM_READONLY APFloat minnum(const APFloat &A, const APFloat &B)
Implements IEEE-754 2008 minNum semantics.
Definition APFloat.h:1737
@ Mul
Product of integers.
@ Sub
Subtraction of integers.
@ Fast
Assign the register banks as fast as possible (default).
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
LLVM_ABI bool isNullConstantOrUndef(SDValue V)
Returns true if V is a constant integer zero or an UNDEF node.
IntPtrTy
Definition InstrProf.h:82
LLVM_ABI bool isInTailCallPosition(const CallBase &Call, const TargetMachine &TM, bool ReturnsFirstArg=false)
Test if the given instruction is in a position to be optimized with a tail-call.
Definition Analysis.cpp:656
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
LLVM_ABI ConstantSDNode * isConstOrConstSplat(SDValue N, bool AllowUndefs=false, bool AllowTruncation=false)
Returns the SDNode if it is a constant splat BuildVector or constant int.
OutputIt copy(R &&Range, OutputIt Out)
Definition STLExtras.h:1901
constexpr unsigned BitWidth
LLVM_ABI bool funcReturnsFirstArgOfCall(const CallInst &CI)
Returns true if the parent of CI returns CI's first argument after calling CI.
Definition Analysis.cpp:836
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI bool isZeroOrZeroSplat(SDValue N, bool AllowUndefs=false)
Return true if the value is a constant 0 integer or a splatted vector of a constant 0 integer (with n...
constexpr auto seq(T Begin, T End)
Iterate over an integral type from Begin up to - but not including - End.
Definition Sequence.h:341
LLVM_ABI bool isOneConstant(SDValue V)
Returns true if V is a constant integer one.
UndefPoisonKind
Enumeration to track whether we are interested in Undef, Poison, or both.
Definition UndefPoison.h:20
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
Align commonAlignment(Align A, uint64_t Offset)
Returns the alignment that satisfies both alignments.
Definition Alignment.h:206
LLVM_ABI bool isNullFPConstant(SDValue V)
Returns true if V is an FP constant with a value of positive zero.
constexpr int64_t SignExtend64(uint64_t x)
Sign-extend the number in the bottom B bits of X to a 64-bit integer.
Definition MathExtras.h:567
unsigned Log2(Align A)
Returns the log2 of the alignment.
Definition Alignment.h:202
LLVM_ABI bool isZeroOrZeroSplatFP(SDValue N, bool AllowUndefs=false)
Return true if the value is a constant (+/-)0.0 floating-point value or a splatted vector thereof (wi...
bool equal(L &&LRange, R &&RRange)
Wrapper function around std::equal to detect if pair-wise elements between two ranges are the same.
Definition STLExtras.h:2162
LLVM_ABI void computeKnownBitsFromRangeMetadata(const MDNode &Ranges, KnownBits &Known)
Compute known bits from the range metadata.
LLVM_READONLY APFloat minimum(const APFloat &A, const APFloat &B)
Implements IEEE 754-2019 minimum semantics.
Definition APFloat.h:1774
LLVM_READONLY APFloat maximumnum(const APFloat &A, const APFloat &B)
Implements IEEE 754-2019 maximumNumber semantics.
Definition APFloat.h:1814
LLVM_ABI bool isOnesOrOnesSplat(SDValue N, bool AllowUndefs=false)
Return true if the value is a constant 1 integer or a splatted vector of a constant 1 integer (with n...
LLVM_ABI bool isAllOnesConstant(SDValue V)
Returns true if V is an integer constant with all bits set.
constexpr uint64_t NextPowerOf2(uint64_t A)
Returns the next power of two (in 64-bits) that is strictly greater than A.
Definition MathExtras.h:368
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
Definition Error.cpp:177
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:880
#define N
A collection of metadata nodes that might be associated with a memory access used by the alias-analys...
Definition Metadata.h:774
MDNode * TBAAStruct
The tag for type-based alias analysis (tbaa struct).
Definition Metadata.h:794
MDNode * TBAA
The tag for type-based alias analysis.
Definition Metadata.h:791
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
constexpr uint64_t value() const
This is a hole in the type system and should not be abused.
Definition Alignment.h:82
static constexpr Align fromLog2(unsigned Log2Value)
Returns an alignment of 1 << Log2Value bytes.
Definition Alignment.h:73
Represents offset+length into a ConstantDataArray.
uint64_t Length
Length of the slice.
uint64_t Offset
Slice starts at this Offset.
void move(uint64_t Delta)
Moves the Offset and adjusts Length accordingly.
const ConstantDataArray * Array
ConstantDataArray pointer.
Extended Value Type.
Definition ValueTypes.h:35
TypeSize getStoreSize() const
Return the number of bytes overwritten by a store of the specified value type.
Definition ValueTypes.h:418
bool isSimple() const
Test if the given EVT is simple (as opposed to being extended).
Definition ValueTypes.h:145
intptr_t getRawBits() const
Definition ValueTypes.h:543
static EVT getVectorVT(LLVMContext &Context, EVT VT, unsigned NumElements, bool IsScalable=false)
Returns the EVT that represents a vector NumElements in length, where each element is of type VT.
Definition ValueTypes.h:70
EVT changeTypeToInteger() const
Return the type converted to an equivalently sized integer or vector with integer element type.
Definition ValueTypes.h:129
bool bitsGT(EVT VT) const
Return true if this has more bits than VT.
Definition ValueTypes.h:307
bool bitsLT(EVT VT) const
Return true if this has less bits than VT.
Definition ValueTypes.h:323
bool isFloatingPoint() const
Return true if this is a FP or a vector FP type.
Definition ValueTypes.h:155
ElementCount getVectorElementCount() const
Definition ValueTypes.h:373
TypeSize getSizeInBits() const
Return the size of the specified value type in bits.
Definition ValueTypes.h:396
unsigned getVectorMinNumElements() const
Given a vector type, return the minimum number of elements it contains.
Definition ValueTypes.h:382
uint64_t getScalarSizeInBits() const
Definition ValueTypes.h:408
MVT getSimpleVT() const
Return the SimpleValueType held in the specified simple EVT.
Definition ValueTypes.h:339
static EVT getIntegerVT(LLVMContext &Context, unsigned BitWidth)
Returns the EVT that represents an integer with the given number of bits.
Definition ValueTypes.h:61
bool isFixedLengthVector() const
Definition ValueTypes.h:199
bool isVector() const
Return true if this is a vector value type.
Definition ValueTypes.h:176
EVT getScalarType() const
If this is a vector type, return the element type, otherwise return this.
Definition ValueTypes.h:346
bool bitsGE(EVT VT) const
Return true if this has no less bits than VT.
Definition ValueTypes.h:315
bool bitsEq(EVT VT) const
Return true if this has the same number of bits as VT.
Definition ValueTypes.h:279
LLVM_ABI Type * getTypeForEVT(LLVMContext &Context) const
This method returns an LLVM type corresponding to the specified EVT.
bool isScalableVector() const
Return true if this is a vector type where the runtime length is machine dependent.
Definition ValueTypes.h:187
EVT getVectorElementType() const
Given a vector type, return the type of each element.
Definition ValueTypes.h:351
bool isExtended() const
Test if the given EVT is extended (as opposed to being simple).
Definition ValueTypes.h:150
LLVM_ABI const fltSemantics & getFltSemantics() const
Returns an APFloat semantics tag appropriate for the value type.
unsigned getVectorNumElements() const
Given a vector type, return the number of elements it contains.
Definition ValueTypes.h:359
bool bitsLE(EVT VT) const
Return true if this has no more bits than VT.
Definition ValueTypes.h:331
EVT getHalfNumVectorElementsVT(LLVMContext &Context) const
Definition ValueTypes.h:484
bool isInteger() const
Return true if this is an integer or a vector integer type.
Definition ValueTypes.h:160
static KnownBits makeConstant(const APInt &C)
Create known bits from a known constant.
Definition KnownBits.h:315
static LLVM_ABI KnownBits mulhu(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits from zero-extended multiply-hi.
static LLVM_ABI KnownBits smax(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for smax(LHS, RHS).
bool isNonNegative() const
Returns true if this value is known to be non-negative.
Definition KnownBits.h:106
bool isZero() const
Returns true if value is all zero.
Definition KnownBits.h:78
static LLVM_ABI KnownBits usub_sat(const KnownBits &LHS, const KnownBits &RHS)
Compute knownbits resulting from llvm.usub.sat(LHS, RHS)
static LLVM_ABI KnownBits ashr(const KnownBits &LHS, const KnownBits &RHS, bool ShAmtNonZero=false, bool Exact=false)
Compute known bits for ashr(LHS, RHS).
static LLVM_ABI KnownBits urem(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for urem(LHS, RHS).
unsigned countMaxTrailingZeros() const
Returns the maximum number of trailing zero bits possible.
Definition KnownBits.h:288
static LLVM_ABI std::optional< bool > ne(const KnownBits &LHS, const KnownBits &RHS)
Determine if these known bits always give the same ICMP_NE result.
KnownBits trunc(unsigned BitWidth) const
Return known bits for a truncation of the value we're tracking.
Definition KnownBits.h:165
KnownBits byteSwap() const
Definition KnownBits.h:559
static LLVM_ABI KnownBits fshl(const KnownBits &LHS, const KnownBits &RHS, const APInt &Amt)
Compute known bits for fshl(LHS, RHS, Amt).
unsigned countMaxPopulation() const
Returns the maximum number of bits that could be one.
Definition KnownBits.h:303
void setAllZero()
Make all bits known to be zero and discard any previous information.
Definition KnownBits.h:84
KnownBits reverseBits() const
Definition KnownBits.h:563
KnownBits concat(const KnownBits &Lo) const
Concatenate the bits from Lo onto the bottom of *this.
Definition KnownBits.h:247
unsigned getBitWidth() const
Get the bit width of this value.
Definition KnownBits.h:44
static LLVM_ABI KnownBits umax(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for umax(LHS, RHS).
KnownBits zext(unsigned BitWidth) const
Return known bits for a zero extension of the value we're tracking.
Definition KnownBits.h:176
void resetAll()
Resets the known state of all bits.
Definition KnownBits.h:72
static KnownBits add(const KnownBits &LHS, const KnownBits &RHS, bool NSW=false, bool NUW=false, bool SelfAdd=false)
Compute knownbits resulting from addition of LHS and RHS.
Definition KnownBits.h:361
static LLVM_ABI KnownBits lshr(const KnownBits &LHS, const KnownBits &RHS, bool ShAmtNonZero=false, bool Exact=false)
Compute known bits for lshr(LHS, RHS).
bool isNonZero() const
Returns true if this value is known to be non-zero.
Definition KnownBits.h:109
static LLVM_ABI KnownBits abdu(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for abdu(LHS, RHS).
KnownBits extractBits(unsigned NumBits, unsigned BitPosition) const
Return a subset of the known bits from [bitPosition,bitPosition+numBits).
Definition KnownBits.h:239
static LLVM_ABI KnownBits pdep(const KnownBits &Val, const KnownBits &Mask)
Compute known bits for pdep(Val, Mask).
static LLVM_ABI KnownBits avgFloorU(const KnownBits &LHS, const KnownBits &RHS)
Compute knownbits resulting from APIntOps::avgFloorU.
KnownBits sext(unsigned BitWidth) const
Return known bits for a sign extension of the value we're tracking.
Definition KnownBits.h:184
static LLVM_ABI KnownBits computeForSubBorrow(const KnownBits &LHS, KnownBits RHS, const KnownBits &Borrow)
Compute known bits results from subtracting RHS from LHS with 1-bit Borrow.
KnownBits zextOrTrunc(unsigned BitWidth) const
Return known bits for a zero extension or truncation of the value we're tracking.
Definition KnownBits.h:200
APInt getMaxValue() const
Return the maximal unsigned value possible given these KnownBits.
Definition KnownBits.h:146
static LLVM_ABI KnownBits fshr(const KnownBits &LHS, const KnownBits &RHS, const APInt &Amt)
Compute known bits for fshr(LHS, RHS, Amt).
static LLVM_ABI KnownBits abds(KnownBits LHS, KnownBits RHS)
Compute known bits for abds(LHS, RHS).
static LLVM_ABI KnownBits smin(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for smin(LHS, RHS).
static LLVM_ABI KnownBits mulhs(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits from sign-extended multiply-hi.
static LLVM_ABI KnownBits srem(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for srem(LHS, RHS).
static LLVM_ABI KnownBits udiv(const KnownBits &LHS, const KnownBits &RHS, bool Exact=false)
Compute known bits for udiv(LHS, RHS).
bool isStrictlyPositive() const
Returns true if this value is known to be positive.
Definition KnownBits.h:112
static LLVM_ABI KnownBits sdiv(const KnownBits &LHS, const KnownBits &RHS, bool Exact=false)
Compute known bits for sdiv(LHS, RHS).
static LLVM_ABI KnownBits avgFloorS(const KnownBits &LHS, const KnownBits &RHS)
Compute knownbits resulting from APIntOps::avgFloorS.
static bool haveNoCommonBitsSet(const KnownBits &LHS, const KnownBits &RHS)
Return true if LHS and RHS have no common bits set.
Definition KnownBits.h:340
bool isNegative() const
Returns true if this value is known to be negative.
Definition KnownBits.h:103
static LLVM_ABI KnownBits computeForAddCarry(const KnownBits &LHS, const KnownBits &RHS, const KnownBits &Carry)
Compute known bits resulting from adding LHS, RHS and a 1-bit Carry.
Definition KnownBits.cpp:54
static KnownBits sub(const KnownBits &LHS, const KnownBits &RHS, bool NSW=false, bool NUW=false)
Compute knownbits resulting from subtraction of LHS and RHS.
Definition KnownBits.h:376
unsigned countMaxLeadingZeros() const
Returns the maximum number of leading zero bits possible.
Definition KnownBits.h:294
static LLVM_ABI KnownBits avgCeilU(const KnownBits &LHS, const KnownBits &RHS)
Compute knownbits resulting from APIntOps::avgCeilU.
static LLVM_ABI KnownBits mul(const KnownBits &LHS, const KnownBits &RHS, bool NoUndefSelfMultiply=false)
Compute known bits resulting from multiplying LHS and RHS.
KnownBits anyext(unsigned BitWidth) const
Return known bits for an "any" extension of the value we're tracking, where we don't know anything ab...
Definition KnownBits.h:171
static LLVM_ABI KnownBits clmul(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for clmul(LHS, RHS).
LLVM_ABI KnownBits abs(bool IntMinIsPoison=false) const
Compute known bits for the absolute value.
static LLVM_ABI KnownBits shl(const KnownBits &LHS, const KnownBits &RHS, bool NUW=false, bool NSW=false, bool ShAmtNonZero=false)
Compute known bits for shl(LHS, RHS).
static LLVM_ABI KnownBits umin(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for umin(LHS, RHS).
static LLVM_ABI KnownBits pext(const KnownBits &Val, const KnownBits &Mask)
Compute known bits for pext(Val, Mask).
static LLVM_ABI KnownBits avgCeilS(const KnownBits &LHS, const KnownBits &RHS)
Compute knownbits resulting from APIntOps::avgCeilS.
bool isUnknown() const
KnownFPClass intersectWith(const KnownFPClass &RHS) const
static LLVM_ABI KnownFPClass bitcast(const fltSemantics &FltSemantics, const KnownBits &Bits)
Report known values for a bitcast into a float with provided semantics.
LLVM IR metadata carried by a MachineMemOperand.
This class contains a discriminated union of information about pointers in memory operands,...
LLVM_ABI bool isDereferenceable(unsigned Size, LLVMContext &C, const DataLayout &DL) const
Return true if memory region [V, V+Offset+Size) is known to be dereferenceable.
LLVM_ABI unsigned getAddrSpace() const
Return the LLVM IR address space number that this pointer points into.
PointerUnion< const Value *, const PseudoSourceValue * > V
This is the IR pointer value for the access, or it is null if unknown.
MachinePointerInfo getWithOffset(int64_t O) const
static LLVM_ABI MachinePointerInfo getFixedStack(MachineFunction &MF, int FI, int64_t Offset=0)
Return a MachinePointerInfo record that refers to the specified FrameIndex.
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
Definition Alignment.h:111
Align valueOrOne() const
For convenience, returns a valid alignment or 1 if undefined.
Definition Alignment.h:135
static MemOp Set(uint64_t Size, bool DstAlignCanChange, Align DstAlign, bool IsZeroMemset, bool IsVolatile)
static MemOp Copy(uint64_t Size, bool DstAlignCanChange, Align DstAlign, Align SrcAlign, bool IsVolatile, bool MemcpyStrSrc=false)
static MemOp Move(uint64_t Size, bool DstAlignCanChange, Align DstAlign, Align SrcAlign, bool IsVolatile)
static StringRef getLibcallImplName(RTLIB::LibcallImpl CallImpl)
Get the libcall routine name for the specified libcall implementation.
These are IR-level optimization flags that may be propagated to SDNodes.
static LLVM_ABI bool isEqual(const KeyTy &Key, const SDNode &N)
The key SelectionDAG uniques SDNodes by.
void AddPointer(const void *P)
SmallVector< SDValue, 0 > OpStorage
Backs Ops when the key is built from a node; empty otherwise.
void AddInteger(T I)
const EVT * VTs
ArrayRef< SDValue > Ops
FoldingSetNodeID Tail
SDNodeKey(unsigned Opcode, SDVTList VTList, ArrayRef< SDValue > Ops)
This represents a list of ValueType's that has been intern'd by a SelectionDAG.
unsigned int NumVTs
Clients of various APIs that cause global effects on the DAG can optionally implement this interface.
virtual void NodeDeleted(SDNode *N, SDNode *E)
The node N that was deleted and, if E is not null, an equivalent node E that replaced it.
virtual void NodeInserted(SDNode *N)
The node N that was inserted.
virtual void NodeUpdated(SDNode *N)
The node N that was updated.
This structure contains all information that is necessary for lowering calls.
CallLoweringInfo & setLibCallee(CallingConv::ID CC, Type *ResultType, SDValue Target, ArgListTy &&ArgsList)
CallLoweringInfo & setDiscardResult(bool Value=true)
CallLoweringInfo & setDebugLoc(const SDLoc &dl)
CallLoweringInfo & setTailCall(bool Value=true)
CallLoweringInfo & setChain(SDValue InChain)