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 OptimizationRemarkEmitter &NewORE, Pass *PassPtr,
1462 const TargetLibraryInfo *LibraryInfo,
1463 const LibcallLoweringInfo *LibcallsInfo,
1464 UniformityInfo *NewUA, ProfileSummaryInfo *PSIin,
1466 FunctionVarLocs const *VarLocs) {
1467 MF = &NewMF;
1468 SDAGISelPass = PassPtr;
1469 ORE = &NewORE;
1472 LibInfo = LibraryInfo;
1473 Libcalls = LibcallsInfo;
1474 Context = &MF->getFunction().getContext();
1475 UA = NewUA;
1476 PSI = PSIin;
1477 BFI = BFIin;
1478 MMI = &MMIin;
1479 FnVarLocs = VarLocs;
1480}
1481
1483 assert(!UpdateListeners && "Dangling registered DAGUpdateListeners");
1484 allnodes_clear();
1485 OperandRecycler.clear(OperandAllocator);
1486 delete DbgInfo;
1487}
1488
1490 return llvm::shouldOptimizeForSize(FLI->MBB->getBasicBlock(), PSI, BFI);
1491}
1492
1493void SelectionDAG::allnodes_clear() {
1494 assert(&*AllNodes.begin() == &EntryNode);
1495 AllNodes.remove(AllNodes.begin());
1496 while (!AllNodes.empty())
1497 DeallocateNode(&AllNodes.front());
1498#ifndef NDEBUG
1499 NextPersistentId = 0;
1500#endif
1501}
1502
1503SDNode *SelectionDAG::lookupNode(const SDNodeKey &Key,
1504 FoldingSetInsertToken &InsertToken) {
1505 SDNode *N = CSEMap.lookup(Key, InsertToken);
1506 if (N) {
1507 switch (N->getOpcode()) {
1508 default: break;
1509 case ISD::Constant:
1510 case ISD::ConstantFP:
1511 llvm_unreachable("Querying for Constant and ConstantFP nodes requires "
1512 "debug location. Use another overload.");
1513 }
1514 }
1515 return N;
1516}
1517
1518SDNode *SelectionDAG::lookupNode(const SDNodeKey &Key, const SDLoc &DL,
1519 FoldingSetInsertToken &InsertToken) {
1520 SDNode *N = CSEMap.lookup(Key, InsertToken);
1521 if (N) {
1522 switch (N->getOpcode()) {
1523 case ISD::Constant:
1524 case ISD::ConstantFP:
1525 // Erase debug location from the node if the node is used at several
1526 // different places. Do not propagate one location to all uses as it
1527 // will cause a worse single stepping debugging experience.
1528 if (N->getDebugLoc() != DL.getDebugLoc())
1529 N->setDebugLoc(DebugLoc());
1530 break;
1531 default:
1532 // When the node's point of use is located earlier in the instruction
1533 // sequence than its prior point of use, update its debug info to the
1534 // earlier location.
1535 if (DL.getIROrder() && DL.getIROrder() < N->getIROrder())
1536 N->setDebugLoc(DL.getDebugLoc());
1537 break;
1538 }
1539 }
1540 return N;
1541}
1542
1544 allnodes_clear();
1545 OperandRecycler.clear(OperandAllocator);
1546 OperandAllocator.Reset();
1547 CSEMap.clear();
1548
1549 ExtendedValueTypeNodes.clear();
1550 ExternalSymbols.clear();
1551 TargetExternalSymbols.clear();
1552 MCSymbols.clear();
1553 SDEI.clear();
1554 llvm::fill(CondCodeNodes, nullptr);
1555 llvm::fill(ValueTypeNodes, nullptr);
1556
1557 EntryNode.UseList = nullptr;
1558 InsertNode(&EntryNode);
1559 Root = getEntryNode();
1560 DbgInfo->clear();
1561}
1562
1564 return VT.bitsGT(Op.getValueType())
1565 ? getNode(ISD::FP_EXTEND, DL, VT, Op)
1566 : getNode(ISD::FP_ROUND, DL, VT, Op,
1567 getIntPtrConstant(0, DL, /*isTarget=*/true));
1568}
1569
1570std::pair<SDValue, SDValue>
1572 const SDLoc &DL, EVT VT) {
1573 assert(!VT.bitsEq(Op.getValueType()) &&
1574 "Strict no-op FP extend/round not allowed.");
1575 SDValue Res =
1576 VT.bitsGT(Op.getValueType())
1577 ? getNode(ISD::STRICT_FP_EXTEND, DL, {VT, MVT::Other}, {Chain, Op})
1578 : getNode(ISD::STRICT_FP_ROUND, DL, {VT, MVT::Other},
1579 {Chain, Op, getIntPtrConstant(0, DL, /*isTarget=*/true)});
1580
1581 return std::pair<SDValue, SDValue>(Res, SDValue(Res.getNode(), 1));
1582}
1583
1585 return VT.bitsGT(Op.getValueType()) ?
1586 getNode(ISD::ANY_EXTEND, DL, VT, Op) :
1587 getNode(ISD::TRUNCATE, DL, VT, Op);
1588}
1589
1591 return VT.bitsGT(Op.getValueType()) ?
1592 getNode(ISD::SIGN_EXTEND, DL, VT, Op) :
1593 getNode(ISD::TRUNCATE, DL, VT, Op);
1594}
1595
1597 return VT.bitsGT(Op.getValueType()) ?
1598 getNode(ISD::ZERO_EXTEND, DL, VT, Op) :
1599 getNode(ISD::TRUNCATE, DL, VT, Op);
1600}
1601
1603 EVT VT) {
1604 assert(!VT.isVector());
1605 auto Type = Op.getValueType();
1606 SDValue DestOp;
1607 if (Type == VT)
1608 return Op;
1609 auto Size = Op.getValueSizeInBits();
1610 DestOp = getBitcast(EVT::getIntegerVT(*Context, Size), Op);
1611 if (DestOp.getValueType() == VT)
1612 return DestOp;
1613
1614 return getAnyExtOrTrunc(DestOp, DL, VT);
1615}
1616
1618 EVT VT) {
1619 assert(!VT.isVector());
1620 auto Type = Op.getValueType();
1621 SDValue DestOp;
1622 if (Type == VT)
1623 return Op;
1624 auto Size = Op.getValueSizeInBits();
1625 DestOp = getBitcast(MVT::getIntegerVT(Size), Op);
1626 if (DestOp.getValueType() == VT)
1627 return DestOp;
1628
1629 return getSExtOrTrunc(DestOp, DL, VT);
1630}
1631
1633 EVT VT) {
1634 assert(!VT.isVector());
1635 auto Type = Op.getValueType();
1636 SDValue DestOp;
1637 if (Type == VT)
1638 return Op;
1639 auto Size = Op.getValueSizeInBits();
1640 DestOp = getBitcast(MVT::getIntegerVT(Size), Op);
1641 if (DestOp.getValueType() == VT)
1642 return DestOp;
1643
1644 return getZExtOrTrunc(DestOp, DL, VT);
1645}
1646
1648 EVT OpVT) {
1649 if (VT.bitsLE(Op.getValueType()))
1650 return getNode(ISD::TRUNCATE, SL, VT, Op);
1651
1652 TargetLowering::BooleanContent BType = TLI->getBooleanContents(OpVT);
1653 return getNode(TLI->getExtendForContent(BType), SL, VT, Op);
1654}
1655
1657 EVT OpVT = Op.getValueType();
1658 assert(VT.isInteger() && OpVT.isInteger() &&
1659 "Cannot getZeroExtendInReg FP types");
1660 assert(VT.isVector() == OpVT.isVector() &&
1661 "getZeroExtendInReg type should be vector iff the operand "
1662 "type is vector!");
1663 assert((!VT.isVector() ||
1665 "Vector element counts must match in getZeroExtendInReg");
1666 assert(VT.getScalarType().bitsLE(OpVT.getScalarType()) && "Not extending!");
1667 if (OpVT == VT)
1668 return Op;
1669 // TODO: Use computeKnownBits instead of AssertZext.
1670 if (Op.getOpcode() == ISD::AssertZext && cast<VTSDNode>(Op.getOperand(1))
1671 ->getVT()
1672 .getScalarType()
1673 .bitsLE(VT.getScalarType()))
1674 return Op;
1676 VT.getScalarSizeInBits());
1677 return getNode(ISD::AND, DL, OpVT, Op, getConstant(Imm, DL, OpVT));
1678}
1679
1681 // Only unsigned pointer semantics are supported right now. In the future this
1682 // might delegate to TLI to check pointer signedness.
1683 return getZExtOrTrunc(Op, DL, VT);
1684}
1685
1687 // Only unsigned pointer semantics are supported right now. In the future this
1688 // might delegate to TLI to check pointer signedness.
1689 return getZeroExtendInReg(Op, DL, VT);
1690}
1691
1693 return getNode(ISD::SUB, DL, VT, getConstant(0, DL, VT), Val);
1694}
1695
1696/// getNOT - Create a bitwise NOT operation as (XOR Val, -1).
1698 return getNode(ISD::XOR, DL, VT, Val, getAllOnesConstant(DL, VT));
1699}
1700
1702 SDValue TrueValue = getBoolConstant(true, DL, VT, VT);
1703 return getNode(ISD::XOR, DL, VT, Val, TrueValue);
1704}
1705
1707 EVT OpVT) {
1708 if (!V)
1709 return getConstant(0, DL, VT);
1710
1711 switch (TLI->getBooleanContents(OpVT)) {
1714 return getConstant(1, DL, VT);
1716 return getAllOnesConstant(DL, VT);
1717 }
1718 llvm_unreachable("Unexpected boolean content enum!");
1719}
1720
1722 bool isT, bool isO) {
1723 return getConstant(APInt(VT.getScalarSizeInBits(), Val, /*isSigned=*/false),
1724 DL, VT, isT, isO);
1725}
1726
1728 bool isT, bool isO) {
1729 return getConstant(*ConstantInt::get(*Context, Val), DL, VT, isT, isO);
1730}
1731
1733 EVT VT, bool isT, bool isO) {
1734 assert(VT.isInteger() && "Cannot create FP integer constant!");
1735
1736 EVT EltVT = VT.getScalarType();
1737 const ConstantInt *Elt = &Val;
1738
1739 // Vector splats are explicit within the DAG, with ConstantSDNode holding the
1740 // to-be-splatted scalar ConstantInt.
1741 if (isa<VectorType>(Elt->getType()))
1742 Elt = ConstantInt::get(*getContext(), Elt->getValue());
1743
1744 // In some cases the vector type is legal but the element type is illegal and
1745 // needs to be promoted, for example v8i8 on ARM. In this case, promote the
1746 // inserted value (the type does not need to match the vector element type).
1747 // Any extra bits introduced will be truncated away.
1748 if (VT.isVector() && TLI->getTypeAction(*getContext(), EltVT) ==
1750 EltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1751 APInt NewVal;
1752 if (TLI->isSExtCheaperThanZExt(VT.getScalarType(), EltVT))
1753 NewVal = Elt->getValue().sextOrTrunc(EltVT.getSizeInBits());
1754 else
1755 NewVal = Elt->getValue().zextOrTrunc(EltVT.getSizeInBits());
1756 Elt = ConstantInt::get(*getContext(), NewVal);
1757 }
1758 // In other cases the element type is illegal and needs to be expanded, for
1759 // example v2i64 on MIPS32. In this case, find the nearest legal type, split
1760 // the value into n parts and use a vector type with n-times the elements.
1761 // Then bitcast to the type requested.
1762 // Legalizing constants too early makes the DAGCombiner's job harder so we
1763 // only legalize if the DAG tells us we must produce legal types.
1764 else if (NewNodesMustHaveLegalTypes && VT.isVector() &&
1765 TLI->getTypeAction(*getContext(), EltVT) ==
1767 const APInt &NewVal = Elt->getValue();
1768 EVT ViaEltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1769 unsigned ViaEltSizeInBits = ViaEltVT.getSizeInBits();
1770
1771 // For scalable vectors, try to use a SPLAT_VECTOR_PARTS node.
1772 if (VT.isScalableVector() ||
1773 TLI->isOperationLegal(ISD::SPLAT_VECTOR, VT)) {
1774 assert(EltVT.getSizeInBits() % ViaEltSizeInBits == 0 &&
1775 "Can only handle an even split!");
1776 unsigned Parts = EltVT.getSizeInBits() / ViaEltSizeInBits;
1777
1778 SmallVector<SDValue, 2> ScalarParts;
1779 for (unsigned i = 0; i != Parts; ++i)
1780 ScalarParts.push_back(getConstant(
1781 NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL,
1782 ViaEltVT, isT, isO));
1783
1784 return getNode(ISD::SPLAT_VECTOR_PARTS, DL, VT, ScalarParts);
1785 }
1786
1787 unsigned ViaVecNumElts = VT.getSizeInBits() / ViaEltSizeInBits;
1788 EVT ViaVecVT = EVT::getVectorVT(*getContext(), ViaEltVT, ViaVecNumElts);
1789
1790 // Check the temporary vector is the correct size. If this fails then
1791 // getTypeToTransformTo() probably returned a type whose size (in bits)
1792 // isn't a power-of-2 factor of the requested type size.
1793 assert(ViaVecVT.getSizeInBits() == VT.getSizeInBits());
1794
1795 SmallVector<SDValue, 2> EltParts;
1796 for (unsigned i = 0; i < ViaVecNumElts / VT.getVectorNumElements(); ++i)
1797 EltParts.push_back(getConstant(
1798 NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL,
1799 ViaEltVT, isT, isO));
1800
1801 // EltParts is currently in little endian order. If we actually want
1802 // big-endian order then reverse it now.
1803 if (getDataLayout().isBigEndian())
1804 std::reverse(EltParts.begin(), EltParts.end());
1805
1806 // The elements must be reversed when the element order is different
1807 // to the endianness of the elements (because the BITCAST is itself a
1808 // vector shuffle in this situation). However, we do not need any code to
1809 // perform this reversal because getConstant() is producing a vector
1810 // splat.
1811 // This situation occurs in MIPS MSA.
1812
1814 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
1815 llvm::append_range(Ops, EltParts);
1816
1817 SDValue V =
1818 getNode(ISD::BITCAST, DL, VT, getBuildVector(ViaVecVT, DL, Ops));
1819 return V;
1820 }
1821
1822 assert(Elt->getBitWidth() == EltVT.getSizeInBits() &&
1823 "APInt size does not match type size!");
1824 unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
1825 SDVTList VTs = getVTList(EltVT);
1826 SDNodeKey ID(Opc, VTs, {});
1827 ID.AddPointer(Elt);
1828 ID.AddBoolean(isO);
1829 FoldingSetInsertToken InsertToken;
1830 SDNode *N = nullptr;
1831 if ((N = lookupNode(ID, DL, InsertToken)))
1832 if (!VT.isVector())
1833 return SDValue(N, 0);
1834
1835 if (!N) {
1836 N = newSDNode<ConstantSDNode>(isT, isO, Elt, VTs);
1837 if (!isT)
1838 N->setDebugLoc(DL.getDebugLoc());
1839 CSEMap.insert(N, InsertToken);
1840 InsertNode(N);
1841 NewSDValueDbgMsg(SDValue(N, 0), "Creating constant: ", this);
1842 }
1843
1844 SDValue Result(N, 0);
1845 if (VT.isVector())
1846 Result = getSplat(VT, DL, Result);
1847 return Result;
1848}
1849
1851 bool isT, bool isO) {
1852 unsigned Size = VT.getScalarSizeInBits();
1853 return getConstant(APInt(Size, Val, /*isSigned=*/true), DL, VT, isT, isO);
1854}
1855
1857 bool IsOpaque) {
1859 IsTarget, IsOpaque);
1860}
1861
1863 bool isTarget) {
1864 return getConstant(Val, DL, TLI->getPointerTy(getDataLayout()), isTarget);
1865}
1866
1868 const SDLoc &DL) {
1869 assert(VT.isInteger() && "Shift amount is not an integer type!");
1870 EVT ShiftVT = TLI->getShiftAmountTy(VT, getDataLayout());
1871 return getConstant(Val, DL, ShiftVT);
1872}
1873
1875 const SDLoc &DL) {
1876 assert(Val.ult(VT.getScalarSizeInBits()) && "Out of range shift");
1877 return getShiftAmountConstant(Val.getZExtValue(), VT, DL);
1878}
1879
1881 bool isTarget) {
1882 return getConstant(Val, DL, TLI->getVectorIdxTy(getDataLayout()), isTarget);
1883}
1884
1886 bool isTarget) {
1887 return getConstantFP(*ConstantFP::get(*getContext(), V), DL, VT, isTarget);
1888}
1889
1891 EVT VT, bool isTarget) {
1892 assert(VT.isFloatingPoint() && "Cannot create integer FP constant!");
1893
1894 EVT EltVT = VT.getScalarType();
1895 const ConstantFP *Elt = &V;
1896
1897 // Vector splats are explicit within the DAG, with ConstantFPSDNode holding
1898 // the to-be-splatted scalar ConstantFP.
1899 if (isa<VectorType>(Elt->getType()))
1900 Elt = ConstantFP::get(*getContext(), Elt->getValue());
1901
1902 // Do the map lookup using the actual bit pattern for the floating point
1903 // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
1904 // we don't have issues with SNANs.
1905 unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
1906 SDVTList VTs = getVTList(EltVT);
1907 SDNodeKey ID(Opc, VTs, {});
1908 ID.AddPointer(Elt);
1909 FoldingSetInsertToken InsertToken;
1910 SDNode *N = nullptr;
1911 if ((N = lookupNode(ID, DL, InsertToken)))
1912 if (!VT.isVector())
1913 return SDValue(N, 0);
1914
1915 if (!N) {
1916 N = newSDNode<ConstantFPSDNode>(isTarget, Elt, VTs);
1917 CSEMap.insert(N, InsertToken);
1918 InsertNode(N);
1919 }
1920
1921 SDValue Result(N, 0);
1922 if (VT.isVector())
1923 Result = getSplat(VT, DL, Result);
1924 NewSDValueDbgMsg(Result, "Creating fp constant: ", this);
1925 return Result;
1926}
1927
1929 bool isTarget) {
1930 EVT EltVT = VT.getScalarType();
1931 if (EltVT == MVT::f32)
1932 return getConstantFP(APFloat((float)Val), DL, VT, isTarget);
1933 if (EltVT == MVT::f64)
1934 return getConstantFP(APFloat(Val), DL, VT, isTarget);
1935 if (EltVT == MVT::f80 || EltVT == MVT::f128 || EltVT == MVT::ppcf128 ||
1936 EltVT == MVT::f16 || EltVT == MVT::bf16) {
1937 bool Ignored;
1938 APFloat APF = APFloat(Val);
1940 &Ignored);
1941 return getConstantFP(APF, DL, VT, isTarget);
1942 }
1943 llvm_unreachable("Unsupported type in getConstantFP");
1944}
1945
1947 EVT VT, int64_t Offset, bool isTargetGA,
1948 unsigned TargetFlags) {
1949 assert((TargetFlags == 0 || isTargetGA) &&
1950 "Cannot set target flags on target-independent globals");
1951
1952 // Truncate (with sign-extension) the offset value to the pointer size.
1954 if (BitWidth < 64)
1956
1957 unsigned Opc;
1958 if (GV->isThreadLocal())
1960 else
1962
1963 SDVTList VTs = getVTList(VT);
1964 SDNodeKey ID(Opc, VTs, {});
1965 ID.AddPointer(GV);
1966 ID.AddInteger(Offset);
1967 ID.AddInteger(TargetFlags);
1968 FoldingSetInsertToken InsertToken;
1969 if (SDNode *E = lookupNode(ID, DL, InsertToken))
1970 return SDValue(E, 0);
1971
1972 auto *N = newSDNode<GlobalAddressSDNode>(
1973 Opc, DL.getIROrder(), DL.getDebugLoc(), GV, VTs, Offset, TargetFlags);
1974 CSEMap.insert(N, InsertToken);
1975 InsertNode(N);
1976 return SDValue(N, 0);
1977}
1978
1980 SDVTList VTs = getVTList(MVT::Untyped);
1982 ID.AddPointer(GV);
1983 FoldingSetInsertToken InsertToken;
1984 if (SDNode *E = lookupNode(ID, SDLoc(), InsertToken))
1985 return SDValue(E, 0);
1986
1987 auto *N = newSDNode<DeactivationSymbolSDNode>(GV, VTs);
1988 CSEMap.insert(N, InsertToken);
1989 InsertNode(N);
1990 return SDValue(N, 0);
1991}
1992
1993SDValue SelectionDAG::getFrameIndex(int FI, EVT VT, bool isTarget) {
1994 unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
1995 SDVTList VTs = getVTList(VT);
1996 SDNodeKey ID(Opc, VTs, {});
1997 ID.AddInteger(FI);
1998 FoldingSetInsertToken InsertToken;
1999 if (SDNode *E = lookupNode(ID, InsertToken))
2000 return SDValue(E, 0);
2001
2002 auto *N = newSDNode<FrameIndexSDNode>(FI, VTs, isTarget);
2003 CSEMap.insert(N, InsertToken);
2004 InsertNode(N);
2005 return SDValue(N, 0);
2006}
2007
2008SDValue SelectionDAG::getJumpTable(int JTI, EVT VT, bool isTarget,
2009 unsigned TargetFlags) {
2010 assert((TargetFlags == 0 || isTarget) &&
2011 "Cannot set target flags on target-independent jump tables");
2012 unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
2013 SDVTList VTs = getVTList(VT);
2014 SDNodeKey ID(Opc, VTs, {});
2015 ID.AddInteger(JTI);
2016 ID.AddInteger(TargetFlags);
2017 FoldingSetInsertToken InsertToken;
2018 if (SDNode *E = lookupNode(ID, InsertToken))
2019 return SDValue(E, 0);
2020
2021 auto *N = newSDNode<JumpTableSDNode>(JTI, VTs, isTarget, TargetFlags);
2022 CSEMap.insert(N, InsertToken);
2023 InsertNode(N);
2024 return SDValue(N, 0);
2025}
2026
2028 const SDLoc &DL) {
2030 return getNode(ISD::JUMP_TABLE_DEBUG_INFO, DL, MVT::Other, Chain,
2031 getTargetConstant(static_cast<uint64_t>(JTI), DL, PTy, true));
2032}
2033
2035 MaybeAlign Alignment, int Offset,
2036 bool isTarget, unsigned TargetFlags) {
2037 assert((TargetFlags == 0 || isTarget) &&
2038 "Cannot set target flags on target-independent globals");
2039 if (!Alignment)
2040 Alignment = shouldOptForSize()
2041 ? getDataLayout().getABITypeAlign(C->getType())
2042 : getDataLayout().getPrefTypeAlign(C->getType());
2043 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
2044 SDVTList VTs = getVTList(VT);
2045 SDNodeKey ID(Opc, VTs, {});
2046 ID.AddInteger(Alignment->value());
2047 ID.AddInteger(Offset);
2048 ID.AddPointer(C);
2049 ID.AddInteger(TargetFlags);
2050 FoldingSetInsertToken InsertToken;
2051 if (SDNode *E = lookupNode(ID, InsertToken))
2052 return SDValue(E, 0);
2053
2054 auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VTs, Offset, *Alignment,
2055 TargetFlags);
2056 CSEMap.insert(N, InsertToken);
2057 InsertNode(N);
2058 SDValue V = SDValue(N, 0);
2059 NewSDValueDbgMsg(V, "Creating new constant pool: ", this);
2060 return V;
2061}
2062
2064 MaybeAlign Alignment, int Offset,
2065 bool isTarget, unsigned TargetFlags) {
2066 assert((TargetFlags == 0 || isTarget) &&
2067 "Cannot set target flags on target-independent globals");
2068 if (!Alignment)
2069 Alignment = getDataLayout().getPrefTypeAlign(C->getType());
2070 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
2071 SDVTList VTs = getVTList(VT);
2072 SDNodeKey ID(Opc, VTs, {});
2073 ID.AddInteger(Alignment->value());
2074 ID.AddInteger(Offset);
2075 C->addSelectionDAGCSEId(ID.Tail);
2076 ID.AddInteger(TargetFlags);
2077 FoldingSetInsertToken InsertToken;
2078 if (SDNode *E = lookupNode(ID, InsertToken))
2079 return SDValue(E, 0);
2080
2081 auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VTs, Offset, *Alignment,
2082 TargetFlags);
2083 CSEMap.insert(N, InsertToken);
2084 InsertNode(N);
2085 return SDValue(N, 0);
2086}
2087
2089 SDNodeKey ID(ISD::BasicBlock, getVTList(MVT::Other), {});
2090 ID.AddPointer(MBB);
2091 FoldingSetInsertToken InsertToken;
2092 if (SDNode *E = lookupNode(ID, InsertToken))
2093 return SDValue(E, 0);
2094
2095 auto *N = newSDNode<BasicBlockSDNode>(MBB);
2096 CSEMap.insert(N, InsertToken);
2097 InsertNode(N);
2098 return SDValue(N, 0);
2099}
2100
2102 if (VT.isSimple() && (unsigned)VT.getSimpleVT().SimpleTy >=
2103 ValueTypeNodes.size())
2104 ValueTypeNodes.resize(VT.getSimpleVT().SimpleTy+1);
2105
2106 SDNode *&N = VT.isExtended() ?
2107 ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT().SimpleTy];
2108
2109 if (N) return SDValue(N, 0);
2110 N = newSDNode<VTSDNode>(VT);
2111 InsertNode(N);
2112 return SDValue(N, 0);
2113}
2114
2116 SDNode *&N = ExternalSymbols[Sym];
2117 if (N) return SDValue(N, 0);
2118 N = newSDNode<ExternalSymbolSDNode>(false, Sym, 0, getVTList(VT));
2119 InsertNode(N);
2120 return SDValue(N, 0);
2121}
2122
2123SDValue SelectionDAG::getExternalSymbol(RTLIB::LibcallImpl Libcall, EVT VT) {
2125 return getExternalSymbol(SymName.data(), VT);
2126}
2127
2129 SDNode *&N = MCSymbols[Sym];
2130 if (N)
2131 return SDValue(N, 0);
2132 N = newSDNode<MCSymbolSDNode>(Sym, getVTList(VT));
2133 InsertNode(N);
2134 return SDValue(N, 0);
2135}
2136
2138 unsigned TargetFlags) {
2139 SDNode *&N =
2140 TargetExternalSymbols[std::pair<std::string, unsigned>(Sym, TargetFlags)];
2141 if (N) return SDValue(N, 0);
2142 N = newSDNode<ExternalSymbolSDNode>(true, Sym, TargetFlags, getVTList(VT));
2143 InsertNode(N);
2144 return SDValue(N, 0);
2145}
2146
2148 EVT VT, unsigned TargetFlags) {
2150 return getTargetExternalSymbol(SymName.data(), VT, TargetFlags);
2151}
2152
2154 if ((unsigned)Cond >= CondCodeNodes.size())
2155 CondCodeNodes.resize(Cond+1);
2156
2157 if (!CondCodeNodes[Cond]) {
2158 auto *N = newSDNode<CondCodeSDNode>(Cond);
2159 CondCodeNodes[Cond] = N;
2160 InsertNode(N);
2161 }
2162
2163 return SDValue(CondCodeNodes[Cond], 0);
2164}
2165
2167 assert(MulImm.getBitWidth() == VT.getSizeInBits() &&
2168 "APInt size does not match type size!");
2169
2170 if (MulImm == 0)
2171 return getConstant(0, DL, VT);
2172
2173 const MachineFunction &MF = getMachineFunction();
2174 const Function &F = MF.getFunction();
2175 ConstantRange CR = getVScaleRange(&F, 64);
2176 if (const APInt *C = CR.getSingleElement())
2177 return getConstant(MulImm * C->getZExtValue(), DL, VT);
2178
2179 return getNode(ISD::VSCALE, DL, VT, getConstant(MulImm, DL, VT));
2180}
2181
2182/// \returns a value of type \p VT that represents the runtime value of \p
2183/// Quantity, i.e. scaled by vscale if it's scalable, or a fixed constant
2184/// otherwise. Quantity should be a FixedOrScalableQuantity, i.e. ElementCount
2185/// or TypeSize.
2186template <typename Ty>
2188 EVT VT, Ty Quantity) {
2189 if (Quantity.isScalable())
2190 return DAG.getVScale(
2191 DL, VT, APInt(VT.getSizeInBits(), Quantity.getKnownMinValue()));
2192
2193 return DAG.getConstant(Quantity.getKnownMinValue(), DL, VT);
2194}
2195
2197 ElementCount EC) {
2198 return getFixedOrScalableQuantity(*this, DL, VT, EC);
2199}
2200
2202 return getFixedOrScalableQuantity(*this, DL, VT, TS);
2203}
2204
2206 ElementCount EC) {
2207 EVT IdxVT = TLI->getVectorIdxTy(getDataLayout());
2208 EVT MaskVT = TLI->getSetCCResultType(getDataLayout(), *getContext(), DataVT);
2209 return getNode(ISD::GET_ACTIVE_LANE_MASK, DL, MaskVT,
2210 getConstant(0, DL, IdxVT), getElementCount(DL, IdxVT, EC));
2211}
2212
2214 APInt One(ResVT.getScalarSizeInBits(), 1);
2215 return getStepVector(DL, ResVT, One);
2216}
2217
2219 const APInt &StepVal) {
2220 assert(ResVT.getScalarSizeInBits() == StepVal.getBitWidth());
2221 if (ResVT.isScalableVector())
2222 return getNode(
2223 ISD::STEP_VECTOR, DL, ResVT,
2224 getTargetConstant(StepVal, DL, ResVT.getVectorElementType()));
2225
2226 SmallVector<SDValue, 16> OpsStepConstants;
2227 for (uint64_t i = 0; i < ResVT.getVectorNumElements(); i++)
2228 OpsStepConstants.push_back(
2229 getConstant(StepVal * i, DL, ResVT.getVectorElementType()));
2230 return getBuildVector(ResVT, DL, OpsStepConstants);
2231}
2232
2233/// Swaps the values of N1 and N2. Swaps all indices in the shuffle mask M that
2234/// point at N1 to point at N2 and indices that point at N2 to point at N1.
2239
2241 SDValue N2, ArrayRef<int> Mask) {
2242 assert(VT.getVectorNumElements() == Mask.size() &&
2243 "Must have the same number of vector elements as mask elements!");
2244 assert(VT == N1.getValueType() && VT == N2.getValueType() &&
2245 "Invalid VECTOR_SHUFFLE");
2246
2247 // Canonicalize shuffle undef, undef -> undef
2248 if (N1.isUndef() && N2.isUndef()) {
2249 if (N1.getOpcode() == ISD::POISON && N2.getOpcode() == ISD::POISON)
2250 return getPOISON(VT);
2251 return getUNDEF(VT);
2252 }
2253
2254 // Validate that all indices in Mask are within the range of the elements
2255 // input to the shuffle.
2256 int NElts = Mask.size();
2257 assert(llvm::all_of(Mask,
2258 [&](int M) { return M < (NElts * 2) && M >= -1; }) &&
2259 "Index out of range");
2260
2261 // Copy the mask so we can do any needed cleanup.
2262 SmallVector<int, 8> MaskVec(Mask);
2263
2264 // Canonicalize shuffle v, v -> v, poison
2265 if (N1 == N2) {
2266 N2 = getPOISON(VT);
2267 for (int i = 0; i != NElts; ++i)
2268 if (MaskVec[i] >= NElts) MaskVec[i] -= NElts;
2269 }
2270
2271 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
2272 if (N1.isUndef())
2273 commuteShuffle(N1, N2, MaskVec);
2274
2275 if (TLI->hasVectorBlend()) {
2276 // If shuffling a splat, try to blend the splat instead. We do this here so
2277 // that even when this arises during lowering we don't have to re-handle it.
2278 auto BlendSplat = [&](BuildVectorSDNode *BV, int Offset) {
2279 BitVector UndefElements;
2280 SDValue Splat = BV->getSplatValue(&UndefElements);
2281 if (!Splat)
2282 return;
2283
2284 for (int i = 0; i < NElts; ++i) {
2285 if (MaskVec[i] < Offset || MaskVec[i] >= (Offset + NElts))
2286 continue;
2287
2288 // If this input comes from undef, mark it as such.
2289 if (UndefElements[MaskVec[i] - Offset]) {
2290 MaskVec[i] = -1;
2291 continue;
2292 }
2293
2294 // If we can blend a non-undef lane, use that instead.
2295 if (!UndefElements[i])
2296 MaskVec[i] = i + Offset;
2297 }
2298 };
2299 if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
2300 BlendSplat(N1BV, 0);
2301 if (auto *N2BV = dyn_cast<BuildVectorSDNode>(N2))
2302 BlendSplat(N2BV, NElts);
2303 }
2304
2305 // Canonicalize all index into lhs, -> shuffle lhs, poison
2306 // Canonicalize all index into rhs, -> shuffle rhs, poison
2307 bool AllLHS = true, AllRHS = true;
2308 bool N2Undef = N2.isUndef();
2309 for (int i = 0; i != NElts; ++i) {
2310 if (MaskVec[i] >= NElts) {
2311 if (N2Undef)
2312 MaskVec[i] = -1;
2313 else
2314 AllLHS = false;
2315 } else if (MaskVec[i] >= 0) {
2316 AllRHS = false;
2317 }
2318 }
2319 if (AllLHS && AllRHS)
2320 return getPOISON(VT);
2321 if (AllLHS && !N2Undef)
2322 N2 = getPOISON(VT);
2323 if (AllRHS) {
2324 N1 = getPOISON(VT);
2325 commuteShuffle(N1, N2, MaskVec);
2326 }
2327 // Reset our undef status after accounting for the mask.
2328 N2Undef = N2.isUndef();
2329 // Re-check whether both sides ended up undef.
2330 if (N1.isUndef() && N2Undef) {
2331 if (N1.getOpcode() == ISD::POISON && N2.getOpcode() == ISD::POISON)
2332 return getPOISON(VT);
2333 return getUNDEF(VT);
2334 }
2335
2336 // If Identity shuffle return that node.
2337 bool Identity = true, AllSame = true;
2338 for (int i = 0; i != NElts; ++i) {
2339 if (MaskVec[i] >= 0 && MaskVec[i] != i) Identity = false;
2340 if (MaskVec[i] != MaskVec[0]) AllSame = false;
2341 }
2342 if (Identity && NElts)
2343 return N1;
2344
2345 // Shuffling a constant splat doesn't change the result.
2346 if (N2Undef) {
2347 SDValue V = N1;
2348
2349 // Look through any bitcasts. We check that these don't change the number
2350 // (and size) of elements and just changes their types.
2351 while (V.getOpcode() == ISD::BITCAST)
2352 V = V->getOperand(0);
2353
2354 // A splat should always show up as a build vector node.
2355 if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) {
2356 BitVector UndefElements;
2357 SDValue Splat = BV->getSplatValue(&UndefElements);
2358 // If this is a splat of an undef, shuffling it is also undef.
2359 if (Splat && Splat.isUndef())
2360 return Splat.getOpcode() == ISD::POISON ? getPOISON(VT) : getUNDEF(VT);
2361
2362 bool SameNumElts =
2363 V.getValueType().getVectorNumElements() == VT.getVectorNumElements();
2364
2365 // We only have a splat which can skip shuffles if there is a splatted
2366 // value and no undef lanes rearranged by the shuffle.
2367 if (Splat && UndefElements.none()) {
2368 // Splat of <x, x, ..., x>, return <x, x, ..., x>, provided that the
2369 // number of elements match or the value splatted is a zero constant.
2370 if (SameNumElts || isNullConstant(Splat))
2371 return N1;
2372 }
2373
2374 // If the shuffle itself creates a splat, build the vector directly.
2375 if (AllSame && SameNumElts) {
2376 EVT BuildVT = BV->getValueType(0);
2377 const SDValue &Splatted = BV->getOperand(MaskVec[0]);
2378 SDValue NewBV = getSplatBuildVector(BuildVT, dl, Splatted);
2379
2380 // We may have jumped through bitcasts, so the type of the
2381 // BUILD_VECTOR may not match the type of the shuffle.
2382 if (BuildVT != VT)
2383 NewBV = getNode(ISD::BITCAST, dl, VT, NewBV);
2384 return NewBV;
2385 }
2386 }
2387 }
2388
2389 SDVTList VTs = getVTList(VT);
2390 SDValue Ops[2] = { N1, N2 };
2392 for (int i = 0; i != NElts; ++i)
2393 ID.AddInteger(MaskVec[i]);
2394
2395 FoldingSetInsertToken InsertToken;
2396 if (SDNode *E = lookupNode(ID, dl, InsertToken))
2397 return SDValue(E, 0);
2398
2399 // Allocate the mask array for the node out of the BumpPtrAllocator, since
2400 // SDNode doesn't have access to it. This memory will be "leaked" when
2401 // the node is deallocated, but recovered when the NodeAllocator is released.
2402 int *MaskAlloc = OperandAllocator.Allocate<int>(NElts);
2403 llvm::copy(MaskVec, MaskAlloc);
2404
2405 auto *N = newSDNode<ShuffleVectorSDNode>(VTs, dl.getIROrder(),
2406 dl.getDebugLoc(), MaskAlloc);
2407 createOperands(N, Ops);
2408
2409 CSEMap.insert(N, InsertToken);
2410 InsertNode(N);
2411 SDValue V = SDValue(N, 0);
2412 NewSDValueDbgMsg(V, "Creating new node: ", this);
2413 return V;
2414}
2415
2417 EVT VT = SV.getValueType(0);
2418 SmallVector<int, 8> MaskVec(SV.getMask());
2420
2421 SDValue Op0 = SV.getOperand(0);
2422 SDValue Op1 = SV.getOperand(1);
2423 return getVectorShuffle(VT, SDLoc(&SV), Op1, Op0, MaskVec);
2424}
2425
2427 SDVTList VTs = getVTList(VT);
2428 SDNodeKey ID(ISD::Register, VTs, {});
2429 ID.AddInteger(Reg.id());
2430 FoldingSetInsertToken InsertToken;
2431 if (SDNode *E = lookupNode(ID, InsertToken))
2432 return SDValue(E, 0);
2433
2434 auto *N = newSDNode<RegisterSDNode>(Reg, VTs);
2435 N->SDNodeBits.IsDivergent = TLI->isSDNodeSourceOfDivergence(N, FLI, UA);
2436 CSEMap.insert(N, InsertToken);
2437 InsertNode(N);
2438 return SDValue(N, 0);
2439}
2440
2442 SDNodeKey ID(ISD::RegisterMask, getVTList(MVT::Untyped), {});
2443 ID.AddPointer(RegMask);
2444 FoldingSetInsertToken InsertToken;
2445 if (SDNode *E = lookupNode(ID, InsertToken))
2446 return SDValue(E, 0);
2447
2448 auto *N = newSDNode<RegisterMaskSDNode>(RegMask);
2449 CSEMap.insert(N, InsertToken);
2450 InsertNode(N);
2451 return SDValue(N, 0);
2452}
2453
2455 MCSymbol *Label) {
2456 return getLabelNode(ISD::EH_LABEL, dl, Root, Label);
2457}
2458
2459SDValue SelectionDAG::getLabelNode(unsigned Opcode, const SDLoc &dl,
2460 SDValue Root, MCSymbol *Label) {
2461 SDValue Ops[] = { Root };
2462 SDNodeKey ID(Opcode, getVTList(MVT::Other), Ops);
2463 ID.AddPointer(Label);
2464 FoldingSetInsertToken InsertToken;
2465 if (SDNode *E = lookupNode(ID, InsertToken))
2466 return SDValue(E, 0);
2467
2468 auto *N =
2469 newSDNode<LabelSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), Label);
2470 createOperands(N, Ops);
2471
2472 CSEMap.insert(N, InsertToken);
2473 InsertNode(N);
2474 return SDValue(N, 0);
2475}
2476
2478 int64_t Offset, bool isTarget,
2479 unsigned TargetFlags) {
2480 unsigned Opc = isTarget ? ISD::TargetBlockAddress : ISD::BlockAddress;
2481 SDVTList VTs = getVTList(VT);
2482
2483 SDNodeKey ID(Opc, VTs, {});
2484 ID.AddPointer(BA);
2485 ID.AddInteger(Offset);
2486 ID.AddInteger(TargetFlags);
2487 FoldingSetInsertToken InsertToken;
2488 if (SDNode *E = lookupNode(ID, InsertToken))
2489 return SDValue(E, 0);
2490
2491 auto *N = newSDNode<BlockAddressSDNode>(Opc, VTs, BA, Offset, TargetFlags);
2492 CSEMap.insert(N, InsertToken);
2493 InsertNode(N);
2494 return SDValue(N, 0);
2495}
2496
2498 SDNodeKey ID(ISD::SRCVALUE, getVTList(MVT::Other), {});
2499 ID.AddPointer(V);
2500
2501 FoldingSetInsertToken InsertToken;
2502 if (SDNode *E = lookupNode(ID, InsertToken))
2503 return SDValue(E, 0);
2504
2505 auto *N = newSDNode<SrcValueSDNode>(V);
2506 CSEMap.insert(N, InsertToken);
2507 InsertNode(N);
2508 return SDValue(N, 0);
2509}
2510
2512 SDNodeKey ID(ISD::MDNODE_SDNODE, getVTList(MVT::Other), {});
2513 ID.AddPointer(MD);
2514
2515 FoldingSetInsertToken InsertToken;
2516 if (SDNode *E = lookupNode(ID, InsertToken))
2517 return SDValue(E, 0);
2518
2519 auto *N = newSDNode<MDNodeSDNode>(MD);
2520 CSEMap.insert(N, InsertToken);
2521 InsertNode(N);
2522 return SDValue(N, 0);
2523}
2524
2526 if (VT == V.getValueType())
2527 return V;
2528
2529 return getNode(ISD::BITCAST, SDLoc(V), VT, V);
2530}
2531
2533 unsigned SrcAS, unsigned DestAS) {
2534 SDVTList VTs = getVTList(VT);
2535 SDValue Ops[] = {Ptr};
2537 ID.AddInteger(SrcAS);
2538 ID.AddInteger(DestAS);
2539
2540 FoldingSetInsertToken InsertToken;
2541 if (SDNode *E = lookupNode(ID, dl, InsertToken))
2542 return SDValue(E, 0);
2543
2544 auto *N = newSDNode<AddrSpaceCastSDNode>(dl.getIROrder(), dl.getDebugLoc(),
2545 VTs, SrcAS, DestAS);
2546 createOperands(N, Ops);
2547
2548 CSEMap.insert(N, InsertToken);
2549 InsertNode(N);
2550 return SDValue(N, 0);
2551}
2552
2554 return getNode(ISD::FREEZE, SDLoc(V), V.getValueType(), V);
2555}
2556
2558 UndefPoisonKind Kind) {
2559 if (isGuaranteedNotToBeUndefOrPoison(V, DemandedElts, Kind))
2560 return V;
2561 return getFreeze(V);
2562}
2563
2564/// getShiftAmountOperand - Return the specified value casted to
2565/// the target's desired shift amount type.
2567 EVT OpTy = Op.getValueType();
2568 EVT ShTy = TLI->getShiftAmountTy(LHSTy, getDataLayout());
2569 if (OpTy == ShTy || OpTy.isVector()) return Op;
2570
2571 return getZExtOrTrunc(Op, SDLoc(Op), ShTy);
2572}
2573
2575 SDLoc dl(Node);
2577 const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2578 EVT VT = Node->getValueType(0);
2579 SDValue Tmp1 = Node->getOperand(0);
2580 SDValue Tmp2 = Node->getOperand(1);
2581 const MaybeAlign MA(Node->getConstantOperandVal(3));
2582
2583 SDValue VAListLoad = getLoad(TLI.getPointerTy(getDataLayout()), dl, Tmp1,
2584 Tmp2, MachinePointerInfo(V));
2585 SDValue VAList = VAListLoad;
2586
2587 if (MA && *MA > TLI.getMinStackArgumentAlignment()) {
2588 VAList = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
2589 getConstant(MA->value() - 1, dl, VAList.getValueType()));
2590
2591 VAList = getNode(
2592 ISD::AND, dl, VAList.getValueType(), VAList,
2593 getSignedConstant(-(int64_t)MA->value(), dl, VAList.getValueType()));
2594 }
2595
2596 // Increment the pointer, VAList, to the next vaarg
2597 Tmp1 = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
2598 getConstant(getDataLayout().getTypeAllocSize(
2599 VT.getTypeForEVT(*getContext())),
2600 dl, VAList.getValueType()));
2601 // Store the incremented VAList to the legalized pointer
2602 Tmp1 =
2603 getStore(VAListLoad.getValue(1), dl, Tmp1, Tmp2, MachinePointerInfo(V));
2604 // Load the actual argument out of the pointer VAList
2605 return getLoad(VT, dl, Tmp1, VAList, MachinePointerInfo());
2606}
2607
2609 SDLoc dl(Node);
2611 // This defaults to loading a pointer from the input and storing it to the
2612 // output, returning the chain.
2613 const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue();
2614 const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue();
2615 SDValue Tmp1 =
2616 getLoad(TLI.getPointerTy(getDataLayout()), dl, Node->getOperand(0),
2617 Node->getOperand(2), MachinePointerInfo(VS));
2618 return getStore(Tmp1.getValue(1), dl, Tmp1, Node->getOperand(1),
2619 MachinePointerInfo(VD));
2620}
2621
2623 const DataLayout &DL = getDataLayout();
2624 Type *Ty = VT.getTypeForEVT(*getContext());
2625 Align RedAlign = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty);
2626
2627 if (TLI->isTypeLegal(VT) || !VT.isVector())
2628 return RedAlign;
2629
2630 const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
2631 const Align StackAlign = TFI->getStackAlign();
2632
2633 // See if we can choose a smaller ABI alignment in cases where it's an
2634 // illegal vector type that will get broken down.
2635 if (RedAlign > StackAlign) {
2636 EVT IntermediateVT;
2637 MVT RegisterVT;
2638 unsigned NumIntermediates;
2639 TLI->getVectorTypeBreakdown(*getContext(), VT, IntermediateVT,
2640 NumIntermediates, RegisterVT);
2641 Ty = IntermediateVT.getTypeForEVT(*getContext());
2642 Align RedAlign2 = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty);
2643 if (RedAlign2 < RedAlign)
2644 RedAlign = RedAlign2;
2645
2646 if (!getMachineFunction().getFrameInfo().isStackRealignable())
2647 // If the stack is not realignable, the alignment should be limited to the
2648 // StackAlignment
2649 RedAlign = std::min(RedAlign, StackAlign);
2650 }
2651
2652 return RedAlign;
2653}
2654
2656 MachineFrameInfo &MFI = MF->getFrameInfo();
2657 const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
2658 int StackID = 0;
2659 if (Bytes.isScalable())
2660 StackID = TFI->getStackIDForScalableVectors();
2661 // The stack id gives an indication of whether the object is scalable or
2662 // not, so it's safe to pass in the minimum size here.
2663 int FrameIdx = MFI.CreateStackObject(Bytes.getKnownMinValue(), Alignment,
2664 false, nullptr, StackID);
2665 return getFrameIndex(FrameIdx, TLI->getFrameIndexTy(getDataLayout()));
2666}
2667
2669 Type *Ty = VT.getTypeForEVT(*getContext());
2670 Align StackAlign =
2671 std::max(getDataLayout().getPrefTypeAlign(Ty), Align(minAlign));
2672 return CreateStackTemporary(VT.getStoreSize(), StackAlign);
2673}
2674
2676 TypeSize VT1Size = VT1.getStoreSize();
2677 TypeSize VT2Size = VT2.getStoreSize();
2678 assert(VT1Size.isScalable() == VT2Size.isScalable() &&
2679 "Don't know how to choose the maximum size when creating a stack "
2680 "temporary");
2681 TypeSize Bytes = VT1Size.getKnownMinValue() > VT2Size.getKnownMinValue()
2682 ? VT1Size
2683 : VT2Size;
2684
2685 Type *Ty1 = VT1.getTypeForEVT(*getContext());
2686 Type *Ty2 = VT2.getTypeForEVT(*getContext());
2687 const DataLayout &DL = getDataLayout();
2688 Align Align = std::max(DL.getPrefTypeAlign(Ty1), DL.getPrefTypeAlign(Ty2));
2689 return CreateStackTemporary(Bytes, Align);
2690}
2691
2693 ISD::CondCode Cond, const SDLoc &dl,
2694 SDNodeFlags Flags) {
2695 EVT OpVT = N1.getValueType();
2696
2697 auto GetUndefBooleanConstant = [&]() {
2698 if (VT.getScalarType() == MVT::i1 ||
2699 TLI->getBooleanContents(OpVT) ==
2701 return getUNDEF(VT);
2702 // ZeroOrOne / ZeroOrNegative require specific values for the high bits,
2703 // so we cannot use getUNDEF(). Return zero instead.
2704 return getConstant(0, dl, VT);
2705 };
2706
2707 // These setcc operations always fold.
2708 switch (Cond) {
2709 default: break;
2710 case ISD::SETFALSE:
2711 case ISD::SETFALSE2: return getBoolConstant(false, dl, VT, OpVT);
2712 case ISD::SETTRUE:
2713 case ISD::SETTRUE2: return getBoolConstant(true, dl, VT, OpVT);
2714
2715 case ISD::SETOEQ:
2716 case ISD::SETOGT:
2717 case ISD::SETOGE:
2718 case ISD::SETOLT:
2719 case ISD::SETOLE:
2720 case ISD::SETONE:
2721 case ISD::SETO:
2722 case ISD::SETUO:
2723 case ISD::SETUEQ:
2724 case ISD::SETUNE:
2725 assert(!OpVT.isInteger() && "Illegal setcc for integer!");
2726 break;
2727 }
2728
2729 if (OpVT.isInteger()) {
2730 // For EQ and NE, we can always pick a value for the undef to make the
2731 // predicate pass or fail, so we can return undef.
2732 // Matches behavior in llvm::ConstantFoldCompareInstruction.
2733 // icmp eq/ne X, undef -> undef.
2734 if ((N1.isUndef() || N2.isUndef()) &&
2735 (Cond == ISD::SETEQ || Cond == ISD::SETNE))
2736 return GetUndefBooleanConstant();
2737
2738 // If both operands are undef, we can return undef for int comparison.
2739 // icmp undef, undef -> undef.
2740 if (N1.isUndef() && N2.isUndef())
2741 return GetUndefBooleanConstant();
2742
2743 // icmp X, X -> true/false
2744 // icmp X, undef -> true/false because undef could be X.
2745 if (N1.isUndef() || N2.isUndef() || N1 == N2)
2746 return getBoolConstant(ISD::isTrueWhenEqual(Cond), dl, VT, OpVT);
2747 }
2748
2750 const APInt &C2 = N2C->getAPIntValue();
2752 const APInt &C1 = N1C->getAPIntValue();
2753
2755 dl, VT, OpVT);
2756 }
2757 }
2758
2759 auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
2760 auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
2761
2762 if (N1CFP && N2CFP) {
2763 APFloat::cmpResult R = N1CFP->getValueAPF().compare(N2CFP->getValueAPF());
2764 switch (Cond) {
2765 default: break;
2766 case ISD::SETEQ: if (R==APFloat::cmpUnordered)
2767 return GetUndefBooleanConstant();
2768 [[fallthrough]];
2769 case ISD::SETOEQ: return getBoolConstant(R==APFloat::cmpEqual, dl, VT,
2770 OpVT);
2771 case ISD::SETNE: if (R==APFloat::cmpUnordered)
2772 return GetUndefBooleanConstant();
2773 [[fallthrough]];
2775 R==APFloat::cmpLessThan, dl, VT,
2776 OpVT);
2777 case ISD::SETLT: if (R==APFloat::cmpUnordered)
2778 return GetUndefBooleanConstant();
2779 [[fallthrough]];
2780 case ISD::SETOLT: return getBoolConstant(R==APFloat::cmpLessThan, dl, VT,
2781 OpVT);
2782 case ISD::SETGT: if (R==APFloat::cmpUnordered)
2783 return GetUndefBooleanConstant();
2784 [[fallthrough]];
2786 VT, OpVT);
2787 case ISD::SETLE: if (R==APFloat::cmpUnordered)
2788 return GetUndefBooleanConstant();
2789 [[fallthrough]];
2791 R==APFloat::cmpEqual, dl, VT,
2792 OpVT);
2793 case ISD::SETGE: if (R==APFloat::cmpUnordered)
2794 return GetUndefBooleanConstant();
2795 [[fallthrough]];
2797 R==APFloat::cmpEqual, dl, VT, OpVT);
2798 case ISD::SETO: return getBoolConstant(R!=APFloat::cmpUnordered, dl, VT,
2799 OpVT);
2800 case ISD::SETUO: return getBoolConstant(R==APFloat::cmpUnordered, dl, VT,
2801 OpVT);
2803 R==APFloat::cmpEqual, dl, VT,
2804 OpVT);
2805 case ISD::SETUNE: return getBoolConstant(R!=APFloat::cmpEqual, dl, VT,
2806 OpVT);
2808 R==APFloat::cmpLessThan, dl, VT,
2809 OpVT);
2811 R==APFloat::cmpUnordered, dl, VT,
2812 OpVT);
2814 VT, OpVT);
2815 case ISD::SETUGE: return getBoolConstant(R!=APFloat::cmpLessThan, dl, VT,
2816 OpVT);
2817 }
2818 } else if (N1CFP && OpVT.isSimple() && !N2.isUndef()) {
2819 // Ensure that the constant occurs on the RHS.
2821 if (!TLI->isCondCodeLegal(SwappedCond, OpVT.getSimpleVT()))
2822 return SDValue();
2823 return getSetCC(dl, VT, N2, N1, SwappedCond, /*Chain=*/{},
2824 /*IsSignaling=*/false, Flags);
2825 } else if ((N2CFP && N2CFP->getValueAPF().isNaN()) ||
2826 (OpVT.isFloatingPoint() && (N1.isUndef() || N2.isUndef()))) {
2827 // If an operand is known to be a nan (or undef that could be a nan), we can
2828 // fold it.
2829 // Choosing NaN for the undef will always make unordered comparison succeed
2830 // and ordered comparison fails.
2831 // Matches behavior in llvm::ConstantFoldCompareInstruction.
2832 switch (ISD::getUnorderedFlavor(Cond)) {
2833 default:
2834 llvm_unreachable("Unknown flavor!");
2835 case 0: // Known false.
2836 return getBoolConstant(false, dl, VT, OpVT);
2837 case 1: // Known true.
2838 return getBoolConstant(true, dl, VT, OpVT);
2839 case 2: // Undefined.
2840 return GetUndefBooleanConstant();
2841 }
2842 }
2843
2844 // Could not fold it.
2845 return SDValue();
2846}
2847
2848/// SignBitIsZero - Return true if the sign bit of Op is known to be zero. We
2849/// use this predicate to simplify operations downstream.
2851 unsigned BitWidth = Op.getScalarValueSizeInBits();
2853}
2854
2855// TODO: Should have argument to specify if sign bit of nan is ignorable.
2857 if (Depth >= MaxRecursionDepth)
2858 return false; // Limit search depth.
2859
2860 unsigned Opc = Op.getOpcode();
2861 switch (Opc) {
2862 case ISD::FABS:
2863 return true;
2864 case ISD::AssertNoFPClass: {
2865 FPClassTest NoFPClass =
2866 static_cast<FPClassTest>(Op.getConstantOperandVal(1));
2867
2868 const FPClassTest TestMask = fcNan | fcNegative;
2869 return (NoFPClass & TestMask) == TestMask;
2870 }
2871 case ISD::ARITH_FENCE:
2872 return SignBitIsZeroFP(Op.getOperand(0), Depth + 1);
2873 case ISD::FEXP:
2874 case ISD::FEXP2:
2875 case ISD::FEXP10:
2876 return Op->getFlags().hasNoNaNs();
2877 case ISD::FMINNUM:
2878 case ISD::FMINNUM_IEEE:
2879 case ISD::FMINIMUM:
2880 case ISD::FMINIMUMNUM:
2881 return SignBitIsZeroFP(Op.getOperand(1), Depth + 1) &&
2882 SignBitIsZeroFP(Op.getOperand(0), Depth + 1);
2883 case ISD::FMAXNUM:
2884 case ISD::FMAXNUM_IEEE:
2885 case ISD::FMAXIMUM:
2886 case ISD::FMAXIMUMNUM:
2887 // TODO: If we can ignore the sign bit of nans, only one side being known 0
2888 // is sufficient.
2889 return SignBitIsZeroFP(Op.getOperand(1), Depth + 1) &&
2890 SignBitIsZeroFP(Op.getOperand(0), Depth + 1);
2891 default:
2892 return false;
2893 }
2894
2895 llvm_unreachable("covered opcode switch");
2896}
2897
2898/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
2899/// this predicate to simplify operations downstream. Mask is known to be zero
2900/// for bits that V cannot have.
2902 unsigned Depth) const {
2903 return Mask.isSubsetOf(computeKnownBits(V, Depth).Zero);
2904}
2905
2906/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero in
2907/// DemandedElts. We use this predicate to simplify operations downstream.
2908/// Mask is known to be zero for bits that V cannot have.
2910 const APInt &DemandedElts,
2911 unsigned Depth) const {
2912 return Mask.isSubsetOf(computeKnownBits(V, DemandedElts, Depth).Zero);
2913}
2914
2915/// MaskedVectorIsZero - Return true if 'Op' is known to be zero in
2916/// DemandedElts. We use this predicate to simplify operations downstream.
2918 unsigned Depth /* = 0 */) const {
2919 return computeKnownBits(V, DemandedElts, Depth).isZero();
2920}
2921
2922/// MaskedValueIsAllOnes - Return true if '(Op & Mask) == Mask'.
2924 unsigned Depth) const {
2925 return Mask.isSubsetOf(computeKnownBits(V, Depth).One);
2926}
2927
2929 const APInt &DemandedElts,
2930 unsigned Depth) const {
2931 EVT VT = Op.getValueType();
2932 assert(VT.isVector() && !VT.isScalableVector() && "Only for fixed vectors!");
2933
2934 unsigned NumElts = VT.getVectorNumElements();
2935 assert(DemandedElts.getBitWidth() == NumElts && "Unexpected demanded mask.");
2936
2937 APInt KnownZeroElements = APInt::getZero(NumElts);
2938 for (unsigned EltIdx = 0; EltIdx != NumElts; ++EltIdx) {
2939 if (!DemandedElts[EltIdx])
2940 continue; // Don't query elements that are not demanded.
2941 APInt Mask = APInt::getOneBitSet(NumElts, EltIdx);
2942 if (MaskedVectorIsZero(Op, Mask, Depth))
2943 KnownZeroElements.setBit(EltIdx);
2944 }
2945 return KnownZeroElements;
2946}
2947
2948/// isSplatValue - Return true if the vector V has the same value
2949/// across all DemandedElts. For scalable vectors, we don't know the
2950/// number of lanes at compile time. Instead, we use a 1 bit APInt
2951/// to represent a conservative value for all lanes; that is, that
2952/// one bit value is implicitly splatted across all lanes.
2953bool SelectionDAG::isSplatValue(SDValue V, const APInt &DemandedElts,
2954 APInt &UndefElts, unsigned Depth) const {
2955 unsigned Opcode = V.getOpcode();
2956 EVT VT = V.getValueType();
2957 assert(VT.isVector() && "Vector type expected");
2958 assert((!VT.isScalableVector() || DemandedElts.getBitWidth() == 1) &&
2959 "scalable demanded bits are ignored");
2960
2961 if (!DemandedElts)
2962 return false; // No demanded elts, better to assume we don't know anything.
2963
2964 if (Depth >= MaxRecursionDepth)
2965 return false; // Limit search depth.
2966
2967 // Deal with some common cases here that work for both fixed and scalable
2968 // vector types.
2969 switch (Opcode) {
2970 case ISD::SPLAT_VECTOR:
2971 UndefElts = V.getOperand(0).isUndef()
2972 ? APInt::getAllOnes(DemandedElts.getBitWidth())
2973 : APInt(DemandedElts.getBitWidth(), 0);
2974 return true;
2975 case ISD::ADD:
2976 case ISD::SUB:
2977 case ISD::AND:
2978 case ISD::XOR:
2979 case ISD::OR: {
2980 APInt UndefLHS, UndefRHS;
2981 SDValue LHS = V.getOperand(0);
2982 SDValue RHS = V.getOperand(1);
2983 // Only recognize splats with the same demanded undef elements for both
2984 // operands, otherwise we might fail to handle binop-specific undef
2985 // handling.
2986 // e.g. (and undef, 0) -> 0 etc.
2987 if (isSplatValue(LHS, DemandedElts, UndefLHS, Depth + 1) &&
2988 isSplatValue(RHS, DemandedElts, UndefRHS, Depth + 1) &&
2989 (DemandedElts & UndefLHS) == (DemandedElts & UndefRHS)) {
2990 UndefElts = UndefLHS | UndefRHS;
2991 return true;
2992 }
2993 return false;
2994 }
2995 case ISD::ABS:
2997 case ISD::TRUNCATE:
2998 case ISD::SIGN_EXTEND:
2999 case ISD::ZERO_EXTEND:
3000 return isSplatValue(V.getOperand(0), DemandedElts, UndefElts, Depth + 1);
3001 default:
3002 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
3003 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID)
3004 return TLI->isSplatValueForTargetNode(V, DemandedElts, UndefElts, *this,
3005 Depth);
3006 break;
3007 }
3008
3009 // We don't support other cases than those above for scalable vectors at
3010 // the moment.
3011 if (VT.isScalableVector())
3012 return false;
3013
3014 unsigned NumElts = VT.getVectorNumElements();
3015 assert(NumElts == DemandedElts.getBitWidth() && "Vector size mismatch");
3016 UndefElts = APInt::getZero(NumElts);
3017
3018 switch (Opcode) {
3019 case ISD::BUILD_VECTOR: {
3020 SDValue Scl;
3021 for (unsigned i = 0; i != NumElts; ++i) {
3022 SDValue Op = V.getOperand(i);
3023 if (Op.isUndef()) {
3024 UndefElts.setBit(i);
3025 continue;
3026 }
3027 if (!DemandedElts[i])
3028 continue;
3029 if (Scl && Scl != Op)
3030 return false;
3031 Scl = Op;
3032 }
3033 return true;
3034 }
3035 case ISD::VECTOR_SHUFFLE: {
3036 // Check if this is a shuffle node doing a splat or a shuffle of a splat.
3037 APInt DemandedLHS = APInt::getZero(NumElts);
3038 APInt DemandedRHS = APInt::getZero(NumElts);
3039 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(V)->getMask();
3040 for (int i = 0; i != (int)NumElts; ++i) {
3041 int M = Mask[i];
3042 if (M < 0) {
3043 UndefElts.setBit(i);
3044 continue;
3045 }
3046 if (!DemandedElts[i])
3047 continue;
3048 if (M < (int)NumElts)
3049 DemandedLHS.setBit(M);
3050 else
3051 DemandedRHS.setBit(M - NumElts);
3052 }
3053
3054 // If we aren't demanding either op, assume there's no splat.
3055 // If we are demanding both ops, assume there's no splat.
3056 if ((DemandedLHS.isZero() && DemandedRHS.isZero()) ||
3057 (!DemandedLHS.isZero() && !DemandedRHS.isZero()))
3058 return false;
3059
3060 // See if the demanded elts of the source op is a splat or we only demand
3061 // one element, which should always be a splat.
3062 // TODO: Handle source ops splats with undefs.
3063 auto CheckSplatSrc = [&](SDValue Src, const APInt &SrcElts) {
3064 APInt SrcUndefs;
3065 return (SrcElts.popcount() == 1) ||
3066 (isSplatValue(Src, SrcElts, SrcUndefs, Depth + 1) &&
3067 (SrcElts & SrcUndefs).isZero());
3068 };
3069 if (!DemandedLHS.isZero())
3070 return CheckSplatSrc(V.getOperand(0), DemandedLHS);
3071 return CheckSplatSrc(V.getOperand(1), DemandedRHS);
3072 }
3074 // Offset the demanded elts by the subvector index.
3075 SDValue Src = V.getOperand(0);
3076 // We don't support scalable vectors at the moment.
3077 if (Src.getValueType().isScalableVector())
3078 return false;
3079 uint64_t Idx = V.getConstantOperandVal(1);
3080 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
3081 APInt UndefSrcElts;
3082 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
3083 if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) {
3084 UndefElts = UndefSrcElts.extractBits(NumElts, Idx);
3085 return true;
3086 }
3087 break;
3088 }
3092 // Widen the demanded elts by the src element count.
3093 SDValue Src = V.getOperand(0);
3094 // We don't support scalable vectors at the moment.
3095 if (Src.getValueType().isScalableVector())
3096 return false;
3097 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
3098 APInt UndefSrcElts;
3099 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts);
3100 if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) {
3101 UndefElts = UndefSrcElts.trunc(NumElts);
3102 return true;
3103 }
3104 break;
3105 }
3106 case ISD::BITCAST: {
3107 SDValue Src = V.getOperand(0);
3108 EVT SrcVT = Src.getValueType();
3109 unsigned SrcBitWidth = SrcVT.getScalarSizeInBits();
3110 unsigned BitWidth = VT.getScalarSizeInBits();
3111
3112 // Ignore bitcasts from unsupported types.
3113 // TODO: Add fp support?
3114 if (!SrcVT.isVector() || !SrcVT.isInteger() || !VT.isInteger())
3115 break;
3116
3117 // Bitcast 'small element' vector to 'large element' vector.
3118 if ((BitWidth % SrcBitWidth) == 0) {
3119 // See if each sub element is a splat.
3120 unsigned Scale = BitWidth / SrcBitWidth;
3121 unsigned NumSrcElts = SrcVT.getVectorNumElements();
3122 APInt ScaledDemandedElts =
3123 APIntOps::ScaleBitMask(DemandedElts, NumSrcElts);
3124 for (unsigned I = 0; I != Scale; ++I) {
3125 APInt SubUndefElts;
3126 APInt SubDemandedElt = APInt::getOneBitSet(Scale, I);
3127 APInt SubDemandedElts = APInt::getSplat(NumSrcElts, SubDemandedElt);
3128 SubDemandedElts &= ScaledDemandedElts;
3129 if (!isSplatValue(Src, SubDemandedElts, SubUndefElts, Depth + 1))
3130 return false;
3131 // TODO: Add support for merging sub undef elements.
3132 if (!SubUndefElts.isZero())
3133 return false;
3134 }
3135 return true;
3136 }
3137 break;
3138 }
3139 }
3140
3141 return false;
3142}
3143
3144/// Helper wrapper to main isSplatValue function.
3145bool SelectionDAG::isSplatValue(SDValue V, bool AllowUndefs) const {
3146 EVT VT = V.getValueType();
3147 assert(VT.isVector() && "Vector type expected");
3148
3149 APInt UndefElts;
3150 // Since the number of lanes in a scalable vector is unknown at compile time,
3151 // we track one bit which is implicitly broadcast to all lanes. This means
3152 // that all lanes in a scalable vector are considered demanded.
3153 APInt DemandedElts
3155 return isSplatValue(V, DemandedElts, UndefElts) &&
3156 (AllowUndefs || !UndefElts);
3157}
3158
3161
3162 EVT VT = V.getValueType();
3163 unsigned Opcode = V.getOpcode();
3164 switch (Opcode) {
3165 default: {
3166 APInt UndefElts;
3167 // Since the number of lanes in a scalable vector is unknown at compile time,
3168 // we track one bit which is implicitly broadcast to all lanes. This means
3169 // that all lanes in a scalable vector are considered demanded.
3170 APInt DemandedElts
3172
3173 if (isSplatValue(V, DemandedElts, UndefElts)) {
3174 if (VT.isScalableVector()) {
3175 // DemandedElts and UndefElts are ignored for scalable vectors, since
3176 // the only supported cases are SPLAT_VECTOR nodes.
3177 SplatIdx = 0;
3178 } else {
3179 // Handle case where all demanded elements are UNDEF.
3180 if (DemandedElts.isSubsetOf(UndefElts)) {
3181 SplatIdx = 0;
3182 return getUNDEF(VT);
3183 }
3184 SplatIdx = (UndefElts & DemandedElts).countr_one();
3185 }
3186 return V;
3187 }
3188 break;
3189 }
3190 case ISD::SPLAT_VECTOR:
3191 SplatIdx = 0;
3192 return V;
3193 case ISD::VECTOR_SHUFFLE: {
3194 assert(!VT.isScalableVector());
3195 // Check if this is a shuffle node doing a splat.
3196 // TODO - remove this and rely purely on SelectionDAG::isSplatValue,
3197 // getTargetVShiftNode currently struggles without the splat source.
3198 auto *SVN = cast<ShuffleVectorSDNode>(V);
3199 if (!SVN->isSplat())
3200 break;
3201 int Idx = SVN->getSplatIndex();
3202 int NumElts = V.getValueType().getVectorNumElements();
3203 SplatIdx = Idx % NumElts;
3204 return V.getOperand(Idx / NumElts);
3205 }
3206 }
3207
3208 return SDValue();
3209}
3210
3212 int SplatIdx;
3213 if (SDValue SrcVector = getSplatSourceVector(V, SplatIdx)) {
3214 EVT SVT = SrcVector.getValueType().getScalarType();
3215 EVT LegalSVT = SVT;
3216 if (LegalTypes && !TLI->isTypeLegal(SVT)) {
3217 if (!SVT.isInteger())
3218 return SDValue();
3219 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
3220 if (LegalSVT.bitsLT(SVT))
3221 return SDValue();
3222 }
3223 return getExtractVectorElt(SDLoc(V), LegalSVT, SrcVector, SplatIdx);
3224 }
3225 return SDValue();
3226}
3227
3228std::optional<ConstantRange>
3230 unsigned Depth) const {
3231 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
3232 V.getOpcode() == ISD::SRA) &&
3233 "Unknown shift node");
3234 // Shifting more than the bitwidth is not valid.
3235 unsigned BitWidth = V.getScalarValueSizeInBits();
3236
3237 if (auto *Cst = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
3238 const APInt &ShAmt = Cst->getAPIntValue();
3239 if (ShAmt.uge(BitWidth))
3240 return std::nullopt;
3241 return ConstantRange(ShAmt);
3242 }
3243
3244 if (auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1))) {
3245 const APInt *MinAmt = nullptr, *MaxAmt = nullptr;
3246 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
3247 if (!DemandedElts[i])
3248 continue;
3249 auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i));
3250 if (!SA) {
3251 MinAmt = MaxAmt = nullptr;
3252 break;
3253 }
3254 const APInt &ShAmt = SA->getAPIntValue();
3255 if (ShAmt.uge(BitWidth))
3256 return std::nullopt;
3257 if (!MinAmt || MinAmt->ugt(ShAmt))
3258 MinAmt = &ShAmt;
3259 if (!MaxAmt || MaxAmt->ult(ShAmt))
3260 MaxAmt = &ShAmt;
3261 }
3262 assert(((!MinAmt && !MaxAmt) || (MinAmt && MaxAmt)) &&
3263 "Failed to find matching min/max shift amounts");
3264 if (MinAmt && MaxAmt)
3265 return ConstantRange(*MinAmt, *MaxAmt + 1);
3266 }
3267
3268 // Use computeKnownBits to find a hidden constant/knownbits (usually type
3269 // legalized). e.g. Hidden behind multiple bitcasts/build_vector/casts etc.
3270 KnownBits KnownAmt = computeKnownBits(V.getOperand(1), DemandedElts, Depth);
3271 if (KnownAmt.getMaxValue().ult(BitWidth))
3272 return ConstantRange::fromKnownBits(KnownAmt, /*IsSigned=*/false);
3273
3274 return std::nullopt;
3275}
3276
3277std::optional<unsigned>
3279 unsigned Depth) const {
3280 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
3281 V.getOpcode() == ISD::SRA) &&
3282 "Unknown shift node");
3283 if (std::optional<ConstantRange> AmtRange =
3284 getValidShiftAmountRange(V, DemandedElts, Depth))
3285 if (const APInt *ShAmt = AmtRange->getSingleElement())
3286 return ShAmt->getZExtValue();
3287 return std::nullopt;
3288}
3289
3290std::optional<unsigned>
3292 APInt DemandedElts = getDemandAllEltsMask(V);
3293 return getValidShiftAmount(V, DemandedElts, Depth);
3294}
3295
3296std::optional<unsigned>
3298 unsigned Depth) const {
3299 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
3300 V.getOpcode() == ISD::SRA) &&
3301 "Unknown shift node");
3302 if (std::optional<ConstantRange> AmtRange =
3303 getValidShiftAmountRange(V, DemandedElts, Depth))
3304 return AmtRange->getUnsignedMin().getZExtValue();
3305 return std::nullopt;
3306}
3307
3308std::optional<unsigned>
3310 APInt DemandedElts = getDemandAllEltsMask(V);
3311 return getValidMinimumShiftAmount(V, DemandedElts, Depth);
3312}
3313
3314std::optional<unsigned>
3316 unsigned Depth) const {
3317 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
3318 V.getOpcode() == ISD::SRA) &&
3319 "Unknown shift node");
3320 if (std::optional<ConstantRange> AmtRange =
3321 getValidShiftAmountRange(V, DemandedElts, Depth))
3322 return AmtRange->getUnsignedMax().getZExtValue();
3323 return std::nullopt;
3324}
3325
3326std::optional<unsigned>
3328 APInt DemandedElts = getDemandAllEltsMask(V);
3329 return getValidMaximumShiftAmount(V, DemandedElts, Depth);
3330}
3331
3332/// Determine which bits of Op are known to be either zero or one and return
3333/// them in Known. For vectors, the known bits are those that are shared by
3334/// every vector element.
3336 APInt DemandedElts = getDemandAllEltsMask(Op);
3337 return computeKnownBits(Op, DemandedElts, Depth);
3338}
3339
3340/// Determine which bits of Op are known to be either zero or one and return
3341/// them in Known. The DemandedElts argument allows us to only collect the known
3342/// bits that are shared by the requested vector elements.
3344 unsigned Depth) const {
3345 unsigned BitWidth = Op.getScalarValueSizeInBits();
3346
3347 KnownBits Known(BitWidth); // Don't know anything.
3348
3349 if (auto OptAPInt = Op->bitcastToAPInt()) {
3350 // We know all of the bits for a constant!
3351 return KnownBits::makeConstant(*std::move(OptAPInt));
3352 }
3353
3354 if (Depth >= MaxRecursionDepth)
3355 return Known; // Limit search depth.
3356
3357 KnownBits Known2;
3358 unsigned NumElts = DemandedElts.getBitWidth();
3359 assert((!Op.getValueType().isScalableVector() || NumElts == 1) &&
3360 "DemandedElts for scalable vectors must be 1 to represent all lanes");
3361 assert((!Op.getValueType().isFixedLengthVector() ||
3362 NumElts == Op.getValueType().getVectorNumElements()) &&
3363 "Unexpected vector size");
3364
3365 if (!DemandedElts)
3366 return Known; // No demanded elts, better to assume we don't know anything.
3367
3368 unsigned Opcode = Op.getOpcode();
3369 switch (Opcode) {
3370 case ISD::FREEZE: {
3371 if (isGuaranteedNotToBeUndefOrPoison(Op.getOperand(0), DemandedElts,
3373 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3374 break;
3375 }
3376 case ISD::MERGE_VALUES:
3377 return computeKnownBits(Op.getOperand(Op.getResNo()), DemandedElts,
3378 Depth + 1);
3379 case ISD::SPLAT_VECTOR: {
3380 SDValue SrcOp = Op.getOperand(0);
3381 assert(SrcOp.getValueSizeInBits() >= BitWidth &&
3382 "Expected SPLAT_VECTOR implicit truncation");
3383 // Implicitly truncate the bits to match the official semantics of
3384 // SPLAT_VECTOR.
3386 break;
3387 }
3389 unsigned ScalarSize = Op.getOperand(0).getScalarValueSizeInBits();
3390 assert(ScalarSize * Op.getNumOperands() == BitWidth &&
3391 "Expected SPLAT_VECTOR_PARTS scalars to cover element width");
3392 for (auto [I, SrcOp] : enumerate(Op->ops())) {
3393 Known.insertBits(computeKnownBits(SrcOp, Depth + 1), ScalarSize * I);
3394 }
3395 break;
3396 }
3397 case ISD::STEP_VECTOR: {
3398 const APInt &Step = Op.getConstantOperandAPInt(0);
3399
3400 if (Step.isPowerOf2())
3401 Known.Zero.setLowBits(Step.logBase2());
3402
3404
3405 if (!isUIntN(BitWidth, Op.getValueType().getVectorMinNumElements()))
3406 break;
3407 const APInt MinNumElts =
3408 APInt(BitWidth, Op.getValueType().getVectorMinNumElements());
3409
3410 bool Overflow;
3411 const APInt MaxNumElts = getVScaleRange(&F, BitWidth)
3413 .umul_ov(MinNumElts, Overflow);
3414 if (Overflow)
3415 break;
3416
3417 const APInt MaxValue = (MaxNumElts - 1).umul_ov(Step, Overflow);
3418 if (Overflow)
3419 break;
3420
3421 Known.Zero.setHighBits(MaxValue.countl_zero());
3422 break;
3423 }
3424 case ISD::BUILD_VECTOR:
3425 assert(!Op.getValueType().isScalableVector());
3426 // Collect the known bits that are shared by every demanded vector element.
3427 Known.setAllConflict();
3428 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
3429 if (!DemandedElts[i])
3430 continue;
3431
3432 SDValue SrcOp = Op.getOperand(i);
3433 if (SrcOp.getOpcode() == ISD::POISON)
3434 continue;
3435
3436 Known2 = computeKnownBits(SrcOp, Depth + 1);
3437
3438 // BUILD_VECTOR can implicitly truncate sources, we must handle this.
3439 if (SrcOp.getValueSizeInBits() != BitWidth) {
3440 assert(SrcOp.getValueSizeInBits() > BitWidth &&
3441 "Expected BUILD_VECTOR implicit truncation");
3442 Known2 = Known2.trunc(BitWidth);
3443 }
3444
3445 // Known bits are the values that are shared by every demanded element.
3446 Known = Known.intersectWith(Known2);
3447
3448 // If we don't know any bits, early out.
3449 if (Known.isUnknown())
3450 break;
3451 }
3452
3453 // If every demanded element was poison, we know nothing.
3454 if (Known.hasConflict())
3455 Known.resetAll();
3456 break;
3457 case ISD::VECTOR_COMPRESS: {
3458 SDValue Vec = Op.getOperand(0);
3459 SDValue PassThru = Op.getOperand(2);
3460 Known = computeKnownBits(PassThru, DemandedElts, Depth + 1);
3461 // If we don't know any bits, early out.
3462 if (Known.isUnknown())
3463 break;
3464 Known2 = computeKnownBits(Vec, Depth + 1);
3465 Known = Known.intersectWith(Known2);
3466 break;
3467 }
3468 case ISD::VECTOR_SHUFFLE: {
3469 assert(!Op.getValueType().isScalableVector());
3470 // Collect the known bits that are shared by every vector element referenced
3471 // by the shuffle.
3472 APInt DemandedLHS, DemandedRHS;
3474 assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
3475 if (!getShuffleDemandedElts(NumElts, SVN->getMask(), DemandedElts,
3476 DemandedLHS, DemandedRHS))
3477 break;
3478
3479 // Known bits are the values that are shared by every demanded element.
3480 Known.setAllConflict();
3481 if (!!DemandedLHS) {
3482 SDValue LHS = Op.getOperand(0);
3483 Known2 = computeKnownBits(LHS, DemandedLHS, Depth + 1);
3484 Known = Known.intersectWith(Known2);
3485 }
3486 // If we don't know any bits, early out.
3487 if (Known.isUnknown())
3488 break;
3489 if (!!DemandedRHS) {
3490 SDValue RHS = Op.getOperand(1);
3491 Known2 = computeKnownBits(RHS, DemandedRHS, Depth + 1);
3492 Known = Known.intersectWith(Known2);
3493 }
3494 break;
3495 }
3496 case ISD::VSCALE: {
3498 const APInt &Multiplier = Op.getConstantOperandAPInt(0);
3500 break;
3501 }
3502 case ISD::CONCAT_VECTORS: {
3503 if (Op.getValueType().isScalableVector())
3504 break;
3505 // Split DemandedElts and test each of the demanded subvectors.
3506 Known.setAllConflict();
3507 EVT SubVectorVT = Op.getOperand(0).getValueType();
3508 unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
3509 unsigned NumSubVectors = Op.getNumOperands();
3510 for (unsigned i = 0; i != NumSubVectors; ++i) {
3511 APInt DemandedSub =
3512 DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts);
3513 if (!!DemandedSub) {
3514 SDValue Sub = Op.getOperand(i);
3515 Known2 = computeKnownBits(Sub, DemandedSub, Depth + 1);
3516 Known = Known.intersectWith(Known2);
3517 }
3518 // If we don't know any bits, early out.
3519 if (Known.isUnknown())
3520 break;
3521 }
3522 break;
3523 }
3524 case ISD::INSERT_SUBVECTOR: {
3525 if (Op.getValueType().isScalableVector())
3526 break;
3527 // Demand any elements from the subvector and the remainder from the src its
3528 // inserted into.
3529 SDValue Src = Op.getOperand(0);
3530 SDValue Sub = Op.getOperand(1);
3531 uint64_t Idx = Op.getConstantOperandVal(2);
3532 unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
3533 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
3534 APInt DemandedSrcElts = DemandedElts;
3535 DemandedSrcElts.clearBits(Idx, Idx + NumSubElts);
3536
3537 Known.setAllConflict();
3538 if (!!DemandedSubElts) {
3539 Known = computeKnownBits(Sub, DemandedSubElts, Depth + 1);
3540 if (Known.isUnknown())
3541 break; // early-out.
3542 }
3543 if (!!DemandedSrcElts) {
3544 Known2 = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
3545 Known = Known.intersectWith(Known2);
3546 }
3547 break;
3548 }
3550 // Offset the demanded elts by the subvector index.
3551 SDValue Src = Op.getOperand(0);
3552
3553 APInt DemandedSrcElts;
3554 if (Src.getValueType().isScalableVector())
3555 DemandedSrcElts = APInt(1, 1); // <=> 'demand all elements'
3556 else {
3557 uint64_t Idx = Op.getConstantOperandVal(1);
3558 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
3559 DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
3560 }
3561 Known = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
3562 break;
3563 }
3564 case ISD::SCALAR_TO_VECTOR: {
3565 if (Op.getValueType().isScalableVector())
3566 break;
3567 // We know about scalar_to_vector as much as we know about it source,
3568 // which becomes the first element of otherwise unknown vector.
3569 if (DemandedElts != 1)
3570 break;
3571
3572 SDValue N0 = Op.getOperand(0);
3573 Known = computeKnownBits(N0, Depth + 1);
3574 if (N0.getValueSizeInBits() != BitWidth)
3575 Known = Known.trunc(BitWidth);
3576
3577 break;
3578 }
3579 case ISD::BITCAST: {
3580 if (Op.getValueType().isScalableVector())
3581 break;
3582
3583 SDValue N0 = Op.getOperand(0);
3584 EVT SubVT = N0.getValueType();
3585 unsigned SubBitWidth = SubVT.getScalarSizeInBits();
3586
3587 // Ignore bitcasts from unsupported types.
3588 if (!(SubVT.isInteger() || SubVT.isFloatingPoint()))
3589 break;
3590
3591 // Fast handling of 'identity' bitcasts.
3592 if (BitWidth == SubBitWidth) {
3593 Known = computeKnownBits(N0, DemandedElts, Depth + 1);
3594 break;
3595 }
3596
3597 bool IsLE = getDataLayout().isLittleEndian();
3598
3599 // Bitcast 'small element' vector to 'large element' scalar/vector.
3600 if ((BitWidth % SubBitWidth) == 0) {
3601 assert(N0.getValueType().isVector() && "Expected bitcast from vector");
3602
3603 // Collect known bits for the (larger) output by collecting the known
3604 // bits from each set of sub elements and shift these into place.
3605 // We need to separately call computeKnownBits for each set of
3606 // sub elements as the knownbits for each is likely to be different.
3607 unsigned SubScale = BitWidth / SubBitWidth;
3608 APInt SubDemandedElts(NumElts * SubScale, 0);
3609 for (unsigned i = 0; i != NumElts; ++i)
3610 if (DemandedElts[i])
3611 SubDemandedElts.setBit(i * SubScale);
3612
3613 for (unsigned i = 0; i != SubScale; ++i) {
3614 Known2 = computeKnownBits(N0, SubDemandedElts.shl(i),
3615 Depth + 1);
3616 unsigned Shifts = IsLE ? i : SubScale - 1 - i;
3617 Known.insertBits(Known2, SubBitWidth * Shifts);
3618 }
3619 }
3620
3621 // Bitcast 'large element' scalar/vector to 'small element' vector.
3622 if ((SubBitWidth % BitWidth) == 0) {
3623 assert(Op.getValueType().isVector() && "Expected bitcast to vector");
3624
3625 // Collect known bits for the (smaller) output by collecting the known
3626 // bits from the overlapping larger input elements and extracting the
3627 // sub sections we actually care about.
3628 unsigned SubScale = SubBitWidth / BitWidth;
3629 APInt SubDemandedElts =
3630 APIntOps::ScaleBitMask(DemandedElts, NumElts / SubScale);
3631 Known2 = computeKnownBits(N0, SubDemandedElts, Depth + 1);
3632
3633 Known.setAllConflict();
3634 for (unsigned i = 0; i != NumElts; ++i)
3635 if (DemandedElts[i]) {
3636 unsigned Shifts = IsLE ? i : NumElts - 1 - i;
3637 unsigned Offset = (Shifts % SubScale) * BitWidth;
3638 Known = Known.intersectWith(Known2.extractBits(BitWidth, Offset));
3639 // If we don't know any bits, early out.
3640 if (Known.isUnknown())
3641 break;
3642 }
3643 }
3644 break;
3645 }
3646 case ISD::AND:
3647 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3648 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3649
3650 Known &= Known2;
3651 break;
3652 case ISD::OR:
3653 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3654 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3655
3656 Known |= Known2;
3657 break;
3658 case ISD::XOR:
3659 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3660 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3661
3662 Known ^= Known2;
3663 break;
3664 case ISD::MUL: {
3665 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3666 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3667 bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1);
3668 // TODO: SelfMultiply can be poison, but not undef.
3669 if (SelfMultiply)
3670 SelfMultiply &= isGuaranteedNotToBeUndefOrPoison(
3671 Op.getOperand(0), DemandedElts, UndefPoisonKind::UndefOrPoison,
3672 Depth + 1);
3673 Known = KnownBits::mul(Known, Known2, SelfMultiply);
3674
3675 // If the multiplication is known not to overflow, the product of a number
3676 // with itself is non-negative. Only do this if we didn't already computed
3677 // the opposite value for the sign bit.
3678 if (Op->getFlags().hasNoSignedWrap() &&
3679 Op.getOperand(0) == Op.getOperand(1) &&
3680 !Known.isNegative())
3681 Known.makeNonNegative();
3682 break;
3683 }
3684 case ISD::MULHU: {
3685 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3686 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3687 Known = KnownBits::mulhu(Known, Known2);
3688 break;
3689 }
3690 case ISD::MULHS: {
3691 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3692 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3693 Known = KnownBits::mulhs(Known, Known2);
3694 break;
3695 }
3696 case ISD::ABDU: {
3697 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3698 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3699 Known = KnownBits::abdu(Known, Known2);
3700 break;
3701 }
3702 case ISD::ABDS: {
3703 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3704 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3705 Known = KnownBits::abds(Known, Known2);
3706 unsigned SignBits1 =
3707 ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
3708 if (SignBits1 == 1)
3709 break;
3710 unsigned SignBits0 =
3711 ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3712 Known.Zero.setHighBits(std::min(SignBits0, SignBits1) - 1);
3713 break;
3714 }
3715 case ISD::UMUL_LOHI: {
3716 assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3717 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3718 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3719 bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1);
3720 if (Op.getResNo() == 0)
3721 Known = KnownBits::mul(Known, Known2, SelfMultiply);
3722 else
3723 Known = KnownBits::mulhu(Known, Known2);
3724 break;
3725 }
3726 case ISD::SMUL_LOHI: {
3727 assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3728 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3729 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3730 bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1);
3731 if (Op.getResNo() == 0)
3732 Known = KnownBits::mul(Known, Known2, SelfMultiply);
3733 else
3734 Known = KnownBits::mulhs(Known, Known2);
3735 break;
3736 }
3737 case ISD::AVGFLOORU: {
3738 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3739 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3740 Known = KnownBits::avgFloorU(Known, Known2);
3741 break;
3742 }
3743 case ISD::AVGCEILU: {
3744 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3745 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3746 Known = KnownBits::avgCeilU(Known, Known2);
3747 break;
3748 }
3749 case ISD::AVGFLOORS: {
3750 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3751 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3752 Known = KnownBits::avgFloorS(Known, Known2);
3753 break;
3754 }
3755 case ISD::AVGCEILS: {
3756 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3757 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3758 Known = KnownBits::avgCeilS(Known, Known2);
3759 break;
3760 }
3761 case ISD::SELECT:
3762 case ISD::VSELECT:
3763 Known = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
3764 // If we don't know any bits, early out.
3765 if (Known.isUnknown())
3766 break;
3767 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth+1);
3768
3769 // Only known if known in both the LHS and RHS.
3770 Known = Known.intersectWith(Known2);
3771 break;
3772 case ISD::SELECT_CC:
3773 Known = computeKnownBits(Op.getOperand(3), DemandedElts, Depth+1);
3774 // If we don't know any bits, early out.
3775 if (Known.isUnknown())
3776 break;
3777 Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
3778
3779 // Only known if known in both the LHS and RHS.
3780 Known = Known.intersectWith(Known2);
3781 break;
3782 case ISD::SMULO:
3783 case ISD::UMULO:
3784 if (Op.getResNo() != 1)
3785 break;
3786 // The boolean result conforms to getBooleanContents.
3787 // If we know the result of a setcc has the top bits zero, use this info.
3788 // We know that we have an integer-based boolean since these operations
3789 // are only available for integer.
3790 if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
3792 BitWidth > 1)
3793 Known.Zero.setBitsFrom(1);
3794 break;
3795 case ISD::SETCC:
3796 case ISD::SETCCCARRY:
3797 case ISD::STRICT_FSETCC:
3798 case ISD::STRICT_FSETCCS: {
3799 unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
3800 // If we know the result of a setcc has the top bits zero, use this info.
3801 if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
3803 BitWidth > 1)
3804 Known.Zero.setBitsFrom(1);
3805 break;
3806 }
3807 case ISD::SHL: {
3808 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3809 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3810
3811 bool NUW = Op->getFlags().hasNoUnsignedWrap();
3812 bool NSW = Op->getFlags().hasNoSignedWrap();
3813
3814 bool ShAmtNonZero = Known2.isNonZero();
3815
3816 Known = KnownBits::shl(Known, Known2, NUW, NSW, ShAmtNonZero);
3817
3818 // Minimum shift low bits are known zero.
3819 if (std::optional<unsigned> ShMinAmt =
3820 getValidMinimumShiftAmount(Op, DemandedElts, Depth + 1))
3821 Known.Zero.setLowBits(*ShMinAmt);
3822 break;
3823 }
3824 case ISD::SRL:
3825 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3826 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3827 Known = KnownBits::lshr(Known, Known2, /*ShAmtNonZero=*/false,
3828 Op->getFlags().hasExact());
3829
3830 // Minimum shift high bits are known zero.
3831 if (std::optional<unsigned> ShMinAmt =
3832 getValidMinimumShiftAmount(Op, DemandedElts, Depth + 1))
3833 Known.Zero.setHighBits(*ShMinAmt);
3834 break;
3835 case ISD::SRA:
3836 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3837 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3838 Known = KnownBits::ashr(Known, Known2, /*ShAmtNonZero=*/false,
3839 Op->getFlags().hasExact());
3840 break;
3841 case ISD::ROTL:
3842 case ISD::ROTR:
3843 if (ConstantSDNode *C =
3844 isConstOrConstSplat(Op.getOperand(1), DemandedElts)) {
3845 unsigned Amt = C->getAPIntValue().urem(BitWidth);
3846
3847 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3848
3849 // Canonicalize to ROTR.
3850 if (Opcode == ISD::ROTL && Amt != 0)
3851 Amt = BitWidth - Amt;
3852
3853 Known.Zero = Known.Zero.rotr(Amt);
3854 Known.One = Known.One.rotr(Amt);
3855 }
3856 break;
3857 case ISD::FSHL:
3858 case ISD::FSHR:
3859 if (ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(2), DemandedElts)) {
3860 unsigned Amt = C->getAPIntValue().urem(BitWidth);
3861
3862 // For fshl, 0-shift returns the 1st arg.
3863 // For fshr, 0-shift returns the 2nd arg.
3864 if (Amt == 0) {
3865 Known = computeKnownBits(Op.getOperand(Opcode == ISD::FSHL ? 0 : 1),
3866 DemandedElts, Depth + 1);
3867 break;
3868 }
3869
3870 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
3871 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
3872 const APInt ShAmt(BitWidth, Amt);
3873 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3874 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3875 Known = Opcode == ISD::FSHL ? KnownBits::fshl(Known, Known2, ShAmt)
3876 : KnownBits::fshr(Known, Known2, ShAmt);
3877 }
3878 break;
3879 case ISD::SHL_PARTS:
3880 case ISD::SRA_PARTS:
3881 case ISD::SRL_PARTS: {
3882 assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3883
3884 // Collect lo/hi source values and concatenate.
3885 unsigned LoBits = Op.getOperand(0).getScalarValueSizeInBits();
3886 unsigned HiBits = Op.getOperand(1).getScalarValueSizeInBits();
3887 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3888 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3889 Known = Known2.concat(Known);
3890
3891 // Collect shift amount.
3892 Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1);
3893
3894 if (Opcode == ISD::SHL_PARTS)
3895 Known = KnownBits::shl(Known, Known2);
3896 else if (Opcode == ISD::SRA_PARTS)
3897 Known = KnownBits::ashr(Known, Known2);
3898 else // if (Opcode == ISD::SRL_PARTS)
3899 Known = KnownBits::lshr(Known, Known2);
3900
3901 // TODO: Minimum shift low/high bits are known zero.
3902
3903 if (Op.getResNo() == 0)
3904 Known = Known.extractBits(LoBits, 0);
3905 else
3906 Known = Known.extractBits(HiBits, LoBits);
3907 break;
3908 }
3910 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3911 EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3912 Known = Known.sextInReg(EVT.getScalarSizeInBits());
3913 break;
3914 }
3915 case ISD::CTTZ:
3916 case ISD::CTTZ_ZERO_POISON: {
3917 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3918 // If we have a known 1, its position is our upper bound.
3919 unsigned PossibleTZ = Known2.countMaxTrailingZeros();
3920 unsigned LowBits = llvm::bit_width(PossibleTZ);
3921 Known.Zero.setBitsFrom(LowBits);
3922 break;
3923 }
3924 case ISD::CTLZ:
3925 case ISD::CTLZ_ZERO_POISON: {
3926 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3927 // If we have a known 1, its position is our upper bound.
3928 unsigned PossibleLZ = Known2.countMaxLeadingZeros();
3929 unsigned LowBits = llvm::bit_width(PossibleLZ);
3930 Known.Zero.setBitsFrom(LowBits);
3931 break;
3932 }
3933 case ISD::CTLS: {
3934 unsigned MinRedundantSignBits =
3935 ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1) - 1;
3936 ConstantRange Range(APInt(BitWidth, MinRedundantSignBits),
3938 Known = Range.toKnownBits();
3939 break;
3940 }
3941 case ISD::CTPOP: {
3942 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3943 // If we know some of the bits are zero, they can't be one.
3944 unsigned PossibleOnes = Known2.countMaxPopulation();
3945 Known.Zero.setBitsFrom(llvm::bit_width(PossibleOnes));
3946 break;
3947 }
3948 case ISD::PARITY: {
3949 // Parity returns 0 everywhere but the LSB.
3950 Known.Zero.setBitsFrom(1);
3951 break;
3952 }
3953 case ISD::PDEP: {
3954 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3955 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3956 Known = KnownBits::pdep(Known2, Known);
3957 break;
3958 }
3959 case ISD::PEXT: {
3960 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3961 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3962 Known = KnownBits::pext(Known2, Known);
3963 break;
3964 }
3965 case ISD::CLMUL: {
3966 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3967 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3968 Known = KnownBits::clmul(Known, Known2);
3969 break;
3970 }
3971 case ISD::MGATHER:
3972 case ISD::MLOAD: {
3973 ISD::LoadExtType ETy =
3974 (Opcode == ISD::MGATHER)
3975 ? cast<MaskedGatherSDNode>(Op)->getExtensionType()
3976 : cast<MaskedLoadSDNode>(Op)->getExtensionType();
3977 if (ETy == ISD::ZEXTLOAD) {
3978 EVT MemVT = cast<MemSDNode>(Op)->getMemoryVT();
3979 KnownBits Known0(MemVT.getScalarSizeInBits());
3980 return Known0.zext(BitWidth);
3981 }
3982 break;
3983 }
3984 case ISD::LOAD: {
3986 const Constant *Cst = TLI->getTargetConstantFromLoad(LD);
3987 if (ISD::isNON_EXTLoad(LD) && Cst) {
3988 // Determine any common known bits from the loaded constant pool value.
3989 Type *CstTy = Cst->getType();
3990 if ((NumElts * BitWidth) == CstTy->getPrimitiveSizeInBits() &&
3991 !Op.getValueType().isScalableVector()) {
3992 // If its a vector splat, then we can (quickly) reuse the scalar path.
3993 // NOTE: We assume all elements match and none are UNDEF.
3994 if (CstTy->isVectorTy()) {
3995 if (const Constant *Splat = Cst->getSplatValue()) {
3996 Cst = Splat;
3997 CstTy = Cst->getType();
3998 }
3999 }
4000 // TODO - do we need to handle different bitwidths?
4001 if (CstTy->isVectorTy() && BitWidth == CstTy->getScalarSizeInBits()) {
4002 // Iterate across all vector elements finding common known bits.
4003 Known.setAllConflict();
4004 for (unsigned i = 0; i != NumElts; ++i) {
4005 if (!DemandedElts[i])
4006 continue;
4007 if (Constant *Elt = Cst->getAggregateElement(i)) {
4008 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
4009 const APInt &Value = CInt->getValue();
4010 Known.One &= Value;
4011 Known.Zero &= ~Value;
4012 continue;
4013 }
4014 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
4015 APInt Value = CFP->getValueAPF().bitcastToAPInt();
4016 Known.One &= Value;
4017 Known.Zero &= ~Value;
4018 continue;
4019 }
4020 }
4021 Known.One.clearAllBits();
4022 Known.Zero.clearAllBits();
4023 break;
4024 }
4025 } else if (BitWidth == CstTy->getPrimitiveSizeInBits()) {
4026 if (auto *CInt = dyn_cast<ConstantInt>(Cst)) {
4027 Known = KnownBits::makeConstant(CInt->getValue());
4028 } else if (auto *CFP = dyn_cast<ConstantFP>(Cst)) {
4029 Known =
4030 KnownBits::makeConstant(CFP->getValueAPF().bitcastToAPInt());
4031 }
4032 }
4033 }
4034 } else if (Op.getResNo() == 0) {
4035 unsigned ScalarMemorySize = LD->getMemoryVT().getScalarSizeInBits();
4036 KnownBits KnownScalarMemory(ScalarMemorySize);
4037 if (const MDNode *MD = LD->getRanges())
4038 computeKnownBitsFromRangeMetadata(*MD, KnownScalarMemory);
4039
4040 // Extend the Known bits from memory to the size of the scalar result.
4041 if (ISD::isZEXTLoad(Op.getNode()))
4042 Known = KnownScalarMemory.zext(BitWidth);
4043 else if (ISD::isSEXTLoad(Op.getNode()))
4044 Known = KnownScalarMemory.sext(BitWidth);
4045 else if (ISD::isEXTLoad(Op.getNode()))
4046 Known = KnownScalarMemory.anyext(BitWidth);
4047 else
4048 Known = KnownScalarMemory;
4049 assert(Known.getBitWidth() == BitWidth);
4050 return Known;
4051 }
4052 break;
4053 }
4055 if (Op.getValueType().isScalableVector())
4056 break;
4057 EVT InVT = Op.getOperand(0).getValueType();
4058 APInt InDemandedElts = DemandedElts.zext(InVT.getVectorNumElements());
4059 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
4060 Known = Known.zext(BitWidth);
4061 break;
4062 }
4063 case ISD::ZERO_EXTEND: {
4064 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4065 Known = Known.zext(BitWidth);
4066 break;
4067 }
4069 if (Op.getValueType().isScalableVector())
4070 break;
4071 EVT InVT = Op.getOperand(0).getValueType();
4072 APInt InDemandedElts = DemandedElts.zext(InVT.getVectorNumElements());
4073 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
4074 // If the sign bit is known to be zero or one, then sext will extend
4075 // it to the top bits, else it will just zext.
4076 Known = Known.sext(BitWidth);
4077 break;
4078 }
4079 case ISD::SIGN_EXTEND: {
4080 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4081 // If the sign bit is known to be zero or one, then sext will extend
4082 // it to the top bits, else it will just zext.
4083 Known = Known.sext(BitWidth);
4084 break;
4085 }
4087 if (Op.getValueType().isScalableVector())
4088 break;
4089 EVT InVT = Op.getOperand(0).getValueType();
4090 APInt InDemandedElts = DemandedElts.zext(InVT.getVectorNumElements());
4091 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
4092 Known = Known.anyext(BitWidth);
4093 break;
4094 }
4095 case ISD::ANY_EXTEND: {
4096 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4097 Known = Known.anyext(BitWidth);
4098 break;
4099 }
4100 case ISD::TRUNCATE: {
4101 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4102 Known = Known.trunc(BitWidth);
4103 break;
4104 }
4105 case ISD::TRUNCATE_SSAT_S: {
4106 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4107 Known = Known.truncSSat(BitWidth);
4108 break;
4109 }
4110 case ISD::TRUNCATE_SSAT_U: {
4111 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4112 Known = Known.truncSSatU(BitWidth);
4113 break;
4114 }
4115 case ISD::TRUNCATE_USAT_U: {
4116 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4117 Known = Known.truncUSat(BitWidth);
4118 break;
4119 }
4120 case ISD::AssertZext: {
4121 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
4123 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4124 Known.Zero |= (~InMask);
4125 Known.One &= (~Known.Zero);
4126 break;
4127 }
4128 case ISD::AssertAlign: {
4129 unsigned LogOfAlign = Log2(cast<AssertAlignSDNode>(Op)->getAlign());
4130 assert(LogOfAlign != 0);
4131
4132 // TODO: Should use maximum with source
4133 // If a node is guaranteed to be aligned, set low zero bits accordingly as
4134 // well as clearing one bits.
4135 Known.Zero.setLowBits(LogOfAlign);
4136 Known.One.clearLowBits(LogOfAlign);
4137 break;
4138 }
4139 case ISD::AssertNoFPClass: {
4140 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4141
4142 FPClassTest NoFPClass =
4143 static_cast<FPClassTest>(Op.getConstantOperandVal(1));
4144 const FPClassTest NegativeTestMask = fcNan | fcNegative;
4145 if ((NoFPClass & NegativeTestMask) == NegativeTestMask) {
4146 // Cannot be negative.
4147 Known.makeNonNegative();
4148 }
4149
4150 const FPClassTest PositiveTestMask = fcNan | fcPositive;
4151 if ((NoFPClass & PositiveTestMask) == PositiveTestMask) {
4152 // Cannot be positive.
4153 Known.makeNegative();
4154 }
4155
4156 break;
4157 }
4158 case ISD::FABS:
4159 // fabs clears the sign bit
4160 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4161 Known.makeNonNegative();
4162 break;
4163 case ISD::FGETSIGN:
4164 // All bits are zero except the low bit.
4165 Known.Zero.setBitsFrom(1);
4166 break;
4167 case ISD::ADD: {
4168 SDNodeFlags Flags = Op.getNode()->getFlags();
4169 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4170 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4171 bool SelfAdd = Op.getOperand(0) == Op.getOperand(1) &&
4173 Op.getOperand(0), DemandedElts,
4175 Known = KnownBits::add(Known, Known2, Flags.hasNoSignedWrap(),
4176 Flags.hasNoUnsignedWrap(), SelfAdd);
4177 break;
4178 }
4179 case ISD::SUB: {
4180 SDNodeFlags Flags = Op.getNode()->getFlags();
4181 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4182 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4183 Known = KnownBits::sub(Known, Known2, Flags.hasNoSignedWrap(),
4184 Flags.hasNoUnsignedWrap());
4185 break;
4186 }
4187 case ISD::USUBO:
4188 case ISD::SSUBO:
4189 case ISD::USUBO_CARRY:
4190 case ISD::SSUBO_CARRY:
4191 if (Op.getResNo() == 1) {
4192 // If we know the result of a setcc has the top bits zero, use this info.
4193 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
4195 BitWidth > 1)
4196 Known.Zero.setBitsFrom(1);
4197 break;
4198 }
4199 [[fallthrough]];
4200 case ISD::SUBC: {
4201 assert(Op.getResNo() == 0 &&
4202 "We only compute knownbits for the difference here.");
4203
4204 // With USUBO_CARRY and SSUBO_CARRY a borrow bit may be added in.
4205 KnownBits Borrow(1);
4206 if (Opcode == ISD::USUBO_CARRY || Opcode == ISD::SSUBO_CARRY) {
4207 Borrow = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1);
4208 // Borrow has bit width 1
4209 Borrow = Borrow.trunc(1);
4210 } else {
4211 Borrow.setAllZero();
4212 }
4213
4214 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4215 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4216 Known = KnownBits::computeForSubBorrow(Known, Known2, Borrow);
4217 break;
4218 }
4219 case ISD::UADDO:
4220 case ISD::SADDO:
4221 case ISD::UADDO_CARRY:
4222 case ISD::SADDO_CARRY:
4223 if (Op.getResNo() == 1) {
4224 // If we know the result of a setcc has the top bits zero, use this info.
4225 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
4227 BitWidth > 1)
4228 Known.Zero.setBitsFrom(1);
4229 break;
4230 }
4231 [[fallthrough]];
4232 case ISD::ADDC:
4233 case ISD::ADDE: {
4234 assert(Op.getResNo() == 0 && "We only compute knownbits for the sum here.");
4235
4236 // With ADDE and UADDO_CARRY, a carry bit may be added in.
4237 KnownBits Carry(1);
4238 if (Opcode == ISD::ADDE)
4239 // Can't track carry from glue, set carry to unknown.
4240 Carry.resetAll();
4241 else if (Opcode == ISD::UADDO_CARRY || Opcode == ISD::SADDO_CARRY) {
4242 Carry = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1);
4243 // Carry has bit width 1
4244 Carry = Carry.trunc(1);
4245 } else {
4246 Carry.setAllZero();
4247 }
4248
4249 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4250 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4251 Known = KnownBits::computeForAddCarry(Known, Known2, Carry);
4252 break;
4253 }
4254 case ISD::UDIV: {
4255 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4256 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4257 Known = KnownBits::udiv(Known, Known2, Op->getFlags().hasExact());
4258 break;
4259 }
4260 case ISD::SDIV: {
4261 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4262 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4263 Known = KnownBits::sdiv(Known, Known2, Op->getFlags().hasExact());
4264 break;
4265 }
4266 case ISD::SREM: {
4267 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4268 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4269 Known = KnownBits::srem(Known, Known2);
4270 break;
4271 }
4272 case ISD::UREM: {
4273 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4274 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4275 Known = KnownBits::urem(Known, Known2);
4276 break;
4277 }
4278 case ISD::EXTRACT_ELEMENT: {
4279 Known = computeKnownBits(Op.getOperand(0), Depth+1);
4280 const unsigned Index = Op.getConstantOperandVal(1);
4281 const unsigned EltBitWidth = Op.getValueSizeInBits();
4282
4283 // Remove low part of known bits mask
4284 Known.Zero = Known.Zero.getHiBits(Known.getBitWidth() - Index * EltBitWidth);
4285 Known.One = Known.One.getHiBits(Known.getBitWidth() - Index * EltBitWidth);
4286
4287 // Remove high part of known bit mask
4288 Known = Known.trunc(EltBitWidth);
4289 break;
4290 }
4292 SDValue InVec = Op.getOperand(0);
4293 SDValue EltNo = Op.getOperand(1);
4294 EVT VecVT = InVec.getValueType();
4295 // computeKnownBits not yet implemented for scalable vectors.
4296 if (VecVT.isScalableVector())
4297 break;
4298 const unsigned EltBitWidth = VecVT.getScalarSizeInBits();
4299 const unsigned NumSrcElts = VecVT.getVectorNumElements();
4300
4301 // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know
4302 // anything about the extended bits.
4303 if (BitWidth > EltBitWidth)
4304 Known = Known.trunc(EltBitWidth);
4305
4306 // If we know the element index, just demand that vector element, else for
4307 // an unknown element index, ignore DemandedElts and demand them all.
4308 APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
4309 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
4310 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
4311 DemandedSrcElts =
4312 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
4313
4314 Known = computeKnownBits(InVec, DemandedSrcElts, Depth + 1);
4315 if (BitWidth > EltBitWidth)
4316 Known = Known.anyext(BitWidth);
4317 break;
4318 }
4320 if (Op.getValueType().isScalableVector())
4321 break;
4322
4323 // If we know the element index, split the demand between the
4324 // source vector and the inserted element, otherwise assume we need
4325 // the original demanded vector elements and the value.
4326 SDValue InVec = Op.getOperand(0);
4327 SDValue InVal = Op.getOperand(1);
4328 SDValue EltNo = Op.getOperand(2);
4329 bool DemandedVal = true;
4330 APInt DemandedVecElts = DemandedElts;
4331 auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
4332 if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
4333 unsigned EltIdx = CEltNo->getZExtValue();
4334 DemandedVal = !!DemandedElts[EltIdx];
4335 DemandedVecElts.clearBit(EltIdx);
4336 }
4337 Known.setAllConflict();
4338 if (DemandedVal) {
4339 Known2 = computeKnownBits(InVal, Depth + 1);
4340 Known = Known.intersectWith(Known2.zextOrTrunc(BitWidth));
4341 }
4342 if (!!DemandedVecElts) {
4343 Known2 = computeKnownBits(InVec, DemandedVecElts, Depth + 1);
4344 Known = Known.intersectWith(Known2);
4345 }
4346 break;
4347 }
4348 case ISD::BITREVERSE: {
4349 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4350 Known = Known2.reverseBits();
4351 break;
4352 }
4353 case ISD::BSWAP: {
4354 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4355 Known = Known2.byteSwap();
4356 break;
4357 }
4358 case ISD::ABS:
4359 case ISD::ABS_MIN_POISON: {
4360 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4361 Known = Known2.abs();
4362 Known.Zero.setHighBits(
4363 ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1) - 1);
4364 break;
4365 }
4366 case ISD::USUBSAT: {
4367 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4368 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4369 Known = KnownBits::usub_sat(Known, Known2);
4370 break;
4371 }
4372 case ISD::UMIN: {
4373 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4374 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4375 Known = KnownBits::umin(Known, Known2);
4376 break;
4377 }
4378 case ISD::UMAX: {
4379 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4380 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4381 Known = KnownBits::umax(Known, Known2);
4382 break;
4383 }
4384 case ISD::SMIN:
4385 case ISD::SMAX: {
4386 // If we have a clamp pattern, we know that the number of sign bits will be
4387 // the minimum of the clamp min/max range.
4388 bool IsMax = (Opcode == ISD::SMAX);
4389 ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
4390 if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
4391 if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
4392 CstHigh =
4393 isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
4394 if (CstLow && CstHigh) {
4395 if (!IsMax)
4396 std::swap(CstLow, CstHigh);
4397
4398 const APInt &ValueLow = CstLow->getAPIntValue();
4399 const APInt &ValueHigh = CstHigh->getAPIntValue();
4400 if (ValueLow.sle(ValueHigh)) {
4401 unsigned LowSignBits = ValueLow.getNumSignBits();
4402 unsigned HighSignBits = ValueHigh.getNumSignBits();
4403 unsigned MinSignBits = std::min(LowSignBits, HighSignBits);
4404 if (ValueLow.isNegative() && ValueHigh.isNegative()) {
4405 Known.One.setHighBits(MinSignBits);
4406 break;
4407 }
4408 if (ValueLow.isNonNegative() && ValueHigh.isNonNegative()) {
4409 Known.Zero.setHighBits(MinSignBits);
4410 break;
4411 }
4412 }
4413 }
4414
4415 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4416 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4417 if (IsMax)
4418 Known = KnownBits::smax(Known, Known2);
4419 else
4420 Known = KnownBits::smin(Known, Known2);
4421
4422 // For SMAX, if CstLow is non-negative we know the result will be
4423 // non-negative and thus all sign bits are 0.
4424 // TODO: There's an equivalent of this for smin with negative constant for
4425 // known ones.
4426 if (IsMax && CstLow) {
4427 const APInt &ValueLow = CstLow->getAPIntValue();
4428 if (ValueLow.isNonNegative()) {
4429 unsigned SignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
4430 Known.Zero.setHighBits(std::min(SignBits, ValueLow.getNumSignBits()));
4431 }
4432 }
4433
4434 break;
4435 }
4436 case ISD::UINT_TO_FP: {
4437 Known.makeNonNegative();
4438 break;
4439 }
4440 case ISD::SINT_TO_FP: {
4441 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4442 if (Known2.isNonNegative())
4443 Known.makeNonNegative();
4444 else if (Known2.isNegative())
4445 Known.makeNegative();
4446 break;
4447 }
4448 case ISD::FP_TO_UINT_SAT: {
4449 // FP_TO_UINT_SAT produces an unsigned value that fits in the saturating VT.
4450 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
4452 break;
4453 }
4454 case ISD::ATOMIC_LOAD: {
4455 // If we are looking at the loaded value.
4456 if (Op.getResNo() == 0) {
4457 auto *AT = cast<AtomicSDNode>(Op);
4458 unsigned ScalarMemorySize = AT->getMemoryVT().getScalarSizeInBits();
4459 KnownBits KnownScalarMemory(ScalarMemorySize);
4460 if (const MDNode *MD = AT->getRanges())
4461 computeKnownBitsFromRangeMetadata(*MD, KnownScalarMemory);
4462
4463 switch (AT->getExtensionType()) {
4464 case ISD::ZEXTLOAD:
4465 Known = KnownScalarMemory.zext(BitWidth);
4466 break;
4467 case ISD::SEXTLOAD:
4468 Known = KnownScalarMemory.sext(BitWidth);
4469 break;
4470 case ISD::EXTLOAD:
4471 switch (TLI->getExtendForAtomicOps()) {
4472 case ISD::ZERO_EXTEND:
4473 Known = KnownScalarMemory.zext(BitWidth);
4474 break;
4475 case ISD::SIGN_EXTEND:
4476 Known = KnownScalarMemory.sext(BitWidth);
4477 break;
4478 default:
4479 Known = KnownScalarMemory.anyext(BitWidth);
4480 break;
4481 }
4482 break;
4483 case ISD::NON_EXTLOAD:
4484 Known = KnownScalarMemory;
4485 break;
4486 }
4487 assert(Known.getBitWidth() == BitWidth);
4488 }
4489 break;
4490 }
4492 if (Op.getResNo() == 1) {
4493 // The boolean result conforms to getBooleanContents.
4494 // If we know the result of a setcc has the top bits zero, use this info.
4495 // We know that we have an integer-based boolean since these operations
4496 // are only available for integer.
4497 if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
4499 BitWidth > 1)
4500 Known.Zero.setBitsFrom(1);
4501 break;
4502 }
4503 [[fallthrough]];
4505 case ISD::ATOMIC_SWAP:
4516 case ISD::ATOMIC_LOAD_UMAX: {
4517 // If we are looking at the loaded value.
4518 if (Op.getResNo() == 0) {
4519 auto *AT = cast<AtomicSDNode>(Op);
4520 unsigned MemBits = AT->getMemoryVT().getScalarSizeInBits();
4521
4522 if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND)
4523 Known.Zero.setBitsFrom(MemBits);
4524 }
4525 break;
4526 }
4527 case ISD::FrameIndex:
4528 case ISD::TargetFrameIndex: {
4529 const MachineFunction &MF = getMachineFunction();
4530 int FrameIdx = cast<FrameIndexSDNode>(Op)->getIndex();
4531 TLI->computeKnownBitsForStackObjectPointer(
4532 Known, MF, MF.getFrameInfo().getObjectAlign(FrameIdx));
4533 break;
4534 }
4535
4536 default:
4537 if (Opcode < ISD::BUILTIN_OP_END)
4538 break;
4539 [[fallthrough]];
4543 // Allow the target to implement this method for its nodes.
4544 TLI->computeKnownBitsForTargetNode(Op, Known, DemandedElts, *this, Depth);
4545 break;
4546 }
4547
4548 return Known;
4549}
4550
4551/// Convert ConstantRange OverflowResult into SelectionDAG::OverflowKind.
4564
4567 // X + 0 never overflow
4568 if (isNullConstant(N1))
4569 return OFK_Never;
4570
4571 // If both operands each have at least two sign bits, the addition
4572 // cannot overflow.
4573 if (ComputeNumSignBits(N0) > 1 && ComputeNumSignBits(N1) > 1)
4574 return OFK_Never;
4575
4576 // TODO: Add ConstantRange::signedAddMayOverflow handling.
4577 return OFK_Sometime;
4578}
4579
4582 // X + 0 never overflow
4583 if (isNullConstant(N1))
4584 return OFK_Never;
4585
4586 // mulhi + 1 never overflow
4587 KnownBits N1Known = computeKnownBits(N1);
4588 if (N0.getOpcode() == ISD::UMUL_LOHI && N0.getResNo() == 1 &&
4589 N1Known.getMaxValue().ult(2))
4590 return OFK_Never;
4591
4592 KnownBits N0Known = computeKnownBits(N0);
4593 if (N1.getOpcode() == ISD::UMUL_LOHI && N1.getResNo() == 1 &&
4594 N0Known.getMaxValue().ult(2))
4595 return OFK_Never;
4596
4597 // Fallback to ConstantRange::unsignedAddMayOverflow handling.
4598 ConstantRange N0Range = ConstantRange::fromKnownBits(N0Known, false);
4599 ConstantRange N1Range = ConstantRange::fromKnownBits(N1Known, false);
4600 return mapOverflowResult(N0Range.unsignedAddMayOverflow(N1Range));
4601}
4602
4605 // X - 0 never overflow
4606 if (isNullConstant(N1))
4607 return OFK_Never;
4608
4609 // If both operands each have at least two sign bits, the subtraction
4610 // cannot overflow.
4611 if (ComputeNumSignBits(N0) > 1 && ComputeNumSignBits(N1) > 1)
4612 return OFK_Never;
4613
4614 KnownBits N0Known = computeKnownBits(N0);
4615 KnownBits N1Known = computeKnownBits(N1);
4616 ConstantRange N0Range = ConstantRange::fromKnownBits(N0Known, true);
4617 ConstantRange N1Range = ConstantRange::fromKnownBits(N1Known, true);
4618 return mapOverflowResult(N0Range.signedSubMayOverflow(N1Range));
4619}
4620
4623 // X - 0 never overflow
4624 if (isNullConstant(N1))
4625 return OFK_Never;
4626
4627 ConstantRange N0Range =
4628 computeConstantRangeIncludingKnownBits(N0, /*ForSigned=*/false);
4629 ConstantRange N1Range =
4630 computeConstantRangeIncludingKnownBits(N1, /*ForSigned=*/false);
4631 return mapOverflowResult(N0Range.unsignedSubMayOverflow(N1Range));
4632}
4633
4636 // X * 0 and X * 1 never overflow.
4637 if (isNullConstant(N1) || isOneConstant(N1))
4638 return OFK_Never;
4639
4642 return mapOverflowResult(N0Range.unsignedMulMayOverflow(N1Range));
4643}
4644
4647 // X * 0 and X * 1 never overflow.
4648 if (isNullConstant(N1) || isOneConstant(N1))
4649 return OFK_Never;
4650
4651 // Get the size of the result.
4652 unsigned BitWidth = N0.getScalarValueSizeInBits();
4653
4654 // Sum of the sign bits.
4655 unsigned SignBits = ComputeNumSignBits(N0) + ComputeNumSignBits(N1);
4656
4657 // If we have enough sign bits, then there's no overflow.
4658 if (SignBits > BitWidth + 1)
4659 return OFK_Never;
4660
4661 if (SignBits == BitWidth + 1) {
4662 // The overflow occurs when the true multiplication of the
4663 // the operands is the minimum negative number.
4664 KnownBits N0Known = computeKnownBits(N0);
4665 KnownBits N1Known = computeKnownBits(N1);
4666 // If one of the operands is non-negative, then there's no
4667 // overflow.
4668 if (N0Known.isNonNegative() || N1Known.isNonNegative())
4669 return OFK_Never;
4670 }
4671
4672 return OFK_Sometime;
4673}
4674
4676 unsigned Depth) const {
4677 APInt DemandedElts = getDemandAllEltsMask(Op);
4678 return computeConstantRange(Op, DemandedElts, ForSigned, Depth);
4679}
4680
4682 const APInt &DemandedElts,
4683 bool ForSigned,
4684 unsigned Depth) const {
4685 EVT VT = Op.getValueType();
4686 unsigned BitWidth = VT.getScalarSizeInBits();
4687
4688 if (Depth >= MaxRecursionDepth)
4689 return ConstantRange::getFull(BitWidth);
4690
4691 if (ConstantSDNode *C = isConstOrConstSplat(Op, DemandedElts))
4692 return ConstantRange(C->getAPIntValue());
4693
4694 unsigned Opcode = Op.getOpcode();
4695 switch (Opcode) {
4696 case ISD::VSCALE: {
4698 const APInt &Multiplier = Op.getConstantOperandAPInt(0);
4699 return getVScaleRange(&F, BitWidth).multiply(Multiplier);
4700 }
4701 default:
4702 break;
4703 }
4704
4705 return ConstantRange::getFull(BitWidth);
4706}
4707
4710 unsigned Depth) const {
4711 APInt DemandedElts = getDemandAllEltsMask(Op);
4712 return computeConstantRangeIncludingKnownBits(Op, DemandedElts, ForSigned,
4713 Depth);
4714}
4715
4717 SDValue Op, const APInt &DemandedElts, bool ForSigned,
4718 unsigned Depth) const {
4719 KnownBits Known = computeKnownBits(Op, DemandedElts, Depth);
4721 ConstantRange CR2 = computeConstantRange(Op, DemandedElts, ForSigned, Depth);
4724 return CR1.intersectWith(CR2, RangeType);
4725}
4726
4728 unsigned Depth) const {
4729 APInt DemandedElts = getDemandAllEltsMask(Val);
4730 return isKnownToBeAPowerOfTwo(Val, DemandedElts, OrZero, Depth);
4731}
4732
4734 const APInt &DemandedElts,
4735 bool OrZero, unsigned Depth) const {
4736 if (Depth >= MaxRecursionDepth)
4737 return false; // Limit search depth.
4738
4739 EVT OpVT = Val.getValueType();
4740 unsigned BitWidth = OpVT.getScalarSizeInBits();
4741 [[maybe_unused]] unsigned NumElts = DemandedElts.getBitWidth();
4742 assert((!OpVT.isScalableVector() || NumElts == 1) &&
4743 "DemandedElts for scalable vectors must be 1 to represent all lanes");
4744 assert(
4745 (!OpVT.isFixedLengthVector() || NumElts == OpVT.getVectorNumElements()) &&
4746 "Unexpected vector size");
4747
4748 auto IsPowerOfTwoOrZero = [BitWidth, OrZero](const ConstantSDNode *C) {
4749 APInt V = C->getAPIntValue().zextOrTrunc(BitWidth);
4750 return (OrZero && V.isZero()) || V.isPowerOf2();
4751 };
4752
4753 // Is the constant a known power of 2 or zero?
4754 if (ISD::matchUnaryPredicate(Val, DemandedElts, IsPowerOfTwoOrZero,
4755 /*AllowUndefs=*/false, /*AllowTruncation=*/true))
4756 return true;
4757
4758 switch (Val.getOpcode()) {
4760 SDValue InVec = Val.getOperand(0);
4761 SDValue EltNo = Val.getOperand(1);
4762 EVT VecVT = InVec.getValueType();
4763
4764 // Skip scalable vectors or implicit extensions.
4765 if (VecVT.isScalableVector() ||
4766 OpVT.getScalarSizeInBits() != VecVT.getScalarSizeInBits())
4767 break;
4768
4769 // If we know the element index, just demand that vector element, else for
4770 // an unknown element index, ignore DemandedElts and demand them all.
4771 const unsigned NumSrcElts = VecVT.getVectorNumElements();
4772 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
4773 APInt DemandedSrcElts =
4774 ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts)
4775 ? APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue())
4776 : APInt::getAllOnes(NumSrcElts);
4777 return isKnownToBeAPowerOfTwo(InVec, DemandedSrcElts, OrZero, Depth + 1);
4778 }
4779
4780 case ISD::AND: {
4781 // Looking for `x & -x` pattern:
4782 // If x == 0:
4783 // x & -x -> 0
4784 // If x != 0:
4785 // x & -x -> non-zero pow2
4786 // so if we find the pattern return whether we know `x` is non-zero.
4787 SDValue X, Z;
4788 if (sd_match(Val, m_And(m_Value(X), m_Neg(m_Deferred(X)))) ||
4789 (sd_match(Val, m_And(m_Value(X), m_Sub(m_Value(Z), m_Deferred(X)))) &&
4790 MaskedVectorIsZero(Z, DemandedElts, Depth + 1)))
4791 return OrZero || isKnownNeverZero(X, DemandedElts, Depth);
4792 break;
4793 }
4794
4795 case ISD::SHL: {
4796 // A left-shift of a constant one will have exactly one bit set because
4797 // shifting the bit off the end is undefined.
4798 auto *C = isConstOrConstSplat(Val.getOperand(0), DemandedElts);
4799 if (C && C->getAPIntValue() == 1)
4800 return true;
4801 return (OrZero || isKnownNeverZero(Val, DemandedElts, Depth)) &&
4802 isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedElts, OrZero,
4803 Depth + 1);
4804 }
4805
4806 case ISD::SRL: {
4807 // A logical right-shift of a constant sign-bit will have exactly
4808 // one bit set.
4809 auto *C = isConstOrConstSplat(Val.getOperand(0), DemandedElts);
4810 if (C && C->getAPIntValue().isSignMask())
4811 return true;
4812 return (OrZero || isKnownNeverZero(Val, DemandedElts, Depth)) &&
4813 isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedElts, OrZero,
4814 Depth + 1);
4815 }
4816
4817 case ISD::TRUNCATE:
4818 return (OrZero || isKnownNeverZero(Val, DemandedElts, Depth)) &&
4819 isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedElts, OrZero,
4820 Depth + 1);
4821
4822 case ISD::ROTL:
4823 case ISD::ROTR:
4824 return isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedElts, OrZero,
4825 Depth + 1);
4826 case ISD::BSWAP:
4827 case ISD::BITREVERSE:
4828 return isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedElts, OrZero,
4829 Depth + 1);
4830
4831 case ISD::SMIN:
4832 case ISD::SMAX:
4833 case ISD::UMIN:
4834 case ISD::UMAX:
4835 return isKnownToBeAPowerOfTwo(Val.getOperand(1), DemandedElts, OrZero,
4836 Depth + 1) &&
4837 isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedElts, OrZero,
4838 Depth + 1);
4839
4840 case ISD::SELECT:
4841 case ISD::VSELECT:
4842 return isKnownToBeAPowerOfTwo(Val.getOperand(2), DemandedElts, OrZero,
4843 Depth + 1) &&
4844 isKnownToBeAPowerOfTwo(Val.getOperand(1), DemandedElts, OrZero,
4845 Depth + 1);
4846
4847 case ISD::ZERO_EXTEND:
4848 return isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedElts, OrZero,
4849 Depth + 1);
4850
4851 case ISD::VSCALE:
4852 // vscale(power-of-two) is a power-of-two
4853 return isKnownToBeAPowerOfTwo(Val.getOperand(0), /*OrZero=*/false,
4854 Depth + 1);
4855
4856 case ISD::VECTOR_SHUFFLE: {
4858 // Demanded elements with undef shuffle mask elements are unknown
4859 // - we cannot guarantee they are a power of two, so return false.
4860 APInt DemandedLHS, DemandedRHS;
4862 assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
4863 if (!getShuffleDemandedElts(NumElts, SVN->getMask(), DemandedElts,
4864 DemandedLHS, DemandedRHS))
4865 return false;
4866
4867 // All demanded elements from LHS must be known power of two.
4868 if (!!DemandedLHS && !isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedLHS,
4869 OrZero, Depth + 1))
4870 return false;
4871
4872 // All demanded elements from RHS must be known power of two.
4873 if (!!DemandedRHS && !isKnownToBeAPowerOfTwo(Val.getOperand(1), DemandedRHS,
4874 OrZero, Depth + 1))
4875 return false;
4876
4877 return true;
4878 }
4879 }
4880
4881 // More could be done here, though the above checks are enough
4882 // to handle some common cases.
4883 return false;
4884}
4885
4887 if (ConstantFPSDNode *C1 = isConstOrConstSplatFP(Val, true))
4888 return C1->getValueAPF().getExactLog2Abs() >= 0;
4889
4890 if (Val.getOpcode() == ISD::UINT_TO_FP || Val.getOpcode() == ISD::SINT_TO_FP)
4891 return isKnownToBeAPowerOfTwo(Val.getOperand(0), Depth + 1);
4892
4893 return false;
4894}
4895
4897 APInt DemandedElts = getDemandAllEltsMask(Op);
4898 return ComputeNumSignBits(Op, DemandedElts, Depth);
4899}
4900
4901unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, const APInt &DemandedElts,
4902 unsigned Depth) const {
4903 EVT VT = Op.getValueType();
4904 assert((VT.isInteger() || VT.isFloatingPoint()) && "Invalid VT!");
4905 unsigned VTBits = VT.getScalarSizeInBits();
4906 unsigned NumElts = DemandedElts.getBitWidth();
4907 unsigned Tmp, Tmp2;
4908 unsigned FirstAnswer = 1;
4909
4910 assert((!VT.isScalableVector() || NumElts == 1) &&
4911 "DemandedElts for scalable vectors must be 1 to represent all lanes");
4912
4913 if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
4914 const APInt &Val = C->getAPIntValue();
4915 return Val.getNumSignBits();
4916 }
4917
4918 if (Depth >= MaxRecursionDepth)
4919 return 1; // Limit search depth.
4920
4921 if (!DemandedElts)
4922 return 1; // No demanded elts, better to assume we don't know anything.
4923
4924 unsigned Opcode = Op.getOpcode();
4925 switch (Opcode) {
4926 default: break;
4927 case ISD::AssertSext:
4928 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
4929 return VTBits-Tmp+1;
4930 case ISD::AssertZext:
4931 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
4932 return VTBits-Tmp;
4933 case ISD::FREEZE:
4934 if (isGuaranteedNotToBeUndefOrPoison(Op.getOperand(0), DemandedElts,
4936 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4937 break;
4938 case ISD::MERGE_VALUES:
4939 return ComputeNumSignBits(Op.getOperand(Op.getResNo()), DemandedElts,
4940 Depth + 1);
4941 case ISD::SPLAT_VECTOR: {
4942 // Check if the sign bits of source go down as far as the truncated value.
4943 unsigned NumSrcBits = Op.getOperand(0).getValueSizeInBits();
4944 unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
4945 if (NumSrcSignBits > (NumSrcBits - VTBits))
4946 return NumSrcSignBits - (NumSrcBits - VTBits);
4947 break;
4948 }
4949 case ISD::BUILD_VECTOR:
4950 assert(!VT.isScalableVector());
4951 Tmp = VTBits;
4952 for (unsigned i = 0, e = Op.getNumOperands(); (i < e) && (Tmp > 1); ++i) {
4953 if (!DemandedElts[i])
4954 continue;
4955
4956 SDValue SrcOp = Op.getOperand(i);
4957 // BUILD_VECTOR can implicitly truncate sources, we handle this specially
4958 // for constant nodes to ensure we only look at the sign bits.
4960 APInt T = C->getAPIntValue().trunc(VTBits);
4961 Tmp2 = T.getNumSignBits();
4962 } else {
4963 Tmp2 = ComputeNumSignBits(SrcOp, Depth + 1);
4964
4965 if (SrcOp.getValueSizeInBits() != VTBits) {
4966 assert(SrcOp.getValueSizeInBits() > VTBits &&
4967 "Expected BUILD_VECTOR implicit truncation");
4968 unsigned ExtraBits = SrcOp.getValueSizeInBits() - VTBits;
4969 Tmp2 = (Tmp2 > ExtraBits ? Tmp2 - ExtraBits : 1);
4970 }
4971 }
4972 Tmp = std::min(Tmp, Tmp2);
4973 }
4974 return Tmp;
4975
4976 case ISD::VECTOR_COMPRESS: {
4977 SDValue Vec = Op.getOperand(0);
4978 SDValue PassThru = Op.getOperand(2);
4979 Tmp = ComputeNumSignBits(PassThru, DemandedElts, Depth + 1);
4980 if (Tmp == 1)
4981 return 1;
4982 Tmp2 = ComputeNumSignBits(Vec, Depth + 1);
4983 Tmp = std::min(Tmp, Tmp2);
4984 return Tmp;
4985 }
4986
4987 case ISD::VECTOR_SHUFFLE: {
4988 // Collect the minimum number of sign bits that are shared by every vector
4989 // element referenced by the shuffle.
4990 APInt DemandedLHS, DemandedRHS;
4992 assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
4993 if (!getShuffleDemandedElts(NumElts, SVN->getMask(), DemandedElts,
4994 DemandedLHS, DemandedRHS))
4995 return 1;
4996
4997 Tmp = std::numeric_limits<unsigned>::max();
4998 if (!!DemandedLHS)
4999 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedLHS, Depth + 1);
5000 if (!!DemandedRHS) {
5001 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedRHS, Depth + 1);
5002 Tmp = std::min(Tmp, Tmp2);
5003 }
5004 // If we don't know anything, early out and try computeKnownBits fall-back.
5005 if (Tmp == 1)
5006 break;
5007 assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
5008 return Tmp;
5009 }
5010
5011 case ISD::BITCAST: {
5012 if (VT.isScalableVector())
5013 break;
5014 SDValue N0 = Op.getOperand(0);
5015 EVT SrcVT = N0.getValueType();
5016 unsigned SrcBits = SrcVT.getScalarSizeInBits();
5017
5018 // Ignore bitcasts from unsupported types..
5019 if (!(SrcVT.isInteger() || SrcVT.isFloatingPoint()))
5020 break;
5021
5022 // Fast handling of 'identity' bitcasts.
5023 if (VTBits == SrcBits)
5024 return ComputeNumSignBits(N0, DemandedElts, Depth + 1);
5025
5026 bool IsLE = getDataLayout().isLittleEndian();
5027
5028 // Bitcast 'large element' scalar/vector to 'small element' vector.
5029 if ((SrcBits % VTBits) == 0) {
5030 assert(VT.isVector() && "Expected bitcast to vector");
5031
5032 unsigned Scale = SrcBits / VTBits;
5033 APInt SrcDemandedElts =
5034 APIntOps::ScaleBitMask(DemandedElts, NumElts / Scale);
5035
5036 // Fast case - sign splat can be simply split across the small elements.
5037 Tmp = ComputeNumSignBits(N0, SrcDemandedElts, Depth + 1);
5038 if (Tmp == SrcBits)
5039 return VTBits;
5040
5041 // Slow case - determine how far the sign extends into each sub-element.
5042 Tmp2 = VTBits;
5043 for (unsigned i = 0; i != NumElts; ++i)
5044 if (DemandedElts[i]) {
5045 unsigned SubOffset = i % Scale;
5046 SubOffset = (IsLE ? ((Scale - 1) - SubOffset) : SubOffset);
5047 SubOffset = SubOffset * VTBits;
5048 if (Tmp <= SubOffset)
5049 return 1;
5050 Tmp2 = std::min(Tmp2, Tmp - SubOffset);
5051 }
5052 return Tmp2;
5053 }
5054 break;
5055 }
5056
5058 // FP_TO_SINT_SAT produces a signed value that fits in the saturating VT.
5059 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
5060 return VTBits - Tmp + 1;
5061 case ISD::SIGN_EXTEND:
5062 Tmp = VTBits - Op.getOperand(0).getScalarValueSizeInBits();
5063 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1) + Tmp;
5065 // Max of the input and what this extends.
5066 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
5067 Tmp = VTBits-Tmp+1;
5068 Tmp2 = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
5069 return std::max(Tmp, Tmp2);
5071 if (VT.isScalableVector())
5072 break;
5073 SDValue Src = Op.getOperand(0);
5074 EVT SrcVT = Src.getValueType();
5075 APInt DemandedSrcElts = DemandedElts.zext(SrcVT.getVectorNumElements());
5076 Tmp = VTBits - SrcVT.getScalarSizeInBits();
5077 return ComputeNumSignBits(Src, DemandedSrcElts, Depth+1) + Tmp;
5078 }
5079 case ISD::SRA:
5080 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5081 // SRA X, C -> adds C sign bits.
5082 if (std::optional<unsigned> ShAmt =
5083 getValidMinimumShiftAmount(Op, DemandedElts, Depth + 1))
5084 Tmp = std::min(Tmp + *ShAmt, VTBits);
5085 return Tmp;
5086 case ISD::SHL:
5087 if (std::optional<ConstantRange> ShAmtRange =
5088 getValidShiftAmountRange(Op, DemandedElts, Depth + 1)) {
5089 unsigned MaxShAmt = ShAmtRange->getUnsignedMax().getZExtValue();
5090 unsigned MinShAmt = ShAmtRange->getUnsignedMin().getZExtValue();
5091 // Try to look through ZERO/SIGN/ANY_EXTEND. If all extended bits are
5092 // shifted out, then we can compute the number of sign bits for the
5093 // operand being extended. A future improvement could be to pass along the
5094 // "shifted left by" information in the recursive calls to
5095 // ComputeKnownSignBits. Allowing us to handle this more generically.
5096 if (ISD::isExtOpcode(Op.getOperand(0).getOpcode())) {
5097 SDValue Ext = Op.getOperand(0);
5098 EVT ExtVT = Ext.getValueType();
5099 SDValue Extendee = Ext.getOperand(0);
5100 EVT ExtendeeVT = Extendee.getValueType();
5101 unsigned SizeDifference =
5102 ExtVT.getScalarSizeInBits() - ExtendeeVT.getScalarSizeInBits();
5103 if (SizeDifference <= MinShAmt) {
5104 Tmp = SizeDifference +
5105 ComputeNumSignBits(Extendee, DemandedElts, Depth + 1);
5106 if (MaxShAmt < Tmp)
5107 return Tmp - MaxShAmt;
5108 }
5109 }
5110 // shl destroys sign bits, ensure it doesn't shift out all sign bits.
5111 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5112 if (MaxShAmt < Tmp)
5113 return Tmp - MaxShAmt;
5114 }
5115 break;
5116 case ISD::AND:
5117 case ISD::OR:
5118 case ISD::XOR: // NOT is handled here.
5119 // Logical binary ops preserve the number of sign bits at the worst.
5120 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
5121 if (Tmp != 1) {
5122 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
5123 FirstAnswer = std::min(Tmp, Tmp2);
5124 // We computed what we know about the sign bits as our first
5125 // answer. Now proceed to the generic code that uses
5126 // computeKnownBits, and pick whichever answer is better.
5127 }
5128 break;
5129
5130 case ISD::SELECT:
5131 case ISD::VSELECT:
5132 Tmp = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
5133 if (Tmp == 1) return 1; // Early out.
5134 Tmp2 = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
5135 return std::min(Tmp, Tmp2);
5136 case ISD::SELECT_CC:
5137 Tmp = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
5138 if (Tmp == 1) return 1; // Early out.
5139 Tmp2 = ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth+1);
5140 return std::min(Tmp, Tmp2);
5141
5142 case ISD::SMIN:
5143 case ISD::SMAX: {
5144 // If we have a clamp pattern, we know that the number of sign bits will be
5145 // the minimum of the clamp min/max range.
5146 bool IsMax = (Opcode == ISD::SMAX);
5147 ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
5148 if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
5149 if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
5150 CstHigh =
5151 isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
5152 if (CstLow && CstHigh) {
5153 if (!IsMax)
5154 std::swap(CstLow, CstHigh);
5155 if (CstLow->getAPIntValue().sle(CstHigh->getAPIntValue())) {
5156 Tmp = CstLow->getAPIntValue().getNumSignBits();
5157 Tmp2 = CstHigh->getAPIntValue().getNumSignBits();
5158 return std::min(Tmp, Tmp2);
5159 }
5160 }
5161
5162 // Fallback - just get the minimum number of sign bits of the operands.
5163 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5164 if (Tmp == 1)
5165 return 1; // Early out.
5166 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
5167 return std::min(Tmp, Tmp2);
5168 }
5169 case ISD::UMIN:
5170 case ISD::UMAX:
5171 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5172 if (Tmp == 1)
5173 return 1; // Early out.
5174 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
5175 return std::min(Tmp, Tmp2);
5176 case ISD::SSUBO_CARRY:
5177 case ISD::USUBO_CARRY:
5178 // sub_carry(x,x,c) -> 0/-1 (sext carry)
5179 if (Op.getResNo() == 0 && Op.getOperand(0) == Op.getOperand(1))
5180 return VTBits;
5181 [[fallthrough]];
5182 case ISD::SADDO:
5183 case ISD::UADDO:
5184 case ISD::SADDO_CARRY:
5185 case ISD::UADDO_CARRY:
5186 case ISD::SSUBO:
5187 case ISD::USUBO:
5188 case ISD::SMULO:
5189 case ISD::UMULO:
5190 if (Op.getResNo() != 1)
5191 break;
5192 // The boolean result conforms to getBooleanContents. Fall through.
5193 // If setcc returns 0/-1, all bits are sign bits.
5194 // We know that we have an integer-based boolean since these operations
5195 // are only available for integer.
5196 if (TLI->getBooleanContents(VT.isVector(), false) ==
5198 return VTBits;
5199 break;
5200 case ISD::SETCC:
5201 case ISD::SETCCCARRY:
5202 case ISD::STRICT_FSETCC:
5203 case ISD::STRICT_FSETCCS: {
5204 unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
5205 // If setcc returns 0/-1, all bits are sign bits.
5206 if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
5208 return VTBits;
5209 break;
5210 }
5212 // Semantically similar to icmp ult.
5213 if (TLI->getBooleanContents(VT.isVector(), /*isFloat=*/false) ==
5215 return VTBits;
5216 break;
5217 case ISD::ROTL:
5218 case ISD::ROTR: {
5219 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5220 ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(1), DemandedElts);
5221 FirstAnswer = SignBitsOps::rot(
5222 Tmp, VTBits, C ? std::optional(C->getAPIntValue()) : std::nullopt,
5223 Opcode == ISD::ROTR);
5224 break;
5225 }
5226 case ISD::ADD:
5227 case ISD::ADDC:
5228 // TODO: Move Operand 1 check before Operand 0 check
5229 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5230 if (Tmp == 1) return 1; // Early out.
5231
5232 // Special case decrementing a value (ADD X, -1):
5233 if (ConstantSDNode *CRHS =
5234 isConstOrConstSplat(Op.getOperand(1), DemandedElts))
5235 if (CRHS->isAllOnes()) {
5237 computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
5238
5239 // If the input is known to be 0 or 1, the output is 0/-1, which is all
5240 // sign bits set.
5241 if ((Known.Zero | 1).isAllOnes())
5242 return VTBits;
5243
5244 // If we are subtracting one from a positive number, there is no carry
5245 // out of the result.
5246 if (Known.isNonNegative())
5247 return Tmp;
5248 }
5249
5250 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
5251 if (Tmp2 == 1) return 1; // Early out.
5252
5253 // Add can have at most one carry bit. Thus we know that the output
5254 // is, at worst, one more bit than the inputs.
5255 return std::min(Tmp, Tmp2) - 1;
5256 case ISD::SUB:
5257 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
5258 if (Tmp2 == 1) return 1; // Early out.
5259
5260 // Handle NEG.
5261 if (ConstantSDNode *CLHS =
5262 isConstOrConstSplat(Op.getOperand(0), DemandedElts))
5263 if (CLHS->isZero()) {
5265 computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
5266 // If the input is known to be 0 or 1, the output is 0/-1, which is all
5267 // sign bits set.
5268 if ((Known.Zero | 1).isAllOnes())
5269 return VTBits;
5270
5271 // If the input is known to be positive (the sign bit is known clear),
5272 // the output of the NEG has the same number of sign bits as the input.
5273 if (Known.isNonNegative())
5274 return Tmp2;
5275
5276 // Otherwise, we treat this like a SUB.
5277 }
5278
5279 // Sub can have at most one carry bit. Thus we know that the output
5280 // is, at worst, one more bit than the inputs.
5281 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5282 if (Tmp == 1) return 1; // Early out.
5283 return std::min(Tmp, Tmp2) - 1;
5284 case ISD::MUL: {
5285 // The output of the Mul can be at most twice the valid bits in the inputs.
5286 unsigned SignBitsOp0 = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
5287 if (SignBitsOp0 == 1)
5288 break;
5289 unsigned SignBitsOp1 = ComputeNumSignBits(Op.getOperand(1), Depth + 1);
5290 if (SignBitsOp1 == 1)
5291 break;
5292 unsigned OutValidBits =
5293 (VTBits - SignBitsOp0 + 1) + (VTBits - SignBitsOp1 + 1);
5294 return OutValidBits > VTBits ? 1 : VTBits - OutValidBits + 1;
5295 }
5296 case ISD::AVGCEILS:
5297 case ISD::AVGFLOORS:
5298 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5299 if (Tmp == 1)
5300 return 1; // Early out.
5301 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
5302 return std::min(Tmp, Tmp2);
5303 case ISD::SREM:
5304 // The sign bit is the LHS's sign bit, except when the result of the
5305 // remainder is zero. The magnitude of the result should be less than or
5306 // equal to the magnitude of the LHS. Therefore, the result should have
5307 // at least as many sign bits as the left hand side.
5308 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5309 case ISD::TRUNCATE: {
5310 // Check if the sign bits of source go down as far as the truncated value.
5311 unsigned NumSrcBits = Op.getOperand(0).getScalarValueSizeInBits();
5312 unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
5313 if (NumSrcSignBits > (NumSrcBits - VTBits))
5314 return NumSrcSignBits - (NumSrcBits - VTBits);
5315 break;
5316 }
5317 case ISD::EXTRACT_ELEMENT: {
5318 if (VT.isScalableVector())
5319 break;
5320 const int KnownSign = ComputeNumSignBits(Op.getOperand(0), Depth+1);
5321 const int BitWidth = Op.getValueSizeInBits();
5322 const int Items = Op.getOperand(0).getValueSizeInBits() / BitWidth;
5323
5324 // Get reverse index (starting from 1), Op1 value indexes elements from
5325 // little end. Sign starts at big end.
5326 const int rIndex = Items - 1 - Op.getConstantOperandVal(1);
5327
5328 // If the sign portion ends in our element the subtraction gives correct
5329 // result. Otherwise it gives either negative or > bitwidth result
5330 return std::clamp(KnownSign - rIndex * BitWidth, 1, BitWidth);
5331 }
5333 if (VT.isScalableVector())
5334 break;
5335 // If we know the element index, split the demand between the
5336 // source vector and the inserted element, otherwise assume we need
5337 // the original demanded vector elements and the value.
5338 SDValue InVec = Op.getOperand(0);
5339 SDValue InVal = Op.getOperand(1);
5340 SDValue EltNo = Op.getOperand(2);
5341 bool DemandedVal = true;
5342 APInt DemandedVecElts = DemandedElts;
5343 auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
5344 if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
5345 unsigned EltIdx = CEltNo->getZExtValue();
5346 DemandedVal = !!DemandedElts[EltIdx];
5347 DemandedVecElts.clearBit(EltIdx);
5348 }
5349 Tmp = std::numeric_limits<unsigned>::max();
5350 if (DemandedVal) {
5351 // TODO - handle implicit truncation of inserted elements.
5352 if (InVal.getScalarValueSizeInBits() != VTBits)
5353 break;
5354 Tmp2 = ComputeNumSignBits(InVal, Depth + 1);
5355 Tmp = std::min(Tmp, Tmp2);
5356 }
5357 if (!!DemandedVecElts) {
5358 Tmp2 = ComputeNumSignBits(InVec, DemandedVecElts, Depth + 1);
5359 Tmp = std::min(Tmp, Tmp2);
5360 }
5361 assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
5362 return Tmp;
5363 }
5365 SDValue InVec = Op.getOperand(0);
5366 SDValue EltNo = Op.getOperand(1);
5367 EVT VecVT = InVec.getValueType();
5368 // ComputeNumSignBits not yet implemented for scalable vectors.
5369 if (VecVT.isScalableVector())
5370 break;
5371 const unsigned BitWidth = Op.getValueSizeInBits();
5372 const unsigned EltBitWidth = Op.getOperand(0).getScalarValueSizeInBits();
5373 const unsigned NumSrcElts = VecVT.getVectorNumElements();
5374
5375 // If BitWidth > EltBitWidth the value is anyext:ed, and we do not know
5376 // anything about sign bits. But if the sizes match we can derive knowledge
5377 // about sign bits from the vector operand.
5378 if (BitWidth != EltBitWidth)
5379 break;
5380
5381 // If we know the element index, just demand that vector element, else for
5382 // an unknown element index, ignore DemandedElts and demand them all.
5383 APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
5384 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
5385 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
5386 DemandedSrcElts =
5387 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
5388
5389 return ComputeNumSignBits(InVec, DemandedSrcElts, Depth + 1);
5390 }
5392 // Offset the demanded elts by the subvector index.
5393 SDValue Src = Op.getOperand(0);
5394
5395 APInt DemandedSrcElts;
5396 if (Src.getValueType().isScalableVector())
5397 DemandedSrcElts = APInt(1, 1);
5398 else {
5399 uint64_t Idx = Op.getConstantOperandVal(1);
5400 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
5401 DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
5402 }
5403 return ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
5404 }
5405 case ISD::CONCAT_VECTORS: {
5406 if (VT.isScalableVector())
5407 break;
5408 // Determine the minimum number of sign bits across all demanded
5409 // elts of the input vectors. Early out if the result is already 1.
5410 Tmp = std::numeric_limits<unsigned>::max();
5411 EVT SubVectorVT = Op.getOperand(0).getValueType();
5412 unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
5413 unsigned NumSubVectors = Op.getNumOperands();
5414 for (unsigned i = 0; (i < NumSubVectors) && (Tmp > 1); ++i) {
5415 APInt DemandedSub =
5416 DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts);
5417 if (!DemandedSub)
5418 continue;
5419 Tmp2 = ComputeNumSignBits(Op.getOperand(i), DemandedSub, Depth + 1);
5420 Tmp = std::min(Tmp, Tmp2);
5421 }
5422 assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
5423 return Tmp;
5424 }
5425 case ISD::INSERT_SUBVECTOR: {
5426 if (VT.isScalableVector())
5427 break;
5428 // Demand any elements from the subvector and the remainder from the src its
5429 // inserted into.
5430 SDValue Src = Op.getOperand(0);
5431 SDValue Sub = Op.getOperand(1);
5432 uint64_t Idx = Op.getConstantOperandVal(2);
5433 unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
5434 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
5435 APInt DemandedSrcElts = DemandedElts;
5436 DemandedSrcElts.clearBits(Idx, Idx + NumSubElts);
5437
5438 Tmp = std::numeric_limits<unsigned>::max();
5439 if (!!DemandedSubElts) {
5440 Tmp = ComputeNumSignBits(Sub, DemandedSubElts, Depth + 1);
5441 if (Tmp == 1)
5442 return 1; // early-out
5443 }
5444 if (!!DemandedSrcElts) {
5445 Tmp2 = ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
5446 Tmp = std::min(Tmp, Tmp2);
5447 }
5448 assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
5449 return Tmp;
5450 }
5451 case ISD::LOAD: {
5452 // If we are looking at the loaded value of the SDNode.
5453 if (Op.getResNo() != 0)
5454 break;
5455
5457 if (const MDNode *Ranges = LD->getRanges()) {
5458 if (DemandedElts != 1)
5459 break;
5460
5462 if (VTBits > CR.getBitWidth()) {
5463 switch (LD->getExtensionType()) {
5464 case ISD::SEXTLOAD:
5465 CR = CR.signExtend(VTBits);
5466 break;
5467 case ISD::ZEXTLOAD:
5468 CR = CR.zeroExtend(VTBits);
5469 break;
5470 default:
5471 break;
5472 }
5473 }
5474
5475 if (VTBits != CR.getBitWidth())
5476 break;
5477 return std::min(CR.getSignedMin().getNumSignBits(),
5479 }
5480
5481 unsigned ExtType = LD->getExtensionType();
5482 switch (ExtType) {
5483 default:
5484 break;
5485 case ISD::SEXTLOAD: // e.g. i16->i32 = '17' bits known.
5486 Tmp = LD->getMemoryVT().getScalarSizeInBits();
5487 return VTBits - Tmp + 1;
5488 case ISD::ZEXTLOAD: // e.g. i16->i32 = '16' bits known.
5489 Tmp = LD->getMemoryVT().getScalarSizeInBits();
5490 return VTBits - Tmp;
5491 case ISD::NON_EXTLOAD:
5492 if (const Constant *Cst = TLI->getTargetConstantFromLoad(LD)) {
5493 // We only need to handle vectors - computeKnownBits should handle
5494 // scalar cases.
5495 Type *CstTy = Cst->getType();
5496 if (CstTy->isVectorTy() && !VT.isScalableVector() &&
5497 (NumElts * VTBits) == CstTy->getPrimitiveSizeInBits() &&
5498 VTBits == CstTy->getScalarSizeInBits()) {
5499 Tmp = VTBits;
5500 for (unsigned i = 0; i != NumElts; ++i) {
5501 if (!DemandedElts[i])
5502 continue;
5503 if (Constant *Elt = Cst->getAggregateElement(i)) {
5504 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
5505 const APInt &Value = CInt->getValue();
5506 Tmp = std::min(Tmp, Value.getNumSignBits());
5507 continue;
5508 }
5509 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
5510 APInt Value = CFP->getValueAPF().bitcastToAPInt();
5511 Tmp = std::min(Tmp, Value.getNumSignBits());
5512 continue;
5513 }
5514 }
5515 // Unknown type. Conservatively assume no bits match sign bit.
5516 return 1;
5517 }
5518 return Tmp;
5519 }
5520 }
5521 break;
5522 }
5523
5524 break;
5525 }
5528 case ISD::ATOMIC_SWAP:
5540 case ISD::ATOMIC_LOAD: {
5541 auto *AT = cast<AtomicSDNode>(Op);
5542 // If we are looking at the loaded value.
5543 if (Op.getResNo() == 0) {
5544 Tmp = AT->getMemoryVT().getScalarSizeInBits();
5545 if (Tmp == VTBits)
5546 return 1; // early-out
5547
5548 // For atomic_load, prefer to use the extension type.
5549 if (Op->getOpcode() == ISD::ATOMIC_LOAD) {
5550 switch (AT->getExtensionType()) {
5551 default:
5552 break;
5553 case ISD::SEXTLOAD:
5554 return VTBits - Tmp + 1;
5555 case ISD::ZEXTLOAD:
5556 return VTBits - Tmp;
5557 }
5558 }
5559
5560 if (TLI->getExtendForAtomicOps() == ISD::SIGN_EXTEND)
5561 return VTBits - Tmp + 1;
5562 if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND)
5563 return VTBits - Tmp;
5564 }
5565 break;
5566 }
5567 }
5568
5569 // Allow the target to implement this method for its nodes.
5570 if (Opcode >= ISD::BUILTIN_OP_END ||
5571 Opcode == ISD::INTRINSIC_WO_CHAIN ||
5572 Opcode == ISD::INTRINSIC_W_CHAIN ||
5573 Opcode == ISD::INTRINSIC_VOID) {
5574 // TODO: This can probably be removed once target code is audited. This
5575 // is here purely to reduce patch size and review complexity.
5576 if (!VT.isScalableVector()) {
5577 unsigned NumBits =
5578 TLI->ComputeNumSignBitsForTargetNode(Op, DemandedElts, *this, Depth);
5579 if (NumBits > 1)
5580 FirstAnswer = std::max(FirstAnswer, NumBits);
5581 }
5582 }
5583
5584 // Finally, if we can prove that the top bits of the result are 0's or 1's,
5585 // use this information.
5586 KnownBits Known = computeKnownBits(Op, DemandedElts, Depth);
5587 return std::max(FirstAnswer, Known.countMinSignBits());
5588}
5589
5591 unsigned Depth) const {
5592 unsigned SignBits = ComputeNumSignBits(Op, Depth);
5593 return Op.getScalarValueSizeInBits() - SignBits + 1;
5594}
5595
5597 const APInt &DemandedElts,
5598 unsigned Depth) const {
5599 unsigned SignBits = ComputeNumSignBits(Op, DemandedElts, Depth);
5600 return Op.getScalarValueSizeInBits() - SignBits + 1;
5601}
5602
5604 UndefPoisonKind Kind,
5605 unsigned Depth) const {
5606 // Early out for FREEZE.
5607 if (Op.getOpcode() == ISD::FREEZE)
5608 return true;
5609
5610 APInt DemandedElts = getDemandAllEltsMask(Op);
5611 return isGuaranteedNotToBeUndefOrPoison(Op, DemandedElts, Kind, Depth);
5612}
5613
5615 const APInt &DemandedElts,
5616 UndefPoisonKind Kind,
5617 unsigned Depth) const {
5618 unsigned Opcode = Op.getOpcode();
5619
5620 // Early out for FREEZE.
5621 if (Opcode == ISD::FREEZE)
5622 return true;
5623
5624 if (Depth >= MaxRecursionDepth)
5625 return false; // Limit search depth.
5626
5627 if (isIntOrFPConstant(Op))
5628 return true;
5629
5630 switch (Opcode) {
5631 case ISD::CONDCODE:
5632 case ISD::VALUETYPE:
5633 case ISD::FrameIndex:
5635 case ISD::CopyFromReg:
5636 return true;
5637
5638 case ISD::POISON:
5639 return !includesPoison(Kind);
5640
5641 case ISD::UNDEF:
5642 return !includesUndef(Kind);
5643
5644 case ISD::BITCAST: {
5645 SDValue Src = Op.getOperand(0);
5646 EVT SrcVT = Src.getValueType();
5647 EVT DstVT = Op.getValueType();
5648
5649 if (!SrcVT.isVector() || !DstVT.isVector())
5650 return isGuaranteedNotToBeUndefOrPoison(Src, Kind, Depth + 1);
5651
5652 unsigned SrcEltBits = SrcVT.getScalarSizeInBits();
5653 unsigned DstEltBits = DstVT.getScalarSizeInBits();
5654 ElementCount NumSrcElts = SrcVT.getVectorElementCount();
5655 [[maybe_unused]] ElementCount NumDstElts = DstVT.getVectorElementCount();
5656
5657 if (SrcEltBits == DstEltBits)
5658 return isGuaranteedNotToBeUndefOrPoison(Src, DemandedElts, Kind,
5659 Depth + 1);
5660
5661 if (SrcEltBits < DstEltBits) {
5662 if (DstEltBits % SrcEltBits != 0)
5663 return isGuaranteedNotToBeUndefOrPoison(Src, Kind, Depth + 1);
5664
5665 assert(NumSrcElts == NumDstElts * (DstEltBits / SrcEltBits) &&
5666 "Unexpected vector bitcast");
5667 APInt DemandedSrcElts =
5668 APIntOps::ScaleBitMask(DemandedElts, NumSrcElts.getKnownMinValue());
5669 return isGuaranteedNotToBeUndefOrPoison(Src, DemandedSrcElts, Kind,
5670 Depth + 1);
5671 }
5672
5673 if (SrcEltBits % DstEltBits != 0)
5674 return isGuaranteedNotToBeUndefOrPoison(Src, Kind, Depth + 1);
5675
5676 assert(NumDstElts == NumSrcElts * (SrcEltBits / DstEltBits) &&
5677 "Unexpected vector bitcast");
5678 APInt DemandedSrcElts =
5679 APIntOps::ScaleBitMask(DemandedElts, NumSrcElts.getKnownMinValue());
5680 return isGuaranteedNotToBeUndefOrPoison(Src, DemandedSrcElts, Kind,
5681 Depth + 1);
5682 }
5683
5684 case ISD::BUILD_VECTOR:
5685 // NOTE: BUILD_VECTOR has implicit truncation of wider scalar elements -
5686 // this shouldn't affect the result.
5687 for (unsigned i = 0, e = Op.getNumOperands(); i < e; ++i) {
5688 if (!DemandedElts[i])
5689 continue;
5690 if (!isGuaranteedNotToBeUndefOrPoison(Op.getOperand(i), Kind, Depth + 1))
5691 return false;
5692 }
5693 return true;
5694
5695 case ISD::CONCAT_VECTORS: {
5696 EVT VT = Op.getValueType();
5697 if (!VT.isFixedLengthVector())
5698 break;
5699
5700 EVT SubVT = Op.getOperand(0).getValueType();
5701 unsigned NumSubElts = SubVT.getVectorNumElements();
5702 for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) {
5703 APInt DemandedSubElts =
5704 DemandedElts.extractBits(NumSubElts, I * NumSubElts);
5705 if (!!DemandedSubElts &&
5706 !isGuaranteedNotToBeUndefOrPoison(Op.getOperand(I), DemandedSubElts,
5707 Kind, Depth + 1))
5708 return false;
5709 }
5710 return true;
5711 }
5712
5714 SDValue Src = Op.getOperand(0);
5715 if (Src.getValueType().isScalableVector())
5716 break;
5717 uint64_t Idx = Op.getConstantOperandVal(1);
5718 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
5719 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
5720 return isGuaranteedNotToBeUndefOrPoison(Src, DemandedSrcElts, Kind,
5721 Depth + 1);
5722 }
5723
5724 case ISD::INSERT_SUBVECTOR: {
5725 if (Op.getValueType().isScalableVector())
5726 break;
5727 SDValue Src = Op.getOperand(0);
5728 SDValue Sub = Op.getOperand(1);
5729 uint64_t Idx = Op.getConstantOperandVal(2);
5730 unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
5731 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
5732 APInt DemandedSrcElts = DemandedElts;
5733 DemandedSrcElts.clearBits(Idx, Idx + NumSubElts);
5734
5735 if (!!DemandedSubElts && !isGuaranteedNotToBeUndefOrPoison(
5736 Sub, DemandedSubElts, Kind, Depth + 1))
5737 return false;
5738 if (!!DemandedSrcElts && !isGuaranteedNotToBeUndefOrPoison(
5739 Src, DemandedSrcElts, Kind, Depth + 1))
5740 return false;
5741 return true;
5742 }
5743
5745 SDValue Src = Op.getOperand(0);
5746 auto *IndexC = dyn_cast<ConstantSDNode>(Op.getOperand(1));
5747 EVT SrcVT = Src.getValueType();
5748 if (SrcVT.isFixedLengthVector() && IndexC &&
5749 IndexC->getAPIntValue().ult(SrcVT.getVectorNumElements())) {
5750 APInt DemandedSrcElts = APInt::getOneBitSet(SrcVT.getVectorNumElements(),
5751 IndexC->getZExtValue());
5752 return isGuaranteedNotToBeUndefOrPoison(Src, DemandedSrcElts, Kind,
5753 Depth + 1);
5754 }
5755 break;
5756 }
5757
5759 SDValue InVec = Op.getOperand(0);
5760 SDValue InVal = Op.getOperand(1);
5761 SDValue EltNo = Op.getOperand(2);
5762 EVT VT = InVec.getValueType();
5763 auto *IndexC = dyn_cast<ConstantSDNode>(EltNo);
5764 if (IndexC && VT.isFixedLengthVector() &&
5765 IndexC->getAPIntValue().ult(VT.getVectorNumElements())) {
5766 if (DemandedElts[IndexC->getZExtValue()] &&
5767 !isGuaranteedNotToBeUndefOrPoison(InVal, Kind, Depth + 1))
5768 return false;
5769 APInt InVecDemandedElts = DemandedElts;
5770 InVecDemandedElts.clearBit(IndexC->getZExtValue());
5771 if (!!InVecDemandedElts &&
5773 peekThroughInsertVectorElt(InVec, InVecDemandedElts),
5774 InVecDemandedElts, Kind, Depth + 1))
5775 return false;
5776 return true;
5777 }
5778 break;
5779 }
5780
5782 // Check upper (known undef) elements.
5783 if (DemandedElts.ugt(1) && includesUndef(Kind))
5784 return false;
5785 // Check element zero.
5786 if (DemandedElts[0] &&
5787 !isGuaranteedNotToBeUndefOrPoison(Op.getOperand(0), Kind, Depth + 1))
5788 return false;
5789 return true;
5790
5791 case ISD::SPLAT_VECTOR:
5792 return isGuaranteedNotToBeUndefOrPoison(Op.getOperand(0), Kind, Depth + 1);
5793
5794 case ISD::SELECT: {
5795 return !canCreateUndefOrPoison(Op, DemandedElts, Kind,
5796 /*ConsiderFlags*/ true, Depth) &&
5797 isGuaranteedNotToBeUndefOrPoison(Op.getOperand(0), Kind,
5798 Depth + 1) &&
5799 isGuaranteedNotToBeUndefOrPoison(Op.getOperand(1), DemandedElts,
5800 Kind, Depth + 1) &&
5801 isGuaranteedNotToBeUndefOrPoison(Op.getOperand(2), DemandedElts,
5802 Kind, Depth + 1);
5803 }
5804
5805 case ISD::VECTOR_SHUFFLE: {
5806 APInt DemandedLHS, DemandedRHS;
5807 auto *SVN = cast<ShuffleVectorSDNode>(Op);
5808 if (!getShuffleDemandedElts(DemandedElts.getBitWidth(), SVN->getMask(),
5809 DemandedElts, DemandedLHS, DemandedRHS,
5810 /*AllowUndefElts=*/false))
5811 return false;
5812 if (!DemandedLHS.isZero() &&
5813 !isGuaranteedNotToBeUndefOrPoison(Op.getOperand(0), DemandedLHS, Kind,
5814 Depth + 1))
5815 return false;
5816 if (!DemandedRHS.isZero() &&
5817 !isGuaranteedNotToBeUndefOrPoison(Op.getOperand(1), DemandedRHS, Kind,
5818 Depth + 1))
5819 return false;
5820 return true;
5821 }
5822
5823 case ISD::SHL:
5824 case ISD::SRL:
5825 case ISD::SRA:
5826 // Shift amount operand is checked by canCreateUndefOrPoison. So it is
5827 // enough to check operand 0 if Op can't create undef/poison.
5828 return !canCreateUndefOrPoison(Op, DemandedElts, Kind,
5829 /*ConsiderFlags*/ true, Depth) &&
5830 isGuaranteedNotToBeUndefOrPoison(Op.getOperand(0), DemandedElts,
5831 Kind, Depth + 1);
5832
5833 case ISD::BSWAP:
5834 case ISD::CTPOP:
5835 case ISD::BITREVERSE:
5836 case ISD::AND:
5837 case ISD::OR:
5838 case ISD::XOR:
5839 case ISD::ADD:
5840 case ISD::SUB:
5841 case ISD::MUL:
5842 case ISD::SADDSAT:
5843 case ISD::UADDSAT:
5844 case ISD::SSUBSAT:
5845 case ISD::USUBSAT:
5846 case ISD::SSHLSAT:
5847 case ISD::USHLSAT:
5848 case ISD::SMIN:
5849 case ISD::SMAX:
5850 case ISD::UMIN:
5851 case ISD::UMAX:
5852 case ISD::ZERO_EXTEND:
5853 case ISD::SIGN_EXTEND:
5854 case ISD::ANY_EXTEND:
5855 case ISD::TRUNCATE:
5856 case ISD::VSELECT: {
5857 // If Op can't create undef/poison and none of its operands are undef/poison
5858 // then Op is never undef/poison. A difference from the more common check
5859 // below, outside the switch, is that we handle elementwise operations for
5860 // which the DemandedElts mask is valid for all operands here.
5861 return !canCreateUndefOrPoison(Op, DemandedElts, Kind,
5862 /*ConsiderFlags*/ true, Depth) &&
5863 all_of(Op->ops(), [&](SDValue V) {
5864 return isGuaranteedNotToBeUndefOrPoison(V, DemandedElts, Kind,
5865 Depth + 1);
5866 });
5867 }
5868
5869 // TODO: Search for noundef attributes from library functions.
5870
5871 // TODO: Pointers dereferenced by ISD::LOAD/STORE ops are noundef.
5872
5873 default:
5874 // Allow the target to implement this method for its nodes.
5875 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
5876 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID)
5877 return TLI->isGuaranteedNotToBeUndefOrPoisonForTargetNode(
5878 Op, DemandedElts, *this, Kind, Depth);
5879 break;
5880 }
5881
5882 // If Op can't create undef/poison and none of its operands are undef/poison
5883 // then Op is never undef/poison.
5884 // NOTE: TargetNodes can handle this in themselves in
5885 // isGuaranteedNotToBeUndefOrPoisonForTargetNode or let
5886 // TargetLowering::isGuaranteedNotToBeUndefOrPoisonForTargetNode handle it.
5887 return !canCreateUndefOrPoison(Op, Kind, /*ConsiderFlags*/ true, Depth) &&
5888 all_of(Op->ops(), [&](SDValue V) {
5889 return isGuaranteedNotToBeUndefOrPoison(V, Kind, Depth + 1);
5890 });
5891}
5892
5894 bool ConsiderFlags,
5895 unsigned Depth) const {
5896 APInt DemandedElts = getDemandAllEltsMask(Op);
5897 return canCreateUndefOrPoison(Op, DemandedElts, Kind, ConsiderFlags, Depth);
5898}
5899
5901 UndefPoisonKind Kind,
5902 bool ConsiderFlags,
5903 unsigned Depth) const {
5904 if (ConsiderFlags && includesPoison(Kind) && Op->hasPoisonGeneratingFlags())
5905 return true;
5906
5907 unsigned Opcode = Op.getOpcode();
5908 switch (Opcode) {
5909 case ISD::AssertSext:
5910 case ISD::AssertZext:
5911 case ISD::AssertAlign:
5913 // Assertion nodes can create poison if the assertion fails.
5914 return includesPoison(Kind);
5915
5916 case ISD::FREEZE:
5920 case ISD::SADDSAT:
5921 case ISD::UADDSAT:
5922 case ISD::SSUBSAT:
5923 case ISD::USUBSAT:
5924 case ISD::MULHU:
5925 case ISD::MULHS:
5926 case ISD::AVGFLOORS:
5927 case ISD::AVGFLOORU:
5928 case ISD::AVGCEILS:
5929 case ISD::AVGCEILU:
5930 case ISD::ABDU:
5931 case ISD::ABDS:
5932 case ISD::SMIN:
5933 case ISD::SMAX:
5934 case ISD::SCMP:
5935 case ISD::UMIN:
5936 case ISD::UMAX:
5937 case ISD::UCMP:
5938 case ISD::AND:
5939 case ISD::XOR:
5940 case ISD::ROTL:
5941 case ISD::ROTR:
5942 case ISD::FSHL:
5943 case ISD::FSHR:
5944 case ISD::BSWAP:
5945 case ISD::CTTZ:
5946 case ISD::CTLZ:
5947 case ISD::CTLS:
5948 case ISD::CTPOP:
5949 case ISD::BITREVERSE:
5950 case ISD::PARITY:
5951 case ISD::SIGN_EXTEND:
5952 case ISD::TRUNCATE:
5956 case ISD::BITCAST:
5957 case ISD::BUILD_VECTOR:
5958 case ISD::BUILD_PAIR:
5959 case ISD::SPLAT_VECTOR:
5960 case ISD::FABS:
5961 case ISD::FCEIL:
5962 case ISD::FFLOOR:
5963 case ISD::FTRUNC:
5964 case ISD::FRINT:
5965 case ISD::FNEARBYINT:
5966 case ISD::FROUND:
5967 case ISD::FROUNDEVEN:
5968 return false;
5969
5970 case ISD::ABS:
5971 // ISD::ABS defines abs(INT_MIN) -> INT_MIN and never generates poison.
5972 // Different to Intrinsic::abs.
5973 return false;
5975 // ABS_MIN_POISON may produce poison if the input is INT_MIN.
5976 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1) <= 1;
5977
5978 case ISD::ADDC:
5979 case ISD::SUBC:
5980 case ISD::ADDE:
5981 case ISD::SUBE:
5982 case ISD::SADDO:
5983 case ISD::SSUBO:
5984 case ISD::SMULO:
5985 case ISD::SADDO_CARRY:
5986 case ISD::SSUBO_CARRY:
5987 case ISD::UADDO:
5988 case ISD::USUBO:
5989 case ISD::UMULO:
5990 case ISD::UADDO_CARRY:
5991 case ISD::USUBO_CARRY:
5992 // No poison on result or overflow flags.
5993 return false;
5994
5995 case ISD::SELECT_CC:
5996 case ISD::SETCC: {
5997 // Integer setcc cannot create undef or poison.
5998 if (Op.getOperand(0).getValueType().isInteger())
5999 return false;
6000
6001 // FP compares are more complicated. They can create poison for nan/infinity
6002 // based on options and flags. The options and flags also cause special
6003 // nonan condition codes to be used. Those condition codes may be preserved
6004 // even if the nonan flag is dropped somewhere.
6005 unsigned CCOp = Opcode == ISD::SETCC ? 2 : 4;
6006 ISD::CondCode CCCode = cast<CondCodeSDNode>(Op.getOperand(CCOp))->get();
6007 return (unsigned)CCCode & 0x10U;
6008 }
6009
6010 case ISD::OR:
6011 case ISD::ZERO_EXTEND:
6012 case ISD::SELECT:
6013 case ISD::VSELECT:
6014 case ISD::ADD:
6015 case ISD::SUB:
6016 case ISD::MUL:
6017 case ISD::FNEG:
6018 case ISD::FADD:
6019 case ISD::FSUB:
6020 case ISD::FMUL:
6021 case ISD::FDIV:
6022 case ISD::FREM:
6023 case ISD::FCOPYSIGN:
6024 case ISD::FMA:
6025 case ISD::FMAD:
6026 case ISD::FMULADD:
6027 case ISD::FP_EXTEND:
6028 case ISD::FMINNUM:
6029 case ISD::FMAXNUM:
6030 case ISD::FMINNUM_IEEE:
6031 case ISD::FMAXNUM_IEEE:
6032 case ISD::FMINIMUM:
6033 case ISD::FMAXIMUM:
6034 case ISD::FMINIMUMNUM:
6035 case ISD::FMAXIMUMNUM:
6041 // No poison except from flags (which is handled above)
6042 return false;
6043
6044 case ISD::SHL:
6045 case ISD::SRL:
6046 case ISD::SRA:
6047 // If the max shift amount isn't in range, then the shift can
6048 // create poison.
6049 return includesPoison(Kind) &&
6050 !getValidMaximumShiftAmount(Op, DemandedElts, Depth + 1);
6051
6054 // If the amount is zero then the result will be poison.
6055 // TODO: Add isKnownNeverZero DemandedElts handling.
6056 return includesPoison(Kind) &&
6057 !isKnownNeverZero(Op.getOperand(0), Depth + 1);
6058
6060 // Check if we demand any upper (undef) elements.
6061 return includesUndef(Kind) && DemandedElts.ugt(1);
6062
6065 // Ensure that the element index is in bounds.
6066 if (includesPoison(Kind)) {
6067 EVT VecVT = Op.getOperand(0).getValueType();
6068 SDValue Idx = Op.getOperand(Opcode == ISD::INSERT_VECTOR_ELT ? 2 : 1);
6069 KnownBits KnownIdx = computeKnownBits(Idx, Depth + 1);
6070 return KnownIdx.getMaxValue().uge(VecVT.getVectorMinNumElements());
6071 }
6072 return false;
6073 }
6074
6075 case ISD::VECTOR_SHUFFLE: {
6076 // Check for any demanded shuffle element that is undef.
6077 auto *SVN = cast<ShuffleVectorSDNode>(Op);
6078 for (auto [Idx, Elt] : enumerate(SVN->getMask()))
6079 if (Elt < 0 && DemandedElts[Idx])
6080 return true;
6081 return false;
6082 }
6083
6085 return false;
6086
6087 default:
6088 // Allow the target to implement this method for its nodes.
6089 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
6090 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID)
6091 return TLI->canCreateUndefOrPoisonForTargetNode(
6092 Op, DemandedElts, *this, Kind, ConsiderFlags, Depth);
6093 break;
6094 }
6095
6096 // Be conservative and return true.
6097 return true;
6098}
6099
6100bool SelectionDAG::isADDLike(SDValue Op, bool NoWrap) const {
6101 unsigned Opcode = Op.getOpcode();
6102 if (Opcode == ISD::OR)
6103 return Op->getFlags().hasDisjoint() ||
6104 haveNoCommonBitsSet(Op.getOperand(0), Op.getOperand(1));
6105 if (Opcode == ISD::XOR)
6106 return !NoWrap && isMinSignedConstant(Op.getOperand(1));
6107 return false;
6108}
6109
6111 return Op.getNumOperands() == 2 && isa<ConstantSDNode>(Op.getOperand(1)) &&
6112 (Op.isAnyAdd() || isADDLike(Op));
6113}
6114
6116 FPClassTest InterestedClasses,
6117 unsigned Depth) const {
6118 APInt DemandedElts = getDemandAllEltsMask(Op);
6119 return computeKnownFPClass(Op, DemandedElts, InterestedClasses, Depth);
6120}
6121
6123 const APInt &DemandedElts,
6124 FPClassTest InterestedClasses,
6125 unsigned Depth) const {
6127
6128 if (const auto *CFP = dyn_cast<ConstantFPSDNode>(Op))
6129 return KnownFPClass(CFP->getValueAPF());
6130
6131 if (Depth >= MaxRecursionDepth)
6132 return Known;
6133
6134 if (Op.getOpcode() == ISD::UNDEF)
6135 return Known;
6136
6137 EVT VT = Op.getValueType();
6138 assert(VT.isFloatingPoint() && "Computing KnownFPClass on non-FP op!");
6139 assert((!VT.isFixedLengthVector() ||
6140 DemandedElts.getBitWidth() == VT.getVectorNumElements()) &&
6141 "Unexpected vector size");
6142
6143 if (!DemandedElts)
6144 return Known;
6145
6146 unsigned Opcode = Op.getOpcode();
6147 switch (Opcode) {
6148 case ISD::POISON: {
6149 Known.KnownFPClasses = fcNone;
6150 Known.setSignBit(false);
6151 break;
6152 }
6153 case ISD::FNEG: {
6154 Known = computeKnownFPClass(Op.getOperand(0), DemandedElts,
6155 InterestedClasses, Depth + 1);
6156 Known.fneg();
6157 break;
6158 }
6159 case ISD::BUILD_VECTOR: {
6160 assert(!VT.isScalableVector());
6161 bool First = true;
6162 for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) {
6163 if (!DemandedElts[I])
6164 continue;
6165
6166 if (First) {
6167 Known =
6168 computeKnownFPClass(Op.getOperand(I), InterestedClasses, Depth + 1);
6169 First = false;
6170 } else {
6171 Known |=
6172 computeKnownFPClass(Op.getOperand(I), InterestedClasses, Depth + 1);
6173 }
6174
6175 if (Known.isUnknown())
6176 break;
6177 }
6178 break;
6179 }
6181 SDValue Src = Op.getOperand(0);
6182 auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6183 EVT SrcVT = Src.getValueType();
6184 if (SrcVT.isFixedLengthVector() && CIdx) {
6185 if (CIdx->getAPIntValue().ult(SrcVT.getVectorNumElements())) {
6186 APInt DemandedSrcElts = APInt::getOneBitSet(
6187 SrcVT.getVectorNumElements(), CIdx->getZExtValue());
6188 Known = computeKnownFPClass(Src, DemandedSrcElts, InterestedClasses,
6189 Depth + 1);
6190 } else {
6191 // Out of bounds index is poison.
6192 Known.KnownFPClasses = fcNone;
6193 }
6194 } else {
6195 Known = computeKnownFPClass(Src, InterestedClasses, Depth + 1);
6196 }
6197 break;
6198 }
6199 case ISD::SPLAT_VECTOR: {
6200 Known = computeKnownFPClass(Op.getOperand(0), InterestedClasses, Depth + 1);
6201 break;
6202 }
6203 case ISD::BITCAST: {
6204 // FIXME: It should not be necessary to check for an elementwise bitcast.
6205 // If a bitcast is not elementwise between vector / scalar types,
6206 // computeKnownBits already splices the known bits of the source elements
6207 // appropriately so as to line up with the bits of the result's demanded
6208 // elements.
6209 EVT SrcVT = Op.getOperand(0).getValueType();
6210 if (VT.isScalableVector() || SrcVT.isScalableVector())
6211 break;
6212 unsigned VTNumElts = VT.isVector() ? VT.getVectorNumElements() : 1;
6213 unsigned SrcVTNumElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1;
6214 if (VTNumElts != SrcVTNumElts)
6215 break;
6216
6217 KnownBits Bits = computeKnownBits(Op, DemandedElts, Depth + 1);
6219 break;
6220 }
6221 case ISD::FABS: {
6222 Known = computeKnownFPClass(Op.getOperand(0), DemandedElts,
6223 InterestedClasses, Depth + 1);
6224 Known.fabs();
6225 break;
6226 }
6227 case ISD::FCOPYSIGN: {
6228 Known = computeKnownFPClass(Op.getOperand(0), DemandedElts,
6229 InterestedClasses, Depth + 1);
6230 KnownFPClass KnownSign = computeKnownFPClass(Op.getOperand(1), DemandedElts,
6231 InterestedClasses, Depth + 1);
6232 Known.copysign(KnownSign);
6233 break;
6234 }
6235 case ISD::AssertNoFPClass: {
6236 Known = computeKnownFPClass(Op.getOperand(0), DemandedElts,
6237 InterestedClasses, Depth + 1);
6238 FPClassTest AssertedClasses =
6239 static_cast<FPClassTest>(Op->getConstantOperandVal(1));
6240 Known.KnownFPClasses &= ~AssertedClasses;
6241 break;
6242 }
6244 SDValue Src = Op.getOperand(0);
6245 EVT SrcVT = Src.getValueType();
6246 if (SrcVT.isFixedLengthVector()) {
6247 unsigned Idx = Op.getConstantOperandVal(1);
6248 unsigned NumSrcElts = SrcVT.getVectorNumElements();
6249
6250 APInt DemandedSrcElts = DemandedElts.zextOrTrunc(NumSrcElts).shl(Idx);
6251 Known = computeKnownFPClass(Src, DemandedSrcElts, InterestedClasses,
6252 Depth + 1);
6253 } else {
6254 Known = computeKnownFPClass(Src, InterestedClasses, Depth + 1);
6255 }
6256 break;
6257 }
6258 case ISD::INSERT_SUBVECTOR: {
6259 SDValue BaseVector = Op.getOperand(0);
6260 SDValue SubVector = Op.getOperand(1);
6261 EVT BaseVT = BaseVector.getValueType();
6262 if (BaseVT.isFixedLengthVector()) {
6263 unsigned Idx = Op.getConstantOperandVal(2);
6264 unsigned NumBaseElts = BaseVT.getVectorNumElements();
6265 unsigned NumSubElts = SubVector.getValueType().getVectorNumElements();
6266
6267 APInt DemandedMask =
6268 APInt::getBitsSet(NumBaseElts, Idx, Idx + NumSubElts);
6269 APInt DemandedSrcElts = DemandedElts & ~DemandedMask;
6270 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
6271
6272 if (!DemandedSrcElts.isZero())
6273 Known = computeKnownFPClass(BaseVector, DemandedSrcElts,
6274 InterestedClasses, Depth + 1);
6275 if (!DemandedSubElts.isZero()) {
6277 SubVector, DemandedSubElts, InterestedClasses, Depth + 1);
6278 Known = DemandedSrcElts.isZero() ? SubKnown : (Known | SubKnown);
6279 }
6280 } else {
6281 Known = computeKnownFPClass(SubVector, InterestedClasses, Depth + 1);
6282 if (!Known.isUnknown())
6283 Known |= computeKnownFPClass(BaseVector, InterestedClasses, Depth + 1);
6284 }
6285 break;
6286 }
6287 case ISD::SELECT:
6288 case ISD::VSELECT: {
6289 // TODO: Add adjustKnownFPClassForSelectArm clamp recognition as in
6290 // IR-level ValueTracking.
6291 KnownFPClass KnownFalseClass = computeKnownFPClass(
6292 Op.getOperand(2), DemandedElts, InterestedClasses, Depth + 1);
6293 if (KnownFalseClass.isUnknown())
6294 break;
6295 KnownFPClass KnownTrueClass = computeKnownFPClass(
6296 Op.getOperand(1), DemandedElts, InterestedClasses, Depth + 1);
6297 Known = KnownTrueClass.intersectWith(KnownFalseClass);
6298 break;
6299 }
6300 default:
6301 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
6302 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID) {
6303 TLI->computeKnownFPClassForTargetNode(Op, Known, DemandedElts, *this,
6304 Depth);
6305 }
6306 break;
6307 }
6308
6309 return Known;
6310}
6311
6313 unsigned Depth) const {
6314 APInt DemandedElts = getDemandAllEltsMask(Op);
6315 return isKnownNeverNaN(Op, DemandedElts, SNaN, Depth);
6316}
6317
6319 bool SNaN, unsigned Depth) const {
6320 assert(!DemandedElts.isZero() && "No demanded elements");
6321
6322 // If we're told that NaNs won't happen, assume they won't.
6323 if (Op->getFlags().hasNoNaNs())
6324 return true;
6325
6326 if (Depth >= MaxRecursionDepth)
6327 return false; // Limit search depth.
6328
6329 unsigned Opcode = Op.getOpcode();
6330 switch (Opcode) {
6331 case ISD::FADD:
6332 case ISD::FSUB:
6333 case ISD::FMUL:
6334 case ISD::FDIV:
6335 case ISD::FREM:
6336 case ISD::FSIN:
6337 case ISD::FCOS:
6338 case ISD::FTAN:
6339 case ISD::FASIN:
6340 case ISD::FACOS:
6341 case ISD::FATAN:
6342 case ISD::FATAN2:
6343 case ISD::FSINH:
6344 case ISD::FCOSH:
6345 case ISD::FTANH:
6346 case ISD::FMA:
6347 case ISD::FMULADD:
6348 case ISD::FMAD: {
6349 if (SNaN)
6350 return true;
6351 // TODO: Need isKnownNeverInfinity
6352 return false;
6353 }
6354 case ISD::FCANONICALIZE:
6355 case ISD::FEXP:
6356 case ISD::FEXP2:
6357 case ISD::FEXP10:
6358 case ISD::FTRUNC:
6359 case ISD::FFLOOR:
6360 case ISD::FCEIL:
6361 case ISD::FROUND:
6362 case ISD::FROUNDEVEN:
6363 case ISD::LROUND:
6364 case ISD::LLROUND:
6365 case ISD::FRINT:
6366 case ISD::LRINT:
6367 case ISD::LLRINT:
6368 case ISD::FNEARBYINT:
6369 case ISD::FLDEXP: {
6370 if (SNaN)
6371 return true;
6372 return isKnownNeverNaN(Op.getOperand(0), DemandedElts, SNaN, Depth + 1);
6373 }
6374 case ISD::FABS:
6375 case ISD::FNEG:
6376 case ISD::FCOPYSIGN: {
6377 return isKnownNeverNaN(Op.getOperand(0), DemandedElts, SNaN, Depth + 1);
6378 }
6379 case ISD::SELECT:
6380 return isKnownNeverNaN(Op.getOperand(1), DemandedElts, SNaN, Depth + 1) &&
6381 isKnownNeverNaN(Op.getOperand(2), DemandedElts, SNaN, Depth + 1);
6382 case ISD::FP_EXTEND:
6383 case ISD::FP_ROUND: {
6384 if (SNaN)
6385 return true;
6386 return isKnownNeverNaN(Op.getOperand(0), DemandedElts, SNaN, Depth + 1);
6387 }
6388 case ISD::SINT_TO_FP:
6389 case ISD::UINT_TO_FP:
6390 return true;
6391 case ISD::FSQRT: // Need is known positive
6392 case ISD::FLOG:
6393 case ISD::FLOG2:
6394 case ISD::FLOG10:
6395 case ISD::FPOWI:
6396 case ISD::FPOW: {
6397 if (SNaN)
6398 return true;
6399 // TODO: Refine on operand
6400 return false;
6401 }
6402 case ISD::FMINNUM:
6403 case ISD::FMAXNUM:
6404 case ISD::FMINIMUMNUM:
6405 case ISD::FMAXIMUMNUM: {
6406 // Only one needs to be known not-nan, since it will be returned if the
6407 // other ends up being one.
6408 return isKnownNeverNaN(Op.getOperand(0), DemandedElts, SNaN, Depth + 1) ||
6409 isKnownNeverNaN(Op.getOperand(1), DemandedElts, SNaN, Depth + 1);
6410 }
6411 case ISD::FMINNUM_IEEE:
6412 case ISD::FMAXNUM_IEEE: {
6413 if (SNaN)
6414 return true;
6415 // This can return a NaN if either operand is an sNaN, or if both operands
6416 // are NaN.
6417 return (isKnownNeverNaN(Op.getOperand(0), DemandedElts, false, Depth + 1) &&
6418 isKnownNeverSNaN(Op.getOperand(1), DemandedElts, Depth + 1)) ||
6419 (isKnownNeverNaN(Op.getOperand(1), DemandedElts, false, Depth + 1) &&
6420 isKnownNeverSNaN(Op.getOperand(0), DemandedElts, Depth + 1));
6421 }
6422 case ISD::FMINIMUM:
6423 case ISD::FMAXIMUM: {
6424 // TODO: Does this quiet or return the origina NaN as-is?
6425 return isKnownNeverNaN(Op.getOperand(0), DemandedElts, SNaN, Depth + 1) &&
6426 isKnownNeverNaN(Op.getOperand(1), DemandedElts, SNaN, Depth + 1);
6427 }
6429 SDValue Src = Op.getOperand(0);
6430 auto *Idx = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6431 EVT SrcVT = Src.getValueType();
6432 if (SrcVT.isFixedLengthVector() && Idx &&
6433 Idx->getAPIntValue().ult(SrcVT.getVectorNumElements())) {
6434 APInt DemandedSrcElts = APInt::getOneBitSet(SrcVT.getVectorNumElements(),
6435 Idx->getZExtValue());
6436 return isKnownNeverNaN(Src, DemandedSrcElts, SNaN, Depth + 1);
6437 }
6438 return isKnownNeverNaN(Src, SNaN, Depth + 1);
6439 }
6441 SDValue Src = Op.getOperand(0);
6442 if (Src.getValueType().isFixedLengthVector()) {
6443 unsigned Idx = Op.getConstantOperandVal(1);
6444 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
6445 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
6446 return isKnownNeverNaN(Src, DemandedSrcElts, SNaN, Depth + 1);
6447 }
6448 return isKnownNeverNaN(Src, SNaN, Depth + 1);
6449 }
6450 case ISD::INSERT_SUBVECTOR: {
6451 SDValue BaseVector = Op.getOperand(0);
6452 SDValue SubVector = Op.getOperand(1);
6453 EVT BaseVectorVT = BaseVector.getValueType();
6454 if (BaseVectorVT.isFixedLengthVector()) {
6455 unsigned Idx = Op.getConstantOperandVal(2);
6456 unsigned NumBaseElts = BaseVectorVT.getVectorNumElements();
6457 unsigned NumSubElts = SubVector.getValueType().getVectorNumElements();
6458
6459 // Clear/Extract the bits at the position where the subvector will be
6460 // inserted.
6461 APInt DemandedMask =
6462 APInt::getBitsSet(NumBaseElts, Idx, Idx + NumSubElts);
6463 APInt DemandedSrcElts = DemandedElts & ~DemandedMask;
6464 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
6465
6466 bool NeverNaN = true;
6467 if (!DemandedSrcElts.isZero())
6468 NeverNaN &=
6469 isKnownNeverNaN(BaseVector, DemandedSrcElts, SNaN, Depth + 1);
6470 if (NeverNaN && !DemandedSubElts.isZero())
6471 NeverNaN &=
6472 isKnownNeverNaN(SubVector, DemandedSubElts, SNaN, Depth + 1);
6473 return NeverNaN;
6474 }
6475 return isKnownNeverNaN(BaseVector, SNaN, Depth + 1) &&
6476 isKnownNeverNaN(SubVector, SNaN, Depth + 1);
6477 }
6478 case ISD::BUILD_VECTOR: {
6479 unsigned NumElts = Op.getNumOperands();
6480 for (unsigned I = 0; I != NumElts; ++I)
6481 if (DemandedElts[I] &&
6482 !isKnownNeverNaN(Op.getOperand(I), SNaN, Depth + 1))
6483 return false;
6484 return true;
6485 }
6486 case ISD::SPLAT_VECTOR:
6487 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
6488 case ISD::AssertNoFPClass: {
6489 FPClassTest NoFPClass =
6490 static_cast<FPClassTest>(Op.getConstantOperandVal(1));
6491 if ((NoFPClass & fcNan) == fcNan)
6492 return true;
6493 if (SNaN && (NoFPClass & fcSNan) == fcSNan)
6494 return true;
6495 return isKnownNeverNaN(Op.getOperand(0), DemandedElts, SNaN, Depth + 1);
6496 }
6497 default:
6498 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
6499 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID) {
6500 return TLI->isKnownNeverNaNForTargetNode(Op, DemandedElts, *this, SNaN,
6501 Depth);
6502 }
6503 break;
6504 }
6505
6506 FPClassTest NanMask = SNaN ? fcSNan : fcNan;
6507 KnownFPClass Known = computeKnownFPClass(Op, DemandedElts, NanMask, Depth);
6508 return Known.isKnownNever(NanMask);
6509}
6510
6512 APInt DemandedElts = getDemandAllEltsMask(Op);
6513 return isKnownNeverLogicalZero(Op, DemandedElts, Depth);
6514}
6515
6517 const APInt &DemandedElts,
6518 unsigned Depth) const {
6519 assert(!DemandedElts.isZero() && "No demanded elements");
6520 EVT VT = Op.getValueType();
6522 computeKnownFPClass(Op, DemandedElts, fcZero | fcSubnormal, Depth);
6523 return Known.isKnownNeverLogicalZero(getDenormalMode(VT));
6524}
6525
6527 APInt DemandedElts = getDemandAllEltsMask(Op);
6528 return isKnownNeverZero(Op, DemandedElts, Depth);
6529}
6530
6532 unsigned Depth) const {
6533 if (Depth >= MaxRecursionDepth)
6534 return false; // Limit search depth.
6535
6536 EVT OpVT = Op.getValueType();
6537 unsigned BitWidth = OpVT.getScalarSizeInBits();
6538
6539 assert(!Op.getValueType().isFloatingPoint() &&
6540 "Floating point types unsupported - use isKnownNeverLogicalZero");
6541
6542 // If the value is a constant, we can obviously see if it is a zero or not.
6543 auto IsNeverZero = [BitWidth](const ConstantSDNode *C) {
6544 APInt V = C->getAPIntValue().zextOrTrunc(BitWidth);
6545 return !V.isZero();
6546 };
6547
6548 if (ISD::matchUnaryPredicate(Op, DemandedElts, IsNeverZero,
6549 /*AllowUndefs=*/false, /*AllowTruncation=*/true))
6550 return true;
6551
6552 // TODO: Recognize more cases here. Most of the cases are also incomplete to
6553 // some degree.
6554 switch (Op.getOpcode()) {
6555 default:
6556 break;
6557
6559 SDValue InVec = Op.getOperand(0);
6560 SDValue EltNo = Op.getOperand(1);
6561 EVT VecVT = InVec.getValueType();
6562
6563 // Skip scalable vectors or implicit extensions.
6564 if (VecVT.isScalableVector() ||
6565 OpVT.getScalarSizeInBits() != VecVT.getScalarSizeInBits())
6566 break;
6567
6568 // If we know the element index, just demand that vector element, else for
6569 // an unknown element index, ignore DemandedElts and demand them all.
6570 const unsigned NumSrcElts = VecVT.getVectorNumElements();
6571 APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
6572 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
6573 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
6574 DemandedSrcElts =
6575 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
6576
6577 return isKnownNeverZero(InVec, DemandedSrcElts, Depth + 1);
6578 }
6579
6580 case ISD::OR:
6581 return isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1) ||
6582 isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6583
6584 case ISD::VSELECT:
6585 case ISD::SELECT:
6586 return isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1) &&
6587 isKnownNeverZero(Op.getOperand(2), DemandedElts, Depth + 1);
6588
6589 case ISD::SHL: {
6590 if (Op->getFlags().hasNoSignedWrap() || Op->getFlags().hasNoUnsignedWrap())
6591 return isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6592 KnownBits ValKnown =
6593 computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
6594 // 1 << X is never zero.
6595 if (ValKnown.One[0])
6596 return true;
6597 // If max shift cnt of known ones is non-zero, result is non-zero.
6598 APInt MaxCnt = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1)
6599 .getMaxValue();
6600 if (MaxCnt.ult(ValKnown.getBitWidth()) &&
6601 !ValKnown.One.shl(MaxCnt).isZero())
6602 return true;
6603 break;
6604 }
6605
6606 case ISD::VECTOR_SHUFFLE: {
6607 if (Op.getValueType().isScalableVector())
6608 return false;
6609
6610 unsigned NumElts = DemandedElts.getBitWidth();
6611
6612 // All demanded elements from LHS and RHS must be known non-zero.
6613 // Demanded elements with undef shuffle mask elements are unknown.
6614
6615 APInt DemandedLHS, DemandedRHS;
6616 auto *SVN = cast<ShuffleVectorSDNode>(Op);
6617 assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
6618 if (!getShuffleDemandedElts(NumElts, SVN->getMask(), DemandedElts,
6619 DemandedLHS, DemandedRHS))
6620 return false;
6621
6622 return (!DemandedLHS ||
6623 isKnownNeverZero(Op.getOperand(0), DemandedLHS, Depth + 1)) &&
6624 (!DemandedRHS ||
6625 isKnownNeverZero(Op.getOperand(1), DemandedRHS, Depth + 1));
6626 }
6627
6628 case ISD::UADDSAT:
6629 case ISD::UMAX:
6630 return isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1) ||
6631 isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6632
6633 case ISD::UMIN:
6634 return isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1) &&
6635 isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6636
6637 // For smin/smax: If either operand is known negative/positive
6638 // respectively we don't need the other to be known at all.
6639 case ISD::SMAX: {
6640 KnownBits Op1 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
6641 if (Op1.isStrictlyPositive())
6642 return true;
6643
6644 KnownBits Op0 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
6645 if (Op0.isStrictlyPositive())
6646 return true;
6647
6648 if (Op1.isNonZero() && Op0.isNonZero())
6649 return true;
6650
6651 return isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1) &&
6652 isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6653 }
6654 case ISD::SMIN: {
6655 KnownBits Op1 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
6656 if (Op1.isNegative())
6657 return true;
6658
6659 KnownBits Op0 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
6660 if (Op0.isNegative())
6661 return true;
6662
6663 if (Op1.isNonZero() && Op0.isNonZero())
6664 return true;
6665
6666 return isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1) &&
6667 isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6668 }
6669
6670 case ISD::ROTL:
6671 case ISD::ROTR:
6672 case ISD::BITREVERSE:
6673 case ISD::BSWAP:
6674 case ISD::CTPOP:
6675 case ISD::ABS:
6677 return isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6678
6679 case ISD::SRA:
6680 case ISD::SRL: {
6681 if (Op->getFlags().hasExact())
6682 return isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6683 KnownBits ValKnown =
6684 computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
6685 if (ValKnown.isNegative())
6686 return true;
6687 // If max shift cnt of known ones is non-zero, result is non-zero.
6688 APInt MaxCnt = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1)
6689 .getMaxValue();
6690 if (MaxCnt.ult(ValKnown.getBitWidth()) &&
6691 !ValKnown.One.lshr(MaxCnt).isZero())
6692 return true;
6693 break;
6694 }
6695 case ISD::UDIV:
6696 case ISD::SDIV:
6697 // div exact can only produce a zero if the dividend is zero.
6698 // TODO: For udiv this is also true if Op1 u<= Op0
6699 if (Op->getFlags().hasExact())
6700 return isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6701 break;
6702
6703 case ISD::ADD:
6704 if (Op->getFlags().hasNoUnsignedWrap())
6705 if (isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1) ||
6706 isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1))
6707 return true;
6708 // TODO: There are a lot more cases we can prove for add.
6709 break;
6710
6711 case ISD::SUB: {
6712 if (isNullConstant(Op.getOperand(0)))
6713 return isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1);
6714
6715 std::optional<bool> ne = KnownBits::ne(
6716 computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1),
6717 computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1));
6718 return ne && *ne;
6719 }
6720
6721 case ISD::MUL:
6722 if (Op->getFlags().hasNoSignedWrap() || Op->getFlags().hasNoUnsignedWrap())
6723 if (isKnownNeverZero(Op.getOperand(1), Depth + 1) &&
6724 isKnownNeverZero(Op.getOperand(0), Depth + 1))
6725 return true;
6726 break;
6727
6728 case ISD::ZERO_EXTEND:
6729 case ISD::SIGN_EXTEND:
6730 return isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6731 case ISD::VSCALE: {
6733 const APInt &Multiplier = Op.getConstantOperandAPInt(0);
6734 ConstantRange CR =
6735 getVScaleRange(&F, Op.getScalarValueSizeInBits()).multiply(Multiplier);
6736 if (!CR.contains(APInt(CR.getBitWidth(), 0)))
6737 return true;
6738 break;
6739 }
6740 }
6741
6742 return computeKnownBits(Op, DemandedElts, Depth).isNonZero();
6743}
6744
6746 if (ConstantFPSDNode *C1 = isConstOrConstSplatFP(Op, true))
6747 return !C1->isNegative();
6748
6749 switch (Op.getOpcode()) {
6750 case ISD::FABS:
6751 case ISD::FEXP:
6752 case ISD::FEXP2:
6753 case ISD::FEXP10:
6754 return true;
6755 default:
6756 return false;
6757 }
6758
6759 llvm_unreachable("covered opcode switch");
6760}
6761
6763 assert(Use.getValueType().isFloatingPoint());
6764 const SDNode *User = Use.getUser();
6765 if (User->getFlags().hasNoSignedZeros())
6766 return true;
6767
6768 unsigned OperandNo = Use.getOperandNo();
6769 // Check if this use is insensitive to the sign of zero
6770 switch (User->getOpcode()) {
6771 case ISD::SETCC:
6772 // Comparisons: IEEE-754 specifies +0.0 == -0.0.
6773 case ISD::FABS:
6774 // fabs always produces +0.0.
6775 return true;
6776 case ISD::FCOPYSIGN:
6777 // copysign overwrites the sign bit of the first operand.
6778 return OperandNo == 0;
6779 case ISD::FADD:
6780 case ISD::FSUB: {
6781 // Arithmetic with non-zero constants fixes the uncertainty around the
6782 // sign bit.
6783 SDValue Other = User->getOperand(1 - OperandNo);
6785 }
6786 case ISD::FP_TO_SINT:
6787 case ISD::FP_TO_UINT:
6788 // fp-to-int conversions normalize signed zeros.
6789 return true;
6790 default:
6791 return false;
6792 }
6793}
6794
6796 if (Op->getFlags().hasNoSignedZeros())
6797 return true;
6798 // FIXME: Limit the amount of checked uses to not introduce a compile-time
6799 // regression. Ideally, this should be implemented as a demanded-bits
6800 // optimization that stems from the users.
6801 if (Op->use_size() > 2)
6802 return false;
6803 return all_of(Op->uses(),
6804 [&](const SDUse &Use) { return canIgnoreSignBitOfZero(Use); });
6805}
6806
6808 // Check the obvious case.
6809 if (A == B) return true;
6810
6811 // For negative and positive zero.
6814 if (CA->isZero() && CB->isZero()) return true;
6815
6816 // Otherwise they may not be equal.
6817 return false;
6818}
6819
6820// Only bits set in Mask must be negated, other bits may be arbitrary.
6822 if (isBitwiseNot(V, AllowUndefs))
6823 return V.getOperand(0);
6824
6825 // Handle any_extend (not (truncate X)) pattern, where Mask only sets
6826 // bits in the non-extended part.
6827 ConstantSDNode *MaskC = isConstOrConstSplat(Mask);
6828 if (!MaskC || V.getOpcode() != ISD::ANY_EXTEND)
6829 return SDValue();
6830 SDValue ExtArg = V.getOperand(0);
6831 if (ExtArg.getScalarValueSizeInBits() >=
6832 MaskC->getAPIntValue().getActiveBits() &&
6833 isBitwiseNot(ExtArg, AllowUndefs) &&
6834 ExtArg.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6835 ExtArg.getOperand(0).getOperand(0).getValueType() == V.getValueType())
6836 return ExtArg.getOperand(0).getOperand(0);
6837 return SDValue();
6838}
6839
6841 // Match masked merge pattern (X & ~M) op (Y & M)
6842 // Including degenerate case (X & ~M) op M
6843 auto MatchNoCommonBitsPattern = [&](SDValue Not, SDValue Mask,
6844 SDValue Other) {
6845 if (SDValue NotOperand =
6846 getBitwiseNotOperand(Not, Mask, /* AllowUndefs */ true)) {
6847 if (NotOperand->getOpcode() == ISD::ZERO_EXTEND ||
6848 NotOperand->getOpcode() == ISD::TRUNCATE)
6849 NotOperand = NotOperand->getOperand(0);
6850
6851 if (Other == NotOperand)
6852 return true;
6853 if (Other->getOpcode() == ISD::AND)
6854 return NotOperand == Other->getOperand(0) ||
6855 NotOperand == Other->getOperand(1);
6856 }
6857 return false;
6858 };
6859
6860 if (A->getOpcode() == ISD::ZERO_EXTEND || A->getOpcode() == ISD::TRUNCATE)
6861 A = A->getOperand(0);
6862
6863 if (B->getOpcode() == ISD::ZERO_EXTEND || B->getOpcode() == ISD::TRUNCATE)
6864 B = B->getOperand(0);
6865
6866 if (A->getOpcode() == ISD::AND)
6867 return MatchNoCommonBitsPattern(A->getOperand(0), A->getOperand(1), B) ||
6868 MatchNoCommonBitsPattern(A->getOperand(1), A->getOperand(0), B);
6869 return false;
6870}
6871
6872// FIXME: unify with llvm::haveNoCommonBitsSet.
6874 assert(A.getValueType() == B.getValueType() &&
6875 "Values must have the same type");
6878 return true;
6881}
6882
6883static SDValue FoldSTEP_VECTOR(const SDLoc &DL, EVT VT, SDValue Step,
6884 SelectionDAG &DAG) {
6885 if (cast<ConstantSDNode>(Step)->isZero())
6886 return DAG.getConstant(0, DL, VT);
6887
6888 return SDValue();
6889}
6890
6893 SelectionDAG &DAG) {
6894 int NumOps = Ops.size();
6895 assert(NumOps != 0 && "Can't build an empty vector!");
6896 assert(!VT.isScalableVector() &&
6897 "BUILD_VECTOR cannot be used with scalable types");
6898 assert(VT.getVectorNumElements() == (unsigned)NumOps &&
6899 "Incorrect element count in BUILD_VECTOR!");
6900
6901 // BUILD_VECTOR of UNDEFs is UNDEF.
6902 bool AllPoison = true;
6903 if (llvm::all_of(Ops, [&AllPoison](SDValue Op) {
6904 AllPoison &= Op.getOpcode() == ISD::POISON;
6905 return Op.isUndef();
6906 }))
6907 return AllPoison ? DAG.getPOISON(VT) : DAG.getUNDEF(VT);
6908
6909 // BUILD_VECTOR of seq extract/insert from the same vector + type is Identity.
6910 SDValue IdentitySrc;
6911 bool IsIdentity = true;
6912 for (int i = 0; i != NumOps; ++i) {
6913 if (Ops[i].getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6914 Ops[i].getOperand(0).getValueType() != VT ||
6915 (IdentitySrc && Ops[i].getOperand(0) != IdentitySrc) ||
6916 !isa<ConstantSDNode>(Ops[i].getOperand(1)) ||
6917 Ops[i].getConstantOperandAPInt(1) != i) {
6918 IsIdentity = false;
6919 break;
6920 }
6921 IdentitySrc = Ops[i].getOperand(0);
6922 }
6923 if (IsIdentity)
6924 return IdentitySrc;
6925
6926 return SDValue();
6927}
6928
6929/// Try to simplify vector concatenation to an input value, undef, or build
6930/// vector.
6933 SelectionDAG &DAG) {
6934 assert(!Ops.empty() && "Can't concatenate an empty list of vectors!");
6936 [Ops](SDValue Op) {
6937 return Ops[0].getValueType() == Op.getValueType();
6938 }) &&
6939 "Concatenation of vectors with inconsistent value types!");
6940 assert((Ops[0].getValueType().getVectorElementCount() * Ops.size()) ==
6941 VT.getVectorElementCount() &&
6942 "Incorrect element count in vector concatenation!");
6943
6944 if (Ops.size() == 1)
6945 return Ops[0];
6946
6947 // Concat of UNDEFs is UNDEF.
6948 bool AllPoison = true;
6949 if (llvm::all_of(Ops, [&AllPoison](SDValue Op) {
6950 AllPoison &= Op.getOpcode() == ISD::POISON;
6951 return Op.isUndef();
6952 }))
6953 return AllPoison ? DAG.getPOISON(VT) : DAG.getUNDEF(VT);
6954
6955 // Scan the operands and look for extract operations from a single source
6956 // that correspond to insertion at the same location via this concatenation:
6957 // concat (extract X, 0*subvec_elts), (extract X, 1*subvec_elts), ...
6958 SDValue IdentitySrc;
6959 bool IsIdentity = true;
6960 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
6961 SDValue Op = Ops[i];
6962 unsigned IdentityIndex = i * Op.getValueType().getVectorMinNumElements();
6963 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
6964 Op.getOperand(0).getValueType() != VT ||
6965 (IdentitySrc && Op.getOperand(0) != IdentitySrc) ||
6966 Op.getConstantOperandVal(1) != IdentityIndex) {
6967 IsIdentity = false;
6968 break;
6969 }
6970 assert((!IdentitySrc || IdentitySrc == Op.getOperand(0)) &&
6971 "Unexpected identity source vector for concat of extracts");
6972 IdentitySrc = Op.getOperand(0);
6973 }
6974 if (IsIdentity) {
6975 assert(IdentitySrc && "Failed to set source vector of extracts");
6976 return IdentitySrc;
6977 }
6978
6979 // The code below this point is only designed to work for fixed width
6980 // vectors, so we bail out for now.
6981 if (VT.isScalableVector())
6982 return SDValue();
6983
6984 // A CONCAT_VECTOR of scalar sources, such as UNDEF, BUILD_VECTOR and
6985 // single-element INSERT_VECTOR_ELT operands can be simplified to one big
6986 // BUILD_VECTOR.
6987 // FIXME: Add support for SCALAR_TO_VECTOR as well.
6988 EVT SVT = VT.getScalarType();
6990 for (SDValue Op : Ops) {
6991 EVT OpVT = Op.getValueType();
6992 if (Op.getOpcode() == ISD::POISON)
6993 Elts.append(OpVT.getVectorNumElements(), DAG.getPOISON(SVT));
6994 else if (Op.getOpcode() == ISD::UNDEF)
6995 Elts.append(OpVT.getVectorNumElements(), DAG.getUNDEF(SVT));
6996 else if (Op.getOpcode() == ISD::BUILD_VECTOR)
6997 Elts.append(Op->op_begin(), Op->op_end());
6998 else if (Op.getOpcode() == ISD::INSERT_VECTOR_ELT &&
6999 OpVT.getVectorNumElements() == 1 &&
7000 isNullConstant(Op.getOperand(2)))
7001 Elts.push_back(Op.getOperand(1));
7002 else
7003 return SDValue();
7004 }
7005
7006 // BUILD_VECTOR requires all inputs to be of the same type, find the
7007 // maximum type and extend them all.
7008 for (SDValue Op : Elts)
7009 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
7010
7011 if (SVT.bitsGT(VT.getScalarType())) {
7012 for (SDValue &Op : Elts) {
7013 if (Op.getOpcode() == ISD::POISON)
7014 Op = DAG.getPOISON(SVT);
7015 else if (Op.getOpcode() == ISD::UNDEF)
7016 Op = DAG.getUNDEF(SVT);
7017 else
7018 Op = DAG.getTargetLoweringInfo().isZExtFree(Op.getValueType(), SVT)
7019 ? DAG.getZExtOrTrunc(Op, DL, SVT)
7020 : DAG.getSExtOrTrunc(Op, DL, SVT);
7021 }
7022 }
7023
7024 SDValue V = DAG.getBuildVector(VT, DL, Elts);
7025 NewSDValueDbgMsg(V, "New node fold concat vectors: ", &DAG);
7026 return V;
7027}
7028
7029/// Gets or creates the specified node.
7030SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT) {
7031 SDVTList VTs = getVTList(VT);
7032 SDNodeKey ID(Opcode, VTs, {});
7033 FoldingSetInsertToken InsertToken;
7034 if (SDNode *E = lookupNode(ID, DL, InsertToken))
7035 return SDValue(E, 0);
7036
7037 auto *N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
7038 CSEMap.insert(N, InsertToken);
7039
7040 InsertNode(N);
7041 SDValue V = SDValue(N, 0);
7042 NewSDValueDbgMsg(V, "Creating new node: ", this);
7043 return V;
7044}
7045
7046SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
7047 SDValue N1) {
7048 SDNodeFlags Flags;
7049 if (Inserter)
7050 Flags = Inserter->getFlags();
7051 return getNode(Opcode, DL, VT, N1, Flags);
7052}
7053
7054SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
7055 SDValue N1, const SDNodeFlags Flags) {
7056 assert(N1.getOpcode() != ISD::DELETED_NODE && "Operand is DELETED_NODE!");
7057
7058 // Constant fold unary operations with a vector integer or float operand.
7059 switch (Opcode) {
7060 default:
7061 // FIXME: Entirely reasonable to perform folding of other unary
7062 // operations here as the need arises.
7063 break;
7064 case ISD::FNEG:
7065 case ISD::FABS:
7066 case ISD::FCEIL:
7067 case ISD::FTRUNC:
7068 case ISD::FFLOOR:
7069 case ISD::FP_EXTEND:
7070 case ISD::FP_TO_SINT:
7071 case ISD::FP_TO_UINT:
7072 case ISD::FP_TO_FP16:
7073 case ISD::FP_TO_BF16:
7074 case ISD::TRUNCATE:
7075 case ISD::ANY_EXTEND:
7076 case ISD::ZERO_EXTEND:
7077 case ISD::SIGN_EXTEND:
7078 case ISD::UINT_TO_FP:
7079 case ISD::SINT_TO_FP:
7080 case ISD::FP16_TO_FP:
7081 case ISD::BF16_TO_FP:
7082 case ISD::BITCAST:
7083 case ISD::ABS:
7085 case ISD::BITREVERSE:
7086 case ISD::BSWAP:
7087 case ISD::CTLZ:
7089 case ISD::CTTZ:
7091 case ISD::CTPOP:
7092 case ISD::CTLS:
7093 case ISD::VECREDUCE_ADD:
7098 case ISD::VECREDUCE_MUL:
7099 case ISD::VECREDUCE_AND:
7100 case ISD::VECREDUCE_OR:
7101 case ISD::VECREDUCE_XOR:
7102 case ISD::STEP_VECTOR: {
7103 SDValue Ops = {N1};
7104 if (SDValue Fold = FoldConstantArithmetic(Opcode, DL, VT, Ops))
7105 return Fold;
7106 }
7107 }
7108
7109 unsigned OpOpcode = N1.getNode()->getOpcode();
7110 switch (Opcode) {
7111 case ISD::STEP_VECTOR:
7112 assert(VT.isScalableVector() &&
7113 "STEP_VECTOR can only be used with scalable types");
7114 assert(OpOpcode == ISD::TargetConstant &&
7115 VT.getVectorElementType() == N1.getValueType() &&
7116 "Unexpected step operand");
7117 break;
7118 case ISD::FREEZE:
7119 assert(VT == N1.getValueType() && "Unexpected VT!");
7121 return N1;
7122 break;
7123 case ISD::TokenFactor:
7124 case ISD::MERGE_VALUES:
7126 return N1; // Factor, merge or concat of one node? No need.
7127 case ISD::BUILD_VECTOR: {
7128 // Attempt to simplify BUILD_VECTOR.
7129 SDValue Ops[] = {N1};
7130 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
7131 return V;
7132 break;
7133 }
7134 case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node");
7135 case ISD::FP_EXTEND:
7137 "Invalid FP cast!");
7138 if (N1.getValueType() == VT) return N1; // noop conversion.
7139 assert((!VT.isVector() || VT.getVectorElementCount() ==
7141 "Vector element count mismatch!");
7142 assert(N1.getValueType().bitsLT(VT) && "Invalid fpext node, dst < src!");
7143 if (N1.isUndef())
7144 return getUNDEF(VT);
7145 break;
7146 case ISD::FP_TO_SINT:
7147 case ISD::FP_TO_UINT:
7148 if (N1.isUndef())
7149 return getUNDEF(VT);
7150 break;
7151 case ISD::SINT_TO_FP:
7152 case ISD::UINT_TO_FP:
7153 // [us]itofp(undef) = 0, because the result value is bounded.
7154 if (N1.isUndef())
7155 return getConstantFP(0.0, DL, VT);
7156 break;
7157 case ISD::SIGN_EXTEND:
7158 assert(VT.isInteger() && N1.getValueType().isInteger() &&
7159 "Invalid SIGN_EXTEND!");
7160 assert(VT.isVector() == N1.getValueType().isVector() &&
7161 "SIGN_EXTEND result type type should be vector iff the operand "
7162 "type is vector!");
7163 if (N1.getValueType() == VT) return N1; // noop extension
7164 assert((!VT.isVector() || VT.getVectorElementCount() ==
7166 "Vector element count mismatch!");
7167 assert(N1.getValueType().bitsLT(VT) && "Invalid sext node, dst < src!");
7168 if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND) {
7169 SDNodeFlags Flags;
7170 if (OpOpcode == ISD::ZERO_EXTEND)
7171 Flags.setNonNeg(N1->getFlags().hasNonNeg());
7172 SDValue NewVal = getNode(OpOpcode, DL, VT, N1.getOperand(0), Flags);
7173 transferDbgValues(N1, NewVal);
7174 return NewVal;
7175 }
7176
7177 if (OpOpcode == ISD::POISON)
7178 return getPOISON(VT);
7179
7180 if (N1.isUndef())
7181 // sext(undef) = 0, because the top bits will all be the same.
7182 return getConstant(0, DL, VT);
7183
7184 // Skip unnecessary sext_inreg pattern:
7185 // (sext (trunc x)) -> x iff the upper bits are all signbits.
7186 if (OpOpcode == ISD::TRUNCATE) {
7187 SDValue OpOp = N1.getOperand(0);
7188 if (OpOp.getValueType() == VT) {
7189 unsigned NumSignExtBits =
7191 if (ComputeNumSignBits(OpOp) > NumSignExtBits) {
7192 transferDbgValues(N1, OpOp);
7193 return OpOp;
7194 }
7195 }
7196 }
7197 break;
7198 case ISD::ZERO_EXTEND:
7199 assert(VT.isInteger() && N1.getValueType().isInteger() &&
7200 "Invalid ZERO_EXTEND!");
7201 assert(VT.isVector() == N1.getValueType().isVector() &&
7202 "ZERO_EXTEND result type type should be vector iff the operand "
7203 "type is vector!");
7204 if (N1.getValueType() == VT) return N1; // noop extension
7205 assert((!VT.isVector() || VT.getVectorElementCount() ==
7207 "Vector element count mismatch!");
7208 assert(N1.getValueType().bitsLT(VT) && "Invalid zext node, dst < src!");
7209 if (OpOpcode == ISD::ZERO_EXTEND) { // (zext (zext x)) -> (zext x)
7210 SDNodeFlags Flags;
7211 Flags.setNonNeg(N1->getFlags().hasNonNeg());
7212 SDValue NewVal =
7213 getNode(ISD::ZERO_EXTEND, DL, VT, N1.getOperand(0), Flags);
7214 transferDbgValues(N1, NewVal);
7215 return NewVal;
7216 }
7217
7218 if (OpOpcode == ISD::POISON)
7219 return getPOISON(VT);
7220
7221 if (N1.isUndef())
7222 // zext(undef) = 0, because the top bits will be zero.
7223 return getConstant(0, DL, VT);
7224
7225 // Skip unnecessary zext_inreg pattern:
7226 // (zext (trunc x)) -> x iff the upper bits are known zero.
7227 // TODO: Remove (zext (trunc (and x, c))) exception which some targets
7228 // use to recognise zext_inreg patterns.
7229 if (OpOpcode == ISD::TRUNCATE) {
7230 SDValue OpOp = N1.getOperand(0);
7231 if (OpOp.getValueType() == VT) {
7232 if (OpOp.getOpcode() != ISD::AND) {
7235 if (MaskedValueIsZero(OpOp, HiBits)) {
7236 transferDbgValues(N1, OpOp);
7237 return OpOp;
7238 }
7239 }
7240 }
7241 }
7242 break;
7243 case ISD::ANY_EXTEND:
7244 assert(VT.isInteger() && N1.getValueType().isInteger() &&
7245 "Invalid ANY_EXTEND!");
7246 assert(VT.isVector() == N1.getValueType().isVector() &&
7247 "ANY_EXTEND result type type should be vector iff the operand "
7248 "type is vector!");
7249 if (N1.getValueType() == VT) return N1; // noop extension
7250 assert((!VT.isVector() || VT.getVectorElementCount() ==
7252 "Vector element count mismatch!");
7253 assert(N1.getValueType().bitsLT(VT) && "Invalid anyext node, dst < src!");
7254
7255 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
7256 OpOpcode == ISD::ANY_EXTEND) {
7257 SDNodeFlags Flags;
7258 if (OpOpcode == ISD::ZERO_EXTEND)
7259 Flags.setNonNeg(N1->getFlags().hasNonNeg());
7260 // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x)
7261 return getNode(OpOpcode, DL, VT, N1.getOperand(0), Flags);
7262 }
7263 if (N1.isUndef())
7264 return getUNDEF(VT);
7265
7266 // (ext (trunc x)) -> x
7267 if (OpOpcode == ISD::TRUNCATE) {
7268 SDValue OpOp = N1.getOperand(0);
7269 if (OpOp.getValueType() == VT) {
7270 transferDbgValues(N1, OpOp);
7271 return OpOp;
7272 }
7273 }
7274 break;
7275 case ISD::TRUNCATE:
7276 assert(VT.isInteger() && N1.getValueType().isInteger() &&
7277 "Invalid TRUNCATE!");
7278 assert(VT.isVector() == N1.getValueType().isVector() &&
7279 "TRUNCATE result type type should be vector iff the operand "
7280 "type is vector!");
7281 if (N1.getValueType() == VT) return N1; // noop truncate
7282 assert((!VT.isVector() || VT.getVectorElementCount() ==
7284 "Vector element count mismatch!");
7285 assert(N1.getValueType().bitsGT(VT) && "Invalid truncate node, src < dst!");
7286 if (OpOpcode == ISD::TRUNCATE)
7287 return getNode(ISD::TRUNCATE, DL, VT, N1.getOperand(0));
7288 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
7289 OpOpcode == ISD::ANY_EXTEND) {
7290 // If the source is smaller than the dest, we still need an extend.
7292 VT.getScalarType())) {
7293 SDNodeFlags Flags;
7294 if (OpOpcode == ISD::ZERO_EXTEND)
7295 Flags.setNonNeg(N1->getFlags().hasNonNeg());
7296 return getNode(OpOpcode, DL, VT, N1.getOperand(0), Flags);
7297 }
7298 if (N1.getOperand(0).getValueType().bitsGT(VT))
7299 return getNode(ISD::TRUNCATE, DL, VT, N1.getOperand(0));
7300 return N1.getOperand(0);
7301 }
7302 if (N1.isUndef())
7303 return getUNDEF(VT);
7304 if (OpOpcode == ISD::VSCALE && !NewNodesMustHaveLegalTypes)
7305 return getVScale(DL, VT,
7307 break;
7311 assert(VT.isVector() && "This DAG node is restricted to vector types.");
7312 assert(N1.getValueType().bitsLE(VT) &&
7313 "The input must be the same size or smaller than the result.");
7316 "The destination vector type must have fewer lanes than the input.");
7317 break;
7318 case ISD::ABS:
7319 assert(VT.isInteger() && VT == N1.getValueType() && "Invalid ABS!");
7320 if (N1.isUndef())
7321 return getConstant(0, DL, VT);
7322 break;
7324 assert(VT.isInteger() && VT == N1.getValueType() &&
7325 "Invalid ABS_MIN_POISON!");
7326 if (N1.isUndef())
7327 return getConstant(0, DL, VT);
7328 break;
7329 case ISD::BSWAP:
7330 assert(VT.isInteger() && VT == N1.getValueType() && "Invalid BSWAP!");
7331 assert((VT.getScalarSizeInBits() % 16 == 0) &&
7332 "BSWAP types must be a multiple of 16 bits!");
7333 if (N1.isUndef())
7334 return getUNDEF(VT);
7335 // bswap(bswap(X)) -> X.
7336 if (OpOpcode == ISD::BSWAP)
7337 return N1.getOperand(0);
7338 break;
7339 case ISD::BITREVERSE:
7340 assert(VT.isInteger() && VT == N1.getValueType() && "Invalid BITREVERSE!");
7341 if (N1.isUndef())
7342 return getUNDEF(VT);
7343 break;
7344 case ISD::BITCAST:
7346 "Cannot BITCAST between types of different sizes!");
7347 if (VT == N1.getValueType()) return N1; // noop conversion.
7348 if (OpOpcode == ISD::BITCAST) // bitconv(bitconv(x)) -> bitconv(x)
7349 return getNode(ISD::BITCAST, DL, VT, N1.getOperand(0));
7350 if (N1.isUndef())
7351 return getUNDEF(VT);
7352 break;
7354 assert(VT.isVector() && !N1.getValueType().isVector() &&
7355 (VT.getVectorElementType() == N1.getValueType() ||
7357 N1.getValueType().isInteger() &&
7359 "Illegal SCALAR_TO_VECTOR node!");
7360 if (N1.isUndef())
7361 return getUNDEF(VT);
7362 // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
7363 if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
7365 N1.getConstantOperandVal(1) == 0 &&
7366 N1.getOperand(0).getValueType() == VT)
7367 return N1.getOperand(0);
7368 break;
7369 case ISD::FNEG:
7370 // Negation of an unknown bag of bits is still completely undefined.
7371 if (N1.isUndef())
7372 return getUNDEF(VT);
7373
7374 if (OpOpcode == ISD::FNEG) // --X -> X
7375 return N1.getOperand(0);
7376 break;
7377 case ISD::FABS:
7378 if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X)
7379 return getNode(ISD::FABS, DL, VT, N1.getOperand(0));
7380 break;
7381 case ISD::VSCALE:
7382 assert(VT == N1.getValueType() && "Unexpected VT!");
7383 break;
7384 case ISD::CTPOP:
7385 if (N1.getValueType().getScalarType() == MVT::i1)
7386 return N1;
7387 break;
7388 case ISD::CTLZ:
7389 case ISD::CTTZ:
7390 if (N1.getValueType().getScalarType() == MVT::i1)
7391 return getNOT(DL, N1, N1.getValueType());
7392 break;
7393 case ISD::CTLS:
7394 if (N1.getValueType().getScalarType() == MVT::i1)
7395 return getConstant(0, DL, VT);
7396 break;
7397 case ISD::VECREDUCE_ADD:
7398 if (N1.getValueType().getScalarType() == MVT::i1)
7399 return getNode(ISD::VECREDUCE_XOR, DL, VT, N1);
7400 break;
7403 if (N1.getValueType().getScalarType() == MVT::i1)
7404 return getNode(ISD::VECREDUCE_OR, DL, VT, N1);
7405 break;
7408 if (N1.getValueType().getScalarType() == MVT::i1)
7409 return getNode(ISD::VECREDUCE_AND, DL, VT, N1);
7410 break;
7411 case ISD::SPLAT_VECTOR:
7412 assert(VT.isVector() && "Wrong return type!");
7413 // FIXME: Hexagon uses i32 scalar for a floating point zero vector so allow
7414 // that for now.
7416 (VT.isFloatingPoint() && N1.getValueType() == MVT::i32) ||
7418 N1.getValueType().isInteger() &&
7420 "Wrong operand type!");
7421 break;
7422 }
7423
7424 SDNode *N;
7425 SDVTList VTs = getVTList(VT);
7426 SDValue Ops[] = {N1};
7427 if (VT != MVT::Glue) { // Don't CSE glue producing nodes
7428 SDNodeKey ID(Opcode, VTs, Ops);
7429 FoldingSetInsertToken InsertToken;
7430 if (SDNode *E = lookupNode(ID, DL, InsertToken)) {
7431 E->intersectFlagsWith(Flags);
7432 return SDValue(E, 0);
7433 }
7434
7435 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
7436 N->setFlags(Flags);
7437 createOperands(N, Ops);
7438 CSEMap.insert(N, InsertToken);
7439 } else {
7440 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
7441 createOperands(N, Ops);
7442 }
7443
7444 InsertNode(N);
7445 SDValue V = SDValue(N, 0);
7446 NewSDValueDbgMsg(V, "Creating new node: ", this);
7447 return V;
7448}
7449
7450static APInt getIntegerIdentity(unsigned Opcode, unsigned BitWidth) {
7451 switch (Opcode) {
7452 default:
7453 llvm_unreachable("Unexpected integer identity opcode");
7454 case ISD::ADD:
7455 case ISD::OR:
7456 case ISD::XOR:
7457 case ISD::UMAX:
7458 return APInt::getZero(BitWidth);
7459 case ISD::MUL:
7460 return APInt(BitWidth, 1);
7461 case ISD::AND:
7462 case ISD::UMIN:
7464 case ISD::SMAX:
7466 case ISD::SMIN:
7468 }
7469}
7470
7471static std::optional<APInt> FoldValue(unsigned Opcode, const APInt &C1,
7472 const APInt &C2) {
7473 switch (Opcode) {
7474 case ISD::ADD: return C1 + C2;
7475 case ISD::SUB: return C1 - C2;
7476 case ISD::MUL: return C1 * C2;
7477 case ISD::AND: return C1 & C2;
7478 case ISD::OR: return C1 | C2;
7479 case ISD::XOR: return C1 ^ C2;
7480 case ISD::SHL: return C1 << C2;
7481 case ISD::SRL: return C1.lshr(C2);
7482 case ISD::SRA: return C1.ashr(C2);
7483 case ISD::ROTL: return C1.rotl(C2);
7484 case ISD::ROTR: return C1.rotr(C2);
7485 case ISD::SMIN: return C1.sle(C2) ? C1 : C2;
7486 case ISD::SMAX: return C1.sge(C2) ? C1 : C2;
7487 case ISD::UMIN: return C1.ule(C2) ? C1 : C2;
7488 case ISD::UMAX: return C1.uge(C2) ? C1 : C2;
7489 case ISD::SADDSAT: return C1.sadd_sat(C2);
7490 case ISD::UADDSAT: return C1.uadd_sat(C2);
7491 case ISD::SSUBSAT: return C1.ssub_sat(C2);
7492 case ISD::USUBSAT: return C1.usub_sat(C2);
7493 case ISD::SSHLSAT: return C1.sshl_sat(C2);
7494 case ISD::USHLSAT: return C1.ushl_sat(C2);
7495 case ISD::UDIV:
7496 if (!C2.getBoolValue())
7497 break;
7498 return C1.udiv(C2);
7499 case ISD::UREM:
7500 if (!C2.getBoolValue())
7501 break;
7502 return C1.urem(C2);
7503 case ISD::SDIV:
7504 if (!C2.getBoolValue())
7505 break;
7506 return C1.sdiv(C2);
7507 case ISD::SREM:
7508 if (!C2.getBoolValue())
7509 break;
7510 return C1.srem(C2);
7511 case ISD::AVGFLOORS:
7512 return APIntOps::avgFloorS(C1, C2);
7513 case ISD::AVGFLOORU:
7514 return APIntOps::avgFloorU(C1, C2);
7515 case ISD::AVGCEILS:
7516 return APIntOps::avgCeilS(C1, C2);
7517 case ISD::AVGCEILU:
7518 return APIntOps::avgCeilU(C1, C2);
7519 case ISD::ABDS:
7520 return APIntOps::abds(C1, C2);
7521 case ISD::ABDU:
7522 return APIntOps::abdu(C1, C2);
7523 case ISD::MULHS:
7524 return APIntOps::mulhs(C1, C2);
7525 case ISD::MULHU:
7526 return APIntOps::mulhu(C1, C2);
7527 case ISD::CLMUL:
7528 return APIntOps::clmul(C1, C2);
7529 case ISD::CLMULR:
7530 return APIntOps::clmulr(C1, C2);
7531 case ISD::CLMULH:
7532 return APIntOps::clmulh(C1, C2);
7533 case ISD::PEXT:
7534 return APIntOps::pext(C1, C2);
7535 case ISD::PDEP:
7536 return APIntOps::pdep(C1, C2);
7537 }
7538 return std::nullopt;
7539}
7540// Handle constant folding with UNDEF.
7541// TODO: Handle more cases.
7542static std::optional<APInt> FoldValueWithUndef(unsigned Opcode, const APInt &C1,
7543 bool IsUndef1, const APInt &C2,
7544 bool IsUndef2) {
7545 if (!(IsUndef1 || IsUndef2))
7546 return FoldValue(Opcode, C1, C2);
7547
7548 // Fold and(x, undef) -> 0
7549 // Fold mul(x, undef) -> 0
7550 if (Opcode == ISD::AND || Opcode == ISD::MUL)
7551 return APInt::getZero(C1.getBitWidth());
7552
7553 return std::nullopt;
7554}
7555
7557 const GlobalAddressSDNode *GA,
7558 const SDNode *N2) {
7559 if (GA->getOpcode() != ISD::GlobalAddress)
7560 return SDValue();
7561 if (!TLI->isOffsetFoldingLegal(GA))
7562 return SDValue();
7563 auto *C2 = dyn_cast<ConstantSDNode>(N2);
7564 if (!C2)
7565 return SDValue();
7566 int64_t Offset = C2->getSExtValue();
7567 switch (Opcode) {
7568 case ISD::ADD:
7569 case ISD::PTRADD:
7570 break;
7571 case ISD::SUB: Offset = -uint64_t(Offset); break;
7572 default: return SDValue();
7573 }
7574 return getGlobalAddress(GA->getGlobal(), SDLoc(C2), VT,
7575 GA->getOffset() + uint64_t(Offset));
7576}
7577
7579 switch (Opcode) {
7580 case ISD::SDIV:
7581 case ISD::UDIV:
7582 case ISD::SREM:
7583 case ISD::UREM: {
7584 // If a divisor is zero/undef or any element of a divisor vector is
7585 // zero/undef, the whole op is undef.
7586 assert(Ops.size() == 2 && "Div/rem should have 2 operands");
7587 SDValue Divisor = Ops[1];
7588 if (Divisor.isUndef() || isNullConstant(Divisor))
7589 return true;
7590
7591 return ISD::isBuildVectorOfConstantSDNodes(Divisor.getNode()) &&
7592 llvm::any_of(Divisor->op_values(),
7593 [](SDValue V) { return V.isUndef() ||
7594 isNullConstant(V); });
7595 // TODO: Handle signed overflow.
7596 }
7597 // TODO: Handle oversized shifts.
7598 default:
7599 return false;
7600 }
7601}
7602
7605 SDNodeFlags Flags) {
7606 // If the opcode is a target-specific ISD node, there's nothing we can
7607 // do here and the operand rules may not line up with the below, so
7608 // bail early.
7609 // We can't create a scalar CONCAT_VECTORS so skip it. It will break
7610 // for concats involving SPLAT_VECTOR. Concats of BUILD_VECTORS are handled by
7611 // foldCONCAT_VECTORS in getNode before this is called.
7612 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::CONCAT_VECTORS)
7613 return SDValue();
7614
7615 unsigned NumOps = Ops.size();
7616 if (NumOps == 0)
7617 return SDValue();
7618
7619 if (isUndef(Opcode, Ops))
7620 return getUNDEF(VT);
7621
7622 // Handle unary special cases.
7623 if (NumOps == 1) {
7624 SDValue N1 = Ops[0];
7625
7626 // Constant fold unary operations with an integer constant operand. Even
7627 // opaque constant will be folded, because the folding of unary operations
7628 // doesn't create new constants with different values. Nevertheless, the
7629 // opaque flag is preserved during folding to prevent future folding with
7630 // other constants.
7631 if (auto *C = dyn_cast<ConstantSDNode>(N1)) {
7632 const APInt &Val = C->getAPIntValue();
7633 switch (Opcode) {
7634 case ISD::SIGN_EXTEND:
7635 return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
7636 C->isTargetOpcode(), C->isOpaque());
7637 case ISD::TRUNCATE:
7638 if (C->isOpaque())
7639 break;
7640 [[fallthrough]];
7641 case ISD::ZERO_EXTEND:
7642 return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
7643 C->isTargetOpcode(), C->isOpaque());
7644 case ISD::ANY_EXTEND:
7645 // Some targets like RISCV prefer to sign extend some types.
7646 if (TLI->isSExtCheaperThanZExt(N1.getValueType(), VT))
7647 return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
7648 C->isTargetOpcode(), C->isOpaque());
7649 return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
7650 C->isTargetOpcode(), C->isOpaque());
7651 case ISD::ABS:
7652 return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(),
7653 C->isOpaque());
7655 if (Val.isMinSignedValue())
7656 return getPOISON(VT);
7657 return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(),
7658 C->isOpaque());
7659 case ISD::BITREVERSE:
7660 return getConstant(Val.reverseBits(), DL, VT, C->isTargetOpcode(),
7661 C->isOpaque());
7662 case ISD::BSWAP:
7663 return getConstant(Val.byteSwap(), DL, VT, C->isTargetOpcode(),
7664 C->isOpaque());
7665 case ISD::CTPOP:
7666 return getConstant(Val.popcount(), DL, VT, C->isTargetOpcode(),
7667 C->isOpaque());
7668 case ISD::CTLZ:
7670 return getConstant(Val.countl_zero(), DL, VT, C->isTargetOpcode(),
7671 C->isOpaque());
7672 case ISD::CTTZ:
7674 return getConstant(Val.countr_zero(), DL, VT, C->isTargetOpcode(),
7675 C->isOpaque());
7676 case ISD::CTLS:
7677 // CTLS returns the number of extra sign bits so subtract one.
7678 return getConstant(Val.getNumSignBits() - 1, DL, VT,
7679 C->isTargetOpcode(), C->isOpaque());
7680 case ISD::UINT_TO_FP:
7681 case ISD::SINT_TO_FP: {
7683 (void)FPV.convertFromAPInt(Val, Opcode == ISD::SINT_TO_FP,
7685 return getConstantFP(FPV, DL, VT);
7686 }
7687 case ISD::FP16_TO_FP:
7688 case ISD::BF16_TO_FP: {
7689 bool Ignored;
7690 APFloat FPV(Opcode == ISD::FP16_TO_FP ? APFloat::IEEEhalf()
7691 : APFloat::BFloat(),
7692 (Val.getBitWidth() == 16) ? Val : Val.trunc(16));
7693
7694 // This can return overflow, underflow, or inexact; we don't care.
7695 // FIXME need to be more flexible about rounding mode.
7697 &Ignored);
7698 return getConstantFP(FPV, DL, VT);
7699 }
7700 case ISD::STEP_VECTOR:
7701 if (SDValue V = FoldSTEP_VECTOR(DL, VT, N1, *this))
7702 return V;
7703 break;
7704 case ISD::BITCAST:
7705 if (VT == MVT::f16 && C->getValueType(0) == MVT::i16)
7706 return getConstantFP(APFloat(APFloat::IEEEhalf(), Val), DL, VT);
7707 if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
7708 return getConstantFP(APFloat(APFloat::IEEEsingle(), Val), DL, VT);
7709 if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
7710 return getConstantFP(APFloat(APFloat::IEEEdouble(), Val), DL, VT);
7711 if (VT == MVT::f128 && C->getValueType(0) == MVT::i128)
7712 return getConstantFP(APFloat(APFloat::IEEEquad(), Val), DL, VT);
7713 break;
7714 }
7715 }
7716
7717 // Constant fold unary operations with a floating point constant operand.
7718 if (auto *C = dyn_cast<ConstantFPSDNode>(N1)) {
7719 APFloat V = C->getValueAPF(); // make copy
7720 switch (Opcode) {
7721 case ISD::FNEG:
7722 V.changeSign();
7723 return getConstantFP(V, DL, VT);
7724 case ISD::FABS:
7725 V.clearSign();
7726 return getConstantFP(V, DL, VT);
7727 case ISD::FCEIL: {
7728 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardPositive);
7730 return getConstantFP(V, DL, VT);
7731 return SDValue();
7732 }
7733 case ISD::FTRUNC: {
7734 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardZero);
7736 return getConstantFP(V, DL, VT);
7737 return SDValue();
7738 }
7739 case ISD::FFLOOR: {
7740 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardNegative);
7742 return getConstantFP(V, DL, VT);
7743 return SDValue();
7744 }
7745 case ISD::FP_EXTEND: {
7746 bool ignored;
7747 // This can return overflow, underflow, or inexact; we don't care.
7748 // FIXME need to be more flexible about rounding mode.
7749 (void)V.convert(VT.getFltSemantics(), APFloat::rmNearestTiesToEven,
7750 &ignored);
7751 return getConstantFP(V, DL, VT);
7752 }
7753 case ISD::FP_TO_SINT:
7754 case ISD::FP_TO_UINT: {
7755 bool ignored;
7756 APSInt IntVal(VT.getSizeInBits(), Opcode == ISD::FP_TO_UINT);
7757 // FIXME need to be more flexible about rounding mode.
7759 V.convertToInteger(IntVal, APFloat::rmTowardZero, &ignored);
7760 if (s == APFloat::opInvalidOp) // inexact is OK, in fact usual
7761 break;
7762 return getConstant(IntVal, DL, VT);
7763 }
7764 case ISD::FP_TO_FP16:
7765 case ISD::FP_TO_BF16: {
7766 bool Ignored;
7767 // This can return overflow, underflow, or inexact; we don't care.
7768 // FIXME need to be more flexible about rounding mode.
7769 (void)V.convert(Opcode == ISD::FP_TO_FP16 ? APFloat::IEEEhalf()
7770 : APFloat::BFloat(),
7772 return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
7773 }
7774 case ISD::BITCAST:
7775 if (VT == MVT::i16 && C->getValueType(0) == MVT::f16)
7776 return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL,
7777 VT);
7778 if (VT == MVT::i16 && C->getValueType(0) == MVT::bf16)
7779 return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL,
7780 VT);
7781 if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
7782 return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), DL,
7783 VT);
7784 if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
7785 return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
7786 break;
7787 }
7788 }
7789
7790 // Early-out if we failed to constant fold a bitcast.
7791 if (Opcode == ISD::BITCAST)
7792 return SDValue();
7793
7794 // Constant fold integer vector reductions with constant BUILD_VECTORs.
7795 if ((Opcode == ISD::VECREDUCE_ADD || Opcode == ISD::VECREDUCE_SMAX ||
7796 Opcode == ISD::VECREDUCE_SMIN || Opcode == ISD::VECREDUCE_UMAX ||
7797 Opcode == ISD::VECREDUCE_UMIN || Opcode == ISD::VECREDUCE_MUL ||
7798 Opcode == ISD::VECREDUCE_OR || Opcode == ISD::VECREDUCE_XOR ||
7799 Opcode == ISD::VECREDUCE_AND) &&
7801 unsigned EltBits = N1.getValueType().getScalarSizeInBits();
7802 unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Opcode);
7803 APInt Acc = getIntegerIdentity(BaseOpcode, EltBits);
7804 for (SDValue Elt : N1->op_values()) {
7805 if (Elt.getOpcode() == ISD::POISON)
7806 return getPOISON(VT);
7807 if (Elt.isUndef() || cast<ConstantSDNode>(Elt)->isOpaque())
7808 return SDValue();
7809 APInt Value = cast<ConstantSDNode>(Elt)->getAPIntValue().trunc(EltBits);
7810 std::optional<APInt> Folded = FoldValue(BaseOpcode, Acc, Value);
7811 assert(Folded &&
7812 "Expected vector reduction base opcode to be foldable");
7813 Acc = *Folded;
7814 }
7815 EVT EltVT = N1.getValueType().getScalarType();
7816 return getAnyExtOrTrunc(getConstant(Acc, DL, EltVT), DL, VT);
7817 }
7818 }
7819
7820 // Handle binops special cases.
7821 if (NumOps == 2) {
7822 if (SDValue CFP = foldConstantFPMath(Opcode, DL, VT, Ops))
7823 return CFP;
7824
7825 if (auto *C1 = dyn_cast<ConstantSDNode>(Ops[0])) {
7826 if (auto *C2 = dyn_cast<ConstantSDNode>(Ops[1])) {
7827 if (C1->isOpaque() || C2->isOpaque())
7828 return SDValue();
7829
7830 std::optional<APInt> FoldAttempt =
7831 FoldValue(Opcode, C1->getAPIntValue(), C2->getAPIntValue());
7832 if (!FoldAttempt)
7833 return SDValue();
7834
7835 SDValue Folded = getConstant(*FoldAttempt, DL, VT);
7836 assert((!Folded || !VT.isVector()) &&
7837 "Can't fold vectors ops with scalar operands");
7838 return Folded;
7839 }
7840 }
7841
7842 // fold (add Sym, c) -> Sym+c
7844 return FoldSymbolOffset(Opcode, VT, GA, Ops[1].getNode());
7845 if (TLI->isCommutativeBinOp(Opcode))
7847 return FoldSymbolOffset(Opcode, VT, GA, Ops[0].getNode());
7848
7849 // fold (sext_in_reg c1) -> c2
7850 if (Opcode == ISD::SIGN_EXTEND_INREG) {
7851 EVT EVT = cast<VTSDNode>(Ops[1])->getVT();
7852
7853 auto SignExtendInReg = [&](APInt Val, llvm::EVT ConstantVT) {
7854 unsigned FromBits = EVT.getScalarSizeInBits();
7855 Val <<= Val.getBitWidth() - FromBits;
7856 Val.ashrInPlace(Val.getBitWidth() - FromBits);
7857 return getConstant(Val, DL, ConstantVT);
7858 };
7859
7860 if (auto *C1 = dyn_cast<ConstantSDNode>(Ops[0])) {
7861 const APInt &Val = C1->getAPIntValue();
7862 return SignExtendInReg(Val, VT);
7863 }
7864
7866 SmallVector<SDValue, 8> ScalarOps;
7867 llvm::EVT OpVT = Ops[0].getOperand(0).getValueType();
7868 for (int I = 0, E = VT.getVectorNumElements(); I != E; ++I) {
7869 SDValue Op = Ops[0].getOperand(I);
7870 if (Op.isUndef()) {
7871 ScalarOps.push_back(getUNDEF(OpVT));
7872 continue;
7873 }
7874 const APInt &Val = cast<ConstantSDNode>(Op)->getAPIntValue();
7875 ScalarOps.push_back(SignExtendInReg(Val, OpVT));
7876 }
7877 return getBuildVector(VT, DL, ScalarOps);
7878 }
7879
7880 if (Ops[0].getOpcode() == ISD::SPLAT_VECTOR &&
7881 isa<ConstantSDNode>(Ops[0].getOperand(0)))
7882 return getNode(ISD::SPLAT_VECTOR, DL, VT,
7883 SignExtendInReg(Ops[0].getConstantOperandAPInt(0),
7884 Ops[0].getOperand(0).getValueType()));
7885 }
7886 }
7887
7888 // Handle fshl/fshr special cases.
7889 if (Opcode == ISD::FSHL || Opcode == ISD::FSHR) {
7890 auto *C1 = dyn_cast<ConstantSDNode>(Ops[0]);
7891 auto *C2 = dyn_cast<ConstantSDNode>(Ops[1]);
7892 auto *C3 = dyn_cast<ConstantSDNode>(Ops[2]);
7893
7894 if (C1 && C2 && C3) {
7895 if (C1->isOpaque() || C2->isOpaque() || C3->isOpaque())
7896 return SDValue();
7897 const APInt &V1 = C1->getAPIntValue(), &V2 = C2->getAPIntValue(),
7898 &V3 = C3->getAPIntValue();
7899
7900 APInt FoldedVal = Opcode == ISD::FSHL ? APIntOps::fshl(V1, V2, V3)
7901 : APIntOps::fshr(V1, V2, V3);
7902 return getConstant(FoldedVal, DL, VT);
7903 }
7904 }
7905
7906 // Handle fma/fmad special cases.
7907 if (Opcode == ISD::FMA || Opcode == ISD::FMAD || Opcode == ISD::FMULADD) {
7908 assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
7909 assert(Ops[0].getValueType() == VT && Ops[1].getValueType() == VT &&
7910 Ops[2].getValueType() == VT && "FMA types must match!");
7914 if (C1 && C2 && C3) {
7915 APFloat V1 = C1->getValueAPF();
7916 const APFloat &V2 = C2->getValueAPF();
7917 const APFloat &V3 = C3->getValueAPF();
7918 if (Opcode == ISD::FMAD || Opcode == ISD::FMULADD) {
7919 V1.multiply(V2, APFloat::rmNearestTiesToEven);
7921 } else
7922 V1.fusedMultiplyAdd(V2, V3, APFloat::rmNearestTiesToEven);
7923 return getConstantFP(V1, DL, VT);
7924 }
7925 }
7926
7927 // This is for vector folding only from here on.
7928 if (!VT.isVector())
7929 return SDValue();
7930
7931 // Constant fold integer partial reductions with constant BUILD_VECTOR
7932 // operands. The reduction order is deliberately unspecified. Use the same
7933 // subvector layout as TargetLowering::expandPartialReduceMLA(), where input
7934 // lane I contributes to accumulator lane I % NumAccElts.
7935 if (Opcode == ISD::PARTIAL_REDUCE_SMLA ||
7936 Opcode == ISD::PARTIAL_REDUCE_UMLA ||
7937 Opcode == ISD::PARTIAL_REDUCE_SUMLA) {
7938 // These nodes have no scalar form, so unsupported cases must not fall
7939 // through to generic per-lane vector folding.
7940 if (!llvm::all_of(Ops, [](SDValue Op) {
7941 return ISD::isBuildVectorOfConstantSDNodes(Op.getNode());
7942 }))
7943 return SDValue();
7944
7945 unsigned AccEltBits = VT.getScalarSizeInBits();
7946 unsigned InputEltBits = Ops[1].getScalarValueSizeInBits();
7947 unsigned NumAccElts = VT.getVectorNumElements();
7948 unsigned NumInputElts = Ops[1].getValueType().getVectorNumElements();
7949 SmallVector<APInt, 8> Results(NumAccElts, APInt::getZero(AccEltBits));
7950 BitVector PoisonElts(NumAccElts);
7951
7952 for (unsigned I = 0; I != NumAccElts; ++I) {
7953 SDValue Elt = Ops[0].getOperand(I);
7954 if (Elt.getOpcode() == ISD::POISON) {
7955 PoisonElts.set(I);
7956 continue;
7957 }
7958 auto *C = dyn_cast<ConstantSDNode>(Elt);
7959 if (!C || C->isOpaque())
7960 return SDValue();
7961 Results[I] = C->getAPIntValue().trunc(AccEltBits);
7962 }
7963
7964 bool IsLHSSigned = Opcode != ISD::PARTIAL_REDUCE_UMLA;
7965 bool IsRHSSigned = Opcode == ISD::PARTIAL_REDUCE_SMLA;
7966 for (unsigned I = 0; I != NumInputElts; ++I) {
7967 const unsigned AccIdx = I % NumAccElts;
7968 SDValue LHSElt = Ops[1].getOperand(I);
7969 SDValue RHSElt = Ops[2].getOperand(I);
7970 if (LHSElt.getOpcode() == ISD::POISON ||
7971 RHSElt.getOpcode() == ISD::POISON) {
7972 PoisonElts.set(AccIdx);
7973 continue;
7974 }
7975
7976 auto *LHS = dyn_cast<ConstantSDNode>(LHSElt);
7977 auto *RHS = dyn_cast<ConstantSDNode>(RHSElt);
7978 if (!LHS || !RHS || LHS->isOpaque() || RHS->isOpaque())
7979 return SDValue();
7980
7981 APInt LHSVal = LHS->getAPIntValue().trunc(InputEltBits);
7982 APInt RHSVal = RHS->getAPIntValue().trunc(InputEltBits);
7983 LHSVal = IsLHSSigned ? LHSVal.sext(AccEltBits) : LHSVal.zext(AccEltBits);
7984 RHSVal = IsRHSSigned ? RHSVal.sext(AccEltBits) : RHSVal.zext(AccEltBits);
7985 Results[AccIdx] += LHSVal * RHSVal;
7986 }
7987
7988 // After type legalization the vector element type may not be a legal
7989 // scalar type (e.g. i16 on AArch64). Create the folded constants in the
7990 // promoted legal scalar type instead, matching the generic per-lane path
7991 // below. Bail out if legalization would narrow the type, since the lane
7992 // value would not fit.
7993 EVT AccEltVT = VT.getVectorElementType();
7994 EVT LegalSVT = AccEltVT;
7995 if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
7996 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
7997 if (LegalSVT.bitsLT(AccEltVT))
7998 return SDValue();
7999 }
8000
8001 SmallVector<SDValue, 8> ResultOps;
8002 for (unsigned I = 0; I != NumAccElts; ++I)
8003 ResultOps.push_back(
8004 PoisonElts[I] ? getPOISON(LegalSVT)
8005 : getConstant(Results[I].sext(LegalSVT.getSizeInBits()),
8006 DL, LegalSVT));
8007 return getBuildVector(VT, DL, ResultOps);
8008 }
8009
8010 ElementCount NumElts = VT.getVectorElementCount();
8011
8012 // See if we can fold through any bitcasted integer ops.
8013 if (NumOps == 2 && VT.isFixedLengthVector() && VT.isInteger() &&
8014 Ops[0].getValueType() == VT && Ops[1].getValueType() == VT &&
8015 (Ops[0].getOpcode() == ISD::BITCAST ||
8016 Ops[1].getOpcode() == ISD::BITCAST)) {
8019 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
8020 auto *BV2 = dyn_cast<BuildVectorSDNode>(N2);
8021 if (BV1 && BV2 && N1.getValueType().isInteger() &&
8022 N2.getValueType().isInteger()) {
8023 bool IsLE = getDataLayout().isLittleEndian();
8024 unsigned EltBits = VT.getScalarSizeInBits();
8025 SmallVector<APInt> RawBits1, RawBits2;
8026 BitVector UndefElts1, UndefElts2;
8027 if (BV1->getConstantRawBits(IsLE, EltBits, RawBits1, UndefElts1) &&
8028 BV2->getConstantRawBits(IsLE, EltBits, RawBits2, UndefElts2)) {
8029 SmallVector<APInt> RawBits;
8030 for (unsigned I = 0, E = NumElts.getFixedValue(); I != E; ++I) {
8031 std::optional<APInt> Fold = FoldValueWithUndef(
8032 Opcode, RawBits1[I], UndefElts1[I], RawBits2[I], UndefElts2[I]);
8033 if (!Fold)
8034 break;
8035 RawBits.push_back(*Fold);
8036 }
8037 if (RawBits.size() == NumElts.getFixedValue()) {
8038 // We have constant folded, but we might need to cast this again back
8039 // to the original (possibly legalized) type.
8040 EVT BVVT, BVEltVT;
8041 if (N1.getValueType() == VT) {
8042 BVVT = N1.getValueType();
8043 BVEltVT = BV1->getOperand(0).getValueType();
8044 } else {
8045 BVVT = N2.getValueType();
8046 BVEltVT = BV2->getOperand(0).getValueType();
8047 }
8048 unsigned BVEltBits = BVEltVT.getSizeInBits();
8049 SmallVector<APInt> DstBits;
8050 BitVector DstUndefs;
8052 DstBits, RawBits, DstUndefs,
8053 BitVector(RawBits.size(), false));
8054 SmallVector<SDValue> Ops(DstBits.size(), getUNDEF(BVEltVT));
8055 for (unsigned I = 0, E = DstBits.size(); I != E; ++I) {
8056 if (DstUndefs[I])
8057 continue;
8058 Ops[I] = getConstant(DstBits[I].sext(BVEltBits), DL, BVEltVT);
8059 }
8060 return getBitcast(VT, getBuildVector(BVVT, DL, Ops));
8061 }
8062 }
8063 }
8064 // Logic ops can be folded from raw integer bits - mainly for AVX512 masks.
8065 if (ISD::isBitwiseLogicOp(Opcode) && isa<ConstantSDNode>(N1) &&
8066 isa<ConstantSDNode>(N2)) {
8067 if (SDValue Res = FoldConstantArithmetic(Opcode, DL, N1.getValueType(),
8068 {N1, N2}, Flags))
8069 return getBitcast(VT, Res);
8070 }
8071 }
8072
8073 // Fold (mul step_vector(C0), C1) to (step_vector(C0 * C1)).
8074 // (shl step_vector(C0), C1) -> (step_vector(C0 << C1))
8075 if ((Opcode == ISD::MUL || Opcode == ISD::SHL) &&
8076 Ops[0].getOpcode() == ISD::STEP_VECTOR) {
8077 APInt RHSVal;
8078 if (ISD::isConstantSplatVector(Ops[1].getNode(), RHSVal)) {
8079 APInt NewStep = Opcode == ISD::MUL
8080 ? Ops[0].getConstantOperandAPInt(0) * RHSVal
8081 : Ops[0].getConstantOperandAPInt(0) << RHSVal;
8082 return getStepVector(DL, VT, NewStep);
8083 }
8084 }
8085
8086 auto IsScalarOrSameVectorSize = [NumElts](const SDValue &Op) {
8087 return !Op.getValueType().isVector() ||
8088 Op.getValueType().getVectorElementCount() == NumElts;
8089 };
8090
8091 auto IsBuildVectorSplatVectorOrUndef = [](const SDValue &Op) {
8092 return Op.isUndef() || Op.getOpcode() == ISD::CONDCODE ||
8093 Op.getOpcode() == ISD::BUILD_VECTOR ||
8094 Op.getOpcode() == ISD::SPLAT_VECTOR;
8095 };
8096
8097 // All operands must be vector types with the same number of elements as
8098 // the result type and must be either UNDEF or a build/splat vector
8099 // or UNDEF scalars.
8100 if (!llvm::all_of(Ops, IsBuildVectorSplatVectorOrUndef) ||
8101 !llvm::all_of(Ops, IsScalarOrSameVectorSize))
8102 return SDValue();
8103
8104 // If we are comparing vectors, then the result needs to be a i1 boolean that
8105 // is then extended back to the legal result type depending on how booleans
8106 // are represented.
8107 EVT SVT = (Opcode == ISD::SETCC ? MVT::i1 : VT.getScalarType());
8108 ISD::NodeType ExtendCode =
8109 (Opcode == ISD::SETCC && SVT != VT.getScalarType())
8110 ? TargetLowering::getExtendForContent(TLI->getBooleanContents(VT))
8112
8113 // Find legal integer scalar type for constant promotion and
8114 // ensure that its scalar size is at least as large as source.
8115 EVT LegalSVT = VT.getScalarType();
8116 if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
8117 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
8118 if (LegalSVT.bitsLT(VT.getScalarType()))
8119 return SDValue();
8120 }
8121
8122 // For scalable vector types we know we're dealing with SPLAT_VECTORs. We
8123 // only have one operand to check. For fixed-length vector types we may have
8124 // a combination of BUILD_VECTOR and SPLAT_VECTOR.
8125 unsigned NumVectorElts = NumElts.isScalable() ? 1 : NumElts.getFixedValue();
8126
8127 // Constant fold each scalar lane separately.
8128 SmallVector<SDValue, 4> ScalarResults;
8129 for (unsigned I = 0; I != NumVectorElts; I++) {
8130 SmallVector<SDValue, 4> ScalarOps;
8131 for (SDValue Op : Ops) {
8132 EVT InSVT = Op.getValueType().getScalarType();
8133 if (Op.getOpcode() != ISD::BUILD_VECTOR &&
8134 Op.getOpcode() != ISD::SPLAT_VECTOR) {
8135 if (Op.isUndef())
8136 ScalarOps.push_back(getUNDEF(InSVT));
8137 else
8138 ScalarOps.push_back(Op);
8139 continue;
8140 }
8141
8142 SDValue ScalarOp =
8143 Op.getOperand(Op.getOpcode() == ISD::SPLAT_VECTOR ? 0 : I);
8144 EVT ScalarVT = ScalarOp.getValueType();
8145
8146 // Build vector (integer) scalar operands may need implicit
8147 // truncation - do this before constant folding.
8148 if (ScalarVT.isInteger() && ScalarVT.bitsGT(InSVT)) {
8149 // Don't create illegally-typed nodes unless they're constants or undef
8150 // - if we fail to constant fold we can't guarantee the (dead) nodes
8151 // we're creating will be cleaned up before being visited for
8152 // legalization.
8153 if (NewNodesMustHaveLegalTypes && !ScalarOp.isUndef() &&
8154 !isa<ConstantSDNode>(ScalarOp) &&
8155 TLI->getTypeAction(*getContext(), InSVT) !=
8157 return SDValue();
8158 ScalarOp = getNode(ISD::TRUNCATE, DL, InSVT, ScalarOp);
8159 }
8160
8161 ScalarOps.push_back(ScalarOp);
8162 }
8163
8164 // Constant fold the scalar operands.
8165 SDValue ScalarResult = getNode(Opcode, DL, SVT, ScalarOps, Flags);
8166
8167 // Scalar folding only succeeded if the result is a constant or UNDEF.
8168 if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant &&
8169 ScalarResult.getOpcode() != ISD::ConstantFP)
8170 return SDValue();
8171
8172 // Legalize the (integer) scalar constant if necessary. We only do
8173 // this once we know the folding succeeded, since otherwise we would
8174 // get a node with illegal type which has a user.
8175 if (LegalSVT != SVT)
8176 ScalarResult = getNode(ExtendCode, DL, LegalSVT, ScalarResult);
8177
8178 ScalarResults.push_back(ScalarResult);
8179 }
8180
8181 SDValue V = NumElts.isScalable() ? getSplatVector(VT, DL, ScalarResults[0])
8182 : getBuildVector(VT, DL, ScalarResults);
8183 NewSDValueDbgMsg(V, "New node fold constant vector: ", this);
8184 return V;
8185}
8186
8189 // TODO: Add support for unary/ternary fp opcodes.
8190 if (Ops.size() != 2)
8191 return SDValue();
8192
8193 // TODO: We don't do any constant folding for strict FP opcodes here, but we
8194 // should. That will require dealing with a potentially non-default
8195 // rounding mode, checking the "opStatus" return value from the APFloat
8196 // math calculations, and possibly other variations.
8197 SDValue N1 = Ops[0];
8198 SDValue N2 = Ops[1];
8199 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1, /*AllowUndefs*/ false);
8200 ConstantFPSDNode *N2CFP = isConstOrConstSplatFP(N2, /*AllowUndefs*/ false);
8201 if (N1CFP && N2CFP) {
8202 APFloat C1 = N1CFP->getValueAPF(); // make copy
8203 const APFloat &C2 = N2CFP->getValueAPF();
8204 switch (Opcode) {
8205 case ISD::FADD:
8207 return getConstantFP(C1, DL, VT);
8208 case ISD::FSUB:
8210 return getConstantFP(C1, DL, VT);
8211 case ISD::FMUL:
8213 return getConstantFP(C1, DL, VT);
8214 case ISD::FDIV:
8216 return getConstantFP(C1, DL, VT);
8217 case ISD::FREM:
8218 C1.mod(C2);
8219 return getConstantFP(C1, DL, VT);
8220 case ISD::FCOPYSIGN:
8221 C1.copySign(C2);
8222 return getConstantFP(C1, DL, VT);
8223 case ISD::FMINNUM:
8224 return getConstantFP(minnum(C1, C2), DL, VT);
8225 case ISD::FMAXNUM:
8226 return getConstantFP(maxnum(C1, C2), DL, VT);
8227 case ISD::FMINIMUM:
8228 return getConstantFP(minimum(C1, C2), DL, VT);
8229 case ISD::FMAXIMUM:
8230 return getConstantFP(maximum(C1, C2), DL, VT);
8231 case ISD::FMINIMUMNUM:
8232 return getConstantFP(minimumnum(C1, C2), DL, VT);
8233 case ISD::FMAXIMUMNUM:
8234 return getConstantFP(maximumnum(C1, C2), DL, VT);
8235 default: break;
8236 }
8237 }
8238 if (N1CFP && Opcode == ISD::FP_ROUND) {
8239 APFloat C1 = N1CFP->getValueAPF(); // make copy
8240 bool Unused;
8241 // This can return overflow, underflow, or inexact; we don't care.
8242 // FIXME need to be more flexible about rounding mode.
8244 &Unused);
8245 return getConstantFP(C1, DL, VT);
8246 }
8247
8248 switch (Opcode) {
8249 case ISD::FSUB:
8250 // -0.0 - undef --> undef (consistent with "fneg undef")
8251 if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1, /*AllowUndefs*/ true))
8252 if (N1C && N1C->getValueAPF().isNegZero() && N2.isUndef())
8253 return getUNDEF(VT);
8254 [[fallthrough]];
8255
8256 case ISD::FADD:
8257 case ISD::FMUL:
8258 case ISD::FDIV:
8259 case ISD::FREM:
8260 // If both operands are undef, the result is undef. If 1 operand is undef,
8261 // the result is NaN. This should match the behavior of the IR optimizer.
8262 if (N1.isUndef() && N2.isUndef())
8263 return getUNDEF(VT);
8264 if (N1.isUndef() || N2.isUndef())
8266 }
8267 return SDValue();
8268}
8269
8271 const SDLoc &DL, EVT DstEltVT) {
8272 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
8273
8274 // If this is already the right type, we're done.
8275 if (SrcEltVT == DstEltVT)
8276 return SDValue(BV, 0);
8277
8278 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
8279 unsigned DstBitSize = DstEltVT.getSizeInBits();
8280
8281 // If this is a conversion of N elements of one type to N elements of another
8282 // type, convert each element. This handles FP<->INT cases.
8283 if (SrcBitSize == DstBitSize) {
8285 for (SDValue Op : BV->op_values()) {
8286 // If the vector element type is not legal, the BUILD_VECTOR operands
8287 // are promoted and implicitly truncated. Make that explicit here.
8288 if (Op.getValueType() != SrcEltVT)
8289 Op = getNode(ISD::TRUNCATE, DL, SrcEltVT, Op);
8290 Ops.push_back(getBitcast(DstEltVT, Op));
8291 }
8292 EVT VT = EVT::getVectorVT(*getContext(), DstEltVT,
8294 return getBuildVector(VT, DL, Ops);
8295 }
8296
8297 // Otherwise, we're growing or shrinking the elements. To avoid having to
8298 // handle annoying details of growing/shrinking FP values, we convert them to
8299 // int first.
8300 if (SrcEltVT.isFloatingPoint()) {
8301 // Convert the input float vector to a int vector where the elements are the
8302 // same sizes.
8303 EVT IntEltVT = EVT::getIntegerVT(*getContext(), SrcEltVT.getSizeInBits());
8304 if (SDValue Tmp = FoldConstantBuildVector(BV, DL, IntEltVT))
8306 DstEltVT);
8307 return SDValue();
8308 }
8309
8310 // Now we know the input is an integer vector. If the output is a FP type,
8311 // convert to integer first, then to FP of the right size.
8312 if (DstEltVT.isFloatingPoint()) {
8313 EVT IntEltVT = EVT::getIntegerVT(*getContext(), DstEltVT.getSizeInBits());
8314 if (SDValue Tmp = FoldConstantBuildVector(BV, DL, IntEltVT))
8316 DstEltVT);
8317 return SDValue();
8318 }
8319
8320 // Okay, we know the src/dst types are both integers of differing types.
8321 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
8322
8323 // Extract the constant raw bit data.
8324 BitVector UndefElements;
8325 SmallVector<APInt> RawBits;
8326 bool IsLE = getDataLayout().isLittleEndian();
8327 if (!BV->getConstantRawBits(IsLE, DstBitSize, RawBits, UndefElements))
8328 return SDValue();
8329
8331 for (unsigned I = 0, E = RawBits.size(); I != E; ++I) {
8332 if (UndefElements[I])
8333 Ops.push_back(getUNDEF(DstEltVT));
8334 else
8335 Ops.push_back(getConstant(RawBits[I], DL, DstEltVT));
8336 }
8337
8338 EVT VT = EVT::getVectorVT(*getContext(), DstEltVT, Ops.size());
8339 return getBuildVector(VT, DL, Ops);
8340}
8341
8343 assert(Val.getValueType().isInteger() && "Invalid AssertAlign!");
8344
8345 // There's no need to assert on a byte-aligned pointer. All pointers are at
8346 // least byte aligned.
8347 if (A == Align(1))
8348 return Val;
8349
8350 SDVTList VTs = getVTList(Val.getValueType());
8351 SDValue Ops[] = {Val};
8352 SDNodeKey ID(ISD::AssertAlign, VTs, Ops);
8353 ID.AddInteger(A.value());
8354
8355 FoldingSetInsertToken InsertToken;
8356 if (SDNode *E = lookupNode(ID, DL, InsertToken))
8357 return SDValue(E, 0);
8358
8359 auto *N =
8360 newSDNode<AssertAlignSDNode>(DL.getIROrder(), DL.getDebugLoc(), VTs, A);
8361 createOperands(N, {Val});
8362
8363 CSEMap.insert(N, InsertToken);
8364 InsertNode(N);
8365
8366 SDValue V(N, 0);
8367 NewSDValueDbgMsg(V, "Creating new node: ", this);
8368 return V;
8369}
8370
8371SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8372 SDValue N1, SDValue N2) {
8373 SDNodeFlags Flags;
8374 if (Inserter)
8375 Flags = Inserter->getFlags();
8376 return getNode(Opcode, DL, VT, N1, N2, Flags);
8377}
8378
8380 SDValue &N2) const {
8381 if (!TLI->isCommutativeBinOp(Opcode))
8382 return;
8383
8384 // Canonicalize:
8385 // binop(const, nonconst) -> binop(nonconst, const)
8388 bool N1CFP = isConstantFPBuildVectorOrConstantFP(N1);
8389 bool N2CFP = isConstantFPBuildVectorOrConstantFP(N2);
8390 if ((N1C && !N2C) || (N1CFP && !N2CFP))
8391 std::swap(N1, N2);
8392
8393 // Canonicalize:
8394 // binop(splat(x), step_vector) -> binop(step_vector, splat(x))
8395 else if (N1.getOpcode() == ISD::SPLAT_VECTOR &&
8397 std::swap(N1, N2);
8398}
8399
8400SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8401 SDValue N1, SDValue N2, const SDNodeFlags Flags) {
8403 N2.getOpcode() != ISD::DELETED_NODE &&
8404 "Operand is DELETED_NODE!");
8405
8406 canonicalizeCommutativeBinop(Opcode, N1, N2);
8407
8408 auto *N1C = dyn_cast<ConstantSDNode>(N1);
8409 auto *N2C = dyn_cast<ConstantSDNode>(N2);
8410
8411 // Don't allow undefs in vector splats - we might be returning N2 when folding
8412 // to zero etc.
8413 ConstantSDNode *N2CV =
8414 isConstOrConstSplat(N2, /*AllowUndefs*/ false, /*AllowTruncation*/ true);
8415
8416 switch (Opcode) {
8417 default: break;
8418 case ISD::TokenFactor:
8419 assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
8420 N2.getValueType() == MVT::Other && "Invalid token factor!");
8421 // Fold trivial token factors.
8422 if (N1.getOpcode() == ISD::EntryToken) return N2;
8423 if (N2.getOpcode() == ISD::EntryToken) return N1;
8424 if (N1 == N2) return N1;
8425 break;
8426 case ISD::BUILD_VECTOR: {
8427 // Attempt to simplify BUILD_VECTOR.
8428 SDValue Ops[] = {N1, N2};
8429 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
8430 return V;
8431 break;
8432 }
8433 case ISD::CONCAT_VECTORS: {
8434 SDValue Ops[] = {N1, N2};
8435 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
8436 return V;
8437 break;
8438 }
8439 case ISD::AND:
8440 assert(VT.isInteger() && "This operator does not apply to FP types!");
8441 assert(N1.getValueType() == N2.getValueType() &&
8442 N1.getValueType() == VT && "Binary operator types must match!");
8443 // (X & 0) -> 0. This commonly occurs when legalizing i64 values, so it's
8444 // worth handling here.
8445 if (N2CV && N2CV->isZero())
8446 return N2;
8447 if (N2CV && N2CV->isAllOnes()) // X & -1 -> X
8448 return N1;
8449 break;
8450 case ISD::OR:
8451 case ISD::XOR:
8452 case ISD::ADD:
8453 case ISD::PTRADD:
8454 case ISD::SUB:
8455 assert(VT.isInteger() && "This operator does not apply to FP types!");
8456 assert(N1.getValueType() == N2.getValueType() &&
8457 N1.getValueType() == VT && "Binary operator types must match!");
8458 // The equal operand types requirement is unnecessarily strong for PTRADD.
8459 // However, the SelectionDAGBuilder does not generate PTRADDs with different
8460 // operand types, and we'd need to re-implement GEP's non-standard wrapping
8461 // logic everywhere where PTRADDs may be folded or combined to properly
8462 // support them. If/when we introduce pointer types to the SDAG, we will
8463 // need to relax this constraint.
8464
8465 // (X ^|+- 0) -> X. This commonly occurs when legalizing i64 values, so
8466 // it's worth handling here.
8467 if (N2CV && N2CV->isZero())
8468 return N1;
8469 if ((Opcode == ISD::ADD || Opcode == ISD::SUB) &&
8470 VT.getScalarType() == MVT::i1)
8471 return getNode(ISD::XOR, DL, VT, N1, N2);
8472 // Fold (add (vscale * C0), (vscale * C1)) to (vscale * (C0 + C1)).
8473 if (Opcode == ISD::ADD && N1.getOpcode() == ISD::VSCALE &&
8474 N2.getOpcode() == ISD::VSCALE) {
8475 const APInt &C1 = N1->getConstantOperandAPInt(0);
8476 const APInt &C2 = N2->getConstantOperandAPInt(0);
8477 return getVScale(DL, VT, C1 + C2);
8478 }
8479 break;
8480 case ISD::MUL:
8481 assert(VT.isInteger() && "This operator does not apply to FP types!");
8482 assert(N1.getValueType() == N2.getValueType() &&
8483 N1.getValueType() == VT && "Binary operator types must match!");
8484 if (VT.getScalarType() == MVT::i1)
8485 return getNode(ISD::AND, DL, VT, N1, N2);
8486 if (N2CV && N2CV->isZero())
8487 return N2;
8488 if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
8489 const APInt &MulImm = N1->getConstantOperandAPInt(0);
8490 const APInt &N2CImm = N2C->getAPIntValue();
8491 return getVScale(DL, VT, MulImm * N2CImm);
8492 }
8493 break;
8494 case ISD::UDIV:
8495 case ISD::UREM:
8496 case ISD::MULHU:
8497 case ISD::MULHS:
8498 case ISD::SDIV:
8499 case ISD::SREM:
8500 case ISD::SADDSAT:
8501 case ISD::SSUBSAT:
8502 case ISD::UADDSAT:
8503 case ISD::USUBSAT:
8504 assert(VT.isInteger() && "This operator does not apply to FP types!");
8505 assert(N1.getValueType() == N2.getValueType() &&
8506 N1.getValueType() == VT && "Binary operator types must match!");
8507 if (VT.getScalarType() == MVT::i1) {
8508 // fold (add_sat x, y) -> (or x, y) for bool types.
8509 if (Opcode == ISD::SADDSAT || Opcode == ISD::UADDSAT)
8510 return getNode(ISD::OR, DL, VT, N1, N2);
8511 // fold (sub_sat x, y) -> (and x, ~y) for bool types.
8512 if (Opcode == ISD::SSUBSAT || Opcode == ISD::USUBSAT)
8513 return getNode(ISD::AND, DL, VT, N1, getNOT(DL, N2, VT));
8514 }
8515 break;
8516 case ISD::SCMP:
8517 case ISD::UCMP:
8518 assert(N1.getValueType() == N2.getValueType() &&
8519 "Types of operands of UCMP/SCMP must match");
8520 assert(N1.getValueType().isVector() == VT.isVector() &&
8521 "Operands and return type of must both be scalars or vectors");
8522 if (VT.isVector())
8525 "Result and operands must have the same number of elements");
8526 break;
8527 case ISD::AVGFLOORS:
8528 case ISD::AVGFLOORU:
8529 case ISD::AVGCEILS:
8530 case ISD::AVGCEILU:
8531 assert(VT.isInteger() && "This operator does not apply to FP types!");
8532 assert(N1.getValueType() == N2.getValueType() &&
8533 N1.getValueType() == VT && "Binary operator types must match!");
8534 break;
8535 case ISD::ABDS:
8536 case ISD::ABDU:
8537 assert(VT.isInteger() && "This operator does not apply to FP types!");
8538 assert(N1.getValueType() == N2.getValueType() &&
8539 N1.getValueType() == VT && "Binary operator types must match!");
8540 if (VT.getScalarType() == MVT::i1)
8541 return getNode(ISD::XOR, DL, VT, N1, N2);
8542 break;
8543 case ISD::SMIN:
8544 case ISD::UMAX:
8545 assert(VT.isInteger() && "This operator does not apply to FP types!");
8546 assert(N1.getValueType() == N2.getValueType() &&
8547 N1.getValueType() == VT && "Binary operator types must match!");
8548 if (VT.getScalarType() == MVT::i1)
8549 return getNode(ISD::OR, DL, VT, N1, N2);
8550 break;
8551 case ISD::SMAX:
8552 case ISD::UMIN:
8553 assert(VT.isInteger() && "This operator does not apply to FP types!");
8554 assert(N1.getValueType() == N2.getValueType() &&
8555 N1.getValueType() == VT && "Binary operator types must match!");
8556 if (VT.getScalarType() == MVT::i1)
8557 return getNode(ISD::AND, DL, VT, N1, N2);
8558 break;
8559 case ISD::FADD:
8560 case ISD::FSUB:
8561 case ISD::FMUL:
8562 case ISD::FDIV:
8563 case ISD::FREM:
8564 assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
8565 assert(N1.getValueType() == N2.getValueType() &&
8566 N1.getValueType() == VT && "Binary operator types must match!");
8567 if (SDValue V = simplifyFPBinop(Opcode, N1, N2, Flags))
8568 return V;
8569 break;
8570 case ISD::FCOPYSIGN: // N1 and result must match. N1/N2 need not match.
8571 assert(N1.getValueType() == VT &&
8574 "Invalid FCOPYSIGN!");
8575 break;
8576 case ISD::SHL:
8577 if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
8578 const APInt &MulImm = N1->getConstantOperandAPInt(0);
8579 const APInt &ShiftImm = N2C->getAPIntValue();
8580 return getVScale(DL, VT, MulImm << ShiftImm);
8581 }
8582 [[fallthrough]];
8583 case ISD::SRA:
8584 case ISD::SRL:
8585 if (SDValue V = simplifyShift(N1, N2))
8586 return V;
8587 [[fallthrough]];
8588 case ISD::ROTL:
8589 case ISD::ROTR:
8590 case ISD::SSHLSAT:
8591 case ISD::USHLSAT:
8592 assert(VT == N1.getValueType() &&
8593 "Shift operators return type must be the same as their first arg");
8594 assert(VT.isInteger() && N2.getValueType().isInteger() &&
8595 "Shifts only work on integers");
8596 assert((!VT.isVector() || VT == N2.getValueType()) &&
8597 "Vector shift amounts must be in the same as their first arg");
8598 // Verify that the shift amount VT is big enough to hold valid shift
8599 // amounts. This catches things like trying to shift an i1024 value by an
8600 // i8, which is easy to fall into in generic code that uses
8601 // TLI.getShiftAmount().
8604 "Invalid use of small shift amount with oversized value!");
8605
8606 // Always fold shifts of i1 values so the code generator doesn't need to
8607 // handle them. Since we know the size of the shift has to be less than the
8608 // size of the value, the shift/rotate count is guaranteed to be zero.
8609 if (VT == MVT::i1)
8610 return N1;
8611 if (N2CV && N2CV->isZero())
8612 return N1;
8613 break;
8614 case ISD::FP_ROUND:
8616 VT.bitsLE(N1.getValueType()) && N2C &&
8617 (N2C->getZExtValue() == 0 || N2C->getZExtValue() == 1) &&
8618 N2.getOpcode() == ISD::TargetConstant && "Invalid FP_ROUND!");
8619 if (N1.getValueType() == VT) return N1; // noop conversion.
8620 break;
8621 case ISD::IS_FPCLASS: {
8623 "IS_FPCLASS is used for a non-floating type");
8624 assert(isa<ConstantSDNode>(N2) && "FPClassTest is not Constant");
8625 // is.fpclass(poison, mask) -> poison
8626 if (N1.getOpcode() == ISD::POISON)
8627 return getPOISON(VT);
8628 FPClassTest Mask = static_cast<FPClassTest>(N2->getAsZExtVal());
8629 // If all tests are made, it doesn't matter what the value is.
8630 if ((Mask & fcAllFlags) == fcAllFlags)
8631 return getBoolConstant(true, DL, VT, N1.getValueType());
8632 if ((Mask & fcAllFlags) == 0)
8633 return getBoolConstant(false, DL, VT, N1.getValueType());
8634 break;
8635 }
8636 case ISD::AssertNoFPClass: {
8638 "AssertNoFPClass is used for a non-floating type");
8639 assert(isa<ConstantSDNode>(N2) && "NoFPClass is not Constant");
8640 FPClassTest NoFPClass = static_cast<FPClassTest>(N2->getAsZExtVal());
8641 assert(llvm::to_underlying(NoFPClass) <=
8643 "FPClassTest value too large");
8644 (void)NoFPClass;
8645 break;
8646 }
8647 case ISD::AssertSext:
8648 case ISD::AssertZext: {
8649 EVT EVT = cast<VTSDNode>(N2)->getVT();
8650 assert(VT == N1.getValueType() && "Not an inreg extend!");
8651 assert(VT.isInteger() && EVT.isInteger() &&
8652 "Cannot *_EXTEND_INREG FP types");
8653 assert(!EVT.isVector() &&
8654 "AssertSExt/AssertZExt type should be the vector element type "
8655 "rather than the vector type!");
8656 assert(EVT.bitsLE(VT.getScalarType()) && "Not extending!");
8657 if (VT.getScalarType() == EVT) return N1; // noop assertion.
8658 break;
8659 }
8661 EVT EVT = cast<VTSDNode>(N2)->getVT();
8662 assert(VT == N1.getValueType() && "Not an inreg extend!");
8663 assert(VT.isInteger() && EVT.isInteger() &&
8664 "Cannot *_EXTEND_INREG FP types");
8665 assert(EVT.isVector() == VT.isVector() &&
8666 "SIGN_EXTEND_INREG type should be vector iff the operand "
8667 "type is vector!");
8668 assert((!EVT.isVector() ||
8670 "Vector element counts must match in SIGN_EXTEND_INREG");
8671 assert(EVT.getScalarType().bitsLE(VT.getScalarType()) && "Not extending!");
8672 if (EVT == VT) return N1; // Not actually extending
8673 break;
8674 }
8676 case ISD::FP_TO_UINT_SAT: {
8677 assert(VT.isInteger() && cast<VTSDNode>(N2)->getVT().isInteger() &&
8678 N1.getValueType().isFloatingPoint() && "Invalid FP_TO_*INT_SAT");
8679 assert(N1.getValueType().isVector() == VT.isVector() &&
8680 "FP_TO_*INT_SAT type should be vector iff the operand type is "
8681 "vector!");
8682 assert((!VT.isVector() || VT.getVectorElementCount() ==
8684 "Vector element counts must match in FP_TO_*INT_SAT");
8685 assert(!cast<VTSDNode>(N2)->getVT().isVector() &&
8686 "Type to saturate to must be a scalar.");
8687 assert(cast<VTSDNode>(N2)->getVT().bitsLE(VT.getScalarType()) &&
8688 "Not extending!");
8689 break;
8690 }
8693 "The result of EXTRACT_VECTOR_ELT must be at least as wide as the \
8694 element type of the vector.");
8695
8696 // Extract from an undefined value or using an undefined index is undefined.
8697 if (N1.isUndef() || N2.isUndef())
8698 return getUNDEF(VT);
8699
8700 // EXTRACT_VECTOR_ELT of out-of-bounds element is POISON for fixed length
8701 // vectors. For scalable vectors we will provide appropriate support for
8702 // dealing with arbitrary indices.
8703 if (N2C && N1.getValueType().isFixedLengthVector() &&
8704 N2C->getAPIntValue().uge(N1.getValueType().getVectorNumElements()))
8705 return getPOISON(VT);
8706
8707 // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
8708 // expanding copies of large vectors from registers. This only works for
8709 // fixed length vectors, since we need to know the exact number of
8710 // elements.
8711 if (N2C && N1.getOpcode() == ISD::CONCAT_VECTORS &&
8713 unsigned Factor = N1.getOperand(0).getValueType().getVectorNumElements();
8714 return getExtractVectorElt(DL, VT,
8715 N1.getOperand(N2C->getZExtValue() / Factor),
8716 N2C->getZExtValue() % Factor);
8717 }
8718
8719 // EXTRACT_VECTOR_ELT of BUILD_VECTOR or SPLAT_VECTOR is often formed while
8720 // lowering is expanding large vector constants.
8721 if (N2C && (N1.getOpcode() == ISD::BUILD_VECTOR ||
8722 N1.getOpcode() == ISD::SPLAT_VECTOR)) {
8725 "BUILD_VECTOR used for scalable vectors");
8726 unsigned Index =
8727 N1.getOpcode() == ISD::BUILD_VECTOR ? N2C->getZExtValue() : 0;
8728 SDValue Elt = N1.getOperand(Index);
8729
8730 if (VT != Elt.getValueType())
8731 // If the vector element type is not legal, the BUILD_VECTOR operands
8732 // are promoted and implicitly truncated, and the result implicitly
8733 // extended. Make that explicit here.
8734 Elt = getAnyExtOrTrunc(Elt, DL, VT);
8735
8736 return Elt;
8737 }
8738
8739 // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
8740 // operations are lowered to scalars.
8741 if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) {
8742 // If the indices are the same, return the inserted element else
8743 // if the indices are known different, extract the element from
8744 // the original vector.
8745 SDValue N1Op2 = N1.getOperand(2);
8747
8748 if (N1Op2C && N2C) {
8749 if (N1Op2C->getZExtValue() == N2C->getZExtValue()) {
8750 if (VT == N1.getOperand(1).getValueType())
8751 return N1.getOperand(1);
8752 if (VT.isFloatingPoint()) {
8754 return getFPExtendOrRound(N1.getOperand(1), DL, VT);
8755 }
8756 return getSExtOrTrunc(N1.getOperand(1), DL, VT);
8757 }
8758 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2);
8759 }
8760 }
8761
8762 // EXTRACT_VECTOR_ELT of v1iX EXTRACT_SUBVECTOR could be formed
8763 // when vector types are scalarized and v1iX is legal.
8764 // vextract (v1iX extract_subvector(vNiX, Idx)) -> vextract(vNiX,Idx).
8765 // Here we are completely ignoring the extract element index (N2),
8766 // which is fine for fixed width vectors, since any index other than 0
8767 // is undefined anyway. However, this cannot be ignored for scalable
8768 // vectors - in theory we could support this, but we don't want to do this
8769 // without a profitability check.
8770 if (N1.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
8772 N1.getValueType().getVectorNumElements() == 1) {
8773 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0),
8774 N1.getOperand(1));
8775 }
8776 break;
8778 assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!");
8779 assert(!N1.getValueType().isVector() && !VT.isVector() &&
8780 (N1.getValueType().isInteger() == VT.isInteger()) &&
8781 N1.getValueType() != VT &&
8782 "Wrong types for EXTRACT_ELEMENT!");
8783
8784 // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
8785 // 64-bit integers into 32-bit parts. Instead of building the extract of
8786 // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
8787 if (N1.getOpcode() == ISD::BUILD_PAIR)
8788 return N1.getOperand(N2C->getZExtValue());
8789
8790 // EXTRACT_ELEMENT of a constant int is also very common.
8791 if (N1C) {
8792 unsigned ElementSize = VT.getSizeInBits();
8793 unsigned Shift = ElementSize * N2C->getZExtValue();
8794 const APInt &Val = N1C->getAPIntValue();
8795 return getConstant(Val.extractBits(ElementSize, Shift), DL, VT);
8796 }
8797 break;
8799 EVT N1VT = N1.getValueType();
8800 assert(VT.isVector() && N1VT.isVector() &&
8801 "Extract subvector VTs must be vectors!");
8803 "Extract subvector VTs must have the same element type!");
8804 assert((VT.isFixedLengthVector() || N1VT.isScalableVector()) &&
8805 "Cannot extract a scalable vector from a fixed length vector!");
8806 assert((VT.isScalableVector() != N1VT.isScalableVector() ||
8808 "Extract subvector must be from larger vector to smaller vector!");
8809 assert(N2C && "Extract subvector index must be a constant");
8810 assert((VT.isScalableVector() != N1VT.isScalableVector() ||
8811 (VT.getVectorMinNumElements() + N2C->getZExtValue()) <=
8812 N1VT.getVectorMinNumElements()) &&
8813 "Extract subvector overflow!");
8814 assert(N2C->getAPIntValue().getBitWidth() ==
8815 TLI->getVectorIdxWidth(getDataLayout()) &&
8816 "Constant index for EXTRACT_SUBVECTOR has an invalid size");
8817 assert(N2C->getZExtValue() % VT.getVectorMinNumElements() == 0 &&
8818 "Extract index is not a multiple of the output vector length");
8819
8820 // Trivial extraction.
8821 if (VT == N1VT)
8822 return N1;
8823
8824 // EXTRACT_SUBVECTOR of an UNDEF is an UNDEF.
8825 if (N1.isUndef())
8826 return getUNDEF(VT);
8827
8828 // EXTRACT_SUBVECTOR of CONCAT_VECTOR can be simplified if the pieces of
8829 // the concat have the same type as the extract.
8830 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
8831 VT == N1.getOperand(0).getValueType()) {
8832 unsigned Factor = VT.getVectorMinNumElements();
8833 return N1.getOperand(N2C->getZExtValue() / Factor);
8834 }
8835
8836 // EXTRACT_SUBVECTOR of INSERT_SUBVECTOR is often created
8837 // during shuffle legalization.
8838 if (N1.getOpcode() == ISD::INSERT_SUBVECTOR && N2 == N1.getOperand(2) &&
8839 VT == N1.getOperand(1).getValueType())
8840 return N1.getOperand(1);
8841 break;
8842 }
8843 }
8844
8845 if (N1.getOpcode() == ISD::POISON || N2.getOpcode() == ISD::POISON) {
8846 switch (Opcode) {
8847 case ISD::XOR:
8848 case ISD::ADD:
8849 case ISD::PTRADD:
8850 case ISD::SUB:
8852 case ISD::UDIV:
8853 case ISD::SDIV:
8854 case ISD::UREM:
8855 case ISD::SREM:
8856 case ISD::MUL:
8857 case ISD::AND:
8858 case ISD::SSUBSAT:
8859 case ISD::USUBSAT:
8860 case ISD::UMIN:
8861 case ISD::OR:
8862 case ISD::SADDSAT:
8863 case ISD::UADDSAT:
8864 case ISD::UMAX:
8865 case ISD::SMAX:
8866 case ISD::SMIN:
8867 // fold op(arg1, poison) -> poison, fold op(poison, arg2) -> poison.
8868 return N2.getOpcode() == ISD::POISON ? N2 : N1;
8869 }
8870 }
8871
8872 // Canonicalize an UNDEF to the RHS, even over a constant.
8873 if (N1.getOpcode() == ISD::UNDEF && N2.getOpcode() != ISD::UNDEF) {
8874 if (TLI->isCommutativeBinOp(Opcode)) {
8875 std::swap(N1, N2);
8876 } else {
8877 switch (Opcode) {
8878 case ISD::PTRADD:
8879 case ISD::SUB:
8880 // fold op(undef, non_undef_arg2) -> undef.
8881 return N1;
8883 case ISD::UDIV:
8884 case ISD::SDIV:
8885 case ISD::UREM:
8886 case ISD::SREM:
8887 case ISD::SSUBSAT:
8888 case ISD::USUBSAT:
8889 // fold op(undef, non_undef_arg2) -> 0.
8890 return getConstant(0, DL, VT);
8891 }
8892 }
8893 }
8894
8895 // Fold a bunch of operators when the RHS is undef.
8896 if (N2.getOpcode() == ISD::UNDEF) {
8897 switch (Opcode) {
8898 case ISD::XOR:
8899 if (N1.getOpcode() == ISD::UNDEF)
8900 // Handle undef ^ undef -> 0 special case. This is a common
8901 // idiom (misuse).
8902 return getConstant(0, DL, VT);
8903 [[fallthrough]];
8904 case ISD::ADD:
8905 case ISD::PTRADD:
8906 case ISD::SUB:
8907 // fold op(arg1, undef) -> undef.
8908 return N2;
8909 case ISD::UDIV:
8910 case ISD::SDIV:
8911 case ISD::UREM:
8912 case ISD::SREM:
8913 // fold op(arg1, undef) -> poison.
8914 return getPOISON(VT);
8915 case ISD::MUL:
8916 case ISD::AND:
8917 case ISD::SSUBSAT:
8918 case ISD::USUBSAT:
8919 case ISD::UMIN:
8920 // fold op(undef, undef) -> undef, fold op(arg1, undef) -> 0.
8921 return N1.getOpcode() == ISD::UNDEF ? N2 : getConstant(0, DL, VT);
8922 case ISD::OR:
8923 case ISD::SADDSAT:
8924 case ISD::UADDSAT:
8925 case ISD::UMAX:
8926 // fold op(undef, undef) -> undef, fold op(arg1, undef) -> -1.
8927 return N1.getOpcode() == ISD::UNDEF ? N2 : getAllOnesConstant(DL, VT);
8928 case ISD::SMAX:
8929 // fold op(undef, undef) -> undef, fold op(arg1, undef) -> MAX_INT.
8930 return N1.getOpcode() == ISD::UNDEF
8931 ? N2
8932 : getConstant(
8934 VT);
8935 case ISD::SMIN:
8936 // fold op(undef, undef) -> undef, fold op(arg1, undef) -> MIN_INT.
8937 return N1.getOpcode() == ISD::UNDEF
8938 ? N2
8939 : getConstant(
8941 VT);
8942 }
8943 }
8944
8945 // Perform trivial constant folding.
8946 if (SDValue SV = FoldConstantArithmetic(Opcode, DL, VT, {N1, N2}, Flags))
8947 return SV;
8948
8949 // Memoize this node if possible.
8950 SDNode *N;
8951 SDVTList VTs = getVTList(VT);
8952 SDValue Ops[] = {N1, N2};
8953 if (VT != MVT::Glue) {
8954 SDNodeKey ID(Opcode, VTs, Ops);
8955 FoldingSetInsertToken InsertToken;
8956 if (SDNode *E = lookupNode(ID, DL, InsertToken)) {
8957 E->intersectFlagsWith(Flags);
8958 return SDValue(E, 0);
8959 }
8960
8961 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
8962 N->setFlags(Flags);
8963 createOperands(N, Ops);
8964 CSEMap.insert(N, InsertToken);
8965 } else {
8966 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
8967 createOperands(N, Ops);
8968 }
8969
8970 InsertNode(N);
8971 SDValue V = SDValue(N, 0);
8972 NewSDValueDbgMsg(V, "Creating new node: ", this);
8973 return V;
8974}
8975
8976SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8977 SDValue N1, SDValue N2, SDValue N3) {
8978 SDNodeFlags Flags;
8979 if (Inserter)
8980 Flags = Inserter->getFlags();
8981 return getNode(Opcode, DL, VT, N1, N2, N3, Flags);
8982}
8983
8984SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8985 SDValue N1, SDValue N2, SDValue N3,
8986 const SDNodeFlags Flags) {
8988 N2.getOpcode() != ISD::DELETED_NODE &&
8989 N3.getOpcode() != ISD::DELETED_NODE &&
8990 "Operand is DELETED_NODE!");
8991 // Perform various simplifications.
8992 switch (Opcode) {
8993 case ISD::BUILD_VECTOR: {
8994 // Attempt to simplify BUILD_VECTOR.
8995 SDValue Ops[] = {N1, N2, N3};
8996 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
8997 return V;
8998 break;
8999 }
9000 case ISD::CONCAT_VECTORS: {
9001 SDValue Ops[] = {N1, N2, N3};
9002 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
9003 return V;
9004 break;
9005 }
9006 case ISD::SETCC: {
9007 assert(VT.isInteger() && "SETCC result type must be an integer!");
9008 assert(N1.getValueType() == N2.getValueType() &&
9009 "SETCC operands must have the same type!");
9010 assert(VT.isVector() == N1.getValueType().isVector() &&
9011 "SETCC type should be vector iff the operand type is vector!");
9012 assert((!VT.isVector() || VT.getVectorElementCount() ==
9014 "SETCC vector element counts must match!");
9015 // Use FoldSetCC to simplify SETCC's.
9016 if (SDValue V =
9017 FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL, Flags))
9018 return V;
9019 break;
9020 }
9021 case ISD::SELECT:
9022 case ISD::VSELECT:
9023 if (SDValue V = simplifySelect(N1, N2, N3))
9024 return V;
9025 break;
9027 llvm_unreachable("should use getVectorShuffle constructor!");
9029 if (isNullConstant(N3))
9030 return N1;
9031 break;
9033 if (isNullConstant(N3))
9034 return N2;
9035 break;
9037 assert(VT.isVector() && VT == N1.getValueType() &&
9038 "INSERT_VECTOR_ELT vector type mismatch");
9040 "INSERT_VECTOR_ELT scalar fp/int mismatch");
9041 assert((!VT.isFloatingPoint() ||
9042 VT.getVectorElementType() == N2.getValueType()) &&
9043 "INSERT_VECTOR_ELT fp scalar type mismatch");
9044 assert((!VT.isInteger() ||
9046 "INSERT_VECTOR_ELT int scalar size mismatch");
9047
9048 auto *N3C = dyn_cast<ConstantSDNode>(N3);
9049 // INSERT_VECTOR_ELT into out-of-bounds element is an UNDEF, except
9050 // for scalable vectors where we will generate appropriate code to
9051 // deal with out-of-bounds cases correctly.
9052 if (N3C && VT.isFixedLengthVector() &&
9053 N3C->getZExtValue() >= VT.getVectorNumElements())
9054 return getUNDEF(VT);
9055
9056 // Undefined index can be assumed out-of-bounds, so that's UNDEF too.
9057 if (N3.isUndef())
9058 return getUNDEF(VT);
9059
9060 // If inserting poison, just use the input vector.
9061 if (N2.getOpcode() == ISD::POISON)
9062 return N1;
9063
9064 // Inserting undef into undef/poison is still undef.
9065 if (N2.getOpcode() == ISD::UNDEF && N1.isUndef())
9066 return getUNDEF(VT);
9067
9068 // If the inserted element is an UNDEF, just use the input vector.
9069 // But not if skipping the insert could make the result more poisonous.
9070 if (N2.isUndef()) {
9071 if (N3C && VT.isFixedLengthVector()) {
9072 APInt EltMask =
9073 APInt::getOneBitSet(VT.getVectorNumElements(), N3C->getZExtValue());
9074 if (isGuaranteedNotToBePoison(N1, EltMask))
9075 return N1;
9076 } else if (isGuaranteedNotToBePoison(N1))
9077 return N1;
9078 }
9079 break;
9080 }
9081 case ISD::INSERT_SUBVECTOR: {
9082 // If inserting poison, just use the input vector,
9083 if (N2.getOpcode() == ISD::POISON)
9084 return N1;
9085
9086 // Inserting undef into undef/poison is still undef.
9087 if (N2.getOpcode() == ISD::UNDEF && N1.isUndef())
9088 return getUNDEF(VT);
9089
9090 EVT N2VT = N2.getValueType();
9091 assert(VT == N1.getValueType() &&
9092 "Dest and insert subvector source types must match!");
9093 assert(VT.isVector() && N2VT.isVector() &&
9094 "Insert subvector VTs must be vectors!");
9096 "Insert subvector VTs must have the same element type!");
9097 assert((VT.isScalableVector() || N2VT.isFixedLengthVector()) &&
9098 "Cannot insert a scalable vector into a fixed length vector!");
9099 assert((VT.isScalableVector() != N2VT.isScalableVector() ||
9101 "Insert subvector must be from smaller vector to larger vector!");
9103 "Insert subvector index must be constant");
9104 assert((VT.isScalableVector() != N2VT.isScalableVector() ||
9105 (N2VT.getVectorMinNumElements() + N3->getAsZExtVal()) <=
9107 "Insert subvector overflow!");
9109 TLI->getVectorIdxWidth(getDataLayout()) &&
9110 "Constant index for INSERT_SUBVECTOR has an invalid size");
9111
9112 // Trivial insertion.
9113 if (VT == N2VT)
9114 return N2;
9115
9116 // If this is an insert of an extracted vector into an undef/poison vector,
9117 // we can just use the input to the extract. But not if skipping the
9118 // extract+insert could make the result more poisonous.
9119 if (N1.isUndef() && N2.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
9120 N2.getOperand(1) == N3 && N2.getOperand(0).getValueType() == VT) {
9121 if (N1.getOpcode() == ISD::POISON)
9122 return N2.getOperand(0);
9123 if (VT.isFixedLengthVector() && N2VT.isFixedLengthVector()) {
9124 unsigned LoBit = N3->getAsZExtVal();
9125 unsigned HiBit = LoBit + N2VT.getVectorNumElements();
9126 APInt EltMask =
9127 APInt::getBitsSet(VT.getVectorNumElements(), LoBit, HiBit);
9128 if (isGuaranteedNotToBePoison(N2.getOperand(0), ~EltMask))
9129 return N2.getOperand(0);
9130 } else if (isGuaranteedNotToBePoison(N2.getOperand(0)))
9131 return N2.getOperand(0);
9132 }
9133
9134 // If the inserted subvector is UNDEF, just use the input vector.
9135 // But not if skipping the insert could make the result more poisonous.
9136 if (N2.isUndef()) {
9137 if (VT.isFixedLengthVector()) {
9138 unsigned LoBit = N3->getAsZExtVal();
9139 unsigned HiBit = LoBit + N2VT.getVectorNumElements();
9140 APInt EltMask =
9141 APInt::getBitsSet(VT.getVectorNumElements(), LoBit, HiBit);
9142 if (isGuaranteedNotToBePoison(N1, EltMask))
9143 return N1;
9144 } else if (isGuaranteedNotToBePoison(N1))
9145 return N1;
9146 }
9147 break;
9148 }
9149 case ISD::BITCAST:
9150 // Fold bit_convert nodes from a type to themselves.
9151 if (N1.getValueType() == VT)
9152 return N1;
9153 break;
9154 case ISD::VECTOR_COMPRESS: {
9155 [[maybe_unused]] EVT VecVT = N1.getValueType();
9156 [[maybe_unused]] EVT MaskVT = N2.getValueType();
9157 [[maybe_unused]] EVT PassthruVT = N3.getValueType();
9158 assert(VT == VecVT && "Vector and result type don't match.");
9159 assert(VecVT.isVector() && MaskVT.isVector() && PassthruVT.isVector() &&
9160 "All inputs must be vectors.");
9161 assert(VecVT == PassthruVT && "Vector and passthru types don't match.");
9163 "Vector and mask must have same number of elements.");
9164
9165 if (N1.isUndef() || N2.isUndef())
9166 return N3;
9167
9168 break;
9169 }
9174 [[maybe_unused]] EVT AccVT = N1.getValueType();
9175 [[maybe_unused]] EVT Input1VT = N2.getValueType();
9176 [[maybe_unused]] EVT Input2VT = N3.getValueType();
9177 assert(Input1VT.isVector() && Input1VT == Input2VT &&
9178 "Expected the second and third operands of the PARTIAL_REDUCE_MLA "
9179 "node to have the same type!");
9180 assert(VT.isVector() && VT == AccVT &&
9181 "Expected the first operand of the PARTIAL_REDUCE_MLA node to have "
9182 "the same type as its result!");
9184 AccVT.getVectorElementCount()) &&
9185 "Expected the element count of the second and third operands of the "
9186 "PARTIAL_REDUCE_MLA node to be a positive integer multiple of the "
9187 "element count of the first operand and the result!");
9189 "Expected the second and third operands of the PARTIAL_REDUCE_MLA "
9190 "node to have an element type which is the same as or smaller than "
9191 "the element type of the first operand and result!");
9192 break;
9193 }
9194 }
9195
9196 // Perform trivial constant folding for arithmetic operators.
9197 switch (Opcode) {
9201 case ISD::FMA:
9202 case ISD::FMAD:
9203 case ISD::SETCC:
9204 case ISD::FSHL:
9205 case ISD::FSHR:
9206 if (SDValue SV =
9207 FoldConstantArithmetic(Opcode, DL, VT, {N1, N2, N3}, Flags))
9208 return SV;
9209 break;
9210 }
9211
9212 // Memoize node if it doesn't produce a glue result.
9213 SDNode *N;
9214 SDVTList VTs = getVTList(VT);
9215 SDValue Ops[] = {N1, N2, N3};
9216 if (VT != MVT::Glue) {
9217 SDNodeKey ID(Opcode, VTs, Ops);
9218 FoldingSetInsertToken InsertToken;
9219 if (SDNode *E = lookupNode(ID, DL, InsertToken)) {
9220 E->intersectFlagsWith(Flags);
9221 return SDValue(E, 0);
9222 }
9223
9224 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
9225 N->setFlags(Flags);
9226 createOperands(N, Ops);
9227 CSEMap.insert(N, InsertToken);
9228 } else {
9229 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
9230 createOperands(N, Ops);
9231 }
9232
9233 InsertNode(N);
9234 SDValue V = SDValue(N, 0);
9235 NewSDValueDbgMsg(V, "Creating new node: ", this);
9236 return V;
9237}
9238
9239SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
9240 SDValue N1, SDValue N2, SDValue N3, SDValue N4,
9241 const SDNodeFlags Flags) {
9242 SDValue Ops[] = { N1, N2, N3, N4 };
9243 return getNode(Opcode, DL, VT, Ops, Flags);
9244}
9245
9246SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
9247 SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
9248 SDNodeFlags Flags;
9249 if (Inserter)
9250 Flags = Inserter->getFlags();
9251 return getNode(Opcode, DL, VT, N1, N2, N3, N4, Flags);
9252}
9253
9254SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
9255 SDValue N1, SDValue N2, SDValue N3, SDValue N4,
9256 SDValue N5, const SDNodeFlags Flags) {
9257 SDValue Ops[] = { N1, N2, N3, N4, N5 };
9258 return getNode(Opcode, DL, VT, Ops, Flags);
9259}
9260
9261SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
9262 SDValue N1, SDValue N2, SDValue N3, SDValue N4,
9263 SDValue N5) {
9264 SDNodeFlags Flags;
9265 if (Inserter)
9266 Flags = Inserter->getFlags();
9267 return getNode(Opcode, DL, VT, N1, N2, N3, N4, N5, Flags);
9268}
9269
9270/// getStackArgumentTokenFactor - Compute a TokenFactor to force all
9271/// the incoming stack arguments to be loaded from the stack.
9273 SmallVector<SDValue, 8> ArgChains;
9274
9275 // Include the original chain at the beginning of the list. When this is
9276 // used by target LowerCall hooks, this helps legalize find the
9277 // CALLSEQ_BEGIN node.
9278 ArgChains.push_back(Chain);
9279
9280 // Add a chain value for each stack argument.
9281 for (SDNode *U : getEntryNode().getNode()->users())
9282 if (LoadSDNode *L = dyn_cast<LoadSDNode>(U))
9283 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
9284 if (FI->getIndex() < 0)
9285 ArgChains.push_back(SDValue(L, 1));
9286
9287 // Build a tokenfactor for all the chains.
9288 return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
9289}
9290
9291/// getMemsetValue - Vectorized representation of the memset value
9292/// operand.
9294 const SDLoc &dl) {
9295 assert(!Value.isUndef());
9296
9297 unsigned NumBits = VT.getScalarSizeInBits();
9299 assert(C->getAPIntValue().getBitWidth() == 8);
9300 APInt Val = APInt::getSplat(NumBits, C->getAPIntValue());
9301 if (VT.isInteger()) {
9302 bool IsOpaque = VT.getSizeInBits() > 64 ||
9303 !DAG.getTargetLoweringInfo().isLegalStoreImmediate(C->getSExtValue());
9304 return DAG.getConstant(Val, dl, VT, false, IsOpaque);
9305 }
9306 return DAG.getConstantFP(APFloat(VT.getFltSemantics(), Val), dl, VT);
9307 }
9308
9309 assert(Value.getValueType() == MVT::i8 && "memset with non-byte fill value?");
9310 EVT IntVT = VT.getScalarType();
9311 if (!IntVT.isInteger())
9312 IntVT = EVT::getIntegerVT(*DAG.getContext(), IntVT.getSizeInBits());
9313
9314 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, Value);
9315 if (NumBits > 8) {
9316 // Use a multiplication with 0x010101... to extend the input to the
9317 // required length.
9318 APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01));
9319 Value = DAG.getNode(ISD::MUL, dl, IntVT, Value,
9320 DAG.getConstant(Magic, dl, IntVT));
9321 }
9322
9323 if (VT != Value.getValueType() && !VT.isInteger())
9324 Value = DAG.getBitcast(VT.getScalarType(), Value);
9325 if (VT != Value.getValueType())
9326 Value = DAG.getSplatBuildVector(VT, dl, Value);
9327
9328 return Value;
9329}
9330
9331/// getMemsetStringVal - Similar to getMemsetValue. Except this is only
9332/// used when a memcpy is turned into a memset when the source is a constant
9333/// string ptr.
9335 const TargetLowering &TLI,
9336 const ConstantDataArraySlice &Slice) {
9337 // Handle vector with all elements zero.
9338 if (Slice.Array == nullptr) {
9339 if (VT.isInteger())
9340 return DAG.getConstant(0, dl, VT);
9341 return DAG.getNode(ISD::BITCAST, dl, VT,
9342 DAG.getConstant(0, dl, VT.changeTypeToInteger()));
9343 }
9344
9345 assert(!VT.isVector() && "Can't handle vector type here!");
9346 unsigned NumVTBits = VT.getSizeInBits();
9347 unsigned NumVTBytes = NumVTBits / 8;
9348 unsigned NumBytes = std::min(NumVTBytes, unsigned(Slice.Length));
9349
9350 APInt Val(NumVTBits, 0);
9351 if (DAG.getDataLayout().isLittleEndian()) {
9352 for (unsigned i = 0; i != NumBytes; ++i)
9353 Val |= (uint64_t)(unsigned char)Slice[i] << i*8;
9354 } else {
9355 for (unsigned i = 0; i != NumBytes; ++i)
9356 Val |= (uint64_t)(unsigned char)Slice[i] << (NumVTBytes-i-1)*8;
9357 }
9358
9359 // If the "cost" of materializing the integer immediate is less than the cost
9360 // of a load, then it is cost effective to turn the load into the immediate.
9361 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
9362 if (TLI.shouldConvertConstantLoadToIntImm(Val, Ty))
9363 return DAG.getConstant(Val, dl, VT);
9364 return SDValue();
9365}
9366
9368 const SDLoc &DL,
9369 const SDNodeFlags Flags) {
9370 SDValue Index = getTypeSize(DL, Base.getValueType(), Offset);
9371 return getMemBasePlusOffset(Base, Index, DL, Flags);
9372}
9373
9375 const SDLoc &DL,
9376 const SDNodeFlags Flags) {
9377 assert(Offset.getValueType().isInteger());
9378 EVT BasePtrVT = Ptr.getValueType();
9379 if (TLI->shouldPreservePtrArith(this->getMachineFunction().getFunction(),
9380 BasePtrVT))
9381 return getNode(ISD::PTRADD, DL, BasePtrVT, Ptr, Offset, Flags);
9382 // InBounds only applies to PTRADD, don't set it if we generate ADD.
9383 SDNodeFlags AddFlags = Flags;
9384 AddFlags.setInBounds(false);
9385 return getNode(ISD::ADD, DL, BasePtrVT, Ptr, Offset, AddFlags);
9386}
9387
9388/// Returns true if memcpy source is constant data.
9390 uint64_t SrcDelta = 0;
9391 GlobalAddressSDNode *G = nullptr;
9392 if (Src.getOpcode() == ISD::GlobalAddress)
9394 else if (Src->isAnyAdd() &&
9395 Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
9396 Src.getOperand(1).getOpcode() == ISD::Constant) {
9397 G = cast<GlobalAddressSDNode>(Src.getOperand(0));
9398 SrcDelta = Src.getConstantOperandVal(1);
9399 }
9400 if (!G)
9401 return false;
9402
9403 return getConstantDataArrayInfo(G->getGlobal(), Slice, 8,
9404 SrcDelta + G->getOffset());
9405}
9406
9408 SelectionDAG &DAG) {
9409 // On Darwin, -Os means optimize for size without hurting performance, so
9410 // only really optimize for size when -Oz (MinSize) is used.
9412 return MF.getFunction().hasMinSize();
9413 return DAG.shouldOptForSize();
9414}
9415
9417 SmallVector<SDValue, 32> &OutChains, unsigned From,
9418 unsigned To, SmallVector<SDValue, 16> &OutLoadChains,
9419 SmallVector<SDValue, 16> &OutStoreChains) {
9420 assert(OutLoadChains.size() && "Missing loads in memcpy inlining");
9421 assert(OutStoreChains.size() && "Missing stores in memcpy inlining");
9422 SmallVector<SDValue, 16> GluedLoadChains;
9423 for (unsigned i = From; i < To; ++i) {
9424 OutChains.push_back(OutLoadChains[i]);
9425 GluedLoadChains.push_back(OutLoadChains[i]);
9426 }
9427
9428 // Chain for all loads.
9429 SDValue LoadToken = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
9430 GluedLoadChains);
9431
9432 for (unsigned i = From; i < To; ++i) {
9433 StoreSDNode *ST = dyn_cast<StoreSDNode>(OutStoreChains[i]);
9434 SDValue NewStore = DAG.getTruncStore(LoadToken, dl, ST->getValue(),
9435 ST->getBasePtr(), ST->getMemoryVT(),
9436 ST->getMemOperand());
9437 OutChains.push_back(NewStore);
9438 }
9439}
9440
9441static SDValue
9443 SDValue Dst, SDValue Src, uint64_t Size, Align DstAlign,
9444 Align SrcAlign, bool isVol, bool AlwaysInline,
9445 MachinePointerInfo DstPtrInfo,
9446 MachinePointerInfo SrcPtrInfo, const AAMDNodes &AAInfo,
9447 BatchAAResults *BatchAA, const MDNode *DstMemCacheHint,
9448 const MDNode *SrcMemCacheHint) {
9449 // Turn a memcpy of undef to nop.
9450 // FIXME: We need to honor volatile even is Src is undef.
9451 if (Src.isUndef())
9452 return Chain;
9453
9454 // Expand memcpy to a series of load and store ops if the size operand falls
9455 // below a certain threshold.
9456 // TODO: In the AlwaysInline case, if the size is big then generate a loop
9457 // rather than maybe a humongous number of loads and stores.
9458 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9459 const DataLayout &DL = DAG.getDataLayout();
9460 LLVMContext &C = *DAG.getContext();
9461 std::vector<EVT> MemOps;
9462 bool DstAlignCanChange = false;
9464 MachineFrameInfo &MFI = MF.getFrameInfo();
9465 bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
9467 if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
9468 DstAlignCanChange = true;
9469 SrcAlign = std::max(SrcAlign, DAG.InferPtrAlign(Src).valueOrOne());
9471 // If marked as volatile, perform a copy even when marked as constant.
9472 bool CopyFromConstant = !isVol && isMemSrcFromConstant(Src, Slice);
9473 bool isZeroConstant = CopyFromConstant && Slice.Array == nullptr;
9474 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize);
9475 const MemOp Op = isZeroConstant
9476 ? MemOp::Set(Size, DstAlignCanChange, DstAlign,
9477 /*IsZeroMemset*/ true, isVol)
9478 : MemOp::Copy(Size, DstAlignCanChange, DstAlign,
9479 SrcAlign, isVol, CopyFromConstant);
9480 if (!TLI.findOptimalMemOpLowering(
9481 C, MemOps, Limit, Op, DstPtrInfo.getAddrSpace(),
9482 SrcPtrInfo.getAddrSpace(), MF.getFunction().getAttributes(), nullptr))
9483 return SDValue();
9484
9485 if (DstAlignCanChange) {
9486 Type *Ty = MemOps[0].getTypeForEVT(C);
9487 Align NewDstAlign = DL.getABITypeAlign(Ty);
9488
9489 // Don't promote to an alignment that would require dynamic stack
9490 // realignment which may conflict with optimizations such as tail call
9491 // optimization.
9493 if (!TRI->hasStackRealignment(MF))
9494 if (MaybeAlign StackAlign = DL.getStackAlignment())
9495 NewDstAlign = std::min(NewDstAlign, *StackAlign);
9496
9497 if (NewDstAlign > DstAlign) {
9498 // Give the stack frame object a larger alignment if needed.
9499 if (MFI.getObjectAlign(FI->getIndex()) < NewDstAlign)
9500 MFI.setObjectAlignment(FI->getIndex(), NewDstAlign);
9501 DstAlign = NewDstAlign;
9502 }
9503 }
9504
9505 // Prepare AAInfo for loads/stores after lowering this memcpy.
9506 AAMDNodes NewAAInfo = AAInfo;
9507 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
9508
9509 const Value *SrcVal = dyn_cast_if_present<const Value *>(SrcPtrInfo.V);
9510 bool isConstant =
9511 BatchAA && SrcVal &&
9512 BatchAA->pointsToConstantMemory(MemoryLocation(SrcVal, Size, AAInfo));
9513
9514 MachineMemOperand::Flags MMOFlags =
9516 SmallVector<SDValue, 16> OutLoadChains;
9517 SmallVector<SDValue, 16> OutStoreChains;
9518 SmallVector<SDValue, 32> OutChains;
9519 unsigned NumMemOps = MemOps.size();
9520 uint64_t SrcOff = 0, DstOff = 0;
9521 for (unsigned i = 0; i != NumMemOps; ++i) {
9522 EVT VT = MemOps[i];
9523 unsigned VTSize = VT.getSizeInBits() / 8;
9525
9526 if (VTSize > Size) {
9527 // Issuing an unaligned load / store pair that overlaps with the previous
9528 // pair. Adjust the offset accordingly.
9529 assert(i == NumMemOps-1 && i != 0);
9530 SrcOff -= VTSize - Size;
9531 DstOff -= VTSize - Size;
9532 }
9533
9534 if (CopyFromConstant &&
9535 (isZeroConstant || (VT.isInteger() && !VT.isVector()))) {
9536 // It's unlikely a store of a vector immediate can be done in a single
9537 // instruction. It would require a load from a constantpool first.
9538 // We only handle zero vectors here.
9539 // FIXME: Handle other cases where store of vector immediate is done in
9540 // a single instruction.
9541 ConstantDataArraySlice SubSlice;
9542 if (SrcOff < Slice.Length) {
9543 SubSlice = Slice;
9544 SubSlice.move(SrcOff);
9545 } else {
9546 // This is an out-of-bounds access and hence UB. Pretend we read zero.
9547 SubSlice.Array = nullptr;
9548 SubSlice.Offset = 0;
9549 SubSlice.Length = VTSize;
9550 }
9551 Value = getMemsetStringVal(VT, dl, DAG, TLI, SubSlice);
9552 if (Value.getNode()) {
9553 Store = DAG.getStore(
9554 Chain, dl, Value,
9555 DAG.getObjectPtrOffset(dl, Dst, TypeSize::getFixed(DstOff)),
9556 DstPtrInfo.getWithOffset(DstOff), DstAlign, MMOFlags,
9557 MMOMetadata(NewAAInfo, /*Ranges=*/nullptr, DstMemCacheHint));
9558 OutChains.push_back(Store);
9559 }
9560 }
9561
9562 if (!Store.getNode()) {
9563 // The type might not be legal for the target. This should only happen
9564 // if the type is smaller than a legal type, as on PPC, so the right
9565 // thing to do is generate a LoadExt/StoreTrunc pair. These simplify
9566 // to Load/Store if NVT==VT.
9567 // FIXME does the case above also need this?
9568 EVT NVT = TLI.getTypeToTransformTo(C, VT);
9569 assert(NVT.bitsGE(VT));
9570
9571 bool isDereferenceable =
9572 SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
9573 MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
9574 if (isDereferenceable)
9576 if (isConstant)
9577 SrcMMOFlags |= MachineMemOperand::MOInvariant;
9578
9579 Value = DAG.getExtLoad(
9580 ISD::EXTLOAD, dl, NVT, Chain,
9581 DAG.getObjectPtrOffset(dl, Src, TypeSize::getFixed(SrcOff)),
9582 SrcPtrInfo.getWithOffset(SrcOff), VT,
9583 commonAlignment(SrcAlign, SrcOff), SrcMMOFlags,
9584 MMOMetadata(NewAAInfo, /*Ranges=*/nullptr, SrcMemCacheHint));
9585 OutLoadChains.push_back(Value.getValue(1));
9586
9587 Store = DAG.getTruncStore(
9588 Chain, dl, Value,
9589 DAG.getObjectPtrOffset(dl, Dst, TypeSize::getFixed(DstOff)),
9590 DstPtrInfo.getWithOffset(DstOff), VT, DstAlign, MMOFlags,
9591 MMOMetadata(NewAAInfo, /*Ranges=*/nullptr, DstMemCacheHint));
9592 OutStoreChains.push_back(Store);
9593 }
9594 SrcOff += VTSize;
9595 DstOff += VTSize;
9596 Size -= VTSize;
9597 }
9598
9599 unsigned GluedLdStLimit = MaxLdStGlue == 0 ?
9601 unsigned NumLdStInMemcpy = OutStoreChains.size();
9602
9603 if (NumLdStInMemcpy) {
9604 // It may be that memcpy might be converted to memset if it's memcpy
9605 // of constants. In such a case, we won't have loads and stores, but
9606 // just stores. In the absence of loads, there is nothing to gang up.
9607 if ((GluedLdStLimit <= 1) || !EnableMemCpyDAGOpt) {
9608 // If target does not care, just leave as it.
9609 for (unsigned i = 0; i < NumLdStInMemcpy; ++i) {
9610 OutChains.push_back(OutLoadChains[i]);
9611 OutChains.push_back(OutStoreChains[i]);
9612 }
9613 } else {
9614 // Ld/St less than/equal limit set by target.
9615 if (NumLdStInMemcpy <= GluedLdStLimit) {
9616 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
9617 NumLdStInMemcpy, OutLoadChains,
9618 OutStoreChains);
9619 } else {
9620 unsigned NumberLdChain = NumLdStInMemcpy / GluedLdStLimit;
9621 unsigned RemainingLdStInMemcpy = NumLdStInMemcpy % GluedLdStLimit;
9622 unsigned GlueIter = 0;
9623
9624 // Residual ld/st.
9625 if (RemainingLdStInMemcpy) {
9627 DAG, dl, OutChains, NumLdStInMemcpy - RemainingLdStInMemcpy,
9628 NumLdStInMemcpy, OutLoadChains, OutStoreChains);
9629 }
9630
9631 for (unsigned cnt = 0; cnt < NumberLdChain; ++cnt) {
9632 unsigned IndexFrom = NumLdStInMemcpy - RemainingLdStInMemcpy -
9633 GlueIter - GluedLdStLimit;
9634 unsigned IndexTo = NumLdStInMemcpy - RemainingLdStInMemcpy - GlueIter;
9635 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, IndexFrom, IndexTo,
9636 OutLoadChains, OutStoreChains);
9637 GlueIter += GluedLdStLimit;
9638 }
9639 }
9640 }
9641 }
9642 return DAG.getTokenFactor(dl, OutChains);
9643}
9644
9646 SelectionDAG &DAG, const SDLoc &dl, SDValue Chain, SDValue Dst, SDValue Src,
9647 uint64_t Size, Align DstAlign, Align SrcAlign, bool isVol,
9648 bool AlwaysInline, MachinePointerInfo DstPtrInfo,
9649 MachinePointerInfo SrcPtrInfo, const AAMDNodes &AAInfo) {
9650 // Turn a memmove of undef to nop.
9651 // FIXME: We need to honor volatile even is Src is undef.
9652 if (Src.isUndef())
9653 return Chain;
9654
9655 // Expand memmove to a series of load and store ops if the size operand falls
9656 // below a certain threshold.
9657 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9658 const DataLayout &DL = DAG.getDataLayout();
9659 LLVMContext &C = *DAG.getContext();
9660 std::vector<EVT> MemOps;
9661 bool DstAlignCanChange = false;
9663 MachineFrameInfo &MFI = MF.getFrameInfo();
9664 bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
9666 if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
9667 DstAlignCanChange = true;
9668 SrcAlign = std::max(SrcAlign, DAG.InferPtrAlign(Src).valueOrOne());
9669 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize);
9670 if (!TLI.findOptimalMemOpLowering(
9671 C, MemOps, Limit,
9672 MemOp::Move(Size, DstAlignCanChange, DstAlign, SrcAlign, isVol),
9673 DstPtrInfo.getAddrSpace(), SrcPtrInfo.getAddrSpace(),
9674 MF.getFunction().getAttributes(), nullptr))
9675 return SDValue();
9676
9677 if (DstAlignCanChange) {
9678 Type *Ty = MemOps[0].getTypeForEVT(C);
9679 Align NewDstAlign = DL.getABITypeAlign(Ty);
9680
9681 // Don't promote to an alignment that would require dynamic stack
9682 // realignment which may conflict with optimizations such as tail call
9683 // optimization.
9685 if (!TRI->hasStackRealignment(MF))
9686 if (MaybeAlign StackAlign = DL.getStackAlignment())
9687 NewDstAlign = std::min(NewDstAlign, *StackAlign);
9688
9689 if (NewDstAlign > DstAlign) {
9690 // Give the stack frame object a larger alignment if needed.
9691 if (MFI.getObjectAlign(FI->getIndex()) < NewDstAlign)
9692 MFI.setObjectAlignment(FI->getIndex(), NewDstAlign);
9693 DstAlign = NewDstAlign;
9694 }
9695 }
9696
9697 // Prepare AAInfo for loads/stores after lowering this memmove.
9698 AAMDNodes NewAAInfo = AAInfo;
9699 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
9700
9701 MachineMemOperand::Flags MMOFlags =
9703 uint64_t SrcOff = 0;
9704 SmallVector<SDValue, 8> LoadValues;
9705 SmallVector<SDValue, 8> LoadChains;
9706 SmallVector<SDValue, 8> OutChains;
9707 unsigned NumMemOps = MemOps.size();
9708 for (unsigned i = 0; i < NumMemOps; i++) {
9709 EVT VT = MemOps[i];
9710 unsigned VTSize = VT.getSizeInBits() / 8;
9711 SDValue Value;
9712 bool IsOverlapping = false;
9713
9714 if (i == NumMemOps - 1 && i != 0 && VTSize > Size - SrcOff) {
9715 // Issuing an unaligned load / store pair that overlaps with the previous
9716 // pair. Adjust the offset accordingly.
9717 SrcOff = Size - VTSize;
9718 IsOverlapping = true;
9719 }
9720
9721 // Calculate the actual alignment at the current offset. The alignment at
9722 // SrcOff may be lower than the base alignment, especially when using
9723 // overlapping loads.
9724 Align SrcAlignAtOffset = commonAlignment(SrcAlign, SrcOff);
9725 if (IsOverlapping) {
9726 // Verify that the target allows misaligned memory accesses at the
9727 // adjusted offset when using overlapping loads.
9728 unsigned Fast;
9729 if (!TLI.allowsMisalignedMemoryAccesses(VT, SrcPtrInfo.getAddrSpace(),
9730 SrcAlignAtOffset, MMOFlags,
9731 &Fast) ||
9732 !Fast) {
9733 // This should have been caught by findOptimalMemOpLowering, but verify
9734 // here for safety.
9735 return SDValue();
9736 }
9737 }
9738
9739 bool isDereferenceable =
9740 SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
9741 MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
9742 if (isDereferenceable)
9744 Value =
9745 DAG.getLoad(VT, dl, Chain,
9746 DAG.getObjectPtrOffset(dl, Src, TypeSize::getFixed(SrcOff)),
9747 SrcPtrInfo.getWithOffset(SrcOff), SrcAlignAtOffset,
9748 SrcMMOFlags, NewAAInfo);
9749 LoadValues.push_back(Value);
9750 LoadChains.push_back(Value.getValue(1));
9751 SrcOff += VTSize;
9752 }
9753 Chain = DAG.getTokenFactor(dl, LoadChains);
9754 OutChains.clear();
9755 uint64_t DstOff = 0;
9756 for (unsigned i = 0; i < NumMemOps; i++) {
9757 EVT VT = MemOps[i];
9758 unsigned VTSize = VT.getSizeInBits() / 8;
9759 SDValue Store;
9760 bool IsOverlapping = false;
9761
9762 if (i == NumMemOps - 1 && i != 0 && VTSize > Size - DstOff) {
9763 // Issuing an unaligned load / store pair that overlaps with the previous
9764 // pair. Adjust the offset accordingly.
9765 DstOff = Size - VTSize;
9766 IsOverlapping = true;
9767 }
9768
9769 // Calculate the actual alignment at the current offset. The alignment at
9770 // DstOff may be lower than the base alignment, especially when using
9771 // overlapping stores.
9772 Align DstAlignAtOffset = commonAlignment(DstAlign, DstOff);
9773 if (IsOverlapping) {
9774 // Verify that the target allows misaligned memory accesses at the
9775 // adjusted offset when using overlapping stores.
9776 unsigned Fast;
9777 if (!TLI.allowsMisalignedMemoryAccesses(VT, DstPtrInfo.getAddrSpace(),
9778 DstAlignAtOffset, MMOFlags,
9779 &Fast) ||
9780 !Fast) {
9781 // This should have been caught by findOptimalMemOpLowering, but verify
9782 // here for safety.
9783 return SDValue();
9784 }
9785 }
9786 Store = DAG.getStore(
9787 Chain, dl, LoadValues[i],
9788 DAG.getObjectPtrOffset(dl, Dst, TypeSize::getFixed(DstOff)),
9789 DstPtrInfo.getWithOffset(DstOff), DstAlignAtOffset, MMOFlags,
9790 NewAAInfo);
9791 OutChains.push_back(Store);
9792 DstOff += VTSize;
9793 }
9794
9795 return DAG.getTokenFactor(dl, OutChains);
9796}
9797
9798/// Lower the call to 'memset' intrinsic function into a series of store
9799/// operations.
9800///
9801/// \param DAG Selection DAG where lowered code is placed.
9802/// \param dl Link to corresponding IR location.
9803/// \param Chain Control flow dependency.
9804/// \param Dst Pointer to destination memory location.
9805/// \param Src Value of byte to write into the memory.
9806/// \param Size Number of bytes to write.
9807/// \param Alignment Alignment of the destination in bytes.
9808/// \param isVol True if destination is volatile.
9809/// \param AlwaysInline Makes sure no function call is generated.
9810/// \param DstPtrInfo IR information on the memory pointer.
9811/// \returns New head in the control flow, if lowering was successful, empty
9812/// SDValue otherwise.
9813///
9814/// The function tries to replace 'llvm.memset' intrinsic with several store
9815/// operations and value calculation code. This is usually profitable for small
9816/// memory size or when the semantic requires inlining.
9818 SDValue Chain, SDValue Dst, SDValue Src,
9819 uint64_t Size, Align Alignment, bool isVol,
9820 bool AlwaysInline, MachinePointerInfo DstPtrInfo,
9821 const AAMDNodes &AAInfo) {
9822 // Turn a memset of undef to nop.
9823 // FIXME: We need to honor volatile even is Src is undef.
9824 if (Src.isUndef())
9825 return Chain;
9826
9827 // Expand memset to a series of load/store ops if the size operand
9828 // falls below a certain threshold.
9829 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9830 std::vector<EVT> MemOps;
9831 bool DstAlignCanChange = false;
9832 LLVMContext &C = *DAG.getContext();
9834 MachineFrameInfo &MFI = MF.getFrameInfo();
9835 bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
9837 if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
9838 DstAlignCanChange = true;
9839 bool IsZeroVal = isNullConstant(Src);
9840 unsigned Limit = AlwaysInline ? ~0 : TLI.getMaxStoresPerMemset(OptSize);
9841
9842 EVT LargestVT;
9843 if (!TLI.findOptimalMemOpLowering(
9844 C, MemOps, Limit,
9845 MemOp::Set(Size, DstAlignCanChange, Alignment, IsZeroVal, isVol),
9846 DstPtrInfo.getAddrSpace(), ~0u, MF.getFunction().getAttributes(),
9847 &LargestVT))
9848 return SDValue();
9849
9850 if (DstAlignCanChange) {
9851 Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
9852 const DataLayout &DL = DAG.getDataLayout();
9853 Align NewAlign = DL.getABITypeAlign(Ty);
9854
9855 // Don't promote to an alignment that would require dynamic stack
9856 // realignment which may conflict with optimizations such as tail call
9857 // optimization.
9859 if (!TRI->hasStackRealignment(MF))
9860 if (MaybeAlign StackAlign = DL.getStackAlignment())
9861 NewAlign = std::min(NewAlign, *StackAlign);
9862
9863 if (NewAlign > Alignment) {
9864 // Give the stack frame object a larger alignment if needed.
9865 if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
9866 MFI.setObjectAlignment(FI->getIndex(), NewAlign);
9867 Alignment = NewAlign;
9868 }
9869 }
9870
9871 SmallVector<SDValue, 8> OutChains;
9872 uint64_t DstOff = 0;
9873 unsigned NumMemOps = MemOps.size();
9874
9875 // Find the largest store and generate the bit pattern for it.
9876 // If target didn't set LargestVT, compute it from MemOps.
9877 if (!LargestVT.isSimple()) {
9878 LargestVT = MemOps[0];
9879 for (unsigned i = 1; i < NumMemOps; i++)
9880 if (MemOps[i].bitsGT(LargestVT))
9881 LargestVT = MemOps[i];
9882 }
9883 SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl);
9884
9885 // Prepare AAInfo for loads/stores after lowering this memset.
9886 AAMDNodes NewAAInfo = AAInfo;
9887 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
9888
9889 for (unsigned i = 0; i < NumMemOps; i++) {
9890 EVT VT = MemOps[i];
9891 unsigned VTSize = VT.getSizeInBits() / 8;
9892 // The target should specify store types that exactly cover the memset size
9893 // (with the last store potentially being oversized for overlapping stores).
9894 assert(Size > 0 && "Target specified more stores than needed in "
9895 "findOptimalMemOpLowering");
9896 if (VTSize > Size) {
9897 // Issuing an unaligned load / store pair that overlaps with the previous
9898 // pair. Adjust the offset accordingly.
9899 assert(i == NumMemOps-1 && i != 0);
9900 DstOff -= VTSize - Size;
9901 }
9902
9903 // If this store is smaller than the largest store see whether we can get
9904 // the smaller value for free with a truncate or extract vector element and
9905 // then store.
9906 SDValue Value = MemSetValue;
9907 if (VT.bitsLT(LargestVT)) {
9908 unsigned Index;
9909 unsigned NElts = LargestVT.getSizeInBits() / VT.getSizeInBits();
9910 EVT SVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), NElts);
9911 if (!LargestVT.isVector() && !VT.isVector() &&
9912 TLI.isTruncateFree(LargestVT, VT))
9913 Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue);
9914 else if (LargestVT.isVector() && !VT.isVector() &&
9916 LargestVT.getTypeForEVT(*DAG.getContext()),
9917 VT.getSizeInBits(), Index) &&
9918 TLI.isTypeLegal(SVT) &&
9919 LargestVT.getSizeInBits() == SVT.getSizeInBits()) {
9920 // Target which can combine store(extractelement VectorTy, Idx) can get
9921 // the smaller value for free.
9922 SDValue TailValue = DAG.getNode(ISD::BITCAST, dl, SVT, MemSetValue);
9923 Value = DAG.getExtractVectorElt(dl, VT, TailValue, Index);
9924 } else
9925 Value = getMemsetValue(Src, VT, DAG, dl);
9926 }
9927 assert(Value.getValueType() == VT && "Value with wrong type.");
9928 SDValue Store = DAG.getStore(
9929 Chain, dl, Value,
9930 DAG.getObjectPtrOffset(dl, Dst, TypeSize::getFixed(DstOff)),
9931 DstPtrInfo.getWithOffset(DstOff), Alignment,
9933 NewAAInfo);
9934 OutChains.push_back(Store);
9935 DstOff += VT.getSizeInBits() / 8;
9936 // For oversized overlapping stores, only subtract the remaining bytes.
9937 // For normal stores, subtract the full store size.
9938 if (VTSize > Size) {
9939 Size = 0;
9940 } else {
9941 Size -= VTSize;
9942 }
9943 }
9944
9945 // After processing all stores, Size should be exactly 0. Any remaining bytes
9946 // indicate a bug in the target's findOptimalMemOpLowering implementation.
9947 assert(Size == 0 && "Target's findOptimalMemOpLowering did not specify "
9948 "stores that exactly cover the memset size");
9949
9950 return DAG.getTokenFactor(dl, OutChains);
9951}
9952
9954 unsigned AS) {
9955 // Lowering memcpy / memset / memmove intrinsics to calls is only valid if all
9956 // pointer operands can be losslessly bitcasted to pointers of address space 0
9957 if (AS != 0 && !TLI->getTargetMachine().isNoopAddrSpaceCast(AS, 0)) {
9958 report_fatal_error("cannot lower memory intrinsic in address space " +
9959 Twine(AS));
9960 }
9961}
9962
9964 const SelectionDAG *SelDAG,
9965 bool AllowReturnsFirstArg) {
9966 if (!CI || !CI->isTailCall())
9967 return false;
9968 // TODO: Fix "returns-first-arg" determination so it doesn't depend on which
9969 // helper symbol we lower to.
9970 return isInTailCallPosition(*CI, SelDAG->getTarget(),
9971 AllowReturnsFirstArg &&
9973}
9974
9975static std::pair<SDValue, SDValue>
9978 const CallInst *CI, RTLIB::Libcall Call,
9979 SelectionDAG *DAG, const TargetLowering *TLI) {
9980 RTLIB::LibcallImpl LCImpl = DAG->getLibcalls().getLibcallImpl(Call);
9981
9982 if (LCImpl == RTLIB::Unsupported)
9983 return {};
9984
9986 bool IsTailCall =
9987 isInTailCallPositionWrapper(CI, DAG, /*AllowReturnsFirstArg=*/true) &&
9988 // Lowering doesn't support tail calling inside a function with
9989 // a swifterror argument yet.
9990 !DAG->hasSwiftErrorArg();
9991 SDValue Callee =
9992 DAG->getExternalSymbol(LCImpl, TLI->getPointerTy(DAG->getDataLayout()));
9993
9994 CLI.setDebugLoc(dl)
9995 .setChain(Chain)
9997 CI->getType(), Callee, std::move(Args))
9998 .setTailCall(IsTailCall);
9999
10000 return TLI->LowerCallTo(CLI);
10001}
10002
10003std::pair<SDValue, SDValue> SelectionDAG::getStrcmp(SDValue Chain,
10004 const SDLoc &dl, SDValue S1,
10005 SDValue S2,
10006 const CallInst *CI) {
10008 TargetLowering::ArgListTy Args = {{S1, PT}, {S2, PT}};
10009 return getRuntimeCallSDValueHelper(Chain, dl, std::move(Args), CI,
10010 RTLIB::STRCMP, this, TLI);
10011}
10012
10013std::pair<SDValue, SDValue> SelectionDAG::getStrstr(SDValue Chain,
10014 const SDLoc &dl, SDValue S1,
10015 SDValue S2,
10016 const CallInst *CI) {
10018 TargetLowering::ArgListTy Args = {{S1, PT}, {S2, PT}};
10019 return getRuntimeCallSDValueHelper(Chain, dl, std::move(Args), CI,
10020 RTLIB::STRSTR, this, TLI);
10021}
10022
10023std::pair<SDValue, SDValue> SelectionDAG::getMemccpy(SDValue Chain,
10024 const SDLoc &dl,
10025 SDValue Dst, SDValue Src,
10027 const CallInst *CI) {
10029
10031 {Dst, PT},
10032 {Src, PT},
10035 return getRuntimeCallSDValueHelper(Chain, dl, std::move(Args), CI,
10036 RTLIB::MEMCCPY, this, TLI);
10037}
10038
10039std::pair<SDValue, SDValue>
10041 SDValue Mem1, SDValue Size, const CallInst *CI) {
10044 {Mem0, PT},
10045 {Mem1, PT},
10047 return getRuntimeCallSDValueHelper(Chain, dl, std::move(Args), CI,
10048 RTLIB::MEMCMP, this, TLI);
10049}
10050
10051std::pair<SDValue, SDValue> SelectionDAG::getStrcpy(SDValue Chain,
10052 const SDLoc &dl,
10053 SDValue Dst, SDValue Src,
10054 const CallInst *CI) {
10056 TargetLowering::ArgListTy Args = {{Dst, PT}, {Src, PT}};
10057 return getRuntimeCallSDValueHelper(Chain, dl, std::move(Args), CI,
10058 RTLIB::STRCPY, this, TLI);
10059}
10060
10061std::pair<SDValue, SDValue> SelectionDAG::getStrlen(SDValue Chain,
10062 const SDLoc &dl,
10063 SDValue Src,
10064 const CallInst *CI) {
10065 // Emit a library call.
10068 return getRuntimeCallSDValueHelper(Chain, dl, std::move(Args), CI,
10069 RTLIB::STRLEN, this, TLI);
10070}
10071
10073 return TLI->supportSwiftError() &&
10074 MF->getFunction().getAttributes().hasAttrSomewhere(
10075 Attribute::SwiftError);
10076}
10077
10079 SDValue Chain, const SDLoc &dl, SDValue Dst, SDValue Src, SDValue Size,
10080 Align DstAlign, Align SrcAlign, bool isVol, bool AlwaysInline,
10081 const CallInst *CI, std::optional<bool> OverrideTailCall,
10082 MachinePointerInfo DstPtrInfo, MachinePointerInfo SrcPtrInfo,
10083 const AAMDNodes &AAInfo, BatchAAResults *BatchAA) {
10084 // Check to see if we should lower the memcpy to loads and stores first.
10085 // For cases within the target-specified limits, this is the best choice.
10086 const MDNode *DstMemCacheHint =
10087 CI ? getMemCacheHintMetadata(*CI, /*OperandNo=*/0) : nullptr;
10088 const MDNode *SrcMemCacheHint =
10089 CI ? getMemCacheHintMetadata(*CI, /*OperandNo=*/1) : nullptr;
10090
10092 if (ConstantSize) {
10093 // Memcpy with size zero? Just return the original chain.
10094 if (ConstantSize->isZero())
10095 return Chain;
10096
10098 *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), DstAlign,
10099 SrcAlign, isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo, BatchAA,
10100 DstMemCacheHint, SrcMemCacheHint);
10101 if (Result.getNode())
10102 return Result;
10103 }
10104
10105 // Then check to see if we should lower the memcpy with target-specific
10106 // code. If the target chooses to do this, this is the next best.
10107 if (TSI) {
10108 SDValue Result = TSI->EmitTargetCodeForMemcpy(
10109 *this, dl, Chain, Dst, Src, Size, DstAlign, SrcAlign, isVol,
10110 AlwaysInline, DstPtrInfo, SrcPtrInfo);
10111 if (Result.getNode())
10112 return Result;
10113 }
10114
10115 // If we really need inline code and the target declined to provide it,
10116 // use a (potentially long) sequence of loads and stores.
10117 if (AlwaysInline) {
10118 assert(ConstantSize && "AlwaysInline requires a constant size!");
10120 *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), DstAlign,
10121 SrcAlign, isVol, true, DstPtrInfo, SrcPtrInfo, AAInfo, BatchAA,
10122 DstMemCacheHint, SrcMemCacheHint);
10123 }
10124
10127
10128 // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc
10129 // memcpy is not guaranteed to be safe. libc memcpys aren't required to
10130 // respect volatile, so they may do things like read or write memory
10131 // beyond the given memory regions. But fixing this isn't easy, and most
10132 // people don't care.
10133
10134 // Emit a library call.
10137 Args.emplace_back(Dst, PtrTy);
10138 Args.emplace_back(Src, PtrTy);
10139 Args.emplace_back(Size, getDataLayout().getIntPtrType(*getContext()));
10140 // FIXME: pass in SDLoc
10142 bool IsTailCall = false;
10143 RTLIB::LibcallImpl MemCpyImpl = TLI->getMemcpyImpl();
10144
10145 if (OverrideTailCall.has_value()) {
10146 IsTailCall = *OverrideTailCall;
10147 } else {
10148 bool LowersToMemcpy = MemCpyImpl == RTLIB::impl_memcpy;
10149 IsTailCall = isInTailCallPositionWrapper(CI, this, LowersToMemcpy);
10150 }
10151 // Lowering doesn't support tail calling inside a function with a
10152 // swifterror argument yet.
10153 IsTailCall &= !hasSwiftErrorArg();
10154
10155 CLI.setDebugLoc(dl)
10156 .setChain(Chain)
10157 .setLibCallee(
10158 Libcalls->getLibcallImplCallingConv(MemCpyImpl),
10159 Dst.getValueType().getTypeForEVT(*getContext()),
10160 getExternalSymbol(MemCpyImpl, TLI->getPointerTy(getDataLayout())),
10161 std::move(Args))
10163 .setTailCall(IsTailCall);
10164
10165 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
10166 return CallResult.second;
10167}
10168
10170 SDValue Dst, SDValue Src, SDValue Size,
10171 Type *SizeTy, unsigned ElemSz,
10172 bool isTailCall,
10173 MachinePointerInfo DstPtrInfo,
10174 MachinePointerInfo SrcPtrInfo) {
10175 // Lowering doesn't support tail calling inside a function with a
10176 // swifterror argument yet.
10177 isTailCall &= !hasSwiftErrorArg();
10178
10179 // Emit a library call.
10182 Args.emplace_back(Dst, ArgTy);
10183 Args.emplace_back(Src, ArgTy);
10184 Args.emplace_back(Size, SizeTy);
10185
10186 RTLIB::Libcall LibraryCall =
10188 RTLIB::LibcallImpl LibcallImpl = Libcalls->getLibcallImpl(LibraryCall);
10189 if (LibcallImpl == RTLIB::Unsupported)
10190 report_fatal_error("Unsupported element size");
10191
10193 CLI.setDebugLoc(dl)
10194 .setChain(Chain)
10195 .setLibCallee(
10196 Libcalls->getLibcallImplCallingConv(LibcallImpl),
10198 getExternalSymbol(LibcallImpl, TLI->getPointerTy(getDataLayout())),
10199 std::move(Args))
10201 .setTailCall(isTailCall);
10202
10203 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
10204 return CallResult.second;
10205}
10206
10208 SDValue Src, SDValue Size, Align DstAlign,
10209 Align SrcAlign, bool isVol, const CallInst *CI,
10210 std::optional<bool> OverrideTailCall,
10211 MachinePointerInfo DstPtrInfo,
10212 MachinePointerInfo SrcPtrInfo,
10213 const AAMDNodes &AAInfo,
10214 BatchAAResults *BatchAA) {
10215 // Check to see if we should lower the memmove to loads and stores first.
10216 // For cases within the target-specified limits, this is the best choice.
10218 if (ConstantSize) {
10219 // Memmove with size zero? Just return the original chain.
10220 if (ConstantSize->isZero())
10221 return Chain;
10222
10224 *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), DstAlign,
10225 SrcAlign, isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo);
10226 if (Result.getNode())
10227 return Result;
10228 }
10229
10230 // Then check to see if we should lower the memmove with target-specific
10231 // code. If the target chooses to do this, this is the next best.
10232 if (TSI) {
10233 SDValue Result = TSI->EmitTargetCodeForMemmove(
10234 *this, dl, Chain, Dst, Src, Size, DstAlign, SrcAlign, isVol, DstPtrInfo,
10235 SrcPtrInfo);
10236 if (Result.getNode())
10237 return Result;
10238 }
10239
10242
10243 // FIXME: If the memmove is volatile, lowering it to plain libc memmove may
10244 // not be safe. See memcpy above for more details.
10245
10246 // Emit a library call.
10249 Args.emplace_back(Dst, PtrTy);
10250 Args.emplace_back(Src, PtrTy);
10251 Args.emplace_back(Size, getDataLayout().getIntPtrType(*getContext()));
10252 // FIXME: pass in SDLoc
10254
10255 RTLIB::LibcallImpl MemmoveImpl = Libcalls->getLibcallImpl(RTLIB::MEMMOVE);
10256
10257 bool IsTailCall = false;
10258 if (OverrideTailCall.has_value()) {
10259 IsTailCall = *OverrideTailCall;
10260 } else {
10261 bool LowersToMemmove = MemmoveImpl == RTLIB::impl_memmove;
10262 IsTailCall = isInTailCallPositionWrapper(CI, this, LowersToMemmove);
10263 }
10264 // Lowering doesn't support tail calling inside a function with a
10265 // swifterror argument yet.
10266 IsTailCall &= !hasSwiftErrorArg();
10267
10268 CLI.setDebugLoc(dl)
10269 .setChain(Chain)
10270 .setLibCallee(
10271 Libcalls->getLibcallImplCallingConv(MemmoveImpl),
10272 Dst.getValueType().getTypeForEVT(*getContext()),
10273 getExternalSymbol(MemmoveImpl, TLI->getPointerTy(getDataLayout())),
10274 std::move(Args))
10276 .setTailCall(IsTailCall);
10277
10278 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
10279 return CallResult.second;
10280}
10281
10283 SDValue Dst, SDValue Src, SDValue Size,
10284 Type *SizeTy, unsigned ElemSz,
10285 bool isTailCall,
10286 MachinePointerInfo DstPtrInfo,
10287 MachinePointerInfo SrcPtrInfo) {
10288 // Lowering doesn't support tail calling inside a function with a
10289 // swifterror argument yet.
10290 isTailCall &= !hasSwiftErrorArg();
10291
10292 // Emit a library call.
10295 Args.emplace_back(Dst, IntPtrTy);
10296 Args.emplace_back(Src, IntPtrTy);
10297 Args.emplace_back(Size, SizeTy);
10298
10299 RTLIB::Libcall LibraryCall =
10301 RTLIB::LibcallImpl LibcallImpl = Libcalls->getLibcallImpl(LibraryCall);
10302 if (LibcallImpl == RTLIB::Unsupported)
10303 report_fatal_error("Unsupported element size");
10304
10306 CLI.setDebugLoc(dl)
10307 .setChain(Chain)
10308 .setLibCallee(
10309 Libcalls->getLibcallImplCallingConv(LibcallImpl),
10311 getExternalSymbol(LibcallImpl, TLI->getPointerTy(getDataLayout())),
10312 std::move(Args))
10314 .setTailCall(isTailCall);
10315
10316 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
10317 return CallResult.second;
10318}
10319
10321 SDValue Src, SDValue Size, Align Alignment,
10322 bool isVol, bool AlwaysInline,
10323 const CallInst *CI,
10324 MachinePointerInfo DstPtrInfo,
10325 const AAMDNodes &AAInfo) {
10326 // Check to see if we should lower the memset to stores first.
10327 // For cases within the target-specified limits, this is the best choice.
10329 if (ConstantSize) {
10330 // Memset with size zero? Just return the original chain.
10331 if (ConstantSize->isZero())
10332 return Chain;
10333
10334 SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src,
10335 ConstantSize->getZExtValue(), Alignment,
10336 isVol, false, DstPtrInfo, AAInfo);
10337
10338 if (Result.getNode())
10339 return Result;
10340 }
10341
10342 // Then check to see if we should lower the memset with target-specific
10343 // code. If the target chooses to do this, this is the next best.
10344 if (TSI) {
10345 SDValue Result = TSI->EmitTargetCodeForMemset(
10346 *this, dl, Chain, Dst, Src, Size, Alignment, isVol, AlwaysInline, DstPtrInfo);
10347 if (Result.getNode())
10348 return Result;
10349 }
10350
10351 // If we really need inline code and the target declined to provide it,
10352 // use a (potentially long) sequence of loads and stores.
10353 if (AlwaysInline) {
10354 assert(ConstantSize && "AlwaysInline requires a constant size!");
10355 SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src,
10356 ConstantSize->getZExtValue(), Alignment,
10357 isVol, true, DstPtrInfo, AAInfo);
10358 assert(Result &&
10359 "getMemsetStores must return a valid sequence when AlwaysInline");
10360 return Result;
10361 }
10362
10364
10365 // Emit a library call.
10366 auto &Ctx = *getContext();
10367 const auto& DL = getDataLayout();
10368
10370 // FIXME: pass in SDLoc
10371 CLI.setDebugLoc(dl).setChain(Chain);
10372
10373 RTLIB::LibcallImpl BzeroImpl = Libcalls->getLibcallImpl(RTLIB::BZERO);
10374 bool UseBZero = BzeroImpl != RTLIB::Unsupported && isNullConstant(Src);
10375
10376 // If zeroing out and bzero is present, use it.
10377 if (UseBZero) {
10379 Args.emplace_back(Dst, PointerType::getUnqual(Ctx));
10380 Args.emplace_back(Size, DL.getIntPtrType(Ctx));
10381 CLI.setLibCallee(
10382 Libcalls->getLibcallImplCallingConv(BzeroImpl), Type::getVoidTy(Ctx),
10383 getExternalSymbol(BzeroImpl, TLI->getPointerTy(DL)), std::move(Args));
10384 } else {
10385 RTLIB::LibcallImpl MemsetImpl = Libcalls->getLibcallImpl(RTLIB::MEMSET);
10386
10388 Args.emplace_back(Dst, PointerType::getUnqual(Ctx));
10389 Args.emplace_back(Src, Src.getValueType().getTypeForEVT(Ctx));
10390 Args.emplace_back(Size, DL.getIntPtrType(Ctx));
10391 CLI.setLibCallee(Libcalls->getLibcallImplCallingConv(MemsetImpl),
10392 Dst.getValueType().getTypeForEVT(Ctx),
10393 getExternalSymbol(MemsetImpl, TLI->getPointerTy(DL)),
10394 std::move(Args));
10395 }
10396
10397 RTLIB::LibcallImpl MemsetImpl = Libcalls->getLibcallImpl(RTLIB::MEMSET);
10398 bool LowersToMemset = MemsetImpl == RTLIB::impl_memset;
10399
10400 // If we're going to use bzero, make sure not to tail call unless the
10401 // subsequent return doesn't need a value, as bzero doesn't return the first
10402 // arg unlike memset.
10403 bool ReturnsFirstArg = CI && funcReturnsFirstArgOfCall(*CI) && !UseBZero;
10404 bool IsTailCall = CI && CI->isTailCall() &&
10406 ReturnsFirstArg && LowersToMemset) &&
10407 // Lowering doesn't support tail calling inside a function
10408 // with a swifterror argument yet.
10410 CLI.setDiscardResult().setTailCall(IsTailCall);
10411
10412 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
10413 return CallResult.second;
10414}
10415
10418 Type *SizeTy, unsigned ElemSz,
10419 bool isTailCall,
10420 MachinePointerInfo DstPtrInfo) {
10421 // Lowering doesn't support tail calling inside a function with a
10422 // swifterror argument yet.
10423 isTailCall &= !hasSwiftErrorArg();
10424
10425 // Emit a library call.
10427 Args.emplace_back(Dst, getDataLayout().getIntPtrType(*getContext()));
10428 Args.emplace_back(Value, Type::getInt8Ty(*getContext()));
10429 Args.emplace_back(Size, SizeTy);
10430
10431 RTLIB::Libcall LibraryCall =
10433 RTLIB::LibcallImpl LibcallImpl = Libcalls->getLibcallImpl(LibraryCall);
10434 if (LibcallImpl == RTLIB::Unsupported)
10435 report_fatal_error("Unsupported element size");
10436
10438 CLI.setDebugLoc(dl)
10439 .setChain(Chain)
10440 .setLibCallee(
10441 Libcalls->getLibcallImplCallingConv(LibcallImpl),
10443 getExternalSymbol(LibcallImpl, TLI->getPointerTy(getDataLayout())),
10444 std::move(Args))
10446 .setTailCall(isTailCall);
10447
10448 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
10449 return CallResult.second;
10450}
10451
10452SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
10454 MachineMemOperand *MMO,
10455 ISD::LoadExtType ExtType) {
10456 SDNodeKey ID(Opcode, VTList, Ops);
10457 ID.AddInteger(MemVT.getRawBits());
10458 ID.AddInteger(getSyntheticNodeSubclassData<AtomicSDNode>(
10459 dl.getIROrder(), Opcode, VTList, MemVT, MMO, ExtType));
10460 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
10461 ID.AddInteger(MMO->getFlags());
10462 FoldingSetInsertToken InsertToken;
10463 if (auto *E = cast_or_null<AtomicSDNode>(lookupNode(ID, dl, InsertToken))) {
10464 E->refineAlignment(MMO);
10465 E->refineMMOMetadata(MMO);
10466 return SDValue(E, 0);
10467 }
10468
10469 auto *N = newSDNode<AtomicSDNode>(dl.getIROrder(), dl.getDebugLoc(), Opcode,
10470 VTList, MemVT, MMO, ExtType);
10471 createOperands(N, Ops);
10472
10473 CSEMap.insert(N, InsertToken);
10474 InsertNode(N);
10475 SDValue V(N, 0);
10476 NewSDValueDbgMsg(V, "Creating new node: ", this);
10477 return V;
10478}
10479
10481 EVT MemVT, SDVTList VTs, SDValue Chain,
10482 SDValue Ptr, SDValue Cmp, SDValue Swp,
10483 MachineMemOperand *MMO) {
10484 assert(Opcode == ISD::ATOMIC_CMP_SWAP ||
10486 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
10487
10488 SDValue Ops[] = {Chain, Ptr, Cmp, Swp};
10489 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
10490}
10491
10492SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
10493 SDValue Chain, SDValue Ptr, SDValue Val,
10494 MachineMemOperand *MMO) {
10495 assert((Opcode == ISD::ATOMIC_LOAD_ADD || Opcode == ISD::ATOMIC_LOAD_SUB ||
10496 Opcode == ISD::ATOMIC_LOAD_AND || Opcode == ISD::ATOMIC_LOAD_CLR ||
10497 Opcode == ISD::ATOMIC_LOAD_OR || Opcode == ISD::ATOMIC_LOAD_XOR ||
10498 Opcode == ISD::ATOMIC_LOAD_NAND || Opcode == ISD::ATOMIC_LOAD_MIN ||
10499 Opcode == ISD::ATOMIC_LOAD_MAX || Opcode == ISD::ATOMIC_LOAD_UMIN ||
10500 Opcode == ISD::ATOMIC_LOAD_UMAX || Opcode == ISD::ATOMIC_LOAD_FADD ||
10501 Opcode == ISD::ATOMIC_LOAD_FSUB || Opcode == ISD::ATOMIC_LOAD_FMAX ||
10502 Opcode == ISD::ATOMIC_LOAD_FMIN ||
10503 Opcode == ISD::ATOMIC_LOAD_FMINIMUM ||
10504 Opcode == ISD::ATOMIC_LOAD_FMAXIMUM ||
10505 Opcode == ISD::ATOMIC_LOAD_UINC_WRAP ||
10506 Opcode == ISD::ATOMIC_LOAD_UDEC_WRAP ||
10507 Opcode == ISD::ATOMIC_LOAD_USUB_COND ||
10508 Opcode == ISD::ATOMIC_LOAD_USUB_SAT || Opcode == ISD::ATOMIC_SWAP ||
10509 Opcode == ISD::ATOMIC_STORE) &&
10510 "Invalid Atomic Op");
10511
10512 EVT VT = Val.getValueType();
10513
10514 SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) :
10515 getVTList(VT, MVT::Other);
10516 SDValue Ops[] = {Chain, Ptr, Val};
10517 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
10518}
10519
10521 EVT MemVT, EVT VT, SDValue Chain,
10522 SDValue Ptr, MachineMemOperand *MMO) {
10523 SDVTList VTs = getVTList(VT, MVT::Other);
10524 SDValue Ops[] = {Chain, Ptr};
10525 return getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, VTs, Ops, MMO, ExtType);
10526}
10527
10528/// getMergeValues - Create a MERGE_VALUES node from the given operands.
10530 if (Ops.size() == 1)
10531 return Ops[0];
10532
10534 VTs.reserve(Ops.size());
10535 for (const SDValue &Op : Ops)
10536 VTs.push_back(Op.getValueType());
10537 return getNode(ISD::MERGE_VALUES, dl, getVTList(VTs), Ops);
10538}
10539
10541 SDValue Chain, const SDLoc &dl) {
10542 SmallVector<SDValue, 4> RetValues;
10543 RetValues.reserve(ResultTypes.size());
10544 for (EVT VT : ResultTypes)
10545 RetValues.push_back(VT == MVT::Other ? Chain : getPOISON(VT));
10546 return getMergeValues(RetValues, dl);
10547}
10548
10550 unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef<SDValue> Ops,
10551 EVT MemVT, MachinePointerInfo PtrInfo, Align Alignment,
10553 const AAMDNodes &AAInfo) {
10554 if (Size.hasValue() && !Size.getValue())
10556
10558 MachineMemOperand *MMO =
10559 MF.getMachineMemOperand(PtrInfo, Flags, Size, Alignment, AAInfo);
10560
10561 return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, MMO);
10562}
10563
10565 SDVTList VTList,
10566 ArrayRef<SDValue> Ops, EVT MemVT,
10567 MachineMemOperand *MMO) {
10568 return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, ArrayRef(MMO));
10569}
10570
10572 SDVTList VTList,
10573 ArrayRef<SDValue> Ops, EVT MemVT,
10575 assert(!MMOs.empty() && "Must have at least one MMO");
10576 assert(
10577 (Opcode == ISD::INTRINSIC_VOID || Opcode == ISD::INTRINSIC_W_CHAIN ||
10578 Opcode == ISD::PREFETCH ||
10579 (Opcode <= (unsigned)std::numeric_limits<int>::max() &&
10580 Opcode >= ISD::BUILTIN_OP_END && TSI->isTargetMemoryOpcode(Opcode))) &&
10581 "Opcode is not a memory-accessing opcode!");
10582
10584 if (MMOs.size() == 1) {
10585 MemRefs = MMOs[0];
10586 } else {
10587 // Allocate: [size_t count][MMO*][MMO*]...
10588 size_t AllocSize =
10589 sizeof(size_t) + MMOs.size() * sizeof(MachineMemOperand *);
10590 void *Buffer = Allocator.Allocate(AllocSize, alignof(size_t));
10591 size_t *CountPtr = static_cast<size_t *>(Buffer);
10592 *CountPtr = MMOs.size();
10593 MachineMemOperand **Array =
10594 reinterpret_cast<MachineMemOperand **>(CountPtr + 1);
10595 llvm::copy(MMOs, Array);
10596 MemRefs = Array;
10597 }
10598
10599 // Memoize the node unless it returns a glue result.
10601 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
10602 SDNodeKey ID(Opcode, VTList, Ops);
10603 ID.AddInteger(getSyntheticNodeSubclassData<MemIntrinsicSDNode>(
10604 Opcode, dl.getIROrder(), VTList, MemVT, MemRefs));
10605 ID.AddInteger(MemVT.getRawBits());
10606 for (const MachineMemOperand *MMO : MMOs) {
10607 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
10608 ID.AddInteger(MMO->getFlags());
10609 }
10610 FoldingSetInsertToken InsertToken;
10611 if (SDNode *E = lookupNode(ID, dl, InsertToken)) {
10612 cast<MemIntrinsicSDNode>(E)->refineAlignment(MMOs);
10613 return SDValue(E, 0);
10614 }
10615
10616 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
10617 VTList, MemVT, MemRefs);
10618 createOperands(N, Ops);
10619 CSEMap.insert(N, InsertToken);
10620 } else {
10621 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
10622 VTList, MemVT, MemRefs);
10623 createOperands(N, Ops);
10624 }
10625 InsertNode(N);
10626 SDValue V(N, 0);
10627 NewSDValueDbgMsg(V, "Creating new node: ", this);
10628 return V;
10629}
10630
10632 SDValue Chain, int FrameIndex) {
10633 const unsigned Opcode = IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END;
10634 const auto VTs = getVTList(MVT::Other);
10635 SDValue Ops[2] = {
10636 Chain,
10637 getFrameIndex(FrameIndex,
10638 getTargetLoweringInfo().getFrameIndexTy(getDataLayout()),
10639 true)};
10640
10641 SDNodeKey ID(Opcode, VTs, Ops);
10642 FoldingSetInsertToken InsertToken;
10643 if (SDNode *E = lookupNode(ID, dl, InsertToken))
10644 return SDValue(E, 0);
10645
10646 LifetimeSDNode *N =
10647 newSDNode<LifetimeSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), VTs);
10648 createOperands(N, Ops);
10649 CSEMap.insert(N, InsertToken);
10650 InsertNode(N);
10651 SDValue V(N, 0);
10652 NewSDValueDbgMsg(V, "Creating new node: ", this);
10653 return V;
10654}
10655
10657 uint64_t Guid, uint64_t Index,
10658 uint32_t Attr) {
10659 const unsigned Opcode = ISD::PSEUDO_PROBE;
10660 const auto VTs = getVTList(MVT::Other);
10661 SDValue Ops[] = {Chain};
10662 SDNodeKey ID(Opcode, VTs, Ops);
10663 ID.AddInteger(Guid);
10664 ID.AddInteger(Index);
10665 ID.AddInteger(Attr);
10666 FoldingSetInsertToken InsertToken;
10667 if (SDNode *E = lookupNode(ID, Dl, InsertToken))
10668 return SDValue(E, 0);
10669
10670 auto *N = newSDNode<PseudoProbeSDNode>(
10671 Opcode, Dl.getIROrder(), Dl.getDebugLoc(), VTs, Guid, Index, Attr);
10672 createOperands(N, Ops);
10673 CSEMap.insert(N, InsertToken);
10674 InsertNode(N);
10675 SDValue V(N, 0);
10676 NewSDValueDbgMsg(V, "Creating new node: ", this);
10677 return V;
10678}
10679
10680/// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
10681/// MachinePointerInfo record from it. This is particularly useful because the
10682/// code generator has many cases where it doesn't bother passing in a
10683/// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
10685 SelectionDAG &DAG, SDValue Ptr,
10686 int64_t Offset = 0) {
10687 // If this is FI+Offset, we can model it.
10688 if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr))
10690 FI->getIndex(), Offset);
10691
10692 // If this is (FI+Offset1)+Offset2, we can model it.
10693 if (Ptr.getOpcode() != ISD::ADD ||
10696 return Info;
10697
10698 int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
10700 DAG.getMachineFunction(), FI,
10701 Offset + cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue());
10702}
10703
10704/// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
10705/// MachinePointerInfo record from it. This is particularly useful because the
10706/// code generator has many cases where it doesn't bother passing in a
10707/// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
10709 SelectionDAG &DAG, SDValue Ptr,
10710 SDValue OffsetOp) {
10711 // If the 'Offset' value isn't a constant, we can't handle this.
10713 return InferPointerInfo(Info, DAG, Ptr, OffsetNode->getSExtValue());
10714 if (OffsetOp.isUndef())
10715 return InferPointerInfo(Info, DAG, Ptr);
10716 return Info;
10717}
10718
10720 EVT VT, const SDLoc &dl, SDValue Chain,
10721 SDValue Ptr, SDValue Offset,
10722 MachinePointerInfo PtrInfo, EVT MemVT,
10723 Align Alignment,
10724 MachineMemOperand::Flags MMOFlags,
10725 const MMOMetadata &Metadata) {
10726 assert(Chain.getValueType() == MVT::Other &&
10727 "Invalid chain type");
10728
10729 MMOFlags |= MachineMemOperand::MOLoad;
10730 assert((MMOFlags & MachineMemOperand::MOStore) == 0);
10731 // If we don't have a PtrInfo, infer the trivial frame index case to simplify
10732 // clients.
10733 if (PtrInfo.V.isNull())
10734 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
10735
10736 TypeSize Size = MemVT.getStoreSize();
10738 MachineMemOperand *MMO =
10739 MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, Alignment, Metadata);
10740 return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO);
10741}
10742
10744 EVT VT, const SDLoc &dl, SDValue Chain,
10745 SDValue Ptr, SDValue Offset, EVT MemVT,
10746 MachineMemOperand *MMO) {
10747 if (VT == MemVT) {
10748 ExtType = ISD::NON_EXTLOAD;
10749 } else if (ExtType == ISD::NON_EXTLOAD) {
10750 assert(VT == MemVT && "Non-extending load from different memory type!");
10751 } else {
10752 // Extending load.
10753 assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) &&
10754 "Should only be an extending load, not truncating!");
10755 assert(VT.isInteger() == MemVT.isInteger() &&
10756 "Cannot convert from FP to Int or Int -> FP!");
10757 assert(VT.isVector() == MemVT.isVector() &&
10758 "Cannot use an ext load to convert to or from a vector!");
10759 assert((!VT.isVector() ||
10761 "Cannot use an ext load to change the number of vector elements!");
10762 }
10763
10764 assert((!MMO->getRanges() ||
10766 ->getBitWidth() == MemVT.getScalarSizeInBits() &&
10767 MemVT.isInteger())) &&
10768 "Range metadata and load type must match!");
10769
10770 bool Indexed = AM != ISD::UNINDEXED;
10771 assert((Indexed || Offset.getOpcode() == ISD::POISON) &&
10772 "Unindexed load with an offset!");
10773
10774 SDVTList VTs = Indexed ?
10775 getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
10776 SDValue Ops[] = { Chain, Ptr, Offset };
10777 SDNodeKey ID(ISD::LOAD, VTs, Ops);
10778 ID.AddInteger(MemVT.getRawBits());
10779 ID.AddInteger(getSyntheticNodeSubclassData<LoadSDNode>(
10780 dl.getIROrder(), VTs, AM, ExtType, MemVT, MMO));
10781 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
10782 ID.AddInteger(MMO->getFlags());
10783 FoldingSetInsertToken InsertToken;
10784 if (auto *E = cast_or_null<LoadSDNode>(lookupNode(ID, dl, InsertToken))) {
10785 E->refineAlignment(MMO);
10786 E->refineMMOMetadata(MMO);
10787 return SDValue(E, 0);
10788 }
10789 auto *N = newSDNode<LoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
10790 ExtType, MemVT, MMO);
10791 createOperands(N, Ops);
10792
10793 CSEMap.insert(N, InsertToken);
10794 InsertNode(N);
10795 SDValue V(N, 0);
10796 NewSDValueDbgMsg(V, "Creating new node: ", this);
10797 return V;
10798}
10799
10801 SDValue Ptr, MachinePointerInfo PtrInfo,
10802 MaybeAlign Alignment,
10803 MachineMemOperand::Flags MMOFlags,
10804 const MMOMetadata &Metadata) {
10806 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
10807 PtrInfo, VT, Alignment, MMOFlags, Metadata);
10808}
10809
10811 SDValue Ptr, MachineMemOperand *MMO) {
10813 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
10814 VT, MMO);
10815}
10816
10818 EVT VT, SDValue Chain, SDValue Ptr,
10819 MachinePointerInfo PtrInfo, EVT MemVT,
10820 MaybeAlign Alignment,
10821 MachineMemOperand::Flags MMOFlags,
10822 const MMOMetadata &Metadata) {
10824 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, PtrInfo,
10825 MemVT, Alignment, MMOFlags, Metadata);
10826}
10827
10829 EVT VT, SDValue Chain, SDValue Ptr, EVT MemVT,
10830 MachineMemOperand *MMO) {
10832 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef,
10833 MemVT, MMO);
10834}
10835
10839 LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
10840 assert(LD->getOffset().getOpcode() == ISD::POISON &&
10841 "Load is already a indexed load!");
10842 // Don't propagate the invariant or dereferenceable flags.
10843 auto MMOFlags =
10844 LD->getMemOperand()->getFlags() &
10846 return getLoad(
10847 AM, LD->getExtensionType(), OrigLoad.getValueType(), dl, LD->getChain(),
10848 Base, Offset, LD->getPointerInfo(), LD->getMemoryVT(), LD->getAlign(),
10849 MMOFlags,
10850 MMOMetadata(LD->getAAInfo(), LD->getRanges(), LD->getMemCacheHint()));
10851}
10852
10854 SDValue Ptr, MachinePointerInfo PtrInfo,
10855 Align Alignment,
10856 MachineMemOperand::Flags MMOFlags,
10857 const MMOMetadata &Metadata) {
10858 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
10859
10860 MMOFlags |= MachineMemOperand::MOStore;
10861 assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
10862 assert(!Metadata.Ranges && "range metadata is invalid for stores");
10863
10864 if (PtrInfo.V.isNull())
10865 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
10866
10869 MachineMemOperand *MMO =
10870 MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, Alignment, Metadata);
10871 return getStore(Chain, dl, Val, Ptr, MMO);
10872}
10873
10875 SDValue Ptr, MachineMemOperand *MMO) {
10877 return getStore(Chain, dl, Val, Ptr, Undef, Val.getValueType(), MMO,
10879}
10880
10882 SDValue Ptr, SDValue Offset, EVT SVT,
10884 bool IsTruncating) {
10885 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
10886 EVT VT = Val.getValueType();
10887 if (VT == SVT) {
10888 IsTruncating = false;
10889 } else if (!IsTruncating) {
10890 assert(VT == SVT && "No-truncating store from different memory type!");
10891 } else {
10893 "Should only be a truncating store, not extending!");
10894 assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!");
10895 assert(VT.isVector() == SVT.isVector() &&
10896 "Cannot use trunc store to convert to or from a vector!");
10897 assert((!VT.isVector() ||
10899 "Cannot use trunc store to change the number of vector elements!");
10900 }
10901
10902 bool Indexed = AM != ISD::UNINDEXED;
10903 assert((Indexed || Offset.getOpcode() == ISD::POISON) &&
10904 "Unindexed store with an offset!");
10905 SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other)
10906 : getVTList(MVT::Other);
10907 SDValue Ops[] = {Chain, Val, Ptr, Offset};
10908 SDNodeKey ID(ISD::STORE, VTs, Ops);
10909 ID.AddInteger(SVT.getRawBits());
10910 ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
10911 dl.getIROrder(), VTs, AM, IsTruncating, SVT, MMO));
10912 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
10913 ID.AddInteger(MMO->getFlags());
10914 FoldingSetInsertToken InsertToken;
10915 if (SDNode *E = lookupNode(ID, dl, InsertToken)) {
10916 cast<StoreSDNode>(E)->refineAlignment(MMO);
10917 cast<StoreSDNode>(E)->refineMMOMetadata(MMO);
10918 return SDValue(E, 0);
10919 }
10920 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
10921 IsTruncating, SVT, MMO);
10922 createOperands(N, Ops);
10923
10924 CSEMap.insert(N, InsertToken);
10925 InsertNode(N);
10926 SDValue V(N, 0);
10927 NewSDValueDbgMsg(V, "Creating new node: ", this);
10928 return V;
10929}
10930
10932 SDValue Ptr, SDValue Offset,
10933 MachinePointerInfo PtrInfo, EVT SVT,
10934 Align Alignment,
10935 MachineMemOperand::Flags MMOFlags,
10936 const MMOMetadata &Metadata) {
10937 assert(Chain.getValueType() == MVT::Other &&
10938 "Invalid chain type");
10939
10940 MMOFlags |= MachineMemOperand::MOStore;
10941 assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
10942 assert(!Metadata.Ranges && "range metadata is invalid for stores");
10943
10944 if (PtrInfo.V.isNull())
10945 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
10946
10948 MachineMemOperand *MMO = MF.getMachineMemOperand(
10949 PtrInfo, MMOFlags, SVT.getStoreSize(), Alignment, Metadata);
10950 return getTruncStore(Chain, dl, Val, Ptr, Offset, SVT, MMO);
10951}
10952
10954 SDValue Ptr, MachinePointerInfo PtrInfo,
10955 EVT SVT, Align Alignment,
10956 MachineMemOperand::Flags MMOFlags,
10957 const MMOMetadata &Metadata) {
10958 return getTruncStore(Chain, dl, Val, Ptr, getPOISON(Ptr.getValueType()),
10959 PtrInfo, SVT, Alignment, MMOFlags, Metadata);
10960}
10961
10963 SDValue Ptr, SDValue Offset, EVT SVT,
10964 MachineMemOperand *MMO) {
10965 return getStore(Chain, dl, Val, Ptr, Offset, SVT, MMO, ISD::UNINDEXED, true);
10966}
10967
10969 SDValue Ptr, EVT SVT,
10970 MachineMemOperand *MMO) {
10971 return getStore(Chain, dl, Val, Ptr, getPOISON(Ptr.getValueType()), SVT, MMO,
10972 ISD::UNINDEXED, true);
10973}
10974
10978 StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
10979 assert(ST->getOffset().getOpcode() == ISD::POISON &&
10980 "Store is already a indexed store!");
10981 return getStore(ST->getChain(), dl, ST->getValue(), Base, Offset,
10982 ST->getMemoryVT(), ST->getMemOperand(), AM,
10983 ST->isTruncatingStore());
10984}
10985
10987 ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &dl,
10988 SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Mask, SDValue EVL,
10989 MachinePointerInfo PtrInfo, EVT MemVT, Align Alignment,
10990 MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
10991 const MDNode *Ranges, bool IsExpanding) {
10992 MMOFlags |= MachineMemOperand::MOLoad;
10993 assert((MMOFlags & MachineMemOperand::MOStore) == 0);
10994 // If we don't have a PtrInfo, infer the trivial frame index case to simplify
10995 // clients.
10996 if (PtrInfo.V.isNull())
10997 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
10998
10999 TypeSize Size = MemVT.getStoreSize();
11001 MachineMemOperand *MMO = MF.getMachineMemOperand(
11002 PtrInfo, MMOFlags, Size, Alignment, MMOMetadata(AAInfo, Ranges));
11003 return getLoadVP(AM, ExtType, VT, dl, Chain, Ptr, Offset, Mask, EVL, MemVT,
11004 MMO, IsExpanding);
11005}
11006
11008 ISD::LoadExtType ExtType, EVT VT,
11009 const SDLoc &dl, SDValue Chain, SDValue Ptr,
11010 SDValue Offset, SDValue Mask, SDValue EVL,
11011 EVT MemVT, MachineMemOperand *MMO,
11012 bool IsExpanding) {
11013 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
11014 assert(Mask.getValueType().getVectorElementCount() ==
11015 VT.getVectorElementCount() &&
11016 "Vector width mismatch between mask and data");
11017
11018 bool Indexed = AM != ISD::UNINDEXED;
11019 assert((Indexed || Offset.getOpcode() == ISD::POISON) &&
11020 "Unindexed load with an offset!");
11021
11022 SDVTList VTs = Indexed ? getVTList(VT, Ptr.getValueType(), MVT::Other)
11023 : getVTList(VT, MVT::Other);
11024 SDValue Ops[] = {Chain, Ptr, Offset, Mask, EVL};
11025 SDNodeKey ID(ISD::VP_LOAD, VTs, Ops);
11026 ID.AddInteger(MemVT.getRawBits());
11027 ID.AddInteger(getSyntheticNodeSubclassData<VPLoadSDNode>(
11028 dl.getIROrder(), VTs, AM, ExtType, IsExpanding, MemVT, MMO));
11029 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11030 ID.AddInteger(MMO->getFlags());
11031 FoldingSetInsertToken InsertToken;
11032 if (auto *E = cast_or_null<VPLoadSDNode>(lookupNode(ID, dl, InsertToken))) {
11033 E->refineAlignment(MMO);
11034 E->refineMMOMetadata(MMO);
11035 return SDValue(E, 0);
11036 }
11037 auto *N = newSDNode<VPLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
11038 ExtType, IsExpanding, MemVT, MMO);
11039 createOperands(N, Ops);
11040
11041 CSEMap.insert(N, InsertToken);
11042 InsertNode(N);
11043 SDValue V(N, 0);
11044 NewSDValueDbgMsg(V, "Creating new node: ", this);
11045 return V;
11046}
11047
11049 SDValue Ptr, SDValue Mask, SDValue EVL,
11050 MachinePointerInfo PtrInfo,
11051 MaybeAlign Alignment,
11052 MachineMemOperand::Flags MMOFlags,
11053 const AAMDNodes &AAInfo, const MDNode *Ranges,
11054 bool IsExpanding) {
11056 return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
11057 Mask, EVL, PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges,
11058 IsExpanding);
11059}
11060
11062 SDValue Ptr, SDValue Mask, SDValue EVL,
11063 MachineMemOperand *MMO, bool IsExpanding) {
11065 return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
11066 Mask, EVL, VT, MMO, IsExpanding);
11067}
11068
11070 EVT VT, SDValue Chain, SDValue Ptr,
11071 SDValue Mask, SDValue EVL,
11072 MachinePointerInfo PtrInfo, EVT MemVT,
11073 MaybeAlign Alignment,
11074 MachineMemOperand::Flags MMOFlags,
11075 const AAMDNodes &AAInfo, bool IsExpanding) {
11077 return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask,
11078 EVL, PtrInfo, MemVT, Alignment, MMOFlags, AAInfo, nullptr,
11079 IsExpanding);
11080}
11081
11083 EVT VT, SDValue Chain, SDValue Ptr,
11084 SDValue Mask, SDValue EVL, EVT MemVT,
11085 MachineMemOperand *MMO, bool IsExpanding) {
11087 return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask,
11088 EVL, MemVT, MMO, IsExpanding);
11089}
11090
11094 auto *LD = cast<VPLoadSDNode>(OrigLoad);
11095 assert(LD->getOffset().getOpcode() == ISD::POISON &&
11096 "Load is already a indexed load!");
11097 // Don't propagate the invariant or dereferenceable flags.
11098 auto MMOFlags =
11099 LD->getMemOperand()->getFlags() &
11101 return getLoadVP(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
11102 LD->getChain(), Base, Offset, LD->getMask(),
11103 LD->getVectorLength(), LD->getPointerInfo(),
11104 LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo(),
11105 nullptr, LD->isExpandingLoad());
11106}
11107
11109 SDValue Ptr, SDValue Offset, SDValue Mask,
11110 SDValue EVL, EVT MemVT, MachineMemOperand *MMO,
11111 ISD::MemIndexedMode AM, bool IsTruncating,
11112 bool IsCompressing) {
11113 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
11114 assert(Mask.getValueType().getVectorElementCount() ==
11116 "Vector width mismatch between mask and data");
11117
11118 bool Indexed = AM != ISD::UNINDEXED;
11119 assert((Indexed || Offset.getOpcode() == ISD::POISON) &&
11120 "Unindexed vp_store with an offset!");
11121 SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other)
11122 : getVTList(MVT::Other);
11123 SDValue Ops[] = {Chain, Val, Ptr, Offset, Mask, EVL};
11124 SDNodeKey ID(ISD::VP_STORE, VTs, Ops);
11125 ID.AddInteger(MemVT.getRawBits());
11126 ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>(
11127 dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
11128 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11129 ID.AddInteger(MMO->getFlags());
11130 FoldingSetInsertToken InsertToken;
11131 if (SDNode *E = lookupNode(ID, dl, InsertToken)) {
11132 cast<VPStoreSDNode>(E)->refineAlignment(MMO);
11133 return SDValue(E, 0);
11134 }
11135 auto *N = newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
11136 IsTruncating, IsCompressing, MemVT, MMO);
11137 createOperands(N, Ops);
11138
11139 CSEMap.insert(N, InsertToken);
11140 InsertNode(N);
11141 SDValue V(N, 0);
11142 NewSDValueDbgMsg(V, "Creating new node: ", this);
11143 return V;
11144}
11145
11147 SDValue Val, SDValue Ptr, SDValue Mask,
11148 SDValue EVL, MachinePointerInfo PtrInfo,
11149 EVT SVT, Align Alignment,
11150 MachineMemOperand::Flags MMOFlags,
11151 const AAMDNodes &AAInfo,
11152 bool IsCompressing) {
11153 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
11154
11155 MMOFlags |= MachineMemOperand::MOStore;
11156 assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
11157
11158 if (PtrInfo.V.isNull())
11159 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
11160
11162 MachineMemOperand *MMO = MF.getMachineMemOperand(
11163 PtrInfo, MMOFlags, SVT.getStoreSize(), Alignment, AAInfo);
11164 return getTruncStoreVP(Chain, dl, Val, Ptr, Mask, EVL, SVT, MMO,
11165 IsCompressing);
11166}
11167
11169 SDValue Val, SDValue Ptr, SDValue Mask,
11170 SDValue EVL, EVT SVT,
11171 MachineMemOperand *MMO,
11172 bool IsCompressing) {
11173 EVT VT = Val.getValueType();
11174
11175 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
11176 if (VT == SVT)
11177 return getStoreVP(Chain, dl, Val, Ptr, getPOISON(Ptr.getValueType()), Mask,
11178 EVL, VT, MMO, ISD::UNINDEXED,
11179 /*IsTruncating*/ false, IsCompressing);
11180
11182 "Should only be a truncating store, not extending!");
11183 assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!");
11184 assert(VT.isVector() == SVT.isVector() &&
11185 "Cannot use trunc store to convert to or from a vector!");
11186 assert((!VT.isVector() ||
11188 "Cannot use trunc store to change the number of vector elements!");
11189
11190 SDVTList VTs = getVTList(MVT::Other);
11192 SDValue Ops[] = {Chain, Val, Ptr, Undef, Mask, EVL};
11193 SDNodeKey ID(ISD::VP_STORE, VTs, Ops);
11194 ID.AddInteger(SVT.getRawBits());
11195 ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>(
11196 dl.getIROrder(), VTs, ISD::UNINDEXED, true, IsCompressing, SVT, MMO));
11197 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11198 ID.AddInteger(MMO->getFlags());
11199 FoldingSetInsertToken InsertToken;
11200 if (SDNode *E = lookupNode(ID, dl, InsertToken)) {
11201 cast<VPStoreSDNode>(E)->refineAlignment(MMO);
11202 return SDValue(E, 0);
11203 }
11204 auto *N =
11205 newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
11206 ISD::UNINDEXED, true, IsCompressing, SVT, MMO);
11207 createOperands(N, Ops);
11208
11209 CSEMap.insert(N, InsertToken);
11210 InsertNode(N);
11211 SDValue V(N, 0);
11212 NewSDValueDbgMsg(V, "Creating new node: ", this);
11213 return V;
11214}
11215
11219 auto *ST = cast<VPStoreSDNode>(OrigStore);
11220 assert(ST->getOffset().getOpcode() == ISD::POISON &&
11221 "Store is already an indexed store!");
11222 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
11223 SDValue Ops[] = {ST->getChain(), ST->getValue(), Base,
11224 Offset, ST->getMask(), ST->getVectorLength()};
11225 SDNodeKey ID(ISD::VP_STORE, VTs, Ops);
11226 ID.AddInteger(ST->getMemoryVT().getRawBits());
11227 ID.AddInteger(ST->getRawSubclassData());
11228 ID.AddInteger(ST->getPointerInfo().getAddrSpace());
11229 ID.AddInteger(ST->getMemOperand()->getFlags());
11230 FoldingSetInsertToken InsertToken;
11231 if (SDNode *E = lookupNode(ID, dl, InsertToken))
11232 return SDValue(E, 0);
11233
11234 auto *N = newSDNode<VPStoreSDNode>(
11235 dl.getIROrder(), dl.getDebugLoc(), VTs, AM, ST->isTruncatingStore(),
11236 ST->isCompressingStore(), ST->getMemoryVT(), ST->getMemOperand());
11237 createOperands(N, Ops);
11238
11239 CSEMap.insert(N, InsertToken);
11240 InsertNode(N);
11241 SDValue V(N, 0);
11242 NewSDValueDbgMsg(V, "Creating new node: ", this);
11243 return V;
11244}
11245
11247 ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &DL,
11248 SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Stride, SDValue Mask,
11249 SDValue EVL, EVT MemVT, MachineMemOperand *MMO, bool IsExpanding) {
11250 bool Indexed = AM != ISD::UNINDEXED;
11251 assert((Indexed || Offset.getOpcode() == ISD::POISON) &&
11252 "Unindexed load with an offset!");
11253
11254 SDValue Ops[] = {Chain, Ptr, Offset, Stride, Mask, EVL};
11255 SDVTList VTs = Indexed ? getVTList(VT, Ptr.getValueType(), MVT::Other)
11256 : getVTList(VT, MVT::Other);
11257 SDNodeKey ID(ISD::EXPERIMENTAL_VP_STRIDED_LOAD, VTs, Ops);
11258 ID.AddInteger(MemVT.getRawBits());
11259 ID.AddInteger(getSyntheticNodeSubclassData<VPStridedLoadSDNode>(
11260 DL.getIROrder(), VTs, AM, ExtType, IsExpanding, MemVT, MMO));
11261 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11262
11263 FoldingSetInsertToken InsertToken;
11264 if (SDNode *E = lookupNode(ID, DL, InsertToken)) {
11265 cast<VPStridedLoadSDNode>(E)->refineAlignment(MMO);
11266 return SDValue(E, 0);
11267 }
11268
11269 auto *N =
11270 newSDNode<VPStridedLoadSDNode>(DL.getIROrder(), DL.getDebugLoc(), VTs, AM,
11271 ExtType, IsExpanding, MemVT, MMO);
11272 createOperands(N, Ops);
11273 CSEMap.insert(N, InsertToken);
11274 InsertNode(N);
11275 SDValue V(N, 0);
11276 NewSDValueDbgMsg(V, "Creating new node: ", this);
11277 return V;
11278}
11279
11281 SDValue Ptr, SDValue Stride,
11282 SDValue Mask, SDValue EVL,
11283 MachineMemOperand *MMO,
11284 bool IsExpanding) {
11286 return getStridedLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, DL, Chain, Ptr,
11287 Undef, Stride, Mask, EVL, VT, MMO, IsExpanding);
11288}
11289
11291 ISD::LoadExtType ExtType, const SDLoc &DL, EVT VT, SDValue Chain,
11292 SDValue Ptr, SDValue Stride, SDValue Mask, SDValue EVL, EVT MemVT,
11293 MachineMemOperand *MMO, bool IsExpanding) {
11295 return getStridedLoadVP(ISD::UNINDEXED, ExtType, VT, DL, Chain, Ptr, Undef,
11296 Stride, Mask, EVL, MemVT, MMO, IsExpanding);
11297}
11298
11300 SDValue Val, SDValue Ptr,
11301 SDValue Offset, SDValue Stride,
11302 SDValue Mask, SDValue EVL, EVT MemVT,
11303 MachineMemOperand *MMO,
11305 bool IsTruncating, bool IsCompressing) {
11306 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
11307 bool Indexed = AM != ISD::UNINDEXED;
11308 assert((Indexed || Offset.getOpcode() == ISD::POISON) &&
11309 "Unindexed vp_store with an offset!");
11310 SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other)
11311 : getVTList(MVT::Other);
11312 SDValue Ops[] = {Chain, Val, Ptr, Offset, Stride, Mask, EVL};
11313 SDNodeKey ID(ISD::EXPERIMENTAL_VP_STRIDED_STORE, VTs, Ops);
11314 ID.AddInteger(MemVT.getRawBits());
11315 ID.AddInteger(getSyntheticNodeSubclassData<VPStridedStoreSDNode>(
11316 DL.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
11317 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11318 FoldingSetInsertToken InsertToken;
11319 if (SDNode *E = lookupNode(ID, DL, InsertToken)) {
11320 cast<VPStridedStoreSDNode>(E)->refineAlignment(MMO);
11321 return SDValue(E, 0);
11322 }
11323 auto *N = newSDNode<VPStridedStoreSDNode>(DL.getIROrder(), DL.getDebugLoc(),
11324 VTs, AM, IsTruncating,
11325 IsCompressing, MemVT, MMO);
11326 createOperands(N, Ops);
11327
11328 CSEMap.insert(N, InsertToken);
11329 InsertNode(N);
11330 SDValue V(N, 0);
11331 NewSDValueDbgMsg(V, "Creating new node: ", this);
11332 return V;
11333}
11334
11336 SDValue Val, SDValue Ptr,
11337 SDValue Stride, SDValue Mask,
11338 SDValue EVL, EVT SVT,
11339 MachineMemOperand *MMO,
11340 bool IsCompressing) {
11341 EVT VT = Val.getValueType();
11342
11343 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
11344 if (VT == SVT)
11345 return getStridedStoreVP(Chain, DL, Val, Ptr, getPOISON(Ptr.getValueType()),
11346 Stride, Mask, EVL, VT, MMO, ISD::UNINDEXED,
11347 /*IsTruncating*/ false, IsCompressing);
11348
11350 "Should only be a truncating store, not extending!");
11351 assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!");
11352 assert(VT.isVector() == SVT.isVector() &&
11353 "Cannot use trunc store to convert to or from a vector!");
11354 assert((!VT.isVector() ||
11356 "Cannot use trunc store to change the number of vector elements!");
11357
11358 SDVTList VTs = getVTList(MVT::Other);
11360 SDValue Ops[] = {Chain, Val, Ptr, Undef, Stride, Mask, EVL};
11361 SDNodeKey ID(ISD::EXPERIMENTAL_VP_STRIDED_STORE, VTs, Ops);
11362 ID.AddInteger(SVT.getRawBits());
11363 ID.AddInteger(getSyntheticNodeSubclassData<VPStridedStoreSDNode>(
11364 DL.getIROrder(), VTs, ISD::UNINDEXED, true, IsCompressing, SVT, MMO));
11365 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11366 FoldingSetInsertToken InsertToken;
11367 if (SDNode *E = lookupNode(ID, DL, InsertToken)) {
11368 cast<VPStridedStoreSDNode>(E)->refineAlignment(MMO);
11369 return SDValue(E, 0);
11370 }
11371 auto *N = newSDNode<VPStridedStoreSDNode>(DL.getIROrder(), DL.getDebugLoc(),
11372 VTs, ISD::UNINDEXED, true,
11373 IsCompressing, SVT, MMO);
11374 createOperands(N, Ops);
11375
11376 CSEMap.insert(N, InsertToken);
11377 InsertNode(N);
11378 SDValue V(N, 0);
11379 NewSDValueDbgMsg(V, "Creating new node: ", this);
11380 return V;
11381}
11382
11385 ISD::MemIndexType IndexType) {
11386 assert(Ops.size() == 6 && "Incompatible number of operands");
11387
11388 SDNodeKey ID(ISD::VP_GATHER, VTs, Ops);
11389 ID.AddInteger(VT.getRawBits());
11390 ID.AddInteger(getSyntheticNodeSubclassData<VPGatherSDNode>(
11391 dl.getIROrder(), VTs, VT, MMO, IndexType));
11392 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11393 ID.AddInteger(MMO->getFlags());
11394 FoldingSetInsertToken InsertToken;
11395 if (SDNode *E = lookupNode(ID, dl, InsertToken)) {
11396 cast<VPGatherSDNode>(E)->refineAlignment(MMO);
11397 return SDValue(E, 0);
11398 }
11399
11400 auto *N = newSDNode<VPGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
11401 VT, MMO, IndexType);
11402 createOperands(N, Ops);
11403
11404 assert(N->getMask().getValueType().getVectorElementCount() ==
11405 N->getValueType(0).getVectorElementCount() &&
11406 "Vector width mismatch between mask and data");
11407 assert(N->getIndex().getValueType().getVectorElementCount().isScalable() ==
11408 N->getValueType(0).getVectorElementCount().isScalable() &&
11409 "Scalable flags of index and data do not match");
11411 N->getIndex().getValueType().getVectorElementCount(),
11412 N->getValueType(0).getVectorElementCount()) &&
11413 "Vector width mismatch between index and data");
11414 assert(isa<ConstantSDNode>(N->getScale()) &&
11415 N->getScale()->getAsAPIntVal().isPowerOf2() &&
11416 "Scale should be a constant power of 2");
11417
11418 CSEMap.insert(N, InsertToken);
11419 InsertNode(N);
11420 SDValue V(N, 0);
11421 NewSDValueDbgMsg(V, "Creating new node: ", this);
11422 return V;
11423}
11424
11427 MachineMemOperand *MMO,
11428 ISD::MemIndexType IndexType) {
11429 assert(Ops.size() == 7 && "Incompatible number of operands");
11430
11431 SDNodeKey ID(ISD::VP_SCATTER, VTs, Ops);
11432 ID.AddInteger(VT.getRawBits());
11433 ID.AddInteger(getSyntheticNodeSubclassData<VPScatterSDNode>(
11434 dl.getIROrder(), VTs, VT, MMO, IndexType));
11435 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11436 ID.AddInteger(MMO->getFlags());
11437 FoldingSetInsertToken InsertToken;
11438 if (SDNode *E = lookupNode(ID, dl, InsertToken)) {
11439 cast<VPScatterSDNode>(E)->refineAlignment(MMO);
11440 return SDValue(E, 0);
11441 }
11442 auto *N = newSDNode<VPScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
11443 VT, MMO, IndexType);
11444 createOperands(N, Ops);
11445
11446 assert(N->getMask().getValueType().getVectorElementCount() ==
11447 N->getValue().getValueType().getVectorElementCount() &&
11448 "Vector width mismatch between mask and data");
11449 assert(
11450 N->getIndex().getValueType().getVectorElementCount().isScalable() ==
11451 N->getValue().getValueType().getVectorElementCount().isScalable() &&
11452 "Scalable flags of index and data do not match");
11454 N->getIndex().getValueType().getVectorElementCount(),
11455 N->getValue().getValueType().getVectorElementCount()) &&
11456 "Vector width mismatch between index and data");
11457 assert(isa<ConstantSDNode>(N->getScale()) &&
11458 N->getScale()->getAsAPIntVal().isPowerOf2() &&
11459 "Scale should be a constant power of 2");
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 SDValue PassThru, EVT MemVT,
11471 MachineMemOperand *MMO,
11473 ISD::LoadExtType ExtTy, bool isExpanding) {
11474 bool Indexed = AM != ISD::UNINDEXED;
11475 assert((Indexed || Offset.getOpcode() == ISD::POISON) &&
11476 "Unindexed masked load with an offset!");
11477 SDVTList VTs = Indexed ? getVTList(VT, Base.getValueType(), MVT::Other)
11478 : getVTList(VT, MVT::Other);
11479 SDValue Ops[] = {Chain, Base, Offset, Mask, PassThru};
11480 SDNodeKey ID(ISD::MLOAD, VTs, Ops);
11481 ID.AddInteger(MemVT.getRawBits());
11482 ID.AddInteger(getSyntheticNodeSubclassData<MaskedLoadSDNode>(
11483 dl.getIROrder(), VTs, AM, ExtTy, isExpanding, MemVT, MMO));
11484 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11485 ID.AddInteger(MMO->getFlags());
11486 FoldingSetInsertToken InsertToken;
11487 if (SDNode *E = lookupNode(ID, dl, InsertToken)) {
11488 cast<MaskedLoadSDNode>(E)->refineAlignment(MMO);
11489 return SDValue(E, 0);
11490 }
11491 auto *N = newSDNode<MaskedLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
11492 AM, ExtTy, isExpanding, MemVT, MMO);
11493 createOperands(N, Ops);
11494
11495 CSEMap.insert(N, InsertToken);
11496 InsertNode(N);
11497 SDValue V(N, 0);
11498 NewSDValueDbgMsg(V, "Creating new node: ", this);
11499 return V;
11500}
11501
11506 assert(LD->getOffset().getOpcode() == ISD::POISON &&
11507 "Masked load is already a indexed load!");
11508 return getMaskedLoad(OrigLoad.getValueType(), dl, LD->getChain(), Base,
11509 Offset, LD->getMask(), LD->getPassThru(),
11510 LD->getMemoryVT(), LD->getMemOperand(), AM,
11511 LD->getExtensionType(), LD->isExpandingLoad());
11512}
11513
11516 SDValue Mask, EVT MemVT,
11517 MachineMemOperand *MMO,
11518 ISD::MemIndexedMode AM, bool IsTruncating,
11519 bool IsCompressing) {
11520 assert(Chain.getValueType() == MVT::Other &&
11521 "Invalid chain type");
11522 bool Indexed = AM != ISD::UNINDEXED;
11523 assert((Indexed || Offset.getOpcode() == ISD::POISON) &&
11524 "Unindexed masked store with an offset!");
11525 SDVTList VTs = Indexed ? getVTList(Base.getValueType(), MVT::Other)
11526 : getVTList(MVT::Other);
11527 SDValue Ops[] = {Chain, Val, Base, Offset, Mask};
11528 SDNodeKey ID(ISD::MSTORE, VTs, Ops);
11529 ID.AddInteger(MemVT.getRawBits());
11530 ID.AddInteger(getSyntheticNodeSubclassData<MaskedStoreSDNode>(
11531 dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
11532 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11533 ID.AddInteger(MMO->getFlags());
11534 FoldingSetInsertToken InsertToken;
11535 if (SDNode *E = lookupNode(ID, dl, InsertToken)) {
11536 cast<MaskedStoreSDNode>(E)->refineAlignment(MMO);
11537 return SDValue(E, 0);
11538 }
11539 auto *N =
11540 newSDNode<MaskedStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
11541 IsTruncating, IsCompressing, MemVT, MMO);
11542 createOperands(N, Ops);
11543
11544 CSEMap.insert(N, InsertToken);
11545 InsertNode(N);
11546 SDValue V(N, 0);
11547 NewSDValueDbgMsg(V, "Creating new node: ", this);
11548 return V;
11549}
11550
11555 assert(ST->getOffset().getOpcode() == ISD::POISON &&
11556 "Masked store is already a indexed store!");
11557 return getMaskedStore(ST->getChain(), dl, ST->getValue(), Base, Offset,
11558 ST->getMask(), ST->getMemoryVT(), ST->getMemOperand(),
11559 AM, ST->isTruncatingStore(), ST->isCompressingStore());
11560}
11561
11564 MachineMemOperand *MMO,
11565 ISD::MemIndexType IndexType,
11566 ISD::LoadExtType ExtTy) {
11567 assert(Ops.size() == 6 && "Incompatible number of operands");
11568
11569 SDNodeKey ID(ISD::MGATHER, VTs, Ops);
11570 ID.AddInteger(MemVT.getRawBits());
11571 ID.AddInteger(getSyntheticNodeSubclassData<MaskedGatherSDNode>(
11572 dl.getIROrder(), VTs, MemVT, MMO, IndexType, ExtTy));
11573 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11574 ID.AddInteger(MMO->getFlags());
11575 FoldingSetInsertToken InsertToken;
11576 if (SDNode *E = lookupNode(ID, dl, InsertToken)) {
11577 cast<MaskedGatherSDNode>(E)->refineAlignment(MMO);
11578 return SDValue(E, 0);
11579 }
11580
11581 auto *N = newSDNode<MaskedGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(),
11582 VTs, MemVT, MMO, IndexType, ExtTy);
11583 createOperands(N, Ops);
11584
11585 assert(N->getPassThru().getValueType() == N->getValueType(0) &&
11586 "Incompatible type of the PassThru value in MaskedGatherSDNode");
11587 assert(N->getMask().getValueType().getVectorElementCount() ==
11588 N->getValueType(0).getVectorElementCount() &&
11589 "Vector width mismatch between mask and data");
11590 assert(N->getIndex().getValueType().getVectorElementCount().isScalable() ==
11591 N->getValueType(0).getVectorElementCount().isScalable() &&
11592 "Scalable flags of index and data do not match");
11594 N->getIndex().getValueType().getVectorElementCount(),
11595 N->getValueType(0).getVectorElementCount()) &&
11596 "Vector width mismatch between index and data");
11597 assert(isa<ConstantSDNode>(N->getScale()) &&
11598 N->getScale()->getAsAPIntVal().isPowerOf2() &&
11599 "Scale should be a constant power of 2");
11600
11601 CSEMap.insert(N, InsertToken);
11602 InsertNode(N);
11603 SDValue V(N, 0);
11604 NewSDValueDbgMsg(V, "Creating new node: ", this);
11605 return V;
11606}
11607
11610 MachineMemOperand *MMO,
11611 ISD::MemIndexType IndexType,
11612 bool IsTrunc) {
11613 assert(Ops.size() == 6 && "Incompatible number of operands");
11614
11615 SDNodeKey ID(ISD::MSCATTER, VTs, Ops);
11616 ID.AddInteger(MemVT.getRawBits());
11617 ID.AddInteger(getSyntheticNodeSubclassData<MaskedScatterSDNode>(
11618 dl.getIROrder(), VTs, MemVT, MMO, IndexType, IsTrunc));
11619 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11620 ID.AddInteger(MMO->getFlags());
11621 FoldingSetInsertToken InsertToken;
11622 if (SDNode *E = lookupNode(ID, dl, InsertToken)) {
11623 cast<MaskedScatterSDNode>(E)->refineAlignment(MMO);
11624 return SDValue(E, 0);
11625 }
11626
11627 auto *N = newSDNode<MaskedScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(),
11628 VTs, MemVT, MMO, IndexType, IsTrunc);
11629 createOperands(N, Ops);
11630
11631 assert(N->getMask().getValueType().getVectorElementCount() ==
11632 N->getValue().getValueType().getVectorElementCount() &&
11633 "Vector width mismatch between mask and data");
11634 assert(
11635 N->getIndex().getValueType().getVectorElementCount().isScalable() ==
11636 N->getValue().getValueType().getVectorElementCount().isScalable() &&
11637 "Scalable flags of index and data do not match");
11639 N->getIndex().getValueType().getVectorElementCount(),
11640 N->getValue().getValueType().getVectorElementCount()) &&
11641 "Vector width mismatch between index and data");
11642 assert(isa<ConstantSDNode>(N->getScale()) &&
11643 N->getScale()->getAsAPIntVal().isPowerOf2() &&
11644 "Scale should be a constant power of 2");
11645
11646 CSEMap.insert(N, InsertToken);
11647 InsertNode(N);
11648 SDValue V(N, 0);
11649 NewSDValueDbgMsg(V, "Creating new node: ", this);
11650 return V;
11651}
11652
11654 const SDLoc &dl, ArrayRef<SDValue> Ops,
11655 MachineMemOperand *MMO,
11656 ISD::MemIndexType IndexType) {
11657 assert(Ops.size() == 7 && "Incompatible number of operands");
11658
11660 ID.AddInteger(MemVT.getRawBits());
11661 ID.AddInteger(getSyntheticNodeSubclassData<MaskedHistogramSDNode>(
11662 dl.getIROrder(), VTs, MemVT, MMO, IndexType));
11663 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11664 ID.AddInteger(MMO->getFlags());
11665 FoldingSetInsertToken InsertToken;
11666 if (SDNode *E = lookupNode(ID, dl, InsertToken)) {
11667 cast<MaskedGatherSDNode>(E)->refineAlignment(MMO);
11668 return SDValue(E, 0);
11669 }
11670
11671 auto *N = newSDNode<MaskedHistogramSDNode>(dl.getIROrder(), dl.getDebugLoc(),
11672 VTs, MemVT, MMO, IndexType);
11673 createOperands(N, Ops);
11674
11675 assert(N->getMask().getValueType().getVectorElementCount() ==
11676 N->getIndex().getValueType().getVectorElementCount() &&
11677 "Vector width mismatch between mask and data");
11678 assert(isa<ConstantSDNode>(N->getScale()) &&
11679 N->getScale()->getAsAPIntVal().isPowerOf2() &&
11680 "Scale should be a constant power of 2");
11681 assert(N->getInc().getValueType().isInteger() && "Non integer update value");
11682
11683 CSEMap.insert(N, InsertToken);
11684 InsertNode(N);
11685 SDValue V(N, 0);
11686 NewSDValueDbgMsg(V, "Creating new node: ", this);
11687 return V;
11688}
11689
11691 SDValue Ptr, SDValue Mask, SDValue EVL,
11692 MachineMemOperand *MMO) {
11693 SDVTList VTs = getVTList(VT, EVL.getValueType(), MVT::Other);
11694 SDValue Ops[] = {Chain, Ptr, Mask, EVL};
11695 SDNodeKey ID(ISD::VP_LOAD_FF, VTs, Ops);
11696 ID.AddInteger(VT.getRawBits());
11697 ID.AddInteger(getSyntheticNodeSubclassData<VPLoadFFSDNode>(DL.getIROrder(),
11698 VTs, VT, MMO));
11699 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11700 ID.AddInteger(MMO->getFlags());
11701 FoldingSetInsertToken InsertToken;
11702 if (SDNode *E = lookupNode(ID, DL, InsertToken)) {
11703 cast<VPLoadFFSDNode>(E)->refineAlignment(MMO);
11704 return SDValue(E, 0);
11705 }
11706 auto *N = newSDNode<VPLoadFFSDNode>(DL.getIROrder(), DL.getDebugLoc(), VTs,
11707 VT, MMO);
11708 createOperands(N, Ops);
11709
11710 CSEMap.insert(N, InsertToken);
11711 InsertNode(N);
11712 SDValue V(N, 0);
11713 NewSDValueDbgMsg(V, "Creating new node: ", this);
11714 return V;
11715}
11716
11718 EVT MemVT, MachineMemOperand *MMO) {
11719 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
11720 SDVTList VTs = getVTList(MVT::Other);
11721 SDValue Ops[] = {Chain, Ptr};
11723 ID.AddInteger(MemVT.getRawBits());
11724 ID.AddInteger(getSyntheticNodeSubclassData<FPStateAccessSDNode>(
11725 ISD::GET_FPENV_MEM, dl.getIROrder(), VTs, MemVT, MMO));
11726 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11727 ID.AddInteger(MMO->getFlags());
11728 FoldingSetInsertToken InsertToken;
11729 if (SDNode *E = lookupNode(ID, dl, InsertToken))
11730 return SDValue(E, 0);
11731
11732 auto *N = newSDNode<FPStateAccessSDNode>(ISD::GET_FPENV_MEM, dl.getIROrder(),
11733 dl.getDebugLoc(), VTs, MemVT, MMO);
11734 createOperands(N, Ops);
11735
11736 CSEMap.insert(N, InsertToken);
11737 InsertNode(N);
11738 SDValue V(N, 0);
11739 NewSDValueDbgMsg(V, "Creating new node: ", this);
11740 return V;
11741}
11742
11744 EVT MemVT, MachineMemOperand *MMO) {
11745 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
11746 SDVTList VTs = getVTList(MVT::Other);
11747 SDValue Ops[] = {Chain, Ptr};
11749 ID.AddInteger(MemVT.getRawBits());
11750 ID.AddInteger(getSyntheticNodeSubclassData<FPStateAccessSDNode>(
11751 ISD::SET_FPENV_MEM, dl.getIROrder(), VTs, MemVT, MMO));
11752 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11753 ID.AddInteger(MMO->getFlags());
11754 FoldingSetInsertToken InsertToken;
11755 if (SDNode *E = lookupNode(ID, dl, InsertToken))
11756 return SDValue(E, 0);
11757
11758 auto *N = newSDNode<FPStateAccessSDNode>(ISD::SET_FPENV_MEM, dl.getIROrder(),
11759 dl.getDebugLoc(), VTs, MemVT, MMO);
11760 createOperands(N, Ops);
11761
11762 CSEMap.insert(N, InsertToken);
11763 InsertNode(N);
11764 SDValue V(N, 0);
11765 NewSDValueDbgMsg(V, "Creating new node: ", this);
11766 return V;
11767}
11768
11770 // select undef, T, F --> T (if T is a constant), otherwise F
11771 // select, ?, undef, F --> F
11772 // select, ?, T, undef --> T
11773 if (Cond.isUndef())
11774 return isConstantValueOfAnyType(T) ? T : F;
11775 if (T.isUndef())
11777 if (F.isUndef())
11779
11780 // select true, T, F --> T
11781 // select false, T, F --> F
11782 if (auto C = isBoolConstant(Cond))
11783 return *C ? T : F;
11784
11785 // select ?, T, T --> T
11786 if (T == F)
11787 return T;
11788
11789 return SDValue();
11790}
11791
11793 // shift undef, Y --> 0 (can always assume that the undef value is 0)
11794 if (X.isUndef())
11795 return getConstant(0, SDLoc(X.getNode()), X.getValueType());
11796 // shift X, undef --> undef (because it may shift by the bitwidth)
11797 if (Y.isUndef())
11798 return getUNDEF(X.getValueType());
11799
11800 // shift 0, Y --> 0
11801 // shift X, 0 --> X
11803 return X;
11804
11805 // shift X, C >= bitwidth(X) --> undef
11806 // All vector elements must be too big (or undef) to avoid partial undefs.
11807 auto isShiftTooBig = [X](ConstantSDNode *Val) {
11808 return !Val || Val->getAPIntValue().uge(X.getScalarValueSizeInBits());
11809 };
11810 if (ISD::matchUnaryPredicate(Y, isShiftTooBig, true))
11811 return getUNDEF(X.getValueType());
11812
11813 // shift i1/vXi1 X, Y --> X (any non-zero shift amount is undefined).
11814 if (X.getValueType().getScalarType() == MVT::i1)
11815 return X;
11816
11817 return SDValue();
11818}
11819
11821 SDNodeFlags Flags) {
11822 // If this operation has 'nnan' or 'ninf' and at least 1 disallowed operand
11823 // (an undef operand can be chosen to be Nan/Inf), then the result of this
11824 // operation is poison. That result can be relaxed to undef.
11825 ConstantFPSDNode *XC = isConstOrConstSplatFP(X, /* AllowUndefs */ true);
11826 ConstantFPSDNode *YC = isConstOrConstSplatFP(Y, /* AllowUndefs */ true);
11827 bool HasNan = (XC && XC->getValueAPF().isNaN()) ||
11828 (YC && YC->getValueAPF().isNaN());
11829 bool HasInf = (XC && XC->getValueAPF().isInfinity()) ||
11830 (YC && YC->getValueAPF().isInfinity());
11831
11832 if (Flags.hasNoNaNs() && (HasNan || X.isUndef() || Y.isUndef()))
11833 return getUNDEF(X.getValueType());
11834
11835 if (Flags.hasNoInfs() && (HasInf || X.isUndef() || Y.isUndef()))
11836 return getUNDEF(X.getValueType());
11837
11838 if (!YC)
11839 return SDValue();
11840
11841 // X + -0.0 --> X
11842 if (Opcode == ISD::FADD)
11843 if (YC->getValueAPF().isNegZero())
11844 return X;
11845
11846 // X - +0.0 --> X
11847 if (Opcode == ISD::FSUB)
11848 if (YC->getValueAPF().isPosZero())
11849 return X;
11850
11851 // X * 1.0 --> X
11852 // X / 1.0 --> X
11853 if (Opcode == ISD::FMUL || Opcode == ISD::FDIV)
11854 if (YC->getValueAPF().isOne())
11855 return X;
11856
11857 // X * 0.0 --> 0.0
11858 if (Opcode == ISD::FMUL && Flags.hasNoNaNs() && Flags.hasNoSignedZeros())
11859 if (YC->getValueAPF().isZero())
11860 return getConstantFP(0.0, SDLoc(Y), Y.getValueType());
11861
11862 return SDValue();
11863}
11864
11866 SDValue Ptr, SDValue SV, unsigned Align) {
11867 SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, dl, MVT::i32) };
11868 return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops);
11869}
11870
11871SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
11873 switch (Ops.size()) {
11874 case 0: return getNode(Opcode, DL, VT);
11875 case 1: return getNode(Opcode, DL, VT, Ops[0].get());
11876 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
11877 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
11878 default: break;
11879 }
11880
11881 // Copy from an SDUse array into an SDValue array for use with
11882 // the regular getNode logic.
11884 return getNode(Opcode, DL, VT, NewOps);
11885}
11886
11887SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
11889 SDNodeFlags Flags;
11890 if (Inserter)
11891 Flags = Inserter->getFlags();
11892 return getNode(Opcode, DL, VT, Ops, Flags);
11893}
11894
11895SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
11896 ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
11897 unsigned NumOps = Ops.size();
11898 switch (NumOps) {
11899 case 0: return getNode(Opcode, DL, VT);
11900 case 1: return getNode(Opcode, DL, VT, Ops[0], Flags);
11901 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Flags);
11902 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2], Flags);
11903 default: break;
11904 }
11905
11906#ifndef NDEBUG
11907 for (const auto &Op : Ops)
11908 assert(Op.getOpcode() != ISD::DELETED_NODE &&
11909 "Operand is DELETED_NODE!");
11910#endif
11911
11912 switch (Opcode) {
11913 default: break;
11914 case ISD::BUILD_VECTOR:
11915 // Attempt to simplify BUILD_VECTOR.
11916 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
11917 return V;
11918 break;
11920 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
11921 return V;
11922 break;
11923 case ISD::SELECT_CC:
11924 assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
11925 assert(Ops[0].getValueType() == Ops[1].getValueType() &&
11926 "LHS and RHS of condition must have same type!");
11927 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
11928 "True and False arms of SelectCC must have same type!");
11929 assert(Ops[2].getValueType() == VT &&
11930 "select_cc node must be of same type as true and false value!");
11931 assert((!Ops[0].getValueType().isVector() ||
11932 Ops[0].getValueType().getVectorElementCount() ==
11933 VT.getVectorElementCount()) &&
11934 "Expected select_cc with vector result to have the same sized "
11935 "comparison type!");
11936 break;
11937 case ISD::BR_CC:
11938 assert(NumOps == 5 && "BR_CC takes 5 operands!");
11939 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
11940 "LHS/RHS of comparison should match types!");
11941 break;
11942 case ISD::VP_REDUCE_MUL:
11943 // If it is VP_REDUCE_MUL mask operation then turn it to VP_REDUCE_AND
11944 if (VT == MVT::i1)
11945 Opcode = ISD::VP_REDUCE_AND;
11946 break;
11947 case ISD::VP_REDUCE_ADD:
11948 // If it is VP_REDUCE_ADD mask operation then turn it to VP_REDUCE_XOR
11949 if (VT == MVT::i1)
11950 Opcode = ISD::VP_REDUCE_XOR;
11951 break;
11952 case ISD::VP_REDUCE_SMAX:
11953 case ISD::VP_REDUCE_UMIN:
11954 // If it is VP_REDUCE_SMAX/VP_REDUCE_UMIN mask operation then turn it to
11955 // VP_REDUCE_AND.
11956 if (VT == MVT::i1)
11957 Opcode = ISD::VP_REDUCE_AND;
11958 break;
11959 case ISD::VP_REDUCE_SMIN:
11960 case ISD::VP_REDUCE_UMAX:
11961 // If it is VP_REDUCE_SMIN/VP_REDUCE_UMAX mask operation then turn it to
11962 // VP_REDUCE_OR.
11963 if (VT == MVT::i1)
11964 Opcode = ISD::VP_REDUCE_OR;
11965 break;
11966 }
11967
11968 // Memoize nodes.
11969 SDNode *N;
11970 SDVTList VTs = getVTList(VT);
11971
11972 if (VT != MVT::Glue) {
11973 SDNodeKey ID(Opcode, VTs, Ops);
11974 FoldingSetInsertToken InsertToken;
11975
11976 if (SDNode *E = lookupNode(ID, DL, InsertToken)) {
11977 E->intersectFlagsWith(Flags);
11978 return SDValue(E, 0);
11979 }
11980
11981 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
11982 createOperands(N, Ops);
11983
11984 CSEMap.insert(N, InsertToken);
11985 } else {
11986 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
11987 createOperands(N, Ops);
11988 }
11989
11990 N->setFlags(Flags);
11991 InsertNode(N);
11992 SDValue V(N, 0);
11993 NewSDValueDbgMsg(V, "Creating new node: ", this);
11994 return V;
11995}
11996
11997SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
11998 ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) {
11999 SDNodeFlags Flags;
12000 if (Inserter)
12001 Flags = Inserter->getFlags();
12002 return getNode(Opcode, DL, getVTList(ResultTys), Ops, Flags);
12003}
12004
12005SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
12007 const SDNodeFlags Flags) {
12008 return getNode(Opcode, DL, getVTList(ResultTys), Ops, Flags);
12009}
12010
12011SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
12013 SDNodeFlags Flags;
12014 if (Inserter)
12015 Flags = Inserter->getFlags();
12016 return getNode(Opcode, DL, VTList, Ops, Flags);
12017}
12018
12019SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
12020 ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
12021 if (VTList.NumVTs == 1)
12022 return getNode(Opcode, DL, VTList.VTs[0], Ops, Flags);
12023
12024#ifndef NDEBUG
12025 for (const auto &Op : Ops)
12026 assert(Op.getOpcode() != ISD::DELETED_NODE &&
12027 "Operand is DELETED_NODE!");
12028#endif
12029
12030 switch (Opcode) {
12031 case ISD::SADDO:
12032 case ISD::UADDO:
12033 case ISD::SSUBO:
12034 case ISD::USUBO: {
12035 assert(VTList.NumVTs == 2 && Ops.size() == 2 &&
12036 "Invalid add/sub overflow op!");
12037 assert(VTList.VTs[0].isInteger() && VTList.VTs[1].isInteger() &&
12038 Ops[0].getValueType() == Ops[1].getValueType() &&
12039 Ops[0].getValueType() == VTList.VTs[0] &&
12040 "Binary operator types must match!");
12041 SDValue N1 = Ops[0], N2 = Ops[1];
12042 canonicalizeCommutativeBinop(Opcode, N1, N2);
12043
12044 // (X +- 0) -> X with zero-overflow.
12045 ConstantSDNode *N2CV = isConstOrConstSplat(N2, /*AllowUndefs*/ false,
12046 /*AllowTruncation*/ true);
12047 if (N2CV && N2CV->isZero()) {
12048 SDValue ZeroOverFlow = getConstant(0, DL, VTList.VTs[1]);
12049 return getNode(ISD::MERGE_VALUES, DL, VTList, {N1, ZeroOverFlow}, Flags);
12050 }
12051
12052 if (VTList.VTs[0].getScalarType() == MVT::i1 &&
12053 VTList.VTs[1].getScalarType() == MVT::i1) {
12054 SDValue F1 = getFreeze(N1);
12055 SDValue F2 = getFreeze(N2);
12056 // {vXi1,vXi1} (u/s)addo(vXi1 x, vXi1y) -> {xor(x,y),and(x,y)}
12057 if (Opcode == ISD::UADDO || Opcode == ISD::SADDO)
12058 return getNode(ISD::MERGE_VALUES, DL, VTList,
12059 {getNode(ISD::XOR, DL, VTList.VTs[0], F1, F2),
12060 getNode(ISD::AND, DL, VTList.VTs[1], F1, F2)},
12061 Flags);
12062 // {vXi1,vXi1} (u/s)subo(vXi1 x, vXi1y) -> {xor(x,y),and(~x,y)}
12063 if (Opcode == ISD::USUBO || Opcode == ISD::SSUBO) {
12064 SDValue NotF1 = getNOT(DL, F1, VTList.VTs[0]);
12065 return getNode(ISD::MERGE_VALUES, DL, VTList,
12066 {getNode(ISD::XOR, DL, VTList.VTs[0], F1, F2),
12067 getNode(ISD::AND, DL, VTList.VTs[1], NotF1, F2)},
12068 Flags);
12069 }
12070 }
12071 break;
12072 }
12073 case ISD::SADDO_CARRY:
12074 case ISD::UADDO_CARRY:
12075 case ISD::SSUBO_CARRY:
12076 case ISD::USUBO_CARRY:
12077 assert(VTList.NumVTs == 2 && Ops.size() == 3 &&
12078 "Invalid add/sub overflow op!");
12079 assert(VTList.VTs[0].isInteger() && VTList.VTs[1].isInteger() &&
12080 Ops[0].getValueType() == Ops[1].getValueType() &&
12081 Ops[0].getValueType() == VTList.VTs[0] &&
12082 Ops[2].getValueType() == VTList.VTs[1] &&
12083 "Binary operator types must match!");
12084 break;
12085 case ISD::SMUL_LOHI:
12086 case ISD::UMUL_LOHI: {
12087 assert(VTList.NumVTs == 2 && Ops.size() == 2 && "Invalid mul lo/hi op!");
12088 assert(VTList.VTs[0].isInteger() && VTList.VTs[0] == VTList.VTs[1] &&
12089 VTList.VTs[0] == Ops[0].getValueType() &&
12090 VTList.VTs[0] == Ops[1].getValueType() &&
12091 "Binary operator types must match!");
12092 // Constant fold.
12095 if (LHS && RHS) {
12096 unsigned Width = VTList.VTs[0].getScalarSizeInBits();
12097 unsigned OutWidth = Width * 2;
12098 APInt Val = LHS->getAPIntValue();
12099 APInt Mul = RHS->getAPIntValue();
12100 if (Opcode == ISD::SMUL_LOHI) {
12101 Val = Val.sext(OutWidth);
12102 Mul = Mul.sext(OutWidth);
12103 } else {
12104 Val = Val.zext(OutWidth);
12105 Mul = Mul.zext(OutWidth);
12106 }
12107 Val *= Mul;
12108
12109 SDValue Hi =
12110 getConstant(Val.extractBits(Width, Width), DL, VTList.VTs[0]);
12111 SDValue Lo = getConstant(Val.trunc(Width), DL, VTList.VTs[0]);
12112 return getNode(ISD::MERGE_VALUES, DL, VTList, {Lo, Hi}, Flags);
12113 }
12114 break;
12115 }
12116 case ISD::FFREXP: {
12117 assert(VTList.NumVTs == 2 && Ops.size() == 1 && "Invalid ffrexp op!");
12118 assert(VTList.VTs[0].isFloatingPoint() && VTList.VTs[1].isInteger() &&
12119 VTList.VTs[0] == Ops[0].getValueType() && "frexp type mismatch");
12120
12122 int FrexpExp;
12123 APFloat FrexpMant =
12124 frexp(C->getValueAPF(), FrexpExp, APFloat::rmNearestTiesToEven);
12125 SDValue Result0 = getConstantFP(FrexpMant, DL, VTList.VTs[0]);
12126 SDValue Result1 = getSignedConstant(FrexpMant.isFinite() ? FrexpExp : 0,
12127 DL, VTList.VTs[1]);
12128 return getNode(ISD::MERGE_VALUES, DL, VTList, {Result0, Result1}, Flags);
12129 }
12130
12131 break;
12132 }
12134 assert(VTList.NumVTs == 2 && Ops.size() == 2 &&
12135 "Invalid STRICT_FP_EXTEND!");
12136 assert(VTList.VTs[0].isFloatingPoint() &&
12137 Ops[1].getValueType().isFloatingPoint() && "Invalid FP cast!");
12138 assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
12139 "STRICT_FP_EXTEND result type should be vector iff the operand "
12140 "type is vector!");
12141 assert((!VTList.VTs[0].isVector() ||
12142 VTList.VTs[0].getVectorElementCount() ==
12143 Ops[1].getValueType().getVectorElementCount()) &&
12144 "Vector element count mismatch!");
12145 assert(Ops[1].getValueType().bitsLT(VTList.VTs[0]) &&
12146 "Invalid fpext node, dst <= src!");
12147 break;
12149 assert(VTList.NumVTs == 2 && Ops.size() == 3 && "Invalid STRICT_FP_ROUND!");
12150 assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
12151 "STRICT_FP_ROUND result type should be vector iff the operand "
12152 "type is vector!");
12153 assert((!VTList.VTs[0].isVector() ||
12154 VTList.VTs[0].getVectorElementCount() ==
12155 Ops[1].getValueType().getVectorElementCount()) &&
12156 "Vector element count mismatch!");
12157 assert(VTList.VTs[0].isFloatingPoint() &&
12158 Ops[1].getValueType().isFloatingPoint() &&
12159 VTList.VTs[0].bitsLT(Ops[1].getValueType()) &&
12160 Ops[2].getOpcode() == ISD::TargetConstant &&
12161 (Ops[2]->getAsZExtVal() == 0 || Ops[2]->getAsZExtVal() == 1) &&
12162 "Invalid STRICT_FP_ROUND!");
12163 break;
12164 }
12165
12166 // Memoize the node unless it returns a glue result.
12167 SDNode *N;
12168 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
12169 SDNodeKey ID(Opcode, VTList, Ops);
12170 FoldingSetInsertToken InsertToken;
12171 if (SDNode *E = lookupNode(ID, DL, InsertToken)) {
12172 E->intersectFlagsWith(Flags);
12173 return SDValue(E, 0);
12174 }
12175
12176 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
12177 createOperands(N, Ops);
12178 CSEMap.insert(N, InsertToken);
12179 } else {
12180 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
12181 createOperands(N, Ops);
12182 }
12183
12184 N->setFlags(Flags);
12185 InsertNode(N);
12186 SDValue V(N, 0);
12187 NewSDValueDbgMsg(V, "Creating new node: ", this);
12188 return V;
12189}
12190
12191SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
12192 SDVTList VTList) {
12193 return getNode(Opcode, DL, VTList, ArrayRef<SDValue>());
12194}
12195
12196SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
12197 SDValue N1) {
12198 SDValue Ops[] = { N1 };
12199 return getNode(Opcode, DL, VTList, Ops);
12200}
12201
12202SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
12203 SDValue N1, SDValue N2) {
12204 SDValue Ops[] = { N1, N2 };
12205 return getNode(Opcode, DL, VTList, Ops);
12206}
12207
12208SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
12209 SDValue N1, SDValue N2, SDValue N3) {
12210 SDValue Ops[] = { N1, N2, N3 };
12211 return getNode(Opcode, DL, VTList, Ops);
12212}
12213
12214SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
12215 SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
12216 SDValue Ops[] = { N1, N2, N3, N4 };
12217 return getNode(Opcode, DL, VTList, Ops);
12218}
12219
12220SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
12221 SDValue N1, SDValue N2, SDValue N3, SDValue N4,
12222 SDValue N5) {
12223 SDValue Ops[] = { N1, N2, N3, N4, N5 };
12224 return getNode(Opcode, DL, VTList, Ops);
12225}
12226
12228 if (!VT.isExtended())
12229 return makeVTList(SDNode::getValueTypeList(VT.getSimpleVT()), 1);
12230
12231 EVT VTs[] = {VT};
12232 return getVTList(VTs);
12233}
12234
12236 EVT VTs[] = {VT1, VT2};
12237 return getVTList(VTs);
12238}
12239
12241 EVT VTs[] = {VT1, VT2, VT3};
12242 return getVTList(VTs);
12243}
12244
12246 EVT VTs[] = {VT1, VT2, VT3, VT4};
12247 return getVTList(VTs);
12248}
12249
12251 auto It = VTLists.find(VTs);
12252 if (It == VTLists.end()) {
12253 EVT *Array = Allocator.Allocate<EVT>(VTs.size());
12254 llvm::copy(VTs, Array);
12255 It = VTLists.insert(ArrayRef(Array, VTs.size())).first;
12256 }
12257 return makeVTList(It->data(), It->size());
12258}
12259
12260/// UpdateNodeOperands - *Mutate* the specified node in-place to have the
12261/// specified operands. If the resultant node already exists in the DAG,
12262/// this does not modify the specified node, instead it returns the node that
12263/// already exists. If the resultant node does not exist in the DAG, the
12264/// input node is returned. As a degenerate case, if you specify the same
12265/// input operands as the node already has, the input node is returned.
12267 assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
12268
12269 // Check to see if there is no change.
12270 if (Op == N->getOperand(0)) return N;
12271
12272 // See if the modified node already exists.
12273 FoldingSetInsertToken InsertToken;
12274 if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertToken))
12275 return Existing;
12276
12277 // Nope it doesn't. Remove the node from its current place in the maps.
12278 if (InsertToken)
12279 if (!RemoveNodeFromCSEMaps(N))
12280 InsertToken = {};
12281
12282 // Now we update the operands.
12283 N->OperandList[0].set(Op);
12284
12286 // If this gets put into a CSE map, add it.
12287 if (InsertToken)
12288 CSEMap.insert(N, InsertToken);
12289 return N;
12290}
12291
12293 assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
12294
12295 // Check to see if there is no change.
12296 if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
12297 return N; // No operands changed, just return the input node.
12298
12299 // See if the modified node already exists.
12300 FoldingSetInsertToken InsertToken;
12301 if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertToken))
12302 return Existing;
12303
12304 // Nope it doesn't. Remove the node from its current place in the maps.
12305 if (InsertToken)
12306 if (!RemoveNodeFromCSEMaps(N))
12307 InsertToken = {};
12308
12309 // Now we update the operands.
12310 if (N->OperandList[0] != Op1)
12311 N->OperandList[0].set(Op1);
12312 if (N->OperandList[1] != Op2)
12313 N->OperandList[1].set(Op2);
12314
12316 // If this gets put into a CSE map, add it.
12317 if (InsertToken)
12318 CSEMap.insert(N, InsertToken);
12319 return N;
12320}
12321
12324 SDValue Ops[] = { Op1, Op2, Op3 };
12325 return UpdateNodeOperands(N, Ops);
12326}
12327
12330 SDValue Op3, SDValue Op4) {
12331 SDValue Ops[] = { Op1, Op2, Op3, Op4 };
12332 return UpdateNodeOperands(N, Ops);
12333}
12334
12337 SDValue Op3, SDValue Op4, SDValue Op5) {
12338 SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 };
12339 return UpdateNodeOperands(N, Ops);
12340}
12341
12344 unsigned NumOps = Ops.size();
12345 assert(N->getNumOperands() == NumOps &&
12346 "Update with wrong number of operands");
12347
12348 // If no operands changed just return the input node.
12349 if (std::equal(Ops.begin(), Ops.end(), N->op_begin()))
12350 return N;
12351
12352 // See if the modified node already exists.
12353 FoldingSetInsertToken InsertToken;
12354 if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertToken))
12355 return Existing;
12356
12357 // Nope it doesn't. Remove the node from its current place in the maps.
12358 if (InsertToken)
12359 if (!RemoveNodeFromCSEMaps(N))
12360 InsertToken = {};
12361
12362 // Now we update the operands.
12363 for (unsigned i = 0; i != NumOps; ++i)
12364 if (N->OperandList[i] != Ops[i])
12365 N->OperandList[i].set(Ops[i]);
12366
12368 // If this gets put into a CSE map, add it.
12369 if (InsertToken)
12370 CSEMap.insert(N, InsertToken);
12371 return N;
12372}
12373
12374/// DropOperands - Release the operands and set this node to have
12375/// zero operands.
12377 // Unlike the code in MorphNodeTo that does this, we don't need to
12378 // watch for dead nodes here.
12379 for (op_iterator I = op_begin(), E = op_end(); I != E; ) {
12380 SDUse &Use = *I++;
12381 Use.set(SDValue());
12382 }
12383}
12384
12386 ArrayRef<MachineMemOperand *> NewMemRefs) {
12387 if (NewMemRefs.empty()) {
12388 N->clearMemRefs();
12389 return;
12390 }
12391
12392 // Check if we can avoid allocating by storing a single reference directly.
12393 if (NewMemRefs.size() == 1) {
12394 N->MemRefs = NewMemRefs[0];
12395 N->NumMemRefs = 1;
12396 return;
12397 }
12398
12399 MachineMemOperand **MemRefsBuffer =
12400 Allocator.template Allocate<MachineMemOperand *>(NewMemRefs.size());
12401 llvm::copy(NewMemRefs, MemRefsBuffer);
12402 N->MemRefs = MemRefsBuffer;
12403 N->NumMemRefs = static_cast<int>(NewMemRefs.size());
12404}
12405
12406/// SelectNodeTo - These are wrappers around MorphNodeTo that accept a
12407/// machine opcode.
12408///
12410 EVT VT) {
12411 SDVTList VTs = getVTList(VT);
12412 return SelectNodeTo(N, MachineOpc, VTs, {});
12413}
12414
12416 EVT VT, SDValue Op1) {
12417 SDVTList VTs = getVTList(VT);
12418 SDValue Ops[] = { Op1 };
12419 return SelectNodeTo(N, MachineOpc, VTs, Ops);
12420}
12421
12423 EVT VT, SDValue Op1,
12424 SDValue Op2) {
12425 SDVTList VTs = getVTList(VT);
12426 SDValue Ops[] = { Op1, Op2 };
12427 return SelectNodeTo(N, MachineOpc, VTs, Ops);
12428}
12429
12431 EVT VT, SDValue Op1,
12432 SDValue Op2, SDValue Op3) {
12433 SDVTList VTs = getVTList(VT);
12434 SDValue Ops[] = { Op1, Op2, Op3 };
12435 return SelectNodeTo(N, MachineOpc, VTs, Ops);
12436}
12437
12440 SDVTList VTs = getVTList(VT);
12441 return SelectNodeTo(N, MachineOpc, VTs, Ops);
12442}
12443
12445 EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) {
12446 SDVTList VTs = getVTList(VT1, VT2);
12447 return SelectNodeTo(N, MachineOpc, VTs, Ops);
12448}
12449
12451 EVT VT1, EVT VT2) {
12452 SDVTList VTs = getVTList(VT1, VT2);
12453 return SelectNodeTo(N, MachineOpc, VTs, {});
12454}
12455
12457 EVT VT1, EVT VT2, EVT VT3,
12459 SDVTList VTs = getVTList(VT1, VT2, VT3);
12460 return SelectNodeTo(N, MachineOpc, VTs, Ops);
12461}
12462
12464 EVT VT1, EVT VT2,
12465 SDValue Op1, SDValue Op2) {
12466 SDVTList VTs = getVTList(VT1, VT2);
12467 SDValue Ops[] = { Op1, Op2 };
12468 return SelectNodeTo(N, MachineOpc, VTs, Ops);
12469}
12470
12473 SDNode *New = MorphNodeTo(N, ~MachineOpc, VTs, Ops);
12474 // Reset the NodeID to -1.
12475 New->setNodeId(-1);
12476 if (New != N) {
12477 ReplaceAllUsesWith(N, New);
12479 }
12480 return New;
12481}
12482
12483/// UpdateSDLocOnMergeSDNode - If the opt level is -O0 then it throws away
12484/// the line number information on the merged node since it is not possible to
12485/// preserve the information that operation is associated with multiple lines.
12486/// This will make the debugger working better at -O0, were there is a higher
12487/// probability having other instructions associated with that line.
12488///
12489/// For IROrder, we keep the smaller of the two
12490SDNode *SelectionDAG::UpdateSDLocOnMergeSDNode(SDNode *N, const SDLoc &OLoc) {
12491 DebugLoc NLoc = N->getDebugLoc();
12492 if (NLoc && OptLevel == CodeGenOptLevel::None && OLoc.getDebugLoc() != NLoc) {
12493 N->setDebugLoc(DebugLoc());
12494 }
12495 unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder());
12496 N->setIROrder(Order);
12497 return N;
12498}
12499
12500/// MorphNodeTo - This *mutates* the specified node to have the specified
12501/// return type, opcode, and operands.
12502///
12503/// Note that MorphNodeTo returns the resultant node. If there is already a
12504/// node of the specified opcode and operands, it returns that node instead of
12505/// the current one. Note that the SDLoc need not be the same.
12506///
12507/// Using MorphNodeTo is faster than creating a new node and swapping it in
12508/// with ReplaceAllUsesWith both because it often avoids allocating a new
12509/// node, and because it doesn't require CSE recalculation for any of
12510/// the node's users.
12511///
12512/// However, note that MorphNodeTo recursively deletes dead nodes from the DAG.
12513/// As a consequence it isn't appropriate to use from within the DAG combiner or
12514/// the legalizer which maintain worklists that would need to be updated when
12515/// deleting things.
12518 // If an identical node already exists, use it.
12519 FoldingSetInsertToken InsertToken;
12520 if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) {
12521 SDNodeKey ID(Opc, VTs, Ops);
12522 AddNodeIDCustom(ID.Tail, N, Opc);
12523 if (SDNode *ON = lookupNode(ID, SDLoc(N), InsertToken))
12524 return UpdateSDLocOnMergeSDNode(ON, SDLoc(N));
12525 }
12526
12527 if (!RemoveNodeFromCSEMaps(N))
12528 InsertToken = {};
12529
12530 // Start the morphing.
12531 N->NodeType = Opc;
12532 N->ValueList = VTs.VTs;
12533 N->NumValues = VTs.NumVTs;
12534
12535 // Clear the operands list, updating used nodes to remove this from their
12536 // use list. Keep track of any operands that become dead as a result.
12537 SmallPtrSet<SDNode*, 16> DeadNodeSet;
12538 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
12539 SDUse &Use = *I++;
12540 SDNode *Used = Use.getNode();
12541 Use.set(SDValue());
12542 if (Used->use_empty())
12543 DeadNodeSet.insert(Used);
12544 }
12545
12546 // For MachineNode, initialize the memory references information.
12548 MN->clearMemRefs();
12549
12550 // Swap for an appropriately sized array from the recycler.
12551 removeOperands(N);
12552 createOperands(N, Ops);
12553
12554 // Delete any nodes that are still dead after adding the uses for the
12555 // new operands.
12556 if (!DeadNodeSet.empty()) {
12557 SmallVector<SDNode *, 16> DeadNodes;
12558 for (SDNode *N : DeadNodeSet)
12559 if (N->use_empty())
12560 DeadNodes.push_back(N);
12561 RemoveDeadNodes(DeadNodes);
12562 }
12563
12564 if (InsertToken)
12565 CSEMap.insert(N, InsertToken); // Memoize the new node.
12566 return N;
12567}
12568
12570 unsigned OrigOpc = Node->getOpcode();
12571 unsigned NewOpc;
12572 switch (OrigOpc) {
12573 default:
12574 llvm_unreachable("mutateStrictFPToFP called with unexpected opcode!");
12575#define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \
12576 case ISD::STRICT_##DAGN: NewOpc = ISD::DAGN; break;
12577#define CMP_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \
12578 case ISD::STRICT_##DAGN: NewOpc = ISD::SETCC; break;
12579#include "llvm/IR/ConstrainedOps.def"
12580 }
12581
12582 assert(Node->getNumValues() == 2 && "Unexpected number of results!");
12583
12584 // We're taking this node out of the chain, so we need to re-link things.
12585 SDValue InputChain = Node->getOperand(0);
12586 SDValue OutputChain = SDValue(Node, 1);
12587 ReplaceAllUsesOfValueWith(OutputChain, InputChain);
12588
12590 for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
12591 Ops.push_back(Node->getOperand(i));
12592
12593 SDVTList VTs = getVTList(Node->getValueType(0));
12594 SDNode *Res = MorphNodeTo(Node, NewOpc, VTs, Ops);
12595
12596 // MorphNodeTo can operate in two ways: if an existing node with the
12597 // specified operands exists, it can just return it. Otherwise, it
12598 // updates the node in place to have the requested operands.
12599 if (Res == Node) {
12600 // If we updated the node in place, reset the node ID. To the isel,
12601 // this should be just like a newly allocated machine node.
12602 Res->setNodeId(-1);
12603 } else {
12606 }
12607
12608 return Res;
12609}
12610
12611/// getMachineNode - These are used for target selectors to create a new node
12612/// with specified return type(s), MachineInstr opcode, and operands.
12613///
12614/// Note that getMachineNode returns the resultant node. If there is already a
12615/// node of the specified opcode and operands, it returns that node instead of
12616/// the current one.
12618 EVT VT) {
12619 SDVTList VTs = getVTList(VT);
12620 return getMachineNode(Opcode, dl, VTs, {});
12621}
12622
12624 EVT VT, SDValue Op1) {
12625 SDVTList VTs = getVTList(VT);
12626 SDValue Ops[] = { Op1 };
12627 return getMachineNode(Opcode, dl, VTs, Ops);
12628}
12629
12631 EVT VT, SDValue Op1, SDValue Op2) {
12632 SDVTList VTs = getVTList(VT);
12633 SDValue Ops[] = { Op1, Op2 };
12634 return getMachineNode(Opcode, dl, VTs, Ops);
12635}
12636
12638 EVT VT, SDValue Op1, SDValue Op2,
12639 SDValue Op3) {
12640 SDVTList VTs = getVTList(VT);
12641 SDValue Ops[] = { Op1, Op2, Op3 };
12642 return getMachineNode(Opcode, dl, VTs, Ops);
12643}
12644
12647 SDVTList VTs = getVTList(VT);
12648 return getMachineNode(Opcode, dl, VTs, Ops);
12649}
12650
12652 EVT VT1, EVT VT2, SDValue Op1,
12653 SDValue Op2) {
12654 SDVTList VTs = getVTList(VT1, VT2);
12655 SDValue Ops[] = { Op1, Op2 };
12656 return getMachineNode(Opcode, dl, VTs, Ops);
12657}
12658
12660 EVT VT1, EVT VT2, SDValue Op1,
12661 SDValue Op2, SDValue Op3) {
12662 SDVTList VTs = getVTList(VT1, VT2);
12663 SDValue Ops[] = { Op1, Op2, Op3 };
12664 return getMachineNode(Opcode, dl, VTs, Ops);
12665}
12666
12668 EVT VT1, EVT VT2,
12670 SDVTList VTs = getVTList(VT1, VT2);
12671 return getMachineNode(Opcode, dl, VTs, Ops);
12672}
12673
12675 EVT VT1, EVT VT2, EVT VT3,
12676 SDValue Op1, SDValue Op2) {
12677 SDVTList VTs = getVTList(VT1, VT2, VT3);
12678 SDValue Ops[] = { Op1, Op2 };
12679 return getMachineNode(Opcode, dl, VTs, Ops);
12680}
12681
12683 EVT VT1, EVT VT2, EVT VT3,
12684 SDValue Op1, SDValue Op2,
12685 SDValue Op3) {
12686 SDVTList VTs = getVTList(VT1, VT2, VT3);
12687 SDValue Ops[] = { Op1, Op2, Op3 };
12688 return getMachineNode(Opcode, dl, VTs, Ops);
12689}
12690
12692 EVT VT1, EVT VT2, EVT VT3,
12694 SDVTList VTs = getVTList(VT1, VT2, VT3);
12695 return getMachineNode(Opcode, dl, VTs, Ops);
12696}
12697
12699 ArrayRef<EVT> ResultTys,
12701 SDVTList VTs = getVTList(ResultTys);
12702 return getMachineNode(Opcode, dl, VTs, Ops);
12703}
12704
12706 SDVTList VTs,
12708 bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue;
12710 FoldingSetInsertToken InsertToken;
12711
12712 if (DoCSE) {
12713 SDNodeKey ID(~Opcode, VTs, Ops);
12714 if (SDNode *E = lookupNode(ID, DL, InsertToken)) {
12715 return cast<MachineSDNode>(UpdateSDLocOnMergeSDNode(E, DL));
12716 }
12717 }
12718
12719 // Allocate a new MachineSDNode.
12720 N = newSDNode<MachineSDNode>(~Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
12721 createOperands(N, Ops);
12722
12723 if (DoCSE)
12724 CSEMap.insert(N, InsertToken);
12725
12726 InsertNode(N);
12727 NewSDValueDbgMsg(SDValue(N, 0), "Creating new machine node: ", this);
12728 return N;
12729}
12730
12731/// getTargetExtractSubreg - A convenience function for creating
12732/// TargetOpcode::EXTRACT_SUBREG nodes.
12734 SDValue Operand) {
12735 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
12736 SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,
12737 VT, Operand, SRIdxVal);
12738 return SDValue(Subreg, 0);
12739}
12740
12741/// getTargetInsertSubreg - A convenience function for creating
12742/// TargetOpcode::INSERT_SUBREG nodes.
12744 SDValue Operand, SDValue Subreg) {
12745 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
12746 SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL,
12747 VT, Operand, Subreg, SRIdxVal);
12748 return SDValue(Result, 0);
12749}
12750
12751/// getNodeIfExists - Get the specified node if it's already available, or
12752/// else return NULL.
12755 bool AllowCommute) {
12756 SDNodeFlags Flags;
12757 if (Inserter)
12758 Flags = Inserter->getFlags();
12759 return getNodeIfExists(Opcode, VTList, Ops, Flags, AllowCommute);
12760}
12761
12764 const SDNodeFlags Flags,
12765 bool AllowCommute) {
12766 if (VTList.VTs[VTList.NumVTs - 1] == MVT::Glue)
12767 return nullptr;
12768
12769 auto Lookup = [&](ArrayRef<SDValue> LookupOps) -> SDNode * {
12770 SDNodeKey ID(Opcode, VTList, LookupOps);
12771 FoldingSetInsertToken InsertToken;
12772 if (SDNode *E = lookupNode(ID, InsertToken)) {
12773 E->intersectFlagsWith(Flags);
12774 return E;
12775 }
12776 return nullptr;
12777 };
12778
12779 if (SDNode *Existing = Lookup(Ops))
12780 return Existing;
12781
12782 if (AllowCommute && TLI->isCommutativeBinOp(Opcode))
12783 return Lookup({Ops[1], Ops[0]});
12784
12785 return nullptr;
12786}
12787
12788/// doesNodeExist - Check if a node exists without modifying its flags.
12789bool SelectionDAG::doesNodeExist(unsigned Opcode, SDVTList VTList,
12791 if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
12792 SDNodeKey ID(Opcode, VTList, Ops);
12793 FoldingSetInsertToken InsertToken;
12794 if (lookupNode(ID, SDLoc(), InsertToken))
12795 return true;
12796 }
12797 return false;
12798}
12799
12800/// getDbgValue - Creates a SDDbgValue node.
12801///
12802/// SDNode
12804 SDNode *N, unsigned R, bool IsIndirect,
12805 const DebugLoc &DL, unsigned O) {
12806 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
12807 "Expected inlined-at fields to agree");
12808 return new (DbgInfo->getAlloc())
12809 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromNode(N, R),
12810 {}, IsIndirect, DL, O,
12811 /*IsVariadic=*/false);
12812}
12813
12814/// Constant
12816 DIExpression *Expr,
12817 const Value *C,
12818 const DebugLoc &DL, unsigned O) {
12819 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
12820 "Expected inlined-at fields to agree");
12821 return new (DbgInfo->getAlloc())
12822 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromConst(C), {},
12823 /*IsIndirect=*/false, DL, O,
12824 /*IsVariadic=*/false);
12825}
12826
12827/// FrameIndex
12829 DIExpression *Expr, unsigned FI,
12830 bool IsIndirect,
12831 const DebugLoc &DL,
12832 unsigned O) {
12833 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
12834 "Expected inlined-at fields to agree");
12835 return getFrameIndexDbgValue(Var, Expr, FI, {}, IsIndirect, DL, O);
12836}
12837
12838/// FrameIndex with dependencies
12840 DIExpression *Expr, unsigned FI,
12841 ArrayRef<SDNode *> Dependencies,
12842 bool IsIndirect,
12843 const DebugLoc &DL,
12844 unsigned O) {
12845 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
12846 "Expected inlined-at fields to agree");
12847 return new (DbgInfo->getAlloc())
12848 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromFrameIdx(FI),
12849 Dependencies, IsIndirect, DL, O,
12850 /*IsVariadic=*/false);
12851}
12852
12853/// VReg
12855 Register VReg, bool IsIndirect,
12856 const DebugLoc &DL, unsigned O) {
12857 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
12858 "Expected inlined-at fields to agree");
12859 return new (DbgInfo->getAlloc())
12860 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromVReg(VReg),
12861 {}, IsIndirect, DL, O,
12862 /*IsVariadic=*/false);
12863}
12864
12867 ArrayRef<SDNode *> Dependencies,
12868 bool IsIndirect, const DebugLoc &DL,
12869 unsigned O, bool IsVariadic) {
12870 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
12871 "Expected inlined-at fields to agree");
12872 return new (DbgInfo->getAlloc())
12873 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, Locs, Dependencies, IsIndirect,
12874 DL, O, IsVariadic);
12875}
12876
12878 unsigned OffsetInBits, unsigned SizeInBits,
12879 bool InvalidateDbg) {
12880 SDNode *FromNode = From.getNode();
12881 SDNode *ToNode = To.getNode();
12882 assert(FromNode && ToNode && "Can't modify dbg values");
12883
12884 // PR35338
12885 // TODO: assert(From != To && "Redundant dbg value transfer");
12886 // TODO: assert(FromNode != ToNode && "Intranode dbg value transfer");
12887 if (From == To || FromNode == ToNode)
12888 return;
12889
12890 if (!FromNode->getHasDebugValue())
12891 return;
12892
12893 SDDbgOperand FromLocOp =
12894 SDDbgOperand::fromNode(From.getNode(), From.getResNo());
12896
12898 for (SDDbgValue *Dbg : GetDbgValues(FromNode)) {
12899 if (Dbg->isInvalidated())
12900 continue;
12901
12902 // TODO: assert(!Dbg->isInvalidated() && "Transfer of invalid dbg value");
12903
12904 // Create a new location ops vector that is equal to the old vector, but
12905 // with each instance of FromLocOp replaced with ToLocOp.
12906 bool Changed = false;
12907 auto NewLocOps = Dbg->copyLocationOps();
12908 std::replace_if(
12909 NewLocOps.begin(), NewLocOps.end(),
12910 [&Changed, FromLocOp](const SDDbgOperand &Op) {
12911 bool Match = Op == FromLocOp;
12912 Changed |= Match;
12913 return Match;
12914 },
12915 ToLocOp);
12916 // Ignore this SDDbgValue if we didn't find a matching location.
12917 if (!Changed)
12918 continue;
12919
12920 DIVariable *Var = Dbg->getVariable();
12921 auto *Expr = Dbg->getExpression();
12922 // If a fragment is requested, update the expression.
12923 if (SizeInBits) {
12924 // When splitting a larger (e.g., sign-extended) value whose
12925 // lower bits are described with an SDDbgValue, do not attempt
12926 // to transfer the SDDbgValue to the upper bits.
12927 if (auto FI = Expr->getFragmentInfo())
12928 if (OffsetInBits + SizeInBits > FI->SizeInBits)
12929 continue;
12930 auto Fragment = DIExpression::createFragmentExpression(Expr, OffsetInBits,
12931 SizeInBits);
12932 if (!Fragment)
12933 continue;
12934 Expr = *Fragment;
12935 }
12936
12937 auto AdditionalDependencies = Dbg->getAdditionalDependencies();
12938 // Clone the SDDbgValue and move it to To.
12939 SDDbgValue *Clone = getDbgValueList(
12940 Var, Expr, NewLocOps, AdditionalDependencies, Dbg->isIndirect(),
12941 Dbg->getDebugLoc(), std::max(ToNode->getIROrder(), Dbg->getOrder()),
12942 Dbg->isVariadic());
12943 ClonedDVs.push_back(Clone);
12944
12945 if (InvalidateDbg) {
12946 // Invalidate value and indicate the SDDbgValue should not be emitted.
12947 Dbg->setIsInvalidated();
12948 Dbg->setIsEmitted();
12949 }
12950 }
12951
12952 for (SDDbgValue *Dbg : ClonedDVs) {
12953 assert(is_contained(Dbg->getSDNodes(), ToNode) &&
12954 "Transferred DbgValues should depend on the new SDNode");
12955 AddDbgValue(Dbg, false);
12956 }
12957}
12958
12960 if (!N.getHasDebugValue())
12961 return;
12962
12963 auto GetLocationOperand = [](SDNode *Node, unsigned ResNo) {
12964 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(Node))
12965 return SDDbgOperand::fromFrameIdx(FISDN->getIndex());
12966 return SDDbgOperand::fromNode(Node, ResNo);
12967 };
12968
12970 for (auto *DV : GetDbgValues(&N)) {
12971 if (DV->isInvalidated())
12972 continue;
12973 switch (N.getOpcode()) {
12974 default:
12975 break;
12976 case ISD::ADD: {
12977 SDValue N0 = N.getOperand(0);
12978 SDValue N1 = N.getOperand(1);
12979 if (!isa<ConstantSDNode>(N0)) {
12980 bool RHSConstant = isa<ConstantSDNode>(N1);
12981 uint64_t Offset;
12982 if (RHSConstant)
12983 Offset = N.getConstantOperandVal(1);
12984 // We are not allowed to turn indirect debug values variadic, so
12985 // don't salvage those.
12986 if (!RHSConstant && DV->isIndirect())
12987 continue;
12988
12989 // Rewrite an ADD constant node into a DIExpression. Since we are
12990 // performing arithmetic to compute the variable's *value* in the
12991 // DIExpression, we need to mark the expression with a
12992 // DW_OP_stack_value.
12993 auto *DIExpr = DV->getExpression();
12994 auto NewLocOps = DV->copyLocationOps();
12995 bool Changed = false;
12996 size_t OrigLocOpsSize = NewLocOps.size();
12997 for (size_t i = 0; i < OrigLocOpsSize; ++i) {
12998 // We're not given a ResNo to compare against because the whole
12999 // node is going away. We know that any ISD::ADD only has one
13000 // result, so we can assume any node match is using the result.
13001 if (NewLocOps[i].getKind() != SDDbgOperand::SDNODE ||
13002 NewLocOps[i].getSDNode() != &N)
13003 continue;
13004 NewLocOps[i] = GetLocationOperand(N0.getNode(), N0.getResNo());
13005 if (RHSConstant) {
13008 DIExpr = DIExpression::appendOpsToArg(DIExpr, ExprOps, i, true);
13009 } else {
13010 // Convert to a variadic expression (if not already).
13011 // convertToVariadicExpression() returns a const pointer, so we use
13012 // a temporary const variable here.
13013 const auto *TmpDIExpr =
13017 ExprOps.push_back(NewLocOps.size());
13018 ExprOps.push_back(dwarf::DW_OP_plus);
13019 SDDbgOperand RHS =
13021 NewLocOps.push_back(RHS);
13022 DIExpr = DIExpression::appendOpsToArg(TmpDIExpr, ExprOps, i, true);
13023 }
13024 Changed = true;
13025 }
13026 (void)Changed;
13027 assert(Changed && "Salvage target doesn't use N");
13028
13029 bool IsVariadic =
13030 DV->isVariadic() || OrigLocOpsSize != NewLocOps.size();
13031
13032 auto AdditionalDependencies = DV->getAdditionalDependencies();
13033 SDDbgValue *Clone = getDbgValueList(
13034 DV->getVariable(), DIExpr, NewLocOps, AdditionalDependencies,
13035 DV->isIndirect(), DV->getDebugLoc(), DV->getOrder(), IsVariadic);
13036 ClonedDVs.push_back(Clone);
13037 DV->setIsInvalidated();
13038 DV->setIsEmitted();
13039 LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting";
13040 N0.getNode()->dumprFull(this);
13041 dbgs() << " into " << *DIExpr << '\n');
13042 }
13043 break;
13044 }
13045 case ISD::TRUNCATE: {
13046 SDValue N0 = N.getOperand(0);
13047 TypeSize FromSize = N0.getValueSizeInBits();
13048 TypeSize ToSize = N.getValueSizeInBits(0);
13049
13050 DIExpression *DbgExpression = DV->getExpression();
13051 auto ExtOps = DIExpression::getExtOps(FromSize, ToSize, false);
13052 auto NewLocOps = DV->copyLocationOps();
13053 bool Changed = false;
13054 for (size_t i = 0; i < NewLocOps.size(); ++i) {
13055 if (NewLocOps[i].getKind() != SDDbgOperand::SDNODE ||
13056 NewLocOps[i].getSDNode() != &N)
13057 continue;
13058
13059 NewLocOps[i] = GetLocationOperand(N0.getNode(), N0.getResNo());
13060 DbgExpression = DIExpression::appendOpsToArg(DbgExpression, ExtOps, i);
13061 Changed = true;
13062 }
13063 assert(Changed && "Salvage target doesn't use N");
13064 (void)Changed;
13065
13066 SDDbgValue *Clone =
13067 getDbgValueList(DV->getVariable(), DbgExpression, NewLocOps,
13068 DV->getAdditionalDependencies(), DV->isIndirect(),
13069 DV->getDebugLoc(), DV->getOrder(), DV->isVariadic());
13070
13071 ClonedDVs.push_back(Clone);
13072 DV->setIsInvalidated();
13073 DV->setIsEmitted();
13074 LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting"; N0.getNode()->dumprFull(this);
13075 dbgs() << " into " << *DbgExpression << '\n');
13076 break;
13077 }
13078 }
13079 }
13080
13081 for (SDDbgValue *Dbg : ClonedDVs) {
13082 assert((!Dbg->getSDNodes().empty() ||
13083 llvm::any_of(Dbg->getLocationOps(),
13084 [&](const SDDbgOperand &Op) {
13085 return Op.getKind() == SDDbgOperand::FRAMEIX;
13086 })) &&
13087 "Salvaged DbgValue should depend on a new SDNode");
13088 AddDbgValue(Dbg, false);
13089 }
13090}
13091
13092/// Creates a SDDbgLabel node.
13094 const DebugLoc &DL, unsigned O) {
13095 assert(cast<DILabel>(Label)->isValidLocationForIntrinsic(DL) &&
13096 "Expected inlined-at fields to agree");
13097 return new (DbgInfo->getAlloc()) SDDbgLabel(Label, DL, O);
13098}
13099
13100namespace {
13101
13102/// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node
13103/// pointed to by a use iterator is deleted, increment the use iterator
13104/// so that it doesn't dangle.
13105///
13106class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener {
13109
13110 void NodeDeleted(SDNode *N, SDNode *E) override {
13111 // Increment the iterator as needed.
13112 while (UI != UE && N == UI->getUser())
13113 ++UI;
13114 }
13115
13116public:
13117 RAUWUpdateListener(SelectionDAG &d,
13120 : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {}
13121};
13122
13123} // end anonymous namespace
13124
13125/// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
13126/// This can cause recursive merging of nodes in the DAG.
13127///
13128/// This version assumes From has a single result value.
13129///
13131 SDNode *From = FromN.getNode();
13132 assert(From->getNumValues() == 1 && FromN.getResNo() == 0 &&
13133 "Cannot replace with this method!");
13134 assert(From != To.getNode() && "Cannot replace uses of with self");
13135
13136 // Preserve Debug Values
13137 transferDbgValues(FromN, To);
13138 // Preserve extra info.
13139 copyExtraInfo(From, To.getNode());
13140
13141 // Iterate over all the existing uses of From. New uses will be added
13142 // to the beginning of the use list, which we avoid visiting.
13143 // This specifically avoids visiting uses of From that arise while the
13144 // replacement is happening, because any such uses would be the result
13145 // of CSE: If an existing node looks like From after one of its operands
13146 // is replaced by To, we don't want to replace of all its users with To
13147 // too. See PR3018 for more info.
13148 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
13149 RAUWUpdateListener Listener(*this, UI, UE);
13150 while (UI != UE) {
13151 SDNode *User = UI->getUser();
13152
13153 // This node is about to morph, remove its old self from the CSE maps.
13154 RemoveNodeFromCSEMaps(User);
13155
13156 // A user can appear in a use list multiple times, and when this
13157 // happens the uses are usually next to each other in the list.
13158 // To help reduce the number of CSE recomputations, process all
13159 // the uses of this user that we can find this way.
13160 do {
13161 SDUse &Use = *UI;
13162 ++UI;
13163 Use.set(To);
13164 if (To->isDivergent() != From->isDivergent())
13166 } while (UI != UE && UI->getUser() == User);
13167 // Now that we have modified User, add it back to the CSE maps. If it
13168 // already exists there, recursively merge the results together.
13169 AddModifiedNodeToCSEMaps(User);
13170 }
13171
13172 // If we just RAUW'd the root, take note.
13173 if (FromN == getRoot())
13174 setRoot(To);
13175}
13176
13177/// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
13178/// This can cause recursive merging of nodes in the DAG.
13179///
13180/// This version assumes that for each value of From, there is a
13181/// corresponding value in To in the same position with the same type.
13182///
13184#ifndef NDEBUG
13185 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
13186 assert((!From->hasAnyUseOfValue(i) ||
13187 From->getValueType(i) == To->getValueType(i)) &&
13188 "Cannot use this version of ReplaceAllUsesWith!");
13189#endif
13190
13191 // Handle the trivial case.
13192 if (From == To)
13193 return;
13194
13195 // Preserve Debug Info. Only do this if there's a use.
13196 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
13197 if (From->hasAnyUseOfValue(i)) {
13198 assert((i < To->getNumValues()) && "Invalid To location");
13199 transferDbgValues(SDValue(From, i), SDValue(To, i));
13200 }
13201 // Preserve extra info.
13202 copyExtraInfo(From, To);
13203
13204 // Iterate over just the existing users of From. See the comments in
13205 // the ReplaceAllUsesWith above.
13206 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
13207 RAUWUpdateListener Listener(*this, UI, UE);
13208 while (UI != UE) {
13209 SDNode *User = UI->getUser();
13210
13211 // This node is about to morph, remove its old self from the CSE maps.
13212 RemoveNodeFromCSEMaps(User);
13213
13214 // A user can appear in a use list multiple times, and when this
13215 // happens the uses are usually next to each other in the list.
13216 // To help reduce the number of CSE recomputations, process all
13217 // the uses of this user that we can find this way.
13218 do {
13219 SDUse &Use = *UI;
13220 ++UI;
13221 Use.setNode(To);
13222 if (To->isDivergent() != From->isDivergent())
13224 } while (UI != UE && UI->getUser() == User);
13225
13226 // Now that we have modified User, add it back to the CSE maps. If it
13227 // already exists there, recursively merge the results together.
13228 AddModifiedNodeToCSEMaps(User);
13229 }
13230
13231 // If we just RAUW'd the root, take note.
13232 if (From == getRoot().getNode())
13233 setRoot(SDValue(To, getRoot().getResNo()));
13234}
13235
13236/// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
13237/// This can cause recursive merging of nodes in the DAG.
13238///
13239/// This version can replace From with any result values. To must match the
13240/// number and types of values returned by From.
13242 if (From->getNumValues() == 1) // Handle the simple case efficiently.
13243 return ReplaceAllUsesWith(SDValue(From, 0), To[0]);
13244
13245 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) {
13246 // Preserve Debug Info.
13247 transferDbgValues(SDValue(From, i), To[i]);
13248 // Preserve extra info.
13249 copyExtraInfo(From, To[i].getNode());
13250 }
13251
13252 // Iterate over just the existing users of From. See the comments in
13253 // the ReplaceAllUsesWith above.
13254 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
13255 RAUWUpdateListener Listener(*this, UI, UE);
13256 while (UI != UE) {
13257 SDNode *User = UI->getUser();
13258
13259 // This node is about to morph, remove its old self from the CSE maps.
13260 RemoveNodeFromCSEMaps(User);
13261
13262 // A user can appear in a use list multiple times, and when this happens the
13263 // uses are usually next to each other in the list. To help reduce the
13264 // number of CSE and divergence recomputations, process all the uses of this
13265 // user that we can find this way.
13266 bool To_IsDivergent = false;
13267 do {
13268 SDUse &Use = *UI;
13269 const SDValue &ToOp = To[Use.getResNo()];
13270 ++UI;
13271 Use.set(ToOp);
13272 if (ToOp.getValueType() != MVT::Other)
13273 To_IsDivergent |= ToOp->isDivergent();
13274 } while (UI != UE && UI->getUser() == User);
13275
13276 if (To_IsDivergent != From->isDivergent())
13278
13279 // Now that we have modified User, add it back to the CSE maps. If it
13280 // already exists there, recursively merge the results together.
13281 AddModifiedNodeToCSEMaps(User);
13282 }
13283
13284 // If we just RAUW'd the root, take note.
13285 if (From == getRoot().getNode())
13286 setRoot(SDValue(To[getRoot().getResNo()]));
13287}
13288
13289/// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
13290/// uses of other values produced by From.getNode() alone. The Deleted
13291/// vector is handled the same way as for ReplaceAllUsesWith.
13293 // Handle the really simple, really trivial case efficiently.
13294 if (From == To) return;
13295
13296 // Handle the simple, trivial, case efficiently.
13297 if (From.getNode()->getNumValues() == 1) {
13298 ReplaceAllUsesWith(From, To);
13299 return;
13300 }
13301
13302 // Preserve Debug Info.
13303 transferDbgValues(From, To);
13304 copyExtraInfo(From.getNode(), To.getNode());
13305
13306 // Iterate over just the existing users of From. See the comments in
13307 // the ReplaceAllUsesWith above.
13308 SDNode::use_iterator UI = From.getNode()->use_begin(),
13309 UE = From.getNode()->use_end();
13310 RAUWUpdateListener Listener(*this, UI, UE);
13311 while (UI != UE) {
13312 SDNode *User = UI->getUser();
13313 bool UserRemovedFromCSEMaps = false;
13314
13315 // A user can appear in a use list multiple times, and when this
13316 // happens the uses are usually next to each other in the list.
13317 // To help reduce the number of CSE recomputations, process all
13318 // the uses of this user that we can find this way.
13319 do {
13320 SDUse &Use = *UI;
13321
13322 // Skip uses of different values from the same node.
13323 if (Use.getResNo() != From.getResNo()) {
13324 ++UI;
13325 continue;
13326 }
13327
13328 // If this node hasn't been modified yet, it's still in the CSE maps,
13329 // so remove its old self from the CSE maps.
13330 if (!UserRemovedFromCSEMaps) {
13331 RemoveNodeFromCSEMaps(User);
13332 UserRemovedFromCSEMaps = true;
13333 }
13334
13335 ++UI;
13336 Use.set(To);
13337 if (To->isDivergent() != From->isDivergent())
13339 } while (UI != UE && UI->getUser() == User);
13340 // We are iterating over all uses of the From node, so if a use
13341 // doesn't use the specific value, no changes are made.
13342 if (!UserRemovedFromCSEMaps)
13343 continue;
13344
13345 // Now that we have modified User, add it back to the CSE maps. If it
13346 // already exists there, recursively merge the results together.
13347 AddModifiedNodeToCSEMaps(User);
13348 }
13349
13350 // If we just RAUW'd the root, take note.
13351 if (From == getRoot())
13352 setRoot(To);
13353}
13354
13355namespace {
13356
13357/// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith
13358/// to record information about a use.
13359struct UseMemo {
13360 SDNode *User;
13361 unsigned Index;
13362 SDUse *Use;
13363};
13364
13365/// operator< - Sort Memos by User.
13366bool operator<(const UseMemo &L, const UseMemo &R) {
13367 return (intptr_t)L.User < (intptr_t)R.User;
13368}
13369
13370/// RAUOVWUpdateListener - Helper for ReplaceAllUsesOfValuesWith - When the node
13371/// pointed to by a UseMemo is deleted, set the User to nullptr to indicate that
13372/// the node already has been taken care of recursively.
13373class RAUOVWUpdateListener : public SelectionDAG::DAGUpdateListener {
13374 SmallVectorImpl<UseMemo> &Uses;
13375
13376 void NodeDeleted(SDNode *N, SDNode *E) override {
13377 for (UseMemo &Memo : Uses)
13378 if (Memo.User == N)
13379 Memo.User = nullptr;
13380 }
13381
13382public:
13383 RAUOVWUpdateListener(SelectionDAG &d, SmallVectorImpl<UseMemo> &uses)
13384 : SelectionDAG::DAGUpdateListener(d), Uses(uses) {}
13385};
13386
13387} // end anonymous namespace
13388
13389/// Return true if a glue output should propagate divergence information.
13391 switch (Node->getOpcode()) {
13392 case ISD::CopyFromReg:
13393 case ISD::CopyToReg:
13394 return false;
13395 default:
13396 return true;
13397 }
13398
13399 llvm_unreachable("covered opcode switch");
13400}
13401
13403 if (TLI->isSDNodeAlwaysUniform(N)) {
13404 assert(!TLI->isSDNodeSourceOfDivergence(N, FLI, UA) &&
13405 "Conflicting divergence information!");
13406 return false;
13407 }
13408 if (TLI->isSDNodeSourceOfDivergence(N, FLI, UA))
13409 return true;
13410 for (const auto &Op : N->ops()) {
13411 EVT VT = Op.getValueType();
13412
13413 // Skip Chain. It does not carry divergence.
13414 if (VT != MVT::Other && Op.getNode()->isDivergent() &&
13415 (VT != MVT::Glue || gluePropagatesDivergence(Op.getNode())))
13416 return true;
13417 }
13418 return false;
13419}
13420
13422 SmallVector<SDNode *, 16> Worklist(1, N);
13423 do {
13424 N = Worklist.pop_back_val();
13425 bool IsDivergent = calculateDivergence(N);
13426 if (N->SDNodeBits.IsDivergent != IsDivergent) {
13427 N->SDNodeBits.IsDivergent = IsDivergent;
13428 llvm::append_range(Worklist, N->users());
13429 }
13430 } while (!Worklist.empty());
13431}
13432
13433void SelectionDAG::CreateTopologicalOrder(std::vector<SDNode *> &Order) {
13435 Order.reserve(AllNodes.size());
13436 for (auto &N : allnodes()) {
13437 unsigned NOps = N.getNumOperands();
13438 Degree[&N] = NOps;
13439 if (0 == NOps)
13440 Order.push_back(&N);
13441 }
13442 for (size_t I = 0; I != Order.size(); ++I) {
13443 SDNode *N = Order[I];
13444 for (auto *U : N->users()) {
13445 unsigned &UnsortedOps = Degree[U];
13446 if (0 == --UnsortedOps)
13447 Order.push_back(U);
13448 }
13449 }
13450}
13451
13452#if !defined(NDEBUG) && LLVM_ENABLE_ABI_BREAKING_CHECKS
13453void SelectionDAG::VerifyDAGDivergence() {
13454 std::vector<SDNode *> TopoOrder;
13455 CreateTopologicalOrder(TopoOrder);
13456 for (auto *N : TopoOrder) {
13457 assert(calculateDivergence(N) == N->isDivergent() &&
13458 "Divergence bit inconsistency detected");
13459 }
13460}
13461#endif
13462
13463/// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving
13464/// uses of other values produced by From.getNode() alone. The same value
13465/// may appear in both the From and To list. The Deleted vector is
13466/// handled the same way as for ReplaceAllUsesWith.
13468 const SDValue *To,
13469 unsigned Num){
13470 // Handle the simple, trivial case efficiently.
13471 if (Num == 1)
13472 return ReplaceAllUsesOfValueWith(*From, *To);
13473
13474 transferDbgValues(*From, *To);
13475 copyExtraInfo(From->getNode(), To->getNode());
13476
13477 // Read up all the uses and make records of them. This helps
13478 // processing new uses that are introduced during the
13479 // replacement process.
13481 for (unsigned i = 0; i != Num; ++i) {
13482 unsigned FromResNo = From[i].getResNo();
13483 SDNode *FromNode = From[i].getNode();
13484 for (SDUse &Use : FromNode->uses()) {
13485 if (Use.getResNo() == FromResNo) {
13486 UseMemo Memo = {Use.getUser(), i, &Use};
13487 Uses.push_back(Memo);
13488 }
13489 }
13490 }
13491
13492 // Sort the uses, so that all the uses from a given User are together.
13494 RAUOVWUpdateListener Listener(*this, Uses);
13495
13496 for (unsigned UseIndex = 0, UseIndexEnd = Uses.size();
13497 UseIndex != UseIndexEnd; ) {
13498 // We know that this user uses some value of From. If it is the right
13499 // value, update it.
13500 SDNode *User = Uses[UseIndex].User;
13501 // If the node has been deleted by recursive CSE updates when updating
13502 // another node, then just skip this entry.
13503 if (User == nullptr) {
13504 ++UseIndex;
13505 continue;
13506 }
13507
13508 // This node is about to morph, remove its old self from the CSE maps.
13509 RemoveNodeFromCSEMaps(User);
13510
13511 // The Uses array is sorted, so all the uses for a given User
13512 // are next to each other in the list.
13513 // To help reduce the number of CSE recomputations, process all
13514 // the uses of this user that we can find this way.
13515 do {
13516 unsigned i = Uses[UseIndex].Index;
13517 SDUse &Use = *Uses[UseIndex].Use;
13518 ++UseIndex;
13519
13520 Use.set(To[i]);
13521 } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User);
13522
13523 // Now that we have modified User, add it back to the CSE maps. If it
13524 // already exists there, recursively merge the results together.
13525 AddModifiedNodeToCSEMaps(User);
13526 }
13527}
13528
13529/// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
13530/// based on their topological order. It returns the maximum id and a vector
13531/// of the SDNodes* in assigned order by reference.
13533 unsigned DAGSize = 0;
13534
13535 // SortedPos tracks the progress of the algorithm. Nodes before it are
13536 // sorted, nodes after it are unsorted. When the algorithm completes
13537 // it is at the end of the list.
13538 allnodes_iterator SortedPos = allnodes_begin();
13539
13540 // Visit all the nodes. Move nodes with no operands to the front of
13541 // the list immediately. Annotate nodes that do have operands with their
13542 // operand count. Before we do this, the Node Id fields of the nodes
13543 // may contain arbitrary values. After, the Node Id fields for nodes
13544 // before SortedPos will contain the topological sort index, and the
13545 // Node Id fields for nodes At SortedPos and after will contain the
13546 // count of outstanding operands.
13548 checkForCycles(&N, this);
13549 unsigned Degree = N.getNumOperands();
13550 if (Degree == 0) {
13551 // A node with no uses, add it to the result array immediately.
13552 N.setNodeId(DAGSize++);
13553 allnodes_iterator Q(&N);
13554 if (Q != SortedPos)
13555 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q));
13556 assert(SortedPos != AllNodes.end() && "Overran node list");
13557 ++SortedPos;
13558 } else {
13559 // Temporarily use the Node Id as scratch space for the degree count.
13560 N.setNodeId(Degree);
13561 }
13562 }
13563
13564 // Visit all the nodes. As we iterate, move nodes into sorted order,
13565 // such that by the time the end is reached all nodes will be sorted.
13566 for (SDNode &Node : allnodes()) {
13567 SDNode *N = &Node;
13568 checkForCycles(N, this);
13569 // N is in sorted position, so all its uses have one less operand
13570 // that needs to be sorted.
13571 for (SDNode *P : N->users()) {
13572 unsigned Degree = P->getNodeId();
13573 assert(Degree != 0 && "Invalid node degree");
13574 --Degree;
13575 if (Degree == 0) {
13576 // All of P's operands are sorted, so P may sorted now.
13577 P->setNodeId(DAGSize++);
13578 if (P->getIterator() != SortedPos)
13579 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P));
13580 assert(SortedPos != AllNodes.end() && "Overran node list");
13581 ++SortedPos;
13582 } else {
13583 // Update P's outstanding operand count.
13584 P->setNodeId(Degree);
13585 }
13586 }
13587 if (Node.getIterator() == SortedPos) {
13588#ifndef NDEBUG
13590 SDNode *S = &*++I;
13591 dbgs() << "Overran sorted position:\n";
13592 S->dumprFull(this); dbgs() << "\n";
13593 dbgs() << "Checking if this is due to cycles\n";
13594 checkForCycles(this, true);
13595#endif
13596 llvm_unreachable(nullptr);
13597 }
13598 }
13599
13600 assert(SortedPos == AllNodes.end() &&
13601 "Topological sort incomplete!");
13602 assert(AllNodes.front().getOpcode() == ISD::EntryToken &&
13603 "First node in topological sort is not the entry token!");
13604 assert(AllNodes.front().getNodeId() == 0 &&
13605 "First node in topological sort has non-zero id!");
13606 assert(AllNodes.front().getNumOperands() == 0 &&
13607 "First node in topological sort has operands!");
13608 assert(AllNodes.back().getNodeId() == (int)DAGSize-1 &&
13609 "Last node in topologic sort has unexpected id!");
13610 assert(AllNodes.back().use_empty() &&
13611 "Last node in topologic sort has users!");
13612 assert(DAGSize == allnodes_size() && "Node count mismatch!");
13613 return DAGSize;
13614}
13615
13617 SmallVectorImpl<const SDNode *> &SortedNodes) const {
13618 SortedNodes.clear();
13619 // Node -> remaining number of outstanding operands.
13620 DenseMap<const SDNode *, unsigned> RemainingOperands;
13621
13622 // Put nodes without any operands into SortedNodes first.
13623 for (const SDNode &N : allnodes()) {
13624 checkForCycles(&N, this);
13625 unsigned NumOperands = N.getNumOperands();
13626 if (NumOperands == 0)
13627 SortedNodes.push_back(&N);
13628 else
13629 // Record their total number of outstanding operands.
13630 RemainingOperands[&N] = NumOperands;
13631 }
13632
13633 // A node is pushed into SortedNodes when all of its operands (predecessors in
13634 // the graph) are also in SortedNodes.
13635 for (unsigned i = 0U; i < SortedNodes.size(); ++i) {
13636 const SDNode *N = SortedNodes[i];
13637 for (const SDNode *U : N->users()) {
13638 // HandleSDNode is never part of a DAG and therefore has no entry in
13639 // RemainingOperands.
13640 if (U->getOpcode() == ISD::HANDLENODE)
13641 continue;
13642 unsigned &NumRemOperands = RemainingOperands[U];
13643 assert(NumRemOperands && "Invalid number of remaining operands");
13644 --NumRemOperands;
13645 if (!NumRemOperands)
13646 SortedNodes.push_back(U);
13647 }
13648 }
13649
13650 assert(SortedNodes.size() == AllNodes.size() && "Node count mismatch");
13651 assert(SortedNodes.front()->getOpcode() == ISD::EntryToken &&
13652 "First node in topological sort is not the entry token");
13653 assert(SortedNodes.front()->getNumOperands() == 0 &&
13654 "First node in topological sort has operands");
13655}
13656
13657/// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the
13658/// value is produced by SD.
13659void SelectionDAG::AddDbgValue(SDDbgValue *DB, bool isParameter) {
13660 for (SDNode *SD : DB->getSDNodes()) {
13661 if (!SD)
13662 continue;
13663 assert(DbgInfo->getSDDbgValues(SD).empty() || SD->getHasDebugValue());
13664 SD->setHasDebugValue(true);
13665 }
13666 DbgInfo->add(DB, isParameter);
13667}
13668
13669void SelectionDAG::AddDbgLabel(SDDbgLabel *DB) { DbgInfo->add(DB); }
13670
13672 SDValue NewMemOpChain) {
13673 assert(isa<MemSDNode>(NewMemOpChain) && "Expected a memop node");
13674 assert(NewMemOpChain.getValueType() == MVT::Other && "Expected a token VT");
13675 // The new memory operation must have the same position as the old load in
13676 // terms of memory dependency. Create a TokenFactor for the old load and new
13677 // memory operation and update uses of the old load's output chain to use that
13678 // TokenFactor.
13679 if (OldChain == NewMemOpChain || OldChain.use_empty())
13680 return NewMemOpChain;
13681
13682 SDValue TokenFactor = getNode(ISD::TokenFactor, SDLoc(OldChain), MVT::Other,
13683 OldChain, NewMemOpChain);
13684 ReplaceAllUsesOfValueWith(OldChain, TokenFactor);
13685 UpdateNodeOperands(TokenFactor.getNode(), OldChain, NewMemOpChain);
13686 return TokenFactor;
13687}
13688
13690 SDValue NewMemOp) {
13691 assert(isa<MemSDNode>(NewMemOp.getNode()) && "Expected a memop node");
13692 SDValue OldChain = SDValue(OldLoad, 1);
13693 SDValue NewMemOpChain = NewMemOp.getValue(1);
13694 return makeEquivalentMemoryOrdering(OldChain, NewMemOpChain);
13695}
13696
13698 Function **OutFunction) {
13699 assert(isa<ExternalSymbolSDNode>(Op) && "Node should be an ExternalSymbol");
13700
13701 auto *Symbol = cast<ExternalSymbolSDNode>(Op)->getSymbol();
13702 auto *Module = MF->getFunction().getParent();
13703 auto *Function = Module->getFunction(Symbol);
13704
13705 if (OutFunction != nullptr)
13706 *OutFunction = Function;
13707
13708 if (Function != nullptr) {
13709 auto PtrTy = TLI->getPointerTy(getDataLayout(), Function->getAddressSpace());
13710 return getGlobalAddress(Function, SDLoc(Op), PtrTy);
13711 }
13712
13713 std::string ErrorStr;
13714 raw_string_ostream ErrorFormatter(ErrorStr);
13715 ErrorFormatter << "Undefined external symbol ";
13716 ErrorFormatter << '"' << Symbol << '"';
13717 report_fatal_error(Twine(ErrorStr));
13718}
13719
13720//===----------------------------------------------------------------------===//
13721// SDNode Class
13722//===----------------------------------------------------------------------===//
13723
13726 return Const != nullptr && Const->isZero();
13727}
13728
13730 return V.isUndef() || isNullConstant(V);
13731}
13732
13735 return Const != nullptr && Const->isZero() && !Const->isNegative();
13736}
13737
13740 return Const != nullptr && Const->isAllOnes();
13741}
13742
13745 return Const != nullptr && Const->isOne();
13746}
13747
13750 return Const != nullptr && Const->isMinSignedValue();
13751}
13752
13754 SDValue V, unsigned OperandNo,
13755 unsigned Depth) const {
13756 APInt DemandedElts = getDemandAllEltsMask(V);
13757 return isIdentityElement(Opcode, Flags, V, DemandedElts, OperandNo, Depth);
13758}
13759
13761 SDValue V, const APInt &DemandedElts,
13762 unsigned OperandNo, unsigned Depth) const {
13763 // NOTE: The cases should match with IR's ConstantExpr::getBinOpIdentity().
13764 // TODO: Target-specific opcodes could be added.
13765 if (V.getValueType().isInteger()) {
13766 KnownBits Known = computeKnownBits(V, DemandedElts, Depth);
13767 if (Known.isConstant()) {
13768 const APInt &Const = Known.getConstant();
13769 switch (Opcode) {
13770 case ISD::ADD:
13771 case ISD::OR:
13772 case ISD::XOR:
13773 case ISD::UMAX:
13774 return Const.isZero();
13775 case ISD::MUL:
13776 return Const.isOne();
13777 case ISD::AND:
13778 case ISD::UMIN:
13779 return Const.isAllOnes();
13780 case ISD::SMAX:
13781 return Const.isMinSignedValue();
13782 case ISD::SMIN:
13783 return Const.isMaxSignedValue();
13784 case ISD::SUB:
13785 case ISD::SHL:
13786 case ISD::SRA:
13787 case ISD::SRL:
13788 return OperandNo == 1 && Const.isZero();
13789 case ISD::UDIV:
13790 case ISD::SDIV:
13791 return OperandNo == 1 && Const.isOne();
13792 }
13793 }
13794 } else if (auto *ConstFP = isConstOrConstSplatFP(V, DemandedElts)) {
13795 switch (Opcode) {
13796 case ISD::FADD:
13797 return ConstFP->isZero() &&
13798 (Flags.hasNoSignedZeros() || ConstFP->isNegative());
13799 case ISD::FSUB:
13800 return OperandNo == 1 && ConstFP->isZero() &&
13801 (Flags.hasNoSignedZeros() || !ConstFP->isNegative());
13802 case ISD::FMUL:
13803 return ConstFP->isOne();
13804 case ISD::FDIV:
13805 return OperandNo == 1 && ConstFP->isOne();
13806 case ISD::FMINNUM:
13807 case ISD::FMAXNUM:
13808 case ISD::FMINIMUMNUM:
13809 case ISD::FMAXIMUMNUM: {
13810 // Neutral element for fminnum/fminimumnum is NaN, Inf or FLT_MAX,
13811 // depending on fast-math flags (FMF).
13812 EVT VT = V.getValueType();
13813 const fltSemantics &Semantics = VT.getFltSemantics();
13814 APFloat NeutralAF = !Flags.hasNoNaNs() ? APFloat::getQNaN(Semantics)
13815 : !Flags.hasNoInfs() ? APFloat::getInf(Semantics)
13816 : APFloat::getLargest(Semantics);
13817 if (Opcode == ISD::FMAXNUM || Opcode == ISD::FMAXIMUMNUM)
13818 NeutralAF.changeSign();
13819
13820 return ConstFP->isExactlyValue(NeutralAF);
13821 }
13822 case ISD::FMINIMUM:
13823 case ISD::FMAXIMUM: {
13824 // Neutral element for fminimum is Inf or FLT_MAX, depending on FMF.
13825 const APFloat &VAPF = ConstFP->getValueAPF();
13826 bool NeutralNegative = (Opcode == ISD::FMAXIMUM);
13827 if (Flags.hasNoInfs())
13828 return VAPF.isLargest() && VAPF.isNegative() == NeutralNegative;
13829 return VAPF.isInfinity() && VAPF.isNegative() == NeutralNegative;
13830 }
13831 }
13832 }
13833 return false;
13834}
13835
13837 while (V.getOpcode() == ISD::BITCAST)
13838 V = V.getOperand(0);
13839 return V;
13840}
13841
13843 while (V.getOpcode() == ISD::BITCAST && V.getOperand(0).hasOneUse())
13844 V = V.getOperand(0);
13845 return V;
13846}
13847
13849 while (V.getOpcode() == ISD::EXTRACT_SUBVECTOR)
13850 V = V.getOperand(0);
13851 return V;
13852}
13853
13855 while (V.getOpcode() == ISD::INSERT_VECTOR_ELT) {
13856 SDValue InVec = V.getOperand(0);
13857 SDValue EltNo = V.getOperand(2);
13858 EVT VT = InVec.getValueType();
13859 auto *IndexC = dyn_cast<ConstantSDNode>(EltNo);
13860 if (IndexC && VT.isFixedLengthVector() &&
13861 IndexC->getAPIntValue().ult(VT.getVectorNumElements()) &&
13862 !DemandedElts[IndexC->getZExtValue()]) {
13863 V = InVec;
13864 continue;
13865 }
13866 break;
13867 }
13868 return V;
13869}
13870
13872 while (V.getOpcode() == ISD::TRUNCATE)
13873 V = V.getOperand(0);
13874 return V;
13875}
13876
13877bool llvm::isBitwiseNot(SDValue V, bool AllowUndefs) {
13878 if (V.getOpcode() != ISD::XOR)
13879 return false;
13880 V = peekThroughBitcasts(V.getOperand(1));
13881 unsigned NumBits = V.getScalarValueSizeInBits();
13882 ConstantSDNode *C =
13883 isConstOrConstSplat(V, AllowUndefs, /*AllowTruncation*/ true);
13884 return C && (C->getAPIntValue().countr_one() >= NumBits);
13885}
13886
13888 bool AllowTruncation) {
13889 APInt DemandedElts = getDemandAllEltsMask(N);
13890 return isConstOrConstSplat(N, DemandedElts, AllowUndefs, AllowTruncation);
13891}
13892
13894 bool AllowUndefs,
13895 bool AllowTruncation) {
13897 return CN;
13898
13899 // SplatVectors can truncate their operands. Ignore that case here unless
13900 // AllowTruncation is set.
13901 if (N->getOpcode() == ISD::SPLAT_VECTOR) {
13902 EVT VecEltVT = N->getValueType(0).getVectorElementType();
13903 if (auto *CN = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
13904 EVT CVT = CN->getValueType(0);
13905 assert(CVT.bitsGE(VecEltVT) && "Illegal splat_vector element extension");
13906 if (AllowTruncation || CVT == VecEltVT)
13907 return CN;
13908 }
13909 }
13910
13912 BitVector UndefElements;
13913 ConstantSDNode *CN = BV->getConstantSplatNode(DemandedElts, &UndefElements);
13914
13915 // BuildVectors can truncate their operands. Ignore that case here unless
13916 // AllowTruncation is set.
13917 // TODO: Look into whether we should allow UndefElements in non-DemandedElts
13918 if (CN && (UndefElements.none() || AllowUndefs)) {
13919 EVT CVT = CN->getValueType(0);
13920 EVT NSVT = N.getValueType().getScalarType();
13921 assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension");
13922 if (AllowTruncation || (CVT == NSVT))
13923 return CN;
13924 }
13925 }
13926
13927 return nullptr;
13928}
13929
13931 APInt DemandedElts = getDemandAllEltsMask(N);
13932 return isConstOrConstSplatFP(N, DemandedElts, AllowUndefs);
13933}
13934
13936 const APInt &DemandedElts,
13937 bool AllowUndefs) {
13939 return CN;
13940
13942 BitVector UndefElements;
13943 ConstantFPSDNode *CN =
13944 BV->getConstantFPSplatNode(DemandedElts, &UndefElements);
13945 // TODO: Look into whether we should allow UndefElements in non-DemandedElts
13946 if (CN && (UndefElements.none() || AllowUndefs))
13947 return CN;
13948 }
13949
13950 if (N.getOpcode() == ISD::SPLAT_VECTOR)
13951 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N.getOperand(0)))
13952 return CN;
13953
13954 return nullptr;
13955}
13956
13957bool llvm::isNullOrNullSplat(SDValue N, bool AllowUndefs) {
13958 // TODO: may want to use peekThroughBitcast() here.
13959 ConstantSDNode *C =
13960 isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation=*/true);
13961 return C && C->isZero();
13962}
13963
13964bool llvm::isOneOrOneSplat(SDValue N, bool AllowUndefs) {
13965 ConstantSDNode *C =
13966 isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation*/ true);
13967 return C && C->isOne();
13968}
13969
13970bool llvm::isOneOrOneSplatFP(SDValue N, bool AllowUndefs) {
13971 ConstantFPSDNode *C = isConstOrConstSplatFP(N, AllowUndefs);
13972 return C && C->isOne();
13973}
13974
13975bool llvm::isAllOnesOrAllOnesSplat(SDValue N, bool AllowUndefs) {
13977 unsigned BitWidth = N.getScalarValueSizeInBits();
13978 ConstantSDNode *C =
13979 isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation=*/true);
13980 return C && C->getAPIntValue().countTrailingOnes() >= BitWidth;
13981}
13982
13983bool llvm::isOnesOrOnesSplat(SDValue N, bool AllowUndefs) {
13984 ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs);
13985 return C && APInt::isSameValue(C->getAPIntValue(),
13986 APInt(C->getAPIntValue().getBitWidth(), 1));
13987}
13988
13989bool llvm::isZeroOrZeroSplat(SDValue N, bool AllowUndefs) {
13991 ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs, true);
13992 return C && C->isZero();
13993}
13994
13995bool llvm::isZeroOrZeroSplatFP(SDValue N, bool AllowUndefs) {
13996 ConstantFPSDNode *C = isConstOrConstSplatFP(N, AllowUndefs);
13997 return C && C->isZero();
13998}
13999
14003
14005 unsigned Opc, unsigned Order, const DebugLoc &dl, SDVTList VTs, EVT memvt,
14007 : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MemRefs(memrefs) {
14008 bool IsVolatile = false;
14009 bool IsNonTemporal = false;
14010 bool IsDereferenceable = true;
14011 bool IsInvariant = true;
14012 for (const MachineMemOperand *MMO : memoperands()) {
14013 IsVolatile |= MMO->isVolatile();
14014 IsNonTemporal |= MMO->isNonTemporal();
14015 IsDereferenceable &= MMO->isDereferenceable();
14016 IsInvariant &= MMO->isInvariant();
14017 }
14018 MemSDNodeBits.IsVolatile = IsVolatile;
14019 MemSDNodeBits.IsNonTemporal = IsNonTemporal;
14020 MemSDNodeBits.IsDereferenceable = IsDereferenceable;
14021 MemSDNodeBits.IsInvariant = IsInvariant;
14022
14023 // For the single-MMO case, we check here that the size of the memory operand
14024 // fits within the size of the MMO. This is because the MMO might indicate
14025 // only a possible address range instead of specifying the affected memory
14026 // addresses precisely.
14029 getMemOperand()->getSize().getValue())) &&
14030 "Size mismatch!");
14031}
14032
14033namespace {
14034
14035 struct EVTArray {
14036 std::vector<EVT> VTs;
14037
14038 EVTArray() {
14039 VTs.reserve(MVT::VALUETYPE_SIZE);
14040 for (unsigned i = 0; i < MVT::VALUETYPE_SIZE; ++i)
14041 VTs.push_back(MVT((MVT::SimpleValueType)i));
14042 }
14043 };
14044
14045} // end anonymous namespace
14046
14047/// getValueTypeList - Return a pointer to the specified value type.
14048///
14049const EVT *SDNode::getValueTypeList(MVT VT) {
14050 static EVTArray SimpleVTArray;
14051
14052 assert(VT < MVT::VALUETYPE_SIZE && "Value type out of range!");
14053 return &SimpleVTArray.VTs[VT.SimpleTy];
14054}
14055
14056/// hasAnyUseOfValue - Return true if there are any use of the indicated
14057/// value. This method ignores uses of other values defined by this operation.
14058bool SDNode::hasAnyUseOfValue(unsigned Value) const {
14059 assert(Value < getNumValues() && "Bad value!");
14060
14061 for (SDUse &U : uses())
14062 if (U.getResNo() == Value)
14063 return true;
14064
14065 return false;
14066}
14067
14068/// isOnlyUserOf - Return true if this node is the only use of N.
14069bool SDNode::isOnlyUserOf(const SDNode *N) const {
14070 bool Seen = false;
14071 for (const SDNode *User : N->users()) {
14072 if (User == this)
14073 Seen = true;
14074 else
14075 return false;
14076 }
14077
14078 return Seen;
14079}
14080
14081/// Return true if the only users of N are contained in Nodes.
14083 bool Seen = false;
14084 for (const SDNode *User : N->users()) {
14085 if (llvm::is_contained(Nodes, User))
14086 Seen = true;
14087 else
14088 return false;
14089 }
14090
14091 return Seen;
14092}
14093
14094/// Return true if the referenced return value is an operand of N.
14095bool SDValue::isOperandOf(const SDNode *N) const {
14096 return is_contained(N->op_values(), *this);
14097}
14098
14099bool SDNode::isOperandOf(const SDNode *N) const {
14100 return any_of(N->op_values(),
14101 [this](SDValue Op) { return this == Op.getNode(); });
14102}
14103
14104/// reachesChainWithoutSideEffects - Return true if this operand (which must
14105/// be a chain) reaches the specified operand without crossing any
14106/// side-effecting instructions on any chain path. In practice, this looks
14107/// through token factors and non-volatile loads. In order to remain efficient,
14108/// this only looks a couple of nodes in, it does not do an exhaustive search.
14109///
14110/// Note that we only need to examine chains when we're searching for
14111/// side-effects; SelectionDAG requires that all side-effects are represented
14112/// by chains, even if another operand would force a specific ordering. This
14113/// constraint is necessary to allow transformations like splitting loads.
14115 unsigned Depth) const {
14116 if (*this == Dest) return true;
14117
14118 // Don't search too deeply, we just want to be able to see through
14119 // TokenFactor's etc.
14120 if (Depth == 0) return false;
14121
14122 // If this is a token factor, all inputs to the TF happen in parallel.
14123 if (getOpcode() == ISD::TokenFactor) {
14124 // First, try a shallow search.
14125 if (is_contained((*this)->ops(), Dest)) {
14126 // We found the chain we want as an operand of this TokenFactor.
14127 // Essentially, we reach the chain without side-effects if we could
14128 // serialize the TokenFactor into a simple chain of operations with
14129 // Dest as the last operation. This is automatically true if the
14130 // chain has one use: there are no other ordering constraints.
14131 // If the chain has more than one use, we give up: some other
14132 // use of Dest might force a side-effect between Dest and the current
14133 // node.
14134 if (Dest.hasOneUse())
14135 return true;
14136 }
14137 // Next, try a deep search: check whether every operand of the TokenFactor
14138 // reaches Dest.
14139 return llvm::all_of((*this)->ops(), [=](SDValue Op) {
14140 return Op.reachesChainWithoutSideEffects(Dest, Depth - 1);
14141 });
14142 }
14143
14144 // Loads don't have side effects, look through them.
14145 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
14146 if (Ld->isUnordered())
14147 return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
14148 }
14149 return false;
14150}
14151
14152bool SDNode::hasPredecessor(const SDNode *N) const {
14155 Worklist.push_back(this);
14156 return hasPredecessorHelper(N, Visited, Worklist);
14157}
14158
14160 this->Flags &= Flags;
14161}
14162
14163SDValue
14165 ArrayRef<ISD::NodeType> CandidateBinOps,
14166 bool AllowPartials) {
14167 // The pattern must end in an extract from index 0.
14168 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
14169 !isNullConstant(Extract->getOperand(1)))
14170 return SDValue();
14171
14172 // Match against one of the candidate binary ops.
14173 SDValue Op = Extract->getOperand(0);
14174 if (llvm::none_of(CandidateBinOps, [Op](ISD::NodeType BinOp) {
14175 return Op.getOpcode() == unsigned(BinOp);
14176 }))
14177 return SDValue();
14178
14179 // Floating-point reductions may require relaxed constraints on the final step
14180 // of the reduction because they may reorder intermediate operations.
14181 unsigned CandidateBinOp = Op.getOpcode();
14182 if (Op.getValueType().isFloatingPoint()) {
14183 SDNodeFlags Flags = Op->getFlags();
14184 switch (CandidateBinOp) {
14185 case ISD::FADD:
14186 if (!Flags.hasNoSignedZeros() || !Flags.hasAllowReassociation())
14187 return SDValue();
14188 break;
14189 default:
14190 llvm_unreachable("Unhandled FP opcode for binop reduction");
14191 }
14192 }
14193
14194 // Matching failed - attempt to see if we did enough stages that a partial
14195 // reduction from a subvector is possible.
14196 auto PartialReduction = [&](SDValue Op, unsigned NumSubElts) {
14197 if (!AllowPartials || !Op)
14198 return SDValue();
14199 EVT OpVT = Op.getValueType();
14200 EVT OpSVT = OpVT.getScalarType();
14201 EVT SubVT = EVT::getVectorVT(*getContext(), OpSVT, NumSubElts);
14202 if (TLI->getExtractSubvectorCost(SubVT, OpVT, 0) >
14204 return SDValue();
14205 BinOp = (ISD::NodeType)CandidateBinOp;
14206 return getExtractSubvector(SDLoc(Op), SubVT, Op, 0);
14207 };
14208
14209 // At each stage, we're looking for something that looks like:
14210 // %s = shufflevector <8 x i32> %op, <8 x i32> undef,
14211 // <8 x i32> <i32 2, i32 3, i32 undef, i32 undef,
14212 // i32 undef, i32 undef, i32 undef, i32 undef>
14213 // %a = binop <8 x i32> %op, %s
14214 // Where the mask changes according to the stage. E.g. for a 3-stage pyramid,
14215 // we expect something like:
14216 // <4,5,6,7,u,u,u,u>
14217 // <2,3,u,u,u,u,u,u>
14218 // <1,u,u,u,u,u,u,u>
14219 // While a partial reduction match would be:
14220 // <2,3,u,u,u,u,u,u>
14221 // <1,u,u,u,u,u,u,u>
14222 unsigned Stages = Log2_32(Op.getValueType().getVectorNumElements());
14223 SDValue PrevOp;
14224 for (unsigned i = 0; i < Stages; ++i) {
14225 unsigned MaskEnd = (1 << i);
14226
14227 if (Op.getOpcode() != CandidateBinOp)
14228 return PartialReduction(PrevOp, MaskEnd);
14229
14230 SDValue Op0 = Op.getOperand(0);
14231 SDValue Op1 = Op.getOperand(1);
14232
14234 if (Shuffle) {
14235 Op = Op1;
14236 } else {
14237 Shuffle = dyn_cast<ShuffleVectorSDNode>(Op1);
14238 Op = Op0;
14239 }
14240
14241 // The first operand of the shuffle should be the same as the other operand
14242 // of the binop.
14243 if (!Shuffle || Shuffle->getOperand(0) != Op)
14244 return PartialReduction(PrevOp, MaskEnd);
14245
14246 // Verify the shuffle has the expected (at this stage of the pyramid) mask.
14247 for (int Index = 0; Index < (int)MaskEnd; ++Index)
14248 if (Shuffle->getMaskElt(Index) != (int)(MaskEnd + Index))
14249 return PartialReduction(PrevOp, MaskEnd);
14250
14251 PrevOp = Op;
14252 }
14253
14254 // Handle subvector reductions, which tend to appear after the shuffle
14255 // reduction stages.
14256 while (Op.getOpcode() == CandidateBinOp) {
14257 unsigned NumElts = Op.getValueType().getVectorNumElements();
14258 SDValue Op0 = Op.getOperand(0);
14259 SDValue Op1 = Op.getOperand(1);
14260 if (Op0.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
14262 Op0.getOperand(0) != Op1.getOperand(0))
14263 break;
14264 SDValue Src = Op0.getOperand(0);
14265 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
14266 if (NumSrcElts != (2 * NumElts))
14267 break;
14268 if (!(Op0.getConstantOperandAPInt(1) == 0 &&
14269 Op1.getConstantOperandAPInt(1) == NumElts) &&
14270 !(Op1.getConstantOperandAPInt(1) == 0 &&
14271 Op0.getConstantOperandAPInt(1) == NumElts))
14272 break;
14273 Op = Src;
14274 }
14275
14276 BinOp = (ISD::NodeType)CandidateBinOp;
14277 return Op;
14278}
14279
14281 EVT VT = N->getValueType(0);
14282 EVT EltVT = VT.getVectorElementType();
14283 unsigned NE = getMaxRuntimeNumElements(VT);
14284
14285 if (VT.isScalableVector() && (NE == 0 || ResNE != 0))
14286 reportFatalUsageError("Cannot unroll scalable vector!");
14287
14288 assert(NE && "Nothing to unroll!");
14289 SDLoc dl(N);
14290
14291 // If ResNE is 0, fully unroll the vector op.
14292 if (ResNE == 0)
14293 ResNE = NE;
14294 else if (NE > ResNE)
14295 NE = ResNE;
14296
14297 if (N->getNumValues() == 2) {
14298 SmallVector<SDValue, 8> Scalars0, Scalars1;
14299 SmallVector<SDValue, 4> Operands(N->getNumOperands());
14300 EVT VT1 = N->getValueType(1);
14301 EVT EltVT1 = VT1.getVectorElementType();
14302
14303 unsigned i;
14304 for (i = 0; i != NE; ++i) {
14305 for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) {
14306 SDValue Operand = N->getOperand(j);
14307 EVT OperandVT = Operand.getValueType();
14308
14309 // A vector operand; extract a single element.
14310 EVT OperandEltVT = OperandVT.getVectorElementType();
14311 Operands[j] = getExtractVectorElt(dl, OperandEltVT, Operand, i);
14312 }
14313
14314 SDValue EltOp = getNode(N->getOpcode(), dl, {EltVT, EltVT1}, Operands);
14315 Scalars0.push_back(EltOp);
14316 Scalars1.push_back(EltOp.getValue(1));
14317 }
14318
14319 for (; i < ResNE; ++i) {
14320 Scalars0.push_back(getUNDEF(EltVT));
14321 Scalars1.push_back(getUNDEF(EltVT1));
14322 }
14323
14325 : ElementCount::getFixed(ResNE);
14326 EVT VecVT = EVT::getVectorVT(*getContext(), EltVT, ResEC);
14327 EVT VecVT1 = EVT::getVectorVT(*getContext(), EltVT1, ResEC);
14328 SDValue Vec0 = buildVectorFromUnrolledParts(VecVT, dl, Scalars0);
14329 SDValue Vec1 = buildVectorFromUnrolledParts(VecVT1, dl, Scalars1);
14330 return getMergeValues({Vec0, Vec1}, dl);
14331 }
14332
14333 assert(N->getNumValues() == 1 &&
14334 "Can't unroll a vector with multiple results!");
14335
14337 SmallVector<SDValue, 4> Operands(N->getNumOperands());
14338
14339 unsigned i;
14340 for (i= 0; i != NE; ++i) {
14341 for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) {
14342 SDValue Operand = N->getOperand(j);
14343 EVT OperandVT = Operand.getValueType();
14344 if (OperandVT.isVector()) {
14345 // A vector operand; extract a single element.
14346 EVT OperandEltVT = OperandVT.getVectorElementType();
14347 Operands[j] = getExtractVectorElt(dl, OperandEltVT, Operand, i);
14348 } else {
14349 // A scalar operand; just use it as is.
14350 Operands[j] = Operand;
14351 }
14352 }
14353
14354 switch (N->getOpcode()) {
14355 default: {
14356 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands,
14357 N->getFlags()));
14358 break;
14359 }
14360 case ISD::VSELECT:
14361 Scalars.push_back(
14362 getNode(ISD::SELECT, dl, EltVT, Operands, N->getFlags()));
14363 break;
14364 case ISD::SHL:
14365 case ISD::SRA:
14366 case ISD::SRL:
14367 case ISD::ROTL:
14368 case ISD::ROTR:
14369 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0],
14371 Operands[1])));
14372 break;
14374 EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType();
14375 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT,
14376 Operands[0],
14377 getValueType(ExtVT)));
14378 break;
14379 }
14380 case ISD::ADDRSPACECAST: {
14381 const auto *ASC = cast<AddrSpaceCastSDNode>(N);
14382 Scalars.push_back(getAddrSpaceCast(dl, EltVT, Operands[0],
14383 ASC->getSrcAddressSpace(),
14384 ASC->getDestAddressSpace()));
14385 break;
14386 }
14387 }
14388 }
14389
14390 for (; i < ResNE; ++i)
14391 Scalars.push_back(getUNDEF(EltVT));
14392
14393 EVT VecVT = VT.isScalableVector()
14394 ? VT
14395 : EVT::getVectorVT(*getContext(), EltVT, ResNE);
14396 return buildVectorFromUnrolledParts(VecVT, dl, Scalars);
14397}
14398
14399std::pair<SDValue, SDValue> SelectionDAG::UnrollVectorOverflowOp(
14400 SDNode *N, unsigned ResNE) {
14401 unsigned Opcode = N->getOpcode();
14402 assert((Opcode == ISD::UADDO || Opcode == ISD::SADDO ||
14403 Opcode == ISD::USUBO || Opcode == ISD::SSUBO ||
14404 Opcode == ISD::UMULO || Opcode == ISD::SMULO) &&
14405 "Expected an overflow opcode");
14406
14407 EVT ResVT = N->getValueType(0);
14408 EVT OvVT = N->getValueType(1);
14409 EVT ResEltVT = ResVT.getVectorElementType();
14410 EVT OvEltVT = OvVT.getVectorElementType();
14411 SDLoc dl(N);
14412
14413 // If ResNE is 0, fully unroll the vector op.
14414 unsigned NE = ResVT.getVectorNumElements();
14415 if (ResNE == 0)
14416 ResNE = NE;
14417 else if (NE > ResNE)
14418 NE = ResNE;
14419
14420 SmallVector<SDValue, 8> LHSScalars;
14421 SmallVector<SDValue, 8> RHSScalars;
14422 ExtractVectorElements(N->getOperand(0), LHSScalars, 0, NE);
14423 ExtractVectorElements(N->getOperand(1), RHSScalars, 0, NE);
14424
14425 EVT SVT = TLI->getSetCCResultType(getDataLayout(), *getContext(), ResEltVT);
14426 SDVTList VTs = getVTList(ResEltVT, SVT);
14427 SmallVector<SDValue, 8> ResScalars;
14428 SmallVector<SDValue, 8> OvScalars;
14429 for (unsigned i = 0; i < NE; ++i) {
14430 SDValue Res = getNode(Opcode, dl, VTs, LHSScalars[i], RHSScalars[i]);
14431 SDValue Ov =
14432 getSelect(dl, OvEltVT, Res.getValue(1),
14433 getBoolConstant(true, dl, OvEltVT, ResVT),
14434 getConstant(0, dl, OvEltVT));
14435
14436 ResScalars.push_back(Res);
14437 OvScalars.push_back(Ov);
14438 }
14439
14440 ResScalars.append(ResNE - NE, getUNDEF(ResEltVT));
14441 OvScalars.append(ResNE - NE, getUNDEF(OvEltVT));
14442
14443 EVT NewResVT = EVT::getVectorVT(*getContext(), ResEltVT, ResNE);
14444 EVT NewOvVT = EVT::getVectorVT(*getContext(), OvEltVT, ResNE);
14445 return std::make_pair(getBuildVector(NewResVT, dl, ResScalars),
14446 getBuildVector(NewOvVT, dl, OvScalars));
14447}
14448
14451 unsigned Bytes, int Dist,
14452 const SelectionDAG &DAG) {
14453 if (LS->isVolatile() || Base->isVolatile())
14454 return false;
14455 // TODO: probably too restrictive for atomics, revisit
14456 if (!LS->isSimple())
14457 return false;
14458 if (LS->isIndexed() || Base->isIndexed())
14459 return false;
14460 if (LS->getChain() != Base->getChain())
14461 return false;
14462 EVT VT = LS->getMemoryVT();
14463 if (VT.getSizeInBits() / 8 != Bytes)
14464 return false;
14465
14466 auto BaseLocDecomp = BaseIndexOffset::match(Base, DAG);
14467 auto LocDecomp = BaseIndexOffset::match(LS, DAG);
14468
14469 int64_t Offset = 0;
14470 if (BaseLocDecomp.equalBaseIndex(LocDecomp, DAG, Offset))
14471 return (Dist * (int64_t)Bytes == Offset);
14472 return false;
14473}
14474
14477 unsigned Bytes,
14478 int Dist) const {
14479 return areNonVolatileConsecutiveLoadsOrStores(LD, Base, Bytes, Dist, *this);
14480}
14481
14484 unsigned Bytes,
14485 int Dist) const {
14486 return areNonVolatileConsecutiveLoadsOrStores(ST, Base, Bytes, Dist, *this);
14487}
14488
14489/// InferPtrAlignment - Infer alignment of a load / store address. Return
14490/// std::nullopt if it cannot be inferred.
14492 // If this is a GlobalAddress + cst, return the alignment.
14493 const GlobalValue *GV = nullptr;
14494 int64_t GVOffset = 0;
14495 if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) {
14496 unsigned PtrWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
14497 KnownBits Known(PtrWidth);
14499 unsigned AlignBits = Known.countMinTrailingZeros();
14500 if (AlignBits)
14501 return commonAlignment(Align(1ull << std::min(31U, AlignBits)), GVOffset);
14502 }
14503
14504 // If this is a direct reference to a stack slot, use information about the
14505 // stack slot's alignment.
14506 int FrameIdx = INT_MIN;
14507 int64_t FrameOffset = 0;
14509 FrameIdx = FI->getIndex();
14510 } else if (isBaseWithConstantOffset(Ptr) &&
14512 // Handle FI+Cst
14513 FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
14514 FrameOffset = Ptr.getConstantOperandVal(1);
14515 }
14516
14517 if (FrameIdx != INT_MIN) {
14519 return commonAlignment(MFI.getObjectAlign(FrameIdx), FrameOffset);
14520 }
14521
14522 return std::nullopt;
14523}
14524
14525/// Split the scalar node with EXTRACT_ELEMENT using the provided
14526/// VTs and return the low/high part.
14527std::pair<SDValue, SDValue> SelectionDAG::SplitScalar(const SDValue &N,
14528 const SDLoc &DL,
14529 const EVT &LoVT,
14530 const EVT &HiVT) {
14531 assert(!LoVT.isVector() && !HiVT.isVector() && !N.getValueType().isVector() &&
14532 "Split node must be a scalar type");
14533 SDValue Lo =
14535 SDValue Hi =
14537 return std::make_pair(Lo, Hi);
14538}
14539
14540/// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type
14541/// which is split (or expanded) into two not necessarily identical pieces.
14542std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const {
14543 // Currently all types are split in half.
14544 EVT LoVT, HiVT;
14545 if (!VT.isVector())
14546 LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT);
14547 else
14548 LoVT = HiVT = VT.getHalfNumVectorElementsVT(*getContext());
14549
14550 return std::make_pair(LoVT, HiVT);
14551}
14552
14553/// GetDependentSplitDestVTs - Compute the VTs needed for the low/hi parts of a
14554/// type, dependent on an enveloping VT that has been split into two identical
14555/// pieces. Sets the HiIsEmpty flag when hi type has zero storage size.
14556std::pair<EVT, EVT>
14558 bool *HiIsEmpty) const {
14559 EVT EltTp = VT.getVectorElementType();
14560 // Examples:
14561 // custom VL=8 with enveloping VL=8/8 yields 8/0 (hi empty)
14562 // custom VL=9 with enveloping VL=8/8 yields 8/1
14563 // custom VL=10 with enveloping VL=8/8 yields 8/2
14564 // etc.
14565 ElementCount VTNumElts = VT.getVectorElementCount();
14566 ElementCount EnvNumElts = EnvVT.getVectorElementCount();
14567 assert(VTNumElts.isScalable() == EnvNumElts.isScalable() &&
14568 "Mixing fixed width and scalable vectors when enveloping a type");
14569 EVT LoVT, HiVT;
14570 if (VTNumElts.getKnownMinValue() > EnvNumElts.getKnownMinValue()) {
14571 LoVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts);
14572 HiVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts - EnvNumElts);
14573 *HiIsEmpty = false;
14574 } else {
14575 // Flag that hi type has zero storage size, but return split envelop type
14576 // (this would be easier if vector types with zero elements were allowed).
14577 LoVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts);
14578 HiVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts);
14579 *HiIsEmpty = true;
14580 }
14581 return std::make_pair(LoVT, HiVT);
14582}
14583
14584/// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the
14585/// low/high part.
14586std::pair<SDValue, SDValue>
14587SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT,
14588 const EVT &HiVT) {
14589 assert(LoVT.isScalableVector() == HiVT.isScalableVector() &&
14590 LoVT.isScalableVector() == N.getValueType().isScalableVector() &&
14591 "Splitting vector with an invalid mixture of fixed and scalable "
14592 "vector types");
14594 N.getValueType().getVectorMinNumElements() &&
14595 "More vector elements requested than available!");
14596 SDValue Lo, Hi;
14597 Lo = getExtractSubvector(DL, LoVT, N, 0);
14598 // For scalable vectors it is safe to use LoVT.getVectorMinNumElements()
14599 // (rather than having to use ElementCount), because EXTRACT_SUBVECTOR scales
14600 // IDX with the runtime scaling factor of the result vector type. For
14601 // fixed-width result vectors, that runtime scaling factor is 1.
14603 return std::make_pair(Lo, Hi);
14604}
14605
14606std::pair<SDValue, SDValue> SelectionDAG::SplitEVL(SDValue N, EVT VecVT,
14607 const SDLoc &DL) {
14608 // Split the vector length parameter.
14609 // %evl -> umin(%evl, %halfnumelts) and usubsat(%evl - %halfnumelts).
14610 EVT VT = N.getValueType();
14612 "Expecting the mask to be an evenly-sized vector");
14613 SDValue HalfNumElts = getElementCount(
14615 SDValue Lo = getNode(ISD::UMIN, DL, VT, N, HalfNumElts);
14616 SDValue Hi = getNode(ISD::USUBSAT, DL, VT, N, HalfNumElts);
14617 return std::make_pair(Lo, Hi);
14618}
14619
14620/// Widen the vector up to the next power of two using INSERT_SUBVECTOR.
14622 EVT VT = N.getValueType();
14625 return getInsertSubvector(DL, getPOISON(WideVT), N, 0);
14626}
14627
14630 unsigned Start, unsigned Count,
14631 EVT EltVT) {
14632 EVT VT = Op.getValueType();
14633 if (Count == 0)
14635 if (EltVT == EVT())
14636 EltVT = VT.getVectorElementType();
14637 SDLoc SL(Op);
14638 for (unsigned i = Start, e = Start + Count; i != e; ++i) {
14639 Args.push_back(getExtractVectorElt(SL, EltVT, Op, i));
14640 }
14641}
14642
14643// getAddressSpace - Return the address space this GlobalAddress belongs to.
14645 return getGlobal()->getType()->getAddressSpace();
14646}
14647
14650 return Val.MachineCPVal->getType();
14651 return Val.ConstVal->getType();
14652}
14653
14654bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue, APInt &SplatUndef,
14655 unsigned &SplatBitSize,
14656 bool &HasAnyUndefs,
14657 unsigned MinSplatBits,
14658 bool IsBigEndian) const {
14659 EVT VT = getValueType(0);
14660 assert(VT.isVector() && "Expected a vector type");
14661 unsigned VecWidth = VT.getSizeInBits();
14662 if (MinSplatBits > VecWidth)
14663 return false;
14664
14665 // FIXME: The widths are based on this node's type, but build vectors can
14666 // truncate their operands.
14667 SplatValue = APInt(VecWidth, 0);
14668 SplatUndef = APInt(VecWidth, 0);
14669
14670 // Get the bits. Bits with undefined values (when the corresponding element
14671 // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared
14672 // in SplatValue. If any of the values are not constant, give up and return
14673 // false.
14674 unsigned int NumOps = getNumOperands();
14675 assert(NumOps > 0 && "isConstantSplat has 0-size build vector");
14676 unsigned EltWidth = VT.getScalarSizeInBits();
14677
14678 for (unsigned j = 0; j < NumOps; ++j) {
14679 unsigned i = IsBigEndian ? NumOps - 1 - j : j;
14680 SDValue OpVal = getOperand(i);
14681 unsigned BitPos = j * EltWidth;
14682
14683 if (OpVal.isUndef())
14684 SplatUndef.setBits(BitPos, BitPos + EltWidth);
14685 else if (auto *CN = dyn_cast<ConstantSDNode>(OpVal))
14686 SplatValue.insertBits(CN->getAPIntValue().zextOrTrunc(EltWidth), BitPos);
14687 else if (auto *CN = dyn_cast<ConstantFPSDNode>(OpVal))
14688 SplatValue.insertBits(CN->getValueAPF().bitcastToAPInt(), BitPos);
14689 else
14690 return false;
14691 }
14692
14693 // The build_vector is all constants or undefs. Find the smallest element
14694 // size that splats the vector.
14695 HasAnyUndefs = (SplatUndef != 0);
14696
14697 // FIXME: This does not work for vectors with elements less than 8 bits.
14698 while (VecWidth > 8) {
14699 // If we can't split in half, stop here.
14700 if (VecWidth & 1)
14701 break;
14702
14703 unsigned HalfSize = VecWidth / 2;
14704 APInt HighValue = SplatValue.extractBits(HalfSize, HalfSize);
14705 APInt LowValue = SplatValue.extractBits(HalfSize, 0);
14706 APInt HighUndef = SplatUndef.extractBits(HalfSize, HalfSize);
14707 APInt LowUndef = SplatUndef.extractBits(HalfSize, 0);
14708
14709 // If the two halves do not match (ignoring undef bits), stop here.
14710 if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) ||
14711 MinSplatBits > HalfSize)
14712 break;
14713
14714 SplatValue = HighValue | LowValue;
14715 SplatUndef = HighUndef & LowUndef;
14716
14717 VecWidth = HalfSize;
14718 }
14719
14720 // FIXME: The loop above only tries to split in halves. But if the input
14721 // vector for example is <3 x i16> it wouldn't be able to detect a
14722 // SplatBitSize of 16. No idea if that is a design flaw currently limiting
14723 // optimizations. I guess that back in the days when this helper was created
14724 // vectors normally was power-of-2 sized.
14725
14726 SplatBitSize = VecWidth;
14727 return true;
14728}
14729
14731 BitVector *UndefElements) const {
14732 unsigned NumOps = getNumOperands();
14733 if (UndefElements) {
14734 UndefElements->clear();
14735 UndefElements->resize(NumOps);
14736 }
14737 assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size");
14738 if (!DemandedElts)
14739 return SDValue();
14740 SDValue Splatted;
14741 for (unsigned i = 0; i != NumOps; ++i) {
14742 if (!DemandedElts[i])
14743 continue;
14744 SDValue Op = getOperand(i);
14745 if (Op.isUndef()) {
14746 if (UndefElements)
14747 (*UndefElements)[i] = true;
14748 } else if (!Splatted) {
14749 Splatted = Op;
14750 } else if (Splatted != Op) {
14751 return SDValue();
14752 }
14753 }
14754
14755 if (!Splatted) {
14756 unsigned FirstDemandedIdx = DemandedElts.countr_zero();
14757 assert(getOperand(FirstDemandedIdx).isUndef() &&
14758 "Can only have a splat without a constant for all undefs.");
14759 return getOperand(FirstDemandedIdx);
14760 }
14761
14762 return Splatted;
14763}
14764
14766 APInt DemandedElts = APInt::getAllOnes(getNumOperands());
14767 return getSplatValue(DemandedElts, UndefElements);
14768}
14769
14771 SmallVectorImpl<SDValue> &Sequence,
14772 BitVector *UndefElements) const {
14773 unsigned NumOps = getNumOperands();
14774 Sequence.clear();
14775 if (UndefElements) {
14776 UndefElements->clear();
14777 UndefElements->resize(NumOps);
14778 }
14779 assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size");
14780 if (!DemandedElts || NumOps < 2 || !isPowerOf2_32(NumOps))
14781 return false;
14782
14783 // Set the undefs even if we don't find a sequence (like getSplatValue).
14784 if (UndefElements)
14785 for (unsigned I = 0; I != NumOps; ++I)
14786 if (DemandedElts[I] && getOperand(I).isUndef())
14787 (*UndefElements)[I] = true;
14788
14789 // Iteratively widen the sequence length looking for repetitions.
14790 for (unsigned SeqLen = 1; SeqLen < NumOps; SeqLen *= 2) {
14791 Sequence.append(SeqLen, SDValue());
14792 for (unsigned I = 0; I != NumOps; ++I) {
14793 if (!DemandedElts[I])
14794 continue;
14795 SDValue &SeqOp = Sequence[I % SeqLen];
14797 if (Op.isUndef()) {
14798 if (!SeqOp)
14799 SeqOp = Op;
14800 continue;
14801 }
14802 if (SeqOp && !SeqOp.isUndef() && SeqOp != Op) {
14803 Sequence.clear();
14804 break;
14805 }
14806 SeqOp = Op;
14807 }
14808 if (!Sequence.empty())
14809 return true;
14810 }
14811
14812 assert(Sequence.empty() && "Failed to empty non-repeating sequence pattern");
14813 return false;
14814}
14815
14817 BitVector *UndefElements) const {
14818 APInt DemandedElts = APInt::getAllOnes(getNumOperands());
14819 return getRepeatedSequence(DemandedElts, Sequence, UndefElements);
14820}
14821
14824 BitVector *UndefElements) const {
14826 getSplatValue(DemandedElts, UndefElements));
14827}
14828
14831 return dyn_cast_or_null<ConstantSDNode>(getSplatValue(UndefElements));
14832}
14833
14836 BitVector *UndefElements) const {
14838 getSplatValue(DemandedElts, UndefElements));
14839}
14840
14845
14846int32_t
14848 uint32_t BitWidth) const {
14849 if (ConstantFPSDNode *CN =
14851 bool IsExact;
14852 APSInt IntVal(BitWidth);
14853 const APFloat &APF = CN->getValueAPF();
14854 if (APF.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) !=
14855 APFloat::opOK ||
14856 !IsExact)
14857 return -1;
14858
14859 return IntVal.exactLogBase2();
14860 }
14861 return -1;
14862}
14863
14865 bool IsLittleEndian, unsigned DstEltSizeInBits,
14866 SmallVectorImpl<APInt> &RawBitElements, BitVector &UndefElements) const {
14867 // Early-out if this contains anything but Undef/Constant/ConstantFP.
14868 if (!isConstant())
14869 return false;
14870
14871 unsigned NumSrcOps = getNumOperands();
14872 unsigned SrcEltSizeInBits = getValueType(0).getScalarSizeInBits();
14873 assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 &&
14874 "Invalid bitcast scale");
14875
14876 // Extract raw src bits.
14877 SmallVector<APInt> SrcBitElements(NumSrcOps,
14878 APInt::getZero(SrcEltSizeInBits));
14879 BitVector SrcUndeElements(NumSrcOps, false);
14880
14881 for (unsigned I = 0; I != NumSrcOps; ++I) {
14883 if (Op.isUndef()) {
14884 SrcUndeElements.set(I);
14885 continue;
14886 }
14887 auto *CInt = dyn_cast<ConstantSDNode>(Op);
14888 auto *CFP = dyn_cast<ConstantFPSDNode>(Op);
14889 assert((CInt || CFP) && "Unknown constant");
14890 SrcBitElements[I] = CInt ? CInt->getAPIntValue().trunc(SrcEltSizeInBits)
14891 : CFP->getValueAPF().bitcastToAPInt();
14892 }
14893
14894 // Recast to dst width.
14895 recastRawBits(IsLittleEndian, DstEltSizeInBits, RawBitElements,
14896 SrcBitElements, UndefElements, SrcUndeElements);
14897 return true;
14898}
14899
14900void BuildVectorSDNode::recastRawBits(bool IsLittleEndian,
14901 unsigned DstEltSizeInBits,
14902 SmallVectorImpl<APInt> &DstBitElements,
14903 ArrayRef<APInt> SrcBitElements,
14904 BitVector &DstUndefElements,
14905 const BitVector &SrcUndefElements) {
14906 unsigned NumSrcOps = SrcBitElements.size();
14907 unsigned SrcEltSizeInBits = SrcBitElements[0].getBitWidth();
14908 assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 &&
14909 "Invalid bitcast scale");
14910 assert(NumSrcOps == SrcUndefElements.size() &&
14911 "Vector size mismatch");
14912
14913 unsigned NumDstOps = (NumSrcOps * SrcEltSizeInBits) / DstEltSizeInBits;
14914 DstUndefElements.clear();
14915 DstUndefElements.resize(NumDstOps, false);
14916 DstBitElements.assign(NumDstOps, APInt::getZero(DstEltSizeInBits));
14917
14918 // Concatenate src elements constant bits together into dst element.
14919 if (SrcEltSizeInBits <= DstEltSizeInBits) {
14920 unsigned Scale = DstEltSizeInBits / SrcEltSizeInBits;
14921 for (unsigned I = 0; I != NumDstOps; ++I) {
14922 DstUndefElements.set(I);
14923 APInt &DstBits = DstBitElements[I];
14924 for (unsigned J = 0; J != Scale; ++J) {
14925 unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1));
14926 if (SrcUndefElements[Idx])
14927 continue;
14928 DstUndefElements.reset(I);
14929 const APInt &SrcBits = SrcBitElements[Idx];
14930 assert(SrcBits.getBitWidth() == SrcEltSizeInBits &&
14931 "Illegal constant bitwidths");
14932 DstBits.insertBits(SrcBits, J * SrcEltSizeInBits);
14933 }
14934 }
14935 return;
14936 }
14937
14938 // Split src element constant bits into dst elements.
14939 unsigned Scale = SrcEltSizeInBits / DstEltSizeInBits;
14940 for (unsigned I = 0; I != NumSrcOps; ++I) {
14941 if (SrcUndefElements[I]) {
14942 DstUndefElements.set(I * Scale, (I + 1) * Scale);
14943 continue;
14944 }
14945 const APInt &SrcBits = SrcBitElements[I];
14946 for (unsigned J = 0; J != Scale; ++J) {
14947 unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1));
14948 APInt &DstBits = DstBitElements[Idx];
14949 DstBits = SrcBits.extractBits(DstEltSizeInBits, J * DstEltSizeInBits);
14950 }
14951 }
14952}
14953
14955 for (const SDValue &Op : op_values()) {
14956 unsigned Opc = Op.getOpcode();
14957 if (!Op.isUndef() && Opc != ISD::Constant && Opc != ISD::ConstantFP)
14958 return false;
14959 }
14960 return true;
14961}
14962
14963std::optional<std::pair<APInt, APInt>>
14965 unsigned NumOps = getNumOperands();
14966 if (NumOps < 2)
14967 return std::nullopt;
14968
14969 unsigned EltSize = getValueType(0).getScalarSizeInBits();
14970 APInt Start, Stride;
14971 int FirstIdx = -1, SecondIdx = -1;
14972
14973 // Find the first two non-undef constant elements to determine Start and
14974 // Stride, then verify all remaining elements match the sequence.
14975 for (unsigned I = 0; I < NumOps; ++I) {
14977 if (Op->isUndef())
14978 continue;
14979 if (!isa<ConstantSDNode>(Op))
14980 return std::nullopt;
14981
14982 APInt Val = getConstantOperandAPInt(I).trunc(EltSize);
14983 if (FirstIdx < 0) {
14984 FirstIdx = I;
14985 Start = Val;
14986 } else if (SecondIdx < 0) {
14987 SecondIdx = I;
14988 // Compute stride using modular arithmetic. Simple division would handle
14989 // common strides (1, 2, -1, etc.), but modular inverse maximizes matches.
14990 // Example: <0, poison, poison, 0xFF> has stride 0x55 since 3*0x55 = 0xFF
14991 // Note that modular arithmetic is agnostic to signed/unsigned.
14992 unsigned IdxDiff = I - FirstIdx;
14993 APInt ValDiff = Val - Start;
14994
14995 // Step 1: Factor out common powers of 2 from IdxDiff and ValDiff.
14996 unsigned CommonPow2Bits = llvm::countr_zero(IdxDiff);
14997 if (ValDiff.countr_zero() < CommonPow2Bits)
14998 return std::nullopt; // ValDiff not divisible by 2^CommonPow2Bits
14999 IdxDiff >>= CommonPow2Bits;
15000 ValDiff.lshrInPlace(CommonPow2Bits);
15001
15002 // Step 2: IdxDiff is now odd, so its inverse mod 2^EltSize exists.
15003 // TODO: There are 2^CommonPow2Bits valid strides; currently we only try
15004 // one, but we could try all candidates to handle more cases.
15005 Stride = ValDiff * APInt(EltSize, IdxDiff).multiplicativeInverse();
15006 if (Stride.isZero())
15007 return std::nullopt;
15008
15009 // Step 3: Adjust Start based on the first defined element's index.
15010 Start -= Stride * FirstIdx;
15011 } else {
15012 // Verify this element matches the sequence.
15013 if (Val != Start + Stride * I)
15014 return std::nullopt;
15015 }
15016 }
15017
15018 // Need at least two defined elements.
15019 if (SecondIdx < 0)
15020 return std::nullopt;
15021
15022 return std::make_pair(Start, Stride);
15023}
15024
15026 // Find the first non-undef value in the shuffle mask.
15027 unsigned i, e;
15028 for (i = 0, e = Mask.size(); i != e && Mask[i] < 0; ++i)
15029 /* search */;
15030
15031 // If all elements are undefined, this shuffle can be considered a splat
15032 // (although it should eventually get simplified away completely).
15033 if (i == e)
15034 return true;
15035
15036 // Make sure all remaining elements are either undef or the same as the first
15037 // non-undef value.
15038 for (int Idx = Mask[i]; i != e; ++i)
15039 if (Mask[i] >= 0 && Mask[i] != Idx)
15040 return false;
15041 return true;
15042}
15043
15044// Returns true if it is a constant integer BuildVector or constant integer,
15045// possibly hidden by a bitcast.
15047 SDValue N, bool AllowOpaques) const {
15049
15050 if (auto *C = dyn_cast<ConstantSDNode>(N))
15051 return AllowOpaques || !C->isOpaque();
15052
15054 return true;
15055
15056 // Treat a GlobalAddress supporting constant offset folding as a
15057 // constant integer.
15058 if (auto *GA = dyn_cast<GlobalAddressSDNode>(N))
15059 if (GA->getOpcode() == ISD::GlobalAddress &&
15060 TLI->isOffsetFoldingLegal(GA))
15061 return true;
15062
15063 if ((N.getOpcode() == ISD::SPLAT_VECTOR) &&
15064 isa<ConstantSDNode>(N.getOperand(0)))
15065 return true;
15066 return false;
15067}
15068
15069// Returns true if it is a constant float BuildVector or constant float.
15072 return true;
15073
15075 return true;
15076
15077 if ((N.getOpcode() == ISD::SPLAT_VECTOR) &&
15078 isa<ConstantFPSDNode>(N.getOperand(0)))
15079 return true;
15080
15081 return false;
15082}
15083
15084std::optional<bool> SelectionDAG::isBoolConstant(SDValue N) const {
15085 ConstantSDNode *Const =
15086 isConstOrConstSplat(N, false, /*AllowTruncation=*/true);
15087 if (!Const)
15088 return std::nullopt;
15089
15090 EVT VT = N->getValueType(0);
15091 const APInt CVal = Const->getAPIntValue().trunc(VT.getScalarSizeInBits());
15092 switch (TLI->getBooleanContents(N.getValueType())) {
15094 if (CVal.isOne())
15095 return true;
15096 if (CVal.isZero())
15097 return false;
15098 return std::nullopt;
15100 if (CVal.isAllOnes())
15101 return true;
15102 if (CVal.isZero())
15103 return false;
15104 return std::nullopt;
15106 return CVal[0];
15107 }
15108 llvm_unreachable("Unknown BooleanContent enum");
15109}
15110
15111void SelectionDAG::createOperands(SDNode *Node, ArrayRef<SDValue> Vals) {
15112 assert(!Node->OperandList && "Node already has operands");
15114 "too many operands to fit into SDNode");
15115 SDUse *Ops = OperandRecycler.allocate(
15116 ArrayRecycler<SDUse>::Capacity::get(Vals.size()), OperandAllocator);
15117
15118 bool IsDivergent = false;
15119 for (unsigned I = 0; I != Vals.size(); ++I) {
15120 Ops[I].setUser(Node);
15121 Ops[I].setInitial(Vals[I]);
15122 EVT VT = Ops[I].getValueType();
15123
15124 // Skip Chain. It does not carry divergence.
15125 if (VT != MVT::Other &&
15126 (VT != MVT::Glue || gluePropagatesDivergence(Ops[I].getNode())) &&
15127 Ops[I].getNode()->isDivergent()) {
15128 IsDivergent = true;
15129 }
15130 }
15131 Node->NumOperands = Vals.size();
15132 Node->OperandList = Ops;
15133 if (!TLI->isSDNodeAlwaysUniform(Node)) {
15134 IsDivergent |= TLI->isSDNodeSourceOfDivergence(Node, FLI, UA);
15135 Node->SDNodeBits.IsDivergent = IsDivergent;
15136 }
15137 checkForCycles(Node);
15138}
15139
15142 size_t Limit = SDNode::getMaxNumOperands();
15143 while (Vals.size() > Limit) {
15144 unsigned SliceIdx = Vals.size() - Limit;
15145 auto ExtractedTFs = ArrayRef<SDValue>(Vals).slice(SliceIdx, Limit);
15146 SDValue NewTF = getNode(ISD::TokenFactor, DL, MVT::Other, ExtractedTFs);
15147 Vals.erase(Vals.begin() + SliceIdx, Vals.end());
15148 Vals.emplace_back(NewTF);
15149 }
15150 return getNode(ISD::TokenFactor, DL, MVT::Other, Vals);
15151}
15152
15154 EVT VT, SDNodeFlags Flags) {
15155 switch (Opcode) {
15156 default:
15157 return SDValue();
15158 case ISD::ADD:
15159 case ISD::OR:
15160 case ISD::XOR:
15161 case ISD::UMAX:
15162 case ISD::MUL:
15163 case ISD::AND:
15164 case ISD::UMIN:
15165 case ISD::SMAX:
15166 case ISD::SMIN:
15168 VT);
15169 case ISD::FADD:
15170 // If flags allow, prefer positive zero since it's generally cheaper
15171 // to materialize on most targets.
15172 return getConstantFP(Flags.hasNoSignedZeros() ? 0.0 : -0.0, DL, VT);
15173 case ISD::FMUL:
15174 return getConstantFP(1.0, DL, VT);
15175 case ISD::FMINNUM:
15176 case ISD::FMAXNUM:
15177 case ISD::FMINIMUMNUM:
15178 case ISD::FMAXIMUMNUM: {
15179 // Neutral element for fminnum/fminimumnum is NaN, Inf or FLT_MAX,
15180 // depending on fast-math flags (FMF).
15181 const fltSemantics &Semantics = VT.getFltSemantics();
15182 APFloat NeutralAF = !Flags.hasNoNaNs() ? APFloat::getQNaN(Semantics) :
15183 !Flags.hasNoInfs() ? APFloat::getInf(Semantics) :
15184 APFloat::getLargest(Semantics);
15185 if (Opcode == ISD::FMAXNUM || Opcode == ISD::FMAXIMUMNUM)
15186 NeutralAF.changeSign();
15187
15188 return getConstantFP(NeutralAF, DL, VT);
15189 }
15190 case ISD::FMINIMUM:
15191 case ISD::FMAXIMUM: {
15192 // Neutral element for fminimum is Inf or FLT_MAX, depending on FMF.
15193 const fltSemantics &Semantics = VT.getFltSemantics();
15194 APFloat NeutralAF = !Flags.hasNoInfs() ? APFloat::getInf(Semantics)
15195 : APFloat::getLargest(Semantics);
15196 if (Opcode == ISD::FMAXIMUM)
15197 NeutralAF.changeSign();
15198
15199 return getConstantFP(NeutralAF, DL, VT);
15200 }
15201
15202 }
15203}
15204
15206 SDValue Acc, SDValue LHS,
15207 SDValue RHS) {
15208 EVT AccVT = Acc.getValueType();
15209 if (AccVT.isFloatingPoint()) {
15210 assert(Opc == ISD::PARTIAL_REDUCE_FMLA && "Unexpected opcode");
15211 SDValue NegRHS = getNode(ISD::FNEG, DL, RHS.getValueType(), RHS);
15212 return getNode(Opc, DL, AccVT, Acc, LHS, NegRHS);
15213 }
15215 "Unexpected opcode");
15216 SDValue NegAcc = getNegative(Acc, DL, AccVT);
15217 SDValue MLA = getNode(Opc, DL, AccVT, NegAcc, LHS, RHS);
15218 return getNegative(MLA, DL, AccVT);
15219}
15220
15221/// Helper used to make a call to a library function that has one argument of
15222/// pointer type.
15223///
15224/// Such functions include 'fegetmode', 'fesetenv' and some others, which are
15225/// used to get or set floating-point state. They have one argument of pointer
15226/// type, which points to the memory region containing bits of the
15227/// floating-point state. The value returned by such function is ignored in the
15228/// created call.
15229///
15230/// \param LibFunc Reference to library function (value of RTLIB::Libcall).
15231/// \param Ptr Pointer used to save/load state.
15232/// \param InChain Ingoing token chain.
15233/// \returns Outgoing chain token.
15235 SDValue InChain,
15236 const SDLoc &DLoc) {
15237 assert(InChain.getValueType() == MVT::Other && "Expected token chain");
15239 Args.emplace_back(Ptr, Ptr.getValueType().getTypeForEVT(*getContext()));
15240 RTLIB::LibcallImpl LibcallImpl =
15241 Libcalls->getLibcallImpl(static_cast<RTLIB::Libcall>(LibFunc));
15242 if (LibcallImpl == RTLIB::Unsupported)
15243 reportFatalUsageError("emitting call to unsupported libcall");
15244
15245 SDValue Callee =
15246 getExternalSymbol(LibcallImpl, TLI->getPointerTy(getDataLayout()));
15248 CLI.setDebugLoc(DLoc).setChain(InChain).setLibCallee(
15249 Libcalls->getLibcallImplCallingConv(LibcallImpl),
15250 Type::getVoidTy(*getContext()), Callee, std::move(Args));
15251 return TLI->LowerCallTo(CLI).second;
15252}
15253
15255 assert(From && To && "Invalid SDNode; empty source SDValue?");
15256 auto I = SDEI.find(From);
15257 if (I == SDEI.end())
15258 return;
15259
15260 // Use of operator[] on the DenseMap may cause an insertion, which invalidates
15261 // the iterator, hence the need to make a copy to prevent a use-after-free.
15262 NodeExtraInfo NEI = I->second;
15263 if (LLVM_LIKELY(!NEI.PCSections)) {
15264 // No deep copy required for the types of extra info set.
15265 //
15266 // FIXME: Investigate if other types of extra info also need deep copy. This
15267 // depends on the types of nodes they can be attached to: if some extra info
15268 // is only ever attached to nodes where a replacement To node is always the
15269 // node where later use and propagation of the extra info has the intended
15270 // semantics, no deep copy is required.
15271 SDEI[To] = std::move(NEI);
15272 return;
15273 }
15274
15275 const SDNode *EntrySDN = getEntryNode().getNode();
15276
15277 // We need to copy NodeExtraInfo to all _new_ nodes that are being introduced
15278 // through the replacement of From with To. Otherwise, replacements of a node
15279 // (From) with more complex nodes (To and its operands) may result in lost
15280 // extra info where the root node (To) is insignificant in further propagating
15281 // and using extra info when further lowering to MIR.
15282 //
15283 // In the first step pre-populate the visited set with the nodes reachable
15284 // from the old From node. This avoids copying NodeExtraInfo to parts of the
15285 // DAG that is not new and should be left untouched.
15286 SmallVector<const SDNode *> Leafs{From}; // Leafs reachable with VisitFrom.
15287 DenseSet<const SDNode *> FromReach; // The set of nodes reachable from From.
15288 auto VisitFrom = [&](auto &&Self, const SDNode *N, int MaxDepth) {
15289 if (MaxDepth == 0) {
15290 // Remember this node in case we need to increase MaxDepth and continue
15291 // populating FromReach from this node.
15292 Leafs.emplace_back(N);
15293 return;
15294 }
15295 if (!FromReach.insert(N).second)
15296 return;
15297 for (const SDValue &Op : N->op_values())
15298 Self(Self, Op.getNode(), MaxDepth - 1);
15299 };
15300
15301 // Copy extra info to To and all its transitive operands (that are new).
15303 auto DeepCopyTo = [&](auto &&Self, const SDNode *N) {
15304 if (FromReach.contains(N))
15305 return true;
15306 if (!Visited.insert(N).second)
15307 return true;
15308 if (EntrySDN == N)
15309 return false;
15310 for (const SDValue &Op : N->op_values()) {
15311 if (N == To && Op.getNode() == EntrySDN) {
15312 // Special case: New node's operand is the entry node; just need to
15313 // copy extra info to new node.
15314 break;
15315 }
15316 if (!Self(Self, Op.getNode()))
15317 return false;
15318 }
15319 // Copy only if entry node was not reached.
15320 SDEI[N] = std::move(NEI);
15321 return true;
15322 };
15323
15324 // We first try with a lower MaxDepth, assuming that the path to common
15325 // operands between From and To is relatively short. This significantly
15326 // improves performance in the common case. The initial MaxDepth is big
15327 // enough to avoid retry in the common case; the last MaxDepth is large
15328 // enough to avoid having to use the fallback below (and protects from
15329 // potential stack exhaustion from recursion).
15330 for (int PrevDepth = 0, MaxDepth = 16; MaxDepth <= 1024;
15331 PrevDepth = MaxDepth, MaxDepth *= 2, Visited.clear()) {
15332 // StartFrom is the previous (or initial) set of leafs reachable at the
15333 // previous maximum depth.
15335 std::swap(StartFrom, Leafs);
15336 for (const SDNode *N : StartFrom)
15337 VisitFrom(VisitFrom, N, MaxDepth - PrevDepth);
15338 if (LLVM_LIKELY(DeepCopyTo(DeepCopyTo, To)))
15339 return;
15340 // This should happen very rarely (reached the entry node).
15341 LLVM_DEBUG(dbgs() << __func__ << ": MaxDepth=" << MaxDepth << " too low\n");
15342 assert(!Leafs.empty());
15343 }
15344
15345 // This should not happen - but if it did, that means the subgraph reachable
15346 // from From has depth greater or equal to maximum MaxDepth, and VisitFrom()
15347 // could not visit all reachable common operands. Consequently, we were able
15348 // to reach the entry node.
15349 errs() << "warning: incomplete propagation of SelectionDAG::NodeExtraInfo\n";
15350 assert(false && "From subgraph too complex - increase max. MaxDepth?");
15351 // Best-effort fallback if assertions disabled.
15352 SDEI[To] = std::move(NEI);
15353}
15354
15356 assert(VT.isVector() && "Can only unroll vector types!");
15357 if (VT.isFixedLengthVector())
15358 return VT.getVectorNumElements();
15359
15360 const MachineFunction &MF = getMachineFunction();
15361 const Function &F = MF.getFunction();
15362
15363 APInt MaxVScale = getVScaleRange(&F, sizeof(unsigned) * 8).getUnsignedMax();
15364 if (MaxVScale.ugt(VScaleUnrollLimit))
15365 return 0;
15366
15367 bool Overflow;
15368 APInt MinNElts(sizeof(unsigned) * 8, VT.getVectorMinNumElements());
15369 APInt MaxNElts = MinNElts.umul_ov(MaxVScale, Overflow);
15370 if (Overflow)
15371 return 0;
15372
15373 return MaxNElts.getZExtValue();
15374}
15375
15377 ArrayRef<SDValue> Scalars) {
15378 assert(Scalars.size() == getMaxRuntimeNumElements(VT) &&
15379 "Element count mismatch!");
15380 if (VT.isFixedLengthVector())
15381 return getBuildVector(VT, DL, Scalars);
15382
15383 SDValue Vec = getPOISON(VT);
15384 // Iterate in reverse so result remains poison until we encounter a lane that
15385 // exists, after which all lower-numbered lanes must also exist.
15386 for (unsigned IdxVal : reverse(seq(Scalars.size())))
15387 Vec = getInsertVectorElt(DL, Vec, Scalars[IdxVal], IdxVal);
15388
15389 return Vec;
15390}
15391
15392#ifndef NDEBUG
15393static void checkForCyclesHelper(const SDNode *N,
15396 const llvm::SelectionDAG *DAG) {
15397 // If this node has already been checked, don't check it again.
15398 if (Checked.count(N))
15399 return;
15400
15401 // If a node has already been visited on this depth-first walk, reject it as
15402 // a cycle.
15403 if (!Visited.insert(N).second) {
15404 errs() << "Detected cycle in SelectionDAG\n";
15405 dbgs() << "Offending node:\n";
15406 N->dumprFull(DAG); dbgs() << "\n";
15407 abort();
15408 }
15409
15410 for (const SDValue &Op : N->op_values())
15411 checkForCyclesHelper(Op.getNode(), Visited, Checked, DAG);
15412
15413 Checked.insert(N);
15414 Visited.erase(N);
15415}
15416#endif
15417
15419 const llvm::SelectionDAG *DAG,
15420 bool force) {
15421#ifndef NDEBUG
15422 bool check = force;
15423#ifdef EXPENSIVE_CHECKS
15424 check = true;
15425#endif // EXPENSIVE_CHECKS
15426 if (check) {
15427 assert(N && "Checking nonexistent SDNode");
15430 checkForCyclesHelper(N, visited, checked, DAG);
15431 }
15432#endif // !NDEBUG
15433}
15434
15435void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) {
15436 checkForCycles(DAG->getRoot().getNode(), DAG, force);
15437}
return SDValue()
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:609
#define LLVM_LIKELY(EXPR)
Definition Compiler.h:343
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:539
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 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 void checkAddrSpaceIsValidForLibcall(const TargetLowering *TLI, unsigned AS)
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:6010
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:2007
LLVM_ABI APInt usub_sat(const APInt &RHS) const
Definition APInt.cpp:2091
LLVM_ABI APInt udiv(const APInt &RHS) const
Unsigned division operation.
Definition APInt.cpp:1600
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
Definition APInt.h:231
void clearBit(unsigned BitPosition)
Set a given bit to 0.
Definition APInt.h:1427
LLVM_ABI APInt zext(unsigned width) const
Zero extend to a new width.
Definition APInt.cpp:1056
static APInt getSignMask(unsigned BitWidth)
Get the SignMask for a specific bit width.
Definition APInt.h:226
bool isMinSignedValue() const
Determine if this is the smallest signed value.
Definition APInt.h:420
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1561
unsigned popcount() const
Count the number of bits set.
Definition APInt.h:1691
LLVM_ABI APInt zextOrTrunc(unsigned width) const
Zero extend or truncate to width.
Definition APInt.cpp:1077
unsigned getActiveBits() const
Compute the number of active bits in the value.
Definition APInt.h:1533
LLVM_ABI APInt trunc(unsigned width) const
Truncate to new width.
Definition APInt.cpp:969
void setBit(unsigned BitPosition)
Set the given bit to 1 whose position is given as "bitPosition".
Definition APInt.h:1351
APInt abs() const
Get the absolute value.
Definition APInt.h:1816
LLVM_ABI APInt sadd_sat(const APInt &RHS) const
Definition APInt.cpp:2062
bool isAllOnes() const
Determine if all bits are set. This is true for zero-width values.
Definition APInt.h:368
bool ugt(const APInt &RHS) const
Unsigned greater than comparison.
Definition APInt.h:1187
static APInt getBitsSet(unsigned numBits, unsigned loBit, unsigned hiBit)
Get a value with a block of bits set.
Definition APInt.h:255
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition APInt.h:377
LLVM_ABI APInt urem(const APInt &RHS) const
Unsigned remainder operation.
Definition APInt.cpp:1693
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1509
bool ult(const APInt &RHS) const
Unsigned less than comparison.
Definition APInt.h:1116
static APInt getSignedMaxValue(unsigned numBits)
Gets maximum signed value of APInt for a specific bit width.
Definition APInt.h:206
bool isNegative() const
Determine sign of this APInt.
Definition APInt.h:326
LLVM_ABI APInt sdiv(const APInt &RHS) const
Signed division function for APInt.
Definition APInt.cpp:1671
LLVM_ABI APInt rotr(unsigned rotateAmt) const
Rotate right by rotateAmt.
Definition APInt.cpp:1198
LLVM_ABI APInt reverseBits() const
Definition APInt.cpp:785
void ashrInPlace(unsigned ShiftAmt)
Arithmetic right-shift this APInt by ShiftAmt in place.
Definition APInt.h:837
bool sle(const APInt &RHS) const
Signed less or equal comparison.
Definition APInt.h:1171
unsigned countr_zero() const
Count the number of trailing zero bits.
Definition APInt.h:1660
unsigned getNumSignBits() const
Computes the number of leading bits of this APInt that are equal to its sign bit.
Definition APInt.h:1649
unsigned countl_zero() const
The APInt version of std::countl_zero.
Definition APInt.h:1619
static LLVM_ABI APInt getSplat(unsigned NewLen, const APInt &V)
Return a value containing V broadcasted over NewLen bits.
Definition APInt.cpp:647
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
Definition APInt.h:216
LLVM_ABI APInt sshl_sat(const APInt &RHS) const
Definition APInt.cpp:2122
LLVM_ABI APInt ushl_sat(const APInt &RHS) const
Definition APInt.cpp:2136
LLVM_ABI APInt sextOrTrunc(unsigned width) const
Sign extend or truncate to width.
Definition APInt.cpp:1085
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:551
LLVM_ABI APInt rotl(unsigned rotateAmt) const
Rotate left by rotateAmt.
Definition APInt.cpp:1185
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:1782
LLVM_ABI APInt uadd_sat(const APInt &RHS) const
Definition APInt.cpp:2072
APInt ashr(unsigned ShiftAmt) const
Arithmetic right-shift function.
Definition APInt.h:830
LLVM_ABI APInt multiplicativeInverse() const
Definition APInt.cpp:1301
LLVM_ABI APInt srem(const APInt &RHS) const
Function for signed remainder operation.
Definition APInt.cpp:1772
bool isNonNegative() const
Determine if this APInt Value is non-negative (>= 0)
Definition APInt.h:331
bool ule(const APInt &RHS) const
Unsigned less or equal comparison.
Definition APInt.h:1155
LLVM_ABI APInt sext(unsigned width) const
Sign extend to a new width.
Definition APInt.cpp:1029
void setBits(unsigned loBit, unsigned hiBit)
Set the bits from loBit (inclusive) to hiBit (exclusive) to 1.
Definition APInt.h:1388
APInt shl(unsigned shiftAmt) const
Left-shift function.
Definition APInt.h:876
LLVM_ABI APInt byteSwap() const
Definition APInt.cpp:763
bool isSubsetOf(const APInt &RHS) const
This operation checks that all bits set in this APInt are also set in RHS.
Definition APInt.h:1262
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
Definition APInt.h:437
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Constructs an APInt value that has the bottom loBitsSet bits set.
Definition APInt.h:303
void clearBits(unsigned LoBit, unsigned HiBit)
Clear the bits from LoBit (inclusive) to HiBit (exclusive) to 0.
Definition APInt.h:1438
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition APInt.h:197
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:1242
bool isOne() const
Determine if this is a value of 1.
Definition APInt.h:386
static APInt getBitsSetFrom(unsigned numBits, unsigned loBit)
Constructs an APInt value that has a contiguous range of bits set.
Definition APInt.h:283
static APInt getOneBitSet(unsigned numBits, unsigned BitNo)
Return an APInt with exactly one bit set in the result.
Definition APInt.h:236
void lshrInPlace(unsigned ShiftAmt)
Logical right-shift this APInt by ShiftAmt in place.
Definition APInt.h:861
APInt lshr(unsigned shiftAmt) const
Logical right-shift function.
Definition APInt.h:854
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
Definition APInt.h:1226
LLVM_ABI APInt ssub_sat(const APInt &RHS) const
Definition APInt.cpp:2081
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:309
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
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:1069
const MDOperand & getOperand(unsigned I) const
Definition Metadata.h:1426
Machine Value Type.
SimpleValueType SimpleTy
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,.
This class contains meta information specific to a module.
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
The optimization diagnostic interface.
Pass interface - Implemented by all 'passes'.
Definition Pass.h:99
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:911
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 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 getAddrSpaceCast(const SDLoc &dl, EVT VT, SDValue Ptr, unsigned SrcAS, unsigned DestAS)
Return an AddrSpaceCastSDNode.
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 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 void init(MachineFunction &NewMF, OptimizationRemarkEmitter &NewORE, Pass *PassPtr, const TargetLibraryInfo *LibraryInfo, const LibcallLoweringInfo *LibcallsInfo, UniformityInfo *UA, ProfileSummaryInfo *PSIin, BlockFrequencyInfo *BFIin, MachineModuleInfo &MMI, FunctionVarLocs const *FnVarLocs)
Prepare this SelectionDAG to process code in the given MachineFunction.
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 getBitcastedSExtOrTrunc(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 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.
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 getBitcastedZExtOrTrunc(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 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
bool hasSwiftErrorArg() const
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
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 makeStateFunctionCall(unsigned LibFunc, SDValue Ptr, SDValue InChain, const SDLoc &DLoc)
Helper used to make a call to a library function that has one argument of pointer type.
LLVM_ABI SDValue getSignedConstant(int64_t Val, const SDLoc &DL, EVT VT, bool isTarget=false, bool isOpaque=false)
LLVM_ABI SDValue getIndexedLoadVP(SDValue OrigLoad, const SDLoc &dl, SDValue Base, SDValue Offset, ISD::MemIndexedMode AM)
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 SDValue getIndexedStoreVP(SDValue OrigStore, const SDLoc &dl, SDValue Base, SDValue Offset, ISD::MemIndexedMode AM)
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 SDValue getTruncStridedStoreVP(SDValue Chain, const SDLoc &DL, SDValue Val, SDValue Ptr, SDValue Stride, SDValue Mask, SDValue EVL, EVT SVT, MachineMemOperand *MMO, bool IsCompressing=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.
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.
virtual bool isNoopAddrSpaceCast(unsigned SrcAS, unsigned DestAS) const
Returns true if a cast between SrcAS and DestAS is a noop.
const Triple & getTargetTriple() const
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:722
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:343
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:288
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:309
static LLVM_ABI Type * getVoidTy(LLVMContext &C)
Definition Type.cpp:282
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
Definition Type.cpp:307
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:197
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.cpp:232
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:874
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:255
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.multiplyCoefficientBy(X) will result in a value whos...
Definition TypeSize.h:269
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:3233
LLVM_ABI APInt mulhu(const APInt &C1, const APInt &C2)
Performs (2*N)-bit multiplication on zero-extended operands.
Definition APInt.cpp:3163
LLVM_ABI APInt avgCeilU(const APInt &C1, const APInt &C2)
Compute the ceil of the unsigned average of C1 and C2.
Definition APInt.cpp:3150
LLVM_ABI APInt avgFloorU(const APInt &C1, const APInt &C2)
Compute the floor of the unsigned average of C1 and C2.
Definition APInt.cpp:3140
LLVM_ABI APInt pext(const APInt &Val, const APInt &Mask)
Perform a "compress" operation, also known as pext or bext.
Definition APInt.cpp:3243
LLVM_ABI APInt fshr(const APInt &Hi, const APInt &Lo, const APInt &Shift)
Perform a funnel shift right.
Definition APInt.cpp:3214
LLVM_ABI APInt mulhs(const APInt &C1, const APInt &C2)
Performs (2*N)-bit multiplication on sign-extended operands.
Definition APInt.cpp:3155
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:3223
LLVM_ABI APInt pdep(const APInt &Val, const APInt &Mask)
Perform an "expand" operation, also known as pdep or bdep.
Definition APInt.cpp:3253
APInt abds(const APInt &A, const APInt &B)
Determine the absolute difference of two APInts considered to be signed.
Definition APInt.h:2295
LLVM_ABI APInt fshl(const APInt &Hi, const APInt &Lo, const APInt &Shift)
Perform a funnel shift left.
Definition APInt.cpp:3205
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:3041
LLVM_ABI APInt clmulh(const APInt &LHS, const APInt &RHS)
Perform a carry-less multiply, and return high-bits.
Definition APInt.cpp:3238
APInt abdu(const APInt &A, const APInt &B)
Determine the absolute difference of two APInts considered to be unsigned.
Definition APInt.h:2300
LLVM_ABI APInt avgFloorS(const APInt &C1, const APInt &C2)
Compute the floor of the signed average of C1 and C2.
Definition APInt.cpp:3135
LLVM_ABI APInt avgCeilS(const APInt &C1, const APInt &C2)
Compute the ceil of the signed average of C1 and C2.
Definition APInt.cpp:3145
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:24
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:41
@ SETCC
SetCC operator - This evaluates to a true value iff the condition is true.
Definition ISDOpcodes.h:829
@ MERGE_VALUES
MERGE_VALUES - This node takes multiple discrete operands and returns them all as its individual resu...
Definition ISDOpcodes.h:261
@ TargetConstantPool
Definition ISDOpcodes.h:189
@ 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:513
@ 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:45
@ POISON
POISON - A poison node.
Definition ISDOpcodes.h:236
@ PARTIAL_REDUCE_SMLA
PARTIAL_REDUCE_[U|S]MLA(Accumulator, Input1, Input2) The partial reduction nodes sign or zero extend ...
@ 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:540
@ SMUL_LOHI
SMUL_LOHI/UMUL_LOHI - Multiply two integers of type iN, producing a signed/unsigned value of type i[2...
Definition ISDOpcodes.h:275
@ INSERT_SUBVECTOR
INSERT_SUBVECTOR(VECTOR1, VECTOR2, IDX) - Returns a vector with VECTOR2 inserted into VECTOR1.
Definition ISDOpcodes.h:602
@ JUMP_TABLE_DEBUG_INFO
JUMP_TABLE_DEBUG_INFO - Jumptable debug info.
@ BSWAP
Byte Swap and Counting operators.
Definition ISDOpcodes.h:789
@ TargetBlockAddress
Definition ISDOpcodes.h:191
@ 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:294
@ FMAD
FMAD - Perform a * b + c, while getting the same result as the separately rounded operations.
Definition ISDOpcodes.h:524
@ ADD
Simple integer binary arithmetic operators.
Definition ISDOpcodes.h:264
@ 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:863
@ ATOMIC_LOAD_USUB_COND
@ FMA
FMA - Perform a * b + c with no intermediate rounding step.
Definition ISDOpcodes.h:520
@ FATAN2
FATAN2 - atan2, inspired by libm.
@ INTRINSIC_VOID
OUTCHAIN = INTRINSIC_VOID(INCHAIN, INTRINSICID, arg1, arg2, ...) This node represents a target intrin...
Definition ISDOpcodes.h:220
@ GlobalAddress
Definition ISDOpcodes.h:88
@ 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:890
@ CONCAT_VECTORS
CONCAT_VECTORS(VECTOR0, VECTOR1, ...) - Given a number of values of vector type with the same length ...
Definition ISDOpcodes.h:586
@ VECREDUCE_FMAX
FMIN/FMAX nodes can have flags, for NaN/NoNaN variants.
@ FADD
Simple binary floating point operators.
Definition ISDOpcodes.h:417
@ 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:749
@ SIGN_EXTEND_VECTOR_INREG
SIGN_EXTEND_VECTOR_INREG(Vector) - This operator represents an in-register sign-extension of the low ...
Definition ISDOpcodes.h:920
@ 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:530
@ 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:254
@ CLMUL
Carry-less multiplication operations.
Definition ISDOpcodes.h:780
@ 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:89
@ 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:798
@ ANNOTATION_LABEL
ANNOTATION_LABEL - Represents a mid basic block label used by annotations.
@ PARTIAL_REDUCE_UMLA
@ SIGN_EXTEND
Conversion operators.
Definition ISDOpcodes.h:854
@ AVGCEILS
AVGCEILS/AVGCEILU - Rounding averaging add - Add two integers using an integer of type i[N+2],...
Definition ISDOpcodes.h:717
@ SCALAR_TO_VECTOR
SCALAR_TO_VECTOR(VAL) - This represents the operation of loading a scalar value into element 0 of the...
Definition ISDOpcodes.h:667
@ TargetExternalSymbol
Definition ISDOpcodes.h:190
@ VECREDUCE_FADD
These reductions have relaxed evaluation order semantics, and have a single vector operand.
@ TargetJumpTable
Definition ISDOpcodes.h:188
@ TargetIndex
TargetIndex - Like a constant pool entry, but with completely target-dependent semantics.
Definition ISDOpcodes.h:198
@ PARTIAL_REDUCE_FMLA
@ PREFETCH
PREFETCH - This corresponds to a prefetch intrinsic.
@ TRUNCATE_SSAT_U
Definition ISDOpcodes.h:883
@ 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:837
@ FNEG
Perform various unary floating-point operations inspired by libm.
@ BR_CC
BR_CC - Conditional branch.
@ SSUBO
Same for subtraction.
Definition ISDOpcodes.h:352
@ STEP_VECTOR
STEP_VECTOR(IMM) - Returns a scalable vector whose lanes are comprised of a linear sequence of unsign...
Definition ISDOpcodes.h:693
@ FCANONICALIZE
Returns platform specific canonical encoding of a floating point number.
Definition ISDOpcodes.h:543
@ IS_FPCLASS
Performs a check of floating point class property, defined by IEEE-754.
Definition ISDOpcodes.h:550
@ SSUBSAT
RESULT = [US]SUBSAT(LHS, RHS) - Perform saturation subtraction on 2 integers with the same bit width ...
Definition ISDOpcodes.h:374
@ SELECT
Select(COND, TRUEVAL, FALSEVAL).
Definition ISDOpcodes.h:806
@ ATOMIC_LOAD
Val, OUTCHAIN = ATOMIC_LOAD(INCHAIN, ptr) This corresponds to "load atomic" instruction.
@ UNDEF
UNDEF - An undefined node.
Definition ISDOpcodes.h:233
@ EXTRACT_ELEMENT
EXTRACT_ELEMENT - This is used to get the lower or upper (determined by a Constant,...
Definition ISDOpcodes.h:247
@ SPLAT_VECTOR
SPLAT_VECTOR(VAL) - Returns a vector with the scalar value VAL duplicated in all lanes.
Definition ISDOpcodes.h:674
@ AssertAlign
AssertAlign - These nodes record if a register contains a value that has a known alignment and the tr...
Definition ISDOpcodes.h:69
@ 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:81
@ CopyFromReg
CopyFromReg - This node indicates that the input value is a virtual or physical register that is defi...
Definition ISDOpcodes.h:230
@ SADDO
RESULT, BOOL = [SU]ADDO(LHS, RHS) - Overflow-aware nodes for addition.
Definition ISDOpcodes.h:348
@ TargetGlobalAddress
TargetGlobalAddress - Like GlobalAddress, but the DAG does no folding or anything else with this node...
Definition ISDOpcodes.h:185
@ ARITH_FENCE
ARITH_FENCE - This corresponds to a arithmetic fence intrinsic.
@ CTLS
Count leading redundant sign bits.
Definition ISDOpcodes.h:802
@ 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:706
@ ATOMIC_LOAD_FMAXIMUM
@ SHL
Shift and rotation operations.
Definition ISDOpcodes.h:771
@ AssertNoFPClass
AssertNoFPClass - These nodes record if a register contains a float value that is known to be not som...
Definition ISDOpcodes.h:78
@ VECTOR_SHUFFLE
VECTOR_SHUFFLE(VEC1, VEC2) - Returns a vector, of the same type as VEC1/VEC2.
Definition ISDOpcodes.h:651
@ EXTRACT_SUBVECTOR
EXTRACT_SUBVECTOR(VECTOR, IDX) - Returns a subvector from VECTOR.
Definition ISDOpcodes.h:616
@ 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:48
@ EXTRACT_VECTOR_ELT
EXTRACT_VECTOR_ELT(VECTOR, IDX) - Returns a single element from VECTOR identified by the (potentially...
Definition ISDOpcodes.h:578
@ CopyToReg
CopyToReg - This node has three operands: a chain, a register number to set to this value,...
Definition ISDOpcodes.h:224
@ ZERO_EXTEND
ZERO_EXTEND - Used for integer types, zeroing the new bits.
Definition ISDOpcodes.h:860
@ TargetConstantFP
Definition ISDOpcodes.h:180
@ SELECT_CC
Select with condition operator - This selects between a true value and a false value (ops #2 and #3) ...
Definition ISDOpcodes.h:821
@ 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:386
@ SMULO
Same for multiplication.
Definition ISDOpcodes.h:356
@ ATOMIC_LOAD_FMINIMUM
@ TargetFrameIndex
Definition ISDOpcodes.h:187
@ VECTOR_SPLICE_LEFT
VECTOR_SPLICE_LEFT(VEC1, VEC2, OFFSET) - Shifts CONCAT_VECTORS(VEC1, VEC2) left by OFFSET elements an...
Definition ISDOpcodes.h:655
@ ANY_EXTEND_VECTOR_INREG
ANY_EXTEND_VECTOR_INREG(Vector) - This operator represents an in-register any-extension of the low la...
Definition ISDOpcodes.h:909
@ SIGN_EXTEND_INREG
SIGN_EXTEND_INREG - This operator atomically performs a SHL/SRA pair to sign extend a small value in ...
Definition ISDOpcodes.h:898
@ SMIN
[US]{MIN/MAX} - Binary minimum or maximum of signed or unsigned integers.
Definition ISDOpcodes.h:729
@ 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:988
@ VSELECT
Select with a vector condition (op #0) and two vector operands (ops #1 and #2), returning a vector re...
Definition ISDOpcodes.h:815
@ UADDO_CARRY
Carry-using nodes for multiple precision addition and subtraction.
Definition ISDOpcodes.h:328
@ 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:785
@ STRICT_FP_ROUND
X = STRICT_FP_ROUND(Y, TRUNC) - Rounding 'Y' from a larger floating point type down to the precision ...
Definition ISDOpcodes.h:502
@ 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:936
@ TargetConstant
TargetConstant* - Like Constant*, but the DAG does not do any folding, simplification,...
Definition ISDOpcodes.h:179
@ STRICT_FP_EXTEND
X = STRICT_FP_EXTEND(Y) - Extend a smaller FP type into a larger FP type.
Definition ISDOpcodes.h:507
@ AND
Bitwise operators - logical and, logical or, logical xor.
Definition ISDOpcodes.h:741
@ INTRINSIC_WO_CHAIN
RESULT = INTRINSIC_WO_CHAIN(INTRINSICID, arg1, arg2, ...) This node represents a target intrinsic fun...
Definition ISDOpcodes.h:205
@ 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:737
@ AVGFLOORS
AVGFLOORS/AVGFLOORU - Averaging add - Add two integers using an integer of type i[N+1],...
Definition ISDOpcodes.h:712
@ VECTOR_SPLICE_RIGHT
VECTOR_SPLICE_RIGHT(VEC1, VEC2, OFFSET) - Shifts CONCAT_VECTORS(VEC1,VEC2) right by OFFSET elements a...
Definition ISDOpcodes.h:659
@ ADDE
Carry-using nodes for multiple precision addition and subtraction.
Definition ISDOpcodes.h:304
@ SPLAT_VECTOR_PARTS
SPLAT_VECTOR_PARTS(SCALAR1, SCALAR2, ...) - Returns a vector with the scalar values joined together a...
Definition ISDOpcodes.h:683
@ FREEZE
FREEZE - FREEZE(VAL) returns an arbitrary value if VAL is UNDEF (or is evaluated to UNDEF),...
Definition ISDOpcodes.h:241
@ INSERT_VECTOR_ELT
INSERT_VECTOR_ELT(VECTOR, VAL, IDX) - Returns VECTOR with the element at IDX replaced with VAL.
Definition ISDOpcodes.h:567
@ TokenFactor
TokenFactor - This node takes multiple tokens as input and produces a single token result.
Definition ISDOpcodes.h:53
@ 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:797
@ ExternalSymbol
Definition ISDOpcodes.h:93
@ 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:969
@ VECTOR_COMPRESS
VECTOR_COMPRESS(Vec, Mask, Passthru) consecutively place vector elements based on mask e....
Definition ISDOpcodes.h:701
@ ZERO_EXTEND_VECTOR_INREG
ZERO_EXTEND_VECTOR_INREG(Vector) - This operator represents an in-register zero-extension of the low ...
Definition ISDOpcodes.h:931
@ 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:955
@ VECREDUCE_FMINIMUM
@ TRUNCATE
TRUNCATE - Completely drop the high bits.
Definition ISDOpcodes.h:866
@ 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:843
@ AssertSext
AssertSext, AssertZext - These nodes record if a register contains a value that has already been zero...
Definition ISDOpcodes.h:62
@ ATOMIC_LOAD_UINC_WRAP
@ FCOPYSIGN
FCOPYSIGN(X, Y) - Return the value of X with the sign of Y.
Definition ISDOpcodes.h:536
@ PARTIAL_REDUCE_SUMLA
@ SADDSAT
RESULT = [US]ADDSAT(LHS, RHS) - Perform saturation addition on 2 integers with the same bit width (W)...
Definition ISDOpcodes.h:365
@ 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:881
@ ABDS
ABDS/ABDU - Absolute difference - Return the absolute difference between two numbers interpreted as s...
Definition ISDOpcodes.h:724
@ TRUNCATE_USAT_U
Definition ISDOpcodes.h:885
@ SADDO_CARRY
Carry-using overflow-aware nodes for multiple precision addition and subtraction.
Definition ISDOpcodes.h:338
@ INTRINSIC_W_CHAIN
RESULT,OUTCHAIN = INTRINSIC_W_CHAIN(INCHAIN, INTRINSICID, arg1, ...) This node represents a target in...
Definition ISDOpcodes.h:213
@ TargetGlobalTLSAddress
Definition ISDOpcodes.h:186
@ ABS_MIN_POISON
ABS with a poison result for INT_MIN.
Definition ISDOpcodes.h:753
@ BUILD_VECTOR
BUILD_VECTOR(ELT0, ELT1, ELT2, ELT3,...) - Return a fixed-width vector with the specified,...
Definition ISDOpcodes.h:558
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(SDNode *N, const SelectionDAG *DAG, 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:668
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:237
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:1759
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:1739
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:2554
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:2208
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:633
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:1746
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:407
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:1636
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 void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
LLVM_ABI 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:1753
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:149
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:539
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:1885
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:719
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:1947
Align commonAlignment(Align A, uint64_t Offset)
Returns the alignment that satisfies both alignments.
Definition Alignment.h:201
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:197
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:2146
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:763
MDNode * TBAAStruct
The tag for type-based alias analysis (tbaa struct).
Definition Metadata.h:783
MDNode * TBAA
The tag for type-based alias analysis.
Definition Metadata.h:780
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:77
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:106
Align valueOrOne() const
For convenience, returns a valid alignment or 1 if undefined.
Definition Alignment.h:130
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)