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"
62#include "llvm/IR/Metadata.h"
63#include "llvm/IR/Type.h"
67#include "llvm/Support/Debug.h"
69#include "llvm/Support/FPFold.h"
78#include <algorithm>
79#include <cassert>
80#include <cstdint>
81#include <cstdlib>
82#include <limits>
83#include <optional>
84#include <string>
85#include <utility>
86#include <vector>
87
88using namespace llvm;
89using namespace llvm::SDPatternMatch;
90
91/// makeVTList - Return an instance of the SDVTList struct initialized with the
92/// specified members.
93static SDVTList makeVTList(const EVT *VTs, unsigned NumVTs) {
94 SDVTList Res = {VTs, NumVTs};
95 return Res;
96}
97
98// Default null implementations of the callbacks.
102
103void SelectionDAG::DAGNodeDeletedListener::anchor() {}
104void SelectionDAG::DAGNodeInsertedListener::anchor() {}
105
106#define DEBUG_TYPE "selectiondag"
107
109 LLVM_DEBUG(dbgs() << Msg; V.getNode()->dump(G););
110}
111
113 return getSelectionDAGOptions().has_predecessor_max_steps;
114}
115
116//===----------------------------------------------------------------------===//
117// ConstantFPSDNode Class
118//===----------------------------------------------------------------------===//
119
120/// isExactlyValue - We don't rely on operator== working on double values, as
121/// it returns true for things that are clearly not equal, like -0.0 and 0.0.
122/// As such, this method can be used to do an exact bit-for-bit comparison of
123/// two floating point values.
125 return getValueAPF().bitwiseIsEqual(V);
126}
127
129 const APFloat& Val) {
130 assert(VT.isFloatingPoint() && "Can only convert between FP types");
131
132 // convert modifies in place, so make a copy.
133 APFloat Val2 = APFloat(Val);
134 bool losesInfo;
136 &losesInfo);
137 return !losesInfo;
138}
139
140//===----------------------------------------------------------------------===//
141// ISD Namespace
142//===----------------------------------------------------------------------===//
143
145 if (V.getOpcode() == ISD::SPLAT_VECTOR) {
146 if (auto OptAPInt = V.getOperand(0)->bitcastToAPInt()) {
147 unsigned EltSize =
148 V.getValueType().getVectorElementType().getSizeInBits();
149 SplatVal = OptAPInt->trunc(EltSize);
150 return true;
151 }
152 }
153
154 auto *BV = dyn_cast<BuildVectorSDNode>(V);
155 if (!BV)
156 return false;
157
158 APInt SplatUndef;
159 unsigned SplatBitSize;
160 bool HasUndefs;
161 unsigned EltSize = V.getValueType().getVectorElementType().getSizeInBits();
162 // Endianness does not matter here. We are checking for a splat given the
163 // element size of the vector, and if we find such a splat for little endian
164 // layout, then that should be valid also for big endian (as the full vector
165 // size is known to be a multiple of the element size).
166 const bool IsBigEndian = false;
167 return BV->isConstantSplat(SplatVal, SplatUndef, SplatBitSize, HasUndefs,
168 EltSize, IsBigEndian) &&
169 EltSize == SplatBitSize;
170}
171
172// FIXME: AllOnes and AllZeros duplicate a lot of code. Could these be
173// specializations of the more general isConstantSplatVector()?
174
175bool ISD::isConstantSplatVectorAllOnes(SDValue V, bool BuildVectorOnly) {
176 // Look through a bit convert.
177 while (V.getOpcode() == ISD::BITCAST)
178 V = V.getOperand(0);
179
180 if (!BuildVectorOnly && V.getOpcode() == ISD::SPLAT_VECTOR) {
181 APInt SplatVal;
182 return isConstantSplatVector(V, SplatVal) && SplatVal.isAllOnes();
183 }
184
185 if (V.getOpcode() != ISD::BUILD_VECTOR)
186 return false;
187
188 unsigned i = 0, e = V.getNumOperands();
189
190 // Skip over all of the undef values.
191 while (i != e && V.getOperand(i).isUndef())
192 ++i;
193
194 // Do not accept an all-undef vector.
195 if (i == e) return false;
196
197 // Do not accept build_vectors that aren't all constants or which have non-~0
198 // elements. We have to be a bit careful here, as the type of the constant
199 // may not be the same as the type of the vector elements due to type
200 // legalization (the elements are promoted to a legal type for the target and
201 // a vector of a type may be legal when the base element type is not).
202 // We only want to check enough bits to cover the vector elements, because
203 // we care if the resultant vector is all ones, not whether the individual
204 // constants are.
205 SDValue NotZero = V.getOperand(i);
206 if (auto OptAPInt = NotZero->bitcastToAPInt()) {
207 unsigned EltSize = V.getValueType().getScalarSizeInBits();
208 if (OptAPInt->countr_one() < EltSize)
209 return false;
210 } else
211 return false;
212
213 // Okay, we have at least one ~0 value, check to see if the rest match or are
214 // undefs. Even with the above element type twiddling, this should be OK, as
215 // the same type legalization should have applied to all the elements.
216 for (++i; i != e; ++i)
217 if (V.getOperand(i) != NotZero && !V.getOperand(i).isUndef())
218 return false;
219 return true;
220}
221
222bool ISD::isConstantSplatVectorAllZeros(SDValue V, bool BuildVectorOnly) {
223 // Look through a bit convert.
224 while (V.getOpcode() == ISD::BITCAST)
225 V = V.getOperand(0);
226
227 if (!BuildVectorOnly && V.getOpcode() == ISD::SPLAT_VECTOR) {
228 APInt SplatVal;
229 return isConstantSplatVector(V, SplatVal) && SplatVal.isZero();
230 }
231
232 if (V.getOpcode() != ISD::BUILD_VECTOR)
233 return false;
234
235 bool IsAllUndef = true;
236 for (const SDValue &Op : V->op_values()) {
237 if (Op.isUndef())
238 continue;
239 IsAllUndef = false;
240 // Do not accept build_vectors that aren't all constants or which have non-0
241 // elements. We have to be a bit careful here, as the type of the constant
242 // may not be the same as the type of the vector elements due to type
243 // legalization (the elements are promoted to a legal type for the target
244 // and a vector of a type may be legal when the base element type is not).
245 // We only want to check enough bits to cover the vector elements, because
246 // we care if the resultant vector is all zeros, not whether the individual
247 // constants are.
248 if (auto OptAPInt = Op->bitcastToAPInt()) {
249 unsigned EltSize = V.getValueType().getScalarSizeInBits();
250 if (OptAPInt->countr_zero() < EltSize)
251 return false;
252 } else
253 return false;
254 }
255
256 // Do not accept an all-undef vector.
257 if (IsAllUndef)
258 return false;
259 return true;
260}
261
263 return isConstantSplatVectorAllOnes(V, /*BuildVectorOnly*/ true);
264}
265
267 return isConstantSplatVectorAllZeros(V, /*BuildVectorOnly*/ true);
268}
269
271 if (V.getOpcode() != ISD::BUILD_VECTOR)
272 return false;
273
274 for (const SDValue &Op : V->op_values()) {
275 if (Op.isUndef())
276 continue;
278 return false;
279 }
280 return true;
281}
282
284 if (V.getOpcode() != ISD::BUILD_VECTOR)
285 return false;
286
287 for (const SDValue &Op : V->op_values()) {
288 if (Op.isUndef())
289 continue;
291 return false;
292 }
293 return true;
294}
295
296bool ISD::isVectorShrinkable(SDValue V, unsigned NewEltSize, bool Signed) {
297 assert(V.getValueType().isVector() && "Expected a vector!");
298
299 unsigned EltSize = V.getValueType().getScalarSizeInBits();
300 if (EltSize <= NewEltSize)
301 return false;
302
303 if (V.getOpcode() == ISD::ZERO_EXTEND) {
304 return (V.getOperand(0).getValueType().getScalarSizeInBits() <=
305 NewEltSize) &&
306 !Signed;
307 }
308 if (V.getOpcode() == ISD::SIGN_EXTEND) {
309 return (V.getOperand(0).getValueType().getScalarSizeInBits() <=
310 NewEltSize) &&
311 Signed;
312 }
313 if (V.getOpcode() != ISD::BUILD_VECTOR)
314 return false;
315
316 for (const SDValue &Op : V->op_values()) {
317 if (Op.isUndef())
318 continue;
320 return false;
321
322 APInt C = Op->getAsAPIntVal().trunc(EltSize);
323 if (Signed && C.trunc(NewEltSize).sext(EltSize) != C)
324 return false;
325 if (!Signed && C.trunc(NewEltSize).zext(EltSize) != C)
326 return false;
327 }
328
329 return true;
330}
331
333 // Return false if the node has no operands.
334 // This is "logically inconsistent" with the definition of "all" but
335 // is probably the desired behavior.
336 if (V.getNumOperands() == 0)
337 return false;
338 return all_of(V->op_values(), [](SDValue Op) { return Op.isUndef(); });
339}
340
342 return V.getOpcode() == ISD::FREEZE && V.getOperand(0).isUndef();
343}
344
345template <typename ConstNodeType>
347 std::function<bool(ConstNodeType *)> Match,
348 bool AllowUndefs, bool AllowTruncation) {
349 // FIXME: Add support for scalar UNDEF cases?
350 if (auto *C = dyn_cast<ConstNodeType>(Op))
351 return Match(C);
352
353 // FIXME: Add support for vector UNDEF cases?
354 if (ISD::BUILD_VECTOR != Op.getOpcode() &&
355 ISD::SPLAT_VECTOR != Op.getOpcode())
356 return false;
357
358 if (ISD::SPLAT_VECTOR == Op.getOpcode() && !DemandedElts)
359 return true;
360
361 EVT SVT = Op.getValueType().getScalarType();
362 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
363 if (ISD::SPLAT_VECTOR != Op.getOpcode() && !DemandedElts[i])
364 continue;
365
366 if (AllowUndefs && Op.getOperand(i).isUndef()) {
367 if (!Match(nullptr))
368 return false;
369 continue;
370 }
371
372 auto *Cst = dyn_cast<ConstNodeType>(Op.getOperand(i));
373 if (!Cst || (!AllowTruncation && Cst->getValueType(0) != SVT) ||
374 !Match(Cst))
375 return false;
376 }
377 return true;
378}
379// Build used template types.
381 SDValue, const APInt &, std::function<bool(ConstantSDNode *)>, bool, bool);
383 SDValue, const APInt &, std::function<bool(ConstantFPSDNode *)>, bool,
384 bool);
385
387 SDValue LHS, SDValue RHS, const APInt &DemandedElts,
388 std::function<bool(ConstantSDNode *, ConstantSDNode *)> Match,
389 bool AllowUndefs, bool AllowTypeMismatch) {
390 if (!AllowTypeMismatch && LHS.getValueType() != RHS.getValueType())
391 return false;
392
393 // TODO: Add support for scalar UNDEF cases?
394 if (auto *LHSCst = dyn_cast<ConstantSDNode>(LHS))
395 if (auto *RHSCst = dyn_cast<ConstantSDNode>(RHS))
396 return Match(LHSCst, RHSCst);
397
398 // TODO: Add support for vector UNDEF cases?
399 if (LHS.getOpcode() != RHS.getOpcode() ||
400 (LHS.getOpcode() != ISD::BUILD_VECTOR &&
401 LHS.getOpcode() != ISD::SPLAT_VECTOR))
402 return false;
403
404 if (ISD::SPLAT_VECTOR == LHS.getOpcode() && !DemandedElts)
405 return true;
406
407 EVT SVT = LHS.getValueType().getScalarType();
408 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
409 if (ISD::SPLAT_VECTOR != LHS.getOpcode() && !DemandedElts[i])
410 continue;
411 SDValue LHSOp = LHS.getOperand(i);
412 SDValue RHSOp = RHS.getOperand(i);
413 bool LHSUndef = AllowUndefs && LHSOp.isUndef();
414 bool RHSUndef = AllowUndefs && RHSOp.isUndef();
415 auto *LHSCst = dyn_cast<ConstantSDNode>(LHSOp);
416 auto *RHSCst = dyn_cast<ConstantSDNode>(RHSOp);
417 if ((!LHSCst && !LHSUndef) || (!RHSCst && !RHSUndef))
418 return false;
419 if (!AllowTypeMismatch && (LHSOp.getValueType() != SVT ||
420 LHSOp.getValueType() != RHSOp.getValueType()))
421 return false;
422 if (!Match(LHSCst, RHSCst))
423 return false;
424 }
425 return true;
426}
427
429 switch (MinMaxOpc) {
430 default:
431 llvm_unreachable("unrecognized opcode");
432 case ISD::UMIN:
433 return ISD::UMAX;
434 case ISD::UMAX:
435 return ISD::UMIN;
436 case ISD::SMIN:
437 return ISD::SMAX;
438 case ISD::SMAX:
439 return ISD::SMIN;
440 }
441}
442
444 switch (MinMaxOpc) {
445 default:
446 llvm_unreachable("unrecognized min/max opcode");
447 case ISD::SMIN:
448 return ISD::UMIN;
449 case ISD::SMAX:
450 return ISD::UMAX;
451 case ISD::UMIN:
452 return ISD::SMIN;
453 case ISD::UMAX:
454 return ISD::SMAX;
455 }
456}
457
459 switch (VecReduceOpcode) {
460 default:
461 llvm_unreachable("Expected VECREDUCE opcode");
464 case ISD::VP_REDUCE_FADD:
465 case ISD::VP_REDUCE_SEQ_FADD:
466 return ISD::FADD;
469 case ISD::VP_REDUCE_FMUL:
470 case ISD::VP_REDUCE_SEQ_FMUL:
471 return ISD::FMUL;
473 case ISD::VP_REDUCE_ADD:
474 return ISD::ADD;
476 case ISD::VP_REDUCE_MUL:
477 return ISD::MUL;
479 case ISD::VP_REDUCE_AND:
480 return ISD::AND;
482 case ISD::VP_REDUCE_OR:
483 return ISD::OR;
485 case ISD::VP_REDUCE_XOR:
486 return ISD::XOR;
488 case ISD::VP_REDUCE_SMAX:
489 return ISD::SMAX;
491 case ISD::VP_REDUCE_SMIN:
492 return ISD::SMIN;
494 case ISD::VP_REDUCE_UMAX:
495 return ISD::UMAX;
497 case ISD::VP_REDUCE_UMIN:
498 return ISD::UMIN;
500 case ISD::VP_REDUCE_FMAX:
501 return ISD::FMAXNUM;
503 case ISD::VP_REDUCE_FMIN:
504 return ISD::FMINNUM;
506 case ISD::VP_REDUCE_FMAXIMUM:
507 return ISD::FMAXIMUM;
509 case ISD::VP_REDUCE_FMINIMUM:
510 return ISD::FMINIMUM;
512 return ISD::FMAXIMUMNUM;
514 return ISD::FMINIMUMNUM;
515 }
516}
517
519 switch (MaskedOpc) {
520 case ISD::MASKED_UDIV:
521 return ISD::UDIV;
522 case ISD::MASKED_SDIV:
523 return ISD::SDIV;
524 case ISD::MASKED_UREM:
525 return ISD::UREM;
526 case ISD::MASKED_SREM:
527 return ISD::SREM;
528 default:
529 llvm_unreachable("Expected masked binop opcode");
530 }
531}
532
533bool ISD::isVPOpcode(unsigned Opcode) {
534 switch (Opcode) {
535 default:
536 return false;
537#define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) \
538 case ISD::VPSD: \
539 return true;
540#include "llvm/IR/VPIntrinsics.def"
541 }
542}
543
544bool ISD::isVPBinaryOp(unsigned Opcode) {
545 switch (Opcode) {
546 default:
547 break;
548#define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) case ISD::VPSD:
549#define VP_PROPERTY_BINARYOP return true;
550#define END_REGISTER_VP_SDNODE(VPSD) break;
551#include "llvm/IR/VPIntrinsics.def"
552 }
553 return false;
554}
555
556bool ISD::isVPReduction(unsigned Opcode) {
557 switch (Opcode) {
558 default:
559 return false;
560 case ISD::VP_REDUCE_ADD:
561 case ISD::VP_REDUCE_MUL:
562 case ISD::VP_REDUCE_AND:
563 case ISD::VP_REDUCE_OR:
564 case ISD::VP_REDUCE_XOR:
565 case ISD::VP_REDUCE_SMAX:
566 case ISD::VP_REDUCE_SMIN:
567 case ISD::VP_REDUCE_UMAX:
568 case ISD::VP_REDUCE_UMIN:
569 case ISD::VP_REDUCE_FMAX:
570 case ISD::VP_REDUCE_FMIN:
571 case ISD::VP_REDUCE_FMAXIMUM:
572 case ISD::VP_REDUCE_FMINIMUM:
573 case ISD::VP_REDUCE_FADD:
574 case ISD::VP_REDUCE_FMUL:
575 case ISD::VP_REDUCE_SEQ_FADD:
576 case ISD::VP_REDUCE_SEQ_FMUL:
577 return true;
578 }
579}
580
581/// The operand position of the vector mask.
582std::optional<unsigned> ISD::getVPMaskIdx(unsigned Opcode) {
583 switch (Opcode) {
584 default:
585 return std::nullopt;
586#define BEGIN_REGISTER_VP_SDNODE(VPSD, LEGALPOS, TDNAME, MASKPOS, ...) \
587 case ISD::VPSD: \
588 return MASKPOS;
589#include "llvm/IR/VPIntrinsics.def"
590 }
591}
592
593/// The operand position of the explicit vector length parameter.
594std::optional<unsigned> ISD::getVPExplicitVectorLengthIdx(unsigned Opcode) {
595 switch (Opcode) {
596 default:
597 return std::nullopt;
598#define BEGIN_REGISTER_VP_SDNODE(VPSD, LEGALPOS, TDNAME, MASKPOS, EVLPOS) \
599 case ISD::VPSD: \
600 return EVLPOS;
601#include "llvm/IR/VPIntrinsics.def"
602 }
603}
604
605std::optional<unsigned> ISD::getBaseOpcodeForVP(unsigned VPOpcode,
606 bool hasFPExcept) {
607 // FIXME: Return strict opcodes in case of fp exceptions.
608 switch (VPOpcode) {
609 default:
610 return std::nullopt;
611#define BEGIN_REGISTER_VP_SDNODE(VPOPC, ...) case ISD::VPOPC:
612#define VP_PROPERTY_FUNCTIONAL_SDOPC(SDOPC) return ISD::SDOPC;
613#define END_REGISTER_VP_SDNODE(VPOPC) break;
614#include "llvm/IR/VPIntrinsics.def"
615 }
616 return std::nullopt;
617}
618
619std::optional<unsigned> ISD::getVPForBaseOpcode(unsigned Opcode) {
620 switch (Opcode) {
621 default:
622 return std::nullopt;
623#define BEGIN_REGISTER_VP_SDNODE(VPOPC, ...) break;
624#define VP_PROPERTY_FUNCTIONAL_SDOPC(SDOPC) case ISD::SDOPC:
625#define END_REGISTER_VP_SDNODE(VPOPC) return ISD::VPOPC;
626#include "llvm/IR/VPIntrinsics.def"
627 }
628}
629
631 switch (ExtType) {
632 case ISD::EXTLOAD:
633 return IsFP ? ISD::FP_EXTEND : ISD::ANY_EXTEND;
634 case ISD::SEXTLOAD:
635 return ISD::SIGN_EXTEND;
636 case ISD::ZEXTLOAD:
637 return ISD::ZERO_EXTEND;
638 default:
639 break;
640 }
641
642 llvm_unreachable("Invalid LoadExtType");
643}
644
646 // To perform this operation, we just need to swap the L and G bits of the
647 // operation.
648 unsigned OldL = (Operation >> 2) & 1;
649 unsigned OldG = (Operation >> 1) & 1;
650 return ISD::CondCode((Operation & ~6) | // Keep the N, U, E bits
651 (OldL << 1) | // New G bit
652 (OldG << 2)); // New L bit.
653}
654
656 unsigned Operation = Op;
657 if (isIntegerLike)
658 Operation ^= 7; // Flip L, G, E bits, but not U.
659 else
660 Operation ^= 15; // Flip all of the condition bits.
661
663 Operation &= ~8; // Don't let N and U bits get set.
664
665 return ISD::CondCode(Operation);
666}
667
671
673 bool isIntegerLike) {
674 return getSetCCInverseImpl(Op, isIntegerLike);
675}
676
677/// For an integer comparison, return 1 if the comparison is a signed operation
678/// and 2 if the result is an unsigned comparison. Return zero if the operation
679/// does not depend on the sign of the input (setne and seteq).
680static int isSignedOp(ISD::CondCode Opcode) {
681 switch (Opcode) {
682 default: llvm_unreachable("Illegal integer setcc operation!");
683 case ISD::SETEQ:
684 case ISD::SETNE: return 0;
685 case ISD::SETLT:
686 case ISD::SETLE:
687 case ISD::SETGT:
688 case ISD::SETGE: return 1;
689 case ISD::SETULT:
690 case ISD::SETULE:
691 case ISD::SETUGT:
692 case ISD::SETUGE: return 2;
693 }
694}
695
697 EVT Type) {
698 bool IsInteger = Type.isInteger();
699 if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
700 // Cannot fold a signed integer setcc with an unsigned integer setcc.
701 return ISD::SETCC_INVALID;
702
703 unsigned Op = Op1 | Op2; // Combine all of the condition bits.
704
705 // If the N and U bits get set, then the resultant comparison DOES suddenly
706 // care about orderedness, and it is true when ordered.
707 if (Op > ISD::SETTRUE2)
708 Op &= ~16; // Clear the U bit if the N bit is set.
709
710 // Canonicalize illegal integer setcc's.
711 if (IsInteger && Op == ISD::SETUNE) // e.g. SETUGT | SETULT
712 Op = ISD::SETNE;
713
714 return ISD::CondCode(Op);
715}
716
718 EVT Type) {
719 bool IsInteger = Type.isInteger();
720 if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
721 // Cannot fold a signed setcc with an unsigned setcc.
722 return ISD::SETCC_INVALID;
723
724 // Combine all of the condition bits.
725 ISD::CondCode Result = ISD::CondCode(Op1 & Op2);
726
727 // Canonicalize illegal integer setcc's.
728 if (IsInteger) {
729 switch (Result) {
730 default: break;
731 case ISD::SETUO : Result = ISD::SETFALSE; break; // SETUGT & SETULT
732 case ISD::SETOEQ: // SETEQ & SETU[LG]E
733 case ISD::SETUEQ: Result = ISD::SETEQ ; break; // SETUGE & SETULE
734 case ISD::SETOLT: Result = ISD::SETULT ; break; // SETULT & SETNE
735 case ISD::SETOGT: Result = ISD::SETUGT ; break; // SETUGT & SETNE
736 }
737 }
738
739 return Result;
740}
741
742//===----------------------------------------------------------------------===//
743// SDNode Key Support
744//===----------------------------------------------------------------------===//
745
746/// If this is an SDNode with special info, add this info to the NodeID data.
747/// MorphNodeTo passes the opcode \p N is becoming, so \p Opc may differ from
748/// N->getOpcode() and a case may only cast to a class \p N already is.
749static void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N,
750 unsigned Opc) {
751 // Machine nodes are uniqued by opcode, value types and operands alone, as in
752 // getMachineNode; MorphNodeTo's clearMemRefs overwrites the fields below.
754 return;
755
756 switch (Opc) {
759 case ISD::MCSymbol:
760 llvm_unreachable("Should only be used on nodes with operands");
761 default: break; // Normal nodes don't need extra info.
763 case ISD::Constant: {
765 ID.AddPointer(C->getConstantIntValue());
766 ID.AddBoolean(C->isOpaque());
767 break;
768 }
770 case ISD::ConstantFP:
771 ID.AddPointer(cast<ConstantFPSDNode>(N)->getConstantFPValue());
772 break;
778 ID.AddPointer(GA->getGlobal());
779 ID.AddInteger(GA->getOffset());
780 ID.AddInteger(GA->getTargetFlags());
781 break;
782 }
783 case ISD::BasicBlock:
784 ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock());
785 break;
786 case ISD::EH_LABEL:
788 ID.AddPointer(cast<LabelSDNode>(N)->getLabel());
789 break;
791 ID.AddPointer(cast<DeactivationSymbolSDNode>(N)->getGlobal());
792 break;
793 case ISD::Register:
794 ID.AddInteger(cast<RegisterSDNode>(N)->getReg().id());
795 break;
797 ID.AddPointer(cast<RegisterMaskSDNode>(N)->getRegMask());
798 break;
799 case ISD::SRCVALUE:
800 ID.AddPointer(cast<SrcValueSDNode>(N)->getValue());
801 break;
802 case ISD::FrameIndex:
804 ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex());
805 break;
807 ID.AddInteger(cast<PseudoProbeSDNode>(N)->getGuid());
808 ID.AddInteger(cast<PseudoProbeSDNode>(N)->getIndex());
809 ID.AddInteger(cast<PseudoProbeSDNode>(N)->getAttributes());
810 break;
811 case ISD::JumpTable:
813 ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex());
814 ID.AddInteger(cast<JumpTableSDNode>(N)->getTargetFlags());
815 break;
819 ID.AddInteger(CP->getAlign().value());
820 ID.AddInteger(CP->getOffset());
823 else
824 ID.AddPointer(CP->getConstVal());
825 ID.AddInteger(CP->getTargetFlags());
826 break;
827 }
828 case ISD::TargetIndex: {
830 ID.AddInteger(TI->getIndex());
831 ID.AddInteger(TI->getOffset());
832 ID.AddInteger(TI->getTargetFlags());
833 break;
834 }
835 case ISD::LOAD: {
836 const LoadSDNode *LD = cast<LoadSDNode>(N);
837 ID.AddInteger(LD->getMemoryVT().getRawBits());
838 ID.AddInteger(LD->getRawSubclassData());
839 ID.AddInteger(LD->getPointerInfo().getAddrSpace());
840 ID.AddInteger(LD->getMemOperand()->getFlags());
841 break;
842 }
843 case ISD::STORE: {
844 const StoreSDNode *ST = cast<StoreSDNode>(N);
845 ID.AddInteger(ST->getMemoryVT().getRawBits());
846 ID.AddInteger(ST->getRawSubclassData());
847 ID.AddInteger(ST->getPointerInfo().getAddrSpace());
848 ID.AddInteger(ST->getMemOperand()->getFlags());
849 break;
850 }
851 case ISD::VP_LOAD: {
852 const VPLoadSDNode *ELD = cast<VPLoadSDNode>(N);
853 ID.AddInteger(ELD->getMemoryVT().getRawBits());
854 ID.AddInteger(ELD->getRawSubclassData());
855 ID.AddInteger(ELD->getPointerInfo().getAddrSpace());
856 ID.AddInteger(ELD->getMemOperand()->getFlags());
857 break;
858 }
859 case ISD::VP_LOAD_FF: {
860 const auto *LD = cast<VPLoadFFSDNode>(N);
861 ID.AddInteger(LD->getMemoryVT().getRawBits());
862 ID.AddInteger(LD->getRawSubclassData());
863 ID.AddInteger(LD->getPointerInfo().getAddrSpace());
864 ID.AddInteger(LD->getMemOperand()->getFlags());
865 break;
866 }
867 case ISD::VP_STORE: {
868 const VPStoreSDNode *EST = cast<VPStoreSDNode>(N);
869 ID.AddInteger(EST->getMemoryVT().getRawBits());
870 ID.AddInteger(EST->getRawSubclassData());
871 ID.AddInteger(EST->getPointerInfo().getAddrSpace());
872 ID.AddInteger(EST->getMemOperand()->getFlags());
873 break;
874 }
875 case ISD::EXPERIMENTAL_VP_STRIDED_LOAD: {
877 ID.AddInteger(SLD->getMemoryVT().getRawBits());
878 ID.AddInteger(SLD->getRawSubclassData());
879 ID.AddInteger(SLD->getPointerInfo().getAddrSpace());
880 break;
881 }
882 case ISD::EXPERIMENTAL_VP_STRIDED_STORE: {
884 ID.AddInteger(SST->getMemoryVT().getRawBits());
885 ID.AddInteger(SST->getRawSubclassData());
886 ID.AddInteger(SST->getPointerInfo().getAddrSpace());
887 break;
888 }
889 case ISD::VP_GATHER: {
891 ID.AddInteger(EG->getMemoryVT().getRawBits());
892 ID.AddInteger(EG->getRawSubclassData());
893 ID.AddInteger(EG->getPointerInfo().getAddrSpace());
894 ID.AddInteger(EG->getMemOperand()->getFlags());
895 break;
896 }
897 case ISD::VP_SCATTER: {
899 ID.AddInteger(ES->getMemoryVT().getRawBits());
900 ID.AddInteger(ES->getRawSubclassData());
901 ID.AddInteger(ES->getPointerInfo().getAddrSpace());
902 ID.AddInteger(ES->getMemOperand()->getFlags());
903 break;
904 }
905 case ISD::MLOAD: {
907 ID.AddInteger(MLD->getMemoryVT().getRawBits());
908 ID.AddInteger(MLD->getRawSubclassData());
909 ID.AddInteger(MLD->getPointerInfo().getAddrSpace());
910 ID.AddInteger(MLD->getMemOperand()->getFlags());
911 break;
912 }
913 case ISD::MSTORE: {
915 ID.AddInteger(MST->getMemoryVT().getRawBits());
916 ID.AddInteger(MST->getRawSubclassData());
917 ID.AddInteger(MST->getPointerInfo().getAddrSpace());
918 ID.AddInteger(MST->getMemOperand()->getFlags());
919 break;
920 }
921 case ISD::MGATHER: {
923 ID.AddInteger(MG->getMemoryVT().getRawBits());
924 ID.AddInteger(MG->getRawSubclassData());
925 ID.AddInteger(MG->getPointerInfo().getAddrSpace());
926 ID.AddInteger(MG->getMemOperand()->getFlags());
927 break;
928 }
929 case ISD::MSCATTER:
933 const MemSDNode *M = cast<MemSDNode>(N);
934 ID.AddInteger(M->getMemoryVT().getRawBits());
935 ID.AddInteger(M->getRawSubclassData());
936 ID.AddInteger(M->getPointerInfo().getAddrSpace());
937 ID.AddInteger(M->getMemOperand()->getFlags());
938 break;
939 }
940 case ISD::VECTOR_SHUFFLE: {
941 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(N)->getMask();
942 for (int M : Mask)
943 ID.AddInteger(M);
944 break;
945 }
946 case ISD::ADDRSPACECAST: {
948 ID.AddInteger(ASC->getSrcAddressSpace());
949 ID.AddInteger(ASC->getDestAddressSpace());
950 break;
951 }
953 case ISD::BlockAddress: {
955 ID.AddPointer(BA->getBlockAddress());
956 ID.AddInteger(BA->getOffset());
957 ID.AddInteger(BA->getTargetFlags());
958 break;
959 }
960 case ISD::AssertAlign:
961 ID.AddInteger(cast<AssertAlignSDNode>(N)->getAlign().value());
962 break;
963 case ISD::PREFETCH:
966 // Handled by MemIntrinsicSDNode check after the switch.
967 break;
969 ID.AddPointer(cast<MDNodeSDNode>(N)->getMD());
970 break;
971 } // end switch (Opc)
972
973 if (auto *AT = dyn_cast<AtomicSDNode>(N)) {
974 ID.AddInteger(AT->getMemoryVT().getRawBits());
975 ID.AddInteger(AT->getRawSubclassData());
976 ID.AddInteger(AT->getPointerInfo().getAddrSpace());
977 ID.AddInteger(AT->getMemOperand()->getFlags());
978 }
979
980 // MemIntrinsic nodes could also have subclass data, address spaces, and flags
981 // to check.
982 if (auto *MN = dyn_cast<MemIntrinsicSDNode>(N)) {
983 ID.AddInteger(MN->getRawSubclassData());
984 ID.AddInteger(MN->getMemoryVT().getRawBits());
985 for (const MachineMemOperand *MMO : MN->memoperands()) {
986 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
987 ID.AddInteger(MMO->getFlags());
988 }
989 }
990}
991
993 : Opcode(N.getOpcode()), VTs(N.getVTList().VTs),
994 OpStorage(N.op_begin(), N.op_end()) {
995 Ops = OpStorage;
996 AddNodeIDCustom(Tail, &N, N.getOpcode());
997}
998
999#ifndef NDEBUG
1000/// Serialize a node the way SDNodes were uniqued before SDNodeKey, to
1001/// cross-check the typed comparison against. Deliberately reads the node
1002/// rather than going through SDNodeKey, so the key constructor is checked too
1003/// and not used as its own oracle.
1004static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) {
1005 ID.AddInteger(N->getOpcode());
1006 ID.AddPointer(N->getVTList().VTs);
1007 for (const SDUse &Op : N->ops()) {
1008 ID.AddPointer(Op.getNode());
1009 ID.AddInteger(Op.getResNo());
1010 }
1011 AddNodeIDCustom(ID, N, N->getOpcode());
1012}
1013
1015 ID.AddInteger(Key.Opcode);
1016 ID.AddPointer(Key.VTs);
1017 for (const SDValue &Op : Key.Ops) {
1018 ID.AddPointer(Op.getNode());
1019 ID.AddInteger(Op.getResNo());
1020 }
1021 ID.AddNodeID(Key.Tail);
1022}
1023#endif
1024
1025static bool keyMatches(const SDNodeKey &Key, const SDNode &N) {
1026 if (N.getOpcode() != Key.Opcode || N.getVTList().VTs != Key.VTs)
1027 return false;
1028 if (!llvm::equal(N.ops(), Key.Ops))
1029 return false;
1030 // Build only what AddNodeIDCustom would have added, which is nothing for
1031 // most opcodes, rather than the whole profile.
1032 FoldingSetNodeID Tail;
1033 AddNodeIDCustom(Tail, &N, N.getOpcode());
1034 return Tail == Key.Tail;
1035}
1036
1038 bool Result = keyMatches(Key, N);
1039
1040#ifndef NDEBUG
1041 FoldingSetNodeID NodeProfile, KeyProfile;
1042 AddNodeIDNode(NodeProfile, &N);
1043 AddNodeIDNode(KeyProfile, Key);
1044 assert((NodeProfile == KeyProfile) == Result &&
1045 "SDNodeKey equality disagrees with profile");
1046#endif
1047 return Result;
1048}
1049
1050//===----------------------------------------------------------------------===//
1051// SelectionDAG Class
1052//===----------------------------------------------------------------------===//
1053
1054/// doNotCSE - Return true if CSE should not be performed for this node.
1055static bool doNotCSE(SDNode *N) {
1056 if (N->getValueType(0) == MVT::Glue)
1057 return true; // Never CSE anything that produces a glue result.
1058
1059 switch (N->getOpcode()) {
1060 default: break;
1061 case ISD::HANDLENODE:
1062 case ISD::EH_LABEL:
1063 return true; // Never CSE these nodes.
1064 }
1065
1066 // Check that remaining values produced are not flags.
1067 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
1068 if (N->getValueType(i) == MVT::Glue)
1069 return true; // Never CSE anything that produces a glue result.
1070
1071 return false;
1072}
1073
1074/// Construct a DemandedElts mask which demands all elements of \p V.
1075/// If \p V is not a fixed-length vector, then this will return a single bit.
1077 EVT VT = V.getValueType();
1078 // Since the number of lanes in a scalable vector is unknown at compile time,
1079 // we track one bit which is implicitly broadcast to all lanes. This means
1080 // that all lanes in a scalable vector are considered demanded.
1082 : APInt(1, 1);
1083}
1084
1085/// RemoveDeadNodes - This method deletes all unreachable nodes in the
1086/// SelectionDAG.
1088 // Create a dummy node (which is not added to allnodes), that adds a reference
1089 // to the root node, preventing it from being deleted.
1090 HandleSDNode Dummy(getRoot());
1091
1092 SmallVector<SDNode*, 128> DeadNodes;
1093
1094 // Add all obviously-dead nodes to the DeadNodes worklist.
1095 for (SDNode &Node : allnodes())
1096 if (Node.use_empty())
1097 DeadNodes.push_back(&Node);
1098
1099 RemoveDeadNodes(DeadNodes);
1100
1101 // If the root changed (e.g. it was a dead load, update the root).
1102 setRoot(Dummy.getValue());
1103}
1104
1105/// RemoveDeadNodes - This method deletes the unreachable nodes in the
1106/// given list, and any nodes that become unreachable as a result.
1108
1109 // Process the worklist, deleting the nodes and adding their uses to the
1110 // worklist.
1111 while (!DeadNodes.empty()) {
1112 SDNode *N = DeadNodes.pop_back_val();
1113 // Skip to next node if we've already managed to delete the node. This could
1114 // happen if replacing a node causes a node previously added to the node to
1115 // be deleted.
1116 if (N->getOpcode() == ISD::DELETED_NODE)
1117 continue;
1118
1119 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1120 DUL->NodeDeleted(N, nullptr);
1121
1122 // Take the node out of the appropriate CSE map.
1123 RemoveNodeFromCSEMaps(N);
1124
1125 // Next, brutally remove the operand list. This is safe to do, as there are
1126 // no cycles in the graph.
1127 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
1128 SDUse &Use = *I++;
1129 SDNode *Operand = Use.getNode();
1130 Use.set(SDValue());
1131
1132 // Now that we removed this operand, see if there are no uses of it left.
1133 if (Operand->use_empty())
1134 DeadNodes.push_back(Operand);
1135 }
1136
1137 DeallocateNode(N);
1138 }
1139}
1140
1142 SmallVector<SDNode*, 16> DeadNodes(1, N);
1143
1144 // Create a dummy node that adds a reference to the root node, preventing
1145 // it from being deleted. (This matters if the root is an operand of the
1146 // dead node.)
1147 HandleSDNode Dummy(getRoot());
1148
1149 RemoveDeadNodes(DeadNodes);
1150}
1151
1153 // First take this out of the appropriate CSE map.
1154 RemoveNodeFromCSEMaps(N);
1155
1156 // Finally, remove uses due to operands of this node, remove from the
1157 // AllNodes list, and delete the node.
1158 DeleteNodeNotInCSEMaps(N);
1159}
1160
1161void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
1162 assert(N->getIterator() != AllNodes.begin() &&
1163 "Cannot delete the entry node!");
1164 assert(N->use_empty() && "Cannot delete a node that is not dead!");
1165
1166 // Drop all of the operands and decrement used node's use counts.
1167 N->DropOperands();
1168
1169 DeallocateNode(N);
1170}
1171
1172void SDDbgInfo::add(SDDbgValue *V, bool isParameter) {
1173 assert(!(V->isVariadic() && isParameter));
1174 if (isParameter)
1175 ByvalParmDbgValues.push_back(V);
1176 else
1177 DbgValues.push_back(V);
1178 for (const SDNode *Node : V->getSDNodes())
1179 if (Node)
1180 DbgValMap[Node].push_back(V);
1181}
1182
1184 DbgValMapType::iterator I = DbgValMap.find(Node);
1185 if (I == DbgValMap.end())
1186 return;
1187 for (auto &Val: I->second)
1188 Val->setIsInvalidated();
1189 DbgValMap.erase(I);
1190}
1191
1192void SelectionDAG::DeallocateNode(SDNode *N) {
1193 // If we have operands, deallocate them.
1195
1196 NodeAllocator.Deallocate(AllNodes.remove(N));
1197
1198 // Set the opcode to DELETED_NODE to help catch bugs when node
1199 // memory is reallocated.
1200 // FIXME: There are places in SDag that have grown a dependency on the opcode
1201 // value in the released node.
1202 __asan_unpoison_memory_region(&N->NodeType, sizeof(N->NodeType));
1203 N->NodeType = ISD::DELETED_NODE;
1204
1205 // If any of the SDDbgValue nodes refer to this SDNode, invalidate
1206 // them and forget about that node.
1207 DbgInfo->erase(N);
1208
1209 // Invalidate extra info.
1210 SDEI.erase(N);
1211}
1212
1213#ifndef NDEBUG
1214/// VerifySDNode - Check the given SDNode. Aborts if it is invalid.
1215void SelectionDAG::verifyNode(SDNode *N) const {
1216 switch (N->getOpcode()) {
1217 default:
1218 if (N->isTargetOpcode())
1220 break;
1221 case ISD::BUILD_PAIR: {
1222 EVT VT = N->getValueType(0);
1223 assert(N->getNumValues() == 1 && "Too many results!");
1224 assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) &&
1225 "Wrong return type!");
1226 assert(N->getNumOperands() == 2 && "Wrong number of operands!");
1227 assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() &&
1228 "Mismatched operand types!");
1229 assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() &&
1230 "Wrong operand type!");
1231 assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() &&
1232 "Wrong return type size");
1233 break;
1234 }
1235 case ISD::BUILD_VECTOR: {
1236 assert(N->getNumValues() == 1 && "Too many results!");
1237 assert(N->getValueType(0).isVector() && "Wrong return type!");
1238 assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() &&
1239 "Wrong number of operands!");
1240 EVT EltVT = N->getValueType(0).getVectorElementType();
1241 for (const SDUse &Op : N->ops()) {
1242 assert((Op.getValueType() == EltVT ||
1243 (EltVT.isInteger() && Op.getValueType().isInteger() &&
1244 EltVT.bitsLE(Op.getValueType()))) &&
1245 "Wrong operand type!");
1246 assert(Op.getValueType() == N->getOperand(0).getValueType() &&
1247 "Operands must all have the same type");
1248 }
1249 break;
1250 }
1251 case ISD::SADDO:
1252 case ISD::UADDO:
1253 case ISD::SSUBO:
1254 case ISD::USUBO:
1255 assert(N->getNumValues() == 2 && "Wrong number of results!");
1256 assert(N->getVTList().NumVTs == 2 && N->getNumOperands() == 2 &&
1257 "Invalid add/sub overflow op!");
1258 assert(N->getVTList().VTs[0].isInteger() &&
1259 N->getVTList().VTs[1].isInteger() &&
1260 N->getOperand(0).getValueType() == N->getOperand(1).getValueType() &&
1261 N->getOperand(0).getValueType() == N->getVTList().VTs[0] &&
1262 "Binary operator types must match!");
1263 break;
1264 }
1265}
1266#endif // NDEBUG
1267
1268/// Insert a newly allocated node into the DAG.
1269///
1270/// Handles insertion into the all nodes list and CSE map, as well as
1271/// verification and other common operations when a new node is allocated.
1272void SelectionDAG::InsertNode(SDNode *N) {
1273 AllNodes.push_back(N);
1274#ifndef NDEBUG
1275 N->PersistentId = NextPersistentId++;
1276 verifyNode(N);
1277#endif
1278 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1279 DUL->NodeInserted(N);
1280}
1281
1282/// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
1283/// correspond to it. This is useful when we're about to delete or repurpose
1284/// the node. We don't want future request for structurally identical nodes
1285/// to return N anymore.
1286bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
1287 bool Erased = false;
1288 switch (N->getOpcode()) {
1289 case ISD::HANDLENODE: return false; // noop.
1290 case ISD::CONDCODE:
1291 assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
1292 "Cond code doesn't exist!");
1293 Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != nullptr;
1294 CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = nullptr;
1295 break;
1297 Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
1298 break;
1300 ExternalSymbolSDNode *ESN = cast<ExternalSymbolSDNode>(N);
1301 Erased = TargetExternalSymbols.erase(std::pair<std::string, unsigned>(
1302 ESN->getSymbol(), ESN->getTargetFlags()));
1303 break;
1304 }
1305 case ISD::MCSymbol: {
1306 auto *MCSN = cast<MCSymbolSDNode>(N);
1307 Erased = MCSymbols.erase(MCSN->getMCSymbol());
1308 break;
1309 }
1310 case ISD::VALUETYPE: {
1311 EVT VT = cast<VTSDNode>(N)->getVT();
1312 if (VT.isExtended()) {
1313 Erased = ExtendedValueTypeNodes.erase(VT);
1314 } else {
1315 Erased = ValueTypeNodes[VT.getSimpleVT().SimpleTy] != nullptr;
1316 ValueTypeNodes[VT.getSimpleVT().SimpleTy] = nullptr;
1317 }
1318 break;
1319 }
1320 default:
1321 // Remove it from the CSE Map.
1322 assert(N->getOpcode() != ISD::DELETED_NODE && "DELETED_NODE in CSEMap!");
1323 assert(N->getOpcode() != ISD::EntryToken && "EntryToken in CSEMap!");
1324 Erased = CSEMap.erase(N);
1325 break;
1326 }
1327#ifndef NDEBUG
1328 // Verify that the node was actually in one of the CSE maps, unless it has a
1329 // glue result (which cannot be CSE'd) or is one of the special cases that are
1330 // not subject to CSE.
1331 if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Glue &&
1332 !N->isMachineOpcode() && !doNotCSE(N)) {
1333 N->dump(this);
1334 dbgs() << "\n";
1335 llvm_unreachable("Node is not in map!");
1336 }
1337#endif
1338 return Erased;
1339}
1340
1341/// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE
1342/// maps and modified in place. Add it back to the CSE maps, unless an identical
1343/// node already exists, in which case transfer all its users to the existing
1344/// node. This transfer can potentially trigger recursive merging.
1345void
1346SelectionDAG::AddModifiedNodeToCSEMaps(SDNode *N) {
1347 // For node types that aren't CSE'd, just act as if no identical node
1348 // already exists.
1349 if (!doNotCSE(N)) {
1350 SDNode *Existing = CSEMap.getOrInsert(N);
1351 if (Existing != N) {
1352 // If there was already an existing matching node, use ReplaceAllUsesWith
1353 // to replace the dead one with the existing one. This can cause
1354 // recursive merging of other unrelated nodes down the line.
1355 Existing->intersectFlagsWith(N->getFlags());
1356 if (auto *MemNode = dyn_cast<MemSDNode>(Existing)) {
1358 cast<MemSDNode>(N)->memoperands();
1359 // Range and cache hint metadata are not part of the DAG CSE key because
1360 // we prefer to CSE even when metadata does not match. Merge potentially
1361 // differing metadata conservatively.
1362 MemNode->refineMMOMetadata(NewMMOs);
1363 }
1364 ReplaceAllUsesWith(N, Existing);
1365
1366 // N is now dead. Inform the listeners and delete it.
1367 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1368 DUL->NodeDeleted(N, Existing);
1369 DeleteNodeNotInCSEMaps(N);
1370 return;
1371 }
1372 }
1373
1374 // If the node doesn't already exist, we updated it. Inform listeners.
1375 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1376 DUL->NodeUpdated(N);
1377}
1378
1379/// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1380/// were replaced with those specified. If this node is never memoized,
1381/// return null, otherwise return a pointer to the slot it would take. If a
1382/// node already exists with these operands, the slot will be non-null.
1383SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op,
1384 FoldingSetInsertToken &InsertToken) {
1385 if (doNotCSE(N))
1386 return nullptr;
1387
1388 SDValue Ops[] = { Op };
1389 SDNodeKey ID(N->getOpcode(), N->getVTList(), Ops);
1390 AddNodeIDCustom(ID.Tail, N, N->getOpcode());
1391 SDNode *Node = lookupNode(ID, SDLoc(N), InsertToken);
1392 if (Node)
1393 Node->intersectFlagsWith(N->getFlags());
1394 return Node;
1395}
1396
1397/// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1398/// were replaced with those specified. If this node is never memoized,
1399/// return null, otherwise return a pointer to the slot it would take. If a
1400/// node already exists with these operands, the slot will be non-null.
1401SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op1, SDValue Op2,
1402 FoldingSetInsertToken &InsertToken) {
1403 if (doNotCSE(N))
1404 return nullptr;
1405
1406 SDValue Ops[] = { Op1, Op2 };
1407 SDNodeKey ID(N->getOpcode(), N->getVTList(), Ops);
1408 AddNodeIDCustom(ID.Tail, N, N->getOpcode());
1409 SDNode *Node = lookupNode(ID, SDLoc(N), InsertToken);
1410 if (Node)
1411 Node->intersectFlagsWith(N->getFlags());
1412 return Node;
1413}
1414
1415/// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1416/// were replaced with those specified. If this node is never memoized,
1417/// return null, otherwise return a pointer to the slot it would take. If a
1418/// node already exists with these operands, the slot will be non-null.
1419SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, ArrayRef<SDValue> Ops,
1420 FoldingSetInsertToken &InsertToken) {
1421 if (doNotCSE(N))
1422 return nullptr;
1423
1424 SDNodeKey ID(N->getOpcode(), N->getVTList(), Ops);
1425 AddNodeIDCustom(ID.Tail, N, N->getOpcode());
1426 SDNode *Node = lookupNode(ID, SDLoc(N), InsertToken);
1427 if (Node)
1428 Node->intersectFlagsWith(N->getFlags());
1429 return Node;
1430}
1431
1433 Type *Ty = VT == MVT::iPTR ? PointerType::get(*getContext(), 0)
1434 : VT.getTypeForEVT(*getContext());
1435
1436 return getDataLayout().getABITypeAlign(Ty);
1437}
1438
1439// EntryNode could meaningfully have debug info if we can find it...
1441 : TM(tm), OptLevel(OL), EntryNode(ISD::EntryToken, 0, DebugLoc(),
1442 getVTList(MVT::Other, MVT::Glue)),
1443 Root(getEntryNode()) {
1444 InsertNode(&EntryNode);
1445 DbgInfo = new SDDbgInfo();
1446}
1447
1449 const TargetLibraryInfo *LibraryInfo,
1450 const LibcallLoweringInfo *LibcallsInfo,
1451 UniformityInfo *NewUA, ProfileSummaryInfo *PSIin,
1452 BlockFrequencyInfo *BFIin,
1453 FunctionVarLocs const *VarLocs) {
1454 MF = &NewMF;
1457 LibInfo = LibraryInfo;
1458 Libcalls = LibcallsInfo;
1459 Context = &MF->getFunction().getContext();
1460 DAGOpts = &Context->getLibraryOptions().get<SelectionDAGOptions>();
1461 UA = NewUA;
1462 PSI = PSIin;
1463 BFI = BFIin;
1464 FnVarLocs = VarLocs;
1465}
1466
1468 assert(!UpdateListeners && "Dangling registered DAGUpdateListeners");
1469 allnodes_clear();
1470 OperandRecycler.clear(OperandAllocator);
1471 delete DbgInfo;
1472}
1473
1475 return llvm::shouldOptimizeForSize(FLI->MBB->getBasicBlock(), PSI, BFI);
1476}
1477
1479 return FLI->MBB->getBasicBlock();
1480}
1481
1482void SelectionDAG::allnodes_clear() {
1483 assert(&*AllNodes.begin() == &EntryNode);
1484 AllNodes.remove(AllNodes.begin());
1485 while (!AllNodes.empty())
1486 DeallocateNode(&AllNodes.front());
1487#ifndef NDEBUG
1488 NextPersistentId = 0;
1489#endif
1490}
1491
1492SDNode *SelectionDAG::lookupNode(const SDNodeKey &Key,
1493 FoldingSetInsertToken &InsertToken) {
1494 SDNode *N = CSEMap.lookup(Key, InsertToken);
1495 if (N) {
1496 switch (N->getOpcode()) {
1497 default: break;
1498 case ISD::Constant:
1499 case ISD::ConstantFP:
1500 llvm_unreachable("Querying for Constant and ConstantFP nodes requires "
1501 "debug location. Use another overload.");
1502 }
1503 }
1504 return N;
1505}
1506
1507SDNode *SelectionDAG::lookupNode(const SDNodeKey &Key, const SDLoc &DL,
1508 FoldingSetInsertToken &InsertToken) {
1509 SDNode *N = CSEMap.lookup(Key, InsertToken);
1510 if (N) {
1511 switch (N->getOpcode()) {
1512 case ISD::Constant:
1513 case ISD::ConstantFP:
1514 // Erase debug location from the node if the node is used at several
1515 // different places. Do not propagate one location to all uses as it
1516 // will cause a worse single stepping debugging experience.
1517 if (N->getDebugLoc() != DL.getDebugLoc())
1518 N->setDebugLoc(DebugLoc());
1519 break;
1520 default:
1521 // When the node's point of use is located earlier in the instruction
1522 // sequence than its prior point of use, update its debug info to the
1523 // earlier location.
1524 if (DL.getIROrder() && DL.getIROrder() < N->getIROrder())
1525 N->setDebugLoc(DL.getDebugLoc());
1526 break;
1527 }
1528 }
1529 return N;
1530}
1531
1533 allnodes_clear();
1534 OperandRecycler.clear(OperandAllocator);
1535 OperandAllocator.Reset();
1536 CSEMap.clear();
1537
1538 ExtendedValueTypeNodes.clear();
1539 ExternalSymbols.clear();
1540 TargetExternalSymbols.clear();
1541 MCSymbols.clear();
1542 SDEI.clear();
1543 llvm::fill(CondCodeNodes, nullptr);
1544 llvm::fill(ValueTypeNodes, nullptr);
1545
1546 EntryNode.UseList = nullptr;
1547 InsertNode(&EntryNode);
1548 Root = getEntryNode();
1549 DbgInfo->clear();
1550}
1551
1553 return VT.bitsGT(Op.getValueType())
1554 ? getNode(ISD::FP_EXTEND, DL, VT, Op)
1555 : getNode(ISD::FP_ROUND, DL, VT, Op,
1556 getIntPtrConstant(0, DL, /*isTarget=*/true));
1557}
1558
1559std::pair<SDValue, SDValue>
1561 const SDLoc &DL, EVT VT) {
1562 assert(!VT.bitsEq(Op.getValueType()) &&
1563 "Strict no-op FP extend/round not allowed.");
1564 SDValue Res =
1565 VT.bitsGT(Op.getValueType())
1566 ? getNode(ISD::STRICT_FP_EXTEND, DL, {VT, MVT::Other}, {Chain, Op})
1567 : getNode(ISD::STRICT_FP_ROUND, DL, {VT, MVT::Other},
1568 {Chain, Op, getIntPtrConstant(0, DL, /*isTarget=*/true)});
1569
1570 return std::pair<SDValue, SDValue>(Res, SDValue(Res.getNode(), 1));
1571}
1572
1574 return VT.bitsGT(Op.getValueType()) ?
1575 getNode(ISD::ANY_EXTEND, DL, VT, Op) :
1576 getNode(ISD::TRUNCATE, DL, VT, Op);
1577}
1578
1580 return VT.bitsGT(Op.getValueType()) ?
1581 getNode(ISD::SIGN_EXTEND, DL, VT, Op) :
1582 getNode(ISD::TRUNCATE, DL, VT, Op);
1583}
1584
1586 return VT.bitsGT(Op.getValueType()) ?
1587 getNode(ISD::ZERO_EXTEND, DL, VT, Op) :
1588 getNode(ISD::TRUNCATE, DL, VT, Op);
1589}
1590
1592 EVT VT) {
1593 assert(!VT.isVector());
1594 auto Type = Op.getValueType();
1595 SDValue DestOp;
1596 if (Type == VT)
1597 return Op;
1598 auto Size = Op.getValueSizeInBits();
1599 DestOp = getBitcast(EVT::getIntegerVT(*Context, Size), Op);
1600 if (DestOp.getValueType() == VT)
1601 return DestOp;
1602
1603 return getAnyExtOrTrunc(DestOp, DL, VT);
1604}
1605
1607 EVT OpVT) {
1608 if (VT.bitsLE(Op.getValueType()))
1609 return getNode(ISD::TRUNCATE, SL, VT, Op);
1610
1611 TargetLowering::BooleanContent BType = TLI->getBooleanContents(OpVT);
1612 return getNode(TLI->getExtendForContent(BType), SL, VT, Op);
1613}
1614
1616 EVT OpVT = Op.getValueType();
1617 assert(VT.isInteger() && OpVT.isInteger() &&
1618 "Cannot getZeroExtendInReg FP types");
1619 assert(VT.isVector() == OpVT.isVector() &&
1620 "getZeroExtendInReg type should be vector iff the operand "
1621 "type is vector!");
1622 assert((!VT.isVector() ||
1624 "Vector element counts must match in getZeroExtendInReg");
1625 assert(VT.getScalarType().bitsLE(OpVT.getScalarType()) && "Not extending!");
1626 if (OpVT == VT)
1627 return Op;
1628 // TODO: Use computeKnownBits instead of AssertZext.
1629 if (Op.getOpcode() == ISD::AssertZext && cast<VTSDNode>(Op.getOperand(1))
1630 ->getVT()
1631 .getScalarType()
1632 .bitsLE(VT.getScalarType()))
1633 return Op;
1635 VT.getScalarSizeInBits());
1636 return getNode(ISD::AND, DL, OpVT, Op, getConstant(Imm, DL, OpVT));
1637}
1638
1640 // Only unsigned pointer semantics are supported right now. In the future this
1641 // might delegate to TLI to check pointer signedness.
1642 return getZExtOrTrunc(Op, DL, VT);
1643}
1644
1646 // Only unsigned pointer semantics are supported right now. In the future this
1647 // might delegate to TLI to check pointer signedness.
1648 return getZeroExtendInReg(Op, DL, VT);
1649}
1650
1652 return getNode(ISD::SUB, DL, VT, getConstant(0, DL, VT), Val);
1653}
1654
1655/// getNOT - Create a bitwise NOT operation as (XOR Val, -1).
1657 return getNode(ISD::XOR, DL, VT, Val, getAllOnesConstant(DL, VT));
1658}
1659
1661 SDValue TrueValue = getBoolConstant(true, DL, VT, VT);
1662 return getNode(ISD::XOR, DL, VT, Val, TrueValue);
1663}
1664
1666 EVT OpVT) {
1667 if (!V)
1668 return getConstant(0, DL, VT);
1669
1670 switch (TLI->getBooleanContents(OpVT)) {
1673 return getConstant(1, DL, VT);
1675 return getAllOnesConstant(DL, VT);
1676 }
1677 llvm_unreachable("Unexpected boolean content enum!");
1678}
1679
1681 bool isT, bool isO) {
1682 return getConstant(APInt(VT.getScalarSizeInBits(), Val, /*isSigned=*/false),
1683 DL, VT, isT, isO);
1684}
1685
1687 bool isT, bool isO) {
1688 return getConstant(*ConstantInt::get(*Context, Val), DL, VT, isT, isO);
1689}
1690
1692 EVT VT, bool isT, bool isO) {
1693 assert(VT.isInteger() && "Cannot create FP integer constant!");
1694
1695 EVT EltVT = VT.getScalarType();
1696 const ConstantInt *Elt = &Val;
1697
1698 // Vector splats are explicit within the DAG, with ConstantSDNode holding the
1699 // to-be-splatted scalar ConstantInt.
1700 if (isa<VectorType>(Elt->getType()))
1701 Elt = ConstantInt::get(*getContext(), Elt->getValue());
1702
1703 // In some cases the vector type is legal but the element type is illegal and
1704 // needs to be promoted, for example v8i8 on ARM. In this case, promote the
1705 // inserted value (the type does not need to match the vector element type).
1706 // Any extra bits introduced will be truncated away.
1707 if (VT.isVector() && TLI->getTypeAction(*getContext(), EltVT) ==
1709 EltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1710 APInt NewVal;
1711 if (TLI->isSExtCheaperThanZExt(VT.getScalarType(), EltVT))
1712 NewVal = Elt->getValue().sextOrTrunc(EltVT.getSizeInBits());
1713 else
1714 NewVal = Elt->getValue().zextOrTrunc(EltVT.getSizeInBits());
1715 Elt = ConstantInt::get(*getContext(), NewVal);
1716 }
1717 // In other cases the element type is illegal and needs to be expanded, for
1718 // example v2i64 on MIPS32. In this case, find the nearest legal type, split
1719 // the value into n parts and use a vector type with n-times the elements.
1720 // Then bitcast to the type requested.
1721 // Legalizing constants too early makes the DAGCombiner's job harder so we
1722 // only legalize if the DAG tells us we must produce legal types.
1723 else if (NewNodesMustHaveLegalTypes && VT.isVector() &&
1724 TLI->getTypeAction(*getContext(), EltVT) ==
1726 const APInt &NewVal = Elt->getValue();
1727 EVT ViaEltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1728 unsigned ViaEltSizeInBits = ViaEltVT.getSizeInBits();
1729
1730 // For scalable vectors, try to use a SPLAT_VECTOR_PARTS node.
1731 if (VT.isScalableVector() ||
1732 TLI->isOperationLegal(ISD::SPLAT_VECTOR, VT)) {
1733 assert(EltVT.getSizeInBits() % ViaEltSizeInBits == 0 &&
1734 "Can only handle an even split!");
1735 unsigned Parts = EltVT.getSizeInBits() / ViaEltSizeInBits;
1736
1737 SmallVector<SDValue, 2> ScalarParts;
1738 for (unsigned i = 0; i != Parts; ++i)
1739 ScalarParts.push_back(getConstant(
1740 NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL,
1741 ViaEltVT, isT, isO));
1742
1743 return getNode(ISD::SPLAT_VECTOR_PARTS, DL, VT, ScalarParts);
1744 }
1745
1746 unsigned ViaVecNumElts = VT.getSizeInBits() / ViaEltSizeInBits;
1747 EVT ViaVecVT = EVT::getVectorVT(*getContext(), ViaEltVT, ViaVecNumElts);
1748
1749 // Check the temporary vector is the correct size. If this fails then
1750 // getTypeToTransformTo() probably returned a type whose size (in bits)
1751 // isn't a power-of-2 factor of the requested type size.
1752 assert(ViaVecVT.getSizeInBits() == VT.getSizeInBits());
1753
1754 SmallVector<SDValue, 2> EltParts;
1755 for (unsigned i = 0; i < ViaVecNumElts / VT.getVectorNumElements(); ++i)
1756 EltParts.push_back(getConstant(
1757 NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL,
1758 ViaEltVT, isT, isO));
1759
1760 // EltParts is currently in little endian order. If we actually want
1761 // big-endian order then reverse it now.
1762 if (getDataLayout().isBigEndian())
1763 std::reverse(EltParts.begin(), EltParts.end());
1764
1765 // The elements must be reversed when the element order is different
1766 // to the endianness of the elements (because the BITCAST is itself a
1767 // vector shuffle in this situation). However, we do not need any code to
1768 // perform this reversal because getConstant() is producing a vector
1769 // splat.
1770 // This situation occurs in MIPS MSA.
1771
1773 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
1774 llvm::append_range(Ops, EltParts);
1775
1776 SDValue V =
1777 getNode(ISD::BITCAST, DL, VT, getBuildVector(ViaVecVT, DL, Ops));
1778 return V;
1779 }
1780
1781 assert(Elt->getBitWidth() == EltVT.getSizeInBits() &&
1782 "APInt size does not match type size!");
1783 unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
1784 SDVTList VTs = getVTList(EltVT);
1785 SDNodeKey ID(Opc, VTs, {});
1786 ID.AddPointer(Elt);
1787 ID.AddBoolean(isO);
1788 FoldingSetInsertToken InsertToken;
1789 SDNode *N = nullptr;
1790 if ((N = lookupNode(ID, DL, InsertToken)))
1791 if (!VT.isVector())
1792 return SDValue(N, 0);
1793
1794 if (!N) {
1795 N = newSDNode<ConstantSDNode>(isT, isO, Elt, VTs);
1796 if (!isT)
1797 N->setDebugLoc(DL.getDebugLoc());
1798 CSEMap.insert(N, InsertToken);
1799 InsertNode(N);
1800 NewSDValueDbgMsg(SDValue(N, 0), "Creating constant: ", this);
1801 }
1802
1803 SDValue Result(N, 0);
1804 if (VT.isVector())
1805 Result = getSplat(VT, DL, Result);
1806 return Result;
1807}
1808
1810 bool isT, bool isO) {
1811 unsigned Size = VT.getScalarSizeInBits();
1812 return getConstant(APInt(Size, Val, /*isSigned=*/true), DL, VT, isT, isO);
1813}
1814
1816 bool IsOpaque) {
1818 IsTarget, IsOpaque);
1819}
1820
1822 bool isTarget) {
1823 return getConstant(Val, DL, TLI->getPointerTy(getDataLayout()), isTarget);
1824}
1825
1827 const SDLoc &DL) {
1828 assert(VT.isInteger() && "Shift amount is not an integer type!");
1829 EVT ShiftVT = TLI->getShiftAmountTy(VT, getDataLayout());
1830 return getConstant(Val, DL, ShiftVT);
1831}
1832
1834 const SDLoc &DL) {
1835 assert(Val.ult(VT.getScalarSizeInBits()) && "Out of range shift");
1836 return getShiftAmountConstant(Val.getZExtValue(), VT, DL);
1837}
1838
1840 bool isTarget) {
1841 return getConstant(Val, DL, TLI->getVectorIdxTy(getDataLayout()), isTarget);
1842}
1843
1845 bool isTarget) {
1846 return getConstantFP(*ConstantFP::get(*getContext(), V), DL, VT, isTarget);
1847}
1848
1849SDValue SelectionDAG::getConstFP(std::optional<FPFoldResult> Result,
1850 const SDLoc &DL, EVT VT, bool isTarget) {
1851 return Result ? getConstantFP(Result->Value, DL, VT, isTarget) : SDValue();
1852}
1853
1855 EVT VT, bool isTarget) {
1856 assert(VT.isFloatingPoint() && "Cannot create integer FP constant!");
1857
1858 EVT EltVT = VT.getScalarType();
1859 const ConstantFP *Elt = &V;
1860
1861 // Vector splats are explicit within the DAG, with ConstantFPSDNode holding
1862 // the to-be-splatted scalar ConstantFP.
1863 if (isa<VectorType>(Elt->getType()))
1864 Elt = ConstantFP::get(*getContext(), Elt->getValue());
1865
1866 // Do the map lookup using the actual bit pattern for the floating point
1867 // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
1868 // we don't have issues with SNANs.
1869 unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
1870 SDVTList VTs = getVTList(EltVT);
1871 SDNodeKey ID(Opc, VTs, {});
1872 ID.AddPointer(Elt);
1873 FoldingSetInsertToken InsertToken;
1874 SDNode *N = nullptr;
1875 if ((N = lookupNode(ID, DL, InsertToken)))
1876 if (!VT.isVector())
1877 return SDValue(N, 0);
1878
1879 if (!N) {
1880 N = newSDNode<ConstantFPSDNode>(isTarget, Elt, VTs);
1881 CSEMap.insert(N, InsertToken);
1882 InsertNode(N);
1883 }
1884
1885 SDValue Result(N, 0);
1886 if (VT.isVector())
1887 Result = getSplat(VT, DL, Result);
1888 NewSDValueDbgMsg(Result, "Creating fp constant: ", this);
1889 return Result;
1890}
1891
1893 bool isTarget) {
1894 EVT EltVT = VT.getScalarType();
1895 if (EltVT == MVT::f32)
1896 return getConstantFP(APFloat((float)Val), DL, VT, isTarget);
1897 if (EltVT == MVT::f64)
1898 return getConstantFP(APFloat(Val), DL, VT, isTarget);
1899 if (EltVT == MVT::f80 || EltVT == MVT::f128 || EltVT == MVT::ppcf128 ||
1900 EltVT == MVT::f16 || EltVT == MVT::bf16) {
1901 bool Ignored;
1902 APFloat APF = APFloat(Val);
1904 &Ignored);
1905 return getConstantFP(APF, DL, VT, isTarget);
1906 }
1907 llvm_unreachable("Unsupported type in getConstantFP");
1908}
1909
1911 EVT VT, int64_t Offset, bool isTargetGA,
1912 unsigned TargetFlags) {
1913 assert((TargetFlags == 0 || isTargetGA) &&
1914 "Cannot set target flags on target-independent globals");
1915
1916 // Truncate (with sign-extension) the offset value to the pointer size.
1918 if (BitWidth < 64)
1920
1921 unsigned Opc;
1922 if (GV->isThreadLocal())
1924 else
1926
1927 SDVTList VTs = getVTList(VT);
1928 SDNodeKey ID(Opc, VTs, {});
1929 ID.AddPointer(GV);
1930 ID.AddInteger(Offset);
1931 ID.AddInteger(TargetFlags);
1932 FoldingSetInsertToken InsertToken;
1933 if (SDNode *E = lookupNode(ID, DL, InsertToken))
1934 return SDValue(E, 0);
1935
1936 auto *N = newSDNode<GlobalAddressSDNode>(
1937 Opc, DL.getIROrder(), DL.getDebugLoc(), GV, VTs, Offset, TargetFlags);
1938 CSEMap.insert(N, InsertToken);
1939 InsertNode(N);
1940 return SDValue(N, 0);
1941}
1942
1944 SDVTList VTs = getVTList(MVT::Untyped);
1946 ID.AddPointer(GV);
1947 FoldingSetInsertToken InsertToken;
1948 if (SDNode *E = lookupNode(ID, SDLoc(), InsertToken))
1949 return SDValue(E, 0);
1950
1951 auto *N = newSDNode<DeactivationSymbolSDNode>(GV, VTs);
1952 CSEMap.insert(N, InsertToken);
1953 InsertNode(N);
1954 return SDValue(N, 0);
1955}
1956
1957SDValue SelectionDAG::getFrameIndex(int FI, EVT VT, bool isTarget) {
1958 unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
1959 SDVTList VTs = getVTList(VT);
1960 SDNodeKey ID(Opc, VTs, {});
1961 ID.AddInteger(FI);
1962 FoldingSetInsertToken InsertToken;
1963 if (SDNode *E = lookupNode(ID, InsertToken))
1964 return SDValue(E, 0);
1965
1966 auto *N = newSDNode<FrameIndexSDNode>(FI, VTs, isTarget);
1967 CSEMap.insert(N, InsertToken);
1968 InsertNode(N);
1969 return SDValue(N, 0);
1970}
1971
1972SDValue SelectionDAG::getJumpTable(int JTI, EVT VT, bool isTarget,
1973 unsigned TargetFlags) {
1974 assert((TargetFlags == 0 || isTarget) &&
1975 "Cannot set target flags on target-independent jump tables");
1976 unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
1977 SDVTList VTs = getVTList(VT);
1978 SDNodeKey ID(Opc, VTs, {});
1979 ID.AddInteger(JTI);
1980 ID.AddInteger(TargetFlags);
1981 FoldingSetInsertToken InsertToken;
1982 if (SDNode *E = lookupNode(ID, InsertToken))
1983 return SDValue(E, 0);
1984
1985 auto *N = newSDNode<JumpTableSDNode>(JTI, VTs, isTarget, TargetFlags);
1986 CSEMap.insert(N, InsertToken);
1987 InsertNode(N);
1988 return SDValue(N, 0);
1989}
1990
1992 const SDLoc &DL) {
1994 return getNode(ISD::JUMP_TABLE_DEBUG_INFO, DL, MVT::Other, Chain,
1995 getTargetConstant(static_cast<uint64_t>(JTI), DL, PTy, true));
1996}
1997
1999 MaybeAlign Alignment, int Offset,
2000 bool isTarget, unsigned TargetFlags) {
2001 assert((TargetFlags == 0 || isTarget) &&
2002 "Cannot set target flags on target-independent globals");
2003 if (!Alignment)
2004 Alignment = shouldOptForSize()
2005 ? getDataLayout().getABITypeAlign(C->getType())
2006 : getDataLayout().getPrefTypeAlign(C->getType());
2007 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
2008 SDVTList VTs = getVTList(VT);
2009 SDNodeKey ID(Opc, VTs, {});
2010 ID.AddInteger(Alignment->value());
2011 ID.AddInteger(Offset);
2012 ID.AddPointer(C);
2013 ID.AddInteger(TargetFlags);
2014 FoldingSetInsertToken InsertToken;
2015 if (SDNode *E = lookupNode(ID, InsertToken))
2016 return SDValue(E, 0);
2017
2018 auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VTs, Offset, *Alignment,
2019 TargetFlags);
2020 CSEMap.insert(N, InsertToken);
2021 InsertNode(N);
2022 SDValue V = SDValue(N, 0);
2023 NewSDValueDbgMsg(V, "Creating new constant pool: ", this);
2024 return V;
2025}
2026
2028 MaybeAlign Alignment, int Offset,
2029 bool isTarget, unsigned TargetFlags) {
2030 assert((TargetFlags == 0 || isTarget) &&
2031 "Cannot set target flags on target-independent globals");
2032 if (!Alignment)
2033 Alignment = getDataLayout().getPrefTypeAlign(C->getType());
2034 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
2035 SDVTList VTs = getVTList(VT);
2036 SDNodeKey ID(Opc, VTs, {});
2037 ID.AddInteger(Alignment->value());
2038 ID.AddInteger(Offset);
2039 C->addSelectionDAGCSEId(ID.Tail);
2040 ID.AddInteger(TargetFlags);
2041 FoldingSetInsertToken InsertToken;
2042 if (SDNode *E = lookupNode(ID, InsertToken))
2043 return SDValue(E, 0);
2044
2045 auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VTs, Offset, *Alignment,
2046 TargetFlags);
2047 CSEMap.insert(N, InsertToken);
2048 InsertNode(N);
2049 return SDValue(N, 0);
2050}
2051
2053 SDNodeKey ID(ISD::BasicBlock, getVTList(MVT::Other), {});
2054 ID.AddPointer(MBB);
2055 FoldingSetInsertToken InsertToken;
2056 if (SDNode *E = lookupNode(ID, InsertToken))
2057 return SDValue(E, 0);
2058
2059 auto *N = newSDNode<BasicBlockSDNode>(MBB);
2060 CSEMap.insert(N, InsertToken);
2061 InsertNode(N);
2062 return SDValue(N, 0);
2063}
2064
2066 if (VT.isSimple() && (unsigned)VT.getSimpleVT().SimpleTy >=
2067 ValueTypeNodes.size())
2068 ValueTypeNodes.resize(VT.getSimpleVT().SimpleTy+1);
2069
2070 SDNode *&N = VT.isExtended() ?
2071 ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT().SimpleTy];
2072
2073 if (N) return SDValue(N, 0);
2074 N = newSDNode<VTSDNode>(VT);
2075 InsertNode(N);
2076 return SDValue(N, 0);
2077}
2078
2080 SDNode *&N = ExternalSymbols[Sym];
2081 if (N) return SDValue(N, 0);
2082 N = newSDNode<ExternalSymbolSDNode>(false, Sym, 0, getVTList(VT));
2083 InsertNode(N);
2084 return SDValue(N, 0);
2085}
2086
2087SDValue SelectionDAG::getExternalSymbol(RTLIB::LibcallImpl Libcall, EVT VT) {
2089 return getExternalSymbol(SymName.data(), VT);
2090}
2091
2093 SDNode *&N = MCSymbols[Sym];
2094 if (N)
2095 return SDValue(N, 0);
2096 N = newSDNode<MCSymbolSDNode>(Sym, getVTList(VT));
2097 InsertNode(N);
2098 return SDValue(N, 0);
2099}
2100
2102 unsigned TargetFlags) {
2103 SDNode *&N =
2104 TargetExternalSymbols[std::pair<std::string, unsigned>(Sym, TargetFlags)];
2105 if (N) return SDValue(N, 0);
2106 N = newSDNode<ExternalSymbolSDNode>(true, Sym, TargetFlags, getVTList(VT));
2107 InsertNode(N);
2108 return SDValue(N, 0);
2109}
2110
2112 EVT VT, unsigned TargetFlags) {
2114 return getTargetExternalSymbol(SymName.data(), VT, TargetFlags);
2115}
2116
2118 if ((unsigned)Cond >= CondCodeNodes.size())
2119 CondCodeNodes.resize(Cond+1);
2120
2121 if (!CondCodeNodes[Cond]) {
2122 auto *N = newSDNode<CondCodeSDNode>(Cond);
2123 CondCodeNodes[Cond] = N;
2124 InsertNode(N);
2125 }
2126
2127 return SDValue(CondCodeNodes[Cond], 0);
2128}
2129
2131 assert(MulImm.getBitWidth() == VT.getSizeInBits() &&
2132 "APInt size does not match type size!");
2133
2134 if (MulImm == 0)
2135 return getConstant(0, DL, VT);
2136
2137 const MachineFunction &MF = getMachineFunction();
2138 const Function &F = MF.getFunction();
2139 ConstantRange CR = getVScaleRange(&F, 64);
2140 if (const APInt *C = CR.getSingleElement())
2141 return getConstant(MulImm * C->getZExtValue(), DL, VT);
2142
2143 return getNode(ISD::VSCALE, DL, VT, getConstant(MulImm, DL, VT));
2144}
2145
2146/// \returns a value of type \p VT that represents the runtime value of \p
2147/// Quantity, i.e. scaled by vscale if it's scalable, or a fixed constant
2148/// otherwise. Quantity should be a FixedOrScalableQuantity, i.e. ElementCount
2149/// or TypeSize.
2150template <typename Ty>
2152 EVT VT, Ty Quantity) {
2153 if (Quantity.isScalable())
2154 return DAG.getVScale(
2155 DL, VT, APInt(VT.getSizeInBits(), Quantity.getKnownMinValue()));
2156
2157 return DAG.getConstant(Quantity.getKnownMinValue(), DL, VT);
2158}
2159
2161 ElementCount EC) {
2162 return getFixedOrScalableQuantity(*this, DL, VT, EC);
2163}
2164
2166 return getFixedOrScalableQuantity(*this, DL, VT, TS);
2167}
2168
2170 ElementCount EC) {
2171 EVT IdxVT = TLI->getVectorIdxTy(getDataLayout());
2172 EVT MaskVT = TLI->getSetCCResultType(getDataLayout(), *getContext(), DataVT);
2173 return getNode(ISD::GET_ACTIVE_LANE_MASK, DL, MaskVT,
2174 getConstant(0, DL, IdxVT), getElementCount(DL, IdxVT, EC));
2175}
2176
2178 APInt One(ResVT.getScalarSizeInBits(), 1);
2179 return getStepVector(DL, ResVT, One);
2180}
2181
2183 const APInt &StepVal) {
2184 assert(ResVT.getScalarSizeInBits() == StepVal.getBitWidth());
2185 if (ResVT.isScalableVector())
2186 return getNode(
2187 ISD::STEP_VECTOR, DL, ResVT,
2188 getTargetConstant(StepVal, DL, ResVT.getVectorElementType()));
2189
2190 SmallVector<SDValue, 16> OpsStepConstants;
2191 for (uint64_t i = 0; i < ResVT.getVectorNumElements(); i++)
2192 OpsStepConstants.push_back(
2193 getConstant(StepVal * i, DL, ResVT.getVectorElementType()));
2194 return getBuildVector(ResVT, DL, OpsStepConstants);
2195}
2196
2197/// Swaps the values of N1 and N2. Swaps all indices in the shuffle mask M that
2198/// point at N1 to point at N2 and indices that point at N2 to point at N1.
2203
2205 SDValue N2, ArrayRef<int> Mask) {
2206 assert(VT.getVectorNumElements() == Mask.size() &&
2207 "Must have the same number of vector elements as mask elements!");
2208 assert(VT == N1.getValueType() && VT == N2.getValueType() &&
2209 "Invalid VECTOR_SHUFFLE");
2210
2211 // Canonicalize shuffle undef, undef -> undef
2212 if (N1.isUndef() && N2.isUndef()) {
2213 if (N1.getOpcode() == ISD::POISON && N2.getOpcode() == ISD::POISON)
2214 return getPOISON(VT);
2215 return getUNDEF(VT);
2216 }
2217
2218 // Validate that all indices in Mask are within the range of the elements
2219 // input to the shuffle.
2220 int NElts = Mask.size();
2221 assert(llvm::all_of(Mask,
2222 [&](int M) { return M < (NElts * 2) && M >= -1; }) &&
2223 "Index out of range");
2224
2225 // Copy the mask so we can do any needed cleanup.
2226 SmallVector<int, 8> MaskVec(Mask);
2227
2228 // Canonicalize shuffle v, v -> v, poison
2229 if (N1 == N2) {
2230 N2 = getPOISON(VT);
2231 for (int i = 0; i != NElts; ++i)
2232 if (MaskVec[i] >= NElts) MaskVec[i] -= NElts;
2233 }
2234
2235 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
2236 if (N1.isUndef())
2237 commuteShuffle(N1, N2, MaskVec);
2238
2239 if (TLI->hasVectorBlend()) {
2240 // If shuffling a splat, try to blend the splat instead. We do this here so
2241 // that even when this arises during lowering we don't have to re-handle it.
2242 auto BlendSplat = [&](BuildVectorSDNode *BV, int Offset) {
2243 BitVector UndefElements;
2244 SDValue Splat = BV->getSplatValue(&UndefElements);
2245 if (!Splat)
2246 return;
2247
2248 for (int i = 0; i < NElts; ++i) {
2249 if (MaskVec[i] < Offset || MaskVec[i] >= (Offset + NElts))
2250 continue;
2251
2252 // If this input comes from undef, mark it as such.
2253 if (UndefElements[MaskVec[i] - Offset]) {
2254 MaskVec[i] = -1;
2255 continue;
2256 }
2257
2258 // If we can blend a non-undef lane, use that instead.
2259 if (!UndefElements[i])
2260 MaskVec[i] = i + Offset;
2261 }
2262 };
2263 if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
2264 BlendSplat(N1BV, 0);
2265 if (auto *N2BV = dyn_cast<BuildVectorSDNode>(N2))
2266 BlendSplat(N2BV, NElts);
2267 }
2268
2269 // Canonicalize all index into lhs, -> shuffle lhs, poison
2270 // Canonicalize all index into rhs, -> shuffle rhs, poison
2271 bool AllLHS = true, AllRHS = true;
2272 bool N2Undef = N2.isUndef();
2273 for (int i = 0; i != NElts; ++i) {
2274 if (MaskVec[i] >= NElts) {
2275 if (N2Undef)
2276 MaskVec[i] = -1;
2277 else
2278 AllLHS = false;
2279 } else if (MaskVec[i] >= 0) {
2280 AllRHS = false;
2281 }
2282 }
2283 if (AllLHS && AllRHS)
2284 return getPOISON(VT);
2285 if (AllLHS && !N2Undef)
2286 N2 = getPOISON(VT);
2287 if (AllRHS) {
2288 N1 = getPOISON(VT);
2289 commuteShuffle(N1, N2, MaskVec);
2290 }
2291 // Reset our undef status after accounting for the mask.
2292 N2Undef = N2.isUndef();
2293 // Re-check whether both sides ended up undef.
2294 if (N1.isUndef() && N2Undef) {
2295 if (N1.getOpcode() == ISD::POISON && N2.getOpcode() == ISD::POISON)
2296 return getPOISON(VT);
2297 return getUNDEF(VT);
2298 }
2299
2300 // If Identity shuffle return that node.
2301 bool Identity = true, AllSame = true;
2302 for (int i = 0; i != NElts; ++i) {
2303 if (MaskVec[i] >= 0 && MaskVec[i] != i) Identity = false;
2304 if (MaskVec[i] != MaskVec[0]) AllSame = false;
2305 }
2306 if (Identity && NElts)
2307 return N1;
2308
2309 // Shuffling a constant splat doesn't change the result.
2310 if (N2Undef) {
2311 SDValue V = N1;
2312
2313 // Look through any bitcasts. We check that these don't change the number
2314 // (and size) of elements and just changes their types.
2315 while (V.getOpcode() == ISD::BITCAST)
2316 V = V->getOperand(0);
2317
2318 // A splat should always show up as a build vector node.
2319 if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) {
2320 BitVector UndefElements;
2321 SDValue Splat = BV->getSplatValue(&UndefElements);
2322 // If this is a splat of an undef, shuffling it is also undef.
2323 if (Splat && Splat.isUndef())
2324 return Splat.getOpcode() == ISD::POISON ? getPOISON(VT) : getUNDEF(VT);
2325
2326 bool SameNumElts =
2327 V.getValueType().getVectorNumElements() == VT.getVectorNumElements();
2328
2329 // We only have a splat which can skip shuffles if there is a splatted
2330 // value and no undef lanes rearranged by the shuffle.
2331 if (Splat && UndefElements.none()) {
2332 // Splat of <x, x, ..., x>, return <x, x, ..., x>, provided that the
2333 // number of elements match or the value splatted is a zero constant.
2334 if (SameNumElts || isNullConstant(Splat))
2335 return N1;
2336 }
2337
2338 // If the shuffle itself creates a splat, build the vector directly.
2339 if (AllSame && SameNumElts) {
2340 EVT BuildVT = BV->getValueType(0);
2341 const SDValue &Splatted = BV->getOperand(MaskVec[0]);
2342 SDValue NewBV = getSplatBuildVector(BuildVT, dl, Splatted);
2343
2344 // We may have jumped through bitcasts, so the type of the
2345 // BUILD_VECTOR may not match the type of the shuffle.
2346 if (BuildVT != VT)
2347 NewBV = getNode(ISD::BITCAST, dl, VT, NewBV);
2348 return NewBV;
2349 }
2350 }
2351 }
2352
2353 SDVTList VTs = getVTList(VT);
2354 SDValue Ops[2] = { N1, N2 };
2356 for (int i = 0; i != NElts; ++i)
2357 ID.AddInteger(MaskVec[i]);
2358
2359 FoldingSetInsertToken InsertToken;
2360 if (SDNode *E = lookupNode(ID, dl, InsertToken))
2361 return SDValue(E, 0);
2362
2363 // Allocate the mask array for the node out of the BumpPtrAllocator, since
2364 // SDNode doesn't have access to it. This memory will be "leaked" when
2365 // the node is deallocated, but recovered when the NodeAllocator is released.
2366 int *MaskAlloc = OperandAllocator.Allocate<int>(NElts);
2367 llvm::copy(MaskVec, MaskAlloc);
2368
2369 auto *N = newSDNode<ShuffleVectorSDNode>(VTs, dl.getIROrder(),
2370 dl.getDebugLoc(), MaskAlloc);
2371 createOperands(N, Ops);
2372
2373 CSEMap.insert(N, InsertToken);
2374 InsertNode(N);
2375 SDValue V = SDValue(N, 0);
2376 NewSDValueDbgMsg(V, "Creating new node: ", this);
2377 return V;
2378}
2379
2381 EVT VT = SV.getValueType(0);
2382 SmallVector<int, 8> MaskVec(SV.getMask());
2384
2385 SDValue Op0 = SV.getOperand(0);
2386 SDValue Op1 = SV.getOperand(1);
2387 return getVectorShuffle(VT, SDLoc(&SV), Op1, Op0, MaskVec);
2388}
2389
2391 SDVTList VTs = getVTList(VT);
2392 SDNodeKey ID(ISD::Register, VTs, {});
2393 ID.AddInteger(Reg.id());
2394 FoldingSetInsertToken InsertToken;
2395 if (SDNode *E = lookupNode(ID, InsertToken))
2396 return SDValue(E, 0);
2397
2398 auto *N = newSDNode<RegisterSDNode>(Reg, VTs);
2399 N->SDNodeBits.IsDivergent = TLI->isSDNodeSourceOfDivergence(N, FLI, UA);
2400 CSEMap.insert(N, InsertToken);
2401 InsertNode(N);
2402 return SDValue(N, 0);
2403}
2404
2406 SDNodeKey ID(ISD::RegisterMask, getVTList(MVT::Untyped), {});
2407 ID.AddPointer(RegMask);
2408 FoldingSetInsertToken InsertToken;
2409 if (SDNode *E = lookupNode(ID, InsertToken))
2410 return SDValue(E, 0);
2411
2412 auto *N = newSDNode<RegisterMaskSDNode>(RegMask);
2413 CSEMap.insert(N, InsertToken);
2414 InsertNode(N);
2415 return SDValue(N, 0);
2416}
2417
2419 MCSymbol *Label) {
2420 return getLabelNode(ISD::EH_LABEL, dl, Root, Label);
2421}
2422
2423SDValue SelectionDAG::getLabelNode(unsigned Opcode, const SDLoc &dl,
2424 SDValue Root, MCSymbol *Label) {
2425 SDValue Ops[] = { Root };
2426 SDNodeKey ID(Opcode, getVTList(MVT::Other), Ops);
2427 ID.AddPointer(Label);
2428 FoldingSetInsertToken InsertToken;
2429 if (SDNode *E = lookupNode(ID, InsertToken))
2430 return SDValue(E, 0);
2431
2432 auto *N =
2433 newSDNode<LabelSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), Label);
2434 createOperands(N, Ops);
2435
2436 CSEMap.insert(N, InsertToken);
2437 InsertNode(N);
2438 return SDValue(N, 0);
2439}
2440
2442 int64_t Offset, bool isTarget,
2443 unsigned TargetFlags) {
2444 unsigned Opc = isTarget ? ISD::TargetBlockAddress : ISD::BlockAddress;
2445 SDVTList VTs = getVTList(VT);
2446
2447 SDNodeKey ID(Opc, VTs, {});
2448 ID.AddPointer(BA);
2449 ID.AddInteger(Offset);
2450 ID.AddInteger(TargetFlags);
2451 FoldingSetInsertToken InsertToken;
2452 if (SDNode *E = lookupNode(ID, InsertToken))
2453 return SDValue(E, 0);
2454
2455 auto *N = newSDNode<BlockAddressSDNode>(Opc, VTs, BA, Offset, TargetFlags);
2456 CSEMap.insert(N, InsertToken);
2457 InsertNode(N);
2458 return SDValue(N, 0);
2459}
2460
2462 SDNodeKey ID(ISD::SRCVALUE, getVTList(MVT::Other), {});
2463 ID.AddPointer(V);
2464
2465 FoldingSetInsertToken InsertToken;
2466 if (SDNode *E = lookupNode(ID, InsertToken))
2467 return SDValue(E, 0);
2468
2469 auto *N = newSDNode<SrcValueSDNode>(V);
2470 CSEMap.insert(N, InsertToken);
2471 InsertNode(N);
2472 return SDValue(N, 0);
2473}
2474
2476 SDNodeKey ID(ISD::MDNODE_SDNODE, getVTList(MVT::Other), {});
2477 ID.AddPointer(MD);
2478
2479 FoldingSetInsertToken InsertToken;
2480 if (SDNode *E = lookupNode(ID, InsertToken))
2481 return SDValue(E, 0);
2482
2483 auto *N = newSDNode<MDNodeSDNode>(MD);
2484 CSEMap.insert(N, InsertToken);
2485 InsertNode(N);
2486 return SDValue(N, 0);
2487}
2488
2490 if (VT == V.getValueType())
2491 return V;
2492
2493 return getNode(ISD::BITCAST, SDLoc(V), VT, V);
2494}
2495
2497 unsigned SrcAS, unsigned DestAS,
2498 const SDNodeFlags Flags) {
2499 SDVTList VTs = getVTList(VT);
2500 SDValue Ops[] = {Ptr};
2502 ID.AddInteger(SrcAS);
2503 ID.AddInteger(DestAS);
2504
2505 FoldingSetInsertToken InsertToken;
2506 if (SDNode *E = lookupNode(ID, dl, InsertToken)) {
2507 E->intersectFlagsWith(Flags);
2508 return SDValue(E, 0);
2509 }
2510
2511 auto *N = newSDNode<AddrSpaceCastSDNode>(dl.getIROrder(), dl.getDebugLoc(),
2512 VTs, SrcAS, DestAS);
2513 N->setFlags(Flags);
2514 createOperands(N, Ops);
2515
2516 CSEMap.insert(N, InsertToken);
2517 InsertNode(N);
2518 return SDValue(N, 0);
2519}
2520
2522 // TODO: Remove isGuaranteedNotToBeUndefOrPoison handling from getNode().
2524 return getNode(ISD::FREEZE, SDLoc(V), V.getValueType(), V);
2525 APInt DemandedElts = getDemandAllEltsMask(V);
2526 return getFreeze(V, DemandedElts, Kind);
2527}
2528
2530 UndefPoisonKind Kind) {
2531 if (isGuaranteedNotToBeUndefOrPoison(V, DemandedElts, Kind))
2532 return V;
2533 return getNode(ISD::FREEZE, SDLoc(V), V.getValueType(), V);
2534}
2535
2536/// getShiftAmountOperand - Return the specified value casted to
2537/// the target's desired shift amount type.
2539 EVT OpTy = Op.getValueType();
2540 EVT ShTy = TLI->getShiftAmountTy(LHSTy, getDataLayout());
2541 if (OpTy == ShTy || OpTy.isVector()) return Op;
2542
2543 return getZExtOrTrunc(Op, SDLoc(Op), ShTy);
2544}
2545
2547 SDLoc dl(Node);
2549 const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2550 EVT VT = Node->getValueType(0);
2551 SDValue Tmp1 = Node->getOperand(0);
2552 SDValue Tmp2 = Node->getOperand(1);
2553 const MaybeAlign MA(Node->getConstantOperandVal(3));
2554
2555 SDValue VAListLoad = getLoad(TLI.getPointerTy(getDataLayout()), dl, Tmp1,
2556 Tmp2, MachinePointerInfo(V));
2557 SDValue VAList = VAListLoad;
2558
2559 if (MA && *MA > TLI.getMinStackArgumentAlignment()) {
2560 VAList = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
2561 getConstant(MA->value() - 1, dl, VAList.getValueType()));
2562
2563 VAList = getNode(
2564 ISD::AND, dl, VAList.getValueType(), VAList,
2565 getSignedConstant(-(int64_t)MA->value(), dl, VAList.getValueType()));
2566 }
2567
2568 // Increment the pointer, VAList, to the next vaarg
2569 Tmp1 = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
2570 getConstant(getDataLayout().getTypeAllocSize(
2571 VT.getTypeForEVT(*getContext())),
2572 dl, VAList.getValueType()));
2573 // Store the incremented VAList to the legalized pointer
2574 Tmp1 =
2575 getStore(VAListLoad.getValue(1), dl, Tmp1, Tmp2, MachinePointerInfo(V));
2576 // Load the actual argument out of the pointer VAList
2577 return getLoad(VT, dl, Tmp1, VAList, MachinePointerInfo());
2578}
2579
2581 SDLoc dl(Node);
2583 // This defaults to loading a pointer from the input and storing it to the
2584 // output, returning the chain.
2585 const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue();
2586 const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue();
2587 SDValue Tmp1 =
2588 getLoad(TLI.getPointerTy(getDataLayout()), dl, Node->getOperand(0),
2589 Node->getOperand(2), MachinePointerInfo(VS));
2590 return getStore(Tmp1.getValue(1), dl, Tmp1, Node->getOperand(1),
2591 MachinePointerInfo(VD));
2592}
2593
2595 const DataLayout &DL = getDataLayout();
2596 Type *Ty = VT.getTypeForEVT(*getContext());
2597 Align RedAlign = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty);
2598
2599 if (TLI->isTypeLegal(VT) || !VT.isVector())
2600 return RedAlign;
2601
2602 const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
2603 const Align StackAlign = TFI->getStackAlign();
2604
2605 // See if we can choose a smaller ABI alignment in cases where it's an
2606 // illegal vector type that will get broken down.
2607 if (RedAlign > StackAlign) {
2608 EVT IntermediateVT;
2609 MVT RegisterVT;
2610 unsigned NumIntermediates;
2611 TLI->getVectorTypeBreakdown(*getContext(), VT, IntermediateVT,
2612 NumIntermediates, RegisterVT);
2613 Ty = IntermediateVT.getTypeForEVT(*getContext());
2614 Align RedAlign2 = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty);
2615 if (RedAlign2 < RedAlign)
2616 RedAlign = RedAlign2;
2617
2618 if (!getMachineFunction().getFrameInfo().isStackRealignable())
2619 // If the stack is not realignable, the alignment should be limited to the
2620 // StackAlignment
2621 RedAlign = std::min(RedAlign, StackAlign);
2622 }
2623
2624 return RedAlign;
2625}
2626
2628 MachineFrameInfo &MFI = MF->getFrameInfo();
2629 const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
2630 int StackID = 0;
2631 if (Bytes.isScalable())
2632 StackID = TFI->getStackIDForScalableVectors();
2633 // The stack id gives an indication of whether the object is scalable or
2634 // not, so it's safe to pass in the minimum size here.
2635 int FrameIdx = MFI.CreateStackObject(Bytes.getKnownMinValue(), Alignment,
2636 false, nullptr, StackID);
2637 return getFrameIndex(FrameIdx, TLI->getFrameIndexTy(getDataLayout()));
2638}
2639
2641 Type *Ty = VT.getTypeForEVT(*getContext());
2642 Align StackAlign =
2643 std::max(getDataLayout().getPrefTypeAlign(Ty), Align(minAlign));
2644 return CreateStackTemporary(VT.getStoreSize(), StackAlign);
2645}
2646
2648 TypeSize VT1Size = VT1.getStoreSize();
2649 TypeSize VT2Size = VT2.getStoreSize();
2650 assert(VT1Size.isScalable() == VT2Size.isScalable() &&
2651 "Don't know how to choose the maximum size when creating a stack "
2652 "temporary");
2653 TypeSize Bytes = VT1Size.getKnownMinValue() > VT2Size.getKnownMinValue()
2654 ? VT1Size
2655 : VT2Size;
2656
2657 Type *Ty1 = VT1.getTypeForEVT(*getContext());
2658 Type *Ty2 = VT2.getTypeForEVT(*getContext());
2659 const DataLayout &DL = getDataLayout();
2660 Align Align = std::max(DL.getPrefTypeAlign(Ty1), DL.getPrefTypeAlign(Ty2));
2661 return CreateStackTemporary(Bytes, Align);
2662}
2663
2665 const SDLoc &DL, SDValue Chain) {
2666 EVT SrcVT = SrcOp.getValueType();
2667 Type *DestType = DestVT.getTypeForEVT(*getContext());
2668 Align DestAlign = getDataLayout().getPrefTypeAlign(DestType);
2669
2670 // Create the stack frame object.
2671 Align SrcAlign =
2673 SDValue FIPtr = CreateStackTemporary(SlotVT.getStoreSize(), SrcAlign);
2674
2675 FrameIndexSDNode *StackPtrFI = cast<FrameIndexSDNode>(FIPtr);
2676 int SPFI = StackPtrFI->getIndex();
2677 MachinePointerInfo PtrInfo =
2679
2680 // Emit a store to the stack slot. Use a truncstore if the input value is
2681 // later than DestVT.
2682 SDValue Store;
2683
2684 if (SrcVT.bitsGT(SlotVT))
2685 Store = getTruncStore(Chain, DL, SrcOp, FIPtr, PtrInfo, SlotVT, SrcAlign);
2686 else {
2687 assert(SrcVT.bitsEq(SlotVT) && "Invalid store");
2688 Store = getStore(Chain, DL, SrcOp, FIPtr, PtrInfo, SrcAlign);
2689 }
2690
2691 // Result is a load from the stack slot.
2692 if (SlotVT.bitsEq(DestVT))
2693 return getLoad(DestVT, DL, Store, FIPtr, PtrInfo, DestAlign);
2694
2695 assert(SlotVT.bitsLT(DestVT) && "Unknown extension!");
2696 return getExtLoad(ISD::EXTLOAD, DL, DestVT, Store, FIPtr, PtrInfo, SlotVT,
2697 DestAlign);
2698}
2699
2701 ISD::CondCode Cond, const SDLoc &dl,
2702 SDNodeFlags Flags) {
2703 EVT OpVT = N1.getValueType();
2704
2705 auto GetUndefBooleanConstant = [&]() {
2706 if (VT.getScalarType() == MVT::i1 ||
2707 TLI->getBooleanContents(OpVT) ==
2709 return getUNDEF(VT);
2710 // ZeroOrOne / ZeroOrNegative require specific values for the high bits,
2711 // so we cannot use getUNDEF(). Return zero instead.
2712 return getConstant(0, dl, VT);
2713 };
2714
2715 // These setcc operations always fold.
2716 switch (Cond) {
2717 default: break;
2718 case ISD::SETFALSE:
2719 case ISD::SETFALSE2: return getBoolConstant(false, dl, VT, OpVT);
2720 case ISD::SETTRUE:
2721 case ISD::SETTRUE2: return getBoolConstant(true, dl, VT, OpVT);
2722
2723 case ISD::SETOEQ:
2724 case ISD::SETOGT:
2725 case ISD::SETOGE:
2726 case ISD::SETOLT:
2727 case ISD::SETOLE:
2728 case ISD::SETONE:
2729 case ISD::SETO:
2730 case ISD::SETUO:
2731 case ISD::SETUEQ:
2732 case ISD::SETUNE:
2733 assert(!OpVT.isInteger() && "Illegal setcc for integer!");
2734 break;
2735 }
2736
2737 if (OpVT.isInteger()) {
2738 // For EQ and NE, we can always pick a value for the undef to make the
2739 // predicate pass or fail, so we can return undef.
2740 // Matches behavior in llvm::ConstantFoldCompareInstruction.
2741 // icmp eq/ne X, undef -> undef.
2742 if ((N1.isUndef() || N2.isUndef()) &&
2743 (Cond == ISD::SETEQ || Cond == ISD::SETNE))
2744 return GetUndefBooleanConstant();
2745
2746 // If both operands are undef, we can return undef for int comparison.
2747 // icmp undef, undef -> undef.
2748 if (N1.isUndef() && N2.isUndef())
2749 return GetUndefBooleanConstant();
2750
2751 // icmp X, X -> true/false
2752 // icmp X, undef -> true/false because undef could be X.
2753 if (N1.isUndef() || N2.isUndef() || N1 == N2)
2754 return getBoolConstant(ISD::isTrueWhenEqual(Cond), dl, VT, OpVT);
2755 }
2756
2757 if (ConstantSDNode *N2C = isConstOrConstSplat(N2)) {
2758 const APInt &C2 = N2C->getAPIntValue();
2759 if (ConstantSDNode *N1C = isConstOrConstSplat(N1)) {
2760 const APInt &C1 = N1C->getAPIntValue();
2761
2763 dl, VT, OpVT);
2764 }
2765 }
2766
2767 auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
2768 auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
2769
2770 if (N1CFP && N2CFP) {
2771 auto MaybeR = tryFoldFCmp(N1CFP->getValueAPF(), N2CFP->getValueAPF(),
2772 getDenormalMode(OpVT));
2773 if (!MaybeR)
2774 return SDValue();
2775 APFloat::cmpResult R = *MaybeR;
2776 switch (Cond) {
2777 default: break;
2778 case ISD::SETEQ: if (R==APFloat::cmpUnordered)
2779 return GetUndefBooleanConstant();
2780 [[fallthrough]];
2781 case ISD::SETOEQ: return getBoolConstant(R==APFloat::cmpEqual, dl, VT,
2782 OpVT);
2783 case ISD::SETNE: if (R==APFloat::cmpUnordered)
2784 return GetUndefBooleanConstant();
2785 [[fallthrough]];
2787 R==APFloat::cmpLessThan, dl, VT,
2788 OpVT);
2789 case ISD::SETLT: if (R==APFloat::cmpUnordered)
2790 return GetUndefBooleanConstant();
2791 [[fallthrough]];
2792 case ISD::SETOLT: return getBoolConstant(R==APFloat::cmpLessThan, dl, VT,
2793 OpVT);
2794 case ISD::SETGT: if (R==APFloat::cmpUnordered)
2795 return GetUndefBooleanConstant();
2796 [[fallthrough]];
2798 VT, OpVT);
2799 case ISD::SETLE: if (R==APFloat::cmpUnordered)
2800 return GetUndefBooleanConstant();
2801 [[fallthrough]];
2803 R==APFloat::cmpEqual, dl, VT,
2804 OpVT);
2805 case ISD::SETGE: if (R==APFloat::cmpUnordered)
2806 return GetUndefBooleanConstant();
2807 [[fallthrough]];
2809 R==APFloat::cmpEqual, dl, VT, OpVT);
2810 case ISD::SETO: return getBoolConstant(R!=APFloat::cmpUnordered, dl, VT,
2811 OpVT);
2812 case ISD::SETUO: return getBoolConstant(R==APFloat::cmpUnordered, dl, VT,
2813 OpVT);
2815 R==APFloat::cmpEqual, dl, VT,
2816 OpVT);
2817 case ISD::SETUNE: return getBoolConstant(R!=APFloat::cmpEqual, dl, VT,
2818 OpVT);
2820 R==APFloat::cmpLessThan, dl, VT,
2821 OpVT);
2823 R==APFloat::cmpUnordered, dl, VT,
2824 OpVT);
2826 VT, OpVT);
2827 case ISD::SETUGE: return getBoolConstant(R!=APFloat::cmpLessThan, dl, VT,
2828 OpVT);
2829 }
2830 } else if (N1CFP && OpVT.isSimple() && !N2.isUndef()) {
2831 // Ensure that the constant occurs on the RHS.
2833 if (!TLI->isCondCodeLegal(SwappedCond, OpVT.getSimpleVT()))
2834 return SDValue();
2835 return getSetCC(dl, VT, N2, N1, SwappedCond, /*Chain=*/{},
2836 /*IsSignaling=*/false, Flags);
2837 } else if ((N2CFP && N2CFP->getValueAPF().isNaN()) ||
2838 (OpVT.isFloatingPoint() && (N1.isUndef() || N2.isUndef()))) {
2839 // If an operand is known to be a nan (or undef that could be a nan), we can
2840 // fold it.
2841 // Choosing NaN for the undef will always make unordered comparison succeed
2842 // and ordered comparison fails.
2843 // Matches behavior in llvm::ConstantFoldCompareInstruction.
2844 switch (ISD::getUnorderedFlavor(Cond)) {
2845 default:
2846 llvm_unreachable("Unknown flavor!");
2847 case 0: // Known false.
2848 return getBoolConstant(false, dl, VT, OpVT);
2849 case 1: // Known true.
2850 return getBoolConstant(true, dl, VT, OpVT);
2851 case 2: // Undefined.
2852 return GetUndefBooleanConstant();
2853 }
2854 }
2855
2856 // Could not fold it.
2857 return SDValue();
2858}
2859
2860/// SignBitIsZero - Return true if the sign bit of Op is known to be zero. We
2861/// use this predicate to simplify operations downstream.
2863 unsigned BitWidth = Op.getScalarValueSizeInBits();
2865}
2866
2867// TODO: Should have argument to specify if sign bit of nan is ignorable.
2869 if (Depth >= MaxRecursionDepth)
2870 return false; // Limit search depth.
2871
2872 unsigned Opc = Op.getOpcode();
2873 switch (Opc) {
2874 case ISD::FABS:
2875 return true;
2876 case ISD::AssertNoFPClass: {
2877 FPClassTest NoFPClass =
2878 static_cast<FPClassTest>(Op.getConstantOperandVal(1));
2879
2880 const FPClassTest TestMask = fcNan | fcNegative;
2881 return (NoFPClass & TestMask) == TestMask;
2882 }
2883 case ISD::ARITH_FENCE:
2884 return SignBitIsZeroFP(Op.getOperand(0), Depth + 1);
2885 case ISD::FEXP:
2886 case ISD::FEXP2:
2887 case ISD::FEXP10:
2888 return Op->getFlags().hasNoNaNs();
2889 case ISD::FMINNUM:
2890 case ISD::FMINNUM_IEEE:
2891 case ISD::FMINIMUM:
2892 case ISD::FMINIMUMNUM:
2893 return SignBitIsZeroFP(Op.getOperand(1), Depth + 1) &&
2894 SignBitIsZeroFP(Op.getOperand(0), Depth + 1);
2895 case ISD::FMAXNUM:
2896 case ISD::FMAXNUM_IEEE:
2897 case ISD::FMAXIMUM:
2898 case ISD::FMAXIMUMNUM:
2899 // TODO: If we can ignore the sign bit of nans, only one side being known 0
2900 // is sufficient.
2901 return SignBitIsZeroFP(Op.getOperand(1), Depth + 1) &&
2902 SignBitIsZeroFP(Op.getOperand(0), Depth + 1);
2903 default:
2904 return false;
2905 }
2906
2907 llvm_unreachable("covered opcode switch");
2908}
2909
2910/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
2911/// this predicate to simplify operations downstream. Mask is known to be zero
2912/// for bits that V cannot have.
2914 unsigned Depth) const {
2915 return Mask.isSubsetOf(computeKnownBits(V, Depth).Zero);
2916}
2917
2918/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero in
2919/// DemandedElts. We use this predicate to simplify operations downstream.
2920/// Mask is known to be zero for bits that V cannot have.
2922 const APInt &DemandedElts,
2923 unsigned Depth) const {
2924 return Mask.isSubsetOf(computeKnownBits(V, DemandedElts, Depth).Zero);
2925}
2926
2927/// MaskedVectorIsZero - Return true if 'Op' is known to be zero in
2928/// DemandedElts. We use this predicate to simplify operations downstream.
2930 unsigned Depth /* = 0 */) const {
2931 return computeKnownBits(V, DemandedElts, Depth).isZero();
2932}
2933
2934/// MaskedValueIsAllOnes - Return true if '(Op & Mask) == Mask'.
2936 unsigned Depth) const {
2937 return Mask.isSubsetOf(computeKnownBits(V, Depth).One);
2938}
2939
2941 const APInt &DemandedElts,
2942 unsigned Depth) const {
2943 EVT VT = Op.getValueType();
2944 assert(VT.isVector() && !VT.isScalableVector() && "Only for fixed vectors!");
2945
2946 unsigned NumElts = VT.getVectorNumElements();
2947 assert(DemandedElts.getBitWidth() == NumElts && "Unexpected demanded mask.");
2948
2949 APInt KnownZeroElements = APInt::getZero(NumElts);
2950 for (unsigned EltIdx = 0; EltIdx != NumElts; ++EltIdx) {
2951 if (!DemandedElts[EltIdx])
2952 continue; // Don't query elements that are not demanded.
2953 APInt Mask = APInt::getOneBitSet(NumElts, EltIdx);
2954 if (MaskedVectorIsZero(Op, Mask, Depth))
2955 KnownZeroElements.setBit(EltIdx);
2956 }
2957 return KnownZeroElements;
2958}
2959
2960/// isSplatValue - Return true if the vector V has the same value
2961/// across all DemandedElts. For scalable vectors, we don't know the
2962/// number of lanes at compile time. Instead, we use a 1 bit APInt
2963/// to represent a conservative value for all lanes; that is, that
2964/// one bit value is implicitly splatted across all lanes.
2965bool SelectionDAG::isSplatValue(SDValue V, const APInt &DemandedElts,
2966 APInt &UndefElts, unsigned Depth) const {
2967 unsigned Opcode = V.getOpcode();
2968 EVT VT = V.getValueType();
2969 assert(VT.isVector() && "Vector type expected");
2970 assert((!VT.isScalableVector() || DemandedElts.getBitWidth() == 1) &&
2971 "scalable demanded bits are ignored");
2972
2973 if (!DemandedElts)
2974 return false; // No demanded elts, better to assume we don't know anything.
2975
2976 if (Depth >= MaxRecursionDepth)
2977 return false; // Limit search depth.
2978
2979 // Deal with some common cases here that work for both fixed and scalable
2980 // vector types.
2981 switch (Opcode) {
2982 case ISD::SPLAT_VECTOR:
2983 UndefElts = V.getOperand(0).isUndef()
2984 ? APInt::getAllOnes(DemandedElts.getBitWidth())
2985 : APInt(DemandedElts.getBitWidth(), 0);
2986 return true;
2987 case ISD::ADD:
2988 case ISD::SUB:
2989 case ISD::AND:
2990 case ISD::XOR:
2991 case ISD::OR: {
2992 APInt UndefLHS, UndefRHS;
2993 SDValue LHS = V.getOperand(0);
2994 SDValue RHS = V.getOperand(1);
2995 // Only recognize splats with the same demanded undef elements for both
2996 // operands, otherwise we might fail to handle binop-specific undef
2997 // handling.
2998 // e.g. (and undef, 0) -> 0 etc.
2999 if (isSplatValue(LHS, DemandedElts, UndefLHS, Depth + 1) &&
3000 isSplatValue(RHS, DemandedElts, UndefRHS, Depth + 1) &&
3001 (DemandedElts & UndefLHS) == (DemandedElts & UndefRHS)) {
3002 UndefElts = UndefLHS | UndefRHS;
3003 return true;
3004 }
3005 return false;
3006 }
3007 case ISD::ABS:
3009 case ISD::TRUNCATE:
3010 case ISD::SIGN_EXTEND:
3011 case ISD::ZERO_EXTEND:
3012 return isSplatValue(V.getOperand(0), DemandedElts, UndefElts, Depth + 1);
3013 default:
3014 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
3015 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID)
3016 return TLI->isSplatValueForTargetNode(V, DemandedElts, UndefElts, *this,
3017 Depth);
3018 break;
3019 }
3020
3021 // We don't support other cases than those above for scalable vectors at
3022 // the moment.
3023 if (VT.isScalableVector())
3024 return false;
3025
3026 unsigned NumElts = VT.getVectorNumElements();
3027 assert(NumElts == DemandedElts.getBitWidth() && "Vector size mismatch");
3028 UndefElts = APInt::getZero(NumElts);
3029
3030 switch (Opcode) {
3031 case ISD::BUILD_VECTOR: {
3032 SDValue Scl;
3033 for (unsigned i = 0; i != NumElts; ++i) {
3034 SDValue Op = V.getOperand(i);
3035 if (Op.isUndef()) {
3036 UndefElts.setBit(i);
3037 continue;
3038 }
3039 if (!DemandedElts[i])
3040 continue;
3041 if (Scl && Scl != Op)
3042 return false;
3043 Scl = Op;
3044 }
3045 return true;
3046 }
3047 case ISD::VECTOR_SHUFFLE: {
3048 // Check if this is a shuffle node doing a splat or a shuffle of a splat.
3049 APInt DemandedLHS = APInt::getZero(NumElts);
3050 APInt DemandedRHS = APInt::getZero(NumElts);
3051 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(V)->getMask();
3052 for (int i = 0; i != (int)NumElts; ++i) {
3053 int M = Mask[i];
3054 if (M < 0) {
3055 UndefElts.setBit(i);
3056 continue;
3057 }
3058 if (!DemandedElts[i])
3059 continue;
3060 if (M < (int)NumElts)
3061 DemandedLHS.setBit(M);
3062 else
3063 DemandedRHS.setBit(M - NumElts);
3064 }
3065
3066 // If we aren't demanding either op, assume there's no splat.
3067 // If we are demanding both ops, assume there's no splat.
3068 if ((DemandedLHS.isZero() && DemandedRHS.isZero()) ||
3069 (!DemandedLHS.isZero() && !DemandedRHS.isZero()))
3070 return false;
3071
3072 // See if the demanded elts of the source op is a splat or we only demand
3073 // one element, which should always be a splat.
3074 // TODO: Handle source ops splats with undefs.
3075 auto CheckSplatSrc = [&](SDValue Src, const APInt &SrcElts) {
3076 APInt SrcUndefs;
3077 return (SrcElts.popcount() == 1) ||
3078 (isSplatValue(Src, SrcElts, SrcUndefs, Depth + 1) &&
3079 (SrcElts & SrcUndefs).isZero());
3080 };
3081 if (!DemandedLHS.isZero())
3082 return CheckSplatSrc(V.getOperand(0), DemandedLHS);
3083 return CheckSplatSrc(V.getOperand(1), DemandedRHS);
3084 }
3086 // Offset the demanded elts by the subvector index.
3087 SDValue Src = V.getOperand(0);
3088 // We don't support scalable vectors at the moment.
3089 if (Src.getValueType().isScalableVector())
3090 return false;
3091 uint64_t Idx = V.getConstantOperandVal(1);
3092 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
3093 APInt UndefSrcElts;
3094 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
3095 if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) {
3096 UndefElts = UndefSrcElts.extractBits(NumElts, Idx);
3097 return true;
3098 }
3099 break;
3100 }
3104 // Widen the demanded elts by the src element count.
3105 SDValue Src = V.getOperand(0);
3106 // We don't support scalable vectors at the moment.
3107 if (Src.getValueType().isScalableVector())
3108 return false;
3109 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
3110 APInt UndefSrcElts;
3111 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts);
3112 if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) {
3113 UndefElts = UndefSrcElts.trunc(NumElts);
3114 return true;
3115 }
3116 break;
3117 }
3118 case ISD::BITCAST: {
3119 SDValue Src = V.getOperand(0);
3120 EVT SrcVT = Src.getValueType();
3121 unsigned SrcBitWidth = SrcVT.getScalarSizeInBits();
3122 unsigned BitWidth = VT.getScalarSizeInBits();
3123
3124 // Ignore bitcasts from unsupported types.
3125 // TODO: Add fp support?
3126 if (!SrcVT.isVector() || !SrcVT.isInteger() || !VT.isInteger())
3127 break;
3128
3129 // Bitcast 'small element' vector to 'large element' vector.
3130 if ((BitWidth % SrcBitWidth) == 0) {
3131 // See if each sub element is a splat.
3132 unsigned Scale = BitWidth / SrcBitWidth;
3133 unsigned NumSrcElts = SrcVT.getVectorNumElements();
3134 APInt ScaledDemandedElts =
3135 APIntOps::ScaleBitMask(DemandedElts, NumSrcElts);
3136 for (unsigned I = 0; I != Scale; ++I) {
3137 APInt SubUndefElts;
3138 APInt SubDemandedElt = APInt::getOneBitSet(Scale, I);
3139 APInt SubDemandedElts = APInt::getSplat(NumSrcElts, SubDemandedElt);
3140 SubDemandedElts &= ScaledDemandedElts;
3141 if (!isSplatValue(Src, SubDemandedElts, SubUndefElts, Depth + 1))
3142 return false;
3143 // TODO: Add support for merging sub undef elements.
3144 if (!SubUndefElts.isZero())
3145 return false;
3146 }
3147 return true;
3148 }
3149 break;
3150 }
3151 }
3152
3153 return false;
3154}
3155
3156/// Helper wrapper to main isSplatValue function.
3157bool SelectionDAG::isSplatValue(SDValue V, bool AllowUndefs) const {
3158 EVT VT = V.getValueType();
3159 assert(VT.isVector() && "Vector type expected");
3160
3161 APInt UndefElts;
3162 // Since the number of lanes in a scalable vector is unknown at compile time,
3163 // we track one bit which is implicitly broadcast to all lanes. This means
3164 // that all lanes in a scalable vector are considered demanded.
3165 APInt DemandedElts
3167 return isSplatValue(V, DemandedElts, UndefElts) &&
3168 (AllowUndefs || !UndefElts);
3169}
3170
3173
3174 EVT VT = V.getValueType();
3175 unsigned Opcode = V.getOpcode();
3176 switch (Opcode) {
3177 default: {
3178 APInt UndefElts;
3179 // Since the number of lanes in a scalable vector is unknown at compile time,
3180 // we track one bit which is implicitly broadcast to all lanes. This means
3181 // that all lanes in a scalable vector are considered demanded.
3182 APInt DemandedElts
3184
3185 if (isSplatValue(V, DemandedElts, UndefElts)) {
3186 if (VT.isScalableVector()) {
3187 // DemandedElts and UndefElts are ignored for scalable vectors, since
3188 // the only supported cases are SPLAT_VECTOR nodes.
3189 SplatIdx = 0;
3190 } else {
3191 // Handle case where all demanded elements are UNDEF.
3192 if (DemandedElts.isSubsetOf(UndefElts)) {
3193 SplatIdx = 0;
3194 return getUNDEF(VT);
3195 }
3196 SplatIdx = (UndefElts & DemandedElts).countr_one();
3197 }
3198 return V;
3199 }
3200 break;
3201 }
3202 case ISD::SPLAT_VECTOR:
3203 SplatIdx = 0;
3204 return V;
3205 case ISD::VECTOR_SHUFFLE: {
3206 assert(!VT.isScalableVector());
3207 // Check if this is a shuffle node doing a splat.
3208 // TODO - remove this and rely purely on SelectionDAG::isSplatValue,
3209 // getTargetVShiftNode currently struggles without the splat source.
3210 auto *SVN = cast<ShuffleVectorSDNode>(V);
3211 if (!SVN->isSplat())
3212 break;
3213 int Idx = SVN->getSplatIndex();
3214 int NumElts = V.getValueType().getVectorNumElements();
3215 SplatIdx = Idx % NumElts;
3216 return V.getOperand(Idx / NumElts);
3217 }
3218 }
3219
3220 return SDValue();
3221}
3222
3224 int SplatIdx;
3225 if (SDValue SrcVector = getSplatSourceVector(V, SplatIdx)) {
3226 EVT SVT = SrcVector.getValueType().getScalarType();
3227 EVT LegalSVT = SVT;
3228 if (LegalTypes && !TLI->isTypeLegal(SVT)) {
3229 if (!SVT.isInteger())
3230 return SDValue();
3231 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
3232 if (LegalSVT.bitsLT(SVT))
3233 return SDValue();
3234 }
3235 return getExtractVectorElt(SDLoc(V), LegalSVT, SrcVector, SplatIdx);
3236 }
3237 return SDValue();
3238}
3239
3240std::optional<ConstantRange>
3242 unsigned Depth) const {
3243 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
3244 V.getOpcode() == ISD::SRA) &&
3245 "Unknown shift node");
3246 // Shifting more than the bitwidth is not valid.
3247 unsigned BitWidth = V.getScalarValueSizeInBits();
3248
3249 if (auto *Cst = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
3250 const APInt &ShAmt = Cst->getAPIntValue();
3251 if (ShAmt.uge(BitWidth))
3252 return std::nullopt;
3253 return ConstantRange(ShAmt);
3254 }
3255
3256 if (auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1))) {
3257 const APInt *MinAmt = nullptr, *MaxAmt = nullptr;
3258 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
3259 if (!DemandedElts[i])
3260 continue;
3261 auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i));
3262 if (!SA) {
3263 MinAmt = MaxAmt = nullptr;
3264 break;
3265 }
3266 const APInt &ShAmt = SA->getAPIntValue();
3267 if (ShAmt.uge(BitWidth))
3268 return std::nullopt;
3269 if (!MinAmt || MinAmt->ugt(ShAmt))
3270 MinAmt = &ShAmt;
3271 if (!MaxAmt || MaxAmt->ult(ShAmt))
3272 MaxAmt = &ShAmt;
3273 }
3274 assert(((!MinAmt && !MaxAmt) || (MinAmt && MaxAmt)) &&
3275 "Failed to find matching min/max shift amounts");
3276 if (MinAmt && MaxAmt)
3277 return ConstantRange(*MinAmt, *MaxAmt + 1);
3278 }
3279
3280 // Use computeKnownBits to find a hidden constant/knownbits (usually type
3281 // legalized). e.g. Hidden behind multiple bitcasts/build_vector/casts etc.
3282 KnownBits KnownAmt = computeKnownBits(V.getOperand(1), DemandedElts, Depth);
3283 if (KnownAmt.getMaxValue().ult(BitWidth))
3284 return ConstantRange::fromKnownBits(KnownAmt, /*IsSigned=*/false);
3285
3286 return std::nullopt;
3287}
3288
3289std::optional<unsigned>
3291 unsigned Depth) const {
3292 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
3293 V.getOpcode() == ISD::SRA) &&
3294 "Unknown shift node");
3295 if (std::optional<ConstantRange> AmtRange =
3296 getValidShiftAmountRange(V, DemandedElts, Depth))
3297 if (const APInt *ShAmt = AmtRange->getSingleElement())
3298 return ShAmt->getZExtValue();
3299 return std::nullopt;
3300}
3301
3302std::optional<unsigned>
3304 APInt DemandedElts = getDemandAllEltsMask(V);
3305 return getValidShiftAmount(V, DemandedElts, Depth);
3306}
3307
3308std::optional<unsigned>
3310 unsigned Depth) const {
3311 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
3312 V.getOpcode() == ISD::SRA) &&
3313 "Unknown shift node");
3314 if (std::optional<ConstantRange> AmtRange =
3315 getValidShiftAmountRange(V, DemandedElts, Depth))
3316 return AmtRange->getUnsignedMin().getZExtValue();
3317 return std::nullopt;
3318}
3319
3320std::optional<unsigned>
3322 APInt DemandedElts = getDemandAllEltsMask(V);
3323 return getValidMinimumShiftAmount(V, DemandedElts, Depth);
3324}
3325
3326std::optional<unsigned>
3328 unsigned Depth) const {
3329 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
3330 V.getOpcode() == ISD::SRA) &&
3331 "Unknown shift node");
3332 if (std::optional<ConstantRange> AmtRange =
3333 getValidShiftAmountRange(V, DemandedElts, Depth))
3334 return AmtRange->getUnsignedMax().getZExtValue();
3335 return std::nullopt;
3336}
3337
3338std::optional<unsigned>
3340 APInt DemandedElts = getDemandAllEltsMask(V);
3341 return getValidMaximumShiftAmount(V, DemandedElts, Depth);
3342}
3343
3344/// Determine which bits of Op are known to be either zero or one and return
3345/// them in Known. For vectors, the known bits are those that are shared by
3346/// every vector element.
3348 APInt DemandedElts = getDemandAllEltsMask(Op);
3349 return computeKnownBits(Op, DemandedElts, Depth);
3350}
3351
3352/// Determine which bits of Op are known to be either zero or one and return
3353/// them in Known. The DemandedElts argument allows us to only collect the known
3354/// bits that are shared by the requested vector elements.
3356 unsigned Depth) const {
3357 unsigned BitWidth = Op.getScalarValueSizeInBits();
3358
3359 KnownBits Known(BitWidth); // Don't know anything.
3360
3361 if (auto OptAPInt = Op->bitcastToAPInt()) {
3362 // We know all of the bits for a constant!
3363 APInt V = *std::move(OptAPInt);
3364
3365 // Swap the low-order and high-order double of a ppc_fp128 when casting to
3366 // i128, see #44482.
3367 //
3368 // A ppc_fp128 is two doubles, with the high-order double stored at the
3369 // lower address. Reading that as an integer therefore puts the high-order
3370 // double in the high 64 bits on big-endian targets and in the low 64 bits
3371 // on little-endian targets.
3372 //
3373 // But APFloat::bitcastToAPInt is endianness-agnostic and always places the
3374 // high-order double in the low 64 bits. Hence the two doubles must be
3375 // flipped on big-endian targets.
3376 if (getDataLayout().isBigEndian() && Op.getValueType() == MVT::ppcf128)
3377 V = V.rotl(64);
3378
3379 return KnownBits::makeConstant(V);
3380 }
3381
3382 if (Depth >= MaxRecursionDepth)
3383 return Known; // Limit search depth.
3384
3385 KnownBits Known2;
3386 unsigned NumElts = DemandedElts.getBitWidth();
3387 assert((!Op.getValueType().isScalableVector() || NumElts == 1) &&
3388 "DemandedElts for scalable vectors must be 1 to represent all lanes");
3389 assert((!Op.getValueType().isFixedLengthVector() ||
3390 NumElts == Op.getValueType().getVectorNumElements()) &&
3391 "Unexpected vector size");
3392
3393 if (!DemandedElts)
3394 return Known; // No demanded elts, better to assume we don't know anything.
3395
3396 unsigned Opcode = Op.getOpcode();
3397 switch (Opcode) {
3398 case ISD::FREEZE: {
3399 if (isGuaranteedNotToBeUndefOrPoison(Op.getOperand(0), DemandedElts,
3401 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3402 break;
3403 }
3404 case ISD::MERGE_VALUES:
3405 return computeKnownBits(Op.getOperand(Op.getResNo()), DemandedElts,
3406 Depth + 1);
3407 case ISD::SPLAT_VECTOR: {
3408 SDValue SrcOp = Op.getOperand(0);
3409 assert(SrcOp.getValueSizeInBits() >= BitWidth &&
3410 "Expected SPLAT_VECTOR implicit truncation");
3411 // Implicitly truncate the bits to match the official semantics of
3412 // SPLAT_VECTOR.
3414 break;
3415 }
3417 unsigned ScalarSize = Op.getOperand(0).getScalarValueSizeInBits();
3418 assert(ScalarSize * Op.getNumOperands() == BitWidth &&
3419 "Expected SPLAT_VECTOR_PARTS scalars to cover element width");
3420 for (auto [I, SrcOp] : enumerate(Op->ops())) {
3421 Known.insertBits(computeKnownBits(SrcOp, Depth + 1), ScalarSize * I);
3422 }
3423 break;
3424 }
3425 case ISD::STEP_VECTOR: {
3426 const APInt &Step = Op.getConstantOperandAPInt(0);
3427
3428 if (Step.isPowerOf2())
3429 Known.Zero.setLowBits(Step.logBase2());
3430
3432
3433 if (!isUIntN(BitWidth, Op.getValueType().getVectorMinNumElements()))
3434 break;
3435 const APInt MinNumElts =
3436 APInt(BitWidth, Op.getValueType().getVectorMinNumElements());
3437
3438 bool Overflow;
3439 const APInt MaxNumElts = getVScaleRange(&F, BitWidth)
3441 .umul_ov(MinNumElts, Overflow);
3442 if (Overflow)
3443 break;
3444
3445 const APInt MaxValue = (MaxNumElts - 1).umul_ov(Step, Overflow);
3446 if (Overflow)
3447 break;
3448
3449 Known.Zero.setHighBits(MaxValue.countl_zero());
3450 break;
3451 }
3452 case ISD::BUILD_VECTOR:
3453 assert(!Op.getValueType().isScalableVector());
3454 // Collect the known bits that are shared by every demanded vector element.
3455 Known.setAllConflict();
3456 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
3457 if (!DemandedElts[i])
3458 continue;
3459
3460 SDValue SrcOp = Op.getOperand(i);
3461 if (SrcOp.getOpcode() == ISD::POISON)
3462 continue;
3463
3464 Known2 = computeKnownBits(SrcOp, Depth + 1);
3465
3466 // BUILD_VECTOR can implicitly truncate sources, we must handle this.
3467 if (SrcOp.getValueSizeInBits() != BitWidth) {
3468 assert(SrcOp.getValueSizeInBits() > BitWidth &&
3469 "Expected BUILD_VECTOR implicit truncation");
3470 Known2 = Known2.trunc(BitWidth);
3471 }
3472
3473 // Known bits are the values that are shared by every demanded element.
3474 Known = Known.intersectWith(Known2);
3475
3476 // If we don't know any bits, early out.
3477 if (Known.isUnknown())
3478 break;
3479 }
3480
3481 // If every demanded element was poison, we know nothing.
3482 if (Known.hasConflict())
3483 Known.resetAll();
3484 break;
3485 case ISD::VECTOR_COMPRESS: {
3486 SDValue Vec = Op.getOperand(0);
3487 SDValue PassThru = Op.getOperand(2);
3488 Known = computeKnownBits(PassThru, DemandedElts, Depth + 1);
3489 // If we don't know any bits, early out.
3490 if (Known.isUnknown())
3491 break;
3492 Known2 = computeKnownBits(Vec, Depth + 1);
3493 Known = Known.intersectWith(Known2);
3494 break;
3495 }
3496 case ISD::VECTOR_SHUFFLE: {
3497 assert(!Op.getValueType().isScalableVector());
3498 // Collect the known bits that are shared by every vector element referenced
3499 // by the shuffle.
3500 APInt DemandedLHS, DemandedRHS;
3502 assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
3503 if (!getShuffleDemandedElts(NumElts, SVN->getMask(), DemandedElts,
3504 DemandedLHS, DemandedRHS))
3505 break;
3506
3507 // Known bits are the values that are shared by every demanded element.
3508 Known.setAllConflict();
3509 if (!!DemandedLHS) {
3510 SDValue LHS = Op.getOperand(0);
3511 Known2 = computeKnownBits(LHS, DemandedLHS, Depth + 1);
3512 Known = Known.intersectWith(Known2);
3513 }
3514 // If we don't know any bits, early out.
3515 if (Known.isUnknown())
3516 break;
3517 if (!!DemandedRHS) {
3518 SDValue RHS = Op.getOperand(1);
3519 Known2 = computeKnownBits(RHS, DemandedRHS, Depth + 1);
3520 Known = Known.intersectWith(Known2);
3521 }
3522 break;
3523 }
3524 case ISD::VSCALE: {
3526 const APInt &Multiplier = Op.getConstantOperandAPInt(0);
3528 break;
3529 }
3530 case ISD::CONCAT_VECTORS: {
3531 if (Op.getValueType().isScalableVector())
3532 break;
3533 // Split DemandedElts and test each of the demanded subvectors.
3534 Known.setAllConflict();
3535 EVT SubVectorVT = Op.getOperand(0).getValueType();
3536 unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
3537 unsigned NumSubVectors = Op.getNumOperands();
3538 for (unsigned i = 0; i != NumSubVectors; ++i) {
3539 APInt DemandedSub =
3540 DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts);
3541 if (!!DemandedSub) {
3542 SDValue Sub = Op.getOperand(i);
3543 Known2 = computeKnownBits(Sub, DemandedSub, Depth + 1);
3544 Known = Known.intersectWith(Known2);
3545 }
3546 // If we don't know any bits, early out.
3547 if (Known.isUnknown())
3548 break;
3549 }
3550 break;
3551 }
3552 case ISD::INSERT_SUBVECTOR: {
3553 if (Op.getValueType().isScalableVector())
3554 break;
3555 // Demand any elements from the subvector and the remainder from the src its
3556 // inserted into.
3557 SDValue Src = Op.getOperand(0);
3558 SDValue Sub = Op.getOperand(1);
3559 uint64_t Idx = Op.getConstantOperandVal(2);
3560 unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
3561 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
3562 APInt DemandedSrcElts = DemandedElts;
3563 DemandedSrcElts.clearBits(Idx, Idx + NumSubElts);
3564
3565 Known.setAllConflict();
3566 if (!!DemandedSubElts) {
3567 Known = computeKnownBits(Sub, DemandedSubElts, Depth + 1);
3568 if (Known.isUnknown())
3569 break; // early-out.
3570 }
3571 if (!!DemandedSrcElts) {
3572 Known2 = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
3573 Known = Known.intersectWith(Known2);
3574 }
3575 break;
3576 }
3578 // Offset the demanded elts by the subvector index.
3579 SDValue Src = Op.getOperand(0);
3580
3581 APInt DemandedSrcElts;
3582 if (Src.getValueType().isScalableVector())
3583 DemandedSrcElts = APInt(1, 1); // <=> 'demand all elements'
3584 else {
3585 uint64_t Idx = Op.getConstantOperandVal(1);
3586 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
3587 DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
3588 }
3589 Known = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
3590 break;
3591 }
3592 case ISD::SCALAR_TO_VECTOR: {
3593 if (Op.getValueType().isScalableVector())
3594 break;
3595 // We know about scalar_to_vector as much as we know about it source,
3596 // which becomes the first element of otherwise unknown vector.
3597 if (DemandedElts != 1)
3598 break;
3599
3600 SDValue N0 = Op.getOperand(0);
3601 Known = computeKnownBits(N0, Depth + 1);
3602 if (N0.getValueSizeInBits() != BitWidth)
3603 Known = Known.trunc(BitWidth);
3604
3605 break;
3606 }
3607 case ISD::BITCAST: {
3608 if (Op.getValueType().isScalableVector())
3609 break;
3610
3611 SDValue N0 = Op.getOperand(0);
3612 EVT SubVT = N0.getValueType();
3613 unsigned SubBitWidth = SubVT.getScalarSizeInBits();
3614
3615 // Ignore bitcasts from unsupported types.
3616 if (!(SubVT.isInteger() || SubVT.isFloatingPoint()))
3617 break;
3618
3619 // Fast handling of 'identity' bitcasts.
3620 if (BitWidth == SubBitWidth) {
3621 Known = computeKnownBits(N0, DemandedElts, Depth + 1);
3622 break;
3623 }
3624
3625 bool IsLE = getDataLayout().isLittleEndian();
3626
3627 // Bitcast 'small element' vector to 'large element' scalar/vector.
3628 if ((BitWidth % SubBitWidth) == 0) {
3629 assert(N0.getValueType().isVector() && "Expected bitcast from vector");
3630
3631 // Collect known bits for the (larger) output by collecting the known
3632 // bits from each set of sub elements and shift these into place.
3633 // We need to separately call computeKnownBits for each set of
3634 // sub elements as the knownbits for each is likely to be different.
3635 unsigned SubScale = BitWidth / SubBitWidth;
3636 APInt SubDemandedElts(NumElts * SubScale, 0);
3637 for (unsigned i = 0; i != NumElts; ++i)
3638 if (DemandedElts[i])
3639 SubDemandedElts.setBit(i * SubScale);
3640
3641 for (unsigned i = 0; i != SubScale; ++i) {
3642 Known2 = computeKnownBits(N0, SubDemandedElts.shl(i),
3643 Depth + 1);
3644 unsigned Shifts = IsLE ? i : SubScale - 1 - i;
3645 Known.insertBits(Known2, SubBitWidth * Shifts);
3646 }
3647 }
3648
3649 // Bitcast 'large element' scalar/vector to 'small element' vector.
3650 if ((SubBitWidth % BitWidth) == 0) {
3651 assert(Op.getValueType().isVector() && "Expected bitcast to vector");
3652
3653 // Collect known bits for the (smaller) output by collecting the known
3654 // bits from the overlapping larger input elements and extracting the
3655 // sub sections we actually care about.
3656 unsigned SubScale = SubBitWidth / BitWidth;
3657 APInt SubDemandedElts =
3658 APIntOps::ScaleBitMask(DemandedElts, NumElts / SubScale);
3659 Known2 = computeKnownBits(N0, SubDemandedElts, Depth + 1);
3660
3661 Known.setAllConflict();
3662 for (unsigned i = 0; i != NumElts; ++i)
3663 if (DemandedElts[i]) {
3664 unsigned Shifts = IsLE ? i : NumElts - 1 - i;
3665 unsigned Offset = (Shifts % SubScale) * BitWidth;
3666 Known = Known.intersectWith(Known2.extractBits(BitWidth, Offset));
3667 // If we don't know any bits, early out.
3668 if (Known.isUnknown())
3669 break;
3670 }
3671 }
3672 break;
3673 }
3674 case ISD::AND:
3675 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3676 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3677
3678 Known &= Known2;
3679 break;
3680 case ISD::OR:
3681 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3682 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3683
3684 Known |= Known2;
3685 break;
3686 case ISD::XOR:
3687 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3688 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3689
3690 Known ^= Known2;
3691 break;
3692 case ISD::MUL: {
3693 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3694 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3695 bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1);
3696 // TODO: SelfMultiply can be poison, but not undef.
3697 if (SelfMultiply)
3698 SelfMultiply &= isGuaranteedNotToBeUndefOrPoison(
3699 Op.getOperand(0), DemandedElts, UndefPoisonKind::UndefOrPoison,
3700 Depth + 1);
3701 Known = KnownBits::mul(Known, Known2, SelfMultiply);
3702
3703 // If the multiplication is known not to overflow, the product of a number
3704 // with itself is non-negative. Only do this if we didn't already computed
3705 // the opposite value for the sign bit.
3706 if (Op->getFlags().hasNoSignedWrap() &&
3707 Op.getOperand(0) == Op.getOperand(1) &&
3708 !Known.isNegative())
3709 Known.makeNonNegative();
3710 break;
3711 }
3712 case ISD::MULHU: {
3713 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3714 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3715 Known = KnownBits::mulhu(Known, Known2);
3716 break;
3717 }
3718 case ISD::MULHS: {
3719 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3720 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3721 Known = KnownBits::mulhs(Known, Known2);
3722 break;
3723 }
3724 case ISD::ABDU: {
3725 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3726 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3727 Known = KnownBits::abdu(Known, Known2);
3728 break;
3729 }
3730 case ISD::ABDS: {
3731 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3732 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3733 Known = KnownBits::abds(Known, Known2);
3734 unsigned SignBits1 =
3735 ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
3736 if (SignBits1 == 1)
3737 break;
3738 unsigned SignBits0 =
3739 ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3740 Known.Zero.setHighBits(std::min(SignBits0, SignBits1) - 1);
3741 break;
3742 }
3743 case ISD::UMUL_LOHI: {
3744 assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3745 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3746 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3747 bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1);
3748 if (Op.getResNo() == 0)
3749 Known = KnownBits::mul(Known, Known2, SelfMultiply);
3750 else
3751 Known = KnownBits::mulhu(Known, Known2);
3752 break;
3753 }
3754 case ISD::SMUL_LOHI: {
3755 assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3756 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3757 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3758 bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1);
3759 if (Op.getResNo() == 0)
3760 Known = KnownBits::mul(Known, Known2, SelfMultiply);
3761 else
3762 Known = KnownBits::mulhs(Known, Known2);
3763 break;
3764 }
3765 case ISD::AVGFLOORU: {
3766 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3767 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3768 Known = KnownBits::avgFloorU(Known, Known2);
3769 break;
3770 }
3771 case ISD::AVGCEILU: {
3772 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3773 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3774 Known = KnownBits::avgCeilU(Known, Known2);
3775 break;
3776 }
3777 case ISD::AVGFLOORS: {
3778 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3779 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3780 Known = KnownBits::avgFloorS(Known, Known2);
3781 break;
3782 }
3783 case ISD::AVGCEILS: {
3784 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3785 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3786 Known = KnownBits::avgCeilS(Known, Known2);
3787 break;
3788 }
3789 case ISD::AVGSUBFLOORU:
3790 case ISD::AVGSUBFLOORS: {
3791 bool IsSigned = Op.getOpcode() == ISD::AVGSUBFLOORS;
3792 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3793 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3794 // Subtract in i[N+1] so the difference can't overflow, then halve.
3795 Known = IsSigned ? Known.sext(BitWidth + 1) : Known.zext(BitWidth + 1);
3796 Known2 = IsSigned ? Known2.sext(BitWidth + 1) : Known2.zext(BitWidth + 1);
3797 Known = KnownBits::sub(Known, Known2);
3798 // The shifted in top bit is unknown, but it is truncated away.
3799 Known >>= 1;
3800 Known = Known.trunc(BitWidth);
3801 break;
3802 }
3803 case ISD::SELECT:
3804 case ISD::VSELECT:
3805 Known = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
3806 // If we don't know any bits, early out.
3807 if (Known.isUnknown())
3808 break;
3809 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth+1);
3810
3811 // Only known if known in both the LHS and RHS.
3812 Known = Known.intersectWith(Known2);
3813 break;
3814 case ISD::SELECT_CC:
3815 Known = computeKnownBits(Op.getOperand(3), DemandedElts, Depth+1);
3816 // If we don't know any bits, early out.
3817 if (Known.isUnknown())
3818 break;
3819 Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
3820
3821 // Only known if known in both the LHS and RHS.
3822 Known = Known.intersectWith(Known2);
3823 break;
3824 case ISD::SMULO:
3825 case ISD::UMULO:
3826 if (Op.getResNo() != 1)
3827 break;
3828 // The boolean result conforms to getBooleanContents.
3829 // If we know the result of a setcc has the top bits zero, use this info.
3830 if (TLI->getBooleanContents(Op.getValueType()) ==
3832 BitWidth > 1)
3833 Known.Zero.setBitsFrom(1);
3834 break;
3835 case ISD::SETCC:
3836 case ISD::SETCCCARRY:
3837 case ISD::STRICT_FSETCC:
3838 case ISD::STRICT_FSETCCS: {
3839 unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
3840 // If we know the result of a setcc has the top bits zero, use this info.
3841 if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
3843 BitWidth > 1)
3844 Known.Zero.setBitsFrom(1);
3845 break;
3846 }
3847 case ISD::SHL: {
3848 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3849 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3850
3851 bool NUW = Op->getFlags().hasNoUnsignedWrap();
3852 bool NSW = Op->getFlags().hasNoSignedWrap();
3853
3854 bool ShAmtNonZero = Known2.isNonZero();
3855
3856 Known = KnownBits::shl(Known, Known2, NUW, NSW, ShAmtNonZero);
3857
3858 // Minimum shift low bits are known zero.
3859 if (std::optional<unsigned> ShMinAmt =
3860 getValidMinimumShiftAmount(Op, DemandedElts, Depth + 1))
3861 Known.Zero.setLowBits(*ShMinAmt);
3862 break;
3863 }
3864 case ISD::SRL:
3865 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3866 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3867 Known = KnownBits::lshr(Known, Known2, /*ShAmtNonZero=*/false,
3868 Op->getFlags().hasExact());
3869
3870 // Minimum shift high bits are known zero.
3871 if (std::optional<unsigned> ShMinAmt =
3872 getValidMinimumShiftAmount(Op, DemandedElts, Depth + 1))
3873 Known.Zero.setHighBits(*ShMinAmt);
3874 break;
3875 case ISD::SRA:
3876 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3877 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3878 Known = KnownBits::ashr(Known, Known2, /*ShAmtNonZero=*/false,
3879 Op->getFlags().hasExact());
3880 break;
3881 case ISD::ROTL:
3882 case ISD::ROTR:
3883 if (ConstantSDNode *C =
3884 isConstOrConstSplat(Op.getOperand(1), DemandedElts)) {
3885 unsigned Amt = C->getAPIntValue().urem(BitWidth);
3886
3887 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3888
3889 // Canonicalize to ROTR.
3890 if (Opcode == ISD::ROTL && Amt != 0)
3891 Amt = BitWidth - Amt;
3892
3893 Known.Zero = Known.Zero.rotr(Amt);
3894 Known.One = Known.One.rotr(Amt);
3895 }
3896 break;
3897 case ISD::FSHL:
3898 case ISD::FSHR:
3899 if (ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(2), DemandedElts)) {
3900 unsigned Amt = C->getAPIntValue().urem(BitWidth);
3901
3902 // For fshl, 0-shift returns the 1st arg.
3903 // For fshr, 0-shift returns the 2nd arg.
3904 if (Amt == 0) {
3905 Known = computeKnownBits(Op.getOperand(Opcode == ISD::FSHL ? 0 : 1),
3906 DemandedElts, Depth + 1);
3907 break;
3908 }
3909
3910 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
3911 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
3912 const APInt ShAmt(BitWidth, Amt);
3913 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3914 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3915 Known = Opcode == ISD::FSHL ? KnownBits::fshl(Known, Known2, ShAmt)
3916 : KnownBits::fshr(Known, Known2, ShAmt);
3917 }
3918 break;
3919 case ISD::SHL_PARTS:
3920 case ISD::SRA_PARTS:
3921 case ISD::SRL_PARTS: {
3922 assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3923
3924 // Collect lo/hi source values and concatenate.
3925 unsigned LoBits = Op.getOperand(0).getScalarValueSizeInBits();
3926 unsigned HiBits = Op.getOperand(1).getScalarValueSizeInBits();
3927 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3928 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3929 Known = Known2.concat(Known);
3930
3931 // Collect shift amount.
3932 Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1);
3933
3934 if (Opcode == ISD::SHL_PARTS)
3935 Known = KnownBits::shl(Known, Known2);
3936 else if (Opcode == ISD::SRA_PARTS)
3937 Known = KnownBits::ashr(Known, Known2);
3938 else // if (Opcode == ISD::SRL_PARTS)
3939 Known = KnownBits::lshr(Known, Known2);
3940
3941 // TODO: Minimum shift low/high bits are known zero.
3942
3943 if (Op.getResNo() == 0)
3944 Known = Known.extractBits(LoBits, 0);
3945 else
3946 Known = Known.extractBits(HiBits, LoBits);
3947 break;
3948 }
3950 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3951 EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3952 Known = Known.sextInReg(EVT.getScalarSizeInBits());
3953 break;
3954 }
3955 case ISD::CTTZ:
3956 case ISD::CTTZ_ZERO_POISON: {
3957 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3958 // If we have a known 1, its position is our upper bound.
3959 unsigned PossibleTZ = Known2.countMaxTrailingZeros();
3960 unsigned LowBits = llvm::bit_width(PossibleTZ);
3961 Known.Zero.setBitsFrom(LowBits);
3962 break;
3963 }
3964 case ISD::CTLZ:
3965 case ISD::CTLZ_ZERO_POISON: {
3966 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3967 Known = Known2.ctlz(/*ZeroIsPoison=*/false).zextOrTrunc(BitWidth);
3968 break;
3969 }
3970 case ISD::CTLS: {
3971 unsigned MinRedundantSignBits =
3972 ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1) - 1;
3973 ConstantRange Range(APInt(BitWidth, MinRedundantSignBits),
3975 Known = Range.toKnownBits();
3976 break;
3977 }
3978 case ISD::CTPOP: {
3979 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3980 // If we know some of the bits are zero, they can't be one.
3981 unsigned PossibleOnes = Known2.countMaxPopulation();
3982 Known.Zero.setBitsFrom(llvm::bit_width(PossibleOnes));
3983 break;
3984 }
3985 case ISD::PARITY: {
3986 // Parity returns 0 everywhere but the LSB.
3987 Known.Zero.setBitsFrom(1);
3988 break;
3989 }
3990 case ISD::PDEP: {
3991 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3992 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3993 Known = KnownBits::pdep(Known2, Known);
3994 break;
3995 }
3996 case ISD::PEXT: {
3997 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3998 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3999 Known = KnownBits::pext(Known2, Known);
4000 break;
4001 }
4002 case ISD::CLMUL: {
4003 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4004 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4005 Known = KnownBits::clmul(Known, Known2);
4006 break;
4007 }
4008 case ISD::MGATHER:
4009 case ISD::MLOAD: {
4010 ISD::LoadExtType ETy =
4011 (Opcode == ISD::MGATHER)
4012 ? cast<MaskedGatherSDNode>(Op)->getExtensionType()
4013 : cast<MaskedLoadSDNode>(Op)->getExtensionType();
4014 if (ETy == ISD::ZEXTLOAD) {
4015 EVT MemVT = cast<MemSDNode>(Op)->getMemoryVT();
4016 KnownBits Known0(MemVT.getScalarSizeInBits());
4017 return Known0.zext(BitWidth);
4018 }
4019 break;
4020 }
4021 case ISD::LOAD: {
4023 const Constant *Cst = TLI->getTargetConstantFromLoad(LD);
4024 if (ISD::isNON_EXTLoad(LD) && Cst) {
4025 // Determine any common known bits from the loaded constant pool value.
4026 Type *CstTy = Cst->getType();
4027 if ((NumElts * BitWidth) == CstTy->getPrimitiveSizeInBits() &&
4028 !Op.getValueType().isScalableVector()) {
4029 // If its a vector splat, then we can (quickly) reuse the scalar path.
4030 // NOTE: We assume all elements match and none are UNDEF.
4031 if (CstTy->isVectorTy()) {
4032 if (const Constant *Splat = Cst->getSplatValue()) {
4033 Cst = Splat;
4034 CstTy = Cst->getType();
4035 }
4036 }
4037 // TODO - do we need to handle different bitwidths?
4038 if (CstTy->isVectorTy() && BitWidth == CstTy->getScalarSizeInBits()) {
4039 // Iterate across all vector elements finding common known bits.
4040 Known.setAllConflict();
4041 for (unsigned i = 0; i != NumElts; ++i) {
4042 if (!DemandedElts[i])
4043 continue;
4044 if (Constant *Elt = Cst->getAggregateElement(i)) {
4045 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
4046 const APInt &Value = CInt->getValue();
4047 Known.One &= Value;
4048 Known.Zero &= ~Value;
4049 continue;
4050 }
4051 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
4052 APInt Value = CFP->getValueAPF().bitcastToAPInt();
4053 Known.One &= Value;
4054 Known.Zero &= ~Value;
4055 continue;
4056 }
4057 }
4058 Known.One.clearAllBits();
4059 Known.Zero.clearAllBits();
4060 break;
4061 }
4062 } else if (BitWidth == CstTy->getPrimitiveSizeInBits()) {
4063 if (auto *CInt = dyn_cast<ConstantInt>(Cst)) {
4064 Known = KnownBits::makeConstant(CInt->getValue());
4065 } else if (auto *CFP = dyn_cast<ConstantFP>(Cst)) {
4066 Known =
4067 KnownBits::makeConstant(CFP->getValueAPF().bitcastToAPInt());
4068 }
4069 }
4070 }
4071 } else if (Op.getResNo() == 0) {
4072 unsigned ScalarMemorySize = LD->getMemoryVT().getScalarSizeInBits();
4073 KnownBits KnownScalarMemory(ScalarMemorySize);
4074 if (const MDNode *MD = LD->getRanges())
4075 computeKnownBitsFromRangeMetadata(*MD, KnownScalarMemory);
4076
4077 // Extend the Known bits from memory to the size of the scalar result.
4078 if (ISD::isZEXTLoad(Op.getNode()))
4079 Known = KnownScalarMemory.zext(BitWidth);
4080 else if (ISD::isSEXTLoad(Op.getNode()))
4081 Known = KnownScalarMemory.sext(BitWidth);
4082 else if (ISD::isEXTLoad(Op.getNode()))
4083 Known = KnownScalarMemory.anyext(BitWidth);
4084 else
4085 Known = KnownScalarMemory;
4086 assert(Known.getBitWidth() == BitWidth);
4087 return Known;
4088 }
4089 break;
4090 }
4092 if (Op.getValueType().isScalableVector())
4093 break;
4094 EVT InVT = Op.getOperand(0).getValueType();
4095 APInt InDemandedElts = DemandedElts.zext(InVT.getVectorNumElements());
4096 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
4097 Known = Known.zext(BitWidth);
4098 break;
4099 }
4100 case ISD::ZERO_EXTEND: {
4101 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4102 Known = Known.zext(BitWidth);
4103 break;
4104 }
4106 if (Op.getValueType().isScalableVector())
4107 break;
4108 EVT InVT = Op.getOperand(0).getValueType();
4109 APInt InDemandedElts = DemandedElts.zext(InVT.getVectorNumElements());
4110 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
4111 // If the sign bit is known to be zero or one, then sext will extend
4112 // it to the top bits, else it will just zext.
4113 Known = Known.sext(BitWidth);
4114 break;
4115 }
4116 case ISD::SIGN_EXTEND: {
4117 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4118 // If the sign bit is known to be zero or one, then sext will extend
4119 // it to the top bits, else it will just zext.
4120 Known = Known.sext(BitWidth);
4121 break;
4122 }
4124 if (Op.getValueType().isScalableVector())
4125 break;
4126 EVT InVT = Op.getOperand(0).getValueType();
4127 APInt InDemandedElts = DemandedElts.zext(InVT.getVectorNumElements());
4128 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
4129 Known = Known.anyext(BitWidth);
4130 break;
4131 }
4132 case ISD::ANY_EXTEND: {
4133 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4134 Known = Known.anyext(BitWidth);
4135 break;
4136 }
4137 case ISD::TRUNCATE: {
4138 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4139 Known = Known.trunc(BitWidth);
4140 break;
4141 }
4142 case ISD::TRUNCATE_SSAT_S: {
4143 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4144 Known = Known.truncSSat(BitWidth);
4145 break;
4146 }
4147 case ISD::TRUNCATE_SSAT_U: {
4148 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4149 Known = Known.truncSSatU(BitWidth);
4150 break;
4151 }
4152 case ISD::TRUNCATE_USAT_U: {
4153 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4154 Known = Known.truncUSat(BitWidth);
4155 break;
4156 }
4157 case ISD::AssertZext: {
4158 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
4160 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4161 Known.Zero |= (~InMask);
4162 Known.One &= (~Known.Zero);
4163 break;
4164 }
4165 case ISD::AssertAlign: {
4166 unsigned LogOfAlign = Log2(cast<AssertAlignSDNode>(Op)->getAlign());
4167 assert(LogOfAlign != 0);
4168
4169 // TODO: Should use maximum with source
4170 // If a node is guaranteed to be aligned, set low zero bits accordingly as
4171 // well as clearing one bits.
4172 Known.Zero.setLowBits(LogOfAlign);
4173 Known.One.clearLowBits(LogOfAlign);
4174 break;
4175 }
4176 case ISD::AssertNoFPClass: {
4177 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4178
4179 FPClassTest NoFPClass =
4180 static_cast<FPClassTest>(Op.getConstantOperandVal(1));
4181
4182 EVT SVT = Op.getValueType().getScalarType();
4183 unsigned SignBitPos;
4184 if (SVT == MVT::ppcf128)
4185 // The sign bit position depends on endianness: ppc_fp128 is two doubles
4186 // in a trenchcoat, and it is the high-order double that carries the sign.
4187 SignBitPos = getDataLayout().isBigEndian() ? 127 : 63;
4189 // IEEE-like formats, bf16, x86_fp80: the sign bit is the integer MSB.
4190 SignBitPos = BitWidth - 1;
4191 else
4192 break;
4193
4194 const FPClassTest NegativeTestMask = fcNan | fcNegative;
4195 if ((NoFPClass & NegativeTestMask) == NegativeTestMask) {
4196 // Cannot be negative.
4197 Known.Zero.setBit(SignBitPos);
4198 }
4199
4200 const FPClassTest PositiveTestMask = fcNan | fcPositive;
4201 if ((NoFPClass & PositiveTestMask) == PositiveTestMask) {
4202 // Cannot be positive.
4203 Known.One.setBit(SignBitPos);
4204 }
4205
4206 break;
4207 }
4208 case ISD::FABS: {
4209 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4210 EVT SVT = Op.getValueType().getScalarType();
4211 if (SVT == MVT::ppcf128) {
4212 // The sign bit position depends on endianness: ppc_fp128 is two doubles
4213 // in a trenchcoat, fabs only clears the sign bit of the high-order
4214 // double.
4215 Known.resetAll();
4216 Known.Zero.setBit(getDataLayout().isBigEndian() ? 127 : 63);
4217 } else if (APFloat::hasSignBitInMSB(SVT.getFltSemantics())) {
4218 // IEEE-like formats, bf16, x86_fp80: the sign bit is the integer MSB,
4219 // fabs clears that sign bit.
4220 Known.Zero.setSignBit();
4221 Known.One.clearSignBit();
4222 }
4223
4224 break;
4225 }
4226 case ISD::FGETSIGN:
4227 // All bits are zero except the low bit.
4228 Known.Zero.setBitsFrom(1);
4229 break;
4230 case ISD::ADD: {
4231 SDNodeFlags Flags = Op.getNode()->getFlags();
4232 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4233 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4234 bool SelfAdd = Op.getOperand(0) == Op.getOperand(1) &&
4236 Op.getOperand(0), DemandedElts,
4238 Known = KnownBits::add(Known, Known2, Flags.hasNoSignedWrap(),
4239 Flags.hasNoUnsignedWrap(), SelfAdd);
4240 break;
4241 }
4242 case ISD::SUB: {
4243 SDNodeFlags Flags = Op.getNode()->getFlags();
4244 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4245 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4246 Known = KnownBits::sub(Known, Known2, Flags.hasNoSignedWrap(),
4247 Flags.hasNoUnsignedWrap());
4248 break;
4249 }
4250 case ISD::USUBO:
4251 case ISD::SSUBO:
4252 case ISD::USUBO_CARRY:
4253 case ISD::SSUBO_CARRY:
4254 if (Op.getResNo() == 1) {
4255 // If we know the result of a setcc has the top bits zero, use this info.
4256 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
4258 BitWidth > 1)
4259 Known.Zero.setBitsFrom(1);
4260 break;
4261 }
4262 [[fallthrough]];
4263 case ISD::SUBC: {
4264 assert(Op.getResNo() == 0 &&
4265 "We only compute knownbits for the difference here.");
4266
4267 // With USUBO_CARRY and SSUBO_CARRY a borrow bit may be added in.
4268 KnownBits Borrow(1);
4269 if (Opcode == ISD::USUBO_CARRY || Opcode == ISD::SSUBO_CARRY) {
4270 Borrow = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1);
4271 // Borrow has bit width 1
4272 Borrow = Borrow.trunc(1);
4273 } else {
4274 Borrow.setAllZero();
4275 }
4276
4277 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4278 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4279 Known = KnownBits::computeForSubBorrow(Known, Known2, Borrow);
4280 break;
4281 }
4282 case ISD::UADDO:
4283 case ISD::SADDO:
4284 case ISD::UADDO_CARRY:
4285 case ISD::SADDO_CARRY:
4286 if (Op.getResNo() == 1) {
4287 // If we know the result of a setcc has the top bits zero, use this info.
4288 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
4290 BitWidth > 1)
4291 Known.Zero.setBitsFrom(1);
4292 break;
4293 }
4294 [[fallthrough]];
4295 case ISD::ADDC:
4296 case ISD::ADDE: {
4297 assert(Op.getResNo() == 0 && "We only compute knownbits for the sum here.");
4298
4299 // With ADDE and UADDO_CARRY, a carry bit may be added in.
4300 KnownBits Carry(1);
4301 if (Opcode == ISD::ADDE)
4302 // Can't track carry from glue, set carry to unknown.
4303 Carry.resetAll();
4304 else if (Opcode == ISD::UADDO_CARRY || Opcode == ISD::SADDO_CARRY) {
4305 Carry = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1);
4306 // Carry has bit width 1
4307 Carry = Carry.trunc(1);
4308 } else {
4309 Carry.setAllZero();
4310 }
4311
4312 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4313 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4314 Known = KnownBits::computeForAddCarry(Known, Known2, Carry);
4315 break;
4316 }
4317 case ISD::UDIV: {
4318 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4319 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4320 Known = KnownBits::udiv(Known, Known2, Op->getFlags().hasExact());
4321 break;
4322 }
4323 case ISD::SDIV: {
4324 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4325 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4326 Known = KnownBits::sdiv(Known, Known2, Op->getFlags().hasExact());
4327 break;
4328 }
4329 case ISD::SREM: {
4330 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4331 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4332 Known = KnownBits::srem(Known, Known2);
4333 break;
4334 }
4335 case ISD::UREM: {
4336 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4337 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4338 Known = KnownBits::urem(Known, Known2);
4339 break;
4340 }
4341 case ISD::EXTRACT_ELEMENT: {
4342 Known = computeKnownBits(Op.getOperand(0), Depth+1);
4343 const unsigned Index = Op.getConstantOperandVal(1);
4344 const unsigned EltBitWidth = Op.getValueSizeInBits();
4345
4346 Known = Known.extractBits(EltBitWidth, Index * EltBitWidth);
4347 break;
4348 }
4350 SDValue InVec = Op.getOperand(0);
4351 SDValue EltNo = Op.getOperand(1);
4352 EVT VecVT = InVec.getValueType();
4353 // computeKnownBits not yet implemented for scalable vectors.
4354 if (VecVT.isScalableVector())
4355 break;
4356 const unsigned EltBitWidth = VecVT.getScalarSizeInBits();
4357 const unsigned NumSrcElts = VecVT.getVectorNumElements();
4358
4359 // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know
4360 // anything about the extended bits.
4361 if (BitWidth > EltBitWidth)
4362 Known = Known.trunc(EltBitWidth);
4363
4364 // If we know the element index, just demand that vector element, else for
4365 // an unknown element index, ignore DemandedElts and demand them all.
4366 APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
4367 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
4368 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
4369 DemandedSrcElts =
4370 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
4371
4372 Known = computeKnownBits(InVec, DemandedSrcElts, Depth + 1);
4373 if (BitWidth > EltBitWidth)
4374 Known = Known.anyext(BitWidth);
4375 break;
4376 }
4377 case ISD::BUILD_PAIR: {
4378 // Operand 0 is the low half and operand 1 the high half,
4379 // KnownBits::concat places its argument in the low bits.
4380 Known = computeKnownBits(Op.getOperand(0), Depth + 1);
4381 Known2 = computeKnownBits(Op.getOperand(1), Depth + 1);
4382 Known = Known2.concat(Known);
4383 break;
4384 }
4386 if (Op.getValueType().isScalableVector())
4387 break;
4388
4389 // If we know the element index, split the demand between the
4390 // source vector and the inserted element, otherwise assume we need
4391 // the original demanded vector elements and the value.
4392 SDValue InVec = Op.getOperand(0);
4393 SDValue InVal = Op.getOperand(1);
4394 SDValue EltNo = Op.getOperand(2);
4395 bool DemandedVal = true;
4396 APInt DemandedVecElts = DemandedElts;
4397 auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
4398 if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
4399 unsigned EltIdx = CEltNo->getZExtValue();
4400 DemandedVal = !!DemandedElts[EltIdx];
4401 DemandedVecElts.clearBit(EltIdx);
4402 }
4403 Known.setAllConflict();
4404 if (DemandedVal) {
4405 Known2 = computeKnownBits(InVal, Depth + 1);
4406 Known = Known.intersectWith(Known2.zextOrTrunc(BitWidth));
4407 }
4408 if (!!DemandedVecElts) {
4409 Known2 = computeKnownBits(InVec, DemandedVecElts, Depth + 1);
4410 Known = Known.intersectWith(Known2);
4411 }
4412 break;
4413 }
4414 case ISD::BITREVERSE: {
4415 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4416 Known = Known2.reverseBits();
4417 break;
4418 }
4419 case ISD::BSWAP: {
4420 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4421 Known = Known2.byteSwap();
4422 break;
4423 }
4424 case ISD::ABS:
4425 case ISD::ABS_MIN_POISON: {
4426 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4427 Known = Known2.abs();
4428 Known.Zero.setHighBits(
4429 ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1) - 1);
4430 break;
4431 }
4432 case ISD::USUBSAT: {
4433 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4434 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4435 Known = KnownBits::usub_sat(Known, Known2);
4436 break;
4437 }
4438 case ISD::UMIN: {
4439 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4440 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4441 Known = KnownBits::umin(Known, Known2);
4442 break;
4443 }
4444 case ISD::UMAX: {
4445 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4446 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4447 Known = KnownBits::umax(Known, Known2);
4448 break;
4449 }
4450 case ISD::SMIN:
4451 case ISD::SMAX: {
4452 // If we have a clamp pattern, we know that the number of sign bits will be
4453 // the minimum of the clamp min/max range.
4454 bool IsMax = (Opcode == ISD::SMAX);
4455 ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
4456 if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
4457 if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
4458 CstHigh =
4459 isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
4460 if (CstLow && CstHigh) {
4461 if (!IsMax)
4462 std::swap(CstLow, CstHigh);
4463
4464 const APInt &ValueLow = CstLow->getAPIntValue();
4465 const APInt &ValueHigh = CstHigh->getAPIntValue();
4466 if (ValueLow.sle(ValueHigh)) {
4467 unsigned LowSignBits = ValueLow.getNumSignBits();
4468 unsigned HighSignBits = ValueHigh.getNumSignBits();
4469 unsigned MinSignBits = std::min(LowSignBits, HighSignBits);
4470 if (ValueLow.isNegative() && ValueHigh.isNegative()) {
4471 Known.One.setHighBits(MinSignBits);
4472 break;
4473 }
4474 if (ValueLow.isNonNegative() && ValueHigh.isNonNegative()) {
4475 Known.Zero.setHighBits(MinSignBits);
4476 break;
4477 }
4478 }
4479 }
4480
4481 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4482 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4483 if (IsMax)
4484 Known = KnownBits::smax(Known, Known2);
4485 else
4486 Known = KnownBits::smin(Known, Known2);
4487
4488 // For SMAX, if CstLow is non-negative we know the result will be
4489 // non-negative and thus all sign bits are 0.
4490 // TODO: There's an equivalent of this for smin with negative constant for
4491 // known ones.
4492 if (IsMax && CstLow) {
4493 const APInt &ValueLow = CstLow->getAPIntValue();
4494 if (ValueLow.isNonNegative()) {
4495 unsigned SignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
4496 Known.Zero.setHighBits(std::min(SignBits, ValueLow.getNumSignBits()));
4497 }
4498 }
4499
4500 break;
4501 }
4502 case ISD::UINT_TO_FP: {
4503 Known.makeNonNegative();
4504 break;
4505 }
4506 case ISD::SINT_TO_FP: {
4507 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4508 if (Known2.isNonNegative())
4509 Known.makeNonNegative();
4510 else if (Known2.isNegative())
4511 Known.makeNegative();
4512 break;
4513 }
4514 case ISD::FP_TO_UINT_SAT: {
4515 // FP_TO_UINT_SAT produces an unsigned value that fits in the saturating VT.
4516 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
4518 break;
4519 }
4520 case ISD::ATOMIC_LOAD: {
4521 // If we are looking at the loaded value.
4522 if (Op.getResNo() == 0) {
4523 auto *AT = cast<AtomicSDNode>(Op);
4524 unsigned ScalarMemorySize = AT->getMemoryVT().getScalarSizeInBits();
4525 KnownBits KnownScalarMemory(ScalarMemorySize);
4526 if (const MDNode *MD = AT->getRanges())
4527 computeKnownBitsFromRangeMetadata(*MD, KnownScalarMemory);
4528
4529 switch (AT->getExtensionType()) {
4530 case ISD::ZEXTLOAD:
4531 Known = KnownScalarMemory.zext(BitWidth);
4532 break;
4533 case ISD::SEXTLOAD:
4534 Known = KnownScalarMemory.sext(BitWidth);
4535 break;
4536 case ISD::EXTLOAD:
4537 switch (TLI->getExtendForAtomicOps()) {
4538 case ISD::ZERO_EXTEND:
4539 Known = KnownScalarMemory.zext(BitWidth);
4540 break;
4541 case ISD::SIGN_EXTEND:
4542 Known = KnownScalarMemory.sext(BitWidth);
4543 break;
4544 default:
4545 Known = KnownScalarMemory.anyext(BitWidth);
4546 break;
4547 }
4548 break;
4549 case ISD::NON_EXTLOAD:
4550 Known = KnownScalarMemory;
4551 break;
4552 }
4553 assert(Known.getBitWidth() == BitWidth);
4554 }
4555 break;
4556 }
4558 if (Op.getResNo() == 1) {
4559 // The boolean result conforms to getBooleanContents.
4560 // If we know the result of a setcc has the top bits zero, use this info.
4561 if (TLI->getBooleanContents(Op.getValueType()) ==
4563 BitWidth > 1)
4564 Known.Zero.setBitsFrom(1);
4565 break;
4566 }
4567 [[fallthrough]];
4569 case ISD::ATOMIC_SWAP:
4580 case ISD::ATOMIC_LOAD_UMAX: {
4581 // If we are looking at the loaded value.
4582 if (Op.getResNo() == 0) {
4583 auto *AT = cast<AtomicSDNode>(Op);
4584 unsigned MemBits = AT->getMemoryVT().getScalarSizeInBits();
4585
4586 if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND)
4587 Known.Zero.setBitsFrom(MemBits);
4588 }
4589 break;
4590 }
4591 case ISD::FrameIndex:
4592 case ISD::TargetFrameIndex: {
4593 const MachineFunction &MF = getMachineFunction();
4594 int FrameIdx = cast<FrameIndexSDNode>(Op)->getIndex();
4595 TLI->computeKnownBitsForStackObjectPointer(
4596 Known, MF, MF.getFrameInfo().getObjectAlign(FrameIdx));
4597 break;
4598 }
4599 case ISD::VP_LOAD_FF: {
4600 if (Op.getResNo() != 1)
4601 break;
4602 // The second result of vp.load.ff is an unsigned value that is less than or
4603 // equal to the EVL operand.
4604 KnownBits VLKB =
4605 computeKnownBits(Op.getOperand(3), DemandedElts, Depth + 1);
4606 // The new VL is also bounded by the largest vector length.
4607 EVT ResVT = Op->getValueType(0);
4608 auto ResKB = KnownBits::makeConstant(
4610 if (ResVT.isScalableVector()) {
4612 ResKB = KnownBits::mul(getVScaleRange(&F, BitWidth).toKnownBits(), ResKB);
4613 }
4614 Known.Zero.setHighBits(KnownBits::umin(VLKB, ResKB).countMinLeadingZeros());
4615 break;
4616 }
4617
4618 default:
4619 if (Opcode < ISD::BUILTIN_OP_END)
4620 break;
4621 [[fallthrough]];
4625 // Allow the target to implement this method for its nodes.
4626 TLI->computeKnownBitsForTargetNode(Op, Known, DemandedElts, *this, Depth);
4627 break;
4628 }
4629
4630 return Known;
4631}
4632
4633/// Convert ConstantRange OverflowResult into SelectionDAG::OverflowKind.
4646
4649 // X + 0 never overflow
4650 if (isNullConstant(N1))
4651 return OFK_Never;
4652
4653 // If both operands each have at least two sign bits, the addition
4654 // cannot overflow.
4655 if (ComputeNumSignBits(N0) > 1 && ComputeNumSignBits(N1) > 1)
4656 return OFK_Never;
4657
4658 // TODO: Add ConstantRange::signedAddMayOverflow handling.
4659 return OFK_Sometime;
4660}
4661
4664 // X + 0 never overflow
4665 if (isNullConstant(N1))
4666 return OFK_Never;
4667
4668 // mulhi + 1 never overflow
4669 KnownBits N1Known = computeKnownBits(N1);
4670 if (N0.getOpcode() == ISD::UMUL_LOHI && N0.getResNo() == 1 &&
4671 N1Known.getMaxValue().ult(2))
4672 return OFK_Never;
4673
4674 KnownBits N0Known = computeKnownBits(N0);
4675 if (N1.getOpcode() == ISD::UMUL_LOHI && N1.getResNo() == 1 &&
4676 N0Known.getMaxValue().ult(2))
4677 return OFK_Never;
4678
4679 // Fallback to ConstantRange::unsignedAddMayOverflow handling.
4680 ConstantRange N0Range = ConstantRange::fromKnownBits(N0Known, false);
4681 ConstantRange N1Range = ConstantRange::fromKnownBits(N1Known, false);
4682 return mapOverflowResult(N0Range.unsignedAddMayOverflow(N1Range));
4683}
4684
4687 // X - 0 never overflow
4688 if (isNullConstant(N1))
4689 return OFK_Never;
4690
4691 // If both operands each have at least two sign bits, the subtraction
4692 // cannot overflow.
4693 if (ComputeNumSignBits(N0) > 1 && ComputeNumSignBits(N1) > 1)
4694 return OFK_Never;
4695
4696 KnownBits N0Known = computeKnownBits(N0);
4697 KnownBits N1Known = computeKnownBits(N1);
4698 ConstantRange N0Range = ConstantRange::fromKnownBits(N0Known, true);
4699 ConstantRange N1Range = ConstantRange::fromKnownBits(N1Known, true);
4700 return mapOverflowResult(N0Range.signedSubMayOverflow(N1Range));
4701}
4702
4705 // X - 0 never overflow
4706 if (isNullConstant(N1))
4707 return OFK_Never;
4708
4709 ConstantRange N0Range =
4710 computeConstantRangeIncludingKnownBits(N0, /*ForSigned=*/false);
4711 ConstantRange N1Range =
4712 computeConstantRangeIncludingKnownBits(N1, /*ForSigned=*/false);
4713 return mapOverflowResult(N0Range.unsignedSubMayOverflow(N1Range));
4714}
4715
4718 // X * 0 and X * 1 never overflow.
4719 if (isNullConstant(N1) || isOneConstant(N1))
4720 return OFK_Never;
4721
4724 return mapOverflowResult(N0Range.unsignedMulMayOverflow(N1Range));
4725}
4726
4729 // X * 0 and X * 1 never overflow.
4730 if (isNullConstant(N1) || isOneConstant(N1))
4731 return OFK_Never;
4732
4733 // Get the size of the result.
4734 unsigned BitWidth = N0.getScalarValueSizeInBits();
4735
4736 // Sum of the sign bits.
4737 unsigned SignBits = ComputeNumSignBits(N0) + ComputeNumSignBits(N1);
4738
4739 // If we have enough sign bits, then there's no overflow.
4740 if (SignBits > BitWidth + 1)
4741 return OFK_Never;
4742
4743 if (SignBits == BitWidth + 1) {
4744 // The overflow occurs when the true multiplication of the
4745 // the operands is the minimum negative number.
4746 KnownBits N0Known = computeKnownBits(N0);
4747 KnownBits N1Known = computeKnownBits(N1);
4748 // If one of the operands is non-negative, then there's no
4749 // overflow.
4750 if (N0Known.isNonNegative() || N1Known.isNonNegative())
4751 return OFK_Never;
4752 }
4753
4754 return OFK_Sometime;
4755}
4756
4758 unsigned Depth) const {
4759 APInt DemandedElts = getDemandAllEltsMask(Op);
4760 return computeConstantRange(Op, DemandedElts, ForSigned, Depth);
4761}
4762
4764 const APInt &DemandedElts,
4765 bool ForSigned,
4766 unsigned Depth) const {
4767 EVT VT = Op.getValueType();
4768 unsigned BitWidth = VT.getScalarSizeInBits();
4769
4770 if (Depth >= MaxRecursionDepth)
4771 return ConstantRange::getFull(BitWidth);
4772
4773 if (ConstantSDNode *C = isConstOrConstSplat(Op, DemandedElts))
4774 return ConstantRange(C->getAPIntValue());
4775
4776 unsigned Opcode = Op.getOpcode();
4777 switch (Opcode) {
4778 case ISD::VSCALE: {
4780 const APInt &Multiplier = Op.getConstantOperandAPInt(0);
4781 return getVScaleRange(&F, BitWidth).multiply(Multiplier);
4782 }
4783 default:
4784 break;
4785 }
4786
4787 return ConstantRange::getFull(BitWidth);
4788}
4789
4792 unsigned Depth) const {
4793 APInt DemandedElts = getDemandAllEltsMask(Op);
4794 return computeConstantRangeIncludingKnownBits(Op, DemandedElts, ForSigned,
4795 Depth);
4796}
4797
4799 SDValue Op, const APInt &DemandedElts, bool ForSigned,
4800 unsigned Depth) const {
4801 KnownBits Known = computeKnownBits(Op, DemandedElts, Depth);
4803 ConstantRange CR2 = computeConstantRange(Op, DemandedElts, ForSigned, Depth);
4806 return CR1.intersectWith(CR2, RangeType);
4807}
4808
4810 unsigned Depth) const {
4811 APInt DemandedElts = getDemandAllEltsMask(Val);
4812 return isKnownToBeAPowerOfTwo(Val, DemandedElts, OrZero, Depth);
4813}
4814
4816 const APInt &DemandedElts,
4817 bool OrZero, unsigned Depth) const {
4818 if (Depth >= MaxRecursionDepth)
4819 return false; // Limit search depth.
4820
4821 EVT OpVT = Val.getValueType();
4822 unsigned BitWidth = OpVT.getScalarSizeInBits();
4823 [[maybe_unused]] unsigned NumElts = DemandedElts.getBitWidth();
4824 assert((!OpVT.isScalableVector() || NumElts == 1) &&
4825 "DemandedElts for scalable vectors must be 1 to represent all lanes");
4826 assert(
4827 (!OpVT.isFixedLengthVector() || NumElts == OpVT.getVectorNumElements()) &&
4828 "Unexpected vector size");
4829
4830 auto IsPowerOfTwoOrZero = [BitWidth, OrZero](const ConstantSDNode *C) {
4831 APInt V = C->getAPIntValue().zextOrTrunc(BitWidth);
4832 return (OrZero && V.isZero()) || V.isPowerOf2();
4833 };
4834
4835 // Is the constant a known power of 2 or zero?
4836 if (ISD::matchUnaryPredicate(Val, DemandedElts, IsPowerOfTwoOrZero,
4837 /*AllowUndefs=*/false, /*AllowTruncation=*/true))
4838 return true;
4839
4840 switch (Val.getOpcode()) {
4842 SDValue InVec = Val.getOperand(0);
4843 SDValue EltNo = Val.getOperand(1);
4844 EVT VecVT = InVec.getValueType();
4845
4846 // Skip scalable vectors or implicit extensions.
4847 if (VecVT.isScalableVector() ||
4848 OpVT.getScalarSizeInBits() != VecVT.getScalarSizeInBits())
4849 break;
4850
4851 // If we know the element index, just demand that vector element, else for
4852 // an unknown element index, ignore DemandedElts and demand them all.
4853 const unsigned NumSrcElts = VecVT.getVectorNumElements();
4854 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
4855 APInt DemandedSrcElts =
4856 ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts)
4857 ? APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue())
4858 : APInt::getAllOnes(NumSrcElts);
4859 return isKnownToBeAPowerOfTwo(InVec, DemandedSrcElts, OrZero, Depth + 1);
4860 }
4861
4862 case ISD::AND: {
4863 // Looking for `x & -x` pattern:
4864 // If x == 0:
4865 // x & -x -> 0
4866 // If x != 0:
4867 // x & -x -> non-zero pow2
4868 // so if we find the pattern return whether we know `x` is non-zero.
4869 SDValue X, Z;
4870 if (sd_match(Val, m_And(m_Value(X), m_Neg(m_Deferred(X)))) ||
4871 (sd_match(Val, m_And(m_Value(X), m_Sub(m_Value(Z), m_Deferred(X)))) &&
4872 MaskedVectorIsZero(Z, DemandedElts, Depth + 1)))
4873 return OrZero || isKnownNeverZero(X, DemandedElts, Depth);
4874 break;
4875 }
4876
4877 case ISD::SHL: {
4878 // A left-shift of a constant one will have exactly one bit set because
4879 // shifting the bit off the end is undefined.
4880 auto *C = isConstOrConstSplat(Val.getOperand(0), DemandedElts);
4881 if (C && C->getAPIntValue() == 1)
4882 return true;
4883 return (OrZero || isKnownNeverZero(Val, DemandedElts, Depth)) &&
4884 isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedElts, OrZero,
4885 Depth + 1);
4886 }
4887
4888 case ISD::SRL: {
4889 // A logical right-shift of a constant sign-bit will have exactly
4890 // one bit set.
4891 auto *C = isConstOrConstSplat(Val.getOperand(0), DemandedElts);
4892 if (C && C->getAPIntValue().isSignMask())
4893 return true;
4894 return (OrZero || isKnownNeverZero(Val, DemandedElts, Depth)) &&
4895 isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedElts, OrZero,
4896 Depth + 1);
4897 }
4898
4899 case ISD::TRUNCATE:
4900 return (OrZero || isKnownNeverZero(Val, DemandedElts, Depth)) &&
4901 isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedElts, OrZero,
4902 Depth + 1);
4903
4904 case ISD::ROTL:
4905 case ISD::ROTR:
4906 return isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedElts, OrZero,
4907 Depth + 1);
4908 case ISD::BSWAP:
4909 case ISD::BITREVERSE:
4910 return isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedElts, OrZero,
4911 Depth + 1);
4912
4913 case ISD::SMIN:
4914 case ISD::SMAX:
4915 case ISD::UMIN:
4916 case ISD::UMAX:
4917 return isKnownToBeAPowerOfTwo(Val.getOperand(1), DemandedElts, OrZero,
4918 Depth + 1) &&
4919 isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedElts, OrZero,
4920 Depth + 1);
4921
4922 case ISD::SELECT:
4923 case ISD::VSELECT:
4924 return isKnownToBeAPowerOfTwo(Val.getOperand(2), DemandedElts, OrZero,
4925 Depth + 1) &&
4926 isKnownToBeAPowerOfTwo(Val.getOperand(1), DemandedElts, OrZero,
4927 Depth + 1);
4928
4929 case ISD::ZERO_EXTEND:
4930 return isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedElts, OrZero,
4931 Depth + 1);
4932
4933 case ISD::VSCALE:
4934 // vscale(power-of-two) is a power-of-two
4935 return isKnownToBeAPowerOfTwo(Val.getOperand(0), /*OrZero=*/false,
4936 Depth + 1);
4937
4938 case ISD::VECTOR_SHUFFLE: {
4940 // Demanded elements with undef shuffle mask elements are unknown
4941 // - we cannot guarantee they are a power of two, so return false.
4942 APInt DemandedLHS, DemandedRHS;
4944 assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
4945 if (!getShuffleDemandedElts(NumElts, SVN->getMask(), DemandedElts,
4946 DemandedLHS, DemandedRHS))
4947 return false;
4948
4949 // All demanded elements from LHS must be known power of two.
4950 if (!!DemandedLHS && !isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedLHS,
4951 OrZero, Depth + 1))
4952 return false;
4953
4954 // All demanded elements from RHS must be known power of two.
4955 if (!!DemandedRHS && !isKnownToBeAPowerOfTwo(Val.getOperand(1), DemandedRHS,
4956 OrZero, Depth + 1))
4957 return false;
4958
4959 return true;
4960 }
4961 }
4962
4963 // More could be done here, though the above checks are enough
4964 // to handle some common cases.
4965 return false;
4966}
4967
4969 if (ConstantFPSDNode *C1 = isConstOrConstSplatFP(Val, true))
4970 return C1->getValueAPF().getExactLog2Abs() >= 0;
4971
4972 if (Val.getOpcode() == ISD::UINT_TO_FP || Val.getOpcode() == ISD::SINT_TO_FP)
4973 return isKnownToBeAPowerOfTwo(Val.getOperand(0), Depth + 1);
4974
4975 return false;
4976}
4977
4979 APInt DemandedElts = getDemandAllEltsMask(Op);
4980 return ComputeNumSignBits(Op, DemandedElts, Depth);
4981}
4982
4983unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, const APInt &DemandedElts,
4984 unsigned Depth) const {
4985 EVT VT = Op.getValueType();
4986 assert((VT.isInteger() || VT.isFloatingPoint()) && "Invalid VT!");
4987 unsigned VTBits = VT.getScalarSizeInBits();
4988 unsigned NumElts = DemandedElts.getBitWidth();
4989 unsigned Tmp, Tmp2;
4990 unsigned FirstAnswer = 1;
4991
4992 assert((!VT.isScalableVector() || NumElts == 1) &&
4993 "DemandedElts for scalable vectors must be 1 to represent all lanes");
4994
4995 if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
4996 const APInt &Val = C->getAPIntValue();
4997 return Val.getNumSignBits();
4998 }
4999
5000 if (Depth >= MaxRecursionDepth)
5001 return 1; // Limit search depth.
5002
5003 if (!DemandedElts)
5004 return 1; // No demanded elts, better to assume we don't know anything.
5005
5006 unsigned Opcode = Op.getOpcode();
5007 switch (Opcode) {
5008 default: break;
5009 case ISD::AssertSext:
5010 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
5011 return VTBits-Tmp+1;
5012 case ISD::AssertZext:
5013 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
5014 return VTBits-Tmp;
5015 case ISD::FREEZE:
5016 if (isGuaranteedNotToBeUndefOrPoison(Op.getOperand(0), DemandedElts,
5018 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5019 break;
5020 case ISD::MERGE_VALUES:
5021 return ComputeNumSignBits(Op.getOperand(Op.getResNo()), DemandedElts,
5022 Depth + 1);
5023 case ISD::SPLAT_VECTOR: {
5024 // Check if the sign bits of source go down as far as the truncated value.
5025 unsigned NumSrcBits = Op.getOperand(0).getValueSizeInBits();
5026 unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
5027 if (NumSrcSignBits > (NumSrcBits - VTBits))
5028 return NumSrcSignBits - (NumSrcBits - VTBits);
5029 break;
5030 }
5031 case ISD::BUILD_VECTOR:
5032 assert(!VT.isScalableVector());
5033 Tmp = VTBits;
5034 for (unsigned i = 0, e = Op.getNumOperands(); (i < e) && (Tmp > 1); ++i) {
5035 if (!DemandedElts[i])
5036 continue;
5037
5038 SDValue SrcOp = Op.getOperand(i);
5039 // BUILD_VECTOR can implicitly truncate sources, we handle this specially
5040 // for constant nodes to ensure we only look at the sign bits.
5042 APInt T = C->getAPIntValue().trunc(VTBits);
5043 Tmp2 = T.getNumSignBits();
5044 } else if (SrcOp.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5045 SrcOp.getOperand(0).getScalarValueSizeInBits() >= VTBits) {
5046 // EXTRACT_VECTOR_ELT can extend the value with high bits undefined. If
5047 // this BUILD_VECTOR truncates those undefined bits we can just look
5048 // through the SrcOp and query the vector directly.
5049 SDValue InVec = SrcOp.getOperand(0);
5050 EVT InVecVT = InVec.getValueType();
5051
5052 APInt DemandedSrcElts;
5053 if (InVecVT.isScalableVector())
5054 // Demand all elements.
5055 DemandedSrcElts = APInt(1, 1);
5056 else {
5057 unsigned NumSrcElts = InVecVT.getVectorNumElements();
5058 auto *ConstEltNo = dyn_cast<ConstantSDNode>(SrcOp.getOperand(1));
5059 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
5060 DemandedSrcElts =
5061 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
5062 else
5063 DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
5064 }
5065
5066 Tmp2 = ComputeNumSignBits(InVec, DemandedSrcElts, Depth + 1);
5067 unsigned ExtraBits = InVec.getScalarValueSizeInBits() - VTBits;
5068 if (ExtraBits)
5069 Tmp2 = (Tmp2 > ExtraBits ? Tmp2 - ExtraBits : 1);
5070 } else {
5071 Tmp2 = ComputeNumSignBits(SrcOp, Depth + 1);
5072
5073 if (SrcOp.getValueSizeInBits() != VTBits) {
5074 assert(SrcOp.getValueSizeInBits() > VTBits &&
5075 "Expected BUILD_VECTOR implicit truncation");
5076 unsigned ExtraBits = SrcOp.getValueSizeInBits() - VTBits;
5077 Tmp2 = (Tmp2 > ExtraBits ? Tmp2 - ExtraBits : 1);
5078 }
5079 }
5080 Tmp = std::min(Tmp, Tmp2);
5081 }
5082 return Tmp;
5083
5084 case ISD::VECTOR_COMPRESS: {
5085 SDValue Vec = Op.getOperand(0);
5086 SDValue PassThru = Op.getOperand(2);
5087 Tmp = ComputeNumSignBits(PassThru, DemandedElts, Depth + 1);
5088 if (Tmp == 1)
5089 return 1;
5090 Tmp2 = ComputeNumSignBits(Vec, Depth + 1);
5091 Tmp = std::min(Tmp, Tmp2);
5092 return Tmp;
5093 }
5094
5095 case ISD::VECTOR_SHUFFLE: {
5096 // Collect the minimum number of sign bits that are shared by every vector
5097 // element referenced by the shuffle.
5098 APInt DemandedLHS, DemandedRHS;
5100 assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
5101 if (!getShuffleDemandedElts(NumElts, SVN->getMask(), DemandedElts,
5102 DemandedLHS, DemandedRHS))
5103 return 1;
5104
5105 Tmp = std::numeric_limits<unsigned>::max();
5106 if (!!DemandedLHS)
5107 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedLHS, Depth + 1);
5108 if (!!DemandedRHS) {
5109 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedRHS, Depth + 1);
5110 Tmp = std::min(Tmp, Tmp2);
5111 }
5112 // If we don't know anything, early out and try computeKnownBits fall-back.
5113 if (Tmp == 1)
5114 break;
5115 assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
5116 return Tmp;
5117 }
5118
5119 case ISD::BITCAST: {
5120 if (VT.isScalableVector())
5121 break;
5122 SDValue N0 = Op.getOperand(0);
5123 EVT SrcVT = N0.getValueType();
5124 unsigned SrcBits = SrcVT.getScalarSizeInBits();
5125
5126 // Ignore bitcasts from unsupported types..
5127 if (!(SrcVT.isInteger() || SrcVT.isFloatingPoint()))
5128 break;
5129
5130 // Fast handling of 'identity' bitcasts.
5131 if (VTBits == SrcBits)
5132 return ComputeNumSignBits(N0, DemandedElts, Depth + 1);
5133
5134 bool IsLE = getDataLayout().isLittleEndian();
5135
5136 // Bitcast 'large element' scalar/vector to 'small element' vector.
5137 if ((SrcBits % VTBits) == 0) {
5138 assert(VT.isVector() && "Expected bitcast to vector");
5139
5140 unsigned Scale = SrcBits / VTBits;
5141 APInt SrcDemandedElts =
5142 APIntOps::ScaleBitMask(DemandedElts, NumElts / Scale);
5143
5144 // Fast case - sign splat can be simply split across the small elements.
5145 Tmp = ComputeNumSignBits(N0, SrcDemandedElts, Depth + 1);
5146 if (Tmp == SrcBits)
5147 return VTBits;
5148
5149 // Slow case - determine how far the sign extends into each sub-element.
5150 Tmp2 = VTBits;
5151 for (unsigned i = 0; i != NumElts; ++i)
5152 if (DemandedElts[i]) {
5153 unsigned SubOffset = i % Scale;
5154 SubOffset = (IsLE ? ((Scale - 1) - SubOffset) : SubOffset);
5155 SubOffset = SubOffset * VTBits;
5156 if (Tmp <= SubOffset)
5157 return 1;
5158 Tmp2 = std::min(Tmp2, Tmp - SubOffset);
5159 }
5160 return Tmp2;
5161 }
5162 break;
5163 }
5164
5166 // FP_TO_SINT_SAT produces a signed value that fits in the saturating VT.
5167 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
5168 return VTBits - Tmp + 1;
5169 case ISD::SIGN_EXTEND:
5170 Tmp = VTBits - Op.getOperand(0).getScalarValueSizeInBits();
5171 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1) + Tmp;
5173 // Max of the input and what this extends.
5174 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
5175 Tmp = VTBits-Tmp+1;
5176 Tmp2 = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
5177 return std::max(Tmp, Tmp2);
5179 if (VT.isScalableVector())
5180 break;
5181 SDValue Src = Op.getOperand(0);
5182 EVT SrcVT = Src.getValueType();
5183 APInt DemandedSrcElts = DemandedElts.zext(SrcVT.getVectorNumElements());
5184 Tmp = VTBits - SrcVT.getScalarSizeInBits();
5185 return ComputeNumSignBits(Src, DemandedSrcElts, Depth+1) + Tmp;
5186 }
5187 case ISD::SRA:
5188 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5189 // SRA X, C -> adds C sign bits.
5190 if (std::optional<unsigned> ShAmt =
5191 getValidMinimumShiftAmount(Op, DemandedElts, Depth + 1))
5192 Tmp = std::min(Tmp + *ShAmt, VTBits);
5193 return Tmp;
5194 case ISD::SHL:
5195 if (std::optional<ConstantRange> ShAmtRange =
5196 getValidShiftAmountRange(Op, DemandedElts, Depth + 1)) {
5197 unsigned MaxShAmt = ShAmtRange->getUnsignedMax().getZExtValue();
5198 unsigned MinShAmt = ShAmtRange->getUnsignedMin().getZExtValue();
5199 // Try to look through ZERO/SIGN/ANY_EXTEND. If all extended bits are
5200 // shifted out, then we can compute the number of sign bits for the
5201 // operand being extended. A future improvement could be to pass along the
5202 // "shifted left by" information in the recursive calls to
5203 // ComputeKnownSignBits. Allowing us to handle this more generically.
5204 if (ISD::isExtOpcode(Op.getOperand(0).getOpcode())) {
5205 SDValue Ext = Op.getOperand(0);
5206 EVT ExtVT = Ext.getValueType();
5207 SDValue Extendee = Ext.getOperand(0);
5208 EVT ExtendeeVT = Extendee.getValueType();
5209 unsigned SizeDifference =
5210 ExtVT.getScalarSizeInBits() - ExtendeeVT.getScalarSizeInBits();
5211 if (SizeDifference <= MinShAmt) {
5212 Tmp = SizeDifference +
5213 ComputeNumSignBits(Extendee, DemandedElts, Depth + 1);
5214 if (MaxShAmt < Tmp)
5215 return Tmp - MaxShAmt;
5216 }
5217 }
5218 // shl destroys sign bits, ensure it doesn't shift out all sign bits.
5219 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5220 if (MaxShAmt < Tmp)
5221 return Tmp - MaxShAmt;
5222 }
5223 break;
5224 case ISD::AND:
5225 case ISD::OR:
5226 case ISD::XOR: // NOT is handled here.
5227 // Logical binary ops preserve the number of sign bits at the worst.
5228 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
5229 if (Tmp != 1) {
5230 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
5231 FirstAnswer = std::min(Tmp, Tmp2);
5232 // We computed what we know about the sign bits as our first
5233 // answer. Now proceed to the generic code that uses
5234 // computeKnownBits, and pick whichever answer is better.
5235 }
5236 break;
5237
5238 case ISD::SELECT:
5239 case ISD::VSELECT:
5240 Tmp = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
5241 if (Tmp == 1) return 1; // Early out.
5242 Tmp2 = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
5243 return std::min(Tmp, Tmp2);
5244 case ISD::SELECT_CC:
5245 Tmp = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
5246 if (Tmp == 1) return 1; // Early out.
5247 Tmp2 = ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth+1);
5248 return std::min(Tmp, Tmp2);
5249
5250 case ISD::SMIN:
5251 case ISD::SMAX: {
5252 // If we have a clamp pattern, we know that the number of sign bits will be
5253 // the minimum of the clamp min/max range.
5254 bool IsMax = (Opcode == ISD::SMAX);
5255 ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
5256 if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
5257 if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
5258 CstHigh =
5259 isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
5260 if (CstLow && CstHigh) {
5261 if (!IsMax)
5262 std::swap(CstLow, CstHigh);
5263 if (CstLow->getAPIntValue().sle(CstHigh->getAPIntValue())) {
5264 Tmp = CstLow->getAPIntValue().getNumSignBits();
5265 Tmp2 = CstHigh->getAPIntValue().getNumSignBits();
5266 return std::min(Tmp, Tmp2);
5267 }
5268 }
5269
5270 // Fallback - just get the minimum number of sign bits of the operands.
5271 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5272 if (Tmp == 1)
5273 return 1; // Early out.
5274 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
5275 return std::min(Tmp, Tmp2);
5276 }
5277 case ISD::UMIN:
5278 case ISD::UMAX:
5279 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5280 if (Tmp == 1)
5281 return 1; // Early out.
5282 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
5283 return std::min(Tmp, Tmp2);
5284 case ISD::SSUBO_CARRY:
5285 case ISD::USUBO_CARRY:
5286 // sub_carry(x,x,c) -> 0/-1 (sext carry)
5287 if (Op.getResNo() == 0 && Op.getOperand(0) == Op.getOperand(1))
5288 return VTBits;
5289 [[fallthrough]];
5290 case ISD::SADDO:
5291 case ISD::UADDO:
5292 case ISD::SADDO_CARRY:
5293 case ISD::UADDO_CARRY:
5294 case ISD::SSUBO:
5295 case ISD::USUBO:
5296 case ISD::SMULO:
5297 case ISD::UMULO:
5298 if (Op.getResNo() != 1)
5299 break;
5300 // The boolean result conforms to getBooleanContents.
5301 // If setcc returns 0/-1, all bits are sign bits.
5302 if (TLI->getBooleanContents(VT) ==
5304 return VTBits;
5305 break;
5306 case ISD::SETCC:
5307 case ISD::SETCCCARRY:
5308 case ISD::STRICT_FSETCC:
5309 case ISD::STRICT_FSETCCS: {
5310 unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
5311 // If setcc returns 0/-1, all bits are sign bits.
5312 if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
5314 return VTBits;
5315 break;
5316 }
5319 // Semantically similar to icmp ult.
5320 if (TLI->getBooleanContents(VT) ==
5322 return VTBits;
5323 break;
5324 case ISD::ROTL:
5325 case ISD::ROTR: {
5326 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5327 ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(1), DemandedElts);
5328 FirstAnswer = SignBitsOps::rot(
5329 Tmp, VTBits, C ? std::optional(C->getAPIntValue()) : std::nullopt,
5330 Opcode == ISD::ROTR);
5331 break;
5332 }
5333 case ISD::ADD:
5334 case ISD::ADDC:
5335 // TODO: Move Operand 1 check before Operand 0 check
5336 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5337 if (Tmp == 1) return 1; // Early out.
5338
5339 // Special case decrementing a value (ADD X, -1):
5340 if (ConstantSDNode *CRHS =
5341 isConstOrConstSplat(Op.getOperand(1), DemandedElts))
5342 if (CRHS->isAllOnes()) {
5344 computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
5345
5346 // If the input is known to be 0 or 1, the output is 0/-1, which is all
5347 // sign bits set.
5348 if ((Known.Zero | 1).isAllOnes())
5349 return VTBits;
5350
5351 // If we are subtracting one from a positive number, there is no carry
5352 // out of the result.
5353 if (Known.isNonNegative())
5354 return Tmp;
5355 }
5356
5357 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
5358 if (Tmp2 == 1) return 1; // Early out.
5359
5360 // Add can have at most one carry bit. Thus we know that the output
5361 // is, at worst, one more bit than the inputs.
5362 return std::min(Tmp, Tmp2) - 1;
5363 case ISD::SUB:
5364 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
5365 if (Tmp2 == 1) return 1; // Early out.
5366
5367 // Handle NEG.
5368 if (ConstantSDNode *CLHS =
5369 isConstOrConstSplat(Op.getOperand(0), DemandedElts))
5370 if (CLHS->isZero()) {
5372 computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
5373 // If the input is known to be 0 or 1, the output is 0/-1, which is all
5374 // sign bits set.
5375 if ((Known.Zero | 1).isAllOnes())
5376 return VTBits;
5377
5378 // If the input is known to be positive (the sign bit is known clear),
5379 // the output of the NEG has the same number of sign bits as the input.
5380 if (Known.isNonNegative())
5381 return Tmp2;
5382
5383 // Otherwise, we treat this like a SUB.
5384 }
5385
5386 // Sub can have at most one carry bit. Thus we know that the output
5387 // is, at worst, one more bit than the inputs.
5388 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5389 if (Tmp == 1) return 1; // Early out.
5390 return std::min(Tmp, Tmp2) - 1;
5391 case ISD::MUL: {
5392 // The output of the Mul can be at most twice the valid bits in the inputs.
5393 unsigned SignBitsOp0 =
5394 ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5395 if (SignBitsOp0 == 1)
5396 break;
5397 unsigned SignBitsOp1 =
5398 ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
5399 if (SignBitsOp1 == 1)
5400 break;
5401 unsigned OutValidBits =
5402 (VTBits - SignBitsOp0 + 1) + (VTBits - SignBitsOp1 + 1);
5403 return OutValidBits > VTBits ? 1 : VTBits - OutValidBits + 1;
5404 }
5405 case ISD::AVGCEILS:
5406 case ISD::AVGFLOORS:
5407 case ISD::AVGSUBFLOORS:
5408 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5409 if (Tmp == 1)
5410 return 1; // Early out.
5411 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
5412 return std::min(Tmp, Tmp2);
5413 case ISD::SREM:
5414 // The sign bit is the LHS's sign bit, except when the result of the
5415 // remainder is zero. The magnitude of the result should be less than or
5416 // equal to the magnitude of the LHS. Therefore, the result should have
5417 // at least as many sign bits as the left hand side.
5418 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5419 case ISD::TRUNCATE: {
5420 // Check if the sign bits of source go down as far as the truncated value.
5421 unsigned NumSrcBits = Op.getOperand(0).getScalarValueSizeInBits();
5422 unsigned NumSrcSignBits =
5423 ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5424 if (NumSrcSignBits > (NumSrcBits - VTBits))
5425 return NumSrcSignBits - (NumSrcBits - VTBits);
5426 break;
5427 }
5428 case ISD::EXTRACT_ELEMENT: {
5429 if (VT.isScalableVector())
5430 break;
5431 const int KnownSign = ComputeNumSignBits(Op.getOperand(0), Depth+1);
5432 const int BitWidth = Op.getValueSizeInBits();
5433 const int Items = Op.getOperand(0).getValueSizeInBits() / BitWidth;
5434
5435 // Get reverse index (starting from 1), Op1 value indexes elements from
5436 // little end. Sign starts at big end.
5437 const int rIndex = Items - 1 - Op.getConstantOperandVal(1);
5438
5439 // If the sign portion ends in our element the subtraction gives correct
5440 // result. Otherwise it gives either negative or > bitwidth result
5441 return std::clamp(KnownSign - rIndex * BitWidth, 1, BitWidth);
5442 }
5444 if (VT.isScalableVector())
5445 break;
5446 // If we know the element index, split the demand between the
5447 // source vector and the inserted element, otherwise assume we need
5448 // the original demanded vector elements and the value.
5449 SDValue InVec = Op.getOperand(0);
5450 SDValue InVal = Op.getOperand(1);
5451 SDValue EltNo = Op.getOperand(2);
5452 bool DemandedVal = true;
5453 APInt DemandedVecElts = DemandedElts;
5454 auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
5455 if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
5456 unsigned EltIdx = CEltNo->getZExtValue();
5457 DemandedVal = !!DemandedElts[EltIdx];
5458 DemandedVecElts.clearBit(EltIdx);
5459 }
5460 Tmp = std::numeric_limits<unsigned>::max();
5461 if (DemandedVal) {
5462 // TODO - handle implicit truncation of inserted elements.
5463 if (InVal.getScalarValueSizeInBits() != VTBits)
5464 break;
5465 Tmp2 = ComputeNumSignBits(InVal, Depth + 1);
5466 Tmp = std::min(Tmp, Tmp2);
5467 }
5468 if (!!DemandedVecElts) {
5469 Tmp2 = ComputeNumSignBits(InVec, DemandedVecElts, Depth + 1);
5470 Tmp = std::min(Tmp, Tmp2);
5471 }
5472 assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
5473 return Tmp;
5474 }
5476 SDValue InVec = Op.getOperand(0);
5477 SDValue EltNo = Op.getOperand(1);
5478 EVT VecVT = InVec.getValueType();
5479 // ComputeNumSignBits not yet implemented for scalable vectors.
5480 if (VecVT.isScalableVector())
5481 break;
5482 const unsigned BitWidth = Op.getValueSizeInBits();
5483 const unsigned EltBitWidth = Op.getOperand(0).getScalarValueSizeInBits();
5484 const unsigned NumSrcElts = VecVT.getVectorNumElements();
5485
5486 // If BitWidth > EltBitWidth the value is anyext:ed, and we do not know
5487 // anything about sign bits. But if the sizes match we can derive knowledge
5488 // about sign bits from the vector operand.
5489 if (BitWidth != EltBitWidth)
5490 break;
5491
5492 // If we know the element index, just demand that vector element, else for
5493 // an unknown element index, ignore DemandedElts and demand them all.
5494 APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
5495 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
5496 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
5497 DemandedSrcElts =
5498 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
5499
5500 return ComputeNumSignBits(InVec, DemandedSrcElts, Depth + 1);
5501 }
5503 // Offset the demanded elts by the subvector index.
5504 SDValue Src = Op.getOperand(0);
5505
5506 APInt DemandedSrcElts;
5507 if (Src.getValueType().isScalableVector())
5508 DemandedSrcElts = APInt(1, 1);
5509 else {
5510 uint64_t Idx = Op.getConstantOperandVal(1);
5511 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
5512 DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
5513 }
5514 return ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
5515 }
5516 case ISD::CONCAT_VECTORS: {
5517 if (VT.isScalableVector())
5518 break;
5519 // Determine the minimum number of sign bits across all demanded
5520 // elts of the input vectors. Early out if the result is already 1.
5521 Tmp = std::numeric_limits<unsigned>::max();
5522 EVT SubVectorVT = Op.getOperand(0).getValueType();
5523 unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
5524 unsigned NumSubVectors = Op.getNumOperands();
5525 for (unsigned i = 0; (i < NumSubVectors) && (Tmp > 1); ++i) {
5526 APInt DemandedSub =
5527 DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts);
5528 if (!DemandedSub)
5529 continue;
5530 Tmp2 = ComputeNumSignBits(Op.getOperand(i), DemandedSub, Depth + 1);
5531 Tmp = std::min(Tmp, Tmp2);
5532 }
5533 assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
5534 return Tmp;
5535 }
5536 case ISD::INSERT_SUBVECTOR: {
5537 SDValue Src = Op.getOperand(0);
5538 SDValue Sub = Op.getOperand(1);
5539 if (VT.isScalableVector()) {
5540 Tmp = ComputeNumSignBits(Sub, Depth + 1);
5541 Tmp = std::min(Tmp, ComputeNumSignBits(Src, Depth + 1));
5542 return Tmp;
5543 }
5544 // Demand any elements from the subvector and the remainder from the src its
5545 // inserted into.
5546 uint64_t Idx = Op.getConstantOperandVal(2);
5547 unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
5548 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
5549 APInt DemandedSrcElts = DemandedElts;
5550 DemandedSrcElts.clearBits(Idx, Idx + NumSubElts);
5551
5552 Tmp = std::numeric_limits<unsigned>::max();
5553 if (!!DemandedSubElts) {
5554 Tmp = ComputeNumSignBits(Sub, DemandedSubElts, Depth + 1);
5555 if (Tmp == 1)
5556 return 1; // early-out
5557 }
5558 if (!!DemandedSrcElts) {
5559 Tmp2 = ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
5560 Tmp = std::min(Tmp, Tmp2);
5561 }
5562 assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
5563 return Tmp;
5564 }
5565 case ISD::LOAD: {
5566 // If we are looking at the loaded value of the SDNode.
5567 if (Op.getResNo() != 0)
5568 break;
5569
5571 if (const MDNode *Ranges = LD->getRanges()) {
5572 if (DemandedElts != 1)
5573 break;
5574
5576 if (VTBits > CR.getBitWidth()) {
5577 switch (LD->getExtensionType()) {
5578 case ISD::SEXTLOAD:
5579 CR = CR.signExtend(VTBits);
5580 break;
5581 case ISD::ZEXTLOAD:
5582 CR = CR.zeroExtend(VTBits);
5583 break;
5584 default:
5585 break;
5586 }
5587 }
5588
5589 if (VTBits != CR.getBitWidth())
5590 break;
5591 return std::min(CR.getSignedMin().getNumSignBits(),
5593 }
5594
5595 unsigned ExtType = LD->getExtensionType();
5596 switch (ExtType) {
5597 default:
5598 break;
5599 case ISD::SEXTLOAD: // e.g. i16->i32 = '17' bits known.
5600 Tmp = LD->getMemoryVT().getScalarSizeInBits();
5601 return VTBits - Tmp + 1;
5602 case ISD::ZEXTLOAD: // e.g. i16->i32 = '16' bits known.
5603 Tmp = LD->getMemoryVT().getScalarSizeInBits();
5604 return VTBits - Tmp;
5605 case ISD::NON_EXTLOAD:
5606 if (const Constant *Cst = TLI->getTargetConstantFromLoad(LD)) {
5607 // We only need to handle vectors - computeKnownBits should handle
5608 // scalar cases.
5609 Type *CstTy = Cst->getType();
5610 if (CstTy->isVectorTy() && !VT.isScalableVector() &&
5611 (NumElts * VTBits) == CstTy->getPrimitiveSizeInBits() &&
5612 VTBits == CstTy->getScalarSizeInBits()) {
5613 Tmp = VTBits;
5614 for (unsigned i = 0; i != NumElts; ++i) {
5615 if (!DemandedElts[i])
5616 continue;
5617 if (Constant *Elt = Cst->getAggregateElement(i)) {
5618 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
5619 const APInt &Value = CInt->getValue();
5620 Tmp = std::min(Tmp, Value.getNumSignBits());
5621 continue;
5622 }
5623 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
5624 APInt Value = CFP->getValueAPF().bitcastToAPInt();
5625 Tmp = std::min(Tmp, Value.getNumSignBits());
5626 continue;
5627 }
5628 }
5629 // Unknown type. Conservatively assume no bits match sign bit.
5630 return 1;
5631 }
5632 return Tmp;
5633 }
5634 }
5635 break;
5636 }
5637
5638 break;
5639 }
5642 case ISD::ATOMIC_SWAP:
5654 case ISD::ATOMIC_LOAD: {
5655 auto *AT = cast<AtomicSDNode>(Op);
5656 // If we are looking at the loaded value.
5657 if (Op.getResNo() == 0) {
5658 Tmp = AT->getMemoryVT().getScalarSizeInBits();
5659 if (Tmp == VTBits)
5660 return 1; // early-out
5661
5662 // For atomic_load, prefer to use the extension type.
5663 if (Op->getOpcode() == ISD::ATOMIC_LOAD) {
5664 switch (AT->getExtensionType()) {
5665 default:
5666 break;
5667 case ISD::SEXTLOAD:
5668 return VTBits - Tmp + 1;
5669 case ISD::ZEXTLOAD:
5670 return VTBits - Tmp;
5671 }
5672 }
5673
5674 if (TLI->getExtendForAtomicOps() == ISD::SIGN_EXTEND)
5675 return VTBits - Tmp + 1;
5676 if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND)
5677 return VTBits - Tmp;
5678 }
5679 break;
5680 }
5681 }
5682
5683 // Allow the target to implement this method for its nodes.
5684 if (Opcode >= ISD::BUILTIN_OP_END ||
5685 Opcode == ISD::INTRINSIC_WO_CHAIN ||
5686 Opcode == ISD::INTRINSIC_W_CHAIN ||
5687 Opcode == ISD::INTRINSIC_VOID) {
5688 // TODO: This can probably be removed once target code is audited. This
5689 // is here purely to reduce patch size and review complexity.
5690 if (!VT.isScalableVector()) {
5691 unsigned NumBits =
5692 TLI->ComputeNumSignBitsForTargetNode(Op, DemandedElts, *this, Depth);
5693 if (NumBits > 1)
5694 FirstAnswer = std::max(FirstAnswer, NumBits);
5695 }
5696 }
5697
5698 // Finally, if we can prove that the top bits of the result are 0's or 1's,
5699 // use this information.
5700 KnownBits Known = computeKnownBits(Op, DemandedElts, Depth);
5701 return std::max(FirstAnswer, Known.countMinSignBits());
5702}
5703
5705 unsigned Depth) const {
5706 unsigned SignBits = ComputeNumSignBits(Op, Depth);
5707 return Op.getScalarValueSizeInBits() - SignBits + 1;
5708}
5709
5711 const APInt &DemandedElts,
5712 unsigned Depth) const {
5713 unsigned SignBits = ComputeNumSignBits(Op, DemandedElts, Depth);
5714 return Op.getScalarValueSizeInBits() - SignBits + 1;
5715}
5716
5718 UndefPoisonKind Kind,
5719 unsigned Depth) const {
5720 // Early out for FREEZE.
5721 if (Op.getOpcode() == ISD::FREEZE)
5722 return true;
5723
5724 APInt DemandedElts = getDemandAllEltsMask(Op);
5725 return isGuaranteedNotToBeUndefOrPoison(Op, DemandedElts, Kind, Depth);
5726}
5727
5729 const APInt &DemandedElts,
5730 UndefPoisonKind Kind,
5731 unsigned Depth) const {
5732 unsigned Opcode = Op.getOpcode();
5733 unsigned NumElts = DemandedElts.getBitWidth();
5734
5735 // Early out for FREEZE / constant.
5736 if (Opcode == ISD::FREEZE || isIntOrFPConstant(Op))
5737 return true;
5738
5739 if (Depth >= MaxRecursionDepth)
5740 return false; // Limit search depth.
5741
5742 switch (Opcode) {
5743 case ISD::CONDCODE:
5744 case ISD::VALUETYPE:
5745 case ISD::FrameIndex:
5747 case ISD::CopyFromReg:
5748 return true;
5749
5750 case ISD::POISON:
5751 return !includesPoison(Kind);
5752
5753 case ISD::UNDEF:
5754 return !includesUndef(Kind);
5755
5756 case ISD::BITCAST: {
5757 SDValue Src = Op.getOperand(0);
5758 EVT SrcVT = Src.getValueType();
5759 EVT DstVT = Op.getValueType();
5760
5761 if (!SrcVT.isVector() || !DstVT.isVector())
5762 return isGuaranteedNotToBeUndefOrPoison(Src, Kind, Depth + 1);
5763
5764 unsigned SrcEltBits = SrcVT.getScalarSizeInBits();
5765 unsigned DstEltBits = DstVT.getScalarSizeInBits();
5766 ElementCount NumSrcElts = SrcVT.getVectorElementCount();
5767 [[maybe_unused]] ElementCount NumDstElts = DstVT.getVectorElementCount();
5768
5769 if (SrcEltBits == DstEltBits)
5770 return isGuaranteedNotToBeUndefOrPoison(Src, DemandedElts, Kind,
5771 Depth + 1);
5772
5773 if (SrcEltBits < DstEltBits) {
5774 if (DstEltBits % SrcEltBits != 0)
5775 return isGuaranteedNotToBeUndefOrPoison(Src, Kind, Depth + 1);
5776
5777 assert(NumSrcElts == NumDstElts * (DstEltBits / SrcEltBits) &&
5778 "Unexpected vector bitcast");
5779 APInt DemandedSrcElts =
5780 APIntOps::ScaleBitMask(DemandedElts, NumSrcElts.getKnownMinValue());
5781 return isGuaranteedNotToBeUndefOrPoison(Src, DemandedSrcElts, Kind,
5782 Depth + 1);
5783 }
5784
5785 if (SrcEltBits % DstEltBits != 0)
5786 return isGuaranteedNotToBeUndefOrPoison(Src, Kind, Depth + 1);
5787
5788 assert(NumDstElts == NumSrcElts * (SrcEltBits / DstEltBits) &&
5789 "Unexpected vector bitcast");
5790 APInt DemandedSrcElts =
5791 APIntOps::ScaleBitMask(DemandedElts, NumSrcElts.getKnownMinValue());
5792 return isGuaranteedNotToBeUndefOrPoison(Src, DemandedSrcElts, Kind,
5793 Depth + 1);
5794 }
5795
5796 case ISD::BUILD_VECTOR:
5797 // NOTE: BUILD_VECTOR has implicit truncation of wider scalar elements -
5798 // this shouldn't affect the result.
5799 for (unsigned i = 0, e = Op.getNumOperands(); i < e; ++i) {
5800 if (!DemandedElts[i])
5801 continue;
5802 if (!isGuaranteedNotToBeUndefOrPoison(Op.getOperand(i), Kind, Depth + 1))
5803 return false;
5804 }
5805 return true;
5806
5807 case ISD::CONCAT_VECTORS: {
5808 EVT VT = Op.getValueType();
5809 if (!VT.isFixedLengthVector())
5810 break;
5811
5812 EVT SubVT = Op.getOperand(0).getValueType();
5813 unsigned NumSubElts = SubVT.getVectorNumElements();
5814 for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) {
5815 APInt DemandedSubElts =
5816 DemandedElts.extractBits(NumSubElts, I * NumSubElts);
5817 if (!!DemandedSubElts &&
5818 !isGuaranteedNotToBeUndefOrPoison(Op.getOperand(I), DemandedSubElts,
5819 Kind, Depth + 1))
5820 return false;
5821 }
5822 return true;
5823 }
5824
5826 SDValue Src = Op.getOperand(0);
5827 if (Src.getValueType().isScalableVector())
5828 break;
5829 uint64_t Idx = Op.getConstantOperandVal(1);
5830 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
5831 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
5832 return isGuaranteedNotToBeUndefOrPoison(Src, DemandedSrcElts, Kind,
5833 Depth + 1);
5834 }
5835
5836 case ISD::INSERT_SUBVECTOR: {
5837 if (Op.getValueType().isScalableVector())
5838 break;
5839 SDValue Src = Op.getOperand(0);
5840 SDValue Sub = Op.getOperand(1);
5841 uint64_t Idx = Op.getConstantOperandVal(2);
5842 unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
5843 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
5844 APInt DemandedSrcElts = DemandedElts;
5845 DemandedSrcElts.clearBits(Idx, Idx + NumSubElts);
5846
5847 if (!!DemandedSubElts && !isGuaranteedNotToBeUndefOrPoison(
5848 Sub, DemandedSubElts, Kind, Depth + 1))
5849 return false;
5850 if (!!DemandedSrcElts && !isGuaranteedNotToBeUndefOrPoison(
5851 Src, DemandedSrcElts, Kind, Depth + 1))
5852 return false;
5853 return true;
5854 }
5855
5857 SDValue Src = Op.getOperand(0);
5858 auto *IndexC = dyn_cast<ConstantSDNode>(Op.getOperand(1));
5859 EVT SrcVT = Src.getValueType();
5860 if (SrcVT.isFixedLengthVector() && IndexC &&
5861 IndexC->getAPIntValue().ult(SrcVT.getVectorNumElements())) {
5862 APInt DemandedSrcElts = APInt::getOneBitSet(SrcVT.getVectorNumElements(),
5863 IndexC->getZExtValue());
5864 return isGuaranteedNotToBeUndefOrPoison(Src, DemandedSrcElts, Kind,
5865 Depth + 1);
5866 }
5867 break;
5868 }
5869
5871 SDValue InVec = Op.getOperand(0);
5872 SDValue InVal = Op.getOperand(1);
5873 SDValue EltNo = Op.getOperand(2);
5874 EVT VT = InVec.getValueType();
5875 auto *IndexC = dyn_cast<ConstantSDNode>(EltNo);
5876 if (IndexC && VT.isFixedLengthVector() &&
5877 IndexC->getAPIntValue().ult(VT.getVectorNumElements())) {
5878 if (DemandedElts[IndexC->getZExtValue()] &&
5879 !isGuaranteedNotToBeUndefOrPoison(InVal, Kind, Depth + 1))
5880 return false;
5881 APInt InVecDemandedElts = DemandedElts;
5882 InVecDemandedElts.clearBit(IndexC->getZExtValue());
5883 if (!!InVecDemandedElts &&
5885 peekThroughInsertVectorElt(InVec, InVecDemandedElts),
5886 InVecDemandedElts, Kind, Depth + 1))
5887 return false;
5888 return true;
5889 }
5890 break;
5891 }
5892
5894 // Check upper (known poison) elements.
5895 if (DemandedElts.ugt(1) && includesPoison(Kind))
5896 return false;
5897 // Check element zero.
5898 if (DemandedElts[0] &&
5899 !isGuaranteedNotToBeUndefOrPoison(Op.getOperand(0), Kind, Depth + 1))
5900 return false;
5901 return true;
5902
5903 case ISD::SPLAT_VECTOR:
5904 return isGuaranteedNotToBeUndefOrPoison(Op.getOperand(0), Kind, Depth + 1);
5905
5906 case ISD::SELECT: {
5907 return !canCreateUndefOrPoison(Op, DemandedElts, Kind,
5908 /*ConsiderFlags*/ true, Depth) &&
5909 isGuaranteedNotToBeUndefOrPoison(Op.getOperand(0), Kind,
5910 Depth + 1) &&
5911 isGuaranteedNotToBeUndefOrPoison(Op.getOperand(1), DemandedElts,
5912 Kind, Depth + 1) &&
5913 isGuaranteedNotToBeUndefOrPoison(Op.getOperand(2), DemandedElts,
5914 Kind, Depth + 1);
5915 }
5916
5917 case ISD::VECTOR_SHUFFLE: {
5918 APInt DemandedLHS, DemandedRHS;
5919 auto *SVN = cast<ShuffleVectorSDNode>(Op);
5920 if (!getShuffleDemandedElts(NumElts, SVN->getMask(), DemandedElts,
5921 DemandedLHS, DemandedRHS,
5922 /*AllowUndefElts=*/false))
5923 return false;
5924 if (!DemandedLHS.isZero() &&
5925 !isGuaranteedNotToBeUndefOrPoison(Op.getOperand(0), DemandedLHS, Kind,
5926 Depth + 1))
5927 return false;
5928 if (!DemandedRHS.isZero() &&
5929 !isGuaranteedNotToBeUndefOrPoison(Op.getOperand(1), DemandedRHS, Kind,
5930 Depth + 1))
5931 return false;
5932 return true;
5933 }
5934
5935 case ISD::SHL:
5936 case ISD::SRL:
5937 case ISD::SRA:
5938 // Shift amount operand is checked by canCreateUndefOrPoison. So it is
5939 // enough to check operand 0 if Op can't create undef/poison.
5940 return !canCreateUndefOrPoison(Op, DemandedElts, Kind,
5941 /*ConsiderFlags*/ true, Depth) &&
5942 isGuaranteedNotToBeUndefOrPoison(Op.getOperand(0), DemandedElts,
5943 Kind, Depth + 1);
5944
5945 case ISD::BSWAP:
5946 case ISD::CTPOP:
5947 case ISD::BITREVERSE:
5948 case ISD::AND:
5949 case ISD::OR:
5950 case ISD::XOR:
5951 case ISD::ADD:
5952 case ISD::SUB:
5953 case ISD::MUL:
5954 case ISD::SADDSAT:
5955 case ISD::UADDSAT:
5956 case ISD::SSUBSAT:
5957 case ISD::USUBSAT:
5958 case ISD::SSHLSAT:
5959 case ISD::USHLSAT:
5960 case ISD::SMIN:
5961 case ISD::SMAX:
5962 case ISD::UMIN:
5963 case ISD::UMAX:
5964 case ISD::ZERO_EXTEND:
5965 case ISD::SIGN_EXTEND:
5966 case ISD::ANY_EXTEND:
5967 case ISD::TRUNCATE:
5968 case ISD::VSELECT: {
5969 // If Op can't create undef/poison and none of its operands are undef/poison
5970 // then Op is never undef/poison. A difference from the more common check
5971 // below, outside the switch, is that we handle elementwise operations for
5972 // which the DemandedElts mask is valid for all operands here.
5973 return !canCreateUndefOrPoison(Op, DemandedElts, Kind,
5974 /*ConsiderFlags*/ true, Depth) &&
5975 all_of(Op->ops(), [&](SDValue V) {
5976 return isGuaranteedNotToBeUndefOrPoison(V, DemandedElts, Kind,
5977 Depth + 1);
5978 });
5979 }
5980
5981 case ISD::LOAD: {
5982 // If we're loading an unindexed constant pool, check if the constant
5983 // contains poison/undef - skip ANYEXT loads.
5984 // TODO: type size mismatch handling.
5985 auto *LD = cast<LoadSDNode>(Op);
5986 if (ISD::isUNINDEXEDLoad(LD) && !ISD::isEXTLoad(LD)) {
5987 if (const Constant *Cst = TLI->getTargetConstantFromLoad(LD)) {
5988 EVT VT = Op.getValueType();
5989 Type *CstTy = Cst->getType();
5990
5991 auto IsSafe = [Kind](const Constant *C) -> bool {
5992 // TODO: expose isGuaranteedNotToBeUndefOrPoison(UndefPoisonKind)
5993 if (includesPoison(Kind) && includesUndef(Kind))
5994 return ::isGuaranteedNotToBeUndefOrPoison(C);
5995 if (includesPoison(Kind))
5996 return ::isGuaranteedNotToBePoison(C);
5997 assert(includesUndef(Kind) && "UndefOnly expected");
5998 return ::isGuaranteedNotToBeUndef(C);
5999 };
6000
6001 // If Cst matches VT vector dimensions, then check per-element.
6002 if (CstTy->isVectorTy() && VT.isFixedLengthVector() &&
6003 VT.getSizeInBits() == CstTy->getPrimitiveSizeInBits() &&
6004 VT.getScalarSizeInBits() == CstTy->getScalarSizeInBits()) {
6005 for (unsigned I = 0; I != NumElts; ++I) {
6006 if (!DemandedElts[I])
6007 continue;
6008 if (Constant *Elt = Cst->getAggregateElement(I)) {
6009 if (IsSafe(Elt))
6010 continue;
6011 }
6012 return false;
6013 }
6014 } else {
6015 return IsSafe(Cst);
6016 }
6017 }
6018 }
6019 break;
6020 }
6021
6022 // TODO: Search for noundef attributes from library functions.
6023
6024 // TODO: Pointers dereferenced by ISD::LOAD/STORE ops are noundef.
6025
6026 default:
6027 // Allow the target to implement this method for its nodes.
6028 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
6029 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID)
6030 return TLI->isGuaranteedNotToBeUndefOrPoisonForTargetNode(
6031 Op, DemandedElts, *this, Kind, Depth);
6032 break;
6033 }
6034
6035 // If Op can't create undef/poison and none of its operands are undef/poison
6036 // then Op is never undef/poison.
6037 // NOTE: TargetNodes can handle this in themselves in
6038 // isGuaranteedNotToBeUndefOrPoisonForTargetNode or let
6039 // TargetLowering::isGuaranteedNotToBeUndefOrPoisonForTargetNode handle it.
6040 return !canCreateUndefOrPoison(Op, Kind, /*ConsiderFlags*/ true, Depth) &&
6041 all_of(Op->ops(), [&](SDValue V) {
6042 return isGuaranteedNotToBeUndefOrPoison(V, Kind, Depth + 1);
6043 });
6044}
6045
6047 bool ConsiderFlags,
6048 unsigned Depth) const {
6049 APInt DemandedElts = getDemandAllEltsMask(Op);
6050 return canCreateUndefOrPoison(Op, DemandedElts, Kind, ConsiderFlags, Depth);
6051}
6052
6054 UndefPoisonKind Kind,
6055 bool ConsiderFlags,
6056 unsigned Depth) const {
6057 if (ConsiderFlags && includesPoison(Kind) && Op->hasPoisonGeneratingFlags())
6058 return true;
6059
6060 unsigned Opcode = Op.getOpcode();
6061 switch (Opcode) {
6062 case ISD::AssertSext:
6063 case ISD::AssertZext:
6064 case ISD::AssertAlign:
6066 // Assertion nodes can create poison if the assertion fails.
6067 return includesPoison(Kind);
6068
6069 case ISD::FREEZE:
6073 case ISD::SADDSAT:
6074 case ISD::UADDSAT:
6075 case ISD::SSUBSAT:
6076 case ISD::USUBSAT:
6077 case ISD::MULHU:
6078 case ISD::MULHS:
6079 case ISD::AVGFLOORS:
6080 case ISD::AVGFLOORU:
6081 case ISD::AVGCEILS:
6082 case ISD::AVGCEILU:
6083 case ISD::AVGSUBFLOORS:
6084 case ISD::AVGSUBFLOORU:
6085 case ISD::ABDU:
6086 case ISD::ABDS:
6087 case ISD::SMIN:
6088 case ISD::SMAX:
6089 case ISD::SCMP:
6090 case ISD::UMIN:
6091 case ISD::UMAX:
6092 case ISD::UCMP:
6093 case ISD::AND:
6094 case ISD::XOR:
6095 case ISD::ROTL:
6096 case ISD::ROTR:
6097 case ISD::FSHL:
6098 case ISD::FSHR:
6099 case ISD::BSWAP:
6100 case ISD::CTTZ:
6101 case ISD::CTLZ:
6102 case ISD::CTLS:
6103 case ISD::CTPOP:
6104 case ISD::BITREVERSE:
6105 case ISD::PARITY:
6106 case ISD::SIGN_EXTEND:
6107 case ISD::TRUNCATE:
6111 case ISD::BITCAST:
6112 case ISD::BUILD_VECTOR:
6113 case ISD::BUILD_PAIR:
6114 case ISD::SPLAT_VECTOR:
6115 case ISD::FABS:
6116 case ISD::FCEIL:
6117 case ISD::FFLOOR:
6118 case ISD::FTRUNC:
6119 case ISD::FRINT:
6120 case ISD::FNEARBYINT:
6121 case ISD::FROUND:
6122 case ISD::FROUNDEVEN:
6123 return false;
6124
6125 case ISD::ABS:
6126 // ISD::ABS defines abs(INT_MIN) -> INT_MIN and never generates poison.
6127 // Different to Intrinsic::abs.
6128 return false;
6130 // ABS_MIN_POISON may produce poison if the input is INT_MIN.
6131 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1) <= 1;
6132
6133 case ISD::ADDC:
6134 case ISD::SUBC:
6135 case ISD::ADDE:
6136 case ISD::SUBE:
6137 case ISD::SADDO:
6138 case ISD::SSUBO:
6139 case ISD::SMULO:
6140 case ISD::SADDO_CARRY:
6141 case ISD::SSUBO_CARRY:
6142 case ISD::UADDO:
6143 case ISD::USUBO:
6144 case ISD::UMULO:
6145 case ISD::UADDO_CARRY:
6146 case ISD::USUBO_CARRY:
6147 // No poison on result or overflow flags.
6148 return false;
6149
6150 case ISD::SELECT_CC:
6151 case ISD::SETCC: {
6152 // Integer setcc cannot create undef or poison.
6153 if (Op.getOperand(0).getValueType().isInteger())
6154 return false;
6155
6156 // FP compares are more complicated. They can create poison for nan/infinity
6157 // based on options and flags. The options and flags also cause special
6158 // nonan condition codes to be used. Those condition codes may be preserved
6159 // even if the nonan flag is dropped somewhere.
6160 unsigned CCOp = Opcode == ISD::SETCC ? 2 : 4;
6161 ISD::CondCode CCCode = Op.getOperandCondCode(CCOp);
6162 return (unsigned)CCCode & 0x10U;
6163 }
6164
6165 case ISD::OR:
6166 case ISD::ZERO_EXTEND:
6167 case ISD::SELECT:
6168 case ISD::VSELECT:
6169 case ISD::ADD:
6170 case ISD::SUB:
6171 case ISD::MUL:
6172 case ISD::FNEG:
6173 case ISD::FADD:
6174 case ISD::FSUB:
6175 case ISD::FMUL:
6176 case ISD::FDIV:
6177 case ISD::FREM:
6178 case ISD::FCOPYSIGN:
6179 case ISD::FMA:
6180 case ISD::FMAD:
6181 case ISD::FMULADD:
6182 case ISD::FP_EXTEND:
6183 case ISD::FMINNUM:
6184 case ISD::FMAXNUM:
6185 case ISD::FMINNUM_IEEE:
6186 case ISD::FMAXNUM_IEEE:
6187 case ISD::FMINIMUM:
6188 case ISD::FMAXIMUM:
6189 case ISD::FMINIMUMNUM:
6190 case ISD::FMAXIMUMNUM:
6196 // No poison except from flags (which is handled above)
6197 return false;
6198
6199 case ISD::SHL:
6200 case ISD::SRL:
6201 case ISD::SRA:
6202 // If the max shift amount isn't in range, then the shift can
6203 // create poison.
6204 return includesPoison(Kind) &&
6205 !getValidMaximumShiftAmount(Op, DemandedElts, Depth + 1);
6206
6209 // If the amount is zero then the result will be poison.
6210 // TODO: Add isKnownNeverZero DemandedElts handling.
6211 return includesPoison(Kind) &&
6212 !isKnownNeverZero(Op.getOperand(0), Depth + 1);
6213
6215 // Check if we demand any upper (poison) elements.
6216 return includesPoison(Kind) && DemandedElts.ugt(1);
6217
6220 // Ensure that the element index is in bounds.
6221 if (includesPoison(Kind)) {
6222 EVT VecVT = Op.getOperand(0).getValueType();
6223 SDValue Idx = Op.getOperand(Opcode == ISD::INSERT_VECTOR_ELT ? 2 : 1);
6224 KnownBits KnownIdx = computeKnownBits(Idx, Depth + 1);
6225 return KnownIdx.getMaxValue().uge(VecVT.getVectorMinNumElements());
6226 }
6227 return false;
6228 }
6229
6230 case ISD::VECTOR_SHUFFLE: {
6231 // Check for any demanded shuffle element that is undef.
6232 auto *SVN = cast<ShuffleVectorSDNode>(Op);
6233 for (auto [Idx, Elt] : enumerate(SVN->getMask()))
6234 if (Elt < 0 && DemandedElts[Idx])
6235 return true;
6236 return false;
6237 }
6238
6240 return false;
6241
6242 default:
6243 // Allow the target to implement this method for its nodes.
6244 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
6245 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID)
6246 return TLI->canCreateUndefOrPoisonForTargetNode(
6247 Op, DemandedElts, *this, Kind, ConsiderFlags, Depth);
6248 break;
6249 }
6250
6251 // Be conservative and return true.
6252 return true;
6253}
6254
6255bool SelectionDAG::isADDLike(SDValue Op, bool NoWrap) const {
6256 unsigned Opcode = Op.getOpcode();
6257 if (Opcode == ISD::OR)
6258 return Op->getFlags().hasDisjoint() ||
6259 haveNoCommonBitsSet(Op.getOperand(0), Op.getOperand(1));
6260 if (Opcode == ISD::XOR)
6261 return !NoWrap && isMinSignedConstant(Op.getOperand(1));
6262 return false;
6263}
6264
6266 return Op.getNumOperands() == 2 && isa<ConstantSDNode>(Op.getOperand(1)) &&
6267 (Op.isAnyAdd() || isADDLike(Op));
6268}
6269
6271 FPClassTest InterestedClasses,
6272 unsigned Depth) const {
6273 APInt DemandedElts = getDemandAllEltsMask(Op);
6274 return computeKnownFPClass(Op, DemandedElts, InterestedClasses, Depth);
6275}
6276
6278 const APInt &DemandedElts,
6279 FPClassTest InterestedClasses,
6280 unsigned Depth) const {
6282
6283 if (const auto *CFP = dyn_cast<ConstantFPSDNode>(Op))
6284 return KnownFPClass(CFP->getValueAPF());
6285
6286 if (Depth >= MaxRecursionDepth)
6287 return Known;
6288
6289 if (Op.getOpcode() == ISD::UNDEF)
6290 return Known;
6291
6292 EVT VT = Op.getValueType();
6293 assert(VT.isFloatingPoint() && "Computing KnownFPClass on non-FP op!");
6294 assert((!VT.isFixedLengthVector() ||
6295 DemandedElts.getBitWidth() == VT.getVectorNumElements()) &&
6296 "Unexpected vector size");
6297
6298 if (!DemandedElts)
6299 return Known;
6300
6301 unsigned Opcode = Op.getOpcode();
6302 switch (Opcode) {
6303 case ISD::POISON: {
6305 break;
6306 }
6307 case ISD::FNEG: {
6308 Known = computeKnownFPClass(Op.getOperand(0), DemandedElts,
6309 InterestedClasses, Depth + 1);
6310 Known.fneg();
6311 break;
6312 }
6313 case ISD::BUILD_VECTOR: {
6314 assert(!VT.isScalableVector());
6315 bool First = true;
6316 for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) {
6317 if (!DemandedElts[I])
6318 continue;
6319
6320 if (First) {
6321 Known =
6322 computeKnownFPClass(Op.getOperand(I), InterestedClasses, Depth + 1);
6323 First = false;
6324 } else {
6325 Known |=
6326 computeKnownFPClass(Op.getOperand(I), InterestedClasses, Depth + 1);
6327 }
6328
6329 if (Known.isUnknown())
6330 break;
6331 }
6332 break;
6333 }
6335 SDValue Src = Op.getOperand(0);
6336 auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6337 EVT SrcVT = Src.getValueType();
6338 if (SrcVT.isFixedLengthVector() && CIdx) {
6339 if (CIdx->getAPIntValue().ult(SrcVT.getVectorNumElements())) {
6340 APInt DemandedSrcElts = APInt::getOneBitSet(
6341 SrcVT.getVectorNumElements(), CIdx->getZExtValue());
6342 Known = computeKnownFPClass(Src, DemandedSrcElts, InterestedClasses,
6343 Depth + 1);
6344 } else {
6345 // Out of bounds index is poison.
6347 }
6348 } else {
6349 Known = computeKnownFPClass(Src, InterestedClasses, Depth + 1);
6350 }
6351 break;
6352 }
6353 case ISD::SPLAT_VECTOR: {
6354 Known = computeKnownFPClass(Op.getOperand(0), InterestedClasses, Depth + 1);
6355 break;
6356 }
6357 case ISD::BITCAST: {
6358 // FIXME: It should not be necessary to check for an elementwise bitcast.
6359 // If a bitcast is not elementwise between vector / scalar types,
6360 // computeKnownBits already splices the known bits of the source elements
6361 // appropriately so as to line up with the bits of the result's demanded
6362 // elements.
6363 EVT SrcVT = Op.getOperand(0).getValueType();
6364 if (VT.isScalableVector() || SrcVT.isScalableVector())
6365 break;
6366 unsigned VTNumElts = VT.isVector() ? VT.getVectorNumElements() : 1;
6367 unsigned SrcVTNumElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1;
6368 if (VTNumElts != SrcVTNumElts)
6369 break;
6370
6371 KnownBits Bits = computeKnownBits(Op, DemandedElts, Depth + 1);
6373 break;
6374 }
6375 case ISD::FABS: {
6376 Known = computeKnownFPClass(Op.getOperand(0), DemandedElts,
6377 InterestedClasses, Depth + 1);
6378 Known.fabs();
6379 break;
6380 }
6381 case ISD::FCOPYSIGN: {
6382 Known = computeKnownFPClass(Op.getOperand(0), DemandedElts,
6383 InterestedClasses, Depth + 1);
6384 KnownFPClass KnownSign = computeKnownFPClass(Op.getOperand(1), DemandedElts,
6385 InterestedClasses, Depth + 1);
6386 Known.copysign(KnownSign);
6387 break;
6388 }
6389 case ISD::AssertNoFPClass: {
6390 Known = computeKnownFPClass(Op.getOperand(0), DemandedElts,
6391 InterestedClasses, Depth + 1);
6392 FPClassTest AssertedClasses =
6393 static_cast<FPClassTest>(Op->getConstantOperandVal(1));
6394 Known.setKnownFPClasses(Known.getKnownFPClasses() & ~AssertedClasses);
6395 break;
6396 }
6398 SDValue Src = Op.getOperand(0);
6399 EVT SrcVT = Src.getValueType();
6400 if (SrcVT.isFixedLengthVector()) {
6401 unsigned Idx = Op.getConstantOperandVal(1);
6402 unsigned NumSrcElts = SrcVT.getVectorNumElements();
6403
6404 APInt DemandedSrcElts = DemandedElts.zextOrTrunc(NumSrcElts).shl(Idx);
6405 Known = computeKnownFPClass(Src, DemandedSrcElts, InterestedClasses,
6406 Depth + 1);
6407 } else {
6408 Known = computeKnownFPClass(Src, InterestedClasses, Depth + 1);
6409 }
6410 break;
6411 }
6412 case ISD::INSERT_SUBVECTOR: {
6413 SDValue BaseVector = Op.getOperand(0);
6414 SDValue SubVector = Op.getOperand(1);
6415 EVT BaseVT = BaseVector.getValueType();
6416 if (BaseVT.isFixedLengthVector()) {
6417 unsigned Idx = Op.getConstantOperandVal(2);
6418 unsigned NumBaseElts = BaseVT.getVectorNumElements();
6419 unsigned NumSubElts = SubVector.getValueType().getVectorNumElements();
6420
6421 APInt DemandedMask =
6422 APInt::getBitsSet(NumBaseElts, Idx, Idx + NumSubElts);
6423 APInt DemandedSrcElts = DemandedElts & ~DemandedMask;
6424 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
6425
6426 if (!DemandedSrcElts.isZero())
6427 Known = computeKnownFPClass(BaseVector, DemandedSrcElts,
6428 InterestedClasses, Depth + 1);
6429 if (!DemandedSubElts.isZero()) {
6431 SubVector, DemandedSubElts, InterestedClasses, Depth + 1);
6432 Known = DemandedSrcElts.isZero() ? SubKnown : (Known | SubKnown);
6433 }
6434 } else {
6435 Known = computeKnownFPClass(SubVector, InterestedClasses, Depth + 1);
6436 if (!Known.isUnknown())
6437 Known |= computeKnownFPClass(BaseVector, InterestedClasses, Depth + 1);
6438 }
6439 break;
6440 }
6441 case ISD::SELECT:
6442 case ISD::VSELECT: {
6443 // TODO: Add adjustKnownFPClassForSelectArm clamp recognition as in
6444 // IR-level ValueTracking.
6445 KnownFPClass KnownFalseClass = computeKnownFPClass(
6446 Op.getOperand(2), DemandedElts, InterestedClasses, Depth + 1);
6447 if (KnownFalseClass.isUnknown())
6448 break;
6449 KnownFPClass KnownTrueClass = computeKnownFPClass(
6450 Op.getOperand(1), DemandedElts, InterestedClasses, Depth + 1);
6451 Known = KnownTrueClass.intersectWith(KnownFalseClass);
6452 break;
6453 }
6454 default:
6455 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
6456 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID) {
6457 TLI->computeKnownFPClassForTargetNode(Op, Known, DemandedElts, *this,
6458 Depth);
6459 }
6460 break;
6461 }
6462
6463 return Known;
6464}
6465
6467 unsigned Depth) const {
6468 APInt DemandedElts = getDemandAllEltsMask(Op);
6469 return isKnownNeverNaN(Op, DemandedElts, SNaN, Depth);
6470}
6471
6473 bool SNaN, unsigned Depth) const {
6474 assert(!DemandedElts.isZero() && "No demanded elements");
6475
6476 // If we're told that NaNs won't happen, assume they won't.
6477 if (Op->getFlags().hasNoNaNs())
6478 return true;
6479
6480 if (Depth >= MaxRecursionDepth)
6481 return false; // Limit search depth.
6482
6483 unsigned Opcode = Op.getOpcode();
6484 switch (Opcode) {
6485 case ISD::FADD:
6486 case ISD::FSUB:
6487 case ISD::FMUL:
6488 case ISD::FDIV:
6489 case ISD::FREM:
6490 case ISD::FSIN:
6491 case ISD::FCOS:
6492 case ISD::FTAN:
6493 case ISD::FASIN:
6494 case ISD::FACOS:
6495 case ISD::FATAN:
6496 case ISD::FATAN2:
6497 case ISD::FSINH:
6498 case ISD::FCOSH:
6499 case ISD::FTANH:
6500 case ISD::FMA:
6501 case ISD::FMULADD:
6502 case ISD::FMAD: {
6503 if (SNaN)
6504 return true;
6505 // TODO: Need isKnownNeverInfinity
6506 return false;
6507 }
6508 case ISD::FCANONICALIZE:
6509 case ISD::FEXP:
6510 case ISD::FEXP2:
6511 case ISD::FEXP10:
6512 case ISD::FTRUNC:
6513 case ISD::FFLOOR:
6514 case ISD::FCEIL:
6515 case ISD::FROUND:
6516 case ISD::FROUNDEVEN:
6517 case ISD::LROUND:
6518 case ISD::LLROUND:
6519 case ISD::FRINT:
6520 case ISD::LRINT:
6521 case ISD::LLRINT:
6522 case ISD::FNEARBYINT:
6523 case ISD::FLDEXP: {
6524 if (SNaN)
6525 return true;
6526 return isKnownNeverNaN(Op.getOperand(0), DemandedElts, SNaN, Depth + 1);
6527 }
6528 case ISD::FABS:
6529 case ISD::FNEG:
6530 case ISD::FCOPYSIGN: {
6531 return isKnownNeverNaN(Op.getOperand(0), DemandedElts, SNaN, Depth + 1);
6532 }
6533 case ISD::SELECT:
6534 return isKnownNeverNaN(Op.getOperand(1), DemandedElts, SNaN, Depth + 1) &&
6535 isKnownNeverNaN(Op.getOperand(2), DemandedElts, SNaN, Depth + 1);
6536 case ISD::FP_EXTEND:
6537 case ISD::FP_ROUND: {
6538 if (SNaN)
6539 return true;
6540 return isKnownNeverNaN(Op.getOperand(0), DemandedElts, SNaN, Depth + 1);
6541 }
6542 case ISD::SINT_TO_FP:
6543 case ISD::UINT_TO_FP:
6544 return true;
6545 case ISD::FSQRT: // Need is known positive
6546 case ISD::FLOG:
6547 case ISD::FLOG2:
6548 case ISD::FLOG10:
6549 case ISD::FPOWI:
6550 case ISD::FPOW: {
6551 if (SNaN)
6552 return true;
6553 // TODO: Refine on operand
6554 return false;
6555 }
6556 case ISD::FMINNUM:
6557 case ISD::FMAXNUM:
6558 case ISD::FMINIMUMNUM:
6559 case ISD::FMAXIMUMNUM: {
6560 // Only one needs to be known not-nan, since it will be returned if the
6561 // other ends up being one.
6562 return isKnownNeverNaN(Op.getOperand(0), DemandedElts, SNaN, Depth + 1) ||
6563 isKnownNeverNaN(Op.getOperand(1), DemandedElts, SNaN, Depth + 1);
6564 }
6565 case ISD::FMINNUM_IEEE:
6566 case ISD::FMAXNUM_IEEE: {
6567 if (SNaN)
6568 return true;
6569 // This can return a NaN if either operand is an sNaN, or if both operands
6570 // are NaN.
6571 return (isKnownNeverNaN(Op.getOperand(0), DemandedElts, false, Depth + 1) &&
6572 isKnownNeverSNaN(Op.getOperand(1), DemandedElts, Depth + 1)) ||
6573 (isKnownNeverNaN(Op.getOperand(1), DemandedElts, false, Depth + 1) &&
6574 isKnownNeverSNaN(Op.getOperand(0), DemandedElts, Depth + 1));
6575 }
6576 case ISD::FMINIMUM:
6577 case ISD::FMAXIMUM: {
6578 // TODO: Does this quiet or return the origina NaN as-is?
6579 return isKnownNeverNaN(Op.getOperand(0), DemandedElts, SNaN, Depth + 1) &&
6580 isKnownNeverNaN(Op.getOperand(1), DemandedElts, SNaN, Depth + 1);
6581 }
6583 SDValue Src = Op.getOperand(0);
6584 auto *Idx = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6585 EVT SrcVT = Src.getValueType();
6586 if (SrcVT.isFixedLengthVector() && Idx &&
6587 Idx->getAPIntValue().ult(SrcVT.getVectorNumElements())) {
6588 APInt DemandedSrcElts = APInt::getOneBitSet(SrcVT.getVectorNumElements(),
6589 Idx->getZExtValue());
6590 return isKnownNeverNaN(Src, DemandedSrcElts, SNaN, Depth + 1);
6591 }
6592 return isKnownNeverNaN(Src, SNaN, Depth + 1);
6593 }
6595 SDValue Src = Op.getOperand(0);
6596 if (Src.getValueType().isFixedLengthVector()) {
6597 unsigned Idx = Op.getConstantOperandVal(1);
6598 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
6599 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
6600 return isKnownNeverNaN(Src, DemandedSrcElts, SNaN, Depth + 1);
6601 }
6602 return isKnownNeverNaN(Src, SNaN, Depth + 1);
6603 }
6604 case ISD::INSERT_SUBVECTOR: {
6605 SDValue BaseVector = Op.getOperand(0);
6606 SDValue SubVector = Op.getOperand(1);
6607 EVT BaseVectorVT = BaseVector.getValueType();
6608 if (BaseVectorVT.isFixedLengthVector()) {
6609 unsigned Idx = Op.getConstantOperandVal(2);
6610 unsigned NumBaseElts = BaseVectorVT.getVectorNumElements();
6611 unsigned NumSubElts = SubVector.getValueType().getVectorNumElements();
6612
6613 // Clear/Extract the bits at the position where the subvector will be
6614 // inserted.
6615 APInt DemandedMask =
6616 APInt::getBitsSet(NumBaseElts, Idx, Idx + NumSubElts);
6617 APInt DemandedSrcElts = DemandedElts & ~DemandedMask;
6618 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
6619
6620 bool NeverNaN = true;
6621 if (!DemandedSrcElts.isZero())
6622 NeverNaN &=
6623 isKnownNeverNaN(BaseVector, DemandedSrcElts, SNaN, Depth + 1);
6624 if (NeverNaN && !DemandedSubElts.isZero())
6625 NeverNaN &=
6626 isKnownNeverNaN(SubVector, DemandedSubElts, SNaN, Depth + 1);
6627 return NeverNaN;
6628 }
6629 return isKnownNeverNaN(BaseVector, SNaN, Depth + 1) &&
6630 isKnownNeverNaN(SubVector, SNaN, Depth + 1);
6631 }
6632 case ISD::BUILD_VECTOR: {
6633 unsigned NumElts = Op.getNumOperands();
6634 for (unsigned I = 0; I != NumElts; ++I)
6635 if (DemandedElts[I] &&
6636 !isKnownNeverNaN(Op.getOperand(I), SNaN, Depth + 1))
6637 return false;
6638 return true;
6639 }
6640 case ISD::SPLAT_VECTOR:
6641 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
6642 case ISD::AssertNoFPClass: {
6643 FPClassTest NoFPClass =
6644 static_cast<FPClassTest>(Op.getConstantOperandVal(1));
6645 if ((NoFPClass & fcNan) == fcNan)
6646 return true;
6647 if (SNaN && (NoFPClass & fcSNan) == fcSNan)
6648 return true;
6649 return isKnownNeverNaN(Op.getOperand(0), DemandedElts, SNaN, Depth + 1);
6650 }
6651 default:
6652 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
6653 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID) {
6654 return TLI->isKnownNeverNaNForTargetNode(Op, DemandedElts, *this, SNaN,
6655 Depth);
6656 }
6657 break;
6658 }
6659
6660 FPClassTest NanMask = SNaN ? fcSNan : fcNan;
6661 KnownFPClass Known = computeKnownFPClass(Op, DemandedElts, NanMask, Depth);
6662 return Known.isKnownNever(NanMask);
6663}
6664
6666 APInt DemandedElts = getDemandAllEltsMask(Op);
6667 return isKnownNeverLogicalZero(Op, DemandedElts, Depth);
6668}
6669
6671 const APInt &DemandedElts,
6672 unsigned Depth) const {
6673 assert(!DemandedElts.isZero() && "No demanded elements");
6674 EVT VT = Op.getValueType();
6676 computeKnownFPClass(Op, DemandedElts, fcZero | fcSubnormal, Depth);
6677 return Known.isKnownNeverLogicalZero(getDenormalMode(VT));
6678}
6679
6681 APInt DemandedElts = getDemandAllEltsMask(Op);
6682 return isKnownNeverZero(Op, DemandedElts, Depth);
6683}
6684
6686 unsigned Depth) const {
6687 if (Depth >= MaxRecursionDepth)
6688 return false; // Limit search depth.
6689
6690 EVT OpVT = Op.getValueType();
6691 unsigned BitWidth = OpVT.getScalarSizeInBits();
6692
6693 assert(!Op.getValueType().isFloatingPoint() &&
6694 "Floating point types unsupported - use isKnownNeverLogicalZero");
6695
6696 // If the value is a constant, we can obviously see if it is a zero or not.
6697 auto IsNeverZero = [BitWidth](const ConstantSDNode *C) {
6698 APInt V = C->getAPIntValue().zextOrTrunc(BitWidth);
6699 return !V.isZero();
6700 };
6701
6702 if (ISD::matchUnaryPredicate(Op, DemandedElts, IsNeverZero,
6703 /*AllowUndefs=*/false, /*AllowTruncation=*/true))
6704 return true;
6705
6706 // TODO: Recognize more cases here. Most of the cases are also incomplete to
6707 // some degree.
6708 switch (Op.getOpcode()) {
6709 default:
6710 break;
6711
6713 SDValue InVec = Op.getOperand(0);
6714 SDValue EltNo = Op.getOperand(1);
6715 EVT VecVT = InVec.getValueType();
6716
6717 // Skip scalable vectors or implicit extensions.
6718 if (VecVT.isScalableVector() ||
6719 OpVT.getScalarSizeInBits() != VecVT.getScalarSizeInBits())
6720 break;
6721
6722 // If we know the element index, just demand that vector element, else for
6723 // an unknown element index, ignore DemandedElts and demand them all.
6724 const unsigned NumSrcElts = VecVT.getVectorNumElements();
6725 APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
6726 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
6727 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
6728 DemandedSrcElts =
6729 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
6730
6731 return isKnownNeverZero(InVec, DemandedSrcElts, Depth + 1);
6732 }
6733
6734 case ISD::OR:
6735 return isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1) ||
6736 isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6737
6738 case ISD::VSELECT:
6739 case ISD::SELECT:
6740 return isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1) &&
6741 isKnownNeverZero(Op.getOperand(2), DemandedElts, Depth + 1);
6742
6743 case ISD::SHL: {
6744 if (Op->getFlags().hasNoSignedWrap() || Op->getFlags().hasNoUnsignedWrap())
6745 return isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6746 KnownBits ValKnown =
6747 computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
6748 // 1 << X is never zero.
6749 if (ValKnown.One[0])
6750 return true;
6751 // If max shift cnt of known ones is non-zero, result is non-zero.
6752 APInt MaxCnt = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1)
6753 .getMaxValue();
6754 if (MaxCnt.ult(ValKnown.getBitWidth()) &&
6755 !ValKnown.One.shl(MaxCnt).isZero())
6756 return true;
6757 break;
6758 }
6759
6760 case ISD::VECTOR_SHUFFLE: {
6761 if (Op.getValueType().isScalableVector())
6762 return false;
6763
6764 unsigned NumElts = DemandedElts.getBitWidth();
6765
6766 // All demanded elements from LHS and RHS must be known non-zero.
6767 // Demanded elements with undef shuffle mask elements are unknown.
6768
6769 APInt DemandedLHS, DemandedRHS;
6770 auto *SVN = cast<ShuffleVectorSDNode>(Op);
6771 assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
6772 if (!getShuffleDemandedElts(NumElts, SVN->getMask(), DemandedElts,
6773 DemandedLHS, DemandedRHS))
6774 return false;
6775
6776 return (!DemandedLHS ||
6777 isKnownNeverZero(Op.getOperand(0), DemandedLHS, Depth + 1)) &&
6778 (!DemandedRHS ||
6779 isKnownNeverZero(Op.getOperand(1), DemandedRHS, Depth + 1));
6780 }
6781
6782 case ISD::UADDSAT:
6783 case ISD::UMAX:
6784 return isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1) ||
6785 isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6786
6787 case ISD::UMIN:
6788 return isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1) &&
6789 isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6790
6791 // For smin/smax: If either operand is known negative/positive
6792 // respectively we don't need the other to be known at all.
6793 case ISD::SMAX: {
6794 KnownBits Op1 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
6795 if (Op1.isStrictlyPositive())
6796 return true;
6797
6798 KnownBits Op0 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
6799 if (Op0.isStrictlyPositive())
6800 return true;
6801
6802 if (Op1.isNonZero() && Op0.isNonZero())
6803 return true;
6804
6805 return isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1) &&
6806 isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6807 }
6808 case ISD::SMIN: {
6809 KnownBits Op1 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
6810 if (Op1.isNegative())
6811 return true;
6812
6813 KnownBits Op0 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
6814 if (Op0.isNegative())
6815 return true;
6816
6817 if (Op1.isNonZero() && Op0.isNonZero())
6818 return true;
6819
6820 return isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1) &&
6821 isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6822 }
6823
6824 case ISD::ROTL:
6825 case ISD::ROTR:
6826 case ISD::BITREVERSE:
6827 case ISD::BSWAP:
6828 case ISD::CTPOP:
6829 case ISD::ABS:
6831 return isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6832
6833 case ISD::SRA:
6834 case ISD::SRL: {
6835 if (Op->getFlags().hasExact())
6836 return isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6837 KnownBits ValKnown =
6838 computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
6839 if (ValKnown.isNegative())
6840 return true;
6841 // If max shift cnt of known ones is non-zero, result is non-zero.
6842 APInt MaxCnt = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1)
6843 .getMaxValue();
6844 if (MaxCnt.ult(ValKnown.getBitWidth()) &&
6845 !ValKnown.One.lshr(MaxCnt).isZero())
6846 return true;
6847 break;
6848 }
6849 case ISD::UDIV:
6850 case ISD::SDIV:
6851 // div exact can only produce a zero if the dividend is zero.
6852 // TODO: For udiv this is also true if Op1 u<= Op0
6853 if (Op->getFlags().hasExact())
6854 return isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6855 break;
6856
6857 case ISD::ADD:
6858 if (Op->getFlags().hasNoUnsignedWrap())
6859 if (isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1) ||
6860 isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1))
6861 return true;
6862 // TODO: There are a lot more cases we can prove for add.
6863 break;
6864
6865 case ISD::SUB: {
6866 if (isNullConstant(Op.getOperand(0)))
6867 return isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1);
6868
6869 std::optional<bool> ne = KnownBits::ne(
6870 computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1),
6871 computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1));
6872 return ne && *ne;
6873 }
6874
6875 case ISD::MUL:
6876 if (Op->getFlags().hasNoSignedWrap() || Op->getFlags().hasNoUnsignedWrap())
6877 if (isKnownNeverZero(Op.getOperand(1), Depth + 1) &&
6878 isKnownNeverZero(Op.getOperand(0), Depth + 1))
6879 return true;
6880 break;
6881
6882 case ISD::ZERO_EXTEND:
6883 case ISD::SIGN_EXTEND:
6884 return isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6885 case ISD::VSCALE: {
6887 const APInt &Multiplier = Op.getConstantOperandAPInt(0);
6888 ConstantRange CR =
6889 getVScaleRange(&F, Op.getScalarValueSizeInBits()).multiply(Multiplier);
6890 if (!CR.contains(APInt(CR.getBitWidth(), 0)))
6891 return true;
6892 break;
6893 }
6894 }
6895
6896 return computeKnownBits(Op, DemandedElts, Depth).isNonZero();
6897}
6898
6901 return !C1->isNegative();
6902
6903 switch (Op.getOpcode()) {
6904 case ISD::FABS:
6905 case ISD::FEXP:
6906 case ISD::FEXP2:
6907 case ISD::FEXP10:
6908 return true;
6909 default:
6910 return false;
6911 }
6912
6913 llvm_unreachable("covered opcode switch");
6914}
6915
6916/// Return true if the standard nsz semantics may not apply for this opcode.
6917/// Opcode is assumed to take float inputs.
6918/// FIXME: Target min/max nodes (e.g. X86ISD::FMINC) aren't included.
6919static bool hasSpecialNszSemantics(unsigned Opcode) {
6920 switch (Opcode) {
6921 case ISD::FMINNUM:
6922 case ISD::FMAXNUM:
6923 case ISD::FMINNUM_IEEE:
6924 case ISD::FMAXNUM_IEEE:
6925 case ISD::FMINIMUM:
6926 case ISD::FMAXIMUM:
6927 case ISD::FMINIMUMNUM:
6928 case ISD::FMAXIMUMNUM:
6933 case ISD::PSEUDO_FMIN:
6934 case ISD::PSEUDO_FMAX:
6943 case ISD::VP_REDUCE_FMIN:
6944 case ISD::VP_REDUCE_FMAX:
6945 case ISD::VP_REDUCE_FMINIMUM:
6946 case ISD::VP_REDUCE_FMAXIMUM:
6947 return true;
6948 default:
6949 return false;
6950 }
6951}
6952
6954 assert(Use.getValueType().isFloatingPoint());
6955 const SDNode *User = Use.getUser();
6956 unsigned Opcode = User->getOpcode();
6957 if (User->getFlags().hasNoSignedZeros() && !hasSpecialNszSemantics(Opcode))
6958 return true;
6959
6960 unsigned OperandNo = Use.getOperandNo();
6961 // Check if this use is insensitive to the sign of zero
6962 switch (Opcode) {
6963 case ISD::SETCC:
6964 // Comparisons: IEEE-754 specifies +0.0 == -0.0.
6965 case ISD::FABS:
6966 // fabs always produces +0.0.
6967 return true;
6968 case ISD::FCOPYSIGN:
6969 // copysign overwrites the sign bit of the first operand.
6970 return OperandNo == 0;
6971 case ISD::FADD:
6972 case ISD::FSUB: {
6973 // Arithmetic with non-zero constants fixes the uncertainty around the
6974 // sign bit.
6975 SDValue Other = User->getOperand(1 - OperandNo);
6977 }
6978 case ISD::FP_TO_SINT:
6979 case ISD::FP_TO_UINT:
6980 // fp-to-int conversions normalize signed zeros.
6981 return true;
6982 case ISD::FMINNUM:
6983 case ISD::FMINNUM_IEEE:
6984 case ISD::FMINIMUM:
6985 case ISD::FMINIMUMNUM:
6986 case ISD::FMAXNUM:
6987 case ISD::FMAXNUM_IEEE:
6988 case ISD::FMAXIMUM:
6989 case ISD::FMAXIMUMNUM:
6990 case ISD::PSEUDO_FMIN:
6991 case ISD::PSEUDO_FMAX: {
6992 // If other value always beats zero, the zero can be ignored.
6993 bool IsMin = Opcode == ISD::FMINNUM || Opcode == ISD::FMINNUM_IEEE ||
6994 Opcode == ISD::FMINIMUM || Opcode == ISD::FMINIMUMNUM ||
6995 Opcode == ISD::PSEUDO_FMIN;
6996 FPClassTest AlwaysBeatsZero =
6998 SDValue Other = User->getOperand(1 - OperandNo);
6999 KnownFPClass Known = computeKnownFPClass(Other, ~AlwaysBeatsZero);
7000 return Known.isKnownNever(~AlwaysBeatsZero);
7001 }
7002 default:
7003 return false;
7004 }
7005}
7006
7008 assert(Op->getNumValues() == 1);
7009 // FIXME: Limit the amount of checked uses to not introduce a compile-time
7010 // regression. Ideally, this should be implemented as a demanded-bits
7011 // optimization that stems from the users.
7012 if (Op->use_size() > 2)
7013 return false;
7014 return all_of(Op->uses(),
7015 [&](const SDUse &Use) { return canIgnoreSignBitOfZero(Use); });
7016}
7017
7019 // Check the obvious case.
7020 if (A == B) return true;
7021
7022 // For negative and positive zero.
7025 if (CA->isZero() && CB->isZero()) return true;
7026
7027 // Otherwise they may not be equal.
7028 return false;
7029}
7030
7031// Only bits set in Mask must be negated, other bits may be arbitrary.
7033 if (isBitwiseNot(V, AllowUndefs))
7034 return V.getOperand(0);
7035
7036 // Handle any_extend (not (truncate X)) pattern, where Mask only sets
7037 // bits in the non-extended part.
7038 ConstantSDNode *MaskC = isConstOrConstSplat(Mask);
7039 if (!MaskC || V.getOpcode() != ISD::ANY_EXTEND)
7040 return SDValue();
7041 SDValue ExtArg = V.getOperand(0);
7042 if (ExtArg.getScalarValueSizeInBits() >=
7043 MaskC->getAPIntValue().getActiveBits() &&
7044 isBitwiseNot(ExtArg, AllowUndefs) &&
7045 ExtArg.getOperand(0).getOpcode() == ISD::TRUNCATE &&
7046 ExtArg.getOperand(0).getOperand(0).getValueType() == V.getValueType())
7047 return ExtArg.getOperand(0).getOperand(0);
7048 return SDValue();
7049}
7050
7052 // Match masked merge pattern (X & ~M) op (Y & M)
7053 // Including degenerate case (X & ~M) op M
7054 auto MatchNoCommonBitsPattern = [&](SDValue Not, SDValue Mask,
7055 SDValue Other) {
7056 if (SDValue NotOperand =
7057 getBitwiseNotOperand(Not, Mask, /* AllowUndefs */ true)) {
7058 if (NotOperand->getOpcode() == ISD::ZERO_EXTEND ||
7059 NotOperand->getOpcode() == ISD::TRUNCATE)
7060 NotOperand = NotOperand->getOperand(0);
7061
7062 if (Other == NotOperand)
7063 return true;
7064 if (Other->getOpcode() == ISD::AND)
7065 return NotOperand == Other->getOperand(0) ||
7066 NotOperand == Other->getOperand(1);
7067 }
7068 return false;
7069 };
7070
7071 if (A->getOpcode() == ISD::ZERO_EXTEND || A->getOpcode() == ISD::TRUNCATE)
7072 A = A->getOperand(0);
7073
7074 if (B->getOpcode() == ISD::ZERO_EXTEND || B->getOpcode() == ISD::TRUNCATE)
7075 B = B->getOperand(0);
7076
7077 if (A->getOpcode() == ISD::AND)
7078 return MatchNoCommonBitsPattern(A->getOperand(0), A->getOperand(1), B) ||
7079 MatchNoCommonBitsPattern(A->getOperand(1), A->getOperand(0), B);
7080 return false;
7081}
7082
7083// FIXME: unify with llvm::haveNoCommonBitsSet.
7085 assert(A.getValueType() == B.getValueType() &&
7086 "Values must have the same type");
7089 return true;
7092}
7093
7094static SDValue FoldSTEP_VECTOR(const SDLoc &DL, EVT VT, SDValue Step,
7095 SelectionDAG &DAG) {
7096 if (cast<ConstantSDNode>(Step)->isZero())
7097 return DAG.getConstant(0, DL, VT);
7098
7099 return SDValue();
7100}
7101
7104 SelectionDAG &DAG) {
7105 int NumOps = Ops.size();
7106 assert(NumOps != 0 && "Can't build an empty vector!");
7107 assert(!VT.isScalableVector() &&
7108 "BUILD_VECTOR cannot be used with scalable types");
7109 assert(VT.getVectorNumElements() == (unsigned)NumOps &&
7110 "Incorrect element count in BUILD_VECTOR!");
7111
7112 // BUILD_VECTOR of UNDEFs is UNDEF.
7113 bool AllPoison = true;
7114 if (llvm::all_of(Ops, [&AllPoison](SDValue Op) {
7115 AllPoison &= Op.getOpcode() == ISD::POISON;
7116 return Op.isUndef();
7117 }))
7118 return AllPoison ? DAG.getPOISON(VT) : DAG.getUNDEF(VT);
7119
7120 // BUILD_VECTOR of seq extract/insert from the same vector + type is Identity.
7121 SDValue IdentitySrc;
7122 bool IsIdentity = true;
7123 for (int i = 0; i != NumOps; ++i) {
7124 if (Ops[i].getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
7125 Ops[i].getOperand(0).getValueType() != VT ||
7126 (IdentitySrc && Ops[i].getOperand(0) != IdentitySrc) ||
7127 !isa<ConstantSDNode>(Ops[i].getOperand(1)) ||
7128 Ops[i].getConstantOperandAPInt(1) != i) {
7129 IsIdentity = false;
7130 break;
7131 }
7132 IdentitySrc = Ops[i].getOperand(0);
7133 }
7134 if (IsIdentity)
7135 return IdentitySrc;
7136
7137 return SDValue();
7138}
7139
7140/// Try to simplify vector concatenation to an input value, undef, or build
7141/// vector.
7144 SelectionDAG &DAG) {
7145 assert(!Ops.empty() && "Can't concatenate an empty list of vectors!");
7147 [Ops](SDValue Op) {
7148 return Ops[0].getValueType() == Op.getValueType();
7149 }) &&
7150 "Concatenation of vectors with inconsistent value types!");
7151 assert((Ops[0].getValueType().getVectorElementCount() * Ops.size()) ==
7152 VT.getVectorElementCount() &&
7153 "Incorrect element count in vector concatenation!");
7154
7155 if (Ops.size() == 1)
7156 return Ops[0];
7157
7158 // Concat of UNDEFs is UNDEF.
7159 bool AllPoison = true;
7160 if (llvm::all_of(Ops, [&AllPoison](SDValue Op) {
7161 AllPoison &= Op.getOpcode() == ISD::POISON;
7162 return Op.isUndef();
7163 }))
7164 return AllPoison ? DAG.getPOISON(VT) : DAG.getUNDEF(VT);
7165
7166 // Scan the operands and look for extract operations from a single source
7167 // that correspond to insertion at the same location via this concatenation:
7168 // concat (extract X, 0*subvec_elts), (extract X, 1*subvec_elts), ...
7169 SDValue IdentitySrc;
7170 bool IsIdentity = true;
7171 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
7172 SDValue Op = Ops[i];
7173 unsigned IdentityIndex = i * Op.getValueType().getVectorMinNumElements();
7174 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
7175 Op.getOperand(0).getValueType() != VT ||
7176 (IdentitySrc && Op.getOperand(0) != IdentitySrc) ||
7177 Op.getConstantOperandVal(1) != IdentityIndex) {
7178 IsIdentity = false;
7179 break;
7180 }
7181 assert((!IdentitySrc || IdentitySrc == Op.getOperand(0)) &&
7182 "Unexpected identity source vector for concat of extracts");
7183 IdentitySrc = Op.getOperand(0);
7184 }
7185 if (IsIdentity) {
7186 assert(IdentitySrc && "Failed to set source vector of extracts");
7187 return IdentitySrc;
7188 }
7189
7190 // The code below this point is only designed to work for fixed width
7191 // vectors, so we bail out for now.
7192 if (VT.isScalableVector())
7193 return SDValue();
7194
7195 // A CONCAT_VECTOR of scalar sources, such as UNDEF, BUILD_VECTOR and
7196 // single-element INSERT_VECTOR_ELT operands can be simplified to one big
7197 // BUILD_VECTOR.
7198 // FIXME: Add support for SCALAR_TO_VECTOR as well.
7199 EVT SVT = VT.getScalarType();
7201 for (SDValue Op : Ops) {
7202 EVT OpVT = Op.getValueType();
7203 if (Op.getOpcode() == ISD::POISON)
7204 Elts.append(OpVT.getVectorNumElements(), DAG.getPOISON(SVT));
7205 else if (Op.getOpcode() == ISD::UNDEF)
7206 Elts.append(OpVT.getVectorNumElements(), DAG.getUNDEF(SVT));
7207 else if (Op.getOpcode() == ISD::BUILD_VECTOR)
7208 Elts.append(Op->op_begin(), Op->op_end());
7209 else if (Op.getOpcode() == ISD::INSERT_VECTOR_ELT &&
7210 OpVT.getVectorNumElements() == 1 &&
7211 isNullConstant(Op.getOperand(2)))
7212 Elts.push_back(Op.getOperand(1));
7213 else
7214 return SDValue();
7215 }
7216
7217 // BUILD_VECTOR requires all inputs to be of the same type, find the
7218 // maximum type and extend them all.
7219 for (SDValue Op : Elts)
7220 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
7221
7222 if (SVT.bitsGT(VT.getScalarType())) {
7223 for (SDValue &Op : Elts) {
7224 if (Op.getOpcode() == ISD::POISON)
7225 Op = DAG.getPOISON(SVT);
7226 else if (Op.getOpcode() == ISD::UNDEF)
7227 Op = DAG.getUNDEF(SVT);
7228 else
7229 Op = DAG.getTargetLoweringInfo().isZExtFree(Op.getValueType(), SVT)
7230 ? DAG.getZExtOrTrunc(Op, DL, SVT)
7231 : DAG.getSExtOrTrunc(Op, DL, SVT);
7232 }
7233 }
7234
7235 SDValue V = DAG.getBuildVector(VT, DL, Elts);
7236 NewSDValueDbgMsg(V, "New node fold concat vectors: ", &DAG);
7237 return V;
7238}
7239
7240/// Gets or creates the specified node.
7241SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT) {
7242 SDVTList VTs = getVTList(VT);
7243 SDNodeKey ID(Opcode, VTs, {});
7244 FoldingSetInsertToken InsertToken;
7245 if (SDNode *E = lookupNode(ID, DL, InsertToken))
7246 return SDValue(E, 0);
7247
7248 auto *N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
7249 CSEMap.insert(N, InsertToken);
7250
7251 InsertNode(N);
7252 SDValue V = SDValue(N, 0);
7253 NewSDValueDbgMsg(V, "Creating new node: ", this);
7254 return V;
7255}
7256
7257SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
7258 SDValue N1) {
7259 SDNodeFlags Flags;
7260 if (Inserter)
7261 Flags = Inserter->getFlags();
7262 return getNode(Opcode, DL, VT, N1, Flags);
7263}
7264
7265SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
7266 SDValue N1, const SDNodeFlags Flags) {
7267 assert(N1.getOpcode() != ISD::DELETED_NODE && "Operand is DELETED_NODE!");
7268
7269 // Constant fold unary operations with a vector integer or float operand.
7270 switch (Opcode) {
7271 default:
7272 // FIXME: Entirely reasonable to perform folding of other unary
7273 // operations here as the need arises.
7274 break;
7275 case ISD::FNEG:
7276 case ISD::FABS:
7277 case ISD::FCEIL:
7278 case ISD::FTRUNC:
7279 case ISD::FFLOOR:
7280 case ISD::FP_EXTEND:
7281 case ISD::FP_TO_SINT:
7282 case ISD::FP_TO_UINT:
7283 case ISD::FP_TO_FP16:
7284 case ISD::FP_TO_BF16:
7285 case ISD::TRUNCATE:
7286 case ISD::ANY_EXTEND:
7287 case ISD::ZERO_EXTEND:
7288 case ISD::SIGN_EXTEND:
7289 case ISD::UINT_TO_FP:
7290 case ISD::SINT_TO_FP:
7291 case ISD::FP16_TO_FP:
7292 case ISD::BF16_TO_FP:
7293 case ISD::BITCAST:
7294 case ISD::ABS:
7296 case ISD::BITREVERSE:
7297 case ISD::BSWAP:
7298 case ISD::CTLZ:
7300 case ISD::CTTZ:
7302 case ISD::CTPOP:
7303 case ISD::PARITY:
7304 case ISD::CTLS:
7305 case ISD::VECREDUCE_ADD:
7310 case ISD::VECREDUCE_MUL:
7311 case ISD::VECREDUCE_AND:
7312 case ISD::VECREDUCE_OR:
7313 case ISD::VECREDUCE_XOR:
7314 case ISD::STEP_VECTOR: {
7315 SDValue Ops = {N1};
7316 if (SDValue Fold = FoldConstantArithmetic(Opcode, DL, VT, Ops, Flags))
7317 return Fold;
7318 }
7319 }
7320
7321 unsigned OpOpcode = N1.getNode()->getOpcode();
7322 switch (Opcode) {
7323 case ISD::STEP_VECTOR:
7324 assert(VT.isScalableVector() &&
7325 "STEP_VECTOR can only be used with scalable types");
7326 assert(OpOpcode == ISD::TargetConstant &&
7327 VT.getVectorElementType() == N1.getValueType() &&
7328 "Unexpected step operand");
7329 break;
7330 case ISD::FREEZE:
7331 assert(VT == N1.getValueType() && "Unexpected VT!");
7333 return N1;
7334 break;
7335 case ISD::TokenFactor:
7336 case ISD::MERGE_VALUES:
7338 return N1; // Factor, merge or concat of one node? No need.
7339 case ISD::BUILD_VECTOR: {
7340 // Attempt to simplify BUILD_VECTOR.
7341 SDValue Ops[] = {N1};
7342 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
7343 return V;
7344 break;
7345 }
7346 case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node");
7347 case ISD::FP_EXTEND:
7349 "Invalid FP cast!");
7350 if (N1.getValueType() == VT) return N1; // noop conversion.
7351 assert((!VT.isVector() || VT.getVectorElementCount() ==
7353 "Vector element count mismatch!");
7354 assert(N1.getValueType().bitsLT(VT) && "Invalid fpext node, dst < src!");
7355 if (N1.isUndef())
7356 return getUNDEF(VT);
7357 break;
7358 case ISD::FP_TO_SINT:
7359 case ISD::FP_TO_UINT:
7360 if (N1.isUndef())
7361 return getUNDEF(VT);
7362 break;
7363 case ISD::SINT_TO_FP:
7364 case ISD::UINT_TO_FP:
7365 // [us]itofp(undef) = 0, because the result value is bounded.
7366 if (N1.isUndef())
7367 return getConstantFP(0.0, DL, VT);
7368 break;
7369 case ISD::SIGN_EXTEND:
7370 assert(VT.isInteger() && N1.getValueType().isInteger() &&
7371 "Invalid SIGN_EXTEND!");
7372 assert(VT.isVector() == N1.getValueType().isVector() &&
7373 "SIGN_EXTEND result type type should be vector iff the operand "
7374 "type is vector!");
7375 if (N1.getValueType() == VT) return N1; // noop extension
7376 assert((!VT.isVector() || VT.getVectorElementCount() ==
7378 "Vector element count mismatch!");
7379 assert(N1.getValueType().bitsLT(VT) && "Invalid sext node, dst < src!");
7380 if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND) {
7381 SDNodeFlags Flags;
7382 if (OpOpcode == ISD::ZERO_EXTEND)
7383 Flags.setNonNeg(N1->getFlags().hasNonNeg());
7384 SDValue NewVal = getNode(OpOpcode, DL, VT, N1.getOperand(0), Flags);
7385 transferDbgValues(N1, NewVal);
7386 return NewVal;
7387 }
7388
7389 if (OpOpcode == ISD::POISON)
7390 return getPOISON(VT);
7391
7392 if (N1.isUndef())
7393 // sext(undef) = 0, because the top bits will all be the same.
7394 return getConstant(0, DL, VT);
7395
7396 // Skip unnecessary sext_inreg pattern:
7397 // (sext (trunc x)) -> x iff the upper bits are all signbits.
7398 if (OpOpcode == ISD::TRUNCATE) {
7399 SDValue OpOp = N1.getOperand(0);
7400 if (OpOp.getValueType() == VT) {
7401 unsigned NumSignExtBits =
7403 if (ComputeNumSignBits(OpOp) > NumSignExtBits) {
7404 transferDbgValues(N1, OpOp);
7405 return OpOp;
7406 }
7407 }
7408 }
7409 break;
7410 case ISD::ZERO_EXTEND:
7411 assert(VT.isInteger() && N1.getValueType().isInteger() &&
7412 "Invalid ZERO_EXTEND!");
7413 assert(VT.isVector() == N1.getValueType().isVector() &&
7414 "ZERO_EXTEND result type type should be vector iff the operand "
7415 "type is vector!");
7416 if (N1.getValueType() == VT) return N1; // noop extension
7417 assert((!VT.isVector() || VT.getVectorElementCount() ==
7419 "Vector element count mismatch!");
7420 assert(N1.getValueType().bitsLT(VT) && "Invalid zext node, dst < src!");
7421 if (OpOpcode == ISD::ZERO_EXTEND) { // (zext (zext x)) -> (zext x)
7422 SDNodeFlags Flags;
7423 Flags.setNonNeg(N1->getFlags().hasNonNeg());
7424 SDValue NewVal =
7425 getNode(ISD::ZERO_EXTEND, DL, VT, N1.getOperand(0), Flags);
7426 transferDbgValues(N1, NewVal);
7427 return NewVal;
7428 }
7429
7430 if (OpOpcode == ISD::POISON)
7431 return getPOISON(VT);
7432
7433 if (N1.isUndef())
7434 // zext(undef) = 0, because the top bits will be zero.
7435 return getConstant(0, DL, VT);
7436
7437 // Skip unnecessary zext_inreg pattern:
7438 // (zext (trunc x)) -> x iff the upper bits are known zero.
7439 // TODO: Remove (zext (trunc (and x, c))) exception which some targets
7440 // use to recognise zext_inreg patterns.
7441 if (OpOpcode == ISD::TRUNCATE) {
7442 SDValue OpOp = N1.getOperand(0);
7443 if (OpOp.getValueType() == VT) {
7444 if (OpOp.getOpcode() != ISD::AND) {
7447 if (MaskedValueIsZero(OpOp, HiBits)) {
7448 transferDbgValues(N1, OpOp);
7449 return OpOp;
7450 }
7451 }
7452 }
7453 }
7454 break;
7455 case ISD::ANY_EXTEND:
7456 assert(VT.isInteger() && N1.getValueType().isInteger() &&
7457 "Invalid ANY_EXTEND!");
7458 assert(VT.isVector() == N1.getValueType().isVector() &&
7459 "ANY_EXTEND result type type should be vector iff the operand "
7460 "type is vector!");
7461 if (N1.getValueType() == VT) return N1; // noop extension
7462 assert((!VT.isVector() || VT.getVectorElementCount() ==
7464 "Vector element count mismatch!");
7465 assert(N1.getValueType().bitsLT(VT) && "Invalid anyext node, dst < src!");
7466
7467 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
7468 OpOpcode == ISD::ANY_EXTEND) {
7469 SDNodeFlags Flags;
7470 if (OpOpcode == ISD::ZERO_EXTEND)
7471 Flags.setNonNeg(N1->getFlags().hasNonNeg());
7472 // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x)
7473 return getNode(OpOpcode, DL, VT, N1.getOperand(0), Flags);
7474 }
7475 if (N1.isUndef())
7476 return getUNDEF(VT);
7477
7478 // (ext (trunc x)) -> x
7479 if (OpOpcode == ISD::TRUNCATE) {
7480 SDValue OpOp = N1.getOperand(0);
7481 if (OpOp.getValueType() == VT) {
7482 transferDbgValues(N1, OpOp);
7483 return OpOp;
7484 }
7485 }
7486 break;
7487 case ISD::TRUNCATE:
7488 assert(VT.isInteger() && N1.getValueType().isInteger() &&
7489 "Invalid TRUNCATE!");
7490 assert(VT.isVector() == N1.getValueType().isVector() &&
7491 "TRUNCATE result type type should be vector iff the operand "
7492 "type is vector!");
7493 if (N1.getValueType() == VT) return N1; // noop truncate
7494 assert((!VT.isVector() || VT.getVectorElementCount() ==
7496 "Vector element count mismatch!");
7497 assert(N1.getValueType().bitsGT(VT) && "Invalid truncate node, src < dst!");
7498 if (OpOpcode == ISD::TRUNCATE)
7499 return getNode(ISD::TRUNCATE, DL, VT, N1.getOperand(0));
7500 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
7501 OpOpcode == ISD::ANY_EXTEND) {
7502 // If the source is smaller than the dest, we still need an extend.
7504 VT.getScalarType())) {
7505 SDNodeFlags Flags;
7506 if (OpOpcode == ISD::ZERO_EXTEND)
7507 Flags.setNonNeg(N1->getFlags().hasNonNeg());
7508 return getNode(OpOpcode, DL, VT, N1.getOperand(0), Flags);
7509 }
7510 if (N1.getOperand(0).getValueType().bitsGT(VT))
7511 return getNode(ISD::TRUNCATE, DL, VT, N1.getOperand(0));
7512 return N1.getOperand(0);
7513 }
7514 if (N1.isUndef())
7515 return getUNDEF(VT);
7516 if (OpOpcode == ISD::VSCALE && !NewNodesMustHaveLegalTypes)
7517 return getVScale(DL, VT,
7519 break;
7523 assert(VT.isVector() && "This DAG node is restricted to vector types.");
7524 assert(N1.getValueType().bitsLE(VT) &&
7525 "The input must be the same size or smaller than the result.");
7528 "The destination vector type must have fewer lanes than the input.");
7529 break;
7530 case ISD::ABS:
7531 assert(VT.isInteger() && VT == N1.getValueType() && "Invalid ABS!");
7532 if (N1.isUndef())
7533 return getConstant(0, DL, VT);
7534 break;
7536 assert(VT.isInteger() && VT == N1.getValueType() &&
7537 "Invalid ABS_MIN_POISON!");
7538 if (N1.isUndef())
7539 return getConstant(0, DL, VT);
7540 break;
7541 case ISD::BSWAP:
7542 assert(VT.isInteger() && VT == N1.getValueType() && "Invalid BSWAP!");
7543 assert((VT.getScalarSizeInBits() % 16 == 0) &&
7544 "BSWAP types must be a multiple of 16 bits!");
7545 if (N1.isUndef())
7546 return getUNDEF(VT);
7547 // bswap(bswap(X)) -> X.
7548 if (OpOpcode == ISD::BSWAP)
7549 return N1.getOperand(0);
7550 break;
7551 case ISD::BITREVERSE:
7552 assert(VT.isInteger() && VT == N1.getValueType() && "Invalid BITREVERSE!");
7553 if (N1.isUndef())
7554 return getUNDEF(VT);
7555 break;
7556 case ISD::BITCAST:
7558 "Cannot BITCAST between types of different sizes!");
7559 if (VT == N1.getValueType()) return N1; // noop conversion.
7560 if (OpOpcode == ISD::BITCAST) // bitconv(bitconv(x)) -> bitconv(x)
7561 return getNode(ISD::BITCAST, DL, VT, N1.getOperand(0));
7562 if (N1.isUndef())
7563 return getUNDEF(VT);
7564 break;
7566 assert(VT.isVector() && !N1.getValueType().isVector() &&
7567 (VT.getVectorElementType() == N1.getValueType() ||
7569 N1.getValueType().isInteger() &&
7571 "Illegal SCALAR_TO_VECTOR node!");
7572 if (N1.isUndef())
7573 return getUNDEF(VT);
7574 // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
7575 if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
7577 N1.getConstantOperandVal(1) == 0 &&
7578 N1.getOperand(0).getValueType() == VT)
7579 return N1.getOperand(0);
7580 break;
7581 case ISD::FNEG:
7582 // Negation of an unknown bag of bits is still completely undefined.
7583 if (N1.isUndef())
7584 return getUNDEF(VT);
7585
7586 if (OpOpcode == ISD::FNEG) // --X -> X
7587 return N1.getOperand(0);
7588 break;
7589 case ISD::FABS:
7590 if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X)
7591 return getNode(ISD::FABS, DL, VT, N1.getOperand(0));
7592 break;
7593 case ISD::VSCALE:
7594 assert(VT == N1.getValueType() && "Unexpected VT!");
7595 break;
7596 case ISD::CTPOP:
7597 if (N1.getValueType().getScalarType() == MVT::i1)
7598 return N1;
7599 break;
7600 case ISD::CTLZ:
7601 case ISD::CTTZ:
7602 if (N1.getValueType().getScalarType() == MVT::i1)
7603 return getNOT(DL, N1, N1.getValueType());
7604 break;
7605 case ISD::CTLS:
7606 if (N1.getValueType().getScalarType() == MVT::i1)
7607 return getConstant(0, DL, VT);
7608 break;
7609 case ISD::VECREDUCE_ADD:
7610 if (N1.getValueType().getScalarType() == MVT::i1)
7611 return getNode(ISD::VECREDUCE_XOR, DL, VT, N1);
7612 break;
7615 if (N1.getValueType().getScalarType() == MVT::i1)
7616 return getNode(ISD::VECREDUCE_OR, DL, VT, N1);
7617 break;
7620 if (N1.getValueType().getScalarType() == MVT::i1)
7621 return getNode(ISD::VECREDUCE_AND, DL, VT, N1);
7622 break;
7624 // With a single lane, the result is true iff that lane is false.
7626 return getLogicalNOT(DL, N1, VT);
7627 break;
7628 case ISD::VECTOR_REPEAT:
7630 "VECTOR_REPEAT requires a fixed-length vector operand");
7631 assert(VT.isScalableVector() &&
7632 "VECTOR_REPEAT requires a scalable vector result");
7635 "VECTOR_REPEAT operand and result element counts must match");
7636 if (VT.getVectorMinNumElements() == 1)
7637 return getSplatVector(
7638 VT, DL, getExtractVectorElt(DL, VT.getVectorElementType(), N1, 0));
7639 break;
7640 case ISD::SPLAT_VECTOR:
7641 assert(VT.isVector() && "Wrong return type!");
7642 // FIXME: Hexagon uses i32 scalar for a floating point zero vector so allow
7643 // that for now.
7645 (VT.isFloatingPoint() && N1.getValueType() == MVT::i32) ||
7647 N1.getValueType().isInteger() &&
7649 "Wrong operand type!");
7650 break;
7651 }
7652
7653 SDNode *N;
7654 SDVTList VTs = getVTList(VT);
7655 SDValue Ops[] = {N1};
7656 if (VT != MVT::Glue) { // Don't CSE glue producing nodes
7657 SDNodeKey ID(Opcode, VTs, Ops);
7658 FoldingSetInsertToken InsertToken;
7659 if (SDNode *E = lookupNode(ID, DL, InsertToken)) {
7660 E->intersectFlagsWith(Flags);
7661 return SDValue(E, 0);
7662 }
7663
7664 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
7665 N->setFlags(Flags);
7666 createOperands(N, Ops);
7667 CSEMap.insert(N, InsertToken);
7668 } else {
7669 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
7670 createOperands(N, Ops);
7671 }
7672
7673 InsertNode(N);
7674 SDValue V = SDValue(N, 0);
7675 NewSDValueDbgMsg(V, "Creating new node: ", this);
7676 return V;
7677}
7678
7679static APInt getIntegerIdentity(unsigned Opcode, unsigned BitWidth) {
7680 switch (Opcode) {
7681 default:
7682 llvm_unreachable("Unexpected integer identity opcode");
7683 case ISD::ADD:
7684 case ISD::OR:
7685 case ISD::XOR:
7686 case ISD::UMAX:
7687 return APInt::getZero(BitWidth);
7688 case ISD::MUL:
7689 return APInt(BitWidth, 1);
7690 case ISD::AND:
7691 case ISD::UMIN:
7693 case ISD::SMAX:
7695 case ISD::SMIN:
7697 }
7698}
7699
7700static std::optional<APInt> FoldValue(unsigned Opcode, const APInt &C1,
7701 const APInt &C2) {
7702 switch (Opcode) {
7703 case ISD::ADD: return C1 + C2;
7704 case ISD::SUB: return C1 - C2;
7705 case ISD::MUL: return C1 * C2;
7706 case ISD::AND: return C1 & C2;
7707 case ISD::OR: return C1 | C2;
7708 case ISD::XOR: return C1 ^ C2;
7709 case ISD::SHL: return C1 << C2;
7710 case ISD::SRL: return C1.lshr(C2);
7711 case ISD::SRA: return C1.ashr(C2);
7712 case ISD::ROTL: return C1.rotl(C2);
7713 case ISD::ROTR: return C1.rotr(C2);
7714 case ISD::SMIN: return C1.sle(C2) ? C1 : C2;
7715 case ISD::SMAX: return C1.sge(C2) ? C1 : C2;
7716 case ISD::UMIN: return C1.ule(C2) ? C1 : C2;
7717 case ISD::UMAX: return C1.uge(C2) ? C1 : C2;
7718 case ISD::SADDSAT: return C1.sadd_sat(C2);
7719 case ISD::UADDSAT: return C1.uadd_sat(C2);
7720 case ISD::SSUBSAT: return C1.ssub_sat(C2);
7721 case ISD::USUBSAT: return C1.usub_sat(C2);
7722 case ISD::SSHLSAT: return C1.sshl_sat(C2);
7723 case ISD::USHLSAT: return C1.ushl_sat(C2);
7724 case ISD::UDIV:
7725 if (!C2.getBoolValue())
7726 break;
7727 return C1.udiv(C2);
7728 case ISD::UREM:
7729 if (!C2.getBoolValue())
7730 break;
7731 return C1.urem(C2);
7732 case ISD::SDIV:
7733 if (!C2.getBoolValue())
7734 break;
7735 return C1.sdiv(C2);
7736 case ISD::SREM:
7737 if (!C2.getBoolValue())
7738 break;
7739 return C1.srem(C2);
7740 case ISD::AVGFLOORS:
7741 return APIntOps::avgFloorS(C1, C2);
7742 case ISD::AVGFLOORU:
7743 return APIntOps::avgFloorU(C1, C2);
7744 case ISD::AVGCEILS:
7745 return APIntOps::avgCeilS(C1, C2);
7746 case ISD::AVGCEILU:
7747 return APIntOps::avgCeilU(C1, C2);
7748 case ISD::AVGSUBFLOORS:
7749 return APIntOps::avgSubFloorS(C1, C2);
7750 case ISD::AVGSUBFLOORU:
7751 return APIntOps::avgSubFloorU(C1, C2);
7752 case ISD::ABDS:
7753 return APIntOps::abds(C1, C2);
7754 case ISD::ABDU:
7755 return APIntOps::abdu(C1, C2);
7756 case ISD::MULHS:
7757 return APIntOps::mulhs(C1, C2);
7758 case ISD::MULHU:
7759 return APIntOps::mulhu(C1, C2);
7760 case ISD::CLMUL:
7761 return APIntOps::clmul(C1, C2);
7762 case ISD::CLMULR:
7763 return APIntOps::clmulr(C1, C2);
7764 case ISD::CLMULH:
7765 return APIntOps::clmulh(C1, C2);
7766 case ISD::PEXT:
7767 return APIntOps::pext(C1, C2);
7768 case ISD::PDEP:
7769 return APIntOps::pdep(C1, C2);
7770 }
7771 return std::nullopt;
7772}
7773// Handle constant folding with UNDEF.
7774// TODO: Handle more cases.
7775static std::optional<APInt> FoldValueWithUndef(unsigned Opcode, const APInt &C1,
7776 bool IsUndef1, const APInt &C2,
7777 bool IsUndef2) {
7778 if (!(IsUndef1 || IsUndef2))
7779 return FoldValue(Opcode, C1, C2);
7780
7781 // Fold and(x, undef) -> 0
7782 // Fold mul(x, undef) -> 0
7783 if (Opcode == ISD::AND || Opcode == ISD::MUL)
7784 return APInt::getZero(C1.getBitWidth());
7785
7786 return std::nullopt;
7787}
7788
7790 const GlobalAddressSDNode *GA,
7791 const SDNode *N2) {
7792 if (GA->getOpcode() != ISD::GlobalAddress)
7793 return SDValue();
7794 if (!TLI->isOffsetFoldingLegal(GA))
7795 return SDValue();
7796 auto *C2 = dyn_cast<ConstantSDNode>(N2);
7797 if (!C2)
7798 return SDValue();
7799 int64_t Offset = C2->getSExtValue();
7800 switch (Opcode) {
7801 case ISD::ADD:
7802 case ISD::PTRADD:
7803 break;
7804 case ISD::SUB: Offset = -uint64_t(Offset); break;
7805 default: return SDValue();
7806 }
7807 return getGlobalAddress(GA->getGlobal(), SDLoc(C2), VT,
7808 GA->getOffset() + uint64_t(Offset));
7809}
7810
7812 switch (Opcode) {
7813 case ISD::SDIV:
7814 case ISD::UDIV:
7815 case ISD::SREM:
7816 case ISD::UREM: {
7817 // If a divisor is zero/undef or any element of a divisor vector is
7818 // zero/undef, the whole op is undef.
7819 assert(Ops.size() == 2 && "Div/rem should have 2 operands");
7820 SDValue Divisor = Ops[1];
7821 if (Divisor.isUndef() || isNullConstant(Divisor))
7822 return true;
7823
7824 return ISD::isBuildVectorOfConstantSDNodes(Divisor) &&
7825 llvm::any_of(Divisor->op_values(), [](SDValue V) {
7826 return V.isUndef() || isNullConstant(V);
7827 });
7828 // TODO: Handle signed overflow.
7829 }
7830 // TODO: Handle oversized shifts.
7831 default:
7832 return false;
7833 }
7834}
7835
7838 SDNodeFlags Flags) {
7839 // If the opcode is a target-specific ISD node, there's nothing we can
7840 // do here and the operand rules may not line up with the below, so
7841 // bail early.
7842 // We can't create a scalar CONCAT_VECTORS so skip it. It will break
7843 // for concats involving SPLAT_VECTOR. Concats of BUILD_VECTORS are handled by
7844 // foldCONCAT_VECTORS in getNode before this is called.
7845 // VECTOR_SHUFFLE_VAR is not elementwise.
7846 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::CONCAT_VECTORS ||
7847 Opcode == ISD::VECTOR_SHUFFLE_VAR)
7848 return SDValue();
7849
7850 unsigned NumOps = Ops.size();
7851 if (NumOps == 0)
7852 return SDValue();
7853
7854 if (isUndef(Opcode, Ops))
7855 return getUNDEF(VT);
7856
7857 // Handle unary special cases.
7858 if (NumOps == 1) {
7859 SDValue N1 = Ops[0];
7860
7861 // Constant fold unary operations with an integer constant operand. Even
7862 // opaque constant will be folded, because the folding of unary operations
7863 // doesn't create new constants with different values. Nevertheless, the
7864 // opaque flag is preserved during folding to prevent future folding with
7865 // other constants.
7866 if (auto *C = dyn_cast<ConstantSDNode>(N1)) {
7867 const APInt &Val = C->getAPIntValue();
7868 switch (Opcode) {
7869 case ISD::SIGN_EXTEND:
7870 return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
7871 C->isTargetOpcode(), C->isOpaque());
7872 case ISD::TRUNCATE:
7873 if (C->isOpaque())
7874 break;
7875 [[fallthrough]];
7876 case ISD::ZERO_EXTEND:
7877 return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
7878 C->isTargetOpcode(), C->isOpaque());
7879 case ISD::ANY_EXTEND:
7880 // Some targets like RISCV prefer to sign extend some types.
7881 if (TLI->isSExtCheaperThanZExt(N1.getValueType(), VT))
7882 return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
7883 C->isTargetOpcode(), C->isOpaque());
7884 return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
7885 C->isTargetOpcode(), C->isOpaque());
7886 case ISD::ABS:
7887 return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(),
7888 C->isOpaque());
7890 if (Val.isMinSignedValue())
7891 return getPOISON(VT);
7892 return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(),
7893 C->isOpaque());
7894 case ISD::BITREVERSE:
7895 return getConstant(Val.reverseBits(), DL, VT, C->isTargetOpcode(),
7896 C->isOpaque());
7897 case ISD::BSWAP:
7898 return getConstant(Val.byteSwap(), DL, VT, C->isTargetOpcode(),
7899 C->isOpaque());
7900 case ISD::CTPOP:
7901 return getConstant(Val.popcount(), DL, VT, C->isTargetOpcode(),
7902 C->isOpaque());
7903 case ISD::PARITY:
7904 return getConstant(Val.popcount() & 1, DL, VT, C->isTargetOpcode(),
7905 C->isOpaque());
7906 case ISD::CTLZ:
7908 return getConstant(Val.countl_zero(), DL, VT, C->isTargetOpcode(),
7909 C->isOpaque());
7910 case ISD::CTTZ:
7912 return getConstant(Val.countr_zero(), DL, VT, C->isTargetOpcode(),
7913 C->isOpaque());
7914 case ISD::CTLS:
7915 // CTLS returns the number of extra sign bits so subtract one.
7916 return getConstant(Val.getNumSignBits() - 1, DL, VT,
7917 C->isTargetOpcode(), C->isOpaque());
7918 case ISD::UINT_TO_FP:
7919 case ISD::SINT_TO_FP: {
7921 (void)FPV.convertFromAPInt(Val, Opcode == ISD::SINT_TO_FP,
7923 return getConstantFP(FPV, DL, VT);
7924 }
7925 case ISD::FP16_TO_FP:
7926 case ISD::BF16_TO_FP: {
7927 bool Ignored;
7928 APFloat FPV(Opcode == ISD::FP16_TO_FP ? APFloat::IEEEhalf()
7929 : APFloat::BFloat(),
7930 (Val.getBitWidth() == 16) ? Val : Val.trunc(16));
7931
7932 // This can return overflow, underflow, or inexact; we don't care.
7933 // FIXME need to be more flexible about rounding mode.
7935 &Ignored);
7936 return getConstantFP(FPV, DL, VT);
7937 }
7938 case ISD::STEP_VECTOR:
7939 if (SDValue V = FoldSTEP_VECTOR(DL, VT, N1, *this))
7940 return V;
7941 break;
7942 case ISD::BITCAST:
7943 if (C->isOpaque())
7944 break;
7945 if (VT == MVT::f16 && C->getValueType(0) == MVT::i16)
7946 return getConstantFP(APFloat(APFloat::IEEEhalf(), Val), DL, VT);
7947 if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
7948 return getConstantFP(APFloat(APFloat::IEEEsingle(), Val), DL, VT);
7949 if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
7950 return getConstantFP(APFloat(APFloat::IEEEdouble(), Val), DL, VT);
7951 if (VT == MVT::f128 && C->getValueType(0) == MVT::i128)
7952 return getConstantFP(APFloat(APFloat::IEEEquad(), Val), DL, VT);
7953 break;
7954 }
7955 }
7956
7957 // Constant fold unary operations with a floating point constant operand.
7958 if (auto *C = dyn_cast<ConstantFPSDNode>(N1)) {
7959 APFloat V = C->getValueAPF(); // make copy
7960 DenormalMode DenormMode = getDenormalMode(N1.getValueType());
7961 switch (Opcode) {
7962 case ISD::FNEG:
7963 V.changeSign();
7964 return getConstantFP(V, DL, VT);
7965 case ISD::FABS:
7966 V.clearSign();
7967 return getConstantFP(V, DL, VT);
7968 case ISD::FCEIL: {
7969 if (auto Res = tryFoldFP(FPOp::Ceil, {V}, DenormMode))
7970 if (Res->Status == APFloat::opOK || Res->Status == APFloat::opInexact)
7971 return getConstantFP(Res->Value, DL, VT);
7972 return SDValue();
7973 }
7974 case ISD::FTRUNC: {
7975 if (auto Res = tryFoldFP(FPOp::Trunc, {V}, DenormMode))
7976 if (Res->Status == APFloat::opOK || Res->Status == APFloat::opInexact)
7977 return getConstantFP(Res->Value, DL, VT);
7978 return SDValue();
7979 }
7980 case ISD::FFLOOR: {
7981 if (auto Res = tryFoldFP(FPOp::Floor, {V}, DenormMode))
7982 if (Res->Status == APFloat::opOK || Res->Status == APFloat::opInexact)
7983 return getConstantFP(Res->Value, DL, VT);
7984 return SDValue();
7985 }
7986 case ISD::FP_EXTEND: {
7987 bool ignored;
7988 // This can return overflow, underflow, or inexact; we don't care.
7989 // FIXME need to be more flexible about rounding mode.
7990 (void)V.convert(VT.getFltSemantics(), APFloat::rmNearestTiesToEven,
7991 &ignored);
7992 return getConstantFP(V, DL, VT);
7993 }
7994 case ISD::FP_TO_SINT:
7995 case ISD::FP_TO_UINT: {
7996 bool ignored;
7997 APSInt IntVal(VT.getSizeInBits(), Opcode == ISD::FP_TO_UINT);
7998 // FIXME need to be more flexible about rounding mode.
8000 V.convertToInteger(IntVal, APFloat::rmTowardZero, &ignored);
8001 if (s == APFloat::opInvalidOp) // inexact is OK, in fact usual
8002 break;
8003 return getConstant(IntVal, DL, VT);
8004 }
8005 case ISD::FP_TO_FP16:
8006 case ISD::FP_TO_BF16: {
8007 bool Ignored;
8008 // This can return overflow, underflow, or inexact; we don't care.
8009 // FIXME need to be more flexible about rounding mode.
8010 (void)V.convert(Opcode == ISD::FP_TO_FP16 ? APFloat::IEEEhalf()
8011 : APFloat::BFloat(),
8013 return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
8014 }
8015 case ISD::BITCAST:
8016 if (VT == MVT::i16 && C->getValueType(0) == MVT::f16)
8017 return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL,
8018 VT);
8019 if (VT == MVT::i16 && C->getValueType(0) == MVT::bf16)
8020 return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL,
8021 VT);
8022 if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
8023 return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), DL,
8024 VT);
8025 if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
8026 return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
8027 break;
8028 }
8029 }
8030
8031 // Early-out if we failed to constant fold a bitcast.
8032 if (Opcode == ISD::BITCAST)
8033 return SDValue();
8034
8035 // Constant fold integer vector reductions with constant BUILD_VECTORs.
8036 if ((Opcode == ISD::VECREDUCE_ADD || Opcode == ISD::VECREDUCE_SMAX ||
8037 Opcode == ISD::VECREDUCE_SMIN || Opcode == ISD::VECREDUCE_UMAX ||
8038 Opcode == ISD::VECREDUCE_UMIN || Opcode == ISD::VECREDUCE_MUL ||
8039 Opcode == ISD::VECREDUCE_OR || Opcode == ISD::VECREDUCE_XOR ||
8040 Opcode == ISD::VECREDUCE_AND) &&
8042 unsigned EltBits = N1.getValueType().getScalarSizeInBits();
8043 unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Opcode);
8044 APInt Acc = getIntegerIdentity(BaseOpcode, EltBits);
8045 for (SDValue Elt : N1->op_values()) {
8046 if (Elt.getOpcode() == ISD::POISON)
8047 return getPOISON(VT);
8048 if (Elt.isUndef() || cast<ConstantSDNode>(Elt)->isOpaque())
8049 return SDValue();
8050 APInt Value = cast<ConstantSDNode>(Elt)->getAPIntValue().trunc(EltBits);
8051 std::optional<APInt> Folded = FoldValue(BaseOpcode, Acc, Value);
8052 assert(Folded &&
8053 "Expected vector reduction base opcode to be foldable");
8054 Acc = *Folded;
8055 }
8056 EVT EltVT = N1.getValueType().getScalarType();
8057 return getAnyExtOrTrunc(getConstant(Acc, DL, EltVT), DL, VT);
8058 }
8059 }
8060
8061 // Handle binops special cases.
8062 if (NumOps == 2) {
8063 if (SDValue CFP = foldConstantFPMath(Opcode, DL, VT, Ops))
8064 return CFP;
8065
8066 if (auto *C1 = dyn_cast<ConstantSDNode>(Ops[0])) {
8067 if (auto *C2 = dyn_cast<ConstantSDNode>(Ops[1])) {
8068 if (C1->isOpaque() || C2->isOpaque())
8069 return SDValue();
8070
8071 std::optional<APInt> FoldAttempt =
8072 FoldValue(Opcode, C1->getAPIntValue(), C2->getAPIntValue());
8073 if (!FoldAttempt)
8074 return SDValue();
8075
8076 SDValue Folded = getConstant(*FoldAttempt, DL, VT);
8077 assert((!Folded || !VT.isVector()) &&
8078 "Can't fold vectors ops with scalar operands");
8079 return Folded;
8080 }
8081 }
8082
8083 // fold (add Sym, c) -> Sym+c
8085 return FoldSymbolOffset(Opcode, VT, GA, Ops[1].getNode());
8086 if (TLI->isCommutativeBinOp(Opcode))
8088 return FoldSymbolOffset(Opcode, VT, GA, Ops[0].getNode());
8089
8090 // fold (sext_in_reg c1) -> c2
8091 if (Opcode == ISD::SIGN_EXTEND_INREG) {
8092 EVT EVT = cast<VTSDNode>(Ops[1])->getVT();
8093
8094 auto SignExtendInReg = [&](APInt Val, llvm::EVT ConstantVT) {
8095 unsigned FromBits = EVT.getScalarSizeInBits();
8096 Val <<= Val.getBitWidth() - FromBits;
8097 Val.ashrInPlace(Val.getBitWidth() - FromBits);
8098 return getConstant(Val, DL, ConstantVT);
8099 };
8100
8101 if (auto *C1 = dyn_cast<ConstantSDNode>(Ops[0])) {
8102 const APInt &Val = C1->getAPIntValue();
8103 return SignExtendInReg(Val, VT);
8104 }
8105
8107 SmallVector<SDValue, 8> ScalarOps;
8108 llvm::EVT OpVT = Ops[0].getOperand(0).getValueType();
8109 for (int I = 0, E = VT.getVectorNumElements(); I != E; ++I) {
8110 SDValue Op = Ops[0].getOperand(I);
8111 if (Op.isUndef()) {
8112 ScalarOps.push_back(getUNDEF(OpVT));
8113 continue;
8114 }
8115 const APInt &Val = cast<ConstantSDNode>(Op)->getAPIntValue();
8116 ScalarOps.push_back(SignExtendInReg(Val, OpVT));
8117 }
8118 return getBuildVector(VT, DL, ScalarOps);
8119 }
8120
8121 if (Ops[0].getOpcode() == ISD::SPLAT_VECTOR &&
8122 isa<ConstantSDNode>(Ops[0].getOperand(0)))
8123 return getNode(ISD::SPLAT_VECTOR, DL, VT,
8124 SignExtendInReg(Ops[0].getConstantOperandAPInt(0),
8125 Ops[0].getOperand(0).getValueType()));
8126 }
8127 }
8128
8129 // Handle fshl/fshr special cases.
8130 if (Opcode == ISD::FSHL || Opcode == ISD::FSHR) {
8131 auto *C1 = dyn_cast<ConstantSDNode>(Ops[0]);
8132 auto *C2 = dyn_cast<ConstantSDNode>(Ops[1]);
8133 auto *C3 = dyn_cast<ConstantSDNode>(Ops[2]);
8134
8135 if (C1 && C2 && C3) {
8136 if (C1->isOpaque() || C2->isOpaque() || C3->isOpaque())
8137 return SDValue();
8138 const APInt &V1 = C1->getAPIntValue(), &V2 = C2->getAPIntValue(),
8139 &V3 = C3->getAPIntValue();
8140
8141 APInt FoldedVal = Opcode == ISD::FSHL ? APIntOps::fshl(V1, V2, V3)
8142 : APIntOps::fshr(V1, V2, V3);
8143 return getConstant(FoldedVal, DL, VT);
8144 }
8145 }
8146
8147 // Handle fma/fmad special cases.
8148 if (Opcode == ISD::FMA || Opcode == ISD::FMAD || Opcode == ISD::FMULADD) {
8149 assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
8150 assert(Ops[0].getValueType() == VT && Ops[1].getValueType() == VT &&
8151 Ops[2].getValueType() == VT && "FMA types must match!");
8155 if (C1 && C2 && C3) {
8157 APFloat V1 = C1->getValueAPF();
8158 const APFloat &V2 = C2->getValueAPF();
8159 const APFloat &V3 = C3->getValueAPF();
8160 if (Opcode == ISD::FMAD || Opcode == ISD::FMULADD) {
8161 if (auto Product = tryFoldFP(FPOp::Mul, {V1, V2}, DM))
8162 return getConstFP(tryFoldFP(FPOp::Add, {Product->Value, V3}, DM), DL,
8163 VT);
8164 return SDValue();
8165 }
8166 return getConstFP(tryFoldFP(FPOp::FMA, {V1, V2, V3}, DM), DL, VT);
8167 }
8168 }
8169
8170 // This is for vector folding only from here on.
8171 if (!VT.isVector())
8172 return SDValue();
8173
8174 // Constant fold integer partial reductions with constant BUILD_VECTOR
8175 // operands. The reduction order is deliberately unspecified. Use the same
8176 // subvector layout as TargetLowering::expandPartialReduceMLA(), where input
8177 // lane I contributes to accumulator lane I % NumAccElts.
8178 if (Opcode == ISD::PARTIAL_REDUCE_SMLA ||
8179 Opcode == ISD::PARTIAL_REDUCE_UMLA ||
8180 Opcode == ISD::PARTIAL_REDUCE_SUMLA) {
8181 // These nodes have no scalar form, so unsupported cases must not fall
8182 // through to generic per-lane vector folding.
8183 if (!llvm::all_of(Ops, [](SDValue Op) {
8185 }))
8186 return SDValue();
8187
8188 unsigned AccEltBits = VT.getScalarSizeInBits();
8189 unsigned InputEltBits = Ops[1].getScalarValueSizeInBits();
8190 unsigned NumAccElts = VT.getVectorNumElements();
8191 unsigned NumInputElts = Ops[1].getValueType().getVectorNumElements();
8192 SmallVector<APInt, 8> Results(NumAccElts, APInt::getZero(AccEltBits));
8193 BitVector PoisonElts(NumAccElts);
8194
8195 for (unsigned I = 0; I != NumAccElts; ++I) {
8196 SDValue Elt = Ops[0].getOperand(I);
8197 if (Elt.getOpcode() == ISD::POISON) {
8198 PoisonElts.set(I);
8199 continue;
8200 }
8201 auto *C = dyn_cast<ConstantSDNode>(Elt);
8202 if (!C || C->isOpaque())
8203 return SDValue();
8204 Results[I] = C->getAPIntValue().trunc(AccEltBits);
8205 }
8206
8207 bool IsLHSSigned = Opcode != ISD::PARTIAL_REDUCE_UMLA;
8208 bool IsRHSSigned = Opcode == ISD::PARTIAL_REDUCE_SMLA;
8209 for (unsigned I = 0; I != NumInputElts; ++I) {
8210 const unsigned AccIdx = I % NumAccElts;
8211 SDValue LHSElt = Ops[1].getOperand(I);
8212 SDValue RHSElt = Ops[2].getOperand(I);
8213 if (LHSElt.getOpcode() == ISD::POISON ||
8214 RHSElt.getOpcode() == ISD::POISON) {
8215 PoisonElts.set(AccIdx);
8216 continue;
8217 }
8218
8219 auto *LHS = dyn_cast<ConstantSDNode>(LHSElt);
8220 auto *RHS = dyn_cast<ConstantSDNode>(RHSElt);
8221 if (!LHS || !RHS || LHS->isOpaque() || RHS->isOpaque())
8222 return SDValue();
8223
8224 APInt LHSVal = LHS->getAPIntValue().trunc(InputEltBits);
8225 APInt RHSVal = RHS->getAPIntValue().trunc(InputEltBits);
8226 LHSVal = IsLHSSigned ? LHSVal.sext(AccEltBits) : LHSVal.zext(AccEltBits);
8227 RHSVal = IsRHSSigned ? RHSVal.sext(AccEltBits) : RHSVal.zext(AccEltBits);
8228 Results[AccIdx] += LHSVal * RHSVal;
8229 }
8230
8231 // After type legalization the vector element type may not be a legal
8232 // scalar type (e.g. i16 on AArch64). Create the folded constants in the
8233 // promoted legal scalar type instead, matching the generic per-lane path
8234 // below. Bail out if legalization would narrow the type, since the lane
8235 // value would not fit.
8236 EVT AccEltVT = VT.getVectorElementType();
8237 EVT LegalSVT = AccEltVT;
8238 if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
8239 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
8240 if (LegalSVT.bitsLT(AccEltVT))
8241 return SDValue();
8242 }
8243
8244 SmallVector<SDValue, 8> ResultOps;
8245 for (unsigned I = 0; I != NumAccElts; ++I)
8246 ResultOps.push_back(
8247 PoisonElts[I] ? getPOISON(LegalSVT)
8248 : getConstant(Results[I].sext(LegalSVT.getSizeInBits()),
8249 DL, LegalSVT));
8250 return getBuildVector(VT, DL, ResultOps);
8251 }
8252
8253 ElementCount NumElts = VT.getVectorElementCount();
8254
8255 // See if we can fold through any bitcasted integer ops.
8256 if (NumOps == 2 && VT.isFixedLengthVector() && VT.isInteger() &&
8257 Ops[0].getValueType() == VT && Ops[1].getValueType() == VT &&
8258 (Ops[0].getOpcode() == ISD::BITCAST ||
8259 Ops[1].getOpcode() == ISD::BITCAST)) {
8262 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
8263 auto *BV2 = dyn_cast<BuildVectorSDNode>(N2);
8264 if (BV1 && BV2 && N1.getValueType().isInteger() &&
8265 N2.getValueType().isInteger()) {
8266 bool IsLE = getDataLayout().isLittleEndian();
8267 unsigned EltBits = VT.getScalarSizeInBits();
8268 SmallVector<APInt> RawBits1, RawBits2;
8269 BitVector UndefElts1, UndefElts2;
8270 if (BV1->getConstantRawBits(IsLE, EltBits, RawBits1, UndefElts1) &&
8271 BV2->getConstantRawBits(IsLE, EltBits, RawBits2, UndefElts2)) {
8272 SmallVector<APInt> RawBits;
8273 for (unsigned I = 0, E = NumElts.getFixedValue(); I != E; ++I) {
8274 std::optional<APInt> Fold = FoldValueWithUndef(
8275 Opcode, RawBits1[I], UndefElts1[I], RawBits2[I], UndefElts2[I]);
8276 if (!Fold)
8277 break;
8278 RawBits.push_back(*Fold);
8279 }
8280 if (RawBits.size() == NumElts.getFixedValue()) {
8281 // We have constant folded, but we might need to cast this again back
8282 // to the original (possibly legalized) type.
8283 EVT BVVT, BVEltVT;
8284 if (N1.getValueType() == VT) {
8285 BVVT = N1.getValueType();
8286 BVEltVT = BV1->getOperand(0).getValueType();
8287 } else {
8288 BVVT = N2.getValueType();
8289 BVEltVT = BV2->getOperand(0).getValueType();
8290 }
8291 unsigned BVEltBits = BVEltVT.getSizeInBits();
8292 SmallVector<APInt> DstBits;
8293 BitVector DstUndefs;
8295 DstBits, RawBits, DstUndefs,
8296 BitVector(RawBits.size(), false));
8297 SmallVector<SDValue> Ops(DstBits.size(), getUNDEF(BVEltVT));
8298 for (unsigned I = 0, E = DstBits.size(); I != E; ++I) {
8299 if (DstUndefs[I])
8300 continue;
8301 Ops[I] = getConstant(DstBits[I].sext(BVEltBits), DL, BVEltVT);
8302 }
8303 return getBitcast(VT, getBuildVector(BVVT, DL, Ops));
8304 }
8305 }
8306 }
8307 // Logic ops can be folded from raw integer bits - mainly for AVX512 masks.
8308 if (ISD::isBitwiseLogicOp(Opcode) && isa<ConstantSDNode>(N1) &&
8309 isa<ConstantSDNode>(N2)) {
8310 if (SDValue Res = FoldConstantArithmetic(Opcode, DL, N1.getValueType(),
8311 {N1, N2}, Flags))
8312 return getBitcast(VT, Res);
8313 }
8314 }
8315
8316 // Fold (mul step_vector(C0), C1) to (step_vector(C0 * C1)).
8317 // (shl step_vector(C0), C1) -> (step_vector(C0 << C1))
8318 if ((Opcode == ISD::MUL || Opcode == ISD::SHL) &&
8319 Ops[0].getOpcode() == ISD::STEP_VECTOR) {
8320 APInt RHSVal;
8321 if (ISD::isConstantSplatVector(Ops[1], RHSVal)) {
8322 APInt NewStep = Opcode == ISD::MUL
8323 ? Ops[0].getConstantOperandAPInt(0) * RHSVal
8324 : Ops[0].getConstantOperandAPInt(0) << RHSVal;
8325 return getStepVector(DL, VT, NewStep);
8326 }
8327 }
8328
8329 auto IsScalarOrSameVectorSize = [NumElts](const SDValue &Op) {
8330 return !Op.getValueType().isVector() ||
8331 Op.getValueType().getVectorElementCount() == NumElts;
8332 };
8333
8334 auto IsBuildVectorSplatVectorOrUndef = [](const SDValue &Op) {
8335 return Op.isUndef() || Op.getOpcode() == ISD::CONDCODE ||
8336 Op.getOpcode() == ISD::BUILD_VECTOR ||
8337 Op.getOpcode() == ISD::SPLAT_VECTOR;
8338 };
8339
8340 // All operands must be vector types with the same number of elements as
8341 // the result type and must be either UNDEF or a build/splat vector
8342 // or UNDEF scalars.
8343 if (!llvm::all_of(Ops, IsBuildVectorSplatVectorOrUndef) ||
8344 !llvm::all_of(Ops, IsScalarOrSameVectorSize))
8345 return SDValue();
8346
8347 // If we are comparing vectors, then the result needs to be a i1 boolean that
8348 // is then extended back to the legal result type depending on how booleans
8349 // are represented.
8350 EVT SVT = (Opcode == ISD::SETCC ? MVT::i1 : VT.getScalarType());
8351 ISD::NodeType ExtendCode =
8352 (Opcode == ISD::SETCC && SVT != VT.getScalarType())
8353 ? TargetLowering::getExtendForContent(TLI->getBooleanContents(VT))
8355
8356 // Find legal integer scalar type for constant promotion and
8357 // ensure that its scalar size is at least as large as source.
8358 EVT LegalSVT = VT.getScalarType();
8359 if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
8360 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
8361 if (LegalSVT.bitsLT(VT.getScalarType()))
8362 return SDValue();
8363 }
8364
8365 // For scalable vector types we know we're dealing with SPLAT_VECTORs. We
8366 // only have one operand to check. For fixed-length vector types we may have
8367 // a combination of BUILD_VECTOR and SPLAT_VECTOR.
8368 unsigned NumVectorElts = NumElts.isScalable() ? 1 : NumElts.getFixedValue();
8369
8370 // Constant fold each scalar lane separately.
8371 SmallVector<SDValue, 4> ScalarResults;
8372 for (unsigned I = 0; I != NumVectorElts; I++) {
8373 SmallVector<SDValue, 4> ScalarOps;
8374 for (SDValue Op : Ops) {
8375 EVT InSVT = Op.getValueType().getScalarType();
8376 if (Op.getOpcode() != ISD::BUILD_VECTOR &&
8377 Op.getOpcode() != ISD::SPLAT_VECTOR) {
8378 if (Op.isUndef())
8379 ScalarOps.push_back(getUNDEF(InSVT));
8380 else
8381 ScalarOps.push_back(Op);
8382 continue;
8383 }
8384
8385 SDValue ScalarOp =
8386 Op.getOperand(Op.getOpcode() == ISD::SPLAT_VECTOR ? 0 : I);
8387 EVT ScalarVT = ScalarOp.getValueType();
8388
8389 // Build vector (integer) scalar operands may need implicit
8390 // truncation - do this before constant folding.
8391 if (ScalarVT.isInteger() && ScalarVT.bitsGT(InSVT)) {
8392 // Don't create illegally-typed nodes unless they're constants or undef
8393 // - if we fail to constant fold we can't guarantee the (dead) nodes
8394 // we're creating will be cleaned up before being visited for
8395 // legalization.
8396 if (NewNodesMustHaveLegalTypes && !ScalarOp.isUndef() &&
8397 !isa<ConstantSDNode>(ScalarOp) &&
8398 TLI->getTypeAction(*getContext(), InSVT) !=
8400 return SDValue();
8401 ScalarOp = getNode(ISD::TRUNCATE, DL, InSVT, ScalarOp);
8402 }
8403
8404 ScalarOps.push_back(ScalarOp);
8405 }
8406
8407 // Constant fold the scalar operands.
8408 SDValue ScalarResult = getNode(Opcode, DL, SVT, ScalarOps, Flags);
8409
8410 // Scalar folding only succeeded if the result is a constant or UNDEF.
8411 if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant &&
8412 ScalarResult.getOpcode() != ISD::ConstantFP)
8413 return SDValue();
8414
8415 // Legalize the (integer) scalar constant if necessary. We only do
8416 // this once we know the folding succeeded, since otherwise we would
8417 // get a node with illegal type which has a user.
8418 if (LegalSVT != SVT)
8419 ScalarResult = getNode(ExtendCode, DL, LegalSVT, ScalarResult);
8420
8421 ScalarResults.push_back(ScalarResult);
8422 }
8423
8424 SDValue V = NumElts.isScalable() ? getSplatVector(VT, DL, ScalarResults[0])
8425 : getBuildVector(VT, DL, ScalarResults);
8426 NewSDValueDbgMsg(V, "New node fold constant vector: ", this);
8427 return V;
8428}
8429
8431 SDVTList VTList,
8433 SDNodeFlags Flags) {
8434 if (VTList.NumVTs == 1)
8435 return FoldConstantArithmetic(Opcode, DL, VTList.VTs[0], Ops, Flags);
8436
8437 switch (Opcode) {
8438 case ISD::SADDO:
8439 case ISD::UADDO:
8440 case ISD::SSUBO:
8441 case ISD::USUBO:
8442 case ISD::SMULO:
8443 case ISD::UMULO: {
8444 // TODO: Support non-splat vector constants.
8447 if (!C1 || !C2 || C1->isOpaque() || C2->isOpaque())
8448 return SDValue();
8449
8450 const APInt &V1 = C1->getAPIntValue(), &V2 = C2->getAPIntValue();
8451 bool Overflow;
8452 APInt Result;
8453 switch (Opcode) {
8454 default:
8455 llvm_unreachable("Unexpected overflow opcode");
8456 case ISD::SADDO:
8457 Result = V1.sadd_ov(V2, Overflow);
8458 break;
8459 case ISD::UADDO:
8460 Result = V1.uadd_ov(V2, Overflow);
8461 break;
8462 case ISD::SSUBO:
8463 Result = V1.ssub_ov(V2, Overflow);
8464 break;
8465 case ISD::USUBO:
8466 Result = V1.usub_ov(V2, Overflow);
8467 break;
8468 case ISD::SMULO:
8469 Result = V1.smul_ov(V2, Overflow);
8470 break;
8471 case ISD::UMULO:
8472 Result = V1.umul_ov(V2, Overflow);
8473 break;
8474 }
8475
8476 EVT VT = VTList.VTs[0];
8477 return getNode(ISD::MERGE_VALUES, DL, VTList,
8478 {getConstant(Result, DL, VT),
8479 getBoolConstant(Overflow, DL, VTList.VTs[1], VT)},
8480 Flags);
8481 }
8482 case ISD::SMUL_LOHI:
8483 case ISD::UMUL_LOHI:
8484 // TODO: Support non-splat vector constants.
8487 if (!C1 || !C2 || C1->isOpaque() || C2->isOpaque())
8488 return SDValue();
8489
8490 const APInt &V1 = C1->getAPIntValue(), &V2 = C2->getAPIntValue();
8491 APInt Lo = V1 * V2;
8492 APInt Hi = (Opcode == ISD::SMUL_LOHI) ? APIntOps::mulhs(V1, V2)
8493 : APIntOps::mulhu(V1, V2);
8494 return getNode(ISD::MERGE_VALUES, DL, VTList,
8495 {getConstant(Lo, DL, VTList.VTs[0]),
8496 getConstant(Hi, DL, VTList.VTs[1])},
8497 Flags);
8498 }
8499 return SDValue();
8500}
8501
8504 // TODO: Add support for unary/ternary fp opcodes.
8505 if (Ops.size() != 2)
8506 return SDValue();
8507
8508 // TODO: We don't do any constant folding for strict FP opcodes here, but we
8509 // should. That will require dealing with a potentially non-default
8510 // rounding mode, checking the "opStatus" return value from the APFloat
8511 // math calculations, and possibly other variations.
8512 SDValue N1 = Ops[0];
8513 SDValue N2 = Ops[1];
8514 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1, /*AllowUndefs*/ false);
8515 ConstantFPSDNode *N2CFP = isConstOrConstSplatFP(N2, /*AllowUndefs*/ false);
8516 if (N1CFP && N2CFP) {
8517 APFloat C1 = N1CFP->getValueAPF();
8518 const APFloat &C2 = N2CFP->getValueAPF();
8520 switch (Opcode) {
8521 case ISD::FADD:
8522 return getConstFP(tryFoldFP(FPOp::Add, {C1, C2}, DM), DL, VT);
8523 case ISD::FSUB:
8524 return getConstFP(tryFoldFP(FPOp::Sub, {C1, C2}, DM), DL, VT);
8525 case ISD::FMUL:
8526 return getConstFP(tryFoldFP(FPOp::Mul, {C1, C2}, DM), DL, VT);
8527 case ISD::FDIV:
8528 return getConstFP(tryFoldFP(FPOp::Div, {C1, C2}, DM), DL, VT);
8529 case ISD::FREM:
8530 return getConstFP(tryFoldFP(FPOp::FRem, {C1, C2}, DM), DL, VT);
8531 case ISD::FCOPYSIGN:
8532 C1.copySign(C2);
8533 return getConstantFP(C1, DL, VT);
8534 case ISD::FMINNUM:
8535 return getConstFP(tryFoldFP(FPOp::MinNum, {C1, C2}, DM), DL, VT);
8536 case ISD::FMAXNUM:
8537 return getConstFP(tryFoldFP(FPOp::MaxNum, {C1, C2}, DM), DL, VT);
8538 case ISD::FMINIMUM:
8539 return getConstFP(tryFoldFP(FPOp::Minimum, {C1, C2}, DM), DL, VT);
8540 case ISD::FMAXIMUM:
8541 return getConstFP(tryFoldFP(FPOp::Maximum, {C1, C2}, DM), DL, VT);
8542 case ISD::FMINIMUMNUM:
8543 return getConstFP(tryFoldFP(FPOp::MinimumNum, {C1, C2}, DM), DL, VT);
8544 case ISD::FMAXIMUMNUM:
8545 return getConstFP(tryFoldFP(FPOp::MaximumNum, {C1, C2}, DM), DL, VT);
8546 default: break;
8547 }
8548 }
8549 if (N1CFP && Opcode == ISD::FP_ROUND) {
8550 APFloat C1 = N1CFP->getValueAPF(); // make copy
8551 bool Unused;
8552 // This can return overflow, underflow, or inexact; we don't care.
8553 // FIXME need to be more flexible about rounding mode.
8555 &Unused);
8556 return getConstantFP(C1, DL, VT);
8557 }
8558
8559 switch (Opcode) {
8560 case ISD::FSUB:
8561 // -0.0 - undef --> undef (consistent with "fneg undef")
8562 if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1, /*AllowUndefs*/ true))
8563 if (N1C && N1C->getValueAPF().isNegZero() && N2.isUndef())
8564 return getUNDEF(VT);
8565 [[fallthrough]];
8566
8567 case ISD::FADD:
8568 case ISD::FMUL:
8569 case ISD::FDIV:
8570 case ISD::FREM:
8571 // If both operands are undef, the result is undef. If 1 operand is undef,
8572 // the result is NaN. This should match the behavior of the IR optimizer.
8573 if (N1.isUndef() && N2.isUndef())
8574 return getUNDEF(VT);
8575 if (N1.isUndef() || N2.isUndef())
8577 }
8578 return SDValue();
8579}
8580
8582 const SDLoc &DL, EVT DstEltVT) {
8583 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
8584
8585 // If this is already the right type, we're done.
8586 if (SrcEltVT == DstEltVT)
8587 return SDValue(BV, 0);
8588
8589 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
8590 unsigned DstBitSize = DstEltVT.getSizeInBits();
8591
8592 // If this is a conversion of N elements of one type to N elements of another
8593 // type, convert each element. This handles FP<->INT cases.
8594 if (SrcBitSize == DstBitSize) {
8596 for (SDValue Op : BV->op_values()) {
8597 // If the vector element type is not legal, the BUILD_VECTOR operands
8598 // are promoted and implicitly truncated. Make that explicit here.
8599 if (Op.getValueType() != SrcEltVT)
8600 Op = getNode(ISD::TRUNCATE, DL, SrcEltVT, Op);
8601 Ops.push_back(getBitcast(DstEltVT, Op));
8602 }
8603 EVT VT = EVT::getVectorVT(*getContext(), DstEltVT,
8605 return getBuildVector(VT, DL, Ops);
8606 }
8607
8608 // Otherwise, we're growing or shrinking the elements. To avoid having to
8609 // handle annoying details of growing/shrinking FP values, we convert them to
8610 // int first.
8611 if (SrcEltVT.isFloatingPoint()) {
8612 // Convert the input float vector to a int vector where the elements are the
8613 // same sizes.
8614 EVT IntEltVT = EVT::getIntegerVT(*getContext(), SrcEltVT.getSizeInBits());
8615 if (SDValue Tmp = FoldConstantBuildVector(BV, DL, IntEltVT))
8617 DstEltVT);
8618 return SDValue();
8619 }
8620
8621 // Now we know the input is an integer vector. If the output is a FP type,
8622 // convert to integer first, then to FP of the right size.
8623 if (DstEltVT.isFloatingPoint()) {
8624 EVT IntEltVT = EVT::getIntegerVT(*getContext(), DstEltVT.getSizeInBits());
8625 if (SDValue Tmp = FoldConstantBuildVector(BV, DL, IntEltVT))
8627 DstEltVT);
8628 return SDValue();
8629 }
8630
8631 // Okay, we know the src/dst types are both integers of differing types.
8632 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
8633
8634 // Extract the constant raw bit data.
8635 BitVector UndefElements;
8636 SmallVector<APInt> RawBits;
8637 bool IsLE = getDataLayout().isLittleEndian();
8638 if (!BV->getConstantRawBits(IsLE, DstBitSize, RawBits, UndefElements))
8639 return SDValue();
8640
8642 for (unsigned I = 0, E = RawBits.size(); I != E; ++I) {
8643 if (UndefElements[I])
8644 Ops.push_back(getUNDEF(DstEltVT));
8645 else
8646 Ops.push_back(getConstant(RawBits[I], DL, DstEltVT));
8647 }
8648
8649 EVT VT = EVT::getVectorVT(*getContext(), DstEltVT, Ops.size());
8650 return getBuildVector(VT, DL, Ops);
8651}
8652
8654 assert(Val.getValueType().isInteger() && "Invalid AssertAlign!");
8655
8656 // There's no need to assert on a byte-aligned pointer. All pointers are at
8657 // least byte aligned.
8658 if (A == Align(1))
8659 return Val;
8660
8661 SDVTList VTs = getVTList(Val.getValueType());
8662 SDValue Ops[] = {Val};
8663 SDNodeKey ID(ISD::AssertAlign, VTs, Ops);
8664 ID.AddInteger(A.value());
8665
8666 FoldingSetInsertToken InsertToken;
8667 if (SDNode *E = lookupNode(ID, DL, InsertToken))
8668 return SDValue(E, 0);
8669
8670 auto *N =
8671 newSDNode<AssertAlignSDNode>(DL.getIROrder(), DL.getDebugLoc(), VTs, A);
8672 createOperands(N, {Val});
8673
8674 CSEMap.insert(N, InsertToken);
8675 InsertNode(N);
8676
8677 SDValue V(N, 0);
8678 NewSDValueDbgMsg(V, "Creating new node: ", this);
8679 return V;
8680}
8681
8682SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8683 SDValue N1, SDValue N2) {
8684 SDNodeFlags Flags;
8685 if (Inserter)
8686 Flags = Inserter->getFlags();
8687 return getNode(Opcode, DL, VT, N1, N2, Flags);
8688}
8689
8691 SDValue &N2) const {
8692 if (!TLI->isCommutativeBinOp(Opcode))
8693 return;
8694
8695 // Canonicalize:
8696 // binop(const, nonconst) -> binop(nonconst, const)
8699 bool N1CFP = isConstantFPBuildVectorOrConstantFP(N1);
8700 bool N2CFP = isConstantFPBuildVectorOrConstantFP(N2);
8701 if ((N1C && !N2C) || (N1CFP && !N2CFP))
8702 std::swap(N1, N2);
8703
8704 // Canonicalize:
8705 // binop(splat(x), step_vector) -> binop(step_vector, splat(x))
8706 else if (N1.getOpcode() == ISD::SPLAT_VECTOR &&
8708 std::swap(N1, N2);
8709}
8710
8711SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8712 SDValue N1, SDValue N2, const SDNodeFlags Flags) {
8714 N2.getOpcode() != ISD::DELETED_NODE &&
8715 "Operand is DELETED_NODE!");
8716
8717 canonicalizeCommutativeBinop(Opcode, N1, N2);
8718
8719 auto *N1C = dyn_cast<ConstantSDNode>(N1);
8720 auto *N2C = dyn_cast<ConstantSDNode>(N2);
8721
8722 // Don't allow undefs in vector splats - we might be returning N2 when folding
8723 // to zero etc.
8724 ConstantSDNode *N2CV =
8725 isConstOrConstSplat(N2, /*AllowUndefs*/ false, /*AllowTruncation*/ true);
8726
8727 switch (Opcode) {
8728 default: break;
8729 case ISD::TokenFactor:
8730 assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
8731 N2.getValueType() == MVT::Other && "Invalid token factor!");
8732 // Fold trivial token factors.
8733 if (N1.getOpcode() == ISD::EntryToken) return N2;
8734 if (N2.getOpcode() == ISD::EntryToken) return N1;
8735 if (N1 == N2) return N1;
8736 break;
8737 case ISD::BUILD_VECTOR: {
8738 // Attempt to simplify BUILD_VECTOR.
8739 SDValue Ops[] = {N1, N2};
8740 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
8741 return V;
8742 break;
8743 }
8744 case ISD::CONCAT_VECTORS: {
8745 SDValue Ops[] = {N1, N2};
8746 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
8747 return V;
8748 break;
8749 }
8750 case ISD::AND:
8751 assert(VT.isInteger() && "This operator does not apply to FP types!");
8752 assert(N1.getValueType() == N2.getValueType() &&
8753 N1.getValueType() == VT && "Binary operator types must match!");
8754 // (X & 0) -> 0. This commonly occurs when legalizing i64 values, so it's
8755 // worth handling here.
8756 if (N2CV && N2CV->isZero())
8757 return N2;
8758 if (N2CV && N2CV->isAllOnes()) // X & -1 -> X
8759 return N1;
8760 break;
8761 case ISD::OR:
8762 case ISD::XOR:
8763 case ISD::ADD:
8764 case ISD::PTRADD:
8765 case ISD::SUB:
8766 assert(VT.isInteger() && "This operator does not apply to FP types!");
8767 assert(N1.getValueType() == N2.getValueType() &&
8768 N1.getValueType() == VT && "Binary operator types must match!");
8769 // The equal operand types requirement is unnecessarily strong for PTRADD.
8770 // However, the SelectionDAGBuilder does not generate PTRADDs with different
8771 // operand types, and we'd need to re-implement GEP's non-standard wrapping
8772 // logic everywhere where PTRADDs may be folded or combined to properly
8773 // support them. If/when we introduce pointer types to the SDAG, we will
8774 // need to relax this constraint.
8775
8776 // (X ^|+- 0) -> X. This commonly occurs when legalizing i64 values, so
8777 // it's worth handling here.
8778 if (N2CV && N2CV->isZero())
8779 return N1;
8780 if ((Opcode == ISD::ADD || Opcode == ISD::SUB) &&
8781 VT.getScalarType() == MVT::i1)
8782 return getNode(ISD::XOR, DL, VT, N1, N2);
8783 // Fold (add (vscale * C0), (vscale * C1)) to (vscale * (C0 + C1)).
8784 if (Opcode == ISD::ADD && N1.getOpcode() == ISD::VSCALE &&
8785 N2.getOpcode() == ISD::VSCALE) {
8786 const APInt &C1 = N1->getConstantOperandAPInt(0);
8787 const APInt &C2 = N2->getConstantOperandAPInt(0);
8788 return getVScale(DL, VT, C1 + C2);
8789 }
8790 break;
8791 case ISD::MUL:
8792 assert(VT.isInteger() && "This operator does not apply to FP types!");
8793 assert(N1.getValueType() == N2.getValueType() &&
8794 N1.getValueType() == VT && "Binary operator types must match!");
8795 if (VT.getScalarType() == MVT::i1)
8796 return getNode(ISD::AND, DL, VT, N1, N2);
8797 if (N2CV && N2CV->isZero())
8798 return N2;
8799 if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
8800 const APInt &MulImm = N1->getConstantOperandAPInt(0);
8801 const APInt &N2CImm = N2C->getAPIntValue();
8802 return getVScale(DL, VT, MulImm * N2CImm);
8803 }
8804 break;
8805 case ISD::UDIV:
8806 case ISD::UREM:
8807 case ISD::MULHU:
8808 case ISD::MULHS:
8809 case ISD::SDIV:
8810 case ISD::SREM:
8811 case ISD::SADDSAT:
8812 case ISD::SSUBSAT:
8813 case ISD::UADDSAT:
8814 case ISD::USUBSAT:
8815 assert(VT.isInteger() && "This operator does not apply to FP types!");
8816 assert(N1.getValueType() == N2.getValueType() &&
8817 N1.getValueType() == VT && "Binary operator types must match!");
8818 if (VT.getScalarType() == MVT::i1) {
8819 // fold (add_sat x, y) -> (or x, y) for bool types.
8820 if (Opcode == ISD::SADDSAT || Opcode == ISD::UADDSAT)
8821 return getNode(ISD::OR, DL, VT, N1, N2);
8822 // fold (sub_sat x, y) -> (and x, ~y) for bool types.
8823 if (Opcode == ISD::SSUBSAT || Opcode == ISD::USUBSAT)
8824 return getNode(ISD::AND, DL, VT, N1, getNOT(DL, N2, VT));
8825 // mulhs/mulhu on i1 are always 0: the high bit of the 2-bit product of
8826 // two booleans is never set. The i1 constant 1 is also -1, so folding
8827 // (mulhs x, 1) to (sra x, 0) in DAGCombiner would be wrong here.
8828 if (Opcode == ISD::MULHS || Opcode == ISD::MULHU)
8829 return getConstant(0, DL, VT);
8830 }
8831 break;
8832 case ISD::SCMP:
8833 case ISD::UCMP:
8834 assert(N1.getValueType() == N2.getValueType() &&
8835 "Types of operands of UCMP/SCMP must match");
8836 assert(N1.getValueType().isVector() == VT.isVector() &&
8837 "Operands and return type of must both be scalars or vectors");
8838 if (VT.isVector())
8841 "Result and operands must have the same number of elements");
8842 break;
8843 case ISD::AVGFLOORS:
8844 case ISD::AVGFLOORU:
8845 case ISD::AVGCEILS:
8846 case ISD::AVGCEILU:
8847 case ISD::AVGSUBFLOORS:
8848 case ISD::AVGSUBFLOORU:
8849 assert(VT.isInteger() && "This operator does not apply to FP types!");
8850 assert(N1.getValueType() == N2.getValueType() &&
8851 N1.getValueType() == VT && "Binary operator types must match!");
8852 break;
8853 case ISD::ABDS:
8854 case ISD::ABDU:
8855 assert(VT.isInteger() && "This operator does not apply to FP types!");
8856 assert(N1.getValueType() == N2.getValueType() &&
8857 N1.getValueType() == VT && "Binary operator types must match!");
8858 if (VT.getScalarType() == MVT::i1)
8859 return getNode(ISD::XOR, DL, VT, N1, N2);
8860 break;
8861 case ISD::SMIN:
8862 case ISD::UMAX:
8863 assert(VT.isInteger() && "This operator does not apply to FP types!");
8864 assert(N1.getValueType() == N2.getValueType() &&
8865 N1.getValueType() == VT && "Binary operator types must match!");
8866 if (VT.getScalarType() == MVT::i1)
8867 return getNode(ISD::OR, DL, VT, N1, N2);
8868 break;
8869 case ISD::SMAX:
8870 case ISD::UMIN:
8871 assert(VT.isInteger() && "This operator does not apply to FP types!");
8872 assert(N1.getValueType() == N2.getValueType() &&
8873 N1.getValueType() == VT && "Binary operator types must match!");
8874 if (VT.getScalarType() == MVT::i1)
8875 return getNode(ISD::AND, DL, VT, N1, N2);
8876 break;
8877 case ISD::FADD:
8878 case ISD::FSUB:
8879 case ISD::FMUL:
8880 case ISD::FDIV:
8881 case ISD::FREM:
8882 assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
8883 assert(N1.getValueType() == N2.getValueType() &&
8884 N1.getValueType() == VT && "Binary operator types must match!");
8885 if (SDValue V = simplifyFPBinop(Opcode, N1, N2, Flags))
8886 return V;
8887 break;
8888 case ISD::FCOPYSIGN: // N1 and result must match. N1/N2 need not match.
8889 assert(N1.getValueType() == VT &&
8892 "Invalid FCOPYSIGN!");
8893 break;
8894 case ISD::SHL:
8895 if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
8896 const APInt &MulImm = N1->getConstantOperandAPInt(0);
8897 const APInt &ShiftImm = N2C->getAPIntValue();
8898 return getVScale(DL, VT, MulImm << ShiftImm);
8899 }
8900 [[fallthrough]];
8901 case ISD::SRA:
8902 case ISD::SRL:
8903 if (SDValue V = simplifyShift(N1, N2))
8904 return V;
8905 [[fallthrough]];
8906 case ISD::ROTL:
8907 case ISD::ROTR:
8908 case ISD::SSHLSAT:
8909 case ISD::USHLSAT:
8910 assert(VT == N1.getValueType() &&
8911 "Shift operators return type must be the same as their first arg");
8912 assert(VT.isInteger() && N2.getValueType().isInteger() &&
8913 "Shifts only work on integers");
8914 assert((!VT.isVector() || VT == N2.getValueType()) &&
8915 "Vector shift amounts must be in the same as their first arg");
8916 // Verify that the shift amount VT is big enough to hold valid shift
8917 // amounts. This catches things like trying to shift an i1024 value by an
8918 // i8, which is easy to fall into in generic code that uses
8919 // TLI.getShiftAmount().
8922 "Invalid use of small shift amount with oversized value!");
8923
8924 // Always fold shifts of i1 values so the code generator doesn't need to
8925 // handle them. Since we know the size of the shift has to be less than the
8926 // size of the value, the shift/rotate count is guaranteed to be zero.
8927 if (VT == MVT::i1)
8928 return N1;
8929 if (N2CV && N2CV->isZero())
8930 return N1;
8931 break;
8932 case ISD::FP_ROUND:
8934 VT.bitsLE(N1.getValueType()) && N2C &&
8935 (N2C->getZExtValue() == 0 || N2C->getZExtValue() == 1) &&
8936 N2.getOpcode() == ISD::TargetConstant && "Invalid FP_ROUND!");
8937 if (N1.getValueType() == VT) return N1; // noop conversion.
8938 break;
8939 case ISD::IS_FPCLASS: {
8941 "IS_FPCLASS is used for a non-floating type");
8942 assert(isa<ConstantSDNode>(N2) && "FPClassTest is not Constant");
8943 // is.fpclass(poison, mask) -> poison
8944 if (N1.getOpcode() == ISD::POISON)
8945 return getPOISON(VT);
8946 FPClassTest Mask = static_cast<FPClassTest>(N2->getAsZExtVal());
8947 // If all tests are made, it doesn't matter what the value is.
8948 if ((Mask & fcAllFlags) == fcAllFlags)
8949 return getBoolConstant(true, DL, VT, N1.getValueType());
8950 if ((Mask & fcAllFlags) == 0)
8951 return getBoolConstant(false, DL, VT, N1.getValueType());
8952 break;
8953 }
8954 case ISD::AssertNoFPClass: {
8956 "AssertNoFPClass is used for a non-floating type");
8957 assert(isa<ConstantSDNode>(N2) && "NoFPClass is not Constant");
8958 FPClassTest NoFPClass = static_cast<FPClassTest>(N2->getAsZExtVal());
8959 assert(llvm::to_underlying(NoFPClass) <=
8961 "FPClassTest value too large");
8962 (void)NoFPClass;
8963 break;
8964 }
8965 case ISD::AssertSext:
8966 case ISD::AssertZext: {
8967 EVT EVT = cast<VTSDNode>(N2)->getVT();
8968 assert(VT == N1.getValueType() && "Not an inreg extend!");
8969 assert(VT.isInteger() && EVT.isInteger() &&
8970 "Cannot *_EXTEND_INREG FP types");
8971 assert(!EVT.isVector() &&
8972 "AssertSExt/AssertZExt type should be the vector element type "
8973 "rather than the vector type!");
8974 assert(EVT.bitsLE(VT.getScalarType()) && "Not extending!");
8975 if (VT.getScalarType() == EVT) return N1; // noop assertion.
8976 break;
8977 }
8979 EVT EVT = cast<VTSDNode>(N2)->getVT();
8980 assert(VT == N1.getValueType() && "Not an inreg extend!");
8981 assert(VT.isInteger() && EVT.isInteger() &&
8982 "Cannot *_EXTEND_INREG FP types");
8983 assert(EVT.isVector() == VT.isVector() &&
8984 "SIGN_EXTEND_INREG type should be vector iff the operand "
8985 "type is vector!");
8986 assert((!EVT.isVector() ||
8988 "Vector element counts must match in SIGN_EXTEND_INREG");
8989 assert(EVT.getScalarType().bitsLE(VT.getScalarType()) && "Not extending!");
8990 if (EVT == VT) return N1; // Not actually extending
8991 break;
8992 }
8994 case ISD::FP_TO_UINT_SAT: {
8995 assert(VT.isInteger() && cast<VTSDNode>(N2)->getVT().isInteger() &&
8996 N1.getValueType().isFloatingPoint() && "Invalid FP_TO_*INT_SAT");
8997 assert(N1.getValueType().isVector() == VT.isVector() &&
8998 "FP_TO_*INT_SAT type should be vector iff the operand type is "
8999 "vector!");
9000 assert((!VT.isVector() || VT.getVectorElementCount() ==
9002 "Vector element counts must match in FP_TO_*INT_SAT");
9003 assert(!cast<VTSDNode>(N2)->getVT().isVector() &&
9004 "Type to saturate to must be a scalar.");
9005 assert(cast<VTSDNode>(N2)->getVT().bitsLE(VT.getScalarType()) &&
9006 "Not extending!");
9007 break;
9008 }
9011 "The result of EXTRACT_VECTOR_ELT must be at least as wide as the \
9012 element type of the vector.");
9013
9014 // Extract from an undefined value or using an undefined index is undefined.
9015 if (N1.isUndef() || N2.isUndef())
9016 return getUNDEF(VT);
9017
9018 // EXTRACT_VECTOR_ELT of out-of-bounds element is POISON for fixed length
9019 // vectors. For scalable vectors we will provide appropriate support for
9020 // dealing with arbitrary indices.
9021 if (N2C && N1.getValueType().isFixedLengthVector() &&
9022 N2C->getAPIntValue().uge(N1.getValueType().getVectorNumElements()))
9023 return getPOISON(VT);
9024
9025 // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
9026 // expanding copies of large vectors from registers. This only works for
9027 // fixed length vectors, since we need to know the exact number of
9028 // elements.
9029 if (N2C && N1.getOpcode() == ISD::CONCAT_VECTORS &&
9031 unsigned Factor = N1.getOperand(0).getValueType().getVectorNumElements();
9032 return getExtractVectorElt(DL, VT,
9033 N1.getOperand(N2C->getZExtValue() / Factor),
9034 N2C->getZExtValue() % Factor);
9035 }
9036
9037 // EXTRACT_VECTOR_ELT of BUILD_VECTOR or SPLAT_VECTOR is often formed while
9038 // lowering is expanding large vector constants.
9039 if (N2C && (N1.getOpcode() == ISD::BUILD_VECTOR ||
9040 N1.getOpcode() == ISD::SPLAT_VECTOR)) {
9043 "BUILD_VECTOR used for scalable vectors");
9044 unsigned Index =
9045 N1.getOpcode() == ISD::BUILD_VECTOR ? N2C->getZExtValue() : 0;
9046 SDValue Elt = N1.getOperand(Index);
9047
9048 if (VT != Elt.getValueType())
9049 // If the vector element type is not legal, the BUILD_VECTOR operands
9050 // are promoted and implicitly truncated, and the result implicitly
9051 // extended. Make that explicit here.
9052 Elt = getAnyExtOrTrunc(Elt, DL, VT);
9053
9054 return Elt;
9055 }
9056
9057 // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
9058 // operations are lowered to scalars.
9059 if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) {
9060 // If the indices are the same, return the inserted element else
9061 // if the indices are known different, extract the element from
9062 // the original vector.
9063 SDValue N1Op2 = N1.getOperand(2);
9065
9066 if (N1Op2C && N2C) {
9067 if (N1Op2C->getZExtValue() == N2C->getZExtValue()) {
9068 if (VT == N1.getOperand(1).getValueType())
9069 return N1.getOperand(1);
9070 if (VT.isFloatingPoint()) {
9072 return getFPExtendOrRound(N1.getOperand(1), DL, VT);
9073 }
9074 return getSExtOrTrunc(N1.getOperand(1), DL, VT);
9075 }
9076 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2);
9077 }
9078 }
9079
9080 // EXTRACT_VECTOR_ELT of v1iX EXTRACT_SUBVECTOR could be formed
9081 // when vector types are scalarized and v1iX is legal.
9082 // vextract (v1iX extract_subvector(vNiX, Idx)) -> vextract(vNiX,Idx).
9083 // Here we are completely ignoring the extract element index (N2),
9084 // which is fine for fixed width vectors, since any index other than 0
9085 // is undefined anyway. However, this cannot be ignored for scalable
9086 // vectors - in theory we could support this, but we don't want to do this
9087 // without a profitability check.
9088 if (N1.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
9090 N1.getValueType().getVectorNumElements() == 1) {
9091 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0),
9092 N1.getOperand(1));
9093 }
9094 break;
9096 assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!");
9097 assert(!N1.getValueType().isVector() && !VT.isVector() &&
9098 (N1.getValueType().isInteger() == VT.isInteger()) &&
9099 N1.getValueType() != VT &&
9100 "Wrong types for EXTRACT_ELEMENT!");
9101
9102 // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
9103 // 64-bit integers into 32-bit parts. Instead of building the extract of
9104 // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
9105 if (N1.getOpcode() == ISD::BUILD_PAIR)
9106 return N1.getOperand(N2C->getZExtValue());
9107
9108 // EXTRACT_ELEMENT of a constant int is also very common.
9109 if (N1C) {
9110 unsigned ElementSize = VT.getSizeInBits();
9111 unsigned Shift = ElementSize * N2C->getZExtValue();
9112 const APInt &Val = N1C->getAPIntValue();
9113 return getConstant(Val.extractBits(ElementSize, Shift), DL, VT);
9114 }
9115 break;
9117 [[maybe_unused]] EVT MaskVT = N2.getValueType();
9118 assert(VT == N1.getValueType() &&
9119 "VECTOR_SHUFFLE_VAR result and source types don't match.");
9120 assert(VT.isVector() && MaskVT.isVector() &&
9121 "VECTOR_SHUFFLE_VAR operands must be vectors.");
9123 "VECTOR_SHUFFLE_VAR mask must be a vector of integers.");
9125 "VECTOR_SHUFFLE_VAR mask has the wrong number of elements.");
9126 // The only in-range index is 0; any other index gives poison.
9128 return N1;
9129 break;
9130 }
9132 EVT N1VT = N1.getValueType();
9133 assert(VT.isVector() && N1VT.isVector() &&
9134 "Extract subvector VTs must be vectors!");
9136 "Extract subvector VTs must have the same element type!");
9137 assert((VT.isFixedLengthVector() || N1VT.isScalableVector()) &&
9138 "Cannot extract a scalable vector from a fixed length vector!");
9139 assert((VT.isScalableVector() != N1VT.isScalableVector() ||
9141 "Extract subvector must be from larger vector to smaller vector!");
9142 assert(N2C && "Extract subvector index must be a constant");
9143 assert((VT.isScalableVector() != N1VT.isScalableVector() ||
9144 (VT.getVectorMinNumElements() + N2C->getZExtValue()) <=
9145 N1VT.getVectorMinNumElements()) &&
9146 "Extract subvector overflow!");
9147 assert(N2C->getAPIntValue().getBitWidth() ==
9148 TLI->getVectorIdxWidth(getDataLayout()) &&
9149 "Constant index for EXTRACT_SUBVECTOR has an invalid size");
9150 assert(N2C->getZExtValue() % VT.getVectorMinNumElements() == 0 &&
9151 "Extract index is not a multiple of the output vector length");
9152
9153 // Trivial extraction.
9154 if (VT == N1VT)
9155 return N1;
9156
9157 // EXTRACT_SUBVECTOR of an UNDEF is an UNDEF.
9158 if (N1.isUndef())
9159 return getUNDEF(VT);
9160
9161 // EXTRACT_SUBVECTOR of CONCAT_VECTOR can be simplified if the pieces of
9162 // the concat have the same type as the extract.
9163 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
9164 VT == N1.getOperand(0).getValueType()) {
9165 unsigned Factor = VT.getVectorMinNumElements();
9166 return N1.getOperand(N2C->getZExtValue() / Factor);
9167 }
9168
9169 // EXTRACT_SUBVECTOR of INSERT_SUBVECTOR is often created
9170 // during shuffle legalization.
9171 if (N1.getOpcode() == ISD::INSERT_SUBVECTOR && N2 == N1.getOperand(2) &&
9172 VT == N1.getOperand(1).getValueType())
9173 return N1.getOperand(1);
9174 break;
9175 }
9176 }
9177
9178 if (N1.getOpcode() == ISD::POISON || N2.getOpcode() == ISD::POISON) {
9179 switch (Opcode) {
9180 case ISD::XOR:
9181 case ISD::ADD:
9182 case ISD::PTRADD:
9183 case ISD::SUB:
9185 case ISD::UDIV:
9186 case ISD::SDIV:
9187 case ISD::UREM:
9188 case ISD::SREM:
9189 case ISD::MUL:
9190 case ISD::AND:
9191 case ISD::SSUBSAT:
9192 case ISD::USUBSAT:
9193 case ISD::UMIN:
9194 case ISD::OR:
9195 case ISD::SADDSAT:
9196 case ISD::UADDSAT:
9197 case ISD::UMAX:
9198 case ISD::SMAX:
9199 case ISD::SMIN:
9200 // fold op(arg1, poison) -> poison, fold op(poison, arg2) -> poison.
9201 return N2.getOpcode() == ISD::POISON ? N2 : N1;
9202 }
9203 }
9204
9205 // Canonicalize an UNDEF to the RHS, even over a constant.
9206 if (N1.getOpcode() == ISD::UNDEF && N2.getOpcode() != ISD::UNDEF) {
9207 if (TLI->isCommutativeBinOp(Opcode)) {
9208 std::swap(N1, N2);
9209 } else {
9210 switch (Opcode) {
9211 case ISD::PTRADD:
9212 case ISD::SUB:
9213 // fold op(undef, non_undef_arg2) -> undef.
9214 return N1;
9216 case ISD::UDIV:
9217 case ISD::SDIV:
9218 case ISD::UREM:
9219 case ISD::SREM:
9220 case ISD::SSUBSAT:
9221 case ISD::USUBSAT:
9222 // fold op(undef, non_undef_arg2) -> 0.
9223 return getConstant(0, DL, VT);
9224 }
9225 }
9226 }
9227
9228 // Fold a bunch of operators when the RHS is undef.
9229 if (N2.getOpcode() == ISD::UNDEF) {
9230 switch (Opcode) {
9231 case ISD::XOR:
9232 if (N1.getOpcode() == ISD::UNDEF)
9233 // Handle undef ^ undef -> 0 special case. This is a common
9234 // idiom (misuse).
9235 return getConstant(0, DL, VT);
9236 [[fallthrough]];
9237 case ISD::ADD:
9238 case ISD::PTRADD:
9239 case ISD::SUB:
9240 // fold op(arg1, undef) -> undef.
9241 return N2;
9242 case ISD::UDIV:
9243 case ISD::SDIV:
9244 case ISD::UREM:
9245 case ISD::SREM:
9246 // fold op(arg1, undef) -> poison.
9247 return getPOISON(VT);
9248 case ISD::MUL:
9249 case ISD::AND:
9250 case ISD::SSUBSAT:
9251 case ISD::USUBSAT:
9252 case ISD::UMIN:
9253 // fold op(undef, undef) -> undef, fold op(arg1, undef) -> 0.
9254 return N1.getOpcode() == ISD::UNDEF ? N2 : getConstant(0, DL, VT);
9255 case ISD::OR:
9256 case ISD::SADDSAT:
9257 case ISD::UADDSAT:
9258 case ISD::UMAX:
9259 // fold op(undef, undef) -> undef, fold op(arg1, undef) -> -1.
9260 return N1.getOpcode() == ISD::UNDEF ? N2 : getAllOnesConstant(DL, VT);
9261 case ISD::SMAX:
9262 // fold op(undef, undef) -> undef, fold op(arg1, undef) -> MAX_INT.
9263 return N1.getOpcode() == ISD::UNDEF
9264 ? N2
9265 : getConstant(
9267 VT);
9268 case ISD::SMIN:
9269 // fold op(undef, undef) -> undef, fold op(arg1, undef) -> MIN_INT.
9270 return N1.getOpcode() == ISD::UNDEF
9271 ? N2
9272 : getConstant(
9274 VT);
9275 }
9276 }
9277
9278 // Perform trivial constant folding.
9279 if (SDValue SV = FoldConstantArithmetic(Opcode, DL, VT, {N1, N2}, Flags))
9280 return SV;
9281
9282 // Memoize this node if possible.
9283 SDNode *N;
9284 SDVTList VTs = getVTList(VT);
9285 SDValue Ops[] = {N1, N2};
9286 if (VT != MVT::Glue) {
9287 SDNodeKey ID(Opcode, VTs, Ops);
9288 FoldingSetInsertToken InsertToken;
9289 if (SDNode *E = lookupNode(ID, DL, InsertToken)) {
9290 E->intersectFlagsWith(Flags);
9291 return SDValue(E, 0);
9292 }
9293
9294 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
9295 N->setFlags(Flags);
9296 createOperands(N, Ops);
9297 CSEMap.insert(N, InsertToken);
9298 } else {
9299 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
9300 createOperands(N, Ops);
9301 }
9302
9303 InsertNode(N);
9304 SDValue V = SDValue(N, 0);
9305 NewSDValueDbgMsg(V, "Creating new node: ", this);
9306 return V;
9307}
9308
9309SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
9310 SDValue N1, SDValue N2, SDValue N3) {
9311 SDNodeFlags Flags;
9312 if (Inserter)
9313 Flags = Inserter->getFlags();
9314 return getNode(Opcode, DL, VT, N1, N2, N3, Flags);
9315}
9316
9317SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
9318 SDValue N1, SDValue N2, SDValue N3,
9319 const SDNodeFlags Flags) {
9321 N2.getOpcode() != ISD::DELETED_NODE &&
9322 N3.getOpcode() != ISD::DELETED_NODE &&
9323 "Operand is DELETED_NODE!");
9324 // Perform various simplifications.
9325 switch (Opcode) {
9326 case ISD::BUILD_VECTOR: {
9327 // Attempt to simplify BUILD_VECTOR.
9328 SDValue Ops[] = {N1, N2, N3};
9329 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
9330 return V;
9331 break;
9332 }
9333 case ISD::CONCAT_VECTORS: {
9334 SDValue Ops[] = {N1, N2, N3};
9335 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
9336 return V;
9337 break;
9338 }
9339 case ISD::SETCC: {
9340 assert(VT.isInteger() && "SETCC result type must be an integer!");
9341 assert(N1.getValueType() == N2.getValueType() &&
9342 "SETCC operands must have the same type!");
9343 assert(VT.isVector() == N1.getValueType().isVector() &&
9344 "SETCC type should be vector iff the operand type is vector!");
9345 assert((!VT.isVector() || VT.getVectorElementCount() ==
9347 "SETCC vector element counts must match!");
9348 // Use FoldSetCC to simplify SETCC's.
9349 if (SDValue V =
9350 FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL, Flags))
9351 return V;
9352 break;
9353 }
9354 case ISD::SELECT:
9355 case ISD::VSELECT:
9356 if (SDValue V = simplifySelect(N1, N2, N3))
9357 return V;
9358 break;
9360 llvm_unreachable("should use getVectorShuffle constructor!");
9362 if (isNullConstant(N3))
9363 return N1;
9364 break;
9366 if (isNullConstant(N3))
9367 return N2;
9368 break;
9370 assert(VT.isVector() && VT == N1.getValueType() &&
9371 "INSERT_VECTOR_ELT vector type mismatch");
9373 "INSERT_VECTOR_ELT scalar fp/int mismatch");
9374 assert((!VT.isFloatingPoint() ||
9375 VT.getVectorElementType() == N2.getValueType()) &&
9376 "INSERT_VECTOR_ELT fp scalar type mismatch");
9377 assert((!VT.isInteger() ||
9379 "INSERT_VECTOR_ELT int scalar size mismatch");
9380
9381 auto *N3C = dyn_cast<ConstantSDNode>(N3);
9382 // INSERT_VECTOR_ELT into out-of-bounds element is an UNDEF, except
9383 // for scalable vectors where we will generate appropriate code to
9384 // deal with out-of-bounds cases correctly.
9385 if (N3C && VT.isFixedLengthVector() &&
9386 N3C->getZExtValue() >= VT.getVectorNumElements())
9387 return getUNDEF(VT);
9388
9389 // Undefined index can be assumed out-of-bounds, so that's UNDEF too.
9390 if (N3.isUndef())
9391 return getUNDEF(VT);
9392
9393 // If inserting poison, just use the input vector.
9394 if (N2.getOpcode() == ISD::POISON)
9395 return N1;
9396
9397 // Inserting undef into undef/poison is still undef.
9398 if (N2.getOpcode() == ISD::UNDEF && N1.isUndef())
9399 return getUNDEF(VT);
9400
9401 // If the inserted element is an UNDEF, just use the input vector.
9402 // But not if skipping the insert could make the result more poisonous.
9403 if (N2.isUndef()) {
9404 if (N3C && VT.isFixedLengthVector()) {
9405 APInt EltMask =
9406 APInt::getOneBitSet(VT.getVectorNumElements(), N3C->getZExtValue());
9407 if (isGuaranteedNotToBePoison(N1, EltMask))
9408 return N1;
9409 } else if (isGuaranteedNotToBePoison(N1))
9410 return N1;
9411 }
9412 break;
9413 }
9414 case ISD::INSERT_SUBVECTOR: {
9415 // If inserting poison, just use the input vector,
9416 if (N2.getOpcode() == ISD::POISON)
9417 return N1;
9418
9419 // Inserting undef into undef/poison is still undef.
9420 if (N2.getOpcode() == ISD::UNDEF && N1.isUndef())
9421 return getUNDEF(VT);
9422
9423 EVT N2VT = N2.getValueType();
9424 assert(VT == N1.getValueType() &&
9425 "Dest and insert subvector source types must match!");
9426 assert(VT.isVector() && N2VT.isVector() &&
9427 "Insert subvector VTs must be vectors!");
9429 "Insert subvector VTs must have the same element type!");
9430 assert((VT.isScalableVector() || N2VT.isFixedLengthVector()) &&
9431 "Cannot insert a scalable vector into a fixed length vector!");
9432 assert((VT.isScalableVector() != N2VT.isScalableVector() ||
9434 "Insert subvector must be from smaller vector to larger vector!");
9436 "Insert subvector index must be constant");
9437 assert((VT.isScalableVector() != N2VT.isScalableVector() ||
9438 (N2VT.getVectorMinNumElements() + N3->getAsZExtVal()) <=
9440 "Insert subvector overflow!");
9442 TLI->getVectorIdxWidth(getDataLayout()) &&
9443 "Constant index for INSERT_SUBVECTOR has an invalid size");
9444
9445 // Trivial insertion.
9446 if (VT == N2VT)
9447 return N2;
9448
9449 // If this is an insert of an extracted vector into an undef/poison vector,
9450 // we can just use the input to the extract. But not if skipping the
9451 // extract+insert could make the result more poisonous.
9452 if (N1.isUndef() && N2.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
9453 N2.getOperand(1) == N3 && N2.getOperand(0).getValueType() == VT) {
9454 if (N1.getOpcode() == ISD::POISON)
9455 return N2.getOperand(0);
9456 if (VT.isFixedLengthVector() && N2VT.isFixedLengthVector()) {
9457 unsigned LoBit = N3->getAsZExtVal();
9458 unsigned HiBit = LoBit + N2VT.getVectorNumElements();
9459 APInt EltMask =
9460 APInt::getBitsSet(VT.getVectorNumElements(), LoBit, HiBit);
9461 if (isGuaranteedNotToBePoison(N2.getOperand(0), ~EltMask))
9462 return N2.getOperand(0);
9463 } else if (isGuaranteedNotToBePoison(N2.getOperand(0)))
9464 return N2.getOperand(0);
9465 }
9466
9467 // If the inserted subvector is UNDEF, just use the input vector.
9468 // But not if skipping the insert could make the result more poisonous.
9469 if (N2.isUndef()) {
9470 if (VT.isFixedLengthVector()) {
9471 unsigned LoBit = N3->getAsZExtVal();
9472 unsigned HiBit = LoBit + N2VT.getVectorNumElements();
9473 APInt EltMask =
9474 APInt::getBitsSet(VT.getVectorNumElements(), LoBit, HiBit);
9475 if (isGuaranteedNotToBePoison(N1, EltMask))
9476 return N1;
9477 } else if (isGuaranteedNotToBePoison(N1))
9478 return N1;
9479 }
9480 break;
9481 }
9482 case ISD::BITCAST:
9483 // Fold bit_convert nodes from a type to themselves.
9484 if (N1.getValueType() == VT)
9485 return N1;
9486 break;
9487 case ISD::VECTOR_COMPRESS: {
9488 [[maybe_unused]] EVT VecVT = N1.getValueType();
9489 [[maybe_unused]] EVT MaskVT = N2.getValueType();
9490 [[maybe_unused]] EVT PassthruVT = N3.getValueType();
9491 assert(VT == VecVT && "Vector and result type don't match.");
9492 assert(VecVT.isVector() && MaskVT.isVector() && PassthruVT.isVector() &&
9493 "All inputs must be vectors.");
9494 assert(VecVT == PassthruVT && "Vector and passthru types don't match.");
9496 "Vector and mask must have same number of elements.");
9497
9498 if (N1.isUndef() || N2.isUndef())
9499 return N3;
9500
9501 break;
9502 }
9507 [[maybe_unused]] EVT AccVT = N1.getValueType();
9508 [[maybe_unused]] EVT Input1VT = N2.getValueType();
9509 [[maybe_unused]] EVT Input2VT = N3.getValueType();
9510 assert(Input1VT.isVector() && Input1VT == Input2VT &&
9511 "Expected the second and third operands of the PARTIAL_REDUCE_MLA "
9512 "node to have the same type!");
9513 assert(VT.isVector() && VT == AccVT &&
9514 "Expected the first operand of the PARTIAL_REDUCE_MLA node to have "
9515 "the same type as its result!");
9517 AccVT.getVectorElementCount()) &&
9518 "Expected the element count of the second and third operands of the "
9519 "PARTIAL_REDUCE_MLA node to be a positive integer multiple of the "
9520 "element count of the first operand and the result!");
9522 "Expected the second and third operands of the PARTIAL_REDUCE_MLA "
9523 "node to have an element type which is the same as or smaller than "
9524 "the element type of the first operand and result!");
9525 break;
9526 }
9527 }
9528
9529 // Perform trivial constant folding for arithmetic operators.
9530 switch (Opcode) {
9534 case ISD::FMA:
9535 case ISD::FMAD:
9536 case ISD::SETCC:
9537 case ISD::FSHL:
9538 case ISD::FSHR:
9539 if (SDValue SV =
9540 FoldConstantArithmetic(Opcode, DL, VT, {N1, N2, N3}, Flags))
9541 return SV;
9542 break;
9543 }
9544
9545 // Memoize node if it doesn't produce a glue result.
9546 SDNode *N;
9547 SDVTList VTs = getVTList(VT);
9548 SDValue Ops[] = {N1, N2, N3};
9549 if (VT != MVT::Glue) {
9550 SDNodeKey ID(Opcode, VTs, Ops);
9551 FoldingSetInsertToken InsertToken;
9552 if (SDNode *E = lookupNode(ID, DL, InsertToken)) {
9553 E->intersectFlagsWith(Flags);
9554 return SDValue(E, 0);
9555 }
9556
9557 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
9558 N->setFlags(Flags);
9559 createOperands(N, Ops);
9560 CSEMap.insert(N, InsertToken);
9561 } else {
9562 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
9563 createOperands(N, Ops);
9564 }
9565
9566 InsertNode(N);
9567 SDValue V = SDValue(N, 0);
9568 NewSDValueDbgMsg(V, "Creating new node: ", this);
9569 return V;
9570}
9571
9572SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
9573 SDValue N1, SDValue N2, SDValue N3, SDValue N4,
9574 const SDNodeFlags Flags) {
9575 SDValue Ops[] = { N1, N2, N3, N4 };
9576 return getNode(Opcode, DL, VT, Ops, Flags);
9577}
9578
9579SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
9580 SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
9581 SDNodeFlags Flags;
9582 if (Inserter)
9583 Flags = Inserter->getFlags();
9584 return getNode(Opcode, DL, VT, N1, N2, N3, N4, Flags);
9585}
9586
9587SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
9588 SDValue N1, SDValue N2, SDValue N3, SDValue N4,
9589 SDValue N5, const SDNodeFlags Flags) {
9590 SDValue Ops[] = { N1, N2, N3, N4, N5 };
9591 return getNode(Opcode, DL, VT, Ops, Flags);
9592}
9593
9594SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
9595 SDValue N1, SDValue N2, SDValue N3, SDValue N4,
9596 SDValue N5) {
9597 SDNodeFlags Flags;
9598 if (Inserter)
9599 Flags = Inserter->getFlags();
9600 return getNode(Opcode, DL, VT, N1, N2, N3, N4, N5, Flags);
9601}
9602
9603/// getStackArgumentTokenFactor - Compute a TokenFactor to force all
9604/// the incoming stack arguments to be loaded from the stack.
9606 SmallVector<SDValue, 8> ArgChains;
9607
9608 // Include the original chain at the beginning of the list. When this is
9609 // used by target LowerCall hooks, this helps legalize find the
9610 // CALLSEQ_BEGIN node.
9611 ArgChains.push_back(Chain);
9612
9613 // Add a chain value for each stack argument.
9614 for (SDNode *U : getEntryNode().getNode()->users())
9615 if (LoadSDNode *L = dyn_cast<LoadSDNode>(U))
9616 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
9617 if (FI->getIndex() < 0)
9618 ArgChains.push_back(SDValue(L, 1));
9619
9620 // Build a tokenfactor for all the chains.
9621 return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
9622}
9623
9624/// getMemsetValue - Vectorized representation of the memset value
9625/// operand.
9627 const SDLoc &dl) {
9628 assert(!Value.isUndef());
9629
9630 unsigned NumBits = VT.getScalarSizeInBits();
9632 assert(C->getAPIntValue().getBitWidth() == 8);
9633 APInt Val = APInt::getSplat(NumBits, C->getAPIntValue());
9634 if (VT.isInteger()) {
9635 bool IsOpaque = VT.getSizeInBits() > 64 ||
9636 !DAG.getTargetLoweringInfo().isLegalStoreImmediate(C->getSExtValue());
9637 return DAG.getConstant(Val, dl, VT, false, IsOpaque);
9638 }
9639 return DAG.getConstantFP(APFloat(VT.getFltSemantics(), Val), dl, VT);
9640 }
9641
9642 assert(Value.getValueType() == MVT::i8 && "memset with non-byte fill value?");
9643 EVT IntVT = VT.getScalarType();
9644 if (!IntVT.isInteger())
9645 IntVT = EVT::getIntegerVT(*DAG.getContext(), IntVT.getSizeInBits());
9646
9647 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, Value);
9648 if (NumBits > 8) {
9649 // Use a multiplication with 0x010101... to extend the input to the
9650 // required length.
9651 APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01));
9652 Value = DAG.getNode(ISD::MUL, dl, IntVT, Value,
9653 DAG.getConstant(Magic, dl, IntVT));
9654 }
9655
9656 if (VT != Value.getValueType() && !VT.isInteger())
9657 Value = DAG.getBitcast(VT.getScalarType(), Value);
9658 if (VT != Value.getValueType())
9659 Value = DAG.getSplatBuildVector(VT, dl, Value);
9660
9661 return Value;
9662}
9663
9664/// getMemsetStringVal - Similar to getMemsetValue. Except this is only
9665/// used when a memcpy is turned into a memset when the source is a constant
9666/// string ptr.
9668 const TargetLowering &TLI,
9669 const ConstantDataArraySlice &Slice) {
9670 // Handle vector with all elements zero.
9671 if (Slice.Array == nullptr) {
9672 if (VT.isInteger())
9673 return DAG.getConstant(0, dl, VT);
9674 return DAG.getNode(ISD::BITCAST, dl, VT,
9675 DAG.getConstant(0, dl, VT.changeTypeToInteger()));
9676 }
9677
9678 assert(!VT.isVector() && "Can't handle vector type here!");
9679 unsigned NumVTBits = VT.getSizeInBits();
9680 unsigned NumVTBytes = NumVTBits / 8;
9681 unsigned NumBytes = std::min(NumVTBytes, unsigned(Slice.Length));
9682
9683 APInt Val(NumVTBits, 0);
9684 if (DAG.getDataLayout().isLittleEndian()) {
9685 for (unsigned i = 0; i != NumBytes; ++i)
9686 Val |= (uint64_t)(unsigned char)Slice[i] << i*8;
9687 } else {
9688 for (unsigned i = 0; i != NumBytes; ++i)
9689 Val |= (uint64_t)(unsigned char)Slice[i] << (NumVTBytes-i-1)*8;
9690 }
9691
9692 // If the "cost" of materializing the integer immediate is less than the cost
9693 // of a load, then it is cost effective to turn the load into the immediate.
9694 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
9695 if (TLI.shouldConvertConstantLoadToIntImm(Val, Ty))
9696 return DAG.getConstant(Val, dl, VT);
9697 return SDValue();
9698}
9699
9701 const SDLoc &DL,
9702 const SDNodeFlags Flags) {
9703 SDValue Index = getTypeSize(DL, Base.getValueType(), Offset);
9704 return getMemBasePlusOffset(Base, Index, DL, Flags);
9705}
9706
9708 const SDLoc &DL,
9709 const SDNodeFlags Flags) {
9710 assert(Offset.getValueType().isInteger());
9711 EVT BasePtrVT = Ptr.getValueType();
9712 if (TLI->shouldPreservePtrArith(this->getMachineFunction().getFunction(),
9713 BasePtrVT))
9714 return getNode(ISD::PTRADD, DL, BasePtrVT, Ptr, Offset, Flags);
9715 // InBounds only applies to PTRADD, don't set it if we generate ADD.
9716 SDNodeFlags AddFlags = Flags;
9717 AddFlags.setInBounds(false);
9718 return getNode(ISD::ADD, DL, BasePtrVT, Ptr, Offset, AddFlags);
9719}
9720
9721/// Returns true if memcpy source is constant data.
9723 uint64_t SrcDelta = 0;
9724 GlobalAddressSDNode *G = nullptr;
9725 if (Src.getOpcode() == ISD::GlobalAddress)
9727 else if (Src->isAnyAdd() &&
9728 Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
9729 Src.getOperand(1).getOpcode() == ISD::Constant) {
9730 G = cast<GlobalAddressSDNode>(Src.getOperand(0));
9731 SrcDelta = Src.getConstantOperandVal(1);
9732 }
9733 if (!G)
9734 return false;
9735
9736 return getConstantDataArrayInfo(G->getGlobal(), Slice, 8,
9737 SrcDelta + G->getOffset());
9738}
9739
9741 SelectionDAG &DAG) {
9742 // On Darwin, -Os means optimize for size without hurting performance, so
9743 // only really optimize for size when -Oz (MinSize) is used.
9745 return MF.getFunction().hasMinSize();
9746 return DAG.shouldOptForSize();
9747}
9748
9750 SmallVector<SDValue, 32> &OutChains, unsigned From,
9751 unsigned To, SmallVector<SDValue, 16> &OutLoadChains,
9752 SmallVector<SDValue, 16> &OutStoreChains) {
9753 assert(OutLoadChains.size() && "Missing loads in memcpy inlining");
9754 assert(OutStoreChains.size() && "Missing stores in memcpy inlining");
9755 SmallVector<SDValue, 16> GluedLoadChains;
9756 for (unsigned i = From; i < To; ++i) {
9757 OutChains.push_back(OutLoadChains[i]);
9758 GluedLoadChains.push_back(OutLoadChains[i]);
9759 }
9760
9761 // Chain for all loads.
9762 SDValue LoadToken = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
9763 GluedLoadChains);
9764
9765 for (unsigned i = From; i < To; ++i) {
9766 StoreSDNode *ST = dyn_cast<StoreSDNode>(OutStoreChains[i]);
9767 SDValue NewStore = DAG.getTruncStore(LoadToken, dl, ST->getValue(),
9768 ST->getBasePtr(), ST->getMemoryVT(),
9769 ST->getMemOperand());
9770 OutChains.push_back(NewStore);
9771 }
9772}
9773
9774static SDValue
9776 SDValue Dst, SDValue Src, uint64_t Size, Align DstAlign,
9777 Align SrcAlign, bool isVol, bool AlwaysInline,
9778 MachinePointerInfo DstPtrInfo,
9779 MachinePointerInfo SrcPtrInfo, const AAMDNodes &AAInfo,
9780 BatchAAResults *BatchAA, const MDNode *DstMemCacheHint,
9781 const MDNode *SrcMemCacheHint) {
9782 // Turn a memcpy of undef to nop.
9783 // FIXME: We need to honor volatile even is Src is undef.
9784 if (Src.isUndef())
9785 return Chain;
9786
9787 // Expand memcpy to a series of load and store ops if the size operand falls
9788 // below a certain threshold.
9789 // TODO: In the AlwaysInline case, if the size is big then generate a loop
9790 // rather than maybe a humongous number of loads and stores.
9792 const DataLayout &DL = DAG.getDataLayout();
9793 LLVMContext &C = *DAG.getContext();
9794 std::vector<EVT> MemOps;
9795 bool DstAlignCanChange = false;
9797 MachineFrameInfo &MFI = MF.getFrameInfo();
9798 bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
9800 if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
9801 DstAlignCanChange = true;
9802 SrcAlign = std::max(SrcAlign, DAG.InferPtrAlign(Src).valueOrOne());
9804 // If marked as volatile, perform a copy even when marked as constant.
9805 bool CopyFromConstant = !isVol && isMemSrcFromConstant(Src, Slice);
9806 bool isZeroConstant = CopyFromConstant && Slice.Array == nullptr;
9807 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize);
9808 const MemOp Op = isZeroConstant
9809 ? MemOp::Set(Size, DstAlignCanChange, DstAlign,
9810 /*IsZeroMemset*/ true, isVol)
9811 : MemOp::Copy(Size, DstAlignCanChange, DstAlign,
9812 SrcAlign, isVol, CopyFromConstant);
9813 if (!TLI.findOptimalMemOpLowering(
9814 C, MemOps, Limit, Op, DstPtrInfo.getAddrSpace(),
9815 SrcPtrInfo.getAddrSpace(), MF.getFunction().getAttributes(), nullptr))
9816 return SDValue();
9817
9818 if (DstAlignCanChange) {
9819 Type *Ty = MemOps[0].getTypeForEVT(C);
9820 Align NewDstAlign = DL.getABITypeAlign(Ty);
9821
9822 // Don't promote to an alignment that would require dynamic stack
9823 // realignment which may conflict with optimizations such as tail call
9824 // optimization.
9826 if (!TRI->hasStackRealignment(MF))
9827 if (MaybeAlign StackAlign = DL.getStackAlignment())
9828 NewDstAlign = std::min(NewDstAlign, *StackAlign);
9829
9830 if (NewDstAlign > DstAlign) {
9831 // Give the stack frame object a larger alignment if needed.
9832 if (MFI.getObjectAlign(FI->getIndex()) < NewDstAlign)
9833 MFI.setObjectAlignment(FI->getIndex(), NewDstAlign);
9834 DstAlign = NewDstAlign;
9835 }
9836 }
9837
9838 // Prepare AAInfo for loads/stores after lowering this memcpy.
9839 AAMDNodes NewAAInfo = AAInfo;
9840 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
9841
9842 const Value *SrcVal = dyn_cast_if_present<const Value *>(SrcPtrInfo.V);
9843 bool isConstant =
9844 BatchAA && SrcVal &&
9845 BatchAA->pointsToConstantMemory(MemoryLocation(SrcVal, Size, AAInfo));
9846
9847 MachineMemOperand::Flags MMOFlags =
9849 SmallVector<SDValue, 16> OutLoadChains;
9850 SmallVector<SDValue, 16> OutStoreChains;
9851 SmallVector<SDValue, 32> OutChains;
9852 unsigned NumMemOps = MemOps.size();
9853 uint64_t SrcOff = 0, DstOff = 0;
9854 for (unsigned i = 0; i != NumMemOps; ++i) {
9855 EVT VT = MemOps[i];
9856 unsigned VTSize = VT.getSizeInBits() / 8;
9858
9859 if (VTSize > Size) {
9860 // Issuing an unaligned load / store pair that overlaps with the previous
9861 // pair. Adjust the offset accordingly.
9862 assert(i == NumMemOps-1 && i != 0);
9863 SrcOff -= VTSize - Size;
9864 DstOff -= VTSize - Size;
9865 }
9866
9867 if (CopyFromConstant &&
9868 (isZeroConstant || (VT.isInteger() && !VT.isVector()))) {
9869 // It's unlikely a store of a vector immediate can be done in a single
9870 // instruction. It would require a load from a constantpool first.
9871 // We only handle zero vectors here.
9872 // FIXME: Handle other cases where store of vector immediate is done in
9873 // a single instruction.
9874 ConstantDataArraySlice SubSlice;
9875 if (SrcOff < Slice.Length) {
9876 SubSlice = Slice;
9877 SubSlice.move(SrcOff);
9878 } else {
9879 // This is an out-of-bounds access and hence UB. Pretend we read zero.
9880 SubSlice.Array = nullptr;
9881 SubSlice.Offset = 0;
9882 SubSlice.Length = VTSize;
9883 }
9884 Value = getMemsetStringVal(VT, dl, DAG, TLI, SubSlice);
9885 if (Value.getNode()) {
9886 Store = DAG.getStore(
9887 Chain, dl, Value,
9888 DAG.getObjectPtrOffset(dl, Dst, TypeSize::getFixed(DstOff)),
9889 DstPtrInfo.getWithOffset(DstOff), DstAlign, MMOFlags,
9890 MMOMetadata(NewAAInfo, /*Ranges=*/nullptr, DstMemCacheHint));
9891 OutChains.push_back(Store);
9892 }
9893 }
9894
9895 if (!Store.getNode()) {
9896 // The type might not be legal for the target. This should only happen
9897 // if the type is smaller than a legal type, as on PPC, so the right
9898 // thing to do is generate a LoadExt/StoreTrunc pair. These simplify
9899 // to Load/Store if NVT==VT.
9900 // FIXME does the case above also need this?
9901 EVT NVT = TLI.getTypeToTransformTo(C, VT);
9902 assert(NVT.bitsGE(VT));
9903
9904 bool isDereferenceable =
9905 SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
9906 MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
9907 if (isDereferenceable)
9909 if (isConstant)
9910 SrcMMOFlags |= MachineMemOperand::MOInvariant;
9911
9912 Value = DAG.getExtLoad(
9913 ISD::EXTLOAD, dl, NVT, Chain,
9914 DAG.getObjectPtrOffset(dl, Src, TypeSize::getFixed(SrcOff)),
9915 SrcPtrInfo.getWithOffset(SrcOff), VT,
9916 commonAlignment(SrcAlign, SrcOff), SrcMMOFlags,
9917 MMOMetadata(NewAAInfo, /*Ranges=*/nullptr, SrcMemCacheHint));
9918 OutLoadChains.push_back(Value.getValue(1));
9919
9920 Store = DAG.getTruncStore(
9921 Chain, dl, Value,
9922 DAG.getObjectPtrOffset(dl, Dst, TypeSize::getFixed(DstOff)),
9923 DstPtrInfo.getWithOffset(DstOff), VT, DstAlign, MMOFlags,
9924 MMOMetadata(NewAAInfo, /*Ranges=*/nullptr, DstMemCacheHint));
9925 OutStoreChains.push_back(Store);
9926 }
9927 SrcOff += VTSize;
9928 DstOff += VTSize;
9929 Size -= VTSize;
9930 }
9931
9932 unsigned MaxLdStGlue = DAG.getSelectionDAGOptions().ldstmemcpy_glue_max;
9933 unsigned GluedLdStLimit =
9934 MaxLdStGlue == 0 ? TLI.getMaxGluedStoresPerMemcpy() : MaxLdStGlue;
9935 unsigned NumLdStInMemcpy = OutStoreChains.size();
9936
9937 if (NumLdStInMemcpy) {
9938 // It may be that memcpy might be converted to memset if it's memcpy
9939 // of constants. In such a case, we won't have loads and stores, but
9940 // just stores. In the absence of loads, there is nothing to gang up.
9941 if ((GluedLdStLimit <= 1) ||
9942 !DAG.getSelectionDAGOptions().enable_memcpy_dag_opt) {
9943 // If target does not care, just leave as it.
9944 for (unsigned i = 0; i < NumLdStInMemcpy; ++i) {
9945 OutChains.push_back(OutLoadChains[i]);
9946 OutChains.push_back(OutStoreChains[i]);
9947 }
9948 } else {
9949 // Ld/St less than/equal limit set by target.
9950 if (NumLdStInMemcpy <= GluedLdStLimit) {
9951 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
9952 NumLdStInMemcpy, OutLoadChains,
9953 OutStoreChains);
9954 } else {
9955 unsigned NumberLdChain = NumLdStInMemcpy / GluedLdStLimit;
9956 unsigned RemainingLdStInMemcpy = NumLdStInMemcpy % GluedLdStLimit;
9957 unsigned GlueIter = 0;
9958
9959 // Residual ld/st.
9960 if (RemainingLdStInMemcpy) {
9962 DAG, dl, OutChains, NumLdStInMemcpy - RemainingLdStInMemcpy,
9963 NumLdStInMemcpy, OutLoadChains, OutStoreChains);
9964 }
9965
9966 for (unsigned cnt = 0; cnt < NumberLdChain; ++cnt) {
9967 unsigned IndexFrom = NumLdStInMemcpy - RemainingLdStInMemcpy -
9968 GlueIter - GluedLdStLimit;
9969 unsigned IndexTo = NumLdStInMemcpy - RemainingLdStInMemcpy - GlueIter;
9970 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, IndexFrom, IndexTo,
9971 OutLoadChains, OutStoreChains);
9972 GlueIter += GluedLdStLimit;
9973 }
9974 }
9975 }
9976 }
9977 return DAG.getTokenFactor(dl, OutChains);
9978}
9979
9981 SelectionDAG &DAG, const SDLoc &dl, SDValue Chain, SDValue Dst, SDValue Src,
9982 uint64_t Size, Align DstAlign, Align SrcAlign, bool isVol,
9983 bool AlwaysInline, MachinePointerInfo DstPtrInfo,
9984 MachinePointerInfo SrcPtrInfo, const AAMDNodes &AAInfo) {
9985 // Turn a memmove of undef to nop.
9986 // FIXME: We need to honor volatile even is Src is undef.
9987 if (Src.isUndef())
9988 return Chain;
9989
9990 // Expand memmove to a series of load and store ops if the size operand falls
9991 // below a certain threshold.
9993 const DataLayout &DL = DAG.getDataLayout();
9994 LLVMContext &C = *DAG.getContext();
9995 std::vector<EVT> MemOps;
9996 bool DstAlignCanChange = false;
9998 MachineFrameInfo &MFI = MF.getFrameInfo();
9999 bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
10001 if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
10002 DstAlignCanChange = true;
10003 SrcAlign = std::max(SrcAlign, DAG.InferPtrAlign(Src).valueOrOne());
10004 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize);
10005 if (!TLI.findOptimalMemOpLowering(
10006 C, MemOps, Limit,
10007 MemOp::Move(Size, DstAlignCanChange, DstAlign, SrcAlign, isVol),
10008 DstPtrInfo.getAddrSpace(), SrcPtrInfo.getAddrSpace(),
10009 MF.getFunction().getAttributes(), nullptr))
10010 return SDValue();
10011
10012 if (DstAlignCanChange) {
10013 Type *Ty = MemOps[0].getTypeForEVT(C);
10014 Align NewDstAlign = DL.getABITypeAlign(Ty);
10015
10016 // Don't promote to an alignment that would require dynamic stack
10017 // realignment which may conflict with optimizations such as tail call
10018 // optimization.
10020 if (!TRI->hasStackRealignment(MF))
10021 if (MaybeAlign StackAlign = DL.getStackAlignment())
10022 NewDstAlign = std::min(NewDstAlign, *StackAlign);
10023
10024 if (NewDstAlign > DstAlign) {
10025 // Give the stack frame object a larger alignment if needed.
10026 if (MFI.getObjectAlign(FI->getIndex()) < NewDstAlign)
10027 MFI.setObjectAlignment(FI->getIndex(), NewDstAlign);
10028 DstAlign = NewDstAlign;
10029 }
10030 }
10031
10032 // Prepare AAInfo for loads/stores after lowering this memmove.
10033 AAMDNodes NewAAInfo = AAInfo;
10034 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
10035
10036 MachineMemOperand::Flags MMOFlags =
10038 uint64_t SrcOff = 0;
10039 SmallVector<SDValue, 8> LoadValues;
10040 SmallVector<SDValue, 8> LoadChains;
10041 SmallVector<SDValue, 8> OutChains;
10042 unsigned NumMemOps = MemOps.size();
10043 for (unsigned i = 0; i < NumMemOps; i++) {
10044 EVT VT = MemOps[i];
10045 unsigned VTSize = VT.getSizeInBits() / 8;
10046 SDValue Value;
10047 bool IsOverlapping = false;
10048
10049 if (i == NumMemOps - 1 && i != 0 && VTSize > Size - SrcOff) {
10050 // Issuing an unaligned load / store pair that overlaps with the previous
10051 // pair. Adjust the offset accordingly.
10052 SrcOff = Size - VTSize;
10053 IsOverlapping = true;
10054 }
10055
10056 // Calculate the actual alignment at the current offset. The alignment at
10057 // SrcOff may be lower than the base alignment, especially when using
10058 // overlapping loads.
10059 Align SrcAlignAtOffset = commonAlignment(SrcAlign, SrcOff);
10060 if (IsOverlapping) {
10061 // Verify that the target allows misaligned memory accesses at the
10062 // adjusted offset when using overlapping loads.
10063 unsigned Fast;
10064 if (!TLI.allowsMisalignedMemoryAccesses(VT, SrcPtrInfo.getAddrSpace(),
10065 SrcAlignAtOffset, MMOFlags,
10066 &Fast) ||
10067 !Fast) {
10068 // This should have been caught by findOptimalMemOpLowering, but verify
10069 // here for safety.
10070 return SDValue();
10071 }
10072 }
10073
10074 bool isDereferenceable =
10075 SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
10076 MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
10077 if (isDereferenceable)
10079 Value =
10080 DAG.getLoad(VT, dl, Chain,
10081 DAG.getObjectPtrOffset(dl, Src, TypeSize::getFixed(SrcOff)),
10082 SrcPtrInfo.getWithOffset(SrcOff), SrcAlignAtOffset,
10083 SrcMMOFlags, NewAAInfo);
10084 LoadValues.push_back(Value);
10085 LoadChains.push_back(Value.getValue(1));
10086 SrcOff += VTSize;
10087 }
10088 Chain = DAG.getTokenFactor(dl, LoadChains);
10089 OutChains.clear();
10090 uint64_t DstOff = 0;
10091 for (unsigned i = 0; i < NumMemOps; i++) {
10092 EVT VT = MemOps[i];
10093 unsigned VTSize = VT.getSizeInBits() / 8;
10094 SDValue Store;
10095 bool IsOverlapping = false;
10096
10097 if (i == NumMemOps - 1 && i != 0 && VTSize > Size - DstOff) {
10098 // Issuing an unaligned load / store pair that overlaps with the previous
10099 // pair. Adjust the offset accordingly.
10100 DstOff = Size - VTSize;
10101 IsOverlapping = true;
10102 }
10103
10104 // Calculate the actual alignment at the current offset. The alignment at
10105 // DstOff may be lower than the base alignment, especially when using
10106 // overlapping stores.
10107 Align DstAlignAtOffset = commonAlignment(DstAlign, DstOff);
10108 if (IsOverlapping) {
10109 // Verify that the target allows misaligned memory accesses at the
10110 // adjusted offset when using overlapping stores.
10111 unsigned Fast;
10112 if (!TLI.allowsMisalignedMemoryAccesses(VT, DstPtrInfo.getAddrSpace(),
10113 DstAlignAtOffset, MMOFlags,
10114 &Fast) ||
10115 !Fast) {
10116 // This should have been caught by findOptimalMemOpLowering, but verify
10117 // here for safety.
10118 return SDValue();
10119 }
10120 }
10121 Store = DAG.getStore(
10122 Chain, dl, LoadValues[i],
10123 DAG.getObjectPtrOffset(dl, Dst, TypeSize::getFixed(DstOff)),
10124 DstPtrInfo.getWithOffset(DstOff), DstAlignAtOffset, MMOFlags,
10125 NewAAInfo);
10126 OutChains.push_back(Store);
10127 DstOff += VTSize;
10128 }
10129
10130 return DAG.getTokenFactor(dl, OutChains);
10131}
10132
10133/// Lower the call to 'memset' intrinsic function into a series of store
10134/// operations.
10135///
10136/// \param DAG Selection DAG where lowered code is placed.
10137/// \param dl Link to corresponding IR location.
10138/// \param Chain Control flow dependency.
10139/// \param Dst Pointer to destination memory location.
10140/// \param Src Value of byte to write into the memory.
10141/// \param Size Number of bytes to write.
10142/// \param Alignment Alignment of the destination in bytes.
10143/// \param isVol True if destination is volatile.
10144/// \param AlwaysInline Makes sure no function call is generated.
10145/// \param DstPtrInfo IR information on the memory pointer.
10146/// \returns New head in the control flow, if lowering was successful, empty
10147/// SDValue otherwise.
10148///
10149/// The function tries to replace 'llvm.memset' intrinsic with several store
10150/// operations and value calculation code. This is usually profitable for small
10151/// memory size or when the semantic requires inlining.
10153 SDValue Chain, SDValue Dst, SDValue Src,
10154 uint64_t Size, Align Alignment, bool isVol,
10155 bool AlwaysInline, MachinePointerInfo DstPtrInfo,
10156 const AAMDNodes &AAInfo) {
10157 // Turn a memset of undef to nop.
10158 // FIXME: We need to honor volatile even is Src is undef.
10159 if (Src.isUndef())
10160 return Chain;
10161
10162 // Expand memset to a series of load/store ops if the size operand
10163 // falls below a certain threshold.
10165 std::vector<EVT> MemOps;
10166 bool DstAlignCanChange = false;
10167 LLVMContext &C = *DAG.getContext();
10169 MachineFrameInfo &MFI = MF.getFrameInfo();
10170 bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
10172 if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
10173 DstAlignCanChange = true;
10174 bool IsZeroVal = isNullConstant(Src);
10175 unsigned Limit = AlwaysInline ? ~0 : TLI.getMaxStoresPerMemset(OptSize);
10176
10177 EVT LargestVT;
10178 if (!TLI.findOptimalMemOpLowering(
10179 C, MemOps, Limit,
10180 MemOp::Set(Size, DstAlignCanChange, Alignment, IsZeroVal, isVol),
10181 DstPtrInfo.getAddrSpace(), ~0u, MF.getFunction().getAttributes(),
10182 &LargestVT))
10183 return SDValue();
10184
10185 if (DstAlignCanChange) {
10186 Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
10187 const DataLayout &DL = DAG.getDataLayout();
10188 Align NewAlign = DL.getABITypeAlign(Ty);
10189
10190 // Don't promote to an alignment that would require dynamic stack
10191 // realignment which may conflict with optimizations such as tail call
10192 // optimization.
10194 if (!TRI->hasStackRealignment(MF))
10195 if (MaybeAlign StackAlign = DL.getStackAlignment())
10196 NewAlign = std::min(NewAlign, *StackAlign);
10197
10198 if (NewAlign > Alignment) {
10199 // Give the stack frame object a larger alignment if needed.
10200 if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
10201 MFI.setObjectAlignment(FI->getIndex(), NewAlign);
10202 Alignment = NewAlign;
10203 }
10204 }
10205
10206 SmallVector<SDValue, 8> OutChains;
10207 uint64_t DstOff = 0;
10208 unsigned NumMemOps = MemOps.size();
10209
10210 // Find the largest store and generate the bit pattern for it.
10211 // If target didn't set LargestVT, compute it from MemOps.
10212 if (!LargestVT.isSimple()) {
10213 LargestVT = MemOps[0];
10214 for (unsigned i = 1; i < NumMemOps; i++)
10215 if (MemOps[i].bitsGT(LargestVT))
10216 LargestVT = MemOps[i];
10217 }
10218 SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl);
10219
10220 // Prepare AAInfo for loads/stores after lowering this memset.
10221 AAMDNodes NewAAInfo = AAInfo;
10222 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
10223
10224 for (unsigned i = 0; i < NumMemOps; i++) {
10225 EVT VT = MemOps[i];
10226 unsigned VTSize = VT.getSizeInBits() / 8;
10227 // The target should specify store types that exactly cover the memset size
10228 // (with the last store potentially being oversized for overlapping stores).
10229 assert(Size > 0 && "Target specified more stores than needed in "
10230 "findOptimalMemOpLowering");
10231 if (VTSize > Size) {
10232 // Issuing an unaligned load / store pair that overlaps with the previous
10233 // pair. Adjust the offset accordingly.
10234 assert(i == NumMemOps-1 && i != 0);
10235 DstOff -= VTSize - Size;
10236 }
10237
10238 // If this store is smaller than the largest store see whether we can get
10239 // the smaller value for free with a truncate or extract vector element and
10240 // then store.
10241 SDValue Value = MemSetValue;
10242 if (VT.bitsLT(LargestVT)) {
10243 unsigned Index;
10244 unsigned NElts = LargestVT.getSizeInBits() / VT.getSizeInBits();
10245 EVT SVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), NElts);
10246 if (!LargestVT.isVector() && !VT.isVector() &&
10247 TLI.isTruncateFree(LargestVT, VT))
10248 Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue);
10249 else if (LargestVT.isVector() && !VT.isVector() &&
10250 TLI.shallExtractConstSplatVectorElementToStore(
10251 LargestVT.getTypeForEVT(*DAG.getContext()),
10252 VT.getSizeInBits(), Index) &&
10253 TLI.isTypeLegal(SVT) &&
10254 LargestVT.getSizeInBits() == SVT.getSizeInBits()) {
10255 // Target which can combine store(extractelement VectorTy, Idx) can get
10256 // the smaller value for free.
10257 SDValue TailValue = DAG.getNode(ISD::BITCAST, dl, SVT, MemSetValue);
10258 Value = DAG.getExtractVectorElt(dl, VT, TailValue, Index);
10259 } else
10260 Value = getMemsetValue(Src, VT, DAG, dl);
10261 }
10262 assert(Value.getValueType() == VT && "Value with wrong type.");
10263 SDValue Store = DAG.getStore(
10264 Chain, dl, Value,
10265 DAG.getObjectPtrOffset(dl, Dst, TypeSize::getFixed(DstOff)),
10266 DstPtrInfo.getWithOffset(DstOff), Alignment,
10268 NewAAInfo);
10269 OutChains.push_back(Store);
10270 DstOff += VT.getSizeInBits() / 8;
10271 // For oversized overlapping stores, only subtract the remaining bytes.
10272 // For normal stores, subtract the full store size.
10273 if (VTSize > Size) {
10274 Size = 0;
10275 } else {
10276 Size -= VTSize;
10277 }
10278 }
10279
10280 // After processing all stores, Size should be exactly 0. Any remaining bytes
10281 // indicate a bug in the target's findOptimalMemOpLowering implementation.
10282 assert(Size == 0 && "Target's findOptimalMemOpLowering did not specify "
10283 "stores that exactly cover the memset size");
10284
10285 return DAG.getTokenFactor(dl, OutChains);
10286}
10287
10289 const DataLayout &DL, unsigned AS) {
10290 // Lowering memcpy / memset / memmove intrinsics to calls is only valid if all
10291 // pointer operands can be losslessly bitcasted to pointers of address space 0
10292 if (AS != 0 && !TLI->getTargetMachine().isNoopAddrSpaceCast(DL, AS, 0)) {
10293 report_fatal_error("cannot lower memory intrinsic in address space " +
10294 Twine(AS));
10295 }
10296}
10297
10298/// The length of a memory intrinsic (e.g. number of bytes to copy) is unsigned
10299/// and may have any integer type. We zero-extend or truncate it to the pointer
10300/// type of the narrower address space being accessed.
10302 SDValue Size, unsigned DstAS,
10303 unsigned SrcAS) {
10305 MVT DstVT = TLI.getPointerTy(DAG.getDataLayout(), DstAS);
10306 MVT SrcVT = TLI.getPointerTy(DAG.getDataLayout(), SrcAS);
10307 return DAG.getZExtOrTrunc(Size, dl, DstVT.bitsLT(SrcVT) ? DstVT : SrcVT);
10308}
10309
10311 const SelectionDAG *SelDAG,
10312 bool AllowReturnsFirstArg) {
10313 if (!CI || !CI->isTailCall())
10314 return false;
10315 // TODO: Fix "returns-first-arg" determination so it doesn't depend on which
10316 // helper symbol we lower to.
10317 return isInTailCallPosition(*CI, SelDAG->getTarget(),
10318 AllowReturnsFirstArg &&
10320}
10321
10322static std::pair<SDValue, SDValue>
10325 const CallInst *CI, RTLIB::Libcall Call,
10326 SelectionDAG *DAG, const TargetLowering *TLI) {
10327 RTLIB::LibcallImpl LCImpl = DAG->getLibcalls().getLibcallImpl(Call);
10328
10329 if (LCImpl == RTLIB::Unsupported)
10330 return {};
10331
10333 bool IsTailCall =
10334 isInTailCallPositionWrapper(CI, DAG, /*AllowReturnsFirstArg=*/true) &&
10335 // Lowering doesn't support tail calling inside a function with
10336 // a swifterror argument yet.
10337 !DAG->hasSwiftErrorArg();
10338 SDValue Callee =
10339 DAG->getExternalSymbol(LCImpl, TLI->getPointerTy(DAG->getDataLayout()));
10340
10341 CLI.setDebugLoc(dl)
10342 .setChain(Chain)
10344 CI->getType(), Callee, std::move(Args))
10345 .setTailCall(IsTailCall);
10346
10347 return TLI->LowerCallTo(CLI);
10348}
10349
10350std::pair<SDValue, SDValue> SelectionDAG::getStrcmp(SDValue Chain,
10351 const SDLoc &dl, SDValue S1,
10352 SDValue S2,
10353 const CallInst *CI) {
10355 TargetLowering::ArgListTy Args = {{S1, PT}, {S2, PT}};
10356 return getRuntimeCallSDValueHelper(Chain, dl, std::move(Args), CI,
10357 RTLIB::STRCMP, this, TLI);
10358}
10359
10360std::pair<SDValue, SDValue> SelectionDAG::getStrstr(SDValue Chain,
10361 const SDLoc &dl, SDValue S1,
10362 SDValue S2,
10363 const CallInst *CI) {
10365 TargetLowering::ArgListTy Args = {{S1, PT}, {S2, PT}};
10366 return getRuntimeCallSDValueHelper(Chain, dl, std::move(Args), CI,
10367 RTLIB::STRSTR, this, TLI);
10368}
10369
10370std::pair<SDValue, SDValue> SelectionDAG::getMemccpy(SDValue Chain,
10371 const SDLoc &dl,
10372 SDValue Dst, SDValue Src,
10374 const CallInst *CI) {
10376
10378 {Dst, PT},
10379 {Src, PT},
10382 return getRuntimeCallSDValueHelper(Chain, dl, std::move(Args), CI,
10383 RTLIB::MEMCCPY, this, TLI);
10384}
10385
10386std::pair<SDValue, SDValue>
10388 SDValue Mem1, SDValue Size, const CallInst *CI) {
10391 {Mem0, PT},
10392 {Mem1, PT},
10394 return getRuntimeCallSDValueHelper(Chain, dl, std::move(Args), CI,
10395 RTLIB::MEMCMP, this, TLI);
10396}
10397
10398std::pair<SDValue, SDValue> SelectionDAG::getStrcpy(SDValue Chain,
10399 const SDLoc &dl,
10400 SDValue Dst, SDValue Src,
10401 const CallInst *CI) {
10403 TargetLowering::ArgListTy Args = {{Dst, PT}, {Src, PT}};
10404 return getRuntimeCallSDValueHelper(Chain, dl, std::move(Args), CI,
10405 RTLIB::STRCPY, this, TLI);
10406}
10407
10408std::pair<SDValue, SDValue> SelectionDAG::getStrlen(SDValue Chain,
10409 const SDLoc &dl,
10410 SDValue Src,
10411 const CallInst *CI) {
10412 // Emit a library call.
10415 return getRuntimeCallSDValueHelper(Chain, dl, std::move(Args), CI,
10416 RTLIB::STRLEN, this, TLI);
10417}
10418
10420 return TLI->supportSwiftError() &&
10421 MF->getFunction().getAttributes().hasAttrSomewhere(
10422 Attribute::SwiftError);
10423}
10424
10426 SDValue Chain, const SDLoc &dl, SDValue Dst, SDValue Src, SDValue Size,
10427 Align DstAlign, Align SrcAlign, bool isVol, bool AlwaysInline,
10428 const CallInst *CI, std::optional<bool> OverrideTailCall,
10429 MachinePointerInfo DstPtrInfo, MachinePointerInfo SrcPtrInfo,
10430 const AAMDNodes &AAInfo, BatchAAResults *BatchAA) {
10431 Size = getMemIntrinsicSize(*this, dl, Size, DstPtrInfo.getAddrSpace(),
10432 SrcPtrInfo.getAddrSpace());
10433 // Check to see if we should lower the memcpy to loads and stores first.
10434 // For cases within the target-specified limits, this is the best choice.
10435 const MDNode *DstMemCacheHint =
10436 CI ? getMemCacheHint(*CI, /*OperandNo=*/0) : nullptr;
10437 const MDNode *SrcMemCacheHint =
10438 CI ? getMemCacheHint(*CI, /*OperandNo=*/1) : nullptr;
10439
10441 if (ConstantSize) {
10442 // Memcpy with size zero? Just return the original chain.
10443 if (ConstantSize->isZero())
10444 return Chain;
10445
10447 *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), DstAlign,
10448 SrcAlign, isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo, BatchAA,
10449 DstMemCacheHint, SrcMemCacheHint);
10450 if (Result.getNode())
10451 return Result;
10452 }
10453
10454 // Then check to see if we should lower the memcpy with target-specific
10455 // code. If the target chooses to do this, this is the next best.
10456 if (TSI) {
10457 bool IsTailCall = OverrideTailCall.value_or(isInTailCallPositionWrapper(
10458 CI, this, /*AllowReturnsFirstArg=*/false)) &&
10460 [[maybe_unused]] SDValue OldRoot = getRoot();
10461 SDValue Result = TSI->EmitTargetCodeForMemcpy(
10462 *this, dl, Chain, Dst, Src, Size, DstAlign, SrcAlign, isVol,
10463 AlwaysInline, IsTailCall, DstPtrInfo, SrcPtrInfo);
10464 assert((Result.getNode() || !IsTailCall || getRoot() != OldRoot) &&
10465 "target declined without clearing IsTailCall");
10466 if (Result.getNode() || IsTailCall)
10467 return Result;
10468 }
10469
10470 // If we really need inline code and the target declined to provide it,
10471 // use a (potentially long) sequence of loads and stores.
10472 if (AlwaysInline) {
10473 assert(ConstantSize && "AlwaysInline requires a constant size!");
10475 *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), DstAlign,
10476 SrcAlign, isVol, true, DstPtrInfo, SrcPtrInfo, AAInfo, BatchAA,
10477 DstMemCacheHint, SrcMemCacheHint);
10478 }
10479
10481 DstPtrInfo.getAddrSpace());
10483 SrcPtrInfo.getAddrSpace());
10484
10485 // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc
10486 // memcpy is not guaranteed to be safe. libc memcpys aren't required to
10487 // respect volatile, so they may do things like read or write memory
10488 // beyond the given memory regions. But fixing this isn't easy, and most
10489 // people don't care.
10490
10491 // Emit a library call.
10494 Args.emplace_back(Dst, PtrTy);
10495 Args.emplace_back(Src, PtrTy);
10496 Args.emplace_back(Size, getDataLayout().getIntPtrType(*getContext()));
10497 // FIXME: pass in SDLoc
10499 bool IsTailCall = false;
10500 RTLIB::LibcallImpl MemCpyImpl = Libcalls->getMemcpyImpl();
10501
10502 if (OverrideTailCall.has_value()) {
10503 IsTailCall = *OverrideTailCall;
10504 } else {
10505 bool LowersToMemcpy = MemCpyImpl == RTLIB::impl_memcpy;
10506 IsTailCall = isInTailCallPositionWrapper(CI, this, LowersToMemcpy);
10507 }
10508 // Lowering doesn't support tail calling inside a function with a
10509 // swifterror argument yet.
10510 IsTailCall &= !hasSwiftErrorArg();
10511
10512 CLI.setDebugLoc(dl)
10513 .setChain(Chain)
10514 .setLibCallee(
10515 Libcalls->getLibcallImplCallingConv(MemCpyImpl),
10516 Dst.getValueType().getTypeForEVT(*getContext()),
10517 getExternalSymbol(MemCpyImpl, TLI->getPointerTy(getDataLayout())),
10518 std::move(Args))
10520 .setTailCall(IsTailCall);
10521
10522 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
10523 return CallResult.second;
10524}
10525
10528 const Module &M = *DAG->getMachineFunction().getFunction().getParent();
10529 Type *SizeTTy = DAG->getLibInfo().getSizeTType(M);
10531 DAG->getZExtOrTrunc(Size, dl, MVT::getVT(SizeTTy)), SizeTTy);
10532}
10533
10535 SDValue Dst, SDValue Src, SDValue Size,
10536 Type *SizeTy, unsigned ElemSz,
10537 bool isTailCall,
10538 MachinePointerInfo DstPtrInfo,
10539 MachinePointerInfo SrcPtrInfo) {
10540 // Lowering doesn't support tail calling inside a function with a
10541 // swifterror argument yet.
10542 isTailCall &= !hasSwiftErrorArg();
10543
10544 // Emit a library call.
10547 Args.emplace_back(Dst, ArgTy);
10548 Args.emplace_back(Src, ArgTy);
10549 Args.emplace_back(getAtomicMemOpSizeArg(this, dl, Size));
10550
10551 RTLIB::Libcall LibraryCall =
10553 RTLIB::LibcallImpl LibcallImpl = Libcalls->getLibcallImpl(LibraryCall);
10554 if (LibcallImpl == RTLIB::Unsupported)
10555 report_fatal_error("Unsupported element size");
10556
10558 CLI.setDebugLoc(dl)
10559 .setChain(Chain)
10560 .setLibCallee(
10561 Libcalls->getLibcallImplCallingConv(LibcallImpl),
10563 getExternalSymbol(LibcallImpl, TLI->getPointerTy(getDataLayout())),
10564 std::move(Args))
10566 .setTailCall(isTailCall);
10567
10568 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
10569 return CallResult.second;
10570}
10571
10573 SDValue Src, SDValue Size, Align DstAlign,
10574 Align SrcAlign, bool isVol, const CallInst *CI,
10575 std::optional<bool> OverrideTailCall,
10576 MachinePointerInfo DstPtrInfo,
10577 MachinePointerInfo SrcPtrInfo,
10578 const AAMDNodes &AAInfo,
10579 BatchAAResults *BatchAA) {
10580 Size = getMemIntrinsicSize(*this, dl, Size, DstPtrInfo.getAddrSpace(),
10581 SrcPtrInfo.getAddrSpace());
10582 // Check to see if we should lower the memmove to loads and stores first.
10583 // For cases within the target-specified limits, this is the best choice.
10585 if (ConstantSize) {
10586 // Memmove with size zero? Just return the original chain.
10587 if (ConstantSize->isZero())
10588 return Chain;
10589
10591 *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), DstAlign,
10592 SrcAlign, isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo);
10593 if (Result.getNode())
10594 return Result;
10595 }
10596
10597 // Then check to see if we should lower the memmove with target-specific
10598 // code. If the target chooses to do this, this is the next best.
10599 if (TSI) {
10600 bool IsTailCall = OverrideTailCall.value_or(isInTailCallPositionWrapper(
10601 CI, this, /*AllowReturnsFirstArg=*/false)) &&
10603 [[maybe_unused]] SDValue OldRoot = getRoot();
10604 SDValue Result = TSI->EmitTargetCodeForMemmove(
10605 *this, dl, Chain, Dst, Src, Size, DstAlign, SrcAlign, isVol, IsTailCall,
10606 DstPtrInfo, SrcPtrInfo);
10607 assert((Result.getNode() || !IsTailCall || getRoot() != OldRoot) &&
10608 "target declined without clearing IsTailCall");
10609 if (Result.getNode() || IsTailCall)
10610 return Result;
10611 }
10612
10614 DstPtrInfo.getAddrSpace());
10616 SrcPtrInfo.getAddrSpace());
10617
10618 // FIXME: If the memmove is volatile, lowering it to plain libc memmove may
10619 // not be safe. See memcpy above for more details.
10620
10621 // Emit a library call.
10624 Args.emplace_back(Dst, PtrTy);
10625 Args.emplace_back(Src, PtrTy);
10626 Args.emplace_back(Size, getDataLayout().getIntPtrType(*getContext()));
10627 // FIXME: pass in SDLoc
10629
10630 RTLIB::LibcallImpl MemmoveImpl = Libcalls->getLibcallImpl(RTLIB::MEMMOVE);
10631
10632 bool IsTailCall = false;
10633 if (OverrideTailCall.has_value()) {
10634 IsTailCall = *OverrideTailCall;
10635 } else {
10636 bool LowersToMemmove = MemmoveImpl == RTLIB::impl_memmove;
10637 IsTailCall = isInTailCallPositionWrapper(CI, this, LowersToMemmove);
10638 }
10639 // Lowering doesn't support tail calling inside a function with a
10640 // swifterror argument yet.
10641 IsTailCall &= !hasSwiftErrorArg();
10642
10643 CLI.setDebugLoc(dl)
10644 .setChain(Chain)
10645 .setLibCallee(
10646 Libcalls->getLibcallImplCallingConv(MemmoveImpl),
10647 Dst.getValueType().getTypeForEVT(*getContext()),
10648 getExternalSymbol(MemmoveImpl, TLI->getPointerTy(getDataLayout())),
10649 std::move(Args))
10651 .setTailCall(IsTailCall);
10652
10653 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
10654 return CallResult.second;
10655}
10656
10658 SDValue Dst, SDValue Src, SDValue Size,
10659 Type *SizeTy, unsigned ElemSz,
10660 bool isTailCall,
10661 MachinePointerInfo DstPtrInfo,
10662 MachinePointerInfo SrcPtrInfo) {
10663 // Lowering doesn't support tail calling inside a function with a
10664 // swifterror argument yet.
10665 isTailCall &= !hasSwiftErrorArg();
10666
10667 // Emit a library call.
10670 Args.emplace_back(Dst, IntPtrTy);
10671 Args.emplace_back(Src, IntPtrTy);
10672 Args.emplace_back(getAtomicMemOpSizeArg(this, dl, Size));
10673
10674 RTLIB::Libcall LibraryCall =
10676 RTLIB::LibcallImpl LibcallImpl = Libcalls->getLibcallImpl(LibraryCall);
10677 if (LibcallImpl == RTLIB::Unsupported)
10678 report_fatal_error("Unsupported element size");
10679
10681 CLI.setDebugLoc(dl)
10682 .setChain(Chain)
10683 .setLibCallee(
10684 Libcalls->getLibcallImplCallingConv(LibcallImpl),
10686 getExternalSymbol(LibcallImpl, TLI->getPointerTy(getDataLayout())),
10687 std::move(Args))
10689 .setTailCall(isTailCall);
10690
10691 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
10692 return CallResult.second;
10693}
10694
10696 SDValue Src, SDValue Size, Align Alignment,
10697 bool isVol, bool AlwaysInline,
10698 const CallInst *CI,
10699 MachinePointerInfo DstPtrInfo,
10700 const AAMDNodes &AAInfo) {
10701 Size = getMemIntrinsicSize(*this, dl, Size, DstPtrInfo.getAddrSpace(),
10702 DstPtrInfo.getAddrSpace());
10703 // Check to see if we should lower the memset to stores first.
10704 // For cases within the target-specified limits, this is the best choice.
10706 if (ConstantSize) {
10707 // Memset with size zero? Just return the original chain.
10708 if (ConstantSize->isZero())
10709 return Chain;
10710
10711 SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src,
10712 ConstantSize->getZExtValue(), Alignment,
10713 isVol, false, DstPtrInfo, AAInfo);
10714
10715 if (Result.getNode())
10716 return Result;
10717 }
10718
10719 // Then check to see if we should lower the memset with target-specific
10720 // code. If the target chooses to do this, this is the next best.
10721 if (TSI) {
10722 bool IsTailCall =
10723 isInTailCallPositionWrapper(CI, this, /*AllowReturnsFirstArg=*/false) &&
10725 [[maybe_unused]] SDValue OldRoot = getRoot();
10726 SDValue Result = TSI->EmitTargetCodeForMemset(
10727 *this, dl, Chain, Dst, Src, Size, Alignment, isVol, AlwaysInline,
10728 IsTailCall, DstPtrInfo);
10729 assert((Result.getNode() || !IsTailCall || getRoot() != OldRoot) &&
10730 "target declined without clearing IsTailCall");
10731 if (Result.getNode() || IsTailCall)
10732 return Result;
10733 }
10734
10735 // If we really need inline code and the target declined to provide it,
10736 // use a (potentially long) sequence of loads and stores.
10737 if (AlwaysInline) {
10738 assert(ConstantSize && "AlwaysInline requires a constant size!");
10739 SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src,
10740 ConstantSize->getZExtValue(), Alignment,
10741 isVol, true, DstPtrInfo, AAInfo);
10742 assert(Result &&
10743 "getMemsetStores must return a valid sequence when AlwaysInline");
10744 return Result;
10745 }
10746
10748 DstPtrInfo.getAddrSpace());
10749
10750 // Emit a library call.
10751 auto &Ctx = *getContext();
10752 const auto& DL = getDataLayout();
10753
10755 // FIXME: pass in SDLoc
10756 CLI.setDebugLoc(dl).setChain(Chain);
10757
10758 RTLIB::LibcallImpl BzeroImpl = Libcalls->getLibcallImpl(RTLIB::BZERO);
10759 bool UseBZero = BzeroImpl != RTLIB::Unsupported && isNullConstant(Src);
10760
10761 // If zeroing out and bzero is present, use it.
10762 if (UseBZero) {
10764 Args.emplace_back(Dst, PointerType::getUnqual(Ctx));
10765 Args.emplace_back(Size, DL.getIntPtrType(Ctx));
10766 CLI.setLibCallee(
10767 Libcalls->getLibcallImplCallingConv(BzeroImpl), Type::getVoidTy(Ctx),
10768 getExternalSymbol(BzeroImpl, TLI->getPointerTy(DL)), std::move(Args));
10769 } else {
10770 RTLIB::LibcallImpl MemsetImpl = Libcalls->getLibcallImpl(RTLIB::MEMSET);
10771
10772 MVT IntVT = MVT::getIntegerVT(LibInfo->getIntSize());
10774 Args.emplace_back(Dst, PointerType::getUnqual(Ctx));
10775 Args.emplace_back(getAnyExtOrTrunc(Src, dl, IntVT),
10776 Type::getIntNTy(Ctx, LibInfo->getIntSize()),
10777 LibInfo->getExtAttrForI32Param());
10778 Args.emplace_back(Size, DL.getIntPtrType(Ctx));
10779
10780 CLI.setLibCallee(Libcalls->getLibcallImplCallingConv(MemsetImpl),
10781 Dst.getValueType().getTypeForEVT(Ctx),
10782 getExternalSymbol(MemsetImpl, TLI->getPointerTy(DL)),
10783 std::move(Args));
10784 }
10785
10786 RTLIB::LibcallImpl MemsetImpl = Libcalls->getLibcallImpl(RTLIB::MEMSET);
10787 bool LowersToMemset = MemsetImpl == RTLIB::impl_memset;
10788
10789 // If we're going to use bzero, make sure not to tail call unless the
10790 // subsequent return doesn't need a value, as bzero doesn't return the first
10791 // arg unlike memset.
10792 bool ReturnsFirstArg = CI && funcReturnsFirstArgOfCall(*CI) && !UseBZero;
10793 bool IsTailCall = CI && CI->isTailCall() &&
10795 ReturnsFirstArg && LowersToMemset) &&
10796 // Lowering doesn't support tail calling inside a function
10797 // with a swifterror argument yet.
10799 CLI.setDiscardResult().setTailCall(IsTailCall);
10800
10801 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
10802 return CallResult.second;
10803}
10804
10807 Type *SizeTy, unsigned ElemSz,
10808 bool isTailCall,
10809 MachinePointerInfo DstPtrInfo) {
10810 // Lowering doesn't support tail calling inside a function with a
10811 // swifterror argument yet.
10812 isTailCall &= !hasSwiftErrorArg();
10813
10814 // Emit a library call.
10815 MVT IntVT = MVT::getIntegerVT(LibInfo->getIntSize());
10817 Args.emplace_back(Dst, getDataLayout().getIntPtrType(*getContext()));
10818 Args.emplace_back(getAnyExtOrTrunc(Value, dl, IntVT),
10819 Type::getIntNTy(*getContext(), LibInfo->getIntSize()),
10820 LibInfo->getExtAttrForI32Param());
10821 Args.emplace_back(getAtomicMemOpSizeArg(this, dl, Size));
10822
10823 RTLIB::Libcall LibraryCall =
10825 RTLIB::LibcallImpl LibcallImpl = Libcalls->getLibcallImpl(LibraryCall);
10826 if (LibcallImpl == RTLIB::Unsupported)
10827 report_fatal_error("Unsupported element size");
10828
10830 CLI.setDebugLoc(dl)
10831 .setChain(Chain)
10832 .setLibCallee(
10833 Libcalls->getLibcallImplCallingConv(LibcallImpl),
10835 getExternalSymbol(LibcallImpl, TLI->getPointerTy(getDataLayout())),
10836 std::move(Args))
10838 .setTailCall(isTailCall);
10839
10840 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
10841 return CallResult.second;
10842}
10843
10844SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
10846 MachineMemOperand *MMO,
10847 ISD::LoadExtType ExtType) {
10848 SDNodeKey ID(Opcode, VTList, Ops);
10849 ID.AddInteger(MemVT.getRawBits());
10850 ID.AddInteger(getSyntheticNodeSubclassData<AtomicSDNode>(
10851 dl.getIROrder(), Opcode, VTList, MemVT, MMO, ExtType));
10852 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
10853 ID.AddInteger(MMO->getFlags());
10854 FoldingSetInsertToken InsertToken;
10855 if (auto *E = cast_or_null<AtomicSDNode>(lookupNode(ID, dl, InsertToken))) {
10856 E->refineAlignment(MMO);
10857 E->refineMMOMetadata(MMO);
10858 return SDValue(E, 0);
10859 }
10860
10861 auto *N = newSDNode<AtomicSDNode>(dl.getIROrder(), dl.getDebugLoc(), Opcode,
10862 VTList, MemVT, MMO, ExtType);
10863 createOperands(N, Ops);
10864
10865 CSEMap.insert(N, InsertToken);
10866 InsertNode(N);
10867 SDValue V(N, 0);
10868 NewSDValueDbgMsg(V, "Creating new node: ", this);
10869 return V;
10870}
10871
10873 EVT MemVT, SDVTList VTs, SDValue Chain,
10874 SDValue Ptr, SDValue Cmp, SDValue Swp,
10875 MachineMemOperand *MMO) {
10876 assert(Opcode == ISD::ATOMIC_CMP_SWAP ||
10878 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
10879
10880 SDValue Ops[] = {Chain, Ptr, Cmp, Swp};
10881 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
10882}
10883
10884SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
10885 SDValue Chain, SDValue Ptr, SDValue Val,
10886 MachineMemOperand *MMO) {
10887 assert((Opcode == ISD::ATOMIC_LOAD_ADD || Opcode == ISD::ATOMIC_LOAD_SUB ||
10888 Opcode == ISD::ATOMIC_LOAD_AND || Opcode == ISD::ATOMIC_LOAD_CLR ||
10889 Opcode == ISD::ATOMIC_LOAD_OR || Opcode == ISD::ATOMIC_LOAD_XOR ||
10890 Opcode == ISD::ATOMIC_LOAD_NAND || Opcode == ISD::ATOMIC_LOAD_MIN ||
10891 Opcode == ISD::ATOMIC_LOAD_MAX || Opcode == ISD::ATOMIC_LOAD_UMIN ||
10892 Opcode == ISD::ATOMIC_LOAD_UMAX || Opcode == ISD::ATOMIC_LOAD_FADD ||
10893 Opcode == ISD::ATOMIC_LOAD_FSUB || Opcode == ISD::ATOMIC_LOAD_FMAX ||
10894 Opcode == ISD::ATOMIC_LOAD_FMIN ||
10895 Opcode == ISD::ATOMIC_LOAD_FMINIMUM ||
10896 Opcode == ISD::ATOMIC_LOAD_FMAXIMUM ||
10897 Opcode == ISD::ATOMIC_LOAD_FMINIMUMNUM ||
10898 Opcode == ISD::ATOMIC_LOAD_FMAXIMUMNUM ||
10899 Opcode == ISD::ATOMIC_LOAD_UINC_WRAP ||
10900 Opcode == ISD::ATOMIC_LOAD_UDEC_WRAP ||
10901 Opcode == ISD::ATOMIC_LOAD_USUB_COND ||
10902 Opcode == ISD::ATOMIC_LOAD_USUB_SAT || Opcode == ISD::ATOMIC_SWAP ||
10903 Opcode == ISD::ATOMIC_STORE) &&
10904 "Invalid Atomic Op");
10905
10906 EVT VT = Val.getValueType();
10907
10908 SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) :
10909 getVTList(VT, MVT::Other);
10910 SDValue Ops[] = {Chain, Ptr, Val};
10911 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
10912}
10913
10915 EVT MemVT, EVT VT, SDValue Chain,
10916 SDValue Ptr, MachineMemOperand *MMO) {
10917 SDVTList VTs = getVTList(VT, MVT::Other);
10918 SDValue Ops[] = {Chain, Ptr};
10919 return getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, VTs, Ops, MMO, ExtType);
10920}
10921
10922/// getMergeValues - Create a MERGE_VALUES node from the given operands.
10924 if (Ops.size() == 1)
10925 return Ops[0];
10926
10928 VTs.reserve(Ops.size());
10929 for (const SDValue &Op : Ops)
10930 VTs.push_back(Op.getValueType());
10931 return getNode(ISD::MERGE_VALUES, dl, getVTList(VTs), Ops);
10932}
10933
10935 SDValue Chain, const SDLoc &dl) {
10936 SmallVector<SDValue, 4> RetValues;
10937 RetValues.reserve(ResultTypes.size());
10938 for (EVT VT : ResultTypes)
10939 RetValues.push_back(VT == MVT::Other ? Chain : getPOISON(VT));
10940 return getMergeValues(RetValues, dl);
10941}
10942
10944 unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef<SDValue> Ops,
10945 EVT MemVT, MachinePointerInfo PtrInfo, Align Alignment,
10947 const AAMDNodes &AAInfo) {
10948 if (Size.hasValue() && !Size.getValue())
10950
10952 MachineMemOperand *MMO =
10953 MF.getMachineMemOperand(PtrInfo, Flags, Size, Alignment, AAInfo);
10954
10955 return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, MMO);
10956}
10957
10959 SDVTList VTList,
10960 ArrayRef<SDValue> Ops, EVT MemVT,
10961 MachineMemOperand *MMO) {
10962 return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, ArrayRef(MMO));
10963}
10964
10966 SDVTList VTList,
10967 ArrayRef<SDValue> Ops, EVT MemVT,
10969 assert(!MMOs.empty() && "Must have at least one MMO");
10970 assert(
10971 (Opcode == ISD::INTRINSIC_VOID || Opcode == ISD::INTRINSIC_W_CHAIN ||
10972 Opcode == ISD::PREFETCH ||
10973 (Opcode <= (unsigned)std::numeric_limits<int>::max() &&
10974 Opcode >= ISD::BUILTIN_OP_END && TSI->isTargetMemoryOpcode(Opcode))) &&
10975 "Opcode is not a memory-accessing opcode!");
10976
10978 if (MMOs.size() == 1) {
10979 MemRefs = MMOs[0];
10980 } else {
10981 // Allocate: [size_t count][MMO*][MMO*]...
10982 size_t AllocSize =
10983 sizeof(size_t) + MMOs.size() * sizeof(MachineMemOperand *);
10984 void *Buffer = Allocator.Allocate(AllocSize, alignof(size_t));
10985 size_t *CountPtr = static_cast<size_t *>(Buffer);
10986 *CountPtr = MMOs.size();
10987 MachineMemOperand **Array =
10988 reinterpret_cast<MachineMemOperand **>(CountPtr + 1);
10989 llvm::copy(MMOs, Array);
10990 MemRefs = Array;
10991 }
10992
10993 // Memoize the node unless it returns a glue result.
10995 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
10996 SDNodeKey ID(Opcode, VTList, Ops);
10997 ID.AddInteger(getSyntheticNodeSubclassData<MemIntrinsicSDNode>(
10998 Opcode, dl.getIROrder(), VTList, MemVT, MemRefs));
10999 ID.AddInteger(MemVT.getRawBits());
11000 for (const MachineMemOperand *MMO : MMOs) {
11001 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11002 ID.AddInteger(MMO->getFlags());
11003 }
11004 FoldingSetInsertToken InsertToken;
11005 if (SDNode *E = lookupNode(ID, dl, InsertToken)) {
11006 cast<MemIntrinsicSDNode>(E)->refineAlignment(MMOs);
11007 return SDValue(E, 0);
11008 }
11009
11010 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
11011 VTList, MemVT, MemRefs);
11012 createOperands(N, Ops);
11013 CSEMap.insert(N, InsertToken);
11014 } else {
11015 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
11016 VTList, MemVT, MemRefs);
11017 createOperands(N, Ops);
11018 }
11019 InsertNode(N);
11020 SDValue V(N, 0);
11021 NewSDValueDbgMsg(V, "Creating new node: ", this);
11022 return V;
11023}
11024
11026 SDValue Chain, int FrameIndex) {
11027 const unsigned Opcode = IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END;
11028 const auto VTs = getVTList(MVT::Other);
11029 SDValue Ops[2] = {
11030 Chain,
11031 getFrameIndex(FrameIndex,
11032 getTargetLoweringInfo().getFrameIndexTy(getDataLayout()),
11033 true)};
11034
11035 SDNodeKey ID(Opcode, VTs, Ops);
11036 FoldingSetInsertToken InsertToken;
11037 if (SDNode *E = lookupNode(ID, dl, InsertToken))
11038 return SDValue(E, 0);
11039
11040 LifetimeSDNode *N =
11041 newSDNode<LifetimeSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), VTs);
11042 createOperands(N, Ops);
11043 CSEMap.insert(N, InsertToken);
11044 InsertNode(N);
11045 SDValue V(N, 0);
11046 NewSDValueDbgMsg(V, "Creating new node: ", this);
11047 return V;
11048}
11049
11051 uint64_t Guid, uint64_t Index,
11052 uint32_t Attr) {
11053 const unsigned Opcode = ISD::PSEUDO_PROBE;
11054 const auto VTs = getVTList(MVT::Other);
11055 SDValue Ops[] = {Chain};
11056 SDNodeKey ID(Opcode, VTs, Ops);
11057 ID.AddInteger(Guid);
11058 ID.AddInteger(Index);
11059 ID.AddInteger(Attr);
11060 FoldingSetInsertToken InsertToken;
11061 if (SDNode *E = lookupNode(ID, Dl, InsertToken))
11062 return SDValue(E, 0);
11063
11064 auto *N = newSDNode<PseudoProbeSDNode>(
11065 Opcode, Dl.getIROrder(), Dl.getDebugLoc(), VTs, Guid, Index, Attr);
11066 createOperands(N, Ops);
11067 CSEMap.insert(N, InsertToken);
11068 InsertNode(N);
11069 SDValue V(N, 0);
11070 NewSDValueDbgMsg(V, "Creating new node: ", this);
11071 return V;
11072}
11073
11074/// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
11075/// MachinePointerInfo record from it. This is particularly useful because the
11076/// code generator has many cases where it doesn't bother passing in a
11077/// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
11079 SelectionDAG &DAG, SDValue Ptr,
11080 int64_t Offset = 0) {
11081 // If this is FI+Offset, we can model it.
11082 if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr))
11084 FI->getIndex(), Offset);
11085
11086 // If this is (FI+Offset1)+Offset2, we can model it.
11087 if (Ptr.getOpcode() != ISD::ADD ||
11090 return Info;
11091
11092 int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
11094 DAG.getMachineFunction(), FI,
11095 Offset + cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue());
11096}
11097
11098/// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
11099/// MachinePointerInfo record from it. This is particularly useful because the
11100/// code generator has many cases where it doesn't bother passing in a
11101/// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
11103 SelectionDAG &DAG, SDValue Ptr,
11104 SDValue OffsetOp) {
11105 // If the 'Offset' value isn't a constant, we can't handle this.
11107 return InferPointerInfo(Info, DAG, Ptr, OffsetNode->getSExtValue());
11108 if (OffsetOp.isUndef())
11109 return InferPointerInfo(Info, DAG, Ptr);
11110 return Info;
11111}
11112
11114 EVT VT, const SDLoc &dl, SDValue Chain,
11115 SDValue Ptr, SDValue Offset,
11116 MachinePointerInfo PtrInfo, EVT MemVT,
11117 Align Alignment,
11118 MachineMemOperand::Flags MMOFlags,
11119 const MMOMetadata &Metadata) {
11120 assert(Chain.getValueType() == MVT::Other &&
11121 "Invalid chain type");
11122
11123 MMOFlags |= MachineMemOperand::MOLoad;
11124 assert((MMOFlags & MachineMemOperand::MOStore) == 0);
11125 // If we don't have a PtrInfo, infer the trivial frame index case to simplify
11126 // clients.
11127 if (PtrInfo.V.isNull())
11128 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
11129
11130 TypeSize Size = MemVT.getStoreSize();
11132 MachineMemOperand *MMO =
11133 MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, Alignment, Metadata);
11134 return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO);
11135}
11136
11138 EVT VT, const SDLoc &dl, SDValue Chain,
11139 SDValue Ptr, SDValue Offset, EVT MemVT,
11140 MachineMemOperand *MMO) {
11141 if (VT == MemVT) {
11142 ExtType = ISD::NON_EXTLOAD;
11143 } else if (ExtType == ISD::NON_EXTLOAD) {
11144 assert(VT == MemVT && "Non-extending load from different memory type!");
11145 } else {
11146 // Extending load.
11147 assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) &&
11148 "Should only be an extending load, not truncating!");
11149 assert(VT.isInteger() == MemVT.isInteger() &&
11150 "Cannot convert from FP to Int or Int -> FP!");
11151 assert(VT.isVector() == MemVT.isVector() &&
11152 "Cannot use an ext load to convert to or from a vector!");
11153 assert((!VT.isVector() ||
11155 "Cannot use an ext load to change the number of vector elements!");
11156 }
11157
11158 assert((!MMO->getRanges() ||
11160 ->getBitWidth() == MemVT.getScalarSizeInBits() &&
11161 MemVT.isInteger())) &&
11162 "Range metadata and load type must match!");
11163
11164 bool Indexed = AM != ISD::UNINDEXED;
11165 assert((Indexed || Offset.getOpcode() == ISD::POISON) &&
11166 "Unindexed load with an offset!");
11167
11168 SDVTList VTs = Indexed ?
11169 getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
11170 SDValue Ops[] = { Chain, Ptr, Offset };
11171 SDNodeKey ID(ISD::LOAD, VTs, Ops);
11172 ID.AddInteger(MemVT.getRawBits());
11173 ID.AddInteger(getSyntheticNodeSubclassData<LoadSDNode>(
11174 dl.getIROrder(), VTs, AM, ExtType, MemVT, MMO));
11175 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11176 ID.AddInteger(MMO->getFlags());
11177 FoldingSetInsertToken InsertToken;
11178 if (auto *E = cast_or_null<LoadSDNode>(lookupNode(ID, dl, InsertToken))) {
11179 E->refineAlignment(MMO);
11180 E->refineMMOMetadata(MMO);
11181 return SDValue(E, 0);
11182 }
11183 auto *N = newSDNode<LoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
11184 ExtType, MemVT, MMO);
11185 createOperands(N, Ops);
11186
11187 CSEMap.insert(N, InsertToken);
11188 InsertNode(N);
11189 SDValue V(N, 0);
11190 NewSDValueDbgMsg(V, "Creating new node: ", this);
11191 return V;
11192}
11193
11195 SDValue Ptr, MachinePointerInfo PtrInfo,
11196 MaybeAlign Alignment,
11197 MachineMemOperand::Flags MMOFlags,
11198 const MMOMetadata &Metadata) {
11200 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
11201 PtrInfo, VT, Alignment, MMOFlags, Metadata);
11202}
11203
11205 SDValue Ptr, MachineMemOperand *MMO) {
11207 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
11208 VT, MMO);
11209}
11210
11212 EVT VT, SDValue Chain, SDValue Ptr,
11213 MachinePointerInfo PtrInfo, EVT MemVT,
11214 MaybeAlign Alignment,
11215 MachineMemOperand::Flags MMOFlags,
11216 const MMOMetadata &Metadata) {
11218 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, PtrInfo,
11219 MemVT, Alignment, MMOFlags, Metadata);
11220}
11221
11223 EVT VT, SDValue Chain, SDValue Ptr, EVT MemVT,
11224 MachineMemOperand *MMO) {
11226 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef,
11227 MemVT, MMO);
11228}
11229
11233 LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
11234 assert(LD->getOffset().getOpcode() == ISD::POISON &&
11235 "Load is already a indexed load!");
11236 // Don't propagate the invariant or dereferenceable flags.
11237 auto MMOFlags =
11238 LD->getMemOperand()->getFlags() &
11240 return getLoad(
11241 AM, LD->getExtensionType(), OrigLoad.getValueType(), dl, LD->getChain(),
11242 Base, Offset, LD->getPointerInfo(), LD->getMemoryVT(), LD->getAlign(),
11243 MMOFlags,
11244 MMOMetadata(LD->getAAInfo(), LD->getRanges(), LD->getMemCacheHint()));
11245}
11246
11248 SDValue Ptr, MachinePointerInfo PtrInfo,
11249 Align Alignment,
11250 MachineMemOperand::Flags MMOFlags,
11251 const MMOMetadata &Metadata) {
11252 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
11253
11254 MMOFlags |= MachineMemOperand::MOStore;
11255 assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
11256 assert(!Metadata.Ranges && "range metadata is invalid for stores");
11257
11258 if (PtrInfo.V.isNull())
11259 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
11260
11263 MachineMemOperand *MMO =
11264 MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, Alignment, Metadata);
11265 return getStore(Chain, dl, Val, Ptr, MMO);
11266}
11267
11269 SDValue Ptr, MachineMemOperand *MMO) {
11271 return getStore(Chain, dl, Val, Ptr, Undef, Val.getValueType(), MMO,
11273}
11274
11276 SDValue Ptr, SDValue Offset, EVT SVT,
11278 bool IsTruncating) {
11279 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
11280 EVT VT = Val.getValueType();
11281 if (VT == SVT) {
11282 IsTruncating = false;
11283 } else if (!IsTruncating) {
11284 assert(VT == SVT && "No-truncating store from different memory type!");
11285 } else {
11287 "Should only be a truncating store, not extending!");
11288 assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!");
11289 assert(VT.isVector() == SVT.isVector() &&
11290 "Cannot use trunc store to convert to or from a vector!");
11291 assert((!VT.isVector() ||
11293 "Cannot use trunc store to change the number of vector elements!");
11294 }
11295
11296 bool Indexed = AM != ISD::UNINDEXED;
11297 assert((Indexed || Offset.getOpcode() == ISD::POISON) &&
11298 "Unindexed store with an offset!");
11299 SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other)
11300 : getVTList(MVT::Other);
11301 SDValue Ops[] = {Chain, Val, Ptr, Offset};
11302 SDNodeKey ID(ISD::STORE, VTs, Ops);
11303 ID.AddInteger(SVT.getRawBits());
11304 ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
11305 dl.getIROrder(), VTs, AM, IsTruncating, SVT, MMO));
11306 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11307 ID.AddInteger(MMO->getFlags());
11308 FoldingSetInsertToken InsertToken;
11309 if (SDNode *E = lookupNode(ID, dl, InsertToken)) {
11310 cast<StoreSDNode>(E)->refineAlignment(MMO);
11311 cast<StoreSDNode>(E)->refineMMOMetadata(MMO);
11312 return SDValue(E, 0);
11313 }
11314 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
11315 IsTruncating, SVT, MMO);
11316 createOperands(N, Ops);
11317
11318 CSEMap.insert(N, InsertToken);
11319 InsertNode(N);
11320 SDValue V(N, 0);
11321 NewSDValueDbgMsg(V, "Creating new node: ", this);
11322 return V;
11323}
11324
11326 SDValue Ptr, SDValue Offset,
11327 MachinePointerInfo PtrInfo, EVT SVT,
11328 Align Alignment,
11329 MachineMemOperand::Flags MMOFlags,
11330 const MMOMetadata &Metadata) {
11331 assert(Chain.getValueType() == MVT::Other &&
11332 "Invalid chain type");
11333
11334 MMOFlags |= MachineMemOperand::MOStore;
11335 assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
11336 assert(!Metadata.Ranges && "range metadata is invalid for stores");
11337
11338 if (PtrInfo.V.isNull())
11339 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
11340
11342 MachineMemOperand *MMO = MF.getMachineMemOperand(
11343 PtrInfo, MMOFlags, SVT.getStoreSize(), Alignment, Metadata);
11344 return getTruncStore(Chain, dl, Val, Ptr, Offset, SVT, MMO);
11345}
11346
11348 SDValue Ptr, MachinePointerInfo PtrInfo,
11349 EVT SVT, Align Alignment,
11350 MachineMemOperand::Flags MMOFlags,
11351 const MMOMetadata &Metadata) {
11352 return getTruncStore(Chain, dl, Val, Ptr, getPOISON(Ptr.getValueType()),
11353 PtrInfo, SVT, Alignment, MMOFlags, Metadata);
11354}
11355
11357 SDValue Ptr, SDValue Offset, EVT SVT,
11358 MachineMemOperand *MMO) {
11359 return getStore(Chain, dl, Val, Ptr, Offset, SVT, MMO, ISD::UNINDEXED, true);
11360}
11361
11363 SDValue Ptr, EVT SVT,
11364 MachineMemOperand *MMO) {
11365 return getStore(Chain, dl, Val, Ptr, getPOISON(Ptr.getValueType()), SVT, MMO,
11366 ISD::UNINDEXED, true);
11367}
11368
11372 StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
11373 assert(ST->getOffset().getOpcode() == ISD::POISON &&
11374 "Store is already a indexed store!");
11375 return getStore(ST->getChain(), dl, ST->getValue(), Base, Offset,
11376 ST->getMemoryVT(), ST->getMemOperand(), AM,
11377 ST->isTruncatingStore());
11378}
11379
11381 ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &dl,
11382 SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Mask, SDValue EVL,
11383 MachinePointerInfo PtrInfo, EVT MemVT, Align Alignment,
11384 MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
11385 const MDNode *Ranges, bool IsExpanding) {
11386 MMOFlags |= MachineMemOperand::MOLoad;
11387 assert((MMOFlags & MachineMemOperand::MOStore) == 0);
11388 // If we don't have a PtrInfo, infer the trivial frame index case to simplify
11389 // clients.
11390 if (PtrInfo.V.isNull())
11391 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
11392
11393 TypeSize Size = MemVT.getStoreSize();
11395 MachineMemOperand *MMO = MF.getMachineMemOperand(
11396 PtrInfo, MMOFlags, Size, Alignment, MMOMetadata(AAInfo, Ranges));
11397 return getLoadVP(AM, ExtType, VT, dl, Chain, Ptr, Offset, Mask, EVL, MemVT,
11398 MMO, IsExpanding);
11399}
11400
11402 ISD::LoadExtType ExtType, EVT VT,
11403 const SDLoc &dl, SDValue Chain, SDValue Ptr,
11404 SDValue Offset, SDValue Mask, SDValue EVL,
11405 EVT MemVT, MachineMemOperand *MMO,
11406 bool IsExpanding) {
11407 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
11408 assert(Mask.getValueType().getVectorElementCount() ==
11409 VT.getVectorElementCount() &&
11410 "Vector width mismatch between mask and data");
11411
11412 bool Indexed = AM != ISD::UNINDEXED;
11413 assert((Indexed || Offset.getOpcode() == ISD::POISON) &&
11414 "Unindexed load with an offset!");
11415
11416 SDVTList VTs = Indexed ? getVTList(VT, Ptr.getValueType(), MVT::Other)
11417 : getVTList(VT, MVT::Other);
11418 SDValue Ops[] = {Chain, Ptr, Offset, Mask, EVL};
11419 SDNodeKey ID(ISD::VP_LOAD, VTs, Ops);
11420 ID.AddInteger(MemVT.getRawBits());
11421 ID.AddInteger(getSyntheticNodeSubclassData<VPLoadSDNode>(
11422 dl.getIROrder(), VTs, AM, ExtType, IsExpanding, MemVT, MMO));
11423 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11424 ID.AddInteger(MMO->getFlags());
11425 FoldingSetInsertToken InsertToken;
11426 if (auto *E = cast_or_null<VPLoadSDNode>(lookupNode(ID, dl, InsertToken))) {
11427 E->refineAlignment(MMO);
11428 E->refineMMOMetadata(MMO);
11429 return SDValue(E, 0);
11430 }
11431 auto *N = newSDNode<VPLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
11432 ExtType, IsExpanding, MemVT, MMO);
11433 createOperands(N, Ops);
11434
11435 CSEMap.insert(N, InsertToken);
11436 InsertNode(N);
11437 SDValue V(N, 0);
11438 NewSDValueDbgMsg(V, "Creating new node: ", this);
11439 return V;
11440}
11441
11443 SDValue Ptr, SDValue Mask, SDValue EVL,
11444 MachinePointerInfo PtrInfo,
11445 MaybeAlign Alignment,
11446 MachineMemOperand::Flags MMOFlags,
11447 const AAMDNodes &AAInfo, const MDNode *Ranges,
11448 bool IsExpanding) {
11450 return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
11451 Mask, EVL, PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges,
11452 IsExpanding);
11453}
11454
11456 SDValue Ptr, SDValue Mask, SDValue EVL,
11457 MachineMemOperand *MMO, bool IsExpanding) {
11459 return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
11460 Mask, EVL, VT, MMO, IsExpanding);
11461}
11462
11464 EVT VT, SDValue Chain, SDValue Ptr,
11465 SDValue Mask, SDValue EVL,
11466 MachinePointerInfo PtrInfo, EVT MemVT,
11467 MaybeAlign Alignment,
11468 MachineMemOperand::Flags MMOFlags,
11469 const AAMDNodes &AAInfo, bool IsExpanding) {
11471 return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask,
11472 EVL, PtrInfo, MemVT, Alignment, MMOFlags, AAInfo, nullptr,
11473 IsExpanding);
11474}
11475
11477 EVT VT, SDValue Chain, SDValue Ptr,
11478 SDValue Mask, SDValue EVL, EVT MemVT,
11479 MachineMemOperand *MMO, bool IsExpanding) {
11481 return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask,
11482 EVL, MemVT, MMO, IsExpanding);
11483}
11484
11486 SDValue Ptr, SDValue Offset, SDValue Mask,
11487 SDValue EVL, EVT MemVT, MachineMemOperand *MMO,
11488 ISD::MemIndexedMode AM, bool IsTruncating,
11489 bool IsCompressing) {
11490 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
11491 assert(Mask.getValueType().getVectorElementCount() ==
11493 "Vector width mismatch between mask and data");
11494
11495 bool Indexed = AM != ISD::UNINDEXED;
11496 assert((Indexed || Offset.getOpcode() == ISD::POISON) &&
11497 "Unindexed vp_store with an offset!");
11498 SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other)
11499 : getVTList(MVT::Other);
11500 SDValue Ops[] = {Chain, Val, Ptr, Offset, Mask, EVL};
11501 SDNodeKey ID(ISD::VP_STORE, VTs, Ops);
11502 ID.AddInteger(MemVT.getRawBits());
11503 ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>(
11504 dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
11505 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11506 ID.AddInteger(MMO->getFlags());
11507 FoldingSetInsertToken InsertToken;
11508 if (SDNode *E = lookupNode(ID, dl, InsertToken)) {
11509 cast<VPStoreSDNode>(E)->refineAlignment(MMO);
11510 return SDValue(E, 0);
11511 }
11512 auto *N = newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
11513 IsTruncating, IsCompressing, MemVT, MMO);
11514 createOperands(N, Ops);
11515
11516 CSEMap.insert(N, InsertToken);
11517 InsertNode(N);
11518 SDValue V(N, 0);
11519 NewSDValueDbgMsg(V, "Creating new node: ", this);
11520 return V;
11521}
11522
11524 SDValue Val, SDValue Ptr, SDValue Mask,
11525 SDValue EVL, MachinePointerInfo PtrInfo,
11526 EVT SVT, Align Alignment,
11527 MachineMemOperand::Flags MMOFlags,
11528 const AAMDNodes &AAInfo,
11529 bool IsCompressing) {
11530 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
11531
11532 MMOFlags |= MachineMemOperand::MOStore;
11533 assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
11534
11535 if (PtrInfo.V.isNull())
11536 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
11537
11539 MachineMemOperand *MMO = MF.getMachineMemOperand(
11540 PtrInfo, MMOFlags, SVT.getStoreSize(), Alignment, AAInfo);
11541 return getTruncStoreVP(Chain, dl, Val, Ptr, Mask, EVL, SVT, MMO,
11542 IsCompressing);
11543}
11544
11546 SDValue Val, SDValue Ptr, SDValue Mask,
11547 SDValue EVL, EVT SVT,
11548 MachineMemOperand *MMO,
11549 bool IsCompressing) {
11550 EVT VT = Val.getValueType();
11551
11552 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
11553 if (VT == SVT)
11554 return getStoreVP(Chain, dl, Val, Ptr, getPOISON(Ptr.getValueType()), Mask,
11555 EVL, VT, MMO, ISD::UNINDEXED,
11556 /*IsTruncating*/ false, IsCompressing);
11557
11559 "Should only be a truncating store, not extending!");
11560 assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!");
11561 assert(VT.isVector() == SVT.isVector() &&
11562 "Cannot use trunc store to convert to or from a vector!");
11563 assert((!VT.isVector() ||
11565 "Cannot use trunc store to change the number of vector elements!");
11566
11567 SDVTList VTs = getVTList(MVT::Other);
11569 SDValue Ops[] = {Chain, Val, Ptr, Undef, Mask, EVL};
11570 SDNodeKey ID(ISD::VP_STORE, VTs, Ops);
11571 ID.AddInteger(SVT.getRawBits());
11572 ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>(
11573 dl.getIROrder(), VTs, ISD::UNINDEXED, true, IsCompressing, SVT, MMO));
11574 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11575 ID.AddInteger(MMO->getFlags());
11576 FoldingSetInsertToken InsertToken;
11577 if (SDNode *E = lookupNode(ID, dl, InsertToken)) {
11578 cast<VPStoreSDNode>(E)->refineAlignment(MMO);
11579 return SDValue(E, 0);
11580 }
11581 auto *N =
11582 newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
11583 ISD::UNINDEXED, true, IsCompressing, SVT, MMO);
11584 createOperands(N, Ops);
11585
11586 CSEMap.insert(N, InsertToken);
11587 InsertNode(N);
11588 SDValue V(N, 0);
11589 NewSDValueDbgMsg(V, "Creating new node: ", this);
11590 return V;
11591}
11592
11594 ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &DL,
11595 SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Stride, SDValue Mask,
11596 SDValue EVL, EVT MemVT, MachineMemOperand *MMO, bool IsExpanding) {
11597 bool Indexed = AM != ISD::UNINDEXED;
11598 assert((Indexed || Offset.getOpcode() == ISD::POISON) &&
11599 "Unindexed load with an offset!");
11600
11601 SDValue Ops[] = {Chain, Ptr, Offset, Stride, Mask, EVL};
11602 SDVTList VTs = Indexed ? getVTList(VT, Ptr.getValueType(), MVT::Other)
11603 : getVTList(VT, MVT::Other);
11604 SDNodeKey ID(ISD::EXPERIMENTAL_VP_STRIDED_LOAD, VTs, Ops);
11605 ID.AddInteger(MemVT.getRawBits());
11606 ID.AddInteger(getSyntheticNodeSubclassData<VPStridedLoadSDNode>(
11607 DL.getIROrder(), VTs, AM, ExtType, IsExpanding, MemVT, MMO));
11608 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11609
11610 FoldingSetInsertToken InsertToken;
11611 if (SDNode *E = lookupNode(ID, DL, InsertToken)) {
11612 cast<VPStridedLoadSDNode>(E)->refineAlignment(MMO);
11613 return SDValue(E, 0);
11614 }
11615
11616 auto *N =
11617 newSDNode<VPStridedLoadSDNode>(DL.getIROrder(), DL.getDebugLoc(), VTs, AM,
11618 ExtType, IsExpanding, MemVT, MMO);
11619 createOperands(N, Ops);
11620 CSEMap.insert(N, InsertToken);
11621 InsertNode(N);
11622 SDValue V(N, 0);
11623 NewSDValueDbgMsg(V, "Creating new node: ", this);
11624 return V;
11625}
11626
11628 SDValue Ptr, SDValue Stride,
11629 SDValue Mask, SDValue EVL,
11630 MachineMemOperand *MMO,
11631 bool IsExpanding) {
11633 return getStridedLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, DL, Chain, Ptr,
11634 Undef, Stride, Mask, EVL, VT, MMO, IsExpanding);
11635}
11636
11638 ISD::LoadExtType ExtType, const SDLoc &DL, EVT VT, SDValue Chain,
11639 SDValue Ptr, SDValue Stride, SDValue Mask, SDValue EVL, EVT MemVT,
11640 MachineMemOperand *MMO, bool IsExpanding) {
11642 return getStridedLoadVP(ISD::UNINDEXED, ExtType, VT, DL, Chain, Ptr, Undef,
11643 Stride, Mask, EVL, MemVT, MMO, IsExpanding);
11644}
11645
11647 SDValue Val, SDValue Ptr,
11648 SDValue Offset, SDValue Stride,
11649 SDValue Mask, SDValue EVL, EVT MemVT,
11650 MachineMemOperand *MMO,
11652 bool IsTruncating, bool IsCompressing) {
11653 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
11654 bool Indexed = AM != ISD::UNINDEXED;
11655 assert((Indexed || Offset.getOpcode() == ISD::POISON) &&
11656 "Unindexed vp_store with an offset!");
11657 SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other)
11658 : getVTList(MVT::Other);
11659 SDValue Ops[] = {Chain, Val, Ptr, Offset, Stride, Mask, EVL};
11660 SDNodeKey ID(ISD::EXPERIMENTAL_VP_STRIDED_STORE, VTs, Ops);
11661 ID.AddInteger(MemVT.getRawBits());
11662 ID.AddInteger(getSyntheticNodeSubclassData<VPStridedStoreSDNode>(
11663 DL.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
11664 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11665 FoldingSetInsertToken InsertToken;
11666 if (SDNode *E = lookupNode(ID, DL, InsertToken)) {
11667 cast<VPStridedStoreSDNode>(E)->refineAlignment(MMO);
11668 return SDValue(E, 0);
11669 }
11670 auto *N = newSDNode<VPStridedStoreSDNode>(DL.getIROrder(), DL.getDebugLoc(),
11671 VTs, AM, IsTruncating,
11672 IsCompressing, MemVT, MMO);
11673 createOperands(N, Ops);
11674
11675 CSEMap.insert(N, InsertToken);
11676 InsertNode(N);
11677 SDValue V(N, 0);
11678 NewSDValueDbgMsg(V, "Creating new node: ", this);
11679 return V;
11680}
11681
11684 ISD::MemIndexType IndexType) {
11685 assert(Ops.size() == 6 && "Incompatible number of operands");
11686
11687 SDNodeKey ID(ISD::VP_GATHER, VTs, Ops);
11688 ID.AddInteger(VT.getRawBits());
11689 ID.AddInteger(getSyntheticNodeSubclassData<VPGatherSDNode>(
11690 dl.getIROrder(), VTs, VT, MMO, IndexType));
11691 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11692 ID.AddInteger(MMO->getFlags());
11693 FoldingSetInsertToken InsertToken;
11694 if (SDNode *E = lookupNode(ID, dl, InsertToken)) {
11695 cast<VPGatherSDNode>(E)->refineAlignment(MMO);
11696 return SDValue(E, 0);
11697 }
11698
11699 auto *N = newSDNode<VPGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
11700 VT, MMO, IndexType);
11701 createOperands(N, Ops);
11702
11703 assert(N->getMask().getValueType().getVectorElementCount() ==
11704 N->getValueType(0).getVectorElementCount() &&
11705 "Vector width mismatch between mask and data");
11706 assert(N->getIndex().getValueType().getVectorElementCount().isScalable() ==
11707 N->getValueType(0).getVectorElementCount().isScalable() &&
11708 "Scalable flags of index and data do not match");
11710 N->getIndex().getValueType().getVectorElementCount(),
11711 N->getValueType(0).getVectorElementCount()) &&
11712 "Vector width mismatch between index and data");
11713 assert(isa<ConstantSDNode>(N->getScale()) &&
11714 N->getScale()->getAsAPIntVal().isPowerOf2() &&
11715 "Scale should be a constant power of 2");
11716
11717 CSEMap.insert(N, InsertToken);
11718 InsertNode(N);
11719 SDValue V(N, 0);
11720 NewSDValueDbgMsg(V, "Creating new node: ", this);
11721 return V;
11722}
11723
11726 MachineMemOperand *MMO,
11727 ISD::MemIndexType IndexType) {
11728 assert(Ops.size() == 7 && "Incompatible number of operands");
11729
11730 SDNodeKey ID(ISD::VP_SCATTER, VTs, Ops);
11731 ID.AddInteger(VT.getRawBits());
11732 ID.AddInteger(getSyntheticNodeSubclassData<VPScatterSDNode>(
11733 dl.getIROrder(), VTs, VT, MMO, IndexType));
11734 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11735 ID.AddInteger(MMO->getFlags());
11736 FoldingSetInsertToken InsertToken;
11737 if (SDNode *E = lookupNode(ID, dl, InsertToken)) {
11738 cast<VPScatterSDNode>(E)->refineAlignment(MMO);
11739 return SDValue(E, 0);
11740 }
11741 auto *N = newSDNode<VPScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
11742 VT, MMO, IndexType);
11743 createOperands(N, Ops);
11744
11745 assert(N->getMask().getValueType().getVectorElementCount() ==
11746 N->getValue().getValueType().getVectorElementCount() &&
11747 "Vector width mismatch between mask and data");
11748 assert(
11749 N->getIndex().getValueType().getVectorElementCount().isScalable() ==
11750 N->getValue().getValueType().getVectorElementCount().isScalable() &&
11751 "Scalable flags of index and data do not match");
11753 N->getIndex().getValueType().getVectorElementCount(),
11754 N->getValue().getValueType().getVectorElementCount()) &&
11755 "Vector width mismatch between index and data");
11756 assert(isa<ConstantSDNode>(N->getScale()) &&
11757 N->getScale()->getAsAPIntVal().isPowerOf2() &&
11758 "Scale should be a constant power of 2");
11759
11760 CSEMap.insert(N, InsertToken);
11761 InsertNode(N);
11762 SDValue V(N, 0);
11763 NewSDValueDbgMsg(V, "Creating new node: ", this);
11764 return V;
11765}
11766
11769 SDValue PassThru, EVT MemVT,
11770 MachineMemOperand *MMO,
11772 ISD::LoadExtType ExtTy, bool isExpanding) {
11773 bool Indexed = AM != ISD::UNINDEXED;
11774 assert((Indexed || Offset.getOpcode() == ISD::POISON) &&
11775 "Unindexed masked load with an offset!");
11776 SDVTList VTs = Indexed ? getVTList(VT, Base.getValueType(), MVT::Other)
11777 : getVTList(VT, MVT::Other);
11778 SDValue Ops[] = {Chain, Base, Offset, Mask, PassThru};
11779 SDNodeKey ID(ISD::MLOAD, VTs, Ops);
11780 ID.AddInteger(MemVT.getRawBits());
11781 ID.AddInteger(getSyntheticNodeSubclassData<MaskedLoadSDNode>(
11782 dl.getIROrder(), VTs, AM, ExtTy, isExpanding, MemVT, MMO));
11783 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11784 ID.AddInteger(MMO->getFlags());
11785 FoldingSetInsertToken InsertToken;
11786 if (SDNode *E = lookupNode(ID, dl, InsertToken)) {
11787 cast<MaskedLoadSDNode>(E)->refineAlignment(MMO);
11788 return SDValue(E, 0);
11789 }
11790 auto *N = newSDNode<MaskedLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
11791 AM, ExtTy, isExpanding, MemVT, MMO);
11792 createOperands(N, Ops);
11793
11794 CSEMap.insert(N, InsertToken);
11795 InsertNode(N);
11796 SDValue V(N, 0);
11797 NewSDValueDbgMsg(V, "Creating new node: ", this);
11798 return V;
11799}
11800
11805 assert(LD->getOffset().getOpcode() == ISD::POISON &&
11806 "Masked load is already a indexed load!");
11807 return getMaskedLoad(OrigLoad.getValueType(), dl, LD->getChain(), Base,
11808 Offset, LD->getMask(), LD->getPassThru(),
11809 LD->getMemoryVT(), LD->getMemOperand(), AM,
11810 LD->getExtensionType(), LD->isExpandingLoad());
11811}
11812
11815 SDValue Mask, EVT MemVT,
11816 MachineMemOperand *MMO,
11817 ISD::MemIndexedMode AM, bool IsTruncating,
11818 bool IsCompressing) {
11819 assert(Chain.getValueType() == MVT::Other &&
11820 "Invalid chain type");
11821 bool Indexed = AM != ISD::UNINDEXED;
11822 assert((Indexed || Offset.getOpcode() == ISD::POISON) &&
11823 "Unindexed masked store with an offset!");
11824 SDVTList VTs = Indexed ? getVTList(Base.getValueType(), MVT::Other)
11825 : getVTList(MVT::Other);
11826 SDValue Ops[] = {Chain, Val, Base, Offset, Mask};
11827 SDNodeKey ID(ISD::MSTORE, VTs, Ops);
11828 ID.AddInteger(MemVT.getRawBits());
11829 ID.AddInteger(getSyntheticNodeSubclassData<MaskedStoreSDNode>(
11830 dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
11831 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11832 ID.AddInteger(MMO->getFlags());
11833 FoldingSetInsertToken InsertToken;
11834 if (SDNode *E = lookupNode(ID, dl, InsertToken)) {
11835 cast<MaskedStoreSDNode>(E)->refineAlignment(MMO);
11836 return SDValue(E, 0);
11837 }
11838 auto *N =
11839 newSDNode<MaskedStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
11840 IsTruncating, IsCompressing, MemVT, MMO);
11841 createOperands(N, Ops);
11842
11843 CSEMap.insert(N, InsertToken);
11844 InsertNode(N);
11845 SDValue V(N, 0);
11846 NewSDValueDbgMsg(V, "Creating new node: ", this);
11847 return V;
11848}
11849
11854 assert(ST->getOffset().getOpcode() == ISD::POISON &&
11855 "Masked store is already a indexed store!");
11856 return getMaskedStore(ST->getChain(), dl, ST->getValue(), Base, Offset,
11857 ST->getMask(), ST->getMemoryVT(), ST->getMemOperand(),
11858 AM, ST->isTruncatingStore(), ST->isCompressingStore());
11859}
11860
11863 MachineMemOperand *MMO,
11864 ISD::MemIndexType IndexType,
11865 ISD::LoadExtType ExtTy) {
11866 assert(Ops.size() == 6 && "Incompatible number of operands");
11867
11868 SDNodeKey ID(ISD::MGATHER, VTs, Ops);
11869 ID.AddInteger(MemVT.getRawBits());
11870 ID.AddInteger(getSyntheticNodeSubclassData<MaskedGatherSDNode>(
11871 dl.getIROrder(), VTs, MemVT, MMO, IndexType, ExtTy));
11872 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11873 ID.AddInteger(MMO->getFlags());
11874 FoldingSetInsertToken InsertToken;
11875 if (SDNode *E = lookupNode(ID, dl, InsertToken)) {
11876 cast<MaskedGatherSDNode>(E)->refineAlignment(MMO);
11877 return SDValue(E, 0);
11878 }
11879
11880 auto *N = newSDNode<MaskedGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(),
11881 VTs, MemVT, MMO, IndexType, ExtTy);
11882 createOperands(N, Ops);
11883
11884 assert(N->getPassThru().getValueType() == N->getValueType(0) &&
11885 "Incompatible type of the PassThru value in MaskedGatherSDNode");
11886 assert(N->getMask().getValueType().getVectorElementCount() ==
11887 N->getValueType(0).getVectorElementCount() &&
11888 "Vector width mismatch between mask and data");
11889 assert(N->getIndex().getValueType().getVectorElementCount().isScalable() ==
11890 N->getValueType(0).getVectorElementCount().isScalable() &&
11891 "Scalable flags of index and data do not match");
11893 N->getIndex().getValueType().getVectorElementCount(),
11894 N->getValueType(0).getVectorElementCount()) &&
11895 "Vector width mismatch between index and data");
11896 assert(isa<ConstantSDNode>(N->getScale()) &&
11897 N->getScale()->getAsAPIntVal().isPowerOf2() &&
11898 "Scale should be a constant power of 2");
11899
11900 CSEMap.insert(N, InsertToken);
11901 InsertNode(N);
11902 SDValue V(N, 0);
11903 NewSDValueDbgMsg(V, "Creating new node: ", this);
11904 return V;
11905}
11906
11909 MachineMemOperand *MMO,
11910 ISD::MemIndexType IndexType,
11911 bool IsTrunc) {
11912 assert(Ops.size() == 6 && "Incompatible number of operands");
11913
11914 SDNodeKey ID(ISD::MSCATTER, VTs, Ops);
11915 ID.AddInteger(MemVT.getRawBits());
11916 ID.AddInteger(getSyntheticNodeSubclassData<MaskedScatterSDNode>(
11917 dl.getIROrder(), VTs, MemVT, MMO, IndexType, IsTrunc));
11918 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11919 ID.AddInteger(MMO->getFlags());
11920 FoldingSetInsertToken InsertToken;
11921 if (SDNode *E = lookupNode(ID, dl, InsertToken)) {
11922 cast<MaskedScatterSDNode>(E)->refineAlignment(MMO);
11923 return SDValue(E, 0);
11924 }
11925
11926 auto *N = newSDNode<MaskedScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(),
11927 VTs, MemVT, MMO, IndexType, IsTrunc);
11928 createOperands(N, Ops);
11929
11930 assert(N->getMask().getValueType().getVectorElementCount() ==
11931 N->getValue().getValueType().getVectorElementCount() &&
11932 "Vector width mismatch between mask and data");
11933 assert(
11934 N->getIndex().getValueType().getVectorElementCount().isScalable() ==
11935 N->getValue().getValueType().getVectorElementCount().isScalable() &&
11936 "Scalable flags of index and data do not match");
11938 N->getIndex().getValueType().getVectorElementCount(),
11939 N->getValue().getValueType().getVectorElementCount()) &&
11940 "Vector width mismatch between index and data");
11941 assert(isa<ConstantSDNode>(N->getScale()) &&
11942 N->getScale()->getAsAPIntVal().isPowerOf2() &&
11943 "Scale should be a constant power of 2");
11944
11945 CSEMap.insert(N, InsertToken);
11946 InsertNode(N);
11947 SDValue V(N, 0);
11948 NewSDValueDbgMsg(V, "Creating new node: ", this);
11949 return V;
11950}
11951
11953 const SDLoc &dl, ArrayRef<SDValue> Ops,
11954 MachineMemOperand *MMO,
11955 ISD::MemIndexType IndexType) {
11956 assert(Ops.size() == 7 && "Incompatible number of operands");
11957
11959 ID.AddInteger(MemVT.getRawBits());
11960 ID.AddInteger(getSyntheticNodeSubclassData<MaskedHistogramSDNode>(
11961 dl.getIROrder(), VTs, MemVT, MMO, IndexType));
11962 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11963 ID.AddInteger(MMO->getFlags());
11964 FoldingSetInsertToken InsertToken;
11965 if (SDNode *E = lookupNode(ID, dl, InsertToken)) {
11966 cast<MaskedGatherSDNode>(E)->refineAlignment(MMO);
11967 return SDValue(E, 0);
11968 }
11969
11970 auto *N = newSDNode<MaskedHistogramSDNode>(dl.getIROrder(), dl.getDebugLoc(),
11971 VTs, MemVT, MMO, IndexType);
11972 createOperands(N, Ops);
11973
11974 assert(N->getMask().getValueType().getVectorElementCount() ==
11975 N->getIndex().getValueType().getVectorElementCount() &&
11976 "Vector width mismatch between mask and data");
11977 assert(isa<ConstantSDNode>(N->getScale()) &&
11978 N->getScale()->getAsAPIntVal().isPowerOf2() &&
11979 "Scale should be a constant power of 2");
11980 assert(N->getInc().getValueType().isInteger() && "Non integer update value");
11981
11982 CSEMap.insert(N, InsertToken);
11983 InsertNode(N);
11984 SDValue V(N, 0);
11985 NewSDValueDbgMsg(V, "Creating new node: ", this);
11986 return V;
11987}
11988
11990 SDValue Ptr, SDValue Mask, SDValue EVL,
11991 MachineMemOperand *MMO) {
11992 SDVTList VTs = getVTList(VT, EVL.getValueType(), MVT::Other);
11993 SDValue Ops[] = {Chain, Ptr, Mask, EVL};
11994 SDNodeKey ID(ISD::VP_LOAD_FF, VTs, Ops);
11995 ID.AddInteger(VT.getRawBits());
11996 ID.AddInteger(getSyntheticNodeSubclassData<VPLoadFFSDNode>(DL.getIROrder(),
11997 VTs, VT, MMO));
11998 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11999 ID.AddInteger(MMO->getFlags());
12000 FoldingSetInsertToken InsertToken;
12001 if (SDNode *E = lookupNode(ID, DL, InsertToken)) {
12002 cast<VPLoadFFSDNode>(E)->refineAlignment(MMO);
12003 return SDValue(E, 0);
12004 }
12005 auto *N = newSDNode<VPLoadFFSDNode>(DL.getIROrder(), DL.getDebugLoc(), VTs,
12006 VT, MMO);
12007 createOperands(N, Ops);
12008
12009 CSEMap.insert(N, InsertToken);
12010 InsertNode(N);
12011 SDValue V(N, 0);
12012 NewSDValueDbgMsg(V, "Creating new node: ", this);
12013 return V;
12014}
12015
12017 EVT MemVT, MachineMemOperand *MMO) {
12018 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
12019 SDVTList VTs = getVTList(MVT::Other);
12020 SDValue Ops[] = {Chain, Ptr};
12022 ID.AddInteger(MemVT.getRawBits());
12023 ID.AddInteger(getSyntheticNodeSubclassData<FPStateAccessSDNode>(
12024 ISD::GET_FPENV_MEM, dl.getIROrder(), VTs, MemVT, MMO));
12025 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
12026 ID.AddInteger(MMO->getFlags());
12027 FoldingSetInsertToken InsertToken;
12028 if (SDNode *E = lookupNode(ID, dl, InsertToken))
12029 return SDValue(E, 0);
12030
12031 auto *N = newSDNode<FPStateAccessSDNode>(ISD::GET_FPENV_MEM, dl.getIROrder(),
12032 dl.getDebugLoc(), VTs, MemVT, MMO);
12033 createOperands(N, Ops);
12034
12035 CSEMap.insert(N, InsertToken);
12036 InsertNode(N);
12037 SDValue V(N, 0);
12038 NewSDValueDbgMsg(V, "Creating new node: ", this);
12039 return V;
12040}
12041
12043 EVT MemVT, MachineMemOperand *MMO) {
12044 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
12045 SDVTList VTs = getVTList(MVT::Other);
12046 SDValue Ops[] = {Chain, Ptr};
12048 ID.AddInteger(MemVT.getRawBits());
12049 ID.AddInteger(getSyntheticNodeSubclassData<FPStateAccessSDNode>(
12050 ISD::SET_FPENV_MEM, dl.getIROrder(), VTs, MemVT, MMO));
12051 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
12052 ID.AddInteger(MMO->getFlags());
12053 FoldingSetInsertToken InsertToken;
12054 if (SDNode *E = lookupNode(ID, dl, InsertToken))
12055 return SDValue(E, 0);
12056
12057 auto *N = newSDNode<FPStateAccessSDNode>(ISD::SET_FPENV_MEM, dl.getIROrder(),
12058 dl.getDebugLoc(), VTs, MemVT, MMO);
12059 createOperands(N, Ops);
12060
12061 CSEMap.insert(N, InsertToken);
12062 InsertNode(N);
12063 SDValue V(N, 0);
12064 NewSDValueDbgMsg(V, "Creating new node: ", this);
12065 return V;
12066}
12067
12069 // select undef, T, F --> T (if T is a constant), otherwise F
12070 // select, ?, undef, F --> F
12071 // select, ?, T, undef --> T
12072 if (Cond.isUndef())
12073 return isConstantValueOfAnyType(T) ? T : F;
12074 if (T.isUndef())
12076 if (F.isUndef())
12078
12079 // select true, T, F --> T
12080 // select false, T, F --> F
12081 if (auto C = isBoolConstant(Cond))
12082 return *C ? T : F;
12083
12084 // select ?, T, T --> T
12085 if (T == F)
12086 return T;
12087
12088 return SDValue();
12089}
12090
12092 // shift undef, Y --> 0 (can always assume that the undef value is 0)
12093 if (X.isUndef())
12094 return getConstant(0, SDLoc(X.getNode()), X.getValueType());
12095 // shift X, undef --> undef (because it may shift by the bitwidth)
12096 if (Y.isUndef())
12097 return getUNDEF(X.getValueType());
12098
12099 // shift 0, Y --> 0
12100 // shift X, 0 --> X
12102 return X;
12103
12104 // shift X, C >= bitwidth(X) --> undef
12105 // All vector elements must be too big (or undef) to avoid partial undefs.
12106 auto isShiftTooBig = [X](ConstantSDNode *Val) {
12107 return !Val || Val->getAPIntValue().uge(X.getScalarValueSizeInBits());
12108 };
12109 if (ISD::matchUnaryPredicate(Y, isShiftTooBig, true))
12110 return getUNDEF(X.getValueType());
12111
12112 // shift i1/vXi1 X, Y --> X (any non-zero shift amount is undefined).
12113 if (X.getValueType().getScalarType() == MVT::i1)
12114 return X;
12115
12116 return SDValue();
12117}
12118
12120 SDNodeFlags Flags) {
12121 // If this operation has 'nnan' or 'ninf' and at least 1 disallowed operand
12122 // (an undef operand can be chosen to be Nan/Inf), then the result of this
12123 // operation is poison. That result can be relaxed to undef.
12124 ConstantFPSDNode *XC = isConstOrConstSplatFP(X, /* AllowUndefs */ true);
12125 ConstantFPSDNode *YC = isConstOrConstSplatFP(Y, /* AllowUndefs */ true);
12126 bool HasNan = (XC && XC->getValueAPF().isNaN()) ||
12127 (YC && YC->getValueAPF().isNaN());
12128 bool HasInf = (XC && XC->getValueAPF().isInfinity()) ||
12129 (YC && YC->getValueAPF().isInfinity());
12130
12131 if (Flags.hasNoNaNs() && (HasNan || X.isUndef() || Y.isUndef()))
12132 return getUNDEF(X.getValueType());
12133
12134 if (Flags.hasNoInfs() && (HasInf || X.isUndef() || Y.isUndef()))
12135 return getUNDEF(X.getValueType());
12136
12137 if (!YC)
12138 return SDValue();
12139
12140 // X + -0.0 --> X
12141 if (Opcode == ISD::FADD)
12142 if (YC->getValueAPF().isNegZero())
12143 return X;
12144
12145 // X - +0.0 --> X
12146 if (Opcode == ISD::FSUB)
12147 if (YC->getValueAPF().isPosZero())
12148 return X;
12149
12150 // X * 1.0 --> X
12151 // X / 1.0 --> X
12152 if (Opcode == ISD::FMUL || Opcode == ISD::FDIV)
12153 if (YC->getValueAPF().isOne())
12154 return X;
12155
12156 // X * 0.0 --> 0.0
12157 if (Opcode == ISD::FMUL && Flags.hasNoNaNs() && Flags.hasNoSignedZeros())
12158 if (YC->getValueAPF().isZero())
12159 return getConstantFP(0.0, SDLoc(Y), Y.getValueType());
12160
12161 return SDValue();
12162}
12163
12165 SDValue Ptr, SDValue SV, unsigned Align) {
12166 SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, dl, MVT::i32) };
12167 return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops);
12168}
12169
12170SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
12172 switch (Ops.size()) {
12173 case 0: return getNode(Opcode, DL, VT);
12174 case 1: return getNode(Opcode, DL, VT, Ops[0].get());
12175 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
12176 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
12177 default: break;
12178 }
12179
12180 // Copy from an SDUse array into an SDValue array for use with
12181 // the regular getNode logic.
12183 return getNode(Opcode, DL, VT, NewOps);
12184}
12185
12186SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
12188 SDNodeFlags Flags;
12189 if (Inserter)
12190 Flags = Inserter->getFlags();
12191 return getNode(Opcode, DL, VT, Ops, Flags);
12192}
12193
12194SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
12195 ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
12196 unsigned NumOps = Ops.size();
12197 switch (NumOps) {
12198 case 0: return getNode(Opcode, DL, VT);
12199 case 1: return getNode(Opcode, DL, VT, Ops[0], Flags);
12200 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Flags);
12201 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2], Flags);
12202 default: break;
12203 }
12204
12205#ifndef NDEBUG
12206 for (const auto &Op : Ops)
12207 assert(Op.getOpcode() != ISD::DELETED_NODE &&
12208 "Operand is DELETED_NODE!");
12209#endif
12210
12211 switch (Opcode) {
12212 default: break;
12213 case ISD::BUILD_VECTOR:
12214 // Attempt to simplify BUILD_VECTOR.
12215 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
12216 return V;
12217 break;
12219 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
12220 return V;
12221 break;
12222 case ISD::SELECT_CC:
12223 assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
12224 assert(Ops[0].getValueType() == Ops[1].getValueType() &&
12225 "LHS and RHS of condition must have same type!");
12226 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
12227 "True and False arms of SelectCC must have same type!");
12228 assert(Ops[2].getValueType() == VT &&
12229 "select_cc node must be of same type as true and false value!");
12230 assert((!Ops[0].getValueType().isVector() ||
12231 Ops[0].getValueType().getVectorElementCount() ==
12232 VT.getVectorElementCount()) &&
12233 "Expected select_cc with vector result to have the same sized "
12234 "comparison type!");
12235 break;
12236 case ISD::BR_CC:
12237 assert(NumOps == 5 && "BR_CC takes 5 operands!");
12238 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
12239 "LHS/RHS of comparison should match types!");
12240 break;
12241 case ISD::VP_REDUCE_MUL:
12242 // If it is VP_REDUCE_MUL mask operation then turn it to VP_REDUCE_AND
12243 if (VT == MVT::i1)
12244 Opcode = ISD::VP_REDUCE_AND;
12245 break;
12246 case ISD::VP_REDUCE_ADD:
12247 // If it is VP_REDUCE_ADD mask operation then turn it to VP_REDUCE_XOR
12248 if (VT == MVT::i1)
12249 Opcode = ISD::VP_REDUCE_XOR;
12250 break;
12251 case ISD::VP_REDUCE_SMAX:
12252 case ISD::VP_REDUCE_UMIN:
12253 // If it is VP_REDUCE_SMAX/VP_REDUCE_UMIN mask operation then turn it to
12254 // VP_REDUCE_AND.
12255 if (VT == MVT::i1)
12256 Opcode = ISD::VP_REDUCE_AND;
12257 break;
12258 case ISD::VP_REDUCE_SMIN:
12259 case ISD::VP_REDUCE_UMAX:
12260 // If it is VP_REDUCE_SMIN/VP_REDUCE_UMAX mask operation then turn it to
12261 // VP_REDUCE_OR.
12262 if (VT == MVT::i1)
12263 Opcode = ISD::VP_REDUCE_OR;
12264 break;
12265 }
12266
12267 // Memoize nodes.
12268 SDNode *N;
12269 SDVTList VTs = getVTList(VT);
12270
12271 if (VT != MVT::Glue) {
12272 SDNodeKey ID(Opcode, VTs, Ops);
12273 FoldingSetInsertToken InsertToken;
12274
12275 if (SDNode *E = lookupNode(ID, DL, InsertToken)) {
12276 E->intersectFlagsWith(Flags);
12277 return SDValue(E, 0);
12278 }
12279
12280 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
12281 createOperands(N, Ops);
12282
12283 CSEMap.insert(N, InsertToken);
12284 } else {
12285 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
12286 createOperands(N, Ops);
12287 }
12288
12289 N->setFlags(Flags);
12290 InsertNode(N);
12291 SDValue V(N, 0);
12292 NewSDValueDbgMsg(V, "Creating new node: ", this);
12293 return V;
12294}
12295
12296SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
12297 ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) {
12298 SDNodeFlags Flags;
12299 if (Inserter)
12300 Flags = Inserter->getFlags();
12301 return getNode(Opcode, DL, getVTList(ResultTys), Ops, Flags);
12302}
12303
12304SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
12306 const SDNodeFlags Flags) {
12307 return getNode(Opcode, DL, getVTList(ResultTys), Ops, Flags);
12308}
12309
12310SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
12312 SDNodeFlags Flags;
12313 if (Inserter)
12314 Flags = Inserter->getFlags();
12315 return getNode(Opcode, DL, VTList, Ops, Flags);
12316}
12317
12318SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
12319 ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
12320 if (VTList.NumVTs == 1)
12321 return getNode(Opcode, DL, VTList.VTs[0], Ops, Flags);
12322
12323#ifndef NDEBUG
12324 for (const auto &Op : Ops)
12325 assert(Op.getOpcode() != ISD::DELETED_NODE &&
12326 "Operand is DELETED_NODE!");
12327#endif
12328
12329 if (SDValue V = FoldConstantArithmetic(Opcode, DL, VTList, Ops, Flags))
12330 return V;
12331
12332 switch (Opcode) {
12333 case ISD::SADDO:
12334 case ISD::UADDO:
12335 case ISD::SSUBO:
12336 case ISD::USUBO: {
12337 assert(VTList.NumVTs == 2 && Ops.size() == 2 &&
12338 "Invalid add/sub overflow op!");
12339 assert(VTList.VTs[0].isInteger() && VTList.VTs[1].isInteger() &&
12340 Ops[0].getValueType() == Ops[1].getValueType() &&
12341 Ops[0].getValueType() == VTList.VTs[0] &&
12342 "Binary operator types must match!");
12343 SDValue N1 = Ops[0], N2 = Ops[1];
12344 canonicalizeCommutativeBinop(Opcode, N1, N2);
12345
12346 // (X +- 0) -> X with zero-overflow.
12347 ConstantSDNode *N2CV = isConstOrConstSplat(N2, /*AllowUndefs*/ false,
12348 /*AllowTruncation*/ true);
12349 if (N2CV && N2CV->isZero()) {
12350 SDValue ZeroOverFlow = getConstant(0, DL, VTList.VTs[1]);
12351 return getNode(ISD::MERGE_VALUES, DL, VTList, {N1, ZeroOverFlow}, Flags);
12352 }
12353
12354 if (VTList.VTs[0].getScalarType() == MVT::i1 &&
12355 VTList.VTs[1].getScalarType() == MVT::i1) {
12356 SDValue F1 = getFreeze(N1);
12357 SDValue F2 = getFreeze(N2);
12358 // {vXi1,vXi1} (u/s)addo(vXi1 x, vXi1y) -> {xor(x,y),and(x,y)}
12359 if (Opcode == ISD::UADDO || Opcode == ISD::SADDO)
12360 return getNode(ISD::MERGE_VALUES, DL, VTList,
12361 {getNode(ISD::XOR, DL, VTList.VTs[0], F1, F2),
12362 getNode(ISD::AND, DL, VTList.VTs[1], F1, F2)},
12363 Flags);
12364 // {vXi1,vXi1} (u/s)subo(vXi1 x, vXi1y) -> {xor(x,y),and(~x,y)}
12365 if (Opcode == ISD::USUBO || Opcode == ISD::SSUBO) {
12366 SDValue NotF1 = getNOT(DL, F1, VTList.VTs[0]);
12367 return getNode(ISD::MERGE_VALUES, DL, VTList,
12368 {getNode(ISD::XOR, DL, VTList.VTs[0], F1, F2),
12369 getNode(ISD::AND, DL, VTList.VTs[1], NotF1, F2)},
12370 Flags);
12371 }
12372 }
12373 break;
12374 }
12375 case ISD::SADDO_CARRY:
12376 case ISD::UADDO_CARRY:
12377 case ISD::SSUBO_CARRY:
12378 case ISD::USUBO_CARRY:
12379 assert(VTList.NumVTs == 2 && Ops.size() == 3 &&
12380 "Invalid add/sub overflow op!");
12381 assert(VTList.VTs[0].isInteger() && VTList.VTs[1].isInteger() &&
12382 Ops[0].getValueType() == Ops[1].getValueType() &&
12383 Ops[0].getValueType() == VTList.VTs[0] &&
12384 Ops[2].getValueType() == VTList.VTs[1] &&
12385 "Binary operator types must match!");
12386 break;
12387 case ISD::SMUL_LOHI:
12388 case ISD::UMUL_LOHI: {
12389 assert(VTList.NumVTs == 2 && Ops.size() == 2 && "Invalid mul lo/hi op!");
12390 assert(VTList.VTs[0].isInteger() && VTList.VTs[0] == VTList.VTs[1] &&
12391 VTList.VTs[0] == Ops[0].getValueType() &&
12392 VTList.VTs[0] == Ops[1].getValueType() &&
12393 "Binary operator types must match!");
12394 break;
12395 }
12396 case ISD::FFREXP: {
12397 assert(VTList.NumVTs == 2 && Ops.size() == 1 && "Invalid ffrexp op!");
12398 assert(VTList.VTs[0].isFloatingPoint() && VTList.VTs[1].isInteger() &&
12399 VTList.VTs[0] == Ops[0].getValueType() && "frexp type mismatch");
12400
12402 int FrexpExp;
12403 APFloat FrexpMant =
12404 frexp(C->getValueAPF(), FrexpExp, APFloat::rmNearestTiesToEven);
12405 SDValue Result0 = getConstantFP(FrexpMant, DL, VTList.VTs[0]);
12406 SDValue Result1 = getSignedConstant(FrexpMant.isFinite() ? FrexpExp : 0,
12407 DL, VTList.VTs[1]);
12408 return getNode(ISD::MERGE_VALUES, DL, VTList, {Result0, Result1}, Flags);
12409 }
12410
12411 break;
12412 }
12414 assert(VTList.NumVTs == 2 && Ops.size() == 2 &&
12415 "Invalid STRICT_FP_EXTEND!");
12416 assert(VTList.VTs[0].isFloatingPoint() &&
12417 Ops[1].getValueType().isFloatingPoint() && "Invalid FP cast!");
12418 assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
12419 "STRICT_FP_EXTEND result type should be vector iff the operand "
12420 "type is vector!");
12421 assert((!VTList.VTs[0].isVector() ||
12422 VTList.VTs[0].getVectorElementCount() ==
12423 Ops[1].getValueType().getVectorElementCount()) &&
12424 "Vector element count mismatch!");
12425 assert(Ops[1].getValueType().bitsLT(VTList.VTs[0]) &&
12426 "Invalid fpext node, dst <= src!");
12427 break;
12429 assert(VTList.NumVTs == 2 && Ops.size() == 3 && "Invalid STRICT_FP_ROUND!");
12430 assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
12431 "STRICT_FP_ROUND result type should be vector iff the operand "
12432 "type is vector!");
12433 assert((!VTList.VTs[0].isVector() ||
12434 VTList.VTs[0].getVectorElementCount() ==
12435 Ops[1].getValueType().getVectorElementCount()) &&
12436 "Vector element count mismatch!");
12437 assert(VTList.VTs[0].isFloatingPoint() &&
12438 Ops[1].getValueType().isFloatingPoint() &&
12439 VTList.VTs[0].bitsLT(Ops[1].getValueType()) &&
12440 Ops[2].getOpcode() == ISD::TargetConstant &&
12441 (Ops[2]->getAsZExtVal() == 0 || Ops[2]->getAsZExtVal() == 1) &&
12442 "Invalid STRICT_FP_ROUND!");
12443 break;
12444 }
12445
12446 // Memoize the node unless it returns a glue result.
12447 SDNode *N;
12448 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
12449 SDNodeKey ID(Opcode, VTList, Ops);
12450 FoldingSetInsertToken InsertToken;
12451 if (SDNode *E = lookupNode(ID, DL, InsertToken)) {
12452 E->intersectFlagsWith(Flags);
12453 return SDValue(E, 0);
12454 }
12455
12456 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
12457 createOperands(N, Ops);
12458 CSEMap.insert(N, InsertToken);
12459 } else {
12460 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
12461 createOperands(N, Ops);
12462 }
12463
12464 N->setFlags(Flags);
12465 InsertNode(N);
12466 SDValue V(N, 0);
12467 NewSDValueDbgMsg(V, "Creating new node: ", this);
12468 return V;
12469}
12470
12471SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
12472 SDVTList VTList) {
12473 return getNode(Opcode, DL, VTList, ArrayRef<SDValue>());
12474}
12475
12476SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
12477 SDValue N1) {
12478 SDValue Ops[] = { N1 };
12479 return getNode(Opcode, DL, VTList, Ops);
12480}
12481
12482SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
12483 SDValue N1, SDValue N2) {
12484 SDValue Ops[] = { N1, N2 };
12485 return getNode(Opcode, DL, VTList, Ops);
12486}
12487
12488SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
12489 SDValue N1, SDValue N2, SDValue N3) {
12490 SDValue Ops[] = { N1, N2, N3 };
12491 return getNode(Opcode, DL, VTList, Ops);
12492}
12493
12494SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
12495 SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
12496 SDValue Ops[] = { N1, N2, N3, N4 };
12497 return getNode(Opcode, DL, VTList, Ops);
12498}
12499
12500SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
12501 SDValue N1, SDValue N2, SDValue N3, SDValue N4,
12502 SDValue N5) {
12503 SDValue Ops[] = { N1, N2, N3, N4, N5 };
12504 return getNode(Opcode, DL, VTList, Ops);
12505}
12506
12508 if (!VT.isExtended())
12509 return makeVTList(SDNode::getValueTypeList(VT.getSimpleVT()), 1);
12510
12511 EVT VTs[] = {VT};
12512 return getVTList(VTs);
12513}
12514
12516 EVT VTs[] = {VT1, VT2};
12517 return getVTList(VTs);
12518}
12519
12521 EVT VTs[] = {VT1, VT2, VT3};
12522 return getVTList(VTs);
12523}
12524
12526 EVT VTs[] = {VT1, VT2, VT3, VT4};
12527 return getVTList(VTs);
12528}
12529
12531 auto It = VTLists.find(VTs);
12532 if (It == VTLists.end()) {
12533 EVT *Array = Allocator.Allocate<EVT>(VTs.size());
12534 llvm::copy(VTs, Array);
12535 It = VTLists.insert(ArrayRef(Array, VTs.size())).first;
12536 }
12537 return makeVTList(It->data(), It->size());
12538}
12539
12540/// UpdateNodeOperands - *Mutate* the specified node in-place to have the
12541/// specified operands. If the resultant node already exists in the DAG,
12542/// this does not modify the specified node, instead it returns the node that
12543/// already exists. If the resultant node does not exist in the DAG, the
12544/// input node is returned. As a degenerate case, if you specify the same
12545/// input operands as the node already has, the input node is returned.
12547 assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
12548
12549 // Check to see if there is no change.
12550 if (Op == N->getOperand(0)) return N;
12551
12552 // See if the modified node already exists.
12553 FoldingSetInsertToken InsertToken;
12554 if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertToken)) {
12555 Existing->intersectFlagsWith(N->getFlags());
12556 return Existing;
12557 }
12558
12559 // Nope it doesn't. Remove the node from its current place in the maps.
12560 if (InsertToken)
12561 if (!RemoveNodeFromCSEMaps(N))
12562 InsertToken = {};
12563
12564 // Now we update the operands.
12565 N->OperandList[0].set(Op);
12566
12568 // If this gets put into a CSE map, add it.
12569 if (InsertToken)
12570 CSEMap.insert(N, InsertToken);
12571 return N;
12572}
12573
12575 assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
12576
12577 // Check to see if there is no change.
12578 if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
12579 return N; // No operands changed, just return the input node.
12580
12581 // See if the modified node already exists.
12582 FoldingSetInsertToken InsertToken;
12583 if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertToken)) {
12584 Existing->intersectFlagsWith(N->getFlags());
12585 return Existing;
12586 }
12587
12588 // Nope it doesn't. Remove the node from its current place in the maps.
12589 if (InsertToken)
12590 if (!RemoveNodeFromCSEMaps(N))
12591 InsertToken = {};
12592
12593 // Now we update the operands.
12594 if (N->OperandList[0] != Op1)
12595 N->OperandList[0].set(Op1);
12596 if (N->OperandList[1] != Op2)
12597 N->OperandList[1].set(Op2);
12598
12600 // If this gets put into a CSE map, add it.
12601 if (InsertToken)
12602 CSEMap.insert(N, InsertToken);
12603 return N;
12604}
12605
12608 SDValue Ops[] = { Op1, Op2, Op3 };
12609 return UpdateNodeOperands(N, Ops);
12610}
12611
12614 SDValue Op3, SDValue Op4) {
12615 SDValue Ops[] = { Op1, Op2, Op3, Op4 };
12616 return UpdateNodeOperands(N, Ops);
12617}
12618
12621 SDValue Op3, SDValue Op4, SDValue Op5) {
12622 SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 };
12623 return UpdateNodeOperands(N, Ops);
12624}
12625
12628 unsigned NumOps = Ops.size();
12629 assert(N->getNumOperands() == NumOps &&
12630 "Update with wrong number of operands");
12631
12632 // If no operands changed just return the input node.
12633 if (std::equal(Ops.begin(), Ops.end(), N->op_begin()))
12634 return N;
12635
12636 // See if the modified node already exists.
12637 FoldingSetInsertToken InsertToken;
12638 if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertToken)) {
12639 Existing->intersectFlagsWith(N->getFlags());
12640 return Existing;
12641 }
12642
12643 // Nope it doesn't. Remove the node from its current place in the maps.
12644 if (InsertToken)
12645 if (!RemoveNodeFromCSEMaps(N))
12646 InsertToken = {};
12647
12648 // Now we update the operands.
12649 for (unsigned i = 0; i != NumOps; ++i)
12650 if (N->OperandList[i] != Ops[i])
12651 N->OperandList[i].set(Ops[i]);
12652
12654 // If this gets put into a CSE map, add it.
12655 if (InsertToken)
12656 CSEMap.insert(N, InsertToken);
12657 return N;
12658}
12659
12660/// DropOperands - Release the operands and set this node to have
12661/// zero operands.
12663 // Unlike the code in MorphNodeTo that does this, we don't need to
12664 // watch for dead nodes here.
12665 for (op_iterator I = op_begin(), E = op_end(); I != E; ) {
12666 SDUse &Use = *I++;
12667 Use.set(SDValue());
12668 }
12669}
12670
12672 ArrayRef<MachineMemOperand *> NewMemRefs) {
12673 if (NewMemRefs.empty()) {
12674 N->clearMemRefs();
12675 return;
12676 }
12677
12678 // Check if we can avoid allocating by storing a single reference directly.
12679 if (NewMemRefs.size() == 1) {
12680 N->MemRefs = NewMemRefs[0];
12681 N->NumMemRefs = 1;
12682 return;
12683 }
12684
12685 MachineMemOperand **MemRefsBuffer =
12686 Allocator.template Allocate<MachineMemOperand *>(NewMemRefs.size());
12687 llvm::copy(NewMemRefs, MemRefsBuffer);
12688 N->MemRefs = MemRefsBuffer;
12689 N->NumMemRefs = static_cast<int>(NewMemRefs.size());
12690}
12691
12692/// SelectNodeTo - These are wrappers around MorphNodeTo that accept a
12693/// machine opcode.
12694///
12696 EVT VT) {
12697 SDVTList VTs = getVTList(VT);
12698 return SelectNodeTo(N, MachineOpc, VTs, {});
12699}
12700
12702 EVT VT, SDValue Op1) {
12703 SDVTList VTs = getVTList(VT);
12704 SDValue Ops[] = { Op1 };
12705 return SelectNodeTo(N, MachineOpc, VTs, Ops);
12706}
12707
12709 EVT VT, SDValue Op1,
12710 SDValue Op2) {
12711 SDVTList VTs = getVTList(VT);
12712 SDValue Ops[] = { Op1, Op2 };
12713 return SelectNodeTo(N, MachineOpc, VTs, Ops);
12714}
12715
12717 EVT VT, SDValue Op1,
12718 SDValue Op2, SDValue Op3) {
12719 SDVTList VTs = getVTList(VT);
12720 SDValue Ops[] = { Op1, Op2, Op3 };
12721 return SelectNodeTo(N, MachineOpc, VTs, Ops);
12722}
12723
12726 SDVTList VTs = getVTList(VT);
12727 return SelectNodeTo(N, MachineOpc, VTs, Ops);
12728}
12729
12731 EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) {
12732 SDVTList VTs = getVTList(VT1, VT2);
12733 return SelectNodeTo(N, MachineOpc, VTs, Ops);
12734}
12735
12737 EVT VT1, EVT VT2) {
12738 SDVTList VTs = getVTList(VT1, VT2);
12739 return SelectNodeTo(N, MachineOpc, VTs, {});
12740}
12741
12743 EVT VT1, EVT VT2, EVT VT3,
12745 SDVTList VTs = getVTList(VT1, VT2, VT3);
12746 return SelectNodeTo(N, MachineOpc, VTs, Ops);
12747}
12748
12750 EVT VT1, EVT VT2,
12751 SDValue Op1, SDValue Op2) {
12752 SDVTList VTs = getVTList(VT1, VT2);
12753 SDValue Ops[] = { Op1, Op2 };
12754 return SelectNodeTo(N, MachineOpc, VTs, Ops);
12755}
12756
12759 SDNode *New = MorphNodeTo(N, ~MachineOpc, VTs, Ops);
12760 // Reset the NodeID to -1.
12761 New->setNodeId(-1);
12762 if (New != N) {
12763 ReplaceAllUsesWith(N, New);
12765 }
12766 return New;
12767}
12768
12769/// UpdateSDLocOnMergeSDNode - If the opt level is -O0 then it throws away
12770/// the line number information on the merged node since it is not possible to
12771/// preserve the information that operation is associated with multiple lines.
12772/// This will make the debugger work better at -O0, where there is a higher
12773/// probability of having other instructions associated with that line.
12774///
12775/// For IROrder, we keep the smaller of the two
12776SDNode *SelectionDAG::UpdateSDLocOnMergeSDNode(SDNode *N, const SDLoc &OLoc) {
12777 DebugLoc NLoc = N->getDebugLoc();
12778 if (NLoc && OptLevel == CodeGenOptLevel::None && OLoc.getDebugLoc() != NLoc) {
12779 N->setDebugLoc(DebugLoc());
12780 }
12781 unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder());
12782 N->setIROrder(Order);
12783 return N;
12784}
12785
12786/// MorphNodeTo - This *mutates* the specified node to have the specified
12787/// return type, opcode, and operands.
12788///
12789/// Note that MorphNodeTo returns the resultant node. If there is already a
12790/// node of the specified opcode and operands, it returns that node instead of
12791/// the current one. Note that the SDLoc need not be the same.
12792///
12793/// Using MorphNodeTo is faster than creating a new node and swapping it in
12794/// with ReplaceAllUsesWith both because it often avoids allocating a new
12795/// node, and because it doesn't require CSE recalculation for any of
12796/// the node's users.
12797///
12798/// However, note that MorphNodeTo recursively deletes dead nodes from the DAG.
12799/// As a consequence it isn't appropriate to use from within the DAG combiner or
12800/// the legalizer which maintain worklists that would need to be updated when
12801/// deleting things.
12804 // If an identical node already exists, use it.
12805 FoldingSetInsertToken InsertToken;
12806 if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) {
12807 SDNodeKey ID(Opc, VTs, Ops);
12808 AddNodeIDCustom(ID.Tail, N, Opc);
12809 if (SDNode *ON = lookupNode(ID, SDLoc(N), InsertToken))
12810 return UpdateSDLocOnMergeSDNode(ON, SDLoc(N));
12811 }
12812
12813 if (!RemoveNodeFromCSEMaps(N))
12814 InsertToken = {};
12815
12816 // Start the morphing.
12817 N->NodeType = Opc;
12818 N->ValueList = VTs.VTs;
12819 N->NumValues = VTs.NumVTs;
12820
12821 // Clear the operands list, updating used nodes to remove this from their
12822 // use list. Keep track of any operands that become dead as a result.
12823 SmallPtrSet<SDNode*, 16> DeadNodeSet;
12824 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
12825 SDUse &Use = *I++;
12826 SDNode *Used = Use.getNode();
12827 Use.set(SDValue());
12828 if (Used->use_empty())
12829 DeadNodeSet.insert(Used);
12830 }
12831
12832 // For MachineNode, initialize the memory references information.
12834 MN->clearMemRefs();
12835
12836 // Swap for an appropriately sized array from the recycler.
12837 removeOperands(N);
12838 createOperands(N, Ops);
12839
12840 // Delete any nodes that are still dead after adding the uses for the
12841 // new operands.
12842 if (!DeadNodeSet.empty()) {
12843 SmallVector<SDNode *, 16> DeadNodes;
12844 for (SDNode *N : DeadNodeSet)
12845 if (N->use_empty())
12846 DeadNodes.push_back(N);
12847 RemoveDeadNodes(DeadNodes);
12848 }
12849
12850 if (InsertToken)
12851 CSEMap.insert(N, InsertToken); // Memoize the new node.
12852 return N;
12853}
12854
12856 unsigned OrigOpc = Node->getOpcode();
12857 unsigned NewOpc;
12858 switch (OrigOpc) {
12859 default:
12860 llvm_unreachable("mutateStrictFPToFP called with unexpected opcode!");
12861#define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \
12862 case ISD::STRICT_##DAGN: NewOpc = ISD::DAGN; break;
12863#define CMP_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \
12864 case ISD::STRICT_##DAGN: NewOpc = ISD::SETCC; break;
12865#include "llvm/IR/ConstrainedOps.def"
12866 }
12867
12868 assert(Node->getNumValues() == 2 && "Unexpected number of results!");
12869
12870 // We're taking this node out of the chain, so we need to re-link things.
12871 SDValue InputChain = Node->getOperand(0);
12872 SDValue OutputChain = SDValue(Node, 1);
12873 ReplaceAllUsesOfValueWith(OutputChain, InputChain);
12874
12876 for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
12877 Ops.push_back(Node->getOperand(i));
12878
12879 SDVTList VTs = getVTList(Node->getValueType(0));
12880 SDNode *Res = MorphNodeTo(Node, NewOpc, VTs, Ops);
12881
12882 // MorphNodeTo can operate in two ways: if an existing node with the
12883 // specified operands exists, it can just return it. Otherwise, it
12884 // updates the node in place to have the requested operands.
12885 if (Res == Node) {
12886 // If we updated the node in place, reset the node ID. To the isel,
12887 // this should be just like a newly allocated machine node.
12888 Res->setNodeId(-1);
12889 } else {
12892 }
12893
12894 return Res;
12895}
12896
12897/// getMachineNode - These are used for target selectors to create a new node
12898/// with specified return type(s), MachineInstr opcode, and operands.
12899///
12900/// Note that getMachineNode returns the resultant node. If there is already a
12901/// node of the specified opcode and operands, it returns that node instead of
12902/// the current one.
12904 EVT VT) {
12905 SDVTList VTs = getVTList(VT);
12906 return getMachineNode(Opcode, dl, VTs, {});
12907}
12908
12910 EVT VT, SDValue Op1) {
12911 SDVTList VTs = getVTList(VT);
12912 SDValue Ops[] = { Op1 };
12913 return getMachineNode(Opcode, dl, VTs, Ops);
12914}
12915
12917 EVT VT, SDValue Op1, SDValue Op2) {
12918 SDVTList VTs = getVTList(VT);
12919 SDValue Ops[] = { Op1, Op2 };
12920 return getMachineNode(Opcode, dl, VTs, Ops);
12921}
12922
12924 EVT VT, SDValue Op1, SDValue Op2,
12925 SDValue Op3) {
12926 SDVTList VTs = getVTList(VT);
12927 SDValue Ops[] = { Op1, Op2, Op3 };
12928 return getMachineNode(Opcode, dl, VTs, Ops);
12929}
12930
12933 SDVTList VTs = getVTList(VT);
12934 return getMachineNode(Opcode, dl, VTs, Ops);
12935}
12936
12938 EVT VT1, EVT VT2, SDValue Op1,
12939 SDValue Op2) {
12940 SDVTList VTs = getVTList(VT1, VT2);
12941 SDValue Ops[] = { Op1, Op2 };
12942 return getMachineNode(Opcode, dl, VTs, Ops);
12943}
12944
12946 EVT VT1, EVT VT2, SDValue Op1,
12947 SDValue Op2, SDValue Op3) {
12948 SDVTList VTs = getVTList(VT1, VT2);
12949 SDValue Ops[] = { Op1, Op2, Op3 };
12950 return getMachineNode(Opcode, dl, VTs, Ops);
12951}
12952
12954 EVT VT1, EVT VT2,
12956 SDVTList VTs = getVTList(VT1, VT2);
12957 return getMachineNode(Opcode, dl, VTs, Ops);
12958}
12959
12961 EVT VT1, EVT VT2, EVT VT3,
12962 SDValue Op1, SDValue Op2) {
12963 SDVTList VTs = getVTList(VT1, VT2, VT3);
12964 SDValue Ops[] = { Op1, Op2 };
12965 return getMachineNode(Opcode, dl, VTs, Ops);
12966}
12967
12969 EVT VT1, EVT VT2, EVT VT3,
12970 SDValue Op1, SDValue Op2,
12971 SDValue Op3) {
12972 SDVTList VTs = getVTList(VT1, VT2, VT3);
12973 SDValue Ops[] = { Op1, Op2, Op3 };
12974 return getMachineNode(Opcode, dl, VTs, Ops);
12975}
12976
12978 EVT VT1, EVT VT2, EVT VT3,
12980 SDVTList VTs = getVTList(VT1, VT2, VT3);
12981 return getMachineNode(Opcode, dl, VTs, Ops);
12982}
12983
12985 ArrayRef<EVT> ResultTys,
12987 SDVTList VTs = getVTList(ResultTys);
12988 return getMachineNode(Opcode, dl, VTs, Ops);
12989}
12990
12992 SDVTList VTs,
12994 bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue;
12996 FoldingSetInsertToken InsertToken;
12997
12998 if (DoCSE) {
12999 SDNodeKey ID(~Opcode, VTs, Ops);
13000 if (SDNode *E = lookupNode(ID, DL, InsertToken)) {
13001 return cast<MachineSDNode>(UpdateSDLocOnMergeSDNode(E, DL));
13002 }
13003 }
13004
13005 // Allocate a new MachineSDNode.
13006 N = newSDNode<MachineSDNode>(~Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
13007 createOperands(N, Ops);
13008
13009 if (DoCSE)
13010 CSEMap.insert(N, InsertToken);
13011
13012 InsertNode(N);
13013 NewSDValueDbgMsg(SDValue(N, 0), "Creating new machine node: ", this);
13014 return N;
13015}
13016
13017/// getTargetExtractSubreg - A convenience function for creating
13018/// TargetOpcode::EXTRACT_SUBREG nodes.
13020 SDValue Operand) {
13021 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
13022 SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,
13023 VT, Operand, SRIdxVal);
13024 return SDValue(Subreg, 0);
13025}
13026
13027/// getTargetInsertSubreg - A convenience function for creating
13028/// TargetOpcode::INSERT_SUBREG nodes.
13030 SDValue Operand, SDValue Subreg) {
13031 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
13032 SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL,
13033 VT, Operand, Subreg, SRIdxVal);
13034 return SDValue(Result, 0);
13035}
13036
13037/// getNodeIfExists - Get the specified node if it's already available, or
13038/// else return NULL.
13041 bool AllowCommute) {
13042 SDNodeFlags Flags;
13043 if (Inserter)
13044 Flags = Inserter->getFlags();
13045 return getNodeIfExists(Opcode, VTList, Ops, Flags, AllowCommute);
13046}
13047
13050 const SDNodeFlags Flags,
13051 bool AllowCommute) {
13052 if (VTList.VTs[VTList.NumVTs - 1] == MVT::Glue)
13053 return nullptr;
13054
13055 auto Lookup = [&](ArrayRef<SDValue> LookupOps) -> SDNode * {
13056 SDNodeKey ID(Opcode, VTList, LookupOps);
13057 FoldingSetInsertToken InsertToken;
13058 if (SDNode *E = lookupNode(ID, InsertToken)) {
13059 E->intersectFlagsWith(Flags);
13060 return E;
13061 }
13062 return nullptr;
13063 };
13064
13065 if (SDNode *Existing = Lookup(Ops))
13066 return Existing;
13067
13068 if (AllowCommute && TLI->isCommutativeBinOp(Opcode))
13069 return Lookup({Ops[1], Ops[0]});
13070
13071 return nullptr;
13072}
13073
13074/// doesNodeExist - Check if a node exists without modifying its flags.
13075bool SelectionDAG::doesNodeExist(unsigned Opcode, SDVTList VTList,
13077 if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
13078 SDNodeKey ID(Opcode, VTList, Ops);
13079 FoldingSetInsertToken InsertToken;
13080 if (lookupNode(ID, SDLoc(), InsertToken))
13081 return true;
13082 }
13083 return false;
13084}
13085
13086/// getDbgValue - Creates a SDDbgValue node.
13087///
13088/// SDNode
13090 SDNode *N, unsigned R, bool IsIndirect,
13091 const DebugLoc &DL, unsigned O) {
13092 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
13093 "Expected inlined-at fields to agree");
13094 return new (DbgInfo->getAlloc())
13095 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromNode(N, R),
13096 {}, IsIndirect, DL, O,
13097 /*IsVariadic=*/false);
13098}
13099
13100/// Constant
13102 DIExpression *Expr,
13103 const Value *C,
13104 const DebugLoc &DL, unsigned O) {
13105 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
13106 "Expected inlined-at fields to agree");
13107 return new (DbgInfo->getAlloc())
13108 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromConst(C), {},
13109 /*IsIndirect=*/false, DL, O,
13110 /*IsVariadic=*/false);
13111}
13112
13113/// FrameIndex
13115 DIExpression *Expr, unsigned FI,
13116 bool IsIndirect,
13117 const DebugLoc &DL,
13118 unsigned O) {
13119 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
13120 "Expected inlined-at fields to agree");
13121 return getFrameIndexDbgValue(Var, Expr, FI, {}, IsIndirect, DL, O);
13122}
13123
13124/// FrameIndex with dependencies
13126 DIExpression *Expr, unsigned FI,
13127 ArrayRef<SDNode *> Dependencies,
13128 bool IsIndirect,
13129 const DebugLoc &DL,
13130 unsigned O) {
13131 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
13132 "Expected inlined-at fields to agree");
13133 return new (DbgInfo->getAlloc())
13134 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromFrameIdx(FI),
13135 Dependencies, IsIndirect, DL, O,
13136 /*IsVariadic=*/false);
13137}
13138
13139/// VReg
13141 Register VReg, bool IsIndirect,
13142 const DebugLoc &DL, unsigned O) {
13143 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
13144 "Expected inlined-at fields to agree");
13145 return new (DbgInfo->getAlloc())
13146 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromVReg(VReg),
13147 {}, IsIndirect, DL, O,
13148 /*IsVariadic=*/false);
13149}
13150
13153 ArrayRef<SDNode *> Dependencies,
13154 bool IsIndirect, const DebugLoc &DL,
13155 unsigned O, bool IsVariadic) {
13156 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
13157 "Expected inlined-at fields to agree");
13158 return new (DbgInfo->getAlloc())
13159 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, Locs, Dependencies, IsIndirect,
13160 DL, O, IsVariadic);
13161}
13162
13164 unsigned OffsetInBits, unsigned SizeInBits,
13165 bool InvalidateDbg) {
13166 SDNode *FromNode = From.getNode();
13167 SDNode *ToNode = To.getNode();
13168 assert(FromNode && ToNode && "Can't modify dbg values");
13169
13170 // PR35338
13171 // TODO: assert(From != To && "Redundant dbg value transfer");
13172 // TODO: assert(FromNode != ToNode && "Intranode dbg value transfer");
13173 if (From == To || FromNode == ToNode)
13174 return;
13175
13176 if (!FromNode->getHasDebugValue())
13177 return;
13178
13179 SDDbgOperand FromLocOp =
13180 SDDbgOperand::fromNode(From.getNode(), From.getResNo());
13182
13184 for (SDDbgValue *Dbg : GetDbgValues(FromNode)) {
13185 if (Dbg->isInvalidated())
13186 continue;
13187
13188 // TODO: assert(!Dbg->isInvalidated() && "Transfer of invalid dbg value");
13189
13190 // Create a new location ops vector that is equal to the old vector, but
13191 // with each instance of FromLocOp replaced with ToLocOp.
13192 bool Changed = false;
13193 auto NewLocOps = Dbg->copyLocationOps();
13194 std::replace_if(
13195 NewLocOps.begin(), NewLocOps.end(),
13196 [&Changed, FromLocOp](const SDDbgOperand &Op) {
13197 bool Match = Op == FromLocOp;
13198 Changed |= Match;
13199 return Match;
13200 },
13201 ToLocOp);
13202 // Ignore this SDDbgValue if we didn't find a matching location.
13203 if (!Changed)
13204 continue;
13205
13206 DIVariable *Var = Dbg->getVariable();
13207 auto *Expr = Dbg->getExpression();
13208 // If a fragment is requested, update the expression.
13209 if (SizeInBits) {
13210 // When splitting a larger (e.g., sign-extended) value whose
13211 // lower bits are described with an SDDbgValue, do not attempt
13212 // to transfer the SDDbgValue to the upper bits.
13213 if (auto FI = Expr->getFragmentInfo())
13214 if (OffsetInBits + SizeInBits > FI->SizeInBits)
13215 continue;
13216 auto Fragment = DIExpression::createFragmentExpression(Expr, OffsetInBits,
13217 SizeInBits);
13218 if (!Fragment)
13219 continue;
13220 Expr = *Fragment;
13221 }
13222
13223 auto AdditionalDependencies = Dbg->getAdditionalDependencies();
13224 // Clone the SDDbgValue and move it to To.
13225 SDDbgValue *Clone = getDbgValueList(
13226 Var, Expr, NewLocOps, AdditionalDependencies, Dbg->isIndirect(),
13227 Dbg->getDebugLoc(), std::max(ToNode->getIROrder(), Dbg->getOrder()),
13228 Dbg->isVariadic());
13229 ClonedDVs.push_back(Clone);
13230
13231 if (InvalidateDbg) {
13232 // Invalidate value and indicate the SDDbgValue should not be emitted.
13233 Dbg->setIsInvalidated();
13234 Dbg->setIsEmitted();
13235 }
13236 }
13237
13238 for (SDDbgValue *Dbg : ClonedDVs) {
13239 assert(is_contained(Dbg->getSDNodes(), ToNode) &&
13240 "Transferred DbgValues should depend on the new SDNode");
13241 AddDbgValue(Dbg, false);
13242 }
13243}
13244
13246 if (!N.getHasDebugValue())
13247 return;
13248
13249 auto GetLocationOperand = [](SDNode *Node, unsigned ResNo) {
13250 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(Node))
13251 return SDDbgOperand::fromFrameIdx(FISDN->getIndex());
13252 return SDDbgOperand::fromNode(Node, ResNo);
13253 };
13254
13256 for (auto *DV : GetDbgValues(&N)) {
13257 if (DV->isInvalidated())
13258 continue;
13259 switch (N.getOpcode()) {
13260 default:
13261 break;
13262 case ISD::ADD: {
13263 SDValue N0 = N.getOperand(0);
13264 SDValue N1 = N.getOperand(1);
13265 if (!isa<ConstantSDNode>(N0)) {
13266 bool RHSConstant = isa<ConstantSDNode>(N1);
13267 uint64_t Offset;
13268 if (RHSConstant)
13269 Offset = N.getConstantOperandVal(1);
13270 // We are not allowed to turn indirect debug values variadic, so
13271 // don't salvage those.
13272 if (!RHSConstant && DV->isIndirect())
13273 continue;
13274
13275 // Rewrite an ADD constant node into a DIExpression. Since we are
13276 // performing arithmetic to compute the variable's *value* in the
13277 // DIExpression, we need to mark the expression with a
13278 // DW_OP_stack_value.
13279 auto *DIExpr = DV->getExpression();
13280 auto NewLocOps = DV->copyLocationOps();
13281 bool Changed = false;
13282 size_t OrigLocOpsSize = NewLocOps.size();
13283 for (size_t i = 0; i < OrigLocOpsSize; ++i) {
13284 // We're not given a ResNo to compare against because the whole
13285 // node is going away. We know that any ISD::ADD only has one
13286 // result, so we can assume any node match is using the result.
13287 if (NewLocOps[i].getKind() != SDDbgOperand::SDNODE ||
13288 NewLocOps[i].getSDNode() != &N)
13289 continue;
13290 NewLocOps[i] = GetLocationOperand(N0.getNode(), N0.getResNo());
13291 if (RHSConstant) {
13294 DIExpr = DIExpression::appendOpsToArg(DIExpr, ExprOps, i, true);
13295 } else {
13296 // Convert to a variadic expression (if not already).
13297 // convertToVariadicExpression() returns a const pointer, so we use
13298 // a temporary const variable here.
13299 const auto *TmpDIExpr =
13303 ExprOps.push_back(NewLocOps.size());
13304 ExprOps.push_back(dwarf::DW_OP_plus);
13305 SDDbgOperand RHS =
13307 NewLocOps.push_back(RHS);
13308 DIExpr = DIExpression::appendOpsToArg(TmpDIExpr, ExprOps, i, true);
13309 }
13310 Changed = true;
13311 }
13312 (void)Changed;
13313 assert(Changed && "Salvage target doesn't use N");
13314
13315 bool IsVariadic =
13316 DV->isVariadic() || OrigLocOpsSize != NewLocOps.size();
13317
13318 auto AdditionalDependencies = DV->getAdditionalDependencies();
13319 SDDbgValue *Clone = getDbgValueList(
13320 DV->getVariable(), DIExpr, NewLocOps, AdditionalDependencies,
13321 DV->isIndirect(), DV->getDebugLoc(), DV->getOrder(), IsVariadic);
13322 ClonedDVs.push_back(Clone);
13323 DV->setIsInvalidated();
13324 DV->setIsEmitted();
13325 LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting";
13326 N0.getNode()->dumprFull(this);
13327 dbgs() << " into " << *DIExpr << '\n');
13328 }
13329 break;
13330 }
13331 case ISD::TRUNCATE: {
13332 SDValue N0 = N.getOperand(0);
13333 TypeSize FromSize = N0.getValueSizeInBits();
13334 TypeSize ToSize = N.getValueSizeInBits(0);
13335
13336 DIExpression *DbgExpression = DV->getExpression();
13337 auto ExtOps = DIExpression::getExtOps(FromSize, ToSize, false);
13338 auto NewLocOps = DV->copyLocationOps();
13339 bool Changed = false;
13340 for (size_t i = 0; i < NewLocOps.size(); ++i) {
13341 if (NewLocOps[i].getKind() != SDDbgOperand::SDNODE ||
13342 NewLocOps[i].getSDNode() != &N)
13343 continue;
13344
13345 NewLocOps[i] = GetLocationOperand(N0.getNode(), N0.getResNo());
13346 DbgExpression = DIExpression::appendOpsToArg(DbgExpression, ExtOps, i);
13347 Changed = true;
13348 }
13349 assert(Changed && "Salvage target doesn't use N");
13350 (void)Changed;
13351
13352 SDDbgValue *Clone =
13353 getDbgValueList(DV->getVariable(), DbgExpression, NewLocOps,
13354 DV->getAdditionalDependencies(), DV->isIndirect(),
13355 DV->getDebugLoc(), DV->getOrder(), DV->isVariadic());
13356
13357 ClonedDVs.push_back(Clone);
13358 DV->setIsInvalidated();
13359 DV->setIsEmitted();
13360 LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting"; N0.getNode()->dumprFull(this);
13361 dbgs() << " into " << *DbgExpression << '\n');
13362 break;
13363 }
13364 }
13365 }
13366
13367 for (SDDbgValue *Dbg : ClonedDVs) {
13368 assert((!Dbg->getSDNodes().empty() ||
13369 llvm::any_of(Dbg->getLocationOps(),
13370 [&](const SDDbgOperand &Op) {
13371 return Op.getKind() == SDDbgOperand::FRAMEIX;
13372 })) &&
13373 "Salvaged DbgValue should depend on a new SDNode");
13374 AddDbgValue(Dbg, false);
13375 }
13376}
13377
13378/// Creates a SDDbgLabel node.
13380 const DebugLoc &DL, unsigned O) {
13381 assert(cast<DILabel>(Label)->isValidLocationForIntrinsic(DL) &&
13382 "Expected inlined-at fields to agree");
13383 return new (DbgInfo->getAlloc()) SDDbgLabel(Label, DL, O);
13384}
13385
13386namespace {
13387
13388/// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node
13389/// pointed to by a use iterator is deleted, increment the use iterator
13390/// so that it doesn't dangle.
13391///
13392class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener {
13395
13396 void NodeDeleted(SDNode *N, SDNode *E) override {
13397 // Increment the iterator as needed.
13398 while (UI != UE && N == UI->getUser())
13399 ++UI;
13400 }
13401
13402public:
13403 RAUWUpdateListener(SelectionDAG &d,
13406 : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {}
13407};
13408
13409} // end anonymous namespace
13410
13411/// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
13412/// This can cause recursive merging of nodes in the DAG.
13413///
13414/// This version assumes From has a single result value.
13415///
13417 SDNode *From = FromN.getNode();
13418 assert(From->getNumValues() == 1 && FromN.getResNo() == 0 &&
13419 "Cannot replace with this method!");
13420 assert(From != To.getNode() && "Cannot replace uses of with self");
13421
13422 // Preserve Debug Values
13423 transferDbgValues(FromN, To);
13424 // Preserve extra info.
13425 copyExtraInfo(From, To.getNode());
13426
13427 // Iterate over all the existing uses of From. New uses will be added
13428 // to the beginning of the use list, which we avoid visiting.
13429 // This specifically avoids visiting uses of From that arise while the
13430 // replacement is happening, because any such uses would be the result
13431 // of CSE: If an existing node looks like From after one of its operands
13432 // is replaced by To, we don't want to replace of all its users with To
13433 // too. See PR3018 for more info.
13434 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
13435 RAUWUpdateListener Listener(*this, UI, UE);
13436 while (UI != UE) {
13437 SDNode *User = UI->getUser();
13438
13439 // This node is about to morph, remove its old self from the CSE maps.
13440 RemoveNodeFromCSEMaps(User);
13441
13442 // A user can appear in a use list multiple times, and when this
13443 // happens the uses are usually next to each other in the list.
13444 // To help reduce the number of CSE recomputations, process all
13445 // the uses of this user that we can find this way.
13446 do {
13447 SDUse &Use = *UI;
13448 ++UI;
13449 Use.set(To);
13450 if (To->isDivergent() != From->isDivergent())
13452 } while (UI != UE && UI->getUser() == User);
13453 // Now that we have modified User, add it back to the CSE maps. If it
13454 // already exists there, recursively merge the results together.
13455 AddModifiedNodeToCSEMaps(User);
13456 }
13457
13458 // If we just RAUW'd the root, take note.
13459 if (FromN == getRoot())
13460 setRoot(To);
13461}
13462
13463/// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
13464/// This can cause recursive merging of nodes in the DAG.
13465///
13466/// This version assumes that for each value of From, there is a
13467/// corresponding value in To in the same position with the same type.
13468///
13470#ifndef NDEBUG
13471 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
13472 assert((!From->hasAnyUseOfValue(i) ||
13473 From->getValueType(i) == To->getValueType(i)) &&
13474 "Cannot use this version of ReplaceAllUsesWith!");
13475#endif
13476
13477 // Handle the trivial case.
13478 if (From == To)
13479 return;
13480
13481 // Preserve Debug Info. Only do this if there's a use.
13482 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
13483 if (From->hasAnyUseOfValue(i)) {
13484 assert((i < To->getNumValues()) && "Invalid To location");
13485 transferDbgValues(SDValue(From, i), SDValue(To, i));
13486 }
13487 // Preserve extra info.
13488 copyExtraInfo(From, To);
13489
13490 // Iterate over just the existing users of From. See the comments in
13491 // the ReplaceAllUsesWith above.
13492 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
13493 RAUWUpdateListener Listener(*this, UI, UE);
13494 while (UI != UE) {
13495 SDNode *User = UI->getUser();
13496
13497 // This node is about to morph, remove its old self from the CSE maps.
13498 RemoveNodeFromCSEMaps(User);
13499
13500 // A user can appear in a use list multiple times, and when this
13501 // happens the uses are usually next to each other in the list.
13502 // To help reduce the number of CSE recomputations, process all
13503 // the uses of this user that we can find this way.
13504 do {
13505 SDUse &Use = *UI;
13506 ++UI;
13507 Use.setNode(To);
13508 if (To->isDivergent() != From->isDivergent())
13510 } while (UI != UE && UI->getUser() == User);
13511
13512 // Now that we have modified User, add it back to the CSE maps. If it
13513 // already exists there, recursively merge the results together.
13514 AddModifiedNodeToCSEMaps(User);
13515 }
13516
13517 // If we just RAUW'd the root, take note.
13518 if (From == getRoot().getNode())
13519 setRoot(SDValue(To, getRoot().getResNo()));
13520}
13521
13522/// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
13523/// This can cause recursive merging of nodes in the DAG.
13524///
13525/// This version can replace From with any result values. To must match the
13526/// number and types of values returned by From.
13528 if (From->getNumValues() == 1) // Handle the simple case efficiently.
13529 return ReplaceAllUsesWith(SDValue(From, 0), To[0]);
13530
13531 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) {
13532 // Preserve Debug Info.
13533 transferDbgValues(SDValue(From, i), To[i]);
13534 // Preserve extra info.
13535 copyExtraInfo(From, To[i].getNode());
13536 }
13537
13538 // Iterate over just the existing users of From. See the comments in
13539 // the ReplaceAllUsesWith above.
13540 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
13541 RAUWUpdateListener Listener(*this, UI, UE);
13542 while (UI != UE) {
13543 SDNode *User = UI->getUser();
13544
13545 // This node is about to morph, remove its old self from the CSE maps.
13546 RemoveNodeFromCSEMaps(User);
13547
13548 // A user can appear in a use list multiple times, and when this happens the
13549 // uses are usually next to each other in the list. To help reduce the
13550 // number of CSE and divergence recomputations, process all the uses of this
13551 // user that we can find this way.
13552 bool To_IsDivergent = false;
13553 do {
13554 SDUse &Use = *UI;
13555 const SDValue &ToOp = To[Use.getResNo()];
13556 ++UI;
13557 Use.set(ToOp);
13558 if (ToOp.getValueType() != MVT::Other)
13559 To_IsDivergent |= ToOp->isDivergent();
13560 } while (UI != UE && UI->getUser() == User);
13561
13562 if (To_IsDivergent != From->isDivergent())
13564
13565 // Now that we have modified User, add it back to the CSE maps. If it
13566 // already exists there, recursively merge the results together.
13567 AddModifiedNodeToCSEMaps(User);
13568 }
13569
13570 // If we just RAUW'd the root, take note.
13571 if (From == getRoot().getNode())
13572 setRoot(SDValue(To[getRoot().getResNo()]));
13573}
13574
13575/// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
13576/// uses of other values produced by From.getNode() alone. The Deleted
13577/// vector is handled the same way as for ReplaceAllUsesWith.
13579 // Handle the really simple, really trivial case efficiently.
13580 if (From == To) return;
13581
13582 // Handle the simple, trivial, case efficiently.
13583 if (From.getNode()->getNumValues() == 1) {
13584 ReplaceAllUsesWith(From, To);
13585 return;
13586 }
13587
13588 // Preserve Debug Info.
13589 transferDbgValues(From, To);
13590 copyExtraInfo(From.getNode(), To.getNode());
13591
13592 // Iterate over just the existing users of From. See the comments in
13593 // the ReplaceAllUsesWith above.
13594 SDNode::use_iterator UI = From.getNode()->use_begin(),
13595 UE = From.getNode()->use_end();
13596 RAUWUpdateListener Listener(*this, UI, UE);
13597 while (UI != UE) {
13598 SDNode *User = UI->getUser();
13599 bool UserRemovedFromCSEMaps = false;
13600
13601 // A user can appear in a use list multiple times, and when this
13602 // happens the uses are usually next to each other in the list.
13603 // To help reduce the number of CSE recomputations, process all
13604 // the uses of this user that we can find this way.
13605 do {
13606 SDUse &Use = *UI;
13607
13608 // Skip uses of different values from the same node.
13609 if (Use.getResNo() != From.getResNo()) {
13610 ++UI;
13611 continue;
13612 }
13613
13614 // If this node hasn't been modified yet, it's still in the CSE maps,
13615 // so remove its old self from the CSE maps.
13616 if (!UserRemovedFromCSEMaps) {
13617 RemoveNodeFromCSEMaps(User);
13618 UserRemovedFromCSEMaps = true;
13619 }
13620
13621 ++UI;
13622 Use.set(To);
13623 if (To->isDivergent() != From->isDivergent())
13625 } while (UI != UE && UI->getUser() == User);
13626 // We are iterating over all uses of the From node, so if a use
13627 // doesn't use the specific value, no changes are made.
13628 if (!UserRemovedFromCSEMaps)
13629 continue;
13630
13631 // Now that we have modified User, add it back to the CSE maps. If it
13632 // already exists there, recursively merge the results together.
13633 AddModifiedNodeToCSEMaps(User);
13634 }
13635
13636 // If we just RAUW'd the root, take note.
13637 if (From == getRoot())
13638 setRoot(To);
13639}
13640
13641namespace {
13642
13643/// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith
13644/// to record information about a use.
13645struct UseMemo {
13646 SDNode *User;
13647 unsigned Index;
13648 SDUse *Use;
13649};
13650
13651/// operator< - Sort Memos by User.
13652bool operator<(const UseMemo &L, const UseMemo &R) {
13653 return (intptr_t)L.User < (intptr_t)R.User;
13654}
13655
13656/// RAUOVWUpdateListener - Helper for ReplaceAllUsesOfValuesWith - When the node
13657/// pointed to by a UseMemo is deleted, set the User to nullptr to indicate that
13658/// the node already has been taken care of recursively.
13659class RAUOVWUpdateListener : public SelectionDAG::DAGUpdateListener {
13660 SmallVectorImpl<UseMemo> &Uses;
13661
13662 void NodeDeleted(SDNode *N, SDNode *E) override {
13663 for (UseMemo &Memo : Uses)
13664 if (Memo.User == N)
13665 Memo.User = nullptr;
13666 }
13667
13668public:
13669 RAUOVWUpdateListener(SelectionDAG &d, SmallVectorImpl<UseMemo> &uses)
13670 : SelectionDAG::DAGUpdateListener(d), Uses(uses) {}
13671};
13672
13673} // end anonymous namespace
13674
13675/// Return true if a glue output should propagate divergence information.
13677 switch (Node->getOpcode()) {
13678 case ISD::CopyFromReg:
13679 case ISD::CopyToReg:
13680 return false;
13681 default:
13682 return true;
13683 }
13684
13685 llvm_unreachable("covered opcode switch");
13686}
13687
13689 if (TLI->isSDNodeAlwaysUniform(N)) {
13690 assert(!TLI->isSDNodeSourceOfDivergence(N, FLI, UA) &&
13691 "Conflicting divergence information!");
13692 return false;
13693 }
13694 if (TLI->isSDNodeSourceOfDivergence(N, FLI, UA))
13695 return true;
13696 for (const auto &Op : N->ops()) {
13697 EVT VT = Op.getValueType();
13698
13699 // Skip Chain. It does not carry divergence.
13700 if (VT != MVT::Other && Op.getNode()->isDivergent() &&
13701 (VT != MVT::Glue || gluePropagatesDivergence(Op.getNode())))
13702 return true;
13703 }
13704 return false;
13705}
13706
13708 SmallVector<SDNode *, 16> Worklist(1, N);
13709 do {
13710 N = Worklist.pop_back_val();
13711 bool IsDivergent = calculateDivergence(N);
13712 if (N->SDNodeBits.IsDivergent != IsDivergent) {
13713 N->SDNodeBits.IsDivergent = IsDivergent;
13714 llvm::append_range(Worklist, N->users());
13715 }
13716 } while (!Worklist.empty());
13717}
13718
13719void SelectionDAG::CreateTopologicalOrder(std::vector<SDNode *> &Order) {
13721 Order.reserve(AllNodes.size());
13722 for (auto &N : allnodes()) {
13723 unsigned NOps = N.getNumOperands();
13724 Degree[&N] = NOps;
13725 if (0 == NOps)
13726 Order.push_back(&N);
13727 }
13728 for (size_t I = 0; I != Order.size(); ++I) {
13729 SDNode *N = Order[I];
13730 for (auto *U : N->users()) {
13731 unsigned &UnsortedOps = Degree[U];
13732 if (0 == --UnsortedOps)
13733 Order.push_back(U);
13734 }
13735 }
13736}
13737
13738#if !defined(NDEBUG) && LLVM_ENABLE_ABI_BREAKING_CHECKS
13739void SelectionDAG::VerifyDAGDivergence() {
13740 std::vector<SDNode *> TopoOrder;
13741 CreateTopologicalOrder(TopoOrder);
13742 for (auto *N : TopoOrder) {
13743 assert(calculateDivergence(N) == N->isDivergent() &&
13744 "Divergence bit inconsistency detected");
13745 }
13746}
13747#endif
13748
13749/// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving
13750/// uses of other values produced by From.getNode() alone. The same value
13751/// may appear in both the From and To list. The Deleted vector is
13752/// handled the same way as for ReplaceAllUsesWith.
13754 const SDValue *To,
13755 unsigned Num){
13756 // Handle the simple, trivial case efficiently.
13757 if (Num == 1)
13758 return ReplaceAllUsesOfValueWith(*From, *To);
13759
13760 transferDbgValues(*From, *To);
13761 copyExtraInfo(From->getNode(), To->getNode());
13762
13763 // Read up all the uses and make records of them. This helps
13764 // processing new uses that are introduced during the
13765 // replacement process.
13767 for (unsigned i = 0; i != Num; ++i) {
13768 unsigned FromResNo = From[i].getResNo();
13769 SDNode *FromNode = From[i].getNode();
13770 for (SDUse &Use : FromNode->uses()) {
13771 if (Use.getResNo() == FromResNo) {
13772 UseMemo Memo = {Use.getUser(), i, &Use};
13773 Uses.push_back(Memo);
13774 }
13775 }
13776 }
13777
13778 // Sort the uses, so that all the uses from a given User are together.
13780 RAUOVWUpdateListener Listener(*this, Uses);
13781
13782 for (unsigned UseIndex = 0, UseIndexEnd = Uses.size();
13783 UseIndex != UseIndexEnd; ) {
13784 // We know that this user uses some value of From. If it is the right
13785 // value, update it.
13786 SDNode *User = Uses[UseIndex].User;
13787 // If the node has been deleted by recursive CSE updates when updating
13788 // another node, then just skip this entry.
13789 if (User == nullptr) {
13790 ++UseIndex;
13791 continue;
13792 }
13793
13794 // This node is about to morph, remove its old self from the CSE maps.
13795 RemoveNodeFromCSEMaps(User);
13796
13797 // The Uses array is sorted, so all the uses for a given User
13798 // are next to each other in the list.
13799 // To help reduce the number of CSE recomputations, process all
13800 // the uses of this user that we can find this way.
13801 do {
13802 unsigned i = Uses[UseIndex].Index;
13803 SDUse &Use = *Uses[UseIndex].Use;
13804 ++UseIndex;
13805
13806 Use.set(To[i]);
13807 } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User);
13808
13809 // Now that we have modified User, add it back to the CSE maps. If it
13810 // already exists there, recursively merge the results together.
13811 AddModifiedNodeToCSEMaps(User);
13812 }
13813}
13814
13815/// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
13816/// based on their topological order. It returns the maximum id and a vector
13817/// of the SDNodes* in assigned order by reference.
13819 unsigned DAGSize = 0;
13820
13821 // SortedPos tracks the progress of the algorithm. Nodes before it are
13822 // sorted, nodes after it are unsorted. When the algorithm completes
13823 // it is at the end of the list.
13824 allnodes_iterator SortedPos = allnodes_begin();
13825
13826 // Visit all the nodes. Move nodes with no operands to the front of
13827 // the list immediately. Annotate nodes that do have operands with their
13828 // operand count. Before we do this, the Node Id fields of the nodes
13829 // may contain arbitrary values. After, the Node Id fields for nodes
13830 // before SortedPos will contain the topological sort index, and the
13831 // Node Id fields for nodes At SortedPos and after will contain the
13832 // count of outstanding operands.
13834 checkForCycles(&N, this);
13835 unsigned Degree = N.getNumOperands();
13836 if (Degree == 0) {
13837 // A node with no uses, add it to the result array immediately.
13838 N.setNodeId(DAGSize++);
13839 allnodes_iterator Q(&N);
13840 if (Q != SortedPos)
13841 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q));
13842 assert(SortedPos != AllNodes.end() && "Overran node list");
13843 ++SortedPos;
13844 } else {
13845 // Temporarily use the Node Id as scratch space for the degree count.
13846 N.setNodeId(Degree);
13847 }
13848 }
13849
13850 // Visit all the nodes. As we iterate, move nodes into sorted order,
13851 // such that by the time the end is reached all nodes will be sorted.
13852 for (SDNode &Node : allnodes()) {
13853 SDNode *N = &Node;
13854 checkForCycles(N, this);
13855 // N is in sorted position, so all its uses have one less operand
13856 // that needs to be sorted.
13857 for (SDNode *P : N->users()) {
13858 unsigned Degree = P->getNodeId();
13859 assert(Degree != 0 && "Invalid node degree");
13860 --Degree;
13861 if (Degree == 0) {
13862 // All of P's operands are sorted, so P may sorted now.
13863 P->setNodeId(DAGSize++);
13864 if (P->getIterator() != SortedPos)
13865 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P));
13866 assert(SortedPos != AllNodes.end() && "Overran node list");
13867 ++SortedPos;
13868 } else {
13869 // Update P's outstanding operand count.
13870 P->setNodeId(Degree);
13871 }
13872 }
13873 if (Node.getIterator() == SortedPos) {
13874#ifndef NDEBUG
13876 SDNode *S = &*++I;
13877 dbgs() << "Overran sorted position:\n";
13878 S->dumprFull(this); dbgs() << "\n";
13879 dbgs() << "Checking if this is due to cycles\n";
13880 checkForCycles(this, true);
13881#endif
13882 llvm_unreachable(nullptr);
13883 }
13884 }
13885
13886 assert(SortedPos == AllNodes.end() &&
13887 "Topological sort incomplete!");
13888 assert(AllNodes.front().getOpcode() == ISD::EntryToken &&
13889 "First node in topological sort is not the entry token!");
13890 assert(AllNodes.front().getNodeId() == 0 &&
13891 "First node in topological sort has non-zero id!");
13892 assert(AllNodes.front().getNumOperands() == 0 &&
13893 "First node in topological sort has operands!");
13894 assert(AllNodes.back().getNodeId() == (int)DAGSize-1 &&
13895 "Last node in topologic sort has unexpected id!");
13896 assert(AllNodes.back().use_empty() &&
13897 "Last node in topologic sort has users!");
13898 assert(DAGSize == allnodes_size() && "Node count mismatch!");
13899 return DAGSize;
13900}
13901
13903 SmallVectorImpl<const SDNode *> &SortedNodes) const {
13904 SortedNodes.clear();
13905 // Node -> remaining number of outstanding operands.
13906 DenseMap<const SDNode *, unsigned> RemainingOperands;
13907
13908 // Put nodes without any operands into SortedNodes first.
13909 for (const SDNode &N : allnodes()) {
13910 checkForCycles(&N, this);
13911 unsigned NumOperands = N.getNumOperands();
13912 if (NumOperands == 0)
13913 SortedNodes.push_back(&N);
13914 else
13915 // Record their total number of outstanding operands.
13916 RemainingOperands[&N] = NumOperands;
13917 }
13918
13919 // A node is pushed into SortedNodes when all of its operands (predecessors in
13920 // the graph) are also in SortedNodes.
13921 for (unsigned i = 0U; i < SortedNodes.size(); ++i) {
13922 const SDNode *N = SortedNodes[i];
13923 for (const SDNode *U : N->users()) {
13924 // HandleSDNode is never part of a DAG and therefore has no entry in
13925 // RemainingOperands.
13926 if (U->getOpcode() == ISD::HANDLENODE)
13927 continue;
13928 unsigned &NumRemOperands = RemainingOperands[U];
13929 assert(NumRemOperands && "Invalid number of remaining operands");
13930 --NumRemOperands;
13931 if (!NumRemOperands)
13932 SortedNodes.push_back(U);
13933 }
13934 }
13935
13936 assert(SortedNodes.size() == AllNodes.size() && "Node count mismatch");
13937 assert(SortedNodes.front()->getOpcode() == ISD::EntryToken &&
13938 "First node in topological sort is not the entry token");
13939 assert(SortedNodes.front()->getNumOperands() == 0 &&
13940 "First node in topological sort has operands");
13941}
13942
13943/// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the
13944/// value is produced by SD.
13945void SelectionDAG::AddDbgValue(SDDbgValue *DB, bool isParameter) {
13946 for (SDNode *SD : DB->getSDNodes()) {
13947 if (!SD)
13948 continue;
13949 assert(DbgInfo->getSDDbgValues(SD).empty() || SD->getHasDebugValue());
13950 SD->setHasDebugValue(true);
13951 }
13952 DbgInfo->add(DB, isParameter);
13953}
13954
13955void SelectionDAG::AddDbgLabel(SDDbgLabel *DB) { DbgInfo->add(DB); }
13956
13958 SDValue NewMemOpChain) {
13959 assert(isa<MemSDNode>(NewMemOpChain) && "Expected a memop node");
13960 assert(NewMemOpChain.getValueType() == MVT::Other && "Expected a token VT");
13961 // The new memory operation must have the same position as the old load in
13962 // terms of memory dependency. Create a TokenFactor for the old load and new
13963 // memory operation and update uses of the old load's output chain to use that
13964 // TokenFactor.
13965 if (OldChain == NewMemOpChain || OldChain.use_empty())
13966 return NewMemOpChain;
13967
13968 SDValue TokenFactor = getNode(ISD::TokenFactor, SDLoc(OldChain), MVT::Other,
13969 OldChain, NewMemOpChain);
13970 ReplaceAllUsesOfValueWith(OldChain, TokenFactor);
13971 UpdateNodeOperands(TokenFactor.getNode(), OldChain, NewMemOpChain);
13972 return TokenFactor;
13973}
13974
13976 SDValue NewMemOp) {
13977 assert(isa<MemSDNode>(NewMemOp.getNode()) && "Expected a memop node");
13978 SDValue OldChain = SDValue(OldLoad, 1);
13979 SDValue NewMemOpChain = NewMemOp.getValue(1);
13980 return makeEquivalentMemoryOrdering(OldChain, NewMemOpChain);
13981}
13982
13984 Function **OutFunction) {
13985 assert(isa<ExternalSymbolSDNode>(Op) && "Node should be an ExternalSymbol");
13986
13987 auto *Symbol = cast<ExternalSymbolSDNode>(Op)->getSymbol();
13988 auto *Module = MF->getFunction().getParent();
13989 auto *Function = Module->getFunction(Symbol);
13990
13991 if (OutFunction != nullptr)
13992 *OutFunction = Function;
13993
13994 if (Function != nullptr) {
13995 auto PtrTy = TLI->getPointerTy(getDataLayout(), Function->getAddressSpace());
13996 return getGlobalAddress(Function, SDLoc(Op), PtrTy);
13997 }
13998
13999 std::string ErrorStr;
14000 raw_string_ostream ErrorFormatter(ErrorStr);
14001 ErrorFormatter << "Undefined external symbol ";
14002 ErrorFormatter << '"' << Symbol << '"';
14003 report_fatal_error(Twine(ErrorStr));
14004}
14005
14006//===----------------------------------------------------------------------===//
14007// SDNode Class
14008//===----------------------------------------------------------------------===//
14009
14012 return Const != nullptr && Const->isZero();
14013}
14014
14016 return V.isUndef() || isNullConstant(V);
14017}
14018
14021 return Const != nullptr && Const->isZero() && !Const->isNegative();
14022}
14023
14026 return Const != nullptr && Const->isAllOnes();
14027}
14028
14031 return Const != nullptr && Const->isOne();
14032}
14033
14036 return Const != nullptr && Const->isMinSignedValue();
14037}
14038
14040 SDValue V, unsigned OperandNo,
14041 unsigned Depth) const {
14042 APInt DemandedElts = getDemandAllEltsMask(V);
14043 return isIdentityElement(Opcode, Flags, V, DemandedElts, OperandNo, Depth);
14044}
14045
14047 SDValue V, const APInt &DemandedElts,
14048 unsigned OperandNo, unsigned Depth) const {
14049 // NOTE: The cases should match with IR's ConstantExpr::getBinOpIdentity().
14050 // TODO: Target-specific opcodes could be added.
14051 if (V.getValueType().isInteger()) {
14052 KnownBits Known = computeKnownBits(V, DemandedElts, Depth);
14053 if (Known.isConstant()) {
14054 const APInt &Const = Known.getConstant();
14055 switch (Opcode) {
14056 case ISD::ADD:
14057 case ISD::OR:
14058 case ISD::XOR:
14059 case ISD::UMAX:
14060 return Const.isZero();
14061 case ISD::MUL:
14062 return Const.isOne();
14063 case ISD::AND:
14064 case ISD::UMIN:
14065 return Const.isAllOnes();
14066 case ISD::SMAX:
14067 return Const.isMinSignedValue();
14068 case ISD::SMIN:
14069 return Const.isMaxSignedValue();
14070 case ISD::SUB:
14071 case ISD::SHL:
14072 case ISD::SRA:
14073 case ISD::SRL:
14074 return OperandNo == 1 && Const.isZero();
14075 case ISD::UDIV:
14076 case ISD::SDIV:
14077 return OperandNo == 1 && Const.isOne();
14078 }
14079 }
14080 } else if (auto *ConstFP = isConstOrConstSplatFP(V, DemandedElts)) {
14081 switch (Opcode) {
14082 case ISD::FADD:
14083 return ConstFP->isZero() &&
14084 (Flags.hasNoSignedZeros() || ConstFP->isNegative());
14085 case ISD::FSUB:
14086 return OperandNo == 1 && ConstFP->isZero() &&
14087 (Flags.hasNoSignedZeros() || !ConstFP->isNegative());
14088 case ISD::FMUL:
14089 return ConstFP->isOne();
14090 case ISD::FDIV:
14091 return OperandNo == 1 && ConstFP->isOne();
14092 case ISD::FMINNUM:
14093 case ISD::FMAXNUM:
14094 case ISD::FMINIMUMNUM:
14095 case ISD::FMAXIMUMNUM: {
14096 // Neutral element for fminnum/fminimumnum is NaN, Inf or FLT_MAX,
14097 // depending on fast-math flags (FMF).
14098 EVT VT = V.getValueType();
14099 const fltSemantics &Semantics = VT.getFltSemantics();
14100 APFloat NeutralAF = !Flags.hasNoNaNs() ? APFloat::getQNaN(Semantics)
14101 : !Flags.hasNoInfs() ? APFloat::getInf(Semantics)
14102 : APFloat::getLargest(Semantics);
14103 if (Opcode == ISD::FMAXNUM || Opcode == ISD::FMAXIMUMNUM)
14104 NeutralAF.changeSign();
14105
14106 return ConstFP->isExactlyValue(NeutralAF);
14107 }
14108 case ISD::FMINIMUM:
14109 case ISD::FMAXIMUM: {
14110 // Neutral element for fminimum is Inf or FLT_MAX, depending on FMF.
14111 const APFloat &VAPF = ConstFP->getValueAPF();
14112 bool NeutralNegative = (Opcode == ISD::FMAXIMUM);
14113 if (Flags.hasNoInfs())
14114 return VAPF.isLargest() && VAPF.isNegative() == NeutralNegative;
14115 return VAPF.isInfinity() && VAPF.isNegative() == NeutralNegative;
14116 }
14117 }
14118 }
14119 return false;
14120}
14121
14123 while (V.getOpcode() == ISD::BITCAST)
14124 V = V.getOperand(0);
14125 return V;
14126}
14127
14129 while (V.getOpcode() == ISD::BITCAST && V.getOperand(0).hasOneUse())
14130 V = V.getOperand(0);
14131 return V;
14132}
14133
14135 while (V.getOpcode() == ISD::EXTRACT_SUBVECTOR)
14136 V = V.getOperand(0);
14137 return V;
14138}
14139
14141 while (V.getOpcode() == ISD::INSERT_VECTOR_ELT) {
14142 SDValue InVec = V.getOperand(0);
14143 SDValue EltNo = V.getOperand(2);
14144 EVT VT = InVec.getValueType();
14145 auto *IndexC = dyn_cast<ConstantSDNode>(EltNo);
14146 if (IndexC && VT.isFixedLengthVector() &&
14147 IndexC->getAPIntValue().ult(VT.getVectorNumElements()) &&
14148 !DemandedElts[IndexC->getZExtValue()]) {
14149 V = InVec;
14150 continue;
14151 }
14152 break;
14153 }
14154 return V;
14155}
14156
14158 while (V.getOpcode() == ISD::TRUNCATE)
14159 V = V.getOperand(0);
14160 return V;
14161}
14162
14163bool llvm::isBitwiseNot(SDValue V, bool AllowUndefs) {
14164 if (V.getOpcode() != ISD::XOR)
14165 return false;
14166 V = peekThroughBitcasts(V.getOperand(1));
14167 unsigned NumBits = V.getScalarValueSizeInBits();
14168 ConstantSDNode *C =
14169 isConstOrConstSplat(V, AllowUndefs, /*AllowTruncation*/ true);
14170 return C && (C->getAPIntValue().countr_one() >= NumBits);
14171}
14172
14174 bool AllowTruncation) {
14175 APInt DemandedElts = getDemandAllEltsMask(N);
14176 return isConstOrConstSplat(N, DemandedElts, AllowUndefs, AllowTruncation);
14177}
14178
14180 bool AllowUndefs,
14181 bool AllowTruncation) {
14183 return CN;
14184
14185 // SplatVectors can truncate their operands. Ignore that case here unless
14186 // AllowTruncation is set.
14187 if (N->getOpcode() == ISD::SPLAT_VECTOR) {
14188 EVT VecEltVT = N->getValueType(0).getVectorElementType();
14189 if (auto *CN = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
14190 EVT CVT = CN->getValueType(0);
14191 assert(CVT.bitsGE(VecEltVT) && "Illegal splat_vector element extension");
14192 if (AllowTruncation || CVT == VecEltVT)
14193 return CN;
14194 }
14195 }
14196
14198 BitVector UndefElements;
14199 ConstantSDNode *CN = BV->getConstantSplatNode(DemandedElts, &UndefElements);
14200
14201 // BuildVectors can truncate their operands. Ignore that case here unless
14202 // AllowTruncation is set.
14203 // TODO: Look into whether we should allow UndefElements in non-DemandedElts
14204 if (CN && (UndefElements.none() || AllowUndefs)) {
14205 EVT CVT = CN->getValueType(0);
14206 EVT NSVT = N.getValueType().getScalarType();
14207 assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension");
14208 if (AllowTruncation || (CVT == NSVT))
14209 return CN;
14210 }
14211 }
14212
14213 if (N.getOpcode() == ISD::MERGE_VALUES)
14214 return isConstOrConstSplat(N.getOperand(N.getResNo()), DemandedElts,
14215 AllowUndefs, AllowTruncation);
14216
14217 return nullptr;
14218}
14219
14221 APInt DemandedElts = getDemandAllEltsMask(N);
14222 return isConstOrConstSplatFP(N, DemandedElts, AllowUndefs);
14223}
14224
14226 const APInt &DemandedElts,
14227 bool AllowUndefs) {
14229 return CN;
14230
14232 BitVector UndefElements;
14233 ConstantFPSDNode *CN =
14234 BV->getConstantFPSplatNode(DemandedElts, &UndefElements);
14235 // TODO: Look into whether we should allow UndefElements in non-DemandedElts
14236 if (CN && (UndefElements.none() || AllowUndefs))
14237 return CN;
14238 }
14239
14240 if (N.getOpcode() == ISD::SPLAT_VECTOR)
14241 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N.getOperand(0)))
14242 return CN;
14243
14244 return nullptr;
14245}
14246
14247bool llvm::isNullOrNullSplat(SDValue N, bool AllowUndefs) {
14248 // TODO: may want to use peekThroughBitcast() here.
14249 ConstantSDNode *C =
14250 isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation=*/true);
14251 return C && C->isZero();
14252}
14253
14254bool llvm::isOneOrOneSplat(SDValue N, bool AllowUndefs) {
14255 ConstantSDNode *C =
14256 isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation*/ true);
14257 return C && C->isOne();
14258}
14259
14260bool llvm::isOneOrOneSplatFP(SDValue N, bool AllowUndefs) {
14261 ConstantFPSDNode *C = isConstOrConstSplatFP(N, AllowUndefs);
14262 return C && C->isOne();
14263}
14264
14265bool llvm::isAllOnesOrAllOnesSplat(SDValue N, bool AllowUndefs) {
14267 unsigned BitWidth = N.getScalarValueSizeInBits();
14268 ConstantSDNode *C =
14269 isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation=*/true);
14270 return C && C->getAPIntValue().countTrailingOnes() >= BitWidth;
14271}
14272
14273bool llvm::isZeroOrZeroSplat(SDValue N, bool AllowUndefs) {
14275 ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs, true);
14276 return C && C->isZero();
14277}
14278
14279bool llvm::isZeroOrZeroSplatFP(SDValue N, bool AllowUndefs) {
14280 ConstantFPSDNode *C = isConstOrConstSplatFP(N, AllowUndefs);
14281 return C && C->isZero();
14282}
14283
14287
14289 unsigned Opc, unsigned Order, const DebugLoc &dl, SDVTList VTs, EVT memvt,
14291 : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MemRefs(memrefs) {
14292 bool IsVolatile = false;
14293 bool IsNonTemporal = false;
14294 bool IsDereferenceable = true;
14295 bool IsInvariant = true;
14296 for (const MachineMemOperand *MMO : memoperands()) {
14297 IsVolatile |= MMO->isVolatile();
14298 IsNonTemporal |= MMO->isNonTemporal();
14299 IsDereferenceable &= MMO->isDereferenceable();
14300 IsInvariant &= MMO->isInvariant();
14301 }
14302 MemSDNodeBits.IsVolatile = IsVolatile;
14303 MemSDNodeBits.IsNonTemporal = IsNonTemporal;
14304 MemSDNodeBits.IsDereferenceable = IsDereferenceable;
14305 MemSDNodeBits.IsInvariant = IsInvariant;
14306
14307 // For the single-MMO case, we check here that the size of the memory operand
14308 // fits within the size of the MMO. This is because the MMO might indicate
14309 // only a possible address range instead of specifying the affected memory
14310 // addresses precisely.
14313 getMemOperand()->getSize().getValue())) &&
14314 "Size mismatch!");
14315}
14316
14317namespace {
14318
14319 struct EVTArray {
14320 std::vector<EVT> VTs;
14321
14322 EVTArray() {
14323 VTs.reserve(MVT::VALUETYPE_SIZE);
14324 for (unsigned i = 0; i < MVT::VALUETYPE_SIZE; ++i)
14325 VTs.push_back(MVT((MVT::SimpleValueType)i));
14326 }
14327 };
14328
14329} // end anonymous namespace
14330
14331/// getValueTypeList - Return a pointer to the specified value type.
14332///
14333const EVT *SDNode::getValueTypeList(MVT VT) {
14334 static EVTArray SimpleVTArray;
14335
14336 assert(VT < MVT::VALUETYPE_SIZE && "Value type out of range!");
14337 return &SimpleVTArray.VTs[VT.SimpleTy];
14338}
14339
14340/// hasAnyUseOfValue - Return true if there are any use of the indicated
14341/// value. This method ignores uses of other values defined by this operation.
14342bool SDNode::hasAnyUseOfValue(unsigned Value) const {
14343 assert(Value < getNumValues() && "Bad value!");
14344
14345 for (SDUse &U : uses())
14346 if (U.getResNo() == Value)
14347 return true;
14348
14349 return false;
14350}
14351
14352/// isOnlyUserOf - Return true if this node is the only use of N.
14353bool SDNode::isOnlyUserOf(const SDNode *N) const {
14354 bool Seen = false;
14355 for (const SDNode *User : N->users()) {
14356 if (User == this)
14357 Seen = true;
14358 else
14359 return false;
14360 }
14361
14362 return Seen;
14363}
14364
14365/// Return true if the only users of N are contained in Nodes.
14367 bool Seen = false;
14368 for (const SDNode *User : N->users()) {
14369 if (llvm::is_contained(Nodes, User))
14370 Seen = true;
14371 else
14372 return false;
14373 }
14374
14375 return Seen;
14376}
14377
14378/// Return true if the referenced return value is an operand of N.
14379bool SDValue::isOperandOf(const SDNode *N) const {
14380 return is_contained(N->op_values(), *this);
14381}
14382
14383bool SDNode::isOperandOf(const SDNode *N) const {
14384 return any_of(N->op_values(),
14385 [this](SDValue Op) { return this == Op.getNode(); });
14386}
14387
14388/// reachesChainWithoutSideEffects - Return true if this operand (which must
14389/// be a chain) reaches the specified operand without crossing any
14390/// side-effecting instructions on any chain path. In practice, this looks
14391/// through token factors and non-volatile loads. In order to remain efficient,
14392/// this only looks a couple of nodes in, it does not do an exhaustive search.
14393///
14394/// Note that we only need to examine chains when we're searching for
14395/// side-effects; SelectionDAG requires that all side-effects are represented
14396/// by chains, even if another operand would force a specific ordering. This
14397/// constraint is necessary to allow transformations like splitting loads.
14399 unsigned Depth) const {
14400 if (*this == Dest) return true;
14401
14402 // Don't search too deeply, we just want to be able to see through
14403 // TokenFactor's etc.
14404 if (Depth == 0) return false;
14405
14406 // If this is a token factor, all inputs to the TF happen in parallel.
14407 if (getOpcode() == ISD::TokenFactor) {
14408 // First, try a shallow search.
14409 if (is_contained((*this)->ops(), Dest)) {
14410 // We found the chain we want as an operand of this TokenFactor.
14411 // Essentially, we reach the chain without side-effects if we could
14412 // serialize the TokenFactor into a simple chain of operations with
14413 // Dest as the last operation. This is automatically true if the
14414 // chain has one use: there are no other ordering constraints.
14415 // If the chain has more than one use, we give up: some other
14416 // use of Dest might force a side-effect between Dest and the current
14417 // node.
14418 if (Dest.hasOneUse())
14419 return true;
14420 }
14421 // Next, try a deep search: check whether every operand of the TokenFactor
14422 // reaches Dest.
14423 return llvm::all_of((*this)->ops(), [=](SDValue Op) {
14424 return Op.reachesChainWithoutSideEffects(Dest, Depth - 1);
14425 });
14426 }
14427
14428 // Loads don't have side effects, look through them.
14429 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
14430 if (Ld->isUnordered())
14431 return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
14432 }
14433 return false;
14434}
14435
14436bool SDNode::hasPredecessor(const SDNode *N) const {
14439 Worklist.push_back(this);
14440 return hasPredecessorHelper(N, Visited, Worklist);
14441}
14442
14444 this->Flags &= Flags;
14445}
14446
14447SDValue
14449 ArrayRef<ISD::NodeType> CandidateBinOps,
14450 bool AllowPartials) {
14451 // The pattern must end in an extract from index 0.
14452 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
14453 !isNullConstant(Extract->getOperand(1)))
14454 return SDValue();
14455
14456 // Match against one of the candidate binary ops.
14457 SDValue Op = Extract->getOperand(0);
14458 if (llvm::none_of(CandidateBinOps, [Op](ISD::NodeType BinOp) {
14459 return Op.getOpcode() == unsigned(BinOp);
14460 }))
14461 return SDValue();
14462
14463 // Floating-point reductions may require relaxed constraints on the final step
14464 // of the reduction because they may reorder intermediate operations.
14465 unsigned CandidateBinOp = Op.getOpcode();
14466 if (Op.getValueType().isFloatingPoint()) {
14467 SDNodeFlags Flags = Op->getFlags();
14468 switch (CandidateBinOp) {
14469 case ISD::FADD:
14470 if (!Flags.hasNoSignedZeros() || !Flags.hasAllowReassociation())
14471 return SDValue();
14472 break;
14473 default:
14474 llvm_unreachable("Unhandled FP opcode for binop reduction");
14475 }
14476 }
14477
14478 // Matching failed - attempt to see if we did enough stages that a partial
14479 // reduction from a subvector is possible.
14480 auto PartialReduction = [&](SDValue Op, unsigned NumSubElts) {
14481 if (!AllowPartials || !Op)
14482 return SDValue();
14483 EVT OpVT = Op.getValueType();
14484 EVT OpSVT = OpVT.getScalarType();
14485 EVT SubVT = EVT::getVectorVT(*getContext(), OpSVT, NumSubElts);
14486 if (TLI->getExtractSubvectorCost(SubVT, OpVT, 0) >
14488 return SDValue();
14489 BinOp = (ISD::NodeType)CandidateBinOp;
14490 return getExtractSubvector(SDLoc(Op), SubVT, Op, 0);
14491 };
14492
14493 // At each stage, we're looking for something that looks like:
14494 // %s = shufflevector <8 x i32> %op, <8 x i32> undef,
14495 // <8 x i32> <i32 2, i32 3, i32 undef, i32 undef,
14496 // i32 undef, i32 undef, i32 undef, i32 undef>
14497 // %a = binop <8 x i32> %op, %s
14498 // Where the mask changes according to the stage. E.g. for a 3-stage pyramid,
14499 // we expect something like:
14500 // <4,5,6,7,u,u,u,u>
14501 // <2,3,u,u,u,u,u,u>
14502 // <1,u,u,u,u,u,u,u>
14503 // While a partial reduction match would be:
14504 // <2,3,u,u,u,u,u,u>
14505 // <1,u,u,u,u,u,u,u>
14506 unsigned Stages = Log2_32(Op.getValueType().getVectorNumElements());
14507 SDValue PrevOp;
14508 for (unsigned i = 0; i < Stages; ++i) {
14509 unsigned MaskEnd = (1 << i);
14510
14511 if (Op.getOpcode() != CandidateBinOp)
14512 return PartialReduction(PrevOp, MaskEnd);
14513
14514 SDValue Op0 = Op.getOperand(0);
14515 SDValue Op1 = Op.getOperand(1);
14516
14518 if (Shuffle) {
14519 Op = Op1;
14520 } else {
14521 Shuffle = dyn_cast<ShuffleVectorSDNode>(Op1);
14522 Op = Op0;
14523 }
14524
14525 // The first operand of the shuffle should be the same as the other operand
14526 // of the binop.
14527 if (!Shuffle || Shuffle->getOperand(0) != Op)
14528 return PartialReduction(PrevOp, MaskEnd);
14529
14530 // Verify the shuffle has the expected (at this stage of the pyramid) mask.
14531 for (int Index = 0; Index < (int)MaskEnd; ++Index)
14532 if (Shuffle->getMaskElt(Index) != (int)(MaskEnd + Index))
14533 return PartialReduction(PrevOp, MaskEnd);
14534
14535 PrevOp = Op;
14536 }
14537
14538 // Handle subvector reductions, which tend to appear after the shuffle
14539 // reduction stages.
14540 while (Op.getOpcode() == CandidateBinOp) {
14541 unsigned NumElts = Op.getValueType().getVectorNumElements();
14542 SDValue Op0 = Op.getOperand(0);
14543 SDValue Op1 = Op.getOperand(1);
14544 if (Op0.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
14546 Op0.getOperand(0) != Op1.getOperand(0))
14547 break;
14548 SDValue Src = Op0.getOperand(0);
14549 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
14550 if (NumSrcElts != (2 * NumElts))
14551 break;
14552 if (!(Op0.getConstantOperandAPInt(1) == 0 &&
14553 Op1.getConstantOperandAPInt(1) == NumElts) &&
14554 !(Op1.getConstantOperandAPInt(1) == 0 &&
14555 Op0.getConstantOperandAPInt(1) == NumElts))
14556 break;
14557 Op = Src;
14558 }
14559
14560 BinOp = (ISD::NodeType)CandidateBinOp;
14561 return Op;
14562}
14563
14565 EVT VT = N->getValueType(0);
14566 EVT EltVT = VT.getVectorElementType();
14567 unsigned NE = getMaxRuntimeNumElements(VT);
14568
14569 if (VT.isScalableVector() && (NE == 0 || ResNE != 0))
14570 reportFatalUsageError("Cannot unroll scalable vector!");
14571
14572 assert(NE && "Nothing to unroll!");
14573 SDLoc dl(N);
14574
14575 // If ResNE is 0, fully unroll the vector op.
14576 if (ResNE == 0)
14577 ResNE = NE;
14578 else if (NE > ResNE)
14579 NE = ResNE;
14580
14581 if (N->getNumValues() == 2) {
14582 SmallVector<SDValue, 8> Scalars0, Scalars1;
14583 SmallVector<SDValue, 4> Operands(N->getNumOperands());
14584 EVT VT1 = N->getValueType(1);
14585 EVT EltVT1 = VT1.getVectorElementType();
14586
14587 unsigned i;
14588 for (i = 0; i != NE; ++i) {
14589 for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) {
14590 SDValue Operand = N->getOperand(j);
14591 EVT OperandVT = Operand.getValueType();
14592
14593 // A vector operand; extract a single element.
14594 EVT OperandEltVT = OperandVT.getVectorElementType();
14595 Operands[j] = getExtractVectorElt(dl, OperandEltVT, Operand, i);
14596 }
14597
14598 SDValue EltOp = getNode(N->getOpcode(), dl, {EltVT, EltVT1}, Operands);
14599 Scalars0.push_back(EltOp);
14600 Scalars1.push_back(EltOp.getValue(1));
14601 }
14602
14603 for (; i < ResNE; ++i) {
14604 Scalars0.push_back(getUNDEF(EltVT));
14605 Scalars1.push_back(getUNDEF(EltVT1));
14606 }
14607
14609 : ElementCount::getFixed(ResNE);
14610 EVT VecVT = EVT::getVectorVT(*getContext(), EltVT, ResEC);
14611 EVT VecVT1 = EVT::getVectorVT(*getContext(), EltVT1, ResEC);
14612 SDValue Vec0 = buildVectorFromUnrolledParts(VecVT, dl, Scalars0);
14613 SDValue Vec1 = buildVectorFromUnrolledParts(VecVT1, dl, Scalars1);
14614 return getMergeValues({Vec0, Vec1}, dl);
14615 }
14616
14617 assert(N->getNumValues() == 1 &&
14618 "Can't unroll a vector with multiple results!");
14619
14621 SmallVector<SDValue, 4> Operands(N->getNumOperands());
14622
14623 unsigned i;
14624 for (i= 0; i != NE; ++i) {
14625 for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) {
14626 SDValue Operand = N->getOperand(j);
14627 EVT OperandVT = Operand.getValueType();
14628 if (OperandVT.isVector()) {
14629 // A vector operand; extract a single element.
14630 EVT OperandEltVT = OperandVT.getVectorElementType();
14631 Operands[j] = getExtractVectorElt(dl, OperandEltVT, Operand, i);
14632 } else {
14633 // A scalar operand; just use it as is.
14634 Operands[j] = Operand;
14635 }
14636 }
14637
14638 switch (N->getOpcode()) {
14639 default: {
14640 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands,
14641 N->getFlags()));
14642 break;
14643 }
14644 case ISD::VSELECT: {
14645 SDValue Cond = Operands[0];
14646 EVT CondVT = Cond.getValueType();
14648 if (CondVT != MVT::i1 &&
14649 TLI.getBooleanContents(N->getOperand(1).getValueType()) !=
14650 TLI.getBooleanContents(CondVT)) {
14651 EVT SetCCVT =
14652 TLI.getSetCCResultType(getDataLayout(), *getContext(), CondVT);
14653 Operands[0] =
14654 getSetCC(dl, SetCCVT, Cond, getConstant(0, dl, CondVT), ISD::SETNE);
14655 }
14656 Scalars.push_back(
14657 getNode(ISD::SELECT, dl, EltVT, Operands, N->getFlags()));
14658 break;
14659 }
14660 case ISD::SHL:
14661 case ISD::SRA:
14662 case ISD::SRL:
14663 case ISD::ROTL:
14664 case ISD::ROTR:
14665 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0],
14667 Operands[1])));
14668 break;
14670 EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType();
14671 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT,
14672 Operands[0],
14673 getValueType(ExtVT)));
14674 break;
14675 }
14676 case ISD::ADDRSPACECAST: {
14677 const auto *ASC = cast<AddrSpaceCastSDNode>(N);
14678 Scalars.push_back(
14679 getAddrSpaceCast(dl, EltVT, Operands[0], ASC->getSrcAddressSpace(),
14680 ASC->getDestAddressSpace(), ASC->getFlags()));
14681 break;
14682 }
14683 }
14684 }
14685
14686 for (; i < ResNE; ++i)
14687 Scalars.push_back(getUNDEF(EltVT));
14688
14689 EVT VecVT = VT.isScalableVector()
14690 ? VT
14691 : EVT::getVectorVT(*getContext(), EltVT, ResNE);
14692 return buildVectorFromUnrolledParts(VecVT, dl, Scalars);
14693}
14694
14695std::pair<SDValue, SDValue> SelectionDAG::UnrollVectorOverflowOp(
14696 SDNode *N, unsigned ResNE) {
14697 unsigned Opcode = N->getOpcode();
14698 assert((Opcode == ISD::UADDO || Opcode == ISD::SADDO ||
14699 Opcode == ISD::USUBO || Opcode == ISD::SSUBO ||
14700 Opcode == ISD::UMULO || Opcode == ISD::SMULO) &&
14701 "Expected an overflow opcode");
14702
14703 EVT ResVT = N->getValueType(0);
14704 EVT OvVT = N->getValueType(1);
14705 EVT ResEltVT = ResVT.getVectorElementType();
14706 EVT OvEltVT = OvVT.getVectorElementType();
14707 SDLoc dl(N);
14708
14709 // If ResNE is 0, fully unroll the vector op.
14710 unsigned NE = ResVT.getVectorNumElements();
14711 if (ResNE == 0)
14712 ResNE = NE;
14713 else if (NE > ResNE)
14714 NE = ResNE;
14715
14716 SmallVector<SDValue, 8> LHSScalars;
14717 SmallVector<SDValue, 8> RHSScalars;
14718 ExtractVectorElements(N->getOperand(0), LHSScalars, 0, NE);
14719 ExtractVectorElements(N->getOperand(1), RHSScalars, 0, NE);
14720
14721 EVT SVT = TLI->getSetCCResultType(getDataLayout(), *getContext(), ResEltVT);
14722 SDVTList VTs = getVTList(ResEltVT, SVT);
14723 SmallVector<SDValue, 8> ResScalars;
14724 SmallVector<SDValue, 8> OvScalars;
14725 for (unsigned i = 0; i < NE; ++i) {
14726 SDValue Res = getNode(Opcode, dl, VTs, LHSScalars[i], RHSScalars[i]);
14727 SDValue Ov =
14728 getSelect(dl, OvEltVT, Res.getValue(1),
14729 getBoolConstant(true, dl, OvEltVT, ResVT),
14730 getConstant(0, dl, OvEltVT));
14731
14732 ResScalars.push_back(Res);
14733 OvScalars.push_back(Ov);
14734 }
14735
14736 ResScalars.append(ResNE - NE, getUNDEF(ResEltVT));
14737 OvScalars.append(ResNE - NE, getUNDEF(OvEltVT));
14738
14739 EVT NewResVT = EVT::getVectorVT(*getContext(), ResEltVT, ResNE);
14740 EVT NewOvVT = EVT::getVectorVT(*getContext(), OvEltVT, ResNE);
14741 return std::make_pair(getBuildVector(NewResVT, dl, ResScalars),
14742 getBuildVector(NewOvVT, dl, OvScalars));
14743}
14744
14747 TypeSize Bytes, int Dist,
14748 const SelectionDAG &DAG) {
14749 if (LS->isVolatile() || Base->isVolatile())
14750 return false;
14751 // TODO: probably too restrictive for atomics, revisit
14752 if (!LS->isSimple())
14753 return false;
14754 if (LS->isIndexed() || Base->isIndexed())
14755 return false;
14756 if (LS->getChain() != Base->getChain())
14757 return false;
14758 EVT VT = LS->getMemoryVT();
14759 if (!VT.getScalarType().isByteSized())
14760 return false;
14761 if (VT.getStoreSize() != Bytes)
14762 return false;
14763
14764 auto BaseLocDecomp = BaseIndexOffset::match(Base, DAG);
14765 auto LocDecomp = BaseIndexOffset::match(LS, DAG);
14767 if (!BaseLocDecomp.equalBaseIndex(LocDecomp, DAG, Offset))
14768 return false;
14769
14770 int64_t ExpectedOffset = Dist * (int64_t)Bytes.getKnownMinValue();
14771 if (Bytes.isFixed())
14772 return Offset == StackOffset::getFixed(ExpectedOffset);
14773 return Offset == StackOffset::getScalable(ExpectedOffset);
14774}
14775
14778 TypeSize Bytes,
14779 int Dist) const {
14780 return areNonVolatileConsecutiveLoadsOrStores(LD, Base, Bytes, Dist, *this);
14781}
14782
14785 TypeSize Bytes,
14786 int Dist) const {
14787 return areNonVolatileConsecutiveLoadsOrStores(ST, Base, Bytes, Dist, *this);
14788}
14789
14790/// InferPtrAlignment - Infer alignment of a load / store address. Return
14791/// std::nullopt if it cannot be inferred.
14793 // If this is a GlobalAddress + cst, return the alignment.
14794 const GlobalValue *GV = nullptr;
14795 int64_t GVOffset = 0;
14796 if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) {
14797 unsigned PtrWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
14798 KnownBits Known(PtrWidth);
14800 unsigned AlignBits = Known.countMinTrailingZeros();
14801 if (AlignBits)
14802 return commonAlignment(Align::fromLog2(std::min(31U, AlignBits)),
14803 GVOffset);
14804 }
14805
14806 // If this is a direct reference to a stack slot, use information about the
14807 // stack slot's alignment.
14808 int FrameIdx = INT_MIN;
14809 int64_t FrameOffset = 0;
14811 FrameIdx = FI->getIndex();
14812 } else if (isBaseWithConstantOffset(Ptr) &&
14814 // Handle FI+Cst
14815 FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
14816 FrameOffset = Ptr.getConstantOperandVal(1);
14817 }
14818
14819 if (FrameIdx != INT_MIN) {
14821 return commonAlignment(MFI.getObjectAlign(FrameIdx), FrameOffset);
14822 }
14823
14824 return std::nullopt;
14825}
14826
14827/// Split the scalar node with EXTRACT_ELEMENT using the provided
14828/// VTs and return the low/high part.
14829std::pair<SDValue, SDValue> SelectionDAG::SplitScalar(const SDValue &N,
14830 const SDLoc &DL,
14831 const EVT &LoVT,
14832 const EVT &HiVT) {
14833 assert(!LoVT.isVector() && !HiVT.isVector() && !N.getValueType().isVector() &&
14834 "Split node must be a scalar type");
14835 SDValue Lo =
14837 SDValue Hi =
14839 return std::make_pair(Lo, Hi);
14840}
14841
14842/// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type
14843/// which is split (or expanded) into two not necessarily identical pieces.
14844std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const {
14845 // Currently all types are split in half.
14846 EVT LoVT, HiVT;
14847 if (!VT.isVector())
14848 LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT);
14849 else
14850 LoVT = HiVT = VT.getHalfNumVectorElementsVT(*getContext());
14851
14852 return std::make_pair(LoVT, HiVT);
14853}
14854
14855/// GetDependentSplitDestVTs - Compute the VTs needed for the low/hi parts of a
14856/// type, dependent on an enveloping VT that has been split into two identical
14857/// pieces. Sets the HiIsEmpty flag when hi type has zero storage size.
14858std::pair<EVT, EVT>
14860 bool *HiIsEmpty) const {
14861 EVT EltTp = VT.getVectorElementType();
14862 // Examples:
14863 // custom VL=8 with enveloping VL=8/8 yields 8/0 (hi empty)
14864 // custom VL=9 with enveloping VL=8/8 yields 8/1
14865 // custom VL=10 with enveloping VL=8/8 yields 8/2
14866 // etc.
14867 ElementCount VTNumElts = VT.getVectorElementCount();
14868 ElementCount EnvNumElts = EnvVT.getVectorElementCount();
14869 assert(VTNumElts.isScalable() == EnvNumElts.isScalable() &&
14870 "Mixing fixed width and scalable vectors when enveloping a type");
14871 EVT LoVT, HiVT;
14872 if (VTNumElts.getKnownMinValue() > EnvNumElts.getKnownMinValue()) {
14873 LoVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts);
14874 HiVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts - EnvNumElts);
14875 *HiIsEmpty = false;
14876 } else {
14877 // Flag that hi type has zero storage size, but return split envelop type
14878 // (this would be easier if vector types with zero elements were allowed).
14879 LoVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts);
14880 HiVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts);
14881 *HiIsEmpty = true;
14882 }
14883 return std::make_pair(LoVT, HiVT);
14884}
14885
14886/// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the
14887/// low/high part.
14888std::pair<SDValue, SDValue>
14889SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT,
14890 const EVT &HiVT) {
14891 assert(LoVT.isScalableVector() == HiVT.isScalableVector() &&
14892 LoVT.isScalableVector() == N.getValueType().isScalableVector() &&
14893 "Splitting vector with an invalid mixture of fixed and scalable "
14894 "vector types");
14896 N.getValueType().getVectorMinNumElements() &&
14897 "More vector elements requested than available!");
14898 SDValue Lo, Hi;
14899 Lo = getExtractSubvector(DL, LoVT, N, 0);
14900 // For scalable vectors it is safe to use LoVT.getVectorMinNumElements()
14901 // (rather than having to use ElementCount), because EXTRACT_SUBVECTOR scales
14902 // IDX with the runtime scaling factor of the result vector type. For
14903 // fixed-width result vectors, that runtime scaling factor is 1.
14905 return std::make_pair(Lo, Hi);
14906}
14907
14908std::pair<SDValue, SDValue> SelectionDAG::SplitEVL(SDValue N, EVT VecVT,
14909 const SDLoc &DL) {
14910 // Split the vector length parameter.
14911 // %evl -> umin(%evl, %halfnumelts) and usubsat(%evl - %halfnumelts).
14912 EVT VT = N.getValueType();
14914 "Expecting the mask to be an evenly-sized vector");
14915 SDValue HalfNumElts = getElementCount(
14917 SDValue Lo = getNode(ISD::UMIN, DL, VT, N, HalfNumElts);
14918 SDValue Hi = getNode(ISD::USUBSAT, DL, VT, N, HalfNumElts);
14919 return std::make_pair(Lo, Hi);
14920}
14921
14922/// Widen the vector up to the next power of two using INSERT_SUBVECTOR.
14924 EVT VT = N.getValueType();
14925 EVT WideVT = VT.changeElementCount(
14926 *getContext(),
14928 return getInsertSubvector(DL, getPOISON(WideVT), N, 0);
14929}
14930
14933 unsigned Start, unsigned Count,
14934 EVT EltVT) {
14935 EVT VT = Op.getValueType();
14936 if (Count == 0)
14938 if (EltVT == EVT())
14939 EltVT = VT.getVectorElementType();
14940 SDLoc SL(Op);
14941 for (unsigned i = Start, e = Start + Count; i != e; ++i) {
14942 Args.push_back(getExtractVectorElt(SL, EltVT, Op, i));
14943 }
14944}
14945
14946// getAddressSpace - Return the address space this GlobalAddress belongs to.
14948 return getGlobal()->getType()->getAddressSpace();
14949}
14950
14953 return Val.MachineCPVal->getType();
14954 return Val.ConstVal->getType();
14955}
14956
14957bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue, APInt &SplatUndef,
14958 unsigned &SplatBitSize,
14959 bool &HasAnyUndefs,
14960 unsigned MinSplatBits,
14961 bool IsBigEndian) const {
14962 EVT VT = getValueType(0);
14963 assert(VT.isVector() && "Expected a vector type");
14964 unsigned VecWidth = VT.getSizeInBits();
14965 if (MinSplatBits > VecWidth)
14966 return false;
14967
14968 // FIXME: The widths are based on this node's type, but build vectors can
14969 // truncate their operands.
14970 SplatValue = APInt(VecWidth, 0);
14971 SplatUndef = APInt(VecWidth, 0);
14972
14973 // Get the bits. Bits with undefined values (when the corresponding element
14974 // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared
14975 // in SplatValue. If any of the values are not constant, give up and return
14976 // false.
14977 unsigned int NumOps = getNumOperands();
14978 assert(NumOps > 0 && "isConstantSplat has 0-size build vector");
14979 unsigned EltWidth = VT.getScalarSizeInBits();
14980
14981 for (unsigned j = 0; j < NumOps; ++j) {
14982 unsigned i = IsBigEndian ? NumOps - 1 - j : j;
14983 SDValue OpVal = getOperand(i);
14984 unsigned BitPos = j * EltWidth;
14985
14986 if (OpVal.isUndef())
14987 SplatUndef.setBits(BitPos, BitPos + EltWidth);
14988 else if (auto *CN = dyn_cast<ConstantSDNode>(OpVal))
14989 SplatValue.insertBits(CN->getAPIntValue().zextOrTrunc(EltWidth), BitPos);
14990 else if (auto *CN = dyn_cast<ConstantFPSDNode>(OpVal))
14991 SplatValue.insertBits(CN->getValueAPF().bitcastToAPInt(), BitPos);
14992 else
14993 return false;
14994 }
14995
14996 // The build_vector is all constants or undefs. Find the smallest element
14997 // size that splats the vector.
14998 HasAnyUndefs = (SplatUndef != 0);
14999
15000 // FIXME: This does not work for vectors with elements less than 8 bits.
15001 while (VecWidth > 8) {
15002 // If we can't split in half, stop here.
15003 if (VecWidth & 1)
15004 break;
15005
15006 unsigned HalfSize = VecWidth / 2;
15007 APInt HighValue = SplatValue.extractBits(HalfSize, HalfSize);
15008 APInt LowValue = SplatValue.extractBits(HalfSize, 0);
15009 APInt HighUndef = SplatUndef.extractBits(HalfSize, HalfSize);
15010 APInt LowUndef = SplatUndef.extractBits(HalfSize, 0);
15011
15012 // If the two halves do not match (ignoring undef bits), stop here.
15013 if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) ||
15014 MinSplatBits > HalfSize)
15015 break;
15016
15017 SplatValue = HighValue | LowValue;
15018 SplatUndef = HighUndef & LowUndef;
15019
15020 VecWidth = HalfSize;
15021 }
15022
15023 // FIXME: The loop above only tries to split in halves. But if the input
15024 // vector for example is <3 x i16> it wouldn't be able to detect a
15025 // SplatBitSize of 16. No idea if that is a design flaw currently limiting
15026 // optimizations. I guess that back in the days when this helper was created
15027 // vectors normally was power-of-2 sized.
15028
15029 SplatBitSize = VecWidth;
15030 return true;
15031}
15032
15034 BitVector *UndefElements) const {
15035 unsigned NumOps = getNumOperands();
15036 if (UndefElements) {
15037 UndefElements->clear();
15038 UndefElements->resize(NumOps);
15039 }
15040 assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size");
15041 if (!DemandedElts)
15042 return SDValue();
15043 SDValue Splatted;
15044 for (unsigned i = 0; i != NumOps; ++i) {
15045 if (!DemandedElts[i])
15046 continue;
15047 SDValue Op = getOperand(i);
15048 if (Op.isUndef()) {
15049 if (UndefElements)
15050 (*UndefElements)[i] = true;
15051 } else if (!Splatted) {
15052 Splatted = Op;
15053 } else if (Splatted != Op) {
15054 return SDValue();
15055 }
15056 }
15057
15058 if (!Splatted) {
15059 unsigned FirstDemandedIdx = DemandedElts.countr_zero();
15060 assert(getOperand(FirstDemandedIdx).isUndef() &&
15061 "Can only have a splat without a constant for all undefs.");
15062 return getOperand(FirstDemandedIdx);
15063 }
15064
15065 return Splatted;
15066}
15067
15069 APInt DemandedElts = APInt::getAllOnes(getNumOperands());
15070 return getSplatValue(DemandedElts, UndefElements);
15071}
15072
15074 SmallVectorImpl<SDValue> &Sequence,
15075 BitVector *UndefElements) const {
15076 unsigned NumOps = getNumOperands();
15077 Sequence.clear();
15078 if (UndefElements) {
15079 UndefElements->clear();
15080 UndefElements->resize(NumOps);
15081 }
15082 assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size");
15083 if (!DemandedElts || NumOps < 2 || !isPowerOf2_32(NumOps))
15084 return false;
15085
15086 // Set the undefs even if we don't find a sequence (like getSplatValue).
15087 if (UndefElements)
15088 for (unsigned I = 0; I != NumOps; ++I)
15089 if (DemandedElts[I] && getOperand(I).isUndef())
15090 (*UndefElements)[I] = true;
15091
15092 // Iteratively widen the sequence length looking for repetitions.
15093 for (unsigned SeqLen = 1; SeqLen < NumOps; SeqLen *= 2) {
15094 Sequence.append(SeqLen, SDValue());
15095 for (unsigned I = 0; I != NumOps; ++I) {
15096 if (!DemandedElts[I])
15097 continue;
15098 SDValue &SeqOp = Sequence[I % SeqLen];
15100 if (Op.isUndef()) {
15101 if (!SeqOp)
15102 SeqOp = Op;
15103 continue;
15104 }
15105 if (SeqOp && !SeqOp.isUndef() && SeqOp != Op) {
15106 Sequence.clear();
15107 break;
15108 }
15109 SeqOp = Op;
15110 }
15111 if (!Sequence.empty())
15112 return true;
15113 }
15114
15115 assert(Sequence.empty() && "Failed to empty non-repeating sequence pattern");
15116 return false;
15117}
15118
15120 BitVector *UndefElements) const {
15121 APInt DemandedElts = APInt::getAllOnes(getNumOperands());
15122 return getRepeatedSequence(DemandedElts, Sequence, UndefElements);
15123}
15124
15127 BitVector *UndefElements) const {
15129 getSplatValue(DemandedElts, UndefElements));
15130}
15131
15134 return dyn_cast_or_null<ConstantSDNode>(getSplatValue(UndefElements));
15135}
15136
15139 BitVector *UndefElements) const {
15141 getSplatValue(DemandedElts, UndefElements));
15142}
15143
15148
15149int32_t
15151 uint32_t BitWidth) const {
15152 if (ConstantFPSDNode *CN =
15154 bool IsExact;
15155 APSInt IntVal(BitWidth);
15156 const APFloat &APF = CN->getValueAPF();
15157 if (APF.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) !=
15158 APFloat::opOK ||
15159 !IsExact)
15160 return -1;
15161
15162 return IntVal.exactLogBase2();
15163 }
15164 return -1;
15165}
15166
15168 bool IsLittleEndian, unsigned DstEltSizeInBits,
15169 SmallVectorImpl<APInt> &RawBitElements, BitVector &UndefElements) const {
15170 // Early-out if this contains anything but Undef/Constant/ConstantFP.
15171 if (!isConstant())
15172 return false;
15173
15174 unsigned NumSrcOps = getNumOperands();
15175 unsigned SrcEltSizeInBits = getValueType(0).getScalarSizeInBits();
15176 assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 &&
15177 "Invalid bitcast scale");
15178
15179 // If the elements don't pack cleanly, don't attempt to recast.
15180 // TODO: Add handling (e.g. bitcast <33 x i8> --> <8 x i33>)
15181 if ((SrcEltSizeInBits % DstEltSizeInBits) != 0 &&
15182 (DstEltSizeInBits % SrcEltSizeInBits) != 0)
15183 return false;
15184
15185 // Extract raw src bits.
15186 SmallVector<APInt> SrcBitElements(NumSrcOps,
15187 APInt::getZero(SrcEltSizeInBits));
15188 BitVector SrcUndeElements(NumSrcOps, false);
15189
15190 for (unsigned I = 0; I != NumSrcOps; ++I) {
15192 if (Op.isUndef()) {
15193 SrcUndeElements.set(I);
15194 continue;
15195 }
15196 auto *CInt = dyn_cast<ConstantSDNode>(Op);
15197 auto *CFP = dyn_cast<ConstantFPSDNode>(Op);
15198 assert((CInt || CFP) && "Unknown constant");
15199 SrcBitElements[I] = CInt ? CInt->getAPIntValue().trunc(SrcEltSizeInBits)
15200 : CFP->getValueAPF().bitcastToAPInt();
15201 }
15202
15203 // Recast to dst width.
15204 recastRawBits(IsLittleEndian, DstEltSizeInBits, RawBitElements,
15205 SrcBitElements, UndefElements, SrcUndeElements);
15206 return true;
15207}
15208
15209void BuildVectorSDNode::recastRawBits(bool IsLittleEndian,
15210 unsigned DstEltSizeInBits,
15211 SmallVectorImpl<APInt> &DstBitElements,
15212 ArrayRef<APInt> SrcBitElements,
15213 BitVector &DstUndefElements,
15214 const BitVector &SrcUndefElements) {
15215 unsigned NumSrcOps = SrcBitElements.size();
15216 unsigned SrcEltSizeInBits = SrcBitElements[0].getBitWidth();
15217 assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 &&
15218 "Invalid bitcast scale");
15219 assert(((SrcEltSizeInBits % DstEltSizeInBits) == 0 ||
15220 (DstEltSizeInBits % SrcEltSizeInBits) == 0) &&
15221 "Unsupported bitcast scale");
15222 assert(NumSrcOps == SrcUndefElements.size() && "Vector size mismatch");
15223
15224 unsigned NumDstOps = (NumSrcOps * SrcEltSizeInBits) / DstEltSizeInBits;
15225 DstUndefElements.clear();
15226 DstUndefElements.resize(NumDstOps, false);
15227 DstBitElements.assign(NumDstOps, APInt::getZero(DstEltSizeInBits));
15228
15229 // Concatenate src elements constant bits together into dst element.
15230 if (SrcEltSizeInBits <= DstEltSizeInBits) {
15231 unsigned Scale = DstEltSizeInBits / SrcEltSizeInBits;
15232 for (unsigned I = 0; I != NumDstOps; ++I) {
15233 DstUndefElements.set(I);
15234 APInt &DstBits = DstBitElements[I];
15235 for (unsigned J = 0; J != Scale; ++J) {
15236 unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1));
15237 if (SrcUndefElements[Idx])
15238 continue;
15239 DstUndefElements.reset(I);
15240 const APInt &SrcBits = SrcBitElements[Idx];
15241 assert(SrcBits.getBitWidth() == SrcEltSizeInBits &&
15242 "Illegal constant bitwidths");
15243 DstBits.insertBits(SrcBits, J * SrcEltSizeInBits);
15244 }
15245 }
15246 return;
15247 }
15248
15249 // Split src element constant bits into dst elements.
15250 unsigned Scale = SrcEltSizeInBits / DstEltSizeInBits;
15251 for (unsigned I = 0; I != NumSrcOps; ++I) {
15252 if (SrcUndefElements[I]) {
15253 DstUndefElements.set(I * Scale, (I + 1) * Scale);
15254 continue;
15255 }
15256 const APInt &SrcBits = SrcBitElements[I];
15257 for (unsigned J = 0; J != Scale; ++J) {
15258 unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1));
15259 APInt &DstBits = DstBitElements[Idx];
15260 DstBits = SrcBits.extractBits(DstEltSizeInBits, J * DstEltSizeInBits);
15261 }
15262 }
15263}
15264
15266 for (const SDValue &Op : op_values()) {
15267 unsigned Opc = Op.getOpcode();
15268 if (!Op.isUndef() && Opc != ISD::Constant && Opc != ISD::ConstantFP)
15269 return false;
15270 }
15271 return true;
15272}
15273
15274std::optional<std::pair<APInt, APInt>>
15276 unsigned NumOps = getNumOperands();
15277 if (NumOps < 2)
15278 return std::nullopt;
15279
15280 unsigned EltSize = getValueType(0).getScalarSizeInBits();
15281 APInt Start, Stride;
15282 int FirstIdx = -1, SecondIdx = -1;
15283
15284 // Find the first two non-undef constant elements to determine Start and
15285 // Stride, then verify all remaining elements match the sequence.
15286 for (unsigned I = 0; I < NumOps; ++I) {
15288 if (Op->isUndef())
15289 continue;
15290 if (!isa<ConstantSDNode>(Op))
15291 return std::nullopt;
15292
15293 APInt Val = getConstantOperandAPInt(I).trunc(EltSize);
15294 if (FirstIdx < 0) {
15295 FirstIdx = I;
15296 Start = Val;
15297 } else if (SecondIdx < 0) {
15298 SecondIdx = I;
15299 // Compute stride using modular arithmetic. Simple division would handle
15300 // common strides (1, 2, -1, etc.), but modular inverse maximizes matches.
15301 // Example: <0, poison, poison, 0xFF> has stride 0x55 since 3*0x55 = 0xFF
15302 // Note that modular arithmetic is agnostic to signed/unsigned.
15303 unsigned IdxDiff = I - FirstIdx;
15304 APInt ValDiff = Val - Start;
15305
15306 // Step 1: Factor out common powers of 2 from IdxDiff and ValDiff.
15307 unsigned CommonPow2Bits = llvm::countr_zero(IdxDiff);
15308 if (ValDiff.countr_zero() < CommonPow2Bits)
15309 return std::nullopt; // ValDiff not divisible by 2^CommonPow2Bits
15310 IdxDiff >>= CommonPow2Bits;
15311 ValDiff.lshrInPlace(CommonPow2Bits);
15312
15313 // Step 2: IdxDiff is now odd, so its inverse mod 2^EltSize exists.
15314 // TODO: There are 2^CommonPow2Bits valid strides; currently we only try
15315 // one, but we could try all candidates to handle more cases.
15316 Stride = ValDiff * APInt(EltSize, IdxDiff).multiplicativeInverse();
15317 if (Stride.isZero())
15318 return std::nullopt;
15319
15320 // Step 3: Adjust Start based on the first defined element's index.
15321 Start -= Stride * FirstIdx;
15322 } else {
15323 // Verify this element matches the sequence.
15324 if (Val != Start + Stride * I)
15325 return std::nullopt;
15326 }
15327 }
15328
15329 // Need at least two defined elements.
15330 if (SecondIdx < 0)
15331 return std::nullopt;
15332
15333 return std::make_pair(Start, Stride);
15334}
15335
15337 // Find the first non-undef value in the shuffle mask.
15338 unsigned i, e;
15339 for (i = 0, e = Mask.size(); i != e && Mask[i] < 0; ++i)
15340 /* search */;
15341
15342 // If all elements are undefined, this shuffle can be considered a splat
15343 // (although it should eventually get simplified away completely).
15344 if (i == e)
15345 return true;
15346
15347 // Make sure all remaining elements are either undef or the same as the first
15348 // non-undef value.
15349 for (int Idx = Mask[i]; i != e; ++i)
15350 if (Mask[i] >= 0 && Mask[i] != Idx)
15351 return false;
15352 return true;
15353}
15354
15355// Returns true if it is a constant integer BuildVector or constant integer,
15356// possibly hidden by a bitcast.
15358 SDValue N, bool AllowOpaques) const {
15360
15361 if (auto *C = dyn_cast<ConstantSDNode>(N))
15362 return AllowOpaques || !C->isOpaque();
15363
15365 return true;
15366
15367 // Treat a GlobalAddress supporting constant offset folding as a
15368 // constant integer.
15369 if (auto *GA = dyn_cast<GlobalAddressSDNode>(N))
15370 if (GA->getOpcode() == ISD::GlobalAddress &&
15371 TLI->isOffsetFoldingLegal(GA))
15372 return true;
15373
15374 if ((N.getOpcode() == ISD::SPLAT_VECTOR) &&
15375 isa<ConstantSDNode>(N.getOperand(0)))
15376 return true;
15377 return false;
15378}
15379
15380// Returns true if it is a constant float BuildVector or constant float.
15383 return true;
15384
15386 return true;
15387
15388 if ((N.getOpcode() == ISD::SPLAT_VECTOR) &&
15389 isa<ConstantFPSDNode>(N.getOperand(0)))
15390 return true;
15391
15392 return false;
15393}
15394
15395std::optional<bool> SelectionDAG::isBoolConstant(SDValue N) const {
15396 ConstantSDNode *Const =
15397 isConstOrConstSplat(N, false, /*AllowTruncation=*/true);
15398 if (!Const)
15399 return std::nullopt;
15400
15401 EVT VT = N.getValueType();
15402 const APInt CVal = Const->getAPIntValue().trunc(VT.getScalarSizeInBits());
15403 switch (TLI->getBooleanContents(VT)) {
15405 if (CVal.isOne())
15406 return true;
15407 if (CVal.isZero())
15408 return false;
15409 return std::nullopt;
15411 if (CVal.isAllOnes())
15412 return true;
15413 if (CVal.isZero())
15414 return false;
15415 return std::nullopt;
15417 return CVal[0];
15418 }
15419 llvm_unreachable("Unknown BooleanContent enum");
15420}
15421
15422void SelectionDAG::createOperands(SDNode *Node, ArrayRef<SDValue> Vals) {
15423 assert(!Node->OperandList && "Node already has operands");
15425 "too many operands to fit into SDNode");
15426 SDUse *Ops = OperandRecycler.allocate(
15427 ArrayRecycler<SDUse>::Capacity::get(Vals.size()), OperandAllocator);
15428
15429 bool IsDivergent = false;
15430 for (unsigned I = 0; I != Vals.size(); ++I) {
15431 Ops[I].setUser(Node);
15432 Ops[I].setInitial(Vals[I]);
15433 EVT VT = Ops[I].getValueType();
15434
15435 // Skip Chain. It does not carry divergence.
15436 if (VT != MVT::Other &&
15437 (VT != MVT::Glue || gluePropagatesDivergence(Ops[I].getNode())) &&
15438 Ops[I].getNode()->isDivergent()) {
15439 IsDivergent = true;
15440 }
15441 }
15442 Node->NumOperands = Vals.size();
15443 Node->OperandList = Ops;
15444 if (!TLI->isSDNodeAlwaysUniform(Node)) {
15445 IsDivergent |= TLI->isSDNodeSourceOfDivergence(Node, FLI, UA);
15446 Node->SDNodeBits.IsDivergent = IsDivergent;
15447 }
15448 checkForCycles(Node);
15449}
15450
15453 size_t Limit = SDNode::getMaxNumOperands();
15454 while (Vals.size() > Limit) {
15455 unsigned SliceIdx = Vals.size() - Limit;
15456 auto ExtractedTFs = ArrayRef<SDValue>(Vals).slice(SliceIdx, Limit);
15457 SDValue NewTF = getNode(ISD::TokenFactor, DL, MVT::Other, ExtractedTFs);
15458 Vals.erase(Vals.begin() + SliceIdx, Vals.end());
15459 Vals.emplace_back(NewTF);
15460 }
15461 return getNode(ISD::TokenFactor, DL, MVT::Other, Vals);
15462}
15463
15465 EVT VT, SDNodeFlags Flags) {
15466 switch (Opcode) {
15467 default:
15468 return SDValue();
15469 case ISD::ADD:
15470 case ISD::OR:
15471 case ISD::XOR:
15472 case ISD::UMAX:
15473 case ISD::MUL:
15474 case ISD::AND:
15475 case ISD::UMIN:
15476 case ISD::SMAX:
15477 case ISD::SMIN:
15479 VT);
15480 case ISD::FADD:
15481 // If flags allow, prefer positive zero since it's generally cheaper
15482 // to materialize on most targets.
15483 return getConstantFP(Flags.hasNoSignedZeros() ? 0.0 : -0.0, DL, VT);
15484 case ISD::FMUL:
15485 return getConstantFP(1.0, DL, VT);
15486 case ISD::FMINNUM:
15487 case ISD::FMAXNUM:
15488 case ISD::FMINIMUMNUM:
15489 case ISD::FMAXIMUMNUM: {
15490 // Neutral element for fminnum/fminimumnum is NaN, Inf or FLT_MAX,
15491 // depending on fast-math flags (FMF).
15492 const fltSemantics &Semantics = VT.getFltSemantics();
15493 APFloat NeutralAF = !Flags.hasNoNaNs() ? APFloat::getQNaN(Semantics) :
15494 !Flags.hasNoInfs() ? APFloat::getInf(Semantics) :
15495 APFloat::getLargest(Semantics);
15496 if (Opcode == ISD::FMAXNUM || Opcode == ISD::FMAXIMUMNUM)
15497 NeutralAF.changeSign();
15498
15499 return getConstantFP(NeutralAF, DL, VT);
15500 }
15501 case ISD::FMINIMUM:
15502 case ISD::FMAXIMUM: {
15503 // Neutral element for fminimum is Inf or FLT_MAX, depending on FMF.
15504 const fltSemantics &Semantics = VT.getFltSemantics();
15505 APFloat NeutralAF = !Flags.hasNoInfs() ? APFloat::getInf(Semantics)
15506 : APFloat::getLargest(Semantics);
15507 if (Opcode == ISD::FMAXIMUM)
15508 NeutralAF.changeSign();
15509
15510 return getConstantFP(NeutralAF, DL, VT);
15511 }
15512
15513 }
15514}
15515
15517 SDValue Acc, SDValue LHS,
15518 SDValue RHS) {
15519 EVT AccVT = Acc.getValueType();
15520 if (AccVT.isFloatingPoint()) {
15521 assert(Opc == ISD::PARTIAL_REDUCE_FMLA && "Unexpected opcode");
15522 SDValue NegRHS = getNode(ISD::FNEG, DL, RHS.getValueType(), RHS);
15523 return getNode(Opc, DL, AccVT, Acc, LHS, NegRHS);
15524 }
15527 "Unexpected opcode");
15528 SDValue NegAcc = getNegative(Acc, DL, AccVT);
15529 SDValue MLA = getNode(Opc, DL, AccVT, NegAcc, LHS, RHS);
15530 return getNegative(MLA, DL, AccVT);
15531}
15532
15533/// Helper used to make a call to a library function that has one argument of
15534/// pointer type.
15535///
15536/// Such functions include 'fegetmode', 'fesetenv' and some others, which are
15537/// used to get or set floating-point state. They have one argument of pointer
15538/// type, which points to the memory region containing bits of the
15539/// floating-point state. The value returned by such function is ignored in the
15540/// created call.
15541///
15542/// \param LibFunc Reference to library function (value of RTLIB::Libcall).
15543/// \param Ptr Pointer used to save/load state.
15544/// \param InChain Ingoing token chain.
15545/// \param Node Node being legalized
15546/// \returns Outgoing chain token.
15548 SDValue InChain, SDNode *Node) {
15549 assert(InChain.getValueType() == MVT::Other && "Expected token chain");
15550 RTLIB::LibcallImpl LibcallImpl =
15551 Libcalls->getLibcallImpl(static_cast<RTLIB::Libcall>(LibFunc));
15552 if (LibcallImpl == RTLIB::Unsupported) {
15553 getContext()->emitError(Twine("no libcall available for ") +
15554 Node->getOperationName(this));
15555 return InChain;
15556 }
15557
15559 Args.emplace_back(Ptr, Ptr.getValueType().getTypeForEVT(*getContext()));
15560 SDValue Callee =
15561 getExternalSymbol(LibcallImpl, TLI->getPointerTy(getDataLayout()));
15563 CLI.setDebugLoc(SDLoc(Node))
15564 .setChain(InChain)
15565 .setLibCallee(Libcalls->getLibcallImplCallingConv(LibcallImpl),
15566 Type::getVoidTy(*getContext()), Callee, std::move(Args));
15567 return TLI->LowerCallTo(CLI).second;
15568}
15569
15571 assert(From && To && "Invalid SDNode; empty source SDValue?");
15572 auto I = SDEI.find(From);
15573 if (I == SDEI.end())
15574 return;
15575
15576 // Use of operator[] on the DenseMap may cause an insertion, which invalidates
15577 // the iterator, hence the need to make a copy to prevent a use-after-free.
15578 NodeExtraInfo NEI = I->second;
15579 if (LLVM_LIKELY(!NEI.PCSections)) {
15580 // No deep copy required for the types of extra info set.
15581 //
15582 // FIXME: Investigate if other types of extra info also need deep copy. This
15583 // depends on the types of nodes they can be attached to: if some extra info
15584 // is only ever attached to nodes where a replacement To node is always the
15585 // node where later use and propagation of the extra info has the intended
15586 // semantics, no deep copy is required.
15587 SDEI[To] = std::move(NEI);
15588 return;
15589 }
15590
15591 const SDNode *EntrySDN = getEntryNode().getNode();
15592
15593 // We need to copy NodeExtraInfo to all _new_ nodes that are being introduced
15594 // through the replacement of From with To. Otherwise, replacements of a node
15595 // (From) with more complex nodes (To and its operands) may result in lost
15596 // extra info where the root node (To) is insignificant in further propagating
15597 // and using extra info when further lowering to MIR.
15598 //
15599 // In the first step pre-populate the visited set with the nodes reachable
15600 // from the old From node. This avoids copying NodeExtraInfo to parts of the
15601 // DAG that is not new and should be left untouched.
15602 SmallVector<const SDNode *> Leafs{From}; // Leafs reachable with VisitFrom.
15603 DenseSet<const SDNode *> FromReach; // The set of nodes reachable from From.
15604 auto VisitFrom = [&](auto &&Self, const SDNode *N, int MaxDepth) {
15605 if (MaxDepth == 0) {
15606 // Remember this node in case we need to increase MaxDepth and continue
15607 // populating FromReach from this node.
15608 Leafs.emplace_back(N);
15609 return;
15610 }
15611 if (!FromReach.insert(N).second)
15612 return;
15613 for (const SDValue &Op : N->op_values())
15614 Self(Self, Op.getNode(), MaxDepth - 1);
15615 };
15616
15617 // Copy extra info to To and all its transitive operands (that are new).
15619 auto DeepCopyTo = [&](auto &&Self, const SDNode *N) {
15620 if (FromReach.contains(N))
15621 return true;
15622 if (!Visited.insert(N).second)
15623 return true;
15624 if (EntrySDN == N)
15625 return false;
15626 for (const SDValue &Op : N->op_values()) {
15627 if (N == To && Op.getNode() == EntrySDN) {
15628 // Special case: New node's operand is the entry node; just need to
15629 // copy extra info to new node.
15630 break;
15631 }
15632 if (!Self(Self, Op.getNode()))
15633 return false;
15634 }
15635 // Copy only if entry node was not reached.
15636 SDEI[N] = std::move(NEI);
15637 return true;
15638 };
15639
15640 // We first try with a lower MaxDepth, assuming that the path to common
15641 // operands between From and To is relatively short. This significantly
15642 // improves performance in the common case. The initial MaxDepth is big
15643 // enough to avoid retry in the common case; the last MaxDepth is large
15644 // enough to avoid having to use the fallback below (and protects from
15645 // potential stack exhaustion from recursion).
15646 for (int PrevDepth = 0, MaxDepth = 16; MaxDepth <= 1024;
15647 PrevDepth = MaxDepth, MaxDepth *= 2, Visited.clear()) {
15648 // StartFrom is the previous (or initial) set of leafs reachable at the
15649 // previous maximum depth.
15651 std::swap(StartFrom, Leafs);
15652 for (const SDNode *N : StartFrom)
15653 VisitFrom(VisitFrom, N, MaxDepth - PrevDepth);
15654 if (LLVM_LIKELY(DeepCopyTo(DeepCopyTo, To)))
15655 return;
15656 // This should happen very rarely (reached the entry node).
15657 LLVM_DEBUG(dbgs() << __func__ << ": MaxDepth=" << MaxDepth << " too low\n");
15658 assert(!Leafs.empty());
15659 }
15660
15661 // This should not happen - but if it did, that means the subgraph reachable
15662 // from From has depth greater or equal to maximum MaxDepth, and VisitFrom()
15663 // could not visit all reachable common operands. Consequently, we were able
15664 // to reach the entry node.
15665 errs() << "warning: incomplete propagation of SelectionDAG::NodeExtraInfo\n";
15666 assert(false && "From subgraph too complex - increase max. MaxDepth?");
15667 // Best-effort fallback if assertions disabled.
15668 SDEI[To] = std::move(NEI);
15669}
15670
15672 assert(VT.isVector() && "Can only unroll vector types!");
15673 if (VT.isFixedLengthVector())
15674 return VT.getVectorNumElements();
15675
15676 const MachineFunction &MF = getMachineFunction();
15677 const Function &F = MF.getFunction();
15678
15679 APInt MaxVScale = getVScaleRange(&F, sizeof(unsigned) * 8).getUnsignedMax();
15680 if (MaxVScale.ugt(getSelectionDAGOptions().vscale_unroll_limit))
15681 return 0;
15682
15683 bool Overflow;
15684 APInt MinNElts(sizeof(unsigned) * 8, VT.getVectorMinNumElements());
15685 APInt MaxNElts = MinNElts.umul_ov(MaxVScale, Overflow);
15686 if (Overflow)
15687 return 0;
15688
15689 return MaxNElts.getZExtValue();
15690}
15691
15693 ArrayRef<SDValue> Scalars) {
15694 assert(Scalars.size() == getMaxRuntimeNumElements(VT) &&
15695 "Element count mismatch!");
15696 if (VT.isFixedLengthVector())
15697 return getBuildVector(VT, DL, Scalars);
15698
15699 SDValue Vec = getPOISON(VT);
15700 // Iterate in reverse so result remains poison until we encounter a lane that
15701 // exists, after which all lower-numbered lanes must also exist.
15702 for (unsigned IdxVal : reverse(seq(Scalars.size())))
15703 Vec = getInsertVectorElt(DL, Vec, Scalars[IdxVal], IdxVal);
15704
15705 return Vec;
15706}
15707
15708#ifndef NDEBUG
15709static void checkForCyclesHelper(const SDNode *N,
15712 const llvm::SelectionDAG *DAG) {
15713 // If this node has already been checked, don't check it again.
15714 if (Checked.count(N))
15715 return;
15716
15717 // If a node has already been visited on this depth-first walk, reject it as
15718 // a cycle.
15719 if (!Visited.insert(N).second) {
15720 errs() << "Detected cycle in SelectionDAG\n";
15721 dbgs() << "Offending node:\n";
15722 N->dumprFull(DAG); dbgs() << "\n";
15723 abort();
15724 }
15725
15726 for (const SDValue &Op : N->op_values())
15727 checkForCyclesHelper(Op.getNode(), Visited, Checked, DAG);
15728
15729 Checked.insert(N);
15730 Visited.erase(N);
15731}
15732#endif
15733
15735 const llvm::SelectionDAG *DAG,
15736 bool force) {
15737#ifndef NDEBUG
15738 bool check = force;
15739#ifdef EXPENSIVE_CHECKS
15740 check = true;
15741#endif // EXPENSIVE_CHECKS
15742 if (check) {
15743 assert(N && "Checking nonexistent SDNode");
15746 checkForCyclesHelper(N, visited, checked, DAG);
15747 }
15748#endif // !NDEBUG
15749}
15750
15751void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) {
15752 checkForCycles(DAG->getRoot().getNode(), DAG, force);
15753}
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...
static RegisterPass< DebugifyModulePass > DM("debugify", "Attach debug info to everything")
This file defines the DenseSet and SmallDenseSet classes.
This file contains constants used for implementing Dwarf debug support.
This file provides fallible floating-point folding operations with explicit rounding and denormal mod...
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)
cmpResult
IEEE-754R 5.11: Floating Point Comparison Relations.
Definition APFloat.h:370
static constexpr roundingMode rmTowardZero
Definition APFloat.h:384
static constexpr roundingMode rmNearestTiesToEven
Definition APFloat.h:380
static LLVM_ABI bool hasSignBitInMSB(const fltSemantics &)
Definition APFloat.cpp:656
static constexpr const fltSemantics & IEEEhalf()
Definition APFloat.h:303
static constexpr const fltSemantics & IEEEsingle()
Definition APFloat.h:305
static constexpr const fltSemantics & BFloat()
Definition APFloat.h:304
static constexpr const fltSemantics & IEEEdouble()
Definition APFloat.h:306
static constexpr const fltSemantics & IEEEquad()
Definition APFloat.h:307
opStatus
IEEE-754R 7: Default exception handling.
Definition APFloat.h:396
static APFloat getQNaN(const fltSemantics &Sem, bool Negative=false, const APInt *payload=nullptr)
Factory for QNaN values.
Definition APFloat.h:1253
LLVM_ABI opStatus convert(const fltSemantics &ToSemantics, roundingMode RM, bool *losesInfo)
Definition APFloat.cpp:6106
bool isNegative() const
Definition APFloat.h:1612
bool isFinite() const
Definition APFloat.h:1617
opStatus convertFromAPInt(const APInt &Input, bool IsSigned, roundingMode RM)
Definition APFloat.h:1480
bool isZero() const
Definition APFloat.h:1608
LLVM_READONLY bool isOne() const
Definition APFloat.h:1705
bool isLargest() const
Definition APFloat.h:1628
static APFloat getLargest(const fltSemantics &Sem, bool Negative=false)
Returns the largest finite number in the given semantics.
Definition APFloat.h:1271
opStatus convertToInteger(MutableArrayRef< integerPart > Input, unsigned int Width, bool IsSigned, roundingMode RM, bool *IsExact) const
Definition APFloat.h:1465
static APFloat getInf(const fltSemantics &Sem, bool Negative=false)
Factory for Positive and Negative Infinity.
Definition APFloat.h:1231
bool isPosZero() const
Definition APFloat.h:1623
bool isNegZero() const
Definition APFloat.h:1624
void changeSign()
Definition APFloat.h:1430
static APFloat getNaN(const fltSemantics &Sem, bool Negative=false, uint64_t payload=0)
Factory for NaN values.
Definition APFloat.h:1242
bool isInfinity() const
Definition APFloat.h:1609
Class for arbitrary precision integers.
Definition APInt.h:78
LLVM_ABI APInt umul_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:2018
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:220
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.
bool isBigEndian() const
Definition DataLayout.h:221
LLVM_ABI Align getPrefTypeAlign(Type *Ty) const
Returns the preferred stack/global alignment for the specified type.
A debug info location.
Definition DebugLoc.h:127
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:1087
const MDOperand & getOperand(unsigned I) const
Definition Metadata.h:1443
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:65
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:882
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 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 getConstFP(std::optional< FPFoldResult > Result, const SDLoc &DL, EVT VT, bool isTarget=false)
Return the folded constant, or an empty SDValue if folding failed.
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 SDValue getFreeze(SDValue V, UndefPoisonKind Kind=UndefPoisonKind::UndefOrPoison)
Return a freeze of V using the SDLoc of the value operand.
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)
LLVM_NO_SANITIZE_CFI_UNRELATED_CAST iterator begin()
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:726
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:294
static LLVM_ABI Type * getVoidTy(LLVMContext &C)
Definition Type.cpp:267
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.h:354
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:187
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Definition Type.cpp:298
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:3254
LLVM_ABI APInt mulhu(const APInt &C1, const APInt &C2)
Performs (2*N)-bit multiplication on zero-extended operands.
Definition APInt.cpp:3184
LLVM_ABI APInt avgCeilU(const APInt &C1, const APInt &C2)
Compute the ceil of the unsigned average of C1 and C2.
Definition APInt.cpp:3161
LLVM_ABI APInt avgFloorU(const APInt &C1, const APInt &C2)
Compute the floor of the unsigned average of C1 and C2.
Definition APInt.cpp:3151
LLVM_ABI APInt pext(const APInt &Val, const APInt &Mask)
Perform a "compress" operation, also known as pext or bext.
Definition APInt.cpp:3264
LLVM_ABI APInt fshr(const APInt &Hi, const APInt &Lo, const APInt &Shift)
Perform a funnel shift right.
Definition APInt.cpp:3235
LLVM_ABI APInt mulhs(const APInt &C1, const APInt &C2)
Performs (2*N)-bit multiplication on sign-extended operands.
Definition APInt.cpp:3176
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:3166
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:3244
LLVM_ABI APInt pdep(const APInt &Val, const APInt &Mask)
Perform an "expand" operation, also known as pdep or bdep.
Definition APInt.cpp:3274
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:3226
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:3052
LLVM_ABI APInt clmulh(const APInt &LHS, const APInt &RHS)
Perform a carry-less multiply, and return high-bits.
Definition APInt.cpp:3259
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:3146
LLVM_ABI APInt avgCeilS(const APInt &C1, const APInt &C2)
Compute the ceil of the signed average of C1 and C2.
Definition APInt.cpp:3156
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:3171
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 isConstantSplatVector(SDValue V, APInt &SplatValue)
Node predicates.
LLVM_ABI bool isBuildVectorOfConstantFPSDNodes(SDValue V)
Return true if the specified value is a BUILD_VECTOR node of all ConstantFPSDNode or undef.
bool isNON_EXTLoad(const SDNode *N)
Returns true if the specified node is a non-extending load.
LLVM_ABI bool isConstantSplatVectorAllZeros(SDValue V, bool BuildVectorOnly=false)
Return true if the specified value is a BUILD_VECTOR or SPLAT_VECTOR where all of the elements are 0 ...
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 NodeType getExtForLoadExtType(bool IsFP, LoadExtType)
bool isZEXTLoad(const SDNode *N)
Returns true if the specified node is a ZEXTLOAD.
LLVM_ABI bool isConstantSplatVectorAllOnes(SDValue V, bool BuildVectorOnly=false)
Return true if the specified value is a BUILD_VECTOR or SPLAT_VECTOR where all of the elements are ~0...
LLVM_ABI bool isFreezeUndef(SDValue V)
Return true if the specified value is FREEZE(UNDEF).
bool isExtOpcode(unsigned Opcode)
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 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 bool allOperandsUndef(SDValue V)
Return true if the value has at least one operand and all operands of the specified value are ISD::UN...
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 bool isBuildVectorAllOnes(SDValue V)
Return true if the specified value is a BUILD_VECTOR where all of the elements are ~0 or undef.
LLVM_ABI std::optional< unsigned > getVPMaskIdx(unsigned Opcode)
The operand position of the vector mask.
LLVM_ABI bool isVectorShrinkable(SDValue V, unsigned NewEltSize, bool Signed)
Returns true if the specified value is a vector where all elements can be truncated to the specified ...
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 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 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 isBuildVectorAllZeros(SDValue V)
Return true if the specified value is a BUILD_VECTOR where all of the elements are 0 or undef.
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.
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 isBuildVectorOfConstantSDNodes(SDValue V)
Return true if the specified value is a BUILD_VECTOR node of all ConstantSDNode 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:680
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:2575
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.
LLVM_ABI std::optional< FPFoldResult > tryFoldFP(FPOp Opcode, ArrayRef< APFloat > Args, DenormalMode Denorms)
Try to evaluate a floating-point operation with the specified inputs.
Definition FPFold.cpp:160
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
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2229
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:1757
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...
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.
@ MaximumNum
Definition FPFold.h:36
@ Maximum
Definition FPFold.h:34
@ Minimum
Definition FPFold.h:33
@ MinimumNum
Definition FPFold.h:35
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
FPClassTest
Floating-point class tests, supported by 'is_fpclass' intrinsic.
LLVM_ABI std::optional< APFloat::cmpResult > tryFoldFCmp(const APFloat &LHS, const APFloat &RHS, DenormalMode Denorms)
Try to compare two floating-point values.
Definition FPFold.cpp:184
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.
LLVM_ABI MDNode * getMemCacheHint(const Instruction &I, unsigned OperandNo=0)
Return the hint payload for operand OperandNo of I, or nullptr if absent.
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
@ 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:709
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:888
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_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:775
MDNode * TBAAStruct
The tag for type-based alias analysis (tbaa struct).
Definition Metadata.h:795
MDNode * TBAA
The tag for type-based alias analysis.
Definition Metadata.h:792
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.
Represent subnormal handling kind for floating point instruction inputs and outputs.
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.
LLVM_ABI KnownBits ctlz(bool ZeroIsPoison=false) const
Compute known bits for the count of leading zeros.
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:562
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:566
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:55
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
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)