LLVM 24.0.0git
SelectionDAG.cpp
Go to the documentation of this file.
1//===- SelectionDAG.cpp - Implement the SelectionDAG data structures ------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This implements the SelectionDAG class.
10//
11//===----------------------------------------------------------------------===//
12
14#include "SDNodeDbgValue.h"
15#include "SelectionDAGOptions.h"
16#include "llvm/ADT/APFloat.h"
17#include "llvm/ADT/APInt.h"
18#include "llvm/ADT/APSInt.h"
19#include "llvm/ADT/ArrayRef.h"
20#include "llvm/ADT/BitVector.h"
21#include "llvm/ADT/DenseSet.h"
22#include "llvm/ADT/FoldingSet.h"
23#include "llvm/ADT/STLExtras.h"
26#include "llvm/ADT/Twine.h"
53#include "llvm/IR/Constant.h"
54#include "llvm/IR/Constants.h"
55#include "llvm/IR/DataLayout.h"
57#include "llvm/IR/DebugLoc.h"
59#include "llvm/IR/Function.h"
60#include "llvm/IR/GlobalValue.h"
62#include "llvm/IR/Metadata.h"
63#include "llvm/IR/Type.h"
67#include "llvm/Support/Debug.h"
69#include "llvm/Support/FPFold.h"
78#include <algorithm>
79#include <cassert>
80#include <cstdint>
81#include <cstdlib>
82#include <limits>
83#include <optional>
84#include <string>
85#include <utility>
86#include <vector>
87
88using namespace llvm;
89using namespace llvm::SDPatternMatch;
90
91/// makeVTList - Return an instance of the SDVTList struct initialized with the
92/// specified members.
93static SDVTList makeVTList(const EVT *VTs, unsigned NumVTs) {
94 SDVTList Res = {VTs, NumVTs};
95 return Res;
96}
97
98// Default null implementations of the callbacks.
102
103void SelectionDAG::DAGNodeDeletedListener::anchor() {}
104void SelectionDAG::DAGNodeInsertedListener::anchor() {}
105
106#define DEBUG_TYPE "selectiondag"
107
109 LLVM_DEBUG(dbgs() << Msg; V.getNode()->dump(G););
110}
111
113 return getSelectionDAGOptions().has_predecessor_max_steps;
114}
115
116//===----------------------------------------------------------------------===//
117// ConstantFPSDNode Class
118//===----------------------------------------------------------------------===//
119
120/// isExactlyValue - We don't rely on operator== working on double values, as
121/// it returns true for things that are clearly not equal, like -0.0 and 0.0.
122/// As such, this method can be used to do an exact bit-for-bit comparison of
123/// two floating point values.
125 return getValueAPF().bitwiseIsEqual(V);
126}
127
129 const APFloat& Val) {
130 assert(VT.isFloatingPoint() && "Can only convert between FP types");
131
132 // convert modifies in place, so make a copy.
133 APFloat Val2 = APFloat(Val);
134 bool losesInfo;
136 &losesInfo);
137 return !losesInfo;
138}
139
140//===----------------------------------------------------------------------===//
141// ISD Namespace
142//===----------------------------------------------------------------------===//
143
145 if (V.getOpcode() == ISD::SPLAT_VECTOR) {
146 if (auto OptAPInt = V.getOperand(0)->bitcastToAPInt()) {
147 unsigned EltSize =
148 V.getValueType().getVectorElementType().getSizeInBits();
149 SplatVal = OptAPInt->trunc(EltSize);
150 return true;
151 }
152 }
153
154 auto *BV = dyn_cast<BuildVectorSDNode>(V);
155 if (!BV)
156 return false;
157
158 APInt SplatUndef;
159 unsigned SplatBitSize;
160 bool HasUndefs;
161 unsigned EltSize = V.getValueType().getVectorElementType().getSizeInBits();
162 // Endianness does not matter here. We are checking for a splat given the
163 // element size of the vector, and if we find such a splat for little endian
164 // layout, then that should be valid also for big endian (as the full vector
165 // size is known to be a multiple of the element size).
166 const bool IsBigEndian = false;
167 return BV->isConstantSplat(SplatVal, SplatUndef, SplatBitSize, HasUndefs,
168 EltSize, IsBigEndian) &&
169 EltSize == SplatBitSize;
170}
171
172// FIXME: AllOnes and AllZeros duplicate a lot of code. Could these be
173// specializations of the more general isConstantSplatVector()?
174
175bool ISD::isConstantSplatVectorAllOnes(SDValue V, bool BuildVectorOnly) {
176 // Look through a bit convert.
177 while (V.getOpcode() == ISD::BITCAST)
178 V = V.getOperand(0);
179
180 if (!BuildVectorOnly && V.getOpcode() == ISD::SPLAT_VECTOR) {
181 APInt SplatVal;
182 return isConstantSplatVector(V, SplatVal) && SplatVal.isAllOnes();
183 }
184
185 if (V.getOpcode() != ISD::BUILD_VECTOR)
186 return false;
187
188 unsigned i = 0, e = V.getNumOperands();
189
190 // Skip over all of the undef values.
191 while (i != e && V.getOperand(i).isUndef())
192 ++i;
193
194 // Do not accept an all-undef vector.
195 if (i == e) return false;
196
197 // Do not accept build_vectors that aren't all constants or which have non-~0
198 // elements. We have to be a bit careful here, as the type of the constant
199 // may not be the same as the type of the vector elements due to type
200 // legalization (the elements are promoted to a legal type for the target and
201 // a vector of a type may be legal when the base element type is not).
202 // We only want to check enough bits to cover the vector elements, because
203 // we care if the resultant vector is all ones, not whether the individual
204 // constants are.
205 SDValue NotZero = V.getOperand(i);
206 if (auto OptAPInt = NotZero->bitcastToAPInt()) {
207 unsigned EltSize = V.getValueType().getScalarSizeInBits();
208 if (OptAPInt->countr_one() < EltSize)
209 return false;
210 } else
211 return false;
212
213 // Okay, we have at least one ~0 value, check to see if the rest match or are
214 // undefs. Even with the above element type twiddling, this should be OK, as
215 // the same type legalization should have applied to all the elements.
216 for (++i; i != e; ++i)
217 if (V.getOperand(i) != NotZero && !V.getOperand(i).isUndef())
218 return false;
219 return true;
220}
221
222bool ISD::isConstantSplatVectorAllZeros(SDValue V, bool BuildVectorOnly) {
223 // Look through a bit convert.
224 while (V.getOpcode() == ISD::BITCAST)
225 V = V.getOperand(0);
226
227 if (!BuildVectorOnly && V.getOpcode() == ISD::SPLAT_VECTOR) {
228 APInt SplatVal;
229 return isConstantSplatVector(V, SplatVal) && SplatVal.isZero();
230 }
231
232 if (V.getOpcode() != ISD::BUILD_VECTOR)
233 return false;
234
235 bool IsAllUndef = true;
236 for (const SDValue &Op : V->op_values()) {
237 if (Op.isUndef())
238 continue;
239 IsAllUndef = false;
240 // Do not accept build_vectors that aren't all constants or which have non-0
241 // elements. We have to be a bit careful here, as the type of the constant
242 // may not be the same as the type of the vector elements due to type
243 // legalization (the elements are promoted to a legal type for the target
244 // and a vector of a type may be legal when the base element type is not).
245 // We only want to check enough bits to cover the vector elements, because
246 // we care if the resultant vector is all zeros, not whether the individual
247 // constants are.
248 if (auto OptAPInt = Op->bitcastToAPInt()) {
249 unsigned EltSize = V.getValueType().getScalarSizeInBits();
250 if (OptAPInt->countr_zero() < EltSize)
251 return false;
252 } else
253 return false;
254 }
255
256 // Do not accept an all-undef vector.
257 if (IsAllUndef)
258 return false;
259 return true;
260}
261
263 return isConstantSplatVectorAllOnes(V, /*BuildVectorOnly*/ true);
264}
265
267 return isConstantSplatVectorAllZeros(V, /*BuildVectorOnly*/ true);
268}
269
271 if (V.getOpcode() != ISD::BUILD_VECTOR)
272 return false;
273
274 for (const SDValue &Op : V->op_values()) {
275 if (Op.isUndef())
276 continue;
278 return false;
279 }
280 return true;
281}
282
284 if (V.getOpcode() != ISD::BUILD_VECTOR)
285 return false;
286
287 for (const SDValue &Op : V->op_values()) {
288 if (Op.isUndef())
289 continue;
291 return false;
292 }
293 return true;
294}
295
296bool ISD::isVectorShrinkable(SDValue V, unsigned NewEltSize, bool Signed) {
297 assert(V.getValueType().isVector() && "Expected a vector!");
298
299 unsigned EltSize = V.getValueType().getScalarSizeInBits();
300 if (EltSize <= NewEltSize)
301 return false;
302
303 if (V.getOpcode() == ISD::ZERO_EXTEND) {
304 return (V.getOperand(0).getValueType().getScalarSizeInBits() <=
305 NewEltSize) &&
306 !Signed;
307 }
308 if (V.getOpcode() == ISD::SIGN_EXTEND) {
309 return (V.getOperand(0).getValueType().getScalarSizeInBits() <=
310 NewEltSize) &&
311 Signed;
312 }
313 if (V.getOpcode() != ISD::BUILD_VECTOR)
314 return false;
315
316 for (const SDValue &Op : V->op_values()) {
317 if (Op.isUndef())
318 continue;
320 return false;
321
322 APInt C = Op->getAsAPIntVal().trunc(EltSize);
323 if (Signed && C.trunc(NewEltSize).sext(EltSize) != C)
324 return false;
325 if (!Signed && C.trunc(NewEltSize).zext(EltSize) != C)
326 return false;
327 }
328
329 return true;
330}
331
333 // Return false if the node has no operands.
334 // This is "logically inconsistent" with the definition of "all" but
335 // is probably the desired behavior.
336 if (V.getNumOperands() == 0)
337 return false;
338 return all_of(V->op_values(), [](SDValue Op) { return Op.isUndef(); });
339}
340
342 return V.getOpcode() == ISD::FREEZE && V.getOperand(0).isUndef();
343}
344
345template <typename ConstNodeType>
347 std::function<bool(ConstNodeType *)> Match,
348 bool AllowUndefs, bool AllowTruncation) {
349 // FIXME: Add support for scalar UNDEF cases?
350 if (auto *C = dyn_cast<ConstNodeType>(Op))
351 return Match(C);
352
353 // FIXME: Add support for vector UNDEF cases?
354 if (ISD::BUILD_VECTOR != Op.getOpcode() &&
355 ISD::SPLAT_VECTOR != Op.getOpcode())
356 return false;
357
358 if (ISD::SPLAT_VECTOR == Op.getOpcode() && !DemandedElts)
359 return true;
360
361 EVT SVT = Op.getValueType().getScalarType();
362 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
363 if (ISD::SPLAT_VECTOR != Op.getOpcode() && !DemandedElts[i])
364 continue;
365
366 if (AllowUndefs && Op.getOperand(i).isUndef()) {
367 if (!Match(nullptr))
368 return false;
369 continue;
370 }
371
372 auto *Cst = dyn_cast<ConstNodeType>(Op.getOperand(i));
373 if (!Cst || (!AllowTruncation && Cst->getValueType(0) != SVT) ||
374 !Match(Cst))
375 return false;
376 }
377 return true;
378}
379// Build used template types.
381 SDValue, const APInt &, std::function<bool(ConstantSDNode *)>, bool, bool);
383 SDValue, const APInt &, std::function<bool(ConstantFPSDNode *)>, bool,
384 bool);
385
387 SDValue LHS, SDValue RHS, const APInt &DemandedElts,
388 std::function<bool(ConstantSDNode *, ConstantSDNode *)> Match,
389 bool AllowUndefs, bool AllowTypeMismatch) {
390 if (!AllowTypeMismatch && LHS.getValueType() != RHS.getValueType())
391 return false;
392
393 // TODO: Add support for scalar UNDEF cases?
394 if (auto *LHSCst = dyn_cast<ConstantSDNode>(LHS))
395 if (auto *RHSCst = dyn_cast<ConstantSDNode>(RHS))
396 return Match(LHSCst, RHSCst);
397
398 // TODO: Add support for vector UNDEF cases?
399 if (LHS.getOpcode() != RHS.getOpcode() ||
400 (LHS.getOpcode() != ISD::BUILD_VECTOR &&
401 LHS.getOpcode() != ISD::SPLAT_VECTOR))
402 return false;
403
404 if (ISD::SPLAT_VECTOR == LHS.getOpcode() && !DemandedElts)
405 return true;
406
407 EVT SVT = LHS.getValueType().getScalarType();
408 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
409 if (ISD::SPLAT_VECTOR != LHS.getOpcode() && !DemandedElts[i])
410 continue;
411 SDValue LHSOp = LHS.getOperand(i);
412 SDValue RHSOp = RHS.getOperand(i);
413 bool LHSUndef = AllowUndefs && LHSOp.isUndef();
414 bool RHSUndef = AllowUndefs && RHSOp.isUndef();
415 auto *LHSCst = dyn_cast<ConstantSDNode>(LHSOp);
416 auto *RHSCst = dyn_cast<ConstantSDNode>(RHSOp);
417 if ((!LHSCst && !LHSUndef) || (!RHSCst && !RHSUndef))
418 return false;
419 if (!AllowTypeMismatch && (LHSOp.getValueType() != SVT ||
420 LHSOp.getValueType() != RHSOp.getValueType()))
421 return false;
422 if (!Match(LHSCst, RHSCst))
423 return false;
424 }
425 return true;
426}
427
429 switch (MinMaxOpc) {
430 default:
431 llvm_unreachable("unrecognized opcode");
432 case ISD::UMIN:
433 return ISD::UMAX;
434 case ISD::UMAX:
435 return ISD::UMIN;
436 case ISD::SMIN:
437 return ISD::SMAX;
438 case ISD::SMAX:
439 return ISD::SMIN;
440 }
441}
442
444 switch (MinMaxOpc) {
445 default:
446 llvm_unreachable("unrecognized min/max opcode");
447 case ISD::SMIN:
448 return ISD::UMIN;
449 case ISD::SMAX:
450 return ISD::UMAX;
451 case ISD::UMIN:
452 return ISD::SMIN;
453 case ISD::UMAX:
454 return ISD::SMAX;
455 }
456}
457
459 switch (VecReduceOpcode) {
460 default:
461 llvm_unreachable("Expected VECREDUCE opcode");
464 case ISD::VP_REDUCE_FADD:
465 case ISD::VP_REDUCE_SEQ_FADD:
466 return ISD::FADD;
469 case ISD::VP_REDUCE_FMUL:
470 case ISD::VP_REDUCE_SEQ_FMUL:
471 return ISD::FMUL;
473 case ISD::VP_REDUCE_ADD:
474 return ISD::ADD;
476 case ISD::VP_REDUCE_MUL:
477 return ISD::MUL;
479 case ISD::VP_REDUCE_AND:
480 return ISD::AND;
482 case ISD::VP_REDUCE_OR:
483 return ISD::OR;
485 case ISD::VP_REDUCE_XOR:
486 return ISD::XOR;
488 case ISD::VP_REDUCE_SMAX:
489 return ISD::SMAX;
491 case ISD::VP_REDUCE_SMIN:
492 return ISD::SMIN;
494 case ISD::VP_REDUCE_UMAX:
495 return ISD::UMAX;
497 case ISD::VP_REDUCE_UMIN:
498 return ISD::UMIN;
500 case ISD::VP_REDUCE_FMAX:
501 return ISD::FMAXNUM;
503 case ISD::VP_REDUCE_FMIN:
504 return ISD::FMINNUM;
506 case ISD::VP_REDUCE_FMAXIMUM:
507 return ISD::FMAXIMUM;
509 case ISD::VP_REDUCE_FMINIMUM:
510 return ISD::FMINIMUM;
512 return ISD::FMAXIMUMNUM;
514 return ISD::FMINIMUMNUM;
515 }
516}
517
519 switch (MaskedOpc) {
520 case ISD::MASKED_UDIV:
521 return ISD::UDIV;
522 case ISD::MASKED_SDIV:
523 return ISD::SDIV;
524 case ISD::MASKED_UREM:
525 return ISD::UREM;
526 case ISD::MASKED_SREM:
527 return ISD::SREM;
528 default:
529 llvm_unreachable("Expected masked binop opcode");
530 }
531}
532
533bool ISD::isVPOpcode(unsigned Opcode) {
534 switch (Opcode) {
535 default:
536 return false;
537#define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) \
538 case ISD::VPSD: \
539 return true;
540#include "llvm/IR/VPIntrinsics.def"
541 }
542}
543
544bool ISD::isVPBinaryOp(unsigned Opcode) {
545 switch (Opcode) {
546 default:
547 break;
548#define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) case ISD::VPSD:
549#define VP_PROPERTY_BINARYOP return true;
550#define END_REGISTER_VP_SDNODE(VPSD) break;
551#include "llvm/IR/VPIntrinsics.def"
552 }
553 return false;
554}
555
556bool ISD::isVPReduction(unsigned Opcode) {
557 switch (Opcode) {
558 default:
559 return false;
560 case ISD::VP_REDUCE_ADD:
561 case ISD::VP_REDUCE_MUL:
562 case ISD::VP_REDUCE_AND:
563 case ISD::VP_REDUCE_OR:
564 case ISD::VP_REDUCE_XOR:
565 case ISD::VP_REDUCE_SMAX:
566 case ISD::VP_REDUCE_SMIN:
567 case ISD::VP_REDUCE_UMAX:
568 case ISD::VP_REDUCE_UMIN:
569 case ISD::VP_REDUCE_FMAX:
570 case ISD::VP_REDUCE_FMIN:
571 case ISD::VP_REDUCE_FMAXIMUM:
572 case ISD::VP_REDUCE_FMINIMUM:
573 case ISD::VP_REDUCE_FADD:
574 case ISD::VP_REDUCE_FMUL:
575 case ISD::VP_REDUCE_SEQ_FADD:
576 case ISD::VP_REDUCE_SEQ_FMUL:
577 return true;
578 }
579}
580
581/// The operand position of the vector mask.
582std::optional<unsigned> ISD::getVPMaskIdx(unsigned Opcode) {
583 switch (Opcode) {
584 default:
585 return std::nullopt;
586#define BEGIN_REGISTER_VP_SDNODE(VPSD, LEGALPOS, TDNAME, MASKPOS, ...) \
587 case ISD::VPSD: \
588 return MASKPOS;
589#include "llvm/IR/VPIntrinsics.def"
590 }
591}
592
593/// The operand position of the explicit vector length parameter.
594std::optional<unsigned> ISD::getVPExplicitVectorLengthIdx(unsigned Opcode) {
595 switch (Opcode) {
596 default:
597 return std::nullopt;
598#define BEGIN_REGISTER_VP_SDNODE(VPSD, LEGALPOS, TDNAME, MASKPOS, EVLPOS) \
599 case ISD::VPSD: \
600 return EVLPOS;
601#include "llvm/IR/VPIntrinsics.def"
602 }
603}
604
605std::optional<unsigned> ISD::getBaseOpcodeForVP(unsigned VPOpcode,
606 bool hasFPExcept) {
607 // FIXME: Return strict opcodes in case of fp exceptions.
608 switch (VPOpcode) {
609 default:
610 return std::nullopt;
611#define BEGIN_REGISTER_VP_SDNODE(VPOPC, ...) case ISD::VPOPC:
612#define VP_PROPERTY_FUNCTIONAL_SDOPC(SDOPC) return ISD::SDOPC;
613#define END_REGISTER_VP_SDNODE(VPOPC) break;
614#include "llvm/IR/VPIntrinsics.def"
615 }
616 return std::nullopt;
617}
618
619std::optional<unsigned> ISD::getVPForBaseOpcode(unsigned Opcode) {
620 switch (Opcode) {
621 default:
622 return std::nullopt;
623#define BEGIN_REGISTER_VP_SDNODE(VPOPC, ...) break;
624#define VP_PROPERTY_FUNCTIONAL_SDOPC(SDOPC) case ISD::SDOPC:
625#define END_REGISTER_VP_SDNODE(VPOPC) return ISD::VPOPC;
626#include "llvm/IR/VPIntrinsics.def"
627 }
628}
629
631 switch (ExtType) {
632 case ISD::EXTLOAD:
633 return IsFP ? ISD::FP_EXTEND : ISD::ANY_EXTEND;
634 case ISD::SEXTLOAD:
635 return ISD::SIGN_EXTEND;
636 case ISD::ZEXTLOAD:
637 return ISD::ZERO_EXTEND;
638 default:
639 break;
640 }
641
642 llvm_unreachable("Invalid LoadExtType");
643}
644
646 // To perform this operation, we just need to swap the L and G bits of the
647 // operation.
648 unsigned OldL = (Operation >> 2) & 1;
649 unsigned OldG = (Operation >> 1) & 1;
650 return ISD::CondCode((Operation & ~6) | // Keep the N, U, E bits
651 (OldL << 1) | // New G bit
652 (OldG << 2)); // New L bit.
653}
654
656 unsigned Operation = Op;
657 if (isIntegerLike)
658 Operation ^= 7; // Flip L, G, E bits, but not U.
659 else
660 Operation ^= 15; // Flip all of the condition bits.
661
663 Operation &= ~8; // Don't let N and U bits get set.
664
665 return ISD::CondCode(Operation);
666}
667
671
673 bool isIntegerLike) {
674 return getSetCCInverseImpl(Op, isIntegerLike);
675}
676
677/// For an integer comparison, return 1 if the comparison is a signed operation
678/// and 2 if the result is an unsigned comparison. Return zero if the operation
679/// does not depend on the sign of the input (setne and seteq).
680static int isSignedOp(ISD::CondCode Opcode) {
681 switch (Opcode) {
682 default: llvm_unreachable("Illegal integer setcc operation!");
683 case ISD::SETEQ:
684 case ISD::SETNE: return 0;
685 case ISD::SETLT:
686 case ISD::SETLE:
687 case ISD::SETGT:
688 case ISD::SETGE: return 1;
689 case ISD::SETULT:
690 case ISD::SETULE:
691 case ISD::SETUGT:
692 case ISD::SETUGE: return 2;
693 }
694}
695
697 EVT Type) {
698 bool IsInteger = Type.isInteger();
699 if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
700 // Cannot fold a signed integer setcc with an unsigned integer setcc.
701 return ISD::SETCC_INVALID;
702
703 unsigned Op = Op1 | Op2; // Combine all of the condition bits.
704
705 // If the N and U bits get set, then the resultant comparison DOES suddenly
706 // care about orderedness, and it is true when ordered.
707 if (Op > ISD::SETTRUE2)
708 Op &= ~16; // Clear the U bit if the N bit is set.
709
710 // Canonicalize illegal integer setcc's.
711 if (IsInteger && Op == ISD::SETUNE) // e.g. SETUGT | SETULT
712 Op = ISD::SETNE;
713
714 return ISD::CondCode(Op);
715}
716
718 EVT Type) {
719 bool IsInteger = Type.isInteger();
720 if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
721 // Cannot fold a signed setcc with an unsigned setcc.
722 return ISD::SETCC_INVALID;
723
724 // Combine all of the condition bits.
725 ISD::CondCode Result = ISD::CondCode(Op1 & Op2);
726
727 // Canonicalize illegal integer setcc's.
728 if (IsInteger) {
729 switch (Result) {
730 default: break;
731 case ISD::SETUO : Result = ISD::SETFALSE; break; // SETUGT & SETULT
732 case ISD::SETOEQ: // SETEQ & SETU[LG]E
733 case ISD::SETUEQ: Result = ISD::SETEQ ; break; // SETUGE & SETULE
734 case ISD::SETOLT: Result = ISD::SETULT ; break; // SETULT & SETNE
735 case ISD::SETOGT: Result = ISD::SETUGT ; break; // SETUGT & SETNE
736 }
737 }
738
739 return Result;
740}
741
742//===----------------------------------------------------------------------===//
743// SDNode Key Support
744//===----------------------------------------------------------------------===//
745
746/// If this is an SDNode with special info, add this info to the NodeID data.
747/// MorphNodeTo passes the opcode \p N is becoming, so \p Opc may differ from
748/// N->getOpcode() and a case may only cast to a class \p N already is.
749static void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N,
750 unsigned Opc) {
751 // Machine nodes are uniqued by opcode, value types and operands alone, as in
752 // getMachineNode; MorphNodeTo's clearMemRefs overwrites the fields below.
754 return;
755
756 switch (Opc) {
759 case ISD::MCSymbol:
760 llvm_unreachable("Should only be used on nodes with operands");
761 default: break; // Normal nodes don't need extra info.
763 case ISD::Constant: {
765 ID.AddPointer(C->getConstantIntValue());
766 ID.AddBoolean(C->isOpaque());
767 break;
768 }
770 case ISD::ConstantFP:
771 ID.AddPointer(cast<ConstantFPSDNode>(N)->getConstantFPValue());
772 break;
778 ID.AddPointer(GA->getGlobal());
779 ID.AddInteger(GA->getOffset());
780 ID.AddInteger(GA->getTargetFlags());
781 break;
782 }
783 case ISD::BasicBlock:
784 ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock());
785 break;
786 case ISD::EH_LABEL:
788 ID.AddPointer(cast<LabelSDNode>(N)->getLabel());
789 break;
791 ID.AddPointer(cast<DeactivationSymbolSDNode>(N)->getGlobal());
792 break;
793 case ISD::Register:
794 ID.AddInteger(cast<RegisterSDNode>(N)->getReg().id());
795 break;
797 ID.AddPointer(cast<RegisterMaskSDNode>(N)->getRegMask());
798 break;
799 case ISD::SRCVALUE:
800 ID.AddPointer(cast<SrcValueSDNode>(N)->getValue());
801 break;
802 case ISD::FrameIndex:
804 ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex());
805 break;
807 ID.AddInteger(cast<PseudoProbeSDNode>(N)->getGuid());
808 ID.AddInteger(cast<PseudoProbeSDNode>(N)->getIndex());
809 ID.AddInteger(cast<PseudoProbeSDNode>(N)->getAttributes());
810 break;
811 case ISD::JumpTable:
813 ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex());
814 ID.AddInteger(cast<JumpTableSDNode>(N)->getTargetFlags());
815 break;
819 ID.AddInteger(CP->getAlign().value());
820 ID.AddInteger(CP->getOffset());
823 else
824 ID.AddPointer(CP->getConstVal());
825 ID.AddInteger(CP->getTargetFlags());
826 break;
827 }
828 case ISD::TargetIndex: {
830 ID.AddInteger(TI->getIndex());
831 ID.AddInteger(TI->getOffset());
832 ID.AddInteger(TI->getTargetFlags());
833 break;
834 }
835 case ISD::LOAD: {
836 const LoadSDNode *LD = cast<LoadSDNode>(N);
837 ID.AddInteger(LD->getMemoryVT().getRawBits());
838 ID.AddInteger(LD->getRawSubclassData());
839 ID.AddInteger(LD->getPointerInfo().getAddrSpace());
840 ID.AddInteger(LD->getMemOperand()->getFlags());
841 break;
842 }
843 case ISD::STORE: {
844 const StoreSDNode *ST = cast<StoreSDNode>(N);
845 ID.AddInteger(ST->getMemoryVT().getRawBits());
846 ID.AddInteger(ST->getRawSubclassData());
847 ID.AddInteger(ST->getPointerInfo().getAddrSpace());
848 ID.AddInteger(ST->getMemOperand()->getFlags());
849 break;
850 }
851 case ISD::VP_LOAD: {
852 const VPLoadSDNode *ELD = cast<VPLoadSDNode>(N);
853 ID.AddInteger(ELD->getMemoryVT().getRawBits());
854 ID.AddInteger(ELD->getRawSubclassData());
855 ID.AddInteger(ELD->getPointerInfo().getAddrSpace());
856 ID.AddInteger(ELD->getMemOperand()->getFlags());
857 break;
858 }
859 case ISD::VP_LOAD_FF: {
860 const auto *LD = cast<VPLoadFFSDNode>(N);
861 ID.AddInteger(LD->getMemoryVT().getRawBits());
862 ID.AddInteger(LD->getRawSubclassData());
863 ID.AddInteger(LD->getPointerInfo().getAddrSpace());
864 ID.AddInteger(LD->getMemOperand()->getFlags());
865 break;
866 }
867 case ISD::VP_STORE: {
868 const VPStoreSDNode *EST = cast<VPStoreSDNode>(N);
869 ID.AddInteger(EST->getMemoryVT().getRawBits());
870 ID.AddInteger(EST->getRawSubclassData());
871 ID.AddInteger(EST->getPointerInfo().getAddrSpace());
872 ID.AddInteger(EST->getMemOperand()->getFlags());
873 break;
874 }
875 case ISD::EXPERIMENTAL_VP_STRIDED_LOAD: {
877 ID.AddInteger(SLD->getMemoryVT().getRawBits());
878 ID.AddInteger(SLD->getRawSubclassData());
879 ID.AddInteger(SLD->getPointerInfo().getAddrSpace());
880 break;
881 }
882 case ISD::EXPERIMENTAL_VP_STRIDED_STORE: {
884 ID.AddInteger(SST->getMemoryVT().getRawBits());
885 ID.AddInteger(SST->getRawSubclassData());
886 ID.AddInteger(SST->getPointerInfo().getAddrSpace());
887 break;
888 }
889 case ISD::VP_GATHER: {
891 ID.AddInteger(EG->getMemoryVT().getRawBits());
892 ID.AddInteger(EG->getRawSubclassData());
893 ID.AddInteger(EG->getPointerInfo().getAddrSpace());
894 ID.AddInteger(EG->getMemOperand()->getFlags());
895 break;
896 }
897 case ISD::VP_SCATTER: {
899 ID.AddInteger(ES->getMemoryVT().getRawBits());
900 ID.AddInteger(ES->getRawSubclassData());
901 ID.AddInteger(ES->getPointerInfo().getAddrSpace());
902 ID.AddInteger(ES->getMemOperand()->getFlags());
903 break;
904 }
905 case ISD::MLOAD: {
907 ID.AddInteger(MLD->getMemoryVT().getRawBits());
908 ID.AddInteger(MLD->getRawSubclassData());
909 ID.AddInteger(MLD->getPointerInfo().getAddrSpace());
910 ID.AddInteger(MLD->getMemOperand()->getFlags());
911 break;
912 }
913 case ISD::MSTORE: {
915 ID.AddInteger(MST->getMemoryVT().getRawBits());
916 ID.AddInteger(MST->getRawSubclassData());
917 ID.AddInteger(MST->getPointerInfo().getAddrSpace());
918 ID.AddInteger(MST->getMemOperand()->getFlags());
919 break;
920 }
921 case ISD::MGATHER: {
923 ID.AddInteger(MG->getMemoryVT().getRawBits());
924 ID.AddInteger(MG->getRawSubclassData());
925 ID.AddInteger(MG->getPointerInfo().getAddrSpace());
926 ID.AddInteger(MG->getMemOperand()->getFlags());
927 break;
928 }
929 case ISD::MSCATTER:
933 const MemSDNode *M = cast<MemSDNode>(N);
934 ID.AddInteger(M->getMemoryVT().getRawBits());
935 ID.AddInteger(M->getRawSubclassData());
936 ID.AddInteger(M->getPointerInfo().getAddrSpace());
937 ID.AddInteger(M->getMemOperand()->getFlags());
938 break;
939 }
940 case ISD::VECTOR_SHUFFLE: {
941 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(N)->getMask();
942 for (int M : Mask)
943 ID.AddInteger(M);
944 break;
945 }
946 case ISD::ADDRSPACECAST: {
948 ID.AddInteger(ASC->getSrcAddressSpace());
949 ID.AddInteger(ASC->getDestAddressSpace());
950 break;
951 }
953 case ISD::BlockAddress: {
955 ID.AddPointer(BA->getBlockAddress());
956 ID.AddInteger(BA->getOffset());
957 ID.AddInteger(BA->getTargetFlags());
958 break;
959 }
960 case ISD::AssertAlign:
961 ID.AddInteger(cast<AssertAlignSDNode>(N)->getAlign().value());
962 break;
963 case ISD::PREFETCH:
966 // Handled by MemIntrinsicSDNode check after the switch.
967 break;
969 ID.AddPointer(cast<MDNodeSDNode>(N)->getMD());
970 break;
971 } // end switch (Opc)
972
973 if (auto *AT = dyn_cast<AtomicSDNode>(N)) {
974 ID.AddInteger(AT->getMemoryVT().getRawBits());
975 ID.AddInteger(AT->getRawSubclassData());
976 ID.AddInteger(AT->getPointerInfo().getAddrSpace());
977 ID.AddInteger(AT->getMemOperand()->getFlags());
978 }
979
980 // MemIntrinsic nodes could also have subclass data, address spaces, and flags
981 // to check.
982 if (auto *MN = dyn_cast<MemIntrinsicSDNode>(N)) {
983 ID.AddInteger(MN->getRawSubclassData());
984 ID.AddInteger(MN->getMemoryVT().getRawBits());
985 for (const MachineMemOperand *MMO : MN->memoperands()) {
986 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
987 ID.AddInteger(MMO->getFlags());
988 }
989 }
990}
991
993 : Opcode(N.getOpcode()), VTs(N.getVTList().VTs),
994 OpStorage(N.op_begin(), N.op_end()) {
995 Ops = OpStorage;
996 AddNodeIDCustom(Tail, &N, N.getOpcode());
997}
998
999#ifndef NDEBUG
1000/// Serialize a node the way SDNodes were uniqued before SDNodeKey, to
1001/// cross-check the typed comparison against. Deliberately reads the node
1002/// rather than going through SDNodeKey, so the key constructor is checked too
1003/// and not used as its own oracle.
1004static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) {
1005 ID.AddInteger(N->getOpcode());
1006 ID.AddPointer(N->getVTList().VTs);
1007 for (const SDUse &Op : N->ops()) {
1008 ID.AddPointer(Op.getNode());
1009 ID.AddInteger(Op.getResNo());
1010 }
1011 AddNodeIDCustom(ID, N, N->getOpcode());
1012}
1013
1015 ID.AddInteger(Key.Opcode);
1016 ID.AddPointer(Key.VTs);
1017 for (const SDValue &Op : Key.Ops) {
1018 ID.AddPointer(Op.getNode());
1019 ID.AddInteger(Op.getResNo());
1020 }
1021 ID.AddNodeID(Key.Tail);
1022}
1023#endif
1024
1025static bool keyMatches(const SDNodeKey &Key, const SDNode &N) {
1026 if (N.getOpcode() != Key.Opcode || N.getVTList().VTs != Key.VTs)
1027 return false;
1028 if (!llvm::equal(N.ops(), Key.Ops))
1029 return false;
1030 // Build only what AddNodeIDCustom would have added, which is nothing for
1031 // most opcodes, rather than the whole profile.
1032 FoldingSetNodeID Tail;
1033 AddNodeIDCustom(Tail, &N, N.getOpcode());
1034 return Tail == Key.Tail;
1035}
1036
1038 bool Result = keyMatches(Key, N);
1039
1040#ifndef NDEBUG
1041 FoldingSetNodeID NodeProfile, KeyProfile;
1042 AddNodeIDNode(NodeProfile, &N);
1043 AddNodeIDNode(KeyProfile, Key);
1044 assert((NodeProfile == KeyProfile) == Result &&
1045 "SDNodeKey equality disagrees with profile");
1046#endif
1047 return Result;
1048}
1049
1050//===----------------------------------------------------------------------===//
1051// SelectionDAG Class
1052//===----------------------------------------------------------------------===//
1053
1054/// doNotCSE - Return true if CSE should not be performed for this node.
1055static bool doNotCSE(SDNode *N) {
1056 if (N->getValueType(0) == MVT::Glue)
1057 return true; // Never CSE anything that produces a glue result.
1058
1059 switch (N->getOpcode()) {
1060 default: break;
1061 case ISD::HANDLENODE:
1062 case ISD::EH_LABEL:
1063 return true; // Never CSE these nodes.
1064 }
1065
1066 // Check that remaining values produced are not flags.
1067 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
1068 if (N->getValueType(i) == MVT::Glue)
1069 return true; // Never CSE anything that produces a glue result.
1070
1071 return false;
1072}
1073
1074/// Construct a DemandedElts mask which demands all elements of \p V.
1075/// If \p V is not a fixed-length vector, then this will return a single bit.
1077 EVT VT = V.getValueType();
1078 // Since the number of lanes in a scalable vector is unknown at compile time,
1079 // we track one bit which is implicitly broadcast to all lanes. This means
1080 // that all lanes in a scalable vector are considered demanded.
1082 : APInt(1, 1);
1083}
1084
1085/// RemoveDeadNodes - This method deletes all unreachable nodes in the
1086/// SelectionDAG.
1088 // Create a dummy node (which is not added to allnodes), that adds a reference
1089 // to the root node, preventing it from being deleted.
1090 HandleSDNode Dummy(getRoot());
1091
1092 SmallVector<SDNode*, 128> DeadNodes;
1093
1094 // Add all obviously-dead nodes to the DeadNodes worklist.
1095 for (SDNode &Node : allnodes())
1096 if (Node.use_empty())
1097 DeadNodes.push_back(&Node);
1098
1099 RemoveDeadNodes(DeadNodes);
1100
1101 // If the root changed (e.g. it was a dead load, update the root).
1102 setRoot(Dummy.getValue());
1103}
1104
1105/// RemoveDeadNodes - This method deletes the unreachable nodes in the
1106/// given list, and any nodes that become unreachable as a result.
1108
1109 // Process the worklist, deleting the nodes and adding their uses to the
1110 // worklist.
1111 while (!DeadNodes.empty()) {
1112 SDNode *N = DeadNodes.pop_back_val();
1113 // Skip to next node if we've already managed to delete the node. This could
1114 // happen if replacing a node causes a node previously added to the node to
1115 // be deleted.
1116 if (N->getOpcode() == ISD::DELETED_NODE)
1117 continue;
1118
1119 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1120 DUL->NodeDeleted(N, nullptr);
1121
1122 // Take the node out of the appropriate CSE map.
1123 RemoveNodeFromCSEMaps(N);
1124
1125 // Next, brutally remove the operand list. This is safe to do, as there are
1126 // no cycles in the graph.
1127 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
1128 SDUse &Use = *I++;
1129 SDNode *Operand = Use.getNode();
1130 Use.set(SDValue());
1131
1132 // Now that we removed this operand, see if there are no uses of it left.
1133 if (Operand->use_empty())
1134 DeadNodes.push_back(Operand);
1135 }
1136
1137 DeallocateNode(N);
1138 }
1139}
1140
1142 SmallVector<SDNode*, 16> DeadNodes(1, N);
1143
1144 // Create a dummy node that adds a reference to the root node, preventing
1145 // it from being deleted. (This matters if the root is an operand of the
1146 // dead node.)
1147 HandleSDNode Dummy(getRoot());
1148
1149 RemoveDeadNodes(DeadNodes);
1150}
1151
1153 // First take this out of the appropriate CSE map.
1154 RemoveNodeFromCSEMaps(N);
1155
1156 // Finally, remove uses due to operands of this node, remove from the
1157 // AllNodes list, and delete the node.
1158 DeleteNodeNotInCSEMaps(N);
1159}
1160
1161void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
1162 assert(N->getIterator() != AllNodes.begin() &&
1163 "Cannot delete the entry node!");
1164 assert(N->use_empty() && "Cannot delete a node that is not dead!");
1165
1166 // Drop all of the operands and decrement used node's use counts.
1167 N->DropOperands();
1168
1169 DeallocateNode(N);
1170}
1171
1172void SDDbgInfo::add(SDDbgValue *V, bool isParameter) {
1173 assert(!(V->isVariadic() && isParameter));
1174 if (isParameter)
1175 ByvalParmDbgValues.push_back(V);
1176 else
1177 DbgValues.push_back(V);
1178 for (const SDNode *Node : V->getSDNodes())
1179 if (Node)
1180 DbgValMap[Node].push_back(V);
1181}
1182
1184 DbgValMapType::iterator I = DbgValMap.find(Node);
1185 if (I == DbgValMap.end())
1186 return;
1187 for (auto &Val: I->second)
1188 Val->setIsInvalidated();
1189 DbgValMap.erase(I);
1190}
1191
1192void SelectionDAG::DeallocateNode(SDNode *N) {
1193 // If we have operands, deallocate them.
1195
1196 NodeAllocator.Deallocate(AllNodes.remove(N));
1197
1198 // Set the opcode to DELETED_NODE to help catch bugs when node
1199 // memory is reallocated.
1200 // FIXME: There are places in SDag that have grown a dependency on the opcode
1201 // value in the released node.
1202 __asan_unpoison_memory_region(&N->NodeType, sizeof(N->NodeType));
1203 N->NodeType = ISD::DELETED_NODE;
1204
1205 // If any of the SDDbgValue nodes refer to this SDNode, invalidate
1206 // them and forget about that node.
1207 DbgInfo->erase(N);
1208
1209 // Invalidate extra info.
1210 SDEI.erase(N);
1211}
1212
1213#ifndef NDEBUG
1214/// VerifySDNode - Check the given SDNode. Aborts if it is invalid.
1215void SelectionDAG::verifyNode(SDNode *N) const {
1216 switch (N->getOpcode()) {
1217 default:
1218 if (N->isTargetOpcode())
1220 break;
1221 case ISD::BUILD_PAIR: {
1222 EVT VT = N->getValueType(0);
1223 assert(N->getNumValues() == 1 && "Too many results!");
1224 assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) &&
1225 "Wrong return type!");
1226 assert(N->getNumOperands() == 2 && "Wrong number of operands!");
1227 assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() &&
1228 "Mismatched operand types!");
1229 assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() &&
1230 "Wrong operand type!");
1231 assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() &&
1232 "Wrong return type size");
1233 break;
1234 }
1235 case ISD::BUILD_VECTOR: {
1236 assert(N->getNumValues() == 1 && "Too many results!");
1237 assert(N->getValueType(0).isVector() && "Wrong return type!");
1238 assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() &&
1239 "Wrong number of operands!");
1240 EVT EltVT = N->getValueType(0).getVectorElementType();
1241 for (const SDUse &Op : N->ops()) {
1242 assert((Op.getValueType() == EltVT ||
1243 (EltVT.isInteger() && Op.getValueType().isInteger() &&
1244 EltVT.bitsLE(Op.getValueType()))) &&
1245 "Wrong operand type!");
1246 assert(Op.getValueType() == N->getOperand(0).getValueType() &&
1247 "Operands must all have the same type");
1248 }
1249 break;
1250 }
1251 case ISD::SADDO:
1252 case ISD::UADDO:
1253 case ISD::SSUBO:
1254 case ISD::USUBO:
1255 assert(N->getNumValues() == 2 && "Wrong number of results!");
1256 assert(N->getVTList().NumVTs == 2 && N->getNumOperands() == 2 &&
1257 "Invalid add/sub overflow op!");
1258 assert(N->getVTList().VTs[0].isInteger() &&
1259 N->getVTList().VTs[1].isInteger() &&
1260 N->getOperand(0).getValueType() == N->getOperand(1).getValueType() &&
1261 N->getOperand(0).getValueType() == N->getVTList().VTs[0] &&
1262 "Binary operator types must match!");
1263 break;
1264 }
1265}
1266#endif // NDEBUG
1267
1268/// Insert a newly allocated node into the DAG.
1269///
1270/// Handles insertion into the all nodes list and CSE map, as well as
1271/// verification and other common operations when a new node is allocated.
1272void SelectionDAG::InsertNode(SDNode *N) {
1273 AllNodes.push_back(N);
1274#ifndef NDEBUG
1275 N->PersistentId = NextPersistentId++;
1276 verifyNode(N);
1277#endif
1278 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1279 DUL->NodeInserted(N);
1280}
1281
1282/// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
1283/// correspond to it. This is useful when we're about to delete or repurpose
1284/// the node. We don't want future request for structurally identical nodes
1285/// to return N anymore.
1286bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
1287 bool Erased = false;
1288 switch (N->getOpcode()) {
1289 case ISD::HANDLENODE: return false; // noop.
1290 case ISD::CONDCODE:
1291 assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
1292 "Cond code doesn't exist!");
1293 Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != nullptr;
1294 CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = nullptr;
1295 break;
1297 Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
1298 break;
1300 ExternalSymbolSDNode *ESN = cast<ExternalSymbolSDNode>(N);
1301 Erased = TargetExternalSymbols.erase(std::pair<std::string, unsigned>(
1302 ESN->getSymbol(), ESN->getTargetFlags()));
1303 break;
1304 }
1305 case ISD::MCSymbol: {
1306 auto *MCSN = cast<MCSymbolSDNode>(N);
1307 Erased = MCSymbols.erase(MCSN->getMCSymbol());
1308 break;
1309 }
1310 case ISD::VALUETYPE: {
1311 EVT VT = cast<VTSDNode>(N)->getVT();
1312 if (VT.isExtended()) {
1313 Erased = ExtendedValueTypeNodes.erase(VT);
1314 } else {
1315 Erased = ValueTypeNodes[VT.getSimpleVT().SimpleTy] != nullptr;
1316 ValueTypeNodes[VT.getSimpleVT().SimpleTy] = nullptr;
1317 }
1318 break;
1319 }
1320 default:
1321 // Remove it from the CSE Map.
1322 assert(N->getOpcode() != ISD::DELETED_NODE && "DELETED_NODE in CSEMap!");
1323 assert(N->getOpcode() != ISD::EntryToken && "EntryToken in CSEMap!");
1324 Erased = CSEMap.erase(N);
1325 break;
1326 }
1327#ifndef NDEBUG
1328 // Verify that the node was actually in one of the CSE maps, unless it has a
1329 // glue result (which cannot be CSE'd) or is one of the special cases that are
1330 // not subject to CSE.
1331 if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Glue &&
1332 !N->isMachineOpcode() && !doNotCSE(N)) {
1333 N->dump(this);
1334 dbgs() << "\n";
1335 llvm_unreachable("Node is not in map!");
1336 }
1337#endif
1338 return Erased;
1339}
1340
1341/// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE
1342/// maps and modified in place. Add it back to the CSE maps, unless an identical
1343/// node already exists, in which case transfer all its users to the existing
1344/// node. This transfer can potentially trigger recursive merging.
1345void
1346SelectionDAG::AddModifiedNodeToCSEMaps(SDNode *N) {
1347 // For node types that aren't CSE'd, just act as if no identical node
1348 // already exists.
1349 if (!doNotCSE(N)) {
1350 SDNode *Existing = CSEMap.getOrInsert(N);
1351 if (Existing != N) {
1352 // If there was already an existing matching node, use ReplaceAllUsesWith
1353 // to replace the dead one with the existing one. This can cause
1354 // recursive merging of other unrelated nodes down the line.
1355 Existing->intersectFlagsWith(N->getFlags());
1356 if (auto *MemNode = dyn_cast<MemSDNode>(Existing)) {
1358 cast<MemSDNode>(N)->memoperands();
1359 // Range and cache hint metadata are not part of the DAG CSE key because
1360 // we prefer to CSE even when metadata does not match. Merge potentially
1361 // differing metadata conservatively.
1362 MemNode->refineMMOMetadata(NewMMOs);
1363 }
1364 ReplaceAllUsesWith(N, Existing);
1365
1366 // N is now dead. Inform the listeners and delete it.
1367 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1368 DUL->NodeDeleted(N, Existing);
1369 DeleteNodeNotInCSEMaps(N);
1370 return;
1371 }
1372 }
1373
1374 // If the node doesn't already exist, we updated it. Inform listeners.
1375 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1376 DUL->NodeUpdated(N);
1377}
1378
1379/// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1380/// were replaced with those specified. If this node is never memoized,
1381/// return null, otherwise return a pointer to the slot it would take. If a
1382/// node already exists with these operands, the slot will be non-null.
1383SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op,
1384 FoldingSetInsertToken &InsertToken) {
1385 if (doNotCSE(N))
1386 return nullptr;
1387
1388 SDValue Ops[] = { Op };
1389 SDNodeKey ID(N->getOpcode(), N->getVTList(), Ops);
1390 AddNodeIDCustom(ID.Tail, N, N->getOpcode());
1391 SDNode *Node = lookupNode(ID, SDLoc(N), InsertToken);
1392 if (Node)
1393 Node->intersectFlagsWith(N->getFlags());
1394 return Node;
1395}
1396
1397/// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1398/// were replaced with those specified. If this node is never memoized,
1399/// return null, otherwise return a pointer to the slot it would take. If a
1400/// node already exists with these operands, the slot will be non-null.
1401SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op1, SDValue Op2,
1402 FoldingSetInsertToken &InsertToken) {
1403 if (doNotCSE(N))
1404 return nullptr;
1405
1406 SDValue Ops[] = { Op1, Op2 };
1407 SDNodeKey ID(N->getOpcode(), N->getVTList(), Ops);
1408 AddNodeIDCustom(ID.Tail, N, N->getOpcode());
1409 SDNode *Node = lookupNode(ID, SDLoc(N), InsertToken);
1410 if (Node)
1411 Node->intersectFlagsWith(N->getFlags());
1412 return Node;
1413}
1414
1415/// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1416/// were replaced with those specified. If this node is never memoized,
1417/// return null, otherwise return a pointer to the slot it would take. If a
1418/// node already exists with these operands, the slot will be non-null.
1419SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, ArrayRef<SDValue> Ops,
1420 FoldingSetInsertToken &InsertToken) {
1421 if (doNotCSE(N))
1422 return nullptr;
1423
1424 SDNodeKey ID(N->getOpcode(), N->getVTList(), Ops);
1425 AddNodeIDCustom(ID.Tail, N, N->getOpcode());
1426 SDNode *Node = lookupNode(ID, SDLoc(N), InsertToken);
1427 if (Node)
1428 Node->intersectFlagsWith(N->getFlags());
1429 return Node;
1430}
1431
1433 Type *Ty = VT == MVT::iPTR ? PointerType::get(*getContext(), 0)
1434 : VT.getTypeForEVT(*getContext());
1435
1436 return getDataLayout().getABITypeAlign(Ty);
1437}
1438
1439// EntryNode could meaningfully have debug info if we can find it...
1441 : TM(tm), OptLevel(OL), EntryNode(ISD::EntryToken, 0, DebugLoc(),
1442 getVTList(MVT::Other, MVT::Glue)),
1443 Root(getEntryNode()) {
1444 InsertNode(&EntryNode);
1445 DbgInfo = new SDDbgInfo();
1446}
1447
1449 const TargetLibraryInfo *LibraryInfo,
1450 const LibcallLoweringInfo *LibcallsInfo,
1451 UniformityInfo *NewUA, ProfileSummaryInfo *PSIin,
1452 BlockFrequencyInfo *BFIin,
1453 FunctionVarLocs const *VarLocs) {
1454 MF = &NewMF;
1457 LibInfo = LibraryInfo;
1458 Libcalls = LibcallsInfo;
1459 Context = &MF->getFunction().getContext();
1460 DAGOpts = &Context->getLibraryOptions().get<SelectionDAGOptions>();
1461 UA = NewUA;
1462 PSI = PSIin;
1463 BFI = BFIin;
1464 FnVarLocs = VarLocs;
1465}
1466
1468 assert(!UpdateListeners && "Dangling registered DAGUpdateListeners");
1469 allnodes_clear();
1470 OperandRecycler.clear(OperandAllocator);
1471 delete DbgInfo;
1472}
1473
1475 return llvm::shouldOptimizeForSize(FLI->MBB->getBasicBlock(), PSI, BFI);
1476}
1477
1479 return FLI->MBB->getBasicBlock();
1480}
1481
1482void SelectionDAG::allnodes_clear() {
1483 assert(&*AllNodes.begin() == &EntryNode);
1484 AllNodes.remove(AllNodes.begin());
1485 while (!AllNodes.empty())
1486 DeallocateNode(&AllNodes.front());
1487#ifndef NDEBUG
1488 NextPersistentId = 0;
1489#endif
1490}
1491
1492SDNode *SelectionDAG::lookupNode(const SDNodeKey &Key,
1493 FoldingSetInsertToken &InsertToken) {
1494 SDNode *N = CSEMap.lookup(Key, InsertToken);
1495 if (N) {
1496 switch (N->getOpcode()) {
1497 default: break;
1498 case ISD::Constant:
1499 case ISD::ConstantFP:
1500 llvm_unreachable("Querying for Constant and ConstantFP nodes requires "
1501 "debug location. Use another overload.");
1502 }
1503 }
1504 return N;
1505}
1506
1507SDNode *SelectionDAG::lookupNode(const SDNodeKey &Key, const SDLoc &DL,
1508 FoldingSetInsertToken &InsertToken) {
1509 SDNode *N = CSEMap.lookup(Key, InsertToken);
1510 if (N) {
1511 switch (N->getOpcode()) {
1512 case ISD::Constant:
1513 case ISD::ConstantFP:
1514 // Erase debug location from the node if the node is used at several
1515 // different places. Do not propagate one location to all uses as it
1516 // will cause a worse single stepping debugging experience.
1517 if (N->getDebugLoc() != DL.getDebugLoc())
1518 N->setDebugLoc(DebugLoc());
1519 break;
1520 default:
1521 // When the node's point of use is located earlier in the instruction
1522 // sequence than its prior point of use, update its debug info to the
1523 // earlier location.
1524 if (DL.getIROrder() && DL.getIROrder() < N->getIROrder())
1525 N->setDebugLoc(DL.getDebugLoc());
1526 break;
1527 }
1528 }
1529 return N;
1530}
1531
1533 allnodes_clear();
1534 OperandRecycler.clear(OperandAllocator);
1535 OperandAllocator.Reset();
1536 CSEMap.clear();
1537
1538 ExtendedValueTypeNodes.clear();
1539 ExternalSymbols.clear();
1540 TargetExternalSymbols.clear();
1541 MCSymbols.clear();
1542 SDEI.clear();
1543 llvm::fill(CondCodeNodes, nullptr);
1544 llvm::fill(ValueTypeNodes, nullptr);
1545
1546 EntryNode.UseList = nullptr;
1547 InsertNode(&EntryNode);
1548 Root = getEntryNode();
1549 DbgInfo->clear();
1550}
1551
1553 return VT.bitsGT(Op.getValueType())
1554 ? getNode(ISD::FP_EXTEND, DL, VT, Op)
1555 : getNode(ISD::FP_ROUND, DL, VT, Op,
1556 getIntPtrConstant(0, DL, /*isTarget=*/true));
1557}
1558
1559std::pair<SDValue, SDValue>
1561 const SDLoc &DL, EVT VT) {
1562 assert(!VT.bitsEq(Op.getValueType()) &&
1563 "Strict no-op FP extend/round not allowed.");
1564 SDValue Res =
1565 VT.bitsGT(Op.getValueType())
1566 ? getNode(ISD::STRICT_FP_EXTEND, DL, {VT, MVT::Other}, {Chain, Op})
1567 : getNode(ISD::STRICT_FP_ROUND, DL, {VT, MVT::Other},
1568 {Chain, Op, getIntPtrConstant(0, DL, /*isTarget=*/true)});
1569
1570 return std::pair<SDValue, SDValue>(Res, SDValue(Res.getNode(), 1));
1571}
1572
1574 return VT.bitsGT(Op.getValueType()) ?
1575 getNode(ISD::ANY_EXTEND, DL, VT, Op) :
1576 getNode(ISD::TRUNCATE, DL, VT, Op);
1577}
1578
1580 return VT.bitsGT(Op.getValueType()) ?
1581 getNode(ISD::SIGN_EXTEND, DL, VT, Op) :
1582 getNode(ISD::TRUNCATE, DL, VT, Op);
1583}
1584
1586 return VT.bitsGT(Op.getValueType()) ?
1587 getNode(ISD::ZERO_EXTEND, DL, VT, Op) :
1588 getNode(ISD::TRUNCATE, DL, VT, Op);
1589}
1590
1592 EVT VT) {
1593 assert(!VT.isVector());
1594 auto Type = Op.getValueType();
1595 SDValue DestOp;
1596 if (Type == VT)
1597 return Op;
1598 auto Size = Op.getValueSizeInBits();
1599 DestOp = getBitcast(EVT::getIntegerVT(*Context, Size), Op);
1600 if (DestOp.getValueType() == VT)
1601 return DestOp;
1602
1603 return getAnyExtOrTrunc(DestOp, DL, VT);
1604}
1605
1607 EVT OpVT) {
1608 if (VT.bitsLE(Op.getValueType()))
1609 return getNode(ISD::TRUNCATE, SL, VT, Op);
1610
1611 TargetLowering::BooleanContent BType = TLI->getBooleanContents(OpVT);
1612 return getNode(TLI->getExtendForContent(BType), SL, VT, Op);
1613}
1614
1616 EVT OpVT = Op.getValueType();
1617 assert(VT.isInteger() && OpVT.isInteger() &&
1618 "Cannot getZeroExtendInReg FP types");
1619 assert(VT.isVector() == OpVT.isVector() &&
1620 "getZeroExtendInReg type should be vector iff the operand "
1621 "type is vector!");
1622 assert((!VT.isVector() ||
1624 "Vector element counts must match in getZeroExtendInReg");
1625 assert(VT.getScalarType().bitsLE(OpVT.getScalarType()) && "Not extending!");
1626 if (OpVT == VT)
1627 return Op;
1628 // TODO: Use computeKnownBits instead of AssertZext.
1629 if (Op.getOpcode() == ISD::AssertZext && cast<VTSDNode>(Op.getOperand(1))
1630 ->getVT()
1631 .getScalarType()
1632 .bitsLE(VT.getScalarType()))
1633 return Op;
1635 VT.getScalarSizeInBits());
1636 return getNode(ISD::AND, DL, OpVT, Op, getConstant(Imm, DL, OpVT));
1637}
1638
1640 // Only unsigned pointer semantics are supported right now. In the future this
1641 // might delegate to TLI to check pointer signedness.
1642 return getZExtOrTrunc(Op, DL, VT);
1643}
1644
1646 // Only unsigned pointer semantics are supported right now. In the future this
1647 // might delegate to TLI to check pointer signedness.
1648 return getZeroExtendInReg(Op, DL, VT);
1649}
1650
1652 return getNode(ISD::SUB, DL, VT, getConstant(0, DL, VT), Val);
1653}
1654
1655/// getNOT - Create a bitwise NOT operation as (XOR Val, -1).
1657 return getNode(ISD::XOR, DL, VT, Val, getAllOnesConstant(DL, VT));
1658}
1659
1661 SDValue TrueValue = getBoolConstant(true, DL, VT, VT);
1662 return getNode(ISD::XOR, DL, VT, Val, TrueValue);
1663}
1664
1666 EVT OpVT) {
1667 if (!V)
1668 return getConstant(0, DL, VT);
1669
1670 switch (TLI->getBooleanContents(OpVT)) {
1673 return getConstant(1, DL, VT);
1675 return getAllOnesConstant(DL, VT);
1676 }
1677 llvm_unreachable("Unexpected boolean content enum!");
1678}
1679
1681 bool isT, bool isO) {
1682 return getConstant(APInt(VT.getScalarSizeInBits(), Val, /*isSigned=*/false),
1683 DL, VT, isT, isO);
1684}
1685
1687 bool isT, bool isO) {
1688 return getConstant(*ConstantInt::get(*Context, Val), DL, VT, isT, isO);
1689}
1690
1692 EVT VT, bool isT, bool isO) {
1693 assert(VT.isInteger() && "Cannot create FP integer constant!");
1694
1695 EVT EltVT = VT.getScalarType();
1696 const ConstantInt *Elt = &Val;
1697
1698 // Vector splats are explicit within the DAG, with ConstantSDNode holding the
1699 // to-be-splatted scalar ConstantInt.
1700 if (isa<VectorType>(Elt->getType()))
1701 Elt = ConstantInt::get(*getContext(), Elt->getValue());
1702
1703 // In some cases the vector type is legal but the element type is illegal and
1704 // needs to be promoted, for example v8i8 on ARM. In this case, promote the
1705 // inserted value (the type does not need to match the vector element type).
1706 // Any extra bits introduced will be truncated away.
1707 if (VT.isVector() && TLI->getTypeAction(*getContext(), EltVT) ==
1709 EltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1710 APInt NewVal;
1711 if (TLI->isSExtCheaperThanZExt(VT.getScalarType(), EltVT))
1712 NewVal = Elt->getValue().sextOrTrunc(EltVT.getSizeInBits());
1713 else
1714 NewVal = Elt->getValue().zextOrTrunc(EltVT.getSizeInBits());
1715 Elt = ConstantInt::get(*getContext(), NewVal);
1716 }
1717 // In other cases the element type is illegal and needs to be expanded, for
1718 // example v2i64 on MIPS32. In this case, find the nearest legal type, split
1719 // the value into n parts and use a vector type with n-times the elements.
1720 // Then bitcast to the type requested.
1721 // Legalizing constants too early makes the DAGCombiner's job harder so we
1722 // only legalize if the DAG tells us we must produce legal types.
1723 else if (NewNodesMustHaveLegalTypes && VT.isVector() &&
1724 TLI->getTypeAction(*getContext(), EltVT) ==
1726 const APInt &NewVal = Elt->getValue();
1727 EVT ViaEltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1728 unsigned ViaEltSizeInBits = ViaEltVT.getSizeInBits();
1729
1730 // For scalable vectors, try to use a SPLAT_VECTOR_PARTS node.
1731 if (VT.isScalableVector() ||
1732 TLI->isOperationLegal(ISD::SPLAT_VECTOR, VT)) {
1733 assert(EltVT.getSizeInBits() % ViaEltSizeInBits == 0 &&
1734 "Can only handle an even split!");
1735 unsigned Parts = EltVT.getSizeInBits() / ViaEltSizeInBits;
1736
1737 SmallVector<SDValue, 2> ScalarParts;
1738 for (unsigned i = 0; i != Parts; ++i)
1739 ScalarParts.push_back(getConstant(
1740 NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL,
1741 ViaEltVT, isT, isO));
1742
1743 return getNode(ISD::SPLAT_VECTOR_PARTS, DL, VT, ScalarParts);
1744 }
1745
1746 unsigned ViaVecNumElts = VT.getSizeInBits() / ViaEltSizeInBits;
1747 EVT ViaVecVT = EVT::getVectorVT(*getContext(), ViaEltVT, ViaVecNumElts);
1748
1749 // Check the temporary vector is the correct size. If this fails then
1750 // getTypeToTransformTo() probably returned a type whose size (in bits)
1751 // isn't a power-of-2 factor of the requested type size.
1752 assert(ViaVecVT.getSizeInBits() == VT.getSizeInBits());
1753
1754 SmallVector<SDValue, 2> EltParts;
1755 for (unsigned i = 0; i < ViaVecNumElts / VT.getVectorNumElements(); ++i)
1756 EltParts.push_back(getConstant(
1757 NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL,
1758 ViaEltVT, isT, isO));
1759
1760 // EltParts is currently in little endian order. If we actually want
1761 // big-endian order then reverse it now.
1762 if (getDataLayout().isBigEndian())
1763 std::reverse(EltParts.begin(), EltParts.end());
1764
1765 // The elements must be reversed when the element order is different
1766 // to the endianness of the elements (because the BITCAST is itself a
1767 // vector shuffle in this situation). However, we do not need any code to
1768 // perform this reversal because getConstant() is producing a vector
1769 // splat.
1770 // This situation occurs in MIPS MSA.
1771
1773 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
1774 llvm::append_range(Ops, EltParts);
1775
1776 SDValue V =
1777 getNode(ISD::BITCAST, DL, VT, getBuildVector(ViaVecVT, DL, Ops));
1778 return V;
1779 }
1780
1781 assert(Elt->getBitWidth() == EltVT.getSizeInBits() &&
1782 "APInt size does not match type size!");
1783 unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
1784 SDVTList VTs = getVTList(EltVT);
1785 SDNodeKey ID(Opc, VTs, {});
1786 ID.AddPointer(Elt);
1787 ID.AddBoolean(isO);
1788 FoldingSetInsertToken InsertToken;
1789 SDNode *N = nullptr;
1790 if ((N = lookupNode(ID, DL, InsertToken)))
1791 if (!VT.isVector())
1792 return SDValue(N, 0);
1793
1794 if (!N) {
1795 N = newSDNode<ConstantSDNode>(isT, isO, Elt, VTs);
1796 if (!isT)
1797 N->setDebugLoc(DL.getDebugLoc());
1798 CSEMap.insert(N, InsertToken);
1799 InsertNode(N);
1800 NewSDValueDbgMsg(SDValue(N, 0), "Creating constant: ", this);
1801 }
1802
1803 SDValue Result(N, 0);
1804 if (VT.isVector())
1805 Result = getSplat(VT, DL, Result);
1806 return Result;
1807}
1808
1810 bool isT, bool isO) {
1811 unsigned Size = VT.getScalarSizeInBits();
1812 return getConstant(APInt(Size, Val, /*isSigned=*/true), DL, VT, isT, isO);
1813}
1814
1816 bool IsOpaque) {
1818 IsTarget, IsOpaque);
1819}
1820
1822 bool isTarget) {
1823 return getConstant(Val, DL, TLI->getPointerTy(getDataLayout()), isTarget);
1824}
1825
1827 const SDLoc &DL) {
1828 assert(VT.isInteger() && "Shift amount is not an integer type!");
1829 EVT ShiftVT = TLI->getShiftAmountTy(VT, getDataLayout());
1830 return getConstant(Val, DL, ShiftVT);
1831}
1832
1834 const SDLoc &DL) {
1835 assert(Val.ult(VT.getScalarSizeInBits()) && "Out of range shift");
1836 return getShiftAmountConstant(Val.getZExtValue(), VT, DL);
1837}
1838
1840 bool isTarget) {
1841 return getConstant(Val, DL, TLI->getVectorIdxTy(getDataLayout()), isTarget);
1842}
1843
1845 bool isTarget) {
1846 return getConstantFP(*ConstantFP::get(*getContext(), V), DL, VT, isTarget);
1847}
1848
1849SDValue SelectionDAG::getConstFP(std::optional<FPFoldResult> Result,
1850 const SDLoc &DL, EVT VT, bool isTarget) {
1851 return Result ? getConstantFP(Result->Value, DL, VT, isTarget) : SDValue();
1852}
1853
1855 EVT VT, bool isTarget) {
1856 assert(VT.isFloatingPoint() && "Cannot create integer FP constant!");
1857
1858 EVT EltVT = VT.getScalarType();
1859 const ConstantFP *Elt = &V;
1860
1861 // Vector splats are explicit within the DAG, with ConstantFPSDNode holding
1862 // the to-be-splatted scalar ConstantFP.
1863 if (isa<VectorType>(Elt->getType()))
1864 Elt = ConstantFP::get(*getContext(), Elt->getValue());
1865
1866 // Do the map lookup using the actual bit pattern for the floating point
1867 // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
1868 // we don't have issues with SNANs.
1869 unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
1870 SDVTList VTs = getVTList(EltVT);
1871 SDNodeKey ID(Opc, VTs, {});
1872 ID.AddPointer(Elt);
1873 FoldingSetInsertToken InsertToken;
1874 SDNode *N = nullptr;
1875 if ((N = lookupNode(ID, DL, InsertToken)))
1876 if (!VT.isVector())
1877 return SDValue(N, 0);
1878
1879 if (!N) {
1880 N = newSDNode<ConstantFPSDNode>(isTarget, Elt, VTs);
1881 CSEMap.insert(N, InsertToken);
1882 InsertNode(N);
1883 }
1884
1885 SDValue Result(N, 0);
1886 if (VT.isVector())
1887 Result = getSplat(VT, DL, Result);
1888 NewSDValueDbgMsg(Result, "Creating fp constant: ", this);
1889 return Result;
1890}
1891
1893 bool isTarget) {
1894 EVT EltVT = VT.getScalarType();
1895 if (EltVT == MVT::f32)
1896 return getConstantFP(APFloat((float)Val), DL, VT, isTarget);
1897 if (EltVT == MVT::f64)
1898 return getConstantFP(APFloat(Val), DL, VT, isTarget);
1899 if (EltVT == MVT::f80 || EltVT == MVT::f128 || EltVT == MVT::ppcf128 ||
1900 EltVT == MVT::f16 || EltVT == MVT::bf16) {
1901 bool Ignored;
1902 APFloat APF = APFloat(Val);
1904 &Ignored);
1905 return getConstantFP(APF, DL, VT, isTarget);
1906 }
1907 llvm_unreachable("Unsupported type in getConstantFP");
1908}
1909
1911 EVT VT, int64_t Offset, bool isTargetGA,
1912 unsigned TargetFlags) {
1913 assert((TargetFlags == 0 || isTargetGA) &&
1914 "Cannot set target flags on target-independent globals");
1915
1916 // Truncate (with sign-extension) the offset value to the pointer size.
1918 if (BitWidth < 64)
1920
1921 unsigned Opc;
1922 if (GV->isThreadLocal())
1924 else
1926
1927 SDVTList VTs = getVTList(VT);
1928 SDNodeKey ID(Opc, VTs, {});
1929 ID.AddPointer(GV);
1930 ID.AddInteger(Offset);
1931 ID.AddInteger(TargetFlags);
1932 FoldingSetInsertToken InsertToken;
1933 if (SDNode *E = lookupNode(ID, DL, InsertToken))
1934 return SDValue(E, 0);
1935
1936 auto *N = newSDNode<GlobalAddressSDNode>(
1937 Opc, DL.getIROrder(), DL.getDebugLoc(), GV, VTs, Offset, TargetFlags);
1938 CSEMap.insert(N, InsertToken);
1939 InsertNode(N);
1940 return SDValue(N, 0);
1941}
1942
1944 SDVTList VTs = getVTList(MVT::Untyped);
1946 ID.AddPointer(GV);
1947 FoldingSetInsertToken InsertToken;
1948 if (SDNode *E = lookupNode(ID, SDLoc(), InsertToken))
1949 return SDValue(E, 0);
1950
1951 auto *N = newSDNode<DeactivationSymbolSDNode>(GV, VTs);
1952 CSEMap.insert(N, InsertToken);
1953 InsertNode(N);
1954 return SDValue(N, 0);
1955}
1956
1957SDValue SelectionDAG::getFrameIndex(int FI, EVT VT, bool isTarget) {
1958 unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
1959 SDVTList VTs = getVTList(VT);
1960 SDNodeKey ID(Opc, VTs, {});
1961 ID.AddInteger(FI);
1962 FoldingSetInsertToken InsertToken;
1963 if (SDNode *E = lookupNode(ID, InsertToken))
1964 return SDValue(E, 0);
1965
1966 auto *N = newSDNode<FrameIndexSDNode>(FI, VTs, isTarget);
1967 CSEMap.insert(N, InsertToken);
1968 InsertNode(N);
1969 return SDValue(N, 0);
1970}
1971
1972SDValue SelectionDAG::getJumpTable(int JTI, EVT VT, bool isTarget,
1973 unsigned TargetFlags) {
1974 assert((TargetFlags == 0 || isTarget) &&
1975 "Cannot set target flags on target-independent jump tables");
1976 unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
1977 SDVTList VTs = getVTList(VT);
1978 SDNodeKey ID(Opc, VTs, {});
1979 ID.AddInteger(JTI);
1980 ID.AddInteger(TargetFlags);
1981 FoldingSetInsertToken InsertToken;
1982 if (SDNode *E = lookupNode(ID, InsertToken))
1983 return SDValue(E, 0);
1984
1985 auto *N = newSDNode<JumpTableSDNode>(JTI, VTs, isTarget, TargetFlags);
1986 CSEMap.insert(N, InsertToken);
1987 InsertNode(N);
1988 return SDValue(N, 0);
1989}
1990
1992 const SDLoc &DL) {
1994 return getNode(ISD::JUMP_TABLE_DEBUG_INFO, DL, MVT::Other, Chain,
1995 getTargetConstant(static_cast<uint64_t>(JTI), DL, PTy, true));
1996}
1997
1999 MaybeAlign Alignment, int Offset,
2000 bool isTarget, unsigned TargetFlags) {
2001 assert((TargetFlags == 0 || isTarget) &&
2002 "Cannot set target flags on target-independent globals");
2003 if (!Alignment)
2004 Alignment = shouldOptForSize()
2005 ? getDataLayout().getABITypeAlign(C->getType())
2006 : getDataLayout().getPrefTypeAlign(C->getType());
2007 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
2008 SDVTList VTs = getVTList(VT);
2009 SDNodeKey ID(Opc, VTs, {});
2010 ID.AddInteger(Alignment->value());
2011 ID.AddInteger(Offset);
2012 ID.AddPointer(C);
2013 ID.AddInteger(TargetFlags);
2014 FoldingSetInsertToken InsertToken;
2015 if (SDNode *E = lookupNode(ID, InsertToken))
2016 return SDValue(E, 0);
2017
2018 auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VTs, Offset, *Alignment,
2019 TargetFlags);
2020 CSEMap.insert(N, InsertToken);
2021 InsertNode(N);
2022 SDValue V = SDValue(N, 0);
2023 NewSDValueDbgMsg(V, "Creating new constant pool: ", this);
2024 return V;
2025}
2026
2028 MaybeAlign Alignment, int Offset,
2029 bool isTarget, unsigned TargetFlags) {
2030 assert((TargetFlags == 0 || isTarget) &&
2031 "Cannot set target flags on target-independent globals");
2032 if (!Alignment)
2033 Alignment = getDataLayout().getPrefTypeAlign(C->getType());
2034 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
2035 SDVTList VTs = getVTList(VT);
2036 SDNodeKey ID(Opc, VTs, {});
2037 ID.AddInteger(Alignment->value());
2038 ID.AddInteger(Offset);
2039 C->addSelectionDAGCSEId(ID.Tail);
2040 ID.AddInteger(TargetFlags);
2041 FoldingSetInsertToken InsertToken;
2042 if (SDNode *E = lookupNode(ID, InsertToken))
2043 return SDValue(E, 0);
2044
2045 auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VTs, Offset, *Alignment,
2046 TargetFlags);
2047 CSEMap.insert(N, InsertToken);
2048 InsertNode(N);
2049 return SDValue(N, 0);
2050}
2051
2053 SDNodeKey ID(ISD::BasicBlock, getVTList(MVT::Other), {});
2054 ID.AddPointer(MBB);
2055 FoldingSetInsertToken InsertToken;
2056 if (SDNode *E = lookupNode(ID, InsertToken))
2057 return SDValue(E, 0);
2058
2059 auto *N = newSDNode<BasicBlockSDNode>(MBB);
2060 CSEMap.insert(N, InsertToken);
2061 InsertNode(N);
2062 return SDValue(N, 0);
2063}
2064
2066 if (VT.isSimple() && (unsigned)VT.getSimpleVT().SimpleTy >=
2067 ValueTypeNodes.size())
2068 ValueTypeNodes.resize(VT.getSimpleVT().SimpleTy+1);
2069
2070 SDNode *&N = VT.isExtended() ?
2071 ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT().SimpleTy];
2072
2073 if (N) return SDValue(N, 0);
2074 N = newSDNode<VTSDNode>(VT);
2075 InsertNode(N);
2076 return SDValue(N, 0);
2077}
2078
2080 SDNode *&N = ExternalSymbols[Sym];
2081 if (N) return SDValue(N, 0);
2082 N = newSDNode<ExternalSymbolSDNode>(false, Sym, 0, getVTList(VT));
2083 InsertNode(N);
2084 return SDValue(N, 0);
2085}
2086
2087SDValue SelectionDAG::getExternalSymbol(RTLIB::LibcallImpl Libcall, EVT VT) {
2089 return getExternalSymbol(SymName.data(), VT);
2090}
2091
2093 SDNode *&N = MCSymbols[Sym];
2094 if (N)
2095 return SDValue(N, 0);
2096 N = newSDNode<MCSymbolSDNode>(Sym, getVTList(VT));
2097 InsertNode(N);
2098 return SDValue(N, 0);
2099}
2100
2102 unsigned TargetFlags) {
2103 SDNode *&N =
2104 TargetExternalSymbols[std::pair<std::string, unsigned>(Sym, TargetFlags)];
2105 if (N) return SDValue(N, 0);
2106 N = newSDNode<ExternalSymbolSDNode>(true, Sym, TargetFlags, getVTList(VT));
2107 InsertNode(N);
2108 return SDValue(N, 0);
2109}
2110
2112 EVT VT, unsigned TargetFlags) {
2114 return getTargetExternalSymbol(SymName.data(), VT, TargetFlags);
2115}
2116
2118 if ((unsigned)Cond >= CondCodeNodes.size())
2119 CondCodeNodes.resize(Cond+1);
2120
2121 if (!CondCodeNodes[Cond]) {
2122 auto *N = newSDNode<CondCodeSDNode>(Cond);
2123 CondCodeNodes[Cond] = N;
2124 InsertNode(N);
2125 }
2126
2127 return SDValue(CondCodeNodes[Cond], 0);
2128}
2129
2131 assert(MulImm.getBitWidth() == VT.getSizeInBits() &&
2132 "APInt size does not match type size!");
2133
2134 if (MulImm == 0)
2135 return getConstant(0, DL, VT);
2136
2137 const MachineFunction &MF = getMachineFunction();
2138 const Function &F = MF.getFunction();
2139 ConstantRange CR = getVScaleRange(&F, 64);
2140 if (const APInt *C = CR.getSingleElement())
2141 return getConstant(MulImm * C->getZExtValue(), DL, VT);
2142
2143 return getNode(ISD::VSCALE, DL, VT, getConstant(MulImm, DL, VT));
2144}
2145
2146/// \returns a value of type \p VT that represents the runtime value of \p
2147/// Quantity, i.e. scaled by vscale if it's scalable, or a fixed constant
2148/// otherwise. Quantity should be a FixedOrScalableQuantity, i.e. ElementCount
2149/// or TypeSize.
2150template <typename Ty>
2152 EVT VT, Ty Quantity) {
2153 if (Quantity.isScalable())
2154 return DAG.getVScale(
2155 DL, VT, APInt(VT.getSizeInBits(), Quantity.getKnownMinValue()));
2156
2157 return DAG.getConstant(Quantity.getKnownMinValue(), DL, VT);
2158}
2159
2161 ElementCount EC) {
2162 return getFixedOrScalableQuantity(*this, DL, VT, EC);
2163}
2164
2166 return getFixedOrScalableQuantity(*this, DL, VT, TS);
2167}
2168
2170 ElementCount EC) {
2171 EVT IdxVT = TLI->getVectorIdxTy(getDataLayout());
2172 EVT MaskVT = TLI->getSetCCResultType(getDataLayout(), *getContext(), DataVT);
2173 return getNode(ISD::GET_ACTIVE_LANE_MASK, DL, MaskVT,
2174 getConstant(0, DL, IdxVT), getElementCount(DL, IdxVT, EC));
2175}
2176
2178 APInt One(ResVT.getScalarSizeInBits(), 1);
2179 return getStepVector(DL, ResVT, One);
2180}
2181
2183 const APInt &StepVal) {
2184 assert(ResVT.getScalarSizeInBits() == StepVal.getBitWidth());
2185 if (ResVT.isScalableVector())
2186 return getNode(
2187 ISD::STEP_VECTOR, DL, ResVT,
2188 getTargetConstant(StepVal, DL, ResVT.getVectorElementType()));
2189
2190 SmallVector<SDValue, 16> OpsStepConstants;
2191 for (uint64_t i = 0; i < ResVT.getVectorNumElements(); i++)
2192 OpsStepConstants.push_back(
2193 getConstant(StepVal * i, DL, ResVT.getVectorElementType()));
2194 return getBuildVector(ResVT, DL, OpsStepConstants);
2195}
2196
2197/// Swaps the values of N1 and N2. Swaps all indices in the shuffle mask M that
2198/// point at N1 to point at N2 and indices that point at N2 to point at N1.
2203
2205 SDValue N2, ArrayRef<int> Mask) {
2206 assert(VT.getVectorNumElements() == Mask.size() &&
2207 "Must have the same number of vector elements as mask elements!");
2208 assert(VT == N1.getValueType() && VT == N2.getValueType() &&
2209 "Invalid VECTOR_SHUFFLE");
2210
2211 // Canonicalize shuffle undef, undef -> undef
2212 if (N1.isUndef() && N2.isUndef()) {
2213 if (N1.getOpcode() == ISD::POISON && N2.getOpcode() == ISD::POISON)
2214 return getPOISON(VT);
2215 return getUNDEF(VT);
2216 }
2217
2218 // Validate that all indices in Mask are within the range of the elements
2219 // input to the shuffle.
2220 int NElts = Mask.size();
2221 assert(llvm::all_of(Mask,
2222 [&](int M) { return M < (NElts * 2) && M >= -1; }) &&
2223 "Index out of range");
2224
2225 // Copy the mask so we can do any needed cleanup.
2226 SmallVector<int, 8> MaskVec(Mask);
2227
2228 // Canonicalize shuffle v, v -> v, poison
2229 if (N1 == N2) {
2230 N2 = getPOISON(VT);
2231 for (int i = 0; i != NElts; ++i)
2232 if (MaskVec[i] >= NElts) MaskVec[i] -= NElts;
2233 }
2234
2235 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
2236 if (N1.isUndef())
2237 commuteShuffle(N1, N2, MaskVec);
2238
2239 if (TLI->hasVectorBlend()) {
2240 // If shuffling a splat, try to blend the splat instead. We do this here so
2241 // that even when this arises during lowering we don't have to re-handle it.
2242 auto BlendSplat = [&](BuildVectorSDNode *BV, int Offset) {
2243 BitVector UndefElements;
2244 SDValue Splat = BV->getSplatValue(&UndefElements);
2245 if (!Splat)
2246 return;
2247
2248 for (int i = 0; i < NElts; ++i) {
2249 if (MaskVec[i] < Offset || MaskVec[i] >= (Offset + NElts))
2250 continue;
2251
2252 // If this input comes from undef, mark it as such.
2253 if (UndefElements[MaskVec[i] - Offset]) {
2254 MaskVec[i] = -1;
2255 continue;
2256 }
2257
2258 // If we can blend a non-undef lane, use that instead.
2259 if (!UndefElements[i])
2260 MaskVec[i] = i + Offset;
2261 }
2262 };
2263 if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
2264 BlendSplat(N1BV, 0);
2265 if (auto *N2BV = dyn_cast<BuildVectorSDNode>(N2))
2266 BlendSplat(N2BV, NElts);
2267 }
2268
2269 // Canonicalize all index into lhs, -> shuffle lhs, poison
2270 // Canonicalize all index into rhs, -> shuffle rhs, poison
2271 bool AllLHS = true, AllRHS = true;
2272 bool N2Undef = N2.isUndef();
2273 for (int i = 0; i != NElts; ++i) {
2274 if (MaskVec[i] >= NElts) {
2275 if (N2Undef)
2276 MaskVec[i] = -1;
2277 else
2278 AllLHS = false;
2279 } else if (MaskVec[i] >= 0) {
2280 AllRHS = false;
2281 }
2282 }
2283 if (AllLHS && AllRHS)
2284 return getPOISON(VT);
2285 if (AllLHS && !N2Undef)
2286 N2 = getPOISON(VT);
2287 if (AllRHS) {
2288 N1 = getPOISON(VT);
2289 commuteShuffle(N1, N2, MaskVec);
2290 }
2291 // Reset our undef status after accounting for the mask.
2292 N2Undef = N2.isUndef();
2293 // Re-check whether both sides ended up undef.
2294 if (N1.isUndef() && N2Undef) {
2295 if (N1.getOpcode() == ISD::POISON && N2.getOpcode() == ISD::POISON)
2296 return getPOISON(VT);
2297 return getUNDEF(VT);
2298 }
2299
2300 // If Identity shuffle return that node.
2301 bool Identity = true, AllSame = true;
2302 for (int i = 0; i != NElts; ++i) {
2303 if (MaskVec[i] >= 0 && MaskVec[i] != i) Identity = false;
2304 if (MaskVec[i] != MaskVec[0]) AllSame = false;
2305 }
2306 if (Identity && NElts)
2307 return N1;
2308
2309 // Shuffling a constant splat doesn't change the result.
2310 if (N2Undef) {
2311 SDValue V = N1;
2312
2313 // Look through any bitcasts. We check that these don't change the number
2314 // (and size) of elements and just changes their types.
2315 while (V.getOpcode() == ISD::BITCAST)
2316 V = V->getOperand(0);
2317
2318 // A splat should always show up as a build vector node.
2319 if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) {
2320 BitVector UndefElements;
2321 SDValue Splat = BV->getSplatValue(&UndefElements);
2322 // If this is a splat of an undef, shuffling it is also undef.
2323 if (Splat && Splat.isUndef())
2324 return Splat.getOpcode() == ISD::POISON ? getPOISON(VT) : getUNDEF(VT);
2325
2326 bool SameNumElts =
2327 V.getValueType().getVectorNumElements() == VT.getVectorNumElements();
2328
2329 // We only have a splat which can skip shuffles if there is a splatted
2330 // value and no undef lanes rearranged by the shuffle.
2331 if (Splat && UndefElements.none()) {
2332 // Splat of <x, x, ..., x>, return <x, x, ..., x>, provided that the
2333 // number of elements match or the value splatted is a zero constant.
2334 if (SameNumElts || isNullConstant(Splat))
2335 return N1;
2336 }
2337
2338 // If the shuffle itself creates a splat, build the vector directly.
2339 if (AllSame && SameNumElts) {
2340 EVT BuildVT = BV->getValueType(0);
2341 const SDValue &Splatted = BV->getOperand(MaskVec[0]);
2342 SDValue NewBV = getSplatBuildVector(BuildVT, dl, Splatted);
2343
2344 // We may have jumped through bitcasts, so the type of the
2345 // BUILD_VECTOR may not match the type of the shuffle.
2346 if (BuildVT != VT)
2347 NewBV = getNode(ISD::BITCAST, dl, VT, NewBV);
2348 return NewBV;
2349 }
2350 }
2351 }
2352
2353 SDVTList VTs = getVTList(VT);
2354 SDValue Ops[2] = { N1, N2 };
2356 for (int i = 0; i != NElts; ++i)
2357 ID.AddInteger(MaskVec[i]);
2358
2359 FoldingSetInsertToken InsertToken;
2360 if (SDNode *E = lookupNode(ID, dl, InsertToken))
2361 return SDValue(E, 0);
2362
2363 // Allocate the mask array for the node out of the BumpPtrAllocator, since
2364 // SDNode doesn't have access to it. This memory will be "leaked" when
2365 // the node is deallocated, but recovered when the NodeAllocator is released.
2366 int *MaskAlloc = OperandAllocator.Allocate<int>(NElts);
2367 llvm::copy(MaskVec, MaskAlloc);
2368
2369 auto *N = newSDNode<ShuffleVectorSDNode>(VTs, dl.getIROrder(),
2370 dl.getDebugLoc(), MaskAlloc);
2371 createOperands(N, Ops);
2372
2373 CSEMap.insert(N, InsertToken);
2374 InsertNode(N);
2375 SDValue V = SDValue(N, 0);
2376 NewSDValueDbgMsg(V, "Creating new node: ", this);
2377 return V;
2378}
2379
2381 EVT VT = SV.getValueType(0);
2382 SmallVector<int, 8> MaskVec(SV.getMask());
2384
2385 SDValue Op0 = SV.getOperand(0);
2386 SDValue Op1 = SV.getOperand(1);
2387 return getVectorShuffle(VT, SDLoc(&SV), Op1, Op0, MaskVec);
2388}
2389
2391 SDVTList VTs = getVTList(VT);
2392 SDNodeKey ID(ISD::Register, VTs, {});
2393 ID.AddInteger(Reg.id());
2394 FoldingSetInsertToken InsertToken;
2395 if (SDNode *E = lookupNode(ID, InsertToken))
2396 return SDValue(E, 0);
2397
2398 auto *N = newSDNode<RegisterSDNode>(Reg, VTs);
2399 N->SDNodeBits.IsDivergent = TLI->isSDNodeSourceOfDivergence(N, FLI, UA);
2400 CSEMap.insert(N, InsertToken);
2401 InsertNode(N);
2402 return SDValue(N, 0);
2403}
2404
2406 SDNodeKey ID(ISD::RegisterMask, getVTList(MVT::Untyped), {});
2407 ID.AddPointer(RegMask);
2408 FoldingSetInsertToken InsertToken;
2409 if (SDNode *E = lookupNode(ID, InsertToken))
2410 return SDValue(E, 0);
2411
2412 auto *N = newSDNode<RegisterMaskSDNode>(RegMask);
2413 CSEMap.insert(N, InsertToken);
2414 InsertNode(N);
2415 return SDValue(N, 0);
2416}
2417
2419 MCSymbol *Label) {
2420 return getLabelNode(ISD::EH_LABEL, dl, Root, Label);
2421}
2422
2423SDValue SelectionDAG::getLabelNode(unsigned Opcode, const SDLoc &dl,
2424 SDValue Root, MCSymbol *Label) {
2425 SDValue Ops[] = { Root };
2426 SDNodeKey ID(Opcode, getVTList(MVT::Other), Ops);
2427 ID.AddPointer(Label);
2428 FoldingSetInsertToken InsertToken;
2429 if (SDNode *E = lookupNode(ID, InsertToken))
2430 return SDValue(E, 0);
2431
2432 auto *N =
2433 newSDNode<LabelSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), Label);
2434 createOperands(N, Ops);
2435
2436 CSEMap.insert(N, InsertToken);
2437 InsertNode(N);
2438 return SDValue(N, 0);
2439}
2440
2442 int64_t Offset, bool isTarget,
2443 unsigned TargetFlags) {
2444 unsigned Opc = isTarget ? ISD::TargetBlockAddress : ISD::BlockAddress;
2445 SDVTList VTs = getVTList(VT);
2446
2447 SDNodeKey ID(Opc, VTs, {});
2448 ID.AddPointer(BA);
2449 ID.AddInteger(Offset);
2450 ID.AddInteger(TargetFlags);
2451 FoldingSetInsertToken InsertToken;
2452 if (SDNode *E = lookupNode(ID, InsertToken))
2453 return SDValue(E, 0);
2454
2455 auto *N = newSDNode<BlockAddressSDNode>(Opc, VTs, BA, Offset, TargetFlags);
2456 CSEMap.insert(N, InsertToken);
2457 InsertNode(N);
2458 return SDValue(N, 0);
2459}
2460
2462 SDNodeKey ID(ISD::SRCVALUE, getVTList(MVT::Other), {});
2463 ID.AddPointer(V);
2464
2465 FoldingSetInsertToken InsertToken;
2466 if (SDNode *E = lookupNode(ID, InsertToken))
2467 return SDValue(E, 0);
2468
2469 auto *N = newSDNode<SrcValueSDNode>(V);
2470 CSEMap.insert(N, InsertToken);
2471 InsertNode(N);
2472 return SDValue(N, 0);
2473}
2474
2476 SDNodeKey ID(ISD::MDNODE_SDNODE, getVTList(MVT::Other), {});
2477 ID.AddPointer(MD);
2478
2479 FoldingSetInsertToken InsertToken;
2480 if (SDNode *E = lookupNode(ID, InsertToken))
2481 return SDValue(E, 0);
2482
2483 auto *N = newSDNode<MDNodeSDNode>(MD);
2484 CSEMap.insert(N, InsertToken);
2485 InsertNode(N);
2486 return SDValue(N, 0);
2487}
2488
2490 if (VT == V.getValueType())
2491 return V;
2492
2493 return getNode(ISD::BITCAST, SDLoc(V), VT, V);
2494}
2495
2497 unsigned SrcAS, unsigned DestAS,
2498 const SDNodeFlags Flags) {
2499 SDVTList VTs = getVTList(VT);
2500 SDValue Ops[] = {Ptr};
2502 ID.AddInteger(SrcAS);
2503 ID.AddInteger(DestAS);
2504
2505 FoldingSetInsertToken InsertToken;
2506 if (SDNode *E = lookupNode(ID, dl, InsertToken)) {
2507 E->intersectFlagsWith(Flags);
2508 return SDValue(E, 0);
2509 }
2510
2511 auto *N = newSDNode<AddrSpaceCastSDNode>(dl.getIROrder(), dl.getDebugLoc(),
2512 VTs, SrcAS, DestAS);
2513 N->setFlags(Flags);
2514 createOperands(N, Ops);
2515
2516 CSEMap.insert(N, InsertToken);
2517 InsertNode(N);
2518 return SDValue(N, 0);
2519}
2520
2522 // TODO: Remove isGuaranteedNotToBeUndefOrPoison handling from getNode().
2524 return getNode(ISD::FREEZE, SDLoc(V), V.getValueType(), V);
2525 APInt DemandedElts = getDemandAllEltsMask(V);
2526 return getFreeze(V, DemandedElts, Kind);
2527}
2528
2530 UndefPoisonKind Kind) {
2531 if (isGuaranteedNotToBeUndefOrPoison(V, DemandedElts, Kind))
2532 return V;
2533 return getNode(ISD::FREEZE, SDLoc(V), V.getValueType(), V);
2534}
2535
2536/// getShiftAmountOperand - Return the specified value casted to
2537/// the target's desired shift amount type.
2539 EVT OpTy = Op.getValueType();
2540 EVT ShTy = TLI->getShiftAmountTy(LHSTy, getDataLayout());
2541 if (OpTy == ShTy || OpTy.isVector()) return Op;
2542
2543 return getZExtOrTrunc(Op, SDLoc(Op), ShTy);
2544}
2545
2547 SDLoc dl(Node);
2549 const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2550 EVT VT = Node->getValueType(0);
2551 SDValue Tmp1 = Node->getOperand(0);
2552 SDValue Tmp2 = Node->getOperand(1);
2553 const MaybeAlign MA(Node->getConstantOperandVal(3));
2554
2555 SDValue VAListLoad = getLoad(TLI.getPointerTy(getDataLayout()), dl, Tmp1,
2556 Tmp2, MachinePointerInfo(V));
2557 SDValue VAList = VAListLoad;
2558
2559 if (MA && *MA > TLI.getMinStackArgumentAlignment()) {
2560 VAList = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
2561 getConstant(MA->value() - 1, dl, VAList.getValueType()));
2562
2563 VAList = getNode(
2564 ISD::AND, dl, VAList.getValueType(), VAList,
2565 getSignedConstant(-(int64_t)MA->value(), dl, VAList.getValueType()));
2566 }
2567
2568 // Increment the pointer, VAList, to the next vaarg
2569 Tmp1 = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
2570 getConstant(getDataLayout().getTypeAllocSize(
2571 VT.getTypeForEVT(*getContext())),
2572 dl, VAList.getValueType()));
2573 // Store the incremented VAList to the legalized pointer
2574 Tmp1 =
2575 getStore(VAListLoad.getValue(1), dl, Tmp1, Tmp2, MachinePointerInfo(V));
2576 // Load the actual argument out of the pointer VAList
2577 return getLoad(VT, dl, Tmp1, VAList, MachinePointerInfo());
2578}
2579
2581 SDLoc dl(Node);
2583 // This defaults to loading a pointer from the input and storing it to the
2584 // output, returning the chain.
2585 const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue();
2586 const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue();
2587 SDValue Tmp1 =
2588 getLoad(TLI.getPointerTy(getDataLayout()), dl, Node->getOperand(0),
2589 Node->getOperand(2), MachinePointerInfo(VS));
2590 return getStore(Tmp1.getValue(1), dl, Tmp1, Node->getOperand(1),
2591 MachinePointerInfo(VD));
2592}
2593
2595 const DataLayout &DL = getDataLayout();
2596 Type *Ty = VT.getTypeForEVT(*getContext());
2597 Align RedAlign = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty);
2598
2599 if (TLI->isTypeLegal(VT) || !VT.isVector())
2600 return RedAlign;
2601
2602 const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
2603 const Align StackAlign = TFI->getStackAlign();
2604
2605 // See if we can choose a smaller ABI alignment in cases where it's an
2606 // illegal vector type that will get broken down.
2607 if (RedAlign > StackAlign) {
2608 EVT IntermediateVT;
2609 MVT RegisterVT;
2610 unsigned NumIntermediates;
2611 TLI->getVectorTypeBreakdown(*getContext(), VT, IntermediateVT,
2612 NumIntermediates, RegisterVT);
2613 Ty = IntermediateVT.getTypeForEVT(*getContext());
2614 Align RedAlign2 = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty);
2615 if (RedAlign2 < RedAlign)
2616 RedAlign = RedAlign2;
2617
2618 if (!getMachineFunction().getFrameInfo().isStackRealignable())
2619 // If the stack is not realignable, the alignment should be limited to the
2620 // StackAlignment
2621 RedAlign = std::min(RedAlign, StackAlign);
2622 }
2623
2624 return RedAlign;
2625}
2626
2628 MachineFrameInfo &MFI = MF->getFrameInfo();
2629 const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
2630 int StackID = 0;
2631 if (Bytes.isScalable())
2632 StackID = TFI->getStackIDForScalableVectors();
2633 // The stack id gives an indication of whether the object is scalable or
2634 // not, so it's safe to pass in the minimum size here.
2635 int FrameIdx = MFI.CreateStackObject(Bytes.getKnownMinValue(), Alignment,
2636 false, nullptr, StackID);
2637 return getFrameIndex(FrameIdx, TLI->getFrameIndexTy(getDataLayout()));
2638}
2639
2641 Type *Ty = VT.getTypeForEVT(*getContext());
2642 Align StackAlign =
2643 std::max(getDataLayout().getPrefTypeAlign(Ty), Align(minAlign));
2644 return CreateStackTemporary(VT.getStoreSize(), StackAlign);
2645}
2646
2648 TypeSize VT1Size = VT1.getStoreSize();
2649 TypeSize VT2Size = VT2.getStoreSize();
2650 assert(VT1Size.isScalable() == VT2Size.isScalable() &&
2651 "Don't know how to choose the maximum size when creating a stack "
2652 "temporary");
2653 TypeSize Bytes = VT1Size.getKnownMinValue() > VT2Size.getKnownMinValue()
2654 ? VT1Size
2655 : VT2Size;
2656
2657 Type *Ty1 = VT1.getTypeForEVT(*getContext());
2658 Type *Ty2 = VT2.getTypeForEVT(*getContext());
2659 const DataLayout &DL = getDataLayout();
2660 Align Align = std::max(DL.getPrefTypeAlign(Ty1), DL.getPrefTypeAlign(Ty2));
2661 return CreateStackTemporary(Bytes, Align);
2662}
2663
2665 const SDLoc &DL, SDValue Chain) {
2666 EVT SrcVT = SrcOp.getValueType();
2667 Type *DestType = DestVT.getTypeForEVT(*getContext());
2668 Align DestAlign = getDataLayout().getPrefTypeAlign(DestType);
2669
2670 // Create the stack frame object.
2671 Align SrcAlign =
2673 SDValue FIPtr = CreateStackTemporary(SlotVT.getStoreSize(), SrcAlign);
2674
2675 FrameIndexSDNode *StackPtrFI = cast<FrameIndexSDNode>(FIPtr);
2676 int SPFI = StackPtrFI->getIndex();
2677 MachinePointerInfo PtrInfo =
2679
2680 // Emit a store to the stack slot. Use a truncstore if the input value is
2681 // later than DestVT.
2682 SDValue Store;
2683
2684 if (SrcVT.bitsGT(SlotVT))
2685 Store = getTruncStore(Chain, DL, SrcOp, FIPtr, PtrInfo, SlotVT, SrcAlign);
2686 else {
2687 assert(SrcVT.bitsEq(SlotVT) && "Invalid store");
2688 Store = getStore(Chain, DL, SrcOp, FIPtr, PtrInfo, SrcAlign);
2689 }
2690
2691 // Result is a load from the stack slot.
2692 if (SlotVT.bitsEq(DestVT))
2693 return getLoad(DestVT, DL, Store, FIPtr, PtrInfo, DestAlign);
2694
2695 assert(SlotVT.bitsLT(DestVT) && "Unknown extension!");
2696 return getExtLoad(ISD::EXTLOAD, DL, DestVT, Store, FIPtr, PtrInfo, SlotVT,
2697 DestAlign);
2698}
2699
2701 ISD::CondCode Cond, const SDLoc &dl,
2702 SDNodeFlags Flags) {
2703 EVT OpVT = N1.getValueType();
2704
2705 auto GetUndefBooleanConstant = [&]() {
2706 if (VT.getScalarType() == MVT::i1 ||
2707 TLI->getBooleanContents(OpVT) ==
2709 return getUNDEF(VT);
2710 // ZeroOrOne / ZeroOrNegative require specific values for the high bits,
2711 // so we cannot use getUNDEF(). Return zero instead.
2712 return getConstant(0, dl, VT);
2713 };
2714
2715 // These setcc operations always fold.
2716 switch (Cond) {
2717 default: break;
2718 case ISD::SETFALSE:
2719 case ISD::SETFALSE2: return getBoolConstant(false, dl, VT, OpVT);
2720 case ISD::SETTRUE:
2721 case ISD::SETTRUE2: return getBoolConstant(true, dl, VT, OpVT);
2722
2723 case ISD::SETOEQ:
2724 case ISD::SETOGT:
2725 case ISD::SETOGE:
2726 case ISD::SETOLT:
2727 case ISD::SETOLE:
2728 case ISD::SETONE:
2729 case ISD::SETO:
2730 case ISD::SETUO:
2731 case ISD::SETUEQ:
2732 case ISD::SETUNE:
2733 assert(!OpVT.isInteger() && "Illegal setcc for integer!");
2734 break;
2735 }
2736
2737 if (OpVT.isInteger()) {
2738 // For EQ and NE, we can always pick a value for the undef to make the
2739 // predicate pass or fail, so we can return undef.
2740 // Matches behavior in llvm::ConstantFoldCompareInstruction.
2741 // icmp eq/ne X, undef -> undef.
2742 if ((N1.isUndef() || N2.isUndef()) &&
2743 (Cond == ISD::SETEQ || Cond == ISD::SETNE))
2744 return GetUndefBooleanConstant();
2745
2746 // If both operands are undef, we can return undef for int comparison.
2747 // icmp undef, undef -> undef.
2748 if (N1.isUndef() && N2.isUndef())
2749 return GetUndefBooleanConstant();
2750
2751 // icmp X, X -> true/false
2752 // icmp X, undef -> true/false because undef could be X.
2753 if (N1.isUndef() || N2.isUndef() || N1 == N2)
2754 return getBoolConstant(ISD::isTrueWhenEqual(Cond), dl, VT, OpVT);
2755 }
2756
2757 if (ConstantSDNode *N2C = isConstOrConstSplat(N2)) {
2758 const APInt &C2 = N2C->getAPIntValue();
2759 if (ConstantSDNode *N1C = isConstOrConstSplat(N1)) {
2760 const APInt &C1 = N1C->getAPIntValue();
2761
2763 dl, VT, OpVT);
2764 }
2765 }
2766
2767 auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
2768 auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
2769
2770 if (N1CFP && N2CFP) {
2771 auto MaybeR = tryFoldFCmp(N1CFP->getValueAPF(), N2CFP->getValueAPF(),
2772 getDenormalMode(OpVT));
2773 if (!MaybeR)
2774 return SDValue();
2775 APFloat::cmpResult R = *MaybeR;
2776 switch (Cond) {
2777 default: break;
2778 case ISD::SETEQ: if (R==APFloat::cmpUnordered)
2779 return GetUndefBooleanConstant();
2780 [[fallthrough]];
2781 case ISD::SETOEQ: return getBoolConstant(R==APFloat::cmpEqual, dl, VT,
2782 OpVT);
2783 case ISD::SETNE: if (R==APFloat::cmpUnordered)
2784 return GetUndefBooleanConstant();
2785 [[fallthrough]];
2787 R==APFloat::cmpLessThan, dl, VT,
2788 OpVT);
2789 case ISD::SETLT: if (R==APFloat::cmpUnordered)
2790 return GetUndefBooleanConstant();
2791 [[fallthrough]];
2792 case ISD::SETOLT: return getBoolConstant(R==APFloat::cmpLessThan, dl, VT,
2793 OpVT);
2794 case ISD::SETGT: if (R==APFloat::cmpUnordered)
2795 return GetUndefBooleanConstant();
2796 [[fallthrough]];
2798 VT, OpVT);
2799 case ISD::SETLE: if (R==APFloat::cmpUnordered)
2800 return GetUndefBooleanConstant();
2801 [[fallthrough]];
2803 R==APFloat::cmpEqual, dl, VT,
2804 OpVT);
2805 case ISD::SETGE: if (R==APFloat::cmpUnordered)
2806 return GetUndefBooleanConstant();
2807 [[fallthrough]];
2809 R==APFloat::cmpEqual, dl, VT, OpVT);
2810 case ISD::SETO: return getBoolConstant(R!=APFloat::cmpUnordered, dl, VT,
2811 OpVT);
2812 case ISD::SETUO: return getBoolConstant(R==APFloat::cmpUnordered, dl, VT,
2813 OpVT);
2815 R==APFloat::cmpEqual, dl, VT,
2816 OpVT);
2817 case ISD::SETUNE: return getBoolConstant(R!=APFloat::cmpEqual, dl, VT,
2818 OpVT);
2820 R==APFloat::cmpLessThan, dl, VT,
2821 OpVT);
2823 R==APFloat::cmpUnordered, dl, VT,
2824 OpVT);
2826 VT, OpVT);
2827 case ISD::SETUGE: return getBoolConstant(R!=APFloat::cmpLessThan, dl, VT,
2828 OpVT);
2829 }
2830 } else if (N1CFP && OpVT.isSimple() && !N2.isUndef()) {
2831 // Ensure that the constant occurs on the RHS.
2833 if (!TLI->isCondCodeLegal(SwappedCond, OpVT.getSimpleVT()))
2834 return SDValue();
2835 return getSetCC(dl, VT, N2, N1, SwappedCond, /*Chain=*/{},
2836 /*IsSignaling=*/false, Flags);
2837 } else if ((N2CFP && N2CFP->getValueAPF().isNaN()) ||
2838 (OpVT.isFloatingPoint() && (N1.isUndef() || N2.isUndef()))) {
2839 // If an operand is known to be a nan (or undef that could be a nan), we can
2840 // fold it.
2841 // Choosing NaN for the undef will always make unordered comparison succeed
2842 // and ordered comparison fails.
2843 // Matches behavior in llvm::ConstantFoldCompareInstruction.
2844 switch (ISD::getUnorderedFlavor(Cond)) {
2845 default:
2846 llvm_unreachable("Unknown flavor!");
2847 case 0: // Known false.
2848 return getBoolConstant(false, dl, VT, OpVT);
2849 case 1: // Known true.
2850 return getBoolConstant(true, dl, VT, OpVT);
2851 case 2: // Undefined.
2852 return GetUndefBooleanConstant();
2853 }
2854 }
2855
2856 // Could not fold it.
2857 return SDValue();
2858}
2859
2860/// SignBitIsZero - Return true if the sign bit of Op is known to be zero. We
2861/// use this predicate to simplify operations downstream.
2863 unsigned BitWidth = Op.getScalarValueSizeInBits();
2865}
2866
2867// TODO: Should have argument to specify if sign bit of nan is ignorable.
2869 if (Depth >= MaxRecursionDepth)
2870 return false; // Limit search depth.
2871
2872 unsigned Opc = Op.getOpcode();
2873 switch (Opc) {
2874 case ISD::FABS:
2875 return true;
2876 case ISD::AssertNoFPClass: {
2877 FPClassTest NoFPClass =
2878 static_cast<FPClassTest>(Op.getConstantOperandVal(1));
2879
2880 const FPClassTest TestMask = fcNan | fcNegative;
2881 return (NoFPClass & TestMask) == TestMask;
2882 }
2883 case ISD::ARITH_FENCE:
2884 return SignBitIsZeroFP(Op.getOperand(0), Depth + 1);
2885 case ISD::FEXP:
2886 case ISD::FEXP2:
2887 case ISD::FEXP10:
2888 return Op->getFlags().hasNoNaNs();
2889 case ISD::FMINNUM:
2890 case ISD::FMINNUM_IEEE:
2891 case ISD::FMINIMUM:
2892 case ISD::FMINIMUMNUM:
2893 return SignBitIsZeroFP(Op.getOperand(1), Depth + 1) &&
2894 SignBitIsZeroFP(Op.getOperand(0), Depth + 1);
2895 case ISD::FMAXNUM:
2896 case ISD::FMAXNUM_IEEE:
2897 case ISD::FMAXIMUM:
2898 case ISD::FMAXIMUMNUM:
2899 // TODO: If we can ignore the sign bit of nans, only one side being known 0
2900 // is sufficient.
2901 return SignBitIsZeroFP(Op.getOperand(1), Depth + 1) &&
2902 SignBitIsZeroFP(Op.getOperand(0), Depth + 1);
2903 default:
2904 return false;
2905 }
2906
2907 llvm_unreachable("covered opcode switch");
2908}
2909
2910/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
2911/// this predicate to simplify operations downstream. Mask is known to be zero
2912/// for bits that V cannot have.
2914 unsigned Depth) const {
2915 return Mask.isSubsetOf(computeKnownBits(V, Depth).Zero);
2916}
2917
2918/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero in
2919/// DemandedElts. We use this predicate to simplify operations downstream.
2920/// Mask is known to be zero for bits that V cannot have.
2922 const APInt &DemandedElts,
2923 unsigned Depth) const {
2924 return Mask.isSubsetOf(computeKnownBits(V, DemandedElts, Depth).Zero);
2925}
2926
2927/// MaskedVectorIsZero - Return true if 'Op' is known to be zero in
2928/// DemandedElts. We use this predicate to simplify operations downstream.
2930 unsigned Depth /* = 0 */) const {
2931 return computeKnownBits(V, DemandedElts, Depth).isZero();
2932}
2933
2934/// MaskedValueIsAllOnes - Return true if '(Op & Mask) == Mask'.
2936 unsigned Depth) const {
2937 return Mask.isSubsetOf(computeKnownBits(V, Depth).One);
2938}
2939
2941 const APInt &DemandedElts,
2942 unsigned Depth) const {
2943 EVT VT = Op.getValueType();
2944 assert(VT.isVector() && !VT.isScalableVector() && "Only for fixed vectors!");
2945
2946 unsigned NumElts = VT.getVectorNumElements();
2947 assert(DemandedElts.getBitWidth() == NumElts && "Unexpected demanded mask.");
2948
2949 APInt KnownZeroElements = APInt::getZero(NumElts);
2950 for (unsigned EltIdx = 0; EltIdx != NumElts; ++EltIdx) {
2951 if (!DemandedElts[EltIdx])
2952 continue; // Don't query elements that are not demanded.
2953 APInt Mask = APInt::getOneBitSet(NumElts, EltIdx);
2954 if (MaskedVectorIsZero(Op, Mask, Depth))
2955 KnownZeroElements.setBit(EltIdx);
2956 }
2957 return KnownZeroElements;
2958}
2959
2960/// isSplatValue - Return true if the vector V has the same value
2961/// across all DemandedElts. For scalable vectors, we don't know the
2962/// number of lanes at compile time. Instead, we use a 1 bit APInt
2963/// to represent a conservative value for all lanes; that is, that
2964/// one bit value is implicitly splatted across all lanes.
2965bool SelectionDAG::isSplatValue(SDValue V, const APInt &DemandedElts,
2966 APInt &UndefElts, unsigned Depth) const {
2967 unsigned Opcode = V.getOpcode();
2968 EVT VT = V.getValueType();
2969 assert(VT.isVector() && "Vector type expected");
2970 assert((!VT.isScalableVector() || DemandedElts.getBitWidth() == 1) &&
2971 "scalable demanded bits are ignored");
2972
2973 if (!DemandedElts)
2974 return false; // No demanded elts, better to assume we don't know anything.
2975
2976 if (Depth >= MaxRecursionDepth)
2977 return false; // Limit search depth.
2978
2979 // Deal with some common cases here that work for both fixed and scalable
2980 // vector types.
2981 switch (Opcode) {
2982 case ISD::SPLAT_VECTOR:
2983 UndefElts = V.getOperand(0).isUndef()
2984 ? APInt::getAllOnes(DemandedElts.getBitWidth())
2985 : APInt(DemandedElts.getBitWidth(), 0);
2986 return true;
2987 case ISD::ADD:
2988 case ISD::SUB:
2989 case ISD::AND:
2990 case ISD::XOR:
2991 case ISD::OR: {
2992 APInt UndefLHS, UndefRHS;
2993 SDValue LHS = V.getOperand(0);
2994 SDValue RHS = V.getOperand(1);
2995 // Only recognize splats with the same demanded undef elements for both
2996 // operands, otherwise we might fail to handle binop-specific undef
2997 // handling.
2998 // e.g. (and undef, 0) -> 0 etc.
2999 if (isSplatValue(LHS, DemandedElts, UndefLHS, Depth + 1) &&
3000 isSplatValue(RHS, DemandedElts, UndefRHS, Depth + 1) &&
3001 (DemandedElts & UndefLHS) == (DemandedElts & UndefRHS)) {
3002 UndefElts = UndefLHS | UndefRHS;
3003 return true;
3004 }
3005 return false;
3006 }
3007 case ISD::ABS:
3009 case ISD::TRUNCATE:
3010 case ISD::SIGN_EXTEND:
3011 case ISD::ZERO_EXTEND:
3012 return isSplatValue(V.getOperand(0), DemandedElts, UndefElts, Depth + 1);
3013 default:
3014 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
3015 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID)
3016 return TLI->isSplatValueForTargetNode(V, DemandedElts, UndefElts, *this,
3017 Depth);
3018 break;
3019 }
3020
3021 // We don't support other cases than those above for scalable vectors at
3022 // the moment.
3023 if (VT.isScalableVector())
3024 return false;
3025
3026 unsigned NumElts = VT.getVectorNumElements();
3027 assert(NumElts == DemandedElts.getBitWidth() && "Vector size mismatch");
3028 UndefElts = APInt::getZero(NumElts);
3029
3030 switch (Opcode) {
3031 case ISD::BUILD_VECTOR: {
3032 SDValue Scl;
3033 for (unsigned i = 0; i != NumElts; ++i) {
3034 SDValue Op = V.getOperand(i);
3035 if (Op.isUndef()) {
3036 UndefElts.setBit(i);
3037 continue;
3038 }
3039 if (!DemandedElts[i])
3040 continue;
3041 if (Scl && Scl != Op)
3042 return false;
3043 Scl = Op;
3044 }
3045 return true;
3046 }
3047 case ISD::VECTOR_SHUFFLE: {
3048 // Check if this is a shuffle node doing a splat or a shuffle of a splat.
3049 APInt DemandedLHS = APInt::getZero(NumElts);
3050 APInt DemandedRHS = APInt::getZero(NumElts);
3051 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(V)->getMask();
3052 for (int i = 0; i != (int)NumElts; ++i) {
3053 int M = Mask[i];
3054 if (M < 0) {
3055 UndefElts.setBit(i);
3056 continue;
3057 }
3058 if (!DemandedElts[i])
3059 continue;
3060 if (M < (int)NumElts)
3061 DemandedLHS.setBit(M);
3062 else
3063 DemandedRHS.setBit(M - NumElts);
3064 }
3065
3066 // If we aren't demanding either op, assume there's no splat.
3067 // If we are demanding both ops, assume there's no splat.
3068 if ((DemandedLHS.isZero() && DemandedRHS.isZero()) ||
3069 (!DemandedLHS.isZero() && !DemandedRHS.isZero()))
3070 return false;
3071
3072 // See if the demanded elts of the source op is a splat or we only demand
3073 // one element, which should always be a splat.
3074 // TODO: Handle source ops splats with undefs.
3075 auto CheckSplatSrc = [&](SDValue Src, const APInt &SrcElts) {
3076 APInt SrcUndefs;
3077 return (SrcElts.popcount() == 1) ||
3078 (isSplatValue(Src, SrcElts, SrcUndefs, Depth + 1) &&
3079 (SrcElts & SrcUndefs).isZero());
3080 };
3081 if (!DemandedLHS.isZero())
3082 return CheckSplatSrc(V.getOperand(0), DemandedLHS);
3083 return CheckSplatSrc(V.getOperand(1), DemandedRHS);
3084 }
3086 // Offset the demanded elts by the subvector index.
3087 SDValue Src = V.getOperand(0);
3088 // We don't support scalable vectors at the moment.
3089 if (Src.getValueType().isScalableVector())
3090 return false;
3091 uint64_t Idx = V.getConstantOperandVal(1);
3092 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
3093 APInt UndefSrcElts;
3094 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
3095 if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) {
3096 UndefElts = UndefSrcElts.extractBits(NumElts, Idx);
3097 return true;
3098 }
3099 break;
3100 }
3104 // Widen the demanded elts by the src element count.
3105 SDValue Src = V.getOperand(0);
3106 // We don't support scalable vectors at the moment.
3107 if (Src.getValueType().isScalableVector())
3108 return false;
3109 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
3110 APInt UndefSrcElts;
3111 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts);
3112 if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) {
3113 UndefElts = UndefSrcElts.trunc(NumElts);
3114 return true;
3115 }
3116 break;
3117 }
3118 case ISD::BITCAST: {
3119 SDValue Src = V.getOperand(0);
3120 EVT SrcVT = Src.getValueType();
3121 unsigned SrcBitWidth = SrcVT.getScalarSizeInBits();
3122 unsigned BitWidth = VT.getScalarSizeInBits();
3123
3124 // Ignore bitcasts from unsupported types.
3125 // TODO: Add fp support?
3126 if (!SrcVT.isVector() || !SrcVT.isInteger() || !VT.isInteger())
3127 break;
3128
3129 // Bitcast 'small element' vector to 'large element' vector.
3130 if ((BitWidth % SrcBitWidth) == 0) {
3131 // See if each sub element is a splat.
3132 unsigned Scale = BitWidth / SrcBitWidth;
3133 unsigned NumSrcElts = SrcVT.getVectorNumElements();
3134 APInt ScaledDemandedElts =
3135 APIntOps::ScaleBitMask(DemandedElts, NumSrcElts);
3136 for (unsigned I = 0; I != Scale; ++I) {
3137 APInt SubUndefElts;
3138 APInt SubDemandedElt = APInt::getOneBitSet(Scale, I);
3139 APInt SubDemandedElts = APInt::getSplat(NumSrcElts, SubDemandedElt);
3140 SubDemandedElts &= ScaledDemandedElts;
3141 if (!isSplatValue(Src, SubDemandedElts, SubUndefElts, Depth + 1))
3142 return false;
3143 // TODO: Add support for merging sub undef elements.
3144 if (!SubUndefElts.isZero())
3145 return false;
3146 }
3147 return true;
3148 }
3149 break;
3150 }
3151 }
3152
3153 return false;
3154}
3155
3156/// Helper wrapper to main isSplatValue function.
3157bool SelectionDAG::isSplatValue(SDValue V, bool AllowUndefs) const {
3158 EVT VT = V.getValueType();
3159 assert(VT.isVector() && "Vector type expected");
3160
3161 APInt UndefElts;
3162 // Since the number of lanes in a scalable vector is unknown at compile time,
3163 // we track one bit which is implicitly broadcast to all lanes. This means
3164 // that all lanes in a scalable vector are considered demanded.
3165 APInt DemandedElts
3167 return isSplatValue(V, DemandedElts, UndefElts) &&
3168 (AllowUndefs || !UndefElts);
3169}
3170
3173
3174 EVT VT = V.getValueType();
3175 unsigned Opcode = V.getOpcode();
3176 switch (Opcode) {
3177 default: {
3178 APInt UndefElts;
3179 // Since the number of lanes in a scalable vector is unknown at compile time,
3180 // we track one bit which is implicitly broadcast to all lanes. This means
3181 // that all lanes in a scalable vector are considered demanded.
3182 APInt DemandedElts
3184
3185 if (isSplatValue(V, DemandedElts, UndefElts)) {
3186 if (VT.isScalableVector()) {
3187 // DemandedElts and UndefElts are ignored for scalable vectors, since
3188 // the only supported cases are SPLAT_VECTOR nodes.
3189 SplatIdx = 0;
3190 } else {
3191 // Handle case where all demanded elements are UNDEF.
3192 if (DemandedElts.isSubsetOf(UndefElts)) {
3193 SplatIdx = 0;
3194 return getUNDEF(VT);
3195 }
3196 SplatIdx = (UndefElts & DemandedElts).countr_one();
3197 }
3198 return V;
3199 }
3200 break;
3201 }
3202 case ISD::SPLAT_VECTOR:
3203 SplatIdx = 0;
3204 return V;
3205 case ISD::VECTOR_SHUFFLE: {
3206 assert(!VT.isScalableVector());
3207 // Check if this is a shuffle node doing a splat.
3208 // TODO - remove this and rely purely on SelectionDAG::isSplatValue,
3209 // getTargetVShiftNode currently struggles without the splat source.
3210 auto *SVN = cast<ShuffleVectorSDNode>(V);
3211 if (!SVN->isSplat())
3212 break;
3213 int Idx = SVN->getSplatIndex();
3214 int NumElts = V.getValueType().getVectorNumElements();
3215 SplatIdx = Idx % NumElts;
3216 return V.getOperand(Idx / NumElts);
3217 }
3218 }
3219
3220 return SDValue();
3221}
3222
3224 int SplatIdx;
3225 if (SDValue SrcVector = getSplatSourceVector(V, SplatIdx)) {
3226 EVT SVT = SrcVector.getValueType().getScalarType();
3227 EVT LegalSVT = SVT;
3228 if (LegalTypes && !TLI->isTypeLegal(SVT)) {
3229 if (!SVT.isInteger())
3230 return SDValue();
3231 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
3232 if (LegalSVT.bitsLT(SVT))
3233 return SDValue();
3234 }
3235 return getExtractVectorElt(SDLoc(V), LegalSVT, SrcVector, SplatIdx);
3236 }
3237 return SDValue();
3238}
3239
3240std::optional<ConstantRange>
3242 unsigned Depth) const {
3243 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
3244 V.getOpcode() == ISD::SRA) &&
3245 "Unknown shift node");
3246 // Shifting more than the bitwidth is not valid.
3247 unsigned BitWidth = V.getScalarValueSizeInBits();
3248
3249 if (auto *Cst = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
3250 const APInt &ShAmt = Cst->getAPIntValue();
3251 if (ShAmt.uge(BitWidth))
3252 return std::nullopt;
3253 return ConstantRange(ShAmt);
3254 }
3255
3256 if (auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1))) {
3257 const APInt *MinAmt = nullptr, *MaxAmt = nullptr;
3258 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
3259 if (!DemandedElts[i])
3260 continue;
3261 auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i));
3262 if (!SA) {
3263 MinAmt = MaxAmt = nullptr;
3264 break;
3265 }
3266 const APInt &ShAmt = SA->getAPIntValue();
3267 if (ShAmt.uge(BitWidth))
3268 return std::nullopt;
3269 if (!MinAmt || MinAmt->ugt(ShAmt))
3270 MinAmt = &ShAmt;
3271 if (!MaxAmt || MaxAmt->ult(ShAmt))
3272 MaxAmt = &ShAmt;
3273 }
3274 assert(((!MinAmt && !MaxAmt) || (MinAmt && MaxAmt)) &&
3275 "Failed to find matching min/max shift amounts");
3276 if (MinAmt && MaxAmt)
3277 return ConstantRange(*MinAmt, *MaxAmt + 1);
3278 }
3279
3280 // Use computeKnownBits to find a hidden constant/knownbits (usually type
3281 // legalized). e.g. Hidden behind multiple bitcasts/build_vector/casts etc.
3282 KnownBits KnownAmt = computeKnownBits(V.getOperand(1), DemandedElts, Depth);
3283 if (KnownAmt.getMaxValue().ult(BitWidth))
3284 return ConstantRange::fromKnownBits(KnownAmt, /*IsSigned=*/false);
3285
3286 return std::nullopt;
3287}
3288
3289std::optional<unsigned>
3291 unsigned Depth) const {
3292 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
3293 V.getOpcode() == ISD::SRA) &&
3294 "Unknown shift node");
3295 if (std::optional<ConstantRange> AmtRange =
3296 getValidShiftAmountRange(V, DemandedElts, Depth))
3297 if (const APInt *ShAmt = AmtRange->getSingleElement())
3298 return ShAmt->getZExtValue();
3299 return std::nullopt;
3300}
3301
3302std::optional<unsigned>
3304 APInt DemandedElts = getDemandAllEltsMask(V);
3305 return getValidShiftAmount(V, DemandedElts, Depth);
3306}
3307
3308std::optional<unsigned>
3310 unsigned Depth) const {
3311 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
3312 V.getOpcode() == ISD::SRA) &&
3313 "Unknown shift node");
3314 if (std::optional<ConstantRange> AmtRange =
3315 getValidShiftAmountRange(V, DemandedElts, Depth))
3316 return AmtRange->getUnsignedMin().getZExtValue();
3317 return std::nullopt;
3318}
3319
3320std::optional<unsigned>
3322 APInt DemandedElts = getDemandAllEltsMask(V);
3323 return getValidMinimumShiftAmount(V, DemandedElts, Depth);
3324}
3325
3326std::optional<unsigned>
3328 unsigned Depth) const {
3329 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
3330 V.getOpcode() == ISD::SRA) &&
3331 "Unknown shift node");
3332 if (std::optional<ConstantRange> AmtRange =
3333 getValidShiftAmountRange(V, DemandedElts, Depth))
3334 return AmtRange->getUnsignedMax().getZExtValue();
3335 return std::nullopt;
3336}
3337
3338std::optional<unsigned>
3340 APInt DemandedElts = getDemandAllEltsMask(V);
3341 return getValidMaximumShiftAmount(V, DemandedElts, Depth);
3342}
3343
3344/// Determine which bits of Op are known to be either zero or one and return
3345/// them in Known. For vectors, the known bits are those that are shared by
3346/// every vector element.
3348 APInt DemandedElts = getDemandAllEltsMask(Op);
3349 return computeKnownBits(Op, DemandedElts, Depth);
3350}
3351
3352/// Determine which bits of Op are known to be either zero or one and return
3353/// them in Known. The DemandedElts argument allows us to only collect the known
3354/// bits that are shared by the requested vector elements.
3356 unsigned Depth) const {
3357 unsigned BitWidth = Op.getScalarValueSizeInBits();
3358
3359 KnownBits Known(BitWidth); // Don't know anything.
3360
3361 if (auto OptAPInt = Op->bitcastToAPInt()) {
3362 // We know all of the bits for a constant!
3363 APInt V = *std::move(OptAPInt);
3364
3365 // Swap the low-order and high-order double of a ppc_fp128 when casting to
3366 // i128, see #44482.
3367 //
3368 // A ppc_fp128 is two doubles, with the high-order double stored at the
3369 // lower address. Reading that as an integer therefore puts the high-order
3370 // double in the high 64 bits on big-endian targets and in the low 64 bits
3371 // on little-endian targets.
3372 //
3373 // But APFloat::bitcastToAPInt is endianness-agnostic and always places the
3374 // high-order double in the low 64 bits. Hence the two doubles must be
3375 // flipped on big-endian targets.
3376 if (getDataLayout().isBigEndian() && Op.getValueType() == MVT::ppcf128)
3377 V = V.rotl(64);
3378
3379 return KnownBits::makeConstant(V);
3380 }
3381
3382 if (Depth >= MaxRecursionDepth)
3383 return Known; // Limit search depth.
3384
3385 KnownBits Known2;
3386 unsigned NumElts = DemandedElts.getBitWidth();
3387 assert((!Op.getValueType().isScalableVector() || NumElts == 1) &&
3388 "DemandedElts for scalable vectors must be 1 to represent all lanes");
3389 assert((!Op.getValueType().isFixedLengthVector() ||
3390 NumElts == Op.getValueType().getVectorNumElements()) &&
3391 "Unexpected vector size");
3392
3393 if (!DemandedElts)
3394 return Known; // No demanded elts, better to assume we don't know anything.
3395
3396 unsigned Opcode = Op.getOpcode();
3397 switch (Opcode) {
3398 case ISD::FREEZE: {
3399 if (isGuaranteedNotToBeUndefOrPoison(Op.getOperand(0), DemandedElts,
3401 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3402 break;
3403 }
3404 case ISD::MERGE_VALUES:
3405 return computeKnownBits(Op.getOperand(Op.getResNo()), DemandedElts,
3406 Depth + 1);
3407 case ISD::SPLAT_VECTOR: {
3408 SDValue SrcOp = Op.getOperand(0);
3409 assert(SrcOp.getValueSizeInBits() >= BitWidth &&
3410 "Expected SPLAT_VECTOR implicit truncation");
3411 // Implicitly truncate the bits to match the official semantics of
3412 // SPLAT_VECTOR.
3414 break;
3415 }
3417 unsigned ScalarSize = Op.getOperand(0).getScalarValueSizeInBits();
3418 assert(ScalarSize * Op.getNumOperands() == BitWidth &&
3419 "Expected SPLAT_VECTOR_PARTS scalars to cover element width");
3420 for (auto [I, SrcOp] : enumerate(Op->ops())) {
3421 Known.insertBits(computeKnownBits(SrcOp, Depth + 1), ScalarSize * I);
3422 }
3423 break;
3424 }
3425 case ISD::STEP_VECTOR: {
3426 const APInt &Step = Op.getConstantOperandAPInt(0);
3427
3428 if (Step.isPowerOf2())
3429 Known.Zero.setLowBits(Step.logBase2());
3430
3432
3433 if (!isUIntN(BitWidth, Op.getValueType().getVectorMinNumElements()))
3434 break;
3435 const APInt MinNumElts =
3436 APInt(BitWidth, Op.getValueType().getVectorMinNumElements());
3437
3438 bool Overflow;
3439 const APInt MaxNumElts = getVScaleRange(&F, BitWidth)
3441 .umul_ov(MinNumElts, Overflow);
3442 if (Overflow)
3443 break;
3444
3445 const APInt MaxValue = (MaxNumElts - 1).umul_ov(Step, Overflow);
3446 if (Overflow)
3447 break;
3448
3449 Known.Zero.setHighBits(MaxValue.countl_zero());
3450 break;
3451 }
3452 case ISD::BUILD_VECTOR:
3453 assert(!Op.getValueType().isScalableVector());
3454 // Collect the known bits that are shared by every demanded vector element.
3455 Known.setAllConflict();
3456 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
3457 if (!DemandedElts[i])
3458 continue;
3459
3460 SDValue SrcOp = Op.getOperand(i);
3461 if (SrcOp.getOpcode() == ISD::POISON)
3462 continue;
3463
3464 Known2 = computeKnownBits(SrcOp, Depth + 1);
3465
3466 // BUILD_VECTOR can implicitly truncate sources, we must handle this.
3467 if (SrcOp.getValueSizeInBits() != BitWidth) {
3468 assert(SrcOp.getValueSizeInBits() > BitWidth &&
3469 "Expected BUILD_VECTOR implicit truncation");
3470 Known2 = Known2.trunc(BitWidth);
3471 }
3472
3473 // Known bits are the values that are shared by every demanded element.
3474 Known = Known.intersectWith(Known2);
3475
3476 // If we don't know any bits, early out.
3477 if (Known.isUnknown())
3478 break;
3479 }
3480
3481 // If every demanded element was poison, we know nothing.
3482 if (Known.hasConflict())
3483 Known.resetAll();
3484 break;
3485 case ISD::VECTOR_COMPRESS: {
3486 SDValue Vec = Op.getOperand(0);
3487 SDValue PassThru = Op.getOperand(2);
3488 Known = computeKnownBits(PassThru, DemandedElts, Depth + 1);
3489 // If we don't know any bits, early out.
3490 if (Known.isUnknown())
3491 break;
3492 Known2 = computeKnownBits(Vec, Depth + 1);
3493 Known = Known.intersectWith(Known2);
3494 break;
3495 }
3496 case ISD::VECTOR_SHUFFLE: {
3497 assert(!Op.getValueType().isScalableVector());
3498 // Collect the known bits that are shared by every vector element referenced
3499 // by the shuffle.
3500 APInt DemandedLHS, DemandedRHS;
3502 assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
3503 if (!getShuffleDemandedElts(NumElts, SVN->getMask(), DemandedElts,
3504 DemandedLHS, DemandedRHS))
3505 break;
3506
3507 // Known bits are the values that are shared by every demanded element.
3508 Known.setAllConflict();
3509 if (!!DemandedLHS) {
3510 SDValue LHS = Op.getOperand(0);
3511 Known2 = computeKnownBits(LHS, DemandedLHS, Depth + 1);
3512 Known = Known.intersectWith(Known2);
3513 }
3514 // If we don't know any bits, early out.
3515 if (Known.isUnknown())
3516 break;
3517 if (!!DemandedRHS) {
3518 SDValue RHS = Op.getOperand(1);
3519 Known2 = computeKnownBits(RHS, DemandedRHS, Depth + 1);
3520 Known = Known.intersectWith(Known2);
3521 }
3522 break;
3523 }
3524 case ISD::VSCALE: {
3526 const APInt &Multiplier = Op.getConstantOperandAPInt(0);
3528 break;
3529 }
3530 case ISD::CONCAT_VECTORS: {
3531 if (Op.getValueType().isScalableVector())
3532 break;
3533 // Split DemandedElts and test each of the demanded subvectors.
3534 Known.setAllConflict();
3535 EVT SubVectorVT = Op.getOperand(0).getValueType();
3536 unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
3537 unsigned NumSubVectors = Op.getNumOperands();
3538 for (unsigned i = 0; i != NumSubVectors; ++i) {
3539 APInt DemandedSub =
3540 DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts);
3541 if (!!DemandedSub) {
3542 SDValue Sub = Op.getOperand(i);
3543 Known2 = computeKnownBits(Sub, DemandedSub, Depth + 1);
3544 Known = Known.intersectWith(Known2);
3545 }
3546 // If we don't know any bits, early out.
3547 if (Known.isUnknown())
3548 break;
3549 }
3550 break;
3551 }
3552 case ISD::INSERT_SUBVECTOR: {
3553 if (Op.getValueType().isScalableVector())
3554 break;
3555 // Demand any elements from the subvector and the remainder from the src its
3556 // inserted into.
3557 SDValue Src = Op.getOperand(0);
3558 SDValue Sub = Op.getOperand(1);
3559 uint64_t Idx = Op.getConstantOperandVal(2);
3560 unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
3561 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
3562 APInt DemandedSrcElts = DemandedElts;
3563 DemandedSrcElts.clearBits(Idx, Idx + NumSubElts);
3564
3565 Known.setAllConflict();
3566 if (!!DemandedSubElts) {
3567 Known = computeKnownBits(Sub, DemandedSubElts, Depth + 1);
3568 if (Known.isUnknown())
3569 break; // early-out.
3570 }
3571 if (!!DemandedSrcElts) {
3572 Known2 = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
3573 Known = Known.intersectWith(Known2);
3574 }
3575 break;
3576 }
3578 // Offset the demanded elts by the subvector index.
3579 SDValue Src = Op.getOperand(0);
3580
3581 APInt DemandedSrcElts;
3582 if (Src.getValueType().isScalableVector())
3583 DemandedSrcElts = APInt(1, 1); // <=> 'demand all elements'
3584 else {
3585 uint64_t Idx = Op.getConstantOperandVal(1);
3586 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
3587 DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
3588 }
3589 Known = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
3590 break;
3591 }
3592 case ISD::SCALAR_TO_VECTOR: {
3593 if (Op.getValueType().isScalableVector())
3594 break;
3595 // We know about scalar_to_vector as much as we know about it source,
3596 // which becomes the first element of otherwise unknown vector.
3597 if (DemandedElts != 1)
3598 break;
3599
3600 SDValue N0 = Op.getOperand(0);
3601 Known = computeKnownBits(N0, Depth + 1);
3602 if (N0.getValueSizeInBits() != BitWidth)
3603 Known = Known.trunc(BitWidth);
3604
3605 break;
3606 }
3607 case ISD::BITCAST: {
3608 if (Op.getValueType().isScalableVector())
3609 break;
3610
3611 SDValue N0 = Op.getOperand(0);
3612 EVT SubVT = N0.getValueType();
3613 unsigned SubBitWidth = SubVT.getScalarSizeInBits();
3614
3615 // Ignore bitcasts from unsupported types.
3616 if (!(SubVT.isInteger() || SubVT.isFloatingPoint()))
3617 break;
3618
3619 // Fast handling of 'identity' bitcasts.
3620 if (BitWidth == SubBitWidth) {
3621 Known = computeKnownBits(N0, DemandedElts, Depth + 1);
3622 break;
3623 }
3624
3625 bool IsLE = getDataLayout().isLittleEndian();
3626
3627 // Bitcast 'small element' vector to 'large element' scalar/vector.
3628 if ((BitWidth % SubBitWidth) == 0) {
3629 assert(N0.getValueType().isVector() && "Expected bitcast from vector");
3630
3631 // Collect known bits for the (larger) output by collecting the known
3632 // bits from each set of sub elements and shift these into place.
3633 // We need to separately call computeKnownBits for each set of
3634 // sub elements as the knownbits for each is likely to be different.
3635 unsigned SubScale = BitWidth / SubBitWidth;
3636 APInt SubDemandedElts(NumElts * SubScale, 0);
3637 for (unsigned i = 0; i != NumElts; ++i)
3638 if (DemandedElts[i])
3639 SubDemandedElts.setBit(i * SubScale);
3640
3641 for (unsigned i = 0; i != SubScale; ++i) {
3642 Known2 = computeKnownBits(N0, SubDemandedElts.shl(i),
3643 Depth + 1);
3644 unsigned Shifts = IsLE ? i : SubScale - 1 - i;
3645 Known.insertBits(Known2, SubBitWidth * Shifts);
3646 }
3647 }
3648
3649 // Bitcast 'large element' scalar/vector to 'small element' vector.
3650 if ((SubBitWidth % BitWidth) == 0) {
3651 assert(Op.getValueType().isVector() && "Expected bitcast to vector");
3652
3653 // Collect known bits for the (smaller) output by collecting the known
3654 // bits from the overlapping larger input elements and extracting the
3655 // sub sections we actually care about.
3656 unsigned SubScale = SubBitWidth / BitWidth;
3657 APInt SubDemandedElts =
3658 APIntOps::ScaleBitMask(DemandedElts, NumElts / SubScale);
3659 Known2 = computeKnownBits(N0, SubDemandedElts, Depth + 1);
3660
3661 Known.setAllConflict();
3662 for (unsigned i = 0; i != NumElts; ++i)
3663 if (DemandedElts[i]) {
3664 unsigned Shifts = IsLE ? i : NumElts - 1 - i;
3665 unsigned Offset = (Shifts % SubScale) * BitWidth;
3666 Known = Known.intersectWith(Known2.extractBits(BitWidth, Offset));
3667 // If we don't know any bits, early out.
3668 if (Known.isUnknown())
3669 break;
3670 }
3671 }
3672 break;
3673 }
3674 case ISD::AND:
3675 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3676 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3677
3678 Known &= Known2;
3679 break;
3680 case ISD::OR:
3681 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3682 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3683
3684 Known |= Known2;
3685 break;
3686 case ISD::XOR:
3687 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3688 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3689
3690 Known ^= Known2;
3691 break;
3692 case ISD::MUL: {
3693 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3694 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3695 bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1);
3696 // TODO: SelfMultiply can be poison, but not undef.
3697 if (SelfMultiply)
3698 SelfMultiply &= isGuaranteedNotToBeUndefOrPoison(
3699 Op.getOperand(0), DemandedElts, UndefPoisonKind::UndefOrPoison,
3700 Depth + 1);
3701 Known = KnownBits::mul(Known, Known2, SelfMultiply);
3702
3703 // If the multiplication is known not to overflow, the product of a number
3704 // with itself is non-negative. Only do this if we didn't already computed
3705 // the opposite value for the sign bit.
3706 if (Op->getFlags().hasNoSignedWrap() &&
3707 Op.getOperand(0) == Op.getOperand(1) &&
3708 !Known.isNegative())
3709 Known.makeNonNegative();
3710 break;
3711 }
3712 case ISD::MULHU: {
3713 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3714 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3715 Known = KnownBits::mulhu(Known, Known2);
3716 break;
3717 }
3718 case ISD::MULHS: {
3719 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3720 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3721 Known = KnownBits::mulhs(Known, Known2);
3722 break;
3723 }
3724 case ISD::ABDU: {
3725 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3726 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3727 Known = KnownBits::abdu(Known, Known2);
3728 break;
3729 }
3730 case ISD::ABDS: {
3731 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3732 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3733 Known = KnownBits::abds(Known, Known2);
3734 unsigned SignBits1 =
3735 ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
3736 if (SignBits1 == 1)
3737 break;
3738 unsigned SignBits0 =
3739 ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3740 Known.Zero.setHighBits(std::min(SignBits0, SignBits1) - 1);
3741 break;
3742 }
3743 case ISD::UMUL_LOHI: {
3744 assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3745 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3746 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3747 bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1);
3748 if (Op.getResNo() == 0)
3749 Known = KnownBits::mul(Known, Known2, SelfMultiply);
3750 else
3751 Known = KnownBits::mulhu(Known, Known2);
3752 break;
3753 }
3754 case ISD::SMUL_LOHI: {
3755 assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3756 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3757 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3758 bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1);
3759 if (Op.getResNo() == 0)
3760 Known = KnownBits::mul(Known, Known2, SelfMultiply);
3761 else
3762 Known = KnownBits::mulhs(Known, Known2);
3763 break;
3764 }
3765 case ISD::AVGFLOORU: {
3766 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3767 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3768 Known = KnownBits::avgFloorU(Known, Known2);
3769 break;
3770 }
3771 case ISD::AVGCEILU: {
3772 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3773 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3774 Known = KnownBits::avgCeilU(Known, Known2);
3775 break;
3776 }
3777 case ISD::AVGFLOORS: {
3778 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3779 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3780 Known = KnownBits::avgFloorS(Known, Known2);
3781 break;
3782 }
3783 case ISD::AVGCEILS: {
3784 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3785 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3786 Known = KnownBits::avgCeilS(Known, Known2);
3787 break;
3788 }
3789 case ISD::AVGSUBFLOORU:
3790 case ISD::AVGSUBFLOORS: {
3791 bool IsSigned = Op.getOpcode() == ISD::AVGSUBFLOORS;
3792 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3793 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3794 // Subtract in i[N+1] so the difference can't overflow, then halve.
3795 Known = IsSigned ? Known.sext(BitWidth + 1) : Known.zext(BitWidth + 1);
3796 Known2 = IsSigned ? Known2.sext(BitWidth + 1) : Known2.zext(BitWidth + 1);
3797 Known = KnownBits::sub(Known, Known2);
3798 // The shifted in top bit is unknown, but it is truncated away.
3799 Known >>= 1;
3800 Known = Known.trunc(BitWidth);
3801 break;
3802 }
3803 case ISD::SELECT:
3804 case ISD::VSELECT:
3805 Known = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
3806 // If we don't know any bits, early out.
3807 if (Known.isUnknown())
3808 break;
3809 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth+1);
3810
3811 // Only known if known in both the LHS and RHS.
3812 Known = Known.intersectWith(Known2);
3813 break;
3814 case ISD::SELECT_CC:
3815 Known = computeKnownBits(Op.getOperand(3), DemandedElts, Depth+1);
3816 // If we don't know any bits, early out.
3817 if (Known.isUnknown())
3818 break;
3819 Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
3820
3821 // Only known if known in both the LHS and RHS.
3822 Known = Known.intersectWith(Known2);
3823 break;
3824 case ISD::SMULO:
3825 case ISD::UMULO:
3826 if (Op.getResNo() != 1)
3827 break;
3828 // The boolean result conforms to getBooleanContents.
3829 // If we know the result of a setcc has the top bits zero, use this info.
3830 if (TLI->getBooleanContents(Op.getValueType()) ==
3832 BitWidth > 1)
3833 Known.Zero.setBitsFrom(1);
3834 break;
3835 case ISD::SETCC:
3836 case ISD::SETCCCARRY:
3837 case ISD::STRICT_FSETCC:
3838 case ISD::STRICT_FSETCCS: {
3839 unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
3840 // If we know the result of a setcc has the top bits zero, use this info.
3841 if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
3843 BitWidth > 1)
3844 Known.Zero.setBitsFrom(1);
3845 break;
3846 }
3847 case ISD::SHL: {
3848 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3849 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3850
3851 bool NUW = Op->getFlags().hasNoUnsignedWrap();
3852 bool NSW = Op->getFlags().hasNoSignedWrap();
3853
3854 bool ShAmtNonZero = Known2.isNonZero();
3855
3856 Known = KnownBits::shl(Known, Known2, NUW, NSW, ShAmtNonZero);
3857
3858 // Minimum shift low bits are known zero.
3859 if (std::optional<unsigned> ShMinAmt =
3860 getValidMinimumShiftAmount(Op, DemandedElts, Depth + 1))
3861 Known.Zero.setLowBits(*ShMinAmt);
3862 break;
3863 }
3864 case ISD::SRL:
3865 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3866 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3867 Known = KnownBits::lshr(Known, Known2, /*ShAmtNonZero=*/false,
3868 Op->getFlags().hasExact());
3869
3870 // Minimum shift high bits are known zero.
3871 if (std::optional<unsigned> ShMinAmt =
3872 getValidMinimumShiftAmount(Op, DemandedElts, Depth + 1))
3873 Known.Zero.setHighBits(*ShMinAmt);
3874 break;
3875 case ISD::SRA:
3876 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3877 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3878 Known = KnownBits::ashr(Known, Known2, /*ShAmtNonZero=*/false,
3879 Op->getFlags().hasExact());
3880 break;
3881 case ISD::ROTL:
3882 case ISD::ROTR:
3883 if (ConstantSDNode *C =
3884 isConstOrConstSplat(Op.getOperand(1), DemandedElts)) {
3885 unsigned Amt = C->getAPIntValue().urem(BitWidth);
3886
3887 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3888
3889 // Canonicalize to ROTR.
3890 if (Opcode == ISD::ROTL && Amt != 0)
3891 Amt = BitWidth - Amt;
3892
3893 Known.Zero = Known.Zero.rotr(Amt);
3894 Known.One = Known.One.rotr(Amt);
3895 }
3896 break;
3897 case ISD::FSHL:
3898 case ISD::FSHR:
3899 if (ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(2), DemandedElts)) {
3900 unsigned Amt = C->getAPIntValue().urem(BitWidth);
3901
3902 // For fshl, 0-shift returns the 1st arg.
3903 // For fshr, 0-shift returns the 2nd arg.
3904 if (Amt == 0) {
3905 Known = computeKnownBits(Op.getOperand(Opcode == ISD::FSHL ? 0 : 1),
3906 DemandedElts, Depth + 1);
3907 break;
3908 }
3909
3910 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
3911 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
3912 const APInt ShAmt(BitWidth, Amt);
3913 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3914 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3915 Known = Opcode == ISD::FSHL ? KnownBits::fshl(Known, Known2, ShAmt)
3916 : KnownBits::fshr(Known, Known2, ShAmt);
3917 }
3918 break;
3919 case ISD::SHL_PARTS:
3920 case ISD::SRA_PARTS:
3921 case ISD::SRL_PARTS: {
3922 assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3923
3924 // Collect lo/hi source values and concatenate.
3925 unsigned LoBits = Op.getOperand(0).getScalarValueSizeInBits();
3926 unsigned HiBits = Op.getOperand(1).getScalarValueSizeInBits();
3927 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3928 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3929 Known = Known2.concat(Known);
3930
3931 // Collect shift amount.
3932 Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1);
3933
3934 if (Opcode == ISD::SHL_PARTS)
3935 Known = KnownBits::shl(Known, Known2);
3936 else if (Opcode == ISD::SRA_PARTS)
3937 Known = KnownBits::ashr(Known, Known2);
3938 else // if (Opcode == ISD::SRL_PARTS)
3939 Known = KnownBits::lshr(Known, Known2);
3940
3941 // TODO: Minimum shift low/high bits are known zero.
3942
3943 if (Op.getResNo() == 0)
3944 Known = Known.extractBits(LoBits, 0);
3945 else
3946 Known = Known.extractBits(HiBits, LoBits);
3947 break;
3948 }
3950 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3951 EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3952 Known = Known.sextInReg(EVT.getScalarSizeInBits());
3953 break;
3954 }
3955 case ISD::CTTZ:
3956 case ISD::CTTZ_ZERO_POISON: {
3957 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3958 // If we have a known 1, its position is our upper bound.
3959 unsigned PossibleTZ = Known2.countMaxTrailingZeros();
3960 unsigned LowBits = llvm::bit_width(PossibleTZ);
3961 Known.Zero.setBitsFrom(LowBits);
3962 break;
3963 }
3964 case ISD::CTLZ:
3965 case ISD::CTLZ_ZERO_POISON: {
3966 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3967 Known = Known2.ctlz(/*ZeroIsPoison=*/false).zextOrTrunc(BitWidth);
3968 break;
3969 }
3970 case ISD::CTLS: {
3971 unsigned MinRedundantSignBits =
3972 ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1) - 1;
3973 ConstantRange Range(APInt(BitWidth, MinRedundantSignBits),
3975 Known = Range.toKnownBits();
3976 break;
3977 }
3978 case ISD::CTPOP: {
3979 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3980 // If we know some of the bits are zero, they can't be one.
3981 unsigned PossibleOnes = Known2.countMaxPopulation();
3982 Known.Zero.setBitsFrom(llvm::bit_width(PossibleOnes));
3983 break;
3984 }
3985 case ISD::PARITY: {
3986 // Parity returns 0 everywhere but the LSB.
3987 Known.Zero.setBitsFrom(1);
3988 break;
3989 }
3990 case ISD::PDEP: {
3991 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3992 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3993 Known = KnownBits::pdep(Known2, Known);
3994 break;
3995 }
3996 case ISD::PEXT: {
3997 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3998 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3999 Known = KnownBits::pext(Known2, Known);
4000 break;
4001 }
4002 case ISD::CLMUL: {
4003 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4004 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4005 Known = KnownBits::clmul(Known, Known2);
4006 break;
4007 }
4008 case ISD::MGATHER:
4009 case ISD::MLOAD: {
4010 ISD::LoadExtType ETy =
4011 (Opcode == ISD::MGATHER)
4012 ? cast<MaskedGatherSDNode>(Op)->getExtensionType()
4013 : cast<MaskedLoadSDNode>(Op)->getExtensionType();
4014 if (ETy == ISD::ZEXTLOAD) {
4015 EVT MemVT = cast<MemSDNode>(Op)->getMemoryVT();
4016 KnownBits Known0(MemVT.getScalarSizeInBits());
4017 return Known0.zext(BitWidth);
4018 }
4019 break;
4020 }
4021 case ISD::LOAD: {
4023 const Constant *Cst = TLI->getTargetConstantFromLoad(LD);
4024 if (ISD::isNON_EXTLoad(LD) && Cst) {
4025 // Determine any common known bits from the loaded constant pool value.
4026 Type *CstTy = Cst->getType();
4027 if ((NumElts * BitWidth) == CstTy->getPrimitiveSizeInBits() &&
4028 !Op.getValueType().isScalableVector()) {
4029 // If its a vector splat, then we can (quickly) reuse the scalar path.
4030 // NOTE: We assume all elements match and none are UNDEF.
4031 if (CstTy->isVectorTy()) {
4032 if (const Constant *Splat = Cst->getSplatValue()) {
4033 Cst = Splat;
4034 CstTy = Cst->getType();
4035 }
4036 }
4037 // TODO - do we need to handle different bitwidths?
4038 if (CstTy->isVectorTy() && BitWidth == CstTy->getScalarSizeInBits()) {
4039 // Iterate across all vector elements finding common known bits.
4040 Known.setAllConflict();
4041 for (unsigned i = 0; i != NumElts; ++i) {
4042 if (!DemandedElts[i])
4043 continue;
4044 if (Constant *Elt = Cst->getAggregateElement(i)) {
4045 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
4046 const APInt &Value = CInt->getValue();
4047 Known.One &= Value;
4048 Known.Zero &= ~Value;
4049 continue;
4050 }
4051 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
4052 APInt Value = CFP->getValueAPF().bitcastToAPInt();
4053 Known.One &= Value;
4054 Known.Zero &= ~Value;
4055 continue;
4056 }
4057 }
4058 Known.One.clearAllBits();
4059 Known.Zero.clearAllBits();
4060 break;
4061 }
4062 } else if (BitWidth == CstTy->getPrimitiveSizeInBits()) {
4063 if (auto *CInt = dyn_cast<ConstantInt>(Cst)) {
4064 Known = KnownBits::makeConstant(CInt->getValue());
4065 } else if (auto *CFP = dyn_cast<ConstantFP>(Cst)) {
4066 Known =
4067 KnownBits::makeConstant(CFP->getValueAPF().bitcastToAPInt());
4068 }
4069 }
4070 }
4071 } else if (Op.getResNo() == 0) {
4072 unsigned ScalarMemorySize = LD->getMemoryVT().getScalarSizeInBits();
4073 KnownBits KnownScalarMemory(ScalarMemorySize);
4074 if (const MDNode *MD = LD->getRanges())
4075 computeKnownBitsFromRangeMetadata(*MD, KnownScalarMemory);
4076
4077 // Extend the Known bits from memory to the size of the scalar result.
4078 if (ISD::isZEXTLoad(Op.getNode()))
4079 Known = KnownScalarMemory.zext(BitWidth);
4080 else if (ISD::isSEXTLoad(Op.getNode()))
4081 Known = KnownScalarMemory.sext(BitWidth);
4082 else if (ISD::isEXTLoad(Op.getNode()))
4083 Known = KnownScalarMemory.anyext(BitWidth);
4084 else
4085 Known = KnownScalarMemory;
4086 assert(Known.getBitWidth() == BitWidth);
4087 return Known;
4088 }
4089 break;
4090 }
4092 if (Op.getValueType().isScalableVector())
4093 break;
4094 EVT InVT = Op.getOperand(0).getValueType();
4095 APInt InDemandedElts = DemandedElts.zext(InVT.getVectorNumElements());
4096 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
4097 Known = Known.zext(BitWidth);
4098 break;
4099 }
4100 case ISD::ZERO_EXTEND: {
4101 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4102 Known = Known.zext(BitWidth);
4103 break;
4104 }
4106 if (Op.getValueType().isScalableVector())
4107 break;
4108 EVT InVT = Op.getOperand(0).getValueType();
4109 APInt InDemandedElts = DemandedElts.zext(InVT.getVectorNumElements());
4110 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
4111 // If the sign bit is known to be zero or one, then sext will extend
4112 // it to the top bits, else it will just zext.
4113 Known = Known.sext(BitWidth);
4114 break;
4115 }
4116 case ISD::SIGN_EXTEND: {
4117 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4118 // If the sign bit is known to be zero or one, then sext will extend
4119 // it to the top bits, else it will just zext.
4120 Known = Known.sext(BitWidth);
4121 break;
4122 }
4124 if (Op.getValueType().isScalableVector())
4125 break;
4126 EVT InVT = Op.getOperand(0).getValueType();
4127 APInt InDemandedElts = DemandedElts.zext(InVT.getVectorNumElements());
4128 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
4129 Known = Known.anyext(BitWidth);
4130 break;
4131 }
4132 case ISD::ANY_EXTEND: {
4133 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4134 Known = Known.anyext(BitWidth);
4135 break;
4136 }
4137 case ISD::TRUNCATE: {
4138 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4139 Known = Known.trunc(BitWidth);
4140 break;
4141 }
4142 case ISD::TRUNCATE_SSAT_S: {
4143 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4144 Known = Known.truncSSat(BitWidth);
4145 break;
4146 }
4147 case ISD::TRUNCATE_SSAT_U: {
4148 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4149 Known = Known.truncSSatU(BitWidth);
4150 break;
4151 }
4152 case ISD::TRUNCATE_USAT_U: {
4153 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4154 Known = Known.truncUSat(BitWidth);
4155 break;
4156 }
4157 case ISD::AssertZext: {
4158 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
4160 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4161 Known.Zero |= (~InMask);
4162 Known.One &= (~Known.Zero);
4163 break;
4164 }
4165 case ISD::AssertAlign: {
4166 unsigned LogOfAlign = Log2(cast<AssertAlignSDNode>(Op)->getAlign());
4167 assert(LogOfAlign != 0);
4168
4169 // TODO: Should use maximum with source
4170 // If a node is guaranteed to be aligned, set low zero bits accordingly as
4171 // well as clearing one bits.
4172 Known.Zero.setLowBits(LogOfAlign);
4173 Known.One.clearLowBits(LogOfAlign);
4174 break;
4175 }
4176 case ISD::AssertNoFPClass: {
4177 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4178
4179 FPClassTest NoFPClass =
4180 static_cast<FPClassTest>(Op.getConstantOperandVal(1));
4181
4182 EVT SVT = Op.getValueType().getScalarType();
4183 unsigned SignBitPos;
4184 if (SVT == MVT::ppcf128)
4185 // The sign bit position depends on endianness: ppc_fp128 is two doubles
4186 // in a trenchcoat, and it is the high-order double that carries the sign.
4187 SignBitPos = getDataLayout().isBigEndian() ? 127 : 63;
4189 // IEEE-like formats, bf16, x86_fp80: the sign bit is the integer MSB.
4190 SignBitPos = BitWidth - 1;
4191 else
4192 break;
4193
4194 const FPClassTest NegativeTestMask = fcNan | fcNegative;
4195 if ((NoFPClass & NegativeTestMask) == NegativeTestMask) {
4196 // Cannot be negative.
4197 Known.Zero.setBit(SignBitPos);
4198 }
4199
4200 const FPClassTest PositiveTestMask = fcNan | fcPositive;
4201 if ((NoFPClass & PositiveTestMask) == PositiveTestMask) {
4202 // Cannot be positive.
4203 Known.One.setBit(SignBitPos);
4204 }
4205
4206 break;
4207 }
4208 case ISD::FABS: {
4209 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4210 EVT SVT = Op.getValueType().getScalarType();
4211 if (SVT == MVT::ppcf128) {
4212 // The sign bit position depends on endianness: ppc_fp128 is two doubles
4213 // in a trenchcoat, fabs only clears the sign bit of the high-order
4214 // double.
4215 Known.resetAll();
4216 Known.Zero.setBit(getDataLayout().isBigEndian() ? 127 : 63);
4217 } else if (APFloat::hasSignBitInMSB(SVT.getFltSemantics())) {
4218 // IEEE-like formats, bf16, x86_fp80: the sign bit is the integer MSB,
4219 // fabs clears that sign bit.
4220 Known.Zero.setSignBit();
4221 Known.One.clearSignBit();
4222 }
4223
4224 break;
4225 }
4226 case ISD::FGETSIGN:
4227 // All bits are zero except the low bit.
4228 Known.Zero.setBitsFrom(1);
4229 break;
4230 case ISD::ADD: {
4231 SDNodeFlags Flags = Op.getNode()->getFlags();
4232 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4233 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4234 bool SelfAdd = Op.getOperand(0) == Op.getOperand(1) &&
4236 Op.getOperand(0), DemandedElts,
4238 Known = KnownBits::add(Known, Known2, Flags.hasNoSignedWrap(),
4239 Flags.hasNoUnsignedWrap(), SelfAdd);
4240 break;
4241 }
4242 case ISD::SUB: {
4243 SDNodeFlags Flags = Op.getNode()->getFlags();
4244 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4245 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4246 Known = KnownBits::sub(Known, Known2, Flags.hasNoSignedWrap(),
4247 Flags.hasNoUnsignedWrap());
4248 break;
4249 }
4250 case ISD::USUBO:
4251 case ISD::SSUBO:
4252 case ISD::USUBO_CARRY:
4253 case ISD::SSUBO_CARRY:
4254 if (Op.getResNo() == 1) {
4255 // If we know the result of a setcc has the top bits zero, use this info.
4256 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
4258 BitWidth > 1)
4259 Known.Zero.setBitsFrom(1);
4260 break;
4261 }
4262 [[fallthrough]];
4263 case ISD::SUBC: {
4264 assert(Op.getResNo() == 0 &&
4265 "We only compute knownbits for the difference here.");
4266
4267 // With USUBO_CARRY and SSUBO_CARRY a borrow bit may be added in.
4268 KnownBits Borrow(1);
4269 if (Opcode == ISD::USUBO_CARRY || Opcode == ISD::SSUBO_CARRY) {
4270 Borrow = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1);
4271 // Borrow has bit width 1
4272 Borrow = Borrow.trunc(1);
4273 } else {
4274 Borrow.setAllZero();
4275 }
4276
4277 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4278 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4279 Known = KnownBits::computeForSubBorrow(Known, Known2, Borrow);
4280 break;
4281 }
4282 case ISD::UADDO:
4283 case ISD::SADDO:
4284 case ISD::UADDO_CARRY:
4285 case ISD::SADDO_CARRY:
4286 if (Op.getResNo() == 1) {
4287 // If we know the result of a setcc has the top bits zero, use this info.
4288 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
4290 BitWidth > 1)
4291 Known.Zero.setBitsFrom(1);
4292 break;
4293 }
4294 [[fallthrough]];
4295 case ISD::ADDC:
4296 case ISD::ADDE: {
4297 assert(Op.getResNo() == 0 && "We only compute knownbits for the sum here.");
4298
4299 // With ADDE and UADDO_CARRY, a carry bit may be added in.
4300 KnownBits Carry(1);
4301 if (Opcode == ISD::ADDE)
4302 // Can't track carry from glue, set carry to unknown.
4303 Carry.resetAll();
4304 else if (Opcode == ISD::UADDO_CARRY || Opcode == ISD::SADDO_CARRY) {
4305 Carry = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1);
4306 // Carry has bit width 1
4307 Carry = Carry.trunc(1);
4308 } else {
4309 Carry.setAllZero();
4310 }
4311
4312 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4313 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4314 Known = KnownBits::computeForAddCarry(Known, Known2, Carry);
4315 break;
4316 }
4317 case ISD::UDIV: {
4318 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4319 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4320 Known = KnownBits::udiv(Known, Known2, Op->getFlags().hasExact());
4321 break;
4322 }
4323 case ISD::SDIV: {
4324 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4325 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4326 Known = KnownBits::sdiv(Known, Known2, Op->getFlags().hasExact());
4327 break;
4328 }
4329 case ISD::SREM: {
4330 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4331 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4332 Known = KnownBits::srem(Known, Known2);
4333 break;
4334 }
4335 case ISD::UREM: {
4336 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4337 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4338 Known = KnownBits::urem(Known, Known2);
4339 break;
4340 }
4341 case ISD::EXTRACT_ELEMENT: {
4342 Known = computeKnownBits(Op.getOperand(0), Depth+1);
4343 const unsigned Index = Op.getConstantOperandVal(1);
4344 const unsigned EltBitWidth = Op.getValueSizeInBits();
4345
4346 Known = Known.extractBits(EltBitWidth, Index * EltBitWidth);
4347 break;
4348 }
4350 SDValue InVec = Op.getOperand(0);
4351 SDValue EltNo = Op.getOperand(1);
4352 EVT VecVT = InVec.getValueType();
4353 // computeKnownBits not yet implemented for scalable vectors.
4354 if (VecVT.isScalableVector())
4355 break;
4356 const unsigned EltBitWidth = VecVT.getScalarSizeInBits();
4357 const unsigned NumSrcElts = VecVT.getVectorNumElements();
4358
4359 // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know
4360 // anything about the extended bits.
4361 if (BitWidth > EltBitWidth)
4362 Known = Known.trunc(EltBitWidth);
4363
4364 // If we know the element index, just demand that vector element, else for
4365 // an unknown element index, ignore DemandedElts and demand them all.
4366 APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
4367 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
4368 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
4369 DemandedSrcElts =
4370 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
4371
4372 Known = computeKnownBits(InVec, DemandedSrcElts, Depth + 1);
4373 if (BitWidth > EltBitWidth)
4374 Known = Known.anyext(BitWidth);
4375 break;
4376 }
4377 case ISD::BUILD_PAIR: {
4378 // Operand 0 is the low half and operand 1 the high half,
4379 // KnownBits::concat places its argument in the low bits.
4380 Known = computeKnownBits(Op.getOperand(0), Depth + 1);
4381 Known2 = computeKnownBits(Op.getOperand(1), Depth + 1);
4382 Known = Known2.concat(Known);
4383 break;
4384 }
4386 if (Op.getValueType().isScalableVector())
4387 break;
4388
4389 // If we know the element index, split the demand between the
4390 // source vector and the inserted element, otherwise assume we need
4391 // the original demanded vector elements and the value.
4392 SDValue InVec = Op.getOperand(0);
4393 SDValue InVal = Op.getOperand(1);
4394 SDValue EltNo = Op.getOperand(2);
4395 bool DemandedVal = true;
4396 APInt DemandedVecElts = DemandedElts;
4397 auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
4398 if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
4399 unsigned EltIdx = CEltNo->getZExtValue();
4400 DemandedVal = !!DemandedElts[EltIdx];
4401 DemandedVecElts.clearBit(EltIdx);
4402 }
4403 Known.setAllConflict();
4404 if (DemandedVal) {
4405 Known2 = computeKnownBits(InVal, Depth + 1);
4406 Known = Known.intersectWith(Known2.zextOrTrunc(BitWidth));
4407 }
4408 if (!!DemandedVecElts) {
4409 Known2 = computeKnownBits(InVec, DemandedVecElts, Depth + 1);
4410 Known = Known.intersectWith(Known2);
4411 }
4412 break;
4413 }
4414 case ISD::BITREVERSE: {
4415 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4416 Known = Known2.reverseBits();
4417 break;
4418 }
4419 case ISD::BSWAP: {
4420 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4421 Known = Known2.byteSwap();
4422 break;
4423 }
4424 case ISD::ABS:
4425 case ISD::ABS_MIN_POISON: {
4426 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4427 Known = Known2.abs();
4428 Known.Zero.setHighBits(
4429 ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1) - 1);
4430 break;
4431 }
4432 case ISD::USUBSAT: {
4433 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4434 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4435 Known = KnownBits::usub_sat(Known, Known2);
4436 break;
4437 }
4438 case ISD::UMIN: {
4439 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4440 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4441 Known = KnownBits::umin(Known, Known2);
4442 break;
4443 }
4444 case ISD::UMAX: {
4445 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4446 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4447 Known = KnownBits::umax(Known, Known2);
4448 break;
4449 }
4450 case ISD::SMIN:
4451 case ISD::SMAX: {
4452 // If we have a clamp pattern, we know that the number of sign bits will be
4453 // the minimum of the clamp min/max range.
4454 bool IsMax = (Opcode == ISD::SMAX);
4455 ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
4456 if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
4457 if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
4458 CstHigh =
4459 isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
4460 if (CstLow && CstHigh) {
4461 if (!IsMax)
4462 std::swap(CstLow, CstHigh);
4463
4464 const APInt &ValueLow = CstLow->getAPIntValue();
4465 const APInt &ValueHigh = CstHigh->getAPIntValue();
4466 if (ValueLow.sle(ValueHigh)) {
4467 unsigned LowSignBits = ValueLow.getNumSignBits();
4468 unsigned HighSignBits = ValueHigh.getNumSignBits();
4469 unsigned MinSignBits = std::min(LowSignBits, HighSignBits);
4470 if (ValueLow.isNegative() && ValueHigh.isNegative()) {
4471 Known.One.setHighBits(MinSignBits);
4472 break;
4473 }
4474 if (ValueLow.isNonNegative() && ValueHigh.isNonNegative()) {
4475 Known.Zero.setHighBits(MinSignBits);
4476 break;
4477 }
4478 }
4479 }
4480
4481 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4482 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4483 if (IsMax)
4484 Known = KnownBits::smax(Known, Known2);
4485 else
4486 Known = KnownBits::smin(Known, Known2);
4487
4488 // For SMAX, if CstLow is non-negative we know the result will be
4489 // non-negative and thus all sign bits are 0.
4490 // TODO: There's an equivalent of this for smin with negative constant for
4491 // known ones.
4492 if (IsMax && CstLow) {
4493 const APInt &ValueLow = CstLow->getAPIntValue();
4494 if (ValueLow.isNonNegative()) {
4495 unsigned SignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
4496 Known.Zero.setHighBits(std::min(SignBits, ValueLow.getNumSignBits()));
4497 }
4498 }
4499
4500 break;
4501 }
4502 case ISD::UINT_TO_FP: {
4503 Known.makeNonNegative();
4504 break;
4505 }
4506 case ISD::SINT_TO_FP: {
4507 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4508 if (Known2.isNonNegative())
4509 Known.makeNonNegative();
4510 else if (Known2.isNegative())
4511 Known.makeNegative();
4512 break;
4513 }
4514 case ISD::FP_TO_UINT_SAT: {
4515 // FP_TO_UINT_SAT produces an unsigned value that fits in the saturating VT.
4516 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
4518 break;
4519 }
4520 case ISD::ATOMIC_LOAD: {
4521 // If we are looking at the loaded value.
4522 if (Op.getResNo() == 0) {
4523 auto *AT = cast<AtomicSDNode>(Op);
4524 unsigned ScalarMemorySize = AT->getMemoryVT().getScalarSizeInBits();
4525 KnownBits KnownScalarMemory(ScalarMemorySize);
4526 if (const MDNode *MD = AT->getRanges())
4527 computeKnownBitsFromRangeMetadata(*MD, KnownScalarMemory);
4528
4529 switch (AT->getExtensionType()) {
4530 case ISD::ZEXTLOAD:
4531 Known = KnownScalarMemory.zext(BitWidth);
4532 break;
4533 case ISD::SEXTLOAD:
4534 Known = KnownScalarMemory.sext(BitWidth);
4535 break;
4536 case ISD::EXTLOAD:
4537 switch (TLI->getExtendForAtomicOps()) {
4538 case ISD::ZERO_EXTEND:
4539 Known = KnownScalarMemory.zext(BitWidth);
4540 break;
4541 case ISD::SIGN_EXTEND:
4542 Known = KnownScalarMemory.sext(BitWidth);
4543 break;
4544 default:
4545 Known = KnownScalarMemory.anyext(BitWidth);
4546 break;
4547 }
4548 break;
4549 case ISD::NON_EXTLOAD:
4550 Known = KnownScalarMemory;
4551 break;
4552 }
4553 assert(Known.getBitWidth() == BitWidth);
4554 }
4555 break;
4556 }
4558 if (Op.getResNo() == 1) {
4559 // The boolean result conforms to getBooleanContents.
4560 // If we know the result of a setcc has the top bits zero, use this info.
4561 if (TLI->getBooleanContents(Op.getValueType()) ==
4563 BitWidth > 1)
4564 Known.Zero.setBitsFrom(1);
4565 break;
4566 }
4567 [[fallthrough]];
4569 case ISD::ATOMIC_SWAP:
4580 case ISD::ATOMIC_LOAD_UMAX: {
4581 // If we are looking at the loaded value.
4582 if (Op.getResNo() == 0) {
4583 auto *AT = cast<AtomicSDNode>(Op);
4584 unsigned MemBits = AT->getMemoryVT().getScalarSizeInBits();
4585
4586 if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND)
4587 Known.Zero.setBitsFrom(MemBits);
4588 }
4589 break;
4590 }
4591 case ISD::FrameIndex:
4592 case ISD::TargetFrameIndex: {
4593 const MachineFunction &MF = getMachineFunction();
4594 int FrameIdx = cast<FrameIndexSDNode>(Op)->getIndex();
4595 TLI->computeKnownBitsForStackObjectPointer(
4596 Known, MF, MF.getFrameInfo().getObjectAlign(FrameIdx));
4597 break;
4598 }
4599 case ISD::VP_LOAD_FF: {
4600 if (Op.getResNo() != 1)
4601 break;
4602 // The second result of vp.load.ff is an unsigned value that is less than or
4603 // equal to the EVL operand.
4604 KnownBits VLKB =
4605 computeKnownBits(Op.getOperand(3), DemandedElts, Depth + 1);
4606 // The new VL is also bounded by the largest vector length.
4607 EVT ResVT = Op->getValueType(0);
4608 auto ResKB = KnownBits::makeConstant(
4610 if (ResVT.isScalableVector()) {
4612 ResKB = KnownBits::mul(getVScaleRange(&F, BitWidth).toKnownBits(), ResKB);
4613 }
4614 Known.Zero.setHighBits(KnownBits::umin(VLKB, ResKB).countMinLeadingZeros());
4615 break;
4616 }
4617
4618 default:
4619 if (Opcode < ISD::BUILTIN_OP_END)
4620 break;
4621 [[fallthrough]];
4625 // Allow the target to implement this method for its nodes.
4626 TLI->computeKnownBitsForTargetNode(Op, Known, DemandedElts, *this, Depth);
4627 break;
4628 }
4629
4630 return Known;
4631}
4632
4633/// Convert ConstantRange OverflowResult into SelectionDAG::OverflowKind.
4646
4649 // X + 0 never overflow
4650 if (isNullConstant(N1))
4651 return OFK_Never;
4652
4653 // If both operands each have at least two sign bits, the addition
4654 // cannot overflow.
4655 if (ComputeNumSignBits(N0) > 1 && ComputeNumSignBits(N1) > 1)
4656 return OFK_Never;
4657
4658 // TODO: Add ConstantRange::signedAddMayOverflow handling.
4659 return OFK_Sometime;
4660}
4661
4664 // X + 0 never overflow
4665 if (isNullConstant(N1))
4666 return OFK_Never;
4667
4668 // mulhi + 1 never overflow
4669 KnownBits N1Known = computeKnownBits(N1);
4670 if (N0.getOpcode() == ISD::UMUL_LOHI && N0.getResNo() == 1 &&
4671 N1Known.getMaxValue().ult(2))
4672 return OFK_Never;
4673
4674 KnownBits N0Known = computeKnownBits(N0);
4675 if (N1.getOpcode() == ISD::UMUL_LOHI && N1.getResNo() == 1 &&
4676 N0Known.getMaxValue().ult(2))
4677 return OFK_Never;
4678
4679 // Fallback to ConstantRange::unsignedAddMayOverflow handling.
4680 ConstantRange N0Range = ConstantRange::fromKnownBits(N0Known, false);
4681 ConstantRange N1Range = ConstantRange::fromKnownBits(N1Known, false);
4682 return mapOverflowResult(N0Range.unsignedAddMayOverflow(N1Range));
4683}
4684
4687 // X - 0 never overflow
4688 if (isNullConstant(N1))
4689 return OFK_Never;
4690
4691 // If both operands each have at least two sign bits, the subtraction
4692 // cannot overflow.
4693 if (ComputeNumSignBits(N0) > 1 && ComputeNumSignBits(N1) > 1)
4694 return OFK_Never;
4695
4696 KnownBits N0Known = computeKnownBits(N0);
4697 KnownBits N1Known = computeKnownBits(N1);
4698 ConstantRange N0Range = ConstantRange::fromKnownBits(N0Known, true);
4699 ConstantRange N1Range = ConstantRange::fromKnownBits(N1Known, true);
4700 return mapOverflowResult(N0Range.signedSubMayOverflow(N1Range));
4701}
4702
4705 // X - 0 never overflow
4706 if (isNullConstant(N1))
4707 return OFK_Never;
4708
4709 ConstantRange N0Range =
4710 computeConstantRangeIncludingKnownBits(N0, /*ForSigned=*/false);
4711 ConstantRange N1Range =
4712 computeConstantRangeIncludingKnownBits(N1, /*ForSigned=*/false);
4713 return mapOverflowResult(N0Range.unsignedSubMayOverflow(N1Range));
4714}
4715
4718 // X * 0 and X * 1 never overflow.
4719 if (isNullConstant(N1) || isOneConstant(N1))
4720 return OFK_Never;
4721
4724 return mapOverflowResult(N0Range.unsignedMulMayOverflow(N1Range));
4725}
4726
4729 // X * 0 and X * 1 never overflow.
4730 if (isNullConstant(N1) || isOneConstant(N1))
4731 return OFK_Never;
4732
4733 // Get the size of the result.
4734 unsigned BitWidth = N0.getScalarValueSizeInBits();
4735
4736 // Sum of the sign bits.
4737 unsigned SignBits = ComputeNumSignBits(N0) + ComputeNumSignBits(N1);
4738
4739 // If we have enough sign bits, then there's no overflow.
4740 if (SignBits > BitWidth + 1)
4741 return OFK_Never;
4742
4743 if (SignBits == BitWidth + 1) {
4744 // The overflow occurs when the true multiplication of the
4745 // the operands is the minimum negative number.
4746 KnownBits N0Known = computeKnownBits(N0);
4747 KnownBits N1Known = computeKnownBits(N1);
4748 // If one of the operands is non-negative, then there's no
4749 // overflow.
4750 if (N0Known.isNonNegative() || N1Known.isNonNegative())
4751 return OFK_Never;
4752 }
4753
4754 return OFK_Sometime;
4755}
4756
4758 unsigned Depth) const {
4759 APInt DemandedElts = getDemandAllEltsMask(Op);
4760 return computeConstantRange(Op, DemandedElts, ForSigned, Depth);
4761}
4762
4764 const APInt &DemandedElts,
4765 bool ForSigned,
4766 unsigned Depth) const {
4767 EVT VT = Op.getValueType();
4768 unsigned BitWidth = VT.getScalarSizeInBits();
4769
4770 if (Depth >= MaxRecursionDepth)
4771 return ConstantRange::getFull(BitWidth);
4772
4773 if (ConstantSDNode *C = isConstOrConstSplat(Op, DemandedElts))
4774 return ConstantRange(C->getAPIntValue());
4775
4776 unsigned Opcode = Op.getOpcode();
4777 switch (Opcode) {
4778 case ISD::VSCALE: {
4780 const APInt &Multiplier = Op.getConstantOperandAPInt(0);
4781 return getVScaleRange(&F, BitWidth).multiply(Multiplier);
4782 }
4783 default:
4784 break;
4785 }
4786
4787 return ConstantRange::getFull(BitWidth);
4788}
4789
4792 unsigned Depth) const {
4793 APInt DemandedElts = getDemandAllEltsMask(Op);
4794 return computeConstantRangeIncludingKnownBits(Op, DemandedElts, ForSigned,
4795 Depth);
4796}
4797
4799 SDValue Op, const APInt &DemandedElts, bool ForSigned,
4800 unsigned Depth) const {
4801 KnownBits Known = computeKnownBits(Op, DemandedElts, Depth);
4803 ConstantRange CR2 = computeConstantRange(Op, DemandedElts, ForSigned, Depth);
4806 return CR1.intersectWith(CR2, RangeType);
4807}
4808
4810 unsigned Depth) const {
4811 APInt DemandedElts = getDemandAllEltsMask(Val);
4812 return isKnownToBeAPowerOfTwo(Val, DemandedElts, OrZero, Depth);
4813}
4814
4816 const APInt &DemandedElts,
4817 bool OrZero, unsigned Depth) const {
4818 if (Depth >= MaxRecursionDepth)
4819 return false; // Limit search depth.
4820
4821 EVT OpVT = Val.getValueType();
4822 unsigned BitWidth = OpVT.getScalarSizeInBits();
4823 [[maybe_unused]] unsigned NumElts = DemandedElts.getBitWidth();
4824 assert((!OpVT.isScalableVector() || NumElts == 1) &&
4825 "DemandedElts for scalable vectors must be 1 to represent all lanes");
4826 assert(
4827 (!OpVT.isFixedLengthVector() || NumElts == OpVT.getVectorNumElements()) &&
4828 "Unexpected vector size");
4829
4830 auto IsPowerOfTwoOrZero = [BitWidth, OrZero](const ConstantSDNode *C) {
4831 APInt V = C->getAPIntValue().zextOrTrunc(BitWidth);
4832 return (OrZero && V.isZero()) || V.isPowerOf2();
4833 };
4834
4835 // Is the constant a known power of 2 or zero?
4836 if (ISD::matchUnaryPredicate(Val, DemandedElts, IsPowerOfTwoOrZero,
4837 /*AllowUndefs=*/false, /*AllowTruncation=*/true))
4838 return true;
4839
4840 switch (Val.getOpcode()) {
4842 SDValue InVec = Val.getOperand(0);
4843 SDValue EltNo = Val.getOperand(1);
4844 EVT VecVT = InVec.getValueType();
4845
4846 // Skip scalable vectors or implicit extensions.
4847 if (VecVT.isScalableVector() ||
4848 OpVT.getScalarSizeInBits() != VecVT.getScalarSizeInBits())
4849 break;
4850
4851 // If we know the element index, just demand that vector element, else for
4852 // an unknown element index, ignore DemandedElts and demand them all.
4853 const unsigned NumSrcElts = VecVT.getVectorNumElements();
4854 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
4855 APInt DemandedSrcElts =
4856 ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts)
4857 ? APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue())
4858 : APInt::getAllOnes(NumSrcElts);
4859 return isKnownToBeAPowerOfTwo(InVec, DemandedSrcElts, OrZero, Depth + 1);
4860 }
4861
4862 case ISD::AND: {
4863 // Looking for `x & -x` pattern:
4864 // If x == 0:
4865 // x & -x -> 0
4866 // If x != 0:
4867 // x & -x -> non-zero pow2
4868 // so if we find the pattern return whether we know `x` is non-zero.
4869 SDValue X, Z;
4870 if (sd_match(Val, m_And(m_Value(X), m_Neg(m_Deferred(X)))) ||
4871 (sd_match(Val, m_And(m_Value(X), m_Sub(m_Value(Z), m_Deferred(X)))) &&
4872 MaskedVectorIsZero(Z, DemandedElts, Depth + 1)))
4873 return OrZero || isKnownNeverZero(X, DemandedElts, Depth);
4874 break;
4875 }
4876
4877 case ISD::SHL: {
4878 // A left-shift of a constant one will have exactly one bit set because
4879 // shifting the bit off the end is undefined.
4880 auto *C = isConstOrConstSplat(Val.getOperand(0), DemandedElts);
4881 if (C && C->getAPIntValue() == 1)
4882 return true;
4883 return (OrZero || isKnownNeverZero(Val, DemandedElts, Depth)) &&
4884 isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedElts, OrZero,
4885 Depth + 1);
4886 }
4887
4888 case ISD::SRL: {
4889 // A logical right-shift of a constant sign-bit will have exactly
4890 // one bit set.
4891 auto *C = isConstOrConstSplat(Val.getOperand(0), DemandedElts);
4892 if (C && C->getAPIntValue().isSignMask())
4893 return true;
4894 return (OrZero || isKnownNeverZero(Val, DemandedElts, Depth)) &&
4895 isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedElts, OrZero,
4896 Depth + 1);
4897 }
4898
4899 case ISD::TRUNCATE:
4900 return (OrZero || isKnownNeverZero(Val, DemandedElts, Depth)) &&
4901 isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedElts, OrZero,
4902 Depth + 1);
4903
4904 case ISD::ROTL:
4905 case ISD::ROTR:
4906 return isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedElts, OrZero,
4907 Depth + 1);
4908 case ISD::BSWAP:
4909 case ISD::BITREVERSE:
4910 return isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedElts, OrZero,
4911 Depth + 1);
4912
4913 case ISD::SMIN:
4914 case ISD::SMAX:
4915 case ISD::UMIN:
4916 case ISD::UMAX:
4917 return isKnownToBeAPowerOfTwo(Val.getOperand(1), DemandedElts, OrZero,
4918 Depth + 1) &&
4919 isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedElts, OrZero,
4920 Depth + 1);
4921
4922 case ISD::SELECT:
4923 case ISD::VSELECT:
4924 return isKnownToBeAPowerOfTwo(Val.getOperand(2), DemandedElts, OrZero,
4925 Depth + 1) &&
4926 isKnownToBeAPowerOfTwo(Val.getOperand(1), DemandedElts, OrZero,
4927 Depth + 1);
4928
4929 case ISD::ZERO_EXTEND:
4930 return isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedElts, OrZero,
4931 Depth + 1);
4932
4933 case ISD::VSCALE:
4934 // vscale(power-of-two) is a power-of-two
4935 return isKnownToBeAPowerOfTwo(Val.getOperand(0), /*OrZero=*/false,
4936 Depth + 1);
4937
4938 case ISD::VECTOR_SHUFFLE: {
4940 // Demanded elements with undef shuffle mask elements are unknown
4941 // - we cannot guarantee they are a power of two, so return false.
4942 APInt DemandedLHS, DemandedRHS;
4944 assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
4945 if (!getShuffleDemandedElts(NumElts, SVN->getMask(), DemandedElts,
4946 DemandedLHS, DemandedRHS))
4947 return false;
4948
4949 // All demanded elements from LHS must be known power of two.
4950 if (!!DemandedLHS && !isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedLHS,
4951 OrZero, Depth + 1))
4952 return false;
4953
4954 // All demanded elements from RHS must be known power of two.
4955 if (!!DemandedRHS && !isKnownToBeAPowerOfTwo(Val.getOperand(1), DemandedRHS,
4956 OrZero, Depth + 1))
4957 return false;
4958
4959 return true;
4960 }
4961 }
4962
4963 // More could be done here, though the above checks are enough
4964 // to handle some common cases.
4965 return false;
4966}
4967
4969 if (ConstantFPSDNode *C1 = isConstOrConstSplatFP(Val, true))
4970 return C1->getValueAPF().getExactLog2Abs() >= 0;
4971
4972 if (Val.getOpcode() == ISD::UINT_TO_FP || Val.getOpcode() == ISD::SINT_TO_FP)
4973 return isKnownToBeAPowerOfTwo(Val.getOperand(0), Depth + 1);
4974
4975 return false;
4976}
4977
4979 APInt DemandedElts = getDemandAllEltsMask(Op);
4980 return ComputeNumSignBits(Op, DemandedElts, Depth);
4981}
4982
4983unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, const APInt &DemandedElts,
4984 unsigned Depth) const {
4985 EVT VT = Op.getValueType();
4986 assert((VT.isInteger() || VT.isFloatingPoint()) && "Invalid VT!");
4987 unsigned VTBits = VT.getScalarSizeInBits();
4988 unsigned NumElts = DemandedElts.getBitWidth();
4989 unsigned Tmp, Tmp2;
4990 unsigned FirstAnswer = 1;
4991
4992 assert((!VT.isScalableVector() || NumElts == 1) &&
4993 "DemandedElts for scalable vectors must be 1 to represent all lanes");
4994
4995 if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
4996 const APInt &Val = C->getAPIntValue();
4997 return Val.getNumSignBits();
4998 }
4999
5000 if (Depth >= MaxRecursionDepth)
5001 return 1; // Limit search depth.
5002
5003 if (!DemandedElts)
5004 return 1; // No demanded elts, better to assume we don't know anything.
5005
5006 unsigned Opcode = Op.getOpcode();
5007 switch (Opcode) {
5008 default: break;
5009 case ISD::AssertSext:
5010 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
5011 return VTBits-Tmp+1;
5012 case ISD::AssertZext:
5013 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
5014 return VTBits-Tmp;
5015 case ISD::FREEZE:
5016 if (isGuaranteedNotToBeUndefOrPoison(Op.getOperand(0), DemandedElts,
5018 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5019 break;
5020 case ISD::MERGE_VALUES:
5021 return ComputeNumSignBits(Op.getOperand(Op.getResNo()), DemandedElts,
5022 Depth + 1);
5023 case ISD::SPLAT_VECTOR: {
5024 // Check if the sign bits of source go down as far as the truncated value.
5025 unsigned NumSrcBits = Op.getOperand(0).getValueSizeInBits();
5026 unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
5027 if (NumSrcSignBits > (NumSrcBits - VTBits))
5028 return NumSrcSignBits - (NumSrcBits - VTBits);
5029 break;
5030 }
5031 case ISD::BUILD_VECTOR:
5032 assert(!VT.isScalableVector());
5033 Tmp = VTBits;
5034 for (unsigned i = 0, e = Op.getNumOperands(); (i < e) && (Tmp > 1); ++i) {
5035 if (!DemandedElts[i])
5036 continue;
5037
5038 SDValue SrcOp = Op.getOperand(i);
5039 // BUILD_VECTOR can implicitly truncate sources, we handle this specially
5040 // for constant nodes to ensure we only look at the sign bits.
5042 APInt T = C->getAPIntValue().trunc(VTBits);
5043 Tmp2 = T.getNumSignBits();
5044 } else if (SrcOp.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5045 SrcOp.getOperand(0).getScalarValueSizeInBits() >= VTBits) {
5046 // EXTRACT_VECTOR_ELT can extend the value with high bits undefined. If
5047 // this BUILD_VECTOR truncates those undefined bits we can just look
5048 // through the SrcOp and query the vector directly.
5049 SDValue InVec = SrcOp.getOperand(0);
5050 EVT InVecVT = InVec.getValueType();
5051
5052 APInt DemandedSrcElts;
5053 if (InVecVT.isScalableVector())
5054 // Demand all elements.
5055 DemandedSrcElts = APInt(1, 1);
5056 else {
5057 unsigned NumSrcElts = InVecVT.getVectorNumElements();
5058 auto *ConstEltNo = dyn_cast<ConstantSDNode>(SrcOp.getOperand(1));
5059 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
5060 DemandedSrcElts =
5061 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
5062 else
5063 DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
5064 }
5065
5066 Tmp2 = ComputeNumSignBits(InVec, DemandedSrcElts, Depth + 1);
5067 unsigned ExtraBits = InVec.getScalarValueSizeInBits() - VTBits;
5068 if (ExtraBits)
5069 Tmp2 = (Tmp2 > ExtraBits ? Tmp2 - ExtraBits : 1);
5070 } else {
5071 Tmp2 = ComputeNumSignBits(SrcOp, Depth + 1);
5072
5073 if (SrcOp.getValueSizeInBits() != VTBits) {
5074 assert(SrcOp.getValueSizeInBits() > VTBits &&
5075 "Expected BUILD_VECTOR implicit truncation");
5076 unsigned ExtraBits = SrcOp.getValueSizeInBits() - VTBits;
5077 Tmp2 = (Tmp2 > ExtraBits ? Tmp2 - ExtraBits : 1);
5078 }
5079 }
5080 Tmp = std::min(Tmp, Tmp2);
5081 }
5082 return Tmp;
5083
5084 case ISD::VECTOR_COMPRESS: {
5085 SDValue Vec = Op.getOperand(0);
5086 SDValue PassThru = Op.getOperand(2);
5087 Tmp = ComputeNumSignBits(PassThru, DemandedElts, Depth + 1);
5088 if (Tmp == 1)
5089 return 1;
5090 Tmp2 = ComputeNumSignBits(Vec, Depth + 1);
5091 Tmp = std::min(Tmp, Tmp2);
5092 return Tmp;
5093 }
5094
5095 case ISD::VECTOR_SHUFFLE: {
5096 // Collect the minimum number of sign bits that are shared by every vector
5097 // element referenced by the shuffle.
5098 APInt DemandedLHS, DemandedRHS;
5100 assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
5101 if (!getShuffleDemandedElts(NumElts, SVN->getMask(), DemandedElts,
5102 DemandedLHS, DemandedRHS))
5103 return 1;
5104
5105 Tmp = std::numeric_limits<unsigned>::max();
5106 if (!!DemandedLHS)
5107 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedLHS, Depth + 1);
5108 if (!!DemandedRHS) {
5109 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedRHS, Depth + 1);
5110 Tmp = std::min(Tmp, Tmp2);
5111 }
5112 // If we don't know anything, early out and try computeKnownBits fall-back.
5113 if (Tmp == 1)
5114 break;
5115 assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
5116 return Tmp;
5117 }
5118
5119 case ISD::BITCAST: {
5120 if (VT.isScalableVector())
5121 break;
5122 SDValue N0 = Op.getOperand(0);
5123 EVT SrcVT = N0.getValueType();
5124 unsigned SrcBits = SrcVT.getScalarSizeInBits();
5125
5126 // Ignore bitcasts from unsupported types..
5127 if (!(SrcVT.isInteger() || SrcVT.isFloatingPoint()))
5128 break;
5129
5130 // Fast handling of 'identity' bitcasts.
5131 if (VTBits == SrcBits)
5132 return ComputeNumSignBits(N0, DemandedElts, Depth + 1);
5133
5134 bool IsLE = getDataLayout().isLittleEndian();
5135
5136 // Bitcast 'large element' scalar/vector to 'small element' vector.
5137 if ((SrcBits % VTBits) == 0) {
5138 assert(VT.isVector() && "Expected bitcast to vector");
5139
5140 unsigned Scale = SrcBits / VTBits;
5141 APInt SrcDemandedElts =
5142 APIntOps::ScaleBitMask(DemandedElts, NumElts / Scale);
5143
5144 // Fast case - sign splat can be simply split across the small elements.
5145 Tmp = ComputeNumSignBits(N0, SrcDemandedElts, Depth + 1);
5146 if (Tmp == SrcBits)
5147 return VTBits;
5148
5149 // Slow case - determine how far the sign extends into each sub-element.
5150 Tmp2 = VTBits;
5151 for (unsigned i = 0; i != NumElts; ++i)
5152 if (DemandedElts[i]) {
5153 unsigned SubOffset = i % Scale;
5154 SubOffset = (IsLE ? ((Scale - 1) - SubOffset) : SubOffset);
5155 SubOffset = SubOffset * VTBits;
5156 if (Tmp <= SubOffset)
5157 return 1;
5158 Tmp2 = std::min(Tmp2, Tmp - SubOffset);
5159 }
5160 return Tmp2;
5161 }
5162 break;
5163 }
5164
5166 // FP_TO_SINT_SAT produces a signed value that fits in the saturating VT.
5167 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
5168 return VTBits - Tmp + 1;
5169 case ISD::SIGN_EXTEND:
5170 Tmp = VTBits - Op.getOperand(0).getScalarValueSizeInBits();
5171 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1) + Tmp;
5173 // Max of the input and what this extends.
5174 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
5175 Tmp = VTBits-Tmp+1;
5176 Tmp2 = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
5177 return std::max(Tmp, Tmp2);
5179 if (VT.isScalableVector())
5180 break;
5181 SDValue Src = Op.getOperand(0);
5182 EVT SrcVT = Src.getValueType();
5183 APInt DemandedSrcElts = DemandedElts.zext(SrcVT.getVectorNumElements());
5184 Tmp = VTBits - SrcVT.getScalarSizeInBits();
5185 return ComputeNumSignBits(Src, DemandedSrcElts, Depth+1) + Tmp;
5186 }
5187 case ISD::SRA:
5188 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5189 // SRA X, C -> adds C sign bits.
5190 if (std::optional<unsigned> ShAmt =
5191 getValidMinimumShiftAmount(Op, DemandedElts, Depth + 1))
5192 Tmp = std::min(Tmp + *ShAmt, VTBits);
5193 return Tmp;
5194 case ISD::SHL:
5195 if (std::optional<ConstantRange> ShAmtRange =
5196 getValidShiftAmountRange(Op, DemandedElts, Depth + 1)) {
5197 unsigned MaxShAmt = ShAmtRange->getUnsignedMax().getZExtValue();
5198 unsigned MinShAmt = ShAmtRange->getUnsignedMin().getZExtValue();
5199 // Try to look through ZERO/SIGN/ANY_EXTEND. If all extended bits are
5200 // shifted out, then we can compute the number of sign bits for the
5201 // operand being extended. A future improvement could be to pass along the
5202 // "shifted left by" information in the recursive calls to
5203 // ComputeKnownSignBits. Allowing us to handle this more generically.
5204 if (ISD::isExtOpcode(Op.getOperand(0).getOpcode())) {
5205 SDValue Ext = Op.getOperand(0);
5206 EVT ExtVT = Ext.getValueType();
5207 SDValue Extendee = Ext.getOperand(0);
5208 EVT ExtendeeVT = Extendee.getValueType();
5209 unsigned SizeDifference =
5210 ExtVT.getScalarSizeInBits() - ExtendeeVT.getScalarSizeInBits();
5211 if (SizeDifference <= MinShAmt) {
5212 Tmp = SizeDifference +
5213 ComputeNumSignBits(Extendee, DemandedElts, Depth + 1);
5214 if (MaxShAmt < Tmp)
5215 return Tmp - MaxShAmt;
5216 }
5217 }
5218 // shl destroys sign bits, ensure it doesn't shift out all sign bits.
5219 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5220 if (MaxShAmt < Tmp)
5221 return Tmp - MaxShAmt;
5222 }
5223 break;
5224 case ISD::AND:
5225 case ISD::OR:
5226 case ISD::XOR: // NOT is handled here.
5227 // Logical binary ops preserve the number of sign bits at the worst.
5228 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
5229 if (Tmp != 1) {
5230 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
5231 FirstAnswer = std::min(Tmp, Tmp2);
5232 // We computed what we know about the sign bits as our first
5233 // answer. Now proceed to the generic code that uses
5234 // computeKnownBits, and pick whichever answer is better.
5235 }
5236 break;
5237
5238 case ISD::SELECT:
5239 case ISD::VSELECT:
5240 Tmp = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
5241 if (Tmp == 1) return 1; // Early out.
5242 Tmp2 = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
5243 return std::min(Tmp, Tmp2);
5244 case ISD::SELECT_CC:
5245 Tmp = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
5246 if (Tmp == 1) return 1; // Early out.
5247 Tmp2 = ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth+1);
5248 return std::min(Tmp, Tmp2);
5249
5250 case ISD::SMIN:
5251 case ISD::SMAX: {
5252 // If we have a clamp pattern, we know that the number of sign bits will be
5253 // the minimum of the clamp min/max range.
5254 bool IsMax = (Opcode == ISD::SMAX);
5255 ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
5256 if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
5257 if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
5258 CstHigh =
5259 isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
5260 if (CstLow && CstHigh) {
5261 if (!IsMax)
5262 std::swap(CstLow, CstHigh);
5263 if (CstLow->getAPIntValue().sle(CstHigh->getAPIntValue())) {
5264 Tmp = CstLow->getAPIntValue().getNumSignBits();
5265 Tmp2 = CstHigh->getAPIntValue().getNumSignBits();
5266 return std::min(Tmp, Tmp2);
5267 }
5268 }
5269
5270 // Fallback - just get the minimum number of sign bits of the operands.
5271 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5272 if (Tmp == 1)
5273 return 1; // Early out.
5274 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
5275 return std::min(Tmp, Tmp2);
5276 }
5277 case ISD::UMIN:
5278 case ISD::UMAX:
5279 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5280 if (Tmp == 1)
5281 return 1; // Early out.
5282 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
5283 return std::min(Tmp, Tmp2);
5284 case ISD::SSUBO_CARRY:
5285 case ISD::USUBO_CARRY:
5286 // sub_carry(x,x,c) -> 0/-1 (sext carry)
5287 if (Op.getResNo() == 0 && Op.getOperand(0) == Op.getOperand(1))
5288 return VTBits;
5289 [[fallthrough]];
5290 case ISD::SADDO:
5291 case ISD::UADDO:
5292 case ISD::SADDO_CARRY:
5293 case ISD::UADDO_CARRY:
5294 case ISD::SSUBO:
5295 case ISD::USUBO:
5296 case ISD::SMULO:
5297 case ISD::UMULO:
5298 if (Op.getResNo() != 1)
5299 break;
5300 // The boolean result conforms to getBooleanContents.
5301 // If setcc returns 0/-1, all bits are sign bits.
5302 if (TLI->getBooleanContents(VT) ==
5304 return VTBits;
5305 break;
5306 case ISD::SETCC:
5307 case ISD::SETCCCARRY:
5308 case ISD::STRICT_FSETCC:
5309 case ISD::STRICT_FSETCCS: {
5310 unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
5311 // If setcc returns 0/-1, all bits are sign bits.
5312 if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
5314 return VTBits;
5315 break;
5316 }
5319 // Semantically similar to icmp ult.
5320 if (TLI->getBooleanContents(VT) ==
5322 return VTBits;
5323 break;
5324 case ISD::ROTL:
5325 case ISD::ROTR: {
5326 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5327 ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(1), DemandedElts);
5328 FirstAnswer = SignBitsOps::rot(
5329 Tmp, VTBits, C ? std::optional(C->getAPIntValue()) : std::nullopt,
5330 Opcode == ISD::ROTR);
5331 break;
5332 }
5333 case ISD::ADD:
5334 case ISD::ADDC:
5335 // TODO: Move Operand 1 check before Operand 0 check
5336 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5337 if (Tmp == 1) return 1; // Early out.
5338
5339 // Special case decrementing a value (ADD X, -1):
5340 if (ConstantSDNode *CRHS =
5341 isConstOrConstSplat(Op.getOperand(1), DemandedElts))
5342 if (CRHS->isAllOnes()) {
5344 computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
5345
5346 // If the input is known to be 0 or 1, the output is 0/-1, which is all
5347 // sign bits set.
5348 if ((Known.Zero | 1).isAllOnes())
5349 return VTBits;
5350
5351 // If we are subtracting one from a positive number, there is no carry
5352 // out of the result.
5353 if (Known.isNonNegative())
5354 return Tmp;
5355 }
5356
5357 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
5358 if (Tmp2 == 1) return 1; // Early out.
5359
5360 // Add can have at most one carry bit. Thus we know that the output
5361 // is, at worst, one more bit than the inputs.
5362 return std::min(Tmp, Tmp2) - 1;
5363 case ISD::SUB:
5364 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
5365 if (Tmp2 == 1) return 1; // Early out.
5366
5367 // Handle NEG.
5368 if (ConstantSDNode *CLHS =
5369 isConstOrConstSplat(Op.getOperand(0), DemandedElts))
5370 if (CLHS->isZero()) {
5372 computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
5373 // If the input is known to be 0 or 1, the output is 0/-1, which is all
5374 // sign bits set.
5375 if ((Known.Zero | 1).isAllOnes())
5376 return VTBits;
5377
5378 // If the input is known to be positive (the sign bit is known clear),
5379 // the output of the NEG has the same number of sign bits as the input.
5380 if (Known.isNonNegative())
5381 return Tmp2;
5382
5383 // Otherwise, we treat this like a SUB.
5384 }
5385
5386 // Sub can have at most one carry bit. Thus we know that the output
5387 // is, at worst, one more bit than the inputs.
5388 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5389 if (Tmp == 1) return 1; // Early out.
5390 return std::min(Tmp, Tmp2) - 1;
5391 case ISD::MUL: {
5392 // The output of the Mul can be at most twice the valid bits in the inputs.
5393 unsigned SignBitsOp0 =
5394 ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5395 if (SignBitsOp0 == 1)
5396 break;
5397 unsigned SignBitsOp1 =
5398 ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
5399 if (SignBitsOp1 == 1)
5400 break;
5401 unsigned OutValidBits =
5402 (VTBits - SignBitsOp0 + 1) + (VTBits - SignBitsOp1 + 1);
5403 return OutValidBits > VTBits ? 1 : VTBits - OutValidBits + 1;
5404 }
5405 case ISD::AVGCEILS:
5406 case ISD::AVGFLOORS:
5407 case ISD::AVGSUBFLOORS:
5408 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5409 if (Tmp == 1)
5410 return 1; // Early out.
5411 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
5412 return std::min(Tmp, Tmp2);
5413 case ISD::SREM:
5414 // The sign bit is the LHS's sign bit, except when the result of the
5415 // remainder is zero. The magnitude of the result should be less than or
5416 // equal to the magnitude of the LHS. Therefore, the result should have
5417 // at least as many sign bits as the left hand side.
5418 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5419 case ISD::TRUNCATE: {
5420 // Check if the sign bits of source go down as far as the truncated value.
5421 unsigned NumSrcBits = Op.getOperand(0).getScalarValueSizeInBits();
5422 unsigned NumSrcSignBits =
5423 ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5424 if (NumSrcSignBits > (NumSrcBits - VTBits))
5425 return NumSrcSignBits - (NumSrcBits - VTBits);
5426 break;
5427 }
5428 case ISD::EXTRACT_ELEMENT: {
5429 if (VT.isScalableVector())
5430 break;
5431 const int KnownSign = ComputeNumSignBits(Op.getOperand(0), Depth+1);
5432 const int BitWidth = Op.getValueSizeInBits();
5433 const int Items = Op.getOperand(0).getValueSizeInBits() / BitWidth;
5434
5435 // Get reverse index (starting from 1), Op1 value indexes elements from
5436 // little end. Sign starts at big end.
5437 const int rIndex = Items - 1 - Op.getConstantOperandVal(1);
5438
5439 // If the sign portion ends in our element the subtraction gives correct
5440 // result. Otherwise it gives either negative or > bitwidth result
5441 return std::clamp(KnownSign - rIndex * BitWidth, 1, BitWidth);
5442 }
5444 if (VT.isScalableVector())
5445 break;
5446 // If we know the element index, split the demand between the
5447 // source vector and the inserted element, otherwise assume we need
5448 // the original demanded vector elements and the value.
5449 SDValue InVec = Op.getOperand(0);
5450 SDValue InVal = Op.getOperand(1);
5451 SDValue EltNo = Op.getOperand(2);
5452 bool DemandedVal = true;
5453 APInt DemandedVecElts = DemandedElts;
5454 auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
5455 if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
5456 unsigned EltIdx = CEltNo->getZExtValue();
5457 DemandedVal = !!DemandedElts[EltIdx];
5458 DemandedVecElts.clearBit(EltIdx);
5459 }
5460 Tmp = std::numeric_limits<unsigned>::max();
5461 if (DemandedVal) {
5462 // TODO - handle implicit truncation of inserted elements.
5463 if (InVal.getScalarValueSizeInBits() != VTBits)
5464 break;
5465 Tmp2 = ComputeNumSignBits(InVal, Depth + 1);
5466 Tmp = std::min(Tmp, Tmp2);
5467 }
5468 if (!!DemandedVecElts) {
5469 Tmp2 = ComputeNumSignBits(InVec, DemandedVecElts, Depth + 1);
5470 Tmp = std::min(Tmp, Tmp2);
5471 }
5472 assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
5473 return Tmp;
5474 }
5476 SDValue InVec = Op.getOperand(0);
5477 SDValue EltNo = Op.getOperand(1);
5478 EVT VecVT = InVec.getValueType();
5479 // ComputeNumSignBits not yet implemented for scalable vectors.
5480 if (VecVT.isScalableVector())
5481 break;
5482 const unsigned BitWidth = Op.getValueSizeInBits();
5483 const unsigned EltBitWidth = Op.getOperand(0).getScalarValueSizeInBits();
5484 const unsigned NumSrcElts = VecVT.getVectorNumElements();
5485
5486 // If BitWidth > EltBitWidth the value is anyext:ed, and we do not know
5487 // anything about sign bits. But if the sizes match we can derive knowledge
5488 // about sign bits from the vector operand.
5489 if (BitWidth != EltBitWidth)
5490 break;
5491
5492 // If we know the element index, just demand that vector element, else for
5493 // an unknown element index, ignore DemandedElts and demand them all.
5494 APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
5495 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
5496 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
5497 DemandedSrcElts =
5498 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
5499
5500 return ComputeNumSignBits(InVec, DemandedSrcElts, Depth + 1);
5501 }
5503 // Offset the demanded elts by the subvector index.
5504 SDValue Src = Op.getOperand(0);
5505
5506 APInt DemandedSrcElts;
5507 if (Src.getValueType().isScalableVector())
5508 DemandedSrcElts = APInt(1, 1);
5509 else {
5510 uint64_t Idx = Op.getConstantOperandVal(1);
5511 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
5512 DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
5513 }
5514 return ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
5515 }
5516 case ISD::CONCAT_VECTORS: {
5517 if (VT.isScalableVector())
5518 break;
5519 // Determine the minimum number of sign bits across all demanded
5520 // elts of the input vectors. Early out if the result is already 1.
5521 Tmp = std::numeric_limits<unsigned>::max();
5522 EVT SubVectorVT = Op.getOperand(0).getValueType();
5523 unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
5524 unsigned NumSubVectors = Op.getNumOperands();
5525 for (unsigned i = 0; (i < NumSubVectors) && (Tmp > 1); ++i) {
5526 APInt DemandedSub =
5527 DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts);
5528 if (!DemandedSub)
5529 continue;
5530 Tmp2 = ComputeNumSignBits(Op.getOperand(i), DemandedSub, Depth + 1);
5531 Tmp = std::min(Tmp, Tmp2);
5532 }
5533 assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
5534 return Tmp;
5535 }
5536 case ISD::INSERT_SUBVECTOR: {
5537 SDValue Src = Op.getOperand(0);
5538 SDValue Sub = Op.getOperand(1);
5539 if (VT.isScalableVector()) {
5540 Tmp = ComputeNumSignBits(Sub, Depth + 1);
5541 Tmp = std::min(Tmp, ComputeNumSignBits(Src, Depth + 1));
5542 return Tmp;
5543 }
5544 // Demand any elements from the subvector and the remainder from the src its
5545 // inserted into.
5546 uint64_t Idx = Op.getConstantOperandVal(2);
5547 unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
5548 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
5549 APInt DemandedSrcElts = DemandedElts;
5550 DemandedSrcElts.clearBits(Idx, Idx + NumSubElts);
5551
5552 Tmp = std::numeric_limits<unsigned>::max();
5553 if (!!DemandedSubElts) {
5554 Tmp = ComputeNumSignBits(Sub, DemandedSubElts, Depth + 1);
5555 if (Tmp == 1)
5556 return 1; // early-out
5557 }
5558 if (!!DemandedSrcElts) {
5559 Tmp2 = ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
5560 Tmp = std::min(Tmp, Tmp2);
5561 }
5562 assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
5563 return Tmp;
5564 }
5565 case ISD::LOAD: {
5566 // If we are looking at the loaded value of the SDNode.
5567 if (Op.getResNo() != 0)
5568 break;
5569
5571 if (const MDNode *Ranges = LD->getRanges()) {
5572 if (DemandedElts != 1)
5573 break;
5574
5576 if (VTBits > CR.getBitWidth()) {
5577 switch (LD->getExtensionType()) {
5578 case ISD::SEXTLOAD:
5579 CR = CR.signExtend(VTBits);
5580 break;
5581 case ISD::ZEXTLOAD:
5582 CR = CR.zeroExtend(VTBits);
5583 break;
5584 default:
5585 break;
5586 }
5587 }
5588
5589 if (VTBits != CR.getBitWidth())
5590 break;
5591 return std::min(CR.getSignedMin().getNumSignBits(),
5593 }
5594
5595 unsigned ExtType = LD->getExtensionType();
5596 switch (ExtType) {
5597 default:
5598 break;
5599 case ISD::SEXTLOAD: // e.g. i16->i32 = '17' bits known.
5600 Tmp = LD->getMemoryVT().getScalarSizeInBits();
5601 return VTBits - Tmp + 1;
5602 case ISD::ZEXTLOAD: // e.g. i16->i32 = '16' bits known.
5603 Tmp = LD->getMemoryVT().getScalarSizeInBits();
5604 return VTBits - Tmp;
5605 case ISD::NON_EXTLOAD:
5606 if (const Constant *Cst = TLI->getTargetConstantFromLoad(LD)) {
5607 // We only need to handle vectors - computeKnownBits should handle
5608 // scalar cases.
5609 Type *CstTy = Cst->getType();
5610 if (CstTy->isVectorTy() && !VT.isScalableVector() &&
5611 (NumElts * VTBits) == CstTy->getPrimitiveSizeInBits() &&
5612 VTBits == CstTy->getScalarSizeInBits()) {
5613 Tmp = VTBits;
5614 for (unsigned i = 0; i != NumElts; ++i) {
5615 if (!DemandedElts[i])
5616 continue;
5617 if (Constant *Elt = Cst->getAggregateElement(i)) {
5618 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
5619 const APInt &Value = CInt->getValue();
5620 Tmp = std::min(Tmp, Value.getNumSignBits());
5621 continue;
5622 }
5623 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
5624 APInt Value = CFP->getValueAPF().bitcastToAPInt();
5625 Tmp = std::min(Tmp, Value.getNumSignBits());
5626 continue;
5627 }
5628 }
5629 // Unknown type. Conservatively assume no bits match sign bit.
5630 return 1;
5631 }
5632 return Tmp;
5633 }
5634 }
5635 break;
5636 }
5637
5638 break;
5639 }
5642 case ISD::ATOMIC_SWAP:
5654 case ISD::ATOMIC_LOAD: {
5655 auto *AT = cast<AtomicSDNode>(Op);
5656 // If we are looking at the loaded value.
5657 if (Op.getResNo() == 0) {
5658 Tmp = AT->getMemoryVT().getScalarSizeInBits();
5659 if (Tmp == VTBits)
5660 return 1; // early-out
5661
5662 // For atomic_load, prefer to use the extension type.
5663 if (Op->getOpcode() == ISD::ATOMIC_LOAD) {
5664 switch (AT->getExtensionType()) {
5665 default:
5666 break;
5667 case ISD::SEXTLOAD:
5668 return VTBits - Tmp + 1;
5669 case ISD::ZEXTLOAD:
5670 return VTBits - Tmp;
5671 }
5672 }
5673
5674 if (TLI->getExtendForAtomicOps() == ISD::SIGN_EXTEND)
5675 return VTBits - Tmp + 1;
5676 if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND)
5677 return VTBits - Tmp;
5678 }
5679 break;
5680 }
5681 }
5682
5683 // Allow the target to implement this method for its nodes.
5684 if (Opcode >= ISD::BUILTIN_OP_END ||
5685 Opcode == ISD::INTRINSIC_WO_CHAIN ||
5686 Opcode == ISD::INTRINSIC_W_CHAIN ||
5687 Opcode == ISD::INTRINSIC_VOID) {
5688 // TODO: This can probably be removed once target code is audited. This
5689 // is here purely to reduce patch size and review complexity.
5690 if (!VT.isScalableVector()) {
5691 unsigned NumBits =
5692 TLI->ComputeNumSignBitsForTargetNode(Op, DemandedElts, *this, Depth);
5693 if (NumBits > 1)
5694 FirstAnswer = std::max(FirstAnswer, NumBits);
5695 }
5696 }
5697
5698 // Finally, if we can prove that the top bits of the result are 0's or 1's,
5699 // use this information.
5700 KnownBits Known = computeKnownBits(Op, DemandedElts, Depth);
5701 return std::max(FirstAnswer, Known.countMinSignBits());
5702}
5703
5705 unsigned Depth) const {
5706 unsigned SignBits = ComputeNumSignBits(Op, Depth);
5707 return Op.getScalarValueSizeInBits() - SignBits + 1;
5708}
5709
5711 const APInt &DemandedElts,
5712 unsigned Depth) const {
5713 unsigned SignBits = ComputeNumSignBits(Op, DemandedElts, Depth);
5714 return Op.getScalarValueSizeInBits() - SignBits + 1;
5715}
5716
5718 UndefPoisonKind Kind,
5719 unsigned Depth) const {
5720 // Early out for FREEZE.
5721 if (Op.getOpcode() == ISD::FREEZE)
5722 return true;
5723
5724 APInt DemandedElts = getDemandAllEltsMask(Op);
5725 return isGuaranteedNotToBeUndefOrPoison(Op, DemandedElts, Kind, Depth);
5726}
5727
5729 const APInt &DemandedElts,
5730 UndefPoisonKind Kind,
5731 unsigned Depth) const {
5732 unsigned Opcode = Op.getOpcode();
5733 unsigned NumElts = DemandedElts.getBitWidth();
5734
5735 // Early out for FREEZE / constant.
5736 if (Opcode == ISD::FREEZE || isIntOrFPConstant(Op))
5737 return true;
5738
5739 if (Depth >= MaxRecursionDepth)
5740 return false; // Limit search depth.
5741
5742 switch (Opcode) {
5743 case ISD::CONDCODE:
5744 case ISD::VALUETYPE:
5745 case ISD::FrameIndex:
5747 case ISD::CopyFromReg:
5748 return true;
5749
5750 case ISD::POISON:
5751 return !includesPoison(Kind);
5752
5753 case ISD::UNDEF:
5754 return !includesUndef(Kind);
5755
5756 case ISD::BITCAST: {
5757 SDValue Src = Op.getOperand(0);
5758 EVT SrcVT = Src.getValueType();
5759 EVT DstVT = Op.getValueType();
5760
5761 if (!SrcVT.isVector() || !DstVT.isVector())
5762 return isGuaranteedNotToBeUndefOrPoison(Src, Kind, Depth + 1);
5763
5764 unsigned SrcEltBits = SrcVT.getScalarSizeInBits();
5765 unsigned DstEltBits = DstVT.getScalarSizeInBits();
5766 ElementCount NumSrcElts = SrcVT.getVectorElementCount();
5767 [[maybe_unused]] ElementCount NumDstElts = DstVT.getVectorElementCount();
5768
5769 if (SrcEltBits == DstEltBits)
5770 return isGuaranteedNotToBeUndefOrPoison(Src, DemandedElts, Kind,
5771 Depth + 1);
5772
5773 if (SrcEltBits < DstEltBits) {
5774 if (DstEltBits % SrcEltBits != 0)
5775 return isGuaranteedNotToBeUndefOrPoison(Src, Kind, Depth + 1);
5776
5777 assert(NumSrcElts == NumDstElts * (DstEltBits / SrcEltBits) &&
5778 "Unexpected vector bitcast");
5779 APInt DemandedSrcElts =
5780 APIntOps::ScaleBitMask(DemandedElts, NumSrcElts.getKnownMinValue());
5781 return isGuaranteedNotToBeUndefOrPoison(Src, DemandedSrcElts, Kind,
5782 Depth + 1);
5783 }
5784
5785 if (SrcEltBits % DstEltBits != 0)
5786 return isGuaranteedNotToBeUndefOrPoison(Src, Kind, Depth + 1);
5787
5788 assert(NumDstElts == NumSrcElts * (SrcEltBits / DstEltBits) &&
5789 "Unexpected vector bitcast");
5790 APInt DemandedSrcElts =
5791 APIntOps::ScaleBitMask(DemandedElts, NumSrcElts.getKnownMinValue());
5792 return isGuaranteedNotToBeUndefOrPoison(Src, DemandedSrcElts, Kind,
5793 Depth + 1);
5794 }
5795
5796 case ISD::BUILD_VECTOR:
5797 // NOTE: BUILD_VECTOR has implicit truncation of wider scalar elements -
5798 // this shouldn't affect the result.
5799 for (unsigned i = 0, e = Op.getNumOperands(); i < e; ++i) {
5800 if (!DemandedElts[i])
5801 continue;
5802 if (!isGuaranteedNotToBeUndefOrPoison(Op.getOperand(i), Kind, Depth + 1))
5803 return false;
5804 }
5805 return true;
5806
5807 case ISD::CONCAT_VECTORS: {
5808 EVT VT = Op.getValueType();
5809 if (!VT.isFixedLengthVector())
5810 break;
5811
5812 EVT SubVT = Op.getOperand(0).getValueType();
5813 unsigned NumSubElts = SubVT.getVectorNumElements();
5814 for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) {
5815 APInt DemandedSubElts =
5816 DemandedElts.extractBits(NumSubElts, I * NumSubElts);
5817 if (!!DemandedSubElts &&
5818 !isGuaranteedNotToBeUndefOrPoison(Op.getOperand(I), DemandedSubElts,
5819 Kind, Depth + 1))
5820 return false;
5821 }
5822 return true;
5823 }
5824
5826 SDValue Src = Op.getOperand(0);
5827 if (Src.getValueType().isScalableVector())
5828 break;
5829 uint64_t Idx = Op.getConstantOperandVal(1);
5830 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
5831 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
5832 return isGuaranteedNotToBeUndefOrPoison(Src, DemandedSrcElts, Kind,
5833 Depth + 1);
5834 }
5835
5836 case ISD::INSERT_SUBVECTOR: {
5837 if (Op.getValueType().isScalableVector())
5838 break;
5839 SDValue Src = Op.getOperand(0);
5840 SDValue Sub = Op.getOperand(1);
5841 uint64_t Idx = Op.getConstantOperandVal(2);
5842 unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
5843 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
5844 APInt DemandedSrcElts = DemandedElts;
5845 DemandedSrcElts.clearBits(Idx, Idx + NumSubElts);
5846
5847 if (!!DemandedSubElts && !isGuaranteedNotToBeUndefOrPoison(
5848 Sub, DemandedSubElts, Kind, Depth + 1))
5849 return false;
5850 if (!!DemandedSrcElts && !isGuaranteedNotToBeUndefOrPoison(
5851 Src, DemandedSrcElts, Kind, Depth + 1))
5852 return false;
5853 return true;
5854 }
5855
5857 SDValue Src = Op.getOperand(0);
5858 auto *IndexC = dyn_cast<ConstantSDNode>(Op.getOperand(1));
5859 EVT SrcVT = Src.getValueType();
5860 if (SrcVT.isFixedLengthVector() && IndexC &&
5861 IndexC->getAPIntValue().ult(SrcVT.getVectorNumElements())) {
5862 APInt DemandedSrcElts = APInt::getOneBitSet(SrcVT.getVectorNumElements(),
5863 IndexC->getZExtValue());
5864 return isGuaranteedNotToBeUndefOrPoison(Src, DemandedSrcElts, Kind,
5865 Depth + 1);
5866 }
5867 break;
5868 }
5869
5871 SDValue InVec = Op.getOperand(0);
5872 SDValue InVal = Op.getOperand(1);
5873 SDValue EltNo = Op.getOperand(2);
5874 EVT VT = InVec.getValueType();
5875 auto *IndexC = dyn_cast<ConstantSDNode>(EltNo);
5876 if (IndexC && VT.isFixedLengthVector() &&
5877 IndexC->getAPIntValue().ult(VT.getVectorNumElements())) {
5878 if (DemandedElts[IndexC->getZExtValue()] &&
5879 !isGuaranteedNotToBeUndefOrPoison(InVal, Kind, Depth + 1))
5880 return false;
5881 APInt InVecDemandedElts = DemandedElts;
5882 InVecDemandedElts.clearBit(IndexC->getZExtValue());
5883 if (!!InVecDemandedElts &&
5885 peekThroughInsertVectorElt(InVec, InVecDemandedElts),
5886 InVecDemandedElts, Kind, Depth + 1))
5887 return false;
5888 return true;
5889 }
5890 break;
5891 }
5892
5894 // Check upper (known poison) elements.
5895 if (DemandedElts.ugt(1) && includesPoison(Kind))
5896 return false;
5897 // Check element zero.
5898 if (DemandedElts[0] &&
5899 !isGuaranteedNotToBeUndefOrPoison(Op.getOperand(0), Kind, Depth + 1))
5900 return false;
5901 return true;
5902
5903 case ISD::SPLAT_VECTOR:
5904 return isGuaranteedNotToBeUndefOrPoison(Op.getOperand(0), Kind, Depth + 1);
5905
5906 case ISD::SELECT: {
5907 return !canCreateUndefOrPoison(Op, DemandedElts, Kind,
5908 /*ConsiderFlags*/ true, Depth) &&
5909 isGuaranteedNotToBeUndefOrPoison(Op.getOperand(0), Kind,
5910 Depth + 1) &&
5911 isGuaranteedNotToBeUndefOrPoison(Op.getOperand(1), DemandedElts,
5912 Kind, Depth + 1) &&
5913 isGuaranteedNotToBeUndefOrPoison(Op.getOperand(2), DemandedElts,
5914 Kind, Depth + 1);
5915 }
5916
5917 case ISD::VECTOR_SHUFFLE: {
5918 APInt DemandedLHS, DemandedRHS;
5919 auto *SVN = cast<ShuffleVectorSDNode>(Op);
5920 if (!getShuffleDemandedElts(NumElts, SVN->getMask(), DemandedElts,
5921 DemandedLHS, DemandedRHS,
5922 /*AllowUndefElts=*/false))
5923 return false;
5924 if (!DemandedLHS.isZero() &&
5925 !isGuaranteedNotToBeUndefOrPoison(Op.getOperand(0), DemandedLHS, Kind,
5926 Depth + 1))
5927 return false;
5928 if (!DemandedRHS.isZero() &&
5929 !isGuaranteedNotToBeUndefOrPoison(Op.getOperand(1), DemandedRHS, Kind,
5930 Depth + 1))
5931 return false;
5932 return true;
5933 }
5934
5935 case ISD::SHL:
5936 case ISD::SRL:
5937 case ISD::SRA:
5938 // Shift amount operand is checked by canCreateUndefOrPoison. So it is
5939 // enough to check operand 0 if Op can't create undef/poison.
5940 return !canCreateUndefOrPoison(Op, DemandedElts, Kind,
5941 /*ConsiderFlags*/ true, Depth) &&
5942 isGuaranteedNotToBeUndefOrPoison(Op.getOperand(0), DemandedElts,
5943 Kind, Depth + 1);
5944
5945 case ISD::ABS:
5947 case ISD::BSWAP:
5948 case ISD::CTPOP:
5949 case ISD::BITREVERSE:
5950 case ISD::AND:
5951 case ISD::OR:
5952 case ISD::XOR:
5953 case ISD::ADD:
5954 case ISD::SUB:
5955 case ISD::MUL:
5956 case ISD::SADDSAT:
5957 case ISD::UADDSAT:
5958 case ISD::SSUBSAT:
5959 case ISD::USUBSAT:
5960 case ISD::SSHLSAT:
5961 case ISD::USHLSAT:
5962 case ISD::SMIN:
5963 case ISD::SMAX:
5964 case ISD::UMIN:
5965 case ISD::UMAX:
5966 case ISD::ZERO_EXTEND:
5967 case ISD::SIGN_EXTEND:
5968 case ISD::ANY_EXTEND:
5969 case ISD::TRUNCATE:
5970 case ISD::VSELECT: {
5971 // If Op can't create undef/poison and none of its operands are undef/poison
5972 // then Op is never undef/poison. A difference from the more common check
5973 // below, outside the switch, is that we handle elementwise operations for
5974 // which the DemandedElts mask is valid for all operands here.
5975 return !canCreateUndefOrPoison(Op, DemandedElts, Kind,
5976 /*ConsiderFlags*/ true, Depth) &&
5977 all_of(Op->ops(), [&](SDValue V) {
5978 return isGuaranteedNotToBeUndefOrPoison(V, DemandedElts, Kind,
5979 Depth + 1);
5980 });
5981 }
5982
5983 case ISD::LOAD: {
5984 // If we're loading an unindexed constant pool, check if the constant
5985 // contains poison/undef - skip ANYEXT loads.
5986 // TODO: type size mismatch handling.
5987 auto *LD = cast<LoadSDNode>(Op);
5988 if (ISD::isUNINDEXEDLoad(LD) && !ISD::isEXTLoad(LD)) {
5989 if (const Constant *Cst = TLI->getTargetConstantFromLoad(LD)) {
5990 EVT VT = Op.getValueType();
5991 Type *CstTy = Cst->getType();
5992
5993 auto IsSafe = [Kind](const Constant *C) -> bool {
5994 // TODO: expose isGuaranteedNotToBeUndefOrPoison(UndefPoisonKind)
5995 if (includesPoison(Kind) && includesUndef(Kind))
5996 return ::isGuaranteedNotToBeUndefOrPoison(C);
5997 if (includesPoison(Kind))
5998 return ::isGuaranteedNotToBePoison(C);
5999 assert(includesUndef(Kind) && "UndefOnly expected");
6000 return ::isGuaranteedNotToBeUndef(C);
6001 };
6002
6003 // If Cst matches VT vector dimensions, then check per-element.
6004 if (CstTy->isVectorTy() && VT.isFixedLengthVector() &&
6005 VT.getSizeInBits() == CstTy->getPrimitiveSizeInBits() &&
6006 VT.getScalarSizeInBits() == CstTy->getScalarSizeInBits()) {
6007 for (unsigned I = 0; I != NumElts; ++I) {
6008 if (!DemandedElts[I])
6009 continue;
6010 if (Constant *Elt = Cst->getAggregateElement(I)) {
6011 if (IsSafe(Elt))
6012 continue;
6013 }
6014 return false;
6015 }
6016 return true;
6017 }
6018
6019 return IsSafe(Cst);
6020 }
6021 }
6022 break;
6023 }
6024
6025 // TODO: Search for noundef attributes from library functions.
6026
6027 // TODO: Pointers dereferenced by ISD::LOAD/STORE ops are noundef.
6028
6029 default:
6030 // Allow the target to implement this method for its nodes.
6031 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
6032 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID)
6033 return TLI->isGuaranteedNotToBeUndefOrPoisonForTargetNode(
6034 Op, DemandedElts, *this, Kind, Depth);
6035 break;
6036 }
6037
6038 // If Op can't create undef/poison and none of its operands are undef/poison
6039 // then Op is never undef/poison.
6040 // NOTE: TargetNodes can handle this in themselves in
6041 // isGuaranteedNotToBeUndefOrPoisonForTargetNode or let
6042 // TargetLowering::isGuaranteedNotToBeUndefOrPoisonForTargetNode handle it.
6043 return !canCreateUndefOrPoison(Op, Kind, /*ConsiderFlags*/ true, Depth) &&
6044 all_of(Op->ops(), [&](SDValue V) {
6045 return isGuaranteedNotToBeUndefOrPoison(V, Kind, Depth + 1);
6046 });
6047}
6048
6050 bool ConsiderFlags,
6051 unsigned Depth) const {
6052 APInt DemandedElts = getDemandAllEltsMask(Op);
6053 return canCreateUndefOrPoison(Op, DemandedElts, Kind, ConsiderFlags, Depth);
6054}
6055
6057 UndefPoisonKind Kind,
6058 bool ConsiderFlags,
6059 unsigned Depth) const {
6060 if (ConsiderFlags && includesPoison(Kind) && Op->hasPoisonGeneratingFlags())
6061 return true;
6062
6063 unsigned Opcode = Op.getOpcode();
6064 switch (Opcode) {
6065 case ISD::AssertSext:
6066 case ISD::AssertZext:
6067 case ISD::AssertAlign:
6069 // Assertion nodes can create poison if the assertion fails.
6070 return includesPoison(Kind);
6071
6072 case ISD::FREEZE:
6076 case ISD::SADDSAT:
6077 case ISD::UADDSAT:
6078 case ISD::SSUBSAT:
6079 case ISD::USUBSAT:
6080 case ISD::MULHU:
6081 case ISD::MULHS:
6082 case ISD::AVGFLOORS:
6083 case ISD::AVGFLOORU:
6084 case ISD::AVGCEILS:
6085 case ISD::AVGCEILU:
6086 case ISD::AVGSUBFLOORS:
6087 case ISD::AVGSUBFLOORU:
6088 case ISD::ABDU:
6089 case ISD::ABDS:
6090 case ISD::SMIN:
6091 case ISD::SMAX:
6092 case ISD::SCMP:
6093 case ISD::UMIN:
6094 case ISD::UMAX:
6095 case ISD::UCMP:
6096 case ISD::AND:
6097 case ISD::XOR:
6098 case ISD::ROTL:
6099 case ISD::ROTR:
6100 case ISD::FSHL:
6101 case ISD::FSHR:
6102 case ISD::BSWAP:
6103 case ISD::CTTZ:
6104 case ISD::CTLZ:
6105 case ISD::CTLS:
6106 case ISD::CTPOP:
6107 case ISD::BITREVERSE:
6108 case ISD::PARITY:
6109 case ISD::SIGN_EXTEND:
6110 case ISD::TRUNCATE:
6114 case ISD::BITCAST:
6115 case ISD::BUILD_VECTOR:
6116 case ISD::BUILD_PAIR:
6117 case ISD::SPLAT_VECTOR:
6118 case ISD::FABS:
6119 case ISD::FCEIL:
6120 case ISD::FFLOOR:
6121 case ISD::FTRUNC:
6122 case ISD::FRINT:
6123 case ISD::FNEARBYINT:
6124 case ISD::FROUND:
6125 case ISD::FROUNDEVEN:
6126 return false;
6127
6128 case ISD::ABS:
6129 // ISD::ABS defines abs(INT_MIN) -> INT_MIN and never generates poison.
6130 // Different to Intrinsic::abs.
6131 return false;
6133 // ABS_MIN_POISON may produce poison if the input is INT_MIN.
6134 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1) <= 1;
6135
6136 case ISD::ADDC:
6137 case ISD::SUBC:
6138 case ISD::ADDE:
6139 case ISD::SUBE:
6140 case ISD::SADDO:
6141 case ISD::SSUBO:
6142 case ISD::SMULO:
6143 case ISD::SADDO_CARRY:
6144 case ISD::SSUBO_CARRY:
6145 case ISD::UADDO:
6146 case ISD::USUBO:
6147 case ISD::UMULO:
6148 case ISD::UADDO_CARRY:
6149 case ISD::USUBO_CARRY:
6150 // No poison on result or overflow flags.
6151 return false;
6152
6153 case ISD::SELECT_CC:
6154 case ISD::SETCC: {
6155 // Integer setcc cannot create undef or poison.
6156 if (Op.getOperand(0).getValueType().isInteger())
6157 return false;
6158
6159 // FP compares are more complicated. They can create poison for nan/infinity
6160 // based on options and flags. The options and flags also cause special
6161 // nonan condition codes to be used. Those condition codes may be preserved
6162 // even if the nonan flag is dropped somewhere.
6163 unsigned CCOp = Opcode == ISD::SETCC ? 2 : 4;
6164 ISD::CondCode CCCode = Op.getOperandCondCode(CCOp);
6165 return (unsigned)CCCode & 0x10U;
6166 }
6167
6168 case ISD::OR:
6169 case ISD::ZERO_EXTEND:
6170 case ISD::SELECT:
6171 case ISD::VSELECT:
6172 case ISD::ADD:
6173 case ISD::SUB:
6174 case ISD::MUL:
6175 case ISD::FNEG:
6176 case ISD::FADD:
6177 case ISD::FSUB:
6178 case ISD::FMUL:
6179 case ISD::FDIV:
6180 case ISD::FREM:
6181 case ISD::FCOPYSIGN:
6182 case ISD::FMA:
6183 case ISD::FMAD:
6184 case ISD::FMULADD:
6185 case ISD::FP_EXTEND:
6186 case ISD::FMINNUM:
6187 case ISD::FMAXNUM:
6188 case ISD::FMINNUM_IEEE:
6189 case ISD::FMAXNUM_IEEE:
6190 case ISD::FMINIMUM:
6191 case ISD::FMAXIMUM:
6192 case ISD::FMINIMUMNUM:
6193 case ISD::FMAXIMUMNUM:
6199 // No poison except from flags (which is handled above)
6200 return false;
6201
6202 case ISD::SHL:
6203 case ISD::SRL:
6204 case ISD::SRA:
6205 // If the max shift amount isn't in range, then the shift can
6206 // create poison.
6207 return includesPoison(Kind) &&
6208 !getValidMaximumShiftAmount(Op, DemandedElts, Depth + 1);
6209
6212 // If the amount is zero then the result will be poison.
6213 // TODO: Add isKnownNeverZero DemandedElts handling.
6214 return includesPoison(Kind) &&
6215 !isKnownNeverZero(Op.getOperand(0), Depth + 1);
6216
6218 // Check if we demand any upper (poison) elements.
6219 return includesPoison(Kind) && DemandedElts.ugt(1);
6220
6223 // Ensure that the element index is in bounds.
6224 if (includesPoison(Kind)) {
6225 EVT VecVT = Op.getOperand(0).getValueType();
6226 SDValue Idx = Op.getOperand(Opcode == ISD::INSERT_VECTOR_ELT ? 2 : 1);
6227 KnownBits KnownIdx = computeKnownBits(Idx, Depth + 1);
6228 return KnownIdx.getMaxValue().uge(VecVT.getVectorMinNumElements());
6229 }
6230 return false;
6231 }
6232
6233 case ISD::VECTOR_SHUFFLE: {
6234 // Check for any demanded shuffle element that is undef.
6235 auto *SVN = cast<ShuffleVectorSDNode>(Op);
6236 for (auto [Idx, Elt] : enumerate(SVN->getMask()))
6237 if (Elt < 0 && DemandedElts[Idx])
6238 return true;
6239 return false;
6240 }
6241
6243 return false;
6244
6245 case ISD::VECREDUCE_AND:
6246 case ISD::VECREDUCE_OR:
6247 case ISD::VECREDUCE_XOR:
6252 // If the result type is wider than the element type, the top bits are
6253 // undef.
6254 return includesUndef(Kind) &&
6255 Op.getScalarValueSizeInBits() >
6256 Op.getOperand(0).getScalarValueSizeInBits();
6257
6258 default:
6259 // Allow the target to implement this method for its nodes.
6260 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
6261 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID)
6262 return TLI->canCreateUndefOrPoisonForTargetNode(
6263 Op, DemandedElts, *this, Kind, ConsiderFlags, Depth);
6264 break;
6265 }
6266
6267 // Be conservative and return true.
6268 return true;
6269}
6270
6271bool SelectionDAG::isADDLike(SDValue Op, bool NoWrap) const {
6272 unsigned Opcode = Op.getOpcode();
6273 if (Opcode == ISD::OR)
6274 return Op->getFlags().hasDisjoint() ||
6275 haveNoCommonBitsSet(Op.getOperand(0), Op.getOperand(1));
6276 if (Opcode == ISD::XOR)
6277 return !NoWrap && isMinSignedConstant(Op.getOperand(1));
6278 return false;
6279}
6280
6282 return Op.getNumOperands() == 2 && isa<ConstantSDNode>(Op.getOperand(1)) &&
6283 (Op.isAnyAdd() || isADDLike(Op));
6284}
6285
6287 FPClassTest InterestedClasses,
6288 unsigned Depth) const {
6289 APInt DemandedElts = getDemandAllEltsMask(Op);
6290 return computeKnownFPClass(Op, DemandedElts, InterestedClasses, Depth);
6291}
6292
6294 const APInt &DemandedElts,
6295 FPClassTest InterestedClasses,
6296 unsigned Depth) const {
6298
6299 if (const auto *CFP = dyn_cast<ConstantFPSDNode>(Op))
6300 return KnownFPClass(CFP->getValueAPF());
6301
6302 if (Depth >= MaxRecursionDepth)
6303 return Known;
6304
6305 if (Op.getOpcode() == ISD::UNDEF)
6306 return Known;
6307
6308 EVT VT = Op.getValueType();
6309 assert(VT.isFloatingPoint() && "Computing KnownFPClass on non-FP op!");
6310 assert((!VT.isFixedLengthVector() ||
6311 DemandedElts.getBitWidth() == VT.getVectorNumElements()) &&
6312 "Unexpected vector size");
6313
6314 if (!DemandedElts)
6315 return Known;
6316
6317 unsigned Opcode = Op.getOpcode();
6318 switch (Opcode) {
6319 case ISD::POISON: {
6321 break;
6322 }
6323 case ISD::FNEG: {
6324 Known = computeKnownFPClass(Op.getOperand(0), DemandedElts,
6325 InterestedClasses, Depth + 1);
6326 Known.fneg();
6327 break;
6328 }
6329 case ISD::BUILD_VECTOR: {
6330 assert(!VT.isScalableVector());
6331 bool First = true;
6332 for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) {
6333 if (!DemandedElts[I])
6334 continue;
6335
6336 if (First) {
6337 Known =
6338 computeKnownFPClass(Op.getOperand(I), InterestedClasses, Depth + 1);
6339 First = false;
6340 } else {
6341 Known |=
6342 computeKnownFPClass(Op.getOperand(I), InterestedClasses, Depth + 1);
6343 }
6344
6345 if (Known.isUnknown())
6346 break;
6347 }
6348 break;
6349 }
6351 SDValue Src = Op.getOperand(0);
6352 auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6353 EVT SrcVT = Src.getValueType();
6354 if (SrcVT.isFixedLengthVector() && CIdx) {
6355 if (CIdx->getAPIntValue().ult(SrcVT.getVectorNumElements())) {
6356 APInt DemandedSrcElts = APInt::getOneBitSet(
6357 SrcVT.getVectorNumElements(), CIdx->getZExtValue());
6358 Known = computeKnownFPClass(Src, DemandedSrcElts, InterestedClasses,
6359 Depth + 1);
6360 } else {
6361 // Out of bounds index is poison.
6363 }
6364 } else {
6365 Known = computeKnownFPClass(Src, InterestedClasses, Depth + 1);
6366 }
6367 break;
6368 }
6369 case ISD::SPLAT_VECTOR: {
6370 Known = computeKnownFPClass(Op.getOperand(0), InterestedClasses, Depth + 1);
6371 break;
6372 }
6373 case ISD::BITCAST: {
6374 // FIXME: It should not be necessary to check for an elementwise bitcast.
6375 // If a bitcast is not elementwise between vector / scalar types,
6376 // computeKnownBits already splices the known bits of the source elements
6377 // appropriately so as to line up with the bits of the result's demanded
6378 // elements.
6379 EVT SrcVT = Op.getOperand(0).getValueType();
6380 if (VT.isScalableVector() || SrcVT.isScalableVector())
6381 break;
6382 unsigned VTNumElts = VT.isVector() ? VT.getVectorNumElements() : 1;
6383 unsigned SrcVTNumElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1;
6384 if (VTNumElts != SrcVTNumElts)
6385 break;
6386
6387 KnownBits Bits = computeKnownBits(Op, DemandedElts, Depth + 1);
6389 break;
6390 }
6391 case ISD::FABS: {
6392 Known = computeKnownFPClass(Op.getOperand(0), DemandedElts,
6393 InterestedClasses, Depth + 1);
6394 Known.fabs();
6395 break;
6396 }
6397 case ISD::FCOPYSIGN: {
6398 Known = computeKnownFPClass(Op.getOperand(0), DemandedElts,
6399 InterestedClasses, Depth + 1);
6400 KnownFPClass KnownSign = computeKnownFPClass(Op.getOperand(1), DemandedElts,
6401 InterestedClasses, Depth + 1);
6402 Known.copysign(KnownSign);
6403 break;
6404 }
6405 case ISD::AssertNoFPClass: {
6406 Known = computeKnownFPClass(Op.getOperand(0), DemandedElts,
6407 InterestedClasses, Depth + 1);
6408 FPClassTest AssertedClasses =
6409 static_cast<FPClassTest>(Op->getConstantOperandVal(1));
6410 Known.setKnownFPClasses(Known.getKnownFPClasses() & ~AssertedClasses);
6411 break;
6412 }
6414 SDValue Src = Op.getOperand(0);
6415 EVT SrcVT = Src.getValueType();
6416 if (SrcVT.isFixedLengthVector()) {
6417 unsigned Idx = Op.getConstantOperandVal(1);
6418 unsigned NumSrcElts = SrcVT.getVectorNumElements();
6419
6420 APInt DemandedSrcElts = DemandedElts.zextOrTrunc(NumSrcElts).shl(Idx);
6421 Known = computeKnownFPClass(Src, DemandedSrcElts, InterestedClasses,
6422 Depth + 1);
6423 } else {
6424 Known = computeKnownFPClass(Src, InterestedClasses, Depth + 1);
6425 }
6426 break;
6427 }
6428 case ISD::INSERT_SUBVECTOR: {
6429 SDValue BaseVector = Op.getOperand(0);
6430 SDValue SubVector = Op.getOperand(1);
6431 EVT BaseVT = BaseVector.getValueType();
6432 if (BaseVT.isFixedLengthVector()) {
6433 unsigned Idx = Op.getConstantOperandVal(2);
6434 unsigned NumBaseElts = BaseVT.getVectorNumElements();
6435 unsigned NumSubElts = SubVector.getValueType().getVectorNumElements();
6436
6437 APInt DemandedMask =
6438 APInt::getBitsSet(NumBaseElts, Idx, Idx + NumSubElts);
6439 APInt DemandedSrcElts = DemandedElts & ~DemandedMask;
6440 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
6441
6442 if (!DemandedSrcElts.isZero())
6443 Known = computeKnownFPClass(BaseVector, DemandedSrcElts,
6444 InterestedClasses, Depth + 1);
6445 if (!DemandedSubElts.isZero()) {
6447 SubVector, DemandedSubElts, InterestedClasses, Depth + 1);
6448 Known = DemandedSrcElts.isZero() ? SubKnown : (Known | SubKnown);
6449 }
6450 } else {
6451 Known = computeKnownFPClass(SubVector, InterestedClasses, Depth + 1);
6452 if (!Known.isUnknown())
6453 Known |= computeKnownFPClass(BaseVector, InterestedClasses, Depth + 1);
6454 }
6455 break;
6456 }
6457 case ISD::SELECT:
6458 case ISD::VSELECT: {
6459 // TODO: Add adjustKnownFPClassForSelectArm clamp recognition as in
6460 // IR-level ValueTracking.
6461 KnownFPClass KnownFalseClass = computeKnownFPClass(
6462 Op.getOperand(2), DemandedElts, InterestedClasses, Depth + 1);
6463 if (KnownFalseClass.isUnknown())
6464 break;
6465 KnownFPClass KnownTrueClass = computeKnownFPClass(
6466 Op.getOperand(1), DemandedElts, InterestedClasses, Depth + 1);
6467 Known = KnownTrueClass.intersectWith(KnownFalseClass);
6468 break;
6469 }
6470 default:
6471 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
6472 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID) {
6473 TLI->computeKnownFPClassForTargetNode(Op, Known, DemandedElts, *this,
6474 Depth);
6475 }
6476 break;
6477 }
6478
6479 return Known;
6480}
6481
6483 unsigned Depth) const {
6484 APInt DemandedElts = getDemandAllEltsMask(Op);
6485 return isKnownNeverNaN(Op, DemandedElts, SNaN, Depth);
6486}
6487
6489 bool SNaN, unsigned Depth) const {
6490 assert(!DemandedElts.isZero() && "No demanded elements");
6491
6492 // If we're told that NaNs won't happen, assume they won't.
6493 if (Op->getFlags().hasNoNaNs())
6494 return true;
6495
6496 if (Depth >= MaxRecursionDepth)
6497 return false; // Limit search depth.
6498
6499 unsigned Opcode = Op.getOpcode();
6500 switch (Opcode) {
6501 case ISD::FADD:
6502 case ISD::FSUB:
6503 case ISD::FMUL:
6504 case ISD::FDIV:
6505 case ISD::FREM:
6506 case ISD::FSIN:
6507 case ISD::FCOS:
6508 case ISD::FTAN:
6509 case ISD::FASIN:
6510 case ISD::FACOS:
6511 case ISD::FATAN:
6512 case ISD::FATAN2:
6513 case ISD::FSINH:
6514 case ISD::FCOSH:
6515 case ISD::FTANH:
6516 case ISD::FMA:
6517 case ISD::FMULADD:
6518 case ISD::FMAD: {
6519 if (SNaN)
6520 return true;
6521 // TODO: Need isKnownNeverInfinity
6522 return false;
6523 }
6524 case ISD::FCANONICALIZE:
6525 case ISD::FEXP:
6526 case ISD::FEXP2:
6527 case ISD::FEXP10:
6528 case ISD::FTRUNC:
6529 case ISD::FFLOOR:
6530 case ISD::FCEIL:
6531 case ISD::FROUND:
6532 case ISD::FROUNDEVEN:
6533 case ISD::LROUND:
6534 case ISD::LLROUND:
6535 case ISD::FRINT:
6536 case ISD::LRINT:
6537 case ISD::LLRINT:
6538 case ISD::FNEARBYINT:
6539 case ISD::FLDEXP: {
6540 if (SNaN)
6541 return true;
6542 return isKnownNeverNaN(Op.getOperand(0), DemandedElts, SNaN, Depth + 1);
6543 }
6544 case ISD::FABS:
6545 case ISD::FNEG:
6546 case ISD::FCOPYSIGN: {
6547 return isKnownNeverNaN(Op.getOperand(0), DemandedElts, SNaN, Depth + 1);
6548 }
6549 case ISD::SELECT:
6550 return isKnownNeverNaN(Op.getOperand(1), DemandedElts, SNaN, Depth + 1) &&
6551 isKnownNeverNaN(Op.getOperand(2), DemandedElts, SNaN, Depth + 1);
6552 case ISD::FP_EXTEND:
6553 case ISD::FP_ROUND: {
6554 if (SNaN)
6555 return true;
6556 return isKnownNeverNaN(Op.getOperand(0), DemandedElts, SNaN, Depth + 1);
6557 }
6558 case ISD::SINT_TO_FP:
6559 case ISD::UINT_TO_FP:
6560 return true;
6561 case ISD::FSQRT: // Need is known positive
6562 case ISD::FLOG:
6563 case ISD::FLOG2:
6564 case ISD::FLOG10:
6565 case ISD::FPOWI:
6566 case ISD::FPOW: {
6567 if (SNaN)
6568 return true;
6569 // TODO: Refine on operand
6570 return false;
6571 }
6572 case ISD::FMINNUM:
6573 case ISD::FMAXNUM:
6574 case ISD::FMINIMUMNUM:
6575 case ISD::FMAXIMUMNUM: {
6576 // Only one needs to be known not-nan, since it will be returned if the
6577 // other ends up being one.
6578 return isKnownNeverNaN(Op.getOperand(0), DemandedElts, SNaN, Depth + 1) ||
6579 isKnownNeverNaN(Op.getOperand(1), DemandedElts, SNaN, Depth + 1);
6580 }
6581 case ISD::FMINNUM_IEEE:
6582 case ISD::FMAXNUM_IEEE: {
6583 if (SNaN)
6584 return true;
6585 // This can return a NaN if either operand is an sNaN, or if both operands
6586 // are NaN.
6587 return (isKnownNeverNaN(Op.getOperand(0), DemandedElts, false, Depth + 1) &&
6588 isKnownNeverSNaN(Op.getOperand(1), DemandedElts, Depth + 1)) ||
6589 (isKnownNeverNaN(Op.getOperand(1), DemandedElts, false, Depth + 1) &&
6590 isKnownNeverSNaN(Op.getOperand(0), DemandedElts, Depth + 1));
6591 }
6592 case ISD::FMINIMUM:
6593 case ISD::FMAXIMUM: {
6594 // TODO: Does this quiet or return the origina NaN as-is?
6595 return isKnownNeverNaN(Op.getOperand(0), DemandedElts, SNaN, Depth + 1) &&
6596 isKnownNeverNaN(Op.getOperand(1), DemandedElts, SNaN, Depth + 1);
6597 }
6599 SDValue Src = Op.getOperand(0);
6600 auto *Idx = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6601 EVT SrcVT = Src.getValueType();
6602 if (SrcVT.isFixedLengthVector() && Idx &&
6603 Idx->getAPIntValue().ult(SrcVT.getVectorNumElements())) {
6604 APInt DemandedSrcElts = APInt::getOneBitSet(SrcVT.getVectorNumElements(),
6605 Idx->getZExtValue());
6606 return isKnownNeverNaN(Src, DemandedSrcElts, SNaN, Depth + 1);
6607 }
6608 return isKnownNeverNaN(Src, SNaN, Depth + 1);
6609 }
6611 SDValue Src = Op.getOperand(0);
6612 if (Src.getValueType().isFixedLengthVector()) {
6613 unsigned Idx = Op.getConstantOperandVal(1);
6614 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
6615 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
6616 return isKnownNeverNaN(Src, DemandedSrcElts, SNaN, Depth + 1);
6617 }
6618 return isKnownNeverNaN(Src, SNaN, Depth + 1);
6619 }
6620 case ISD::INSERT_SUBVECTOR: {
6621 SDValue BaseVector = Op.getOperand(0);
6622 SDValue SubVector = Op.getOperand(1);
6623 EVT BaseVectorVT = BaseVector.getValueType();
6624 if (BaseVectorVT.isFixedLengthVector()) {
6625 unsigned Idx = Op.getConstantOperandVal(2);
6626 unsigned NumBaseElts = BaseVectorVT.getVectorNumElements();
6627 unsigned NumSubElts = SubVector.getValueType().getVectorNumElements();
6628
6629 // Clear/Extract the bits at the position where the subvector will be
6630 // inserted.
6631 APInt DemandedMask =
6632 APInt::getBitsSet(NumBaseElts, Idx, Idx + NumSubElts);
6633 APInt DemandedSrcElts = DemandedElts & ~DemandedMask;
6634 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
6635
6636 bool NeverNaN = true;
6637 if (!DemandedSrcElts.isZero())
6638 NeverNaN &=
6639 isKnownNeverNaN(BaseVector, DemandedSrcElts, SNaN, Depth + 1);
6640 if (NeverNaN && !DemandedSubElts.isZero())
6641 NeverNaN &=
6642 isKnownNeverNaN(SubVector, DemandedSubElts, SNaN, Depth + 1);
6643 return NeverNaN;
6644 }
6645 return isKnownNeverNaN(BaseVector, SNaN, Depth + 1) &&
6646 isKnownNeverNaN(SubVector, SNaN, Depth + 1);
6647 }
6648 case ISD::BUILD_VECTOR: {
6649 unsigned NumElts = Op.getNumOperands();
6650 for (unsigned I = 0; I != NumElts; ++I)
6651 if (DemandedElts[I] &&
6652 !isKnownNeverNaN(Op.getOperand(I), SNaN, Depth + 1))
6653 return false;
6654 return true;
6655 }
6656 case ISD::SPLAT_VECTOR:
6657 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
6658 case ISD::AssertNoFPClass: {
6659 FPClassTest NoFPClass =
6660 static_cast<FPClassTest>(Op.getConstantOperandVal(1));
6661 if ((NoFPClass & fcNan) == fcNan)
6662 return true;
6663 if (SNaN && (NoFPClass & fcSNan) == fcSNan)
6664 return true;
6665 return isKnownNeverNaN(Op.getOperand(0), DemandedElts, SNaN, Depth + 1);
6666 }
6667 default:
6668 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
6669 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID) {
6670 return TLI->isKnownNeverNaNForTargetNode(Op, DemandedElts, *this, SNaN,
6671 Depth);
6672 }
6673 break;
6674 }
6675
6676 FPClassTest NanMask = SNaN ? fcSNan : fcNan;
6677 KnownFPClass Known = computeKnownFPClass(Op, DemandedElts, NanMask, Depth);
6678 return Known.isKnownNever(NanMask);
6679}
6680
6682 APInt DemandedElts = getDemandAllEltsMask(Op);
6683 return isKnownNeverLogicalZero(Op, DemandedElts, Depth);
6684}
6685
6687 const APInt &DemandedElts,
6688 unsigned Depth) const {
6689 assert(!DemandedElts.isZero() && "No demanded elements");
6690 EVT VT = Op.getValueType();
6692 computeKnownFPClass(Op, DemandedElts, fcZero | fcSubnormal, Depth);
6693 return Known.isKnownNeverLogicalZero(getDenormalMode(VT));
6694}
6695
6697 APInt DemandedElts = getDemandAllEltsMask(Op);
6698 return isKnownNeverZero(Op, DemandedElts, Depth);
6699}
6700
6702 unsigned Depth) const {
6703 if (Depth >= MaxRecursionDepth)
6704 return false; // Limit search depth.
6705
6706 EVT OpVT = Op.getValueType();
6707 unsigned BitWidth = OpVT.getScalarSizeInBits();
6708
6709 assert(!Op.getValueType().isFloatingPoint() &&
6710 "Floating point types unsupported - use isKnownNeverLogicalZero");
6711
6712 // If the value is a constant, we can obviously see if it is a zero or not.
6713 auto IsNeverZero = [BitWidth](const ConstantSDNode *C) {
6714 APInt V = C->getAPIntValue().zextOrTrunc(BitWidth);
6715 return !V.isZero();
6716 };
6717
6718 if (ISD::matchUnaryPredicate(Op, DemandedElts, IsNeverZero,
6719 /*AllowUndefs=*/false, /*AllowTruncation=*/true))
6720 return true;
6721
6722 // TODO: Recognize more cases here. Most of the cases are also incomplete to
6723 // some degree.
6724 switch (Op.getOpcode()) {
6725 default:
6726 break;
6727
6729 SDValue InVec = Op.getOperand(0);
6730 SDValue EltNo = Op.getOperand(1);
6731 EVT VecVT = InVec.getValueType();
6732
6733 // Skip scalable vectors or implicit extensions.
6734 if (VecVT.isScalableVector() ||
6735 OpVT.getScalarSizeInBits() != VecVT.getScalarSizeInBits())
6736 break;
6737
6738 // If we know the element index, just demand that vector element, else for
6739 // an unknown element index, ignore DemandedElts and demand them all.
6740 const unsigned NumSrcElts = VecVT.getVectorNumElements();
6741 APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
6742 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
6743 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
6744 DemandedSrcElts =
6745 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
6746
6747 return isKnownNeverZero(InVec, DemandedSrcElts, Depth + 1);
6748 }
6749
6750 case ISD::OR:
6751 return isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1) ||
6752 isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6753
6754 case ISD::VSELECT:
6755 case ISD::SELECT:
6756 return isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1) &&
6757 isKnownNeverZero(Op.getOperand(2), DemandedElts, Depth + 1);
6758
6759 case ISD::SHL: {
6760 if (Op->getFlags().hasNoSignedWrap() || Op->getFlags().hasNoUnsignedWrap())
6761 return isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6762 KnownBits ValKnown =
6763 computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
6764 // 1 << X is never zero.
6765 if (ValKnown.One[0])
6766 return true;
6767 // If max shift cnt of known ones is non-zero, result is non-zero.
6768 APInt MaxCnt = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1)
6769 .getMaxValue();
6770 if (MaxCnt.ult(ValKnown.getBitWidth()) &&
6771 !ValKnown.One.shl(MaxCnt).isZero())
6772 return true;
6773 break;
6774 }
6775
6776 case ISD::VECTOR_SHUFFLE: {
6777 if (Op.getValueType().isScalableVector())
6778 return false;
6779
6780 unsigned NumElts = DemandedElts.getBitWidth();
6781
6782 // All demanded elements from LHS and RHS must be known non-zero.
6783 // Demanded elements with undef shuffle mask elements are unknown.
6784
6785 APInt DemandedLHS, DemandedRHS;
6786 auto *SVN = cast<ShuffleVectorSDNode>(Op);
6787 assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
6788 if (!getShuffleDemandedElts(NumElts, SVN->getMask(), DemandedElts,
6789 DemandedLHS, DemandedRHS))
6790 return false;
6791
6792 return (!DemandedLHS ||
6793 isKnownNeverZero(Op.getOperand(0), DemandedLHS, Depth + 1)) &&
6794 (!DemandedRHS ||
6795 isKnownNeverZero(Op.getOperand(1), DemandedRHS, Depth + 1));
6796 }
6797
6798 case ISD::UADDSAT:
6799 case ISD::UMAX:
6800 return isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1) ||
6801 isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6802
6803 case ISD::UMIN:
6804 return isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1) &&
6805 isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6806
6807 // For smin/smax: If either operand is known negative/positive
6808 // respectively we don't need the other to be known at all.
6809 case ISD::SMAX: {
6810 KnownBits Op1 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
6811 if (Op1.isStrictlyPositive())
6812 return true;
6813
6814 KnownBits Op0 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
6815 if (Op0.isStrictlyPositive())
6816 return true;
6817
6818 if (Op1.isNonZero() && Op0.isNonZero())
6819 return true;
6820
6821 return isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1) &&
6822 isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6823 }
6824 case ISD::SMIN: {
6825 KnownBits Op1 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
6826 if (Op1.isNegative())
6827 return true;
6828
6829 KnownBits Op0 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
6830 if (Op0.isNegative())
6831 return true;
6832
6833 if (Op1.isNonZero() && Op0.isNonZero())
6834 return true;
6835
6836 return isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1) &&
6837 isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6838 }
6839
6840 case ISD::ROTL:
6841 case ISD::ROTR:
6842 case ISD::BITREVERSE:
6843 case ISD::BSWAP:
6844 case ISD::CTPOP:
6845 case ISD::ABS:
6847 return isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6848
6849 case ISD::SRA:
6850 case ISD::SRL: {
6851 if (Op->getFlags().hasExact())
6852 return isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6853 KnownBits ValKnown =
6854 computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
6855 if (ValKnown.isNegative())
6856 return true;
6857 // If max shift cnt of known ones is non-zero, result is non-zero.
6858 APInt MaxCnt = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1)
6859 .getMaxValue();
6860 if (MaxCnt.ult(ValKnown.getBitWidth()) &&
6861 !ValKnown.One.lshr(MaxCnt).isZero())
6862 return true;
6863 break;
6864 }
6865 case ISD::UDIV:
6866 case ISD::SDIV:
6867 // div exact can only produce a zero if the dividend is zero.
6868 // TODO: For udiv this is also true if Op1 u<= Op0
6869 if (Op->getFlags().hasExact())
6870 return isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6871 break;
6872
6873 case ISD::ADD:
6874 if (Op->getFlags().hasNoUnsignedWrap())
6875 if (isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1) ||
6876 isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1))
6877 return true;
6878 // TODO: There are a lot more cases we can prove for add.
6879 break;
6880
6881 case ISD::SUB: {
6882 if (isNullConstant(Op.getOperand(0)))
6883 return isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1);
6884
6885 std::optional<bool> ne = KnownBits::ne(
6886 computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1),
6887 computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1));
6888 return ne && *ne;
6889 }
6890
6891 case ISD::MUL:
6892 if (Op->getFlags().hasNoSignedWrap() || Op->getFlags().hasNoUnsignedWrap())
6893 if (isKnownNeverZero(Op.getOperand(1), Depth + 1) &&
6894 isKnownNeverZero(Op.getOperand(0), Depth + 1))
6895 return true;
6896 break;
6897
6898 case ISD::ZERO_EXTEND:
6899 case ISD::SIGN_EXTEND:
6900 return isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6901 case ISD::VSCALE: {
6903 const APInt &Multiplier = Op.getConstantOperandAPInt(0);
6904 ConstantRange CR =
6905 getVScaleRange(&F, Op.getScalarValueSizeInBits()).multiply(Multiplier);
6906 if (!CR.contains(APInt(CR.getBitWidth(), 0)))
6907 return true;
6908 break;
6909 }
6910 }
6911
6912 return computeKnownBits(Op, DemandedElts, Depth).isNonZero();
6913}
6914
6917 return !C1->isNegative();
6918
6919 switch (Op.getOpcode()) {
6920 case ISD::FABS:
6921 case ISD::FEXP:
6922 case ISD::FEXP2:
6923 case ISD::FEXP10:
6924 return true;
6925 default:
6926 return false;
6927 }
6928
6929 llvm_unreachable("covered opcode switch");
6930}
6931
6932/// Return true if the standard nsz semantics may not apply for this opcode.
6933/// Opcode is assumed to take float inputs.
6934/// FIXME: Target min/max nodes (e.g. X86ISD::FMINC) aren't included.
6935static bool hasSpecialNszSemantics(unsigned Opcode) {
6936 switch (Opcode) {
6937 case ISD::FMINNUM:
6938 case ISD::FMAXNUM:
6939 case ISD::FMINNUM_IEEE:
6940 case ISD::FMAXNUM_IEEE:
6941 case ISD::FMINIMUM:
6942 case ISD::FMAXIMUM:
6943 case ISD::FMINIMUMNUM:
6944 case ISD::FMAXIMUMNUM:
6949 case ISD::PSEUDO_FMIN:
6950 case ISD::PSEUDO_FMAX:
6959 case ISD::VP_REDUCE_FMIN:
6960 case ISD::VP_REDUCE_FMAX:
6961 case ISD::VP_REDUCE_FMINIMUM:
6962 case ISD::VP_REDUCE_FMAXIMUM:
6963 return true;
6964 default:
6965 return false;
6966 }
6967}
6968
6970 assert(Use.getValueType().isFloatingPoint());
6971 const SDNode *User = Use.getUser();
6972 unsigned Opcode = User->getOpcode();
6973 if (User->getFlags().hasNoSignedZeros() && !hasSpecialNszSemantics(Opcode))
6974 return true;
6975
6976 unsigned OperandNo = Use.getOperandNo();
6977 // Check if this use is insensitive to the sign of zero
6978 switch (Opcode) {
6979 case ISD::SETCC:
6980 // Comparisons: IEEE-754 specifies +0.0 == -0.0.
6981 case ISD::FABS:
6982 // fabs always produces +0.0.
6983 return true;
6984 case ISD::FCOPYSIGN:
6985 // copysign overwrites the sign bit of the first operand.
6986 return OperandNo == 0;
6987 case ISD::FADD:
6988 case ISD::FSUB: {
6989 // Arithmetic with non-zero constants fixes the uncertainty around the
6990 // sign bit.
6991 SDValue Other = User->getOperand(1 - OperandNo);
6993 }
6994 case ISD::FP_TO_SINT:
6995 case ISD::FP_TO_UINT:
6996 // fp-to-int conversions normalize signed zeros.
6997 return true;
6998 case ISD::FMINNUM:
6999 case ISD::FMINNUM_IEEE:
7000 case ISD::FMINIMUM:
7001 case ISD::FMINIMUMNUM:
7002 case ISD::FMAXNUM:
7003 case ISD::FMAXNUM_IEEE:
7004 case ISD::FMAXIMUM:
7005 case ISD::FMAXIMUMNUM:
7006 case ISD::PSEUDO_FMIN:
7007 case ISD::PSEUDO_FMAX: {
7008 // If other value always beats zero, the zero can be ignored.
7009 bool IsMin = Opcode == ISD::FMINNUM || Opcode == ISD::FMINNUM_IEEE ||
7010 Opcode == ISD::FMINIMUM || Opcode == ISD::FMINIMUMNUM ||
7011 Opcode == ISD::PSEUDO_FMIN;
7012 FPClassTest AlwaysBeatsZero =
7014 SDValue Other = User->getOperand(1 - OperandNo);
7015 KnownFPClass Known = computeKnownFPClass(Other, ~AlwaysBeatsZero);
7016 return Known.isKnownNever(~AlwaysBeatsZero);
7017 }
7018 default:
7019 return false;
7020 }
7021}
7022
7024 assert(Op->getNumValues() == 1);
7025 // FIXME: Limit the amount of checked uses to not introduce a compile-time
7026 // regression. Ideally, this should be implemented as a demanded-bits
7027 // optimization that stems from the users.
7028 if (Op->use_size() > 2)
7029 return false;
7030 return all_of(Op->uses(),
7031 [&](const SDUse &Use) { return canIgnoreSignBitOfZero(Use); });
7032}
7033
7035 // Check the obvious case.
7036 if (A == B) return true;
7037
7038 // For negative and positive zero.
7041 if (CA->isZero() && CB->isZero()) return true;
7042
7043 // Otherwise they may not be equal.
7044 return false;
7045}
7046
7047// Only bits set in Mask must be negated, other bits may be arbitrary.
7049 if (isBitwiseNot(V, AllowUndefs))
7050 return V.getOperand(0);
7051
7052 // Handle any_extend (not (truncate X)) pattern, where Mask only sets
7053 // bits in the non-extended part.
7054 ConstantSDNode *MaskC = isConstOrConstSplat(Mask);
7055 if (!MaskC || V.getOpcode() != ISD::ANY_EXTEND)
7056 return SDValue();
7057 SDValue ExtArg = V.getOperand(0);
7058 if (ExtArg.getScalarValueSizeInBits() >=
7059 MaskC->getAPIntValue().getActiveBits() &&
7060 isBitwiseNot(ExtArg, AllowUndefs) &&
7061 ExtArg.getOperand(0).getOpcode() == ISD::TRUNCATE &&
7062 ExtArg.getOperand(0).getOperand(0).getValueType() == V.getValueType())
7063 return ExtArg.getOperand(0).getOperand(0);
7064 return SDValue();
7065}
7066
7068 // Match masked merge pattern (X & ~M) op (Y & M)
7069 // Including degenerate case (X & ~M) op M
7070 auto MatchNoCommonBitsPattern = [&](SDValue Not, SDValue Mask,
7071 SDValue Other) {
7072 if (SDValue NotOperand =
7073 getBitwiseNotOperand(Not, Mask, /* AllowUndefs */ true)) {
7074 if (NotOperand->getOpcode() == ISD::ZERO_EXTEND ||
7075 NotOperand->getOpcode() == ISD::TRUNCATE)
7076 NotOperand = NotOperand->getOperand(0);
7077
7078 if (Other == NotOperand)
7079 return true;
7080 if (Other->getOpcode() == ISD::AND)
7081 return NotOperand == Other->getOperand(0) ||
7082 NotOperand == Other->getOperand(1);
7083 }
7084 return false;
7085 };
7086
7087 if (A->getOpcode() == ISD::ZERO_EXTEND || A->getOpcode() == ISD::TRUNCATE)
7088 A = A->getOperand(0);
7089
7090 if (B->getOpcode() == ISD::ZERO_EXTEND || B->getOpcode() == ISD::TRUNCATE)
7091 B = B->getOperand(0);
7092
7093 if (A->getOpcode() == ISD::AND)
7094 return MatchNoCommonBitsPattern(A->getOperand(0), A->getOperand(1), B) ||
7095 MatchNoCommonBitsPattern(A->getOperand(1), A->getOperand(0), B);
7096 return false;
7097}
7098
7099// FIXME: unify with llvm::haveNoCommonBitsSet.
7101 assert(A.getValueType() == B.getValueType() &&
7102 "Values must have the same type");
7105 return true;
7108}
7109
7110static SDValue FoldSTEP_VECTOR(const SDLoc &DL, EVT VT, SDValue Step,
7111 SelectionDAG &DAG) {
7112 if (cast<ConstantSDNode>(Step)->isZero())
7113 return DAG.getConstant(0, DL, VT);
7114
7115 return SDValue();
7116}
7117
7120 SelectionDAG &DAG) {
7121 int NumOps = Ops.size();
7122 assert(NumOps != 0 && "Can't build an empty vector!");
7123 assert(!VT.isScalableVector() &&
7124 "BUILD_VECTOR cannot be used with scalable types");
7125 assert(VT.getVectorNumElements() == (unsigned)NumOps &&
7126 "Incorrect element count in BUILD_VECTOR!");
7127
7128 // BUILD_VECTOR of UNDEFs is UNDEF.
7129 bool AllPoison = true;
7130 if (llvm::all_of(Ops, [&AllPoison](SDValue Op) {
7131 AllPoison &= Op.getOpcode() == ISD::POISON;
7132 return Op.isUndef();
7133 }))
7134 return AllPoison ? DAG.getPOISON(VT) : DAG.getUNDEF(VT);
7135
7136 // BUILD_VECTOR of seq extract/insert from the same vector + type is Identity.
7137 SDValue IdentitySrc;
7138 bool IsIdentity = true;
7139 for (int i = 0; i != NumOps; ++i) {
7140 if (Ops[i].getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
7141 Ops[i].getOperand(0).getValueType() != VT ||
7142 (IdentitySrc && Ops[i].getOperand(0) != IdentitySrc) ||
7143 !isa<ConstantSDNode>(Ops[i].getOperand(1)) ||
7144 Ops[i].getConstantOperandAPInt(1) != i) {
7145 IsIdentity = false;
7146 break;
7147 }
7148 IdentitySrc = Ops[i].getOperand(0);
7149 }
7150 if (IsIdentity)
7151 return IdentitySrc;
7152
7153 return SDValue();
7154}
7155
7156/// Try to simplify vector concatenation to an input value, undef, or build
7157/// vector.
7160 SelectionDAG &DAG) {
7161 assert(!Ops.empty() && "Can't concatenate an empty list of vectors!");
7163 [Ops](SDValue Op) {
7164 return Ops[0].getValueType() == Op.getValueType();
7165 }) &&
7166 "Concatenation of vectors with inconsistent value types!");
7167 assert((Ops[0].getValueType().getVectorElementCount() * Ops.size()) ==
7168 VT.getVectorElementCount() &&
7169 "Incorrect element count in vector concatenation!");
7170
7171 if (Ops.size() == 1)
7172 return Ops[0];
7173
7174 // Concat of UNDEFs is UNDEF.
7175 bool AllPoison = true;
7176 if (llvm::all_of(Ops, [&AllPoison](SDValue Op) {
7177 AllPoison &= Op.getOpcode() == ISD::POISON;
7178 return Op.isUndef();
7179 }))
7180 return AllPoison ? DAG.getPOISON(VT) : DAG.getUNDEF(VT);
7181
7182 // Scan the operands and look for extract operations from a single source
7183 // that correspond to insertion at the same location via this concatenation:
7184 // concat (extract X, 0*subvec_elts), (extract X, 1*subvec_elts), ...
7185 SDValue IdentitySrc;
7186 bool IsIdentity = true;
7187 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
7188 SDValue Op = Ops[i];
7189 unsigned IdentityIndex = i * Op.getValueType().getVectorMinNumElements();
7190 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
7191 Op.getOperand(0).getValueType() != VT ||
7192 (IdentitySrc && Op.getOperand(0) != IdentitySrc) ||
7193 Op.getConstantOperandVal(1) != IdentityIndex) {
7194 IsIdentity = false;
7195 break;
7196 }
7197 assert((!IdentitySrc || IdentitySrc == Op.getOperand(0)) &&
7198 "Unexpected identity source vector for concat of extracts");
7199 IdentitySrc = Op.getOperand(0);
7200 }
7201 if (IsIdentity) {
7202 assert(IdentitySrc && "Failed to set source vector of extracts");
7203 return IdentitySrc;
7204 }
7205
7206 // The code below this point is only designed to work for fixed width
7207 // vectors, so we bail out for now.
7208 if (VT.isScalableVector())
7209 return SDValue();
7210
7211 // A CONCAT_VECTOR of scalar sources, such as UNDEF, BUILD_VECTOR and
7212 // single-element INSERT_VECTOR_ELT operands can be simplified to one big
7213 // BUILD_VECTOR.
7214 // FIXME: Add support for SCALAR_TO_VECTOR as well.
7215 EVT SVT = VT.getScalarType();
7217 for (SDValue Op : Ops) {
7218 EVT OpVT = Op.getValueType();
7219 if (Op.getOpcode() == ISD::POISON)
7220 Elts.append(OpVT.getVectorNumElements(), DAG.getPOISON(SVT));
7221 else if (Op.getOpcode() == ISD::UNDEF)
7222 Elts.append(OpVT.getVectorNumElements(), DAG.getUNDEF(SVT));
7223 else if (Op.getOpcode() == ISD::BUILD_VECTOR)
7224 Elts.append(Op->op_begin(), Op->op_end());
7225 else if (Op.getOpcode() == ISD::INSERT_VECTOR_ELT &&
7226 OpVT.getVectorNumElements() == 1 &&
7227 isNullConstant(Op.getOperand(2)))
7228 Elts.push_back(Op.getOperand(1));
7229 else
7230 return SDValue();
7231 }
7232
7233 // BUILD_VECTOR requires all inputs to be of the same type, find the
7234 // maximum type and extend them all.
7235 for (SDValue Op : Elts)
7236 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
7237
7238 if (SVT.bitsGT(VT.getScalarType())) {
7239 for (SDValue &Op : Elts) {
7240 if (Op.getOpcode() == ISD::POISON)
7241 Op = DAG.getPOISON(SVT);
7242 else if (Op.getOpcode() == ISD::UNDEF)
7243 Op = DAG.getUNDEF(SVT);
7244 else
7245 Op = DAG.getTargetLoweringInfo().isZExtFree(Op.getValueType(), SVT)
7246 ? DAG.getZExtOrTrunc(Op, DL, SVT)
7247 : DAG.getSExtOrTrunc(Op, DL, SVT);
7248 }
7249 }
7250
7251 SDValue V = DAG.getBuildVector(VT, DL, Elts);
7252 NewSDValueDbgMsg(V, "New node fold concat vectors: ", &DAG);
7253 return V;
7254}
7255
7256/// Gets or creates the specified node.
7257SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT) {
7258 SDVTList VTs = getVTList(VT);
7259 SDNodeKey ID(Opcode, VTs, {});
7260 FoldingSetInsertToken InsertToken;
7261 if (SDNode *E = lookupNode(ID, DL, InsertToken))
7262 return SDValue(E, 0);
7263
7264 auto *N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
7265 CSEMap.insert(N, InsertToken);
7266
7267 InsertNode(N);
7268 SDValue V = SDValue(N, 0);
7269 NewSDValueDbgMsg(V, "Creating new node: ", this);
7270 return V;
7271}
7272
7273SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
7274 SDValue N1) {
7275 SDNodeFlags Flags;
7276 if (Inserter)
7277 Flags = Inserter->getFlags();
7278 return getNode(Opcode, DL, VT, N1, Flags);
7279}
7280
7281SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
7282 SDValue N1, const SDNodeFlags Flags) {
7283 assert(N1.getOpcode() != ISD::DELETED_NODE && "Operand is DELETED_NODE!");
7284
7285 // Constant fold unary operations with a vector integer or float operand.
7286 switch (Opcode) {
7287 default:
7288 // FIXME: Entirely reasonable to perform folding of other unary
7289 // operations here as the need arises.
7290 break;
7291 case ISD::FNEG:
7292 case ISD::FABS:
7293 case ISD::FCEIL:
7294 case ISD::FTRUNC:
7295 case ISD::FFLOOR:
7296 case ISD::FP_EXTEND:
7297 case ISD::FP_TO_SINT:
7298 case ISD::FP_TO_UINT:
7299 case ISD::FP_TO_FP16:
7300 case ISD::FP_TO_BF16:
7301 case ISD::TRUNCATE:
7302 case ISD::ANY_EXTEND:
7303 case ISD::ZERO_EXTEND:
7304 case ISD::SIGN_EXTEND:
7305 case ISD::UINT_TO_FP:
7306 case ISD::SINT_TO_FP:
7307 case ISD::FP16_TO_FP:
7308 case ISD::BF16_TO_FP:
7309 case ISD::BITCAST:
7310 case ISD::ABS:
7312 case ISD::BITREVERSE:
7313 case ISD::BSWAP:
7314 case ISD::CTLZ:
7316 case ISD::CTTZ:
7318 case ISD::CTPOP:
7319 case ISD::PARITY:
7320 case ISD::CTLS:
7321 case ISD::VECREDUCE_ADD:
7326 case ISD::VECREDUCE_MUL:
7327 case ISD::VECREDUCE_AND:
7328 case ISD::VECREDUCE_OR:
7329 case ISD::VECREDUCE_XOR:
7330 case ISD::STEP_VECTOR: {
7331 SDValue Ops = {N1};
7332 if (SDValue Fold = FoldConstantArithmetic(Opcode, DL, VT, Ops, Flags))
7333 return Fold;
7334 }
7335 }
7336
7337 unsigned OpOpcode = N1.getNode()->getOpcode();
7338 switch (Opcode) {
7339 case ISD::STEP_VECTOR:
7340 assert(VT.isScalableVector() &&
7341 "STEP_VECTOR can only be used with scalable types");
7342 assert(OpOpcode == ISD::TargetConstant &&
7343 VT.getVectorElementType() == N1.getValueType() &&
7344 "Unexpected step operand");
7345 break;
7346 case ISD::FREEZE:
7347 assert(VT == N1.getValueType() && "Unexpected VT!");
7349 return N1;
7350 break;
7351 case ISD::TokenFactor:
7352 case ISD::MERGE_VALUES:
7354 return N1; // Factor, merge or concat of one node? No need.
7355 case ISD::BUILD_VECTOR: {
7356 // Attempt to simplify BUILD_VECTOR.
7357 SDValue Ops[] = {N1};
7358 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
7359 return V;
7360 break;
7361 }
7362 case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node");
7363 case ISD::FP_EXTEND:
7365 "Invalid FP cast!");
7366 if (N1.getValueType() == VT) return N1; // noop conversion.
7367 assert((!VT.isVector() || VT.getVectorElementCount() ==
7369 "Vector element count mismatch!");
7370 assert(N1.getValueType().bitsLT(VT) && "Invalid fpext node, dst < src!");
7371 if (N1.isUndef())
7372 return getUNDEF(VT);
7373 break;
7374 case ISD::FP_TO_SINT:
7375 case ISD::FP_TO_UINT:
7376 if (N1.isUndef())
7377 return getUNDEF(VT);
7378 break;
7379 case ISD::SINT_TO_FP:
7380 case ISD::UINT_TO_FP:
7381 // [us]itofp(undef) = 0, because the result value is bounded.
7382 if (N1.isUndef())
7383 return getConstantFP(0.0, DL, VT);
7384 break;
7385 case ISD::SIGN_EXTEND:
7386 assert(VT.isInteger() && N1.getValueType().isInteger() &&
7387 "Invalid SIGN_EXTEND!");
7388 assert(VT.isVector() == N1.getValueType().isVector() &&
7389 "SIGN_EXTEND result type type should be vector iff the operand "
7390 "type is vector!");
7391 if (N1.getValueType() == VT) return N1; // noop extension
7392 assert((!VT.isVector() || VT.getVectorElementCount() ==
7394 "Vector element count mismatch!");
7395 assert(N1.getValueType().bitsLT(VT) && "Invalid sext node, dst < src!");
7396 if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND) {
7397 SDNodeFlags Flags;
7398 if (OpOpcode == ISD::ZERO_EXTEND)
7399 Flags.setNonNeg(N1->getFlags().hasNonNeg());
7400 SDValue NewVal = getNode(OpOpcode, DL, VT, N1.getOperand(0), Flags);
7401 transferDbgValues(N1, NewVal);
7402 return NewVal;
7403 }
7404
7405 if (OpOpcode == ISD::POISON)
7406 return getPOISON(VT);
7407
7408 if (N1.isUndef())
7409 // sext(undef) = 0, because the top bits will all be the same.
7410 return getConstant(0, DL, VT);
7411
7412 // Skip unnecessary sext_inreg pattern:
7413 // (sext (trunc x)) -> x iff the upper bits are all signbits.
7414 if (OpOpcode == ISD::TRUNCATE) {
7415 SDValue OpOp = N1.getOperand(0);
7416 if (OpOp.getValueType() == VT) {
7417 unsigned NumSignExtBits =
7419 if (ComputeNumSignBits(OpOp) > NumSignExtBits) {
7420 transferDbgValues(N1, OpOp);
7421 return OpOp;
7422 }
7423 }
7424 }
7425 break;
7426 case ISD::ZERO_EXTEND:
7427 assert(VT.isInteger() && N1.getValueType().isInteger() &&
7428 "Invalid ZERO_EXTEND!");
7429 assert(VT.isVector() == N1.getValueType().isVector() &&
7430 "ZERO_EXTEND result type type should be vector iff the operand "
7431 "type is vector!");
7432 if (N1.getValueType() == VT) return N1; // noop extension
7433 assert((!VT.isVector() || VT.getVectorElementCount() ==
7435 "Vector element count mismatch!");
7436 assert(N1.getValueType().bitsLT(VT) && "Invalid zext node, dst < src!");
7437 if (OpOpcode == ISD::ZERO_EXTEND) { // (zext (zext x)) -> (zext x)
7438 SDNodeFlags Flags;
7439 Flags.setNonNeg(N1->getFlags().hasNonNeg());
7440 SDValue NewVal =
7441 getNode(ISD::ZERO_EXTEND, DL, VT, N1.getOperand(0), Flags);
7442 transferDbgValues(N1, NewVal);
7443 return NewVal;
7444 }
7445
7446 if (OpOpcode == ISD::POISON)
7447 return getPOISON(VT);
7448
7449 if (N1.isUndef())
7450 // zext(undef) = 0, because the top bits will be zero.
7451 return getConstant(0, DL, VT);
7452
7453 // Skip unnecessary zext_inreg pattern:
7454 // (zext (trunc x)) -> x iff the upper bits are known zero.
7455 // TODO: Remove (zext (trunc (and x, c))) exception which some targets
7456 // use to recognise zext_inreg patterns.
7457 if (OpOpcode == ISD::TRUNCATE) {
7458 SDValue OpOp = N1.getOperand(0);
7459 if (OpOp.getValueType() == VT) {
7460 if (OpOp.getOpcode() != ISD::AND) {
7463 if (MaskedValueIsZero(OpOp, HiBits)) {
7464 transferDbgValues(N1, OpOp);
7465 return OpOp;
7466 }
7467 }
7468 }
7469 }
7470 break;
7471 case ISD::ANY_EXTEND:
7472 assert(VT.isInteger() && N1.getValueType().isInteger() &&
7473 "Invalid ANY_EXTEND!");
7474 assert(VT.isVector() == N1.getValueType().isVector() &&
7475 "ANY_EXTEND result type type should be vector iff the operand "
7476 "type is vector!");
7477 if (N1.getValueType() == VT) return N1; // noop extension
7478 assert((!VT.isVector() || VT.getVectorElementCount() ==
7480 "Vector element count mismatch!");
7481 assert(N1.getValueType().bitsLT(VT) && "Invalid anyext node, dst < src!");
7482
7483 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
7484 OpOpcode == ISD::ANY_EXTEND) {
7485 SDNodeFlags Flags;
7486 if (OpOpcode == ISD::ZERO_EXTEND)
7487 Flags.setNonNeg(N1->getFlags().hasNonNeg());
7488 // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x)
7489 return getNode(OpOpcode, DL, VT, N1.getOperand(0), Flags);
7490 }
7491 if (N1.isUndef())
7492 return getUNDEF(VT);
7493
7494 // (ext (trunc x)) -> x
7495 if (OpOpcode == ISD::TRUNCATE) {
7496 SDValue OpOp = N1.getOperand(0);
7497 if (OpOp.getValueType() == VT) {
7498 transferDbgValues(N1, OpOp);
7499 return OpOp;
7500 }
7501 }
7502 break;
7503 case ISD::TRUNCATE:
7504 assert(VT.isInteger() && N1.getValueType().isInteger() &&
7505 "Invalid TRUNCATE!");
7506 assert(VT.isVector() == N1.getValueType().isVector() &&
7507 "TRUNCATE result type type should be vector iff the operand "
7508 "type is vector!");
7509 if (N1.getValueType() == VT) return N1; // noop truncate
7510 assert((!VT.isVector() || VT.getVectorElementCount() ==
7512 "Vector element count mismatch!");
7513 assert(N1.getValueType().bitsGT(VT) && "Invalid truncate node, src < dst!");
7514 if (OpOpcode == ISD::TRUNCATE)
7515 return getNode(ISD::TRUNCATE, DL, VT, N1.getOperand(0));
7516 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
7517 OpOpcode == ISD::ANY_EXTEND) {
7518 // If the source is smaller than the dest, we still need an extend.
7520 VT.getScalarType())) {
7521 SDNodeFlags Flags;
7522 if (OpOpcode == ISD::ZERO_EXTEND)
7523 Flags.setNonNeg(N1->getFlags().hasNonNeg());
7524 return getNode(OpOpcode, DL, VT, N1.getOperand(0), Flags);
7525 }
7526 if (N1.getOperand(0).getValueType().bitsGT(VT))
7527 return getNode(ISD::TRUNCATE, DL, VT, N1.getOperand(0));
7528 return N1.getOperand(0);
7529 }
7530 if (N1.isUndef())
7531 return getUNDEF(VT);
7532 if (OpOpcode == ISD::VSCALE && !NewNodesMustHaveLegalTypes)
7533 return getVScale(DL, VT,
7535 break;
7539 assert(VT.isVector() && "This DAG node is restricted to vector types.");
7540 assert(N1.getValueType().bitsLE(VT) &&
7541 "The input must be the same size or smaller than the result.");
7544 "The destination vector type must have fewer lanes than the input.");
7545 break;
7546 case ISD::ABS:
7547 assert(VT.isInteger() && VT == N1.getValueType() && "Invalid ABS!");
7548 if (N1.isUndef())
7549 return getConstant(0, DL, VT);
7550 break;
7552 assert(VT.isInteger() && VT == N1.getValueType() &&
7553 "Invalid ABS_MIN_POISON!");
7554 if (N1.isUndef())
7555 return getConstant(0, DL, VT);
7556 break;
7557 case ISD::BSWAP:
7558 assert(VT.isInteger() && VT == N1.getValueType() && "Invalid BSWAP!");
7559 assert((VT.getScalarSizeInBits() % 16 == 0) &&
7560 "BSWAP types must be a multiple of 16 bits!");
7561 if (N1.isUndef())
7562 return getUNDEF(VT);
7563 // bswap(bswap(X)) -> X.
7564 if (OpOpcode == ISD::BSWAP)
7565 return N1.getOperand(0);
7566 break;
7567 case ISD::BITREVERSE:
7568 assert(VT.isInteger() && VT == N1.getValueType() && "Invalid BITREVERSE!");
7569 if (N1.isUndef())
7570 return getUNDEF(VT);
7571 break;
7572 case ISD::BITCAST:
7574 "Cannot BITCAST between types of different sizes!");
7575 if (VT == N1.getValueType()) return N1; // noop conversion.
7576 if (OpOpcode == ISD::BITCAST) // bitconv(bitconv(x)) -> bitconv(x)
7577 return getNode(ISD::BITCAST, DL, VT, N1.getOperand(0));
7578 if (N1.isUndef())
7579 return getUNDEF(VT);
7580 break;
7582 assert(VT.isVector() && !N1.getValueType().isVector() &&
7583 (VT.getVectorElementType() == N1.getValueType() ||
7585 N1.getValueType().isInteger() &&
7587 "Illegal SCALAR_TO_VECTOR node!");
7588 if (N1.isUndef())
7589 return getUNDEF(VT);
7590 // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
7591 if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
7593 N1.getConstantOperandVal(1) == 0 &&
7594 N1.getOperand(0).getValueType() == VT)
7595 return N1.getOperand(0);
7596 break;
7597 case ISD::FNEG:
7598 // Negation of an unknown bag of bits is still completely undefined.
7599 if (N1.isUndef())
7600 return getUNDEF(VT);
7601
7602 if (OpOpcode == ISD::FNEG) // --X -> X
7603 return N1.getOperand(0);
7604 break;
7605 case ISD::FABS:
7606 if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X)
7607 return getNode(ISD::FABS, DL, VT, N1.getOperand(0));
7608 break;
7609 case ISD::VSCALE:
7610 assert(VT == N1.getValueType() && "Unexpected VT!");
7611 break;
7612 case ISD::CTPOP:
7613 if (N1.getValueType().getScalarType() == MVT::i1)
7614 return N1;
7615 break;
7616 case ISD::CTLZ:
7617 case ISD::CTTZ:
7618 if (N1.getValueType().getScalarType() == MVT::i1)
7619 return getNOT(DL, N1, N1.getValueType());
7620 break;
7621 case ISD::CTLS:
7622 if (N1.getValueType().getScalarType() == MVT::i1)
7623 return getConstant(0, DL, VT);
7624 break;
7625 case ISD::VECREDUCE_ADD:
7626 if (N1.getValueType().getScalarType() == MVT::i1)
7627 return getNode(ISD::VECREDUCE_XOR, DL, VT, N1);
7628 break;
7631 if (N1.getValueType().getScalarType() == MVT::i1)
7632 return getNode(ISD::VECREDUCE_OR, DL, VT, N1);
7633 break;
7636 if (N1.getValueType().getScalarType() == MVT::i1)
7637 return getNode(ISD::VECREDUCE_AND, DL, VT, N1);
7638 break;
7640 // With a single lane, the result is true iff that lane is false.
7642 return getLogicalNOT(DL, N1, VT);
7643 break;
7644 case ISD::VECTOR_REPEAT:
7646 "VECTOR_REPEAT requires a fixed-length vector operand");
7647 assert(VT.isScalableVector() &&
7648 "VECTOR_REPEAT requires a scalable vector result");
7651 "VECTOR_REPEAT operand and result element counts must match");
7652 if (VT.getVectorMinNumElements() == 1)
7653 return getSplatVector(
7654 VT, DL, getExtractVectorElt(DL, VT.getVectorElementType(), N1, 0));
7655 break;
7656 case ISD::SPLAT_VECTOR:
7657 assert(VT.isVector() && "Wrong return type!");
7658 // FIXME: Hexagon uses i32 scalar for a floating point zero vector so allow
7659 // that for now.
7661 (VT.isFloatingPoint() && N1.getValueType() == MVT::i32) ||
7663 N1.getValueType().isInteger() &&
7665 "Wrong operand type!");
7666 break;
7667 }
7668
7669 SDNode *N;
7670 SDVTList VTs = getVTList(VT);
7671 SDValue Ops[] = {N1};
7672 if (VT != MVT::Glue) { // Don't CSE glue producing nodes
7673 SDNodeKey ID(Opcode, VTs, Ops);
7674 FoldingSetInsertToken InsertToken;
7675 if (SDNode *E = lookupNode(ID, DL, InsertToken)) {
7676 E->intersectFlagsWith(Flags);
7677 return SDValue(E, 0);
7678 }
7679
7680 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
7681 N->setFlags(Flags);
7682 createOperands(N, Ops);
7683 CSEMap.insert(N, InsertToken);
7684 } else {
7685 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
7686 createOperands(N, Ops);
7687 }
7688
7689 InsertNode(N);
7690 SDValue V = SDValue(N, 0);
7691 NewSDValueDbgMsg(V, "Creating new node: ", this);
7692 return V;
7693}
7694
7695static APInt getIntegerIdentity(unsigned Opcode, unsigned BitWidth) {
7696 switch (Opcode) {
7697 default:
7698 llvm_unreachable("Unexpected integer identity opcode");
7699 case ISD::ADD:
7700 case ISD::OR:
7701 case ISD::XOR:
7702 case ISD::UMAX:
7703 return APInt::getZero(BitWidth);
7704 case ISD::MUL:
7705 return APInt(BitWidth, 1);
7706 case ISD::AND:
7707 case ISD::UMIN:
7709 case ISD::SMAX:
7711 case ISD::SMIN:
7713 }
7714}
7715
7716static std::optional<APInt> FoldValue(unsigned Opcode, const APInt &C1,
7717 const APInt &C2) {
7718 switch (Opcode) {
7719 case ISD::ADD: return C1 + C2;
7720 case ISD::SUB: return C1 - C2;
7721 case ISD::MUL: return C1 * C2;
7722 case ISD::AND: return C1 & C2;
7723 case ISD::OR: return C1 | C2;
7724 case ISD::XOR: return C1 ^ C2;
7725 case ISD::SHL: return C1 << C2;
7726 case ISD::SRL: return C1.lshr(C2);
7727 case ISD::SRA: return C1.ashr(C2);
7728 case ISD::ROTL: return C1.rotl(C2);
7729 case ISD::ROTR: return C1.rotr(C2);
7730 case ISD::SMIN: return C1.sle(C2) ? C1 : C2;
7731 case ISD::SMAX: return C1.sge(C2) ? C1 : C2;
7732 case ISD::UMIN: return C1.ule(C2) ? C1 : C2;
7733 case ISD::UMAX: return C1.uge(C2) ? C1 : C2;
7734 case ISD::SADDSAT: return C1.sadd_sat(C2);
7735 case ISD::UADDSAT: return C1.uadd_sat(C2);
7736 case ISD::SSUBSAT: return C1.ssub_sat(C2);
7737 case ISD::USUBSAT: return C1.usub_sat(C2);
7738 case ISD::SSHLSAT: return C1.sshl_sat(C2);
7739 case ISD::USHLSAT: return C1.ushl_sat(C2);
7740 case ISD::UDIV:
7741 if (!C2.getBoolValue())
7742 break;
7743 return C1.udiv(C2);
7744 case ISD::UREM:
7745 if (!C2.getBoolValue())
7746 break;
7747 return C1.urem(C2);
7748 case ISD::SDIV:
7749 if (!C2.getBoolValue())
7750 break;
7751 return C1.sdiv(C2);
7752 case ISD::SREM:
7753 if (!C2.getBoolValue())
7754 break;
7755 return C1.srem(C2);
7756 case ISD::AVGFLOORS:
7757 return APIntOps::avgFloorS(C1, C2);
7758 case ISD::AVGFLOORU:
7759 return APIntOps::avgFloorU(C1, C2);
7760 case ISD::AVGCEILS:
7761 return APIntOps::avgCeilS(C1, C2);
7762 case ISD::AVGCEILU:
7763 return APIntOps::avgCeilU(C1, C2);
7764 case ISD::AVGSUBFLOORS:
7765 return APIntOps::avgSubFloorS(C1, C2);
7766 case ISD::AVGSUBFLOORU:
7767 return APIntOps::avgSubFloorU(C1, C2);
7768 case ISD::ABDS:
7769 return APIntOps::abds(C1, C2);
7770 case ISD::ABDU:
7771 return APIntOps::abdu(C1, C2);
7772 case ISD::MULHS:
7773 return APIntOps::mulhs(C1, C2);
7774 case ISD::MULHU:
7775 return APIntOps::mulhu(C1, C2);
7776 case ISD::CLMUL:
7777 return APIntOps::clmul(C1, C2);
7778 case ISD::CLMULR:
7779 return APIntOps::clmulr(C1, C2);
7780 case ISD::CLMULH:
7781 return APIntOps::clmulh(C1, C2);
7782 case ISD::PEXT:
7783 return APIntOps::pext(C1, C2);
7784 case ISD::PDEP:
7785 return APIntOps::pdep(C1, C2);
7786 }
7787 return std::nullopt;
7788}
7789// Handle constant folding with UNDEF.
7790// TODO: Handle more cases.
7791static std::optional<APInt> FoldValueWithUndef(unsigned Opcode, const APInt &C1,
7792 bool IsUndef1, const APInt &C2,
7793 bool IsUndef2) {
7794 if (!(IsUndef1 || IsUndef2))
7795 return FoldValue(Opcode, C1, C2);
7796
7797 // Fold and(x, undef) -> 0
7798 // Fold mul(x, undef) -> 0
7799 if (Opcode == ISD::AND || Opcode == ISD::MUL)
7800 return APInt::getZero(C1.getBitWidth());
7801
7802 return std::nullopt;
7803}
7804
7806 const GlobalAddressSDNode *GA,
7807 const SDNode *N2) {
7808 if (GA->getOpcode() != ISD::GlobalAddress)
7809 return SDValue();
7810 if (!TLI->isOffsetFoldingLegal(GA))
7811 return SDValue();
7812 auto *C2 = dyn_cast<ConstantSDNode>(N2);
7813 if (!C2)
7814 return SDValue();
7815 int64_t Offset = C2->getSExtValue();
7816 switch (Opcode) {
7817 case ISD::ADD:
7818 case ISD::PTRADD:
7819 break;
7820 case ISD::SUB: Offset = -uint64_t(Offset); break;
7821 default: return SDValue();
7822 }
7823 return getGlobalAddress(GA->getGlobal(), SDLoc(C2), VT,
7824 GA->getOffset() + uint64_t(Offset));
7825}
7826
7828 switch (Opcode) {
7829 case ISD::SDIV:
7830 case ISD::UDIV:
7831 case ISD::SREM:
7832 case ISD::UREM: {
7833 // If a divisor is zero/undef or any element of a divisor vector is
7834 // zero/undef, the whole op is undef.
7835 assert(Ops.size() == 2 && "Div/rem should have 2 operands");
7836 SDValue Divisor = Ops[1];
7837 if (Divisor.isUndef() || isNullConstant(Divisor))
7838 return true;
7839
7840 return ISD::isBuildVectorOfConstantSDNodes(Divisor) &&
7841 llvm::any_of(Divisor->op_values(), [](SDValue V) {
7842 return V.isUndef() || isNullConstant(V);
7843 });
7844 // TODO: Handle signed overflow.
7845 }
7846 // TODO: Handle oversized shifts.
7847 default:
7848 return false;
7849 }
7850}
7851
7854 SDNodeFlags Flags) {
7855 // If the opcode is a target-specific ISD node, there's nothing we can
7856 // do here and the operand rules may not line up with the below, so
7857 // bail early.
7858 // We can't create a scalar CONCAT_VECTORS so skip it. It will break
7859 // for concats involving SPLAT_VECTOR. Concats of BUILD_VECTORS are handled by
7860 // foldCONCAT_VECTORS in getNode before this is called.
7861 // VECTOR_SHUFFLE_VAR is not elementwise.
7862 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::CONCAT_VECTORS ||
7863 Opcode == ISD::VECTOR_SHUFFLE_VAR)
7864 return SDValue();
7865
7866 unsigned NumOps = Ops.size();
7867 if (NumOps == 0)
7868 return SDValue();
7869
7870 if (isUndef(Opcode, Ops))
7871 return getUNDEF(VT);
7872
7873 // Handle unary special cases.
7874 if (NumOps == 1) {
7875 SDValue N1 = Ops[0];
7876
7877 // Constant fold unary operations with an integer constant operand. Even
7878 // opaque constant will be folded, because the folding of unary operations
7879 // doesn't create new constants with different values. Nevertheless, the
7880 // opaque flag is preserved during folding to prevent future folding with
7881 // other constants.
7882 if (auto *C = dyn_cast<ConstantSDNode>(N1)) {
7883 const APInt &Val = C->getAPIntValue();
7884 switch (Opcode) {
7885 case ISD::SIGN_EXTEND:
7886 return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
7887 C->isTargetOpcode(), C->isOpaque());
7888 case ISD::TRUNCATE:
7889 if (C->isOpaque())
7890 break;
7891 [[fallthrough]];
7892 case ISD::ZERO_EXTEND:
7893 return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
7894 C->isTargetOpcode(), C->isOpaque());
7895 case ISD::ANY_EXTEND:
7896 // Some targets like RISCV prefer to sign extend some types.
7897 if (TLI->isSExtCheaperThanZExt(N1.getValueType(), VT))
7898 return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
7899 C->isTargetOpcode(), C->isOpaque());
7900 return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
7901 C->isTargetOpcode(), C->isOpaque());
7902 case ISD::ABS:
7903 return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(),
7904 C->isOpaque());
7906 if (Val.isMinSignedValue())
7907 return getPOISON(VT);
7908 return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(),
7909 C->isOpaque());
7910 case ISD::BITREVERSE:
7911 return getConstant(Val.reverseBits(), DL, VT, C->isTargetOpcode(),
7912 C->isOpaque());
7913 case ISD::BSWAP:
7914 return getConstant(Val.byteSwap(), DL, VT, C->isTargetOpcode(),
7915 C->isOpaque());
7916 case ISD::CTPOP:
7917 return getConstant(Val.popcount(), DL, VT, C->isTargetOpcode(),
7918 C->isOpaque());
7919 case ISD::PARITY:
7920 return getConstant(Val.popcount() & 1, DL, VT, C->isTargetOpcode(),
7921 C->isOpaque());
7922 case ISD::CTLZ:
7924 return getConstant(Val.countl_zero(), DL, VT, C->isTargetOpcode(),
7925 C->isOpaque());
7926 case ISD::CTTZ:
7928 return getConstant(Val.countr_zero(), DL, VT, C->isTargetOpcode(),
7929 C->isOpaque());
7930 case ISD::CTLS:
7931 // CTLS returns the number of extra sign bits so subtract one.
7932 return getConstant(Val.getNumSignBits() - 1, DL, VT,
7933 C->isTargetOpcode(), C->isOpaque());
7934 case ISD::UINT_TO_FP:
7935 case ISD::SINT_TO_FP: {
7937 (void)FPV.convertFromAPInt(Val, Opcode == ISD::SINT_TO_FP,
7939 return getConstantFP(FPV, DL, VT);
7940 }
7941 case ISD::FP16_TO_FP:
7942 case ISD::BF16_TO_FP: {
7943 bool Ignored;
7944 APFloat FPV(Opcode == ISD::FP16_TO_FP ? APFloat::IEEEhalf()
7945 : APFloat::BFloat(),
7946 (Val.getBitWidth() == 16) ? Val : Val.trunc(16));
7947
7948 // This can return overflow, underflow, or inexact; we don't care.
7949 // FIXME need to be more flexible about rounding mode.
7951 &Ignored);
7952 return getConstantFP(FPV, DL, VT);
7953 }
7954 case ISD::STEP_VECTOR:
7955 if (SDValue V = FoldSTEP_VECTOR(DL, VT, N1, *this))
7956 return V;
7957 break;
7958 case ISD::BITCAST:
7959 if (C->isOpaque())
7960 break;
7961 if (VT == MVT::f16 && C->getValueType(0) == MVT::i16)
7962 return getConstantFP(APFloat(APFloat::IEEEhalf(), Val), DL, VT);
7963 if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
7964 return getConstantFP(APFloat(APFloat::IEEEsingle(), Val), DL, VT);
7965 if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
7966 return getConstantFP(APFloat(APFloat::IEEEdouble(), Val), DL, VT);
7967 if (VT == MVT::f128 && C->getValueType(0) == MVT::i128)
7968 return getConstantFP(APFloat(APFloat::IEEEquad(), Val), DL, VT);
7969 break;
7970 }
7971 }
7972
7973 // Constant fold unary operations with a floating point constant operand.
7974 if (auto *C = dyn_cast<ConstantFPSDNode>(N1)) {
7975 APFloat V = C->getValueAPF(); // make copy
7976 DenormalMode DenormMode = getDenormalMode(N1.getValueType());
7977 switch (Opcode) {
7978 case ISD::FNEG:
7979 V.changeSign();
7980 return getConstantFP(V, DL, VT);
7981 case ISD::FABS:
7982 V.clearSign();
7983 return getConstantFP(V, DL, VT);
7984 case ISD::FCEIL: {
7985 if (auto Res = tryFoldFP(FPOp::Ceil, {V}, DenormMode))
7986 if (Res->Status == APFloat::opOK || Res->Status == APFloat::opInexact)
7987 return getConstantFP(Res->Value, DL, VT);
7988 return SDValue();
7989 }
7990 case ISD::FTRUNC: {
7991 if (auto Res = tryFoldFP(FPOp::Trunc, {V}, DenormMode))
7992 if (Res->Status == APFloat::opOK || Res->Status == APFloat::opInexact)
7993 return getConstantFP(Res->Value, DL, VT);
7994 return SDValue();
7995 }
7996 case ISD::FFLOOR: {
7997 if (auto Res = tryFoldFP(FPOp::Floor, {V}, DenormMode))
7998 if (Res->Status == APFloat::opOK || Res->Status == APFloat::opInexact)
7999 return getConstantFP(Res->Value, DL, VT);
8000 return SDValue();
8001 }
8002 case ISD::FP_EXTEND: {
8003 bool ignored;
8004 // This can return overflow, underflow, or inexact; we don't care.
8005 // FIXME need to be more flexible about rounding mode.
8006 (void)V.convert(VT.getFltSemantics(), APFloat::rmNearestTiesToEven,
8007 &ignored);
8008 return getConstantFP(V, DL, VT);
8009 }
8010 case ISD::FP_TO_SINT:
8011 case ISD::FP_TO_UINT: {
8012 bool ignored;
8013 APSInt IntVal(VT.getSizeInBits(), Opcode == ISD::FP_TO_UINT);
8014 // FIXME need to be more flexible about rounding mode.
8016 V.convertToInteger(IntVal, APFloat::rmTowardZero, &ignored);
8017 if (s == APFloat::opInvalidOp) // inexact is OK, in fact usual
8018 break;
8019 return getConstant(IntVal, DL, VT);
8020 }
8021 case ISD::FP_TO_FP16:
8022 case ISD::FP_TO_BF16: {
8023 bool Ignored;
8024 // This can return overflow, underflow, or inexact; we don't care.
8025 // FIXME need to be more flexible about rounding mode.
8026 (void)V.convert(Opcode == ISD::FP_TO_FP16 ? APFloat::IEEEhalf()
8027 : APFloat::BFloat(),
8029 return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
8030 }
8031 case ISD::BITCAST:
8032 if (VT == MVT::i16 && C->getValueType(0) == MVT::f16)
8033 return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL,
8034 VT);
8035 if (VT == MVT::i16 && C->getValueType(0) == MVT::bf16)
8036 return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL,
8037 VT);
8038 if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
8039 return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), DL,
8040 VT);
8041 if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
8042 return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
8043 break;
8044 }
8045 }
8046
8047 // Early-out if we failed to constant fold a bitcast.
8048 if (Opcode == ISD::BITCAST)
8049 return SDValue();
8050
8051 // Constant fold integer vector reductions with constant BUILD_VECTORs.
8052 if ((Opcode == ISD::VECREDUCE_ADD || Opcode == ISD::VECREDUCE_SMAX ||
8053 Opcode == ISD::VECREDUCE_SMIN || Opcode == ISD::VECREDUCE_UMAX ||
8054 Opcode == ISD::VECREDUCE_UMIN || Opcode == ISD::VECREDUCE_MUL ||
8055 Opcode == ISD::VECREDUCE_OR || Opcode == ISD::VECREDUCE_XOR ||
8056 Opcode == ISD::VECREDUCE_AND) &&
8058 unsigned EltBits = N1.getValueType().getScalarSizeInBits();
8059 unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Opcode);
8060 APInt Acc = getIntegerIdentity(BaseOpcode, EltBits);
8061 for (SDValue Elt : N1->op_values()) {
8062 if (Elt.getOpcode() == ISD::POISON)
8063 return getPOISON(VT);
8064 if (Elt.isUndef() || cast<ConstantSDNode>(Elt)->isOpaque())
8065 return SDValue();
8066 APInt Value = cast<ConstantSDNode>(Elt)->getAPIntValue().trunc(EltBits);
8067 std::optional<APInt> Folded = FoldValue(BaseOpcode, Acc, Value);
8068 assert(Folded &&
8069 "Expected vector reduction base opcode to be foldable");
8070 Acc = *Folded;
8071 }
8072 EVT EltVT = N1.getValueType().getScalarType();
8073 return getAnyExtOrTrunc(getConstant(Acc, DL, EltVT), DL, VT);
8074 }
8075 }
8076
8077 // Handle binops special cases.
8078 if (NumOps == 2) {
8079 if (SDValue CFP = foldConstantFPMath(Opcode, DL, VT, Ops))
8080 return CFP;
8081
8082 if (auto *C1 = dyn_cast<ConstantSDNode>(Ops[0])) {
8083 if (auto *C2 = dyn_cast<ConstantSDNode>(Ops[1])) {
8084 if (C1->isOpaque() || C2->isOpaque())
8085 return SDValue();
8086
8087 std::optional<APInt> FoldAttempt =
8088 FoldValue(Opcode, C1->getAPIntValue(), C2->getAPIntValue());
8089 if (!FoldAttempt)
8090 return SDValue();
8091
8092 SDValue Folded = getConstant(*FoldAttempt, DL, VT);
8093 assert((!Folded || !VT.isVector()) &&
8094 "Can't fold vectors ops with scalar operands");
8095 return Folded;
8096 }
8097 }
8098
8099 // fold (add Sym, c) -> Sym+c
8101 return FoldSymbolOffset(Opcode, VT, GA, Ops[1].getNode());
8102 if (TLI->isCommutativeBinOp(Opcode))
8104 return FoldSymbolOffset(Opcode, VT, GA, Ops[0].getNode());
8105
8106 // fold (sext_in_reg c1) -> c2
8107 if (Opcode == ISD::SIGN_EXTEND_INREG) {
8108 EVT EVT = cast<VTSDNode>(Ops[1])->getVT();
8109
8110 auto SignExtendInReg = [&](APInt Val, llvm::EVT ConstantVT) {
8111 unsigned FromBits = EVT.getScalarSizeInBits();
8112 Val <<= Val.getBitWidth() - FromBits;
8113 Val.ashrInPlace(Val.getBitWidth() - FromBits);
8114 return getConstant(Val, DL, ConstantVT);
8115 };
8116
8117 if (auto *C1 = dyn_cast<ConstantSDNode>(Ops[0])) {
8118 const APInt &Val = C1->getAPIntValue();
8119 return SignExtendInReg(Val, VT);
8120 }
8121
8123 SmallVector<SDValue, 8> ScalarOps;
8124 llvm::EVT OpVT = Ops[0].getOperand(0).getValueType();
8125 for (int I = 0, E = VT.getVectorNumElements(); I != E; ++I) {
8126 SDValue Op = Ops[0].getOperand(I);
8127 if (Op.isUndef()) {
8128 ScalarOps.push_back(getUNDEF(OpVT));
8129 continue;
8130 }
8131 const APInt &Val = cast<ConstantSDNode>(Op)->getAPIntValue();
8132 ScalarOps.push_back(SignExtendInReg(Val, OpVT));
8133 }
8134 return getBuildVector(VT, DL, ScalarOps);
8135 }
8136
8137 if (Ops[0].getOpcode() == ISD::SPLAT_VECTOR &&
8138 isa<ConstantSDNode>(Ops[0].getOperand(0)))
8139 return getNode(ISD::SPLAT_VECTOR, DL, VT,
8140 SignExtendInReg(Ops[0].getConstantOperandAPInt(0),
8141 Ops[0].getOperand(0).getValueType()));
8142 }
8143 }
8144
8145 // Handle fshl/fshr special cases.
8146 if (Opcode == ISD::FSHL || Opcode == ISD::FSHR) {
8147 auto *C1 = dyn_cast<ConstantSDNode>(Ops[0]);
8148 auto *C2 = dyn_cast<ConstantSDNode>(Ops[1]);
8149 auto *C3 = dyn_cast<ConstantSDNode>(Ops[2]);
8150
8151 if (C1 && C2 && C3) {
8152 if (C1->isOpaque() || C2->isOpaque() || C3->isOpaque())
8153 return SDValue();
8154 const APInt &V1 = C1->getAPIntValue(), &V2 = C2->getAPIntValue(),
8155 &V3 = C3->getAPIntValue();
8156
8157 APInt FoldedVal = Opcode == ISD::FSHL ? APIntOps::fshl(V1, V2, V3)
8158 : APIntOps::fshr(V1, V2, V3);
8159 return getConstant(FoldedVal, DL, VT);
8160 }
8161 }
8162
8163 // Handle fma/fmad special cases.
8164 if (Opcode == ISD::FMA || Opcode == ISD::FMAD || Opcode == ISD::FMULADD) {
8165 assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
8166 assert(Ops[0].getValueType() == VT && Ops[1].getValueType() == VT &&
8167 Ops[2].getValueType() == VT && "FMA types must match!");
8171 if (C1 && C2 && C3) {
8173 APFloat V1 = C1->getValueAPF();
8174 const APFloat &V2 = C2->getValueAPF();
8175 const APFloat &V3 = C3->getValueAPF();
8176 if (Opcode == ISD::FMAD || Opcode == ISD::FMULADD) {
8177 if (auto Product = tryFoldFP(FPOp::Mul, {V1, V2}, DM))
8178 return getConstFP(tryFoldFP(FPOp::Add, {Product->Value, V3}, DM), DL,
8179 VT);
8180 return SDValue();
8181 }
8182 return getConstFP(tryFoldFP(FPOp::FMA, {V1, V2, V3}, DM), DL, VT);
8183 }
8184 }
8185
8186 // This is for vector folding only from here on.
8187 if (!VT.isVector())
8188 return SDValue();
8189
8190 // Constant fold integer partial reductions with constant BUILD_VECTOR
8191 // operands. The reduction order is deliberately unspecified. Use the same
8192 // subvector layout as TargetLowering::expandPartialReduceMLA(), where input
8193 // lane I contributes to accumulator lane I % NumAccElts.
8194 if (Opcode == ISD::PARTIAL_REDUCE_SMLA ||
8195 Opcode == ISD::PARTIAL_REDUCE_UMLA ||
8196 Opcode == ISD::PARTIAL_REDUCE_SUMLA) {
8197 // These nodes have no scalar form, so unsupported cases must not fall
8198 // through to generic per-lane vector folding.
8199 if (!llvm::all_of(Ops, [](SDValue Op) {
8201 }))
8202 return SDValue();
8203
8204 unsigned AccEltBits = VT.getScalarSizeInBits();
8205 unsigned InputEltBits = Ops[1].getScalarValueSizeInBits();
8206 unsigned NumAccElts = VT.getVectorNumElements();
8207 unsigned NumInputElts = Ops[1].getValueType().getVectorNumElements();
8208 SmallVector<APInt, 8> Results(NumAccElts, APInt::getZero(AccEltBits));
8209 BitVector PoisonElts(NumAccElts);
8210
8211 for (unsigned I = 0; I != NumAccElts; ++I) {
8212 SDValue Elt = Ops[0].getOperand(I);
8213 if (Elt.getOpcode() == ISD::POISON) {
8214 PoisonElts.set(I);
8215 continue;
8216 }
8217 auto *C = dyn_cast<ConstantSDNode>(Elt);
8218 if (!C || C->isOpaque())
8219 return SDValue();
8220 Results[I] = C->getAPIntValue().trunc(AccEltBits);
8221 }
8222
8223 bool IsLHSSigned = Opcode != ISD::PARTIAL_REDUCE_UMLA;
8224 bool IsRHSSigned = Opcode == ISD::PARTIAL_REDUCE_SMLA;
8225 for (unsigned I = 0; I != NumInputElts; ++I) {
8226 const unsigned AccIdx = I % NumAccElts;
8227 SDValue LHSElt = Ops[1].getOperand(I);
8228 SDValue RHSElt = Ops[2].getOperand(I);
8229 if (LHSElt.getOpcode() == ISD::POISON ||
8230 RHSElt.getOpcode() == ISD::POISON) {
8231 PoisonElts.set(AccIdx);
8232 continue;
8233 }
8234
8235 auto *LHS = dyn_cast<ConstantSDNode>(LHSElt);
8236 auto *RHS = dyn_cast<ConstantSDNode>(RHSElt);
8237 if (!LHS || !RHS || LHS->isOpaque() || RHS->isOpaque())
8238 return SDValue();
8239
8240 APInt LHSVal = LHS->getAPIntValue().trunc(InputEltBits);
8241 APInt RHSVal = RHS->getAPIntValue().trunc(InputEltBits);
8242 LHSVal = IsLHSSigned ? LHSVal.sext(AccEltBits) : LHSVal.zext(AccEltBits);
8243 RHSVal = IsRHSSigned ? RHSVal.sext(AccEltBits) : RHSVal.zext(AccEltBits);
8244 Results[AccIdx] += LHSVal * RHSVal;
8245 }
8246
8247 // After type legalization the vector element type may not be a legal
8248 // scalar type (e.g. i16 on AArch64). Create the folded constants in the
8249 // promoted legal scalar type instead, matching the generic per-lane path
8250 // below. Bail out if legalization would narrow the type, since the lane
8251 // value would not fit.
8252 EVT AccEltVT = VT.getVectorElementType();
8253 EVT LegalSVT = AccEltVT;
8254 if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
8255 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
8256 if (LegalSVT.bitsLT(AccEltVT))
8257 return SDValue();
8258 }
8259
8260 SmallVector<SDValue, 8> ResultOps;
8261 for (unsigned I = 0; I != NumAccElts; ++I)
8262 ResultOps.push_back(
8263 PoisonElts[I] ? getPOISON(LegalSVT)
8264 : getConstant(Results[I].sext(LegalSVT.getSizeInBits()),
8265 DL, LegalSVT));
8266 return getBuildVector(VT, DL, ResultOps);
8267 }
8268
8269 ElementCount NumElts = VT.getVectorElementCount();
8270
8271 // See if we can fold through any bitcasted integer ops.
8272 if (NumOps == 2 && VT.isFixedLengthVector() && VT.isInteger() &&
8273 Ops[0].getValueType() == VT && Ops[1].getValueType() == VT &&
8274 (Ops[0].getOpcode() == ISD::BITCAST ||
8275 Ops[1].getOpcode() == ISD::BITCAST)) {
8278 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
8279 auto *BV2 = dyn_cast<BuildVectorSDNode>(N2);
8280 if (BV1 && BV2 && N1.getValueType().isInteger() &&
8281 N2.getValueType().isInteger()) {
8282 bool IsLE = getDataLayout().isLittleEndian();
8283 unsigned EltBits = VT.getScalarSizeInBits();
8284 SmallVector<APInt> RawBits1, RawBits2;
8285 BitVector UndefElts1, UndefElts2;
8286 if (BV1->getConstantRawBits(IsLE, EltBits, RawBits1, UndefElts1) &&
8287 BV2->getConstantRawBits(IsLE, EltBits, RawBits2, UndefElts2)) {
8288 SmallVector<APInt> RawBits;
8289 for (unsigned I = 0, E = NumElts.getFixedValue(); I != E; ++I) {
8290 std::optional<APInt> Fold = FoldValueWithUndef(
8291 Opcode, RawBits1[I], UndefElts1[I], RawBits2[I], UndefElts2[I]);
8292 if (!Fold)
8293 break;
8294 RawBits.push_back(*Fold);
8295 }
8296 if (RawBits.size() == NumElts.getFixedValue()) {
8297 // We have constant folded, but we might need to cast this again back
8298 // to the original (possibly legalized) type.
8299 EVT BVVT, BVEltVT;
8300 if (N1.getValueType() == VT) {
8301 BVVT = N1.getValueType();
8302 BVEltVT = BV1->getOperand(0).getValueType();
8303 } else {
8304 BVVT = N2.getValueType();
8305 BVEltVT = BV2->getOperand(0).getValueType();
8306 }
8307 unsigned BVEltBits = BVEltVT.getSizeInBits();
8308 SmallVector<APInt> DstBits;
8309 BitVector DstUndefs;
8311 DstBits, RawBits, DstUndefs,
8312 BitVector(RawBits.size(), false));
8313 SmallVector<SDValue> Ops(DstBits.size(), getUNDEF(BVEltVT));
8314 for (unsigned I = 0, E = DstBits.size(); I != E; ++I) {
8315 if (DstUndefs[I])
8316 continue;
8317 Ops[I] = getConstant(DstBits[I].sext(BVEltBits), DL, BVEltVT);
8318 }
8319 return getBitcast(VT, getBuildVector(BVVT, DL, Ops));
8320 }
8321 }
8322 }
8323 // Logic ops can be folded from raw integer bits - mainly for AVX512 masks.
8324 if (ISD::isBitwiseLogicOp(Opcode) && isa<ConstantSDNode>(N1) &&
8325 isa<ConstantSDNode>(N2)) {
8326 if (SDValue Res = FoldConstantArithmetic(Opcode, DL, N1.getValueType(),
8327 {N1, N2}, Flags))
8328 return getBitcast(VT, Res);
8329 }
8330 }
8331
8332 // Fold (mul step_vector(C0), C1) to (step_vector(C0 * C1)).
8333 // (shl step_vector(C0), C1) -> (step_vector(C0 << C1))
8334 if ((Opcode == ISD::MUL || Opcode == ISD::SHL) &&
8335 Ops[0].getOpcode() == ISD::STEP_VECTOR) {
8336 APInt RHSVal;
8337 if (ISD::isConstantSplatVector(Ops[1], RHSVal)) {
8338 APInt NewStep = Opcode == ISD::MUL
8339 ? Ops[0].getConstantOperandAPInt(0) * RHSVal
8340 : Ops[0].getConstantOperandAPInt(0) << RHSVal;
8341 return getStepVector(DL, VT, NewStep);
8342 }
8343 }
8344
8345 auto IsScalarOrSameVectorSize = [NumElts](const SDValue &Op) {
8346 return !Op.getValueType().isVector() ||
8347 Op.getValueType().getVectorElementCount() == NumElts;
8348 };
8349
8350 auto IsBuildVectorSplatVectorOrUndef = [](const SDValue &Op) {
8351 return Op.isUndef() || Op.getOpcode() == ISD::CONDCODE ||
8352 Op.getOpcode() == ISD::BUILD_VECTOR ||
8353 Op.getOpcode() == ISD::SPLAT_VECTOR;
8354 };
8355
8356 // All operands must be vector types with the same number of elements as
8357 // the result type and must be either UNDEF or a build/splat vector
8358 // or UNDEF scalars.
8359 if (!llvm::all_of(Ops, IsBuildVectorSplatVectorOrUndef) ||
8360 !llvm::all_of(Ops, IsScalarOrSameVectorSize))
8361 return SDValue();
8362
8363 // If we are comparing vectors, then the result needs to be a i1 boolean that
8364 // is then extended back to the legal result type depending on how booleans
8365 // are represented.
8366 EVT SVT = (Opcode == ISD::SETCC ? MVT::i1 : VT.getScalarType());
8367 ISD::NodeType ExtendCode =
8368 (Opcode == ISD::SETCC && SVT != VT.getScalarType())
8369 ? TargetLowering::getExtendForContent(TLI->getBooleanContents(VT))
8371
8372 // Find legal integer scalar type for constant promotion and
8373 // ensure that its scalar size is at least as large as source.
8374 EVT LegalSVT = VT.getScalarType();
8375 if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
8376 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
8377 if (LegalSVT.bitsLT(VT.getScalarType()))
8378 return SDValue();
8379 }
8380
8381 // For scalable vector types we know we're dealing with SPLAT_VECTORs. We
8382 // only have one operand to check. For fixed-length vector types we may have
8383 // a combination of BUILD_VECTOR and SPLAT_VECTOR.
8384 unsigned NumVectorElts = NumElts.isScalable() ? 1 : NumElts.getFixedValue();
8385
8386 // Constant fold each scalar lane separately.
8387 SmallVector<SDValue, 4> ScalarResults;
8388 for (unsigned I = 0; I != NumVectorElts; I++) {
8389 SmallVector<SDValue, 4> ScalarOps;
8390 for (SDValue Op : Ops) {
8391 EVT InSVT = Op.getValueType().getScalarType();
8392 if (Op.getOpcode() != ISD::BUILD_VECTOR &&
8393 Op.getOpcode() != ISD::SPLAT_VECTOR) {
8394 if (Op.isUndef())
8395 ScalarOps.push_back(getUNDEF(InSVT));
8396 else
8397 ScalarOps.push_back(Op);
8398 continue;
8399 }
8400
8401 SDValue ScalarOp =
8402 Op.getOperand(Op.getOpcode() == ISD::SPLAT_VECTOR ? 0 : I);
8403 EVT ScalarVT = ScalarOp.getValueType();
8404
8405 // Build vector (integer) scalar operands may need implicit
8406 // truncation - do this before constant folding.
8407 if (ScalarVT.isInteger() && ScalarVT.bitsGT(InSVT)) {
8408 // Don't create illegally-typed nodes unless they're constants or undef
8409 // - if we fail to constant fold we can't guarantee the (dead) nodes
8410 // we're creating will be cleaned up before being visited for
8411 // legalization.
8412 if (NewNodesMustHaveLegalTypes && !ScalarOp.isUndef() &&
8413 !isa<ConstantSDNode>(ScalarOp) &&
8414 TLI->getTypeAction(*getContext(), InSVT) !=
8416 return SDValue();
8417 ScalarOp = getNode(ISD::TRUNCATE, DL, InSVT, ScalarOp);
8418 }
8419
8420 ScalarOps.push_back(ScalarOp);
8421 }
8422
8423 // Constant fold the scalar operands.
8424 SDValue ScalarResult = getNode(Opcode, DL, SVT, ScalarOps, Flags);
8425
8426 // Scalar folding only succeeded if the result is a constant or UNDEF.
8427 if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant &&
8428 ScalarResult.getOpcode() != ISD::ConstantFP)
8429 return SDValue();
8430
8431 // Legalize the (integer) scalar constant if necessary. We only do
8432 // this once we know the folding succeeded, since otherwise we would
8433 // get a node with illegal type which has a user.
8434 if (LegalSVT != SVT)
8435 ScalarResult = getNode(ExtendCode, DL, LegalSVT, ScalarResult);
8436
8437 ScalarResults.push_back(ScalarResult);
8438 }
8439
8440 SDValue V = NumElts.isScalable() ? getSplatVector(VT, DL, ScalarResults[0])
8441 : getBuildVector(VT, DL, ScalarResults);
8442 NewSDValueDbgMsg(V, "New node fold constant vector: ", this);
8443 return V;
8444}
8445
8447 SDVTList VTList,
8449 SDNodeFlags Flags) {
8450 if (VTList.NumVTs == 1)
8451 return FoldConstantArithmetic(Opcode, DL, VTList.VTs[0], Ops, Flags);
8452
8453 switch (Opcode) {
8454 case ISD::SADDO:
8455 case ISD::UADDO:
8456 case ISD::SSUBO:
8457 case ISD::USUBO:
8458 case ISD::SMULO:
8459 case ISD::UMULO: {
8460 // TODO: Support non-splat vector constants.
8463 if (!C1 || !C2 || C1->isOpaque() || C2->isOpaque())
8464 return SDValue();
8465
8466 const APInt &V1 = C1->getAPIntValue(), &V2 = C2->getAPIntValue();
8467 bool Overflow;
8468 APInt Result;
8469 switch (Opcode) {
8470 default:
8471 llvm_unreachable("Unexpected overflow opcode");
8472 case ISD::SADDO:
8473 Result = V1.sadd_ov(V2, Overflow);
8474 break;
8475 case ISD::UADDO:
8476 Result = V1.uadd_ov(V2, Overflow);
8477 break;
8478 case ISD::SSUBO:
8479 Result = V1.ssub_ov(V2, Overflow);
8480 break;
8481 case ISD::USUBO:
8482 Result = V1.usub_ov(V2, Overflow);
8483 break;
8484 case ISD::SMULO:
8485 Result = V1.smul_ov(V2, Overflow);
8486 break;
8487 case ISD::UMULO:
8488 Result = V1.umul_ov(V2, Overflow);
8489 break;
8490 }
8491
8492 EVT VT = VTList.VTs[0];
8493 return getNode(ISD::MERGE_VALUES, DL, VTList,
8494 {getConstant(Result, DL, VT),
8495 getBoolConstant(Overflow, DL, VTList.VTs[1], VT)},
8496 Flags);
8497 }
8498 case ISD::SMUL_LOHI:
8499 case ISD::UMUL_LOHI:
8500 // TODO: Support non-splat vector constants.
8503 if (!C1 || !C2 || C1->isOpaque() || C2->isOpaque())
8504 return SDValue();
8505
8506 const APInt &V1 = C1->getAPIntValue(), &V2 = C2->getAPIntValue();
8507 APInt Lo = V1 * V2;
8508 APInt Hi = (Opcode == ISD::SMUL_LOHI) ? APIntOps::mulhs(V1, V2)
8509 : APIntOps::mulhu(V1, V2);
8510 return getNode(ISD::MERGE_VALUES, DL, VTList,
8511 {getConstant(Lo, DL, VTList.VTs[0]),
8512 getConstant(Hi, DL, VTList.VTs[1])},
8513 Flags);
8514 }
8515 return SDValue();
8516}
8517
8520 // TODO: Add support for unary/ternary fp opcodes.
8521 if (Ops.size() != 2)
8522 return SDValue();
8523
8524 // TODO: We don't do any constant folding for strict FP opcodes here, but we
8525 // should. That will require dealing with a potentially non-default
8526 // rounding mode, checking the "opStatus" return value from the APFloat
8527 // math calculations, and possibly other variations.
8528 SDValue N1 = Ops[0];
8529 SDValue N2 = Ops[1];
8530 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1, /*AllowUndefs*/ false);
8531 ConstantFPSDNode *N2CFP = isConstOrConstSplatFP(N2, /*AllowUndefs*/ false);
8532 if (N1CFP && N2CFP) {
8533 APFloat C1 = N1CFP->getValueAPF();
8534 const APFloat &C2 = N2CFP->getValueAPF();
8536 switch (Opcode) {
8537 case ISD::FADD:
8538 return getConstFP(tryFoldFP(FPOp::Add, {C1, C2}, DM), DL, VT);
8539 case ISD::FSUB:
8540 return getConstFP(tryFoldFP(FPOp::Sub, {C1, C2}, DM), DL, VT);
8541 case ISD::FMUL:
8542 return getConstFP(tryFoldFP(FPOp::Mul, {C1, C2}, DM), DL, VT);
8543 case ISD::FDIV:
8544 return getConstFP(tryFoldFP(FPOp::Div, {C1, C2}, DM), DL, VT);
8545 case ISD::FREM:
8546 return getConstFP(tryFoldFP(FPOp::FRem, {C1, C2}, DM), DL, VT);
8547 case ISD::FCOPYSIGN:
8548 C1.copySign(C2);
8549 return getConstantFP(C1, DL, VT);
8550 case ISD::FMINNUM:
8551 return getConstFP(tryFoldFP(FPOp::MinNum, {C1, C2}, DM), DL, VT);
8552 case ISD::FMAXNUM:
8553 return getConstFP(tryFoldFP(FPOp::MaxNum, {C1, C2}, DM), DL, VT);
8554 case ISD::FMINIMUM:
8555 return getConstFP(tryFoldFP(FPOp::Minimum, {C1, C2}, DM), DL, VT);
8556 case ISD::FMAXIMUM:
8557 return getConstFP(tryFoldFP(FPOp::Maximum, {C1, C2}, DM), DL, VT);
8558 case ISD::FMINIMUMNUM:
8559 return getConstFP(tryFoldFP(FPOp::MinimumNum, {C1, C2}, DM), DL, VT);
8560 case ISD::FMAXIMUMNUM:
8561 return getConstFP(tryFoldFP(FPOp::MaximumNum, {C1, C2}, DM), DL, VT);
8562 default: break;
8563 }
8564 }
8565 if (N1CFP && Opcode == ISD::FP_ROUND) {
8566 APFloat C1 = N1CFP->getValueAPF(); // make copy
8567 bool Unused;
8568 // This can return overflow, underflow, or inexact; we don't care.
8569 // FIXME need to be more flexible about rounding mode.
8571 &Unused);
8572 return getConstantFP(C1, DL, VT);
8573 }
8574
8575 switch (Opcode) {
8576 case ISD::FSUB:
8577 // -0.0 - undef --> undef (consistent with "fneg undef")
8578 if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1, /*AllowUndefs*/ true))
8579 if (N1C && N1C->getValueAPF().isNegZero() && N2.isUndef())
8580 return getUNDEF(VT);
8581 [[fallthrough]];
8582
8583 case ISD::FADD:
8584 case ISD::FMUL:
8585 case ISD::FDIV:
8586 case ISD::FREM:
8587 // If both operands are undef, the result is undef. If 1 operand is undef,
8588 // the result is NaN. This should match the behavior of the IR optimizer.
8589 if (N1.isUndef() && N2.isUndef())
8590 return getUNDEF(VT);
8591 if (N1.isUndef() || N2.isUndef())
8593 }
8594 return SDValue();
8595}
8596
8598 const SDLoc &DL, EVT DstEltVT) {
8599 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
8600
8601 // If this is already the right type, we're done.
8602 if (SrcEltVT == DstEltVT)
8603 return SDValue(BV, 0);
8604
8605 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
8606 unsigned DstBitSize = DstEltVT.getSizeInBits();
8607
8608 // If this is a conversion of N elements of one type to N elements of another
8609 // type, convert each element. This handles FP<->INT cases.
8610 if (SrcBitSize == DstBitSize) {
8612 for (SDValue Op : BV->op_values()) {
8613 // If the vector element type is not legal, the BUILD_VECTOR operands
8614 // are promoted and implicitly truncated. Make that explicit here.
8615 if (Op.getValueType() != SrcEltVT)
8616 Op = getNode(ISD::TRUNCATE, DL, SrcEltVT, Op);
8617 Ops.push_back(getBitcast(DstEltVT, Op));
8618 }
8619 EVT VT = EVT::getVectorVT(*getContext(), DstEltVT,
8621 return getBuildVector(VT, DL, Ops);
8622 }
8623
8624 // Otherwise, we're growing or shrinking the elements. To avoid having to
8625 // handle annoying details of growing/shrinking FP values, we convert them to
8626 // int first.
8627 if (SrcEltVT.isFloatingPoint()) {
8628 // Convert the input float vector to a int vector where the elements are the
8629 // same sizes.
8630 EVT IntEltVT = EVT::getIntegerVT(*getContext(), SrcEltVT.getSizeInBits());
8631 if (SDValue Tmp = FoldConstantBuildVector(BV, DL, IntEltVT))
8633 DstEltVT);
8634 return SDValue();
8635 }
8636
8637 // Now we know the input is an integer vector. If the output is a FP type,
8638 // convert to integer first, then to FP of the right size.
8639 if (DstEltVT.isFloatingPoint()) {
8640 EVT IntEltVT = EVT::getIntegerVT(*getContext(), DstEltVT.getSizeInBits());
8641 if (SDValue Tmp = FoldConstantBuildVector(BV, DL, IntEltVT))
8643 DstEltVT);
8644 return SDValue();
8645 }
8646
8647 // Okay, we know the src/dst types are both integers of differing types.
8648 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
8649
8650 // Extract the constant raw bit data.
8651 BitVector UndefElements;
8652 SmallVector<APInt> RawBits;
8653 bool IsLE = getDataLayout().isLittleEndian();
8654 if (!BV->getConstantRawBits(IsLE, DstBitSize, RawBits, UndefElements))
8655 return SDValue();
8656
8658 for (unsigned I = 0, E = RawBits.size(); I != E; ++I) {
8659 if (UndefElements[I])
8660 Ops.push_back(getUNDEF(DstEltVT));
8661 else
8662 Ops.push_back(getConstant(RawBits[I], DL, DstEltVT));
8663 }
8664
8665 EVT VT = EVT::getVectorVT(*getContext(), DstEltVT, Ops.size());
8666 return getBuildVector(VT, DL, Ops);
8667}
8668
8670 assert(Val.getValueType().isInteger() && "Invalid AssertAlign!");
8671
8672 // There's no need to assert on a byte-aligned pointer. All pointers are at
8673 // least byte aligned.
8674 if (A == Align(1))
8675 return Val;
8676
8677 SDVTList VTs = getVTList(Val.getValueType());
8678 SDValue Ops[] = {Val};
8679 SDNodeKey ID(ISD::AssertAlign, VTs, Ops);
8680 ID.AddInteger(A.value());
8681
8682 FoldingSetInsertToken InsertToken;
8683 if (SDNode *E = lookupNode(ID, DL, InsertToken))
8684 return SDValue(E, 0);
8685
8686 auto *N =
8687 newSDNode<AssertAlignSDNode>(DL.getIROrder(), DL.getDebugLoc(), VTs, A);
8688 createOperands(N, {Val});
8689
8690 CSEMap.insert(N, InsertToken);
8691 InsertNode(N);
8692
8693 SDValue V(N, 0);
8694 NewSDValueDbgMsg(V, "Creating new node: ", this);
8695 return V;
8696}
8697
8698SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8699 SDValue N1, SDValue N2) {
8700 SDNodeFlags Flags;
8701 if (Inserter)
8702 Flags = Inserter->getFlags();
8703 return getNode(Opcode, DL, VT, N1, N2, Flags);
8704}
8705
8707 SDValue &N2) const {
8708 if (!TLI->isCommutativeBinOp(Opcode))
8709 return;
8710
8711 // Canonicalize:
8712 // binop(const, nonconst) -> binop(nonconst, const)
8715 bool N1CFP = isConstantFPBuildVectorOrConstantFP(N1);
8716 bool N2CFP = isConstantFPBuildVectorOrConstantFP(N2);
8717 if ((N1C && !N2C) || (N1CFP && !N2CFP))
8718 std::swap(N1, N2);
8719
8720 // Canonicalize:
8721 // binop(splat(x), step_vector) -> binop(step_vector, splat(x))
8722 else if (N1.getOpcode() == ISD::SPLAT_VECTOR &&
8724 std::swap(N1, N2);
8725}
8726
8727SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8728 SDValue N1, SDValue N2, const SDNodeFlags Flags) {
8730 N2.getOpcode() != ISD::DELETED_NODE &&
8731 "Operand is DELETED_NODE!");
8732
8733 canonicalizeCommutativeBinop(Opcode, N1, N2);
8734
8735 auto *N1C = dyn_cast<ConstantSDNode>(N1);
8736 auto *N2C = dyn_cast<ConstantSDNode>(N2);
8737
8738 // Don't allow undefs in vector splats - we might be returning N2 when folding
8739 // to zero etc.
8740 ConstantSDNode *N2CV =
8741 isConstOrConstSplat(N2, /*AllowUndefs*/ false, /*AllowTruncation*/ true);
8742
8743 switch (Opcode) {
8744 default: break;
8745 case ISD::TokenFactor:
8746 assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
8747 N2.getValueType() == MVT::Other && "Invalid token factor!");
8748 // Fold trivial token factors.
8749 if (N1.getOpcode() == ISD::EntryToken) return N2;
8750 if (N2.getOpcode() == ISD::EntryToken) return N1;
8751 if (N1 == N2) return N1;
8752 break;
8753 case ISD::BUILD_VECTOR: {
8754 // Attempt to simplify BUILD_VECTOR.
8755 SDValue Ops[] = {N1, N2};
8756 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
8757 return V;
8758 break;
8759 }
8760 case ISD::CONCAT_VECTORS: {
8761 SDValue Ops[] = {N1, N2};
8762 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
8763 return V;
8764 break;
8765 }
8766 case ISD::AND:
8767 assert(VT.isInteger() && "This operator does not apply to FP types!");
8768 assert(N1.getValueType() == N2.getValueType() &&
8769 N1.getValueType() == VT && "Binary operator types must match!");
8770 // (X & 0) -> 0. This commonly occurs when legalizing i64 values, so it's
8771 // worth handling here.
8772 if (N2CV && N2CV->isZero())
8773 return N2;
8774 if (N2CV && N2CV->isAllOnes()) // X & -1 -> X
8775 return N1;
8776 break;
8777 case ISD::OR:
8778 case ISD::XOR:
8779 case ISD::ADD:
8780 case ISD::PTRADD:
8781 case ISD::SUB:
8782 assert(VT.isInteger() && "This operator does not apply to FP types!");
8783 assert(N1.getValueType() == N2.getValueType() &&
8784 N1.getValueType() == VT && "Binary operator types must match!");
8785 // The equal operand types requirement is unnecessarily strong for PTRADD.
8786 // However, the SelectionDAGBuilder does not generate PTRADDs with different
8787 // operand types, and we'd need to re-implement GEP's non-standard wrapping
8788 // logic everywhere where PTRADDs may be folded or combined to properly
8789 // support them. If/when we introduce pointer types to the SDAG, we will
8790 // need to relax this constraint.
8791
8792 // (X ^|+- 0) -> X. This commonly occurs when legalizing i64 values, so
8793 // it's worth handling here.
8794 if (N2CV && N2CV->isZero())
8795 return N1;
8796 if ((Opcode == ISD::ADD || Opcode == ISD::SUB) &&
8797 VT.getScalarType() == MVT::i1)
8798 return getNode(ISD::XOR, DL, VT, N1, N2);
8799 // Fold (add (vscale * C0), (vscale * C1)) to (vscale * (C0 + C1)).
8800 if (Opcode == ISD::ADD && N1.getOpcode() == ISD::VSCALE &&
8801 N2.getOpcode() == ISD::VSCALE) {
8802 const APInt &C1 = N1->getConstantOperandAPInt(0);
8803 const APInt &C2 = N2->getConstantOperandAPInt(0);
8804 return getVScale(DL, VT, C1 + C2);
8805 }
8806 break;
8807 case ISD::MUL:
8808 assert(VT.isInteger() && "This operator does not apply to FP types!");
8809 assert(N1.getValueType() == N2.getValueType() &&
8810 N1.getValueType() == VT && "Binary operator types must match!");
8811 if (VT.getScalarType() == MVT::i1)
8812 return getNode(ISD::AND, DL, VT, N1, N2);
8813 if (N2CV && N2CV->isZero())
8814 return N2;
8815 if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
8816 const APInt &MulImm = N1->getConstantOperandAPInt(0);
8817 const APInt &N2CImm = N2C->getAPIntValue();
8818 return getVScale(DL, VT, MulImm * N2CImm);
8819 }
8820 break;
8821 case ISD::UDIV:
8822 case ISD::UREM:
8823 case ISD::MULHU:
8824 case ISD::MULHS:
8825 case ISD::SDIV:
8826 case ISD::SREM:
8827 case ISD::SADDSAT:
8828 case ISD::SSUBSAT:
8829 case ISD::UADDSAT:
8830 case ISD::USUBSAT:
8831 assert(VT.isInteger() && "This operator does not apply to FP types!");
8832 assert(N1.getValueType() == N2.getValueType() &&
8833 N1.getValueType() == VT && "Binary operator types must match!");
8834 if (VT.getScalarType() == MVT::i1) {
8835 // fold (add_sat x, y) -> (or x, y) for bool types.
8836 if (Opcode == ISD::SADDSAT || Opcode == ISD::UADDSAT)
8837 return getNode(ISD::OR, DL, VT, N1, N2);
8838 // fold (sub_sat x, y) -> (and x, ~y) for bool types.
8839 if (Opcode == ISD::SSUBSAT || Opcode == ISD::USUBSAT)
8840 return getNode(ISD::AND, DL, VT, N1, getNOT(DL, N2, VT));
8841 // mulhs/mulhu on i1 are always 0: the high bit of the 2-bit product of
8842 // two booleans is never set. The i1 constant 1 is also -1, so folding
8843 // (mulhs x, 1) to (sra x, 0) in DAGCombiner would be wrong here.
8844 if (Opcode == ISD::MULHS || Opcode == ISD::MULHU)
8845 return getConstant(0, DL, VT);
8846 }
8847 break;
8848 case ISD::SCMP:
8849 case ISD::UCMP:
8850 assert(N1.getValueType() == N2.getValueType() &&
8851 "Types of operands of UCMP/SCMP must match");
8852 assert(N1.getValueType().isVector() == VT.isVector() &&
8853 "Operands and return type of must both be scalars or vectors");
8854 if (VT.isVector())
8857 "Result and operands must have the same number of elements");
8858 break;
8859 case ISD::AVGFLOORS:
8860 case ISD::AVGFLOORU:
8861 case ISD::AVGCEILS:
8862 case ISD::AVGCEILU:
8863 case ISD::AVGSUBFLOORS:
8864 case ISD::AVGSUBFLOORU:
8865 assert(VT.isInteger() && "This operator does not apply to FP types!");
8866 assert(N1.getValueType() == N2.getValueType() &&
8867 N1.getValueType() == VT && "Binary operator types must match!");
8868 break;
8869 case ISD::ABDS:
8870 case ISD::ABDU:
8871 assert(VT.isInteger() && "This operator does not apply to FP types!");
8872 assert(N1.getValueType() == N2.getValueType() &&
8873 N1.getValueType() == VT && "Binary operator types must match!");
8874 if (VT.getScalarType() == MVT::i1)
8875 return getNode(ISD::XOR, DL, VT, N1, N2);
8876 break;
8877 case ISD::SMIN:
8878 case ISD::UMAX:
8879 assert(VT.isInteger() && "This operator does not apply to FP types!");
8880 assert(N1.getValueType() == N2.getValueType() &&
8881 N1.getValueType() == VT && "Binary operator types must match!");
8882 if (VT.getScalarType() == MVT::i1)
8883 return getNode(ISD::OR, DL, VT, N1, N2);
8884 break;
8885 case ISD::SMAX:
8886 case ISD::UMIN:
8887 assert(VT.isInteger() && "This operator does not apply to FP types!");
8888 assert(N1.getValueType() == N2.getValueType() &&
8889 N1.getValueType() == VT && "Binary operator types must match!");
8890 if (VT.getScalarType() == MVT::i1)
8891 return getNode(ISD::AND, DL, VT, N1, N2);
8892 break;
8893 case ISD::FADD:
8894 case ISD::FSUB:
8895 case ISD::FMUL:
8896 case ISD::FDIV:
8897 case ISD::FREM:
8898 assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
8899 assert(N1.getValueType() == N2.getValueType() &&
8900 N1.getValueType() == VT && "Binary operator types must match!");
8901 if (SDValue V = simplifyFPBinop(Opcode, N1, N2, Flags))
8902 return V;
8903 break;
8904 case ISD::FCOPYSIGN: // N1 and result must match. N1/N2 need not match.
8905 assert(N1.getValueType() == VT &&
8908 "Invalid FCOPYSIGN!");
8909 break;
8910 case ISD::SHL:
8911 if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
8912 const APInt &MulImm = N1->getConstantOperandAPInt(0);
8913 const APInt &ShiftImm = N2C->getAPIntValue();
8914 return getVScale(DL, VT, MulImm << ShiftImm);
8915 }
8916 [[fallthrough]];
8917 case ISD::SRA:
8918 case ISD::SRL:
8919 if (SDValue V = simplifyShift(N1, N2))
8920 return V;
8921 [[fallthrough]];
8922 case ISD::ROTL:
8923 case ISD::ROTR:
8924 case ISD::SSHLSAT:
8925 case ISD::USHLSAT:
8926 assert(VT == N1.getValueType() &&
8927 "Shift operators return type must be the same as their first arg");
8928 assert(VT.isInteger() && N2.getValueType().isInteger() &&
8929 "Shifts only work on integers");
8930 assert((!VT.isVector() || VT == N2.getValueType()) &&
8931 "Vector shift amounts must be in the same as their first arg");
8932 // Verify that the shift amount VT is big enough to hold valid shift
8933 // amounts. This catches things like trying to shift an i1024 value by an
8934 // i8, which is easy to fall into in generic code that uses
8935 // TLI.getShiftAmount().
8938 "Invalid use of small shift amount with oversized value!");
8939
8940 // Always fold shifts of i1 values so the code generator doesn't need to
8941 // handle them. Since we know the size of the shift has to be less than the
8942 // size of the value, the shift/rotate count is guaranteed to be zero.
8943 if (VT == MVT::i1)
8944 return N1;
8945 if (N2CV && N2CV->isZero())
8946 return N1;
8947 break;
8948 case ISD::FP_ROUND:
8950 VT.bitsLE(N1.getValueType()) && N2C &&
8951 (N2C->getZExtValue() == 0 || N2C->getZExtValue() == 1) &&
8952 N2.getOpcode() == ISD::TargetConstant && "Invalid FP_ROUND!");
8953 if (N1.getValueType() == VT) return N1; // noop conversion.
8954 break;
8955 case ISD::IS_FPCLASS: {
8957 "IS_FPCLASS is used for a non-floating type");
8958 assert(isa<ConstantSDNode>(N2) && "FPClassTest is not Constant");
8959 // is.fpclass(poison, mask) -> poison
8960 if (N1.getOpcode() == ISD::POISON)
8961 return getPOISON(VT);
8962 FPClassTest Mask = static_cast<FPClassTest>(N2->getAsZExtVal());
8963 // If all tests are made, it doesn't matter what the value is.
8964 if ((Mask & fcAllFlags) == fcAllFlags)
8965 return getBoolConstant(true, DL, VT, N1.getValueType());
8966 if ((Mask & fcAllFlags) == 0)
8967 return getBoolConstant(false, DL, VT, N1.getValueType());
8968 break;
8969 }
8970 case ISD::AssertNoFPClass: {
8972 "AssertNoFPClass is used for a non-floating type");
8973 assert(isa<ConstantSDNode>(N2) && "NoFPClass is not Constant");
8974 FPClassTest NoFPClass = static_cast<FPClassTest>(N2->getAsZExtVal());
8975 assert(llvm::to_underlying(NoFPClass) <=
8977 "FPClassTest value too large");
8978 (void)NoFPClass;
8979 break;
8980 }
8981 case ISD::AssertSext:
8982 case ISD::AssertZext: {
8983 EVT EVT = cast<VTSDNode>(N2)->getVT();
8984 assert(VT == N1.getValueType() && "Not an inreg extend!");
8985 assert(VT.isInteger() && EVT.isInteger() &&
8986 "Cannot *_EXTEND_INREG FP types");
8987 assert(!EVT.isVector() &&
8988 "AssertSExt/AssertZExt type should be the vector element type "
8989 "rather than the vector type!");
8990 assert(EVT.bitsLE(VT.getScalarType()) && "Not extending!");
8991 if (VT.getScalarType() == EVT) return N1; // noop assertion.
8992 break;
8993 }
8995 EVT EVT = cast<VTSDNode>(N2)->getVT();
8996 assert(VT == N1.getValueType() && "Not an inreg extend!");
8997 assert(VT.isInteger() && EVT.isInteger() &&
8998 "Cannot *_EXTEND_INREG FP types");
8999 assert(EVT.isVector() == VT.isVector() &&
9000 "SIGN_EXTEND_INREG type should be vector iff the operand "
9001 "type is vector!");
9002 assert((!EVT.isVector() ||
9004 "Vector element counts must match in SIGN_EXTEND_INREG");
9005 assert(EVT.getScalarType().bitsLE(VT.getScalarType()) && "Not extending!");
9006 if (EVT == VT) return N1; // Not actually extending
9007 break;
9008 }
9010 case ISD::FP_TO_UINT_SAT: {
9011 assert(VT.isInteger() && cast<VTSDNode>(N2)->getVT().isInteger() &&
9012 N1.getValueType().isFloatingPoint() && "Invalid FP_TO_*INT_SAT");
9013 assert(N1.getValueType().isVector() == VT.isVector() &&
9014 "FP_TO_*INT_SAT type should be vector iff the operand type is "
9015 "vector!");
9016 assert((!VT.isVector() || VT.getVectorElementCount() ==
9018 "Vector element counts must match in FP_TO_*INT_SAT");
9019 assert(!cast<VTSDNode>(N2)->getVT().isVector() &&
9020 "Type to saturate to must be a scalar.");
9021 assert(cast<VTSDNode>(N2)->getVT().bitsLE(VT.getScalarType()) &&
9022 "Not extending!");
9023 break;
9024 }
9027 "The result of EXTRACT_VECTOR_ELT must be at least as wide as the \
9028 element type of the vector.");
9029
9030 // Extract from an undefined value or using an undefined index is undefined.
9031 if (N1.isUndef() || N2.isUndef())
9032 return getUNDEF(VT);
9033
9034 // EXTRACT_VECTOR_ELT of out-of-bounds element is POISON for fixed length
9035 // vectors. For scalable vectors we will provide appropriate support for
9036 // dealing with arbitrary indices.
9037 if (N2C && N1.getValueType().isFixedLengthVector() &&
9038 N2C->getAPIntValue().uge(N1.getValueType().getVectorNumElements()))
9039 return getPOISON(VT);
9040
9041 // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
9042 // expanding copies of large vectors from registers. This only works for
9043 // fixed length vectors, since we need to know the exact number of
9044 // elements.
9045 if (N2C && N1.getOpcode() == ISD::CONCAT_VECTORS &&
9047 unsigned Factor = N1.getOperand(0).getValueType().getVectorNumElements();
9048 return getExtractVectorElt(DL, VT,
9049 N1.getOperand(N2C->getZExtValue() / Factor),
9050 N2C->getZExtValue() % Factor);
9051 }
9052
9053 // EXTRACT_VECTOR_ELT of BUILD_VECTOR or SPLAT_VECTOR is often formed while
9054 // lowering is expanding large vector constants.
9055 if (N2C && (N1.getOpcode() == ISD::BUILD_VECTOR ||
9056 N1.getOpcode() == ISD::SPLAT_VECTOR)) {
9059 "BUILD_VECTOR used for scalable vectors");
9060 unsigned Index =
9061 N1.getOpcode() == ISD::BUILD_VECTOR ? N2C->getZExtValue() : 0;
9062 SDValue Elt = N1.getOperand(Index);
9063
9064 if (VT != Elt.getValueType())
9065 // If the vector element type is not legal, the BUILD_VECTOR operands
9066 // are promoted and implicitly truncated, and the result implicitly
9067 // extended. Make that explicit here.
9068 Elt = getAnyExtOrTrunc(Elt, DL, VT);
9069
9070 return Elt;
9071 }
9072
9073 // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
9074 // operations are lowered to scalars.
9075 if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) {
9076 // If the indices are the same, return the inserted element else
9077 // if the indices are known different, extract the element from
9078 // the original vector.
9079 SDValue N1Op2 = N1.getOperand(2);
9081
9082 if (N1Op2C && N2C) {
9083 if (N1Op2C->getZExtValue() == N2C->getZExtValue()) {
9084 if (VT == N1.getOperand(1).getValueType())
9085 return N1.getOperand(1);
9086 if (VT.isFloatingPoint()) {
9088 return getFPExtendOrRound(N1.getOperand(1), DL, VT);
9089 }
9090 return getSExtOrTrunc(N1.getOperand(1), DL, VT);
9091 }
9092 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2);
9093 }
9094 }
9095
9096 // EXTRACT_VECTOR_ELT of v1iX EXTRACT_SUBVECTOR could be formed
9097 // when vector types are scalarized and v1iX is legal.
9098 // vextract (v1iX extract_subvector(vNiX, Idx)) -> vextract(vNiX,Idx).
9099 // Here we are completely ignoring the extract element index (N2),
9100 // which is fine for fixed width vectors, since any index other than 0
9101 // is undefined anyway. However, this cannot be ignored for scalable
9102 // vectors - in theory we could support this, but we don't want to do this
9103 // without a profitability check.
9104 if (N1.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
9106 N1.getValueType().getVectorNumElements() == 1) {
9107 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0),
9108 N1.getOperand(1));
9109 }
9110 break;
9112 assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!");
9113 assert(!N1.getValueType().isVector() && !VT.isVector() &&
9114 (N1.getValueType().isInteger() == VT.isInteger()) &&
9115 N1.getValueType() != VT &&
9116 "Wrong types for EXTRACT_ELEMENT!");
9117
9118 // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
9119 // 64-bit integers into 32-bit parts. Instead of building the extract of
9120 // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
9121 if (N1.getOpcode() == ISD::BUILD_PAIR)
9122 return N1.getOperand(N2C->getZExtValue());
9123
9124 // EXTRACT_ELEMENT of a constant int is also very common.
9125 if (N1C) {
9126 unsigned ElementSize = VT.getSizeInBits();
9127 unsigned Shift = ElementSize * N2C->getZExtValue();
9128 const APInt &Val = N1C->getAPIntValue();
9129 return getConstant(Val.extractBits(ElementSize, Shift), DL, VT);
9130 }
9131 break;
9133 [[maybe_unused]] EVT MaskVT = N2.getValueType();
9134 assert(VT == N1.getValueType() &&
9135 "VECTOR_SHUFFLE_VAR result and source types don't match.");
9136 assert(VT.isVector() && MaskVT.isVector() &&
9137 "VECTOR_SHUFFLE_VAR operands must be vectors.");
9139 "VECTOR_SHUFFLE_VAR mask must be a vector of integers.");
9141 "VECTOR_SHUFFLE_VAR mask has the wrong number of elements.");
9142 // The only in-range index is 0; any other index gives poison.
9144 return N1;
9145 break;
9146 }
9148 EVT N1VT = N1.getValueType();
9149 assert(VT.isVector() && N1VT.isVector() &&
9150 "Extract subvector VTs must be vectors!");
9152 "Extract subvector VTs must have the same element type!");
9153 assert((VT.isFixedLengthVector() || N1VT.isScalableVector()) &&
9154 "Cannot extract a scalable vector from a fixed length vector!");
9155 assert((VT.isScalableVector() != N1VT.isScalableVector() ||
9157 "Extract subvector must be from larger vector to smaller vector!");
9158 assert(N2C && "Extract subvector index must be a constant");
9159 assert((VT.isScalableVector() != N1VT.isScalableVector() ||
9160 (VT.getVectorMinNumElements() + N2C->getZExtValue()) <=
9161 N1VT.getVectorMinNumElements()) &&
9162 "Extract subvector overflow!");
9163 assert(N2C->getAPIntValue().getBitWidth() ==
9164 TLI->getVectorIdxWidth(getDataLayout()) &&
9165 "Constant index for EXTRACT_SUBVECTOR has an invalid size");
9166 assert(N2C->getZExtValue() % VT.getVectorMinNumElements() == 0 &&
9167 "Extract index is not a multiple of the output vector length");
9168
9169 // Trivial extraction.
9170 if (VT == N1VT)
9171 return N1;
9172
9173 // EXTRACT_SUBVECTOR of an UNDEF is an UNDEF.
9174 if (N1.isUndef())
9175 return getUNDEF(VT);
9176
9177 // EXTRACT_SUBVECTOR of CONCAT_VECTOR can be simplified if the pieces of
9178 // the concat have the same type as the extract.
9179 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
9180 VT == N1.getOperand(0).getValueType()) {
9181 unsigned Factor = VT.getVectorMinNumElements();
9182 return N1.getOperand(N2C->getZExtValue() / Factor);
9183 }
9184
9185 // EXTRACT_SUBVECTOR of INSERT_SUBVECTOR is often created
9186 // during shuffle legalization.
9187 if (N1.getOpcode() == ISD::INSERT_SUBVECTOR && N2 == N1.getOperand(2) &&
9188 VT == N1.getOperand(1).getValueType())
9189 return N1.getOperand(1);
9190 break;
9191 }
9192 }
9193
9194 if (N1.getOpcode() == ISD::POISON || N2.getOpcode() == ISD::POISON) {
9195 switch (Opcode) {
9196 case ISD::XOR:
9197 case ISD::ADD:
9198 case ISD::PTRADD:
9199 case ISD::SUB:
9201 case ISD::UDIV:
9202 case ISD::SDIV:
9203 case ISD::UREM:
9204 case ISD::SREM:
9205 case ISD::MUL:
9206 case ISD::AND:
9207 case ISD::SSUBSAT:
9208 case ISD::USUBSAT:
9209 case ISD::UMIN:
9210 case ISD::OR:
9211 case ISD::SADDSAT:
9212 case ISD::UADDSAT:
9213 case ISD::UMAX:
9214 case ISD::SMAX:
9215 case ISD::SMIN:
9216 // fold op(arg1, poison) -> poison, fold op(poison, arg2) -> poison.
9217 return N2.getOpcode() == ISD::POISON ? N2 : N1;
9218 case ISD::ROTL:
9219 case ISD::ROTR:
9220 // fold op(arg1, poison) -> poison, fold op(poison, arg2) -> poison.
9221 // NOTE: N2 ValueType might not match VT.
9222 return getPOISON(VT);
9223 }
9224 }
9225
9226 // Canonicalize an UNDEF to the RHS, even over a constant.
9227 if (N1.getOpcode() == ISD::UNDEF && N2.getOpcode() != ISD::UNDEF) {
9228 if (TLI->isCommutativeBinOp(Opcode)) {
9229 std::swap(N1, N2);
9230 } else {
9231 switch (Opcode) {
9232 case ISD::PTRADD:
9233 case ISD::ROTL:
9234 case ISD::ROTR:
9235 case ISD::SUB:
9236 // fold op(undef, non_undef_arg2) -> undef.
9237 return N1;
9239 case ISD::UDIV:
9240 case ISD::SDIV:
9241 case ISD::UREM:
9242 case ISD::SREM:
9243 case ISD::SSUBSAT:
9244 case ISD::USUBSAT:
9245 // fold op(undef, non_undef_arg2) -> 0.
9246 return getConstant(0, DL, VT);
9247 }
9248 }
9249 }
9250
9251 // Fold a bunch of operators when the RHS is undef.
9252 if (N2.getOpcode() == ISD::UNDEF) {
9253 switch (Opcode) {
9254 case ISD::XOR:
9255 if (N1.getOpcode() == ISD::UNDEF)
9256 // Handle undef ^ undef -> 0 special case. This is a common
9257 // idiom (misuse).
9258 return getConstant(0, DL, VT);
9259 [[fallthrough]];
9260 case ISD::ADD:
9261 case ISD::PTRADD:
9262 case ISD::SUB:
9263 // fold op(arg1, undef) -> undef.
9264 return N2;
9265 case ISD::UDIV:
9266 case ISD::SDIV:
9267 case ISD::UREM:
9268 case ISD::SREM:
9269 // fold op(arg1, undef) -> poison.
9270 return getPOISON(VT);
9271 case ISD::ROTL:
9272 case ISD::ROTR:
9273 // fold op(arg1, undef) -> arg1.
9274 return N1;
9275 case ISD::MUL:
9276 case ISD::AND:
9277 case ISD::SSUBSAT:
9278 case ISD::USUBSAT:
9279 case ISD::UMIN:
9280 // fold op(undef, undef) -> undef, fold op(arg1, undef) -> 0.
9281 return N1.getOpcode() == ISD::UNDEF ? N2 : getConstant(0, DL, VT);
9282 case ISD::OR:
9283 case ISD::SADDSAT:
9284 case ISD::UADDSAT:
9285 case ISD::UMAX:
9286 // fold op(undef, undef) -> undef, fold op(arg1, undef) -> -1.
9287 return N1.getOpcode() == ISD::UNDEF ? N2 : getAllOnesConstant(DL, VT);
9288 case ISD::SMAX:
9289 // fold op(undef, undef) -> undef, fold op(arg1, undef) -> MAX_INT.
9290 return N1.getOpcode() == ISD::UNDEF
9291 ? N2
9292 : getConstant(
9294 VT);
9295 case ISD::SMIN:
9296 // fold op(undef, undef) -> undef, fold op(arg1, undef) -> MIN_INT.
9297 return N1.getOpcode() == ISD::UNDEF
9298 ? N2
9299 : getConstant(
9301 VT);
9302 }
9303 }
9304
9305 // Perform trivial constant folding.
9306 if (SDValue SV = FoldConstantArithmetic(Opcode, DL, VT, {N1, N2}, Flags))
9307 return SV;
9308
9309 // Memoize this node if possible.
9310 SDNode *N;
9311 SDVTList VTs = getVTList(VT);
9312 SDValue Ops[] = {N1, N2};
9313 if (VT != MVT::Glue) {
9314 SDNodeKey ID(Opcode, VTs, Ops);
9315 FoldingSetInsertToken InsertToken;
9316 if (SDNode *E = lookupNode(ID, DL, InsertToken)) {
9317 E->intersectFlagsWith(Flags);
9318 return SDValue(E, 0);
9319 }
9320
9321 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
9322 N->setFlags(Flags);
9323 createOperands(N, Ops);
9324 CSEMap.insert(N, InsertToken);
9325 } else {
9326 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
9327 createOperands(N, Ops);
9328 }
9329
9330 InsertNode(N);
9331 SDValue V = SDValue(N, 0);
9332 NewSDValueDbgMsg(V, "Creating new node: ", this);
9333 return V;
9334}
9335
9336SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
9337 SDValue N1, SDValue N2, SDValue N3) {
9338 SDNodeFlags Flags;
9339 if (Inserter)
9340 Flags = Inserter->getFlags();
9341 return getNode(Opcode, DL, VT, N1, N2, N3, Flags);
9342}
9343
9344SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
9345 SDValue N1, SDValue N2, SDValue N3,
9346 const SDNodeFlags Flags) {
9348 N2.getOpcode() != ISD::DELETED_NODE &&
9349 N3.getOpcode() != ISD::DELETED_NODE &&
9350 "Operand is DELETED_NODE!");
9351 // Perform various simplifications.
9352 switch (Opcode) {
9353 case ISD::BUILD_VECTOR: {
9354 // Attempt to simplify BUILD_VECTOR.
9355 SDValue Ops[] = {N1, N2, N3};
9356 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
9357 return V;
9358 break;
9359 }
9360 case ISD::CONCAT_VECTORS: {
9361 SDValue Ops[] = {N1, N2, N3};
9362 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
9363 return V;
9364 break;
9365 }
9366 case ISD::SETCC: {
9367 assert(VT.isInteger() && "SETCC result type must be an integer!");
9368 assert(N1.getValueType() == N2.getValueType() &&
9369 "SETCC operands must have the same type!");
9370 assert(VT.isVector() == N1.getValueType().isVector() &&
9371 "SETCC type should be vector iff the operand type is vector!");
9372 assert((!VT.isVector() || VT.getVectorElementCount() ==
9374 "SETCC vector element counts must match!");
9375 // Use FoldSetCC to simplify SETCC's.
9376 if (SDValue V =
9377 FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL, Flags))
9378 return V;
9379 break;
9380 }
9381 case ISD::SELECT:
9382 case ISD::VSELECT:
9383 if (SDValue V = simplifySelect(N1, N2, N3))
9384 return V;
9385 break;
9387 llvm_unreachable("should use getVectorShuffle constructor!");
9389 if (isNullConstant(N3))
9390 return N1;
9391 break;
9393 if (isNullConstant(N3))
9394 return N2;
9395 break;
9397 assert(VT.isVector() && VT == N1.getValueType() &&
9398 "INSERT_VECTOR_ELT vector type mismatch");
9400 "INSERT_VECTOR_ELT scalar fp/int mismatch");
9401 assert((!VT.isFloatingPoint() ||
9402 VT.getVectorElementType() == N2.getValueType()) &&
9403 "INSERT_VECTOR_ELT fp scalar type mismatch");
9404 assert((!VT.isInteger() ||
9406 "INSERT_VECTOR_ELT int scalar size mismatch");
9407
9408 auto *N3C = dyn_cast<ConstantSDNode>(N3);
9409 // INSERT_VECTOR_ELT into out-of-bounds element is an UNDEF, except
9410 // for scalable vectors where we will generate appropriate code to
9411 // deal with out-of-bounds cases correctly.
9412 if (N3C && VT.isFixedLengthVector() &&
9413 N3C->getZExtValue() >= VT.getVectorNumElements())
9414 return getUNDEF(VT);
9415
9416 // Undefined index can be assumed out-of-bounds, so that's UNDEF too.
9417 if (N3.isUndef())
9418 return getUNDEF(VT);
9419
9420 // If inserting poison, just use the input vector.
9421 if (N2.getOpcode() == ISD::POISON)
9422 return N1;
9423
9424 // Inserting undef into undef/poison is still undef.
9425 if (N2.getOpcode() == ISD::UNDEF && N1.isUndef())
9426 return getUNDEF(VT);
9427
9428 // If the inserted element is an UNDEF, just use the input vector.
9429 // But not if skipping the insert could make the result more poisonous.
9430 if (N2.isUndef()) {
9431 if (N3C && VT.isFixedLengthVector()) {
9432 APInt EltMask =
9433 APInt::getOneBitSet(VT.getVectorNumElements(), N3C->getZExtValue());
9434 if (isGuaranteedNotToBePoison(N1, EltMask))
9435 return N1;
9436 } else if (isGuaranteedNotToBePoison(N1))
9437 return N1;
9438 }
9439 break;
9440 }
9441 case ISD::INSERT_SUBVECTOR: {
9442 // If inserting poison, just use the input vector,
9443 if (N2.getOpcode() == ISD::POISON)
9444 return N1;
9445
9446 // Inserting undef into undef/poison is still undef.
9447 if (N2.getOpcode() == ISD::UNDEF && N1.isUndef())
9448 return getUNDEF(VT);
9449
9450 EVT N2VT = N2.getValueType();
9451 assert(VT == N1.getValueType() &&
9452 "Dest and insert subvector source types must match!");
9453 assert(VT.isVector() && N2VT.isVector() &&
9454 "Insert subvector VTs must be vectors!");
9456 "Insert subvector VTs must have the same element type!");
9457 assert((VT.isScalableVector() || N2VT.isFixedLengthVector()) &&
9458 "Cannot insert a scalable vector into a fixed length vector!");
9459 assert((VT.isScalableVector() != N2VT.isScalableVector() ||
9461 "Insert subvector must be from smaller vector to larger vector!");
9463 "Insert subvector index must be constant");
9464 assert((VT.isScalableVector() != N2VT.isScalableVector() ||
9465 (N2VT.getVectorMinNumElements() + N3->getAsZExtVal()) <=
9467 "Insert subvector overflow!");
9469 TLI->getVectorIdxWidth(getDataLayout()) &&
9470 "Constant index for INSERT_SUBVECTOR has an invalid size");
9471
9472 // Trivial insertion.
9473 if (VT == N2VT)
9474 return N2;
9475
9476 // If this is an insert of an extracted vector into an undef/poison vector,
9477 // we can just use the input to the extract. But not if skipping the
9478 // extract+insert could make the result more poisonous.
9479 if (N1.isUndef() && N2.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
9480 N2.getOperand(1) == N3 && N2.getOperand(0).getValueType() == VT) {
9481 if (N1.getOpcode() == ISD::POISON)
9482 return N2.getOperand(0);
9483 if (VT.isFixedLengthVector() && N2VT.isFixedLengthVector()) {
9484 unsigned LoBit = N3->getAsZExtVal();
9485 unsigned HiBit = LoBit + N2VT.getVectorNumElements();
9486 APInt EltMask =
9487 APInt::getBitsSet(VT.getVectorNumElements(), LoBit, HiBit);
9488 if (isGuaranteedNotToBePoison(N2.getOperand(0), ~EltMask))
9489 return N2.getOperand(0);
9490 } else if (isGuaranteedNotToBePoison(N2.getOperand(0)))
9491 return N2.getOperand(0);
9492 }
9493
9494 // If the inserted subvector is UNDEF, just use the input vector.
9495 // But not if skipping the insert could make the result more poisonous.
9496 if (N2.isUndef()) {
9497 if (VT.isFixedLengthVector()) {
9498 unsigned LoBit = N3->getAsZExtVal();
9499 unsigned HiBit = LoBit + N2VT.getVectorNumElements();
9500 APInt EltMask =
9501 APInt::getBitsSet(VT.getVectorNumElements(), LoBit, HiBit);
9502 if (isGuaranteedNotToBePoison(N1, EltMask))
9503 return N1;
9504 } else if (isGuaranteedNotToBePoison(N1))
9505 return N1;
9506 }
9507 break;
9508 }
9509 case ISD::BITCAST:
9510 // Fold bit_convert nodes from a type to themselves.
9511 if (N1.getValueType() == VT)
9512 return N1;
9513 break;
9514 case ISD::VECTOR_COMPRESS: {
9515 [[maybe_unused]] EVT VecVT = N1.getValueType();
9516 [[maybe_unused]] EVT MaskVT = N2.getValueType();
9517 [[maybe_unused]] EVT PassthruVT = N3.getValueType();
9518 assert(VT == VecVT && "Vector and result type don't match.");
9519 assert(VecVT.isVector() && MaskVT.isVector() && PassthruVT.isVector() &&
9520 "All inputs must be vectors.");
9521 assert(VecVT == PassthruVT && "Vector and passthru types don't match.");
9523 "Vector and mask must have same number of elements.");
9524
9525 if (N1.isUndef() || N2.isUndef())
9526 return N3;
9527
9528 break;
9529 }
9534 [[maybe_unused]] EVT AccVT = N1.getValueType();
9535 [[maybe_unused]] EVT Input1VT = N2.getValueType();
9536 [[maybe_unused]] EVT Input2VT = N3.getValueType();
9537 assert(Input1VT.isVector() && Input1VT == Input2VT &&
9538 "Expected the second and third operands of the PARTIAL_REDUCE_MLA "
9539 "node to have the same type!");
9540 assert(VT.isVector() && VT == AccVT &&
9541 "Expected the first operand of the PARTIAL_REDUCE_MLA node to have "
9542 "the same type as its result!");
9544 AccVT.getVectorElementCount()) &&
9545 "Expected the element count of the second and third operands of the "
9546 "PARTIAL_REDUCE_MLA node to be a positive integer multiple of the "
9547 "element count of the first operand and the result!");
9549 "Expected the second and third operands of the PARTIAL_REDUCE_MLA "
9550 "node to have an element type which is the same as or smaller than "
9551 "the element type of the first operand and result!");
9552 break;
9553 }
9554 }
9555
9556 // Perform trivial constant folding for arithmetic operators.
9557 switch (Opcode) {
9561 case ISD::FMA:
9562 case ISD::FMAD:
9563 case ISD::SETCC:
9564 case ISD::FSHL:
9565 case ISD::FSHR:
9566 if (SDValue SV =
9567 FoldConstantArithmetic(Opcode, DL, VT, {N1, N2, N3}, Flags))
9568 return SV;
9569 break;
9570 }
9571
9572 // Memoize node if it doesn't produce a glue result.
9573 SDNode *N;
9574 SDVTList VTs = getVTList(VT);
9575 SDValue Ops[] = {N1, N2, N3};
9576 if (VT != MVT::Glue) {
9577 SDNodeKey ID(Opcode, VTs, Ops);
9578 FoldingSetInsertToken InsertToken;
9579 if (SDNode *E = lookupNode(ID, DL, InsertToken)) {
9580 E->intersectFlagsWith(Flags);
9581 return SDValue(E, 0);
9582 }
9583
9584 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
9585 N->setFlags(Flags);
9586 createOperands(N, Ops);
9587 CSEMap.insert(N, InsertToken);
9588 } else {
9589 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
9590 createOperands(N, Ops);
9591 }
9592
9593 InsertNode(N);
9594 SDValue V = SDValue(N, 0);
9595 NewSDValueDbgMsg(V, "Creating new node: ", this);
9596 return V;
9597}
9598
9599SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
9600 SDValue N1, SDValue N2, SDValue N3, SDValue N4,
9601 const SDNodeFlags Flags) {
9602 SDValue Ops[] = { N1, N2, N3, N4 };
9603 return getNode(Opcode, DL, VT, Ops, Flags);
9604}
9605
9606SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
9607 SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
9608 SDNodeFlags Flags;
9609 if (Inserter)
9610 Flags = Inserter->getFlags();
9611 return getNode(Opcode, DL, VT, N1, N2, N3, N4, Flags);
9612}
9613
9614SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
9615 SDValue N1, SDValue N2, SDValue N3, SDValue N4,
9616 SDValue N5, const SDNodeFlags Flags) {
9617 SDValue Ops[] = { N1, N2, N3, N4, N5 };
9618 return getNode(Opcode, DL, VT, Ops, Flags);
9619}
9620
9621SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
9622 SDValue N1, SDValue N2, SDValue N3, SDValue N4,
9623 SDValue N5) {
9624 SDNodeFlags Flags;
9625 if (Inserter)
9626 Flags = Inserter->getFlags();
9627 return getNode(Opcode, DL, VT, N1, N2, N3, N4, N5, Flags);
9628}
9629
9630/// getStackArgumentTokenFactor - Compute a TokenFactor to force all
9631/// the incoming stack arguments to be loaded from the stack.
9633 SmallVector<SDValue, 8> ArgChains;
9634
9635 // Include the original chain at the beginning of the list. When this is
9636 // used by target LowerCall hooks, this helps legalize find the
9637 // CALLSEQ_BEGIN node.
9638 ArgChains.push_back(Chain);
9639
9640 // Add a chain value for each stack argument.
9641 for (SDNode *U : getEntryNode().getNode()->users())
9642 if (LoadSDNode *L = dyn_cast<LoadSDNode>(U))
9643 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
9644 if (FI->getIndex() < 0)
9645 ArgChains.push_back(SDValue(L, 1));
9646
9647 // Build a tokenfactor for all the chains.
9648 return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
9649}
9650
9651/// getMemsetValue - Vectorized representation of the memset value
9652/// operand.
9654 const SDLoc &dl) {
9655 assert(!Value.isUndef());
9656
9657 unsigned NumBits = VT.getScalarSizeInBits();
9659 assert(C->getAPIntValue().getBitWidth() == 8);
9660 APInt Val = APInt::getSplat(NumBits, C->getAPIntValue());
9661 if (VT.isInteger()) {
9662 bool IsOpaque = VT.getSizeInBits() > 64 ||
9663 !DAG.getTargetLoweringInfo().isLegalStoreImmediate(C->getSExtValue());
9664 return DAG.getConstant(Val, dl, VT, false, IsOpaque);
9665 }
9666 return DAG.getConstantFP(APFloat(VT.getFltSemantics(), Val), dl, VT);
9667 }
9668
9669 assert(Value.getValueType() == MVT::i8 && "memset with non-byte fill value?");
9670 EVT IntVT = VT.getScalarType();
9671 if (!IntVT.isInteger())
9672 IntVT = EVT::getIntegerVT(*DAG.getContext(), IntVT.getSizeInBits());
9673
9674 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, Value);
9675 if (NumBits > 8) {
9676 // Use a multiplication with 0x010101... to extend the input to the
9677 // required length.
9678 APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01));
9679 Value = DAG.getNode(ISD::MUL, dl, IntVT, Value,
9680 DAG.getConstant(Magic, dl, IntVT));
9681 }
9682
9683 if (VT != Value.getValueType() && !VT.isInteger())
9684 Value = DAG.getBitcast(VT.getScalarType(), Value);
9685 if (VT != Value.getValueType())
9686 Value = DAG.getSplatBuildVector(VT, dl, Value);
9687
9688 return Value;
9689}
9690
9691/// getMemsetStringVal - Similar to getMemsetValue. Except this is only
9692/// used when a memcpy is turned into a memset when the source is a constant
9693/// string ptr.
9695 const TargetLowering &TLI,
9696 const ConstantDataArraySlice &Slice) {
9697 // Handle vector with all elements zero.
9698 if (Slice.Array == nullptr) {
9699 if (VT.isInteger())
9700 return DAG.getConstant(0, dl, VT);
9701 return DAG.getNode(ISD::BITCAST, dl, VT,
9702 DAG.getConstant(0, dl, VT.changeTypeToInteger()));
9703 }
9704
9705 assert(!VT.isVector() && "Can't handle vector type here!");
9706 unsigned NumVTBits = VT.getSizeInBits();
9707 unsigned NumVTBytes = NumVTBits / 8;
9708 unsigned NumBytes = std::min(NumVTBytes, unsigned(Slice.Length));
9709
9710 APInt Val(NumVTBits, 0);
9711 if (DAG.getDataLayout().isLittleEndian()) {
9712 for (unsigned i = 0; i != NumBytes; ++i)
9713 Val |= (uint64_t)(unsigned char)Slice[i] << i*8;
9714 } else {
9715 for (unsigned i = 0; i != NumBytes; ++i)
9716 Val |= (uint64_t)(unsigned char)Slice[i] << (NumVTBytes-i-1)*8;
9717 }
9718
9719 // If the "cost" of materializing the integer immediate is less than the cost
9720 // of a load, then it is cost effective to turn the load into the immediate.
9721 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
9722 if (TLI.shouldConvertConstantLoadToIntImm(Val, Ty))
9723 return DAG.getConstant(Val, dl, VT);
9724 return SDValue();
9725}
9726
9728 const SDLoc &DL,
9729 const SDNodeFlags Flags) {
9730 SDValue Index = getTypeSize(DL, Base.getValueType(), Offset);
9731 return getMemBasePlusOffset(Base, Index, DL, Flags);
9732}
9733
9735 const SDLoc &DL,
9736 const SDNodeFlags Flags) {
9737 assert(Offset.getValueType().isInteger());
9738 EVT BasePtrVT = Ptr.getValueType();
9739 if (TLI->shouldPreservePtrArith(this->getMachineFunction().getFunction(),
9740 BasePtrVT))
9741 return getNode(ISD::PTRADD, DL, BasePtrVT, Ptr, Offset, Flags);
9742 // InBounds only applies to PTRADD, don't set it if we generate ADD.
9743 SDNodeFlags AddFlags = Flags;
9744 AddFlags.setInBounds(false);
9745 return getNode(ISD::ADD, DL, BasePtrVT, Ptr, Offset, AddFlags);
9746}
9747
9748/// Returns true if memcpy source is constant data.
9750 uint64_t SrcDelta = 0;
9751 GlobalAddressSDNode *G = nullptr;
9752 if (Src.getOpcode() == ISD::GlobalAddress)
9754 else if (Src->isAnyAdd() &&
9755 Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
9756 Src.getOperand(1).getOpcode() == ISD::Constant) {
9757 G = cast<GlobalAddressSDNode>(Src.getOperand(0));
9758 SrcDelta = Src.getConstantOperandVal(1);
9759 }
9760 if (!G)
9761 return false;
9762
9763 return getConstantDataArrayInfo(G->getGlobal(), Slice, 8,
9764 SrcDelta + G->getOffset());
9765}
9766
9768 SelectionDAG &DAG) {
9769 // On Darwin, -Os means optimize for size without hurting performance, so
9770 // only really optimize for size when -Oz (MinSize) is used.
9772 return MF.getFunction().hasMinSize();
9773 return DAG.shouldOptForSize();
9774}
9775
9777 SmallVector<SDValue, 32> &OutChains, unsigned From,
9778 unsigned To, SmallVector<SDValue, 16> &OutLoadChains,
9779 SmallVector<SDValue, 16> &OutStoreChains) {
9780 assert(OutLoadChains.size() && "Missing loads in memcpy inlining");
9781 assert(OutStoreChains.size() && "Missing stores in memcpy inlining");
9782 SmallVector<SDValue, 16> GluedLoadChains;
9783 for (unsigned i = From; i < To; ++i) {
9784 OutChains.push_back(OutLoadChains[i]);
9785 GluedLoadChains.push_back(OutLoadChains[i]);
9786 }
9787
9788 // Chain for all loads.
9789 SDValue LoadToken = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
9790 GluedLoadChains);
9791
9792 for (unsigned i = From; i < To; ++i) {
9793 StoreSDNode *ST = dyn_cast<StoreSDNode>(OutStoreChains[i]);
9794 SDValue NewStore = DAG.getTruncStore(LoadToken, dl, ST->getValue(),
9795 ST->getBasePtr(), ST->getMemoryVT(),
9796 ST->getMemOperand());
9797 OutChains.push_back(NewStore);
9798 }
9799}
9800
9801static SDValue
9803 SDValue Dst, SDValue Src, uint64_t Size, Align DstAlign,
9804 Align SrcAlign, bool isVol, bool AlwaysInline,
9805 MachinePointerInfo DstPtrInfo,
9806 MachinePointerInfo SrcPtrInfo, const AAMDNodes &AAInfo,
9807 BatchAAResults *BatchAA, const MDNode *DstMemCacheHint,
9808 const MDNode *SrcMemCacheHint) {
9809 // Turn a memcpy of undef to nop.
9810 // FIXME: We need to honor volatile even is Src is undef.
9811 if (Src.isUndef())
9812 return Chain;
9813
9814 // Expand memcpy to a series of load and store ops if the size operand falls
9815 // below a certain threshold.
9816 // TODO: In the AlwaysInline case, if the size is big then generate a loop
9817 // rather than maybe a humongous number of loads and stores.
9819 const DataLayout &DL = DAG.getDataLayout();
9820 LLVMContext &C = *DAG.getContext();
9821 std::vector<EVT> MemOps;
9822 bool DstAlignCanChange = false;
9824 MachineFrameInfo &MFI = MF.getFrameInfo();
9825 bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
9827 if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
9828 DstAlignCanChange = true;
9829 SrcAlign = std::max(SrcAlign, DAG.InferPtrAlign(Src).valueOrOne());
9831 // If marked as volatile, perform a copy even when marked as constant.
9832 bool CopyFromConstant = !isVol && isMemSrcFromConstant(Src, Slice);
9833 bool isZeroConstant = CopyFromConstant && Slice.Array == nullptr;
9834 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize);
9835 const MemOp Op = isZeroConstant
9836 ? MemOp::Set(Size, DstAlignCanChange, DstAlign,
9837 /*IsZeroMemset*/ true, isVol)
9838 : MemOp::Copy(Size, DstAlignCanChange, DstAlign,
9839 SrcAlign, isVol, CopyFromConstant);
9840 if (!TLI.findOptimalMemOpLowering(
9841 C, MemOps, Limit, Op, DstPtrInfo.getAddrSpace(),
9842 SrcPtrInfo.getAddrSpace(), MF.getFunction().getAttributes(), nullptr))
9843 return SDValue();
9844
9845 if (DstAlignCanChange) {
9846 Type *Ty = MemOps[0].getTypeForEVT(C);
9847 Align NewDstAlign = DL.getABITypeAlign(Ty);
9848
9849 // Don't promote to an alignment that would require dynamic stack
9850 // realignment which may conflict with optimizations such as tail call
9851 // optimization.
9853 if (!TRI->hasStackRealignment(MF))
9854 if (MaybeAlign StackAlign = DL.getStackAlignment())
9855 NewDstAlign = std::min(NewDstAlign, *StackAlign);
9856
9857 if (NewDstAlign > DstAlign) {
9858 // Give the stack frame object a larger alignment if needed.
9859 if (MFI.getObjectAlign(FI->getIndex()) < NewDstAlign)
9860 MFI.setObjectAlignment(FI->getIndex(), NewDstAlign);
9861 DstAlign = NewDstAlign;
9862 }
9863 }
9864
9865 // Prepare AAInfo for loads/stores after lowering this memcpy.
9866 AAMDNodes NewAAInfo = AAInfo;
9867 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
9868
9869 const Value *SrcVal = dyn_cast_if_present<const Value *>(SrcPtrInfo.V);
9870 bool isConstant =
9871 BatchAA && SrcVal &&
9872 BatchAA->pointsToConstantMemory(MemoryLocation(SrcVal, Size, AAInfo));
9873
9874 MachineMemOperand::Flags MMOFlags =
9876 SmallVector<SDValue, 16> OutLoadChains;
9877 SmallVector<SDValue, 16> OutStoreChains;
9878 SmallVector<SDValue, 32> OutChains;
9879 unsigned NumMemOps = MemOps.size();
9880 uint64_t SrcOff = 0, DstOff = 0;
9881 for (unsigned i = 0; i != NumMemOps; ++i) {
9882 EVT VT = MemOps[i];
9883 unsigned VTSize = VT.getSizeInBits() / 8;
9885
9886 if (VTSize > Size) {
9887 // Issuing an unaligned load / store pair that overlaps with the previous
9888 // pair. Adjust the offset accordingly.
9889 assert(i == NumMemOps-1 && i != 0);
9890 SrcOff -= VTSize - Size;
9891 DstOff -= VTSize - Size;
9892 }
9893
9894 if (CopyFromConstant &&
9895 (isZeroConstant || (VT.isInteger() && !VT.isVector()))) {
9896 // It's unlikely a store of a vector immediate can be done in a single
9897 // instruction. It would require a load from a constantpool first.
9898 // We only handle zero vectors here.
9899 // FIXME: Handle other cases where store of vector immediate is done in
9900 // a single instruction.
9901 ConstantDataArraySlice SubSlice;
9902 if (SrcOff < Slice.Length) {
9903 SubSlice = Slice;
9904 SubSlice.move(SrcOff);
9905 } else {
9906 // This is an out-of-bounds access and hence UB. Pretend we read zero.
9907 SubSlice.Array = nullptr;
9908 SubSlice.Offset = 0;
9909 SubSlice.Length = VTSize;
9910 }
9911 Value = getMemsetStringVal(VT, dl, DAG, TLI, SubSlice);
9912 if (Value.getNode()) {
9913 Store = DAG.getStore(
9914 Chain, dl, Value,
9915 DAG.getObjectPtrOffset(dl, Dst, TypeSize::getFixed(DstOff)),
9916 DstPtrInfo.getWithOffset(DstOff), DstAlign, MMOFlags,
9917 MMOMetadata(NewAAInfo, /*Ranges=*/nullptr, DstMemCacheHint));
9918 OutChains.push_back(Store);
9919 }
9920 }
9921
9922 if (!Store.getNode()) {
9923 // The type might not be legal for the target. This should only happen
9924 // if the type is smaller than a legal type, as on PPC, so the right
9925 // thing to do is generate a LoadExt/StoreTrunc pair. These simplify
9926 // to Load/Store if NVT==VT.
9927 // FIXME does the case above also need this?
9928 EVT NVT = TLI.getTypeToTransformTo(C, VT);
9929 assert(NVT.bitsGE(VT));
9930
9931 bool isDereferenceable =
9932 SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
9933 MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
9934 if (isDereferenceable)
9936 if (isConstant)
9937 SrcMMOFlags |= MachineMemOperand::MOInvariant;
9938
9939 Value = DAG.getExtLoad(
9940 ISD::EXTLOAD, dl, NVT, Chain,
9941 DAG.getObjectPtrOffset(dl, Src, TypeSize::getFixed(SrcOff)),
9942 SrcPtrInfo.getWithOffset(SrcOff), VT,
9943 commonAlignment(SrcAlign, SrcOff), SrcMMOFlags,
9944 MMOMetadata(NewAAInfo, /*Ranges=*/nullptr, SrcMemCacheHint));
9945 OutLoadChains.push_back(Value.getValue(1));
9946
9947 Store = DAG.getTruncStore(
9948 Chain, dl, Value,
9949 DAG.getObjectPtrOffset(dl, Dst, TypeSize::getFixed(DstOff)),
9950 DstPtrInfo.getWithOffset(DstOff), VT, DstAlign, MMOFlags,
9951 MMOMetadata(NewAAInfo, /*Ranges=*/nullptr, DstMemCacheHint));
9952 OutStoreChains.push_back(Store);
9953 }
9954 SrcOff += VTSize;
9955 DstOff += VTSize;
9956 Size -= VTSize;
9957 }
9958
9959 unsigned MaxLdStGlue = DAG.getSelectionDAGOptions().ldstmemcpy_glue_max;
9960 unsigned GluedLdStLimit =
9961 MaxLdStGlue == 0 ? TLI.getMaxGluedStoresPerMemcpy() : MaxLdStGlue;
9962 unsigned NumLdStInMemcpy = OutStoreChains.size();
9963
9964 if (NumLdStInMemcpy) {
9965 // It may be that memcpy might be converted to memset if it's memcpy
9966 // of constants. In such a case, we won't have loads and stores, but
9967 // just stores. In the absence of loads, there is nothing to gang up.
9968 if ((GluedLdStLimit <= 1) ||
9969 !DAG.getSelectionDAGOptions().enable_memcpy_dag_opt) {
9970 // If target does not care, just leave as it.
9971 for (unsigned i = 0; i < NumLdStInMemcpy; ++i) {
9972 OutChains.push_back(OutLoadChains[i]);
9973 OutChains.push_back(OutStoreChains[i]);
9974 }
9975 } else {
9976 // Ld/St less than/equal limit set by target.
9977 if (NumLdStInMemcpy <= GluedLdStLimit) {
9978 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
9979 NumLdStInMemcpy, OutLoadChains,
9980 OutStoreChains);
9981 } else {
9982 unsigned NumberLdChain = NumLdStInMemcpy / GluedLdStLimit;
9983 unsigned RemainingLdStInMemcpy = NumLdStInMemcpy % GluedLdStLimit;
9984 unsigned GlueIter = 0;
9985
9986 // Residual ld/st.
9987 if (RemainingLdStInMemcpy) {
9989 DAG, dl, OutChains, NumLdStInMemcpy - RemainingLdStInMemcpy,
9990 NumLdStInMemcpy, OutLoadChains, OutStoreChains);
9991 }
9992
9993 for (unsigned cnt = 0; cnt < NumberLdChain; ++cnt) {
9994 unsigned IndexFrom = NumLdStInMemcpy - RemainingLdStInMemcpy -
9995 GlueIter - GluedLdStLimit;
9996 unsigned IndexTo = NumLdStInMemcpy - RemainingLdStInMemcpy - GlueIter;
9997 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, IndexFrom, IndexTo,
9998 OutLoadChains, OutStoreChains);
9999 GlueIter += GluedLdStLimit;
10000 }
10001 }
10002 }
10003 }
10004 return DAG.getTokenFactor(dl, OutChains);
10005}
10006
10008 SelectionDAG &DAG, const SDLoc &dl, SDValue Chain, SDValue Dst, SDValue Src,
10009 uint64_t Size, Align DstAlign, Align SrcAlign, bool isVol,
10010 bool AlwaysInline, MachinePointerInfo DstPtrInfo,
10011 MachinePointerInfo SrcPtrInfo, const AAMDNodes &AAInfo) {
10012 // Turn a memmove of undef to nop.
10013 // FIXME: We need to honor volatile even is Src is undef.
10014 if (Src.isUndef())
10015 return Chain;
10016
10017 // Expand memmove to a series of load and store ops if the size operand falls
10018 // below a certain threshold.
10020 const DataLayout &DL = DAG.getDataLayout();
10021 LLVMContext &C = *DAG.getContext();
10022 std::vector<EVT> MemOps;
10023 bool DstAlignCanChange = false;
10025 MachineFrameInfo &MFI = MF.getFrameInfo();
10026 bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
10028 if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
10029 DstAlignCanChange = true;
10030 SrcAlign = std::max(SrcAlign, DAG.InferPtrAlign(Src).valueOrOne());
10031 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize);
10032 if (!TLI.findOptimalMemOpLowering(
10033 C, MemOps, Limit,
10034 MemOp::Move(Size, DstAlignCanChange, DstAlign, SrcAlign, isVol),
10035 DstPtrInfo.getAddrSpace(), SrcPtrInfo.getAddrSpace(),
10036 MF.getFunction().getAttributes(), nullptr))
10037 return SDValue();
10038
10039 if (DstAlignCanChange) {
10040 Type *Ty = MemOps[0].getTypeForEVT(C);
10041 Align NewDstAlign = DL.getABITypeAlign(Ty);
10042
10043 // Don't promote to an alignment that would require dynamic stack
10044 // realignment which may conflict with optimizations such as tail call
10045 // optimization.
10047 if (!TRI->hasStackRealignment(MF))
10048 if (MaybeAlign StackAlign = DL.getStackAlignment())
10049 NewDstAlign = std::min(NewDstAlign, *StackAlign);
10050
10051 if (NewDstAlign > DstAlign) {
10052 // Give the stack frame object a larger alignment if needed.
10053 if (MFI.getObjectAlign(FI->getIndex()) < NewDstAlign)
10054 MFI.setObjectAlignment(FI->getIndex(), NewDstAlign);
10055 DstAlign = NewDstAlign;
10056 }
10057 }
10058
10059 // Prepare AAInfo for loads/stores after lowering this memmove.
10060 AAMDNodes NewAAInfo = AAInfo;
10061 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
10062
10063 MachineMemOperand::Flags MMOFlags =
10065 uint64_t SrcOff = 0;
10066 SmallVector<SDValue, 8> LoadValues;
10067 SmallVector<SDValue, 8> LoadChains;
10068 SmallVector<SDValue, 8> OutChains;
10069 unsigned NumMemOps = MemOps.size();
10070 for (unsigned i = 0; i < NumMemOps; i++) {
10071 EVT VT = MemOps[i];
10072 unsigned VTSize = VT.getSizeInBits() / 8;
10073 SDValue Value;
10074 bool IsOverlapping = false;
10075
10076 if (i == NumMemOps - 1 && i != 0 && VTSize > Size - SrcOff) {
10077 // Issuing an unaligned load / store pair that overlaps with the previous
10078 // pair. Adjust the offset accordingly.
10079 SrcOff = Size - VTSize;
10080 IsOverlapping = true;
10081 }
10082
10083 // Calculate the actual alignment at the current offset. The alignment at
10084 // SrcOff may be lower than the base alignment, especially when using
10085 // overlapping loads.
10086 Align SrcAlignAtOffset = commonAlignment(SrcAlign, SrcOff);
10087 if (IsOverlapping) {
10088 // Verify that the target allows misaligned memory accesses at the
10089 // adjusted offset when using overlapping loads.
10090 unsigned Fast;
10091 if (!TLI.allowsMisalignedMemoryAccesses(VT, SrcPtrInfo.getAddrSpace(),
10092 SrcAlignAtOffset, MMOFlags,
10093 &Fast) ||
10094 !Fast) {
10095 // This should have been caught by findOptimalMemOpLowering, but verify
10096 // here for safety.
10097 return SDValue();
10098 }
10099 }
10100
10101 bool isDereferenceable =
10102 SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
10103 MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
10104 if (isDereferenceable)
10106 Value =
10107 DAG.getLoad(VT, dl, Chain,
10108 DAG.getObjectPtrOffset(dl, Src, TypeSize::getFixed(SrcOff)),
10109 SrcPtrInfo.getWithOffset(SrcOff), SrcAlignAtOffset,
10110 SrcMMOFlags, NewAAInfo);
10111 LoadValues.push_back(Value);
10112 LoadChains.push_back(Value.getValue(1));
10113 SrcOff += VTSize;
10114 }
10115 Chain = DAG.getTokenFactor(dl, LoadChains);
10116 OutChains.clear();
10117 uint64_t DstOff = 0;
10118 for (unsigned i = 0; i < NumMemOps; i++) {
10119 EVT VT = MemOps[i];
10120 unsigned VTSize = VT.getSizeInBits() / 8;
10121 SDValue Store;
10122 bool IsOverlapping = false;
10123
10124 if (i == NumMemOps - 1 && i != 0 && VTSize > Size - DstOff) {
10125 // Issuing an unaligned load / store pair that overlaps with the previous
10126 // pair. Adjust the offset accordingly.
10127 DstOff = Size - VTSize;
10128 IsOverlapping = true;
10129 }
10130
10131 // Calculate the actual alignment at the current offset. The alignment at
10132 // DstOff may be lower than the base alignment, especially when using
10133 // overlapping stores.
10134 Align DstAlignAtOffset = commonAlignment(DstAlign, DstOff);
10135 if (IsOverlapping) {
10136 // Verify that the target allows misaligned memory accesses at the
10137 // adjusted offset when using overlapping stores.
10138 unsigned Fast;
10139 if (!TLI.allowsMisalignedMemoryAccesses(VT, DstPtrInfo.getAddrSpace(),
10140 DstAlignAtOffset, MMOFlags,
10141 &Fast) ||
10142 !Fast) {
10143 // This should have been caught by findOptimalMemOpLowering, but verify
10144 // here for safety.
10145 return SDValue();
10146 }
10147 }
10148 Store = DAG.getStore(
10149 Chain, dl, LoadValues[i],
10150 DAG.getObjectPtrOffset(dl, Dst, TypeSize::getFixed(DstOff)),
10151 DstPtrInfo.getWithOffset(DstOff), DstAlignAtOffset, MMOFlags,
10152 NewAAInfo);
10153 OutChains.push_back(Store);
10154 DstOff += VTSize;
10155 }
10156
10157 return DAG.getTokenFactor(dl, OutChains);
10158}
10159
10160/// Lower the call to 'memset' intrinsic function into a series of store
10161/// operations.
10162///
10163/// \param DAG Selection DAG where lowered code is placed.
10164/// \param dl Link to corresponding IR location.
10165/// \param Chain Control flow dependency.
10166/// \param Dst Pointer to destination memory location.
10167/// \param Src Value of byte to write into the memory.
10168/// \param Size Number of bytes to write.
10169/// \param Alignment Alignment of the destination in bytes.
10170/// \param isVol True if destination is volatile.
10171/// \param AlwaysInline Makes sure no function call is generated.
10172/// \param DstPtrInfo IR information on the memory pointer.
10173/// \returns New head in the control flow, if lowering was successful, empty
10174/// SDValue otherwise.
10175///
10176/// The function tries to replace 'llvm.memset' intrinsic with several store
10177/// operations and value calculation code. This is usually profitable for small
10178/// memory size or when the semantic requires inlining.
10180 SDValue Chain, SDValue Dst, SDValue Src,
10181 uint64_t Size, Align Alignment, bool isVol,
10182 bool AlwaysInline, MachinePointerInfo DstPtrInfo,
10183 const AAMDNodes &AAInfo) {
10184 // Turn a memset of undef to nop.
10185 // FIXME: We need to honor volatile even is Src is undef.
10186 if (Src.isUndef())
10187 return Chain;
10188
10189 // Expand memset to a series of load/store ops if the size operand
10190 // falls below a certain threshold.
10192 std::vector<EVT> MemOps;
10193 bool DstAlignCanChange = false;
10194 LLVMContext &C = *DAG.getContext();
10196 MachineFrameInfo &MFI = MF.getFrameInfo();
10197 bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
10199 if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
10200 DstAlignCanChange = true;
10201 bool IsZeroVal = isNullConstant(Src);
10202 unsigned Limit = AlwaysInline ? ~0 : TLI.getMaxStoresPerMemset(OptSize);
10203
10204 EVT LargestVT;
10205 if (!TLI.findOptimalMemOpLowering(
10206 C, MemOps, Limit,
10207 MemOp::Set(Size, DstAlignCanChange, Alignment, IsZeroVal, isVol),
10208 DstPtrInfo.getAddrSpace(), ~0u, MF.getFunction().getAttributes(),
10209 &LargestVT))
10210 return SDValue();
10211
10212 if (DstAlignCanChange) {
10213 Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
10214 const DataLayout &DL = DAG.getDataLayout();
10215 Align NewAlign = DL.getABITypeAlign(Ty);
10216
10217 // Don't promote to an alignment that would require dynamic stack
10218 // realignment which may conflict with optimizations such as tail call
10219 // optimization.
10221 if (!TRI->hasStackRealignment(MF))
10222 if (MaybeAlign StackAlign = DL.getStackAlignment())
10223 NewAlign = std::min(NewAlign, *StackAlign);
10224
10225 if (NewAlign > Alignment) {
10226 // Give the stack frame object a larger alignment if needed.
10227 if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
10228 MFI.setObjectAlignment(FI->getIndex(), NewAlign);
10229 Alignment = NewAlign;
10230 }
10231 }
10232
10233 SmallVector<SDValue, 8> OutChains;
10234 uint64_t DstOff = 0;
10235 unsigned NumMemOps = MemOps.size();
10236
10237 // Find the largest store and generate the bit pattern for it.
10238 // If target didn't set LargestVT, compute it from MemOps.
10239 if (!LargestVT.isSimple()) {
10240 LargestVT = MemOps[0];
10241 for (unsigned i = 1; i < NumMemOps; i++)
10242 if (MemOps[i].bitsGT(LargestVT))
10243 LargestVT = MemOps[i];
10244 }
10245 SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl);
10246
10247 // Prepare AAInfo for loads/stores after lowering this memset.
10248 AAMDNodes NewAAInfo = AAInfo;
10249 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
10250
10251 for (unsigned i = 0; i < NumMemOps; i++) {
10252 EVT VT = MemOps[i];
10253 unsigned VTSize = VT.getSizeInBits() / 8;
10254 // The target should specify store types that exactly cover the memset size
10255 // (with the last store potentially being oversized for overlapping stores).
10256 assert(Size > 0 && "Target specified more stores than needed in "
10257 "findOptimalMemOpLowering");
10258 if (VTSize > Size) {
10259 // Issuing an unaligned load / store pair that overlaps with the previous
10260 // pair. Adjust the offset accordingly.
10261 assert(i == NumMemOps-1 && i != 0);
10262 DstOff -= VTSize - Size;
10263 }
10264
10265 // If this store is smaller than the largest store see whether we can get
10266 // the smaller value for free with a truncate or extract vector element and
10267 // then store.
10268 SDValue Value = MemSetValue;
10269 if (VT.bitsLT(LargestVT)) {
10270 unsigned Index;
10271 unsigned NElts = LargestVT.getSizeInBits() / VT.getSizeInBits();
10272 EVT SVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), NElts);
10273 if (!LargestVT.isVector() && !VT.isVector() &&
10274 TLI.isTruncateFree(LargestVT, VT))
10275 Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue);
10276 else if (LargestVT.isVector() && !VT.isVector() &&
10277 TLI.shallExtractConstSplatVectorElementToStore(
10278 LargestVT.getTypeForEVT(*DAG.getContext()),
10279 VT.getSizeInBits(), Index) &&
10280 TLI.isTypeLegal(SVT) &&
10281 LargestVT.getSizeInBits() == SVT.getSizeInBits()) {
10282 // Target which can combine store(extractelement VectorTy, Idx) can get
10283 // the smaller value for free.
10284 SDValue TailValue = DAG.getNode(ISD::BITCAST, dl, SVT, MemSetValue);
10285 Value = DAG.getExtractVectorElt(dl, VT, TailValue, Index);
10286 } else
10287 Value = getMemsetValue(Src, VT, DAG, dl);
10288 }
10289 assert(Value.getValueType() == VT && "Value with wrong type.");
10290 SDValue Store = DAG.getStore(
10291 Chain, dl, Value,
10292 DAG.getObjectPtrOffset(dl, Dst, TypeSize::getFixed(DstOff)),
10293 DstPtrInfo.getWithOffset(DstOff), Alignment,
10295 NewAAInfo);
10296 OutChains.push_back(Store);
10297 DstOff += VT.getSizeInBits() / 8;
10298 // For oversized overlapping stores, only subtract the remaining bytes.
10299 // For normal stores, subtract the full store size.
10300 if (VTSize > Size) {
10301 Size = 0;
10302 } else {
10303 Size -= VTSize;
10304 }
10305 }
10306
10307 // After processing all stores, Size should be exactly 0. Any remaining bytes
10308 // indicate a bug in the target's findOptimalMemOpLowering implementation.
10309 assert(Size == 0 && "Target's findOptimalMemOpLowering did not specify "
10310 "stores that exactly cover the memset size");
10311
10312 return DAG.getTokenFactor(dl, OutChains);
10313}
10314
10316 const DataLayout &DL, unsigned AS) {
10317 // Lowering memcpy / memset / memmove intrinsics to calls is only valid if all
10318 // pointer operands can be losslessly bitcasted to pointers of address space 0
10319 if (AS != 0 && !TLI->getTargetMachine().isNoopAddrSpaceCast(DL, AS, 0)) {
10320 report_fatal_error("cannot lower memory intrinsic in address space " +
10321 Twine(AS));
10322 }
10323}
10324
10325/// The length of a memory intrinsic (e.g. number of bytes to copy) is unsigned
10326/// and may have any integer type. We zero-extend or truncate it to the pointer
10327/// type of the narrower address space being accessed.
10329 SDValue Size, unsigned DstAS,
10330 unsigned SrcAS) {
10332 MVT DstVT = TLI.getPointerTy(DAG.getDataLayout(), DstAS);
10333 MVT SrcVT = TLI.getPointerTy(DAG.getDataLayout(), SrcAS);
10334 return DAG.getZExtOrTrunc(Size, dl, DstVT.bitsLT(SrcVT) ? DstVT : SrcVT);
10335}
10336
10338 const SelectionDAG *SelDAG,
10339 bool AllowReturnsFirstArg) {
10340 if (!CI || !CI->isTailCall())
10341 return false;
10342 // TODO: Fix "returns-first-arg" determination so it doesn't depend on which
10343 // helper symbol we lower to.
10344 return isInTailCallPosition(*CI, SelDAG->getTarget(),
10345 AllowReturnsFirstArg &&
10347}
10348
10349static std::pair<SDValue, SDValue>
10352 const CallInst *CI, RTLIB::Libcall Call,
10353 SelectionDAG *DAG, const TargetLowering *TLI) {
10354 RTLIB::LibcallImpl LCImpl = DAG->getLibcalls().getLibcallImpl(Call);
10355
10356 if (LCImpl == RTLIB::Unsupported)
10357 return {};
10358
10360 bool IsTailCall =
10361 isInTailCallPositionWrapper(CI, DAG, /*AllowReturnsFirstArg=*/true) &&
10362 // Lowering doesn't support tail calling inside a function with
10363 // a swifterror argument yet.
10364 !DAG->hasSwiftErrorArg();
10365 SDValue Callee =
10366 DAG->getExternalSymbol(LCImpl, TLI->getPointerTy(DAG->getDataLayout()));
10367
10368 CLI.setDebugLoc(dl)
10369 .setChain(Chain)
10371 CI->getType(), Callee, std::move(Args))
10372 .setTailCall(IsTailCall);
10373
10374 return TLI->LowerCallTo(CLI);
10375}
10376
10377std::pair<SDValue, SDValue> SelectionDAG::getStrcmp(SDValue Chain,
10378 const SDLoc &dl, SDValue S1,
10379 SDValue S2,
10380 const CallInst *CI) {
10382 TargetLowering::ArgListTy Args = {{S1, PT}, {S2, PT}};
10383 return getRuntimeCallSDValueHelper(Chain, dl, std::move(Args), CI,
10384 RTLIB::STRCMP, this, TLI);
10385}
10386
10387std::pair<SDValue, SDValue> SelectionDAG::getStrstr(SDValue Chain,
10388 const SDLoc &dl, SDValue S1,
10389 SDValue S2,
10390 const CallInst *CI) {
10392 TargetLowering::ArgListTy Args = {{S1, PT}, {S2, PT}};
10393 return getRuntimeCallSDValueHelper(Chain, dl, std::move(Args), CI,
10394 RTLIB::STRSTR, this, TLI);
10395}
10396
10397std::pair<SDValue, SDValue> SelectionDAG::getMemccpy(SDValue Chain,
10398 const SDLoc &dl,
10399 SDValue Dst, SDValue Src,
10401 const CallInst *CI) {
10403
10405 {Dst, PT},
10406 {Src, PT},
10409 return getRuntimeCallSDValueHelper(Chain, dl, std::move(Args), CI,
10410 RTLIB::MEMCCPY, this, TLI);
10411}
10412
10413std::pair<SDValue, SDValue>
10415 SDValue Mem1, SDValue Size, const CallInst *CI) {
10418 {Mem0, PT},
10419 {Mem1, PT},
10421 return getRuntimeCallSDValueHelper(Chain, dl, std::move(Args), CI,
10422 RTLIB::MEMCMP, this, TLI);
10423}
10424
10425std::pair<SDValue, SDValue> SelectionDAG::getStrcpy(SDValue Chain,
10426 const SDLoc &dl,
10427 SDValue Dst, SDValue Src,
10428 const CallInst *CI) {
10430 TargetLowering::ArgListTy Args = {{Dst, PT}, {Src, PT}};
10431 return getRuntimeCallSDValueHelper(Chain, dl, std::move(Args), CI,
10432 RTLIB::STRCPY, this, TLI);
10433}
10434
10435std::pair<SDValue, SDValue> SelectionDAG::getStrlen(SDValue Chain,
10436 const SDLoc &dl,
10437 SDValue Src,
10438 const CallInst *CI) {
10439 // Emit a library call.
10442 return getRuntimeCallSDValueHelper(Chain, dl, std::move(Args), CI,
10443 RTLIB::STRLEN, this, TLI);
10444}
10445
10447 return TLI->supportSwiftError() &&
10448 MF->getFunction().getAttributes().hasAttrSomewhere(
10449 Attribute::SwiftError);
10450}
10451
10453 SDValue Chain, const SDLoc &dl, SDValue Dst, SDValue Src, SDValue Size,
10454 Align DstAlign, Align SrcAlign, bool isVol, bool AlwaysInline,
10455 const CallInst *CI, std::optional<bool> OverrideTailCall,
10456 MachinePointerInfo DstPtrInfo, MachinePointerInfo SrcPtrInfo,
10457 const AAMDNodes &AAInfo, BatchAAResults *BatchAA) {
10458 Size = getMemIntrinsicSize(*this, dl, Size, DstPtrInfo.getAddrSpace(),
10459 SrcPtrInfo.getAddrSpace());
10460 // Check to see if we should lower the memcpy to loads and stores first.
10461 // For cases within the target-specified limits, this is the best choice.
10462 const MDNode *DstMemCacheHint =
10463 CI ? getMemCacheHint(*CI, /*OperandNo=*/0) : nullptr;
10464 const MDNode *SrcMemCacheHint =
10465 CI ? getMemCacheHint(*CI, /*OperandNo=*/1) : nullptr;
10466
10468 if (ConstantSize) {
10469 // Memcpy with size zero? Just return the original chain.
10470 if (ConstantSize->isZero())
10471 return Chain;
10472
10474 *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), DstAlign,
10475 SrcAlign, isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo, BatchAA,
10476 DstMemCacheHint, SrcMemCacheHint);
10477 if (Result.getNode())
10478 return Result;
10479 }
10480
10481 // Then check to see if we should lower the memcpy with target-specific
10482 // code. If the target chooses to do this, this is the next best.
10483 if (TSI) {
10484 bool IsTailCall = OverrideTailCall.value_or(isInTailCallPositionWrapper(
10485 CI, this, /*AllowReturnsFirstArg=*/false)) &&
10487 [[maybe_unused]] SDValue OldRoot = getRoot();
10488 SDValue Result = TSI->EmitTargetCodeForMemcpy(
10489 *this, dl, Chain, Dst, Src, Size, DstAlign, SrcAlign, isVol,
10490 AlwaysInline, IsTailCall, DstPtrInfo, SrcPtrInfo);
10491 assert((Result.getNode() || !IsTailCall || getRoot() != OldRoot) &&
10492 "target declined without clearing IsTailCall");
10493 if (Result.getNode() || IsTailCall)
10494 return Result;
10495 }
10496
10497 // If we really need inline code and the target declined to provide it,
10498 // use a (potentially long) sequence of loads and stores.
10499 if (AlwaysInline) {
10500 assert(ConstantSize && "AlwaysInline requires a constant size!");
10502 *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), DstAlign,
10503 SrcAlign, isVol, true, DstPtrInfo, SrcPtrInfo, AAInfo, BatchAA,
10504 DstMemCacheHint, SrcMemCacheHint);
10505 }
10506
10508 DstPtrInfo.getAddrSpace());
10510 SrcPtrInfo.getAddrSpace());
10511
10512 // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc
10513 // memcpy is not guaranteed to be safe. libc memcpys aren't required to
10514 // respect volatile, so they may do things like read or write memory
10515 // beyond the given memory regions. But fixing this isn't easy, and most
10516 // people don't care.
10517
10518 // Emit a library call.
10521 Args.emplace_back(Dst, PtrTy);
10522 Args.emplace_back(Src, PtrTy);
10523 Args.emplace_back(Size, getDataLayout().getIntPtrType(*getContext()));
10524 // FIXME: pass in SDLoc
10526 bool IsTailCall = false;
10527 RTLIB::LibcallImpl MemCpyImpl = Libcalls->getMemcpyImpl();
10528
10529 if (OverrideTailCall.has_value()) {
10530 IsTailCall = *OverrideTailCall;
10531 } else {
10532 bool LowersToMemcpy = MemCpyImpl == RTLIB::impl_memcpy;
10533 IsTailCall = isInTailCallPositionWrapper(CI, this, LowersToMemcpy);
10534 }
10535 // Lowering doesn't support tail calling inside a function with a
10536 // swifterror argument yet.
10537 IsTailCall &= !hasSwiftErrorArg();
10538
10539 CLI.setDebugLoc(dl)
10540 .setChain(Chain)
10541 .setLibCallee(
10542 Libcalls->getLibcallImplCallingConv(MemCpyImpl),
10543 Dst.getValueType().getTypeForEVT(*getContext()),
10544 getExternalSymbol(MemCpyImpl, TLI->getPointerTy(getDataLayout())),
10545 std::move(Args))
10547 .setTailCall(IsTailCall);
10548
10549 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
10550 return CallResult.second;
10551}
10552
10555 const Module &M = *DAG->getMachineFunction().getFunction().getParent();
10556 Type *SizeTTy = DAG->getLibInfo().getSizeTType(M);
10558 DAG->getZExtOrTrunc(Size, dl, MVT::getVT(SizeTTy)), SizeTTy);
10559}
10560
10562 SDValue Dst, SDValue Src, SDValue Size,
10563 Type *SizeTy, unsigned ElemSz,
10564 bool isTailCall,
10565 MachinePointerInfo DstPtrInfo,
10566 MachinePointerInfo SrcPtrInfo) {
10567 // Lowering doesn't support tail calling inside a function with a
10568 // swifterror argument yet.
10569 isTailCall &= !hasSwiftErrorArg();
10570
10571 // Emit a library call.
10574 Args.emplace_back(Dst, ArgTy);
10575 Args.emplace_back(Src, ArgTy);
10576 Args.emplace_back(getAtomicMemOpSizeArg(this, dl, Size));
10577
10578 RTLIB::Libcall LibraryCall =
10580 RTLIB::LibcallImpl LibcallImpl = Libcalls->getLibcallImpl(LibraryCall);
10581 if (LibcallImpl == RTLIB::Unsupported)
10582 report_fatal_error("Unsupported element size");
10583
10585 CLI.setDebugLoc(dl)
10586 .setChain(Chain)
10587 .setLibCallee(
10588 Libcalls->getLibcallImplCallingConv(LibcallImpl),
10590 getExternalSymbol(LibcallImpl, TLI->getPointerTy(getDataLayout())),
10591 std::move(Args))
10593 .setTailCall(isTailCall);
10594
10595 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
10596 return CallResult.second;
10597}
10598
10600 SDValue Src, SDValue Size, Align DstAlign,
10601 Align SrcAlign, bool isVol, const CallInst *CI,
10602 std::optional<bool> OverrideTailCall,
10603 MachinePointerInfo DstPtrInfo,
10604 MachinePointerInfo SrcPtrInfo,
10605 const AAMDNodes &AAInfo,
10606 BatchAAResults *BatchAA) {
10607 Size = getMemIntrinsicSize(*this, dl, Size, DstPtrInfo.getAddrSpace(),
10608 SrcPtrInfo.getAddrSpace());
10609 // Check to see if we should lower the memmove to loads and stores first.
10610 // For cases within the target-specified limits, this is the best choice.
10612 if (ConstantSize) {
10613 // Memmove with size zero? Just return the original chain.
10614 if (ConstantSize->isZero())
10615 return Chain;
10616
10618 *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), DstAlign,
10619 SrcAlign, isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo);
10620 if (Result.getNode())
10621 return Result;
10622 }
10623
10624 // Then check to see if we should lower the memmove with target-specific
10625 // code. If the target chooses to do this, this is the next best.
10626 if (TSI) {
10627 bool IsTailCall = OverrideTailCall.value_or(isInTailCallPositionWrapper(
10628 CI, this, /*AllowReturnsFirstArg=*/false)) &&
10630 [[maybe_unused]] SDValue OldRoot = getRoot();
10631 SDValue Result = TSI->EmitTargetCodeForMemmove(
10632 *this, dl, Chain, Dst, Src, Size, DstAlign, SrcAlign, isVol, IsTailCall,
10633 DstPtrInfo, SrcPtrInfo);
10634 assert((Result.getNode() || !IsTailCall || getRoot() != OldRoot) &&
10635 "target declined without clearing IsTailCall");
10636 if (Result.getNode() || IsTailCall)
10637 return Result;
10638 }
10639
10641 DstPtrInfo.getAddrSpace());
10643 SrcPtrInfo.getAddrSpace());
10644
10645 // FIXME: If the memmove is volatile, lowering it to plain libc memmove may
10646 // not be safe. See memcpy above for more details.
10647
10648 // Emit a library call.
10651 Args.emplace_back(Dst, PtrTy);
10652 Args.emplace_back(Src, PtrTy);
10653 Args.emplace_back(Size, getDataLayout().getIntPtrType(*getContext()));
10654 // FIXME: pass in SDLoc
10656
10657 RTLIB::LibcallImpl MemmoveImpl = Libcalls->getLibcallImpl(RTLIB::MEMMOVE);
10658
10659 bool IsTailCall = false;
10660 if (OverrideTailCall.has_value()) {
10661 IsTailCall = *OverrideTailCall;
10662 } else {
10663 bool LowersToMemmove = MemmoveImpl == RTLIB::impl_memmove;
10664 IsTailCall = isInTailCallPositionWrapper(CI, this, LowersToMemmove);
10665 }
10666 // Lowering doesn't support tail calling inside a function with a
10667 // swifterror argument yet.
10668 IsTailCall &= !hasSwiftErrorArg();
10669
10670 CLI.setDebugLoc(dl)
10671 .setChain(Chain)
10672 .setLibCallee(
10673 Libcalls->getLibcallImplCallingConv(MemmoveImpl),
10674 Dst.getValueType().getTypeForEVT(*getContext()),
10675 getExternalSymbol(MemmoveImpl, TLI->getPointerTy(getDataLayout())),
10676 std::move(Args))
10678 .setTailCall(IsTailCall);
10679
10680 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
10681 return CallResult.second;
10682}
10683
10685 SDValue Dst, SDValue Src, SDValue Size,
10686 Type *SizeTy, unsigned ElemSz,
10687 bool isTailCall,
10688 MachinePointerInfo DstPtrInfo,
10689 MachinePointerInfo SrcPtrInfo) {
10690 // Lowering doesn't support tail calling inside a function with a
10691 // swifterror argument yet.
10692 isTailCall &= !hasSwiftErrorArg();
10693
10694 // Emit a library call.
10697 Args.emplace_back(Dst, IntPtrTy);
10698 Args.emplace_back(Src, IntPtrTy);
10699 Args.emplace_back(getAtomicMemOpSizeArg(this, dl, Size));
10700
10701 RTLIB::Libcall LibraryCall =
10703 RTLIB::LibcallImpl LibcallImpl = Libcalls->getLibcallImpl(LibraryCall);
10704 if (LibcallImpl == RTLIB::Unsupported)
10705 report_fatal_error("Unsupported element size");
10706
10708 CLI.setDebugLoc(dl)
10709 .setChain(Chain)
10710 .setLibCallee(
10711 Libcalls->getLibcallImplCallingConv(LibcallImpl),
10713 getExternalSymbol(LibcallImpl, TLI->getPointerTy(getDataLayout())),
10714 std::move(Args))
10716 .setTailCall(isTailCall);
10717
10718 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
10719 return CallResult.second;
10720}
10721
10723 SDValue Src, SDValue Size, Align Alignment,
10724 bool isVol, bool AlwaysInline,
10725 const CallInst *CI,
10726 MachinePointerInfo DstPtrInfo,
10727 const AAMDNodes &AAInfo) {
10728 Size = getMemIntrinsicSize(*this, dl, Size, DstPtrInfo.getAddrSpace(),
10729 DstPtrInfo.getAddrSpace());
10730 // Check to see if we should lower the memset to stores first.
10731 // For cases within the target-specified limits, this is the best choice.
10733 if (ConstantSize) {
10734 // Memset with size zero? Just return the original chain.
10735 if (ConstantSize->isZero())
10736 return Chain;
10737
10738 SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src,
10739 ConstantSize->getZExtValue(), Alignment,
10740 isVol, false, DstPtrInfo, AAInfo);
10741
10742 if (Result.getNode())
10743 return Result;
10744 }
10745
10746 // Then check to see if we should lower the memset with target-specific
10747 // code. If the target chooses to do this, this is the next best.
10748 if (TSI) {
10749 bool IsTailCall =
10750 isInTailCallPositionWrapper(CI, this, /*AllowReturnsFirstArg=*/false) &&
10752 [[maybe_unused]] SDValue OldRoot = getRoot();
10753 SDValue Result = TSI->EmitTargetCodeForMemset(
10754 *this, dl, Chain, Dst, Src, Size, Alignment, isVol, AlwaysInline,
10755 IsTailCall, DstPtrInfo);
10756 assert((Result.getNode() || !IsTailCall || getRoot() != OldRoot) &&
10757 "target declined without clearing IsTailCall");
10758 if (Result.getNode() || IsTailCall)
10759 return Result;
10760 }
10761
10762 // If we really need inline code and the target declined to provide it,
10763 // use a (potentially long) sequence of loads and stores.
10764 if (AlwaysInline) {
10765 assert(ConstantSize && "AlwaysInline requires a constant size!");
10766 SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src,
10767 ConstantSize->getZExtValue(), Alignment,
10768 isVol, true, DstPtrInfo, AAInfo);
10769 assert(Result &&
10770 "getMemsetStores must return a valid sequence when AlwaysInline");
10771 return Result;
10772 }
10773
10775 DstPtrInfo.getAddrSpace());
10776
10777 // Emit a library call.
10778 auto &Ctx = *getContext();
10779 const auto& DL = getDataLayout();
10780
10782 // FIXME: pass in SDLoc
10783 CLI.setDebugLoc(dl).setChain(Chain);
10784
10785 RTLIB::LibcallImpl BzeroImpl = Libcalls->getLibcallImpl(RTLIB::BZERO);
10786 bool UseBZero = BzeroImpl != RTLIB::Unsupported && isNullConstant(Src);
10787
10788 // If zeroing out and bzero is present, use it.
10789 if (UseBZero) {
10791 Args.emplace_back(Dst, PointerType::getUnqual(Ctx));
10792 Args.emplace_back(Size, DL.getIntPtrType(Ctx));
10793 CLI.setLibCallee(
10794 Libcalls->getLibcallImplCallingConv(BzeroImpl), Type::getVoidTy(Ctx),
10795 getExternalSymbol(BzeroImpl, TLI->getPointerTy(DL)), std::move(Args));
10796 } else {
10797 RTLIB::LibcallImpl MemsetImpl = Libcalls->getLibcallImpl(RTLIB::MEMSET);
10798
10799 MVT IntVT = MVT::getIntegerVT(LibInfo->getIntSize());
10801 Args.emplace_back(Dst, PointerType::getUnqual(Ctx));
10802 Args.emplace_back(getAnyExtOrTrunc(Src, dl, IntVT),
10803 Type::getIntNTy(Ctx, LibInfo->getIntSize()),
10804 LibInfo->getExtAttrForI32Param());
10805 Args.emplace_back(Size, DL.getIntPtrType(Ctx));
10806
10807 CLI.setLibCallee(Libcalls->getLibcallImplCallingConv(MemsetImpl),
10808 Dst.getValueType().getTypeForEVT(Ctx),
10809 getExternalSymbol(MemsetImpl, TLI->getPointerTy(DL)),
10810 std::move(Args));
10811 }
10812
10813 RTLIB::LibcallImpl MemsetImpl = Libcalls->getLibcallImpl(RTLIB::MEMSET);
10814 bool LowersToMemset = MemsetImpl == RTLIB::impl_memset;
10815
10816 // If we're going to use bzero, make sure not to tail call unless the
10817 // subsequent return doesn't need a value, as bzero doesn't return the first
10818 // arg unlike memset.
10819 bool ReturnsFirstArg = CI && funcReturnsFirstArgOfCall(*CI) && !UseBZero;
10820 bool IsTailCall = CI && CI->isTailCall() &&
10822 ReturnsFirstArg && LowersToMemset) &&
10823 // Lowering doesn't support tail calling inside a function
10824 // with a swifterror argument yet.
10826 CLI.setDiscardResult().setTailCall(IsTailCall);
10827
10828 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
10829 return CallResult.second;
10830}
10831
10834 Type *SizeTy, unsigned ElemSz,
10835 bool isTailCall,
10836 MachinePointerInfo DstPtrInfo) {
10837 // Lowering doesn't support tail calling inside a function with a
10838 // swifterror argument yet.
10839 isTailCall &= !hasSwiftErrorArg();
10840
10841 // Emit a library call.
10842 MVT IntVT = MVT::getIntegerVT(LibInfo->getIntSize());
10844 Args.emplace_back(Dst, getDataLayout().getIntPtrType(*getContext()));
10845 Args.emplace_back(getAnyExtOrTrunc(Value, dl, IntVT),
10846 Type::getIntNTy(*getContext(), LibInfo->getIntSize()),
10847 LibInfo->getExtAttrForI32Param());
10848 Args.emplace_back(getAtomicMemOpSizeArg(this, dl, Size));
10849
10850 RTLIB::Libcall LibraryCall =
10852 RTLIB::LibcallImpl LibcallImpl = Libcalls->getLibcallImpl(LibraryCall);
10853 if (LibcallImpl == RTLIB::Unsupported)
10854 report_fatal_error("Unsupported element size");
10855
10857 CLI.setDebugLoc(dl)
10858 .setChain(Chain)
10859 .setLibCallee(
10860 Libcalls->getLibcallImplCallingConv(LibcallImpl),
10862 getExternalSymbol(LibcallImpl, TLI->getPointerTy(getDataLayout())),
10863 std::move(Args))
10865 .setTailCall(isTailCall);
10866
10867 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
10868 return CallResult.second;
10869}
10870
10871SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
10873 MachineMemOperand *MMO,
10874 ISD::LoadExtType ExtType) {
10875 SDNodeKey ID(Opcode, VTList, Ops);
10876 ID.AddInteger(MemVT.getRawBits());
10877 ID.AddInteger(getSyntheticNodeSubclassData<AtomicSDNode>(
10878 dl.getIROrder(), Opcode, VTList, MemVT, MMO, ExtType));
10879 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
10880 ID.AddInteger(MMO->getFlags());
10881 FoldingSetInsertToken InsertToken;
10882 if (auto *E = cast_or_null<AtomicSDNode>(lookupNode(ID, dl, InsertToken))) {
10883 E->refineAlignment(MMO);
10884 E->refineMMOMetadata(MMO);
10885 return SDValue(E, 0);
10886 }
10887
10888 auto *N = newSDNode<AtomicSDNode>(dl.getIROrder(), dl.getDebugLoc(), Opcode,
10889 VTList, MemVT, MMO, ExtType);
10890 createOperands(N, Ops);
10891
10892 CSEMap.insert(N, InsertToken);
10893 InsertNode(N);
10894 SDValue V(N, 0);
10895 NewSDValueDbgMsg(V, "Creating new node: ", this);
10896 return V;
10897}
10898
10900 EVT MemVT, SDVTList VTs, SDValue Chain,
10901 SDValue Ptr, SDValue Cmp, SDValue Swp,
10902 MachineMemOperand *MMO) {
10903 assert(Opcode == ISD::ATOMIC_CMP_SWAP ||
10905 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
10906
10907 SDValue Ops[] = {Chain, Ptr, Cmp, Swp};
10908 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
10909}
10910
10911SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
10912 SDValue Chain, SDValue Ptr, SDValue Val,
10913 MachineMemOperand *MMO) {
10914 assert((Opcode == ISD::ATOMIC_LOAD_ADD || Opcode == ISD::ATOMIC_LOAD_SUB ||
10915 Opcode == ISD::ATOMIC_LOAD_AND || Opcode == ISD::ATOMIC_LOAD_CLR ||
10916 Opcode == ISD::ATOMIC_LOAD_OR || Opcode == ISD::ATOMIC_LOAD_XOR ||
10917 Opcode == ISD::ATOMIC_LOAD_NAND || Opcode == ISD::ATOMIC_LOAD_MIN ||
10918 Opcode == ISD::ATOMIC_LOAD_MAX || Opcode == ISD::ATOMIC_LOAD_UMIN ||
10919 Opcode == ISD::ATOMIC_LOAD_UMAX || Opcode == ISD::ATOMIC_LOAD_FADD ||
10920 Opcode == ISD::ATOMIC_LOAD_FSUB || Opcode == ISD::ATOMIC_LOAD_FMAX ||
10921 Opcode == ISD::ATOMIC_LOAD_FMIN ||
10922 Opcode == ISD::ATOMIC_LOAD_FMINIMUM ||
10923 Opcode == ISD::ATOMIC_LOAD_FMAXIMUM ||
10924 Opcode == ISD::ATOMIC_LOAD_FMINIMUMNUM ||
10925 Opcode == ISD::ATOMIC_LOAD_FMAXIMUMNUM ||
10926 Opcode == ISD::ATOMIC_LOAD_UINC_WRAP ||
10927 Opcode == ISD::ATOMIC_LOAD_UDEC_WRAP ||
10928 Opcode == ISD::ATOMIC_LOAD_USUB_COND ||
10929 Opcode == ISD::ATOMIC_LOAD_USUB_SAT || Opcode == ISD::ATOMIC_SWAP ||
10930 Opcode == ISD::ATOMIC_STORE) &&
10931 "Invalid Atomic Op");
10932
10933 EVT VT = Val.getValueType();
10934
10935 SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) :
10936 getVTList(VT, MVT::Other);
10937 SDValue Ops[] = {Chain, Ptr, Val};
10938 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
10939}
10940
10942 EVT MemVT, EVT VT, SDValue Chain,
10943 SDValue Ptr, MachineMemOperand *MMO) {
10944 SDVTList VTs = getVTList(VT, MVT::Other);
10945 SDValue Ops[] = {Chain, Ptr};
10946 return getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, VTs, Ops, MMO, ExtType);
10947}
10948
10949/// getMergeValues - Create a MERGE_VALUES node from the given operands.
10951 if (Ops.size() == 1)
10952 return Ops[0];
10953
10955 VTs.reserve(Ops.size());
10956 for (const SDValue &Op : Ops)
10957 VTs.push_back(Op.getValueType());
10958 return getNode(ISD::MERGE_VALUES, dl, getVTList(VTs), Ops);
10959}
10960
10962 SDValue Chain, const SDLoc &dl) {
10963 SmallVector<SDValue, 4> RetValues;
10964 RetValues.reserve(ResultTypes.size());
10965 for (EVT VT : ResultTypes)
10966 RetValues.push_back(VT == MVT::Other ? Chain : getPOISON(VT));
10967 return getMergeValues(RetValues, dl);
10968}
10969
10971 unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef<SDValue> Ops,
10972 EVT MemVT, MachinePointerInfo PtrInfo, Align Alignment,
10974 const AAMDNodes &AAInfo) {
10975 if (Size.hasValue() && !Size.getValue())
10977
10979 MachineMemOperand *MMO =
10980 MF.getMachineMemOperand(PtrInfo, Flags, Size, Alignment, AAInfo);
10981
10982 return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, MMO);
10983}
10984
10986 SDVTList VTList,
10987 ArrayRef<SDValue> Ops, EVT MemVT,
10988 MachineMemOperand *MMO) {
10989 return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, ArrayRef(MMO));
10990}
10991
10993 SDVTList VTList,
10994 ArrayRef<SDValue> Ops, EVT MemVT,
10996 assert(!MMOs.empty() && "Must have at least one MMO");
10997 assert(
10998 (Opcode == ISD::INTRINSIC_VOID || Opcode == ISD::INTRINSIC_W_CHAIN ||
10999 Opcode == ISD::PREFETCH ||
11000 (Opcode <= (unsigned)std::numeric_limits<int>::max() &&
11001 Opcode >= ISD::BUILTIN_OP_END && TSI->isTargetMemoryOpcode(Opcode))) &&
11002 "Opcode is not a memory-accessing opcode!");
11003
11005 if (MMOs.size() == 1) {
11006 MemRefs = MMOs[0];
11007 } else {
11008 // Allocate: [size_t count][MMO*][MMO*]...
11009 size_t AllocSize =
11010 sizeof(size_t) + MMOs.size() * sizeof(MachineMemOperand *);
11011 void *Buffer = Allocator.Allocate(AllocSize, alignof(size_t));
11012 size_t *CountPtr = static_cast<size_t *>(Buffer);
11013 *CountPtr = MMOs.size();
11014 MachineMemOperand **Array =
11015 reinterpret_cast<MachineMemOperand **>(CountPtr + 1);
11016 llvm::copy(MMOs, Array);
11017 MemRefs = Array;
11018 }
11019
11020 // Memoize the node unless it returns a glue result.
11022 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
11023 SDNodeKey ID(Opcode, VTList, Ops);
11024 ID.AddInteger(getSyntheticNodeSubclassData<MemIntrinsicSDNode>(
11025 Opcode, dl.getIROrder(), VTList, MemVT, MemRefs));
11026 ID.AddInteger(MemVT.getRawBits());
11027 for (const MachineMemOperand *MMO : MMOs) {
11028 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11029 ID.AddInteger(MMO->getFlags());
11030 }
11031 FoldingSetInsertToken InsertToken;
11032 if (SDNode *E = lookupNode(ID, dl, InsertToken)) {
11033 cast<MemIntrinsicSDNode>(E)->refineAlignment(MMOs);
11034 return SDValue(E, 0);
11035 }
11036
11037 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
11038 VTList, MemVT, MemRefs);
11039 createOperands(N, Ops);
11040 CSEMap.insert(N, InsertToken);
11041 } else {
11042 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
11043 VTList, MemVT, MemRefs);
11044 createOperands(N, Ops);
11045 }
11046 InsertNode(N);
11047 SDValue V(N, 0);
11048 NewSDValueDbgMsg(V, "Creating new node: ", this);
11049 return V;
11050}
11051
11053 SDValue Chain, int FrameIndex) {
11054 const unsigned Opcode = IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END;
11055 const auto VTs = getVTList(MVT::Other);
11056 SDValue Ops[2] = {
11057 Chain,
11058 getFrameIndex(FrameIndex,
11059 getTargetLoweringInfo().getFrameIndexTy(getDataLayout()),
11060 true)};
11061
11062 SDNodeKey ID(Opcode, VTs, Ops);
11063 FoldingSetInsertToken InsertToken;
11064 if (SDNode *E = lookupNode(ID, dl, InsertToken))
11065 return SDValue(E, 0);
11066
11067 LifetimeSDNode *N =
11068 newSDNode<LifetimeSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), VTs);
11069 createOperands(N, Ops);
11070 CSEMap.insert(N, InsertToken);
11071 InsertNode(N);
11072 SDValue V(N, 0);
11073 NewSDValueDbgMsg(V, "Creating new node: ", this);
11074 return V;
11075}
11076
11078 uint64_t Guid, uint64_t Index,
11079 uint32_t Attr) {
11080 const unsigned Opcode = ISD::PSEUDO_PROBE;
11081 const auto VTs = getVTList(MVT::Other);
11082 SDValue Ops[] = {Chain};
11083 SDNodeKey ID(Opcode, VTs, Ops);
11084 ID.AddInteger(Guid);
11085 ID.AddInteger(Index);
11086 ID.AddInteger(Attr);
11087 FoldingSetInsertToken InsertToken;
11088 if (SDNode *E = lookupNode(ID, Dl, InsertToken))
11089 return SDValue(E, 0);
11090
11091 auto *N = newSDNode<PseudoProbeSDNode>(
11092 Opcode, Dl.getIROrder(), Dl.getDebugLoc(), VTs, Guid, Index, Attr);
11093 createOperands(N, Ops);
11094 CSEMap.insert(N, InsertToken);
11095 InsertNode(N);
11096 SDValue V(N, 0);
11097 NewSDValueDbgMsg(V, "Creating new node: ", this);
11098 return V;
11099}
11100
11101/// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
11102/// MachinePointerInfo record from it. This is particularly useful because the
11103/// code generator has many cases where it doesn't bother passing in a
11104/// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
11106 SelectionDAG &DAG, SDValue Ptr,
11107 int64_t Offset = 0) {
11108 // If this is FI+Offset, we can model it.
11109 if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr))
11111 FI->getIndex(), Offset);
11112
11113 // If this is (FI+Offset1)+Offset2, we can model it.
11114 if (Ptr.getOpcode() != ISD::ADD ||
11117 return Info;
11118
11119 int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
11121 DAG.getMachineFunction(), FI,
11122 Offset + cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue());
11123}
11124
11125/// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
11126/// MachinePointerInfo record from it. This is particularly useful because the
11127/// code generator has many cases where it doesn't bother passing in a
11128/// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
11130 SelectionDAG &DAG, SDValue Ptr,
11131 SDValue OffsetOp) {
11132 // If the 'Offset' value isn't a constant, we can't handle this.
11134 return InferPointerInfo(Info, DAG, Ptr, OffsetNode->getSExtValue());
11135 if (OffsetOp.isUndef())
11136 return InferPointerInfo(Info, DAG, Ptr);
11137 return Info;
11138}
11139
11141 EVT VT, const SDLoc &dl, SDValue Chain,
11142 SDValue Ptr, SDValue Offset,
11143 MachinePointerInfo PtrInfo, EVT MemVT,
11144 Align Alignment,
11145 MachineMemOperand::Flags MMOFlags,
11146 const MMOMetadata &Metadata) {
11147 assert(Chain.getValueType() == MVT::Other &&
11148 "Invalid chain type");
11149
11150 MMOFlags |= MachineMemOperand::MOLoad;
11151 assert((MMOFlags & MachineMemOperand::MOStore) == 0);
11152 // If we don't have a PtrInfo, infer the trivial frame index case to simplify
11153 // clients.
11154 if (PtrInfo.V.isNull())
11155 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
11156
11157 TypeSize Size = MemVT.getStoreSize();
11159 MachineMemOperand *MMO =
11160 MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, Alignment, Metadata);
11161 return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO);
11162}
11163
11165 EVT VT, const SDLoc &dl, SDValue Chain,
11166 SDValue Ptr, SDValue Offset, EVT MemVT,
11167 MachineMemOperand *MMO) {
11168 if (VT == MemVT) {
11169 ExtType = ISD::NON_EXTLOAD;
11170 } else if (ExtType == ISD::NON_EXTLOAD) {
11171 assert(VT == MemVT && "Non-extending load from different memory type!");
11172 } else {
11173 // Extending load.
11174 assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) &&
11175 "Should only be an extending load, not truncating!");
11176 assert(VT.isInteger() == MemVT.isInteger() &&
11177 "Cannot convert from FP to Int or Int -> FP!");
11178 assert(VT.isVector() == MemVT.isVector() &&
11179 "Cannot use an ext load to convert to or from a vector!");
11180 assert((!VT.isVector() ||
11182 "Cannot use an ext load to change the number of vector elements!");
11183 }
11184
11185 assert((!MMO->getRanges() ||
11187 ->getBitWidth() == MemVT.getScalarSizeInBits() &&
11188 MemVT.isInteger())) &&
11189 "Range metadata and load type must match!");
11190
11191 bool Indexed = AM != ISD::UNINDEXED;
11192 assert((Indexed || Offset.getOpcode() == ISD::POISON) &&
11193 "Unindexed load with an offset!");
11194
11195 SDVTList VTs = Indexed ?
11196 getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
11197 SDValue Ops[] = { Chain, Ptr, Offset };
11198 SDNodeKey ID(ISD::LOAD, VTs, Ops);
11199 ID.AddInteger(MemVT.getRawBits());
11200 ID.AddInteger(getSyntheticNodeSubclassData<LoadSDNode>(
11201 dl.getIROrder(), VTs, AM, ExtType, MemVT, MMO));
11202 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11203 ID.AddInteger(MMO->getFlags());
11204 FoldingSetInsertToken InsertToken;
11205 if (auto *E = cast_or_null<LoadSDNode>(lookupNode(ID, dl, InsertToken))) {
11206 E->refineAlignment(MMO);
11207 E->refineMMOMetadata(MMO);
11208 return SDValue(E, 0);
11209 }
11210 auto *N = newSDNode<LoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
11211 ExtType, MemVT, MMO);
11212 createOperands(N, Ops);
11213
11214 CSEMap.insert(N, InsertToken);
11215 InsertNode(N);
11216 SDValue V(N, 0);
11217 NewSDValueDbgMsg(V, "Creating new node: ", this);
11218 return V;
11219}
11220
11222 SDValue Ptr, MachinePointerInfo PtrInfo,
11223 MaybeAlign Alignment,
11224 MachineMemOperand::Flags MMOFlags,
11225 const MMOMetadata &Metadata) {
11227 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
11228 PtrInfo, VT, Alignment, MMOFlags, Metadata);
11229}
11230
11232 SDValue Ptr, MachineMemOperand *MMO) {
11234 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
11235 VT, MMO);
11236}
11237
11239 EVT VT, SDValue Chain, SDValue Ptr,
11240 MachinePointerInfo PtrInfo, EVT MemVT,
11241 MaybeAlign Alignment,
11242 MachineMemOperand::Flags MMOFlags,
11243 const MMOMetadata &Metadata) {
11245 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, PtrInfo,
11246 MemVT, Alignment, MMOFlags, Metadata);
11247}
11248
11250 EVT VT, SDValue Chain, SDValue Ptr, EVT MemVT,
11251 MachineMemOperand *MMO) {
11253 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef,
11254 MemVT, MMO);
11255}
11256
11260 LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
11261 assert(LD->getOffset().getOpcode() == ISD::POISON &&
11262 "Load is already a indexed load!");
11263 // Don't propagate the invariant or dereferenceable flags.
11264 auto MMOFlags =
11265 LD->getMemOperand()->getFlags() &
11267 return getLoad(
11268 AM, LD->getExtensionType(), OrigLoad.getValueType(), dl, LD->getChain(),
11269 Base, Offset, LD->getPointerInfo(), LD->getMemoryVT(), LD->getAlign(),
11270 MMOFlags,
11271 MMOMetadata(LD->getAAInfo(), LD->getRanges(), LD->getMemCacheHint()));
11272}
11273
11275 SDValue Ptr, MachinePointerInfo PtrInfo,
11276 Align Alignment,
11277 MachineMemOperand::Flags MMOFlags,
11278 const MMOMetadata &Metadata) {
11279 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
11280
11281 MMOFlags |= MachineMemOperand::MOStore;
11282 assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
11283 assert(!Metadata.Ranges && "range metadata is invalid for stores");
11284
11285 if (PtrInfo.V.isNull())
11286 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
11287
11290 MachineMemOperand *MMO =
11291 MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, Alignment, Metadata);
11292 return getStore(Chain, dl, Val, Ptr, MMO);
11293}
11294
11296 SDValue Ptr, MachineMemOperand *MMO) {
11298 return getStore(Chain, dl, Val, Ptr, Undef, Val.getValueType(), MMO,
11300}
11301
11303 SDValue Ptr, SDValue Offset, EVT SVT,
11305 bool IsTruncating) {
11306 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
11307 EVT VT = Val.getValueType();
11308 if (VT == SVT) {
11309 IsTruncating = false;
11310 } else if (!IsTruncating) {
11311 assert(VT == SVT && "No-truncating store from different memory type!");
11312 } else {
11314 "Should only be a truncating store, not extending!");
11315 assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!");
11316 assert(VT.isVector() == SVT.isVector() &&
11317 "Cannot use trunc store to convert to or from a vector!");
11318 assert((!VT.isVector() ||
11320 "Cannot use trunc store to change the number of vector elements!");
11321 }
11322
11323 bool Indexed = AM != ISD::UNINDEXED;
11324 assert((Indexed || Offset.getOpcode() == ISD::POISON) &&
11325 "Unindexed store with an offset!");
11326 SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other)
11327 : getVTList(MVT::Other);
11328 SDValue Ops[] = {Chain, Val, Ptr, Offset};
11329 SDNodeKey ID(ISD::STORE, VTs, Ops);
11330 ID.AddInteger(SVT.getRawBits());
11331 ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
11332 dl.getIROrder(), VTs, AM, IsTruncating, SVT, MMO));
11333 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11334 ID.AddInteger(MMO->getFlags());
11335 FoldingSetInsertToken InsertToken;
11336 if (SDNode *E = lookupNode(ID, dl, InsertToken)) {
11337 cast<StoreSDNode>(E)->refineAlignment(MMO);
11338 cast<StoreSDNode>(E)->refineMMOMetadata(MMO);
11339 return SDValue(E, 0);
11340 }
11341 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
11342 IsTruncating, SVT, MMO);
11343 createOperands(N, Ops);
11344
11345 CSEMap.insert(N, InsertToken);
11346 InsertNode(N);
11347 SDValue V(N, 0);
11348 NewSDValueDbgMsg(V, "Creating new node: ", this);
11349 return V;
11350}
11351
11353 SDValue Ptr, SDValue Offset,
11354 MachinePointerInfo PtrInfo, EVT SVT,
11355 Align Alignment,
11356 MachineMemOperand::Flags MMOFlags,
11357 const MMOMetadata &Metadata) {
11358 assert(Chain.getValueType() == MVT::Other &&
11359 "Invalid chain type");
11360
11361 MMOFlags |= MachineMemOperand::MOStore;
11362 assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
11363 assert(!Metadata.Ranges && "range metadata is invalid for stores");
11364
11365 if (PtrInfo.V.isNull())
11366 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
11367
11369 MachineMemOperand *MMO = MF.getMachineMemOperand(
11370 PtrInfo, MMOFlags, SVT.getStoreSize(), Alignment, Metadata);
11371 return getTruncStore(Chain, dl, Val, Ptr, Offset, SVT, MMO);
11372}
11373
11375 SDValue Ptr, MachinePointerInfo PtrInfo,
11376 EVT SVT, Align Alignment,
11377 MachineMemOperand::Flags MMOFlags,
11378 const MMOMetadata &Metadata) {
11379 return getTruncStore(Chain, dl, Val, Ptr, getPOISON(Ptr.getValueType()),
11380 PtrInfo, SVT, Alignment, MMOFlags, Metadata);
11381}
11382
11384 SDValue Ptr, SDValue Offset, EVT SVT,
11385 MachineMemOperand *MMO) {
11386 return getStore(Chain, dl, Val, Ptr, Offset, SVT, MMO, ISD::UNINDEXED, true);
11387}
11388
11390 SDValue Ptr, EVT SVT,
11391 MachineMemOperand *MMO) {
11392 return getStore(Chain, dl, Val, Ptr, getPOISON(Ptr.getValueType()), SVT, MMO,
11393 ISD::UNINDEXED, true);
11394}
11395
11399 StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
11400 assert(ST->getOffset().getOpcode() == ISD::POISON &&
11401 "Store is already a indexed store!");
11402 return getStore(ST->getChain(), dl, ST->getValue(), Base, Offset,
11403 ST->getMemoryVT(), ST->getMemOperand(), AM,
11404 ST->isTruncatingStore());
11405}
11406
11408 ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &dl,
11409 SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Mask, SDValue EVL,
11410 MachinePointerInfo PtrInfo, EVT MemVT, Align Alignment,
11411 MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
11412 const MDNode *Ranges, bool IsExpanding) {
11413 MMOFlags |= MachineMemOperand::MOLoad;
11414 assert((MMOFlags & MachineMemOperand::MOStore) == 0);
11415 // If we don't have a PtrInfo, infer the trivial frame index case to simplify
11416 // clients.
11417 if (PtrInfo.V.isNull())
11418 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
11419
11420 TypeSize Size = MemVT.getStoreSize();
11422 MachineMemOperand *MMO = MF.getMachineMemOperand(
11423 PtrInfo, MMOFlags, Size, Alignment, MMOMetadata(AAInfo, Ranges));
11424 return getLoadVP(AM, ExtType, VT, dl, Chain, Ptr, Offset, Mask, EVL, MemVT,
11425 MMO, IsExpanding);
11426}
11427
11429 ISD::LoadExtType ExtType, EVT VT,
11430 const SDLoc &dl, SDValue Chain, SDValue Ptr,
11431 SDValue Offset, SDValue Mask, SDValue EVL,
11432 EVT MemVT, MachineMemOperand *MMO,
11433 bool IsExpanding) {
11434 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
11435 assert(Mask.getValueType().getVectorElementCount() ==
11436 VT.getVectorElementCount() &&
11437 "Vector width mismatch between mask and data");
11438
11439 bool Indexed = AM != ISD::UNINDEXED;
11440 assert((Indexed || Offset.getOpcode() == ISD::POISON) &&
11441 "Unindexed load with an offset!");
11442
11443 SDVTList VTs = Indexed ? getVTList(VT, Ptr.getValueType(), MVT::Other)
11444 : getVTList(VT, MVT::Other);
11445 SDValue Ops[] = {Chain, Ptr, Offset, Mask, EVL};
11446 SDNodeKey ID(ISD::VP_LOAD, VTs, Ops);
11447 ID.AddInteger(MemVT.getRawBits());
11448 ID.AddInteger(getSyntheticNodeSubclassData<VPLoadSDNode>(
11449 dl.getIROrder(), VTs, AM, ExtType, IsExpanding, MemVT, MMO));
11450 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11451 ID.AddInteger(MMO->getFlags());
11452 FoldingSetInsertToken InsertToken;
11453 if (auto *E = cast_or_null<VPLoadSDNode>(lookupNode(ID, dl, InsertToken))) {
11454 E->refineAlignment(MMO);
11455 E->refineMMOMetadata(MMO);
11456 return SDValue(E, 0);
11457 }
11458 auto *N = newSDNode<VPLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
11459 ExtType, IsExpanding, MemVT, MMO);
11460 createOperands(N, Ops);
11461
11462 CSEMap.insert(N, InsertToken);
11463 InsertNode(N);
11464 SDValue V(N, 0);
11465 NewSDValueDbgMsg(V, "Creating new node: ", this);
11466 return V;
11467}
11468
11470 SDValue Ptr, SDValue Mask, SDValue EVL,
11471 MachinePointerInfo PtrInfo,
11472 MaybeAlign Alignment,
11473 MachineMemOperand::Flags MMOFlags,
11474 const AAMDNodes &AAInfo, const MDNode *Ranges,
11475 bool IsExpanding) {
11477 return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
11478 Mask, EVL, PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges,
11479 IsExpanding);
11480}
11481
11483 SDValue Ptr, SDValue Mask, SDValue EVL,
11484 MachineMemOperand *MMO, bool IsExpanding) {
11486 return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
11487 Mask, EVL, VT, MMO, IsExpanding);
11488}
11489
11491 EVT VT, SDValue Chain, SDValue Ptr,
11492 SDValue Mask, SDValue EVL,
11493 MachinePointerInfo PtrInfo, EVT MemVT,
11494 MaybeAlign Alignment,
11495 MachineMemOperand::Flags MMOFlags,
11496 const AAMDNodes &AAInfo, bool IsExpanding) {
11498 return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask,
11499 EVL, PtrInfo, MemVT, Alignment, MMOFlags, AAInfo, nullptr,
11500 IsExpanding);
11501}
11502
11504 EVT VT, SDValue Chain, SDValue Ptr,
11505 SDValue Mask, SDValue EVL, EVT MemVT,
11506 MachineMemOperand *MMO, bool IsExpanding) {
11508 return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask,
11509 EVL, MemVT, MMO, IsExpanding);
11510}
11511
11513 SDValue Ptr, SDValue Offset, SDValue Mask,
11514 SDValue EVL, EVT MemVT, MachineMemOperand *MMO,
11515 ISD::MemIndexedMode AM, bool IsTruncating,
11516 bool IsCompressing) {
11517 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
11518 assert(Mask.getValueType().getVectorElementCount() ==
11520 "Vector width mismatch between mask and data");
11521
11522 bool Indexed = AM != ISD::UNINDEXED;
11523 assert((Indexed || Offset.getOpcode() == ISD::POISON) &&
11524 "Unindexed vp_store with an offset!");
11525 SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other)
11526 : getVTList(MVT::Other);
11527 SDValue Ops[] = {Chain, Val, Ptr, Offset, Mask, EVL};
11528 SDNodeKey ID(ISD::VP_STORE, VTs, Ops);
11529 ID.AddInteger(MemVT.getRawBits());
11530 ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>(
11531 dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
11532 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11533 ID.AddInteger(MMO->getFlags());
11534 FoldingSetInsertToken InsertToken;
11535 if (SDNode *E = lookupNode(ID, dl, InsertToken)) {
11536 cast<VPStoreSDNode>(E)->refineAlignment(MMO);
11537 return SDValue(E, 0);
11538 }
11539 auto *N = newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
11540 IsTruncating, IsCompressing, MemVT, MMO);
11541 createOperands(N, Ops);
11542
11543 CSEMap.insert(N, InsertToken);
11544 InsertNode(N);
11545 SDValue V(N, 0);
11546 NewSDValueDbgMsg(V, "Creating new node: ", this);
11547 return V;
11548}
11549
11551 SDValue Val, SDValue Ptr, SDValue Mask,
11552 SDValue EVL, MachinePointerInfo PtrInfo,
11553 EVT SVT, Align Alignment,
11554 MachineMemOperand::Flags MMOFlags,
11555 const AAMDNodes &AAInfo,
11556 bool IsCompressing) {
11557 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
11558
11559 MMOFlags |= MachineMemOperand::MOStore;
11560 assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
11561
11562 if (PtrInfo.V.isNull())
11563 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
11564
11566 MachineMemOperand *MMO = MF.getMachineMemOperand(
11567 PtrInfo, MMOFlags, SVT.getStoreSize(), Alignment, AAInfo);
11568 return getTruncStoreVP(Chain, dl, Val, Ptr, Mask, EVL, SVT, MMO,
11569 IsCompressing);
11570}
11571
11573 SDValue Val, SDValue Ptr, SDValue Mask,
11574 SDValue EVL, EVT SVT,
11575 MachineMemOperand *MMO,
11576 bool IsCompressing) {
11577 EVT VT = Val.getValueType();
11578
11579 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
11580 if (VT == SVT)
11581 return getStoreVP(Chain, dl, Val, Ptr, getPOISON(Ptr.getValueType()), Mask,
11582 EVL, VT, MMO, ISD::UNINDEXED,
11583 /*IsTruncating*/ false, IsCompressing);
11584
11586 "Should only be a truncating store, not extending!");
11587 assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!");
11588 assert(VT.isVector() == SVT.isVector() &&
11589 "Cannot use trunc store to convert to or from a vector!");
11590 assert((!VT.isVector() ||
11592 "Cannot use trunc store to change the number of vector elements!");
11593
11594 SDVTList VTs = getVTList(MVT::Other);
11596 SDValue Ops[] = {Chain, Val, Ptr, Undef, Mask, EVL};
11597 SDNodeKey ID(ISD::VP_STORE, VTs, Ops);
11598 ID.AddInteger(SVT.getRawBits());
11599 ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>(
11600 dl.getIROrder(), VTs, ISD::UNINDEXED, true, IsCompressing, SVT, MMO));
11601 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11602 ID.AddInteger(MMO->getFlags());
11603 FoldingSetInsertToken InsertToken;
11604 if (SDNode *E = lookupNode(ID, dl, InsertToken)) {
11605 cast<VPStoreSDNode>(E)->refineAlignment(MMO);
11606 return SDValue(E, 0);
11607 }
11608 auto *N =
11609 newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
11610 ISD::UNINDEXED, true, IsCompressing, SVT, MMO);
11611 createOperands(N, Ops);
11612
11613 CSEMap.insert(N, InsertToken);
11614 InsertNode(N);
11615 SDValue V(N, 0);
11616 NewSDValueDbgMsg(V, "Creating new node: ", this);
11617 return V;
11618}
11619
11621 ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &DL,
11622 SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Stride, SDValue Mask,
11623 SDValue EVL, EVT MemVT, MachineMemOperand *MMO, bool IsExpanding) {
11624 bool Indexed = AM != ISD::UNINDEXED;
11625 assert((Indexed || Offset.getOpcode() == ISD::POISON) &&
11626 "Unindexed load with an offset!");
11627
11628 SDValue Ops[] = {Chain, Ptr, Offset, Stride, Mask, EVL};
11629 SDVTList VTs = Indexed ? getVTList(VT, Ptr.getValueType(), MVT::Other)
11630 : getVTList(VT, MVT::Other);
11631 SDNodeKey ID(ISD::EXPERIMENTAL_VP_STRIDED_LOAD, VTs, Ops);
11632 ID.AddInteger(MemVT.getRawBits());
11633 ID.AddInteger(getSyntheticNodeSubclassData<VPStridedLoadSDNode>(
11634 DL.getIROrder(), VTs, AM, ExtType, IsExpanding, MemVT, MMO));
11635 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11636
11637 FoldingSetInsertToken InsertToken;
11638 if (SDNode *E = lookupNode(ID, DL, InsertToken)) {
11639 cast<VPStridedLoadSDNode>(E)->refineAlignment(MMO);
11640 return SDValue(E, 0);
11641 }
11642
11643 auto *N =
11644 newSDNode<VPStridedLoadSDNode>(DL.getIROrder(), DL.getDebugLoc(), VTs, AM,
11645 ExtType, IsExpanding, MemVT, MMO);
11646 createOperands(N, Ops);
11647 CSEMap.insert(N, InsertToken);
11648 InsertNode(N);
11649 SDValue V(N, 0);
11650 NewSDValueDbgMsg(V, "Creating new node: ", this);
11651 return V;
11652}
11653
11655 SDValue Ptr, SDValue Stride,
11656 SDValue Mask, SDValue EVL,
11657 MachineMemOperand *MMO,
11658 bool IsExpanding) {
11660 return getStridedLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, DL, Chain, Ptr,
11661 Undef, Stride, Mask, EVL, VT, MMO, IsExpanding);
11662}
11663
11665 ISD::LoadExtType ExtType, const SDLoc &DL, EVT VT, SDValue Chain,
11666 SDValue Ptr, SDValue Stride, SDValue Mask, SDValue EVL, EVT MemVT,
11667 MachineMemOperand *MMO, bool IsExpanding) {
11669 return getStridedLoadVP(ISD::UNINDEXED, ExtType, VT, DL, Chain, Ptr, Undef,
11670 Stride, Mask, EVL, MemVT, MMO, IsExpanding);
11671}
11672
11674 SDValue Val, SDValue Ptr,
11675 SDValue Offset, SDValue Stride,
11676 SDValue Mask, SDValue EVL, EVT MemVT,
11677 MachineMemOperand *MMO,
11679 bool IsTruncating, bool IsCompressing) {
11680 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
11681 bool Indexed = AM != ISD::UNINDEXED;
11682 assert((Indexed || Offset.getOpcode() == ISD::POISON) &&
11683 "Unindexed vp_store with an offset!");
11684 SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other)
11685 : getVTList(MVT::Other);
11686 SDValue Ops[] = {Chain, Val, Ptr, Offset, Stride, Mask, EVL};
11687 SDNodeKey ID(ISD::EXPERIMENTAL_VP_STRIDED_STORE, VTs, Ops);
11688 ID.AddInteger(MemVT.getRawBits());
11689 ID.AddInteger(getSyntheticNodeSubclassData<VPStridedStoreSDNode>(
11690 DL.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
11691 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11692 FoldingSetInsertToken InsertToken;
11693 if (SDNode *E = lookupNode(ID, DL, InsertToken)) {
11694 cast<VPStridedStoreSDNode>(E)->refineAlignment(MMO);
11695 return SDValue(E, 0);
11696 }
11697 auto *N = newSDNode<VPStridedStoreSDNode>(DL.getIROrder(), DL.getDebugLoc(),
11698 VTs, AM, IsTruncating,
11699 IsCompressing, MemVT, MMO);
11700 createOperands(N, Ops);
11701
11702 CSEMap.insert(N, InsertToken);
11703 InsertNode(N);
11704 SDValue V(N, 0);
11705 NewSDValueDbgMsg(V, "Creating new node: ", this);
11706 return V;
11707}
11708
11711 ISD::MemIndexType IndexType) {
11712 assert(Ops.size() == 6 && "Incompatible number of operands");
11713
11714 SDNodeKey ID(ISD::VP_GATHER, VTs, Ops);
11715 ID.AddInteger(VT.getRawBits());
11716 ID.AddInteger(getSyntheticNodeSubclassData<VPGatherSDNode>(
11717 dl.getIROrder(), VTs, VT, MMO, IndexType));
11718 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11719 ID.AddInteger(MMO->getFlags());
11720 FoldingSetInsertToken InsertToken;
11721 if (SDNode *E = lookupNode(ID, dl, InsertToken)) {
11722 cast<VPGatherSDNode>(E)->refineAlignment(MMO);
11723 return SDValue(E, 0);
11724 }
11725
11726 auto *N = newSDNode<VPGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
11727 VT, MMO, IndexType);
11728 createOperands(N, Ops);
11729
11730 assert(N->getMask().getValueType().getVectorElementCount() ==
11731 N->getValueType(0).getVectorElementCount() &&
11732 "Vector width mismatch between mask and data");
11733 assert(N->getIndex().getValueType().getVectorElementCount().isScalable() ==
11734 N->getValueType(0).getVectorElementCount().isScalable() &&
11735 "Scalable flags of index and data do not match");
11737 N->getIndex().getValueType().getVectorElementCount(),
11738 N->getValueType(0).getVectorElementCount()) &&
11739 "Vector width mismatch between index and data");
11740 assert(isa<ConstantSDNode>(N->getScale()) &&
11741 N->getScale()->getAsAPIntVal().isPowerOf2() &&
11742 "Scale should be a constant power of 2");
11743
11744 CSEMap.insert(N, InsertToken);
11745 InsertNode(N);
11746 SDValue V(N, 0);
11747 NewSDValueDbgMsg(V, "Creating new node: ", this);
11748 return V;
11749}
11750
11753 MachineMemOperand *MMO,
11754 ISD::MemIndexType IndexType) {
11755 assert(Ops.size() == 7 && "Incompatible number of operands");
11756
11757 SDNodeKey ID(ISD::VP_SCATTER, VTs, Ops);
11758 ID.AddInteger(VT.getRawBits());
11759 ID.AddInteger(getSyntheticNodeSubclassData<VPScatterSDNode>(
11760 dl.getIROrder(), VTs, VT, MMO, IndexType));
11761 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11762 ID.AddInteger(MMO->getFlags());
11763 FoldingSetInsertToken InsertToken;
11764 if (SDNode *E = lookupNode(ID, dl, InsertToken)) {
11765 cast<VPScatterSDNode>(E)->refineAlignment(MMO);
11766 return SDValue(E, 0);
11767 }
11768 auto *N = newSDNode<VPScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
11769 VT, MMO, IndexType);
11770 createOperands(N, Ops);
11771
11772 assert(N->getMask().getValueType().getVectorElementCount() ==
11773 N->getValue().getValueType().getVectorElementCount() &&
11774 "Vector width mismatch between mask and data");
11775 assert(
11776 N->getIndex().getValueType().getVectorElementCount().isScalable() ==
11777 N->getValue().getValueType().getVectorElementCount().isScalable() &&
11778 "Scalable flags of index and data do not match");
11780 N->getIndex().getValueType().getVectorElementCount(),
11781 N->getValue().getValueType().getVectorElementCount()) &&
11782 "Vector width mismatch between index and data");
11783 assert(isa<ConstantSDNode>(N->getScale()) &&
11784 N->getScale()->getAsAPIntVal().isPowerOf2() &&
11785 "Scale should be a constant power of 2");
11786
11787 CSEMap.insert(N, InsertToken);
11788 InsertNode(N);
11789 SDValue V(N, 0);
11790 NewSDValueDbgMsg(V, "Creating new node: ", this);
11791 return V;
11792}
11793
11796 SDValue PassThru, EVT MemVT,
11797 MachineMemOperand *MMO,
11799 ISD::LoadExtType ExtTy, bool isExpanding) {
11800 bool Indexed = AM != ISD::UNINDEXED;
11801 assert((Indexed || Offset.getOpcode() == ISD::POISON) &&
11802 "Unindexed masked load with an offset!");
11803 SDVTList VTs = Indexed ? getVTList(VT, Base.getValueType(), MVT::Other)
11804 : getVTList(VT, MVT::Other);
11805 SDValue Ops[] = {Chain, Base, Offset, Mask, PassThru};
11806 SDNodeKey ID(ISD::MLOAD, VTs, Ops);
11807 ID.AddInteger(MemVT.getRawBits());
11808 ID.AddInteger(getSyntheticNodeSubclassData<MaskedLoadSDNode>(
11809 dl.getIROrder(), VTs, AM, ExtTy, isExpanding, MemVT, MMO));
11810 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11811 ID.AddInteger(MMO->getFlags());
11812 FoldingSetInsertToken InsertToken;
11813 if (SDNode *E = lookupNode(ID, dl, InsertToken)) {
11814 cast<MaskedLoadSDNode>(E)->refineAlignment(MMO);
11815 return SDValue(E, 0);
11816 }
11817 auto *N = newSDNode<MaskedLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
11818 AM, ExtTy, isExpanding, MemVT, MMO);
11819 createOperands(N, Ops);
11820
11821 CSEMap.insert(N, InsertToken);
11822 InsertNode(N);
11823 SDValue V(N, 0);
11824 NewSDValueDbgMsg(V, "Creating new node: ", this);
11825 return V;
11826}
11827
11832 assert(LD->getOffset().getOpcode() == ISD::POISON &&
11833 "Masked load is already a indexed load!");
11834 return getMaskedLoad(OrigLoad.getValueType(), dl, LD->getChain(), Base,
11835 Offset, LD->getMask(), LD->getPassThru(),
11836 LD->getMemoryVT(), LD->getMemOperand(), AM,
11837 LD->getExtensionType(), LD->isExpandingLoad());
11838}
11839
11842 SDValue Mask, EVT MemVT,
11843 MachineMemOperand *MMO,
11844 ISD::MemIndexedMode AM, bool IsTruncating,
11845 bool IsCompressing) {
11846 assert(Chain.getValueType() == MVT::Other &&
11847 "Invalid chain type");
11848 bool Indexed = AM != ISD::UNINDEXED;
11849 assert((Indexed || Offset.getOpcode() == ISD::POISON) &&
11850 "Unindexed masked store with an offset!");
11851 SDVTList VTs = Indexed ? getVTList(Base.getValueType(), MVT::Other)
11852 : getVTList(MVT::Other);
11853 SDValue Ops[] = {Chain, Val, Base, Offset, Mask};
11854 SDNodeKey ID(ISD::MSTORE, VTs, Ops);
11855 ID.AddInteger(MemVT.getRawBits());
11856 ID.AddInteger(getSyntheticNodeSubclassData<MaskedStoreSDNode>(
11857 dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
11858 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11859 ID.AddInteger(MMO->getFlags());
11860 FoldingSetInsertToken InsertToken;
11861 if (SDNode *E = lookupNode(ID, dl, InsertToken)) {
11862 cast<MaskedStoreSDNode>(E)->refineAlignment(MMO);
11863 return SDValue(E, 0);
11864 }
11865 auto *N =
11866 newSDNode<MaskedStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
11867 IsTruncating, IsCompressing, MemVT, MMO);
11868 createOperands(N, Ops);
11869
11870 CSEMap.insert(N, InsertToken);
11871 InsertNode(N);
11872 SDValue V(N, 0);
11873 NewSDValueDbgMsg(V, "Creating new node: ", this);
11874 return V;
11875}
11876
11881 assert(ST->getOffset().getOpcode() == ISD::POISON &&
11882 "Masked store is already a indexed store!");
11883 return getMaskedStore(ST->getChain(), dl, ST->getValue(), Base, Offset,
11884 ST->getMask(), ST->getMemoryVT(), ST->getMemOperand(),
11885 AM, ST->isTruncatingStore(), ST->isCompressingStore());
11886}
11887
11890 MachineMemOperand *MMO,
11891 ISD::MemIndexType IndexType,
11892 ISD::LoadExtType ExtTy) {
11893 assert(Ops.size() == 6 && "Incompatible number of operands");
11894
11895 SDNodeKey ID(ISD::MGATHER, VTs, Ops);
11896 ID.AddInteger(MemVT.getRawBits());
11897 ID.AddInteger(getSyntheticNodeSubclassData<MaskedGatherSDNode>(
11898 dl.getIROrder(), VTs, MemVT, MMO, IndexType, ExtTy));
11899 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11900 ID.AddInteger(MMO->getFlags());
11901 FoldingSetInsertToken InsertToken;
11902 if (SDNode *E = lookupNode(ID, dl, InsertToken)) {
11903 cast<MaskedGatherSDNode>(E)->refineAlignment(MMO);
11904 return SDValue(E, 0);
11905 }
11906
11907 auto *N = newSDNode<MaskedGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(),
11908 VTs, MemVT, MMO, IndexType, ExtTy);
11909 createOperands(N, Ops);
11910
11911 assert(N->getPassThru().getValueType() == N->getValueType(0) &&
11912 "Incompatible type of the PassThru value in MaskedGatherSDNode");
11913 assert(N->getMask().getValueType().getVectorElementCount() ==
11914 N->getValueType(0).getVectorElementCount() &&
11915 "Vector width mismatch between mask and data");
11916 assert(N->getIndex().getValueType().getVectorElementCount().isScalable() ==
11917 N->getValueType(0).getVectorElementCount().isScalable() &&
11918 "Scalable flags of index and data do not match");
11920 N->getIndex().getValueType().getVectorElementCount(),
11921 N->getValueType(0).getVectorElementCount()) &&
11922 "Vector width mismatch between index and data");
11923 assert(isa<ConstantSDNode>(N->getScale()) &&
11924 N->getScale()->getAsAPIntVal().isPowerOf2() &&
11925 "Scale should be a constant power of 2");
11926
11927 CSEMap.insert(N, InsertToken);
11928 InsertNode(N);
11929 SDValue V(N, 0);
11930 NewSDValueDbgMsg(V, "Creating new node: ", this);
11931 return V;
11932}
11933
11936 MachineMemOperand *MMO,
11937 ISD::MemIndexType IndexType,
11938 bool IsTrunc) {
11939 assert(Ops.size() == 6 && "Incompatible number of operands");
11940
11941 SDNodeKey ID(ISD::MSCATTER, VTs, Ops);
11942 ID.AddInteger(MemVT.getRawBits());
11943 ID.AddInteger(getSyntheticNodeSubclassData<MaskedScatterSDNode>(
11944 dl.getIROrder(), VTs, MemVT, MMO, IndexType, IsTrunc));
11945 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11946 ID.AddInteger(MMO->getFlags());
11947 FoldingSetInsertToken InsertToken;
11948 if (SDNode *E = lookupNode(ID, dl, InsertToken)) {
11949 cast<MaskedScatterSDNode>(E)->refineAlignment(MMO);
11950 return SDValue(E, 0);
11951 }
11952
11953 auto *N = newSDNode<MaskedScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(),
11954 VTs, MemVT, MMO, IndexType, IsTrunc);
11955 createOperands(N, Ops);
11956
11957 assert(N->getMask().getValueType().getVectorElementCount() ==
11958 N->getValue().getValueType().getVectorElementCount() &&
11959 "Vector width mismatch between mask and data");
11960 assert(
11961 N->getIndex().getValueType().getVectorElementCount().isScalable() ==
11962 N->getValue().getValueType().getVectorElementCount().isScalable() &&
11963 "Scalable flags of index and data do not match");
11965 N->getIndex().getValueType().getVectorElementCount(),
11966 N->getValue().getValueType().getVectorElementCount()) &&
11967 "Vector width mismatch between index and data");
11968 assert(isa<ConstantSDNode>(N->getScale()) &&
11969 N->getScale()->getAsAPIntVal().isPowerOf2() &&
11970 "Scale should be a constant power of 2");
11971
11972 CSEMap.insert(N, InsertToken);
11973 InsertNode(N);
11974 SDValue V(N, 0);
11975 NewSDValueDbgMsg(V, "Creating new node: ", this);
11976 return V;
11977}
11978
11980 const SDLoc &dl, ArrayRef<SDValue> Ops,
11981 MachineMemOperand *MMO,
11982 ISD::MemIndexType IndexType) {
11983 assert(Ops.size() == 7 && "Incompatible number of operands");
11984
11986 ID.AddInteger(MemVT.getRawBits());
11987 ID.AddInteger(getSyntheticNodeSubclassData<MaskedHistogramSDNode>(
11988 dl.getIROrder(), VTs, MemVT, MMO, IndexType));
11989 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11990 ID.AddInteger(MMO->getFlags());
11991 FoldingSetInsertToken InsertToken;
11992 if (SDNode *E = lookupNode(ID, dl, InsertToken)) {
11993 cast<MaskedGatherSDNode>(E)->refineAlignment(MMO);
11994 return SDValue(E, 0);
11995 }
11996
11997 auto *N = newSDNode<MaskedHistogramSDNode>(dl.getIROrder(), dl.getDebugLoc(),
11998 VTs, MemVT, MMO, IndexType);
11999 createOperands(N, Ops);
12000
12001 assert(N->getMask().getValueType().getVectorElementCount() ==
12002 N->getIndex().getValueType().getVectorElementCount() &&
12003 "Vector width mismatch between mask and data");
12004 assert(isa<ConstantSDNode>(N->getScale()) &&
12005 N->getScale()->getAsAPIntVal().isPowerOf2() &&
12006 "Scale should be a constant power of 2");
12007 assert(N->getInc().getValueType().isInteger() && "Non integer update value");
12008
12009 CSEMap.insert(N, InsertToken);
12010 InsertNode(N);
12011 SDValue V(N, 0);
12012 NewSDValueDbgMsg(V, "Creating new node: ", this);
12013 return V;
12014}
12015
12017 SDValue Ptr, SDValue Mask, SDValue EVL,
12018 MachineMemOperand *MMO) {
12019 SDVTList VTs = getVTList(VT, EVL.getValueType(), MVT::Other);
12020 SDValue Ops[] = {Chain, Ptr, Mask, EVL};
12021 SDNodeKey ID(ISD::VP_LOAD_FF, VTs, Ops);
12022 ID.AddInteger(VT.getRawBits());
12023 ID.AddInteger(getSyntheticNodeSubclassData<VPLoadFFSDNode>(DL.getIROrder(),
12024 VTs, VT, MMO));
12025 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
12026 ID.AddInteger(MMO->getFlags());
12027 FoldingSetInsertToken InsertToken;
12028 if (SDNode *E = lookupNode(ID, DL, InsertToken)) {
12029 cast<VPLoadFFSDNode>(E)->refineAlignment(MMO);
12030 return SDValue(E, 0);
12031 }
12032 auto *N = newSDNode<VPLoadFFSDNode>(DL.getIROrder(), DL.getDebugLoc(), VTs,
12033 VT, MMO);
12034 createOperands(N, Ops);
12035
12036 CSEMap.insert(N, InsertToken);
12037 InsertNode(N);
12038 SDValue V(N, 0);
12039 NewSDValueDbgMsg(V, "Creating new node: ", this);
12040 return V;
12041}
12042
12044 EVT MemVT, MachineMemOperand *MMO) {
12045 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
12046 SDVTList VTs = getVTList(MVT::Other);
12047 SDValue Ops[] = {Chain, Ptr};
12049 ID.AddInteger(MemVT.getRawBits());
12050 ID.AddInteger(getSyntheticNodeSubclassData<FPStateAccessSDNode>(
12051 ISD::GET_FPENV_MEM, dl.getIROrder(), VTs, MemVT, MMO));
12052 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
12053 ID.AddInteger(MMO->getFlags());
12054 FoldingSetInsertToken InsertToken;
12055 if (SDNode *E = lookupNode(ID, dl, InsertToken))
12056 return SDValue(E, 0);
12057
12058 auto *N = newSDNode<FPStateAccessSDNode>(ISD::GET_FPENV_MEM, dl.getIROrder(),
12059 dl.getDebugLoc(), VTs, MemVT, MMO);
12060 createOperands(N, Ops);
12061
12062 CSEMap.insert(N, InsertToken);
12063 InsertNode(N);
12064 SDValue V(N, 0);
12065 NewSDValueDbgMsg(V, "Creating new node: ", this);
12066 return V;
12067}
12068
12070 EVT MemVT, MachineMemOperand *MMO) {
12071 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
12072 SDVTList VTs = getVTList(MVT::Other);
12073 SDValue Ops[] = {Chain, Ptr};
12075 ID.AddInteger(MemVT.getRawBits());
12076 ID.AddInteger(getSyntheticNodeSubclassData<FPStateAccessSDNode>(
12077 ISD::SET_FPENV_MEM, dl.getIROrder(), VTs, MemVT, MMO));
12078 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
12079 ID.AddInteger(MMO->getFlags());
12080 FoldingSetInsertToken InsertToken;
12081 if (SDNode *E = lookupNode(ID, dl, InsertToken))
12082 return SDValue(E, 0);
12083
12084 auto *N = newSDNode<FPStateAccessSDNode>(ISD::SET_FPENV_MEM, dl.getIROrder(),
12085 dl.getDebugLoc(), VTs, MemVT, MMO);
12086 createOperands(N, Ops);
12087
12088 CSEMap.insert(N, InsertToken);
12089 InsertNode(N);
12090 SDValue V(N, 0);
12091 NewSDValueDbgMsg(V, "Creating new node: ", this);
12092 return V;
12093}
12094
12096 // select undef, T, F --> T (if T is a constant), otherwise F
12097 // select, ?, undef, F --> F
12098 // select, ?, T, undef --> T
12099 if (Cond.isUndef())
12100 return isConstantValueOfAnyType(T) ? T : F;
12101 if (T.isUndef())
12103 if (F.isUndef())
12105
12106 // select true, T, F --> T
12107 // select false, T, F --> F
12108 if (auto C = isBoolConstant(Cond))
12109 return *C ? T : F;
12110
12111 // select ?, T, T --> T
12112 if (T == F)
12113 return T;
12114
12115 return SDValue();
12116}
12117
12119 // shift undef, Y --> 0 (can always assume that the undef value is 0)
12120 if (X.isUndef())
12121 return getConstant(0, SDLoc(X.getNode()), X.getValueType());
12122 // shift X, undef --> undef (because it may shift by the bitwidth)
12123 if (Y.isUndef())
12124 return getUNDEF(X.getValueType());
12125
12126 // shift 0, Y --> 0
12127 // shift X, 0 --> X
12129 return X;
12130
12131 // shift X, C >= bitwidth(X) --> undef
12132 // All vector elements must be too big (or undef) to avoid partial undefs.
12133 auto isShiftTooBig = [X](ConstantSDNode *Val) {
12134 return !Val || Val->getAPIntValue().uge(X.getScalarValueSizeInBits());
12135 };
12136 if (ISD::matchUnaryPredicate(Y, isShiftTooBig, true))
12137 return getUNDEF(X.getValueType());
12138
12139 // shift i1/vXi1 X, Y --> X (any non-zero shift amount is undefined).
12140 if (X.getValueType().getScalarType() == MVT::i1)
12141 return X;
12142
12143 return SDValue();
12144}
12145
12147 SDNodeFlags Flags) {
12148 // If this operation has 'nnan' or 'ninf' and at least 1 disallowed operand
12149 // (an undef operand can be chosen to be Nan/Inf), then the result of this
12150 // operation is poison. That result can be relaxed to undef.
12151 ConstantFPSDNode *XC = isConstOrConstSplatFP(X, /* AllowUndefs */ true);
12152 ConstantFPSDNode *YC = isConstOrConstSplatFP(Y, /* AllowUndefs */ true);
12153 bool HasNan = (XC && XC->getValueAPF().isNaN()) ||
12154 (YC && YC->getValueAPF().isNaN());
12155 bool HasInf = (XC && XC->getValueAPF().isInfinity()) ||
12156 (YC && YC->getValueAPF().isInfinity());
12157
12158 if (Flags.hasNoNaNs() && (HasNan || X.isUndef() || Y.isUndef()))
12159 return getUNDEF(X.getValueType());
12160
12161 if (Flags.hasNoInfs() && (HasInf || X.isUndef() || Y.isUndef()))
12162 return getUNDEF(X.getValueType());
12163
12164 if (!YC)
12165 return SDValue();
12166
12167 // X + -0.0 --> X
12168 if (Opcode == ISD::FADD)
12169 if (YC->getValueAPF().isNegZero())
12170 return X;
12171
12172 // X - +0.0 --> X
12173 if (Opcode == ISD::FSUB)
12174 if (YC->getValueAPF().isPosZero())
12175 return X;
12176
12177 // X * 1.0 --> X
12178 // X / 1.0 --> X
12179 if (Opcode == ISD::FMUL || Opcode == ISD::FDIV)
12180 if (YC->getValueAPF().isOne())
12181 return X;
12182
12183 // X * 0.0 --> 0.0
12184 if (Opcode == ISD::FMUL && Flags.hasNoNaNs() && Flags.hasNoSignedZeros())
12185 if (YC->getValueAPF().isZero())
12186 return getConstantFP(0.0, SDLoc(Y), Y.getValueType());
12187
12188 return SDValue();
12189}
12190
12192 SDValue Ptr, SDValue SV, unsigned Align) {
12193 SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, dl, MVT::i32) };
12194 return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops);
12195}
12196
12197SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
12199 switch (Ops.size()) {
12200 case 0: return getNode(Opcode, DL, VT);
12201 case 1: return getNode(Opcode, DL, VT, Ops[0].get());
12202 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
12203 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
12204 default: break;
12205 }
12206
12207 // Copy from an SDUse array into an SDValue array for use with
12208 // the regular getNode logic.
12210 return getNode(Opcode, DL, VT, NewOps);
12211}
12212
12213SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
12215 SDNodeFlags Flags;
12216 if (Inserter)
12217 Flags = Inserter->getFlags();
12218 return getNode(Opcode, DL, VT, Ops, Flags);
12219}
12220
12221SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
12222 ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
12223 unsigned NumOps = Ops.size();
12224 switch (NumOps) {
12225 case 0: return getNode(Opcode, DL, VT);
12226 case 1: return getNode(Opcode, DL, VT, Ops[0], Flags);
12227 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Flags);
12228 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2], Flags);
12229 default: break;
12230 }
12231
12232#ifndef NDEBUG
12233 for (const auto &Op : Ops)
12234 assert(Op.getOpcode() != ISD::DELETED_NODE &&
12235 "Operand is DELETED_NODE!");
12236#endif
12237
12238 switch (Opcode) {
12239 default: break;
12240 case ISD::BUILD_VECTOR:
12241 // Attempt to simplify BUILD_VECTOR.
12242 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
12243 return V;
12244 break;
12246 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
12247 return V;
12248 break;
12249 case ISD::SELECT_CC:
12250 assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
12251 assert(Ops[0].getValueType() == Ops[1].getValueType() &&
12252 "LHS and RHS of condition must have same type!");
12253 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
12254 "True and False arms of SelectCC must have same type!");
12255 assert(Ops[2].getValueType() == VT &&
12256 "select_cc node must be of same type as true and false value!");
12257 assert((!Ops[0].getValueType().isVector() ||
12258 Ops[0].getValueType().getVectorElementCount() ==
12259 VT.getVectorElementCount()) &&
12260 "Expected select_cc with vector result to have the same sized "
12261 "comparison type!");
12262 break;
12263 case ISD::BR_CC:
12264 assert(NumOps == 5 && "BR_CC takes 5 operands!");
12265 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
12266 "LHS/RHS of comparison should match types!");
12267 break;
12268 case ISD::VP_REDUCE_MUL:
12269 // If it is VP_REDUCE_MUL mask operation then turn it to VP_REDUCE_AND
12270 if (VT == MVT::i1)
12271 Opcode = ISD::VP_REDUCE_AND;
12272 break;
12273 case ISD::VP_REDUCE_ADD:
12274 // If it is VP_REDUCE_ADD mask operation then turn it to VP_REDUCE_XOR
12275 if (VT == MVT::i1)
12276 Opcode = ISD::VP_REDUCE_XOR;
12277 break;
12278 case ISD::VP_REDUCE_SMAX:
12279 case ISD::VP_REDUCE_UMIN:
12280 // If it is VP_REDUCE_SMAX/VP_REDUCE_UMIN mask operation then turn it to
12281 // VP_REDUCE_AND.
12282 if (VT == MVT::i1)
12283 Opcode = ISD::VP_REDUCE_AND;
12284 break;
12285 case ISD::VP_REDUCE_SMIN:
12286 case ISD::VP_REDUCE_UMAX:
12287 // If it is VP_REDUCE_SMIN/VP_REDUCE_UMAX mask operation then turn it to
12288 // VP_REDUCE_OR.
12289 if (VT == MVT::i1)
12290 Opcode = ISD::VP_REDUCE_OR;
12291 break;
12292 }
12293
12294 // Memoize nodes.
12295 SDNode *N;
12296 SDVTList VTs = getVTList(VT);
12297
12298 if (VT != MVT::Glue) {
12299 SDNodeKey ID(Opcode, VTs, Ops);
12300 FoldingSetInsertToken InsertToken;
12301
12302 if (SDNode *E = lookupNode(ID, DL, InsertToken)) {
12303 E->intersectFlagsWith(Flags);
12304 return SDValue(E, 0);
12305 }
12306
12307 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
12308 createOperands(N, Ops);
12309
12310 CSEMap.insert(N, InsertToken);
12311 } else {
12312 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
12313 createOperands(N, Ops);
12314 }
12315
12316 N->setFlags(Flags);
12317 InsertNode(N);
12318 SDValue V(N, 0);
12319 NewSDValueDbgMsg(V, "Creating new node: ", this);
12320 return V;
12321}
12322
12323SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
12324 ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) {
12325 SDNodeFlags Flags;
12326 if (Inserter)
12327 Flags = Inserter->getFlags();
12328 return getNode(Opcode, DL, getVTList(ResultTys), Ops, Flags);
12329}
12330
12331SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
12333 const SDNodeFlags Flags) {
12334 return getNode(Opcode, DL, getVTList(ResultTys), Ops, Flags);
12335}
12336
12337SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
12339 SDNodeFlags Flags;
12340 if (Inserter)
12341 Flags = Inserter->getFlags();
12342 return getNode(Opcode, DL, VTList, Ops, Flags);
12343}
12344
12345SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
12346 ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
12347 if (VTList.NumVTs == 1)
12348 return getNode(Opcode, DL, VTList.VTs[0], Ops, Flags);
12349
12350#ifndef NDEBUG
12351 for (const auto &Op : Ops)
12352 assert(Op.getOpcode() != ISD::DELETED_NODE &&
12353 "Operand is DELETED_NODE!");
12354#endif
12355
12356 if (SDValue V = FoldConstantArithmetic(Opcode, DL, VTList, Ops, Flags))
12357 return V;
12358
12359 switch (Opcode) {
12360 case ISD::SADDO:
12361 case ISD::UADDO:
12362 case ISD::SSUBO:
12363 case ISD::USUBO: {
12364 assert(VTList.NumVTs == 2 && Ops.size() == 2 &&
12365 "Invalid add/sub overflow op!");
12366 assert(VTList.VTs[0].isInteger() && VTList.VTs[1].isInteger() &&
12367 Ops[0].getValueType() == Ops[1].getValueType() &&
12368 Ops[0].getValueType() == VTList.VTs[0] &&
12369 "Binary operator types must match!");
12370 SDValue N1 = Ops[0], N2 = Ops[1];
12371 canonicalizeCommutativeBinop(Opcode, N1, N2);
12372
12373 // (X +- 0) -> X with zero-overflow.
12374 ConstantSDNode *N2CV = isConstOrConstSplat(N2, /*AllowUndefs*/ false,
12375 /*AllowTruncation*/ true);
12376 if (N2CV && N2CV->isZero()) {
12377 SDValue ZeroOverFlow = getConstant(0, DL, VTList.VTs[1]);
12378 return getNode(ISD::MERGE_VALUES, DL, VTList, {N1, ZeroOverFlow}, Flags);
12379 }
12380
12381 if (VTList.VTs[0].getScalarType() == MVT::i1 &&
12382 VTList.VTs[1].getScalarType() == MVT::i1) {
12383 SDValue F1 = getFreeze(N1);
12384 SDValue F2 = getFreeze(N2);
12385 // {vXi1,vXi1} (u/s)addo(vXi1 x, vXi1y) -> {xor(x,y),and(x,y)}
12386 if (Opcode == ISD::UADDO || Opcode == ISD::SADDO)
12387 return getNode(ISD::MERGE_VALUES, DL, VTList,
12388 {getNode(ISD::XOR, DL, VTList.VTs[0], F1, F2),
12389 getNode(ISD::AND, DL, VTList.VTs[1], F1, F2)},
12390 Flags);
12391 // {vXi1,vXi1} (u/s)subo(vXi1 x, vXi1y) -> {xor(x,y),and(~x,y)}
12392 if (Opcode == ISD::USUBO || Opcode == ISD::SSUBO) {
12393 SDValue NotF1 = getNOT(DL, F1, VTList.VTs[0]);
12394 return getNode(ISD::MERGE_VALUES, DL, VTList,
12395 {getNode(ISD::XOR, DL, VTList.VTs[0], F1, F2),
12396 getNode(ISD::AND, DL, VTList.VTs[1], NotF1, F2)},
12397 Flags);
12398 }
12399 }
12400 break;
12401 }
12402 case ISD::SADDO_CARRY:
12403 case ISD::UADDO_CARRY:
12404 case ISD::SSUBO_CARRY:
12405 case ISD::USUBO_CARRY:
12406 assert(VTList.NumVTs == 2 && Ops.size() == 3 &&
12407 "Invalid add/sub overflow op!");
12408 assert(VTList.VTs[0].isInteger() && VTList.VTs[1].isInteger() &&
12409 Ops[0].getValueType() == Ops[1].getValueType() &&
12410 Ops[0].getValueType() == VTList.VTs[0] &&
12411 Ops[2].getValueType() == VTList.VTs[1] &&
12412 "Binary operator types must match!");
12413 break;
12414 case ISD::SMUL_LOHI:
12415 case ISD::UMUL_LOHI: {
12416 assert(VTList.NumVTs == 2 && Ops.size() == 2 && "Invalid mul lo/hi op!");
12417 assert(VTList.VTs[0].isInteger() && VTList.VTs[0] == VTList.VTs[1] &&
12418 VTList.VTs[0] == Ops[0].getValueType() &&
12419 VTList.VTs[0] == Ops[1].getValueType() &&
12420 "Binary operator types must match!");
12421 break;
12422 }
12423 case ISD::FFREXP: {
12424 assert(VTList.NumVTs == 2 && Ops.size() == 1 && "Invalid ffrexp op!");
12425 assert(VTList.VTs[0].isFloatingPoint() && VTList.VTs[1].isInteger() &&
12426 VTList.VTs[0] == Ops[0].getValueType() && "frexp type mismatch");
12427
12429 int FrexpExp;
12430 APFloat FrexpMant =
12431 frexp(C->getValueAPF(), FrexpExp, APFloat::rmNearestTiesToEven);
12432 SDValue Result0 = getConstantFP(FrexpMant, DL, VTList.VTs[0]);
12433 SDValue Result1 = getSignedConstant(FrexpMant.isFinite() ? FrexpExp : 0,
12434 DL, VTList.VTs[1]);
12435 return getNode(ISD::MERGE_VALUES, DL, VTList, {Result0, Result1}, Flags);
12436 }
12437
12438 break;
12439 }
12441 assert(VTList.NumVTs == 2 && Ops.size() == 2 &&
12442 "Invalid STRICT_FP_EXTEND!");
12443 assert(VTList.VTs[0].isFloatingPoint() &&
12444 Ops[1].getValueType().isFloatingPoint() && "Invalid FP cast!");
12445 assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
12446 "STRICT_FP_EXTEND result type should be vector iff the operand "
12447 "type is vector!");
12448 assert((!VTList.VTs[0].isVector() ||
12449 VTList.VTs[0].getVectorElementCount() ==
12450 Ops[1].getValueType().getVectorElementCount()) &&
12451 "Vector element count mismatch!");
12452 assert(Ops[1].getValueType().bitsLT(VTList.VTs[0]) &&
12453 "Invalid fpext node, dst <= src!");
12454 break;
12456 assert(VTList.NumVTs == 2 && Ops.size() == 3 && "Invalid STRICT_FP_ROUND!");
12457 assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
12458 "STRICT_FP_ROUND result type should be vector iff the operand "
12459 "type is vector!");
12460 assert((!VTList.VTs[0].isVector() ||
12461 VTList.VTs[0].getVectorElementCount() ==
12462 Ops[1].getValueType().getVectorElementCount()) &&
12463 "Vector element count mismatch!");
12464 assert(VTList.VTs[0].isFloatingPoint() &&
12465 Ops[1].getValueType().isFloatingPoint() &&
12466 VTList.VTs[0].bitsLT(Ops[1].getValueType()) &&
12467 Ops[2].getOpcode() == ISD::TargetConstant &&
12468 (Ops[2]->getAsZExtVal() == 0 || Ops[2]->getAsZExtVal() == 1) &&
12469 "Invalid STRICT_FP_ROUND!");
12470 break;
12471 }
12472
12473 // Memoize the node unless it returns a glue result.
12474 SDNode *N;
12475 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
12476 SDNodeKey ID(Opcode, VTList, Ops);
12477 FoldingSetInsertToken InsertToken;
12478 if (SDNode *E = lookupNode(ID, DL, InsertToken)) {
12479 E->intersectFlagsWith(Flags);
12480 return SDValue(E, 0);
12481 }
12482
12483 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
12484 createOperands(N, Ops);
12485 CSEMap.insert(N, InsertToken);
12486 } else {
12487 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
12488 createOperands(N, Ops);
12489 }
12490
12491 N->setFlags(Flags);
12492 InsertNode(N);
12493 SDValue V(N, 0);
12494 NewSDValueDbgMsg(V, "Creating new node: ", this);
12495 return V;
12496}
12497
12498SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
12499 SDVTList VTList) {
12500 return getNode(Opcode, DL, VTList, ArrayRef<SDValue>());
12501}
12502
12503SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
12504 SDValue N1) {
12505 SDValue Ops[] = { N1 };
12506 return getNode(Opcode, DL, VTList, Ops);
12507}
12508
12509SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
12510 SDValue N1, SDValue N2) {
12511 SDValue Ops[] = { N1, N2 };
12512 return getNode(Opcode, DL, VTList, Ops);
12513}
12514
12515SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
12516 SDValue N1, SDValue N2, SDValue N3) {
12517 SDValue Ops[] = { N1, N2, N3 };
12518 return getNode(Opcode, DL, VTList, Ops);
12519}
12520
12521SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
12522 SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
12523 SDValue Ops[] = { N1, N2, N3, N4 };
12524 return getNode(Opcode, DL, VTList, Ops);
12525}
12526
12527SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
12528 SDValue N1, SDValue N2, SDValue N3, SDValue N4,
12529 SDValue N5) {
12530 SDValue Ops[] = { N1, N2, N3, N4, N5 };
12531 return getNode(Opcode, DL, VTList, Ops);
12532}
12533
12535 if (!VT.isExtended())
12536 return makeVTList(SDNode::getValueTypeList(VT.getSimpleVT()), 1);
12537
12538 EVT VTs[] = {VT};
12539 return getVTList(VTs);
12540}
12541
12543 EVT VTs[] = {VT1, VT2};
12544 return getVTList(VTs);
12545}
12546
12548 EVT VTs[] = {VT1, VT2, VT3};
12549 return getVTList(VTs);
12550}
12551
12553 EVT VTs[] = {VT1, VT2, VT3, VT4};
12554 return getVTList(VTs);
12555}
12556
12558 auto It = VTLists.find(VTs);
12559 if (It == VTLists.end()) {
12560 EVT *Array = Allocator.Allocate<EVT>(VTs.size());
12561 llvm::copy(VTs, Array);
12562 It = VTLists.insert(ArrayRef(Array, VTs.size())).first;
12563 }
12564 return makeVTList(It->data(), It->size());
12565}
12566
12567/// UpdateNodeOperands - *Mutate* the specified node in-place to have the
12568/// specified operands. If the resultant node already exists in the DAG,
12569/// this does not modify the specified node, instead it returns the node that
12570/// already exists. If the resultant node does not exist in the DAG, the
12571/// input node is returned. As a degenerate case, if you specify the same
12572/// input operands as the node already has, the input node is returned.
12574 assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
12575
12576 // Check to see if there is no change.
12577 if (Op == N->getOperand(0)) return N;
12578
12579 // See if the modified node already exists.
12580 FoldingSetInsertToken InsertToken;
12581 if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertToken)) {
12582 Existing->intersectFlagsWith(N->getFlags());
12583 return Existing;
12584 }
12585
12586 // Nope it doesn't. Remove the node from its current place in the maps.
12587 if (InsertToken)
12588 if (!RemoveNodeFromCSEMaps(N))
12589 InsertToken = {};
12590
12591 // Now we update the operands.
12592 N->OperandList[0].set(Op);
12593
12595 // If this gets put into a CSE map, add it.
12596 if (InsertToken)
12597 CSEMap.insert(N, InsertToken);
12598 return N;
12599}
12600
12602 assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
12603
12604 // Check to see if there is no change.
12605 if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
12606 return N; // No operands changed, just return the input node.
12607
12608 // See if the modified node already exists.
12609 FoldingSetInsertToken InsertToken;
12610 if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertToken)) {
12611 Existing->intersectFlagsWith(N->getFlags());
12612 return Existing;
12613 }
12614
12615 // Nope it doesn't. Remove the node from its current place in the maps.
12616 if (InsertToken)
12617 if (!RemoveNodeFromCSEMaps(N))
12618 InsertToken = {};
12619
12620 // Now we update the operands.
12621 if (N->OperandList[0] != Op1)
12622 N->OperandList[0].set(Op1);
12623 if (N->OperandList[1] != Op2)
12624 N->OperandList[1].set(Op2);
12625
12627 // If this gets put into a CSE map, add it.
12628 if (InsertToken)
12629 CSEMap.insert(N, InsertToken);
12630 return N;
12631}
12632
12635 SDValue Ops[] = { Op1, Op2, Op3 };
12636 return UpdateNodeOperands(N, Ops);
12637}
12638
12641 SDValue Op3, SDValue Op4) {
12642 SDValue Ops[] = { Op1, Op2, Op3, Op4 };
12643 return UpdateNodeOperands(N, Ops);
12644}
12645
12648 SDValue Op3, SDValue Op4, SDValue Op5) {
12649 SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 };
12650 return UpdateNodeOperands(N, Ops);
12651}
12652
12655 unsigned NumOps = Ops.size();
12656 assert(N->getNumOperands() == NumOps &&
12657 "Update with wrong number of operands");
12658
12659 // If no operands changed just return the input node.
12660 if (std::equal(Ops.begin(), Ops.end(), N->op_begin()))
12661 return N;
12662
12663 // See if the modified node already exists.
12664 FoldingSetInsertToken InsertToken;
12665 if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertToken)) {
12666 Existing->intersectFlagsWith(N->getFlags());
12667 return Existing;
12668 }
12669
12670 // Nope it doesn't. Remove the node from its current place in the maps.
12671 if (InsertToken)
12672 if (!RemoveNodeFromCSEMaps(N))
12673 InsertToken = {};
12674
12675 // Now we update the operands.
12676 for (unsigned i = 0; i != NumOps; ++i)
12677 if (N->OperandList[i] != Ops[i])
12678 N->OperandList[i].set(Ops[i]);
12679
12681 // If this gets put into a CSE map, add it.
12682 if (InsertToken)
12683 CSEMap.insert(N, InsertToken);
12684 return N;
12685}
12686
12687/// DropOperands - Release the operands and set this node to have
12688/// zero operands.
12690 // Unlike the code in MorphNodeTo that does this, we don't need to
12691 // watch for dead nodes here.
12692 for (op_iterator I = op_begin(), E = op_end(); I != E; ) {
12693 SDUse &Use = *I++;
12694 Use.set(SDValue());
12695 }
12696}
12697
12699 ArrayRef<MachineMemOperand *> NewMemRefs) {
12700 if (NewMemRefs.empty()) {
12701 N->clearMemRefs();
12702 return;
12703 }
12704
12705 // Check if we can avoid allocating by storing a single reference directly.
12706 if (NewMemRefs.size() == 1) {
12707 N->MemRefs = NewMemRefs[0];
12708 N->NumMemRefs = 1;
12709 return;
12710 }
12711
12712 MachineMemOperand **MemRefsBuffer =
12713 Allocator.template Allocate<MachineMemOperand *>(NewMemRefs.size());
12714 llvm::copy(NewMemRefs, MemRefsBuffer);
12715 N->MemRefs = MemRefsBuffer;
12716 N->NumMemRefs = static_cast<int>(NewMemRefs.size());
12717}
12718
12719/// SelectNodeTo - These are wrappers around MorphNodeTo that accept a
12720/// machine opcode.
12721///
12723 EVT VT) {
12724 SDVTList VTs = getVTList(VT);
12725 return SelectNodeTo(N, MachineOpc, VTs, {});
12726}
12727
12729 EVT VT, SDValue Op1) {
12730 SDVTList VTs = getVTList(VT);
12731 SDValue Ops[] = { Op1 };
12732 return SelectNodeTo(N, MachineOpc, VTs, Ops);
12733}
12734
12736 EVT VT, SDValue Op1,
12737 SDValue Op2) {
12738 SDVTList VTs = getVTList(VT);
12739 SDValue Ops[] = { Op1, Op2 };
12740 return SelectNodeTo(N, MachineOpc, VTs, Ops);
12741}
12742
12744 EVT VT, SDValue Op1,
12745 SDValue Op2, SDValue Op3) {
12746 SDVTList VTs = getVTList(VT);
12747 SDValue Ops[] = { Op1, Op2, Op3 };
12748 return SelectNodeTo(N, MachineOpc, VTs, Ops);
12749}
12750
12753 SDVTList VTs = getVTList(VT);
12754 return SelectNodeTo(N, MachineOpc, VTs, Ops);
12755}
12756
12758 EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) {
12759 SDVTList VTs = getVTList(VT1, VT2);
12760 return SelectNodeTo(N, MachineOpc, VTs, Ops);
12761}
12762
12764 EVT VT1, EVT VT2) {
12765 SDVTList VTs = getVTList(VT1, VT2);
12766 return SelectNodeTo(N, MachineOpc, VTs, {});
12767}
12768
12770 EVT VT1, EVT VT2, EVT VT3,
12772 SDVTList VTs = getVTList(VT1, VT2, VT3);
12773 return SelectNodeTo(N, MachineOpc, VTs, Ops);
12774}
12775
12777 EVT VT1, EVT VT2,
12778 SDValue Op1, SDValue Op2) {
12779 SDVTList VTs = getVTList(VT1, VT2);
12780 SDValue Ops[] = { Op1, Op2 };
12781 return SelectNodeTo(N, MachineOpc, VTs, Ops);
12782}
12783
12786 SDNode *New = MorphNodeTo(N, ~MachineOpc, VTs, Ops);
12787 // Reset the NodeID to -1.
12788 New->setNodeId(-1);
12789 if (New != N) {
12790 ReplaceAllUsesWith(N, New);
12792 }
12793 return New;
12794}
12795
12796/// UpdateSDLocOnMergeSDNode - If the opt level is -O0 then it throws away
12797/// the line number information on the merged node since it is not possible to
12798/// preserve the information that operation is associated with multiple lines.
12799/// This will make the debugger work better at -O0, where there is a higher
12800/// probability of having other instructions associated with that line.
12801///
12802/// For IROrder, we keep the smaller of the two
12803SDNode *SelectionDAG::UpdateSDLocOnMergeSDNode(SDNode *N, const SDLoc &OLoc) {
12804 DebugLoc NLoc = N->getDebugLoc();
12805 if (NLoc && OptLevel == CodeGenOptLevel::None && OLoc.getDebugLoc() != NLoc) {
12806 N->setDebugLoc(DebugLoc());
12807 }
12808 unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder());
12809 N->setIROrder(Order);
12810 return N;
12811}
12812
12813/// MorphNodeTo - This *mutates* the specified node to have the specified
12814/// return type, opcode, and operands.
12815///
12816/// Note that MorphNodeTo returns the resultant node. If there is already a
12817/// node of the specified opcode and operands, it returns that node instead of
12818/// the current one. Note that the SDLoc need not be the same.
12819///
12820/// Using MorphNodeTo is faster than creating a new node and swapping it in
12821/// with ReplaceAllUsesWith both because it often avoids allocating a new
12822/// node, and because it doesn't require CSE recalculation for any of
12823/// the node's users.
12824///
12825/// However, note that MorphNodeTo recursively deletes dead nodes from the DAG.
12826/// As a consequence it isn't appropriate to use from within the DAG combiner or
12827/// the legalizer which maintain worklists that would need to be updated when
12828/// deleting things.
12831 // If an identical node already exists, use it.
12832 FoldingSetInsertToken InsertToken;
12833 if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) {
12834 SDNodeKey ID(Opc, VTs, Ops);
12835 AddNodeIDCustom(ID.Tail, N, Opc);
12836 if (SDNode *ON = lookupNode(ID, SDLoc(N), InsertToken))
12837 return UpdateSDLocOnMergeSDNode(ON, SDLoc(N));
12838 }
12839
12840 if (!RemoveNodeFromCSEMaps(N))
12841 InsertToken = {};
12842
12843 // Start the morphing.
12844 N->NodeType = Opc;
12845 N->ValueList = VTs.VTs;
12846 N->NumValues = VTs.NumVTs;
12847
12848 // Clear the operands list, updating used nodes to remove this from their
12849 // use list. Keep track of any operands that become dead as a result.
12850 SmallPtrSet<SDNode*, 16> DeadNodeSet;
12851 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
12852 SDUse &Use = *I++;
12853 SDNode *Used = Use.getNode();
12854 Use.set(SDValue());
12855 if (Used->use_empty())
12856 DeadNodeSet.insert(Used);
12857 }
12858
12859 // For MachineNode, initialize the memory references information.
12861 MN->clearMemRefs();
12862
12863 // Swap for an appropriately sized array from the recycler.
12864 removeOperands(N);
12865 createOperands(N, Ops);
12866
12867 // Delete any nodes that are still dead after adding the uses for the
12868 // new operands.
12869 if (!DeadNodeSet.empty()) {
12870 SmallVector<SDNode *, 16> DeadNodes;
12871 for (SDNode *N : DeadNodeSet)
12872 if (N->use_empty())
12873 DeadNodes.push_back(N);
12874 RemoveDeadNodes(DeadNodes);
12875 }
12876
12877 if (InsertToken)
12878 CSEMap.insert(N, InsertToken); // Memoize the new node.
12879 return N;
12880}
12881
12883 unsigned OrigOpc = Node->getOpcode();
12884 unsigned NewOpc;
12885 switch (OrigOpc) {
12886 default:
12887 llvm_unreachable("mutateStrictFPToFP called with unexpected opcode!");
12888#define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \
12889 case ISD::STRICT_##DAGN: NewOpc = ISD::DAGN; break;
12890#define CMP_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \
12891 case ISD::STRICT_##DAGN: NewOpc = ISD::SETCC; break;
12892#include "llvm/IR/ConstrainedOps.def"
12893 }
12894
12895 assert(Node->getNumValues() == 2 && "Unexpected number of results!");
12896
12897 // We're taking this node out of the chain, so we need to re-link things.
12898 SDValue InputChain = Node->getOperand(0);
12899 SDValue OutputChain = SDValue(Node, 1);
12900 ReplaceAllUsesOfValueWith(OutputChain, InputChain);
12901
12903 for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
12904 Ops.push_back(Node->getOperand(i));
12905
12906 SDVTList VTs = getVTList(Node->getValueType(0));
12907 SDNode *Res = MorphNodeTo(Node, NewOpc, VTs, Ops);
12908
12909 // MorphNodeTo can operate in two ways: if an existing node with the
12910 // specified operands exists, it can just return it. Otherwise, it
12911 // updates the node in place to have the requested operands.
12912 if (Res == Node) {
12913 // If we updated the node in place, reset the node ID. To the isel,
12914 // this should be just like a newly allocated machine node.
12915 Res->setNodeId(-1);
12916 } else {
12919 }
12920
12921 return Res;
12922}
12923
12924/// getMachineNode - These are used for target selectors to create a new node
12925/// with specified return type(s), MachineInstr opcode, and operands.
12926///
12927/// Note that getMachineNode returns the resultant node. If there is already a
12928/// node of the specified opcode and operands, it returns that node instead of
12929/// the current one.
12931 EVT VT) {
12932 SDVTList VTs = getVTList(VT);
12933 return getMachineNode(Opcode, dl, VTs, {});
12934}
12935
12937 EVT VT, SDValue Op1) {
12938 SDVTList VTs = getVTList(VT);
12939 SDValue Ops[] = { Op1 };
12940 return getMachineNode(Opcode, dl, VTs, Ops);
12941}
12942
12944 EVT VT, SDValue Op1, SDValue Op2) {
12945 SDVTList VTs = getVTList(VT);
12946 SDValue Ops[] = { Op1, Op2 };
12947 return getMachineNode(Opcode, dl, VTs, Ops);
12948}
12949
12951 EVT VT, SDValue Op1, SDValue Op2,
12952 SDValue Op3) {
12953 SDVTList VTs = getVTList(VT);
12954 SDValue Ops[] = { Op1, Op2, Op3 };
12955 return getMachineNode(Opcode, dl, VTs, Ops);
12956}
12957
12960 SDVTList VTs = getVTList(VT);
12961 return getMachineNode(Opcode, dl, VTs, Ops);
12962}
12963
12965 EVT VT1, EVT VT2, SDValue Op1,
12966 SDValue Op2) {
12967 SDVTList VTs = getVTList(VT1, VT2);
12968 SDValue Ops[] = { Op1, Op2 };
12969 return getMachineNode(Opcode, dl, VTs, Ops);
12970}
12971
12973 EVT VT1, EVT VT2, SDValue Op1,
12974 SDValue Op2, SDValue Op3) {
12975 SDVTList VTs = getVTList(VT1, VT2);
12976 SDValue Ops[] = { Op1, Op2, Op3 };
12977 return getMachineNode(Opcode, dl, VTs, Ops);
12978}
12979
12981 EVT VT1, EVT VT2,
12983 SDVTList VTs = getVTList(VT1, VT2);
12984 return getMachineNode(Opcode, dl, VTs, Ops);
12985}
12986
12988 EVT VT1, EVT VT2, EVT VT3,
12989 SDValue Op1, SDValue Op2) {
12990 SDVTList VTs = getVTList(VT1, VT2, VT3);
12991 SDValue Ops[] = { Op1, Op2 };
12992 return getMachineNode(Opcode, dl, VTs, Ops);
12993}
12994
12996 EVT VT1, EVT VT2, EVT VT3,
12997 SDValue Op1, SDValue Op2,
12998 SDValue Op3) {
12999 SDVTList VTs = getVTList(VT1, VT2, VT3);
13000 SDValue Ops[] = { Op1, Op2, Op3 };
13001 return getMachineNode(Opcode, dl, VTs, Ops);
13002}
13003
13005 EVT VT1, EVT VT2, EVT VT3,
13007 SDVTList VTs = getVTList(VT1, VT2, VT3);
13008 return getMachineNode(Opcode, dl, VTs, Ops);
13009}
13010
13012 ArrayRef<EVT> ResultTys,
13014 SDVTList VTs = getVTList(ResultTys);
13015 return getMachineNode(Opcode, dl, VTs, Ops);
13016}
13017
13019 SDVTList VTs,
13021 bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue;
13023 FoldingSetInsertToken InsertToken;
13024
13025 if (DoCSE) {
13026 SDNodeKey ID(~Opcode, VTs, Ops);
13027 if (SDNode *E = lookupNode(ID, DL, InsertToken)) {
13028 return cast<MachineSDNode>(UpdateSDLocOnMergeSDNode(E, DL));
13029 }
13030 }
13031
13032 // Allocate a new MachineSDNode.
13033 N = newSDNode<MachineSDNode>(~Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
13034 createOperands(N, Ops);
13035
13036 if (DoCSE)
13037 CSEMap.insert(N, InsertToken);
13038
13039 InsertNode(N);
13040 NewSDValueDbgMsg(SDValue(N, 0), "Creating new machine node: ", this);
13041 return N;
13042}
13043
13044/// getTargetExtractSubreg - A convenience function for creating
13045/// TargetOpcode::EXTRACT_SUBREG nodes.
13047 SDValue Operand) {
13048 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
13049 SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,
13050 VT, Operand, SRIdxVal);
13051 return SDValue(Subreg, 0);
13052}
13053
13054/// getTargetInsertSubreg - A convenience function for creating
13055/// TargetOpcode::INSERT_SUBREG nodes.
13057 SDValue Operand, SDValue Subreg) {
13058 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
13059 SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL,
13060 VT, Operand, Subreg, SRIdxVal);
13061 return SDValue(Result, 0);
13062}
13063
13064/// getNodeIfExists - Get the specified node if it's already available, or
13065/// else return NULL.
13068 bool AllowCommute) {
13069 SDNodeFlags Flags;
13070 if (Inserter)
13071 Flags = Inserter->getFlags();
13072 return getNodeIfExists(Opcode, VTList, Ops, Flags, AllowCommute);
13073}
13074
13077 const SDNodeFlags Flags,
13078 bool AllowCommute) {
13079 if (VTList.VTs[VTList.NumVTs - 1] == MVT::Glue)
13080 return nullptr;
13081
13082 auto Lookup = [&](ArrayRef<SDValue> LookupOps) -> SDNode * {
13083 SDNodeKey ID(Opcode, VTList, LookupOps);
13084 FoldingSetInsertToken InsertToken;
13085 if (SDNode *E = lookupNode(ID, InsertToken)) {
13086 E->intersectFlagsWith(Flags);
13087 return E;
13088 }
13089 return nullptr;
13090 };
13091
13092 if (SDNode *Existing = Lookup(Ops))
13093 return Existing;
13094
13095 if (AllowCommute && TLI->isCommutativeBinOp(Opcode))
13096 return Lookup({Ops[1], Ops[0]});
13097
13098 return nullptr;
13099}
13100
13101/// doesNodeExist - Check if a node exists without modifying its flags.
13102bool SelectionDAG::doesNodeExist(unsigned Opcode, SDVTList VTList,
13104 if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
13105 SDNodeKey ID(Opcode, VTList, Ops);
13106 FoldingSetInsertToken InsertToken;
13107 if (lookupNode(ID, SDLoc(), InsertToken))
13108 return true;
13109 }
13110 return false;
13111}
13112
13113/// getDbgValue - Creates a SDDbgValue node.
13114///
13115/// SDNode
13117 SDNode *N, unsigned R, bool IsIndirect,
13118 const DebugLoc &DL, unsigned O) {
13119 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
13120 "Expected inlined-at fields to agree");
13121 return new (DbgInfo->getAlloc())
13122 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromNode(N, R),
13123 {}, IsIndirect, DL, O,
13124 /*IsVariadic=*/false);
13125}
13126
13127/// Constant
13129 DIExpression *Expr,
13130 const Value *C,
13131 const DebugLoc &DL, unsigned O) {
13132 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
13133 "Expected inlined-at fields to agree");
13134 return new (DbgInfo->getAlloc())
13135 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromConst(C), {},
13136 /*IsIndirect=*/false, DL, O,
13137 /*IsVariadic=*/false);
13138}
13139
13140/// FrameIndex
13142 DIExpression *Expr, unsigned FI,
13143 bool IsIndirect,
13144 const DebugLoc &DL,
13145 unsigned O) {
13146 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
13147 "Expected inlined-at fields to agree");
13148 return getFrameIndexDbgValue(Var, Expr, FI, {}, IsIndirect, DL, O);
13149}
13150
13151/// FrameIndex with dependencies
13153 DIExpression *Expr, unsigned FI,
13154 ArrayRef<SDNode *> Dependencies,
13155 bool IsIndirect,
13156 const DebugLoc &DL,
13157 unsigned O) {
13158 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
13159 "Expected inlined-at fields to agree");
13160 return new (DbgInfo->getAlloc())
13161 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromFrameIdx(FI),
13162 Dependencies, IsIndirect, DL, O,
13163 /*IsVariadic=*/false);
13164}
13165
13166/// VReg
13168 Register VReg, bool IsIndirect,
13169 const DebugLoc &DL, unsigned O) {
13170 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
13171 "Expected inlined-at fields to agree");
13172 return new (DbgInfo->getAlloc())
13173 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromVReg(VReg),
13174 {}, IsIndirect, DL, O,
13175 /*IsVariadic=*/false);
13176}
13177
13180 ArrayRef<SDNode *> Dependencies,
13181 bool IsIndirect, const DebugLoc &DL,
13182 unsigned O, bool IsVariadic) {
13183 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
13184 "Expected inlined-at fields to agree");
13185 return new (DbgInfo->getAlloc())
13186 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, Locs, Dependencies, IsIndirect,
13187 DL, O, IsVariadic);
13188}
13189
13191 unsigned OffsetInBits, unsigned SizeInBits,
13192 bool InvalidateDbg) {
13193 SDNode *FromNode = From.getNode();
13194 SDNode *ToNode = To.getNode();
13195 assert(FromNode && ToNode && "Can't modify dbg values");
13196
13197 // PR35338
13198 // TODO: assert(From != To && "Redundant dbg value transfer");
13199 // TODO: assert(FromNode != ToNode && "Intranode dbg value transfer");
13200 if (From == To || FromNode == ToNode)
13201 return;
13202
13203 if (!FromNode->getHasDebugValue())
13204 return;
13205
13206 SDDbgOperand FromLocOp =
13207 SDDbgOperand::fromNode(From.getNode(), From.getResNo());
13209
13211 for (SDDbgValue *Dbg : GetDbgValues(FromNode)) {
13212 if (Dbg->isInvalidated())
13213 continue;
13214
13215 // TODO: assert(!Dbg->isInvalidated() && "Transfer of invalid dbg value");
13216
13217 // Create a new location ops vector that is equal to the old vector, but
13218 // with each instance of FromLocOp replaced with ToLocOp.
13219 bool Changed = false;
13220 auto NewLocOps = Dbg->copyLocationOps();
13221 std::replace_if(
13222 NewLocOps.begin(), NewLocOps.end(),
13223 [&Changed, FromLocOp](const SDDbgOperand &Op) {
13224 bool Match = Op == FromLocOp;
13225 Changed |= Match;
13226 return Match;
13227 },
13228 ToLocOp);
13229 // Ignore this SDDbgValue if we didn't find a matching location.
13230 if (!Changed)
13231 continue;
13232
13233 DIVariable *Var = Dbg->getVariable();
13234 auto *Expr = Dbg->getExpression();
13235 // If a fragment is requested, update the expression.
13236 if (SizeInBits) {
13237 // When splitting a larger (e.g., sign-extended) value whose
13238 // lower bits are described with an SDDbgValue, do not attempt
13239 // to transfer the SDDbgValue to the upper bits.
13240 if (auto FI = Expr->getFragmentInfo())
13241 if (OffsetInBits + SizeInBits > FI->SizeInBits)
13242 continue;
13243 auto Fragment = DIExpression::createFragmentExpression(Expr, OffsetInBits,
13244 SizeInBits);
13245 if (!Fragment)
13246 continue;
13247 Expr = *Fragment;
13248 }
13249
13250 auto AdditionalDependencies = Dbg->getAdditionalDependencies();
13251 // Clone the SDDbgValue and move it to To.
13252 SDDbgValue *Clone = getDbgValueList(
13253 Var, Expr, NewLocOps, AdditionalDependencies, Dbg->isIndirect(),
13254 Dbg->getDebugLoc(), std::max(ToNode->getIROrder(), Dbg->getOrder()),
13255 Dbg->isVariadic());
13256 ClonedDVs.push_back(Clone);
13257
13258 if (InvalidateDbg) {
13259 // Invalidate value and indicate the SDDbgValue should not be emitted.
13260 Dbg->setIsInvalidated();
13261 Dbg->setIsEmitted();
13262 }
13263 }
13264
13265 for (SDDbgValue *Dbg : ClonedDVs) {
13266 assert(is_contained(Dbg->getSDNodes(), ToNode) &&
13267 "Transferred DbgValues should depend on the new SDNode");
13268 AddDbgValue(Dbg, false);
13269 }
13270}
13271
13273 if (!N.getHasDebugValue())
13274 return;
13275
13276 auto GetLocationOperand = [](SDNode *Node, unsigned ResNo) {
13277 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(Node))
13278 return SDDbgOperand::fromFrameIdx(FISDN->getIndex());
13279 return SDDbgOperand::fromNode(Node, ResNo);
13280 };
13281
13283 for (auto *DV : GetDbgValues(&N)) {
13284 if (DV->isInvalidated())
13285 continue;
13286 switch (N.getOpcode()) {
13287 default:
13288 break;
13289 case ISD::ADD: {
13290 SDValue N0 = N.getOperand(0);
13291 SDValue N1 = N.getOperand(1);
13292 if (!isa<ConstantSDNode>(N0)) {
13293 bool RHSConstant = isa<ConstantSDNode>(N1);
13294 uint64_t Offset;
13295 if (RHSConstant)
13296 Offset = N.getConstantOperandVal(1);
13297 // We are not allowed to turn indirect debug values variadic, so
13298 // don't salvage those.
13299 if (!RHSConstant && DV->isIndirect())
13300 continue;
13301
13302 // Rewrite an ADD constant node into a DIExpression. Since we are
13303 // performing arithmetic to compute the variable's *value* in the
13304 // DIExpression, we need to mark the expression with a
13305 // DW_OP_stack_value.
13306 auto *DIExpr = DV->getExpression();
13307 auto NewLocOps = DV->copyLocationOps();
13308 bool Changed = false;
13309 size_t OrigLocOpsSize = NewLocOps.size();
13310 for (size_t i = 0; i < OrigLocOpsSize; ++i) {
13311 // We're not given a ResNo to compare against because the whole
13312 // node is going away. We know that any ISD::ADD only has one
13313 // result, so we can assume any node match is using the result.
13314 if (NewLocOps[i].getKind() != SDDbgOperand::SDNODE ||
13315 NewLocOps[i].getSDNode() != &N)
13316 continue;
13317 NewLocOps[i] = GetLocationOperand(N0.getNode(), N0.getResNo());
13318 if (RHSConstant) {
13321 DIExpr = DIExpression::appendOpsToArg(DIExpr, ExprOps, i, true);
13322 } else {
13323 // Convert to a variadic expression (if not already).
13324 // convertToVariadicExpression() returns a const pointer, so we use
13325 // a temporary const variable here.
13326 const auto *TmpDIExpr =
13330 ExprOps.push_back(NewLocOps.size());
13331 ExprOps.push_back(dwarf::DW_OP_plus);
13332 SDDbgOperand RHS =
13334 NewLocOps.push_back(RHS);
13335 DIExpr = DIExpression::appendOpsToArg(TmpDIExpr, ExprOps, i, true);
13336 }
13337 Changed = true;
13338 }
13339 (void)Changed;
13340 assert(Changed && "Salvage target doesn't use N");
13341
13342 bool IsVariadic =
13343 DV->isVariadic() || OrigLocOpsSize != NewLocOps.size();
13344
13345 auto AdditionalDependencies = DV->getAdditionalDependencies();
13346 SDDbgValue *Clone = getDbgValueList(
13347 DV->getVariable(), DIExpr, NewLocOps, AdditionalDependencies,
13348 DV->isIndirect(), DV->getDebugLoc(), DV->getOrder(), IsVariadic);
13349 ClonedDVs.push_back(Clone);
13350 DV->setIsInvalidated();
13351 DV->setIsEmitted();
13352 LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting";
13353 N0.getNode()->dumprFull(this);
13354 dbgs() << " into " << *DIExpr << '\n');
13355 }
13356 break;
13357 }
13358 case ISD::TRUNCATE: {
13359 SDValue N0 = N.getOperand(0);
13360 TypeSize FromSize = N0.getValueSizeInBits();
13361 TypeSize ToSize = N.getValueSizeInBits(0);
13362
13363 DIExpression *DbgExpression = DV->getExpression();
13364 auto ExtOps = DIExpression::getExtOps(FromSize, ToSize, false);
13365 auto NewLocOps = DV->copyLocationOps();
13366 bool Changed = false;
13367 for (size_t i = 0; i < NewLocOps.size(); ++i) {
13368 if (NewLocOps[i].getKind() != SDDbgOperand::SDNODE ||
13369 NewLocOps[i].getSDNode() != &N)
13370 continue;
13371
13372 NewLocOps[i] = GetLocationOperand(N0.getNode(), N0.getResNo());
13373 DbgExpression = DIExpression::appendOpsToArg(DbgExpression, ExtOps, i);
13374 Changed = true;
13375 }
13376 assert(Changed && "Salvage target doesn't use N");
13377 (void)Changed;
13378
13379 SDDbgValue *Clone =
13380 getDbgValueList(DV->getVariable(), DbgExpression, NewLocOps,
13381 DV->getAdditionalDependencies(), DV->isIndirect(),
13382 DV->getDebugLoc(), DV->getOrder(), DV->isVariadic());
13383
13384 ClonedDVs.push_back(Clone);
13385 DV->setIsInvalidated();
13386 DV->setIsEmitted();
13387 LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting"; N0.getNode()->dumprFull(this);
13388 dbgs() << " into " << *DbgExpression << '\n');
13389 break;
13390 }
13391 }
13392 }
13393
13394 for (SDDbgValue *Dbg : ClonedDVs) {
13395 assert((!Dbg->getSDNodes().empty() ||
13396 llvm::any_of(Dbg->getLocationOps(),
13397 [&](const SDDbgOperand &Op) {
13398 return Op.getKind() == SDDbgOperand::FRAMEIX;
13399 })) &&
13400 "Salvaged DbgValue should depend on a new SDNode");
13401 AddDbgValue(Dbg, false);
13402 }
13403}
13404
13405/// Creates a SDDbgLabel node.
13407 const DebugLoc &DL, unsigned O) {
13408 assert(cast<DILabel>(Label)->isValidLocationForIntrinsic(DL) &&
13409 "Expected inlined-at fields to agree");
13410 return new (DbgInfo->getAlloc()) SDDbgLabel(Label, DL, O);
13411}
13412
13413namespace {
13414
13415/// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node
13416/// pointed to by a use iterator is deleted, increment the use iterator
13417/// so that it doesn't dangle.
13418///
13419class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener {
13422
13423 void NodeDeleted(SDNode *N, SDNode *E) override {
13424 // Increment the iterator as needed.
13425 while (UI != UE && N == UI->getUser())
13426 ++UI;
13427 }
13428
13429public:
13430 RAUWUpdateListener(SelectionDAG &d,
13433 : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {}
13434};
13435
13436} // end anonymous namespace
13437
13438/// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
13439/// This can cause recursive merging of nodes in the DAG.
13440///
13441/// This version assumes From has a single result value.
13442///
13444 SDNode *From = FromN.getNode();
13445 assert(From->getNumValues() == 1 && FromN.getResNo() == 0 &&
13446 "Cannot replace with this method!");
13447 assert(From != To.getNode() && "Cannot replace uses of with self");
13448
13449 // Preserve Debug Values
13450 transferDbgValues(FromN, To);
13451 // Preserve extra info.
13452 copyExtraInfo(From, To.getNode());
13453
13454 // Iterate over all the existing uses of From. New uses will be added
13455 // to the beginning of the use list, which we avoid visiting.
13456 // This specifically avoids visiting uses of From that arise while the
13457 // replacement is happening, because any such uses would be the result
13458 // of CSE: If an existing node looks like From after one of its operands
13459 // is replaced by To, we don't want to replace of all its users with To
13460 // too. See PR3018 for more info.
13461 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
13462 RAUWUpdateListener Listener(*this, UI, UE);
13463 while (UI != UE) {
13464 SDNode *User = UI->getUser();
13465
13466 // This node is about to morph, remove its old self from the CSE maps.
13467 RemoveNodeFromCSEMaps(User);
13468
13469 // A user can appear in a use list multiple times, and when this
13470 // happens the uses are usually next to each other in the list.
13471 // To help reduce the number of CSE recomputations, process all
13472 // the uses of this user that we can find this way.
13473 do {
13474 SDUse &Use = *UI;
13475 ++UI;
13476 Use.set(To);
13477 if (To->isDivergent() != From->isDivergent())
13479 } while (UI != UE && UI->getUser() == User);
13480 // Now that we have modified User, add it back to the CSE maps. If it
13481 // already exists there, recursively merge the results together.
13482 AddModifiedNodeToCSEMaps(User);
13483 }
13484
13485 // If we just RAUW'd the root, take note.
13486 if (FromN == getRoot())
13487 setRoot(To);
13488}
13489
13490/// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
13491/// This can cause recursive merging of nodes in the DAG.
13492///
13493/// This version assumes that for each value of From, there is a
13494/// corresponding value in To in the same position with the same type.
13495///
13497#ifndef NDEBUG
13498 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
13499 assert((!From->hasAnyUseOfValue(i) ||
13500 From->getValueType(i) == To->getValueType(i)) &&
13501 "Cannot use this version of ReplaceAllUsesWith!");
13502#endif
13503
13504 // Handle the trivial case.
13505 if (From == To)
13506 return;
13507
13508 // Preserve Debug Info. Only do this if there's a use.
13509 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
13510 if (From->hasAnyUseOfValue(i)) {
13511 assert((i < To->getNumValues()) && "Invalid To location");
13512 transferDbgValues(SDValue(From, i), SDValue(To, i));
13513 }
13514 // Preserve extra info.
13515 copyExtraInfo(From, To);
13516
13517 // Iterate over just the existing users of From. See the comments in
13518 // the ReplaceAllUsesWith above.
13519 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
13520 RAUWUpdateListener Listener(*this, UI, UE);
13521 while (UI != UE) {
13522 SDNode *User = UI->getUser();
13523
13524 // This node is about to morph, remove its old self from the CSE maps.
13525 RemoveNodeFromCSEMaps(User);
13526
13527 // A user can appear in a use list multiple times, and when this
13528 // happens the uses are usually next to each other in the list.
13529 // To help reduce the number of CSE recomputations, process all
13530 // the uses of this user that we can find this way.
13531 do {
13532 SDUse &Use = *UI;
13533 ++UI;
13534 Use.setNode(To);
13535 if (To->isDivergent() != From->isDivergent())
13537 } while (UI != UE && UI->getUser() == User);
13538
13539 // Now that we have modified User, add it back to the CSE maps. If it
13540 // already exists there, recursively merge the results together.
13541 AddModifiedNodeToCSEMaps(User);
13542 }
13543
13544 // If we just RAUW'd the root, take note.
13545 if (From == getRoot().getNode())
13546 setRoot(SDValue(To, getRoot().getResNo()));
13547}
13548
13549/// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
13550/// This can cause recursive merging of nodes in the DAG.
13551///
13552/// This version can replace From with any result values. To must match the
13553/// number and types of values returned by From.
13555 if (From->getNumValues() == 1) // Handle the simple case efficiently.
13556 return ReplaceAllUsesWith(SDValue(From, 0), To[0]);
13557
13558 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) {
13559 // Preserve Debug Info.
13560 transferDbgValues(SDValue(From, i), To[i]);
13561 // Preserve extra info.
13562 copyExtraInfo(From, To[i].getNode());
13563 }
13564
13565 // Iterate over just the existing users of From. See the comments in
13566 // the ReplaceAllUsesWith above.
13567 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
13568 RAUWUpdateListener Listener(*this, UI, UE);
13569 while (UI != UE) {
13570 SDNode *User = UI->getUser();
13571
13572 // This node is about to morph, remove its old self from the CSE maps.
13573 RemoveNodeFromCSEMaps(User);
13574
13575 // A user can appear in a use list multiple times, and when this happens the
13576 // uses are usually next to each other in the list. To help reduce the
13577 // number of CSE and divergence recomputations, process all the uses of this
13578 // user that we can find this way.
13579 bool To_IsDivergent = false;
13580 do {
13581 SDUse &Use = *UI;
13582 const SDValue &ToOp = To[Use.getResNo()];
13583 ++UI;
13584 Use.set(ToOp);
13585 if (ToOp.getValueType() != MVT::Other)
13586 To_IsDivergent |= ToOp->isDivergent();
13587 } while (UI != UE && UI->getUser() == User);
13588
13589 if (To_IsDivergent != From->isDivergent())
13591
13592 // Now that we have modified User, add it back to the CSE maps. If it
13593 // already exists there, recursively merge the results together.
13594 AddModifiedNodeToCSEMaps(User);
13595 }
13596
13597 // If we just RAUW'd the root, take note.
13598 if (From == getRoot().getNode())
13599 setRoot(SDValue(To[getRoot().getResNo()]));
13600}
13601
13602/// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
13603/// uses of other values produced by From.getNode() alone. The Deleted
13604/// vector is handled the same way as for ReplaceAllUsesWith.
13608
13610 SDNode *SkipUser) {
13611 // Handle the really simple, really trivial case efficiently.
13612 if (From == To) return;
13613
13614 // Handle the simple, trivial, case efficiently.
13615 if (!SkipUser && From.getNode()->getNumValues() == 1) {
13616 ReplaceAllUsesWith(From, To);
13617 return;
13618 }
13619
13620 // Preserve Debug Info.
13621 transferDbgValues(From, To);
13622 copyExtraInfo(From.getNode(), To.getNode());
13623
13624 // Iterate over just the existing users of From. See the comments in
13625 // the ReplaceAllUsesWith above.
13626 SDNode::use_iterator UI = From.getNode()->use_begin(),
13627 UE = From.getNode()->use_end();
13628 RAUWUpdateListener Listener(*this, UI, UE);
13629 while (UI != UE) {
13630 SDNode *User = UI->getUser();
13631 if (User == SkipUser) {
13632 ++UI;
13633 continue;
13634 }
13635 bool UserRemovedFromCSEMaps = false;
13636
13637 // A user can appear in a use list multiple times, and when this
13638 // happens the uses are usually next to each other in the list.
13639 // To help reduce the number of CSE recomputations, process all
13640 // the uses of this user that we can find this way.
13641 do {
13642 SDUse &Use = *UI;
13643
13644 // Skip uses of different values from the same node.
13645 if (Use.getResNo() != From.getResNo()) {
13646 ++UI;
13647 continue;
13648 }
13649
13650 // If this node hasn't been modified yet, it's still in the CSE maps,
13651 // so remove its old self from the CSE maps.
13652 if (!UserRemovedFromCSEMaps) {
13653 RemoveNodeFromCSEMaps(User);
13654 UserRemovedFromCSEMaps = true;
13655 }
13656
13657 ++UI;
13658 Use.set(To);
13659 if (To->isDivergent() != From->isDivergent())
13661 } while (UI != UE && UI->getUser() == User);
13662 // We are iterating over all uses of the From node, so if a use
13663 // doesn't use the specific value, no changes are made.
13664 if (!UserRemovedFromCSEMaps)
13665 continue;
13666
13667 // Now that we have modified User, add it back to the CSE maps. If it
13668 // already exists there, recursively merge the results together.
13669 AddModifiedNodeToCSEMaps(User);
13670 }
13671
13672 // If we just RAUW'd the root, take note.
13673 if (From == getRoot())
13674 setRoot(To);
13675}
13676
13677namespace {
13678
13679/// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith
13680/// to record information about a use.
13681struct UseMemo {
13682 SDNode *User;
13683 unsigned Index;
13684 SDUse *Use;
13685};
13686
13687/// operator< - Sort Memos by User.
13688bool operator<(const UseMemo &L, const UseMemo &R) {
13689 return (intptr_t)L.User < (intptr_t)R.User;
13690}
13691
13692/// RAUOVWUpdateListener - Helper for ReplaceAllUsesOfValuesWith - When the node
13693/// pointed to by a UseMemo is deleted, set the User to nullptr to indicate that
13694/// the node already has been taken care of recursively.
13695class RAUOVWUpdateListener : public SelectionDAG::DAGUpdateListener {
13696 SmallVectorImpl<UseMemo> &Uses;
13697
13698 void NodeDeleted(SDNode *N, SDNode *E) override {
13699 for (UseMemo &Memo : Uses)
13700 if (Memo.User == N)
13701 Memo.User = nullptr;
13702 }
13703
13704public:
13705 RAUOVWUpdateListener(SelectionDAG &d, SmallVectorImpl<UseMemo> &uses)
13706 : SelectionDAG::DAGUpdateListener(d), Uses(uses) {}
13707};
13708
13709} // end anonymous namespace
13710
13711/// Return true if a glue output should propagate divergence information.
13713 switch (Node->getOpcode()) {
13714 case ISD::CopyFromReg:
13715 case ISD::CopyToReg:
13716 return false;
13717 default:
13718 return true;
13719 }
13720
13721 llvm_unreachable("covered opcode switch");
13722}
13723
13725 if (TLI->isSDNodeAlwaysUniform(N)) {
13726 assert(!TLI->isSDNodeSourceOfDivergence(N, FLI, UA) &&
13727 "Conflicting divergence information!");
13728 return false;
13729 }
13730 if (TLI->isSDNodeSourceOfDivergence(N, FLI, UA))
13731 return true;
13732 for (const auto &Op : N->ops()) {
13733 EVT VT = Op.getValueType();
13734
13735 // Skip Chain. It does not carry divergence.
13736 if (VT != MVT::Other && Op.getNode()->isDivergent() &&
13737 (VT != MVT::Glue || gluePropagatesDivergence(Op.getNode())))
13738 return true;
13739 }
13740 return false;
13741}
13742
13744 SmallVector<SDNode *, 16> Worklist(1, N);
13745 do {
13746 N = Worklist.pop_back_val();
13747 bool IsDivergent = calculateDivergence(N);
13748 if (N->SDNodeBits.IsDivergent != IsDivergent) {
13749 N->SDNodeBits.IsDivergent = IsDivergent;
13750 llvm::append_range(Worklist, N->users());
13751 }
13752 } while (!Worklist.empty());
13753}
13754
13755void SelectionDAG::CreateTopologicalOrder(std::vector<SDNode *> &Order) {
13757 Order.reserve(AllNodes.size());
13758 for (auto &N : allnodes()) {
13759 unsigned NOps = N.getNumOperands();
13760 Degree[&N] = NOps;
13761 if (0 == NOps)
13762 Order.push_back(&N);
13763 }
13764 for (size_t I = 0; I != Order.size(); ++I) {
13765 SDNode *N = Order[I];
13766 for (auto *U : N->users()) {
13767 unsigned &UnsortedOps = Degree[U];
13768 if (0 == --UnsortedOps)
13769 Order.push_back(U);
13770 }
13771 }
13772}
13773
13774#if !defined(NDEBUG) && LLVM_ENABLE_ABI_BREAKING_CHECKS
13775void SelectionDAG::VerifyDAGDivergence() {
13776 std::vector<SDNode *> TopoOrder;
13777 CreateTopologicalOrder(TopoOrder);
13778 for (auto *N : TopoOrder) {
13779 assert(calculateDivergence(N) == N->isDivergent() &&
13780 "Divergence bit inconsistency detected");
13781 }
13782}
13783#endif
13784
13785/// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving
13786/// uses of other values produced by From.getNode() alone. The same value
13787/// may appear in both the From and To list. The Deleted vector is
13788/// handled the same way as for ReplaceAllUsesWith.
13790 const SDValue *To,
13791 unsigned Num){
13792 // Handle the simple, trivial case efficiently.
13793 if (Num == 1)
13794 return ReplaceAllUsesOfValueWith(*From, *To);
13795
13796 transferDbgValues(*From, *To);
13797 copyExtraInfo(From->getNode(), To->getNode());
13798
13799 // Read up all the uses and make records of them. This helps
13800 // processing new uses that are introduced during the
13801 // replacement process.
13803 for (unsigned i = 0; i != Num; ++i) {
13804 unsigned FromResNo = From[i].getResNo();
13805 SDNode *FromNode = From[i].getNode();
13806 for (SDUse &Use : FromNode->uses()) {
13807 if (Use.getResNo() == FromResNo) {
13808 UseMemo Memo = {Use.getUser(), i, &Use};
13809 Uses.push_back(Memo);
13810 }
13811 }
13812 }
13813
13814 // Sort the uses, so that all the uses from a given User are together.
13816 RAUOVWUpdateListener Listener(*this, Uses);
13817
13818 for (unsigned UseIndex = 0, UseIndexEnd = Uses.size();
13819 UseIndex != UseIndexEnd; ) {
13820 // We know that this user uses some value of From. If it is the right
13821 // value, update it.
13822 SDNode *User = Uses[UseIndex].User;
13823 // If the node has been deleted by recursive CSE updates when updating
13824 // another node, then just skip this entry.
13825 if (User == nullptr) {
13826 ++UseIndex;
13827 continue;
13828 }
13829
13830 // This node is about to morph, remove its old self from the CSE maps.
13831 RemoveNodeFromCSEMaps(User);
13832
13833 // The Uses array is sorted, so all the uses for a given User
13834 // are next to each other in the list.
13835 // To help reduce the number of CSE recomputations, process all
13836 // the uses of this user that we can find this way.
13837 do {
13838 unsigned i = Uses[UseIndex].Index;
13839 SDUse &Use = *Uses[UseIndex].Use;
13840 ++UseIndex;
13841
13842 Use.set(To[i]);
13843 } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User);
13844
13845 // Now that we have modified User, add it back to the CSE maps. If it
13846 // already exists there, recursively merge the results together.
13847 AddModifiedNodeToCSEMaps(User);
13848 }
13849}
13850
13851/// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
13852/// based on their topological order. It returns the maximum id and a vector
13853/// of the SDNodes* in assigned order by reference.
13855 unsigned DAGSize = 0;
13856
13857 // SortedPos tracks the progress of the algorithm. Nodes before it are
13858 // sorted, nodes after it are unsorted. When the algorithm completes
13859 // it is at the end of the list.
13860 allnodes_iterator SortedPos = allnodes_begin();
13861
13862 // Visit all the nodes. Move nodes with no operands to the front of
13863 // the list immediately. Annotate nodes that do have operands with their
13864 // operand count. Before we do this, the Node Id fields of the nodes
13865 // may contain arbitrary values. After, the Node Id fields for nodes
13866 // before SortedPos will contain the topological sort index, and the
13867 // Node Id fields for nodes At SortedPos and after will contain the
13868 // count of outstanding operands.
13870 checkForCycles(&N, this);
13871 unsigned Degree = N.getNumOperands();
13872 if (Degree == 0) {
13873 // A node with no uses, add it to the result array immediately.
13874 N.setNodeId(DAGSize++);
13875 allnodes_iterator Q(&N);
13876 if (Q != SortedPos)
13877 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q));
13878 assert(SortedPos != AllNodes.end() && "Overran node list");
13879 ++SortedPos;
13880 } else {
13881 // Temporarily use the Node Id as scratch space for the degree count.
13882 N.setNodeId(Degree);
13883 }
13884 }
13885
13886 // Visit all the nodes. As we iterate, move nodes into sorted order,
13887 // such that by the time the end is reached all nodes will be sorted.
13888 for (SDNode &Node : allnodes()) {
13889 SDNode *N = &Node;
13890 checkForCycles(N, this);
13891 // N is in sorted position, so all its uses have one less operand
13892 // that needs to be sorted.
13893 for (SDNode *P : N->users()) {
13894 unsigned Degree = P->getNodeId();
13895 assert(Degree != 0 && "Invalid node degree");
13896 --Degree;
13897 if (Degree == 0) {
13898 // All of P's operands are sorted, so P may sorted now.
13899 P->setNodeId(DAGSize++);
13900 if (P->getIterator() != SortedPos)
13901 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P));
13902 assert(SortedPos != AllNodes.end() && "Overran node list");
13903 ++SortedPos;
13904 } else {
13905 // Update P's outstanding operand count.
13906 P->setNodeId(Degree);
13907 }
13908 }
13909 if (Node.getIterator() == SortedPos) {
13910#ifndef NDEBUG
13912 SDNode *S = &*++I;
13913 dbgs() << "Overran sorted position:\n";
13914 S->dumprFull(this); dbgs() << "\n";
13915 dbgs() << "Checking if this is due to cycles\n";
13916 checkForCycles(this, true);
13917#endif
13918 llvm_unreachable(nullptr);
13919 }
13920 }
13921
13922 assert(SortedPos == AllNodes.end() &&
13923 "Topological sort incomplete!");
13924 assert(AllNodes.front().getOpcode() == ISD::EntryToken &&
13925 "First node in topological sort is not the entry token!");
13926 assert(AllNodes.front().getNodeId() == 0 &&
13927 "First node in topological sort has non-zero id!");
13928 assert(AllNodes.front().getNumOperands() == 0 &&
13929 "First node in topological sort has operands!");
13930 assert(AllNodes.back().getNodeId() == (int)DAGSize-1 &&
13931 "Last node in topologic sort has unexpected id!");
13932 assert(AllNodes.back().use_empty() &&
13933 "Last node in topologic sort has users!");
13934 assert(DAGSize == allnodes_size() && "Node count mismatch!");
13935 return DAGSize;
13936}
13937
13939 SmallVectorImpl<const SDNode *> &SortedNodes) const {
13940 SortedNodes.clear();
13941 // Node -> remaining number of outstanding operands.
13942 DenseMap<const SDNode *, unsigned> RemainingOperands;
13943
13944 // Put nodes without any operands into SortedNodes first.
13945 for (const SDNode &N : allnodes()) {
13946 checkForCycles(&N, this);
13947 unsigned NumOperands = N.getNumOperands();
13948 if (NumOperands == 0)
13949 SortedNodes.push_back(&N);
13950 else
13951 // Record their total number of outstanding operands.
13952 RemainingOperands[&N] = NumOperands;
13953 }
13954
13955 // A node is pushed into SortedNodes when all of its operands (predecessors in
13956 // the graph) are also in SortedNodes.
13957 for (unsigned i = 0U; i < SortedNodes.size(); ++i) {
13958 const SDNode *N = SortedNodes[i];
13959 for (const SDNode *U : N->users()) {
13960 // HandleSDNode is never part of a DAG and therefore has no entry in
13961 // RemainingOperands.
13962 if (U->getOpcode() == ISD::HANDLENODE)
13963 continue;
13964 unsigned &NumRemOperands = RemainingOperands[U];
13965 assert(NumRemOperands && "Invalid number of remaining operands");
13966 --NumRemOperands;
13967 if (!NumRemOperands)
13968 SortedNodes.push_back(U);
13969 }
13970 }
13971
13972 assert(SortedNodes.size() == AllNodes.size() && "Node count mismatch");
13973 assert(SortedNodes.front()->getOpcode() == ISD::EntryToken &&
13974 "First node in topological sort is not the entry token");
13975 assert(SortedNodes.front()->getNumOperands() == 0 &&
13976 "First node in topological sort has operands");
13977}
13978
13979/// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the
13980/// value is produced by SD.
13981void SelectionDAG::AddDbgValue(SDDbgValue *DB, bool isParameter) {
13982 for (SDNode *SD : DB->getSDNodes()) {
13983 if (!SD)
13984 continue;
13985 assert(DbgInfo->getSDDbgValues(SD).empty() || SD->getHasDebugValue());
13986 SD->setHasDebugValue(true);
13987 }
13988 DbgInfo->add(DB, isParameter);
13989}
13990
13991void SelectionDAG::AddDbgLabel(SDDbgLabel *DB) { DbgInfo->add(DB); }
13992
13994 SDValue NewMemOpChain) {
13995 assert(isa<MemSDNode>(NewMemOpChain) && "Expected a memop node");
13996 assert(NewMemOpChain.getValueType() == MVT::Other && "Expected a token VT");
13997 // The new memory operation must have the same position as the old load in
13998 // terms of memory dependency. Create a TokenFactor for the old load and new
13999 // memory operation and update uses of the old load's output chain to use that
14000 // TokenFactor.
14001 if (OldChain == NewMemOpChain || OldChain.use_empty())
14002 return NewMemOpChain;
14003
14004 SDValue TokenFactor = getNode(ISD::TokenFactor, SDLoc(OldChain), MVT::Other,
14005 OldChain, NewMemOpChain);
14006 // Leave the TokenFactor's own operand unchanged. Temporarily making it
14007 // self-referential can collide with an existing node during recursive CSE.
14008 ReplaceAllOtherUsesOfValueWith(OldChain, TokenFactor, TokenFactor.getNode());
14009 return TokenFactor;
14010}
14011
14013 SDValue NewMemOp) {
14014 assert(isa<MemSDNode>(NewMemOp.getNode()) && "Expected a memop node");
14015 SDValue OldChain = SDValue(OldLoad, 1);
14016 SDValue NewMemOpChain = NewMemOp.getValue(1);
14017 return makeEquivalentMemoryOrdering(OldChain, NewMemOpChain);
14018}
14019
14021 Function **OutFunction) {
14022 assert(isa<ExternalSymbolSDNode>(Op) && "Node should be an ExternalSymbol");
14023
14024 auto *Symbol = cast<ExternalSymbolSDNode>(Op)->getSymbol();
14025 auto *Module = MF->getFunction().getParent();
14026 auto *Function = Module->getFunction(Symbol);
14027
14028 if (OutFunction != nullptr)
14029 *OutFunction = Function;
14030
14031 if (Function != nullptr) {
14032 auto PtrTy = TLI->getPointerTy(getDataLayout(), Function->getAddressSpace());
14033 return getGlobalAddress(Function, SDLoc(Op), PtrTy);
14034 }
14035
14036 std::string ErrorStr;
14037 raw_string_ostream ErrorFormatter(ErrorStr);
14038 ErrorFormatter << "Undefined external symbol ";
14039 ErrorFormatter << '"' << Symbol << '"';
14040 report_fatal_error(Twine(ErrorStr));
14041}
14042
14043//===----------------------------------------------------------------------===//
14044// SDNode Class
14045//===----------------------------------------------------------------------===//
14046
14049 return Const != nullptr && Const->isZero();
14050}
14051
14053 return V.isUndef() || isNullConstant(V);
14054}
14055
14058 return Const != nullptr && Const->isZero() && !Const->isNegative();
14059}
14060
14063 return Const != nullptr && Const->isAllOnes();
14064}
14065
14068 return Const != nullptr && Const->isOne();
14069}
14070
14073 return Const != nullptr && Const->isMinSignedValue();
14074}
14075
14077 SDValue V, unsigned OperandNo,
14078 unsigned Depth) const {
14079 APInt DemandedElts = getDemandAllEltsMask(V);
14080 return isIdentityElement(Opcode, Flags, V, DemandedElts, OperandNo, Depth);
14081}
14082
14084 SDValue V, const APInt &DemandedElts,
14085 unsigned OperandNo, unsigned Depth) const {
14086 // NOTE: The cases should match with IR's ConstantExpr::getBinOpIdentity().
14087 // TODO: Target-specific opcodes could be added.
14088 if (V.getValueType().isInteger()) {
14089 KnownBits Known = computeKnownBits(V, DemandedElts, Depth);
14090 if (Known.isConstant()) {
14091 const APInt &Const = Known.getConstant();
14092 switch (Opcode) {
14093 case ISD::ADD:
14094 case ISD::OR:
14095 case ISD::XOR:
14096 case ISD::UMAX:
14097 return Const.isZero();
14098 case ISD::MUL:
14099 return Const.isOne();
14100 case ISD::AND:
14101 case ISD::UMIN:
14102 return Const.isAllOnes();
14103 case ISD::SMAX:
14104 return Const.isMinSignedValue();
14105 case ISD::SMIN:
14106 return Const.isMaxSignedValue();
14107 case ISD::SUB:
14108 case ISD::SHL:
14109 case ISD::SRA:
14110 case ISD::SRL:
14111 return OperandNo == 1 && Const.isZero();
14112 case ISD::UDIV:
14113 case ISD::SDIV:
14114 return OperandNo == 1 && Const.isOne();
14115 }
14116 }
14117 } else if (auto *ConstFP = isConstOrConstSplatFP(V, DemandedElts)) {
14118 switch (Opcode) {
14119 case ISD::FADD:
14120 return ConstFP->isZero() &&
14121 (Flags.hasNoSignedZeros() || ConstFP->isNegative());
14122 case ISD::FSUB:
14123 return OperandNo == 1 && ConstFP->isZero() &&
14124 (Flags.hasNoSignedZeros() || !ConstFP->isNegative());
14125 case ISD::FMUL:
14126 return ConstFP->isOne();
14127 case ISD::FDIV:
14128 return OperandNo == 1 && ConstFP->isOne();
14129 case ISD::FMINNUM:
14130 case ISD::FMAXNUM:
14131 case ISD::FMINIMUMNUM:
14132 case ISD::FMAXIMUMNUM: {
14133 // Neutral element for fminnum/fminimumnum is NaN, Inf or FLT_MAX,
14134 // depending on fast-math flags (FMF).
14135 EVT VT = V.getValueType();
14136 const fltSemantics &Semantics = VT.getFltSemantics();
14137 APFloat NeutralAF = !Flags.hasNoNaNs() ? APFloat::getQNaN(Semantics)
14138 : !Flags.hasNoInfs() ? APFloat::getInf(Semantics)
14139 : APFloat::getLargest(Semantics);
14140 if (Opcode == ISD::FMAXNUM || Opcode == ISD::FMAXIMUMNUM)
14141 NeutralAF.changeSign();
14142
14143 return ConstFP->isExactlyValue(NeutralAF);
14144 }
14145 case ISD::FMINIMUM:
14146 case ISD::FMAXIMUM: {
14147 // Neutral element for fminimum is Inf or FLT_MAX, depending on FMF.
14148 const APFloat &VAPF = ConstFP->getValueAPF();
14149 bool NeutralNegative = (Opcode == ISD::FMAXIMUM);
14150 if (Flags.hasNoInfs())
14151 return VAPF.isLargest() && VAPF.isNegative() == NeutralNegative;
14152 return VAPF.isInfinity() && VAPF.isNegative() == NeutralNegative;
14153 }
14154 }
14155 }
14156 return false;
14157}
14158
14160 while (V.getOpcode() == ISD::BITCAST)
14161 V = V.getOperand(0);
14162 return V;
14163}
14164
14166 while (V.getOpcode() == ISD::BITCAST && V.getOperand(0).hasOneUse())
14167 V = V.getOperand(0);
14168 return V;
14169}
14170
14172 while (V.getOpcode() == ISD::EXTRACT_SUBVECTOR)
14173 V = V.getOperand(0);
14174 return V;
14175}
14176
14178 while (V.getOpcode() == ISD::INSERT_VECTOR_ELT) {
14179 SDValue InVec = V.getOperand(0);
14180 SDValue EltNo = V.getOperand(2);
14181 EVT VT = InVec.getValueType();
14182 auto *IndexC = dyn_cast<ConstantSDNode>(EltNo);
14183 if (IndexC && VT.isFixedLengthVector() &&
14184 IndexC->getAPIntValue().ult(VT.getVectorNumElements()) &&
14185 !DemandedElts[IndexC->getZExtValue()]) {
14186 V = InVec;
14187 continue;
14188 }
14189 break;
14190 }
14191 return V;
14192}
14193
14195 while (V.getOpcode() == ISD::TRUNCATE)
14196 V = V.getOperand(0);
14197 return V;
14198}
14199
14200bool llvm::isBitwiseNot(SDValue V, bool AllowUndefs) {
14201 if (V.getOpcode() != ISD::XOR)
14202 return false;
14203 V = peekThroughBitcasts(V.getOperand(1));
14204 unsigned NumBits = V.getScalarValueSizeInBits();
14205 ConstantSDNode *C =
14206 isConstOrConstSplat(V, AllowUndefs, /*AllowTruncation*/ true);
14207 return C && (C->getAPIntValue().countr_one() >= NumBits);
14208}
14209
14211 bool AllowTruncation) {
14212 APInt DemandedElts = getDemandAllEltsMask(N);
14213 return isConstOrConstSplat(N, DemandedElts, AllowUndefs, AllowTruncation);
14214}
14215
14217 bool AllowUndefs,
14218 bool AllowTruncation) {
14220 return CN;
14221
14222 // SplatVectors can truncate their operands. Ignore that case here unless
14223 // AllowTruncation is set.
14224 if (N->getOpcode() == ISD::SPLAT_VECTOR) {
14225 EVT VecEltVT = N->getValueType(0).getVectorElementType();
14226 if (auto *CN = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
14227 EVT CVT = CN->getValueType(0);
14228 assert(CVT.bitsGE(VecEltVT) && "Illegal splat_vector element extension");
14229 if (AllowTruncation || CVT == VecEltVT)
14230 return CN;
14231 }
14232 }
14233
14235 BitVector UndefElements;
14236 ConstantSDNode *CN = BV->getConstantSplatNode(DemandedElts, &UndefElements);
14237
14238 // BuildVectors can truncate their operands. Ignore that case here unless
14239 // AllowTruncation is set.
14240 // TODO: Look into whether we should allow UndefElements in non-DemandedElts
14241 if (CN && (UndefElements.none() || AllowUndefs)) {
14242 EVT CVT = CN->getValueType(0);
14243 EVT NSVT = N.getValueType().getScalarType();
14244 assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension");
14245 if (AllowTruncation || (CVT == NSVT))
14246 return CN;
14247 }
14248 }
14249
14250 if (N.getOpcode() == ISD::MERGE_VALUES)
14251 return isConstOrConstSplat(N.getOperand(N.getResNo()), DemandedElts,
14252 AllowUndefs, AllowTruncation);
14253
14254 return nullptr;
14255}
14256
14258 APInt DemandedElts = getDemandAllEltsMask(N);
14259 return isConstOrConstSplatFP(N, DemandedElts, AllowUndefs);
14260}
14261
14263 const APInt &DemandedElts,
14264 bool AllowUndefs) {
14266 return CN;
14267
14269 BitVector UndefElements;
14270 ConstantFPSDNode *CN =
14271 BV->getConstantFPSplatNode(DemandedElts, &UndefElements);
14272 // TODO: Look into whether we should allow UndefElements in non-DemandedElts
14273 if (CN && (UndefElements.none() || AllowUndefs))
14274 return CN;
14275 }
14276
14277 if (N.getOpcode() == ISD::SPLAT_VECTOR)
14278 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N.getOperand(0)))
14279 return CN;
14280
14281 return nullptr;
14282}
14283
14284bool llvm::isNullOrNullSplat(SDValue N, bool AllowUndefs) {
14285 // TODO: may want to use peekThroughBitcast() here.
14286 ConstantSDNode *C =
14287 isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation=*/true);
14288 return C && C->isZero();
14289}
14290
14291bool llvm::isOneOrOneSplat(SDValue N, bool AllowUndefs) {
14292 ConstantSDNode *C =
14293 isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation*/ true);
14294 return C && C->isOne();
14295}
14296
14297bool llvm::isOneOrOneSplatFP(SDValue N, bool AllowUndefs) {
14298 ConstantFPSDNode *C = isConstOrConstSplatFP(N, AllowUndefs);
14299 return C && C->isOne();
14300}
14301
14302bool llvm::isAllOnesOrAllOnesSplat(SDValue N, bool AllowUndefs) {
14304 unsigned BitWidth = N.getScalarValueSizeInBits();
14305 ConstantSDNode *C =
14306 isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation=*/true);
14307 return C && C->getAPIntValue().countTrailingOnes() >= BitWidth;
14308}
14309
14310bool llvm::isZeroOrZeroSplat(SDValue N, bool AllowUndefs) {
14312 ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs, true);
14313 return C && C->isZero();
14314}
14315
14316bool llvm::isZeroOrZeroSplatFP(SDValue N, bool AllowUndefs) {
14317 ConstantFPSDNode *C = isConstOrConstSplatFP(N, AllowUndefs);
14318 return C && C->isZero();
14319}
14320
14324
14326 unsigned Opc, unsigned Order, const DebugLoc &dl, SDVTList VTs, EVT memvt,
14328 : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MemRefs(memrefs) {
14329 bool IsVolatile = false;
14330 bool IsNonTemporal = false;
14331 bool IsDereferenceable = true;
14332 bool IsInvariant = true;
14333 for (const MachineMemOperand *MMO : memoperands()) {
14334 IsVolatile |= MMO->isVolatile();
14335 IsNonTemporal |= MMO->isNonTemporal();
14336 IsDereferenceable &= MMO->isDereferenceable();
14337 IsInvariant &= MMO->isInvariant();
14338 }
14339 MemSDNodeBits.IsVolatile = IsVolatile;
14340 MemSDNodeBits.IsNonTemporal = IsNonTemporal;
14341 MemSDNodeBits.IsDereferenceable = IsDereferenceable;
14342 MemSDNodeBits.IsInvariant = IsInvariant;
14343
14344 // For the single-MMO case, we check here that the size of the memory operand
14345 // fits within the size of the MMO. This is because the MMO might indicate
14346 // only a possible address range instead of specifying the affected memory
14347 // addresses precisely.
14350 getMemOperand()->getSize().getValue())) &&
14351 "Size mismatch!");
14352}
14353
14354namespace {
14355
14356 struct EVTArray {
14357 std::vector<EVT> VTs;
14358
14359 EVTArray() {
14360 VTs.reserve(MVT::VALUETYPE_SIZE);
14361 for (unsigned i = 0; i < MVT::VALUETYPE_SIZE; ++i)
14362 VTs.push_back(MVT((MVT::SimpleValueType)i));
14363 }
14364 };
14365
14366} // end anonymous namespace
14367
14368/// getValueTypeList - Return a pointer to the specified value type.
14369///
14370const EVT *SDNode::getValueTypeList(MVT VT) {
14371 static EVTArray SimpleVTArray;
14372
14373 assert(VT < MVT::VALUETYPE_SIZE && "Value type out of range!");
14374 return &SimpleVTArray.VTs[VT.SimpleTy];
14375}
14376
14377/// hasAnyUseOfValue - Return true if there are any use of the indicated
14378/// value. This method ignores uses of other values defined by this operation.
14379bool SDNode::hasAnyUseOfValue(unsigned Value) const {
14380 assert(Value < getNumValues() && "Bad value!");
14381
14382 for (SDUse &U : uses())
14383 if (U.getResNo() == Value)
14384 return true;
14385
14386 return false;
14387}
14388
14389/// isOnlyUserOf - Return true if this node is the only use of N.
14390bool SDNode::isOnlyUserOf(const SDNode *N) const {
14391 bool Seen = false;
14392 for (const SDNode *User : N->users()) {
14393 if (User == this)
14394 Seen = true;
14395 else
14396 return false;
14397 }
14398
14399 return Seen;
14400}
14401
14402/// Return true if the only users of N are contained in Nodes.
14404 bool Seen = false;
14405 for (const SDNode *User : N->users()) {
14406 if (llvm::is_contained(Nodes, User))
14407 Seen = true;
14408 else
14409 return false;
14410 }
14411
14412 return Seen;
14413}
14414
14415/// Return true if the referenced return value is an operand of N.
14416bool SDValue::isOperandOf(const SDNode *N) const {
14417 return is_contained(N->op_values(), *this);
14418}
14419
14420bool SDNode::isOperandOf(const SDNode *N) const {
14421 return any_of(N->op_values(),
14422 [this](SDValue Op) { return this == Op.getNode(); });
14423}
14424
14425/// reachesChainWithoutSideEffects - Return true if this operand (which must
14426/// be a chain) reaches the specified operand without crossing any
14427/// side-effecting instructions on any chain path. In practice, this looks
14428/// through token factors and non-volatile loads. In order to remain efficient,
14429/// this only looks a couple of nodes in, it does not do an exhaustive search.
14430///
14431/// Note that we only need to examine chains when we're searching for
14432/// side-effects; SelectionDAG requires that all side-effects are represented
14433/// by chains, even if another operand would force a specific ordering. This
14434/// constraint is necessary to allow transformations like splitting loads.
14436 unsigned Depth) const {
14437 if (*this == Dest) return true;
14438
14439 // Don't search too deeply, we just want to be able to see through
14440 // TokenFactor's etc.
14441 if (Depth == 0) return false;
14442
14443 // If this is a token factor, all inputs to the TF happen in parallel.
14444 if (getOpcode() == ISD::TokenFactor) {
14445 // First, try a shallow search.
14446 if (is_contained((*this)->ops(), Dest)) {
14447 // We found the chain we want as an operand of this TokenFactor.
14448 // Essentially, we reach the chain without side-effects if we could
14449 // serialize the TokenFactor into a simple chain of operations with
14450 // Dest as the last operation. This is automatically true if the
14451 // chain has one use: there are no other ordering constraints.
14452 // If the chain has more than one use, we give up: some other
14453 // use of Dest might force a side-effect between Dest and the current
14454 // node.
14455 if (Dest.hasOneUse())
14456 return true;
14457 }
14458 // Next, try a deep search: check whether every operand of the TokenFactor
14459 // reaches Dest.
14460 return llvm::all_of((*this)->ops(), [=](SDValue Op) {
14461 return Op.reachesChainWithoutSideEffects(Dest, Depth - 1);
14462 });
14463 }
14464
14465 // Loads don't have side effects, look through them.
14466 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
14467 if (Ld->isUnordered())
14468 return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
14469 }
14470 return false;
14471}
14472
14473bool SDNode::hasPredecessor(const SDNode *N) const {
14476 Worklist.push_back(this);
14477 return hasPredecessorHelper(N, Visited, Worklist);
14478}
14479
14481 this->Flags &= Flags;
14482}
14483
14484SDValue
14486 ArrayRef<ISD::NodeType> CandidateBinOps,
14487 bool AllowPartials) {
14488 // The pattern must end in an extract from index 0.
14489 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
14490 !isNullConstant(Extract->getOperand(1)))
14491 return SDValue();
14492
14493 // Match against one of the candidate binary ops.
14494 SDValue Op = Extract->getOperand(0);
14495 if (llvm::none_of(CandidateBinOps, [Op](ISD::NodeType BinOp) {
14496 return Op.getOpcode() == unsigned(BinOp);
14497 }))
14498 return SDValue();
14499
14500 // Floating-point reductions may require relaxed constraints on the final step
14501 // of the reduction because they may reorder intermediate operations.
14502 unsigned CandidateBinOp = Op.getOpcode();
14503 if (Op.getValueType().isFloatingPoint()) {
14504 SDNodeFlags Flags = Op->getFlags();
14505 switch (CandidateBinOp) {
14506 case ISD::FADD:
14507 if (!Flags.hasNoSignedZeros() || !Flags.hasAllowReassociation())
14508 return SDValue();
14509 break;
14510 default:
14511 llvm_unreachable("Unhandled FP opcode for binop reduction");
14512 }
14513 }
14514
14515 // Matching failed - attempt to see if we did enough stages that a partial
14516 // reduction from a subvector is possible.
14517 auto PartialReduction = [&](SDValue Op, unsigned NumSubElts) {
14518 if (!AllowPartials || !Op)
14519 return SDValue();
14520 EVT OpVT = Op.getValueType();
14521 EVT OpSVT = OpVT.getScalarType();
14522 EVT SubVT = EVT::getVectorVT(*getContext(), OpSVT, NumSubElts);
14523 if (TLI->getExtractSubvectorCost(SubVT, OpVT, 0) >
14525 return SDValue();
14526 BinOp = (ISD::NodeType)CandidateBinOp;
14527 return getExtractSubvector(SDLoc(Op), SubVT, Op, 0);
14528 };
14529
14530 // At each stage, we're looking for something that looks like:
14531 // %s = shufflevector <8 x i32> %op, <8 x i32> undef,
14532 // <8 x i32> <i32 2, i32 3, i32 undef, i32 undef,
14533 // i32 undef, i32 undef, i32 undef, i32 undef>
14534 // %a = binop <8 x i32> %op, %s
14535 // Where the mask changes according to the stage. E.g. for a 3-stage pyramid,
14536 // we expect something like:
14537 // <4,5,6,7,u,u,u,u>
14538 // <2,3,u,u,u,u,u,u>
14539 // <1,u,u,u,u,u,u,u>
14540 // While a partial reduction match would be:
14541 // <2,3,u,u,u,u,u,u>
14542 // <1,u,u,u,u,u,u,u>
14543 unsigned Stages = Log2_32(Op.getValueType().getVectorNumElements());
14544 SDValue PrevOp;
14545 for (unsigned i = 0; i < Stages; ++i) {
14546 unsigned MaskEnd = (1 << i);
14547
14548 if (Op.getOpcode() != CandidateBinOp)
14549 return PartialReduction(PrevOp, MaskEnd);
14550
14551 SDValue Op0 = Op.getOperand(0);
14552 SDValue Op1 = Op.getOperand(1);
14553
14555 if (Shuffle) {
14556 Op = Op1;
14557 } else {
14558 Shuffle = dyn_cast<ShuffleVectorSDNode>(Op1);
14559 Op = Op0;
14560 }
14561
14562 // The first operand of the shuffle should be the same as the other operand
14563 // of the binop.
14564 if (!Shuffle || Shuffle->getOperand(0) != Op)
14565 return PartialReduction(PrevOp, MaskEnd);
14566
14567 // Verify the shuffle has the expected (at this stage of the pyramid) mask.
14568 for (int Index = 0; Index < (int)MaskEnd; ++Index)
14569 if (Shuffle->getMaskElt(Index) != (int)(MaskEnd + Index))
14570 return PartialReduction(PrevOp, MaskEnd);
14571
14572 PrevOp = Op;
14573 }
14574
14575 // Handle subvector reductions, which tend to appear after the shuffle
14576 // reduction stages.
14577 while (Op.getOpcode() == CandidateBinOp) {
14578 unsigned NumElts = Op.getValueType().getVectorNumElements();
14579 SDValue Op0 = Op.getOperand(0);
14580 SDValue Op1 = Op.getOperand(1);
14581 if (Op0.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
14583 Op0.getOperand(0) != Op1.getOperand(0))
14584 break;
14585 SDValue Src = Op0.getOperand(0);
14586 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
14587 if (NumSrcElts != (2 * NumElts))
14588 break;
14589 if (!(Op0.getConstantOperandAPInt(1) == 0 &&
14590 Op1.getConstantOperandAPInt(1) == NumElts) &&
14591 !(Op1.getConstantOperandAPInt(1) == 0 &&
14592 Op0.getConstantOperandAPInt(1) == NumElts))
14593 break;
14594 Op = Src;
14595 }
14596
14597 BinOp = (ISD::NodeType)CandidateBinOp;
14598 return Op;
14599}
14600
14602 EVT VT = N->getValueType(0);
14603 EVT EltVT = VT.getVectorElementType();
14604 unsigned NE = getMaxRuntimeNumElements(VT);
14605
14606 if (VT.isScalableVector() && (NE == 0 || ResNE != 0))
14607 reportFatalUsageError("Cannot unroll scalable vector!");
14608
14609 assert(NE && "Nothing to unroll!");
14610 SDLoc dl(N);
14611
14612 // If ResNE is 0, fully unroll the vector op.
14613 if (ResNE == 0)
14614 ResNE = NE;
14615 else if (NE > ResNE)
14616 NE = ResNE;
14617
14618 if (N->getNumValues() == 2) {
14619 SmallVector<SDValue, 8> Scalars0, Scalars1;
14620 SmallVector<SDValue, 4> Operands(N->getNumOperands());
14621 EVT VT1 = N->getValueType(1);
14622 EVT EltVT1 = VT1.getVectorElementType();
14623
14624 unsigned i;
14625 for (i = 0; i != NE; ++i) {
14626 for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) {
14627 SDValue Operand = N->getOperand(j);
14628 EVT OperandVT = Operand.getValueType();
14629
14630 // A vector operand; extract a single element.
14631 EVT OperandEltVT = OperandVT.getVectorElementType();
14632 Operands[j] = getExtractVectorElt(dl, OperandEltVT, Operand, i);
14633 }
14634
14635 SDValue EltOp = getNode(N->getOpcode(), dl, {EltVT, EltVT1}, Operands);
14636 Scalars0.push_back(EltOp);
14637 Scalars1.push_back(EltOp.getValue(1));
14638 }
14639
14640 for (; i < ResNE; ++i) {
14641 Scalars0.push_back(getUNDEF(EltVT));
14642 Scalars1.push_back(getUNDEF(EltVT1));
14643 }
14644
14646 : ElementCount::getFixed(ResNE);
14647 EVT VecVT = EVT::getVectorVT(*getContext(), EltVT, ResEC);
14648 EVT VecVT1 = EVT::getVectorVT(*getContext(), EltVT1, ResEC);
14649 SDValue Vec0 = buildVectorFromUnrolledParts(VecVT, dl, Scalars0);
14650 SDValue Vec1 = buildVectorFromUnrolledParts(VecVT1, dl, Scalars1);
14651 return getMergeValues({Vec0, Vec1}, dl);
14652 }
14653
14654 assert(N->getNumValues() == 1 &&
14655 "Can't unroll a vector with multiple results!");
14656
14658 SmallVector<SDValue, 4> Operands(N->getNumOperands());
14659
14660 unsigned i;
14661 for (i= 0; i != NE; ++i) {
14662 for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) {
14663 SDValue Operand = N->getOperand(j);
14664 EVT OperandVT = Operand.getValueType();
14665 if (OperandVT.isVector()) {
14666 // A vector operand; extract a single element.
14667 EVT OperandEltVT = OperandVT.getVectorElementType();
14668 Operands[j] = getExtractVectorElt(dl, OperandEltVT, Operand, i);
14669 } else {
14670 // A scalar operand; just use it as is.
14671 Operands[j] = Operand;
14672 }
14673 }
14674
14675 switch (N->getOpcode()) {
14676 default: {
14677 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands,
14678 N->getFlags()));
14679 break;
14680 }
14681 case ISD::VSELECT: {
14682 SDValue Cond = Operands[0];
14683 EVT CondVT = Cond.getValueType();
14685 if (CondVT != MVT::i1 &&
14686 TLI.getBooleanContents(N->getOperand(1).getValueType()) !=
14687 TLI.getBooleanContents(CondVT)) {
14688 EVT SetCCVT =
14689 TLI.getSetCCResultType(getDataLayout(), *getContext(), CondVT);
14690 Operands[0] =
14691 getSetCC(dl, SetCCVT, Cond, getConstant(0, dl, CondVT), ISD::SETNE);
14692 }
14693 Scalars.push_back(
14694 getNode(ISD::SELECT, dl, EltVT, Operands, N->getFlags()));
14695 break;
14696 }
14697 case ISD::SHL:
14698 case ISD::SRA:
14699 case ISD::SRL:
14700 case ISD::ROTL:
14701 case ISD::ROTR:
14702 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0],
14704 Operands[1])));
14705 break;
14707 EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType();
14708 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT,
14709 Operands[0],
14710 getValueType(ExtVT)));
14711 break;
14712 }
14713 case ISD::ADDRSPACECAST: {
14714 const auto *ASC = cast<AddrSpaceCastSDNode>(N);
14715 Scalars.push_back(
14716 getAddrSpaceCast(dl, EltVT, Operands[0], ASC->getSrcAddressSpace(),
14717 ASC->getDestAddressSpace(), ASC->getFlags()));
14718 break;
14719 }
14720 }
14721 }
14722
14723 for (; i < ResNE; ++i)
14724 Scalars.push_back(getUNDEF(EltVT));
14725
14726 EVT VecVT = VT.isScalableVector()
14727 ? VT
14728 : EVT::getVectorVT(*getContext(), EltVT, ResNE);
14729 return buildVectorFromUnrolledParts(VecVT, dl, Scalars);
14730}
14731
14732std::pair<SDValue, SDValue> SelectionDAG::UnrollVectorOverflowOp(
14733 SDNode *N, unsigned ResNE) {
14734 unsigned Opcode = N->getOpcode();
14735 assert((Opcode == ISD::UADDO || Opcode == ISD::SADDO ||
14736 Opcode == ISD::USUBO || Opcode == ISD::SSUBO ||
14737 Opcode == ISD::UMULO || Opcode == ISD::SMULO) &&
14738 "Expected an overflow opcode");
14739
14740 EVT ResVT = N->getValueType(0);
14741 EVT OvVT = N->getValueType(1);
14742 EVT ResEltVT = ResVT.getVectorElementType();
14743 EVT OvEltVT = OvVT.getVectorElementType();
14744 SDLoc dl(N);
14745
14746 // If ResNE is 0, fully unroll the vector op.
14747 unsigned NE = ResVT.getVectorNumElements();
14748 if (ResNE == 0)
14749 ResNE = NE;
14750 else if (NE > ResNE)
14751 NE = ResNE;
14752
14753 SmallVector<SDValue, 8> LHSScalars;
14754 SmallVector<SDValue, 8> RHSScalars;
14755 ExtractVectorElements(N->getOperand(0), LHSScalars, 0, NE);
14756 ExtractVectorElements(N->getOperand(1), RHSScalars, 0, NE);
14757
14758 EVT SVT = TLI->getSetCCResultType(getDataLayout(), *getContext(), ResEltVT);
14759 SDVTList VTs = getVTList(ResEltVT, SVT);
14760 SmallVector<SDValue, 8> ResScalars;
14761 SmallVector<SDValue, 8> OvScalars;
14762 for (unsigned i = 0; i < NE; ++i) {
14763 SDValue Res = getNode(Opcode, dl, VTs, LHSScalars[i], RHSScalars[i]);
14764 SDValue Ov =
14765 getSelect(dl, OvEltVT, Res.getValue(1),
14766 getBoolConstant(true, dl, OvEltVT, ResVT),
14767 getConstant(0, dl, OvEltVT));
14768
14769 ResScalars.push_back(Res);
14770 OvScalars.push_back(Ov);
14771 }
14772
14773 ResScalars.append(ResNE - NE, getUNDEF(ResEltVT));
14774 OvScalars.append(ResNE - NE, getUNDEF(OvEltVT));
14775
14776 EVT NewResVT = EVT::getVectorVT(*getContext(), ResEltVT, ResNE);
14777 EVT NewOvVT = EVT::getVectorVT(*getContext(), OvEltVT, ResNE);
14778 return std::make_pair(getBuildVector(NewResVT, dl, ResScalars),
14779 getBuildVector(NewOvVT, dl, OvScalars));
14780}
14781
14784 TypeSize Bytes, int Dist,
14785 const SelectionDAG &DAG) {
14786 if (LS->isVolatile() || Base->isVolatile())
14787 return false;
14788 // TODO: probably too restrictive for atomics, revisit
14789 if (!LS->isSimple())
14790 return false;
14791 if (LS->isIndexed() || Base->isIndexed())
14792 return false;
14793 if (LS->getChain() != Base->getChain())
14794 return false;
14795 EVT VT = LS->getMemoryVT();
14796 if (!VT.getScalarType().isByteSized())
14797 return false;
14798 if (VT.getStoreSize() != Bytes)
14799 return false;
14800
14801 auto BaseLocDecomp = BaseIndexOffset::match(Base, DAG);
14802 auto LocDecomp = BaseIndexOffset::match(LS, DAG);
14804 if (!BaseLocDecomp.equalBaseIndex(LocDecomp, DAG, Offset))
14805 return false;
14806
14807 int64_t ExpectedOffset = Dist * (int64_t)Bytes.getKnownMinValue();
14808 if (Bytes.isFixed())
14809 return Offset == StackOffset::getFixed(ExpectedOffset);
14810 return Offset == StackOffset::getScalable(ExpectedOffset);
14811}
14812
14815 TypeSize Bytes,
14816 int Dist) const {
14817 return areNonVolatileConsecutiveLoadsOrStores(LD, Base, Bytes, Dist, *this);
14818}
14819
14822 TypeSize Bytes,
14823 int Dist) const {
14824 return areNonVolatileConsecutiveLoadsOrStores(ST, Base, Bytes, Dist, *this);
14825}
14826
14827/// InferPtrAlignment - Infer alignment of a load / store address. Return
14828/// std::nullopt if it cannot be inferred.
14830 // If this is a GlobalAddress + cst, return the alignment.
14831 const GlobalValue *GV = nullptr;
14832 int64_t GVOffset = 0;
14833 if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) {
14834 unsigned PtrWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
14835 KnownBits Known(PtrWidth);
14837 unsigned AlignBits = Known.countMinTrailingZeros();
14838 if (AlignBits)
14839 return commonAlignment(Align::fromLog2(std::min(31U, AlignBits)),
14840 GVOffset);
14841 }
14842
14843 // If this is a direct reference to a stack slot, use information about the
14844 // stack slot's alignment.
14845 int FrameIdx = INT_MIN;
14846 int64_t FrameOffset = 0;
14848 FrameIdx = FI->getIndex();
14849 } else if (isBaseWithConstantOffset(Ptr) &&
14851 // Handle FI+Cst
14852 FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
14853 FrameOffset = Ptr.getConstantOperandVal(1);
14854 }
14855
14856 if (FrameIdx != INT_MIN) {
14858 return commonAlignment(MFI.getObjectAlign(FrameIdx), FrameOffset);
14859 }
14860
14861 return std::nullopt;
14862}
14863
14864/// Split the scalar node with EXTRACT_ELEMENT using the provided
14865/// VTs and return the low/high part.
14866std::pair<SDValue, SDValue> SelectionDAG::SplitScalar(const SDValue &N,
14867 const SDLoc &DL,
14868 const EVT &LoVT,
14869 const EVT &HiVT) {
14870 assert(!LoVT.isVector() && !HiVT.isVector() && !N.getValueType().isVector() &&
14871 "Split node must be a scalar type");
14872 SDValue Lo =
14874 SDValue Hi =
14876 return std::make_pair(Lo, Hi);
14877}
14878
14879/// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type
14880/// which is split (or expanded) into two not necessarily identical pieces.
14881std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const {
14882 // Currently all types are split in half.
14883 EVT LoVT, HiVT;
14884 if (!VT.isVector())
14885 LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT);
14886 else
14887 LoVT = HiVT = VT.getHalfNumVectorElementsVT(*getContext());
14888
14889 return std::make_pair(LoVT, HiVT);
14890}
14891
14892/// GetDependentSplitDestVTs - Compute the VTs needed for the low/hi parts of a
14893/// type, dependent on an enveloping VT that has been split into two identical
14894/// pieces. Sets the HiIsEmpty flag when hi type has zero storage size.
14895std::pair<EVT, EVT>
14897 bool *HiIsEmpty) const {
14898 EVT EltTp = VT.getVectorElementType();
14899 // Examples:
14900 // custom VL=8 with enveloping VL=8/8 yields 8/0 (hi empty)
14901 // custom VL=9 with enveloping VL=8/8 yields 8/1
14902 // custom VL=10 with enveloping VL=8/8 yields 8/2
14903 // etc.
14904 ElementCount VTNumElts = VT.getVectorElementCount();
14905 ElementCount EnvNumElts = EnvVT.getVectorElementCount();
14906 assert(VTNumElts.isScalable() == EnvNumElts.isScalable() &&
14907 "Mixing fixed width and scalable vectors when enveloping a type");
14908 EVT LoVT, HiVT;
14909 if (VTNumElts.getKnownMinValue() > EnvNumElts.getKnownMinValue()) {
14910 LoVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts);
14911 HiVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts - EnvNumElts);
14912 *HiIsEmpty = false;
14913 } else {
14914 // Flag that hi type has zero storage size, but return split envelop type
14915 // (this would be easier if vector types with zero elements were allowed).
14916 LoVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts);
14917 HiVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts);
14918 *HiIsEmpty = true;
14919 }
14920 return std::make_pair(LoVT, HiVT);
14921}
14922
14923/// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the
14924/// low/high part.
14925std::pair<SDValue, SDValue>
14926SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT,
14927 const EVT &HiVT) {
14928 assert(LoVT.isScalableVector() == HiVT.isScalableVector() &&
14929 LoVT.isScalableVector() == N.getValueType().isScalableVector() &&
14930 "Splitting vector with an invalid mixture of fixed and scalable "
14931 "vector types");
14933 N.getValueType().getVectorMinNumElements() &&
14934 "More vector elements requested than available!");
14935 SDValue Lo, Hi;
14936 Lo = getExtractSubvector(DL, LoVT, N, 0);
14937 // For scalable vectors it is safe to use LoVT.getVectorMinNumElements()
14938 // (rather than having to use ElementCount), because EXTRACT_SUBVECTOR scales
14939 // IDX with the runtime scaling factor of the result vector type. For
14940 // fixed-width result vectors, that runtime scaling factor is 1.
14942 return std::make_pair(Lo, Hi);
14943}
14944
14945std::pair<SDValue, SDValue> SelectionDAG::SplitEVL(SDValue N, EVT VecVT,
14946 const SDLoc &DL) {
14947 // Split the vector length parameter.
14948 // %evl -> umin(%evl, %halfnumelts) and usubsat(%evl - %halfnumelts).
14949 EVT VT = N.getValueType();
14951 "Expecting the mask to be an evenly-sized vector");
14952 SDValue HalfNumElts = getElementCount(
14954 SDValue Lo = getNode(ISD::UMIN, DL, VT, N, HalfNumElts);
14955 SDValue Hi = getNode(ISD::USUBSAT, DL, VT, N, HalfNumElts);
14956 return std::make_pair(Lo, Hi);
14957}
14958
14959/// Widen the vector up to the next power of two using INSERT_SUBVECTOR.
14961 EVT VT = N.getValueType();
14962 EVT WideVT = VT.changeElementCount(
14963 *getContext(),
14965 return getInsertSubvector(DL, getPOISON(WideVT), N, 0);
14966}
14967
14970 unsigned Start, unsigned Count,
14971 EVT EltVT) {
14972 EVT VT = Op.getValueType();
14973 if (Count == 0)
14975 if (EltVT == EVT())
14976 EltVT = VT.getVectorElementType();
14977 SDLoc SL(Op);
14978 for (unsigned i = Start, e = Start + Count; i != e; ++i) {
14979 Args.push_back(getExtractVectorElt(SL, EltVT, Op, i));
14980 }
14981}
14982
14983// getAddressSpace - Return the address space this GlobalAddress belongs to.
14985 return getGlobal()->getType()->getAddressSpace();
14986}
14987
14990 return Val.MachineCPVal->getType();
14991 return Val.ConstVal->getType();
14992}
14993
14994bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue, APInt &SplatUndef,
14995 unsigned &SplatBitSize,
14996 bool &HasAnyUndefs,
14997 unsigned MinSplatBits,
14998 bool IsBigEndian) const {
14999 EVT VT = getValueType(0);
15000 assert(VT.isVector() && "Expected a vector type");
15001 unsigned VecWidth = VT.getSizeInBits();
15002 if (MinSplatBits > VecWidth)
15003 return false;
15004
15005 // FIXME: The widths are based on this node's type, but build vectors can
15006 // truncate their operands.
15007 SplatValue = APInt(VecWidth, 0);
15008 SplatUndef = APInt(VecWidth, 0);
15009
15010 // Get the bits. Bits with undefined values (when the corresponding element
15011 // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared
15012 // in SplatValue. If any of the values are not constant, give up and return
15013 // false.
15014 unsigned int NumOps = getNumOperands();
15015 assert(NumOps > 0 && "isConstantSplat has 0-size build vector");
15016 unsigned EltWidth = VT.getScalarSizeInBits();
15017
15018 for (unsigned j = 0; j < NumOps; ++j) {
15019 unsigned i = IsBigEndian ? NumOps - 1 - j : j;
15020 SDValue OpVal = getOperand(i);
15021 unsigned BitPos = j * EltWidth;
15022
15023 if (OpVal.isUndef())
15024 SplatUndef.setBits(BitPos, BitPos + EltWidth);
15025 else if (auto *CN = dyn_cast<ConstantSDNode>(OpVal))
15026 SplatValue.insertBits(CN->getAPIntValue().zextOrTrunc(EltWidth), BitPos);
15027 else if (auto *CN = dyn_cast<ConstantFPSDNode>(OpVal))
15028 SplatValue.insertBits(CN->getValueAPF().bitcastToAPInt(), BitPos);
15029 else
15030 return false;
15031 }
15032
15033 // The build_vector is all constants or undefs. Find the smallest element
15034 // size that splats the vector.
15035 HasAnyUndefs = (SplatUndef != 0);
15036
15037 // FIXME: This does not work for vectors with elements less than 8 bits.
15038 while (VecWidth > 8) {
15039 // If we can't split in half, stop here.
15040 if (VecWidth & 1)
15041 break;
15042
15043 unsigned HalfSize = VecWidth / 2;
15044 APInt HighValue = SplatValue.extractBits(HalfSize, HalfSize);
15045 APInt LowValue = SplatValue.extractBits(HalfSize, 0);
15046 APInt HighUndef = SplatUndef.extractBits(HalfSize, HalfSize);
15047 APInt LowUndef = SplatUndef.extractBits(HalfSize, 0);
15048
15049 // If the two halves do not match (ignoring undef bits), stop here.
15050 if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) ||
15051 MinSplatBits > HalfSize)
15052 break;
15053
15054 SplatValue = HighValue | LowValue;
15055 SplatUndef = HighUndef & LowUndef;
15056
15057 VecWidth = HalfSize;
15058 }
15059
15060 // FIXME: The loop above only tries to split in halves. But if the input
15061 // vector for example is <3 x i16> it wouldn't be able to detect a
15062 // SplatBitSize of 16. No idea if that is a design flaw currently limiting
15063 // optimizations. I guess that back in the days when this helper was created
15064 // vectors normally was power-of-2 sized.
15065
15066 SplatBitSize = VecWidth;
15067 return true;
15068}
15069
15071 BitVector *UndefElements) const {
15072 unsigned NumOps = getNumOperands();
15073 if (UndefElements) {
15074 UndefElements->clear();
15075 UndefElements->resize(NumOps);
15076 }
15077 assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size");
15078 if (!DemandedElts)
15079 return SDValue();
15080 SDValue Splatted;
15081 for (unsigned i = 0; i != NumOps; ++i) {
15082 if (!DemandedElts[i])
15083 continue;
15084 SDValue Op = getOperand(i);
15085 if (Op.isUndef()) {
15086 if (UndefElements)
15087 (*UndefElements)[i] = true;
15088 } else if (!Splatted) {
15089 Splatted = Op;
15090 } else if (Splatted != Op) {
15091 return SDValue();
15092 }
15093 }
15094
15095 if (!Splatted) {
15096 unsigned FirstDemandedIdx = DemandedElts.countr_zero();
15097 assert(getOperand(FirstDemandedIdx).isUndef() &&
15098 "Can only have a splat without a constant for all undefs.");
15099 return getOperand(FirstDemandedIdx);
15100 }
15101
15102 return Splatted;
15103}
15104
15106 APInt DemandedElts = APInt::getAllOnes(getNumOperands());
15107 return getSplatValue(DemandedElts, UndefElements);
15108}
15109
15111 SmallVectorImpl<SDValue> &Sequence,
15112 BitVector *UndefElements) const {
15113 unsigned NumOps = getNumOperands();
15114 Sequence.clear();
15115 if (UndefElements) {
15116 UndefElements->clear();
15117 UndefElements->resize(NumOps);
15118 }
15119 assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size");
15120 if (!DemandedElts || NumOps < 2 || !isPowerOf2_32(NumOps))
15121 return false;
15122
15123 // Set the undefs even if we don't find a sequence (like getSplatValue).
15124 if (UndefElements)
15125 for (unsigned I = 0; I != NumOps; ++I)
15126 if (DemandedElts[I] && getOperand(I).isUndef())
15127 (*UndefElements)[I] = true;
15128
15129 // Iteratively widen the sequence length looking for repetitions.
15130 for (unsigned SeqLen = 1; SeqLen < NumOps; SeqLen *= 2) {
15131 Sequence.append(SeqLen, SDValue());
15132 for (unsigned I = 0; I != NumOps; ++I) {
15133 if (!DemandedElts[I])
15134 continue;
15135 SDValue &SeqOp = Sequence[I % SeqLen];
15137 if (Op.isUndef()) {
15138 if (!SeqOp)
15139 SeqOp = Op;
15140 continue;
15141 }
15142 if (SeqOp && !SeqOp.isUndef() && SeqOp != Op) {
15143 Sequence.clear();
15144 break;
15145 }
15146 SeqOp = Op;
15147 }
15148 if (!Sequence.empty())
15149 return true;
15150 }
15151
15152 assert(Sequence.empty() && "Failed to empty non-repeating sequence pattern");
15153 return false;
15154}
15155
15157 BitVector *UndefElements) const {
15158 APInt DemandedElts = APInt::getAllOnes(getNumOperands());
15159 return getRepeatedSequence(DemandedElts, Sequence, UndefElements);
15160}
15161
15164 BitVector *UndefElements) const {
15166 getSplatValue(DemandedElts, UndefElements));
15167}
15168
15171 return dyn_cast_or_null<ConstantSDNode>(getSplatValue(UndefElements));
15172}
15173
15176 BitVector *UndefElements) const {
15178 getSplatValue(DemandedElts, UndefElements));
15179}
15180
15185
15186int32_t
15188 uint32_t BitWidth) const {
15189 if (ConstantFPSDNode *CN =
15191 bool IsExact;
15192 APSInt IntVal(BitWidth);
15193 const APFloat &APF = CN->getValueAPF();
15194 if (APF.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) !=
15195 APFloat::opOK ||
15196 !IsExact)
15197 return -1;
15198
15199 return IntVal.exactLogBase2();
15200 }
15201 return -1;
15202}
15203
15205 bool IsLittleEndian, unsigned DstEltSizeInBits,
15206 SmallVectorImpl<APInt> &RawBitElements, BitVector &UndefElements) const {
15207 // Early-out if this contains anything but Undef/Constant/ConstantFP.
15208 if (!isConstant())
15209 return false;
15210
15211 unsigned NumSrcOps = getNumOperands();
15212 unsigned SrcEltSizeInBits = getValueType(0).getScalarSizeInBits();
15213 assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 &&
15214 "Invalid bitcast scale");
15215
15216 // If the elements don't pack cleanly, don't attempt to recast.
15217 // TODO: Add handling (e.g. bitcast <33 x i8> --> <8 x i33>)
15218 if ((SrcEltSizeInBits % DstEltSizeInBits) != 0 &&
15219 (DstEltSizeInBits % SrcEltSizeInBits) != 0)
15220 return false;
15221
15222 // Extract raw src bits.
15223 SmallVector<APInt> SrcBitElements(NumSrcOps,
15224 APInt::getZero(SrcEltSizeInBits));
15225 BitVector SrcUndeElements(NumSrcOps, false);
15226
15227 for (unsigned I = 0; I != NumSrcOps; ++I) {
15229 if (Op.isUndef()) {
15230 SrcUndeElements.set(I);
15231 continue;
15232 }
15233 auto *CInt = dyn_cast<ConstantSDNode>(Op);
15234 auto *CFP = dyn_cast<ConstantFPSDNode>(Op);
15235 assert((CInt || CFP) && "Unknown constant");
15236 SrcBitElements[I] = CInt ? CInt->getAPIntValue().trunc(SrcEltSizeInBits)
15237 : CFP->getValueAPF().bitcastToAPInt();
15238 }
15239
15240 // Recast to dst width.
15241 recastRawBits(IsLittleEndian, DstEltSizeInBits, RawBitElements,
15242 SrcBitElements, UndefElements, SrcUndeElements);
15243 return true;
15244}
15245
15246void BuildVectorSDNode::recastRawBits(bool IsLittleEndian,
15247 unsigned DstEltSizeInBits,
15248 SmallVectorImpl<APInt> &DstBitElements,
15249 ArrayRef<APInt> SrcBitElements,
15250 BitVector &DstUndefElements,
15251 const BitVector &SrcUndefElements) {
15252 unsigned NumSrcOps = SrcBitElements.size();
15253 unsigned SrcEltSizeInBits = SrcBitElements[0].getBitWidth();
15254 assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 &&
15255 "Invalid bitcast scale");
15256 assert(((SrcEltSizeInBits % DstEltSizeInBits) == 0 ||
15257 (DstEltSizeInBits % SrcEltSizeInBits) == 0) &&
15258 "Unsupported bitcast scale");
15259 assert(NumSrcOps == SrcUndefElements.size() && "Vector size mismatch");
15260
15261 unsigned NumDstOps = (NumSrcOps * SrcEltSizeInBits) / DstEltSizeInBits;
15262 DstUndefElements.clear();
15263 DstUndefElements.resize(NumDstOps, false);
15264 DstBitElements.assign(NumDstOps, APInt::getZero(DstEltSizeInBits));
15265
15266 // Concatenate src elements constant bits together into dst element.
15267 if (SrcEltSizeInBits <= DstEltSizeInBits) {
15268 unsigned Scale = DstEltSizeInBits / SrcEltSizeInBits;
15269 for (unsigned I = 0; I != NumDstOps; ++I) {
15270 DstUndefElements.set(I);
15271 APInt &DstBits = DstBitElements[I];
15272 for (unsigned J = 0; J != Scale; ++J) {
15273 unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1));
15274 if (SrcUndefElements[Idx])
15275 continue;
15276 DstUndefElements.reset(I);
15277 const APInt &SrcBits = SrcBitElements[Idx];
15278 assert(SrcBits.getBitWidth() == SrcEltSizeInBits &&
15279 "Illegal constant bitwidths");
15280 DstBits.insertBits(SrcBits, J * SrcEltSizeInBits);
15281 }
15282 }
15283 return;
15284 }
15285
15286 // Split src element constant bits into dst elements.
15287 unsigned Scale = SrcEltSizeInBits / DstEltSizeInBits;
15288 for (unsigned I = 0; I != NumSrcOps; ++I) {
15289 if (SrcUndefElements[I]) {
15290 DstUndefElements.set(I * Scale, (I + 1) * Scale);
15291 continue;
15292 }
15293 const APInt &SrcBits = SrcBitElements[I];
15294 for (unsigned J = 0; J != Scale; ++J) {
15295 unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1));
15296 APInt &DstBits = DstBitElements[Idx];
15297 DstBits = SrcBits.extractBits(DstEltSizeInBits, J * DstEltSizeInBits);
15298 }
15299 }
15300}
15301
15303 for (const SDValue &Op : op_values()) {
15304 unsigned Opc = Op.getOpcode();
15305 if (!Op.isUndef() && Opc != ISD::Constant && Opc != ISD::ConstantFP)
15306 return false;
15307 }
15308 return true;
15309}
15310
15311std::optional<std::pair<APInt, APInt>>
15313 unsigned NumOps = getNumOperands();
15314 if (NumOps < 2)
15315 return std::nullopt;
15316
15317 unsigned EltSize = getValueType(0).getScalarSizeInBits();
15318 APInt Start, Stride;
15319 int FirstIdx = -1, SecondIdx = -1;
15320
15321 // Find the first two non-undef constant elements to determine Start and
15322 // Stride, then verify all remaining elements match the sequence.
15323 for (unsigned I = 0; I < NumOps; ++I) {
15325 if (Op->isUndef())
15326 continue;
15327 if (!isa<ConstantSDNode>(Op))
15328 return std::nullopt;
15329
15330 APInt Val = getConstantOperandAPInt(I).trunc(EltSize);
15331 if (FirstIdx < 0) {
15332 FirstIdx = I;
15333 Start = Val;
15334 } else if (SecondIdx < 0) {
15335 SecondIdx = I;
15336 // Compute stride using modular arithmetic. Simple division would handle
15337 // common strides (1, 2, -1, etc.), but modular inverse maximizes matches.
15338 // Example: <0, poison, poison, 0xFF> has stride 0x55 since 3*0x55 = 0xFF
15339 // Note that modular arithmetic is agnostic to signed/unsigned.
15340 unsigned IdxDiff = I - FirstIdx;
15341 APInt ValDiff = Val - Start;
15342
15343 // Step 1: Factor out common powers of 2 from IdxDiff and ValDiff.
15344 unsigned CommonPow2Bits = llvm::countr_zero(IdxDiff);
15345 if (ValDiff.countr_zero() < CommonPow2Bits)
15346 return std::nullopt; // ValDiff not divisible by 2^CommonPow2Bits
15347 IdxDiff >>= CommonPow2Bits;
15348 ValDiff.lshrInPlace(CommonPow2Bits);
15349
15350 // Step 2: IdxDiff is now odd, so its inverse mod 2^EltSize exists.
15351 // TODO: There are 2^CommonPow2Bits valid strides; currently we only try
15352 // one, but we could try all candidates to handle more cases.
15353 Stride = ValDiff * APInt(EltSize, IdxDiff).multiplicativeInverse();
15354 if (Stride.isZero())
15355 return std::nullopt;
15356
15357 // Step 3: Adjust Start based on the first defined element's index.
15358 Start -= Stride * FirstIdx;
15359 } else {
15360 // Verify this element matches the sequence.
15361 if (Val != Start + Stride * I)
15362 return std::nullopt;
15363 }
15364 }
15365
15366 // Need at least two defined elements.
15367 if (SecondIdx < 0)
15368 return std::nullopt;
15369
15370 return std::make_pair(Start, Stride);
15371}
15372
15374 // Find the first non-undef value in the shuffle mask.
15375 unsigned i, e;
15376 for (i = 0, e = Mask.size(); i != e && Mask[i] < 0; ++i)
15377 /* search */;
15378
15379 // If all elements are undefined, this shuffle can be considered a splat
15380 // (although it should eventually get simplified away completely).
15381 if (i == e)
15382 return true;
15383
15384 // Make sure all remaining elements are either undef or the same as the first
15385 // non-undef value.
15386 for (int Idx = Mask[i]; i != e; ++i)
15387 if (Mask[i] >= 0 && Mask[i] != Idx)
15388 return false;
15389 return true;
15390}
15391
15392// Returns true if it is a constant integer BuildVector or constant integer,
15393// possibly hidden by a bitcast.
15395 SDValue N, bool AllowOpaques) const {
15397
15398 if (auto *C = dyn_cast<ConstantSDNode>(N))
15399 return AllowOpaques || !C->isOpaque();
15400
15402 return true;
15403
15404 // Treat a GlobalAddress supporting constant offset folding as a
15405 // constant integer.
15406 if (auto *GA = dyn_cast<GlobalAddressSDNode>(N))
15407 if (GA->getOpcode() == ISD::GlobalAddress &&
15408 TLI->isOffsetFoldingLegal(GA))
15409 return true;
15410
15411 if ((N.getOpcode() == ISD::SPLAT_VECTOR) &&
15412 isa<ConstantSDNode>(N.getOperand(0)))
15413 return true;
15414 return false;
15415}
15416
15417// Returns true if it is a constant float BuildVector or constant float.
15420 return true;
15421
15423 return true;
15424
15425 if ((N.getOpcode() == ISD::SPLAT_VECTOR) &&
15426 isa<ConstantFPSDNode>(N.getOperand(0)))
15427 return true;
15428
15429 return false;
15430}
15431
15432std::optional<bool> SelectionDAG::isBoolConstant(SDValue N) const {
15433 ConstantSDNode *Const =
15434 isConstOrConstSplat(N, false, /*AllowTruncation=*/true);
15435 if (!Const)
15436 return std::nullopt;
15437
15438 EVT VT = N.getValueType();
15439 const APInt CVal = Const->getAPIntValue().trunc(VT.getScalarSizeInBits());
15440 switch (TLI->getBooleanContents(VT)) {
15442 if (CVal.isOne())
15443 return true;
15444 if (CVal.isZero())
15445 return false;
15446 return std::nullopt;
15448 if (CVal.isAllOnes())
15449 return true;
15450 if (CVal.isZero())
15451 return false;
15452 return std::nullopt;
15454 return CVal[0];
15455 }
15456 llvm_unreachable("Unknown BooleanContent enum");
15457}
15458
15459void SelectionDAG::createOperands(SDNode *Node, ArrayRef<SDValue> Vals) {
15460 assert(!Node->OperandList && "Node already has operands");
15462 "too many operands to fit into SDNode");
15463 SDUse *Ops = OperandRecycler.allocate(
15464 ArrayRecycler<SDUse>::Capacity::get(Vals.size()), OperandAllocator);
15465
15466 bool IsDivergent = false;
15467 for (unsigned I = 0; I != Vals.size(); ++I) {
15468 Ops[I].setUser(Node);
15469 Ops[I].setInitial(Vals[I]);
15470 EVT VT = Ops[I].getValueType();
15471
15472 // Skip Chain. It does not carry divergence.
15473 if (VT != MVT::Other &&
15474 (VT != MVT::Glue || gluePropagatesDivergence(Ops[I].getNode())) &&
15475 Ops[I].getNode()->isDivergent()) {
15476 IsDivergent = true;
15477 }
15478 }
15479 Node->NumOperands = Vals.size();
15480 Node->OperandList = Ops;
15481 if (!TLI->isSDNodeAlwaysUniform(Node)) {
15482 IsDivergent |= TLI->isSDNodeSourceOfDivergence(Node, FLI, UA);
15483 Node->SDNodeBits.IsDivergent = IsDivergent;
15484 }
15485 checkForCycles(Node);
15486}
15487
15490 size_t Limit = SDNode::getMaxNumOperands();
15491 while (Vals.size() > Limit) {
15492 unsigned SliceIdx = Vals.size() - Limit;
15493 auto ExtractedTFs = ArrayRef<SDValue>(Vals).slice(SliceIdx, Limit);
15494 SDValue NewTF = getNode(ISD::TokenFactor, DL, MVT::Other, ExtractedTFs);
15495 Vals.erase(Vals.begin() + SliceIdx, Vals.end());
15496 Vals.emplace_back(NewTF);
15497 }
15498 return getNode(ISD::TokenFactor, DL, MVT::Other, Vals);
15499}
15500
15502 EVT VT, SDNodeFlags Flags) {
15503 switch (Opcode) {
15504 default:
15505 return SDValue();
15506 case ISD::ADD:
15507 case ISD::OR:
15508 case ISD::XOR:
15509 case ISD::UMAX:
15510 case ISD::MUL:
15511 case ISD::AND:
15512 case ISD::UMIN:
15513 case ISD::SMAX:
15514 case ISD::SMIN:
15516 VT);
15517 case ISD::FADD:
15518 // If flags allow, prefer positive zero since it's generally cheaper
15519 // to materialize on most targets.
15520 return getConstantFP(Flags.hasNoSignedZeros() ? 0.0 : -0.0, DL, VT);
15521 case ISD::FMUL:
15522 return getConstantFP(1.0, DL, VT);
15523 case ISD::FMINNUM:
15524 case ISD::FMAXNUM:
15525 case ISD::FMINIMUMNUM:
15526 case ISD::FMAXIMUMNUM: {
15527 // Neutral element for fminnum/fminimumnum is NaN, Inf or FLT_MAX,
15528 // depending on fast-math flags (FMF).
15529 const fltSemantics &Semantics = VT.getFltSemantics();
15530 APFloat NeutralAF = !Flags.hasNoNaNs() ? APFloat::getQNaN(Semantics) :
15531 !Flags.hasNoInfs() ? APFloat::getInf(Semantics) :
15532 APFloat::getLargest(Semantics);
15533 if (Opcode == ISD::FMAXNUM || Opcode == ISD::FMAXIMUMNUM)
15534 NeutralAF.changeSign();
15535
15536 return getConstantFP(NeutralAF, DL, VT);
15537 }
15538 case ISD::FMINIMUM:
15539 case ISD::FMAXIMUM: {
15540 // Neutral element for fminimum is Inf or FLT_MAX, depending on FMF.
15541 const fltSemantics &Semantics = VT.getFltSemantics();
15542 APFloat NeutralAF = !Flags.hasNoInfs() ? APFloat::getInf(Semantics)
15543 : APFloat::getLargest(Semantics);
15544 if (Opcode == ISD::FMAXIMUM)
15545 NeutralAF.changeSign();
15546
15547 return getConstantFP(NeutralAF, DL, VT);
15548 }
15549
15550 }
15551}
15552
15554 SDValue Acc, SDValue LHS,
15555 SDValue RHS) {
15556 EVT AccVT = Acc.getValueType();
15557 if (AccVT.isFloatingPoint()) {
15558 assert(Opc == ISD::PARTIAL_REDUCE_FMLA && "Unexpected opcode");
15559 SDValue NegRHS = getNode(ISD::FNEG, DL, RHS.getValueType(), RHS);
15560 return getNode(Opc, DL, AccVT, Acc, LHS, NegRHS);
15561 }
15564 "Unexpected opcode");
15565 SDValue NegAcc = getNegative(Acc, DL, AccVT);
15566 SDValue MLA = getNode(Opc, DL, AccVT, NegAcc, LHS, RHS);
15567 return getNegative(MLA, DL, AccVT);
15568}
15569
15570/// Helper used to make a call to a library function that has one argument of
15571/// pointer type.
15572///
15573/// Such functions include 'fegetmode', 'fesetenv' and some others, which are
15574/// used to get or set floating-point state. They have one argument of pointer
15575/// type, which points to the memory region containing bits of the
15576/// floating-point state. The value returned by such function is ignored in the
15577/// created call.
15578///
15579/// \param LibFunc Reference to library function (value of RTLIB::Libcall).
15580/// \param Ptr Pointer used to save/load state.
15581/// \param InChain Ingoing token chain.
15582/// \param Node Node being legalized
15583/// \returns Outgoing chain token.
15585 SDValue InChain, SDNode *Node) {
15586 assert(InChain.getValueType() == MVT::Other && "Expected token chain");
15587 RTLIB::LibcallImpl LibcallImpl =
15588 Libcalls->getLibcallImpl(static_cast<RTLIB::Libcall>(LibFunc));
15589 if (LibcallImpl == RTLIB::Unsupported) {
15590 getContext()->emitError(Twine("no libcall available for ") +
15591 Node->getOperationName(this));
15592 return InChain;
15593 }
15594
15596 Args.emplace_back(Ptr, Ptr.getValueType().getTypeForEVT(*getContext()));
15597 SDValue Callee =
15598 getExternalSymbol(LibcallImpl, TLI->getPointerTy(getDataLayout()));
15600 CLI.setDebugLoc(SDLoc(Node))
15601 .setChain(InChain)
15602 .setLibCallee(Libcalls->getLibcallImplCallingConv(LibcallImpl),
15603 Type::getVoidTy(*getContext()), Callee, std::move(Args));
15604 return TLI->LowerCallTo(CLI).second;
15605}
15606
15608 assert(From && To && "Invalid SDNode; empty source SDValue?");
15609 auto I = SDEI.find(From);
15610 if (I == SDEI.end())
15611 return;
15612
15613 // Use of operator[] on the DenseMap may cause an insertion, which invalidates
15614 // the iterator, hence the need to make a copy to prevent a use-after-free.
15615 NodeExtraInfo NEI = I->second;
15616 if (LLVM_LIKELY(!NEI.PCSections)) {
15617 // No deep copy required for the types of extra info set.
15618 //
15619 // FIXME: Investigate if other types of extra info also need deep copy. This
15620 // depends on the types of nodes they can be attached to: if some extra info
15621 // is only ever attached to nodes where a replacement To node is always the
15622 // node where later use and propagation of the extra info has the intended
15623 // semantics, no deep copy is required.
15624 SDEI[To] = std::move(NEI);
15625 return;
15626 }
15627
15628 const SDNode *EntrySDN = getEntryNode().getNode();
15629
15630 // We need to copy NodeExtraInfo to all _new_ nodes that are being introduced
15631 // through the replacement of From with To. Otherwise, replacements of a node
15632 // (From) with more complex nodes (To and its operands) may result in lost
15633 // extra info where the root node (To) is insignificant in further propagating
15634 // and using extra info when further lowering to MIR.
15635 //
15636 // In the first step pre-populate the visited set with the nodes reachable
15637 // from the old From node. This avoids copying NodeExtraInfo to parts of the
15638 // DAG that is not new and should be left untouched.
15639 SmallVector<const SDNode *> Leafs{From}; // Leafs reachable with VisitFrom.
15640 DenseSet<const SDNode *> FromReach; // The set of nodes reachable from From.
15641 auto VisitFrom = [&](auto &&Self, const SDNode *N, int MaxDepth) {
15642 if (MaxDepth == 0) {
15643 // Remember this node in case we need to increase MaxDepth and continue
15644 // populating FromReach from this node.
15645 Leafs.emplace_back(N);
15646 return;
15647 }
15648 if (!FromReach.insert(N).second)
15649 return;
15650 for (const SDValue &Op : N->op_values())
15651 Self(Self, Op.getNode(), MaxDepth - 1);
15652 };
15653
15654 // Copy extra info to To and all its transitive operands (that are new).
15656 auto DeepCopyTo = [&](auto &&Self, const SDNode *N) {
15657 if (FromReach.contains(N))
15658 return true;
15659 if (!Visited.insert(N).second)
15660 return true;
15661 if (EntrySDN == N)
15662 return false;
15663 for (const SDValue &Op : N->op_values()) {
15664 if (N == To && Op.getNode() == EntrySDN) {
15665 // Special case: New node's operand is the entry node; just need to
15666 // copy extra info to new node.
15667 break;
15668 }
15669 if (!Self(Self, Op.getNode()))
15670 return false;
15671 }
15672 // Copy only if entry node was not reached.
15673 SDEI[N] = std::move(NEI);
15674 return true;
15675 };
15676
15677 // We first try with a lower MaxDepth, assuming that the path to common
15678 // operands between From and To is relatively short. This significantly
15679 // improves performance in the common case. The initial MaxDepth is big
15680 // enough to avoid retry in the common case; the last MaxDepth is large
15681 // enough to avoid having to use the fallback below (and protects from
15682 // potential stack exhaustion from recursion).
15683 for (int PrevDepth = 0, MaxDepth = 16; MaxDepth <= 1024;
15684 PrevDepth = MaxDepth, MaxDepth *= 2, Visited.clear()) {
15685 // StartFrom is the previous (or initial) set of leafs reachable at the
15686 // previous maximum depth.
15688 std::swap(StartFrom, Leafs);
15689 for (const SDNode *N : StartFrom)
15690 VisitFrom(VisitFrom, N, MaxDepth - PrevDepth);
15691 if (LLVM_LIKELY(DeepCopyTo(DeepCopyTo, To)))
15692 return;
15693 // This should happen very rarely (reached the entry node).
15694 LLVM_DEBUG(dbgs() << __func__ << ": MaxDepth=" << MaxDepth << " too low\n");
15695 assert(!Leafs.empty());
15696 }
15697
15698 // This should not happen - but if it did, that means the subgraph reachable
15699 // from From has depth greater or equal to maximum MaxDepth, and VisitFrom()
15700 // could not visit all reachable common operands. Consequently, we were able
15701 // to reach the entry node.
15702 errs() << "warning: incomplete propagation of SelectionDAG::NodeExtraInfo\n";
15703 assert(false && "From subgraph too complex - increase max. MaxDepth?");
15704 // Best-effort fallback if assertions disabled.
15705 SDEI[To] = std::move(NEI);
15706}
15707
15709 assert(VT.isVector() && "Can only unroll vector types!");
15710 if (VT.isFixedLengthVector())
15711 return VT.getVectorNumElements();
15712
15713 const MachineFunction &MF = getMachineFunction();
15714 const Function &F = MF.getFunction();
15715
15716 APInt MaxVScale = getVScaleRange(&F, sizeof(unsigned) * 8).getUnsignedMax();
15717 if (MaxVScale.ugt(getSelectionDAGOptions().vscale_unroll_limit))
15718 return 0;
15719
15720 bool Overflow;
15721 APInt MinNElts(sizeof(unsigned) * 8, VT.getVectorMinNumElements());
15722 APInt MaxNElts = MinNElts.umul_ov(MaxVScale, Overflow);
15723 if (Overflow)
15724 return 0;
15725
15726 return MaxNElts.getZExtValue();
15727}
15728
15730 ArrayRef<SDValue> Scalars) {
15731 assert(Scalars.size() == getMaxRuntimeNumElements(VT) &&
15732 "Element count mismatch!");
15733 if (VT.isFixedLengthVector())
15734 return getBuildVector(VT, DL, Scalars);
15735
15736 SDValue Vec = getPOISON(VT);
15737 // Iterate in reverse so result remains poison until we encounter a lane that
15738 // exists, after which all lower-numbered lanes must also exist.
15739 for (unsigned IdxVal : reverse(seq(Scalars.size())))
15740 Vec = getInsertVectorElt(DL, Vec, Scalars[IdxVal], IdxVal);
15741
15742 return Vec;
15743}
15744
15745#ifndef NDEBUG
15746static void checkForCyclesHelper(const SDNode *N,
15749 const llvm::SelectionDAG *DAG) {
15750 // If this node has already been checked, don't check it again.
15751 if (Checked.count(N))
15752 return;
15753
15754 // If a node has already been visited on this depth-first walk, reject it as
15755 // a cycle.
15756 if (!Visited.insert(N).second) {
15757 errs() << "Detected cycle in SelectionDAG\n";
15758 dbgs() << "Offending node:\n";
15759 N->dumprFull(DAG); dbgs() << "\n";
15760 abort();
15761 }
15762
15763 for (const SDValue &Op : N->op_values())
15764 checkForCyclesHelper(Op.getNode(), Visited, Checked, DAG);
15765
15766 Checked.insert(N);
15767 Visited.erase(N);
15768}
15769#endif
15770
15772 const llvm::SelectionDAG *DAG,
15773 bool force) {
15774#ifndef NDEBUG
15775 bool check = force;
15776#ifdef EXPENSIVE_CHECKS
15777 check = true;
15778#endif // EXPENSIVE_CHECKS
15779 if (check) {
15780 assert(N && "Checking nonexistent SDNode");
15783 checkForCyclesHelper(N, visited, checked, DAG);
15784 }
15785#endif // !NDEBUG
15786}
15787
15788void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) {
15789 checkForCycles(DAG->getRoot().getNode(), DAG, force);
15790}
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)
MachineBasicBlock * Folded
SmallVector< MachineOperand, 4 > Cond
unsigned Opc
#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
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:369
static constexpr roundingMode rmTowardZero
Definition APFloat.h:383
static constexpr roundingMode rmNearestTiesToEven
Definition APFloat.h:379
static LLVM_ABI bool hasSignBitInMSB(const fltSemantics &)
Definition APFloat.cpp:655
static constexpr const fltSemantics & IEEEhalf()
Definition APFloat.h:302
static constexpr const fltSemantics & IEEEsingle()
Definition APFloat.h:304
static constexpr const fltSemantics & BFloat()
Definition APFloat.h:303
static constexpr const fltSemantics & IEEEdouble()
Definition APFloat.h:305
static constexpr const fltSemantics & IEEEquad()
Definition APFloat.h:306
opStatus
IEEE-754R 7: Default exception handling.
Definition APFloat.h:395
static APFloat getQNaN(const fltSemantics &Sem, bool Negative=false, const APInt *payload=nullptr)
Factory for QNaN values.
Definition APFloat.h:1257
LLVM_ABI opStatus convert(const fltSemantics &ToSemantics, roundingMode RM, bool *losesInfo)
Definition APFloat.cpp:6103
bool isNegative() const
Definition APFloat.h:1616
bool isFinite() const
Definition APFloat.h:1621
opStatus convertFromAPInt(const APInt &Input, bool IsSigned, roundingMode RM)
Definition APFloat.h:1484
bool isZero() const
Definition APFloat.h:1612
LLVM_READONLY bool isOne() const
Definition APFloat.h:1709
bool isLargest() const
Definition APFloat.h:1632
static APFloat getLargest(const fltSemantics &Sem, bool Negative=false)
Returns the largest finite number in the given semantics.
Definition APFloat.h:1275
opStatus convertToInteger(MutableArrayRef< integerPart > Input, unsigned int Width, bool IsSigned, roundingMode RM, bool *IsExact) const
Definition APFloat.h:1469
static APFloat getInf(const fltSemantics &Sem, bool Negative=false)
Factory for Positive and Negative Infinity.
Definition APFloat.h:1235
bool isPosZero() const
Definition APFloat.h:1627
bool isNegZero() const
Definition APFloat.h:1628
void changeSign()
Definition APFloat.h:1434
static APFloat getNaN(const fltSemantics &Sem, bool Negative=false, uint64_t payload=0)
Factory for NaN values.
Definition APFloat.h:1246
bool isInfinity() const
Definition APFloat.h:1613
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:61
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:63
bool isLittleEndian() const
Layout endianness...
Definition DataLayout.h:219
LLVM_ABI IntegerType * getIntPtrType(LLVMContext &C, unsigned AddressSpace=0) const
Returns an integer type with size at least as big as that of a pointer in the given address space.
LLVM_ABI Align getABITypeAlign(Type *Ty) const
Returns the minimum ABI-required alignment for the specified type.
LLVM_ABI unsigned getPointerTypeSizeInBits(Type *) const
The pointer representation size in bits for this type.
bool isBigEndian() const
Definition DataLayout.h:220
LLVM_ABI Align getPrefTypeAlign(Type *Ty) const
Returns the preferred stack/global alignment for the specified type.
A debug info location.
Definition DebugLoc.h:126
Implements a dense probed hash-table based set.
Definition DenseSet.h:283
static constexpr ElementCount getFixed(ScalarTy MinVal)
Definition TypeSize.h:306
constexpr bool isScalar() const
Exactly one element.
Definition TypeSize.h:317
const char * getSymbol() const
Insertion token: a failed lookup fills it in, the matching insert consumes it.
Definition FoldingSet.h:284
This class is used to gather all the unique data bits of a node.
Definition FoldingSet.h:162
Data structure describing the variable locations in a function.
bool hasMinSize() const
Optimize this function for minimum size (-Oz).
Definition Function.h:705
AttributeList getAttributes() const
Return the attribute list for this Function.
Definition Function.h:329
LLVM_ABI unsigned getAddressSpace() const
const GlobalValue * getGlobal() const
bool isThreadLocal() const
If the value is "Thread Local", its value isn't shared by the threads.
unsigned getAddressSpace() const
Module * getParent()
Get the module that this global value is contained inside of...
PointerType * getType() const
Global values are always pointers.
This class is used to form a handle around another node that is persistent and is updated across invo...
const SDValue & getValue() const
static LLVM_ABI bool compare(const APInt &LHS, const APInt &RHS, ICmpInst::Predicate Pred)
Return result of LHS Pred RHS comparison.
bool isUnknown() const
KnownFPClass intersectWith(const KnownFPClass &RHS) const
static KnownFPClass getEmpty()
static LLVM_ABI KnownFPClass bitcast(const fltSemantics &FltSemantics, const KnownBits &Bits)
Report known values for a bitcast into a float with provided semantics.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
LLVM_ABI void emitError(const Instruction *I, const Twine &ErrorStr)
emitError - Emit an error message to the currently installed error handler with optional location inf...
Base class for LoadSDNode and StoreSDNode.
Tracks which library functions to use for a particular subtarget or function.
CallingConv::ID getLibcallImplCallingConv(RTLIB::LibcallImpl Call) const
Get the CallingConv that should be used for the specified libcall.
RTLIB::LibcallImpl getLibcallImpl(RTLIB::Libcall Call) const
Return the lowering's selection of implementation call for Call.
This SDNode is used for LIFETIME_START/LIFETIME_END values.
This class is used to represent ISD::LOAD nodes.
static LocationSize precise(uint64_t Value)
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition MCSymbol.h:42
Metadata node.
Definition Metadata.h:1087
const MDOperand & getOperand(unsigned I) const
Definition Metadata.h:1443
Machine Value Type.
SimpleValueType SimpleTy
static LLVM_ABI MVT getVT(Type *Ty, bool HandleUnknown=false)
Return the value type corresponding to the specified type.
bool bitsLT(MVT VT) const
Return true if this has less bits than VT.
static MVT getIntegerVT(unsigned BitWidth)
Abstract base class for all machine specific constantpool value subclasses.
virtual void addSelectionDAGCSEId(FoldingSetNodeID &ID)=0
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted.
LLVM_ABI int CreateStackObject(uint64_t Size, Align Alignment, bool isSpillSlot, const AllocaInst *Alloca=nullptr, uint8_t ID=0)
Create a new statically sized stack object, returning a nonnegative identifier to represent it.
Align getObjectAlign(int ObjectIdx) const
Return the alignment of the specified stack object.
bool isFixedObjectIndex(int ObjectIdx) const
Returns true if the specified index corresponds to a fixed stack object.
void setObjectAlignment(int ObjectIdx, Align Alignment)
setObjectAlignment - Change the alignment of the specified stack object.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
Function & getFunction()
Return the LLVM function that this machine code represents.
const TargetMachine & getTarget() const
getTarget - Return the target machine this machine code is compiled with
A description of a memory reference used in the backend.
const MDNode * getRanges() const
Return the range tag for the memory reference.
Flags
Flags values. These may be or'd together.
@ MOVolatile
The memory access is volatile.
@ MODereferenceable
The memory access is dereferenceable (i.e., doesn't trap).
@ MOLoad
The memory access reads data.
@ MOInvariant
The memory access always returns the same value (or traps).
@ MOStore
The memory access writes data.
const MachinePointerInfo & getPointerInfo() const
Flags getFlags() const
Return the raw flags of the source value,.
An SDNode that represents everything that will be needed to construct a MachineInstr.
This class is used to represent an MGATHER node.
This class is used to represent an MLOAD node.
This class is used to represent an MSTORE node.
This SDNode is used for target intrinsics that touch memory and need an associated MachineMemOperand.
This is an abstract virtual class for memory operations.
size_t getNumMemOperands() const
Return the number of memory operands.
LLVM_ABI MemSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl, SDVTList VTs, EVT memvt, PointerUnion< MachineMemOperand *, MachineMemOperand ** > memrefs)
Constructor that supports single or multiple MMOs.
PointerUnion< MachineMemOperand *, MachineMemOperand ** > MemRefs
Memory reference information.
MachineMemOperand * getMemOperand() const
Return the unique MachineMemOperand object describing the memory reference performed by operation.
const MachinePointerInfo & getPointerInfo() const
ArrayRef< MachineMemOperand * > memoperands() const
Return the memory operands for this node.
unsigned getRawSubclassData() const
Return the SubclassData value, without HasDebugValue.
EVT getMemoryVT() const
Return the type of the in-memory value.
Representation for a specific memory location.
Root of the metadata hierarchy.
Definition Metadata.h:65
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
Function * getFunction(StringRef Name) const
Look up the specified function in the module symbol table.
Definition Module.cpp:254
Represent a mutable reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:294
Class to represent pointers.
static PointerType * getUnqual(LLVMContext &C)
This constructs an opaque pointer to an object in the default address space (address space zero).
static LLVM_ABI PointerType * get(LLVMContext &C, unsigned AddressSpace)
This constructs an opaque pointer to an object in a numbered address space.
Definition Type.cpp:882
unsigned getAddressSpace() const
Return the address space of the Pointer type.
A discriminated union of two or more pointer types, with the discriminator in the low bits of the poi...
bool isNull() const
Test if the pointer held in the union is null, regardless of which type it is.
Analysis providing profile information.
void Deallocate(SubClass *E)
Deallocate - Release storage for the pointed-to object.
Wrapper class representing virtual and physical registers.
Definition Register.h:20
Keeps track of dbg_value information through SDISel.
LLVM_ABI void add(SDDbgValue *V, bool isParameter)
LLVM_ABI void erase(const SDNode *Node)
Invalidate all DbgValues attached to the node and remove it from the Node-to-DbgValues map.
Holds the information from a dbg_label node through SDISel.
Holds the information for a single machine location through SDISel; either an SDNode,...
static SDDbgOperand fromNode(SDNode *Node, unsigned ResNo)
static SDDbgOperand fromFrameIdx(unsigned FrameIdx)
static SDDbgOperand fromVReg(Register VReg)
static SDDbgOperand fromConst(const Value *Const)
@ SDNODE
Value is the result of an expression.
Holds the information from a dbg_value node through SDISel.
Wrapper class for IR location info (IR ordering and DebugLoc) to be passed into SDNode creation funct...
const DebugLoc & getDebugLoc() const
unsigned getIROrder() const
This class provides iterator support for SDUse operands that use a specific SDNode.
Represents one node in the SelectionDAG.
const APInt & getAsAPIntVal() const
Helper method returns the APInt value of a ConstantSDNode.
bool isMachineOpcode() const
Test if this node has a post-isel opcode, directly corresponding to a MachineInstr opcode.
LLVM_ABI void dumprFull(const SelectionDAG *G=nullptr) const
printrFull to dbgs().
unsigned getOpcode() const
Return the SelectionDAG opcode value for this node.
bool isDivergent() const
LLVM_ABI bool isOnlyUserOf(const SDNode *N) const
Return true if this node is the only use of N.
iterator_range< value_op_iterator > op_values() const
unsigned getIROrder() const
Return the node ordering.
static constexpr size_t getMaxNumOperands()
Return the maximum number of operands that a SDNode can hold.
iterator_range< use_iterator > uses()
MemSDNodeBitfields MemSDNodeBits
bool getHasDebugValue() const
SDNodeFlags getFlags() const
void setNodeId(int Id)
Set unique node id.
LLVM_ABI void intersectFlagsWith(const SDNodeFlags Flags)
Clear any flags in this node that aren't also set in Flags.
static bool hasPredecessorHelper(const SDNode *N, SmallPtrSetImpl< const SDNode * > &Visited, SmallVectorImpl< const SDNode * > &Worklist, unsigned int MaxSteps=0, bool TopologicalPrune=false)
Returns true if N is a predecessor of any node in Worklist.
uint64_t getAsZExtVal() const
Helper method returns the zero-extended integer value of a ConstantSDNode.
bool use_empty() const
Return true if there are no uses of this node.
unsigned getNumValues() const
Return the number of values defined/returned by this operator.
unsigned getNumOperands() const
Return the number of values used by this operation.
const SDValue & getOperand(unsigned Num) const
static LLVM_ABI bool areOnlyUsersOf(ArrayRef< const SDNode * > Nodes, const SDNode *N)
Return true if all the users of N are contained in Nodes.
use_iterator use_begin() const
Provide iteration support to walk over all uses of an SDNode.
LLVM_ABI bool isOperandOf(const SDNode *N) const
Return true if this node is an operand of N.
const APInt & getConstantOperandAPInt(unsigned Num) const
Helper method returns the APInt of a ConstantSDNode operand.
std::optional< APInt > bitcastToAPInt() const
LLVM_ABI bool hasPredecessor(const SDNode *N) const
Return true if N is a predecessor of this node.
LLVM_ABI bool hasAnyUseOfValue(unsigned Value) const
Return true if there are any use of the indicated value.
EVT getValueType(unsigned ResNo) const
Return the type of a specified result.
bool isUndef() const
Returns true if the node type is UNDEF or POISON.
op_iterator op_end() const
op_iterator op_begin() const
static use_iterator use_end()
LLVM_ABI void DropOperands()
Release the operands and set this node to have zero operands.
SDNode(unsigned Opc, unsigned Order, DebugLoc dl, SDVTList VTs)
Create an SDNode.
Represents a use of a SDNode.
SDNode * getUser()
This returns the SDNode that contains this Use.
Unlike LLVM values, Selection DAG nodes may return multiple values as the result of a computation.
bool isUndef() const
SDNode * getNode() const
get the SDNode which holds the desired result
bool hasOneUse() const
Return true if there is exactly one node using value ResNo of Node, in exactly one operand.
LLVM_ABI bool isOperandOf(const SDNode *N) const
Return true if the referenced return value is an operand of N.
SDValue()=default
LLVM_ABI bool reachesChainWithoutSideEffects(SDValue Dest, unsigned Depth=2) const
Return true if this operand (which must be a chain) reaches the specified operand without crossing an...
SDValue getValue(unsigned R) const
EVT getValueType() const
Return the ValueType of the referenced return value.
TypeSize getValueSizeInBits() const
Returns the size of the value in bits.
const SDValue & getOperand(unsigned i) const
bool use_empty() const
Return true if there are no nodes using value ResNo of Node.
const APInt & getConstantOperandAPInt(unsigned i) const
uint64_t getScalarValueSizeInBits() const
unsigned getResNo() const
get the index which selects a specific result in the SDNode
uint64_t getConstantOperandVal(unsigned i) const
unsigned getOpcode() const
virtual void verifyTargetNode(const SelectionDAG &DAG, const SDNode *N) const
Checks that the given target-specific node is valid. Aborts if it is not.
This is used to represent a portion of an LLVM function in a low-level Data Dependence DAG representa...
LLVM_ABI SDValue getElementCount(const SDLoc &DL, EVT VT, ElementCount EC)
LLVM_ABI Align getReducedAlign(EVT VT, bool UseABI)
In most cases this function returns the ABI alignment for a given type, except for illegal vector typ...
LLVM_ABI SDValue getShiftAmountOperand(EVT LHSTy, SDValue Op)
Return the specified value casted to the target's desired shift amount type.
LLVM_ABI std::pair< SDValue, SDValue > getMemccpy(SDValue Chain, const SDLoc &dl, SDValue Dst, SDValue Src, SDValue C, SDValue Size, const CallInst *CI)
Lower a memccpy operation into a target library call and return the resulting chain and call result a...
LLVM_ABI SDValue emitStackConvert(SDValue SrcOp, EVT SlotVT, EVT DestVT, const SDLoc &DL, SDValue Chain)
Emit a store/load combination to the stack.
LLVM_ABI bool isKnownNeverLogicalZero(SDValue Op, const APInt &DemandedElts, unsigned Depth=0) const
Test whether the given floating point SDValue (or all elements of it, if it is a vector) is known to ...
LLVM_ABI SDValue getExtLoadVP(ISD::LoadExtType ExtType, const SDLoc &dl, EVT VT, SDValue Chain, SDValue Ptr, SDValue Mask, SDValue EVL, MachinePointerInfo PtrInfo, EVT MemVT, MaybeAlign Alignment, MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo, bool IsExpanding=false)
SDValue getExtractVectorElt(const SDLoc &DL, EVT VT, SDValue Vec, unsigned Idx)
Extract element at Idx from Vec.
LLVM_ABI SDValue getSplatSourceVector(SDValue V, int &SplatIndex)
If V is a splatted value, return the source vector and its splat index.
LLVM_ABI SDValue getLabelNode(unsigned Opcode, const SDLoc &dl, SDValue Root, MCSymbol *Label)
LLVM_ABI OverflowKind computeOverflowForUnsignedSub(SDValue N0, SDValue N1) const
Determine if the result of the unsigned sub of 2 nodes can overflow.
LLVM_ABI unsigned ComputeMaxSignificantBits(SDValue Op, unsigned Depth=0) const
Get the upper bound on bit size for this Value Op as a signed integer.
const SDValue & getRoot() const
Return the root tag of the SelectionDAG.
LLVM_ABI std::pair< SDValue, SDValue > getStrlen(SDValue Chain, const SDLoc &dl, SDValue Src, const CallInst *CI)
Lower a strlen operation into a target library call and return the resulting chain and call result as...
LLVM_ABI SDValue getMaskedGather(SDVTList VTs, EVT MemVT, const SDLoc &dl, ArrayRef< SDValue > Ops, MachineMemOperand *MMO, ISD::MemIndexType IndexType, ISD::LoadExtType ExtTy)
LLVM_ABI unsigned getHasPredecessorMaxSteps() const
LLVM_ABI SDValue FoldSetCC(EVT VT, SDValue N1, SDValue N2, ISD::CondCode Cond, const SDLoc &dl, SDNodeFlags Flags={})
Constant fold a setcc to true or false.
bool isKnownNeverSNaN(SDValue Op, const APInt &DemandedElts, unsigned Depth=0) const
LLVM_ABI SDValue makeStateFunctionCall(unsigned LibFunc, SDValue Ptr, SDValue InChain, SDNode *Node)
Helper used to make a call to a library function that has one argument of pointer type.
LLVM_ABI std::optional< bool > isBoolConstant(SDValue N) const
Check if a value \op N is a constant using the target's BooleanContent for its type.
LLVM_ABI SDValue getStackArgumentTokenFactor(SDValue Chain)
Compute a TokenFactor to force all the incoming stack arguments to be loaded from the stack.
const TargetSubtargetInfo & getSubtarget() const
LLVM_ABI ConstantRange computeConstantRange(SDValue Op, bool ForSigned, unsigned Depth=0) const
Determine the possible constant range of an integer or vector of integers.
LLVM_ABI SDValue getMergeValues(ArrayRef< SDValue > Ops, const SDLoc &dl)
Create a MERGE_VALUES node from the given operands.
LLVM_ABI SDVTList getVTList(EVT VT)
Return an SDVTList that represents the list of values specified.
LLVM_ABI SDValue getShiftAmountConstant(uint64_t Val, EVT VT, const SDLoc &DL)
LLVM_ABI void updateDivergence(SDNode *N)
LLVM_ABI SDValue getSplatValue(SDValue V, bool LegalTypes=false)
If V is a splat vector, return its scalar source operand by extracting that element from the source v...
LLVM_ABI SDValue getAllOnesConstant(const SDLoc &DL, EVT VT, bool IsTarget=false, bool IsOpaque=false)
LLVM_ABI MachineSDNode * getMachineNode(unsigned Opcode, const SDLoc &dl, EVT VT)
These are used for target selectors to create a new node with specified return type(s),...
LLVM_ABI void ExtractVectorElements(SDValue Op, SmallVectorImpl< SDValue > &Args, unsigned Start=0, unsigned Count=0, EVT EltVT=EVT())
Append the extracted elements from Start to Count out of the vector Op in Args.
LLVM_ABI SDValue getAtomicMemset(SDValue Chain, const SDLoc &dl, SDValue Dst, SDValue Value, SDValue Size, Type *SizeTy, unsigned ElemSz, bool isTailCall, MachinePointerInfo DstPtrInfo)
LLVM_ABI SDValue getAtomicLoad(ISD::LoadExtType ExtType, const SDLoc &dl, EVT MemVT, EVT VT, SDValue Chain, SDValue Ptr, MachineMemOperand *MMO)
LLVM_ABI SDNode * getNodeIfExists(unsigned Opcode, SDVTList VTList, ArrayRef< SDValue > Ops, const SDNodeFlags Flags, bool AllowCommute=false)
Get the specified node if it's already available, or else return NULL.
LLVM_ABI SDValue getPseudoProbeNode(const SDLoc &Dl, SDValue Chain, uint64_t Guid, uint64_t Index, uint32_t Attr)
Creates a PseudoProbeSDNode with function GUID Guid and the index of the block Index it is probing,...
LLVM_ABI SDNode * SelectNodeTo(SDNode *N, unsigned MachineOpc, EVT VT)
These are used for target selectors to mutate the specified node to have the specified return type,...
LLVM_ABI const BasicBlock * getBasicBlock() const
LLVM_ABI SelectionDAG(const TargetMachine &TM, CodeGenOptLevel)
LLVM_ABI SDValue getMemset(SDValue Chain, const SDLoc &dl, SDValue Dst, SDValue Src, SDValue Size, Align Alignment, bool isVol, bool AlwaysInline, const CallInst *CI, MachinePointerInfo DstPtrInfo, const AAMDNodes &AAInfo=AAMDNodes())
LLVM_ABI SDValue getConstantPool(const Constant *C, EVT VT, MaybeAlign Align=std::nullopt, int Offs=0, bool isT=false, unsigned TargetFlags=0)
LLVM_ABI SDValue getStridedLoadVP(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &DL, SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Stride, SDValue Mask, SDValue EVL, EVT MemVT, MachineMemOperand *MMO, bool IsExpanding=false)
LLVM_ABI SDValue getAtomicCmpSwap(unsigned Opcode, const SDLoc &dl, EVT MemVT, SDVTList VTs, SDValue Chain, SDValue Ptr, SDValue Cmp, SDValue Swp, MachineMemOperand *MMO)
Gets a node for an atomic cmpxchg op.
LLVM_ABI SDValue makeEquivalentMemoryOrdering(SDValue OldChain, SDValue NewMemOpChain)
If an existing load has uses of its chain, create a token factor node with that chain and the new mem...
LLVM_ABI bool isConstantIntBuildVectorOrConstantInt(SDValue N, bool AllowOpaques=true) const
Test whether the given value is a constant int or similar node.
LLVM_ABI void ReplaceAllUsesOfValuesWith(const SDValue *From, const SDValue *To, unsigned Num)
Like ReplaceAllUsesOfValueWith, but for multiple values at once.
LLVM_ABI SDValue getJumpTableDebugInfo(int JTI, SDValue Chain, const SDLoc &DL)
LLVM_ABI SDValue getSymbolFunctionGlobalAddress(SDValue Op, Function **TargetFunction=nullptr)
Return a GlobalAddress of the function from the current module with name matching the given ExternalS...
LLVM_ABI std::optional< unsigned > getValidMaximumShiftAmount(SDValue V, const APInt &DemandedElts, unsigned Depth=0) const
If a SHL/SRA/SRL node V has shift amounts that are all less than the element bit-width of the shift n...
LLVM_ABI bool areNonVolatileConsecutiveLoads(LoadSDNode *LD, LoadSDNode *Base, TypeSize Bytes, int Dist) const
Return true if loads are next to each other and can be merged.
LLVM_ABI SDValue UnrollVectorOp(SDNode *N, unsigned ResNE=0)
Utility function used by legalize and lowering to "unroll" a vector operation by splitting out the sc...
LLVM_ABI SDValue getVScale(const SDLoc &DL, EVT VT, APInt MulImm)
Return a node that represents the runtime scaling 'MulImm * RuntimeVL'.
LLVM_ABI SDValue getConstantFP(double Val, const SDLoc &DL, EVT VT, bool isTarget=false)
Create a ConstantFPSDNode wrapping a constant value.
OverflowKind
Used to represent the possible overflow behavior of an operation.
LLVM_ABI bool haveNoCommonBitsSet(SDValue A, SDValue B) const
Return true if A and B have no common bits set.
LLVM_ABI SDValue getAddrSpaceCast(const SDLoc &dl, EVT VT, SDValue Ptr, unsigned SrcAS, unsigned DestAS, const SDNodeFlags Flags=SDNodeFlags())
Return an AddrSpaceCastSDNode.
SDValue getExtractSubvector(const SDLoc &DL, EVT VT, SDValue Vec, unsigned Idx)
Return the VT typed sub-vector of Vec at Idx.
LLVM_ABI bool cannotBeOrderedNegativeFP(SDValue Op) const
Test whether the given float value is known to be positive.
LLVM_ABI SDValue getRegister(Register Reg, EVT VT)
LLVM_ABI bool calculateDivergence(SDNode *N)
LLVM_ABI std::pair< SDValue, SDValue > getStrcmp(SDValue Chain, const SDLoc &dl, SDValue S0, SDValue S1, const CallInst *CI)
Lower a strcmp operation into a target library call and return the resulting chain and call result as...
LLVM_ABI SDValue getGetFPEnv(SDValue Chain, const SDLoc &dl, SDValue Ptr, EVT MemVT, MachineMemOperand *MMO)
LLVM_ABI SDValue getAssertAlign(const SDLoc &DL, SDValue V, Align A)
Return an AssertAlignSDNode.
LLVM_ABI SDNode * mutateStrictFPToFP(SDNode *Node)
Mutate the specified strict FP node to its non-strict equivalent, unlinking the node from its chain a...
LLVM_ABI bool canIgnoreSignBitOfZero(const SDUse &Use) const
Check if the user of Use produces the same result regardless of the sign of a zero in the used float ...
LLVM_ABI bool SignBitIsZeroFP(SDValue Op, unsigned Depth=0) const
Return true if the sign bit of Op is known to be zero, for a floating-point value.
LLVM_ABI SDValue getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef< SDValue > Ops, EVT MemVT, MachinePointerInfo PtrInfo, Align Alignment, MachineMemOperand::Flags Flags=MachineMemOperand::MOLoad|MachineMemOperand::MOStore, LocationSize Size=LocationSize::precise(0), const AAMDNodes &AAInfo=AAMDNodes())
Creates a MemIntrinsicNode that may produce a result and takes a list of operands.
SDValue getInsertSubvector(const SDLoc &DL, SDValue Vec, SDValue SubVec, unsigned Idx)
Insert SubVec at the Idx element of Vec.
LLVM_ABI SDValue getStepVector(const SDLoc &DL, EVT ResVT, const APInt &StepVal)
Returns a vector of type ResVT whose elements contain the linear sequence <0, Step,...
SDValue getSetCC(const SDLoc &DL, EVT VT, SDValue LHS, SDValue RHS, ISD::CondCode Cond, SDValue Chain=SDValue(), bool IsSignaling=false, SDNodeFlags Flags={})
Helper function to make it easier to build SetCC's if you just have an ISD::CondCode instead of an SD...
LLVM_ABI SDValue getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, SDValue Chain, SDValue Ptr, SDValue Val, MachineMemOperand *MMO)
Gets a node for an atomic op, produces result (if relevant) and chain and takes 2 operands.
LLVM_ABI Align getEVTAlign(EVT MemoryVT) const
Compute the default alignment value for the given type.
LLVM_ABI bool shouldOptForSize() const
LLVM_ABI bool hasSwiftErrorArg() const
LLVM_ABI SDValue buildVectorFromUnrolledParts(EVT VT, const SDLoc &DL, ArrayRef< SDValue > Scalars)
Returns a vector constructed from the scalar values in order.
LLVM_ABI SDValue getNOT(const SDLoc &DL, SDValue Val, EVT VT)
Create a bitwise NOT operation as (XOR Val, -1).
LLVM_ABI SDValue getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst, SDValue Src, SDValue Size, Align DstAlign, Align SrcAlign, bool isVol, bool AlwaysInline, const CallInst *CI, std::optional< bool > OverrideTailCall, MachinePointerInfo DstPtrInfo, MachinePointerInfo SrcPtrInfo, const AAMDNodes &AAInfo=AAMDNodes(), BatchAAResults *BatchAA=nullptr)
const TargetLowering & getTargetLoweringInfo() const
LLVM_ABI bool isEqualTo(SDValue A, SDValue B) const
Test whether two SDValues are known to compare equal.
static constexpr unsigned MaxRecursionDepth
LLVM_ABI unsigned getMaxRuntimeNumElements(EVT VT) const
Returns the maximum runtime number of elements in VT if known, or 0 otherwise.
LLVM_ABI SDValue getStridedStoreVP(SDValue Chain, const SDLoc &DL, SDValue Val, SDValue Ptr, SDValue Offset, SDValue Stride, SDValue Mask, SDValue EVL, EVT MemVT, MachineMemOperand *MMO, ISD::MemIndexedMode AM, bool IsTruncating=false, bool IsCompressing=false)
bool isGuaranteedNotToBePoison(SDValue Op, unsigned Depth=0) const
Return true if this function can prove that Op is never poison.
LLVM_ABI SDValue getIdentityElement(unsigned Opcode, const SDLoc &DL, EVT VT, SDNodeFlags Flags)
Get the (commutative) identity element for the given opcode, if it exists.
LLVM_ABI SDValue expandVACopy(SDNode *Node)
Expand the specified ISD::VACOPY node as the Legalize pass would.
LLVM_ABI SDValue getIndexedMaskedLoad(SDValue OrigLoad, const SDLoc &dl, SDValue Base, SDValue Offset, ISD::MemIndexedMode AM)
LLVM_ABI APInt computeVectorKnownZeroElements(SDValue Op, const APInt &DemandedElts, unsigned Depth=0) const
For each demanded element of a vector, see if it is known to be zero.
LLVM_ABI void AddDbgValue(SDDbgValue *DB, bool isParameter)
Add a dbg_value SDNode.
bool NewNodesMustHaveLegalTypes
When true, additional steps are taken to ensure that getConstant() and similar functions return DAG n...
LLVM_ABI std::pair< EVT, EVT > GetSplitDestVTs(const EVT &VT) const
Compute the VTs needed for the low/hi parts of a type which is split (or expanded) into two not neces...
LLVM_ABI void salvageDebugInfo(SDNode &N)
To be invoked on an SDNode that is slated to be erased.
LLVM_ABI SDNode * MorphNodeTo(SDNode *N, unsigned Opc, SDVTList VTs, ArrayRef< SDValue > Ops)
This mutates the specified node to have the specified return type, opcode, and operands.
LLVM_ABI std::pair< SDValue, SDValue > UnrollVectorOverflowOp(SDNode *N, unsigned ResNE=0)
Like UnrollVectorOp(), but for the [US](ADD|SUB|MUL)O family of opcodes.
allnodes_const_iterator allnodes_begin() const
SDValue getUNDEF(EVT VT)
Return an UNDEF node. UNDEF does not have a useful SDLoc.
LLVM_ABI SDValue getGatherVP(SDVTList VTs, EVT VT, const SDLoc &dl, ArrayRef< SDValue > Ops, MachineMemOperand *MMO, ISD::MemIndexType IndexType)
SDValue getBuildVector(EVT VT, const SDLoc &DL, ArrayRef< SDValue > Ops)
Return an ISD::BUILD_VECTOR node.
LLVM_ABI SDValue getBitcastedAnyExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of integer type, to the integer type VT, by first bitcasting (from potentia...
LLVM_ABI bool isSplatValue(SDValue V, const APInt &DemandedElts, APInt &UndefElts, unsigned Depth=0) const
Test whether V has a splatted value for all the demanded elements.
LLVM_ABI void DeleteNode(SDNode *N)
Remove the specified node from the system.
LLVM_ABI SDValue getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val, SDValue Ptr, SDValue Offset, MachinePointerInfo PtrInfo, EVT SVT, Align Alignment, MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const MMOMetadata &Metadata=MMOMetadata())
LLVM_ABI SDValue getBitcast(EVT VT, SDValue V)
Return a bitcast using the SDLoc of the value operand, and casting to the provided type.
LLVM_ABI SDDbgValue * getDbgValueList(DIVariable *Var, DIExpression *Expr, ArrayRef< SDDbgOperand > Locs, ArrayRef< SDNode * > Dependencies, bool IsIndirect, const DebugLoc &DL, unsigned O, bool IsVariadic)
Creates a SDDbgValue node from a list of locations.
LLVM_ABI std::pair< SDValue, SDValue > getStrcpy(SDValue Chain, const SDLoc &dl, SDValue Dst, SDValue Src, const CallInst *CI)
Lower a strcpy operation into a target library call and return the resulting chain and call result as...
SDValue getSelect(const SDLoc &DL, EVT VT, SDValue Cond, SDValue LHS, SDValue RHS, SDNodeFlags Flags=SDNodeFlags())
Helper function to make it easier to build Select's if you just have operands and don't want to check...
LLVM_ABI SDValue getNegative(SDValue Val, const SDLoc &DL, EVT VT)
Create negative operation as (SUB 0, Val).
LLVM_ABI std::optional< unsigned > getValidShiftAmount(SDValue V, const APInt &DemandedElts, unsigned Depth=0) const
If a SHL/SRA/SRL node V has a uniform shift amount that is less than the element bit-width of the shi...
LLVM_ABI void setNodeMemRefs(MachineSDNode *N, ArrayRef< MachineMemOperand * > NewMemRefs)
Mutate the specified machine node's memory references to the provided list.
LLVM_ABI SDValue simplifySelect(SDValue Cond, SDValue TVal, SDValue FVal)
Try to simplify a select/vselect into 1 of its operands or a constant.
LLVM_ABI SDValue getZeroExtendInReg(SDValue Op, const SDLoc &DL, EVT VT)
Return the expression required to zero extend the Op value assuming it was the smaller SrcTy value.
LLVM_ABI bool isConstantFPBuildVectorOrConstantFP(SDValue N) const
Test whether the given value is a constant FP or similar node.
const DataLayout & getDataLayout() const
LLVM_ABI SDValue getConstFP(std::optional< FPFoldResult > Result, const SDLoc &DL, EVT VT, bool isTarget=false)
Return the folded constant, or an empty SDValue if folding failed.
LLVM_ABI SDValue getPartialReduceMLS(unsigned Opc, const SDLoc &DL, SDValue Acc, SDValue LHS, SDValue RHS)
Get an expression that implements a partial multiply-subtract reduction.
LLVM_ABI SDValue expandVAArg(SDNode *Node)
Expand the specified ISD::VAARG node as the Legalize pass would.
LLVM_ABI SDValue getTokenFactor(const SDLoc &DL, SmallVectorImpl< SDValue > &Vals)
Creates a new TokenFactor containing Vals.
LLVM_ABI SDValue getStore(SDValue Chain, const SDLoc &dl, SDValue Val, SDValue Ptr, MachinePointerInfo PtrInfo, Align Alignment, MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const MMOMetadata &Metadata=MMOMetadata())
Helper function to build ISD::STORE nodes.
LLVM_ABI bool doesNodeExist(unsigned Opcode, SDVTList VTList, ArrayRef< SDValue > Ops)
Check if a node exists without modifying its flags.
LLVM_ABI bool areNonVolatileConsecutiveStores(StoreSDNode *ST, StoreSDNode *Base, TypeSize Bytes, int Dist) const
Return true if stores are next to each other and can be merged.
LLVM_ABI ConstantRange computeConstantRangeIncludingKnownBits(SDValue Op, bool ForSigned, unsigned Depth=0) const
Combine constant ranges from computeConstantRange() and computeKnownBits().
const SelectionDAGTargetInfo & getSelectionDAGInfo() const
LLVM_ABI SDValue getMaskedHistogram(SDVTList VTs, EVT MemVT, const SDLoc &dl, ArrayRef< SDValue > Ops, MachineMemOperand *MMO, ISD::MemIndexType IndexType)
LLVM_ABI SDDbgLabel * getDbgLabel(DILabel *Label, const DebugLoc &DL, unsigned O)
Creates a SDDbgLabel node.
LLVM_ABI SDValue getStoreVP(SDValue Chain, const SDLoc &dl, SDValue Val, SDValue Ptr, SDValue Offset, SDValue Mask, SDValue EVL, EVT MemVT, MachineMemOperand *MMO, ISD::MemIndexedMode AM, bool IsTruncating=false, bool IsCompressing=false)
LLVM_ABI OverflowKind computeOverflowForUnsignedMul(SDValue N0, SDValue N1) const
Determine if the result of the unsigned mul of 2 nodes can overflow.
LLVM_ABI void copyExtraInfo(SDNode *From, SDNode *To)
Copy extra info associated with one node to another.
LLVM_ABI SDValue getConstant(uint64_t Val, const SDLoc &DL, EVT VT, bool isTarget=false, bool isOpaque=false)
Create a ConstantSDNode wrapping a constant value.
LLVM_ABI SDValue getMemBasePlusOffset(SDValue Base, TypeSize Offset, const SDLoc &DL, const SDNodeFlags Flags=SDNodeFlags())
Returns sum of the base pointer and offset.
LLVM_ABI SDValue getGlobalAddress(const GlobalValue *GV, const SDLoc &DL, EVT VT, int64_t offset=0, bool isTargetGA=false, unsigned TargetFlags=0)
LLVM_ABI SDValue getVAArg(EVT VT, const SDLoc &dl, SDValue Chain, SDValue Ptr, SDValue SV, unsigned Align)
VAArg produces a result and token chain, and takes a pointer and a source value as input.
LLVM_ABI SDValue getLoadFFVP(EVT VT, const SDLoc &DL, SDValue Chain, SDValue Ptr, SDValue Mask, SDValue EVL, MachineMemOperand *MMO)
LLVM_ABI SDValue getTypeSize(const SDLoc &DL, EVT VT, TypeSize TS)
LLVM_ABI SDValue getMDNode(const MDNode *MD)
Return an MDNodeSDNode which holds an MDNode.
LLVM_ABI void clear()
Clear state and free memory necessary to make this SelectionDAG ready to process a new block.
LLVM_ABI std::pair< SDValue, SDValue > getMemcmp(SDValue Chain, const SDLoc &dl, SDValue Dst, SDValue Src, SDValue Size, const CallInst *CI)
Lower a memcmp operation into a target library call and return the resulting chain and call result as...
LLVM_ABI void ReplaceAllUsesWith(SDValue From, SDValue To)
Modify anything using 'From' to use 'To' instead.
LLVM_ABI SDValue getCommutedVectorShuffle(const ShuffleVectorSDNode &SV)
Returns an ISD::VECTOR_SHUFFLE node semantically equivalent to the shuffle node in input but with swa...
LLVM_ABI SDValue getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl, EVT VT, SDValue Chain, SDValue Ptr, MachinePointerInfo PtrInfo, EVT MemVT, MaybeAlign Alignment=MaybeAlign(), MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const MMOMetadata &Metadata=MMOMetadata())
LLVM_ABI std::pair< SDValue, SDValue > SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT, const EVT &HiVT)
Split the vector with EXTRACT_SUBVECTOR using the provided VTs and return the low/high part.
LLVM_ABI SDValue getSignedConstant(int64_t Val, const SDLoc &DL, EVT VT, bool isTarget=false, bool isOpaque=false)
LLVM_ABI SDValue getSrcValue(const Value *v)
Construct a node to track a Value* through the backend.
SDValue getSplatVector(EVT VT, const SDLoc &DL, SDValue Op)
LLVM_ABI SDValue getAtomicMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst, SDValue Src, SDValue Size, Type *SizeTy, unsigned ElemSz, bool isTailCall, MachinePointerInfo DstPtrInfo, MachinePointerInfo SrcPtrInfo)
LLVM_ABI OverflowKind computeOverflowForSignedMul(SDValue N0, SDValue N1) const
Determine if the result of the signed mul of 2 nodes can overflow.
LLVM_ABI MaybeAlign InferPtrAlign(SDValue Ptr) const
Infer alignment of a load / store address.
LLVM_ABI void dump() const
Dump the textual format of this DAG.
LLVM_ABI bool MaskedValueIsAllOnes(SDValue Op, const APInt &Mask, unsigned Depth=0) const
Return true if '(Op & Mask) == Mask'.
LLVM_ABI bool SignBitIsZero(SDValue Op, unsigned Depth=0) const
Return true if the sign bit of Op is known to be zero.
LLVM_ABI void RemoveDeadNodes()
This method deletes all unreachable nodes in the SelectionDAG.
LLVM_ABI void RemoveDeadNode(SDNode *N)
Remove the specified node from the system.
LLVM_ABI void AddDbgLabel(SDDbgLabel *DB)
Add a dbg_label SDNode.
bool isConstantValueOfAnyType(SDValue N) const
LLVM_ABI bool canCreateUndefOrPoison(SDValue Op, const APInt &DemandedElts, UndefPoisonKind Kind=UndefPoisonKind::UndefOrPoison, bool ConsiderFlags=true, unsigned Depth=0) const
Return true if Op can create undef or poison from non-undef & non-poison operands.
SDValue getInsertVectorElt(const SDLoc &DL, SDValue Vec, SDValue Elt, unsigned Idx)
Insert Elt into Vec at offset Idx.
LLVM_ABI SDValue getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT, SDValue Operand)
A convenience function for creating TargetInstrInfo::EXTRACT_SUBREG nodes.
LLVM_ABI SDValue getSExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of integer type, to the integer type VT, by either sign-extending or trunca...
LLVM_ABI SDDbgValue * getVRegDbgValue(DIVariable *Var, DIExpression *Expr, Register VReg, bool IsIndirect, const DebugLoc &DL, unsigned O)
Creates a VReg SDDbgValue node.
LLVM_ABI SDValue getLoad(EVT VT, const SDLoc &dl, SDValue Chain, SDValue Ptr, MachinePointerInfo PtrInfo, MaybeAlign Alignment=MaybeAlign(), MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const MMOMetadata &Metadata=MMOMetadata())
Loads are not normal binary operators: their result type is not determined by their operands,...
LLVM_ABI KnownFPClass computeKnownFPClass(SDValue Op, FPClassTest InterestedClasses, unsigned Depth=0) const
Determine floating-point class information about Op.
LLVM_ABI bool isIdentityElement(unsigned Opc, SDNodeFlags Flags, SDValue V, unsigned OperandNo, unsigned Depth=0) const
Returns true if V is an identity element of Opc with Flags.
LLVM_ABI SDValue getEHLabel(const SDLoc &dl, SDValue Root, MCSymbol *Label)
LLVM_ABI bool isGuaranteedNotToBeUndefOrPoison(SDValue Op, UndefPoisonKind Kind=UndefPoisonKind::UndefOrPoison, unsigned Depth=0) const
Return true if this function can prove that Op is never poison and, Kind can be used to track poison ...
LLVM_ABI bool isKnownNeverZero(SDValue Op, unsigned Depth=0) const
Test whether the given SDValue is known to contain non-zero value(s).
LLVM_ABI SDValue getIndexedStore(SDValue OrigStore, const SDLoc &dl, SDValue Base, SDValue Offset, ISD::MemIndexedMode AM)
LLVM_ABI SDValue FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL, EVT VT, ArrayRef< SDValue > Ops, SDNodeFlags Flags=SDNodeFlags())
LLVM_ABI std::optional< unsigned > getValidMinimumShiftAmount(SDValue V, const APInt &DemandedElts, unsigned Depth=0) const
If a SHL/SRA/SRL node V has shift amounts that are all less than the element bit-width of the shift n...
LLVM_ABI SDValue getSetFPEnv(SDValue Chain, const SDLoc &dl, SDValue Ptr, EVT MemVT, MachineMemOperand *MMO)
LLVM_ABI SDValue getBoolExtOrTrunc(SDValue Op, const SDLoc &SL, EVT VT, EVT OpVT)
Convert Op, which must be of integer type, to the integer type VT, by using an extension appropriate ...
LLVM_ABI SDValue getMaskedStore(SDValue Chain, const SDLoc &dl, SDValue Val, SDValue Base, SDValue Offset, SDValue Mask, EVT MemVT, MachineMemOperand *MMO, ISD::MemIndexedMode AM, bool IsTruncating=false, bool IsCompressing=false)
LLVM_ABI SDValue getExternalSymbol(const char *Sym, EVT VT)
const TargetMachine & getTarget() const
LLVM_ABI std::pair< SDValue, SDValue > getStrictFPExtendOrRound(SDValue Op, SDValue Chain, const SDLoc &DL, EVT VT)
Convert Op, which must be a STRICT operation of float type, to the float type VT, by either extending...
LLVM_ABI std::pair< SDValue, SDValue > SplitEVL(SDValue N, EVT VecVT, const SDLoc &DL)
Split the explicit vector length parameter of a VP operation.
LLVM_ABI SDValue getPtrExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of integer type, to the integer type VT, by either truncating it or perform...
LLVM_ABI SDValue getMaskFromElementCount(const SDLoc &DL, EVT VT, ElementCount Len)
Return a vector with the first 'Len' lanes set to true and remaining lanes set to false.
LLVM_ABI SDValue getAnyExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of integer type, to the integer type VT, by either any-extending or truncat...
iterator_range< allnodes_iterator > allnodes()
LLVM_ABI SDValue getBlockAddress(const BlockAddress *BA, EVT VT, int64_t Offset=0, bool isTarget=false, unsigned TargetFlags=0)
LLVM_ABI SDValue WidenVector(const SDValue &N, const SDLoc &DL)
Widen the vector up to the next power of two using INSERT_SUBVECTOR.
const LibcallLoweringInfo & getLibcalls() const
LLVM_ABI SDValue getLoadVP(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &dl, SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Mask, SDValue EVL, MachinePointerInfo PtrInfo, EVT MemVT, Align Alignment, MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo, const MDNode *Ranges=nullptr, bool IsExpanding=false)
LLVM_ABI SDValue getIntPtrConstant(uint64_t Val, const SDLoc &DL, bool isTarget=false)
LLVM_ABI SDDbgValue * getConstantDbgValue(DIVariable *Var, DIExpression *Expr, const Value *C, const DebugLoc &DL, unsigned O)
Creates a constant SDDbgValue node.
LLVM_ABI SDValue getScatterVP(SDVTList VTs, EVT VT, const SDLoc &dl, ArrayRef< SDValue > Ops, MachineMemOperand *MMO, ISD::MemIndexType IndexType)
LLVM_ABI SDValue getValueType(EVT)
LLVM_ABI SDValue getLifetimeNode(bool IsStart, const SDLoc &dl, SDValue Chain, int FrameIndex)
Creates a LifetimeSDNode that starts (IsStart==true) or ends (IsStart==false) the lifetime of the Fra...
ArrayRef< SDDbgValue * > GetDbgValues(const SDNode *SD) const
Get the debug values which reference the given SDNode.
LLVM_ABI SDValue getNode(unsigned Opcode, const SDLoc &DL, EVT VT, ArrayRef< SDUse > Ops)
Gets or creates the specified node.
LLVM_ABI OverflowKind computeOverflowForSignedAdd(SDValue N0, SDValue N1) const
Determine if the result of the signed addition of 2 nodes can overflow.
LLVM_ABI SDValue getFPExtendOrRound(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of float type, to the float type VT, by either extending or rounding (by tr...
LLVM_ABI unsigned AssignTopologicalOrder()
Topological-sort the AllNodes list and a assign a unique node id for each node in the DAG based on th...
ilist< SDNode >::size_type allnodes_size() const
LLVM_ABI bool isKnownNeverNaN(SDValue Op, const APInt &DemandedElts, bool SNaN=false, unsigned Depth=0) const
Test whether the given SDValue (or all elements of it, if it is a vector) is known to never be NaN in...
LLVM_ABI SDValue FoldConstantBuildVector(BuildVectorSDNode *BV, const SDLoc &DL, EVT DstEltVT)
Fold BUILD_VECTOR of constants/undefs to the destination type BUILD_VECTOR of constants/undefs elemen...
LLVM_ABI SDValue getAtomicMemmove(SDValue Chain, const SDLoc &dl, SDValue Dst, SDValue Src, SDValue Size, Type *SizeTy, unsigned ElemSz, bool isTailCall, MachinePointerInfo DstPtrInfo, MachinePointerInfo SrcPtrInfo)
LLVM_ABI SDValue getIndexedMaskedStore(SDValue OrigStore, const SDLoc &dl, SDValue Base, SDValue Offset, ISD::MemIndexedMode AM)
LLVM_ABI SDValue getTruncStoreVP(SDValue Chain, const SDLoc &dl, SDValue Val, SDValue Ptr, SDValue Mask, SDValue EVL, MachinePointerInfo PtrInfo, EVT SVT, Align Alignment, MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo, bool IsCompressing=false)
SDValue getTargetConstant(uint64_t Val, const SDLoc &DL, EVT VT, bool isOpaque=false)
const TargetLibraryInfo & getLibInfo() const
LLVM_ABI unsigned ComputeNumSignBits(SDValue Op, unsigned Depth=0) const
Return the number of times the sign bit of the register is replicated into the other bits.
LLVM_ABI bool MaskedVectorIsZero(SDValue Op, const APInt &DemandedElts, unsigned Depth=0) const
Return true if 'Op' is known to be zero in DemandedElts.
LLVM_ABI SDValue getBoolConstant(bool V, const SDLoc &DL, EVT VT, EVT OpVT)
Create a true or false constant of type VT using the target's BooleanContent for type OpVT.
LLVM_ABI SDDbgValue * getFrameIndexDbgValue(DIVariable *Var, DIExpression *Expr, unsigned FI, bool IsIndirect, const DebugLoc &DL, unsigned O)
Creates a FrameIndex SDDbgValue node.
LLVM_ABI SDValue getExtStridedLoadVP(ISD::LoadExtType ExtType, const SDLoc &DL, EVT VT, SDValue Chain, SDValue Ptr, SDValue Stride, SDValue Mask, SDValue EVL, EVT MemVT, MachineMemOperand *MMO, bool IsExpanding=false)
LLVM_ABI SDValue getMemmove(SDValue Chain, const SDLoc &dl, SDValue Dst, SDValue Src, SDValue Size, Align DstAlign, Align SrcAlign, bool isVol, const CallInst *CI, std::optional< bool > OverrideTailCall, MachinePointerInfo DstPtrInfo, MachinePointerInfo SrcPtrInfo, const AAMDNodes &AAInfo=AAMDNodes(), BatchAAResults *BatchAA=nullptr)
LLVM_ABI SDValue getJumpTable(int JTI, EVT VT, bool isTarget=false, unsigned TargetFlags=0)
LLVM_ABI bool isBaseWithConstantOffset(SDValue Op) const
Return true if the specified operand is an ISD::ADD with a ConstantSDNode on the right-hand side,...
LLVM_ABI SDValue getVectorIdxConstant(uint64_t Val, const SDLoc &DL, bool isTarget=false)
LLVM_ABI void getTopologicallyOrderedNodes(SmallVectorImpl< const SDNode * > &SortedNodes) const
Get all the nodes in their topological order without modifying any states.
LLVM_ABI void ReplaceAllUsesOfValueWith(SDValue From, SDValue To)
Replace any uses of From with To, leaving uses of other values produced by From.getNode() alone.
MachineFunction & getMachineFunction() const
LLVM_ABI SDValue getFreeze(SDValue V, UndefPoisonKind Kind=UndefPoisonKind::UndefOrPoison)
Return a freeze of V using the SDLoc of the value operand.
LLVM_ABI std::pair< SDValue, SDValue > getStrstr(SDValue Chain, const SDLoc &dl, SDValue S0, SDValue S1, const CallInst *CI)
Lower a strstr operation into a target library call and return the resulting chain and call result as...
LLVM_ABI SDValue getPtrExtendInReg(SDValue Op, const SDLoc &DL, EVT VT)
Return the expression required to extend the Op as a pointer value assuming it was the smaller SrcTy ...
LLVM_ABI OverflowKind computeOverflowForUnsignedAdd(SDValue N0, SDValue N1) const
Determine if the result of the unsigned addition of 2 nodes can overflow.
SDValue getPOISON(EVT VT)
Return a POISON node. POISON does not have a useful SDLoc.
SDValue getSplatBuildVector(EVT VT, const SDLoc &DL, SDValue Op)
Return a splat ISD::BUILD_VECTOR node, consisting of Op splatted to all elements.
LLVM_ABI SDValue getErrorMergeValues(ArrayRef< EVT > ResultTypes, SDValue Chain, const SDLoc &dl)
Return poison values for each of ResultTypes, substituting Chain for any result of type MVT::Other,...
LLVM_ABI SDValue getFrameIndex(int FI, EVT VT, bool isTarget=false)
LLVM_ABI bool canIgnoreSignBitOfZeroResult(SDValue Op) const
Check if all uses of Op (limited to checking two for compile-time performance) are insensitive to sig...
LLVM_ABI void canonicalizeCommutativeBinop(unsigned Opcode, SDValue &N1, SDValue &N2) const
Swap N1 and N2 if Opcode is a commutative binary opcode and the canonical form expects the opposite o...
LLVM_ABI KnownBits computeKnownBits(SDValue Op, unsigned Depth=0) const
Determine which bits of Op are known to be either zero or one and return them in Known.
LLVM_ABI SDValue getRegisterMask(const uint32_t *RegMask)
LLVM_ABI SDValue getZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of integer type, to the integer type VT, by either zero-extending or trunca...
const SelectionDAGOptions & getSelectionDAGOptions() const
LLVM_ABI SDValue getCondCode(ISD::CondCode Cond)
LLVM_ABI bool MaskedValueIsZero(SDValue Op, const APInt &Mask, unsigned Depth=0) const
Return true if 'Op & Mask' is known to be zero.
LLVM_ABI bool isKnownToBeAPowerOfTwoFP(SDValue Val, unsigned Depth=0) const
Test if the given fp value is known to be an integer power-of-2, either positive or negative.
LLVM_ABI OverflowKind computeOverflowForSignedSub(SDValue N0, SDValue N1) const
Determine if the result of the signed sub of 2 nodes can overflow.
LLVM_ABI void init(MachineFunction &NewMF, const TargetLibraryInfo *LibraryInfo, const LibcallLoweringInfo *LibcallsInfo, UniformityInfo *UA, ProfileSummaryInfo *PSIin, BlockFrequencyInfo *BFIin, FunctionVarLocs const *FnVarLocs)
Prepare this SelectionDAG to process code in the given MachineFunction.
SDValue getObjectPtrOffset(const SDLoc &SL, SDValue Ptr, TypeSize Offset)
Create an add instruction with appropriate flags when used for addressing some offset of an object.
LLVMContext * getContext() const
LLVM_ABI SDValue simplifyFPBinop(unsigned Opcode, SDValue X, SDValue Y, SDNodeFlags Flags)
Try to simplify a floating-point binary operation into 1 of its operands or a constant.
const SDValue & setRoot(SDValue N)
Set the current root tag of the SelectionDAG.
LLVM_ABI bool isKnownToBeAPowerOfTwo(SDValue Val, bool OrZero=false, unsigned Depth=0) const
Test if the given value is known to have exactly one bit set.
LLVM_ABI void ReplaceAllOtherUsesOfValueWith(SDValue From, SDValue To, SDNode *SkipUser)
Like ReplaceAllUsesOfValueWith, but leave uses in SkipUser unchanged.
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:727
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:1716
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:1700
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:1761
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)