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 return getNode(ISD::FREEZE, SDLoc(V), V.getValueType(), V);
2523}
2524
2526 UndefPoisonKind Kind) {
2527 if (isGuaranteedNotToBeUndefOrPoison(V, DemandedElts, Kind))
2528 return V;
2529 return getFreeze(V);
2530}
2531
2532/// getShiftAmountOperand - Return the specified value casted to
2533/// the target's desired shift amount type.
2535 EVT OpTy = Op.getValueType();
2536 EVT ShTy = TLI->getShiftAmountTy(LHSTy, getDataLayout());
2537 if (OpTy == ShTy || OpTy.isVector()) return Op;
2538
2539 return getZExtOrTrunc(Op, SDLoc(Op), ShTy);
2540}
2541
2543 SDLoc dl(Node);
2545 const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2546 EVT VT = Node->getValueType(0);
2547 SDValue Tmp1 = Node->getOperand(0);
2548 SDValue Tmp2 = Node->getOperand(1);
2549 const MaybeAlign MA(Node->getConstantOperandVal(3));
2550
2551 SDValue VAListLoad = getLoad(TLI.getPointerTy(getDataLayout()), dl, Tmp1,
2552 Tmp2, MachinePointerInfo(V));
2553 SDValue VAList = VAListLoad;
2554
2555 if (MA && *MA > TLI.getMinStackArgumentAlignment()) {
2556 VAList = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
2557 getConstant(MA->value() - 1, dl, VAList.getValueType()));
2558
2559 VAList = getNode(
2560 ISD::AND, dl, VAList.getValueType(), VAList,
2561 getSignedConstant(-(int64_t)MA->value(), dl, VAList.getValueType()));
2562 }
2563
2564 // Increment the pointer, VAList, to the next vaarg
2565 Tmp1 = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
2566 getConstant(getDataLayout().getTypeAllocSize(
2567 VT.getTypeForEVT(*getContext())),
2568 dl, VAList.getValueType()));
2569 // Store the incremented VAList to the legalized pointer
2570 Tmp1 =
2571 getStore(VAListLoad.getValue(1), dl, Tmp1, Tmp2, MachinePointerInfo(V));
2572 // Load the actual argument out of the pointer VAList
2573 return getLoad(VT, dl, Tmp1, VAList, MachinePointerInfo());
2574}
2575
2577 SDLoc dl(Node);
2579 // This defaults to loading a pointer from the input and storing it to the
2580 // output, returning the chain.
2581 const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue();
2582 const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue();
2583 SDValue Tmp1 =
2584 getLoad(TLI.getPointerTy(getDataLayout()), dl, Node->getOperand(0),
2585 Node->getOperand(2), MachinePointerInfo(VS));
2586 return getStore(Tmp1.getValue(1), dl, Tmp1, Node->getOperand(1),
2587 MachinePointerInfo(VD));
2588}
2589
2591 const DataLayout &DL = getDataLayout();
2592 Type *Ty = VT.getTypeForEVT(*getContext());
2593 Align RedAlign = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty);
2594
2595 if (TLI->isTypeLegal(VT) || !VT.isVector())
2596 return RedAlign;
2597
2598 const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
2599 const Align StackAlign = TFI->getStackAlign();
2600
2601 // See if we can choose a smaller ABI alignment in cases where it's an
2602 // illegal vector type that will get broken down.
2603 if (RedAlign > StackAlign) {
2604 EVT IntermediateVT;
2605 MVT RegisterVT;
2606 unsigned NumIntermediates;
2607 TLI->getVectorTypeBreakdown(*getContext(), VT, IntermediateVT,
2608 NumIntermediates, RegisterVT);
2609 Ty = IntermediateVT.getTypeForEVT(*getContext());
2610 Align RedAlign2 = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty);
2611 if (RedAlign2 < RedAlign)
2612 RedAlign = RedAlign2;
2613
2614 if (!getMachineFunction().getFrameInfo().isStackRealignable())
2615 // If the stack is not realignable, the alignment should be limited to the
2616 // StackAlignment
2617 RedAlign = std::min(RedAlign, StackAlign);
2618 }
2619
2620 return RedAlign;
2621}
2622
2624 MachineFrameInfo &MFI = MF->getFrameInfo();
2625 const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
2626 int StackID = 0;
2627 if (Bytes.isScalable())
2628 StackID = TFI->getStackIDForScalableVectors();
2629 // The stack id gives an indication of whether the object is scalable or
2630 // not, so it's safe to pass in the minimum size here.
2631 int FrameIdx = MFI.CreateStackObject(Bytes.getKnownMinValue(), Alignment,
2632 false, nullptr, StackID);
2633 return getFrameIndex(FrameIdx, TLI->getFrameIndexTy(getDataLayout()));
2634}
2635
2637 Type *Ty = VT.getTypeForEVT(*getContext());
2638 Align StackAlign =
2639 std::max(getDataLayout().getPrefTypeAlign(Ty), Align(minAlign));
2640 return CreateStackTemporary(VT.getStoreSize(), StackAlign);
2641}
2642
2644 TypeSize VT1Size = VT1.getStoreSize();
2645 TypeSize VT2Size = VT2.getStoreSize();
2646 assert(VT1Size.isScalable() == VT2Size.isScalable() &&
2647 "Don't know how to choose the maximum size when creating a stack "
2648 "temporary");
2649 TypeSize Bytes = VT1Size.getKnownMinValue() > VT2Size.getKnownMinValue()
2650 ? VT1Size
2651 : VT2Size;
2652
2653 Type *Ty1 = VT1.getTypeForEVT(*getContext());
2654 Type *Ty2 = VT2.getTypeForEVT(*getContext());
2655 const DataLayout &DL = getDataLayout();
2656 Align Align = std::max(DL.getPrefTypeAlign(Ty1), DL.getPrefTypeAlign(Ty2));
2657 return CreateStackTemporary(Bytes, Align);
2658}
2659
2661 const SDLoc &DL, SDValue Chain) {
2662 EVT SrcVT = SrcOp.getValueType();
2663 Type *DestType = DestVT.getTypeForEVT(*getContext());
2664 Align DestAlign = getDataLayout().getPrefTypeAlign(DestType);
2665
2666 // Create the stack frame object.
2667 Align SrcAlign =
2669 SDValue FIPtr = CreateStackTemporary(SlotVT.getStoreSize(), SrcAlign);
2670
2671 FrameIndexSDNode *StackPtrFI = cast<FrameIndexSDNode>(FIPtr);
2672 int SPFI = StackPtrFI->getIndex();
2673 MachinePointerInfo PtrInfo =
2675
2676 // Emit a store to the stack slot. Use a truncstore if the input value is
2677 // later than DestVT.
2678 SDValue Store;
2679
2680 if (SrcVT.bitsGT(SlotVT))
2681 Store = getTruncStore(Chain, DL, SrcOp, FIPtr, PtrInfo, SlotVT, SrcAlign);
2682 else {
2683 assert(SrcVT.bitsEq(SlotVT) && "Invalid store");
2684 Store = getStore(Chain, DL, SrcOp, FIPtr, PtrInfo, SrcAlign);
2685 }
2686
2687 // Result is a load from the stack slot.
2688 if (SlotVT.bitsEq(DestVT))
2689 return getLoad(DestVT, DL, Store, FIPtr, PtrInfo, DestAlign);
2690
2691 assert(SlotVT.bitsLT(DestVT) && "Unknown extension!");
2692 return getExtLoad(ISD::EXTLOAD, DL, DestVT, Store, FIPtr, PtrInfo, SlotVT,
2693 DestAlign);
2694}
2695
2697 ISD::CondCode Cond, const SDLoc &dl,
2698 SDNodeFlags Flags) {
2699 EVT OpVT = N1.getValueType();
2700
2701 auto GetUndefBooleanConstant = [&]() {
2702 if (VT.getScalarType() == MVT::i1 ||
2703 TLI->getBooleanContents(OpVT) ==
2705 return getUNDEF(VT);
2706 // ZeroOrOne / ZeroOrNegative require specific values for the high bits,
2707 // so we cannot use getUNDEF(). Return zero instead.
2708 return getConstant(0, dl, VT);
2709 };
2710
2711 // These setcc operations always fold.
2712 switch (Cond) {
2713 default: break;
2714 case ISD::SETFALSE:
2715 case ISD::SETFALSE2: return getBoolConstant(false, dl, VT, OpVT);
2716 case ISD::SETTRUE:
2717 case ISD::SETTRUE2: return getBoolConstant(true, dl, VT, OpVT);
2718
2719 case ISD::SETOEQ:
2720 case ISD::SETOGT:
2721 case ISD::SETOGE:
2722 case ISD::SETOLT:
2723 case ISD::SETOLE:
2724 case ISD::SETONE:
2725 case ISD::SETO:
2726 case ISD::SETUO:
2727 case ISD::SETUEQ:
2728 case ISD::SETUNE:
2729 assert(!OpVT.isInteger() && "Illegal setcc for integer!");
2730 break;
2731 }
2732
2733 if (OpVT.isInteger()) {
2734 // For EQ and NE, we can always pick a value for the undef to make the
2735 // predicate pass or fail, so we can return undef.
2736 // Matches behavior in llvm::ConstantFoldCompareInstruction.
2737 // icmp eq/ne X, undef -> undef.
2738 if ((N1.isUndef() || N2.isUndef()) &&
2739 (Cond == ISD::SETEQ || Cond == ISD::SETNE))
2740 return GetUndefBooleanConstant();
2741
2742 // If both operands are undef, we can return undef for int comparison.
2743 // icmp undef, undef -> undef.
2744 if (N1.isUndef() && N2.isUndef())
2745 return GetUndefBooleanConstant();
2746
2747 // icmp X, X -> true/false
2748 // icmp X, undef -> true/false because undef could be X.
2749 if (N1.isUndef() || N2.isUndef() || N1 == N2)
2750 return getBoolConstant(ISD::isTrueWhenEqual(Cond), dl, VT, OpVT);
2751 }
2752
2753 if (ConstantSDNode *N2C = isConstOrConstSplat(N2)) {
2754 const APInt &C2 = N2C->getAPIntValue();
2755 if (ConstantSDNode *N1C = isConstOrConstSplat(N1)) {
2756 const APInt &C1 = N1C->getAPIntValue();
2757
2759 dl, VT, OpVT);
2760 }
2761 }
2762
2763 auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
2764 auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
2765
2766 if (N1CFP && N2CFP) {
2767 auto MaybeR = tryFoldFCmp(N1CFP->getValueAPF(), N2CFP->getValueAPF(),
2768 getDenormalMode(OpVT));
2769 if (!MaybeR)
2770 return SDValue();
2771 APFloat::cmpResult R = *MaybeR;
2772 switch (Cond) {
2773 default: break;
2774 case ISD::SETEQ: if (R==APFloat::cmpUnordered)
2775 return GetUndefBooleanConstant();
2776 [[fallthrough]];
2777 case ISD::SETOEQ: return getBoolConstant(R==APFloat::cmpEqual, dl, VT,
2778 OpVT);
2779 case ISD::SETNE: if (R==APFloat::cmpUnordered)
2780 return GetUndefBooleanConstant();
2781 [[fallthrough]];
2783 R==APFloat::cmpLessThan, dl, VT,
2784 OpVT);
2785 case ISD::SETLT: if (R==APFloat::cmpUnordered)
2786 return GetUndefBooleanConstant();
2787 [[fallthrough]];
2788 case ISD::SETOLT: return getBoolConstant(R==APFloat::cmpLessThan, dl, VT,
2789 OpVT);
2790 case ISD::SETGT: if (R==APFloat::cmpUnordered)
2791 return GetUndefBooleanConstant();
2792 [[fallthrough]];
2794 VT, OpVT);
2795 case ISD::SETLE: if (R==APFloat::cmpUnordered)
2796 return GetUndefBooleanConstant();
2797 [[fallthrough]];
2799 R==APFloat::cmpEqual, dl, VT,
2800 OpVT);
2801 case ISD::SETGE: if (R==APFloat::cmpUnordered)
2802 return GetUndefBooleanConstant();
2803 [[fallthrough]];
2805 R==APFloat::cmpEqual, dl, VT, OpVT);
2806 case ISD::SETO: return getBoolConstant(R!=APFloat::cmpUnordered, dl, VT,
2807 OpVT);
2808 case ISD::SETUO: return getBoolConstant(R==APFloat::cmpUnordered, dl, VT,
2809 OpVT);
2811 R==APFloat::cmpEqual, dl, VT,
2812 OpVT);
2813 case ISD::SETUNE: return getBoolConstant(R!=APFloat::cmpEqual, dl, VT,
2814 OpVT);
2816 R==APFloat::cmpLessThan, dl, VT,
2817 OpVT);
2819 R==APFloat::cmpUnordered, dl, VT,
2820 OpVT);
2822 VT, OpVT);
2823 case ISD::SETUGE: return getBoolConstant(R!=APFloat::cmpLessThan, dl, VT,
2824 OpVT);
2825 }
2826 } else if (N1CFP && OpVT.isSimple() && !N2.isUndef()) {
2827 // Ensure that the constant occurs on the RHS.
2829 if (!TLI->isCondCodeLegal(SwappedCond, OpVT.getSimpleVT()))
2830 return SDValue();
2831 return getSetCC(dl, VT, N2, N1, SwappedCond, /*Chain=*/{},
2832 /*IsSignaling=*/false, Flags);
2833 } else if ((N2CFP && N2CFP->getValueAPF().isNaN()) ||
2834 (OpVT.isFloatingPoint() && (N1.isUndef() || N2.isUndef()))) {
2835 // If an operand is known to be a nan (or undef that could be a nan), we can
2836 // fold it.
2837 // Choosing NaN for the undef will always make unordered comparison succeed
2838 // and ordered comparison fails.
2839 // Matches behavior in llvm::ConstantFoldCompareInstruction.
2840 switch (ISD::getUnorderedFlavor(Cond)) {
2841 default:
2842 llvm_unreachable("Unknown flavor!");
2843 case 0: // Known false.
2844 return getBoolConstant(false, dl, VT, OpVT);
2845 case 1: // Known true.
2846 return getBoolConstant(true, dl, VT, OpVT);
2847 case 2: // Undefined.
2848 return GetUndefBooleanConstant();
2849 }
2850 }
2851
2852 // Could not fold it.
2853 return SDValue();
2854}
2855
2856/// SignBitIsZero - Return true if the sign bit of Op is known to be zero. We
2857/// use this predicate to simplify operations downstream.
2859 unsigned BitWidth = Op.getScalarValueSizeInBits();
2861}
2862
2863// TODO: Should have argument to specify if sign bit of nan is ignorable.
2865 if (Depth >= MaxRecursionDepth)
2866 return false; // Limit search depth.
2867
2868 unsigned Opc = Op.getOpcode();
2869 switch (Opc) {
2870 case ISD::FABS:
2871 return true;
2872 case ISD::AssertNoFPClass: {
2873 FPClassTest NoFPClass =
2874 static_cast<FPClassTest>(Op.getConstantOperandVal(1));
2875
2876 const FPClassTest TestMask = fcNan | fcNegative;
2877 return (NoFPClass & TestMask) == TestMask;
2878 }
2879 case ISD::ARITH_FENCE:
2880 return SignBitIsZeroFP(Op.getOperand(0), Depth + 1);
2881 case ISD::FEXP:
2882 case ISD::FEXP2:
2883 case ISD::FEXP10:
2884 return Op->getFlags().hasNoNaNs();
2885 case ISD::FMINNUM:
2886 case ISD::FMINNUM_IEEE:
2887 case ISD::FMINIMUM:
2888 case ISD::FMINIMUMNUM:
2889 return SignBitIsZeroFP(Op.getOperand(1), Depth + 1) &&
2890 SignBitIsZeroFP(Op.getOperand(0), Depth + 1);
2891 case ISD::FMAXNUM:
2892 case ISD::FMAXNUM_IEEE:
2893 case ISD::FMAXIMUM:
2894 case ISD::FMAXIMUMNUM:
2895 // TODO: If we can ignore the sign bit of nans, only one side being known 0
2896 // is sufficient.
2897 return SignBitIsZeroFP(Op.getOperand(1), Depth + 1) &&
2898 SignBitIsZeroFP(Op.getOperand(0), Depth + 1);
2899 default:
2900 return false;
2901 }
2902
2903 llvm_unreachable("covered opcode switch");
2904}
2905
2906/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
2907/// this predicate to simplify operations downstream. Mask is known to be zero
2908/// for bits that V cannot have.
2910 unsigned Depth) const {
2911 return Mask.isSubsetOf(computeKnownBits(V, Depth).Zero);
2912}
2913
2914/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero in
2915/// DemandedElts. We use this predicate to simplify operations downstream.
2916/// Mask is known to be zero for bits that V cannot have.
2918 const APInt &DemandedElts,
2919 unsigned Depth) const {
2920 return Mask.isSubsetOf(computeKnownBits(V, DemandedElts, Depth).Zero);
2921}
2922
2923/// MaskedVectorIsZero - Return true if 'Op' is known to be zero in
2924/// DemandedElts. We use this predicate to simplify operations downstream.
2926 unsigned Depth /* = 0 */) const {
2927 return computeKnownBits(V, DemandedElts, Depth).isZero();
2928}
2929
2930/// MaskedValueIsAllOnes - Return true if '(Op & Mask) == Mask'.
2932 unsigned Depth) const {
2933 return Mask.isSubsetOf(computeKnownBits(V, Depth).One);
2934}
2935
2937 const APInt &DemandedElts,
2938 unsigned Depth) const {
2939 EVT VT = Op.getValueType();
2940 assert(VT.isVector() && !VT.isScalableVector() && "Only for fixed vectors!");
2941
2942 unsigned NumElts = VT.getVectorNumElements();
2943 assert(DemandedElts.getBitWidth() == NumElts && "Unexpected demanded mask.");
2944
2945 APInt KnownZeroElements = APInt::getZero(NumElts);
2946 for (unsigned EltIdx = 0; EltIdx != NumElts; ++EltIdx) {
2947 if (!DemandedElts[EltIdx])
2948 continue; // Don't query elements that are not demanded.
2949 APInt Mask = APInt::getOneBitSet(NumElts, EltIdx);
2950 if (MaskedVectorIsZero(Op, Mask, Depth))
2951 KnownZeroElements.setBit(EltIdx);
2952 }
2953 return KnownZeroElements;
2954}
2955
2956/// isSplatValue - Return true if the vector V has the same value
2957/// across all DemandedElts. For scalable vectors, we don't know the
2958/// number of lanes at compile time. Instead, we use a 1 bit APInt
2959/// to represent a conservative value for all lanes; that is, that
2960/// one bit value is implicitly splatted across all lanes.
2961bool SelectionDAG::isSplatValue(SDValue V, const APInt &DemandedElts,
2962 APInt &UndefElts, unsigned Depth) const {
2963 unsigned Opcode = V.getOpcode();
2964 EVT VT = V.getValueType();
2965 assert(VT.isVector() && "Vector type expected");
2966 assert((!VT.isScalableVector() || DemandedElts.getBitWidth() == 1) &&
2967 "scalable demanded bits are ignored");
2968
2969 if (!DemandedElts)
2970 return false; // No demanded elts, better to assume we don't know anything.
2971
2972 if (Depth >= MaxRecursionDepth)
2973 return false; // Limit search depth.
2974
2975 // Deal with some common cases here that work for both fixed and scalable
2976 // vector types.
2977 switch (Opcode) {
2978 case ISD::SPLAT_VECTOR:
2979 UndefElts = V.getOperand(0).isUndef()
2980 ? APInt::getAllOnes(DemandedElts.getBitWidth())
2981 : APInt(DemandedElts.getBitWidth(), 0);
2982 return true;
2983 case ISD::ADD:
2984 case ISD::SUB:
2985 case ISD::AND:
2986 case ISD::XOR:
2987 case ISD::OR: {
2988 APInt UndefLHS, UndefRHS;
2989 SDValue LHS = V.getOperand(0);
2990 SDValue RHS = V.getOperand(1);
2991 // Only recognize splats with the same demanded undef elements for both
2992 // operands, otherwise we might fail to handle binop-specific undef
2993 // handling.
2994 // e.g. (and undef, 0) -> 0 etc.
2995 if (isSplatValue(LHS, DemandedElts, UndefLHS, Depth + 1) &&
2996 isSplatValue(RHS, DemandedElts, UndefRHS, Depth + 1) &&
2997 (DemandedElts & UndefLHS) == (DemandedElts & UndefRHS)) {
2998 UndefElts = UndefLHS | UndefRHS;
2999 return true;
3000 }
3001 return false;
3002 }
3003 case ISD::ABS:
3005 case ISD::TRUNCATE:
3006 case ISD::SIGN_EXTEND:
3007 case ISD::ZERO_EXTEND:
3008 return isSplatValue(V.getOperand(0), DemandedElts, UndefElts, Depth + 1);
3009 default:
3010 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
3011 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID)
3012 return TLI->isSplatValueForTargetNode(V, DemandedElts, UndefElts, *this,
3013 Depth);
3014 break;
3015 }
3016
3017 // We don't support other cases than those above for scalable vectors at
3018 // the moment.
3019 if (VT.isScalableVector())
3020 return false;
3021
3022 unsigned NumElts = VT.getVectorNumElements();
3023 assert(NumElts == DemandedElts.getBitWidth() && "Vector size mismatch");
3024 UndefElts = APInt::getZero(NumElts);
3025
3026 switch (Opcode) {
3027 case ISD::BUILD_VECTOR: {
3028 SDValue Scl;
3029 for (unsigned i = 0; i != NumElts; ++i) {
3030 SDValue Op = V.getOperand(i);
3031 if (Op.isUndef()) {
3032 UndefElts.setBit(i);
3033 continue;
3034 }
3035 if (!DemandedElts[i])
3036 continue;
3037 if (Scl && Scl != Op)
3038 return false;
3039 Scl = Op;
3040 }
3041 return true;
3042 }
3043 case ISD::VECTOR_SHUFFLE: {
3044 // Check if this is a shuffle node doing a splat or a shuffle of a splat.
3045 APInt DemandedLHS = APInt::getZero(NumElts);
3046 APInt DemandedRHS = APInt::getZero(NumElts);
3047 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(V)->getMask();
3048 for (int i = 0; i != (int)NumElts; ++i) {
3049 int M = Mask[i];
3050 if (M < 0) {
3051 UndefElts.setBit(i);
3052 continue;
3053 }
3054 if (!DemandedElts[i])
3055 continue;
3056 if (M < (int)NumElts)
3057 DemandedLHS.setBit(M);
3058 else
3059 DemandedRHS.setBit(M - NumElts);
3060 }
3061
3062 // If we aren't demanding either op, assume there's no splat.
3063 // If we are demanding both ops, assume there's no splat.
3064 if ((DemandedLHS.isZero() && DemandedRHS.isZero()) ||
3065 (!DemandedLHS.isZero() && !DemandedRHS.isZero()))
3066 return false;
3067
3068 // See if the demanded elts of the source op is a splat or we only demand
3069 // one element, which should always be a splat.
3070 // TODO: Handle source ops splats with undefs.
3071 auto CheckSplatSrc = [&](SDValue Src, const APInt &SrcElts) {
3072 APInt SrcUndefs;
3073 return (SrcElts.popcount() == 1) ||
3074 (isSplatValue(Src, SrcElts, SrcUndefs, Depth + 1) &&
3075 (SrcElts & SrcUndefs).isZero());
3076 };
3077 if (!DemandedLHS.isZero())
3078 return CheckSplatSrc(V.getOperand(0), DemandedLHS);
3079 return CheckSplatSrc(V.getOperand(1), DemandedRHS);
3080 }
3082 // Offset the demanded elts by the subvector index.
3083 SDValue Src = V.getOperand(0);
3084 // We don't support scalable vectors at the moment.
3085 if (Src.getValueType().isScalableVector())
3086 return false;
3087 uint64_t Idx = V.getConstantOperandVal(1);
3088 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
3089 APInt UndefSrcElts;
3090 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
3091 if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) {
3092 UndefElts = UndefSrcElts.extractBits(NumElts, Idx);
3093 return true;
3094 }
3095 break;
3096 }
3100 // Widen the demanded elts by the src element count.
3101 SDValue Src = V.getOperand(0);
3102 // We don't support scalable vectors at the moment.
3103 if (Src.getValueType().isScalableVector())
3104 return false;
3105 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
3106 APInt UndefSrcElts;
3107 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts);
3108 if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) {
3109 UndefElts = UndefSrcElts.trunc(NumElts);
3110 return true;
3111 }
3112 break;
3113 }
3114 case ISD::BITCAST: {
3115 SDValue Src = V.getOperand(0);
3116 EVT SrcVT = Src.getValueType();
3117 unsigned SrcBitWidth = SrcVT.getScalarSizeInBits();
3118 unsigned BitWidth = VT.getScalarSizeInBits();
3119
3120 // Ignore bitcasts from unsupported types.
3121 // TODO: Add fp support?
3122 if (!SrcVT.isVector() || !SrcVT.isInteger() || !VT.isInteger())
3123 break;
3124
3125 // Bitcast 'small element' vector to 'large element' vector.
3126 if ((BitWidth % SrcBitWidth) == 0) {
3127 // See if each sub element is a splat.
3128 unsigned Scale = BitWidth / SrcBitWidth;
3129 unsigned NumSrcElts = SrcVT.getVectorNumElements();
3130 APInt ScaledDemandedElts =
3131 APIntOps::ScaleBitMask(DemandedElts, NumSrcElts);
3132 for (unsigned I = 0; I != Scale; ++I) {
3133 APInt SubUndefElts;
3134 APInt SubDemandedElt = APInt::getOneBitSet(Scale, I);
3135 APInt SubDemandedElts = APInt::getSplat(NumSrcElts, SubDemandedElt);
3136 SubDemandedElts &= ScaledDemandedElts;
3137 if (!isSplatValue(Src, SubDemandedElts, SubUndefElts, Depth + 1))
3138 return false;
3139 // TODO: Add support for merging sub undef elements.
3140 if (!SubUndefElts.isZero())
3141 return false;
3142 }
3143 return true;
3144 }
3145 break;
3146 }
3147 }
3148
3149 return false;
3150}
3151
3152/// Helper wrapper to main isSplatValue function.
3153bool SelectionDAG::isSplatValue(SDValue V, bool AllowUndefs) const {
3154 EVT VT = V.getValueType();
3155 assert(VT.isVector() && "Vector type expected");
3156
3157 APInt UndefElts;
3158 // Since the number of lanes in a scalable vector is unknown at compile time,
3159 // we track one bit which is implicitly broadcast to all lanes. This means
3160 // that all lanes in a scalable vector are considered demanded.
3161 APInt DemandedElts
3163 return isSplatValue(V, DemandedElts, UndefElts) &&
3164 (AllowUndefs || !UndefElts);
3165}
3166
3169
3170 EVT VT = V.getValueType();
3171 unsigned Opcode = V.getOpcode();
3172 switch (Opcode) {
3173 default: {
3174 APInt UndefElts;
3175 // Since the number of lanes in a scalable vector is unknown at compile time,
3176 // we track one bit which is implicitly broadcast to all lanes. This means
3177 // that all lanes in a scalable vector are considered demanded.
3178 APInt DemandedElts
3180
3181 if (isSplatValue(V, DemandedElts, UndefElts)) {
3182 if (VT.isScalableVector()) {
3183 // DemandedElts and UndefElts are ignored for scalable vectors, since
3184 // the only supported cases are SPLAT_VECTOR nodes.
3185 SplatIdx = 0;
3186 } else {
3187 // Handle case where all demanded elements are UNDEF.
3188 if (DemandedElts.isSubsetOf(UndefElts)) {
3189 SplatIdx = 0;
3190 return getUNDEF(VT);
3191 }
3192 SplatIdx = (UndefElts & DemandedElts).countr_one();
3193 }
3194 return V;
3195 }
3196 break;
3197 }
3198 case ISD::SPLAT_VECTOR:
3199 SplatIdx = 0;
3200 return V;
3201 case ISD::VECTOR_SHUFFLE: {
3202 assert(!VT.isScalableVector());
3203 // Check if this is a shuffle node doing a splat.
3204 // TODO - remove this and rely purely on SelectionDAG::isSplatValue,
3205 // getTargetVShiftNode currently struggles without the splat source.
3206 auto *SVN = cast<ShuffleVectorSDNode>(V);
3207 if (!SVN->isSplat())
3208 break;
3209 int Idx = SVN->getSplatIndex();
3210 int NumElts = V.getValueType().getVectorNumElements();
3211 SplatIdx = Idx % NumElts;
3212 return V.getOperand(Idx / NumElts);
3213 }
3214 }
3215
3216 return SDValue();
3217}
3218
3220 int SplatIdx;
3221 if (SDValue SrcVector = getSplatSourceVector(V, SplatIdx)) {
3222 EVT SVT = SrcVector.getValueType().getScalarType();
3223 EVT LegalSVT = SVT;
3224 if (LegalTypes && !TLI->isTypeLegal(SVT)) {
3225 if (!SVT.isInteger())
3226 return SDValue();
3227 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
3228 if (LegalSVT.bitsLT(SVT))
3229 return SDValue();
3230 }
3231 return getExtractVectorElt(SDLoc(V), LegalSVT, SrcVector, SplatIdx);
3232 }
3233 return SDValue();
3234}
3235
3236std::optional<ConstantRange>
3238 unsigned Depth) const {
3239 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
3240 V.getOpcode() == ISD::SRA) &&
3241 "Unknown shift node");
3242 // Shifting more than the bitwidth is not valid.
3243 unsigned BitWidth = V.getScalarValueSizeInBits();
3244
3245 if (auto *Cst = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
3246 const APInt &ShAmt = Cst->getAPIntValue();
3247 if (ShAmt.uge(BitWidth))
3248 return std::nullopt;
3249 return ConstantRange(ShAmt);
3250 }
3251
3252 if (auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1))) {
3253 const APInt *MinAmt = nullptr, *MaxAmt = nullptr;
3254 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
3255 if (!DemandedElts[i])
3256 continue;
3257 auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i));
3258 if (!SA) {
3259 MinAmt = MaxAmt = nullptr;
3260 break;
3261 }
3262 const APInt &ShAmt = SA->getAPIntValue();
3263 if (ShAmt.uge(BitWidth))
3264 return std::nullopt;
3265 if (!MinAmt || MinAmt->ugt(ShAmt))
3266 MinAmt = &ShAmt;
3267 if (!MaxAmt || MaxAmt->ult(ShAmt))
3268 MaxAmt = &ShAmt;
3269 }
3270 assert(((!MinAmt && !MaxAmt) || (MinAmt && MaxAmt)) &&
3271 "Failed to find matching min/max shift amounts");
3272 if (MinAmt && MaxAmt)
3273 return ConstantRange(*MinAmt, *MaxAmt + 1);
3274 }
3275
3276 // Use computeKnownBits to find a hidden constant/knownbits (usually type
3277 // legalized). e.g. Hidden behind multiple bitcasts/build_vector/casts etc.
3278 KnownBits KnownAmt = computeKnownBits(V.getOperand(1), DemandedElts, Depth);
3279 if (KnownAmt.getMaxValue().ult(BitWidth))
3280 return ConstantRange::fromKnownBits(KnownAmt, /*IsSigned=*/false);
3281
3282 return std::nullopt;
3283}
3284
3285std::optional<unsigned>
3287 unsigned Depth) const {
3288 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
3289 V.getOpcode() == ISD::SRA) &&
3290 "Unknown shift node");
3291 if (std::optional<ConstantRange> AmtRange =
3292 getValidShiftAmountRange(V, DemandedElts, Depth))
3293 if (const APInt *ShAmt = AmtRange->getSingleElement())
3294 return ShAmt->getZExtValue();
3295 return std::nullopt;
3296}
3297
3298std::optional<unsigned>
3300 APInt DemandedElts = getDemandAllEltsMask(V);
3301 return getValidShiftAmount(V, DemandedElts, Depth);
3302}
3303
3304std::optional<unsigned>
3306 unsigned Depth) const {
3307 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
3308 V.getOpcode() == ISD::SRA) &&
3309 "Unknown shift node");
3310 if (std::optional<ConstantRange> AmtRange =
3311 getValidShiftAmountRange(V, DemandedElts, Depth))
3312 return AmtRange->getUnsignedMin().getZExtValue();
3313 return std::nullopt;
3314}
3315
3316std::optional<unsigned>
3318 APInt DemandedElts = getDemandAllEltsMask(V);
3319 return getValidMinimumShiftAmount(V, DemandedElts, Depth);
3320}
3321
3322std::optional<unsigned>
3324 unsigned Depth) const {
3325 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
3326 V.getOpcode() == ISD::SRA) &&
3327 "Unknown shift node");
3328 if (std::optional<ConstantRange> AmtRange =
3329 getValidShiftAmountRange(V, DemandedElts, Depth))
3330 return AmtRange->getUnsignedMax().getZExtValue();
3331 return std::nullopt;
3332}
3333
3334std::optional<unsigned>
3336 APInt DemandedElts = getDemandAllEltsMask(V);
3337 return getValidMaximumShiftAmount(V, DemandedElts, Depth);
3338}
3339
3340/// Determine which bits of Op are known to be either zero or one and return
3341/// them in Known. For vectors, the known bits are those that are shared by
3342/// every vector element.
3344 APInt DemandedElts = getDemandAllEltsMask(Op);
3345 return computeKnownBits(Op, DemandedElts, Depth);
3346}
3347
3348/// Determine which bits of Op are known to be either zero or one and return
3349/// them in Known. The DemandedElts argument allows us to only collect the known
3350/// bits that are shared by the requested vector elements.
3352 unsigned Depth) const {
3353 unsigned BitWidth = Op.getScalarValueSizeInBits();
3354
3355 KnownBits Known(BitWidth); // Don't know anything.
3356
3357 if (auto OptAPInt = Op->bitcastToAPInt()) {
3358 // We know all of the bits for a constant!
3359 APInt V = *std::move(OptAPInt);
3360
3361 // Swap the low-order and high-order double of a ppc_fp128 when casting to
3362 // i128, see #44482.
3363 //
3364 // A ppc_fp128 is two doubles, with the high-order double stored at the
3365 // lower address. Reading that as an integer therefore puts the high-order
3366 // double in the high 64 bits on big-endian targets and in the low 64 bits
3367 // on little-endian targets.
3368 //
3369 // But APFloat::bitcastToAPInt is endianness-agnostic and always places the
3370 // high-order double in the low 64 bits. Hence the two doubles must be
3371 // flipped on big-endian targets.
3372 if (getDataLayout().isBigEndian() && Op.getValueType() == MVT::ppcf128)
3373 V = V.rotl(64);
3374
3375 return KnownBits::makeConstant(V);
3376 }
3377
3378 if (Depth >= MaxRecursionDepth)
3379 return Known; // Limit search depth.
3380
3381 KnownBits Known2;
3382 unsigned NumElts = DemandedElts.getBitWidth();
3383 assert((!Op.getValueType().isScalableVector() || NumElts == 1) &&
3384 "DemandedElts for scalable vectors must be 1 to represent all lanes");
3385 assert((!Op.getValueType().isFixedLengthVector() ||
3386 NumElts == Op.getValueType().getVectorNumElements()) &&
3387 "Unexpected vector size");
3388
3389 if (!DemandedElts)
3390 return Known; // No demanded elts, better to assume we don't know anything.
3391
3392 unsigned Opcode = Op.getOpcode();
3393 switch (Opcode) {
3394 case ISD::FREEZE: {
3395 if (isGuaranteedNotToBeUndefOrPoison(Op.getOperand(0), DemandedElts,
3397 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3398 break;
3399 }
3400 case ISD::MERGE_VALUES:
3401 return computeKnownBits(Op.getOperand(Op.getResNo()), DemandedElts,
3402 Depth + 1);
3403 case ISD::SPLAT_VECTOR: {
3404 SDValue SrcOp = Op.getOperand(0);
3405 assert(SrcOp.getValueSizeInBits() >= BitWidth &&
3406 "Expected SPLAT_VECTOR implicit truncation");
3407 // Implicitly truncate the bits to match the official semantics of
3408 // SPLAT_VECTOR.
3410 break;
3411 }
3413 unsigned ScalarSize = Op.getOperand(0).getScalarValueSizeInBits();
3414 assert(ScalarSize * Op.getNumOperands() == BitWidth &&
3415 "Expected SPLAT_VECTOR_PARTS scalars to cover element width");
3416 for (auto [I, SrcOp] : enumerate(Op->ops())) {
3417 Known.insertBits(computeKnownBits(SrcOp, Depth + 1), ScalarSize * I);
3418 }
3419 break;
3420 }
3421 case ISD::STEP_VECTOR: {
3422 const APInt &Step = Op.getConstantOperandAPInt(0);
3423
3424 if (Step.isPowerOf2())
3425 Known.Zero.setLowBits(Step.logBase2());
3426
3428
3429 if (!isUIntN(BitWidth, Op.getValueType().getVectorMinNumElements()))
3430 break;
3431 const APInt MinNumElts =
3432 APInt(BitWidth, Op.getValueType().getVectorMinNumElements());
3433
3434 bool Overflow;
3435 const APInt MaxNumElts = getVScaleRange(&F, BitWidth)
3437 .umul_ov(MinNumElts, Overflow);
3438 if (Overflow)
3439 break;
3440
3441 const APInt MaxValue = (MaxNumElts - 1).umul_ov(Step, Overflow);
3442 if (Overflow)
3443 break;
3444
3445 Known.Zero.setHighBits(MaxValue.countl_zero());
3446 break;
3447 }
3448 case ISD::BUILD_VECTOR:
3449 assert(!Op.getValueType().isScalableVector());
3450 // Collect the known bits that are shared by every demanded vector element.
3451 Known.setAllConflict();
3452 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
3453 if (!DemandedElts[i])
3454 continue;
3455
3456 SDValue SrcOp = Op.getOperand(i);
3457 if (SrcOp.getOpcode() == ISD::POISON)
3458 continue;
3459
3460 Known2 = computeKnownBits(SrcOp, Depth + 1);
3461
3462 // BUILD_VECTOR can implicitly truncate sources, we must handle this.
3463 if (SrcOp.getValueSizeInBits() != BitWidth) {
3464 assert(SrcOp.getValueSizeInBits() > BitWidth &&
3465 "Expected BUILD_VECTOR implicit truncation");
3466 Known2 = Known2.trunc(BitWidth);
3467 }
3468
3469 // Known bits are the values that are shared by every demanded element.
3470 Known = Known.intersectWith(Known2);
3471
3472 // If we don't know any bits, early out.
3473 if (Known.isUnknown())
3474 break;
3475 }
3476
3477 // If every demanded element was poison, we know nothing.
3478 if (Known.hasConflict())
3479 Known.resetAll();
3480 break;
3481 case ISD::VECTOR_COMPRESS: {
3482 SDValue Vec = Op.getOperand(0);
3483 SDValue PassThru = Op.getOperand(2);
3484 Known = computeKnownBits(PassThru, DemandedElts, Depth + 1);
3485 // If we don't know any bits, early out.
3486 if (Known.isUnknown())
3487 break;
3488 Known2 = computeKnownBits(Vec, Depth + 1);
3489 Known = Known.intersectWith(Known2);
3490 break;
3491 }
3492 case ISD::VECTOR_SHUFFLE: {
3493 assert(!Op.getValueType().isScalableVector());
3494 // Collect the known bits that are shared by every vector element referenced
3495 // by the shuffle.
3496 APInt DemandedLHS, DemandedRHS;
3498 assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
3499 if (!getShuffleDemandedElts(NumElts, SVN->getMask(), DemandedElts,
3500 DemandedLHS, DemandedRHS))
3501 break;
3502
3503 // Known bits are the values that are shared by every demanded element.
3504 Known.setAllConflict();
3505 if (!!DemandedLHS) {
3506 SDValue LHS = Op.getOperand(0);
3507 Known2 = computeKnownBits(LHS, DemandedLHS, Depth + 1);
3508 Known = Known.intersectWith(Known2);
3509 }
3510 // If we don't know any bits, early out.
3511 if (Known.isUnknown())
3512 break;
3513 if (!!DemandedRHS) {
3514 SDValue RHS = Op.getOperand(1);
3515 Known2 = computeKnownBits(RHS, DemandedRHS, Depth + 1);
3516 Known = Known.intersectWith(Known2);
3517 }
3518 break;
3519 }
3520 case ISD::VSCALE: {
3522 const APInt &Multiplier = Op.getConstantOperandAPInt(0);
3524 break;
3525 }
3526 case ISD::CONCAT_VECTORS: {
3527 if (Op.getValueType().isScalableVector())
3528 break;
3529 // Split DemandedElts and test each of the demanded subvectors.
3530 Known.setAllConflict();
3531 EVT SubVectorVT = Op.getOperand(0).getValueType();
3532 unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
3533 unsigned NumSubVectors = Op.getNumOperands();
3534 for (unsigned i = 0; i != NumSubVectors; ++i) {
3535 APInt DemandedSub =
3536 DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts);
3537 if (!!DemandedSub) {
3538 SDValue Sub = Op.getOperand(i);
3539 Known2 = computeKnownBits(Sub, DemandedSub, Depth + 1);
3540 Known = Known.intersectWith(Known2);
3541 }
3542 // If we don't know any bits, early out.
3543 if (Known.isUnknown())
3544 break;
3545 }
3546 break;
3547 }
3548 case ISD::INSERT_SUBVECTOR: {
3549 if (Op.getValueType().isScalableVector())
3550 break;
3551 // Demand any elements from the subvector and the remainder from the src its
3552 // inserted into.
3553 SDValue Src = Op.getOperand(0);
3554 SDValue Sub = Op.getOperand(1);
3555 uint64_t Idx = Op.getConstantOperandVal(2);
3556 unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
3557 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
3558 APInt DemandedSrcElts = DemandedElts;
3559 DemandedSrcElts.clearBits(Idx, Idx + NumSubElts);
3560
3561 Known.setAllConflict();
3562 if (!!DemandedSubElts) {
3563 Known = computeKnownBits(Sub, DemandedSubElts, Depth + 1);
3564 if (Known.isUnknown())
3565 break; // early-out.
3566 }
3567 if (!!DemandedSrcElts) {
3568 Known2 = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
3569 Known = Known.intersectWith(Known2);
3570 }
3571 break;
3572 }
3574 // Offset the demanded elts by the subvector index.
3575 SDValue Src = Op.getOperand(0);
3576
3577 APInt DemandedSrcElts;
3578 if (Src.getValueType().isScalableVector())
3579 DemandedSrcElts = APInt(1, 1); // <=> 'demand all elements'
3580 else {
3581 uint64_t Idx = Op.getConstantOperandVal(1);
3582 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
3583 DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
3584 }
3585 Known = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
3586 break;
3587 }
3588 case ISD::SCALAR_TO_VECTOR: {
3589 if (Op.getValueType().isScalableVector())
3590 break;
3591 // We know about scalar_to_vector as much as we know about it source,
3592 // which becomes the first element of otherwise unknown vector.
3593 if (DemandedElts != 1)
3594 break;
3595
3596 SDValue N0 = Op.getOperand(0);
3597 Known = computeKnownBits(N0, Depth + 1);
3598 if (N0.getValueSizeInBits() != BitWidth)
3599 Known = Known.trunc(BitWidth);
3600
3601 break;
3602 }
3603 case ISD::BITCAST: {
3604 if (Op.getValueType().isScalableVector())
3605 break;
3606
3607 SDValue N0 = Op.getOperand(0);
3608 EVT SubVT = N0.getValueType();
3609 unsigned SubBitWidth = SubVT.getScalarSizeInBits();
3610
3611 // Ignore bitcasts from unsupported types.
3612 if (!(SubVT.isInteger() || SubVT.isFloatingPoint()))
3613 break;
3614
3615 // Fast handling of 'identity' bitcasts.
3616 if (BitWidth == SubBitWidth) {
3617 Known = computeKnownBits(N0, DemandedElts, Depth + 1);
3618 break;
3619 }
3620
3621 bool IsLE = getDataLayout().isLittleEndian();
3622
3623 // Bitcast 'small element' vector to 'large element' scalar/vector.
3624 if ((BitWidth % SubBitWidth) == 0) {
3625 assert(N0.getValueType().isVector() && "Expected bitcast from vector");
3626
3627 // Collect known bits for the (larger) output by collecting the known
3628 // bits from each set of sub elements and shift these into place.
3629 // We need to separately call computeKnownBits for each set of
3630 // sub elements as the knownbits for each is likely to be different.
3631 unsigned SubScale = BitWidth / SubBitWidth;
3632 APInt SubDemandedElts(NumElts * SubScale, 0);
3633 for (unsigned i = 0; i != NumElts; ++i)
3634 if (DemandedElts[i])
3635 SubDemandedElts.setBit(i * SubScale);
3636
3637 for (unsigned i = 0; i != SubScale; ++i) {
3638 Known2 = computeKnownBits(N0, SubDemandedElts.shl(i),
3639 Depth + 1);
3640 unsigned Shifts = IsLE ? i : SubScale - 1 - i;
3641 Known.insertBits(Known2, SubBitWidth * Shifts);
3642 }
3643 }
3644
3645 // Bitcast 'large element' scalar/vector to 'small element' vector.
3646 if ((SubBitWidth % BitWidth) == 0) {
3647 assert(Op.getValueType().isVector() && "Expected bitcast to vector");
3648
3649 // Collect known bits for the (smaller) output by collecting the known
3650 // bits from the overlapping larger input elements and extracting the
3651 // sub sections we actually care about.
3652 unsigned SubScale = SubBitWidth / BitWidth;
3653 APInt SubDemandedElts =
3654 APIntOps::ScaleBitMask(DemandedElts, NumElts / SubScale);
3655 Known2 = computeKnownBits(N0, SubDemandedElts, Depth + 1);
3656
3657 Known.setAllConflict();
3658 for (unsigned i = 0; i != NumElts; ++i)
3659 if (DemandedElts[i]) {
3660 unsigned Shifts = IsLE ? i : NumElts - 1 - i;
3661 unsigned Offset = (Shifts % SubScale) * BitWidth;
3662 Known = Known.intersectWith(Known2.extractBits(BitWidth, Offset));
3663 // If we don't know any bits, early out.
3664 if (Known.isUnknown())
3665 break;
3666 }
3667 }
3668 break;
3669 }
3670 case ISD::AND:
3671 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3672 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3673
3674 Known &= Known2;
3675 break;
3676 case ISD::OR:
3677 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3678 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3679
3680 Known |= Known2;
3681 break;
3682 case ISD::XOR:
3683 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3684 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3685
3686 Known ^= Known2;
3687 break;
3688 case ISD::MUL: {
3689 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3690 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3691 bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1);
3692 // TODO: SelfMultiply can be poison, but not undef.
3693 if (SelfMultiply)
3694 SelfMultiply &= isGuaranteedNotToBeUndefOrPoison(
3695 Op.getOperand(0), DemandedElts, UndefPoisonKind::UndefOrPoison,
3696 Depth + 1);
3697 Known = KnownBits::mul(Known, Known2, SelfMultiply);
3698
3699 // If the multiplication is known not to overflow, the product of a number
3700 // with itself is non-negative. Only do this if we didn't already computed
3701 // the opposite value for the sign bit.
3702 if (Op->getFlags().hasNoSignedWrap() &&
3703 Op.getOperand(0) == Op.getOperand(1) &&
3704 !Known.isNegative())
3705 Known.makeNonNegative();
3706 break;
3707 }
3708 case ISD::MULHU: {
3709 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3710 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3711 Known = KnownBits::mulhu(Known, Known2);
3712 break;
3713 }
3714 case ISD::MULHS: {
3715 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3716 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3717 Known = KnownBits::mulhs(Known, Known2);
3718 break;
3719 }
3720 case ISD::ABDU: {
3721 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3722 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3723 Known = KnownBits::abdu(Known, Known2);
3724 break;
3725 }
3726 case ISD::ABDS: {
3727 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3728 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3729 Known = KnownBits::abds(Known, Known2);
3730 unsigned SignBits1 =
3731 ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
3732 if (SignBits1 == 1)
3733 break;
3734 unsigned SignBits0 =
3735 ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3736 Known.Zero.setHighBits(std::min(SignBits0, SignBits1) - 1);
3737 break;
3738 }
3739 case ISD::UMUL_LOHI: {
3740 assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3741 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3742 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3743 bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1);
3744 if (Op.getResNo() == 0)
3745 Known = KnownBits::mul(Known, Known2, SelfMultiply);
3746 else
3747 Known = KnownBits::mulhu(Known, Known2);
3748 break;
3749 }
3750 case ISD::SMUL_LOHI: {
3751 assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3752 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3753 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3754 bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1);
3755 if (Op.getResNo() == 0)
3756 Known = KnownBits::mul(Known, Known2, SelfMultiply);
3757 else
3758 Known = KnownBits::mulhs(Known, Known2);
3759 break;
3760 }
3761 case ISD::AVGFLOORU: {
3762 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3763 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3764 Known = KnownBits::avgFloorU(Known, Known2);
3765 break;
3766 }
3767 case ISD::AVGCEILU: {
3768 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3769 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3770 Known = KnownBits::avgCeilU(Known, Known2);
3771 break;
3772 }
3773 case ISD::AVGFLOORS: {
3774 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3775 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3776 Known = KnownBits::avgFloorS(Known, Known2);
3777 break;
3778 }
3779 case ISD::AVGCEILS: {
3780 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3781 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3782 Known = KnownBits::avgCeilS(Known, Known2);
3783 break;
3784 }
3785 case ISD::AVGSUBFLOORU:
3786 case ISD::AVGSUBFLOORS: {
3787 bool IsSigned = Op.getOpcode() == ISD::AVGSUBFLOORS;
3788 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3789 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3790 // Subtract in i[N+1] so the difference can't overflow, then halve.
3791 Known = IsSigned ? Known.sext(BitWidth + 1) : Known.zext(BitWidth + 1);
3792 Known2 = IsSigned ? Known2.sext(BitWidth + 1) : Known2.zext(BitWidth + 1);
3793 Known = KnownBits::sub(Known, Known2);
3794 // The shifted in top bit is unknown, but it is truncated away.
3795 Known >>= 1;
3796 Known = Known.trunc(BitWidth);
3797 break;
3798 }
3799 case ISD::SELECT:
3800 case ISD::VSELECT:
3801 Known = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
3802 // If we don't know any bits, early out.
3803 if (Known.isUnknown())
3804 break;
3805 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth+1);
3806
3807 // Only known if known in both the LHS and RHS.
3808 Known = Known.intersectWith(Known2);
3809 break;
3810 case ISD::SELECT_CC:
3811 Known = computeKnownBits(Op.getOperand(3), DemandedElts, Depth+1);
3812 // If we don't know any bits, early out.
3813 if (Known.isUnknown())
3814 break;
3815 Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
3816
3817 // Only known if known in both the LHS and RHS.
3818 Known = Known.intersectWith(Known2);
3819 break;
3820 case ISD::SMULO:
3821 case ISD::UMULO:
3822 if (Op.getResNo() != 1)
3823 break;
3824 // The boolean result conforms to getBooleanContents.
3825 // If we know the result of a setcc has the top bits zero, use this info.
3826 // We know that we have an integer-based boolean since these operations
3827 // are only available for integer.
3828 if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
3830 BitWidth > 1)
3831 Known.Zero.setBitsFrom(1);
3832 break;
3833 case ISD::SETCC:
3834 case ISD::SETCCCARRY:
3835 case ISD::STRICT_FSETCC:
3836 case ISD::STRICT_FSETCCS: {
3837 unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
3838 // If we know the result of a setcc has the top bits zero, use this info.
3839 if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
3841 BitWidth > 1)
3842 Known.Zero.setBitsFrom(1);
3843 break;
3844 }
3845 case ISD::SHL: {
3846 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3847 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3848
3849 bool NUW = Op->getFlags().hasNoUnsignedWrap();
3850 bool NSW = Op->getFlags().hasNoSignedWrap();
3851
3852 bool ShAmtNonZero = Known2.isNonZero();
3853
3854 Known = KnownBits::shl(Known, Known2, NUW, NSW, ShAmtNonZero);
3855
3856 // Minimum shift low bits are known zero.
3857 if (std::optional<unsigned> ShMinAmt =
3858 getValidMinimumShiftAmount(Op, DemandedElts, Depth + 1))
3859 Known.Zero.setLowBits(*ShMinAmt);
3860 break;
3861 }
3862 case ISD::SRL:
3863 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3864 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3865 Known = KnownBits::lshr(Known, Known2, /*ShAmtNonZero=*/false,
3866 Op->getFlags().hasExact());
3867
3868 // Minimum shift high bits are known zero.
3869 if (std::optional<unsigned> ShMinAmt =
3870 getValidMinimumShiftAmount(Op, DemandedElts, Depth + 1))
3871 Known.Zero.setHighBits(*ShMinAmt);
3872 break;
3873 case ISD::SRA:
3874 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3875 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3876 Known = KnownBits::ashr(Known, Known2, /*ShAmtNonZero=*/false,
3877 Op->getFlags().hasExact());
3878 break;
3879 case ISD::ROTL:
3880 case ISD::ROTR:
3881 if (ConstantSDNode *C =
3882 isConstOrConstSplat(Op.getOperand(1), DemandedElts)) {
3883 unsigned Amt = C->getAPIntValue().urem(BitWidth);
3884
3885 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3886
3887 // Canonicalize to ROTR.
3888 if (Opcode == ISD::ROTL && Amt != 0)
3889 Amt = BitWidth - Amt;
3890
3891 Known.Zero = Known.Zero.rotr(Amt);
3892 Known.One = Known.One.rotr(Amt);
3893 }
3894 break;
3895 case ISD::FSHL:
3896 case ISD::FSHR:
3897 if (ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(2), DemandedElts)) {
3898 unsigned Amt = C->getAPIntValue().urem(BitWidth);
3899
3900 // For fshl, 0-shift returns the 1st arg.
3901 // For fshr, 0-shift returns the 2nd arg.
3902 if (Amt == 0) {
3903 Known = computeKnownBits(Op.getOperand(Opcode == ISD::FSHL ? 0 : 1),
3904 DemandedElts, Depth + 1);
3905 break;
3906 }
3907
3908 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
3909 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
3910 const APInt ShAmt(BitWidth, Amt);
3911 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3912 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3913 Known = Opcode == ISD::FSHL ? KnownBits::fshl(Known, Known2, ShAmt)
3914 : KnownBits::fshr(Known, Known2, ShAmt);
3915 }
3916 break;
3917 case ISD::SHL_PARTS:
3918 case ISD::SRA_PARTS:
3919 case ISD::SRL_PARTS: {
3920 assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3921
3922 // Collect lo/hi source values and concatenate.
3923 unsigned LoBits = Op.getOperand(0).getScalarValueSizeInBits();
3924 unsigned HiBits = Op.getOperand(1).getScalarValueSizeInBits();
3925 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3926 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3927 Known = Known2.concat(Known);
3928
3929 // Collect shift amount.
3930 Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1);
3931
3932 if (Opcode == ISD::SHL_PARTS)
3933 Known = KnownBits::shl(Known, Known2);
3934 else if (Opcode == ISD::SRA_PARTS)
3935 Known = KnownBits::ashr(Known, Known2);
3936 else // if (Opcode == ISD::SRL_PARTS)
3937 Known = KnownBits::lshr(Known, Known2);
3938
3939 // TODO: Minimum shift low/high bits are known zero.
3940
3941 if (Op.getResNo() == 0)
3942 Known = Known.extractBits(LoBits, 0);
3943 else
3944 Known = Known.extractBits(HiBits, LoBits);
3945 break;
3946 }
3948 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3949 EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3950 Known = Known.sextInReg(EVT.getScalarSizeInBits());
3951 break;
3952 }
3953 case ISD::CTTZ:
3954 case ISD::CTTZ_ZERO_POISON: {
3955 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3956 // If we have a known 1, its position is our upper bound.
3957 unsigned PossibleTZ = Known2.countMaxTrailingZeros();
3958 unsigned LowBits = llvm::bit_width(PossibleTZ);
3959 Known.Zero.setBitsFrom(LowBits);
3960 break;
3961 }
3962 case ISD::CTLZ:
3963 case ISD::CTLZ_ZERO_POISON: {
3964 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3965 Known = Known2.ctlz(/*ZeroIsPoison=*/false).zextOrTrunc(BitWidth);
3966 break;
3967 }
3968 case ISD::CTLS: {
3969 unsigned MinRedundantSignBits =
3970 ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1) - 1;
3971 ConstantRange Range(APInt(BitWidth, MinRedundantSignBits),
3973 Known = Range.toKnownBits();
3974 break;
3975 }
3976 case ISD::CTPOP: {
3977 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3978 // If we know some of the bits are zero, they can't be one.
3979 unsigned PossibleOnes = Known2.countMaxPopulation();
3980 Known.Zero.setBitsFrom(llvm::bit_width(PossibleOnes));
3981 break;
3982 }
3983 case ISD::PARITY: {
3984 // Parity returns 0 everywhere but the LSB.
3985 Known.Zero.setBitsFrom(1);
3986 break;
3987 }
3988 case ISD::PDEP: {
3989 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3990 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3991 Known = KnownBits::pdep(Known2, Known);
3992 break;
3993 }
3994 case ISD::PEXT: {
3995 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3996 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3997 Known = KnownBits::pext(Known2, Known);
3998 break;
3999 }
4000 case ISD::CLMUL: {
4001 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4002 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4003 Known = KnownBits::clmul(Known, Known2);
4004 break;
4005 }
4006 case ISD::MGATHER:
4007 case ISD::MLOAD: {
4008 ISD::LoadExtType ETy =
4009 (Opcode == ISD::MGATHER)
4010 ? cast<MaskedGatherSDNode>(Op)->getExtensionType()
4011 : cast<MaskedLoadSDNode>(Op)->getExtensionType();
4012 if (ETy == ISD::ZEXTLOAD) {
4013 EVT MemVT = cast<MemSDNode>(Op)->getMemoryVT();
4014 KnownBits Known0(MemVT.getScalarSizeInBits());
4015 return Known0.zext(BitWidth);
4016 }
4017 break;
4018 }
4019 case ISD::LOAD: {
4021 const Constant *Cst = TLI->getTargetConstantFromLoad(LD);
4022 if (ISD::isNON_EXTLoad(LD) && Cst) {
4023 // Determine any common known bits from the loaded constant pool value.
4024 Type *CstTy = Cst->getType();
4025 if ((NumElts * BitWidth) == CstTy->getPrimitiveSizeInBits() &&
4026 !Op.getValueType().isScalableVector()) {
4027 // If its a vector splat, then we can (quickly) reuse the scalar path.
4028 // NOTE: We assume all elements match and none are UNDEF.
4029 if (CstTy->isVectorTy()) {
4030 if (const Constant *Splat = Cst->getSplatValue()) {
4031 Cst = Splat;
4032 CstTy = Cst->getType();
4033 }
4034 }
4035 // TODO - do we need to handle different bitwidths?
4036 if (CstTy->isVectorTy() && BitWidth == CstTy->getScalarSizeInBits()) {
4037 // Iterate across all vector elements finding common known bits.
4038 Known.setAllConflict();
4039 for (unsigned i = 0; i != NumElts; ++i) {
4040 if (!DemandedElts[i])
4041 continue;
4042 if (Constant *Elt = Cst->getAggregateElement(i)) {
4043 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
4044 const APInt &Value = CInt->getValue();
4045 Known.One &= Value;
4046 Known.Zero &= ~Value;
4047 continue;
4048 }
4049 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
4050 APInt Value = CFP->getValueAPF().bitcastToAPInt();
4051 Known.One &= Value;
4052 Known.Zero &= ~Value;
4053 continue;
4054 }
4055 }
4056 Known.One.clearAllBits();
4057 Known.Zero.clearAllBits();
4058 break;
4059 }
4060 } else if (BitWidth == CstTy->getPrimitiveSizeInBits()) {
4061 if (auto *CInt = dyn_cast<ConstantInt>(Cst)) {
4062 Known = KnownBits::makeConstant(CInt->getValue());
4063 } else if (auto *CFP = dyn_cast<ConstantFP>(Cst)) {
4064 Known =
4065 KnownBits::makeConstant(CFP->getValueAPF().bitcastToAPInt());
4066 }
4067 }
4068 }
4069 } else if (Op.getResNo() == 0) {
4070 unsigned ScalarMemorySize = LD->getMemoryVT().getScalarSizeInBits();
4071 KnownBits KnownScalarMemory(ScalarMemorySize);
4072 if (const MDNode *MD = LD->getRanges())
4073 computeKnownBitsFromRangeMetadata(*MD, KnownScalarMemory);
4074
4075 // Extend the Known bits from memory to the size of the scalar result.
4076 if (ISD::isZEXTLoad(Op.getNode()))
4077 Known = KnownScalarMemory.zext(BitWidth);
4078 else if (ISD::isSEXTLoad(Op.getNode()))
4079 Known = KnownScalarMemory.sext(BitWidth);
4080 else if (ISD::isEXTLoad(Op.getNode()))
4081 Known = KnownScalarMemory.anyext(BitWidth);
4082 else
4083 Known = KnownScalarMemory;
4084 assert(Known.getBitWidth() == BitWidth);
4085 return Known;
4086 }
4087 break;
4088 }
4090 if (Op.getValueType().isScalableVector())
4091 break;
4092 EVT InVT = Op.getOperand(0).getValueType();
4093 APInt InDemandedElts = DemandedElts.zext(InVT.getVectorNumElements());
4094 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
4095 Known = Known.zext(BitWidth);
4096 break;
4097 }
4098 case ISD::ZERO_EXTEND: {
4099 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4100 Known = Known.zext(BitWidth);
4101 break;
4102 }
4104 if (Op.getValueType().isScalableVector())
4105 break;
4106 EVT InVT = Op.getOperand(0).getValueType();
4107 APInt InDemandedElts = DemandedElts.zext(InVT.getVectorNumElements());
4108 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
4109 // If the sign bit is known to be zero or one, then sext will extend
4110 // it to the top bits, else it will just zext.
4111 Known = Known.sext(BitWidth);
4112 break;
4113 }
4114 case ISD::SIGN_EXTEND: {
4115 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4116 // If the sign bit is known to be zero or one, then sext will extend
4117 // it to the top bits, else it will just zext.
4118 Known = Known.sext(BitWidth);
4119 break;
4120 }
4122 if (Op.getValueType().isScalableVector())
4123 break;
4124 EVT InVT = Op.getOperand(0).getValueType();
4125 APInt InDemandedElts = DemandedElts.zext(InVT.getVectorNumElements());
4126 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
4127 Known = Known.anyext(BitWidth);
4128 break;
4129 }
4130 case ISD::ANY_EXTEND: {
4131 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4132 Known = Known.anyext(BitWidth);
4133 break;
4134 }
4135 case ISD::TRUNCATE: {
4136 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4137 Known = Known.trunc(BitWidth);
4138 break;
4139 }
4140 case ISD::TRUNCATE_SSAT_S: {
4141 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4142 Known = Known.truncSSat(BitWidth);
4143 break;
4144 }
4145 case ISD::TRUNCATE_SSAT_U: {
4146 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4147 Known = Known.truncSSatU(BitWidth);
4148 break;
4149 }
4150 case ISD::TRUNCATE_USAT_U: {
4151 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4152 Known = Known.truncUSat(BitWidth);
4153 break;
4154 }
4155 case ISD::AssertZext: {
4156 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
4158 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4159 Known.Zero |= (~InMask);
4160 Known.One &= (~Known.Zero);
4161 break;
4162 }
4163 case ISD::AssertAlign: {
4164 unsigned LogOfAlign = Log2(cast<AssertAlignSDNode>(Op)->getAlign());
4165 assert(LogOfAlign != 0);
4166
4167 // TODO: Should use maximum with source
4168 // If a node is guaranteed to be aligned, set low zero bits accordingly as
4169 // well as clearing one bits.
4170 Known.Zero.setLowBits(LogOfAlign);
4171 Known.One.clearLowBits(LogOfAlign);
4172 break;
4173 }
4174 case ISD::AssertNoFPClass: {
4175 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4176
4177 FPClassTest NoFPClass =
4178 static_cast<FPClassTest>(Op.getConstantOperandVal(1));
4179 const FPClassTest NegativeTestMask = fcNan | fcNegative;
4180 if ((NoFPClass & NegativeTestMask) == NegativeTestMask) {
4181 // Cannot be negative.
4182 Known.makeNonNegative();
4183 }
4184
4185 const FPClassTest PositiveTestMask = fcNan | fcPositive;
4186 if ((NoFPClass & PositiveTestMask) == PositiveTestMask) {
4187 // Cannot be positive.
4188 Known.makeNegative();
4189 }
4190
4191 break;
4192 }
4193 case ISD::FABS:
4194 // fabs clears the sign bit
4195 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4196 Known.Zero.setSignBit();
4197 Known.One.clearSignBit();
4198 break;
4199 case ISD::FGETSIGN:
4200 // All bits are zero except the low bit.
4201 Known.Zero.setBitsFrom(1);
4202 break;
4203 case ISD::ADD: {
4204 SDNodeFlags Flags = Op.getNode()->getFlags();
4205 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4206 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4207 bool SelfAdd = Op.getOperand(0) == Op.getOperand(1) &&
4209 Op.getOperand(0), DemandedElts,
4211 Known = KnownBits::add(Known, Known2, Flags.hasNoSignedWrap(),
4212 Flags.hasNoUnsignedWrap(), SelfAdd);
4213 break;
4214 }
4215 case ISD::SUB: {
4216 SDNodeFlags Flags = Op.getNode()->getFlags();
4217 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4218 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4219 Known = KnownBits::sub(Known, Known2, Flags.hasNoSignedWrap(),
4220 Flags.hasNoUnsignedWrap());
4221 break;
4222 }
4223 case ISD::USUBO:
4224 case ISD::SSUBO:
4225 case ISD::USUBO_CARRY:
4226 case ISD::SSUBO_CARRY:
4227 if (Op.getResNo() == 1) {
4228 // If we know the result of a setcc has the top bits zero, use this info.
4229 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
4231 BitWidth > 1)
4232 Known.Zero.setBitsFrom(1);
4233 break;
4234 }
4235 [[fallthrough]];
4236 case ISD::SUBC: {
4237 assert(Op.getResNo() == 0 &&
4238 "We only compute knownbits for the difference here.");
4239
4240 // With USUBO_CARRY and SSUBO_CARRY a borrow bit may be added in.
4241 KnownBits Borrow(1);
4242 if (Opcode == ISD::USUBO_CARRY || Opcode == ISD::SSUBO_CARRY) {
4243 Borrow = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1);
4244 // Borrow has bit width 1
4245 Borrow = Borrow.trunc(1);
4246 } else {
4247 Borrow.setAllZero();
4248 }
4249
4250 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4251 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4252 Known = KnownBits::computeForSubBorrow(Known, Known2, Borrow);
4253 break;
4254 }
4255 case ISD::UADDO:
4256 case ISD::SADDO:
4257 case ISD::UADDO_CARRY:
4258 case ISD::SADDO_CARRY:
4259 if (Op.getResNo() == 1) {
4260 // If we know the result of a setcc has the top bits zero, use this info.
4261 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
4263 BitWidth > 1)
4264 Known.Zero.setBitsFrom(1);
4265 break;
4266 }
4267 [[fallthrough]];
4268 case ISD::ADDC:
4269 case ISD::ADDE: {
4270 assert(Op.getResNo() == 0 && "We only compute knownbits for the sum here.");
4271
4272 // With ADDE and UADDO_CARRY, a carry bit may be added in.
4273 KnownBits Carry(1);
4274 if (Opcode == ISD::ADDE)
4275 // Can't track carry from glue, set carry to unknown.
4276 Carry.resetAll();
4277 else if (Opcode == ISD::UADDO_CARRY || Opcode == ISD::SADDO_CARRY) {
4278 Carry = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1);
4279 // Carry has bit width 1
4280 Carry = Carry.trunc(1);
4281 } else {
4282 Carry.setAllZero();
4283 }
4284
4285 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4286 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4287 Known = KnownBits::computeForAddCarry(Known, Known2, Carry);
4288 break;
4289 }
4290 case ISD::UDIV: {
4291 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4292 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4293 Known = KnownBits::udiv(Known, Known2, Op->getFlags().hasExact());
4294 break;
4295 }
4296 case ISD::SDIV: {
4297 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4298 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4299 Known = KnownBits::sdiv(Known, Known2, Op->getFlags().hasExact());
4300 break;
4301 }
4302 case ISD::SREM: {
4303 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4304 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4305 Known = KnownBits::srem(Known, Known2);
4306 break;
4307 }
4308 case ISD::UREM: {
4309 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4310 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4311 Known = KnownBits::urem(Known, Known2);
4312 break;
4313 }
4314 case ISD::EXTRACT_ELEMENT: {
4315 Known = computeKnownBits(Op.getOperand(0), Depth+1);
4316 const unsigned Index = Op.getConstantOperandVal(1);
4317 const unsigned EltBitWidth = Op.getValueSizeInBits();
4318
4319 Known = Known.extractBits(EltBitWidth, Index * EltBitWidth);
4320 break;
4321 }
4323 SDValue InVec = Op.getOperand(0);
4324 SDValue EltNo = Op.getOperand(1);
4325 EVT VecVT = InVec.getValueType();
4326 // computeKnownBits not yet implemented for scalable vectors.
4327 if (VecVT.isScalableVector())
4328 break;
4329 const unsigned EltBitWidth = VecVT.getScalarSizeInBits();
4330 const unsigned NumSrcElts = VecVT.getVectorNumElements();
4331
4332 // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know
4333 // anything about the extended bits.
4334 if (BitWidth > EltBitWidth)
4335 Known = Known.trunc(EltBitWidth);
4336
4337 // If we know the element index, just demand that vector element, else for
4338 // an unknown element index, ignore DemandedElts and demand them all.
4339 APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
4340 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
4341 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
4342 DemandedSrcElts =
4343 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
4344
4345 Known = computeKnownBits(InVec, DemandedSrcElts, Depth + 1);
4346 if (BitWidth > EltBitWidth)
4347 Known = Known.anyext(BitWidth);
4348 break;
4349 }
4350 case ISD::BUILD_PAIR: {
4351 // Operand 0 is the low half and operand 1 the high half,
4352 // KnownBits::concat places its argument in the low bits.
4353 Known = computeKnownBits(Op.getOperand(0), Depth + 1);
4354 Known2 = computeKnownBits(Op.getOperand(1), Depth + 1);
4355 Known = Known2.concat(Known);
4356 break;
4357 }
4359 if (Op.getValueType().isScalableVector())
4360 break;
4361
4362 // If we know the element index, split the demand between the
4363 // source vector and the inserted element, otherwise assume we need
4364 // the original demanded vector elements and the value.
4365 SDValue InVec = Op.getOperand(0);
4366 SDValue InVal = Op.getOperand(1);
4367 SDValue EltNo = Op.getOperand(2);
4368 bool DemandedVal = true;
4369 APInt DemandedVecElts = DemandedElts;
4370 auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
4371 if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
4372 unsigned EltIdx = CEltNo->getZExtValue();
4373 DemandedVal = !!DemandedElts[EltIdx];
4374 DemandedVecElts.clearBit(EltIdx);
4375 }
4376 Known.setAllConflict();
4377 if (DemandedVal) {
4378 Known2 = computeKnownBits(InVal, Depth + 1);
4379 Known = Known.intersectWith(Known2.zextOrTrunc(BitWidth));
4380 }
4381 if (!!DemandedVecElts) {
4382 Known2 = computeKnownBits(InVec, DemandedVecElts, Depth + 1);
4383 Known = Known.intersectWith(Known2);
4384 }
4385 break;
4386 }
4387 case ISD::BITREVERSE: {
4388 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4389 Known = Known2.reverseBits();
4390 break;
4391 }
4392 case ISD::BSWAP: {
4393 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4394 Known = Known2.byteSwap();
4395 break;
4396 }
4397 case ISD::ABS:
4398 case ISD::ABS_MIN_POISON: {
4399 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4400 Known = Known2.abs();
4401 Known.Zero.setHighBits(
4402 ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1) - 1);
4403 break;
4404 }
4405 case ISD::USUBSAT: {
4406 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4407 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4408 Known = KnownBits::usub_sat(Known, Known2);
4409 break;
4410 }
4411 case ISD::UMIN: {
4412 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4413 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4414 Known = KnownBits::umin(Known, Known2);
4415 break;
4416 }
4417 case ISD::UMAX: {
4418 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4419 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4420 Known = KnownBits::umax(Known, Known2);
4421 break;
4422 }
4423 case ISD::SMIN:
4424 case ISD::SMAX: {
4425 // If we have a clamp pattern, we know that the number of sign bits will be
4426 // the minimum of the clamp min/max range.
4427 bool IsMax = (Opcode == ISD::SMAX);
4428 ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
4429 if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
4430 if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
4431 CstHigh =
4432 isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
4433 if (CstLow && CstHigh) {
4434 if (!IsMax)
4435 std::swap(CstLow, CstHigh);
4436
4437 const APInt &ValueLow = CstLow->getAPIntValue();
4438 const APInt &ValueHigh = CstHigh->getAPIntValue();
4439 if (ValueLow.sle(ValueHigh)) {
4440 unsigned LowSignBits = ValueLow.getNumSignBits();
4441 unsigned HighSignBits = ValueHigh.getNumSignBits();
4442 unsigned MinSignBits = std::min(LowSignBits, HighSignBits);
4443 if (ValueLow.isNegative() && ValueHigh.isNegative()) {
4444 Known.One.setHighBits(MinSignBits);
4445 break;
4446 }
4447 if (ValueLow.isNonNegative() && ValueHigh.isNonNegative()) {
4448 Known.Zero.setHighBits(MinSignBits);
4449 break;
4450 }
4451 }
4452 }
4453
4454 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4455 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4456 if (IsMax)
4457 Known = KnownBits::smax(Known, Known2);
4458 else
4459 Known = KnownBits::smin(Known, Known2);
4460
4461 // For SMAX, if CstLow is non-negative we know the result will be
4462 // non-negative and thus all sign bits are 0.
4463 // TODO: There's an equivalent of this for smin with negative constant for
4464 // known ones.
4465 if (IsMax && CstLow) {
4466 const APInt &ValueLow = CstLow->getAPIntValue();
4467 if (ValueLow.isNonNegative()) {
4468 unsigned SignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
4469 Known.Zero.setHighBits(std::min(SignBits, ValueLow.getNumSignBits()));
4470 }
4471 }
4472
4473 break;
4474 }
4475 case ISD::UINT_TO_FP: {
4476 Known.makeNonNegative();
4477 break;
4478 }
4479 case ISD::SINT_TO_FP: {
4480 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4481 if (Known2.isNonNegative())
4482 Known.makeNonNegative();
4483 else if (Known2.isNegative())
4484 Known.makeNegative();
4485 break;
4486 }
4487 case ISD::FP_TO_UINT_SAT: {
4488 // FP_TO_UINT_SAT produces an unsigned value that fits in the saturating VT.
4489 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
4491 break;
4492 }
4493 case ISD::ATOMIC_LOAD: {
4494 // If we are looking at the loaded value.
4495 if (Op.getResNo() == 0) {
4496 auto *AT = cast<AtomicSDNode>(Op);
4497 unsigned ScalarMemorySize = AT->getMemoryVT().getScalarSizeInBits();
4498 KnownBits KnownScalarMemory(ScalarMemorySize);
4499 if (const MDNode *MD = AT->getRanges())
4500 computeKnownBitsFromRangeMetadata(*MD, KnownScalarMemory);
4501
4502 switch (AT->getExtensionType()) {
4503 case ISD::ZEXTLOAD:
4504 Known = KnownScalarMemory.zext(BitWidth);
4505 break;
4506 case ISD::SEXTLOAD:
4507 Known = KnownScalarMemory.sext(BitWidth);
4508 break;
4509 case ISD::EXTLOAD:
4510 switch (TLI->getExtendForAtomicOps()) {
4511 case ISD::ZERO_EXTEND:
4512 Known = KnownScalarMemory.zext(BitWidth);
4513 break;
4514 case ISD::SIGN_EXTEND:
4515 Known = KnownScalarMemory.sext(BitWidth);
4516 break;
4517 default:
4518 Known = KnownScalarMemory.anyext(BitWidth);
4519 break;
4520 }
4521 break;
4522 case ISD::NON_EXTLOAD:
4523 Known = KnownScalarMemory;
4524 break;
4525 }
4526 assert(Known.getBitWidth() == BitWidth);
4527 }
4528 break;
4529 }
4531 if (Op.getResNo() == 1) {
4532 // The boolean result conforms to getBooleanContents.
4533 // If we know the result of a setcc has the top bits zero, use this info.
4534 // We know that we have an integer-based boolean since these operations
4535 // are only available for integer.
4536 if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
4538 BitWidth > 1)
4539 Known.Zero.setBitsFrom(1);
4540 break;
4541 }
4542 [[fallthrough]];
4544 case ISD::ATOMIC_SWAP:
4555 case ISD::ATOMIC_LOAD_UMAX: {
4556 // If we are looking at the loaded value.
4557 if (Op.getResNo() == 0) {
4558 auto *AT = cast<AtomicSDNode>(Op);
4559 unsigned MemBits = AT->getMemoryVT().getScalarSizeInBits();
4560
4561 if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND)
4562 Known.Zero.setBitsFrom(MemBits);
4563 }
4564 break;
4565 }
4566 case ISD::FrameIndex:
4567 case ISD::TargetFrameIndex: {
4568 const MachineFunction &MF = getMachineFunction();
4569 int FrameIdx = cast<FrameIndexSDNode>(Op)->getIndex();
4570 TLI->computeKnownBitsForStackObjectPointer(
4571 Known, MF, MF.getFrameInfo().getObjectAlign(FrameIdx));
4572 break;
4573 }
4574 case ISD::VP_LOAD_FF: {
4575 if (Op.getResNo() != 1)
4576 break;
4577 // The second result of vp.load.ff is an unsigned value that is less than or
4578 // equal to the EVL operand.
4579 KnownBits VLKB =
4580 computeKnownBits(Op.getOperand(3), DemandedElts, Depth + 1);
4581 // The new VL is also bounded by the largest vector length.
4582 EVT ResVT = Op->getValueType(0);
4583 auto ResKB = KnownBits::makeConstant(
4585 if (ResVT.isScalableVector()) {
4587 ResKB = KnownBits::mul(getVScaleRange(&F, BitWidth).toKnownBits(), ResKB);
4588 }
4589 Known.Zero.setHighBits(KnownBits::umin(VLKB, ResKB).countMinLeadingZeros());
4590 break;
4591 }
4592
4593 default:
4594 if (Opcode < ISD::BUILTIN_OP_END)
4595 break;
4596 [[fallthrough]];
4600 // Allow the target to implement this method for its nodes.
4601 TLI->computeKnownBitsForTargetNode(Op, Known, DemandedElts, *this, Depth);
4602 break;
4603 }
4604
4605 return Known;
4606}
4607
4608/// Convert ConstantRange OverflowResult into SelectionDAG::OverflowKind.
4621
4624 // X + 0 never overflow
4625 if (isNullConstant(N1))
4626 return OFK_Never;
4627
4628 // If both operands each have at least two sign bits, the addition
4629 // cannot overflow.
4630 if (ComputeNumSignBits(N0) > 1 && ComputeNumSignBits(N1) > 1)
4631 return OFK_Never;
4632
4633 // TODO: Add ConstantRange::signedAddMayOverflow handling.
4634 return OFK_Sometime;
4635}
4636
4639 // X + 0 never overflow
4640 if (isNullConstant(N1))
4641 return OFK_Never;
4642
4643 // mulhi + 1 never overflow
4644 KnownBits N1Known = computeKnownBits(N1);
4645 if (N0.getOpcode() == ISD::UMUL_LOHI && N0.getResNo() == 1 &&
4646 N1Known.getMaxValue().ult(2))
4647 return OFK_Never;
4648
4649 KnownBits N0Known = computeKnownBits(N0);
4650 if (N1.getOpcode() == ISD::UMUL_LOHI && N1.getResNo() == 1 &&
4651 N0Known.getMaxValue().ult(2))
4652 return OFK_Never;
4653
4654 // Fallback to ConstantRange::unsignedAddMayOverflow handling.
4655 ConstantRange N0Range = ConstantRange::fromKnownBits(N0Known, false);
4656 ConstantRange N1Range = ConstantRange::fromKnownBits(N1Known, false);
4657 return mapOverflowResult(N0Range.unsignedAddMayOverflow(N1Range));
4658}
4659
4662 // X - 0 never overflow
4663 if (isNullConstant(N1))
4664 return OFK_Never;
4665
4666 // If both operands each have at least two sign bits, the subtraction
4667 // cannot overflow.
4668 if (ComputeNumSignBits(N0) > 1 && ComputeNumSignBits(N1) > 1)
4669 return OFK_Never;
4670
4671 KnownBits N0Known = computeKnownBits(N0);
4672 KnownBits N1Known = computeKnownBits(N1);
4673 ConstantRange N0Range = ConstantRange::fromKnownBits(N0Known, true);
4674 ConstantRange N1Range = ConstantRange::fromKnownBits(N1Known, true);
4675 return mapOverflowResult(N0Range.signedSubMayOverflow(N1Range));
4676}
4677
4680 // X - 0 never overflow
4681 if (isNullConstant(N1))
4682 return OFK_Never;
4683
4684 ConstantRange N0Range =
4685 computeConstantRangeIncludingKnownBits(N0, /*ForSigned=*/false);
4686 ConstantRange N1Range =
4687 computeConstantRangeIncludingKnownBits(N1, /*ForSigned=*/false);
4688 return mapOverflowResult(N0Range.unsignedSubMayOverflow(N1Range));
4689}
4690
4693 // X * 0 and X * 1 never overflow.
4694 if (isNullConstant(N1) || isOneConstant(N1))
4695 return OFK_Never;
4696
4699 return mapOverflowResult(N0Range.unsignedMulMayOverflow(N1Range));
4700}
4701
4704 // X * 0 and X * 1 never overflow.
4705 if (isNullConstant(N1) || isOneConstant(N1))
4706 return OFK_Never;
4707
4708 // Get the size of the result.
4709 unsigned BitWidth = N0.getScalarValueSizeInBits();
4710
4711 // Sum of the sign bits.
4712 unsigned SignBits = ComputeNumSignBits(N0) + ComputeNumSignBits(N1);
4713
4714 // If we have enough sign bits, then there's no overflow.
4715 if (SignBits > BitWidth + 1)
4716 return OFK_Never;
4717
4718 if (SignBits == BitWidth + 1) {
4719 // The overflow occurs when the true multiplication of the
4720 // the operands is the minimum negative number.
4721 KnownBits N0Known = computeKnownBits(N0);
4722 KnownBits N1Known = computeKnownBits(N1);
4723 // If one of the operands is non-negative, then there's no
4724 // overflow.
4725 if (N0Known.isNonNegative() || N1Known.isNonNegative())
4726 return OFK_Never;
4727 }
4728
4729 return OFK_Sometime;
4730}
4731
4733 unsigned Depth) const {
4734 APInt DemandedElts = getDemandAllEltsMask(Op);
4735 return computeConstantRange(Op, DemandedElts, ForSigned, Depth);
4736}
4737
4739 const APInt &DemandedElts,
4740 bool ForSigned,
4741 unsigned Depth) const {
4742 EVT VT = Op.getValueType();
4743 unsigned BitWidth = VT.getScalarSizeInBits();
4744
4745 if (Depth >= MaxRecursionDepth)
4746 return ConstantRange::getFull(BitWidth);
4747
4748 if (ConstantSDNode *C = isConstOrConstSplat(Op, DemandedElts))
4749 return ConstantRange(C->getAPIntValue());
4750
4751 unsigned Opcode = Op.getOpcode();
4752 switch (Opcode) {
4753 case ISD::VSCALE: {
4755 const APInt &Multiplier = Op.getConstantOperandAPInt(0);
4756 return getVScaleRange(&F, BitWidth).multiply(Multiplier);
4757 }
4758 default:
4759 break;
4760 }
4761
4762 return ConstantRange::getFull(BitWidth);
4763}
4764
4767 unsigned Depth) const {
4768 APInt DemandedElts = getDemandAllEltsMask(Op);
4769 return computeConstantRangeIncludingKnownBits(Op, DemandedElts, ForSigned,
4770 Depth);
4771}
4772
4774 SDValue Op, const APInt &DemandedElts, bool ForSigned,
4775 unsigned Depth) const {
4776 KnownBits Known = computeKnownBits(Op, DemandedElts, Depth);
4778 ConstantRange CR2 = computeConstantRange(Op, DemandedElts, ForSigned, Depth);
4781 return CR1.intersectWith(CR2, RangeType);
4782}
4783
4785 unsigned Depth) const {
4786 APInt DemandedElts = getDemandAllEltsMask(Val);
4787 return isKnownToBeAPowerOfTwo(Val, DemandedElts, OrZero, Depth);
4788}
4789
4791 const APInt &DemandedElts,
4792 bool OrZero, unsigned Depth) const {
4793 if (Depth >= MaxRecursionDepth)
4794 return false; // Limit search depth.
4795
4796 EVT OpVT = Val.getValueType();
4797 unsigned BitWidth = OpVT.getScalarSizeInBits();
4798 [[maybe_unused]] unsigned NumElts = DemandedElts.getBitWidth();
4799 assert((!OpVT.isScalableVector() || NumElts == 1) &&
4800 "DemandedElts for scalable vectors must be 1 to represent all lanes");
4801 assert(
4802 (!OpVT.isFixedLengthVector() || NumElts == OpVT.getVectorNumElements()) &&
4803 "Unexpected vector size");
4804
4805 auto IsPowerOfTwoOrZero = [BitWidth, OrZero](const ConstantSDNode *C) {
4806 APInt V = C->getAPIntValue().zextOrTrunc(BitWidth);
4807 return (OrZero && V.isZero()) || V.isPowerOf2();
4808 };
4809
4810 // Is the constant a known power of 2 or zero?
4811 if (ISD::matchUnaryPredicate(Val, DemandedElts, IsPowerOfTwoOrZero,
4812 /*AllowUndefs=*/false, /*AllowTruncation=*/true))
4813 return true;
4814
4815 switch (Val.getOpcode()) {
4817 SDValue InVec = Val.getOperand(0);
4818 SDValue EltNo = Val.getOperand(1);
4819 EVT VecVT = InVec.getValueType();
4820
4821 // Skip scalable vectors or implicit extensions.
4822 if (VecVT.isScalableVector() ||
4823 OpVT.getScalarSizeInBits() != VecVT.getScalarSizeInBits())
4824 break;
4825
4826 // If we know the element index, just demand that vector element, else for
4827 // an unknown element index, ignore DemandedElts and demand them all.
4828 const unsigned NumSrcElts = VecVT.getVectorNumElements();
4829 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
4830 APInt DemandedSrcElts =
4831 ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts)
4832 ? APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue())
4833 : APInt::getAllOnes(NumSrcElts);
4834 return isKnownToBeAPowerOfTwo(InVec, DemandedSrcElts, OrZero, Depth + 1);
4835 }
4836
4837 case ISD::AND: {
4838 // Looking for `x & -x` pattern:
4839 // If x == 0:
4840 // x & -x -> 0
4841 // If x != 0:
4842 // x & -x -> non-zero pow2
4843 // so if we find the pattern return whether we know `x` is non-zero.
4844 SDValue X, Z;
4845 if (sd_match(Val, m_And(m_Value(X), m_Neg(m_Deferred(X)))) ||
4846 (sd_match(Val, m_And(m_Value(X), m_Sub(m_Value(Z), m_Deferred(X)))) &&
4847 MaskedVectorIsZero(Z, DemandedElts, Depth + 1)))
4848 return OrZero || isKnownNeverZero(X, DemandedElts, Depth);
4849 break;
4850 }
4851
4852 case ISD::SHL: {
4853 // A left-shift of a constant one will have exactly one bit set because
4854 // shifting the bit off the end is undefined.
4855 auto *C = isConstOrConstSplat(Val.getOperand(0), DemandedElts);
4856 if (C && C->getAPIntValue() == 1)
4857 return true;
4858 return (OrZero || isKnownNeverZero(Val, DemandedElts, Depth)) &&
4859 isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedElts, OrZero,
4860 Depth + 1);
4861 }
4862
4863 case ISD::SRL: {
4864 // A logical right-shift of a constant sign-bit will have exactly
4865 // one bit set.
4866 auto *C = isConstOrConstSplat(Val.getOperand(0), DemandedElts);
4867 if (C && C->getAPIntValue().isSignMask())
4868 return true;
4869 return (OrZero || isKnownNeverZero(Val, DemandedElts, Depth)) &&
4870 isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedElts, OrZero,
4871 Depth + 1);
4872 }
4873
4874 case ISD::TRUNCATE:
4875 return (OrZero || isKnownNeverZero(Val, DemandedElts, Depth)) &&
4876 isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedElts, OrZero,
4877 Depth + 1);
4878
4879 case ISD::ROTL:
4880 case ISD::ROTR:
4881 return isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedElts, OrZero,
4882 Depth + 1);
4883 case ISD::BSWAP:
4884 case ISD::BITREVERSE:
4885 return isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedElts, OrZero,
4886 Depth + 1);
4887
4888 case ISD::SMIN:
4889 case ISD::SMAX:
4890 case ISD::UMIN:
4891 case ISD::UMAX:
4892 return isKnownToBeAPowerOfTwo(Val.getOperand(1), DemandedElts, OrZero,
4893 Depth + 1) &&
4894 isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedElts, OrZero,
4895 Depth + 1);
4896
4897 case ISD::SELECT:
4898 case ISD::VSELECT:
4899 return isKnownToBeAPowerOfTwo(Val.getOperand(2), DemandedElts, OrZero,
4900 Depth + 1) &&
4901 isKnownToBeAPowerOfTwo(Val.getOperand(1), DemandedElts, OrZero,
4902 Depth + 1);
4903
4904 case ISD::ZERO_EXTEND:
4905 return isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedElts, OrZero,
4906 Depth + 1);
4907
4908 case ISD::VSCALE:
4909 // vscale(power-of-two) is a power-of-two
4910 return isKnownToBeAPowerOfTwo(Val.getOperand(0), /*OrZero=*/false,
4911 Depth + 1);
4912
4913 case ISD::VECTOR_SHUFFLE: {
4915 // Demanded elements with undef shuffle mask elements are unknown
4916 // - we cannot guarantee they are a power of two, so return false.
4917 APInt DemandedLHS, DemandedRHS;
4919 assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
4920 if (!getShuffleDemandedElts(NumElts, SVN->getMask(), DemandedElts,
4921 DemandedLHS, DemandedRHS))
4922 return false;
4923
4924 // All demanded elements from LHS must be known power of two.
4925 if (!!DemandedLHS && !isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedLHS,
4926 OrZero, Depth + 1))
4927 return false;
4928
4929 // All demanded elements from RHS must be known power of two.
4930 if (!!DemandedRHS && !isKnownToBeAPowerOfTwo(Val.getOperand(1), DemandedRHS,
4931 OrZero, Depth + 1))
4932 return false;
4933
4934 return true;
4935 }
4936 }
4937
4938 // More could be done here, though the above checks are enough
4939 // to handle some common cases.
4940 return false;
4941}
4942
4944 if (ConstantFPSDNode *C1 = isConstOrConstSplatFP(Val, true))
4945 return C1->getValueAPF().getExactLog2Abs() >= 0;
4946
4947 if (Val.getOpcode() == ISD::UINT_TO_FP || Val.getOpcode() == ISD::SINT_TO_FP)
4948 return isKnownToBeAPowerOfTwo(Val.getOperand(0), Depth + 1);
4949
4950 return false;
4951}
4952
4954 APInt DemandedElts = getDemandAllEltsMask(Op);
4955 return ComputeNumSignBits(Op, DemandedElts, Depth);
4956}
4957
4958unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, const APInt &DemandedElts,
4959 unsigned Depth) const {
4960 EVT VT = Op.getValueType();
4961 assert((VT.isInteger() || VT.isFloatingPoint()) && "Invalid VT!");
4962 unsigned VTBits = VT.getScalarSizeInBits();
4963 unsigned NumElts = DemandedElts.getBitWidth();
4964 unsigned Tmp, Tmp2;
4965 unsigned FirstAnswer = 1;
4966
4967 assert((!VT.isScalableVector() || NumElts == 1) &&
4968 "DemandedElts for scalable vectors must be 1 to represent all lanes");
4969
4970 if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
4971 const APInt &Val = C->getAPIntValue();
4972 return Val.getNumSignBits();
4973 }
4974
4975 if (Depth >= MaxRecursionDepth)
4976 return 1; // Limit search depth.
4977
4978 if (!DemandedElts)
4979 return 1; // No demanded elts, better to assume we don't know anything.
4980
4981 unsigned Opcode = Op.getOpcode();
4982 switch (Opcode) {
4983 default: break;
4984 case ISD::AssertSext:
4985 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
4986 return VTBits-Tmp+1;
4987 case ISD::AssertZext:
4988 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
4989 return VTBits-Tmp;
4990 case ISD::FREEZE:
4991 if (isGuaranteedNotToBeUndefOrPoison(Op.getOperand(0), DemandedElts,
4993 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4994 break;
4995 case ISD::MERGE_VALUES:
4996 return ComputeNumSignBits(Op.getOperand(Op.getResNo()), DemandedElts,
4997 Depth + 1);
4998 case ISD::SPLAT_VECTOR: {
4999 // Check if the sign bits of source go down as far as the truncated value.
5000 unsigned NumSrcBits = Op.getOperand(0).getValueSizeInBits();
5001 unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
5002 if (NumSrcSignBits > (NumSrcBits - VTBits))
5003 return NumSrcSignBits - (NumSrcBits - VTBits);
5004 break;
5005 }
5006 case ISD::BUILD_VECTOR:
5007 assert(!VT.isScalableVector());
5008 Tmp = VTBits;
5009 for (unsigned i = 0, e = Op.getNumOperands(); (i < e) && (Tmp > 1); ++i) {
5010 if (!DemandedElts[i])
5011 continue;
5012
5013 SDValue SrcOp = Op.getOperand(i);
5014 // BUILD_VECTOR can implicitly truncate sources, we handle this specially
5015 // for constant nodes to ensure we only look at the sign bits.
5017 APInt T = C->getAPIntValue().trunc(VTBits);
5018 Tmp2 = T.getNumSignBits();
5019 } else if (SrcOp.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5020 SrcOp.getOperand(0).getScalarValueSizeInBits() >= VTBits) {
5021 // EXTRACT_VECTOR_ELT can extend the value with high bits undefined. If
5022 // this BUILD_VECTOR truncates those undefined bits we can just look
5023 // through the SrcOp and query the vector directly.
5024 SDValue InVec = SrcOp.getOperand(0);
5025 EVT InVecVT = InVec.getValueType();
5026
5027 APInt DemandedSrcElts;
5028 if (InVecVT.isScalableVector())
5029 // Demand all elements.
5030 DemandedSrcElts = APInt(1, 1);
5031 else {
5032 unsigned NumSrcElts = InVecVT.getVectorNumElements();
5033 auto *ConstEltNo = dyn_cast<ConstantSDNode>(SrcOp.getOperand(1));
5034 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
5035 DemandedSrcElts =
5036 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
5037 else
5038 DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
5039 }
5040
5041 Tmp2 = ComputeNumSignBits(InVec, DemandedSrcElts, Depth + 1);
5042 unsigned ExtraBits = InVec.getScalarValueSizeInBits() - VTBits;
5043 if (ExtraBits)
5044 Tmp2 = (Tmp2 > ExtraBits ? Tmp2 - ExtraBits : 1);
5045 } else {
5046 Tmp2 = ComputeNumSignBits(SrcOp, Depth + 1);
5047
5048 if (SrcOp.getValueSizeInBits() != VTBits) {
5049 assert(SrcOp.getValueSizeInBits() > VTBits &&
5050 "Expected BUILD_VECTOR implicit truncation");
5051 unsigned ExtraBits = SrcOp.getValueSizeInBits() - VTBits;
5052 Tmp2 = (Tmp2 > ExtraBits ? Tmp2 - ExtraBits : 1);
5053 }
5054 }
5055 Tmp = std::min(Tmp, Tmp2);
5056 }
5057 return Tmp;
5058
5059 case ISD::VECTOR_COMPRESS: {
5060 SDValue Vec = Op.getOperand(0);
5061 SDValue PassThru = Op.getOperand(2);
5062 Tmp = ComputeNumSignBits(PassThru, DemandedElts, Depth + 1);
5063 if (Tmp == 1)
5064 return 1;
5065 Tmp2 = ComputeNumSignBits(Vec, Depth + 1);
5066 Tmp = std::min(Tmp, Tmp2);
5067 return Tmp;
5068 }
5069
5070 case ISD::VECTOR_SHUFFLE: {
5071 // Collect the minimum number of sign bits that are shared by every vector
5072 // element referenced by the shuffle.
5073 APInt DemandedLHS, DemandedRHS;
5075 assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
5076 if (!getShuffleDemandedElts(NumElts, SVN->getMask(), DemandedElts,
5077 DemandedLHS, DemandedRHS))
5078 return 1;
5079
5080 Tmp = std::numeric_limits<unsigned>::max();
5081 if (!!DemandedLHS)
5082 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedLHS, Depth + 1);
5083 if (!!DemandedRHS) {
5084 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedRHS, Depth + 1);
5085 Tmp = std::min(Tmp, Tmp2);
5086 }
5087 // If we don't know anything, early out and try computeKnownBits fall-back.
5088 if (Tmp == 1)
5089 break;
5090 assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
5091 return Tmp;
5092 }
5093
5094 case ISD::BITCAST: {
5095 if (VT.isScalableVector())
5096 break;
5097 SDValue N0 = Op.getOperand(0);
5098 EVT SrcVT = N0.getValueType();
5099 unsigned SrcBits = SrcVT.getScalarSizeInBits();
5100
5101 // Ignore bitcasts from unsupported types..
5102 if (!(SrcVT.isInteger() || SrcVT.isFloatingPoint()))
5103 break;
5104
5105 // Fast handling of 'identity' bitcasts.
5106 if (VTBits == SrcBits)
5107 return ComputeNumSignBits(N0, DemandedElts, Depth + 1);
5108
5109 bool IsLE = getDataLayout().isLittleEndian();
5110
5111 // Bitcast 'large element' scalar/vector to 'small element' vector.
5112 if ((SrcBits % VTBits) == 0) {
5113 assert(VT.isVector() && "Expected bitcast to vector");
5114
5115 unsigned Scale = SrcBits / VTBits;
5116 APInt SrcDemandedElts =
5117 APIntOps::ScaleBitMask(DemandedElts, NumElts / Scale);
5118
5119 // Fast case - sign splat can be simply split across the small elements.
5120 Tmp = ComputeNumSignBits(N0, SrcDemandedElts, Depth + 1);
5121 if (Tmp == SrcBits)
5122 return VTBits;
5123
5124 // Slow case - determine how far the sign extends into each sub-element.
5125 Tmp2 = VTBits;
5126 for (unsigned i = 0; i != NumElts; ++i)
5127 if (DemandedElts[i]) {
5128 unsigned SubOffset = i % Scale;
5129 SubOffset = (IsLE ? ((Scale - 1) - SubOffset) : SubOffset);
5130 SubOffset = SubOffset * VTBits;
5131 if (Tmp <= SubOffset)
5132 return 1;
5133 Tmp2 = std::min(Tmp2, Tmp - SubOffset);
5134 }
5135 return Tmp2;
5136 }
5137 break;
5138 }
5139
5141 // FP_TO_SINT_SAT produces a signed value that fits in the saturating VT.
5142 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
5143 return VTBits - Tmp + 1;
5144 case ISD::SIGN_EXTEND:
5145 Tmp = VTBits - Op.getOperand(0).getScalarValueSizeInBits();
5146 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1) + Tmp;
5148 // Max of the input and what this extends.
5149 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
5150 Tmp = VTBits-Tmp+1;
5151 Tmp2 = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
5152 return std::max(Tmp, Tmp2);
5154 if (VT.isScalableVector())
5155 break;
5156 SDValue Src = Op.getOperand(0);
5157 EVT SrcVT = Src.getValueType();
5158 APInt DemandedSrcElts = DemandedElts.zext(SrcVT.getVectorNumElements());
5159 Tmp = VTBits - SrcVT.getScalarSizeInBits();
5160 return ComputeNumSignBits(Src, DemandedSrcElts, Depth+1) + Tmp;
5161 }
5162 case ISD::SRA:
5163 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5164 // SRA X, C -> adds C sign bits.
5165 if (std::optional<unsigned> ShAmt =
5166 getValidMinimumShiftAmount(Op, DemandedElts, Depth + 1))
5167 Tmp = std::min(Tmp + *ShAmt, VTBits);
5168 return Tmp;
5169 case ISD::SHL:
5170 if (std::optional<ConstantRange> ShAmtRange =
5171 getValidShiftAmountRange(Op, DemandedElts, Depth + 1)) {
5172 unsigned MaxShAmt = ShAmtRange->getUnsignedMax().getZExtValue();
5173 unsigned MinShAmt = ShAmtRange->getUnsignedMin().getZExtValue();
5174 // Try to look through ZERO/SIGN/ANY_EXTEND. If all extended bits are
5175 // shifted out, then we can compute the number of sign bits for the
5176 // operand being extended. A future improvement could be to pass along the
5177 // "shifted left by" information in the recursive calls to
5178 // ComputeKnownSignBits. Allowing us to handle this more generically.
5179 if (ISD::isExtOpcode(Op.getOperand(0).getOpcode())) {
5180 SDValue Ext = Op.getOperand(0);
5181 EVT ExtVT = Ext.getValueType();
5182 SDValue Extendee = Ext.getOperand(0);
5183 EVT ExtendeeVT = Extendee.getValueType();
5184 unsigned SizeDifference =
5185 ExtVT.getScalarSizeInBits() - ExtendeeVT.getScalarSizeInBits();
5186 if (SizeDifference <= MinShAmt) {
5187 Tmp = SizeDifference +
5188 ComputeNumSignBits(Extendee, DemandedElts, Depth + 1);
5189 if (MaxShAmt < Tmp)
5190 return Tmp - MaxShAmt;
5191 }
5192 }
5193 // shl destroys sign bits, ensure it doesn't shift out all sign bits.
5194 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5195 if (MaxShAmt < Tmp)
5196 return Tmp - MaxShAmt;
5197 }
5198 break;
5199 case ISD::AND:
5200 case ISD::OR:
5201 case ISD::XOR: // NOT is handled here.
5202 // Logical binary ops preserve the number of sign bits at the worst.
5203 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
5204 if (Tmp != 1) {
5205 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
5206 FirstAnswer = std::min(Tmp, Tmp2);
5207 // We computed what we know about the sign bits as our first
5208 // answer. Now proceed to the generic code that uses
5209 // computeKnownBits, and pick whichever answer is better.
5210 }
5211 break;
5212
5213 case ISD::SELECT:
5214 case ISD::VSELECT:
5215 Tmp = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
5216 if (Tmp == 1) return 1; // Early out.
5217 Tmp2 = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
5218 return std::min(Tmp, Tmp2);
5219 case ISD::SELECT_CC:
5220 Tmp = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
5221 if (Tmp == 1) return 1; // Early out.
5222 Tmp2 = ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth+1);
5223 return std::min(Tmp, Tmp2);
5224
5225 case ISD::SMIN:
5226 case ISD::SMAX: {
5227 // If we have a clamp pattern, we know that the number of sign bits will be
5228 // the minimum of the clamp min/max range.
5229 bool IsMax = (Opcode == ISD::SMAX);
5230 ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
5231 if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
5232 if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
5233 CstHigh =
5234 isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
5235 if (CstLow && CstHigh) {
5236 if (!IsMax)
5237 std::swap(CstLow, CstHigh);
5238 if (CstLow->getAPIntValue().sle(CstHigh->getAPIntValue())) {
5239 Tmp = CstLow->getAPIntValue().getNumSignBits();
5240 Tmp2 = CstHigh->getAPIntValue().getNumSignBits();
5241 return std::min(Tmp, Tmp2);
5242 }
5243 }
5244
5245 // Fallback - just get the minimum number of sign bits of the operands.
5246 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5247 if (Tmp == 1)
5248 return 1; // Early out.
5249 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
5250 return std::min(Tmp, Tmp2);
5251 }
5252 case ISD::UMIN:
5253 case ISD::UMAX:
5254 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5255 if (Tmp == 1)
5256 return 1; // Early out.
5257 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
5258 return std::min(Tmp, Tmp2);
5259 case ISD::SSUBO_CARRY:
5260 case ISD::USUBO_CARRY:
5261 // sub_carry(x,x,c) -> 0/-1 (sext carry)
5262 if (Op.getResNo() == 0 && Op.getOperand(0) == Op.getOperand(1))
5263 return VTBits;
5264 [[fallthrough]];
5265 case ISD::SADDO:
5266 case ISD::UADDO:
5267 case ISD::SADDO_CARRY:
5268 case ISD::UADDO_CARRY:
5269 case ISD::SSUBO:
5270 case ISD::USUBO:
5271 case ISD::SMULO:
5272 case ISD::UMULO:
5273 if (Op.getResNo() != 1)
5274 break;
5275 // The boolean result conforms to getBooleanContents. Fall through.
5276 // If setcc returns 0/-1, all bits are sign bits.
5277 // We know that we have an integer-based boolean since these operations
5278 // are only available for integer.
5279 if (TLI->getBooleanContents(VT.isVector(), false) ==
5281 return VTBits;
5282 break;
5283 case ISD::SETCC:
5284 case ISD::SETCCCARRY:
5285 case ISD::STRICT_FSETCC:
5286 case ISD::STRICT_FSETCCS: {
5287 unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
5288 // If setcc returns 0/-1, all bits are sign bits.
5289 if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
5291 return VTBits;
5292 break;
5293 }
5296 // Semantically similar to icmp ult.
5297 if (TLI->getBooleanContents(VT.isVector(), /*isFloat=*/false) ==
5299 return VTBits;
5300 break;
5301 case ISD::ROTL:
5302 case ISD::ROTR: {
5303 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5304 ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(1), DemandedElts);
5305 FirstAnswer = SignBitsOps::rot(
5306 Tmp, VTBits, C ? std::optional(C->getAPIntValue()) : std::nullopt,
5307 Opcode == ISD::ROTR);
5308 break;
5309 }
5310 case ISD::ADD:
5311 case ISD::ADDC:
5312 // TODO: Move Operand 1 check before Operand 0 check
5313 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5314 if (Tmp == 1) return 1; // Early out.
5315
5316 // Special case decrementing a value (ADD X, -1):
5317 if (ConstantSDNode *CRHS =
5318 isConstOrConstSplat(Op.getOperand(1), DemandedElts))
5319 if (CRHS->isAllOnes()) {
5321 computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
5322
5323 // If the input is known to be 0 or 1, the output is 0/-1, which is all
5324 // sign bits set.
5325 if ((Known.Zero | 1).isAllOnes())
5326 return VTBits;
5327
5328 // If we are subtracting one from a positive number, there is no carry
5329 // out of the result.
5330 if (Known.isNonNegative())
5331 return Tmp;
5332 }
5333
5334 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
5335 if (Tmp2 == 1) return 1; // Early out.
5336
5337 // Add can have at most one carry bit. Thus we know that the output
5338 // is, at worst, one more bit than the inputs.
5339 return std::min(Tmp, Tmp2) - 1;
5340 case ISD::SUB:
5341 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
5342 if (Tmp2 == 1) return 1; // Early out.
5343
5344 // Handle NEG.
5345 if (ConstantSDNode *CLHS =
5346 isConstOrConstSplat(Op.getOperand(0), DemandedElts))
5347 if (CLHS->isZero()) {
5349 computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
5350 // If the input is known to be 0 or 1, the output is 0/-1, which is all
5351 // sign bits set.
5352 if ((Known.Zero | 1).isAllOnes())
5353 return VTBits;
5354
5355 // If the input is known to be positive (the sign bit is known clear),
5356 // the output of the NEG has the same number of sign bits as the input.
5357 if (Known.isNonNegative())
5358 return Tmp2;
5359
5360 // Otherwise, we treat this like a SUB.
5361 }
5362
5363 // Sub can have at most one carry bit. Thus we know that the output
5364 // is, at worst, one more bit than the inputs.
5365 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5366 if (Tmp == 1) return 1; // Early out.
5367 return std::min(Tmp, Tmp2) - 1;
5368 case ISD::MUL: {
5369 // The output of the Mul can be at most twice the valid bits in the inputs.
5370 unsigned SignBitsOp0 =
5371 ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5372 if (SignBitsOp0 == 1)
5373 break;
5374 unsigned SignBitsOp1 =
5375 ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
5376 if (SignBitsOp1 == 1)
5377 break;
5378 unsigned OutValidBits =
5379 (VTBits - SignBitsOp0 + 1) + (VTBits - SignBitsOp1 + 1);
5380 return OutValidBits > VTBits ? 1 : VTBits - OutValidBits + 1;
5381 }
5382 case ISD::AVGCEILS:
5383 case ISD::AVGFLOORS:
5384 case ISD::AVGSUBFLOORS:
5385 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5386 if (Tmp == 1)
5387 return 1; // Early out.
5388 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
5389 return std::min(Tmp, Tmp2);
5390 case ISD::SREM:
5391 // The sign bit is the LHS's sign bit, except when the result of the
5392 // remainder is zero. The magnitude of the result should be less than or
5393 // equal to the magnitude of the LHS. Therefore, the result should have
5394 // at least as many sign bits as the left hand side.
5395 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5396 case ISD::TRUNCATE: {
5397 // Check if the sign bits of source go down as far as the truncated value.
5398 unsigned NumSrcBits = Op.getOperand(0).getScalarValueSizeInBits();
5399 unsigned NumSrcSignBits =
5400 ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5401 if (NumSrcSignBits > (NumSrcBits - VTBits))
5402 return NumSrcSignBits - (NumSrcBits - VTBits);
5403 break;
5404 }
5405 case ISD::EXTRACT_ELEMENT: {
5406 if (VT.isScalableVector())
5407 break;
5408 const int KnownSign = ComputeNumSignBits(Op.getOperand(0), Depth+1);
5409 const int BitWidth = Op.getValueSizeInBits();
5410 const int Items = Op.getOperand(0).getValueSizeInBits() / BitWidth;
5411
5412 // Get reverse index (starting from 1), Op1 value indexes elements from
5413 // little end. Sign starts at big end.
5414 const int rIndex = Items - 1 - Op.getConstantOperandVal(1);
5415
5416 // If the sign portion ends in our element the subtraction gives correct
5417 // result. Otherwise it gives either negative or > bitwidth result
5418 return std::clamp(KnownSign - rIndex * BitWidth, 1, BitWidth);
5419 }
5421 if (VT.isScalableVector())
5422 break;
5423 // If we know the element index, split the demand between the
5424 // source vector and the inserted element, otherwise assume we need
5425 // the original demanded vector elements and the value.
5426 SDValue InVec = Op.getOperand(0);
5427 SDValue InVal = Op.getOperand(1);
5428 SDValue EltNo = Op.getOperand(2);
5429 bool DemandedVal = true;
5430 APInt DemandedVecElts = DemandedElts;
5431 auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
5432 if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
5433 unsigned EltIdx = CEltNo->getZExtValue();
5434 DemandedVal = !!DemandedElts[EltIdx];
5435 DemandedVecElts.clearBit(EltIdx);
5436 }
5437 Tmp = std::numeric_limits<unsigned>::max();
5438 if (DemandedVal) {
5439 // TODO - handle implicit truncation of inserted elements.
5440 if (InVal.getScalarValueSizeInBits() != VTBits)
5441 break;
5442 Tmp2 = ComputeNumSignBits(InVal, Depth + 1);
5443 Tmp = std::min(Tmp, Tmp2);
5444 }
5445 if (!!DemandedVecElts) {
5446 Tmp2 = ComputeNumSignBits(InVec, DemandedVecElts, Depth + 1);
5447 Tmp = std::min(Tmp, Tmp2);
5448 }
5449 assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
5450 return Tmp;
5451 }
5453 SDValue InVec = Op.getOperand(0);
5454 SDValue EltNo = Op.getOperand(1);
5455 EVT VecVT = InVec.getValueType();
5456 // ComputeNumSignBits not yet implemented for scalable vectors.
5457 if (VecVT.isScalableVector())
5458 break;
5459 const unsigned BitWidth = Op.getValueSizeInBits();
5460 const unsigned EltBitWidth = Op.getOperand(0).getScalarValueSizeInBits();
5461 const unsigned NumSrcElts = VecVT.getVectorNumElements();
5462
5463 // If BitWidth > EltBitWidth the value is anyext:ed, and we do not know
5464 // anything about sign bits. But if the sizes match we can derive knowledge
5465 // about sign bits from the vector operand.
5466 if (BitWidth != EltBitWidth)
5467 break;
5468
5469 // If we know the element index, just demand that vector element, else for
5470 // an unknown element index, ignore DemandedElts and demand them all.
5471 APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
5472 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
5473 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
5474 DemandedSrcElts =
5475 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
5476
5477 return ComputeNumSignBits(InVec, DemandedSrcElts, Depth + 1);
5478 }
5480 // Offset the demanded elts by the subvector index.
5481 SDValue Src = Op.getOperand(0);
5482
5483 APInt DemandedSrcElts;
5484 if (Src.getValueType().isScalableVector())
5485 DemandedSrcElts = APInt(1, 1);
5486 else {
5487 uint64_t Idx = Op.getConstantOperandVal(1);
5488 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
5489 DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
5490 }
5491 return ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
5492 }
5493 case ISD::CONCAT_VECTORS: {
5494 if (VT.isScalableVector())
5495 break;
5496 // Determine the minimum number of sign bits across all demanded
5497 // elts of the input vectors. Early out if the result is already 1.
5498 Tmp = std::numeric_limits<unsigned>::max();
5499 EVT SubVectorVT = Op.getOperand(0).getValueType();
5500 unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
5501 unsigned NumSubVectors = Op.getNumOperands();
5502 for (unsigned i = 0; (i < NumSubVectors) && (Tmp > 1); ++i) {
5503 APInt DemandedSub =
5504 DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts);
5505 if (!DemandedSub)
5506 continue;
5507 Tmp2 = ComputeNumSignBits(Op.getOperand(i), DemandedSub, Depth + 1);
5508 Tmp = std::min(Tmp, Tmp2);
5509 }
5510 assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
5511 return Tmp;
5512 }
5513 case ISD::INSERT_SUBVECTOR: {
5514 SDValue Src = Op.getOperand(0);
5515 SDValue Sub = Op.getOperand(1);
5516 if (VT.isScalableVector()) {
5517 Tmp = ComputeNumSignBits(Sub, Depth + 1);
5518 Tmp = std::min(Tmp, ComputeNumSignBits(Src, Depth + 1));
5519 return Tmp;
5520 }
5521 // Demand any elements from the subvector and the remainder from the src its
5522 // inserted into.
5523 uint64_t Idx = Op.getConstantOperandVal(2);
5524 unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
5525 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
5526 APInt DemandedSrcElts = DemandedElts;
5527 DemandedSrcElts.clearBits(Idx, Idx + NumSubElts);
5528
5529 Tmp = std::numeric_limits<unsigned>::max();
5530 if (!!DemandedSubElts) {
5531 Tmp = ComputeNumSignBits(Sub, DemandedSubElts, Depth + 1);
5532 if (Tmp == 1)
5533 return 1; // early-out
5534 }
5535 if (!!DemandedSrcElts) {
5536 Tmp2 = ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
5537 Tmp = std::min(Tmp, Tmp2);
5538 }
5539 assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
5540 return Tmp;
5541 }
5542 case ISD::LOAD: {
5543 // If we are looking at the loaded value of the SDNode.
5544 if (Op.getResNo() != 0)
5545 break;
5546
5548 if (const MDNode *Ranges = LD->getRanges()) {
5549 if (DemandedElts != 1)
5550 break;
5551
5553 if (VTBits > CR.getBitWidth()) {
5554 switch (LD->getExtensionType()) {
5555 case ISD::SEXTLOAD:
5556 CR = CR.signExtend(VTBits);
5557 break;
5558 case ISD::ZEXTLOAD:
5559 CR = CR.zeroExtend(VTBits);
5560 break;
5561 default:
5562 break;
5563 }
5564 }
5565
5566 if (VTBits != CR.getBitWidth())
5567 break;
5568 return std::min(CR.getSignedMin().getNumSignBits(),
5570 }
5571
5572 unsigned ExtType = LD->getExtensionType();
5573 switch (ExtType) {
5574 default:
5575 break;
5576 case ISD::SEXTLOAD: // e.g. i16->i32 = '17' bits known.
5577 Tmp = LD->getMemoryVT().getScalarSizeInBits();
5578 return VTBits - Tmp + 1;
5579 case ISD::ZEXTLOAD: // e.g. i16->i32 = '16' bits known.
5580 Tmp = LD->getMemoryVT().getScalarSizeInBits();
5581 return VTBits - Tmp;
5582 case ISD::NON_EXTLOAD:
5583 if (const Constant *Cst = TLI->getTargetConstantFromLoad(LD)) {
5584 // We only need to handle vectors - computeKnownBits should handle
5585 // scalar cases.
5586 Type *CstTy = Cst->getType();
5587 if (CstTy->isVectorTy() && !VT.isScalableVector() &&
5588 (NumElts * VTBits) == CstTy->getPrimitiveSizeInBits() &&
5589 VTBits == CstTy->getScalarSizeInBits()) {
5590 Tmp = VTBits;
5591 for (unsigned i = 0; i != NumElts; ++i) {
5592 if (!DemandedElts[i])
5593 continue;
5594 if (Constant *Elt = Cst->getAggregateElement(i)) {
5595 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
5596 const APInt &Value = CInt->getValue();
5597 Tmp = std::min(Tmp, Value.getNumSignBits());
5598 continue;
5599 }
5600 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
5601 APInt Value = CFP->getValueAPF().bitcastToAPInt();
5602 Tmp = std::min(Tmp, Value.getNumSignBits());
5603 continue;
5604 }
5605 }
5606 // Unknown type. Conservatively assume no bits match sign bit.
5607 return 1;
5608 }
5609 return Tmp;
5610 }
5611 }
5612 break;
5613 }
5614
5615 break;
5616 }
5619 case ISD::ATOMIC_SWAP:
5631 case ISD::ATOMIC_LOAD: {
5632 auto *AT = cast<AtomicSDNode>(Op);
5633 // If we are looking at the loaded value.
5634 if (Op.getResNo() == 0) {
5635 Tmp = AT->getMemoryVT().getScalarSizeInBits();
5636 if (Tmp == VTBits)
5637 return 1; // early-out
5638
5639 // For atomic_load, prefer to use the extension type.
5640 if (Op->getOpcode() == ISD::ATOMIC_LOAD) {
5641 switch (AT->getExtensionType()) {
5642 default:
5643 break;
5644 case ISD::SEXTLOAD:
5645 return VTBits - Tmp + 1;
5646 case ISD::ZEXTLOAD:
5647 return VTBits - Tmp;
5648 }
5649 }
5650
5651 if (TLI->getExtendForAtomicOps() == ISD::SIGN_EXTEND)
5652 return VTBits - Tmp + 1;
5653 if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND)
5654 return VTBits - Tmp;
5655 }
5656 break;
5657 }
5658 }
5659
5660 // Allow the target to implement this method for its nodes.
5661 if (Opcode >= ISD::BUILTIN_OP_END ||
5662 Opcode == ISD::INTRINSIC_WO_CHAIN ||
5663 Opcode == ISD::INTRINSIC_W_CHAIN ||
5664 Opcode == ISD::INTRINSIC_VOID) {
5665 // TODO: This can probably be removed once target code is audited. This
5666 // is here purely to reduce patch size and review complexity.
5667 if (!VT.isScalableVector()) {
5668 unsigned NumBits =
5669 TLI->ComputeNumSignBitsForTargetNode(Op, DemandedElts, *this, Depth);
5670 if (NumBits > 1)
5671 FirstAnswer = std::max(FirstAnswer, NumBits);
5672 }
5673 }
5674
5675 // Finally, if we can prove that the top bits of the result are 0's or 1's,
5676 // use this information.
5677 KnownBits Known = computeKnownBits(Op, DemandedElts, Depth);
5678 return std::max(FirstAnswer, Known.countMinSignBits());
5679}
5680
5682 unsigned Depth) const {
5683 unsigned SignBits = ComputeNumSignBits(Op, Depth);
5684 return Op.getScalarValueSizeInBits() - SignBits + 1;
5685}
5686
5688 const APInt &DemandedElts,
5689 unsigned Depth) const {
5690 unsigned SignBits = ComputeNumSignBits(Op, DemandedElts, Depth);
5691 return Op.getScalarValueSizeInBits() - SignBits + 1;
5692}
5693
5695 UndefPoisonKind Kind,
5696 unsigned Depth) const {
5697 // Early out for FREEZE.
5698 if (Op.getOpcode() == ISD::FREEZE)
5699 return true;
5700
5701 APInt DemandedElts = getDemandAllEltsMask(Op);
5702 return isGuaranteedNotToBeUndefOrPoison(Op, DemandedElts, Kind, Depth);
5703}
5704
5706 const APInt &DemandedElts,
5707 UndefPoisonKind Kind,
5708 unsigned Depth) const {
5709 unsigned Opcode = Op.getOpcode();
5710 unsigned NumElts = DemandedElts.getBitWidth();
5711
5712 // Early out for FREEZE / constant.
5713 if (Opcode == ISD::FREEZE || isIntOrFPConstant(Op))
5714 return true;
5715
5716 if (Depth >= MaxRecursionDepth)
5717 return false; // Limit search depth.
5718
5719 switch (Opcode) {
5720 case ISD::CONDCODE:
5721 case ISD::VALUETYPE:
5722 case ISD::FrameIndex:
5724 case ISD::CopyFromReg:
5725 return true;
5726
5727 case ISD::POISON:
5728 return !includesPoison(Kind);
5729
5730 case ISD::UNDEF:
5731 return !includesUndef(Kind);
5732
5733 case ISD::BITCAST: {
5734 SDValue Src = Op.getOperand(0);
5735 EVT SrcVT = Src.getValueType();
5736 EVT DstVT = Op.getValueType();
5737
5738 if (!SrcVT.isVector() || !DstVT.isVector())
5739 return isGuaranteedNotToBeUndefOrPoison(Src, Kind, Depth + 1);
5740
5741 unsigned SrcEltBits = SrcVT.getScalarSizeInBits();
5742 unsigned DstEltBits = DstVT.getScalarSizeInBits();
5743 ElementCount NumSrcElts = SrcVT.getVectorElementCount();
5744 [[maybe_unused]] ElementCount NumDstElts = DstVT.getVectorElementCount();
5745
5746 if (SrcEltBits == DstEltBits)
5747 return isGuaranteedNotToBeUndefOrPoison(Src, DemandedElts, Kind,
5748 Depth + 1);
5749
5750 if (SrcEltBits < DstEltBits) {
5751 if (DstEltBits % SrcEltBits != 0)
5752 return isGuaranteedNotToBeUndefOrPoison(Src, Kind, Depth + 1);
5753
5754 assert(NumSrcElts == NumDstElts * (DstEltBits / SrcEltBits) &&
5755 "Unexpected vector bitcast");
5756 APInt DemandedSrcElts =
5757 APIntOps::ScaleBitMask(DemandedElts, NumSrcElts.getKnownMinValue());
5758 return isGuaranteedNotToBeUndefOrPoison(Src, DemandedSrcElts, Kind,
5759 Depth + 1);
5760 }
5761
5762 if (SrcEltBits % DstEltBits != 0)
5763 return isGuaranteedNotToBeUndefOrPoison(Src, Kind, Depth + 1);
5764
5765 assert(NumDstElts == NumSrcElts * (SrcEltBits / DstEltBits) &&
5766 "Unexpected vector bitcast");
5767 APInt DemandedSrcElts =
5768 APIntOps::ScaleBitMask(DemandedElts, NumSrcElts.getKnownMinValue());
5769 return isGuaranteedNotToBeUndefOrPoison(Src, DemandedSrcElts, Kind,
5770 Depth + 1);
5771 }
5772
5773 case ISD::BUILD_VECTOR:
5774 // NOTE: BUILD_VECTOR has implicit truncation of wider scalar elements -
5775 // this shouldn't affect the result.
5776 for (unsigned i = 0, e = Op.getNumOperands(); i < e; ++i) {
5777 if (!DemandedElts[i])
5778 continue;
5779 if (!isGuaranteedNotToBeUndefOrPoison(Op.getOperand(i), Kind, Depth + 1))
5780 return false;
5781 }
5782 return true;
5783
5784 case ISD::CONCAT_VECTORS: {
5785 EVT VT = Op.getValueType();
5786 if (!VT.isFixedLengthVector())
5787 break;
5788
5789 EVT SubVT = Op.getOperand(0).getValueType();
5790 unsigned NumSubElts = SubVT.getVectorNumElements();
5791 for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) {
5792 APInt DemandedSubElts =
5793 DemandedElts.extractBits(NumSubElts, I * NumSubElts);
5794 if (!!DemandedSubElts &&
5795 !isGuaranteedNotToBeUndefOrPoison(Op.getOperand(I), DemandedSubElts,
5796 Kind, Depth + 1))
5797 return false;
5798 }
5799 return true;
5800 }
5801
5803 SDValue Src = Op.getOperand(0);
5804 if (Src.getValueType().isScalableVector())
5805 break;
5806 uint64_t Idx = Op.getConstantOperandVal(1);
5807 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
5808 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
5809 return isGuaranteedNotToBeUndefOrPoison(Src, DemandedSrcElts, Kind,
5810 Depth + 1);
5811 }
5812
5813 case ISD::INSERT_SUBVECTOR: {
5814 if (Op.getValueType().isScalableVector())
5815 break;
5816 SDValue Src = Op.getOperand(0);
5817 SDValue Sub = Op.getOperand(1);
5818 uint64_t Idx = Op.getConstantOperandVal(2);
5819 unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
5820 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
5821 APInt DemandedSrcElts = DemandedElts;
5822 DemandedSrcElts.clearBits(Idx, Idx + NumSubElts);
5823
5824 if (!!DemandedSubElts && !isGuaranteedNotToBeUndefOrPoison(
5825 Sub, DemandedSubElts, Kind, Depth + 1))
5826 return false;
5827 if (!!DemandedSrcElts && !isGuaranteedNotToBeUndefOrPoison(
5828 Src, DemandedSrcElts, Kind, Depth + 1))
5829 return false;
5830 return true;
5831 }
5832
5834 SDValue Src = Op.getOperand(0);
5835 auto *IndexC = dyn_cast<ConstantSDNode>(Op.getOperand(1));
5836 EVT SrcVT = Src.getValueType();
5837 if (SrcVT.isFixedLengthVector() && IndexC &&
5838 IndexC->getAPIntValue().ult(SrcVT.getVectorNumElements())) {
5839 APInt DemandedSrcElts = APInt::getOneBitSet(SrcVT.getVectorNumElements(),
5840 IndexC->getZExtValue());
5841 return isGuaranteedNotToBeUndefOrPoison(Src, DemandedSrcElts, Kind,
5842 Depth + 1);
5843 }
5844 break;
5845 }
5846
5848 SDValue InVec = Op.getOperand(0);
5849 SDValue InVal = Op.getOperand(1);
5850 SDValue EltNo = Op.getOperand(2);
5851 EVT VT = InVec.getValueType();
5852 auto *IndexC = dyn_cast<ConstantSDNode>(EltNo);
5853 if (IndexC && VT.isFixedLengthVector() &&
5854 IndexC->getAPIntValue().ult(VT.getVectorNumElements())) {
5855 if (DemandedElts[IndexC->getZExtValue()] &&
5856 !isGuaranteedNotToBeUndefOrPoison(InVal, Kind, Depth + 1))
5857 return false;
5858 APInt InVecDemandedElts = DemandedElts;
5859 InVecDemandedElts.clearBit(IndexC->getZExtValue());
5860 if (!!InVecDemandedElts &&
5862 peekThroughInsertVectorElt(InVec, InVecDemandedElts),
5863 InVecDemandedElts, Kind, Depth + 1))
5864 return false;
5865 return true;
5866 }
5867 break;
5868 }
5869
5871 // Check upper (known poison) elements.
5872 if (DemandedElts.ugt(1) && includesPoison(Kind))
5873 return false;
5874 // Check element zero.
5875 if (DemandedElts[0] &&
5876 !isGuaranteedNotToBeUndefOrPoison(Op.getOperand(0), Kind, Depth + 1))
5877 return false;
5878 return true;
5879
5880 case ISD::SPLAT_VECTOR:
5881 return isGuaranteedNotToBeUndefOrPoison(Op.getOperand(0), Kind, Depth + 1);
5882
5883 case ISD::SELECT: {
5884 return !canCreateUndefOrPoison(Op, DemandedElts, Kind,
5885 /*ConsiderFlags*/ true, Depth) &&
5886 isGuaranteedNotToBeUndefOrPoison(Op.getOperand(0), Kind,
5887 Depth + 1) &&
5888 isGuaranteedNotToBeUndefOrPoison(Op.getOperand(1), DemandedElts,
5889 Kind, Depth + 1) &&
5890 isGuaranteedNotToBeUndefOrPoison(Op.getOperand(2), DemandedElts,
5891 Kind, Depth + 1);
5892 }
5893
5894 case ISD::VECTOR_SHUFFLE: {
5895 APInt DemandedLHS, DemandedRHS;
5896 auto *SVN = cast<ShuffleVectorSDNode>(Op);
5897 if (!getShuffleDemandedElts(NumElts, SVN->getMask(), DemandedElts,
5898 DemandedLHS, DemandedRHS,
5899 /*AllowUndefElts=*/false))
5900 return false;
5901 if (!DemandedLHS.isZero() &&
5902 !isGuaranteedNotToBeUndefOrPoison(Op.getOperand(0), DemandedLHS, Kind,
5903 Depth + 1))
5904 return false;
5905 if (!DemandedRHS.isZero() &&
5906 !isGuaranteedNotToBeUndefOrPoison(Op.getOperand(1), DemandedRHS, Kind,
5907 Depth + 1))
5908 return false;
5909 return true;
5910 }
5911
5912 case ISD::SHL:
5913 case ISD::SRL:
5914 case ISD::SRA:
5915 // Shift amount operand is checked by canCreateUndefOrPoison. So it is
5916 // enough to check operand 0 if Op can't create undef/poison.
5917 return !canCreateUndefOrPoison(Op, DemandedElts, Kind,
5918 /*ConsiderFlags*/ true, Depth) &&
5919 isGuaranteedNotToBeUndefOrPoison(Op.getOperand(0), DemandedElts,
5920 Kind, Depth + 1);
5921
5922 case ISD::BSWAP:
5923 case ISD::CTPOP:
5924 case ISD::BITREVERSE:
5925 case ISD::AND:
5926 case ISD::OR:
5927 case ISD::XOR:
5928 case ISD::ADD:
5929 case ISD::SUB:
5930 case ISD::MUL:
5931 case ISD::SADDSAT:
5932 case ISD::UADDSAT:
5933 case ISD::SSUBSAT:
5934 case ISD::USUBSAT:
5935 case ISD::SSHLSAT:
5936 case ISD::USHLSAT:
5937 case ISD::SMIN:
5938 case ISD::SMAX:
5939 case ISD::UMIN:
5940 case ISD::UMAX:
5941 case ISD::ZERO_EXTEND:
5942 case ISD::SIGN_EXTEND:
5943 case ISD::ANY_EXTEND:
5944 case ISD::TRUNCATE:
5945 case ISD::VSELECT: {
5946 // If Op can't create undef/poison and none of its operands are undef/poison
5947 // then Op is never undef/poison. A difference from the more common check
5948 // below, outside the switch, is that we handle elementwise operations for
5949 // which the DemandedElts mask is valid for all operands here.
5950 return !canCreateUndefOrPoison(Op, DemandedElts, Kind,
5951 /*ConsiderFlags*/ true, Depth) &&
5952 all_of(Op->ops(), [&](SDValue V) {
5953 return isGuaranteedNotToBeUndefOrPoison(V, DemandedElts, Kind,
5954 Depth + 1);
5955 });
5956 }
5957
5958 case ISD::LOAD: {
5959 // If we're loading an unindexed constant pool, check if the constant
5960 // contains poison/undef - skip ANYEXT loads.
5961 // TODO: type size mismatch handling.
5962 auto *LD = cast<LoadSDNode>(Op);
5963 if (ISD::isUNINDEXEDLoad(LD) && !ISD::isEXTLoad(LD)) {
5964 if (const Constant *Cst = TLI->getTargetConstantFromLoad(LD)) {
5965 EVT VT = Op.getValueType();
5966 Type *CstTy = Cst->getType();
5967
5968 auto IsSafe = [Kind](const Constant *C) -> bool {
5969 // TODO: expose isGuaranteedNotToBeUndefOrPoison(UndefPoisonKind)
5970 if (includesPoison(Kind) && includesUndef(Kind))
5971 return ::isGuaranteedNotToBeUndefOrPoison(C);
5972 if (includesPoison(Kind))
5973 return ::isGuaranteedNotToBePoison(C);
5974 assert(includesUndef(Kind) && "UndefOnly expected");
5975 return ::isGuaranteedNotToBeUndef(C);
5976 };
5977
5978 // If Cst matches VT vector dimensions, then check per-element.
5979 if (CstTy->isVectorTy() && VT.isFixedLengthVector() &&
5980 VT.getSizeInBits() == CstTy->getPrimitiveSizeInBits() &&
5981 VT.getScalarSizeInBits() == CstTy->getScalarSizeInBits()) {
5982 for (unsigned I = 0; I != NumElts; ++I) {
5983 if (!DemandedElts[I])
5984 continue;
5985 if (Constant *Elt = Cst->getAggregateElement(I)) {
5986 if (IsSafe(Elt))
5987 continue;
5988 }
5989 return false;
5990 }
5991 } else {
5992 return IsSafe(Cst);
5993 }
5994 }
5995 }
5996 break;
5997 }
5998
5999 // TODO: Search for noundef attributes from library functions.
6000
6001 // TODO: Pointers dereferenced by ISD::LOAD/STORE ops are noundef.
6002
6003 default:
6004 // Allow the target to implement this method for its nodes.
6005 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
6006 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID)
6007 return TLI->isGuaranteedNotToBeUndefOrPoisonForTargetNode(
6008 Op, DemandedElts, *this, Kind, Depth);
6009 break;
6010 }
6011
6012 // If Op can't create undef/poison and none of its operands are undef/poison
6013 // then Op is never undef/poison.
6014 // NOTE: TargetNodes can handle this in themselves in
6015 // isGuaranteedNotToBeUndefOrPoisonForTargetNode or let
6016 // TargetLowering::isGuaranteedNotToBeUndefOrPoisonForTargetNode handle it.
6017 return !canCreateUndefOrPoison(Op, Kind, /*ConsiderFlags*/ true, Depth) &&
6018 all_of(Op->ops(), [&](SDValue V) {
6019 return isGuaranteedNotToBeUndefOrPoison(V, Kind, Depth + 1);
6020 });
6021}
6022
6024 bool ConsiderFlags,
6025 unsigned Depth) const {
6026 APInt DemandedElts = getDemandAllEltsMask(Op);
6027 return canCreateUndefOrPoison(Op, DemandedElts, Kind, ConsiderFlags, Depth);
6028}
6029
6031 UndefPoisonKind Kind,
6032 bool ConsiderFlags,
6033 unsigned Depth) const {
6034 if (ConsiderFlags && includesPoison(Kind) && Op->hasPoisonGeneratingFlags())
6035 return true;
6036
6037 unsigned Opcode = Op.getOpcode();
6038 switch (Opcode) {
6039 case ISD::AssertSext:
6040 case ISD::AssertZext:
6041 case ISD::AssertAlign:
6043 // Assertion nodes can create poison if the assertion fails.
6044 return includesPoison(Kind);
6045
6046 case ISD::FREEZE:
6050 case ISD::SADDSAT:
6051 case ISD::UADDSAT:
6052 case ISD::SSUBSAT:
6053 case ISD::USUBSAT:
6054 case ISD::MULHU:
6055 case ISD::MULHS:
6056 case ISD::AVGFLOORS:
6057 case ISD::AVGFLOORU:
6058 case ISD::AVGCEILS:
6059 case ISD::AVGCEILU:
6060 case ISD::AVGSUBFLOORS:
6061 case ISD::AVGSUBFLOORU:
6062 case ISD::ABDU:
6063 case ISD::ABDS:
6064 case ISD::SMIN:
6065 case ISD::SMAX:
6066 case ISD::SCMP:
6067 case ISD::UMIN:
6068 case ISD::UMAX:
6069 case ISD::UCMP:
6070 case ISD::AND:
6071 case ISD::XOR:
6072 case ISD::ROTL:
6073 case ISD::ROTR:
6074 case ISD::FSHL:
6075 case ISD::FSHR:
6076 case ISD::BSWAP:
6077 case ISD::CTTZ:
6078 case ISD::CTLZ:
6079 case ISD::CTLS:
6080 case ISD::CTPOP:
6081 case ISD::BITREVERSE:
6082 case ISD::PARITY:
6083 case ISD::SIGN_EXTEND:
6084 case ISD::TRUNCATE:
6088 case ISD::BITCAST:
6089 case ISD::BUILD_VECTOR:
6090 case ISD::BUILD_PAIR:
6091 case ISD::SPLAT_VECTOR:
6092 case ISD::FABS:
6093 case ISD::FCEIL:
6094 case ISD::FFLOOR:
6095 case ISD::FTRUNC:
6096 case ISD::FRINT:
6097 case ISD::FNEARBYINT:
6098 case ISD::FROUND:
6099 case ISD::FROUNDEVEN:
6100 return false;
6101
6102 case ISD::ABS:
6103 // ISD::ABS defines abs(INT_MIN) -> INT_MIN and never generates poison.
6104 // Different to Intrinsic::abs.
6105 return false;
6107 // ABS_MIN_POISON may produce poison if the input is INT_MIN.
6108 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1) <= 1;
6109
6110 case ISD::ADDC:
6111 case ISD::SUBC:
6112 case ISD::ADDE:
6113 case ISD::SUBE:
6114 case ISD::SADDO:
6115 case ISD::SSUBO:
6116 case ISD::SMULO:
6117 case ISD::SADDO_CARRY:
6118 case ISD::SSUBO_CARRY:
6119 case ISD::UADDO:
6120 case ISD::USUBO:
6121 case ISD::UMULO:
6122 case ISD::UADDO_CARRY:
6123 case ISD::USUBO_CARRY:
6124 // No poison on result or overflow flags.
6125 return false;
6126
6127 case ISD::SELECT_CC:
6128 case ISD::SETCC: {
6129 // Integer setcc cannot create undef or poison.
6130 if (Op.getOperand(0).getValueType().isInteger())
6131 return false;
6132
6133 // FP compares are more complicated. They can create poison for nan/infinity
6134 // based on options and flags. The options and flags also cause special
6135 // nonan condition codes to be used. Those condition codes may be preserved
6136 // even if the nonan flag is dropped somewhere.
6137 unsigned CCOp = Opcode == ISD::SETCC ? 2 : 4;
6138 ISD::CondCode CCCode = Op.getOperandCondCode(CCOp);
6139 return (unsigned)CCCode & 0x10U;
6140 }
6141
6142 case ISD::OR:
6143 case ISD::ZERO_EXTEND:
6144 case ISD::SELECT:
6145 case ISD::VSELECT:
6146 case ISD::ADD:
6147 case ISD::SUB:
6148 case ISD::MUL:
6149 case ISD::FNEG:
6150 case ISD::FADD:
6151 case ISD::FSUB:
6152 case ISD::FMUL:
6153 case ISD::FDIV:
6154 case ISD::FREM:
6155 case ISD::FCOPYSIGN:
6156 case ISD::FMA:
6157 case ISD::FMAD:
6158 case ISD::FMULADD:
6159 case ISD::FP_EXTEND:
6160 case ISD::FMINNUM:
6161 case ISD::FMAXNUM:
6162 case ISD::FMINNUM_IEEE:
6163 case ISD::FMAXNUM_IEEE:
6164 case ISD::FMINIMUM:
6165 case ISD::FMAXIMUM:
6166 case ISD::FMINIMUMNUM:
6167 case ISD::FMAXIMUMNUM:
6173 // No poison except from flags (which is handled above)
6174 return false;
6175
6176 case ISD::SHL:
6177 case ISD::SRL:
6178 case ISD::SRA:
6179 // If the max shift amount isn't in range, then the shift can
6180 // create poison.
6181 return includesPoison(Kind) &&
6182 !getValidMaximumShiftAmount(Op, DemandedElts, Depth + 1);
6183
6186 // If the amount is zero then the result will be poison.
6187 // TODO: Add isKnownNeverZero DemandedElts handling.
6188 return includesPoison(Kind) &&
6189 !isKnownNeverZero(Op.getOperand(0), Depth + 1);
6190
6192 // Check if we demand any upper (poison) elements.
6193 return includesPoison(Kind) && DemandedElts.ugt(1);
6194
6197 // Ensure that the element index is in bounds.
6198 if (includesPoison(Kind)) {
6199 EVT VecVT = Op.getOperand(0).getValueType();
6200 SDValue Idx = Op.getOperand(Opcode == ISD::INSERT_VECTOR_ELT ? 2 : 1);
6201 KnownBits KnownIdx = computeKnownBits(Idx, Depth + 1);
6202 return KnownIdx.getMaxValue().uge(VecVT.getVectorMinNumElements());
6203 }
6204 return false;
6205 }
6206
6207 case ISD::VECTOR_SHUFFLE: {
6208 // Check for any demanded shuffle element that is undef.
6209 auto *SVN = cast<ShuffleVectorSDNode>(Op);
6210 for (auto [Idx, Elt] : enumerate(SVN->getMask()))
6211 if (Elt < 0 && DemandedElts[Idx])
6212 return true;
6213 return false;
6214 }
6215
6217 return false;
6218
6219 default:
6220 // Allow the target to implement this method for its nodes.
6221 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
6222 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID)
6223 return TLI->canCreateUndefOrPoisonForTargetNode(
6224 Op, DemandedElts, *this, Kind, ConsiderFlags, Depth);
6225 break;
6226 }
6227
6228 // Be conservative and return true.
6229 return true;
6230}
6231
6232bool SelectionDAG::isADDLike(SDValue Op, bool NoWrap) const {
6233 unsigned Opcode = Op.getOpcode();
6234 if (Opcode == ISD::OR)
6235 return Op->getFlags().hasDisjoint() ||
6236 haveNoCommonBitsSet(Op.getOperand(0), Op.getOperand(1));
6237 if (Opcode == ISD::XOR)
6238 return !NoWrap && isMinSignedConstant(Op.getOperand(1));
6239 return false;
6240}
6241
6243 return Op.getNumOperands() == 2 && isa<ConstantSDNode>(Op.getOperand(1)) &&
6244 (Op.isAnyAdd() || isADDLike(Op));
6245}
6246
6248 FPClassTest InterestedClasses,
6249 unsigned Depth) const {
6250 APInt DemandedElts = getDemandAllEltsMask(Op);
6251 return computeKnownFPClass(Op, DemandedElts, InterestedClasses, Depth);
6252}
6253
6255 const APInt &DemandedElts,
6256 FPClassTest InterestedClasses,
6257 unsigned Depth) const {
6259
6260 if (const auto *CFP = dyn_cast<ConstantFPSDNode>(Op))
6261 return KnownFPClass(CFP->getValueAPF());
6262
6263 if (Depth >= MaxRecursionDepth)
6264 return Known;
6265
6266 if (Op.getOpcode() == ISD::UNDEF)
6267 return Known;
6268
6269 EVT VT = Op.getValueType();
6270 assert(VT.isFloatingPoint() && "Computing KnownFPClass on non-FP op!");
6271 assert((!VT.isFixedLengthVector() ||
6272 DemandedElts.getBitWidth() == VT.getVectorNumElements()) &&
6273 "Unexpected vector size");
6274
6275 if (!DemandedElts)
6276 return Known;
6277
6278 unsigned Opcode = Op.getOpcode();
6279 switch (Opcode) {
6280 case ISD::POISON: {
6282 break;
6283 }
6284 case ISD::FNEG: {
6285 Known = computeKnownFPClass(Op.getOperand(0), DemandedElts,
6286 InterestedClasses, Depth + 1);
6287 Known.fneg();
6288 break;
6289 }
6290 case ISD::BUILD_VECTOR: {
6291 assert(!VT.isScalableVector());
6292 bool First = true;
6293 for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) {
6294 if (!DemandedElts[I])
6295 continue;
6296
6297 if (First) {
6298 Known =
6299 computeKnownFPClass(Op.getOperand(I), InterestedClasses, Depth + 1);
6300 First = false;
6301 } else {
6302 Known |=
6303 computeKnownFPClass(Op.getOperand(I), InterestedClasses, Depth + 1);
6304 }
6305
6306 if (Known.isUnknown())
6307 break;
6308 }
6309 break;
6310 }
6312 SDValue Src = Op.getOperand(0);
6313 auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6314 EVT SrcVT = Src.getValueType();
6315 if (SrcVT.isFixedLengthVector() && CIdx) {
6316 if (CIdx->getAPIntValue().ult(SrcVT.getVectorNumElements())) {
6317 APInt DemandedSrcElts = APInt::getOneBitSet(
6318 SrcVT.getVectorNumElements(), CIdx->getZExtValue());
6319 Known = computeKnownFPClass(Src, DemandedSrcElts, InterestedClasses,
6320 Depth + 1);
6321 } else {
6322 // Out of bounds index is poison.
6324 }
6325 } else {
6326 Known = computeKnownFPClass(Src, InterestedClasses, Depth + 1);
6327 }
6328 break;
6329 }
6330 case ISD::SPLAT_VECTOR: {
6331 Known = computeKnownFPClass(Op.getOperand(0), InterestedClasses, Depth + 1);
6332 break;
6333 }
6334 case ISD::BITCAST: {
6335 // FIXME: It should not be necessary to check for an elementwise bitcast.
6336 // If a bitcast is not elementwise between vector / scalar types,
6337 // computeKnownBits already splices the known bits of the source elements
6338 // appropriately so as to line up with the bits of the result's demanded
6339 // elements.
6340 EVT SrcVT = Op.getOperand(0).getValueType();
6341 if (VT.isScalableVector() || SrcVT.isScalableVector())
6342 break;
6343 unsigned VTNumElts = VT.isVector() ? VT.getVectorNumElements() : 1;
6344 unsigned SrcVTNumElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1;
6345 if (VTNumElts != SrcVTNumElts)
6346 break;
6347
6348 KnownBits Bits = computeKnownBits(Op, DemandedElts, Depth + 1);
6350 break;
6351 }
6352 case ISD::FABS: {
6353 Known = computeKnownFPClass(Op.getOperand(0), DemandedElts,
6354 InterestedClasses, Depth + 1);
6355 Known.fabs();
6356 break;
6357 }
6358 case ISD::FCOPYSIGN: {
6359 Known = computeKnownFPClass(Op.getOperand(0), DemandedElts,
6360 InterestedClasses, Depth + 1);
6361 KnownFPClass KnownSign = computeKnownFPClass(Op.getOperand(1), DemandedElts,
6362 InterestedClasses, Depth + 1);
6363 Known.copysign(KnownSign);
6364 break;
6365 }
6366 case ISD::AssertNoFPClass: {
6367 Known = computeKnownFPClass(Op.getOperand(0), DemandedElts,
6368 InterestedClasses, Depth + 1);
6369 FPClassTest AssertedClasses =
6370 static_cast<FPClassTest>(Op->getConstantOperandVal(1));
6371 Known.setKnownFPClasses(Known.getKnownFPClasses() & ~AssertedClasses);
6372 break;
6373 }
6375 SDValue Src = Op.getOperand(0);
6376 EVT SrcVT = Src.getValueType();
6377 if (SrcVT.isFixedLengthVector()) {
6378 unsigned Idx = Op.getConstantOperandVal(1);
6379 unsigned NumSrcElts = SrcVT.getVectorNumElements();
6380
6381 APInt DemandedSrcElts = DemandedElts.zextOrTrunc(NumSrcElts).shl(Idx);
6382 Known = computeKnownFPClass(Src, DemandedSrcElts, InterestedClasses,
6383 Depth + 1);
6384 } else {
6385 Known = computeKnownFPClass(Src, InterestedClasses, Depth + 1);
6386 }
6387 break;
6388 }
6389 case ISD::INSERT_SUBVECTOR: {
6390 SDValue BaseVector = Op.getOperand(0);
6391 SDValue SubVector = Op.getOperand(1);
6392 EVT BaseVT = BaseVector.getValueType();
6393 if (BaseVT.isFixedLengthVector()) {
6394 unsigned Idx = Op.getConstantOperandVal(2);
6395 unsigned NumBaseElts = BaseVT.getVectorNumElements();
6396 unsigned NumSubElts = SubVector.getValueType().getVectorNumElements();
6397
6398 APInt DemandedMask =
6399 APInt::getBitsSet(NumBaseElts, Idx, Idx + NumSubElts);
6400 APInt DemandedSrcElts = DemandedElts & ~DemandedMask;
6401 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
6402
6403 if (!DemandedSrcElts.isZero())
6404 Known = computeKnownFPClass(BaseVector, DemandedSrcElts,
6405 InterestedClasses, Depth + 1);
6406 if (!DemandedSubElts.isZero()) {
6408 SubVector, DemandedSubElts, InterestedClasses, Depth + 1);
6409 Known = DemandedSrcElts.isZero() ? SubKnown : (Known | SubKnown);
6410 }
6411 } else {
6412 Known = computeKnownFPClass(SubVector, InterestedClasses, Depth + 1);
6413 if (!Known.isUnknown())
6414 Known |= computeKnownFPClass(BaseVector, InterestedClasses, Depth + 1);
6415 }
6416 break;
6417 }
6418 case ISD::SELECT:
6419 case ISD::VSELECT: {
6420 // TODO: Add adjustKnownFPClassForSelectArm clamp recognition as in
6421 // IR-level ValueTracking.
6422 KnownFPClass KnownFalseClass = computeKnownFPClass(
6423 Op.getOperand(2), DemandedElts, InterestedClasses, Depth + 1);
6424 if (KnownFalseClass.isUnknown())
6425 break;
6426 KnownFPClass KnownTrueClass = computeKnownFPClass(
6427 Op.getOperand(1), DemandedElts, InterestedClasses, Depth + 1);
6428 Known = KnownTrueClass.intersectWith(KnownFalseClass);
6429 break;
6430 }
6431 default:
6432 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
6433 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID) {
6434 TLI->computeKnownFPClassForTargetNode(Op, Known, DemandedElts, *this,
6435 Depth);
6436 }
6437 break;
6438 }
6439
6440 return Known;
6441}
6442
6444 unsigned Depth) const {
6445 APInt DemandedElts = getDemandAllEltsMask(Op);
6446 return isKnownNeverNaN(Op, DemandedElts, SNaN, Depth);
6447}
6448
6450 bool SNaN, unsigned Depth) const {
6451 assert(!DemandedElts.isZero() && "No demanded elements");
6452
6453 // If we're told that NaNs won't happen, assume they won't.
6454 if (Op->getFlags().hasNoNaNs())
6455 return true;
6456
6457 if (Depth >= MaxRecursionDepth)
6458 return false; // Limit search depth.
6459
6460 unsigned Opcode = Op.getOpcode();
6461 switch (Opcode) {
6462 case ISD::FADD:
6463 case ISD::FSUB:
6464 case ISD::FMUL:
6465 case ISD::FDIV:
6466 case ISD::FREM:
6467 case ISD::FSIN:
6468 case ISD::FCOS:
6469 case ISD::FTAN:
6470 case ISD::FASIN:
6471 case ISD::FACOS:
6472 case ISD::FATAN:
6473 case ISD::FATAN2:
6474 case ISD::FSINH:
6475 case ISD::FCOSH:
6476 case ISD::FTANH:
6477 case ISD::FMA:
6478 case ISD::FMULADD:
6479 case ISD::FMAD: {
6480 if (SNaN)
6481 return true;
6482 // TODO: Need isKnownNeverInfinity
6483 return false;
6484 }
6485 case ISD::FCANONICALIZE:
6486 case ISD::FEXP:
6487 case ISD::FEXP2:
6488 case ISD::FEXP10:
6489 case ISD::FTRUNC:
6490 case ISD::FFLOOR:
6491 case ISD::FCEIL:
6492 case ISD::FROUND:
6493 case ISD::FROUNDEVEN:
6494 case ISD::LROUND:
6495 case ISD::LLROUND:
6496 case ISD::FRINT:
6497 case ISD::LRINT:
6498 case ISD::LLRINT:
6499 case ISD::FNEARBYINT:
6500 case ISD::FLDEXP: {
6501 if (SNaN)
6502 return true;
6503 return isKnownNeverNaN(Op.getOperand(0), DemandedElts, SNaN, Depth + 1);
6504 }
6505 case ISD::FABS:
6506 case ISD::FNEG:
6507 case ISD::FCOPYSIGN: {
6508 return isKnownNeverNaN(Op.getOperand(0), DemandedElts, SNaN, Depth + 1);
6509 }
6510 case ISD::SELECT:
6511 return isKnownNeverNaN(Op.getOperand(1), DemandedElts, SNaN, Depth + 1) &&
6512 isKnownNeverNaN(Op.getOperand(2), DemandedElts, SNaN, Depth + 1);
6513 case ISD::FP_EXTEND:
6514 case ISD::FP_ROUND: {
6515 if (SNaN)
6516 return true;
6517 return isKnownNeverNaN(Op.getOperand(0), DemandedElts, SNaN, Depth + 1);
6518 }
6519 case ISD::SINT_TO_FP:
6520 case ISD::UINT_TO_FP:
6521 return true;
6522 case ISD::FSQRT: // Need is known positive
6523 case ISD::FLOG:
6524 case ISD::FLOG2:
6525 case ISD::FLOG10:
6526 case ISD::FPOWI:
6527 case ISD::FPOW: {
6528 if (SNaN)
6529 return true;
6530 // TODO: Refine on operand
6531 return false;
6532 }
6533 case ISD::FMINNUM:
6534 case ISD::FMAXNUM:
6535 case ISD::FMINIMUMNUM:
6536 case ISD::FMAXIMUMNUM: {
6537 // Only one needs to be known not-nan, since it will be returned if the
6538 // other ends up being one.
6539 return isKnownNeverNaN(Op.getOperand(0), DemandedElts, SNaN, Depth + 1) ||
6540 isKnownNeverNaN(Op.getOperand(1), DemandedElts, SNaN, Depth + 1);
6541 }
6542 case ISD::FMINNUM_IEEE:
6543 case ISD::FMAXNUM_IEEE: {
6544 if (SNaN)
6545 return true;
6546 // This can return a NaN if either operand is an sNaN, or if both operands
6547 // are NaN.
6548 return (isKnownNeverNaN(Op.getOperand(0), DemandedElts, false, Depth + 1) &&
6549 isKnownNeverSNaN(Op.getOperand(1), DemandedElts, Depth + 1)) ||
6550 (isKnownNeverNaN(Op.getOperand(1), DemandedElts, false, Depth + 1) &&
6551 isKnownNeverSNaN(Op.getOperand(0), DemandedElts, Depth + 1));
6552 }
6553 case ISD::FMINIMUM:
6554 case ISD::FMAXIMUM: {
6555 // TODO: Does this quiet or return the origina NaN as-is?
6556 return isKnownNeverNaN(Op.getOperand(0), DemandedElts, SNaN, Depth + 1) &&
6557 isKnownNeverNaN(Op.getOperand(1), DemandedElts, SNaN, Depth + 1);
6558 }
6560 SDValue Src = Op.getOperand(0);
6561 auto *Idx = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6562 EVT SrcVT = Src.getValueType();
6563 if (SrcVT.isFixedLengthVector() && Idx &&
6564 Idx->getAPIntValue().ult(SrcVT.getVectorNumElements())) {
6565 APInt DemandedSrcElts = APInt::getOneBitSet(SrcVT.getVectorNumElements(),
6566 Idx->getZExtValue());
6567 return isKnownNeverNaN(Src, DemandedSrcElts, SNaN, Depth + 1);
6568 }
6569 return isKnownNeverNaN(Src, SNaN, Depth + 1);
6570 }
6572 SDValue Src = Op.getOperand(0);
6573 if (Src.getValueType().isFixedLengthVector()) {
6574 unsigned Idx = Op.getConstantOperandVal(1);
6575 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
6576 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
6577 return isKnownNeverNaN(Src, DemandedSrcElts, SNaN, Depth + 1);
6578 }
6579 return isKnownNeverNaN(Src, SNaN, Depth + 1);
6580 }
6581 case ISD::INSERT_SUBVECTOR: {
6582 SDValue BaseVector = Op.getOperand(0);
6583 SDValue SubVector = Op.getOperand(1);
6584 EVT BaseVectorVT = BaseVector.getValueType();
6585 if (BaseVectorVT.isFixedLengthVector()) {
6586 unsigned Idx = Op.getConstantOperandVal(2);
6587 unsigned NumBaseElts = BaseVectorVT.getVectorNumElements();
6588 unsigned NumSubElts = SubVector.getValueType().getVectorNumElements();
6589
6590 // Clear/Extract the bits at the position where the subvector will be
6591 // inserted.
6592 APInt DemandedMask =
6593 APInt::getBitsSet(NumBaseElts, Idx, Idx + NumSubElts);
6594 APInt DemandedSrcElts = DemandedElts & ~DemandedMask;
6595 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
6596
6597 bool NeverNaN = true;
6598 if (!DemandedSrcElts.isZero())
6599 NeverNaN &=
6600 isKnownNeverNaN(BaseVector, DemandedSrcElts, SNaN, Depth + 1);
6601 if (NeverNaN && !DemandedSubElts.isZero())
6602 NeverNaN &=
6603 isKnownNeverNaN(SubVector, DemandedSubElts, SNaN, Depth + 1);
6604 return NeverNaN;
6605 }
6606 return isKnownNeverNaN(BaseVector, SNaN, Depth + 1) &&
6607 isKnownNeverNaN(SubVector, SNaN, Depth + 1);
6608 }
6609 case ISD::BUILD_VECTOR: {
6610 unsigned NumElts = Op.getNumOperands();
6611 for (unsigned I = 0; I != NumElts; ++I)
6612 if (DemandedElts[I] &&
6613 !isKnownNeverNaN(Op.getOperand(I), SNaN, Depth + 1))
6614 return false;
6615 return true;
6616 }
6617 case ISD::SPLAT_VECTOR:
6618 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
6619 case ISD::AssertNoFPClass: {
6620 FPClassTest NoFPClass =
6621 static_cast<FPClassTest>(Op.getConstantOperandVal(1));
6622 if ((NoFPClass & fcNan) == fcNan)
6623 return true;
6624 if (SNaN && (NoFPClass & fcSNan) == fcSNan)
6625 return true;
6626 return isKnownNeverNaN(Op.getOperand(0), DemandedElts, SNaN, Depth + 1);
6627 }
6628 default:
6629 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
6630 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID) {
6631 return TLI->isKnownNeverNaNForTargetNode(Op, DemandedElts, *this, SNaN,
6632 Depth);
6633 }
6634 break;
6635 }
6636
6637 FPClassTest NanMask = SNaN ? fcSNan : fcNan;
6638 KnownFPClass Known = computeKnownFPClass(Op, DemandedElts, NanMask, Depth);
6639 return Known.isKnownNever(NanMask);
6640}
6641
6643 APInt DemandedElts = getDemandAllEltsMask(Op);
6644 return isKnownNeverLogicalZero(Op, DemandedElts, Depth);
6645}
6646
6648 const APInt &DemandedElts,
6649 unsigned Depth) const {
6650 assert(!DemandedElts.isZero() && "No demanded elements");
6651 EVT VT = Op.getValueType();
6653 computeKnownFPClass(Op, DemandedElts, fcZero | fcSubnormal, Depth);
6654 return Known.isKnownNeverLogicalZero(getDenormalMode(VT));
6655}
6656
6658 APInt DemandedElts = getDemandAllEltsMask(Op);
6659 return isKnownNeverZero(Op, DemandedElts, Depth);
6660}
6661
6663 unsigned Depth) const {
6664 if (Depth >= MaxRecursionDepth)
6665 return false; // Limit search depth.
6666
6667 EVT OpVT = Op.getValueType();
6668 unsigned BitWidth = OpVT.getScalarSizeInBits();
6669
6670 assert(!Op.getValueType().isFloatingPoint() &&
6671 "Floating point types unsupported - use isKnownNeverLogicalZero");
6672
6673 // If the value is a constant, we can obviously see if it is a zero or not.
6674 auto IsNeverZero = [BitWidth](const ConstantSDNode *C) {
6675 APInt V = C->getAPIntValue().zextOrTrunc(BitWidth);
6676 return !V.isZero();
6677 };
6678
6679 if (ISD::matchUnaryPredicate(Op, DemandedElts, IsNeverZero,
6680 /*AllowUndefs=*/false, /*AllowTruncation=*/true))
6681 return true;
6682
6683 // TODO: Recognize more cases here. Most of the cases are also incomplete to
6684 // some degree.
6685 switch (Op.getOpcode()) {
6686 default:
6687 break;
6688
6690 SDValue InVec = Op.getOperand(0);
6691 SDValue EltNo = Op.getOperand(1);
6692 EVT VecVT = InVec.getValueType();
6693
6694 // Skip scalable vectors or implicit extensions.
6695 if (VecVT.isScalableVector() ||
6696 OpVT.getScalarSizeInBits() != VecVT.getScalarSizeInBits())
6697 break;
6698
6699 // If we know the element index, just demand that vector element, else for
6700 // an unknown element index, ignore DemandedElts and demand them all.
6701 const unsigned NumSrcElts = VecVT.getVectorNumElements();
6702 APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
6703 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
6704 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
6705 DemandedSrcElts =
6706 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
6707
6708 return isKnownNeverZero(InVec, DemandedSrcElts, Depth + 1);
6709 }
6710
6711 case ISD::OR:
6712 return isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1) ||
6713 isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6714
6715 case ISD::VSELECT:
6716 case ISD::SELECT:
6717 return isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1) &&
6718 isKnownNeverZero(Op.getOperand(2), DemandedElts, Depth + 1);
6719
6720 case ISD::SHL: {
6721 if (Op->getFlags().hasNoSignedWrap() || Op->getFlags().hasNoUnsignedWrap())
6722 return isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6723 KnownBits ValKnown =
6724 computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
6725 // 1 << X is never zero.
6726 if (ValKnown.One[0])
6727 return true;
6728 // If max shift cnt of known ones is non-zero, result is non-zero.
6729 APInt MaxCnt = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1)
6730 .getMaxValue();
6731 if (MaxCnt.ult(ValKnown.getBitWidth()) &&
6732 !ValKnown.One.shl(MaxCnt).isZero())
6733 return true;
6734 break;
6735 }
6736
6737 case ISD::VECTOR_SHUFFLE: {
6738 if (Op.getValueType().isScalableVector())
6739 return false;
6740
6741 unsigned NumElts = DemandedElts.getBitWidth();
6742
6743 // All demanded elements from LHS and RHS must be known non-zero.
6744 // Demanded elements with undef shuffle mask elements are unknown.
6745
6746 APInt DemandedLHS, DemandedRHS;
6747 auto *SVN = cast<ShuffleVectorSDNode>(Op);
6748 assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
6749 if (!getShuffleDemandedElts(NumElts, SVN->getMask(), DemandedElts,
6750 DemandedLHS, DemandedRHS))
6751 return false;
6752
6753 return (!DemandedLHS ||
6754 isKnownNeverZero(Op.getOperand(0), DemandedLHS, Depth + 1)) &&
6755 (!DemandedRHS ||
6756 isKnownNeverZero(Op.getOperand(1), DemandedRHS, Depth + 1));
6757 }
6758
6759 case ISD::UADDSAT:
6760 case ISD::UMAX:
6761 return isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1) ||
6762 isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6763
6764 case ISD::UMIN:
6765 return isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1) &&
6766 isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6767
6768 // For smin/smax: If either operand is known negative/positive
6769 // respectively we don't need the other to be known at all.
6770 case ISD::SMAX: {
6771 KnownBits Op1 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
6772 if (Op1.isStrictlyPositive())
6773 return true;
6774
6775 KnownBits Op0 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
6776 if (Op0.isStrictlyPositive())
6777 return true;
6778
6779 if (Op1.isNonZero() && Op0.isNonZero())
6780 return true;
6781
6782 return isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1) &&
6783 isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6784 }
6785 case ISD::SMIN: {
6786 KnownBits Op1 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
6787 if (Op1.isNegative())
6788 return true;
6789
6790 KnownBits Op0 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
6791 if (Op0.isNegative())
6792 return true;
6793
6794 if (Op1.isNonZero() && Op0.isNonZero())
6795 return true;
6796
6797 return isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1) &&
6798 isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6799 }
6800
6801 case ISD::ROTL:
6802 case ISD::ROTR:
6803 case ISD::BITREVERSE:
6804 case ISD::BSWAP:
6805 case ISD::CTPOP:
6806 case ISD::ABS:
6808 return isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6809
6810 case ISD::SRA:
6811 case ISD::SRL: {
6812 if (Op->getFlags().hasExact())
6813 return isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6814 KnownBits ValKnown =
6815 computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
6816 if (ValKnown.isNegative())
6817 return true;
6818 // If max shift cnt of known ones is non-zero, result is non-zero.
6819 APInt MaxCnt = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1)
6820 .getMaxValue();
6821 if (MaxCnt.ult(ValKnown.getBitWidth()) &&
6822 !ValKnown.One.lshr(MaxCnt).isZero())
6823 return true;
6824 break;
6825 }
6826 case ISD::UDIV:
6827 case ISD::SDIV:
6828 // div exact can only produce a zero if the dividend is zero.
6829 // TODO: For udiv this is also true if Op1 u<= Op0
6830 if (Op->getFlags().hasExact())
6831 return isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6832 break;
6833
6834 case ISD::ADD:
6835 if (Op->getFlags().hasNoUnsignedWrap())
6836 if (isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1) ||
6837 isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1))
6838 return true;
6839 // TODO: There are a lot more cases we can prove for add.
6840 break;
6841
6842 case ISD::SUB: {
6843 if (isNullConstant(Op.getOperand(0)))
6844 return isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1);
6845
6846 std::optional<bool> ne = KnownBits::ne(
6847 computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1),
6848 computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1));
6849 return ne && *ne;
6850 }
6851
6852 case ISD::MUL:
6853 if (Op->getFlags().hasNoSignedWrap() || Op->getFlags().hasNoUnsignedWrap())
6854 if (isKnownNeverZero(Op.getOperand(1), Depth + 1) &&
6855 isKnownNeverZero(Op.getOperand(0), Depth + 1))
6856 return true;
6857 break;
6858
6859 case ISD::ZERO_EXTEND:
6860 case ISD::SIGN_EXTEND:
6861 return isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6862 case ISD::VSCALE: {
6864 const APInt &Multiplier = Op.getConstantOperandAPInt(0);
6865 ConstantRange CR =
6866 getVScaleRange(&F, Op.getScalarValueSizeInBits()).multiply(Multiplier);
6867 if (!CR.contains(APInt(CR.getBitWidth(), 0)))
6868 return true;
6869 break;
6870 }
6871 }
6872
6873 return computeKnownBits(Op, DemandedElts, Depth).isNonZero();
6874}
6875
6878 return !C1->isNegative();
6879
6880 switch (Op.getOpcode()) {
6881 case ISD::FABS:
6882 case ISD::FEXP:
6883 case ISD::FEXP2:
6884 case ISD::FEXP10:
6885 return true;
6886 default:
6887 return false;
6888 }
6889
6890 llvm_unreachable("covered opcode switch");
6891}
6892
6893/// Return true if the standard nsz semantics may not apply for this opcode.
6894/// Opcode is assumed to take float inputs.
6895/// FIXME: Target min/max nodes (e.g. X86ISD::FMINC) aren't included.
6896static bool hasSpecialNszSemantics(unsigned Opcode) {
6897 switch (Opcode) {
6898 case ISD::FMINNUM:
6899 case ISD::FMAXNUM:
6900 case ISD::FMINNUM_IEEE:
6901 case ISD::FMAXNUM_IEEE:
6902 case ISD::FMINIMUM:
6903 case ISD::FMAXIMUM:
6904 case ISD::FMINIMUMNUM:
6905 case ISD::FMAXIMUMNUM:
6910 case ISD::PSEUDO_FMIN:
6911 case ISD::PSEUDO_FMAX:
6920 case ISD::VP_REDUCE_FMIN:
6921 case ISD::VP_REDUCE_FMAX:
6922 case ISD::VP_REDUCE_FMINIMUM:
6923 case ISD::VP_REDUCE_FMAXIMUM:
6924 return true;
6925 default:
6926 return false;
6927 }
6928}
6929
6931 assert(Use.getValueType().isFloatingPoint());
6932 const SDNode *User = Use.getUser();
6933 unsigned Opcode = User->getOpcode();
6934 if (User->getFlags().hasNoSignedZeros() && !hasSpecialNszSemantics(Opcode))
6935 return true;
6936
6937 unsigned OperandNo = Use.getOperandNo();
6938 // Check if this use is insensitive to the sign of zero
6939 switch (Opcode) {
6940 case ISD::SETCC:
6941 // Comparisons: IEEE-754 specifies +0.0 == -0.0.
6942 case ISD::FABS:
6943 // fabs always produces +0.0.
6944 return true;
6945 case ISD::FCOPYSIGN:
6946 // copysign overwrites the sign bit of the first operand.
6947 return OperandNo == 0;
6948 case ISD::FADD:
6949 case ISD::FSUB: {
6950 // Arithmetic with non-zero constants fixes the uncertainty around the
6951 // sign bit.
6952 SDValue Other = User->getOperand(1 - OperandNo);
6954 }
6955 case ISD::FP_TO_SINT:
6956 case ISD::FP_TO_UINT:
6957 // fp-to-int conversions normalize signed zeros.
6958 return true;
6959 case ISD::FMINNUM:
6960 case ISD::FMINNUM_IEEE:
6961 case ISD::FMINIMUM:
6962 case ISD::FMINIMUMNUM:
6963 case ISD::FMAXNUM:
6964 case ISD::FMAXNUM_IEEE:
6965 case ISD::FMAXIMUM:
6966 case ISD::FMAXIMUMNUM:
6967 case ISD::PSEUDO_FMIN:
6968 case ISD::PSEUDO_FMAX: {
6969 // If other value always beats zero, the zero can be ignored.
6970 bool IsMin = Opcode == ISD::FMINNUM || Opcode == ISD::FMINNUM_IEEE ||
6971 Opcode == ISD::FMINIMUM || Opcode == ISD::FMINIMUMNUM ||
6972 Opcode == ISD::PSEUDO_FMIN;
6973 FPClassTest AlwaysBeatsZero =
6975 SDValue Other = User->getOperand(1 - OperandNo);
6976 KnownFPClass Known = computeKnownFPClass(Other, ~AlwaysBeatsZero);
6977 return Known.isKnownNever(~AlwaysBeatsZero);
6978 }
6979 default:
6980 return false;
6981 }
6982}
6983
6985 assert(Op->getNumValues() == 1);
6986 // FIXME: Limit the amount of checked uses to not introduce a compile-time
6987 // regression. Ideally, this should be implemented as a demanded-bits
6988 // optimization that stems from the users.
6989 if (Op->use_size() > 2)
6990 return false;
6991 return all_of(Op->uses(),
6992 [&](const SDUse &Use) { return canIgnoreSignBitOfZero(Use); });
6993}
6994
6996 // Check the obvious case.
6997 if (A == B) return true;
6998
6999 // For negative and positive zero.
7002 if (CA->isZero() && CB->isZero()) return true;
7003
7004 // Otherwise they may not be equal.
7005 return false;
7006}
7007
7008// Only bits set in Mask must be negated, other bits may be arbitrary.
7010 if (isBitwiseNot(V, AllowUndefs))
7011 return V.getOperand(0);
7012
7013 // Handle any_extend (not (truncate X)) pattern, where Mask only sets
7014 // bits in the non-extended part.
7015 ConstantSDNode *MaskC = isConstOrConstSplat(Mask);
7016 if (!MaskC || V.getOpcode() != ISD::ANY_EXTEND)
7017 return SDValue();
7018 SDValue ExtArg = V.getOperand(0);
7019 if (ExtArg.getScalarValueSizeInBits() >=
7020 MaskC->getAPIntValue().getActiveBits() &&
7021 isBitwiseNot(ExtArg, AllowUndefs) &&
7022 ExtArg.getOperand(0).getOpcode() == ISD::TRUNCATE &&
7023 ExtArg.getOperand(0).getOperand(0).getValueType() == V.getValueType())
7024 return ExtArg.getOperand(0).getOperand(0);
7025 return SDValue();
7026}
7027
7029 // Match masked merge pattern (X & ~M) op (Y & M)
7030 // Including degenerate case (X & ~M) op M
7031 auto MatchNoCommonBitsPattern = [&](SDValue Not, SDValue Mask,
7032 SDValue Other) {
7033 if (SDValue NotOperand =
7034 getBitwiseNotOperand(Not, Mask, /* AllowUndefs */ true)) {
7035 if (NotOperand->getOpcode() == ISD::ZERO_EXTEND ||
7036 NotOperand->getOpcode() == ISD::TRUNCATE)
7037 NotOperand = NotOperand->getOperand(0);
7038
7039 if (Other == NotOperand)
7040 return true;
7041 if (Other->getOpcode() == ISD::AND)
7042 return NotOperand == Other->getOperand(0) ||
7043 NotOperand == Other->getOperand(1);
7044 }
7045 return false;
7046 };
7047
7048 if (A->getOpcode() == ISD::ZERO_EXTEND || A->getOpcode() == ISD::TRUNCATE)
7049 A = A->getOperand(0);
7050
7051 if (B->getOpcode() == ISD::ZERO_EXTEND || B->getOpcode() == ISD::TRUNCATE)
7052 B = B->getOperand(0);
7053
7054 if (A->getOpcode() == ISD::AND)
7055 return MatchNoCommonBitsPattern(A->getOperand(0), A->getOperand(1), B) ||
7056 MatchNoCommonBitsPattern(A->getOperand(1), A->getOperand(0), B);
7057 return false;
7058}
7059
7060// FIXME: unify with llvm::haveNoCommonBitsSet.
7062 assert(A.getValueType() == B.getValueType() &&
7063 "Values must have the same type");
7066 return true;
7069}
7070
7071static SDValue FoldSTEP_VECTOR(const SDLoc &DL, EVT VT, SDValue Step,
7072 SelectionDAG &DAG) {
7073 if (cast<ConstantSDNode>(Step)->isZero())
7074 return DAG.getConstant(0, DL, VT);
7075
7076 return SDValue();
7077}
7078
7081 SelectionDAG &DAG) {
7082 int NumOps = Ops.size();
7083 assert(NumOps != 0 && "Can't build an empty vector!");
7084 assert(!VT.isScalableVector() &&
7085 "BUILD_VECTOR cannot be used with scalable types");
7086 assert(VT.getVectorNumElements() == (unsigned)NumOps &&
7087 "Incorrect element count in BUILD_VECTOR!");
7088
7089 // BUILD_VECTOR of UNDEFs is UNDEF.
7090 bool AllPoison = true;
7091 if (llvm::all_of(Ops, [&AllPoison](SDValue Op) {
7092 AllPoison &= Op.getOpcode() == ISD::POISON;
7093 return Op.isUndef();
7094 }))
7095 return AllPoison ? DAG.getPOISON(VT) : DAG.getUNDEF(VT);
7096
7097 // BUILD_VECTOR of seq extract/insert from the same vector + type is Identity.
7098 SDValue IdentitySrc;
7099 bool IsIdentity = true;
7100 for (int i = 0; i != NumOps; ++i) {
7101 if (Ops[i].getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
7102 Ops[i].getOperand(0).getValueType() != VT ||
7103 (IdentitySrc && Ops[i].getOperand(0) != IdentitySrc) ||
7104 !isa<ConstantSDNode>(Ops[i].getOperand(1)) ||
7105 Ops[i].getConstantOperandAPInt(1) != i) {
7106 IsIdentity = false;
7107 break;
7108 }
7109 IdentitySrc = Ops[i].getOperand(0);
7110 }
7111 if (IsIdentity)
7112 return IdentitySrc;
7113
7114 return SDValue();
7115}
7116
7117/// Try to simplify vector concatenation to an input value, undef, or build
7118/// vector.
7121 SelectionDAG &DAG) {
7122 assert(!Ops.empty() && "Can't concatenate an empty list of vectors!");
7124 [Ops](SDValue Op) {
7125 return Ops[0].getValueType() == Op.getValueType();
7126 }) &&
7127 "Concatenation of vectors with inconsistent value types!");
7128 assert((Ops[0].getValueType().getVectorElementCount() * Ops.size()) ==
7129 VT.getVectorElementCount() &&
7130 "Incorrect element count in vector concatenation!");
7131
7132 if (Ops.size() == 1)
7133 return Ops[0];
7134
7135 // Concat of UNDEFs is UNDEF.
7136 bool AllPoison = true;
7137 if (llvm::all_of(Ops, [&AllPoison](SDValue Op) {
7138 AllPoison &= Op.getOpcode() == ISD::POISON;
7139 return Op.isUndef();
7140 }))
7141 return AllPoison ? DAG.getPOISON(VT) : DAG.getUNDEF(VT);
7142
7143 // Scan the operands and look for extract operations from a single source
7144 // that correspond to insertion at the same location via this concatenation:
7145 // concat (extract X, 0*subvec_elts), (extract X, 1*subvec_elts), ...
7146 SDValue IdentitySrc;
7147 bool IsIdentity = true;
7148 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
7149 SDValue Op = Ops[i];
7150 unsigned IdentityIndex = i * Op.getValueType().getVectorMinNumElements();
7151 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
7152 Op.getOperand(0).getValueType() != VT ||
7153 (IdentitySrc && Op.getOperand(0) != IdentitySrc) ||
7154 Op.getConstantOperandVal(1) != IdentityIndex) {
7155 IsIdentity = false;
7156 break;
7157 }
7158 assert((!IdentitySrc || IdentitySrc == Op.getOperand(0)) &&
7159 "Unexpected identity source vector for concat of extracts");
7160 IdentitySrc = Op.getOperand(0);
7161 }
7162 if (IsIdentity) {
7163 assert(IdentitySrc && "Failed to set source vector of extracts");
7164 return IdentitySrc;
7165 }
7166
7167 // The code below this point is only designed to work for fixed width
7168 // vectors, so we bail out for now.
7169 if (VT.isScalableVector())
7170 return SDValue();
7171
7172 // A CONCAT_VECTOR of scalar sources, such as UNDEF, BUILD_VECTOR and
7173 // single-element INSERT_VECTOR_ELT operands can be simplified to one big
7174 // BUILD_VECTOR.
7175 // FIXME: Add support for SCALAR_TO_VECTOR as well.
7176 EVT SVT = VT.getScalarType();
7178 for (SDValue Op : Ops) {
7179 EVT OpVT = Op.getValueType();
7180 if (Op.getOpcode() == ISD::POISON)
7181 Elts.append(OpVT.getVectorNumElements(), DAG.getPOISON(SVT));
7182 else if (Op.getOpcode() == ISD::UNDEF)
7183 Elts.append(OpVT.getVectorNumElements(), DAG.getUNDEF(SVT));
7184 else if (Op.getOpcode() == ISD::BUILD_VECTOR)
7185 Elts.append(Op->op_begin(), Op->op_end());
7186 else if (Op.getOpcode() == ISD::INSERT_VECTOR_ELT &&
7187 OpVT.getVectorNumElements() == 1 &&
7188 isNullConstant(Op.getOperand(2)))
7189 Elts.push_back(Op.getOperand(1));
7190 else
7191 return SDValue();
7192 }
7193
7194 // BUILD_VECTOR requires all inputs to be of the same type, find the
7195 // maximum type and extend them all.
7196 for (SDValue Op : Elts)
7197 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
7198
7199 if (SVT.bitsGT(VT.getScalarType())) {
7200 for (SDValue &Op : Elts) {
7201 if (Op.getOpcode() == ISD::POISON)
7202 Op = DAG.getPOISON(SVT);
7203 else if (Op.getOpcode() == ISD::UNDEF)
7204 Op = DAG.getUNDEF(SVT);
7205 else
7206 Op = DAG.getTargetLoweringInfo().isZExtFree(Op.getValueType(), SVT)
7207 ? DAG.getZExtOrTrunc(Op, DL, SVT)
7208 : DAG.getSExtOrTrunc(Op, DL, SVT);
7209 }
7210 }
7211
7212 SDValue V = DAG.getBuildVector(VT, DL, Elts);
7213 NewSDValueDbgMsg(V, "New node fold concat vectors: ", &DAG);
7214 return V;
7215}
7216
7217/// Gets or creates the specified node.
7218SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT) {
7219 SDVTList VTs = getVTList(VT);
7220 SDNodeKey ID(Opcode, VTs, {});
7221 FoldingSetInsertToken InsertToken;
7222 if (SDNode *E = lookupNode(ID, DL, InsertToken))
7223 return SDValue(E, 0);
7224
7225 auto *N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
7226 CSEMap.insert(N, InsertToken);
7227
7228 InsertNode(N);
7229 SDValue V = SDValue(N, 0);
7230 NewSDValueDbgMsg(V, "Creating new node: ", this);
7231 return V;
7232}
7233
7234SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
7235 SDValue N1) {
7236 SDNodeFlags Flags;
7237 if (Inserter)
7238 Flags = Inserter->getFlags();
7239 return getNode(Opcode, DL, VT, N1, Flags);
7240}
7241
7242SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
7243 SDValue N1, const SDNodeFlags Flags) {
7244 assert(N1.getOpcode() != ISD::DELETED_NODE && "Operand is DELETED_NODE!");
7245
7246 // Constant fold unary operations with a vector integer or float operand.
7247 switch (Opcode) {
7248 default:
7249 // FIXME: Entirely reasonable to perform folding of other unary
7250 // operations here as the need arises.
7251 break;
7252 case ISD::FNEG:
7253 case ISD::FABS:
7254 case ISD::FCEIL:
7255 case ISD::FTRUNC:
7256 case ISD::FFLOOR:
7257 case ISD::FP_EXTEND:
7258 case ISD::FP_TO_SINT:
7259 case ISD::FP_TO_UINT:
7260 case ISD::FP_TO_FP16:
7261 case ISD::FP_TO_BF16:
7262 case ISD::TRUNCATE:
7263 case ISD::ANY_EXTEND:
7264 case ISD::ZERO_EXTEND:
7265 case ISD::SIGN_EXTEND:
7266 case ISD::UINT_TO_FP:
7267 case ISD::SINT_TO_FP:
7268 case ISD::FP16_TO_FP:
7269 case ISD::BF16_TO_FP:
7270 case ISD::BITCAST:
7271 case ISD::ABS:
7273 case ISD::BITREVERSE:
7274 case ISD::BSWAP:
7275 case ISD::CTLZ:
7277 case ISD::CTTZ:
7279 case ISD::CTPOP:
7280 case ISD::PARITY:
7281 case ISD::CTLS:
7282 case ISD::VECREDUCE_ADD:
7287 case ISD::VECREDUCE_MUL:
7288 case ISD::VECREDUCE_AND:
7289 case ISD::VECREDUCE_OR:
7290 case ISD::VECREDUCE_XOR:
7291 case ISD::STEP_VECTOR: {
7292 SDValue Ops = {N1};
7293 if (SDValue Fold = FoldConstantArithmetic(Opcode, DL, VT, Ops, Flags))
7294 return Fold;
7295 }
7296 }
7297
7298 unsigned OpOpcode = N1.getNode()->getOpcode();
7299 switch (Opcode) {
7300 case ISD::STEP_VECTOR:
7301 assert(VT.isScalableVector() &&
7302 "STEP_VECTOR can only be used with scalable types");
7303 assert(OpOpcode == ISD::TargetConstant &&
7304 VT.getVectorElementType() == N1.getValueType() &&
7305 "Unexpected step operand");
7306 break;
7307 case ISD::FREEZE:
7308 assert(VT == N1.getValueType() && "Unexpected VT!");
7310 return N1;
7311 break;
7312 case ISD::TokenFactor:
7313 case ISD::MERGE_VALUES:
7315 return N1; // Factor, merge or concat of one node? No need.
7316 case ISD::BUILD_VECTOR: {
7317 // Attempt to simplify BUILD_VECTOR.
7318 SDValue Ops[] = {N1};
7319 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
7320 return V;
7321 break;
7322 }
7323 case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node");
7324 case ISD::FP_EXTEND:
7326 "Invalid FP cast!");
7327 if (N1.getValueType() == VT) return N1; // noop conversion.
7328 assert((!VT.isVector() || VT.getVectorElementCount() ==
7330 "Vector element count mismatch!");
7331 assert(N1.getValueType().bitsLT(VT) && "Invalid fpext node, dst < src!");
7332 if (N1.isUndef())
7333 return getUNDEF(VT);
7334 break;
7335 case ISD::FP_TO_SINT:
7336 case ISD::FP_TO_UINT:
7337 if (N1.isUndef())
7338 return getUNDEF(VT);
7339 break;
7340 case ISD::SINT_TO_FP:
7341 case ISD::UINT_TO_FP:
7342 // [us]itofp(undef) = 0, because the result value is bounded.
7343 if (N1.isUndef())
7344 return getConstantFP(0.0, DL, VT);
7345 break;
7346 case ISD::SIGN_EXTEND:
7347 assert(VT.isInteger() && N1.getValueType().isInteger() &&
7348 "Invalid SIGN_EXTEND!");
7349 assert(VT.isVector() == N1.getValueType().isVector() &&
7350 "SIGN_EXTEND result type type should be vector iff the operand "
7351 "type is vector!");
7352 if (N1.getValueType() == VT) return N1; // noop extension
7353 assert((!VT.isVector() || VT.getVectorElementCount() ==
7355 "Vector element count mismatch!");
7356 assert(N1.getValueType().bitsLT(VT) && "Invalid sext node, dst < src!");
7357 if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND) {
7358 SDNodeFlags Flags;
7359 if (OpOpcode == ISD::ZERO_EXTEND)
7360 Flags.setNonNeg(N1->getFlags().hasNonNeg());
7361 SDValue NewVal = getNode(OpOpcode, DL, VT, N1.getOperand(0), Flags);
7362 transferDbgValues(N1, NewVal);
7363 return NewVal;
7364 }
7365
7366 if (OpOpcode == ISD::POISON)
7367 return getPOISON(VT);
7368
7369 if (N1.isUndef())
7370 // sext(undef) = 0, because the top bits will all be the same.
7371 return getConstant(0, DL, VT);
7372
7373 // Skip unnecessary sext_inreg pattern:
7374 // (sext (trunc x)) -> x iff the upper bits are all signbits.
7375 if (OpOpcode == ISD::TRUNCATE) {
7376 SDValue OpOp = N1.getOperand(0);
7377 if (OpOp.getValueType() == VT) {
7378 unsigned NumSignExtBits =
7380 if (ComputeNumSignBits(OpOp) > NumSignExtBits) {
7381 transferDbgValues(N1, OpOp);
7382 return OpOp;
7383 }
7384 }
7385 }
7386 break;
7387 case ISD::ZERO_EXTEND:
7388 assert(VT.isInteger() && N1.getValueType().isInteger() &&
7389 "Invalid ZERO_EXTEND!");
7390 assert(VT.isVector() == N1.getValueType().isVector() &&
7391 "ZERO_EXTEND result type type should be vector iff the operand "
7392 "type is vector!");
7393 if (N1.getValueType() == VT) return N1; // noop extension
7394 assert((!VT.isVector() || VT.getVectorElementCount() ==
7396 "Vector element count mismatch!");
7397 assert(N1.getValueType().bitsLT(VT) && "Invalid zext node, dst < src!");
7398 if (OpOpcode == ISD::ZERO_EXTEND) { // (zext (zext x)) -> (zext x)
7399 SDNodeFlags Flags;
7400 Flags.setNonNeg(N1->getFlags().hasNonNeg());
7401 SDValue NewVal =
7402 getNode(ISD::ZERO_EXTEND, DL, VT, N1.getOperand(0), Flags);
7403 transferDbgValues(N1, NewVal);
7404 return NewVal;
7405 }
7406
7407 if (OpOpcode == ISD::POISON)
7408 return getPOISON(VT);
7409
7410 if (N1.isUndef())
7411 // zext(undef) = 0, because the top bits will be zero.
7412 return getConstant(0, DL, VT);
7413
7414 // Skip unnecessary zext_inreg pattern:
7415 // (zext (trunc x)) -> x iff the upper bits are known zero.
7416 // TODO: Remove (zext (trunc (and x, c))) exception which some targets
7417 // use to recognise zext_inreg patterns.
7418 if (OpOpcode == ISD::TRUNCATE) {
7419 SDValue OpOp = N1.getOperand(0);
7420 if (OpOp.getValueType() == VT) {
7421 if (OpOp.getOpcode() != ISD::AND) {
7424 if (MaskedValueIsZero(OpOp, HiBits)) {
7425 transferDbgValues(N1, OpOp);
7426 return OpOp;
7427 }
7428 }
7429 }
7430 }
7431 break;
7432 case ISD::ANY_EXTEND:
7433 assert(VT.isInteger() && N1.getValueType().isInteger() &&
7434 "Invalid ANY_EXTEND!");
7435 assert(VT.isVector() == N1.getValueType().isVector() &&
7436 "ANY_EXTEND result type type should be vector iff the operand "
7437 "type is vector!");
7438 if (N1.getValueType() == VT) return N1; // noop extension
7439 assert((!VT.isVector() || VT.getVectorElementCount() ==
7441 "Vector element count mismatch!");
7442 assert(N1.getValueType().bitsLT(VT) && "Invalid anyext node, dst < src!");
7443
7444 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
7445 OpOpcode == ISD::ANY_EXTEND) {
7446 SDNodeFlags Flags;
7447 if (OpOpcode == ISD::ZERO_EXTEND)
7448 Flags.setNonNeg(N1->getFlags().hasNonNeg());
7449 // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x)
7450 return getNode(OpOpcode, DL, VT, N1.getOperand(0), Flags);
7451 }
7452 if (N1.isUndef())
7453 return getUNDEF(VT);
7454
7455 // (ext (trunc x)) -> x
7456 if (OpOpcode == ISD::TRUNCATE) {
7457 SDValue OpOp = N1.getOperand(0);
7458 if (OpOp.getValueType() == VT) {
7459 transferDbgValues(N1, OpOp);
7460 return OpOp;
7461 }
7462 }
7463 break;
7464 case ISD::TRUNCATE:
7465 assert(VT.isInteger() && N1.getValueType().isInteger() &&
7466 "Invalid TRUNCATE!");
7467 assert(VT.isVector() == N1.getValueType().isVector() &&
7468 "TRUNCATE result type type should be vector iff the operand "
7469 "type is vector!");
7470 if (N1.getValueType() == VT) return N1; // noop truncate
7471 assert((!VT.isVector() || VT.getVectorElementCount() ==
7473 "Vector element count mismatch!");
7474 assert(N1.getValueType().bitsGT(VT) && "Invalid truncate node, src < dst!");
7475 if (OpOpcode == ISD::TRUNCATE)
7476 return getNode(ISD::TRUNCATE, DL, VT, N1.getOperand(0));
7477 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
7478 OpOpcode == ISD::ANY_EXTEND) {
7479 // If the source is smaller than the dest, we still need an extend.
7481 VT.getScalarType())) {
7482 SDNodeFlags Flags;
7483 if (OpOpcode == ISD::ZERO_EXTEND)
7484 Flags.setNonNeg(N1->getFlags().hasNonNeg());
7485 return getNode(OpOpcode, DL, VT, N1.getOperand(0), Flags);
7486 }
7487 if (N1.getOperand(0).getValueType().bitsGT(VT))
7488 return getNode(ISD::TRUNCATE, DL, VT, N1.getOperand(0));
7489 return N1.getOperand(0);
7490 }
7491 if (N1.isUndef())
7492 return getUNDEF(VT);
7493 if (OpOpcode == ISD::VSCALE && !NewNodesMustHaveLegalTypes)
7494 return getVScale(DL, VT,
7496 break;
7500 assert(VT.isVector() && "This DAG node is restricted to vector types.");
7501 assert(N1.getValueType().bitsLE(VT) &&
7502 "The input must be the same size or smaller than the result.");
7505 "The destination vector type must have fewer lanes than the input.");
7506 break;
7507 case ISD::ABS:
7508 assert(VT.isInteger() && VT == N1.getValueType() && "Invalid ABS!");
7509 if (N1.isUndef())
7510 return getConstant(0, DL, VT);
7511 break;
7513 assert(VT.isInteger() && VT == N1.getValueType() &&
7514 "Invalid ABS_MIN_POISON!");
7515 if (N1.isUndef())
7516 return getConstant(0, DL, VT);
7517 break;
7518 case ISD::BSWAP:
7519 assert(VT.isInteger() && VT == N1.getValueType() && "Invalid BSWAP!");
7520 assert((VT.getScalarSizeInBits() % 16 == 0) &&
7521 "BSWAP types must be a multiple of 16 bits!");
7522 if (N1.isUndef())
7523 return getUNDEF(VT);
7524 // bswap(bswap(X)) -> X.
7525 if (OpOpcode == ISD::BSWAP)
7526 return N1.getOperand(0);
7527 break;
7528 case ISD::BITREVERSE:
7529 assert(VT.isInteger() && VT == N1.getValueType() && "Invalid BITREVERSE!");
7530 if (N1.isUndef())
7531 return getUNDEF(VT);
7532 break;
7533 case ISD::BITCAST:
7535 "Cannot BITCAST between types of different sizes!");
7536 if (VT == N1.getValueType()) return N1; // noop conversion.
7537 if (OpOpcode == ISD::BITCAST) // bitconv(bitconv(x)) -> bitconv(x)
7538 return getNode(ISD::BITCAST, DL, VT, N1.getOperand(0));
7539 if (N1.isUndef())
7540 return getUNDEF(VT);
7541 break;
7543 assert(VT.isVector() && !N1.getValueType().isVector() &&
7544 (VT.getVectorElementType() == N1.getValueType() ||
7546 N1.getValueType().isInteger() &&
7548 "Illegal SCALAR_TO_VECTOR node!");
7549 if (N1.isUndef())
7550 return getUNDEF(VT);
7551 // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
7552 if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
7554 N1.getConstantOperandVal(1) == 0 &&
7555 N1.getOperand(0).getValueType() == VT)
7556 return N1.getOperand(0);
7557 break;
7558 case ISD::FNEG:
7559 // Negation of an unknown bag of bits is still completely undefined.
7560 if (N1.isUndef())
7561 return getUNDEF(VT);
7562
7563 if (OpOpcode == ISD::FNEG) // --X -> X
7564 return N1.getOperand(0);
7565 break;
7566 case ISD::FABS:
7567 if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X)
7568 return getNode(ISD::FABS, DL, VT, N1.getOperand(0));
7569 break;
7570 case ISD::VSCALE:
7571 assert(VT == N1.getValueType() && "Unexpected VT!");
7572 break;
7573 case ISD::CTPOP:
7574 if (N1.getValueType().getScalarType() == MVT::i1)
7575 return N1;
7576 break;
7577 case ISD::CTLZ:
7578 case ISD::CTTZ:
7579 if (N1.getValueType().getScalarType() == MVT::i1)
7580 return getNOT(DL, N1, N1.getValueType());
7581 break;
7582 case ISD::CTLS:
7583 if (N1.getValueType().getScalarType() == MVT::i1)
7584 return getConstant(0, DL, VT);
7585 break;
7586 case ISD::VECREDUCE_ADD:
7587 if (N1.getValueType().getScalarType() == MVT::i1)
7588 return getNode(ISD::VECREDUCE_XOR, DL, VT, N1);
7589 break;
7592 if (N1.getValueType().getScalarType() == MVT::i1)
7593 return getNode(ISD::VECREDUCE_OR, DL, VT, N1);
7594 break;
7597 if (N1.getValueType().getScalarType() == MVT::i1)
7598 return getNode(ISD::VECREDUCE_AND, DL, VT, N1);
7599 break;
7601 // With a single lane, the result is true iff that lane is false.
7603 return getLogicalNOT(DL, N1, VT);
7604 break;
7605 case ISD::VECTOR_REPEAT:
7607 "VECTOR_REPEAT requires a fixed-length vector operand");
7608 assert(VT.isScalableVector() &&
7609 "VECTOR_REPEAT requires a scalable vector result");
7612 "VECTOR_REPEAT operand and result element counts must match");
7613 if (VT.getVectorMinNumElements() == 1)
7614 return getSplatVector(
7615 VT, DL, getExtractVectorElt(DL, VT.getVectorElementType(), N1, 0));
7616 break;
7617 case ISD::SPLAT_VECTOR:
7618 assert(VT.isVector() && "Wrong return type!");
7619 // FIXME: Hexagon uses i32 scalar for a floating point zero vector so allow
7620 // that for now.
7622 (VT.isFloatingPoint() && N1.getValueType() == MVT::i32) ||
7624 N1.getValueType().isInteger() &&
7626 "Wrong operand type!");
7627 break;
7628 }
7629
7630 SDNode *N;
7631 SDVTList VTs = getVTList(VT);
7632 SDValue Ops[] = {N1};
7633 if (VT != MVT::Glue) { // Don't CSE glue producing nodes
7634 SDNodeKey ID(Opcode, VTs, Ops);
7635 FoldingSetInsertToken InsertToken;
7636 if (SDNode *E = lookupNode(ID, DL, InsertToken)) {
7637 E->intersectFlagsWith(Flags);
7638 return SDValue(E, 0);
7639 }
7640
7641 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
7642 N->setFlags(Flags);
7643 createOperands(N, Ops);
7644 CSEMap.insert(N, InsertToken);
7645 } else {
7646 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
7647 createOperands(N, Ops);
7648 }
7649
7650 InsertNode(N);
7651 SDValue V = SDValue(N, 0);
7652 NewSDValueDbgMsg(V, "Creating new node: ", this);
7653 return V;
7654}
7655
7656static APInt getIntegerIdentity(unsigned Opcode, unsigned BitWidth) {
7657 switch (Opcode) {
7658 default:
7659 llvm_unreachable("Unexpected integer identity opcode");
7660 case ISD::ADD:
7661 case ISD::OR:
7662 case ISD::XOR:
7663 case ISD::UMAX:
7664 return APInt::getZero(BitWidth);
7665 case ISD::MUL:
7666 return APInt(BitWidth, 1);
7667 case ISD::AND:
7668 case ISD::UMIN:
7670 case ISD::SMAX:
7672 case ISD::SMIN:
7674 }
7675}
7676
7677static std::optional<APInt> FoldValue(unsigned Opcode, const APInt &C1,
7678 const APInt &C2) {
7679 switch (Opcode) {
7680 case ISD::ADD: return C1 + C2;
7681 case ISD::SUB: return C1 - C2;
7682 case ISD::MUL: return C1 * C2;
7683 case ISD::AND: return C1 & C2;
7684 case ISD::OR: return C1 | C2;
7685 case ISD::XOR: return C1 ^ C2;
7686 case ISD::SHL: return C1 << C2;
7687 case ISD::SRL: return C1.lshr(C2);
7688 case ISD::SRA: return C1.ashr(C2);
7689 case ISD::ROTL: return C1.rotl(C2);
7690 case ISD::ROTR: return C1.rotr(C2);
7691 case ISD::SMIN: return C1.sle(C2) ? C1 : C2;
7692 case ISD::SMAX: return C1.sge(C2) ? C1 : C2;
7693 case ISD::UMIN: return C1.ule(C2) ? C1 : C2;
7694 case ISD::UMAX: return C1.uge(C2) ? C1 : C2;
7695 case ISD::SADDSAT: return C1.sadd_sat(C2);
7696 case ISD::UADDSAT: return C1.uadd_sat(C2);
7697 case ISD::SSUBSAT: return C1.ssub_sat(C2);
7698 case ISD::USUBSAT: return C1.usub_sat(C2);
7699 case ISD::SSHLSAT: return C1.sshl_sat(C2);
7700 case ISD::USHLSAT: return C1.ushl_sat(C2);
7701 case ISD::UDIV:
7702 if (!C2.getBoolValue())
7703 break;
7704 return C1.udiv(C2);
7705 case ISD::UREM:
7706 if (!C2.getBoolValue())
7707 break;
7708 return C1.urem(C2);
7709 case ISD::SDIV:
7710 if (!C2.getBoolValue())
7711 break;
7712 return C1.sdiv(C2);
7713 case ISD::SREM:
7714 if (!C2.getBoolValue())
7715 break;
7716 return C1.srem(C2);
7717 case ISD::AVGFLOORS:
7718 return APIntOps::avgFloorS(C1, C2);
7719 case ISD::AVGFLOORU:
7720 return APIntOps::avgFloorU(C1, C2);
7721 case ISD::AVGCEILS:
7722 return APIntOps::avgCeilS(C1, C2);
7723 case ISD::AVGCEILU:
7724 return APIntOps::avgCeilU(C1, C2);
7725 case ISD::AVGSUBFLOORS:
7726 return APIntOps::avgSubFloorS(C1, C2);
7727 case ISD::AVGSUBFLOORU:
7728 return APIntOps::avgSubFloorU(C1, C2);
7729 case ISD::ABDS:
7730 return APIntOps::abds(C1, C2);
7731 case ISD::ABDU:
7732 return APIntOps::abdu(C1, C2);
7733 case ISD::MULHS:
7734 return APIntOps::mulhs(C1, C2);
7735 case ISD::MULHU:
7736 return APIntOps::mulhu(C1, C2);
7737 case ISD::CLMUL:
7738 return APIntOps::clmul(C1, C2);
7739 case ISD::CLMULR:
7740 return APIntOps::clmulr(C1, C2);
7741 case ISD::CLMULH:
7742 return APIntOps::clmulh(C1, C2);
7743 case ISD::PEXT:
7744 return APIntOps::pext(C1, C2);
7745 case ISD::PDEP:
7746 return APIntOps::pdep(C1, C2);
7747 }
7748 return std::nullopt;
7749}
7750// Handle constant folding with UNDEF.
7751// TODO: Handle more cases.
7752static std::optional<APInt> FoldValueWithUndef(unsigned Opcode, const APInt &C1,
7753 bool IsUndef1, const APInt &C2,
7754 bool IsUndef2) {
7755 if (!(IsUndef1 || IsUndef2))
7756 return FoldValue(Opcode, C1, C2);
7757
7758 // Fold and(x, undef) -> 0
7759 // Fold mul(x, undef) -> 0
7760 if (Opcode == ISD::AND || Opcode == ISD::MUL)
7761 return APInt::getZero(C1.getBitWidth());
7762
7763 return std::nullopt;
7764}
7765
7767 const GlobalAddressSDNode *GA,
7768 const SDNode *N2) {
7769 if (GA->getOpcode() != ISD::GlobalAddress)
7770 return SDValue();
7771 if (!TLI->isOffsetFoldingLegal(GA))
7772 return SDValue();
7773 auto *C2 = dyn_cast<ConstantSDNode>(N2);
7774 if (!C2)
7775 return SDValue();
7776 int64_t Offset = C2->getSExtValue();
7777 switch (Opcode) {
7778 case ISD::ADD:
7779 case ISD::PTRADD:
7780 break;
7781 case ISD::SUB: Offset = -uint64_t(Offset); break;
7782 default: return SDValue();
7783 }
7784 return getGlobalAddress(GA->getGlobal(), SDLoc(C2), VT,
7785 GA->getOffset() + uint64_t(Offset));
7786}
7787
7789 switch (Opcode) {
7790 case ISD::SDIV:
7791 case ISD::UDIV:
7792 case ISD::SREM:
7793 case ISD::UREM: {
7794 // If a divisor is zero/undef or any element of a divisor vector is
7795 // zero/undef, the whole op is undef.
7796 assert(Ops.size() == 2 && "Div/rem should have 2 operands");
7797 SDValue Divisor = Ops[1];
7798 if (Divisor.isUndef() || isNullConstant(Divisor))
7799 return true;
7800
7801 return ISD::isBuildVectorOfConstantSDNodes(Divisor) &&
7802 llvm::any_of(Divisor->op_values(), [](SDValue V) {
7803 return V.isUndef() || isNullConstant(V);
7804 });
7805 // TODO: Handle signed overflow.
7806 }
7807 // TODO: Handle oversized shifts.
7808 default:
7809 return false;
7810 }
7811}
7812
7815 SDNodeFlags Flags) {
7816 // If the opcode is a target-specific ISD node, there's nothing we can
7817 // do here and the operand rules may not line up with the below, so
7818 // bail early.
7819 // We can't create a scalar CONCAT_VECTORS so skip it. It will break
7820 // for concats involving SPLAT_VECTOR. Concats of BUILD_VECTORS are handled by
7821 // foldCONCAT_VECTORS in getNode before this is called.
7822 // VECTOR_SHUFFLE_VAR is not elementwise.
7823 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::CONCAT_VECTORS ||
7824 Opcode == ISD::VECTOR_SHUFFLE_VAR)
7825 return SDValue();
7826
7827 unsigned NumOps = Ops.size();
7828 if (NumOps == 0)
7829 return SDValue();
7830
7831 if (isUndef(Opcode, Ops))
7832 return getUNDEF(VT);
7833
7834 // Handle unary special cases.
7835 if (NumOps == 1) {
7836 SDValue N1 = Ops[0];
7837
7838 // Constant fold unary operations with an integer constant operand. Even
7839 // opaque constant will be folded, because the folding of unary operations
7840 // doesn't create new constants with different values. Nevertheless, the
7841 // opaque flag is preserved during folding to prevent future folding with
7842 // other constants.
7843 if (auto *C = dyn_cast<ConstantSDNode>(N1)) {
7844 const APInt &Val = C->getAPIntValue();
7845 switch (Opcode) {
7846 case ISD::SIGN_EXTEND:
7847 return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
7848 C->isTargetOpcode(), C->isOpaque());
7849 case ISD::TRUNCATE:
7850 if (C->isOpaque())
7851 break;
7852 [[fallthrough]];
7853 case ISD::ZERO_EXTEND:
7854 return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
7855 C->isTargetOpcode(), C->isOpaque());
7856 case ISD::ANY_EXTEND:
7857 // Some targets like RISCV prefer to sign extend some types.
7858 if (TLI->isSExtCheaperThanZExt(N1.getValueType(), VT))
7859 return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
7860 C->isTargetOpcode(), C->isOpaque());
7861 return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
7862 C->isTargetOpcode(), C->isOpaque());
7863 case ISD::ABS:
7864 return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(),
7865 C->isOpaque());
7867 if (Val.isMinSignedValue())
7868 return getPOISON(VT);
7869 return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(),
7870 C->isOpaque());
7871 case ISD::BITREVERSE:
7872 return getConstant(Val.reverseBits(), DL, VT, C->isTargetOpcode(),
7873 C->isOpaque());
7874 case ISD::BSWAP:
7875 return getConstant(Val.byteSwap(), DL, VT, C->isTargetOpcode(),
7876 C->isOpaque());
7877 case ISD::CTPOP:
7878 return getConstant(Val.popcount(), DL, VT, C->isTargetOpcode(),
7879 C->isOpaque());
7880 case ISD::PARITY:
7881 return getConstant(Val.popcount() & 1, DL, VT, C->isTargetOpcode(),
7882 C->isOpaque());
7883 case ISD::CTLZ:
7885 return getConstant(Val.countl_zero(), DL, VT, C->isTargetOpcode(),
7886 C->isOpaque());
7887 case ISD::CTTZ:
7889 return getConstant(Val.countr_zero(), DL, VT, C->isTargetOpcode(),
7890 C->isOpaque());
7891 case ISD::CTLS:
7892 // CTLS returns the number of extra sign bits so subtract one.
7893 return getConstant(Val.getNumSignBits() - 1, DL, VT,
7894 C->isTargetOpcode(), C->isOpaque());
7895 case ISD::UINT_TO_FP:
7896 case ISD::SINT_TO_FP: {
7898 (void)FPV.convertFromAPInt(Val, Opcode == ISD::SINT_TO_FP,
7900 return getConstantFP(FPV, DL, VT);
7901 }
7902 case ISD::FP16_TO_FP:
7903 case ISD::BF16_TO_FP: {
7904 bool Ignored;
7905 APFloat FPV(Opcode == ISD::FP16_TO_FP ? APFloat::IEEEhalf()
7906 : APFloat::BFloat(),
7907 (Val.getBitWidth() == 16) ? Val : Val.trunc(16));
7908
7909 // This can return overflow, underflow, or inexact; we don't care.
7910 // FIXME need to be more flexible about rounding mode.
7912 &Ignored);
7913 return getConstantFP(FPV, DL, VT);
7914 }
7915 case ISD::STEP_VECTOR:
7916 if (SDValue V = FoldSTEP_VECTOR(DL, VT, N1, *this))
7917 return V;
7918 break;
7919 case ISD::BITCAST:
7920 if (C->isOpaque())
7921 break;
7922 if (VT == MVT::f16 && C->getValueType(0) == MVT::i16)
7923 return getConstantFP(APFloat(APFloat::IEEEhalf(), Val), DL, VT);
7924 if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
7925 return getConstantFP(APFloat(APFloat::IEEEsingle(), Val), DL, VT);
7926 if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
7927 return getConstantFP(APFloat(APFloat::IEEEdouble(), Val), DL, VT);
7928 if (VT == MVT::f128 && C->getValueType(0) == MVT::i128)
7929 return getConstantFP(APFloat(APFloat::IEEEquad(), Val), DL, VT);
7930 break;
7931 }
7932 }
7933
7934 // Constant fold unary operations with a floating point constant operand.
7935 if (auto *C = dyn_cast<ConstantFPSDNode>(N1)) {
7936 APFloat V = C->getValueAPF(); // make copy
7937 DenormalMode DenormMode = getDenormalMode(N1.getValueType());
7938 switch (Opcode) {
7939 case ISD::FNEG:
7940 V.changeSign();
7941 return getConstantFP(V, DL, VT);
7942 case ISD::FABS:
7943 V.clearSign();
7944 return getConstantFP(V, DL, VT);
7945 case ISD::FCEIL: {
7946 if (auto Res = tryFoldFP(FPOp::Ceil, {V}, DenormMode))
7947 if (Res->Status == APFloat::opOK || Res->Status == APFloat::opInexact)
7948 return getConstantFP(Res->Value, DL, VT);
7949 return SDValue();
7950 }
7951 case ISD::FTRUNC: {
7952 if (auto Res = tryFoldFP(FPOp::Trunc, {V}, DenormMode))
7953 if (Res->Status == APFloat::opOK || Res->Status == APFloat::opInexact)
7954 return getConstantFP(Res->Value, DL, VT);
7955 return SDValue();
7956 }
7957 case ISD::FFLOOR: {
7958 if (auto Res = tryFoldFP(FPOp::Floor, {V}, DenormMode))
7959 if (Res->Status == APFloat::opOK || Res->Status == APFloat::opInexact)
7960 return getConstantFP(Res->Value, DL, VT);
7961 return SDValue();
7962 }
7963 case ISD::FP_EXTEND: {
7964 bool ignored;
7965 // This can return overflow, underflow, or inexact; we don't care.
7966 // FIXME need to be more flexible about rounding mode.
7967 (void)V.convert(VT.getFltSemantics(), APFloat::rmNearestTiesToEven,
7968 &ignored);
7969 return getConstantFP(V, DL, VT);
7970 }
7971 case ISD::FP_TO_SINT:
7972 case ISD::FP_TO_UINT: {
7973 bool ignored;
7974 APSInt IntVal(VT.getSizeInBits(), Opcode == ISD::FP_TO_UINT);
7975 // FIXME need to be more flexible about rounding mode.
7977 V.convertToInteger(IntVal, APFloat::rmTowardZero, &ignored);
7978 if (s == APFloat::opInvalidOp) // inexact is OK, in fact usual
7979 break;
7980 return getConstant(IntVal, DL, VT);
7981 }
7982 case ISD::FP_TO_FP16:
7983 case ISD::FP_TO_BF16: {
7984 bool Ignored;
7985 // This can return overflow, underflow, or inexact; we don't care.
7986 // FIXME need to be more flexible about rounding mode.
7987 (void)V.convert(Opcode == ISD::FP_TO_FP16 ? APFloat::IEEEhalf()
7988 : APFloat::BFloat(),
7990 return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
7991 }
7992 case ISD::BITCAST:
7993 if (VT == MVT::i16 && C->getValueType(0) == MVT::f16)
7994 return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL,
7995 VT);
7996 if (VT == MVT::i16 && C->getValueType(0) == MVT::bf16)
7997 return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL,
7998 VT);
7999 if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
8000 return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), DL,
8001 VT);
8002 if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
8003 return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
8004 break;
8005 }
8006 }
8007
8008 // Early-out if we failed to constant fold a bitcast.
8009 if (Opcode == ISD::BITCAST)
8010 return SDValue();
8011
8012 // Constant fold integer vector reductions with constant BUILD_VECTORs.
8013 if ((Opcode == ISD::VECREDUCE_ADD || Opcode == ISD::VECREDUCE_SMAX ||
8014 Opcode == ISD::VECREDUCE_SMIN || Opcode == ISD::VECREDUCE_UMAX ||
8015 Opcode == ISD::VECREDUCE_UMIN || Opcode == ISD::VECREDUCE_MUL ||
8016 Opcode == ISD::VECREDUCE_OR || Opcode == ISD::VECREDUCE_XOR ||
8017 Opcode == ISD::VECREDUCE_AND) &&
8019 unsigned EltBits = N1.getValueType().getScalarSizeInBits();
8020 unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Opcode);
8021 APInt Acc = getIntegerIdentity(BaseOpcode, EltBits);
8022 for (SDValue Elt : N1->op_values()) {
8023 if (Elt.getOpcode() == ISD::POISON)
8024 return getPOISON(VT);
8025 if (Elt.isUndef() || cast<ConstantSDNode>(Elt)->isOpaque())
8026 return SDValue();
8027 APInt Value = cast<ConstantSDNode>(Elt)->getAPIntValue().trunc(EltBits);
8028 std::optional<APInt> Folded = FoldValue(BaseOpcode, Acc, Value);
8029 assert(Folded &&
8030 "Expected vector reduction base opcode to be foldable");
8031 Acc = *Folded;
8032 }
8033 EVT EltVT = N1.getValueType().getScalarType();
8034 return getAnyExtOrTrunc(getConstant(Acc, DL, EltVT), DL, VT);
8035 }
8036 }
8037
8038 // Handle binops special cases.
8039 if (NumOps == 2) {
8040 if (SDValue CFP = foldConstantFPMath(Opcode, DL, VT, Ops))
8041 return CFP;
8042
8043 if (auto *C1 = dyn_cast<ConstantSDNode>(Ops[0])) {
8044 if (auto *C2 = dyn_cast<ConstantSDNode>(Ops[1])) {
8045 if (C1->isOpaque() || C2->isOpaque())
8046 return SDValue();
8047
8048 std::optional<APInt> FoldAttempt =
8049 FoldValue(Opcode, C1->getAPIntValue(), C2->getAPIntValue());
8050 if (!FoldAttempt)
8051 return SDValue();
8052
8053 SDValue Folded = getConstant(*FoldAttempt, DL, VT);
8054 assert((!Folded || !VT.isVector()) &&
8055 "Can't fold vectors ops with scalar operands");
8056 return Folded;
8057 }
8058 }
8059
8060 // fold (add Sym, c) -> Sym+c
8062 return FoldSymbolOffset(Opcode, VT, GA, Ops[1].getNode());
8063 if (TLI->isCommutativeBinOp(Opcode))
8065 return FoldSymbolOffset(Opcode, VT, GA, Ops[0].getNode());
8066
8067 // fold (sext_in_reg c1) -> c2
8068 if (Opcode == ISD::SIGN_EXTEND_INREG) {
8069 EVT EVT = cast<VTSDNode>(Ops[1])->getVT();
8070
8071 auto SignExtendInReg = [&](APInt Val, llvm::EVT ConstantVT) {
8072 unsigned FromBits = EVT.getScalarSizeInBits();
8073 Val <<= Val.getBitWidth() - FromBits;
8074 Val.ashrInPlace(Val.getBitWidth() - FromBits);
8075 return getConstant(Val, DL, ConstantVT);
8076 };
8077
8078 if (auto *C1 = dyn_cast<ConstantSDNode>(Ops[0])) {
8079 const APInt &Val = C1->getAPIntValue();
8080 return SignExtendInReg(Val, VT);
8081 }
8082
8084 SmallVector<SDValue, 8> ScalarOps;
8085 llvm::EVT OpVT = Ops[0].getOperand(0).getValueType();
8086 for (int I = 0, E = VT.getVectorNumElements(); I != E; ++I) {
8087 SDValue Op = Ops[0].getOperand(I);
8088 if (Op.isUndef()) {
8089 ScalarOps.push_back(getUNDEF(OpVT));
8090 continue;
8091 }
8092 const APInt &Val = cast<ConstantSDNode>(Op)->getAPIntValue();
8093 ScalarOps.push_back(SignExtendInReg(Val, OpVT));
8094 }
8095 return getBuildVector(VT, DL, ScalarOps);
8096 }
8097
8098 if (Ops[0].getOpcode() == ISD::SPLAT_VECTOR &&
8099 isa<ConstantSDNode>(Ops[0].getOperand(0)))
8100 return getNode(ISD::SPLAT_VECTOR, DL, VT,
8101 SignExtendInReg(Ops[0].getConstantOperandAPInt(0),
8102 Ops[0].getOperand(0).getValueType()));
8103 }
8104 }
8105
8106 // Handle fshl/fshr special cases.
8107 if (Opcode == ISD::FSHL || Opcode == ISD::FSHR) {
8108 auto *C1 = dyn_cast<ConstantSDNode>(Ops[0]);
8109 auto *C2 = dyn_cast<ConstantSDNode>(Ops[1]);
8110 auto *C3 = dyn_cast<ConstantSDNode>(Ops[2]);
8111
8112 if (C1 && C2 && C3) {
8113 if (C1->isOpaque() || C2->isOpaque() || C3->isOpaque())
8114 return SDValue();
8115 const APInt &V1 = C1->getAPIntValue(), &V2 = C2->getAPIntValue(),
8116 &V3 = C3->getAPIntValue();
8117
8118 APInt FoldedVal = Opcode == ISD::FSHL ? APIntOps::fshl(V1, V2, V3)
8119 : APIntOps::fshr(V1, V2, V3);
8120 return getConstant(FoldedVal, DL, VT);
8121 }
8122 }
8123
8124 // Handle fma/fmad special cases.
8125 if (Opcode == ISD::FMA || Opcode == ISD::FMAD || Opcode == ISD::FMULADD) {
8126 assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
8127 assert(Ops[0].getValueType() == VT && Ops[1].getValueType() == VT &&
8128 Ops[2].getValueType() == VT && "FMA types must match!");
8132 if (C1 && C2 && C3) {
8134 APFloat V1 = C1->getValueAPF();
8135 const APFloat &V2 = C2->getValueAPF();
8136 const APFloat &V3 = C3->getValueAPF();
8137 if (Opcode == ISD::FMAD || Opcode == ISD::FMULADD) {
8138 if (auto Product = tryFoldFP(FPOp::Mul, {V1, V2}, DM))
8139 return getConstFP(tryFoldFP(FPOp::Add, {Product->Value, V3}, DM), DL,
8140 VT);
8141 return SDValue();
8142 }
8143 return getConstFP(tryFoldFP(FPOp::FMA, {V1, V2, V3}, DM), DL, VT);
8144 }
8145 }
8146
8147 // This is for vector folding only from here on.
8148 if (!VT.isVector())
8149 return SDValue();
8150
8151 // Constant fold integer partial reductions with constant BUILD_VECTOR
8152 // operands. The reduction order is deliberately unspecified. Use the same
8153 // subvector layout as TargetLowering::expandPartialReduceMLA(), where input
8154 // lane I contributes to accumulator lane I % NumAccElts.
8155 if (Opcode == ISD::PARTIAL_REDUCE_SMLA ||
8156 Opcode == ISD::PARTIAL_REDUCE_UMLA ||
8157 Opcode == ISD::PARTIAL_REDUCE_SUMLA) {
8158 // These nodes have no scalar form, so unsupported cases must not fall
8159 // through to generic per-lane vector folding.
8160 if (!llvm::all_of(Ops, [](SDValue Op) {
8162 }))
8163 return SDValue();
8164
8165 unsigned AccEltBits = VT.getScalarSizeInBits();
8166 unsigned InputEltBits = Ops[1].getScalarValueSizeInBits();
8167 unsigned NumAccElts = VT.getVectorNumElements();
8168 unsigned NumInputElts = Ops[1].getValueType().getVectorNumElements();
8169 SmallVector<APInt, 8> Results(NumAccElts, APInt::getZero(AccEltBits));
8170 BitVector PoisonElts(NumAccElts);
8171
8172 for (unsigned I = 0; I != NumAccElts; ++I) {
8173 SDValue Elt = Ops[0].getOperand(I);
8174 if (Elt.getOpcode() == ISD::POISON) {
8175 PoisonElts.set(I);
8176 continue;
8177 }
8178 auto *C = dyn_cast<ConstantSDNode>(Elt);
8179 if (!C || C->isOpaque())
8180 return SDValue();
8181 Results[I] = C->getAPIntValue().trunc(AccEltBits);
8182 }
8183
8184 bool IsLHSSigned = Opcode != ISD::PARTIAL_REDUCE_UMLA;
8185 bool IsRHSSigned = Opcode == ISD::PARTIAL_REDUCE_SMLA;
8186 for (unsigned I = 0; I != NumInputElts; ++I) {
8187 const unsigned AccIdx = I % NumAccElts;
8188 SDValue LHSElt = Ops[1].getOperand(I);
8189 SDValue RHSElt = Ops[2].getOperand(I);
8190 if (LHSElt.getOpcode() == ISD::POISON ||
8191 RHSElt.getOpcode() == ISD::POISON) {
8192 PoisonElts.set(AccIdx);
8193 continue;
8194 }
8195
8196 auto *LHS = dyn_cast<ConstantSDNode>(LHSElt);
8197 auto *RHS = dyn_cast<ConstantSDNode>(RHSElt);
8198 if (!LHS || !RHS || LHS->isOpaque() || RHS->isOpaque())
8199 return SDValue();
8200
8201 APInt LHSVal = LHS->getAPIntValue().trunc(InputEltBits);
8202 APInt RHSVal = RHS->getAPIntValue().trunc(InputEltBits);
8203 LHSVal = IsLHSSigned ? LHSVal.sext(AccEltBits) : LHSVal.zext(AccEltBits);
8204 RHSVal = IsRHSSigned ? RHSVal.sext(AccEltBits) : RHSVal.zext(AccEltBits);
8205 Results[AccIdx] += LHSVal * RHSVal;
8206 }
8207
8208 // After type legalization the vector element type may not be a legal
8209 // scalar type (e.g. i16 on AArch64). Create the folded constants in the
8210 // promoted legal scalar type instead, matching the generic per-lane path
8211 // below. Bail out if legalization would narrow the type, since the lane
8212 // value would not fit.
8213 EVT AccEltVT = VT.getVectorElementType();
8214 EVT LegalSVT = AccEltVT;
8215 if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
8216 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
8217 if (LegalSVT.bitsLT(AccEltVT))
8218 return SDValue();
8219 }
8220
8221 SmallVector<SDValue, 8> ResultOps;
8222 for (unsigned I = 0; I != NumAccElts; ++I)
8223 ResultOps.push_back(
8224 PoisonElts[I] ? getPOISON(LegalSVT)
8225 : getConstant(Results[I].sext(LegalSVT.getSizeInBits()),
8226 DL, LegalSVT));
8227 return getBuildVector(VT, DL, ResultOps);
8228 }
8229
8230 ElementCount NumElts = VT.getVectorElementCount();
8231
8232 // See if we can fold through any bitcasted integer ops.
8233 if (NumOps == 2 && VT.isFixedLengthVector() && VT.isInteger() &&
8234 Ops[0].getValueType() == VT && Ops[1].getValueType() == VT &&
8235 (Ops[0].getOpcode() == ISD::BITCAST ||
8236 Ops[1].getOpcode() == ISD::BITCAST)) {
8239 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
8240 auto *BV2 = dyn_cast<BuildVectorSDNode>(N2);
8241 if (BV1 && BV2 && N1.getValueType().isInteger() &&
8242 N2.getValueType().isInteger()) {
8243 bool IsLE = getDataLayout().isLittleEndian();
8244 unsigned EltBits = VT.getScalarSizeInBits();
8245 SmallVector<APInt> RawBits1, RawBits2;
8246 BitVector UndefElts1, UndefElts2;
8247 if (BV1->getConstantRawBits(IsLE, EltBits, RawBits1, UndefElts1) &&
8248 BV2->getConstantRawBits(IsLE, EltBits, RawBits2, UndefElts2)) {
8249 SmallVector<APInt> RawBits;
8250 for (unsigned I = 0, E = NumElts.getFixedValue(); I != E; ++I) {
8251 std::optional<APInt> Fold = FoldValueWithUndef(
8252 Opcode, RawBits1[I], UndefElts1[I], RawBits2[I], UndefElts2[I]);
8253 if (!Fold)
8254 break;
8255 RawBits.push_back(*Fold);
8256 }
8257 if (RawBits.size() == NumElts.getFixedValue()) {
8258 // We have constant folded, but we might need to cast this again back
8259 // to the original (possibly legalized) type.
8260 EVT BVVT, BVEltVT;
8261 if (N1.getValueType() == VT) {
8262 BVVT = N1.getValueType();
8263 BVEltVT = BV1->getOperand(0).getValueType();
8264 } else {
8265 BVVT = N2.getValueType();
8266 BVEltVT = BV2->getOperand(0).getValueType();
8267 }
8268 unsigned BVEltBits = BVEltVT.getSizeInBits();
8269 SmallVector<APInt> DstBits;
8270 BitVector DstUndefs;
8272 DstBits, RawBits, DstUndefs,
8273 BitVector(RawBits.size(), false));
8274 SmallVector<SDValue> Ops(DstBits.size(), getUNDEF(BVEltVT));
8275 for (unsigned I = 0, E = DstBits.size(); I != E; ++I) {
8276 if (DstUndefs[I])
8277 continue;
8278 Ops[I] = getConstant(DstBits[I].sext(BVEltBits), DL, BVEltVT);
8279 }
8280 return getBitcast(VT, getBuildVector(BVVT, DL, Ops));
8281 }
8282 }
8283 }
8284 // Logic ops can be folded from raw integer bits - mainly for AVX512 masks.
8285 if (ISD::isBitwiseLogicOp(Opcode) && isa<ConstantSDNode>(N1) &&
8286 isa<ConstantSDNode>(N2)) {
8287 if (SDValue Res = FoldConstantArithmetic(Opcode, DL, N1.getValueType(),
8288 {N1, N2}, Flags))
8289 return getBitcast(VT, Res);
8290 }
8291 }
8292
8293 // Fold (mul step_vector(C0), C1) to (step_vector(C0 * C1)).
8294 // (shl step_vector(C0), C1) -> (step_vector(C0 << C1))
8295 if ((Opcode == ISD::MUL || Opcode == ISD::SHL) &&
8296 Ops[0].getOpcode() == ISD::STEP_VECTOR) {
8297 APInt RHSVal;
8298 if (ISD::isConstantSplatVector(Ops[1], RHSVal)) {
8299 APInt NewStep = Opcode == ISD::MUL
8300 ? Ops[0].getConstantOperandAPInt(0) * RHSVal
8301 : Ops[0].getConstantOperandAPInt(0) << RHSVal;
8302 return getStepVector(DL, VT, NewStep);
8303 }
8304 }
8305
8306 auto IsScalarOrSameVectorSize = [NumElts](const SDValue &Op) {
8307 return !Op.getValueType().isVector() ||
8308 Op.getValueType().getVectorElementCount() == NumElts;
8309 };
8310
8311 auto IsBuildVectorSplatVectorOrUndef = [](const SDValue &Op) {
8312 return Op.isUndef() || Op.getOpcode() == ISD::CONDCODE ||
8313 Op.getOpcode() == ISD::BUILD_VECTOR ||
8314 Op.getOpcode() == ISD::SPLAT_VECTOR;
8315 };
8316
8317 // All operands must be vector types with the same number of elements as
8318 // the result type and must be either UNDEF or a build/splat vector
8319 // or UNDEF scalars.
8320 if (!llvm::all_of(Ops, IsBuildVectorSplatVectorOrUndef) ||
8321 !llvm::all_of(Ops, IsScalarOrSameVectorSize))
8322 return SDValue();
8323
8324 // If we are comparing vectors, then the result needs to be a i1 boolean that
8325 // is then extended back to the legal result type depending on how booleans
8326 // are represented.
8327 EVT SVT = (Opcode == ISD::SETCC ? MVT::i1 : VT.getScalarType());
8328 ISD::NodeType ExtendCode =
8329 (Opcode == ISD::SETCC && SVT != VT.getScalarType())
8330 ? TargetLowering::getExtendForContent(TLI->getBooleanContents(VT))
8332
8333 // Find legal integer scalar type for constant promotion and
8334 // ensure that its scalar size is at least as large as source.
8335 EVT LegalSVT = VT.getScalarType();
8336 if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
8337 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
8338 if (LegalSVT.bitsLT(VT.getScalarType()))
8339 return SDValue();
8340 }
8341
8342 // For scalable vector types we know we're dealing with SPLAT_VECTORs. We
8343 // only have one operand to check. For fixed-length vector types we may have
8344 // a combination of BUILD_VECTOR and SPLAT_VECTOR.
8345 unsigned NumVectorElts = NumElts.isScalable() ? 1 : NumElts.getFixedValue();
8346
8347 // Constant fold each scalar lane separately.
8348 SmallVector<SDValue, 4> ScalarResults;
8349 for (unsigned I = 0; I != NumVectorElts; I++) {
8350 SmallVector<SDValue, 4> ScalarOps;
8351 for (SDValue Op : Ops) {
8352 EVT InSVT = Op.getValueType().getScalarType();
8353 if (Op.getOpcode() != ISD::BUILD_VECTOR &&
8354 Op.getOpcode() != ISD::SPLAT_VECTOR) {
8355 if (Op.isUndef())
8356 ScalarOps.push_back(getUNDEF(InSVT));
8357 else
8358 ScalarOps.push_back(Op);
8359 continue;
8360 }
8361
8362 SDValue ScalarOp =
8363 Op.getOperand(Op.getOpcode() == ISD::SPLAT_VECTOR ? 0 : I);
8364 EVT ScalarVT = ScalarOp.getValueType();
8365
8366 // Build vector (integer) scalar operands may need implicit
8367 // truncation - do this before constant folding.
8368 if (ScalarVT.isInteger() && ScalarVT.bitsGT(InSVT)) {
8369 // Don't create illegally-typed nodes unless they're constants or undef
8370 // - if we fail to constant fold we can't guarantee the (dead) nodes
8371 // we're creating will be cleaned up before being visited for
8372 // legalization.
8373 if (NewNodesMustHaveLegalTypes && !ScalarOp.isUndef() &&
8374 !isa<ConstantSDNode>(ScalarOp) &&
8375 TLI->getTypeAction(*getContext(), InSVT) !=
8377 return SDValue();
8378 ScalarOp = getNode(ISD::TRUNCATE, DL, InSVT, ScalarOp);
8379 }
8380
8381 ScalarOps.push_back(ScalarOp);
8382 }
8383
8384 // Constant fold the scalar operands.
8385 SDValue ScalarResult = getNode(Opcode, DL, SVT, ScalarOps, Flags);
8386
8387 // Scalar folding only succeeded if the result is a constant or UNDEF.
8388 if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant &&
8389 ScalarResult.getOpcode() != ISD::ConstantFP)
8390 return SDValue();
8391
8392 // Legalize the (integer) scalar constant if necessary. We only do
8393 // this once we know the folding succeeded, since otherwise we would
8394 // get a node with illegal type which has a user.
8395 if (LegalSVT != SVT)
8396 ScalarResult = getNode(ExtendCode, DL, LegalSVT, ScalarResult);
8397
8398 ScalarResults.push_back(ScalarResult);
8399 }
8400
8401 SDValue V = NumElts.isScalable() ? getSplatVector(VT, DL, ScalarResults[0])
8402 : getBuildVector(VT, DL, ScalarResults);
8403 NewSDValueDbgMsg(V, "New node fold constant vector: ", this);
8404 return V;
8405}
8406
8408 SDVTList VTList,
8410 SDNodeFlags Flags) {
8411 if (VTList.NumVTs == 1)
8412 return FoldConstantArithmetic(Opcode, DL, VTList.VTs[0], Ops, Flags);
8413
8414 switch (Opcode) {
8415 case ISD::SADDO:
8416 case ISD::UADDO:
8417 case ISD::SSUBO:
8418 case ISD::USUBO:
8419 case ISD::SMULO:
8420 case ISD::UMULO: {
8421 // TODO: Support non-splat vector constants.
8424 if (!C1 || !C2 || C1->isOpaque() || C2->isOpaque())
8425 return SDValue();
8426
8427 const APInt &V1 = C1->getAPIntValue(), &V2 = C2->getAPIntValue();
8428 bool Overflow;
8429 APInt Result;
8430 switch (Opcode) {
8431 default:
8432 llvm_unreachable("Unexpected overflow opcode");
8433 case ISD::SADDO:
8434 Result = V1.sadd_ov(V2, Overflow);
8435 break;
8436 case ISD::UADDO:
8437 Result = V1.uadd_ov(V2, Overflow);
8438 break;
8439 case ISD::SSUBO:
8440 Result = V1.ssub_ov(V2, Overflow);
8441 break;
8442 case ISD::USUBO:
8443 Result = V1.usub_ov(V2, Overflow);
8444 break;
8445 case ISD::SMULO:
8446 Result = V1.smul_ov(V2, Overflow);
8447 break;
8448 case ISD::UMULO:
8449 Result = V1.umul_ov(V2, Overflow);
8450 break;
8451 }
8452
8453 EVT VT = VTList.VTs[0];
8454 return getNode(ISD::MERGE_VALUES, DL, VTList,
8455 {getConstant(Result, DL, VT),
8456 getBoolConstant(Overflow, DL, VTList.VTs[1], VT)},
8457 Flags);
8458 }
8459 case ISD::SMUL_LOHI:
8460 case ISD::UMUL_LOHI:
8461 // TODO: Support non-splat vector constants.
8464 if (!C1 || !C2 || C1->isOpaque() || C2->isOpaque())
8465 return SDValue();
8466
8467 const APInt &V1 = C1->getAPIntValue(), &V2 = C2->getAPIntValue();
8468 APInt Lo = V1 * V2;
8469 APInt Hi = (Opcode == ISD::SMUL_LOHI) ? APIntOps::mulhs(V1, V2)
8470 : APIntOps::mulhu(V1, V2);
8471 return getNode(ISD::MERGE_VALUES, DL, VTList,
8472 {getConstant(Lo, DL, VTList.VTs[0]),
8473 getConstant(Hi, DL, VTList.VTs[1])},
8474 Flags);
8475 }
8476 return SDValue();
8477}
8478
8481 // TODO: Add support for unary/ternary fp opcodes.
8482 if (Ops.size() != 2)
8483 return SDValue();
8484
8485 // TODO: We don't do any constant folding for strict FP opcodes here, but we
8486 // should. That will require dealing with a potentially non-default
8487 // rounding mode, checking the "opStatus" return value from the APFloat
8488 // math calculations, and possibly other variations.
8489 SDValue N1 = Ops[0];
8490 SDValue N2 = Ops[1];
8491 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1, /*AllowUndefs*/ false);
8492 ConstantFPSDNode *N2CFP = isConstOrConstSplatFP(N2, /*AllowUndefs*/ false);
8493 if (N1CFP && N2CFP) {
8494 APFloat C1 = N1CFP->getValueAPF();
8495 const APFloat &C2 = N2CFP->getValueAPF();
8497 switch (Opcode) {
8498 case ISD::FADD:
8499 return getConstFP(tryFoldFP(FPOp::Add, {C1, C2}, DM), DL, VT);
8500 case ISD::FSUB:
8501 return getConstFP(tryFoldFP(FPOp::Sub, {C1, C2}, DM), DL, VT);
8502 case ISD::FMUL:
8503 return getConstFP(tryFoldFP(FPOp::Mul, {C1, C2}, DM), DL, VT);
8504 case ISD::FDIV:
8505 return getConstFP(tryFoldFP(FPOp::Div, {C1, C2}, DM), DL, VT);
8506 case ISD::FREM:
8507 return getConstFP(tryFoldFP(FPOp::FRem, {C1, C2}, DM), DL, VT);
8508 case ISD::FCOPYSIGN:
8509 C1.copySign(C2);
8510 return getConstantFP(C1, DL, VT);
8511 case ISD::FMINNUM:
8512 return getConstFP(tryFoldFP(FPOp::MinNum, {C1, C2}, DM), DL, VT);
8513 case ISD::FMAXNUM:
8514 return getConstFP(tryFoldFP(FPOp::MaxNum, {C1, C2}, DM), DL, VT);
8515 case ISD::FMINIMUM:
8516 return getConstFP(tryFoldFP(FPOp::Minimum, {C1, C2}, DM), DL, VT);
8517 case ISD::FMAXIMUM:
8518 return getConstFP(tryFoldFP(FPOp::Maximum, {C1, C2}, DM), DL, VT);
8519 case ISD::FMINIMUMNUM:
8520 return getConstFP(tryFoldFP(FPOp::MinimumNum, {C1, C2}, DM), DL, VT);
8521 case ISD::FMAXIMUMNUM:
8522 return getConstFP(tryFoldFP(FPOp::MaximumNum, {C1, C2}, DM), DL, VT);
8523 default: break;
8524 }
8525 }
8526 if (N1CFP && Opcode == ISD::FP_ROUND) {
8527 APFloat C1 = N1CFP->getValueAPF(); // make copy
8528 bool Unused;
8529 // This can return overflow, underflow, or inexact; we don't care.
8530 // FIXME need to be more flexible about rounding mode.
8532 &Unused);
8533 return getConstantFP(C1, DL, VT);
8534 }
8535
8536 switch (Opcode) {
8537 case ISD::FSUB:
8538 // -0.0 - undef --> undef (consistent with "fneg undef")
8539 if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1, /*AllowUndefs*/ true))
8540 if (N1C && N1C->getValueAPF().isNegZero() && N2.isUndef())
8541 return getUNDEF(VT);
8542 [[fallthrough]];
8543
8544 case ISD::FADD:
8545 case ISD::FMUL:
8546 case ISD::FDIV:
8547 case ISD::FREM:
8548 // If both operands are undef, the result is undef. If 1 operand is undef,
8549 // the result is NaN. This should match the behavior of the IR optimizer.
8550 if (N1.isUndef() && N2.isUndef())
8551 return getUNDEF(VT);
8552 if (N1.isUndef() || N2.isUndef())
8554 }
8555 return SDValue();
8556}
8557
8559 const SDLoc &DL, EVT DstEltVT) {
8560 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
8561
8562 // If this is already the right type, we're done.
8563 if (SrcEltVT == DstEltVT)
8564 return SDValue(BV, 0);
8565
8566 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
8567 unsigned DstBitSize = DstEltVT.getSizeInBits();
8568
8569 // If this is a conversion of N elements of one type to N elements of another
8570 // type, convert each element. This handles FP<->INT cases.
8571 if (SrcBitSize == DstBitSize) {
8573 for (SDValue Op : BV->op_values()) {
8574 // If the vector element type is not legal, the BUILD_VECTOR operands
8575 // are promoted and implicitly truncated. Make that explicit here.
8576 if (Op.getValueType() != SrcEltVT)
8577 Op = getNode(ISD::TRUNCATE, DL, SrcEltVT, Op);
8578 Ops.push_back(getBitcast(DstEltVT, Op));
8579 }
8580 EVT VT = EVT::getVectorVT(*getContext(), DstEltVT,
8582 return getBuildVector(VT, DL, Ops);
8583 }
8584
8585 // Otherwise, we're growing or shrinking the elements. To avoid having to
8586 // handle annoying details of growing/shrinking FP values, we convert them to
8587 // int first.
8588 if (SrcEltVT.isFloatingPoint()) {
8589 // Convert the input float vector to a int vector where the elements are the
8590 // same sizes.
8591 EVT IntEltVT = EVT::getIntegerVT(*getContext(), SrcEltVT.getSizeInBits());
8592 if (SDValue Tmp = FoldConstantBuildVector(BV, DL, IntEltVT))
8594 DstEltVT);
8595 return SDValue();
8596 }
8597
8598 // Now we know the input is an integer vector. If the output is a FP type,
8599 // convert to integer first, then to FP of the right size.
8600 if (DstEltVT.isFloatingPoint()) {
8601 EVT IntEltVT = EVT::getIntegerVT(*getContext(), DstEltVT.getSizeInBits());
8602 if (SDValue Tmp = FoldConstantBuildVector(BV, DL, IntEltVT))
8604 DstEltVT);
8605 return SDValue();
8606 }
8607
8608 // Okay, we know the src/dst types are both integers of differing types.
8609 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
8610
8611 // Extract the constant raw bit data.
8612 BitVector UndefElements;
8613 SmallVector<APInt> RawBits;
8614 bool IsLE = getDataLayout().isLittleEndian();
8615 if (!BV->getConstantRawBits(IsLE, DstBitSize, RawBits, UndefElements))
8616 return SDValue();
8617
8619 for (unsigned I = 0, E = RawBits.size(); I != E; ++I) {
8620 if (UndefElements[I])
8621 Ops.push_back(getUNDEF(DstEltVT));
8622 else
8623 Ops.push_back(getConstant(RawBits[I], DL, DstEltVT));
8624 }
8625
8626 EVT VT = EVT::getVectorVT(*getContext(), DstEltVT, Ops.size());
8627 return getBuildVector(VT, DL, Ops);
8628}
8629
8631 assert(Val.getValueType().isInteger() && "Invalid AssertAlign!");
8632
8633 // There's no need to assert on a byte-aligned pointer. All pointers are at
8634 // least byte aligned.
8635 if (A == Align(1))
8636 return Val;
8637
8638 SDVTList VTs = getVTList(Val.getValueType());
8639 SDValue Ops[] = {Val};
8640 SDNodeKey ID(ISD::AssertAlign, VTs, Ops);
8641 ID.AddInteger(A.value());
8642
8643 FoldingSetInsertToken InsertToken;
8644 if (SDNode *E = lookupNode(ID, DL, InsertToken))
8645 return SDValue(E, 0);
8646
8647 auto *N =
8648 newSDNode<AssertAlignSDNode>(DL.getIROrder(), DL.getDebugLoc(), VTs, A);
8649 createOperands(N, {Val});
8650
8651 CSEMap.insert(N, InsertToken);
8652 InsertNode(N);
8653
8654 SDValue V(N, 0);
8655 NewSDValueDbgMsg(V, "Creating new node: ", this);
8656 return V;
8657}
8658
8659SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8660 SDValue N1, SDValue N2) {
8661 SDNodeFlags Flags;
8662 if (Inserter)
8663 Flags = Inserter->getFlags();
8664 return getNode(Opcode, DL, VT, N1, N2, Flags);
8665}
8666
8668 SDValue &N2) const {
8669 if (!TLI->isCommutativeBinOp(Opcode))
8670 return;
8671
8672 // Canonicalize:
8673 // binop(const, nonconst) -> binop(nonconst, const)
8676 bool N1CFP = isConstantFPBuildVectorOrConstantFP(N1);
8677 bool N2CFP = isConstantFPBuildVectorOrConstantFP(N2);
8678 if ((N1C && !N2C) || (N1CFP && !N2CFP))
8679 std::swap(N1, N2);
8680
8681 // Canonicalize:
8682 // binop(splat(x), step_vector) -> binop(step_vector, splat(x))
8683 else if (N1.getOpcode() == ISD::SPLAT_VECTOR &&
8685 std::swap(N1, N2);
8686}
8687
8688SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8689 SDValue N1, SDValue N2, const SDNodeFlags Flags) {
8691 N2.getOpcode() != ISD::DELETED_NODE &&
8692 "Operand is DELETED_NODE!");
8693
8694 canonicalizeCommutativeBinop(Opcode, N1, N2);
8695
8696 auto *N1C = dyn_cast<ConstantSDNode>(N1);
8697 auto *N2C = dyn_cast<ConstantSDNode>(N2);
8698
8699 // Don't allow undefs in vector splats - we might be returning N2 when folding
8700 // to zero etc.
8701 ConstantSDNode *N2CV =
8702 isConstOrConstSplat(N2, /*AllowUndefs*/ false, /*AllowTruncation*/ true);
8703
8704 switch (Opcode) {
8705 default: break;
8706 case ISD::TokenFactor:
8707 assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
8708 N2.getValueType() == MVT::Other && "Invalid token factor!");
8709 // Fold trivial token factors.
8710 if (N1.getOpcode() == ISD::EntryToken) return N2;
8711 if (N2.getOpcode() == ISD::EntryToken) return N1;
8712 if (N1 == N2) return N1;
8713 break;
8714 case ISD::BUILD_VECTOR: {
8715 // Attempt to simplify BUILD_VECTOR.
8716 SDValue Ops[] = {N1, N2};
8717 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
8718 return V;
8719 break;
8720 }
8721 case ISD::CONCAT_VECTORS: {
8722 SDValue Ops[] = {N1, N2};
8723 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
8724 return V;
8725 break;
8726 }
8727 case ISD::AND:
8728 assert(VT.isInteger() && "This operator does not apply to FP types!");
8729 assert(N1.getValueType() == N2.getValueType() &&
8730 N1.getValueType() == VT && "Binary operator types must match!");
8731 // (X & 0) -> 0. This commonly occurs when legalizing i64 values, so it's
8732 // worth handling here.
8733 if (N2CV && N2CV->isZero())
8734 return N2;
8735 if (N2CV && N2CV->isAllOnes()) // X & -1 -> X
8736 return N1;
8737 break;
8738 case ISD::OR:
8739 case ISD::XOR:
8740 case ISD::ADD:
8741 case ISD::PTRADD:
8742 case ISD::SUB:
8743 assert(VT.isInteger() && "This operator does not apply to FP types!");
8744 assert(N1.getValueType() == N2.getValueType() &&
8745 N1.getValueType() == VT && "Binary operator types must match!");
8746 // The equal operand types requirement is unnecessarily strong for PTRADD.
8747 // However, the SelectionDAGBuilder does not generate PTRADDs with different
8748 // operand types, and we'd need to re-implement GEP's non-standard wrapping
8749 // logic everywhere where PTRADDs may be folded or combined to properly
8750 // support them. If/when we introduce pointer types to the SDAG, we will
8751 // need to relax this constraint.
8752
8753 // (X ^|+- 0) -> X. This commonly occurs when legalizing i64 values, so
8754 // it's worth handling here.
8755 if (N2CV && N2CV->isZero())
8756 return N1;
8757 if ((Opcode == ISD::ADD || Opcode == ISD::SUB) &&
8758 VT.getScalarType() == MVT::i1)
8759 return getNode(ISD::XOR, DL, VT, N1, N2);
8760 // Fold (add (vscale * C0), (vscale * C1)) to (vscale * (C0 + C1)).
8761 if (Opcode == ISD::ADD && N1.getOpcode() == ISD::VSCALE &&
8762 N2.getOpcode() == ISD::VSCALE) {
8763 const APInt &C1 = N1->getConstantOperandAPInt(0);
8764 const APInt &C2 = N2->getConstantOperandAPInt(0);
8765 return getVScale(DL, VT, C1 + C2);
8766 }
8767 break;
8768 case ISD::MUL:
8769 assert(VT.isInteger() && "This operator does not apply to FP types!");
8770 assert(N1.getValueType() == N2.getValueType() &&
8771 N1.getValueType() == VT && "Binary operator types must match!");
8772 if (VT.getScalarType() == MVT::i1)
8773 return getNode(ISD::AND, DL, VT, N1, N2);
8774 if (N2CV && N2CV->isZero())
8775 return N2;
8776 if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
8777 const APInt &MulImm = N1->getConstantOperandAPInt(0);
8778 const APInt &N2CImm = N2C->getAPIntValue();
8779 return getVScale(DL, VT, MulImm * N2CImm);
8780 }
8781 break;
8782 case ISD::UDIV:
8783 case ISD::UREM:
8784 case ISD::MULHU:
8785 case ISD::MULHS:
8786 case ISD::SDIV:
8787 case ISD::SREM:
8788 case ISD::SADDSAT:
8789 case ISD::SSUBSAT:
8790 case ISD::UADDSAT:
8791 case ISD::USUBSAT:
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 // fold (add_sat x, y) -> (or x, y) for bool types.
8797 if (Opcode == ISD::SADDSAT || Opcode == ISD::UADDSAT)
8798 return getNode(ISD::OR, DL, VT, N1, N2);
8799 // fold (sub_sat x, y) -> (and x, ~y) for bool types.
8800 if (Opcode == ISD::SSUBSAT || Opcode == ISD::USUBSAT)
8801 return getNode(ISD::AND, DL, VT, N1, getNOT(DL, N2, VT));
8802 // mulhs/mulhu on i1 are always 0: the high bit of the 2-bit product of
8803 // two booleans is never set. The i1 constant 1 is also -1, so folding
8804 // (mulhs x, 1) to (sra x, 0) in DAGCombiner would be wrong here.
8805 if (Opcode == ISD::MULHS || Opcode == ISD::MULHU)
8806 return getConstant(0, DL, VT);
8807 }
8808 break;
8809 case ISD::SCMP:
8810 case ISD::UCMP:
8811 assert(N1.getValueType() == N2.getValueType() &&
8812 "Types of operands of UCMP/SCMP must match");
8813 assert(N1.getValueType().isVector() == VT.isVector() &&
8814 "Operands and return type of must both be scalars or vectors");
8815 if (VT.isVector())
8818 "Result and operands must have the same number of elements");
8819 break;
8820 case ISD::AVGFLOORS:
8821 case ISD::AVGFLOORU:
8822 case ISD::AVGCEILS:
8823 case ISD::AVGCEILU:
8824 case ISD::AVGSUBFLOORS:
8825 case ISD::AVGSUBFLOORU:
8826 assert(VT.isInteger() && "This operator does not apply to FP types!");
8827 assert(N1.getValueType() == N2.getValueType() &&
8828 N1.getValueType() == VT && "Binary operator types must match!");
8829 break;
8830 case ISD::ABDS:
8831 case ISD::ABDU:
8832 assert(VT.isInteger() && "This operator does not apply to FP types!");
8833 assert(N1.getValueType() == N2.getValueType() &&
8834 N1.getValueType() == VT && "Binary operator types must match!");
8835 if (VT.getScalarType() == MVT::i1)
8836 return getNode(ISD::XOR, DL, VT, N1, N2);
8837 break;
8838 case ISD::SMIN:
8839 case ISD::UMAX:
8840 assert(VT.isInteger() && "This operator does not apply to FP types!");
8841 assert(N1.getValueType() == N2.getValueType() &&
8842 N1.getValueType() == VT && "Binary operator types must match!");
8843 if (VT.getScalarType() == MVT::i1)
8844 return getNode(ISD::OR, DL, VT, N1, N2);
8845 break;
8846 case ISD::SMAX:
8847 case ISD::UMIN:
8848 assert(VT.isInteger() && "This operator does not apply to FP types!");
8849 assert(N1.getValueType() == N2.getValueType() &&
8850 N1.getValueType() == VT && "Binary operator types must match!");
8851 if (VT.getScalarType() == MVT::i1)
8852 return getNode(ISD::AND, DL, VT, N1, N2);
8853 break;
8854 case ISD::FADD:
8855 case ISD::FSUB:
8856 case ISD::FMUL:
8857 case ISD::FDIV:
8858 case ISD::FREM:
8859 assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
8860 assert(N1.getValueType() == N2.getValueType() &&
8861 N1.getValueType() == VT && "Binary operator types must match!");
8862 if (SDValue V = simplifyFPBinop(Opcode, N1, N2, Flags))
8863 return V;
8864 break;
8865 case ISD::FCOPYSIGN: // N1 and result must match. N1/N2 need not match.
8866 assert(N1.getValueType() == VT &&
8869 "Invalid FCOPYSIGN!");
8870 break;
8871 case ISD::SHL:
8872 if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
8873 const APInt &MulImm = N1->getConstantOperandAPInt(0);
8874 const APInt &ShiftImm = N2C->getAPIntValue();
8875 return getVScale(DL, VT, MulImm << ShiftImm);
8876 }
8877 [[fallthrough]];
8878 case ISD::SRA:
8879 case ISD::SRL:
8880 if (SDValue V = simplifyShift(N1, N2))
8881 return V;
8882 [[fallthrough]];
8883 case ISD::ROTL:
8884 case ISD::ROTR:
8885 case ISD::SSHLSAT:
8886 case ISD::USHLSAT:
8887 assert(VT == N1.getValueType() &&
8888 "Shift operators return type must be the same as their first arg");
8889 assert(VT.isInteger() && N2.getValueType().isInteger() &&
8890 "Shifts only work on integers");
8891 assert((!VT.isVector() || VT == N2.getValueType()) &&
8892 "Vector shift amounts must be in the same as their first arg");
8893 // Verify that the shift amount VT is big enough to hold valid shift
8894 // amounts. This catches things like trying to shift an i1024 value by an
8895 // i8, which is easy to fall into in generic code that uses
8896 // TLI.getShiftAmount().
8899 "Invalid use of small shift amount with oversized value!");
8900
8901 // Always fold shifts of i1 values so the code generator doesn't need to
8902 // handle them. Since we know the size of the shift has to be less than the
8903 // size of the value, the shift/rotate count is guaranteed to be zero.
8904 if (VT == MVT::i1)
8905 return N1;
8906 if (N2CV && N2CV->isZero())
8907 return N1;
8908 break;
8909 case ISD::FP_ROUND:
8911 VT.bitsLE(N1.getValueType()) && N2C &&
8912 (N2C->getZExtValue() == 0 || N2C->getZExtValue() == 1) &&
8913 N2.getOpcode() == ISD::TargetConstant && "Invalid FP_ROUND!");
8914 if (N1.getValueType() == VT) return N1; // noop conversion.
8915 break;
8916 case ISD::IS_FPCLASS: {
8918 "IS_FPCLASS is used for a non-floating type");
8919 assert(isa<ConstantSDNode>(N2) && "FPClassTest is not Constant");
8920 // is.fpclass(poison, mask) -> poison
8921 if (N1.getOpcode() == ISD::POISON)
8922 return getPOISON(VT);
8923 FPClassTest Mask = static_cast<FPClassTest>(N2->getAsZExtVal());
8924 // If all tests are made, it doesn't matter what the value is.
8925 if ((Mask & fcAllFlags) == fcAllFlags)
8926 return getBoolConstant(true, DL, VT, N1.getValueType());
8927 if ((Mask & fcAllFlags) == 0)
8928 return getBoolConstant(false, DL, VT, N1.getValueType());
8929 break;
8930 }
8931 case ISD::AssertNoFPClass: {
8933 "AssertNoFPClass is used for a non-floating type");
8934 assert(isa<ConstantSDNode>(N2) && "NoFPClass is not Constant");
8935 FPClassTest NoFPClass = static_cast<FPClassTest>(N2->getAsZExtVal());
8936 assert(llvm::to_underlying(NoFPClass) <=
8938 "FPClassTest value too large");
8939 (void)NoFPClass;
8940 break;
8941 }
8942 case ISD::AssertSext:
8943 case ISD::AssertZext: {
8944 EVT EVT = cast<VTSDNode>(N2)->getVT();
8945 assert(VT == N1.getValueType() && "Not an inreg extend!");
8946 assert(VT.isInteger() && EVT.isInteger() &&
8947 "Cannot *_EXTEND_INREG FP types");
8948 assert(!EVT.isVector() &&
8949 "AssertSExt/AssertZExt type should be the vector element type "
8950 "rather than the vector type!");
8951 assert(EVT.bitsLE(VT.getScalarType()) && "Not extending!");
8952 if (VT.getScalarType() == EVT) return N1; // noop assertion.
8953 break;
8954 }
8956 EVT EVT = cast<VTSDNode>(N2)->getVT();
8957 assert(VT == N1.getValueType() && "Not an inreg extend!");
8958 assert(VT.isInteger() && EVT.isInteger() &&
8959 "Cannot *_EXTEND_INREG FP types");
8960 assert(EVT.isVector() == VT.isVector() &&
8961 "SIGN_EXTEND_INREG type should be vector iff the operand "
8962 "type is vector!");
8963 assert((!EVT.isVector() ||
8965 "Vector element counts must match in SIGN_EXTEND_INREG");
8966 assert(EVT.getScalarType().bitsLE(VT.getScalarType()) && "Not extending!");
8967 if (EVT == VT) return N1; // Not actually extending
8968 break;
8969 }
8971 case ISD::FP_TO_UINT_SAT: {
8972 assert(VT.isInteger() && cast<VTSDNode>(N2)->getVT().isInteger() &&
8973 N1.getValueType().isFloatingPoint() && "Invalid FP_TO_*INT_SAT");
8974 assert(N1.getValueType().isVector() == VT.isVector() &&
8975 "FP_TO_*INT_SAT type should be vector iff the operand type is "
8976 "vector!");
8977 assert((!VT.isVector() || VT.getVectorElementCount() ==
8979 "Vector element counts must match in FP_TO_*INT_SAT");
8980 assert(!cast<VTSDNode>(N2)->getVT().isVector() &&
8981 "Type to saturate to must be a scalar.");
8982 assert(cast<VTSDNode>(N2)->getVT().bitsLE(VT.getScalarType()) &&
8983 "Not extending!");
8984 break;
8985 }
8988 "The result of EXTRACT_VECTOR_ELT must be at least as wide as the \
8989 element type of the vector.");
8990
8991 // Extract from an undefined value or using an undefined index is undefined.
8992 if (N1.isUndef() || N2.isUndef())
8993 return getUNDEF(VT);
8994
8995 // EXTRACT_VECTOR_ELT of out-of-bounds element is POISON for fixed length
8996 // vectors. For scalable vectors we will provide appropriate support for
8997 // dealing with arbitrary indices.
8998 if (N2C && N1.getValueType().isFixedLengthVector() &&
8999 N2C->getAPIntValue().uge(N1.getValueType().getVectorNumElements()))
9000 return getPOISON(VT);
9001
9002 // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
9003 // expanding copies of large vectors from registers. This only works for
9004 // fixed length vectors, since we need to know the exact number of
9005 // elements.
9006 if (N2C && N1.getOpcode() == ISD::CONCAT_VECTORS &&
9008 unsigned Factor = N1.getOperand(0).getValueType().getVectorNumElements();
9009 return getExtractVectorElt(DL, VT,
9010 N1.getOperand(N2C->getZExtValue() / Factor),
9011 N2C->getZExtValue() % Factor);
9012 }
9013
9014 // EXTRACT_VECTOR_ELT of BUILD_VECTOR or SPLAT_VECTOR is often formed while
9015 // lowering is expanding large vector constants.
9016 if (N2C && (N1.getOpcode() == ISD::BUILD_VECTOR ||
9017 N1.getOpcode() == ISD::SPLAT_VECTOR)) {
9020 "BUILD_VECTOR used for scalable vectors");
9021 unsigned Index =
9022 N1.getOpcode() == ISD::BUILD_VECTOR ? N2C->getZExtValue() : 0;
9023 SDValue Elt = N1.getOperand(Index);
9024
9025 if (VT != Elt.getValueType())
9026 // If the vector element type is not legal, the BUILD_VECTOR operands
9027 // are promoted and implicitly truncated, and the result implicitly
9028 // extended. Make that explicit here.
9029 Elt = getAnyExtOrTrunc(Elt, DL, VT);
9030
9031 return Elt;
9032 }
9033
9034 // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
9035 // operations are lowered to scalars.
9036 if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) {
9037 // If the indices are the same, return the inserted element else
9038 // if the indices are known different, extract the element from
9039 // the original vector.
9040 SDValue N1Op2 = N1.getOperand(2);
9042
9043 if (N1Op2C && N2C) {
9044 if (N1Op2C->getZExtValue() == N2C->getZExtValue()) {
9045 if (VT == N1.getOperand(1).getValueType())
9046 return N1.getOperand(1);
9047 if (VT.isFloatingPoint()) {
9049 return getFPExtendOrRound(N1.getOperand(1), DL, VT);
9050 }
9051 return getSExtOrTrunc(N1.getOperand(1), DL, VT);
9052 }
9053 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2);
9054 }
9055 }
9056
9057 // EXTRACT_VECTOR_ELT of v1iX EXTRACT_SUBVECTOR could be formed
9058 // when vector types are scalarized and v1iX is legal.
9059 // vextract (v1iX extract_subvector(vNiX, Idx)) -> vextract(vNiX,Idx).
9060 // Here we are completely ignoring the extract element index (N2),
9061 // which is fine for fixed width vectors, since any index other than 0
9062 // is undefined anyway. However, this cannot be ignored for scalable
9063 // vectors - in theory we could support this, but we don't want to do this
9064 // without a profitability check.
9065 if (N1.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
9067 N1.getValueType().getVectorNumElements() == 1) {
9068 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0),
9069 N1.getOperand(1));
9070 }
9071 break;
9073 assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!");
9074 assert(!N1.getValueType().isVector() && !VT.isVector() &&
9075 (N1.getValueType().isInteger() == VT.isInteger()) &&
9076 N1.getValueType() != VT &&
9077 "Wrong types for EXTRACT_ELEMENT!");
9078
9079 // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
9080 // 64-bit integers into 32-bit parts. Instead of building the extract of
9081 // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
9082 if (N1.getOpcode() == ISD::BUILD_PAIR)
9083 return N1.getOperand(N2C->getZExtValue());
9084
9085 // EXTRACT_ELEMENT of a constant int is also very common.
9086 if (N1C) {
9087 unsigned ElementSize = VT.getSizeInBits();
9088 unsigned Shift = ElementSize * N2C->getZExtValue();
9089 const APInt &Val = N1C->getAPIntValue();
9090 return getConstant(Val.extractBits(ElementSize, Shift), DL, VT);
9091 }
9092 break;
9094 [[maybe_unused]] EVT MaskVT = N2.getValueType();
9095 assert(VT == N1.getValueType() &&
9096 "VECTOR_SHUFFLE_VAR result and source types don't match.");
9097 assert(VT.isVector() && MaskVT.isVector() &&
9098 "VECTOR_SHUFFLE_VAR operands must be vectors.");
9100 "VECTOR_SHUFFLE_VAR mask must be a vector of integers.");
9102 "VECTOR_SHUFFLE_VAR mask has the wrong number of elements.");
9103 // The only in-range index is 0; any other index gives poison.
9105 return N1;
9106 break;
9107 }
9109 EVT N1VT = N1.getValueType();
9110 assert(VT.isVector() && N1VT.isVector() &&
9111 "Extract subvector VTs must be vectors!");
9113 "Extract subvector VTs must have the same element type!");
9114 assert((VT.isFixedLengthVector() || N1VT.isScalableVector()) &&
9115 "Cannot extract a scalable vector from a fixed length vector!");
9116 assert((VT.isScalableVector() != N1VT.isScalableVector() ||
9118 "Extract subvector must be from larger vector to smaller vector!");
9119 assert(N2C && "Extract subvector index must be a constant");
9120 assert((VT.isScalableVector() != N1VT.isScalableVector() ||
9121 (VT.getVectorMinNumElements() + N2C->getZExtValue()) <=
9122 N1VT.getVectorMinNumElements()) &&
9123 "Extract subvector overflow!");
9124 assert(N2C->getAPIntValue().getBitWidth() ==
9125 TLI->getVectorIdxWidth(getDataLayout()) &&
9126 "Constant index for EXTRACT_SUBVECTOR has an invalid size");
9127 assert(N2C->getZExtValue() % VT.getVectorMinNumElements() == 0 &&
9128 "Extract index is not a multiple of the output vector length");
9129
9130 // Trivial extraction.
9131 if (VT == N1VT)
9132 return N1;
9133
9134 // EXTRACT_SUBVECTOR of an UNDEF is an UNDEF.
9135 if (N1.isUndef())
9136 return getUNDEF(VT);
9137
9138 // EXTRACT_SUBVECTOR of CONCAT_VECTOR can be simplified if the pieces of
9139 // the concat have the same type as the extract.
9140 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
9141 VT == N1.getOperand(0).getValueType()) {
9142 unsigned Factor = VT.getVectorMinNumElements();
9143 return N1.getOperand(N2C->getZExtValue() / Factor);
9144 }
9145
9146 // EXTRACT_SUBVECTOR of INSERT_SUBVECTOR is often created
9147 // during shuffle legalization.
9148 if (N1.getOpcode() == ISD::INSERT_SUBVECTOR && N2 == N1.getOperand(2) &&
9149 VT == N1.getOperand(1).getValueType())
9150 return N1.getOperand(1);
9151 break;
9152 }
9153 }
9154
9155 if (N1.getOpcode() == ISD::POISON || N2.getOpcode() == ISD::POISON) {
9156 switch (Opcode) {
9157 case ISD::XOR:
9158 case ISD::ADD:
9159 case ISD::PTRADD:
9160 case ISD::SUB:
9162 case ISD::UDIV:
9163 case ISD::SDIV:
9164 case ISD::UREM:
9165 case ISD::SREM:
9166 case ISD::MUL:
9167 case ISD::AND:
9168 case ISD::SSUBSAT:
9169 case ISD::USUBSAT:
9170 case ISD::UMIN:
9171 case ISD::OR:
9172 case ISD::SADDSAT:
9173 case ISD::UADDSAT:
9174 case ISD::UMAX:
9175 case ISD::SMAX:
9176 case ISD::SMIN:
9177 // fold op(arg1, poison) -> poison, fold op(poison, arg2) -> poison.
9178 return N2.getOpcode() == ISD::POISON ? N2 : N1;
9179 }
9180 }
9181
9182 // Canonicalize an UNDEF to the RHS, even over a constant.
9183 if (N1.getOpcode() == ISD::UNDEF && N2.getOpcode() != ISD::UNDEF) {
9184 if (TLI->isCommutativeBinOp(Opcode)) {
9185 std::swap(N1, N2);
9186 } else {
9187 switch (Opcode) {
9188 case ISD::PTRADD:
9189 case ISD::SUB:
9190 // fold op(undef, non_undef_arg2) -> undef.
9191 return N1;
9193 case ISD::UDIV:
9194 case ISD::SDIV:
9195 case ISD::UREM:
9196 case ISD::SREM:
9197 case ISD::SSUBSAT:
9198 case ISD::USUBSAT:
9199 // fold op(undef, non_undef_arg2) -> 0.
9200 return getConstant(0, DL, VT);
9201 }
9202 }
9203 }
9204
9205 // Fold a bunch of operators when the RHS is undef.
9206 if (N2.getOpcode() == ISD::UNDEF) {
9207 switch (Opcode) {
9208 case ISD::XOR:
9209 if (N1.getOpcode() == ISD::UNDEF)
9210 // Handle undef ^ undef -> 0 special case. This is a common
9211 // idiom (misuse).
9212 return getConstant(0, DL, VT);
9213 [[fallthrough]];
9214 case ISD::ADD:
9215 case ISD::PTRADD:
9216 case ISD::SUB:
9217 // fold op(arg1, undef) -> undef.
9218 return N2;
9219 case ISD::UDIV:
9220 case ISD::SDIV:
9221 case ISD::UREM:
9222 case ISD::SREM:
9223 // fold op(arg1, undef) -> poison.
9224 return getPOISON(VT);
9225 case ISD::MUL:
9226 case ISD::AND:
9227 case ISD::SSUBSAT:
9228 case ISD::USUBSAT:
9229 case ISD::UMIN:
9230 // fold op(undef, undef) -> undef, fold op(arg1, undef) -> 0.
9231 return N1.getOpcode() == ISD::UNDEF ? N2 : getConstant(0, DL, VT);
9232 case ISD::OR:
9233 case ISD::SADDSAT:
9234 case ISD::UADDSAT:
9235 case ISD::UMAX:
9236 // fold op(undef, undef) -> undef, fold op(arg1, undef) -> -1.
9237 return N1.getOpcode() == ISD::UNDEF ? N2 : getAllOnesConstant(DL, VT);
9238 case ISD::SMAX:
9239 // fold op(undef, undef) -> undef, fold op(arg1, undef) -> MAX_INT.
9240 return N1.getOpcode() == ISD::UNDEF
9241 ? N2
9242 : getConstant(
9244 VT);
9245 case ISD::SMIN:
9246 // fold op(undef, undef) -> undef, fold op(arg1, undef) -> MIN_INT.
9247 return N1.getOpcode() == ISD::UNDEF
9248 ? N2
9249 : getConstant(
9251 VT);
9252 }
9253 }
9254
9255 // Perform trivial constant folding.
9256 if (SDValue SV = FoldConstantArithmetic(Opcode, DL, VT, {N1, N2}, Flags))
9257 return SV;
9258
9259 // Memoize this node if possible.
9260 SDNode *N;
9261 SDVTList VTs = getVTList(VT);
9262 SDValue Ops[] = {N1, N2};
9263 if (VT != MVT::Glue) {
9264 SDNodeKey ID(Opcode, VTs, Ops);
9265 FoldingSetInsertToken InsertToken;
9266 if (SDNode *E = lookupNode(ID, DL, InsertToken)) {
9267 E->intersectFlagsWith(Flags);
9268 return SDValue(E, 0);
9269 }
9270
9271 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
9272 N->setFlags(Flags);
9273 createOperands(N, Ops);
9274 CSEMap.insert(N, InsertToken);
9275 } else {
9276 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
9277 createOperands(N, Ops);
9278 }
9279
9280 InsertNode(N);
9281 SDValue V = SDValue(N, 0);
9282 NewSDValueDbgMsg(V, "Creating new node: ", this);
9283 return V;
9284}
9285
9286SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
9287 SDValue N1, SDValue N2, SDValue N3) {
9288 SDNodeFlags Flags;
9289 if (Inserter)
9290 Flags = Inserter->getFlags();
9291 return getNode(Opcode, DL, VT, N1, N2, N3, Flags);
9292}
9293
9294SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
9295 SDValue N1, SDValue N2, SDValue N3,
9296 const SDNodeFlags Flags) {
9298 N2.getOpcode() != ISD::DELETED_NODE &&
9299 N3.getOpcode() != ISD::DELETED_NODE &&
9300 "Operand is DELETED_NODE!");
9301 // Perform various simplifications.
9302 switch (Opcode) {
9303 case ISD::BUILD_VECTOR: {
9304 // Attempt to simplify BUILD_VECTOR.
9305 SDValue Ops[] = {N1, N2, N3};
9306 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
9307 return V;
9308 break;
9309 }
9310 case ISD::CONCAT_VECTORS: {
9311 SDValue Ops[] = {N1, N2, N3};
9312 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
9313 return V;
9314 break;
9315 }
9316 case ISD::SETCC: {
9317 assert(VT.isInteger() && "SETCC result type must be an integer!");
9318 assert(N1.getValueType() == N2.getValueType() &&
9319 "SETCC operands must have the same type!");
9320 assert(VT.isVector() == N1.getValueType().isVector() &&
9321 "SETCC type should be vector iff the operand type is vector!");
9322 assert((!VT.isVector() || VT.getVectorElementCount() ==
9324 "SETCC vector element counts must match!");
9325 // Use FoldSetCC to simplify SETCC's.
9326 if (SDValue V =
9327 FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL, Flags))
9328 return V;
9329 break;
9330 }
9331 case ISD::SELECT:
9332 case ISD::VSELECT:
9333 if (SDValue V = simplifySelect(N1, N2, N3))
9334 return V;
9335 break;
9337 llvm_unreachable("should use getVectorShuffle constructor!");
9339 if (isNullConstant(N3))
9340 return N1;
9341 break;
9343 if (isNullConstant(N3))
9344 return N2;
9345 break;
9347 assert(VT.isVector() && VT == N1.getValueType() &&
9348 "INSERT_VECTOR_ELT vector type mismatch");
9350 "INSERT_VECTOR_ELT scalar fp/int mismatch");
9351 assert((!VT.isFloatingPoint() ||
9352 VT.getVectorElementType() == N2.getValueType()) &&
9353 "INSERT_VECTOR_ELT fp scalar type mismatch");
9354 assert((!VT.isInteger() ||
9356 "INSERT_VECTOR_ELT int scalar size mismatch");
9357
9358 auto *N3C = dyn_cast<ConstantSDNode>(N3);
9359 // INSERT_VECTOR_ELT into out-of-bounds element is an UNDEF, except
9360 // for scalable vectors where we will generate appropriate code to
9361 // deal with out-of-bounds cases correctly.
9362 if (N3C && VT.isFixedLengthVector() &&
9363 N3C->getZExtValue() >= VT.getVectorNumElements())
9364 return getUNDEF(VT);
9365
9366 // Undefined index can be assumed out-of-bounds, so that's UNDEF too.
9367 if (N3.isUndef())
9368 return getUNDEF(VT);
9369
9370 // If inserting poison, just use the input vector.
9371 if (N2.getOpcode() == ISD::POISON)
9372 return N1;
9373
9374 // Inserting undef into undef/poison is still undef.
9375 if (N2.getOpcode() == ISD::UNDEF && N1.isUndef())
9376 return getUNDEF(VT);
9377
9378 // If the inserted element is an UNDEF, just use the input vector.
9379 // But not if skipping the insert could make the result more poisonous.
9380 if (N2.isUndef()) {
9381 if (N3C && VT.isFixedLengthVector()) {
9382 APInt EltMask =
9383 APInt::getOneBitSet(VT.getVectorNumElements(), N3C->getZExtValue());
9384 if (isGuaranteedNotToBePoison(N1, EltMask))
9385 return N1;
9386 } else if (isGuaranteedNotToBePoison(N1))
9387 return N1;
9388 }
9389 break;
9390 }
9391 case ISD::INSERT_SUBVECTOR: {
9392 // If inserting poison, just use the input vector,
9393 if (N2.getOpcode() == ISD::POISON)
9394 return N1;
9395
9396 // Inserting undef into undef/poison is still undef.
9397 if (N2.getOpcode() == ISD::UNDEF && N1.isUndef())
9398 return getUNDEF(VT);
9399
9400 EVT N2VT = N2.getValueType();
9401 assert(VT == N1.getValueType() &&
9402 "Dest and insert subvector source types must match!");
9403 assert(VT.isVector() && N2VT.isVector() &&
9404 "Insert subvector VTs must be vectors!");
9406 "Insert subvector VTs must have the same element type!");
9407 assert((VT.isScalableVector() || N2VT.isFixedLengthVector()) &&
9408 "Cannot insert a scalable vector into a fixed length vector!");
9409 assert((VT.isScalableVector() != N2VT.isScalableVector() ||
9411 "Insert subvector must be from smaller vector to larger vector!");
9413 "Insert subvector index must be constant");
9414 assert((VT.isScalableVector() != N2VT.isScalableVector() ||
9415 (N2VT.getVectorMinNumElements() + N3->getAsZExtVal()) <=
9417 "Insert subvector overflow!");
9419 TLI->getVectorIdxWidth(getDataLayout()) &&
9420 "Constant index for INSERT_SUBVECTOR has an invalid size");
9421
9422 // Trivial insertion.
9423 if (VT == N2VT)
9424 return N2;
9425
9426 // If this is an insert of an extracted vector into an undef/poison vector,
9427 // we can just use the input to the extract. But not if skipping the
9428 // extract+insert could make the result more poisonous.
9429 if (N1.isUndef() && N2.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
9430 N2.getOperand(1) == N3 && N2.getOperand(0).getValueType() == VT) {
9431 if (N1.getOpcode() == ISD::POISON)
9432 return N2.getOperand(0);
9433 if (VT.isFixedLengthVector() && N2VT.isFixedLengthVector()) {
9434 unsigned LoBit = N3->getAsZExtVal();
9435 unsigned HiBit = LoBit + N2VT.getVectorNumElements();
9436 APInt EltMask =
9437 APInt::getBitsSet(VT.getVectorNumElements(), LoBit, HiBit);
9438 if (isGuaranteedNotToBePoison(N2.getOperand(0), ~EltMask))
9439 return N2.getOperand(0);
9440 } else if (isGuaranteedNotToBePoison(N2.getOperand(0)))
9441 return N2.getOperand(0);
9442 }
9443
9444 // If the inserted subvector is UNDEF, just use the input vector.
9445 // But not if skipping the insert could make the result more poisonous.
9446 if (N2.isUndef()) {
9447 if (VT.isFixedLengthVector()) {
9448 unsigned LoBit = N3->getAsZExtVal();
9449 unsigned HiBit = LoBit + N2VT.getVectorNumElements();
9450 APInt EltMask =
9451 APInt::getBitsSet(VT.getVectorNumElements(), LoBit, HiBit);
9452 if (isGuaranteedNotToBePoison(N1, EltMask))
9453 return N1;
9454 } else if (isGuaranteedNotToBePoison(N1))
9455 return N1;
9456 }
9457 break;
9458 }
9459 case ISD::BITCAST:
9460 // Fold bit_convert nodes from a type to themselves.
9461 if (N1.getValueType() == VT)
9462 return N1;
9463 break;
9464 case ISD::VECTOR_COMPRESS: {
9465 [[maybe_unused]] EVT VecVT = N1.getValueType();
9466 [[maybe_unused]] EVT MaskVT = N2.getValueType();
9467 [[maybe_unused]] EVT PassthruVT = N3.getValueType();
9468 assert(VT == VecVT && "Vector and result type don't match.");
9469 assert(VecVT.isVector() && MaskVT.isVector() && PassthruVT.isVector() &&
9470 "All inputs must be vectors.");
9471 assert(VecVT == PassthruVT && "Vector and passthru types don't match.");
9473 "Vector and mask must have same number of elements.");
9474
9475 if (N1.isUndef() || N2.isUndef())
9476 return N3;
9477
9478 break;
9479 }
9484 [[maybe_unused]] EVT AccVT = N1.getValueType();
9485 [[maybe_unused]] EVT Input1VT = N2.getValueType();
9486 [[maybe_unused]] EVT Input2VT = N3.getValueType();
9487 assert(Input1VT.isVector() && Input1VT == Input2VT &&
9488 "Expected the second and third operands of the PARTIAL_REDUCE_MLA "
9489 "node to have the same type!");
9490 assert(VT.isVector() && VT == AccVT &&
9491 "Expected the first operand of the PARTIAL_REDUCE_MLA node to have "
9492 "the same type as its result!");
9494 AccVT.getVectorElementCount()) &&
9495 "Expected the element count of the second and third operands of the "
9496 "PARTIAL_REDUCE_MLA node to be a positive integer multiple of the "
9497 "element count of the first operand and the result!");
9499 "Expected the second and third operands of the PARTIAL_REDUCE_MLA "
9500 "node to have an element type which is the same as or smaller than "
9501 "the element type of the first operand and result!");
9502 break;
9503 }
9504 }
9505
9506 // Perform trivial constant folding for arithmetic operators.
9507 switch (Opcode) {
9511 case ISD::FMA:
9512 case ISD::FMAD:
9513 case ISD::SETCC:
9514 case ISD::FSHL:
9515 case ISD::FSHR:
9516 if (SDValue SV =
9517 FoldConstantArithmetic(Opcode, DL, VT, {N1, N2, N3}, Flags))
9518 return SV;
9519 break;
9520 }
9521
9522 // Memoize node if it doesn't produce a glue result.
9523 SDNode *N;
9524 SDVTList VTs = getVTList(VT);
9525 SDValue Ops[] = {N1, N2, N3};
9526 if (VT != MVT::Glue) {
9527 SDNodeKey ID(Opcode, VTs, Ops);
9528 FoldingSetInsertToken InsertToken;
9529 if (SDNode *E = lookupNode(ID, DL, InsertToken)) {
9530 E->intersectFlagsWith(Flags);
9531 return SDValue(E, 0);
9532 }
9533
9534 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
9535 N->setFlags(Flags);
9536 createOperands(N, Ops);
9537 CSEMap.insert(N, InsertToken);
9538 } else {
9539 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
9540 createOperands(N, Ops);
9541 }
9542
9543 InsertNode(N);
9544 SDValue V = SDValue(N, 0);
9545 NewSDValueDbgMsg(V, "Creating new node: ", this);
9546 return V;
9547}
9548
9549SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
9550 SDValue N1, SDValue N2, SDValue N3, SDValue N4,
9551 const SDNodeFlags Flags) {
9552 SDValue Ops[] = { N1, N2, N3, N4 };
9553 return getNode(Opcode, DL, VT, Ops, Flags);
9554}
9555
9556SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
9557 SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
9558 SDNodeFlags Flags;
9559 if (Inserter)
9560 Flags = Inserter->getFlags();
9561 return getNode(Opcode, DL, VT, N1, N2, N3, N4, Flags);
9562}
9563
9564SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
9565 SDValue N1, SDValue N2, SDValue N3, SDValue N4,
9566 SDValue N5, const SDNodeFlags Flags) {
9567 SDValue Ops[] = { N1, N2, N3, N4, N5 };
9568 return getNode(Opcode, DL, VT, Ops, Flags);
9569}
9570
9571SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
9572 SDValue N1, SDValue N2, SDValue N3, SDValue N4,
9573 SDValue N5) {
9574 SDNodeFlags Flags;
9575 if (Inserter)
9576 Flags = Inserter->getFlags();
9577 return getNode(Opcode, DL, VT, N1, N2, N3, N4, N5, Flags);
9578}
9579
9580/// getStackArgumentTokenFactor - Compute a TokenFactor to force all
9581/// the incoming stack arguments to be loaded from the stack.
9583 SmallVector<SDValue, 8> ArgChains;
9584
9585 // Include the original chain at the beginning of the list. When this is
9586 // used by target LowerCall hooks, this helps legalize find the
9587 // CALLSEQ_BEGIN node.
9588 ArgChains.push_back(Chain);
9589
9590 // Add a chain value for each stack argument.
9591 for (SDNode *U : getEntryNode().getNode()->users())
9592 if (LoadSDNode *L = dyn_cast<LoadSDNode>(U))
9593 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
9594 if (FI->getIndex() < 0)
9595 ArgChains.push_back(SDValue(L, 1));
9596
9597 // Build a tokenfactor for all the chains.
9598 return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
9599}
9600
9601/// getMemsetValue - Vectorized representation of the memset value
9602/// operand.
9604 const SDLoc &dl) {
9605 assert(!Value.isUndef());
9606
9607 unsigned NumBits = VT.getScalarSizeInBits();
9609 assert(C->getAPIntValue().getBitWidth() == 8);
9610 APInt Val = APInt::getSplat(NumBits, C->getAPIntValue());
9611 if (VT.isInteger()) {
9612 bool IsOpaque = VT.getSizeInBits() > 64 ||
9613 !DAG.getTargetLoweringInfo().isLegalStoreImmediate(C->getSExtValue());
9614 return DAG.getConstant(Val, dl, VT, false, IsOpaque);
9615 }
9616 return DAG.getConstantFP(APFloat(VT.getFltSemantics(), Val), dl, VT);
9617 }
9618
9619 assert(Value.getValueType() == MVT::i8 && "memset with non-byte fill value?");
9620 EVT IntVT = VT.getScalarType();
9621 if (!IntVT.isInteger())
9622 IntVT = EVT::getIntegerVT(*DAG.getContext(), IntVT.getSizeInBits());
9623
9624 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, Value);
9625 if (NumBits > 8) {
9626 // Use a multiplication with 0x010101... to extend the input to the
9627 // required length.
9628 APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01));
9629 Value = DAG.getNode(ISD::MUL, dl, IntVT, Value,
9630 DAG.getConstant(Magic, dl, IntVT));
9631 }
9632
9633 if (VT != Value.getValueType() && !VT.isInteger())
9634 Value = DAG.getBitcast(VT.getScalarType(), Value);
9635 if (VT != Value.getValueType())
9636 Value = DAG.getSplatBuildVector(VT, dl, Value);
9637
9638 return Value;
9639}
9640
9641/// getMemsetStringVal - Similar to getMemsetValue. Except this is only
9642/// used when a memcpy is turned into a memset when the source is a constant
9643/// string ptr.
9645 const TargetLowering &TLI,
9646 const ConstantDataArraySlice &Slice) {
9647 // Handle vector with all elements zero.
9648 if (Slice.Array == nullptr) {
9649 if (VT.isInteger())
9650 return DAG.getConstant(0, dl, VT);
9651 return DAG.getNode(ISD::BITCAST, dl, VT,
9652 DAG.getConstant(0, dl, VT.changeTypeToInteger()));
9653 }
9654
9655 assert(!VT.isVector() && "Can't handle vector type here!");
9656 unsigned NumVTBits = VT.getSizeInBits();
9657 unsigned NumVTBytes = NumVTBits / 8;
9658 unsigned NumBytes = std::min(NumVTBytes, unsigned(Slice.Length));
9659
9660 APInt Val(NumVTBits, 0);
9661 if (DAG.getDataLayout().isLittleEndian()) {
9662 for (unsigned i = 0; i != NumBytes; ++i)
9663 Val |= (uint64_t)(unsigned char)Slice[i] << i*8;
9664 } else {
9665 for (unsigned i = 0; i != NumBytes; ++i)
9666 Val |= (uint64_t)(unsigned char)Slice[i] << (NumVTBytes-i-1)*8;
9667 }
9668
9669 // If the "cost" of materializing the integer immediate is less than the cost
9670 // of a load, then it is cost effective to turn the load into the immediate.
9671 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
9672 if (TLI.shouldConvertConstantLoadToIntImm(Val, Ty))
9673 return DAG.getConstant(Val, dl, VT);
9674 return SDValue();
9675}
9676
9678 const SDLoc &DL,
9679 const SDNodeFlags Flags) {
9680 SDValue Index = getTypeSize(DL, Base.getValueType(), Offset);
9681 return getMemBasePlusOffset(Base, Index, DL, Flags);
9682}
9683
9685 const SDLoc &DL,
9686 const SDNodeFlags Flags) {
9687 assert(Offset.getValueType().isInteger());
9688 EVT BasePtrVT = Ptr.getValueType();
9689 if (TLI->shouldPreservePtrArith(this->getMachineFunction().getFunction(),
9690 BasePtrVT))
9691 return getNode(ISD::PTRADD, DL, BasePtrVT, Ptr, Offset, Flags);
9692 // InBounds only applies to PTRADD, don't set it if we generate ADD.
9693 SDNodeFlags AddFlags = Flags;
9694 AddFlags.setInBounds(false);
9695 return getNode(ISD::ADD, DL, BasePtrVT, Ptr, Offset, AddFlags);
9696}
9697
9698/// Returns true if memcpy source is constant data.
9700 uint64_t SrcDelta = 0;
9701 GlobalAddressSDNode *G = nullptr;
9702 if (Src.getOpcode() == ISD::GlobalAddress)
9704 else if (Src->isAnyAdd() &&
9705 Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
9706 Src.getOperand(1).getOpcode() == ISD::Constant) {
9707 G = cast<GlobalAddressSDNode>(Src.getOperand(0));
9708 SrcDelta = Src.getConstantOperandVal(1);
9709 }
9710 if (!G)
9711 return false;
9712
9713 return getConstantDataArrayInfo(G->getGlobal(), Slice, 8,
9714 SrcDelta + G->getOffset());
9715}
9716
9718 SelectionDAG &DAG) {
9719 // On Darwin, -Os means optimize for size without hurting performance, so
9720 // only really optimize for size when -Oz (MinSize) is used.
9722 return MF.getFunction().hasMinSize();
9723 return DAG.shouldOptForSize();
9724}
9725
9727 SmallVector<SDValue, 32> &OutChains, unsigned From,
9728 unsigned To, SmallVector<SDValue, 16> &OutLoadChains,
9729 SmallVector<SDValue, 16> &OutStoreChains) {
9730 assert(OutLoadChains.size() && "Missing loads in memcpy inlining");
9731 assert(OutStoreChains.size() && "Missing stores in memcpy inlining");
9732 SmallVector<SDValue, 16> GluedLoadChains;
9733 for (unsigned i = From; i < To; ++i) {
9734 OutChains.push_back(OutLoadChains[i]);
9735 GluedLoadChains.push_back(OutLoadChains[i]);
9736 }
9737
9738 // Chain for all loads.
9739 SDValue LoadToken = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
9740 GluedLoadChains);
9741
9742 for (unsigned i = From; i < To; ++i) {
9743 StoreSDNode *ST = dyn_cast<StoreSDNode>(OutStoreChains[i]);
9744 SDValue NewStore = DAG.getTruncStore(LoadToken, dl, ST->getValue(),
9745 ST->getBasePtr(), ST->getMemoryVT(),
9746 ST->getMemOperand());
9747 OutChains.push_back(NewStore);
9748 }
9749}
9750
9751static SDValue
9753 SDValue Dst, SDValue Src, uint64_t Size, Align DstAlign,
9754 Align SrcAlign, bool isVol, bool AlwaysInline,
9755 MachinePointerInfo DstPtrInfo,
9756 MachinePointerInfo SrcPtrInfo, const AAMDNodes &AAInfo,
9757 BatchAAResults *BatchAA, const MDNode *DstMemCacheHint,
9758 const MDNode *SrcMemCacheHint) {
9759 // Turn a memcpy of undef to nop.
9760 // FIXME: We need to honor volatile even is Src is undef.
9761 if (Src.isUndef())
9762 return Chain;
9763
9764 // Expand memcpy to a series of load and store ops if the size operand falls
9765 // below a certain threshold.
9766 // TODO: In the AlwaysInline case, if the size is big then generate a loop
9767 // rather than maybe a humongous number of loads and stores.
9769 const DataLayout &DL = DAG.getDataLayout();
9770 LLVMContext &C = *DAG.getContext();
9771 std::vector<EVT> MemOps;
9772 bool DstAlignCanChange = false;
9774 MachineFrameInfo &MFI = MF.getFrameInfo();
9775 bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
9777 if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
9778 DstAlignCanChange = true;
9779 SrcAlign = std::max(SrcAlign, DAG.InferPtrAlign(Src).valueOrOne());
9781 // If marked as volatile, perform a copy even when marked as constant.
9782 bool CopyFromConstant = !isVol && isMemSrcFromConstant(Src, Slice);
9783 bool isZeroConstant = CopyFromConstant && Slice.Array == nullptr;
9784 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize);
9785 const MemOp Op = isZeroConstant
9786 ? MemOp::Set(Size, DstAlignCanChange, DstAlign,
9787 /*IsZeroMemset*/ true, isVol)
9788 : MemOp::Copy(Size, DstAlignCanChange, DstAlign,
9789 SrcAlign, isVol, CopyFromConstant);
9790 if (!TLI.findOptimalMemOpLowering(
9791 C, MemOps, Limit, Op, DstPtrInfo.getAddrSpace(),
9792 SrcPtrInfo.getAddrSpace(), MF.getFunction().getAttributes(), nullptr))
9793 return SDValue();
9794
9795 if (DstAlignCanChange) {
9796 Type *Ty = MemOps[0].getTypeForEVT(C);
9797 Align NewDstAlign = DL.getABITypeAlign(Ty);
9798
9799 // Don't promote to an alignment that would require dynamic stack
9800 // realignment which may conflict with optimizations such as tail call
9801 // optimization.
9803 if (!TRI->hasStackRealignment(MF))
9804 if (MaybeAlign StackAlign = DL.getStackAlignment())
9805 NewDstAlign = std::min(NewDstAlign, *StackAlign);
9806
9807 if (NewDstAlign > DstAlign) {
9808 // Give the stack frame object a larger alignment if needed.
9809 if (MFI.getObjectAlign(FI->getIndex()) < NewDstAlign)
9810 MFI.setObjectAlignment(FI->getIndex(), NewDstAlign);
9811 DstAlign = NewDstAlign;
9812 }
9813 }
9814
9815 // Prepare AAInfo for loads/stores after lowering this memcpy.
9816 AAMDNodes NewAAInfo = AAInfo;
9817 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
9818
9819 const Value *SrcVal = dyn_cast_if_present<const Value *>(SrcPtrInfo.V);
9820 bool isConstant =
9821 BatchAA && SrcVal &&
9822 BatchAA->pointsToConstantMemory(MemoryLocation(SrcVal, Size, AAInfo));
9823
9824 MachineMemOperand::Flags MMOFlags =
9826 SmallVector<SDValue, 16> OutLoadChains;
9827 SmallVector<SDValue, 16> OutStoreChains;
9828 SmallVector<SDValue, 32> OutChains;
9829 unsigned NumMemOps = MemOps.size();
9830 uint64_t SrcOff = 0, DstOff = 0;
9831 for (unsigned i = 0; i != NumMemOps; ++i) {
9832 EVT VT = MemOps[i];
9833 unsigned VTSize = VT.getSizeInBits() / 8;
9835
9836 if (VTSize > Size) {
9837 // Issuing an unaligned load / store pair that overlaps with the previous
9838 // pair. Adjust the offset accordingly.
9839 assert(i == NumMemOps-1 && i != 0);
9840 SrcOff -= VTSize - Size;
9841 DstOff -= VTSize - Size;
9842 }
9843
9844 if (CopyFromConstant &&
9845 (isZeroConstant || (VT.isInteger() && !VT.isVector()))) {
9846 // It's unlikely a store of a vector immediate can be done in a single
9847 // instruction. It would require a load from a constantpool first.
9848 // We only handle zero vectors here.
9849 // FIXME: Handle other cases where store of vector immediate is done in
9850 // a single instruction.
9851 ConstantDataArraySlice SubSlice;
9852 if (SrcOff < Slice.Length) {
9853 SubSlice = Slice;
9854 SubSlice.move(SrcOff);
9855 } else {
9856 // This is an out-of-bounds access and hence UB. Pretend we read zero.
9857 SubSlice.Array = nullptr;
9858 SubSlice.Offset = 0;
9859 SubSlice.Length = VTSize;
9860 }
9861 Value = getMemsetStringVal(VT, dl, DAG, TLI, SubSlice);
9862 if (Value.getNode()) {
9863 Store = DAG.getStore(
9864 Chain, dl, Value,
9865 DAG.getObjectPtrOffset(dl, Dst, TypeSize::getFixed(DstOff)),
9866 DstPtrInfo.getWithOffset(DstOff), DstAlign, MMOFlags,
9867 MMOMetadata(NewAAInfo, /*Ranges=*/nullptr, DstMemCacheHint));
9868 OutChains.push_back(Store);
9869 }
9870 }
9871
9872 if (!Store.getNode()) {
9873 // The type might not be legal for the target. This should only happen
9874 // if the type is smaller than a legal type, as on PPC, so the right
9875 // thing to do is generate a LoadExt/StoreTrunc pair. These simplify
9876 // to Load/Store if NVT==VT.
9877 // FIXME does the case above also need this?
9878 EVT NVT = TLI.getTypeToTransformTo(C, VT);
9879 assert(NVT.bitsGE(VT));
9880
9881 bool isDereferenceable =
9882 SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
9883 MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
9884 if (isDereferenceable)
9886 if (isConstant)
9887 SrcMMOFlags |= MachineMemOperand::MOInvariant;
9888
9889 Value = DAG.getExtLoad(
9890 ISD::EXTLOAD, dl, NVT, Chain,
9891 DAG.getObjectPtrOffset(dl, Src, TypeSize::getFixed(SrcOff)),
9892 SrcPtrInfo.getWithOffset(SrcOff), VT,
9893 commonAlignment(SrcAlign, SrcOff), SrcMMOFlags,
9894 MMOMetadata(NewAAInfo, /*Ranges=*/nullptr, SrcMemCacheHint));
9895 OutLoadChains.push_back(Value.getValue(1));
9896
9897 Store = DAG.getTruncStore(
9898 Chain, dl, Value,
9899 DAG.getObjectPtrOffset(dl, Dst, TypeSize::getFixed(DstOff)),
9900 DstPtrInfo.getWithOffset(DstOff), VT, DstAlign, MMOFlags,
9901 MMOMetadata(NewAAInfo, /*Ranges=*/nullptr, DstMemCacheHint));
9902 OutStoreChains.push_back(Store);
9903 }
9904 SrcOff += VTSize;
9905 DstOff += VTSize;
9906 Size -= VTSize;
9907 }
9908
9909 unsigned MaxLdStGlue = DAG.getSelectionDAGOptions().ldstmemcpy_glue_max;
9910 unsigned GluedLdStLimit =
9911 MaxLdStGlue == 0 ? TLI.getMaxGluedStoresPerMemcpy() : MaxLdStGlue;
9912 unsigned NumLdStInMemcpy = OutStoreChains.size();
9913
9914 if (NumLdStInMemcpy) {
9915 // It may be that memcpy might be converted to memset if it's memcpy
9916 // of constants. In such a case, we won't have loads and stores, but
9917 // just stores. In the absence of loads, there is nothing to gang up.
9918 if ((GluedLdStLimit <= 1) ||
9919 !DAG.getSelectionDAGOptions().enable_memcpy_dag_opt) {
9920 // If target does not care, just leave as it.
9921 for (unsigned i = 0; i < NumLdStInMemcpy; ++i) {
9922 OutChains.push_back(OutLoadChains[i]);
9923 OutChains.push_back(OutStoreChains[i]);
9924 }
9925 } else {
9926 // Ld/St less than/equal limit set by target.
9927 if (NumLdStInMemcpy <= GluedLdStLimit) {
9928 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
9929 NumLdStInMemcpy, OutLoadChains,
9930 OutStoreChains);
9931 } else {
9932 unsigned NumberLdChain = NumLdStInMemcpy / GluedLdStLimit;
9933 unsigned RemainingLdStInMemcpy = NumLdStInMemcpy % GluedLdStLimit;
9934 unsigned GlueIter = 0;
9935
9936 // Residual ld/st.
9937 if (RemainingLdStInMemcpy) {
9939 DAG, dl, OutChains, NumLdStInMemcpy - RemainingLdStInMemcpy,
9940 NumLdStInMemcpy, OutLoadChains, OutStoreChains);
9941 }
9942
9943 for (unsigned cnt = 0; cnt < NumberLdChain; ++cnt) {
9944 unsigned IndexFrom = NumLdStInMemcpy - RemainingLdStInMemcpy -
9945 GlueIter - GluedLdStLimit;
9946 unsigned IndexTo = NumLdStInMemcpy - RemainingLdStInMemcpy - GlueIter;
9947 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, IndexFrom, IndexTo,
9948 OutLoadChains, OutStoreChains);
9949 GlueIter += GluedLdStLimit;
9950 }
9951 }
9952 }
9953 }
9954 return DAG.getTokenFactor(dl, OutChains);
9955}
9956
9958 SelectionDAG &DAG, const SDLoc &dl, SDValue Chain, SDValue Dst, SDValue Src,
9959 uint64_t Size, Align DstAlign, Align SrcAlign, bool isVol,
9960 bool AlwaysInline, MachinePointerInfo DstPtrInfo,
9961 MachinePointerInfo SrcPtrInfo, const AAMDNodes &AAInfo) {
9962 // Turn a memmove of undef to nop.
9963 // FIXME: We need to honor volatile even is Src is undef.
9964 if (Src.isUndef())
9965 return Chain;
9966
9967 // Expand memmove to a series of load and store ops if the size operand falls
9968 // below a certain threshold.
9970 const DataLayout &DL = DAG.getDataLayout();
9971 LLVMContext &C = *DAG.getContext();
9972 std::vector<EVT> MemOps;
9973 bool DstAlignCanChange = false;
9975 MachineFrameInfo &MFI = MF.getFrameInfo();
9976 bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
9978 if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
9979 DstAlignCanChange = true;
9980 SrcAlign = std::max(SrcAlign, DAG.InferPtrAlign(Src).valueOrOne());
9981 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize);
9982 if (!TLI.findOptimalMemOpLowering(
9983 C, MemOps, Limit,
9984 MemOp::Move(Size, DstAlignCanChange, DstAlign, SrcAlign, isVol),
9985 DstPtrInfo.getAddrSpace(), SrcPtrInfo.getAddrSpace(),
9986 MF.getFunction().getAttributes(), nullptr))
9987 return SDValue();
9988
9989 if (DstAlignCanChange) {
9990 Type *Ty = MemOps[0].getTypeForEVT(C);
9991 Align NewDstAlign = DL.getABITypeAlign(Ty);
9992
9993 // Don't promote to an alignment that would require dynamic stack
9994 // realignment which may conflict with optimizations such as tail call
9995 // optimization.
9997 if (!TRI->hasStackRealignment(MF))
9998 if (MaybeAlign StackAlign = DL.getStackAlignment())
9999 NewDstAlign = std::min(NewDstAlign, *StackAlign);
10000
10001 if (NewDstAlign > DstAlign) {
10002 // Give the stack frame object a larger alignment if needed.
10003 if (MFI.getObjectAlign(FI->getIndex()) < NewDstAlign)
10004 MFI.setObjectAlignment(FI->getIndex(), NewDstAlign);
10005 DstAlign = NewDstAlign;
10006 }
10007 }
10008
10009 // Prepare AAInfo for loads/stores after lowering this memmove.
10010 AAMDNodes NewAAInfo = AAInfo;
10011 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
10012
10013 MachineMemOperand::Flags MMOFlags =
10015 uint64_t SrcOff = 0;
10016 SmallVector<SDValue, 8> LoadValues;
10017 SmallVector<SDValue, 8> LoadChains;
10018 SmallVector<SDValue, 8> OutChains;
10019 unsigned NumMemOps = MemOps.size();
10020 for (unsigned i = 0; i < NumMemOps; i++) {
10021 EVT VT = MemOps[i];
10022 unsigned VTSize = VT.getSizeInBits() / 8;
10023 SDValue Value;
10024 bool IsOverlapping = false;
10025
10026 if (i == NumMemOps - 1 && i != 0 && VTSize > Size - SrcOff) {
10027 // Issuing an unaligned load / store pair that overlaps with the previous
10028 // pair. Adjust the offset accordingly.
10029 SrcOff = Size - VTSize;
10030 IsOverlapping = true;
10031 }
10032
10033 // Calculate the actual alignment at the current offset. The alignment at
10034 // SrcOff may be lower than the base alignment, especially when using
10035 // overlapping loads.
10036 Align SrcAlignAtOffset = commonAlignment(SrcAlign, SrcOff);
10037 if (IsOverlapping) {
10038 // Verify that the target allows misaligned memory accesses at the
10039 // adjusted offset when using overlapping loads.
10040 unsigned Fast;
10041 if (!TLI.allowsMisalignedMemoryAccesses(VT, SrcPtrInfo.getAddrSpace(),
10042 SrcAlignAtOffset, MMOFlags,
10043 &Fast) ||
10044 !Fast) {
10045 // This should have been caught by findOptimalMemOpLowering, but verify
10046 // here for safety.
10047 return SDValue();
10048 }
10049 }
10050
10051 bool isDereferenceable =
10052 SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
10053 MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
10054 if (isDereferenceable)
10056 Value =
10057 DAG.getLoad(VT, dl, Chain,
10058 DAG.getObjectPtrOffset(dl, Src, TypeSize::getFixed(SrcOff)),
10059 SrcPtrInfo.getWithOffset(SrcOff), SrcAlignAtOffset,
10060 SrcMMOFlags, NewAAInfo);
10061 LoadValues.push_back(Value);
10062 LoadChains.push_back(Value.getValue(1));
10063 SrcOff += VTSize;
10064 }
10065 Chain = DAG.getTokenFactor(dl, LoadChains);
10066 OutChains.clear();
10067 uint64_t DstOff = 0;
10068 for (unsigned i = 0; i < NumMemOps; i++) {
10069 EVT VT = MemOps[i];
10070 unsigned VTSize = VT.getSizeInBits() / 8;
10071 SDValue Store;
10072 bool IsOverlapping = false;
10073
10074 if (i == NumMemOps - 1 && i != 0 && VTSize > Size - DstOff) {
10075 // Issuing an unaligned load / store pair that overlaps with the previous
10076 // pair. Adjust the offset accordingly.
10077 DstOff = Size - VTSize;
10078 IsOverlapping = true;
10079 }
10080
10081 // Calculate the actual alignment at the current offset. The alignment at
10082 // DstOff may be lower than the base alignment, especially when using
10083 // overlapping stores.
10084 Align DstAlignAtOffset = commonAlignment(DstAlign, DstOff);
10085 if (IsOverlapping) {
10086 // Verify that the target allows misaligned memory accesses at the
10087 // adjusted offset when using overlapping stores.
10088 unsigned Fast;
10089 if (!TLI.allowsMisalignedMemoryAccesses(VT, DstPtrInfo.getAddrSpace(),
10090 DstAlignAtOffset, MMOFlags,
10091 &Fast) ||
10092 !Fast) {
10093 // This should have been caught by findOptimalMemOpLowering, but verify
10094 // here for safety.
10095 return SDValue();
10096 }
10097 }
10098 Store = DAG.getStore(
10099 Chain, dl, LoadValues[i],
10100 DAG.getObjectPtrOffset(dl, Dst, TypeSize::getFixed(DstOff)),
10101 DstPtrInfo.getWithOffset(DstOff), DstAlignAtOffset, MMOFlags,
10102 NewAAInfo);
10103 OutChains.push_back(Store);
10104 DstOff += VTSize;
10105 }
10106
10107 return DAG.getTokenFactor(dl, OutChains);
10108}
10109
10110/// Lower the call to 'memset' intrinsic function into a series of store
10111/// operations.
10112///
10113/// \param DAG Selection DAG where lowered code is placed.
10114/// \param dl Link to corresponding IR location.
10115/// \param Chain Control flow dependency.
10116/// \param Dst Pointer to destination memory location.
10117/// \param Src Value of byte to write into the memory.
10118/// \param Size Number of bytes to write.
10119/// \param Alignment Alignment of the destination in bytes.
10120/// \param isVol True if destination is volatile.
10121/// \param AlwaysInline Makes sure no function call is generated.
10122/// \param DstPtrInfo IR information on the memory pointer.
10123/// \returns New head in the control flow, if lowering was successful, empty
10124/// SDValue otherwise.
10125///
10126/// The function tries to replace 'llvm.memset' intrinsic with several store
10127/// operations and value calculation code. This is usually profitable for small
10128/// memory size or when the semantic requires inlining.
10130 SDValue Chain, SDValue Dst, SDValue Src,
10131 uint64_t Size, Align Alignment, bool isVol,
10132 bool AlwaysInline, MachinePointerInfo DstPtrInfo,
10133 const AAMDNodes &AAInfo) {
10134 // Turn a memset of undef to nop.
10135 // FIXME: We need to honor volatile even is Src is undef.
10136 if (Src.isUndef())
10137 return Chain;
10138
10139 // Expand memset to a series of load/store ops if the size operand
10140 // falls below a certain threshold.
10142 std::vector<EVT> MemOps;
10143 bool DstAlignCanChange = false;
10144 LLVMContext &C = *DAG.getContext();
10146 MachineFrameInfo &MFI = MF.getFrameInfo();
10147 bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
10149 if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
10150 DstAlignCanChange = true;
10151 bool IsZeroVal = isNullConstant(Src);
10152 unsigned Limit = AlwaysInline ? ~0 : TLI.getMaxStoresPerMemset(OptSize);
10153
10154 EVT LargestVT;
10155 if (!TLI.findOptimalMemOpLowering(
10156 C, MemOps, Limit,
10157 MemOp::Set(Size, DstAlignCanChange, Alignment, IsZeroVal, isVol),
10158 DstPtrInfo.getAddrSpace(), ~0u, MF.getFunction().getAttributes(),
10159 &LargestVT))
10160 return SDValue();
10161
10162 if (DstAlignCanChange) {
10163 Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
10164 const DataLayout &DL = DAG.getDataLayout();
10165 Align NewAlign = DL.getABITypeAlign(Ty);
10166
10167 // Don't promote to an alignment that would require dynamic stack
10168 // realignment which may conflict with optimizations such as tail call
10169 // optimization.
10171 if (!TRI->hasStackRealignment(MF))
10172 if (MaybeAlign StackAlign = DL.getStackAlignment())
10173 NewAlign = std::min(NewAlign, *StackAlign);
10174
10175 if (NewAlign > Alignment) {
10176 // Give the stack frame object a larger alignment if needed.
10177 if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
10178 MFI.setObjectAlignment(FI->getIndex(), NewAlign);
10179 Alignment = NewAlign;
10180 }
10181 }
10182
10183 SmallVector<SDValue, 8> OutChains;
10184 uint64_t DstOff = 0;
10185 unsigned NumMemOps = MemOps.size();
10186
10187 // Find the largest store and generate the bit pattern for it.
10188 // If target didn't set LargestVT, compute it from MemOps.
10189 if (!LargestVT.isSimple()) {
10190 LargestVT = MemOps[0];
10191 for (unsigned i = 1; i < NumMemOps; i++)
10192 if (MemOps[i].bitsGT(LargestVT))
10193 LargestVT = MemOps[i];
10194 }
10195 SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl);
10196
10197 // Prepare AAInfo for loads/stores after lowering this memset.
10198 AAMDNodes NewAAInfo = AAInfo;
10199 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
10200
10201 for (unsigned i = 0; i < NumMemOps; i++) {
10202 EVT VT = MemOps[i];
10203 unsigned VTSize = VT.getSizeInBits() / 8;
10204 // The target should specify store types that exactly cover the memset size
10205 // (with the last store potentially being oversized for overlapping stores).
10206 assert(Size > 0 && "Target specified more stores than needed in "
10207 "findOptimalMemOpLowering");
10208 if (VTSize > Size) {
10209 // Issuing an unaligned load / store pair that overlaps with the previous
10210 // pair. Adjust the offset accordingly.
10211 assert(i == NumMemOps-1 && i != 0);
10212 DstOff -= VTSize - Size;
10213 }
10214
10215 // If this store is smaller than the largest store see whether we can get
10216 // the smaller value for free with a truncate or extract vector element and
10217 // then store.
10218 SDValue Value = MemSetValue;
10219 if (VT.bitsLT(LargestVT)) {
10220 unsigned Index;
10221 unsigned NElts = LargestVT.getSizeInBits() / VT.getSizeInBits();
10222 EVT SVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), NElts);
10223 if (!LargestVT.isVector() && !VT.isVector() &&
10224 TLI.isTruncateFree(LargestVT, VT))
10225 Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue);
10226 else if (LargestVT.isVector() && !VT.isVector() &&
10227 TLI.shallExtractConstSplatVectorElementToStore(
10228 LargestVT.getTypeForEVT(*DAG.getContext()),
10229 VT.getSizeInBits(), Index) &&
10230 TLI.isTypeLegal(SVT) &&
10231 LargestVT.getSizeInBits() == SVT.getSizeInBits()) {
10232 // Target which can combine store(extractelement VectorTy, Idx) can get
10233 // the smaller value for free.
10234 SDValue TailValue = DAG.getNode(ISD::BITCAST, dl, SVT, MemSetValue);
10235 Value = DAG.getExtractVectorElt(dl, VT, TailValue, Index);
10236 } else
10237 Value = getMemsetValue(Src, VT, DAG, dl);
10238 }
10239 assert(Value.getValueType() == VT && "Value with wrong type.");
10240 SDValue Store = DAG.getStore(
10241 Chain, dl, Value,
10242 DAG.getObjectPtrOffset(dl, Dst, TypeSize::getFixed(DstOff)),
10243 DstPtrInfo.getWithOffset(DstOff), Alignment,
10245 NewAAInfo);
10246 OutChains.push_back(Store);
10247 DstOff += VT.getSizeInBits() / 8;
10248 // For oversized overlapping stores, only subtract the remaining bytes.
10249 // For normal stores, subtract the full store size.
10250 if (VTSize > Size) {
10251 Size = 0;
10252 } else {
10253 Size -= VTSize;
10254 }
10255 }
10256
10257 // After processing all stores, Size should be exactly 0. Any remaining bytes
10258 // indicate a bug in the target's findOptimalMemOpLowering implementation.
10259 assert(Size == 0 && "Target's findOptimalMemOpLowering did not specify "
10260 "stores that exactly cover the memset size");
10261
10262 return DAG.getTokenFactor(dl, OutChains);
10263}
10264
10266 const DataLayout &DL, unsigned AS) {
10267 // Lowering memcpy / memset / memmove intrinsics to calls is only valid if all
10268 // pointer operands can be losslessly bitcasted to pointers of address space 0
10269 if (AS != 0 && !TLI->getTargetMachine().isNoopAddrSpaceCast(DL, AS, 0)) {
10270 report_fatal_error("cannot lower memory intrinsic in address space " +
10271 Twine(AS));
10272 }
10273}
10274
10275/// The length of a memory intrinsic (e.g. number of bytes to copy) is unsigned
10276/// and may have any integer type. We zero-extend or truncate it to the pointer
10277/// type of the narrower address space being accessed.
10279 SDValue Size, unsigned DstAS,
10280 unsigned SrcAS) {
10282 MVT DstVT = TLI.getPointerTy(DAG.getDataLayout(), DstAS);
10283 MVT SrcVT = TLI.getPointerTy(DAG.getDataLayout(), SrcAS);
10284 return DAG.getZExtOrTrunc(Size, dl, DstVT.bitsLT(SrcVT) ? DstVT : SrcVT);
10285}
10286
10288 const SelectionDAG *SelDAG,
10289 bool AllowReturnsFirstArg) {
10290 if (!CI || !CI->isTailCall())
10291 return false;
10292 // TODO: Fix "returns-first-arg" determination so it doesn't depend on which
10293 // helper symbol we lower to.
10294 return isInTailCallPosition(*CI, SelDAG->getTarget(),
10295 AllowReturnsFirstArg &&
10297}
10298
10299static std::pair<SDValue, SDValue>
10302 const CallInst *CI, RTLIB::Libcall Call,
10303 SelectionDAG *DAG, const TargetLowering *TLI) {
10304 RTLIB::LibcallImpl LCImpl = DAG->getLibcalls().getLibcallImpl(Call);
10305
10306 if (LCImpl == RTLIB::Unsupported)
10307 return {};
10308
10310 bool IsTailCall =
10311 isInTailCallPositionWrapper(CI, DAG, /*AllowReturnsFirstArg=*/true) &&
10312 // Lowering doesn't support tail calling inside a function with
10313 // a swifterror argument yet.
10314 !DAG->hasSwiftErrorArg();
10315 SDValue Callee =
10316 DAG->getExternalSymbol(LCImpl, TLI->getPointerTy(DAG->getDataLayout()));
10317
10318 CLI.setDebugLoc(dl)
10319 .setChain(Chain)
10321 CI->getType(), Callee, std::move(Args))
10322 .setTailCall(IsTailCall);
10323
10324 return TLI->LowerCallTo(CLI);
10325}
10326
10327std::pair<SDValue, SDValue> SelectionDAG::getStrcmp(SDValue Chain,
10328 const SDLoc &dl, SDValue S1,
10329 SDValue S2,
10330 const CallInst *CI) {
10332 TargetLowering::ArgListTy Args = {{S1, PT}, {S2, PT}};
10333 return getRuntimeCallSDValueHelper(Chain, dl, std::move(Args), CI,
10334 RTLIB::STRCMP, this, TLI);
10335}
10336
10337std::pair<SDValue, SDValue> SelectionDAG::getStrstr(SDValue Chain,
10338 const SDLoc &dl, SDValue S1,
10339 SDValue S2,
10340 const CallInst *CI) {
10342 TargetLowering::ArgListTy Args = {{S1, PT}, {S2, PT}};
10343 return getRuntimeCallSDValueHelper(Chain, dl, std::move(Args), CI,
10344 RTLIB::STRSTR, this, TLI);
10345}
10346
10347std::pair<SDValue, SDValue> SelectionDAG::getMemccpy(SDValue Chain,
10348 const SDLoc &dl,
10349 SDValue Dst, SDValue Src,
10351 const CallInst *CI) {
10353
10355 {Dst, PT},
10356 {Src, PT},
10359 return getRuntimeCallSDValueHelper(Chain, dl, std::move(Args), CI,
10360 RTLIB::MEMCCPY, this, TLI);
10361}
10362
10363std::pair<SDValue, SDValue>
10365 SDValue Mem1, SDValue Size, const CallInst *CI) {
10368 {Mem0, PT},
10369 {Mem1, PT},
10371 return getRuntimeCallSDValueHelper(Chain, dl, std::move(Args), CI,
10372 RTLIB::MEMCMP, this, TLI);
10373}
10374
10375std::pair<SDValue, SDValue> SelectionDAG::getStrcpy(SDValue Chain,
10376 const SDLoc &dl,
10377 SDValue Dst, SDValue Src,
10378 const CallInst *CI) {
10380 TargetLowering::ArgListTy Args = {{Dst, PT}, {Src, PT}};
10381 return getRuntimeCallSDValueHelper(Chain, dl, std::move(Args), CI,
10382 RTLIB::STRCPY, this, TLI);
10383}
10384
10385std::pair<SDValue, SDValue> SelectionDAG::getStrlen(SDValue Chain,
10386 const SDLoc &dl,
10387 SDValue Src,
10388 const CallInst *CI) {
10389 // Emit a library call.
10392 return getRuntimeCallSDValueHelper(Chain, dl, std::move(Args), CI,
10393 RTLIB::STRLEN, this, TLI);
10394}
10395
10397 return TLI->supportSwiftError() &&
10398 MF->getFunction().getAttributes().hasAttrSomewhere(
10399 Attribute::SwiftError);
10400}
10401
10403 SDValue Chain, const SDLoc &dl, SDValue Dst, SDValue Src, SDValue Size,
10404 Align DstAlign, Align SrcAlign, bool isVol, bool AlwaysInline,
10405 const CallInst *CI, std::optional<bool> OverrideTailCall,
10406 MachinePointerInfo DstPtrInfo, MachinePointerInfo SrcPtrInfo,
10407 const AAMDNodes &AAInfo, BatchAAResults *BatchAA) {
10408 Size = getMemIntrinsicSize(*this, dl, Size, DstPtrInfo.getAddrSpace(),
10409 SrcPtrInfo.getAddrSpace());
10410 // Check to see if we should lower the memcpy to loads and stores first.
10411 // For cases within the target-specified limits, this is the best choice.
10412 const MDNode *DstMemCacheHint =
10413 CI ? getMemCacheHint(*CI, /*OperandNo=*/0) : nullptr;
10414 const MDNode *SrcMemCacheHint =
10415 CI ? getMemCacheHint(*CI, /*OperandNo=*/1) : nullptr;
10416
10418 if (ConstantSize) {
10419 // Memcpy with size zero? Just return the original chain.
10420 if (ConstantSize->isZero())
10421 return Chain;
10422
10424 *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), DstAlign,
10425 SrcAlign, isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo, BatchAA,
10426 DstMemCacheHint, SrcMemCacheHint);
10427 if (Result.getNode())
10428 return Result;
10429 }
10430
10431 // Then check to see if we should lower the memcpy with target-specific
10432 // code. If the target chooses to do this, this is the next best.
10433 if (TSI) {
10434 bool IsTailCall = OverrideTailCall.value_or(isInTailCallPositionWrapper(
10435 CI, this, /*AllowReturnsFirstArg=*/false)) &&
10437 [[maybe_unused]] SDValue OldRoot = getRoot();
10438 SDValue Result = TSI->EmitTargetCodeForMemcpy(
10439 *this, dl, Chain, Dst, Src, Size, DstAlign, SrcAlign, isVol,
10440 AlwaysInline, IsTailCall, DstPtrInfo, SrcPtrInfo);
10441 assert((Result.getNode() || !IsTailCall || getRoot() != OldRoot) &&
10442 "target declined without clearing IsTailCall");
10443 if (Result.getNode() || IsTailCall)
10444 return Result;
10445 }
10446
10447 // If we really need inline code and the target declined to provide it,
10448 // use a (potentially long) sequence of loads and stores.
10449 if (AlwaysInline) {
10450 assert(ConstantSize && "AlwaysInline requires a constant size!");
10452 *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), DstAlign,
10453 SrcAlign, isVol, true, DstPtrInfo, SrcPtrInfo, AAInfo, BatchAA,
10454 DstMemCacheHint, SrcMemCacheHint);
10455 }
10456
10458 DstPtrInfo.getAddrSpace());
10460 SrcPtrInfo.getAddrSpace());
10461
10462 // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc
10463 // memcpy is not guaranteed to be safe. libc memcpys aren't required to
10464 // respect volatile, so they may do things like read or write memory
10465 // beyond the given memory regions. But fixing this isn't easy, and most
10466 // people don't care.
10467
10468 // Emit a library call.
10471 Args.emplace_back(Dst, PtrTy);
10472 Args.emplace_back(Src, PtrTy);
10473 Args.emplace_back(Size, getDataLayout().getIntPtrType(*getContext()));
10474 // FIXME: pass in SDLoc
10476 bool IsTailCall = false;
10477 RTLIB::LibcallImpl MemCpyImpl = Libcalls->getMemcpyImpl();
10478
10479 if (OverrideTailCall.has_value()) {
10480 IsTailCall = *OverrideTailCall;
10481 } else {
10482 bool LowersToMemcpy = MemCpyImpl == RTLIB::impl_memcpy;
10483 IsTailCall = isInTailCallPositionWrapper(CI, this, LowersToMemcpy);
10484 }
10485 // Lowering doesn't support tail calling inside a function with a
10486 // swifterror argument yet.
10487 IsTailCall &= !hasSwiftErrorArg();
10488
10489 CLI.setDebugLoc(dl)
10490 .setChain(Chain)
10491 .setLibCallee(
10492 Libcalls->getLibcallImplCallingConv(MemCpyImpl),
10493 Dst.getValueType().getTypeForEVT(*getContext()),
10494 getExternalSymbol(MemCpyImpl, TLI->getPointerTy(getDataLayout())),
10495 std::move(Args))
10497 .setTailCall(IsTailCall);
10498
10499 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
10500 return CallResult.second;
10501}
10502
10505 const Module &M = *DAG->getMachineFunction().getFunction().getParent();
10506 Type *SizeTTy = DAG->getLibInfo().getSizeTType(M);
10508 DAG->getZExtOrTrunc(Size, dl, MVT::getVT(SizeTTy)), SizeTTy);
10509}
10510
10512 SDValue Dst, SDValue Src, SDValue Size,
10513 Type *SizeTy, unsigned ElemSz,
10514 bool isTailCall,
10515 MachinePointerInfo DstPtrInfo,
10516 MachinePointerInfo SrcPtrInfo) {
10517 // Lowering doesn't support tail calling inside a function with a
10518 // swifterror argument yet.
10519 isTailCall &= !hasSwiftErrorArg();
10520
10521 // Emit a library call.
10524 Args.emplace_back(Dst, ArgTy);
10525 Args.emplace_back(Src, ArgTy);
10526 Args.emplace_back(getAtomicMemOpSizeArg(this, dl, Size));
10527
10528 RTLIB::Libcall LibraryCall =
10530 RTLIB::LibcallImpl LibcallImpl = Libcalls->getLibcallImpl(LibraryCall);
10531 if (LibcallImpl == RTLIB::Unsupported)
10532 report_fatal_error("Unsupported element size");
10533
10535 CLI.setDebugLoc(dl)
10536 .setChain(Chain)
10537 .setLibCallee(
10538 Libcalls->getLibcallImplCallingConv(LibcallImpl),
10540 getExternalSymbol(LibcallImpl, TLI->getPointerTy(getDataLayout())),
10541 std::move(Args))
10543 .setTailCall(isTailCall);
10544
10545 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
10546 return CallResult.second;
10547}
10548
10550 SDValue Src, SDValue Size, Align DstAlign,
10551 Align SrcAlign, bool isVol, const CallInst *CI,
10552 std::optional<bool> OverrideTailCall,
10553 MachinePointerInfo DstPtrInfo,
10554 MachinePointerInfo SrcPtrInfo,
10555 const AAMDNodes &AAInfo,
10556 BatchAAResults *BatchAA) {
10557 Size = getMemIntrinsicSize(*this, dl, Size, DstPtrInfo.getAddrSpace(),
10558 SrcPtrInfo.getAddrSpace());
10559 // Check to see if we should lower the memmove to loads and stores first.
10560 // For cases within the target-specified limits, this is the best choice.
10562 if (ConstantSize) {
10563 // Memmove with size zero? Just return the original chain.
10564 if (ConstantSize->isZero())
10565 return Chain;
10566
10568 *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), DstAlign,
10569 SrcAlign, isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo);
10570 if (Result.getNode())
10571 return Result;
10572 }
10573
10574 // Then check to see if we should lower the memmove with target-specific
10575 // code. If the target chooses to do this, this is the next best.
10576 if (TSI) {
10577 bool IsTailCall = OverrideTailCall.value_or(isInTailCallPositionWrapper(
10578 CI, this, /*AllowReturnsFirstArg=*/false)) &&
10580 [[maybe_unused]] SDValue OldRoot = getRoot();
10581 SDValue Result = TSI->EmitTargetCodeForMemmove(
10582 *this, dl, Chain, Dst, Src, Size, DstAlign, SrcAlign, isVol, IsTailCall,
10583 DstPtrInfo, SrcPtrInfo);
10584 assert((Result.getNode() || !IsTailCall || getRoot() != OldRoot) &&
10585 "target declined without clearing IsTailCall");
10586 if (Result.getNode() || IsTailCall)
10587 return Result;
10588 }
10589
10591 DstPtrInfo.getAddrSpace());
10593 SrcPtrInfo.getAddrSpace());
10594
10595 // FIXME: If the memmove is volatile, lowering it to plain libc memmove may
10596 // not be safe. See memcpy above for more details.
10597
10598 // Emit a library call.
10601 Args.emplace_back(Dst, PtrTy);
10602 Args.emplace_back(Src, PtrTy);
10603 Args.emplace_back(Size, getDataLayout().getIntPtrType(*getContext()));
10604 // FIXME: pass in SDLoc
10606
10607 RTLIB::LibcallImpl MemmoveImpl = Libcalls->getLibcallImpl(RTLIB::MEMMOVE);
10608
10609 bool IsTailCall = false;
10610 if (OverrideTailCall.has_value()) {
10611 IsTailCall = *OverrideTailCall;
10612 } else {
10613 bool LowersToMemmove = MemmoveImpl == RTLIB::impl_memmove;
10614 IsTailCall = isInTailCallPositionWrapper(CI, this, LowersToMemmove);
10615 }
10616 // Lowering doesn't support tail calling inside a function with a
10617 // swifterror argument yet.
10618 IsTailCall &= !hasSwiftErrorArg();
10619
10620 CLI.setDebugLoc(dl)
10621 .setChain(Chain)
10622 .setLibCallee(
10623 Libcalls->getLibcallImplCallingConv(MemmoveImpl),
10624 Dst.getValueType().getTypeForEVT(*getContext()),
10625 getExternalSymbol(MemmoveImpl, TLI->getPointerTy(getDataLayout())),
10626 std::move(Args))
10628 .setTailCall(IsTailCall);
10629
10630 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
10631 return CallResult.second;
10632}
10633
10635 SDValue Dst, SDValue Src, SDValue Size,
10636 Type *SizeTy, unsigned ElemSz,
10637 bool isTailCall,
10638 MachinePointerInfo DstPtrInfo,
10639 MachinePointerInfo SrcPtrInfo) {
10640 // Lowering doesn't support tail calling inside a function with a
10641 // swifterror argument yet.
10642 isTailCall &= !hasSwiftErrorArg();
10643
10644 // Emit a library call.
10647 Args.emplace_back(Dst, IntPtrTy);
10648 Args.emplace_back(Src, IntPtrTy);
10649 Args.emplace_back(getAtomicMemOpSizeArg(this, dl, Size));
10650
10651 RTLIB::Libcall LibraryCall =
10653 RTLIB::LibcallImpl LibcallImpl = Libcalls->getLibcallImpl(LibraryCall);
10654 if (LibcallImpl == RTLIB::Unsupported)
10655 report_fatal_error("Unsupported element size");
10656
10658 CLI.setDebugLoc(dl)
10659 .setChain(Chain)
10660 .setLibCallee(
10661 Libcalls->getLibcallImplCallingConv(LibcallImpl),
10663 getExternalSymbol(LibcallImpl, TLI->getPointerTy(getDataLayout())),
10664 std::move(Args))
10666 .setTailCall(isTailCall);
10667
10668 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
10669 return CallResult.second;
10670}
10671
10673 SDValue Src, SDValue Size, Align Alignment,
10674 bool isVol, bool AlwaysInline,
10675 const CallInst *CI,
10676 MachinePointerInfo DstPtrInfo,
10677 const AAMDNodes &AAInfo) {
10678 Size = getMemIntrinsicSize(*this, dl, Size, DstPtrInfo.getAddrSpace(),
10679 DstPtrInfo.getAddrSpace());
10680 // Check to see if we should lower the memset to stores first.
10681 // For cases within the target-specified limits, this is the best choice.
10683 if (ConstantSize) {
10684 // Memset with size zero? Just return the original chain.
10685 if (ConstantSize->isZero())
10686 return Chain;
10687
10688 SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src,
10689 ConstantSize->getZExtValue(), Alignment,
10690 isVol, false, DstPtrInfo, AAInfo);
10691
10692 if (Result.getNode())
10693 return Result;
10694 }
10695
10696 // Then check to see if we should lower the memset with target-specific
10697 // code. If the target chooses to do this, this is the next best.
10698 if (TSI) {
10699 bool IsTailCall =
10700 isInTailCallPositionWrapper(CI, this, /*AllowReturnsFirstArg=*/false) &&
10702 [[maybe_unused]] SDValue OldRoot = getRoot();
10703 SDValue Result = TSI->EmitTargetCodeForMemset(
10704 *this, dl, Chain, Dst, Src, Size, Alignment, isVol, AlwaysInline,
10705 IsTailCall, DstPtrInfo);
10706 assert((Result.getNode() || !IsTailCall || getRoot() != OldRoot) &&
10707 "target declined without clearing IsTailCall");
10708 if (Result.getNode() || IsTailCall)
10709 return Result;
10710 }
10711
10712 // If we really need inline code and the target declined to provide it,
10713 // use a (potentially long) sequence of loads and stores.
10714 if (AlwaysInline) {
10715 assert(ConstantSize && "AlwaysInline requires a constant size!");
10716 SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src,
10717 ConstantSize->getZExtValue(), Alignment,
10718 isVol, true, DstPtrInfo, AAInfo);
10719 assert(Result &&
10720 "getMemsetStores must return a valid sequence when AlwaysInline");
10721 return Result;
10722 }
10723
10725 DstPtrInfo.getAddrSpace());
10726
10727 // Emit a library call.
10728 auto &Ctx = *getContext();
10729 const auto& DL = getDataLayout();
10730
10732 // FIXME: pass in SDLoc
10733 CLI.setDebugLoc(dl).setChain(Chain);
10734
10735 RTLIB::LibcallImpl BzeroImpl = Libcalls->getLibcallImpl(RTLIB::BZERO);
10736 bool UseBZero = BzeroImpl != RTLIB::Unsupported && isNullConstant(Src);
10737
10738 // If zeroing out and bzero is present, use it.
10739 if (UseBZero) {
10741 Args.emplace_back(Dst, PointerType::getUnqual(Ctx));
10742 Args.emplace_back(Size, DL.getIntPtrType(Ctx));
10743 CLI.setLibCallee(
10744 Libcalls->getLibcallImplCallingConv(BzeroImpl), Type::getVoidTy(Ctx),
10745 getExternalSymbol(BzeroImpl, TLI->getPointerTy(DL)), std::move(Args));
10746 } else {
10747 RTLIB::LibcallImpl MemsetImpl = Libcalls->getLibcallImpl(RTLIB::MEMSET);
10748
10749 MVT IntVT = MVT::getIntegerVT(LibInfo->getIntSize());
10751 Args.emplace_back(Dst, PointerType::getUnqual(Ctx));
10752 Args.emplace_back(getAnyExtOrTrunc(Src, dl, IntVT),
10753 Type::getIntNTy(Ctx, LibInfo->getIntSize()),
10754 LibInfo->getExtAttrForI32Param());
10755 Args.emplace_back(Size, DL.getIntPtrType(Ctx));
10756
10757 CLI.setLibCallee(Libcalls->getLibcallImplCallingConv(MemsetImpl),
10758 Dst.getValueType().getTypeForEVT(Ctx),
10759 getExternalSymbol(MemsetImpl, TLI->getPointerTy(DL)),
10760 std::move(Args));
10761 }
10762
10763 RTLIB::LibcallImpl MemsetImpl = Libcalls->getLibcallImpl(RTLIB::MEMSET);
10764 bool LowersToMemset = MemsetImpl == RTLIB::impl_memset;
10765
10766 // If we're going to use bzero, make sure not to tail call unless the
10767 // subsequent return doesn't need a value, as bzero doesn't return the first
10768 // arg unlike memset.
10769 bool ReturnsFirstArg = CI && funcReturnsFirstArgOfCall(*CI) && !UseBZero;
10770 bool IsTailCall = CI && CI->isTailCall() &&
10772 ReturnsFirstArg && LowersToMemset) &&
10773 // Lowering doesn't support tail calling inside a function
10774 // with a swifterror argument yet.
10776 CLI.setDiscardResult().setTailCall(IsTailCall);
10777
10778 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
10779 return CallResult.second;
10780}
10781
10784 Type *SizeTy, unsigned ElemSz,
10785 bool isTailCall,
10786 MachinePointerInfo DstPtrInfo) {
10787 // Lowering doesn't support tail calling inside a function with a
10788 // swifterror argument yet.
10789 isTailCall &= !hasSwiftErrorArg();
10790
10791 // Emit a library call.
10792 MVT IntVT = MVT::getIntegerVT(LibInfo->getIntSize());
10794 Args.emplace_back(Dst, getDataLayout().getIntPtrType(*getContext()));
10795 Args.emplace_back(getAnyExtOrTrunc(Value, dl, IntVT),
10796 Type::getIntNTy(*getContext(), LibInfo->getIntSize()),
10797 LibInfo->getExtAttrForI32Param());
10798 Args.emplace_back(getAtomicMemOpSizeArg(this, dl, Size));
10799
10800 RTLIB::Libcall LibraryCall =
10802 RTLIB::LibcallImpl LibcallImpl = Libcalls->getLibcallImpl(LibraryCall);
10803 if (LibcallImpl == RTLIB::Unsupported)
10804 report_fatal_error("Unsupported element size");
10805
10807 CLI.setDebugLoc(dl)
10808 .setChain(Chain)
10809 .setLibCallee(
10810 Libcalls->getLibcallImplCallingConv(LibcallImpl),
10812 getExternalSymbol(LibcallImpl, TLI->getPointerTy(getDataLayout())),
10813 std::move(Args))
10815 .setTailCall(isTailCall);
10816
10817 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
10818 return CallResult.second;
10819}
10820
10821SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
10823 MachineMemOperand *MMO,
10824 ISD::LoadExtType ExtType) {
10825 SDNodeKey ID(Opcode, VTList, Ops);
10826 ID.AddInteger(MemVT.getRawBits());
10827 ID.AddInteger(getSyntheticNodeSubclassData<AtomicSDNode>(
10828 dl.getIROrder(), Opcode, VTList, MemVT, MMO, ExtType));
10829 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
10830 ID.AddInteger(MMO->getFlags());
10831 FoldingSetInsertToken InsertToken;
10832 if (auto *E = cast_or_null<AtomicSDNode>(lookupNode(ID, dl, InsertToken))) {
10833 E->refineAlignment(MMO);
10834 E->refineMMOMetadata(MMO);
10835 return SDValue(E, 0);
10836 }
10837
10838 auto *N = newSDNode<AtomicSDNode>(dl.getIROrder(), dl.getDebugLoc(), Opcode,
10839 VTList, MemVT, MMO, ExtType);
10840 createOperands(N, Ops);
10841
10842 CSEMap.insert(N, InsertToken);
10843 InsertNode(N);
10844 SDValue V(N, 0);
10845 NewSDValueDbgMsg(V, "Creating new node: ", this);
10846 return V;
10847}
10848
10850 EVT MemVT, SDVTList VTs, SDValue Chain,
10851 SDValue Ptr, SDValue Cmp, SDValue Swp,
10852 MachineMemOperand *MMO) {
10853 assert(Opcode == ISD::ATOMIC_CMP_SWAP ||
10855 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
10856
10857 SDValue Ops[] = {Chain, Ptr, Cmp, Swp};
10858 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
10859}
10860
10861SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
10862 SDValue Chain, SDValue Ptr, SDValue Val,
10863 MachineMemOperand *MMO) {
10864 assert((Opcode == ISD::ATOMIC_LOAD_ADD || Opcode == ISD::ATOMIC_LOAD_SUB ||
10865 Opcode == ISD::ATOMIC_LOAD_AND || Opcode == ISD::ATOMIC_LOAD_CLR ||
10866 Opcode == ISD::ATOMIC_LOAD_OR || Opcode == ISD::ATOMIC_LOAD_XOR ||
10867 Opcode == ISD::ATOMIC_LOAD_NAND || Opcode == ISD::ATOMIC_LOAD_MIN ||
10868 Opcode == ISD::ATOMIC_LOAD_MAX || Opcode == ISD::ATOMIC_LOAD_UMIN ||
10869 Opcode == ISD::ATOMIC_LOAD_UMAX || Opcode == ISD::ATOMIC_LOAD_FADD ||
10870 Opcode == ISD::ATOMIC_LOAD_FSUB || Opcode == ISD::ATOMIC_LOAD_FMAX ||
10871 Opcode == ISD::ATOMIC_LOAD_FMIN ||
10872 Opcode == ISD::ATOMIC_LOAD_FMINIMUM ||
10873 Opcode == ISD::ATOMIC_LOAD_FMAXIMUM ||
10874 Opcode == ISD::ATOMIC_LOAD_FMINIMUMNUM ||
10875 Opcode == ISD::ATOMIC_LOAD_FMAXIMUMNUM ||
10876 Opcode == ISD::ATOMIC_LOAD_UINC_WRAP ||
10877 Opcode == ISD::ATOMIC_LOAD_UDEC_WRAP ||
10878 Opcode == ISD::ATOMIC_LOAD_USUB_COND ||
10879 Opcode == ISD::ATOMIC_LOAD_USUB_SAT || Opcode == ISD::ATOMIC_SWAP ||
10880 Opcode == ISD::ATOMIC_STORE) &&
10881 "Invalid Atomic Op");
10882
10883 EVT VT = Val.getValueType();
10884
10885 SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) :
10886 getVTList(VT, MVT::Other);
10887 SDValue Ops[] = {Chain, Ptr, Val};
10888 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
10889}
10890
10892 EVT MemVT, EVT VT, SDValue Chain,
10893 SDValue Ptr, MachineMemOperand *MMO) {
10894 SDVTList VTs = getVTList(VT, MVT::Other);
10895 SDValue Ops[] = {Chain, Ptr};
10896 return getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, VTs, Ops, MMO, ExtType);
10897}
10898
10899/// getMergeValues - Create a MERGE_VALUES node from the given operands.
10901 if (Ops.size() == 1)
10902 return Ops[0];
10903
10905 VTs.reserve(Ops.size());
10906 for (const SDValue &Op : Ops)
10907 VTs.push_back(Op.getValueType());
10908 return getNode(ISD::MERGE_VALUES, dl, getVTList(VTs), Ops);
10909}
10910
10912 SDValue Chain, const SDLoc &dl) {
10913 SmallVector<SDValue, 4> RetValues;
10914 RetValues.reserve(ResultTypes.size());
10915 for (EVT VT : ResultTypes)
10916 RetValues.push_back(VT == MVT::Other ? Chain : getPOISON(VT));
10917 return getMergeValues(RetValues, dl);
10918}
10919
10921 unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef<SDValue> Ops,
10922 EVT MemVT, MachinePointerInfo PtrInfo, Align Alignment,
10924 const AAMDNodes &AAInfo) {
10925 if (Size.hasValue() && !Size.getValue())
10927
10929 MachineMemOperand *MMO =
10930 MF.getMachineMemOperand(PtrInfo, Flags, Size, Alignment, AAInfo);
10931
10932 return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, MMO);
10933}
10934
10936 SDVTList VTList,
10937 ArrayRef<SDValue> Ops, EVT MemVT,
10938 MachineMemOperand *MMO) {
10939 return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, ArrayRef(MMO));
10940}
10941
10943 SDVTList VTList,
10944 ArrayRef<SDValue> Ops, EVT MemVT,
10946 assert(!MMOs.empty() && "Must have at least one MMO");
10947 assert(
10948 (Opcode == ISD::INTRINSIC_VOID || Opcode == ISD::INTRINSIC_W_CHAIN ||
10949 Opcode == ISD::PREFETCH ||
10950 (Opcode <= (unsigned)std::numeric_limits<int>::max() &&
10951 Opcode >= ISD::BUILTIN_OP_END && TSI->isTargetMemoryOpcode(Opcode))) &&
10952 "Opcode is not a memory-accessing opcode!");
10953
10955 if (MMOs.size() == 1) {
10956 MemRefs = MMOs[0];
10957 } else {
10958 // Allocate: [size_t count][MMO*][MMO*]...
10959 size_t AllocSize =
10960 sizeof(size_t) + MMOs.size() * sizeof(MachineMemOperand *);
10961 void *Buffer = Allocator.Allocate(AllocSize, alignof(size_t));
10962 size_t *CountPtr = static_cast<size_t *>(Buffer);
10963 *CountPtr = MMOs.size();
10964 MachineMemOperand **Array =
10965 reinterpret_cast<MachineMemOperand **>(CountPtr + 1);
10966 llvm::copy(MMOs, Array);
10967 MemRefs = Array;
10968 }
10969
10970 // Memoize the node unless it returns a glue result.
10972 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
10973 SDNodeKey ID(Opcode, VTList, Ops);
10974 ID.AddInteger(getSyntheticNodeSubclassData<MemIntrinsicSDNode>(
10975 Opcode, dl.getIROrder(), VTList, MemVT, MemRefs));
10976 ID.AddInteger(MemVT.getRawBits());
10977 for (const MachineMemOperand *MMO : MMOs) {
10978 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
10979 ID.AddInteger(MMO->getFlags());
10980 }
10981 FoldingSetInsertToken InsertToken;
10982 if (SDNode *E = lookupNode(ID, dl, InsertToken)) {
10983 cast<MemIntrinsicSDNode>(E)->refineAlignment(MMOs);
10984 return SDValue(E, 0);
10985 }
10986
10987 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
10988 VTList, MemVT, MemRefs);
10989 createOperands(N, Ops);
10990 CSEMap.insert(N, InsertToken);
10991 } else {
10992 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
10993 VTList, MemVT, MemRefs);
10994 createOperands(N, Ops);
10995 }
10996 InsertNode(N);
10997 SDValue V(N, 0);
10998 NewSDValueDbgMsg(V, "Creating new node: ", this);
10999 return V;
11000}
11001
11003 SDValue Chain, int FrameIndex) {
11004 const unsigned Opcode = IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END;
11005 const auto VTs = getVTList(MVT::Other);
11006 SDValue Ops[2] = {
11007 Chain,
11008 getFrameIndex(FrameIndex,
11009 getTargetLoweringInfo().getFrameIndexTy(getDataLayout()),
11010 true)};
11011
11012 SDNodeKey ID(Opcode, VTs, Ops);
11013 FoldingSetInsertToken InsertToken;
11014 if (SDNode *E = lookupNode(ID, dl, InsertToken))
11015 return SDValue(E, 0);
11016
11017 LifetimeSDNode *N =
11018 newSDNode<LifetimeSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), VTs);
11019 createOperands(N, Ops);
11020 CSEMap.insert(N, InsertToken);
11021 InsertNode(N);
11022 SDValue V(N, 0);
11023 NewSDValueDbgMsg(V, "Creating new node: ", this);
11024 return V;
11025}
11026
11028 uint64_t Guid, uint64_t Index,
11029 uint32_t Attr) {
11030 const unsigned Opcode = ISD::PSEUDO_PROBE;
11031 const auto VTs = getVTList(MVT::Other);
11032 SDValue Ops[] = {Chain};
11033 SDNodeKey ID(Opcode, VTs, Ops);
11034 ID.AddInteger(Guid);
11035 ID.AddInteger(Index);
11036 ID.AddInteger(Attr);
11037 FoldingSetInsertToken InsertToken;
11038 if (SDNode *E = lookupNode(ID, Dl, InsertToken))
11039 return SDValue(E, 0);
11040
11041 auto *N = newSDNode<PseudoProbeSDNode>(
11042 Opcode, Dl.getIROrder(), Dl.getDebugLoc(), VTs, Guid, Index, Attr);
11043 createOperands(N, Ops);
11044 CSEMap.insert(N, InsertToken);
11045 InsertNode(N);
11046 SDValue V(N, 0);
11047 NewSDValueDbgMsg(V, "Creating new node: ", this);
11048 return V;
11049}
11050
11051/// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
11052/// MachinePointerInfo record from it. This is particularly useful because the
11053/// code generator has many cases where it doesn't bother passing in a
11054/// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
11056 SelectionDAG &DAG, SDValue Ptr,
11057 int64_t Offset = 0) {
11058 // If this is FI+Offset, we can model it.
11059 if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr))
11061 FI->getIndex(), Offset);
11062
11063 // If this is (FI+Offset1)+Offset2, we can model it.
11064 if (Ptr.getOpcode() != ISD::ADD ||
11067 return Info;
11068
11069 int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
11071 DAG.getMachineFunction(), FI,
11072 Offset + cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue());
11073}
11074
11075/// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
11076/// MachinePointerInfo record from it. This is particularly useful because the
11077/// code generator has many cases where it doesn't bother passing in a
11078/// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
11080 SelectionDAG &DAG, SDValue Ptr,
11081 SDValue OffsetOp) {
11082 // If the 'Offset' value isn't a constant, we can't handle this.
11084 return InferPointerInfo(Info, DAG, Ptr, OffsetNode->getSExtValue());
11085 if (OffsetOp.isUndef())
11086 return InferPointerInfo(Info, DAG, Ptr);
11087 return Info;
11088}
11089
11091 EVT VT, const SDLoc &dl, SDValue Chain,
11092 SDValue Ptr, SDValue Offset,
11093 MachinePointerInfo PtrInfo, EVT MemVT,
11094 Align Alignment,
11095 MachineMemOperand::Flags MMOFlags,
11096 const MMOMetadata &Metadata) {
11097 assert(Chain.getValueType() == MVT::Other &&
11098 "Invalid chain type");
11099
11100 MMOFlags |= MachineMemOperand::MOLoad;
11101 assert((MMOFlags & MachineMemOperand::MOStore) == 0);
11102 // If we don't have a PtrInfo, infer the trivial frame index case to simplify
11103 // clients.
11104 if (PtrInfo.V.isNull())
11105 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
11106
11107 TypeSize Size = MemVT.getStoreSize();
11109 MachineMemOperand *MMO =
11110 MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, Alignment, Metadata);
11111 return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO);
11112}
11113
11115 EVT VT, const SDLoc &dl, SDValue Chain,
11116 SDValue Ptr, SDValue Offset, EVT MemVT,
11117 MachineMemOperand *MMO) {
11118 if (VT == MemVT) {
11119 ExtType = ISD::NON_EXTLOAD;
11120 } else if (ExtType == ISD::NON_EXTLOAD) {
11121 assert(VT == MemVT && "Non-extending load from different memory type!");
11122 } else {
11123 // Extending load.
11124 assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) &&
11125 "Should only be an extending load, not truncating!");
11126 assert(VT.isInteger() == MemVT.isInteger() &&
11127 "Cannot convert from FP to Int or Int -> FP!");
11128 assert(VT.isVector() == MemVT.isVector() &&
11129 "Cannot use an ext load to convert to or from a vector!");
11130 assert((!VT.isVector() ||
11132 "Cannot use an ext load to change the number of vector elements!");
11133 }
11134
11135 assert((!MMO->getRanges() ||
11137 ->getBitWidth() == MemVT.getScalarSizeInBits() &&
11138 MemVT.isInteger())) &&
11139 "Range metadata and load type must match!");
11140
11141 bool Indexed = AM != ISD::UNINDEXED;
11142 assert((Indexed || Offset.getOpcode() == ISD::POISON) &&
11143 "Unindexed load with an offset!");
11144
11145 SDVTList VTs = Indexed ?
11146 getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
11147 SDValue Ops[] = { Chain, Ptr, Offset };
11148 SDNodeKey ID(ISD::LOAD, VTs, Ops);
11149 ID.AddInteger(MemVT.getRawBits());
11150 ID.AddInteger(getSyntheticNodeSubclassData<LoadSDNode>(
11151 dl.getIROrder(), VTs, AM, ExtType, MemVT, MMO));
11152 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11153 ID.AddInteger(MMO->getFlags());
11154 FoldingSetInsertToken InsertToken;
11155 if (auto *E = cast_or_null<LoadSDNode>(lookupNode(ID, dl, InsertToken))) {
11156 E->refineAlignment(MMO);
11157 E->refineMMOMetadata(MMO);
11158 return SDValue(E, 0);
11159 }
11160 auto *N = newSDNode<LoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
11161 ExtType, MemVT, MMO);
11162 createOperands(N, Ops);
11163
11164 CSEMap.insert(N, InsertToken);
11165 InsertNode(N);
11166 SDValue V(N, 0);
11167 NewSDValueDbgMsg(V, "Creating new node: ", this);
11168 return V;
11169}
11170
11172 SDValue Ptr, MachinePointerInfo PtrInfo,
11173 MaybeAlign Alignment,
11174 MachineMemOperand::Flags MMOFlags,
11175 const MMOMetadata &Metadata) {
11177 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
11178 PtrInfo, VT, Alignment, MMOFlags, Metadata);
11179}
11180
11182 SDValue Ptr, MachineMemOperand *MMO) {
11184 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
11185 VT, MMO);
11186}
11187
11189 EVT VT, SDValue Chain, SDValue Ptr,
11190 MachinePointerInfo PtrInfo, EVT MemVT,
11191 MaybeAlign Alignment,
11192 MachineMemOperand::Flags MMOFlags,
11193 const MMOMetadata &Metadata) {
11195 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, PtrInfo,
11196 MemVT, Alignment, MMOFlags, Metadata);
11197}
11198
11200 EVT VT, SDValue Chain, SDValue Ptr, EVT MemVT,
11201 MachineMemOperand *MMO) {
11203 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef,
11204 MemVT, MMO);
11205}
11206
11210 LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
11211 assert(LD->getOffset().getOpcode() == ISD::POISON &&
11212 "Load is already a indexed load!");
11213 // Don't propagate the invariant or dereferenceable flags.
11214 auto MMOFlags =
11215 LD->getMemOperand()->getFlags() &
11217 return getLoad(
11218 AM, LD->getExtensionType(), OrigLoad.getValueType(), dl, LD->getChain(),
11219 Base, Offset, LD->getPointerInfo(), LD->getMemoryVT(), LD->getAlign(),
11220 MMOFlags,
11221 MMOMetadata(LD->getAAInfo(), LD->getRanges(), LD->getMemCacheHint()));
11222}
11223
11225 SDValue Ptr, MachinePointerInfo PtrInfo,
11226 Align Alignment,
11227 MachineMemOperand::Flags MMOFlags,
11228 const MMOMetadata &Metadata) {
11229 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
11230
11231 MMOFlags |= MachineMemOperand::MOStore;
11232 assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
11233 assert(!Metadata.Ranges && "range metadata is invalid for stores");
11234
11235 if (PtrInfo.V.isNull())
11236 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
11237
11240 MachineMemOperand *MMO =
11241 MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, Alignment, Metadata);
11242 return getStore(Chain, dl, Val, Ptr, MMO);
11243}
11244
11246 SDValue Ptr, MachineMemOperand *MMO) {
11248 return getStore(Chain, dl, Val, Ptr, Undef, Val.getValueType(), MMO,
11250}
11251
11253 SDValue Ptr, SDValue Offset, EVT SVT,
11255 bool IsTruncating) {
11256 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
11257 EVT VT = Val.getValueType();
11258 if (VT == SVT) {
11259 IsTruncating = false;
11260 } else if (!IsTruncating) {
11261 assert(VT == SVT && "No-truncating store from different memory type!");
11262 } else {
11264 "Should only be a truncating store, not extending!");
11265 assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!");
11266 assert(VT.isVector() == SVT.isVector() &&
11267 "Cannot use trunc store to convert to or from a vector!");
11268 assert((!VT.isVector() ||
11270 "Cannot use trunc store to change the number of vector elements!");
11271 }
11272
11273 bool Indexed = AM != ISD::UNINDEXED;
11274 assert((Indexed || Offset.getOpcode() == ISD::POISON) &&
11275 "Unindexed store with an offset!");
11276 SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other)
11277 : getVTList(MVT::Other);
11278 SDValue Ops[] = {Chain, Val, Ptr, Offset};
11279 SDNodeKey ID(ISD::STORE, VTs, Ops);
11280 ID.AddInteger(SVT.getRawBits());
11281 ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
11282 dl.getIROrder(), VTs, AM, IsTruncating, SVT, MMO));
11283 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11284 ID.AddInteger(MMO->getFlags());
11285 FoldingSetInsertToken InsertToken;
11286 if (SDNode *E = lookupNode(ID, dl, InsertToken)) {
11287 cast<StoreSDNode>(E)->refineAlignment(MMO);
11288 cast<StoreSDNode>(E)->refineMMOMetadata(MMO);
11289 return SDValue(E, 0);
11290 }
11291 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
11292 IsTruncating, SVT, MMO);
11293 createOperands(N, Ops);
11294
11295 CSEMap.insert(N, InsertToken);
11296 InsertNode(N);
11297 SDValue V(N, 0);
11298 NewSDValueDbgMsg(V, "Creating new node: ", this);
11299 return V;
11300}
11301
11303 SDValue Ptr, SDValue Offset,
11304 MachinePointerInfo PtrInfo, EVT SVT,
11305 Align Alignment,
11306 MachineMemOperand::Flags MMOFlags,
11307 const MMOMetadata &Metadata) {
11308 assert(Chain.getValueType() == MVT::Other &&
11309 "Invalid chain type");
11310
11311 MMOFlags |= MachineMemOperand::MOStore;
11312 assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
11313 assert(!Metadata.Ranges && "range metadata is invalid for stores");
11314
11315 if (PtrInfo.V.isNull())
11316 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
11317
11319 MachineMemOperand *MMO = MF.getMachineMemOperand(
11320 PtrInfo, MMOFlags, SVT.getStoreSize(), Alignment, Metadata);
11321 return getTruncStore(Chain, dl, Val, Ptr, Offset, SVT, MMO);
11322}
11323
11325 SDValue Ptr, MachinePointerInfo PtrInfo,
11326 EVT SVT, Align Alignment,
11327 MachineMemOperand::Flags MMOFlags,
11328 const MMOMetadata &Metadata) {
11329 return getTruncStore(Chain, dl, Val, Ptr, getPOISON(Ptr.getValueType()),
11330 PtrInfo, SVT, Alignment, MMOFlags, Metadata);
11331}
11332
11334 SDValue Ptr, SDValue Offset, EVT SVT,
11335 MachineMemOperand *MMO) {
11336 return getStore(Chain, dl, Val, Ptr, Offset, SVT, MMO, ISD::UNINDEXED, true);
11337}
11338
11340 SDValue Ptr, EVT SVT,
11341 MachineMemOperand *MMO) {
11342 return getStore(Chain, dl, Val, Ptr, getPOISON(Ptr.getValueType()), SVT, MMO,
11343 ISD::UNINDEXED, true);
11344}
11345
11349 StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
11350 assert(ST->getOffset().getOpcode() == ISD::POISON &&
11351 "Store is already a indexed store!");
11352 return getStore(ST->getChain(), dl, ST->getValue(), Base, Offset,
11353 ST->getMemoryVT(), ST->getMemOperand(), AM,
11354 ST->isTruncatingStore());
11355}
11356
11358 ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &dl,
11359 SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Mask, SDValue EVL,
11360 MachinePointerInfo PtrInfo, EVT MemVT, Align Alignment,
11361 MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
11362 const MDNode *Ranges, bool IsExpanding) {
11363 MMOFlags |= MachineMemOperand::MOLoad;
11364 assert((MMOFlags & MachineMemOperand::MOStore) == 0);
11365 // If we don't have a PtrInfo, infer the trivial frame index case to simplify
11366 // clients.
11367 if (PtrInfo.V.isNull())
11368 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
11369
11370 TypeSize Size = MemVT.getStoreSize();
11372 MachineMemOperand *MMO = MF.getMachineMemOperand(
11373 PtrInfo, MMOFlags, Size, Alignment, MMOMetadata(AAInfo, Ranges));
11374 return getLoadVP(AM, ExtType, VT, dl, Chain, Ptr, Offset, Mask, EVL, MemVT,
11375 MMO, IsExpanding);
11376}
11377
11379 ISD::LoadExtType ExtType, EVT VT,
11380 const SDLoc &dl, SDValue Chain, SDValue Ptr,
11381 SDValue Offset, SDValue Mask, SDValue EVL,
11382 EVT MemVT, MachineMemOperand *MMO,
11383 bool IsExpanding) {
11384 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
11385 assert(Mask.getValueType().getVectorElementCount() ==
11386 VT.getVectorElementCount() &&
11387 "Vector width mismatch between mask and data");
11388
11389 bool Indexed = AM != ISD::UNINDEXED;
11390 assert((Indexed || Offset.getOpcode() == ISD::POISON) &&
11391 "Unindexed load with an offset!");
11392
11393 SDVTList VTs = Indexed ? getVTList(VT, Ptr.getValueType(), MVT::Other)
11394 : getVTList(VT, MVT::Other);
11395 SDValue Ops[] = {Chain, Ptr, Offset, Mask, EVL};
11396 SDNodeKey ID(ISD::VP_LOAD, VTs, Ops);
11397 ID.AddInteger(MemVT.getRawBits());
11398 ID.AddInteger(getSyntheticNodeSubclassData<VPLoadSDNode>(
11399 dl.getIROrder(), VTs, AM, ExtType, IsExpanding, MemVT, MMO));
11400 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11401 ID.AddInteger(MMO->getFlags());
11402 FoldingSetInsertToken InsertToken;
11403 if (auto *E = cast_or_null<VPLoadSDNode>(lookupNode(ID, dl, InsertToken))) {
11404 E->refineAlignment(MMO);
11405 E->refineMMOMetadata(MMO);
11406 return SDValue(E, 0);
11407 }
11408 auto *N = newSDNode<VPLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
11409 ExtType, IsExpanding, MemVT, MMO);
11410 createOperands(N, Ops);
11411
11412 CSEMap.insert(N, InsertToken);
11413 InsertNode(N);
11414 SDValue V(N, 0);
11415 NewSDValueDbgMsg(V, "Creating new node: ", this);
11416 return V;
11417}
11418
11420 SDValue Ptr, SDValue Mask, SDValue EVL,
11421 MachinePointerInfo PtrInfo,
11422 MaybeAlign Alignment,
11423 MachineMemOperand::Flags MMOFlags,
11424 const AAMDNodes &AAInfo, const MDNode *Ranges,
11425 bool IsExpanding) {
11427 return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
11428 Mask, EVL, PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges,
11429 IsExpanding);
11430}
11431
11433 SDValue Ptr, SDValue Mask, SDValue EVL,
11434 MachineMemOperand *MMO, bool IsExpanding) {
11436 return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
11437 Mask, EVL, VT, MMO, IsExpanding);
11438}
11439
11441 EVT VT, SDValue Chain, SDValue Ptr,
11442 SDValue Mask, SDValue EVL,
11443 MachinePointerInfo PtrInfo, EVT MemVT,
11444 MaybeAlign Alignment,
11445 MachineMemOperand::Flags MMOFlags,
11446 const AAMDNodes &AAInfo, bool IsExpanding) {
11448 return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask,
11449 EVL, PtrInfo, MemVT, Alignment, MMOFlags, AAInfo, nullptr,
11450 IsExpanding);
11451}
11452
11454 EVT VT, SDValue Chain, SDValue Ptr,
11455 SDValue Mask, SDValue EVL, EVT MemVT,
11456 MachineMemOperand *MMO, bool IsExpanding) {
11458 return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask,
11459 EVL, MemVT, MMO, IsExpanding);
11460}
11461
11463 SDValue Ptr, SDValue Offset, SDValue Mask,
11464 SDValue EVL, EVT MemVT, MachineMemOperand *MMO,
11465 ISD::MemIndexedMode AM, bool IsTruncating,
11466 bool IsCompressing) {
11467 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
11468 assert(Mask.getValueType().getVectorElementCount() ==
11470 "Vector width mismatch between mask and data");
11471
11472 bool Indexed = AM != ISD::UNINDEXED;
11473 assert((Indexed || Offset.getOpcode() == ISD::POISON) &&
11474 "Unindexed vp_store with an offset!");
11475 SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other)
11476 : getVTList(MVT::Other);
11477 SDValue Ops[] = {Chain, Val, Ptr, Offset, Mask, EVL};
11478 SDNodeKey ID(ISD::VP_STORE, VTs, Ops);
11479 ID.AddInteger(MemVT.getRawBits());
11480 ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>(
11481 dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
11482 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11483 ID.AddInteger(MMO->getFlags());
11484 FoldingSetInsertToken InsertToken;
11485 if (SDNode *E = lookupNode(ID, dl, InsertToken)) {
11486 cast<VPStoreSDNode>(E)->refineAlignment(MMO);
11487 return SDValue(E, 0);
11488 }
11489 auto *N = newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
11490 IsTruncating, IsCompressing, MemVT, MMO);
11491 createOperands(N, Ops);
11492
11493 CSEMap.insert(N, InsertToken);
11494 InsertNode(N);
11495 SDValue V(N, 0);
11496 NewSDValueDbgMsg(V, "Creating new node: ", this);
11497 return V;
11498}
11499
11501 SDValue Val, SDValue Ptr, SDValue Mask,
11502 SDValue EVL, MachinePointerInfo PtrInfo,
11503 EVT SVT, Align Alignment,
11504 MachineMemOperand::Flags MMOFlags,
11505 const AAMDNodes &AAInfo,
11506 bool IsCompressing) {
11507 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
11508
11509 MMOFlags |= MachineMemOperand::MOStore;
11510 assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
11511
11512 if (PtrInfo.V.isNull())
11513 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
11514
11516 MachineMemOperand *MMO = MF.getMachineMemOperand(
11517 PtrInfo, MMOFlags, SVT.getStoreSize(), Alignment, AAInfo);
11518 return getTruncStoreVP(Chain, dl, Val, Ptr, Mask, EVL, SVT, MMO,
11519 IsCompressing);
11520}
11521
11523 SDValue Val, SDValue Ptr, SDValue Mask,
11524 SDValue EVL, EVT SVT,
11525 MachineMemOperand *MMO,
11526 bool IsCompressing) {
11527 EVT VT = Val.getValueType();
11528
11529 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
11530 if (VT == SVT)
11531 return getStoreVP(Chain, dl, Val, Ptr, getPOISON(Ptr.getValueType()), Mask,
11532 EVL, VT, MMO, ISD::UNINDEXED,
11533 /*IsTruncating*/ false, IsCompressing);
11534
11536 "Should only be a truncating store, not extending!");
11537 assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!");
11538 assert(VT.isVector() == SVT.isVector() &&
11539 "Cannot use trunc store to convert to or from a vector!");
11540 assert((!VT.isVector() ||
11542 "Cannot use trunc store to change the number of vector elements!");
11543
11544 SDVTList VTs = getVTList(MVT::Other);
11546 SDValue Ops[] = {Chain, Val, Ptr, Undef, Mask, EVL};
11547 SDNodeKey ID(ISD::VP_STORE, VTs, Ops);
11548 ID.AddInteger(SVT.getRawBits());
11549 ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>(
11550 dl.getIROrder(), VTs, ISD::UNINDEXED, true, IsCompressing, SVT, MMO));
11551 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11552 ID.AddInteger(MMO->getFlags());
11553 FoldingSetInsertToken InsertToken;
11554 if (SDNode *E = lookupNode(ID, dl, InsertToken)) {
11555 cast<VPStoreSDNode>(E)->refineAlignment(MMO);
11556 return SDValue(E, 0);
11557 }
11558 auto *N =
11559 newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
11560 ISD::UNINDEXED, true, IsCompressing, SVT, MMO);
11561 createOperands(N, Ops);
11562
11563 CSEMap.insert(N, InsertToken);
11564 InsertNode(N);
11565 SDValue V(N, 0);
11566 NewSDValueDbgMsg(V, "Creating new node: ", this);
11567 return V;
11568}
11569
11571 ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &DL,
11572 SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Stride, SDValue Mask,
11573 SDValue EVL, EVT MemVT, MachineMemOperand *MMO, bool IsExpanding) {
11574 bool Indexed = AM != ISD::UNINDEXED;
11575 assert((Indexed || Offset.getOpcode() == ISD::POISON) &&
11576 "Unindexed load with an offset!");
11577
11578 SDValue Ops[] = {Chain, Ptr, Offset, Stride, Mask, EVL};
11579 SDVTList VTs = Indexed ? getVTList(VT, Ptr.getValueType(), MVT::Other)
11580 : getVTList(VT, MVT::Other);
11581 SDNodeKey ID(ISD::EXPERIMENTAL_VP_STRIDED_LOAD, VTs, Ops);
11582 ID.AddInteger(MemVT.getRawBits());
11583 ID.AddInteger(getSyntheticNodeSubclassData<VPStridedLoadSDNode>(
11584 DL.getIROrder(), VTs, AM, ExtType, IsExpanding, MemVT, MMO));
11585 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11586
11587 FoldingSetInsertToken InsertToken;
11588 if (SDNode *E = lookupNode(ID, DL, InsertToken)) {
11589 cast<VPStridedLoadSDNode>(E)->refineAlignment(MMO);
11590 return SDValue(E, 0);
11591 }
11592
11593 auto *N =
11594 newSDNode<VPStridedLoadSDNode>(DL.getIROrder(), DL.getDebugLoc(), VTs, AM,
11595 ExtType, IsExpanding, MemVT, MMO);
11596 createOperands(N, Ops);
11597 CSEMap.insert(N, InsertToken);
11598 InsertNode(N);
11599 SDValue V(N, 0);
11600 NewSDValueDbgMsg(V, "Creating new node: ", this);
11601 return V;
11602}
11603
11605 SDValue Ptr, SDValue Stride,
11606 SDValue Mask, SDValue EVL,
11607 MachineMemOperand *MMO,
11608 bool IsExpanding) {
11610 return getStridedLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, DL, Chain, Ptr,
11611 Undef, Stride, Mask, EVL, VT, MMO, IsExpanding);
11612}
11613
11615 ISD::LoadExtType ExtType, const SDLoc &DL, EVT VT, SDValue Chain,
11616 SDValue Ptr, SDValue Stride, SDValue Mask, SDValue EVL, EVT MemVT,
11617 MachineMemOperand *MMO, bool IsExpanding) {
11619 return getStridedLoadVP(ISD::UNINDEXED, ExtType, VT, DL, Chain, Ptr, Undef,
11620 Stride, Mask, EVL, MemVT, MMO, IsExpanding);
11621}
11622
11624 SDValue Val, SDValue Ptr,
11625 SDValue Offset, SDValue Stride,
11626 SDValue Mask, SDValue EVL, EVT MemVT,
11627 MachineMemOperand *MMO,
11629 bool IsTruncating, bool IsCompressing) {
11630 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
11631 bool Indexed = AM != ISD::UNINDEXED;
11632 assert((Indexed || Offset.getOpcode() == ISD::POISON) &&
11633 "Unindexed vp_store with an offset!");
11634 SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other)
11635 : getVTList(MVT::Other);
11636 SDValue Ops[] = {Chain, Val, Ptr, Offset, Stride, Mask, EVL};
11637 SDNodeKey ID(ISD::EXPERIMENTAL_VP_STRIDED_STORE, VTs, Ops);
11638 ID.AddInteger(MemVT.getRawBits());
11639 ID.AddInteger(getSyntheticNodeSubclassData<VPStridedStoreSDNode>(
11640 DL.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
11641 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11642 FoldingSetInsertToken InsertToken;
11643 if (SDNode *E = lookupNode(ID, DL, InsertToken)) {
11644 cast<VPStridedStoreSDNode>(E)->refineAlignment(MMO);
11645 return SDValue(E, 0);
11646 }
11647 auto *N = newSDNode<VPStridedStoreSDNode>(DL.getIROrder(), DL.getDebugLoc(),
11648 VTs, AM, IsTruncating,
11649 IsCompressing, MemVT, MMO);
11650 createOperands(N, Ops);
11651
11652 CSEMap.insert(N, InsertToken);
11653 InsertNode(N);
11654 SDValue V(N, 0);
11655 NewSDValueDbgMsg(V, "Creating new node: ", this);
11656 return V;
11657}
11658
11661 ISD::MemIndexType IndexType) {
11662 assert(Ops.size() == 6 && "Incompatible number of operands");
11663
11664 SDNodeKey ID(ISD::VP_GATHER, VTs, Ops);
11665 ID.AddInteger(VT.getRawBits());
11666 ID.AddInteger(getSyntheticNodeSubclassData<VPGatherSDNode>(
11667 dl.getIROrder(), VTs, VT, MMO, IndexType));
11668 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11669 ID.AddInteger(MMO->getFlags());
11670 FoldingSetInsertToken InsertToken;
11671 if (SDNode *E = lookupNode(ID, dl, InsertToken)) {
11672 cast<VPGatherSDNode>(E)->refineAlignment(MMO);
11673 return SDValue(E, 0);
11674 }
11675
11676 auto *N = newSDNode<VPGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
11677 VT, MMO, IndexType);
11678 createOperands(N, Ops);
11679
11680 assert(N->getMask().getValueType().getVectorElementCount() ==
11681 N->getValueType(0).getVectorElementCount() &&
11682 "Vector width mismatch between mask and data");
11683 assert(N->getIndex().getValueType().getVectorElementCount().isScalable() ==
11684 N->getValueType(0).getVectorElementCount().isScalable() &&
11685 "Scalable flags of index and data do not match");
11687 N->getIndex().getValueType().getVectorElementCount(),
11688 N->getValueType(0).getVectorElementCount()) &&
11689 "Vector width mismatch between index and data");
11690 assert(isa<ConstantSDNode>(N->getScale()) &&
11691 N->getScale()->getAsAPIntVal().isPowerOf2() &&
11692 "Scale should be a constant power of 2");
11693
11694 CSEMap.insert(N, InsertToken);
11695 InsertNode(N);
11696 SDValue V(N, 0);
11697 NewSDValueDbgMsg(V, "Creating new node: ", this);
11698 return V;
11699}
11700
11703 MachineMemOperand *MMO,
11704 ISD::MemIndexType IndexType) {
11705 assert(Ops.size() == 7 && "Incompatible number of operands");
11706
11707 SDNodeKey ID(ISD::VP_SCATTER, VTs, Ops);
11708 ID.AddInteger(VT.getRawBits());
11709 ID.AddInteger(getSyntheticNodeSubclassData<VPScatterSDNode>(
11710 dl.getIROrder(), VTs, VT, MMO, IndexType));
11711 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11712 ID.AddInteger(MMO->getFlags());
11713 FoldingSetInsertToken InsertToken;
11714 if (SDNode *E = lookupNode(ID, dl, InsertToken)) {
11715 cast<VPScatterSDNode>(E)->refineAlignment(MMO);
11716 return SDValue(E, 0);
11717 }
11718 auto *N = newSDNode<VPScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
11719 VT, MMO, IndexType);
11720 createOperands(N, Ops);
11721
11722 assert(N->getMask().getValueType().getVectorElementCount() ==
11723 N->getValue().getValueType().getVectorElementCount() &&
11724 "Vector width mismatch between mask and data");
11725 assert(
11726 N->getIndex().getValueType().getVectorElementCount().isScalable() ==
11727 N->getValue().getValueType().getVectorElementCount().isScalable() &&
11728 "Scalable flags of index and data do not match");
11730 N->getIndex().getValueType().getVectorElementCount(),
11731 N->getValue().getValueType().getVectorElementCount()) &&
11732 "Vector width mismatch between index and data");
11733 assert(isa<ConstantSDNode>(N->getScale()) &&
11734 N->getScale()->getAsAPIntVal().isPowerOf2() &&
11735 "Scale should be a constant power of 2");
11736
11737 CSEMap.insert(N, InsertToken);
11738 InsertNode(N);
11739 SDValue V(N, 0);
11740 NewSDValueDbgMsg(V, "Creating new node: ", this);
11741 return V;
11742}
11743
11746 SDValue PassThru, EVT MemVT,
11747 MachineMemOperand *MMO,
11749 ISD::LoadExtType ExtTy, bool isExpanding) {
11750 bool Indexed = AM != ISD::UNINDEXED;
11751 assert((Indexed || Offset.getOpcode() == ISD::POISON) &&
11752 "Unindexed masked load with an offset!");
11753 SDVTList VTs = Indexed ? getVTList(VT, Base.getValueType(), MVT::Other)
11754 : getVTList(VT, MVT::Other);
11755 SDValue Ops[] = {Chain, Base, Offset, Mask, PassThru};
11756 SDNodeKey ID(ISD::MLOAD, VTs, Ops);
11757 ID.AddInteger(MemVT.getRawBits());
11758 ID.AddInteger(getSyntheticNodeSubclassData<MaskedLoadSDNode>(
11759 dl.getIROrder(), VTs, AM, ExtTy, isExpanding, MemVT, MMO));
11760 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11761 ID.AddInteger(MMO->getFlags());
11762 FoldingSetInsertToken InsertToken;
11763 if (SDNode *E = lookupNode(ID, dl, InsertToken)) {
11764 cast<MaskedLoadSDNode>(E)->refineAlignment(MMO);
11765 return SDValue(E, 0);
11766 }
11767 auto *N = newSDNode<MaskedLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
11768 AM, ExtTy, isExpanding, MemVT, MMO);
11769 createOperands(N, Ops);
11770
11771 CSEMap.insert(N, InsertToken);
11772 InsertNode(N);
11773 SDValue V(N, 0);
11774 NewSDValueDbgMsg(V, "Creating new node: ", this);
11775 return V;
11776}
11777
11782 assert(LD->getOffset().getOpcode() == ISD::POISON &&
11783 "Masked load is already a indexed load!");
11784 return getMaskedLoad(OrigLoad.getValueType(), dl, LD->getChain(), Base,
11785 Offset, LD->getMask(), LD->getPassThru(),
11786 LD->getMemoryVT(), LD->getMemOperand(), AM,
11787 LD->getExtensionType(), LD->isExpandingLoad());
11788}
11789
11792 SDValue Mask, EVT MemVT,
11793 MachineMemOperand *MMO,
11794 ISD::MemIndexedMode AM, bool IsTruncating,
11795 bool IsCompressing) {
11796 assert(Chain.getValueType() == MVT::Other &&
11797 "Invalid chain type");
11798 bool Indexed = AM != ISD::UNINDEXED;
11799 assert((Indexed || Offset.getOpcode() == ISD::POISON) &&
11800 "Unindexed masked store with an offset!");
11801 SDVTList VTs = Indexed ? getVTList(Base.getValueType(), MVT::Other)
11802 : getVTList(MVT::Other);
11803 SDValue Ops[] = {Chain, Val, Base, Offset, Mask};
11804 SDNodeKey ID(ISD::MSTORE, VTs, Ops);
11805 ID.AddInteger(MemVT.getRawBits());
11806 ID.AddInteger(getSyntheticNodeSubclassData<MaskedStoreSDNode>(
11807 dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
11808 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11809 ID.AddInteger(MMO->getFlags());
11810 FoldingSetInsertToken InsertToken;
11811 if (SDNode *E = lookupNode(ID, dl, InsertToken)) {
11812 cast<MaskedStoreSDNode>(E)->refineAlignment(MMO);
11813 return SDValue(E, 0);
11814 }
11815 auto *N =
11816 newSDNode<MaskedStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
11817 IsTruncating, IsCompressing, MemVT, MMO);
11818 createOperands(N, Ops);
11819
11820 CSEMap.insert(N, InsertToken);
11821 InsertNode(N);
11822 SDValue V(N, 0);
11823 NewSDValueDbgMsg(V, "Creating new node: ", this);
11824 return V;
11825}
11826
11831 assert(ST->getOffset().getOpcode() == ISD::POISON &&
11832 "Masked store is already a indexed store!");
11833 return getMaskedStore(ST->getChain(), dl, ST->getValue(), Base, Offset,
11834 ST->getMask(), ST->getMemoryVT(), ST->getMemOperand(),
11835 AM, ST->isTruncatingStore(), ST->isCompressingStore());
11836}
11837
11840 MachineMemOperand *MMO,
11841 ISD::MemIndexType IndexType,
11842 ISD::LoadExtType ExtTy) {
11843 assert(Ops.size() == 6 && "Incompatible number of operands");
11844
11845 SDNodeKey ID(ISD::MGATHER, VTs, Ops);
11846 ID.AddInteger(MemVT.getRawBits());
11847 ID.AddInteger(getSyntheticNodeSubclassData<MaskedGatherSDNode>(
11848 dl.getIROrder(), VTs, MemVT, MMO, IndexType, ExtTy));
11849 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11850 ID.AddInteger(MMO->getFlags());
11851 FoldingSetInsertToken InsertToken;
11852 if (SDNode *E = lookupNode(ID, dl, InsertToken)) {
11853 cast<MaskedGatherSDNode>(E)->refineAlignment(MMO);
11854 return SDValue(E, 0);
11855 }
11856
11857 auto *N = newSDNode<MaskedGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(),
11858 VTs, MemVT, MMO, IndexType, ExtTy);
11859 createOperands(N, Ops);
11860
11861 assert(N->getPassThru().getValueType() == N->getValueType(0) &&
11862 "Incompatible type of the PassThru value in MaskedGatherSDNode");
11863 assert(N->getMask().getValueType().getVectorElementCount() ==
11864 N->getValueType(0).getVectorElementCount() &&
11865 "Vector width mismatch between mask and data");
11866 assert(N->getIndex().getValueType().getVectorElementCount().isScalable() ==
11867 N->getValueType(0).getVectorElementCount().isScalable() &&
11868 "Scalable flags of index and data do not match");
11870 N->getIndex().getValueType().getVectorElementCount(),
11871 N->getValueType(0).getVectorElementCount()) &&
11872 "Vector width mismatch between index and data");
11873 assert(isa<ConstantSDNode>(N->getScale()) &&
11874 N->getScale()->getAsAPIntVal().isPowerOf2() &&
11875 "Scale should be a constant power of 2");
11876
11877 CSEMap.insert(N, InsertToken);
11878 InsertNode(N);
11879 SDValue V(N, 0);
11880 NewSDValueDbgMsg(V, "Creating new node: ", this);
11881 return V;
11882}
11883
11886 MachineMemOperand *MMO,
11887 ISD::MemIndexType IndexType,
11888 bool IsTrunc) {
11889 assert(Ops.size() == 6 && "Incompatible number of operands");
11890
11891 SDNodeKey ID(ISD::MSCATTER, VTs, Ops);
11892 ID.AddInteger(MemVT.getRawBits());
11893 ID.AddInteger(getSyntheticNodeSubclassData<MaskedScatterSDNode>(
11894 dl.getIROrder(), VTs, MemVT, MMO, IndexType, IsTrunc));
11895 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11896 ID.AddInteger(MMO->getFlags());
11897 FoldingSetInsertToken InsertToken;
11898 if (SDNode *E = lookupNode(ID, dl, InsertToken)) {
11899 cast<MaskedScatterSDNode>(E)->refineAlignment(MMO);
11900 return SDValue(E, 0);
11901 }
11902
11903 auto *N = newSDNode<MaskedScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(),
11904 VTs, MemVT, MMO, IndexType, IsTrunc);
11905 createOperands(N, Ops);
11906
11907 assert(N->getMask().getValueType().getVectorElementCount() ==
11908 N->getValue().getValueType().getVectorElementCount() &&
11909 "Vector width mismatch between mask and data");
11910 assert(
11911 N->getIndex().getValueType().getVectorElementCount().isScalable() ==
11912 N->getValue().getValueType().getVectorElementCount().isScalable() &&
11913 "Scalable flags of index and data do not match");
11915 N->getIndex().getValueType().getVectorElementCount(),
11916 N->getValue().getValueType().getVectorElementCount()) &&
11917 "Vector width mismatch between index and data");
11918 assert(isa<ConstantSDNode>(N->getScale()) &&
11919 N->getScale()->getAsAPIntVal().isPowerOf2() &&
11920 "Scale should be a constant power of 2");
11921
11922 CSEMap.insert(N, InsertToken);
11923 InsertNode(N);
11924 SDValue V(N, 0);
11925 NewSDValueDbgMsg(V, "Creating new node: ", this);
11926 return V;
11927}
11928
11930 const SDLoc &dl, ArrayRef<SDValue> Ops,
11931 MachineMemOperand *MMO,
11932 ISD::MemIndexType IndexType) {
11933 assert(Ops.size() == 7 && "Incompatible number of operands");
11934
11936 ID.AddInteger(MemVT.getRawBits());
11937 ID.AddInteger(getSyntheticNodeSubclassData<MaskedHistogramSDNode>(
11938 dl.getIROrder(), VTs, MemVT, MMO, IndexType));
11939 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11940 ID.AddInteger(MMO->getFlags());
11941 FoldingSetInsertToken InsertToken;
11942 if (SDNode *E = lookupNode(ID, dl, InsertToken)) {
11943 cast<MaskedGatherSDNode>(E)->refineAlignment(MMO);
11944 return SDValue(E, 0);
11945 }
11946
11947 auto *N = newSDNode<MaskedHistogramSDNode>(dl.getIROrder(), dl.getDebugLoc(),
11948 VTs, MemVT, MMO, IndexType);
11949 createOperands(N, Ops);
11950
11951 assert(N->getMask().getValueType().getVectorElementCount() ==
11952 N->getIndex().getValueType().getVectorElementCount() &&
11953 "Vector width mismatch between mask and data");
11954 assert(isa<ConstantSDNode>(N->getScale()) &&
11955 N->getScale()->getAsAPIntVal().isPowerOf2() &&
11956 "Scale should be a constant power of 2");
11957 assert(N->getInc().getValueType().isInteger() && "Non integer update value");
11958
11959 CSEMap.insert(N, InsertToken);
11960 InsertNode(N);
11961 SDValue V(N, 0);
11962 NewSDValueDbgMsg(V, "Creating new node: ", this);
11963 return V;
11964}
11965
11967 SDValue Ptr, SDValue Mask, SDValue EVL,
11968 MachineMemOperand *MMO) {
11969 SDVTList VTs = getVTList(VT, EVL.getValueType(), MVT::Other);
11970 SDValue Ops[] = {Chain, Ptr, Mask, EVL};
11971 SDNodeKey ID(ISD::VP_LOAD_FF, VTs, Ops);
11972 ID.AddInteger(VT.getRawBits());
11973 ID.AddInteger(getSyntheticNodeSubclassData<VPLoadFFSDNode>(DL.getIROrder(),
11974 VTs, VT, MMO));
11975 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11976 ID.AddInteger(MMO->getFlags());
11977 FoldingSetInsertToken InsertToken;
11978 if (SDNode *E = lookupNode(ID, DL, InsertToken)) {
11979 cast<VPLoadFFSDNode>(E)->refineAlignment(MMO);
11980 return SDValue(E, 0);
11981 }
11982 auto *N = newSDNode<VPLoadFFSDNode>(DL.getIROrder(), DL.getDebugLoc(), VTs,
11983 VT, MMO);
11984 createOperands(N, Ops);
11985
11986 CSEMap.insert(N, InsertToken);
11987 InsertNode(N);
11988 SDValue V(N, 0);
11989 NewSDValueDbgMsg(V, "Creating new node: ", this);
11990 return V;
11991}
11992
11994 EVT MemVT, MachineMemOperand *MMO) {
11995 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
11996 SDVTList VTs = getVTList(MVT::Other);
11997 SDValue Ops[] = {Chain, Ptr};
11999 ID.AddInteger(MemVT.getRawBits());
12000 ID.AddInteger(getSyntheticNodeSubclassData<FPStateAccessSDNode>(
12001 ISD::GET_FPENV_MEM, dl.getIROrder(), VTs, MemVT, MMO));
12002 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
12003 ID.AddInteger(MMO->getFlags());
12004 FoldingSetInsertToken InsertToken;
12005 if (SDNode *E = lookupNode(ID, dl, InsertToken))
12006 return SDValue(E, 0);
12007
12008 auto *N = newSDNode<FPStateAccessSDNode>(ISD::GET_FPENV_MEM, dl.getIROrder(),
12009 dl.getDebugLoc(), VTs, MemVT, MMO);
12010 createOperands(N, Ops);
12011
12012 CSEMap.insert(N, InsertToken);
12013 InsertNode(N);
12014 SDValue V(N, 0);
12015 NewSDValueDbgMsg(V, "Creating new node: ", this);
12016 return V;
12017}
12018
12020 EVT MemVT, MachineMemOperand *MMO) {
12021 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
12022 SDVTList VTs = getVTList(MVT::Other);
12023 SDValue Ops[] = {Chain, Ptr};
12025 ID.AddInteger(MemVT.getRawBits());
12026 ID.AddInteger(getSyntheticNodeSubclassData<FPStateAccessSDNode>(
12027 ISD::SET_FPENV_MEM, dl.getIROrder(), VTs, MemVT, MMO));
12028 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
12029 ID.AddInteger(MMO->getFlags());
12030 FoldingSetInsertToken InsertToken;
12031 if (SDNode *E = lookupNode(ID, dl, InsertToken))
12032 return SDValue(E, 0);
12033
12034 auto *N = newSDNode<FPStateAccessSDNode>(ISD::SET_FPENV_MEM, dl.getIROrder(),
12035 dl.getDebugLoc(), VTs, MemVT, MMO);
12036 createOperands(N, Ops);
12037
12038 CSEMap.insert(N, InsertToken);
12039 InsertNode(N);
12040 SDValue V(N, 0);
12041 NewSDValueDbgMsg(V, "Creating new node: ", this);
12042 return V;
12043}
12044
12046 // select undef, T, F --> T (if T is a constant), otherwise F
12047 // select, ?, undef, F --> F
12048 // select, ?, T, undef --> T
12049 if (Cond.isUndef())
12050 return isConstantValueOfAnyType(T) ? T : F;
12051 if (T.isUndef())
12053 if (F.isUndef())
12055
12056 // select true, T, F --> T
12057 // select false, T, F --> F
12058 if (auto C = isBoolConstant(Cond))
12059 return *C ? T : F;
12060
12061 // select ?, T, T --> T
12062 if (T == F)
12063 return T;
12064
12065 return SDValue();
12066}
12067
12069 // shift undef, Y --> 0 (can always assume that the undef value is 0)
12070 if (X.isUndef())
12071 return getConstant(0, SDLoc(X.getNode()), X.getValueType());
12072 // shift X, undef --> undef (because it may shift by the bitwidth)
12073 if (Y.isUndef())
12074 return getUNDEF(X.getValueType());
12075
12076 // shift 0, Y --> 0
12077 // shift X, 0 --> X
12079 return X;
12080
12081 // shift X, C >= bitwidth(X) --> undef
12082 // All vector elements must be too big (or undef) to avoid partial undefs.
12083 auto isShiftTooBig = [X](ConstantSDNode *Val) {
12084 return !Val || Val->getAPIntValue().uge(X.getScalarValueSizeInBits());
12085 };
12086 if (ISD::matchUnaryPredicate(Y, isShiftTooBig, true))
12087 return getUNDEF(X.getValueType());
12088
12089 // shift i1/vXi1 X, Y --> X (any non-zero shift amount is undefined).
12090 if (X.getValueType().getScalarType() == MVT::i1)
12091 return X;
12092
12093 return SDValue();
12094}
12095
12097 SDNodeFlags Flags) {
12098 // If this operation has 'nnan' or 'ninf' and at least 1 disallowed operand
12099 // (an undef operand can be chosen to be Nan/Inf), then the result of this
12100 // operation is poison. That result can be relaxed to undef.
12101 ConstantFPSDNode *XC = isConstOrConstSplatFP(X, /* AllowUndefs */ true);
12102 ConstantFPSDNode *YC = isConstOrConstSplatFP(Y, /* AllowUndefs */ true);
12103 bool HasNan = (XC && XC->getValueAPF().isNaN()) ||
12104 (YC && YC->getValueAPF().isNaN());
12105 bool HasInf = (XC && XC->getValueAPF().isInfinity()) ||
12106 (YC && YC->getValueAPF().isInfinity());
12107
12108 if (Flags.hasNoNaNs() && (HasNan || X.isUndef() || Y.isUndef()))
12109 return getUNDEF(X.getValueType());
12110
12111 if (Flags.hasNoInfs() && (HasInf || X.isUndef() || Y.isUndef()))
12112 return getUNDEF(X.getValueType());
12113
12114 if (!YC)
12115 return SDValue();
12116
12117 // X + -0.0 --> X
12118 if (Opcode == ISD::FADD)
12119 if (YC->getValueAPF().isNegZero())
12120 return X;
12121
12122 // X - +0.0 --> X
12123 if (Opcode == ISD::FSUB)
12124 if (YC->getValueAPF().isPosZero())
12125 return X;
12126
12127 // X * 1.0 --> X
12128 // X / 1.0 --> X
12129 if (Opcode == ISD::FMUL || Opcode == ISD::FDIV)
12130 if (YC->getValueAPF().isOne())
12131 return X;
12132
12133 // X * 0.0 --> 0.0
12134 if (Opcode == ISD::FMUL && Flags.hasNoNaNs() && Flags.hasNoSignedZeros())
12135 if (YC->getValueAPF().isZero())
12136 return getConstantFP(0.0, SDLoc(Y), Y.getValueType());
12137
12138 return SDValue();
12139}
12140
12142 SDValue Ptr, SDValue SV, unsigned Align) {
12143 SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, dl, MVT::i32) };
12144 return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops);
12145}
12146
12147SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
12149 switch (Ops.size()) {
12150 case 0: return getNode(Opcode, DL, VT);
12151 case 1: return getNode(Opcode, DL, VT, Ops[0].get());
12152 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
12153 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
12154 default: break;
12155 }
12156
12157 // Copy from an SDUse array into an SDValue array for use with
12158 // the regular getNode logic.
12160 return getNode(Opcode, DL, VT, NewOps);
12161}
12162
12163SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
12165 SDNodeFlags Flags;
12166 if (Inserter)
12167 Flags = Inserter->getFlags();
12168 return getNode(Opcode, DL, VT, Ops, Flags);
12169}
12170
12171SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
12172 ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
12173 unsigned NumOps = Ops.size();
12174 switch (NumOps) {
12175 case 0: return getNode(Opcode, DL, VT);
12176 case 1: return getNode(Opcode, DL, VT, Ops[0], Flags);
12177 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Flags);
12178 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2], Flags);
12179 default: break;
12180 }
12181
12182#ifndef NDEBUG
12183 for (const auto &Op : Ops)
12184 assert(Op.getOpcode() != ISD::DELETED_NODE &&
12185 "Operand is DELETED_NODE!");
12186#endif
12187
12188 switch (Opcode) {
12189 default: break;
12190 case ISD::BUILD_VECTOR:
12191 // Attempt to simplify BUILD_VECTOR.
12192 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
12193 return V;
12194 break;
12196 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
12197 return V;
12198 break;
12199 case ISD::SELECT_CC:
12200 assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
12201 assert(Ops[0].getValueType() == Ops[1].getValueType() &&
12202 "LHS and RHS of condition must have same type!");
12203 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
12204 "True and False arms of SelectCC must have same type!");
12205 assert(Ops[2].getValueType() == VT &&
12206 "select_cc node must be of same type as true and false value!");
12207 assert((!Ops[0].getValueType().isVector() ||
12208 Ops[0].getValueType().getVectorElementCount() ==
12209 VT.getVectorElementCount()) &&
12210 "Expected select_cc with vector result to have the same sized "
12211 "comparison type!");
12212 break;
12213 case ISD::BR_CC:
12214 assert(NumOps == 5 && "BR_CC takes 5 operands!");
12215 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
12216 "LHS/RHS of comparison should match types!");
12217 break;
12218 case ISD::VP_REDUCE_MUL:
12219 // If it is VP_REDUCE_MUL mask operation then turn it to VP_REDUCE_AND
12220 if (VT == MVT::i1)
12221 Opcode = ISD::VP_REDUCE_AND;
12222 break;
12223 case ISD::VP_REDUCE_ADD:
12224 // If it is VP_REDUCE_ADD mask operation then turn it to VP_REDUCE_XOR
12225 if (VT == MVT::i1)
12226 Opcode = ISD::VP_REDUCE_XOR;
12227 break;
12228 case ISD::VP_REDUCE_SMAX:
12229 case ISD::VP_REDUCE_UMIN:
12230 // If it is VP_REDUCE_SMAX/VP_REDUCE_UMIN mask operation then turn it to
12231 // VP_REDUCE_AND.
12232 if (VT == MVT::i1)
12233 Opcode = ISD::VP_REDUCE_AND;
12234 break;
12235 case ISD::VP_REDUCE_SMIN:
12236 case ISD::VP_REDUCE_UMAX:
12237 // If it is VP_REDUCE_SMIN/VP_REDUCE_UMAX mask operation then turn it to
12238 // VP_REDUCE_OR.
12239 if (VT == MVT::i1)
12240 Opcode = ISD::VP_REDUCE_OR;
12241 break;
12242 }
12243
12244 // Memoize nodes.
12245 SDNode *N;
12246 SDVTList VTs = getVTList(VT);
12247
12248 if (VT != MVT::Glue) {
12249 SDNodeKey ID(Opcode, VTs, Ops);
12250 FoldingSetInsertToken InsertToken;
12251
12252 if (SDNode *E = lookupNode(ID, DL, InsertToken)) {
12253 E->intersectFlagsWith(Flags);
12254 return SDValue(E, 0);
12255 }
12256
12257 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
12258 createOperands(N, Ops);
12259
12260 CSEMap.insert(N, InsertToken);
12261 } else {
12262 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
12263 createOperands(N, Ops);
12264 }
12265
12266 N->setFlags(Flags);
12267 InsertNode(N);
12268 SDValue V(N, 0);
12269 NewSDValueDbgMsg(V, "Creating new node: ", this);
12270 return V;
12271}
12272
12273SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
12274 ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) {
12275 SDNodeFlags Flags;
12276 if (Inserter)
12277 Flags = Inserter->getFlags();
12278 return getNode(Opcode, DL, getVTList(ResultTys), Ops, Flags);
12279}
12280
12281SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
12283 const SDNodeFlags Flags) {
12284 return getNode(Opcode, DL, getVTList(ResultTys), Ops, Flags);
12285}
12286
12287SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
12289 SDNodeFlags Flags;
12290 if (Inserter)
12291 Flags = Inserter->getFlags();
12292 return getNode(Opcode, DL, VTList, Ops, Flags);
12293}
12294
12295SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
12296 ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
12297 if (VTList.NumVTs == 1)
12298 return getNode(Opcode, DL, VTList.VTs[0], Ops, Flags);
12299
12300#ifndef NDEBUG
12301 for (const auto &Op : Ops)
12302 assert(Op.getOpcode() != ISD::DELETED_NODE &&
12303 "Operand is DELETED_NODE!");
12304#endif
12305
12306 if (SDValue V = FoldConstantArithmetic(Opcode, DL, VTList, Ops, Flags))
12307 return V;
12308
12309 switch (Opcode) {
12310 case ISD::SADDO:
12311 case ISD::UADDO:
12312 case ISD::SSUBO:
12313 case ISD::USUBO: {
12314 assert(VTList.NumVTs == 2 && Ops.size() == 2 &&
12315 "Invalid add/sub overflow op!");
12316 assert(VTList.VTs[0].isInteger() && VTList.VTs[1].isInteger() &&
12317 Ops[0].getValueType() == Ops[1].getValueType() &&
12318 Ops[0].getValueType() == VTList.VTs[0] &&
12319 "Binary operator types must match!");
12320 SDValue N1 = Ops[0], N2 = Ops[1];
12321 canonicalizeCommutativeBinop(Opcode, N1, N2);
12322
12323 // (X +- 0) -> X with zero-overflow.
12324 ConstantSDNode *N2CV = isConstOrConstSplat(N2, /*AllowUndefs*/ false,
12325 /*AllowTruncation*/ true);
12326 if (N2CV && N2CV->isZero()) {
12327 SDValue ZeroOverFlow = getConstant(0, DL, VTList.VTs[1]);
12328 return getNode(ISD::MERGE_VALUES, DL, VTList, {N1, ZeroOverFlow}, Flags);
12329 }
12330
12331 if (VTList.VTs[0].getScalarType() == MVT::i1 &&
12332 VTList.VTs[1].getScalarType() == MVT::i1) {
12333 SDValue F1 = getFreeze(N1);
12334 SDValue F2 = getFreeze(N2);
12335 // {vXi1,vXi1} (u/s)addo(vXi1 x, vXi1y) -> {xor(x,y),and(x,y)}
12336 if (Opcode == ISD::UADDO || Opcode == ISD::SADDO)
12337 return getNode(ISD::MERGE_VALUES, DL, VTList,
12338 {getNode(ISD::XOR, DL, VTList.VTs[0], F1, F2),
12339 getNode(ISD::AND, DL, VTList.VTs[1], F1, F2)},
12340 Flags);
12341 // {vXi1,vXi1} (u/s)subo(vXi1 x, vXi1y) -> {xor(x,y),and(~x,y)}
12342 if (Opcode == ISD::USUBO || Opcode == ISD::SSUBO) {
12343 SDValue NotF1 = getNOT(DL, F1, VTList.VTs[0]);
12344 return getNode(ISD::MERGE_VALUES, DL, VTList,
12345 {getNode(ISD::XOR, DL, VTList.VTs[0], F1, F2),
12346 getNode(ISD::AND, DL, VTList.VTs[1], NotF1, F2)},
12347 Flags);
12348 }
12349 }
12350 break;
12351 }
12352 case ISD::SADDO_CARRY:
12353 case ISD::UADDO_CARRY:
12354 case ISD::SSUBO_CARRY:
12355 case ISD::USUBO_CARRY:
12356 assert(VTList.NumVTs == 2 && Ops.size() == 3 &&
12357 "Invalid add/sub overflow op!");
12358 assert(VTList.VTs[0].isInteger() && VTList.VTs[1].isInteger() &&
12359 Ops[0].getValueType() == Ops[1].getValueType() &&
12360 Ops[0].getValueType() == VTList.VTs[0] &&
12361 Ops[2].getValueType() == VTList.VTs[1] &&
12362 "Binary operator types must match!");
12363 break;
12364 case ISD::SMUL_LOHI:
12365 case ISD::UMUL_LOHI: {
12366 assert(VTList.NumVTs == 2 && Ops.size() == 2 && "Invalid mul lo/hi op!");
12367 assert(VTList.VTs[0].isInteger() && VTList.VTs[0] == VTList.VTs[1] &&
12368 VTList.VTs[0] == Ops[0].getValueType() &&
12369 VTList.VTs[0] == Ops[1].getValueType() &&
12370 "Binary operator types must match!");
12371 break;
12372 }
12373 case ISD::FFREXP: {
12374 assert(VTList.NumVTs == 2 && Ops.size() == 1 && "Invalid ffrexp op!");
12375 assert(VTList.VTs[0].isFloatingPoint() && VTList.VTs[1].isInteger() &&
12376 VTList.VTs[0] == Ops[0].getValueType() && "frexp type mismatch");
12377
12379 int FrexpExp;
12380 APFloat FrexpMant =
12381 frexp(C->getValueAPF(), FrexpExp, APFloat::rmNearestTiesToEven);
12382 SDValue Result0 = getConstantFP(FrexpMant, DL, VTList.VTs[0]);
12383 SDValue Result1 = getSignedConstant(FrexpMant.isFinite() ? FrexpExp : 0,
12384 DL, VTList.VTs[1]);
12385 return getNode(ISD::MERGE_VALUES, DL, VTList, {Result0, Result1}, Flags);
12386 }
12387
12388 break;
12389 }
12391 assert(VTList.NumVTs == 2 && Ops.size() == 2 &&
12392 "Invalid STRICT_FP_EXTEND!");
12393 assert(VTList.VTs[0].isFloatingPoint() &&
12394 Ops[1].getValueType().isFloatingPoint() && "Invalid FP cast!");
12395 assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
12396 "STRICT_FP_EXTEND result type should be vector iff the operand "
12397 "type is vector!");
12398 assert((!VTList.VTs[0].isVector() ||
12399 VTList.VTs[0].getVectorElementCount() ==
12400 Ops[1].getValueType().getVectorElementCount()) &&
12401 "Vector element count mismatch!");
12402 assert(Ops[1].getValueType().bitsLT(VTList.VTs[0]) &&
12403 "Invalid fpext node, dst <= src!");
12404 break;
12406 assert(VTList.NumVTs == 2 && Ops.size() == 3 && "Invalid STRICT_FP_ROUND!");
12407 assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
12408 "STRICT_FP_ROUND result type should be vector iff the operand "
12409 "type is vector!");
12410 assert((!VTList.VTs[0].isVector() ||
12411 VTList.VTs[0].getVectorElementCount() ==
12412 Ops[1].getValueType().getVectorElementCount()) &&
12413 "Vector element count mismatch!");
12414 assert(VTList.VTs[0].isFloatingPoint() &&
12415 Ops[1].getValueType().isFloatingPoint() &&
12416 VTList.VTs[0].bitsLT(Ops[1].getValueType()) &&
12417 Ops[2].getOpcode() == ISD::TargetConstant &&
12418 (Ops[2]->getAsZExtVal() == 0 || Ops[2]->getAsZExtVal() == 1) &&
12419 "Invalid STRICT_FP_ROUND!");
12420 break;
12421 }
12422
12423 // Memoize the node unless it returns a glue result.
12424 SDNode *N;
12425 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
12426 SDNodeKey ID(Opcode, VTList, Ops);
12427 FoldingSetInsertToken InsertToken;
12428 if (SDNode *E = lookupNode(ID, DL, InsertToken)) {
12429 E->intersectFlagsWith(Flags);
12430 return SDValue(E, 0);
12431 }
12432
12433 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
12434 createOperands(N, Ops);
12435 CSEMap.insert(N, InsertToken);
12436 } else {
12437 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
12438 createOperands(N, Ops);
12439 }
12440
12441 N->setFlags(Flags);
12442 InsertNode(N);
12443 SDValue V(N, 0);
12444 NewSDValueDbgMsg(V, "Creating new node: ", this);
12445 return V;
12446}
12447
12448SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
12449 SDVTList VTList) {
12450 return getNode(Opcode, DL, VTList, ArrayRef<SDValue>());
12451}
12452
12453SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
12454 SDValue N1) {
12455 SDValue Ops[] = { N1 };
12456 return getNode(Opcode, DL, VTList, Ops);
12457}
12458
12459SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
12460 SDValue N1, SDValue N2) {
12461 SDValue Ops[] = { N1, N2 };
12462 return getNode(Opcode, DL, VTList, Ops);
12463}
12464
12465SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
12466 SDValue N1, SDValue N2, SDValue N3) {
12467 SDValue Ops[] = { N1, N2, N3 };
12468 return getNode(Opcode, DL, VTList, Ops);
12469}
12470
12471SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
12472 SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
12473 SDValue Ops[] = { N1, N2, N3, N4 };
12474 return getNode(Opcode, DL, VTList, Ops);
12475}
12476
12477SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
12478 SDValue N1, SDValue N2, SDValue N3, SDValue N4,
12479 SDValue N5) {
12480 SDValue Ops[] = { N1, N2, N3, N4, N5 };
12481 return getNode(Opcode, DL, VTList, Ops);
12482}
12483
12485 if (!VT.isExtended())
12486 return makeVTList(SDNode::getValueTypeList(VT.getSimpleVT()), 1);
12487
12488 EVT VTs[] = {VT};
12489 return getVTList(VTs);
12490}
12491
12493 EVT VTs[] = {VT1, VT2};
12494 return getVTList(VTs);
12495}
12496
12498 EVT VTs[] = {VT1, VT2, VT3};
12499 return getVTList(VTs);
12500}
12501
12503 EVT VTs[] = {VT1, VT2, VT3, VT4};
12504 return getVTList(VTs);
12505}
12506
12508 auto It = VTLists.find(VTs);
12509 if (It == VTLists.end()) {
12510 EVT *Array = Allocator.Allocate<EVT>(VTs.size());
12511 llvm::copy(VTs, Array);
12512 It = VTLists.insert(ArrayRef(Array, VTs.size())).first;
12513 }
12514 return makeVTList(It->data(), It->size());
12515}
12516
12517/// UpdateNodeOperands - *Mutate* the specified node in-place to have the
12518/// specified operands. If the resultant node already exists in the DAG,
12519/// this does not modify the specified node, instead it returns the node that
12520/// already exists. If the resultant node does not exist in the DAG, the
12521/// input node is returned. As a degenerate case, if you specify the same
12522/// input operands as the node already has, the input node is returned.
12524 assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
12525
12526 // Check to see if there is no change.
12527 if (Op == N->getOperand(0)) return N;
12528
12529 // See if the modified node already exists.
12530 FoldingSetInsertToken InsertToken;
12531 if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertToken)) {
12532 Existing->intersectFlagsWith(N->getFlags());
12533 return Existing;
12534 }
12535
12536 // Nope it doesn't. Remove the node from its current place in the maps.
12537 if (InsertToken)
12538 if (!RemoveNodeFromCSEMaps(N))
12539 InsertToken = {};
12540
12541 // Now we update the operands.
12542 N->OperandList[0].set(Op);
12543
12545 // If this gets put into a CSE map, add it.
12546 if (InsertToken)
12547 CSEMap.insert(N, InsertToken);
12548 return N;
12549}
12550
12552 assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
12553
12554 // Check to see if there is no change.
12555 if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
12556 return N; // No operands changed, just return the input node.
12557
12558 // See if the modified node already exists.
12559 FoldingSetInsertToken InsertToken;
12560 if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertToken)) {
12561 Existing->intersectFlagsWith(N->getFlags());
12562 return Existing;
12563 }
12564
12565 // Nope it doesn't. Remove the node from its current place in the maps.
12566 if (InsertToken)
12567 if (!RemoveNodeFromCSEMaps(N))
12568 InsertToken = {};
12569
12570 // Now we update the operands.
12571 if (N->OperandList[0] != Op1)
12572 N->OperandList[0].set(Op1);
12573 if (N->OperandList[1] != Op2)
12574 N->OperandList[1].set(Op2);
12575
12577 // If this gets put into a CSE map, add it.
12578 if (InsertToken)
12579 CSEMap.insert(N, InsertToken);
12580 return N;
12581}
12582
12585 SDValue Ops[] = { Op1, Op2, Op3 };
12586 return UpdateNodeOperands(N, Ops);
12587}
12588
12591 SDValue Op3, SDValue Op4) {
12592 SDValue Ops[] = { Op1, Op2, Op3, Op4 };
12593 return UpdateNodeOperands(N, Ops);
12594}
12595
12598 SDValue Op3, SDValue Op4, SDValue Op5) {
12599 SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 };
12600 return UpdateNodeOperands(N, Ops);
12601}
12602
12605 unsigned NumOps = Ops.size();
12606 assert(N->getNumOperands() == NumOps &&
12607 "Update with wrong number of operands");
12608
12609 // If no operands changed just return the input node.
12610 if (std::equal(Ops.begin(), Ops.end(), N->op_begin()))
12611 return N;
12612
12613 // See if the modified node already exists.
12614 FoldingSetInsertToken InsertToken;
12615 if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertToken)) {
12616 Existing->intersectFlagsWith(N->getFlags());
12617 return Existing;
12618 }
12619
12620 // Nope it doesn't. Remove the node from its current place in the maps.
12621 if (InsertToken)
12622 if (!RemoveNodeFromCSEMaps(N))
12623 InsertToken = {};
12624
12625 // Now we update the operands.
12626 for (unsigned i = 0; i != NumOps; ++i)
12627 if (N->OperandList[i] != Ops[i])
12628 N->OperandList[i].set(Ops[i]);
12629
12631 // If this gets put into a CSE map, add it.
12632 if (InsertToken)
12633 CSEMap.insert(N, InsertToken);
12634 return N;
12635}
12636
12637/// DropOperands - Release the operands and set this node to have
12638/// zero operands.
12640 // Unlike the code in MorphNodeTo that does this, we don't need to
12641 // watch for dead nodes here.
12642 for (op_iterator I = op_begin(), E = op_end(); I != E; ) {
12643 SDUse &Use = *I++;
12644 Use.set(SDValue());
12645 }
12646}
12647
12649 ArrayRef<MachineMemOperand *> NewMemRefs) {
12650 if (NewMemRefs.empty()) {
12651 N->clearMemRefs();
12652 return;
12653 }
12654
12655 // Check if we can avoid allocating by storing a single reference directly.
12656 if (NewMemRefs.size() == 1) {
12657 N->MemRefs = NewMemRefs[0];
12658 N->NumMemRefs = 1;
12659 return;
12660 }
12661
12662 MachineMemOperand **MemRefsBuffer =
12663 Allocator.template Allocate<MachineMemOperand *>(NewMemRefs.size());
12664 llvm::copy(NewMemRefs, MemRefsBuffer);
12665 N->MemRefs = MemRefsBuffer;
12666 N->NumMemRefs = static_cast<int>(NewMemRefs.size());
12667}
12668
12669/// SelectNodeTo - These are wrappers around MorphNodeTo that accept a
12670/// machine opcode.
12671///
12673 EVT VT) {
12674 SDVTList VTs = getVTList(VT);
12675 return SelectNodeTo(N, MachineOpc, VTs, {});
12676}
12677
12679 EVT VT, SDValue Op1) {
12680 SDVTList VTs = getVTList(VT);
12681 SDValue Ops[] = { Op1 };
12682 return SelectNodeTo(N, MachineOpc, VTs, Ops);
12683}
12684
12686 EVT VT, SDValue Op1,
12687 SDValue Op2) {
12688 SDVTList VTs = getVTList(VT);
12689 SDValue Ops[] = { Op1, Op2 };
12690 return SelectNodeTo(N, MachineOpc, VTs, Ops);
12691}
12692
12694 EVT VT, SDValue Op1,
12695 SDValue Op2, SDValue Op3) {
12696 SDVTList VTs = getVTList(VT);
12697 SDValue Ops[] = { Op1, Op2, Op3 };
12698 return SelectNodeTo(N, MachineOpc, VTs, Ops);
12699}
12700
12703 SDVTList VTs = getVTList(VT);
12704 return SelectNodeTo(N, MachineOpc, VTs, Ops);
12705}
12706
12708 EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) {
12709 SDVTList VTs = getVTList(VT1, VT2);
12710 return SelectNodeTo(N, MachineOpc, VTs, Ops);
12711}
12712
12714 EVT VT1, EVT VT2) {
12715 SDVTList VTs = getVTList(VT1, VT2);
12716 return SelectNodeTo(N, MachineOpc, VTs, {});
12717}
12718
12720 EVT VT1, EVT VT2, EVT VT3,
12722 SDVTList VTs = getVTList(VT1, VT2, VT3);
12723 return SelectNodeTo(N, MachineOpc, VTs, Ops);
12724}
12725
12727 EVT VT1, EVT VT2,
12728 SDValue Op1, SDValue Op2) {
12729 SDVTList VTs = getVTList(VT1, VT2);
12730 SDValue Ops[] = { Op1, Op2 };
12731 return SelectNodeTo(N, MachineOpc, VTs, Ops);
12732}
12733
12736 SDNode *New = MorphNodeTo(N, ~MachineOpc, VTs, Ops);
12737 // Reset the NodeID to -1.
12738 New->setNodeId(-1);
12739 if (New != N) {
12740 ReplaceAllUsesWith(N, New);
12742 }
12743 return New;
12744}
12745
12746/// UpdateSDLocOnMergeSDNode - If the opt level is -O0 then it throws away
12747/// the line number information on the merged node since it is not possible to
12748/// preserve the information that operation is associated with multiple lines.
12749/// This will make the debugger work better at -O0, where there is a higher
12750/// probability of having other instructions associated with that line.
12751///
12752/// For IROrder, we keep the smaller of the two
12753SDNode *SelectionDAG::UpdateSDLocOnMergeSDNode(SDNode *N, const SDLoc &OLoc) {
12754 DebugLoc NLoc = N->getDebugLoc();
12755 if (NLoc && OptLevel == CodeGenOptLevel::None && OLoc.getDebugLoc() != NLoc) {
12756 N->setDebugLoc(DebugLoc());
12757 }
12758 unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder());
12759 N->setIROrder(Order);
12760 return N;
12761}
12762
12763/// MorphNodeTo - This *mutates* the specified node to have the specified
12764/// return type, opcode, and operands.
12765///
12766/// Note that MorphNodeTo returns the resultant node. If there is already a
12767/// node of the specified opcode and operands, it returns that node instead of
12768/// the current one. Note that the SDLoc need not be the same.
12769///
12770/// Using MorphNodeTo is faster than creating a new node and swapping it in
12771/// with ReplaceAllUsesWith both because it often avoids allocating a new
12772/// node, and because it doesn't require CSE recalculation for any of
12773/// the node's users.
12774///
12775/// However, note that MorphNodeTo recursively deletes dead nodes from the DAG.
12776/// As a consequence it isn't appropriate to use from within the DAG combiner or
12777/// the legalizer which maintain worklists that would need to be updated when
12778/// deleting things.
12781 // If an identical node already exists, use it.
12782 FoldingSetInsertToken InsertToken;
12783 if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) {
12784 SDNodeKey ID(Opc, VTs, Ops);
12785 AddNodeIDCustom(ID.Tail, N, Opc);
12786 if (SDNode *ON = lookupNode(ID, SDLoc(N), InsertToken))
12787 return UpdateSDLocOnMergeSDNode(ON, SDLoc(N));
12788 }
12789
12790 if (!RemoveNodeFromCSEMaps(N))
12791 InsertToken = {};
12792
12793 // Start the morphing.
12794 N->NodeType = Opc;
12795 N->ValueList = VTs.VTs;
12796 N->NumValues = VTs.NumVTs;
12797
12798 // Clear the operands list, updating used nodes to remove this from their
12799 // use list. Keep track of any operands that become dead as a result.
12800 SmallPtrSet<SDNode*, 16> DeadNodeSet;
12801 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
12802 SDUse &Use = *I++;
12803 SDNode *Used = Use.getNode();
12804 Use.set(SDValue());
12805 if (Used->use_empty())
12806 DeadNodeSet.insert(Used);
12807 }
12808
12809 // For MachineNode, initialize the memory references information.
12811 MN->clearMemRefs();
12812
12813 // Swap for an appropriately sized array from the recycler.
12814 removeOperands(N);
12815 createOperands(N, Ops);
12816
12817 // Delete any nodes that are still dead after adding the uses for the
12818 // new operands.
12819 if (!DeadNodeSet.empty()) {
12820 SmallVector<SDNode *, 16> DeadNodes;
12821 for (SDNode *N : DeadNodeSet)
12822 if (N->use_empty())
12823 DeadNodes.push_back(N);
12824 RemoveDeadNodes(DeadNodes);
12825 }
12826
12827 if (InsertToken)
12828 CSEMap.insert(N, InsertToken); // Memoize the new node.
12829 return N;
12830}
12831
12833 unsigned OrigOpc = Node->getOpcode();
12834 unsigned NewOpc;
12835 switch (OrigOpc) {
12836 default:
12837 llvm_unreachable("mutateStrictFPToFP called with unexpected opcode!");
12838#define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \
12839 case ISD::STRICT_##DAGN: NewOpc = ISD::DAGN; break;
12840#define CMP_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \
12841 case ISD::STRICT_##DAGN: NewOpc = ISD::SETCC; break;
12842#include "llvm/IR/ConstrainedOps.def"
12843 }
12844
12845 assert(Node->getNumValues() == 2 && "Unexpected number of results!");
12846
12847 // We're taking this node out of the chain, so we need to re-link things.
12848 SDValue InputChain = Node->getOperand(0);
12849 SDValue OutputChain = SDValue(Node, 1);
12850 ReplaceAllUsesOfValueWith(OutputChain, InputChain);
12851
12853 for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
12854 Ops.push_back(Node->getOperand(i));
12855
12856 SDVTList VTs = getVTList(Node->getValueType(0));
12857 SDNode *Res = MorphNodeTo(Node, NewOpc, VTs, Ops);
12858
12859 // MorphNodeTo can operate in two ways: if an existing node with the
12860 // specified operands exists, it can just return it. Otherwise, it
12861 // updates the node in place to have the requested operands.
12862 if (Res == Node) {
12863 // If we updated the node in place, reset the node ID. To the isel,
12864 // this should be just like a newly allocated machine node.
12865 Res->setNodeId(-1);
12866 } else {
12869 }
12870
12871 return Res;
12872}
12873
12874/// getMachineNode - These are used for target selectors to create a new node
12875/// with specified return type(s), MachineInstr opcode, and operands.
12876///
12877/// Note that getMachineNode returns the resultant node. If there is already a
12878/// node of the specified opcode and operands, it returns that node instead of
12879/// the current one.
12881 EVT VT) {
12882 SDVTList VTs = getVTList(VT);
12883 return getMachineNode(Opcode, dl, VTs, {});
12884}
12885
12887 EVT VT, SDValue Op1) {
12888 SDVTList VTs = getVTList(VT);
12889 SDValue Ops[] = { Op1 };
12890 return getMachineNode(Opcode, dl, VTs, Ops);
12891}
12892
12894 EVT VT, SDValue Op1, SDValue Op2) {
12895 SDVTList VTs = getVTList(VT);
12896 SDValue Ops[] = { Op1, Op2 };
12897 return getMachineNode(Opcode, dl, VTs, Ops);
12898}
12899
12901 EVT VT, SDValue Op1, SDValue Op2,
12902 SDValue Op3) {
12903 SDVTList VTs = getVTList(VT);
12904 SDValue Ops[] = { Op1, Op2, Op3 };
12905 return getMachineNode(Opcode, dl, VTs, Ops);
12906}
12907
12910 SDVTList VTs = getVTList(VT);
12911 return getMachineNode(Opcode, dl, VTs, Ops);
12912}
12913
12915 EVT VT1, EVT VT2, SDValue Op1,
12916 SDValue Op2) {
12917 SDVTList VTs = getVTList(VT1, VT2);
12918 SDValue Ops[] = { Op1, Op2 };
12919 return getMachineNode(Opcode, dl, VTs, Ops);
12920}
12921
12923 EVT VT1, EVT VT2, SDValue Op1,
12924 SDValue Op2, SDValue Op3) {
12925 SDVTList VTs = getVTList(VT1, VT2);
12926 SDValue Ops[] = { Op1, Op2, Op3 };
12927 return getMachineNode(Opcode, dl, VTs, Ops);
12928}
12929
12931 EVT VT1, EVT VT2,
12933 SDVTList VTs = getVTList(VT1, VT2);
12934 return getMachineNode(Opcode, dl, VTs, Ops);
12935}
12936
12938 EVT VT1, EVT VT2, EVT VT3,
12939 SDValue Op1, SDValue Op2) {
12940 SDVTList VTs = getVTList(VT1, VT2, VT3);
12941 SDValue Ops[] = { Op1, Op2 };
12942 return getMachineNode(Opcode, dl, VTs, Ops);
12943}
12944
12946 EVT VT1, EVT VT2, EVT VT3,
12947 SDValue Op1, SDValue Op2,
12948 SDValue Op3) {
12949 SDVTList VTs = getVTList(VT1, VT2, VT3);
12950 SDValue Ops[] = { Op1, Op2, Op3 };
12951 return getMachineNode(Opcode, dl, VTs, Ops);
12952}
12953
12955 EVT VT1, EVT VT2, EVT VT3,
12957 SDVTList VTs = getVTList(VT1, VT2, VT3);
12958 return getMachineNode(Opcode, dl, VTs, Ops);
12959}
12960
12962 ArrayRef<EVT> ResultTys,
12964 SDVTList VTs = getVTList(ResultTys);
12965 return getMachineNode(Opcode, dl, VTs, Ops);
12966}
12967
12969 SDVTList VTs,
12971 bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue;
12973 FoldingSetInsertToken InsertToken;
12974
12975 if (DoCSE) {
12976 SDNodeKey ID(~Opcode, VTs, Ops);
12977 if (SDNode *E = lookupNode(ID, DL, InsertToken)) {
12978 return cast<MachineSDNode>(UpdateSDLocOnMergeSDNode(E, DL));
12979 }
12980 }
12981
12982 // Allocate a new MachineSDNode.
12983 N = newSDNode<MachineSDNode>(~Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
12984 createOperands(N, Ops);
12985
12986 if (DoCSE)
12987 CSEMap.insert(N, InsertToken);
12988
12989 InsertNode(N);
12990 NewSDValueDbgMsg(SDValue(N, 0), "Creating new machine node: ", this);
12991 return N;
12992}
12993
12994/// getTargetExtractSubreg - A convenience function for creating
12995/// TargetOpcode::EXTRACT_SUBREG nodes.
12997 SDValue Operand) {
12998 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
12999 SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,
13000 VT, Operand, SRIdxVal);
13001 return SDValue(Subreg, 0);
13002}
13003
13004/// getTargetInsertSubreg - A convenience function for creating
13005/// TargetOpcode::INSERT_SUBREG nodes.
13007 SDValue Operand, SDValue Subreg) {
13008 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
13009 SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL,
13010 VT, Operand, Subreg, SRIdxVal);
13011 return SDValue(Result, 0);
13012}
13013
13014/// getNodeIfExists - Get the specified node if it's already available, or
13015/// else return NULL.
13018 bool AllowCommute) {
13019 SDNodeFlags Flags;
13020 if (Inserter)
13021 Flags = Inserter->getFlags();
13022 return getNodeIfExists(Opcode, VTList, Ops, Flags, AllowCommute);
13023}
13024
13027 const SDNodeFlags Flags,
13028 bool AllowCommute) {
13029 if (VTList.VTs[VTList.NumVTs - 1] == MVT::Glue)
13030 return nullptr;
13031
13032 auto Lookup = [&](ArrayRef<SDValue> LookupOps) -> SDNode * {
13033 SDNodeKey ID(Opcode, VTList, LookupOps);
13034 FoldingSetInsertToken InsertToken;
13035 if (SDNode *E = lookupNode(ID, InsertToken)) {
13036 E->intersectFlagsWith(Flags);
13037 return E;
13038 }
13039 return nullptr;
13040 };
13041
13042 if (SDNode *Existing = Lookup(Ops))
13043 return Existing;
13044
13045 if (AllowCommute && TLI->isCommutativeBinOp(Opcode))
13046 return Lookup({Ops[1], Ops[0]});
13047
13048 return nullptr;
13049}
13050
13051/// doesNodeExist - Check if a node exists without modifying its flags.
13052bool SelectionDAG::doesNodeExist(unsigned Opcode, SDVTList VTList,
13054 if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
13055 SDNodeKey ID(Opcode, VTList, Ops);
13056 FoldingSetInsertToken InsertToken;
13057 if (lookupNode(ID, SDLoc(), InsertToken))
13058 return true;
13059 }
13060 return false;
13061}
13062
13063/// getDbgValue - Creates a SDDbgValue node.
13064///
13065/// SDNode
13067 SDNode *N, unsigned R, bool IsIndirect,
13068 const DebugLoc &DL, unsigned O) {
13069 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
13070 "Expected inlined-at fields to agree");
13071 return new (DbgInfo->getAlloc())
13072 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromNode(N, R),
13073 {}, IsIndirect, DL, O,
13074 /*IsVariadic=*/false);
13075}
13076
13077/// Constant
13079 DIExpression *Expr,
13080 const Value *C,
13081 const DebugLoc &DL, unsigned O) {
13082 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
13083 "Expected inlined-at fields to agree");
13084 return new (DbgInfo->getAlloc())
13085 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromConst(C), {},
13086 /*IsIndirect=*/false, DL, O,
13087 /*IsVariadic=*/false);
13088}
13089
13090/// FrameIndex
13092 DIExpression *Expr, unsigned FI,
13093 bool IsIndirect,
13094 const DebugLoc &DL,
13095 unsigned O) {
13096 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
13097 "Expected inlined-at fields to agree");
13098 return getFrameIndexDbgValue(Var, Expr, FI, {}, IsIndirect, DL, O);
13099}
13100
13101/// FrameIndex with dependencies
13103 DIExpression *Expr, unsigned FI,
13104 ArrayRef<SDNode *> Dependencies,
13105 bool IsIndirect,
13106 const DebugLoc &DL,
13107 unsigned O) {
13108 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
13109 "Expected inlined-at fields to agree");
13110 return new (DbgInfo->getAlloc())
13111 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromFrameIdx(FI),
13112 Dependencies, IsIndirect, DL, O,
13113 /*IsVariadic=*/false);
13114}
13115
13116/// VReg
13118 Register VReg, bool IsIndirect,
13119 const DebugLoc &DL, unsigned O) {
13120 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
13121 "Expected inlined-at fields to agree");
13122 return new (DbgInfo->getAlloc())
13123 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromVReg(VReg),
13124 {}, IsIndirect, DL, O,
13125 /*IsVariadic=*/false);
13126}
13127
13130 ArrayRef<SDNode *> Dependencies,
13131 bool IsIndirect, const DebugLoc &DL,
13132 unsigned O, bool IsVariadic) {
13133 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
13134 "Expected inlined-at fields to agree");
13135 return new (DbgInfo->getAlloc())
13136 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, Locs, Dependencies, IsIndirect,
13137 DL, O, IsVariadic);
13138}
13139
13141 unsigned OffsetInBits, unsigned SizeInBits,
13142 bool InvalidateDbg) {
13143 SDNode *FromNode = From.getNode();
13144 SDNode *ToNode = To.getNode();
13145 assert(FromNode && ToNode && "Can't modify dbg values");
13146
13147 // PR35338
13148 // TODO: assert(From != To && "Redundant dbg value transfer");
13149 // TODO: assert(FromNode != ToNode && "Intranode dbg value transfer");
13150 if (From == To || FromNode == ToNode)
13151 return;
13152
13153 if (!FromNode->getHasDebugValue())
13154 return;
13155
13156 SDDbgOperand FromLocOp =
13157 SDDbgOperand::fromNode(From.getNode(), From.getResNo());
13159
13161 for (SDDbgValue *Dbg : GetDbgValues(FromNode)) {
13162 if (Dbg->isInvalidated())
13163 continue;
13164
13165 // TODO: assert(!Dbg->isInvalidated() && "Transfer of invalid dbg value");
13166
13167 // Create a new location ops vector that is equal to the old vector, but
13168 // with each instance of FromLocOp replaced with ToLocOp.
13169 bool Changed = false;
13170 auto NewLocOps = Dbg->copyLocationOps();
13171 std::replace_if(
13172 NewLocOps.begin(), NewLocOps.end(),
13173 [&Changed, FromLocOp](const SDDbgOperand &Op) {
13174 bool Match = Op == FromLocOp;
13175 Changed |= Match;
13176 return Match;
13177 },
13178 ToLocOp);
13179 // Ignore this SDDbgValue if we didn't find a matching location.
13180 if (!Changed)
13181 continue;
13182
13183 DIVariable *Var = Dbg->getVariable();
13184 auto *Expr = Dbg->getExpression();
13185 // If a fragment is requested, update the expression.
13186 if (SizeInBits) {
13187 // When splitting a larger (e.g., sign-extended) value whose
13188 // lower bits are described with an SDDbgValue, do not attempt
13189 // to transfer the SDDbgValue to the upper bits.
13190 if (auto FI = Expr->getFragmentInfo())
13191 if (OffsetInBits + SizeInBits > FI->SizeInBits)
13192 continue;
13193 auto Fragment = DIExpression::createFragmentExpression(Expr, OffsetInBits,
13194 SizeInBits);
13195 if (!Fragment)
13196 continue;
13197 Expr = *Fragment;
13198 }
13199
13200 auto AdditionalDependencies = Dbg->getAdditionalDependencies();
13201 // Clone the SDDbgValue and move it to To.
13202 SDDbgValue *Clone = getDbgValueList(
13203 Var, Expr, NewLocOps, AdditionalDependencies, Dbg->isIndirect(),
13204 Dbg->getDebugLoc(), std::max(ToNode->getIROrder(), Dbg->getOrder()),
13205 Dbg->isVariadic());
13206 ClonedDVs.push_back(Clone);
13207
13208 if (InvalidateDbg) {
13209 // Invalidate value and indicate the SDDbgValue should not be emitted.
13210 Dbg->setIsInvalidated();
13211 Dbg->setIsEmitted();
13212 }
13213 }
13214
13215 for (SDDbgValue *Dbg : ClonedDVs) {
13216 assert(is_contained(Dbg->getSDNodes(), ToNode) &&
13217 "Transferred DbgValues should depend on the new SDNode");
13218 AddDbgValue(Dbg, false);
13219 }
13220}
13221
13223 if (!N.getHasDebugValue())
13224 return;
13225
13226 auto GetLocationOperand = [](SDNode *Node, unsigned ResNo) {
13227 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(Node))
13228 return SDDbgOperand::fromFrameIdx(FISDN->getIndex());
13229 return SDDbgOperand::fromNode(Node, ResNo);
13230 };
13231
13233 for (auto *DV : GetDbgValues(&N)) {
13234 if (DV->isInvalidated())
13235 continue;
13236 switch (N.getOpcode()) {
13237 default:
13238 break;
13239 case ISD::ADD: {
13240 SDValue N0 = N.getOperand(0);
13241 SDValue N1 = N.getOperand(1);
13242 if (!isa<ConstantSDNode>(N0)) {
13243 bool RHSConstant = isa<ConstantSDNode>(N1);
13244 uint64_t Offset;
13245 if (RHSConstant)
13246 Offset = N.getConstantOperandVal(1);
13247 // We are not allowed to turn indirect debug values variadic, so
13248 // don't salvage those.
13249 if (!RHSConstant && DV->isIndirect())
13250 continue;
13251
13252 // Rewrite an ADD constant node into a DIExpression. Since we are
13253 // performing arithmetic to compute the variable's *value* in the
13254 // DIExpression, we need to mark the expression with a
13255 // DW_OP_stack_value.
13256 auto *DIExpr = DV->getExpression();
13257 auto NewLocOps = DV->copyLocationOps();
13258 bool Changed = false;
13259 size_t OrigLocOpsSize = NewLocOps.size();
13260 for (size_t i = 0; i < OrigLocOpsSize; ++i) {
13261 // We're not given a ResNo to compare against because the whole
13262 // node is going away. We know that any ISD::ADD only has one
13263 // result, so we can assume any node match is using the result.
13264 if (NewLocOps[i].getKind() != SDDbgOperand::SDNODE ||
13265 NewLocOps[i].getSDNode() != &N)
13266 continue;
13267 NewLocOps[i] = GetLocationOperand(N0.getNode(), N0.getResNo());
13268 if (RHSConstant) {
13271 DIExpr = DIExpression::appendOpsToArg(DIExpr, ExprOps, i, true);
13272 } else {
13273 // Convert to a variadic expression (if not already).
13274 // convertToVariadicExpression() returns a const pointer, so we use
13275 // a temporary const variable here.
13276 const auto *TmpDIExpr =
13280 ExprOps.push_back(NewLocOps.size());
13281 ExprOps.push_back(dwarf::DW_OP_plus);
13282 SDDbgOperand RHS =
13284 NewLocOps.push_back(RHS);
13285 DIExpr = DIExpression::appendOpsToArg(TmpDIExpr, ExprOps, i, true);
13286 }
13287 Changed = true;
13288 }
13289 (void)Changed;
13290 assert(Changed && "Salvage target doesn't use N");
13291
13292 bool IsVariadic =
13293 DV->isVariadic() || OrigLocOpsSize != NewLocOps.size();
13294
13295 auto AdditionalDependencies = DV->getAdditionalDependencies();
13296 SDDbgValue *Clone = getDbgValueList(
13297 DV->getVariable(), DIExpr, NewLocOps, AdditionalDependencies,
13298 DV->isIndirect(), DV->getDebugLoc(), DV->getOrder(), IsVariadic);
13299 ClonedDVs.push_back(Clone);
13300 DV->setIsInvalidated();
13301 DV->setIsEmitted();
13302 LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting";
13303 N0.getNode()->dumprFull(this);
13304 dbgs() << " into " << *DIExpr << '\n');
13305 }
13306 break;
13307 }
13308 case ISD::TRUNCATE: {
13309 SDValue N0 = N.getOperand(0);
13310 TypeSize FromSize = N0.getValueSizeInBits();
13311 TypeSize ToSize = N.getValueSizeInBits(0);
13312
13313 DIExpression *DbgExpression = DV->getExpression();
13314 auto ExtOps = DIExpression::getExtOps(FromSize, ToSize, false);
13315 auto NewLocOps = DV->copyLocationOps();
13316 bool Changed = false;
13317 for (size_t i = 0; i < NewLocOps.size(); ++i) {
13318 if (NewLocOps[i].getKind() != SDDbgOperand::SDNODE ||
13319 NewLocOps[i].getSDNode() != &N)
13320 continue;
13321
13322 NewLocOps[i] = GetLocationOperand(N0.getNode(), N0.getResNo());
13323 DbgExpression = DIExpression::appendOpsToArg(DbgExpression, ExtOps, i);
13324 Changed = true;
13325 }
13326 assert(Changed && "Salvage target doesn't use N");
13327 (void)Changed;
13328
13329 SDDbgValue *Clone =
13330 getDbgValueList(DV->getVariable(), DbgExpression, NewLocOps,
13331 DV->getAdditionalDependencies(), DV->isIndirect(),
13332 DV->getDebugLoc(), DV->getOrder(), DV->isVariadic());
13333
13334 ClonedDVs.push_back(Clone);
13335 DV->setIsInvalidated();
13336 DV->setIsEmitted();
13337 LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting"; N0.getNode()->dumprFull(this);
13338 dbgs() << " into " << *DbgExpression << '\n');
13339 break;
13340 }
13341 }
13342 }
13343
13344 for (SDDbgValue *Dbg : ClonedDVs) {
13345 assert((!Dbg->getSDNodes().empty() ||
13346 llvm::any_of(Dbg->getLocationOps(),
13347 [&](const SDDbgOperand &Op) {
13348 return Op.getKind() == SDDbgOperand::FRAMEIX;
13349 })) &&
13350 "Salvaged DbgValue should depend on a new SDNode");
13351 AddDbgValue(Dbg, false);
13352 }
13353}
13354
13355/// Creates a SDDbgLabel node.
13357 const DebugLoc &DL, unsigned O) {
13358 assert(cast<DILabel>(Label)->isValidLocationForIntrinsic(DL) &&
13359 "Expected inlined-at fields to agree");
13360 return new (DbgInfo->getAlloc()) SDDbgLabel(Label, DL, O);
13361}
13362
13363namespace {
13364
13365/// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node
13366/// pointed to by a use iterator is deleted, increment the use iterator
13367/// so that it doesn't dangle.
13368///
13369class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener {
13372
13373 void NodeDeleted(SDNode *N, SDNode *E) override {
13374 // Increment the iterator as needed.
13375 while (UI != UE && N == UI->getUser())
13376 ++UI;
13377 }
13378
13379public:
13380 RAUWUpdateListener(SelectionDAG &d,
13383 : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {}
13384};
13385
13386} // end anonymous namespace
13387
13388/// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
13389/// This can cause recursive merging of nodes in the DAG.
13390///
13391/// This version assumes From has a single result value.
13392///
13394 SDNode *From = FromN.getNode();
13395 assert(From->getNumValues() == 1 && FromN.getResNo() == 0 &&
13396 "Cannot replace with this method!");
13397 assert(From != To.getNode() && "Cannot replace uses of with self");
13398
13399 // Preserve Debug Values
13400 transferDbgValues(FromN, To);
13401 // Preserve extra info.
13402 copyExtraInfo(From, To.getNode());
13403
13404 // Iterate over all the existing uses of From. New uses will be added
13405 // to the beginning of the use list, which we avoid visiting.
13406 // This specifically avoids visiting uses of From that arise while the
13407 // replacement is happening, because any such uses would be the result
13408 // of CSE: If an existing node looks like From after one of its operands
13409 // is replaced by To, we don't want to replace of all its users with To
13410 // too. See PR3018 for more info.
13411 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
13412 RAUWUpdateListener Listener(*this, UI, UE);
13413 while (UI != UE) {
13414 SDNode *User = UI->getUser();
13415
13416 // This node is about to morph, remove its old self from the CSE maps.
13417 RemoveNodeFromCSEMaps(User);
13418
13419 // A user can appear in a use list multiple times, and when this
13420 // happens the uses are usually next to each other in the list.
13421 // To help reduce the number of CSE recomputations, process all
13422 // the uses of this user that we can find this way.
13423 do {
13424 SDUse &Use = *UI;
13425 ++UI;
13426 Use.set(To);
13427 if (To->isDivergent() != From->isDivergent())
13429 } while (UI != UE && UI->getUser() == User);
13430 // Now that we have modified User, add it back to the CSE maps. If it
13431 // already exists there, recursively merge the results together.
13432 AddModifiedNodeToCSEMaps(User);
13433 }
13434
13435 // If we just RAUW'd the root, take note.
13436 if (FromN == getRoot())
13437 setRoot(To);
13438}
13439
13440/// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
13441/// This can cause recursive merging of nodes in the DAG.
13442///
13443/// This version assumes that for each value of From, there is a
13444/// corresponding value in To in the same position with the same type.
13445///
13447#ifndef NDEBUG
13448 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
13449 assert((!From->hasAnyUseOfValue(i) ||
13450 From->getValueType(i) == To->getValueType(i)) &&
13451 "Cannot use this version of ReplaceAllUsesWith!");
13452#endif
13453
13454 // Handle the trivial case.
13455 if (From == To)
13456 return;
13457
13458 // Preserve Debug Info. Only do this if there's a use.
13459 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
13460 if (From->hasAnyUseOfValue(i)) {
13461 assert((i < To->getNumValues()) && "Invalid To location");
13462 transferDbgValues(SDValue(From, i), SDValue(To, i));
13463 }
13464 // Preserve extra info.
13465 copyExtraInfo(From, To);
13466
13467 // Iterate over just the existing users of From. See the comments in
13468 // the ReplaceAllUsesWith above.
13469 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
13470 RAUWUpdateListener Listener(*this, UI, UE);
13471 while (UI != UE) {
13472 SDNode *User = UI->getUser();
13473
13474 // This node is about to morph, remove its old self from the CSE maps.
13475 RemoveNodeFromCSEMaps(User);
13476
13477 // A user can appear in a use list multiple times, and when this
13478 // happens the uses are usually next to each other in the list.
13479 // To help reduce the number of CSE recomputations, process all
13480 // the uses of this user that we can find this way.
13481 do {
13482 SDUse &Use = *UI;
13483 ++UI;
13484 Use.setNode(To);
13485 if (To->isDivergent() != From->isDivergent())
13487 } while (UI != UE && UI->getUser() == User);
13488
13489 // Now that we have modified User, add it back to the CSE maps. If it
13490 // already exists there, recursively merge the results together.
13491 AddModifiedNodeToCSEMaps(User);
13492 }
13493
13494 // If we just RAUW'd the root, take note.
13495 if (From == getRoot().getNode())
13496 setRoot(SDValue(To, getRoot().getResNo()));
13497}
13498
13499/// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
13500/// This can cause recursive merging of nodes in the DAG.
13501///
13502/// This version can replace From with any result values. To must match the
13503/// number and types of values returned by From.
13505 if (From->getNumValues() == 1) // Handle the simple case efficiently.
13506 return ReplaceAllUsesWith(SDValue(From, 0), To[0]);
13507
13508 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) {
13509 // Preserve Debug Info.
13510 transferDbgValues(SDValue(From, i), To[i]);
13511 // Preserve extra info.
13512 copyExtraInfo(From, To[i].getNode());
13513 }
13514
13515 // Iterate over just the existing users of From. See the comments in
13516 // the ReplaceAllUsesWith above.
13517 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
13518 RAUWUpdateListener Listener(*this, UI, UE);
13519 while (UI != UE) {
13520 SDNode *User = UI->getUser();
13521
13522 // This node is about to morph, remove its old self from the CSE maps.
13523 RemoveNodeFromCSEMaps(User);
13524
13525 // A user can appear in a use list multiple times, and when this happens the
13526 // uses are usually next to each other in the list. To help reduce the
13527 // number of CSE and divergence recomputations, process all the uses of this
13528 // user that we can find this way.
13529 bool To_IsDivergent = false;
13530 do {
13531 SDUse &Use = *UI;
13532 const SDValue &ToOp = To[Use.getResNo()];
13533 ++UI;
13534 Use.set(ToOp);
13535 if (ToOp.getValueType() != MVT::Other)
13536 To_IsDivergent |= ToOp->isDivergent();
13537 } while (UI != UE && UI->getUser() == User);
13538
13539 if (To_IsDivergent != From->isDivergent())
13541
13542 // Now that we have modified User, add it back to the CSE maps. If it
13543 // already exists there, recursively merge the results together.
13544 AddModifiedNodeToCSEMaps(User);
13545 }
13546
13547 // If we just RAUW'd the root, take note.
13548 if (From == getRoot().getNode())
13549 setRoot(SDValue(To[getRoot().getResNo()]));
13550}
13551
13552/// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
13553/// uses of other values produced by From.getNode() alone. The Deleted
13554/// vector is handled the same way as for ReplaceAllUsesWith.
13556 // Handle the really simple, really trivial case efficiently.
13557 if (From == To) return;
13558
13559 // Handle the simple, trivial, case efficiently.
13560 if (From.getNode()->getNumValues() == 1) {
13561 ReplaceAllUsesWith(From, To);
13562 return;
13563 }
13564
13565 // Preserve Debug Info.
13566 transferDbgValues(From, To);
13567 copyExtraInfo(From.getNode(), To.getNode());
13568
13569 // Iterate over just the existing users of From. See the comments in
13570 // the ReplaceAllUsesWith above.
13571 SDNode::use_iterator UI = From.getNode()->use_begin(),
13572 UE = From.getNode()->use_end();
13573 RAUWUpdateListener Listener(*this, UI, UE);
13574 while (UI != UE) {
13575 SDNode *User = UI->getUser();
13576 bool UserRemovedFromCSEMaps = false;
13577
13578 // A user can appear in a use list multiple times, and when this
13579 // happens the uses are usually next to each other in the list.
13580 // To help reduce the number of CSE recomputations, process all
13581 // the uses of this user that we can find this way.
13582 do {
13583 SDUse &Use = *UI;
13584
13585 // Skip uses of different values from the same node.
13586 if (Use.getResNo() != From.getResNo()) {
13587 ++UI;
13588 continue;
13589 }
13590
13591 // If this node hasn't been modified yet, it's still in the CSE maps,
13592 // so remove its old self from the CSE maps.
13593 if (!UserRemovedFromCSEMaps) {
13594 RemoveNodeFromCSEMaps(User);
13595 UserRemovedFromCSEMaps = true;
13596 }
13597
13598 ++UI;
13599 Use.set(To);
13600 if (To->isDivergent() != From->isDivergent())
13602 } while (UI != UE && UI->getUser() == User);
13603 // We are iterating over all uses of the From node, so if a use
13604 // doesn't use the specific value, no changes are made.
13605 if (!UserRemovedFromCSEMaps)
13606 continue;
13607
13608 // Now that we have modified User, add it back to the CSE maps. If it
13609 // already exists there, recursively merge the results together.
13610 AddModifiedNodeToCSEMaps(User);
13611 }
13612
13613 // If we just RAUW'd the root, take note.
13614 if (From == getRoot())
13615 setRoot(To);
13616}
13617
13618namespace {
13619
13620/// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith
13621/// to record information about a use.
13622struct UseMemo {
13623 SDNode *User;
13624 unsigned Index;
13625 SDUse *Use;
13626};
13627
13628/// operator< - Sort Memos by User.
13629bool operator<(const UseMemo &L, const UseMemo &R) {
13630 return (intptr_t)L.User < (intptr_t)R.User;
13631}
13632
13633/// RAUOVWUpdateListener - Helper for ReplaceAllUsesOfValuesWith - When the node
13634/// pointed to by a UseMemo is deleted, set the User to nullptr to indicate that
13635/// the node already has been taken care of recursively.
13636class RAUOVWUpdateListener : public SelectionDAG::DAGUpdateListener {
13637 SmallVectorImpl<UseMemo> &Uses;
13638
13639 void NodeDeleted(SDNode *N, SDNode *E) override {
13640 for (UseMemo &Memo : Uses)
13641 if (Memo.User == N)
13642 Memo.User = nullptr;
13643 }
13644
13645public:
13646 RAUOVWUpdateListener(SelectionDAG &d, SmallVectorImpl<UseMemo> &uses)
13647 : SelectionDAG::DAGUpdateListener(d), Uses(uses) {}
13648};
13649
13650} // end anonymous namespace
13651
13652/// Return true if a glue output should propagate divergence information.
13654 switch (Node->getOpcode()) {
13655 case ISD::CopyFromReg:
13656 case ISD::CopyToReg:
13657 return false;
13658 default:
13659 return true;
13660 }
13661
13662 llvm_unreachable("covered opcode switch");
13663}
13664
13666 if (TLI->isSDNodeAlwaysUniform(N)) {
13667 assert(!TLI->isSDNodeSourceOfDivergence(N, FLI, UA) &&
13668 "Conflicting divergence information!");
13669 return false;
13670 }
13671 if (TLI->isSDNodeSourceOfDivergence(N, FLI, UA))
13672 return true;
13673 for (const auto &Op : N->ops()) {
13674 EVT VT = Op.getValueType();
13675
13676 // Skip Chain. It does not carry divergence.
13677 if (VT != MVT::Other && Op.getNode()->isDivergent() &&
13678 (VT != MVT::Glue || gluePropagatesDivergence(Op.getNode())))
13679 return true;
13680 }
13681 return false;
13682}
13683
13685 SmallVector<SDNode *, 16> Worklist(1, N);
13686 do {
13687 N = Worklist.pop_back_val();
13688 bool IsDivergent = calculateDivergence(N);
13689 if (N->SDNodeBits.IsDivergent != IsDivergent) {
13690 N->SDNodeBits.IsDivergent = IsDivergent;
13691 llvm::append_range(Worklist, N->users());
13692 }
13693 } while (!Worklist.empty());
13694}
13695
13696void SelectionDAG::CreateTopologicalOrder(std::vector<SDNode *> &Order) {
13698 Order.reserve(AllNodes.size());
13699 for (auto &N : allnodes()) {
13700 unsigned NOps = N.getNumOperands();
13701 Degree[&N] = NOps;
13702 if (0 == NOps)
13703 Order.push_back(&N);
13704 }
13705 for (size_t I = 0; I != Order.size(); ++I) {
13706 SDNode *N = Order[I];
13707 for (auto *U : N->users()) {
13708 unsigned &UnsortedOps = Degree[U];
13709 if (0 == --UnsortedOps)
13710 Order.push_back(U);
13711 }
13712 }
13713}
13714
13715#if !defined(NDEBUG) && LLVM_ENABLE_ABI_BREAKING_CHECKS
13716void SelectionDAG::VerifyDAGDivergence() {
13717 std::vector<SDNode *> TopoOrder;
13718 CreateTopologicalOrder(TopoOrder);
13719 for (auto *N : TopoOrder) {
13720 assert(calculateDivergence(N) == N->isDivergent() &&
13721 "Divergence bit inconsistency detected");
13722 }
13723}
13724#endif
13725
13726/// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving
13727/// uses of other values produced by From.getNode() alone. The same value
13728/// may appear in both the From and To list. The Deleted vector is
13729/// handled the same way as for ReplaceAllUsesWith.
13731 const SDValue *To,
13732 unsigned Num){
13733 // Handle the simple, trivial case efficiently.
13734 if (Num == 1)
13735 return ReplaceAllUsesOfValueWith(*From, *To);
13736
13737 transferDbgValues(*From, *To);
13738 copyExtraInfo(From->getNode(), To->getNode());
13739
13740 // Read up all the uses and make records of them. This helps
13741 // processing new uses that are introduced during the
13742 // replacement process.
13744 for (unsigned i = 0; i != Num; ++i) {
13745 unsigned FromResNo = From[i].getResNo();
13746 SDNode *FromNode = From[i].getNode();
13747 for (SDUse &Use : FromNode->uses()) {
13748 if (Use.getResNo() == FromResNo) {
13749 UseMemo Memo = {Use.getUser(), i, &Use};
13750 Uses.push_back(Memo);
13751 }
13752 }
13753 }
13754
13755 // Sort the uses, so that all the uses from a given User are together.
13757 RAUOVWUpdateListener Listener(*this, Uses);
13758
13759 for (unsigned UseIndex = 0, UseIndexEnd = Uses.size();
13760 UseIndex != UseIndexEnd; ) {
13761 // We know that this user uses some value of From. If it is the right
13762 // value, update it.
13763 SDNode *User = Uses[UseIndex].User;
13764 // If the node has been deleted by recursive CSE updates when updating
13765 // another node, then just skip this entry.
13766 if (User == nullptr) {
13767 ++UseIndex;
13768 continue;
13769 }
13770
13771 // This node is about to morph, remove its old self from the CSE maps.
13772 RemoveNodeFromCSEMaps(User);
13773
13774 // The Uses array is sorted, so all the uses for a given User
13775 // are next to each other in the list.
13776 // To help reduce the number of CSE recomputations, process all
13777 // the uses of this user that we can find this way.
13778 do {
13779 unsigned i = Uses[UseIndex].Index;
13780 SDUse &Use = *Uses[UseIndex].Use;
13781 ++UseIndex;
13782
13783 Use.set(To[i]);
13784 } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User);
13785
13786 // Now that we have modified User, add it back to the CSE maps. If it
13787 // already exists there, recursively merge the results together.
13788 AddModifiedNodeToCSEMaps(User);
13789 }
13790}
13791
13792/// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
13793/// based on their topological order. It returns the maximum id and a vector
13794/// of the SDNodes* in assigned order by reference.
13796 unsigned DAGSize = 0;
13797
13798 // SortedPos tracks the progress of the algorithm. Nodes before it are
13799 // sorted, nodes after it are unsorted. When the algorithm completes
13800 // it is at the end of the list.
13801 allnodes_iterator SortedPos = allnodes_begin();
13802
13803 // Visit all the nodes. Move nodes with no operands to the front of
13804 // the list immediately. Annotate nodes that do have operands with their
13805 // operand count. Before we do this, the Node Id fields of the nodes
13806 // may contain arbitrary values. After, the Node Id fields for nodes
13807 // before SortedPos will contain the topological sort index, and the
13808 // Node Id fields for nodes At SortedPos and after will contain the
13809 // count of outstanding operands.
13811 checkForCycles(&N, this);
13812 unsigned Degree = N.getNumOperands();
13813 if (Degree == 0) {
13814 // A node with no uses, add it to the result array immediately.
13815 N.setNodeId(DAGSize++);
13816 allnodes_iterator Q(&N);
13817 if (Q != SortedPos)
13818 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q));
13819 assert(SortedPos != AllNodes.end() && "Overran node list");
13820 ++SortedPos;
13821 } else {
13822 // Temporarily use the Node Id as scratch space for the degree count.
13823 N.setNodeId(Degree);
13824 }
13825 }
13826
13827 // Visit all the nodes. As we iterate, move nodes into sorted order,
13828 // such that by the time the end is reached all nodes will be sorted.
13829 for (SDNode &Node : allnodes()) {
13830 SDNode *N = &Node;
13831 checkForCycles(N, this);
13832 // N is in sorted position, so all its uses have one less operand
13833 // that needs to be sorted.
13834 for (SDNode *P : N->users()) {
13835 unsigned Degree = P->getNodeId();
13836 assert(Degree != 0 && "Invalid node degree");
13837 --Degree;
13838 if (Degree == 0) {
13839 // All of P's operands are sorted, so P may sorted now.
13840 P->setNodeId(DAGSize++);
13841 if (P->getIterator() != SortedPos)
13842 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P));
13843 assert(SortedPos != AllNodes.end() && "Overran node list");
13844 ++SortedPos;
13845 } else {
13846 // Update P's outstanding operand count.
13847 P->setNodeId(Degree);
13848 }
13849 }
13850 if (Node.getIterator() == SortedPos) {
13851#ifndef NDEBUG
13853 SDNode *S = &*++I;
13854 dbgs() << "Overran sorted position:\n";
13855 S->dumprFull(this); dbgs() << "\n";
13856 dbgs() << "Checking if this is due to cycles\n";
13857 checkForCycles(this, true);
13858#endif
13859 llvm_unreachable(nullptr);
13860 }
13861 }
13862
13863 assert(SortedPos == AllNodes.end() &&
13864 "Topological sort incomplete!");
13865 assert(AllNodes.front().getOpcode() == ISD::EntryToken &&
13866 "First node in topological sort is not the entry token!");
13867 assert(AllNodes.front().getNodeId() == 0 &&
13868 "First node in topological sort has non-zero id!");
13869 assert(AllNodes.front().getNumOperands() == 0 &&
13870 "First node in topological sort has operands!");
13871 assert(AllNodes.back().getNodeId() == (int)DAGSize-1 &&
13872 "Last node in topologic sort has unexpected id!");
13873 assert(AllNodes.back().use_empty() &&
13874 "Last node in topologic sort has users!");
13875 assert(DAGSize == allnodes_size() && "Node count mismatch!");
13876 return DAGSize;
13877}
13878
13880 SmallVectorImpl<const SDNode *> &SortedNodes) const {
13881 SortedNodes.clear();
13882 // Node -> remaining number of outstanding operands.
13883 DenseMap<const SDNode *, unsigned> RemainingOperands;
13884
13885 // Put nodes without any operands into SortedNodes first.
13886 for (const SDNode &N : allnodes()) {
13887 checkForCycles(&N, this);
13888 unsigned NumOperands = N.getNumOperands();
13889 if (NumOperands == 0)
13890 SortedNodes.push_back(&N);
13891 else
13892 // Record their total number of outstanding operands.
13893 RemainingOperands[&N] = NumOperands;
13894 }
13895
13896 // A node is pushed into SortedNodes when all of its operands (predecessors in
13897 // the graph) are also in SortedNodes.
13898 for (unsigned i = 0U; i < SortedNodes.size(); ++i) {
13899 const SDNode *N = SortedNodes[i];
13900 for (const SDNode *U : N->users()) {
13901 // HandleSDNode is never part of a DAG and therefore has no entry in
13902 // RemainingOperands.
13903 if (U->getOpcode() == ISD::HANDLENODE)
13904 continue;
13905 unsigned &NumRemOperands = RemainingOperands[U];
13906 assert(NumRemOperands && "Invalid number of remaining operands");
13907 --NumRemOperands;
13908 if (!NumRemOperands)
13909 SortedNodes.push_back(U);
13910 }
13911 }
13912
13913 assert(SortedNodes.size() == AllNodes.size() && "Node count mismatch");
13914 assert(SortedNodes.front()->getOpcode() == ISD::EntryToken &&
13915 "First node in topological sort is not the entry token");
13916 assert(SortedNodes.front()->getNumOperands() == 0 &&
13917 "First node in topological sort has operands");
13918}
13919
13920/// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the
13921/// value is produced by SD.
13922void SelectionDAG::AddDbgValue(SDDbgValue *DB, bool isParameter) {
13923 for (SDNode *SD : DB->getSDNodes()) {
13924 if (!SD)
13925 continue;
13926 assert(DbgInfo->getSDDbgValues(SD).empty() || SD->getHasDebugValue());
13927 SD->setHasDebugValue(true);
13928 }
13929 DbgInfo->add(DB, isParameter);
13930}
13931
13932void SelectionDAG::AddDbgLabel(SDDbgLabel *DB) { DbgInfo->add(DB); }
13933
13935 SDValue NewMemOpChain) {
13936 assert(isa<MemSDNode>(NewMemOpChain) && "Expected a memop node");
13937 assert(NewMemOpChain.getValueType() == MVT::Other && "Expected a token VT");
13938 // The new memory operation must have the same position as the old load in
13939 // terms of memory dependency. Create a TokenFactor for the old load and new
13940 // memory operation and update uses of the old load's output chain to use that
13941 // TokenFactor.
13942 if (OldChain == NewMemOpChain || OldChain.use_empty())
13943 return NewMemOpChain;
13944
13945 SDValue TokenFactor = getNode(ISD::TokenFactor, SDLoc(OldChain), MVT::Other,
13946 OldChain, NewMemOpChain);
13947 ReplaceAllUsesOfValueWith(OldChain, TokenFactor);
13948 UpdateNodeOperands(TokenFactor.getNode(), OldChain, NewMemOpChain);
13949 return TokenFactor;
13950}
13951
13953 SDValue NewMemOp) {
13954 assert(isa<MemSDNode>(NewMemOp.getNode()) && "Expected a memop node");
13955 SDValue OldChain = SDValue(OldLoad, 1);
13956 SDValue NewMemOpChain = NewMemOp.getValue(1);
13957 return makeEquivalentMemoryOrdering(OldChain, NewMemOpChain);
13958}
13959
13961 Function **OutFunction) {
13962 assert(isa<ExternalSymbolSDNode>(Op) && "Node should be an ExternalSymbol");
13963
13964 auto *Symbol = cast<ExternalSymbolSDNode>(Op)->getSymbol();
13965 auto *Module = MF->getFunction().getParent();
13966 auto *Function = Module->getFunction(Symbol);
13967
13968 if (OutFunction != nullptr)
13969 *OutFunction = Function;
13970
13971 if (Function != nullptr) {
13972 auto PtrTy = TLI->getPointerTy(getDataLayout(), Function->getAddressSpace());
13973 return getGlobalAddress(Function, SDLoc(Op), PtrTy);
13974 }
13975
13976 std::string ErrorStr;
13977 raw_string_ostream ErrorFormatter(ErrorStr);
13978 ErrorFormatter << "Undefined external symbol ";
13979 ErrorFormatter << '"' << Symbol << '"';
13980 report_fatal_error(Twine(ErrorStr));
13981}
13982
13983//===----------------------------------------------------------------------===//
13984// SDNode Class
13985//===----------------------------------------------------------------------===//
13986
13989 return Const != nullptr && Const->isZero();
13990}
13991
13993 return V.isUndef() || isNullConstant(V);
13994}
13995
13998 return Const != nullptr && Const->isZero() && !Const->isNegative();
13999}
14000
14003 return Const != nullptr && Const->isAllOnes();
14004}
14005
14008 return Const != nullptr && Const->isOne();
14009}
14010
14013 return Const != nullptr && Const->isMinSignedValue();
14014}
14015
14017 SDValue V, unsigned OperandNo,
14018 unsigned Depth) const {
14019 APInt DemandedElts = getDemandAllEltsMask(V);
14020 return isIdentityElement(Opcode, Flags, V, DemandedElts, OperandNo, Depth);
14021}
14022
14024 SDValue V, const APInt &DemandedElts,
14025 unsigned OperandNo, unsigned Depth) const {
14026 // NOTE: The cases should match with IR's ConstantExpr::getBinOpIdentity().
14027 // TODO: Target-specific opcodes could be added.
14028 if (V.getValueType().isInteger()) {
14029 KnownBits Known = computeKnownBits(V, DemandedElts, Depth);
14030 if (Known.isConstant()) {
14031 const APInt &Const = Known.getConstant();
14032 switch (Opcode) {
14033 case ISD::ADD:
14034 case ISD::OR:
14035 case ISD::XOR:
14036 case ISD::UMAX:
14037 return Const.isZero();
14038 case ISD::MUL:
14039 return Const.isOne();
14040 case ISD::AND:
14041 case ISD::UMIN:
14042 return Const.isAllOnes();
14043 case ISD::SMAX:
14044 return Const.isMinSignedValue();
14045 case ISD::SMIN:
14046 return Const.isMaxSignedValue();
14047 case ISD::SUB:
14048 case ISD::SHL:
14049 case ISD::SRA:
14050 case ISD::SRL:
14051 return OperandNo == 1 && Const.isZero();
14052 case ISD::UDIV:
14053 case ISD::SDIV:
14054 return OperandNo == 1 && Const.isOne();
14055 }
14056 }
14057 } else if (auto *ConstFP = isConstOrConstSplatFP(V, DemandedElts)) {
14058 switch (Opcode) {
14059 case ISD::FADD:
14060 return ConstFP->isZero() &&
14061 (Flags.hasNoSignedZeros() || ConstFP->isNegative());
14062 case ISD::FSUB:
14063 return OperandNo == 1 && ConstFP->isZero() &&
14064 (Flags.hasNoSignedZeros() || !ConstFP->isNegative());
14065 case ISD::FMUL:
14066 return ConstFP->isOne();
14067 case ISD::FDIV:
14068 return OperandNo == 1 && ConstFP->isOne();
14069 case ISD::FMINNUM:
14070 case ISD::FMAXNUM:
14071 case ISD::FMINIMUMNUM:
14072 case ISD::FMAXIMUMNUM: {
14073 // Neutral element for fminnum/fminimumnum is NaN, Inf or FLT_MAX,
14074 // depending on fast-math flags (FMF).
14075 EVT VT = V.getValueType();
14076 const fltSemantics &Semantics = VT.getFltSemantics();
14077 APFloat NeutralAF = !Flags.hasNoNaNs() ? APFloat::getQNaN(Semantics)
14078 : !Flags.hasNoInfs() ? APFloat::getInf(Semantics)
14079 : APFloat::getLargest(Semantics);
14080 if (Opcode == ISD::FMAXNUM || Opcode == ISD::FMAXIMUMNUM)
14081 NeutralAF.changeSign();
14082
14083 return ConstFP->isExactlyValue(NeutralAF);
14084 }
14085 case ISD::FMINIMUM:
14086 case ISD::FMAXIMUM: {
14087 // Neutral element for fminimum is Inf or FLT_MAX, depending on FMF.
14088 const APFloat &VAPF = ConstFP->getValueAPF();
14089 bool NeutralNegative = (Opcode == ISD::FMAXIMUM);
14090 if (Flags.hasNoInfs())
14091 return VAPF.isLargest() && VAPF.isNegative() == NeutralNegative;
14092 return VAPF.isInfinity() && VAPF.isNegative() == NeutralNegative;
14093 }
14094 }
14095 }
14096 return false;
14097}
14098
14100 while (V.getOpcode() == ISD::BITCAST)
14101 V = V.getOperand(0);
14102 return V;
14103}
14104
14106 while (V.getOpcode() == ISD::BITCAST && V.getOperand(0).hasOneUse())
14107 V = V.getOperand(0);
14108 return V;
14109}
14110
14112 while (V.getOpcode() == ISD::EXTRACT_SUBVECTOR)
14113 V = V.getOperand(0);
14114 return V;
14115}
14116
14118 while (V.getOpcode() == ISD::INSERT_VECTOR_ELT) {
14119 SDValue InVec = V.getOperand(0);
14120 SDValue EltNo = V.getOperand(2);
14121 EVT VT = InVec.getValueType();
14122 auto *IndexC = dyn_cast<ConstantSDNode>(EltNo);
14123 if (IndexC && VT.isFixedLengthVector() &&
14124 IndexC->getAPIntValue().ult(VT.getVectorNumElements()) &&
14125 !DemandedElts[IndexC->getZExtValue()]) {
14126 V = InVec;
14127 continue;
14128 }
14129 break;
14130 }
14131 return V;
14132}
14133
14135 while (V.getOpcode() == ISD::TRUNCATE)
14136 V = V.getOperand(0);
14137 return V;
14138}
14139
14140bool llvm::isBitwiseNot(SDValue V, bool AllowUndefs) {
14141 if (V.getOpcode() != ISD::XOR)
14142 return false;
14143 V = peekThroughBitcasts(V.getOperand(1));
14144 unsigned NumBits = V.getScalarValueSizeInBits();
14145 ConstantSDNode *C =
14146 isConstOrConstSplat(V, AllowUndefs, /*AllowTruncation*/ true);
14147 return C && (C->getAPIntValue().countr_one() >= NumBits);
14148}
14149
14151 bool AllowTruncation) {
14152 APInt DemandedElts = getDemandAllEltsMask(N);
14153 return isConstOrConstSplat(N, DemandedElts, AllowUndefs, AllowTruncation);
14154}
14155
14157 bool AllowUndefs,
14158 bool AllowTruncation) {
14160 return CN;
14161
14162 // SplatVectors can truncate their operands. Ignore that case here unless
14163 // AllowTruncation is set.
14164 if (N->getOpcode() == ISD::SPLAT_VECTOR) {
14165 EVT VecEltVT = N->getValueType(0).getVectorElementType();
14166 if (auto *CN = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
14167 EVT CVT = CN->getValueType(0);
14168 assert(CVT.bitsGE(VecEltVT) && "Illegal splat_vector element extension");
14169 if (AllowTruncation || CVT == VecEltVT)
14170 return CN;
14171 }
14172 }
14173
14175 BitVector UndefElements;
14176 ConstantSDNode *CN = BV->getConstantSplatNode(DemandedElts, &UndefElements);
14177
14178 // BuildVectors can truncate their operands. Ignore that case here unless
14179 // AllowTruncation is set.
14180 // TODO: Look into whether we should allow UndefElements in non-DemandedElts
14181 if (CN && (UndefElements.none() || AllowUndefs)) {
14182 EVT CVT = CN->getValueType(0);
14183 EVT NSVT = N.getValueType().getScalarType();
14184 assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension");
14185 if (AllowTruncation || (CVT == NSVT))
14186 return CN;
14187 }
14188 }
14189
14190 if (N.getOpcode() == ISD::MERGE_VALUES)
14191 return isConstOrConstSplat(N.getOperand(N.getResNo()), DemandedElts,
14192 AllowUndefs, AllowTruncation);
14193
14194 return nullptr;
14195}
14196
14198 APInt DemandedElts = getDemandAllEltsMask(N);
14199 return isConstOrConstSplatFP(N, DemandedElts, AllowUndefs);
14200}
14201
14203 const APInt &DemandedElts,
14204 bool AllowUndefs) {
14206 return CN;
14207
14209 BitVector UndefElements;
14210 ConstantFPSDNode *CN =
14211 BV->getConstantFPSplatNode(DemandedElts, &UndefElements);
14212 // TODO: Look into whether we should allow UndefElements in non-DemandedElts
14213 if (CN && (UndefElements.none() || AllowUndefs))
14214 return CN;
14215 }
14216
14217 if (N.getOpcode() == ISD::SPLAT_VECTOR)
14218 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N.getOperand(0)))
14219 return CN;
14220
14221 return nullptr;
14222}
14223
14224bool llvm::isNullOrNullSplat(SDValue N, bool AllowUndefs) {
14225 // TODO: may want to use peekThroughBitcast() here.
14226 ConstantSDNode *C =
14227 isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation=*/true);
14228 return C && C->isZero();
14229}
14230
14231bool llvm::isOneOrOneSplat(SDValue N, bool AllowUndefs) {
14232 ConstantSDNode *C =
14233 isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation*/ true);
14234 return C && C->isOne();
14235}
14236
14237bool llvm::isOneOrOneSplatFP(SDValue N, bool AllowUndefs) {
14238 ConstantFPSDNode *C = isConstOrConstSplatFP(N, AllowUndefs);
14239 return C && C->isOne();
14240}
14241
14242bool llvm::isAllOnesOrAllOnesSplat(SDValue N, bool AllowUndefs) {
14244 unsigned BitWidth = N.getScalarValueSizeInBits();
14245 ConstantSDNode *C =
14246 isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation=*/true);
14247 return C && C->getAPIntValue().countTrailingOnes() >= BitWidth;
14248}
14249
14250bool llvm::isZeroOrZeroSplat(SDValue N, bool AllowUndefs) {
14252 ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs, true);
14253 return C && C->isZero();
14254}
14255
14256bool llvm::isZeroOrZeroSplatFP(SDValue N, bool AllowUndefs) {
14257 ConstantFPSDNode *C = isConstOrConstSplatFP(N, AllowUndefs);
14258 return C && C->isZero();
14259}
14260
14264
14266 unsigned Opc, unsigned Order, const DebugLoc &dl, SDVTList VTs, EVT memvt,
14268 : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MemRefs(memrefs) {
14269 bool IsVolatile = false;
14270 bool IsNonTemporal = false;
14271 bool IsDereferenceable = true;
14272 bool IsInvariant = true;
14273 for (const MachineMemOperand *MMO : memoperands()) {
14274 IsVolatile |= MMO->isVolatile();
14275 IsNonTemporal |= MMO->isNonTemporal();
14276 IsDereferenceable &= MMO->isDereferenceable();
14277 IsInvariant &= MMO->isInvariant();
14278 }
14279 MemSDNodeBits.IsVolatile = IsVolatile;
14280 MemSDNodeBits.IsNonTemporal = IsNonTemporal;
14281 MemSDNodeBits.IsDereferenceable = IsDereferenceable;
14282 MemSDNodeBits.IsInvariant = IsInvariant;
14283
14284 // For the single-MMO case, we check here that the size of the memory operand
14285 // fits within the size of the MMO. This is because the MMO might indicate
14286 // only a possible address range instead of specifying the affected memory
14287 // addresses precisely.
14290 getMemOperand()->getSize().getValue())) &&
14291 "Size mismatch!");
14292}
14293
14294namespace {
14295
14296 struct EVTArray {
14297 std::vector<EVT> VTs;
14298
14299 EVTArray() {
14300 VTs.reserve(MVT::VALUETYPE_SIZE);
14301 for (unsigned i = 0; i < MVT::VALUETYPE_SIZE; ++i)
14302 VTs.push_back(MVT((MVT::SimpleValueType)i));
14303 }
14304 };
14305
14306} // end anonymous namespace
14307
14308/// getValueTypeList - Return a pointer to the specified value type.
14309///
14310const EVT *SDNode::getValueTypeList(MVT VT) {
14311 static EVTArray SimpleVTArray;
14312
14313 assert(VT < MVT::VALUETYPE_SIZE && "Value type out of range!");
14314 return &SimpleVTArray.VTs[VT.SimpleTy];
14315}
14316
14317/// hasAnyUseOfValue - Return true if there are any use of the indicated
14318/// value. This method ignores uses of other values defined by this operation.
14319bool SDNode::hasAnyUseOfValue(unsigned Value) const {
14320 assert(Value < getNumValues() && "Bad value!");
14321
14322 for (SDUse &U : uses())
14323 if (U.getResNo() == Value)
14324 return true;
14325
14326 return false;
14327}
14328
14329/// isOnlyUserOf - Return true if this node is the only use of N.
14330bool SDNode::isOnlyUserOf(const SDNode *N) const {
14331 bool Seen = false;
14332 for (const SDNode *User : N->users()) {
14333 if (User == this)
14334 Seen = true;
14335 else
14336 return false;
14337 }
14338
14339 return Seen;
14340}
14341
14342/// Return true if the only users of N are contained in Nodes.
14344 bool Seen = false;
14345 for (const SDNode *User : N->users()) {
14346 if (llvm::is_contained(Nodes, User))
14347 Seen = true;
14348 else
14349 return false;
14350 }
14351
14352 return Seen;
14353}
14354
14355/// Return true if the referenced return value is an operand of N.
14356bool SDValue::isOperandOf(const SDNode *N) const {
14357 return is_contained(N->op_values(), *this);
14358}
14359
14360bool SDNode::isOperandOf(const SDNode *N) const {
14361 return any_of(N->op_values(),
14362 [this](SDValue Op) { return this == Op.getNode(); });
14363}
14364
14365/// reachesChainWithoutSideEffects - Return true if this operand (which must
14366/// be a chain) reaches the specified operand without crossing any
14367/// side-effecting instructions on any chain path. In practice, this looks
14368/// through token factors and non-volatile loads. In order to remain efficient,
14369/// this only looks a couple of nodes in, it does not do an exhaustive search.
14370///
14371/// Note that we only need to examine chains when we're searching for
14372/// side-effects; SelectionDAG requires that all side-effects are represented
14373/// by chains, even if another operand would force a specific ordering. This
14374/// constraint is necessary to allow transformations like splitting loads.
14376 unsigned Depth) const {
14377 if (*this == Dest) return true;
14378
14379 // Don't search too deeply, we just want to be able to see through
14380 // TokenFactor's etc.
14381 if (Depth == 0) return false;
14382
14383 // If this is a token factor, all inputs to the TF happen in parallel.
14384 if (getOpcode() == ISD::TokenFactor) {
14385 // First, try a shallow search.
14386 if (is_contained((*this)->ops(), Dest)) {
14387 // We found the chain we want as an operand of this TokenFactor.
14388 // Essentially, we reach the chain without side-effects if we could
14389 // serialize the TokenFactor into a simple chain of operations with
14390 // Dest as the last operation. This is automatically true if the
14391 // chain has one use: there are no other ordering constraints.
14392 // If the chain has more than one use, we give up: some other
14393 // use of Dest might force a side-effect between Dest and the current
14394 // node.
14395 if (Dest.hasOneUse())
14396 return true;
14397 }
14398 // Next, try a deep search: check whether every operand of the TokenFactor
14399 // reaches Dest.
14400 return llvm::all_of((*this)->ops(), [=](SDValue Op) {
14401 return Op.reachesChainWithoutSideEffects(Dest, Depth - 1);
14402 });
14403 }
14404
14405 // Loads don't have side effects, look through them.
14406 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
14407 if (Ld->isUnordered())
14408 return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
14409 }
14410 return false;
14411}
14412
14413bool SDNode::hasPredecessor(const SDNode *N) const {
14416 Worklist.push_back(this);
14417 return hasPredecessorHelper(N, Visited, Worklist);
14418}
14419
14421 this->Flags &= Flags;
14422}
14423
14424SDValue
14426 ArrayRef<ISD::NodeType> CandidateBinOps,
14427 bool AllowPartials) {
14428 // The pattern must end in an extract from index 0.
14429 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
14430 !isNullConstant(Extract->getOperand(1)))
14431 return SDValue();
14432
14433 // Match against one of the candidate binary ops.
14434 SDValue Op = Extract->getOperand(0);
14435 if (llvm::none_of(CandidateBinOps, [Op](ISD::NodeType BinOp) {
14436 return Op.getOpcode() == unsigned(BinOp);
14437 }))
14438 return SDValue();
14439
14440 // Floating-point reductions may require relaxed constraints on the final step
14441 // of the reduction because they may reorder intermediate operations.
14442 unsigned CandidateBinOp = Op.getOpcode();
14443 if (Op.getValueType().isFloatingPoint()) {
14444 SDNodeFlags Flags = Op->getFlags();
14445 switch (CandidateBinOp) {
14446 case ISD::FADD:
14447 if (!Flags.hasNoSignedZeros() || !Flags.hasAllowReassociation())
14448 return SDValue();
14449 break;
14450 default:
14451 llvm_unreachable("Unhandled FP opcode for binop reduction");
14452 }
14453 }
14454
14455 // Matching failed - attempt to see if we did enough stages that a partial
14456 // reduction from a subvector is possible.
14457 auto PartialReduction = [&](SDValue Op, unsigned NumSubElts) {
14458 if (!AllowPartials || !Op)
14459 return SDValue();
14460 EVT OpVT = Op.getValueType();
14461 EVT OpSVT = OpVT.getScalarType();
14462 EVT SubVT = EVT::getVectorVT(*getContext(), OpSVT, NumSubElts);
14463 if (TLI->getExtractSubvectorCost(SubVT, OpVT, 0) >
14465 return SDValue();
14466 BinOp = (ISD::NodeType)CandidateBinOp;
14467 return getExtractSubvector(SDLoc(Op), SubVT, Op, 0);
14468 };
14469
14470 // At each stage, we're looking for something that looks like:
14471 // %s = shufflevector <8 x i32> %op, <8 x i32> undef,
14472 // <8 x i32> <i32 2, i32 3, i32 undef, i32 undef,
14473 // i32 undef, i32 undef, i32 undef, i32 undef>
14474 // %a = binop <8 x i32> %op, %s
14475 // Where the mask changes according to the stage. E.g. for a 3-stage pyramid,
14476 // we expect something like:
14477 // <4,5,6,7,u,u,u,u>
14478 // <2,3,u,u,u,u,u,u>
14479 // <1,u,u,u,u,u,u,u>
14480 // While a partial reduction match would be:
14481 // <2,3,u,u,u,u,u,u>
14482 // <1,u,u,u,u,u,u,u>
14483 unsigned Stages = Log2_32(Op.getValueType().getVectorNumElements());
14484 SDValue PrevOp;
14485 for (unsigned i = 0; i < Stages; ++i) {
14486 unsigned MaskEnd = (1 << i);
14487
14488 if (Op.getOpcode() != CandidateBinOp)
14489 return PartialReduction(PrevOp, MaskEnd);
14490
14491 SDValue Op0 = Op.getOperand(0);
14492 SDValue Op1 = Op.getOperand(1);
14493
14495 if (Shuffle) {
14496 Op = Op1;
14497 } else {
14498 Shuffle = dyn_cast<ShuffleVectorSDNode>(Op1);
14499 Op = Op0;
14500 }
14501
14502 // The first operand of the shuffle should be the same as the other operand
14503 // of the binop.
14504 if (!Shuffle || Shuffle->getOperand(0) != Op)
14505 return PartialReduction(PrevOp, MaskEnd);
14506
14507 // Verify the shuffle has the expected (at this stage of the pyramid) mask.
14508 for (int Index = 0; Index < (int)MaskEnd; ++Index)
14509 if (Shuffle->getMaskElt(Index) != (int)(MaskEnd + Index))
14510 return PartialReduction(PrevOp, MaskEnd);
14511
14512 PrevOp = Op;
14513 }
14514
14515 // Handle subvector reductions, which tend to appear after the shuffle
14516 // reduction stages.
14517 while (Op.getOpcode() == CandidateBinOp) {
14518 unsigned NumElts = Op.getValueType().getVectorNumElements();
14519 SDValue Op0 = Op.getOperand(0);
14520 SDValue Op1 = Op.getOperand(1);
14521 if (Op0.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
14523 Op0.getOperand(0) != Op1.getOperand(0))
14524 break;
14525 SDValue Src = Op0.getOperand(0);
14526 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
14527 if (NumSrcElts != (2 * NumElts))
14528 break;
14529 if (!(Op0.getConstantOperandAPInt(1) == 0 &&
14530 Op1.getConstantOperandAPInt(1) == NumElts) &&
14531 !(Op1.getConstantOperandAPInt(1) == 0 &&
14532 Op0.getConstantOperandAPInt(1) == NumElts))
14533 break;
14534 Op = Src;
14535 }
14536
14537 BinOp = (ISD::NodeType)CandidateBinOp;
14538 return Op;
14539}
14540
14542 EVT VT = N->getValueType(0);
14543 EVT EltVT = VT.getVectorElementType();
14544 unsigned NE = getMaxRuntimeNumElements(VT);
14545
14546 if (VT.isScalableVector() && (NE == 0 || ResNE != 0))
14547 reportFatalUsageError("Cannot unroll scalable vector!");
14548
14549 assert(NE && "Nothing to unroll!");
14550 SDLoc dl(N);
14551
14552 // If ResNE is 0, fully unroll the vector op.
14553 if (ResNE == 0)
14554 ResNE = NE;
14555 else if (NE > ResNE)
14556 NE = ResNE;
14557
14558 if (N->getNumValues() == 2) {
14559 SmallVector<SDValue, 8> Scalars0, Scalars1;
14560 SmallVector<SDValue, 4> Operands(N->getNumOperands());
14561 EVT VT1 = N->getValueType(1);
14562 EVT EltVT1 = VT1.getVectorElementType();
14563
14564 unsigned i;
14565 for (i = 0; i != NE; ++i) {
14566 for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) {
14567 SDValue Operand = N->getOperand(j);
14568 EVT OperandVT = Operand.getValueType();
14569
14570 // A vector operand; extract a single element.
14571 EVT OperandEltVT = OperandVT.getVectorElementType();
14572 Operands[j] = getExtractVectorElt(dl, OperandEltVT, Operand, i);
14573 }
14574
14575 SDValue EltOp = getNode(N->getOpcode(), dl, {EltVT, EltVT1}, Operands);
14576 Scalars0.push_back(EltOp);
14577 Scalars1.push_back(EltOp.getValue(1));
14578 }
14579
14580 for (; i < ResNE; ++i) {
14581 Scalars0.push_back(getUNDEF(EltVT));
14582 Scalars1.push_back(getUNDEF(EltVT1));
14583 }
14584
14586 : ElementCount::getFixed(ResNE);
14587 EVT VecVT = EVT::getVectorVT(*getContext(), EltVT, ResEC);
14588 EVT VecVT1 = EVT::getVectorVT(*getContext(), EltVT1, ResEC);
14589 SDValue Vec0 = buildVectorFromUnrolledParts(VecVT, dl, Scalars0);
14590 SDValue Vec1 = buildVectorFromUnrolledParts(VecVT1, dl, Scalars1);
14591 return getMergeValues({Vec0, Vec1}, dl);
14592 }
14593
14594 assert(N->getNumValues() == 1 &&
14595 "Can't unroll a vector with multiple results!");
14596
14598 SmallVector<SDValue, 4> Operands(N->getNumOperands());
14599
14600 unsigned i;
14601 for (i= 0; i != NE; ++i) {
14602 for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) {
14603 SDValue Operand = N->getOperand(j);
14604 EVT OperandVT = Operand.getValueType();
14605 if (OperandVT.isVector()) {
14606 // A vector operand; extract a single element.
14607 EVT OperandEltVT = OperandVT.getVectorElementType();
14608 Operands[j] = getExtractVectorElt(dl, OperandEltVT, Operand, i);
14609 } else {
14610 // A scalar operand; just use it as is.
14611 Operands[j] = Operand;
14612 }
14613 }
14614
14615 switch (N->getOpcode()) {
14616 default: {
14617 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands,
14618 N->getFlags()));
14619 break;
14620 }
14621 case ISD::VSELECT: {
14622 SDValue Cond = Operands[0];
14623 EVT CondVT = Cond.getValueType();
14625 if (CondVT != MVT::i1 &&
14626 TLI.getBooleanContents(N->getOperand(1).getValueType()) !=
14627 TLI.getBooleanContents(CondVT)) {
14628 EVT SetCCVT =
14629 TLI.getSetCCResultType(getDataLayout(), *getContext(), CondVT);
14630 Operands[0] =
14631 getSetCC(dl, SetCCVT, Cond, getConstant(0, dl, CondVT), ISD::SETNE);
14632 }
14633 Scalars.push_back(
14634 getNode(ISD::SELECT, dl, EltVT, Operands, N->getFlags()));
14635 break;
14636 }
14637 case ISD::SHL:
14638 case ISD::SRA:
14639 case ISD::SRL:
14640 case ISD::ROTL:
14641 case ISD::ROTR:
14642 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0],
14644 Operands[1])));
14645 break;
14647 EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType();
14648 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT,
14649 Operands[0],
14650 getValueType(ExtVT)));
14651 break;
14652 }
14653 case ISD::ADDRSPACECAST: {
14654 const auto *ASC = cast<AddrSpaceCastSDNode>(N);
14655 Scalars.push_back(
14656 getAddrSpaceCast(dl, EltVT, Operands[0], ASC->getSrcAddressSpace(),
14657 ASC->getDestAddressSpace(), ASC->getFlags()));
14658 break;
14659 }
14660 }
14661 }
14662
14663 for (; i < ResNE; ++i)
14664 Scalars.push_back(getUNDEF(EltVT));
14665
14666 EVT VecVT = VT.isScalableVector()
14667 ? VT
14668 : EVT::getVectorVT(*getContext(), EltVT, ResNE);
14669 return buildVectorFromUnrolledParts(VecVT, dl, Scalars);
14670}
14671
14672std::pair<SDValue, SDValue> SelectionDAG::UnrollVectorOverflowOp(
14673 SDNode *N, unsigned ResNE) {
14674 unsigned Opcode = N->getOpcode();
14675 assert((Opcode == ISD::UADDO || Opcode == ISD::SADDO ||
14676 Opcode == ISD::USUBO || Opcode == ISD::SSUBO ||
14677 Opcode == ISD::UMULO || Opcode == ISD::SMULO) &&
14678 "Expected an overflow opcode");
14679
14680 EVT ResVT = N->getValueType(0);
14681 EVT OvVT = N->getValueType(1);
14682 EVT ResEltVT = ResVT.getVectorElementType();
14683 EVT OvEltVT = OvVT.getVectorElementType();
14684 SDLoc dl(N);
14685
14686 // If ResNE is 0, fully unroll the vector op.
14687 unsigned NE = ResVT.getVectorNumElements();
14688 if (ResNE == 0)
14689 ResNE = NE;
14690 else if (NE > ResNE)
14691 NE = ResNE;
14692
14693 SmallVector<SDValue, 8> LHSScalars;
14694 SmallVector<SDValue, 8> RHSScalars;
14695 ExtractVectorElements(N->getOperand(0), LHSScalars, 0, NE);
14696 ExtractVectorElements(N->getOperand(1), RHSScalars, 0, NE);
14697
14698 EVT SVT = TLI->getSetCCResultType(getDataLayout(), *getContext(), ResEltVT);
14699 SDVTList VTs = getVTList(ResEltVT, SVT);
14700 SmallVector<SDValue, 8> ResScalars;
14701 SmallVector<SDValue, 8> OvScalars;
14702 for (unsigned i = 0; i < NE; ++i) {
14703 SDValue Res = getNode(Opcode, dl, VTs, LHSScalars[i], RHSScalars[i]);
14704 SDValue Ov =
14705 getSelect(dl, OvEltVT, Res.getValue(1),
14706 getBoolConstant(true, dl, OvEltVT, ResVT),
14707 getConstant(0, dl, OvEltVT));
14708
14709 ResScalars.push_back(Res);
14710 OvScalars.push_back(Ov);
14711 }
14712
14713 ResScalars.append(ResNE - NE, getUNDEF(ResEltVT));
14714 OvScalars.append(ResNE - NE, getUNDEF(OvEltVT));
14715
14716 EVT NewResVT = EVT::getVectorVT(*getContext(), ResEltVT, ResNE);
14717 EVT NewOvVT = EVT::getVectorVT(*getContext(), OvEltVT, ResNE);
14718 return std::make_pair(getBuildVector(NewResVT, dl, ResScalars),
14719 getBuildVector(NewOvVT, dl, OvScalars));
14720}
14721
14724 TypeSize Bytes, int Dist,
14725 const SelectionDAG &DAG) {
14726 if (LS->isVolatile() || Base->isVolatile())
14727 return false;
14728 // TODO: probably too restrictive for atomics, revisit
14729 if (!LS->isSimple())
14730 return false;
14731 if (LS->isIndexed() || Base->isIndexed())
14732 return false;
14733 if (LS->getChain() != Base->getChain())
14734 return false;
14735 EVT VT = LS->getMemoryVT();
14736 if (!VT.getScalarType().isByteSized())
14737 return false;
14738 if (VT.getStoreSize() != Bytes)
14739 return false;
14740
14741 auto BaseLocDecomp = BaseIndexOffset::match(Base, DAG);
14742 auto LocDecomp = BaseIndexOffset::match(LS, DAG);
14744 if (!BaseLocDecomp.equalBaseIndex(LocDecomp, DAG, Offset))
14745 return false;
14746
14747 int64_t ExpectedOffset = Dist * (int64_t)Bytes.getKnownMinValue();
14748 if (Bytes.isFixed())
14749 return Offset == StackOffset::getFixed(ExpectedOffset);
14750 return Offset == StackOffset::getScalable(ExpectedOffset);
14751}
14752
14755 TypeSize Bytes,
14756 int Dist) const {
14757 return areNonVolatileConsecutiveLoadsOrStores(LD, Base, Bytes, Dist, *this);
14758}
14759
14762 TypeSize Bytes,
14763 int Dist) const {
14764 return areNonVolatileConsecutiveLoadsOrStores(ST, Base, Bytes, Dist, *this);
14765}
14766
14767/// InferPtrAlignment - Infer alignment of a load / store address. Return
14768/// std::nullopt if it cannot be inferred.
14770 // If this is a GlobalAddress + cst, return the alignment.
14771 const GlobalValue *GV = nullptr;
14772 int64_t GVOffset = 0;
14773 if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) {
14774 unsigned PtrWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
14775 KnownBits Known(PtrWidth);
14777 unsigned AlignBits = Known.countMinTrailingZeros();
14778 if (AlignBits)
14779 return commonAlignment(Align::fromLog2(std::min(31U, AlignBits)),
14780 GVOffset);
14781 }
14782
14783 // If this is a direct reference to a stack slot, use information about the
14784 // stack slot's alignment.
14785 int FrameIdx = INT_MIN;
14786 int64_t FrameOffset = 0;
14788 FrameIdx = FI->getIndex();
14789 } else if (isBaseWithConstantOffset(Ptr) &&
14791 // Handle FI+Cst
14792 FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
14793 FrameOffset = Ptr.getConstantOperandVal(1);
14794 }
14795
14796 if (FrameIdx != INT_MIN) {
14798 return commonAlignment(MFI.getObjectAlign(FrameIdx), FrameOffset);
14799 }
14800
14801 return std::nullopt;
14802}
14803
14804/// Split the scalar node with EXTRACT_ELEMENT using the provided
14805/// VTs and return the low/high part.
14806std::pair<SDValue, SDValue> SelectionDAG::SplitScalar(const SDValue &N,
14807 const SDLoc &DL,
14808 const EVT &LoVT,
14809 const EVT &HiVT) {
14810 assert(!LoVT.isVector() && !HiVT.isVector() && !N.getValueType().isVector() &&
14811 "Split node must be a scalar type");
14812 SDValue Lo =
14814 SDValue Hi =
14816 return std::make_pair(Lo, Hi);
14817}
14818
14819/// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type
14820/// which is split (or expanded) into two not necessarily identical pieces.
14821std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const {
14822 // Currently all types are split in half.
14823 EVT LoVT, HiVT;
14824 if (!VT.isVector())
14825 LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT);
14826 else
14827 LoVT = HiVT = VT.getHalfNumVectorElementsVT(*getContext());
14828
14829 return std::make_pair(LoVT, HiVT);
14830}
14831
14832/// GetDependentSplitDestVTs - Compute the VTs needed for the low/hi parts of a
14833/// type, dependent on an enveloping VT that has been split into two identical
14834/// pieces. Sets the HiIsEmpty flag when hi type has zero storage size.
14835std::pair<EVT, EVT>
14837 bool *HiIsEmpty) const {
14838 EVT EltTp = VT.getVectorElementType();
14839 // Examples:
14840 // custom VL=8 with enveloping VL=8/8 yields 8/0 (hi empty)
14841 // custom VL=9 with enveloping VL=8/8 yields 8/1
14842 // custom VL=10 with enveloping VL=8/8 yields 8/2
14843 // etc.
14844 ElementCount VTNumElts = VT.getVectorElementCount();
14845 ElementCount EnvNumElts = EnvVT.getVectorElementCount();
14846 assert(VTNumElts.isScalable() == EnvNumElts.isScalable() &&
14847 "Mixing fixed width and scalable vectors when enveloping a type");
14848 EVT LoVT, HiVT;
14849 if (VTNumElts.getKnownMinValue() > EnvNumElts.getKnownMinValue()) {
14850 LoVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts);
14851 HiVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts - EnvNumElts);
14852 *HiIsEmpty = false;
14853 } else {
14854 // Flag that hi type has zero storage size, but return split envelop type
14855 // (this would be easier if vector types with zero elements were allowed).
14856 LoVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts);
14857 HiVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts);
14858 *HiIsEmpty = true;
14859 }
14860 return std::make_pair(LoVT, HiVT);
14861}
14862
14863/// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the
14864/// low/high part.
14865std::pair<SDValue, SDValue>
14866SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT,
14867 const EVT &HiVT) {
14868 assert(LoVT.isScalableVector() == HiVT.isScalableVector() &&
14869 LoVT.isScalableVector() == N.getValueType().isScalableVector() &&
14870 "Splitting vector with an invalid mixture of fixed and scalable "
14871 "vector types");
14873 N.getValueType().getVectorMinNumElements() &&
14874 "More vector elements requested than available!");
14875 SDValue Lo, Hi;
14876 Lo = getExtractSubvector(DL, LoVT, N, 0);
14877 // For scalable vectors it is safe to use LoVT.getVectorMinNumElements()
14878 // (rather than having to use ElementCount), because EXTRACT_SUBVECTOR scales
14879 // IDX with the runtime scaling factor of the result vector type. For
14880 // fixed-width result vectors, that runtime scaling factor is 1.
14882 return std::make_pair(Lo, Hi);
14883}
14884
14885std::pair<SDValue, SDValue> SelectionDAG::SplitEVL(SDValue N, EVT VecVT,
14886 const SDLoc &DL) {
14887 // Split the vector length parameter.
14888 // %evl -> umin(%evl, %halfnumelts) and usubsat(%evl - %halfnumelts).
14889 EVT VT = N.getValueType();
14891 "Expecting the mask to be an evenly-sized vector");
14892 SDValue HalfNumElts = getElementCount(
14894 SDValue Lo = getNode(ISD::UMIN, DL, VT, N, HalfNumElts);
14895 SDValue Hi = getNode(ISD::USUBSAT, DL, VT, N, HalfNumElts);
14896 return std::make_pair(Lo, Hi);
14897}
14898
14899/// Widen the vector up to the next power of two using INSERT_SUBVECTOR.
14901 EVT VT = N.getValueType();
14902 EVT WideVT = VT.changeElementCount(
14903 *getContext(),
14905 return getInsertSubvector(DL, getPOISON(WideVT), N, 0);
14906}
14907
14910 unsigned Start, unsigned Count,
14911 EVT EltVT) {
14912 EVT VT = Op.getValueType();
14913 if (Count == 0)
14915 if (EltVT == EVT())
14916 EltVT = VT.getVectorElementType();
14917 SDLoc SL(Op);
14918 for (unsigned i = Start, e = Start + Count; i != e; ++i) {
14919 Args.push_back(getExtractVectorElt(SL, EltVT, Op, i));
14920 }
14921}
14922
14923// getAddressSpace - Return the address space this GlobalAddress belongs to.
14925 return getGlobal()->getType()->getAddressSpace();
14926}
14927
14930 return Val.MachineCPVal->getType();
14931 return Val.ConstVal->getType();
14932}
14933
14934bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue, APInt &SplatUndef,
14935 unsigned &SplatBitSize,
14936 bool &HasAnyUndefs,
14937 unsigned MinSplatBits,
14938 bool IsBigEndian) const {
14939 EVT VT = getValueType(0);
14940 assert(VT.isVector() && "Expected a vector type");
14941 unsigned VecWidth = VT.getSizeInBits();
14942 if (MinSplatBits > VecWidth)
14943 return false;
14944
14945 // FIXME: The widths are based on this node's type, but build vectors can
14946 // truncate their operands.
14947 SplatValue = APInt(VecWidth, 0);
14948 SplatUndef = APInt(VecWidth, 0);
14949
14950 // Get the bits. Bits with undefined values (when the corresponding element
14951 // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared
14952 // in SplatValue. If any of the values are not constant, give up and return
14953 // false.
14954 unsigned int NumOps = getNumOperands();
14955 assert(NumOps > 0 && "isConstantSplat has 0-size build vector");
14956 unsigned EltWidth = VT.getScalarSizeInBits();
14957
14958 for (unsigned j = 0; j < NumOps; ++j) {
14959 unsigned i = IsBigEndian ? NumOps - 1 - j : j;
14960 SDValue OpVal = getOperand(i);
14961 unsigned BitPos = j * EltWidth;
14962
14963 if (OpVal.isUndef())
14964 SplatUndef.setBits(BitPos, BitPos + EltWidth);
14965 else if (auto *CN = dyn_cast<ConstantSDNode>(OpVal))
14966 SplatValue.insertBits(CN->getAPIntValue().zextOrTrunc(EltWidth), BitPos);
14967 else if (auto *CN = dyn_cast<ConstantFPSDNode>(OpVal))
14968 SplatValue.insertBits(CN->getValueAPF().bitcastToAPInt(), BitPos);
14969 else
14970 return false;
14971 }
14972
14973 // The build_vector is all constants or undefs. Find the smallest element
14974 // size that splats the vector.
14975 HasAnyUndefs = (SplatUndef != 0);
14976
14977 // FIXME: This does not work for vectors with elements less than 8 bits.
14978 while (VecWidth > 8) {
14979 // If we can't split in half, stop here.
14980 if (VecWidth & 1)
14981 break;
14982
14983 unsigned HalfSize = VecWidth / 2;
14984 APInt HighValue = SplatValue.extractBits(HalfSize, HalfSize);
14985 APInt LowValue = SplatValue.extractBits(HalfSize, 0);
14986 APInt HighUndef = SplatUndef.extractBits(HalfSize, HalfSize);
14987 APInt LowUndef = SplatUndef.extractBits(HalfSize, 0);
14988
14989 // If the two halves do not match (ignoring undef bits), stop here.
14990 if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) ||
14991 MinSplatBits > HalfSize)
14992 break;
14993
14994 SplatValue = HighValue | LowValue;
14995 SplatUndef = HighUndef & LowUndef;
14996
14997 VecWidth = HalfSize;
14998 }
14999
15000 // FIXME: The loop above only tries to split in halves. But if the input
15001 // vector for example is <3 x i16> it wouldn't be able to detect a
15002 // SplatBitSize of 16. No idea if that is a design flaw currently limiting
15003 // optimizations. I guess that back in the days when this helper was created
15004 // vectors normally was power-of-2 sized.
15005
15006 SplatBitSize = VecWidth;
15007 return true;
15008}
15009
15011 BitVector *UndefElements) const {
15012 unsigned NumOps = getNumOperands();
15013 if (UndefElements) {
15014 UndefElements->clear();
15015 UndefElements->resize(NumOps);
15016 }
15017 assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size");
15018 if (!DemandedElts)
15019 return SDValue();
15020 SDValue Splatted;
15021 for (unsigned i = 0; i != NumOps; ++i) {
15022 if (!DemandedElts[i])
15023 continue;
15024 SDValue Op = getOperand(i);
15025 if (Op.isUndef()) {
15026 if (UndefElements)
15027 (*UndefElements)[i] = true;
15028 } else if (!Splatted) {
15029 Splatted = Op;
15030 } else if (Splatted != Op) {
15031 return SDValue();
15032 }
15033 }
15034
15035 if (!Splatted) {
15036 unsigned FirstDemandedIdx = DemandedElts.countr_zero();
15037 assert(getOperand(FirstDemandedIdx).isUndef() &&
15038 "Can only have a splat without a constant for all undefs.");
15039 return getOperand(FirstDemandedIdx);
15040 }
15041
15042 return Splatted;
15043}
15044
15046 APInt DemandedElts = APInt::getAllOnes(getNumOperands());
15047 return getSplatValue(DemandedElts, UndefElements);
15048}
15049
15051 SmallVectorImpl<SDValue> &Sequence,
15052 BitVector *UndefElements) const {
15053 unsigned NumOps = getNumOperands();
15054 Sequence.clear();
15055 if (UndefElements) {
15056 UndefElements->clear();
15057 UndefElements->resize(NumOps);
15058 }
15059 assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size");
15060 if (!DemandedElts || NumOps < 2 || !isPowerOf2_32(NumOps))
15061 return false;
15062
15063 // Set the undefs even if we don't find a sequence (like getSplatValue).
15064 if (UndefElements)
15065 for (unsigned I = 0; I != NumOps; ++I)
15066 if (DemandedElts[I] && getOperand(I).isUndef())
15067 (*UndefElements)[I] = true;
15068
15069 // Iteratively widen the sequence length looking for repetitions.
15070 for (unsigned SeqLen = 1; SeqLen < NumOps; SeqLen *= 2) {
15071 Sequence.append(SeqLen, SDValue());
15072 for (unsigned I = 0; I != NumOps; ++I) {
15073 if (!DemandedElts[I])
15074 continue;
15075 SDValue &SeqOp = Sequence[I % SeqLen];
15077 if (Op.isUndef()) {
15078 if (!SeqOp)
15079 SeqOp = Op;
15080 continue;
15081 }
15082 if (SeqOp && !SeqOp.isUndef() && SeqOp != Op) {
15083 Sequence.clear();
15084 break;
15085 }
15086 SeqOp = Op;
15087 }
15088 if (!Sequence.empty())
15089 return true;
15090 }
15091
15092 assert(Sequence.empty() && "Failed to empty non-repeating sequence pattern");
15093 return false;
15094}
15095
15097 BitVector *UndefElements) const {
15098 APInt DemandedElts = APInt::getAllOnes(getNumOperands());
15099 return getRepeatedSequence(DemandedElts, Sequence, UndefElements);
15100}
15101
15104 BitVector *UndefElements) const {
15106 getSplatValue(DemandedElts, UndefElements));
15107}
15108
15111 return dyn_cast_or_null<ConstantSDNode>(getSplatValue(UndefElements));
15112}
15113
15116 BitVector *UndefElements) const {
15118 getSplatValue(DemandedElts, UndefElements));
15119}
15120
15125
15126int32_t
15128 uint32_t BitWidth) const {
15129 if (ConstantFPSDNode *CN =
15131 bool IsExact;
15132 APSInt IntVal(BitWidth);
15133 const APFloat &APF = CN->getValueAPF();
15134 if (APF.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) !=
15135 APFloat::opOK ||
15136 !IsExact)
15137 return -1;
15138
15139 return IntVal.exactLogBase2();
15140 }
15141 return -1;
15142}
15143
15145 bool IsLittleEndian, unsigned DstEltSizeInBits,
15146 SmallVectorImpl<APInt> &RawBitElements, BitVector &UndefElements) const {
15147 // Early-out if this contains anything but Undef/Constant/ConstantFP.
15148 if (!isConstant())
15149 return false;
15150
15151 unsigned NumSrcOps = getNumOperands();
15152 unsigned SrcEltSizeInBits = getValueType(0).getScalarSizeInBits();
15153 assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 &&
15154 "Invalid bitcast scale");
15155
15156 // If the elements don't pack cleanly, don't attempt to recast.
15157 // TODO: Add handling (e.g. bitcast <33 x i8> --> <8 x i33>)
15158 if ((SrcEltSizeInBits % DstEltSizeInBits) != 0 &&
15159 (DstEltSizeInBits % SrcEltSizeInBits) != 0)
15160 return false;
15161
15162 // Extract raw src bits.
15163 SmallVector<APInt> SrcBitElements(NumSrcOps,
15164 APInt::getZero(SrcEltSizeInBits));
15165 BitVector SrcUndeElements(NumSrcOps, false);
15166
15167 for (unsigned I = 0; I != NumSrcOps; ++I) {
15169 if (Op.isUndef()) {
15170 SrcUndeElements.set(I);
15171 continue;
15172 }
15173 auto *CInt = dyn_cast<ConstantSDNode>(Op);
15174 auto *CFP = dyn_cast<ConstantFPSDNode>(Op);
15175 assert((CInt || CFP) && "Unknown constant");
15176 SrcBitElements[I] = CInt ? CInt->getAPIntValue().trunc(SrcEltSizeInBits)
15177 : CFP->getValueAPF().bitcastToAPInt();
15178 }
15179
15180 // Recast to dst width.
15181 recastRawBits(IsLittleEndian, DstEltSizeInBits, RawBitElements,
15182 SrcBitElements, UndefElements, SrcUndeElements);
15183 return true;
15184}
15185
15186void BuildVectorSDNode::recastRawBits(bool IsLittleEndian,
15187 unsigned DstEltSizeInBits,
15188 SmallVectorImpl<APInt> &DstBitElements,
15189 ArrayRef<APInt> SrcBitElements,
15190 BitVector &DstUndefElements,
15191 const BitVector &SrcUndefElements) {
15192 unsigned NumSrcOps = SrcBitElements.size();
15193 unsigned SrcEltSizeInBits = SrcBitElements[0].getBitWidth();
15194 assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 &&
15195 "Invalid bitcast scale");
15196 assert(((SrcEltSizeInBits % DstEltSizeInBits) == 0 ||
15197 (DstEltSizeInBits % SrcEltSizeInBits) == 0) &&
15198 "Unsupported bitcast scale");
15199 assert(NumSrcOps == SrcUndefElements.size() && "Vector size mismatch");
15200
15201 unsigned NumDstOps = (NumSrcOps * SrcEltSizeInBits) / DstEltSizeInBits;
15202 DstUndefElements.clear();
15203 DstUndefElements.resize(NumDstOps, false);
15204 DstBitElements.assign(NumDstOps, APInt::getZero(DstEltSizeInBits));
15205
15206 // Concatenate src elements constant bits together into dst element.
15207 if (SrcEltSizeInBits <= DstEltSizeInBits) {
15208 unsigned Scale = DstEltSizeInBits / SrcEltSizeInBits;
15209 for (unsigned I = 0; I != NumDstOps; ++I) {
15210 DstUndefElements.set(I);
15211 APInt &DstBits = DstBitElements[I];
15212 for (unsigned J = 0; J != Scale; ++J) {
15213 unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1));
15214 if (SrcUndefElements[Idx])
15215 continue;
15216 DstUndefElements.reset(I);
15217 const APInt &SrcBits = SrcBitElements[Idx];
15218 assert(SrcBits.getBitWidth() == SrcEltSizeInBits &&
15219 "Illegal constant bitwidths");
15220 DstBits.insertBits(SrcBits, J * SrcEltSizeInBits);
15221 }
15222 }
15223 return;
15224 }
15225
15226 // Split src element constant bits into dst elements.
15227 unsigned Scale = SrcEltSizeInBits / DstEltSizeInBits;
15228 for (unsigned I = 0; I != NumSrcOps; ++I) {
15229 if (SrcUndefElements[I]) {
15230 DstUndefElements.set(I * Scale, (I + 1) * Scale);
15231 continue;
15232 }
15233 const APInt &SrcBits = SrcBitElements[I];
15234 for (unsigned J = 0; J != Scale; ++J) {
15235 unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1));
15236 APInt &DstBits = DstBitElements[Idx];
15237 DstBits = SrcBits.extractBits(DstEltSizeInBits, J * DstEltSizeInBits);
15238 }
15239 }
15240}
15241
15243 for (const SDValue &Op : op_values()) {
15244 unsigned Opc = Op.getOpcode();
15245 if (!Op.isUndef() && Opc != ISD::Constant && Opc != ISD::ConstantFP)
15246 return false;
15247 }
15248 return true;
15249}
15250
15251std::optional<std::pair<APInt, APInt>>
15253 unsigned NumOps = getNumOperands();
15254 if (NumOps < 2)
15255 return std::nullopt;
15256
15257 unsigned EltSize = getValueType(0).getScalarSizeInBits();
15258 APInt Start, Stride;
15259 int FirstIdx = -1, SecondIdx = -1;
15260
15261 // Find the first two non-undef constant elements to determine Start and
15262 // Stride, then verify all remaining elements match the sequence.
15263 for (unsigned I = 0; I < NumOps; ++I) {
15265 if (Op->isUndef())
15266 continue;
15267 if (!isa<ConstantSDNode>(Op))
15268 return std::nullopt;
15269
15270 APInt Val = getConstantOperandAPInt(I).trunc(EltSize);
15271 if (FirstIdx < 0) {
15272 FirstIdx = I;
15273 Start = Val;
15274 } else if (SecondIdx < 0) {
15275 SecondIdx = I;
15276 // Compute stride using modular arithmetic. Simple division would handle
15277 // common strides (1, 2, -1, etc.), but modular inverse maximizes matches.
15278 // Example: <0, poison, poison, 0xFF> has stride 0x55 since 3*0x55 = 0xFF
15279 // Note that modular arithmetic is agnostic to signed/unsigned.
15280 unsigned IdxDiff = I - FirstIdx;
15281 APInt ValDiff = Val - Start;
15282
15283 // Step 1: Factor out common powers of 2 from IdxDiff and ValDiff.
15284 unsigned CommonPow2Bits = llvm::countr_zero(IdxDiff);
15285 if (ValDiff.countr_zero() < CommonPow2Bits)
15286 return std::nullopt; // ValDiff not divisible by 2^CommonPow2Bits
15287 IdxDiff >>= CommonPow2Bits;
15288 ValDiff.lshrInPlace(CommonPow2Bits);
15289
15290 // Step 2: IdxDiff is now odd, so its inverse mod 2^EltSize exists.
15291 // TODO: There are 2^CommonPow2Bits valid strides; currently we only try
15292 // one, but we could try all candidates to handle more cases.
15293 Stride = ValDiff * APInt(EltSize, IdxDiff).multiplicativeInverse();
15294 if (Stride.isZero())
15295 return std::nullopt;
15296
15297 // Step 3: Adjust Start based on the first defined element's index.
15298 Start -= Stride * FirstIdx;
15299 } else {
15300 // Verify this element matches the sequence.
15301 if (Val != Start + Stride * I)
15302 return std::nullopt;
15303 }
15304 }
15305
15306 // Need at least two defined elements.
15307 if (SecondIdx < 0)
15308 return std::nullopt;
15309
15310 return std::make_pair(Start, Stride);
15311}
15312
15314 // Find the first non-undef value in the shuffle mask.
15315 unsigned i, e;
15316 for (i = 0, e = Mask.size(); i != e && Mask[i] < 0; ++i)
15317 /* search */;
15318
15319 // If all elements are undefined, this shuffle can be considered a splat
15320 // (although it should eventually get simplified away completely).
15321 if (i == e)
15322 return true;
15323
15324 // Make sure all remaining elements are either undef or the same as the first
15325 // non-undef value.
15326 for (int Idx = Mask[i]; i != e; ++i)
15327 if (Mask[i] >= 0 && Mask[i] != Idx)
15328 return false;
15329 return true;
15330}
15331
15332// Returns true if it is a constant integer BuildVector or constant integer,
15333// possibly hidden by a bitcast.
15335 SDValue N, bool AllowOpaques) const {
15337
15338 if (auto *C = dyn_cast<ConstantSDNode>(N))
15339 return AllowOpaques || !C->isOpaque();
15340
15342 return true;
15343
15344 // Treat a GlobalAddress supporting constant offset folding as a
15345 // constant integer.
15346 if (auto *GA = dyn_cast<GlobalAddressSDNode>(N))
15347 if (GA->getOpcode() == ISD::GlobalAddress &&
15348 TLI->isOffsetFoldingLegal(GA))
15349 return true;
15350
15351 if ((N.getOpcode() == ISD::SPLAT_VECTOR) &&
15352 isa<ConstantSDNode>(N.getOperand(0)))
15353 return true;
15354 return false;
15355}
15356
15357// Returns true if it is a constant float BuildVector or constant float.
15360 return true;
15361
15363 return true;
15364
15365 if ((N.getOpcode() == ISD::SPLAT_VECTOR) &&
15366 isa<ConstantFPSDNode>(N.getOperand(0)))
15367 return true;
15368
15369 return false;
15370}
15371
15372std::optional<bool> SelectionDAG::isBoolConstant(SDValue N) const {
15373 ConstantSDNode *Const =
15374 isConstOrConstSplat(N, false, /*AllowTruncation=*/true);
15375 if (!Const)
15376 return std::nullopt;
15377
15378 EVT VT = N.getValueType();
15379 const APInt CVal = Const->getAPIntValue().trunc(VT.getScalarSizeInBits());
15380 switch (TLI->getBooleanContents(VT)) {
15382 if (CVal.isOne())
15383 return true;
15384 if (CVal.isZero())
15385 return false;
15386 return std::nullopt;
15388 if (CVal.isAllOnes())
15389 return true;
15390 if (CVal.isZero())
15391 return false;
15392 return std::nullopt;
15394 return CVal[0];
15395 }
15396 llvm_unreachable("Unknown BooleanContent enum");
15397}
15398
15399void SelectionDAG::createOperands(SDNode *Node, ArrayRef<SDValue> Vals) {
15400 assert(!Node->OperandList && "Node already has operands");
15402 "too many operands to fit into SDNode");
15403 SDUse *Ops = OperandRecycler.allocate(
15404 ArrayRecycler<SDUse>::Capacity::get(Vals.size()), OperandAllocator);
15405
15406 bool IsDivergent = false;
15407 for (unsigned I = 0; I != Vals.size(); ++I) {
15408 Ops[I].setUser(Node);
15409 Ops[I].setInitial(Vals[I]);
15410 EVT VT = Ops[I].getValueType();
15411
15412 // Skip Chain. It does not carry divergence.
15413 if (VT != MVT::Other &&
15414 (VT != MVT::Glue || gluePropagatesDivergence(Ops[I].getNode())) &&
15415 Ops[I].getNode()->isDivergent()) {
15416 IsDivergent = true;
15417 }
15418 }
15419 Node->NumOperands = Vals.size();
15420 Node->OperandList = Ops;
15421 if (!TLI->isSDNodeAlwaysUniform(Node)) {
15422 IsDivergent |= TLI->isSDNodeSourceOfDivergence(Node, FLI, UA);
15423 Node->SDNodeBits.IsDivergent = IsDivergent;
15424 }
15425 checkForCycles(Node);
15426}
15427
15430 size_t Limit = SDNode::getMaxNumOperands();
15431 while (Vals.size() > Limit) {
15432 unsigned SliceIdx = Vals.size() - Limit;
15433 auto ExtractedTFs = ArrayRef<SDValue>(Vals).slice(SliceIdx, Limit);
15434 SDValue NewTF = getNode(ISD::TokenFactor, DL, MVT::Other, ExtractedTFs);
15435 Vals.erase(Vals.begin() + SliceIdx, Vals.end());
15436 Vals.emplace_back(NewTF);
15437 }
15438 return getNode(ISD::TokenFactor, DL, MVT::Other, Vals);
15439}
15440
15442 EVT VT, SDNodeFlags Flags) {
15443 switch (Opcode) {
15444 default:
15445 return SDValue();
15446 case ISD::ADD:
15447 case ISD::OR:
15448 case ISD::XOR:
15449 case ISD::UMAX:
15450 case ISD::MUL:
15451 case ISD::AND:
15452 case ISD::UMIN:
15453 case ISD::SMAX:
15454 case ISD::SMIN:
15456 VT);
15457 case ISD::FADD:
15458 // If flags allow, prefer positive zero since it's generally cheaper
15459 // to materialize on most targets.
15460 return getConstantFP(Flags.hasNoSignedZeros() ? 0.0 : -0.0, DL, VT);
15461 case ISD::FMUL:
15462 return getConstantFP(1.0, DL, VT);
15463 case ISD::FMINNUM:
15464 case ISD::FMAXNUM:
15465 case ISD::FMINIMUMNUM:
15466 case ISD::FMAXIMUMNUM: {
15467 // Neutral element for fminnum/fminimumnum is NaN, Inf or FLT_MAX,
15468 // depending on fast-math flags (FMF).
15469 const fltSemantics &Semantics = VT.getFltSemantics();
15470 APFloat NeutralAF = !Flags.hasNoNaNs() ? APFloat::getQNaN(Semantics) :
15471 !Flags.hasNoInfs() ? APFloat::getInf(Semantics) :
15472 APFloat::getLargest(Semantics);
15473 if (Opcode == ISD::FMAXNUM || Opcode == ISD::FMAXIMUMNUM)
15474 NeutralAF.changeSign();
15475
15476 return getConstantFP(NeutralAF, DL, VT);
15477 }
15478 case ISD::FMINIMUM:
15479 case ISD::FMAXIMUM: {
15480 // Neutral element for fminimum is Inf or FLT_MAX, depending on FMF.
15481 const fltSemantics &Semantics = VT.getFltSemantics();
15482 APFloat NeutralAF = !Flags.hasNoInfs() ? APFloat::getInf(Semantics)
15483 : APFloat::getLargest(Semantics);
15484 if (Opcode == ISD::FMAXIMUM)
15485 NeutralAF.changeSign();
15486
15487 return getConstantFP(NeutralAF, DL, VT);
15488 }
15489
15490 }
15491}
15492
15494 SDValue Acc, SDValue LHS,
15495 SDValue RHS) {
15496 EVT AccVT = Acc.getValueType();
15497 if (AccVT.isFloatingPoint()) {
15498 assert(Opc == ISD::PARTIAL_REDUCE_FMLA && "Unexpected opcode");
15499 SDValue NegRHS = getNode(ISD::FNEG, DL, RHS.getValueType(), RHS);
15500 return getNode(Opc, DL, AccVT, Acc, LHS, NegRHS);
15501 }
15504 "Unexpected opcode");
15505 SDValue NegAcc = getNegative(Acc, DL, AccVT);
15506 SDValue MLA = getNode(Opc, DL, AccVT, NegAcc, LHS, RHS);
15507 return getNegative(MLA, DL, AccVT);
15508}
15509
15510/// Helper used to make a call to a library function that has one argument of
15511/// pointer type.
15512///
15513/// Such functions include 'fegetmode', 'fesetenv' and some others, which are
15514/// used to get or set floating-point state. They have one argument of pointer
15515/// type, which points to the memory region containing bits of the
15516/// floating-point state. The value returned by such function is ignored in the
15517/// created call.
15518///
15519/// \param LibFunc Reference to library function (value of RTLIB::Libcall).
15520/// \param Ptr Pointer used to save/load state.
15521/// \param InChain Ingoing token chain.
15522/// \param Node Node being legalized
15523/// \returns Outgoing chain token.
15525 SDValue InChain, SDNode *Node) {
15526 assert(InChain.getValueType() == MVT::Other && "Expected token chain");
15527 RTLIB::LibcallImpl LibcallImpl =
15528 Libcalls->getLibcallImpl(static_cast<RTLIB::Libcall>(LibFunc));
15529 if (LibcallImpl == RTLIB::Unsupported) {
15530 getContext()->emitError(Twine("no libcall available for ") +
15531 Node->getOperationName(this));
15532 return InChain;
15533 }
15534
15536 Args.emplace_back(Ptr, Ptr.getValueType().getTypeForEVT(*getContext()));
15537 SDValue Callee =
15538 getExternalSymbol(LibcallImpl, TLI->getPointerTy(getDataLayout()));
15540 CLI.setDebugLoc(SDLoc(Node))
15541 .setChain(InChain)
15542 .setLibCallee(Libcalls->getLibcallImplCallingConv(LibcallImpl),
15543 Type::getVoidTy(*getContext()), Callee, std::move(Args));
15544 return TLI->LowerCallTo(CLI).second;
15545}
15546
15548 assert(From && To && "Invalid SDNode; empty source SDValue?");
15549 auto I = SDEI.find(From);
15550 if (I == SDEI.end())
15551 return;
15552
15553 // Use of operator[] on the DenseMap may cause an insertion, which invalidates
15554 // the iterator, hence the need to make a copy to prevent a use-after-free.
15555 NodeExtraInfo NEI = I->second;
15556 if (LLVM_LIKELY(!NEI.PCSections)) {
15557 // No deep copy required for the types of extra info set.
15558 //
15559 // FIXME: Investigate if other types of extra info also need deep copy. This
15560 // depends on the types of nodes they can be attached to: if some extra info
15561 // is only ever attached to nodes where a replacement To node is always the
15562 // node where later use and propagation of the extra info has the intended
15563 // semantics, no deep copy is required.
15564 SDEI[To] = std::move(NEI);
15565 return;
15566 }
15567
15568 const SDNode *EntrySDN = getEntryNode().getNode();
15569
15570 // We need to copy NodeExtraInfo to all _new_ nodes that are being introduced
15571 // through the replacement of From with To. Otherwise, replacements of a node
15572 // (From) with more complex nodes (To and its operands) may result in lost
15573 // extra info where the root node (To) is insignificant in further propagating
15574 // and using extra info when further lowering to MIR.
15575 //
15576 // In the first step pre-populate the visited set with the nodes reachable
15577 // from the old From node. This avoids copying NodeExtraInfo to parts of the
15578 // DAG that is not new and should be left untouched.
15579 SmallVector<const SDNode *> Leafs{From}; // Leafs reachable with VisitFrom.
15580 DenseSet<const SDNode *> FromReach; // The set of nodes reachable from From.
15581 auto VisitFrom = [&](auto &&Self, const SDNode *N, int MaxDepth) {
15582 if (MaxDepth == 0) {
15583 // Remember this node in case we need to increase MaxDepth and continue
15584 // populating FromReach from this node.
15585 Leafs.emplace_back(N);
15586 return;
15587 }
15588 if (!FromReach.insert(N).second)
15589 return;
15590 for (const SDValue &Op : N->op_values())
15591 Self(Self, Op.getNode(), MaxDepth - 1);
15592 };
15593
15594 // Copy extra info to To and all its transitive operands (that are new).
15596 auto DeepCopyTo = [&](auto &&Self, const SDNode *N) {
15597 if (FromReach.contains(N))
15598 return true;
15599 if (!Visited.insert(N).second)
15600 return true;
15601 if (EntrySDN == N)
15602 return false;
15603 for (const SDValue &Op : N->op_values()) {
15604 if (N == To && Op.getNode() == EntrySDN) {
15605 // Special case: New node's operand is the entry node; just need to
15606 // copy extra info to new node.
15607 break;
15608 }
15609 if (!Self(Self, Op.getNode()))
15610 return false;
15611 }
15612 // Copy only if entry node was not reached.
15613 SDEI[N] = std::move(NEI);
15614 return true;
15615 };
15616
15617 // We first try with a lower MaxDepth, assuming that the path to common
15618 // operands between From and To is relatively short. This significantly
15619 // improves performance in the common case. The initial MaxDepth is big
15620 // enough to avoid retry in the common case; the last MaxDepth is large
15621 // enough to avoid having to use the fallback below (and protects from
15622 // potential stack exhaustion from recursion).
15623 for (int PrevDepth = 0, MaxDepth = 16; MaxDepth <= 1024;
15624 PrevDepth = MaxDepth, MaxDepth *= 2, Visited.clear()) {
15625 // StartFrom is the previous (or initial) set of leafs reachable at the
15626 // previous maximum depth.
15628 std::swap(StartFrom, Leafs);
15629 for (const SDNode *N : StartFrom)
15630 VisitFrom(VisitFrom, N, MaxDepth - PrevDepth);
15631 if (LLVM_LIKELY(DeepCopyTo(DeepCopyTo, To)))
15632 return;
15633 // This should happen very rarely (reached the entry node).
15634 LLVM_DEBUG(dbgs() << __func__ << ": MaxDepth=" << MaxDepth << " too low\n");
15635 assert(!Leafs.empty());
15636 }
15637
15638 // This should not happen - but if it did, that means the subgraph reachable
15639 // from From has depth greater or equal to maximum MaxDepth, and VisitFrom()
15640 // could not visit all reachable common operands. Consequently, we were able
15641 // to reach the entry node.
15642 errs() << "warning: incomplete propagation of SelectionDAG::NodeExtraInfo\n";
15643 assert(false && "From subgraph too complex - increase max. MaxDepth?");
15644 // Best-effort fallback if assertions disabled.
15645 SDEI[To] = std::move(NEI);
15646}
15647
15649 assert(VT.isVector() && "Can only unroll vector types!");
15650 if (VT.isFixedLengthVector())
15651 return VT.getVectorNumElements();
15652
15653 const MachineFunction &MF = getMachineFunction();
15654 const Function &F = MF.getFunction();
15655
15656 APInt MaxVScale = getVScaleRange(&F, sizeof(unsigned) * 8).getUnsignedMax();
15657 if (MaxVScale.ugt(getSelectionDAGOptions().vscale_unroll_limit))
15658 return 0;
15659
15660 bool Overflow;
15661 APInt MinNElts(sizeof(unsigned) * 8, VT.getVectorMinNumElements());
15662 APInt MaxNElts = MinNElts.umul_ov(MaxVScale, Overflow);
15663 if (Overflow)
15664 return 0;
15665
15666 return MaxNElts.getZExtValue();
15667}
15668
15670 ArrayRef<SDValue> Scalars) {
15671 assert(Scalars.size() == getMaxRuntimeNumElements(VT) &&
15672 "Element count mismatch!");
15673 if (VT.isFixedLengthVector())
15674 return getBuildVector(VT, DL, Scalars);
15675
15676 SDValue Vec = getPOISON(VT);
15677 // Iterate in reverse so result remains poison until we encounter a lane that
15678 // exists, after which all lower-numbered lanes must also exist.
15679 for (unsigned IdxVal : reverse(seq(Scalars.size())))
15680 Vec = getInsertVectorElt(DL, Vec, Scalars[IdxVal], IdxVal);
15681
15682 return Vec;
15683}
15684
15685#ifndef NDEBUG
15686static void checkForCyclesHelper(const SDNode *N,
15689 const llvm::SelectionDAG *DAG) {
15690 // If this node has already been checked, don't check it again.
15691 if (Checked.count(N))
15692 return;
15693
15694 // If a node has already been visited on this depth-first walk, reject it as
15695 // a cycle.
15696 if (!Visited.insert(N).second) {
15697 errs() << "Detected cycle in SelectionDAG\n";
15698 dbgs() << "Offending node:\n";
15699 N->dumprFull(DAG); dbgs() << "\n";
15700 abort();
15701 }
15702
15703 for (const SDValue &Op : N->op_values())
15704 checkForCyclesHelper(Op.getNode(), Visited, Checked, DAG);
15705
15706 Checked.insert(N);
15707 Visited.erase(N);
15708}
15709#endif
15710
15712 const llvm::SelectionDAG *DAG,
15713 bool force) {
15714#ifndef NDEBUG
15715 bool check = force;
15716#ifdef EXPENSIVE_CHECKS
15717 check = true;
15718#endif // EXPENSIVE_CHECKS
15719 if (check) {
15720 assert(N && "Checking nonexistent SDNode");
15723 checkForCyclesHelper(N, visited, checked, DAG);
15724 }
15725#endif // !NDEBUG
15726}
15727
15728void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) {
15729 checkForCycles(DAG->getRoot().getNode(), DAG, force);
15730}
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 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:6101
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.
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 SDValue getFreeze(SDValue V)
Return a freeze using the SDLoc of the value operand.
LLVM_ABI SDNode * SelectNodeTo(SDNode *N, unsigned MachineOpc, EVT VT)
These are used for target selectors to mutate the specified node to have the specified return type,...
LLVM_ABI const BasicBlock * getBasicBlock() const
LLVM_ABI SelectionDAG(const TargetMachine &TM, CodeGenOptLevel)
LLVM_ABI SDValue getMemset(SDValue Chain, const SDLoc &dl, SDValue Dst, SDValue Src, SDValue Size, Align Alignment, bool isVol, bool AlwaysInline, const CallInst *CI, MachinePointerInfo DstPtrInfo, const AAMDNodes &AAInfo=AAMDNodes())
LLVM_ABI SDValue getConstantPool(const Constant *C, EVT VT, MaybeAlign Align=std::nullopt, int Offs=0, bool isT=false, unsigned TargetFlags=0)
LLVM_ABI SDValue getStridedLoadVP(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &DL, SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Stride, SDValue Mask, SDValue EVL, EVT MemVT, MachineMemOperand *MMO, bool IsExpanding=false)
LLVM_ABI SDValue getAtomicCmpSwap(unsigned Opcode, const SDLoc &dl, EVT MemVT, SDVTList VTs, SDValue Chain, SDValue Ptr, SDValue Cmp, SDValue Swp, MachineMemOperand *MMO)
Gets a node for an atomic cmpxchg op.
LLVM_ABI SDValue makeEquivalentMemoryOrdering(SDValue OldChain, SDValue NewMemOpChain)
If an existing load has uses of its chain, create a token factor node with that chain and the new mem...
LLVM_ABI bool isConstantIntBuildVectorOrConstantInt(SDValue N, bool AllowOpaques=true) const
Test whether the given value is a constant int or similar node.
LLVM_ABI void ReplaceAllUsesOfValuesWith(const SDValue *From, const SDValue *To, unsigned Num)
Like ReplaceAllUsesOfValueWith, but for multiple values at once.
LLVM_ABI SDValue getJumpTableDebugInfo(int JTI, SDValue Chain, const SDLoc &DL)
LLVM_ABI SDValue getSymbolFunctionGlobalAddress(SDValue Op, Function **TargetFunction=nullptr)
Return a GlobalAddress of the function from the current module with name matching the given ExternalS...
LLVM_ABI std::optional< unsigned > getValidMaximumShiftAmount(SDValue V, const APInt &DemandedElts, unsigned Depth=0) const
If a SHL/SRA/SRL node V has shift amounts that are all less than the element bit-width of the shift n...
LLVM_ABI bool areNonVolatileConsecutiveLoads(LoadSDNode *LD, LoadSDNode *Base, TypeSize Bytes, int Dist) const
Return true if loads are next to each other and can be merged.
LLVM_ABI SDValue UnrollVectorOp(SDNode *N, unsigned ResNE=0)
Utility function used by legalize and lowering to "unroll" a vector operation by splitting out the sc...
LLVM_ABI SDValue getVScale(const SDLoc &DL, EVT VT, APInt MulImm)
Return a node that represents the runtime scaling 'MulImm * RuntimeVL'.
LLVM_ABI SDValue getConstantFP(double Val, const SDLoc &DL, EVT VT, bool isTarget=false)
Create a ConstantFPSDNode wrapping a constant value.
OverflowKind
Used to represent the possible overflow behavior of an operation.
LLVM_ABI bool haveNoCommonBitsSet(SDValue A, SDValue B) const
Return true if A and B have no common bits set.
LLVM_ABI SDValue getAddrSpaceCast(const SDLoc &dl, EVT VT, SDValue Ptr, unsigned SrcAS, unsigned DestAS, const SDNodeFlags Flags=SDNodeFlags())
Return an AddrSpaceCastSDNode.
SDValue getExtractSubvector(const SDLoc &DL, EVT VT, SDValue Vec, unsigned Idx)
Return the VT typed sub-vector of Vec at Idx.
LLVM_ABI bool cannotBeOrderedNegativeFP(SDValue Op) const
Test whether the given float value is known to be positive.
LLVM_ABI SDValue getRegister(Register Reg, EVT VT)
LLVM_ABI bool calculateDivergence(SDNode *N)
LLVM_ABI std::pair< SDValue, SDValue > getStrcmp(SDValue Chain, const SDLoc &dl, SDValue S0, SDValue S1, const CallInst *CI)
Lower a strcmp operation into a target library call and return the resulting chain and call result as...
LLVM_ABI SDValue getGetFPEnv(SDValue Chain, const SDLoc &dl, SDValue Ptr, EVT MemVT, MachineMemOperand *MMO)
LLVM_ABI SDValue getAssertAlign(const SDLoc &DL, SDValue V, Align A)
Return an AssertAlignSDNode.
LLVM_ABI SDNode * mutateStrictFPToFP(SDNode *Node)
Mutate the specified strict FP node to its non-strict equivalent, unlinking the node from its chain a...
LLVM_ABI bool canIgnoreSignBitOfZero(const SDUse &Use) const
Check if the user of Use produces the same result regardless of the sign of a zero in the used float ...
LLVM_ABI bool SignBitIsZeroFP(SDValue Op, unsigned Depth=0) const
Return true if the sign bit of Op is known to be zero, for a floating-point value.
LLVM_ABI SDValue getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef< SDValue > Ops, EVT MemVT, MachinePointerInfo PtrInfo, Align Alignment, MachineMemOperand::Flags Flags=MachineMemOperand::MOLoad|MachineMemOperand::MOStore, LocationSize Size=LocationSize::precise(0), const AAMDNodes &AAInfo=AAMDNodes())
Creates a MemIntrinsicNode that may produce a result and takes a list of operands.
SDValue getInsertSubvector(const SDLoc &DL, SDValue Vec, SDValue SubVec, unsigned Idx)
Insert SubVec at the Idx element of Vec.
LLVM_ABI SDValue getStepVector(const SDLoc &DL, EVT ResVT, const APInt &StepVal)
Returns a vector of type ResVT whose elements contain the linear sequence <0, Step,...
SDValue getSetCC(const SDLoc &DL, EVT VT, SDValue LHS, SDValue RHS, ISD::CondCode Cond, SDValue Chain=SDValue(), bool IsSignaling=false, SDNodeFlags Flags={})
Helper function to make it easier to build SetCC's if you just have an ISD::CondCode instead of an SD...
LLVM_ABI SDValue getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, SDValue Chain, SDValue Ptr, SDValue Val, MachineMemOperand *MMO)
Gets a node for an atomic op, produces result (if relevant) and chain and takes 2 operands.
LLVM_ABI Align getEVTAlign(EVT MemoryVT) const
Compute the default alignment value for the given type.
LLVM_ABI bool shouldOptForSize() const
LLVM_ABI bool hasSwiftErrorArg() const
LLVM_ABI SDValue buildVectorFromUnrolledParts(EVT VT, const SDLoc &DL, ArrayRef< SDValue > Scalars)
Returns a vector constructed from the scalar values in order.
LLVM_ABI SDValue getNOT(const SDLoc &DL, SDValue Val, EVT VT)
Create a bitwise NOT operation as (XOR Val, -1).
LLVM_ABI SDValue getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst, SDValue Src, SDValue Size, Align DstAlign, Align SrcAlign, bool isVol, bool AlwaysInline, const CallInst *CI, std::optional< bool > OverrideTailCall, MachinePointerInfo DstPtrInfo, MachinePointerInfo SrcPtrInfo, const AAMDNodes &AAInfo=AAMDNodes(), BatchAAResults *BatchAA=nullptr)
const TargetLowering & getTargetLoweringInfo() const
LLVM_ABI bool isEqualTo(SDValue A, SDValue B) const
Test whether two SDValues are known to compare equal.
static constexpr unsigned MaxRecursionDepth
LLVM_ABI unsigned getMaxRuntimeNumElements(EVT VT) const
Returns the maximum runtime number of elements in VT if known, or 0 otherwise.
LLVM_ABI SDValue getStridedStoreVP(SDValue Chain, const SDLoc &DL, SDValue Val, SDValue Ptr, SDValue Offset, SDValue Stride, SDValue Mask, SDValue EVL, EVT MemVT, MachineMemOperand *MMO, ISD::MemIndexedMode AM, bool IsTruncating=false, bool IsCompressing=false)
bool isGuaranteedNotToBePoison(SDValue Op, unsigned Depth=0) const
Return true if this function can prove that Op is never poison.
LLVM_ABI SDValue getIdentityElement(unsigned Opcode, const SDLoc &DL, EVT VT, SDNodeFlags Flags)
Get the (commutative) identity element for the given opcode, if it exists.
LLVM_ABI SDValue expandVACopy(SDNode *Node)
Expand the specified ISD::VACOPY node as the Legalize pass would.
LLVM_ABI SDValue getIndexedMaskedLoad(SDValue OrigLoad, const SDLoc &dl, SDValue Base, SDValue Offset, ISD::MemIndexedMode AM)
LLVM_ABI APInt computeVectorKnownZeroElements(SDValue Op, const APInt &DemandedElts, unsigned Depth=0) const
For each demanded element of a vector, see if it is known to be zero.
LLVM_ABI void AddDbgValue(SDDbgValue *DB, bool isParameter)
Add a dbg_value SDNode.
bool NewNodesMustHaveLegalTypes
When true, additional steps are taken to ensure that getConstant() and similar functions return DAG n...
LLVM_ABI std::pair< EVT, EVT > GetSplitDestVTs(const EVT &VT) const
Compute the VTs needed for the low/hi parts of a type which is split (or expanded) into two not neces...
LLVM_ABI void salvageDebugInfo(SDNode &N)
To be invoked on an SDNode that is slated to be erased.
LLVM_ABI SDNode * MorphNodeTo(SDNode *N, unsigned Opc, SDVTList VTs, ArrayRef< SDValue > Ops)
This mutates the specified node to have the specified return type, opcode, and operands.
LLVM_ABI std::pair< SDValue, SDValue > UnrollVectorOverflowOp(SDNode *N, unsigned ResNE=0)
Like UnrollVectorOp(), but for the [US](ADD|SUB|MUL)O family of opcodes.
allnodes_const_iterator allnodes_begin() const
SDValue getUNDEF(EVT VT)
Return an UNDEF node. UNDEF does not have a useful SDLoc.
LLVM_ABI SDValue getGatherVP(SDVTList VTs, EVT VT, const SDLoc &dl, ArrayRef< SDValue > Ops, MachineMemOperand *MMO, ISD::MemIndexType IndexType)
SDValue getBuildVector(EVT VT, const SDLoc &DL, ArrayRef< SDValue > Ops)
Return an ISD::BUILD_VECTOR node.
LLVM_ABI SDValue getBitcastedAnyExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of integer type, to the integer type VT, by first bitcasting (from potentia...
LLVM_ABI bool isSplatValue(SDValue V, const APInt &DemandedElts, APInt &UndefElts, unsigned Depth=0) const
Test whether V has a splatted value for all the demanded elements.
LLVM_ABI void DeleteNode(SDNode *N)
Remove the specified node from the system.
LLVM_ABI SDValue getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val, SDValue Ptr, SDValue Offset, MachinePointerInfo PtrInfo, EVT SVT, Align Alignment, MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const MMOMetadata &Metadata=MMOMetadata())
LLVM_ABI SDValue getBitcast(EVT VT, SDValue V)
Return a bitcast using the SDLoc of the value operand, and casting to the provided type.
LLVM_ABI SDDbgValue * getDbgValueList(DIVariable *Var, DIExpression *Expr, ArrayRef< SDDbgOperand > Locs, ArrayRef< SDNode * > Dependencies, bool IsIndirect, const DebugLoc &DL, unsigned O, bool IsVariadic)
Creates a SDDbgValue node from a list of locations.
LLVM_ABI std::pair< SDValue, SDValue > getStrcpy(SDValue Chain, const SDLoc &dl, SDValue Dst, SDValue Src, const CallInst *CI)
Lower a strcpy operation into a target library call and return the resulting chain and call result as...
SDValue getSelect(const SDLoc &DL, EVT VT, SDValue Cond, SDValue LHS, SDValue RHS, SDNodeFlags Flags=SDNodeFlags())
Helper function to make it easier to build Select's if you just have operands and don't want to check...
LLVM_ABI SDValue getNegative(SDValue Val, const SDLoc &DL, EVT VT)
Create negative operation as (SUB 0, Val).
LLVM_ABI std::optional< unsigned > getValidShiftAmount(SDValue V, const APInt &DemandedElts, unsigned Depth=0) const
If a SHL/SRA/SRL node V has a uniform shift amount that is less than the element bit-width of the shi...
LLVM_ABI void setNodeMemRefs(MachineSDNode *N, ArrayRef< MachineMemOperand * > NewMemRefs)
Mutate the specified machine node's memory references to the provided list.
LLVM_ABI SDValue simplifySelect(SDValue Cond, SDValue TVal, SDValue FVal)
Try to simplify a select/vselect into 1 of its operands or a constant.
LLVM_ABI SDValue getZeroExtendInReg(SDValue Op, const SDLoc &DL, EVT VT)
Return the expression required to zero extend the Op value assuming it was the smaller SrcTy value.
LLVM_ABI bool isConstantFPBuildVectorOrConstantFP(SDValue N) const
Test whether the given value is a constant FP or similar node.
const DataLayout & getDataLayout() const
LLVM_ABI SDValue 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 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)