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 "SelectionDAGOptions.h"
16#include "llvm/ADT/APFloat.h"
17#include "llvm/ADT/APInt.h"
18#include "llvm/ADT/APSInt.h"
19#include "llvm/ADT/ArrayRef.h"
20#include "llvm/ADT/BitVector.h"
21#include "llvm/ADT/DenseSet.h"
22#include "llvm/ADT/FoldingSet.h"
23#include "llvm/ADT/STLExtras.h"
26#include "llvm/ADT/Twine.h"
53#include "llvm/IR/Constant.h"
54#include "llvm/IR/Constants.h"
55#include "llvm/IR/DataLayout.h"
57#include "llvm/IR/DebugLoc.h"
59#include "llvm/IR/Function.h"
60#include "llvm/IR/GlobalValue.h"
61#include "llvm/IR/Metadata.h"
62#include "llvm/IR/Type.h"
66#include "llvm/Support/Debug.h"
76#include <algorithm>
77#include <cassert>
78#include <cstdint>
79#include <cstdlib>
80#include <limits>
81#include <optional>
82#include <string>
83#include <utility>
84#include <vector>
85
86using namespace llvm;
87using namespace llvm::SDPatternMatch;
88
89/// makeVTList - Return an instance of the SDVTList struct initialized with the
90/// specified members.
91static SDVTList makeVTList(const EVT *VTs, unsigned NumVTs) {
92 SDVTList Res = {VTs, NumVTs};
93 return Res;
94}
95
96// Default null implementations of the callbacks.
100
101void SelectionDAG::DAGNodeDeletedListener::anchor() {}
102void SelectionDAG::DAGNodeInsertedListener::anchor() {}
103
104#define DEBUG_TYPE "selectiondag"
105
107 LLVM_DEBUG(dbgs() << Msg; V.getNode()->dump(G););
108}
109
111 return getSelectionDAGOptions().has_predecessor_max_steps;
112}
113
114//===----------------------------------------------------------------------===//
115// ConstantFPSDNode Class
116//===----------------------------------------------------------------------===//
117
118/// isExactlyValue - We don't rely on operator== working on double values, as
119/// it returns true for things that are clearly not equal, like -0.0 and 0.0.
120/// As such, this method can be used to do an exact bit-for-bit comparison of
121/// two floating point values.
123 return getValueAPF().bitwiseIsEqual(V);
124}
125
127 const APFloat& Val) {
128 assert(VT.isFloatingPoint() && "Can only convert between FP types");
129
130 // convert modifies in place, so make a copy.
131 APFloat Val2 = APFloat(Val);
132 bool losesInfo;
134 &losesInfo);
135 return !losesInfo;
136}
137
138//===----------------------------------------------------------------------===//
139// ISD Namespace
140//===----------------------------------------------------------------------===//
141
142bool ISD::isConstantSplatVector(const SDNode *N, APInt &SplatVal) {
143 if (N->getOpcode() == ISD::SPLAT_VECTOR) {
144 if (auto OptAPInt = N->getOperand(0)->bitcastToAPInt()) {
145 unsigned EltSize =
146 N->getValueType(0).getVectorElementType().getSizeInBits();
147 SplatVal = OptAPInt->trunc(EltSize);
148 return true;
149 }
150 }
151
152 auto *BV = dyn_cast<BuildVectorSDNode>(N);
153 if (!BV)
154 return false;
155
156 APInt SplatUndef;
157 unsigned SplatBitSize;
158 bool HasUndefs;
159 unsigned EltSize = N->getValueType(0).getVectorElementType().getSizeInBits();
160 // Endianness does not matter here. We are checking for a splat given the
161 // element size of the vector, and if we find such a splat for little endian
162 // layout, then that should be valid also for big endian (as the full vector
163 // size is known to be a multiple of the element size).
164 const bool IsBigEndian = false;
165 return BV->isConstantSplat(SplatVal, SplatUndef, SplatBitSize, HasUndefs,
166 EltSize, IsBigEndian) &&
167 EltSize == SplatBitSize;
168}
169
170// FIXME: AllOnes and AllZeros duplicate a lot of code. Could these be
171// specializations of the more general isConstantSplatVector()?
172
173bool ISD::isConstantSplatVectorAllOnes(const SDNode *N, bool BuildVectorOnly) {
174 // Look through a bit convert.
175 while (N->getOpcode() == ISD::BITCAST)
176 N = N->getOperand(0).getNode();
177
178 if (!BuildVectorOnly && N->getOpcode() == ISD::SPLAT_VECTOR) {
179 APInt SplatVal;
180 return isConstantSplatVector(N, SplatVal) && SplatVal.isAllOnes();
181 }
182
183 if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
184
185 unsigned i = 0, e = N->getNumOperands();
186
187 // Skip over all of the undef values.
188 while (i != e && N->getOperand(i).isUndef())
189 ++i;
190
191 // Do not accept an all-undef vector.
192 if (i == e) return false;
193
194 // Do not accept build_vectors that aren't all constants or which have non-~0
195 // elements. We have to be a bit careful here, as the type of the constant
196 // may not be the same as the type of the vector elements due to type
197 // legalization (the elements are promoted to a legal type for the target and
198 // a vector of a type may be legal when the base element type is not).
199 // We only want to check enough bits to cover the vector elements, because
200 // we care if the resultant vector is all ones, not whether the individual
201 // constants are.
202 SDValue NotZero = N->getOperand(i);
203 if (auto OptAPInt = NotZero->bitcastToAPInt()) {
204 unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
205 if (OptAPInt->countr_one() < EltSize)
206 return false;
207 } else
208 return false;
209
210 // Okay, we have at least one ~0 value, check to see if the rest match or are
211 // undefs. Even with the above element type twiddling, this should be OK, as
212 // the same type legalization should have applied to all the elements.
213 for (++i; i != e; ++i)
214 if (N->getOperand(i) != NotZero && !N->getOperand(i).isUndef())
215 return false;
216 return true;
217}
218
219bool ISD::isConstantSplatVectorAllZeros(const SDNode *N, bool BuildVectorOnly) {
220 // Look through a bit convert.
221 while (N->getOpcode() == ISD::BITCAST)
222 N = N->getOperand(0).getNode();
223
224 if (!BuildVectorOnly && N->getOpcode() == ISD::SPLAT_VECTOR) {
225 APInt SplatVal;
226 return isConstantSplatVector(N, SplatVal) && SplatVal.isZero();
227 }
228
229 if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
230
231 bool IsAllUndef = true;
232 for (const SDValue &Op : N->op_values()) {
233 if (Op.isUndef())
234 continue;
235 IsAllUndef = false;
236 // Do not accept build_vectors that aren't all constants or which have non-0
237 // elements. We have to be a bit careful here, as the type of the constant
238 // may not be the same as the type of the vector elements due to type
239 // legalization (the elements are promoted to a legal type for the target
240 // and a vector of a type may be legal when the base element type is not).
241 // We only want to check enough bits to cover the vector elements, because
242 // we care if the resultant vector is all zeros, not whether the individual
243 // constants are.
244 if (auto OptAPInt = Op->bitcastToAPInt()) {
245 unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
246 if (OptAPInt->countr_zero() < EltSize)
247 return false;
248 } else
249 return false;
250 }
251
252 // Do not accept an all-undef vector.
253 if (IsAllUndef)
254 return false;
255 return true;
256}
257
259 return isConstantSplatVectorAllOnes(N, /*BuildVectorOnly*/ true);
260}
261
263 return isConstantSplatVectorAllZeros(N, /*BuildVectorOnly*/ true);
264}
265
267 if (N->getOpcode() != ISD::BUILD_VECTOR)
268 return false;
269
270 for (const SDValue &Op : N->op_values()) {
271 if (Op.isUndef())
272 continue;
274 return false;
275 }
276 return true;
277}
278
280 if (N->getOpcode() != ISD::BUILD_VECTOR)
281 return false;
282
283 for (const SDValue &Op : N->op_values()) {
284 if (Op.isUndef())
285 continue;
287 return false;
288 }
289 return true;
290}
291
292bool ISD::isVectorShrinkable(const SDNode *N, unsigned NewEltSize,
293 bool Signed) {
294 assert(N->getValueType(0).isVector() && "Expected a vector!");
295
296 unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
297 if (EltSize <= NewEltSize)
298 return false;
299
300 if (N->getOpcode() == ISD::ZERO_EXTEND) {
301 return (N->getOperand(0).getValueType().getScalarSizeInBits() <=
302 NewEltSize) &&
303 !Signed;
304 }
305 if (N->getOpcode() == ISD::SIGN_EXTEND) {
306 return (N->getOperand(0).getValueType().getScalarSizeInBits() <=
307 NewEltSize) &&
308 Signed;
309 }
310 if (N->getOpcode() != ISD::BUILD_VECTOR)
311 return false;
312
313 for (const SDValue &Op : N->op_values()) {
314 if (Op.isUndef())
315 continue;
317 return false;
318
319 APInt C = Op->getAsAPIntVal().trunc(EltSize);
320 if (Signed && C.trunc(NewEltSize).sext(EltSize) != C)
321 return false;
322 if (!Signed && C.trunc(NewEltSize).zext(EltSize) != C)
323 return false;
324 }
325
326 return true;
327}
328
330 // Return false if the node has no operands.
331 // This is "logically inconsistent" with the definition of "all" but
332 // is probably the desired behavior.
333 if (N->getNumOperands() == 0)
334 return false;
335 return all_of(N->op_values(), [](SDValue Op) { return Op.isUndef(); });
336}
337
339 return N->getOpcode() == ISD::FREEZE && N->getOperand(0).isUndef();
340}
341
342template <typename ConstNodeType>
344 std::function<bool(ConstNodeType *)> Match,
345 bool AllowUndefs, bool AllowTruncation) {
346 // FIXME: Add support for scalar UNDEF cases?
347 if (auto *C = dyn_cast<ConstNodeType>(Op))
348 return Match(C);
349
350 // FIXME: Add support for vector UNDEF cases?
351 if (ISD::BUILD_VECTOR != Op.getOpcode() &&
352 ISD::SPLAT_VECTOR != Op.getOpcode())
353 return false;
354
355 if (ISD::SPLAT_VECTOR == Op.getOpcode() && !DemandedElts)
356 return true;
357
358 EVT SVT = Op.getValueType().getScalarType();
359 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
360 if (ISD::SPLAT_VECTOR != Op.getOpcode() && !DemandedElts[i])
361 continue;
362
363 if (AllowUndefs && Op.getOperand(i).isUndef()) {
364 if (!Match(nullptr))
365 return false;
366 continue;
367 }
368
369 auto *Cst = dyn_cast<ConstNodeType>(Op.getOperand(i));
370 if (!Cst || (!AllowTruncation && Cst->getValueType(0) != SVT) ||
371 !Match(Cst))
372 return false;
373 }
374 return true;
375}
376// Build used template types.
378 SDValue, const APInt &, std::function<bool(ConstantSDNode *)>, bool, bool);
380 SDValue, const APInt &, std::function<bool(ConstantFPSDNode *)>, bool,
381 bool);
382
384 SDValue LHS, SDValue RHS, const APInt &DemandedElts,
385 std::function<bool(ConstantSDNode *, ConstantSDNode *)> Match,
386 bool AllowUndefs, bool AllowTypeMismatch) {
387 if (!AllowTypeMismatch && LHS.getValueType() != RHS.getValueType())
388 return false;
389
390 // TODO: Add support for scalar UNDEF cases?
391 if (auto *LHSCst = dyn_cast<ConstantSDNode>(LHS))
392 if (auto *RHSCst = dyn_cast<ConstantSDNode>(RHS))
393 return Match(LHSCst, RHSCst);
394
395 // TODO: Add support for vector UNDEF cases?
396 if (LHS.getOpcode() != RHS.getOpcode() ||
397 (LHS.getOpcode() != ISD::BUILD_VECTOR &&
398 LHS.getOpcode() != ISD::SPLAT_VECTOR))
399 return false;
400
401 if (ISD::SPLAT_VECTOR == LHS.getOpcode() && !DemandedElts)
402 return true;
403
404 EVT SVT = LHS.getValueType().getScalarType();
405 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
406 if (ISD::SPLAT_VECTOR != LHS.getOpcode() && !DemandedElts[i])
407 continue;
408 SDValue LHSOp = LHS.getOperand(i);
409 SDValue RHSOp = RHS.getOperand(i);
410 bool LHSUndef = AllowUndefs && LHSOp.isUndef();
411 bool RHSUndef = AllowUndefs && RHSOp.isUndef();
412 auto *LHSCst = dyn_cast<ConstantSDNode>(LHSOp);
413 auto *RHSCst = dyn_cast<ConstantSDNode>(RHSOp);
414 if ((!LHSCst && !LHSUndef) || (!RHSCst && !RHSUndef))
415 return false;
416 if (!AllowTypeMismatch && (LHSOp.getValueType() != SVT ||
417 LHSOp.getValueType() != RHSOp.getValueType()))
418 return false;
419 if (!Match(LHSCst, RHSCst))
420 return false;
421 }
422 return true;
423}
424
426 switch (MinMaxOpc) {
427 default:
428 llvm_unreachable("unrecognized opcode");
429 case ISD::UMIN:
430 return ISD::UMAX;
431 case ISD::UMAX:
432 return ISD::UMIN;
433 case ISD::SMIN:
434 return ISD::SMAX;
435 case ISD::SMAX:
436 return ISD::SMIN;
437 }
438}
439
441 switch (MinMaxOpc) {
442 default:
443 llvm_unreachable("unrecognized min/max opcode");
444 case ISD::SMIN:
445 return ISD::UMIN;
446 case ISD::SMAX:
447 return ISD::UMAX;
448 case ISD::UMIN:
449 return ISD::SMIN;
450 case ISD::UMAX:
451 return ISD::SMAX;
452 }
453}
454
456 switch (VecReduceOpcode) {
457 default:
458 llvm_unreachable("Expected VECREDUCE opcode");
461 case ISD::VP_REDUCE_FADD:
462 case ISD::VP_REDUCE_SEQ_FADD:
463 return ISD::FADD;
466 case ISD::VP_REDUCE_FMUL:
467 case ISD::VP_REDUCE_SEQ_FMUL:
468 return ISD::FMUL;
470 case ISD::VP_REDUCE_ADD:
471 return ISD::ADD;
473 case ISD::VP_REDUCE_MUL:
474 return ISD::MUL;
476 case ISD::VP_REDUCE_AND:
477 return ISD::AND;
479 case ISD::VP_REDUCE_OR:
480 return ISD::OR;
482 case ISD::VP_REDUCE_XOR:
483 return ISD::XOR;
485 case ISD::VP_REDUCE_SMAX:
486 return ISD::SMAX;
488 case ISD::VP_REDUCE_SMIN:
489 return ISD::SMIN;
491 case ISD::VP_REDUCE_UMAX:
492 return ISD::UMAX;
494 case ISD::VP_REDUCE_UMIN:
495 return ISD::UMIN;
497 case ISD::VP_REDUCE_FMAX:
498 return ISD::FMAXNUM;
500 case ISD::VP_REDUCE_FMIN:
501 return ISD::FMINNUM;
503 case ISD::VP_REDUCE_FMAXIMUM:
504 return ISD::FMAXIMUM;
506 case ISD::VP_REDUCE_FMINIMUM:
507 return ISD::FMINIMUM;
509 return ISD::FMAXIMUMNUM;
511 return ISD::FMINIMUMNUM;
512 }
513}
514
516 switch (MaskedOpc) {
517 case ISD::MASKED_UDIV:
518 return ISD::UDIV;
519 case ISD::MASKED_SDIV:
520 return ISD::SDIV;
521 case ISD::MASKED_UREM:
522 return ISD::UREM;
523 case ISD::MASKED_SREM:
524 return ISD::SREM;
525 default:
526 llvm_unreachable("Expected masked binop opcode");
527 }
528}
529
530bool ISD::isVPOpcode(unsigned Opcode) {
531 switch (Opcode) {
532 default:
533 return false;
534#define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) \
535 case ISD::VPSD: \
536 return true;
537#include "llvm/IR/VPIntrinsics.def"
538 }
539}
540
541bool ISD::isVPBinaryOp(unsigned Opcode) {
542 switch (Opcode) {
543 default:
544 break;
545#define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) case ISD::VPSD:
546#define VP_PROPERTY_BINARYOP return true;
547#define END_REGISTER_VP_SDNODE(VPSD) break;
548#include "llvm/IR/VPIntrinsics.def"
549 }
550 return false;
551}
552
553bool ISD::isVPReduction(unsigned Opcode) {
554 switch (Opcode) {
555 default:
556 return false;
557 case ISD::VP_REDUCE_ADD:
558 case ISD::VP_REDUCE_MUL:
559 case ISD::VP_REDUCE_AND:
560 case ISD::VP_REDUCE_OR:
561 case ISD::VP_REDUCE_XOR:
562 case ISD::VP_REDUCE_SMAX:
563 case ISD::VP_REDUCE_SMIN:
564 case ISD::VP_REDUCE_UMAX:
565 case ISD::VP_REDUCE_UMIN:
566 case ISD::VP_REDUCE_FMAX:
567 case ISD::VP_REDUCE_FMIN:
568 case ISD::VP_REDUCE_FMAXIMUM:
569 case ISD::VP_REDUCE_FMINIMUM:
570 case ISD::VP_REDUCE_FADD:
571 case ISD::VP_REDUCE_FMUL:
572 case ISD::VP_REDUCE_SEQ_FADD:
573 case ISD::VP_REDUCE_SEQ_FMUL:
574 return true;
575 }
576}
577
578/// The operand position of the vector mask.
579std::optional<unsigned> ISD::getVPMaskIdx(unsigned Opcode) {
580 switch (Opcode) {
581 default:
582 return std::nullopt;
583#define BEGIN_REGISTER_VP_SDNODE(VPSD, LEGALPOS, TDNAME, MASKPOS, ...) \
584 case ISD::VPSD: \
585 return MASKPOS;
586#include "llvm/IR/VPIntrinsics.def"
587 }
588}
589
590/// The operand position of the explicit vector length parameter.
591std::optional<unsigned> ISD::getVPExplicitVectorLengthIdx(unsigned Opcode) {
592 switch (Opcode) {
593 default:
594 return std::nullopt;
595#define BEGIN_REGISTER_VP_SDNODE(VPSD, LEGALPOS, TDNAME, MASKPOS, EVLPOS) \
596 case ISD::VPSD: \
597 return EVLPOS;
598#include "llvm/IR/VPIntrinsics.def"
599 }
600}
601
602std::optional<unsigned> ISD::getBaseOpcodeForVP(unsigned VPOpcode,
603 bool hasFPExcept) {
604 // FIXME: Return strict opcodes in case of fp exceptions.
605 switch (VPOpcode) {
606 default:
607 return std::nullopt;
608#define BEGIN_REGISTER_VP_SDNODE(VPOPC, ...) case ISD::VPOPC:
609#define VP_PROPERTY_FUNCTIONAL_SDOPC(SDOPC) return ISD::SDOPC;
610#define END_REGISTER_VP_SDNODE(VPOPC) break;
611#include "llvm/IR/VPIntrinsics.def"
612 }
613 return std::nullopt;
614}
615
616std::optional<unsigned> ISD::getVPForBaseOpcode(unsigned Opcode) {
617 switch (Opcode) {
618 default:
619 return std::nullopt;
620#define BEGIN_REGISTER_VP_SDNODE(VPOPC, ...) break;
621#define VP_PROPERTY_FUNCTIONAL_SDOPC(SDOPC) case ISD::SDOPC:
622#define END_REGISTER_VP_SDNODE(VPOPC) return ISD::VPOPC;
623#include "llvm/IR/VPIntrinsics.def"
624 }
625}
626
628 switch (ExtType) {
629 case ISD::EXTLOAD:
630 return IsFP ? ISD::FP_EXTEND : ISD::ANY_EXTEND;
631 case ISD::SEXTLOAD:
632 return ISD::SIGN_EXTEND;
633 case ISD::ZEXTLOAD:
634 return ISD::ZERO_EXTEND;
635 default:
636 break;
637 }
638
639 llvm_unreachable("Invalid LoadExtType");
640}
641
643 // To perform this operation, we just need to swap the L and G bits of the
644 // operation.
645 unsigned OldL = (Operation >> 2) & 1;
646 unsigned OldG = (Operation >> 1) & 1;
647 return ISD::CondCode((Operation & ~6) | // Keep the N, U, E bits
648 (OldL << 1) | // New G bit
649 (OldG << 2)); // New L bit.
650}
651
653 unsigned Operation = Op;
654 if (isIntegerLike)
655 Operation ^= 7; // Flip L, G, E bits, but not U.
656 else
657 Operation ^= 15; // Flip all of the condition bits.
658
660 Operation &= ~8; // Don't let N and U bits get set.
661
662 return ISD::CondCode(Operation);
663}
664
668
670 bool isIntegerLike) {
671 return getSetCCInverseImpl(Op, isIntegerLike);
672}
673
674/// For an integer comparison, return 1 if the comparison is a signed operation
675/// and 2 if the result is an unsigned comparison. Return zero if the operation
676/// does not depend on the sign of the input (setne and seteq).
677static int isSignedOp(ISD::CondCode Opcode) {
678 switch (Opcode) {
679 default: llvm_unreachable("Illegal integer setcc operation!");
680 case ISD::SETEQ:
681 case ISD::SETNE: return 0;
682 case ISD::SETLT:
683 case ISD::SETLE:
684 case ISD::SETGT:
685 case ISD::SETGE: return 1;
686 case ISD::SETULT:
687 case ISD::SETULE:
688 case ISD::SETUGT:
689 case ISD::SETUGE: return 2;
690 }
691}
692
694 EVT Type) {
695 bool IsInteger = Type.isInteger();
696 if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
697 // Cannot fold a signed integer setcc with an unsigned integer setcc.
698 return ISD::SETCC_INVALID;
699
700 unsigned Op = Op1 | Op2; // Combine all of the condition bits.
701
702 // If the N and U bits get set, then the resultant comparison DOES suddenly
703 // care about orderedness, and it is true when ordered.
704 if (Op > ISD::SETTRUE2)
705 Op &= ~16; // Clear the U bit if the N bit is set.
706
707 // Canonicalize illegal integer setcc's.
708 if (IsInteger && Op == ISD::SETUNE) // e.g. SETUGT | SETULT
709 Op = ISD::SETNE;
710
711 return ISD::CondCode(Op);
712}
713
715 EVT Type) {
716 bool IsInteger = Type.isInteger();
717 if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
718 // Cannot fold a signed setcc with an unsigned setcc.
719 return ISD::SETCC_INVALID;
720
721 // Combine all of the condition bits.
722 ISD::CondCode Result = ISD::CondCode(Op1 & Op2);
723
724 // Canonicalize illegal integer setcc's.
725 if (IsInteger) {
726 switch (Result) {
727 default: break;
728 case ISD::SETUO : Result = ISD::SETFALSE; break; // SETUGT & SETULT
729 case ISD::SETOEQ: // SETEQ & SETU[LG]E
730 case ISD::SETUEQ: Result = ISD::SETEQ ; break; // SETUGE & SETULE
731 case ISD::SETOLT: Result = ISD::SETULT ; break; // SETULT & SETNE
732 case ISD::SETOGT: Result = ISD::SETUGT ; break; // SETUGT & SETNE
733 }
734 }
735
736 return Result;
737}
738
739//===----------------------------------------------------------------------===//
740// SDNode Key Support
741//===----------------------------------------------------------------------===//
742
743/// If this is an SDNode with special info, add this info to the NodeID data.
744/// MorphNodeTo passes the opcode \p N is becoming, so \p Opc may differ from
745/// N->getOpcode() and a case may only cast to a class \p N already is.
746static void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N,
747 unsigned Opc) {
748 // Machine nodes are uniqued by opcode, value types and operands alone, as in
749 // getMachineNode; MorphNodeTo's clearMemRefs overwrites the fields below.
751 return;
752
753 switch (Opc) {
756 case ISD::MCSymbol:
757 llvm_unreachable("Should only be used on nodes with operands");
758 default: break; // Normal nodes don't need extra info.
760 case ISD::Constant: {
762 ID.AddPointer(C->getConstantIntValue());
763 ID.AddBoolean(C->isOpaque());
764 break;
765 }
767 case ISD::ConstantFP:
768 ID.AddPointer(cast<ConstantFPSDNode>(N)->getConstantFPValue());
769 break;
775 ID.AddPointer(GA->getGlobal());
776 ID.AddInteger(GA->getOffset());
777 ID.AddInteger(GA->getTargetFlags());
778 break;
779 }
780 case ISD::BasicBlock:
781 ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock());
782 break;
783 case ISD::EH_LABEL:
785 ID.AddPointer(cast<LabelSDNode>(N)->getLabel());
786 break;
788 ID.AddPointer(cast<DeactivationSymbolSDNode>(N)->getGlobal());
789 break;
790 case ISD::Register:
791 ID.AddInteger(cast<RegisterSDNode>(N)->getReg().id());
792 break;
794 ID.AddPointer(cast<RegisterMaskSDNode>(N)->getRegMask());
795 break;
796 case ISD::SRCVALUE:
797 ID.AddPointer(cast<SrcValueSDNode>(N)->getValue());
798 break;
799 case ISD::FrameIndex:
801 ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex());
802 break;
804 ID.AddInteger(cast<PseudoProbeSDNode>(N)->getGuid());
805 ID.AddInteger(cast<PseudoProbeSDNode>(N)->getIndex());
806 ID.AddInteger(cast<PseudoProbeSDNode>(N)->getAttributes());
807 break;
808 case ISD::JumpTable:
810 ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex());
811 ID.AddInteger(cast<JumpTableSDNode>(N)->getTargetFlags());
812 break;
816 ID.AddInteger(CP->getAlign().value());
817 ID.AddInteger(CP->getOffset());
820 else
821 ID.AddPointer(CP->getConstVal());
822 ID.AddInteger(CP->getTargetFlags());
823 break;
824 }
825 case ISD::TargetIndex: {
827 ID.AddInteger(TI->getIndex());
828 ID.AddInteger(TI->getOffset());
829 ID.AddInteger(TI->getTargetFlags());
830 break;
831 }
832 case ISD::LOAD: {
833 const LoadSDNode *LD = cast<LoadSDNode>(N);
834 ID.AddInteger(LD->getMemoryVT().getRawBits());
835 ID.AddInteger(LD->getRawSubclassData());
836 ID.AddInteger(LD->getPointerInfo().getAddrSpace());
837 ID.AddInteger(LD->getMemOperand()->getFlags());
838 break;
839 }
840 case ISD::STORE: {
841 const StoreSDNode *ST = cast<StoreSDNode>(N);
842 ID.AddInteger(ST->getMemoryVT().getRawBits());
843 ID.AddInteger(ST->getRawSubclassData());
844 ID.AddInteger(ST->getPointerInfo().getAddrSpace());
845 ID.AddInteger(ST->getMemOperand()->getFlags());
846 break;
847 }
848 case ISD::VP_LOAD: {
849 const VPLoadSDNode *ELD = cast<VPLoadSDNode>(N);
850 ID.AddInteger(ELD->getMemoryVT().getRawBits());
851 ID.AddInteger(ELD->getRawSubclassData());
852 ID.AddInteger(ELD->getPointerInfo().getAddrSpace());
853 ID.AddInteger(ELD->getMemOperand()->getFlags());
854 break;
855 }
856 case ISD::VP_LOAD_FF: {
857 const auto *LD = cast<VPLoadFFSDNode>(N);
858 ID.AddInteger(LD->getMemoryVT().getRawBits());
859 ID.AddInteger(LD->getRawSubclassData());
860 ID.AddInteger(LD->getPointerInfo().getAddrSpace());
861 ID.AddInteger(LD->getMemOperand()->getFlags());
862 break;
863 }
864 case ISD::VP_STORE: {
865 const VPStoreSDNode *EST = cast<VPStoreSDNode>(N);
866 ID.AddInteger(EST->getMemoryVT().getRawBits());
867 ID.AddInteger(EST->getRawSubclassData());
868 ID.AddInteger(EST->getPointerInfo().getAddrSpace());
869 ID.AddInteger(EST->getMemOperand()->getFlags());
870 break;
871 }
872 case ISD::EXPERIMENTAL_VP_STRIDED_LOAD: {
874 ID.AddInteger(SLD->getMemoryVT().getRawBits());
875 ID.AddInteger(SLD->getRawSubclassData());
876 ID.AddInteger(SLD->getPointerInfo().getAddrSpace());
877 break;
878 }
879 case ISD::EXPERIMENTAL_VP_STRIDED_STORE: {
881 ID.AddInteger(SST->getMemoryVT().getRawBits());
882 ID.AddInteger(SST->getRawSubclassData());
883 ID.AddInteger(SST->getPointerInfo().getAddrSpace());
884 break;
885 }
886 case ISD::VP_GATHER: {
888 ID.AddInteger(EG->getMemoryVT().getRawBits());
889 ID.AddInteger(EG->getRawSubclassData());
890 ID.AddInteger(EG->getPointerInfo().getAddrSpace());
891 ID.AddInteger(EG->getMemOperand()->getFlags());
892 break;
893 }
894 case ISD::VP_SCATTER: {
896 ID.AddInteger(ES->getMemoryVT().getRawBits());
897 ID.AddInteger(ES->getRawSubclassData());
898 ID.AddInteger(ES->getPointerInfo().getAddrSpace());
899 ID.AddInteger(ES->getMemOperand()->getFlags());
900 break;
901 }
902 case ISD::MLOAD: {
904 ID.AddInteger(MLD->getMemoryVT().getRawBits());
905 ID.AddInteger(MLD->getRawSubclassData());
906 ID.AddInteger(MLD->getPointerInfo().getAddrSpace());
907 ID.AddInteger(MLD->getMemOperand()->getFlags());
908 break;
909 }
910 case ISD::MSTORE: {
912 ID.AddInteger(MST->getMemoryVT().getRawBits());
913 ID.AddInteger(MST->getRawSubclassData());
914 ID.AddInteger(MST->getPointerInfo().getAddrSpace());
915 ID.AddInteger(MST->getMemOperand()->getFlags());
916 break;
917 }
918 case ISD::MGATHER: {
920 ID.AddInteger(MG->getMemoryVT().getRawBits());
921 ID.AddInteger(MG->getRawSubclassData());
922 ID.AddInteger(MG->getPointerInfo().getAddrSpace());
923 ID.AddInteger(MG->getMemOperand()->getFlags());
924 break;
925 }
926 case ISD::MSCATTER:
930 const MemSDNode *M = cast<MemSDNode>(N);
931 ID.AddInteger(M->getMemoryVT().getRawBits());
932 ID.AddInteger(M->getRawSubclassData());
933 ID.AddInteger(M->getPointerInfo().getAddrSpace());
934 ID.AddInteger(M->getMemOperand()->getFlags());
935 break;
936 }
937 case ISD::VECTOR_SHUFFLE: {
938 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(N)->getMask();
939 for (int M : Mask)
940 ID.AddInteger(M);
941 break;
942 }
943 case ISD::ADDRSPACECAST: {
945 ID.AddInteger(ASC->getSrcAddressSpace());
946 ID.AddInteger(ASC->getDestAddressSpace());
947 break;
948 }
950 case ISD::BlockAddress: {
952 ID.AddPointer(BA->getBlockAddress());
953 ID.AddInteger(BA->getOffset());
954 ID.AddInteger(BA->getTargetFlags());
955 break;
956 }
957 case ISD::AssertAlign:
958 ID.AddInteger(cast<AssertAlignSDNode>(N)->getAlign().value());
959 break;
960 case ISD::PREFETCH:
963 // Handled by MemIntrinsicSDNode check after the switch.
964 break;
966 ID.AddPointer(cast<MDNodeSDNode>(N)->getMD());
967 break;
968 } // end switch (Opc)
969
970 if (auto *AT = dyn_cast<AtomicSDNode>(N)) {
971 ID.AddInteger(AT->getMemoryVT().getRawBits());
972 ID.AddInteger(AT->getRawSubclassData());
973 ID.AddInteger(AT->getPointerInfo().getAddrSpace());
974 ID.AddInteger(AT->getMemOperand()->getFlags());
975 }
976
977 // MemIntrinsic nodes could also have subclass data, address spaces, and flags
978 // to check.
979 if (auto *MN = dyn_cast<MemIntrinsicSDNode>(N)) {
980 ID.AddInteger(MN->getRawSubclassData());
981 ID.AddInteger(MN->getMemoryVT().getRawBits());
982 for (const MachineMemOperand *MMO : MN->memoperands()) {
983 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
984 ID.AddInteger(MMO->getFlags());
985 }
986 }
987}
988
990 : Opcode(N.getOpcode()), VTs(N.getVTList().VTs),
991 OpStorage(N.op_begin(), N.op_end()) {
992 Ops = OpStorage;
993 AddNodeIDCustom(Tail, &N, N.getOpcode());
994}
995
996#ifndef NDEBUG
997/// Serialize a node the way SDNodes were uniqued before SDNodeKey, to
998/// cross-check the typed comparison against. Deliberately reads the node
999/// rather than going through SDNodeKey, so the key constructor is checked too
1000/// and not used as its own oracle.
1001static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) {
1002 ID.AddInteger(N->getOpcode());
1003 ID.AddPointer(N->getVTList().VTs);
1004 for (const SDUse &Op : N->ops()) {
1005 ID.AddPointer(Op.getNode());
1006 ID.AddInteger(Op.getResNo());
1007 }
1008 AddNodeIDCustom(ID, N, N->getOpcode());
1009}
1010
1012 ID.AddInteger(Key.Opcode);
1013 ID.AddPointer(Key.VTs);
1014 for (const SDValue &Op : Key.Ops) {
1015 ID.AddPointer(Op.getNode());
1016 ID.AddInteger(Op.getResNo());
1017 }
1018 ID.AddNodeID(Key.Tail);
1019}
1020#endif
1021
1022static bool keyMatches(const SDNodeKey &Key, const SDNode &N) {
1023 if (N.getOpcode() != Key.Opcode || N.getVTList().VTs != Key.VTs)
1024 return false;
1025 if (!llvm::equal(N.ops(), Key.Ops))
1026 return false;
1027 // Build only what AddNodeIDCustom would have added, which is nothing for
1028 // most opcodes, rather than the whole profile.
1029 FoldingSetNodeID Tail;
1030 AddNodeIDCustom(Tail, &N, N.getOpcode());
1031 return Tail == Key.Tail;
1032}
1033
1035 bool Result = keyMatches(Key, N);
1036
1037#ifndef NDEBUG
1038 FoldingSetNodeID NodeProfile, KeyProfile;
1039 AddNodeIDNode(NodeProfile, &N);
1040 AddNodeIDNode(KeyProfile, Key);
1041 assert((NodeProfile == KeyProfile) == Result &&
1042 "SDNodeKey equality disagrees with profile");
1043#endif
1044 return Result;
1045}
1046
1047//===----------------------------------------------------------------------===//
1048// SelectionDAG Class
1049//===----------------------------------------------------------------------===//
1050
1051/// doNotCSE - Return true if CSE should not be performed for this node.
1052static bool doNotCSE(SDNode *N) {
1053 if (N->getValueType(0) == MVT::Glue)
1054 return true; // Never CSE anything that produces a glue result.
1055
1056 switch (N->getOpcode()) {
1057 default: break;
1058 case ISD::HANDLENODE:
1059 case ISD::EH_LABEL:
1060 return true; // Never CSE these nodes.
1061 }
1062
1063 // Check that remaining values produced are not flags.
1064 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
1065 if (N->getValueType(i) == MVT::Glue)
1066 return true; // Never CSE anything that produces a glue result.
1067
1068 return false;
1069}
1070
1071/// Construct a DemandedElts mask which demands all elements of \p V.
1072/// If \p V is not a fixed-length vector, then this will return a single bit.
1074 EVT VT = V.getValueType();
1075 // Since the number of lanes in a scalable vector is unknown at compile time,
1076 // we track one bit which is implicitly broadcast to all lanes. This means
1077 // that all lanes in a scalable vector are considered demanded.
1079 : APInt(1, 1);
1080}
1081
1082/// RemoveDeadNodes - This method deletes all unreachable nodes in the
1083/// SelectionDAG.
1085 // Create a dummy node (which is not added to allnodes), that adds a reference
1086 // to the root node, preventing it from being deleted.
1087 HandleSDNode Dummy(getRoot());
1088
1089 SmallVector<SDNode*, 128> DeadNodes;
1090
1091 // Add all obviously-dead nodes to the DeadNodes worklist.
1092 for (SDNode &Node : allnodes())
1093 if (Node.use_empty())
1094 DeadNodes.push_back(&Node);
1095
1096 RemoveDeadNodes(DeadNodes);
1097
1098 // If the root changed (e.g. it was a dead load, update the root).
1099 setRoot(Dummy.getValue());
1100}
1101
1102/// RemoveDeadNodes - This method deletes the unreachable nodes in the
1103/// given list, and any nodes that become unreachable as a result.
1105
1106 // Process the worklist, deleting the nodes and adding their uses to the
1107 // worklist.
1108 while (!DeadNodes.empty()) {
1109 SDNode *N = DeadNodes.pop_back_val();
1110 // Skip to next node if we've already managed to delete the node. This could
1111 // happen if replacing a node causes a node previously added to the node to
1112 // be deleted.
1113 if (N->getOpcode() == ISD::DELETED_NODE)
1114 continue;
1115
1116 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1117 DUL->NodeDeleted(N, nullptr);
1118
1119 // Take the node out of the appropriate CSE map.
1120 RemoveNodeFromCSEMaps(N);
1121
1122 // Next, brutally remove the operand list. This is safe to do, as there are
1123 // no cycles in the graph.
1124 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
1125 SDUse &Use = *I++;
1126 SDNode *Operand = Use.getNode();
1127 Use.set(SDValue());
1128
1129 // Now that we removed this operand, see if there are no uses of it left.
1130 if (Operand->use_empty())
1131 DeadNodes.push_back(Operand);
1132 }
1133
1134 DeallocateNode(N);
1135 }
1136}
1137
1139 SmallVector<SDNode*, 16> DeadNodes(1, N);
1140
1141 // Create a dummy node that adds a reference to the root node, preventing
1142 // it from being deleted. (This matters if the root is an operand of the
1143 // dead node.)
1144 HandleSDNode Dummy(getRoot());
1145
1146 RemoveDeadNodes(DeadNodes);
1147}
1148
1150 // First take this out of the appropriate CSE map.
1151 RemoveNodeFromCSEMaps(N);
1152
1153 // Finally, remove uses due to operands of this node, remove from the
1154 // AllNodes list, and delete the node.
1155 DeleteNodeNotInCSEMaps(N);
1156}
1157
1158void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
1159 assert(N->getIterator() != AllNodes.begin() &&
1160 "Cannot delete the entry node!");
1161 assert(N->use_empty() && "Cannot delete a node that is not dead!");
1162
1163 // Drop all of the operands and decrement used node's use counts.
1164 N->DropOperands();
1165
1166 DeallocateNode(N);
1167}
1168
1169void SDDbgInfo::add(SDDbgValue *V, bool isParameter) {
1170 assert(!(V->isVariadic() && isParameter));
1171 if (isParameter)
1172 ByvalParmDbgValues.push_back(V);
1173 else
1174 DbgValues.push_back(V);
1175 for (const SDNode *Node : V->getSDNodes())
1176 if (Node)
1177 DbgValMap[Node].push_back(V);
1178}
1179
1181 DbgValMapType::iterator I = DbgValMap.find(Node);
1182 if (I == DbgValMap.end())
1183 return;
1184 for (auto &Val: I->second)
1185 Val->setIsInvalidated();
1186 DbgValMap.erase(I);
1187}
1188
1189void SelectionDAG::DeallocateNode(SDNode *N) {
1190 // If we have operands, deallocate them.
1192
1193 NodeAllocator.Deallocate(AllNodes.remove(N));
1194
1195 // Set the opcode to DELETED_NODE to help catch bugs when node
1196 // memory is reallocated.
1197 // FIXME: There are places in SDag that have grown a dependency on the opcode
1198 // value in the released node.
1199 __asan_unpoison_memory_region(&N->NodeType, sizeof(N->NodeType));
1200 N->NodeType = ISD::DELETED_NODE;
1201
1202 // If any of the SDDbgValue nodes refer to this SDNode, invalidate
1203 // them and forget about that node.
1204 DbgInfo->erase(N);
1205
1206 // Invalidate extra info.
1207 SDEI.erase(N);
1208}
1209
1210#ifndef NDEBUG
1211/// VerifySDNode - Check the given SDNode. Aborts if it is invalid.
1212void SelectionDAG::verifyNode(SDNode *N) const {
1213 switch (N->getOpcode()) {
1214 default:
1215 if (N->isTargetOpcode())
1217 break;
1218 case ISD::BUILD_PAIR: {
1219 EVT VT = N->getValueType(0);
1220 assert(N->getNumValues() == 1 && "Too many results!");
1221 assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) &&
1222 "Wrong return type!");
1223 assert(N->getNumOperands() == 2 && "Wrong number of operands!");
1224 assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() &&
1225 "Mismatched operand types!");
1226 assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() &&
1227 "Wrong operand type!");
1228 assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() &&
1229 "Wrong return type size");
1230 break;
1231 }
1232 case ISD::BUILD_VECTOR: {
1233 assert(N->getNumValues() == 1 && "Too many results!");
1234 assert(N->getValueType(0).isVector() && "Wrong return type!");
1235 assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() &&
1236 "Wrong number of operands!");
1237 EVT EltVT = N->getValueType(0).getVectorElementType();
1238 for (const SDUse &Op : N->ops()) {
1239 assert((Op.getValueType() == EltVT ||
1240 (EltVT.isInteger() && Op.getValueType().isInteger() &&
1241 EltVT.bitsLE(Op.getValueType()))) &&
1242 "Wrong operand type!");
1243 assert(Op.getValueType() == N->getOperand(0).getValueType() &&
1244 "Operands must all have the same type");
1245 }
1246 break;
1247 }
1248 case ISD::SADDO:
1249 case ISD::UADDO:
1250 case ISD::SSUBO:
1251 case ISD::USUBO:
1252 assert(N->getNumValues() == 2 && "Wrong number of results!");
1253 assert(N->getVTList().NumVTs == 2 && N->getNumOperands() == 2 &&
1254 "Invalid add/sub overflow op!");
1255 assert(N->getVTList().VTs[0].isInteger() &&
1256 N->getVTList().VTs[1].isInteger() &&
1257 N->getOperand(0).getValueType() == N->getOperand(1).getValueType() &&
1258 N->getOperand(0).getValueType() == N->getVTList().VTs[0] &&
1259 "Binary operator types must match!");
1260 break;
1261 }
1262}
1263#endif // NDEBUG
1264
1265/// Insert a newly allocated node into the DAG.
1266///
1267/// Handles insertion into the all nodes list and CSE map, as well as
1268/// verification and other common operations when a new node is allocated.
1269void SelectionDAG::InsertNode(SDNode *N) {
1270 AllNodes.push_back(N);
1271#ifndef NDEBUG
1272 N->PersistentId = NextPersistentId++;
1273 verifyNode(N);
1274#endif
1275 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1276 DUL->NodeInserted(N);
1277}
1278
1279/// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
1280/// correspond to it. This is useful when we're about to delete or repurpose
1281/// the node. We don't want future request for structurally identical nodes
1282/// to return N anymore.
1283bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
1284 bool Erased = false;
1285 switch (N->getOpcode()) {
1286 case ISD::HANDLENODE: return false; // noop.
1287 case ISD::CONDCODE:
1288 assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
1289 "Cond code doesn't exist!");
1290 Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != nullptr;
1291 CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = nullptr;
1292 break;
1294 Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
1295 break;
1297 ExternalSymbolSDNode *ESN = cast<ExternalSymbolSDNode>(N);
1298 Erased = TargetExternalSymbols.erase(std::pair<std::string, unsigned>(
1299 ESN->getSymbol(), ESN->getTargetFlags()));
1300 break;
1301 }
1302 case ISD::MCSymbol: {
1303 auto *MCSN = cast<MCSymbolSDNode>(N);
1304 Erased = MCSymbols.erase(MCSN->getMCSymbol());
1305 break;
1306 }
1307 case ISD::VALUETYPE: {
1308 EVT VT = cast<VTSDNode>(N)->getVT();
1309 if (VT.isExtended()) {
1310 Erased = ExtendedValueTypeNodes.erase(VT);
1311 } else {
1312 Erased = ValueTypeNodes[VT.getSimpleVT().SimpleTy] != nullptr;
1313 ValueTypeNodes[VT.getSimpleVT().SimpleTy] = nullptr;
1314 }
1315 break;
1316 }
1317 default:
1318 // Remove it from the CSE Map.
1319 assert(N->getOpcode() != ISD::DELETED_NODE && "DELETED_NODE in CSEMap!");
1320 assert(N->getOpcode() != ISD::EntryToken && "EntryToken in CSEMap!");
1321 Erased = CSEMap.erase(N);
1322 break;
1323 }
1324#ifndef NDEBUG
1325 // Verify that the node was actually in one of the CSE maps, unless it has a
1326 // glue result (which cannot be CSE'd) or is one of the special cases that are
1327 // not subject to CSE.
1328 if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Glue &&
1329 !N->isMachineOpcode() && !doNotCSE(N)) {
1330 N->dump(this);
1331 dbgs() << "\n";
1332 llvm_unreachable("Node is not in map!");
1333 }
1334#endif
1335 return Erased;
1336}
1337
1338/// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE
1339/// maps and modified in place. Add it back to the CSE maps, unless an identical
1340/// node already exists, in which case transfer all its users to the existing
1341/// node. This transfer can potentially trigger recursive merging.
1342void
1343SelectionDAG::AddModifiedNodeToCSEMaps(SDNode *N) {
1344 // For node types that aren't CSE'd, just act as if no identical node
1345 // already exists.
1346 if (!doNotCSE(N)) {
1347 SDNode *Existing = CSEMap.getOrInsert(N);
1348 if (Existing != N) {
1349 // If there was already an existing matching node, use ReplaceAllUsesWith
1350 // to replace the dead one with the existing one. This can cause
1351 // recursive merging of other unrelated nodes down the line.
1352 Existing->intersectFlagsWith(N->getFlags());
1353 if (auto *MemNode = dyn_cast<MemSDNode>(Existing)) {
1355 cast<MemSDNode>(N)->memoperands();
1356 // Range and cache hint metadata are not part of the DAG CSE key because
1357 // we prefer to CSE even when metadata does not match. Merge potentially
1358 // differing metadata conservatively.
1359 MemNode->refineMMOMetadata(NewMMOs);
1360 }
1361 ReplaceAllUsesWith(N, Existing);
1362
1363 // N is now dead. Inform the listeners and delete it.
1364 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1365 DUL->NodeDeleted(N, Existing);
1366 DeleteNodeNotInCSEMaps(N);
1367 return;
1368 }
1369 }
1370
1371 // If the node doesn't already exist, we updated it. Inform listeners.
1372 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1373 DUL->NodeUpdated(N);
1374}
1375
1376/// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1377/// were replaced with those specified. If this node is never memoized,
1378/// return null, otherwise return a pointer to the slot it would take. If a
1379/// node already exists with these operands, the slot will be non-null.
1380SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op,
1381 FoldingSetInsertToken &InsertToken) {
1382 if (doNotCSE(N))
1383 return nullptr;
1384
1385 SDValue Ops[] = { Op };
1386 SDNodeKey ID(N->getOpcode(), N->getVTList(), Ops);
1387 AddNodeIDCustom(ID.Tail, N, N->getOpcode());
1388 SDNode *Node = lookupNode(ID, SDLoc(N), InsertToken);
1389 if (Node)
1390 Node->intersectFlagsWith(N->getFlags());
1391 return Node;
1392}
1393
1394/// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1395/// were replaced with those specified. If this node is never memoized,
1396/// return null, otherwise return a pointer to the slot it would take. If a
1397/// node already exists with these operands, the slot will be non-null.
1398SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op1, SDValue Op2,
1399 FoldingSetInsertToken &InsertToken) {
1400 if (doNotCSE(N))
1401 return nullptr;
1402
1403 SDValue Ops[] = { Op1, Op2 };
1404 SDNodeKey ID(N->getOpcode(), N->getVTList(), Ops);
1405 AddNodeIDCustom(ID.Tail, N, N->getOpcode());
1406 SDNode *Node = lookupNode(ID, SDLoc(N), InsertToken);
1407 if (Node)
1408 Node->intersectFlagsWith(N->getFlags());
1409 return Node;
1410}
1411
1412/// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1413/// were replaced with those specified. If this node is never memoized,
1414/// return null, otherwise return a pointer to the slot it would take. If a
1415/// node already exists with these operands, the slot will be non-null.
1416SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, ArrayRef<SDValue> Ops,
1417 FoldingSetInsertToken &InsertToken) {
1418 if (doNotCSE(N))
1419 return nullptr;
1420
1421 SDNodeKey ID(N->getOpcode(), N->getVTList(), Ops);
1422 AddNodeIDCustom(ID.Tail, N, N->getOpcode());
1423 SDNode *Node = lookupNode(ID, SDLoc(N), InsertToken);
1424 if (Node)
1425 Node->intersectFlagsWith(N->getFlags());
1426 return Node;
1427}
1428
1430 Type *Ty = VT == MVT::iPTR ? PointerType::get(*getContext(), 0)
1431 : VT.getTypeForEVT(*getContext());
1432
1433 return getDataLayout().getABITypeAlign(Ty);
1434}
1435
1436// EntryNode could meaningfully have debug info if we can find it...
1438 : TM(tm), OptLevel(OL), EntryNode(ISD::EntryToken, 0, DebugLoc(),
1439 getVTList(MVT::Other, MVT::Glue)),
1440 Root(getEntryNode()) {
1441 InsertNode(&EntryNode);
1442 DbgInfo = new SDDbgInfo();
1443}
1444
1446 const TargetLibraryInfo *LibraryInfo,
1447 const LibcallLoweringInfo *LibcallsInfo,
1448 UniformityInfo *NewUA, ProfileSummaryInfo *PSIin,
1449 BlockFrequencyInfo *BFIin,
1450 FunctionVarLocs const *VarLocs) {
1451 MF = &NewMF;
1454 LibInfo = LibraryInfo;
1455 Libcalls = LibcallsInfo;
1456 Context = &MF->getFunction().getContext();
1457 DAGOpts = &Context->getLibraryOptions().get<SelectionDAGOptions>();
1458 UA = NewUA;
1459 PSI = PSIin;
1460 BFI = BFIin;
1461 FnVarLocs = VarLocs;
1462}
1463
1465 assert(!UpdateListeners && "Dangling registered DAGUpdateListeners");
1466 allnodes_clear();
1467 OperandRecycler.clear(OperandAllocator);
1468 delete DbgInfo;
1469}
1470
1472 return llvm::shouldOptimizeForSize(FLI->MBB->getBasicBlock(), PSI, BFI);
1473}
1474
1476 return FLI->MBB->getBasicBlock();
1477}
1478
1479void SelectionDAG::allnodes_clear() {
1480 assert(&*AllNodes.begin() == &EntryNode);
1481 AllNodes.remove(AllNodes.begin());
1482 while (!AllNodes.empty())
1483 DeallocateNode(&AllNodes.front());
1484#ifndef NDEBUG
1485 NextPersistentId = 0;
1486#endif
1487}
1488
1489SDNode *SelectionDAG::lookupNode(const SDNodeKey &Key,
1490 FoldingSetInsertToken &InsertToken) {
1491 SDNode *N = CSEMap.lookup(Key, InsertToken);
1492 if (N) {
1493 switch (N->getOpcode()) {
1494 default: break;
1495 case ISD::Constant:
1496 case ISD::ConstantFP:
1497 llvm_unreachable("Querying for Constant and ConstantFP nodes requires "
1498 "debug location. Use another overload.");
1499 }
1500 }
1501 return N;
1502}
1503
1504SDNode *SelectionDAG::lookupNode(const SDNodeKey &Key, const SDLoc &DL,
1505 FoldingSetInsertToken &InsertToken) {
1506 SDNode *N = CSEMap.lookup(Key, InsertToken);
1507 if (N) {
1508 switch (N->getOpcode()) {
1509 case ISD::Constant:
1510 case ISD::ConstantFP:
1511 // Erase debug location from the node if the node is used at several
1512 // different places. Do not propagate one location to all uses as it
1513 // will cause a worse single stepping debugging experience.
1514 if (N->getDebugLoc() != DL.getDebugLoc())
1515 N->setDebugLoc(DebugLoc());
1516 break;
1517 default:
1518 // When the node's point of use is located earlier in the instruction
1519 // sequence than its prior point of use, update its debug info to the
1520 // earlier location.
1521 if (DL.getIROrder() && DL.getIROrder() < N->getIROrder())
1522 N->setDebugLoc(DL.getDebugLoc());
1523 break;
1524 }
1525 }
1526 return N;
1527}
1528
1530 allnodes_clear();
1531 OperandRecycler.clear(OperandAllocator);
1532 OperandAllocator.Reset();
1533 CSEMap.clear();
1534
1535 ExtendedValueTypeNodes.clear();
1536 ExternalSymbols.clear();
1537 TargetExternalSymbols.clear();
1538 MCSymbols.clear();
1539 SDEI.clear();
1540 llvm::fill(CondCodeNodes, nullptr);
1541 llvm::fill(ValueTypeNodes, nullptr);
1542
1543 EntryNode.UseList = nullptr;
1544 InsertNode(&EntryNode);
1545 Root = getEntryNode();
1546 DbgInfo->clear();
1547}
1548
1550 return VT.bitsGT(Op.getValueType())
1551 ? getNode(ISD::FP_EXTEND, DL, VT, Op)
1552 : getNode(ISD::FP_ROUND, DL, VT, Op,
1553 getIntPtrConstant(0, DL, /*isTarget=*/true));
1554}
1555
1556std::pair<SDValue, SDValue>
1558 const SDLoc &DL, EVT VT) {
1559 assert(!VT.bitsEq(Op.getValueType()) &&
1560 "Strict no-op FP extend/round not allowed.");
1561 SDValue Res =
1562 VT.bitsGT(Op.getValueType())
1563 ? getNode(ISD::STRICT_FP_EXTEND, DL, {VT, MVT::Other}, {Chain, Op})
1564 : getNode(ISD::STRICT_FP_ROUND, DL, {VT, MVT::Other},
1565 {Chain, Op, getIntPtrConstant(0, DL, /*isTarget=*/true)});
1566
1567 return std::pair<SDValue, SDValue>(Res, SDValue(Res.getNode(), 1));
1568}
1569
1571 return VT.bitsGT(Op.getValueType()) ?
1572 getNode(ISD::ANY_EXTEND, DL, VT, Op) :
1573 getNode(ISD::TRUNCATE, DL, VT, Op);
1574}
1575
1577 return VT.bitsGT(Op.getValueType()) ?
1578 getNode(ISD::SIGN_EXTEND, DL, VT, Op) :
1579 getNode(ISD::TRUNCATE, DL, VT, Op);
1580}
1581
1583 return VT.bitsGT(Op.getValueType()) ?
1584 getNode(ISD::ZERO_EXTEND, DL, VT, Op) :
1585 getNode(ISD::TRUNCATE, DL, VT, Op);
1586}
1587
1589 EVT VT) {
1590 assert(!VT.isVector());
1591 auto Type = Op.getValueType();
1592 SDValue DestOp;
1593 if (Type == VT)
1594 return Op;
1595 auto Size = Op.getValueSizeInBits();
1596 DestOp = getBitcast(EVT::getIntegerVT(*Context, Size), Op);
1597 if (DestOp.getValueType() == VT)
1598 return DestOp;
1599
1600 return getAnyExtOrTrunc(DestOp, DL, VT);
1601}
1602
1604 EVT OpVT) {
1605 if (VT.bitsLE(Op.getValueType()))
1606 return getNode(ISD::TRUNCATE, SL, VT, Op);
1607
1608 TargetLowering::BooleanContent BType = TLI->getBooleanContents(OpVT);
1609 return getNode(TLI->getExtendForContent(BType), SL, VT, Op);
1610}
1611
1613 EVT OpVT = Op.getValueType();
1614 assert(VT.isInteger() && OpVT.isInteger() &&
1615 "Cannot getZeroExtendInReg FP types");
1616 assert(VT.isVector() == OpVT.isVector() &&
1617 "getZeroExtendInReg type should be vector iff the operand "
1618 "type is vector!");
1619 assert((!VT.isVector() ||
1621 "Vector element counts must match in getZeroExtendInReg");
1622 assert(VT.getScalarType().bitsLE(OpVT.getScalarType()) && "Not extending!");
1623 if (OpVT == VT)
1624 return Op;
1625 // TODO: Use computeKnownBits instead of AssertZext.
1626 if (Op.getOpcode() == ISD::AssertZext && cast<VTSDNode>(Op.getOperand(1))
1627 ->getVT()
1628 .getScalarType()
1629 .bitsLE(VT.getScalarType()))
1630 return Op;
1632 VT.getScalarSizeInBits());
1633 return getNode(ISD::AND, DL, OpVT, Op, getConstant(Imm, DL, OpVT));
1634}
1635
1637 // Only unsigned pointer semantics are supported right now. In the future this
1638 // might delegate to TLI to check pointer signedness.
1639 return getZExtOrTrunc(Op, DL, VT);
1640}
1641
1643 // Only unsigned pointer semantics are supported right now. In the future this
1644 // might delegate to TLI to check pointer signedness.
1645 return getZeroExtendInReg(Op, DL, VT);
1646}
1647
1649 return getNode(ISD::SUB, DL, VT, getConstant(0, DL, VT), Val);
1650}
1651
1652/// getNOT - Create a bitwise NOT operation as (XOR Val, -1).
1654 return getNode(ISD::XOR, DL, VT, Val, getAllOnesConstant(DL, VT));
1655}
1656
1658 SDValue TrueValue = getBoolConstant(true, DL, VT, VT);
1659 return getNode(ISD::XOR, DL, VT, Val, TrueValue);
1660}
1661
1663 EVT OpVT) {
1664 if (!V)
1665 return getConstant(0, DL, VT);
1666
1667 switch (TLI->getBooleanContents(OpVT)) {
1670 return getConstant(1, DL, VT);
1672 return getAllOnesConstant(DL, VT);
1673 }
1674 llvm_unreachable("Unexpected boolean content enum!");
1675}
1676
1678 bool isT, bool isO) {
1679 return getConstant(APInt(VT.getScalarSizeInBits(), Val, /*isSigned=*/false),
1680 DL, VT, isT, isO);
1681}
1682
1684 bool isT, bool isO) {
1685 return getConstant(*ConstantInt::get(*Context, Val), DL, VT, isT, isO);
1686}
1687
1689 EVT VT, bool isT, bool isO) {
1690 assert(VT.isInteger() && "Cannot create FP integer constant!");
1691
1692 EVT EltVT = VT.getScalarType();
1693 const ConstantInt *Elt = &Val;
1694
1695 // Vector splats are explicit within the DAG, with ConstantSDNode holding the
1696 // to-be-splatted scalar ConstantInt.
1697 if (isa<VectorType>(Elt->getType()))
1698 Elt = ConstantInt::get(*getContext(), Elt->getValue());
1699
1700 // In some cases the vector type is legal but the element type is illegal and
1701 // needs to be promoted, for example v8i8 on ARM. In this case, promote the
1702 // inserted value (the type does not need to match the vector element type).
1703 // Any extra bits introduced will be truncated away.
1704 if (VT.isVector() && TLI->getTypeAction(*getContext(), EltVT) ==
1706 EltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1707 APInt NewVal;
1708 if (TLI->isSExtCheaperThanZExt(VT.getScalarType(), EltVT))
1709 NewVal = Elt->getValue().sextOrTrunc(EltVT.getSizeInBits());
1710 else
1711 NewVal = Elt->getValue().zextOrTrunc(EltVT.getSizeInBits());
1712 Elt = ConstantInt::get(*getContext(), NewVal);
1713 }
1714 // In other cases the element type is illegal and needs to be expanded, for
1715 // example v2i64 on MIPS32. In this case, find the nearest legal type, split
1716 // the value into n parts and use a vector type with n-times the elements.
1717 // Then bitcast to the type requested.
1718 // Legalizing constants too early makes the DAGCombiner's job harder so we
1719 // only legalize if the DAG tells us we must produce legal types.
1720 else if (NewNodesMustHaveLegalTypes && VT.isVector() &&
1721 TLI->getTypeAction(*getContext(), EltVT) ==
1723 const APInt &NewVal = Elt->getValue();
1724 EVT ViaEltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1725 unsigned ViaEltSizeInBits = ViaEltVT.getSizeInBits();
1726
1727 // For scalable vectors, try to use a SPLAT_VECTOR_PARTS node.
1728 if (VT.isScalableVector() ||
1729 TLI->isOperationLegal(ISD::SPLAT_VECTOR, VT)) {
1730 assert(EltVT.getSizeInBits() % ViaEltSizeInBits == 0 &&
1731 "Can only handle an even split!");
1732 unsigned Parts = EltVT.getSizeInBits() / ViaEltSizeInBits;
1733
1734 SmallVector<SDValue, 2> ScalarParts;
1735 for (unsigned i = 0; i != Parts; ++i)
1736 ScalarParts.push_back(getConstant(
1737 NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL,
1738 ViaEltVT, isT, isO));
1739
1740 return getNode(ISD::SPLAT_VECTOR_PARTS, DL, VT, ScalarParts);
1741 }
1742
1743 unsigned ViaVecNumElts = VT.getSizeInBits() / ViaEltSizeInBits;
1744 EVT ViaVecVT = EVT::getVectorVT(*getContext(), ViaEltVT, ViaVecNumElts);
1745
1746 // Check the temporary vector is the correct size. If this fails then
1747 // getTypeToTransformTo() probably returned a type whose size (in bits)
1748 // isn't a power-of-2 factor of the requested type size.
1749 assert(ViaVecVT.getSizeInBits() == VT.getSizeInBits());
1750
1751 SmallVector<SDValue, 2> EltParts;
1752 for (unsigned i = 0; i < ViaVecNumElts / VT.getVectorNumElements(); ++i)
1753 EltParts.push_back(getConstant(
1754 NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL,
1755 ViaEltVT, isT, isO));
1756
1757 // EltParts is currently in little endian order. If we actually want
1758 // big-endian order then reverse it now.
1759 if (getDataLayout().isBigEndian())
1760 std::reverse(EltParts.begin(), EltParts.end());
1761
1762 // The elements must be reversed when the element order is different
1763 // to the endianness of the elements (because the BITCAST is itself a
1764 // vector shuffle in this situation). However, we do not need any code to
1765 // perform this reversal because getConstant() is producing a vector
1766 // splat.
1767 // This situation occurs in MIPS MSA.
1768
1770 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
1771 llvm::append_range(Ops, EltParts);
1772
1773 SDValue V =
1774 getNode(ISD::BITCAST, DL, VT, getBuildVector(ViaVecVT, DL, Ops));
1775 return V;
1776 }
1777
1778 assert(Elt->getBitWidth() == EltVT.getSizeInBits() &&
1779 "APInt size does not match type size!");
1780 unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
1781 SDVTList VTs = getVTList(EltVT);
1782 SDNodeKey ID(Opc, VTs, {});
1783 ID.AddPointer(Elt);
1784 ID.AddBoolean(isO);
1785 FoldingSetInsertToken InsertToken;
1786 SDNode *N = nullptr;
1787 if ((N = lookupNode(ID, DL, InsertToken)))
1788 if (!VT.isVector())
1789 return SDValue(N, 0);
1790
1791 if (!N) {
1792 N = newSDNode<ConstantSDNode>(isT, isO, Elt, VTs);
1793 if (!isT)
1794 N->setDebugLoc(DL.getDebugLoc());
1795 CSEMap.insert(N, InsertToken);
1796 InsertNode(N);
1797 NewSDValueDbgMsg(SDValue(N, 0), "Creating constant: ", this);
1798 }
1799
1800 SDValue Result(N, 0);
1801 if (VT.isVector())
1802 Result = getSplat(VT, DL, Result);
1803 return Result;
1804}
1805
1807 bool isT, bool isO) {
1808 unsigned Size = VT.getScalarSizeInBits();
1809 return getConstant(APInt(Size, Val, /*isSigned=*/true), DL, VT, isT, isO);
1810}
1811
1813 bool IsOpaque) {
1815 IsTarget, IsOpaque);
1816}
1817
1819 bool isTarget) {
1820 return getConstant(Val, DL, TLI->getPointerTy(getDataLayout()), isTarget);
1821}
1822
1824 const SDLoc &DL) {
1825 assert(VT.isInteger() && "Shift amount is not an integer type!");
1826 EVT ShiftVT = TLI->getShiftAmountTy(VT, getDataLayout());
1827 return getConstant(Val, DL, ShiftVT);
1828}
1829
1831 const SDLoc &DL) {
1832 assert(Val.ult(VT.getScalarSizeInBits()) && "Out of range shift");
1833 return getShiftAmountConstant(Val.getZExtValue(), VT, DL);
1834}
1835
1837 bool isTarget) {
1838 return getConstant(Val, DL, TLI->getVectorIdxTy(getDataLayout()), isTarget);
1839}
1840
1842 bool isTarget) {
1843 return getConstantFP(*ConstantFP::get(*getContext(), V), DL, VT, isTarget);
1844}
1845
1847 EVT VT, bool isTarget) {
1848 assert(VT.isFloatingPoint() && "Cannot create integer FP constant!");
1849
1850 EVT EltVT = VT.getScalarType();
1851 const ConstantFP *Elt = &V;
1852
1853 // Vector splats are explicit within the DAG, with ConstantFPSDNode holding
1854 // the to-be-splatted scalar ConstantFP.
1855 if (isa<VectorType>(Elt->getType()))
1856 Elt = ConstantFP::get(*getContext(), Elt->getValue());
1857
1858 // Do the map lookup using the actual bit pattern for the floating point
1859 // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
1860 // we don't have issues with SNANs.
1861 unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
1862 SDVTList VTs = getVTList(EltVT);
1863 SDNodeKey ID(Opc, VTs, {});
1864 ID.AddPointer(Elt);
1865 FoldingSetInsertToken InsertToken;
1866 SDNode *N = nullptr;
1867 if ((N = lookupNode(ID, DL, InsertToken)))
1868 if (!VT.isVector())
1869 return SDValue(N, 0);
1870
1871 if (!N) {
1872 N = newSDNode<ConstantFPSDNode>(isTarget, Elt, VTs);
1873 CSEMap.insert(N, InsertToken);
1874 InsertNode(N);
1875 }
1876
1877 SDValue Result(N, 0);
1878 if (VT.isVector())
1879 Result = getSplat(VT, DL, Result);
1880 NewSDValueDbgMsg(Result, "Creating fp constant: ", this);
1881 return Result;
1882}
1883
1885 bool isTarget) {
1886 EVT EltVT = VT.getScalarType();
1887 if (EltVT == MVT::f32)
1888 return getConstantFP(APFloat((float)Val), DL, VT, isTarget);
1889 if (EltVT == MVT::f64)
1890 return getConstantFP(APFloat(Val), DL, VT, isTarget);
1891 if (EltVT == MVT::f80 || EltVT == MVT::f128 || EltVT == MVT::ppcf128 ||
1892 EltVT == MVT::f16 || EltVT == MVT::bf16) {
1893 bool Ignored;
1894 APFloat APF = APFloat(Val);
1896 &Ignored);
1897 return getConstantFP(APF, DL, VT, isTarget);
1898 }
1899 llvm_unreachable("Unsupported type in getConstantFP");
1900}
1901
1903 EVT VT, int64_t Offset, bool isTargetGA,
1904 unsigned TargetFlags) {
1905 assert((TargetFlags == 0 || isTargetGA) &&
1906 "Cannot set target flags on target-independent globals");
1907
1908 // Truncate (with sign-extension) the offset value to the pointer size.
1910 if (BitWidth < 64)
1912
1913 unsigned Opc;
1914 if (GV->isThreadLocal())
1916 else
1918
1919 SDVTList VTs = getVTList(VT);
1920 SDNodeKey ID(Opc, VTs, {});
1921 ID.AddPointer(GV);
1922 ID.AddInteger(Offset);
1923 ID.AddInteger(TargetFlags);
1924 FoldingSetInsertToken InsertToken;
1925 if (SDNode *E = lookupNode(ID, DL, InsertToken))
1926 return SDValue(E, 0);
1927
1928 auto *N = newSDNode<GlobalAddressSDNode>(
1929 Opc, DL.getIROrder(), DL.getDebugLoc(), GV, VTs, Offset, TargetFlags);
1930 CSEMap.insert(N, InsertToken);
1931 InsertNode(N);
1932 return SDValue(N, 0);
1933}
1934
1936 SDVTList VTs = getVTList(MVT::Untyped);
1938 ID.AddPointer(GV);
1939 FoldingSetInsertToken InsertToken;
1940 if (SDNode *E = lookupNode(ID, SDLoc(), InsertToken))
1941 return SDValue(E, 0);
1942
1943 auto *N = newSDNode<DeactivationSymbolSDNode>(GV, VTs);
1944 CSEMap.insert(N, InsertToken);
1945 InsertNode(N);
1946 return SDValue(N, 0);
1947}
1948
1949SDValue SelectionDAG::getFrameIndex(int FI, EVT VT, bool isTarget) {
1950 unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
1951 SDVTList VTs = getVTList(VT);
1952 SDNodeKey ID(Opc, VTs, {});
1953 ID.AddInteger(FI);
1954 FoldingSetInsertToken InsertToken;
1955 if (SDNode *E = lookupNode(ID, InsertToken))
1956 return SDValue(E, 0);
1957
1958 auto *N = newSDNode<FrameIndexSDNode>(FI, VTs, isTarget);
1959 CSEMap.insert(N, InsertToken);
1960 InsertNode(N);
1961 return SDValue(N, 0);
1962}
1963
1964SDValue SelectionDAG::getJumpTable(int JTI, EVT VT, bool isTarget,
1965 unsigned TargetFlags) {
1966 assert((TargetFlags == 0 || isTarget) &&
1967 "Cannot set target flags on target-independent jump tables");
1968 unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
1969 SDVTList VTs = getVTList(VT);
1970 SDNodeKey ID(Opc, VTs, {});
1971 ID.AddInteger(JTI);
1972 ID.AddInteger(TargetFlags);
1973 FoldingSetInsertToken InsertToken;
1974 if (SDNode *E = lookupNode(ID, InsertToken))
1975 return SDValue(E, 0);
1976
1977 auto *N = newSDNode<JumpTableSDNode>(JTI, VTs, isTarget, TargetFlags);
1978 CSEMap.insert(N, InsertToken);
1979 InsertNode(N);
1980 return SDValue(N, 0);
1981}
1982
1984 const SDLoc &DL) {
1986 return getNode(ISD::JUMP_TABLE_DEBUG_INFO, DL, MVT::Other, Chain,
1987 getTargetConstant(static_cast<uint64_t>(JTI), DL, PTy, true));
1988}
1989
1991 MaybeAlign Alignment, int Offset,
1992 bool isTarget, unsigned TargetFlags) {
1993 assert((TargetFlags == 0 || isTarget) &&
1994 "Cannot set target flags on target-independent globals");
1995 if (!Alignment)
1996 Alignment = shouldOptForSize()
1997 ? getDataLayout().getABITypeAlign(C->getType())
1998 : getDataLayout().getPrefTypeAlign(C->getType());
1999 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
2000 SDVTList VTs = getVTList(VT);
2001 SDNodeKey ID(Opc, VTs, {});
2002 ID.AddInteger(Alignment->value());
2003 ID.AddInteger(Offset);
2004 ID.AddPointer(C);
2005 ID.AddInteger(TargetFlags);
2006 FoldingSetInsertToken InsertToken;
2007 if (SDNode *E = lookupNode(ID, InsertToken))
2008 return SDValue(E, 0);
2009
2010 auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VTs, Offset, *Alignment,
2011 TargetFlags);
2012 CSEMap.insert(N, InsertToken);
2013 InsertNode(N);
2014 SDValue V = SDValue(N, 0);
2015 NewSDValueDbgMsg(V, "Creating new constant pool: ", this);
2016 return V;
2017}
2018
2020 MaybeAlign Alignment, int Offset,
2021 bool isTarget, unsigned TargetFlags) {
2022 assert((TargetFlags == 0 || isTarget) &&
2023 "Cannot set target flags on target-independent globals");
2024 if (!Alignment)
2025 Alignment = getDataLayout().getPrefTypeAlign(C->getType());
2026 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
2027 SDVTList VTs = getVTList(VT);
2028 SDNodeKey ID(Opc, VTs, {});
2029 ID.AddInteger(Alignment->value());
2030 ID.AddInteger(Offset);
2031 C->addSelectionDAGCSEId(ID.Tail);
2032 ID.AddInteger(TargetFlags);
2033 FoldingSetInsertToken InsertToken;
2034 if (SDNode *E = lookupNode(ID, InsertToken))
2035 return SDValue(E, 0);
2036
2037 auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VTs, Offset, *Alignment,
2038 TargetFlags);
2039 CSEMap.insert(N, InsertToken);
2040 InsertNode(N);
2041 return SDValue(N, 0);
2042}
2043
2045 SDNodeKey ID(ISD::BasicBlock, getVTList(MVT::Other), {});
2046 ID.AddPointer(MBB);
2047 FoldingSetInsertToken InsertToken;
2048 if (SDNode *E = lookupNode(ID, InsertToken))
2049 return SDValue(E, 0);
2050
2051 auto *N = newSDNode<BasicBlockSDNode>(MBB);
2052 CSEMap.insert(N, InsertToken);
2053 InsertNode(N);
2054 return SDValue(N, 0);
2055}
2056
2058 if (VT.isSimple() && (unsigned)VT.getSimpleVT().SimpleTy >=
2059 ValueTypeNodes.size())
2060 ValueTypeNodes.resize(VT.getSimpleVT().SimpleTy+1);
2061
2062 SDNode *&N = VT.isExtended() ?
2063 ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT().SimpleTy];
2064
2065 if (N) return SDValue(N, 0);
2066 N = newSDNode<VTSDNode>(VT);
2067 InsertNode(N);
2068 return SDValue(N, 0);
2069}
2070
2072 SDNode *&N = ExternalSymbols[Sym];
2073 if (N) return SDValue(N, 0);
2074 N = newSDNode<ExternalSymbolSDNode>(false, Sym, 0, getVTList(VT));
2075 InsertNode(N);
2076 return SDValue(N, 0);
2077}
2078
2079SDValue SelectionDAG::getExternalSymbol(RTLIB::LibcallImpl Libcall, EVT VT) {
2081 return getExternalSymbol(SymName.data(), VT);
2082}
2083
2085 SDNode *&N = MCSymbols[Sym];
2086 if (N)
2087 return SDValue(N, 0);
2088 N = newSDNode<MCSymbolSDNode>(Sym, getVTList(VT));
2089 InsertNode(N);
2090 return SDValue(N, 0);
2091}
2092
2094 unsigned TargetFlags) {
2095 SDNode *&N =
2096 TargetExternalSymbols[std::pair<std::string, unsigned>(Sym, TargetFlags)];
2097 if (N) return SDValue(N, 0);
2098 N = newSDNode<ExternalSymbolSDNode>(true, Sym, TargetFlags, getVTList(VT));
2099 InsertNode(N);
2100 return SDValue(N, 0);
2101}
2102
2104 EVT VT, unsigned TargetFlags) {
2106 return getTargetExternalSymbol(SymName.data(), VT, TargetFlags);
2107}
2108
2110 if ((unsigned)Cond >= CondCodeNodes.size())
2111 CondCodeNodes.resize(Cond+1);
2112
2113 if (!CondCodeNodes[Cond]) {
2114 auto *N = newSDNode<CondCodeSDNode>(Cond);
2115 CondCodeNodes[Cond] = N;
2116 InsertNode(N);
2117 }
2118
2119 return SDValue(CondCodeNodes[Cond], 0);
2120}
2121
2123 assert(MulImm.getBitWidth() == VT.getSizeInBits() &&
2124 "APInt size does not match type size!");
2125
2126 if (MulImm == 0)
2127 return getConstant(0, DL, VT);
2128
2129 const MachineFunction &MF = getMachineFunction();
2130 const Function &F = MF.getFunction();
2131 ConstantRange CR = getVScaleRange(&F, 64);
2132 if (const APInt *C = CR.getSingleElement())
2133 return getConstant(MulImm * C->getZExtValue(), DL, VT);
2134
2135 return getNode(ISD::VSCALE, DL, VT, getConstant(MulImm, DL, VT));
2136}
2137
2138/// \returns a value of type \p VT that represents the runtime value of \p
2139/// Quantity, i.e. scaled by vscale if it's scalable, or a fixed constant
2140/// otherwise. Quantity should be a FixedOrScalableQuantity, i.e. ElementCount
2141/// or TypeSize.
2142template <typename Ty>
2144 EVT VT, Ty Quantity) {
2145 if (Quantity.isScalable())
2146 return DAG.getVScale(
2147 DL, VT, APInt(VT.getSizeInBits(), Quantity.getKnownMinValue()));
2148
2149 return DAG.getConstant(Quantity.getKnownMinValue(), DL, VT);
2150}
2151
2153 ElementCount EC) {
2154 return getFixedOrScalableQuantity(*this, DL, VT, EC);
2155}
2156
2158 return getFixedOrScalableQuantity(*this, DL, VT, TS);
2159}
2160
2162 ElementCount EC) {
2163 EVT IdxVT = TLI->getVectorIdxTy(getDataLayout());
2164 EVT MaskVT = TLI->getSetCCResultType(getDataLayout(), *getContext(), DataVT);
2165 return getNode(ISD::GET_ACTIVE_LANE_MASK, DL, MaskVT,
2166 getConstant(0, DL, IdxVT), getElementCount(DL, IdxVT, EC));
2167}
2168
2170 APInt One(ResVT.getScalarSizeInBits(), 1);
2171 return getStepVector(DL, ResVT, One);
2172}
2173
2175 const APInt &StepVal) {
2176 assert(ResVT.getScalarSizeInBits() == StepVal.getBitWidth());
2177 if (ResVT.isScalableVector())
2178 return getNode(
2179 ISD::STEP_VECTOR, DL, ResVT,
2180 getTargetConstant(StepVal, DL, ResVT.getVectorElementType()));
2181
2182 SmallVector<SDValue, 16> OpsStepConstants;
2183 for (uint64_t i = 0; i < ResVT.getVectorNumElements(); i++)
2184 OpsStepConstants.push_back(
2185 getConstant(StepVal * i, DL, ResVT.getVectorElementType()));
2186 return getBuildVector(ResVT, DL, OpsStepConstants);
2187}
2188
2189/// Swaps the values of N1 and N2. Swaps all indices in the shuffle mask M that
2190/// point at N1 to point at N2 and indices that point at N2 to point at N1.
2195
2197 SDValue N2, ArrayRef<int> Mask) {
2198 assert(VT.getVectorNumElements() == Mask.size() &&
2199 "Must have the same number of vector elements as mask elements!");
2200 assert(VT == N1.getValueType() && VT == N2.getValueType() &&
2201 "Invalid VECTOR_SHUFFLE");
2202
2203 // Canonicalize shuffle undef, undef -> undef
2204 if (N1.isUndef() && N2.isUndef()) {
2205 if (N1.getOpcode() == ISD::POISON && N2.getOpcode() == ISD::POISON)
2206 return getPOISON(VT);
2207 return getUNDEF(VT);
2208 }
2209
2210 // Validate that all indices in Mask are within the range of the elements
2211 // input to the shuffle.
2212 int NElts = Mask.size();
2213 assert(llvm::all_of(Mask,
2214 [&](int M) { return M < (NElts * 2) && M >= -1; }) &&
2215 "Index out of range");
2216
2217 // Copy the mask so we can do any needed cleanup.
2218 SmallVector<int, 8> MaskVec(Mask);
2219
2220 // Canonicalize shuffle v, v -> v, poison
2221 if (N1 == N2) {
2222 N2 = getPOISON(VT);
2223 for (int i = 0; i != NElts; ++i)
2224 if (MaskVec[i] >= NElts) MaskVec[i] -= NElts;
2225 }
2226
2227 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
2228 if (N1.isUndef())
2229 commuteShuffle(N1, N2, MaskVec);
2230
2231 if (TLI->hasVectorBlend()) {
2232 // If shuffling a splat, try to blend the splat instead. We do this here so
2233 // that even when this arises during lowering we don't have to re-handle it.
2234 auto BlendSplat = [&](BuildVectorSDNode *BV, int Offset) {
2235 BitVector UndefElements;
2236 SDValue Splat = BV->getSplatValue(&UndefElements);
2237 if (!Splat)
2238 return;
2239
2240 for (int i = 0; i < NElts; ++i) {
2241 if (MaskVec[i] < Offset || MaskVec[i] >= (Offset + NElts))
2242 continue;
2243
2244 // If this input comes from undef, mark it as such.
2245 if (UndefElements[MaskVec[i] - Offset]) {
2246 MaskVec[i] = -1;
2247 continue;
2248 }
2249
2250 // If we can blend a non-undef lane, use that instead.
2251 if (!UndefElements[i])
2252 MaskVec[i] = i + Offset;
2253 }
2254 };
2255 if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
2256 BlendSplat(N1BV, 0);
2257 if (auto *N2BV = dyn_cast<BuildVectorSDNode>(N2))
2258 BlendSplat(N2BV, NElts);
2259 }
2260
2261 // Canonicalize all index into lhs, -> shuffle lhs, poison
2262 // Canonicalize all index into rhs, -> shuffle rhs, poison
2263 bool AllLHS = true, AllRHS = true;
2264 bool N2Undef = N2.isUndef();
2265 for (int i = 0; i != NElts; ++i) {
2266 if (MaskVec[i] >= NElts) {
2267 if (N2Undef)
2268 MaskVec[i] = -1;
2269 else
2270 AllLHS = false;
2271 } else if (MaskVec[i] >= 0) {
2272 AllRHS = false;
2273 }
2274 }
2275 if (AllLHS && AllRHS)
2276 return getPOISON(VT);
2277 if (AllLHS && !N2Undef)
2278 N2 = getPOISON(VT);
2279 if (AllRHS) {
2280 N1 = getPOISON(VT);
2281 commuteShuffle(N1, N2, MaskVec);
2282 }
2283 // Reset our undef status after accounting for the mask.
2284 N2Undef = N2.isUndef();
2285 // Re-check whether both sides ended up undef.
2286 if (N1.isUndef() && N2Undef) {
2287 if (N1.getOpcode() == ISD::POISON && N2.getOpcode() == ISD::POISON)
2288 return getPOISON(VT);
2289 return getUNDEF(VT);
2290 }
2291
2292 // If Identity shuffle return that node.
2293 bool Identity = true, AllSame = true;
2294 for (int i = 0; i != NElts; ++i) {
2295 if (MaskVec[i] >= 0 && MaskVec[i] != i) Identity = false;
2296 if (MaskVec[i] != MaskVec[0]) AllSame = false;
2297 }
2298 if (Identity && NElts)
2299 return N1;
2300
2301 // Shuffling a constant splat doesn't change the result.
2302 if (N2Undef) {
2303 SDValue V = N1;
2304
2305 // Look through any bitcasts. We check that these don't change the number
2306 // (and size) of elements and just changes their types.
2307 while (V.getOpcode() == ISD::BITCAST)
2308 V = V->getOperand(0);
2309
2310 // A splat should always show up as a build vector node.
2311 if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) {
2312 BitVector UndefElements;
2313 SDValue Splat = BV->getSplatValue(&UndefElements);
2314 // If this is a splat of an undef, shuffling it is also undef.
2315 if (Splat && Splat.isUndef())
2316 return Splat.getOpcode() == ISD::POISON ? getPOISON(VT) : getUNDEF(VT);
2317
2318 bool SameNumElts =
2319 V.getValueType().getVectorNumElements() == VT.getVectorNumElements();
2320
2321 // We only have a splat which can skip shuffles if there is a splatted
2322 // value and no undef lanes rearranged by the shuffle.
2323 if (Splat && UndefElements.none()) {
2324 // Splat of <x, x, ..., x>, return <x, x, ..., x>, provided that the
2325 // number of elements match or the value splatted is a zero constant.
2326 if (SameNumElts || isNullConstant(Splat))
2327 return N1;
2328 }
2329
2330 // If the shuffle itself creates a splat, build the vector directly.
2331 if (AllSame && SameNumElts) {
2332 EVT BuildVT = BV->getValueType(0);
2333 const SDValue &Splatted = BV->getOperand(MaskVec[0]);
2334 SDValue NewBV = getSplatBuildVector(BuildVT, dl, Splatted);
2335
2336 // We may have jumped through bitcasts, so the type of the
2337 // BUILD_VECTOR may not match the type of the shuffle.
2338 if (BuildVT != VT)
2339 NewBV = getNode(ISD::BITCAST, dl, VT, NewBV);
2340 return NewBV;
2341 }
2342 }
2343 }
2344
2345 SDVTList VTs = getVTList(VT);
2346 SDValue Ops[2] = { N1, N2 };
2348 for (int i = 0; i != NElts; ++i)
2349 ID.AddInteger(MaskVec[i]);
2350
2351 FoldingSetInsertToken InsertToken;
2352 if (SDNode *E = lookupNode(ID, dl, InsertToken))
2353 return SDValue(E, 0);
2354
2355 // Allocate the mask array for the node out of the BumpPtrAllocator, since
2356 // SDNode doesn't have access to it. This memory will be "leaked" when
2357 // the node is deallocated, but recovered when the NodeAllocator is released.
2358 int *MaskAlloc = OperandAllocator.Allocate<int>(NElts);
2359 llvm::copy(MaskVec, MaskAlloc);
2360
2361 auto *N = newSDNode<ShuffleVectorSDNode>(VTs, dl.getIROrder(),
2362 dl.getDebugLoc(), MaskAlloc);
2363 createOperands(N, Ops);
2364
2365 CSEMap.insert(N, InsertToken);
2366 InsertNode(N);
2367 SDValue V = SDValue(N, 0);
2368 NewSDValueDbgMsg(V, "Creating new node: ", this);
2369 return V;
2370}
2371
2373 EVT VT = SV.getValueType(0);
2374 SmallVector<int, 8> MaskVec(SV.getMask());
2376
2377 SDValue Op0 = SV.getOperand(0);
2378 SDValue Op1 = SV.getOperand(1);
2379 return getVectorShuffle(VT, SDLoc(&SV), Op1, Op0, MaskVec);
2380}
2381
2383 SDVTList VTs = getVTList(VT);
2384 SDNodeKey ID(ISD::Register, VTs, {});
2385 ID.AddInteger(Reg.id());
2386 FoldingSetInsertToken InsertToken;
2387 if (SDNode *E = lookupNode(ID, InsertToken))
2388 return SDValue(E, 0);
2389
2390 auto *N = newSDNode<RegisterSDNode>(Reg, VTs);
2391 N->SDNodeBits.IsDivergent = TLI->isSDNodeSourceOfDivergence(N, FLI, UA);
2392 CSEMap.insert(N, InsertToken);
2393 InsertNode(N);
2394 return SDValue(N, 0);
2395}
2396
2398 SDNodeKey ID(ISD::RegisterMask, getVTList(MVT::Untyped), {});
2399 ID.AddPointer(RegMask);
2400 FoldingSetInsertToken InsertToken;
2401 if (SDNode *E = lookupNode(ID, InsertToken))
2402 return SDValue(E, 0);
2403
2404 auto *N = newSDNode<RegisterMaskSDNode>(RegMask);
2405 CSEMap.insert(N, InsertToken);
2406 InsertNode(N);
2407 return SDValue(N, 0);
2408}
2409
2411 MCSymbol *Label) {
2412 return getLabelNode(ISD::EH_LABEL, dl, Root, Label);
2413}
2414
2415SDValue SelectionDAG::getLabelNode(unsigned Opcode, const SDLoc &dl,
2416 SDValue Root, MCSymbol *Label) {
2417 SDValue Ops[] = { Root };
2418 SDNodeKey ID(Opcode, getVTList(MVT::Other), Ops);
2419 ID.AddPointer(Label);
2420 FoldingSetInsertToken InsertToken;
2421 if (SDNode *E = lookupNode(ID, InsertToken))
2422 return SDValue(E, 0);
2423
2424 auto *N =
2425 newSDNode<LabelSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), Label);
2426 createOperands(N, Ops);
2427
2428 CSEMap.insert(N, InsertToken);
2429 InsertNode(N);
2430 return SDValue(N, 0);
2431}
2432
2434 int64_t Offset, bool isTarget,
2435 unsigned TargetFlags) {
2436 unsigned Opc = isTarget ? ISD::TargetBlockAddress : ISD::BlockAddress;
2437 SDVTList VTs = getVTList(VT);
2438
2439 SDNodeKey ID(Opc, VTs, {});
2440 ID.AddPointer(BA);
2441 ID.AddInteger(Offset);
2442 ID.AddInteger(TargetFlags);
2443 FoldingSetInsertToken InsertToken;
2444 if (SDNode *E = lookupNode(ID, InsertToken))
2445 return SDValue(E, 0);
2446
2447 auto *N = newSDNode<BlockAddressSDNode>(Opc, VTs, BA, Offset, TargetFlags);
2448 CSEMap.insert(N, InsertToken);
2449 InsertNode(N);
2450 return SDValue(N, 0);
2451}
2452
2454 SDNodeKey ID(ISD::SRCVALUE, getVTList(MVT::Other), {});
2455 ID.AddPointer(V);
2456
2457 FoldingSetInsertToken InsertToken;
2458 if (SDNode *E = lookupNode(ID, InsertToken))
2459 return SDValue(E, 0);
2460
2461 auto *N = newSDNode<SrcValueSDNode>(V);
2462 CSEMap.insert(N, InsertToken);
2463 InsertNode(N);
2464 return SDValue(N, 0);
2465}
2466
2468 SDNodeKey ID(ISD::MDNODE_SDNODE, getVTList(MVT::Other), {});
2469 ID.AddPointer(MD);
2470
2471 FoldingSetInsertToken InsertToken;
2472 if (SDNode *E = lookupNode(ID, InsertToken))
2473 return SDValue(E, 0);
2474
2475 auto *N = newSDNode<MDNodeSDNode>(MD);
2476 CSEMap.insert(N, InsertToken);
2477 InsertNode(N);
2478 return SDValue(N, 0);
2479}
2480
2482 if (VT == V.getValueType())
2483 return V;
2484
2485 return getNode(ISD::BITCAST, SDLoc(V), VT, V);
2486}
2487
2489 unsigned SrcAS, unsigned DestAS,
2490 const SDNodeFlags Flags) {
2491 SDVTList VTs = getVTList(VT);
2492 SDValue Ops[] = {Ptr};
2494 ID.AddInteger(SrcAS);
2495 ID.AddInteger(DestAS);
2496
2497 FoldingSetInsertToken InsertToken;
2498 if (SDNode *E = lookupNode(ID, dl, InsertToken)) {
2499 E->intersectFlagsWith(Flags);
2500 return SDValue(E, 0);
2501 }
2502
2503 auto *N = newSDNode<AddrSpaceCastSDNode>(dl.getIROrder(), dl.getDebugLoc(),
2504 VTs, SrcAS, DestAS);
2505 N->setFlags(Flags);
2506 createOperands(N, Ops);
2507
2508 CSEMap.insert(N, InsertToken);
2509 InsertNode(N);
2510 return SDValue(N, 0);
2511}
2512
2514 return getNode(ISD::FREEZE, SDLoc(V), V.getValueType(), V);
2515}
2516
2518 UndefPoisonKind Kind) {
2519 if (isGuaranteedNotToBeUndefOrPoison(V, DemandedElts, Kind))
2520 return V;
2521 return getFreeze(V);
2522}
2523
2524/// getShiftAmountOperand - Return the specified value casted to
2525/// the target's desired shift amount type.
2527 EVT OpTy = Op.getValueType();
2528 EVT ShTy = TLI->getShiftAmountTy(LHSTy, getDataLayout());
2529 if (OpTy == ShTy || OpTy.isVector()) return Op;
2530
2531 return getZExtOrTrunc(Op, SDLoc(Op), ShTy);
2532}
2533
2535 SDLoc dl(Node);
2537 const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2538 EVT VT = Node->getValueType(0);
2539 SDValue Tmp1 = Node->getOperand(0);
2540 SDValue Tmp2 = Node->getOperand(1);
2541 const MaybeAlign MA(Node->getConstantOperandVal(3));
2542
2543 SDValue VAListLoad = getLoad(TLI.getPointerTy(getDataLayout()), dl, Tmp1,
2544 Tmp2, MachinePointerInfo(V));
2545 SDValue VAList = VAListLoad;
2546
2547 if (MA && *MA > TLI.getMinStackArgumentAlignment()) {
2548 VAList = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
2549 getConstant(MA->value() - 1, dl, VAList.getValueType()));
2550
2551 VAList = getNode(
2552 ISD::AND, dl, VAList.getValueType(), VAList,
2553 getSignedConstant(-(int64_t)MA->value(), dl, VAList.getValueType()));
2554 }
2555
2556 // Increment the pointer, VAList, to the next vaarg
2557 Tmp1 = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
2558 getConstant(getDataLayout().getTypeAllocSize(
2559 VT.getTypeForEVT(*getContext())),
2560 dl, VAList.getValueType()));
2561 // Store the incremented VAList to the legalized pointer
2562 Tmp1 =
2563 getStore(VAListLoad.getValue(1), dl, Tmp1, Tmp2, MachinePointerInfo(V));
2564 // Load the actual argument out of the pointer VAList
2565 return getLoad(VT, dl, Tmp1, VAList, MachinePointerInfo());
2566}
2567
2569 SDLoc dl(Node);
2571 // This defaults to loading a pointer from the input and storing it to the
2572 // output, returning the chain.
2573 const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue();
2574 const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue();
2575 SDValue Tmp1 =
2576 getLoad(TLI.getPointerTy(getDataLayout()), dl, Node->getOperand(0),
2577 Node->getOperand(2), MachinePointerInfo(VS));
2578 return getStore(Tmp1.getValue(1), dl, Tmp1, Node->getOperand(1),
2579 MachinePointerInfo(VD));
2580}
2581
2583 const DataLayout &DL = getDataLayout();
2584 Type *Ty = VT.getTypeForEVT(*getContext());
2585 Align RedAlign = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty);
2586
2587 if (TLI->isTypeLegal(VT) || !VT.isVector())
2588 return RedAlign;
2589
2590 const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
2591 const Align StackAlign = TFI->getStackAlign();
2592
2593 // See if we can choose a smaller ABI alignment in cases where it's an
2594 // illegal vector type that will get broken down.
2595 if (RedAlign > StackAlign) {
2596 EVT IntermediateVT;
2597 MVT RegisterVT;
2598 unsigned NumIntermediates;
2599 TLI->getVectorTypeBreakdown(*getContext(), VT, IntermediateVT,
2600 NumIntermediates, RegisterVT);
2601 Ty = IntermediateVT.getTypeForEVT(*getContext());
2602 Align RedAlign2 = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty);
2603 if (RedAlign2 < RedAlign)
2604 RedAlign = RedAlign2;
2605
2606 if (!getMachineFunction().getFrameInfo().isStackRealignable())
2607 // If the stack is not realignable, the alignment should be limited to the
2608 // StackAlignment
2609 RedAlign = std::min(RedAlign, StackAlign);
2610 }
2611
2612 return RedAlign;
2613}
2614
2616 MachineFrameInfo &MFI = MF->getFrameInfo();
2617 const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
2618 int StackID = 0;
2619 if (Bytes.isScalable())
2620 StackID = TFI->getStackIDForScalableVectors();
2621 // The stack id gives an indication of whether the object is scalable or
2622 // not, so it's safe to pass in the minimum size here.
2623 int FrameIdx = MFI.CreateStackObject(Bytes.getKnownMinValue(), Alignment,
2624 false, nullptr, StackID);
2625 return getFrameIndex(FrameIdx, TLI->getFrameIndexTy(getDataLayout()));
2626}
2627
2629 Type *Ty = VT.getTypeForEVT(*getContext());
2630 Align StackAlign =
2631 std::max(getDataLayout().getPrefTypeAlign(Ty), Align(minAlign));
2632 return CreateStackTemporary(VT.getStoreSize(), StackAlign);
2633}
2634
2636 TypeSize VT1Size = VT1.getStoreSize();
2637 TypeSize VT2Size = VT2.getStoreSize();
2638 assert(VT1Size.isScalable() == VT2Size.isScalable() &&
2639 "Don't know how to choose the maximum size when creating a stack "
2640 "temporary");
2641 TypeSize Bytes = VT1Size.getKnownMinValue() > VT2Size.getKnownMinValue()
2642 ? VT1Size
2643 : VT2Size;
2644
2645 Type *Ty1 = VT1.getTypeForEVT(*getContext());
2646 Type *Ty2 = VT2.getTypeForEVT(*getContext());
2647 const DataLayout &DL = getDataLayout();
2648 Align Align = std::max(DL.getPrefTypeAlign(Ty1), DL.getPrefTypeAlign(Ty2));
2649 return CreateStackTemporary(Bytes, Align);
2650}
2651
2653 const SDLoc &DL, SDValue Chain) {
2654 EVT SrcVT = SrcOp.getValueType();
2655 Type *DestType = DestVT.getTypeForEVT(*getContext());
2656 Align DestAlign = getDataLayout().getPrefTypeAlign(DestType);
2657
2658 // Create the stack frame object.
2659 Align SrcAlign =
2661 SDValue FIPtr = CreateStackTemporary(SlotVT.getStoreSize(), SrcAlign);
2662
2663 FrameIndexSDNode *StackPtrFI = cast<FrameIndexSDNode>(FIPtr);
2664 int SPFI = StackPtrFI->getIndex();
2665 MachinePointerInfo PtrInfo =
2667
2668 // Emit a store to the stack slot. Use a truncstore if the input value is
2669 // later than DestVT.
2670 SDValue Store;
2671
2672 if (SrcVT.bitsGT(SlotVT))
2673 Store = getTruncStore(Chain, DL, SrcOp, FIPtr, PtrInfo, SlotVT, SrcAlign);
2674 else {
2675 assert(SrcVT.bitsEq(SlotVT) && "Invalid store");
2676 Store = getStore(Chain, DL, SrcOp, FIPtr, PtrInfo, SrcAlign);
2677 }
2678
2679 // Result is a load from the stack slot.
2680 if (SlotVT.bitsEq(DestVT))
2681 return getLoad(DestVT, DL, Store, FIPtr, PtrInfo, DestAlign);
2682
2683 assert(SlotVT.bitsLT(DestVT) && "Unknown extension!");
2684 return getExtLoad(ISD::EXTLOAD, DL, DestVT, Store, FIPtr, PtrInfo, SlotVT,
2685 DestAlign);
2686}
2687
2689 ISD::CondCode Cond, const SDLoc &dl,
2690 SDNodeFlags Flags) {
2691 EVT OpVT = N1.getValueType();
2692
2693 auto GetUndefBooleanConstant = [&]() {
2694 if (VT.getScalarType() == MVT::i1 ||
2695 TLI->getBooleanContents(OpVT) ==
2697 return getUNDEF(VT);
2698 // ZeroOrOne / ZeroOrNegative require specific values for the high bits,
2699 // so we cannot use getUNDEF(). Return zero instead.
2700 return getConstant(0, dl, VT);
2701 };
2702
2703 // These setcc operations always fold.
2704 switch (Cond) {
2705 default: break;
2706 case ISD::SETFALSE:
2707 case ISD::SETFALSE2: return getBoolConstant(false, dl, VT, OpVT);
2708 case ISD::SETTRUE:
2709 case ISD::SETTRUE2: return getBoolConstant(true, dl, VT, OpVT);
2710
2711 case ISD::SETOEQ:
2712 case ISD::SETOGT:
2713 case ISD::SETOGE:
2714 case ISD::SETOLT:
2715 case ISD::SETOLE:
2716 case ISD::SETONE:
2717 case ISD::SETO:
2718 case ISD::SETUO:
2719 case ISD::SETUEQ:
2720 case ISD::SETUNE:
2721 assert(!OpVT.isInteger() && "Illegal setcc for integer!");
2722 break;
2723 }
2724
2725 if (OpVT.isInteger()) {
2726 // For EQ and NE, we can always pick a value for the undef to make the
2727 // predicate pass or fail, so we can return undef.
2728 // Matches behavior in llvm::ConstantFoldCompareInstruction.
2729 // icmp eq/ne X, undef -> undef.
2730 if ((N1.isUndef() || N2.isUndef()) &&
2731 (Cond == ISD::SETEQ || Cond == ISD::SETNE))
2732 return GetUndefBooleanConstant();
2733
2734 // If both operands are undef, we can return undef for int comparison.
2735 // icmp undef, undef -> undef.
2736 if (N1.isUndef() && N2.isUndef())
2737 return GetUndefBooleanConstant();
2738
2739 // icmp X, X -> true/false
2740 // icmp X, undef -> true/false because undef could be X.
2741 if (N1.isUndef() || N2.isUndef() || N1 == N2)
2742 return getBoolConstant(ISD::isTrueWhenEqual(Cond), dl, VT, OpVT);
2743 }
2744
2745 if (ConstantSDNode *N2C = isConstOrConstSplat(N2)) {
2746 const APInt &C2 = N2C->getAPIntValue();
2747 if (ConstantSDNode *N1C = isConstOrConstSplat(N1)) {
2748 const APInt &C1 = N1C->getAPIntValue();
2749
2751 dl, VT, OpVT);
2752 }
2753 }
2754
2755 auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
2756 auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
2757
2758 if (N1CFP && N2CFP) {
2759 APFloat::cmpResult R = N1CFP->getValueAPF().compare(N2CFP->getValueAPF());
2760 switch (Cond) {
2761 default: break;
2762 case ISD::SETEQ: if (R==APFloat::cmpUnordered)
2763 return GetUndefBooleanConstant();
2764 [[fallthrough]];
2765 case ISD::SETOEQ: return getBoolConstant(R==APFloat::cmpEqual, dl, VT,
2766 OpVT);
2767 case ISD::SETNE: if (R==APFloat::cmpUnordered)
2768 return GetUndefBooleanConstant();
2769 [[fallthrough]];
2771 R==APFloat::cmpLessThan, dl, VT,
2772 OpVT);
2773 case ISD::SETLT: if (R==APFloat::cmpUnordered)
2774 return GetUndefBooleanConstant();
2775 [[fallthrough]];
2776 case ISD::SETOLT: return getBoolConstant(R==APFloat::cmpLessThan, dl, VT,
2777 OpVT);
2778 case ISD::SETGT: if (R==APFloat::cmpUnordered)
2779 return GetUndefBooleanConstant();
2780 [[fallthrough]];
2782 VT, OpVT);
2783 case ISD::SETLE: if (R==APFloat::cmpUnordered)
2784 return GetUndefBooleanConstant();
2785 [[fallthrough]];
2787 R==APFloat::cmpEqual, dl, VT,
2788 OpVT);
2789 case ISD::SETGE: if (R==APFloat::cmpUnordered)
2790 return GetUndefBooleanConstant();
2791 [[fallthrough]];
2793 R==APFloat::cmpEqual, dl, VT, OpVT);
2794 case ISD::SETO: return getBoolConstant(R!=APFloat::cmpUnordered, dl, VT,
2795 OpVT);
2796 case ISD::SETUO: return getBoolConstant(R==APFloat::cmpUnordered, dl, VT,
2797 OpVT);
2799 R==APFloat::cmpEqual, dl, VT,
2800 OpVT);
2801 case ISD::SETUNE: return getBoolConstant(R!=APFloat::cmpEqual, dl, VT,
2802 OpVT);
2804 R==APFloat::cmpLessThan, dl, VT,
2805 OpVT);
2807 R==APFloat::cmpUnordered, dl, VT,
2808 OpVT);
2810 VT, OpVT);
2811 case ISD::SETUGE: return getBoolConstant(R!=APFloat::cmpLessThan, dl, VT,
2812 OpVT);
2813 }
2814 } else if (N1CFP && OpVT.isSimple() && !N2.isUndef()) {
2815 // Ensure that the constant occurs on the RHS.
2817 if (!TLI->isCondCodeLegal(SwappedCond, OpVT.getSimpleVT()))
2818 return SDValue();
2819 return getSetCC(dl, VT, N2, N1, SwappedCond, /*Chain=*/{},
2820 /*IsSignaling=*/false, Flags);
2821 } else if ((N2CFP && N2CFP->getValueAPF().isNaN()) ||
2822 (OpVT.isFloatingPoint() && (N1.isUndef() || N2.isUndef()))) {
2823 // If an operand is known to be a nan (or undef that could be a nan), we can
2824 // fold it.
2825 // Choosing NaN for the undef will always make unordered comparison succeed
2826 // and ordered comparison fails.
2827 // Matches behavior in llvm::ConstantFoldCompareInstruction.
2828 switch (ISD::getUnorderedFlavor(Cond)) {
2829 default:
2830 llvm_unreachable("Unknown flavor!");
2831 case 0: // Known false.
2832 return getBoolConstant(false, dl, VT, OpVT);
2833 case 1: // Known true.
2834 return getBoolConstant(true, dl, VT, OpVT);
2835 case 2: // Undefined.
2836 return GetUndefBooleanConstant();
2837 }
2838 }
2839
2840 // Could not fold it.
2841 return SDValue();
2842}
2843
2844/// SignBitIsZero - Return true if the sign bit of Op is known to be zero. We
2845/// use this predicate to simplify operations downstream.
2847 unsigned BitWidth = Op.getScalarValueSizeInBits();
2849}
2850
2851// TODO: Should have argument to specify if sign bit of nan is ignorable.
2853 if (Depth >= MaxRecursionDepth)
2854 return false; // Limit search depth.
2855
2856 unsigned Opc = Op.getOpcode();
2857 switch (Opc) {
2858 case ISD::FABS:
2859 return true;
2860 case ISD::AssertNoFPClass: {
2861 FPClassTest NoFPClass =
2862 static_cast<FPClassTest>(Op.getConstantOperandVal(1));
2863
2864 const FPClassTest TestMask = fcNan | fcNegative;
2865 return (NoFPClass & TestMask) == TestMask;
2866 }
2867 case ISD::ARITH_FENCE:
2868 return SignBitIsZeroFP(Op.getOperand(0), Depth + 1);
2869 case ISD::FEXP:
2870 case ISD::FEXP2:
2871 case ISD::FEXP10:
2872 return Op->getFlags().hasNoNaNs();
2873 case ISD::FMINNUM:
2874 case ISD::FMINNUM_IEEE:
2875 case ISD::FMINIMUM:
2876 case ISD::FMINIMUMNUM:
2877 return SignBitIsZeroFP(Op.getOperand(1), Depth + 1) &&
2878 SignBitIsZeroFP(Op.getOperand(0), Depth + 1);
2879 case ISD::FMAXNUM:
2880 case ISD::FMAXNUM_IEEE:
2881 case ISD::FMAXIMUM:
2882 case ISD::FMAXIMUMNUM:
2883 // TODO: If we can ignore the sign bit of nans, only one side being known 0
2884 // is sufficient.
2885 return SignBitIsZeroFP(Op.getOperand(1), Depth + 1) &&
2886 SignBitIsZeroFP(Op.getOperand(0), Depth + 1);
2887 default:
2888 return false;
2889 }
2890
2891 llvm_unreachable("covered opcode switch");
2892}
2893
2894/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
2895/// this predicate to simplify operations downstream. Mask is known to be zero
2896/// for bits that V cannot have.
2898 unsigned Depth) const {
2899 return Mask.isSubsetOf(computeKnownBits(V, Depth).Zero);
2900}
2901
2902/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero in
2903/// DemandedElts. We use this predicate to simplify operations downstream.
2904/// Mask is known to be zero for bits that V cannot have.
2906 const APInt &DemandedElts,
2907 unsigned Depth) const {
2908 return Mask.isSubsetOf(computeKnownBits(V, DemandedElts, Depth).Zero);
2909}
2910
2911/// MaskedVectorIsZero - Return true if 'Op' is known to be zero in
2912/// DemandedElts. We use this predicate to simplify operations downstream.
2914 unsigned Depth /* = 0 */) const {
2915 return computeKnownBits(V, DemandedElts, Depth).isZero();
2916}
2917
2918/// MaskedValueIsAllOnes - Return true if '(Op & Mask) == Mask'.
2920 unsigned Depth) const {
2921 return Mask.isSubsetOf(computeKnownBits(V, Depth).One);
2922}
2923
2925 const APInt &DemandedElts,
2926 unsigned Depth) const {
2927 EVT VT = Op.getValueType();
2928 assert(VT.isVector() && !VT.isScalableVector() && "Only for fixed vectors!");
2929
2930 unsigned NumElts = VT.getVectorNumElements();
2931 assert(DemandedElts.getBitWidth() == NumElts && "Unexpected demanded mask.");
2932
2933 APInt KnownZeroElements = APInt::getZero(NumElts);
2934 for (unsigned EltIdx = 0; EltIdx != NumElts; ++EltIdx) {
2935 if (!DemandedElts[EltIdx])
2936 continue; // Don't query elements that are not demanded.
2937 APInt Mask = APInt::getOneBitSet(NumElts, EltIdx);
2938 if (MaskedVectorIsZero(Op, Mask, Depth))
2939 KnownZeroElements.setBit(EltIdx);
2940 }
2941 return KnownZeroElements;
2942}
2943
2944/// isSplatValue - Return true if the vector V has the same value
2945/// across all DemandedElts. For scalable vectors, we don't know the
2946/// number of lanes at compile time. Instead, we use a 1 bit APInt
2947/// to represent a conservative value for all lanes; that is, that
2948/// one bit value is implicitly splatted across all lanes.
2949bool SelectionDAG::isSplatValue(SDValue V, const APInt &DemandedElts,
2950 APInt &UndefElts, unsigned Depth) const {
2951 unsigned Opcode = V.getOpcode();
2952 EVT VT = V.getValueType();
2953 assert(VT.isVector() && "Vector type expected");
2954 assert((!VT.isScalableVector() || DemandedElts.getBitWidth() == 1) &&
2955 "scalable demanded bits are ignored");
2956
2957 if (!DemandedElts)
2958 return false; // No demanded elts, better to assume we don't know anything.
2959
2960 if (Depth >= MaxRecursionDepth)
2961 return false; // Limit search depth.
2962
2963 // Deal with some common cases here that work for both fixed and scalable
2964 // vector types.
2965 switch (Opcode) {
2966 case ISD::SPLAT_VECTOR:
2967 UndefElts = V.getOperand(0).isUndef()
2968 ? APInt::getAllOnes(DemandedElts.getBitWidth())
2969 : APInt(DemandedElts.getBitWidth(), 0);
2970 return true;
2971 case ISD::ADD:
2972 case ISD::SUB:
2973 case ISD::AND:
2974 case ISD::XOR:
2975 case ISD::OR: {
2976 APInt UndefLHS, UndefRHS;
2977 SDValue LHS = V.getOperand(0);
2978 SDValue RHS = V.getOperand(1);
2979 // Only recognize splats with the same demanded undef elements for both
2980 // operands, otherwise we might fail to handle binop-specific undef
2981 // handling.
2982 // e.g. (and undef, 0) -> 0 etc.
2983 if (isSplatValue(LHS, DemandedElts, UndefLHS, Depth + 1) &&
2984 isSplatValue(RHS, DemandedElts, UndefRHS, Depth + 1) &&
2985 (DemandedElts & UndefLHS) == (DemandedElts & UndefRHS)) {
2986 UndefElts = UndefLHS | UndefRHS;
2987 return true;
2988 }
2989 return false;
2990 }
2991 case ISD::ABS:
2993 case ISD::TRUNCATE:
2994 case ISD::SIGN_EXTEND:
2995 case ISD::ZERO_EXTEND:
2996 return isSplatValue(V.getOperand(0), DemandedElts, UndefElts, Depth + 1);
2997 default:
2998 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
2999 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID)
3000 return TLI->isSplatValueForTargetNode(V, DemandedElts, UndefElts, *this,
3001 Depth);
3002 break;
3003 }
3004
3005 // We don't support other cases than those above for scalable vectors at
3006 // the moment.
3007 if (VT.isScalableVector())
3008 return false;
3009
3010 unsigned NumElts = VT.getVectorNumElements();
3011 assert(NumElts == DemandedElts.getBitWidth() && "Vector size mismatch");
3012 UndefElts = APInt::getZero(NumElts);
3013
3014 switch (Opcode) {
3015 case ISD::BUILD_VECTOR: {
3016 SDValue Scl;
3017 for (unsigned i = 0; i != NumElts; ++i) {
3018 SDValue Op = V.getOperand(i);
3019 if (Op.isUndef()) {
3020 UndefElts.setBit(i);
3021 continue;
3022 }
3023 if (!DemandedElts[i])
3024 continue;
3025 if (Scl && Scl != Op)
3026 return false;
3027 Scl = Op;
3028 }
3029 return true;
3030 }
3031 case ISD::VECTOR_SHUFFLE: {
3032 // Check if this is a shuffle node doing a splat or a shuffle of a splat.
3033 APInt DemandedLHS = APInt::getZero(NumElts);
3034 APInt DemandedRHS = APInt::getZero(NumElts);
3035 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(V)->getMask();
3036 for (int i = 0; i != (int)NumElts; ++i) {
3037 int M = Mask[i];
3038 if (M < 0) {
3039 UndefElts.setBit(i);
3040 continue;
3041 }
3042 if (!DemandedElts[i])
3043 continue;
3044 if (M < (int)NumElts)
3045 DemandedLHS.setBit(M);
3046 else
3047 DemandedRHS.setBit(M - NumElts);
3048 }
3049
3050 // If we aren't demanding either op, assume there's no splat.
3051 // If we are demanding both ops, assume there's no splat.
3052 if ((DemandedLHS.isZero() && DemandedRHS.isZero()) ||
3053 (!DemandedLHS.isZero() && !DemandedRHS.isZero()))
3054 return false;
3055
3056 // See if the demanded elts of the source op is a splat or we only demand
3057 // one element, which should always be a splat.
3058 // TODO: Handle source ops splats with undefs.
3059 auto CheckSplatSrc = [&](SDValue Src, const APInt &SrcElts) {
3060 APInt SrcUndefs;
3061 return (SrcElts.popcount() == 1) ||
3062 (isSplatValue(Src, SrcElts, SrcUndefs, Depth + 1) &&
3063 (SrcElts & SrcUndefs).isZero());
3064 };
3065 if (!DemandedLHS.isZero())
3066 return CheckSplatSrc(V.getOperand(0), DemandedLHS);
3067 return CheckSplatSrc(V.getOperand(1), DemandedRHS);
3068 }
3070 // Offset the demanded elts by the subvector index.
3071 SDValue Src = V.getOperand(0);
3072 // We don't support scalable vectors at the moment.
3073 if (Src.getValueType().isScalableVector())
3074 return false;
3075 uint64_t Idx = V.getConstantOperandVal(1);
3076 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
3077 APInt UndefSrcElts;
3078 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
3079 if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) {
3080 UndefElts = UndefSrcElts.extractBits(NumElts, Idx);
3081 return true;
3082 }
3083 break;
3084 }
3088 // Widen the demanded elts by the src element count.
3089 SDValue Src = V.getOperand(0);
3090 // We don't support scalable vectors at the moment.
3091 if (Src.getValueType().isScalableVector())
3092 return false;
3093 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
3094 APInt UndefSrcElts;
3095 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts);
3096 if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) {
3097 UndefElts = UndefSrcElts.trunc(NumElts);
3098 return true;
3099 }
3100 break;
3101 }
3102 case ISD::BITCAST: {
3103 SDValue Src = V.getOperand(0);
3104 EVT SrcVT = Src.getValueType();
3105 unsigned SrcBitWidth = SrcVT.getScalarSizeInBits();
3106 unsigned BitWidth = VT.getScalarSizeInBits();
3107
3108 // Ignore bitcasts from unsupported types.
3109 // TODO: Add fp support?
3110 if (!SrcVT.isVector() || !SrcVT.isInteger() || !VT.isInteger())
3111 break;
3112
3113 // Bitcast 'small element' vector to 'large element' vector.
3114 if ((BitWidth % SrcBitWidth) == 0) {
3115 // See if each sub element is a splat.
3116 unsigned Scale = BitWidth / SrcBitWidth;
3117 unsigned NumSrcElts = SrcVT.getVectorNumElements();
3118 APInt ScaledDemandedElts =
3119 APIntOps::ScaleBitMask(DemandedElts, NumSrcElts);
3120 for (unsigned I = 0; I != Scale; ++I) {
3121 APInt SubUndefElts;
3122 APInt SubDemandedElt = APInt::getOneBitSet(Scale, I);
3123 APInt SubDemandedElts = APInt::getSplat(NumSrcElts, SubDemandedElt);
3124 SubDemandedElts &= ScaledDemandedElts;
3125 if (!isSplatValue(Src, SubDemandedElts, SubUndefElts, Depth + 1))
3126 return false;
3127 // TODO: Add support for merging sub undef elements.
3128 if (!SubUndefElts.isZero())
3129 return false;
3130 }
3131 return true;
3132 }
3133 break;
3134 }
3135 }
3136
3137 return false;
3138}
3139
3140/// Helper wrapper to main isSplatValue function.
3141bool SelectionDAG::isSplatValue(SDValue V, bool AllowUndefs) const {
3142 EVT VT = V.getValueType();
3143 assert(VT.isVector() && "Vector type expected");
3144
3145 APInt UndefElts;
3146 // Since the number of lanes in a scalable vector is unknown at compile time,
3147 // we track one bit which is implicitly broadcast to all lanes. This means
3148 // that all lanes in a scalable vector are considered demanded.
3149 APInt DemandedElts
3151 return isSplatValue(V, DemandedElts, UndefElts) &&
3152 (AllowUndefs || !UndefElts);
3153}
3154
3157
3158 EVT VT = V.getValueType();
3159 unsigned Opcode = V.getOpcode();
3160 switch (Opcode) {
3161 default: {
3162 APInt UndefElts;
3163 // Since the number of lanes in a scalable vector is unknown at compile time,
3164 // we track one bit which is implicitly broadcast to all lanes. This means
3165 // that all lanes in a scalable vector are considered demanded.
3166 APInt DemandedElts
3168
3169 if (isSplatValue(V, DemandedElts, UndefElts)) {
3170 if (VT.isScalableVector()) {
3171 // DemandedElts and UndefElts are ignored for scalable vectors, since
3172 // the only supported cases are SPLAT_VECTOR nodes.
3173 SplatIdx = 0;
3174 } else {
3175 // Handle case where all demanded elements are UNDEF.
3176 if (DemandedElts.isSubsetOf(UndefElts)) {
3177 SplatIdx = 0;
3178 return getUNDEF(VT);
3179 }
3180 SplatIdx = (UndefElts & DemandedElts).countr_one();
3181 }
3182 return V;
3183 }
3184 break;
3185 }
3186 case ISD::SPLAT_VECTOR:
3187 SplatIdx = 0;
3188 return V;
3189 case ISD::VECTOR_SHUFFLE: {
3190 assert(!VT.isScalableVector());
3191 // Check if this is a shuffle node doing a splat.
3192 // TODO - remove this and rely purely on SelectionDAG::isSplatValue,
3193 // getTargetVShiftNode currently struggles without the splat source.
3194 auto *SVN = cast<ShuffleVectorSDNode>(V);
3195 if (!SVN->isSplat())
3196 break;
3197 int Idx = SVN->getSplatIndex();
3198 int NumElts = V.getValueType().getVectorNumElements();
3199 SplatIdx = Idx % NumElts;
3200 return V.getOperand(Idx / NumElts);
3201 }
3202 }
3203
3204 return SDValue();
3205}
3206
3208 int SplatIdx;
3209 if (SDValue SrcVector = getSplatSourceVector(V, SplatIdx)) {
3210 EVT SVT = SrcVector.getValueType().getScalarType();
3211 EVT LegalSVT = SVT;
3212 if (LegalTypes && !TLI->isTypeLegal(SVT)) {
3213 if (!SVT.isInteger())
3214 return SDValue();
3215 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
3216 if (LegalSVT.bitsLT(SVT))
3217 return SDValue();
3218 }
3219 return getExtractVectorElt(SDLoc(V), LegalSVT, SrcVector, SplatIdx);
3220 }
3221 return SDValue();
3222}
3223
3224std::optional<ConstantRange>
3226 unsigned Depth) const {
3227 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
3228 V.getOpcode() == ISD::SRA) &&
3229 "Unknown shift node");
3230 // Shifting more than the bitwidth is not valid.
3231 unsigned BitWidth = V.getScalarValueSizeInBits();
3232
3233 if (auto *Cst = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
3234 const APInt &ShAmt = Cst->getAPIntValue();
3235 if (ShAmt.uge(BitWidth))
3236 return std::nullopt;
3237 return ConstantRange(ShAmt);
3238 }
3239
3240 if (auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1))) {
3241 const APInt *MinAmt = nullptr, *MaxAmt = nullptr;
3242 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
3243 if (!DemandedElts[i])
3244 continue;
3245 auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i));
3246 if (!SA) {
3247 MinAmt = MaxAmt = nullptr;
3248 break;
3249 }
3250 const APInt &ShAmt = SA->getAPIntValue();
3251 if (ShAmt.uge(BitWidth))
3252 return std::nullopt;
3253 if (!MinAmt || MinAmt->ugt(ShAmt))
3254 MinAmt = &ShAmt;
3255 if (!MaxAmt || MaxAmt->ult(ShAmt))
3256 MaxAmt = &ShAmt;
3257 }
3258 assert(((!MinAmt && !MaxAmt) || (MinAmt && MaxAmt)) &&
3259 "Failed to find matching min/max shift amounts");
3260 if (MinAmt && MaxAmt)
3261 return ConstantRange(*MinAmt, *MaxAmt + 1);
3262 }
3263
3264 // Use computeKnownBits to find a hidden constant/knownbits (usually type
3265 // legalized). e.g. Hidden behind multiple bitcasts/build_vector/casts etc.
3266 KnownBits KnownAmt = computeKnownBits(V.getOperand(1), DemandedElts, Depth);
3267 if (KnownAmt.getMaxValue().ult(BitWidth))
3268 return ConstantRange::fromKnownBits(KnownAmt, /*IsSigned=*/false);
3269
3270 return std::nullopt;
3271}
3272
3273std::optional<unsigned>
3275 unsigned Depth) const {
3276 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
3277 V.getOpcode() == ISD::SRA) &&
3278 "Unknown shift node");
3279 if (std::optional<ConstantRange> AmtRange =
3280 getValidShiftAmountRange(V, DemandedElts, Depth))
3281 if (const APInt *ShAmt = AmtRange->getSingleElement())
3282 return ShAmt->getZExtValue();
3283 return std::nullopt;
3284}
3285
3286std::optional<unsigned>
3288 APInt DemandedElts = getDemandAllEltsMask(V);
3289 return getValidShiftAmount(V, DemandedElts, Depth);
3290}
3291
3292std::optional<unsigned>
3294 unsigned Depth) const {
3295 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
3296 V.getOpcode() == ISD::SRA) &&
3297 "Unknown shift node");
3298 if (std::optional<ConstantRange> AmtRange =
3299 getValidShiftAmountRange(V, DemandedElts, Depth))
3300 return AmtRange->getUnsignedMin().getZExtValue();
3301 return std::nullopt;
3302}
3303
3304std::optional<unsigned>
3306 APInt DemandedElts = getDemandAllEltsMask(V);
3307 return getValidMinimumShiftAmount(V, DemandedElts, Depth);
3308}
3309
3310std::optional<unsigned>
3312 unsigned Depth) const {
3313 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
3314 V.getOpcode() == ISD::SRA) &&
3315 "Unknown shift node");
3316 if (std::optional<ConstantRange> AmtRange =
3317 getValidShiftAmountRange(V, DemandedElts, Depth))
3318 return AmtRange->getUnsignedMax().getZExtValue();
3319 return std::nullopt;
3320}
3321
3322std::optional<unsigned>
3324 APInt DemandedElts = getDemandAllEltsMask(V);
3325 return getValidMaximumShiftAmount(V, DemandedElts, Depth);
3326}
3327
3328/// Determine which bits of Op are known to be either zero or one and return
3329/// them in Known. For vectors, the known bits are those that are shared by
3330/// every vector element.
3332 APInt DemandedElts = getDemandAllEltsMask(Op);
3333 return computeKnownBits(Op, DemandedElts, Depth);
3334}
3335
3336/// Determine which bits of Op are known to be either zero or one and return
3337/// them in Known. The DemandedElts argument allows us to only collect the known
3338/// bits that are shared by the requested vector elements.
3340 unsigned Depth) const {
3341 unsigned BitWidth = Op.getScalarValueSizeInBits();
3342
3343 KnownBits Known(BitWidth); // Don't know anything.
3344
3345 if (auto OptAPInt = Op->bitcastToAPInt()) {
3346 // We know all of the bits for a constant!
3347 APInt V = *std::move(OptAPInt);
3348
3349 // Swap the low-order and high-order double of a ppc_fp128 when casting to
3350 // i128, see #44482.
3351 //
3352 // A ppc_fp128 is two doubles, with the high-order double stored at the
3353 // lower address. Reading that as an integer therefore puts the high-order
3354 // double in the high 64 bits on big-endian targets and in the low 64 bits
3355 // on little-endian targets.
3356 //
3357 // But APFloat::bitcastToAPInt is endianness-agnostic and always places the
3358 // high-order double in the low 64 bits. Hence the two doubles must be
3359 // flipped on big-endian targets.
3360 if (getDataLayout().isBigEndian() && Op.getValueType() == MVT::ppcf128)
3361 V = V.rotl(64);
3362
3363 return KnownBits::makeConstant(V);
3364 }
3365
3366 if (Depth >= MaxRecursionDepth)
3367 return Known; // Limit search depth.
3368
3369 KnownBits Known2;
3370 unsigned NumElts = DemandedElts.getBitWidth();
3371 assert((!Op.getValueType().isScalableVector() || NumElts == 1) &&
3372 "DemandedElts for scalable vectors must be 1 to represent all lanes");
3373 assert((!Op.getValueType().isFixedLengthVector() ||
3374 NumElts == Op.getValueType().getVectorNumElements()) &&
3375 "Unexpected vector size");
3376
3377 if (!DemandedElts)
3378 return Known; // No demanded elts, better to assume we don't know anything.
3379
3380 unsigned Opcode = Op.getOpcode();
3381 switch (Opcode) {
3382 case ISD::FREEZE: {
3383 if (isGuaranteedNotToBeUndefOrPoison(Op.getOperand(0), DemandedElts,
3385 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3386 break;
3387 }
3388 case ISD::MERGE_VALUES:
3389 return computeKnownBits(Op.getOperand(Op.getResNo()), DemandedElts,
3390 Depth + 1);
3391 case ISD::SPLAT_VECTOR: {
3392 SDValue SrcOp = Op.getOperand(0);
3393 assert(SrcOp.getValueSizeInBits() >= BitWidth &&
3394 "Expected SPLAT_VECTOR implicit truncation");
3395 // Implicitly truncate the bits to match the official semantics of
3396 // SPLAT_VECTOR.
3398 break;
3399 }
3401 unsigned ScalarSize = Op.getOperand(0).getScalarValueSizeInBits();
3402 assert(ScalarSize * Op.getNumOperands() == BitWidth &&
3403 "Expected SPLAT_VECTOR_PARTS scalars to cover element width");
3404 for (auto [I, SrcOp] : enumerate(Op->ops())) {
3405 Known.insertBits(computeKnownBits(SrcOp, Depth + 1), ScalarSize * I);
3406 }
3407 break;
3408 }
3409 case ISD::STEP_VECTOR: {
3410 const APInt &Step = Op.getConstantOperandAPInt(0);
3411
3412 if (Step.isPowerOf2())
3413 Known.Zero.setLowBits(Step.logBase2());
3414
3416
3417 if (!isUIntN(BitWidth, Op.getValueType().getVectorMinNumElements()))
3418 break;
3419 const APInt MinNumElts =
3420 APInt(BitWidth, Op.getValueType().getVectorMinNumElements());
3421
3422 bool Overflow;
3423 const APInt MaxNumElts = getVScaleRange(&F, BitWidth)
3425 .umul_ov(MinNumElts, Overflow);
3426 if (Overflow)
3427 break;
3428
3429 const APInt MaxValue = (MaxNumElts - 1).umul_ov(Step, Overflow);
3430 if (Overflow)
3431 break;
3432
3433 Known.Zero.setHighBits(MaxValue.countl_zero());
3434 break;
3435 }
3436 case ISD::BUILD_VECTOR:
3437 assert(!Op.getValueType().isScalableVector());
3438 // Collect the known bits that are shared by every demanded vector element.
3439 Known.setAllConflict();
3440 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
3441 if (!DemandedElts[i])
3442 continue;
3443
3444 SDValue SrcOp = Op.getOperand(i);
3445 if (SrcOp.getOpcode() == ISD::POISON)
3446 continue;
3447
3448 Known2 = computeKnownBits(SrcOp, Depth + 1);
3449
3450 // BUILD_VECTOR can implicitly truncate sources, we must handle this.
3451 if (SrcOp.getValueSizeInBits() != BitWidth) {
3452 assert(SrcOp.getValueSizeInBits() > BitWidth &&
3453 "Expected BUILD_VECTOR implicit truncation");
3454 Known2 = Known2.trunc(BitWidth);
3455 }
3456
3457 // Known bits are the values that are shared by every demanded element.
3458 Known = Known.intersectWith(Known2);
3459
3460 // If we don't know any bits, early out.
3461 if (Known.isUnknown())
3462 break;
3463 }
3464
3465 // If every demanded element was poison, we know nothing.
3466 if (Known.hasConflict())
3467 Known.resetAll();
3468 break;
3469 case ISD::VECTOR_COMPRESS: {
3470 SDValue Vec = Op.getOperand(0);
3471 SDValue PassThru = Op.getOperand(2);
3472 Known = computeKnownBits(PassThru, DemandedElts, Depth + 1);
3473 // If we don't know any bits, early out.
3474 if (Known.isUnknown())
3475 break;
3476 Known2 = computeKnownBits(Vec, Depth + 1);
3477 Known = Known.intersectWith(Known2);
3478 break;
3479 }
3480 case ISD::VECTOR_SHUFFLE: {
3481 assert(!Op.getValueType().isScalableVector());
3482 // Collect the known bits that are shared by every vector element referenced
3483 // by the shuffle.
3484 APInt DemandedLHS, DemandedRHS;
3486 assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
3487 if (!getShuffleDemandedElts(NumElts, SVN->getMask(), DemandedElts,
3488 DemandedLHS, DemandedRHS))
3489 break;
3490
3491 // Known bits are the values that are shared by every demanded element.
3492 Known.setAllConflict();
3493 if (!!DemandedLHS) {
3494 SDValue LHS = Op.getOperand(0);
3495 Known2 = computeKnownBits(LHS, DemandedLHS, Depth + 1);
3496 Known = Known.intersectWith(Known2);
3497 }
3498 // If we don't know any bits, early out.
3499 if (Known.isUnknown())
3500 break;
3501 if (!!DemandedRHS) {
3502 SDValue RHS = Op.getOperand(1);
3503 Known2 = computeKnownBits(RHS, DemandedRHS, Depth + 1);
3504 Known = Known.intersectWith(Known2);
3505 }
3506 break;
3507 }
3508 case ISD::VSCALE: {
3510 const APInt &Multiplier = Op.getConstantOperandAPInt(0);
3512 break;
3513 }
3514 case ISD::CONCAT_VECTORS: {
3515 if (Op.getValueType().isScalableVector())
3516 break;
3517 // Split DemandedElts and test each of the demanded subvectors.
3518 Known.setAllConflict();
3519 EVT SubVectorVT = Op.getOperand(0).getValueType();
3520 unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
3521 unsigned NumSubVectors = Op.getNumOperands();
3522 for (unsigned i = 0; i != NumSubVectors; ++i) {
3523 APInt DemandedSub =
3524 DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts);
3525 if (!!DemandedSub) {
3526 SDValue Sub = Op.getOperand(i);
3527 Known2 = computeKnownBits(Sub, DemandedSub, Depth + 1);
3528 Known = Known.intersectWith(Known2);
3529 }
3530 // If we don't know any bits, early out.
3531 if (Known.isUnknown())
3532 break;
3533 }
3534 break;
3535 }
3536 case ISD::INSERT_SUBVECTOR: {
3537 if (Op.getValueType().isScalableVector())
3538 break;
3539 // Demand any elements from the subvector and the remainder from the src its
3540 // inserted into.
3541 SDValue Src = Op.getOperand(0);
3542 SDValue Sub = Op.getOperand(1);
3543 uint64_t Idx = Op.getConstantOperandVal(2);
3544 unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
3545 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
3546 APInt DemandedSrcElts = DemandedElts;
3547 DemandedSrcElts.clearBits(Idx, Idx + NumSubElts);
3548
3549 Known.setAllConflict();
3550 if (!!DemandedSubElts) {
3551 Known = computeKnownBits(Sub, DemandedSubElts, Depth + 1);
3552 if (Known.isUnknown())
3553 break; // early-out.
3554 }
3555 if (!!DemandedSrcElts) {
3556 Known2 = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
3557 Known = Known.intersectWith(Known2);
3558 }
3559 break;
3560 }
3562 // Offset the demanded elts by the subvector index.
3563 SDValue Src = Op.getOperand(0);
3564
3565 APInt DemandedSrcElts;
3566 if (Src.getValueType().isScalableVector())
3567 DemandedSrcElts = APInt(1, 1); // <=> 'demand all elements'
3568 else {
3569 uint64_t Idx = Op.getConstantOperandVal(1);
3570 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
3571 DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
3572 }
3573 Known = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
3574 break;
3575 }
3576 case ISD::SCALAR_TO_VECTOR: {
3577 if (Op.getValueType().isScalableVector())
3578 break;
3579 // We know about scalar_to_vector as much as we know about it source,
3580 // which becomes the first element of otherwise unknown vector.
3581 if (DemandedElts != 1)
3582 break;
3583
3584 SDValue N0 = Op.getOperand(0);
3585 Known = computeKnownBits(N0, Depth + 1);
3586 if (N0.getValueSizeInBits() != BitWidth)
3587 Known = Known.trunc(BitWidth);
3588
3589 break;
3590 }
3591 case ISD::BITCAST: {
3592 if (Op.getValueType().isScalableVector())
3593 break;
3594
3595 SDValue N0 = Op.getOperand(0);
3596 EVT SubVT = N0.getValueType();
3597 unsigned SubBitWidth = SubVT.getScalarSizeInBits();
3598
3599 // Ignore bitcasts from unsupported types.
3600 if (!(SubVT.isInteger() || SubVT.isFloatingPoint()))
3601 break;
3602
3603 // Fast handling of 'identity' bitcasts.
3604 if (BitWidth == SubBitWidth) {
3605 Known = computeKnownBits(N0, DemandedElts, Depth + 1);
3606 break;
3607 }
3608
3609 bool IsLE = getDataLayout().isLittleEndian();
3610
3611 // Bitcast 'small element' vector to 'large element' scalar/vector.
3612 if ((BitWidth % SubBitWidth) == 0) {
3613 assert(N0.getValueType().isVector() && "Expected bitcast from vector");
3614
3615 // Collect known bits for the (larger) output by collecting the known
3616 // bits from each set of sub elements and shift these into place.
3617 // We need to separately call computeKnownBits for each set of
3618 // sub elements as the knownbits for each is likely to be different.
3619 unsigned SubScale = BitWidth / SubBitWidth;
3620 APInt SubDemandedElts(NumElts * SubScale, 0);
3621 for (unsigned i = 0; i != NumElts; ++i)
3622 if (DemandedElts[i])
3623 SubDemandedElts.setBit(i * SubScale);
3624
3625 for (unsigned i = 0; i != SubScale; ++i) {
3626 Known2 = computeKnownBits(N0, SubDemandedElts.shl(i),
3627 Depth + 1);
3628 unsigned Shifts = IsLE ? i : SubScale - 1 - i;
3629 Known.insertBits(Known2, SubBitWidth * Shifts);
3630 }
3631 }
3632
3633 // Bitcast 'large element' scalar/vector to 'small element' vector.
3634 if ((SubBitWidth % BitWidth) == 0) {
3635 assert(Op.getValueType().isVector() && "Expected bitcast to vector");
3636
3637 // Collect known bits for the (smaller) output by collecting the known
3638 // bits from the overlapping larger input elements and extracting the
3639 // sub sections we actually care about.
3640 unsigned SubScale = SubBitWidth / BitWidth;
3641 APInt SubDemandedElts =
3642 APIntOps::ScaleBitMask(DemandedElts, NumElts / SubScale);
3643 Known2 = computeKnownBits(N0, SubDemandedElts, Depth + 1);
3644
3645 Known.setAllConflict();
3646 for (unsigned i = 0; i != NumElts; ++i)
3647 if (DemandedElts[i]) {
3648 unsigned Shifts = IsLE ? i : NumElts - 1 - i;
3649 unsigned Offset = (Shifts % SubScale) * BitWidth;
3650 Known = Known.intersectWith(Known2.extractBits(BitWidth, Offset));
3651 // If we don't know any bits, early out.
3652 if (Known.isUnknown())
3653 break;
3654 }
3655 }
3656 break;
3657 }
3658 case ISD::AND:
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::OR:
3665 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3666 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3667
3668 Known |= Known2;
3669 break;
3670 case ISD::XOR:
3671 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3672 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3673
3674 Known ^= Known2;
3675 break;
3676 case ISD::MUL: {
3677 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3678 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3679 bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1);
3680 // TODO: SelfMultiply can be poison, but not undef.
3681 if (SelfMultiply)
3682 SelfMultiply &= isGuaranteedNotToBeUndefOrPoison(
3683 Op.getOperand(0), DemandedElts, UndefPoisonKind::UndefOrPoison,
3684 Depth + 1);
3685 Known = KnownBits::mul(Known, Known2, SelfMultiply);
3686
3687 // If the multiplication is known not to overflow, the product of a number
3688 // with itself is non-negative. Only do this if we didn't already computed
3689 // the opposite value for the sign bit.
3690 if (Op->getFlags().hasNoSignedWrap() &&
3691 Op.getOperand(0) == Op.getOperand(1) &&
3692 !Known.isNegative())
3693 Known.makeNonNegative();
3694 break;
3695 }
3696 case ISD::MULHU: {
3697 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3698 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3699 Known = KnownBits::mulhu(Known, Known2);
3700 break;
3701 }
3702 case ISD::MULHS: {
3703 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3704 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3705 Known = KnownBits::mulhs(Known, Known2);
3706 break;
3707 }
3708 case ISD::ABDU: {
3709 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3710 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3711 Known = KnownBits::abdu(Known, Known2);
3712 break;
3713 }
3714 case ISD::ABDS: {
3715 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3716 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3717 Known = KnownBits::abds(Known, Known2);
3718 unsigned SignBits1 =
3719 ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
3720 if (SignBits1 == 1)
3721 break;
3722 unsigned SignBits0 =
3723 ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3724 Known.Zero.setHighBits(std::min(SignBits0, SignBits1) - 1);
3725 break;
3726 }
3727 case ISD::UMUL_LOHI: {
3728 assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3729 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3730 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3731 bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1);
3732 if (Op.getResNo() == 0)
3733 Known = KnownBits::mul(Known, Known2, SelfMultiply);
3734 else
3735 Known = KnownBits::mulhu(Known, Known2);
3736 break;
3737 }
3738 case ISD::SMUL_LOHI: {
3739 assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3740 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3741 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3742 bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1);
3743 if (Op.getResNo() == 0)
3744 Known = KnownBits::mul(Known, Known2, SelfMultiply);
3745 else
3746 Known = KnownBits::mulhs(Known, Known2);
3747 break;
3748 }
3749 case ISD::AVGFLOORU: {
3750 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3751 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3752 Known = KnownBits::avgFloorU(Known, Known2);
3753 break;
3754 }
3755 case ISD::AVGCEILU: {
3756 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3757 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3758 Known = KnownBits::avgCeilU(Known, Known2);
3759 break;
3760 }
3761 case ISD::AVGFLOORS: {
3762 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3763 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3764 Known = KnownBits::avgFloorS(Known, Known2);
3765 break;
3766 }
3767 case ISD::AVGCEILS: {
3768 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3769 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3770 Known = KnownBits::avgCeilS(Known, Known2);
3771 break;
3772 }
3773 case ISD::AVGSUBFLOORU:
3774 case ISD::AVGSUBFLOORS: {
3775 bool IsSigned = Op.getOpcode() == ISD::AVGSUBFLOORS;
3776 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3777 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3778 // Subtract in i[N+1] so the difference can't overflow, then halve.
3779 Known = IsSigned ? Known.sext(BitWidth + 1) : Known.zext(BitWidth + 1);
3780 Known2 = IsSigned ? Known2.sext(BitWidth + 1) : Known2.zext(BitWidth + 1);
3781 Known = KnownBits::sub(Known, Known2);
3782 // The shifted in top bit is unknown, but it is truncated away.
3783 Known >>= 1;
3784 Known = Known.trunc(BitWidth);
3785 break;
3786 }
3787 case ISD::SELECT:
3788 case ISD::VSELECT:
3789 Known = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
3790 // If we don't know any bits, early out.
3791 if (Known.isUnknown())
3792 break;
3793 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth+1);
3794
3795 // Only known if known in both the LHS and RHS.
3796 Known = Known.intersectWith(Known2);
3797 break;
3798 case ISD::SELECT_CC:
3799 Known = computeKnownBits(Op.getOperand(3), DemandedElts, Depth+1);
3800 // If we don't know any bits, early out.
3801 if (Known.isUnknown())
3802 break;
3803 Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
3804
3805 // Only known if known in both the LHS and RHS.
3806 Known = Known.intersectWith(Known2);
3807 break;
3808 case ISD::SMULO:
3809 case ISD::UMULO:
3810 if (Op.getResNo() != 1)
3811 break;
3812 // The boolean result conforms to getBooleanContents.
3813 // If we know the result of a setcc has the top bits zero, use this info.
3814 // We know that we have an integer-based boolean since these operations
3815 // are only available for integer.
3816 if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
3818 BitWidth > 1)
3819 Known.Zero.setBitsFrom(1);
3820 break;
3821 case ISD::SETCC:
3822 case ISD::SETCCCARRY:
3823 case ISD::STRICT_FSETCC:
3824 case ISD::STRICT_FSETCCS: {
3825 unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
3826 // If we know the result of a setcc has the top bits zero, use this info.
3827 if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
3829 BitWidth > 1)
3830 Known.Zero.setBitsFrom(1);
3831 break;
3832 }
3833 case ISD::SHL: {
3834 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3835 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3836
3837 bool NUW = Op->getFlags().hasNoUnsignedWrap();
3838 bool NSW = Op->getFlags().hasNoSignedWrap();
3839
3840 bool ShAmtNonZero = Known2.isNonZero();
3841
3842 Known = KnownBits::shl(Known, Known2, NUW, NSW, ShAmtNonZero);
3843
3844 // Minimum shift low bits are known zero.
3845 if (std::optional<unsigned> ShMinAmt =
3846 getValidMinimumShiftAmount(Op, DemandedElts, Depth + 1))
3847 Known.Zero.setLowBits(*ShMinAmt);
3848 break;
3849 }
3850 case ISD::SRL:
3851 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3852 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3853 Known = KnownBits::lshr(Known, Known2, /*ShAmtNonZero=*/false,
3854 Op->getFlags().hasExact());
3855
3856 // Minimum shift high bits are known zero.
3857 if (std::optional<unsigned> ShMinAmt =
3858 getValidMinimumShiftAmount(Op, DemandedElts, Depth + 1))
3859 Known.Zero.setHighBits(*ShMinAmt);
3860 break;
3861 case ISD::SRA:
3862 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3863 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3864 Known = KnownBits::ashr(Known, Known2, /*ShAmtNonZero=*/false,
3865 Op->getFlags().hasExact());
3866 break;
3867 case ISD::ROTL:
3868 case ISD::ROTR:
3869 if (ConstantSDNode *C =
3870 isConstOrConstSplat(Op.getOperand(1), DemandedElts)) {
3871 unsigned Amt = C->getAPIntValue().urem(BitWidth);
3872
3873 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3874
3875 // Canonicalize to ROTR.
3876 if (Opcode == ISD::ROTL && Amt != 0)
3877 Amt = BitWidth - Amt;
3878
3879 Known.Zero = Known.Zero.rotr(Amt);
3880 Known.One = Known.One.rotr(Amt);
3881 }
3882 break;
3883 case ISD::FSHL:
3884 case ISD::FSHR:
3885 if (ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(2), DemandedElts)) {
3886 unsigned Amt = C->getAPIntValue().urem(BitWidth);
3887
3888 // For fshl, 0-shift returns the 1st arg.
3889 // For fshr, 0-shift returns the 2nd arg.
3890 if (Amt == 0) {
3891 Known = computeKnownBits(Op.getOperand(Opcode == ISD::FSHL ? 0 : 1),
3892 DemandedElts, Depth + 1);
3893 break;
3894 }
3895
3896 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
3897 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
3898 const APInt ShAmt(BitWidth, Amt);
3899 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3900 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3901 Known = Opcode == ISD::FSHL ? KnownBits::fshl(Known, Known2, ShAmt)
3902 : KnownBits::fshr(Known, Known2, ShAmt);
3903 }
3904 break;
3905 case ISD::SHL_PARTS:
3906 case ISD::SRA_PARTS:
3907 case ISD::SRL_PARTS: {
3908 assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3909
3910 // Collect lo/hi source values and concatenate.
3911 unsigned LoBits = Op.getOperand(0).getScalarValueSizeInBits();
3912 unsigned HiBits = Op.getOperand(1).getScalarValueSizeInBits();
3913 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3914 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3915 Known = Known2.concat(Known);
3916
3917 // Collect shift amount.
3918 Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1);
3919
3920 if (Opcode == ISD::SHL_PARTS)
3921 Known = KnownBits::shl(Known, Known2);
3922 else if (Opcode == ISD::SRA_PARTS)
3923 Known = KnownBits::ashr(Known, Known2);
3924 else // if (Opcode == ISD::SRL_PARTS)
3925 Known = KnownBits::lshr(Known, Known2);
3926
3927 // TODO: Minimum shift low/high bits are known zero.
3928
3929 if (Op.getResNo() == 0)
3930 Known = Known.extractBits(LoBits, 0);
3931 else
3932 Known = Known.extractBits(HiBits, LoBits);
3933 break;
3934 }
3936 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3937 EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3938 Known = Known.sextInReg(EVT.getScalarSizeInBits());
3939 break;
3940 }
3941 case ISD::CTTZ:
3942 case ISD::CTTZ_ZERO_POISON: {
3943 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3944 // If we have a known 1, its position is our upper bound.
3945 unsigned PossibleTZ = Known2.countMaxTrailingZeros();
3946 unsigned LowBits = llvm::bit_width(PossibleTZ);
3947 Known.Zero.setBitsFrom(LowBits);
3948 break;
3949 }
3950 case ISD::CTLZ:
3951 case ISD::CTLZ_ZERO_POISON: {
3952 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3953 // If we have a known 1, its position is our upper bound.
3954 unsigned PossibleLZ = Known2.countMaxLeadingZeros();
3955 unsigned LowBits = llvm::bit_width(PossibleLZ);
3956 Known.Zero.setBitsFrom(LowBits);
3957 break;
3958 }
3959 case ISD::CTLS: {
3960 unsigned MinRedundantSignBits =
3961 ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1) - 1;
3962 ConstantRange Range(APInt(BitWidth, MinRedundantSignBits),
3964 Known = Range.toKnownBits();
3965 break;
3966 }
3967 case ISD::CTPOP: {
3968 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3969 // If we know some of the bits are zero, they can't be one.
3970 unsigned PossibleOnes = Known2.countMaxPopulation();
3971 Known.Zero.setBitsFrom(llvm::bit_width(PossibleOnes));
3972 break;
3973 }
3974 case ISD::PARITY: {
3975 // Parity returns 0 everywhere but the LSB.
3976 Known.Zero.setBitsFrom(1);
3977 break;
3978 }
3979 case ISD::PDEP: {
3980 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3981 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3982 Known = KnownBits::pdep(Known2, Known);
3983 break;
3984 }
3985 case ISD::PEXT: {
3986 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3987 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3988 Known = KnownBits::pext(Known2, Known);
3989 break;
3990 }
3991 case ISD::CLMUL: {
3992 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3993 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3994 Known = KnownBits::clmul(Known, Known2);
3995 break;
3996 }
3997 case ISD::MGATHER:
3998 case ISD::MLOAD: {
3999 ISD::LoadExtType ETy =
4000 (Opcode == ISD::MGATHER)
4001 ? cast<MaskedGatherSDNode>(Op)->getExtensionType()
4002 : cast<MaskedLoadSDNode>(Op)->getExtensionType();
4003 if (ETy == ISD::ZEXTLOAD) {
4004 EVT MemVT = cast<MemSDNode>(Op)->getMemoryVT();
4005 KnownBits Known0(MemVT.getScalarSizeInBits());
4006 return Known0.zext(BitWidth);
4007 }
4008 break;
4009 }
4010 case ISD::LOAD: {
4012 const Constant *Cst = TLI->getTargetConstantFromLoad(LD);
4013 if (ISD::isNON_EXTLoad(LD) && Cst) {
4014 // Determine any common known bits from the loaded constant pool value.
4015 Type *CstTy = Cst->getType();
4016 if ((NumElts * BitWidth) == CstTy->getPrimitiveSizeInBits() &&
4017 !Op.getValueType().isScalableVector()) {
4018 // If its a vector splat, then we can (quickly) reuse the scalar path.
4019 // NOTE: We assume all elements match and none are UNDEF.
4020 if (CstTy->isVectorTy()) {
4021 if (const Constant *Splat = Cst->getSplatValue()) {
4022 Cst = Splat;
4023 CstTy = Cst->getType();
4024 }
4025 }
4026 // TODO - do we need to handle different bitwidths?
4027 if (CstTy->isVectorTy() && BitWidth == CstTy->getScalarSizeInBits()) {
4028 // Iterate across all vector elements finding common known bits.
4029 Known.setAllConflict();
4030 for (unsigned i = 0; i != NumElts; ++i) {
4031 if (!DemandedElts[i])
4032 continue;
4033 if (Constant *Elt = Cst->getAggregateElement(i)) {
4034 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
4035 const APInt &Value = CInt->getValue();
4036 Known.One &= Value;
4037 Known.Zero &= ~Value;
4038 continue;
4039 }
4040 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
4041 APInt Value = CFP->getValueAPF().bitcastToAPInt();
4042 Known.One &= Value;
4043 Known.Zero &= ~Value;
4044 continue;
4045 }
4046 }
4047 Known.One.clearAllBits();
4048 Known.Zero.clearAllBits();
4049 break;
4050 }
4051 } else if (BitWidth == CstTy->getPrimitiveSizeInBits()) {
4052 if (auto *CInt = dyn_cast<ConstantInt>(Cst)) {
4053 Known = KnownBits::makeConstant(CInt->getValue());
4054 } else if (auto *CFP = dyn_cast<ConstantFP>(Cst)) {
4055 Known =
4056 KnownBits::makeConstant(CFP->getValueAPF().bitcastToAPInt());
4057 }
4058 }
4059 }
4060 } else if (Op.getResNo() == 0) {
4061 unsigned ScalarMemorySize = LD->getMemoryVT().getScalarSizeInBits();
4062 KnownBits KnownScalarMemory(ScalarMemorySize);
4063 if (const MDNode *MD = LD->getRanges())
4064 computeKnownBitsFromRangeMetadata(*MD, KnownScalarMemory);
4065
4066 // Extend the Known bits from memory to the size of the scalar result.
4067 if (ISD::isZEXTLoad(Op.getNode()))
4068 Known = KnownScalarMemory.zext(BitWidth);
4069 else if (ISD::isSEXTLoad(Op.getNode()))
4070 Known = KnownScalarMemory.sext(BitWidth);
4071 else if (ISD::isEXTLoad(Op.getNode()))
4072 Known = KnownScalarMemory.anyext(BitWidth);
4073 else
4074 Known = KnownScalarMemory;
4075 assert(Known.getBitWidth() == BitWidth);
4076 return Known;
4077 }
4078 break;
4079 }
4081 if (Op.getValueType().isScalableVector())
4082 break;
4083 EVT InVT = Op.getOperand(0).getValueType();
4084 APInt InDemandedElts = DemandedElts.zext(InVT.getVectorNumElements());
4085 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
4086 Known = Known.zext(BitWidth);
4087 break;
4088 }
4089 case ISD::ZERO_EXTEND: {
4090 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4091 Known = Known.zext(BitWidth);
4092 break;
4093 }
4095 if (Op.getValueType().isScalableVector())
4096 break;
4097 EVT InVT = Op.getOperand(0).getValueType();
4098 APInt InDemandedElts = DemandedElts.zext(InVT.getVectorNumElements());
4099 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
4100 // If the sign bit is known to be zero or one, then sext will extend
4101 // it to the top bits, else it will just zext.
4102 Known = Known.sext(BitWidth);
4103 break;
4104 }
4105 case ISD::SIGN_EXTEND: {
4106 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4107 // If the sign bit is known to be zero or one, then sext will extend
4108 // it to the top bits, else it will just zext.
4109 Known = Known.sext(BitWidth);
4110 break;
4111 }
4113 if (Op.getValueType().isScalableVector())
4114 break;
4115 EVT InVT = Op.getOperand(0).getValueType();
4116 APInt InDemandedElts = DemandedElts.zext(InVT.getVectorNumElements());
4117 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
4118 Known = Known.anyext(BitWidth);
4119 break;
4120 }
4121 case ISD::ANY_EXTEND: {
4122 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4123 Known = Known.anyext(BitWidth);
4124 break;
4125 }
4126 case ISD::TRUNCATE: {
4127 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4128 Known = Known.trunc(BitWidth);
4129 break;
4130 }
4131 case ISD::TRUNCATE_SSAT_S: {
4132 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4133 Known = Known.truncSSat(BitWidth);
4134 break;
4135 }
4136 case ISD::TRUNCATE_SSAT_U: {
4137 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4138 Known = Known.truncSSatU(BitWidth);
4139 break;
4140 }
4141 case ISD::TRUNCATE_USAT_U: {
4142 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4143 Known = Known.truncUSat(BitWidth);
4144 break;
4145 }
4146 case ISD::AssertZext: {
4147 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
4149 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4150 Known.Zero |= (~InMask);
4151 Known.One &= (~Known.Zero);
4152 break;
4153 }
4154 case ISD::AssertAlign: {
4155 unsigned LogOfAlign = Log2(cast<AssertAlignSDNode>(Op)->getAlign());
4156 assert(LogOfAlign != 0);
4157
4158 // TODO: Should use maximum with source
4159 // If a node is guaranteed to be aligned, set low zero bits accordingly as
4160 // well as clearing one bits.
4161 Known.Zero.setLowBits(LogOfAlign);
4162 Known.One.clearLowBits(LogOfAlign);
4163 break;
4164 }
4165 case ISD::AssertNoFPClass: {
4166 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4167
4168 FPClassTest NoFPClass =
4169 static_cast<FPClassTest>(Op.getConstantOperandVal(1));
4170 const FPClassTest NegativeTestMask = fcNan | fcNegative;
4171 if ((NoFPClass & NegativeTestMask) == NegativeTestMask) {
4172 // Cannot be negative.
4173 Known.makeNonNegative();
4174 }
4175
4176 const FPClassTest PositiveTestMask = fcNan | fcPositive;
4177 if ((NoFPClass & PositiveTestMask) == PositiveTestMask) {
4178 // Cannot be positive.
4179 Known.makeNegative();
4180 }
4181
4182 break;
4183 }
4184 case ISD::FABS:
4185 // fabs clears the sign bit
4186 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4187 Known.Zero.setSignBit();
4188 Known.One.clearSignBit();
4189 break;
4190 case ISD::FGETSIGN:
4191 // All bits are zero except the low bit.
4192 Known.Zero.setBitsFrom(1);
4193 break;
4194 case ISD::ADD: {
4195 SDNodeFlags Flags = Op.getNode()->getFlags();
4196 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4197 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4198 bool SelfAdd = Op.getOperand(0) == Op.getOperand(1) &&
4200 Op.getOperand(0), DemandedElts,
4202 Known = KnownBits::add(Known, Known2, Flags.hasNoSignedWrap(),
4203 Flags.hasNoUnsignedWrap(), SelfAdd);
4204 break;
4205 }
4206 case ISD::SUB: {
4207 SDNodeFlags Flags = Op.getNode()->getFlags();
4208 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4209 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4210 Known = KnownBits::sub(Known, Known2, Flags.hasNoSignedWrap(),
4211 Flags.hasNoUnsignedWrap());
4212 break;
4213 }
4214 case ISD::USUBO:
4215 case ISD::SSUBO:
4216 case ISD::USUBO_CARRY:
4217 case ISD::SSUBO_CARRY:
4218 if (Op.getResNo() == 1) {
4219 // If we know the result of a setcc has the top bits zero, use this info.
4220 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
4222 BitWidth > 1)
4223 Known.Zero.setBitsFrom(1);
4224 break;
4225 }
4226 [[fallthrough]];
4227 case ISD::SUBC: {
4228 assert(Op.getResNo() == 0 &&
4229 "We only compute knownbits for the difference here.");
4230
4231 // With USUBO_CARRY and SSUBO_CARRY a borrow bit may be added in.
4232 KnownBits Borrow(1);
4233 if (Opcode == ISD::USUBO_CARRY || Opcode == ISD::SSUBO_CARRY) {
4234 Borrow = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1);
4235 // Borrow has bit width 1
4236 Borrow = Borrow.trunc(1);
4237 } else {
4238 Borrow.setAllZero();
4239 }
4240
4241 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4242 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4243 Known = KnownBits::computeForSubBorrow(Known, Known2, Borrow);
4244 break;
4245 }
4246 case ISD::UADDO:
4247 case ISD::SADDO:
4248 case ISD::UADDO_CARRY:
4249 case ISD::SADDO_CARRY:
4250 if (Op.getResNo() == 1) {
4251 // If we know the result of a setcc has the top bits zero, use this info.
4252 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
4254 BitWidth > 1)
4255 Known.Zero.setBitsFrom(1);
4256 break;
4257 }
4258 [[fallthrough]];
4259 case ISD::ADDC:
4260 case ISD::ADDE: {
4261 assert(Op.getResNo() == 0 && "We only compute knownbits for the sum here.");
4262
4263 // With ADDE and UADDO_CARRY, a carry bit may be added in.
4264 KnownBits Carry(1);
4265 if (Opcode == ISD::ADDE)
4266 // Can't track carry from glue, set carry to unknown.
4267 Carry.resetAll();
4268 else if (Opcode == ISD::UADDO_CARRY || Opcode == ISD::SADDO_CARRY) {
4269 Carry = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1);
4270 // Carry has bit width 1
4271 Carry = Carry.trunc(1);
4272 } else {
4273 Carry.setAllZero();
4274 }
4275
4276 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4277 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4278 Known = KnownBits::computeForAddCarry(Known, Known2, Carry);
4279 break;
4280 }
4281 case ISD::UDIV: {
4282 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4283 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4284 Known = KnownBits::udiv(Known, Known2, Op->getFlags().hasExact());
4285 break;
4286 }
4287 case ISD::SDIV: {
4288 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4289 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4290 Known = KnownBits::sdiv(Known, Known2, Op->getFlags().hasExact());
4291 break;
4292 }
4293 case ISD::SREM: {
4294 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4295 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4296 Known = KnownBits::srem(Known, Known2);
4297 break;
4298 }
4299 case ISD::UREM: {
4300 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4301 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4302 Known = KnownBits::urem(Known, Known2);
4303 break;
4304 }
4305 case ISD::EXTRACT_ELEMENT: {
4306 Known = computeKnownBits(Op.getOperand(0), Depth+1);
4307 const unsigned Index = Op.getConstantOperandVal(1);
4308 const unsigned EltBitWidth = Op.getValueSizeInBits();
4309
4310 Known = Known.extractBits(EltBitWidth, Index * EltBitWidth);
4311 break;
4312 }
4314 SDValue InVec = Op.getOperand(0);
4315 SDValue EltNo = Op.getOperand(1);
4316 EVT VecVT = InVec.getValueType();
4317 // computeKnownBits not yet implemented for scalable vectors.
4318 if (VecVT.isScalableVector())
4319 break;
4320 const unsigned EltBitWidth = VecVT.getScalarSizeInBits();
4321 const unsigned NumSrcElts = VecVT.getVectorNumElements();
4322
4323 // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know
4324 // anything about the extended bits.
4325 if (BitWidth > EltBitWidth)
4326 Known = Known.trunc(EltBitWidth);
4327
4328 // If we know the element index, just demand that vector element, else for
4329 // an unknown element index, ignore DemandedElts and demand them all.
4330 APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
4331 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
4332 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
4333 DemandedSrcElts =
4334 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
4335
4336 Known = computeKnownBits(InVec, DemandedSrcElts, Depth + 1);
4337 if (BitWidth > EltBitWidth)
4338 Known = Known.anyext(BitWidth);
4339 break;
4340 }
4341 case ISD::BUILD_PAIR: {
4342 // Operand 0 is the low half and operand 1 the high half,
4343 // KnownBits::concat places its argument in the low bits.
4344 Known = computeKnownBits(Op.getOperand(0), Depth + 1);
4345 Known2 = computeKnownBits(Op.getOperand(1), Depth + 1);
4346 Known = Known2.concat(Known);
4347 break;
4348 }
4350 if (Op.getValueType().isScalableVector())
4351 break;
4352
4353 // If we know the element index, split the demand between the
4354 // source vector and the inserted element, otherwise assume we need
4355 // the original demanded vector elements and the value.
4356 SDValue InVec = Op.getOperand(0);
4357 SDValue InVal = Op.getOperand(1);
4358 SDValue EltNo = Op.getOperand(2);
4359 bool DemandedVal = true;
4360 APInt DemandedVecElts = DemandedElts;
4361 auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
4362 if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
4363 unsigned EltIdx = CEltNo->getZExtValue();
4364 DemandedVal = !!DemandedElts[EltIdx];
4365 DemandedVecElts.clearBit(EltIdx);
4366 }
4367 Known.setAllConflict();
4368 if (DemandedVal) {
4369 Known2 = computeKnownBits(InVal, Depth + 1);
4370 Known = Known.intersectWith(Known2.zextOrTrunc(BitWidth));
4371 }
4372 if (!!DemandedVecElts) {
4373 Known2 = computeKnownBits(InVec, DemandedVecElts, Depth + 1);
4374 Known = Known.intersectWith(Known2);
4375 }
4376 break;
4377 }
4378 case ISD::BITREVERSE: {
4379 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4380 Known = Known2.reverseBits();
4381 break;
4382 }
4383 case ISD::BSWAP: {
4384 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4385 Known = Known2.byteSwap();
4386 break;
4387 }
4388 case ISD::ABS:
4389 case ISD::ABS_MIN_POISON: {
4390 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4391 Known = Known2.abs();
4392 Known.Zero.setHighBits(
4393 ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1) - 1);
4394 break;
4395 }
4396 case ISD::USUBSAT: {
4397 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4398 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4399 Known = KnownBits::usub_sat(Known, Known2);
4400 break;
4401 }
4402 case ISD::UMIN: {
4403 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4404 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4405 Known = KnownBits::umin(Known, Known2);
4406 break;
4407 }
4408 case ISD::UMAX: {
4409 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4410 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4411 Known = KnownBits::umax(Known, Known2);
4412 break;
4413 }
4414 case ISD::SMIN:
4415 case ISD::SMAX: {
4416 // If we have a clamp pattern, we know that the number of sign bits will be
4417 // the minimum of the clamp min/max range.
4418 bool IsMax = (Opcode == ISD::SMAX);
4419 ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
4420 if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
4421 if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
4422 CstHigh =
4423 isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
4424 if (CstLow && CstHigh) {
4425 if (!IsMax)
4426 std::swap(CstLow, CstHigh);
4427
4428 const APInt &ValueLow = CstLow->getAPIntValue();
4429 const APInt &ValueHigh = CstHigh->getAPIntValue();
4430 if (ValueLow.sle(ValueHigh)) {
4431 unsigned LowSignBits = ValueLow.getNumSignBits();
4432 unsigned HighSignBits = ValueHigh.getNumSignBits();
4433 unsigned MinSignBits = std::min(LowSignBits, HighSignBits);
4434 if (ValueLow.isNegative() && ValueHigh.isNegative()) {
4435 Known.One.setHighBits(MinSignBits);
4436 break;
4437 }
4438 if (ValueLow.isNonNegative() && ValueHigh.isNonNegative()) {
4439 Known.Zero.setHighBits(MinSignBits);
4440 break;
4441 }
4442 }
4443 }
4444
4445 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4446 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4447 if (IsMax)
4448 Known = KnownBits::smax(Known, Known2);
4449 else
4450 Known = KnownBits::smin(Known, Known2);
4451
4452 // For SMAX, if CstLow is non-negative we know the result will be
4453 // non-negative and thus all sign bits are 0.
4454 // TODO: There's an equivalent of this for smin with negative constant for
4455 // known ones.
4456 if (IsMax && CstLow) {
4457 const APInt &ValueLow = CstLow->getAPIntValue();
4458 if (ValueLow.isNonNegative()) {
4459 unsigned SignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
4460 Known.Zero.setHighBits(std::min(SignBits, ValueLow.getNumSignBits()));
4461 }
4462 }
4463
4464 break;
4465 }
4466 case ISD::UINT_TO_FP: {
4467 Known.makeNonNegative();
4468 break;
4469 }
4470 case ISD::SINT_TO_FP: {
4471 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4472 if (Known2.isNonNegative())
4473 Known.makeNonNegative();
4474 else if (Known2.isNegative())
4475 Known.makeNegative();
4476 break;
4477 }
4478 case ISD::FP_TO_UINT_SAT: {
4479 // FP_TO_UINT_SAT produces an unsigned value that fits in the saturating VT.
4480 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
4482 break;
4483 }
4484 case ISD::ATOMIC_LOAD: {
4485 // If we are looking at the loaded value.
4486 if (Op.getResNo() == 0) {
4487 auto *AT = cast<AtomicSDNode>(Op);
4488 unsigned ScalarMemorySize = AT->getMemoryVT().getScalarSizeInBits();
4489 KnownBits KnownScalarMemory(ScalarMemorySize);
4490 if (const MDNode *MD = AT->getRanges())
4491 computeKnownBitsFromRangeMetadata(*MD, KnownScalarMemory);
4492
4493 switch (AT->getExtensionType()) {
4494 case ISD::ZEXTLOAD:
4495 Known = KnownScalarMemory.zext(BitWidth);
4496 break;
4497 case ISD::SEXTLOAD:
4498 Known = KnownScalarMemory.sext(BitWidth);
4499 break;
4500 case ISD::EXTLOAD:
4501 switch (TLI->getExtendForAtomicOps()) {
4502 case ISD::ZERO_EXTEND:
4503 Known = KnownScalarMemory.zext(BitWidth);
4504 break;
4505 case ISD::SIGN_EXTEND:
4506 Known = KnownScalarMemory.sext(BitWidth);
4507 break;
4508 default:
4509 Known = KnownScalarMemory.anyext(BitWidth);
4510 break;
4511 }
4512 break;
4513 case ISD::NON_EXTLOAD:
4514 Known = KnownScalarMemory;
4515 break;
4516 }
4517 assert(Known.getBitWidth() == BitWidth);
4518 }
4519 break;
4520 }
4522 if (Op.getResNo() == 1) {
4523 // The boolean result conforms to getBooleanContents.
4524 // If we know the result of a setcc has the top bits zero, use this info.
4525 // We know that we have an integer-based boolean since these operations
4526 // are only available for integer.
4527 if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
4529 BitWidth > 1)
4530 Known.Zero.setBitsFrom(1);
4531 break;
4532 }
4533 [[fallthrough]];
4535 case ISD::ATOMIC_SWAP:
4546 case ISD::ATOMIC_LOAD_UMAX: {
4547 // If we are looking at the loaded value.
4548 if (Op.getResNo() == 0) {
4549 auto *AT = cast<AtomicSDNode>(Op);
4550 unsigned MemBits = AT->getMemoryVT().getScalarSizeInBits();
4551
4552 if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND)
4553 Known.Zero.setBitsFrom(MemBits);
4554 }
4555 break;
4556 }
4557 case ISD::FrameIndex:
4558 case ISD::TargetFrameIndex: {
4559 const MachineFunction &MF = getMachineFunction();
4560 int FrameIdx = cast<FrameIndexSDNode>(Op)->getIndex();
4561 TLI->computeKnownBitsForStackObjectPointer(
4562 Known, MF, MF.getFrameInfo().getObjectAlign(FrameIdx));
4563 break;
4564 }
4565 case ISD::VP_LOAD_FF: {
4566 if (Op.getResNo() != 1)
4567 break;
4568 // The second result of vp.load.ff is an unsigned value that is less than or
4569 // equal to the EVL operand.
4570 KnownBits VLKB =
4571 computeKnownBits(Op.getOperand(3), DemandedElts, Depth + 1);
4572 // The new VL is also bounded by the largest vector length.
4573 EVT ResVT = Op->getValueType(0);
4574 auto ResKB = KnownBits::makeConstant(
4576 if (ResVT.isScalableVector()) {
4578 ResKB = KnownBits::mul(getVScaleRange(&F, BitWidth).toKnownBits(), ResKB);
4579 }
4580 Known.Zero.setHighBits(KnownBits::umin(VLKB, ResKB).countMinLeadingZeros());
4581 break;
4582 }
4583
4584 default:
4585 if (Opcode < ISD::BUILTIN_OP_END)
4586 break;
4587 [[fallthrough]];
4591 // Allow the target to implement this method for its nodes.
4592 TLI->computeKnownBitsForTargetNode(Op, Known, DemandedElts, *this, Depth);
4593 break;
4594 }
4595
4596 return Known;
4597}
4598
4599/// Convert ConstantRange OverflowResult into SelectionDAG::OverflowKind.
4612
4615 // X + 0 never overflow
4616 if (isNullConstant(N1))
4617 return OFK_Never;
4618
4619 // If both operands each have at least two sign bits, the addition
4620 // cannot overflow.
4621 if (ComputeNumSignBits(N0) > 1 && ComputeNumSignBits(N1) > 1)
4622 return OFK_Never;
4623
4624 // TODO: Add ConstantRange::signedAddMayOverflow handling.
4625 return OFK_Sometime;
4626}
4627
4630 // X + 0 never overflow
4631 if (isNullConstant(N1))
4632 return OFK_Never;
4633
4634 // mulhi + 1 never overflow
4635 KnownBits N1Known = computeKnownBits(N1);
4636 if (N0.getOpcode() == ISD::UMUL_LOHI && N0.getResNo() == 1 &&
4637 N1Known.getMaxValue().ult(2))
4638 return OFK_Never;
4639
4640 KnownBits N0Known = computeKnownBits(N0);
4641 if (N1.getOpcode() == ISD::UMUL_LOHI && N1.getResNo() == 1 &&
4642 N0Known.getMaxValue().ult(2))
4643 return OFK_Never;
4644
4645 // Fallback to ConstantRange::unsignedAddMayOverflow handling.
4646 ConstantRange N0Range = ConstantRange::fromKnownBits(N0Known, false);
4647 ConstantRange N1Range = ConstantRange::fromKnownBits(N1Known, false);
4648 return mapOverflowResult(N0Range.unsignedAddMayOverflow(N1Range));
4649}
4650
4653 // X - 0 never overflow
4654 if (isNullConstant(N1))
4655 return OFK_Never;
4656
4657 // If both operands each have at least two sign bits, the subtraction
4658 // cannot overflow.
4659 if (ComputeNumSignBits(N0) > 1 && ComputeNumSignBits(N1) > 1)
4660 return OFK_Never;
4661
4662 KnownBits N0Known = computeKnownBits(N0);
4663 KnownBits N1Known = computeKnownBits(N1);
4664 ConstantRange N0Range = ConstantRange::fromKnownBits(N0Known, true);
4665 ConstantRange N1Range = ConstantRange::fromKnownBits(N1Known, true);
4666 return mapOverflowResult(N0Range.signedSubMayOverflow(N1Range));
4667}
4668
4671 // X - 0 never overflow
4672 if (isNullConstant(N1))
4673 return OFK_Never;
4674
4675 ConstantRange N0Range =
4676 computeConstantRangeIncludingKnownBits(N0, /*ForSigned=*/false);
4677 ConstantRange N1Range =
4678 computeConstantRangeIncludingKnownBits(N1, /*ForSigned=*/false);
4679 return mapOverflowResult(N0Range.unsignedSubMayOverflow(N1Range));
4680}
4681
4684 // X * 0 and X * 1 never overflow.
4685 if (isNullConstant(N1) || isOneConstant(N1))
4686 return OFK_Never;
4687
4690 return mapOverflowResult(N0Range.unsignedMulMayOverflow(N1Range));
4691}
4692
4695 // X * 0 and X * 1 never overflow.
4696 if (isNullConstant(N1) || isOneConstant(N1))
4697 return OFK_Never;
4698
4699 // Get the size of the result.
4700 unsigned BitWidth = N0.getScalarValueSizeInBits();
4701
4702 // Sum of the sign bits.
4703 unsigned SignBits = ComputeNumSignBits(N0) + ComputeNumSignBits(N1);
4704
4705 // If we have enough sign bits, then there's no overflow.
4706 if (SignBits > BitWidth + 1)
4707 return OFK_Never;
4708
4709 if (SignBits == BitWidth + 1) {
4710 // The overflow occurs when the true multiplication of the
4711 // the operands is the minimum negative number.
4712 KnownBits N0Known = computeKnownBits(N0);
4713 KnownBits N1Known = computeKnownBits(N1);
4714 // If one of the operands is non-negative, then there's no
4715 // overflow.
4716 if (N0Known.isNonNegative() || N1Known.isNonNegative())
4717 return OFK_Never;
4718 }
4719
4720 return OFK_Sometime;
4721}
4722
4724 unsigned Depth) const {
4725 APInt DemandedElts = getDemandAllEltsMask(Op);
4726 return computeConstantRange(Op, DemandedElts, ForSigned, Depth);
4727}
4728
4730 const APInt &DemandedElts,
4731 bool ForSigned,
4732 unsigned Depth) const {
4733 EVT VT = Op.getValueType();
4734 unsigned BitWidth = VT.getScalarSizeInBits();
4735
4736 if (Depth >= MaxRecursionDepth)
4737 return ConstantRange::getFull(BitWidth);
4738
4739 if (ConstantSDNode *C = isConstOrConstSplat(Op, DemandedElts))
4740 return ConstantRange(C->getAPIntValue());
4741
4742 unsigned Opcode = Op.getOpcode();
4743 switch (Opcode) {
4744 case ISD::VSCALE: {
4746 const APInt &Multiplier = Op.getConstantOperandAPInt(0);
4747 return getVScaleRange(&F, BitWidth).multiply(Multiplier);
4748 }
4749 default:
4750 break;
4751 }
4752
4753 return ConstantRange::getFull(BitWidth);
4754}
4755
4758 unsigned Depth) const {
4759 APInt DemandedElts = getDemandAllEltsMask(Op);
4760 return computeConstantRangeIncludingKnownBits(Op, DemandedElts, ForSigned,
4761 Depth);
4762}
4763
4765 SDValue Op, const APInt &DemandedElts, bool ForSigned,
4766 unsigned Depth) const {
4767 KnownBits Known = computeKnownBits(Op, DemandedElts, Depth);
4769 ConstantRange CR2 = computeConstantRange(Op, DemandedElts, ForSigned, Depth);
4772 return CR1.intersectWith(CR2, RangeType);
4773}
4774
4776 unsigned Depth) const {
4777 APInt DemandedElts = getDemandAllEltsMask(Val);
4778 return isKnownToBeAPowerOfTwo(Val, DemandedElts, OrZero, Depth);
4779}
4780
4782 const APInt &DemandedElts,
4783 bool OrZero, unsigned Depth) const {
4784 if (Depth >= MaxRecursionDepth)
4785 return false; // Limit search depth.
4786
4787 EVT OpVT = Val.getValueType();
4788 unsigned BitWidth = OpVT.getScalarSizeInBits();
4789 [[maybe_unused]] unsigned NumElts = DemandedElts.getBitWidth();
4790 assert((!OpVT.isScalableVector() || NumElts == 1) &&
4791 "DemandedElts for scalable vectors must be 1 to represent all lanes");
4792 assert(
4793 (!OpVT.isFixedLengthVector() || NumElts == OpVT.getVectorNumElements()) &&
4794 "Unexpected vector size");
4795
4796 auto IsPowerOfTwoOrZero = [BitWidth, OrZero](const ConstantSDNode *C) {
4797 APInt V = C->getAPIntValue().zextOrTrunc(BitWidth);
4798 return (OrZero && V.isZero()) || V.isPowerOf2();
4799 };
4800
4801 // Is the constant a known power of 2 or zero?
4802 if (ISD::matchUnaryPredicate(Val, DemandedElts, IsPowerOfTwoOrZero,
4803 /*AllowUndefs=*/false, /*AllowTruncation=*/true))
4804 return true;
4805
4806 switch (Val.getOpcode()) {
4808 SDValue InVec = Val.getOperand(0);
4809 SDValue EltNo = Val.getOperand(1);
4810 EVT VecVT = InVec.getValueType();
4811
4812 // Skip scalable vectors or implicit extensions.
4813 if (VecVT.isScalableVector() ||
4814 OpVT.getScalarSizeInBits() != VecVT.getScalarSizeInBits())
4815 break;
4816
4817 // If we know the element index, just demand that vector element, else for
4818 // an unknown element index, ignore DemandedElts and demand them all.
4819 const unsigned NumSrcElts = VecVT.getVectorNumElements();
4820 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
4821 APInt DemandedSrcElts =
4822 ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts)
4823 ? APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue())
4824 : APInt::getAllOnes(NumSrcElts);
4825 return isKnownToBeAPowerOfTwo(InVec, DemandedSrcElts, OrZero, Depth + 1);
4826 }
4827
4828 case ISD::AND: {
4829 // Looking for `x & -x` pattern:
4830 // If x == 0:
4831 // x & -x -> 0
4832 // If x != 0:
4833 // x & -x -> non-zero pow2
4834 // so if we find the pattern return whether we know `x` is non-zero.
4835 SDValue X, Z;
4836 if (sd_match(Val, m_And(m_Value(X), m_Neg(m_Deferred(X)))) ||
4837 (sd_match(Val, m_And(m_Value(X), m_Sub(m_Value(Z), m_Deferred(X)))) &&
4838 MaskedVectorIsZero(Z, DemandedElts, Depth + 1)))
4839 return OrZero || isKnownNeverZero(X, DemandedElts, Depth);
4840 break;
4841 }
4842
4843 case ISD::SHL: {
4844 // A left-shift of a constant one will have exactly one bit set because
4845 // shifting the bit off the end is undefined.
4846 auto *C = isConstOrConstSplat(Val.getOperand(0), DemandedElts);
4847 if (C && C->getAPIntValue() == 1)
4848 return true;
4849 return (OrZero || isKnownNeverZero(Val, DemandedElts, Depth)) &&
4850 isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedElts, OrZero,
4851 Depth + 1);
4852 }
4853
4854 case ISD::SRL: {
4855 // A logical right-shift of a constant sign-bit will have exactly
4856 // one bit set.
4857 auto *C = isConstOrConstSplat(Val.getOperand(0), DemandedElts);
4858 if (C && C->getAPIntValue().isSignMask())
4859 return true;
4860 return (OrZero || isKnownNeverZero(Val, DemandedElts, Depth)) &&
4861 isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedElts, OrZero,
4862 Depth + 1);
4863 }
4864
4865 case ISD::TRUNCATE:
4866 return (OrZero || isKnownNeverZero(Val, DemandedElts, Depth)) &&
4867 isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedElts, OrZero,
4868 Depth + 1);
4869
4870 case ISD::ROTL:
4871 case ISD::ROTR:
4872 return isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedElts, OrZero,
4873 Depth + 1);
4874 case ISD::BSWAP:
4875 case ISD::BITREVERSE:
4876 return isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedElts, OrZero,
4877 Depth + 1);
4878
4879 case ISD::SMIN:
4880 case ISD::SMAX:
4881 case ISD::UMIN:
4882 case ISD::UMAX:
4883 return isKnownToBeAPowerOfTwo(Val.getOperand(1), DemandedElts, OrZero,
4884 Depth + 1) &&
4885 isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedElts, OrZero,
4886 Depth + 1);
4887
4888 case ISD::SELECT:
4889 case ISD::VSELECT:
4890 return isKnownToBeAPowerOfTwo(Val.getOperand(2), DemandedElts, OrZero,
4891 Depth + 1) &&
4892 isKnownToBeAPowerOfTwo(Val.getOperand(1), DemandedElts, OrZero,
4893 Depth + 1);
4894
4895 case ISD::ZERO_EXTEND:
4896 return isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedElts, OrZero,
4897 Depth + 1);
4898
4899 case ISD::VSCALE:
4900 // vscale(power-of-two) is a power-of-two
4901 return isKnownToBeAPowerOfTwo(Val.getOperand(0), /*OrZero=*/false,
4902 Depth + 1);
4903
4904 case ISD::VECTOR_SHUFFLE: {
4906 // Demanded elements with undef shuffle mask elements are unknown
4907 // - we cannot guarantee they are a power of two, so return false.
4908 APInt DemandedLHS, DemandedRHS;
4910 assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
4911 if (!getShuffleDemandedElts(NumElts, SVN->getMask(), DemandedElts,
4912 DemandedLHS, DemandedRHS))
4913 return false;
4914
4915 // All demanded elements from LHS must be known power of two.
4916 if (!!DemandedLHS && !isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedLHS,
4917 OrZero, Depth + 1))
4918 return false;
4919
4920 // All demanded elements from RHS must be known power of two.
4921 if (!!DemandedRHS && !isKnownToBeAPowerOfTwo(Val.getOperand(1), DemandedRHS,
4922 OrZero, Depth + 1))
4923 return false;
4924
4925 return true;
4926 }
4927 }
4928
4929 // More could be done here, though the above checks are enough
4930 // to handle some common cases.
4931 return false;
4932}
4933
4935 if (ConstantFPSDNode *C1 = isConstOrConstSplatFP(Val, true))
4936 return C1->getValueAPF().getExactLog2Abs() >= 0;
4937
4938 if (Val.getOpcode() == ISD::UINT_TO_FP || Val.getOpcode() == ISD::SINT_TO_FP)
4939 return isKnownToBeAPowerOfTwo(Val.getOperand(0), Depth + 1);
4940
4941 return false;
4942}
4943
4945 APInt DemandedElts = getDemandAllEltsMask(Op);
4946 return ComputeNumSignBits(Op, DemandedElts, Depth);
4947}
4948
4949unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, const APInt &DemandedElts,
4950 unsigned Depth) const {
4951 EVT VT = Op.getValueType();
4952 assert((VT.isInteger() || VT.isFloatingPoint()) && "Invalid VT!");
4953 unsigned VTBits = VT.getScalarSizeInBits();
4954 unsigned NumElts = DemandedElts.getBitWidth();
4955 unsigned Tmp, Tmp2;
4956 unsigned FirstAnswer = 1;
4957
4958 assert((!VT.isScalableVector() || NumElts == 1) &&
4959 "DemandedElts for scalable vectors must be 1 to represent all lanes");
4960
4961 if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
4962 const APInt &Val = C->getAPIntValue();
4963 return Val.getNumSignBits();
4964 }
4965
4966 if (Depth >= MaxRecursionDepth)
4967 return 1; // Limit search depth.
4968
4969 if (!DemandedElts)
4970 return 1; // No demanded elts, better to assume we don't know anything.
4971
4972 unsigned Opcode = Op.getOpcode();
4973 switch (Opcode) {
4974 default: break;
4975 case ISD::AssertSext:
4976 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
4977 return VTBits-Tmp+1;
4978 case ISD::AssertZext:
4979 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
4980 return VTBits-Tmp;
4981 case ISD::FREEZE:
4982 if (isGuaranteedNotToBeUndefOrPoison(Op.getOperand(0), DemandedElts,
4984 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4985 break;
4986 case ISD::MERGE_VALUES:
4987 return ComputeNumSignBits(Op.getOperand(Op.getResNo()), DemandedElts,
4988 Depth + 1);
4989 case ISD::SPLAT_VECTOR: {
4990 // Check if the sign bits of source go down as far as the truncated value.
4991 unsigned NumSrcBits = Op.getOperand(0).getValueSizeInBits();
4992 unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
4993 if (NumSrcSignBits > (NumSrcBits - VTBits))
4994 return NumSrcSignBits - (NumSrcBits - VTBits);
4995 break;
4996 }
4997 case ISD::BUILD_VECTOR:
4998 assert(!VT.isScalableVector());
4999 Tmp = VTBits;
5000 for (unsigned i = 0, e = Op.getNumOperands(); (i < e) && (Tmp > 1); ++i) {
5001 if (!DemandedElts[i])
5002 continue;
5003
5004 SDValue SrcOp = Op.getOperand(i);
5005 // BUILD_VECTOR can implicitly truncate sources, we handle this specially
5006 // for constant nodes to ensure we only look at the sign bits.
5008 APInt T = C->getAPIntValue().trunc(VTBits);
5009 Tmp2 = T.getNumSignBits();
5010 } else if (SrcOp.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5011 SrcOp.getOperand(0).getScalarValueSizeInBits() >= VTBits) {
5012 // EXTRACT_VECTOR_ELT can extend the value with high bits undefined. If
5013 // this BUILD_VECTOR truncates those undefined bits we can just look
5014 // through the SrcOp and query the vector directly.
5015 SDValue InVec = SrcOp.getOperand(0);
5016 EVT InVecVT = InVec.getValueType();
5017
5018 APInt DemandedSrcElts;
5019 if (InVecVT.isScalableVector())
5020 // Demand all elements.
5021 DemandedSrcElts = APInt(1, 1);
5022 else {
5023 unsigned NumSrcElts = InVecVT.getVectorNumElements();
5024 auto *ConstEltNo = dyn_cast<ConstantSDNode>(SrcOp.getOperand(1));
5025 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
5026 DemandedSrcElts =
5027 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
5028 else
5029 DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
5030 }
5031
5032 Tmp2 = ComputeNumSignBits(InVec, DemandedSrcElts, Depth + 1);
5033 unsigned ExtraBits = InVec.getScalarValueSizeInBits() - VTBits;
5034 if (ExtraBits)
5035 Tmp2 = (Tmp2 > ExtraBits ? Tmp2 - ExtraBits : 1);
5036 } else {
5037 Tmp2 = ComputeNumSignBits(SrcOp, Depth + 1);
5038
5039 if (SrcOp.getValueSizeInBits() != VTBits) {
5040 assert(SrcOp.getValueSizeInBits() > VTBits &&
5041 "Expected BUILD_VECTOR implicit truncation");
5042 unsigned ExtraBits = SrcOp.getValueSizeInBits() - VTBits;
5043 Tmp2 = (Tmp2 > ExtraBits ? Tmp2 - ExtraBits : 1);
5044 }
5045 }
5046 Tmp = std::min(Tmp, Tmp2);
5047 }
5048 return Tmp;
5049
5050 case ISD::VECTOR_COMPRESS: {
5051 SDValue Vec = Op.getOperand(0);
5052 SDValue PassThru = Op.getOperand(2);
5053 Tmp = ComputeNumSignBits(PassThru, DemandedElts, Depth + 1);
5054 if (Tmp == 1)
5055 return 1;
5056 Tmp2 = ComputeNumSignBits(Vec, Depth + 1);
5057 Tmp = std::min(Tmp, Tmp2);
5058 return Tmp;
5059 }
5060
5061 case ISD::VECTOR_SHUFFLE: {
5062 // Collect the minimum number of sign bits that are shared by every vector
5063 // element referenced by the shuffle.
5064 APInt DemandedLHS, DemandedRHS;
5066 assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
5067 if (!getShuffleDemandedElts(NumElts, SVN->getMask(), DemandedElts,
5068 DemandedLHS, DemandedRHS))
5069 return 1;
5070
5071 Tmp = std::numeric_limits<unsigned>::max();
5072 if (!!DemandedLHS)
5073 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedLHS, Depth + 1);
5074 if (!!DemandedRHS) {
5075 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedRHS, Depth + 1);
5076 Tmp = std::min(Tmp, Tmp2);
5077 }
5078 // If we don't know anything, early out and try computeKnownBits fall-back.
5079 if (Tmp == 1)
5080 break;
5081 assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
5082 return Tmp;
5083 }
5084
5085 case ISD::BITCAST: {
5086 if (VT.isScalableVector())
5087 break;
5088 SDValue N0 = Op.getOperand(0);
5089 EVT SrcVT = N0.getValueType();
5090 unsigned SrcBits = SrcVT.getScalarSizeInBits();
5091
5092 // Ignore bitcasts from unsupported types..
5093 if (!(SrcVT.isInteger() || SrcVT.isFloatingPoint()))
5094 break;
5095
5096 // Fast handling of 'identity' bitcasts.
5097 if (VTBits == SrcBits)
5098 return ComputeNumSignBits(N0, DemandedElts, Depth + 1);
5099
5100 bool IsLE = getDataLayout().isLittleEndian();
5101
5102 // Bitcast 'large element' scalar/vector to 'small element' vector.
5103 if ((SrcBits % VTBits) == 0) {
5104 assert(VT.isVector() && "Expected bitcast to vector");
5105
5106 unsigned Scale = SrcBits / VTBits;
5107 APInt SrcDemandedElts =
5108 APIntOps::ScaleBitMask(DemandedElts, NumElts / Scale);
5109
5110 // Fast case - sign splat can be simply split across the small elements.
5111 Tmp = ComputeNumSignBits(N0, SrcDemandedElts, Depth + 1);
5112 if (Tmp == SrcBits)
5113 return VTBits;
5114
5115 // Slow case - determine how far the sign extends into each sub-element.
5116 Tmp2 = VTBits;
5117 for (unsigned i = 0; i != NumElts; ++i)
5118 if (DemandedElts[i]) {
5119 unsigned SubOffset = i % Scale;
5120 SubOffset = (IsLE ? ((Scale - 1) - SubOffset) : SubOffset);
5121 SubOffset = SubOffset * VTBits;
5122 if (Tmp <= SubOffset)
5123 return 1;
5124 Tmp2 = std::min(Tmp2, Tmp - SubOffset);
5125 }
5126 return Tmp2;
5127 }
5128 break;
5129 }
5130
5132 // FP_TO_SINT_SAT produces a signed value that fits in the saturating VT.
5133 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
5134 return VTBits - Tmp + 1;
5135 case ISD::SIGN_EXTEND:
5136 Tmp = VTBits - Op.getOperand(0).getScalarValueSizeInBits();
5137 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1) + Tmp;
5139 // Max of the input and what this extends.
5140 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
5141 Tmp = VTBits-Tmp+1;
5142 Tmp2 = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
5143 return std::max(Tmp, Tmp2);
5145 if (VT.isScalableVector())
5146 break;
5147 SDValue Src = Op.getOperand(0);
5148 EVT SrcVT = Src.getValueType();
5149 APInt DemandedSrcElts = DemandedElts.zext(SrcVT.getVectorNumElements());
5150 Tmp = VTBits - SrcVT.getScalarSizeInBits();
5151 return ComputeNumSignBits(Src, DemandedSrcElts, Depth+1) + Tmp;
5152 }
5153 case ISD::SRA:
5154 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5155 // SRA X, C -> adds C sign bits.
5156 if (std::optional<unsigned> ShAmt =
5157 getValidMinimumShiftAmount(Op, DemandedElts, Depth + 1))
5158 Tmp = std::min(Tmp + *ShAmt, VTBits);
5159 return Tmp;
5160 case ISD::SHL:
5161 if (std::optional<ConstantRange> ShAmtRange =
5162 getValidShiftAmountRange(Op, DemandedElts, Depth + 1)) {
5163 unsigned MaxShAmt = ShAmtRange->getUnsignedMax().getZExtValue();
5164 unsigned MinShAmt = ShAmtRange->getUnsignedMin().getZExtValue();
5165 // Try to look through ZERO/SIGN/ANY_EXTEND. If all extended bits are
5166 // shifted out, then we can compute the number of sign bits for the
5167 // operand being extended. A future improvement could be to pass along the
5168 // "shifted left by" information in the recursive calls to
5169 // ComputeKnownSignBits. Allowing us to handle this more generically.
5170 if (ISD::isExtOpcode(Op.getOperand(0).getOpcode())) {
5171 SDValue Ext = Op.getOperand(0);
5172 EVT ExtVT = Ext.getValueType();
5173 SDValue Extendee = Ext.getOperand(0);
5174 EVT ExtendeeVT = Extendee.getValueType();
5175 unsigned SizeDifference =
5176 ExtVT.getScalarSizeInBits() - ExtendeeVT.getScalarSizeInBits();
5177 if (SizeDifference <= MinShAmt) {
5178 Tmp = SizeDifference +
5179 ComputeNumSignBits(Extendee, DemandedElts, Depth + 1);
5180 if (MaxShAmt < Tmp)
5181 return Tmp - MaxShAmt;
5182 }
5183 }
5184 // shl destroys sign bits, ensure it doesn't shift out all sign bits.
5185 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5186 if (MaxShAmt < Tmp)
5187 return Tmp - MaxShAmt;
5188 }
5189 break;
5190 case ISD::AND:
5191 case ISD::OR:
5192 case ISD::XOR: // NOT is handled here.
5193 // Logical binary ops preserve the number of sign bits at the worst.
5194 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
5195 if (Tmp != 1) {
5196 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
5197 FirstAnswer = std::min(Tmp, Tmp2);
5198 // We computed what we know about the sign bits as our first
5199 // answer. Now proceed to the generic code that uses
5200 // computeKnownBits, and pick whichever answer is better.
5201 }
5202 break;
5203
5204 case ISD::SELECT:
5205 case ISD::VSELECT:
5206 Tmp = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
5207 if (Tmp == 1) return 1; // Early out.
5208 Tmp2 = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
5209 return std::min(Tmp, Tmp2);
5210 case ISD::SELECT_CC:
5211 Tmp = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
5212 if (Tmp == 1) return 1; // Early out.
5213 Tmp2 = ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth+1);
5214 return std::min(Tmp, Tmp2);
5215
5216 case ISD::SMIN:
5217 case ISD::SMAX: {
5218 // If we have a clamp pattern, we know that the number of sign bits will be
5219 // the minimum of the clamp min/max range.
5220 bool IsMax = (Opcode == ISD::SMAX);
5221 ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
5222 if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
5223 if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
5224 CstHigh =
5225 isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
5226 if (CstLow && CstHigh) {
5227 if (!IsMax)
5228 std::swap(CstLow, CstHigh);
5229 if (CstLow->getAPIntValue().sle(CstHigh->getAPIntValue())) {
5230 Tmp = CstLow->getAPIntValue().getNumSignBits();
5231 Tmp2 = CstHigh->getAPIntValue().getNumSignBits();
5232 return std::min(Tmp, Tmp2);
5233 }
5234 }
5235
5236 // Fallback - just get the minimum number of sign bits of the operands.
5237 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5238 if (Tmp == 1)
5239 return 1; // Early out.
5240 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
5241 return std::min(Tmp, Tmp2);
5242 }
5243 case ISD::UMIN:
5244 case ISD::UMAX:
5245 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5246 if (Tmp == 1)
5247 return 1; // Early out.
5248 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
5249 return std::min(Tmp, Tmp2);
5250 case ISD::SSUBO_CARRY:
5251 case ISD::USUBO_CARRY:
5252 // sub_carry(x,x,c) -> 0/-1 (sext carry)
5253 if (Op.getResNo() == 0 && Op.getOperand(0) == Op.getOperand(1))
5254 return VTBits;
5255 [[fallthrough]];
5256 case ISD::SADDO:
5257 case ISD::UADDO:
5258 case ISD::SADDO_CARRY:
5259 case ISD::UADDO_CARRY:
5260 case ISD::SSUBO:
5261 case ISD::USUBO:
5262 case ISD::SMULO:
5263 case ISD::UMULO:
5264 if (Op.getResNo() != 1)
5265 break;
5266 // The boolean result conforms to getBooleanContents. Fall through.
5267 // If setcc returns 0/-1, all bits are sign bits.
5268 // We know that we have an integer-based boolean since these operations
5269 // are only available for integer.
5270 if (TLI->getBooleanContents(VT.isVector(), false) ==
5272 return VTBits;
5273 break;
5274 case ISD::SETCC:
5275 case ISD::SETCCCARRY:
5276 case ISD::STRICT_FSETCC:
5277 case ISD::STRICT_FSETCCS: {
5278 unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
5279 // If setcc returns 0/-1, all bits are sign bits.
5280 if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
5282 return VTBits;
5283 break;
5284 }
5287 // Semantically similar to icmp ult.
5288 if (TLI->getBooleanContents(VT.isVector(), /*isFloat=*/false) ==
5290 return VTBits;
5291 break;
5292 case ISD::ROTL:
5293 case ISD::ROTR: {
5294 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5295 ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(1), DemandedElts);
5296 FirstAnswer = SignBitsOps::rot(
5297 Tmp, VTBits, C ? std::optional(C->getAPIntValue()) : std::nullopt,
5298 Opcode == ISD::ROTR);
5299 break;
5300 }
5301 case ISD::ADD:
5302 case ISD::ADDC:
5303 // TODO: Move Operand 1 check before Operand 0 check
5304 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5305 if (Tmp == 1) return 1; // Early out.
5306
5307 // Special case decrementing a value (ADD X, -1):
5308 if (ConstantSDNode *CRHS =
5309 isConstOrConstSplat(Op.getOperand(1), DemandedElts))
5310 if (CRHS->isAllOnes()) {
5312 computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
5313
5314 // If the input is known to be 0 or 1, the output is 0/-1, which is all
5315 // sign bits set.
5316 if ((Known.Zero | 1).isAllOnes())
5317 return VTBits;
5318
5319 // If we are subtracting one from a positive number, there is no carry
5320 // out of the result.
5321 if (Known.isNonNegative())
5322 return Tmp;
5323 }
5324
5325 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
5326 if (Tmp2 == 1) return 1; // Early out.
5327
5328 // Add can have at most one carry bit. Thus we know that the output
5329 // is, at worst, one more bit than the inputs.
5330 return std::min(Tmp, Tmp2) - 1;
5331 case ISD::SUB:
5332 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
5333 if (Tmp2 == 1) return 1; // Early out.
5334
5335 // Handle NEG.
5336 if (ConstantSDNode *CLHS =
5337 isConstOrConstSplat(Op.getOperand(0), DemandedElts))
5338 if (CLHS->isZero()) {
5340 computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
5341 // If the input is known to be 0 or 1, the output is 0/-1, which is all
5342 // sign bits set.
5343 if ((Known.Zero | 1).isAllOnes())
5344 return VTBits;
5345
5346 // If the input is known to be positive (the sign bit is known clear),
5347 // the output of the NEG has the same number of sign bits as the input.
5348 if (Known.isNonNegative())
5349 return Tmp2;
5350
5351 // Otherwise, we treat this like a SUB.
5352 }
5353
5354 // Sub can have at most one carry bit. Thus we know that the output
5355 // is, at worst, one more bit than the inputs.
5356 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5357 if (Tmp == 1) return 1; // Early out.
5358 return std::min(Tmp, Tmp2) - 1;
5359 case ISD::MUL: {
5360 // The output of the Mul can be at most twice the valid bits in the inputs.
5361 unsigned SignBitsOp0 =
5362 ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5363 if (SignBitsOp0 == 1)
5364 break;
5365 unsigned SignBitsOp1 =
5366 ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
5367 if (SignBitsOp1 == 1)
5368 break;
5369 unsigned OutValidBits =
5370 (VTBits - SignBitsOp0 + 1) + (VTBits - SignBitsOp1 + 1);
5371 return OutValidBits > VTBits ? 1 : VTBits - OutValidBits + 1;
5372 }
5373 case ISD::AVGCEILS:
5374 case ISD::AVGFLOORS:
5375 case ISD::AVGSUBFLOORS:
5376 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5377 if (Tmp == 1)
5378 return 1; // Early out.
5379 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
5380 return std::min(Tmp, Tmp2);
5381 case ISD::SREM:
5382 // The sign bit is the LHS's sign bit, except when the result of the
5383 // remainder is zero. The magnitude of the result should be less than or
5384 // equal to the magnitude of the LHS. Therefore, the result should have
5385 // at least as many sign bits as the left hand side.
5386 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5387 case ISD::TRUNCATE: {
5388 // Check if the sign bits of source go down as far as the truncated value.
5389 unsigned NumSrcBits = Op.getOperand(0).getScalarValueSizeInBits();
5390 unsigned NumSrcSignBits =
5391 ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5392 if (NumSrcSignBits > (NumSrcBits - VTBits))
5393 return NumSrcSignBits - (NumSrcBits - VTBits);
5394 break;
5395 }
5396 case ISD::EXTRACT_ELEMENT: {
5397 if (VT.isScalableVector())
5398 break;
5399 const int KnownSign = ComputeNumSignBits(Op.getOperand(0), Depth+1);
5400 const int BitWidth = Op.getValueSizeInBits();
5401 const int Items = Op.getOperand(0).getValueSizeInBits() / BitWidth;
5402
5403 // Get reverse index (starting from 1), Op1 value indexes elements from
5404 // little end. Sign starts at big end.
5405 const int rIndex = Items - 1 - Op.getConstantOperandVal(1);
5406
5407 // If the sign portion ends in our element the subtraction gives correct
5408 // result. Otherwise it gives either negative or > bitwidth result
5409 return std::clamp(KnownSign - rIndex * BitWidth, 1, BitWidth);
5410 }
5412 if (VT.isScalableVector())
5413 break;
5414 // If we know the element index, split the demand between the
5415 // source vector and the inserted element, otherwise assume we need
5416 // the original demanded vector elements and the value.
5417 SDValue InVec = Op.getOperand(0);
5418 SDValue InVal = Op.getOperand(1);
5419 SDValue EltNo = Op.getOperand(2);
5420 bool DemandedVal = true;
5421 APInt DemandedVecElts = DemandedElts;
5422 auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
5423 if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
5424 unsigned EltIdx = CEltNo->getZExtValue();
5425 DemandedVal = !!DemandedElts[EltIdx];
5426 DemandedVecElts.clearBit(EltIdx);
5427 }
5428 Tmp = std::numeric_limits<unsigned>::max();
5429 if (DemandedVal) {
5430 // TODO - handle implicit truncation of inserted elements.
5431 if (InVal.getScalarValueSizeInBits() != VTBits)
5432 break;
5433 Tmp2 = ComputeNumSignBits(InVal, Depth + 1);
5434 Tmp = std::min(Tmp, Tmp2);
5435 }
5436 if (!!DemandedVecElts) {
5437 Tmp2 = ComputeNumSignBits(InVec, DemandedVecElts, Depth + 1);
5438 Tmp = std::min(Tmp, Tmp2);
5439 }
5440 assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
5441 return Tmp;
5442 }
5444 SDValue InVec = Op.getOperand(0);
5445 SDValue EltNo = Op.getOperand(1);
5446 EVT VecVT = InVec.getValueType();
5447 // ComputeNumSignBits not yet implemented for scalable vectors.
5448 if (VecVT.isScalableVector())
5449 break;
5450 const unsigned BitWidth = Op.getValueSizeInBits();
5451 const unsigned EltBitWidth = Op.getOperand(0).getScalarValueSizeInBits();
5452 const unsigned NumSrcElts = VecVT.getVectorNumElements();
5453
5454 // If BitWidth > EltBitWidth the value is anyext:ed, and we do not know
5455 // anything about sign bits. But if the sizes match we can derive knowledge
5456 // about sign bits from the vector operand.
5457 if (BitWidth != EltBitWidth)
5458 break;
5459
5460 // If we know the element index, just demand that vector element, else for
5461 // an unknown element index, ignore DemandedElts and demand them all.
5462 APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
5463 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
5464 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
5465 DemandedSrcElts =
5466 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
5467
5468 return ComputeNumSignBits(InVec, DemandedSrcElts, Depth + 1);
5469 }
5471 // Offset the demanded elts by the subvector index.
5472 SDValue Src = Op.getOperand(0);
5473
5474 APInt DemandedSrcElts;
5475 if (Src.getValueType().isScalableVector())
5476 DemandedSrcElts = APInt(1, 1);
5477 else {
5478 uint64_t Idx = Op.getConstantOperandVal(1);
5479 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
5480 DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
5481 }
5482 return ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
5483 }
5484 case ISD::CONCAT_VECTORS: {
5485 if (VT.isScalableVector())
5486 break;
5487 // Determine the minimum number of sign bits across all demanded
5488 // elts of the input vectors. Early out if the result is already 1.
5489 Tmp = std::numeric_limits<unsigned>::max();
5490 EVT SubVectorVT = Op.getOperand(0).getValueType();
5491 unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
5492 unsigned NumSubVectors = Op.getNumOperands();
5493 for (unsigned i = 0; (i < NumSubVectors) && (Tmp > 1); ++i) {
5494 APInt DemandedSub =
5495 DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts);
5496 if (!DemandedSub)
5497 continue;
5498 Tmp2 = ComputeNumSignBits(Op.getOperand(i), DemandedSub, Depth + 1);
5499 Tmp = std::min(Tmp, Tmp2);
5500 }
5501 assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
5502 return Tmp;
5503 }
5504 case ISD::INSERT_SUBVECTOR: {
5505 SDValue Src = Op.getOperand(0);
5506 SDValue Sub = Op.getOperand(1);
5507 if (VT.isScalableVector()) {
5508 Tmp = ComputeNumSignBits(Sub, Depth + 1);
5509 Tmp = std::min(Tmp, ComputeNumSignBits(Src, Depth + 1));
5510 return Tmp;
5511 }
5512 // Demand any elements from the subvector and the remainder from the src its
5513 // inserted into.
5514 uint64_t Idx = Op.getConstantOperandVal(2);
5515 unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
5516 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
5517 APInt DemandedSrcElts = DemandedElts;
5518 DemandedSrcElts.clearBits(Idx, Idx + NumSubElts);
5519
5520 Tmp = std::numeric_limits<unsigned>::max();
5521 if (!!DemandedSubElts) {
5522 Tmp = ComputeNumSignBits(Sub, DemandedSubElts, Depth + 1);
5523 if (Tmp == 1)
5524 return 1; // early-out
5525 }
5526 if (!!DemandedSrcElts) {
5527 Tmp2 = ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
5528 Tmp = std::min(Tmp, Tmp2);
5529 }
5530 assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
5531 return Tmp;
5532 }
5533 case ISD::LOAD: {
5534 // If we are looking at the loaded value of the SDNode.
5535 if (Op.getResNo() != 0)
5536 break;
5537
5539 if (const MDNode *Ranges = LD->getRanges()) {
5540 if (DemandedElts != 1)
5541 break;
5542
5544 if (VTBits > CR.getBitWidth()) {
5545 switch (LD->getExtensionType()) {
5546 case ISD::SEXTLOAD:
5547 CR = CR.signExtend(VTBits);
5548 break;
5549 case ISD::ZEXTLOAD:
5550 CR = CR.zeroExtend(VTBits);
5551 break;
5552 default:
5553 break;
5554 }
5555 }
5556
5557 if (VTBits != CR.getBitWidth())
5558 break;
5559 return std::min(CR.getSignedMin().getNumSignBits(),
5561 }
5562
5563 unsigned ExtType = LD->getExtensionType();
5564 switch (ExtType) {
5565 default:
5566 break;
5567 case ISD::SEXTLOAD: // e.g. i16->i32 = '17' bits known.
5568 Tmp = LD->getMemoryVT().getScalarSizeInBits();
5569 return VTBits - Tmp + 1;
5570 case ISD::ZEXTLOAD: // e.g. i16->i32 = '16' bits known.
5571 Tmp = LD->getMemoryVT().getScalarSizeInBits();
5572 return VTBits - Tmp;
5573 case ISD::NON_EXTLOAD:
5574 if (const Constant *Cst = TLI->getTargetConstantFromLoad(LD)) {
5575 // We only need to handle vectors - computeKnownBits should handle
5576 // scalar cases.
5577 Type *CstTy = Cst->getType();
5578 if (CstTy->isVectorTy() && !VT.isScalableVector() &&
5579 (NumElts * VTBits) == CstTy->getPrimitiveSizeInBits() &&
5580 VTBits == CstTy->getScalarSizeInBits()) {
5581 Tmp = VTBits;
5582 for (unsigned i = 0; i != NumElts; ++i) {
5583 if (!DemandedElts[i])
5584 continue;
5585 if (Constant *Elt = Cst->getAggregateElement(i)) {
5586 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
5587 const APInt &Value = CInt->getValue();
5588 Tmp = std::min(Tmp, Value.getNumSignBits());
5589 continue;
5590 }
5591 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
5592 APInt Value = CFP->getValueAPF().bitcastToAPInt();
5593 Tmp = std::min(Tmp, Value.getNumSignBits());
5594 continue;
5595 }
5596 }
5597 // Unknown type. Conservatively assume no bits match sign bit.
5598 return 1;
5599 }
5600 return Tmp;
5601 }
5602 }
5603 break;
5604 }
5605
5606 break;
5607 }
5610 case ISD::ATOMIC_SWAP:
5622 case ISD::ATOMIC_LOAD: {
5623 auto *AT = cast<AtomicSDNode>(Op);
5624 // If we are looking at the loaded value.
5625 if (Op.getResNo() == 0) {
5626 Tmp = AT->getMemoryVT().getScalarSizeInBits();
5627 if (Tmp == VTBits)
5628 return 1; // early-out
5629
5630 // For atomic_load, prefer to use the extension type.
5631 if (Op->getOpcode() == ISD::ATOMIC_LOAD) {
5632 switch (AT->getExtensionType()) {
5633 default:
5634 break;
5635 case ISD::SEXTLOAD:
5636 return VTBits - Tmp + 1;
5637 case ISD::ZEXTLOAD:
5638 return VTBits - Tmp;
5639 }
5640 }
5641
5642 if (TLI->getExtendForAtomicOps() == ISD::SIGN_EXTEND)
5643 return VTBits - Tmp + 1;
5644 if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND)
5645 return VTBits - Tmp;
5646 }
5647 break;
5648 }
5649 }
5650
5651 // Allow the target to implement this method for its nodes.
5652 if (Opcode >= ISD::BUILTIN_OP_END ||
5653 Opcode == ISD::INTRINSIC_WO_CHAIN ||
5654 Opcode == ISD::INTRINSIC_W_CHAIN ||
5655 Opcode == ISD::INTRINSIC_VOID) {
5656 // TODO: This can probably be removed once target code is audited. This
5657 // is here purely to reduce patch size and review complexity.
5658 if (!VT.isScalableVector()) {
5659 unsigned NumBits =
5660 TLI->ComputeNumSignBitsForTargetNode(Op, DemandedElts, *this, Depth);
5661 if (NumBits > 1)
5662 FirstAnswer = std::max(FirstAnswer, NumBits);
5663 }
5664 }
5665
5666 // Finally, if we can prove that the top bits of the result are 0's or 1's,
5667 // use this information.
5668 KnownBits Known = computeKnownBits(Op, DemandedElts, Depth);
5669 return std::max(FirstAnswer, Known.countMinSignBits());
5670}
5671
5673 unsigned Depth) const {
5674 unsigned SignBits = ComputeNumSignBits(Op, Depth);
5675 return Op.getScalarValueSizeInBits() - SignBits + 1;
5676}
5677
5679 const APInt &DemandedElts,
5680 unsigned Depth) const {
5681 unsigned SignBits = ComputeNumSignBits(Op, DemandedElts, Depth);
5682 return Op.getScalarValueSizeInBits() - SignBits + 1;
5683}
5684
5686 UndefPoisonKind Kind,
5687 unsigned Depth) const {
5688 // Early out for FREEZE.
5689 if (Op.getOpcode() == ISD::FREEZE)
5690 return true;
5691
5692 APInt DemandedElts = getDemandAllEltsMask(Op);
5693 return isGuaranteedNotToBeUndefOrPoison(Op, DemandedElts, Kind, Depth);
5694}
5695
5697 const APInt &DemandedElts,
5698 UndefPoisonKind Kind,
5699 unsigned Depth) const {
5700 unsigned Opcode = Op.getOpcode();
5701
5702 // Early out for FREEZE.
5703 if (Opcode == ISD::FREEZE)
5704 return true;
5705
5706 if (Depth >= MaxRecursionDepth)
5707 return false; // Limit search depth.
5708
5709 if (isIntOrFPConstant(Op))
5710 return true;
5711
5712 switch (Opcode) {
5713 case ISD::CONDCODE:
5714 case ISD::VALUETYPE:
5715 case ISD::FrameIndex:
5717 case ISD::CopyFromReg:
5718 return true;
5719
5720 case ISD::POISON:
5721 return !includesPoison(Kind);
5722
5723 case ISD::UNDEF:
5724 return !includesUndef(Kind);
5725
5726 case ISD::BITCAST: {
5727 SDValue Src = Op.getOperand(0);
5728 EVT SrcVT = Src.getValueType();
5729 EVT DstVT = Op.getValueType();
5730
5731 if (!SrcVT.isVector() || !DstVT.isVector())
5732 return isGuaranteedNotToBeUndefOrPoison(Src, Kind, Depth + 1);
5733
5734 unsigned SrcEltBits = SrcVT.getScalarSizeInBits();
5735 unsigned DstEltBits = DstVT.getScalarSizeInBits();
5736 ElementCount NumSrcElts = SrcVT.getVectorElementCount();
5737 [[maybe_unused]] ElementCount NumDstElts = DstVT.getVectorElementCount();
5738
5739 if (SrcEltBits == DstEltBits)
5740 return isGuaranteedNotToBeUndefOrPoison(Src, DemandedElts, Kind,
5741 Depth + 1);
5742
5743 if (SrcEltBits < DstEltBits) {
5744 if (DstEltBits % SrcEltBits != 0)
5745 return isGuaranteedNotToBeUndefOrPoison(Src, Kind, Depth + 1);
5746
5747 assert(NumSrcElts == NumDstElts * (DstEltBits / SrcEltBits) &&
5748 "Unexpected vector bitcast");
5749 APInt DemandedSrcElts =
5750 APIntOps::ScaleBitMask(DemandedElts, NumSrcElts.getKnownMinValue());
5751 return isGuaranteedNotToBeUndefOrPoison(Src, DemandedSrcElts, Kind,
5752 Depth + 1);
5753 }
5754
5755 if (SrcEltBits % DstEltBits != 0)
5756 return isGuaranteedNotToBeUndefOrPoison(Src, Kind, Depth + 1);
5757
5758 assert(NumDstElts == NumSrcElts * (SrcEltBits / DstEltBits) &&
5759 "Unexpected vector bitcast");
5760 APInt DemandedSrcElts =
5761 APIntOps::ScaleBitMask(DemandedElts, NumSrcElts.getKnownMinValue());
5762 return isGuaranteedNotToBeUndefOrPoison(Src, DemandedSrcElts, Kind,
5763 Depth + 1);
5764 }
5765
5766 case ISD::BUILD_VECTOR:
5767 // NOTE: BUILD_VECTOR has implicit truncation of wider scalar elements -
5768 // this shouldn't affect the result.
5769 for (unsigned i = 0, e = Op.getNumOperands(); i < e; ++i) {
5770 if (!DemandedElts[i])
5771 continue;
5772 if (!isGuaranteedNotToBeUndefOrPoison(Op.getOperand(i), Kind, Depth + 1))
5773 return false;
5774 }
5775 return true;
5776
5777 case ISD::CONCAT_VECTORS: {
5778 EVT VT = Op.getValueType();
5779 if (!VT.isFixedLengthVector())
5780 break;
5781
5782 EVT SubVT = Op.getOperand(0).getValueType();
5783 unsigned NumSubElts = SubVT.getVectorNumElements();
5784 for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) {
5785 APInt DemandedSubElts =
5786 DemandedElts.extractBits(NumSubElts, I * NumSubElts);
5787 if (!!DemandedSubElts &&
5788 !isGuaranteedNotToBeUndefOrPoison(Op.getOperand(I), DemandedSubElts,
5789 Kind, Depth + 1))
5790 return false;
5791 }
5792 return true;
5793 }
5794
5796 SDValue Src = Op.getOperand(0);
5797 if (Src.getValueType().isScalableVector())
5798 break;
5799 uint64_t Idx = Op.getConstantOperandVal(1);
5800 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
5801 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
5802 return isGuaranteedNotToBeUndefOrPoison(Src, DemandedSrcElts, Kind,
5803 Depth + 1);
5804 }
5805
5806 case ISD::INSERT_SUBVECTOR: {
5807 if (Op.getValueType().isScalableVector())
5808 break;
5809 SDValue Src = Op.getOperand(0);
5810 SDValue Sub = Op.getOperand(1);
5811 uint64_t Idx = Op.getConstantOperandVal(2);
5812 unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
5813 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
5814 APInt DemandedSrcElts = DemandedElts;
5815 DemandedSrcElts.clearBits(Idx, Idx + NumSubElts);
5816
5817 if (!!DemandedSubElts && !isGuaranteedNotToBeUndefOrPoison(
5818 Sub, DemandedSubElts, Kind, Depth + 1))
5819 return false;
5820 if (!!DemandedSrcElts && !isGuaranteedNotToBeUndefOrPoison(
5821 Src, DemandedSrcElts, Kind, Depth + 1))
5822 return false;
5823 return true;
5824 }
5825
5827 SDValue Src = Op.getOperand(0);
5828 auto *IndexC = dyn_cast<ConstantSDNode>(Op.getOperand(1));
5829 EVT SrcVT = Src.getValueType();
5830 if (SrcVT.isFixedLengthVector() && IndexC &&
5831 IndexC->getAPIntValue().ult(SrcVT.getVectorNumElements())) {
5832 APInt DemandedSrcElts = APInt::getOneBitSet(SrcVT.getVectorNumElements(),
5833 IndexC->getZExtValue());
5834 return isGuaranteedNotToBeUndefOrPoison(Src, DemandedSrcElts, Kind,
5835 Depth + 1);
5836 }
5837 break;
5838 }
5839
5841 SDValue InVec = Op.getOperand(0);
5842 SDValue InVal = Op.getOperand(1);
5843 SDValue EltNo = Op.getOperand(2);
5844 EVT VT = InVec.getValueType();
5845 auto *IndexC = dyn_cast<ConstantSDNode>(EltNo);
5846 if (IndexC && VT.isFixedLengthVector() &&
5847 IndexC->getAPIntValue().ult(VT.getVectorNumElements())) {
5848 if (DemandedElts[IndexC->getZExtValue()] &&
5849 !isGuaranteedNotToBeUndefOrPoison(InVal, Kind, Depth + 1))
5850 return false;
5851 APInt InVecDemandedElts = DemandedElts;
5852 InVecDemandedElts.clearBit(IndexC->getZExtValue());
5853 if (!!InVecDemandedElts &&
5855 peekThroughInsertVectorElt(InVec, InVecDemandedElts),
5856 InVecDemandedElts, Kind, Depth + 1))
5857 return false;
5858 return true;
5859 }
5860 break;
5861 }
5862
5864 // Check upper (known poison) elements.
5865 if (DemandedElts.ugt(1) && includesPoison(Kind))
5866 return false;
5867 // Check element zero.
5868 if (DemandedElts[0] &&
5869 !isGuaranteedNotToBeUndefOrPoison(Op.getOperand(0), Kind, Depth + 1))
5870 return false;
5871 return true;
5872
5873 case ISD::SPLAT_VECTOR:
5874 return isGuaranteedNotToBeUndefOrPoison(Op.getOperand(0), Kind, Depth + 1);
5875
5876 case ISD::SELECT: {
5877 return !canCreateUndefOrPoison(Op, DemandedElts, Kind,
5878 /*ConsiderFlags*/ true, Depth) &&
5879 isGuaranteedNotToBeUndefOrPoison(Op.getOperand(0), Kind,
5880 Depth + 1) &&
5881 isGuaranteedNotToBeUndefOrPoison(Op.getOperand(1), DemandedElts,
5882 Kind, Depth + 1) &&
5883 isGuaranteedNotToBeUndefOrPoison(Op.getOperand(2), DemandedElts,
5884 Kind, Depth + 1);
5885 }
5886
5887 case ISD::VECTOR_SHUFFLE: {
5888 APInt DemandedLHS, DemandedRHS;
5889 auto *SVN = cast<ShuffleVectorSDNode>(Op);
5890 if (!getShuffleDemandedElts(DemandedElts.getBitWidth(), SVN->getMask(),
5891 DemandedElts, DemandedLHS, DemandedRHS,
5892 /*AllowUndefElts=*/false))
5893 return false;
5894 if (!DemandedLHS.isZero() &&
5895 !isGuaranteedNotToBeUndefOrPoison(Op.getOperand(0), DemandedLHS, Kind,
5896 Depth + 1))
5897 return false;
5898 if (!DemandedRHS.isZero() &&
5899 !isGuaranteedNotToBeUndefOrPoison(Op.getOperand(1), DemandedRHS, Kind,
5900 Depth + 1))
5901 return false;
5902 return true;
5903 }
5904
5905 case ISD::SHL:
5906 case ISD::SRL:
5907 case ISD::SRA:
5908 // Shift amount operand is checked by canCreateUndefOrPoison. So it is
5909 // enough to check operand 0 if Op can't create undef/poison.
5910 return !canCreateUndefOrPoison(Op, DemandedElts, Kind,
5911 /*ConsiderFlags*/ true, Depth) &&
5912 isGuaranteedNotToBeUndefOrPoison(Op.getOperand(0), DemandedElts,
5913 Kind, Depth + 1);
5914
5915 case ISD::BSWAP:
5916 case ISD::CTPOP:
5917 case ISD::BITREVERSE:
5918 case ISD::AND:
5919 case ISD::OR:
5920 case ISD::XOR:
5921 case ISD::ADD:
5922 case ISD::SUB:
5923 case ISD::MUL:
5924 case ISD::SADDSAT:
5925 case ISD::UADDSAT:
5926 case ISD::SSUBSAT:
5927 case ISD::USUBSAT:
5928 case ISD::SSHLSAT:
5929 case ISD::USHLSAT:
5930 case ISD::SMIN:
5931 case ISD::SMAX:
5932 case ISD::UMIN:
5933 case ISD::UMAX:
5934 case ISD::ZERO_EXTEND:
5935 case ISD::SIGN_EXTEND:
5936 case ISD::ANY_EXTEND:
5937 case ISD::TRUNCATE:
5938 case ISD::VSELECT: {
5939 // If Op can't create undef/poison and none of its operands are undef/poison
5940 // then Op is never undef/poison. A difference from the more common check
5941 // below, outside the switch, is that we handle elementwise operations for
5942 // which the DemandedElts mask is valid for all operands here.
5943 return !canCreateUndefOrPoison(Op, DemandedElts, Kind,
5944 /*ConsiderFlags*/ true, Depth) &&
5945 all_of(Op->ops(), [&](SDValue V) {
5946 return isGuaranteedNotToBeUndefOrPoison(V, DemandedElts, Kind,
5947 Depth + 1);
5948 });
5949 }
5950
5951 case ISD::LOAD: {
5952 // If we're loading an unindexed constant pool, check if the constant
5953 // contains poison/undef - skip ANYEXT loads.
5954 // TODO: DemandedElts and type size mismatch handling.
5955 auto *LD = cast<LoadSDNode>(Op);
5956 if (ISD::isUNINDEXEDLoad(LD) && !ISD::isEXTLoad(LD)) {
5957 if (const Constant *Cst = TLI->getTargetConstantFromLoad(LD)) {
5958 // TODO: expose isGuaranteedNotToBeUndefOrPoison(UndefPoisonKind)
5959 if (includesPoison(Kind) && includesUndef(Kind))
5960 return ::isGuaranteedNotToBeUndefOrPoison(Cst);
5961 if (includesPoison(Kind))
5962 return ::isGuaranteedNotToBePoison(Cst);
5963 assert(includesUndef(Kind) && "UndefOnly expected");
5964 return ::isGuaranteedNotToBeUndef(Cst);
5965 }
5966 }
5967 break;
5968 }
5969
5970 // TODO: Search for noundef attributes from library functions.
5971
5972 // TODO: Pointers dereferenced by ISD::LOAD/STORE ops are noundef.
5973
5974 default:
5975 // Allow the target to implement this method for its nodes.
5976 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
5977 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID)
5978 return TLI->isGuaranteedNotToBeUndefOrPoisonForTargetNode(
5979 Op, DemandedElts, *this, Kind, Depth);
5980 break;
5981 }
5982
5983 // If Op can't create undef/poison and none of its operands are undef/poison
5984 // then Op is never undef/poison.
5985 // NOTE: TargetNodes can handle this in themselves in
5986 // isGuaranteedNotToBeUndefOrPoisonForTargetNode or let
5987 // TargetLowering::isGuaranteedNotToBeUndefOrPoisonForTargetNode handle it.
5988 return !canCreateUndefOrPoison(Op, Kind, /*ConsiderFlags*/ true, Depth) &&
5989 all_of(Op->ops(), [&](SDValue V) {
5990 return isGuaranteedNotToBeUndefOrPoison(V, Kind, Depth + 1);
5991 });
5992}
5993
5995 bool ConsiderFlags,
5996 unsigned Depth) const {
5997 APInt DemandedElts = getDemandAllEltsMask(Op);
5998 return canCreateUndefOrPoison(Op, DemandedElts, Kind, ConsiderFlags, Depth);
5999}
6000
6002 UndefPoisonKind Kind,
6003 bool ConsiderFlags,
6004 unsigned Depth) const {
6005 if (ConsiderFlags && includesPoison(Kind) && Op->hasPoisonGeneratingFlags())
6006 return true;
6007
6008 unsigned Opcode = Op.getOpcode();
6009 switch (Opcode) {
6010 case ISD::AssertSext:
6011 case ISD::AssertZext:
6012 case ISD::AssertAlign:
6014 // Assertion nodes can create poison if the assertion fails.
6015 return includesPoison(Kind);
6016
6017 case ISD::FREEZE:
6021 case ISD::SADDSAT:
6022 case ISD::UADDSAT:
6023 case ISD::SSUBSAT:
6024 case ISD::USUBSAT:
6025 case ISD::MULHU:
6026 case ISD::MULHS:
6027 case ISD::AVGFLOORS:
6028 case ISD::AVGFLOORU:
6029 case ISD::AVGCEILS:
6030 case ISD::AVGCEILU:
6031 case ISD::AVGSUBFLOORS:
6032 case ISD::AVGSUBFLOORU:
6033 case ISD::ABDU:
6034 case ISD::ABDS:
6035 case ISD::SMIN:
6036 case ISD::SMAX:
6037 case ISD::SCMP:
6038 case ISD::UMIN:
6039 case ISD::UMAX:
6040 case ISD::UCMP:
6041 case ISD::AND:
6042 case ISD::XOR:
6043 case ISD::ROTL:
6044 case ISD::ROTR:
6045 case ISD::FSHL:
6046 case ISD::FSHR:
6047 case ISD::BSWAP:
6048 case ISD::CTTZ:
6049 case ISD::CTLZ:
6050 case ISD::CTLS:
6051 case ISD::CTPOP:
6052 case ISD::BITREVERSE:
6053 case ISD::PARITY:
6054 case ISD::SIGN_EXTEND:
6055 case ISD::TRUNCATE:
6059 case ISD::BITCAST:
6060 case ISD::BUILD_VECTOR:
6061 case ISD::BUILD_PAIR:
6062 case ISD::SPLAT_VECTOR:
6063 case ISD::FABS:
6064 case ISD::FCEIL:
6065 case ISD::FFLOOR:
6066 case ISD::FTRUNC:
6067 case ISD::FRINT:
6068 case ISD::FNEARBYINT:
6069 case ISD::FROUND:
6070 case ISD::FROUNDEVEN:
6071 return false;
6072
6073 case ISD::ABS:
6074 // ISD::ABS defines abs(INT_MIN) -> INT_MIN and never generates poison.
6075 // Different to Intrinsic::abs.
6076 return false;
6078 // ABS_MIN_POISON may produce poison if the input is INT_MIN.
6079 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1) <= 1;
6080
6081 case ISD::ADDC:
6082 case ISD::SUBC:
6083 case ISD::ADDE:
6084 case ISD::SUBE:
6085 case ISD::SADDO:
6086 case ISD::SSUBO:
6087 case ISD::SMULO:
6088 case ISD::SADDO_CARRY:
6089 case ISD::SSUBO_CARRY:
6090 case ISD::UADDO:
6091 case ISD::USUBO:
6092 case ISD::UMULO:
6093 case ISD::UADDO_CARRY:
6094 case ISD::USUBO_CARRY:
6095 // No poison on result or overflow flags.
6096 return false;
6097
6098 case ISD::SELECT_CC:
6099 case ISD::SETCC: {
6100 // Integer setcc cannot create undef or poison.
6101 if (Op.getOperand(0).getValueType().isInteger())
6102 return false;
6103
6104 // FP compares are more complicated. They can create poison for nan/infinity
6105 // based on options and flags. The options and flags also cause special
6106 // nonan condition codes to be used. Those condition codes may be preserved
6107 // even if the nonan flag is dropped somewhere.
6108 unsigned CCOp = Opcode == ISD::SETCC ? 2 : 4;
6109 ISD::CondCode CCCode = Op.getOperandCondCode(CCOp);
6110 return (unsigned)CCCode & 0x10U;
6111 }
6112
6113 case ISD::OR:
6114 case ISD::ZERO_EXTEND:
6115 case ISD::SELECT:
6116 case ISD::VSELECT:
6117 case ISD::ADD:
6118 case ISD::SUB:
6119 case ISD::MUL:
6120 case ISD::FNEG:
6121 case ISD::FADD:
6122 case ISD::FSUB:
6123 case ISD::FMUL:
6124 case ISD::FDIV:
6125 case ISD::FREM:
6126 case ISD::FCOPYSIGN:
6127 case ISD::FMA:
6128 case ISD::FMAD:
6129 case ISD::FMULADD:
6130 case ISD::FP_EXTEND:
6131 case ISD::FMINNUM:
6132 case ISD::FMAXNUM:
6133 case ISD::FMINNUM_IEEE:
6134 case ISD::FMAXNUM_IEEE:
6135 case ISD::FMINIMUM:
6136 case ISD::FMAXIMUM:
6137 case ISD::FMINIMUMNUM:
6138 case ISD::FMAXIMUMNUM:
6144 // No poison except from flags (which is handled above)
6145 return false;
6146
6147 case ISD::SHL:
6148 case ISD::SRL:
6149 case ISD::SRA:
6150 // If the max shift amount isn't in range, then the shift can
6151 // create poison.
6152 return includesPoison(Kind) &&
6153 !getValidMaximumShiftAmount(Op, DemandedElts, Depth + 1);
6154
6157 // If the amount is zero then the result will be poison.
6158 // TODO: Add isKnownNeverZero DemandedElts handling.
6159 return includesPoison(Kind) &&
6160 !isKnownNeverZero(Op.getOperand(0), Depth + 1);
6161
6163 // Check if we demand any upper (poison) elements.
6164 return includesPoison(Kind) && DemandedElts.ugt(1);
6165
6168 // Ensure that the element index is in bounds.
6169 if (includesPoison(Kind)) {
6170 EVT VecVT = Op.getOperand(0).getValueType();
6171 SDValue Idx = Op.getOperand(Opcode == ISD::INSERT_VECTOR_ELT ? 2 : 1);
6172 KnownBits KnownIdx = computeKnownBits(Idx, Depth + 1);
6173 return KnownIdx.getMaxValue().uge(VecVT.getVectorMinNumElements());
6174 }
6175 return false;
6176 }
6177
6178 case ISD::VECTOR_SHUFFLE: {
6179 // Check for any demanded shuffle element that is undef.
6180 auto *SVN = cast<ShuffleVectorSDNode>(Op);
6181 for (auto [Idx, Elt] : enumerate(SVN->getMask()))
6182 if (Elt < 0 && DemandedElts[Idx])
6183 return true;
6184 return false;
6185 }
6186
6188 return false;
6189
6190 default:
6191 // Allow the target to implement this method for its nodes.
6192 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
6193 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID)
6194 return TLI->canCreateUndefOrPoisonForTargetNode(
6195 Op, DemandedElts, *this, Kind, ConsiderFlags, Depth);
6196 break;
6197 }
6198
6199 // Be conservative and return true.
6200 return true;
6201}
6202
6203bool SelectionDAG::isADDLike(SDValue Op, bool NoWrap) const {
6204 unsigned Opcode = Op.getOpcode();
6205 if (Opcode == ISD::OR)
6206 return Op->getFlags().hasDisjoint() ||
6207 haveNoCommonBitsSet(Op.getOperand(0), Op.getOperand(1));
6208 if (Opcode == ISD::XOR)
6209 return !NoWrap && isMinSignedConstant(Op.getOperand(1));
6210 return false;
6211}
6212
6214 return Op.getNumOperands() == 2 && isa<ConstantSDNode>(Op.getOperand(1)) &&
6215 (Op.isAnyAdd() || isADDLike(Op));
6216}
6217
6219 FPClassTest InterestedClasses,
6220 unsigned Depth) const {
6221 APInt DemandedElts = getDemandAllEltsMask(Op);
6222 return computeKnownFPClass(Op, DemandedElts, InterestedClasses, Depth);
6223}
6224
6226 const APInt &DemandedElts,
6227 FPClassTest InterestedClasses,
6228 unsigned Depth) const {
6230
6231 if (const auto *CFP = dyn_cast<ConstantFPSDNode>(Op))
6232 return KnownFPClass(CFP->getValueAPF());
6233
6234 if (Depth >= MaxRecursionDepth)
6235 return Known;
6236
6237 if (Op.getOpcode() == ISD::UNDEF)
6238 return Known;
6239
6240 EVT VT = Op.getValueType();
6241 assert(VT.isFloatingPoint() && "Computing KnownFPClass on non-FP op!");
6242 assert((!VT.isFixedLengthVector() ||
6243 DemandedElts.getBitWidth() == VT.getVectorNumElements()) &&
6244 "Unexpected vector size");
6245
6246 if (!DemandedElts)
6247 return Known;
6248
6249 unsigned Opcode = Op.getOpcode();
6250 switch (Opcode) {
6251 case ISD::POISON: {
6253 break;
6254 }
6255 case ISD::FNEG: {
6256 Known = computeKnownFPClass(Op.getOperand(0), DemandedElts,
6257 InterestedClasses, Depth + 1);
6258 Known.fneg();
6259 break;
6260 }
6261 case ISD::BUILD_VECTOR: {
6262 assert(!VT.isScalableVector());
6263 bool First = true;
6264 for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) {
6265 if (!DemandedElts[I])
6266 continue;
6267
6268 if (First) {
6269 Known =
6270 computeKnownFPClass(Op.getOperand(I), InterestedClasses, Depth + 1);
6271 First = false;
6272 } else {
6273 Known |=
6274 computeKnownFPClass(Op.getOperand(I), InterestedClasses, Depth + 1);
6275 }
6276
6277 if (Known.isUnknown())
6278 break;
6279 }
6280 break;
6281 }
6283 SDValue Src = Op.getOperand(0);
6284 auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6285 EVT SrcVT = Src.getValueType();
6286 if (SrcVT.isFixedLengthVector() && CIdx) {
6287 if (CIdx->getAPIntValue().ult(SrcVT.getVectorNumElements())) {
6288 APInt DemandedSrcElts = APInt::getOneBitSet(
6289 SrcVT.getVectorNumElements(), CIdx->getZExtValue());
6290 Known = computeKnownFPClass(Src, DemandedSrcElts, InterestedClasses,
6291 Depth + 1);
6292 } else {
6293 // Out of bounds index is poison.
6295 }
6296 } else {
6297 Known = computeKnownFPClass(Src, InterestedClasses, Depth + 1);
6298 }
6299 break;
6300 }
6301 case ISD::SPLAT_VECTOR: {
6302 Known = computeKnownFPClass(Op.getOperand(0), InterestedClasses, Depth + 1);
6303 break;
6304 }
6305 case ISD::BITCAST: {
6306 // FIXME: It should not be necessary to check for an elementwise bitcast.
6307 // If a bitcast is not elementwise between vector / scalar types,
6308 // computeKnownBits already splices the known bits of the source elements
6309 // appropriately so as to line up with the bits of the result's demanded
6310 // elements.
6311 EVT SrcVT = Op.getOperand(0).getValueType();
6312 if (VT.isScalableVector() || SrcVT.isScalableVector())
6313 break;
6314 unsigned VTNumElts = VT.isVector() ? VT.getVectorNumElements() : 1;
6315 unsigned SrcVTNumElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1;
6316 if (VTNumElts != SrcVTNumElts)
6317 break;
6318
6319 KnownBits Bits = computeKnownBits(Op, DemandedElts, Depth + 1);
6321 break;
6322 }
6323 case ISD::FABS: {
6324 Known = computeKnownFPClass(Op.getOperand(0), DemandedElts,
6325 InterestedClasses, Depth + 1);
6326 Known.fabs();
6327 break;
6328 }
6329 case ISD::FCOPYSIGN: {
6330 Known = computeKnownFPClass(Op.getOperand(0), DemandedElts,
6331 InterestedClasses, Depth + 1);
6332 KnownFPClass KnownSign = computeKnownFPClass(Op.getOperand(1), DemandedElts,
6333 InterestedClasses, Depth + 1);
6334 Known.copysign(KnownSign);
6335 break;
6336 }
6337 case ISD::AssertNoFPClass: {
6338 Known = computeKnownFPClass(Op.getOperand(0), DemandedElts,
6339 InterestedClasses, Depth + 1);
6340 FPClassTest AssertedClasses =
6341 static_cast<FPClassTest>(Op->getConstantOperandVal(1));
6342 Known.setKnownFPClasses(Known.getKnownFPClasses() & ~AssertedClasses);
6343 break;
6344 }
6346 SDValue Src = Op.getOperand(0);
6347 EVT SrcVT = Src.getValueType();
6348 if (SrcVT.isFixedLengthVector()) {
6349 unsigned Idx = Op.getConstantOperandVal(1);
6350 unsigned NumSrcElts = SrcVT.getVectorNumElements();
6351
6352 APInt DemandedSrcElts = DemandedElts.zextOrTrunc(NumSrcElts).shl(Idx);
6353 Known = computeKnownFPClass(Src, DemandedSrcElts, InterestedClasses,
6354 Depth + 1);
6355 } else {
6356 Known = computeKnownFPClass(Src, InterestedClasses, Depth + 1);
6357 }
6358 break;
6359 }
6360 case ISD::INSERT_SUBVECTOR: {
6361 SDValue BaseVector = Op.getOperand(0);
6362 SDValue SubVector = Op.getOperand(1);
6363 EVT BaseVT = BaseVector.getValueType();
6364 if (BaseVT.isFixedLengthVector()) {
6365 unsigned Idx = Op.getConstantOperandVal(2);
6366 unsigned NumBaseElts = BaseVT.getVectorNumElements();
6367 unsigned NumSubElts = SubVector.getValueType().getVectorNumElements();
6368
6369 APInt DemandedMask =
6370 APInt::getBitsSet(NumBaseElts, Idx, Idx + NumSubElts);
6371 APInt DemandedSrcElts = DemandedElts & ~DemandedMask;
6372 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
6373
6374 if (!DemandedSrcElts.isZero())
6375 Known = computeKnownFPClass(BaseVector, DemandedSrcElts,
6376 InterestedClasses, Depth + 1);
6377 if (!DemandedSubElts.isZero()) {
6379 SubVector, DemandedSubElts, InterestedClasses, Depth + 1);
6380 Known = DemandedSrcElts.isZero() ? SubKnown : (Known | SubKnown);
6381 }
6382 } else {
6383 Known = computeKnownFPClass(SubVector, InterestedClasses, Depth + 1);
6384 if (!Known.isUnknown())
6385 Known |= computeKnownFPClass(BaseVector, InterestedClasses, Depth + 1);
6386 }
6387 break;
6388 }
6389 case ISD::SELECT:
6390 case ISD::VSELECT: {
6391 // TODO: Add adjustKnownFPClassForSelectArm clamp recognition as in
6392 // IR-level ValueTracking.
6393 KnownFPClass KnownFalseClass = computeKnownFPClass(
6394 Op.getOperand(2), DemandedElts, InterestedClasses, Depth + 1);
6395 if (KnownFalseClass.isUnknown())
6396 break;
6397 KnownFPClass KnownTrueClass = computeKnownFPClass(
6398 Op.getOperand(1), DemandedElts, InterestedClasses, Depth + 1);
6399 Known = KnownTrueClass.intersectWith(KnownFalseClass);
6400 break;
6401 }
6402 default:
6403 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
6404 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID) {
6405 TLI->computeKnownFPClassForTargetNode(Op, Known, DemandedElts, *this,
6406 Depth);
6407 }
6408 break;
6409 }
6410
6411 return Known;
6412}
6413
6415 unsigned Depth) const {
6416 APInt DemandedElts = getDemandAllEltsMask(Op);
6417 return isKnownNeverNaN(Op, DemandedElts, SNaN, Depth);
6418}
6419
6421 bool SNaN, unsigned Depth) const {
6422 assert(!DemandedElts.isZero() && "No demanded elements");
6423
6424 // If we're told that NaNs won't happen, assume they won't.
6425 if (Op->getFlags().hasNoNaNs())
6426 return true;
6427
6428 if (Depth >= MaxRecursionDepth)
6429 return false; // Limit search depth.
6430
6431 unsigned Opcode = Op.getOpcode();
6432 switch (Opcode) {
6433 case ISD::FADD:
6434 case ISD::FSUB:
6435 case ISD::FMUL:
6436 case ISD::FDIV:
6437 case ISD::FREM:
6438 case ISD::FSIN:
6439 case ISD::FCOS:
6440 case ISD::FTAN:
6441 case ISD::FASIN:
6442 case ISD::FACOS:
6443 case ISD::FATAN:
6444 case ISD::FATAN2:
6445 case ISD::FSINH:
6446 case ISD::FCOSH:
6447 case ISD::FTANH:
6448 case ISD::FMA:
6449 case ISD::FMULADD:
6450 case ISD::FMAD: {
6451 if (SNaN)
6452 return true;
6453 // TODO: Need isKnownNeverInfinity
6454 return false;
6455 }
6456 case ISD::FCANONICALIZE:
6457 case ISD::FEXP:
6458 case ISD::FEXP2:
6459 case ISD::FEXP10:
6460 case ISD::FTRUNC:
6461 case ISD::FFLOOR:
6462 case ISD::FCEIL:
6463 case ISD::FROUND:
6464 case ISD::FROUNDEVEN:
6465 case ISD::LROUND:
6466 case ISD::LLROUND:
6467 case ISD::FRINT:
6468 case ISD::LRINT:
6469 case ISD::LLRINT:
6470 case ISD::FNEARBYINT:
6471 case ISD::FLDEXP: {
6472 if (SNaN)
6473 return true;
6474 return isKnownNeverNaN(Op.getOperand(0), DemandedElts, SNaN, Depth + 1);
6475 }
6476 case ISD::FABS:
6477 case ISD::FNEG:
6478 case ISD::FCOPYSIGN: {
6479 return isKnownNeverNaN(Op.getOperand(0), DemandedElts, SNaN, Depth + 1);
6480 }
6481 case ISD::SELECT:
6482 return isKnownNeverNaN(Op.getOperand(1), DemandedElts, SNaN, Depth + 1) &&
6483 isKnownNeverNaN(Op.getOperand(2), DemandedElts, SNaN, Depth + 1);
6484 case ISD::FP_EXTEND:
6485 case ISD::FP_ROUND: {
6486 if (SNaN)
6487 return true;
6488 return isKnownNeverNaN(Op.getOperand(0), DemandedElts, SNaN, Depth + 1);
6489 }
6490 case ISD::SINT_TO_FP:
6491 case ISD::UINT_TO_FP:
6492 return true;
6493 case ISD::FSQRT: // Need is known positive
6494 case ISD::FLOG:
6495 case ISD::FLOG2:
6496 case ISD::FLOG10:
6497 case ISD::FPOWI:
6498 case ISD::FPOW: {
6499 if (SNaN)
6500 return true;
6501 // TODO: Refine on operand
6502 return false;
6503 }
6504 case ISD::FMINNUM:
6505 case ISD::FMAXNUM:
6506 case ISD::FMINIMUMNUM:
6507 case ISD::FMAXIMUMNUM: {
6508 // Only one needs to be known not-nan, since it will be returned if the
6509 // other ends up being one.
6510 return isKnownNeverNaN(Op.getOperand(0), DemandedElts, SNaN, Depth + 1) ||
6511 isKnownNeverNaN(Op.getOperand(1), DemandedElts, SNaN, Depth + 1);
6512 }
6513 case ISD::FMINNUM_IEEE:
6514 case ISD::FMAXNUM_IEEE: {
6515 if (SNaN)
6516 return true;
6517 // This can return a NaN if either operand is an sNaN, or if both operands
6518 // are NaN.
6519 return (isKnownNeverNaN(Op.getOperand(0), DemandedElts, false, Depth + 1) &&
6520 isKnownNeverSNaN(Op.getOperand(1), DemandedElts, Depth + 1)) ||
6521 (isKnownNeverNaN(Op.getOperand(1), DemandedElts, false, Depth + 1) &&
6522 isKnownNeverSNaN(Op.getOperand(0), DemandedElts, Depth + 1));
6523 }
6524 case ISD::FMINIMUM:
6525 case ISD::FMAXIMUM: {
6526 // TODO: Does this quiet or return the origina NaN as-is?
6527 return isKnownNeverNaN(Op.getOperand(0), DemandedElts, SNaN, Depth + 1) &&
6528 isKnownNeverNaN(Op.getOperand(1), DemandedElts, SNaN, Depth + 1);
6529 }
6531 SDValue Src = Op.getOperand(0);
6532 auto *Idx = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6533 EVT SrcVT = Src.getValueType();
6534 if (SrcVT.isFixedLengthVector() && Idx &&
6535 Idx->getAPIntValue().ult(SrcVT.getVectorNumElements())) {
6536 APInt DemandedSrcElts = APInt::getOneBitSet(SrcVT.getVectorNumElements(),
6537 Idx->getZExtValue());
6538 return isKnownNeverNaN(Src, DemandedSrcElts, SNaN, Depth + 1);
6539 }
6540 return isKnownNeverNaN(Src, SNaN, Depth + 1);
6541 }
6543 SDValue Src = Op.getOperand(0);
6544 if (Src.getValueType().isFixedLengthVector()) {
6545 unsigned Idx = Op.getConstantOperandVal(1);
6546 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
6547 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
6548 return isKnownNeverNaN(Src, DemandedSrcElts, SNaN, Depth + 1);
6549 }
6550 return isKnownNeverNaN(Src, SNaN, Depth + 1);
6551 }
6552 case ISD::INSERT_SUBVECTOR: {
6553 SDValue BaseVector = Op.getOperand(0);
6554 SDValue SubVector = Op.getOperand(1);
6555 EVT BaseVectorVT = BaseVector.getValueType();
6556 if (BaseVectorVT.isFixedLengthVector()) {
6557 unsigned Idx = Op.getConstantOperandVal(2);
6558 unsigned NumBaseElts = BaseVectorVT.getVectorNumElements();
6559 unsigned NumSubElts = SubVector.getValueType().getVectorNumElements();
6560
6561 // Clear/Extract the bits at the position where the subvector will be
6562 // inserted.
6563 APInt DemandedMask =
6564 APInt::getBitsSet(NumBaseElts, Idx, Idx + NumSubElts);
6565 APInt DemandedSrcElts = DemandedElts & ~DemandedMask;
6566 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
6567
6568 bool NeverNaN = true;
6569 if (!DemandedSrcElts.isZero())
6570 NeverNaN &=
6571 isKnownNeverNaN(BaseVector, DemandedSrcElts, SNaN, Depth + 1);
6572 if (NeverNaN && !DemandedSubElts.isZero())
6573 NeverNaN &=
6574 isKnownNeverNaN(SubVector, DemandedSubElts, SNaN, Depth + 1);
6575 return NeverNaN;
6576 }
6577 return isKnownNeverNaN(BaseVector, SNaN, Depth + 1) &&
6578 isKnownNeverNaN(SubVector, SNaN, Depth + 1);
6579 }
6580 case ISD::BUILD_VECTOR: {
6581 unsigned NumElts = Op.getNumOperands();
6582 for (unsigned I = 0; I != NumElts; ++I)
6583 if (DemandedElts[I] &&
6584 !isKnownNeverNaN(Op.getOperand(I), SNaN, Depth + 1))
6585 return false;
6586 return true;
6587 }
6588 case ISD::SPLAT_VECTOR:
6589 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
6590 case ISD::AssertNoFPClass: {
6591 FPClassTest NoFPClass =
6592 static_cast<FPClassTest>(Op.getConstantOperandVal(1));
6593 if ((NoFPClass & fcNan) == fcNan)
6594 return true;
6595 if (SNaN && (NoFPClass & fcSNan) == fcSNan)
6596 return true;
6597 return isKnownNeverNaN(Op.getOperand(0), DemandedElts, SNaN, Depth + 1);
6598 }
6599 default:
6600 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
6601 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID) {
6602 return TLI->isKnownNeverNaNForTargetNode(Op, DemandedElts, *this, SNaN,
6603 Depth);
6604 }
6605 break;
6606 }
6607
6608 FPClassTest NanMask = SNaN ? fcSNan : fcNan;
6609 KnownFPClass Known = computeKnownFPClass(Op, DemandedElts, NanMask, Depth);
6610 return Known.isKnownNever(NanMask);
6611}
6612
6614 APInt DemandedElts = getDemandAllEltsMask(Op);
6615 return isKnownNeverLogicalZero(Op, DemandedElts, Depth);
6616}
6617
6619 const APInt &DemandedElts,
6620 unsigned Depth) const {
6621 assert(!DemandedElts.isZero() && "No demanded elements");
6622 EVT VT = Op.getValueType();
6624 computeKnownFPClass(Op, DemandedElts, fcZero | fcSubnormal, Depth);
6625 return Known.isKnownNeverLogicalZero(getDenormalMode(VT));
6626}
6627
6629 APInt DemandedElts = getDemandAllEltsMask(Op);
6630 return isKnownNeverZero(Op, DemandedElts, Depth);
6631}
6632
6634 unsigned Depth) const {
6635 if (Depth >= MaxRecursionDepth)
6636 return false; // Limit search depth.
6637
6638 EVT OpVT = Op.getValueType();
6639 unsigned BitWidth = OpVT.getScalarSizeInBits();
6640
6641 assert(!Op.getValueType().isFloatingPoint() &&
6642 "Floating point types unsupported - use isKnownNeverLogicalZero");
6643
6644 // If the value is a constant, we can obviously see if it is a zero or not.
6645 auto IsNeverZero = [BitWidth](const ConstantSDNode *C) {
6646 APInt V = C->getAPIntValue().zextOrTrunc(BitWidth);
6647 return !V.isZero();
6648 };
6649
6650 if (ISD::matchUnaryPredicate(Op, DemandedElts, IsNeverZero,
6651 /*AllowUndefs=*/false, /*AllowTruncation=*/true))
6652 return true;
6653
6654 // TODO: Recognize more cases here. Most of the cases are also incomplete to
6655 // some degree.
6656 switch (Op.getOpcode()) {
6657 default:
6658 break;
6659
6661 SDValue InVec = Op.getOperand(0);
6662 SDValue EltNo = Op.getOperand(1);
6663 EVT VecVT = InVec.getValueType();
6664
6665 // Skip scalable vectors or implicit extensions.
6666 if (VecVT.isScalableVector() ||
6667 OpVT.getScalarSizeInBits() != VecVT.getScalarSizeInBits())
6668 break;
6669
6670 // If we know the element index, just demand that vector element, else for
6671 // an unknown element index, ignore DemandedElts and demand them all.
6672 const unsigned NumSrcElts = VecVT.getVectorNumElements();
6673 APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
6674 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
6675 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
6676 DemandedSrcElts =
6677 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
6678
6679 return isKnownNeverZero(InVec, DemandedSrcElts, Depth + 1);
6680 }
6681
6682 case ISD::OR:
6683 return isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1) ||
6684 isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6685
6686 case ISD::VSELECT:
6687 case ISD::SELECT:
6688 return isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1) &&
6689 isKnownNeverZero(Op.getOperand(2), DemandedElts, Depth + 1);
6690
6691 case ISD::SHL: {
6692 if (Op->getFlags().hasNoSignedWrap() || Op->getFlags().hasNoUnsignedWrap())
6693 return isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6694 KnownBits ValKnown =
6695 computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
6696 // 1 << X is never zero.
6697 if (ValKnown.One[0])
6698 return true;
6699 // If max shift cnt of known ones is non-zero, result is non-zero.
6700 APInt MaxCnt = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1)
6701 .getMaxValue();
6702 if (MaxCnt.ult(ValKnown.getBitWidth()) &&
6703 !ValKnown.One.shl(MaxCnt).isZero())
6704 return true;
6705 break;
6706 }
6707
6708 case ISD::VECTOR_SHUFFLE: {
6709 if (Op.getValueType().isScalableVector())
6710 return false;
6711
6712 unsigned NumElts = DemandedElts.getBitWidth();
6713
6714 // All demanded elements from LHS and RHS must be known non-zero.
6715 // Demanded elements with undef shuffle mask elements are unknown.
6716
6717 APInt DemandedLHS, DemandedRHS;
6718 auto *SVN = cast<ShuffleVectorSDNode>(Op);
6719 assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
6720 if (!getShuffleDemandedElts(NumElts, SVN->getMask(), DemandedElts,
6721 DemandedLHS, DemandedRHS))
6722 return false;
6723
6724 return (!DemandedLHS ||
6725 isKnownNeverZero(Op.getOperand(0), DemandedLHS, Depth + 1)) &&
6726 (!DemandedRHS ||
6727 isKnownNeverZero(Op.getOperand(1), DemandedRHS, Depth + 1));
6728 }
6729
6730 case ISD::UADDSAT:
6731 case ISD::UMAX:
6732 return isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1) ||
6733 isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6734
6735 case ISD::UMIN:
6736 return isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1) &&
6737 isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6738
6739 // For smin/smax: If either operand is known negative/positive
6740 // respectively we don't need the other to be known at all.
6741 case ISD::SMAX: {
6742 KnownBits Op1 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
6743 if (Op1.isStrictlyPositive())
6744 return true;
6745
6746 KnownBits Op0 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
6747 if (Op0.isStrictlyPositive())
6748 return true;
6749
6750 if (Op1.isNonZero() && Op0.isNonZero())
6751 return true;
6752
6753 return isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1) &&
6754 isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6755 }
6756 case ISD::SMIN: {
6757 KnownBits Op1 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
6758 if (Op1.isNegative())
6759 return true;
6760
6761 KnownBits Op0 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
6762 if (Op0.isNegative())
6763 return true;
6764
6765 if (Op1.isNonZero() && Op0.isNonZero())
6766 return true;
6767
6768 return isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1) &&
6769 isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6770 }
6771
6772 case ISD::ROTL:
6773 case ISD::ROTR:
6774 case ISD::BITREVERSE:
6775 case ISD::BSWAP:
6776 case ISD::CTPOP:
6777 case ISD::ABS:
6779 return isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6780
6781 case ISD::SRA:
6782 case ISD::SRL: {
6783 if (Op->getFlags().hasExact())
6784 return isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6785 KnownBits ValKnown =
6786 computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
6787 if (ValKnown.isNegative())
6788 return true;
6789 // If max shift cnt of known ones is non-zero, result is non-zero.
6790 APInt MaxCnt = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1)
6791 .getMaxValue();
6792 if (MaxCnt.ult(ValKnown.getBitWidth()) &&
6793 !ValKnown.One.lshr(MaxCnt).isZero())
6794 return true;
6795 break;
6796 }
6797 case ISD::UDIV:
6798 case ISD::SDIV:
6799 // div exact can only produce a zero if the dividend is zero.
6800 // TODO: For udiv this is also true if Op1 u<= Op0
6801 if (Op->getFlags().hasExact())
6802 return isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6803 break;
6804
6805 case ISD::ADD:
6806 if (Op->getFlags().hasNoUnsignedWrap())
6807 if (isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1) ||
6808 isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1))
6809 return true;
6810 // TODO: There are a lot more cases we can prove for add.
6811 break;
6812
6813 case ISD::SUB: {
6814 if (isNullConstant(Op.getOperand(0)))
6815 return isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1);
6816
6817 std::optional<bool> ne = KnownBits::ne(
6818 computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1),
6819 computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1));
6820 return ne && *ne;
6821 }
6822
6823 case ISD::MUL:
6824 if (Op->getFlags().hasNoSignedWrap() || Op->getFlags().hasNoUnsignedWrap())
6825 if (isKnownNeverZero(Op.getOperand(1), Depth + 1) &&
6826 isKnownNeverZero(Op.getOperand(0), Depth + 1))
6827 return true;
6828 break;
6829
6830 case ISD::ZERO_EXTEND:
6831 case ISD::SIGN_EXTEND:
6832 return isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6833 case ISD::VSCALE: {
6835 const APInt &Multiplier = Op.getConstantOperandAPInt(0);
6836 ConstantRange CR =
6837 getVScaleRange(&F, Op.getScalarValueSizeInBits()).multiply(Multiplier);
6838 if (!CR.contains(APInt(CR.getBitWidth(), 0)))
6839 return true;
6840 break;
6841 }
6842 }
6843
6844 return computeKnownBits(Op, DemandedElts, Depth).isNonZero();
6845}
6846
6849 return !C1->isNegative();
6850
6851 switch (Op.getOpcode()) {
6852 case ISD::FABS:
6853 case ISD::FEXP:
6854 case ISD::FEXP2:
6855 case ISD::FEXP10:
6856 return true;
6857 default:
6858 return false;
6859 }
6860
6861 llvm_unreachable("covered opcode switch");
6862}
6863
6864/// Return true if the standard nsz semantics may not apply for this opcode.
6865/// Opcode is assumed to take float inputs.
6866/// FIXME: Target min/max nodes (e.g. X86ISD::FMINC) aren't included.
6867static bool hasSpecialNszSemantics(unsigned Opcode) {
6868 switch (Opcode) {
6869 case ISD::FMINNUM:
6870 case ISD::FMAXNUM:
6871 case ISD::FMINNUM_IEEE:
6872 case ISD::FMAXNUM_IEEE:
6873 case ISD::FMINIMUM:
6874 case ISD::FMAXIMUM:
6875 case ISD::FMINIMUMNUM:
6876 case ISD::FMAXIMUMNUM:
6881 case ISD::PSEUDO_FMIN:
6882 case ISD::PSEUDO_FMAX:
6891 case ISD::VP_REDUCE_FMIN:
6892 case ISD::VP_REDUCE_FMAX:
6893 case ISD::VP_REDUCE_FMINIMUM:
6894 case ISD::VP_REDUCE_FMAXIMUM:
6895 return true;
6896 default:
6897 return false;
6898 }
6899}
6900
6902 assert(Use.getValueType().isFloatingPoint());
6903 const SDNode *User = Use.getUser();
6904 unsigned Opcode = User->getOpcode();
6905 if (User->getFlags().hasNoSignedZeros() && !hasSpecialNszSemantics(Opcode))
6906 return true;
6907
6908 unsigned OperandNo = Use.getOperandNo();
6909 // Check if this use is insensitive to the sign of zero
6910 switch (Opcode) {
6911 case ISD::SETCC:
6912 // Comparisons: IEEE-754 specifies +0.0 == -0.0.
6913 case ISD::FABS:
6914 // fabs always produces +0.0.
6915 return true;
6916 case ISD::FCOPYSIGN:
6917 // copysign overwrites the sign bit of the first operand.
6918 return OperandNo == 0;
6919 case ISD::FADD:
6920 case ISD::FSUB: {
6921 // Arithmetic with non-zero constants fixes the uncertainty around the
6922 // sign bit.
6923 SDValue Other = User->getOperand(1 - OperandNo);
6925 }
6926 case ISD::FP_TO_SINT:
6927 case ISD::FP_TO_UINT:
6928 // fp-to-int conversions normalize signed zeros.
6929 return true;
6930 case ISD::FMINNUM:
6931 case ISD::FMINNUM_IEEE:
6932 case ISD::FMINIMUM:
6933 case ISD::FMINIMUMNUM:
6934 case ISD::FMAXNUM:
6935 case ISD::FMAXNUM_IEEE:
6936 case ISD::FMAXIMUM:
6937 case ISD::FMAXIMUMNUM:
6938 case ISD::PSEUDO_FMIN:
6939 case ISD::PSEUDO_FMAX: {
6940 // If other value always beats zero, the zero can be ignored.
6941 bool IsMin = Opcode == ISD::FMINNUM || Opcode == ISD::FMINNUM_IEEE ||
6942 Opcode == ISD::FMINIMUM || Opcode == ISD::FMINIMUMNUM ||
6943 Opcode == ISD::PSEUDO_FMIN;
6944 FPClassTest AlwaysBeatsZero =
6946 SDValue Other = User->getOperand(1 - OperandNo);
6947 KnownFPClass Known = computeKnownFPClass(Other, ~AlwaysBeatsZero);
6948 return Known.isKnownNever(~AlwaysBeatsZero);
6949 }
6950 default:
6951 return false;
6952 }
6953}
6954
6956 assert(Op->getNumValues() == 1);
6957 // FIXME: Limit the amount of checked uses to not introduce a compile-time
6958 // regression. Ideally, this should be implemented as a demanded-bits
6959 // optimization that stems from the users.
6960 if (Op->use_size() > 2)
6961 return false;
6962 return all_of(Op->uses(),
6963 [&](const SDUse &Use) { return canIgnoreSignBitOfZero(Use); });
6964}
6965
6967 // Check the obvious case.
6968 if (A == B) return true;
6969
6970 // For negative and positive zero.
6973 if (CA->isZero() && CB->isZero()) return true;
6974
6975 // Otherwise they may not be equal.
6976 return false;
6977}
6978
6979// Only bits set in Mask must be negated, other bits may be arbitrary.
6981 if (isBitwiseNot(V, AllowUndefs))
6982 return V.getOperand(0);
6983
6984 // Handle any_extend (not (truncate X)) pattern, where Mask only sets
6985 // bits in the non-extended part.
6986 ConstantSDNode *MaskC = isConstOrConstSplat(Mask);
6987 if (!MaskC || V.getOpcode() != ISD::ANY_EXTEND)
6988 return SDValue();
6989 SDValue ExtArg = V.getOperand(0);
6990 if (ExtArg.getScalarValueSizeInBits() >=
6991 MaskC->getAPIntValue().getActiveBits() &&
6992 isBitwiseNot(ExtArg, AllowUndefs) &&
6993 ExtArg.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6994 ExtArg.getOperand(0).getOperand(0).getValueType() == V.getValueType())
6995 return ExtArg.getOperand(0).getOperand(0);
6996 return SDValue();
6997}
6998
7000 // Match masked merge pattern (X & ~M) op (Y & M)
7001 // Including degenerate case (X & ~M) op M
7002 auto MatchNoCommonBitsPattern = [&](SDValue Not, SDValue Mask,
7003 SDValue Other) {
7004 if (SDValue NotOperand =
7005 getBitwiseNotOperand(Not, Mask, /* AllowUndefs */ true)) {
7006 if (NotOperand->getOpcode() == ISD::ZERO_EXTEND ||
7007 NotOperand->getOpcode() == ISD::TRUNCATE)
7008 NotOperand = NotOperand->getOperand(0);
7009
7010 if (Other == NotOperand)
7011 return true;
7012 if (Other->getOpcode() == ISD::AND)
7013 return NotOperand == Other->getOperand(0) ||
7014 NotOperand == Other->getOperand(1);
7015 }
7016 return false;
7017 };
7018
7019 if (A->getOpcode() == ISD::ZERO_EXTEND || A->getOpcode() == ISD::TRUNCATE)
7020 A = A->getOperand(0);
7021
7022 if (B->getOpcode() == ISD::ZERO_EXTEND || B->getOpcode() == ISD::TRUNCATE)
7023 B = B->getOperand(0);
7024
7025 if (A->getOpcode() == ISD::AND)
7026 return MatchNoCommonBitsPattern(A->getOperand(0), A->getOperand(1), B) ||
7027 MatchNoCommonBitsPattern(A->getOperand(1), A->getOperand(0), B);
7028 return false;
7029}
7030
7031// FIXME: unify with llvm::haveNoCommonBitsSet.
7033 assert(A.getValueType() == B.getValueType() &&
7034 "Values must have the same type");
7037 return true;
7040}
7041
7042static SDValue FoldSTEP_VECTOR(const SDLoc &DL, EVT VT, SDValue Step,
7043 SelectionDAG &DAG) {
7044 if (cast<ConstantSDNode>(Step)->isZero())
7045 return DAG.getConstant(0, DL, VT);
7046
7047 return SDValue();
7048}
7049
7052 SelectionDAG &DAG) {
7053 int NumOps = Ops.size();
7054 assert(NumOps != 0 && "Can't build an empty vector!");
7055 assert(!VT.isScalableVector() &&
7056 "BUILD_VECTOR cannot be used with scalable types");
7057 assert(VT.getVectorNumElements() == (unsigned)NumOps &&
7058 "Incorrect element count in BUILD_VECTOR!");
7059
7060 // BUILD_VECTOR of UNDEFs is UNDEF.
7061 bool AllPoison = true;
7062 if (llvm::all_of(Ops, [&AllPoison](SDValue Op) {
7063 AllPoison &= Op.getOpcode() == ISD::POISON;
7064 return Op.isUndef();
7065 }))
7066 return AllPoison ? DAG.getPOISON(VT) : DAG.getUNDEF(VT);
7067
7068 // BUILD_VECTOR of seq extract/insert from the same vector + type is Identity.
7069 SDValue IdentitySrc;
7070 bool IsIdentity = true;
7071 for (int i = 0; i != NumOps; ++i) {
7072 if (Ops[i].getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
7073 Ops[i].getOperand(0).getValueType() != VT ||
7074 (IdentitySrc && Ops[i].getOperand(0) != IdentitySrc) ||
7075 !isa<ConstantSDNode>(Ops[i].getOperand(1)) ||
7076 Ops[i].getConstantOperandAPInt(1) != i) {
7077 IsIdentity = false;
7078 break;
7079 }
7080 IdentitySrc = Ops[i].getOperand(0);
7081 }
7082 if (IsIdentity)
7083 return IdentitySrc;
7084
7085 return SDValue();
7086}
7087
7088/// Try to simplify vector concatenation to an input value, undef, or build
7089/// vector.
7092 SelectionDAG &DAG) {
7093 assert(!Ops.empty() && "Can't concatenate an empty list of vectors!");
7095 [Ops](SDValue Op) {
7096 return Ops[0].getValueType() == Op.getValueType();
7097 }) &&
7098 "Concatenation of vectors with inconsistent value types!");
7099 assert((Ops[0].getValueType().getVectorElementCount() * Ops.size()) ==
7100 VT.getVectorElementCount() &&
7101 "Incorrect element count in vector concatenation!");
7102
7103 if (Ops.size() == 1)
7104 return Ops[0];
7105
7106 // Concat of UNDEFs is UNDEF.
7107 bool AllPoison = true;
7108 if (llvm::all_of(Ops, [&AllPoison](SDValue Op) {
7109 AllPoison &= Op.getOpcode() == ISD::POISON;
7110 return Op.isUndef();
7111 }))
7112 return AllPoison ? DAG.getPOISON(VT) : DAG.getUNDEF(VT);
7113
7114 // Scan the operands and look for extract operations from a single source
7115 // that correspond to insertion at the same location via this concatenation:
7116 // concat (extract X, 0*subvec_elts), (extract X, 1*subvec_elts), ...
7117 SDValue IdentitySrc;
7118 bool IsIdentity = true;
7119 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
7120 SDValue Op = Ops[i];
7121 unsigned IdentityIndex = i * Op.getValueType().getVectorMinNumElements();
7122 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
7123 Op.getOperand(0).getValueType() != VT ||
7124 (IdentitySrc && Op.getOperand(0) != IdentitySrc) ||
7125 Op.getConstantOperandVal(1) != IdentityIndex) {
7126 IsIdentity = false;
7127 break;
7128 }
7129 assert((!IdentitySrc || IdentitySrc == Op.getOperand(0)) &&
7130 "Unexpected identity source vector for concat of extracts");
7131 IdentitySrc = Op.getOperand(0);
7132 }
7133 if (IsIdentity) {
7134 assert(IdentitySrc && "Failed to set source vector of extracts");
7135 return IdentitySrc;
7136 }
7137
7138 // The code below this point is only designed to work for fixed width
7139 // vectors, so we bail out for now.
7140 if (VT.isScalableVector())
7141 return SDValue();
7142
7143 // A CONCAT_VECTOR of scalar sources, such as UNDEF, BUILD_VECTOR and
7144 // single-element INSERT_VECTOR_ELT operands can be simplified to one big
7145 // BUILD_VECTOR.
7146 // FIXME: Add support for SCALAR_TO_VECTOR as well.
7147 EVT SVT = VT.getScalarType();
7149 for (SDValue Op : Ops) {
7150 EVT OpVT = Op.getValueType();
7151 if (Op.getOpcode() == ISD::POISON)
7152 Elts.append(OpVT.getVectorNumElements(), DAG.getPOISON(SVT));
7153 else if (Op.getOpcode() == ISD::UNDEF)
7154 Elts.append(OpVT.getVectorNumElements(), DAG.getUNDEF(SVT));
7155 else if (Op.getOpcode() == ISD::BUILD_VECTOR)
7156 Elts.append(Op->op_begin(), Op->op_end());
7157 else if (Op.getOpcode() == ISD::INSERT_VECTOR_ELT &&
7158 OpVT.getVectorNumElements() == 1 &&
7159 isNullConstant(Op.getOperand(2)))
7160 Elts.push_back(Op.getOperand(1));
7161 else
7162 return SDValue();
7163 }
7164
7165 // BUILD_VECTOR requires all inputs to be of the same type, find the
7166 // maximum type and extend them all.
7167 for (SDValue Op : Elts)
7168 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
7169
7170 if (SVT.bitsGT(VT.getScalarType())) {
7171 for (SDValue &Op : Elts) {
7172 if (Op.getOpcode() == ISD::POISON)
7173 Op = DAG.getPOISON(SVT);
7174 else if (Op.getOpcode() == ISD::UNDEF)
7175 Op = DAG.getUNDEF(SVT);
7176 else
7177 Op = DAG.getTargetLoweringInfo().isZExtFree(Op.getValueType(), SVT)
7178 ? DAG.getZExtOrTrunc(Op, DL, SVT)
7179 : DAG.getSExtOrTrunc(Op, DL, SVT);
7180 }
7181 }
7182
7183 SDValue V = DAG.getBuildVector(VT, DL, Elts);
7184 NewSDValueDbgMsg(V, "New node fold concat vectors: ", &DAG);
7185 return V;
7186}
7187
7188/// Gets or creates the specified node.
7189SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT) {
7190 SDVTList VTs = getVTList(VT);
7191 SDNodeKey ID(Opcode, VTs, {});
7192 FoldingSetInsertToken InsertToken;
7193 if (SDNode *E = lookupNode(ID, DL, InsertToken))
7194 return SDValue(E, 0);
7195
7196 auto *N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
7197 CSEMap.insert(N, InsertToken);
7198
7199 InsertNode(N);
7200 SDValue V = SDValue(N, 0);
7201 NewSDValueDbgMsg(V, "Creating new node: ", this);
7202 return V;
7203}
7204
7205SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
7206 SDValue N1) {
7207 SDNodeFlags Flags;
7208 if (Inserter)
7209 Flags = Inserter->getFlags();
7210 return getNode(Opcode, DL, VT, N1, Flags);
7211}
7212
7213SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
7214 SDValue N1, const SDNodeFlags Flags) {
7215 assert(N1.getOpcode() != ISD::DELETED_NODE && "Operand is DELETED_NODE!");
7216
7217 // Constant fold unary operations with a vector integer or float operand.
7218 switch (Opcode) {
7219 default:
7220 // FIXME: Entirely reasonable to perform folding of other unary
7221 // operations here as the need arises.
7222 break;
7223 case ISD::FNEG:
7224 case ISD::FABS:
7225 case ISD::FCEIL:
7226 case ISD::FTRUNC:
7227 case ISD::FFLOOR:
7228 case ISD::FP_EXTEND:
7229 case ISD::FP_TO_SINT:
7230 case ISD::FP_TO_UINT:
7231 case ISD::FP_TO_FP16:
7232 case ISD::FP_TO_BF16:
7233 case ISD::TRUNCATE:
7234 case ISD::ANY_EXTEND:
7235 case ISD::ZERO_EXTEND:
7236 case ISD::SIGN_EXTEND:
7237 case ISD::UINT_TO_FP:
7238 case ISD::SINT_TO_FP:
7239 case ISD::FP16_TO_FP:
7240 case ISD::BF16_TO_FP:
7241 case ISD::BITCAST:
7242 case ISD::ABS:
7244 case ISD::BITREVERSE:
7245 case ISD::BSWAP:
7246 case ISD::CTLZ:
7248 case ISD::CTTZ:
7250 case ISD::CTPOP:
7251 case ISD::PARITY:
7252 case ISD::CTLS:
7253 case ISD::VECREDUCE_ADD:
7258 case ISD::VECREDUCE_MUL:
7259 case ISD::VECREDUCE_AND:
7260 case ISD::VECREDUCE_OR:
7261 case ISD::VECREDUCE_XOR:
7262 case ISD::STEP_VECTOR: {
7263 SDValue Ops = {N1};
7264 if (SDValue Fold = FoldConstantArithmetic(Opcode, DL, VT, Ops, Flags))
7265 return Fold;
7266 }
7267 }
7268
7269 unsigned OpOpcode = N1.getNode()->getOpcode();
7270 switch (Opcode) {
7271 case ISD::STEP_VECTOR:
7272 assert(VT.isScalableVector() &&
7273 "STEP_VECTOR can only be used with scalable types");
7274 assert(OpOpcode == ISD::TargetConstant &&
7275 VT.getVectorElementType() == N1.getValueType() &&
7276 "Unexpected step operand");
7277 break;
7278 case ISD::FREEZE:
7279 assert(VT == N1.getValueType() && "Unexpected VT!");
7281 return N1;
7282 break;
7283 case ISD::TokenFactor:
7284 case ISD::MERGE_VALUES:
7286 return N1; // Factor, merge or concat of one node? No need.
7287 case ISD::BUILD_VECTOR: {
7288 // Attempt to simplify BUILD_VECTOR.
7289 SDValue Ops[] = {N1};
7290 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
7291 return V;
7292 break;
7293 }
7294 case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node");
7295 case ISD::FP_EXTEND:
7297 "Invalid FP cast!");
7298 if (N1.getValueType() == VT) return N1; // noop conversion.
7299 assert((!VT.isVector() || VT.getVectorElementCount() ==
7301 "Vector element count mismatch!");
7302 assert(N1.getValueType().bitsLT(VT) && "Invalid fpext node, dst < src!");
7303 if (N1.isUndef())
7304 return getUNDEF(VT);
7305 break;
7306 case ISD::FP_TO_SINT:
7307 case ISD::FP_TO_UINT:
7308 if (N1.isUndef())
7309 return getUNDEF(VT);
7310 break;
7311 case ISD::SINT_TO_FP:
7312 case ISD::UINT_TO_FP:
7313 // [us]itofp(undef) = 0, because the result value is bounded.
7314 if (N1.isUndef())
7315 return getConstantFP(0.0, DL, VT);
7316 break;
7317 case ISD::SIGN_EXTEND:
7318 assert(VT.isInteger() && N1.getValueType().isInteger() &&
7319 "Invalid SIGN_EXTEND!");
7320 assert(VT.isVector() == N1.getValueType().isVector() &&
7321 "SIGN_EXTEND result type type should be vector iff the operand "
7322 "type is vector!");
7323 if (N1.getValueType() == VT) return N1; // noop extension
7324 assert((!VT.isVector() || VT.getVectorElementCount() ==
7326 "Vector element count mismatch!");
7327 assert(N1.getValueType().bitsLT(VT) && "Invalid sext node, dst < src!");
7328 if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND) {
7329 SDNodeFlags Flags;
7330 if (OpOpcode == ISD::ZERO_EXTEND)
7331 Flags.setNonNeg(N1->getFlags().hasNonNeg());
7332 SDValue NewVal = getNode(OpOpcode, DL, VT, N1.getOperand(0), Flags);
7333 transferDbgValues(N1, NewVal);
7334 return NewVal;
7335 }
7336
7337 if (OpOpcode == ISD::POISON)
7338 return getPOISON(VT);
7339
7340 if (N1.isUndef())
7341 // sext(undef) = 0, because the top bits will all be the same.
7342 return getConstant(0, DL, VT);
7343
7344 // Skip unnecessary sext_inreg pattern:
7345 // (sext (trunc x)) -> x iff the upper bits are all signbits.
7346 if (OpOpcode == ISD::TRUNCATE) {
7347 SDValue OpOp = N1.getOperand(0);
7348 if (OpOp.getValueType() == VT) {
7349 unsigned NumSignExtBits =
7351 if (ComputeNumSignBits(OpOp) > NumSignExtBits) {
7352 transferDbgValues(N1, OpOp);
7353 return OpOp;
7354 }
7355 }
7356 }
7357 break;
7358 case ISD::ZERO_EXTEND:
7359 assert(VT.isInteger() && N1.getValueType().isInteger() &&
7360 "Invalid ZERO_EXTEND!");
7361 assert(VT.isVector() == N1.getValueType().isVector() &&
7362 "ZERO_EXTEND result type type should be vector iff the operand "
7363 "type is vector!");
7364 if (N1.getValueType() == VT) return N1; // noop extension
7365 assert((!VT.isVector() || VT.getVectorElementCount() ==
7367 "Vector element count mismatch!");
7368 assert(N1.getValueType().bitsLT(VT) && "Invalid zext node, dst < src!");
7369 if (OpOpcode == ISD::ZERO_EXTEND) { // (zext (zext x)) -> (zext x)
7370 SDNodeFlags Flags;
7371 Flags.setNonNeg(N1->getFlags().hasNonNeg());
7372 SDValue NewVal =
7373 getNode(ISD::ZERO_EXTEND, DL, VT, N1.getOperand(0), Flags);
7374 transferDbgValues(N1, NewVal);
7375 return NewVal;
7376 }
7377
7378 if (OpOpcode == ISD::POISON)
7379 return getPOISON(VT);
7380
7381 if (N1.isUndef())
7382 // zext(undef) = 0, because the top bits will be zero.
7383 return getConstant(0, DL, VT);
7384
7385 // Skip unnecessary zext_inreg pattern:
7386 // (zext (trunc x)) -> x iff the upper bits are known zero.
7387 // TODO: Remove (zext (trunc (and x, c))) exception which some targets
7388 // use to recognise zext_inreg patterns.
7389 if (OpOpcode == ISD::TRUNCATE) {
7390 SDValue OpOp = N1.getOperand(0);
7391 if (OpOp.getValueType() == VT) {
7392 if (OpOp.getOpcode() != ISD::AND) {
7395 if (MaskedValueIsZero(OpOp, HiBits)) {
7396 transferDbgValues(N1, OpOp);
7397 return OpOp;
7398 }
7399 }
7400 }
7401 }
7402 break;
7403 case ISD::ANY_EXTEND:
7404 assert(VT.isInteger() && N1.getValueType().isInteger() &&
7405 "Invalid ANY_EXTEND!");
7406 assert(VT.isVector() == N1.getValueType().isVector() &&
7407 "ANY_EXTEND result type type should be vector iff the operand "
7408 "type is vector!");
7409 if (N1.getValueType() == VT) return N1; // noop extension
7410 assert((!VT.isVector() || VT.getVectorElementCount() ==
7412 "Vector element count mismatch!");
7413 assert(N1.getValueType().bitsLT(VT) && "Invalid anyext node, dst < src!");
7414
7415 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
7416 OpOpcode == ISD::ANY_EXTEND) {
7417 SDNodeFlags Flags;
7418 if (OpOpcode == ISD::ZERO_EXTEND)
7419 Flags.setNonNeg(N1->getFlags().hasNonNeg());
7420 // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x)
7421 return getNode(OpOpcode, DL, VT, N1.getOperand(0), Flags);
7422 }
7423 if (N1.isUndef())
7424 return getUNDEF(VT);
7425
7426 // (ext (trunc x)) -> x
7427 if (OpOpcode == ISD::TRUNCATE) {
7428 SDValue OpOp = N1.getOperand(0);
7429 if (OpOp.getValueType() == VT) {
7430 transferDbgValues(N1, OpOp);
7431 return OpOp;
7432 }
7433 }
7434 break;
7435 case ISD::TRUNCATE:
7436 assert(VT.isInteger() && N1.getValueType().isInteger() &&
7437 "Invalid TRUNCATE!");
7438 assert(VT.isVector() == N1.getValueType().isVector() &&
7439 "TRUNCATE result type type should be vector iff the operand "
7440 "type is vector!");
7441 if (N1.getValueType() == VT) return N1; // noop truncate
7442 assert((!VT.isVector() || VT.getVectorElementCount() ==
7444 "Vector element count mismatch!");
7445 assert(N1.getValueType().bitsGT(VT) && "Invalid truncate node, src < dst!");
7446 if (OpOpcode == ISD::TRUNCATE)
7447 return getNode(ISD::TRUNCATE, DL, VT, N1.getOperand(0));
7448 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
7449 OpOpcode == ISD::ANY_EXTEND) {
7450 // If the source is smaller than the dest, we still need an extend.
7452 VT.getScalarType())) {
7453 SDNodeFlags Flags;
7454 if (OpOpcode == ISD::ZERO_EXTEND)
7455 Flags.setNonNeg(N1->getFlags().hasNonNeg());
7456 return getNode(OpOpcode, DL, VT, N1.getOperand(0), Flags);
7457 }
7458 if (N1.getOperand(0).getValueType().bitsGT(VT))
7459 return getNode(ISD::TRUNCATE, DL, VT, N1.getOperand(0));
7460 return N1.getOperand(0);
7461 }
7462 if (N1.isUndef())
7463 return getUNDEF(VT);
7464 if (OpOpcode == ISD::VSCALE && !NewNodesMustHaveLegalTypes)
7465 return getVScale(DL, VT,
7467 break;
7471 assert(VT.isVector() && "This DAG node is restricted to vector types.");
7472 assert(N1.getValueType().bitsLE(VT) &&
7473 "The input must be the same size or smaller than the result.");
7476 "The destination vector type must have fewer lanes than the input.");
7477 break;
7478 case ISD::ABS:
7479 assert(VT.isInteger() && VT == N1.getValueType() && "Invalid ABS!");
7480 if (N1.isUndef())
7481 return getConstant(0, DL, VT);
7482 break;
7484 assert(VT.isInteger() && VT == N1.getValueType() &&
7485 "Invalid ABS_MIN_POISON!");
7486 if (N1.isUndef())
7487 return getConstant(0, DL, VT);
7488 break;
7489 case ISD::BSWAP:
7490 assert(VT.isInteger() && VT == N1.getValueType() && "Invalid BSWAP!");
7491 assert((VT.getScalarSizeInBits() % 16 == 0) &&
7492 "BSWAP types must be a multiple of 16 bits!");
7493 if (N1.isUndef())
7494 return getUNDEF(VT);
7495 // bswap(bswap(X)) -> X.
7496 if (OpOpcode == ISD::BSWAP)
7497 return N1.getOperand(0);
7498 break;
7499 case ISD::BITREVERSE:
7500 assert(VT.isInteger() && VT == N1.getValueType() && "Invalid BITREVERSE!");
7501 if (N1.isUndef())
7502 return getUNDEF(VT);
7503 break;
7504 case ISD::BITCAST:
7506 "Cannot BITCAST between types of different sizes!");
7507 if (VT == N1.getValueType()) return N1; // noop conversion.
7508 if (OpOpcode == ISD::BITCAST) // bitconv(bitconv(x)) -> bitconv(x)
7509 return getNode(ISD::BITCAST, DL, VT, N1.getOperand(0));
7510 if (N1.isUndef())
7511 return getUNDEF(VT);
7512 break;
7514 assert(VT.isVector() && !N1.getValueType().isVector() &&
7515 (VT.getVectorElementType() == N1.getValueType() ||
7517 N1.getValueType().isInteger() &&
7519 "Illegal SCALAR_TO_VECTOR node!");
7520 if (N1.isUndef())
7521 return getUNDEF(VT);
7522 // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
7523 if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
7525 N1.getConstantOperandVal(1) == 0 &&
7526 N1.getOperand(0).getValueType() == VT)
7527 return N1.getOperand(0);
7528 break;
7529 case ISD::FNEG:
7530 // Negation of an unknown bag of bits is still completely undefined.
7531 if (N1.isUndef())
7532 return getUNDEF(VT);
7533
7534 if (OpOpcode == ISD::FNEG) // --X -> X
7535 return N1.getOperand(0);
7536 break;
7537 case ISD::FABS:
7538 if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X)
7539 return getNode(ISD::FABS, DL, VT, N1.getOperand(0));
7540 break;
7541 case ISD::VSCALE:
7542 assert(VT == N1.getValueType() && "Unexpected VT!");
7543 break;
7544 case ISD::CTPOP:
7545 if (N1.getValueType().getScalarType() == MVT::i1)
7546 return N1;
7547 break;
7548 case ISD::CTLZ:
7549 case ISD::CTTZ:
7550 if (N1.getValueType().getScalarType() == MVT::i1)
7551 return getNOT(DL, N1, N1.getValueType());
7552 break;
7553 case ISD::CTLS:
7554 if (N1.getValueType().getScalarType() == MVT::i1)
7555 return getConstant(0, DL, VT);
7556 break;
7557 case ISD::VECREDUCE_ADD:
7558 if (N1.getValueType().getScalarType() == MVT::i1)
7559 return getNode(ISD::VECREDUCE_XOR, DL, VT, N1);
7560 break;
7563 if (N1.getValueType().getScalarType() == MVT::i1)
7564 return getNode(ISD::VECREDUCE_OR, DL, VT, N1);
7565 break;
7568 if (N1.getValueType().getScalarType() == MVT::i1)
7569 return getNode(ISD::VECREDUCE_AND, DL, VT, N1);
7570 break;
7572 // With a single lane, the result is true iff that lane is false.
7574 return getLogicalNOT(DL, N1, VT);
7575 break;
7576 case ISD::VECTOR_REPEAT:
7578 "VECTOR_REPEAT requires a fixed-length vector operand");
7579 assert(VT.isScalableVector() &&
7580 "VECTOR_REPEAT requires a scalable vector result");
7583 "VECTOR_REPEAT operand and result element counts must match");
7584 if (VT.getVectorMinNumElements() == 1)
7585 return getSplatVector(
7586 VT, DL, getExtractVectorElt(DL, VT.getVectorElementType(), N1, 0));
7587 break;
7588 case ISD::SPLAT_VECTOR:
7589 assert(VT.isVector() && "Wrong return type!");
7590 // FIXME: Hexagon uses i32 scalar for a floating point zero vector so allow
7591 // that for now.
7593 (VT.isFloatingPoint() && N1.getValueType() == MVT::i32) ||
7595 N1.getValueType().isInteger() &&
7597 "Wrong operand type!");
7598 break;
7599 }
7600
7601 SDNode *N;
7602 SDVTList VTs = getVTList(VT);
7603 SDValue Ops[] = {N1};
7604 if (VT != MVT::Glue) { // Don't CSE glue producing nodes
7605 SDNodeKey ID(Opcode, VTs, Ops);
7606 FoldingSetInsertToken InsertToken;
7607 if (SDNode *E = lookupNode(ID, DL, InsertToken)) {
7608 E->intersectFlagsWith(Flags);
7609 return SDValue(E, 0);
7610 }
7611
7612 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
7613 N->setFlags(Flags);
7614 createOperands(N, Ops);
7615 CSEMap.insert(N, InsertToken);
7616 } else {
7617 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
7618 createOperands(N, Ops);
7619 }
7620
7621 InsertNode(N);
7622 SDValue V = SDValue(N, 0);
7623 NewSDValueDbgMsg(V, "Creating new node: ", this);
7624 return V;
7625}
7626
7627static APInt getIntegerIdentity(unsigned Opcode, unsigned BitWidth) {
7628 switch (Opcode) {
7629 default:
7630 llvm_unreachable("Unexpected integer identity opcode");
7631 case ISD::ADD:
7632 case ISD::OR:
7633 case ISD::XOR:
7634 case ISD::UMAX:
7635 return APInt::getZero(BitWidth);
7636 case ISD::MUL:
7637 return APInt(BitWidth, 1);
7638 case ISD::AND:
7639 case ISD::UMIN:
7641 case ISD::SMAX:
7643 case ISD::SMIN:
7645 }
7646}
7647
7648static std::optional<APInt> FoldValue(unsigned Opcode, const APInt &C1,
7649 const APInt &C2) {
7650 switch (Opcode) {
7651 case ISD::ADD: return C1 + C2;
7652 case ISD::SUB: return C1 - C2;
7653 case ISD::MUL: return C1 * C2;
7654 case ISD::AND: return C1 & C2;
7655 case ISD::OR: return C1 | C2;
7656 case ISD::XOR: return C1 ^ C2;
7657 case ISD::SHL: return C1 << C2;
7658 case ISD::SRL: return C1.lshr(C2);
7659 case ISD::SRA: return C1.ashr(C2);
7660 case ISD::ROTL: return C1.rotl(C2);
7661 case ISD::ROTR: return C1.rotr(C2);
7662 case ISD::SMIN: return C1.sle(C2) ? C1 : C2;
7663 case ISD::SMAX: return C1.sge(C2) ? C1 : C2;
7664 case ISD::UMIN: return C1.ule(C2) ? C1 : C2;
7665 case ISD::UMAX: return C1.uge(C2) ? C1 : C2;
7666 case ISD::SADDSAT: return C1.sadd_sat(C2);
7667 case ISD::UADDSAT: return C1.uadd_sat(C2);
7668 case ISD::SSUBSAT: return C1.ssub_sat(C2);
7669 case ISD::USUBSAT: return C1.usub_sat(C2);
7670 case ISD::SSHLSAT: return C1.sshl_sat(C2);
7671 case ISD::USHLSAT: return C1.ushl_sat(C2);
7672 case ISD::UDIV:
7673 if (!C2.getBoolValue())
7674 break;
7675 return C1.udiv(C2);
7676 case ISD::UREM:
7677 if (!C2.getBoolValue())
7678 break;
7679 return C1.urem(C2);
7680 case ISD::SDIV:
7681 if (!C2.getBoolValue())
7682 break;
7683 return C1.sdiv(C2);
7684 case ISD::SREM:
7685 if (!C2.getBoolValue())
7686 break;
7687 return C1.srem(C2);
7688 case ISD::AVGFLOORS:
7689 return APIntOps::avgFloorS(C1, C2);
7690 case ISD::AVGFLOORU:
7691 return APIntOps::avgFloorU(C1, C2);
7692 case ISD::AVGCEILS:
7693 return APIntOps::avgCeilS(C1, C2);
7694 case ISD::AVGCEILU:
7695 return APIntOps::avgCeilU(C1, C2);
7696 case ISD::AVGSUBFLOORS:
7697 return APIntOps::avgSubFloorS(C1, C2);
7698 case ISD::AVGSUBFLOORU:
7699 return APIntOps::avgSubFloorU(C1, C2);
7700 case ISD::ABDS:
7701 return APIntOps::abds(C1, C2);
7702 case ISD::ABDU:
7703 return APIntOps::abdu(C1, C2);
7704 case ISD::MULHS:
7705 return APIntOps::mulhs(C1, C2);
7706 case ISD::MULHU:
7707 return APIntOps::mulhu(C1, C2);
7708 case ISD::CLMUL:
7709 return APIntOps::clmul(C1, C2);
7710 case ISD::CLMULR:
7711 return APIntOps::clmulr(C1, C2);
7712 case ISD::CLMULH:
7713 return APIntOps::clmulh(C1, C2);
7714 case ISD::PEXT:
7715 return APIntOps::pext(C1, C2);
7716 case ISD::PDEP:
7717 return APIntOps::pdep(C1, C2);
7718 }
7719 return std::nullopt;
7720}
7721// Handle constant folding with UNDEF.
7722// TODO: Handle more cases.
7723static std::optional<APInt> FoldValueWithUndef(unsigned Opcode, const APInt &C1,
7724 bool IsUndef1, const APInt &C2,
7725 bool IsUndef2) {
7726 if (!(IsUndef1 || IsUndef2))
7727 return FoldValue(Opcode, C1, C2);
7728
7729 // Fold and(x, undef) -> 0
7730 // Fold mul(x, undef) -> 0
7731 if (Opcode == ISD::AND || Opcode == ISD::MUL)
7732 return APInt::getZero(C1.getBitWidth());
7733
7734 return std::nullopt;
7735}
7736
7738 const GlobalAddressSDNode *GA,
7739 const SDNode *N2) {
7740 if (GA->getOpcode() != ISD::GlobalAddress)
7741 return SDValue();
7742 if (!TLI->isOffsetFoldingLegal(GA))
7743 return SDValue();
7744 auto *C2 = dyn_cast<ConstantSDNode>(N2);
7745 if (!C2)
7746 return SDValue();
7747 int64_t Offset = C2->getSExtValue();
7748 switch (Opcode) {
7749 case ISD::ADD:
7750 case ISD::PTRADD:
7751 break;
7752 case ISD::SUB: Offset = -uint64_t(Offset); break;
7753 default: return SDValue();
7754 }
7755 return getGlobalAddress(GA->getGlobal(), SDLoc(C2), VT,
7756 GA->getOffset() + uint64_t(Offset));
7757}
7758
7760 switch (Opcode) {
7761 case ISD::SDIV:
7762 case ISD::UDIV:
7763 case ISD::SREM:
7764 case ISD::UREM: {
7765 // If a divisor is zero/undef or any element of a divisor vector is
7766 // zero/undef, the whole op is undef.
7767 assert(Ops.size() == 2 && "Div/rem should have 2 operands");
7768 SDValue Divisor = Ops[1];
7769 if (Divisor.isUndef() || isNullConstant(Divisor))
7770 return true;
7771
7772 return ISD::isBuildVectorOfConstantSDNodes(Divisor.getNode()) &&
7773 llvm::any_of(Divisor->op_values(),
7774 [](SDValue V) { return V.isUndef() ||
7775 isNullConstant(V); });
7776 // TODO: Handle signed overflow.
7777 }
7778 // TODO: Handle oversized shifts.
7779 default:
7780 return false;
7781 }
7782}
7783
7786 SDNodeFlags Flags) {
7787 // If the opcode is a target-specific ISD node, there's nothing we can
7788 // do here and the operand rules may not line up with the below, so
7789 // bail early.
7790 // We can't create a scalar CONCAT_VECTORS so skip it. It will break
7791 // for concats involving SPLAT_VECTOR. Concats of BUILD_VECTORS are handled by
7792 // foldCONCAT_VECTORS in getNode before this is called.
7793 // VECTOR_SHUFFLE_VAR is not elementwise.
7794 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::CONCAT_VECTORS ||
7795 Opcode == ISD::VECTOR_SHUFFLE_VAR)
7796 return SDValue();
7797
7798 unsigned NumOps = Ops.size();
7799 if (NumOps == 0)
7800 return SDValue();
7801
7802 if (isUndef(Opcode, Ops))
7803 return getUNDEF(VT);
7804
7805 // Handle unary special cases.
7806 if (NumOps == 1) {
7807 SDValue N1 = Ops[0];
7808
7809 // Constant fold unary operations with an integer constant operand. Even
7810 // opaque constant will be folded, because the folding of unary operations
7811 // doesn't create new constants with different values. Nevertheless, the
7812 // opaque flag is preserved during folding to prevent future folding with
7813 // other constants.
7814 if (auto *C = dyn_cast<ConstantSDNode>(N1)) {
7815 const APInt &Val = C->getAPIntValue();
7816 switch (Opcode) {
7817 case ISD::SIGN_EXTEND:
7818 return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
7819 C->isTargetOpcode(), C->isOpaque());
7820 case ISD::TRUNCATE:
7821 if (C->isOpaque())
7822 break;
7823 [[fallthrough]];
7824 case ISD::ZERO_EXTEND:
7825 return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
7826 C->isTargetOpcode(), C->isOpaque());
7827 case ISD::ANY_EXTEND:
7828 // Some targets like RISCV prefer to sign extend some types.
7829 if (TLI->isSExtCheaperThanZExt(N1.getValueType(), VT))
7830 return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
7831 C->isTargetOpcode(), C->isOpaque());
7832 return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
7833 C->isTargetOpcode(), C->isOpaque());
7834 case ISD::ABS:
7835 return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(),
7836 C->isOpaque());
7838 if (Val.isMinSignedValue())
7839 return getPOISON(VT);
7840 return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(),
7841 C->isOpaque());
7842 case ISD::BITREVERSE:
7843 return getConstant(Val.reverseBits(), DL, VT, C->isTargetOpcode(),
7844 C->isOpaque());
7845 case ISD::BSWAP:
7846 return getConstant(Val.byteSwap(), DL, VT, C->isTargetOpcode(),
7847 C->isOpaque());
7848 case ISD::CTPOP:
7849 return getConstant(Val.popcount(), DL, VT, C->isTargetOpcode(),
7850 C->isOpaque());
7851 case ISD::PARITY:
7852 return getConstant(Val.popcount() & 1, DL, VT, C->isTargetOpcode(),
7853 C->isOpaque());
7854 case ISD::CTLZ:
7856 return getConstant(Val.countl_zero(), DL, VT, C->isTargetOpcode(),
7857 C->isOpaque());
7858 case ISD::CTTZ:
7860 return getConstant(Val.countr_zero(), DL, VT, C->isTargetOpcode(),
7861 C->isOpaque());
7862 case ISD::CTLS:
7863 // CTLS returns the number of extra sign bits so subtract one.
7864 return getConstant(Val.getNumSignBits() - 1, DL, VT,
7865 C->isTargetOpcode(), C->isOpaque());
7866 case ISD::UINT_TO_FP:
7867 case ISD::SINT_TO_FP: {
7869 (void)FPV.convertFromAPInt(Val, Opcode == ISD::SINT_TO_FP,
7871 return getConstantFP(FPV, DL, VT);
7872 }
7873 case ISD::FP16_TO_FP:
7874 case ISD::BF16_TO_FP: {
7875 bool Ignored;
7876 APFloat FPV(Opcode == ISD::FP16_TO_FP ? APFloat::IEEEhalf()
7877 : APFloat::BFloat(),
7878 (Val.getBitWidth() == 16) ? Val : Val.trunc(16));
7879
7880 // This can return overflow, underflow, or inexact; we don't care.
7881 // FIXME need to be more flexible about rounding mode.
7883 &Ignored);
7884 return getConstantFP(FPV, DL, VT);
7885 }
7886 case ISD::STEP_VECTOR:
7887 if (SDValue V = FoldSTEP_VECTOR(DL, VT, N1, *this))
7888 return V;
7889 break;
7890 case ISD::BITCAST:
7891 if (C->isOpaque())
7892 break;
7893 if (VT == MVT::f16 && C->getValueType(0) == MVT::i16)
7894 return getConstantFP(APFloat(APFloat::IEEEhalf(), Val), DL, VT);
7895 if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
7896 return getConstantFP(APFloat(APFloat::IEEEsingle(), Val), DL, VT);
7897 if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
7898 return getConstantFP(APFloat(APFloat::IEEEdouble(), Val), DL, VT);
7899 if (VT == MVT::f128 && C->getValueType(0) == MVT::i128)
7900 return getConstantFP(APFloat(APFloat::IEEEquad(), Val), DL, VT);
7901 break;
7902 }
7903 }
7904
7905 // Constant fold unary operations with a floating point constant operand.
7906 if (auto *C = dyn_cast<ConstantFPSDNode>(N1)) {
7907 APFloat V = C->getValueAPF(); // make copy
7908 switch (Opcode) {
7909 case ISD::FNEG:
7910 V.changeSign();
7911 return getConstantFP(V, DL, VT);
7912 case ISD::FABS:
7913 V.clearSign();
7914 return getConstantFP(V, DL, VT);
7915 case ISD::FCEIL: {
7916 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardPositive);
7918 return getConstantFP(V, DL, VT);
7919 return SDValue();
7920 }
7921 case ISD::FTRUNC: {
7922 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardZero);
7924 return getConstantFP(V, DL, VT);
7925 return SDValue();
7926 }
7927 case ISD::FFLOOR: {
7928 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardNegative);
7930 return getConstantFP(V, DL, VT);
7931 return SDValue();
7932 }
7933 case ISD::FP_EXTEND: {
7934 bool ignored;
7935 // This can return overflow, underflow, or inexact; we don't care.
7936 // FIXME need to be more flexible about rounding mode.
7937 (void)V.convert(VT.getFltSemantics(), APFloat::rmNearestTiesToEven,
7938 &ignored);
7939 return getConstantFP(V, DL, VT);
7940 }
7941 case ISD::FP_TO_SINT:
7942 case ISD::FP_TO_UINT: {
7943 bool ignored;
7944 APSInt IntVal(VT.getSizeInBits(), Opcode == ISD::FP_TO_UINT);
7945 // FIXME need to be more flexible about rounding mode.
7947 V.convertToInteger(IntVal, APFloat::rmTowardZero, &ignored);
7948 if (s == APFloat::opInvalidOp) // inexact is OK, in fact usual
7949 break;
7950 return getConstant(IntVal, DL, VT);
7951 }
7952 case ISD::FP_TO_FP16:
7953 case ISD::FP_TO_BF16: {
7954 bool Ignored;
7955 // This can return overflow, underflow, or inexact; we don't care.
7956 // FIXME need to be more flexible about rounding mode.
7957 (void)V.convert(Opcode == ISD::FP_TO_FP16 ? APFloat::IEEEhalf()
7958 : APFloat::BFloat(),
7960 return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
7961 }
7962 case ISD::BITCAST:
7963 if (VT == MVT::i16 && C->getValueType(0) == MVT::f16)
7964 return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL,
7965 VT);
7966 if (VT == MVT::i16 && C->getValueType(0) == MVT::bf16)
7967 return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL,
7968 VT);
7969 if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
7970 return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), DL,
7971 VT);
7972 if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
7973 return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
7974 break;
7975 }
7976 }
7977
7978 // Early-out if we failed to constant fold a bitcast.
7979 if (Opcode == ISD::BITCAST)
7980 return SDValue();
7981
7982 // Constant fold integer vector reductions with constant BUILD_VECTORs.
7983 if ((Opcode == ISD::VECREDUCE_ADD || Opcode == ISD::VECREDUCE_SMAX ||
7984 Opcode == ISD::VECREDUCE_SMIN || Opcode == ISD::VECREDUCE_UMAX ||
7985 Opcode == ISD::VECREDUCE_UMIN || Opcode == ISD::VECREDUCE_MUL ||
7986 Opcode == ISD::VECREDUCE_OR || Opcode == ISD::VECREDUCE_XOR ||
7987 Opcode == ISD::VECREDUCE_AND) &&
7989 unsigned EltBits = N1.getValueType().getScalarSizeInBits();
7990 unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Opcode);
7991 APInt Acc = getIntegerIdentity(BaseOpcode, EltBits);
7992 for (SDValue Elt : N1->op_values()) {
7993 if (Elt.getOpcode() == ISD::POISON)
7994 return getPOISON(VT);
7995 if (Elt.isUndef() || cast<ConstantSDNode>(Elt)->isOpaque())
7996 return SDValue();
7997 APInt Value = cast<ConstantSDNode>(Elt)->getAPIntValue().trunc(EltBits);
7998 std::optional<APInt> Folded = FoldValue(BaseOpcode, Acc, Value);
7999 assert(Folded &&
8000 "Expected vector reduction base opcode to be foldable");
8001 Acc = *Folded;
8002 }
8003 EVT EltVT = N1.getValueType().getScalarType();
8004 return getAnyExtOrTrunc(getConstant(Acc, DL, EltVT), DL, VT);
8005 }
8006 }
8007
8008 // Handle binops special cases.
8009 if (NumOps == 2) {
8010 if (SDValue CFP = foldConstantFPMath(Opcode, DL, VT, Ops))
8011 return CFP;
8012
8013 if (auto *C1 = dyn_cast<ConstantSDNode>(Ops[0])) {
8014 if (auto *C2 = dyn_cast<ConstantSDNode>(Ops[1])) {
8015 if (C1->isOpaque() || C2->isOpaque())
8016 return SDValue();
8017
8018 std::optional<APInt> FoldAttempt =
8019 FoldValue(Opcode, C1->getAPIntValue(), C2->getAPIntValue());
8020 if (!FoldAttempt)
8021 return SDValue();
8022
8023 SDValue Folded = getConstant(*FoldAttempt, DL, VT);
8024 assert((!Folded || !VT.isVector()) &&
8025 "Can't fold vectors ops with scalar operands");
8026 return Folded;
8027 }
8028 }
8029
8030 // fold (add Sym, c) -> Sym+c
8032 return FoldSymbolOffset(Opcode, VT, GA, Ops[1].getNode());
8033 if (TLI->isCommutativeBinOp(Opcode))
8035 return FoldSymbolOffset(Opcode, VT, GA, Ops[0].getNode());
8036
8037 // fold (sext_in_reg c1) -> c2
8038 if (Opcode == ISD::SIGN_EXTEND_INREG) {
8039 EVT EVT = cast<VTSDNode>(Ops[1])->getVT();
8040
8041 auto SignExtendInReg = [&](APInt Val, llvm::EVT ConstantVT) {
8042 unsigned FromBits = EVT.getScalarSizeInBits();
8043 Val <<= Val.getBitWidth() - FromBits;
8044 Val.ashrInPlace(Val.getBitWidth() - FromBits);
8045 return getConstant(Val, DL, ConstantVT);
8046 };
8047
8048 if (auto *C1 = dyn_cast<ConstantSDNode>(Ops[0])) {
8049 const APInt &Val = C1->getAPIntValue();
8050 return SignExtendInReg(Val, VT);
8051 }
8052
8054 SmallVector<SDValue, 8> ScalarOps;
8055 llvm::EVT OpVT = Ops[0].getOperand(0).getValueType();
8056 for (int I = 0, E = VT.getVectorNumElements(); I != E; ++I) {
8057 SDValue Op = Ops[0].getOperand(I);
8058 if (Op.isUndef()) {
8059 ScalarOps.push_back(getUNDEF(OpVT));
8060 continue;
8061 }
8062 const APInt &Val = cast<ConstantSDNode>(Op)->getAPIntValue();
8063 ScalarOps.push_back(SignExtendInReg(Val, OpVT));
8064 }
8065 return getBuildVector(VT, DL, ScalarOps);
8066 }
8067
8068 if (Ops[0].getOpcode() == ISD::SPLAT_VECTOR &&
8069 isa<ConstantSDNode>(Ops[0].getOperand(0)))
8070 return getNode(ISD::SPLAT_VECTOR, DL, VT,
8071 SignExtendInReg(Ops[0].getConstantOperandAPInt(0),
8072 Ops[0].getOperand(0).getValueType()));
8073 }
8074 }
8075
8076 // Handle fshl/fshr special cases.
8077 if (Opcode == ISD::FSHL || Opcode == ISD::FSHR) {
8078 auto *C1 = dyn_cast<ConstantSDNode>(Ops[0]);
8079 auto *C2 = dyn_cast<ConstantSDNode>(Ops[1]);
8080 auto *C3 = dyn_cast<ConstantSDNode>(Ops[2]);
8081
8082 if (C1 && C2 && C3) {
8083 if (C1->isOpaque() || C2->isOpaque() || C3->isOpaque())
8084 return SDValue();
8085 const APInt &V1 = C1->getAPIntValue(), &V2 = C2->getAPIntValue(),
8086 &V3 = C3->getAPIntValue();
8087
8088 APInt FoldedVal = Opcode == ISD::FSHL ? APIntOps::fshl(V1, V2, V3)
8089 : APIntOps::fshr(V1, V2, V3);
8090 return getConstant(FoldedVal, DL, VT);
8091 }
8092 }
8093
8094 // Handle fma/fmad special cases.
8095 if (Opcode == ISD::FMA || Opcode == ISD::FMAD || Opcode == ISD::FMULADD) {
8096 assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
8097 assert(Ops[0].getValueType() == VT && Ops[1].getValueType() == VT &&
8098 Ops[2].getValueType() == VT && "FMA types must match!");
8102 if (C1 && C2 && C3) {
8103 APFloat V1 = C1->getValueAPF();
8104 const APFloat &V2 = C2->getValueAPF();
8105 const APFloat &V3 = C3->getValueAPF();
8106 if (Opcode == ISD::FMAD || Opcode == ISD::FMULADD) {
8107 V1.multiply(V2, APFloat::rmNearestTiesToEven);
8109 } else
8110 V1.fusedMultiplyAdd(V2, V3, APFloat::rmNearestTiesToEven);
8111 return getConstantFP(V1, DL, VT);
8112 }
8113 }
8114
8115 // This is for vector folding only from here on.
8116 if (!VT.isVector())
8117 return SDValue();
8118
8119 // Constant fold integer partial reductions with constant BUILD_VECTOR
8120 // operands. The reduction order is deliberately unspecified. Use the same
8121 // subvector layout as TargetLowering::expandPartialReduceMLA(), where input
8122 // lane I contributes to accumulator lane I % NumAccElts.
8123 if (Opcode == ISD::PARTIAL_REDUCE_SMLA ||
8124 Opcode == ISD::PARTIAL_REDUCE_UMLA ||
8125 Opcode == ISD::PARTIAL_REDUCE_SUMLA) {
8126 // These nodes have no scalar form, so unsupported cases must not fall
8127 // through to generic per-lane vector folding.
8128 if (!llvm::all_of(Ops, [](SDValue Op) {
8129 return ISD::isBuildVectorOfConstantSDNodes(Op.getNode());
8130 }))
8131 return SDValue();
8132
8133 unsigned AccEltBits = VT.getScalarSizeInBits();
8134 unsigned InputEltBits = Ops[1].getScalarValueSizeInBits();
8135 unsigned NumAccElts = VT.getVectorNumElements();
8136 unsigned NumInputElts = Ops[1].getValueType().getVectorNumElements();
8137 SmallVector<APInt, 8> Results(NumAccElts, APInt::getZero(AccEltBits));
8138 BitVector PoisonElts(NumAccElts);
8139
8140 for (unsigned I = 0; I != NumAccElts; ++I) {
8141 SDValue Elt = Ops[0].getOperand(I);
8142 if (Elt.getOpcode() == ISD::POISON) {
8143 PoisonElts.set(I);
8144 continue;
8145 }
8146 auto *C = dyn_cast<ConstantSDNode>(Elt);
8147 if (!C || C->isOpaque())
8148 return SDValue();
8149 Results[I] = C->getAPIntValue().trunc(AccEltBits);
8150 }
8151
8152 bool IsLHSSigned = Opcode != ISD::PARTIAL_REDUCE_UMLA;
8153 bool IsRHSSigned = Opcode == ISD::PARTIAL_REDUCE_SMLA;
8154 for (unsigned I = 0; I != NumInputElts; ++I) {
8155 const unsigned AccIdx = I % NumAccElts;
8156 SDValue LHSElt = Ops[1].getOperand(I);
8157 SDValue RHSElt = Ops[2].getOperand(I);
8158 if (LHSElt.getOpcode() == ISD::POISON ||
8159 RHSElt.getOpcode() == ISD::POISON) {
8160 PoisonElts.set(AccIdx);
8161 continue;
8162 }
8163
8164 auto *LHS = dyn_cast<ConstantSDNode>(LHSElt);
8165 auto *RHS = dyn_cast<ConstantSDNode>(RHSElt);
8166 if (!LHS || !RHS || LHS->isOpaque() || RHS->isOpaque())
8167 return SDValue();
8168
8169 APInt LHSVal = LHS->getAPIntValue().trunc(InputEltBits);
8170 APInt RHSVal = RHS->getAPIntValue().trunc(InputEltBits);
8171 LHSVal = IsLHSSigned ? LHSVal.sext(AccEltBits) : LHSVal.zext(AccEltBits);
8172 RHSVal = IsRHSSigned ? RHSVal.sext(AccEltBits) : RHSVal.zext(AccEltBits);
8173 Results[AccIdx] += LHSVal * RHSVal;
8174 }
8175
8176 // After type legalization the vector element type may not be a legal
8177 // scalar type (e.g. i16 on AArch64). Create the folded constants in the
8178 // promoted legal scalar type instead, matching the generic per-lane path
8179 // below. Bail out if legalization would narrow the type, since the lane
8180 // value would not fit.
8181 EVT AccEltVT = VT.getVectorElementType();
8182 EVT LegalSVT = AccEltVT;
8183 if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
8184 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
8185 if (LegalSVT.bitsLT(AccEltVT))
8186 return SDValue();
8187 }
8188
8189 SmallVector<SDValue, 8> ResultOps;
8190 for (unsigned I = 0; I != NumAccElts; ++I)
8191 ResultOps.push_back(
8192 PoisonElts[I] ? getPOISON(LegalSVT)
8193 : getConstant(Results[I].sext(LegalSVT.getSizeInBits()),
8194 DL, LegalSVT));
8195 return getBuildVector(VT, DL, ResultOps);
8196 }
8197
8198 ElementCount NumElts = VT.getVectorElementCount();
8199
8200 // See if we can fold through any bitcasted integer ops.
8201 if (NumOps == 2 && VT.isFixedLengthVector() && VT.isInteger() &&
8202 Ops[0].getValueType() == VT && Ops[1].getValueType() == VT &&
8203 (Ops[0].getOpcode() == ISD::BITCAST ||
8204 Ops[1].getOpcode() == ISD::BITCAST)) {
8207 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
8208 auto *BV2 = dyn_cast<BuildVectorSDNode>(N2);
8209 if (BV1 && BV2 && N1.getValueType().isInteger() &&
8210 N2.getValueType().isInteger()) {
8211 bool IsLE = getDataLayout().isLittleEndian();
8212 unsigned EltBits = VT.getScalarSizeInBits();
8213 SmallVector<APInt> RawBits1, RawBits2;
8214 BitVector UndefElts1, UndefElts2;
8215 if (BV1->getConstantRawBits(IsLE, EltBits, RawBits1, UndefElts1) &&
8216 BV2->getConstantRawBits(IsLE, EltBits, RawBits2, UndefElts2)) {
8217 SmallVector<APInt> RawBits;
8218 for (unsigned I = 0, E = NumElts.getFixedValue(); I != E; ++I) {
8219 std::optional<APInt> Fold = FoldValueWithUndef(
8220 Opcode, RawBits1[I], UndefElts1[I], RawBits2[I], UndefElts2[I]);
8221 if (!Fold)
8222 break;
8223 RawBits.push_back(*Fold);
8224 }
8225 if (RawBits.size() == NumElts.getFixedValue()) {
8226 // We have constant folded, but we might need to cast this again back
8227 // to the original (possibly legalized) type.
8228 EVT BVVT, BVEltVT;
8229 if (N1.getValueType() == VT) {
8230 BVVT = N1.getValueType();
8231 BVEltVT = BV1->getOperand(0).getValueType();
8232 } else {
8233 BVVT = N2.getValueType();
8234 BVEltVT = BV2->getOperand(0).getValueType();
8235 }
8236 unsigned BVEltBits = BVEltVT.getSizeInBits();
8237 SmallVector<APInt> DstBits;
8238 BitVector DstUndefs;
8240 DstBits, RawBits, DstUndefs,
8241 BitVector(RawBits.size(), false));
8242 SmallVector<SDValue> Ops(DstBits.size(), getUNDEF(BVEltVT));
8243 for (unsigned I = 0, E = DstBits.size(); I != E; ++I) {
8244 if (DstUndefs[I])
8245 continue;
8246 Ops[I] = getConstant(DstBits[I].sext(BVEltBits), DL, BVEltVT);
8247 }
8248 return getBitcast(VT, getBuildVector(BVVT, DL, Ops));
8249 }
8250 }
8251 }
8252 // Logic ops can be folded from raw integer bits - mainly for AVX512 masks.
8253 if (ISD::isBitwiseLogicOp(Opcode) && isa<ConstantSDNode>(N1) &&
8254 isa<ConstantSDNode>(N2)) {
8255 if (SDValue Res = FoldConstantArithmetic(Opcode, DL, N1.getValueType(),
8256 {N1, N2}, Flags))
8257 return getBitcast(VT, Res);
8258 }
8259 }
8260
8261 // Fold (mul step_vector(C0), C1) to (step_vector(C0 * C1)).
8262 // (shl step_vector(C0), C1) -> (step_vector(C0 << C1))
8263 if ((Opcode == ISD::MUL || Opcode == ISD::SHL) &&
8264 Ops[0].getOpcode() == ISD::STEP_VECTOR) {
8265 APInt RHSVal;
8266 if (ISD::isConstantSplatVector(Ops[1].getNode(), RHSVal)) {
8267 APInt NewStep = Opcode == ISD::MUL
8268 ? Ops[0].getConstantOperandAPInt(0) * RHSVal
8269 : Ops[0].getConstantOperandAPInt(0) << RHSVal;
8270 return getStepVector(DL, VT, NewStep);
8271 }
8272 }
8273
8274 auto IsScalarOrSameVectorSize = [NumElts](const SDValue &Op) {
8275 return !Op.getValueType().isVector() ||
8276 Op.getValueType().getVectorElementCount() == NumElts;
8277 };
8278
8279 auto IsBuildVectorSplatVectorOrUndef = [](const SDValue &Op) {
8280 return Op.isUndef() || Op.getOpcode() == ISD::CONDCODE ||
8281 Op.getOpcode() == ISD::BUILD_VECTOR ||
8282 Op.getOpcode() == ISD::SPLAT_VECTOR;
8283 };
8284
8285 // All operands must be vector types with the same number of elements as
8286 // the result type and must be either UNDEF or a build/splat vector
8287 // or UNDEF scalars.
8288 if (!llvm::all_of(Ops, IsBuildVectorSplatVectorOrUndef) ||
8289 !llvm::all_of(Ops, IsScalarOrSameVectorSize))
8290 return SDValue();
8291
8292 // If we are comparing vectors, then the result needs to be a i1 boolean that
8293 // is then extended back to the legal result type depending on how booleans
8294 // are represented.
8295 EVT SVT = (Opcode == ISD::SETCC ? MVT::i1 : VT.getScalarType());
8296 ISD::NodeType ExtendCode =
8297 (Opcode == ISD::SETCC && SVT != VT.getScalarType())
8298 ? TargetLowering::getExtendForContent(TLI->getBooleanContents(VT))
8300
8301 // Find legal integer scalar type for constant promotion and
8302 // ensure that its scalar size is at least as large as source.
8303 EVT LegalSVT = VT.getScalarType();
8304 if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
8305 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
8306 if (LegalSVT.bitsLT(VT.getScalarType()))
8307 return SDValue();
8308 }
8309
8310 // For scalable vector types we know we're dealing with SPLAT_VECTORs. We
8311 // only have one operand to check. For fixed-length vector types we may have
8312 // a combination of BUILD_VECTOR and SPLAT_VECTOR.
8313 unsigned NumVectorElts = NumElts.isScalable() ? 1 : NumElts.getFixedValue();
8314
8315 // Constant fold each scalar lane separately.
8316 SmallVector<SDValue, 4> ScalarResults;
8317 for (unsigned I = 0; I != NumVectorElts; I++) {
8318 SmallVector<SDValue, 4> ScalarOps;
8319 for (SDValue Op : Ops) {
8320 EVT InSVT = Op.getValueType().getScalarType();
8321 if (Op.getOpcode() != ISD::BUILD_VECTOR &&
8322 Op.getOpcode() != ISD::SPLAT_VECTOR) {
8323 if (Op.isUndef())
8324 ScalarOps.push_back(getUNDEF(InSVT));
8325 else
8326 ScalarOps.push_back(Op);
8327 continue;
8328 }
8329
8330 SDValue ScalarOp =
8331 Op.getOperand(Op.getOpcode() == ISD::SPLAT_VECTOR ? 0 : I);
8332 EVT ScalarVT = ScalarOp.getValueType();
8333
8334 // Build vector (integer) scalar operands may need implicit
8335 // truncation - do this before constant folding.
8336 if (ScalarVT.isInteger() && ScalarVT.bitsGT(InSVT)) {
8337 // Don't create illegally-typed nodes unless they're constants or undef
8338 // - if we fail to constant fold we can't guarantee the (dead) nodes
8339 // we're creating will be cleaned up before being visited for
8340 // legalization.
8341 if (NewNodesMustHaveLegalTypes && !ScalarOp.isUndef() &&
8342 !isa<ConstantSDNode>(ScalarOp) &&
8343 TLI->getTypeAction(*getContext(), InSVT) !=
8345 return SDValue();
8346 ScalarOp = getNode(ISD::TRUNCATE, DL, InSVT, ScalarOp);
8347 }
8348
8349 ScalarOps.push_back(ScalarOp);
8350 }
8351
8352 // Constant fold the scalar operands.
8353 SDValue ScalarResult = getNode(Opcode, DL, SVT, ScalarOps, Flags);
8354
8355 // Scalar folding only succeeded if the result is a constant or UNDEF.
8356 if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant &&
8357 ScalarResult.getOpcode() != ISD::ConstantFP)
8358 return SDValue();
8359
8360 // Legalize the (integer) scalar constant if necessary. We only do
8361 // this once we know the folding succeeded, since otherwise we would
8362 // get a node with illegal type which has a user.
8363 if (LegalSVT != SVT)
8364 ScalarResult = getNode(ExtendCode, DL, LegalSVT, ScalarResult);
8365
8366 ScalarResults.push_back(ScalarResult);
8367 }
8368
8369 SDValue V = NumElts.isScalable() ? getSplatVector(VT, DL, ScalarResults[0])
8370 : getBuildVector(VT, DL, ScalarResults);
8371 NewSDValueDbgMsg(V, "New node fold constant vector: ", this);
8372 return V;
8373}
8374
8376 SDVTList VTList,
8378 SDNodeFlags Flags) {
8379 if (VTList.NumVTs == 1)
8380 return FoldConstantArithmetic(Opcode, DL, VTList.VTs[0], Ops, Flags);
8381
8382 switch (Opcode) {
8383 case ISD::SADDO:
8384 case ISD::UADDO:
8385 case ISD::SSUBO:
8386 case ISD::USUBO:
8387 case ISD::SMULO:
8388 case ISD::UMULO: {
8389 // TODO: Support non-splat vector constants.
8392 if (!C1 || !C2 || C1->isOpaque() || C2->isOpaque())
8393 return SDValue();
8394
8395 const APInt &V1 = C1->getAPIntValue(), &V2 = C2->getAPIntValue();
8396 bool Overflow;
8397 APInt Result;
8398 switch (Opcode) {
8399 default:
8400 llvm_unreachable("Unexpected overflow opcode");
8401 case ISD::SADDO:
8402 Result = V1.sadd_ov(V2, Overflow);
8403 break;
8404 case ISD::UADDO:
8405 Result = V1.uadd_ov(V2, Overflow);
8406 break;
8407 case ISD::SSUBO:
8408 Result = V1.ssub_ov(V2, Overflow);
8409 break;
8410 case ISD::USUBO:
8411 Result = V1.usub_ov(V2, Overflow);
8412 break;
8413 case ISD::SMULO:
8414 Result = V1.smul_ov(V2, Overflow);
8415 break;
8416 case ISD::UMULO:
8417 Result = V1.umul_ov(V2, Overflow);
8418 break;
8419 }
8420
8421 EVT VT = VTList.VTs[0];
8422 return getNode(ISD::MERGE_VALUES, DL, VTList,
8423 {getConstant(Result, DL, VT),
8424 getBoolConstant(Overflow, DL, VTList.VTs[1], VT)},
8425 Flags);
8426 }
8427 case ISD::SMUL_LOHI:
8428 case ISD::UMUL_LOHI:
8429 // TODO: Support non-splat vector constants.
8432 if (!C1 || !C2 || C1->isOpaque() || C2->isOpaque())
8433 return SDValue();
8434
8435 const APInt &V1 = C1->getAPIntValue(), &V2 = C2->getAPIntValue();
8436 APInt Lo = V1 * V2;
8437 APInt Hi = (Opcode == ISD::SMUL_LOHI) ? APIntOps::mulhs(V1, V2)
8438 : APIntOps::mulhu(V1, V2);
8439 return getNode(ISD::MERGE_VALUES, DL, VTList,
8440 {getConstant(Lo, DL, VTList.VTs[0]),
8441 getConstant(Hi, DL, VTList.VTs[1])},
8442 Flags);
8443 }
8444 return SDValue();
8445}
8446
8449 // TODO: Add support for unary/ternary fp opcodes.
8450 if (Ops.size() != 2)
8451 return SDValue();
8452
8453 // TODO: We don't do any constant folding for strict FP opcodes here, but we
8454 // should. That will require dealing with a potentially non-default
8455 // rounding mode, checking the "opStatus" return value from the APFloat
8456 // math calculations, and possibly other variations.
8457 SDValue N1 = Ops[0];
8458 SDValue N2 = Ops[1];
8459 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1, /*AllowUndefs*/ false);
8460 ConstantFPSDNode *N2CFP = isConstOrConstSplatFP(N2, /*AllowUndefs*/ false);
8461 if (N1CFP && N2CFP) {
8462 APFloat C1 = N1CFP->getValueAPF(); // make copy
8463 const APFloat &C2 = N2CFP->getValueAPF();
8464 switch (Opcode) {
8465 case ISD::FADD:
8467 return getConstantFP(C1, DL, VT);
8468 case ISD::FSUB:
8469 C1.subtract(C2, APFloat::rmNearestTiesToEven);
8470 return getConstantFP(C1, DL, VT);
8471 case ISD::FMUL:
8472 C1.multiply(C2, APFloat::rmNearestTiesToEven);
8473 return getConstantFP(C1, DL, VT);
8474 case ISD::FDIV:
8475 C1.divide(C2, APFloat::rmNearestTiesToEven);
8476 return getConstantFP(C1, DL, VT);
8477 case ISD::FREM:
8478 C1.mod(C2);
8479 return getConstantFP(C1, DL, VT);
8480 case ISD::FCOPYSIGN:
8481 C1.copySign(C2);
8482 return getConstantFP(C1, DL, VT);
8483 case ISD::FMINNUM:
8484 return getConstantFP(minnum(C1, C2), DL, VT);
8485 case ISD::FMAXNUM:
8486 return getConstantFP(maxnum(C1, C2), DL, VT);
8487 case ISD::FMINIMUM:
8488 return getConstantFP(minimum(C1, C2), DL, VT);
8489 case ISD::FMAXIMUM:
8490 return getConstantFP(maximum(C1, C2), DL, VT);
8491 case ISD::FMINIMUMNUM:
8492 return getConstantFP(minimumnum(C1, C2), DL, VT);
8493 case ISD::FMAXIMUMNUM:
8494 return getConstantFP(maximumnum(C1, C2), DL, VT);
8495 default: break;
8496 }
8497 }
8498 if (N1CFP && Opcode == ISD::FP_ROUND) {
8499 APFloat C1 = N1CFP->getValueAPF(); // make copy
8500 bool Unused;
8501 // This can return overflow, underflow, or inexact; we don't care.
8502 // FIXME need to be more flexible about rounding mode.
8504 &Unused);
8505 return getConstantFP(C1, DL, VT);
8506 }
8507
8508 switch (Opcode) {
8509 case ISD::FSUB:
8510 // -0.0 - undef --> undef (consistent with "fneg undef")
8511 if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1, /*AllowUndefs*/ true))
8512 if (N1C && N1C->getValueAPF().isNegZero() && N2.isUndef())
8513 return getUNDEF(VT);
8514 [[fallthrough]];
8515
8516 case ISD::FADD:
8517 case ISD::FMUL:
8518 case ISD::FDIV:
8519 case ISD::FREM:
8520 // If both operands are undef, the result is undef. If 1 operand is undef,
8521 // the result is NaN. This should match the behavior of the IR optimizer.
8522 if (N1.isUndef() && N2.isUndef())
8523 return getUNDEF(VT);
8524 if (N1.isUndef() || N2.isUndef())
8526 }
8527 return SDValue();
8528}
8529
8531 const SDLoc &DL, EVT DstEltVT) {
8532 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
8533
8534 // If this is already the right type, we're done.
8535 if (SrcEltVT == DstEltVT)
8536 return SDValue(BV, 0);
8537
8538 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
8539 unsigned DstBitSize = DstEltVT.getSizeInBits();
8540
8541 // If this is a conversion of N elements of one type to N elements of another
8542 // type, convert each element. This handles FP<->INT cases.
8543 if (SrcBitSize == DstBitSize) {
8545 for (SDValue Op : BV->op_values()) {
8546 // If the vector element type is not legal, the BUILD_VECTOR operands
8547 // are promoted and implicitly truncated. Make that explicit here.
8548 if (Op.getValueType() != SrcEltVT)
8549 Op = getNode(ISD::TRUNCATE, DL, SrcEltVT, Op);
8550 Ops.push_back(getBitcast(DstEltVT, Op));
8551 }
8552 EVT VT = EVT::getVectorVT(*getContext(), DstEltVT,
8554 return getBuildVector(VT, DL, Ops);
8555 }
8556
8557 // Otherwise, we're growing or shrinking the elements. To avoid having to
8558 // handle annoying details of growing/shrinking FP values, we convert them to
8559 // int first.
8560 if (SrcEltVT.isFloatingPoint()) {
8561 // Convert the input float vector to a int vector where the elements are the
8562 // same sizes.
8563 EVT IntEltVT = EVT::getIntegerVT(*getContext(), SrcEltVT.getSizeInBits());
8564 if (SDValue Tmp = FoldConstantBuildVector(BV, DL, IntEltVT))
8566 DstEltVT);
8567 return SDValue();
8568 }
8569
8570 // Now we know the input is an integer vector. If the output is a FP type,
8571 // convert to integer first, then to FP of the right size.
8572 if (DstEltVT.isFloatingPoint()) {
8573 EVT IntEltVT = EVT::getIntegerVT(*getContext(), DstEltVT.getSizeInBits());
8574 if (SDValue Tmp = FoldConstantBuildVector(BV, DL, IntEltVT))
8576 DstEltVT);
8577 return SDValue();
8578 }
8579
8580 // Okay, we know the src/dst types are both integers of differing types.
8581 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
8582
8583 // Extract the constant raw bit data.
8584 BitVector UndefElements;
8585 SmallVector<APInt> RawBits;
8586 bool IsLE = getDataLayout().isLittleEndian();
8587 if (!BV->getConstantRawBits(IsLE, DstBitSize, RawBits, UndefElements))
8588 return SDValue();
8589
8591 for (unsigned I = 0, E = RawBits.size(); I != E; ++I) {
8592 if (UndefElements[I])
8593 Ops.push_back(getUNDEF(DstEltVT));
8594 else
8595 Ops.push_back(getConstant(RawBits[I], DL, DstEltVT));
8596 }
8597
8598 EVT VT = EVT::getVectorVT(*getContext(), DstEltVT, Ops.size());
8599 return getBuildVector(VT, DL, Ops);
8600}
8601
8603 assert(Val.getValueType().isInteger() && "Invalid AssertAlign!");
8604
8605 // There's no need to assert on a byte-aligned pointer. All pointers are at
8606 // least byte aligned.
8607 if (A == Align(1))
8608 return Val;
8609
8610 SDVTList VTs = getVTList(Val.getValueType());
8611 SDValue Ops[] = {Val};
8612 SDNodeKey ID(ISD::AssertAlign, VTs, Ops);
8613 ID.AddInteger(A.value());
8614
8615 FoldingSetInsertToken InsertToken;
8616 if (SDNode *E = lookupNode(ID, DL, InsertToken))
8617 return SDValue(E, 0);
8618
8619 auto *N =
8620 newSDNode<AssertAlignSDNode>(DL.getIROrder(), DL.getDebugLoc(), VTs, A);
8621 createOperands(N, {Val});
8622
8623 CSEMap.insert(N, InsertToken);
8624 InsertNode(N);
8625
8626 SDValue V(N, 0);
8627 NewSDValueDbgMsg(V, "Creating new node: ", this);
8628 return V;
8629}
8630
8631SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8632 SDValue N1, SDValue N2) {
8633 SDNodeFlags Flags;
8634 if (Inserter)
8635 Flags = Inserter->getFlags();
8636 return getNode(Opcode, DL, VT, N1, N2, Flags);
8637}
8638
8640 SDValue &N2) const {
8641 if (!TLI->isCommutativeBinOp(Opcode))
8642 return;
8643
8644 // Canonicalize:
8645 // binop(const, nonconst) -> binop(nonconst, const)
8648 bool N1CFP = isConstantFPBuildVectorOrConstantFP(N1);
8649 bool N2CFP = isConstantFPBuildVectorOrConstantFP(N2);
8650 if ((N1C && !N2C) || (N1CFP && !N2CFP))
8651 std::swap(N1, N2);
8652
8653 // Canonicalize:
8654 // binop(splat(x), step_vector) -> binop(step_vector, splat(x))
8655 else if (N1.getOpcode() == ISD::SPLAT_VECTOR &&
8657 std::swap(N1, N2);
8658}
8659
8660SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8661 SDValue N1, SDValue N2, const SDNodeFlags Flags) {
8663 N2.getOpcode() != ISD::DELETED_NODE &&
8664 "Operand is DELETED_NODE!");
8665
8666 canonicalizeCommutativeBinop(Opcode, N1, N2);
8667
8668 auto *N1C = dyn_cast<ConstantSDNode>(N1);
8669 auto *N2C = dyn_cast<ConstantSDNode>(N2);
8670
8671 // Don't allow undefs in vector splats - we might be returning N2 when folding
8672 // to zero etc.
8673 ConstantSDNode *N2CV =
8674 isConstOrConstSplat(N2, /*AllowUndefs*/ false, /*AllowTruncation*/ true);
8675
8676 switch (Opcode) {
8677 default: break;
8678 case ISD::TokenFactor:
8679 assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
8680 N2.getValueType() == MVT::Other && "Invalid token factor!");
8681 // Fold trivial token factors.
8682 if (N1.getOpcode() == ISD::EntryToken) return N2;
8683 if (N2.getOpcode() == ISD::EntryToken) return N1;
8684 if (N1 == N2) return N1;
8685 break;
8686 case ISD::BUILD_VECTOR: {
8687 // Attempt to simplify BUILD_VECTOR.
8688 SDValue Ops[] = {N1, N2};
8689 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
8690 return V;
8691 break;
8692 }
8693 case ISD::CONCAT_VECTORS: {
8694 SDValue Ops[] = {N1, N2};
8695 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
8696 return V;
8697 break;
8698 }
8699 case ISD::AND:
8700 assert(VT.isInteger() && "This operator does not apply to FP types!");
8701 assert(N1.getValueType() == N2.getValueType() &&
8702 N1.getValueType() == VT && "Binary operator types must match!");
8703 // (X & 0) -> 0. This commonly occurs when legalizing i64 values, so it's
8704 // worth handling here.
8705 if (N2CV && N2CV->isZero())
8706 return N2;
8707 if (N2CV && N2CV->isAllOnes()) // X & -1 -> X
8708 return N1;
8709 break;
8710 case ISD::OR:
8711 case ISD::XOR:
8712 case ISD::ADD:
8713 case ISD::PTRADD:
8714 case ISD::SUB:
8715 assert(VT.isInteger() && "This operator does not apply to FP types!");
8716 assert(N1.getValueType() == N2.getValueType() &&
8717 N1.getValueType() == VT && "Binary operator types must match!");
8718 // The equal operand types requirement is unnecessarily strong for PTRADD.
8719 // However, the SelectionDAGBuilder does not generate PTRADDs with different
8720 // operand types, and we'd need to re-implement GEP's non-standard wrapping
8721 // logic everywhere where PTRADDs may be folded or combined to properly
8722 // support them. If/when we introduce pointer types to the SDAG, we will
8723 // need to relax this constraint.
8724
8725 // (X ^|+- 0) -> X. This commonly occurs when legalizing i64 values, so
8726 // it's worth handling here.
8727 if (N2CV && N2CV->isZero())
8728 return N1;
8729 if ((Opcode == ISD::ADD || Opcode == ISD::SUB) &&
8730 VT.getScalarType() == MVT::i1)
8731 return getNode(ISD::XOR, DL, VT, N1, N2);
8732 // Fold (add (vscale * C0), (vscale * C1)) to (vscale * (C0 + C1)).
8733 if (Opcode == ISD::ADD && N1.getOpcode() == ISD::VSCALE &&
8734 N2.getOpcode() == ISD::VSCALE) {
8735 const APInt &C1 = N1->getConstantOperandAPInt(0);
8736 const APInt &C2 = N2->getConstantOperandAPInt(0);
8737 return getVScale(DL, VT, C1 + C2);
8738 }
8739 break;
8740 case ISD::MUL:
8741 assert(VT.isInteger() && "This operator does not apply to FP types!");
8742 assert(N1.getValueType() == N2.getValueType() &&
8743 N1.getValueType() == VT && "Binary operator types must match!");
8744 if (VT.getScalarType() == MVT::i1)
8745 return getNode(ISD::AND, DL, VT, N1, N2);
8746 if (N2CV && N2CV->isZero())
8747 return N2;
8748 if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
8749 const APInt &MulImm = N1->getConstantOperandAPInt(0);
8750 const APInt &N2CImm = N2C->getAPIntValue();
8751 return getVScale(DL, VT, MulImm * N2CImm);
8752 }
8753 break;
8754 case ISD::UDIV:
8755 case ISD::UREM:
8756 case ISD::MULHU:
8757 case ISD::MULHS:
8758 case ISD::SDIV:
8759 case ISD::SREM:
8760 case ISD::SADDSAT:
8761 case ISD::SSUBSAT:
8762 case ISD::UADDSAT:
8763 case ISD::USUBSAT:
8764 assert(VT.isInteger() && "This operator does not apply to FP types!");
8765 assert(N1.getValueType() == N2.getValueType() &&
8766 N1.getValueType() == VT && "Binary operator types must match!");
8767 if (VT.getScalarType() == MVT::i1) {
8768 // fold (add_sat x, y) -> (or x, y) for bool types.
8769 if (Opcode == ISD::SADDSAT || Opcode == ISD::UADDSAT)
8770 return getNode(ISD::OR, DL, VT, N1, N2);
8771 // fold (sub_sat x, y) -> (and x, ~y) for bool types.
8772 if (Opcode == ISD::SSUBSAT || Opcode == ISD::USUBSAT)
8773 return getNode(ISD::AND, DL, VT, N1, getNOT(DL, N2, VT));
8774 // mulhs/mulhu on i1 are always 0: the high bit of the 2-bit product of
8775 // two booleans is never set. The i1 constant 1 is also -1, so folding
8776 // (mulhs x, 1) to (sra x, 0) in DAGCombiner would be wrong here.
8777 if (Opcode == ISD::MULHS || Opcode == ISD::MULHU)
8778 return getConstant(0, DL, VT);
8779 }
8780 break;
8781 case ISD::SCMP:
8782 case ISD::UCMP:
8783 assert(N1.getValueType() == N2.getValueType() &&
8784 "Types of operands of UCMP/SCMP must match");
8785 assert(N1.getValueType().isVector() == VT.isVector() &&
8786 "Operands and return type of must both be scalars or vectors");
8787 if (VT.isVector())
8790 "Result and operands must have the same number of elements");
8791 break;
8792 case ISD::AVGFLOORS:
8793 case ISD::AVGFLOORU:
8794 case ISD::AVGCEILS:
8795 case ISD::AVGCEILU:
8796 case ISD::AVGSUBFLOORS:
8797 case ISD::AVGSUBFLOORU:
8798 assert(VT.isInteger() && "This operator does not apply to FP types!");
8799 assert(N1.getValueType() == N2.getValueType() &&
8800 N1.getValueType() == VT && "Binary operator types must match!");
8801 break;
8802 case ISD::ABDS:
8803 case ISD::ABDU:
8804 assert(VT.isInteger() && "This operator does not apply to FP types!");
8805 assert(N1.getValueType() == N2.getValueType() &&
8806 N1.getValueType() == VT && "Binary operator types must match!");
8807 if (VT.getScalarType() == MVT::i1)
8808 return getNode(ISD::XOR, DL, VT, N1, N2);
8809 break;
8810 case ISD::SMIN:
8811 case ISD::UMAX:
8812 assert(VT.isInteger() && "This operator does not apply to FP types!");
8813 assert(N1.getValueType() == N2.getValueType() &&
8814 N1.getValueType() == VT && "Binary operator types must match!");
8815 if (VT.getScalarType() == MVT::i1)
8816 return getNode(ISD::OR, DL, VT, N1, N2);
8817 break;
8818 case ISD::SMAX:
8819 case ISD::UMIN:
8820 assert(VT.isInteger() && "This operator does not apply to FP types!");
8821 assert(N1.getValueType() == N2.getValueType() &&
8822 N1.getValueType() == VT && "Binary operator types must match!");
8823 if (VT.getScalarType() == MVT::i1)
8824 return getNode(ISD::AND, DL, VT, N1, N2);
8825 break;
8826 case ISD::FADD:
8827 case ISD::FSUB:
8828 case ISD::FMUL:
8829 case ISD::FDIV:
8830 case ISD::FREM:
8831 assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
8832 assert(N1.getValueType() == N2.getValueType() &&
8833 N1.getValueType() == VT && "Binary operator types must match!");
8834 if (SDValue V = simplifyFPBinop(Opcode, N1, N2, Flags))
8835 return V;
8836 break;
8837 case ISD::FCOPYSIGN: // N1 and result must match. N1/N2 need not match.
8838 assert(N1.getValueType() == VT &&
8841 "Invalid FCOPYSIGN!");
8842 break;
8843 case ISD::SHL:
8844 if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
8845 const APInt &MulImm = N1->getConstantOperandAPInt(0);
8846 const APInt &ShiftImm = N2C->getAPIntValue();
8847 return getVScale(DL, VT, MulImm << ShiftImm);
8848 }
8849 [[fallthrough]];
8850 case ISD::SRA:
8851 case ISD::SRL:
8852 if (SDValue V = simplifyShift(N1, N2))
8853 return V;
8854 [[fallthrough]];
8855 case ISD::ROTL:
8856 case ISD::ROTR:
8857 case ISD::SSHLSAT:
8858 case ISD::USHLSAT:
8859 assert(VT == N1.getValueType() &&
8860 "Shift operators return type must be the same as their first arg");
8861 assert(VT.isInteger() && N2.getValueType().isInteger() &&
8862 "Shifts only work on integers");
8863 assert((!VT.isVector() || VT == N2.getValueType()) &&
8864 "Vector shift amounts must be in the same as their first arg");
8865 // Verify that the shift amount VT is big enough to hold valid shift
8866 // amounts. This catches things like trying to shift an i1024 value by an
8867 // i8, which is easy to fall into in generic code that uses
8868 // TLI.getShiftAmount().
8871 "Invalid use of small shift amount with oversized value!");
8872
8873 // Always fold shifts of i1 values so the code generator doesn't need to
8874 // handle them. Since we know the size of the shift has to be less than the
8875 // size of the value, the shift/rotate count is guaranteed to be zero.
8876 if (VT == MVT::i1)
8877 return N1;
8878 if (N2CV && N2CV->isZero())
8879 return N1;
8880 break;
8881 case ISD::FP_ROUND:
8883 VT.bitsLE(N1.getValueType()) && N2C &&
8884 (N2C->getZExtValue() == 0 || N2C->getZExtValue() == 1) &&
8885 N2.getOpcode() == ISD::TargetConstant && "Invalid FP_ROUND!");
8886 if (N1.getValueType() == VT) return N1; // noop conversion.
8887 break;
8888 case ISD::IS_FPCLASS: {
8890 "IS_FPCLASS is used for a non-floating type");
8891 assert(isa<ConstantSDNode>(N2) && "FPClassTest is not Constant");
8892 // is.fpclass(poison, mask) -> poison
8893 if (N1.getOpcode() == ISD::POISON)
8894 return getPOISON(VT);
8895 FPClassTest Mask = static_cast<FPClassTest>(N2->getAsZExtVal());
8896 // If all tests are made, it doesn't matter what the value is.
8897 if ((Mask & fcAllFlags) == fcAllFlags)
8898 return getBoolConstant(true, DL, VT, N1.getValueType());
8899 if ((Mask & fcAllFlags) == 0)
8900 return getBoolConstant(false, DL, VT, N1.getValueType());
8901 break;
8902 }
8903 case ISD::AssertNoFPClass: {
8905 "AssertNoFPClass is used for a non-floating type");
8906 assert(isa<ConstantSDNode>(N2) && "NoFPClass is not Constant");
8907 FPClassTest NoFPClass = static_cast<FPClassTest>(N2->getAsZExtVal());
8908 assert(llvm::to_underlying(NoFPClass) <=
8910 "FPClassTest value too large");
8911 (void)NoFPClass;
8912 break;
8913 }
8914 case ISD::AssertSext:
8915 case ISD::AssertZext: {
8916 EVT EVT = cast<VTSDNode>(N2)->getVT();
8917 assert(VT == N1.getValueType() && "Not an inreg extend!");
8918 assert(VT.isInteger() && EVT.isInteger() &&
8919 "Cannot *_EXTEND_INREG FP types");
8920 assert(!EVT.isVector() &&
8921 "AssertSExt/AssertZExt type should be the vector element type "
8922 "rather than the vector type!");
8923 assert(EVT.bitsLE(VT.getScalarType()) && "Not extending!");
8924 if (VT.getScalarType() == EVT) return N1; // noop assertion.
8925 break;
8926 }
8928 EVT EVT = cast<VTSDNode>(N2)->getVT();
8929 assert(VT == N1.getValueType() && "Not an inreg extend!");
8930 assert(VT.isInteger() && EVT.isInteger() &&
8931 "Cannot *_EXTEND_INREG FP types");
8932 assert(EVT.isVector() == VT.isVector() &&
8933 "SIGN_EXTEND_INREG type should be vector iff the operand "
8934 "type is vector!");
8935 assert((!EVT.isVector() ||
8937 "Vector element counts must match in SIGN_EXTEND_INREG");
8938 assert(EVT.getScalarType().bitsLE(VT.getScalarType()) && "Not extending!");
8939 if (EVT == VT) return N1; // Not actually extending
8940 break;
8941 }
8943 case ISD::FP_TO_UINT_SAT: {
8944 assert(VT.isInteger() && cast<VTSDNode>(N2)->getVT().isInteger() &&
8945 N1.getValueType().isFloatingPoint() && "Invalid FP_TO_*INT_SAT");
8946 assert(N1.getValueType().isVector() == VT.isVector() &&
8947 "FP_TO_*INT_SAT type should be vector iff the operand type is "
8948 "vector!");
8949 assert((!VT.isVector() || VT.getVectorElementCount() ==
8951 "Vector element counts must match in FP_TO_*INT_SAT");
8952 assert(!cast<VTSDNode>(N2)->getVT().isVector() &&
8953 "Type to saturate to must be a scalar.");
8954 assert(cast<VTSDNode>(N2)->getVT().bitsLE(VT.getScalarType()) &&
8955 "Not extending!");
8956 break;
8957 }
8960 "The result of EXTRACT_VECTOR_ELT must be at least as wide as the \
8961 element type of the vector.");
8962
8963 // Extract from an undefined value or using an undefined index is undefined.
8964 if (N1.isUndef() || N2.isUndef())
8965 return getUNDEF(VT);
8966
8967 // EXTRACT_VECTOR_ELT of out-of-bounds element is POISON for fixed length
8968 // vectors. For scalable vectors we will provide appropriate support for
8969 // dealing with arbitrary indices.
8970 if (N2C && N1.getValueType().isFixedLengthVector() &&
8971 N2C->getAPIntValue().uge(N1.getValueType().getVectorNumElements()))
8972 return getPOISON(VT);
8973
8974 // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
8975 // expanding copies of large vectors from registers. This only works for
8976 // fixed length vectors, since we need to know the exact number of
8977 // elements.
8978 if (N2C && N1.getOpcode() == ISD::CONCAT_VECTORS &&
8980 unsigned Factor = N1.getOperand(0).getValueType().getVectorNumElements();
8981 return getExtractVectorElt(DL, VT,
8982 N1.getOperand(N2C->getZExtValue() / Factor),
8983 N2C->getZExtValue() % Factor);
8984 }
8985
8986 // EXTRACT_VECTOR_ELT of BUILD_VECTOR or SPLAT_VECTOR is often formed while
8987 // lowering is expanding large vector constants.
8988 if (N2C && (N1.getOpcode() == ISD::BUILD_VECTOR ||
8989 N1.getOpcode() == ISD::SPLAT_VECTOR)) {
8992 "BUILD_VECTOR used for scalable vectors");
8993 unsigned Index =
8994 N1.getOpcode() == ISD::BUILD_VECTOR ? N2C->getZExtValue() : 0;
8995 SDValue Elt = N1.getOperand(Index);
8996
8997 if (VT != Elt.getValueType())
8998 // If the vector element type is not legal, the BUILD_VECTOR operands
8999 // are promoted and implicitly truncated, and the result implicitly
9000 // extended. Make that explicit here.
9001 Elt = getAnyExtOrTrunc(Elt, DL, VT);
9002
9003 return Elt;
9004 }
9005
9006 // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
9007 // operations are lowered to scalars.
9008 if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) {
9009 // If the indices are the same, return the inserted element else
9010 // if the indices are known different, extract the element from
9011 // the original vector.
9012 SDValue N1Op2 = N1.getOperand(2);
9014
9015 if (N1Op2C && N2C) {
9016 if (N1Op2C->getZExtValue() == N2C->getZExtValue()) {
9017 if (VT == N1.getOperand(1).getValueType())
9018 return N1.getOperand(1);
9019 if (VT.isFloatingPoint()) {
9021 return getFPExtendOrRound(N1.getOperand(1), DL, VT);
9022 }
9023 return getSExtOrTrunc(N1.getOperand(1), DL, VT);
9024 }
9025 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2);
9026 }
9027 }
9028
9029 // EXTRACT_VECTOR_ELT of v1iX EXTRACT_SUBVECTOR could be formed
9030 // when vector types are scalarized and v1iX is legal.
9031 // vextract (v1iX extract_subvector(vNiX, Idx)) -> vextract(vNiX,Idx).
9032 // Here we are completely ignoring the extract element index (N2),
9033 // which is fine for fixed width vectors, since any index other than 0
9034 // is undefined anyway. However, this cannot be ignored for scalable
9035 // vectors - in theory we could support this, but we don't want to do this
9036 // without a profitability check.
9037 if (N1.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
9039 N1.getValueType().getVectorNumElements() == 1) {
9040 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0),
9041 N1.getOperand(1));
9042 }
9043 break;
9045 assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!");
9046 assert(!N1.getValueType().isVector() && !VT.isVector() &&
9047 (N1.getValueType().isInteger() == VT.isInteger()) &&
9048 N1.getValueType() != VT &&
9049 "Wrong types for EXTRACT_ELEMENT!");
9050
9051 // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
9052 // 64-bit integers into 32-bit parts. Instead of building the extract of
9053 // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
9054 if (N1.getOpcode() == ISD::BUILD_PAIR)
9055 return N1.getOperand(N2C->getZExtValue());
9056
9057 // EXTRACT_ELEMENT of a constant int is also very common.
9058 if (N1C) {
9059 unsigned ElementSize = VT.getSizeInBits();
9060 unsigned Shift = ElementSize * N2C->getZExtValue();
9061 const APInt &Val = N1C->getAPIntValue();
9062 return getConstant(Val.extractBits(ElementSize, Shift), DL, VT);
9063 }
9064 break;
9066 [[maybe_unused]] EVT MaskVT = N2.getValueType();
9067 assert(VT == N1.getValueType() &&
9068 "VECTOR_SHUFFLE_VAR result and source types don't match.");
9069 assert(VT.isVector() && MaskVT.isVector() &&
9070 "VECTOR_SHUFFLE_VAR operands must be vectors.");
9072 "VECTOR_SHUFFLE_VAR mask must be a vector of integers.");
9074 "VECTOR_SHUFFLE_VAR mask has the wrong number of elements.");
9075 break;
9076 }
9078 EVT N1VT = N1.getValueType();
9079 assert(VT.isVector() && N1VT.isVector() &&
9080 "Extract subvector VTs must be vectors!");
9082 "Extract subvector VTs must have the same element type!");
9083 assert((VT.isFixedLengthVector() || N1VT.isScalableVector()) &&
9084 "Cannot extract a scalable vector from a fixed length vector!");
9085 assert((VT.isScalableVector() != N1VT.isScalableVector() ||
9087 "Extract subvector must be from larger vector to smaller vector!");
9088 assert(N2C && "Extract subvector index must be a constant");
9089 assert((VT.isScalableVector() != N1VT.isScalableVector() ||
9090 (VT.getVectorMinNumElements() + N2C->getZExtValue()) <=
9091 N1VT.getVectorMinNumElements()) &&
9092 "Extract subvector overflow!");
9093 assert(N2C->getAPIntValue().getBitWidth() ==
9094 TLI->getVectorIdxWidth(getDataLayout()) &&
9095 "Constant index for EXTRACT_SUBVECTOR has an invalid size");
9096 assert(N2C->getZExtValue() % VT.getVectorMinNumElements() == 0 &&
9097 "Extract index is not a multiple of the output vector length");
9098
9099 // Trivial extraction.
9100 if (VT == N1VT)
9101 return N1;
9102
9103 // EXTRACT_SUBVECTOR of an UNDEF is an UNDEF.
9104 if (N1.isUndef())
9105 return getUNDEF(VT);
9106
9107 // EXTRACT_SUBVECTOR of CONCAT_VECTOR can be simplified if the pieces of
9108 // the concat have the same type as the extract.
9109 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
9110 VT == N1.getOperand(0).getValueType()) {
9111 unsigned Factor = VT.getVectorMinNumElements();
9112 return N1.getOperand(N2C->getZExtValue() / Factor);
9113 }
9114
9115 // EXTRACT_SUBVECTOR of INSERT_SUBVECTOR is often created
9116 // during shuffle legalization.
9117 if (N1.getOpcode() == ISD::INSERT_SUBVECTOR && N2 == N1.getOperand(2) &&
9118 VT == N1.getOperand(1).getValueType())
9119 return N1.getOperand(1);
9120 break;
9121 }
9122 }
9123
9124 if (N1.getOpcode() == ISD::POISON || N2.getOpcode() == ISD::POISON) {
9125 switch (Opcode) {
9126 case ISD::XOR:
9127 case ISD::ADD:
9128 case ISD::PTRADD:
9129 case ISD::SUB:
9131 case ISD::UDIV:
9132 case ISD::SDIV:
9133 case ISD::UREM:
9134 case ISD::SREM:
9135 case ISD::MUL:
9136 case ISD::AND:
9137 case ISD::SSUBSAT:
9138 case ISD::USUBSAT:
9139 case ISD::UMIN:
9140 case ISD::OR:
9141 case ISD::SADDSAT:
9142 case ISD::UADDSAT:
9143 case ISD::UMAX:
9144 case ISD::SMAX:
9145 case ISD::SMIN:
9146 // fold op(arg1, poison) -> poison, fold op(poison, arg2) -> poison.
9147 return N2.getOpcode() == ISD::POISON ? N2 : N1;
9148 }
9149 }
9150
9151 // Canonicalize an UNDEF to the RHS, even over a constant.
9152 if (N1.getOpcode() == ISD::UNDEF && N2.getOpcode() != ISD::UNDEF) {
9153 if (TLI->isCommutativeBinOp(Opcode)) {
9154 std::swap(N1, N2);
9155 } else {
9156 switch (Opcode) {
9157 case ISD::PTRADD:
9158 case ISD::SUB:
9159 // fold op(undef, non_undef_arg2) -> undef.
9160 return N1;
9162 case ISD::UDIV:
9163 case ISD::SDIV:
9164 case ISD::UREM:
9165 case ISD::SREM:
9166 case ISD::SSUBSAT:
9167 case ISD::USUBSAT:
9168 // fold op(undef, non_undef_arg2) -> 0.
9169 return getConstant(0, DL, VT);
9170 }
9171 }
9172 }
9173
9174 // Fold a bunch of operators when the RHS is undef.
9175 if (N2.getOpcode() == ISD::UNDEF) {
9176 switch (Opcode) {
9177 case ISD::XOR:
9178 if (N1.getOpcode() == ISD::UNDEF)
9179 // Handle undef ^ undef -> 0 special case. This is a common
9180 // idiom (misuse).
9181 return getConstant(0, DL, VT);
9182 [[fallthrough]];
9183 case ISD::ADD:
9184 case ISD::PTRADD:
9185 case ISD::SUB:
9186 // fold op(arg1, undef) -> undef.
9187 return N2;
9188 case ISD::UDIV:
9189 case ISD::SDIV:
9190 case ISD::UREM:
9191 case ISD::SREM:
9192 // fold op(arg1, undef) -> poison.
9193 return getPOISON(VT);
9194 case ISD::MUL:
9195 case ISD::AND:
9196 case ISD::SSUBSAT:
9197 case ISD::USUBSAT:
9198 case ISD::UMIN:
9199 // fold op(undef, undef) -> undef, fold op(arg1, undef) -> 0.
9200 return N1.getOpcode() == ISD::UNDEF ? N2 : getConstant(0, DL, VT);
9201 case ISD::OR:
9202 case ISD::SADDSAT:
9203 case ISD::UADDSAT:
9204 case ISD::UMAX:
9205 // fold op(undef, undef) -> undef, fold op(arg1, undef) -> -1.
9206 return N1.getOpcode() == ISD::UNDEF ? N2 : getAllOnesConstant(DL, VT);
9207 case ISD::SMAX:
9208 // fold op(undef, undef) -> undef, fold op(arg1, undef) -> MAX_INT.
9209 return N1.getOpcode() == ISD::UNDEF
9210 ? N2
9211 : getConstant(
9213 VT);
9214 case ISD::SMIN:
9215 // fold op(undef, undef) -> undef, fold op(arg1, undef) -> MIN_INT.
9216 return N1.getOpcode() == ISD::UNDEF
9217 ? N2
9218 : getConstant(
9220 VT);
9221 }
9222 }
9223
9224 // Perform trivial constant folding.
9225 if (SDValue SV = FoldConstantArithmetic(Opcode, DL, VT, {N1, N2}, Flags))
9226 return SV;
9227
9228 // Memoize this node if possible.
9229 SDNode *N;
9230 SDVTList VTs = getVTList(VT);
9231 SDValue Ops[] = {N1, N2};
9232 if (VT != MVT::Glue) {
9233 SDNodeKey ID(Opcode, VTs, Ops);
9234 FoldingSetInsertToken InsertToken;
9235 if (SDNode *E = lookupNode(ID, DL, InsertToken)) {
9236 E->intersectFlagsWith(Flags);
9237 return SDValue(E, 0);
9238 }
9239
9240 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
9241 N->setFlags(Flags);
9242 createOperands(N, Ops);
9243 CSEMap.insert(N, InsertToken);
9244 } else {
9245 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
9246 createOperands(N, Ops);
9247 }
9248
9249 InsertNode(N);
9250 SDValue V = SDValue(N, 0);
9251 NewSDValueDbgMsg(V, "Creating new node: ", this);
9252 return V;
9253}
9254
9255SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
9256 SDValue N1, SDValue N2, SDValue N3) {
9257 SDNodeFlags Flags;
9258 if (Inserter)
9259 Flags = Inserter->getFlags();
9260 return getNode(Opcode, DL, VT, N1, N2, N3, Flags);
9261}
9262
9263SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
9264 SDValue N1, SDValue N2, SDValue N3,
9265 const SDNodeFlags Flags) {
9267 N2.getOpcode() != ISD::DELETED_NODE &&
9268 N3.getOpcode() != ISD::DELETED_NODE &&
9269 "Operand is DELETED_NODE!");
9270 // Perform various simplifications.
9271 switch (Opcode) {
9272 case ISD::BUILD_VECTOR: {
9273 // Attempt to simplify BUILD_VECTOR.
9274 SDValue Ops[] = {N1, N2, N3};
9275 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
9276 return V;
9277 break;
9278 }
9279 case ISD::CONCAT_VECTORS: {
9280 SDValue Ops[] = {N1, N2, N3};
9281 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
9282 return V;
9283 break;
9284 }
9285 case ISD::SETCC: {
9286 assert(VT.isInteger() && "SETCC result type must be an integer!");
9287 assert(N1.getValueType() == N2.getValueType() &&
9288 "SETCC operands must have the same type!");
9289 assert(VT.isVector() == N1.getValueType().isVector() &&
9290 "SETCC type should be vector iff the operand type is vector!");
9291 assert((!VT.isVector() || VT.getVectorElementCount() ==
9293 "SETCC vector element counts must match!");
9294 // Use FoldSetCC to simplify SETCC's.
9295 if (SDValue V =
9296 FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL, Flags))
9297 return V;
9298 break;
9299 }
9300 case ISD::SELECT:
9301 case ISD::VSELECT:
9302 if (SDValue V = simplifySelect(N1, N2, N3))
9303 return V;
9304 break;
9306 llvm_unreachable("should use getVectorShuffle constructor!");
9308 if (isNullConstant(N3))
9309 return N1;
9310 break;
9312 if (isNullConstant(N3))
9313 return N2;
9314 break;
9316 assert(VT.isVector() && VT == N1.getValueType() &&
9317 "INSERT_VECTOR_ELT vector type mismatch");
9319 "INSERT_VECTOR_ELT scalar fp/int mismatch");
9320 assert((!VT.isFloatingPoint() ||
9321 VT.getVectorElementType() == N2.getValueType()) &&
9322 "INSERT_VECTOR_ELT fp scalar type mismatch");
9323 assert((!VT.isInteger() ||
9325 "INSERT_VECTOR_ELT int scalar size mismatch");
9326
9327 auto *N3C = dyn_cast<ConstantSDNode>(N3);
9328 // INSERT_VECTOR_ELT into out-of-bounds element is an UNDEF, except
9329 // for scalable vectors where we will generate appropriate code to
9330 // deal with out-of-bounds cases correctly.
9331 if (N3C && VT.isFixedLengthVector() &&
9332 N3C->getZExtValue() >= VT.getVectorNumElements())
9333 return getUNDEF(VT);
9334
9335 // Undefined index can be assumed out-of-bounds, so that's UNDEF too.
9336 if (N3.isUndef())
9337 return getUNDEF(VT);
9338
9339 // If inserting poison, just use the input vector.
9340 if (N2.getOpcode() == ISD::POISON)
9341 return N1;
9342
9343 // Inserting undef into undef/poison is still undef.
9344 if (N2.getOpcode() == ISD::UNDEF && N1.isUndef())
9345 return getUNDEF(VT);
9346
9347 // If the inserted element is an UNDEF, just use the input vector.
9348 // But not if skipping the insert could make the result more poisonous.
9349 if (N2.isUndef()) {
9350 if (N3C && VT.isFixedLengthVector()) {
9351 APInt EltMask =
9352 APInt::getOneBitSet(VT.getVectorNumElements(), N3C->getZExtValue());
9353 if (isGuaranteedNotToBePoison(N1, EltMask))
9354 return N1;
9355 } else if (isGuaranteedNotToBePoison(N1))
9356 return N1;
9357 }
9358 break;
9359 }
9360 case ISD::INSERT_SUBVECTOR: {
9361 // If inserting poison, just use the input vector,
9362 if (N2.getOpcode() == ISD::POISON)
9363 return N1;
9364
9365 // Inserting undef into undef/poison is still undef.
9366 if (N2.getOpcode() == ISD::UNDEF && N1.isUndef())
9367 return getUNDEF(VT);
9368
9369 EVT N2VT = N2.getValueType();
9370 assert(VT == N1.getValueType() &&
9371 "Dest and insert subvector source types must match!");
9372 assert(VT.isVector() && N2VT.isVector() &&
9373 "Insert subvector VTs must be vectors!");
9375 "Insert subvector VTs must have the same element type!");
9376 assert((VT.isScalableVector() || N2VT.isFixedLengthVector()) &&
9377 "Cannot insert a scalable vector into a fixed length vector!");
9378 assert((VT.isScalableVector() != N2VT.isScalableVector() ||
9380 "Insert subvector must be from smaller vector to larger vector!");
9382 "Insert subvector index must be constant");
9383 assert((VT.isScalableVector() != N2VT.isScalableVector() ||
9384 (N2VT.getVectorMinNumElements() + N3->getAsZExtVal()) <=
9386 "Insert subvector overflow!");
9388 TLI->getVectorIdxWidth(getDataLayout()) &&
9389 "Constant index for INSERT_SUBVECTOR has an invalid size");
9390
9391 // Trivial insertion.
9392 if (VT == N2VT)
9393 return N2;
9394
9395 // If this is an insert of an extracted vector into an undef/poison vector,
9396 // we can just use the input to the extract. But not if skipping the
9397 // extract+insert could make the result more poisonous.
9398 if (N1.isUndef() && N2.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
9399 N2.getOperand(1) == N3 && N2.getOperand(0).getValueType() == VT) {
9400 if (N1.getOpcode() == ISD::POISON)
9401 return N2.getOperand(0);
9402 if (VT.isFixedLengthVector() && N2VT.isFixedLengthVector()) {
9403 unsigned LoBit = N3->getAsZExtVal();
9404 unsigned HiBit = LoBit + N2VT.getVectorNumElements();
9405 APInt EltMask =
9406 APInt::getBitsSet(VT.getVectorNumElements(), LoBit, HiBit);
9407 if (isGuaranteedNotToBePoison(N2.getOperand(0), ~EltMask))
9408 return N2.getOperand(0);
9409 } else if (isGuaranteedNotToBePoison(N2.getOperand(0)))
9410 return N2.getOperand(0);
9411 }
9412
9413 // If the inserted subvector is UNDEF, just use the input vector.
9414 // But not if skipping the insert could make the result more poisonous.
9415 if (N2.isUndef()) {
9416 if (VT.isFixedLengthVector()) {
9417 unsigned LoBit = N3->getAsZExtVal();
9418 unsigned HiBit = LoBit + N2VT.getVectorNumElements();
9419 APInt EltMask =
9420 APInt::getBitsSet(VT.getVectorNumElements(), LoBit, HiBit);
9421 if (isGuaranteedNotToBePoison(N1, EltMask))
9422 return N1;
9423 } else if (isGuaranteedNotToBePoison(N1))
9424 return N1;
9425 }
9426 break;
9427 }
9428 case ISD::BITCAST:
9429 // Fold bit_convert nodes from a type to themselves.
9430 if (N1.getValueType() == VT)
9431 return N1;
9432 break;
9433 case ISD::VECTOR_COMPRESS: {
9434 [[maybe_unused]] EVT VecVT = N1.getValueType();
9435 [[maybe_unused]] EVT MaskVT = N2.getValueType();
9436 [[maybe_unused]] EVT PassthruVT = N3.getValueType();
9437 assert(VT == VecVT && "Vector and result type don't match.");
9438 assert(VecVT.isVector() && MaskVT.isVector() && PassthruVT.isVector() &&
9439 "All inputs must be vectors.");
9440 assert(VecVT == PassthruVT && "Vector and passthru types don't match.");
9442 "Vector and mask must have same number of elements.");
9443
9444 if (N1.isUndef() || N2.isUndef())
9445 return N3;
9446
9447 break;
9448 }
9453 [[maybe_unused]] EVT AccVT = N1.getValueType();
9454 [[maybe_unused]] EVT Input1VT = N2.getValueType();
9455 [[maybe_unused]] EVT Input2VT = N3.getValueType();
9456 assert(Input1VT.isVector() && Input1VT == Input2VT &&
9457 "Expected the second and third operands of the PARTIAL_REDUCE_MLA "
9458 "node to have the same type!");
9459 assert(VT.isVector() && VT == AccVT &&
9460 "Expected the first operand of the PARTIAL_REDUCE_MLA node to have "
9461 "the same type as its result!");
9463 AccVT.getVectorElementCount()) &&
9464 "Expected the element count of the second and third operands of the "
9465 "PARTIAL_REDUCE_MLA node to be a positive integer multiple of the "
9466 "element count of the first operand and the result!");
9468 "Expected the second and third operands of the PARTIAL_REDUCE_MLA "
9469 "node to have an element type which is the same as or smaller than "
9470 "the element type of the first operand and result!");
9471 break;
9472 }
9473 }
9474
9475 // Perform trivial constant folding for arithmetic operators.
9476 switch (Opcode) {
9480 case ISD::FMA:
9481 case ISD::FMAD:
9482 case ISD::SETCC:
9483 case ISD::FSHL:
9484 case ISD::FSHR:
9485 if (SDValue SV =
9486 FoldConstantArithmetic(Opcode, DL, VT, {N1, N2, N3}, Flags))
9487 return SV;
9488 break;
9489 }
9490
9491 // Memoize node if it doesn't produce a glue result.
9492 SDNode *N;
9493 SDVTList VTs = getVTList(VT);
9494 SDValue Ops[] = {N1, N2, N3};
9495 if (VT != MVT::Glue) {
9496 SDNodeKey ID(Opcode, VTs, Ops);
9497 FoldingSetInsertToken InsertToken;
9498 if (SDNode *E = lookupNode(ID, DL, InsertToken)) {
9499 E->intersectFlagsWith(Flags);
9500 return SDValue(E, 0);
9501 }
9502
9503 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
9504 N->setFlags(Flags);
9505 createOperands(N, Ops);
9506 CSEMap.insert(N, InsertToken);
9507 } else {
9508 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
9509 createOperands(N, Ops);
9510 }
9511
9512 InsertNode(N);
9513 SDValue V = SDValue(N, 0);
9514 NewSDValueDbgMsg(V, "Creating new node: ", this);
9515 return V;
9516}
9517
9518SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
9519 SDValue N1, SDValue N2, SDValue N3, SDValue N4,
9520 const SDNodeFlags Flags) {
9521 SDValue Ops[] = { N1, N2, N3, N4 };
9522 return getNode(Opcode, DL, VT, Ops, Flags);
9523}
9524
9525SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
9526 SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
9527 SDNodeFlags Flags;
9528 if (Inserter)
9529 Flags = Inserter->getFlags();
9530 return getNode(Opcode, DL, VT, N1, N2, N3, N4, Flags);
9531}
9532
9533SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
9534 SDValue N1, SDValue N2, SDValue N3, SDValue N4,
9535 SDValue N5, const SDNodeFlags Flags) {
9536 SDValue Ops[] = { N1, N2, N3, N4, N5 };
9537 return getNode(Opcode, DL, VT, Ops, Flags);
9538}
9539
9540SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
9541 SDValue N1, SDValue N2, SDValue N3, SDValue N4,
9542 SDValue N5) {
9543 SDNodeFlags Flags;
9544 if (Inserter)
9545 Flags = Inserter->getFlags();
9546 return getNode(Opcode, DL, VT, N1, N2, N3, N4, N5, Flags);
9547}
9548
9549/// getStackArgumentTokenFactor - Compute a TokenFactor to force all
9550/// the incoming stack arguments to be loaded from the stack.
9552 SmallVector<SDValue, 8> ArgChains;
9553
9554 // Include the original chain at the beginning of the list. When this is
9555 // used by target LowerCall hooks, this helps legalize find the
9556 // CALLSEQ_BEGIN node.
9557 ArgChains.push_back(Chain);
9558
9559 // Add a chain value for each stack argument.
9560 for (SDNode *U : getEntryNode().getNode()->users())
9561 if (LoadSDNode *L = dyn_cast<LoadSDNode>(U))
9562 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
9563 if (FI->getIndex() < 0)
9564 ArgChains.push_back(SDValue(L, 1));
9565
9566 // Build a tokenfactor for all the chains.
9567 return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
9568}
9569
9570/// getMemsetValue - Vectorized representation of the memset value
9571/// operand.
9573 const SDLoc &dl) {
9574 assert(!Value.isUndef());
9575
9576 unsigned NumBits = VT.getScalarSizeInBits();
9578 assert(C->getAPIntValue().getBitWidth() == 8);
9579 APInt Val = APInt::getSplat(NumBits, C->getAPIntValue());
9580 if (VT.isInteger()) {
9581 bool IsOpaque = VT.getSizeInBits() > 64 ||
9582 !DAG.getTargetLoweringInfo().isLegalStoreImmediate(C->getSExtValue());
9583 return DAG.getConstant(Val, dl, VT, false, IsOpaque);
9584 }
9585 return DAG.getConstantFP(APFloat(VT.getFltSemantics(), Val), dl, VT);
9586 }
9587
9588 assert(Value.getValueType() == MVT::i8 && "memset with non-byte fill value?");
9589 EVT IntVT = VT.getScalarType();
9590 if (!IntVT.isInteger())
9591 IntVT = EVT::getIntegerVT(*DAG.getContext(), IntVT.getSizeInBits());
9592
9593 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, Value);
9594 if (NumBits > 8) {
9595 // Use a multiplication with 0x010101... to extend the input to the
9596 // required length.
9597 APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01));
9598 Value = DAG.getNode(ISD::MUL, dl, IntVT, Value,
9599 DAG.getConstant(Magic, dl, IntVT));
9600 }
9601
9602 if (VT != Value.getValueType() && !VT.isInteger())
9603 Value = DAG.getBitcast(VT.getScalarType(), Value);
9604 if (VT != Value.getValueType())
9605 Value = DAG.getSplatBuildVector(VT, dl, Value);
9606
9607 return Value;
9608}
9609
9610/// getMemsetStringVal - Similar to getMemsetValue. Except this is only
9611/// used when a memcpy is turned into a memset when the source is a constant
9612/// string ptr.
9614 const TargetLowering &TLI,
9615 const ConstantDataArraySlice &Slice) {
9616 // Handle vector with all elements zero.
9617 if (Slice.Array == nullptr) {
9618 if (VT.isInteger())
9619 return DAG.getConstant(0, dl, VT);
9620 return DAG.getNode(ISD::BITCAST, dl, VT,
9621 DAG.getConstant(0, dl, VT.changeTypeToInteger()));
9622 }
9623
9624 assert(!VT.isVector() && "Can't handle vector type here!");
9625 unsigned NumVTBits = VT.getSizeInBits();
9626 unsigned NumVTBytes = NumVTBits / 8;
9627 unsigned NumBytes = std::min(NumVTBytes, unsigned(Slice.Length));
9628
9629 APInt Val(NumVTBits, 0);
9630 if (DAG.getDataLayout().isLittleEndian()) {
9631 for (unsigned i = 0; i != NumBytes; ++i)
9632 Val |= (uint64_t)(unsigned char)Slice[i] << i*8;
9633 } else {
9634 for (unsigned i = 0; i != NumBytes; ++i)
9635 Val |= (uint64_t)(unsigned char)Slice[i] << (NumVTBytes-i-1)*8;
9636 }
9637
9638 // If the "cost" of materializing the integer immediate is less than the cost
9639 // of a load, then it is cost effective to turn the load into the immediate.
9640 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
9641 if (TLI.shouldConvertConstantLoadToIntImm(Val, Ty))
9642 return DAG.getConstant(Val, dl, VT);
9643 return SDValue();
9644}
9645
9647 const SDLoc &DL,
9648 const SDNodeFlags Flags) {
9649 SDValue Index = getTypeSize(DL, Base.getValueType(), Offset);
9650 return getMemBasePlusOffset(Base, Index, DL, Flags);
9651}
9652
9654 const SDLoc &DL,
9655 const SDNodeFlags Flags) {
9656 assert(Offset.getValueType().isInteger());
9657 EVT BasePtrVT = Ptr.getValueType();
9658 if (TLI->shouldPreservePtrArith(this->getMachineFunction().getFunction(),
9659 BasePtrVT))
9660 return getNode(ISD::PTRADD, DL, BasePtrVT, Ptr, Offset, Flags);
9661 // InBounds only applies to PTRADD, don't set it if we generate ADD.
9662 SDNodeFlags AddFlags = Flags;
9663 AddFlags.setInBounds(false);
9664 return getNode(ISD::ADD, DL, BasePtrVT, Ptr, Offset, AddFlags);
9665}
9666
9667/// Returns true if memcpy source is constant data.
9669 uint64_t SrcDelta = 0;
9670 GlobalAddressSDNode *G = nullptr;
9671 if (Src.getOpcode() == ISD::GlobalAddress)
9673 else if (Src->isAnyAdd() &&
9674 Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
9675 Src.getOperand(1).getOpcode() == ISD::Constant) {
9676 G = cast<GlobalAddressSDNode>(Src.getOperand(0));
9677 SrcDelta = Src.getConstantOperandVal(1);
9678 }
9679 if (!G)
9680 return false;
9681
9682 return getConstantDataArrayInfo(G->getGlobal(), Slice, 8,
9683 SrcDelta + G->getOffset());
9684}
9685
9687 SelectionDAG &DAG) {
9688 // On Darwin, -Os means optimize for size without hurting performance, so
9689 // only really optimize for size when -Oz (MinSize) is used.
9691 return MF.getFunction().hasMinSize();
9692 return DAG.shouldOptForSize();
9693}
9694
9696 SmallVector<SDValue, 32> &OutChains, unsigned From,
9697 unsigned To, SmallVector<SDValue, 16> &OutLoadChains,
9698 SmallVector<SDValue, 16> &OutStoreChains) {
9699 assert(OutLoadChains.size() && "Missing loads in memcpy inlining");
9700 assert(OutStoreChains.size() && "Missing stores in memcpy inlining");
9701 SmallVector<SDValue, 16> GluedLoadChains;
9702 for (unsigned i = From; i < To; ++i) {
9703 OutChains.push_back(OutLoadChains[i]);
9704 GluedLoadChains.push_back(OutLoadChains[i]);
9705 }
9706
9707 // Chain for all loads.
9708 SDValue LoadToken = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
9709 GluedLoadChains);
9710
9711 for (unsigned i = From; i < To; ++i) {
9712 StoreSDNode *ST = dyn_cast<StoreSDNode>(OutStoreChains[i]);
9713 SDValue NewStore = DAG.getTruncStore(LoadToken, dl, ST->getValue(),
9714 ST->getBasePtr(), ST->getMemoryVT(),
9715 ST->getMemOperand());
9716 OutChains.push_back(NewStore);
9717 }
9718}
9719
9720static SDValue
9722 SDValue Dst, SDValue Src, uint64_t Size, Align DstAlign,
9723 Align SrcAlign, bool isVol, bool AlwaysInline,
9724 MachinePointerInfo DstPtrInfo,
9725 MachinePointerInfo SrcPtrInfo, const AAMDNodes &AAInfo,
9726 BatchAAResults *BatchAA, const MDNode *DstMemCacheHint,
9727 const MDNode *SrcMemCacheHint) {
9728 // Turn a memcpy of undef to nop.
9729 // FIXME: We need to honor volatile even is Src is undef.
9730 if (Src.isUndef())
9731 return Chain;
9732
9733 // Expand memcpy to a series of load and store ops if the size operand falls
9734 // below a certain threshold.
9735 // TODO: In the AlwaysInline case, if the size is big then generate a loop
9736 // rather than maybe a humongous number of loads and stores.
9738 const DataLayout &DL = DAG.getDataLayout();
9739 LLVMContext &C = *DAG.getContext();
9740 std::vector<EVT> MemOps;
9741 bool DstAlignCanChange = false;
9743 MachineFrameInfo &MFI = MF.getFrameInfo();
9744 bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
9746 if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
9747 DstAlignCanChange = true;
9748 SrcAlign = std::max(SrcAlign, DAG.InferPtrAlign(Src).valueOrOne());
9750 // If marked as volatile, perform a copy even when marked as constant.
9751 bool CopyFromConstant = !isVol && isMemSrcFromConstant(Src, Slice);
9752 bool isZeroConstant = CopyFromConstant && Slice.Array == nullptr;
9753 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize);
9754 const MemOp Op = isZeroConstant
9755 ? MemOp::Set(Size, DstAlignCanChange, DstAlign,
9756 /*IsZeroMemset*/ true, isVol)
9757 : MemOp::Copy(Size, DstAlignCanChange, DstAlign,
9758 SrcAlign, isVol, CopyFromConstant);
9759 if (!TLI.findOptimalMemOpLowering(
9760 C, MemOps, Limit, Op, DstPtrInfo.getAddrSpace(),
9761 SrcPtrInfo.getAddrSpace(), MF.getFunction().getAttributes(), nullptr))
9762 return SDValue();
9763
9764 if (DstAlignCanChange) {
9765 Type *Ty = MemOps[0].getTypeForEVT(C);
9766 Align NewDstAlign = DL.getABITypeAlign(Ty);
9767
9768 // Don't promote to an alignment that would require dynamic stack
9769 // realignment which may conflict with optimizations such as tail call
9770 // optimization.
9772 if (!TRI->hasStackRealignment(MF))
9773 if (MaybeAlign StackAlign = DL.getStackAlignment())
9774 NewDstAlign = std::min(NewDstAlign, *StackAlign);
9775
9776 if (NewDstAlign > DstAlign) {
9777 // Give the stack frame object a larger alignment if needed.
9778 if (MFI.getObjectAlign(FI->getIndex()) < NewDstAlign)
9779 MFI.setObjectAlignment(FI->getIndex(), NewDstAlign);
9780 DstAlign = NewDstAlign;
9781 }
9782 }
9783
9784 // Prepare AAInfo for loads/stores after lowering this memcpy.
9785 AAMDNodes NewAAInfo = AAInfo;
9786 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
9787
9788 const Value *SrcVal = dyn_cast_if_present<const Value *>(SrcPtrInfo.V);
9789 bool isConstant =
9790 BatchAA && SrcVal &&
9791 BatchAA->pointsToConstantMemory(MemoryLocation(SrcVal, Size, AAInfo));
9792
9793 MachineMemOperand::Flags MMOFlags =
9795 SmallVector<SDValue, 16> OutLoadChains;
9796 SmallVector<SDValue, 16> OutStoreChains;
9797 SmallVector<SDValue, 32> OutChains;
9798 unsigned NumMemOps = MemOps.size();
9799 uint64_t SrcOff = 0, DstOff = 0;
9800 for (unsigned i = 0; i != NumMemOps; ++i) {
9801 EVT VT = MemOps[i];
9802 unsigned VTSize = VT.getSizeInBits() / 8;
9804
9805 if (VTSize > Size) {
9806 // Issuing an unaligned load / store pair that overlaps with the previous
9807 // pair. Adjust the offset accordingly.
9808 assert(i == NumMemOps-1 && i != 0);
9809 SrcOff -= VTSize - Size;
9810 DstOff -= VTSize - Size;
9811 }
9812
9813 if (CopyFromConstant &&
9814 (isZeroConstant || (VT.isInteger() && !VT.isVector()))) {
9815 // It's unlikely a store of a vector immediate can be done in a single
9816 // instruction. It would require a load from a constantpool first.
9817 // We only handle zero vectors here.
9818 // FIXME: Handle other cases where store of vector immediate is done in
9819 // a single instruction.
9820 ConstantDataArraySlice SubSlice;
9821 if (SrcOff < Slice.Length) {
9822 SubSlice = Slice;
9823 SubSlice.move(SrcOff);
9824 } else {
9825 // This is an out-of-bounds access and hence UB. Pretend we read zero.
9826 SubSlice.Array = nullptr;
9827 SubSlice.Offset = 0;
9828 SubSlice.Length = VTSize;
9829 }
9830 Value = getMemsetStringVal(VT, dl, DAG, TLI, SubSlice);
9831 if (Value.getNode()) {
9832 Store = DAG.getStore(
9833 Chain, dl, Value,
9834 DAG.getObjectPtrOffset(dl, Dst, TypeSize::getFixed(DstOff)),
9835 DstPtrInfo.getWithOffset(DstOff), DstAlign, MMOFlags,
9836 MMOMetadata(NewAAInfo, /*Ranges=*/nullptr, DstMemCacheHint));
9837 OutChains.push_back(Store);
9838 }
9839 }
9840
9841 if (!Store.getNode()) {
9842 // The type might not be legal for the target. This should only happen
9843 // if the type is smaller than a legal type, as on PPC, so the right
9844 // thing to do is generate a LoadExt/StoreTrunc pair. These simplify
9845 // to Load/Store if NVT==VT.
9846 // FIXME does the case above also need this?
9847 EVT NVT = TLI.getTypeToTransformTo(C, VT);
9848 assert(NVT.bitsGE(VT));
9849
9850 bool isDereferenceable =
9851 SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
9852 MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
9853 if (isDereferenceable)
9855 if (isConstant)
9856 SrcMMOFlags |= MachineMemOperand::MOInvariant;
9857
9858 Value = DAG.getExtLoad(
9859 ISD::EXTLOAD, dl, NVT, Chain,
9860 DAG.getObjectPtrOffset(dl, Src, TypeSize::getFixed(SrcOff)),
9861 SrcPtrInfo.getWithOffset(SrcOff), VT,
9862 commonAlignment(SrcAlign, SrcOff), SrcMMOFlags,
9863 MMOMetadata(NewAAInfo, /*Ranges=*/nullptr, SrcMemCacheHint));
9864 OutLoadChains.push_back(Value.getValue(1));
9865
9866 Store = DAG.getTruncStore(
9867 Chain, dl, Value,
9868 DAG.getObjectPtrOffset(dl, Dst, TypeSize::getFixed(DstOff)),
9869 DstPtrInfo.getWithOffset(DstOff), VT, DstAlign, MMOFlags,
9870 MMOMetadata(NewAAInfo, /*Ranges=*/nullptr, DstMemCacheHint));
9871 OutStoreChains.push_back(Store);
9872 }
9873 SrcOff += VTSize;
9874 DstOff += VTSize;
9875 Size -= VTSize;
9876 }
9877
9878 unsigned MaxLdStGlue = DAG.getSelectionDAGOptions().ldstmemcpy_glue_max;
9879 unsigned GluedLdStLimit =
9880 MaxLdStGlue == 0 ? TLI.getMaxGluedStoresPerMemcpy() : MaxLdStGlue;
9881 unsigned NumLdStInMemcpy = OutStoreChains.size();
9882
9883 if (NumLdStInMemcpy) {
9884 // It may be that memcpy might be converted to memset if it's memcpy
9885 // of constants. In such a case, we won't have loads and stores, but
9886 // just stores. In the absence of loads, there is nothing to gang up.
9887 if ((GluedLdStLimit <= 1) ||
9888 !DAG.getSelectionDAGOptions().enable_memcpy_dag_opt) {
9889 // If target does not care, just leave as it.
9890 for (unsigned i = 0; i < NumLdStInMemcpy; ++i) {
9891 OutChains.push_back(OutLoadChains[i]);
9892 OutChains.push_back(OutStoreChains[i]);
9893 }
9894 } else {
9895 // Ld/St less than/equal limit set by target.
9896 if (NumLdStInMemcpy <= GluedLdStLimit) {
9897 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
9898 NumLdStInMemcpy, OutLoadChains,
9899 OutStoreChains);
9900 } else {
9901 unsigned NumberLdChain = NumLdStInMemcpy / GluedLdStLimit;
9902 unsigned RemainingLdStInMemcpy = NumLdStInMemcpy % GluedLdStLimit;
9903 unsigned GlueIter = 0;
9904
9905 // Residual ld/st.
9906 if (RemainingLdStInMemcpy) {
9908 DAG, dl, OutChains, NumLdStInMemcpy - RemainingLdStInMemcpy,
9909 NumLdStInMemcpy, OutLoadChains, OutStoreChains);
9910 }
9911
9912 for (unsigned cnt = 0; cnt < NumberLdChain; ++cnt) {
9913 unsigned IndexFrom = NumLdStInMemcpy - RemainingLdStInMemcpy -
9914 GlueIter - GluedLdStLimit;
9915 unsigned IndexTo = NumLdStInMemcpy - RemainingLdStInMemcpy - GlueIter;
9916 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, IndexFrom, IndexTo,
9917 OutLoadChains, OutStoreChains);
9918 GlueIter += GluedLdStLimit;
9919 }
9920 }
9921 }
9922 }
9923 return DAG.getTokenFactor(dl, OutChains);
9924}
9925
9927 SelectionDAG &DAG, const SDLoc &dl, SDValue Chain, SDValue Dst, SDValue Src,
9928 uint64_t Size, Align DstAlign, Align SrcAlign, bool isVol,
9929 bool AlwaysInline, MachinePointerInfo DstPtrInfo,
9930 MachinePointerInfo SrcPtrInfo, const AAMDNodes &AAInfo) {
9931 // Turn a memmove of undef to nop.
9932 // FIXME: We need to honor volatile even is Src is undef.
9933 if (Src.isUndef())
9934 return Chain;
9935
9936 // Expand memmove to a series of load and store ops if the size operand falls
9937 // below a certain threshold.
9939 const DataLayout &DL = DAG.getDataLayout();
9940 LLVMContext &C = *DAG.getContext();
9941 std::vector<EVT> MemOps;
9942 bool DstAlignCanChange = false;
9944 MachineFrameInfo &MFI = MF.getFrameInfo();
9945 bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
9947 if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
9948 DstAlignCanChange = true;
9949 SrcAlign = std::max(SrcAlign, DAG.InferPtrAlign(Src).valueOrOne());
9950 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize);
9951 if (!TLI.findOptimalMemOpLowering(
9952 C, MemOps, Limit,
9953 MemOp::Move(Size, DstAlignCanChange, DstAlign, SrcAlign, isVol),
9954 DstPtrInfo.getAddrSpace(), SrcPtrInfo.getAddrSpace(),
9955 MF.getFunction().getAttributes(), nullptr))
9956 return SDValue();
9957
9958 if (DstAlignCanChange) {
9959 Type *Ty = MemOps[0].getTypeForEVT(C);
9960 Align NewDstAlign = DL.getABITypeAlign(Ty);
9961
9962 // Don't promote to an alignment that would require dynamic stack
9963 // realignment which may conflict with optimizations such as tail call
9964 // optimization.
9966 if (!TRI->hasStackRealignment(MF))
9967 if (MaybeAlign StackAlign = DL.getStackAlignment())
9968 NewDstAlign = std::min(NewDstAlign, *StackAlign);
9969
9970 if (NewDstAlign > DstAlign) {
9971 // Give the stack frame object a larger alignment if needed.
9972 if (MFI.getObjectAlign(FI->getIndex()) < NewDstAlign)
9973 MFI.setObjectAlignment(FI->getIndex(), NewDstAlign);
9974 DstAlign = NewDstAlign;
9975 }
9976 }
9977
9978 // Prepare AAInfo for loads/stores after lowering this memmove.
9979 AAMDNodes NewAAInfo = AAInfo;
9980 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
9981
9982 MachineMemOperand::Flags MMOFlags =
9984 uint64_t SrcOff = 0;
9985 SmallVector<SDValue, 8> LoadValues;
9986 SmallVector<SDValue, 8> LoadChains;
9987 SmallVector<SDValue, 8> OutChains;
9988 unsigned NumMemOps = MemOps.size();
9989 for (unsigned i = 0; i < NumMemOps; i++) {
9990 EVT VT = MemOps[i];
9991 unsigned VTSize = VT.getSizeInBits() / 8;
9992 SDValue Value;
9993 bool IsOverlapping = false;
9994
9995 if (i == NumMemOps - 1 && i != 0 && VTSize > Size - SrcOff) {
9996 // Issuing an unaligned load / store pair that overlaps with the previous
9997 // pair. Adjust the offset accordingly.
9998 SrcOff = Size - VTSize;
9999 IsOverlapping = true;
10000 }
10001
10002 // Calculate the actual alignment at the current offset. The alignment at
10003 // SrcOff may be lower than the base alignment, especially when using
10004 // overlapping loads.
10005 Align SrcAlignAtOffset = commonAlignment(SrcAlign, SrcOff);
10006 if (IsOverlapping) {
10007 // Verify that the target allows misaligned memory accesses at the
10008 // adjusted offset when using overlapping loads.
10009 unsigned Fast;
10010 if (!TLI.allowsMisalignedMemoryAccesses(VT, SrcPtrInfo.getAddrSpace(),
10011 SrcAlignAtOffset, MMOFlags,
10012 &Fast) ||
10013 !Fast) {
10014 // This should have been caught by findOptimalMemOpLowering, but verify
10015 // here for safety.
10016 return SDValue();
10017 }
10018 }
10019
10020 bool isDereferenceable =
10021 SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
10022 MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
10023 if (isDereferenceable)
10025 Value =
10026 DAG.getLoad(VT, dl, Chain,
10027 DAG.getObjectPtrOffset(dl, Src, TypeSize::getFixed(SrcOff)),
10028 SrcPtrInfo.getWithOffset(SrcOff), SrcAlignAtOffset,
10029 SrcMMOFlags, NewAAInfo);
10030 LoadValues.push_back(Value);
10031 LoadChains.push_back(Value.getValue(1));
10032 SrcOff += VTSize;
10033 }
10034 Chain = DAG.getTokenFactor(dl, LoadChains);
10035 OutChains.clear();
10036 uint64_t DstOff = 0;
10037 for (unsigned i = 0; i < NumMemOps; i++) {
10038 EVT VT = MemOps[i];
10039 unsigned VTSize = VT.getSizeInBits() / 8;
10040 SDValue Store;
10041 bool IsOverlapping = false;
10042
10043 if (i == NumMemOps - 1 && i != 0 && VTSize > Size - DstOff) {
10044 // Issuing an unaligned load / store pair that overlaps with the previous
10045 // pair. Adjust the offset accordingly.
10046 DstOff = Size - VTSize;
10047 IsOverlapping = true;
10048 }
10049
10050 // Calculate the actual alignment at the current offset. The alignment at
10051 // DstOff may be lower than the base alignment, especially when using
10052 // overlapping stores.
10053 Align DstAlignAtOffset = commonAlignment(DstAlign, DstOff);
10054 if (IsOverlapping) {
10055 // Verify that the target allows misaligned memory accesses at the
10056 // adjusted offset when using overlapping stores.
10057 unsigned Fast;
10058 if (!TLI.allowsMisalignedMemoryAccesses(VT, DstPtrInfo.getAddrSpace(),
10059 DstAlignAtOffset, MMOFlags,
10060 &Fast) ||
10061 !Fast) {
10062 // This should have been caught by findOptimalMemOpLowering, but verify
10063 // here for safety.
10064 return SDValue();
10065 }
10066 }
10067 Store = DAG.getStore(
10068 Chain, dl, LoadValues[i],
10069 DAG.getObjectPtrOffset(dl, Dst, TypeSize::getFixed(DstOff)),
10070 DstPtrInfo.getWithOffset(DstOff), DstAlignAtOffset, MMOFlags,
10071 NewAAInfo);
10072 OutChains.push_back(Store);
10073 DstOff += VTSize;
10074 }
10075
10076 return DAG.getTokenFactor(dl, OutChains);
10077}
10078
10079/// Lower the call to 'memset' intrinsic function into a series of store
10080/// operations.
10081///
10082/// \param DAG Selection DAG where lowered code is placed.
10083/// \param dl Link to corresponding IR location.
10084/// \param Chain Control flow dependency.
10085/// \param Dst Pointer to destination memory location.
10086/// \param Src Value of byte to write into the memory.
10087/// \param Size Number of bytes to write.
10088/// \param Alignment Alignment of the destination in bytes.
10089/// \param isVol True if destination is volatile.
10090/// \param AlwaysInline Makes sure no function call is generated.
10091/// \param DstPtrInfo IR information on the memory pointer.
10092/// \returns New head in the control flow, if lowering was successful, empty
10093/// SDValue otherwise.
10094///
10095/// The function tries to replace 'llvm.memset' intrinsic with several store
10096/// operations and value calculation code. This is usually profitable for small
10097/// memory size or when the semantic requires inlining.
10099 SDValue Chain, SDValue Dst, SDValue Src,
10100 uint64_t Size, Align Alignment, bool isVol,
10101 bool AlwaysInline, MachinePointerInfo DstPtrInfo,
10102 const AAMDNodes &AAInfo) {
10103 // Turn a memset of undef to nop.
10104 // FIXME: We need to honor volatile even is Src is undef.
10105 if (Src.isUndef())
10106 return Chain;
10107
10108 // Expand memset to a series of load/store ops if the size operand
10109 // falls below a certain threshold.
10111 std::vector<EVT> MemOps;
10112 bool DstAlignCanChange = false;
10113 LLVMContext &C = *DAG.getContext();
10115 MachineFrameInfo &MFI = MF.getFrameInfo();
10116 bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
10118 if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
10119 DstAlignCanChange = true;
10120 bool IsZeroVal = isNullConstant(Src);
10121 unsigned Limit = AlwaysInline ? ~0 : TLI.getMaxStoresPerMemset(OptSize);
10122
10123 EVT LargestVT;
10124 if (!TLI.findOptimalMemOpLowering(
10125 C, MemOps, Limit,
10126 MemOp::Set(Size, DstAlignCanChange, Alignment, IsZeroVal, isVol),
10127 DstPtrInfo.getAddrSpace(), ~0u, MF.getFunction().getAttributes(),
10128 &LargestVT))
10129 return SDValue();
10130
10131 if (DstAlignCanChange) {
10132 Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
10133 const DataLayout &DL = DAG.getDataLayout();
10134 Align NewAlign = DL.getABITypeAlign(Ty);
10135
10136 // Don't promote to an alignment that would require dynamic stack
10137 // realignment which may conflict with optimizations such as tail call
10138 // optimization.
10140 if (!TRI->hasStackRealignment(MF))
10141 if (MaybeAlign StackAlign = DL.getStackAlignment())
10142 NewAlign = std::min(NewAlign, *StackAlign);
10143
10144 if (NewAlign > Alignment) {
10145 // Give the stack frame object a larger alignment if needed.
10146 if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
10147 MFI.setObjectAlignment(FI->getIndex(), NewAlign);
10148 Alignment = NewAlign;
10149 }
10150 }
10151
10152 SmallVector<SDValue, 8> OutChains;
10153 uint64_t DstOff = 0;
10154 unsigned NumMemOps = MemOps.size();
10155
10156 // Find the largest store and generate the bit pattern for it.
10157 // If target didn't set LargestVT, compute it from MemOps.
10158 if (!LargestVT.isSimple()) {
10159 LargestVT = MemOps[0];
10160 for (unsigned i = 1; i < NumMemOps; i++)
10161 if (MemOps[i].bitsGT(LargestVT))
10162 LargestVT = MemOps[i];
10163 }
10164 SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl);
10165
10166 // Prepare AAInfo for loads/stores after lowering this memset.
10167 AAMDNodes NewAAInfo = AAInfo;
10168 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
10169
10170 for (unsigned i = 0; i < NumMemOps; i++) {
10171 EVT VT = MemOps[i];
10172 unsigned VTSize = VT.getSizeInBits() / 8;
10173 // The target should specify store types that exactly cover the memset size
10174 // (with the last store potentially being oversized for overlapping stores).
10175 assert(Size > 0 && "Target specified more stores than needed in "
10176 "findOptimalMemOpLowering");
10177 if (VTSize > Size) {
10178 // Issuing an unaligned load / store pair that overlaps with the previous
10179 // pair. Adjust the offset accordingly.
10180 assert(i == NumMemOps-1 && i != 0);
10181 DstOff -= VTSize - Size;
10182 }
10183
10184 // If this store is smaller than the largest store see whether we can get
10185 // the smaller value for free with a truncate or extract vector element and
10186 // then store.
10187 SDValue Value = MemSetValue;
10188 if (VT.bitsLT(LargestVT)) {
10189 unsigned Index;
10190 unsigned NElts = LargestVT.getSizeInBits() / VT.getSizeInBits();
10191 EVT SVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), NElts);
10192 if (!LargestVT.isVector() && !VT.isVector() &&
10193 TLI.isTruncateFree(LargestVT, VT))
10194 Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue);
10195 else if (LargestVT.isVector() && !VT.isVector() &&
10196 TLI.shallExtractConstSplatVectorElementToStore(
10197 LargestVT.getTypeForEVT(*DAG.getContext()),
10198 VT.getSizeInBits(), Index) &&
10199 TLI.isTypeLegal(SVT) &&
10200 LargestVT.getSizeInBits() == SVT.getSizeInBits()) {
10201 // Target which can combine store(extractelement VectorTy, Idx) can get
10202 // the smaller value for free.
10203 SDValue TailValue = DAG.getNode(ISD::BITCAST, dl, SVT, MemSetValue);
10204 Value = DAG.getExtractVectorElt(dl, VT, TailValue, Index);
10205 } else
10206 Value = getMemsetValue(Src, VT, DAG, dl);
10207 }
10208 assert(Value.getValueType() == VT && "Value with wrong type.");
10209 SDValue Store = DAG.getStore(
10210 Chain, dl, Value,
10211 DAG.getObjectPtrOffset(dl, Dst, TypeSize::getFixed(DstOff)),
10212 DstPtrInfo.getWithOffset(DstOff), Alignment,
10214 NewAAInfo);
10215 OutChains.push_back(Store);
10216 DstOff += VT.getSizeInBits() / 8;
10217 // For oversized overlapping stores, only subtract the remaining bytes.
10218 // For normal stores, subtract the full store size.
10219 if (VTSize > Size) {
10220 Size = 0;
10221 } else {
10222 Size -= VTSize;
10223 }
10224 }
10225
10226 // After processing all stores, Size should be exactly 0. Any remaining bytes
10227 // indicate a bug in the target's findOptimalMemOpLowering implementation.
10228 assert(Size == 0 && "Target's findOptimalMemOpLowering did not specify "
10229 "stores that exactly cover the memset size");
10230
10231 return DAG.getTokenFactor(dl, OutChains);
10232}
10233
10235 const DataLayout &DL, unsigned AS) {
10236 // Lowering memcpy / memset / memmove intrinsics to calls is only valid if all
10237 // pointer operands can be losslessly bitcasted to pointers of address space 0
10238 if (AS != 0 && !TLI->getTargetMachine().isNoopAddrSpaceCast(DL, AS, 0)) {
10239 report_fatal_error("cannot lower memory intrinsic in address space " +
10240 Twine(AS));
10241 }
10242}
10243
10244/// The length of a memory intrinsic (e.g. number of bytes to copy) is unsigned
10245/// and may have any integer type. We zero-extend or truncate it to the pointer
10246/// type of the narrower address space being accessed.
10248 SDValue Size, unsigned DstAS,
10249 unsigned SrcAS) {
10251 MVT DstVT = TLI.getPointerTy(DAG.getDataLayout(), DstAS);
10252 MVT SrcVT = TLI.getPointerTy(DAG.getDataLayout(), SrcAS);
10253 return DAG.getZExtOrTrunc(Size, dl, DstVT.bitsLT(SrcVT) ? DstVT : SrcVT);
10254}
10255
10257 const SelectionDAG *SelDAG,
10258 bool AllowReturnsFirstArg) {
10259 if (!CI || !CI->isTailCall())
10260 return false;
10261 // TODO: Fix "returns-first-arg" determination so it doesn't depend on which
10262 // helper symbol we lower to.
10263 return isInTailCallPosition(*CI, SelDAG->getTarget(),
10264 AllowReturnsFirstArg &&
10266}
10267
10268static std::pair<SDValue, SDValue>
10271 const CallInst *CI, RTLIB::Libcall Call,
10272 SelectionDAG *DAG, const TargetLowering *TLI) {
10273 RTLIB::LibcallImpl LCImpl = DAG->getLibcalls().getLibcallImpl(Call);
10274
10275 if (LCImpl == RTLIB::Unsupported)
10276 return {};
10277
10279 bool IsTailCall =
10280 isInTailCallPositionWrapper(CI, DAG, /*AllowReturnsFirstArg=*/true) &&
10281 // Lowering doesn't support tail calling inside a function with
10282 // a swifterror argument yet.
10283 !DAG->hasSwiftErrorArg();
10284 SDValue Callee =
10285 DAG->getExternalSymbol(LCImpl, TLI->getPointerTy(DAG->getDataLayout()));
10286
10287 CLI.setDebugLoc(dl)
10288 .setChain(Chain)
10290 CI->getType(), Callee, std::move(Args))
10291 .setTailCall(IsTailCall);
10292
10293 return TLI->LowerCallTo(CLI);
10294}
10295
10296std::pair<SDValue, SDValue> SelectionDAG::getStrcmp(SDValue Chain,
10297 const SDLoc &dl, SDValue S1,
10298 SDValue S2,
10299 const CallInst *CI) {
10301 TargetLowering::ArgListTy Args = {{S1, PT}, {S2, PT}};
10302 return getRuntimeCallSDValueHelper(Chain, dl, std::move(Args), CI,
10303 RTLIB::STRCMP, this, TLI);
10304}
10305
10306std::pair<SDValue, SDValue> SelectionDAG::getStrstr(SDValue Chain,
10307 const SDLoc &dl, SDValue S1,
10308 SDValue S2,
10309 const CallInst *CI) {
10311 TargetLowering::ArgListTy Args = {{S1, PT}, {S2, PT}};
10312 return getRuntimeCallSDValueHelper(Chain, dl, std::move(Args), CI,
10313 RTLIB::STRSTR, this, TLI);
10314}
10315
10316std::pair<SDValue, SDValue> SelectionDAG::getMemccpy(SDValue Chain,
10317 const SDLoc &dl,
10318 SDValue Dst, SDValue Src,
10320 const CallInst *CI) {
10322
10324 {Dst, PT},
10325 {Src, PT},
10328 return getRuntimeCallSDValueHelper(Chain, dl, std::move(Args), CI,
10329 RTLIB::MEMCCPY, this, TLI);
10330}
10331
10332std::pair<SDValue, SDValue>
10334 SDValue Mem1, SDValue Size, const CallInst *CI) {
10337 {Mem0, PT},
10338 {Mem1, PT},
10340 return getRuntimeCallSDValueHelper(Chain, dl, std::move(Args), CI,
10341 RTLIB::MEMCMP, this, TLI);
10342}
10343
10344std::pair<SDValue, SDValue> SelectionDAG::getStrcpy(SDValue Chain,
10345 const SDLoc &dl,
10346 SDValue Dst, SDValue Src,
10347 const CallInst *CI) {
10349 TargetLowering::ArgListTy Args = {{Dst, PT}, {Src, PT}};
10350 return getRuntimeCallSDValueHelper(Chain, dl, std::move(Args), CI,
10351 RTLIB::STRCPY, this, TLI);
10352}
10353
10354std::pair<SDValue, SDValue> SelectionDAG::getStrlen(SDValue Chain,
10355 const SDLoc &dl,
10356 SDValue Src,
10357 const CallInst *CI) {
10358 // Emit a library call.
10361 return getRuntimeCallSDValueHelper(Chain, dl, std::move(Args), CI,
10362 RTLIB::STRLEN, this, TLI);
10363}
10364
10366 return TLI->supportSwiftError() &&
10367 MF->getFunction().getAttributes().hasAttrSomewhere(
10368 Attribute::SwiftError);
10369}
10370
10372 SDValue Chain, const SDLoc &dl, SDValue Dst, SDValue Src, SDValue Size,
10373 Align DstAlign, Align SrcAlign, bool isVol, bool AlwaysInline,
10374 const CallInst *CI, std::optional<bool> OverrideTailCall,
10375 MachinePointerInfo DstPtrInfo, MachinePointerInfo SrcPtrInfo,
10376 const AAMDNodes &AAInfo, BatchAAResults *BatchAA) {
10377 Size = getMemIntrinsicSize(*this, dl, Size, DstPtrInfo.getAddrSpace(),
10378 SrcPtrInfo.getAddrSpace());
10379 // Check to see if we should lower the memcpy to loads and stores first.
10380 // For cases within the target-specified limits, this is the best choice.
10381 const MDNode *DstMemCacheHint =
10382 CI ? getMemCacheHintMetadata(*CI, /*OperandNo=*/0) : nullptr;
10383 const MDNode *SrcMemCacheHint =
10384 CI ? getMemCacheHintMetadata(*CI, /*OperandNo=*/1) : nullptr;
10385
10387 if (ConstantSize) {
10388 // Memcpy with size zero? Just return the original chain.
10389 if (ConstantSize->isZero())
10390 return Chain;
10391
10393 *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), DstAlign,
10394 SrcAlign, isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo, BatchAA,
10395 DstMemCacheHint, SrcMemCacheHint);
10396 if (Result.getNode())
10397 return Result;
10398 }
10399
10400 // Then check to see if we should lower the memcpy with target-specific
10401 // code. If the target chooses to do this, this is the next best.
10402 if (TSI) {
10403 SDValue Result = TSI->EmitTargetCodeForMemcpy(
10404 *this, dl, Chain, Dst, Src, Size, DstAlign, SrcAlign, isVol,
10405 AlwaysInline, DstPtrInfo, SrcPtrInfo);
10406 if (Result.getNode())
10407 return Result;
10408 }
10409
10410 // If we really need inline code and the target declined to provide it,
10411 // use a (potentially long) sequence of loads and stores.
10412 if (AlwaysInline) {
10413 assert(ConstantSize && "AlwaysInline requires a constant size!");
10415 *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), DstAlign,
10416 SrcAlign, isVol, true, DstPtrInfo, SrcPtrInfo, AAInfo, BatchAA,
10417 DstMemCacheHint, SrcMemCacheHint);
10418 }
10419
10421 DstPtrInfo.getAddrSpace());
10423 SrcPtrInfo.getAddrSpace());
10424
10425 // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc
10426 // memcpy is not guaranteed to be safe. libc memcpys aren't required to
10427 // respect volatile, so they may do things like read or write memory
10428 // beyond the given memory regions. But fixing this isn't easy, and most
10429 // people don't care.
10430
10431 // Emit a library call.
10434 Args.emplace_back(Dst, PtrTy);
10435 Args.emplace_back(Src, PtrTy);
10436 Args.emplace_back(Size, getDataLayout().getIntPtrType(*getContext()));
10437 // FIXME: pass in SDLoc
10439 bool IsTailCall = false;
10440 RTLIB::LibcallImpl MemCpyImpl = Libcalls->getMemcpyImpl();
10441
10442 if (OverrideTailCall.has_value()) {
10443 IsTailCall = *OverrideTailCall;
10444 } else {
10445 bool LowersToMemcpy = MemCpyImpl == RTLIB::impl_memcpy;
10446 IsTailCall = isInTailCallPositionWrapper(CI, this, LowersToMemcpy);
10447 }
10448 // Lowering doesn't support tail calling inside a function with a
10449 // swifterror argument yet.
10450 IsTailCall &= !hasSwiftErrorArg();
10451
10452 CLI.setDebugLoc(dl)
10453 .setChain(Chain)
10454 .setLibCallee(
10455 Libcalls->getLibcallImplCallingConv(MemCpyImpl),
10456 Dst.getValueType().getTypeForEVT(*getContext()),
10457 getExternalSymbol(MemCpyImpl, TLI->getPointerTy(getDataLayout())),
10458 std::move(Args))
10460 .setTailCall(IsTailCall);
10461
10462 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
10463 return CallResult.second;
10464}
10465
10468 const Module &M = *DAG->getMachineFunction().getFunction().getParent();
10469 Type *SizeTTy = DAG->getLibInfo().getSizeTType(M);
10471 DAG->getZExtOrTrunc(Size, dl, MVT::getVT(SizeTTy)), SizeTTy);
10472}
10473
10475 SDValue Dst, SDValue Src, SDValue Size,
10476 Type *SizeTy, unsigned ElemSz,
10477 bool isTailCall,
10478 MachinePointerInfo DstPtrInfo,
10479 MachinePointerInfo SrcPtrInfo) {
10480 // Lowering doesn't support tail calling inside a function with a
10481 // swifterror argument yet.
10482 isTailCall &= !hasSwiftErrorArg();
10483
10484 // Emit a library call.
10487 Args.emplace_back(Dst, ArgTy);
10488 Args.emplace_back(Src, ArgTy);
10489 Args.emplace_back(getAtomicMemOpSizeArg(this, dl, Size));
10490
10491 RTLIB::Libcall LibraryCall =
10493 RTLIB::LibcallImpl LibcallImpl = Libcalls->getLibcallImpl(LibraryCall);
10494 if (LibcallImpl == RTLIB::Unsupported)
10495 report_fatal_error("Unsupported element size");
10496
10498 CLI.setDebugLoc(dl)
10499 .setChain(Chain)
10500 .setLibCallee(
10501 Libcalls->getLibcallImplCallingConv(LibcallImpl),
10503 getExternalSymbol(LibcallImpl, TLI->getPointerTy(getDataLayout())),
10504 std::move(Args))
10506 .setTailCall(isTailCall);
10507
10508 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
10509 return CallResult.second;
10510}
10511
10513 SDValue Src, SDValue Size, Align DstAlign,
10514 Align SrcAlign, bool isVol, const CallInst *CI,
10515 std::optional<bool> OverrideTailCall,
10516 MachinePointerInfo DstPtrInfo,
10517 MachinePointerInfo SrcPtrInfo,
10518 const AAMDNodes &AAInfo,
10519 BatchAAResults *BatchAA) {
10520 Size = getMemIntrinsicSize(*this, dl, Size, DstPtrInfo.getAddrSpace(),
10521 SrcPtrInfo.getAddrSpace());
10522 // Check to see if we should lower the memmove to loads and stores first.
10523 // For cases within the target-specified limits, this is the best choice.
10525 if (ConstantSize) {
10526 // Memmove with size zero? Just return the original chain.
10527 if (ConstantSize->isZero())
10528 return Chain;
10529
10531 *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), DstAlign,
10532 SrcAlign, isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo);
10533 if (Result.getNode())
10534 return Result;
10535 }
10536
10537 // Then check to see if we should lower the memmove with target-specific
10538 // code. If the target chooses to do this, this is the next best.
10539 if (TSI) {
10540 SDValue Result = TSI->EmitTargetCodeForMemmove(
10541 *this, dl, Chain, Dst, Src, Size, DstAlign, SrcAlign, isVol, DstPtrInfo,
10542 SrcPtrInfo);
10543 if (Result.getNode())
10544 return Result;
10545 }
10546
10548 DstPtrInfo.getAddrSpace());
10550 SrcPtrInfo.getAddrSpace());
10551
10552 // FIXME: If the memmove is volatile, lowering it to plain libc memmove may
10553 // not be safe. See memcpy above for more details.
10554
10555 // Emit a library call.
10558 Args.emplace_back(Dst, PtrTy);
10559 Args.emplace_back(Src, PtrTy);
10560 Args.emplace_back(Size, getDataLayout().getIntPtrType(*getContext()));
10561 // FIXME: pass in SDLoc
10563
10564 RTLIB::LibcallImpl MemmoveImpl = Libcalls->getLibcallImpl(RTLIB::MEMMOVE);
10565
10566 bool IsTailCall = false;
10567 if (OverrideTailCall.has_value()) {
10568 IsTailCall = *OverrideTailCall;
10569 } else {
10570 bool LowersToMemmove = MemmoveImpl == RTLIB::impl_memmove;
10571 IsTailCall = isInTailCallPositionWrapper(CI, this, LowersToMemmove);
10572 }
10573 // Lowering doesn't support tail calling inside a function with a
10574 // swifterror argument yet.
10575 IsTailCall &= !hasSwiftErrorArg();
10576
10577 CLI.setDebugLoc(dl)
10578 .setChain(Chain)
10579 .setLibCallee(
10580 Libcalls->getLibcallImplCallingConv(MemmoveImpl),
10581 Dst.getValueType().getTypeForEVT(*getContext()),
10582 getExternalSymbol(MemmoveImpl, TLI->getPointerTy(getDataLayout())),
10583 std::move(Args))
10585 .setTailCall(IsTailCall);
10586
10587 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
10588 return CallResult.second;
10589}
10590
10592 SDValue Dst, SDValue Src, SDValue Size,
10593 Type *SizeTy, unsigned ElemSz,
10594 bool isTailCall,
10595 MachinePointerInfo DstPtrInfo,
10596 MachinePointerInfo SrcPtrInfo) {
10597 // Lowering doesn't support tail calling inside a function with a
10598 // swifterror argument yet.
10599 isTailCall &= !hasSwiftErrorArg();
10600
10601 // Emit a library call.
10604 Args.emplace_back(Dst, IntPtrTy);
10605 Args.emplace_back(Src, IntPtrTy);
10606 Args.emplace_back(getAtomicMemOpSizeArg(this, dl, Size));
10607
10608 RTLIB::Libcall LibraryCall =
10610 RTLIB::LibcallImpl LibcallImpl = Libcalls->getLibcallImpl(LibraryCall);
10611 if (LibcallImpl == RTLIB::Unsupported)
10612 report_fatal_error("Unsupported element size");
10613
10615 CLI.setDebugLoc(dl)
10616 .setChain(Chain)
10617 .setLibCallee(
10618 Libcalls->getLibcallImplCallingConv(LibcallImpl),
10620 getExternalSymbol(LibcallImpl, TLI->getPointerTy(getDataLayout())),
10621 std::move(Args))
10623 .setTailCall(isTailCall);
10624
10625 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
10626 return CallResult.second;
10627}
10628
10630 SDValue Src, SDValue Size, Align Alignment,
10631 bool isVol, bool AlwaysInline,
10632 const CallInst *CI,
10633 MachinePointerInfo DstPtrInfo,
10634 const AAMDNodes &AAInfo) {
10635 Size = getMemIntrinsicSize(*this, dl, Size, DstPtrInfo.getAddrSpace(),
10636 DstPtrInfo.getAddrSpace());
10637 // Check to see if we should lower the memset to stores first.
10638 // For cases within the target-specified limits, this is the best choice.
10640 if (ConstantSize) {
10641 // Memset with size zero? Just return the original chain.
10642 if (ConstantSize->isZero())
10643 return Chain;
10644
10645 SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src,
10646 ConstantSize->getZExtValue(), Alignment,
10647 isVol, false, DstPtrInfo, AAInfo);
10648
10649 if (Result.getNode())
10650 return Result;
10651 }
10652
10653 // Then check to see if we should lower the memset with target-specific
10654 // code. If the target chooses to do this, this is the next best.
10655 if (TSI) {
10656 SDValue Result = TSI->EmitTargetCodeForMemset(
10657 *this, dl, Chain, Dst, Src, Size, Alignment, isVol, AlwaysInline, DstPtrInfo);
10658 if (Result.getNode())
10659 return Result;
10660 }
10661
10662 // If we really need inline code and the target declined to provide it,
10663 // use a (potentially long) sequence of loads and stores.
10664 if (AlwaysInline) {
10665 assert(ConstantSize && "AlwaysInline requires a constant size!");
10666 SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src,
10667 ConstantSize->getZExtValue(), Alignment,
10668 isVol, true, DstPtrInfo, AAInfo);
10669 assert(Result &&
10670 "getMemsetStores must return a valid sequence when AlwaysInline");
10671 return Result;
10672 }
10673
10675 DstPtrInfo.getAddrSpace());
10676
10677 // Emit a library call.
10678 auto &Ctx = *getContext();
10679 const auto& DL = getDataLayout();
10680
10682 // FIXME: pass in SDLoc
10683 CLI.setDebugLoc(dl).setChain(Chain);
10684
10685 RTLIB::LibcallImpl BzeroImpl = Libcalls->getLibcallImpl(RTLIB::BZERO);
10686 bool UseBZero = BzeroImpl != RTLIB::Unsupported && isNullConstant(Src);
10687
10688 // If zeroing out and bzero is present, use it.
10689 if (UseBZero) {
10691 Args.emplace_back(Dst, PointerType::getUnqual(Ctx));
10692 Args.emplace_back(Size, DL.getIntPtrType(Ctx));
10693 CLI.setLibCallee(
10694 Libcalls->getLibcallImplCallingConv(BzeroImpl), Type::getVoidTy(Ctx),
10695 getExternalSymbol(BzeroImpl, TLI->getPointerTy(DL)), std::move(Args));
10696 } else {
10697 RTLIB::LibcallImpl MemsetImpl = Libcalls->getLibcallImpl(RTLIB::MEMSET);
10698
10699 MVT IntVT = MVT::getIntegerVT(LibInfo->getIntSize());
10701 Args.emplace_back(Dst, PointerType::getUnqual(Ctx));
10702 Args.emplace_back(getAnyExtOrTrunc(Src, dl, IntVT),
10703 Type::getIntNTy(Ctx, LibInfo->getIntSize()),
10704 LibInfo->getExtAttrForI32Param());
10705 Args.emplace_back(Size, DL.getIntPtrType(Ctx));
10706
10707 CLI.setLibCallee(Libcalls->getLibcallImplCallingConv(MemsetImpl),
10708 Dst.getValueType().getTypeForEVT(Ctx),
10709 getExternalSymbol(MemsetImpl, TLI->getPointerTy(DL)),
10710 std::move(Args));
10711 }
10712
10713 RTLIB::LibcallImpl MemsetImpl = Libcalls->getLibcallImpl(RTLIB::MEMSET);
10714 bool LowersToMemset = MemsetImpl == RTLIB::impl_memset;
10715
10716 // If we're going to use bzero, make sure not to tail call unless the
10717 // subsequent return doesn't need a value, as bzero doesn't return the first
10718 // arg unlike memset.
10719 bool ReturnsFirstArg = CI && funcReturnsFirstArgOfCall(*CI) && !UseBZero;
10720 bool IsTailCall = CI && CI->isTailCall() &&
10722 ReturnsFirstArg && LowersToMemset) &&
10723 // Lowering doesn't support tail calling inside a function
10724 // with a swifterror argument yet.
10726 CLI.setDiscardResult().setTailCall(IsTailCall);
10727
10728 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
10729 return CallResult.second;
10730}
10731
10734 Type *SizeTy, unsigned ElemSz,
10735 bool isTailCall,
10736 MachinePointerInfo DstPtrInfo) {
10737 // Lowering doesn't support tail calling inside a function with a
10738 // swifterror argument yet.
10739 isTailCall &= !hasSwiftErrorArg();
10740
10741 // Emit a library call.
10742 MVT IntVT = MVT::getIntegerVT(LibInfo->getIntSize());
10744 Args.emplace_back(Dst, getDataLayout().getIntPtrType(*getContext()));
10745 Args.emplace_back(getAnyExtOrTrunc(Value, dl, IntVT),
10746 Type::getIntNTy(*getContext(), LibInfo->getIntSize()),
10747 LibInfo->getExtAttrForI32Param());
10748 Args.emplace_back(getAtomicMemOpSizeArg(this, dl, Size));
10749
10750 RTLIB::Libcall LibraryCall =
10752 RTLIB::LibcallImpl LibcallImpl = Libcalls->getLibcallImpl(LibraryCall);
10753 if (LibcallImpl == RTLIB::Unsupported)
10754 report_fatal_error("Unsupported element size");
10755
10757 CLI.setDebugLoc(dl)
10758 .setChain(Chain)
10759 .setLibCallee(
10760 Libcalls->getLibcallImplCallingConv(LibcallImpl),
10762 getExternalSymbol(LibcallImpl, TLI->getPointerTy(getDataLayout())),
10763 std::move(Args))
10765 .setTailCall(isTailCall);
10766
10767 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
10768 return CallResult.second;
10769}
10770
10771SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
10773 MachineMemOperand *MMO,
10774 ISD::LoadExtType ExtType) {
10775 SDNodeKey ID(Opcode, VTList, Ops);
10776 ID.AddInteger(MemVT.getRawBits());
10777 ID.AddInteger(getSyntheticNodeSubclassData<AtomicSDNode>(
10778 dl.getIROrder(), Opcode, VTList, MemVT, MMO, ExtType));
10779 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
10780 ID.AddInteger(MMO->getFlags());
10781 FoldingSetInsertToken InsertToken;
10782 if (auto *E = cast_or_null<AtomicSDNode>(lookupNode(ID, dl, InsertToken))) {
10783 E->refineAlignment(MMO);
10784 E->refineMMOMetadata(MMO);
10785 return SDValue(E, 0);
10786 }
10787
10788 auto *N = newSDNode<AtomicSDNode>(dl.getIROrder(), dl.getDebugLoc(), Opcode,
10789 VTList, MemVT, MMO, ExtType);
10790 createOperands(N, Ops);
10791
10792 CSEMap.insert(N, InsertToken);
10793 InsertNode(N);
10794 SDValue V(N, 0);
10795 NewSDValueDbgMsg(V, "Creating new node: ", this);
10796 return V;
10797}
10798
10800 EVT MemVT, SDVTList VTs, SDValue Chain,
10801 SDValue Ptr, SDValue Cmp, SDValue Swp,
10802 MachineMemOperand *MMO) {
10803 assert(Opcode == ISD::ATOMIC_CMP_SWAP ||
10805 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
10806
10807 SDValue Ops[] = {Chain, Ptr, Cmp, Swp};
10808 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
10809}
10810
10811SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
10812 SDValue Chain, SDValue Ptr, SDValue Val,
10813 MachineMemOperand *MMO) {
10814 assert((Opcode == ISD::ATOMIC_LOAD_ADD || Opcode == ISD::ATOMIC_LOAD_SUB ||
10815 Opcode == ISD::ATOMIC_LOAD_AND || Opcode == ISD::ATOMIC_LOAD_CLR ||
10816 Opcode == ISD::ATOMIC_LOAD_OR || Opcode == ISD::ATOMIC_LOAD_XOR ||
10817 Opcode == ISD::ATOMIC_LOAD_NAND || Opcode == ISD::ATOMIC_LOAD_MIN ||
10818 Opcode == ISD::ATOMIC_LOAD_MAX || Opcode == ISD::ATOMIC_LOAD_UMIN ||
10819 Opcode == ISD::ATOMIC_LOAD_UMAX || Opcode == ISD::ATOMIC_LOAD_FADD ||
10820 Opcode == ISD::ATOMIC_LOAD_FSUB || Opcode == ISD::ATOMIC_LOAD_FMAX ||
10821 Opcode == ISD::ATOMIC_LOAD_FMIN ||
10822 Opcode == ISD::ATOMIC_LOAD_FMINIMUM ||
10823 Opcode == ISD::ATOMIC_LOAD_FMAXIMUM ||
10824 Opcode == ISD::ATOMIC_LOAD_FMINIMUMNUM ||
10825 Opcode == ISD::ATOMIC_LOAD_FMAXIMUMNUM ||
10826 Opcode == ISD::ATOMIC_LOAD_UINC_WRAP ||
10827 Opcode == ISD::ATOMIC_LOAD_UDEC_WRAP ||
10828 Opcode == ISD::ATOMIC_LOAD_USUB_COND ||
10829 Opcode == ISD::ATOMIC_LOAD_USUB_SAT || Opcode == ISD::ATOMIC_SWAP ||
10830 Opcode == ISD::ATOMIC_STORE) &&
10831 "Invalid Atomic Op");
10832
10833 EVT VT = Val.getValueType();
10834
10835 SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) :
10836 getVTList(VT, MVT::Other);
10837 SDValue Ops[] = {Chain, Ptr, Val};
10838 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
10839}
10840
10842 EVT MemVT, EVT VT, SDValue Chain,
10843 SDValue Ptr, MachineMemOperand *MMO) {
10844 SDVTList VTs = getVTList(VT, MVT::Other);
10845 SDValue Ops[] = {Chain, Ptr};
10846 return getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, VTs, Ops, MMO, ExtType);
10847}
10848
10849/// getMergeValues - Create a MERGE_VALUES node from the given operands.
10851 if (Ops.size() == 1)
10852 return Ops[0];
10853
10855 VTs.reserve(Ops.size());
10856 for (const SDValue &Op : Ops)
10857 VTs.push_back(Op.getValueType());
10858 return getNode(ISD::MERGE_VALUES, dl, getVTList(VTs), Ops);
10859}
10860
10862 SDValue Chain, const SDLoc &dl) {
10863 SmallVector<SDValue, 4> RetValues;
10864 RetValues.reserve(ResultTypes.size());
10865 for (EVT VT : ResultTypes)
10866 RetValues.push_back(VT == MVT::Other ? Chain : getPOISON(VT));
10867 return getMergeValues(RetValues, dl);
10868}
10869
10871 unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef<SDValue> Ops,
10872 EVT MemVT, MachinePointerInfo PtrInfo, Align Alignment,
10874 const AAMDNodes &AAInfo) {
10875 if (Size.hasValue() && !Size.getValue())
10877
10879 MachineMemOperand *MMO =
10880 MF.getMachineMemOperand(PtrInfo, Flags, Size, Alignment, AAInfo);
10881
10882 return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, MMO);
10883}
10884
10886 SDVTList VTList,
10887 ArrayRef<SDValue> Ops, EVT MemVT,
10888 MachineMemOperand *MMO) {
10889 return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, ArrayRef(MMO));
10890}
10891
10893 SDVTList VTList,
10894 ArrayRef<SDValue> Ops, EVT MemVT,
10896 assert(!MMOs.empty() && "Must have at least one MMO");
10897 assert(
10898 (Opcode == ISD::INTRINSIC_VOID || Opcode == ISD::INTRINSIC_W_CHAIN ||
10899 Opcode == ISD::PREFETCH ||
10900 (Opcode <= (unsigned)std::numeric_limits<int>::max() &&
10901 Opcode >= ISD::BUILTIN_OP_END && TSI->isTargetMemoryOpcode(Opcode))) &&
10902 "Opcode is not a memory-accessing opcode!");
10903
10905 if (MMOs.size() == 1) {
10906 MemRefs = MMOs[0];
10907 } else {
10908 // Allocate: [size_t count][MMO*][MMO*]...
10909 size_t AllocSize =
10910 sizeof(size_t) + MMOs.size() * sizeof(MachineMemOperand *);
10911 void *Buffer = Allocator.Allocate(AllocSize, alignof(size_t));
10912 size_t *CountPtr = static_cast<size_t *>(Buffer);
10913 *CountPtr = MMOs.size();
10914 MachineMemOperand **Array =
10915 reinterpret_cast<MachineMemOperand **>(CountPtr + 1);
10916 llvm::copy(MMOs, Array);
10917 MemRefs = Array;
10918 }
10919
10920 // Memoize the node unless it returns a glue result.
10922 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
10923 SDNodeKey ID(Opcode, VTList, Ops);
10924 ID.AddInteger(getSyntheticNodeSubclassData<MemIntrinsicSDNode>(
10925 Opcode, dl.getIROrder(), VTList, MemVT, MemRefs));
10926 ID.AddInteger(MemVT.getRawBits());
10927 for (const MachineMemOperand *MMO : MMOs) {
10928 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
10929 ID.AddInteger(MMO->getFlags());
10930 }
10931 FoldingSetInsertToken InsertToken;
10932 if (SDNode *E = lookupNode(ID, dl, InsertToken)) {
10933 cast<MemIntrinsicSDNode>(E)->refineAlignment(MMOs);
10934 return SDValue(E, 0);
10935 }
10936
10937 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
10938 VTList, MemVT, MemRefs);
10939 createOperands(N, Ops);
10940 CSEMap.insert(N, InsertToken);
10941 } else {
10942 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
10943 VTList, MemVT, MemRefs);
10944 createOperands(N, Ops);
10945 }
10946 InsertNode(N);
10947 SDValue V(N, 0);
10948 NewSDValueDbgMsg(V, "Creating new node: ", this);
10949 return V;
10950}
10951
10953 SDValue Chain, int FrameIndex) {
10954 const unsigned Opcode = IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END;
10955 const auto VTs = getVTList(MVT::Other);
10956 SDValue Ops[2] = {
10957 Chain,
10958 getFrameIndex(FrameIndex,
10959 getTargetLoweringInfo().getFrameIndexTy(getDataLayout()),
10960 true)};
10961
10962 SDNodeKey ID(Opcode, VTs, Ops);
10963 FoldingSetInsertToken InsertToken;
10964 if (SDNode *E = lookupNode(ID, dl, InsertToken))
10965 return SDValue(E, 0);
10966
10967 LifetimeSDNode *N =
10968 newSDNode<LifetimeSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), VTs);
10969 createOperands(N, Ops);
10970 CSEMap.insert(N, InsertToken);
10971 InsertNode(N);
10972 SDValue V(N, 0);
10973 NewSDValueDbgMsg(V, "Creating new node: ", this);
10974 return V;
10975}
10976
10978 uint64_t Guid, uint64_t Index,
10979 uint32_t Attr) {
10980 const unsigned Opcode = ISD::PSEUDO_PROBE;
10981 const auto VTs = getVTList(MVT::Other);
10982 SDValue Ops[] = {Chain};
10983 SDNodeKey ID(Opcode, VTs, Ops);
10984 ID.AddInteger(Guid);
10985 ID.AddInteger(Index);
10986 ID.AddInteger(Attr);
10987 FoldingSetInsertToken InsertToken;
10988 if (SDNode *E = lookupNode(ID, Dl, InsertToken))
10989 return SDValue(E, 0);
10990
10991 auto *N = newSDNode<PseudoProbeSDNode>(
10992 Opcode, Dl.getIROrder(), Dl.getDebugLoc(), VTs, Guid, Index, Attr);
10993 createOperands(N, Ops);
10994 CSEMap.insert(N, InsertToken);
10995 InsertNode(N);
10996 SDValue V(N, 0);
10997 NewSDValueDbgMsg(V, "Creating new node: ", this);
10998 return V;
10999}
11000
11001/// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
11002/// MachinePointerInfo record from it. This is particularly useful because the
11003/// code generator has many cases where it doesn't bother passing in a
11004/// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
11006 SelectionDAG &DAG, SDValue Ptr,
11007 int64_t Offset = 0) {
11008 // If this is FI+Offset, we can model it.
11009 if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr))
11011 FI->getIndex(), Offset);
11012
11013 // If this is (FI+Offset1)+Offset2, we can model it.
11014 if (Ptr.getOpcode() != ISD::ADD ||
11017 return Info;
11018
11019 int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
11021 DAG.getMachineFunction(), FI,
11022 Offset + cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue());
11023}
11024
11025/// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
11026/// MachinePointerInfo record from it. This is particularly useful because the
11027/// code generator has many cases where it doesn't bother passing in a
11028/// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
11030 SelectionDAG &DAG, SDValue Ptr,
11031 SDValue OffsetOp) {
11032 // If the 'Offset' value isn't a constant, we can't handle this.
11034 return InferPointerInfo(Info, DAG, Ptr, OffsetNode->getSExtValue());
11035 if (OffsetOp.isUndef())
11036 return InferPointerInfo(Info, DAG, Ptr);
11037 return Info;
11038}
11039
11041 EVT VT, const SDLoc &dl, SDValue Chain,
11042 SDValue Ptr, SDValue Offset,
11043 MachinePointerInfo PtrInfo, EVT MemVT,
11044 Align Alignment,
11045 MachineMemOperand::Flags MMOFlags,
11046 const MMOMetadata &Metadata) {
11047 assert(Chain.getValueType() == MVT::Other &&
11048 "Invalid chain type");
11049
11050 MMOFlags |= MachineMemOperand::MOLoad;
11051 assert((MMOFlags & MachineMemOperand::MOStore) == 0);
11052 // If we don't have a PtrInfo, infer the trivial frame index case to simplify
11053 // clients.
11054 if (PtrInfo.V.isNull())
11055 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
11056
11057 TypeSize Size = MemVT.getStoreSize();
11059 MachineMemOperand *MMO =
11060 MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, Alignment, Metadata);
11061 return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO);
11062}
11063
11065 EVT VT, const SDLoc &dl, SDValue Chain,
11066 SDValue Ptr, SDValue Offset, EVT MemVT,
11067 MachineMemOperand *MMO) {
11068 if (VT == MemVT) {
11069 ExtType = ISD::NON_EXTLOAD;
11070 } else if (ExtType == ISD::NON_EXTLOAD) {
11071 assert(VT == MemVT && "Non-extending load from different memory type!");
11072 } else {
11073 // Extending load.
11074 assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) &&
11075 "Should only be an extending load, not truncating!");
11076 assert(VT.isInteger() == MemVT.isInteger() &&
11077 "Cannot convert from FP to Int or Int -> FP!");
11078 assert(VT.isVector() == MemVT.isVector() &&
11079 "Cannot use an ext load to convert to or from a vector!");
11080 assert((!VT.isVector() ||
11082 "Cannot use an ext load to change the number of vector elements!");
11083 }
11084
11085 assert((!MMO->getRanges() ||
11087 ->getBitWidth() == MemVT.getScalarSizeInBits() &&
11088 MemVT.isInteger())) &&
11089 "Range metadata and load type must match!");
11090
11091 bool Indexed = AM != ISD::UNINDEXED;
11092 assert((Indexed || Offset.getOpcode() == ISD::POISON) &&
11093 "Unindexed load with an offset!");
11094
11095 SDVTList VTs = Indexed ?
11096 getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
11097 SDValue Ops[] = { Chain, Ptr, Offset };
11098 SDNodeKey ID(ISD::LOAD, VTs, Ops);
11099 ID.AddInteger(MemVT.getRawBits());
11100 ID.AddInteger(getSyntheticNodeSubclassData<LoadSDNode>(
11101 dl.getIROrder(), VTs, AM, ExtType, MemVT, MMO));
11102 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11103 ID.AddInteger(MMO->getFlags());
11104 FoldingSetInsertToken InsertToken;
11105 if (auto *E = cast_or_null<LoadSDNode>(lookupNode(ID, dl, InsertToken))) {
11106 E->refineAlignment(MMO);
11107 E->refineMMOMetadata(MMO);
11108 return SDValue(E, 0);
11109 }
11110 auto *N = newSDNode<LoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
11111 ExtType, MemVT, MMO);
11112 createOperands(N, Ops);
11113
11114 CSEMap.insert(N, InsertToken);
11115 InsertNode(N);
11116 SDValue V(N, 0);
11117 NewSDValueDbgMsg(V, "Creating new node: ", this);
11118 return V;
11119}
11120
11122 SDValue Ptr, MachinePointerInfo PtrInfo,
11123 MaybeAlign Alignment,
11124 MachineMemOperand::Flags MMOFlags,
11125 const MMOMetadata &Metadata) {
11127 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
11128 PtrInfo, VT, Alignment, MMOFlags, Metadata);
11129}
11130
11132 SDValue Ptr, MachineMemOperand *MMO) {
11134 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
11135 VT, MMO);
11136}
11137
11139 EVT VT, SDValue Chain, SDValue Ptr,
11140 MachinePointerInfo PtrInfo, EVT MemVT,
11141 MaybeAlign Alignment,
11142 MachineMemOperand::Flags MMOFlags,
11143 const MMOMetadata &Metadata) {
11145 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, PtrInfo,
11146 MemVT, Alignment, MMOFlags, Metadata);
11147}
11148
11150 EVT VT, SDValue Chain, SDValue Ptr, EVT MemVT,
11151 MachineMemOperand *MMO) {
11153 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef,
11154 MemVT, MMO);
11155}
11156
11160 LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
11161 assert(LD->getOffset().getOpcode() == ISD::POISON &&
11162 "Load is already a indexed load!");
11163 // Don't propagate the invariant or dereferenceable flags.
11164 auto MMOFlags =
11165 LD->getMemOperand()->getFlags() &
11167 return getLoad(
11168 AM, LD->getExtensionType(), OrigLoad.getValueType(), dl, LD->getChain(),
11169 Base, Offset, LD->getPointerInfo(), LD->getMemoryVT(), LD->getAlign(),
11170 MMOFlags,
11171 MMOMetadata(LD->getAAInfo(), LD->getRanges(), LD->getMemCacheHint()));
11172}
11173
11175 SDValue Ptr, MachinePointerInfo PtrInfo,
11176 Align Alignment,
11177 MachineMemOperand::Flags MMOFlags,
11178 const MMOMetadata &Metadata) {
11179 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
11180
11181 MMOFlags |= MachineMemOperand::MOStore;
11182 assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
11183 assert(!Metadata.Ranges && "range metadata is invalid for stores");
11184
11185 if (PtrInfo.V.isNull())
11186 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
11187
11190 MachineMemOperand *MMO =
11191 MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, Alignment, Metadata);
11192 return getStore(Chain, dl, Val, Ptr, MMO);
11193}
11194
11196 SDValue Ptr, MachineMemOperand *MMO) {
11198 return getStore(Chain, dl, Val, Ptr, Undef, Val.getValueType(), MMO,
11200}
11201
11203 SDValue Ptr, SDValue Offset, EVT SVT,
11205 bool IsTruncating) {
11206 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
11207 EVT VT = Val.getValueType();
11208 if (VT == SVT) {
11209 IsTruncating = false;
11210 } else if (!IsTruncating) {
11211 assert(VT == SVT && "No-truncating store from different memory type!");
11212 } else {
11214 "Should only be a truncating store, not extending!");
11215 assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!");
11216 assert(VT.isVector() == SVT.isVector() &&
11217 "Cannot use trunc store to convert to or from a vector!");
11218 assert((!VT.isVector() ||
11220 "Cannot use trunc store to change the number of vector elements!");
11221 }
11222
11223 bool Indexed = AM != ISD::UNINDEXED;
11224 assert((Indexed || Offset.getOpcode() == ISD::POISON) &&
11225 "Unindexed store with an offset!");
11226 SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other)
11227 : getVTList(MVT::Other);
11228 SDValue Ops[] = {Chain, Val, Ptr, Offset};
11229 SDNodeKey ID(ISD::STORE, VTs, Ops);
11230 ID.AddInteger(SVT.getRawBits());
11231 ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
11232 dl.getIROrder(), VTs, AM, IsTruncating, SVT, MMO));
11233 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11234 ID.AddInteger(MMO->getFlags());
11235 FoldingSetInsertToken InsertToken;
11236 if (SDNode *E = lookupNode(ID, dl, InsertToken)) {
11237 cast<StoreSDNode>(E)->refineAlignment(MMO);
11238 cast<StoreSDNode>(E)->refineMMOMetadata(MMO);
11239 return SDValue(E, 0);
11240 }
11241 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
11242 IsTruncating, SVT, MMO);
11243 createOperands(N, Ops);
11244
11245 CSEMap.insert(N, InsertToken);
11246 InsertNode(N);
11247 SDValue V(N, 0);
11248 NewSDValueDbgMsg(V, "Creating new node: ", this);
11249 return V;
11250}
11251
11253 SDValue Ptr, SDValue Offset,
11254 MachinePointerInfo PtrInfo, EVT SVT,
11255 Align Alignment,
11256 MachineMemOperand::Flags MMOFlags,
11257 const MMOMetadata &Metadata) {
11258 assert(Chain.getValueType() == MVT::Other &&
11259 "Invalid chain type");
11260
11261 MMOFlags |= MachineMemOperand::MOStore;
11262 assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
11263 assert(!Metadata.Ranges && "range metadata is invalid for stores");
11264
11265 if (PtrInfo.V.isNull())
11266 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
11267
11269 MachineMemOperand *MMO = MF.getMachineMemOperand(
11270 PtrInfo, MMOFlags, SVT.getStoreSize(), Alignment, Metadata);
11271 return getTruncStore(Chain, dl, Val, Ptr, Offset, SVT, MMO);
11272}
11273
11275 SDValue Ptr, MachinePointerInfo PtrInfo,
11276 EVT SVT, Align Alignment,
11277 MachineMemOperand::Flags MMOFlags,
11278 const MMOMetadata &Metadata) {
11279 return getTruncStore(Chain, dl, Val, Ptr, getPOISON(Ptr.getValueType()),
11280 PtrInfo, SVT, Alignment, MMOFlags, Metadata);
11281}
11282
11284 SDValue Ptr, SDValue Offset, EVT SVT,
11285 MachineMemOperand *MMO) {
11286 return getStore(Chain, dl, Val, Ptr, Offset, SVT, MMO, ISD::UNINDEXED, true);
11287}
11288
11290 SDValue Ptr, EVT SVT,
11291 MachineMemOperand *MMO) {
11292 return getStore(Chain, dl, Val, Ptr, getPOISON(Ptr.getValueType()), SVT, MMO,
11293 ISD::UNINDEXED, true);
11294}
11295
11299 StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
11300 assert(ST->getOffset().getOpcode() == ISD::POISON &&
11301 "Store is already a indexed store!");
11302 return getStore(ST->getChain(), dl, ST->getValue(), Base, Offset,
11303 ST->getMemoryVT(), ST->getMemOperand(), AM,
11304 ST->isTruncatingStore());
11305}
11306
11308 ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &dl,
11309 SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Mask, SDValue EVL,
11310 MachinePointerInfo PtrInfo, EVT MemVT, Align Alignment,
11311 MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
11312 const MDNode *Ranges, bool IsExpanding) {
11313 MMOFlags |= MachineMemOperand::MOLoad;
11314 assert((MMOFlags & MachineMemOperand::MOStore) == 0);
11315 // If we don't have a PtrInfo, infer the trivial frame index case to simplify
11316 // clients.
11317 if (PtrInfo.V.isNull())
11318 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
11319
11320 TypeSize Size = MemVT.getStoreSize();
11322 MachineMemOperand *MMO = MF.getMachineMemOperand(
11323 PtrInfo, MMOFlags, Size, Alignment, MMOMetadata(AAInfo, Ranges));
11324 return getLoadVP(AM, ExtType, VT, dl, Chain, Ptr, Offset, Mask, EVL, MemVT,
11325 MMO, IsExpanding);
11326}
11327
11329 ISD::LoadExtType ExtType, EVT VT,
11330 const SDLoc &dl, SDValue Chain, SDValue Ptr,
11331 SDValue Offset, SDValue Mask, SDValue EVL,
11332 EVT MemVT, MachineMemOperand *MMO,
11333 bool IsExpanding) {
11334 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
11335 assert(Mask.getValueType().getVectorElementCount() ==
11336 VT.getVectorElementCount() &&
11337 "Vector width mismatch between mask and data");
11338
11339 bool Indexed = AM != ISD::UNINDEXED;
11340 assert((Indexed || Offset.getOpcode() == ISD::POISON) &&
11341 "Unindexed load with an offset!");
11342
11343 SDVTList VTs = Indexed ? getVTList(VT, Ptr.getValueType(), MVT::Other)
11344 : getVTList(VT, MVT::Other);
11345 SDValue Ops[] = {Chain, Ptr, Offset, Mask, EVL};
11346 SDNodeKey ID(ISD::VP_LOAD, VTs, Ops);
11347 ID.AddInteger(MemVT.getRawBits());
11348 ID.AddInteger(getSyntheticNodeSubclassData<VPLoadSDNode>(
11349 dl.getIROrder(), VTs, AM, ExtType, IsExpanding, MemVT, MMO));
11350 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11351 ID.AddInteger(MMO->getFlags());
11352 FoldingSetInsertToken InsertToken;
11353 if (auto *E = cast_or_null<VPLoadSDNode>(lookupNode(ID, dl, InsertToken))) {
11354 E->refineAlignment(MMO);
11355 E->refineMMOMetadata(MMO);
11356 return SDValue(E, 0);
11357 }
11358 auto *N = newSDNode<VPLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
11359 ExtType, IsExpanding, MemVT, MMO);
11360 createOperands(N, Ops);
11361
11362 CSEMap.insert(N, InsertToken);
11363 InsertNode(N);
11364 SDValue V(N, 0);
11365 NewSDValueDbgMsg(V, "Creating new node: ", this);
11366 return V;
11367}
11368
11370 SDValue Ptr, SDValue Mask, SDValue EVL,
11371 MachinePointerInfo PtrInfo,
11372 MaybeAlign Alignment,
11373 MachineMemOperand::Flags MMOFlags,
11374 const AAMDNodes &AAInfo, const MDNode *Ranges,
11375 bool IsExpanding) {
11377 return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
11378 Mask, EVL, PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges,
11379 IsExpanding);
11380}
11381
11383 SDValue Ptr, SDValue Mask, SDValue EVL,
11384 MachineMemOperand *MMO, bool IsExpanding) {
11386 return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
11387 Mask, EVL, VT, MMO, IsExpanding);
11388}
11389
11391 EVT VT, SDValue Chain, SDValue Ptr,
11392 SDValue Mask, SDValue EVL,
11393 MachinePointerInfo PtrInfo, EVT MemVT,
11394 MaybeAlign Alignment,
11395 MachineMemOperand::Flags MMOFlags,
11396 const AAMDNodes &AAInfo, bool IsExpanding) {
11398 return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask,
11399 EVL, PtrInfo, MemVT, Alignment, MMOFlags, AAInfo, nullptr,
11400 IsExpanding);
11401}
11402
11404 EVT VT, SDValue Chain, SDValue Ptr,
11405 SDValue Mask, SDValue EVL, EVT MemVT,
11406 MachineMemOperand *MMO, bool IsExpanding) {
11408 return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask,
11409 EVL, MemVT, MMO, IsExpanding);
11410}
11411
11413 SDValue Ptr, SDValue Offset, SDValue Mask,
11414 SDValue EVL, EVT MemVT, MachineMemOperand *MMO,
11415 ISD::MemIndexedMode AM, bool IsTruncating,
11416 bool IsCompressing) {
11417 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
11418 assert(Mask.getValueType().getVectorElementCount() ==
11420 "Vector width mismatch between mask and data");
11421
11422 bool Indexed = AM != ISD::UNINDEXED;
11423 assert((Indexed || Offset.getOpcode() == ISD::POISON) &&
11424 "Unindexed vp_store with an offset!");
11425 SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other)
11426 : getVTList(MVT::Other);
11427 SDValue Ops[] = {Chain, Val, Ptr, Offset, Mask, EVL};
11428 SDNodeKey ID(ISD::VP_STORE, VTs, Ops);
11429 ID.AddInteger(MemVT.getRawBits());
11430 ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>(
11431 dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
11432 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11433 ID.AddInteger(MMO->getFlags());
11434 FoldingSetInsertToken InsertToken;
11435 if (SDNode *E = lookupNode(ID, dl, InsertToken)) {
11436 cast<VPStoreSDNode>(E)->refineAlignment(MMO);
11437 return SDValue(E, 0);
11438 }
11439 auto *N = newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
11440 IsTruncating, IsCompressing, MemVT, MMO);
11441 createOperands(N, Ops);
11442
11443 CSEMap.insert(N, InsertToken);
11444 InsertNode(N);
11445 SDValue V(N, 0);
11446 NewSDValueDbgMsg(V, "Creating new node: ", this);
11447 return V;
11448}
11449
11451 SDValue Val, SDValue Ptr, SDValue Mask,
11452 SDValue EVL, MachinePointerInfo PtrInfo,
11453 EVT SVT, Align Alignment,
11454 MachineMemOperand::Flags MMOFlags,
11455 const AAMDNodes &AAInfo,
11456 bool IsCompressing) {
11457 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
11458
11459 MMOFlags |= MachineMemOperand::MOStore;
11460 assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
11461
11462 if (PtrInfo.V.isNull())
11463 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
11464
11466 MachineMemOperand *MMO = MF.getMachineMemOperand(
11467 PtrInfo, MMOFlags, SVT.getStoreSize(), Alignment, AAInfo);
11468 return getTruncStoreVP(Chain, dl, Val, Ptr, Mask, EVL, SVT, MMO,
11469 IsCompressing);
11470}
11471
11473 SDValue Val, SDValue Ptr, SDValue Mask,
11474 SDValue EVL, EVT SVT,
11475 MachineMemOperand *MMO,
11476 bool IsCompressing) {
11477 EVT VT = Val.getValueType();
11478
11479 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
11480 if (VT == SVT)
11481 return getStoreVP(Chain, dl, Val, Ptr, getPOISON(Ptr.getValueType()), Mask,
11482 EVL, VT, MMO, ISD::UNINDEXED,
11483 /*IsTruncating*/ false, IsCompressing);
11484
11486 "Should only be a truncating store, not extending!");
11487 assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!");
11488 assert(VT.isVector() == SVT.isVector() &&
11489 "Cannot use trunc store to convert to or from a vector!");
11490 assert((!VT.isVector() ||
11492 "Cannot use trunc store to change the number of vector elements!");
11493
11494 SDVTList VTs = getVTList(MVT::Other);
11496 SDValue Ops[] = {Chain, Val, Ptr, Undef, Mask, EVL};
11497 SDNodeKey ID(ISD::VP_STORE, VTs, Ops);
11498 ID.AddInteger(SVT.getRawBits());
11499 ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>(
11500 dl.getIROrder(), VTs, ISD::UNINDEXED, true, IsCompressing, SVT, MMO));
11501 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11502 ID.AddInteger(MMO->getFlags());
11503 FoldingSetInsertToken InsertToken;
11504 if (SDNode *E = lookupNode(ID, dl, InsertToken)) {
11505 cast<VPStoreSDNode>(E)->refineAlignment(MMO);
11506 return SDValue(E, 0);
11507 }
11508 auto *N =
11509 newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
11510 ISD::UNINDEXED, true, IsCompressing, SVT, MMO);
11511 createOperands(N, Ops);
11512
11513 CSEMap.insert(N, InsertToken);
11514 InsertNode(N);
11515 SDValue V(N, 0);
11516 NewSDValueDbgMsg(V, "Creating new node: ", this);
11517 return V;
11518}
11519
11521 ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &DL,
11522 SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Stride, SDValue Mask,
11523 SDValue EVL, EVT MemVT, MachineMemOperand *MMO, bool IsExpanding) {
11524 bool Indexed = AM != ISD::UNINDEXED;
11525 assert((Indexed || Offset.getOpcode() == ISD::POISON) &&
11526 "Unindexed load with an offset!");
11527
11528 SDValue Ops[] = {Chain, Ptr, Offset, Stride, Mask, EVL};
11529 SDVTList VTs = Indexed ? getVTList(VT, Ptr.getValueType(), MVT::Other)
11530 : getVTList(VT, MVT::Other);
11531 SDNodeKey ID(ISD::EXPERIMENTAL_VP_STRIDED_LOAD, VTs, Ops);
11532 ID.AddInteger(MemVT.getRawBits());
11533 ID.AddInteger(getSyntheticNodeSubclassData<VPStridedLoadSDNode>(
11534 DL.getIROrder(), VTs, AM, ExtType, IsExpanding, MemVT, MMO));
11535 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11536
11537 FoldingSetInsertToken InsertToken;
11538 if (SDNode *E = lookupNode(ID, DL, InsertToken)) {
11539 cast<VPStridedLoadSDNode>(E)->refineAlignment(MMO);
11540 return SDValue(E, 0);
11541 }
11542
11543 auto *N =
11544 newSDNode<VPStridedLoadSDNode>(DL.getIROrder(), DL.getDebugLoc(), VTs, AM,
11545 ExtType, IsExpanding, MemVT, MMO);
11546 createOperands(N, Ops);
11547 CSEMap.insert(N, InsertToken);
11548 InsertNode(N);
11549 SDValue V(N, 0);
11550 NewSDValueDbgMsg(V, "Creating new node: ", this);
11551 return V;
11552}
11553
11555 SDValue Ptr, SDValue Stride,
11556 SDValue Mask, SDValue EVL,
11557 MachineMemOperand *MMO,
11558 bool IsExpanding) {
11560 return getStridedLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, DL, Chain, Ptr,
11561 Undef, Stride, Mask, EVL, VT, MMO, IsExpanding);
11562}
11563
11565 ISD::LoadExtType ExtType, const SDLoc &DL, EVT VT, SDValue Chain,
11566 SDValue Ptr, SDValue Stride, SDValue Mask, SDValue EVL, EVT MemVT,
11567 MachineMemOperand *MMO, bool IsExpanding) {
11569 return getStridedLoadVP(ISD::UNINDEXED, ExtType, VT, DL, Chain, Ptr, Undef,
11570 Stride, Mask, EVL, MemVT, MMO, IsExpanding);
11571}
11572
11574 SDValue Val, SDValue Ptr,
11575 SDValue Offset, SDValue Stride,
11576 SDValue Mask, SDValue EVL, EVT MemVT,
11577 MachineMemOperand *MMO,
11579 bool IsTruncating, bool IsCompressing) {
11580 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
11581 bool Indexed = AM != ISD::UNINDEXED;
11582 assert((Indexed || Offset.getOpcode() == ISD::POISON) &&
11583 "Unindexed vp_store with an offset!");
11584 SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other)
11585 : getVTList(MVT::Other);
11586 SDValue Ops[] = {Chain, Val, Ptr, Offset, Stride, Mask, EVL};
11587 SDNodeKey ID(ISD::EXPERIMENTAL_VP_STRIDED_STORE, VTs, Ops);
11588 ID.AddInteger(MemVT.getRawBits());
11589 ID.AddInteger(getSyntheticNodeSubclassData<VPStridedStoreSDNode>(
11590 DL.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
11591 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11592 FoldingSetInsertToken InsertToken;
11593 if (SDNode *E = lookupNode(ID, DL, InsertToken)) {
11594 cast<VPStridedStoreSDNode>(E)->refineAlignment(MMO);
11595 return SDValue(E, 0);
11596 }
11597 auto *N = newSDNode<VPStridedStoreSDNode>(DL.getIROrder(), DL.getDebugLoc(),
11598 VTs, AM, IsTruncating,
11599 IsCompressing, MemVT, MMO);
11600 createOperands(N, Ops);
11601
11602 CSEMap.insert(N, InsertToken);
11603 InsertNode(N);
11604 SDValue V(N, 0);
11605 NewSDValueDbgMsg(V, "Creating new node: ", this);
11606 return V;
11607}
11608
11611 ISD::MemIndexType IndexType) {
11612 assert(Ops.size() == 6 && "Incompatible number of operands");
11613
11614 SDNodeKey ID(ISD::VP_GATHER, VTs, Ops);
11615 ID.AddInteger(VT.getRawBits());
11616 ID.AddInteger(getSyntheticNodeSubclassData<VPGatherSDNode>(
11617 dl.getIROrder(), VTs, VT, MMO, IndexType));
11618 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11619 ID.AddInteger(MMO->getFlags());
11620 FoldingSetInsertToken InsertToken;
11621 if (SDNode *E = lookupNode(ID, dl, InsertToken)) {
11622 cast<VPGatherSDNode>(E)->refineAlignment(MMO);
11623 return SDValue(E, 0);
11624 }
11625
11626 auto *N = newSDNode<VPGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
11627 VT, MMO, IndexType);
11628 createOperands(N, Ops);
11629
11630 assert(N->getMask().getValueType().getVectorElementCount() ==
11631 N->getValueType(0).getVectorElementCount() &&
11632 "Vector width mismatch between mask and data");
11633 assert(N->getIndex().getValueType().getVectorElementCount().isScalable() ==
11634 N->getValueType(0).getVectorElementCount().isScalable() &&
11635 "Scalable flags of index and data do not match");
11637 N->getIndex().getValueType().getVectorElementCount(),
11638 N->getValueType(0).getVectorElementCount()) &&
11639 "Vector width mismatch between index and data");
11640 assert(isa<ConstantSDNode>(N->getScale()) &&
11641 N->getScale()->getAsAPIntVal().isPowerOf2() &&
11642 "Scale should be a constant power of 2");
11643
11644 CSEMap.insert(N, InsertToken);
11645 InsertNode(N);
11646 SDValue V(N, 0);
11647 NewSDValueDbgMsg(V, "Creating new node: ", this);
11648 return V;
11649}
11650
11653 MachineMemOperand *MMO,
11654 ISD::MemIndexType IndexType) {
11655 assert(Ops.size() == 7 && "Incompatible number of operands");
11656
11657 SDNodeKey ID(ISD::VP_SCATTER, VTs, Ops);
11658 ID.AddInteger(VT.getRawBits());
11659 ID.AddInteger(getSyntheticNodeSubclassData<VPScatterSDNode>(
11660 dl.getIROrder(), VTs, VT, MMO, IndexType));
11661 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11662 ID.AddInteger(MMO->getFlags());
11663 FoldingSetInsertToken InsertToken;
11664 if (SDNode *E = lookupNode(ID, dl, InsertToken)) {
11665 cast<VPScatterSDNode>(E)->refineAlignment(MMO);
11666 return SDValue(E, 0);
11667 }
11668 auto *N = newSDNode<VPScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
11669 VT, MMO, IndexType);
11670 createOperands(N, Ops);
11671
11672 assert(N->getMask().getValueType().getVectorElementCount() ==
11673 N->getValue().getValueType().getVectorElementCount() &&
11674 "Vector width mismatch between mask and data");
11675 assert(
11676 N->getIndex().getValueType().getVectorElementCount().isScalable() ==
11677 N->getValue().getValueType().getVectorElementCount().isScalable() &&
11678 "Scalable flags of index and data do not match");
11680 N->getIndex().getValueType().getVectorElementCount(),
11681 N->getValue().getValueType().getVectorElementCount()) &&
11682 "Vector width mismatch between index and data");
11683 assert(isa<ConstantSDNode>(N->getScale()) &&
11684 N->getScale()->getAsAPIntVal().isPowerOf2() &&
11685 "Scale should be a constant power of 2");
11686
11687 CSEMap.insert(N, InsertToken);
11688 InsertNode(N);
11689 SDValue V(N, 0);
11690 NewSDValueDbgMsg(V, "Creating new node: ", this);
11691 return V;
11692}
11693
11696 SDValue PassThru, EVT MemVT,
11697 MachineMemOperand *MMO,
11699 ISD::LoadExtType ExtTy, bool isExpanding) {
11700 bool Indexed = AM != ISD::UNINDEXED;
11701 assert((Indexed || Offset.getOpcode() == ISD::POISON) &&
11702 "Unindexed masked load with an offset!");
11703 SDVTList VTs = Indexed ? getVTList(VT, Base.getValueType(), MVT::Other)
11704 : getVTList(VT, MVT::Other);
11705 SDValue Ops[] = {Chain, Base, Offset, Mask, PassThru};
11706 SDNodeKey ID(ISD::MLOAD, VTs, Ops);
11707 ID.AddInteger(MemVT.getRawBits());
11708 ID.AddInteger(getSyntheticNodeSubclassData<MaskedLoadSDNode>(
11709 dl.getIROrder(), VTs, AM, ExtTy, isExpanding, MemVT, MMO));
11710 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11711 ID.AddInteger(MMO->getFlags());
11712 FoldingSetInsertToken InsertToken;
11713 if (SDNode *E = lookupNode(ID, dl, InsertToken)) {
11714 cast<MaskedLoadSDNode>(E)->refineAlignment(MMO);
11715 return SDValue(E, 0);
11716 }
11717 auto *N = newSDNode<MaskedLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
11718 AM, ExtTy, isExpanding, MemVT, MMO);
11719 createOperands(N, Ops);
11720
11721 CSEMap.insert(N, InsertToken);
11722 InsertNode(N);
11723 SDValue V(N, 0);
11724 NewSDValueDbgMsg(V, "Creating new node: ", this);
11725 return V;
11726}
11727
11732 assert(LD->getOffset().getOpcode() == ISD::POISON &&
11733 "Masked load is already a indexed load!");
11734 return getMaskedLoad(OrigLoad.getValueType(), dl, LD->getChain(), Base,
11735 Offset, LD->getMask(), LD->getPassThru(),
11736 LD->getMemoryVT(), LD->getMemOperand(), AM,
11737 LD->getExtensionType(), LD->isExpandingLoad());
11738}
11739
11742 SDValue Mask, EVT MemVT,
11743 MachineMemOperand *MMO,
11744 ISD::MemIndexedMode AM, bool IsTruncating,
11745 bool IsCompressing) {
11746 assert(Chain.getValueType() == MVT::Other &&
11747 "Invalid chain type");
11748 bool Indexed = AM != ISD::UNINDEXED;
11749 assert((Indexed || Offset.getOpcode() == ISD::POISON) &&
11750 "Unindexed masked store with an offset!");
11751 SDVTList VTs = Indexed ? getVTList(Base.getValueType(), MVT::Other)
11752 : getVTList(MVT::Other);
11753 SDValue Ops[] = {Chain, Val, Base, Offset, Mask};
11754 SDNodeKey ID(ISD::MSTORE, VTs, Ops);
11755 ID.AddInteger(MemVT.getRawBits());
11756 ID.AddInteger(getSyntheticNodeSubclassData<MaskedStoreSDNode>(
11757 dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
11758 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11759 ID.AddInteger(MMO->getFlags());
11760 FoldingSetInsertToken InsertToken;
11761 if (SDNode *E = lookupNode(ID, dl, InsertToken)) {
11762 cast<MaskedStoreSDNode>(E)->refineAlignment(MMO);
11763 return SDValue(E, 0);
11764 }
11765 auto *N =
11766 newSDNode<MaskedStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
11767 IsTruncating, IsCompressing, MemVT, MMO);
11768 createOperands(N, Ops);
11769
11770 CSEMap.insert(N, InsertToken);
11771 InsertNode(N);
11772 SDValue V(N, 0);
11773 NewSDValueDbgMsg(V, "Creating new node: ", this);
11774 return V;
11775}
11776
11781 assert(ST->getOffset().getOpcode() == ISD::POISON &&
11782 "Masked store is already a indexed store!");
11783 return getMaskedStore(ST->getChain(), dl, ST->getValue(), Base, Offset,
11784 ST->getMask(), ST->getMemoryVT(), ST->getMemOperand(),
11785 AM, ST->isTruncatingStore(), ST->isCompressingStore());
11786}
11787
11790 MachineMemOperand *MMO,
11791 ISD::MemIndexType IndexType,
11792 ISD::LoadExtType ExtTy) {
11793 assert(Ops.size() == 6 && "Incompatible number of operands");
11794
11795 SDNodeKey ID(ISD::MGATHER, VTs, Ops);
11796 ID.AddInteger(MemVT.getRawBits());
11797 ID.AddInteger(getSyntheticNodeSubclassData<MaskedGatherSDNode>(
11798 dl.getIROrder(), VTs, MemVT, MMO, IndexType, ExtTy));
11799 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11800 ID.AddInteger(MMO->getFlags());
11801 FoldingSetInsertToken InsertToken;
11802 if (SDNode *E = lookupNode(ID, dl, InsertToken)) {
11803 cast<MaskedGatherSDNode>(E)->refineAlignment(MMO);
11804 return SDValue(E, 0);
11805 }
11806
11807 auto *N = newSDNode<MaskedGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(),
11808 VTs, MemVT, MMO, IndexType, ExtTy);
11809 createOperands(N, Ops);
11810
11811 assert(N->getPassThru().getValueType() == N->getValueType(0) &&
11812 "Incompatible type of the PassThru value in MaskedGatherSDNode");
11813 assert(N->getMask().getValueType().getVectorElementCount() ==
11814 N->getValueType(0).getVectorElementCount() &&
11815 "Vector width mismatch between mask and data");
11816 assert(N->getIndex().getValueType().getVectorElementCount().isScalable() ==
11817 N->getValueType(0).getVectorElementCount().isScalable() &&
11818 "Scalable flags of index and data do not match");
11820 N->getIndex().getValueType().getVectorElementCount(),
11821 N->getValueType(0).getVectorElementCount()) &&
11822 "Vector width mismatch between index and data");
11823 assert(isa<ConstantSDNode>(N->getScale()) &&
11824 N->getScale()->getAsAPIntVal().isPowerOf2() &&
11825 "Scale should be a constant power of 2");
11826
11827 CSEMap.insert(N, InsertToken);
11828 InsertNode(N);
11829 SDValue V(N, 0);
11830 NewSDValueDbgMsg(V, "Creating new node: ", this);
11831 return V;
11832}
11833
11836 MachineMemOperand *MMO,
11837 ISD::MemIndexType IndexType,
11838 bool IsTrunc) {
11839 assert(Ops.size() == 6 && "Incompatible number of operands");
11840
11841 SDNodeKey ID(ISD::MSCATTER, VTs, Ops);
11842 ID.AddInteger(MemVT.getRawBits());
11843 ID.AddInteger(getSyntheticNodeSubclassData<MaskedScatterSDNode>(
11844 dl.getIROrder(), VTs, MemVT, MMO, IndexType, IsTrunc));
11845 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11846 ID.AddInteger(MMO->getFlags());
11847 FoldingSetInsertToken InsertToken;
11848 if (SDNode *E = lookupNode(ID, dl, InsertToken)) {
11849 cast<MaskedScatterSDNode>(E)->refineAlignment(MMO);
11850 return SDValue(E, 0);
11851 }
11852
11853 auto *N = newSDNode<MaskedScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(),
11854 VTs, MemVT, MMO, IndexType, IsTrunc);
11855 createOperands(N, Ops);
11856
11857 assert(N->getMask().getValueType().getVectorElementCount() ==
11858 N->getValue().getValueType().getVectorElementCount() &&
11859 "Vector width mismatch between mask and data");
11860 assert(
11861 N->getIndex().getValueType().getVectorElementCount().isScalable() ==
11862 N->getValue().getValueType().getVectorElementCount().isScalable() &&
11863 "Scalable flags of index and data do not match");
11865 N->getIndex().getValueType().getVectorElementCount(),
11866 N->getValue().getValueType().getVectorElementCount()) &&
11867 "Vector width mismatch between index and data");
11868 assert(isa<ConstantSDNode>(N->getScale()) &&
11869 N->getScale()->getAsAPIntVal().isPowerOf2() &&
11870 "Scale should be a constant power of 2");
11871
11872 CSEMap.insert(N, InsertToken);
11873 InsertNode(N);
11874 SDValue V(N, 0);
11875 NewSDValueDbgMsg(V, "Creating new node: ", this);
11876 return V;
11877}
11878
11880 const SDLoc &dl, ArrayRef<SDValue> Ops,
11881 MachineMemOperand *MMO,
11882 ISD::MemIndexType IndexType) {
11883 assert(Ops.size() == 7 && "Incompatible number of operands");
11884
11886 ID.AddInteger(MemVT.getRawBits());
11887 ID.AddInteger(getSyntheticNodeSubclassData<MaskedHistogramSDNode>(
11888 dl.getIROrder(), VTs, MemVT, MMO, IndexType));
11889 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11890 ID.AddInteger(MMO->getFlags());
11891 FoldingSetInsertToken InsertToken;
11892 if (SDNode *E = lookupNode(ID, dl, InsertToken)) {
11893 cast<MaskedGatherSDNode>(E)->refineAlignment(MMO);
11894 return SDValue(E, 0);
11895 }
11896
11897 auto *N = newSDNode<MaskedHistogramSDNode>(dl.getIROrder(), dl.getDebugLoc(),
11898 VTs, MemVT, MMO, IndexType);
11899 createOperands(N, Ops);
11900
11901 assert(N->getMask().getValueType().getVectorElementCount() ==
11902 N->getIndex().getValueType().getVectorElementCount() &&
11903 "Vector width mismatch between mask and data");
11904 assert(isa<ConstantSDNode>(N->getScale()) &&
11905 N->getScale()->getAsAPIntVal().isPowerOf2() &&
11906 "Scale should be a constant power of 2");
11907 assert(N->getInc().getValueType().isInteger() && "Non integer update value");
11908
11909 CSEMap.insert(N, InsertToken);
11910 InsertNode(N);
11911 SDValue V(N, 0);
11912 NewSDValueDbgMsg(V, "Creating new node: ", this);
11913 return V;
11914}
11915
11917 SDValue Ptr, SDValue Mask, SDValue EVL,
11918 MachineMemOperand *MMO) {
11919 SDVTList VTs = getVTList(VT, EVL.getValueType(), MVT::Other);
11920 SDValue Ops[] = {Chain, Ptr, Mask, EVL};
11921 SDNodeKey ID(ISD::VP_LOAD_FF, VTs, Ops);
11922 ID.AddInteger(VT.getRawBits());
11923 ID.AddInteger(getSyntheticNodeSubclassData<VPLoadFFSDNode>(DL.getIROrder(),
11924 VTs, VT, MMO));
11925 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11926 ID.AddInteger(MMO->getFlags());
11927 FoldingSetInsertToken InsertToken;
11928 if (SDNode *E = lookupNode(ID, DL, InsertToken)) {
11929 cast<VPLoadFFSDNode>(E)->refineAlignment(MMO);
11930 return SDValue(E, 0);
11931 }
11932 auto *N = newSDNode<VPLoadFFSDNode>(DL.getIROrder(), DL.getDebugLoc(), VTs,
11933 VT, MMO);
11934 createOperands(N, Ops);
11935
11936 CSEMap.insert(N, InsertToken);
11937 InsertNode(N);
11938 SDValue V(N, 0);
11939 NewSDValueDbgMsg(V, "Creating new node: ", this);
11940 return V;
11941}
11942
11944 EVT MemVT, MachineMemOperand *MMO) {
11945 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
11946 SDVTList VTs = getVTList(MVT::Other);
11947 SDValue Ops[] = {Chain, Ptr};
11949 ID.AddInteger(MemVT.getRawBits());
11950 ID.AddInteger(getSyntheticNodeSubclassData<FPStateAccessSDNode>(
11951 ISD::GET_FPENV_MEM, dl.getIROrder(), VTs, MemVT, MMO));
11952 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11953 ID.AddInteger(MMO->getFlags());
11954 FoldingSetInsertToken InsertToken;
11955 if (SDNode *E = lookupNode(ID, dl, InsertToken))
11956 return SDValue(E, 0);
11957
11958 auto *N = newSDNode<FPStateAccessSDNode>(ISD::GET_FPENV_MEM, dl.getIROrder(),
11959 dl.getDebugLoc(), VTs, MemVT, MMO);
11960 createOperands(N, Ops);
11961
11962 CSEMap.insert(N, InsertToken);
11963 InsertNode(N);
11964 SDValue V(N, 0);
11965 NewSDValueDbgMsg(V, "Creating new node: ", this);
11966 return V;
11967}
11968
11970 EVT MemVT, MachineMemOperand *MMO) {
11971 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
11972 SDVTList VTs = getVTList(MVT::Other);
11973 SDValue Ops[] = {Chain, Ptr};
11975 ID.AddInteger(MemVT.getRawBits());
11976 ID.AddInteger(getSyntheticNodeSubclassData<FPStateAccessSDNode>(
11977 ISD::SET_FPENV_MEM, dl.getIROrder(), VTs, MemVT, MMO));
11978 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11979 ID.AddInteger(MMO->getFlags());
11980 FoldingSetInsertToken InsertToken;
11981 if (SDNode *E = lookupNode(ID, dl, InsertToken))
11982 return SDValue(E, 0);
11983
11984 auto *N = newSDNode<FPStateAccessSDNode>(ISD::SET_FPENV_MEM, dl.getIROrder(),
11985 dl.getDebugLoc(), VTs, MemVT, MMO);
11986 createOperands(N, Ops);
11987
11988 CSEMap.insert(N, InsertToken);
11989 InsertNode(N);
11990 SDValue V(N, 0);
11991 NewSDValueDbgMsg(V, "Creating new node: ", this);
11992 return V;
11993}
11994
11996 // select undef, T, F --> T (if T is a constant), otherwise F
11997 // select, ?, undef, F --> F
11998 // select, ?, T, undef --> T
11999 if (Cond.isUndef())
12000 return isConstantValueOfAnyType(T) ? T : F;
12001 if (T.isUndef())
12003 if (F.isUndef())
12005
12006 // select true, T, F --> T
12007 // select false, T, F --> F
12008 if (auto C = isBoolConstant(Cond))
12009 return *C ? T : F;
12010
12011 // select ?, T, T --> T
12012 if (T == F)
12013 return T;
12014
12015 return SDValue();
12016}
12017
12019 // shift undef, Y --> 0 (can always assume that the undef value is 0)
12020 if (X.isUndef())
12021 return getConstant(0, SDLoc(X.getNode()), X.getValueType());
12022 // shift X, undef --> undef (because it may shift by the bitwidth)
12023 if (Y.isUndef())
12024 return getUNDEF(X.getValueType());
12025
12026 // shift 0, Y --> 0
12027 // shift X, 0 --> X
12029 return X;
12030
12031 // shift X, C >= bitwidth(X) --> undef
12032 // All vector elements must be too big (or undef) to avoid partial undefs.
12033 auto isShiftTooBig = [X](ConstantSDNode *Val) {
12034 return !Val || Val->getAPIntValue().uge(X.getScalarValueSizeInBits());
12035 };
12036 if (ISD::matchUnaryPredicate(Y, isShiftTooBig, true))
12037 return getUNDEF(X.getValueType());
12038
12039 // shift i1/vXi1 X, Y --> X (any non-zero shift amount is undefined).
12040 if (X.getValueType().getScalarType() == MVT::i1)
12041 return X;
12042
12043 return SDValue();
12044}
12045
12047 SDNodeFlags Flags) {
12048 // If this operation has 'nnan' or 'ninf' and at least 1 disallowed operand
12049 // (an undef operand can be chosen to be Nan/Inf), then the result of this
12050 // operation is poison. That result can be relaxed to undef.
12051 ConstantFPSDNode *XC = isConstOrConstSplatFP(X, /* AllowUndefs */ true);
12052 ConstantFPSDNode *YC = isConstOrConstSplatFP(Y, /* AllowUndefs */ true);
12053 bool HasNan = (XC && XC->getValueAPF().isNaN()) ||
12054 (YC && YC->getValueAPF().isNaN());
12055 bool HasInf = (XC && XC->getValueAPF().isInfinity()) ||
12056 (YC && YC->getValueAPF().isInfinity());
12057
12058 if (Flags.hasNoNaNs() && (HasNan || X.isUndef() || Y.isUndef()))
12059 return getUNDEF(X.getValueType());
12060
12061 if (Flags.hasNoInfs() && (HasInf || X.isUndef() || Y.isUndef()))
12062 return getUNDEF(X.getValueType());
12063
12064 if (!YC)
12065 return SDValue();
12066
12067 // X + -0.0 --> X
12068 if (Opcode == ISD::FADD)
12069 if (YC->getValueAPF().isNegZero())
12070 return X;
12071
12072 // X - +0.0 --> X
12073 if (Opcode == ISD::FSUB)
12074 if (YC->getValueAPF().isPosZero())
12075 return X;
12076
12077 // X * 1.0 --> X
12078 // X / 1.0 --> X
12079 if (Opcode == ISD::FMUL || Opcode == ISD::FDIV)
12080 if (YC->getValueAPF().isOne())
12081 return X;
12082
12083 // X * 0.0 --> 0.0
12084 if (Opcode == ISD::FMUL && Flags.hasNoNaNs() && Flags.hasNoSignedZeros())
12085 if (YC->getValueAPF().isZero())
12086 return getConstantFP(0.0, SDLoc(Y), Y.getValueType());
12087
12088 return SDValue();
12089}
12090
12092 SDValue Ptr, SDValue SV, unsigned Align) {
12093 SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, dl, MVT::i32) };
12094 return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops);
12095}
12096
12097SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
12099 switch (Ops.size()) {
12100 case 0: return getNode(Opcode, DL, VT);
12101 case 1: return getNode(Opcode, DL, VT, Ops[0].get());
12102 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
12103 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
12104 default: break;
12105 }
12106
12107 // Copy from an SDUse array into an SDValue array for use with
12108 // the regular getNode logic.
12110 return getNode(Opcode, DL, VT, NewOps);
12111}
12112
12113SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
12115 SDNodeFlags Flags;
12116 if (Inserter)
12117 Flags = Inserter->getFlags();
12118 return getNode(Opcode, DL, VT, Ops, Flags);
12119}
12120
12121SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
12122 ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
12123 unsigned NumOps = Ops.size();
12124 switch (NumOps) {
12125 case 0: return getNode(Opcode, DL, VT);
12126 case 1: return getNode(Opcode, DL, VT, Ops[0], Flags);
12127 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Flags);
12128 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2], Flags);
12129 default: break;
12130 }
12131
12132#ifndef NDEBUG
12133 for (const auto &Op : Ops)
12134 assert(Op.getOpcode() != ISD::DELETED_NODE &&
12135 "Operand is DELETED_NODE!");
12136#endif
12137
12138 switch (Opcode) {
12139 default: break;
12140 case ISD::BUILD_VECTOR:
12141 // Attempt to simplify BUILD_VECTOR.
12142 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
12143 return V;
12144 break;
12146 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
12147 return V;
12148 break;
12149 case ISD::SELECT_CC:
12150 assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
12151 assert(Ops[0].getValueType() == Ops[1].getValueType() &&
12152 "LHS and RHS of condition must have same type!");
12153 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
12154 "True and False arms of SelectCC must have same type!");
12155 assert(Ops[2].getValueType() == VT &&
12156 "select_cc node must be of same type as true and false value!");
12157 assert((!Ops[0].getValueType().isVector() ||
12158 Ops[0].getValueType().getVectorElementCount() ==
12159 VT.getVectorElementCount()) &&
12160 "Expected select_cc with vector result to have the same sized "
12161 "comparison type!");
12162 break;
12163 case ISD::BR_CC:
12164 assert(NumOps == 5 && "BR_CC takes 5 operands!");
12165 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
12166 "LHS/RHS of comparison should match types!");
12167 break;
12168 case ISD::VP_REDUCE_MUL:
12169 // If it is VP_REDUCE_MUL mask operation then turn it to VP_REDUCE_AND
12170 if (VT == MVT::i1)
12171 Opcode = ISD::VP_REDUCE_AND;
12172 break;
12173 case ISD::VP_REDUCE_ADD:
12174 // If it is VP_REDUCE_ADD mask operation then turn it to VP_REDUCE_XOR
12175 if (VT == MVT::i1)
12176 Opcode = ISD::VP_REDUCE_XOR;
12177 break;
12178 case ISD::VP_REDUCE_SMAX:
12179 case ISD::VP_REDUCE_UMIN:
12180 // If it is VP_REDUCE_SMAX/VP_REDUCE_UMIN mask operation then turn it to
12181 // VP_REDUCE_AND.
12182 if (VT == MVT::i1)
12183 Opcode = ISD::VP_REDUCE_AND;
12184 break;
12185 case ISD::VP_REDUCE_SMIN:
12186 case ISD::VP_REDUCE_UMAX:
12187 // If it is VP_REDUCE_SMIN/VP_REDUCE_UMAX mask operation then turn it to
12188 // VP_REDUCE_OR.
12189 if (VT == MVT::i1)
12190 Opcode = ISD::VP_REDUCE_OR;
12191 break;
12192 }
12193
12194 // Memoize nodes.
12195 SDNode *N;
12196 SDVTList VTs = getVTList(VT);
12197
12198 if (VT != MVT::Glue) {
12199 SDNodeKey ID(Opcode, VTs, Ops);
12200 FoldingSetInsertToken InsertToken;
12201
12202 if (SDNode *E = lookupNode(ID, DL, InsertToken)) {
12203 E->intersectFlagsWith(Flags);
12204 return SDValue(E, 0);
12205 }
12206
12207 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
12208 createOperands(N, Ops);
12209
12210 CSEMap.insert(N, InsertToken);
12211 } else {
12212 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
12213 createOperands(N, Ops);
12214 }
12215
12216 N->setFlags(Flags);
12217 InsertNode(N);
12218 SDValue V(N, 0);
12219 NewSDValueDbgMsg(V, "Creating new node: ", this);
12220 return V;
12221}
12222
12223SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
12224 ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) {
12225 SDNodeFlags Flags;
12226 if (Inserter)
12227 Flags = Inserter->getFlags();
12228 return getNode(Opcode, DL, getVTList(ResultTys), Ops, Flags);
12229}
12230
12231SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
12233 const SDNodeFlags Flags) {
12234 return getNode(Opcode, DL, getVTList(ResultTys), Ops, Flags);
12235}
12236
12237SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
12239 SDNodeFlags Flags;
12240 if (Inserter)
12241 Flags = Inserter->getFlags();
12242 return getNode(Opcode, DL, VTList, Ops, Flags);
12243}
12244
12245SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
12246 ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
12247 if (VTList.NumVTs == 1)
12248 return getNode(Opcode, DL, VTList.VTs[0], Ops, Flags);
12249
12250#ifndef NDEBUG
12251 for (const auto &Op : Ops)
12252 assert(Op.getOpcode() != ISD::DELETED_NODE &&
12253 "Operand is DELETED_NODE!");
12254#endif
12255
12256 if (SDValue V = FoldConstantArithmetic(Opcode, DL, VTList, Ops, Flags))
12257 return V;
12258
12259 switch (Opcode) {
12260 case ISD::SADDO:
12261 case ISD::UADDO:
12262 case ISD::SSUBO:
12263 case ISD::USUBO: {
12264 assert(VTList.NumVTs == 2 && Ops.size() == 2 &&
12265 "Invalid add/sub overflow op!");
12266 assert(VTList.VTs[0].isInteger() && VTList.VTs[1].isInteger() &&
12267 Ops[0].getValueType() == Ops[1].getValueType() &&
12268 Ops[0].getValueType() == VTList.VTs[0] &&
12269 "Binary operator types must match!");
12270 SDValue N1 = Ops[0], N2 = Ops[1];
12271 canonicalizeCommutativeBinop(Opcode, N1, N2);
12272
12273 // (X +- 0) -> X with zero-overflow.
12274 ConstantSDNode *N2CV = isConstOrConstSplat(N2, /*AllowUndefs*/ false,
12275 /*AllowTruncation*/ true);
12276 if (N2CV && N2CV->isZero()) {
12277 SDValue ZeroOverFlow = getConstant(0, DL, VTList.VTs[1]);
12278 return getNode(ISD::MERGE_VALUES, DL, VTList, {N1, ZeroOverFlow}, Flags);
12279 }
12280
12281 if (VTList.VTs[0].getScalarType() == MVT::i1 &&
12282 VTList.VTs[1].getScalarType() == MVT::i1) {
12283 SDValue F1 = getFreeze(N1);
12284 SDValue F2 = getFreeze(N2);
12285 // {vXi1,vXi1} (u/s)addo(vXi1 x, vXi1y) -> {xor(x,y),and(x,y)}
12286 if (Opcode == ISD::UADDO || Opcode == ISD::SADDO)
12287 return getNode(ISD::MERGE_VALUES, DL, VTList,
12288 {getNode(ISD::XOR, DL, VTList.VTs[0], F1, F2),
12289 getNode(ISD::AND, DL, VTList.VTs[1], F1, F2)},
12290 Flags);
12291 // {vXi1,vXi1} (u/s)subo(vXi1 x, vXi1y) -> {xor(x,y),and(~x,y)}
12292 if (Opcode == ISD::USUBO || Opcode == ISD::SSUBO) {
12293 SDValue NotF1 = getNOT(DL, F1, VTList.VTs[0]);
12294 return getNode(ISD::MERGE_VALUES, DL, VTList,
12295 {getNode(ISD::XOR, DL, VTList.VTs[0], F1, F2),
12296 getNode(ISD::AND, DL, VTList.VTs[1], NotF1, F2)},
12297 Flags);
12298 }
12299 }
12300 break;
12301 }
12302 case ISD::SADDO_CARRY:
12303 case ISD::UADDO_CARRY:
12304 case ISD::SSUBO_CARRY:
12305 case ISD::USUBO_CARRY:
12306 assert(VTList.NumVTs == 2 && Ops.size() == 3 &&
12307 "Invalid add/sub overflow op!");
12308 assert(VTList.VTs[0].isInteger() && VTList.VTs[1].isInteger() &&
12309 Ops[0].getValueType() == Ops[1].getValueType() &&
12310 Ops[0].getValueType() == VTList.VTs[0] &&
12311 Ops[2].getValueType() == VTList.VTs[1] &&
12312 "Binary operator types must match!");
12313 break;
12314 case ISD::SMUL_LOHI:
12315 case ISD::UMUL_LOHI: {
12316 assert(VTList.NumVTs == 2 && Ops.size() == 2 && "Invalid mul lo/hi op!");
12317 assert(VTList.VTs[0].isInteger() && VTList.VTs[0] == VTList.VTs[1] &&
12318 VTList.VTs[0] == Ops[0].getValueType() &&
12319 VTList.VTs[0] == Ops[1].getValueType() &&
12320 "Binary operator types must match!");
12321 break;
12322 }
12323 case ISD::FFREXP: {
12324 assert(VTList.NumVTs == 2 && Ops.size() == 1 && "Invalid ffrexp op!");
12325 assert(VTList.VTs[0].isFloatingPoint() && VTList.VTs[1].isInteger() &&
12326 VTList.VTs[0] == Ops[0].getValueType() && "frexp type mismatch");
12327
12329 int FrexpExp;
12330 APFloat FrexpMant =
12331 frexp(C->getValueAPF(), FrexpExp, APFloat::rmNearestTiesToEven);
12332 SDValue Result0 = getConstantFP(FrexpMant, DL, VTList.VTs[0]);
12333 SDValue Result1 = getSignedConstant(FrexpMant.isFinite() ? FrexpExp : 0,
12334 DL, VTList.VTs[1]);
12335 return getNode(ISD::MERGE_VALUES, DL, VTList, {Result0, Result1}, Flags);
12336 }
12337
12338 break;
12339 }
12341 assert(VTList.NumVTs == 2 && Ops.size() == 2 &&
12342 "Invalid STRICT_FP_EXTEND!");
12343 assert(VTList.VTs[0].isFloatingPoint() &&
12344 Ops[1].getValueType().isFloatingPoint() && "Invalid FP cast!");
12345 assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
12346 "STRICT_FP_EXTEND result type should be vector iff the operand "
12347 "type is vector!");
12348 assert((!VTList.VTs[0].isVector() ||
12349 VTList.VTs[0].getVectorElementCount() ==
12350 Ops[1].getValueType().getVectorElementCount()) &&
12351 "Vector element count mismatch!");
12352 assert(Ops[1].getValueType().bitsLT(VTList.VTs[0]) &&
12353 "Invalid fpext node, dst <= src!");
12354 break;
12356 assert(VTList.NumVTs == 2 && Ops.size() == 3 && "Invalid STRICT_FP_ROUND!");
12357 assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
12358 "STRICT_FP_ROUND result type should be vector iff the operand "
12359 "type is vector!");
12360 assert((!VTList.VTs[0].isVector() ||
12361 VTList.VTs[0].getVectorElementCount() ==
12362 Ops[1].getValueType().getVectorElementCount()) &&
12363 "Vector element count mismatch!");
12364 assert(VTList.VTs[0].isFloatingPoint() &&
12365 Ops[1].getValueType().isFloatingPoint() &&
12366 VTList.VTs[0].bitsLT(Ops[1].getValueType()) &&
12367 Ops[2].getOpcode() == ISD::TargetConstant &&
12368 (Ops[2]->getAsZExtVal() == 0 || Ops[2]->getAsZExtVal() == 1) &&
12369 "Invalid STRICT_FP_ROUND!");
12370 break;
12371 }
12372
12373 // Memoize the node unless it returns a glue result.
12374 SDNode *N;
12375 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
12376 SDNodeKey ID(Opcode, VTList, Ops);
12377 FoldingSetInsertToken InsertToken;
12378 if (SDNode *E = lookupNode(ID, DL, InsertToken)) {
12379 E->intersectFlagsWith(Flags);
12380 return SDValue(E, 0);
12381 }
12382
12383 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
12384 createOperands(N, Ops);
12385 CSEMap.insert(N, InsertToken);
12386 } else {
12387 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
12388 createOperands(N, Ops);
12389 }
12390
12391 N->setFlags(Flags);
12392 InsertNode(N);
12393 SDValue V(N, 0);
12394 NewSDValueDbgMsg(V, "Creating new node: ", this);
12395 return V;
12396}
12397
12398SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
12399 SDVTList VTList) {
12400 return getNode(Opcode, DL, VTList, ArrayRef<SDValue>());
12401}
12402
12403SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
12404 SDValue N1) {
12405 SDValue Ops[] = { N1 };
12406 return getNode(Opcode, DL, VTList, Ops);
12407}
12408
12409SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
12410 SDValue N1, SDValue N2) {
12411 SDValue Ops[] = { N1, N2 };
12412 return getNode(Opcode, DL, VTList, Ops);
12413}
12414
12415SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
12416 SDValue N1, SDValue N2, SDValue N3) {
12417 SDValue Ops[] = { N1, N2, N3 };
12418 return getNode(Opcode, DL, VTList, Ops);
12419}
12420
12421SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
12422 SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
12423 SDValue Ops[] = { N1, N2, N3, N4 };
12424 return getNode(Opcode, DL, VTList, Ops);
12425}
12426
12427SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
12428 SDValue N1, SDValue N2, SDValue N3, SDValue N4,
12429 SDValue N5) {
12430 SDValue Ops[] = { N1, N2, N3, N4, N5 };
12431 return getNode(Opcode, DL, VTList, Ops);
12432}
12433
12435 if (!VT.isExtended())
12436 return makeVTList(SDNode::getValueTypeList(VT.getSimpleVT()), 1);
12437
12438 EVT VTs[] = {VT};
12439 return getVTList(VTs);
12440}
12441
12443 EVT VTs[] = {VT1, VT2};
12444 return getVTList(VTs);
12445}
12446
12448 EVT VTs[] = {VT1, VT2, VT3};
12449 return getVTList(VTs);
12450}
12451
12453 EVT VTs[] = {VT1, VT2, VT3, VT4};
12454 return getVTList(VTs);
12455}
12456
12458 auto It = VTLists.find(VTs);
12459 if (It == VTLists.end()) {
12460 EVT *Array = Allocator.Allocate<EVT>(VTs.size());
12461 llvm::copy(VTs, Array);
12462 It = VTLists.insert(ArrayRef(Array, VTs.size())).first;
12463 }
12464 return makeVTList(It->data(), It->size());
12465}
12466
12467/// UpdateNodeOperands - *Mutate* the specified node in-place to have the
12468/// specified operands. If the resultant node already exists in the DAG,
12469/// this does not modify the specified node, instead it returns the node that
12470/// already exists. If the resultant node does not exist in the DAG, the
12471/// input node is returned. As a degenerate case, if you specify the same
12472/// input operands as the node already has, the input node is returned.
12474 assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
12475
12476 // Check to see if there is no change.
12477 if (Op == N->getOperand(0)) return N;
12478
12479 // See if the modified node already exists.
12480 FoldingSetInsertToken InsertToken;
12481 if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertToken))
12482 return Existing;
12483
12484 // Nope it doesn't. Remove the node from its current place in the maps.
12485 if (InsertToken)
12486 if (!RemoveNodeFromCSEMaps(N))
12487 InsertToken = {};
12488
12489 // Now we update the operands.
12490 N->OperandList[0].set(Op);
12491
12493 // If this gets put into a CSE map, add it.
12494 if (InsertToken)
12495 CSEMap.insert(N, InsertToken);
12496 return N;
12497}
12498
12500 assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
12501
12502 // Check to see if there is no change.
12503 if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
12504 return N; // No operands changed, just return the input node.
12505
12506 // See if the modified node already exists.
12507 FoldingSetInsertToken InsertToken;
12508 if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertToken))
12509 return Existing;
12510
12511 // Nope it doesn't. Remove the node from its current place in the maps.
12512 if (InsertToken)
12513 if (!RemoveNodeFromCSEMaps(N))
12514 InsertToken = {};
12515
12516 // Now we update the operands.
12517 if (N->OperandList[0] != Op1)
12518 N->OperandList[0].set(Op1);
12519 if (N->OperandList[1] != Op2)
12520 N->OperandList[1].set(Op2);
12521
12523 // If this gets put into a CSE map, add it.
12524 if (InsertToken)
12525 CSEMap.insert(N, InsertToken);
12526 return N;
12527}
12528
12531 SDValue Ops[] = { Op1, Op2, Op3 };
12532 return UpdateNodeOperands(N, Ops);
12533}
12534
12537 SDValue Op3, SDValue Op4) {
12538 SDValue Ops[] = { Op1, Op2, Op3, Op4 };
12539 return UpdateNodeOperands(N, Ops);
12540}
12541
12544 SDValue Op3, SDValue Op4, SDValue Op5) {
12545 SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 };
12546 return UpdateNodeOperands(N, Ops);
12547}
12548
12551 unsigned NumOps = Ops.size();
12552 assert(N->getNumOperands() == NumOps &&
12553 "Update with wrong number of operands");
12554
12555 // If no operands changed just return the input node.
12556 if (std::equal(Ops.begin(), Ops.end(), N->op_begin()))
12557 return N;
12558
12559 // See if the modified node already exists.
12560 FoldingSetInsertToken InsertToken;
12561 if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertToken))
12562 return Existing;
12563
12564 // Nope it doesn't. Remove the node from its current place in the maps.
12565 if (InsertToken)
12566 if (!RemoveNodeFromCSEMaps(N))
12567 InsertToken = {};
12568
12569 // Now we update the operands.
12570 for (unsigned i = 0; i != NumOps; ++i)
12571 if (N->OperandList[i] != Ops[i])
12572 N->OperandList[i].set(Ops[i]);
12573
12575 // If this gets put into a CSE map, add it.
12576 if (InsertToken)
12577 CSEMap.insert(N, InsertToken);
12578 return N;
12579}
12580
12581/// DropOperands - Release the operands and set this node to have
12582/// zero operands.
12584 // Unlike the code in MorphNodeTo that does this, we don't need to
12585 // watch for dead nodes here.
12586 for (op_iterator I = op_begin(), E = op_end(); I != E; ) {
12587 SDUse &Use = *I++;
12588 Use.set(SDValue());
12589 }
12590}
12591
12593 ArrayRef<MachineMemOperand *> NewMemRefs) {
12594 if (NewMemRefs.empty()) {
12595 N->clearMemRefs();
12596 return;
12597 }
12598
12599 // Check if we can avoid allocating by storing a single reference directly.
12600 if (NewMemRefs.size() == 1) {
12601 N->MemRefs = NewMemRefs[0];
12602 N->NumMemRefs = 1;
12603 return;
12604 }
12605
12606 MachineMemOperand **MemRefsBuffer =
12607 Allocator.template Allocate<MachineMemOperand *>(NewMemRefs.size());
12608 llvm::copy(NewMemRefs, MemRefsBuffer);
12609 N->MemRefs = MemRefsBuffer;
12610 N->NumMemRefs = static_cast<int>(NewMemRefs.size());
12611}
12612
12613/// SelectNodeTo - These are wrappers around MorphNodeTo that accept a
12614/// machine opcode.
12615///
12617 EVT VT) {
12618 SDVTList VTs = getVTList(VT);
12619 return SelectNodeTo(N, MachineOpc, VTs, {});
12620}
12621
12623 EVT VT, SDValue Op1) {
12624 SDVTList VTs = getVTList(VT);
12625 SDValue Ops[] = { Op1 };
12626 return SelectNodeTo(N, MachineOpc, VTs, Ops);
12627}
12628
12630 EVT VT, SDValue Op1,
12631 SDValue Op2) {
12632 SDVTList VTs = getVTList(VT);
12633 SDValue Ops[] = { Op1, Op2 };
12634 return SelectNodeTo(N, MachineOpc, VTs, Ops);
12635}
12636
12638 EVT VT, SDValue Op1,
12639 SDValue Op2, SDValue Op3) {
12640 SDVTList VTs = getVTList(VT);
12641 SDValue Ops[] = { Op1, Op2, Op3 };
12642 return SelectNodeTo(N, MachineOpc, VTs, Ops);
12643}
12644
12647 SDVTList VTs = getVTList(VT);
12648 return SelectNodeTo(N, MachineOpc, VTs, Ops);
12649}
12650
12652 EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) {
12653 SDVTList VTs = getVTList(VT1, VT2);
12654 return SelectNodeTo(N, MachineOpc, VTs, Ops);
12655}
12656
12658 EVT VT1, EVT VT2) {
12659 SDVTList VTs = getVTList(VT1, VT2);
12660 return SelectNodeTo(N, MachineOpc, VTs, {});
12661}
12662
12664 EVT VT1, EVT VT2, EVT VT3,
12666 SDVTList VTs = getVTList(VT1, VT2, VT3);
12667 return SelectNodeTo(N, MachineOpc, VTs, Ops);
12668}
12669
12671 EVT VT1, EVT VT2,
12672 SDValue Op1, SDValue Op2) {
12673 SDVTList VTs = getVTList(VT1, VT2);
12674 SDValue Ops[] = { Op1, Op2 };
12675 return SelectNodeTo(N, MachineOpc, VTs, Ops);
12676}
12677
12680 SDNode *New = MorphNodeTo(N, ~MachineOpc, VTs, Ops);
12681 // Reset the NodeID to -1.
12682 New->setNodeId(-1);
12683 if (New != N) {
12684 ReplaceAllUsesWith(N, New);
12686 }
12687 return New;
12688}
12689
12690/// UpdateSDLocOnMergeSDNode - If the opt level is -O0 then it throws away
12691/// the line number information on the merged node since it is not possible to
12692/// preserve the information that operation is associated with multiple lines.
12693/// This will make the debugger work better at -O0, where there is a higher
12694/// probability of having other instructions associated with that line.
12695///
12696/// For IROrder, we keep the smaller of the two
12697SDNode *SelectionDAG::UpdateSDLocOnMergeSDNode(SDNode *N, const SDLoc &OLoc) {
12698 DebugLoc NLoc = N->getDebugLoc();
12699 if (NLoc && OptLevel == CodeGenOptLevel::None && OLoc.getDebugLoc() != NLoc) {
12700 N->setDebugLoc(DebugLoc());
12701 }
12702 unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder());
12703 N->setIROrder(Order);
12704 return N;
12705}
12706
12707/// MorphNodeTo - This *mutates* the specified node to have the specified
12708/// return type, opcode, and operands.
12709///
12710/// Note that MorphNodeTo returns the resultant node. If there is already a
12711/// node of the specified opcode and operands, it returns that node instead of
12712/// the current one. Note that the SDLoc need not be the same.
12713///
12714/// Using MorphNodeTo is faster than creating a new node and swapping it in
12715/// with ReplaceAllUsesWith both because it often avoids allocating a new
12716/// node, and because it doesn't require CSE recalculation for any of
12717/// the node's users.
12718///
12719/// However, note that MorphNodeTo recursively deletes dead nodes from the DAG.
12720/// As a consequence it isn't appropriate to use from within the DAG combiner or
12721/// the legalizer which maintain worklists that would need to be updated when
12722/// deleting things.
12725 // If an identical node already exists, use it.
12726 FoldingSetInsertToken InsertToken;
12727 if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) {
12728 SDNodeKey ID(Opc, VTs, Ops);
12729 AddNodeIDCustom(ID.Tail, N, Opc);
12730 if (SDNode *ON = lookupNode(ID, SDLoc(N), InsertToken))
12731 return UpdateSDLocOnMergeSDNode(ON, SDLoc(N));
12732 }
12733
12734 if (!RemoveNodeFromCSEMaps(N))
12735 InsertToken = {};
12736
12737 // Start the morphing.
12738 N->NodeType = Opc;
12739 N->ValueList = VTs.VTs;
12740 N->NumValues = VTs.NumVTs;
12741
12742 // Clear the operands list, updating used nodes to remove this from their
12743 // use list. Keep track of any operands that become dead as a result.
12744 SmallPtrSet<SDNode*, 16> DeadNodeSet;
12745 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
12746 SDUse &Use = *I++;
12747 SDNode *Used = Use.getNode();
12748 Use.set(SDValue());
12749 if (Used->use_empty())
12750 DeadNodeSet.insert(Used);
12751 }
12752
12753 // For MachineNode, initialize the memory references information.
12755 MN->clearMemRefs();
12756
12757 // Swap for an appropriately sized array from the recycler.
12758 removeOperands(N);
12759 createOperands(N, Ops);
12760
12761 // Delete any nodes that are still dead after adding the uses for the
12762 // new operands.
12763 if (!DeadNodeSet.empty()) {
12764 SmallVector<SDNode *, 16> DeadNodes;
12765 for (SDNode *N : DeadNodeSet)
12766 if (N->use_empty())
12767 DeadNodes.push_back(N);
12768 RemoveDeadNodes(DeadNodes);
12769 }
12770
12771 if (InsertToken)
12772 CSEMap.insert(N, InsertToken); // Memoize the new node.
12773 return N;
12774}
12775
12777 unsigned OrigOpc = Node->getOpcode();
12778 unsigned NewOpc;
12779 switch (OrigOpc) {
12780 default:
12781 llvm_unreachable("mutateStrictFPToFP called with unexpected opcode!");
12782#define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \
12783 case ISD::STRICT_##DAGN: NewOpc = ISD::DAGN; break;
12784#define CMP_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \
12785 case ISD::STRICT_##DAGN: NewOpc = ISD::SETCC; break;
12786#include "llvm/IR/ConstrainedOps.def"
12787 }
12788
12789 assert(Node->getNumValues() == 2 && "Unexpected number of results!");
12790
12791 // We're taking this node out of the chain, so we need to re-link things.
12792 SDValue InputChain = Node->getOperand(0);
12793 SDValue OutputChain = SDValue(Node, 1);
12794 ReplaceAllUsesOfValueWith(OutputChain, InputChain);
12795
12797 for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
12798 Ops.push_back(Node->getOperand(i));
12799
12800 SDVTList VTs = getVTList(Node->getValueType(0));
12801 SDNode *Res = MorphNodeTo(Node, NewOpc, VTs, Ops);
12802
12803 // MorphNodeTo can operate in two ways: if an existing node with the
12804 // specified operands exists, it can just return it. Otherwise, it
12805 // updates the node in place to have the requested operands.
12806 if (Res == Node) {
12807 // If we updated the node in place, reset the node ID. To the isel,
12808 // this should be just like a newly allocated machine node.
12809 Res->setNodeId(-1);
12810 } else {
12813 }
12814
12815 return Res;
12816}
12817
12818/// getMachineNode - These are used for target selectors to create a new node
12819/// with specified return type(s), MachineInstr opcode, and operands.
12820///
12821/// Note that getMachineNode returns the resultant node. If there is already a
12822/// node of the specified opcode and operands, it returns that node instead of
12823/// the current one.
12825 EVT VT) {
12826 SDVTList VTs = getVTList(VT);
12827 return getMachineNode(Opcode, dl, VTs, {});
12828}
12829
12831 EVT VT, SDValue Op1) {
12832 SDVTList VTs = getVTList(VT);
12833 SDValue Ops[] = { Op1 };
12834 return getMachineNode(Opcode, dl, VTs, Ops);
12835}
12836
12838 EVT VT, SDValue Op1, SDValue Op2) {
12839 SDVTList VTs = getVTList(VT);
12840 SDValue Ops[] = { Op1, Op2 };
12841 return getMachineNode(Opcode, dl, VTs, Ops);
12842}
12843
12845 EVT VT, SDValue Op1, SDValue Op2,
12846 SDValue Op3) {
12847 SDVTList VTs = getVTList(VT);
12848 SDValue Ops[] = { Op1, Op2, Op3 };
12849 return getMachineNode(Opcode, dl, VTs, Ops);
12850}
12851
12854 SDVTList VTs = getVTList(VT);
12855 return getMachineNode(Opcode, dl, VTs, Ops);
12856}
12857
12859 EVT VT1, EVT VT2, SDValue Op1,
12860 SDValue Op2) {
12861 SDVTList VTs = getVTList(VT1, VT2);
12862 SDValue Ops[] = { Op1, Op2 };
12863 return getMachineNode(Opcode, dl, VTs, Ops);
12864}
12865
12867 EVT VT1, EVT VT2, SDValue Op1,
12868 SDValue Op2, SDValue Op3) {
12869 SDVTList VTs = getVTList(VT1, VT2);
12870 SDValue Ops[] = { Op1, Op2, Op3 };
12871 return getMachineNode(Opcode, dl, VTs, Ops);
12872}
12873
12875 EVT VT1, EVT VT2,
12877 SDVTList VTs = getVTList(VT1, VT2);
12878 return getMachineNode(Opcode, dl, VTs, Ops);
12879}
12880
12882 EVT VT1, EVT VT2, EVT VT3,
12883 SDValue Op1, SDValue Op2) {
12884 SDVTList VTs = getVTList(VT1, VT2, VT3);
12885 SDValue Ops[] = { Op1, Op2 };
12886 return getMachineNode(Opcode, dl, VTs, Ops);
12887}
12888
12890 EVT VT1, EVT VT2, EVT VT3,
12891 SDValue Op1, SDValue Op2,
12892 SDValue Op3) {
12893 SDVTList VTs = getVTList(VT1, VT2, VT3);
12894 SDValue Ops[] = { Op1, Op2, Op3 };
12895 return getMachineNode(Opcode, dl, VTs, Ops);
12896}
12897
12899 EVT VT1, EVT VT2, EVT VT3,
12901 SDVTList VTs = getVTList(VT1, VT2, VT3);
12902 return getMachineNode(Opcode, dl, VTs, Ops);
12903}
12904
12906 ArrayRef<EVT> ResultTys,
12908 SDVTList VTs = getVTList(ResultTys);
12909 return getMachineNode(Opcode, dl, VTs, Ops);
12910}
12911
12913 SDVTList VTs,
12915 bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue;
12917 FoldingSetInsertToken InsertToken;
12918
12919 if (DoCSE) {
12920 SDNodeKey ID(~Opcode, VTs, Ops);
12921 if (SDNode *E = lookupNode(ID, DL, InsertToken)) {
12922 return cast<MachineSDNode>(UpdateSDLocOnMergeSDNode(E, DL));
12923 }
12924 }
12925
12926 // Allocate a new MachineSDNode.
12927 N = newSDNode<MachineSDNode>(~Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
12928 createOperands(N, Ops);
12929
12930 if (DoCSE)
12931 CSEMap.insert(N, InsertToken);
12932
12933 InsertNode(N);
12934 NewSDValueDbgMsg(SDValue(N, 0), "Creating new machine node: ", this);
12935 return N;
12936}
12937
12938/// getTargetExtractSubreg - A convenience function for creating
12939/// TargetOpcode::EXTRACT_SUBREG nodes.
12941 SDValue Operand) {
12942 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
12943 SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,
12944 VT, Operand, SRIdxVal);
12945 return SDValue(Subreg, 0);
12946}
12947
12948/// getTargetInsertSubreg - A convenience function for creating
12949/// TargetOpcode::INSERT_SUBREG nodes.
12951 SDValue Operand, SDValue Subreg) {
12952 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
12953 SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL,
12954 VT, Operand, Subreg, SRIdxVal);
12955 return SDValue(Result, 0);
12956}
12957
12958/// getNodeIfExists - Get the specified node if it's already available, or
12959/// else return NULL.
12962 bool AllowCommute) {
12963 SDNodeFlags Flags;
12964 if (Inserter)
12965 Flags = Inserter->getFlags();
12966 return getNodeIfExists(Opcode, VTList, Ops, Flags, AllowCommute);
12967}
12968
12971 const SDNodeFlags Flags,
12972 bool AllowCommute) {
12973 if (VTList.VTs[VTList.NumVTs - 1] == MVT::Glue)
12974 return nullptr;
12975
12976 auto Lookup = [&](ArrayRef<SDValue> LookupOps) -> SDNode * {
12977 SDNodeKey ID(Opcode, VTList, LookupOps);
12978 FoldingSetInsertToken InsertToken;
12979 if (SDNode *E = lookupNode(ID, InsertToken)) {
12980 E->intersectFlagsWith(Flags);
12981 return E;
12982 }
12983 return nullptr;
12984 };
12985
12986 if (SDNode *Existing = Lookup(Ops))
12987 return Existing;
12988
12989 if (AllowCommute && TLI->isCommutativeBinOp(Opcode))
12990 return Lookup({Ops[1], Ops[0]});
12991
12992 return nullptr;
12993}
12994
12995/// doesNodeExist - Check if a node exists without modifying its flags.
12996bool SelectionDAG::doesNodeExist(unsigned Opcode, SDVTList VTList,
12998 if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
12999 SDNodeKey ID(Opcode, VTList, Ops);
13000 FoldingSetInsertToken InsertToken;
13001 if (lookupNode(ID, SDLoc(), InsertToken))
13002 return true;
13003 }
13004 return false;
13005}
13006
13007/// getDbgValue - Creates a SDDbgValue node.
13008///
13009/// SDNode
13011 SDNode *N, unsigned R, bool IsIndirect,
13012 const DebugLoc &DL, unsigned O) {
13013 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
13014 "Expected inlined-at fields to agree");
13015 return new (DbgInfo->getAlloc())
13016 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromNode(N, R),
13017 {}, IsIndirect, DL, O,
13018 /*IsVariadic=*/false);
13019}
13020
13021/// Constant
13023 DIExpression *Expr,
13024 const Value *C,
13025 const DebugLoc &DL, unsigned O) {
13026 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
13027 "Expected inlined-at fields to agree");
13028 return new (DbgInfo->getAlloc())
13029 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromConst(C), {},
13030 /*IsIndirect=*/false, DL, O,
13031 /*IsVariadic=*/false);
13032}
13033
13034/// FrameIndex
13036 DIExpression *Expr, unsigned FI,
13037 bool IsIndirect,
13038 const DebugLoc &DL,
13039 unsigned O) {
13040 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
13041 "Expected inlined-at fields to agree");
13042 return getFrameIndexDbgValue(Var, Expr, FI, {}, IsIndirect, DL, O);
13043}
13044
13045/// FrameIndex with dependencies
13047 DIExpression *Expr, unsigned FI,
13048 ArrayRef<SDNode *> Dependencies,
13049 bool IsIndirect,
13050 const DebugLoc &DL,
13051 unsigned O) {
13052 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
13053 "Expected inlined-at fields to agree");
13054 return new (DbgInfo->getAlloc())
13055 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromFrameIdx(FI),
13056 Dependencies, IsIndirect, DL, O,
13057 /*IsVariadic=*/false);
13058}
13059
13060/// VReg
13062 Register VReg, bool IsIndirect,
13063 const DebugLoc &DL, unsigned O) {
13064 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
13065 "Expected inlined-at fields to agree");
13066 return new (DbgInfo->getAlloc())
13067 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromVReg(VReg),
13068 {}, IsIndirect, DL, O,
13069 /*IsVariadic=*/false);
13070}
13071
13074 ArrayRef<SDNode *> Dependencies,
13075 bool IsIndirect, const DebugLoc &DL,
13076 unsigned O, bool IsVariadic) {
13077 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
13078 "Expected inlined-at fields to agree");
13079 return new (DbgInfo->getAlloc())
13080 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, Locs, Dependencies, IsIndirect,
13081 DL, O, IsVariadic);
13082}
13083
13085 unsigned OffsetInBits, unsigned SizeInBits,
13086 bool InvalidateDbg) {
13087 SDNode *FromNode = From.getNode();
13088 SDNode *ToNode = To.getNode();
13089 assert(FromNode && ToNode && "Can't modify dbg values");
13090
13091 // PR35338
13092 // TODO: assert(From != To && "Redundant dbg value transfer");
13093 // TODO: assert(FromNode != ToNode && "Intranode dbg value transfer");
13094 if (From == To || FromNode == ToNode)
13095 return;
13096
13097 if (!FromNode->getHasDebugValue())
13098 return;
13099
13100 SDDbgOperand FromLocOp =
13101 SDDbgOperand::fromNode(From.getNode(), From.getResNo());
13103
13105 for (SDDbgValue *Dbg : GetDbgValues(FromNode)) {
13106 if (Dbg->isInvalidated())
13107 continue;
13108
13109 // TODO: assert(!Dbg->isInvalidated() && "Transfer of invalid dbg value");
13110
13111 // Create a new location ops vector that is equal to the old vector, but
13112 // with each instance of FromLocOp replaced with ToLocOp.
13113 bool Changed = false;
13114 auto NewLocOps = Dbg->copyLocationOps();
13115 std::replace_if(
13116 NewLocOps.begin(), NewLocOps.end(),
13117 [&Changed, FromLocOp](const SDDbgOperand &Op) {
13118 bool Match = Op == FromLocOp;
13119 Changed |= Match;
13120 return Match;
13121 },
13122 ToLocOp);
13123 // Ignore this SDDbgValue if we didn't find a matching location.
13124 if (!Changed)
13125 continue;
13126
13127 DIVariable *Var = Dbg->getVariable();
13128 auto *Expr = Dbg->getExpression();
13129 // If a fragment is requested, update the expression.
13130 if (SizeInBits) {
13131 // When splitting a larger (e.g., sign-extended) value whose
13132 // lower bits are described with an SDDbgValue, do not attempt
13133 // to transfer the SDDbgValue to the upper bits.
13134 if (auto FI = Expr->getFragmentInfo())
13135 if (OffsetInBits + SizeInBits > FI->SizeInBits)
13136 continue;
13137 auto Fragment = DIExpression::createFragmentExpression(Expr, OffsetInBits,
13138 SizeInBits);
13139 if (!Fragment)
13140 continue;
13141 Expr = *Fragment;
13142 }
13143
13144 auto AdditionalDependencies = Dbg->getAdditionalDependencies();
13145 // Clone the SDDbgValue and move it to To.
13146 SDDbgValue *Clone = getDbgValueList(
13147 Var, Expr, NewLocOps, AdditionalDependencies, Dbg->isIndirect(),
13148 Dbg->getDebugLoc(), std::max(ToNode->getIROrder(), Dbg->getOrder()),
13149 Dbg->isVariadic());
13150 ClonedDVs.push_back(Clone);
13151
13152 if (InvalidateDbg) {
13153 // Invalidate value and indicate the SDDbgValue should not be emitted.
13154 Dbg->setIsInvalidated();
13155 Dbg->setIsEmitted();
13156 }
13157 }
13158
13159 for (SDDbgValue *Dbg : ClonedDVs) {
13160 assert(is_contained(Dbg->getSDNodes(), ToNode) &&
13161 "Transferred DbgValues should depend on the new SDNode");
13162 AddDbgValue(Dbg, false);
13163 }
13164}
13165
13167 if (!N.getHasDebugValue())
13168 return;
13169
13170 auto GetLocationOperand = [](SDNode *Node, unsigned ResNo) {
13171 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(Node))
13172 return SDDbgOperand::fromFrameIdx(FISDN->getIndex());
13173 return SDDbgOperand::fromNode(Node, ResNo);
13174 };
13175
13177 for (auto *DV : GetDbgValues(&N)) {
13178 if (DV->isInvalidated())
13179 continue;
13180 switch (N.getOpcode()) {
13181 default:
13182 break;
13183 case ISD::ADD: {
13184 SDValue N0 = N.getOperand(0);
13185 SDValue N1 = N.getOperand(1);
13186 if (!isa<ConstantSDNode>(N0)) {
13187 bool RHSConstant = isa<ConstantSDNode>(N1);
13188 uint64_t Offset;
13189 if (RHSConstant)
13190 Offset = N.getConstantOperandVal(1);
13191 // We are not allowed to turn indirect debug values variadic, so
13192 // don't salvage those.
13193 if (!RHSConstant && DV->isIndirect())
13194 continue;
13195
13196 // Rewrite an ADD constant node into a DIExpression. Since we are
13197 // performing arithmetic to compute the variable's *value* in the
13198 // DIExpression, we need to mark the expression with a
13199 // DW_OP_stack_value.
13200 auto *DIExpr = DV->getExpression();
13201 auto NewLocOps = DV->copyLocationOps();
13202 bool Changed = false;
13203 size_t OrigLocOpsSize = NewLocOps.size();
13204 for (size_t i = 0; i < OrigLocOpsSize; ++i) {
13205 // We're not given a ResNo to compare against because the whole
13206 // node is going away. We know that any ISD::ADD only has one
13207 // result, so we can assume any node match is using the result.
13208 if (NewLocOps[i].getKind() != SDDbgOperand::SDNODE ||
13209 NewLocOps[i].getSDNode() != &N)
13210 continue;
13211 NewLocOps[i] = GetLocationOperand(N0.getNode(), N0.getResNo());
13212 if (RHSConstant) {
13215 DIExpr = DIExpression::appendOpsToArg(DIExpr, ExprOps, i, true);
13216 } else {
13217 // Convert to a variadic expression (if not already).
13218 // convertToVariadicExpression() returns a const pointer, so we use
13219 // a temporary const variable here.
13220 const auto *TmpDIExpr =
13224 ExprOps.push_back(NewLocOps.size());
13225 ExprOps.push_back(dwarf::DW_OP_plus);
13226 SDDbgOperand RHS =
13228 NewLocOps.push_back(RHS);
13229 DIExpr = DIExpression::appendOpsToArg(TmpDIExpr, ExprOps, i, true);
13230 }
13231 Changed = true;
13232 }
13233 (void)Changed;
13234 assert(Changed && "Salvage target doesn't use N");
13235
13236 bool IsVariadic =
13237 DV->isVariadic() || OrigLocOpsSize != NewLocOps.size();
13238
13239 auto AdditionalDependencies = DV->getAdditionalDependencies();
13240 SDDbgValue *Clone = getDbgValueList(
13241 DV->getVariable(), DIExpr, NewLocOps, AdditionalDependencies,
13242 DV->isIndirect(), DV->getDebugLoc(), DV->getOrder(), IsVariadic);
13243 ClonedDVs.push_back(Clone);
13244 DV->setIsInvalidated();
13245 DV->setIsEmitted();
13246 LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting";
13247 N0.getNode()->dumprFull(this);
13248 dbgs() << " into " << *DIExpr << '\n');
13249 }
13250 break;
13251 }
13252 case ISD::TRUNCATE: {
13253 SDValue N0 = N.getOperand(0);
13254 TypeSize FromSize = N0.getValueSizeInBits();
13255 TypeSize ToSize = N.getValueSizeInBits(0);
13256
13257 DIExpression *DbgExpression = DV->getExpression();
13258 auto ExtOps = DIExpression::getExtOps(FromSize, ToSize, false);
13259 auto NewLocOps = DV->copyLocationOps();
13260 bool Changed = false;
13261 for (size_t i = 0; i < NewLocOps.size(); ++i) {
13262 if (NewLocOps[i].getKind() != SDDbgOperand::SDNODE ||
13263 NewLocOps[i].getSDNode() != &N)
13264 continue;
13265
13266 NewLocOps[i] = GetLocationOperand(N0.getNode(), N0.getResNo());
13267 DbgExpression = DIExpression::appendOpsToArg(DbgExpression, ExtOps, i);
13268 Changed = true;
13269 }
13270 assert(Changed && "Salvage target doesn't use N");
13271 (void)Changed;
13272
13273 SDDbgValue *Clone =
13274 getDbgValueList(DV->getVariable(), DbgExpression, NewLocOps,
13275 DV->getAdditionalDependencies(), DV->isIndirect(),
13276 DV->getDebugLoc(), DV->getOrder(), DV->isVariadic());
13277
13278 ClonedDVs.push_back(Clone);
13279 DV->setIsInvalidated();
13280 DV->setIsEmitted();
13281 LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting"; N0.getNode()->dumprFull(this);
13282 dbgs() << " into " << *DbgExpression << '\n');
13283 break;
13284 }
13285 }
13286 }
13287
13288 for (SDDbgValue *Dbg : ClonedDVs) {
13289 assert((!Dbg->getSDNodes().empty() ||
13290 llvm::any_of(Dbg->getLocationOps(),
13291 [&](const SDDbgOperand &Op) {
13292 return Op.getKind() == SDDbgOperand::FRAMEIX;
13293 })) &&
13294 "Salvaged DbgValue should depend on a new SDNode");
13295 AddDbgValue(Dbg, false);
13296 }
13297}
13298
13299/// Creates a SDDbgLabel node.
13301 const DebugLoc &DL, unsigned O) {
13302 assert(cast<DILabel>(Label)->isValidLocationForIntrinsic(DL) &&
13303 "Expected inlined-at fields to agree");
13304 return new (DbgInfo->getAlloc()) SDDbgLabel(Label, DL, O);
13305}
13306
13307namespace {
13308
13309/// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node
13310/// pointed to by a use iterator is deleted, increment the use iterator
13311/// so that it doesn't dangle.
13312///
13313class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener {
13316
13317 void NodeDeleted(SDNode *N, SDNode *E) override {
13318 // Increment the iterator as needed.
13319 while (UI != UE && N == UI->getUser())
13320 ++UI;
13321 }
13322
13323public:
13324 RAUWUpdateListener(SelectionDAG &d,
13327 : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {}
13328};
13329
13330} // end anonymous namespace
13331
13332/// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
13333/// This can cause recursive merging of nodes in the DAG.
13334///
13335/// This version assumes From has a single result value.
13336///
13338 SDNode *From = FromN.getNode();
13339 assert(From->getNumValues() == 1 && FromN.getResNo() == 0 &&
13340 "Cannot replace with this method!");
13341 assert(From != To.getNode() && "Cannot replace uses of with self");
13342
13343 // Preserve Debug Values
13344 transferDbgValues(FromN, To);
13345 // Preserve extra info.
13346 copyExtraInfo(From, To.getNode());
13347
13348 // Iterate over all the existing uses of From. New uses will be added
13349 // to the beginning of the use list, which we avoid visiting.
13350 // This specifically avoids visiting uses of From that arise while the
13351 // replacement is happening, because any such uses would be the result
13352 // of CSE: If an existing node looks like From after one of its operands
13353 // is replaced by To, we don't want to replace of all its users with To
13354 // too. See PR3018 for more info.
13355 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
13356 RAUWUpdateListener Listener(*this, UI, UE);
13357 while (UI != UE) {
13358 SDNode *User = UI->getUser();
13359
13360 // This node is about to morph, remove its old self from the CSE maps.
13361 RemoveNodeFromCSEMaps(User);
13362
13363 // A user can appear in a use list multiple times, and when this
13364 // happens the uses are usually next to each other in the list.
13365 // To help reduce the number of CSE recomputations, process all
13366 // the uses of this user that we can find this way.
13367 do {
13368 SDUse &Use = *UI;
13369 ++UI;
13370 Use.set(To);
13371 if (To->isDivergent() != From->isDivergent())
13373 } while (UI != UE && UI->getUser() == User);
13374 // Now that we have modified User, add it back to the CSE maps. If it
13375 // already exists there, recursively merge the results together.
13376 AddModifiedNodeToCSEMaps(User);
13377 }
13378
13379 // If we just RAUW'd the root, take note.
13380 if (FromN == getRoot())
13381 setRoot(To);
13382}
13383
13384/// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
13385/// This can cause recursive merging of nodes in the DAG.
13386///
13387/// This version assumes that for each value of From, there is a
13388/// corresponding value in To in the same position with the same type.
13389///
13391#ifndef NDEBUG
13392 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
13393 assert((!From->hasAnyUseOfValue(i) ||
13394 From->getValueType(i) == To->getValueType(i)) &&
13395 "Cannot use this version of ReplaceAllUsesWith!");
13396#endif
13397
13398 // Handle the trivial case.
13399 if (From == To)
13400 return;
13401
13402 // Preserve Debug Info. Only do this if there's a use.
13403 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
13404 if (From->hasAnyUseOfValue(i)) {
13405 assert((i < To->getNumValues()) && "Invalid To location");
13406 transferDbgValues(SDValue(From, i), SDValue(To, i));
13407 }
13408 // Preserve extra info.
13409 copyExtraInfo(From, To);
13410
13411 // Iterate over just the existing users of From. See the comments in
13412 // the ReplaceAllUsesWith above.
13413 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
13414 RAUWUpdateListener Listener(*this, UI, UE);
13415 while (UI != UE) {
13416 SDNode *User = UI->getUser();
13417
13418 // This node is about to morph, remove its old self from the CSE maps.
13419 RemoveNodeFromCSEMaps(User);
13420
13421 // A user can appear in a use list multiple times, and when this
13422 // happens the uses are usually next to each other in the list.
13423 // To help reduce the number of CSE recomputations, process all
13424 // the uses of this user that we can find this way.
13425 do {
13426 SDUse &Use = *UI;
13427 ++UI;
13428 Use.setNode(To);
13429 if (To->isDivergent() != From->isDivergent())
13431 } while (UI != UE && UI->getUser() == User);
13432
13433 // Now that we have modified User, add it back to the CSE maps. If it
13434 // already exists there, recursively merge the results together.
13435 AddModifiedNodeToCSEMaps(User);
13436 }
13437
13438 // If we just RAUW'd the root, take note.
13439 if (From == getRoot().getNode())
13440 setRoot(SDValue(To, getRoot().getResNo()));
13441}
13442
13443/// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
13444/// This can cause recursive merging of nodes in the DAG.
13445///
13446/// This version can replace From with any result values. To must match the
13447/// number and types of values returned by From.
13449 if (From->getNumValues() == 1) // Handle the simple case efficiently.
13450 return ReplaceAllUsesWith(SDValue(From, 0), To[0]);
13451
13452 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) {
13453 // Preserve Debug Info.
13454 transferDbgValues(SDValue(From, i), To[i]);
13455 // Preserve extra info.
13456 copyExtraInfo(From, To[i].getNode());
13457 }
13458
13459 // Iterate over just the existing users of From. See the comments in
13460 // the ReplaceAllUsesWith above.
13461 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
13462 RAUWUpdateListener Listener(*this, UI, UE);
13463 while (UI != UE) {
13464 SDNode *User = UI->getUser();
13465
13466 // This node is about to morph, remove its old self from the CSE maps.
13467 RemoveNodeFromCSEMaps(User);
13468
13469 // A user can appear in a use list multiple times, and when this happens the
13470 // uses are usually next to each other in the list. To help reduce the
13471 // number of CSE and divergence recomputations, process all the uses of this
13472 // user that we can find this way.
13473 bool To_IsDivergent = false;
13474 do {
13475 SDUse &Use = *UI;
13476 const SDValue &ToOp = To[Use.getResNo()];
13477 ++UI;
13478 Use.set(ToOp);
13479 if (ToOp.getValueType() != MVT::Other)
13480 To_IsDivergent |= ToOp->isDivergent();
13481 } while (UI != UE && UI->getUser() == User);
13482
13483 if (To_IsDivergent != From->isDivergent())
13485
13486 // Now that we have modified User, add it back to the CSE maps. If it
13487 // already exists there, recursively merge the results together.
13488 AddModifiedNodeToCSEMaps(User);
13489 }
13490
13491 // If we just RAUW'd the root, take note.
13492 if (From == getRoot().getNode())
13493 setRoot(SDValue(To[getRoot().getResNo()]));
13494}
13495
13496/// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
13497/// uses of other values produced by From.getNode() alone. The Deleted
13498/// vector is handled the same way as for ReplaceAllUsesWith.
13500 // Handle the really simple, really trivial case efficiently.
13501 if (From == To) return;
13502
13503 // Handle the simple, trivial, case efficiently.
13504 if (From.getNode()->getNumValues() == 1) {
13505 ReplaceAllUsesWith(From, To);
13506 return;
13507 }
13508
13509 // Preserve Debug Info.
13510 transferDbgValues(From, To);
13511 copyExtraInfo(From.getNode(), To.getNode());
13512
13513 // Iterate over just the existing users of From. See the comments in
13514 // the ReplaceAllUsesWith above.
13515 SDNode::use_iterator UI = From.getNode()->use_begin(),
13516 UE = From.getNode()->use_end();
13517 RAUWUpdateListener Listener(*this, UI, UE);
13518 while (UI != UE) {
13519 SDNode *User = UI->getUser();
13520 bool UserRemovedFromCSEMaps = false;
13521
13522 // A user can appear in a use list multiple times, and when this
13523 // happens the uses are usually next to each other in the list.
13524 // To help reduce the number of CSE recomputations, process all
13525 // the uses of this user that we can find this way.
13526 do {
13527 SDUse &Use = *UI;
13528
13529 // Skip uses of different values from the same node.
13530 if (Use.getResNo() != From.getResNo()) {
13531 ++UI;
13532 continue;
13533 }
13534
13535 // If this node hasn't been modified yet, it's still in the CSE maps,
13536 // so remove its old self from the CSE maps.
13537 if (!UserRemovedFromCSEMaps) {
13538 RemoveNodeFromCSEMaps(User);
13539 UserRemovedFromCSEMaps = true;
13540 }
13541
13542 ++UI;
13543 Use.set(To);
13544 if (To->isDivergent() != From->isDivergent())
13546 } while (UI != UE && UI->getUser() == User);
13547 // We are iterating over all uses of the From node, so if a use
13548 // doesn't use the specific value, no changes are made.
13549 if (!UserRemovedFromCSEMaps)
13550 continue;
13551
13552 // Now that we have modified User, add it back to the CSE maps. If it
13553 // already exists there, recursively merge the results together.
13554 AddModifiedNodeToCSEMaps(User);
13555 }
13556
13557 // If we just RAUW'd the root, take note.
13558 if (From == getRoot())
13559 setRoot(To);
13560}
13561
13562namespace {
13563
13564/// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith
13565/// to record information about a use.
13566struct UseMemo {
13567 SDNode *User;
13568 unsigned Index;
13569 SDUse *Use;
13570};
13571
13572/// operator< - Sort Memos by User.
13573bool operator<(const UseMemo &L, const UseMemo &R) {
13574 return (intptr_t)L.User < (intptr_t)R.User;
13575}
13576
13577/// RAUOVWUpdateListener - Helper for ReplaceAllUsesOfValuesWith - When the node
13578/// pointed to by a UseMemo is deleted, set the User to nullptr to indicate that
13579/// the node already has been taken care of recursively.
13580class RAUOVWUpdateListener : public SelectionDAG::DAGUpdateListener {
13581 SmallVectorImpl<UseMemo> &Uses;
13582
13583 void NodeDeleted(SDNode *N, SDNode *E) override {
13584 for (UseMemo &Memo : Uses)
13585 if (Memo.User == N)
13586 Memo.User = nullptr;
13587 }
13588
13589public:
13590 RAUOVWUpdateListener(SelectionDAG &d, SmallVectorImpl<UseMemo> &uses)
13591 : SelectionDAG::DAGUpdateListener(d), Uses(uses) {}
13592};
13593
13594} // end anonymous namespace
13595
13596/// Return true if a glue output should propagate divergence information.
13598 switch (Node->getOpcode()) {
13599 case ISD::CopyFromReg:
13600 case ISD::CopyToReg:
13601 return false;
13602 default:
13603 return true;
13604 }
13605
13606 llvm_unreachable("covered opcode switch");
13607}
13608
13610 if (TLI->isSDNodeAlwaysUniform(N)) {
13611 assert(!TLI->isSDNodeSourceOfDivergence(N, FLI, UA) &&
13612 "Conflicting divergence information!");
13613 return false;
13614 }
13615 if (TLI->isSDNodeSourceOfDivergence(N, FLI, UA))
13616 return true;
13617 for (const auto &Op : N->ops()) {
13618 EVT VT = Op.getValueType();
13619
13620 // Skip Chain. It does not carry divergence.
13621 if (VT != MVT::Other && Op.getNode()->isDivergent() &&
13622 (VT != MVT::Glue || gluePropagatesDivergence(Op.getNode())))
13623 return true;
13624 }
13625 return false;
13626}
13627
13629 SmallVector<SDNode *, 16> Worklist(1, N);
13630 do {
13631 N = Worklist.pop_back_val();
13632 bool IsDivergent = calculateDivergence(N);
13633 if (N->SDNodeBits.IsDivergent != IsDivergent) {
13634 N->SDNodeBits.IsDivergent = IsDivergent;
13635 llvm::append_range(Worklist, N->users());
13636 }
13637 } while (!Worklist.empty());
13638}
13639
13640void SelectionDAG::CreateTopologicalOrder(std::vector<SDNode *> &Order) {
13642 Order.reserve(AllNodes.size());
13643 for (auto &N : allnodes()) {
13644 unsigned NOps = N.getNumOperands();
13645 Degree[&N] = NOps;
13646 if (0 == NOps)
13647 Order.push_back(&N);
13648 }
13649 for (size_t I = 0; I != Order.size(); ++I) {
13650 SDNode *N = Order[I];
13651 for (auto *U : N->users()) {
13652 unsigned &UnsortedOps = Degree[U];
13653 if (0 == --UnsortedOps)
13654 Order.push_back(U);
13655 }
13656 }
13657}
13658
13659#if !defined(NDEBUG) && LLVM_ENABLE_ABI_BREAKING_CHECKS
13660void SelectionDAG::VerifyDAGDivergence() {
13661 std::vector<SDNode *> TopoOrder;
13662 CreateTopologicalOrder(TopoOrder);
13663 for (auto *N : TopoOrder) {
13664 assert(calculateDivergence(N) == N->isDivergent() &&
13665 "Divergence bit inconsistency detected");
13666 }
13667}
13668#endif
13669
13670/// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving
13671/// uses of other values produced by From.getNode() alone. The same value
13672/// may appear in both the From and To list. The Deleted vector is
13673/// handled the same way as for ReplaceAllUsesWith.
13675 const SDValue *To,
13676 unsigned Num){
13677 // Handle the simple, trivial case efficiently.
13678 if (Num == 1)
13679 return ReplaceAllUsesOfValueWith(*From, *To);
13680
13681 transferDbgValues(*From, *To);
13682 copyExtraInfo(From->getNode(), To->getNode());
13683
13684 // Read up all the uses and make records of them. This helps
13685 // processing new uses that are introduced during the
13686 // replacement process.
13688 for (unsigned i = 0; i != Num; ++i) {
13689 unsigned FromResNo = From[i].getResNo();
13690 SDNode *FromNode = From[i].getNode();
13691 for (SDUse &Use : FromNode->uses()) {
13692 if (Use.getResNo() == FromResNo) {
13693 UseMemo Memo = {Use.getUser(), i, &Use};
13694 Uses.push_back(Memo);
13695 }
13696 }
13697 }
13698
13699 // Sort the uses, so that all the uses from a given User are together.
13701 RAUOVWUpdateListener Listener(*this, Uses);
13702
13703 for (unsigned UseIndex = 0, UseIndexEnd = Uses.size();
13704 UseIndex != UseIndexEnd; ) {
13705 // We know that this user uses some value of From. If it is the right
13706 // value, update it.
13707 SDNode *User = Uses[UseIndex].User;
13708 // If the node has been deleted by recursive CSE updates when updating
13709 // another node, then just skip this entry.
13710 if (User == nullptr) {
13711 ++UseIndex;
13712 continue;
13713 }
13714
13715 // This node is about to morph, remove its old self from the CSE maps.
13716 RemoveNodeFromCSEMaps(User);
13717
13718 // The Uses array is sorted, so all the uses for a given User
13719 // are next to each other in the list.
13720 // To help reduce the number of CSE recomputations, process all
13721 // the uses of this user that we can find this way.
13722 do {
13723 unsigned i = Uses[UseIndex].Index;
13724 SDUse &Use = *Uses[UseIndex].Use;
13725 ++UseIndex;
13726
13727 Use.set(To[i]);
13728 } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User);
13729
13730 // Now that we have modified User, add it back to the CSE maps. If it
13731 // already exists there, recursively merge the results together.
13732 AddModifiedNodeToCSEMaps(User);
13733 }
13734}
13735
13736/// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
13737/// based on their topological order. It returns the maximum id and a vector
13738/// of the SDNodes* in assigned order by reference.
13740 unsigned DAGSize = 0;
13741
13742 // SortedPos tracks the progress of the algorithm. Nodes before it are
13743 // sorted, nodes after it are unsorted. When the algorithm completes
13744 // it is at the end of the list.
13745 allnodes_iterator SortedPos = allnodes_begin();
13746
13747 // Visit all the nodes. Move nodes with no operands to the front of
13748 // the list immediately. Annotate nodes that do have operands with their
13749 // operand count. Before we do this, the Node Id fields of the nodes
13750 // may contain arbitrary values. After, the Node Id fields for nodes
13751 // before SortedPos will contain the topological sort index, and the
13752 // Node Id fields for nodes At SortedPos and after will contain the
13753 // count of outstanding operands.
13755 checkForCycles(&N, this);
13756 unsigned Degree = N.getNumOperands();
13757 if (Degree == 0) {
13758 // A node with no uses, add it to the result array immediately.
13759 N.setNodeId(DAGSize++);
13760 allnodes_iterator Q(&N);
13761 if (Q != SortedPos)
13762 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q));
13763 assert(SortedPos != AllNodes.end() && "Overran node list");
13764 ++SortedPos;
13765 } else {
13766 // Temporarily use the Node Id as scratch space for the degree count.
13767 N.setNodeId(Degree);
13768 }
13769 }
13770
13771 // Visit all the nodes. As we iterate, move nodes into sorted order,
13772 // such that by the time the end is reached all nodes will be sorted.
13773 for (SDNode &Node : allnodes()) {
13774 SDNode *N = &Node;
13775 checkForCycles(N, this);
13776 // N is in sorted position, so all its uses have one less operand
13777 // that needs to be sorted.
13778 for (SDNode *P : N->users()) {
13779 unsigned Degree = P->getNodeId();
13780 assert(Degree != 0 && "Invalid node degree");
13781 --Degree;
13782 if (Degree == 0) {
13783 // All of P's operands are sorted, so P may sorted now.
13784 P->setNodeId(DAGSize++);
13785 if (P->getIterator() != SortedPos)
13786 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P));
13787 assert(SortedPos != AllNodes.end() && "Overran node list");
13788 ++SortedPos;
13789 } else {
13790 // Update P's outstanding operand count.
13791 P->setNodeId(Degree);
13792 }
13793 }
13794 if (Node.getIterator() == SortedPos) {
13795#ifndef NDEBUG
13797 SDNode *S = &*++I;
13798 dbgs() << "Overran sorted position:\n";
13799 S->dumprFull(this); dbgs() << "\n";
13800 dbgs() << "Checking if this is due to cycles\n";
13801 checkForCycles(this, true);
13802#endif
13803 llvm_unreachable(nullptr);
13804 }
13805 }
13806
13807 assert(SortedPos == AllNodes.end() &&
13808 "Topological sort incomplete!");
13809 assert(AllNodes.front().getOpcode() == ISD::EntryToken &&
13810 "First node in topological sort is not the entry token!");
13811 assert(AllNodes.front().getNodeId() == 0 &&
13812 "First node in topological sort has non-zero id!");
13813 assert(AllNodes.front().getNumOperands() == 0 &&
13814 "First node in topological sort has operands!");
13815 assert(AllNodes.back().getNodeId() == (int)DAGSize-1 &&
13816 "Last node in topologic sort has unexpected id!");
13817 assert(AllNodes.back().use_empty() &&
13818 "Last node in topologic sort has users!");
13819 assert(DAGSize == allnodes_size() && "Node count mismatch!");
13820 return DAGSize;
13821}
13822
13824 SmallVectorImpl<const SDNode *> &SortedNodes) const {
13825 SortedNodes.clear();
13826 // Node -> remaining number of outstanding operands.
13827 DenseMap<const SDNode *, unsigned> RemainingOperands;
13828
13829 // Put nodes without any operands into SortedNodes first.
13830 for (const SDNode &N : allnodes()) {
13831 checkForCycles(&N, this);
13832 unsigned NumOperands = N.getNumOperands();
13833 if (NumOperands == 0)
13834 SortedNodes.push_back(&N);
13835 else
13836 // Record their total number of outstanding operands.
13837 RemainingOperands[&N] = NumOperands;
13838 }
13839
13840 // A node is pushed into SortedNodes when all of its operands (predecessors in
13841 // the graph) are also in SortedNodes.
13842 for (unsigned i = 0U; i < SortedNodes.size(); ++i) {
13843 const SDNode *N = SortedNodes[i];
13844 for (const SDNode *U : N->users()) {
13845 // HandleSDNode is never part of a DAG and therefore has no entry in
13846 // RemainingOperands.
13847 if (U->getOpcode() == ISD::HANDLENODE)
13848 continue;
13849 unsigned &NumRemOperands = RemainingOperands[U];
13850 assert(NumRemOperands && "Invalid number of remaining operands");
13851 --NumRemOperands;
13852 if (!NumRemOperands)
13853 SortedNodes.push_back(U);
13854 }
13855 }
13856
13857 assert(SortedNodes.size() == AllNodes.size() && "Node count mismatch");
13858 assert(SortedNodes.front()->getOpcode() == ISD::EntryToken &&
13859 "First node in topological sort is not the entry token");
13860 assert(SortedNodes.front()->getNumOperands() == 0 &&
13861 "First node in topological sort has operands");
13862}
13863
13864/// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the
13865/// value is produced by SD.
13866void SelectionDAG::AddDbgValue(SDDbgValue *DB, bool isParameter) {
13867 for (SDNode *SD : DB->getSDNodes()) {
13868 if (!SD)
13869 continue;
13870 assert(DbgInfo->getSDDbgValues(SD).empty() || SD->getHasDebugValue());
13871 SD->setHasDebugValue(true);
13872 }
13873 DbgInfo->add(DB, isParameter);
13874}
13875
13876void SelectionDAG::AddDbgLabel(SDDbgLabel *DB) { DbgInfo->add(DB); }
13877
13879 SDValue NewMemOpChain) {
13880 assert(isa<MemSDNode>(NewMemOpChain) && "Expected a memop node");
13881 assert(NewMemOpChain.getValueType() == MVT::Other && "Expected a token VT");
13882 // The new memory operation must have the same position as the old load in
13883 // terms of memory dependency. Create a TokenFactor for the old load and new
13884 // memory operation and update uses of the old load's output chain to use that
13885 // TokenFactor.
13886 if (OldChain == NewMemOpChain || OldChain.use_empty())
13887 return NewMemOpChain;
13888
13889 SDValue TokenFactor = getNode(ISD::TokenFactor, SDLoc(OldChain), MVT::Other,
13890 OldChain, NewMemOpChain);
13891 ReplaceAllUsesOfValueWith(OldChain, TokenFactor);
13892 UpdateNodeOperands(TokenFactor.getNode(), OldChain, NewMemOpChain);
13893 return TokenFactor;
13894}
13895
13897 SDValue NewMemOp) {
13898 assert(isa<MemSDNode>(NewMemOp.getNode()) && "Expected a memop node");
13899 SDValue OldChain = SDValue(OldLoad, 1);
13900 SDValue NewMemOpChain = NewMemOp.getValue(1);
13901 return makeEquivalentMemoryOrdering(OldChain, NewMemOpChain);
13902}
13903
13905 Function **OutFunction) {
13906 assert(isa<ExternalSymbolSDNode>(Op) && "Node should be an ExternalSymbol");
13907
13908 auto *Symbol = cast<ExternalSymbolSDNode>(Op)->getSymbol();
13909 auto *Module = MF->getFunction().getParent();
13910 auto *Function = Module->getFunction(Symbol);
13911
13912 if (OutFunction != nullptr)
13913 *OutFunction = Function;
13914
13915 if (Function != nullptr) {
13916 auto PtrTy = TLI->getPointerTy(getDataLayout(), Function->getAddressSpace());
13917 return getGlobalAddress(Function, SDLoc(Op), PtrTy);
13918 }
13919
13920 std::string ErrorStr;
13921 raw_string_ostream ErrorFormatter(ErrorStr);
13922 ErrorFormatter << "Undefined external symbol ";
13923 ErrorFormatter << '"' << Symbol << '"';
13924 report_fatal_error(Twine(ErrorStr));
13925}
13926
13927//===----------------------------------------------------------------------===//
13928// SDNode Class
13929//===----------------------------------------------------------------------===//
13930
13933 return Const != nullptr && Const->isZero();
13934}
13935
13937 return V.isUndef() || isNullConstant(V);
13938}
13939
13942 return Const != nullptr && Const->isZero() && !Const->isNegative();
13943}
13944
13947 return Const != nullptr && Const->isAllOnes();
13948}
13949
13952 return Const != nullptr && Const->isOne();
13953}
13954
13957 return Const != nullptr && Const->isMinSignedValue();
13958}
13959
13961 SDValue V, unsigned OperandNo,
13962 unsigned Depth) const {
13963 APInt DemandedElts = getDemandAllEltsMask(V);
13964 return isIdentityElement(Opcode, Flags, V, DemandedElts, OperandNo, Depth);
13965}
13966
13968 SDValue V, const APInt &DemandedElts,
13969 unsigned OperandNo, unsigned Depth) const {
13970 // NOTE: The cases should match with IR's ConstantExpr::getBinOpIdentity().
13971 // TODO: Target-specific opcodes could be added.
13972 if (V.getValueType().isInteger()) {
13973 KnownBits Known = computeKnownBits(V, DemandedElts, Depth);
13974 if (Known.isConstant()) {
13975 const APInt &Const = Known.getConstant();
13976 switch (Opcode) {
13977 case ISD::ADD:
13978 case ISD::OR:
13979 case ISD::XOR:
13980 case ISD::UMAX:
13981 return Const.isZero();
13982 case ISD::MUL:
13983 return Const.isOne();
13984 case ISD::AND:
13985 case ISD::UMIN:
13986 return Const.isAllOnes();
13987 case ISD::SMAX:
13988 return Const.isMinSignedValue();
13989 case ISD::SMIN:
13990 return Const.isMaxSignedValue();
13991 case ISD::SUB:
13992 case ISD::SHL:
13993 case ISD::SRA:
13994 case ISD::SRL:
13995 return OperandNo == 1 && Const.isZero();
13996 case ISD::UDIV:
13997 case ISD::SDIV:
13998 return OperandNo == 1 && Const.isOne();
13999 }
14000 }
14001 } else if (auto *ConstFP = isConstOrConstSplatFP(V, DemandedElts)) {
14002 switch (Opcode) {
14003 case ISD::FADD:
14004 return ConstFP->isZero() &&
14005 (Flags.hasNoSignedZeros() || ConstFP->isNegative());
14006 case ISD::FSUB:
14007 return OperandNo == 1 && ConstFP->isZero() &&
14008 (Flags.hasNoSignedZeros() || !ConstFP->isNegative());
14009 case ISD::FMUL:
14010 return ConstFP->isOne();
14011 case ISD::FDIV:
14012 return OperandNo == 1 && ConstFP->isOne();
14013 case ISD::FMINNUM:
14014 case ISD::FMAXNUM:
14015 case ISD::FMINIMUMNUM:
14016 case ISD::FMAXIMUMNUM: {
14017 // Neutral element for fminnum/fminimumnum is NaN, Inf or FLT_MAX,
14018 // depending on fast-math flags (FMF).
14019 EVT VT = V.getValueType();
14020 const fltSemantics &Semantics = VT.getFltSemantics();
14021 APFloat NeutralAF = !Flags.hasNoNaNs() ? APFloat::getQNaN(Semantics)
14022 : !Flags.hasNoInfs() ? APFloat::getInf(Semantics)
14023 : APFloat::getLargest(Semantics);
14024 if (Opcode == ISD::FMAXNUM || Opcode == ISD::FMAXIMUMNUM)
14025 NeutralAF.changeSign();
14026
14027 return ConstFP->isExactlyValue(NeutralAF);
14028 }
14029 case ISD::FMINIMUM:
14030 case ISD::FMAXIMUM: {
14031 // Neutral element for fminimum is Inf or FLT_MAX, depending on FMF.
14032 const APFloat &VAPF = ConstFP->getValueAPF();
14033 bool NeutralNegative = (Opcode == ISD::FMAXIMUM);
14034 if (Flags.hasNoInfs())
14035 return VAPF.isLargest() && VAPF.isNegative() == NeutralNegative;
14036 return VAPF.isInfinity() && VAPF.isNegative() == NeutralNegative;
14037 }
14038 }
14039 }
14040 return false;
14041}
14042
14044 while (V.getOpcode() == ISD::BITCAST)
14045 V = V.getOperand(0);
14046 return V;
14047}
14048
14050 while (V.getOpcode() == ISD::BITCAST && V.getOperand(0).hasOneUse())
14051 V = V.getOperand(0);
14052 return V;
14053}
14054
14056 while (V.getOpcode() == ISD::EXTRACT_SUBVECTOR)
14057 V = V.getOperand(0);
14058 return V;
14059}
14060
14062 while (V.getOpcode() == ISD::INSERT_VECTOR_ELT) {
14063 SDValue InVec = V.getOperand(0);
14064 SDValue EltNo = V.getOperand(2);
14065 EVT VT = InVec.getValueType();
14066 auto *IndexC = dyn_cast<ConstantSDNode>(EltNo);
14067 if (IndexC && VT.isFixedLengthVector() &&
14068 IndexC->getAPIntValue().ult(VT.getVectorNumElements()) &&
14069 !DemandedElts[IndexC->getZExtValue()]) {
14070 V = InVec;
14071 continue;
14072 }
14073 break;
14074 }
14075 return V;
14076}
14077
14079 while (V.getOpcode() == ISD::TRUNCATE)
14080 V = V.getOperand(0);
14081 return V;
14082}
14083
14084bool llvm::isBitwiseNot(SDValue V, bool AllowUndefs) {
14085 if (V.getOpcode() != ISD::XOR)
14086 return false;
14087 V = peekThroughBitcasts(V.getOperand(1));
14088 unsigned NumBits = V.getScalarValueSizeInBits();
14089 ConstantSDNode *C =
14090 isConstOrConstSplat(V, AllowUndefs, /*AllowTruncation*/ true);
14091 return C && (C->getAPIntValue().countr_one() >= NumBits);
14092}
14093
14095 bool AllowTruncation) {
14096 APInt DemandedElts = getDemandAllEltsMask(N);
14097 return isConstOrConstSplat(N, DemandedElts, AllowUndefs, AllowTruncation);
14098}
14099
14101 bool AllowUndefs,
14102 bool AllowTruncation) {
14104 return CN;
14105
14106 // SplatVectors can truncate their operands. Ignore that case here unless
14107 // AllowTruncation is set.
14108 if (N->getOpcode() == ISD::SPLAT_VECTOR) {
14109 EVT VecEltVT = N->getValueType(0).getVectorElementType();
14110 if (auto *CN = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
14111 EVT CVT = CN->getValueType(0);
14112 assert(CVT.bitsGE(VecEltVT) && "Illegal splat_vector element extension");
14113 if (AllowTruncation || CVT == VecEltVT)
14114 return CN;
14115 }
14116 }
14117
14119 BitVector UndefElements;
14120 ConstantSDNode *CN = BV->getConstantSplatNode(DemandedElts, &UndefElements);
14121
14122 // BuildVectors can truncate their operands. Ignore that case here unless
14123 // AllowTruncation is set.
14124 // TODO: Look into whether we should allow UndefElements in non-DemandedElts
14125 if (CN && (UndefElements.none() || AllowUndefs)) {
14126 EVT CVT = CN->getValueType(0);
14127 EVT NSVT = N.getValueType().getScalarType();
14128 assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension");
14129 if (AllowTruncation || (CVT == NSVT))
14130 return CN;
14131 }
14132 }
14133
14134 if (N.getOpcode() == ISD::MERGE_VALUES)
14135 return isConstOrConstSplat(N.getOperand(N.getResNo()), DemandedElts,
14136 AllowUndefs, AllowTruncation);
14137
14138 return nullptr;
14139}
14140
14142 APInt DemandedElts = getDemandAllEltsMask(N);
14143 return isConstOrConstSplatFP(N, DemandedElts, AllowUndefs);
14144}
14145
14147 const APInt &DemandedElts,
14148 bool AllowUndefs) {
14150 return CN;
14151
14153 BitVector UndefElements;
14154 ConstantFPSDNode *CN =
14155 BV->getConstantFPSplatNode(DemandedElts, &UndefElements);
14156 // TODO: Look into whether we should allow UndefElements in non-DemandedElts
14157 if (CN && (UndefElements.none() || AllowUndefs))
14158 return CN;
14159 }
14160
14161 if (N.getOpcode() == ISD::SPLAT_VECTOR)
14162 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N.getOperand(0)))
14163 return CN;
14164
14165 return nullptr;
14166}
14167
14168bool llvm::isNullOrNullSplat(SDValue N, bool AllowUndefs) {
14169 // TODO: may want to use peekThroughBitcast() here.
14170 ConstantSDNode *C =
14171 isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation=*/true);
14172 return C && C->isZero();
14173}
14174
14175bool llvm::isOneOrOneSplat(SDValue N, bool AllowUndefs) {
14176 ConstantSDNode *C =
14177 isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation*/ true);
14178 return C && C->isOne();
14179}
14180
14181bool llvm::isOneOrOneSplatFP(SDValue N, bool AllowUndefs) {
14182 ConstantFPSDNode *C = isConstOrConstSplatFP(N, AllowUndefs);
14183 return C && C->isOne();
14184}
14185
14186bool llvm::isAllOnesOrAllOnesSplat(SDValue N, bool AllowUndefs) {
14188 unsigned BitWidth = N.getScalarValueSizeInBits();
14189 ConstantSDNode *C =
14190 isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation=*/true);
14191 return C && C->getAPIntValue().countTrailingOnes() >= BitWidth;
14192}
14193
14194bool llvm::isZeroOrZeroSplat(SDValue N, bool AllowUndefs) {
14196 ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs, true);
14197 return C && C->isZero();
14198}
14199
14200bool llvm::isZeroOrZeroSplatFP(SDValue N, bool AllowUndefs) {
14201 ConstantFPSDNode *C = isConstOrConstSplatFP(N, AllowUndefs);
14202 return C && C->isZero();
14203}
14204
14208
14210 unsigned Opc, unsigned Order, const DebugLoc &dl, SDVTList VTs, EVT memvt,
14212 : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MemRefs(memrefs) {
14213 bool IsVolatile = false;
14214 bool IsNonTemporal = false;
14215 bool IsDereferenceable = true;
14216 bool IsInvariant = true;
14217 for (const MachineMemOperand *MMO : memoperands()) {
14218 IsVolatile |= MMO->isVolatile();
14219 IsNonTemporal |= MMO->isNonTemporal();
14220 IsDereferenceable &= MMO->isDereferenceable();
14221 IsInvariant &= MMO->isInvariant();
14222 }
14223 MemSDNodeBits.IsVolatile = IsVolatile;
14224 MemSDNodeBits.IsNonTemporal = IsNonTemporal;
14225 MemSDNodeBits.IsDereferenceable = IsDereferenceable;
14226 MemSDNodeBits.IsInvariant = IsInvariant;
14227
14228 // For the single-MMO case, we check here that the size of the memory operand
14229 // fits within the size of the MMO. This is because the MMO might indicate
14230 // only a possible address range instead of specifying the affected memory
14231 // addresses precisely.
14234 getMemOperand()->getSize().getValue())) &&
14235 "Size mismatch!");
14236}
14237
14238namespace {
14239
14240 struct EVTArray {
14241 std::vector<EVT> VTs;
14242
14243 EVTArray() {
14244 VTs.reserve(MVT::VALUETYPE_SIZE);
14245 for (unsigned i = 0; i < MVT::VALUETYPE_SIZE; ++i)
14246 VTs.push_back(MVT((MVT::SimpleValueType)i));
14247 }
14248 };
14249
14250} // end anonymous namespace
14251
14252/// getValueTypeList - Return a pointer to the specified value type.
14253///
14254const EVT *SDNode::getValueTypeList(MVT VT) {
14255 static EVTArray SimpleVTArray;
14256
14257 assert(VT < MVT::VALUETYPE_SIZE && "Value type out of range!");
14258 return &SimpleVTArray.VTs[VT.SimpleTy];
14259}
14260
14261/// hasAnyUseOfValue - Return true if there are any use of the indicated
14262/// value. This method ignores uses of other values defined by this operation.
14263bool SDNode::hasAnyUseOfValue(unsigned Value) const {
14264 assert(Value < getNumValues() && "Bad value!");
14265
14266 for (SDUse &U : uses())
14267 if (U.getResNo() == Value)
14268 return true;
14269
14270 return false;
14271}
14272
14273/// isOnlyUserOf - Return true if this node is the only use of N.
14274bool SDNode::isOnlyUserOf(const SDNode *N) const {
14275 bool Seen = false;
14276 for (const SDNode *User : N->users()) {
14277 if (User == this)
14278 Seen = true;
14279 else
14280 return false;
14281 }
14282
14283 return Seen;
14284}
14285
14286/// Return true if the only users of N are contained in Nodes.
14288 bool Seen = false;
14289 for (const SDNode *User : N->users()) {
14290 if (llvm::is_contained(Nodes, User))
14291 Seen = true;
14292 else
14293 return false;
14294 }
14295
14296 return Seen;
14297}
14298
14299/// Return true if the referenced return value is an operand of N.
14300bool SDValue::isOperandOf(const SDNode *N) const {
14301 return is_contained(N->op_values(), *this);
14302}
14303
14304bool SDNode::isOperandOf(const SDNode *N) const {
14305 return any_of(N->op_values(),
14306 [this](SDValue Op) { return this == Op.getNode(); });
14307}
14308
14309/// reachesChainWithoutSideEffects - Return true if this operand (which must
14310/// be a chain) reaches the specified operand without crossing any
14311/// side-effecting instructions on any chain path. In practice, this looks
14312/// through token factors and non-volatile loads. In order to remain efficient,
14313/// this only looks a couple of nodes in, it does not do an exhaustive search.
14314///
14315/// Note that we only need to examine chains when we're searching for
14316/// side-effects; SelectionDAG requires that all side-effects are represented
14317/// by chains, even if another operand would force a specific ordering. This
14318/// constraint is necessary to allow transformations like splitting loads.
14320 unsigned Depth) const {
14321 if (*this == Dest) return true;
14322
14323 // Don't search too deeply, we just want to be able to see through
14324 // TokenFactor's etc.
14325 if (Depth == 0) return false;
14326
14327 // If this is a token factor, all inputs to the TF happen in parallel.
14328 if (getOpcode() == ISD::TokenFactor) {
14329 // First, try a shallow search.
14330 if (is_contained((*this)->ops(), Dest)) {
14331 // We found the chain we want as an operand of this TokenFactor.
14332 // Essentially, we reach the chain without side-effects if we could
14333 // serialize the TokenFactor into a simple chain of operations with
14334 // Dest as the last operation. This is automatically true if the
14335 // chain has one use: there are no other ordering constraints.
14336 // If the chain has more than one use, we give up: some other
14337 // use of Dest might force a side-effect between Dest and the current
14338 // node.
14339 if (Dest.hasOneUse())
14340 return true;
14341 }
14342 // Next, try a deep search: check whether every operand of the TokenFactor
14343 // reaches Dest.
14344 return llvm::all_of((*this)->ops(), [=](SDValue Op) {
14345 return Op.reachesChainWithoutSideEffects(Dest, Depth - 1);
14346 });
14347 }
14348
14349 // Loads don't have side effects, look through them.
14350 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
14351 if (Ld->isUnordered())
14352 return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
14353 }
14354 return false;
14355}
14356
14357bool SDNode::hasPredecessor(const SDNode *N) const {
14360 Worklist.push_back(this);
14361 return hasPredecessorHelper(N, Visited, Worklist);
14362}
14363
14365 this->Flags &= Flags;
14366}
14367
14368SDValue
14370 ArrayRef<ISD::NodeType> CandidateBinOps,
14371 bool AllowPartials) {
14372 // The pattern must end in an extract from index 0.
14373 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
14374 !isNullConstant(Extract->getOperand(1)))
14375 return SDValue();
14376
14377 // Match against one of the candidate binary ops.
14378 SDValue Op = Extract->getOperand(0);
14379 if (llvm::none_of(CandidateBinOps, [Op](ISD::NodeType BinOp) {
14380 return Op.getOpcode() == unsigned(BinOp);
14381 }))
14382 return SDValue();
14383
14384 // Floating-point reductions may require relaxed constraints on the final step
14385 // of the reduction because they may reorder intermediate operations.
14386 unsigned CandidateBinOp = Op.getOpcode();
14387 if (Op.getValueType().isFloatingPoint()) {
14388 SDNodeFlags Flags = Op->getFlags();
14389 switch (CandidateBinOp) {
14390 case ISD::FADD:
14391 if (!Flags.hasNoSignedZeros() || !Flags.hasAllowReassociation())
14392 return SDValue();
14393 break;
14394 default:
14395 llvm_unreachable("Unhandled FP opcode for binop reduction");
14396 }
14397 }
14398
14399 // Matching failed - attempt to see if we did enough stages that a partial
14400 // reduction from a subvector is possible.
14401 auto PartialReduction = [&](SDValue Op, unsigned NumSubElts) {
14402 if (!AllowPartials || !Op)
14403 return SDValue();
14404 EVT OpVT = Op.getValueType();
14405 EVT OpSVT = OpVT.getScalarType();
14406 EVT SubVT = EVT::getVectorVT(*getContext(), OpSVT, NumSubElts);
14407 if (TLI->getExtractSubvectorCost(SubVT, OpVT, 0) >
14409 return SDValue();
14410 BinOp = (ISD::NodeType)CandidateBinOp;
14411 return getExtractSubvector(SDLoc(Op), SubVT, Op, 0);
14412 };
14413
14414 // At each stage, we're looking for something that looks like:
14415 // %s = shufflevector <8 x i32> %op, <8 x i32> undef,
14416 // <8 x i32> <i32 2, i32 3, i32 undef, i32 undef,
14417 // i32 undef, i32 undef, i32 undef, i32 undef>
14418 // %a = binop <8 x i32> %op, %s
14419 // Where the mask changes according to the stage. E.g. for a 3-stage pyramid,
14420 // we expect something like:
14421 // <4,5,6,7,u,u,u,u>
14422 // <2,3,u,u,u,u,u,u>
14423 // <1,u,u,u,u,u,u,u>
14424 // While a partial reduction match would be:
14425 // <2,3,u,u,u,u,u,u>
14426 // <1,u,u,u,u,u,u,u>
14427 unsigned Stages = Log2_32(Op.getValueType().getVectorNumElements());
14428 SDValue PrevOp;
14429 for (unsigned i = 0; i < Stages; ++i) {
14430 unsigned MaskEnd = (1 << i);
14431
14432 if (Op.getOpcode() != CandidateBinOp)
14433 return PartialReduction(PrevOp, MaskEnd);
14434
14435 SDValue Op0 = Op.getOperand(0);
14436 SDValue Op1 = Op.getOperand(1);
14437
14439 if (Shuffle) {
14440 Op = Op1;
14441 } else {
14442 Shuffle = dyn_cast<ShuffleVectorSDNode>(Op1);
14443 Op = Op0;
14444 }
14445
14446 // The first operand of the shuffle should be the same as the other operand
14447 // of the binop.
14448 if (!Shuffle || Shuffle->getOperand(0) != Op)
14449 return PartialReduction(PrevOp, MaskEnd);
14450
14451 // Verify the shuffle has the expected (at this stage of the pyramid) mask.
14452 for (int Index = 0; Index < (int)MaskEnd; ++Index)
14453 if (Shuffle->getMaskElt(Index) != (int)(MaskEnd + Index))
14454 return PartialReduction(PrevOp, MaskEnd);
14455
14456 PrevOp = Op;
14457 }
14458
14459 // Handle subvector reductions, which tend to appear after the shuffle
14460 // reduction stages.
14461 while (Op.getOpcode() == CandidateBinOp) {
14462 unsigned NumElts = Op.getValueType().getVectorNumElements();
14463 SDValue Op0 = Op.getOperand(0);
14464 SDValue Op1 = Op.getOperand(1);
14465 if (Op0.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
14467 Op0.getOperand(0) != Op1.getOperand(0))
14468 break;
14469 SDValue Src = Op0.getOperand(0);
14470 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
14471 if (NumSrcElts != (2 * NumElts))
14472 break;
14473 if (!(Op0.getConstantOperandAPInt(1) == 0 &&
14474 Op1.getConstantOperandAPInt(1) == NumElts) &&
14475 !(Op1.getConstantOperandAPInt(1) == 0 &&
14476 Op0.getConstantOperandAPInt(1) == NumElts))
14477 break;
14478 Op = Src;
14479 }
14480
14481 BinOp = (ISD::NodeType)CandidateBinOp;
14482 return Op;
14483}
14484
14486 EVT VT = N->getValueType(0);
14487 EVT EltVT = VT.getVectorElementType();
14488 unsigned NE = getMaxRuntimeNumElements(VT);
14489
14490 if (VT.isScalableVector() && (NE == 0 || ResNE != 0))
14491 reportFatalUsageError("Cannot unroll scalable vector!");
14492
14493 assert(NE && "Nothing to unroll!");
14494 SDLoc dl(N);
14495
14496 // If ResNE is 0, fully unroll the vector op.
14497 if (ResNE == 0)
14498 ResNE = NE;
14499 else if (NE > ResNE)
14500 NE = ResNE;
14501
14502 if (N->getNumValues() == 2) {
14503 SmallVector<SDValue, 8> Scalars0, Scalars1;
14504 SmallVector<SDValue, 4> Operands(N->getNumOperands());
14505 EVT VT1 = N->getValueType(1);
14506 EVT EltVT1 = VT1.getVectorElementType();
14507
14508 unsigned i;
14509 for (i = 0; i != NE; ++i) {
14510 for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) {
14511 SDValue Operand = N->getOperand(j);
14512 EVT OperandVT = Operand.getValueType();
14513
14514 // A vector operand; extract a single element.
14515 EVT OperandEltVT = OperandVT.getVectorElementType();
14516 Operands[j] = getExtractVectorElt(dl, OperandEltVT, Operand, i);
14517 }
14518
14519 SDValue EltOp = getNode(N->getOpcode(), dl, {EltVT, EltVT1}, Operands);
14520 Scalars0.push_back(EltOp);
14521 Scalars1.push_back(EltOp.getValue(1));
14522 }
14523
14524 for (; i < ResNE; ++i) {
14525 Scalars0.push_back(getUNDEF(EltVT));
14526 Scalars1.push_back(getUNDEF(EltVT1));
14527 }
14528
14530 : ElementCount::getFixed(ResNE);
14531 EVT VecVT = EVT::getVectorVT(*getContext(), EltVT, ResEC);
14532 EVT VecVT1 = EVT::getVectorVT(*getContext(), EltVT1, ResEC);
14533 SDValue Vec0 = buildVectorFromUnrolledParts(VecVT, dl, Scalars0);
14534 SDValue Vec1 = buildVectorFromUnrolledParts(VecVT1, dl, Scalars1);
14535 return getMergeValues({Vec0, Vec1}, dl);
14536 }
14537
14538 assert(N->getNumValues() == 1 &&
14539 "Can't unroll a vector with multiple results!");
14540
14542 SmallVector<SDValue, 4> Operands(N->getNumOperands());
14543
14544 unsigned i;
14545 for (i= 0; i != NE; ++i) {
14546 for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) {
14547 SDValue Operand = N->getOperand(j);
14548 EVT OperandVT = Operand.getValueType();
14549 if (OperandVT.isVector()) {
14550 // A vector operand; extract a single element.
14551 EVT OperandEltVT = OperandVT.getVectorElementType();
14552 Operands[j] = getExtractVectorElt(dl, OperandEltVT, Operand, i);
14553 } else {
14554 // A scalar operand; just use it as is.
14555 Operands[j] = Operand;
14556 }
14557 }
14558
14559 switch (N->getOpcode()) {
14560 default: {
14561 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands,
14562 N->getFlags()));
14563 break;
14564 }
14565 case ISD::VSELECT:
14566 Scalars.push_back(
14567 getNode(ISD::SELECT, dl, EltVT, Operands, N->getFlags()));
14568 break;
14569 case ISD::SHL:
14570 case ISD::SRA:
14571 case ISD::SRL:
14572 case ISD::ROTL:
14573 case ISD::ROTR:
14574 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0],
14576 Operands[1])));
14577 break;
14579 EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType();
14580 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT,
14581 Operands[0],
14582 getValueType(ExtVT)));
14583 break;
14584 }
14585 case ISD::ADDRSPACECAST: {
14586 const auto *ASC = cast<AddrSpaceCastSDNode>(N);
14587 Scalars.push_back(
14588 getAddrSpaceCast(dl, EltVT, Operands[0], ASC->getSrcAddressSpace(),
14589 ASC->getDestAddressSpace(), ASC->getFlags()));
14590 break;
14591 }
14592 }
14593 }
14594
14595 for (; i < ResNE; ++i)
14596 Scalars.push_back(getUNDEF(EltVT));
14597
14598 EVT VecVT = VT.isScalableVector()
14599 ? VT
14600 : EVT::getVectorVT(*getContext(), EltVT, ResNE);
14601 return buildVectorFromUnrolledParts(VecVT, dl, Scalars);
14602}
14603
14604std::pair<SDValue, SDValue> SelectionDAG::UnrollVectorOverflowOp(
14605 SDNode *N, unsigned ResNE) {
14606 unsigned Opcode = N->getOpcode();
14607 assert((Opcode == ISD::UADDO || Opcode == ISD::SADDO ||
14608 Opcode == ISD::USUBO || Opcode == ISD::SSUBO ||
14609 Opcode == ISD::UMULO || Opcode == ISD::SMULO) &&
14610 "Expected an overflow opcode");
14611
14612 EVT ResVT = N->getValueType(0);
14613 EVT OvVT = N->getValueType(1);
14614 EVT ResEltVT = ResVT.getVectorElementType();
14615 EVT OvEltVT = OvVT.getVectorElementType();
14616 SDLoc dl(N);
14617
14618 // If ResNE is 0, fully unroll the vector op.
14619 unsigned NE = ResVT.getVectorNumElements();
14620 if (ResNE == 0)
14621 ResNE = NE;
14622 else if (NE > ResNE)
14623 NE = ResNE;
14624
14625 SmallVector<SDValue, 8> LHSScalars;
14626 SmallVector<SDValue, 8> RHSScalars;
14627 ExtractVectorElements(N->getOperand(0), LHSScalars, 0, NE);
14628 ExtractVectorElements(N->getOperand(1), RHSScalars, 0, NE);
14629
14630 EVT SVT = TLI->getSetCCResultType(getDataLayout(), *getContext(), ResEltVT);
14631 SDVTList VTs = getVTList(ResEltVT, SVT);
14632 SmallVector<SDValue, 8> ResScalars;
14633 SmallVector<SDValue, 8> OvScalars;
14634 for (unsigned i = 0; i < NE; ++i) {
14635 SDValue Res = getNode(Opcode, dl, VTs, LHSScalars[i], RHSScalars[i]);
14636 SDValue Ov =
14637 getSelect(dl, OvEltVT, Res.getValue(1),
14638 getBoolConstant(true, dl, OvEltVT, ResVT),
14639 getConstant(0, dl, OvEltVT));
14640
14641 ResScalars.push_back(Res);
14642 OvScalars.push_back(Ov);
14643 }
14644
14645 ResScalars.append(ResNE - NE, getUNDEF(ResEltVT));
14646 OvScalars.append(ResNE - NE, getUNDEF(OvEltVT));
14647
14648 EVT NewResVT = EVT::getVectorVT(*getContext(), ResEltVT, ResNE);
14649 EVT NewOvVT = EVT::getVectorVT(*getContext(), OvEltVT, ResNE);
14650 return std::make_pair(getBuildVector(NewResVT, dl, ResScalars),
14651 getBuildVector(NewOvVT, dl, OvScalars));
14652}
14653
14656 TypeSize Bytes, int Dist,
14657 const SelectionDAG &DAG) {
14658 if (LS->isVolatile() || Base->isVolatile())
14659 return false;
14660 // TODO: probably too restrictive for atomics, revisit
14661 if (!LS->isSimple())
14662 return false;
14663 if (LS->isIndexed() || Base->isIndexed())
14664 return false;
14665 if (LS->getChain() != Base->getChain())
14666 return false;
14667 EVT VT = LS->getMemoryVT();
14668 if (!VT.getScalarType().isByteSized())
14669 return false;
14670 if (VT.getStoreSize() != Bytes)
14671 return false;
14672
14673 auto BaseLocDecomp = BaseIndexOffset::match(Base, DAG);
14674 auto LocDecomp = BaseIndexOffset::match(LS, DAG);
14676 if (!BaseLocDecomp.equalBaseIndex(LocDecomp, DAG, Offset))
14677 return false;
14678
14679 int64_t ExpectedOffset = Dist * (int64_t)Bytes.getKnownMinValue();
14680 if (Bytes.isFixed())
14681 return Offset == StackOffset::getFixed(ExpectedOffset);
14682 return Offset == StackOffset::getScalable(ExpectedOffset);
14683}
14684
14687 TypeSize Bytes,
14688 int Dist) const {
14689 return areNonVolatileConsecutiveLoadsOrStores(LD, Base, Bytes, Dist, *this);
14690}
14691
14694 TypeSize Bytes,
14695 int Dist) const {
14696 return areNonVolatileConsecutiveLoadsOrStores(ST, Base, Bytes, Dist, *this);
14697}
14698
14699/// InferPtrAlignment - Infer alignment of a load / store address. Return
14700/// std::nullopt if it cannot be inferred.
14702 // If this is a GlobalAddress + cst, return the alignment.
14703 const GlobalValue *GV = nullptr;
14704 int64_t GVOffset = 0;
14705 if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) {
14706 unsigned PtrWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
14707 KnownBits Known(PtrWidth);
14709 unsigned AlignBits = Known.countMinTrailingZeros();
14710 if (AlignBits)
14711 return commonAlignment(Align::fromLog2(std::min(31U, AlignBits)),
14712 GVOffset);
14713 }
14714
14715 // If this is a direct reference to a stack slot, use information about the
14716 // stack slot's alignment.
14717 int FrameIdx = INT_MIN;
14718 int64_t FrameOffset = 0;
14720 FrameIdx = FI->getIndex();
14721 } else if (isBaseWithConstantOffset(Ptr) &&
14723 // Handle FI+Cst
14724 FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
14725 FrameOffset = Ptr.getConstantOperandVal(1);
14726 }
14727
14728 if (FrameIdx != INT_MIN) {
14730 return commonAlignment(MFI.getObjectAlign(FrameIdx), FrameOffset);
14731 }
14732
14733 return std::nullopt;
14734}
14735
14736/// Split the scalar node with EXTRACT_ELEMENT using the provided
14737/// VTs and return the low/high part.
14738std::pair<SDValue, SDValue> SelectionDAG::SplitScalar(const SDValue &N,
14739 const SDLoc &DL,
14740 const EVT &LoVT,
14741 const EVT &HiVT) {
14742 assert(!LoVT.isVector() && !HiVT.isVector() && !N.getValueType().isVector() &&
14743 "Split node must be a scalar type");
14744 SDValue Lo =
14746 SDValue Hi =
14748 return std::make_pair(Lo, Hi);
14749}
14750
14751/// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type
14752/// which is split (or expanded) into two not necessarily identical pieces.
14753std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const {
14754 // Currently all types are split in half.
14755 EVT LoVT, HiVT;
14756 if (!VT.isVector())
14757 LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT);
14758 else
14759 LoVT = HiVT = VT.getHalfNumVectorElementsVT(*getContext());
14760
14761 return std::make_pair(LoVT, HiVT);
14762}
14763
14764/// GetDependentSplitDestVTs - Compute the VTs needed for the low/hi parts of a
14765/// type, dependent on an enveloping VT that has been split into two identical
14766/// pieces. Sets the HiIsEmpty flag when hi type has zero storage size.
14767std::pair<EVT, EVT>
14769 bool *HiIsEmpty) const {
14770 EVT EltTp = VT.getVectorElementType();
14771 // Examples:
14772 // custom VL=8 with enveloping VL=8/8 yields 8/0 (hi empty)
14773 // custom VL=9 with enveloping VL=8/8 yields 8/1
14774 // custom VL=10 with enveloping VL=8/8 yields 8/2
14775 // etc.
14776 ElementCount VTNumElts = VT.getVectorElementCount();
14777 ElementCount EnvNumElts = EnvVT.getVectorElementCount();
14778 assert(VTNumElts.isScalable() == EnvNumElts.isScalable() &&
14779 "Mixing fixed width and scalable vectors when enveloping a type");
14780 EVT LoVT, HiVT;
14781 if (VTNumElts.getKnownMinValue() > EnvNumElts.getKnownMinValue()) {
14782 LoVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts);
14783 HiVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts - EnvNumElts);
14784 *HiIsEmpty = false;
14785 } else {
14786 // Flag that hi type has zero storage size, but return split envelop type
14787 // (this would be easier if vector types with zero elements were allowed).
14788 LoVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts);
14789 HiVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts);
14790 *HiIsEmpty = true;
14791 }
14792 return std::make_pair(LoVT, HiVT);
14793}
14794
14795/// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the
14796/// low/high part.
14797std::pair<SDValue, SDValue>
14798SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT,
14799 const EVT &HiVT) {
14800 assert(LoVT.isScalableVector() == HiVT.isScalableVector() &&
14801 LoVT.isScalableVector() == N.getValueType().isScalableVector() &&
14802 "Splitting vector with an invalid mixture of fixed and scalable "
14803 "vector types");
14805 N.getValueType().getVectorMinNumElements() &&
14806 "More vector elements requested than available!");
14807 SDValue Lo, Hi;
14808 Lo = getExtractSubvector(DL, LoVT, N, 0);
14809 // For scalable vectors it is safe to use LoVT.getVectorMinNumElements()
14810 // (rather than having to use ElementCount), because EXTRACT_SUBVECTOR scales
14811 // IDX with the runtime scaling factor of the result vector type. For
14812 // fixed-width result vectors, that runtime scaling factor is 1.
14814 return std::make_pair(Lo, Hi);
14815}
14816
14817std::pair<SDValue, SDValue> SelectionDAG::SplitEVL(SDValue N, EVT VecVT,
14818 const SDLoc &DL) {
14819 // Split the vector length parameter.
14820 // %evl -> umin(%evl, %halfnumelts) and usubsat(%evl - %halfnumelts).
14821 EVT VT = N.getValueType();
14823 "Expecting the mask to be an evenly-sized vector");
14824 SDValue HalfNumElts = getElementCount(
14826 SDValue Lo = getNode(ISD::UMIN, DL, VT, N, HalfNumElts);
14827 SDValue Hi = getNode(ISD::USUBSAT, DL, VT, N, HalfNumElts);
14828 return std::make_pair(Lo, Hi);
14829}
14830
14831/// Widen the vector up to the next power of two using INSERT_SUBVECTOR.
14833 EVT VT = N.getValueType();
14834 EVT WideVT = VT.changeElementCount(
14835 *getContext(),
14837 return getInsertSubvector(DL, getPOISON(WideVT), N, 0);
14838}
14839
14842 unsigned Start, unsigned Count,
14843 EVT EltVT) {
14844 EVT VT = Op.getValueType();
14845 if (Count == 0)
14847 if (EltVT == EVT())
14848 EltVT = VT.getVectorElementType();
14849 SDLoc SL(Op);
14850 for (unsigned i = Start, e = Start + Count; i != e; ++i) {
14851 Args.push_back(getExtractVectorElt(SL, EltVT, Op, i));
14852 }
14853}
14854
14855// getAddressSpace - Return the address space this GlobalAddress belongs to.
14857 return getGlobal()->getType()->getAddressSpace();
14858}
14859
14862 return Val.MachineCPVal->getType();
14863 return Val.ConstVal->getType();
14864}
14865
14866bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue, APInt &SplatUndef,
14867 unsigned &SplatBitSize,
14868 bool &HasAnyUndefs,
14869 unsigned MinSplatBits,
14870 bool IsBigEndian) const {
14871 EVT VT = getValueType(0);
14872 assert(VT.isVector() && "Expected a vector type");
14873 unsigned VecWidth = VT.getSizeInBits();
14874 if (MinSplatBits > VecWidth)
14875 return false;
14876
14877 // FIXME: The widths are based on this node's type, but build vectors can
14878 // truncate their operands.
14879 SplatValue = APInt(VecWidth, 0);
14880 SplatUndef = APInt(VecWidth, 0);
14881
14882 // Get the bits. Bits with undefined values (when the corresponding element
14883 // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared
14884 // in SplatValue. If any of the values are not constant, give up and return
14885 // false.
14886 unsigned int NumOps = getNumOperands();
14887 assert(NumOps > 0 && "isConstantSplat has 0-size build vector");
14888 unsigned EltWidth = VT.getScalarSizeInBits();
14889
14890 for (unsigned j = 0; j < NumOps; ++j) {
14891 unsigned i = IsBigEndian ? NumOps - 1 - j : j;
14892 SDValue OpVal = getOperand(i);
14893 unsigned BitPos = j * EltWidth;
14894
14895 if (OpVal.isUndef())
14896 SplatUndef.setBits(BitPos, BitPos + EltWidth);
14897 else if (auto *CN = dyn_cast<ConstantSDNode>(OpVal))
14898 SplatValue.insertBits(CN->getAPIntValue().zextOrTrunc(EltWidth), BitPos);
14899 else if (auto *CN = dyn_cast<ConstantFPSDNode>(OpVal))
14900 SplatValue.insertBits(CN->getValueAPF().bitcastToAPInt(), BitPos);
14901 else
14902 return false;
14903 }
14904
14905 // The build_vector is all constants or undefs. Find the smallest element
14906 // size that splats the vector.
14907 HasAnyUndefs = (SplatUndef != 0);
14908
14909 // FIXME: This does not work for vectors with elements less than 8 bits.
14910 while (VecWidth > 8) {
14911 // If we can't split in half, stop here.
14912 if (VecWidth & 1)
14913 break;
14914
14915 unsigned HalfSize = VecWidth / 2;
14916 APInt HighValue = SplatValue.extractBits(HalfSize, HalfSize);
14917 APInt LowValue = SplatValue.extractBits(HalfSize, 0);
14918 APInt HighUndef = SplatUndef.extractBits(HalfSize, HalfSize);
14919 APInt LowUndef = SplatUndef.extractBits(HalfSize, 0);
14920
14921 // If the two halves do not match (ignoring undef bits), stop here.
14922 if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) ||
14923 MinSplatBits > HalfSize)
14924 break;
14925
14926 SplatValue = HighValue | LowValue;
14927 SplatUndef = HighUndef & LowUndef;
14928
14929 VecWidth = HalfSize;
14930 }
14931
14932 // FIXME: The loop above only tries to split in halves. But if the input
14933 // vector for example is <3 x i16> it wouldn't be able to detect a
14934 // SplatBitSize of 16. No idea if that is a design flaw currently limiting
14935 // optimizations. I guess that back in the days when this helper was created
14936 // vectors normally was power-of-2 sized.
14937
14938 SplatBitSize = VecWidth;
14939 return true;
14940}
14941
14943 BitVector *UndefElements) const {
14944 unsigned NumOps = getNumOperands();
14945 if (UndefElements) {
14946 UndefElements->clear();
14947 UndefElements->resize(NumOps);
14948 }
14949 assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size");
14950 if (!DemandedElts)
14951 return SDValue();
14952 SDValue Splatted;
14953 for (unsigned i = 0; i != NumOps; ++i) {
14954 if (!DemandedElts[i])
14955 continue;
14956 SDValue Op = getOperand(i);
14957 if (Op.isUndef()) {
14958 if (UndefElements)
14959 (*UndefElements)[i] = true;
14960 } else if (!Splatted) {
14961 Splatted = Op;
14962 } else if (Splatted != Op) {
14963 return SDValue();
14964 }
14965 }
14966
14967 if (!Splatted) {
14968 unsigned FirstDemandedIdx = DemandedElts.countr_zero();
14969 assert(getOperand(FirstDemandedIdx).isUndef() &&
14970 "Can only have a splat without a constant for all undefs.");
14971 return getOperand(FirstDemandedIdx);
14972 }
14973
14974 return Splatted;
14975}
14976
14978 APInt DemandedElts = APInt::getAllOnes(getNumOperands());
14979 return getSplatValue(DemandedElts, UndefElements);
14980}
14981
14983 SmallVectorImpl<SDValue> &Sequence,
14984 BitVector *UndefElements) const {
14985 unsigned NumOps = getNumOperands();
14986 Sequence.clear();
14987 if (UndefElements) {
14988 UndefElements->clear();
14989 UndefElements->resize(NumOps);
14990 }
14991 assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size");
14992 if (!DemandedElts || NumOps < 2 || !isPowerOf2_32(NumOps))
14993 return false;
14994
14995 // Set the undefs even if we don't find a sequence (like getSplatValue).
14996 if (UndefElements)
14997 for (unsigned I = 0; I != NumOps; ++I)
14998 if (DemandedElts[I] && getOperand(I).isUndef())
14999 (*UndefElements)[I] = true;
15000
15001 // Iteratively widen the sequence length looking for repetitions.
15002 for (unsigned SeqLen = 1; SeqLen < NumOps; SeqLen *= 2) {
15003 Sequence.append(SeqLen, SDValue());
15004 for (unsigned I = 0; I != NumOps; ++I) {
15005 if (!DemandedElts[I])
15006 continue;
15007 SDValue &SeqOp = Sequence[I % SeqLen];
15009 if (Op.isUndef()) {
15010 if (!SeqOp)
15011 SeqOp = Op;
15012 continue;
15013 }
15014 if (SeqOp && !SeqOp.isUndef() && SeqOp != Op) {
15015 Sequence.clear();
15016 break;
15017 }
15018 SeqOp = Op;
15019 }
15020 if (!Sequence.empty())
15021 return true;
15022 }
15023
15024 assert(Sequence.empty() && "Failed to empty non-repeating sequence pattern");
15025 return false;
15026}
15027
15029 BitVector *UndefElements) const {
15030 APInt DemandedElts = APInt::getAllOnes(getNumOperands());
15031 return getRepeatedSequence(DemandedElts, Sequence, UndefElements);
15032}
15033
15036 BitVector *UndefElements) const {
15038 getSplatValue(DemandedElts, UndefElements));
15039}
15040
15043 return dyn_cast_or_null<ConstantSDNode>(getSplatValue(UndefElements));
15044}
15045
15048 BitVector *UndefElements) const {
15050 getSplatValue(DemandedElts, UndefElements));
15051}
15052
15057
15058int32_t
15060 uint32_t BitWidth) const {
15061 if (ConstantFPSDNode *CN =
15063 bool IsExact;
15064 APSInt IntVal(BitWidth);
15065 const APFloat &APF = CN->getValueAPF();
15066 if (APF.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) !=
15067 APFloat::opOK ||
15068 !IsExact)
15069 return -1;
15070
15071 return IntVal.exactLogBase2();
15072 }
15073 return -1;
15074}
15075
15077 bool IsLittleEndian, unsigned DstEltSizeInBits,
15078 SmallVectorImpl<APInt> &RawBitElements, BitVector &UndefElements) const {
15079 // Early-out if this contains anything but Undef/Constant/ConstantFP.
15080 if (!isConstant())
15081 return false;
15082
15083 unsigned NumSrcOps = getNumOperands();
15084 unsigned SrcEltSizeInBits = getValueType(0).getScalarSizeInBits();
15085 assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 &&
15086 "Invalid bitcast scale");
15087
15088 // If the elements don't pack cleanly, don't attempt to recast.
15089 // TODO: Add handling (e.g. bitcast <33 x i8> --> <8 x i33>)
15090 if ((SrcEltSizeInBits % DstEltSizeInBits) != 0 &&
15091 (DstEltSizeInBits % SrcEltSizeInBits) != 0)
15092 return false;
15093
15094 // Extract raw src bits.
15095 SmallVector<APInt> SrcBitElements(NumSrcOps,
15096 APInt::getZero(SrcEltSizeInBits));
15097 BitVector SrcUndeElements(NumSrcOps, false);
15098
15099 for (unsigned I = 0; I != NumSrcOps; ++I) {
15101 if (Op.isUndef()) {
15102 SrcUndeElements.set(I);
15103 continue;
15104 }
15105 auto *CInt = dyn_cast<ConstantSDNode>(Op);
15106 auto *CFP = dyn_cast<ConstantFPSDNode>(Op);
15107 assert((CInt || CFP) && "Unknown constant");
15108 SrcBitElements[I] = CInt ? CInt->getAPIntValue().trunc(SrcEltSizeInBits)
15109 : CFP->getValueAPF().bitcastToAPInt();
15110 }
15111
15112 // Recast to dst width.
15113 recastRawBits(IsLittleEndian, DstEltSizeInBits, RawBitElements,
15114 SrcBitElements, UndefElements, SrcUndeElements);
15115 return true;
15116}
15117
15118void BuildVectorSDNode::recastRawBits(bool IsLittleEndian,
15119 unsigned DstEltSizeInBits,
15120 SmallVectorImpl<APInt> &DstBitElements,
15121 ArrayRef<APInt> SrcBitElements,
15122 BitVector &DstUndefElements,
15123 const BitVector &SrcUndefElements) {
15124 unsigned NumSrcOps = SrcBitElements.size();
15125 unsigned SrcEltSizeInBits = SrcBitElements[0].getBitWidth();
15126 assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 &&
15127 "Invalid bitcast scale");
15128 assert(((SrcEltSizeInBits % DstEltSizeInBits) == 0 ||
15129 (DstEltSizeInBits % SrcEltSizeInBits) == 0) &&
15130 "Unsupported bitcast scale");
15131 assert(NumSrcOps == SrcUndefElements.size() && "Vector size mismatch");
15132
15133 unsigned NumDstOps = (NumSrcOps * SrcEltSizeInBits) / DstEltSizeInBits;
15134 DstUndefElements.clear();
15135 DstUndefElements.resize(NumDstOps, false);
15136 DstBitElements.assign(NumDstOps, APInt::getZero(DstEltSizeInBits));
15137
15138 // Concatenate src elements constant bits together into dst element.
15139 if (SrcEltSizeInBits <= DstEltSizeInBits) {
15140 unsigned Scale = DstEltSizeInBits / SrcEltSizeInBits;
15141 for (unsigned I = 0; I != NumDstOps; ++I) {
15142 DstUndefElements.set(I);
15143 APInt &DstBits = DstBitElements[I];
15144 for (unsigned J = 0; J != Scale; ++J) {
15145 unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1));
15146 if (SrcUndefElements[Idx])
15147 continue;
15148 DstUndefElements.reset(I);
15149 const APInt &SrcBits = SrcBitElements[Idx];
15150 assert(SrcBits.getBitWidth() == SrcEltSizeInBits &&
15151 "Illegal constant bitwidths");
15152 DstBits.insertBits(SrcBits, J * SrcEltSizeInBits);
15153 }
15154 }
15155 return;
15156 }
15157
15158 // Split src element constant bits into dst elements.
15159 unsigned Scale = SrcEltSizeInBits / DstEltSizeInBits;
15160 for (unsigned I = 0; I != NumSrcOps; ++I) {
15161 if (SrcUndefElements[I]) {
15162 DstUndefElements.set(I * Scale, (I + 1) * Scale);
15163 continue;
15164 }
15165 const APInt &SrcBits = SrcBitElements[I];
15166 for (unsigned J = 0; J != Scale; ++J) {
15167 unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1));
15168 APInt &DstBits = DstBitElements[Idx];
15169 DstBits = SrcBits.extractBits(DstEltSizeInBits, J * DstEltSizeInBits);
15170 }
15171 }
15172}
15173
15175 for (const SDValue &Op : op_values()) {
15176 unsigned Opc = Op.getOpcode();
15177 if (!Op.isUndef() && Opc != ISD::Constant && Opc != ISD::ConstantFP)
15178 return false;
15179 }
15180 return true;
15181}
15182
15183std::optional<std::pair<APInt, APInt>>
15185 unsigned NumOps = getNumOperands();
15186 if (NumOps < 2)
15187 return std::nullopt;
15188
15189 unsigned EltSize = getValueType(0).getScalarSizeInBits();
15190 APInt Start, Stride;
15191 int FirstIdx = -1, SecondIdx = -1;
15192
15193 // Find the first two non-undef constant elements to determine Start and
15194 // Stride, then verify all remaining elements match the sequence.
15195 for (unsigned I = 0; I < NumOps; ++I) {
15197 if (Op->isUndef())
15198 continue;
15199 if (!isa<ConstantSDNode>(Op))
15200 return std::nullopt;
15201
15202 APInt Val = getConstantOperandAPInt(I).trunc(EltSize);
15203 if (FirstIdx < 0) {
15204 FirstIdx = I;
15205 Start = Val;
15206 } else if (SecondIdx < 0) {
15207 SecondIdx = I;
15208 // Compute stride using modular arithmetic. Simple division would handle
15209 // common strides (1, 2, -1, etc.), but modular inverse maximizes matches.
15210 // Example: <0, poison, poison, 0xFF> has stride 0x55 since 3*0x55 = 0xFF
15211 // Note that modular arithmetic is agnostic to signed/unsigned.
15212 unsigned IdxDiff = I - FirstIdx;
15213 APInt ValDiff = Val - Start;
15214
15215 // Step 1: Factor out common powers of 2 from IdxDiff and ValDiff.
15216 unsigned CommonPow2Bits = llvm::countr_zero(IdxDiff);
15217 if (ValDiff.countr_zero() < CommonPow2Bits)
15218 return std::nullopt; // ValDiff not divisible by 2^CommonPow2Bits
15219 IdxDiff >>= CommonPow2Bits;
15220 ValDiff.lshrInPlace(CommonPow2Bits);
15221
15222 // Step 2: IdxDiff is now odd, so its inverse mod 2^EltSize exists.
15223 // TODO: There are 2^CommonPow2Bits valid strides; currently we only try
15224 // one, but we could try all candidates to handle more cases.
15225 Stride = ValDiff * APInt(EltSize, IdxDiff).multiplicativeInverse();
15226 if (Stride.isZero())
15227 return std::nullopt;
15228
15229 // Step 3: Adjust Start based on the first defined element's index.
15230 Start -= Stride * FirstIdx;
15231 } else {
15232 // Verify this element matches the sequence.
15233 if (Val != Start + Stride * I)
15234 return std::nullopt;
15235 }
15236 }
15237
15238 // Need at least two defined elements.
15239 if (SecondIdx < 0)
15240 return std::nullopt;
15241
15242 return std::make_pair(Start, Stride);
15243}
15244
15246 // Find the first non-undef value in the shuffle mask.
15247 unsigned i, e;
15248 for (i = 0, e = Mask.size(); i != e && Mask[i] < 0; ++i)
15249 /* search */;
15250
15251 // If all elements are undefined, this shuffle can be considered a splat
15252 // (although it should eventually get simplified away completely).
15253 if (i == e)
15254 return true;
15255
15256 // Make sure all remaining elements are either undef or the same as the first
15257 // non-undef value.
15258 for (int Idx = Mask[i]; i != e; ++i)
15259 if (Mask[i] >= 0 && Mask[i] != Idx)
15260 return false;
15261 return true;
15262}
15263
15264// Returns true if it is a constant integer BuildVector or constant integer,
15265// possibly hidden by a bitcast.
15267 SDValue N, bool AllowOpaques) const {
15269
15270 if (auto *C = dyn_cast<ConstantSDNode>(N))
15271 return AllowOpaques || !C->isOpaque();
15272
15274 return true;
15275
15276 // Treat a GlobalAddress supporting constant offset folding as a
15277 // constant integer.
15278 if (auto *GA = dyn_cast<GlobalAddressSDNode>(N))
15279 if (GA->getOpcode() == ISD::GlobalAddress &&
15280 TLI->isOffsetFoldingLegal(GA))
15281 return true;
15282
15283 if ((N.getOpcode() == ISD::SPLAT_VECTOR) &&
15284 isa<ConstantSDNode>(N.getOperand(0)))
15285 return true;
15286 return false;
15287}
15288
15289// Returns true if it is a constant float BuildVector or constant float.
15292 return true;
15293
15295 return true;
15296
15297 if ((N.getOpcode() == ISD::SPLAT_VECTOR) &&
15298 isa<ConstantFPSDNode>(N.getOperand(0)))
15299 return true;
15300
15301 return false;
15302}
15303
15304std::optional<bool> SelectionDAG::isBoolConstant(SDValue N) const {
15305 ConstantSDNode *Const =
15306 isConstOrConstSplat(N, false, /*AllowTruncation=*/true);
15307 if (!Const)
15308 return std::nullopt;
15309
15310 EVT VT = N.getValueType();
15311 const APInt CVal = Const->getAPIntValue().trunc(VT.getScalarSizeInBits());
15312 switch (TLI->getBooleanContents(VT)) {
15314 if (CVal.isOne())
15315 return true;
15316 if (CVal.isZero())
15317 return false;
15318 return std::nullopt;
15320 if (CVal.isAllOnes())
15321 return true;
15322 if (CVal.isZero())
15323 return false;
15324 return std::nullopt;
15326 return CVal[0];
15327 }
15328 llvm_unreachable("Unknown BooleanContent enum");
15329}
15330
15331void SelectionDAG::createOperands(SDNode *Node, ArrayRef<SDValue> Vals) {
15332 assert(!Node->OperandList && "Node already has operands");
15334 "too many operands to fit into SDNode");
15335 SDUse *Ops = OperandRecycler.allocate(
15336 ArrayRecycler<SDUse>::Capacity::get(Vals.size()), OperandAllocator);
15337
15338 bool IsDivergent = false;
15339 for (unsigned I = 0; I != Vals.size(); ++I) {
15340 Ops[I].setUser(Node);
15341 Ops[I].setInitial(Vals[I]);
15342 EVT VT = Ops[I].getValueType();
15343
15344 // Skip Chain. It does not carry divergence.
15345 if (VT != MVT::Other &&
15346 (VT != MVT::Glue || gluePropagatesDivergence(Ops[I].getNode())) &&
15347 Ops[I].getNode()->isDivergent()) {
15348 IsDivergent = true;
15349 }
15350 }
15351 Node->NumOperands = Vals.size();
15352 Node->OperandList = Ops;
15353 if (!TLI->isSDNodeAlwaysUniform(Node)) {
15354 IsDivergent |= TLI->isSDNodeSourceOfDivergence(Node, FLI, UA);
15355 Node->SDNodeBits.IsDivergent = IsDivergent;
15356 }
15357 checkForCycles(Node);
15358}
15359
15362 size_t Limit = SDNode::getMaxNumOperands();
15363 while (Vals.size() > Limit) {
15364 unsigned SliceIdx = Vals.size() - Limit;
15365 auto ExtractedTFs = ArrayRef<SDValue>(Vals).slice(SliceIdx, Limit);
15366 SDValue NewTF = getNode(ISD::TokenFactor, DL, MVT::Other, ExtractedTFs);
15367 Vals.erase(Vals.begin() + SliceIdx, Vals.end());
15368 Vals.emplace_back(NewTF);
15369 }
15370 return getNode(ISD::TokenFactor, DL, MVT::Other, Vals);
15371}
15372
15374 EVT VT, SDNodeFlags Flags) {
15375 switch (Opcode) {
15376 default:
15377 return SDValue();
15378 case ISD::ADD:
15379 case ISD::OR:
15380 case ISD::XOR:
15381 case ISD::UMAX:
15382 case ISD::MUL:
15383 case ISD::AND:
15384 case ISD::UMIN:
15385 case ISD::SMAX:
15386 case ISD::SMIN:
15388 VT);
15389 case ISD::FADD:
15390 // If flags allow, prefer positive zero since it's generally cheaper
15391 // to materialize on most targets.
15392 return getConstantFP(Flags.hasNoSignedZeros() ? 0.0 : -0.0, DL, VT);
15393 case ISD::FMUL:
15394 return getConstantFP(1.0, DL, VT);
15395 case ISD::FMINNUM:
15396 case ISD::FMAXNUM:
15397 case ISD::FMINIMUMNUM:
15398 case ISD::FMAXIMUMNUM: {
15399 // Neutral element for fminnum/fminimumnum is NaN, Inf or FLT_MAX,
15400 // depending on fast-math flags (FMF).
15401 const fltSemantics &Semantics = VT.getFltSemantics();
15402 APFloat NeutralAF = !Flags.hasNoNaNs() ? APFloat::getQNaN(Semantics) :
15403 !Flags.hasNoInfs() ? APFloat::getInf(Semantics) :
15404 APFloat::getLargest(Semantics);
15405 if (Opcode == ISD::FMAXNUM || Opcode == ISD::FMAXIMUMNUM)
15406 NeutralAF.changeSign();
15407
15408 return getConstantFP(NeutralAF, DL, VT);
15409 }
15410 case ISD::FMINIMUM:
15411 case ISD::FMAXIMUM: {
15412 // Neutral element for fminimum is Inf or FLT_MAX, depending on FMF.
15413 const fltSemantics &Semantics = VT.getFltSemantics();
15414 APFloat NeutralAF = !Flags.hasNoInfs() ? APFloat::getInf(Semantics)
15415 : APFloat::getLargest(Semantics);
15416 if (Opcode == ISD::FMAXIMUM)
15417 NeutralAF.changeSign();
15418
15419 return getConstantFP(NeutralAF, DL, VT);
15420 }
15421
15422 }
15423}
15424
15426 SDValue Acc, SDValue LHS,
15427 SDValue RHS) {
15428 EVT AccVT = Acc.getValueType();
15429 if (AccVT.isFloatingPoint()) {
15430 assert(Opc == ISD::PARTIAL_REDUCE_FMLA && "Unexpected opcode");
15431 SDValue NegRHS = getNode(ISD::FNEG, DL, RHS.getValueType(), RHS);
15432 return getNode(Opc, DL, AccVT, Acc, LHS, NegRHS);
15433 }
15436 "Unexpected opcode");
15437 SDValue NegAcc = getNegative(Acc, DL, AccVT);
15438 SDValue MLA = getNode(Opc, DL, AccVT, NegAcc, LHS, RHS);
15439 return getNegative(MLA, DL, AccVT);
15440}
15441
15442/// Helper used to make a call to a library function that has one argument of
15443/// pointer type.
15444///
15445/// Such functions include 'fegetmode', 'fesetenv' and some others, which are
15446/// used to get or set floating-point state. They have one argument of pointer
15447/// type, which points to the memory region containing bits of the
15448/// floating-point state. The value returned by such function is ignored in the
15449/// created call.
15450///
15451/// \param LibFunc Reference to library function (value of RTLIB::Libcall).
15452/// \param Ptr Pointer used to save/load state.
15453/// \param InChain Ingoing token chain.
15454/// \param Node Node being legalized
15455/// \returns Outgoing chain token.
15457 SDValue InChain, SDNode *Node) {
15458 assert(InChain.getValueType() == MVT::Other && "Expected token chain");
15459 RTLIB::LibcallImpl LibcallImpl =
15460 Libcalls->getLibcallImpl(static_cast<RTLIB::Libcall>(LibFunc));
15461 if (LibcallImpl == RTLIB::Unsupported) {
15462 getContext()->emitError(Twine("no libcall available for ") +
15463 Node->getOperationName(this));
15464 return InChain;
15465 }
15466
15468 Args.emplace_back(Ptr, Ptr.getValueType().getTypeForEVT(*getContext()));
15469 SDValue Callee =
15470 getExternalSymbol(LibcallImpl, TLI->getPointerTy(getDataLayout()));
15472 CLI.setDebugLoc(SDLoc(Node))
15473 .setChain(InChain)
15474 .setLibCallee(Libcalls->getLibcallImplCallingConv(LibcallImpl),
15475 Type::getVoidTy(*getContext()), Callee, std::move(Args));
15476 return TLI->LowerCallTo(CLI).second;
15477}
15478
15480 assert(From && To && "Invalid SDNode; empty source SDValue?");
15481 auto I = SDEI.find(From);
15482 if (I == SDEI.end())
15483 return;
15484
15485 // Use of operator[] on the DenseMap may cause an insertion, which invalidates
15486 // the iterator, hence the need to make a copy to prevent a use-after-free.
15487 NodeExtraInfo NEI = I->second;
15488 if (LLVM_LIKELY(!NEI.PCSections)) {
15489 // No deep copy required for the types of extra info set.
15490 //
15491 // FIXME: Investigate if other types of extra info also need deep copy. This
15492 // depends on the types of nodes they can be attached to: if some extra info
15493 // is only ever attached to nodes where a replacement To node is always the
15494 // node where later use and propagation of the extra info has the intended
15495 // semantics, no deep copy is required.
15496 SDEI[To] = std::move(NEI);
15497 return;
15498 }
15499
15500 const SDNode *EntrySDN = getEntryNode().getNode();
15501
15502 // We need to copy NodeExtraInfo to all _new_ nodes that are being introduced
15503 // through the replacement of From with To. Otherwise, replacements of a node
15504 // (From) with more complex nodes (To and its operands) may result in lost
15505 // extra info where the root node (To) is insignificant in further propagating
15506 // and using extra info when further lowering to MIR.
15507 //
15508 // In the first step pre-populate the visited set with the nodes reachable
15509 // from the old From node. This avoids copying NodeExtraInfo to parts of the
15510 // DAG that is not new and should be left untouched.
15511 SmallVector<const SDNode *> Leafs{From}; // Leafs reachable with VisitFrom.
15512 DenseSet<const SDNode *> FromReach; // The set of nodes reachable from From.
15513 auto VisitFrom = [&](auto &&Self, const SDNode *N, int MaxDepth) {
15514 if (MaxDepth == 0) {
15515 // Remember this node in case we need to increase MaxDepth and continue
15516 // populating FromReach from this node.
15517 Leafs.emplace_back(N);
15518 return;
15519 }
15520 if (!FromReach.insert(N).second)
15521 return;
15522 for (const SDValue &Op : N->op_values())
15523 Self(Self, Op.getNode(), MaxDepth - 1);
15524 };
15525
15526 // Copy extra info to To and all its transitive operands (that are new).
15528 auto DeepCopyTo = [&](auto &&Self, const SDNode *N) {
15529 if (FromReach.contains(N))
15530 return true;
15531 if (!Visited.insert(N).second)
15532 return true;
15533 if (EntrySDN == N)
15534 return false;
15535 for (const SDValue &Op : N->op_values()) {
15536 if (N == To && Op.getNode() == EntrySDN) {
15537 // Special case: New node's operand is the entry node; just need to
15538 // copy extra info to new node.
15539 break;
15540 }
15541 if (!Self(Self, Op.getNode()))
15542 return false;
15543 }
15544 // Copy only if entry node was not reached.
15545 SDEI[N] = std::move(NEI);
15546 return true;
15547 };
15548
15549 // We first try with a lower MaxDepth, assuming that the path to common
15550 // operands between From and To is relatively short. This significantly
15551 // improves performance in the common case. The initial MaxDepth is big
15552 // enough to avoid retry in the common case; the last MaxDepth is large
15553 // enough to avoid having to use the fallback below (and protects from
15554 // potential stack exhaustion from recursion).
15555 for (int PrevDepth = 0, MaxDepth = 16; MaxDepth <= 1024;
15556 PrevDepth = MaxDepth, MaxDepth *= 2, Visited.clear()) {
15557 // StartFrom is the previous (or initial) set of leafs reachable at the
15558 // previous maximum depth.
15560 std::swap(StartFrom, Leafs);
15561 for (const SDNode *N : StartFrom)
15562 VisitFrom(VisitFrom, N, MaxDepth - PrevDepth);
15563 if (LLVM_LIKELY(DeepCopyTo(DeepCopyTo, To)))
15564 return;
15565 // This should happen very rarely (reached the entry node).
15566 LLVM_DEBUG(dbgs() << __func__ << ": MaxDepth=" << MaxDepth << " too low\n");
15567 assert(!Leafs.empty());
15568 }
15569
15570 // This should not happen - but if it did, that means the subgraph reachable
15571 // from From has depth greater or equal to maximum MaxDepth, and VisitFrom()
15572 // could not visit all reachable common operands. Consequently, we were able
15573 // to reach the entry node.
15574 errs() << "warning: incomplete propagation of SelectionDAG::NodeExtraInfo\n";
15575 assert(false && "From subgraph too complex - increase max. MaxDepth?");
15576 // Best-effort fallback if assertions disabled.
15577 SDEI[To] = std::move(NEI);
15578}
15579
15581 assert(VT.isVector() && "Can only unroll vector types!");
15582 if (VT.isFixedLengthVector())
15583 return VT.getVectorNumElements();
15584
15585 const MachineFunction &MF = getMachineFunction();
15586 const Function &F = MF.getFunction();
15587
15588 APInt MaxVScale = getVScaleRange(&F, sizeof(unsigned) * 8).getUnsignedMax();
15589 if (MaxVScale.ugt(getSelectionDAGOptions().vscale_unroll_limit))
15590 return 0;
15591
15592 bool Overflow;
15593 APInt MinNElts(sizeof(unsigned) * 8, VT.getVectorMinNumElements());
15594 APInt MaxNElts = MinNElts.umul_ov(MaxVScale, Overflow);
15595 if (Overflow)
15596 return 0;
15597
15598 return MaxNElts.getZExtValue();
15599}
15600
15602 ArrayRef<SDValue> Scalars) {
15603 assert(Scalars.size() == getMaxRuntimeNumElements(VT) &&
15604 "Element count mismatch!");
15605 if (VT.isFixedLengthVector())
15606 return getBuildVector(VT, DL, Scalars);
15607
15608 SDValue Vec = getPOISON(VT);
15609 // Iterate in reverse so result remains poison until we encounter a lane that
15610 // exists, after which all lower-numbered lanes must also exist.
15611 for (unsigned IdxVal : reverse(seq(Scalars.size())))
15612 Vec = getInsertVectorElt(DL, Vec, Scalars[IdxVal], IdxVal);
15613
15614 return Vec;
15615}
15616
15617#ifndef NDEBUG
15618static void checkForCyclesHelper(const SDNode *N,
15621 const llvm::SelectionDAG *DAG) {
15622 // If this node has already been checked, don't check it again.
15623 if (Checked.count(N))
15624 return;
15625
15626 // If a node has already been visited on this depth-first walk, reject it as
15627 // a cycle.
15628 if (!Visited.insert(N).second) {
15629 errs() << "Detected cycle in SelectionDAG\n";
15630 dbgs() << "Offending node:\n";
15631 N->dumprFull(DAG); dbgs() << "\n";
15632 abort();
15633 }
15634
15635 for (const SDValue &Op : N->op_values())
15636 checkForCyclesHelper(Op.getNode(), Visited, Checked, DAG);
15637
15638 Checked.insert(N);
15639 Visited.erase(N);
15640}
15641#endif
15642
15644 const llvm::SelectionDAG *DAG,
15645 bool force) {
15646#ifndef NDEBUG
15647 bool check = force;
15648#ifdef EXPENSIVE_CHECKS
15649 check = true;
15650#endif // EXPENSIVE_CHECKS
15651 if (check) {
15652 assert(N && "Checking nonexistent SDNode");
15655 checkForCyclesHelper(N, visited, checked, DAG);
15656 }
15657#endif // !NDEBUG
15658}
15659
15660void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) {
15661 checkForCycles(DAG->getRoot().getNode(), DAG, force);
15662}
return SDValue()
const TargetLowering & TLI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
uint64_t Imm
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:665
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:621
#define LLVM_LIKELY(EXPR)
Definition Compiler.h:347
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:550
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
MachineBasicBlock * Folded
SmallVector< MachineOperand, 4 > Cond
int64_t C1
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 SDValue getMemsetStringVal(EVT VT, const SDLoc &dl, SelectionDAG &DAG, const TargetLowering &TLI, const ConstantDataArraySlice &Slice)
getMemsetStringVal - Similar to getMemsetValue.
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 TargetLoweringBase::ArgListEntry getAtomicMemOpSizeArg(SelectionDAG *DAG, const SDLoc &dl, SDValue Size)
static bool hasSpecialNszSemantics(unsigned Opcode)
Return true if the standard nsz semantics may not apply for this opcode.
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 bool areNonVolatileConsecutiveLoadsOrStores(LSBaseSDNode *LS, LSBaseSDNode *Base, TypeSize Bytes, int Dist, const SelectionDAG &DAG)
static APInt getIntegerIdentity(unsigned Opcode, unsigned BitWidth)
static SDValue getMemIntrinsicSize(SelectionDAG &DAG, const SDLoc &dl, SDValue Size, unsigned DstAS, unsigned SrcAS)
The length of a memory intrinsic (e.g.
static void checkAddrSpaceIsValidForLibcall(const TargetLowering *TLI, const DataLayout &DL, unsigned AS)
static SDValue foldCONCAT_VECTORS(const SDLoc &DL, EVT VT, ArrayRef< SDValue > Ops, SelectionDAG &DAG)
Try to simplify vector concatenation to an input value, undef, or build vector.
static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info, SelectionDAG &DAG, SDValue Ptr, int64_t Offset=0)
InferPointerInfo - If the specified ptr/offset is a frame index, infer a MachinePointerInfo record fr...
static bool isInTailCallPositionWrapper(const CallInst *CI, const SelectionDAG *SelDAG, bool AllowReturnsFirstArg)
static bool keyMatches(const SDNodeKey &Key, const SDNode &N)
static bool 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 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
LLVM_ABI opStatus convert(const fltSemantics &ToSemantics, roundingMode RM, bool *losesInfo)
Definition APFloat.cpp:6045
bool isNegative() const
Definition APFloat.h:1583
bool isFinite() const
Definition APFloat.h:1588
opStatus convertFromAPInt(const APInt &Input, bool IsSigned, roundingMode RM)
Definition APFloat.h:1451
bool isZero() const
Definition APFloat.h:1579
LLVM_READONLY bool isOne() const
Definition APFloat.h:1676
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
bool isPosZero() const
Definition APFloat.h:1594
bool isNegZero() const
Definition APFloat.h:1595
void changeSign()
Definition APFloat.h:1401
static APFloat getNaN(const fltSemantics &Sem, bool Negative=false, uint64_t payload=0)
Factory for NaN values.
Definition APFloat.h:1213
bool isInfinity() const
Definition APFloat.h:1580
Class for arbitrary precision integers.
Definition APInt.h:78
LLVM_ABI APInt umul_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:2009
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
Definition APInt.h:230
void clearBit(unsigned BitPosition)
Set a given bit to 0.
Definition APInt.h:1426
LLVM_ABI APInt zext(unsigned width) const
Zero extend to a new width.
Definition APInt.cpp:1057
static APInt getSignMask(unsigned BitWidth)
Get the SignMask for a specific bit width.
Definition APInt.h:225
bool isMinSignedValue() const
Determine if this is the smallest signed value.
Definition APInt.h:419
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1560
unsigned popcount() const
Count the number of bits set.
Definition APInt.h:1690
LLVM_ABI APInt zextOrTrunc(unsigned width) const
Zero extend or truncate to width.
Definition APInt.cpp:1078
unsigned getActiveBits() const
Compute the number of active bits in the value.
Definition APInt.h:1532
LLVM_ABI APInt trunc(unsigned width) const
Truncate to new width.
Definition APInt.cpp:970
void setBit(unsigned BitPosition)
Set the given bit to 1 whose position is given as "bitPosition".
Definition APInt.h:1350
APInt abs() const
Get the absolute value.
Definition APInt.h:1815
bool isAllOnes() const
Determine if all bits are set. This is true for zero-width values.
Definition APInt.h:367
bool ugt(const APInt &RHS) const
Unsigned greater than comparison.
Definition APInt.h:1186
static APInt getBitsSet(unsigned numBits, unsigned loBit, unsigned hiBit)
Get a value with a block of bits set.
Definition APInt.h:254
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition APInt.h:376
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1508
bool ult(const APInt &RHS) const
Unsigned less than comparison.
Definition APInt.h:1115
static APInt getSignedMaxValue(unsigned numBits)
Gets maximum signed value of APInt for a specific bit width.
Definition APInt.h:205
bool isNegative() const
Determine sign of this APInt.
Definition APInt.h:325
LLVM_ABI APInt reverseBits() const
Definition APInt.cpp:786
void ashrInPlace(unsigned ShiftAmt)
Arithmetic right-shift this APInt by ShiftAmt in place.
Definition APInt.h:836
bool sle(const APInt &RHS) const
Signed less or equal comparison.
Definition APInt.h:1170
unsigned countr_zero() const
Count the number of trailing zero bits.
Definition APInt.h:1659
unsigned getNumSignBits() const
Computes the number of leading bits of this APInt that are equal to its sign bit.
Definition APInt.h:1648
unsigned countl_zero() const
The APInt version of std::countl_zero.
Definition APInt.h:1618
static LLVM_ABI APInt getSplat(unsigned NewLen, const APInt &V)
Return a value containing V broadcasted over NewLen bits.
Definition APInt.cpp:648
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
Definition APInt.h:215
LLVM_ABI APInt sextOrTrunc(unsigned width) const
Sign extend or truncate to width.
Definition APInt.cpp:1086
LLVM_ABI void insertBits(const APInt &SubBits, unsigned bitPosition)
Insert the bits from a smaller APInt starting at bitPosition.
Definition APInt.cpp:393
unsigned logBase2() const
Definition APInt.h:1781
LLVM_ABI APInt multiplicativeInverse() const
Definition APInt.cpp:1303
bool isNonNegative() const
Determine if this APInt Value is non-negative (>= 0)
Definition APInt.h:330
LLVM_ABI APInt sext(unsigned width) const
Sign extend to a new width.
Definition APInt.cpp:1030
void setBits(unsigned loBit, unsigned hiBit)
Set the bits from loBit (inclusive) to hiBit (exclusive) to 1.
Definition APInt.h:1387
APInt shl(unsigned shiftAmt) const
Left-shift function.
Definition APInt.h:875
LLVM_ABI APInt byteSwap() const
Definition APInt.cpp:764
bool isSubsetOf(const APInt &RHS) const
This operation checks that all bits set in this APInt are also set in RHS.
Definition APInt.h:1261
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
Definition APInt.h:436
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Constructs an APInt value that has the bottom loBitsSet bits set.
Definition APInt.h:302
void clearBits(unsigned LoBit, unsigned HiBit)
Clear the bits from LoBit (inclusive) to HiBit (exclusive) to 0.
Definition APInt.h:1437
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition APInt.h:196
LLVM_ABI APInt extractBits(unsigned numBits, unsigned bitPosition) const
Return an APInt with the extracted bits [bitPosition,bitPosition+numBits).
Definition APInt.cpp:478
bool isOne() const
Determine if this is a value of 1.
Definition APInt.h:385
static APInt getBitsSetFrom(unsigned numBits, unsigned loBit)
Constructs an APInt value that has a contiguous range of bits set.
Definition APInt.h:282
static APInt getOneBitSet(unsigned numBits, unsigned BitNo)
Return an APInt with exactly one bit set in the result.
Definition APInt.h:235
void lshrInPlace(unsigned ShiftAmt)
Logical right-shift this APInt by ShiftAmt in place.
Definition APInt.h:860
APInt lshr(unsigned shiftAmt) const
Logical right-shift function.
Definition APInt.h:853
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
Definition APInt.h:1225
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, and fixed/scalable offsets.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
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:410
void resize(unsigned N, bool t=false)
Grow or shrink the bitvector.
Definition BitVector.h:356
void clear()
Removes all bits from the bitvector.
Definition BitVector.h:350
BitVector & set()
Set all bits in the bitvector.
Definition BitVector.h:367
bool none() const
Returns true if none of the bits are set.
Definition BitVector.h:208
size_type size() const
Returns the number of bits in this bitvector.
Definition BitVector.h:179
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:44
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:283
static constexpr ElementCount getFixed(ScalarTy MinVal)
Definition TypeSize.h:306
constexpr bool isScalar() const
Exactly one element.
Definition TypeSize.h:317
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:705
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.
bool isUnknown() const
KnownFPClass intersectWith(const KnownFPClass &RHS) const
static KnownFPClass getEmpty()
static LLVM_ABI KnownFPClass bitcast(const fltSemantics &FltSemantics, const KnownBits &Bits)
Report known values for a bitcast into a float with provided semantics.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
LLVM_ABI void emitError(const Instruction *I, const Twine &ErrorStr)
emitError - Emit an error message to the currently installed error handler with optional location inf...
Base class for LoadSDNode and StoreSDNode.
Tracks which library functions to use for a particular subtarget or function.
CallingConv::ID getLibcallImplCallingConv(RTLIB::LibcallImpl Call) const
Get the CallingConv that should be used for the specified libcall.
RTLIB::LibcallImpl getLibcallImpl(RTLIB::Libcall Call) const
Return the lowering's selection of implementation call for Call.
This SDNode is used for LIFETIME_START/LIFETIME_END values.
This class is used to represent ISD::LOAD nodes.
static LocationSize precise(uint64_t Value)
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition MCSymbol.h:42
Metadata node.
Definition Metadata.h:1081
const MDOperand & getOperand(unsigned I) const
Definition Metadata.h:1437
Machine Value Type.
SimpleValueType SimpleTy
static LLVM_ABI MVT getVT(Type *Ty, bool HandleUnknown=false)
Return the value type corresponding to the specified type.
bool bitsLT(MVT VT) const
Return true if this has less bits than VT.
static MVT getIntegerVT(unsigned BitWidth)
Abstract base class for all machine specific constantpool value subclasses.
virtual void addSelectionDAGCSEId(FoldingSetNodeID &ID)=0
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted.
LLVM_ABI int CreateStackObject(uint64_t Size, Align Alignment, bool isSpillSlot, const AllocaInst *Alloca=nullptr, uint8_t ID=0)
Create a new statically sized stack object, returning a nonnegative identifier to represent it.
Align getObjectAlign(int ObjectIdx) const
Return the alignment of the specified stack object.
bool isFixedObjectIndex(int ObjectIdx) const
Returns true if the specified index corresponds to a fixed stack object.
void setObjectAlignment(int ObjectIdx, Align Alignment)
setObjectAlignment - Change the alignment of the specified stack object.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
Function & getFunction()
Return the LLVM function that this machine code represents.
const TargetMachine & getTarget() const
getTarget - Return the target machine this machine code is compiled with
A description of a memory reference used in the backend.
const MDNode * getRanges() const
Return the range tag for the memory reference.
Flags
Flags values. These may be or'd together.
@ MOVolatile
The memory access is volatile.
@ MODereferenceable
The memory access is dereferenceable (i.e., doesn't trap).
@ MOLoad
The memory access reads data.
@ MOInvariant
The memory access always returns the same value (or traps).
@ MOStore
The memory access writes data.
const MachinePointerInfo & getPointerInfo() const
Flags getFlags() const
Return the raw flags of the source value,.
An SDNode that represents everything that will be needed to construct a MachineInstr.
This class is used to represent an MGATHER node.
This class is used to represent an MLOAD node.
This class is used to represent an MSTORE node.
This SDNode is used for target intrinsics that touch memory and need an associated MachineMemOperand.
This is an abstract virtual class for memory operations.
size_t getNumMemOperands() const
Return the number of memory operands.
LLVM_ABI MemSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl, SDVTList VTs, EVT memvt, PointerUnion< MachineMemOperand *, MachineMemOperand ** > memrefs)
Constructor that supports single or multiple MMOs.
PointerUnion< MachineMemOperand *, MachineMemOperand ** > MemRefs
Memory reference information.
MachineMemOperand * getMemOperand() const
Return the unique MachineMemOperand object describing the memory reference performed by operation.
const MachinePointerInfo & getPointerInfo() const
ArrayRef< MachineMemOperand * > memoperands() const
Return the memory operands for this node.
unsigned getRawSubclassData() const
Return the SubclassData value, without HasDebugValue.
EVT getMemoryVT() const
Return the type of the in-memory value.
Representation for a specific memory location.
Root of the metadata hierarchy.
Definition Metadata.h:64
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
Function * getFunction(StringRef Name) const
Look up the specified function in the module symbol table.
Definition Module.cpp:254
Represent a mutable reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:294
Class to represent pointers.
static PointerType * getUnqual(LLVMContext &C)
This constructs an opaque pointer to an object in the default address space (address space zero).
static LLVM_ABI PointerType * get(LLVMContext &C, unsigned AddressSpace)
This constructs an opaque pointer to an object in a numbered address space.
Definition Type.cpp:887
unsigned getAddressSpace() const
Return the address space of the Pointer type.
A discriminated union of two or more pointer types, with the discriminator in the low bits of the poi...
bool isNull() const
Test if the pointer held in the union is null, regardless of which type it is.
Analysis providing profile information.
void Deallocate(SubClass *E)
Deallocate - Release storage for the pointed-to object.
Wrapper class representing virtual and physical registers.
Definition Register.h:20
Keeps track of dbg_value information through SDISel.
LLVM_ABI void add(SDDbgValue *V, bool isParameter)
LLVM_ABI void erase(const SDNode *Node)
Invalidate all DbgValues attached to the node and remove it from the Node-to-DbgValues map.
Holds the information from a dbg_label node through SDISel.
Holds the information for a single machine location through SDISel; either an SDNode,...
static SDDbgOperand fromNode(SDNode *Node, unsigned ResNo)
static SDDbgOperand fromFrameIdx(unsigned FrameIdx)
static SDDbgOperand fromVReg(Register VReg)
static SDDbgOperand fromConst(const Value *Const)
@ SDNODE
Value is the result of an expression.
Holds the information from a dbg_value node through SDISel.
Wrapper class for IR location info (IR ordering and DebugLoc) to be passed into SDNode creation funct...
const DebugLoc & getDebugLoc() const
unsigned getIROrder() const
This class provides iterator support for SDUse operands that use a specific SDNode.
Represents one node in the SelectionDAG.
const APInt & getAsAPIntVal() const
Helper method returns the APInt value of a ConstantSDNode.
bool isMachineOpcode() const
Test if this node has a post-isel opcode, directly corresponding to a MachineInstr opcode.
LLVM_ABI void dumprFull(const SelectionDAG *G=nullptr) const
printrFull to dbgs().
unsigned getOpcode() const
Return the SelectionDAG opcode value for this node.
bool isDivergent() const
LLVM_ABI bool isOnlyUserOf(const SDNode *N) const
Return true if this node is the only use of N.
iterator_range< value_op_iterator > op_values() const
unsigned getIROrder() const
Return the node ordering.
static constexpr size_t getMaxNumOperands()
Return the maximum number of operands that a SDNode can hold.
iterator_range< use_iterator > uses()
MemSDNodeBitfields MemSDNodeBits
bool getHasDebugValue() const
SDNodeFlags getFlags() const
void setNodeId(int Id)
Set unique node id.
LLVM_ABI void intersectFlagsWith(const SDNodeFlags Flags)
Clear any flags in this node that aren't also set in Flags.
static bool hasPredecessorHelper(const SDNode *N, SmallPtrSetImpl< const SDNode * > &Visited, SmallVectorImpl< const SDNode * > &Worklist, unsigned int MaxSteps=0, bool TopologicalPrune=false)
Returns true if N is a predecessor of any node in Worklist.
uint64_t getAsZExtVal() const
Helper method returns the zero-extended integer value of a ConstantSDNode.
bool use_empty() const
Return true if there are no uses of this node.
unsigned getNumValues() const
Return the number of values defined/returned by this operator.
unsigned getNumOperands() const
Return the number of values used by this operation.
const SDValue & getOperand(unsigned Num) const
static LLVM_ABI bool areOnlyUsersOf(ArrayRef< const SDNode * > Nodes, const SDNode *N)
Return true if all the users of N are contained in Nodes.
use_iterator use_begin() const
Provide iteration support to walk over all uses of an SDNode.
LLVM_ABI bool isOperandOf(const SDNode *N) const
Return true if this node is an operand of N.
const APInt & getConstantOperandAPInt(unsigned Num) const
Helper method returns the APInt of a ConstantSDNode operand.
std::optional< APInt > bitcastToAPInt() const
LLVM_ABI bool hasPredecessor(const SDNode *N) const
Return true if N is a predecessor of this node.
LLVM_ABI bool hasAnyUseOfValue(unsigned Value) const
Return true if there are any use of the indicated value.
EVT getValueType(unsigned ResNo) const
Return the type of a specified result.
bool isUndef() const
Returns true if the node type is UNDEF or POISON.
op_iterator op_end() const
op_iterator op_begin() const
static use_iterator use_end()
LLVM_ABI void DropOperands()
Release the operands and set this node to have zero operands.
SDNode(unsigned Opc, unsigned Order, DebugLoc dl, SDVTList VTs)
Create an SDNode.
Represents a use of a SDNode.
SDNode * getUser()
This returns the SDNode that contains this Use.
Unlike LLVM values, Selection DAG nodes may return multiple values as the result of a computation.
bool isUndef() const
SDNode * getNode() const
get the SDNode which holds the desired result
bool hasOneUse() const
Return true if there is exactly one node using value ResNo of Node, in exactly one operand.
LLVM_ABI bool isOperandOf(const SDNode *N) const
Return true if the referenced return value is an operand of N.
SDValue()=default
LLVM_ABI bool reachesChainWithoutSideEffects(SDValue Dest, unsigned Depth=2) const
Return true if this operand (which must be a chain) reaches the specified operand without crossing an...
SDValue getValue(unsigned R) const
EVT getValueType() const
Return the ValueType of the referenced return value.
TypeSize getValueSizeInBits() const
Returns the size of the value in bits.
const SDValue & getOperand(unsigned i) const
bool use_empty() const
Return true if there are no nodes using value ResNo of Node.
const APInt & getConstantOperandAPInt(unsigned i) const
uint64_t getScalarValueSizeInBits() const
unsigned getResNo() const
get the index which selects a specific result in the SDNode
uint64_t getConstantOperandVal(unsigned i) const
unsigned getOpcode() const
virtual void verifyTargetNode(const SelectionDAG &DAG, const SDNode *N) const
Checks that the given target-specific node is valid. Aborts if it is not.
This is used to represent a portion of an LLVM function in a low-level Data Dependence DAG representa...
LLVM_ABI SDValue getElementCount(const SDLoc &DL, EVT VT, ElementCount EC)
LLVM_ABI Align getReducedAlign(EVT VT, bool UseABI)
In most cases this function returns the ABI alignment for a given type, except for illegal vector typ...
LLVM_ABI SDValue getShiftAmountOperand(EVT LHSTy, SDValue Op)
Return the specified value casted to the target's desired shift amount type.
LLVM_ABI std::pair< SDValue, SDValue > getMemccpy(SDValue Chain, const SDLoc &dl, SDValue Dst, SDValue Src, SDValue C, SDValue Size, const CallInst *CI)
Lower a memccpy operation into a target library call and return the resulting chain and call result a...
LLVM_ABI SDValue emitStackConvert(SDValue SrcOp, EVT SlotVT, EVT DestVT, const SDLoc &DL, SDValue Chain)
Emit a store/load combination to the stack.
LLVM_ABI bool isKnownNeverLogicalZero(SDValue Op, const APInt &DemandedElts, unsigned Depth=0) const
Test whether the given floating point SDValue (or all elements of it, if it is a vector) is known to ...
LLVM_ABI SDValue getExtLoadVP(ISD::LoadExtType ExtType, const SDLoc &dl, EVT VT, SDValue Chain, SDValue Ptr, SDValue Mask, SDValue EVL, MachinePointerInfo PtrInfo, EVT MemVT, MaybeAlign Alignment, MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo, bool IsExpanding=false)
SDValue getExtractVectorElt(const SDLoc &DL, EVT VT, SDValue Vec, unsigned Idx)
Extract element at Idx from Vec.
LLVM_ABI SDValue getSplatSourceVector(SDValue V, int &SplatIndex)
If V is a splatted value, return the source vector and its splat index.
LLVM_ABI SDValue getLabelNode(unsigned Opcode, const SDLoc &dl, SDValue Root, MCSymbol *Label)
LLVM_ABI OverflowKind computeOverflowForUnsignedSub(SDValue N0, SDValue N1) const
Determine if the result of the unsigned sub of 2 nodes can overflow.
LLVM_ABI unsigned ComputeMaxSignificantBits(SDValue Op, unsigned Depth=0) const
Get the upper bound on bit size for this Value Op as a signed integer.
const SDValue & getRoot() const
Return the root tag of the SelectionDAG.
LLVM_ABI std::pair< SDValue, SDValue > getStrlen(SDValue Chain, const SDLoc &dl, SDValue Src, const CallInst *CI)
Lower a strlen operation into a target library call and return the resulting chain and call result as...
LLVM_ABI SDValue getMaskedGather(SDVTList VTs, EVT MemVT, const SDLoc &dl, ArrayRef< SDValue > Ops, MachineMemOperand *MMO, ISD::MemIndexType IndexType, ISD::LoadExtType ExtTy)
LLVM_ABI unsigned getHasPredecessorMaxSteps() const
LLVM_ABI SDValue FoldSetCC(EVT VT, SDValue N1, SDValue N2, ISD::CondCode Cond, const SDLoc &dl, SDNodeFlags Flags={})
Constant fold a setcc to true or false.
bool isKnownNeverSNaN(SDValue Op, const APInt &DemandedElts, unsigned Depth=0) const
LLVM_ABI SDValue makeStateFunctionCall(unsigned LibFunc, SDValue Ptr, SDValue InChain, SDNode *Node)
Helper used to make a call to a library function that has one argument of pointer type.
LLVM_ABI std::optional< bool > isBoolConstant(SDValue N) const
Check if a value \op N is a constant using the target's BooleanContent for its type.
LLVM_ABI SDValue getStackArgumentTokenFactor(SDValue Chain)
Compute a TokenFactor to force all the incoming stack arguments to be loaded from the stack.
const TargetSubtargetInfo & getSubtarget() const
LLVM_ABI ConstantRange computeConstantRange(SDValue Op, bool ForSigned, unsigned Depth=0) const
Determine the possible constant range of an integer or vector of integers.
LLVM_ABI SDValue getMergeValues(ArrayRef< SDValue > Ops, const SDLoc &dl)
Create a MERGE_VALUES node from the given operands.
LLVM_ABI SDVTList getVTList(EVT VT)
Return an SDVTList that represents the list of values specified.
LLVM_ABI SDValue getShiftAmountConstant(uint64_t Val, EVT VT, const SDLoc &DL)
LLVM_ABI void updateDivergence(SDNode *N)
LLVM_ABI SDValue getSplatValue(SDValue V, bool LegalTypes=false)
If V is a splat vector, return its scalar source operand by extracting that element from the source v...
LLVM_ABI SDValue getAllOnesConstant(const SDLoc &DL, EVT VT, bool IsTarget=false, bool IsOpaque=false)
LLVM_ABI MachineSDNode * getMachineNode(unsigned Opcode, const SDLoc &dl, EVT VT)
These are used for target selectors to create a new node with specified return type(s),...
LLVM_ABI void ExtractVectorElements(SDValue Op, SmallVectorImpl< SDValue > &Args, unsigned Start=0, unsigned Count=0, EVT EltVT=EVT())
Append the extracted elements from Start to Count out of the vector Op in Args.
LLVM_ABI SDValue getAtomicMemset(SDValue Chain, const SDLoc &dl, SDValue Dst, SDValue Value, SDValue Size, Type *SizeTy, unsigned ElemSz, bool isTailCall, MachinePointerInfo DstPtrInfo)
LLVM_ABI SDValue getAtomicLoad(ISD::LoadExtType ExtType, const SDLoc &dl, EVT MemVT, EVT VT, SDValue Chain, SDValue Ptr, MachineMemOperand *MMO)
LLVM_ABI SDNode * getNodeIfExists(unsigned Opcode, SDVTList VTList, ArrayRef< SDValue > Ops, const SDNodeFlags Flags, bool AllowCommute=false)
Get the specified node if it's already available, or else return NULL.
LLVM_ABI SDValue getPseudoProbeNode(const SDLoc &Dl, SDValue Chain, uint64_t Guid, uint64_t Index, uint32_t Attr)
Creates a PseudoProbeSDNode with function GUID Guid and the index of the block Index it is probing,...
LLVM_ABI SDValue getFreeze(SDValue V)
Return a freeze using the SDLoc of the value operand.
LLVM_ABI SDNode * SelectNodeTo(SDNode *N, unsigned MachineOpc, EVT VT)
These are used for target selectors to mutate the specified node to have the specified return type,...
LLVM_ABI const BasicBlock * getBasicBlock() const
LLVM_ABI SelectionDAG(const TargetMachine &TM, CodeGenOptLevel)
LLVM_ABI SDValue getMemset(SDValue Chain, const SDLoc &dl, SDValue Dst, SDValue Src, SDValue Size, Align Alignment, bool isVol, bool AlwaysInline, const CallInst *CI, MachinePointerInfo DstPtrInfo, const AAMDNodes &AAInfo=AAMDNodes())
LLVM_ABI SDValue getConstantPool(const Constant *C, EVT VT, MaybeAlign Align=std::nullopt, int Offs=0, bool isT=false, unsigned TargetFlags=0)
LLVM_ABI SDValue getStridedLoadVP(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &DL, SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Stride, SDValue Mask, SDValue EVL, EVT MemVT, MachineMemOperand *MMO, bool IsExpanding=false)
LLVM_ABI SDValue getAtomicCmpSwap(unsigned Opcode, const SDLoc &dl, EVT MemVT, SDVTList VTs, SDValue Chain, SDValue Ptr, SDValue Cmp, SDValue Swp, MachineMemOperand *MMO)
Gets a node for an atomic cmpxchg op.
LLVM_ABI SDValue makeEquivalentMemoryOrdering(SDValue OldChain, SDValue NewMemOpChain)
If an existing load has uses of its chain, create a token factor node with that chain and the new mem...
LLVM_ABI bool isConstantIntBuildVectorOrConstantInt(SDValue N, bool AllowOpaques=true) const
Test whether the given value is a constant int or similar node.
LLVM_ABI void ReplaceAllUsesOfValuesWith(const SDValue *From, const SDValue *To, unsigned Num)
Like ReplaceAllUsesOfValueWith, but for multiple values at once.
LLVM_ABI SDValue getJumpTableDebugInfo(int JTI, SDValue Chain, const SDLoc &DL)
LLVM_ABI SDValue getSymbolFunctionGlobalAddress(SDValue Op, Function **TargetFunction=nullptr)
Return a GlobalAddress of the function from the current module with name matching the given ExternalS...
LLVM_ABI std::optional< unsigned > getValidMaximumShiftAmount(SDValue V, const APInt &DemandedElts, unsigned Depth=0) const
If a SHL/SRA/SRL node V has shift amounts that are all less than the element bit-width of the shift n...
LLVM_ABI bool areNonVolatileConsecutiveLoads(LoadSDNode *LD, LoadSDNode *Base, TypeSize Bytes, int Dist) const
Return true if loads are next to each other and can be merged.
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.
LLVM_ABI bool haveNoCommonBitsSet(SDValue A, SDValue B) const
Return true if A and B have no common bits set.
LLVM_ABI SDValue getAddrSpaceCast(const SDLoc &dl, EVT VT, SDValue Ptr, unsigned SrcAS, unsigned DestAS, const SDNodeFlags Flags=SDNodeFlags())
Return an AddrSpaceCastSDNode.
SDValue getExtractSubvector(const SDLoc &DL, EVT VT, SDValue Vec, unsigned Idx)
Return the VT typed sub-vector of Vec at Idx.
LLVM_ABI bool cannotBeOrderedNegativeFP(SDValue Op) const
Test whether the given float value is known to be positive.
LLVM_ABI SDValue getRegister(Register Reg, EVT VT)
LLVM_ABI bool calculateDivergence(SDNode *N)
LLVM_ABI std::pair< SDValue, SDValue > getStrcmp(SDValue Chain, const SDLoc &dl, SDValue S0, SDValue S1, const CallInst *CI)
Lower a strcmp operation into a target library call and return the resulting chain and call result as...
LLVM_ABI SDValue getGetFPEnv(SDValue Chain, const SDLoc &dl, SDValue Ptr, EVT MemVT, MachineMemOperand *MMO)
LLVM_ABI SDValue getAssertAlign(const SDLoc &DL, SDValue V, Align A)
Return an AssertAlignSDNode.
LLVM_ABI SDNode * mutateStrictFPToFP(SDNode *Node)
Mutate the specified strict FP node to its non-strict equivalent, unlinking the node from its chain a...
LLVM_ABI bool canIgnoreSignBitOfZero(const SDUse &Use) const
Check if the user of Use produces the same result regardless of the sign of a zero in the used float ...
LLVM_ABI bool SignBitIsZeroFP(SDValue Op, unsigned Depth=0) const
Return true if the sign bit of Op is known to be zero, for a floating-point value.
LLVM_ABI SDValue getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef< SDValue > Ops, EVT MemVT, MachinePointerInfo PtrInfo, Align Alignment, MachineMemOperand::Flags Flags=MachineMemOperand::MOLoad|MachineMemOperand::MOStore, LocationSize Size=LocationSize::precise(0), const AAMDNodes &AAInfo=AAMDNodes())
Creates a MemIntrinsicNode that may produce a result and takes a list of operands.
SDValue getInsertSubvector(const SDLoc &DL, SDValue Vec, SDValue SubVec, unsigned Idx)
Insert SubVec at the Idx element of Vec.
LLVM_ABI SDValue getStepVector(const SDLoc &DL, EVT ResVT, const APInt &StepVal)
Returns a vector of type ResVT whose elements contain the linear sequence <0, Step,...
SDValue getSetCC(const SDLoc &DL, EVT VT, SDValue LHS, SDValue RHS, ISD::CondCode Cond, SDValue Chain=SDValue(), bool IsSignaling=false, SDNodeFlags Flags={})
Helper function to make it easier to build SetCC's if you just have an ISD::CondCode instead of an SD...
LLVM_ABI SDValue getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, SDValue Chain, SDValue Ptr, SDValue Val, MachineMemOperand *MMO)
Gets a node for an atomic op, produces result (if relevant) and chain and takes 2 operands.
LLVM_ABI Align getEVTAlign(EVT MemoryVT) const
Compute the default alignment value for the given type.
LLVM_ABI bool shouldOptForSize() const
LLVM_ABI bool hasSwiftErrorArg() const
LLVM_ABI SDValue buildVectorFromUnrolledParts(EVT VT, const SDLoc &DL, ArrayRef< SDValue > Scalars)
Returns a vector constructed from the scalar values in order.
LLVM_ABI SDValue getNOT(const SDLoc &DL, SDValue Val, EVT VT)
Create a bitwise NOT operation as (XOR Val, -1).
LLVM_ABI SDValue getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst, SDValue Src, SDValue Size, Align DstAlign, Align SrcAlign, bool isVol, bool AlwaysInline, const CallInst *CI, std::optional< bool > OverrideTailCall, MachinePointerInfo DstPtrInfo, MachinePointerInfo SrcPtrInfo, const AAMDNodes &AAInfo=AAMDNodes(), BatchAAResults *BatchAA=nullptr)
const TargetLowering & getTargetLoweringInfo() const
LLVM_ABI bool isEqualTo(SDValue A, SDValue B) const
Test whether two SDValues are known to compare equal.
static constexpr unsigned MaxRecursionDepth
LLVM_ABI unsigned getMaxRuntimeNumElements(EVT VT) const
Returns the maximum runtime number of elements in VT if known, or 0 otherwise.
LLVM_ABI SDValue getStridedStoreVP(SDValue Chain, const SDLoc &DL, SDValue Val, SDValue Ptr, SDValue Offset, SDValue Stride, SDValue Mask, SDValue EVL, EVT MemVT, MachineMemOperand *MMO, ISD::MemIndexedMode AM, bool IsTruncating=false, bool IsCompressing=false)
bool isGuaranteedNotToBePoison(SDValue Op, unsigned Depth=0) const
Return true if this function can prove that Op is never poison.
LLVM_ABI SDValue getIdentityElement(unsigned Opcode, const SDLoc &DL, EVT VT, SDNodeFlags Flags)
Get the (commutative) identity element for the given opcode, if it exists.
LLVM_ABI SDValue expandVACopy(SDNode *Node)
Expand the specified ISD::VACOPY node as the Legalize pass would.
LLVM_ABI SDValue getIndexedMaskedLoad(SDValue OrigLoad, const SDLoc &dl, SDValue Base, SDValue Offset, ISD::MemIndexedMode AM)
LLVM_ABI APInt computeVectorKnownZeroElements(SDValue Op, const APInt &DemandedElts, unsigned Depth=0) const
For each demanded element of a vector, see if it is known to be zero.
LLVM_ABI void AddDbgValue(SDDbgValue *DB, bool isParameter)
Add a dbg_value SDNode.
bool NewNodesMustHaveLegalTypes
When true, additional steps are taken to ensure that getConstant() and similar functions return DAG n...
LLVM_ABI std::pair< EVT, EVT > GetSplitDestVTs(const EVT &VT) const
Compute the VTs needed for the low/hi parts of a type which is split (or expanded) into two not neces...
LLVM_ABI void salvageDebugInfo(SDNode &N)
To be invoked on an SDNode that is slated to be erased.
LLVM_ABI SDNode * MorphNodeTo(SDNode *N, unsigned Opc, SDVTList VTs, ArrayRef< SDValue > Ops)
This mutates the specified node to have the specified return type, opcode, and operands.
LLVM_ABI std::pair< SDValue, SDValue > UnrollVectorOverflowOp(SDNode *N, unsigned ResNE=0)
Like UnrollVectorOp(), but for the [US](ADD|SUB|MUL)O family of opcodes.
allnodes_const_iterator allnodes_begin() const
SDValue getUNDEF(EVT VT)
Return an UNDEF node. UNDEF does not have a useful SDLoc.
LLVM_ABI SDValue getGatherVP(SDVTList VTs, EVT VT, const SDLoc &dl, ArrayRef< SDValue > Ops, MachineMemOperand *MMO, ISD::MemIndexType IndexType)
SDValue getBuildVector(EVT VT, const SDLoc &DL, ArrayRef< SDValue > Ops)
Return an ISD::BUILD_VECTOR node.
LLVM_ABI SDValue getBitcastedAnyExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of integer type, to the integer type VT, by first bitcasting (from potentia...
LLVM_ABI bool isSplatValue(SDValue V, const APInt &DemandedElts, APInt &UndefElts, unsigned Depth=0) const
Test whether V has a splatted value for all the demanded elements.
LLVM_ABI void DeleteNode(SDNode *N)
Remove the specified node from the system.
LLVM_ABI SDValue getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val, SDValue Ptr, SDValue Offset, MachinePointerInfo PtrInfo, EVT SVT, Align Alignment, MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const MMOMetadata &Metadata=MMOMetadata())
LLVM_ABI SDValue getBitcast(EVT VT, SDValue V)
Return a bitcast using the SDLoc of the value operand, and casting to the provided type.
LLVM_ABI SDDbgValue * getDbgValueList(DIVariable *Var, DIExpression *Expr, ArrayRef< SDDbgOperand > Locs, ArrayRef< SDNode * > Dependencies, bool IsIndirect, const DebugLoc &DL, unsigned O, bool IsVariadic)
Creates a SDDbgValue node from a list of locations.
LLVM_ABI std::pair< SDValue, SDValue > getStrcpy(SDValue Chain, const SDLoc &dl, SDValue Dst, SDValue Src, const CallInst *CI)
Lower a strcpy operation into a target library call and return the resulting chain and call result as...
SDValue getSelect(const SDLoc &DL, EVT VT, SDValue Cond, SDValue LHS, SDValue RHS, SDNodeFlags Flags=SDNodeFlags())
Helper function to make it easier to build Select's if you just have operands and don't want to check...
LLVM_ABI SDValue getNegative(SDValue Val, const SDLoc &DL, EVT VT)
Create negative operation as (SUB 0, Val).
LLVM_ABI std::optional< unsigned > getValidShiftAmount(SDValue V, const APInt &DemandedElts, unsigned Depth=0) const
If a SHL/SRA/SRL node V has a uniform shift amount that is less than the element bit-width of the shi...
LLVM_ABI void setNodeMemRefs(MachineSDNode *N, ArrayRef< MachineMemOperand * > NewMemRefs)
Mutate the specified machine node's memory references to the provided list.
LLVM_ABI SDValue simplifySelect(SDValue Cond, SDValue TVal, SDValue FVal)
Try to simplify a select/vselect into 1 of its operands or a constant.
LLVM_ABI SDValue getZeroExtendInReg(SDValue Op, const SDLoc &DL, EVT VT)
Return the expression required to zero extend the Op value assuming it was the smaller SrcTy value.
LLVM_ABI bool isConstantFPBuildVectorOrConstantFP(SDValue N) const
Test whether the given value is a constant FP or similar node.
const DataLayout & getDataLayout() const
LLVM_ABI SDValue getPartialReduceMLS(unsigned Opc, const SDLoc &DL, SDValue Acc, SDValue LHS, SDValue RHS)
Get an expression that implements a partial multiply-subtract reduction.
LLVM_ABI SDValue expandVAArg(SDNode *Node)
Expand the specified ISD::VAARG node as the Legalize pass would.
LLVM_ABI SDValue getTokenFactor(const SDLoc &DL, SmallVectorImpl< SDValue > &Vals)
Creates a new TokenFactor containing Vals.
LLVM_ABI SDValue getStore(SDValue Chain, const SDLoc &dl, SDValue Val, SDValue Ptr, MachinePointerInfo PtrInfo, Align Alignment, MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const MMOMetadata &Metadata=MMOMetadata())
Helper function to build ISD::STORE nodes.
LLVM_ABI bool doesNodeExist(unsigned Opcode, SDVTList VTList, ArrayRef< SDValue > Ops)
Check if a node exists without modifying its flags.
LLVM_ABI bool areNonVolatileConsecutiveStores(StoreSDNode *ST, StoreSDNode *Base, TypeSize Bytes, int Dist) const
Return true if stores are next to each other and can be merged.
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 SDValue getMaskedHistogram(SDVTList VTs, EVT MemVT, const SDLoc &dl, ArrayRef< SDValue > Ops, MachineMemOperand *MMO, ISD::MemIndexType IndexType)
LLVM_ABI SDDbgLabel * getDbgLabel(DILabel *Label, const DebugLoc &DL, unsigned O)
Creates a SDDbgLabel node.
LLVM_ABI SDValue getStoreVP(SDValue Chain, const SDLoc &dl, SDValue Val, SDValue Ptr, SDValue Offset, SDValue Mask, SDValue EVL, EVT MemVT, MachineMemOperand *MMO, ISD::MemIndexedMode AM, bool IsTruncating=false, bool IsCompressing=false)
LLVM_ABI OverflowKind computeOverflowForUnsignedMul(SDValue N0, SDValue N1) const
Determine if the result of the unsigned mul of 2 nodes can overflow.
LLVM_ABI void copyExtraInfo(SDNode *From, SDNode *To)
Copy extra info associated with one node to another.
LLVM_ABI SDValue getConstant(uint64_t Val, const SDLoc &DL, EVT VT, bool isTarget=false, bool isOpaque=false)
Create a ConstantSDNode wrapping a constant value.
LLVM_ABI SDValue getMemBasePlusOffset(SDValue Base, TypeSize Offset, const SDLoc &DL, const SDNodeFlags Flags=SDNodeFlags())
Returns sum of the base pointer and offset.
LLVM_ABI SDValue getGlobalAddress(const GlobalValue *GV, const SDLoc &DL, EVT VT, int64_t offset=0, bool isTargetGA=false, unsigned TargetFlags=0)
LLVM_ABI SDValue getVAArg(EVT VT, const SDLoc &dl, SDValue Chain, SDValue Ptr, SDValue SV, unsigned Align)
VAArg produces a result and token chain, and takes a pointer and a source value as input.
LLVM_ABI SDValue getLoadFFVP(EVT VT, const SDLoc &DL, SDValue Chain, SDValue Ptr, SDValue Mask, SDValue EVL, MachineMemOperand *MMO)
LLVM_ABI SDValue getTypeSize(const SDLoc &DL, EVT VT, TypeSize TS)
LLVM_ABI SDValue getMDNode(const MDNode *MD)
Return an MDNodeSDNode which holds an MDNode.
LLVM_ABI void clear()
Clear state and free memory necessary to make this SelectionDAG ready to process a new block.
LLVM_ABI std::pair< SDValue, SDValue > getMemcmp(SDValue Chain, const SDLoc &dl, SDValue Dst, SDValue Src, SDValue Size, const CallInst *CI)
Lower a memcmp operation into a target library call and return the resulting chain and call result as...
LLVM_ABI void ReplaceAllUsesWith(SDValue From, SDValue To)
Modify anything using 'From' to use 'To' instead.
LLVM_ABI SDValue getCommutedVectorShuffle(const ShuffleVectorSDNode &SV)
Returns an ISD::VECTOR_SHUFFLE node semantically equivalent to the shuffle node in input but with swa...
LLVM_ABI SDValue getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl, EVT VT, SDValue Chain, SDValue Ptr, MachinePointerInfo PtrInfo, EVT MemVT, MaybeAlign Alignment=MaybeAlign(), MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const MMOMetadata &Metadata=MMOMetadata())
LLVM_ABI std::pair< SDValue, SDValue > SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT, const EVT &HiVT)
Split the vector with EXTRACT_SUBVECTOR using the provided VTs and return the low/high part.
LLVM_ABI SDValue getSignedConstant(int64_t Val, const SDLoc &DL, EVT VT, bool isTarget=false, bool isOpaque=false)
LLVM_ABI SDValue getSrcValue(const Value *v)
Construct a node to track a Value* through the backend.
SDValue getSplatVector(EVT VT, const SDLoc &DL, SDValue Op)
LLVM_ABI SDValue getAtomicMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst, SDValue Src, SDValue Size, Type *SizeTy, unsigned ElemSz, bool isTailCall, MachinePointerInfo DstPtrInfo, MachinePointerInfo SrcPtrInfo)
LLVM_ABI OverflowKind computeOverflowForSignedMul(SDValue N0, SDValue N1) const
Determine if the result of the signed mul of 2 nodes can overflow.
LLVM_ABI MaybeAlign InferPtrAlign(SDValue Ptr) const
Infer alignment of a load / store address.
LLVM_ABI void dump() const
Dump the textual format of this DAG.
LLVM_ABI bool MaskedValueIsAllOnes(SDValue Op, const APInt &Mask, unsigned Depth=0) const
Return true if '(Op & Mask) == Mask'.
LLVM_ABI bool SignBitIsZero(SDValue Op, unsigned Depth=0) const
Return true if the sign bit of Op is known to be zero.
LLVM_ABI void RemoveDeadNodes()
This method deletes all unreachable nodes in the SelectionDAG.
LLVM_ABI void RemoveDeadNode(SDNode *N)
Remove the specified node from the system.
LLVM_ABI void AddDbgLabel(SDDbgLabel *DB)
Add a dbg_label SDNode.
bool isConstantValueOfAnyType(SDValue N) const
LLVM_ABI bool canCreateUndefOrPoison(SDValue Op, const APInt &DemandedElts, UndefPoisonKind Kind=UndefPoisonKind::UndefOrPoison, bool ConsiderFlags=true, unsigned Depth=0) const
Return true if Op can create undef or poison from non-undef & non-poison operands.
SDValue getInsertVectorElt(const SDLoc &DL, SDValue Vec, SDValue Elt, unsigned Idx)
Insert Elt into Vec at offset Idx.
LLVM_ABI SDValue getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT, SDValue Operand)
A convenience function for creating TargetInstrInfo::EXTRACT_SUBREG nodes.
LLVM_ABI SDValue getSExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of integer type, to the integer type VT, by either sign-extending or trunca...
LLVM_ABI SDDbgValue * getVRegDbgValue(DIVariable *Var, DIExpression *Expr, Register VReg, bool IsIndirect, const DebugLoc &DL, unsigned O)
Creates a VReg SDDbgValue node.
LLVM_ABI SDValue getLoad(EVT VT, const SDLoc &dl, SDValue Chain, SDValue Ptr, MachinePointerInfo PtrInfo, MaybeAlign Alignment=MaybeAlign(), MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const MMOMetadata &Metadata=MMOMetadata())
Loads are not normal binary operators: their result type is not determined by their operands,...
LLVM_ABI KnownFPClass computeKnownFPClass(SDValue Op, FPClassTest InterestedClasses, unsigned Depth=0) const
Determine floating-point class information about Op.
LLVM_ABI bool isIdentityElement(unsigned Opc, SDNodeFlags Flags, SDValue V, unsigned OperandNo, unsigned Depth=0) const
Returns true if V is an identity element of Opc with Flags.
LLVM_ABI SDValue getEHLabel(const SDLoc &dl, SDValue Root, MCSymbol *Label)
LLVM_ABI bool isGuaranteedNotToBeUndefOrPoison(SDValue Op, UndefPoisonKind Kind=UndefPoisonKind::UndefOrPoison, unsigned Depth=0) const
Return true if this function can prove that Op is never poison and, Kind can be used to track poison ...
LLVM_ABI bool isKnownNeverZero(SDValue Op, unsigned Depth=0) const
Test whether the given SDValue is known to contain non-zero value(s).
LLVM_ABI SDValue getIndexedStore(SDValue OrigStore, const SDLoc &dl, SDValue Base, SDValue Offset, ISD::MemIndexedMode AM)
LLVM_ABI SDValue FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL, EVT VT, ArrayRef< SDValue > Ops, SDNodeFlags Flags=SDNodeFlags())
LLVM_ABI std::optional< unsigned > getValidMinimumShiftAmount(SDValue V, const APInt &DemandedElts, unsigned Depth=0) const
If a SHL/SRA/SRL node V has shift amounts that are all less than the element bit-width of the shift n...
LLVM_ABI SDValue getSetFPEnv(SDValue Chain, const SDLoc &dl, SDValue Ptr, EVT MemVT, MachineMemOperand *MMO)
LLVM_ABI SDValue getBoolExtOrTrunc(SDValue Op, const SDLoc &SL, EVT VT, EVT OpVT)
Convert Op, which must be of integer type, to the integer type VT, by using an extension appropriate ...
LLVM_ABI SDValue getMaskedStore(SDValue Chain, const SDLoc &dl, SDValue Val, SDValue Base, SDValue Offset, SDValue Mask, EVT MemVT, MachineMemOperand *MMO, ISD::MemIndexedMode AM, bool IsTruncating=false, bool IsCompressing=false)
LLVM_ABI SDValue getExternalSymbol(const char *Sym, EVT VT)
const TargetMachine & getTarget() const
LLVM_ABI std::pair< SDValue, SDValue > getStrictFPExtendOrRound(SDValue Op, SDValue Chain, const SDLoc &DL, EVT VT)
Convert Op, which must be a STRICT operation of float type, to the float type VT, by either extending...
LLVM_ABI std::pair< SDValue, SDValue > SplitEVL(SDValue N, EVT VecVT, const SDLoc &DL)
Split the explicit vector length parameter of a VP operation.
LLVM_ABI SDValue getPtrExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of integer type, to the integer type VT, by either truncating it or perform...
LLVM_ABI SDValue getMaskFromElementCount(const SDLoc &DL, EVT VT, ElementCount Len)
Return a vector with the first 'Len' lanes set to true and remaining lanes set to false.
LLVM_ABI SDValue getAnyExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of integer type, to the integer type VT, by either any-extending or truncat...
iterator_range< allnodes_iterator > allnodes()
LLVM_ABI SDValue getBlockAddress(const BlockAddress *BA, EVT VT, int64_t Offset=0, bool isTarget=false, unsigned TargetFlags=0)
LLVM_ABI SDValue WidenVector(const SDValue &N, const SDLoc &DL)
Widen the vector up to the next power of two using INSERT_SUBVECTOR.
const LibcallLoweringInfo & getLibcalls() const
LLVM_ABI SDValue getLoadVP(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &dl, SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Mask, SDValue EVL, MachinePointerInfo PtrInfo, EVT MemVT, Align Alignment, MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo, const MDNode *Ranges=nullptr, bool IsExpanding=false)
LLVM_ABI SDValue getIntPtrConstant(uint64_t Val, const SDLoc &DL, bool isTarget=false)
LLVM_ABI SDDbgValue * getConstantDbgValue(DIVariable *Var, DIExpression *Expr, const Value *C, const DebugLoc &DL, unsigned O)
Creates a constant SDDbgValue node.
LLVM_ABI SDValue getScatterVP(SDVTList VTs, EVT VT, const SDLoc &dl, ArrayRef< SDValue > Ops, MachineMemOperand *MMO, ISD::MemIndexType IndexType)
LLVM_ABI SDValue getValueType(EVT)
LLVM_ABI SDValue getLifetimeNode(bool IsStart, const SDLoc &dl, SDValue Chain, int FrameIndex)
Creates a LifetimeSDNode that starts (IsStart==true) or ends (IsStart==false) the lifetime of the Fra...
ArrayRef< SDDbgValue * > GetDbgValues(const SDNode *SD) const
Get the debug values which reference the given SDNode.
LLVM_ABI SDValue getNode(unsigned Opcode, const SDLoc &DL, EVT VT, ArrayRef< SDUse > Ops)
Gets or creates the specified node.
LLVM_ABI OverflowKind computeOverflowForSignedAdd(SDValue N0, SDValue N1) const
Determine if the result of the signed addition of 2 nodes can overflow.
LLVM_ABI SDValue getFPExtendOrRound(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of float type, to the float type VT, by either extending or rounding (by tr...
LLVM_ABI unsigned AssignTopologicalOrder()
Topological-sort the AllNodes list and a assign a unique node id for each node in the DAG based on th...
ilist< SDNode >::size_type allnodes_size() const
LLVM_ABI bool isKnownNeverNaN(SDValue Op, const APInt &DemandedElts, bool SNaN=false, unsigned Depth=0) const
Test whether the given SDValue (or all elements of it, if it is a vector) is known to never be NaN in...
LLVM_ABI SDValue FoldConstantBuildVector(BuildVectorSDNode *BV, const SDLoc &DL, EVT DstEltVT)
Fold BUILD_VECTOR of constants/undefs to the destination type BUILD_VECTOR of constants/undefs elemen...
LLVM_ABI SDValue getAtomicMemmove(SDValue Chain, const SDLoc &dl, SDValue Dst, SDValue Src, SDValue Size, Type *SizeTy, unsigned ElemSz, bool isTailCall, MachinePointerInfo DstPtrInfo, MachinePointerInfo SrcPtrInfo)
LLVM_ABI SDValue getIndexedMaskedStore(SDValue OrigStore, const SDLoc &dl, SDValue Base, SDValue Offset, ISD::MemIndexedMode AM)
LLVM_ABI SDValue getTruncStoreVP(SDValue Chain, const SDLoc &dl, SDValue Val, SDValue Ptr, SDValue Mask, SDValue EVL, MachinePointerInfo PtrInfo, EVT SVT, Align Alignment, MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo, bool IsCompressing=false)
SDValue getTargetConstant(uint64_t Val, const SDLoc &DL, EVT VT, bool isOpaque=false)
const TargetLibraryInfo & getLibInfo() const
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 bool canIgnoreSignBitOfZeroResult(SDValue Op) const
Check if all uses of Op (limited to checking two for compile-time performance) are insensitive to sig...
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...
const SelectionDAGOptions & getSelectionDAGOptions() const
LLVM_ABI SDValue getCondCode(ISD::CondCode Cond)
LLVM_ABI bool MaskedValueIsZero(SDValue Op, const APInt &Mask, unsigned Depth=0) const
Return true if 'Op & Mask' is known to be zero.
LLVM_ABI bool isKnownToBeAPowerOfTwoFP(SDValue Val, unsigned Depth=0) const
Test if the given fp value is known to be an integer power-of-2, either positive or negative.
LLVM_ABI OverflowKind computeOverflowForSignedSub(SDValue N0, SDValue N1) const
Determine if the result of the signed sub of 2 nodes can overflow.
LLVM_ABI void init(MachineFunction &NewMF, const TargetLibraryInfo *LibraryInfo, const LibcallLoweringInfo *LibcallsInfo, UniformityInfo *UA, ProfileSummaryInfo *PSIin, BlockFrequencyInfo *BFIin, FunctionVarLocs const *FnVarLocs)
Prepare this SelectionDAG to process code in the given MachineFunction.
SDValue getObjectPtrOffset(const SDLoc &SL, SDValue Ptr, TypeSize Offset)
Create an add instruction with appropriate flags when used for addressing some offset of an object.
LLVMContext * getContext() const
LLVM_ABI SDValue simplifyFPBinop(unsigned Opcode, SDValue X, SDValue Y, SDNodeFlags Flags)
Try to simplify a floating-point binary operation into 1 of its operands or a constant.
const SDValue & setRoot(SDValue N)
Set the current root tag of the SelectionDAG.
LLVM_ABI bool isKnownToBeAPowerOfTwo(SDValue Val, bool OrZero=false, unsigned Depth=0) const
Test if the given value is known to have exactly one bit set.
LLVM_ABI SDValue getDeactivationSymbol(const GlobalValue *GV)
LLVM_ABI SDValue getTargetExternalSymbol(const char *Sym, EVT VT, unsigned TargetFlags=0)
LLVM_ABI SDValue getMCSymbol(MCSymbol *Sym, EVT VT)
LLVM_ABI bool isUndef(unsigned Opcode, ArrayRef< SDValue > Ops)
Return true if the result of this operation is always undefined.
LLVM_ABI SDValue CreateStackTemporary(TypeSize Bytes, Align Alignment)
Create a stack temporary based on the size in bytes and the alignment.
LLVM_ABI SDNode * UpdateNodeOperands(SDNode *N, SDValue Op)
Mutate the specified node in-place to have the specified operands.
LLVM_ABI std::pair< EVT, EVT > GetDependentSplitDestVTs(const EVT &VT, const EVT &EnvVT, bool *HiIsEmpty) const
Compute the VTs needed for the low/hi parts of a type, dependent on an enveloping VT that has been sp...
LLVM_ABI SDValue foldConstantFPMath(unsigned Opcode, const SDLoc &DL, EVT VT, ArrayRef< SDValue > Ops)
Fold floating-point operations when all operands are constants and/or undefined.
LLVM_ABI std::optional< ConstantRange > getValidShiftAmountRange(SDValue V, const APInt &DemandedElts, unsigned Depth) const
If a SHL/SRA/SRL node V has shift amounts that are all less than the element bit-width of the shift n...
LLVM_ABI SDValue FoldSymbolOffset(unsigned Opcode, EVT VT, const GlobalAddressSDNode *GA, const SDNode *N2)
LLVM_ABI SDValue getIndexedLoad(SDValue OrigLoad, const SDLoc &dl, SDValue Base, SDValue Offset, ISD::MemIndexedMode AM)
LLVM_ABI SDValue getTargetInsertSubreg(int SRIdx, const SDLoc &DL, EVT VT, SDValue Operand, SDValue Subreg)
A convenience function for creating TargetInstrInfo::INSERT_SUBREG nodes.
SDValue getEntryNode() const
Return the token chain corresponding to the entry of the function.
LLVM_ABI SDDbgValue * getDbgValue(DIVariable *Var, DIExpression *Expr, SDNode *N, unsigned R, bool IsIndirect, const DebugLoc &DL, unsigned O)
Creates a SDDbgValue node.
LLVM_ABI SDValue getMaskedLoad(EVT VT, const SDLoc &dl, SDValue Chain, SDValue Base, SDValue Offset, SDValue Mask, SDValue Src0, EVT MemVT, MachineMemOperand *MMO, ISD::MemIndexedMode AM, ISD::LoadExtType, bool IsExpanding=false)
DenormalMode getDenormalMode(EVT VT) const
Return the current function's default denormal handling kind for the given floating point type.
SDValue getSplat(EVT VT, const SDLoc &DL, SDValue Op)
Returns a node representing a splat of one value into all lanes of the provided vector type.
LLVM_ABI std::pair< SDValue, SDValue > SplitScalar(const SDValue &N, const SDLoc &DL, const EVT &LoVT, const EVT &HiVT)
Split the scalar node with EXTRACT_ELEMENT using the provided VTs and return the low/high part.
LLVM_ABI SDValue matchBinOpReduction(SDNode *Extract, ISD::NodeType &BinOp, ArrayRef< ISD::NodeType > CandidateBinOps, bool AllowPartials=false)
Match a binop + shuffle pyramid that represents a horizontal reduction over the elements of a vector ...
LLVM_ABI bool isADDLike(SDValue Op, bool NoWrap=false) const
Return true if the specified operand is an ISD::OR or ISD::XOR node that can be treated as an ISD::AD...
LLVM_ABI SDValue getVectorShuffle(EVT VT, const SDLoc &dl, SDValue N1, SDValue N2, ArrayRef< int > Mask)
Return an ISD::VECTOR_SHUFFLE node.
LLVM_ABI SDValue simplifyShift(SDValue X, SDValue Y)
Try to simplify a shift into 1 of its operands or a constant.
LLVM_ABI 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.
StackOffset holds a fixed and a scalable offset in bytes.
Definition TypeSize.h:31
int64_t getFixed() const
Returns the fixed component of the stack.
Definition TypeSize.h:47
int64_t getScalable() const
Returns the scalable component of the stack.
Definition TypeSize.h:50
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.
IntegerType * getSizeTType(const Module &M) const
Returns an IntegerType corresponding to size_t.
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...
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.
std::vector< ArgListEntry > ArgListTy
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...
Primary interface to the complete machine description for the target machine.
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:725
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:352
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:283
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:299
static LLVM_ABI Type * getVoidTy(LLVMContext &C)
Definition Type.cpp:272
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:187
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.cpp:222
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Definition Type.cpp:303
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
LLVM_ABI unsigned getOperandNo() const
Return the operand # of this use in its User.
Definition Use.cpp:35
LLVM_ABI void set(Value *Val)
Definition Value.h:876
User * getUser() const
Returns the User that contains this Use.
Definition Use.h:61
Value * getOperand(unsigned i) const
Definition User.h:207
This class is used to represent an VP_GATHER node.
This class is used to represent a VP_LOAD node.
This class is used to represent an VP_SCATTER node.
This class is used to represent a VP_STORE node.
This class is used to represent an EXPERIMENTAL_VP_STRIDED_LOAD node.
This class is used to represent an EXPERIMENTAL_VP_STRIDED_STORE node.
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:210
bool contains(const_arg_type_t< ValueT > V) const
Check if the set contains the given element.
Definition DenseSet.h:183
constexpr bool hasKnownScalarFactor(const FixedOrScalableQuantity &RHS) const
Returns true if there exists a value X where RHS*X will result in a value whose quantity matches our ...
Definition TypeSize.h:266
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:201
static constexpr bool isKnownLE(const FixedOrScalableQuantity &LHS, const FixedOrScalableQuantity &RHS)
Definition TypeSize.h:231
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:169
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:177
constexpr bool isFixed() const
Returns true if the quantity is not scaled by vscale.
Definition TypeSize.h:172
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
Definition TypeSize.h:166
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:253
static constexpr bool isKnownGE(const FixedOrScalableQuantity &LHS, const FixedOrScalableQuantity &RHS)
Definition TypeSize.h:238
A raw_ostream that writes to an std::string.
CallInst * Call
#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:3245
LLVM_ABI APInt mulhu(const APInt &C1, const APInt &C2)
Performs (2*N)-bit multiplication on zero-extended operands.
Definition APInt.cpp:3175
LLVM_ABI APInt avgCeilU(const APInt &C1, const APInt &C2)
Compute the ceil of the unsigned average of C1 and C2.
Definition APInt.cpp:3152
LLVM_ABI APInt avgFloorU(const APInt &C1, const APInt &C2)
Compute the floor of the unsigned average of C1 and C2.
Definition APInt.cpp:3142
LLVM_ABI APInt pext(const APInt &Val, const APInt &Mask)
Perform a "compress" operation, also known as pext or bext.
Definition APInt.cpp:3255
LLVM_ABI APInt fshr(const APInt &Hi, const APInt &Lo, const APInt &Shift)
Perform a funnel shift right.
Definition APInt.cpp:3226
LLVM_ABI APInt mulhs(const APInt &C1, const APInt &C2)
Performs (2*N)-bit multiplication on sign-extended operands.
Definition APInt.cpp:3167
LLVM_ABI APInt avgSubFloorS(const APInt &C1, const APInt &C2)
Compute floor((C1 - C2) / 2) where C1 and C2 are treated as signed, so the subtraction is performed w...
Definition APInt.cpp:3157
LLVM_ABI APInt clmul(const APInt &LHS, const APInt &RHS)
Perform a carry-less multiply, also known as XOR multiplication, and return low-bits.
Definition APInt.cpp:3235
LLVM_ABI APInt pdep(const APInt &Val, const APInt &Mask)
Perform an "expand" operation, also known as pdep or bdep.
Definition APInt.cpp:3265
APInt abds(const APInt &A, const APInt &B)
Determine the absolute difference of two APInts considered to be signed.
Definition APInt.h:2294
LLVM_ABI APInt fshl(const APInt &Hi, const APInt &Lo, const APInt &Shift)
Perform a funnel shift left.
Definition APInt.cpp:3217
LLVM_ABI APInt ScaleBitMask(const APInt &A, unsigned NewBitWidth, bool MatchAllBits=false)
Splat/Merge neighboring bits to widen/narrow the bitmask represented by.
Definition APInt.cpp:3043
LLVM_ABI APInt clmulh(const APInt &LHS, const APInt &RHS)
Perform a carry-less multiply, and return high-bits.
Definition APInt.cpp:3250
APInt abdu(const APInt &A, const APInt &B)
Determine the absolute difference of two APInts considered to be unsigned.
Definition APInt.h:2299
LLVM_ABI APInt avgFloorS(const APInt &C1, const APInt &C2)
Compute the floor of the signed average of C1 and C2.
Definition APInt.cpp:3137
LLVM_ABI APInt avgCeilS(const APInt &C1, const APInt &C2)
Compute the ceil of the signed average of C1 and C2.
Definition APInt.cpp:3147
LLVM_ABI APInt avgSubFloorU(const APInt &C1, const APInt &C2)
Compute floor((C1 - C2) / 2) where C1 and C2 are treated as unsigned, so the subtraction is performed...
Definition APInt.cpp:3162
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
LLVM_ABI CondCode getSetCCInverse(CondCode Operation, bool isIntegerLike)
Return the operation corresponding to !(X op Y), where 'op' is a valid SetCC operation.
ISD namespace - This namespace contains an enum which represents all of the SelectionDAG node types a...
Definition ISDOpcodes.h:26
LLVM_ABI CondCode getSetCCAndOperation(CondCode Op1, CondCode Op2, EVT Type)
Return the result of a logical AND between different comparisons of identical values: ((X op1 Y) & (X...
LLVM_ABI bool isConstantSplatVectorAllOnes(const SDNode *N, bool BuildVectorOnly=false)
Return true if the specified node is a BUILD_VECTOR or SPLAT_VECTOR where all of the elements are ~0 ...
bool isNON_EXTLoad(const SDNode *N)
Returns true if the specified node is a non-extending load.
bool matchUnaryPredicateImpl(SDValue Op, const APInt &DemandedElts, std::function< bool(ConstNodeType *)> Match, bool AllowUndefs=false, bool AllowTruncation=false)
Attempt to match a unary predicate against a scalar/splat constant or every element of a constant BUI...
NodeType
ISD::NodeType enum - This enum defines the target-independent operators for a SelectionDAG.
Definition ISDOpcodes.h:43
@ SETCC
SetCC operator - This evaluates to a true value iff the condition is true.
Definition ISDOpcodes.h:851
@ MERGE_VALUES
MERGE_VALUES - This node takes multiple discrete operands and returns them all as its individual resu...
Definition ISDOpcodes.h:263
@ TargetConstantPool
Definition ISDOpcodes.h:191
@ MDNODE_SDNODE
MDNODE_SDNODE - This is a node that holdes an MDNode*, which is used to reference metadata in the IR.
@ STRICT_FSETCC
STRICT_FSETCC/STRICT_FSETCCS - Constrained versions of SETCC, used for floating-point operands only.
Definition ISDOpcodes.h:516
@ PTRADD
PTRADD represents pointer arithmetic semantics, for targets that opt in using shouldPreservePtrArith(...
@ DELETED_NODE
DELETED_NODE - This is an illegal value that is used to catch errors.
Definition ISDOpcodes.h:47
@ POISON
POISON - A poison node.
Definition ISDOpcodes.h:238
@ PARTIAL_REDUCE_SMLA
PARTIAL_REDUCE_[U|S]MLA(Accumulator, Input1, Input2) The partial reduction nodes sign or zero extend ...
@ ATOMIC_LOAD_FMINIMUMNUM
@ MASK_BEFOREFIRST
Has one mask vector operand.
@ VECREDUCE_SEQ_FADD
Generic reduction nodes.
@ MLOAD
Masked load and store - consecutive vector load and store operations with additional mask operand tha...
@ VECREDUCE_FMINIMUMNUM
@ FGETSIGN
INT = FGETSIGN(FP) - Return the sign bit of the specified floating point value as an integer 0/1 valu...
Definition ISDOpcodes.h:543
@ SMUL_LOHI
SMUL_LOHI/UMUL_LOHI - Multiply two integers of type iN, producing a signed/unsigned value of type i[2...
Definition ISDOpcodes.h:277
@ AVGSUBFLOORS
AVGSUBFLOORS/AVGSUBFLOORU - Averaging subtract - Subtract two integers using an integer of type i[N+1...
Definition ISDOpcodes.h:739
@ INSERT_SUBVECTOR
INSERT_SUBVECTOR(VECTOR1, VECTOR2, IDX) - Returns a vector with VECTOR2 inserted into VECTOR1.
Definition ISDOpcodes.h:605
@ JUMP_TABLE_DEBUG_INFO
JUMP_TABLE_DEBUG_INFO - Jumptable debug info.
@ BSWAP
Byte Swap and Counting operators.
Definition ISDOpcodes.h:811
@ TargetBlockAddress
Definition ISDOpcodes.h:193
@ DEACTIVATION_SYMBOL
Untyped node storing deactivation symbol reference (DeactivationSymbolSDNode).
@ ATOMIC_STORE
OUTCHAIN = ATOMIC_STORE(INCHAIN, val, ptr) This corresponds to "store atomic" instruction.
@ ADDC
Carry-setting nodes for multiple precision addition and subtraction.
Definition ISDOpcodes.h:296
@ FMAD
FMAD - Perform a * b + c, while getting the same result as the separately rounded operations.
Definition ISDOpcodes.h:527
@ ADD
Simple integer binary arithmetic operators.
Definition ISDOpcodes.h:266
@ LOAD
LOAD and STORE have token chains as their first operand, then the same operands as an LLVM load/store...
@ ANY_EXTEND
ANY_EXTEND - Used for integer types. The high bits are undefined.
Definition ISDOpcodes.h:885
@ ATOMIC_LOAD_USUB_COND
@ FMA
FMA - Perform a * b + c with no intermediate rounding step.
Definition ISDOpcodes.h:523
@ PSEUDO_FMIN
PSEUDO_FMIN is strictly equivalent to op0 olt op1 ?
@ FATAN2
FATAN2 - atan2, inspired by libm.
@ INTRINSIC_VOID
OUTCHAIN = INTRINSIC_VOID(INCHAIN, INTRINSICID, arg1, arg2, ...) This node represents a target intrin...
Definition ISDOpcodes.h:222
@ GlobalAddress
Definition ISDOpcodes.h:90
@ ATOMIC_CMP_SWAP_WITH_SUCCESS
Val, Success, OUTCHAIN = ATOMIC_CMP_SWAP_WITH_SUCCESS(INCHAIN, ptr, cmp, swap) N.b.
@ STRICT_FMINIMUM
Definition ISDOpcodes.h:476
@ SINT_TO_FP
[SU]INT_TO_FP - These operators convert integers (whose interpreted sign depends on the first letter)...
Definition ISDOpcodes.h:912
@ CONCAT_VECTORS
CONCAT_VECTORS(VECTOR0, VECTOR1, ...) - Given a number of values of vector type with the same length ...
Definition ISDOpcodes.h:589
@ VECREDUCE_FMAX
FMIN/FMAX nodes can have flags, for NaN/NoNaN variants.
@ FADD
Simple binary floating point operators.
Definition ISDOpcodes.h:420
@ VECREDUCE_FMAXIMUM
FMINIMUM/FMAXIMUM nodes propatate NaNs and signed zeroes using the llvm.minimum and llvm....
@ VECTOR_SHUFFLE_VAR
VECTOR_SHUFFLE_VAR(VEC, MASK) - Returns VEC permuted by MASK, an integer vector with the same number ...
Definition ISDOpcodes.h:665
@ ABS
ABS - Determine the unsigned absolute value of a signed integer value of the same bitwidth.
Definition ISDOpcodes.h:771
@ SIGN_EXTEND_VECTOR_INREG
SIGN_EXTEND_VECTOR_INREG(Vector) - This operator represents an in-register sign-extension of the low ...
Definition ISDOpcodes.h:942
@ FP16_TO_FP
FP16_TO_FP, FP_TO_FP16 - These operators are used to perform promotions and truncation for half-preci...
@ FMULADD
FMULADD - Performs a * b + c, with, or without, intermediate rounding.
Definition ISDOpcodes.h:533
@ BITCAST
BITCAST - This operator converts between integer, vector and FP values, as if the value was stored to...
@ STRICT_PSEUDO_FMAX
Definition ISDOpcodes.h:465
@ BUILD_PAIR
BUILD_PAIR - This is the opposite of EXTRACT_ELEMENT in some ways.
Definition ISDOpcodes.h:256
@ CLMUL
Carry-less multiplication operations.
Definition ISDOpcodes.h:802
@ FLDEXP
FLDEXP - ldexp, inspired by libm (op0 * 2**op1).
@ BUILTIN_OP_END
BUILTIN_OP_END - This must be the last enum value in this list.
@ GlobalTLSAddress
Definition ISDOpcodes.h:91
@ SRCVALUE
SRCVALUE - This is a node type that holds a Value* that is used to make reference to a value in the L...
@ EH_LABEL
EH_LABEL - Represents a label in mid basic block used to track locations needed for debug and excepti...
@ ATOMIC_LOAD_USUB_SAT
@ CTLZ_ZERO_POISON
Definition ISDOpcodes.h:820
@ ANNOTATION_LABEL
ANNOTATION_LABEL - Represents a mid basic block label used by annotations.
@ PARTIAL_REDUCE_UMLA
@ SIGN_EXTEND
Conversion operators.
Definition ISDOpcodes.h:876
@ AVGCEILS
AVGCEILS/AVGCEILU - Rounding averaging add - Add two integers using an integer of type i[N+2],...
Definition ISDOpcodes.h:731
@ SCALAR_TO_VECTOR
SCALAR_TO_VECTOR(VAL) - This represents the operation of loading a scalar value into element 0 of the...
Definition ISDOpcodes.h:681
@ TargetExternalSymbol
Definition ISDOpcodes.h:192
@ VECREDUCE_FADD
These reductions have relaxed evaluation order semantics, and have a single vector operand.
@ TargetJumpTable
Definition ISDOpcodes.h:190
@ TargetIndex
TargetIndex - Like a constant pool entry, but with completely target-dependent semantics.
Definition ISDOpcodes.h:200
@ PARTIAL_REDUCE_FMLA
@ PREFETCH
PREFETCH - This corresponds to a prefetch intrinsic.
@ STRICT_PSEUDO_FMIN
Definition ISDOpcodes.h:464
@ TRUNCATE_SSAT_U
Definition ISDOpcodes.h:905
@ 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:859
@ FNEG
Perform various unary floating-point operations inspired by libm.
@ BR_CC
BR_CC - Conditional branch.
@ SSUBO
Same for subtraction.
Definition ISDOpcodes.h:355
@ STEP_VECTOR
STEP_VECTOR(IMM) - Returns a scalable vector whose lanes are comprised of a linear sequence of unsign...
Definition ISDOpcodes.h:707
@ FCANONICALIZE
Returns platform specific canonical encoding of a floating point number.
Definition ISDOpcodes.h:546
@ IS_FPCLASS
Performs a check of floating point class property, defined by IEEE-754.
Definition ISDOpcodes.h:553
@ SSUBSAT
RESULT = [US]SUBSAT(LHS, RHS) - Perform saturation subtraction on 2 integers with the same bit width ...
Definition ISDOpcodes.h:377
@ SELECT
Select(COND, TRUEVAL, FALSEVAL).
Definition ISDOpcodes.h:828
@ ATOMIC_LOAD
Val, OUTCHAIN = ATOMIC_LOAD(INCHAIN, ptr) This corresponds to "load atomic" instruction.
@ UNDEF
UNDEF - An undefined node.
Definition ISDOpcodes.h:235
@ EXTRACT_ELEMENT
EXTRACT_ELEMENT - This is used to get the lower or upper (determined by a Constant,...
Definition ISDOpcodes.h:249
@ SPLAT_VECTOR
SPLAT_VECTOR(VAL) - Returns a vector with the scalar value VAL duplicated in all lanes.
Definition ISDOpcodes.h:688
@ AssertAlign
AssertAlign - These nodes record if a register contains a value that has a known alignment and the tr...
Definition ISDOpcodes.h:71
@ GET_ACTIVE_LANE_MASK
GET_ACTIVE_LANE_MASK - this corrosponds to the llvm.get.active.lane.mask intrinsic.
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
@ CopyFromReg
CopyFromReg - This node indicates that the input value is a virtual or physical register that is defi...
Definition ISDOpcodes.h:232
@ SADDO
RESULT, BOOL = [SU]ADDO(LHS, RHS) - Overflow-aware nodes for addition.
Definition ISDOpcodes.h:351
@ TargetGlobalAddress
TargetGlobalAddress - Like GlobalAddress, but the DAG does no folding or anything else with this node...
Definition ISDOpcodes.h:187
@ ARITH_FENCE
ARITH_FENCE - This corresponds to a arithmetic fence intrinsic.
@ CTLS
Count leading redundant sign bits.
Definition ISDOpcodes.h:824
@ 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:720
@ ATOMIC_LOAD_FMAXIMUM
@ SHL
Shift and rotation operations.
Definition ISDOpcodes.h:793
@ AssertNoFPClass
AssertNoFPClass - These nodes record if a register contains a float value that is known to be not som...
Definition ISDOpcodes.h:80
@ VECTOR_SHUFFLE
VECTOR_SHUFFLE(VEC1, VEC2) - Returns a vector, of the same type as VEC1/VEC2.
Definition ISDOpcodes.h:659
@ EXTRACT_SUBVECTOR
EXTRACT_SUBVECTOR(VECTOR, IDX) - Returns a subvector from VECTOR.
Definition ISDOpcodes.h:619
@ FMINNUM_IEEE
FMINNUM_IEEE/FMAXNUM_IEEE - Same as FMINNUM/FMAXNUM, except that a signaling NaN operand deterministi...
@ STRICT_FMAXIMUM
Definition ISDOpcodes.h:475
@ EntryToken
EntryToken - This is the marker used to indicate the start of a region.
Definition ISDOpcodes.h:50
@ EXTRACT_VECTOR_ELT
EXTRACT_VECTOR_ELT(VECTOR, IDX) - Returns a single element from VECTOR identified by the (potentially...
Definition ISDOpcodes.h:581
@ CopyToReg
CopyToReg - This node has three operands: a chain, a register number to set to this value,...
Definition ISDOpcodes.h:226
@ ZERO_EXTEND
ZERO_EXTEND - Used for integer types, zeroing the new bits.
Definition ISDOpcodes.h:882
@ TargetConstantFP
Definition ISDOpcodes.h:182
@ SELECT_CC
Select with condition operator - This selects between a true value and a false value (ops #2 and #3) ...
Definition ISDOpcodes.h:843
@ 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 - Same semantics as the llvm.minnum/maxnum intrinsics.
@ SSHLSAT
RESULT = [US]SHLSAT(LHS, RHS) - Perform saturation left shift.
Definition ISDOpcodes.h:389
@ SMULO
Same for multiplication.
Definition ISDOpcodes.h:359
@ ATOMIC_LOAD_FMINIMUM
@ TargetFrameIndex
Definition ISDOpcodes.h:189
@ VECTOR_SPLICE_LEFT
VECTOR_SPLICE_LEFT(VEC1, VEC2, OFFSET) - Shifts CONCAT_VECTORS(VEC1, VEC2) left by OFFSET elements an...
Definition ISDOpcodes.h:669
@ ANY_EXTEND_VECTOR_INREG
ANY_EXTEND_VECTOR_INREG(Vector) - This operator represents an in-register any-extension of the low la...
Definition ISDOpcodes.h:931
@ SIGN_EXTEND_INREG
SIGN_EXTEND_INREG - This operator atomically performs a SHL/SRA pair to sign extend a small value in ...
Definition ISDOpcodes.h:920
@ SMIN
[US]{MIN/MAX} - Binary minimum or maximum of signed or unsigned integers.
Definition ISDOpcodes.h:751
@ 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.
@ VSELECT
Select with a vector condition (op #0) and two vector operands (ops #1 and #2), returning a vector re...
Definition ISDOpcodes.h:837
@ UADDO_CARRY
Carry-using nodes for multiple precision addition and subtraction.
Definition ISDOpcodes.h:331
@ MGATHER
Masked gather and scatter - load and store operations for a vector of random addresses with additiona...
@ HANDLENODE
HANDLENODE node - Used as a handle for various purposes.
@ ATOMIC_LOAD_FMAXIMUMNUM
@ 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:807
@ STRICT_FP_ROUND
X = STRICT_FP_ROUND(Y, TRUNC) - Rounding 'Y' from a larger floating point type down to the precision ...
Definition ISDOpcodes.h:505
@ FMINIMUM
FMINIMUM/FMAXIMUM - Same semantics as the llvm.minimum/maximum intrinsics.
@ FP_TO_SINT
FP_TO_[US]INT - Convert a floating point value to a signed or unsigned integer.
Definition ISDOpcodes.h:958
@ TargetConstant
TargetConstant* - Like Constant*, but the DAG does not do any folding, simplification,...
Definition ISDOpcodes.h:181
@ STRICT_FP_EXTEND
X = STRICT_FP_EXTEND(Y) - Extend a smaller FP type into a larger FP type.
Definition ISDOpcodes.h:510
@ AND
Bitwise operators - logical and, logical or, logical xor.
Definition ISDOpcodes.h:763
@ INTRINSIC_WO_CHAIN
RESULT = INTRINSIC_WO_CHAIN(INTRINSICID, arg1, arg2, ...) This node represents a target intrinsic fun...
Definition ISDOpcodes.h:207
@ GET_FPENV_MEM
Gets the current floating-point environment.
@ PSEUDO_PROBE
Pseudo probe for AutoFDO, as a place holder in a basic block to improve the sample counts quality.
@ SCMP
[US]CMP - 3-way comparison of signed or unsigned integers.
Definition ISDOpcodes.h:759
@ AVGFLOORS
AVGFLOORS/AVGFLOORU - Averaging add - Add two integers using an integer of type i[N+1],...
Definition ISDOpcodes.h:726
@ VECTOR_SPLICE_RIGHT
VECTOR_SPLICE_RIGHT(VEC1, VEC2, OFFSET) - Shifts CONCAT_VECTORS(VEC1,VEC2) right by OFFSET elements a...
Definition ISDOpcodes.h:673
@ ADDE
Carry-using nodes for multiple precision addition and subtraction.
Definition ISDOpcodes.h:306
@ SPLAT_VECTOR_PARTS
SPLAT_VECTOR_PARTS(SCALAR1, SCALAR2, ...) - Returns a vector with the scalar values joined together a...
Definition ISDOpcodes.h:697
@ FREEZE
FREEZE - FREEZE(VAL) returns an arbitrary value if VAL is UNDEF (or is evaluated to UNDEF),...
Definition ISDOpcodes.h:243
@ INSERT_VECTOR_ELT
INSERT_VECTOR_ELT(VECTOR, VAL, IDX) - Returns VECTOR with the element at IDX replaced with VAL.
Definition ISDOpcodes.h:570
@ TokenFactor
TokenFactor - This node takes multiple tokens as input and produces a single token result.
Definition ISDOpcodes.h:55
@ ATOMIC_SWAP
Val, OUTCHAIN = ATOMIC_SWAP(INCHAIN, ptr, amt) Val, OUTCHAIN = ATOMIC_LOAD_[OpName](INCHAIN,...
@ CTTZ_ZERO_POISON
Bit counting operators with a poisoned result for zero inputs.
Definition ISDOpcodes.h:819
@ ExternalSymbol
Definition ISDOpcodes.h:95
@ FFREXP
FFREXP - frexp, extract fractional and exponent component of a floating-point value.
@ FP_ROUND
X = FP_ROUND(Y, TRUNC) - Rounding 'Y' from a larger floating point type down to the precision of the ...
Definition ISDOpcodes.h:991
@ VECTOR_COMPRESS
VECTOR_COMPRESS(Vec, Mask, Passthru) consecutively place vector elements based on mask e....
Definition ISDOpcodes.h:715
@ ZERO_EXTEND_VECTOR_INREG
ZERO_EXTEND_VECTOR_INREG(Vector) - This operator represents an in-register zero-extension of the low ...
Definition ISDOpcodes.h:953
@ 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:977
@ VECREDUCE_FMINIMUM
@ TRUNCATE
TRUNCATE - Completely drop the high bits.
Definition ISDOpcodes.h:888
@ 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:865
@ AssertSext
AssertSext, AssertZext - These nodes record if a register contains a value that has already been zero...
Definition ISDOpcodes.h:64
@ ATOMIC_LOAD_UINC_WRAP
@ FCOPYSIGN
FCOPYSIGN(X, Y) - Return the value of X with the sign of Y.
Definition ISDOpcodes.h:539
@ PARTIAL_REDUCE_SUMLA
@ SADDSAT
RESULT = [US]ADDSAT(LHS, RHS) - Perform saturation addition on 2 integers with the same bit width (W)...
Definition ISDOpcodes.h:368
@ VECTOR_REPEAT
VECTOR_REPEAT(FIXED_LENGTH_VECTOR) Repeatedly copies the elements of the source fixed-length vector t...
Definition ISDOpcodes.h:645
@ SET_FPENV_MEM
Sets the current floating point environment.
@ FMINIMUMNUM
FMINIMUMNUM/FMAXIMUMNUM - Same semantics as the llvm.minimumnum/maximumnum intrinsics.
@ TRUNCATE_SSAT_S
TRUNCATE_[SU]SAT_[SU] - Truncate for saturated operand [SU] located in middle, prefix for SAT means i...
Definition ISDOpcodes.h:903
@ ABDS
ABDS/ABDU - Absolute difference - Return the absolute difference between two numbers interpreted as s...
Definition ISDOpcodes.h:746
@ TRUNCATE_USAT_U
Definition ISDOpcodes.h:907
@ SADDO_CARRY
Carry-using overflow-aware nodes for multiple precision addition and subtraction.
Definition ISDOpcodes.h:341
@ INTRINSIC_W_CHAIN
RESULT,OUTCHAIN = INTRINSIC_W_CHAIN(INCHAIN, INTRINSICID, arg1, ...) This node represents a target in...
Definition ISDOpcodes.h:215
@ TargetGlobalTLSAddress
Definition ISDOpcodes.h:188
@ ABS_MIN_POISON
ABS with a poison result for INT_MIN.
Definition ISDOpcodes.h:775
@ BUILD_VECTOR
BUILD_VECTOR(ELT0, ELT1, ELT2, ELT3,...) - Return a fixed-width vector with the specified,...
Definition ISDOpcodes.h:561
LLVM_ABI NodeType getOppositeSignednessMinMaxOpcode(unsigned MinMaxOpc)
Given a MinMaxOpc of ISD::(U|S)MIN or ISD::(U|S)MAX, returns the corresponding opcode with the opposi...
LLVM_ABI bool isBuildVectorOfConstantSDNodes(const SDNode *N)
Return true if the specified node is a BUILD_VECTOR node of all ConstantSDNode or undef.
LLVM_ABI NodeType getExtForLoadExtType(bool IsFP, LoadExtType)
bool isZEXTLoad(const SDNode *N)
Returns true if the specified node is a ZEXTLOAD.
bool isExtOpcode(unsigned Opcode)
LLVM_ABI bool isConstantSplatVectorAllZeros(const SDNode *N, bool BuildVectorOnly=false)
Return true if the specified node is a BUILD_VECTOR or SPLAT_VECTOR where all of the elements are 0 o...
LLVM_ABI NodeType getUnmaskedBinOpOpcode(unsigned MaskedOpc)
Given a MaskedOpc of ISD::MASKED_(U|S)(DIV|REM), returns the unmasked ISD::(U|S)(DIV|REM).
LLVM_ABI bool isVectorShrinkable(const SDNode *N, unsigned NewEltSize, bool Signed)
Returns true if the specified node is a vector where all elements can be truncated to the specified e...
LLVM_ABI bool isVPBinaryOp(unsigned Opcode)
Whether this is a vector-predicated binary operation opcode.
LLVM_ABI CondCode getSetCCInverse(CondCode Operation, EVT Type)
Return the operation corresponding to !(X op Y), where 'op' is a valid SetCC operation.
LLVM_ABI std::optional< unsigned > getBaseOpcodeForVP(unsigned Opcode, bool hasFPExcept)
Translate this VP Opcode to its corresponding non-VP Opcode.
bool isBitwiseLogicOp(unsigned Opcode)
Whether this is bitwise logic opcode.
bool isTrueWhenEqual(CondCode Cond)
Return true if the specified condition returns true if the two operands to the condition are equal.
LLVM_ABI std::optional< unsigned > getVPMaskIdx(unsigned Opcode)
The operand position of the vector mask.
unsigned getUnorderedFlavor(CondCode Cond)
This function returns 0 if the condition is always false if an operand is a NaN, 1 if the condition i...
bool isUNINDEXEDLoad(const SDNode *N)
Returns true if the specified node is an unindexed load.
LLVM_ABI std::optional< unsigned > getVPExplicitVectorLengthIdx(unsigned Opcode)
The operand position of the explicit vector length parameter.
LLVM_ABI bool matchBinaryPredicate(SDValue LHS, SDValue RHS, const APInt &DemandedElts, std::function< bool(ConstantSDNode *, ConstantSDNode *)> Match, bool AllowUndefs=false, bool AllowTypeMismatch=false)
Attempt to match a binary predicate against a pair of scalar/splat constants or every element of a pa...
bool isEXTLoad(const SDNode *N)
Returns true if the specified node is a EXTLOAD.
LLVM_ABI bool allOperandsUndef(const SDNode *N)
Return true if the node has at least one operand and all operands of the specified node are ISD::UNDE...
LLVM_ABI bool isFreezeUndef(const SDNode *N)
Return true if the specified node is FREEZE(UNDEF).
LLVM_ABI CondCode getSetCCSwappedOperands(CondCode Operation)
Return the operation corresponding to (Y op X) when given the operation for (X op Y).
LLVM_ABI std::optional< unsigned > getVPForBaseOpcode(unsigned Opcode)
Translate this non-VP Opcode to its corresponding VP Opcode.
MemIndexType
MemIndexType enum - This enum defines how to interpret MGATHER/SCATTER's index parameter when calcula...
LLVM_ABI bool isBuildVectorAllZeros(const SDNode *N)
Return true if the specified node is a BUILD_VECTOR where all of the elements are 0 or undef.
LLVM_ABI bool isConstantSplatVector(const SDNode *N, APInt &SplatValue)
Node predicates.
LLVM_ABI NodeType getInverseMinMaxOpcode(unsigned MinMaxOpc)
Given a MinMaxOpc of ISD::(U|S)MIN or ISD::(U|S)MAX, returns ISD::(U|S)MAX and ISD::(U|S)MIN,...
LLVM_ABI bool isVPReduction(unsigned Opcode)
Whether this is a vector-predicated reduction opcode.
MemIndexedMode
MemIndexedMode enum - This enum defines the load / store indexed addressing modes.
LLVM_ABI bool isBuildVectorOfConstantFPSDNodes(const SDNode *N)
Return true if the specified node is a BUILD_VECTOR node of all ConstantFPSDNode or undef.
bool isSEXTLoad(const SDNode *N)
Returns true if the specified node is a SEXTLOAD.
CondCode
ISD::CondCode enum - These are ordered carefully to make the bitfields below work out,...
LLVM_ABI bool isBuildVectorAllOnes(const SDNode *N)
Return true if the specified node is a BUILD_VECTOR where all of the elements are ~0 or undef.
LLVM_ABI NodeType getVecReduceBaseOpcode(unsigned VecReduceOpcode)
Get underlying scalar opcode for VECREDUCE opcode.
LoadExtType
LoadExtType enum - This enum defines the three variants of LOADEXT (load with extension).
LLVM_ABI bool isVPOpcode(unsigned Opcode)
Whether this is a vector-predicated Opcode.
bool matchUnaryPredicate(SDValue Op, const APInt &DemandedElts, std::function< bool(ConstantSDNode *)> Match, bool AllowUndefs=false, bool AllowTruncation=false)
Hook for matching ConstantSDNode predicate.
LLVM_ABI CondCode getSetCCOrOperation(CondCode Op1, CondCode Op2, EVT Type)
Return the result of a logical OR between different comparisons of identical values: ((X op1 Y) | (X ...
BinaryOp_match< SpecificConstantMatch, SrcTy, TargetOpcode::G_SUB > m_Neg(const SrcTy &&Src)
Matches a register negated by a G_SUB.
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
match_deferred< Value > m_Deferred(Value *const &V)
Like m_Specific(), but works if the specific value to match is determined as part of the same match()...
auto m_Value()
Match an arbitrary value and ignore it.
BinaryOp_match< LHS, RHS, Instruction::Sub > m_Sub(const LHS &L, const RHS &R)
LLVM_ABI Libcall getMEMCPY_ELEMENT_UNORDERED_ATOMIC(uint64_t ElementSize)
getMEMCPY_ELEMENT_UNORDERED_ATOMIC - Return MEMCPY_ELEMENT_UNORDERED_ATOMIC_* value for the given ele...
LLVM_ABI Libcall getMEMSET_ELEMENT_UNORDERED_ATOMIC(uint64_t ElementSize)
getMEMSET_ELEMENT_UNORDERED_ATOMIC - Return MEMSET_ELEMENT_UNORDERED_ATOMIC_* value for the given ele...
LLVM_ABI Libcall getMEMMOVE_ELEMENT_UNORDERED_ATOMIC(uint64_t ElementSize)
getMEMMOVE_ELEMENT_UNORDERED_ATOMIC - Return MEMMOVE_ELEMENT_UNORDERED_ATOMIC_* value for the given e...
bool sd_match(SDValue N, Pattern &&P)
LLVM_ABI unsigned rot(unsigned SrcSignBits, unsigned BitWidth, std::optional< APInt > RotAmt, bool IsRotateRight)
Compute the number of sign bits after rotating a value.
@ DW_OP_LLVM_arg
Only used in LLVM metadata.
Definition Dwarf.h:149
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract(Y &&MD)
Extract a Value from Metadata.
Definition Metadata.h:679
NodeAddr< NodeBase * > Node
Definition RDFGraph.h:381
This is an optimization pass for GlobalISel generic memory operations.
GenericUniformityInfo< SSAContext > UniformityInfo
unsigned Log2_32_Ceil(uint32_t Value)
Return the ceil log base 2 of the specified value, 32 if the value is zero.
Definition MathExtras.h:339
@ Offset
Definition DWP.cpp:577
bool operator<(int64_t V1, const APSInt &V2)
Definition APSInt.h:360
LLVM_ABI ISD::CondCode getICmpCondCode(ICmpInst::Predicate Pred)
getICmpCondCode - Return the ISD condition code corresponding to the given LLVM IR integer condition ...
Definition Analysis.cpp:248
void fill(R &&Range, T &&Value)
Provide wrappers to std::fill which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1775
LLVM_ABI SDValue peekThroughExtractSubvectors(SDValue V)
Return the non-extracted vector source operand of V if it exists.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
LLVM_ABI bool isNullConstant(SDValue V)
Returns true if V is a constant integer zero.
LLVM_ABI bool isAllOnesOrAllOnesSplat(const MachineInstr &MI, const MachineRegisterInfo &MRI, bool AllowUndefs=false)
Return true if the value is a constant -1 integer or a splatted vector of a constant -1 integer (with...
Definition Utils.cpp:1717
LLVM_ABI SDValue getBitwiseNotOperand(SDValue V, SDValue Mask, bool AllowUndefs)
If V is a bitwise not, returns the inverted operand.
@ Known
Known to have no common set bits.
@ Undef
Value of the register doesn't matter.
LLVM_ABI SDValue peekThroughBitcasts(SDValue V)
Return the non-bitcasted source operand of V if it exists.
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2570
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
int countr_one(T Value)
Count the number of ones from the least significant bit to the first zero bit.
Definition bit.h:315
@ Store
The extracted value is stored (ExtractElement only).
bool isIntOrFPConstant(SDValue V)
Return true if V is either a integer or FP constant.
auto dyn_cast_if_present(const Y &Val)
dyn_cast_if_present<X> - Functionally identical to dyn_cast, except that a null (or none in the case ...
Definition Casting.h:732
LLVM_ABI bool getConstantDataArrayInfo(const Value *V, ConstantDataArraySlice &Slice, unsigned ElementSize, uint64_t Offset=0)
Returns true if the value V is a pointer into a ConstantDataArray.
LLVM_ABI bool isOneOrOneSplatFP(SDValue V, bool AllowUndefs=false)
Return true if the value is a constant floating-point value, or a splatted vector of a constant float...
int bit_width(T Value)
Returns the number of bits needed to represent Value if Value is nonzero.
Definition bit.h:325
LLVM_READONLY APFloat maximum(const APFloat &A, const APFloat &B)
Implements IEEE 754-2019 maximum semantics.
Definition APFloat.h:1816
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2224
constexpr bool isUIntN(unsigned N, uint64_t x)
Checks if an unsigned integer fits into the given (dynamic) bit width.
Definition MathExtras.h:244
LLVM_ABI bool shouldOptimizeForSize(const MachineFunction *MF, ProfileSummaryInfo *PSI, const MachineBlockFrequencyInfo *BFI, PGSOQueryType QueryType=PGSOQueryType::Other)
Returns true if machine function MF is suggested to be size-optimized based on the profile.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:649
LLVM_ABI void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
auto cast_or_null(const Y &Val)
Definition Casting.h:714
LLVM_ABI bool isNullOrNullSplat(const MachineInstr &MI, const MachineRegisterInfo &MRI, bool AllowUndefs=false)
Return true if the value is a constant 0 integer or a splatted vector of a constant 0 integer (with n...
Definition Utils.cpp:1699
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:1728
int countr_zero(T Val)
Count number of 0's from the least significant bit to the most stopping at the first 1.
Definition bit.h:204
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
LLVM_ABI bool getShuffleDemandedElts(int SrcWidth, ArrayRef< int > Mask, const APInt &DemandedElts, APInt &DemandedLHS, APInt &DemandedRHS, bool AllowUndefElts=false)
Transform a shuffle mask's output demanded element mask into demanded element masks for the 2 operand...
LLVM_READONLY APFloat maxnum(const APFloat &A, const APFloat &B)
Implements IEEE-754 2008 maxNum semantics.
Definition APFloat.h:1771
unsigned Log2_32(uint32_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
Definition MathExtras.h:326
LLVM_ABI bool isBitwiseNot(SDValue V, bool AllowUndefs=false)
Returns true if V is a bitwise not operation.
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
LLVM_ABI SDValue peekThroughInsertVectorElt(SDValue V, const APInt &DemandedElts)
Recursively peek through INSERT_VECTOR_ELT nodes, returning the source vector operand of V,...
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition MathExtras.h:280
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
LLVM_ABI void checkForCycles(const SelectionDAG *DAG, bool force=false)
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
LLVM_READONLY APFloat minimumnum(const APFloat &A, const APFloat &B)
Implements IEEE 754-2019 minimumNumber semantics.
Definition APFloat.h:1802
FPClassTest
Floating-point class tests, supported by 'is_fpclass' intrinsic.
LLVM_ABI const MDNode * getMemCacheHintMetadata(const Instruction &I, unsigned OperandNo=0)
Return the cache hint metadata node for memory operand OperandNo on I, or nullptr when the instructio...
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI SDValue peekThroughTruncates(SDValue V)
Return the non-truncated source operand of V if it exists.
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1769
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
constexpr std::underlying_type_t< Enum > to_underlying(Enum E)
Returns underlying integer value of an enum.
LLVM_ABI ConstantRange getVScaleRange(const Function *F, unsigned BitWidth)
Determine the possible constant range of vscale with the given bit width, based on the vscale_range f...
LLVM_ABI SDValue peekThroughOneUseBitcasts(SDValue V)
Return the non-bitcasted and one-use source operand of V if it exists.
CodeGenOptLevel
Code generation optimization level.
Definition CodeGen.h:280
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:1752
@ Sub
Subtraction of integers.
@ Fast
Assign the register banks as fast as possible (default).
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
LLVM_ABI bool isNullConstantOrUndef(SDValue V)
Returns true if V is a constant integer zero or an UNDEF node.
IntPtrTy
Definition InstrProf.h:82
LLVM_ABI bool isInTailCallPosition(const CallBase &Call, const TargetMachine &TM, bool ReturnsFirstArg=false)
Test if the given instruction is in a position to be optimized with a tail-call.
Definition Analysis.cpp:656
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
LLVM_ABI ConstantSDNode * isConstOrConstSplat(SDValue N, bool AllowUndefs=false, bool AllowTruncation=false)
Returns the SDNode if it is a constant splat BuildVector or constant int.
OutputIt copy(R &&Range, OutputIt Out)
Definition STLExtras.h:1901
constexpr unsigned BitWidth
LLVM_ABI bool funcReturnsFirstArgOfCall(const CallInst &CI)
Returns true if the parent of CI returns CI's first argument after calling CI.
Definition Analysis.cpp:835
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI bool isZeroOrZeroSplat(SDValue N, bool AllowUndefs=false)
Return true if the value is a constant 0 integer or a splatted vector of a constant 0 integer (with n...
constexpr auto seq(T Begin, T End)
Iterate over an integral type from Begin up to - but not including - End.
Definition Sequence.h:341
LLVM_ABI bool isOneConstant(SDValue V)
Returns true if V is a constant integer one.
UndefPoisonKind
Enumeration to track whether we are interested in Undef, Poison, or both.
Definition UndefPoison.h:20
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
Align commonAlignment(Align A, uint64_t Offset)
Returns the alignment that satisfies both alignments.
Definition Alignment.h:206
LLVM_ABI bool isNullFPConstant(SDValue V)
Returns true if V is an FP constant with a value of positive zero.
constexpr int64_t SignExtend64(uint64_t x)
Sign-extend the number in the bottom B bits of X to a 64-bit integer.
Definition MathExtras.h:572
unsigned Log2(Align A)
Returns the log2 of the alignment.
Definition Alignment.h:202
LLVM_ABI bool isZeroOrZeroSplatFP(SDValue N, bool AllowUndefs=false)
Return true if the value is a constant (+/-)0.0 floating-point value or a splatted vector thereof (wi...
bool equal(L &&LRange, R &&RRange)
Wrapper function around std::equal to detect if pair-wise elements between two ranges are the same.
Definition STLExtras.h:2162
LLVM_ABI void computeKnownBitsFromRangeMetadata(const MDNode &Ranges, KnownBits &Known)
Compute known bits from the range metadata.
LLVM_READONLY APFloat minimum(const APFloat &A, const APFloat &B)
Implements IEEE 754-2019 minimum semantics.
Definition APFloat.h:1789
LLVM_READONLY APFloat maximumnum(const APFloat &A, const APFloat &B)
Implements IEEE 754-2019 maximumNumber semantics.
Definition APFloat.h:1829
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:881
#define N
A collection of metadata nodes that might be associated with a memory access used by the alias-analys...
Definition Metadata.h:774
MDNode * TBAAStruct
The tag for type-based alias analysis (tbaa struct).
Definition Metadata.h:794
MDNode * TBAA
The tag for type-based alias analysis.
Definition Metadata.h:791
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
constexpr uint64_t value() const
This is a hole in the type system and should not be abused.
Definition Alignment.h:82
static constexpr Align fromLog2(unsigned Log2Value)
Returns an alignment of 1 << Log2Value bytes.
Definition Alignment.h:73
Represents offset+length into a ConstantDataArray.
uint64_t Length
Length of the slice.
uint64_t Offset
Slice starts at this Offset.
void move(uint64_t Delta)
Moves the Offset and adjusts Length accordingly.
const ConstantDataArray * Array
ConstantDataArray pointer.
Extended Value Type.
Definition ValueTypes.h:35
TypeSize getStoreSize() const
Return the number of bytes overwritten by a store of the specified value type.
Definition ValueTypes.h:433
bool isSimple() const
Test if the given EVT is simple (as opposed to being extended).
Definition ValueTypes.h:160
intptr_t getRawBits() const
Definition ValueTypes.h:562
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:144
bool bitsGT(EVT VT) const
Return true if this has more bits than VT.
Definition ValueTypes.h:322
bool bitsLT(EVT VT) const
Return true if this has less bits than VT.
Definition ValueTypes.h:338
bool isFloatingPoint() const
Return true if this is a FP or a vector FP type.
Definition ValueTypes.h:170
ElementCount getVectorElementCount() const
Definition ValueTypes.h:388
TypeSize getSizeInBits() const
Return the size of the specified value type in bits.
Definition ValueTypes.h:411
bool isByteSized() const
Return true if the bit size is a multiple of 8.
Definition ValueTypes.h:281
EVT changeElementCount(LLVMContext &Context, ElementCount EC) const
Return a VT for a type whose attributes match ourselves with the exception of the element count that ...
Definition ValueTypes.h:121
unsigned getVectorMinNumElements() const
Given a vector type, return the minimum number of elements it contains.
Definition ValueTypes.h:397
uint64_t getScalarSizeInBits() const
Definition ValueTypes.h:423
MVT getSimpleVT() const
Return the SimpleValueType held in the specified simple EVT.
Definition ValueTypes.h:354
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:214
bool isVector() const
Return true if this is a vector value type.
Definition ValueTypes.h:191
EVT getScalarType() const
If this is a vector type, return the element type, otherwise return this.
Definition ValueTypes.h:361
bool bitsGE(EVT VT) const
Return true if this has no less bits than VT.
Definition ValueTypes.h:330
bool bitsEq(EVT VT) const
Return true if this has the same number of bits as VT.
Definition ValueTypes.h:294
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:202
EVT getVectorElementType() const
Given a vector type, return the type of each element.
Definition ValueTypes.h:366
bool isExtended() const
Test if the given EVT is extended (as opposed to being simple).
Definition ValueTypes.h:165
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:374
bool bitsLE(EVT VT) const
Return true if this has no more bits than VT.
Definition ValueTypes.h:346
EVT getHalfNumVectorElementsVT(LLVMContext &Context) const
Definition ValueTypes.h:499
bool isInteger() const
Return true if this is an integer or a vector integer type.
Definition ValueTypes.h:175
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.
LLVM IR metadata carried by a MachineMemOperand.
This class contains a discriminated union of information about pointers in memory operands,...
LLVM_ABI bool isDereferenceable(unsigned Size, LLVMContext &C, const DataLayout &DL) const
Return true if memory region [V, V+Offset+Size) is known to be dereferenceable.
LLVM_ABI unsigned getAddrSpace() const
Return the LLVM IR address space number that this pointer points into.
PointerUnion< const Value *, const PseudoSourceValue * > V
This is the IR pointer value for the access, or it is null if unknown.
MachinePointerInfo getWithOffset(int64_t O) const
static LLVM_ABI MachinePointerInfo getFixedStack(MachineFunction &MF, int FI, int64_t Offset=0)
Return a MachinePointerInfo record that refers to the specified FrameIndex.
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
Definition Alignment.h:111
Align valueOrOne() const
For convenience, returns a valid alignment or 1 if undefined.
Definition Alignment.h:135
static MemOp Set(uint64_t Size, bool DstAlignCanChange, Align DstAlign, bool IsZeroMemset, bool IsVolatile)
static MemOp Copy(uint64_t Size, bool DstAlignCanChange, Align DstAlign, Align SrcAlign, bool IsVolatile, bool MemcpyStrSrc=false)
static MemOp Move(uint64_t Size, bool DstAlignCanChange, Align DstAlign, Align SrcAlign, bool IsVolatile)
static StringRef getLibcallImplName(RTLIB::LibcallImpl CallImpl)
Get the libcall routine name for the specified libcall implementation.
These are IR-level optimization flags that may be propagated to SDNodes.
static LLVM_ABI bool isEqual(const KeyTy &Key, const SDNode &N)
The key SelectionDAG uniques SDNodes by.
void AddPointer(const void *P)
SmallVector< SDValue, 0 > OpStorage
Backs Ops when the key is built from a node; empty otherwise.
void AddInteger(T I)
const EVT * VTs
ArrayRef< SDValue > Ops
FoldingSetNodeID Tail
SDNodeKey(unsigned Opcode, SDVTList VTList, ArrayRef< SDValue > Ops)
This represents a list of ValueType's that has been intern'd by a SelectionDAG.
unsigned int NumVTs
Clients of various APIs that cause global effects on the DAG can optionally implement this interface.
virtual void NodeDeleted(SDNode *N, SDNode *E)
The node N that was deleted and, if E is not null, an equivalent node E that replaced it.
virtual void NodeInserted(SDNode *N)
The node N that was inserted.
virtual void NodeUpdated(SDNode *N)
The node N that was updated.
This structure contains all information that is necessary for lowering calls.
CallLoweringInfo & setLibCallee(CallingConv::ID CC, Type *ResultType, SDValue Target, ArgListTy &&ArgsList)
CallLoweringInfo & setDiscardResult(bool Value=true)
CallLoweringInfo & setDebugLoc(const SDLoc &dl)
CallLoweringInfo & setTailCall(bool Value=true)
CallLoweringInfo & setChain(SDValue InChain)