LLVM 24.0.0git
SelectionDAG.cpp
Go to the documentation of this file.
1//===- SelectionDAG.cpp - Implement the SelectionDAG data structures ------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This implements the SelectionDAG class.
10//
11//===----------------------------------------------------------------------===//
12
14#include "SDNodeDbgValue.h"
15#include "llvm/ADT/APFloat.h"
16#include "llvm/ADT/APInt.h"
17#include "llvm/ADT/APSInt.h"
18#include "llvm/ADT/ArrayRef.h"
19#include "llvm/ADT/BitVector.h"
20#include "llvm/ADT/DenseSet.h"
21#include "llvm/ADT/FoldingSet.h"
22#include "llvm/ADT/STLExtras.h"
25#include "llvm/ADT/Twine.h"
52#include "llvm/IR/Constant.h"
53#include "llvm/IR/Constants.h"
54#include "llvm/IR/DataLayout.h"
56#include "llvm/IR/DebugLoc.h"
58#include "llvm/IR/Function.h"
59#include "llvm/IR/GlobalValue.h"
60#include "llvm/IR/Metadata.h"
61#include "llvm/IR/Type.h"
65#include "llvm/Support/Debug.h"
75#include <algorithm>
76#include <cassert>
77#include <cstdint>
78#include <cstdlib>
79#include <limits>
80#include <optional>
81#include <string>
82#include <utility>
83#include <vector>
84
85using namespace llvm;
86using namespace llvm::SDPatternMatch;
87
88/// makeVTList - Return an instance of the SDVTList struct initialized with the
89/// specified members.
90static SDVTList makeVTList(const EVT *VTs, unsigned NumVTs) {
91 SDVTList Res = {VTs, NumVTs};
92 return Res;
93}
94
95// Default null implementations of the callbacks.
99
100void SelectionDAG::DAGNodeDeletedListener::anchor() {}
101void SelectionDAG::DAGNodeInsertedListener::anchor() {}
102
103#define DEBUG_TYPE "selectiondag"
104
105static cl::opt<bool> EnableMemCpyDAGOpt("enable-memcpy-dag-opt",
106 cl::Hidden, cl::init(true),
107 cl::desc("Gang up loads and stores generated by inlining of memcpy"));
108
109static cl::opt<int> MaxLdStGlue("ldstmemcpy-glue-max",
110 cl::desc("Number limit for gluing ld/st of memcpy."),
111 cl::Hidden, cl::init(0));
112
114 MaxSteps("has-predecessor-max-steps", cl::Hidden, cl::init(8192),
115 cl::desc("DAG combiner limit number of steps when searching DAG "
116 "for predecessor nodes"));
117
119 LLVM_DEBUG(dbgs() << Msg; V.getNode()->dump(G););
120}
121
123
124//===----------------------------------------------------------------------===//
125// ConstantFPSDNode Class
126//===----------------------------------------------------------------------===//
127
128/// isExactlyValue - We don't rely on operator== working on double values, as
129/// it returns true for things that are clearly not equal, like -0.0 and 0.0.
130/// As such, this method can be used to do an exact bit-for-bit comparison of
131/// two floating point values.
133 return getValueAPF().bitwiseIsEqual(V);
134}
135
137 const APFloat& Val) {
138 assert(VT.isFloatingPoint() && "Can only convert between FP types");
139
140 // convert modifies in place, so make a copy.
141 APFloat Val2 = APFloat(Val);
142 bool losesInfo;
144 &losesInfo);
145 return !losesInfo;
146}
147
148//===----------------------------------------------------------------------===//
149// ISD Namespace
150//===----------------------------------------------------------------------===//
151
152bool ISD::isConstantSplatVector(const SDNode *N, APInt &SplatVal) {
153 if (N->getOpcode() == ISD::SPLAT_VECTOR) {
154 if (auto OptAPInt = N->getOperand(0)->bitcastToAPInt()) {
155 unsigned EltSize =
156 N->getValueType(0).getVectorElementType().getSizeInBits();
157 SplatVal = OptAPInt->trunc(EltSize);
158 return true;
159 }
160 }
161
162 auto *BV = dyn_cast<BuildVectorSDNode>(N);
163 if (!BV)
164 return false;
165
166 APInt SplatUndef;
167 unsigned SplatBitSize;
168 bool HasUndefs;
169 unsigned EltSize = N->getValueType(0).getVectorElementType().getSizeInBits();
170 // Endianness does not matter here. We are checking for a splat given the
171 // element size of the vector, and if we find such a splat for little endian
172 // layout, then that should be valid also for big endian (as the full vector
173 // size is known to be a multiple of the element size).
174 const bool IsBigEndian = false;
175 return BV->isConstantSplat(SplatVal, SplatUndef, SplatBitSize, HasUndefs,
176 EltSize, IsBigEndian) &&
177 EltSize == SplatBitSize;
178}
179
180// FIXME: AllOnes and AllZeros duplicate a lot of code. Could these be
181// specializations of the more general isConstantSplatVector()?
182
183bool ISD::isConstantSplatVectorAllOnes(const SDNode *N, bool BuildVectorOnly) {
184 // Look through a bit convert.
185 while (N->getOpcode() == ISD::BITCAST)
186 N = N->getOperand(0).getNode();
187
188 if (!BuildVectorOnly && N->getOpcode() == ISD::SPLAT_VECTOR) {
189 APInt SplatVal;
190 return isConstantSplatVector(N, SplatVal) && SplatVal.isAllOnes();
191 }
192
193 if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
194
195 unsigned i = 0, e = N->getNumOperands();
196
197 // Skip over all of the undef values.
198 while (i != e && N->getOperand(i).isUndef())
199 ++i;
200
201 // Do not accept an all-undef vector.
202 if (i == e) return false;
203
204 // Do not accept build_vectors that aren't all constants or which have non-~0
205 // elements. We have to be a bit careful here, as the type of the constant
206 // may not be the same as the type of the vector elements due to type
207 // legalization (the elements are promoted to a legal type for the target and
208 // a vector of a type may be legal when the base element type is not).
209 // We only want to check enough bits to cover the vector elements, because
210 // we care if the resultant vector is all ones, not whether the individual
211 // constants are.
212 SDValue NotZero = N->getOperand(i);
213 if (auto OptAPInt = NotZero->bitcastToAPInt()) {
214 unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
215 if (OptAPInt->countr_one() < EltSize)
216 return false;
217 } else
218 return false;
219
220 // Okay, we have at least one ~0 value, check to see if the rest match or are
221 // undefs. Even with the above element type twiddling, this should be OK, as
222 // the same type legalization should have applied to all the elements.
223 for (++i; i != e; ++i)
224 if (N->getOperand(i) != NotZero && !N->getOperand(i).isUndef())
225 return false;
226 return true;
227}
228
229bool ISD::isConstantSplatVectorAllZeros(const SDNode *N, bool BuildVectorOnly) {
230 // Look through a bit convert.
231 while (N->getOpcode() == ISD::BITCAST)
232 N = N->getOperand(0).getNode();
233
234 if (!BuildVectorOnly && N->getOpcode() == ISD::SPLAT_VECTOR) {
235 APInt SplatVal;
236 return isConstantSplatVector(N, SplatVal) && SplatVal.isZero();
237 }
238
239 if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
240
241 bool IsAllUndef = true;
242 for (const SDValue &Op : N->op_values()) {
243 if (Op.isUndef())
244 continue;
245 IsAllUndef = false;
246 // Do not accept build_vectors that aren't all constants or which have non-0
247 // elements. We have to be a bit careful here, as the type of the constant
248 // may not be the same as the type of the vector elements due to type
249 // legalization (the elements are promoted to a legal type for the target
250 // and a vector of a type may be legal when the base element type is not).
251 // We only want to check enough bits to cover the vector elements, because
252 // we care if the resultant vector is all zeros, not whether the individual
253 // constants are.
254 if (auto OptAPInt = Op->bitcastToAPInt()) {
255 unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
256 if (OptAPInt->countr_zero() < EltSize)
257 return false;
258 } else
259 return false;
260 }
261
262 // Do not accept an all-undef vector.
263 if (IsAllUndef)
264 return false;
265 return true;
266}
267
269 return isConstantSplatVectorAllOnes(N, /*BuildVectorOnly*/ true);
270}
271
273 return isConstantSplatVectorAllZeros(N, /*BuildVectorOnly*/ true);
274}
275
277 if (N->getOpcode() != ISD::BUILD_VECTOR)
278 return false;
279
280 for (const SDValue &Op : N->op_values()) {
281 if (Op.isUndef())
282 continue;
284 return false;
285 }
286 return true;
287}
288
290 if (N->getOpcode() != ISD::BUILD_VECTOR)
291 return false;
292
293 for (const SDValue &Op : N->op_values()) {
294 if (Op.isUndef())
295 continue;
297 return false;
298 }
299 return true;
300}
301
302bool ISD::isVectorShrinkable(const SDNode *N, unsigned NewEltSize,
303 bool Signed) {
304 assert(N->getValueType(0).isVector() && "Expected a vector!");
305
306 unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
307 if (EltSize <= NewEltSize)
308 return false;
309
310 if (N->getOpcode() == ISD::ZERO_EXTEND) {
311 return (N->getOperand(0).getValueType().getScalarSizeInBits() <=
312 NewEltSize) &&
313 !Signed;
314 }
315 if (N->getOpcode() == ISD::SIGN_EXTEND) {
316 return (N->getOperand(0).getValueType().getScalarSizeInBits() <=
317 NewEltSize) &&
318 Signed;
319 }
320 if (N->getOpcode() != ISD::BUILD_VECTOR)
321 return false;
322
323 for (const SDValue &Op : N->op_values()) {
324 if (Op.isUndef())
325 continue;
327 return false;
328
329 APInt C = Op->getAsAPIntVal().trunc(EltSize);
330 if (Signed && C.trunc(NewEltSize).sext(EltSize) != C)
331 return false;
332 if (!Signed && C.trunc(NewEltSize).zext(EltSize) != C)
333 return false;
334 }
335
336 return true;
337}
338
340 // Return false if the node has no operands.
341 // This is "logically inconsistent" with the definition of "all" but
342 // is probably the desired behavior.
343 if (N->getNumOperands() == 0)
344 return false;
345 return all_of(N->op_values(), [](SDValue Op) { return Op.isUndef(); });
346}
347
349 return N->getOpcode() == ISD::FREEZE && N->getOperand(0).isUndef();
350}
351
352template <typename ConstNodeType>
354 std::function<bool(ConstNodeType *)> Match,
355 bool AllowUndefs, bool AllowTruncation) {
356 // FIXME: Add support for scalar UNDEF cases?
357 if (auto *C = dyn_cast<ConstNodeType>(Op))
358 return Match(C);
359
360 // FIXME: Add support for vector UNDEF cases?
361 if (ISD::BUILD_VECTOR != Op.getOpcode() &&
362 ISD::SPLAT_VECTOR != Op.getOpcode())
363 return false;
364
365 EVT SVT = Op.getValueType().getScalarType();
366 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
367 if (AllowUndefs && Op.getOperand(i).isUndef()) {
368 if (!Match(nullptr))
369 return false;
370 continue;
371 }
372
373 auto *Cst = dyn_cast<ConstNodeType>(Op.getOperand(i));
374 if (!Cst || (!AllowTruncation && Cst->getValueType(0) != SVT) ||
375 !Match(Cst))
376 return false;
377 }
378 return true;
379}
380// Build used template types.
382 SDValue, std::function<bool(ConstantSDNode *)>, bool, bool);
384 SDValue, std::function<bool(ConstantFPSDNode *)>, bool, bool);
385
387 SDValue LHS, SDValue RHS,
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 EVT SVT = LHS.getValueType().getScalarType();
405 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
406 SDValue LHSOp = LHS.getOperand(i);
407 SDValue RHSOp = RHS.getOperand(i);
408 bool LHSUndef = AllowUndefs && LHSOp.isUndef();
409 bool RHSUndef = AllowUndefs && RHSOp.isUndef();
410 auto *LHSCst = dyn_cast<ConstantSDNode>(LHSOp);
411 auto *RHSCst = dyn_cast<ConstantSDNode>(RHSOp);
412 if ((!LHSCst && !LHSUndef) || (!RHSCst && !RHSUndef))
413 return false;
414 if (!AllowTypeMismatch && (LHSOp.getValueType() != SVT ||
415 LHSOp.getValueType() != RHSOp.getValueType()))
416 return false;
417 if (!Match(LHSCst, RHSCst))
418 return false;
419 }
420 return true;
421}
422
424 switch (MinMaxOpc) {
425 default:
426 llvm_unreachable("unrecognized opcode");
427 case ISD::UMIN:
428 return ISD::UMAX;
429 case ISD::UMAX:
430 return ISD::UMIN;
431 case ISD::SMIN:
432 return ISD::SMAX;
433 case ISD::SMAX:
434 return ISD::SMIN;
435 }
436}
437
439 switch (MinMaxOpc) {
440 default:
441 llvm_unreachable("unrecognized min/max opcode");
442 case ISD::SMIN:
443 return ISD::UMIN;
444 case ISD::SMAX:
445 return ISD::UMAX;
446 case ISD::UMIN:
447 return ISD::SMIN;
448 case ISD::UMAX:
449 return ISD::SMAX;
450 }
451}
452
454 switch (VecReduceOpcode) {
455 default:
456 llvm_unreachable("Expected VECREDUCE opcode");
459 case ISD::VP_REDUCE_FADD:
460 case ISD::VP_REDUCE_SEQ_FADD:
461 return ISD::FADD;
464 case ISD::VP_REDUCE_FMUL:
465 case ISD::VP_REDUCE_SEQ_FMUL:
466 return ISD::FMUL;
468 case ISD::VP_REDUCE_ADD:
469 return ISD::ADD;
471 case ISD::VP_REDUCE_MUL:
472 return ISD::MUL;
474 case ISD::VP_REDUCE_AND:
475 return ISD::AND;
477 case ISD::VP_REDUCE_OR:
478 return ISD::OR;
480 case ISD::VP_REDUCE_XOR:
481 return ISD::XOR;
483 case ISD::VP_REDUCE_SMAX:
484 return ISD::SMAX;
486 case ISD::VP_REDUCE_SMIN:
487 return ISD::SMIN;
489 case ISD::VP_REDUCE_UMAX:
490 return ISD::UMAX;
492 case ISD::VP_REDUCE_UMIN:
493 return ISD::UMIN;
495 case ISD::VP_REDUCE_FMAX:
496 return ISD::FMAXNUM;
498 case ISD::VP_REDUCE_FMIN:
499 return ISD::FMINNUM;
501 case ISD::VP_REDUCE_FMAXIMUM:
502 return ISD::FMAXIMUM;
504 case ISD::VP_REDUCE_FMINIMUM:
505 return ISD::FMINIMUM;
506 }
507}
508
510 switch (MaskedOpc) {
511 case ISD::MASKED_UDIV:
512 return ISD::UDIV;
513 case ISD::MASKED_SDIV:
514 return ISD::SDIV;
515 case ISD::MASKED_UREM:
516 return ISD::UREM;
517 case ISD::MASKED_SREM:
518 return ISD::SREM;
519 default:
520 llvm_unreachable("Expected masked binop opcode");
521 }
522}
523
524bool ISD::isVPOpcode(unsigned Opcode) {
525 switch (Opcode) {
526 default:
527 return false;
528#define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) \
529 case ISD::VPSD: \
530 return true;
531#include "llvm/IR/VPIntrinsics.def"
532 }
533}
534
535bool ISD::isVPBinaryOp(unsigned Opcode) {
536 switch (Opcode) {
537 default:
538 break;
539#define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) case ISD::VPSD:
540#define VP_PROPERTY_BINARYOP return true;
541#define END_REGISTER_VP_SDNODE(VPSD) break;
542#include "llvm/IR/VPIntrinsics.def"
543 }
544 return false;
545}
546
547bool ISD::isVPReduction(unsigned Opcode) {
548 switch (Opcode) {
549 default:
550 return false;
551 case ISD::VP_REDUCE_ADD:
552 case ISD::VP_REDUCE_MUL:
553 case ISD::VP_REDUCE_AND:
554 case ISD::VP_REDUCE_OR:
555 case ISD::VP_REDUCE_XOR:
556 case ISD::VP_REDUCE_SMAX:
557 case ISD::VP_REDUCE_SMIN:
558 case ISD::VP_REDUCE_UMAX:
559 case ISD::VP_REDUCE_UMIN:
560 case ISD::VP_REDUCE_FMAX:
561 case ISD::VP_REDUCE_FMIN:
562 case ISD::VP_REDUCE_FMAXIMUM:
563 case ISD::VP_REDUCE_FMINIMUM:
564 case ISD::VP_REDUCE_FADD:
565 case ISD::VP_REDUCE_FMUL:
566 case ISD::VP_REDUCE_SEQ_FADD:
567 case ISD::VP_REDUCE_SEQ_FMUL:
568 return true;
569 }
570}
571
572/// The operand position of the vector mask.
573std::optional<unsigned> ISD::getVPMaskIdx(unsigned Opcode) {
574 switch (Opcode) {
575 default:
576 return std::nullopt;
577#define BEGIN_REGISTER_VP_SDNODE(VPSD, LEGALPOS, TDNAME, MASKPOS, ...) \
578 case ISD::VPSD: \
579 return MASKPOS;
580#include "llvm/IR/VPIntrinsics.def"
581 }
582}
583
584/// The operand position of the explicit vector length parameter.
585std::optional<unsigned> ISD::getVPExplicitVectorLengthIdx(unsigned Opcode) {
586 switch (Opcode) {
587 default:
588 return std::nullopt;
589#define BEGIN_REGISTER_VP_SDNODE(VPSD, LEGALPOS, TDNAME, MASKPOS, EVLPOS) \
590 case ISD::VPSD: \
591 return EVLPOS;
592#include "llvm/IR/VPIntrinsics.def"
593 }
594}
595
596std::optional<unsigned> ISD::getBaseOpcodeForVP(unsigned VPOpcode,
597 bool hasFPExcept) {
598 // FIXME: Return strict opcodes in case of fp exceptions.
599 switch (VPOpcode) {
600 default:
601 return std::nullopt;
602#define BEGIN_REGISTER_VP_SDNODE(VPOPC, ...) case ISD::VPOPC:
603#define VP_PROPERTY_FUNCTIONAL_SDOPC(SDOPC) return ISD::SDOPC;
604#define END_REGISTER_VP_SDNODE(VPOPC) break;
605#include "llvm/IR/VPIntrinsics.def"
606 }
607 return std::nullopt;
608}
609
610std::optional<unsigned> ISD::getVPForBaseOpcode(unsigned Opcode) {
611 switch (Opcode) {
612 default:
613 return std::nullopt;
614#define BEGIN_REGISTER_VP_SDNODE(VPOPC, ...) break;
615#define VP_PROPERTY_FUNCTIONAL_SDOPC(SDOPC) case ISD::SDOPC:
616#define END_REGISTER_VP_SDNODE(VPOPC) return ISD::VPOPC;
617#include "llvm/IR/VPIntrinsics.def"
618 }
619}
620
622 switch (ExtType) {
623 case ISD::EXTLOAD:
624 return IsFP ? ISD::FP_EXTEND : ISD::ANY_EXTEND;
625 case ISD::SEXTLOAD:
626 return ISD::SIGN_EXTEND;
627 case ISD::ZEXTLOAD:
628 return ISD::ZERO_EXTEND;
629 default:
630 break;
631 }
632
633 llvm_unreachable("Invalid LoadExtType");
634}
635
637 // To perform this operation, we just need to swap the L and G bits of the
638 // operation.
639 unsigned OldL = (Operation >> 2) & 1;
640 unsigned OldG = (Operation >> 1) & 1;
641 return ISD::CondCode((Operation & ~6) | // Keep the N, U, E bits
642 (OldL << 1) | // New G bit
643 (OldG << 2)); // New L bit.
644}
645
647 unsigned Operation = Op;
648 if (isIntegerLike)
649 Operation ^= 7; // Flip L, G, E bits, but not U.
650 else
651 Operation ^= 15; // Flip all of the condition bits.
652
654 Operation &= ~8; // Don't let N and U bits get set.
655
656 return ISD::CondCode(Operation);
657}
658
662
664 bool isIntegerLike) {
665 return getSetCCInverseImpl(Op, isIntegerLike);
666}
667
668/// For an integer comparison, return 1 if the comparison is a signed operation
669/// and 2 if the result is an unsigned comparison. Return zero if the operation
670/// does not depend on the sign of the input (setne and seteq).
671static int isSignedOp(ISD::CondCode Opcode) {
672 switch (Opcode) {
673 default: llvm_unreachable("Illegal integer setcc operation!");
674 case ISD::SETEQ:
675 case ISD::SETNE: return 0;
676 case ISD::SETLT:
677 case ISD::SETLE:
678 case ISD::SETGT:
679 case ISD::SETGE: return 1;
680 case ISD::SETULT:
681 case ISD::SETULE:
682 case ISD::SETUGT:
683 case ISD::SETUGE: return 2;
684 }
685}
686
688 EVT Type) {
689 bool IsInteger = Type.isInteger();
690 if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
691 // Cannot fold a signed integer setcc with an unsigned integer setcc.
692 return ISD::SETCC_INVALID;
693
694 unsigned Op = Op1 | Op2; // Combine all of the condition bits.
695
696 // If the N and U bits get set, then the resultant comparison DOES suddenly
697 // care about orderedness, and it is true when ordered.
698 if (Op > ISD::SETTRUE2)
699 Op &= ~16; // Clear the U bit if the N bit is set.
700
701 // Canonicalize illegal integer setcc's.
702 if (IsInteger && Op == ISD::SETUNE) // e.g. SETUGT | SETULT
703 Op = ISD::SETNE;
704
705 return ISD::CondCode(Op);
706}
707
709 EVT Type) {
710 bool IsInteger = Type.isInteger();
711 if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
712 // Cannot fold a signed setcc with an unsigned setcc.
713 return ISD::SETCC_INVALID;
714
715 // Combine all of the condition bits.
716 ISD::CondCode Result = ISD::CondCode(Op1 & Op2);
717
718 // Canonicalize illegal integer setcc's.
719 if (IsInteger) {
720 switch (Result) {
721 default: break;
722 case ISD::SETUO : Result = ISD::SETFALSE; break; // SETUGT & SETULT
723 case ISD::SETOEQ: // SETEQ & SETU[LG]E
724 case ISD::SETUEQ: Result = ISD::SETEQ ; break; // SETUGE & SETULE
725 case ISD::SETOLT: Result = ISD::SETULT ; break; // SETULT & SETNE
726 case ISD::SETOGT: Result = ISD::SETUGT ; break; // SETUGT & SETNE
727 }
728 }
729
730 return Result;
731}
732
733//===----------------------------------------------------------------------===//
734// SDNode Profile Support
735//===----------------------------------------------------------------------===//
736
737/// AddNodeIDOpcode - Add the node opcode to the NodeID data.
738static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC) {
739 ID.AddInteger(OpC);
740}
741
742/// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them
743/// solely with their pointer.
745 ID.AddPointer(VTList.VTs);
746}
747
748/// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
751 for (const auto &Op : Ops) {
752 ID.AddPointer(Op.getNode());
753 ID.AddInteger(Op.getResNo());
754 }
755}
756
757/// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
760 for (const auto &Op : Ops) {
761 ID.AddPointer(Op.getNode());
762 ID.AddInteger(Op.getResNo());
763 }
764}
765
766static void AddNodeIDNode(FoldingSetNodeID &ID, unsigned OpC,
767 SDVTList VTList, ArrayRef<SDValue> OpList) {
768 AddNodeIDOpcode(ID, OpC);
769 AddNodeIDValueTypes(ID, VTList);
770 AddNodeIDOperands(ID, OpList);
771}
772
773/// If this is an SDNode with special info, add this info to the NodeID data.
774static void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N) {
775 switch (N->getOpcode()) {
778 case ISD::MCSymbol:
779 llvm_unreachable("Should only be used on nodes with operands");
780 default: break; // Normal nodes don't need extra info.
782 case ISD::Constant: {
784 ID.AddPointer(C->getConstantIntValue());
785 ID.AddBoolean(C->isOpaque());
786 break;
787 }
789 case ISD::ConstantFP:
790 ID.AddPointer(cast<ConstantFPSDNode>(N)->getConstantFPValue());
791 break;
797 ID.AddPointer(GA->getGlobal());
798 ID.AddInteger(GA->getOffset());
799 ID.AddInteger(GA->getTargetFlags());
800 break;
801 }
802 case ISD::BasicBlock:
803 ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock());
804 break;
805 case ISD::Register:
806 ID.AddInteger(cast<RegisterSDNode>(N)->getReg().id());
807 break;
809 ID.AddPointer(cast<RegisterMaskSDNode>(N)->getRegMask());
810 break;
811 case ISD::SRCVALUE:
812 ID.AddPointer(cast<SrcValueSDNode>(N)->getValue());
813 break;
814 case ISD::FrameIndex:
816 ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex());
817 break;
819 ID.AddInteger(cast<PseudoProbeSDNode>(N)->getGuid());
820 ID.AddInteger(cast<PseudoProbeSDNode>(N)->getIndex());
821 ID.AddInteger(cast<PseudoProbeSDNode>(N)->getAttributes());
822 break;
823 case ISD::JumpTable:
825 ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex());
826 ID.AddInteger(cast<JumpTableSDNode>(N)->getTargetFlags());
827 break;
831 ID.AddInteger(CP->getAlign().value());
832 ID.AddInteger(CP->getOffset());
835 else
836 ID.AddPointer(CP->getConstVal());
837 ID.AddInteger(CP->getTargetFlags());
838 break;
839 }
840 case ISD::TargetIndex: {
842 ID.AddInteger(TI->getIndex());
843 ID.AddInteger(TI->getOffset());
844 ID.AddInteger(TI->getTargetFlags());
845 break;
846 }
847 case ISD::LOAD: {
848 const LoadSDNode *LD = cast<LoadSDNode>(N);
849 ID.AddInteger(LD->getMemoryVT().getRawBits());
850 ID.AddInteger(LD->getRawSubclassData());
851 ID.AddInteger(LD->getPointerInfo().getAddrSpace());
852 ID.AddInteger(LD->getMemOperand()->getFlags());
853 break;
854 }
855 case ISD::STORE: {
856 const StoreSDNode *ST = cast<StoreSDNode>(N);
857 ID.AddInteger(ST->getMemoryVT().getRawBits());
858 ID.AddInteger(ST->getRawSubclassData());
859 ID.AddInteger(ST->getPointerInfo().getAddrSpace());
860 ID.AddInteger(ST->getMemOperand()->getFlags());
861 break;
862 }
863 case ISD::VP_LOAD: {
864 const VPLoadSDNode *ELD = cast<VPLoadSDNode>(N);
865 ID.AddInteger(ELD->getMemoryVT().getRawBits());
866 ID.AddInteger(ELD->getRawSubclassData());
867 ID.AddInteger(ELD->getPointerInfo().getAddrSpace());
868 ID.AddInteger(ELD->getMemOperand()->getFlags());
869 break;
870 }
871 case ISD::VP_LOAD_FF: {
872 const auto *LD = cast<VPLoadFFSDNode>(N);
873 ID.AddInteger(LD->getMemoryVT().getRawBits());
874 ID.AddInteger(LD->getRawSubclassData());
875 ID.AddInteger(LD->getPointerInfo().getAddrSpace());
876 ID.AddInteger(LD->getMemOperand()->getFlags());
877 break;
878 }
879 case ISD::VP_STORE: {
880 const VPStoreSDNode *EST = cast<VPStoreSDNode>(N);
881 ID.AddInteger(EST->getMemoryVT().getRawBits());
882 ID.AddInteger(EST->getRawSubclassData());
883 ID.AddInteger(EST->getPointerInfo().getAddrSpace());
884 ID.AddInteger(EST->getMemOperand()->getFlags());
885 break;
886 }
887 case ISD::EXPERIMENTAL_VP_STRIDED_LOAD: {
889 ID.AddInteger(SLD->getMemoryVT().getRawBits());
890 ID.AddInteger(SLD->getRawSubclassData());
891 ID.AddInteger(SLD->getPointerInfo().getAddrSpace());
892 break;
893 }
894 case ISD::EXPERIMENTAL_VP_STRIDED_STORE: {
896 ID.AddInteger(SST->getMemoryVT().getRawBits());
897 ID.AddInteger(SST->getRawSubclassData());
898 ID.AddInteger(SST->getPointerInfo().getAddrSpace());
899 break;
900 }
901 case ISD::VP_GATHER: {
903 ID.AddInteger(EG->getMemoryVT().getRawBits());
904 ID.AddInteger(EG->getRawSubclassData());
905 ID.AddInteger(EG->getPointerInfo().getAddrSpace());
906 ID.AddInteger(EG->getMemOperand()->getFlags());
907 break;
908 }
909 case ISD::VP_SCATTER: {
911 ID.AddInteger(ES->getMemoryVT().getRawBits());
912 ID.AddInteger(ES->getRawSubclassData());
913 ID.AddInteger(ES->getPointerInfo().getAddrSpace());
914 ID.AddInteger(ES->getMemOperand()->getFlags());
915 break;
916 }
917 case ISD::MLOAD: {
919 ID.AddInteger(MLD->getMemoryVT().getRawBits());
920 ID.AddInteger(MLD->getRawSubclassData());
921 ID.AddInteger(MLD->getPointerInfo().getAddrSpace());
922 ID.AddInteger(MLD->getMemOperand()->getFlags());
923 break;
924 }
925 case ISD::MSTORE: {
927 ID.AddInteger(MST->getMemoryVT().getRawBits());
928 ID.AddInteger(MST->getRawSubclassData());
929 ID.AddInteger(MST->getPointerInfo().getAddrSpace());
930 ID.AddInteger(MST->getMemOperand()->getFlags());
931 break;
932 }
933 case ISD::MGATHER: {
935 ID.AddInteger(MG->getMemoryVT().getRawBits());
936 ID.AddInteger(MG->getRawSubclassData());
937 ID.AddInteger(MG->getPointerInfo().getAddrSpace());
938 ID.AddInteger(MG->getMemOperand()->getFlags());
939 break;
940 }
941 case ISD::MSCATTER: {
943 ID.AddInteger(MS->getMemoryVT().getRawBits());
944 ID.AddInteger(MS->getRawSubclassData());
945 ID.AddInteger(MS->getPointerInfo().getAddrSpace());
946 ID.AddInteger(MS->getMemOperand()->getFlags());
947 break;
948 }
951 case ISD::ATOMIC_SWAP:
963 case ISD::ATOMIC_LOAD:
964 case ISD::ATOMIC_STORE: {
965 const AtomicSDNode *AT = cast<AtomicSDNode>(N);
966 ID.AddInteger(AT->getMemoryVT().getRawBits());
967 ID.AddInteger(AT->getRawSubclassData());
968 ID.AddInteger(AT->getPointerInfo().getAddrSpace());
969 ID.AddInteger(AT->getMemOperand()->getFlags());
970 break;
971 }
972 case ISD::VECTOR_SHUFFLE: {
973 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(N)->getMask();
974 for (int M : Mask)
975 ID.AddInteger(M);
976 break;
977 }
978 case ISD::ADDRSPACECAST: {
980 ID.AddInteger(ASC->getSrcAddressSpace());
981 ID.AddInteger(ASC->getDestAddressSpace());
982 break;
983 }
985 case ISD::BlockAddress: {
987 ID.AddPointer(BA->getBlockAddress());
988 ID.AddInteger(BA->getOffset());
989 ID.AddInteger(BA->getTargetFlags());
990 break;
991 }
992 case ISD::AssertAlign:
993 ID.AddInteger(cast<AssertAlignSDNode>(N)->getAlign().value());
994 break;
995 case ISD::PREFETCH:
998 // Handled by MemIntrinsicSDNode check after the switch.
999 break;
1000 case ISD::MDNODE_SDNODE:
1001 ID.AddPointer(cast<MDNodeSDNode>(N)->getMD());
1002 break;
1003 } // end switch (N->getOpcode())
1004
1005 // MemIntrinsic nodes could also have subclass data, address spaces, and flags
1006 // to check.
1007 if (auto *MN = dyn_cast<MemIntrinsicSDNode>(N)) {
1008 ID.AddInteger(MN->getRawSubclassData());
1009 ID.AddInteger(MN->getMemoryVT().getRawBits());
1010 for (const MachineMemOperand *MMO : MN->memoperands()) {
1011 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
1012 ID.AddInteger(MMO->getFlags());
1013 }
1014 }
1015}
1016
1017/// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID
1018/// data.
1019static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) {
1020 AddNodeIDOpcode(ID, N->getOpcode());
1021 // Add the return value info.
1022 AddNodeIDValueTypes(ID, N->getVTList());
1023 // Add the operand info.
1024 AddNodeIDOperands(ID, N->ops());
1025
1026 // Handle SDNode leafs with special info.
1027 AddNodeIDCustom(ID, N);
1028}
1029
1030//===----------------------------------------------------------------------===//
1031// SelectionDAG Class
1032//===----------------------------------------------------------------------===//
1033
1034/// doNotCSE - Return true if CSE should not be performed for this node.
1035static bool doNotCSE(SDNode *N) {
1036 if (N->getValueType(0) == MVT::Glue)
1037 return true; // Never CSE anything that produces a glue result.
1038
1039 switch (N->getOpcode()) {
1040 default: break;
1041 case ISD::HANDLENODE:
1042 case ISD::EH_LABEL:
1043 return true; // Never CSE these nodes.
1044 }
1045
1046 // Check that remaining values produced are not flags.
1047 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
1048 if (N->getValueType(i) == MVT::Glue)
1049 return true; // Never CSE anything that produces a glue result.
1050
1051 return false;
1052}
1053
1054/// Construct a DemandedElts mask which demands all elements of \p V.
1055/// If \p V is not a fixed-length vector, then this will return a single bit.
1057 EVT VT = V.getValueType();
1058 // Since the number of lanes in a scalable vector is unknown at compile time,
1059 // we track one bit which is implicitly broadcast to all lanes. This means
1060 // that all lanes in a scalable vector are considered demanded.
1062 : APInt(1, 1);
1063}
1064
1065/// RemoveDeadNodes - This method deletes all unreachable nodes in the
1066/// SelectionDAG.
1068 // Create a dummy node (which is not added to allnodes), that adds a reference
1069 // to the root node, preventing it from being deleted.
1070 HandleSDNode Dummy(getRoot());
1071
1072 SmallVector<SDNode*, 128> DeadNodes;
1073
1074 // Add all obviously-dead nodes to the DeadNodes worklist.
1075 for (SDNode &Node : allnodes())
1076 if (Node.use_empty())
1077 DeadNodes.push_back(&Node);
1078
1079 RemoveDeadNodes(DeadNodes);
1080
1081 // If the root changed (e.g. it was a dead load, update the root).
1082 setRoot(Dummy.getValue());
1083}
1084
1085/// RemoveDeadNodes - This method deletes the unreachable nodes in the
1086/// given list, and any nodes that become unreachable as a result.
1088
1089 // Process the worklist, deleting the nodes and adding their uses to the
1090 // worklist.
1091 while (!DeadNodes.empty()) {
1092 SDNode *N = DeadNodes.pop_back_val();
1093 // Skip to next node if we've already managed to delete the node. This could
1094 // happen if replacing a node causes a node previously added to the node to
1095 // be deleted.
1096 if (N->getOpcode() == ISD::DELETED_NODE)
1097 continue;
1098
1099 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1100 DUL->NodeDeleted(N, nullptr);
1101
1102 // Take the node out of the appropriate CSE map.
1103 RemoveNodeFromCSEMaps(N);
1104
1105 // Next, brutally remove the operand list. This is safe to do, as there are
1106 // no cycles in the graph.
1107 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
1108 SDUse &Use = *I++;
1109 SDNode *Operand = Use.getNode();
1110 Use.set(SDValue());
1111
1112 // Now that we removed this operand, see if there are no uses of it left.
1113 if (Operand->use_empty())
1114 DeadNodes.push_back(Operand);
1115 }
1116
1117 DeallocateNode(N);
1118 }
1119}
1120
1122 SmallVector<SDNode*, 16> DeadNodes(1, N);
1123
1124 // Create a dummy node that adds a reference to the root node, preventing
1125 // it from being deleted. (This matters if the root is an operand of the
1126 // dead node.)
1127 HandleSDNode Dummy(getRoot());
1128
1129 RemoveDeadNodes(DeadNodes);
1130}
1131
1133 // First take this out of the appropriate CSE map.
1134 RemoveNodeFromCSEMaps(N);
1135
1136 // Finally, remove uses due to operands of this node, remove from the
1137 // AllNodes list, and delete the node.
1138 DeleteNodeNotInCSEMaps(N);
1139}
1140
1141void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
1142 assert(N->getIterator() != AllNodes.begin() &&
1143 "Cannot delete the entry node!");
1144 assert(N->use_empty() && "Cannot delete a node that is not dead!");
1145
1146 // Drop all of the operands and decrement used node's use counts.
1147 N->DropOperands();
1148
1149 DeallocateNode(N);
1150}
1151
1152void SDDbgInfo::add(SDDbgValue *V, bool isParameter) {
1153 assert(!(V->isVariadic() && isParameter));
1154 if (isParameter)
1155 ByvalParmDbgValues.push_back(V);
1156 else
1157 DbgValues.push_back(V);
1158 for (const SDNode *Node : V->getSDNodes())
1159 if (Node)
1160 DbgValMap[Node].push_back(V);
1161}
1162
1164 DbgValMapType::iterator I = DbgValMap.find(Node);
1165 if (I == DbgValMap.end())
1166 return;
1167 for (auto &Val: I->second)
1168 Val->setIsInvalidated();
1169 DbgValMap.erase(I);
1170}
1171
1172void SelectionDAG::DeallocateNode(SDNode *N) {
1173 // If we have operands, deallocate them.
1175
1176 NodeAllocator.Deallocate(AllNodes.remove(N));
1177
1178 // Set the opcode to DELETED_NODE to help catch bugs when node
1179 // memory is reallocated.
1180 // FIXME: There are places in SDag that have grown a dependency on the opcode
1181 // value in the released node.
1182 __asan_unpoison_memory_region(&N->NodeType, sizeof(N->NodeType));
1183 N->NodeType = ISD::DELETED_NODE;
1184
1185 // If any of the SDDbgValue nodes refer to this SDNode, invalidate
1186 // them and forget about that node.
1187 DbgInfo->erase(N);
1188
1189 // Invalidate extra info.
1190 SDEI.erase(N);
1191}
1192
1193#ifndef NDEBUG
1194/// VerifySDNode - Check the given SDNode. Aborts if it is invalid.
1195void SelectionDAG::verifyNode(SDNode *N) const {
1196 switch (N->getOpcode()) {
1197 default:
1198 if (N->isTargetOpcode())
1200 break;
1201 case ISD::BUILD_PAIR: {
1202 EVT VT = N->getValueType(0);
1203 assert(N->getNumValues() == 1 && "Too many results!");
1204 assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) &&
1205 "Wrong return type!");
1206 assert(N->getNumOperands() == 2 && "Wrong number of operands!");
1207 assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() &&
1208 "Mismatched operand types!");
1209 assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() &&
1210 "Wrong operand type!");
1211 assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() &&
1212 "Wrong return type size");
1213 break;
1214 }
1215 case ISD::BUILD_VECTOR: {
1216 assert(N->getNumValues() == 1 && "Too many results!");
1217 assert(N->getValueType(0).isVector() && "Wrong return type!");
1218 assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() &&
1219 "Wrong number of operands!");
1220 EVT EltVT = N->getValueType(0).getVectorElementType();
1221 for (const SDUse &Op : N->ops()) {
1222 assert((Op.getValueType() == EltVT ||
1223 (EltVT.isInteger() && Op.getValueType().isInteger() &&
1224 EltVT.bitsLE(Op.getValueType()))) &&
1225 "Wrong operand type!");
1226 assert(Op.getValueType() == N->getOperand(0).getValueType() &&
1227 "Operands must all have the same type");
1228 }
1229 break;
1230 }
1231 case ISD::SADDO:
1232 case ISD::UADDO:
1233 case ISD::SSUBO:
1234 case ISD::USUBO:
1235 assert(N->getNumValues() == 2 && "Wrong number of results!");
1236 assert(N->getVTList().NumVTs == 2 && N->getNumOperands() == 2 &&
1237 "Invalid add/sub overflow op!");
1238 assert(N->getVTList().VTs[0].isInteger() &&
1239 N->getVTList().VTs[1].isInteger() &&
1240 N->getOperand(0).getValueType() == N->getOperand(1).getValueType() &&
1241 N->getOperand(0).getValueType() == N->getVTList().VTs[0] &&
1242 "Binary operator types must match!");
1243 break;
1244 }
1245}
1246#endif // NDEBUG
1247
1248/// Insert a newly allocated node into the DAG.
1249///
1250/// Handles insertion into the all nodes list and CSE map, as well as
1251/// verification and other common operations when a new node is allocated.
1252void SelectionDAG::InsertNode(SDNode *N) {
1253 AllNodes.push_back(N);
1254#ifndef NDEBUG
1255 N->PersistentId = NextPersistentId++;
1256 verifyNode(N);
1257#endif
1258 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1259 DUL->NodeInserted(N);
1260}
1261
1262/// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
1263/// correspond to it. This is useful when we're about to delete or repurpose
1264/// the node. We don't want future request for structurally identical nodes
1265/// to return N anymore.
1266bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
1267 bool Erased = false;
1268 switch (N->getOpcode()) {
1269 case ISD::HANDLENODE: return false; // noop.
1270 case ISD::CONDCODE:
1271 assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
1272 "Cond code doesn't exist!");
1273 Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != nullptr;
1274 CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = nullptr;
1275 break;
1277 Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
1278 break;
1280 ExternalSymbolSDNode *ESN = cast<ExternalSymbolSDNode>(N);
1281 Erased = TargetExternalSymbols.erase(std::pair<std::string, unsigned>(
1282 ESN->getSymbol(), ESN->getTargetFlags()));
1283 break;
1284 }
1285 case ISD::MCSymbol: {
1286 auto *MCSN = cast<MCSymbolSDNode>(N);
1287 Erased = MCSymbols.erase(MCSN->getMCSymbol());
1288 break;
1289 }
1290 case ISD::VALUETYPE: {
1291 EVT VT = cast<VTSDNode>(N)->getVT();
1292 if (VT.isExtended()) {
1293 Erased = ExtendedValueTypeNodes.erase(VT);
1294 } else {
1295 Erased = ValueTypeNodes[VT.getSimpleVT().SimpleTy] != nullptr;
1296 ValueTypeNodes[VT.getSimpleVT().SimpleTy] = nullptr;
1297 }
1298 break;
1299 }
1300 default:
1301 // Remove it from the CSE Map.
1302 assert(N->getOpcode() != ISD::DELETED_NODE && "DELETED_NODE in CSEMap!");
1303 assert(N->getOpcode() != ISD::EntryToken && "EntryToken in CSEMap!");
1304 Erased = CSEMap.RemoveNode(N);
1305 break;
1306 }
1307#ifndef NDEBUG
1308 // Verify that the node was actually in one of the CSE maps, unless it has a
1309 // glue result (which cannot be CSE'd) or is one of the special cases that are
1310 // not subject to CSE.
1311 if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Glue &&
1312 !N->isMachineOpcode() && !doNotCSE(N)) {
1313 N->dump(this);
1314 dbgs() << "\n";
1315 llvm_unreachable("Node is not in map!");
1316 }
1317#endif
1318 return Erased;
1319}
1320
1321/// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE
1322/// maps and modified in place. Add it back to the CSE maps, unless an identical
1323/// node already exists, in which case transfer all its users to the existing
1324/// node. This transfer can potentially trigger recursive merging.
1325void
1326SelectionDAG::AddModifiedNodeToCSEMaps(SDNode *N) {
1327 // For node types that aren't CSE'd, just act as if no identical node
1328 // already exists.
1329 if (!doNotCSE(N)) {
1330 SDNode *Existing = CSEMap.GetOrInsertNode(N);
1331 if (Existing != N) {
1332 // If there was already an existing matching node, use ReplaceAllUsesWith
1333 // to replace the dead one with the existing one. This can cause
1334 // recursive merging of other unrelated nodes down the line.
1335 Existing->intersectFlagsWith(N->getFlags());
1336 if (auto *MemNode = dyn_cast<MemSDNode>(Existing)) {
1338 cast<MemSDNode>(N)->memoperands();
1339 // Range and cache hint metadata are not part of the DAG CSE key because
1340 // we prefer to CSE even when metadata does not match. Merge potentially
1341 // differing metadata conservatively.
1342 MemNode->refineMMOMetadata(NewMMOs);
1343 }
1344 ReplaceAllUsesWith(N, Existing);
1345
1346 // N is now dead. Inform the listeners and delete it.
1347 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1348 DUL->NodeDeleted(N, Existing);
1349 DeleteNodeNotInCSEMaps(N);
1350 return;
1351 }
1352 }
1353
1354 // If the node doesn't already exist, we updated it. Inform listeners.
1355 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1356 DUL->NodeUpdated(N);
1357}
1358
1359/// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1360/// were replaced with those specified. If this node is never memoized,
1361/// return null, otherwise return a pointer to the slot it would take. If a
1362/// node already exists with these operands, the slot will be non-null.
1363SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op,
1364 void *&InsertPos) {
1365 if (doNotCSE(N))
1366 return nullptr;
1367
1368 SDValue Ops[] = { Op };
1369 FoldingSetNodeID ID;
1370 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1371 AddNodeIDCustom(ID, N);
1372 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1373 if (Node)
1374 Node->intersectFlagsWith(N->getFlags());
1375 return Node;
1376}
1377
1378/// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1379/// were replaced with those specified. If this node is never memoized,
1380/// return null, otherwise return a pointer to the slot it would take. If a
1381/// node already exists with these operands, the slot will be non-null.
1382SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
1383 SDValue Op1, SDValue Op2,
1384 void *&InsertPos) {
1385 if (doNotCSE(N))
1386 return nullptr;
1387
1388 SDValue Ops[] = { Op1, Op2 };
1389 FoldingSetNodeID ID;
1390 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1391 AddNodeIDCustom(ID, N);
1392 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1393 if (Node)
1394 Node->intersectFlagsWith(N->getFlags());
1395 return Node;
1396}
1397
1398/// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1399/// were replaced with those specified. If this node is never memoized,
1400/// return null, otherwise return a pointer to the slot it would take. If a
1401/// node already exists with these operands, the slot will be non-null.
1402SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, ArrayRef<SDValue> Ops,
1403 void *&InsertPos) {
1404 if (doNotCSE(N))
1405 return nullptr;
1406
1407 FoldingSetNodeID ID;
1408 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1409 AddNodeIDCustom(ID, N);
1410 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1411 if (Node)
1412 Node->intersectFlagsWith(N->getFlags());
1413 return Node;
1414}
1415
1417 Type *Ty = VT == MVT::iPTR ? PointerType::get(*getContext(), 0)
1418 : VT.getTypeForEVT(*getContext());
1419
1420 return getDataLayout().getABITypeAlign(Ty);
1421}
1422
1423// EntryNode could meaningfully have debug info if we can find it...
1425 : TM(tm), OptLevel(OL), EntryNode(ISD::EntryToken, 0, DebugLoc(),
1426 getVTList(MVT::Other, MVT::Glue)),
1427 Root(getEntryNode()) {
1428 InsertNode(&EntryNode);
1429 DbgInfo = new SDDbgInfo();
1430}
1431
1433 OptimizationRemarkEmitter &NewORE, Pass *PassPtr,
1434 const TargetLibraryInfo *LibraryInfo,
1435 const LibcallLoweringInfo *LibcallsInfo,
1436 UniformityInfo *NewUA, ProfileSummaryInfo *PSIin,
1438 FunctionVarLocs const *VarLocs) {
1439 MF = &NewMF;
1440 SDAGISelPass = PassPtr;
1441 ORE = &NewORE;
1444 LibInfo = LibraryInfo;
1445 Libcalls = LibcallsInfo;
1446 Context = &MF->getFunction().getContext();
1447 UA = NewUA;
1448 PSI = PSIin;
1449 BFI = BFIin;
1450 MMI = &MMIin;
1451 FnVarLocs = VarLocs;
1452}
1453
1455 assert(!UpdateListeners && "Dangling registered DAGUpdateListeners");
1456 allnodes_clear();
1457 OperandRecycler.clear(OperandAllocator);
1458 delete DbgInfo;
1459}
1460
1462 return llvm::shouldOptimizeForSize(FLI->MBB->getBasicBlock(), PSI, BFI);
1463}
1464
1465void SelectionDAG::allnodes_clear() {
1466 assert(&*AllNodes.begin() == &EntryNode);
1467 AllNodes.remove(AllNodes.begin());
1468 while (!AllNodes.empty())
1469 DeallocateNode(&AllNodes.front());
1470#ifndef NDEBUG
1471 NextPersistentId = 0;
1472#endif
1473}
1474
1475SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
1476 void *&InsertPos) {
1477 SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
1478 if (N) {
1479 switch (N->getOpcode()) {
1480 default: break;
1481 case ISD::Constant:
1482 case ISD::ConstantFP:
1483 llvm_unreachable("Querying for Constant and ConstantFP nodes requires "
1484 "debug location. Use another overload.");
1485 }
1486 }
1487 return N;
1488}
1489
1490SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
1491 const SDLoc &DL, void *&InsertPos) {
1492 SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
1493 if (N) {
1494 switch (N->getOpcode()) {
1495 case ISD::Constant:
1496 case ISD::ConstantFP:
1497 // Erase debug location from the node if the node is used at several
1498 // different places. Do not propagate one location to all uses as it
1499 // will cause a worse single stepping debugging experience.
1500 if (N->getDebugLoc() != DL.getDebugLoc())
1501 N->setDebugLoc(DebugLoc());
1502 break;
1503 default:
1504 // When the node's point of use is located earlier in the instruction
1505 // sequence than its prior point of use, update its debug info to the
1506 // earlier location.
1507 if (DL.getIROrder() && DL.getIROrder() < N->getIROrder())
1508 N->setDebugLoc(DL.getDebugLoc());
1509 break;
1510 }
1511 }
1512 return N;
1513}
1514
1516 allnodes_clear();
1517 OperandRecycler.clear(OperandAllocator);
1518 OperandAllocator.Reset();
1519 CSEMap.clear();
1520
1521 ExtendedValueTypeNodes.clear();
1522 ExternalSymbols.clear();
1523 TargetExternalSymbols.clear();
1524 MCSymbols.clear();
1525 SDEI.clear();
1526 llvm::fill(CondCodeNodes, nullptr);
1527 llvm::fill(ValueTypeNodes, nullptr);
1528
1529 EntryNode.UseList = nullptr;
1530 InsertNode(&EntryNode);
1531 Root = getEntryNode();
1532 DbgInfo->clear();
1533}
1534
1536 return VT.bitsGT(Op.getValueType())
1537 ? getNode(ISD::FP_EXTEND, DL, VT, Op)
1538 : getNode(ISD::FP_ROUND, DL, VT, Op,
1539 getIntPtrConstant(0, DL, /*isTarget=*/true));
1540}
1541
1542std::pair<SDValue, SDValue>
1544 const SDLoc &DL, EVT VT) {
1545 assert(!VT.bitsEq(Op.getValueType()) &&
1546 "Strict no-op FP extend/round not allowed.");
1547 SDValue Res =
1548 VT.bitsGT(Op.getValueType())
1549 ? getNode(ISD::STRICT_FP_EXTEND, DL, {VT, MVT::Other}, {Chain, Op})
1550 : getNode(ISD::STRICT_FP_ROUND, DL, {VT, MVT::Other},
1551 {Chain, Op, getIntPtrConstant(0, DL, /*isTarget=*/true)});
1552
1553 return std::pair<SDValue, SDValue>(Res, SDValue(Res.getNode(), 1));
1554}
1555
1557 return VT.bitsGT(Op.getValueType()) ?
1558 getNode(ISD::ANY_EXTEND, DL, VT, Op) :
1559 getNode(ISD::TRUNCATE, DL, VT, Op);
1560}
1561
1563 return VT.bitsGT(Op.getValueType()) ?
1564 getNode(ISD::SIGN_EXTEND, DL, VT, Op) :
1565 getNode(ISD::TRUNCATE, DL, VT, Op);
1566}
1567
1569 return VT.bitsGT(Op.getValueType()) ?
1570 getNode(ISD::ZERO_EXTEND, DL, VT, Op) :
1571 getNode(ISD::TRUNCATE, DL, VT, Op);
1572}
1573
1575 EVT VT) {
1576 assert(!VT.isVector());
1577 auto Type = Op.getValueType();
1578 SDValue DestOp;
1579 if (Type == VT)
1580 return Op;
1581 auto Size = Op.getValueSizeInBits();
1582 DestOp = getBitcast(EVT::getIntegerVT(*Context, Size), Op);
1583 if (DestOp.getValueType() == VT)
1584 return DestOp;
1585
1586 return getAnyExtOrTrunc(DestOp, DL, VT);
1587}
1588
1590 EVT VT) {
1591 assert(!VT.isVector());
1592 auto Type = Op.getValueType();
1593 SDValue DestOp;
1594 if (Type == VT)
1595 return Op;
1596 auto Size = Op.getValueSizeInBits();
1597 DestOp = getBitcast(MVT::getIntegerVT(Size), Op);
1598 if (DestOp.getValueType() == VT)
1599 return DestOp;
1600
1601 return getSExtOrTrunc(DestOp, DL, VT);
1602}
1603
1605 EVT VT) {
1606 assert(!VT.isVector());
1607 auto Type = Op.getValueType();
1608 SDValue DestOp;
1609 if (Type == VT)
1610 return Op;
1611 auto Size = Op.getValueSizeInBits();
1612 DestOp = getBitcast(MVT::getIntegerVT(Size), Op);
1613 if (DestOp.getValueType() == VT)
1614 return DestOp;
1615
1616 return getZExtOrTrunc(DestOp, DL, VT);
1617}
1618
1620 EVT OpVT) {
1621 if (VT.bitsLE(Op.getValueType()))
1622 return getNode(ISD::TRUNCATE, SL, VT, Op);
1623
1624 TargetLowering::BooleanContent BType = TLI->getBooleanContents(OpVT);
1625 return getNode(TLI->getExtendForContent(BType), SL, VT, Op);
1626}
1627
1629 EVT OpVT = Op.getValueType();
1630 assert(VT.isInteger() && OpVT.isInteger() &&
1631 "Cannot getZeroExtendInReg FP types");
1632 assert(VT.isVector() == OpVT.isVector() &&
1633 "getZeroExtendInReg type should be vector iff the operand "
1634 "type is vector!");
1635 assert((!VT.isVector() ||
1637 "Vector element counts must match in getZeroExtendInReg");
1638 assert(VT.getScalarType().bitsLE(OpVT.getScalarType()) && "Not extending!");
1639 if (OpVT == VT)
1640 return Op;
1641 // TODO: Use computeKnownBits instead of AssertZext.
1642 if (Op.getOpcode() == ISD::AssertZext && cast<VTSDNode>(Op.getOperand(1))
1643 ->getVT()
1644 .getScalarType()
1645 .bitsLE(VT.getScalarType()))
1646 return Op;
1648 VT.getScalarSizeInBits());
1649 return getNode(ISD::AND, DL, OpVT, Op, getConstant(Imm, DL, OpVT));
1650}
1651
1653 SDValue EVL, const SDLoc &DL,
1654 EVT VT) {
1655 EVT OpVT = Op.getValueType();
1656 assert(VT.isInteger() && OpVT.isInteger() &&
1657 "Cannot getVPZeroExtendInReg FP types");
1658 assert(VT.isVector() && OpVT.isVector() &&
1659 "getVPZeroExtendInReg type and operand type should be vector!");
1661 "Vector element counts must match in getZeroExtendInReg");
1662 assert(VT.getScalarType().bitsLE(OpVT.getScalarType()) && "Not extending!");
1663 if (OpVT == VT)
1664 return Op;
1666 VT.getScalarSizeInBits());
1667 return getNode(ISD::VP_AND, DL, OpVT, Op, getConstant(Imm, DL, OpVT), Mask,
1668 EVL);
1669}
1670
1672 // Only unsigned pointer semantics are supported right now. In the future this
1673 // might delegate to TLI to check pointer signedness.
1674 return getZExtOrTrunc(Op, DL, VT);
1675}
1676
1678 // Only unsigned pointer semantics are supported right now. In the future this
1679 // might delegate to TLI to check pointer signedness.
1680 return getZeroExtendInReg(Op, DL, VT);
1681}
1682
1684 return getNode(ISD::SUB, DL, VT, getConstant(0, DL, VT), Val);
1685}
1686
1687/// getNOT - Create a bitwise NOT operation as (XOR Val, -1).
1689 return getNode(ISD::XOR, DL, VT, Val, getAllOnesConstant(DL, VT));
1690}
1691
1693 SDValue TrueValue = getBoolConstant(true, DL, VT, VT);
1694 return getNode(ISD::XOR, DL, VT, Val, TrueValue);
1695}
1696
1698 SDValue Mask, SDValue EVL, EVT VT) {
1699 SDValue TrueValue = getBoolConstant(true, DL, VT, VT);
1700 return getNode(ISD::VP_XOR, DL, VT, Val, TrueValue, Mask, EVL);
1701}
1702
1704 SDValue Mask, SDValue EVL) {
1705 return getVPZExtOrTrunc(DL, VT, Op, Mask, EVL);
1706}
1707
1709 SDValue Mask, SDValue EVL) {
1710 if (VT.bitsGT(Op.getValueType()))
1711 return getNode(ISD::VP_ZERO_EXTEND, DL, VT, Op, Mask, EVL);
1712 if (VT.bitsLT(Op.getValueType()))
1713 return getNode(ISD::VP_TRUNCATE, DL, VT, Op, Mask, EVL);
1714 return Op;
1715}
1716
1718 EVT OpVT) {
1719 if (!V)
1720 return getConstant(0, DL, VT);
1721
1722 switch (TLI->getBooleanContents(OpVT)) {
1725 return getConstant(1, DL, VT);
1727 return getAllOnesConstant(DL, VT);
1728 }
1729 llvm_unreachable("Unexpected boolean content enum!");
1730}
1731
1733 bool isT, bool isO) {
1734 return getConstant(APInt(VT.getScalarSizeInBits(), Val, /*isSigned=*/false),
1735 DL, VT, isT, isO);
1736}
1737
1739 bool isT, bool isO) {
1740 return getConstant(*ConstantInt::get(*Context, Val), DL, VT, isT, isO);
1741}
1742
1744 EVT VT, bool isT, bool isO) {
1745 assert(VT.isInteger() && "Cannot create FP integer constant!");
1746
1747 EVT EltVT = VT.getScalarType();
1748 const ConstantInt *Elt = &Val;
1749
1750 // Vector splats are explicit within the DAG, with ConstantSDNode holding the
1751 // to-be-splatted scalar ConstantInt.
1752 if (isa<VectorType>(Elt->getType()))
1753 Elt = ConstantInt::get(*getContext(), Elt->getValue());
1754
1755 // In some cases the vector type is legal but the element type is illegal and
1756 // needs to be promoted, for example v8i8 on ARM. In this case, promote the
1757 // inserted value (the type does not need to match the vector element type).
1758 // Any extra bits introduced will be truncated away.
1759 if (VT.isVector() && TLI->getTypeAction(*getContext(), EltVT) ==
1761 EltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1762 APInt NewVal;
1763 if (TLI->isSExtCheaperThanZExt(VT.getScalarType(), EltVT))
1764 NewVal = Elt->getValue().sextOrTrunc(EltVT.getSizeInBits());
1765 else
1766 NewVal = Elt->getValue().zextOrTrunc(EltVT.getSizeInBits());
1767 Elt = ConstantInt::get(*getContext(), NewVal);
1768 }
1769 // In other cases the element type is illegal and needs to be expanded, for
1770 // example v2i64 on MIPS32. In this case, find the nearest legal type, split
1771 // the value into n parts and use a vector type with n-times the elements.
1772 // Then bitcast to the type requested.
1773 // Legalizing constants too early makes the DAGCombiner's job harder so we
1774 // only legalize if the DAG tells us we must produce legal types.
1775 else if (NewNodesMustHaveLegalTypes && VT.isVector() &&
1776 TLI->getTypeAction(*getContext(), EltVT) ==
1778 const APInt &NewVal = Elt->getValue();
1779 EVT ViaEltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1780 unsigned ViaEltSizeInBits = ViaEltVT.getSizeInBits();
1781
1782 // For scalable vectors, try to use a SPLAT_VECTOR_PARTS node.
1783 if (VT.isScalableVector() ||
1784 TLI->isOperationLegal(ISD::SPLAT_VECTOR, VT)) {
1785 assert(EltVT.getSizeInBits() % ViaEltSizeInBits == 0 &&
1786 "Can only handle an even split!");
1787 unsigned Parts = EltVT.getSizeInBits() / ViaEltSizeInBits;
1788
1789 SmallVector<SDValue, 2> ScalarParts;
1790 for (unsigned i = 0; i != Parts; ++i)
1791 ScalarParts.push_back(getConstant(
1792 NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL,
1793 ViaEltVT, isT, isO));
1794
1795 return getNode(ISD::SPLAT_VECTOR_PARTS, DL, VT, ScalarParts);
1796 }
1797
1798 unsigned ViaVecNumElts = VT.getSizeInBits() / ViaEltSizeInBits;
1799 EVT ViaVecVT = EVT::getVectorVT(*getContext(), ViaEltVT, ViaVecNumElts);
1800
1801 // Check the temporary vector is the correct size. If this fails then
1802 // getTypeToTransformTo() probably returned a type whose size (in bits)
1803 // isn't a power-of-2 factor of the requested type size.
1804 assert(ViaVecVT.getSizeInBits() == VT.getSizeInBits());
1805
1806 SmallVector<SDValue, 2> EltParts;
1807 for (unsigned i = 0; i < ViaVecNumElts / VT.getVectorNumElements(); ++i)
1808 EltParts.push_back(getConstant(
1809 NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL,
1810 ViaEltVT, isT, isO));
1811
1812 // EltParts is currently in little endian order. If we actually want
1813 // big-endian order then reverse it now.
1814 if (getDataLayout().isBigEndian())
1815 std::reverse(EltParts.begin(), EltParts.end());
1816
1817 // The elements must be reversed when the element order is different
1818 // to the endianness of the elements (because the BITCAST is itself a
1819 // vector shuffle in this situation). However, we do not need any code to
1820 // perform this reversal because getConstant() is producing a vector
1821 // splat.
1822 // This situation occurs in MIPS MSA.
1823
1825 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
1826 llvm::append_range(Ops, EltParts);
1827
1828 SDValue V =
1829 getNode(ISD::BITCAST, DL, VT, getBuildVector(ViaVecVT, DL, Ops));
1830 return V;
1831 }
1832
1833 assert(Elt->getBitWidth() == EltVT.getSizeInBits() &&
1834 "APInt size does not match type size!");
1835 unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
1836 SDVTList VTs = getVTList(EltVT);
1838 AddNodeIDNode(ID, Opc, VTs, {});
1839 ID.AddPointer(Elt);
1840 ID.AddBoolean(isO);
1841 void *IP = nullptr;
1842 SDNode *N = nullptr;
1843 if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1844 if (!VT.isVector())
1845 return SDValue(N, 0);
1846
1847 if (!N) {
1848 N = newSDNode<ConstantSDNode>(isT, isO, Elt, VTs);
1849 if (!isT)
1850 N->setDebugLoc(DL.getDebugLoc());
1851 CSEMap.InsertNode(N, IP);
1852 InsertNode(N);
1853 NewSDValueDbgMsg(SDValue(N, 0), "Creating constant: ", this);
1854 }
1855
1856 SDValue Result(N, 0);
1857 if (VT.isVector())
1858 Result = getSplat(VT, DL, Result);
1859 return Result;
1860}
1861
1863 bool isT, bool isO) {
1864 unsigned Size = VT.getScalarSizeInBits();
1865 return getConstant(APInt(Size, Val, /*isSigned=*/true), DL, VT, isT, isO);
1866}
1867
1869 bool IsOpaque) {
1871 IsTarget, IsOpaque);
1872}
1873
1875 bool isTarget) {
1876 return getConstant(Val, DL, TLI->getPointerTy(getDataLayout()), isTarget);
1877}
1878
1880 const SDLoc &DL) {
1881 assert(VT.isInteger() && "Shift amount is not an integer type!");
1882 EVT ShiftVT = TLI->getShiftAmountTy(VT, getDataLayout());
1883 return getConstant(Val, DL, ShiftVT);
1884}
1885
1887 const SDLoc &DL) {
1888 assert(Val.ult(VT.getScalarSizeInBits()) && "Out of range shift");
1889 return getShiftAmountConstant(Val.getZExtValue(), VT, DL);
1890}
1891
1893 bool isTarget) {
1894 return getConstant(Val, DL, TLI->getVectorIdxTy(getDataLayout()), isTarget);
1895}
1896
1898 bool isTarget) {
1899 return getConstantFP(*ConstantFP::get(*getContext(), V), DL, VT, isTarget);
1900}
1901
1903 EVT VT, bool isTarget) {
1904 assert(VT.isFloatingPoint() && "Cannot create integer FP constant!");
1905
1906 EVT EltVT = VT.getScalarType();
1907 const ConstantFP *Elt = &V;
1908
1909 // Vector splats are explicit within the DAG, with ConstantFPSDNode holding
1910 // the to-be-splatted scalar ConstantFP.
1911 if (isa<VectorType>(Elt->getType()))
1912 Elt = ConstantFP::get(*getContext(), Elt->getValue());
1913
1914 // Do the map lookup using the actual bit pattern for the floating point
1915 // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
1916 // we don't have issues with SNANs.
1917 unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
1918 SDVTList VTs = getVTList(EltVT);
1920 AddNodeIDNode(ID, Opc, VTs, {});
1921 ID.AddPointer(Elt);
1922 void *IP = nullptr;
1923 SDNode *N = nullptr;
1924 if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1925 if (!VT.isVector())
1926 return SDValue(N, 0);
1927
1928 if (!N) {
1929 N = newSDNode<ConstantFPSDNode>(isTarget, Elt, VTs);
1930 CSEMap.InsertNode(N, IP);
1931 InsertNode(N);
1932 }
1933
1934 SDValue Result(N, 0);
1935 if (VT.isVector())
1936 Result = getSplat(VT, DL, Result);
1937 NewSDValueDbgMsg(Result, "Creating fp constant: ", this);
1938 return Result;
1939}
1940
1942 bool isTarget) {
1943 EVT EltVT = VT.getScalarType();
1944 if (EltVT == MVT::f32)
1945 return getConstantFP(APFloat((float)Val), DL, VT, isTarget);
1946 if (EltVT == MVT::f64)
1947 return getConstantFP(APFloat(Val), DL, VT, isTarget);
1948 if (EltVT == MVT::f80 || EltVT == MVT::f128 || EltVT == MVT::ppcf128 ||
1949 EltVT == MVT::f16 || EltVT == MVT::bf16) {
1950 bool Ignored;
1951 APFloat APF = APFloat(Val);
1953 &Ignored);
1954 return getConstantFP(APF, DL, VT, isTarget);
1955 }
1956 llvm_unreachable("Unsupported type in getConstantFP");
1957}
1958
1960 EVT VT, int64_t Offset, bool isTargetGA,
1961 unsigned TargetFlags) {
1962 assert((TargetFlags == 0 || isTargetGA) &&
1963 "Cannot set target flags on target-independent globals");
1964
1965 // Truncate (with sign-extension) the offset value to the pointer size.
1967 if (BitWidth < 64)
1969
1970 unsigned Opc;
1971 if (GV->isThreadLocal())
1973 else
1975
1976 SDVTList VTs = getVTList(VT);
1978 AddNodeIDNode(ID, Opc, VTs, {});
1979 ID.AddPointer(GV);
1980 ID.AddInteger(Offset);
1981 ID.AddInteger(TargetFlags);
1982 void *IP = nullptr;
1983 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
1984 return SDValue(E, 0);
1985
1986 auto *N = newSDNode<GlobalAddressSDNode>(
1987 Opc, DL.getIROrder(), DL.getDebugLoc(), GV, VTs, Offset, TargetFlags);
1988 CSEMap.InsertNode(N, IP);
1989 InsertNode(N);
1990 return SDValue(N, 0);
1991}
1992
1994 SDVTList VTs = getVTList(MVT::Untyped);
1997 ID.AddPointer(GV);
1998 void *IP = nullptr;
1999 if (SDNode *E = FindNodeOrInsertPos(ID, SDLoc(), IP))
2000 return SDValue(E, 0);
2001
2002 auto *N = newSDNode<DeactivationSymbolSDNode>(GV, VTs);
2003 CSEMap.InsertNode(N, IP);
2004 InsertNode(N);
2005 return SDValue(N, 0);
2006}
2007
2008SDValue SelectionDAG::getFrameIndex(int FI, EVT VT, bool isTarget) {
2009 unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
2010 SDVTList VTs = getVTList(VT);
2012 AddNodeIDNode(ID, Opc, VTs, {});
2013 ID.AddInteger(FI);
2014 void *IP = nullptr;
2015 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2016 return SDValue(E, 0);
2017
2018 auto *N = newSDNode<FrameIndexSDNode>(FI, VTs, isTarget);
2019 CSEMap.InsertNode(N, IP);
2020 InsertNode(N);
2021 return SDValue(N, 0);
2022}
2023
2024SDValue SelectionDAG::getJumpTable(int JTI, EVT VT, bool isTarget,
2025 unsigned TargetFlags) {
2026 assert((TargetFlags == 0 || isTarget) &&
2027 "Cannot set target flags on target-independent jump tables");
2028 unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
2029 SDVTList VTs = getVTList(VT);
2031 AddNodeIDNode(ID, Opc, VTs, {});
2032 ID.AddInteger(JTI);
2033 ID.AddInteger(TargetFlags);
2034 void *IP = nullptr;
2035 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2036 return SDValue(E, 0);
2037
2038 auto *N = newSDNode<JumpTableSDNode>(JTI, VTs, isTarget, TargetFlags);
2039 CSEMap.InsertNode(N, IP);
2040 InsertNode(N);
2041 return SDValue(N, 0);
2042}
2043
2045 const SDLoc &DL) {
2047 return getNode(ISD::JUMP_TABLE_DEBUG_INFO, DL, MVT::Other, Chain,
2048 getTargetConstant(static_cast<uint64_t>(JTI), DL, PTy, true));
2049}
2050
2052 MaybeAlign Alignment, int Offset,
2053 bool isTarget, unsigned TargetFlags) {
2054 assert((TargetFlags == 0 || isTarget) &&
2055 "Cannot set target flags on target-independent globals");
2056 if (!Alignment)
2057 Alignment = shouldOptForSize()
2058 ? getDataLayout().getABITypeAlign(C->getType())
2059 : getDataLayout().getPrefTypeAlign(C->getType());
2060 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
2061 SDVTList VTs = getVTList(VT);
2063 AddNodeIDNode(ID, Opc, VTs, {});
2064 ID.AddInteger(Alignment->value());
2065 ID.AddInteger(Offset);
2066 ID.AddPointer(C);
2067 ID.AddInteger(TargetFlags);
2068 void *IP = nullptr;
2069 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2070 return SDValue(E, 0);
2071
2072 auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VTs, Offset, *Alignment,
2073 TargetFlags);
2074 CSEMap.InsertNode(N, IP);
2075 InsertNode(N);
2076 SDValue V = SDValue(N, 0);
2077 NewSDValueDbgMsg(V, "Creating new constant pool: ", this);
2078 return V;
2079}
2080
2082 MaybeAlign Alignment, int Offset,
2083 bool isTarget, unsigned TargetFlags) {
2084 assert((TargetFlags == 0 || isTarget) &&
2085 "Cannot set target flags on target-independent globals");
2086 if (!Alignment)
2087 Alignment = getDataLayout().getPrefTypeAlign(C->getType());
2088 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
2089 SDVTList VTs = getVTList(VT);
2091 AddNodeIDNode(ID, Opc, VTs, {});
2092 ID.AddInteger(Alignment->value());
2093 ID.AddInteger(Offset);
2094 C->addSelectionDAGCSEId(ID);
2095 ID.AddInteger(TargetFlags);
2096 void *IP = nullptr;
2097 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2098 return SDValue(E, 0);
2099
2100 auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VTs, Offset, *Alignment,
2101 TargetFlags);
2102 CSEMap.InsertNode(N, IP);
2103 InsertNode(N);
2104 return SDValue(N, 0);
2105}
2106
2109 AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), {});
2110 ID.AddPointer(MBB);
2111 void *IP = nullptr;
2112 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2113 return SDValue(E, 0);
2114
2115 auto *N = newSDNode<BasicBlockSDNode>(MBB);
2116 CSEMap.InsertNode(N, IP);
2117 InsertNode(N);
2118 return SDValue(N, 0);
2119}
2120
2122 if (VT.isSimple() && (unsigned)VT.getSimpleVT().SimpleTy >=
2123 ValueTypeNodes.size())
2124 ValueTypeNodes.resize(VT.getSimpleVT().SimpleTy+1);
2125
2126 SDNode *&N = VT.isExtended() ?
2127 ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT().SimpleTy];
2128
2129 if (N) return SDValue(N, 0);
2130 N = newSDNode<VTSDNode>(VT);
2131 InsertNode(N);
2132 return SDValue(N, 0);
2133}
2134
2136 SDNode *&N = ExternalSymbols[Sym];
2137 if (N) return SDValue(N, 0);
2138 N = newSDNode<ExternalSymbolSDNode>(false, Sym, 0, getVTList(VT));
2139 InsertNode(N);
2140 return SDValue(N, 0);
2141}
2142
2143SDValue SelectionDAG::getExternalSymbol(RTLIB::LibcallImpl Libcall, EVT VT) {
2145 return getExternalSymbol(SymName.data(), VT);
2146}
2147
2149 SDNode *&N = MCSymbols[Sym];
2150 if (N)
2151 return SDValue(N, 0);
2152 N = newSDNode<MCSymbolSDNode>(Sym, getVTList(VT));
2153 InsertNode(N);
2154 return SDValue(N, 0);
2155}
2156
2158 unsigned TargetFlags) {
2159 SDNode *&N =
2160 TargetExternalSymbols[std::pair<std::string, unsigned>(Sym, TargetFlags)];
2161 if (N) return SDValue(N, 0);
2162 N = newSDNode<ExternalSymbolSDNode>(true, Sym, TargetFlags, getVTList(VT));
2163 InsertNode(N);
2164 return SDValue(N, 0);
2165}
2166
2168 EVT VT, unsigned TargetFlags) {
2170 return getTargetExternalSymbol(SymName.data(), VT, TargetFlags);
2171}
2172
2174 if ((unsigned)Cond >= CondCodeNodes.size())
2175 CondCodeNodes.resize(Cond+1);
2176
2177 if (!CondCodeNodes[Cond]) {
2178 auto *N = newSDNode<CondCodeSDNode>(Cond);
2179 CondCodeNodes[Cond] = N;
2180 InsertNode(N);
2181 }
2182
2183 return SDValue(CondCodeNodes[Cond], 0);
2184}
2185
2187 assert(MulImm.getBitWidth() == VT.getSizeInBits() &&
2188 "APInt size does not match type size!");
2189
2190 if (MulImm == 0)
2191 return getConstant(0, DL, VT);
2192
2193 const MachineFunction &MF = getMachineFunction();
2194 const Function &F = MF.getFunction();
2195 ConstantRange CR = getVScaleRange(&F, 64);
2196 if (const APInt *C = CR.getSingleElement())
2197 return getConstant(MulImm * C->getZExtValue(), DL, VT);
2198
2199 return getNode(ISD::VSCALE, DL, VT, getConstant(MulImm, DL, VT));
2200}
2201
2202/// \returns a value of type \p VT that represents the runtime value of \p
2203/// Quantity, i.e. scaled by vscale if it's scalable, or a fixed constant
2204/// otherwise. Quantity should be a FixedOrScalableQuantity, i.e. ElementCount
2205/// or TypeSize.
2206template <typename Ty>
2208 EVT VT, Ty Quantity) {
2209 if (Quantity.isScalable())
2210 return DAG.getVScale(
2211 DL, VT, APInt(VT.getSizeInBits(), Quantity.getKnownMinValue()));
2212
2213 return DAG.getConstant(Quantity.getKnownMinValue(), DL, VT);
2214}
2215
2217 ElementCount EC) {
2218 return getFixedOrScalableQuantity(*this, DL, VT, EC);
2219}
2220
2222 return getFixedOrScalableQuantity(*this, DL, VT, TS);
2223}
2224
2226 ElementCount EC) {
2227 EVT IdxVT = TLI->getVectorIdxTy(getDataLayout());
2228 EVT MaskVT = TLI->getSetCCResultType(getDataLayout(), *getContext(), DataVT);
2229 return getNode(ISD::GET_ACTIVE_LANE_MASK, DL, MaskVT,
2230 getConstant(0, DL, IdxVT), getElementCount(DL, IdxVT, EC));
2231}
2232
2234 APInt One(ResVT.getScalarSizeInBits(), 1);
2235 return getStepVector(DL, ResVT, One);
2236}
2237
2239 const APInt &StepVal) {
2240 assert(ResVT.getScalarSizeInBits() == StepVal.getBitWidth());
2241 if (ResVT.isScalableVector())
2242 return getNode(
2243 ISD::STEP_VECTOR, DL, ResVT,
2244 getTargetConstant(StepVal, DL, ResVT.getVectorElementType()));
2245
2246 SmallVector<SDValue, 16> OpsStepConstants;
2247 for (uint64_t i = 0; i < ResVT.getVectorNumElements(); i++)
2248 OpsStepConstants.push_back(
2249 getConstant(StepVal * i, DL, ResVT.getVectorElementType()));
2250 return getBuildVector(ResVT, DL, OpsStepConstants);
2251}
2252
2253/// Swaps the values of N1 and N2. Swaps all indices in the shuffle mask M that
2254/// point at N1 to point at N2 and indices that point at N2 to point at N1.
2259
2261 SDValue N2, ArrayRef<int> Mask) {
2262 assert(VT.getVectorNumElements() == Mask.size() &&
2263 "Must have the same number of vector elements as mask elements!");
2264 assert(VT == N1.getValueType() && VT == N2.getValueType() &&
2265 "Invalid VECTOR_SHUFFLE");
2266
2267 // Canonicalize shuffle undef, undef -> undef
2268 if (N1.isUndef() && N2.isUndef()) {
2269 if (N1.getOpcode() == ISD::POISON && N2.getOpcode() == ISD::POISON)
2270 return getPOISON(VT);
2271 return getUNDEF(VT);
2272 }
2273
2274 // Validate that all indices in Mask are within the range of the elements
2275 // input to the shuffle.
2276 int NElts = Mask.size();
2277 assert(llvm::all_of(Mask,
2278 [&](int M) { return M < (NElts * 2) && M >= -1; }) &&
2279 "Index out of range");
2280
2281 // Copy the mask so we can do any needed cleanup.
2282 SmallVector<int, 8> MaskVec(Mask);
2283
2284 // Canonicalize shuffle v, v -> v, poison
2285 if (N1 == N2) {
2286 N2 = getPOISON(VT);
2287 for (int i = 0; i != NElts; ++i)
2288 if (MaskVec[i] >= NElts) MaskVec[i] -= NElts;
2289 }
2290
2291 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
2292 if (N1.isUndef())
2293 commuteShuffle(N1, N2, MaskVec);
2294
2295 if (TLI->hasVectorBlend()) {
2296 // If shuffling a splat, try to blend the splat instead. We do this here so
2297 // that even when this arises during lowering we don't have to re-handle it.
2298 auto BlendSplat = [&](BuildVectorSDNode *BV, int Offset) {
2299 BitVector UndefElements;
2300 SDValue Splat = BV->getSplatValue(&UndefElements);
2301 if (!Splat)
2302 return;
2303
2304 for (int i = 0; i < NElts; ++i) {
2305 if (MaskVec[i] < Offset || MaskVec[i] >= (Offset + NElts))
2306 continue;
2307
2308 // If this input comes from undef, mark it as such.
2309 if (UndefElements[MaskVec[i] - Offset]) {
2310 MaskVec[i] = -1;
2311 continue;
2312 }
2313
2314 // If we can blend a non-undef lane, use that instead.
2315 if (!UndefElements[i])
2316 MaskVec[i] = i + Offset;
2317 }
2318 };
2319 if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
2320 BlendSplat(N1BV, 0);
2321 if (auto *N2BV = dyn_cast<BuildVectorSDNode>(N2))
2322 BlendSplat(N2BV, NElts);
2323 }
2324
2325 // Canonicalize all index into lhs, -> shuffle lhs, poison
2326 // Canonicalize all index into rhs, -> shuffle rhs, poison
2327 bool AllLHS = true, AllRHS = true;
2328 bool N2Undef = N2.isUndef();
2329 for (int i = 0; i != NElts; ++i) {
2330 if (MaskVec[i] >= NElts) {
2331 if (N2Undef)
2332 MaskVec[i] = -1;
2333 else
2334 AllLHS = false;
2335 } else if (MaskVec[i] >= 0) {
2336 AllRHS = false;
2337 }
2338 }
2339 if (AllLHS && AllRHS)
2340 return getPOISON(VT);
2341 if (AllLHS && !N2Undef)
2342 N2 = getPOISON(VT);
2343 if (AllRHS) {
2344 N1 = getPOISON(VT);
2345 commuteShuffle(N1, N2, MaskVec);
2346 }
2347 // Reset our undef status after accounting for the mask.
2348 N2Undef = N2.isUndef();
2349 // Re-check whether both sides ended up undef.
2350 if (N1.isUndef() && N2Undef) {
2351 if (N1.getOpcode() == ISD::POISON && N2.getOpcode() == ISD::POISON)
2352 return getPOISON(VT);
2353 return getUNDEF(VT);
2354 }
2355
2356 // If Identity shuffle return that node.
2357 bool Identity = true, AllSame = true;
2358 for (int i = 0; i != NElts; ++i) {
2359 if (MaskVec[i] >= 0 && MaskVec[i] != i) Identity = false;
2360 if (MaskVec[i] != MaskVec[0]) AllSame = false;
2361 }
2362 if (Identity && NElts)
2363 return N1;
2364
2365 // Shuffling a constant splat doesn't change the result.
2366 if (N2Undef) {
2367 SDValue V = N1;
2368
2369 // Look through any bitcasts. We check that these don't change the number
2370 // (and size) of elements and just changes their types.
2371 while (V.getOpcode() == ISD::BITCAST)
2372 V = V->getOperand(0);
2373
2374 // A splat should always show up as a build vector node.
2375 if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) {
2376 BitVector UndefElements;
2377 SDValue Splat = BV->getSplatValue(&UndefElements);
2378 // If this is a splat of an undef, shuffling it is also undef.
2379 if (Splat && Splat.isUndef())
2380 return Splat.getOpcode() == ISD::POISON ? getPOISON(VT) : getUNDEF(VT);
2381
2382 bool SameNumElts =
2383 V.getValueType().getVectorNumElements() == VT.getVectorNumElements();
2384
2385 // We only have a splat which can skip shuffles if there is a splatted
2386 // value and no undef lanes rearranged by the shuffle.
2387 if (Splat && UndefElements.none()) {
2388 // Splat of <x, x, ..., x>, return <x, x, ..., x>, provided that the
2389 // number of elements match or the value splatted is a zero constant.
2390 if (SameNumElts || isNullConstant(Splat))
2391 return N1;
2392 }
2393
2394 // If the shuffle itself creates a splat, build the vector directly.
2395 if (AllSame && SameNumElts) {
2396 EVT BuildVT = BV->getValueType(0);
2397 const SDValue &Splatted = BV->getOperand(MaskVec[0]);
2398 SDValue NewBV = getSplatBuildVector(BuildVT, dl, Splatted);
2399
2400 // We may have jumped through bitcasts, so the type of the
2401 // BUILD_VECTOR may not match the type of the shuffle.
2402 if (BuildVT != VT)
2403 NewBV = getNode(ISD::BITCAST, dl, VT, NewBV);
2404 return NewBV;
2405 }
2406 }
2407 }
2408
2409 SDVTList VTs = getVTList(VT);
2411 SDValue Ops[2] = { N1, N2 };
2413 for (int i = 0; i != NElts; ++i)
2414 ID.AddInteger(MaskVec[i]);
2415
2416 void* IP = nullptr;
2417 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
2418 return SDValue(E, 0);
2419
2420 // Allocate the mask array for the node out of the BumpPtrAllocator, since
2421 // SDNode doesn't have access to it. This memory will be "leaked" when
2422 // the node is deallocated, but recovered when the NodeAllocator is released.
2423 int *MaskAlloc = OperandAllocator.Allocate<int>(NElts);
2424 llvm::copy(MaskVec, MaskAlloc);
2425
2426 auto *N = newSDNode<ShuffleVectorSDNode>(VTs, dl.getIROrder(),
2427 dl.getDebugLoc(), MaskAlloc);
2428 createOperands(N, Ops);
2429
2430 CSEMap.InsertNode(N, IP);
2431 InsertNode(N);
2432 SDValue V = SDValue(N, 0);
2433 NewSDValueDbgMsg(V, "Creating new node: ", this);
2434 return V;
2435}
2436
2438 EVT VT = SV.getValueType(0);
2439 SmallVector<int, 8> MaskVec(SV.getMask());
2441
2442 SDValue Op0 = SV.getOperand(0);
2443 SDValue Op1 = SV.getOperand(1);
2444 return getVectorShuffle(VT, SDLoc(&SV), Op1, Op0, MaskVec);
2445}
2446
2448 SDVTList VTs = getVTList(VT);
2450 AddNodeIDNode(ID, ISD::Register, VTs, {});
2451 ID.AddInteger(Reg.id());
2452 void *IP = nullptr;
2453 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2454 return SDValue(E, 0);
2455
2456 auto *N = newSDNode<RegisterSDNode>(Reg, VTs);
2457 N->SDNodeBits.IsDivergent = TLI->isSDNodeSourceOfDivergence(N, FLI, UA);
2458 CSEMap.InsertNode(N, IP);
2459 InsertNode(N);
2460 return SDValue(N, 0);
2461}
2462
2465 AddNodeIDNode(ID, ISD::RegisterMask, getVTList(MVT::Untyped), {});
2466 ID.AddPointer(RegMask);
2467 void *IP = nullptr;
2468 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2469 return SDValue(E, 0);
2470
2471 auto *N = newSDNode<RegisterMaskSDNode>(RegMask);
2472 CSEMap.InsertNode(N, IP);
2473 InsertNode(N);
2474 return SDValue(N, 0);
2475}
2476
2478 MCSymbol *Label) {
2479 return getLabelNode(ISD::EH_LABEL, dl, Root, Label);
2480}
2481
2482SDValue SelectionDAG::getLabelNode(unsigned Opcode, const SDLoc &dl,
2483 SDValue Root, MCSymbol *Label) {
2485 SDValue Ops[] = { Root };
2486 AddNodeIDNode(ID, Opcode, getVTList(MVT::Other), Ops);
2487 ID.AddPointer(Label);
2488 void *IP = nullptr;
2489 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2490 return SDValue(E, 0);
2491
2492 auto *N =
2493 newSDNode<LabelSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), Label);
2494 createOperands(N, Ops);
2495
2496 CSEMap.InsertNode(N, IP);
2497 InsertNode(N);
2498 return SDValue(N, 0);
2499}
2500
2502 int64_t Offset, bool isTarget,
2503 unsigned TargetFlags) {
2504 unsigned Opc = isTarget ? ISD::TargetBlockAddress : ISD::BlockAddress;
2505 SDVTList VTs = getVTList(VT);
2506
2508 AddNodeIDNode(ID, Opc, VTs, {});
2509 ID.AddPointer(BA);
2510 ID.AddInteger(Offset);
2511 ID.AddInteger(TargetFlags);
2512 void *IP = nullptr;
2513 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2514 return SDValue(E, 0);
2515
2516 auto *N = newSDNode<BlockAddressSDNode>(Opc, VTs, BA, Offset, TargetFlags);
2517 CSEMap.InsertNode(N, IP);
2518 InsertNode(N);
2519 return SDValue(N, 0);
2520}
2521
2524 AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), {});
2525 ID.AddPointer(V);
2526
2527 void *IP = nullptr;
2528 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2529 return SDValue(E, 0);
2530
2531 auto *N = newSDNode<SrcValueSDNode>(V);
2532 CSEMap.InsertNode(N, IP);
2533 InsertNode(N);
2534 return SDValue(N, 0);
2535}
2536
2539 AddNodeIDNode(ID, ISD::MDNODE_SDNODE, getVTList(MVT::Other), {});
2540 ID.AddPointer(MD);
2541
2542 void *IP = nullptr;
2543 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2544 return SDValue(E, 0);
2545
2546 auto *N = newSDNode<MDNodeSDNode>(MD);
2547 CSEMap.InsertNode(N, IP);
2548 InsertNode(N);
2549 return SDValue(N, 0);
2550}
2551
2553 if (VT == V.getValueType())
2554 return V;
2555
2556 return getNode(ISD::BITCAST, SDLoc(V), VT, V);
2557}
2558
2560 unsigned SrcAS, unsigned DestAS) {
2561 SDVTList VTs = getVTList(VT);
2562 SDValue Ops[] = {Ptr};
2565 ID.AddInteger(SrcAS);
2566 ID.AddInteger(DestAS);
2567
2568 void *IP = nullptr;
2569 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
2570 return SDValue(E, 0);
2571
2572 auto *N = newSDNode<AddrSpaceCastSDNode>(dl.getIROrder(), dl.getDebugLoc(),
2573 VTs, SrcAS, DestAS);
2574 createOperands(N, Ops);
2575
2576 CSEMap.InsertNode(N, IP);
2577 InsertNode(N);
2578 return SDValue(N, 0);
2579}
2580
2582 return getNode(ISD::FREEZE, SDLoc(V), V.getValueType(), V);
2583}
2584
2586 UndefPoisonKind Kind) {
2587 if (isGuaranteedNotToBeUndefOrPoison(V, DemandedElts, Kind))
2588 return V;
2589 return getFreeze(V);
2590}
2591
2592/// getShiftAmountOperand - Return the specified value casted to
2593/// the target's desired shift amount type.
2595 EVT OpTy = Op.getValueType();
2596 EVT ShTy = TLI->getShiftAmountTy(LHSTy, getDataLayout());
2597 if (OpTy == ShTy || OpTy.isVector()) return Op;
2598
2599 return getZExtOrTrunc(Op, SDLoc(Op), ShTy);
2600}
2601
2603 SDLoc dl(Node);
2605 const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2606 EVT VT = Node->getValueType(0);
2607 SDValue Tmp1 = Node->getOperand(0);
2608 SDValue Tmp2 = Node->getOperand(1);
2609 const MaybeAlign MA(Node->getConstantOperandVal(3));
2610
2611 SDValue VAListLoad = getLoad(TLI.getPointerTy(getDataLayout()), dl, Tmp1,
2612 Tmp2, MachinePointerInfo(V));
2613 SDValue VAList = VAListLoad;
2614
2615 if (MA && *MA > TLI.getMinStackArgumentAlignment()) {
2616 VAList = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
2617 getConstant(MA->value() - 1, dl, VAList.getValueType()));
2618
2619 VAList = getNode(
2620 ISD::AND, dl, VAList.getValueType(), VAList,
2621 getSignedConstant(-(int64_t)MA->value(), dl, VAList.getValueType()));
2622 }
2623
2624 // Increment the pointer, VAList, to the next vaarg
2625 Tmp1 = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
2626 getConstant(getDataLayout().getTypeAllocSize(
2627 VT.getTypeForEVT(*getContext())),
2628 dl, VAList.getValueType()));
2629 // Store the incremented VAList to the legalized pointer
2630 Tmp1 =
2631 getStore(VAListLoad.getValue(1), dl, Tmp1, Tmp2, MachinePointerInfo(V));
2632 // Load the actual argument out of the pointer VAList
2633 return getLoad(VT, dl, Tmp1, VAList, MachinePointerInfo());
2634}
2635
2637 SDLoc dl(Node);
2639 // This defaults to loading a pointer from the input and storing it to the
2640 // output, returning the chain.
2641 const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue();
2642 const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue();
2643 SDValue Tmp1 =
2644 getLoad(TLI.getPointerTy(getDataLayout()), dl, Node->getOperand(0),
2645 Node->getOperand(2), MachinePointerInfo(VS));
2646 return getStore(Tmp1.getValue(1), dl, Tmp1, Node->getOperand(1),
2647 MachinePointerInfo(VD));
2648}
2649
2651 const DataLayout &DL = getDataLayout();
2652 Type *Ty = VT.getTypeForEVT(*getContext());
2653 Align RedAlign = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty);
2654
2655 if (TLI->isTypeLegal(VT) || !VT.isVector())
2656 return RedAlign;
2657
2658 const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
2659 const Align StackAlign = TFI->getStackAlign();
2660
2661 // See if we can choose a smaller ABI alignment in cases where it's an
2662 // illegal vector type that will get broken down.
2663 if (RedAlign > StackAlign) {
2664 EVT IntermediateVT;
2665 MVT RegisterVT;
2666 unsigned NumIntermediates;
2667 TLI->getVectorTypeBreakdown(*getContext(), VT, IntermediateVT,
2668 NumIntermediates, RegisterVT);
2669 Ty = IntermediateVT.getTypeForEVT(*getContext());
2670 Align RedAlign2 = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty);
2671 if (RedAlign2 < RedAlign)
2672 RedAlign = RedAlign2;
2673
2674 if (!getMachineFunction().getFrameInfo().isStackRealignable())
2675 // If the stack is not realignable, the alignment should be limited to the
2676 // StackAlignment
2677 RedAlign = std::min(RedAlign, StackAlign);
2678 }
2679
2680 return RedAlign;
2681}
2682
2684 MachineFrameInfo &MFI = MF->getFrameInfo();
2685 const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
2686 int StackID = 0;
2687 if (Bytes.isScalable())
2688 StackID = TFI->getStackIDForScalableVectors();
2689 // The stack id gives an indication of whether the object is scalable or
2690 // not, so it's safe to pass in the minimum size here.
2691 int FrameIdx = MFI.CreateStackObject(Bytes.getKnownMinValue(), Alignment,
2692 false, nullptr, StackID);
2693 return getFrameIndex(FrameIdx, TLI->getFrameIndexTy(getDataLayout()));
2694}
2695
2697 Type *Ty = VT.getTypeForEVT(*getContext());
2698 Align StackAlign =
2699 std::max(getDataLayout().getPrefTypeAlign(Ty), Align(minAlign));
2700 return CreateStackTemporary(VT.getStoreSize(), StackAlign);
2701}
2702
2704 TypeSize VT1Size = VT1.getStoreSize();
2705 TypeSize VT2Size = VT2.getStoreSize();
2706 assert(VT1Size.isScalable() == VT2Size.isScalable() &&
2707 "Don't know how to choose the maximum size when creating a stack "
2708 "temporary");
2709 TypeSize Bytes = VT1Size.getKnownMinValue() > VT2Size.getKnownMinValue()
2710 ? VT1Size
2711 : VT2Size;
2712
2713 Type *Ty1 = VT1.getTypeForEVT(*getContext());
2714 Type *Ty2 = VT2.getTypeForEVT(*getContext());
2715 const DataLayout &DL = getDataLayout();
2716 Align Align = std::max(DL.getPrefTypeAlign(Ty1), DL.getPrefTypeAlign(Ty2));
2717 return CreateStackTemporary(Bytes, Align);
2718}
2719
2721 ISD::CondCode Cond, const SDLoc &dl,
2722 SDNodeFlags Flags) {
2723 EVT OpVT = N1.getValueType();
2724
2725 auto GetUndefBooleanConstant = [&]() {
2726 if (VT.getScalarType() == MVT::i1 ||
2727 TLI->getBooleanContents(OpVT) ==
2729 return getUNDEF(VT);
2730 // ZeroOrOne / ZeroOrNegative require specific values for the high bits,
2731 // so we cannot use getUNDEF(). Return zero instead.
2732 return getConstant(0, dl, VT);
2733 };
2734
2735 // These setcc operations always fold.
2736 switch (Cond) {
2737 default: break;
2738 case ISD::SETFALSE:
2739 case ISD::SETFALSE2: return getBoolConstant(false, dl, VT, OpVT);
2740 case ISD::SETTRUE:
2741 case ISD::SETTRUE2: return getBoolConstant(true, dl, VT, OpVT);
2742
2743 case ISD::SETOEQ:
2744 case ISD::SETOGT:
2745 case ISD::SETOGE:
2746 case ISD::SETOLT:
2747 case ISD::SETOLE:
2748 case ISD::SETONE:
2749 case ISD::SETO:
2750 case ISD::SETUO:
2751 case ISD::SETUEQ:
2752 case ISD::SETUNE:
2753 assert(!OpVT.isInteger() && "Illegal setcc for integer!");
2754 break;
2755 }
2756
2757 if (OpVT.isInteger()) {
2758 // For EQ and NE, we can always pick a value for the undef to make the
2759 // predicate pass or fail, so we can return undef.
2760 // Matches behavior in llvm::ConstantFoldCompareInstruction.
2761 // icmp eq/ne X, undef -> undef.
2762 if ((N1.isUndef() || N2.isUndef()) &&
2763 (Cond == ISD::SETEQ || Cond == ISD::SETNE))
2764 return GetUndefBooleanConstant();
2765
2766 // If both operands are undef, we can return undef for int comparison.
2767 // icmp undef, undef -> undef.
2768 if (N1.isUndef() && N2.isUndef())
2769 return GetUndefBooleanConstant();
2770
2771 // icmp X, X -> true/false
2772 // icmp X, undef -> true/false because undef could be X.
2773 if (N1.isUndef() || N2.isUndef() || N1 == N2)
2774 return getBoolConstant(ISD::isTrueWhenEqual(Cond), dl, VT, OpVT);
2775 }
2776
2778 const APInt &C2 = N2C->getAPIntValue();
2780 const APInt &C1 = N1C->getAPIntValue();
2781
2783 dl, VT, OpVT);
2784 }
2785 }
2786
2787 auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
2788 auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
2789
2790 if (N1CFP && N2CFP) {
2791 APFloat::cmpResult R = N1CFP->getValueAPF().compare(N2CFP->getValueAPF());
2792 switch (Cond) {
2793 default: break;
2794 case ISD::SETEQ: if (R==APFloat::cmpUnordered)
2795 return GetUndefBooleanConstant();
2796 [[fallthrough]];
2797 case ISD::SETOEQ: return getBoolConstant(R==APFloat::cmpEqual, dl, VT,
2798 OpVT);
2799 case ISD::SETNE: if (R==APFloat::cmpUnordered)
2800 return GetUndefBooleanConstant();
2801 [[fallthrough]];
2803 R==APFloat::cmpLessThan, dl, VT,
2804 OpVT);
2805 case ISD::SETLT: if (R==APFloat::cmpUnordered)
2806 return GetUndefBooleanConstant();
2807 [[fallthrough]];
2808 case ISD::SETOLT: return getBoolConstant(R==APFloat::cmpLessThan, dl, VT,
2809 OpVT);
2810 case ISD::SETGT: if (R==APFloat::cmpUnordered)
2811 return GetUndefBooleanConstant();
2812 [[fallthrough]];
2814 VT, OpVT);
2815 case ISD::SETLE: if (R==APFloat::cmpUnordered)
2816 return GetUndefBooleanConstant();
2817 [[fallthrough]];
2819 R==APFloat::cmpEqual, dl, VT,
2820 OpVT);
2821 case ISD::SETGE: if (R==APFloat::cmpUnordered)
2822 return GetUndefBooleanConstant();
2823 [[fallthrough]];
2825 R==APFloat::cmpEqual, dl, VT, OpVT);
2826 case ISD::SETO: return getBoolConstant(R!=APFloat::cmpUnordered, dl, VT,
2827 OpVT);
2828 case ISD::SETUO: return getBoolConstant(R==APFloat::cmpUnordered, dl, VT,
2829 OpVT);
2831 R==APFloat::cmpEqual, dl, VT,
2832 OpVT);
2833 case ISD::SETUNE: return getBoolConstant(R!=APFloat::cmpEqual, dl, VT,
2834 OpVT);
2836 R==APFloat::cmpLessThan, dl, VT,
2837 OpVT);
2839 R==APFloat::cmpUnordered, dl, VT,
2840 OpVT);
2842 VT, OpVT);
2843 case ISD::SETUGE: return getBoolConstant(R!=APFloat::cmpLessThan, dl, VT,
2844 OpVT);
2845 }
2846 } else if (N1CFP && OpVT.isSimple() && !N2.isUndef()) {
2847 // Ensure that the constant occurs on the RHS.
2849 if (!TLI->isCondCodeLegal(SwappedCond, OpVT.getSimpleVT()))
2850 return SDValue();
2851 return getSetCC(dl, VT, N2, N1, SwappedCond, /*Chain=*/{},
2852 /*IsSignaling=*/false, Flags);
2853 } else if ((N2CFP && N2CFP->getValueAPF().isNaN()) ||
2854 (OpVT.isFloatingPoint() && (N1.isUndef() || N2.isUndef()))) {
2855 // If an operand is known to be a nan (or undef that could be a nan), we can
2856 // fold it.
2857 // Choosing NaN for the undef will always make unordered comparison succeed
2858 // and ordered comparison fails.
2859 // Matches behavior in llvm::ConstantFoldCompareInstruction.
2860 switch (ISD::getUnorderedFlavor(Cond)) {
2861 default:
2862 llvm_unreachable("Unknown flavor!");
2863 case 0: // Known false.
2864 return getBoolConstant(false, dl, VT, OpVT);
2865 case 1: // Known true.
2866 return getBoolConstant(true, dl, VT, OpVT);
2867 case 2: // Undefined.
2868 return GetUndefBooleanConstant();
2869 }
2870 }
2871
2872 // Could not fold it.
2873 return SDValue();
2874}
2875
2876/// SignBitIsZero - Return true if the sign bit of Op is known to be zero. We
2877/// use this predicate to simplify operations downstream.
2879 unsigned BitWidth = Op.getScalarValueSizeInBits();
2881}
2882
2883// TODO: Should have argument to specify if sign bit of nan is ignorable.
2885 if (Depth >= MaxRecursionDepth)
2886 return false; // Limit search depth.
2887
2888 unsigned Opc = Op.getOpcode();
2889 switch (Opc) {
2890 case ISD::FABS:
2891 return true;
2892 case ISD::AssertNoFPClass: {
2893 FPClassTest NoFPClass =
2894 static_cast<FPClassTest>(Op.getConstantOperandVal(1));
2895
2896 const FPClassTest TestMask = fcNan | fcNegative;
2897 return (NoFPClass & TestMask) == TestMask;
2898 }
2899 case ISD::ARITH_FENCE:
2900 return SignBitIsZeroFP(Op.getOperand(0), Depth + 1);
2901 case ISD::FEXP:
2902 case ISD::FEXP2:
2903 case ISD::FEXP10:
2904 return Op->getFlags().hasNoNaNs();
2905 case ISD::FMINNUM:
2906 case ISD::FMINNUM_IEEE:
2907 case ISD::FMINIMUM:
2908 case ISD::FMINIMUMNUM:
2909 return SignBitIsZeroFP(Op.getOperand(1), Depth + 1) &&
2910 SignBitIsZeroFP(Op.getOperand(0), Depth + 1);
2911 case ISD::FMAXNUM:
2912 case ISD::FMAXNUM_IEEE:
2913 case ISD::FMAXIMUM:
2914 case ISD::FMAXIMUMNUM:
2915 // TODO: If we can ignore the sign bit of nans, only one side being known 0
2916 // is sufficient.
2917 return SignBitIsZeroFP(Op.getOperand(1), Depth + 1) &&
2918 SignBitIsZeroFP(Op.getOperand(0), Depth + 1);
2919 default:
2920 return false;
2921 }
2922
2923 llvm_unreachable("covered opcode switch");
2924}
2925
2926/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
2927/// this predicate to simplify operations downstream. Mask is known to be zero
2928/// for bits that V cannot have.
2930 unsigned Depth) const {
2931 return Mask.isSubsetOf(computeKnownBits(V, Depth).Zero);
2932}
2933
2934/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero in
2935/// DemandedElts. We use this predicate to simplify operations downstream.
2936/// Mask is known to be zero for bits that V cannot have.
2938 const APInt &DemandedElts,
2939 unsigned Depth) const {
2940 return Mask.isSubsetOf(computeKnownBits(V, DemandedElts, Depth).Zero);
2941}
2942
2943/// MaskedVectorIsZero - Return true if 'Op' is known to be zero in
2944/// DemandedElts. We use this predicate to simplify operations downstream.
2946 unsigned Depth /* = 0 */) const {
2947 return computeKnownBits(V, DemandedElts, Depth).isZero();
2948}
2949
2950/// MaskedValueIsAllOnes - Return true if '(Op & Mask) == Mask'.
2952 unsigned Depth) const {
2953 return Mask.isSubsetOf(computeKnownBits(V, Depth).One);
2954}
2955
2957 const APInt &DemandedElts,
2958 unsigned Depth) const {
2959 EVT VT = Op.getValueType();
2960 assert(VT.isVector() && !VT.isScalableVector() && "Only for fixed vectors!");
2961
2962 unsigned NumElts = VT.getVectorNumElements();
2963 assert(DemandedElts.getBitWidth() == NumElts && "Unexpected demanded mask.");
2964
2965 APInt KnownZeroElements = APInt::getZero(NumElts);
2966 for (unsigned EltIdx = 0; EltIdx != NumElts; ++EltIdx) {
2967 if (!DemandedElts[EltIdx])
2968 continue; // Don't query elements that are not demanded.
2969 APInt Mask = APInt::getOneBitSet(NumElts, EltIdx);
2970 if (MaskedVectorIsZero(Op, Mask, Depth))
2971 KnownZeroElements.setBit(EltIdx);
2972 }
2973 return KnownZeroElements;
2974}
2975
2976/// isSplatValue - Return true if the vector V has the same value
2977/// across all DemandedElts. For scalable vectors, we don't know the
2978/// number of lanes at compile time. Instead, we use a 1 bit APInt
2979/// to represent a conservative value for all lanes; that is, that
2980/// one bit value is implicitly splatted across all lanes.
2981bool SelectionDAG::isSplatValue(SDValue V, const APInt &DemandedElts,
2982 APInt &UndefElts, unsigned Depth) const {
2983 unsigned Opcode = V.getOpcode();
2984 EVT VT = V.getValueType();
2985 assert(VT.isVector() && "Vector type expected");
2986 assert((!VT.isScalableVector() || DemandedElts.getBitWidth() == 1) &&
2987 "scalable demanded bits are ignored");
2988
2989 if (!DemandedElts)
2990 return false; // No demanded elts, better to assume we don't know anything.
2991
2992 if (Depth >= MaxRecursionDepth)
2993 return false; // Limit search depth.
2994
2995 // Deal with some common cases here that work for both fixed and scalable
2996 // vector types.
2997 switch (Opcode) {
2998 case ISD::SPLAT_VECTOR:
2999 UndefElts = V.getOperand(0).isUndef()
3000 ? APInt::getAllOnes(DemandedElts.getBitWidth())
3001 : APInt(DemandedElts.getBitWidth(), 0);
3002 return true;
3003 case ISD::ADD:
3004 case ISD::SUB:
3005 case ISD::AND:
3006 case ISD::XOR:
3007 case ISD::OR: {
3008 APInt UndefLHS, UndefRHS;
3009 SDValue LHS = V.getOperand(0);
3010 SDValue RHS = V.getOperand(1);
3011 // Only recognize splats with the same demanded undef elements for both
3012 // operands, otherwise we might fail to handle binop-specific undef
3013 // handling.
3014 // e.g. (and undef, 0) -> 0 etc.
3015 if (isSplatValue(LHS, DemandedElts, UndefLHS, Depth + 1) &&
3016 isSplatValue(RHS, DemandedElts, UndefRHS, Depth + 1) &&
3017 (DemandedElts & UndefLHS) == (DemandedElts & UndefRHS)) {
3018 UndefElts = UndefLHS | UndefRHS;
3019 return true;
3020 }
3021 return false;
3022 }
3023 case ISD::ABS:
3025 case ISD::TRUNCATE:
3026 case ISD::SIGN_EXTEND:
3027 case ISD::ZERO_EXTEND:
3028 return isSplatValue(V.getOperand(0), DemandedElts, UndefElts, Depth + 1);
3029 default:
3030 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
3031 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID)
3032 return TLI->isSplatValueForTargetNode(V, DemandedElts, UndefElts, *this,
3033 Depth);
3034 break;
3035 }
3036
3037 // We don't support other cases than those above for scalable vectors at
3038 // the moment.
3039 if (VT.isScalableVector())
3040 return false;
3041
3042 unsigned NumElts = VT.getVectorNumElements();
3043 assert(NumElts == DemandedElts.getBitWidth() && "Vector size mismatch");
3044 UndefElts = APInt::getZero(NumElts);
3045
3046 switch (Opcode) {
3047 case ISD::BUILD_VECTOR: {
3048 SDValue Scl;
3049 for (unsigned i = 0; i != NumElts; ++i) {
3050 SDValue Op = V.getOperand(i);
3051 if (Op.isUndef()) {
3052 UndefElts.setBit(i);
3053 continue;
3054 }
3055 if (!DemandedElts[i])
3056 continue;
3057 if (Scl && Scl != Op)
3058 return false;
3059 Scl = Op;
3060 }
3061 return true;
3062 }
3063 case ISD::VECTOR_SHUFFLE: {
3064 // Check if this is a shuffle node doing a splat or a shuffle of a splat.
3065 APInt DemandedLHS = APInt::getZero(NumElts);
3066 APInt DemandedRHS = APInt::getZero(NumElts);
3067 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(V)->getMask();
3068 for (int i = 0; i != (int)NumElts; ++i) {
3069 int M = Mask[i];
3070 if (M < 0) {
3071 UndefElts.setBit(i);
3072 continue;
3073 }
3074 if (!DemandedElts[i])
3075 continue;
3076 if (M < (int)NumElts)
3077 DemandedLHS.setBit(M);
3078 else
3079 DemandedRHS.setBit(M - NumElts);
3080 }
3081
3082 // If we aren't demanding either op, assume there's no splat.
3083 // If we are demanding both ops, assume there's no splat.
3084 if ((DemandedLHS.isZero() && DemandedRHS.isZero()) ||
3085 (!DemandedLHS.isZero() && !DemandedRHS.isZero()))
3086 return false;
3087
3088 // See if the demanded elts of the source op is a splat or we only demand
3089 // one element, which should always be a splat.
3090 // TODO: Handle source ops splats with undefs.
3091 auto CheckSplatSrc = [&](SDValue Src, const APInt &SrcElts) {
3092 APInt SrcUndefs;
3093 return (SrcElts.popcount() == 1) ||
3094 (isSplatValue(Src, SrcElts, SrcUndefs, Depth + 1) &&
3095 (SrcElts & SrcUndefs).isZero());
3096 };
3097 if (!DemandedLHS.isZero())
3098 return CheckSplatSrc(V.getOperand(0), DemandedLHS);
3099 return CheckSplatSrc(V.getOperand(1), DemandedRHS);
3100 }
3102 // Offset the demanded elts by the subvector index.
3103 SDValue Src = V.getOperand(0);
3104 // We don't support scalable vectors at the moment.
3105 if (Src.getValueType().isScalableVector())
3106 return false;
3107 uint64_t Idx = V.getConstantOperandVal(1);
3108 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
3109 APInt UndefSrcElts;
3110 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
3111 if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) {
3112 UndefElts = UndefSrcElts.extractBits(NumElts, Idx);
3113 return true;
3114 }
3115 break;
3116 }
3120 // Widen the demanded elts by the src element count.
3121 SDValue Src = V.getOperand(0);
3122 // We don't support scalable vectors at the moment.
3123 if (Src.getValueType().isScalableVector())
3124 return false;
3125 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
3126 APInt UndefSrcElts;
3127 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts);
3128 if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) {
3129 UndefElts = UndefSrcElts.trunc(NumElts);
3130 return true;
3131 }
3132 break;
3133 }
3134 case ISD::BITCAST: {
3135 SDValue Src = V.getOperand(0);
3136 EVT SrcVT = Src.getValueType();
3137 unsigned SrcBitWidth = SrcVT.getScalarSizeInBits();
3138 unsigned BitWidth = VT.getScalarSizeInBits();
3139
3140 // Ignore bitcasts from unsupported types.
3141 // TODO: Add fp support?
3142 if (!SrcVT.isVector() || !SrcVT.isInteger() || !VT.isInteger())
3143 break;
3144
3145 // Bitcast 'small element' vector to 'large element' vector.
3146 if ((BitWidth % SrcBitWidth) == 0) {
3147 // See if each sub element is a splat.
3148 unsigned Scale = BitWidth / SrcBitWidth;
3149 unsigned NumSrcElts = SrcVT.getVectorNumElements();
3150 APInt ScaledDemandedElts =
3151 APIntOps::ScaleBitMask(DemandedElts, NumSrcElts);
3152 for (unsigned I = 0; I != Scale; ++I) {
3153 APInt SubUndefElts;
3154 APInt SubDemandedElt = APInt::getOneBitSet(Scale, I);
3155 APInt SubDemandedElts = APInt::getSplat(NumSrcElts, SubDemandedElt);
3156 SubDemandedElts &= ScaledDemandedElts;
3157 if (!isSplatValue(Src, SubDemandedElts, SubUndefElts, Depth + 1))
3158 return false;
3159 // TODO: Add support for merging sub undef elements.
3160 if (!SubUndefElts.isZero())
3161 return false;
3162 }
3163 return true;
3164 }
3165 break;
3166 }
3167 }
3168
3169 return false;
3170}
3171
3172/// Helper wrapper to main isSplatValue function.
3173bool SelectionDAG::isSplatValue(SDValue V, bool AllowUndefs) const {
3174 EVT VT = V.getValueType();
3175 assert(VT.isVector() && "Vector type expected");
3176
3177 APInt UndefElts;
3178 // Since the number of lanes in a scalable vector is unknown at compile time,
3179 // we track one bit which is implicitly broadcast to all lanes. This means
3180 // that all lanes in a scalable vector are considered demanded.
3181 APInt DemandedElts
3183 return isSplatValue(V, DemandedElts, UndefElts) &&
3184 (AllowUndefs || !UndefElts);
3185}
3186
3189
3190 EVT VT = V.getValueType();
3191 unsigned Opcode = V.getOpcode();
3192 switch (Opcode) {
3193 default: {
3194 APInt UndefElts;
3195 // Since the number of lanes in a scalable vector is unknown at compile time,
3196 // we track one bit which is implicitly broadcast to all lanes. This means
3197 // that all lanes in a scalable vector are considered demanded.
3198 APInt DemandedElts
3200
3201 if (isSplatValue(V, DemandedElts, UndefElts)) {
3202 if (VT.isScalableVector()) {
3203 // DemandedElts and UndefElts are ignored for scalable vectors, since
3204 // the only supported cases are SPLAT_VECTOR nodes.
3205 SplatIdx = 0;
3206 } else {
3207 // Handle case where all demanded elements are UNDEF.
3208 if (DemandedElts.isSubsetOf(UndefElts)) {
3209 SplatIdx = 0;
3210 return getUNDEF(VT);
3211 }
3212 SplatIdx = (UndefElts & DemandedElts).countr_one();
3213 }
3214 return V;
3215 }
3216 break;
3217 }
3218 case ISD::SPLAT_VECTOR:
3219 SplatIdx = 0;
3220 return V;
3221 case ISD::VECTOR_SHUFFLE: {
3222 assert(!VT.isScalableVector());
3223 // Check if this is a shuffle node doing a splat.
3224 // TODO - remove this and rely purely on SelectionDAG::isSplatValue,
3225 // getTargetVShiftNode currently struggles without the splat source.
3226 auto *SVN = cast<ShuffleVectorSDNode>(V);
3227 if (!SVN->isSplat())
3228 break;
3229 int Idx = SVN->getSplatIndex();
3230 int NumElts = V.getValueType().getVectorNumElements();
3231 SplatIdx = Idx % NumElts;
3232 return V.getOperand(Idx / NumElts);
3233 }
3234 }
3235
3236 return SDValue();
3237}
3238
3240 int SplatIdx;
3241 if (SDValue SrcVector = getSplatSourceVector(V, SplatIdx)) {
3242 EVT SVT = SrcVector.getValueType().getScalarType();
3243 EVT LegalSVT = SVT;
3244 if (LegalTypes && !TLI->isTypeLegal(SVT)) {
3245 if (!SVT.isInteger())
3246 return SDValue();
3247 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
3248 if (LegalSVT.bitsLT(SVT))
3249 return SDValue();
3250 }
3251 return getExtractVectorElt(SDLoc(V), LegalSVT, SrcVector, SplatIdx);
3252 }
3253 return SDValue();
3254}
3255
3256std::optional<ConstantRange>
3258 unsigned Depth) const {
3259 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
3260 V.getOpcode() == ISD::SRA) &&
3261 "Unknown shift node");
3262 // Shifting more than the bitwidth is not valid.
3263 unsigned BitWidth = V.getScalarValueSizeInBits();
3264
3265 if (auto *Cst = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
3266 const APInt &ShAmt = Cst->getAPIntValue();
3267 if (ShAmt.uge(BitWidth))
3268 return std::nullopt;
3269 return ConstantRange(ShAmt);
3270 }
3271
3272 if (auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1))) {
3273 const APInt *MinAmt = nullptr, *MaxAmt = nullptr;
3274 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
3275 if (!DemandedElts[i])
3276 continue;
3277 auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i));
3278 if (!SA) {
3279 MinAmt = MaxAmt = nullptr;
3280 break;
3281 }
3282 const APInt &ShAmt = SA->getAPIntValue();
3283 if (ShAmt.uge(BitWidth))
3284 return std::nullopt;
3285 if (!MinAmt || MinAmt->ugt(ShAmt))
3286 MinAmt = &ShAmt;
3287 if (!MaxAmt || MaxAmt->ult(ShAmt))
3288 MaxAmt = &ShAmt;
3289 }
3290 assert(((!MinAmt && !MaxAmt) || (MinAmt && MaxAmt)) &&
3291 "Failed to find matching min/max shift amounts");
3292 if (MinAmt && MaxAmt)
3293 return ConstantRange(*MinAmt, *MaxAmt + 1);
3294 }
3295
3296 // Use computeKnownBits to find a hidden constant/knownbits (usually type
3297 // legalized). e.g. Hidden behind multiple bitcasts/build_vector/casts etc.
3298 KnownBits KnownAmt = computeKnownBits(V.getOperand(1), DemandedElts, Depth);
3299 if (KnownAmt.getMaxValue().ult(BitWidth))
3300 return ConstantRange::fromKnownBits(KnownAmt, /*IsSigned=*/false);
3301
3302 return std::nullopt;
3303}
3304
3305std::optional<unsigned>
3307 unsigned Depth) const {
3308 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
3309 V.getOpcode() == ISD::SRA) &&
3310 "Unknown shift node");
3311 if (std::optional<ConstantRange> AmtRange =
3312 getValidShiftAmountRange(V, DemandedElts, Depth))
3313 if (const APInt *ShAmt = AmtRange->getSingleElement())
3314 return ShAmt->getZExtValue();
3315 return std::nullopt;
3316}
3317
3318std::optional<unsigned>
3320 APInt DemandedElts = getDemandAllEltsMask(V);
3321 return getValidShiftAmount(V, DemandedElts, Depth);
3322}
3323
3324std::optional<unsigned>
3326 unsigned Depth) const {
3327 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
3328 V.getOpcode() == ISD::SRA) &&
3329 "Unknown shift node");
3330 if (std::optional<ConstantRange> AmtRange =
3331 getValidShiftAmountRange(V, DemandedElts, Depth))
3332 return AmtRange->getUnsignedMin().getZExtValue();
3333 return std::nullopt;
3334}
3335
3336std::optional<unsigned>
3338 APInt DemandedElts = getDemandAllEltsMask(V);
3339 return getValidMinimumShiftAmount(V, DemandedElts, Depth);
3340}
3341
3342std::optional<unsigned>
3344 unsigned Depth) const {
3345 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
3346 V.getOpcode() == ISD::SRA) &&
3347 "Unknown shift node");
3348 if (std::optional<ConstantRange> AmtRange =
3349 getValidShiftAmountRange(V, DemandedElts, Depth))
3350 return AmtRange->getUnsignedMax().getZExtValue();
3351 return std::nullopt;
3352}
3353
3354std::optional<unsigned>
3356 APInt DemandedElts = getDemandAllEltsMask(V);
3357 return getValidMaximumShiftAmount(V, DemandedElts, Depth);
3358}
3359
3360/// Determine which bits of Op are known to be either zero or one and return
3361/// them in Known. For vectors, the known bits are those that are shared by
3362/// every vector element.
3364 APInt DemandedElts = getDemandAllEltsMask(Op);
3365 return computeKnownBits(Op, DemandedElts, Depth);
3366}
3367
3368/// Determine which bits of Op are known to be either zero or one and return
3369/// them in Known. The DemandedElts argument allows us to only collect the known
3370/// bits that are shared by the requested vector elements.
3372 unsigned Depth) const {
3373 unsigned BitWidth = Op.getScalarValueSizeInBits();
3374
3375 KnownBits Known(BitWidth); // Don't know anything.
3376
3377 if (auto OptAPInt = Op->bitcastToAPInt()) {
3378 // We know all of the bits for a constant!
3379 return KnownBits::makeConstant(*std::move(OptAPInt));
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::MERGE_VALUES:
3399 return computeKnownBits(Op.getOperand(Op.getResNo()), DemandedElts,
3400 Depth + 1);
3401 case ISD::SPLAT_VECTOR: {
3402 SDValue SrcOp = Op.getOperand(0);
3403 assert(SrcOp.getValueSizeInBits() >= BitWidth &&
3404 "Expected SPLAT_VECTOR implicit truncation");
3405 // Implicitly truncate the bits to match the official semantics of
3406 // SPLAT_VECTOR.
3408 break;
3409 }
3411 unsigned ScalarSize = Op.getOperand(0).getScalarValueSizeInBits();
3412 assert(ScalarSize * Op.getNumOperands() == BitWidth &&
3413 "Expected SPLAT_VECTOR_PARTS scalars to cover element width");
3414 for (auto [I, SrcOp] : enumerate(Op->ops())) {
3415 Known.insertBits(computeKnownBits(SrcOp, Depth + 1), ScalarSize * I);
3416 }
3417 break;
3418 }
3419 case ISD::STEP_VECTOR: {
3420 const APInt &Step = Op.getConstantOperandAPInt(0);
3421
3422 if (Step.isPowerOf2())
3423 Known.Zero.setLowBits(Step.logBase2());
3424
3426
3427 if (!isUIntN(BitWidth, Op.getValueType().getVectorMinNumElements()))
3428 break;
3429 const APInt MinNumElts =
3430 APInt(BitWidth, Op.getValueType().getVectorMinNumElements());
3431
3432 bool Overflow;
3433 const APInt MaxNumElts = getVScaleRange(&F, BitWidth)
3435 .umul_ov(MinNumElts, Overflow);
3436 if (Overflow)
3437 break;
3438
3439 const APInt MaxValue = (MaxNumElts - 1).umul_ov(Step, Overflow);
3440 if (Overflow)
3441 break;
3442
3443 Known.Zero.setHighBits(MaxValue.countl_zero());
3444 break;
3445 }
3446 case ISD::BUILD_VECTOR:
3447 assert(!Op.getValueType().isScalableVector());
3448 // Collect the known bits that are shared by every demanded vector element.
3449 Known.setAllConflict();
3450 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
3451 if (!DemandedElts[i])
3452 continue;
3453
3454 SDValue SrcOp = Op.getOperand(i);
3455 Known2 = computeKnownBits(SrcOp, Depth + 1);
3456
3457 // BUILD_VECTOR can implicitly truncate sources, we must handle this.
3458 if (SrcOp.getValueSizeInBits() != BitWidth) {
3459 assert(SrcOp.getValueSizeInBits() > BitWidth &&
3460 "Expected BUILD_VECTOR implicit truncation");
3461 Known2 = Known2.trunc(BitWidth);
3462 }
3463
3464 // Known bits are the values that are shared by every demanded element.
3465 Known = Known.intersectWith(Known2);
3466
3467 // If we don't know any bits, early out.
3468 if (Known.isUnknown())
3469 break;
3470 }
3471 break;
3472 case ISD::VECTOR_COMPRESS: {
3473 SDValue Vec = Op.getOperand(0);
3474 SDValue PassThru = Op.getOperand(2);
3475 Known = computeKnownBits(PassThru, DemandedElts, Depth + 1);
3476 // If we don't know any bits, early out.
3477 if (Known.isUnknown())
3478 break;
3479 Known2 = computeKnownBits(Vec, Depth + 1);
3480 Known = Known.intersectWith(Known2);
3481 break;
3482 }
3483 case ISD::VECTOR_SHUFFLE: {
3484 assert(!Op.getValueType().isScalableVector());
3485 // Collect the known bits that are shared by every vector element referenced
3486 // by the shuffle.
3487 APInt DemandedLHS, DemandedRHS;
3489 assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
3490 if (!getShuffleDemandedElts(NumElts, SVN->getMask(), DemandedElts,
3491 DemandedLHS, DemandedRHS))
3492 break;
3493
3494 // Known bits are the values that are shared by every demanded element.
3495 Known.setAllConflict();
3496 if (!!DemandedLHS) {
3497 SDValue LHS = Op.getOperand(0);
3498 Known2 = computeKnownBits(LHS, DemandedLHS, Depth + 1);
3499 Known = Known.intersectWith(Known2);
3500 }
3501 // If we don't know any bits, early out.
3502 if (Known.isUnknown())
3503 break;
3504 if (!!DemandedRHS) {
3505 SDValue RHS = Op.getOperand(1);
3506 Known2 = computeKnownBits(RHS, DemandedRHS, Depth + 1);
3507 Known = Known.intersectWith(Known2);
3508 }
3509 break;
3510 }
3511 case ISD::VSCALE: {
3513 const APInt &Multiplier = Op.getConstantOperandAPInt(0);
3515 break;
3516 }
3517 case ISD::CONCAT_VECTORS: {
3518 if (Op.getValueType().isScalableVector())
3519 break;
3520 // Split DemandedElts and test each of the demanded subvectors.
3521 Known.setAllConflict();
3522 EVT SubVectorVT = Op.getOperand(0).getValueType();
3523 unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
3524 unsigned NumSubVectors = Op.getNumOperands();
3525 for (unsigned i = 0; i != NumSubVectors; ++i) {
3526 APInt DemandedSub =
3527 DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts);
3528 if (!!DemandedSub) {
3529 SDValue Sub = Op.getOperand(i);
3530 Known2 = computeKnownBits(Sub, DemandedSub, Depth + 1);
3531 Known = Known.intersectWith(Known2);
3532 }
3533 // If we don't know any bits, early out.
3534 if (Known.isUnknown())
3535 break;
3536 }
3537 break;
3538 }
3539 case ISD::INSERT_SUBVECTOR: {
3540 if (Op.getValueType().isScalableVector())
3541 break;
3542 // Demand any elements from the subvector and the remainder from the src its
3543 // inserted into.
3544 SDValue Src = Op.getOperand(0);
3545 SDValue Sub = Op.getOperand(1);
3546 uint64_t Idx = Op.getConstantOperandVal(2);
3547 unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
3548 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
3549 APInt DemandedSrcElts = DemandedElts;
3550 DemandedSrcElts.clearBits(Idx, Idx + NumSubElts);
3551
3552 Known.setAllConflict();
3553 if (!!DemandedSubElts) {
3554 Known = computeKnownBits(Sub, DemandedSubElts, Depth + 1);
3555 if (Known.isUnknown())
3556 break; // early-out.
3557 }
3558 if (!!DemandedSrcElts) {
3559 Known2 = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
3560 Known = Known.intersectWith(Known2);
3561 }
3562 break;
3563 }
3565 // Offset the demanded elts by the subvector index.
3566 SDValue Src = Op.getOperand(0);
3567
3568 APInt DemandedSrcElts;
3569 if (Src.getValueType().isScalableVector())
3570 DemandedSrcElts = APInt(1, 1); // <=> 'demand all elements'
3571 else {
3572 uint64_t Idx = Op.getConstantOperandVal(1);
3573 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
3574 DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
3575 }
3576 Known = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
3577 break;
3578 }
3579 case ISD::SCALAR_TO_VECTOR: {
3580 if (Op.getValueType().isScalableVector())
3581 break;
3582 // We know about scalar_to_vector as much as we know about it source,
3583 // which becomes the first element of otherwise unknown vector.
3584 if (DemandedElts != 1)
3585 break;
3586
3587 SDValue N0 = Op.getOperand(0);
3588 Known = computeKnownBits(N0, Depth + 1);
3589 if (N0.getValueSizeInBits() != BitWidth)
3590 Known = Known.trunc(BitWidth);
3591
3592 break;
3593 }
3594 case ISD::BITCAST: {
3595 if (Op.getValueType().isScalableVector())
3596 break;
3597
3598 SDValue N0 = Op.getOperand(0);
3599 EVT SubVT = N0.getValueType();
3600 unsigned SubBitWidth = SubVT.getScalarSizeInBits();
3601
3602 // Ignore bitcasts from unsupported types.
3603 if (!(SubVT.isInteger() || SubVT.isFloatingPoint()))
3604 break;
3605
3606 // Fast handling of 'identity' bitcasts.
3607 if (BitWidth == SubBitWidth) {
3608 Known = computeKnownBits(N0, DemandedElts, Depth + 1);
3609 break;
3610 }
3611
3612 bool IsLE = getDataLayout().isLittleEndian();
3613
3614 // Bitcast 'small element' vector to 'large element' scalar/vector.
3615 if ((BitWidth % SubBitWidth) == 0) {
3616 assert(N0.getValueType().isVector() && "Expected bitcast from vector");
3617
3618 // Collect known bits for the (larger) output by collecting the known
3619 // bits from each set of sub elements and shift these into place.
3620 // We need to separately call computeKnownBits for each set of
3621 // sub elements as the knownbits for each is likely to be different.
3622 unsigned SubScale = BitWidth / SubBitWidth;
3623 APInt SubDemandedElts(NumElts * SubScale, 0);
3624 for (unsigned i = 0; i != NumElts; ++i)
3625 if (DemandedElts[i])
3626 SubDemandedElts.setBit(i * SubScale);
3627
3628 for (unsigned i = 0; i != SubScale; ++i) {
3629 Known2 = computeKnownBits(N0, SubDemandedElts.shl(i),
3630 Depth + 1);
3631 unsigned Shifts = IsLE ? i : SubScale - 1 - i;
3632 Known.insertBits(Known2, SubBitWidth * Shifts);
3633 }
3634 }
3635
3636 // Bitcast 'large element' scalar/vector to 'small element' vector.
3637 if ((SubBitWidth % BitWidth) == 0) {
3638 assert(Op.getValueType().isVector() && "Expected bitcast to vector");
3639
3640 // Collect known bits for the (smaller) output by collecting the known
3641 // bits from the overlapping larger input elements and extracting the
3642 // sub sections we actually care about.
3643 unsigned SubScale = SubBitWidth / BitWidth;
3644 APInt SubDemandedElts =
3645 APIntOps::ScaleBitMask(DemandedElts, NumElts / SubScale);
3646 Known2 = computeKnownBits(N0, SubDemandedElts, Depth + 1);
3647
3648 Known.setAllConflict();
3649 for (unsigned i = 0; i != NumElts; ++i)
3650 if (DemandedElts[i]) {
3651 unsigned Shifts = IsLE ? i : NumElts - 1 - i;
3652 unsigned Offset = (Shifts % SubScale) * BitWidth;
3653 Known = Known.intersectWith(Known2.extractBits(BitWidth, Offset));
3654 // If we don't know any bits, early out.
3655 if (Known.isUnknown())
3656 break;
3657 }
3658 }
3659 break;
3660 }
3661 case ISD::AND:
3662 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3663 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3664
3665 Known &= Known2;
3666 break;
3667 case ISD::OR:
3668 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3669 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3670
3671 Known |= Known2;
3672 break;
3673 case ISD::XOR:
3674 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3675 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3676
3677 Known ^= Known2;
3678 break;
3679 case ISD::MUL: {
3680 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3681 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3682 bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1);
3683 // TODO: SelfMultiply can be poison, but not undef.
3684 if (SelfMultiply)
3685 SelfMultiply &= isGuaranteedNotToBeUndefOrPoison(
3686 Op.getOperand(0), DemandedElts, UndefPoisonKind::UndefOrPoison,
3687 Depth + 1);
3688 Known = KnownBits::mul(Known, Known2, SelfMultiply);
3689
3690 // If the multiplication is known not to overflow, the product of a number
3691 // with itself is non-negative. Only do this if we didn't already computed
3692 // the opposite value for the sign bit.
3693 if (Op->getFlags().hasNoSignedWrap() &&
3694 Op.getOperand(0) == Op.getOperand(1) &&
3695 !Known.isNegative())
3696 Known.makeNonNegative();
3697 break;
3698 }
3699 case ISD::MULHU: {
3700 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3701 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3702 Known = KnownBits::mulhu(Known, Known2);
3703 break;
3704 }
3705 case ISD::MULHS: {
3706 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3707 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3708 Known = KnownBits::mulhs(Known, Known2);
3709 break;
3710 }
3711 case ISD::ABDU: {
3712 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3713 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3714 Known = KnownBits::abdu(Known, Known2);
3715 break;
3716 }
3717 case ISD::ABDS: {
3718 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3719 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3720 Known = KnownBits::abds(Known, Known2);
3721 unsigned SignBits1 =
3722 ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
3723 if (SignBits1 == 1)
3724 break;
3725 unsigned SignBits0 =
3726 ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3727 Known.Zero.setHighBits(std::min(SignBits0, SignBits1) - 1);
3728 break;
3729 }
3730 case ISD::UMUL_LOHI: {
3731 assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3732 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3733 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3734 bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1);
3735 if (Op.getResNo() == 0)
3736 Known = KnownBits::mul(Known, Known2, SelfMultiply);
3737 else
3738 Known = KnownBits::mulhu(Known, Known2);
3739 break;
3740 }
3741 case ISD::SMUL_LOHI: {
3742 assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3743 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3744 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3745 bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1);
3746 if (Op.getResNo() == 0)
3747 Known = KnownBits::mul(Known, Known2, SelfMultiply);
3748 else
3749 Known = KnownBits::mulhs(Known, Known2);
3750 break;
3751 }
3752 case ISD::AVGFLOORU: {
3753 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3754 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3755 Known = KnownBits::avgFloorU(Known, Known2);
3756 break;
3757 }
3758 case ISD::AVGCEILU: {
3759 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3760 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3761 Known = KnownBits::avgCeilU(Known, Known2);
3762 break;
3763 }
3764 case ISD::AVGFLOORS: {
3765 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3766 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3767 Known = KnownBits::avgFloorS(Known, Known2);
3768 break;
3769 }
3770 case ISD::AVGCEILS: {
3771 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3772 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3773 Known = KnownBits::avgCeilS(Known, Known2);
3774 break;
3775 }
3776 case ISD::SELECT:
3777 case ISD::VSELECT:
3778 Known = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
3779 // If we don't know any bits, early out.
3780 if (Known.isUnknown())
3781 break;
3782 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth+1);
3783
3784 // Only known if known in both the LHS and RHS.
3785 Known = Known.intersectWith(Known2);
3786 break;
3787 case ISD::SELECT_CC:
3788 Known = computeKnownBits(Op.getOperand(3), DemandedElts, Depth+1);
3789 // If we don't know any bits, early out.
3790 if (Known.isUnknown())
3791 break;
3792 Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
3793
3794 // Only known if known in both the LHS and RHS.
3795 Known = Known.intersectWith(Known2);
3796 break;
3797 case ISD::SMULO:
3798 case ISD::UMULO:
3799 if (Op.getResNo() != 1)
3800 break;
3801 // The boolean result conforms to getBooleanContents.
3802 // If we know the result of a setcc has the top bits zero, use this info.
3803 // We know that we have an integer-based boolean since these operations
3804 // are only available for integer.
3805 if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
3807 BitWidth > 1)
3808 Known.Zero.setBitsFrom(1);
3809 break;
3810 case ISD::SETCC:
3811 case ISD::SETCCCARRY:
3812 case ISD::STRICT_FSETCC:
3813 case ISD::STRICT_FSETCCS: {
3814 unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
3815 // If we know the result of a setcc has the top bits zero, use this info.
3816 if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
3818 BitWidth > 1)
3819 Known.Zero.setBitsFrom(1);
3820 break;
3821 }
3822 case ISD::SHL: {
3823 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3824 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3825
3826 bool NUW = Op->getFlags().hasNoUnsignedWrap();
3827 bool NSW = Op->getFlags().hasNoSignedWrap();
3828
3829 bool ShAmtNonZero = Known2.isNonZero();
3830
3831 Known = KnownBits::shl(Known, Known2, NUW, NSW, ShAmtNonZero);
3832
3833 // Minimum shift low bits are known zero.
3834 if (std::optional<unsigned> ShMinAmt =
3835 getValidMinimumShiftAmount(Op, DemandedElts, Depth + 1))
3836 Known.Zero.setLowBits(*ShMinAmt);
3837 break;
3838 }
3839 case ISD::SRL:
3840 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3841 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3842 Known = KnownBits::lshr(Known, Known2, /*ShAmtNonZero=*/false,
3843 Op->getFlags().hasExact());
3844
3845 // Minimum shift high bits are known zero.
3846 if (std::optional<unsigned> ShMinAmt =
3847 getValidMinimumShiftAmount(Op, DemandedElts, Depth + 1))
3848 Known.Zero.setHighBits(*ShMinAmt);
3849 break;
3850 case ISD::SRA:
3851 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3852 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3853 Known = KnownBits::ashr(Known, Known2, /*ShAmtNonZero=*/false,
3854 Op->getFlags().hasExact());
3855 break;
3856 case ISD::ROTL:
3857 case ISD::ROTR:
3858 if (ConstantSDNode *C =
3859 isConstOrConstSplat(Op.getOperand(1), DemandedElts)) {
3860 unsigned Amt = C->getAPIntValue().urem(BitWidth);
3861
3862 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3863
3864 // Canonicalize to ROTR.
3865 if (Opcode == ISD::ROTL && Amt != 0)
3866 Amt = BitWidth - Amt;
3867
3868 Known.Zero = Known.Zero.rotr(Amt);
3869 Known.One = Known.One.rotr(Amt);
3870 }
3871 break;
3872 case ISD::FSHL:
3873 case ISD::FSHR:
3874 if (ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(2), DemandedElts)) {
3875 unsigned Amt = C->getAPIntValue().urem(BitWidth);
3876
3877 // For fshl, 0-shift returns the 1st arg.
3878 // For fshr, 0-shift returns the 2nd arg.
3879 if (Amt == 0) {
3880 Known = computeKnownBits(Op.getOperand(Opcode == ISD::FSHL ? 0 : 1),
3881 DemandedElts, Depth + 1);
3882 break;
3883 }
3884
3885 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
3886 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
3887 const APInt ShAmt(BitWidth, Amt);
3888 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3889 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3890 Known = Opcode == ISD::FSHL ? KnownBits::fshl(Known, Known2, ShAmt)
3891 : KnownBits::fshr(Known, Known2, ShAmt);
3892 }
3893 break;
3894 case ISD::SHL_PARTS:
3895 case ISD::SRA_PARTS:
3896 case ISD::SRL_PARTS: {
3897 assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3898
3899 // Collect lo/hi source values and concatenate.
3900 unsigned LoBits = Op.getOperand(0).getScalarValueSizeInBits();
3901 unsigned HiBits = Op.getOperand(1).getScalarValueSizeInBits();
3902 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3903 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3904 Known = Known2.concat(Known);
3905
3906 // Collect shift amount.
3907 Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1);
3908
3909 if (Opcode == ISD::SHL_PARTS)
3910 Known = KnownBits::shl(Known, Known2);
3911 else if (Opcode == ISD::SRA_PARTS)
3912 Known = KnownBits::ashr(Known, Known2);
3913 else // if (Opcode == ISD::SRL_PARTS)
3914 Known = KnownBits::lshr(Known, Known2);
3915
3916 // TODO: Minimum shift low/high bits are known zero.
3917
3918 if (Op.getResNo() == 0)
3919 Known = Known.extractBits(LoBits, 0);
3920 else
3921 Known = Known.extractBits(HiBits, LoBits);
3922 break;
3923 }
3925 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3926 EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3927 Known = Known.sextInReg(EVT.getScalarSizeInBits());
3928 break;
3929 }
3930 case ISD::CTTZ:
3931 case ISD::CTTZ_ZERO_POISON: {
3932 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3933 // If we have a known 1, its position is our upper bound.
3934 unsigned PossibleTZ = Known2.countMaxTrailingZeros();
3935 unsigned LowBits = llvm::bit_width(PossibleTZ);
3936 Known.Zero.setBitsFrom(LowBits);
3937 break;
3938 }
3939 case ISD::CTLZ:
3940 case ISD::CTLZ_ZERO_POISON: {
3941 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3942 // If we have a known 1, its position is our upper bound.
3943 unsigned PossibleLZ = Known2.countMaxLeadingZeros();
3944 unsigned LowBits = llvm::bit_width(PossibleLZ);
3945 Known.Zero.setBitsFrom(LowBits);
3946 break;
3947 }
3948 case ISD::CTLS: {
3949 unsigned MinRedundantSignBits =
3950 ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1) - 1;
3951 ConstantRange Range(APInt(BitWidth, MinRedundantSignBits),
3953 Known = Range.toKnownBits();
3954 break;
3955 }
3956 case ISD::CTPOP: {
3957 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3958 // If we know some of the bits are zero, they can't be one.
3959 unsigned PossibleOnes = Known2.countMaxPopulation();
3960 Known.Zero.setBitsFrom(llvm::bit_width(PossibleOnes));
3961 break;
3962 }
3963 case ISD::PARITY: {
3964 // Parity returns 0 everywhere but the LSB.
3965 Known.Zero.setBitsFrom(1);
3966 break;
3967 }
3968 case ISD::PDEP: {
3969 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3970 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3971 Known = KnownBits::pdep(Known2, Known);
3972 break;
3973 }
3974 case ISD::PEXT: {
3975 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3976 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3977 Known = KnownBits::pext(Known2, Known);
3978 break;
3979 }
3980 case ISD::CLMUL: {
3981 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3982 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3983 Known = KnownBits::clmul(Known, Known2);
3984 break;
3985 }
3986 case ISD::MGATHER:
3987 case ISD::MLOAD: {
3988 ISD::LoadExtType ETy =
3989 (Opcode == ISD::MGATHER)
3990 ? cast<MaskedGatherSDNode>(Op)->getExtensionType()
3991 : cast<MaskedLoadSDNode>(Op)->getExtensionType();
3992 if (ETy == ISD::ZEXTLOAD) {
3993 EVT MemVT = cast<MemSDNode>(Op)->getMemoryVT();
3994 KnownBits Known0(MemVT.getScalarSizeInBits());
3995 return Known0.zext(BitWidth);
3996 }
3997 break;
3998 }
3999 case ISD::LOAD: {
4001 const Constant *Cst = TLI->getTargetConstantFromLoad(LD);
4002 if (ISD::isNON_EXTLoad(LD) && Cst) {
4003 // Determine any common known bits from the loaded constant pool value.
4004 Type *CstTy = Cst->getType();
4005 if ((NumElts * BitWidth) == CstTy->getPrimitiveSizeInBits() &&
4006 !Op.getValueType().isScalableVector()) {
4007 // If its a vector splat, then we can (quickly) reuse the scalar path.
4008 // NOTE: We assume all elements match and none are UNDEF.
4009 if (CstTy->isVectorTy()) {
4010 if (const Constant *Splat = Cst->getSplatValue()) {
4011 Cst = Splat;
4012 CstTy = Cst->getType();
4013 }
4014 }
4015 // TODO - do we need to handle different bitwidths?
4016 if (CstTy->isVectorTy() && BitWidth == CstTy->getScalarSizeInBits()) {
4017 // Iterate across all vector elements finding common known bits.
4018 Known.setAllConflict();
4019 for (unsigned i = 0; i != NumElts; ++i) {
4020 if (!DemandedElts[i])
4021 continue;
4022 if (Constant *Elt = Cst->getAggregateElement(i)) {
4023 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
4024 const APInt &Value = CInt->getValue();
4025 Known.One &= Value;
4026 Known.Zero &= ~Value;
4027 continue;
4028 }
4029 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
4030 APInt Value = CFP->getValueAPF().bitcastToAPInt();
4031 Known.One &= Value;
4032 Known.Zero &= ~Value;
4033 continue;
4034 }
4035 }
4036 Known.One.clearAllBits();
4037 Known.Zero.clearAllBits();
4038 break;
4039 }
4040 } else if (BitWidth == CstTy->getPrimitiveSizeInBits()) {
4041 if (auto *CInt = dyn_cast<ConstantInt>(Cst)) {
4042 Known = KnownBits::makeConstant(CInt->getValue());
4043 } else if (auto *CFP = dyn_cast<ConstantFP>(Cst)) {
4044 Known =
4045 KnownBits::makeConstant(CFP->getValueAPF().bitcastToAPInt());
4046 }
4047 }
4048 }
4049 } else if (Op.getResNo() == 0) {
4050 unsigned ScalarMemorySize = LD->getMemoryVT().getScalarSizeInBits();
4051 KnownBits KnownScalarMemory(ScalarMemorySize);
4052 if (const MDNode *MD = LD->getRanges())
4053 computeKnownBitsFromRangeMetadata(*MD, KnownScalarMemory);
4054
4055 // Extend the Known bits from memory to the size of the scalar result.
4056 if (ISD::isZEXTLoad(Op.getNode()))
4057 Known = KnownScalarMemory.zext(BitWidth);
4058 else if (ISD::isSEXTLoad(Op.getNode()))
4059 Known = KnownScalarMemory.sext(BitWidth);
4060 else if (ISD::isEXTLoad(Op.getNode()))
4061 Known = KnownScalarMemory.anyext(BitWidth);
4062 else
4063 Known = KnownScalarMemory;
4064 assert(Known.getBitWidth() == BitWidth);
4065 return Known;
4066 }
4067 break;
4068 }
4070 if (Op.getValueType().isScalableVector())
4071 break;
4072 EVT InVT = Op.getOperand(0).getValueType();
4073 APInt InDemandedElts = DemandedElts.zext(InVT.getVectorNumElements());
4074 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
4075 Known = Known.zext(BitWidth);
4076 break;
4077 }
4078 case ISD::ZERO_EXTEND: {
4079 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4080 Known = Known.zext(BitWidth);
4081 break;
4082 }
4084 if (Op.getValueType().isScalableVector())
4085 break;
4086 EVT InVT = Op.getOperand(0).getValueType();
4087 APInt InDemandedElts = DemandedElts.zext(InVT.getVectorNumElements());
4088 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
4089 // If the sign bit is known to be zero or one, then sext will extend
4090 // it to the top bits, else it will just zext.
4091 Known = Known.sext(BitWidth);
4092 break;
4093 }
4094 case ISD::SIGN_EXTEND: {
4095 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4096 // If the sign bit is known to be zero or one, then sext will extend
4097 // it to the top bits, else it will just zext.
4098 Known = Known.sext(BitWidth);
4099 break;
4100 }
4102 if (Op.getValueType().isScalableVector())
4103 break;
4104 EVT InVT = Op.getOperand(0).getValueType();
4105 APInt InDemandedElts = DemandedElts.zext(InVT.getVectorNumElements());
4106 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
4107 Known = Known.anyext(BitWidth);
4108 break;
4109 }
4110 case ISD::ANY_EXTEND: {
4111 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4112 Known = Known.anyext(BitWidth);
4113 break;
4114 }
4115 case ISD::TRUNCATE: {
4116 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4117 Known = Known.trunc(BitWidth);
4118 break;
4119 }
4120 case ISD::TRUNCATE_SSAT_S: {
4121 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4122 Known = Known.truncSSat(BitWidth);
4123 break;
4124 }
4125 case ISD::TRUNCATE_SSAT_U: {
4126 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4127 Known = Known.truncSSatU(BitWidth);
4128 break;
4129 }
4130 case ISD::TRUNCATE_USAT_U: {
4131 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4132 Known = Known.truncUSat(BitWidth);
4133 break;
4134 }
4135 case ISD::AssertZext: {
4136 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
4138 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4139 Known.Zero |= (~InMask);
4140 Known.One &= (~Known.Zero);
4141 break;
4142 }
4143 case ISD::AssertAlign: {
4144 unsigned LogOfAlign = Log2(cast<AssertAlignSDNode>(Op)->getAlign());
4145 assert(LogOfAlign != 0);
4146
4147 // TODO: Should use maximum with source
4148 // If a node is guaranteed to be aligned, set low zero bits accordingly as
4149 // well as clearing one bits.
4150 Known.Zero.setLowBits(LogOfAlign);
4151 Known.One.clearLowBits(LogOfAlign);
4152 break;
4153 }
4154 case ISD::AssertNoFPClass: {
4155 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4156
4157 FPClassTest NoFPClass =
4158 static_cast<FPClassTest>(Op.getConstantOperandVal(1));
4159 const FPClassTest NegativeTestMask = fcNan | fcNegative;
4160 if ((NoFPClass & NegativeTestMask) == NegativeTestMask) {
4161 // Cannot be negative.
4162 Known.makeNonNegative();
4163 }
4164
4165 const FPClassTest PositiveTestMask = fcNan | fcPositive;
4166 if ((NoFPClass & PositiveTestMask) == PositiveTestMask) {
4167 // Cannot be positive.
4168 Known.makeNegative();
4169 }
4170
4171 break;
4172 }
4173 case ISD::FABS:
4174 // fabs clears the sign bit
4175 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4176 Known.makeNonNegative();
4177 break;
4178 case ISD::FGETSIGN:
4179 // All bits are zero except the low bit.
4180 Known.Zero.setBitsFrom(1);
4181 break;
4182 case ISD::ADD: {
4183 SDNodeFlags Flags = Op.getNode()->getFlags();
4184 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4185 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4186 bool SelfAdd = Op.getOperand(0) == Op.getOperand(1) &&
4188 Op.getOperand(0), DemandedElts,
4190 Known = KnownBits::add(Known, Known2, Flags.hasNoSignedWrap(),
4191 Flags.hasNoUnsignedWrap(), SelfAdd);
4192 break;
4193 }
4194 case ISD::SUB: {
4195 SDNodeFlags Flags = Op.getNode()->getFlags();
4196 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4197 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4198 Known = KnownBits::sub(Known, Known2, Flags.hasNoSignedWrap(),
4199 Flags.hasNoUnsignedWrap());
4200 break;
4201 }
4202 case ISD::USUBO:
4203 case ISD::SSUBO:
4204 case ISD::USUBO_CARRY:
4205 case ISD::SSUBO_CARRY:
4206 if (Op.getResNo() == 1) {
4207 // If we know the result of a setcc has the top bits zero, use this info.
4208 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
4210 BitWidth > 1)
4211 Known.Zero.setBitsFrom(1);
4212 break;
4213 }
4214 [[fallthrough]];
4215 case ISD::SUBC: {
4216 assert(Op.getResNo() == 0 &&
4217 "We only compute knownbits for the difference here.");
4218
4219 // With USUBO_CARRY and SSUBO_CARRY a borrow bit may be added in.
4220 KnownBits Borrow(1);
4221 if (Opcode == ISD::USUBO_CARRY || Opcode == ISD::SSUBO_CARRY) {
4222 Borrow = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1);
4223 // Borrow has bit width 1
4224 Borrow = Borrow.trunc(1);
4225 } else {
4226 Borrow.setAllZero();
4227 }
4228
4229 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4230 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4231 Known = KnownBits::computeForSubBorrow(Known, Known2, Borrow);
4232 break;
4233 }
4234 case ISD::UADDO:
4235 case ISD::SADDO:
4236 case ISD::UADDO_CARRY:
4237 case ISD::SADDO_CARRY:
4238 if (Op.getResNo() == 1) {
4239 // If we know the result of a setcc has the top bits zero, use this info.
4240 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
4242 BitWidth > 1)
4243 Known.Zero.setBitsFrom(1);
4244 break;
4245 }
4246 [[fallthrough]];
4247 case ISD::ADDC:
4248 case ISD::ADDE: {
4249 assert(Op.getResNo() == 0 && "We only compute knownbits for the sum here.");
4250
4251 // With ADDE and UADDO_CARRY, a carry bit may be added in.
4252 KnownBits Carry(1);
4253 if (Opcode == ISD::ADDE)
4254 // Can't track carry from glue, set carry to unknown.
4255 Carry.resetAll();
4256 else if (Opcode == ISD::UADDO_CARRY || Opcode == ISD::SADDO_CARRY) {
4257 Carry = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1);
4258 // Carry has bit width 1
4259 Carry = Carry.trunc(1);
4260 } else {
4261 Carry.setAllZero();
4262 }
4263
4264 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4265 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4266 Known = KnownBits::computeForAddCarry(Known, Known2, Carry);
4267 break;
4268 }
4269 case ISD::UDIV: {
4270 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4271 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4272 Known = KnownBits::udiv(Known, Known2, Op->getFlags().hasExact());
4273 break;
4274 }
4275 case ISD::SDIV: {
4276 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4277 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4278 Known = KnownBits::sdiv(Known, Known2, Op->getFlags().hasExact());
4279 break;
4280 }
4281 case ISD::SREM: {
4282 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4283 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4284 Known = KnownBits::srem(Known, Known2);
4285 break;
4286 }
4287 case ISD::UREM: {
4288 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4289 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4290 Known = KnownBits::urem(Known, Known2);
4291 break;
4292 }
4293 case ISD::EXTRACT_ELEMENT: {
4294 Known = computeKnownBits(Op.getOperand(0), Depth+1);
4295 const unsigned Index = Op.getConstantOperandVal(1);
4296 const unsigned EltBitWidth = Op.getValueSizeInBits();
4297
4298 // Remove low part of known bits mask
4299 Known.Zero = Known.Zero.getHiBits(Known.getBitWidth() - Index * EltBitWidth);
4300 Known.One = Known.One.getHiBits(Known.getBitWidth() - Index * EltBitWidth);
4301
4302 // Remove high part of known bit mask
4303 Known = Known.trunc(EltBitWidth);
4304 break;
4305 }
4307 SDValue InVec = Op.getOperand(0);
4308 SDValue EltNo = Op.getOperand(1);
4309 EVT VecVT = InVec.getValueType();
4310 // computeKnownBits not yet implemented for scalable vectors.
4311 if (VecVT.isScalableVector())
4312 break;
4313 const unsigned EltBitWidth = VecVT.getScalarSizeInBits();
4314 const unsigned NumSrcElts = VecVT.getVectorNumElements();
4315
4316 // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know
4317 // anything about the extended bits.
4318 if (BitWidth > EltBitWidth)
4319 Known = Known.trunc(EltBitWidth);
4320
4321 // If we know the element index, just demand that vector element, else for
4322 // an unknown element index, ignore DemandedElts and demand them all.
4323 APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
4324 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
4325 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
4326 DemandedSrcElts =
4327 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
4328
4329 Known = computeKnownBits(InVec, DemandedSrcElts, Depth + 1);
4330 if (BitWidth > EltBitWidth)
4331 Known = Known.anyext(BitWidth);
4332 break;
4333 }
4335 if (Op.getValueType().isScalableVector())
4336 break;
4337
4338 // If we know the element index, split the demand between the
4339 // source vector and the inserted element, otherwise assume we need
4340 // the original demanded vector elements and the value.
4341 SDValue InVec = Op.getOperand(0);
4342 SDValue InVal = Op.getOperand(1);
4343 SDValue EltNo = Op.getOperand(2);
4344 bool DemandedVal = true;
4345 APInt DemandedVecElts = DemandedElts;
4346 auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
4347 if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
4348 unsigned EltIdx = CEltNo->getZExtValue();
4349 DemandedVal = !!DemandedElts[EltIdx];
4350 DemandedVecElts.clearBit(EltIdx);
4351 }
4352 Known.setAllConflict();
4353 if (DemandedVal) {
4354 Known2 = computeKnownBits(InVal, Depth + 1);
4355 Known = Known.intersectWith(Known2.zextOrTrunc(BitWidth));
4356 }
4357 if (!!DemandedVecElts) {
4358 Known2 = computeKnownBits(InVec, DemandedVecElts, Depth + 1);
4359 Known = Known.intersectWith(Known2);
4360 }
4361 break;
4362 }
4363 case ISD::BITREVERSE: {
4364 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4365 Known = Known2.reverseBits();
4366 break;
4367 }
4368 case ISD::BSWAP: {
4369 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4370 Known = Known2.byteSwap();
4371 break;
4372 }
4373 case ISD::ABS:
4374 case ISD::ABS_MIN_POISON: {
4375 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4376 Known = Known2.abs();
4377 Known.Zero.setHighBits(
4378 ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1) - 1);
4379 break;
4380 }
4381 case ISD::USUBSAT: {
4382 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4383 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4384 Known = KnownBits::usub_sat(Known, Known2);
4385 break;
4386 }
4387 case ISD::UMIN: {
4388 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4389 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4390 Known = KnownBits::umin(Known, Known2);
4391 break;
4392 }
4393 case ISD::UMAX: {
4394 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4395 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4396 Known = KnownBits::umax(Known, Known2);
4397 break;
4398 }
4399 case ISD::SMIN:
4400 case ISD::SMAX: {
4401 // If we have a clamp pattern, we know that the number of sign bits will be
4402 // the minimum of the clamp min/max range.
4403 bool IsMax = (Opcode == ISD::SMAX);
4404 ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
4405 if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
4406 if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
4407 CstHigh =
4408 isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
4409 if (CstLow && CstHigh) {
4410 if (!IsMax)
4411 std::swap(CstLow, CstHigh);
4412
4413 const APInt &ValueLow = CstLow->getAPIntValue();
4414 const APInt &ValueHigh = CstHigh->getAPIntValue();
4415 if (ValueLow.sle(ValueHigh)) {
4416 unsigned LowSignBits = ValueLow.getNumSignBits();
4417 unsigned HighSignBits = ValueHigh.getNumSignBits();
4418 unsigned MinSignBits = std::min(LowSignBits, HighSignBits);
4419 if (ValueLow.isNegative() && ValueHigh.isNegative()) {
4420 Known.One.setHighBits(MinSignBits);
4421 break;
4422 }
4423 if (ValueLow.isNonNegative() && ValueHigh.isNonNegative()) {
4424 Known.Zero.setHighBits(MinSignBits);
4425 break;
4426 }
4427 }
4428 }
4429
4430 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4431 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4432 if (IsMax)
4433 Known = KnownBits::smax(Known, Known2);
4434 else
4435 Known = KnownBits::smin(Known, Known2);
4436
4437 // For SMAX, if CstLow is non-negative we know the result will be
4438 // non-negative and thus all sign bits are 0.
4439 // TODO: There's an equivalent of this for smin with negative constant for
4440 // known ones.
4441 if (IsMax && CstLow) {
4442 const APInt &ValueLow = CstLow->getAPIntValue();
4443 if (ValueLow.isNonNegative()) {
4444 unsigned SignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
4445 Known.Zero.setHighBits(std::min(SignBits, ValueLow.getNumSignBits()));
4446 }
4447 }
4448
4449 break;
4450 }
4451 case ISD::UINT_TO_FP: {
4452 Known.makeNonNegative();
4453 break;
4454 }
4455 case ISD::SINT_TO_FP: {
4456 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4457 if (Known2.isNonNegative())
4458 Known.makeNonNegative();
4459 else if (Known2.isNegative())
4460 Known.makeNegative();
4461 break;
4462 }
4463 case ISD::FP_TO_UINT_SAT: {
4464 // FP_TO_UINT_SAT produces an unsigned value that fits in the saturating VT.
4465 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
4467 break;
4468 }
4469 case ISD::ATOMIC_LOAD: {
4470 // If we are looking at the loaded value.
4471 if (Op.getResNo() == 0) {
4472 auto *AT = cast<AtomicSDNode>(Op);
4473 unsigned ScalarMemorySize = AT->getMemoryVT().getScalarSizeInBits();
4474 KnownBits KnownScalarMemory(ScalarMemorySize);
4475 if (const MDNode *MD = AT->getRanges())
4476 computeKnownBitsFromRangeMetadata(*MD, KnownScalarMemory);
4477
4478 switch (AT->getExtensionType()) {
4479 case ISD::ZEXTLOAD:
4480 Known = KnownScalarMemory.zext(BitWidth);
4481 break;
4482 case ISD::SEXTLOAD:
4483 Known = KnownScalarMemory.sext(BitWidth);
4484 break;
4485 case ISD::EXTLOAD:
4486 switch (TLI->getExtendForAtomicOps()) {
4487 case ISD::ZERO_EXTEND:
4488 Known = KnownScalarMemory.zext(BitWidth);
4489 break;
4490 case ISD::SIGN_EXTEND:
4491 Known = KnownScalarMemory.sext(BitWidth);
4492 break;
4493 default:
4494 Known = KnownScalarMemory.anyext(BitWidth);
4495 break;
4496 }
4497 break;
4498 case ISD::NON_EXTLOAD:
4499 Known = KnownScalarMemory;
4500 break;
4501 }
4502 assert(Known.getBitWidth() == BitWidth);
4503 }
4504 break;
4505 }
4507 if (Op.getResNo() == 1) {
4508 // The boolean result conforms to getBooleanContents.
4509 // If we know the result of a setcc has the top bits zero, use this info.
4510 // We know that we have an integer-based boolean since these operations
4511 // are only available for integer.
4512 if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
4514 BitWidth > 1)
4515 Known.Zero.setBitsFrom(1);
4516 break;
4517 }
4518 [[fallthrough]];
4520 case ISD::ATOMIC_SWAP:
4531 case ISD::ATOMIC_LOAD_UMAX: {
4532 // If we are looking at the loaded value.
4533 if (Op.getResNo() == 0) {
4534 auto *AT = cast<AtomicSDNode>(Op);
4535 unsigned MemBits = AT->getMemoryVT().getScalarSizeInBits();
4536
4537 if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND)
4538 Known.Zero.setBitsFrom(MemBits);
4539 }
4540 break;
4541 }
4542 case ISD::FrameIndex:
4543 case ISD::TargetFrameIndex: {
4544 const MachineFunction &MF = getMachineFunction();
4545 int FrameIdx = cast<FrameIndexSDNode>(Op)->getIndex();
4546 TLI->computeKnownBitsForStackObjectPointer(
4547 Known, MF, MF.getFrameInfo().getObjectAlign(FrameIdx));
4548 break;
4549 }
4550
4551 default:
4552 if (Opcode < ISD::BUILTIN_OP_END)
4553 break;
4554 [[fallthrough]];
4558 // Allow the target to implement this method for its nodes.
4559 TLI->computeKnownBitsForTargetNode(Op, Known, DemandedElts, *this, Depth);
4560 break;
4561 }
4562
4563 return Known;
4564}
4565
4566/// Convert ConstantRange OverflowResult into SelectionDAG::OverflowKind.
4579
4582 // X + 0 never overflow
4583 if (isNullConstant(N1))
4584 return OFK_Never;
4585
4586 // If both operands each have at least two sign bits, the addition
4587 // cannot overflow.
4588 if (ComputeNumSignBits(N0) > 1 && ComputeNumSignBits(N1) > 1)
4589 return OFK_Never;
4590
4591 // TODO: Add ConstantRange::signedAddMayOverflow handling.
4592 return OFK_Sometime;
4593}
4594
4597 // X + 0 never overflow
4598 if (isNullConstant(N1))
4599 return OFK_Never;
4600
4601 // mulhi + 1 never overflow
4602 KnownBits N1Known = computeKnownBits(N1);
4603 if (N0.getOpcode() == ISD::UMUL_LOHI && N0.getResNo() == 1 &&
4604 N1Known.getMaxValue().ult(2))
4605 return OFK_Never;
4606
4607 KnownBits N0Known = computeKnownBits(N0);
4608 if (N1.getOpcode() == ISD::UMUL_LOHI && N1.getResNo() == 1 &&
4609 N0Known.getMaxValue().ult(2))
4610 return OFK_Never;
4611
4612 // Fallback to ConstantRange::unsignedAddMayOverflow handling.
4613 ConstantRange N0Range = ConstantRange::fromKnownBits(N0Known, false);
4614 ConstantRange N1Range = ConstantRange::fromKnownBits(N1Known, false);
4615 return mapOverflowResult(N0Range.unsignedAddMayOverflow(N1Range));
4616}
4617
4620 // X - 0 never overflow
4621 if (isNullConstant(N1))
4622 return OFK_Never;
4623
4624 // If both operands each have at least two sign bits, the subtraction
4625 // cannot overflow.
4626 if (ComputeNumSignBits(N0) > 1 && ComputeNumSignBits(N1) > 1)
4627 return OFK_Never;
4628
4629 KnownBits N0Known = computeKnownBits(N0);
4630 KnownBits N1Known = computeKnownBits(N1);
4631 ConstantRange N0Range = ConstantRange::fromKnownBits(N0Known, true);
4632 ConstantRange N1Range = ConstantRange::fromKnownBits(N1Known, true);
4633 return mapOverflowResult(N0Range.signedSubMayOverflow(N1Range));
4634}
4635
4638 // X - 0 never overflow
4639 if (isNullConstant(N1))
4640 return OFK_Never;
4641
4642 ConstantRange N0Range =
4643 computeConstantRangeIncludingKnownBits(N0, /*ForSigned=*/false);
4644 ConstantRange N1Range =
4645 computeConstantRangeIncludingKnownBits(N1, /*ForSigned=*/false);
4646 return mapOverflowResult(N0Range.unsignedSubMayOverflow(N1Range));
4647}
4648
4651 // X * 0 and X * 1 never overflow.
4652 if (isNullConstant(N1) || isOneConstant(N1))
4653 return OFK_Never;
4654
4657 return mapOverflowResult(N0Range.unsignedMulMayOverflow(N1Range));
4658}
4659
4662 // X * 0 and X * 1 never overflow.
4663 if (isNullConstant(N1) || isOneConstant(N1))
4664 return OFK_Never;
4665
4666 // Get the size of the result.
4667 unsigned BitWidth = N0.getScalarValueSizeInBits();
4668
4669 // Sum of the sign bits.
4670 unsigned SignBits = ComputeNumSignBits(N0) + ComputeNumSignBits(N1);
4671
4672 // If we have enough sign bits, then there's no overflow.
4673 if (SignBits > BitWidth + 1)
4674 return OFK_Never;
4675
4676 if (SignBits == BitWidth + 1) {
4677 // The overflow occurs when the true multiplication of the
4678 // the operands is the minimum negative number.
4679 KnownBits N0Known = computeKnownBits(N0);
4680 KnownBits N1Known = computeKnownBits(N1);
4681 // If one of the operands is non-negative, then there's no
4682 // overflow.
4683 if (N0Known.isNonNegative() || N1Known.isNonNegative())
4684 return OFK_Never;
4685 }
4686
4687 return OFK_Sometime;
4688}
4689
4691 unsigned Depth) const {
4692 APInt DemandedElts = getDemandAllEltsMask(Op);
4693 return computeConstantRange(Op, DemandedElts, ForSigned, Depth);
4694}
4695
4697 const APInt &DemandedElts,
4698 bool ForSigned,
4699 unsigned Depth) const {
4700 EVT VT = Op.getValueType();
4701 unsigned BitWidth = VT.getScalarSizeInBits();
4702
4703 if (Depth >= MaxRecursionDepth)
4704 return ConstantRange::getFull(BitWidth);
4705
4706 if (ConstantSDNode *C = isConstOrConstSplat(Op, DemandedElts))
4707 return ConstantRange(C->getAPIntValue());
4708
4709 unsigned Opcode = Op.getOpcode();
4710 switch (Opcode) {
4711 case ISD::VSCALE: {
4713 const APInt &Multiplier = Op.getConstantOperandAPInt(0);
4714 return getVScaleRange(&F, BitWidth).multiply(Multiplier);
4715 }
4716 default:
4717 break;
4718 }
4719
4720 return ConstantRange::getFull(BitWidth);
4721}
4722
4725 unsigned Depth) const {
4726 APInt DemandedElts = getDemandAllEltsMask(Op);
4727 return computeConstantRangeIncludingKnownBits(Op, DemandedElts, ForSigned,
4728 Depth);
4729}
4730
4732 SDValue Op, const APInt &DemandedElts, bool ForSigned,
4733 unsigned Depth) const {
4734 KnownBits Known = computeKnownBits(Op, DemandedElts, Depth);
4736 ConstantRange CR2 = computeConstantRange(Op, DemandedElts, ForSigned, Depth);
4739 return CR1.intersectWith(CR2, RangeType);
4740}
4741
4743 unsigned Depth) const {
4744 APInt DemandedElts = getDemandAllEltsMask(Val);
4745 return isKnownToBeAPowerOfTwo(Val, DemandedElts, OrZero, Depth);
4746}
4747
4749 const APInt &DemandedElts,
4750 bool OrZero, unsigned Depth) const {
4751 if (Depth >= MaxRecursionDepth)
4752 return false; // Limit search depth.
4753
4754 EVT OpVT = Val.getValueType();
4755 unsigned BitWidth = OpVT.getScalarSizeInBits();
4756 [[maybe_unused]] unsigned NumElts = DemandedElts.getBitWidth();
4757 assert((!OpVT.isScalableVector() || NumElts == 1) &&
4758 "DemandedElts for scalable vectors must be 1 to represent all lanes");
4759 assert(
4760 (!OpVT.isFixedLengthVector() || NumElts == OpVT.getVectorNumElements()) &&
4761 "Unexpected vector size");
4762
4763 auto IsPowerOfTwoOrZero = [BitWidth, OrZero](const ConstantSDNode *C) {
4764 APInt V = C->getAPIntValue().zextOrTrunc(BitWidth);
4765 return (OrZero && V.isZero()) || V.isPowerOf2();
4766 };
4767
4768 // Is the constant a known power of 2 or zero?
4769 if (ISD::matchUnaryPredicate(Val, IsPowerOfTwoOrZero))
4770 return true;
4771
4772 switch (Val.getOpcode()) {
4773 case ISD::BUILD_VECTOR:
4774 // Are all operands of a build vector constant powers of two or zero?
4775 if (all_of(enumerate(Val->ops()), [&](auto P) {
4776 auto *C = dyn_cast<ConstantSDNode>(P.value());
4777 return !DemandedElts[P.index()] || (C && IsPowerOfTwoOrZero(C));
4778 }))
4779 return true;
4780 break;
4781
4782 case ISD::SPLAT_VECTOR:
4783 // Is the operand of a splat vector a constant power of two?
4784 if (auto *C = dyn_cast<ConstantSDNode>(Val->getOperand(0)))
4785 if (IsPowerOfTwoOrZero(C))
4786 return true;
4787 break;
4788
4790 SDValue InVec = Val.getOperand(0);
4791 SDValue EltNo = Val.getOperand(1);
4792 EVT VecVT = InVec.getValueType();
4793
4794 // Skip scalable vectors or implicit extensions.
4795 if (VecVT.isScalableVector() ||
4796 OpVT.getScalarSizeInBits() != VecVT.getScalarSizeInBits())
4797 break;
4798
4799 // If we know the element index, just demand that vector element, else for
4800 // an unknown element index, ignore DemandedElts and demand them all.
4801 const unsigned NumSrcElts = VecVT.getVectorNumElements();
4802 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
4803 APInt DemandedSrcElts =
4804 ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts)
4805 ? APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue())
4806 : APInt::getAllOnes(NumSrcElts);
4807 return isKnownToBeAPowerOfTwo(InVec, DemandedSrcElts, OrZero, Depth + 1);
4808 }
4809
4810 case ISD::AND: {
4811 // Looking for `x & -x` pattern:
4812 // If x == 0:
4813 // x & -x -> 0
4814 // If x != 0:
4815 // x & -x -> non-zero pow2
4816 // so if we find the pattern return whether we know `x` is non-zero.
4817 SDValue X, Z;
4818 if (sd_match(Val, m_And(m_Value(X), m_Neg(m_Deferred(X)))) ||
4819 (sd_match(Val, m_And(m_Value(X), m_Sub(m_Value(Z), m_Deferred(X)))) &&
4820 MaskedVectorIsZero(Z, DemandedElts, Depth + 1)))
4821 return OrZero || isKnownNeverZero(X, DemandedElts, Depth);
4822 break;
4823 }
4824
4825 case ISD::SHL: {
4826 // A left-shift of a constant one will have exactly one bit set because
4827 // shifting the bit off the end is undefined.
4828 auto *C = isConstOrConstSplat(Val.getOperand(0), DemandedElts);
4829 if (C && C->getAPIntValue() == 1)
4830 return true;
4831 return (OrZero || isKnownNeverZero(Val, DemandedElts, Depth)) &&
4832 isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedElts, OrZero,
4833 Depth + 1);
4834 }
4835
4836 case ISD::SRL: {
4837 // A logical right-shift of a constant sign-bit will have exactly
4838 // one bit set.
4839 auto *C = isConstOrConstSplat(Val.getOperand(0), DemandedElts);
4840 if (C && C->getAPIntValue().isSignMask())
4841 return true;
4842 return (OrZero || isKnownNeverZero(Val, DemandedElts, Depth)) &&
4843 isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedElts, OrZero,
4844 Depth + 1);
4845 }
4846
4847 case ISD::TRUNCATE:
4848 return (OrZero || isKnownNeverZero(Val, DemandedElts, Depth)) &&
4849 isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedElts, OrZero,
4850 Depth + 1);
4851
4852 case ISD::ROTL:
4853 case ISD::ROTR:
4854 return isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedElts, OrZero,
4855 Depth + 1);
4856 case ISD::BSWAP:
4857 case ISD::BITREVERSE:
4858 return isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedElts, OrZero,
4859 Depth + 1);
4860
4861 case ISD::SMIN:
4862 case ISD::SMAX:
4863 case ISD::UMIN:
4864 case ISD::UMAX:
4865 return isKnownToBeAPowerOfTwo(Val.getOperand(1), DemandedElts, OrZero,
4866 Depth + 1) &&
4867 isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedElts, OrZero,
4868 Depth + 1);
4869
4870 case ISD::SELECT:
4871 case ISD::VSELECT:
4872 return isKnownToBeAPowerOfTwo(Val.getOperand(2), DemandedElts, OrZero,
4873 Depth + 1) &&
4874 isKnownToBeAPowerOfTwo(Val.getOperand(1), DemandedElts, OrZero,
4875 Depth + 1);
4876
4877 case ISD::ZERO_EXTEND:
4878 return isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedElts, OrZero,
4879 Depth + 1);
4880
4881 case ISD::VSCALE:
4882 // vscale(power-of-two) is a power-of-two
4883 return isKnownToBeAPowerOfTwo(Val.getOperand(0), /*OrZero=*/false,
4884 Depth + 1);
4885
4886 case ISD::VECTOR_SHUFFLE: {
4888 // Demanded elements with undef shuffle mask elements are unknown
4889 // - we cannot guarantee they are a power of two, so return false.
4890 APInt DemandedLHS, DemandedRHS;
4892 assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
4893 if (!getShuffleDemandedElts(NumElts, SVN->getMask(), DemandedElts,
4894 DemandedLHS, DemandedRHS))
4895 return false;
4896
4897 // All demanded elements from LHS must be known power of two.
4898 if (!!DemandedLHS && !isKnownToBeAPowerOfTwo(Val.getOperand(0), DemandedLHS,
4899 OrZero, Depth + 1))
4900 return false;
4901
4902 // All demanded elements from RHS must be known power of two.
4903 if (!!DemandedRHS && !isKnownToBeAPowerOfTwo(Val.getOperand(1), DemandedRHS,
4904 OrZero, Depth + 1))
4905 return false;
4906
4907 return true;
4908 }
4909 }
4910
4911 // More could be done here, though the above checks are enough
4912 // to handle some common cases.
4913 return false;
4914}
4915
4917 if (ConstantFPSDNode *C1 = isConstOrConstSplatFP(Val, true))
4918 return C1->getValueAPF().getExactLog2Abs() >= 0;
4919
4920 if (Val.getOpcode() == ISD::UINT_TO_FP || Val.getOpcode() == ISD::SINT_TO_FP)
4921 return isKnownToBeAPowerOfTwo(Val.getOperand(0), Depth + 1);
4922
4923 return false;
4924}
4925
4927 APInt DemandedElts = getDemandAllEltsMask(Op);
4928 return ComputeNumSignBits(Op, DemandedElts, Depth);
4929}
4930
4931unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, const APInt &DemandedElts,
4932 unsigned Depth) const {
4933 EVT VT = Op.getValueType();
4934 assert((VT.isInteger() || VT.isFloatingPoint()) && "Invalid VT!");
4935 unsigned VTBits = VT.getScalarSizeInBits();
4936 unsigned NumElts = DemandedElts.getBitWidth();
4937 unsigned Tmp, Tmp2;
4938 unsigned FirstAnswer = 1;
4939
4940 assert((!VT.isScalableVector() || NumElts == 1) &&
4941 "DemandedElts for scalable vectors must be 1 to represent all lanes");
4942
4943 if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
4944 const APInt &Val = C->getAPIntValue();
4945 return Val.getNumSignBits();
4946 }
4947
4948 if (Depth >= MaxRecursionDepth)
4949 return 1; // Limit search depth.
4950
4951 if (!DemandedElts)
4952 return 1; // No demanded elts, better to assume we don't know anything.
4953
4954 unsigned Opcode = Op.getOpcode();
4955 switch (Opcode) {
4956 default: break;
4957 case ISD::AssertSext:
4958 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
4959 return VTBits-Tmp+1;
4960 case ISD::AssertZext:
4961 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
4962 return VTBits-Tmp;
4963 case ISD::FREEZE:
4964 if (isGuaranteedNotToBeUndefOrPoison(Op.getOperand(0), DemandedElts,
4966 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4967 break;
4968 case ISD::MERGE_VALUES:
4969 return ComputeNumSignBits(Op.getOperand(Op.getResNo()), DemandedElts,
4970 Depth + 1);
4971 case ISD::SPLAT_VECTOR: {
4972 // Check if the sign bits of source go down as far as the truncated value.
4973 unsigned NumSrcBits = Op.getOperand(0).getValueSizeInBits();
4974 unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
4975 if (NumSrcSignBits > (NumSrcBits - VTBits))
4976 return NumSrcSignBits - (NumSrcBits - VTBits);
4977 break;
4978 }
4979 case ISD::BUILD_VECTOR:
4980 assert(!VT.isScalableVector());
4981 Tmp = VTBits;
4982 for (unsigned i = 0, e = Op.getNumOperands(); (i < e) && (Tmp > 1); ++i) {
4983 if (!DemandedElts[i])
4984 continue;
4985
4986 SDValue SrcOp = Op.getOperand(i);
4987 // BUILD_VECTOR can implicitly truncate sources, we handle this specially
4988 // for constant nodes to ensure we only look at the sign bits.
4990 APInt T = C->getAPIntValue().trunc(VTBits);
4991 Tmp2 = T.getNumSignBits();
4992 } else {
4993 Tmp2 = ComputeNumSignBits(SrcOp, Depth + 1);
4994
4995 if (SrcOp.getValueSizeInBits() != VTBits) {
4996 assert(SrcOp.getValueSizeInBits() > VTBits &&
4997 "Expected BUILD_VECTOR implicit truncation");
4998 unsigned ExtraBits = SrcOp.getValueSizeInBits() - VTBits;
4999 Tmp2 = (Tmp2 > ExtraBits ? Tmp2 - ExtraBits : 1);
5000 }
5001 }
5002 Tmp = std::min(Tmp, Tmp2);
5003 }
5004 return Tmp;
5005
5006 case ISD::VECTOR_COMPRESS: {
5007 SDValue Vec = Op.getOperand(0);
5008 SDValue PassThru = Op.getOperand(2);
5009 Tmp = ComputeNumSignBits(PassThru, DemandedElts, Depth + 1);
5010 if (Tmp == 1)
5011 return 1;
5012 Tmp2 = ComputeNumSignBits(Vec, Depth + 1);
5013 Tmp = std::min(Tmp, Tmp2);
5014 return Tmp;
5015 }
5016
5017 case ISD::VECTOR_SHUFFLE: {
5018 // Collect the minimum number of sign bits that are shared by every vector
5019 // element referenced by the shuffle.
5020 APInt DemandedLHS, DemandedRHS;
5022 assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
5023 if (!getShuffleDemandedElts(NumElts, SVN->getMask(), DemandedElts,
5024 DemandedLHS, DemandedRHS))
5025 return 1;
5026
5027 Tmp = std::numeric_limits<unsigned>::max();
5028 if (!!DemandedLHS)
5029 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedLHS, Depth + 1);
5030 if (!!DemandedRHS) {
5031 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedRHS, Depth + 1);
5032 Tmp = std::min(Tmp, Tmp2);
5033 }
5034 // If we don't know anything, early out and try computeKnownBits fall-back.
5035 if (Tmp == 1)
5036 break;
5037 assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
5038 return Tmp;
5039 }
5040
5041 case ISD::BITCAST: {
5042 if (VT.isScalableVector())
5043 break;
5044 SDValue N0 = Op.getOperand(0);
5045 EVT SrcVT = N0.getValueType();
5046 unsigned SrcBits = SrcVT.getScalarSizeInBits();
5047
5048 // Ignore bitcasts from unsupported types..
5049 if (!(SrcVT.isInteger() || SrcVT.isFloatingPoint()))
5050 break;
5051
5052 // Fast handling of 'identity' bitcasts.
5053 if (VTBits == SrcBits)
5054 return ComputeNumSignBits(N0, DemandedElts, Depth + 1);
5055
5056 bool IsLE = getDataLayout().isLittleEndian();
5057
5058 // Bitcast 'large element' scalar/vector to 'small element' vector.
5059 if ((SrcBits % VTBits) == 0) {
5060 assert(VT.isVector() && "Expected bitcast to vector");
5061
5062 unsigned Scale = SrcBits / VTBits;
5063 APInt SrcDemandedElts =
5064 APIntOps::ScaleBitMask(DemandedElts, NumElts / Scale);
5065
5066 // Fast case - sign splat can be simply split across the small elements.
5067 Tmp = ComputeNumSignBits(N0, SrcDemandedElts, Depth + 1);
5068 if (Tmp == SrcBits)
5069 return VTBits;
5070
5071 // Slow case - determine how far the sign extends into each sub-element.
5072 Tmp2 = VTBits;
5073 for (unsigned i = 0; i != NumElts; ++i)
5074 if (DemandedElts[i]) {
5075 unsigned SubOffset = i % Scale;
5076 SubOffset = (IsLE ? ((Scale - 1) - SubOffset) : SubOffset);
5077 SubOffset = SubOffset * VTBits;
5078 if (Tmp <= SubOffset)
5079 return 1;
5080 Tmp2 = std::min(Tmp2, Tmp - SubOffset);
5081 }
5082 return Tmp2;
5083 }
5084 break;
5085 }
5086
5088 // FP_TO_SINT_SAT produces a signed value that fits in the saturating VT.
5089 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
5090 return VTBits - Tmp + 1;
5091 case ISD::SIGN_EXTEND:
5092 Tmp = VTBits - Op.getOperand(0).getScalarValueSizeInBits();
5093 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1) + Tmp;
5095 // Max of the input and what this extends.
5096 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
5097 Tmp = VTBits-Tmp+1;
5098 Tmp2 = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
5099 return std::max(Tmp, Tmp2);
5101 if (VT.isScalableVector())
5102 break;
5103 SDValue Src = Op.getOperand(0);
5104 EVT SrcVT = Src.getValueType();
5105 APInt DemandedSrcElts = DemandedElts.zext(SrcVT.getVectorNumElements());
5106 Tmp = VTBits - SrcVT.getScalarSizeInBits();
5107 return ComputeNumSignBits(Src, DemandedSrcElts, Depth+1) + Tmp;
5108 }
5109 case ISD::SRA:
5110 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5111 // SRA X, C -> adds C sign bits.
5112 if (std::optional<unsigned> ShAmt =
5113 getValidMinimumShiftAmount(Op, DemandedElts, Depth + 1))
5114 Tmp = std::min(Tmp + *ShAmt, VTBits);
5115 return Tmp;
5116 case ISD::SHL:
5117 if (std::optional<ConstantRange> ShAmtRange =
5118 getValidShiftAmountRange(Op, DemandedElts, Depth + 1)) {
5119 unsigned MaxShAmt = ShAmtRange->getUnsignedMax().getZExtValue();
5120 unsigned MinShAmt = ShAmtRange->getUnsignedMin().getZExtValue();
5121 // Try to look through ZERO/SIGN/ANY_EXTEND. If all extended bits are
5122 // shifted out, then we can compute the number of sign bits for the
5123 // operand being extended. A future improvement could be to pass along the
5124 // "shifted left by" information in the recursive calls to
5125 // ComputeKnownSignBits. Allowing us to handle this more generically.
5126 if (ISD::isExtOpcode(Op.getOperand(0).getOpcode())) {
5127 SDValue Ext = Op.getOperand(0);
5128 EVT ExtVT = Ext.getValueType();
5129 SDValue Extendee = Ext.getOperand(0);
5130 EVT ExtendeeVT = Extendee.getValueType();
5131 unsigned SizeDifference =
5132 ExtVT.getScalarSizeInBits() - ExtendeeVT.getScalarSizeInBits();
5133 if (SizeDifference <= MinShAmt) {
5134 Tmp = SizeDifference +
5135 ComputeNumSignBits(Extendee, DemandedElts, Depth + 1);
5136 if (MaxShAmt < Tmp)
5137 return Tmp - MaxShAmt;
5138 }
5139 }
5140 // shl destroys sign bits, ensure it doesn't shift out all sign bits.
5141 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5142 if (MaxShAmt < Tmp)
5143 return Tmp - MaxShAmt;
5144 }
5145 break;
5146 case ISD::AND:
5147 case ISD::OR:
5148 case ISD::XOR: // NOT is handled here.
5149 // Logical binary ops preserve the number of sign bits at the worst.
5150 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
5151 if (Tmp != 1) {
5152 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
5153 FirstAnswer = std::min(Tmp, Tmp2);
5154 // We computed what we know about the sign bits as our first
5155 // answer. Now proceed to the generic code that uses
5156 // computeKnownBits, and pick whichever answer is better.
5157 }
5158 break;
5159
5160 case ISD::SELECT:
5161 case ISD::VSELECT:
5162 Tmp = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
5163 if (Tmp == 1) return 1; // Early out.
5164 Tmp2 = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
5165 return std::min(Tmp, Tmp2);
5166 case ISD::SELECT_CC:
5167 Tmp = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
5168 if (Tmp == 1) return 1; // Early out.
5169 Tmp2 = ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth+1);
5170 return std::min(Tmp, Tmp2);
5171
5172 case ISD::SMIN:
5173 case ISD::SMAX: {
5174 // If we have a clamp pattern, we know that the number of sign bits will be
5175 // the minimum of the clamp min/max range.
5176 bool IsMax = (Opcode == ISD::SMAX);
5177 ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
5178 if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
5179 if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
5180 CstHigh =
5181 isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
5182 if (CstLow && CstHigh) {
5183 if (!IsMax)
5184 std::swap(CstLow, CstHigh);
5185 if (CstLow->getAPIntValue().sle(CstHigh->getAPIntValue())) {
5186 Tmp = CstLow->getAPIntValue().getNumSignBits();
5187 Tmp2 = CstHigh->getAPIntValue().getNumSignBits();
5188 return std::min(Tmp, Tmp2);
5189 }
5190 }
5191
5192 // Fallback - just get the minimum number of sign bits of the operands.
5193 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5194 if (Tmp == 1)
5195 return 1; // Early out.
5196 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
5197 return std::min(Tmp, Tmp2);
5198 }
5199 case ISD::UMIN:
5200 case ISD::UMAX:
5201 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5202 if (Tmp == 1)
5203 return 1; // Early out.
5204 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
5205 return std::min(Tmp, Tmp2);
5206 case ISD::SSUBO_CARRY:
5207 case ISD::USUBO_CARRY:
5208 // sub_carry(x,x,c) -> 0/-1 (sext carry)
5209 if (Op.getResNo() == 0 && Op.getOperand(0) == Op.getOperand(1))
5210 return VTBits;
5211 [[fallthrough]];
5212 case ISD::SADDO:
5213 case ISD::UADDO:
5214 case ISD::SADDO_CARRY:
5215 case ISD::UADDO_CARRY:
5216 case ISD::SSUBO:
5217 case ISD::USUBO:
5218 case ISD::SMULO:
5219 case ISD::UMULO:
5220 if (Op.getResNo() != 1)
5221 break;
5222 // The boolean result conforms to getBooleanContents. Fall through.
5223 // If setcc returns 0/-1, all bits are sign bits.
5224 // We know that we have an integer-based boolean since these operations
5225 // are only available for integer.
5226 if (TLI->getBooleanContents(VT.isVector(), false) ==
5228 return VTBits;
5229 break;
5230 case ISD::SETCC:
5231 case ISD::SETCCCARRY:
5232 case ISD::STRICT_FSETCC:
5233 case ISD::STRICT_FSETCCS: {
5234 unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
5235 // If setcc returns 0/-1, all bits are sign bits.
5236 if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
5238 return VTBits;
5239 break;
5240 }
5242 // Semantically similar to icmp ult.
5243 if (TLI->getBooleanContents(VT.isVector(), /*isFloat=*/false) ==
5245 return VTBits;
5246 break;
5247 case ISD::ROTL:
5248 case ISD::ROTR:
5249 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5250
5251 // If we're rotating an 0/-1 value, then it stays an 0/-1 value.
5252 if (Tmp == VTBits)
5253 return VTBits;
5254
5255 if (ConstantSDNode *C =
5256 isConstOrConstSplat(Op.getOperand(1), DemandedElts)) {
5257 unsigned RotAmt = C->getAPIntValue().urem(VTBits);
5258
5259 // Handle rotate right by N like a rotate left by 32-N.
5260 if (Opcode == ISD::ROTR)
5261 RotAmt = (VTBits - RotAmt) % VTBits;
5262
5263 // If we aren't rotating out all of the known-in sign bits, return the
5264 // number that are left. This handles rotl(sext(x), 1) for example.
5265 if (Tmp > (RotAmt + 1)) return (Tmp - RotAmt);
5266 }
5267 break;
5268 case ISD::ADD:
5269 case ISD::ADDC:
5270 // TODO: Move Operand 1 check before Operand 0 check
5271 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5272 if (Tmp == 1) return 1; // Early out.
5273
5274 // Special case decrementing a value (ADD X, -1):
5275 if (ConstantSDNode *CRHS =
5276 isConstOrConstSplat(Op.getOperand(1), DemandedElts))
5277 if (CRHS->isAllOnes()) {
5279 computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
5280
5281 // If the input is known to be 0 or 1, the output is 0/-1, which is all
5282 // sign bits set.
5283 if ((Known.Zero | 1).isAllOnes())
5284 return VTBits;
5285
5286 // If we are subtracting one from a positive number, there is no carry
5287 // out of the result.
5288 if (Known.isNonNegative())
5289 return Tmp;
5290 }
5291
5292 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
5293 if (Tmp2 == 1) return 1; // Early out.
5294
5295 // Add can have at most one carry bit. Thus we know that the output
5296 // is, at worst, one more bit than the inputs.
5297 return std::min(Tmp, Tmp2) - 1;
5298 case ISD::SUB:
5299 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
5300 if (Tmp2 == 1) return 1; // Early out.
5301
5302 // Handle NEG.
5303 if (ConstantSDNode *CLHS =
5304 isConstOrConstSplat(Op.getOperand(0), DemandedElts))
5305 if (CLHS->isZero()) {
5307 computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
5308 // If the input is known to be 0 or 1, the output is 0/-1, which is all
5309 // sign bits set.
5310 if ((Known.Zero | 1).isAllOnes())
5311 return VTBits;
5312
5313 // If the input is known to be positive (the sign bit is known clear),
5314 // the output of the NEG has the same number of sign bits as the input.
5315 if (Known.isNonNegative())
5316 return Tmp2;
5317
5318 // Otherwise, we treat this like a SUB.
5319 }
5320
5321 // Sub can have at most one carry bit. Thus we know that the output
5322 // is, at worst, one more bit than the inputs.
5323 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5324 if (Tmp == 1) return 1; // Early out.
5325 return std::min(Tmp, Tmp2) - 1;
5326 case ISD::MUL: {
5327 // The output of the Mul can be at most twice the valid bits in the inputs.
5328 unsigned SignBitsOp0 = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
5329 if (SignBitsOp0 == 1)
5330 break;
5331 unsigned SignBitsOp1 = ComputeNumSignBits(Op.getOperand(1), Depth + 1);
5332 if (SignBitsOp1 == 1)
5333 break;
5334 unsigned OutValidBits =
5335 (VTBits - SignBitsOp0 + 1) + (VTBits - SignBitsOp1 + 1);
5336 return OutValidBits > VTBits ? 1 : VTBits - OutValidBits + 1;
5337 }
5338 case ISD::AVGCEILS:
5339 case ISD::AVGFLOORS:
5340 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5341 if (Tmp == 1)
5342 return 1; // Early out.
5343 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
5344 return std::min(Tmp, Tmp2);
5345 case ISD::SREM:
5346 // The sign bit is the LHS's sign bit, except when the result of the
5347 // remainder is zero. The magnitude of the result should be less than or
5348 // equal to the magnitude of the LHS. Therefore, the result should have
5349 // at least as many sign bits as the left hand side.
5350 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
5351 case ISD::TRUNCATE: {
5352 // Check if the sign bits of source go down as far as the truncated value.
5353 unsigned NumSrcBits = Op.getOperand(0).getScalarValueSizeInBits();
5354 unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
5355 if (NumSrcSignBits > (NumSrcBits - VTBits))
5356 return NumSrcSignBits - (NumSrcBits - VTBits);
5357 break;
5358 }
5359 case ISD::EXTRACT_ELEMENT: {
5360 if (VT.isScalableVector())
5361 break;
5362 const int KnownSign = ComputeNumSignBits(Op.getOperand(0), Depth+1);
5363 const int BitWidth = Op.getValueSizeInBits();
5364 const int Items = Op.getOperand(0).getValueSizeInBits() / BitWidth;
5365
5366 // Get reverse index (starting from 1), Op1 value indexes elements from
5367 // little end. Sign starts at big end.
5368 const int rIndex = Items - 1 - Op.getConstantOperandVal(1);
5369
5370 // If the sign portion ends in our element the subtraction gives correct
5371 // result. Otherwise it gives either negative or > bitwidth result
5372 return std::clamp(KnownSign - rIndex * BitWidth, 1, BitWidth);
5373 }
5375 if (VT.isScalableVector())
5376 break;
5377 // If we know the element index, split the demand between the
5378 // source vector and the inserted element, otherwise assume we need
5379 // the original demanded vector elements and the value.
5380 SDValue InVec = Op.getOperand(0);
5381 SDValue InVal = Op.getOperand(1);
5382 SDValue EltNo = Op.getOperand(2);
5383 bool DemandedVal = true;
5384 APInt DemandedVecElts = DemandedElts;
5385 auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
5386 if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
5387 unsigned EltIdx = CEltNo->getZExtValue();
5388 DemandedVal = !!DemandedElts[EltIdx];
5389 DemandedVecElts.clearBit(EltIdx);
5390 }
5391 Tmp = std::numeric_limits<unsigned>::max();
5392 if (DemandedVal) {
5393 // TODO - handle implicit truncation of inserted elements.
5394 if (InVal.getScalarValueSizeInBits() != VTBits)
5395 break;
5396 Tmp2 = ComputeNumSignBits(InVal, Depth + 1);
5397 Tmp = std::min(Tmp, Tmp2);
5398 }
5399 if (!!DemandedVecElts) {
5400 Tmp2 = ComputeNumSignBits(InVec, DemandedVecElts, Depth + 1);
5401 Tmp = std::min(Tmp, Tmp2);
5402 }
5403 assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
5404 return Tmp;
5405 }
5407 SDValue InVec = Op.getOperand(0);
5408 SDValue EltNo = Op.getOperand(1);
5409 EVT VecVT = InVec.getValueType();
5410 // ComputeNumSignBits not yet implemented for scalable vectors.
5411 if (VecVT.isScalableVector())
5412 break;
5413 const unsigned BitWidth = Op.getValueSizeInBits();
5414 const unsigned EltBitWidth = Op.getOperand(0).getScalarValueSizeInBits();
5415 const unsigned NumSrcElts = VecVT.getVectorNumElements();
5416
5417 // If BitWidth > EltBitWidth the value is anyext:ed, and we do not know
5418 // anything about sign bits. But if the sizes match we can derive knowledge
5419 // about sign bits from the vector operand.
5420 if (BitWidth != EltBitWidth)
5421 break;
5422
5423 // If we know the element index, just demand that vector element, else for
5424 // an unknown element index, ignore DemandedElts and demand them all.
5425 APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
5426 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
5427 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
5428 DemandedSrcElts =
5429 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
5430
5431 return ComputeNumSignBits(InVec, DemandedSrcElts, Depth + 1);
5432 }
5434 // Offset the demanded elts by the subvector index.
5435 SDValue Src = Op.getOperand(0);
5436
5437 APInt DemandedSrcElts;
5438 if (Src.getValueType().isScalableVector())
5439 DemandedSrcElts = APInt(1, 1);
5440 else {
5441 uint64_t Idx = Op.getConstantOperandVal(1);
5442 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
5443 DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
5444 }
5445 return ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
5446 }
5447 case ISD::CONCAT_VECTORS: {
5448 if (VT.isScalableVector())
5449 break;
5450 // Determine the minimum number of sign bits across all demanded
5451 // elts of the input vectors. Early out if the result is already 1.
5452 Tmp = std::numeric_limits<unsigned>::max();
5453 EVT SubVectorVT = Op.getOperand(0).getValueType();
5454 unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
5455 unsigned NumSubVectors = Op.getNumOperands();
5456 for (unsigned i = 0; (i < NumSubVectors) && (Tmp > 1); ++i) {
5457 APInt DemandedSub =
5458 DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts);
5459 if (!DemandedSub)
5460 continue;
5461 Tmp2 = ComputeNumSignBits(Op.getOperand(i), DemandedSub, Depth + 1);
5462 Tmp = std::min(Tmp, Tmp2);
5463 }
5464 assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
5465 return Tmp;
5466 }
5467 case ISD::INSERT_SUBVECTOR: {
5468 if (VT.isScalableVector())
5469 break;
5470 // Demand any elements from the subvector and the remainder from the src its
5471 // inserted into.
5472 SDValue Src = Op.getOperand(0);
5473 SDValue Sub = Op.getOperand(1);
5474 uint64_t Idx = Op.getConstantOperandVal(2);
5475 unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
5476 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
5477 APInt DemandedSrcElts = DemandedElts;
5478 DemandedSrcElts.clearBits(Idx, Idx + NumSubElts);
5479
5480 Tmp = std::numeric_limits<unsigned>::max();
5481 if (!!DemandedSubElts) {
5482 Tmp = ComputeNumSignBits(Sub, DemandedSubElts, Depth + 1);
5483 if (Tmp == 1)
5484 return 1; // early-out
5485 }
5486 if (!!DemandedSrcElts) {
5487 Tmp2 = ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
5488 Tmp = std::min(Tmp, Tmp2);
5489 }
5490 assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
5491 return Tmp;
5492 }
5493 case ISD::LOAD: {
5494 // If we are looking at the loaded value of the SDNode.
5495 if (Op.getResNo() != 0)
5496 break;
5497
5499 if (const MDNode *Ranges = LD->getRanges()) {
5500 if (DemandedElts != 1)
5501 break;
5502
5504 if (VTBits > CR.getBitWidth()) {
5505 switch (LD->getExtensionType()) {
5506 case ISD::SEXTLOAD:
5507 CR = CR.signExtend(VTBits);
5508 break;
5509 case ISD::ZEXTLOAD:
5510 CR = CR.zeroExtend(VTBits);
5511 break;
5512 default:
5513 break;
5514 }
5515 }
5516
5517 if (VTBits != CR.getBitWidth())
5518 break;
5519 return std::min(CR.getSignedMin().getNumSignBits(),
5521 }
5522
5523 unsigned ExtType = LD->getExtensionType();
5524 switch (ExtType) {
5525 default:
5526 break;
5527 case ISD::SEXTLOAD: // e.g. i16->i32 = '17' bits known.
5528 Tmp = LD->getMemoryVT().getScalarSizeInBits();
5529 return VTBits - Tmp + 1;
5530 case ISD::ZEXTLOAD: // e.g. i16->i32 = '16' bits known.
5531 Tmp = LD->getMemoryVT().getScalarSizeInBits();
5532 return VTBits - Tmp;
5533 case ISD::NON_EXTLOAD:
5534 if (const Constant *Cst = TLI->getTargetConstantFromLoad(LD)) {
5535 // We only need to handle vectors - computeKnownBits should handle
5536 // scalar cases.
5537 Type *CstTy = Cst->getType();
5538 if (CstTy->isVectorTy() && !VT.isScalableVector() &&
5539 (NumElts * VTBits) == CstTy->getPrimitiveSizeInBits() &&
5540 VTBits == CstTy->getScalarSizeInBits()) {
5541 Tmp = VTBits;
5542 for (unsigned i = 0; i != NumElts; ++i) {
5543 if (!DemandedElts[i])
5544 continue;
5545 if (Constant *Elt = Cst->getAggregateElement(i)) {
5546 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
5547 const APInt &Value = CInt->getValue();
5548 Tmp = std::min(Tmp, Value.getNumSignBits());
5549 continue;
5550 }
5551 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
5552 APInt Value = CFP->getValueAPF().bitcastToAPInt();
5553 Tmp = std::min(Tmp, Value.getNumSignBits());
5554 continue;
5555 }
5556 }
5557 // Unknown type. Conservatively assume no bits match sign bit.
5558 return 1;
5559 }
5560 return Tmp;
5561 }
5562 }
5563 break;
5564 }
5565
5566 break;
5567 }
5570 case ISD::ATOMIC_SWAP:
5582 case ISD::ATOMIC_LOAD: {
5583 auto *AT = cast<AtomicSDNode>(Op);
5584 // If we are looking at the loaded value.
5585 if (Op.getResNo() == 0) {
5586 Tmp = AT->getMemoryVT().getScalarSizeInBits();
5587 if (Tmp == VTBits)
5588 return 1; // early-out
5589
5590 // For atomic_load, prefer to use the extension type.
5591 if (Op->getOpcode() == ISD::ATOMIC_LOAD) {
5592 switch (AT->getExtensionType()) {
5593 default:
5594 break;
5595 case ISD::SEXTLOAD:
5596 return VTBits - Tmp + 1;
5597 case ISD::ZEXTLOAD:
5598 return VTBits - Tmp;
5599 }
5600 }
5601
5602 if (TLI->getExtendForAtomicOps() == ISD::SIGN_EXTEND)
5603 return VTBits - Tmp + 1;
5604 if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND)
5605 return VTBits - Tmp;
5606 }
5607 break;
5608 }
5609 }
5610
5611 // Allow the target to implement this method for its nodes.
5612 if (Opcode >= ISD::BUILTIN_OP_END ||
5613 Opcode == ISD::INTRINSIC_WO_CHAIN ||
5614 Opcode == ISD::INTRINSIC_W_CHAIN ||
5615 Opcode == ISD::INTRINSIC_VOID) {
5616 // TODO: This can probably be removed once target code is audited. This
5617 // is here purely to reduce patch size and review complexity.
5618 if (!VT.isScalableVector()) {
5619 unsigned NumBits =
5620 TLI->ComputeNumSignBitsForTargetNode(Op, DemandedElts, *this, Depth);
5621 if (NumBits > 1)
5622 FirstAnswer = std::max(FirstAnswer, NumBits);
5623 }
5624 }
5625
5626 // Finally, if we can prove that the top bits of the result are 0's or 1's,
5627 // use this information.
5628 KnownBits Known = computeKnownBits(Op, DemandedElts, Depth);
5629 return std::max(FirstAnswer, Known.countMinSignBits());
5630}
5631
5633 unsigned Depth) const {
5634 unsigned SignBits = ComputeNumSignBits(Op, Depth);
5635 return Op.getScalarValueSizeInBits() - SignBits + 1;
5636}
5637
5639 const APInt &DemandedElts,
5640 unsigned Depth) const {
5641 unsigned SignBits = ComputeNumSignBits(Op, DemandedElts, Depth);
5642 return Op.getScalarValueSizeInBits() - SignBits + 1;
5643}
5644
5646 UndefPoisonKind Kind,
5647 unsigned Depth) const {
5648 // Early out for FREEZE.
5649 if (Op.getOpcode() == ISD::FREEZE)
5650 return true;
5651
5652 APInt DemandedElts = getDemandAllEltsMask(Op);
5653 return isGuaranteedNotToBeUndefOrPoison(Op, DemandedElts, Kind, Depth);
5654}
5655
5657 const APInt &DemandedElts,
5658 UndefPoisonKind Kind,
5659 unsigned Depth) const {
5660 unsigned Opcode = Op.getOpcode();
5661
5662 // Early out for FREEZE.
5663 if (Opcode == ISD::FREEZE)
5664 return true;
5665
5666 if (Depth >= MaxRecursionDepth)
5667 return false; // Limit search depth.
5668
5669 if (isIntOrFPConstant(Op))
5670 return true;
5671
5672 switch (Opcode) {
5673 case ISD::CONDCODE:
5674 case ISD::VALUETYPE:
5675 case ISD::FrameIndex:
5677 case ISD::CopyFromReg:
5678 return true;
5679
5680 case ISD::POISON:
5681 return !includesPoison(Kind);
5682
5683 case ISD::UNDEF:
5684 return !includesUndef(Kind);
5685
5686 case ISD::BITCAST: {
5687 SDValue Src = Op.getOperand(0);
5688 EVT SrcVT = Src.getValueType();
5689 EVT DstVT = Op.getValueType();
5690
5691 if (!SrcVT.isVector() || !DstVT.isVector())
5692 return isGuaranteedNotToBeUndefOrPoison(Src, Kind, Depth + 1);
5693
5694 unsigned SrcEltBits = SrcVT.getScalarSizeInBits();
5695 unsigned DstEltBits = DstVT.getScalarSizeInBits();
5696 ElementCount NumSrcElts = SrcVT.getVectorElementCount();
5697 [[maybe_unused]] ElementCount NumDstElts = DstVT.getVectorElementCount();
5698
5699 if (SrcEltBits == DstEltBits)
5700 return isGuaranteedNotToBeUndefOrPoison(Src, DemandedElts, Kind,
5701 Depth + 1);
5702
5703 if (SrcEltBits < DstEltBits) {
5704 if (DstEltBits % SrcEltBits != 0)
5705 return isGuaranteedNotToBeUndefOrPoison(Src, Kind, Depth + 1);
5706
5707 assert(NumSrcElts == NumDstElts * (DstEltBits / SrcEltBits) &&
5708 "Unexpected vector bitcast");
5709 APInt DemandedSrcElts =
5710 APIntOps::ScaleBitMask(DemandedElts, NumSrcElts.getKnownMinValue());
5711 return isGuaranteedNotToBeUndefOrPoison(Src, DemandedSrcElts, Kind,
5712 Depth + 1);
5713 }
5714
5715 if (SrcEltBits % DstEltBits != 0)
5716 return isGuaranteedNotToBeUndefOrPoison(Src, Kind, Depth + 1);
5717
5718 assert(NumDstElts == NumSrcElts * (SrcEltBits / DstEltBits) &&
5719 "Unexpected vector bitcast");
5720 APInt DemandedSrcElts =
5721 APIntOps::ScaleBitMask(DemandedElts, NumSrcElts.getKnownMinValue());
5722 return isGuaranteedNotToBeUndefOrPoison(Src, DemandedSrcElts, Kind,
5723 Depth + 1);
5724 }
5725
5726 case ISD::BUILD_VECTOR:
5727 // NOTE: BUILD_VECTOR has implicit truncation of wider scalar elements -
5728 // this shouldn't affect the result.
5729 for (unsigned i = 0, e = Op.getNumOperands(); i < e; ++i) {
5730 if (!DemandedElts[i])
5731 continue;
5732 if (!isGuaranteedNotToBeUndefOrPoison(Op.getOperand(i), Kind, Depth + 1))
5733 return false;
5734 }
5735 return true;
5736
5737 case ISD::CONCAT_VECTORS: {
5738 EVT VT = Op.getValueType();
5739 if (!VT.isFixedLengthVector())
5740 break;
5741
5742 EVT SubVT = Op.getOperand(0).getValueType();
5743 unsigned NumSubElts = SubVT.getVectorNumElements();
5744 for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) {
5745 APInt DemandedSubElts =
5746 DemandedElts.extractBits(NumSubElts, I * NumSubElts);
5747 if (!!DemandedSubElts &&
5748 !isGuaranteedNotToBeUndefOrPoison(Op.getOperand(I), DemandedSubElts,
5749 Kind, Depth + 1))
5750 return false;
5751 }
5752 return true;
5753 }
5754
5756 SDValue Src = Op.getOperand(0);
5757 if (Src.getValueType().isScalableVector())
5758 break;
5759 uint64_t Idx = Op.getConstantOperandVal(1);
5760 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
5761 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
5762 return isGuaranteedNotToBeUndefOrPoison(Src, DemandedSrcElts, Kind,
5763 Depth + 1);
5764 }
5765
5766 case ISD::INSERT_SUBVECTOR: {
5767 if (Op.getValueType().isScalableVector())
5768 break;
5769 SDValue Src = Op.getOperand(0);
5770 SDValue Sub = Op.getOperand(1);
5771 uint64_t Idx = Op.getConstantOperandVal(2);
5772 unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
5773 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
5774 APInt DemandedSrcElts = DemandedElts;
5775 DemandedSrcElts.clearBits(Idx, Idx + NumSubElts);
5776
5777 if (!!DemandedSubElts && !isGuaranteedNotToBeUndefOrPoison(
5778 Sub, DemandedSubElts, Kind, Depth + 1))
5779 return false;
5780 if (!!DemandedSrcElts && !isGuaranteedNotToBeUndefOrPoison(
5781 Src, DemandedSrcElts, Kind, Depth + 1))
5782 return false;
5783 return true;
5784 }
5785
5787 SDValue Src = Op.getOperand(0);
5788 auto *IndexC = dyn_cast<ConstantSDNode>(Op.getOperand(1));
5789 EVT SrcVT = Src.getValueType();
5790 if (SrcVT.isFixedLengthVector() && IndexC &&
5791 IndexC->getAPIntValue().ult(SrcVT.getVectorNumElements())) {
5792 APInt DemandedSrcElts = APInt::getOneBitSet(SrcVT.getVectorNumElements(),
5793 IndexC->getZExtValue());
5794 return isGuaranteedNotToBeUndefOrPoison(Src, DemandedSrcElts, Kind,
5795 Depth + 1);
5796 }
5797 break;
5798 }
5799
5801 SDValue InVec = Op.getOperand(0);
5802 SDValue InVal = Op.getOperand(1);
5803 SDValue EltNo = Op.getOperand(2);
5804 EVT VT = InVec.getValueType();
5805 auto *IndexC = dyn_cast<ConstantSDNode>(EltNo);
5806 if (IndexC && VT.isFixedLengthVector() &&
5807 IndexC->getAPIntValue().ult(VT.getVectorNumElements())) {
5808 if (DemandedElts[IndexC->getZExtValue()] &&
5809 !isGuaranteedNotToBeUndefOrPoison(InVal, Kind, Depth + 1))
5810 return false;
5811 APInt InVecDemandedElts = DemandedElts;
5812 InVecDemandedElts.clearBit(IndexC->getZExtValue());
5813 if (!!InVecDemandedElts &&
5815 peekThroughInsertVectorElt(InVec, InVecDemandedElts),
5816 InVecDemandedElts, Kind, Depth + 1))
5817 return false;
5818 return true;
5819 }
5820 break;
5821 }
5822
5824 // Check upper (known undef) elements.
5825 if (DemandedElts.ugt(1) && includesUndef(Kind))
5826 return false;
5827 // Check element zero.
5828 if (DemandedElts[0] &&
5829 !isGuaranteedNotToBeUndefOrPoison(Op.getOperand(0), Kind, Depth + 1))
5830 return false;
5831 return true;
5832
5833 case ISD::SPLAT_VECTOR:
5834 return isGuaranteedNotToBeUndefOrPoison(Op.getOperand(0), Kind, Depth + 1);
5835
5836 case ISD::SELECT: {
5837 return !canCreateUndefOrPoison(Op, DemandedElts, Kind,
5838 /*ConsiderFlags*/ true, Depth) &&
5839 isGuaranteedNotToBeUndefOrPoison(Op.getOperand(0), Kind,
5840 Depth + 1) &&
5841 isGuaranteedNotToBeUndefOrPoison(Op.getOperand(1), DemandedElts,
5842 Kind, Depth + 1) &&
5843 isGuaranteedNotToBeUndefOrPoison(Op.getOperand(2), DemandedElts,
5844 Kind, Depth + 1);
5845 }
5846
5847 case ISD::VECTOR_SHUFFLE: {
5848 APInt DemandedLHS, DemandedRHS;
5849 auto *SVN = cast<ShuffleVectorSDNode>(Op);
5850 if (!getShuffleDemandedElts(DemandedElts.getBitWidth(), SVN->getMask(),
5851 DemandedElts, DemandedLHS, DemandedRHS,
5852 /*AllowUndefElts=*/false))
5853 return false;
5854 if (!DemandedLHS.isZero() &&
5855 !isGuaranteedNotToBeUndefOrPoison(Op.getOperand(0), DemandedLHS, Kind,
5856 Depth + 1))
5857 return false;
5858 if (!DemandedRHS.isZero() &&
5859 !isGuaranteedNotToBeUndefOrPoison(Op.getOperand(1), DemandedRHS, Kind,
5860 Depth + 1))
5861 return false;
5862 return true;
5863 }
5864
5865 case ISD::SHL:
5866 case ISD::SRL:
5867 case ISD::SRA:
5868 // Shift amount operand is checked by canCreateUndefOrPoison. So it is
5869 // enough to check operand 0 if Op can't create undef/poison.
5870 return !canCreateUndefOrPoison(Op, DemandedElts, Kind,
5871 /*ConsiderFlags*/ true, Depth) &&
5872 isGuaranteedNotToBeUndefOrPoison(Op.getOperand(0), DemandedElts,
5873 Kind, Depth + 1);
5874
5875 case ISD::BSWAP:
5876 case ISD::CTPOP:
5877 case ISD::BITREVERSE:
5878 case ISD::AND:
5879 case ISD::OR:
5880 case ISD::XOR:
5881 case ISD::ADD:
5882 case ISD::SUB:
5883 case ISD::MUL:
5884 case ISD::SADDSAT:
5885 case ISD::UADDSAT:
5886 case ISD::SSUBSAT:
5887 case ISD::USUBSAT:
5888 case ISD::SSHLSAT:
5889 case ISD::USHLSAT:
5890 case ISD::SMIN:
5891 case ISD::SMAX:
5892 case ISD::UMIN:
5893 case ISD::UMAX:
5894 case ISD::ZERO_EXTEND:
5895 case ISD::SIGN_EXTEND:
5896 case ISD::ANY_EXTEND:
5897 case ISD::TRUNCATE:
5898 case ISD::VSELECT: {
5899 // If Op can't create undef/poison and none of its operands are undef/poison
5900 // then Op is never undef/poison. A difference from the more common check
5901 // below, outside the switch, is that we handle elementwise operations for
5902 // which the DemandedElts mask is valid for all operands here.
5903 return !canCreateUndefOrPoison(Op, DemandedElts, Kind,
5904 /*ConsiderFlags*/ true, Depth) &&
5905 all_of(Op->ops(), [&](SDValue V) {
5906 return isGuaranteedNotToBeUndefOrPoison(V, DemandedElts, Kind,
5907 Depth + 1);
5908 });
5909 }
5910
5911 // TODO: Search for noundef attributes from library functions.
5912
5913 // TODO: Pointers dereferenced by ISD::LOAD/STORE ops are noundef.
5914
5915 default:
5916 // Allow the target to implement this method for its nodes.
5917 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
5918 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID)
5919 return TLI->isGuaranteedNotToBeUndefOrPoisonForTargetNode(
5920 Op, DemandedElts, *this, Kind, Depth);
5921 break;
5922 }
5923
5924 // If Op can't create undef/poison and none of its operands are undef/poison
5925 // then Op is never undef/poison.
5926 // NOTE: TargetNodes can handle this in themselves in
5927 // isGuaranteedNotToBeUndefOrPoisonForTargetNode or let
5928 // TargetLowering::isGuaranteedNotToBeUndefOrPoisonForTargetNode handle it.
5929 return !canCreateUndefOrPoison(Op, Kind, /*ConsiderFlags*/ true, Depth) &&
5930 all_of(Op->ops(), [&](SDValue V) {
5931 return isGuaranteedNotToBeUndefOrPoison(V, Kind, Depth + 1);
5932 });
5933}
5934
5936 bool ConsiderFlags,
5937 unsigned Depth) const {
5938 APInt DemandedElts = getDemandAllEltsMask(Op);
5939 return canCreateUndefOrPoison(Op, DemandedElts, Kind, ConsiderFlags, Depth);
5940}
5941
5943 UndefPoisonKind Kind,
5944 bool ConsiderFlags,
5945 unsigned Depth) const {
5946 if (ConsiderFlags && includesPoison(Kind) && Op->hasPoisonGeneratingFlags())
5947 return true;
5948
5949 unsigned Opcode = Op.getOpcode();
5950 switch (Opcode) {
5951 case ISD::AssertSext:
5952 case ISD::AssertZext:
5953 case ISD::AssertAlign:
5955 // Assertion nodes can create poison if the assertion fails.
5956 return includesPoison(Kind);
5957
5958 case ISD::FREEZE:
5962 case ISD::SADDSAT:
5963 case ISD::UADDSAT:
5964 case ISD::SSUBSAT:
5965 case ISD::USUBSAT:
5966 case ISD::MULHU:
5967 case ISD::MULHS:
5968 case ISD::AVGFLOORS:
5969 case ISD::AVGFLOORU:
5970 case ISD::AVGCEILS:
5971 case ISD::AVGCEILU:
5972 case ISD::ABDU:
5973 case ISD::ABDS:
5974 case ISD::SMIN:
5975 case ISD::SMAX:
5976 case ISD::SCMP:
5977 case ISD::UMIN:
5978 case ISD::UMAX:
5979 case ISD::UCMP:
5980 case ISD::AND:
5981 case ISD::XOR:
5982 case ISD::ROTL:
5983 case ISD::ROTR:
5984 case ISD::FSHL:
5985 case ISD::FSHR:
5986 case ISD::BSWAP:
5987 case ISD::CTTZ:
5988 case ISD::CTLZ:
5989 case ISD::CTLS:
5990 case ISD::CTPOP:
5991 case ISD::BITREVERSE:
5992 case ISD::PARITY:
5993 case ISD::SIGN_EXTEND:
5994 case ISD::TRUNCATE:
5998 case ISD::BITCAST:
5999 case ISD::BUILD_VECTOR:
6000 case ISD::BUILD_PAIR:
6001 case ISD::SPLAT_VECTOR:
6002 case ISD::FABS:
6003 case ISD::FCEIL:
6004 case ISD::FFLOOR:
6005 case ISD::FTRUNC:
6006 case ISD::FRINT:
6007 case ISD::FNEARBYINT:
6008 case ISD::FROUND:
6009 case ISD::FROUNDEVEN:
6010 return false;
6011
6012 case ISD::ABS:
6013 // ISD::ABS defines abs(INT_MIN) -> INT_MIN and never generates poison.
6014 // Different to Intrinsic::abs.
6015 return false;
6017 // ABS_MIN_POISON may produce poison if the input is INT_MIN.
6018 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1) <= 1;
6019
6020 case ISD::ADDC:
6021 case ISD::SUBC:
6022 case ISD::ADDE:
6023 case ISD::SUBE:
6024 case ISD::SADDO:
6025 case ISD::SSUBO:
6026 case ISD::SMULO:
6027 case ISD::SADDO_CARRY:
6028 case ISD::SSUBO_CARRY:
6029 case ISD::UADDO:
6030 case ISD::USUBO:
6031 case ISD::UMULO:
6032 case ISD::UADDO_CARRY:
6033 case ISD::USUBO_CARRY:
6034 // No poison on result or overflow flags.
6035 return false;
6036
6037 case ISD::SELECT_CC:
6038 case ISD::SETCC: {
6039 // Integer setcc cannot create undef or poison.
6040 if (Op.getOperand(0).getValueType().isInteger())
6041 return false;
6042
6043 // FP compares are more complicated. They can create poison for nan/infinity
6044 // based on options and flags. The options and flags also cause special
6045 // nonan condition codes to be used. Those condition codes may be preserved
6046 // even if the nonan flag is dropped somewhere.
6047 unsigned CCOp = Opcode == ISD::SETCC ? 2 : 4;
6048 ISD::CondCode CCCode = cast<CondCodeSDNode>(Op.getOperand(CCOp))->get();
6049 return (unsigned)CCCode & 0x10U;
6050 }
6051
6052 case ISD::OR:
6053 case ISD::ZERO_EXTEND:
6054 case ISD::SELECT:
6055 case ISD::VSELECT:
6056 case ISD::ADD:
6057 case ISD::SUB:
6058 case ISD::MUL:
6059 case ISD::FNEG:
6060 case ISD::FADD:
6061 case ISD::FSUB:
6062 case ISD::FMUL:
6063 case ISD::FDIV:
6064 case ISD::FREM:
6065 case ISD::FCOPYSIGN:
6066 case ISD::FMA:
6067 case ISD::FMAD:
6068 case ISD::FMULADD:
6069 case ISD::FP_EXTEND:
6070 case ISD::FMINNUM:
6071 case ISD::FMAXNUM:
6072 case ISD::FMINNUM_IEEE:
6073 case ISD::FMAXNUM_IEEE:
6074 case ISD::FMINIMUM:
6075 case ISD::FMAXIMUM:
6076 case ISD::FMINIMUMNUM:
6077 case ISD::FMAXIMUMNUM:
6083 // No poison except from flags (which is handled above)
6084 return false;
6085
6086 case ISD::SHL:
6087 case ISD::SRL:
6088 case ISD::SRA:
6089 // If the max shift amount isn't in range, then the shift can
6090 // create poison.
6091 return includesPoison(Kind) &&
6092 !getValidMaximumShiftAmount(Op, DemandedElts, Depth + 1);
6093
6096 // If the amount is zero then the result will be poison.
6097 // TODO: Add isKnownNeverZero DemandedElts handling.
6098 return includesPoison(Kind) &&
6099 !isKnownNeverZero(Op.getOperand(0), Depth + 1);
6100
6102 // Check if we demand any upper (undef) elements.
6103 return includesUndef(Kind) && DemandedElts.ugt(1);
6104
6107 // Ensure that the element index is in bounds.
6108 if (includesPoison(Kind)) {
6109 EVT VecVT = Op.getOperand(0).getValueType();
6110 SDValue Idx = Op.getOperand(Opcode == ISD::INSERT_VECTOR_ELT ? 2 : 1);
6111 KnownBits KnownIdx = computeKnownBits(Idx, Depth + 1);
6112 return KnownIdx.getMaxValue().uge(VecVT.getVectorMinNumElements());
6113 }
6114 return false;
6115 }
6116
6117 case ISD::VECTOR_SHUFFLE: {
6118 // Check for any demanded shuffle element that is undef.
6119 auto *SVN = cast<ShuffleVectorSDNode>(Op);
6120 for (auto [Idx, Elt] : enumerate(SVN->getMask()))
6121 if (Elt < 0 && DemandedElts[Idx])
6122 return true;
6123 return false;
6124 }
6125
6127 return false;
6128
6129 default:
6130 // Allow the target to implement this method for its nodes.
6131 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
6132 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID)
6133 return TLI->canCreateUndefOrPoisonForTargetNode(
6134 Op, DemandedElts, *this, Kind, ConsiderFlags, Depth);
6135 break;
6136 }
6137
6138 // Be conservative and return true.
6139 return true;
6140}
6141
6142bool SelectionDAG::isADDLike(SDValue Op, bool NoWrap) const {
6143 unsigned Opcode = Op.getOpcode();
6144 if (Opcode == ISD::OR)
6145 return Op->getFlags().hasDisjoint() ||
6146 haveNoCommonBitsSet(Op.getOperand(0), Op.getOperand(1));
6147 if (Opcode == ISD::XOR)
6148 return !NoWrap && isMinSignedConstant(Op.getOperand(1));
6149 return false;
6150}
6151
6153 return Op.getNumOperands() == 2 && isa<ConstantSDNode>(Op.getOperand(1)) &&
6154 (Op.isAnyAdd() || isADDLike(Op));
6155}
6156
6158 FPClassTest InterestedClasses,
6159 unsigned Depth) const {
6160 APInt DemandedElts = getDemandAllEltsMask(Op);
6161 return computeKnownFPClass(Op, DemandedElts, InterestedClasses, Depth);
6162}
6163
6165 const APInt &DemandedElts,
6166 FPClassTest InterestedClasses,
6167 unsigned Depth) const {
6169
6170 if (const auto *CFP = dyn_cast<ConstantFPSDNode>(Op))
6171 return KnownFPClass(CFP->getValueAPF());
6172
6173 if (Depth >= MaxRecursionDepth)
6174 return Known;
6175
6176 if (Op.getOpcode() == ISD::UNDEF)
6177 return Known;
6178
6179 EVT VT = Op.getValueType();
6180 assert(VT.isFloatingPoint() && "Computing KnownFPClass on non-FP op!");
6181 assert((!VT.isFixedLengthVector() ||
6182 DemandedElts.getBitWidth() == VT.getVectorNumElements()) &&
6183 "Unexpected vector size");
6184
6185 if (!DemandedElts)
6186 return Known;
6187
6188 unsigned Opcode = Op.getOpcode();
6189 switch (Opcode) {
6190 case ISD::POISON: {
6191 Known.KnownFPClasses = fcNone;
6192 Known.SignBit = false;
6193 break;
6194 }
6195 case ISD::FNEG: {
6196 Known = computeKnownFPClass(Op.getOperand(0), DemandedElts,
6197 InterestedClasses, Depth + 1);
6198 Known.fneg();
6199 break;
6200 }
6201 case ISD::BUILD_VECTOR: {
6202 assert(!VT.isScalableVector());
6203 bool First = true;
6204 for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) {
6205 if (!DemandedElts[I])
6206 continue;
6207
6208 if (First) {
6209 Known =
6210 computeKnownFPClass(Op.getOperand(I), InterestedClasses, Depth + 1);
6211 First = false;
6212 } else {
6213 Known |=
6214 computeKnownFPClass(Op.getOperand(I), InterestedClasses, Depth + 1);
6215 }
6216
6217 if (Known.isUnknown())
6218 break;
6219 }
6220 break;
6221 }
6223 SDValue Src = Op.getOperand(0);
6224 auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6225 EVT SrcVT = Src.getValueType();
6226 if (SrcVT.isFixedLengthVector() && CIdx) {
6227 if (CIdx->getAPIntValue().ult(SrcVT.getVectorNumElements())) {
6228 APInt DemandedSrcElts = APInt::getOneBitSet(
6229 SrcVT.getVectorNumElements(), CIdx->getZExtValue());
6230 Known = computeKnownFPClass(Src, DemandedSrcElts, InterestedClasses,
6231 Depth + 1);
6232 } else {
6233 // Out of bounds index is poison.
6234 Known.KnownFPClasses = fcNone;
6235 }
6236 } else {
6237 Known = computeKnownFPClass(Src, InterestedClasses, Depth + 1);
6238 }
6239 break;
6240 }
6241 case ISD::SPLAT_VECTOR: {
6242 Known = computeKnownFPClass(Op.getOperand(0), InterestedClasses, Depth + 1);
6243 break;
6244 }
6245 case ISD::BITCAST: {
6246 // FIXME: It should not be necessary to check for an elementwise bitcast.
6247 // If a bitcast is not elementwise between vector / scalar types,
6248 // computeKnownBits already splices the known bits of the source elements
6249 // appropriately so as to line up with the bits of the result's demanded
6250 // elements.
6251 EVT SrcVT = Op.getOperand(0).getValueType();
6252 if (VT.isScalableVector() || SrcVT.isScalableVector())
6253 break;
6254 unsigned VTNumElts = VT.isVector() ? VT.getVectorNumElements() : 1;
6255 unsigned SrcVTNumElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1;
6256 if (VTNumElts != SrcVTNumElts)
6257 break;
6258
6259 KnownBits Bits = computeKnownBits(Op, DemandedElts, Depth + 1);
6261 break;
6262 }
6263 case ISD::FABS: {
6264 Known = computeKnownFPClass(Op.getOperand(0), DemandedElts,
6265 InterestedClasses, Depth + 1);
6266 Known.fabs();
6267 break;
6268 }
6269 case ISD::FCOPYSIGN: {
6270 Known = computeKnownFPClass(Op.getOperand(0), DemandedElts,
6271 InterestedClasses, Depth + 1);
6272 KnownFPClass KnownSign = computeKnownFPClass(Op.getOperand(1), DemandedElts,
6273 InterestedClasses, Depth + 1);
6274 Known.copysign(KnownSign);
6275 break;
6276 }
6277 case ISD::AssertNoFPClass: {
6278 Known = computeKnownFPClass(Op.getOperand(0), DemandedElts,
6279 InterestedClasses, Depth + 1);
6280 FPClassTest AssertedClasses =
6281 static_cast<FPClassTest>(Op->getConstantOperandVal(1));
6282 Known.KnownFPClasses &= ~AssertedClasses;
6283 break;
6284 }
6286 SDValue Src = Op.getOperand(0);
6287 EVT SrcVT = Src.getValueType();
6288 if (SrcVT.isFixedLengthVector()) {
6289 unsigned Idx = Op.getConstantOperandVal(1);
6290 unsigned NumSrcElts = SrcVT.getVectorNumElements();
6291
6292 APInt DemandedSrcElts = DemandedElts.zextOrTrunc(NumSrcElts).shl(Idx);
6293 Known = computeKnownFPClass(Src, DemandedSrcElts, InterestedClasses,
6294 Depth + 1);
6295 } else {
6296 Known = computeKnownFPClass(Src, InterestedClasses, Depth + 1);
6297 }
6298 break;
6299 }
6300 case ISD::INSERT_SUBVECTOR: {
6301 SDValue BaseVector = Op.getOperand(0);
6302 SDValue SubVector = Op.getOperand(1);
6303 EVT BaseVT = BaseVector.getValueType();
6304 if (BaseVT.isFixedLengthVector()) {
6305 unsigned Idx = Op.getConstantOperandVal(2);
6306 unsigned NumBaseElts = BaseVT.getVectorNumElements();
6307 unsigned NumSubElts = SubVector.getValueType().getVectorNumElements();
6308
6309 APInt DemandedMask =
6310 APInt::getBitsSet(NumBaseElts, Idx, Idx + NumSubElts);
6311 APInt DemandedSrcElts = DemandedElts & ~DemandedMask;
6312 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
6313
6314 if (!DemandedSrcElts.isZero())
6315 Known = computeKnownFPClass(BaseVector, DemandedSrcElts,
6316 InterestedClasses, Depth + 1);
6317 if (!DemandedSubElts.isZero()) {
6319 SubVector, DemandedSubElts, InterestedClasses, Depth + 1);
6320 Known = DemandedSrcElts.isZero() ? SubKnown : (Known | SubKnown);
6321 }
6322 } else {
6323 Known = computeKnownFPClass(SubVector, InterestedClasses, Depth + 1);
6324 if (!Known.isUnknown())
6325 Known |= computeKnownFPClass(BaseVector, InterestedClasses, Depth + 1);
6326 }
6327 break;
6328 }
6329 case ISD::SELECT:
6330 case ISD::VSELECT: {
6331 // TODO: Add adjustKnownFPClassForSelectArm clamp recognition as in
6332 // IR-level ValueTracking.
6333 KnownFPClass KnownFalseClass = computeKnownFPClass(
6334 Op.getOperand(2), DemandedElts, InterestedClasses, Depth + 1);
6335 if (KnownFalseClass.isUnknown())
6336 break;
6337 KnownFPClass KnownTrueClass = computeKnownFPClass(
6338 Op.getOperand(1), DemandedElts, InterestedClasses, Depth + 1);
6339 Known = KnownTrueClass.intersectWith(KnownFalseClass);
6340 break;
6341 }
6342 default:
6343 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
6344 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID) {
6345 TLI->computeKnownFPClassForTargetNode(Op, Known, DemandedElts, *this,
6346 Depth);
6347 }
6348 break;
6349 }
6350
6351 return Known;
6352}
6353
6355 unsigned Depth) const {
6356 APInt DemandedElts = getDemandAllEltsMask(Op);
6357 return isKnownNeverNaN(Op, DemandedElts, SNaN, Depth);
6358}
6359
6361 bool SNaN, unsigned Depth) const {
6362 assert(!DemandedElts.isZero() && "No demanded elements");
6363
6364 // If we're told that NaNs won't happen, assume they won't.
6365 if (Op->getFlags().hasNoNaNs())
6366 return true;
6367
6368 if (Depth >= MaxRecursionDepth)
6369 return false; // Limit search depth.
6370
6371 unsigned Opcode = Op.getOpcode();
6372 switch (Opcode) {
6373 case ISD::FADD:
6374 case ISD::FSUB:
6375 case ISD::FMUL:
6376 case ISD::FDIV:
6377 case ISD::FREM:
6378 case ISD::FSIN:
6379 case ISD::FCOS:
6380 case ISD::FTAN:
6381 case ISD::FASIN:
6382 case ISD::FACOS:
6383 case ISD::FATAN:
6384 case ISD::FATAN2:
6385 case ISD::FSINH:
6386 case ISD::FCOSH:
6387 case ISD::FTANH:
6388 case ISD::FMA:
6389 case ISD::FMULADD:
6390 case ISD::FMAD: {
6391 if (SNaN)
6392 return true;
6393 // TODO: Need isKnownNeverInfinity
6394 return false;
6395 }
6396 case ISD::FCANONICALIZE:
6397 case ISD::FEXP:
6398 case ISD::FEXP2:
6399 case ISD::FEXP10:
6400 case ISD::FTRUNC:
6401 case ISD::FFLOOR:
6402 case ISD::FCEIL:
6403 case ISD::FROUND:
6404 case ISD::FROUNDEVEN:
6405 case ISD::LROUND:
6406 case ISD::LLROUND:
6407 case ISD::FRINT:
6408 case ISD::LRINT:
6409 case ISD::LLRINT:
6410 case ISD::FNEARBYINT:
6411 case ISD::FLDEXP: {
6412 if (SNaN)
6413 return true;
6414 return isKnownNeverNaN(Op.getOperand(0), DemandedElts, SNaN, Depth + 1);
6415 }
6416 case ISD::FABS:
6417 case ISD::FNEG:
6418 case ISD::FCOPYSIGN: {
6419 return isKnownNeverNaN(Op.getOperand(0), DemandedElts, SNaN, Depth + 1);
6420 }
6421 case ISD::SELECT:
6422 return isKnownNeverNaN(Op.getOperand(1), DemandedElts, SNaN, Depth + 1) &&
6423 isKnownNeverNaN(Op.getOperand(2), DemandedElts, SNaN, Depth + 1);
6424 case ISD::FP_EXTEND:
6425 case ISD::FP_ROUND: {
6426 if (SNaN)
6427 return true;
6428 return isKnownNeverNaN(Op.getOperand(0), DemandedElts, SNaN, Depth + 1);
6429 }
6430 case ISD::SINT_TO_FP:
6431 case ISD::UINT_TO_FP:
6432 return true;
6433 case ISD::FSQRT: // Need is known positive
6434 case ISD::FLOG:
6435 case ISD::FLOG2:
6436 case ISD::FLOG10:
6437 case ISD::FPOWI:
6438 case ISD::FPOW: {
6439 if (SNaN)
6440 return true;
6441 // TODO: Refine on operand
6442 return false;
6443 }
6444 case ISD::FMINNUM:
6445 case ISD::FMAXNUM:
6446 case ISD::FMINIMUMNUM:
6447 case ISD::FMAXIMUMNUM: {
6448 // Only one needs to be known not-nan, since it will be returned if the
6449 // other ends up being one.
6450 return isKnownNeverNaN(Op.getOperand(0), DemandedElts, SNaN, Depth + 1) ||
6451 isKnownNeverNaN(Op.getOperand(1), DemandedElts, SNaN, Depth + 1);
6452 }
6453 case ISD::FMINNUM_IEEE:
6454 case ISD::FMAXNUM_IEEE: {
6455 if (SNaN)
6456 return true;
6457 // This can return a NaN if either operand is an sNaN, or if both operands
6458 // are NaN.
6459 return (isKnownNeverNaN(Op.getOperand(0), DemandedElts, false, Depth + 1) &&
6460 isKnownNeverSNaN(Op.getOperand(1), DemandedElts, Depth + 1)) ||
6461 (isKnownNeverNaN(Op.getOperand(1), DemandedElts, false, Depth + 1) &&
6462 isKnownNeverSNaN(Op.getOperand(0), DemandedElts, Depth + 1));
6463 }
6464 case ISD::FMINIMUM:
6465 case ISD::FMAXIMUM: {
6466 // TODO: Does this quiet or return the origina NaN as-is?
6467 return isKnownNeverNaN(Op.getOperand(0), DemandedElts, SNaN, Depth + 1) &&
6468 isKnownNeverNaN(Op.getOperand(1), DemandedElts, SNaN, Depth + 1);
6469 }
6471 SDValue Src = Op.getOperand(0);
6472 auto *Idx = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6473 EVT SrcVT = Src.getValueType();
6474 if (SrcVT.isFixedLengthVector() && Idx &&
6475 Idx->getAPIntValue().ult(SrcVT.getVectorNumElements())) {
6476 APInt DemandedSrcElts = APInt::getOneBitSet(SrcVT.getVectorNumElements(),
6477 Idx->getZExtValue());
6478 return isKnownNeverNaN(Src, DemandedSrcElts, SNaN, Depth + 1);
6479 }
6480 return isKnownNeverNaN(Src, SNaN, Depth + 1);
6481 }
6483 SDValue Src = Op.getOperand(0);
6484 if (Src.getValueType().isFixedLengthVector()) {
6485 unsigned Idx = Op.getConstantOperandVal(1);
6486 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
6487 APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
6488 return isKnownNeverNaN(Src, DemandedSrcElts, SNaN, Depth + 1);
6489 }
6490 return isKnownNeverNaN(Src, SNaN, Depth + 1);
6491 }
6492 case ISD::INSERT_SUBVECTOR: {
6493 SDValue BaseVector = Op.getOperand(0);
6494 SDValue SubVector = Op.getOperand(1);
6495 EVT BaseVectorVT = BaseVector.getValueType();
6496 if (BaseVectorVT.isFixedLengthVector()) {
6497 unsigned Idx = Op.getConstantOperandVal(2);
6498 unsigned NumBaseElts = BaseVectorVT.getVectorNumElements();
6499 unsigned NumSubElts = SubVector.getValueType().getVectorNumElements();
6500
6501 // Clear/Extract the bits at the position where the subvector will be
6502 // inserted.
6503 APInt DemandedMask =
6504 APInt::getBitsSet(NumBaseElts, Idx, Idx + NumSubElts);
6505 APInt DemandedSrcElts = DemandedElts & ~DemandedMask;
6506 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
6507
6508 bool NeverNaN = true;
6509 if (!DemandedSrcElts.isZero())
6510 NeverNaN &=
6511 isKnownNeverNaN(BaseVector, DemandedSrcElts, SNaN, Depth + 1);
6512 if (NeverNaN && !DemandedSubElts.isZero())
6513 NeverNaN &=
6514 isKnownNeverNaN(SubVector, DemandedSubElts, SNaN, Depth + 1);
6515 return NeverNaN;
6516 }
6517 return isKnownNeverNaN(BaseVector, SNaN, Depth + 1) &&
6518 isKnownNeverNaN(SubVector, SNaN, Depth + 1);
6519 }
6520 case ISD::BUILD_VECTOR: {
6521 unsigned NumElts = Op.getNumOperands();
6522 for (unsigned I = 0; I != NumElts; ++I)
6523 if (DemandedElts[I] &&
6524 !isKnownNeverNaN(Op.getOperand(I), SNaN, Depth + 1))
6525 return false;
6526 return true;
6527 }
6528 case ISD::SPLAT_VECTOR:
6529 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
6530 case ISD::AssertNoFPClass: {
6531 FPClassTest NoFPClass =
6532 static_cast<FPClassTest>(Op.getConstantOperandVal(1));
6533 if ((NoFPClass & fcNan) == fcNan)
6534 return true;
6535 if (SNaN && (NoFPClass & fcSNan) == fcSNan)
6536 return true;
6537 return isKnownNeverNaN(Op.getOperand(0), DemandedElts, SNaN, Depth + 1);
6538 }
6539 default:
6540 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
6541 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID) {
6542 return TLI->isKnownNeverNaNForTargetNode(Op, DemandedElts, *this, SNaN,
6543 Depth);
6544 }
6545 break;
6546 }
6547
6548 FPClassTest NanMask = SNaN ? fcSNan : fcNan;
6549 KnownFPClass Known = computeKnownFPClass(Op, DemandedElts, NanMask, Depth);
6550 return Known.isKnownNever(NanMask);
6551}
6552
6554 APInt DemandedElts = getDemandAllEltsMask(Op);
6555 return isKnownNeverLogicalZero(Op, DemandedElts, Depth);
6556}
6557
6559 const APInt &DemandedElts,
6560 unsigned Depth) const {
6561 assert(!DemandedElts.isZero() && "No demanded elements");
6562 EVT VT = Op.getValueType();
6564 computeKnownFPClass(Op, DemandedElts, fcZero | fcSubnormal, Depth);
6565 return Known.isKnownNeverLogicalZero(getDenormalMode(VT));
6566}
6567
6569 APInt DemandedElts = getDemandAllEltsMask(Op);
6570 return isKnownNeverZero(Op, DemandedElts, Depth);
6571}
6572
6574 unsigned Depth) const {
6575 if (Depth >= MaxRecursionDepth)
6576 return false; // Limit search depth.
6577
6578 EVT OpVT = Op.getValueType();
6579 unsigned BitWidth = OpVT.getScalarSizeInBits();
6580
6581 assert(!Op.getValueType().isFloatingPoint() &&
6582 "Floating point types unsupported - use isKnownNeverLogicalZero");
6583
6584 // If the value is a constant, we can obviously see if it is a zero or not.
6585 auto IsNeverZero = [BitWidth](const ConstantSDNode *C) {
6586 APInt V = C->getAPIntValue().zextOrTrunc(BitWidth);
6587 return !V.isZero();
6588 };
6589
6590 if (ISD::matchUnaryPredicate(Op, IsNeverZero))
6591 return true;
6592
6593 // TODO: Recognize more cases here. Most of the cases are also incomplete to
6594 // some degree.
6595 switch (Op.getOpcode()) {
6596 default:
6597 break;
6598
6599 case ISD::BUILD_VECTOR:
6600 // Are all operands of a build vector constant non-zero?
6601 if (all_of(enumerate(Op->ops()), [&](auto P) {
6602 auto *C = dyn_cast<ConstantSDNode>(P.value());
6603 return !DemandedElts[P.index()] || (C && IsNeverZero(C));
6604 }))
6605 return true;
6606 break;
6607
6608 case ISD::SPLAT_VECTOR:
6609 // Is the operand of a splat vector a constant non-zero?
6610 if (auto *C = dyn_cast<ConstantSDNode>(Op->getOperand(0)))
6611 if (IsNeverZero(C))
6612 return true;
6613 break;
6614
6616 SDValue InVec = Op.getOperand(0);
6617 SDValue EltNo = Op.getOperand(1);
6618 EVT VecVT = InVec.getValueType();
6619
6620 // Skip scalable vectors or implicit extensions.
6621 if (VecVT.isScalableVector() ||
6622 OpVT.getScalarSizeInBits() != VecVT.getScalarSizeInBits())
6623 break;
6624
6625 // If we know the element index, just demand that vector element, else for
6626 // an unknown element index, ignore DemandedElts and demand them all.
6627 const unsigned NumSrcElts = VecVT.getVectorNumElements();
6628 APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
6629 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
6630 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
6631 DemandedSrcElts =
6632 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
6633
6634 return isKnownNeverZero(InVec, DemandedSrcElts, Depth + 1);
6635 }
6636
6637 case ISD::OR:
6638 return isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1) ||
6639 isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6640
6641 case ISD::VSELECT:
6642 case ISD::SELECT:
6643 return isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1) &&
6644 isKnownNeverZero(Op.getOperand(2), DemandedElts, Depth + 1);
6645
6646 case ISD::SHL: {
6647 if (Op->getFlags().hasNoSignedWrap() || Op->getFlags().hasNoUnsignedWrap())
6648 return isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6649 KnownBits ValKnown =
6650 computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
6651 // 1 << X is never zero.
6652 if (ValKnown.One[0])
6653 return true;
6654 // If max shift cnt of known ones is non-zero, result is non-zero.
6655 APInt MaxCnt = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1)
6656 .getMaxValue();
6657 if (MaxCnt.ult(ValKnown.getBitWidth()) &&
6658 !ValKnown.One.shl(MaxCnt).isZero())
6659 return true;
6660 break;
6661 }
6662
6663 case ISD::VECTOR_SHUFFLE: {
6664 if (Op.getValueType().isScalableVector())
6665 return false;
6666
6667 unsigned NumElts = DemandedElts.getBitWidth();
6668
6669 // All demanded elements from LHS and RHS must be known non-zero.
6670 // Demanded elements with undef shuffle mask elements are unknown.
6671
6672 APInt DemandedLHS, DemandedRHS;
6673 auto *SVN = cast<ShuffleVectorSDNode>(Op);
6674 assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
6675 if (!getShuffleDemandedElts(NumElts, SVN->getMask(), DemandedElts,
6676 DemandedLHS, DemandedRHS))
6677 return false;
6678
6679 return (!DemandedLHS ||
6680 isKnownNeverZero(Op.getOperand(0), DemandedLHS, Depth + 1)) &&
6681 (!DemandedRHS ||
6682 isKnownNeverZero(Op.getOperand(1), DemandedRHS, Depth + 1));
6683 }
6684
6685 case ISD::UADDSAT:
6686 case ISD::UMAX:
6687 return isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1) ||
6688 isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6689
6690 case ISD::UMIN:
6691 return isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1) &&
6692 isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6693
6694 // For smin/smax: If either operand is known negative/positive
6695 // respectively we don't need the other to be known at all.
6696 case ISD::SMAX: {
6697 KnownBits Op1 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
6698 if (Op1.isStrictlyPositive())
6699 return true;
6700
6701 KnownBits Op0 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
6702 if (Op0.isStrictlyPositive())
6703 return true;
6704
6705 if (Op1.isNonZero() && Op0.isNonZero())
6706 return true;
6707
6708 return isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1) &&
6709 isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6710 }
6711 case ISD::SMIN: {
6712 KnownBits Op1 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
6713 if (Op1.isNegative())
6714 return true;
6715
6716 KnownBits Op0 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
6717 if (Op0.isNegative())
6718 return true;
6719
6720 if (Op1.isNonZero() && Op0.isNonZero())
6721 return true;
6722
6723 return isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1) &&
6724 isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6725 }
6726
6727 case ISD::ROTL:
6728 case ISD::ROTR:
6729 case ISD::BITREVERSE:
6730 case ISD::BSWAP:
6731 case ISD::CTPOP:
6732 case ISD::ABS:
6734 return isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6735
6736 case ISD::SRA:
6737 case ISD::SRL: {
6738 if (Op->getFlags().hasExact())
6739 return isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6740 KnownBits ValKnown =
6741 computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
6742 if (ValKnown.isNegative())
6743 return true;
6744 // If max shift cnt of known ones is non-zero, result is non-zero.
6745 APInt MaxCnt = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1)
6746 .getMaxValue();
6747 if (MaxCnt.ult(ValKnown.getBitWidth()) &&
6748 !ValKnown.One.lshr(MaxCnt).isZero())
6749 return true;
6750 break;
6751 }
6752 case ISD::UDIV:
6753 case ISD::SDIV:
6754 // div exact can only produce a zero if the dividend is zero.
6755 // TODO: For udiv this is also true if Op1 u<= Op0
6756 if (Op->getFlags().hasExact())
6757 return isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6758 break;
6759
6760 case ISD::ADD:
6761 if (Op->getFlags().hasNoUnsignedWrap())
6762 if (isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1) ||
6763 isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1))
6764 return true;
6765 // TODO: There are a lot more cases we can prove for add.
6766 break;
6767
6768 case ISD::SUB: {
6769 if (isNullConstant(Op.getOperand(0)))
6770 return isKnownNeverZero(Op.getOperand(1), DemandedElts, Depth + 1);
6771
6772 std::optional<bool> ne = KnownBits::ne(
6773 computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1),
6774 computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1));
6775 return ne && *ne;
6776 }
6777
6778 case ISD::MUL:
6779 if (Op->getFlags().hasNoSignedWrap() || Op->getFlags().hasNoUnsignedWrap())
6780 if (isKnownNeverZero(Op.getOperand(1), Depth + 1) &&
6781 isKnownNeverZero(Op.getOperand(0), Depth + 1))
6782 return true;
6783 break;
6784
6785 case ISD::ZERO_EXTEND:
6786 case ISD::SIGN_EXTEND:
6787 return isKnownNeverZero(Op.getOperand(0), DemandedElts, Depth + 1);
6788 case ISD::VSCALE: {
6790 const APInt &Multiplier = Op.getConstantOperandAPInt(0);
6791 ConstantRange CR =
6792 getVScaleRange(&F, Op.getScalarValueSizeInBits()).multiply(Multiplier);
6793 if (!CR.contains(APInt(CR.getBitWidth(), 0)))
6794 return true;
6795 break;
6796 }
6797 }
6798
6799 return computeKnownBits(Op, DemandedElts, Depth).isNonZero();
6800}
6801
6803 if (ConstantFPSDNode *C1 = isConstOrConstSplatFP(Op, true))
6804 return !C1->isNegative();
6805
6806 switch (Op.getOpcode()) {
6807 case ISD::FABS:
6808 case ISD::FEXP:
6809 case ISD::FEXP2:
6810 case ISD::FEXP10:
6811 return true;
6812 default:
6813 return false;
6814 }
6815
6816 llvm_unreachable("covered opcode switch");
6817}
6818
6820 assert(Use.getValueType().isFloatingPoint());
6821 const SDNode *User = Use.getUser();
6822 if (User->getFlags().hasNoSignedZeros())
6823 return true;
6824
6825 unsigned OperandNo = Use.getOperandNo();
6826 // Check if this use is insensitive to the sign of zero
6827 switch (User->getOpcode()) {
6828 case ISD::SETCC:
6829 // Comparisons: IEEE-754 specifies +0.0 == -0.0.
6830 case ISD::FABS:
6831 // fabs always produces +0.0.
6832 return true;
6833 case ISD::FCOPYSIGN:
6834 // copysign overwrites the sign bit of the first operand.
6835 return OperandNo == 0;
6836 case ISD::FADD:
6837 case ISD::FSUB: {
6838 // Arithmetic with non-zero constants fixes the uncertainty around the
6839 // sign bit.
6840 SDValue Other = User->getOperand(1 - OperandNo);
6842 }
6843 case ISD::FP_TO_SINT:
6844 case ISD::FP_TO_UINT:
6845 // fp-to-int conversions normalize signed zeros.
6846 return true;
6847 default:
6848 return false;
6849 }
6850}
6851
6853 if (Op->getFlags().hasNoSignedZeros())
6854 return true;
6855 // FIXME: Limit the amount of checked uses to not introduce a compile-time
6856 // regression. Ideally, this should be implemented as a demanded-bits
6857 // optimization that stems from the users.
6858 if (Op->use_size() > 2)
6859 return false;
6860 return all_of(Op->uses(),
6861 [&](const SDUse &Use) { return canIgnoreSignBitOfZero(Use); });
6862}
6863
6865 // Check the obvious case.
6866 if (A == B) return true;
6867
6868 // For negative and positive zero.
6871 if (CA->isZero() && CB->isZero()) return true;
6872
6873 // Otherwise they may not be equal.
6874 return false;
6875}
6876
6877// Only bits set in Mask must be negated, other bits may be arbitrary.
6879 if (isBitwiseNot(V, AllowUndefs))
6880 return V.getOperand(0);
6881
6882 // Handle any_extend (not (truncate X)) pattern, where Mask only sets
6883 // bits in the non-extended part.
6884 ConstantSDNode *MaskC = isConstOrConstSplat(Mask);
6885 if (!MaskC || V.getOpcode() != ISD::ANY_EXTEND)
6886 return SDValue();
6887 SDValue ExtArg = V.getOperand(0);
6888 if (ExtArg.getScalarValueSizeInBits() >=
6889 MaskC->getAPIntValue().getActiveBits() &&
6890 isBitwiseNot(ExtArg, AllowUndefs) &&
6891 ExtArg.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6892 ExtArg.getOperand(0).getOperand(0).getValueType() == V.getValueType())
6893 return ExtArg.getOperand(0).getOperand(0);
6894 return SDValue();
6895}
6896
6898 // Match masked merge pattern (X & ~M) op (Y & M)
6899 // Including degenerate case (X & ~M) op M
6900 auto MatchNoCommonBitsPattern = [&](SDValue Not, SDValue Mask,
6901 SDValue Other) {
6902 if (SDValue NotOperand =
6903 getBitwiseNotOperand(Not, Mask, /* AllowUndefs */ true)) {
6904 if (NotOperand->getOpcode() == ISD::ZERO_EXTEND ||
6905 NotOperand->getOpcode() == ISD::TRUNCATE)
6906 NotOperand = NotOperand->getOperand(0);
6907
6908 if (Other == NotOperand)
6909 return true;
6910 if (Other->getOpcode() == ISD::AND)
6911 return NotOperand == Other->getOperand(0) ||
6912 NotOperand == Other->getOperand(1);
6913 }
6914 return false;
6915 };
6916
6917 if (A->getOpcode() == ISD::ZERO_EXTEND || A->getOpcode() == ISD::TRUNCATE)
6918 A = A->getOperand(0);
6919
6920 if (B->getOpcode() == ISD::ZERO_EXTEND || B->getOpcode() == ISD::TRUNCATE)
6921 B = B->getOperand(0);
6922
6923 if (A->getOpcode() == ISD::AND)
6924 return MatchNoCommonBitsPattern(A->getOperand(0), A->getOperand(1), B) ||
6925 MatchNoCommonBitsPattern(A->getOperand(1), A->getOperand(0), B);
6926 return false;
6927}
6928
6929// FIXME: unify with llvm::haveNoCommonBitsSet.
6931 assert(A.getValueType() == B.getValueType() &&
6932 "Values must have the same type");
6935 return true;
6938}
6939
6940static SDValue FoldSTEP_VECTOR(const SDLoc &DL, EVT VT, SDValue Step,
6941 SelectionDAG &DAG) {
6942 if (cast<ConstantSDNode>(Step)->isZero())
6943 return DAG.getConstant(0, DL, VT);
6944
6945 return SDValue();
6946}
6947
6950 SelectionDAG &DAG) {
6951 int NumOps = Ops.size();
6952 assert(NumOps != 0 && "Can't build an empty vector!");
6953 assert(!VT.isScalableVector() &&
6954 "BUILD_VECTOR cannot be used with scalable types");
6955 assert(VT.getVectorNumElements() == (unsigned)NumOps &&
6956 "Incorrect element count in BUILD_VECTOR!");
6957
6958 // BUILD_VECTOR of UNDEFs is UNDEF.
6959 bool AllPoison = true;
6960 if (llvm::all_of(Ops, [&AllPoison](SDValue Op) {
6961 AllPoison &= Op.getOpcode() == ISD::POISON;
6962 return Op.isUndef();
6963 }))
6964 return AllPoison ? DAG.getPOISON(VT) : DAG.getUNDEF(VT);
6965
6966 // BUILD_VECTOR of seq extract/insert from the same vector + type is Identity.
6967 SDValue IdentitySrc;
6968 bool IsIdentity = true;
6969 for (int i = 0; i != NumOps; ++i) {
6970 if (Ops[i].getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6971 Ops[i].getOperand(0).getValueType() != VT ||
6972 (IdentitySrc && Ops[i].getOperand(0) != IdentitySrc) ||
6973 !isa<ConstantSDNode>(Ops[i].getOperand(1)) ||
6974 Ops[i].getConstantOperandAPInt(1) != i) {
6975 IsIdentity = false;
6976 break;
6977 }
6978 IdentitySrc = Ops[i].getOperand(0);
6979 }
6980 if (IsIdentity)
6981 return IdentitySrc;
6982
6983 return SDValue();
6984}
6985
6986/// Try to simplify vector concatenation to an input value, undef, or build
6987/// vector.
6990 SelectionDAG &DAG) {
6991 assert(!Ops.empty() && "Can't concatenate an empty list of vectors!");
6993 [Ops](SDValue Op) {
6994 return Ops[0].getValueType() == Op.getValueType();
6995 }) &&
6996 "Concatenation of vectors with inconsistent value types!");
6997 assert((Ops[0].getValueType().getVectorElementCount() * Ops.size()) ==
6998 VT.getVectorElementCount() &&
6999 "Incorrect element count in vector concatenation!");
7000
7001 if (Ops.size() == 1)
7002 return Ops[0];
7003
7004 // Concat of UNDEFs is UNDEF.
7005 bool AllPoison = true;
7006 if (llvm::all_of(Ops, [&AllPoison](SDValue Op) {
7007 AllPoison &= Op.getOpcode() == ISD::POISON;
7008 return Op.isUndef();
7009 }))
7010 return AllPoison ? DAG.getPOISON(VT) : DAG.getUNDEF(VT);
7011
7012 // Scan the operands and look for extract operations from a single source
7013 // that correspond to insertion at the same location via this concatenation:
7014 // concat (extract X, 0*subvec_elts), (extract X, 1*subvec_elts), ...
7015 SDValue IdentitySrc;
7016 bool IsIdentity = true;
7017 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
7018 SDValue Op = Ops[i];
7019 unsigned IdentityIndex = i * Op.getValueType().getVectorMinNumElements();
7020 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
7021 Op.getOperand(0).getValueType() != VT ||
7022 (IdentitySrc && Op.getOperand(0) != IdentitySrc) ||
7023 Op.getConstantOperandVal(1) != IdentityIndex) {
7024 IsIdentity = false;
7025 break;
7026 }
7027 assert((!IdentitySrc || IdentitySrc == Op.getOperand(0)) &&
7028 "Unexpected identity source vector for concat of extracts");
7029 IdentitySrc = Op.getOperand(0);
7030 }
7031 if (IsIdentity) {
7032 assert(IdentitySrc && "Failed to set source vector of extracts");
7033 return IdentitySrc;
7034 }
7035
7036 // The code below this point is only designed to work for fixed width
7037 // vectors, so we bail out for now.
7038 if (VT.isScalableVector())
7039 return SDValue();
7040
7041 // A CONCAT_VECTOR of scalar sources, such as UNDEF, BUILD_VECTOR and
7042 // single-element INSERT_VECTOR_ELT operands can be simplified to one big
7043 // BUILD_VECTOR.
7044 // FIXME: Add support for SCALAR_TO_VECTOR as well.
7045 EVT SVT = VT.getScalarType();
7047 for (SDValue Op : Ops) {
7048 EVT OpVT = Op.getValueType();
7049 if (Op.getOpcode() == ISD::POISON)
7050 Elts.append(OpVT.getVectorNumElements(), DAG.getPOISON(SVT));
7051 else if (Op.getOpcode() == ISD::UNDEF)
7052 Elts.append(OpVT.getVectorNumElements(), DAG.getUNDEF(SVT));
7053 else if (Op.getOpcode() == ISD::BUILD_VECTOR)
7054 Elts.append(Op->op_begin(), Op->op_end());
7055 else if (Op.getOpcode() == ISD::INSERT_VECTOR_ELT &&
7056 OpVT.getVectorNumElements() == 1 &&
7057 isNullConstant(Op.getOperand(2)))
7058 Elts.push_back(Op.getOperand(1));
7059 else
7060 return SDValue();
7061 }
7062
7063 // BUILD_VECTOR requires all inputs to be of the same type, find the
7064 // maximum type and extend them all.
7065 for (SDValue Op : Elts)
7066 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
7067
7068 if (SVT.bitsGT(VT.getScalarType())) {
7069 for (SDValue &Op : Elts) {
7070 if (Op.getOpcode() == ISD::POISON)
7071 Op = DAG.getPOISON(SVT);
7072 else if (Op.getOpcode() == ISD::UNDEF)
7073 Op = DAG.getUNDEF(SVT);
7074 else
7075 Op = DAG.getTargetLoweringInfo().isZExtFree(Op.getValueType(), SVT)
7076 ? DAG.getZExtOrTrunc(Op, DL, SVT)
7077 : DAG.getSExtOrTrunc(Op, DL, SVT);
7078 }
7079 }
7080
7081 SDValue V = DAG.getBuildVector(VT, DL, Elts);
7082 NewSDValueDbgMsg(V, "New node fold concat vectors: ", &DAG);
7083 return V;
7084}
7085
7086/// Gets or creates the specified node.
7087SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT) {
7088 SDVTList VTs = getVTList(VT);
7090 AddNodeIDNode(ID, Opcode, VTs, {});
7091 void *IP = nullptr;
7092 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
7093 return SDValue(E, 0);
7094
7095 auto *N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
7096 CSEMap.InsertNode(N, IP);
7097
7098 InsertNode(N);
7099 SDValue V = SDValue(N, 0);
7100 NewSDValueDbgMsg(V, "Creating new node: ", this);
7101 return V;
7102}
7103
7104SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
7105 SDValue N1) {
7106 SDNodeFlags Flags;
7107 if (Inserter)
7108 Flags = Inserter->getFlags();
7109 return getNode(Opcode, DL, VT, N1, Flags);
7110}
7111
7112SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
7113 SDValue N1, const SDNodeFlags Flags) {
7114 assert(N1.getOpcode() != ISD::DELETED_NODE && "Operand is DELETED_NODE!");
7115
7116 // Constant fold unary operations with a vector integer or float operand.
7117 switch (Opcode) {
7118 default:
7119 // FIXME: Entirely reasonable to perform folding of other unary
7120 // operations here as the need arises.
7121 break;
7122 case ISD::FNEG:
7123 case ISD::FABS:
7124 case ISD::FCEIL:
7125 case ISD::FTRUNC:
7126 case ISD::FFLOOR:
7127 case ISD::FP_EXTEND:
7128 case ISD::FP_TO_SINT:
7129 case ISD::FP_TO_UINT:
7130 case ISD::FP_TO_FP16:
7131 case ISD::FP_TO_BF16:
7132 case ISD::TRUNCATE:
7133 case ISD::ANY_EXTEND:
7134 case ISD::ZERO_EXTEND:
7135 case ISD::SIGN_EXTEND:
7136 case ISD::UINT_TO_FP:
7137 case ISD::SINT_TO_FP:
7138 case ISD::FP16_TO_FP:
7139 case ISD::BF16_TO_FP:
7140 case ISD::BITCAST:
7141 case ISD::ABS:
7143 case ISD::BITREVERSE:
7144 case ISD::BSWAP:
7145 case ISD::CTLZ:
7147 case ISD::CTTZ:
7149 case ISD::CTPOP:
7150 case ISD::CTLS:
7151 case ISD::VECREDUCE_ADD:
7156 case ISD::VECREDUCE_MUL:
7157 case ISD::VECREDUCE_AND:
7158 case ISD::VECREDUCE_OR:
7159 case ISD::VECREDUCE_XOR:
7160 case ISD::STEP_VECTOR: {
7161 SDValue Ops = {N1};
7162 if (SDValue Fold = FoldConstantArithmetic(Opcode, DL, VT, Ops))
7163 return Fold;
7164 }
7165 }
7166
7167 unsigned OpOpcode = N1.getNode()->getOpcode();
7168 switch (Opcode) {
7169 case ISD::STEP_VECTOR:
7170 assert(VT.isScalableVector() &&
7171 "STEP_VECTOR can only be used with scalable types");
7172 assert(OpOpcode == ISD::TargetConstant &&
7173 VT.getVectorElementType() == N1.getValueType() &&
7174 "Unexpected step operand");
7175 break;
7176 case ISD::FREEZE:
7177 assert(VT == N1.getValueType() && "Unexpected VT!");
7179 return N1;
7180 break;
7181 case ISD::TokenFactor:
7182 case ISD::MERGE_VALUES:
7184 return N1; // Factor, merge or concat of one node? No need.
7185 case ISD::BUILD_VECTOR: {
7186 // Attempt to simplify BUILD_VECTOR.
7187 SDValue Ops[] = {N1};
7188 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
7189 return V;
7190 break;
7191 }
7192 case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node");
7193 case ISD::FP_EXTEND:
7195 "Invalid FP cast!");
7196 if (N1.getValueType() == VT) return N1; // noop conversion.
7197 assert((!VT.isVector() || VT.getVectorElementCount() ==
7199 "Vector element count mismatch!");
7200 assert(N1.getValueType().bitsLT(VT) && "Invalid fpext node, dst < src!");
7201 if (N1.isUndef())
7202 return getUNDEF(VT);
7203 break;
7204 case ISD::FP_TO_SINT:
7205 case ISD::FP_TO_UINT:
7206 if (N1.isUndef())
7207 return getUNDEF(VT);
7208 break;
7209 case ISD::SINT_TO_FP:
7210 case ISD::UINT_TO_FP:
7211 // [us]itofp(undef) = 0, because the result value is bounded.
7212 if (N1.isUndef())
7213 return getConstantFP(0.0, DL, VT);
7214 break;
7215 case ISD::SIGN_EXTEND:
7216 assert(VT.isInteger() && N1.getValueType().isInteger() &&
7217 "Invalid SIGN_EXTEND!");
7218 assert(VT.isVector() == N1.getValueType().isVector() &&
7219 "SIGN_EXTEND result type type should be vector iff the operand "
7220 "type is vector!");
7221 if (N1.getValueType() == VT) return N1; // noop extension
7222 assert((!VT.isVector() || VT.getVectorElementCount() ==
7224 "Vector element count mismatch!");
7225 assert(N1.getValueType().bitsLT(VT) && "Invalid sext node, dst < src!");
7226 if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND) {
7227 SDNodeFlags Flags;
7228 if (OpOpcode == ISD::ZERO_EXTEND)
7229 Flags.setNonNeg(N1->getFlags().hasNonNeg());
7230 SDValue NewVal = getNode(OpOpcode, DL, VT, N1.getOperand(0), Flags);
7231 transferDbgValues(N1, NewVal);
7232 return NewVal;
7233 }
7234
7235 if (OpOpcode == ISD::POISON)
7236 return getPOISON(VT);
7237
7238 if (N1.isUndef())
7239 // sext(undef) = 0, because the top bits will all be the same.
7240 return getConstant(0, DL, VT);
7241
7242 // Skip unnecessary sext_inreg pattern:
7243 // (sext (trunc x)) -> x iff the upper bits are all signbits.
7244 if (OpOpcode == ISD::TRUNCATE) {
7245 SDValue OpOp = N1.getOperand(0);
7246 if (OpOp.getValueType() == VT) {
7247 unsigned NumSignExtBits =
7249 if (ComputeNumSignBits(OpOp) > NumSignExtBits) {
7250 transferDbgValues(N1, OpOp);
7251 return OpOp;
7252 }
7253 }
7254 }
7255 break;
7256 case ISD::ZERO_EXTEND:
7257 assert(VT.isInteger() && N1.getValueType().isInteger() &&
7258 "Invalid ZERO_EXTEND!");
7259 assert(VT.isVector() == N1.getValueType().isVector() &&
7260 "ZERO_EXTEND result type type should be vector iff the operand "
7261 "type is vector!");
7262 if (N1.getValueType() == VT) return N1; // noop extension
7263 assert((!VT.isVector() || VT.getVectorElementCount() ==
7265 "Vector element count mismatch!");
7266 assert(N1.getValueType().bitsLT(VT) && "Invalid zext node, dst < src!");
7267 if (OpOpcode == ISD::ZERO_EXTEND) { // (zext (zext x)) -> (zext x)
7268 SDNodeFlags Flags;
7269 Flags.setNonNeg(N1->getFlags().hasNonNeg());
7270 SDValue NewVal =
7271 getNode(ISD::ZERO_EXTEND, DL, VT, N1.getOperand(0), Flags);
7272 transferDbgValues(N1, NewVal);
7273 return NewVal;
7274 }
7275
7276 if (OpOpcode == ISD::POISON)
7277 return getPOISON(VT);
7278
7279 if (N1.isUndef())
7280 // zext(undef) = 0, because the top bits will be zero.
7281 return getConstant(0, DL, VT);
7282
7283 // Skip unnecessary zext_inreg pattern:
7284 // (zext (trunc x)) -> x iff the upper bits are known zero.
7285 // TODO: Remove (zext (trunc (and x, c))) exception which some targets
7286 // use to recognise zext_inreg patterns.
7287 if (OpOpcode == ISD::TRUNCATE) {
7288 SDValue OpOp = N1.getOperand(0);
7289 if (OpOp.getValueType() == VT) {
7290 if (OpOp.getOpcode() != ISD::AND) {
7293 if (MaskedValueIsZero(OpOp, HiBits)) {
7294 transferDbgValues(N1, OpOp);
7295 return OpOp;
7296 }
7297 }
7298 }
7299 }
7300 break;
7301 case ISD::ANY_EXTEND:
7302 assert(VT.isInteger() && N1.getValueType().isInteger() &&
7303 "Invalid ANY_EXTEND!");
7304 assert(VT.isVector() == N1.getValueType().isVector() &&
7305 "ANY_EXTEND result type type should be vector iff the operand "
7306 "type is vector!");
7307 if (N1.getValueType() == VT) return N1; // noop extension
7308 assert((!VT.isVector() || VT.getVectorElementCount() ==
7310 "Vector element count mismatch!");
7311 assert(N1.getValueType().bitsLT(VT) && "Invalid anyext node, dst < src!");
7312
7313 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
7314 OpOpcode == ISD::ANY_EXTEND) {
7315 SDNodeFlags Flags;
7316 if (OpOpcode == ISD::ZERO_EXTEND)
7317 Flags.setNonNeg(N1->getFlags().hasNonNeg());
7318 // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x)
7319 return getNode(OpOpcode, DL, VT, N1.getOperand(0), Flags);
7320 }
7321 if (N1.isUndef())
7322 return getUNDEF(VT);
7323
7324 // (ext (trunc x)) -> x
7325 if (OpOpcode == ISD::TRUNCATE) {
7326 SDValue OpOp = N1.getOperand(0);
7327 if (OpOp.getValueType() == VT) {
7328 transferDbgValues(N1, OpOp);
7329 return OpOp;
7330 }
7331 }
7332 break;
7333 case ISD::TRUNCATE:
7334 assert(VT.isInteger() && N1.getValueType().isInteger() &&
7335 "Invalid TRUNCATE!");
7336 assert(VT.isVector() == N1.getValueType().isVector() &&
7337 "TRUNCATE result type type should be vector iff the operand "
7338 "type is vector!");
7339 if (N1.getValueType() == VT) return N1; // noop truncate
7340 assert((!VT.isVector() || VT.getVectorElementCount() ==
7342 "Vector element count mismatch!");
7343 assert(N1.getValueType().bitsGT(VT) && "Invalid truncate node, src < dst!");
7344 if (OpOpcode == ISD::TRUNCATE)
7345 return getNode(ISD::TRUNCATE, DL, VT, N1.getOperand(0));
7346 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
7347 OpOpcode == ISD::ANY_EXTEND) {
7348 // If the source is smaller than the dest, we still need an extend.
7350 VT.getScalarType())) {
7351 SDNodeFlags Flags;
7352 if (OpOpcode == ISD::ZERO_EXTEND)
7353 Flags.setNonNeg(N1->getFlags().hasNonNeg());
7354 return getNode(OpOpcode, DL, VT, N1.getOperand(0), Flags);
7355 }
7356 if (N1.getOperand(0).getValueType().bitsGT(VT))
7357 return getNode(ISD::TRUNCATE, DL, VT, N1.getOperand(0));
7358 return N1.getOperand(0);
7359 }
7360 if (N1.isUndef())
7361 return getUNDEF(VT);
7362 if (OpOpcode == ISD::VSCALE && !NewNodesMustHaveLegalTypes)
7363 return getVScale(DL, VT,
7365 break;
7369 assert(VT.isVector() && "This DAG node is restricted to vector types.");
7370 assert(N1.getValueType().bitsLE(VT) &&
7371 "The input must be the same size or smaller than the result.");
7374 "The destination vector type must have fewer lanes than the input.");
7375 break;
7376 case ISD::ABS:
7377 assert(VT.isInteger() && VT == N1.getValueType() && "Invalid ABS!");
7378 if (N1.isUndef())
7379 return getConstant(0, DL, VT);
7380 break;
7382 assert(VT.isInteger() && VT == N1.getValueType() &&
7383 "Invalid ABS_MIN_POISON!");
7384 if (N1.isUndef())
7385 return getConstant(0, DL, VT);
7386 break;
7387 case ISD::BSWAP:
7388 assert(VT.isInteger() && VT == N1.getValueType() && "Invalid BSWAP!");
7389 assert((VT.getScalarSizeInBits() % 16 == 0) &&
7390 "BSWAP types must be a multiple of 16 bits!");
7391 if (N1.isUndef())
7392 return getUNDEF(VT);
7393 // bswap(bswap(X)) -> X.
7394 if (OpOpcode == ISD::BSWAP)
7395 return N1.getOperand(0);
7396 break;
7397 case ISD::BITREVERSE:
7398 assert(VT.isInteger() && VT == N1.getValueType() && "Invalid BITREVERSE!");
7399 if (N1.isUndef())
7400 return getUNDEF(VT);
7401 break;
7402 case ISD::BITCAST:
7404 "Cannot BITCAST between types of different sizes!");
7405 if (VT == N1.getValueType()) return N1; // noop conversion.
7406 if (OpOpcode == ISD::BITCAST) // bitconv(bitconv(x)) -> bitconv(x)
7407 return getNode(ISD::BITCAST, DL, VT, N1.getOperand(0));
7408 if (N1.isUndef())
7409 return getUNDEF(VT);
7410 break;
7412 assert(VT.isVector() && !N1.getValueType().isVector() &&
7413 (VT.getVectorElementType() == N1.getValueType() ||
7415 N1.getValueType().isInteger() &&
7417 "Illegal SCALAR_TO_VECTOR node!");
7418 if (N1.isUndef())
7419 return getUNDEF(VT);
7420 // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
7421 if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
7423 N1.getConstantOperandVal(1) == 0 &&
7424 N1.getOperand(0).getValueType() == VT)
7425 return N1.getOperand(0);
7426 break;
7427 case ISD::FNEG:
7428 // Negation of an unknown bag of bits is still completely undefined.
7429 if (N1.isUndef())
7430 return getUNDEF(VT);
7431
7432 if (OpOpcode == ISD::FNEG) // --X -> X
7433 return N1.getOperand(0);
7434 break;
7435 case ISD::FABS:
7436 if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X)
7437 return getNode(ISD::FABS, DL, VT, N1.getOperand(0));
7438 break;
7439 case ISD::VSCALE:
7440 assert(VT == N1.getValueType() && "Unexpected VT!");
7441 break;
7442 case ISD::CTPOP:
7443 if (N1.getValueType().getScalarType() == MVT::i1)
7444 return N1;
7445 break;
7446 case ISD::CTLZ:
7447 case ISD::CTTZ:
7448 if (N1.getValueType().getScalarType() == MVT::i1)
7449 return getNOT(DL, N1, N1.getValueType());
7450 break;
7451 case ISD::CTLS:
7452 if (N1.getValueType().getScalarType() == MVT::i1)
7453 return getConstant(0, DL, VT);
7454 break;
7455 case ISD::VECREDUCE_ADD:
7456 if (N1.getValueType().getScalarType() == MVT::i1)
7457 return getNode(ISD::VECREDUCE_XOR, DL, VT, N1);
7458 break;
7461 if (N1.getValueType().getScalarType() == MVT::i1)
7462 return getNode(ISD::VECREDUCE_OR, DL, VT, N1);
7463 break;
7466 if (N1.getValueType().getScalarType() == MVT::i1)
7467 return getNode(ISD::VECREDUCE_AND, DL, VT, N1);
7468 break;
7469 case ISD::SPLAT_VECTOR:
7470 assert(VT.isVector() && "Wrong return type!");
7471 // FIXME: Hexagon uses i32 scalar for a floating point zero vector so allow
7472 // that for now.
7474 (VT.isFloatingPoint() && N1.getValueType() == MVT::i32) ||
7476 N1.getValueType().isInteger() &&
7478 "Wrong operand type!");
7479 break;
7480 }
7481
7482 SDNode *N;
7483 SDVTList VTs = getVTList(VT);
7484 SDValue Ops[] = {N1};
7485 if (VT != MVT::Glue) { // Don't CSE glue producing nodes
7487 AddNodeIDNode(ID, Opcode, VTs, Ops);
7488 void *IP = nullptr;
7489 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
7490 E->intersectFlagsWith(Flags);
7491 return SDValue(E, 0);
7492 }
7493
7494 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
7495 N->setFlags(Flags);
7496 createOperands(N, Ops);
7497 CSEMap.InsertNode(N, IP);
7498 } else {
7499 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
7500 createOperands(N, Ops);
7501 }
7502
7503 InsertNode(N);
7504 SDValue V = SDValue(N, 0);
7505 NewSDValueDbgMsg(V, "Creating new node: ", this);
7506 return V;
7507}
7508
7509static APInt getIntegerIdentity(unsigned Opcode, unsigned BitWidth) {
7510 switch (Opcode) {
7511 default:
7512 llvm_unreachable("Unexpected integer identity opcode");
7513 case ISD::ADD:
7514 case ISD::OR:
7515 case ISD::XOR:
7516 case ISD::UMAX:
7517 return APInt::getZero(BitWidth);
7518 case ISD::MUL:
7519 return APInt(BitWidth, 1);
7520 case ISD::AND:
7521 case ISD::UMIN:
7523 case ISD::SMAX:
7525 case ISD::SMIN:
7527 }
7528}
7529
7530static std::optional<APInt> FoldValue(unsigned Opcode, const APInt &C1,
7531 const APInt &C2) {
7532 switch (Opcode) {
7533 case ISD::ADD: return C1 + C2;
7534 case ISD::SUB: return C1 - C2;
7535 case ISD::MUL: return C1 * C2;
7536 case ISD::AND: return C1 & C2;
7537 case ISD::OR: return C1 | C2;
7538 case ISD::XOR: return C1 ^ C2;
7539 case ISD::SHL: return C1 << C2;
7540 case ISD::SRL: return C1.lshr(C2);
7541 case ISD::SRA: return C1.ashr(C2);
7542 case ISD::ROTL: return C1.rotl(C2);
7543 case ISD::ROTR: return C1.rotr(C2);
7544 case ISD::SMIN: return C1.sle(C2) ? C1 : C2;
7545 case ISD::SMAX: return C1.sge(C2) ? C1 : C2;
7546 case ISD::UMIN: return C1.ule(C2) ? C1 : C2;
7547 case ISD::UMAX: return C1.uge(C2) ? C1 : C2;
7548 case ISD::SADDSAT: return C1.sadd_sat(C2);
7549 case ISD::UADDSAT: return C1.uadd_sat(C2);
7550 case ISD::SSUBSAT: return C1.ssub_sat(C2);
7551 case ISD::USUBSAT: return C1.usub_sat(C2);
7552 case ISD::SSHLSAT: return C1.sshl_sat(C2);
7553 case ISD::USHLSAT: return C1.ushl_sat(C2);
7554 case ISD::UDIV:
7555 if (!C2.getBoolValue())
7556 break;
7557 return C1.udiv(C2);
7558 case ISD::UREM:
7559 if (!C2.getBoolValue())
7560 break;
7561 return C1.urem(C2);
7562 case ISD::SDIV:
7563 if (!C2.getBoolValue())
7564 break;
7565 return C1.sdiv(C2);
7566 case ISD::SREM:
7567 if (!C2.getBoolValue())
7568 break;
7569 return C1.srem(C2);
7570 case ISD::AVGFLOORS:
7571 return APIntOps::avgFloorS(C1, C2);
7572 case ISD::AVGFLOORU:
7573 return APIntOps::avgFloorU(C1, C2);
7574 case ISD::AVGCEILS:
7575 return APIntOps::avgCeilS(C1, C2);
7576 case ISD::AVGCEILU:
7577 return APIntOps::avgCeilU(C1, C2);
7578 case ISD::ABDS:
7579 return APIntOps::abds(C1, C2);
7580 case ISD::ABDU:
7581 return APIntOps::abdu(C1, C2);
7582 case ISD::MULHS:
7583 return APIntOps::mulhs(C1, C2);
7584 case ISD::MULHU:
7585 return APIntOps::mulhu(C1, C2);
7586 case ISD::CLMUL:
7587 return APIntOps::clmul(C1, C2);
7588 case ISD::CLMULR:
7589 return APIntOps::clmulr(C1, C2);
7590 case ISD::CLMULH:
7591 return APIntOps::clmulh(C1, C2);
7592 case ISD::PEXT:
7593 return APIntOps::pext(C1, C2);
7594 case ISD::PDEP:
7595 return APIntOps::pdep(C1, C2);
7596 }
7597 return std::nullopt;
7598}
7599// Handle constant folding with UNDEF.
7600// TODO: Handle more cases.
7601static std::optional<APInt> FoldValueWithUndef(unsigned Opcode, const APInt &C1,
7602 bool IsUndef1, const APInt &C2,
7603 bool IsUndef2) {
7604 if (!(IsUndef1 || IsUndef2))
7605 return FoldValue(Opcode, C1, C2);
7606
7607 // Fold and(x, undef) -> 0
7608 // Fold mul(x, undef) -> 0
7609 if (Opcode == ISD::AND || Opcode == ISD::MUL)
7610 return APInt::getZero(C1.getBitWidth());
7611
7612 return std::nullopt;
7613}
7614
7616 const GlobalAddressSDNode *GA,
7617 const SDNode *N2) {
7618 if (GA->getOpcode() != ISD::GlobalAddress)
7619 return SDValue();
7620 if (!TLI->isOffsetFoldingLegal(GA))
7621 return SDValue();
7622 auto *C2 = dyn_cast<ConstantSDNode>(N2);
7623 if (!C2)
7624 return SDValue();
7625 int64_t Offset = C2->getSExtValue();
7626 switch (Opcode) {
7627 case ISD::ADD:
7628 case ISD::PTRADD:
7629 break;
7630 case ISD::SUB: Offset = -uint64_t(Offset); break;
7631 default: return SDValue();
7632 }
7633 return getGlobalAddress(GA->getGlobal(), SDLoc(C2), VT,
7634 GA->getOffset() + uint64_t(Offset));
7635}
7636
7638 switch (Opcode) {
7639 case ISD::SDIV:
7640 case ISD::UDIV:
7641 case ISD::SREM:
7642 case ISD::UREM: {
7643 // If a divisor is zero/undef or any element of a divisor vector is
7644 // zero/undef, the whole op is undef.
7645 assert(Ops.size() == 2 && "Div/rem should have 2 operands");
7646 SDValue Divisor = Ops[1];
7647 if (Divisor.isUndef() || isNullConstant(Divisor))
7648 return true;
7649
7650 return ISD::isBuildVectorOfConstantSDNodes(Divisor.getNode()) &&
7651 llvm::any_of(Divisor->op_values(),
7652 [](SDValue V) { return V.isUndef() ||
7653 isNullConstant(V); });
7654 // TODO: Handle signed overflow.
7655 }
7656 // TODO: Handle oversized shifts.
7657 default:
7658 return false;
7659 }
7660}
7661
7664 SDNodeFlags Flags) {
7665 // If the opcode is a target-specific ISD node, there's nothing we can
7666 // do here and the operand rules may not line up with the below, so
7667 // bail early.
7668 // We can't create a scalar CONCAT_VECTORS so skip it. It will break
7669 // for concats involving SPLAT_VECTOR. Concats of BUILD_VECTORS are handled by
7670 // foldCONCAT_VECTORS in getNode before this is called.
7671 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::CONCAT_VECTORS)
7672 return SDValue();
7673
7674 unsigned NumOps = Ops.size();
7675 if (NumOps == 0)
7676 return SDValue();
7677
7678 if (isUndef(Opcode, Ops))
7679 return getUNDEF(VT);
7680
7681 // Handle unary special cases.
7682 if (NumOps == 1) {
7683 SDValue N1 = Ops[0];
7684
7685 // Constant fold unary operations with an integer constant operand. Even
7686 // opaque constant will be folded, because the folding of unary operations
7687 // doesn't create new constants with different values. Nevertheless, the
7688 // opaque flag is preserved during folding to prevent future folding with
7689 // other constants.
7690 if (auto *C = dyn_cast<ConstantSDNode>(N1)) {
7691 const APInt &Val = C->getAPIntValue();
7692 switch (Opcode) {
7693 case ISD::SIGN_EXTEND:
7694 return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
7695 C->isTargetOpcode(), C->isOpaque());
7696 case ISD::TRUNCATE:
7697 if (C->isOpaque())
7698 break;
7699 [[fallthrough]];
7700 case ISD::ZERO_EXTEND:
7701 return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
7702 C->isTargetOpcode(), C->isOpaque());
7703 case ISD::ANY_EXTEND:
7704 // Some targets like RISCV prefer to sign extend some types.
7705 if (TLI->isSExtCheaperThanZExt(N1.getValueType(), VT))
7706 return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
7707 C->isTargetOpcode(), C->isOpaque());
7708 return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
7709 C->isTargetOpcode(), C->isOpaque());
7710 case ISD::ABS:
7711 return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(),
7712 C->isOpaque());
7714 if (Val.isMinSignedValue())
7715 return getPOISON(VT);
7716 return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(),
7717 C->isOpaque());
7718 case ISD::BITREVERSE:
7719 return getConstant(Val.reverseBits(), DL, VT, C->isTargetOpcode(),
7720 C->isOpaque());
7721 case ISD::BSWAP:
7722 return getConstant(Val.byteSwap(), DL, VT, C->isTargetOpcode(),
7723 C->isOpaque());
7724 case ISD::CTPOP:
7725 return getConstant(Val.popcount(), DL, VT, C->isTargetOpcode(),
7726 C->isOpaque());
7727 case ISD::CTLZ:
7729 return getConstant(Val.countl_zero(), DL, VT, C->isTargetOpcode(),
7730 C->isOpaque());
7731 case ISD::CTTZ:
7733 return getConstant(Val.countr_zero(), DL, VT, C->isTargetOpcode(),
7734 C->isOpaque());
7735 case ISD::CTLS:
7736 // CTLS returns the number of extra sign bits so subtract one.
7737 return getConstant(Val.getNumSignBits() - 1, DL, VT,
7738 C->isTargetOpcode(), C->isOpaque());
7739 case ISD::UINT_TO_FP:
7740 case ISD::SINT_TO_FP: {
7742 (void)FPV.convertFromAPInt(Val, Opcode == ISD::SINT_TO_FP,
7744 return getConstantFP(FPV, DL, VT);
7745 }
7746 case ISD::FP16_TO_FP:
7747 case ISD::BF16_TO_FP: {
7748 bool Ignored;
7749 APFloat FPV(Opcode == ISD::FP16_TO_FP ? APFloat::IEEEhalf()
7750 : APFloat::BFloat(),
7751 (Val.getBitWidth() == 16) ? Val : Val.trunc(16));
7752
7753 // This can return overflow, underflow, or inexact; we don't care.
7754 // FIXME need to be more flexible about rounding mode.
7756 &Ignored);
7757 return getConstantFP(FPV, DL, VT);
7758 }
7759 case ISD::STEP_VECTOR:
7760 if (SDValue V = FoldSTEP_VECTOR(DL, VT, N1, *this))
7761 return V;
7762 break;
7763 case ISD::BITCAST:
7764 if (VT == MVT::f16 && C->getValueType(0) == MVT::i16)
7765 return getConstantFP(APFloat(APFloat::IEEEhalf(), Val), DL, VT);
7766 if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
7767 return getConstantFP(APFloat(APFloat::IEEEsingle(), Val), DL, VT);
7768 if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
7769 return getConstantFP(APFloat(APFloat::IEEEdouble(), Val), DL, VT);
7770 if (VT == MVT::f128 && C->getValueType(0) == MVT::i128)
7771 return getConstantFP(APFloat(APFloat::IEEEquad(), Val), DL, VT);
7772 break;
7773 }
7774 }
7775
7776 // Constant fold unary operations with a floating point constant operand.
7777 if (auto *C = dyn_cast<ConstantFPSDNode>(N1)) {
7778 APFloat V = C->getValueAPF(); // make copy
7779 switch (Opcode) {
7780 case ISD::FNEG:
7781 V.changeSign();
7782 return getConstantFP(V, DL, VT);
7783 case ISD::FABS:
7784 V.clearSign();
7785 return getConstantFP(V, DL, VT);
7786 case ISD::FCEIL: {
7787 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardPositive);
7789 return getConstantFP(V, DL, VT);
7790 return SDValue();
7791 }
7792 case ISD::FTRUNC: {
7793 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardZero);
7795 return getConstantFP(V, DL, VT);
7796 return SDValue();
7797 }
7798 case ISD::FFLOOR: {
7799 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardNegative);
7801 return getConstantFP(V, DL, VT);
7802 return SDValue();
7803 }
7804 case ISD::FP_EXTEND: {
7805 bool ignored;
7806 // This can return overflow, underflow, or inexact; we don't care.
7807 // FIXME need to be more flexible about rounding mode.
7808 (void)V.convert(VT.getFltSemantics(), APFloat::rmNearestTiesToEven,
7809 &ignored);
7810 return getConstantFP(V, DL, VT);
7811 }
7812 case ISD::FP_TO_SINT:
7813 case ISD::FP_TO_UINT: {
7814 bool ignored;
7815 APSInt IntVal(VT.getSizeInBits(), Opcode == ISD::FP_TO_UINT);
7816 // FIXME need to be more flexible about rounding mode.
7818 V.convertToInteger(IntVal, APFloat::rmTowardZero, &ignored);
7819 if (s == APFloat::opInvalidOp) // inexact is OK, in fact usual
7820 break;
7821 return getConstant(IntVal, DL, VT);
7822 }
7823 case ISD::FP_TO_FP16:
7824 case ISD::FP_TO_BF16: {
7825 bool Ignored;
7826 // This can return overflow, underflow, or inexact; we don't care.
7827 // FIXME need to be more flexible about rounding mode.
7828 (void)V.convert(Opcode == ISD::FP_TO_FP16 ? APFloat::IEEEhalf()
7829 : APFloat::BFloat(),
7831 return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
7832 }
7833 case ISD::BITCAST:
7834 if (VT == MVT::i16 && C->getValueType(0) == MVT::f16)
7835 return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL,
7836 VT);
7837 if (VT == MVT::i16 && C->getValueType(0) == MVT::bf16)
7838 return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL,
7839 VT);
7840 if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
7841 return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), DL,
7842 VT);
7843 if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
7844 return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
7845 break;
7846 }
7847 }
7848
7849 // Early-out if we failed to constant fold a bitcast.
7850 if (Opcode == ISD::BITCAST)
7851 return SDValue();
7852
7853 // Constant fold integer vector reductions with constant BUILD_VECTORs.
7854 if ((Opcode == ISD::VECREDUCE_ADD || Opcode == ISD::VECREDUCE_SMAX ||
7855 Opcode == ISD::VECREDUCE_SMIN || Opcode == ISD::VECREDUCE_UMAX ||
7856 Opcode == ISD::VECREDUCE_UMIN || Opcode == ISD::VECREDUCE_MUL ||
7857 Opcode == ISD::VECREDUCE_OR || Opcode == ISD::VECREDUCE_XOR ||
7858 Opcode == ISD::VECREDUCE_AND) &&
7860 unsigned EltBits = N1.getValueType().getScalarSizeInBits();
7861 unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Opcode);
7862 APInt Acc = getIntegerIdentity(BaseOpcode, EltBits);
7863 for (SDValue Elt : N1->op_values()) {
7864 if (Elt.getOpcode() == ISD::POISON)
7865 return getPOISON(VT);
7866 if (Elt.isUndef() || cast<ConstantSDNode>(Elt)->isOpaque())
7867 return SDValue();
7868 APInt Value = cast<ConstantSDNode>(Elt)->getAPIntValue().trunc(EltBits);
7869 std::optional<APInt> Folded = FoldValue(BaseOpcode, Acc, Value);
7870 assert(Folded &&
7871 "Expected vector reduction base opcode to be foldable");
7872 Acc = *Folded;
7873 }
7874 EVT EltVT = N1.getValueType().getScalarType();
7875 return getAnyExtOrTrunc(getConstant(Acc, DL, EltVT), DL, VT);
7876 }
7877 }
7878
7879 // Handle binops special cases.
7880 if (NumOps == 2) {
7881 if (SDValue CFP = foldConstantFPMath(Opcode, DL, VT, Ops))
7882 return CFP;
7883
7884 if (auto *C1 = dyn_cast<ConstantSDNode>(Ops[0])) {
7885 if (auto *C2 = dyn_cast<ConstantSDNode>(Ops[1])) {
7886 if (C1->isOpaque() || C2->isOpaque())
7887 return SDValue();
7888
7889 std::optional<APInt> FoldAttempt =
7890 FoldValue(Opcode, C1->getAPIntValue(), C2->getAPIntValue());
7891 if (!FoldAttempt)
7892 return SDValue();
7893
7894 SDValue Folded = getConstant(*FoldAttempt, DL, VT);
7895 assert((!Folded || !VT.isVector()) &&
7896 "Can't fold vectors ops with scalar operands");
7897 return Folded;
7898 }
7899 }
7900
7901 // fold (add Sym, c) -> Sym+c
7903 return FoldSymbolOffset(Opcode, VT, GA, Ops[1].getNode());
7904 if (TLI->isCommutativeBinOp(Opcode))
7906 return FoldSymbolOffset(Opcode, VT, GA, Ops[0].getNode());
7907
7908 // fold (sext_in_reg c1) -> c2
7909 if (Opcode == ISD::SIGN_EXTEND_INREG) {
7910 EVT EVT = cast<VTSDNode>(Ops[1])->getVT();
7911
7912 auto SignExtendInReg = [&](APInt Val, llvm::EVT ConstantVT) {
7913 unsigned FromBits = EVT.getScalarSizeInBits();
7914 Val <<= Val.getBitWidth() - FromBits;
7915 Val.ashrInPlace(Val.getBitWidth() - FromBits);
7916 return getConstant(Val, DL, ConstantVT);
7917 };
7918
7919 if (auto *C1 = dyn_cast<ConstantSDNode>(Ops[0])) {
7920 const APInt &Val = C1->getAPIntValue();
7921 return SignExtendInReg(Val, VT);
7922 }
7923
7925 SmallVector<SDValue, 8> ScalarOps;
7926 llvm::EVT OpVT = Ops[0].getOperand(0).getValueType();
7927 for (int I = 0, E = VT.getVectorNumElements(); I != E; ++I) {
7928 SDValue Op = Ops[0].getOperand(I);
7929 if (Op.isUndef()) {
7930 ScalarOps.push_back(getUNDEF(OpVT));
7931 continue;
7932 }
7933 const APInt &Val = cast<ConstantSDNode>(Op)->getAPIntValue();
7934 ScalarOps.push_back(SignExtendInReg(Val, OpVT));
7935 }
7936 return getBuildVector(VT, DL, ScalarOps);
7937 }
7938
7939 if (Ops[0].getOpcode() == ISD::SPLAT_VECTOR &&
7940 isa<ConstantSDNode>(Ops[0].getOperand(0)))
7941 return getNode(ISD::SPLAT_VECTOR, DL, VT,
7942 SignExtendInReg(Ops[0].getConstantOperandAPInt(0),
7943 Ops[0].getOperand(0).getValueType()));
7944 }
7945 }
7946
7947 // Handle fshl/fshr special cases.
7948 if (Opcode == ISD::FSHL || Opcode == ISD::FSHR) {
7949 auto *C1 = dyn_cast<ConstantSDNode>(Ops[0]);
7950 auto *C2 = dyn_cast<ConstantSDNode>(Ops[1]);
7951 auto *C3 = dyn_cast<ConstantSDNode>(Ops[2]);
7952
7953 if (C1 && C2 && C3) {
7954 if (C1->isOpaque() || C2->isOpaque() || C3->isOpaque())
7955 return SDValue();
7956 const APInt &V1 = C1->getAPIntValue(), &V2 = C2->getAPIntValue(),
7957 &V3 = C3->getAPIntValue();
7958
7959 APInt FoldedVal = Opcode == ISD::FSHL ? APIntOps::fshl(V1, V2, V3)
7960 : APIntOps::fshr(V1, V2, V3);
7961 return getConstant(FoldedVal, DL, VT);
7962 }
7963 }
7964
7965 // Handle fma/fmad special cases.
7966 if (Opcode == ISD::FMA || Opcode == ISD::FMAD || Opcode == ISD::FMULADD) {
7967 assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
7968 assert(Ops[0].getValueType() == VT && Ops[1].getValueType() == VT &&
7969 Ops[2].getValueType() == VT && "FMA types must match!");
7973 if (C1 && C2 && C3) {
7974 APFloat V1 = C1->getValueAPF();
7975 const APFloat &V2 = C2->getValueAPF();
7976 const APFloat &V3 = C3->getValueAPF();
7977 if (Opcode == ISD::FMAD || Opcode == ISD::FMULADD) {
7978 V1.multiply(V2, APFloat::rmNearestTiesToEven);
7980 } else
7981 V1.fusedMultiplyAdd(V2, V3, APFloat::rmNearestTiesToEven);
7982 return getConstantFP(V1, DL, VT);
7983 }
7984 }
7985
7986 // This is for vector folding only from here on.
7987 if (!VT.isVector())
7988 return SDValue();
7989
7990 // Constant fold integer partial reductions with constant BUILD_VECTOR
7991 // operands. The reduction order is deliberately unspecified. Use the same
7992 // subvector layout as TargetLowering::expandPartialReduceMLA(), where input
7993 // lane I contributes to accumulator lane I % NumAccElts.
7994 if (Opcode == ISD::PARTIAL_REDUCE_SMLA ||
7995 Opcode == ISD::PARTIAL_REDUCE_UMLA ||
7996 Opcode == ISD::PARTIAL_REDUCE_SUMLA) {
7997 // These nodes have no scalar form, so unsupported cases must not fall
7998 // through to generic per-lane vector folding.
7999 if (!llvm::all_of(Ops, [](SDValue Op) {
8000 return ISD::isBuildVectorOfConstantSDNodes(Op.getNode());
8001 }))
8002 return SDValue();
8003
8004 unsigned AccEltBits = VT.getScalarSizeInBits();
8005 unsigned InputEltBits = Ops[1].getScalarValueSizeInBits();
8006 unsigned NumAccElts = VT.getVectorNumElements();
8007 unsigned NumInputElts = Ops[1].getValueType().getVectorNumElements();
8008 SmallVector<APInt, 8> Results(NumAccElts, APInt::getZero(AccEltBits));
8009 BitVector PoisonElts(NumAccElts);
8010
8011 for (unsigned I = 0; I != NumAccElts; ++I) {
8012 SDValue Elt = Ops[0].getOperand(I);
8013 if (Elt.getOpcode() == ISD::POISON) {
8014 PoisonElts.set(I);
8015 continue;
8016 }
8017 auto *C = dyn_cast<ConstantSDNode>(Elt);
8018 if (!C || C->isOpaque())
8019 return SDValue();
8020 Results[I] = C->getAPIntValue().trunc(AccEltBits);
8021 }
8022
8023 bool IsLHSSigned = Opcode != ISD::PARTIAL_REDUCE_UMLA;
8024 bool IsRHSSigned = Opcode == ISD::PARTIAL_REDUCE_SMLA;
8025 for (unsigned I = 0; I != NumInputElts; ++I) {
8026 const unsigned AccIdx = I % NumAccElts;
8027 SDValue LHSElt = Ops[1].getOperand(I);
8028 SDValue RHSElt = Ops[2].getOperand(I);
8029 if (LHSElt.getOpcode() == ISD::POISON ||
8030 RHSElt.getOpcode() == ISD::POISON) {
8031 PoisonElts.set(AccIdx);
8032 continue;
8033 }
8034
8035 auto *LHS = dyn_cast<ConstantSDNode>(LHSElt);
8036 auto *RHS = dyn_cast<ConstantSDNode>(RHSElt);
8037 if (!LHS || !RHS || LHS->isOpaque() || RHS->isOpaque())
8038 return SDValue();
8039
8040 APInt LHSVal = LHS->getAPIntValue().trunc(InputEltBits);
8041 APInt RHSVal = RHS->getAPIntValue().trunc(InputEltBits);
8042 LHSVal = IsLHSSigned ? LHSVal.sext(AccEltBits) : LHSVal.zext(AccEltBits);
8043 RHSVal = IsRHSSigned ? RHSVal.sext(AccEltBits) : RHSVal.zext(AccEltBits);
8044 Results[AccIdx] += LHSVal * RHSVal;
8045 }
8046
8047 // After type legalization the vector element type may not be a legal
8048 // scalar type (e.g. i16 on AArch64). Create the folded constants in the
8049 // promoted legal scalar type instead, matching the generic per-lane path
8050 // below. Bail out if legalization would narrow the type, since the lane
8051 // value would not fit.
8052 EVT AccEltVT = VT.getVectorElementType();
8053 EVT LegalSVT = AccEltVT;
8054 if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
8055 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
8056 if (LegalSVT.bitsLT(AccEltVT))
8057 return SDValue();
8058 }
8059
8060 SmallVector<SDValue, 8> ResultOps;
8061 for (unsigned I = 0; I != NumAccElts; ++I)
8062 ResultOps.push_back(
8063 PoisonElts[I] ? getPOISON(LegalSVT)
8064 : getConstant(Results[I].sext(LegalSVT.getSizeInBits()),
8065 DL, LegalSVT));
8066 return getBuildVector(VT, DL, ResultOps);
8067 }
8068
8069 ElementCount NumElts = VT.getVectorElementCount();
8070
8071 // See if we can fold through any bitcasted integer ops.
8072 if (NumOps == 2 && VT.isFixedLengthVector() && VT.isInteger() &&
8073 Ops[0].getValueType() == VT && Ops[1].getValueType() == VT &&
8074 (Ops[0].getOpcode() == ISD::BITCAST ||
8075 Ops[1].getOpcode() == ISD::BITCAST)) {
8078 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
8079 auto *BV2 = dyn_cast<BuildVectorSDNode>(N2);
8080 if (BV1 && BV2 && N1.getValueType().isInteger() &&
8081 N2.getValueType().isInteger()) {
8082 bool IsLE = getDataLayout().isLittleEndian();
8083 unsigned EltBits = VT.getScalarSizeInBits();
8084 SmallVector<APInt> RawBits1, RawBits2;
8085 BitVector UndefElts1, UndefElts2;
8086 if (BV1->getConstantRawBits(IsLE, EltBits, RawBits1, UndefElts1) &&
8087 BV2->getConstantRawBits(IsLE, EltBits, RawBits2, UndefElts2)) {
8088 SmallVector<APInt> RawBits;
8089 for (unsigned I = 0, E = NumElts.getFixedValue(); I != E; ++I) {
8090 std::optional<APInt> Fold = FoldValueWithUndef(
8091 Opcode, RawBits1[I], UndefElts1[I], RawBits2[I], UndefElts2[I]);
8092 if (!Fold)
8093 break;
8094 RawBits.push_back(*Fold);
8095 }
8096 if (RawBits.size() == NumElts.getFixedValue()) {
8097 // We have constant folded, but we might need to cast this again back
8098 // to the original (possibly legalized) type.
8099 EVT BVVT, BVEltVT;
8100 if (N1.getValueType() == VT) {
8101 BVVT = N1.getValueType();
8102 BVEltVT = BV1->getOperand(0).getValueType();
8103 } else {
8104 BVVT = N2.getValueType();
8105 BVEltVT = BV2->getOperand(0).getValueType();
8106 }
8107 unsigned BVEltBits = BVEltVT.getSizeInBits();
8108 SmallVector<APInt> DstBits;
8109 BitVector DstUndefs;
8111 DstBits, RawBits, DstUndefs,
8112 BitVector(RawBits.size(), false));
8113 SmallVector<SDValue> Ops(DstBits.size(), getUNDEF(BVEltVT));
8114 for (unsigned I = 0, E = DstBits.size(); I != E; ++I) {
8115 if (DstUndefs[I])
8116 continue;
8117 Ops[I] = getConstant(DstBits[I].sext(BVEltBits), DL, BVEltVT);
8118 }
8119 return getBitcast(VT, getBuildVector(BVVT, DL, Ops));
8120 }
8121 }
8122 }
8123 // Logic ops can be folded from raw integer bits - mainly for AVX512 masks.
8124 if (ISD::isBitwiseLogicOp(Opcode) && isa<ConstantSDNode>(N1) &&
8125 isa<ConstantSDNode>(N2)) {
8126 if (SDValue Res = FoldConstantArithmetic(Opcode, DL, N1.getValueType(),
8127 {N1, N2}, Flags))
8128 return getBitcast(VT, Res);
8129 }
8130 }
8131
8132 // Fold (mul step_vector(C0), C1) to (step_vector(C0 * C1)).
8133 // (shl step_vector(C0), C1) -> (step_vector(C0 << C1))
8134 if ((Opcode == ISD::MUL || Opcode == ISD::SHL) &&
8135 Ops[0].getOpcode() == ISD::STEP_VECTOR) {
8136 APInt RHSVal;
8137 if (ISD::isConstantSplatVector(Ops[1].getNode(), RHSVal)) {
8138 APInt NewStep = Opcode == ISD::MUL
8139 ? Ops[0].getConstantOperandAPInt(0) * RHSVal
8140 : Ops[0].getConstantOperandAPInt(0) << RHSVal;
8141 return getStepVector(DL, VT, NewStep);
8142 }
8143 }
8144
8145 auto IsScalarOrSameVectorSize = [NumElts](const SDValue &Op) {
8146 return !Op.getValueType().isVector() ||
8147 Op.getValueType().getVectorElementCount() == NumElts;
8148 };
8149
8150 auto IsBuildVectorSplatVectorOrUndef = [](const SDValue &Op) {
8151 return Op.isUndef() || Op.getOpcode() == ISD::CONDCODE ||
8152 Op.getOpcode() == ISD::BUILD_VECTOR ||
8153 Op.getOpcode() == ISD::SPLAT_VECTOR;
8154 };
8155
8156 // All operands must be vector types with the same number of elements as
8157 // the result type and must be either UNDEF or a build/splat vector
8158 // or UNDEF scalars.
8159 if (!llvm::all_of(Ops, IsBuildVectorSplatVectorOrUndef) ||
8160 !llvm::all_of(Ops, IsScalarOrSameVectorSize))
8161 return SDValue();
8162
8163 // If we are comparing vectors, then the result needs to be a i1 boolean that
8164 // is then extended back to the legal result type depending on how booleans
8165 // are represented.
8166 EVT SVT = (Opcode == ISD::SETCC ? MVT::i1 : VT.getScalarType());
8167 ISD::NodeType ExtendCode =
8168 (Opcode == ISD::SETCC && SVT != VT.getScalarType())
8169 ? TargetLowering::getExtendForContent(TLI->getBooleanContents(VT))
8171
8172 // Find legal integer scalar type for constant promotion and
8173 // ensure that its scalar size is at least as large as source.
8174 EVT LegalSVT = VT.getScalarType();
8175 if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
8176 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
8177 if (LegalSVT.bitsLT(VT.getScalarType()))
8178 return SDValue();
8179 }
8180
8181 // For scalable vector types we know we're dealing with SPLAT_VECTORs. We
8182 // only have one operand to check. For fixed-length vector types we may have
8183 // a combination of BUILD_VECTOR and SPLAT_VECTOR.
8184 unsigned NumVectorElts = NumElts.isScalable() ? 1 : NumElts.getFixedValue();
8185
8186 // Constant fold each scalar lane separately.
8187 SmallVector<SDValue, 4> ScalarResults;
8188 for (unsigned I = 0; I != NumVectorElts; I++) {
8189 SmallVector<SDValue, 4> ScalarOps;
8190 for (SDValue Op : Ops) {
8191 EVT InSVT = Op.getValueType().getScalarType();
8192 if (Op.getOpcode() != ISD::BUILD_VECTOR &&
8193 Op.getOpcode() != ISD::SPLAT_VECTOR) {
8194 if (Op.isUndef())
8195 ScalarOps.push_back(getUNDEF(InSVT));
8196 else
8197 ScalarOps.push_back(Op);
8198 continue;
8199 }
8200
8201 SDValue ScalarOp =
8202 Op.getOperand(Op.getOpcode() == ISD::SPLAT_VECTOR ? 0 : I);
8203 EVT ScalarVT = ScalarOp.getValueType();
8204
8205 // Build vector (integer) scalar operands may need implicit
8206 // truncation - do this before constant folding.
8207 if (ScalarVT.isInteger() && ScalarVT.bitsGT(InSVT)) {
8208 // Don't create illegally-typed nodes unless they're constants or undef
8209 // - if we fail to constant fold we can't guarantee the (dead) nodes
8210 // we're creating will be cleaned up before being visited for
8211 // legalization.
8212 if (NewNodesMustHaveLegalTypes && !ScalarOp.isUndef() &&
8213 !isa<ConstantSDNode>(ScalarOp) &&
8214 TLI->getTypeAction(*getContext(), InSVT) !=
8216 return SDValue();
8217 ScalarOp = getNode(ISD::TRUNCATE, DL, InSVT, ScalarOp);
8218 }
8219
8220 ScalarOps.push_back(ScalarOp);
8221 }
8222
8223 // Constant fold the scalar operands.
8224 SDValue ScalarResult = getNode(Opcode, DL, SVT, ScalarOps, Flags);
8225
8226 // Scalar folding only succeeded if the result is a constant or UNDEF.
8227 if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant &&
8228 ScalarResult.getOpcode() != ISD::ConstantFP)
8229 return SDValue();
8230
8231 // Legalize the (integer) scalar constant if necessary. We only do
8232 // this once we know the folding succeeded, since otherwise we would
8233 // get a node with illegal type which has a user.
8234 if (LegalSVT != SVT)
8235 ScalarResult = getNode(ExtendCode, DL, LegalSVT, ScalarResult);
8236
8237 ScalarResults.push_back(ScalarResult);
8238 }
8239
8240 SDValue V = NumElts.isScalable() ? getSplatVector(VT, DL, ScalarResults[0])
8241 : getBuildVector(VT, DL, ScalarResults);
8242 NewSDValueDbgMsg(V, "New node fold constant vector: ", this);
8243 return V;
8244}
8245
8248 // TODO: Add support for unary/ternary fp opcodes.
8249 if (Ops.size() != 2)
8250 return SDValue();
8251
8252 // TODO: We don't do any constant folding for strict FP opcodes here, but we
8253 // should. That will require dealing with a potentially non-default
8254 // rounding mode, checking the "opStatus" return value from the APFloat
8255 // math calculations, and possibly other variations.
8256 SDValue N1 = Ops[0];
8257 SDValue N2 = Ops[1];
8258 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1, /*AllowUndefs*/ false);
8259 ConstantFPSDNode *N2CFP = isConstOrConstSplatFP(N2, /*AllowUndefs*/ false);
8260 if (N1CFP && N2CFP) {
8261 APFloat C1 = N1CFP->getValueAPF(); // make copy
8262 const APFloat &C2 = N2CFP->getValueAPF();
8263 switch (Opcode) {
8264 case ISD::FADD:
8266 return getConstantFP(C1, DL, VT);
8267 case ISD::FSUB:
8269 return getConstantFP(C1, DL, VT);
8270 case ISD::FMUL:
8272 return getConstantFP(C1, DL, VT);
8273 case ISD::FDIV:
8275 return getConstantFP(C1, DL, VT);
8276 case ISD::FREM:
8277 C1.mod(C2);
8278 return getConstantFP(C1, DL, VT);
8279 case ISD::FCOPYSIGN:
8280 C1.copySign(C2);
8281 return getConstantFP(C1, DL, VT);
8282 case ISD::FMINNUM:
8283 return getConstantFP(minnum(C1, C2), DL, VT);
8284 case ISD::FMAXNUM:
8285 return getConstantFP(maxnum(C1, C2), DL, VT);
8286 case ISD::FMINIMUM:
8287 return getConstantFP(minimum(C1, C2), DL, VT);
8288 case ISD::FMAXIMUM:
8289 return getConstantFP(maximum(C1, C2), DL, VT);
8290 case ISD::FMINIMUMNUM:
8291 return getConstantFP(minimumnum(C1, C2), DL, VT);
8292 case ISD::FMAXIMUMNUM:
8293 return getConstantFP(maximumnum(C1, C2), DL, VT);
8294 default: break;
8295 }
8296 }
8297 if (N1CFP && Opcode == ISD::FP_ROUND) {
8298 APFloat C1 = N1CFP->getValueAPF(); // make copy
8299 bool Unused;
8300 // This can return overflow, underflow, or inexact; we don't care.
8301 // FIXME need to be more flexible about rounding mode.
8303 &Unused);
8304 return getConstantFP(C1, DL, VT);
8305 }
8306
8307 switch (Opcode) {
8308 case ISD::FSUB:
8309 // -0.0 - undef --> undef (consistent with "fneg undef")
8310 if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1, /*AllowUndefs*/ true))
8311 if (N1C && N1C->getValueAPF().isNegZero() && N2.isUndef())
8312 return getUNDEF(VT);
8313 [[fallthrough]];
8314
8315 case ISD::FADD:
8316 case ISD::FMUL:
8317 case ISD::FDIV:
8318 case ISD::FREM:
8319 // If both operands are undef, the result is undef. If 1 operand is undef,
8320 // the result is NaN. This should match the behavior of the IR optimizer.
8321 if (N1.isUndef() && N2.isUndef())
8322 return getUNDEF(VT);
8323 if (N1.isUndef() || N2.isUndef())
8325 }
8326 return SDValue();
8327}
8328
8330 const SDLoc &DL, EVT DstEltVT) {
8331 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
8332
8333 // If this is already the right type, we're done.
8334 if (SrcEltVT == DstEltVT)
8335 return SDValue(BV, 0);
8336
8337 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
8338 unsigned DstBitSize = DstEltVT.getSizeInBits();
8339
8340 // If this is a conversion of N elements of one type to N elements of another
8341 // type, convert each element. This handles FP<->INT cases.
8342 if (SrcBitSize == DstBitSize) {
8344 for (SDValue Op : BV->op_values()) {
8345 // If the vector element type is not legal, the BUILD_VECTOR operands
8346 // are promoted and implicitly truncated. Make that explicit here.
8347 if (Op.getValueType() != SrcEltVT)
8348 Op = getNode(ISD::TRUNCATE, DL, SrcEltVT, Op);
8349 Ops.push_back(getBitcast(DstEltVT, Op));
8350 }
8351 EVT VT = EVT::getVectorVT(*getContext(), DstEltVT,
8353 return getBuildVector(VT, DL, Ops);
8354 }
8355
8356 // Otherwise, we're growing or shrinking the elements. To avoid having to
8357 // handle annoying details of growing/shrinking FP values, we convert them to
8358 // int first.
8359 if (SrcEltVT.isFloatingPoint()) {
8360 // Convert the input float vector to a int vector where the elements are the
8361 // same sizes.
8362 EVT IntEltVT = EVT::getIntegerVT(*getContext(), SrcEltVT.getSizeInBits());
8363 if (SDValue Tmp = FoldConstantBuildVector(BV, DL, IntEltVT))
8365 DstEltVT);
8366 return SDValue();
8367 }
8368
8369 // Now we know the input is an integer vector. If the output is a FP type,
8370 // convert to integer first, then to FP of the right size.
8371 if (DstEltVT.isFloatingPoint()) {
8372 EVT IntEltVT = EVT::getIntegerVT(*getContext(), DstEltVT.getSizeInBits());
8373 if (SDValue Tmp = FoldConstantBuildVector(BV, DL, IntEltVT))
8375 DstEltVT);
8376 return SDValue();
8377 }
8378
8379 // Okay, we know the src/dst types are both integers of differing types.
8380 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
8381
8382 // Extract the constant raw bit data.
8383 BitVector UndefElements;
8384 SmallVector<APInt> RawBits;
8385 bool IsLE = getDataLayout().isLittleEndian();
8386 if (!BV->getConstantRawBits(IsLE, DstBitSize, RawBits, UndefElements))
8387 return SDValue();
8388
8390 for (unsigned I = 0, E = RawBits.size(); I != E; ++I) {
8391 if (UndefElements[I])
8392 Ops.push_back(getUNDEF(DstEltVT));
8393 else
8394 Ops.push_back(getConstant(RawBits[I], DL, DstEltVT));
8395 }
8396
8397 EVT VT = EVT::getVectorVT(*getContext(), DstEltVT, Ops.size());
8398 return getBuildVector(VT, DL, Ops);
8399}
8400
8402 assert(Val.getValueType().isInteger() && "Invalid AssertAlign!");
8403
8404 // There's no need to assert on a byte-aligned pointer. All pointers are at
8405 // least byte aligned.
8406 if (A == Align(1))
8407 return Val;
8408
8409 SDVTList VTs = getVTList(Val.getValueType());
8411 AddNodeIDNode(ID, ISD::AssertAlign, VTs, {Val});
8412 ID.AddInteger(A.value());
8413
8414 void *IP = nullptr;
8415 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
8416 return SDValue(E, 0);
8417
8418 auto *N =
8419 newSDNode<AssertAlignSDNode>(DL.getIROrder(), DL.getDebugLoc(), VTs, A);
8420 createOperands(N, {Val});
8421
8422 CSEMap.InsertNode(N, IP);
8423 InsertNode(N);
8424
8425 SDValue V(N, 0);
8426 NewSDValueDbgMsg(V, "Creating new node: ", this);
8427 return V;
8428}
8429
8430SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8431 SDValue N1, SDValue N2) {
8432 SDNodeFlags Flags;
8433 if (Inserter)
8434 Flags = Inserter->getFlags();
8435 return getNode(Opcode, DL, VT, N1, N2, Flags);
8436}
8437
8439 SDValue &N2) const {
8440 if (!TLI->isCommutativeBinOp(Opcode))
8441 return;
8442
8443 // Canonicalize:
8444 // binop(const, nonconst) -> binop(nonconst, const)
8447 bool N1CFP = isConstantFPBuildVectorOrConstantFP(N1);
8448 bool N2CFP = isConstantFPBuildVectorOrConstantFP(N2);
8449 if ((N1C && !N2C) || (N1CFP && !N2CFP))
8450 std::swap(N1, N2);
8451
8452 // Canonicalize:
8453 // binop(splat(x), step_vector) -> binop(step_vector, splat(x))
8454 else if (N1.getOpcode() == ISD::SPLAT_VECTOR &&
8456 std::swap(N1, N2);
8457}
8458
8459SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8460 SDValue N1, SDValue N2, const SDNodeFlags Flags) {
8462 N2.getOpcode() != ISD::DELETED_NODE &&
8463 "Operand is DELETED_NODE!");
8464
8465 canonicalizeCommutativeBinop(Opcode, N1, N2);
8466
8467 auto *N1C = dyn_cast<ConstantSDNode>(N1);
8468 auto *N2C = dyn_cast<ConstantSDNode>(N2);
8469
8470 // Don't allow undefs in vector splats - we might be returning N2 when folding
8471 // to zero etc.
8472 ConstantSDNode *N2CV =
8473 isConstOrConstSplat(N2, /*AllowUndefs*/ false, /*AllowTruncation*/ true);
8474
8475 switch (Opcode) {
8476 default: break;
8477 case ISD::TokenFactor:
8478 assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
8479 N2.getValueType() == MVT::Other && "Invalid token factor!");
8480 // Fold trivial token factors.
8481 if (N1.getOpcode() == ISD::EntryToken) return N2;
8482 if (N2.getOpcode() == ISD::EntryToken) return N1;
8483 if (N1 == N2) return N1;
8484 break;
8485 case ISD::BUILD_VECTOR: {
8486 // Attempt to simplify BUILD_VECTOR.
8487 SDValue Ops[] = {N1, N2};
8488 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
8489 return V;
8490 break;
8491 }
8492 case ISD::CONCAT_VECTORS: {
8493 SDValue Ops[] = {N1, N2};
8494 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
8495 return V;
8496 break;
8497 }
8498 case ISD::AND:
8499 assert(VT.isInteger() && "This operator does not apply to FP types!");
8500 assert(N1.getValueType() == N2.getValueType() &&
8501 N1.getValueType() == VT && "Binary operator types must match!");
8502 // (X & 0) -> 0. This commonly occurs when legalizing i64 values, so it's
8503 // worth handling here.
8504 if (N2CV && N2CV->isZero())
8505 return N2;
8506 if (N2CV && N2CV->isAllOnes()) // X & -1 -> X
8507 return N1;
8508 break;
8509 case ISD::OR:
8510 case ISD::XOR:
8511 case ISD::ADD:
8512 case ISD::PTRADD:
8513 case ISD::SUB:
8514 assert(VT.isInteger() && "This operator does not apply to FP types!");
8515 assert(N1.getValueType() == N2.getValueType() &&
8516 N1.getValueType() == VT && "Binary operator types must match!");
8517 // The equal operand types requirement is unnecessarily strong for PTRADD.
8518 // However, the SelectionDAGBuilder does not generate PTRADDs with different
8519 // operand types, and we'd need to re-implement GEP's non-standard wrapping
8520 // logic everywhere where PTRADDs may be folded or combined to properly
8521 // support them. If/when we introduce pointer types to the SDAG, we will
8522 // need to relax this constraint.
8523
8524 // (X ^|+- 0) -> X. This commonly occurs when legalizing i64 values, so
8525 // it's worth handling here.
8526 if (N2CV && N2CV->isZero())
8527 return N1;
8528 if ((Opcode == ISD::ADD || Opcode == ISD::SUB) &&
8529 VT.getScalarType() == MVT::i1)
8530 return getNode(ISD::XOR, DL, VT, N1, N2);
8531 // Fold (add (vscale * C0), (vscale * C1)) to (vscale * (C0 + C1)).
8532 if (Opcode == ISD::ADD && N1.getOpcode() == ISD::VSCALE &&
8533 N2.getOpcode() == ISD::VSCALE) {
8534 const APInt &C1 = N1->getConstantOperandAPInt(0);
8535 const APInt &C2 = N2->getConstantOperandAPInt(0);
8536 return getVScale(DL, VT, C1 + C2);
8537 }
8538 break;
8539 case ISD::MUL:
8540 assert(VT.isInteger() && "This operator does not apply to FP types!");
8541 assert(N1.getValueType() == N2.getValueType() &&
8542 N1.getValueType() == VT && "Binary operator types must match!");
8543 if (VT.getScalarType() == MVT::i1)
8544 return getNode(ISD::AND, DL, VT, N1, N2);
8545 if (N2CV && N2CV->isZero())
8546 return N2;
8547 if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
8548 const APInt &MulImm = N1->getConstantOperandAPInt(0);
8549 const APInt &N2CImm = N2C->getAPIntValue();
8550 return getVScale(DL, VT, MulImm * N2CImm);
8551 }
8552 break;
8553 case ISD::UDIV:
8554 case ISD::UREM:
8555 case ISD::MULHU:
8556 case ISD::MULHS:
8557 case ISD::SDIV:
8558 case ISD::SREM:
8559 case ISD::SADDSAT:
8560 case ISD::SSUBSAT:
8561 case ISD::UADDSAT:
8562 case ISD::USUBSAT:
8563 assert(VT.isInteger() && "This operator does not apply to FP types!");
8564 assert(N1.getValueType() == N2.getValueType() &&
8565 N1.getValueType() == VT && "Binary operator types must match!");
8566 if (VT.getScalarType() == MVT::i1) {
8567 // fold (add_sat x, y) -> (or x, y) for bool types.
8568 if (Opcode == ISD::SADDSAT || Opcode == ISD::UADDSAT)
8569 return getNode(ISD::OR, DL, VT, N1, N2);
8570 // fold (sub_sat x, y) -> (and x, ~y) for bool types.
8571 if (Opcode == ISD::SSUBSAT || Opcode == ISD::USUBSAT)
8572 return getNode(ISD::AND, DL, VT, N1, getNOT(DL, N2, VT));
8573 }
8574 break;
8575 case ISD::SCMP:
8576 case ISD::UCMP:
8577 assert(N1.getValueType() == N2.getValueType() &&
8578 "Types of operands of UCMP/SCMP must match");
8579 assert(N1.getValueType().isVector() == VT.isVector() &&
8580 "Operands and return type of must both be scalars or vectors");
8581 if (VT.isVector())
8584 "Result and operands must have the same number of elements");
8585 break;
8586 case ISD::AVGFLOORS:
8587 case ISD::AVGFLOORU:
8588 case ISD::AVGCEILS:
8589 case ISD::AVGCEILU:
8590 assert(VT.isInteger() && "This operator does not apply to FP types!");
8591 assert(N1.getValueType() == N2.getValueType() &&
8592 N1.getValueType() == VT && "Binary operator types must match!");
8593 break;
8594 case ISD::ABDS:
8595 case ISD::ABDU:
8596 assert(VT.isInteger() && "This operator does not apply to FP types!");
8597 assert(N1.getValueType() == N2.getValueType() &&
8598 N1.getValueType() == VT && "Binary operator types must match!");
8599 if (VT.getScalarType() == MVT::i1)
8600 return getNode(ISD::XOR, DL, VT, N1, N2);
8601 break;
8602 case ISD::SMIN:
8603 case ISD::UMAX:
8604 assert(VT.isInteger() && "This operator does not apply to FP types!");
8605 assert(N1.getValueType() == N2.getValueType() &&
8606 N1.getValueType() == VT && "Binary operator types must match!");
8607 if (VT.getScalarType() == MVT::i1)
8608 return getNode(ISD::OR, DL, VT, N1, N2);
8609 break;
8610 case ISD::SMAX:
8611 case ISD::UMIN:
8612 assert(VT.isInteger() && "This operator does not apply to FP types!");
8613 assert(N1.getValueType() == N2.getValueType() &&
8614 N1.getValueType() == VT && "Binary operator types must match!");
8615 if (VT.getScalarType() == MVT::i1)
8616 return getNode(ISD::AND, DL, VT, N1, N2);
8617 break;
8618 case ISD::FADD:
8619 case ISD::FSUB:
8620 case ISD::FMUL:
8621 case ISD::FDIV:
8622 case ISD::FREM:
8623 assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
8624 assert(N1.getValueType() == N2.getValueType() &&
8625 N1.getValueType() == VT && "Binary operator types must match!");
8626 if (SDValue V = simplifyFPBinop(Opcode, N1, N2, Flags))
8627 return V;
8628 break;
8629 case ISD::FCOPYSIGN: // N1 and result must match. N1/N2 need not match.
8630 assert(N1.getValueType() == VT &&
8633 "Invalid FCOPYSIGN!");
8634 break;
8635 case ISD::SHL:
8636 if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
8637 const APInt &MulImm = N1->getConstantOperandAPInt(0);
8638 const APInt &ShiftImm = N2C->getAPIntValue();
8639 return getVScale(DL, VT, MulImm << ShiftImm);
8640 }
8641 [[fallthrough]];
8642 case ISD::SRA:
8643 case ISD::SRL:
8644 if (SDValue V = simplifyShift(N1, N2))
8645 return V;
8646 [[fallthrough]];
8647 case ISD::ROTL:
8648 case ISD::ROTR:
8649 case ISD::SSHLSAT:
8650 case ISD::USHLSAT:
8651 assert(VT == N1.getValueType() &&
8652 "Shift operators return type must be the same as their first arg");
8653 assert(VT.isInteger() && N2.getValueType().isInteger() &&
8654 "Shifts only work on integers");
8655 assert((!VT.isVector() || VT == N2.getValueType()) &&
8656 "Vector shift amounts must be in the same as their first arg");
8657 // Verify that the shift amount VT is big enough to hold valid shift
8658 // amounts. This catches things like trying to shift an i1024 value by an
8659 // i8, which is easy to fall into in generic code that uses
8660 // TLI.getShiftAmount().
8663 "Invalid use of small shift amount with oversized value!");
8664
8665 // Always fold shifts of i1 values so the code generator doesn't need to
8666 // handle them. Since we know the size of the shift has to be less than the
8667 // size of the value, the shift/rotate count is guaranteed to be zero.
8668 if (VT == MVT::i1)
8669 return N1;
8670 if (N2CV && N2CV->isZero())
8671 return N1;
8672 break;
8673 case ISD::FP_ROUND:
8675 VT.bitsLE(N1.getValueType()) && N2C &&
8676 (N2C->getZExtValue() == 0 || N2C->getZExtValue() == 1) &&
8677 N2.getOpcode() == ISD::TargetConstant && "Invalid FP_ROUND!");
8678 if (N1.getValueType() == VT) return N1; // noop conversion.
8679 break;
8680 case ISD::IS_FPCLASS: {
8682 "IS_FPCLASS is used for a non-floating type");
8683 assert(isa<ConstantSDNode>(N2) && "FPClassTest is not Constant");
8684 // is.fpclass(poison, mask) -> poison
8685 if (N1.getOpcode() == ISD::POISON)
8686 return getPOISON(VT);
8687 FPClassTest Mask = static_cast<FPClassTest>(N2->getAsZExtVal());
8688 // If all tests are made, it doesn't matter what the value is.
8689 if ((Mask & fcAllFlags) == fcAllFlags)
8690 return getBoolConstant(true, DL, VT, N1.getValueType());
8691 if ((Mask & fcAllFlags) == 0)
8692 return getBoolConstant(false, DL, VT, N1.getValueType());
8693 break;
8694 }
8695 case ISD::AssertNoFPClass: {
8697 "AssertNoFPClass is used for a non-floating type");
8698 assert(isa<ConstantSDNode>(N2) && "NoFPClass is not Constant");
8699 FPClassTest NoFPClass = static_cast<FPClassTest>(N2->getAsZExtVal());
8700 assert(llvm::to_underlying(NoFPClass) <=
8702 "FPClassTest value too large");
8703 (void)NoFPClass;
8704 break;
8705 }
8706 case ISD::AssertSext:
8707 case ISD::AssertZext: {
8708 EVT EVT = cast<VTSDNode>(N2)->getVT();
8709 assert(VT == N1.getValueType() && "Not an inreg extend!");
8710 assert(VT.isInteger() && EVT.isInteger() &&
8711 "Cannot *_EXTEND_INREG FP types");
8712 assert(!EVT.isVector() &&
8713 "AssertSExt/AssertZExt type should be the vector element type "
8714 "rather than the vector type!");
8715 assert(EVT.bitsLE(VT.getScalarType()) && "Not extending!");
8716 if (VT.getScalarType() == EVT) return N1; // noop assertion.
8717 break;
8718 }
8720 EVT EVT = cast<VTSDNode>(N2)->getVT();
8721 assert(VT == N1.getValueType() && "Not an inreg extend!");
8722 assert(VT.isInteger() && EVT.isInteger() &&
8723 "Cannot *_EXTEND_INREG FP types");
8724 assert(EVT.isVector() == VT.isVector() &&
8725 "SIGN_EXTEND_INREG type should be vector iff the operand "
8726 "type is vector!");
8727 assert((!EVT.isVector() ||
8729 "Vector element counts must match in SIGN_EXTEND_INREG");
8730 assert(EVT.getScalarType().bitsLE(VT.getScalarType()) && "Not extending!");
8731 if (EVT == VT) return N1; // Not actually extending
8732 break;
8733 }
8735 case ISD::FP_TO_UINT_SAT: {
8736 assert(VT.isInteger() && cast<VTSDNode>(N2)->getVT().isInteger() &&
8737 N1.getValueType().isFloatingPoint() && "Invalid FP_TO_*INT_SAT");
8738 assert(N1.getValueType().isVector() == VT.isVector() &&
8739 "FP_TO_*INT_SAT type should be vector iff the operand type is "
8740 "vector!");
8741 assert((!VT.isVector() || VT.getVectorElementCount() ==
8743 "Vector element counts must match in FP_TO_*INT_SAT");
8744 assert(!cast<VTSDNode>(N2)->getVT().isVector() &&
8745 "Type to saturate to must be a scalar.");
8746 assert(cast<VTSDNode>(N2)->getVT().bitsLE(VT.getScalarType()) &&
8747 "Not extending!");
8748 break;
8749 }
8752 "The result of EXTRACT_VECTOR_ELT must be at least as wide as the \
8753 element type of the vector.");
8754
8755 // Extract from an undefined value or using an undefined index is undefined.
8756 if (N1.isUndef() || N2.isUndef())
8757 return getUNDEF(VT);
8758
8759 // EXTRACT_VECTOR_ELT of out-of-bounds element is POISON for fixed length
8760 // vectors. For scalable vectors we will provide appropriate support for
8761 // dealing with arbitrary indices.
8762 if (N2C && N1.getValueType().isFixedLengthVector() &&
8763 N2C->getAPIntValue().uge(N1.getValueType().getVectorNumElements()))
8764 return getPOISON(VT);
8765
8766 // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
8767 // expanding copies of large vectors from registers. This only works for
8768 // fixed length vectors, since we need to know the exact number of
8769 // elements.
8770 if (N2C && N1.getOpcode() == ISD::CONCAT_VECTORS &&
8772 unsigned Factor = N1.getOperand(0).getValueType().getVectorNumElements();
8773 return getExtractVectorElt(DL, VT,
8774 N1.getOperand(N2C->getZExtValue() / Factor),
8775 N2C->getZExtValue() % Factor);
8776 }
8777
8778 // EXTRACT_VECTOR_ELT of BUILD_VECTOR or SPLAT_VECTOR is often formed while
8779 // lowering is expanding large vector constants.
8780 if (N2C && (N1.getOpcode() == ISD::BUILD_VECTOR ||
8781 N1.getOpcode() == ISD::SPLAT_VECTOR)) {
8784 "BUILD_VECTOR used for scalable vectors");
8785 unsigned Index =
8786 N1.getOpcode() == ISD::BUILD_VECTOR ? N2C->getZExtValue() : 0;
8787 SDValue Elt = N1.getOperand(Index);
8788
8789 if (VT != Elt.getValueType())
8790 // If the vector element type is not legal, the BUILD_VECTOR operands
8791 // are promoted and implicitly truncated, and the result implicitly
8792 // extended. Make that explicit here.
8793 Elt = getAnyExtOrTrunc(Elt, DL, VT);
8794
8795 return Elt;
8796 }
8797
8798 // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
8799 // operations are lowered to scalars.
8800 if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) {
8801 // If the indices are the same, return the inserted element else
8802 // if the indices are known different, extract the element from
8803 // the original vector.
8804 SDValue N1Op2 = N1.getOperand(2);
8806
8807 if (N1Op2C && N2C) {
8808 if (N1Op2C->getZExtValue() == N2C->getZExtValue()) {
8809 if (VT == N1.getOperand(1).getValueType())
8810 return N1.getOperand(1);
8811 if (VT.isFloatingPoint()) {
8813 return getFPExtendOrRound(N1.getOperand(1), DL, VT);
8814 }
8815 return getSExtOrTrunc(N1.getOperand(1), DL, VT);
8816 }
8817 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2);
8818 }
8819 }
8820
8821 // EXTRACT_VECTOR_ELT of v1iX EXTRACT_SUBVECTOR could be formed
8822 // when vector types are scalarized and v1iX is legal.
8823 // vextract (v1iX extract_subvector(vNiX, Idx)) -> vextract(vNiX,Idx).
8824 // Here we are completely ignoring the extract element index (N2),
8825 // which is fine for fixed width vectors, since any index other than 0
8826 // is undefined anyway. However, this cannot be ignored for scalable
8827 // vectors - in theory we could support this, but we don't want to do this
8828 // without a profitability check.
8829 if (N1.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
8831 N1.getValueType().getVectorNumElements() == 1) {
8832 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0),
8833 N1.getOperand(1));
8834 }
8835 break;
8837 assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!");
8838 assert(!N1.getValueType().isVector() && !VT.isVector() &&
8839 (N1.getValueType().isInteger() == VT.isInteger()) &&
8840 N1.getValueType() != VT &&
8841 "Wrong types for EXTRACT_ELEMENT!");
8842
8843 // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
8844 // 64-bit integers into 32-bit parts. Instead of building the extract of
8845 // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
8846 if (N1.getOpcode() == ISD::BUILD_PAIR)
8847 return N1.getOperand(N2C->getZExtValue());
8848
8849 // EXTRACT_ELEMENT of a constant int is also very common.
8850 if (N1C) {
8851 unsigned ElementSize = VT.getSizeInBits();
8852 unsigned Shift = ElementSize * N2C->getZExtValue();
8853 const APInt &Val = N1C->getAPIntValue();
8854 return getConstant(Val.extractBits(ElementSize, Shift), DL, VT);
8855 }
8856 break;
8858 EVT N1VT = N1.getValueType();
8859 assert(VT.isVector() && N1VT.isVector() &&
8860 "Extract subvector VTs must be vectors!");
8862 "Extract subvector VTs must have the same element type!");
8863 assert((VT.isFixedLengthVector() || N1VT.isScalableVector()) &&
8864 "Cannot extract a scalable vector from a fixed length vector!");
8865 assert((VT.isScalableVector() != N1VT.isScalableVector() ||
8867 "Extract subvector must be from larger vector to smaller vector!");
8868 assert(N2C && "Extract subvector index must be a constant");
8869 assert((VT.isScalableVector() != N1VT.isScalableVector() ||
8870 (VT.getVectorMinNumElements() + N2C->getZExtValue()) <=
8871 N1VT.getVectorMinNumElements()) &&
8872 "Extract subvector overflow!");
8873 assert(N2C->getAPIntValue().getBitWidth() ==
8874 TLI->getVectorIdxWidth(getDataLayout()) &&
8875 "Constant index for EXTRACT_SUBVECTOR has an invalid size");
8876 assert(N2C->getZExtValue() % VT.getVectorMinNumElements() == 0 &&
8877 "Extract index is not a multiple of the output vector length");
8878
8879 // Trivial extraction.
8880 if (VT == N1VT)
8881 return N1;
8882
8883 // EXTRACT_SUBVECTOR of an UNDEF is an UNDEF.
8884 if (N1.isUndef())
8885 return getUNDEF(VT);
8886
8887 // EXTRACT_SUBVECTOR of CONCAT_VECTOR can be simplified if the pieces of
8888 // the concat have the same type as the extract.
8889 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
8890 VT == N1.getOperand(0).getValueType()) {
8891 unsigned Factor = VT.getVectorMinNumElements();
8892 return N1.getOperand(N2C->getZExtValue() / Factor);
8893 }
8894
8895 // EXTRACT_SUBVECTOR of INSERT_SUBVECTOR is often created
8896 // during shuffle legalization.
8897 if (N1.getOpcode() == ISD::INSERT_SUBVECTOR && N2 == N1.getOperand(2) &&
8898 VT == N1.getOperand(1).getValueType())
8899 return N1.getOperand(1);
8900 break;
8901 }
8902 }
8903
8904 if (N1.getOpcode() == ISD::POISON || N2.getOpcode() == ISD::POISON) {
8905 switch (Opcode) {
8906 case ISD::XOR:
8907 case ISD::ADD:
8908 case ISD::PTRADD:
8909 case ISD::SUB:
8911 case ISD::UDIV:
8912 case ISD::SDIV:
8913 case ISD::UREM:
8914 case ISD::SREM:
8915 case ISD::MUL:
8916 case ISD::AND:
8917 case ISD::SSUBSAT:
8918 case ISD::USUBSAT:
8919 case ISD::UMIN:
8920 case ISD::OR:
8921 case ISD::SADDSAT:
8922 case ISD::UADDSAT:
8923 case ISD::UMAX:
8924 case ISD::SMAX:
8925 case ISD::SMIN:
8926 // fold op(arg1, poison) -> poison, fold op(poison, arg2) -> poison.
8927 return N2.getOpcode() == ISD::POISON ? N2 : N1;
8928 }
8929 }
8930
8931 // Canonicalize an UNDEF to the RHS, even over a constant.
8932 if (N1.getOpcode() == ISD::UNDEF && N2.getOpcode() != ISD::UNDEF) {
8933 if (TLI->isCommutativeBinOp(Opcode)) {
8934 std::swap(N1, N2);
8935 } else {
8936 switch (Opcode) {
8937 case ISD::PTRADD:
8938 case ISD::SUB:
8939 // fold op(undef, non_undef_arg2) -> undef.
8940 return N1;
8942 case ISD::UDIV:
8943 case ISD::SDIV:
8944 case ISD::UREM:
8945 case ISD::SREM:
8946 case ISD::SSUBSAT:
8947 case ISD::USUBSAT:
8948 // fold op(undef, non_undef_arg2) -> 0.
8949 return getConstant(0, DL, VT);
8950 }
8951 }
8952 }
8953
8954 // Fold a bunch of operators when the RHS is undef.
8955 if (N2.getOpcode() == ISD::UNDEF) {
8956 switch (Opcode) {
8957 case ISD::XOR:
8958 if (N1.getOpcode() == ISD::UNDEF)
8959 // Handle undef ^ undef -> 0 special case. This is a common
8960 // idiom (misuse).
8961 return getConstant(0, DL, VT);
8962 [[fallthrough]];
8963 case ISD::ADD:
8964 case ISD::PTRADD:
8965 case ISD::SUB:
8966 // fold op(arg1, undef) -> undef.
8967 return N2;
8968 case ISD::UDIV:
8969 case ISD::SDIV:
8970 case ISD::UREM:
8971 case ISD::SREM:
8972 // fold op(arg1, undef) -> poison.
8973 return getPOISON(VT);
8974 case ISD::MUL:
8975 case ISD::AND:
8976 case ISD::SSUBSAT:
8977 case ISD::USUBSAT:
8978 case ISD::UMIN:
8979 // fold op(undef, undef) -> undef, fold op(arg1, undef) -> 0.
8980 return N1.getOpcode() == ISD::UNDEF ? N2 : getConstant(0, DL, VT);
8981 case ISD::OR:
8982 case ISD::SADDSAT:
8983 case ISD::UADDSAT:
8984 case ISD::UMAX:
8985 // fold op(undef, undef) -> undef, fold op(arg1, undef) -> -1.
8986 return N1.getOpcode() == ISD::UNDEF ? N2 : getAllOnesConstant(DL, VT);
8987 case ISD::SMAX:
8988 // fold op(undef, undef) -> undef, fold op(arg1, undef) -> MAX_INT.
8989 return N1.getOpcode() == ISD::UNDEF
8990 ? N2
8991 : getConstant(
8993 VT);
8994 case ISD::SMIN:
8995 // fold op(undef, undef) -> undef, fold op(arg1, undef) -> MIN_INT.
8996 return N1.getOpcode() == ISD::UNDEF
8997 ? N2
8998 : getConstant(
9000 VT);
9001 }
9002 }
9003
9004 // Perform trivial constant folding.
9005 if (SDValue SV = FoldConstantArithmetic(Opcode, DL, VT, {N1, N2}, Flags))
9006 return SV;
9007
9008 // Memoize this node if possible.
9009 SDNode *N;
9010 SDVTList VTs = getVTList(VT);
9011 SDValue Ops[] = {N1, N2};
9012 if (VT != MVT::Glue) {
9014 AddNodeIDNode(ID, Opcode, VTs, Ops);
9015 void *IP = nullptr;
9016 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
9017 E->intersectFlagsWith(Flags);
9018 return SDValue(E, 0);
9019 }
9020
9021 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
9022 N->setFlags(Flags);
9023 createOperands(N, Ops);
9024 CSEMap.InsertNode(N, IP);
9025 } else {
9026 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
9027 createOperands(N, Ops);
9028 }
9029
9030 InsertNode(N);
9031 SDValue V = SDValue(N, 0);
9032 NewSDValueDbgMsg(V, "Creating new node: ", this);
9033 return V;
9034}
9035
9036SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
9037 SDValue N1, SDValue N2, SDValue N3) {
9038 SDNodeFlags Flags;
9039 if (Inserter)
9040 Flags = Inserter->getFlags();
9041 return getNode(Opcode, DL, VT, N1, N2, N3, Flags);
9042}
9043
9044SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
9045 SDValue N1, SDValue N2, SDValue N3,
9046 const SDNodeFlags Flags) {
9048 N2.getOpcode() != ISD::DELETED_NODE &&
9049 N3.getOpcode() != ISD::DELETED_NODE &&
9050 "Operand is DELETED_NODE!");
9051 // Perform various simplifications.
9052 switch (Opcode) {
9053 case ISD::BUILD_VECTOR: {
9054 // Attempt to simplify BUILD_VECTOR.
9055 SDValue Ops[] = {N1, N2, N3};
9056 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
9057 return V;
9058 break;
9059 }
9060 case ISD::CONCAT_VECTORS: {
9061 SDValue Ops[] = {N1, N2, N3};
9062 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
9063 return V;
9064 break;
9065 }
9066 case ISD::SETCC: {
9067 assert(VT.isInteger() && "SETCC result type must be an integer!");
9068 assert(N1.getValueType() == N2.getValueType() &&
9069 "SETCC operands must have the same type!");
9070 assert(VT.isVector() == N1.getValueType().isVector() &&
9071 "SETCC type should be vector iff the operand type is vector!");
9072 assert((!VT.isVector() || VT.getVectorElementCount() ==
9074 "SETCC vector element counts must match!");
9075 // Use FoldSetCC to simplify SETCC's.
9076 if (SDValue V =
9077 FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL, Flags))
9078 return V;
9079 break;
9080 }
9081 case ISD::SELECT:
9082 case ISD::VSELECT:
9083 if (SDValue V = simplifySelect(N1, N2, N3))
9084 return V;
9085 break;
9087 llvm_unreachable("should use getVectorShuffle constructor!");
9089 if (isNullConstant(N3))
9090 return N1;
9091 break;
9093 if (isNullConstant(N3))
9094 return N2;
9095 break;
9097 assert(VT.isVector() && VT == N1.getValueType() &&
9098 "INSERT_VECTOR_ELT vector type mismatch");
9100 "INSERT_VECTOR_ELT scalar fp/int mismatch");
9101 assert((!VT.isFloatingPoint() ||
9102 VT.getVectorElementType() == N2.getValueType()) &&
9103 "INSERT_VECTOR_ELT fp scalar type mismatch");
9104 assert((!VT.isInteger() ||
9106 "INSERT_VECTOR_ELT int scalar size mismatch");
9107
9108 auto *N3C = dyn_cast<ConstantSDNode>(N3);
9109 // INSERT_VECTOR_ELT into out-of-bounds element is an UNDEF, except
9110 // for scalable vectors where we will generate appropriate code to
9111 // deal with out-of-bounds cases correctly.
9112 if (N3C && VT.isFixedLengthVector() &&
9113 N3C->getZExtValue() >= VT.getVectorNumElements())
9114 return getUNDEF(VT);
9115
9116 // Undefined index can be assumed out-of-bounds, so that's UNDEF too.
9117 if (N3.isUndef())
9118 return getUNDEF(VT);
9119
9120 // If inserting poison, just use the input vector.
9121 if (N2.getOpcode() == ISD::POISON)
9122 return N1;
9123
9124 // Inserting undef into undef/poison is still undef.
9125 if (N2.getOpcode() == ISD::UNDEF && N1.isUndef())
9126 return getUNDEF(VT);
9127
9128 // If the inserted element is an UNDEF, just use the input vector.
9129 // But not if skipping the insert could make the result more poisonous.
9130 if (N2.isUndef()) {
9131 if (N3C && VT.isFixedLengthVector()) {
9132 APInt EltMask =
9133 APInt::getOneBitSet(VT.getVectorNumElements(), N3C->getZExtValue());
9134 if (isGuaranteedNotToBePoison(N1, EltMask))
9135 return N1;
9136 } else if (isGuaranteedNotToBePoison(N1))
9137 return N1;
9138 }
9139 break;
9140 }
9141 case ISD::INSERT_SUBVECTOR: {
9142 // If inserting poison, just use the input vector,
9143 if (N2.getOpcode() == ISD::POISON)
9144 return N1;
9145
9146 // Inserting undef into undef/poison is still undef.
9147 if (N2.getOpcode() == ISD::UNDEF && N1.isUndef())
9148 return getUNDEF(VT);
9149
9150 EVT N2VT = N2.getValueType();
9151 assert(VT == N1.getValueType() &&
9152 "Dest and insert subvector source types must match!");
9153 assert(VT.isVector() && N2VT.isVector() &&
9154 "Insert subvector VTs must be vectors!");
9156 "Insert subvector VTs must have the same element type!");
9157 assert((VT.isScalableVector() || N2VT.isFixedLengthVector()) &&
9158 "Cannot insert a scalable vector into a fixed length vector!");
9159 assert((VT.isScalableVector() != N2VT.isScalableVector() ||
9161 "Insert subvector must be from smaller vector to larger vector!");
9163 "Insert subvector index must be constant");
9164 assert((VT.isScalableVector() != N2VT.isScalableVector() ||
9165 (N2VT.getVectorMinNumElements() + N3->getAsZExtVal()) <=
9167 "Insert subvector overflow!");
9169 TLI->getVectorIdxWidth(getDataLayout()) &&
9170 "Constant index for INSERT_SUBVECTOR has an invalid size");
9171
9172 // Trivial insertion.
9173 if (VT == N2VT)
9174 return N2;
9175
9176 // If this is an insert of an extracted vector into an undef/poison vector,
9177 // we can just use the input to the extract. But not if skipping the
9178 // extract+insert could make the result more poisonous.
9179 if (N1.isUndef() && N2.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
9180 N2.getOperand(1) == N3 && N2.getOperand(0).getValueType() == VT) {
9181 if (N1.getOpcode() == ISD::POISON)
9182 return N2.getOperand(0);
9183 if (VT.isFixedLengthVector() && N2VT.isFixedLengthVector()) {
9184 unsigned LoBit = N3->getAsZExtVal();
9185 unsigned HiBit = LoBit + N2VT.getVectorNumElements();
9186 APInt EltMask =
9187 APInt::getBitsSet(VT.getVectorNumElements(), LoBit, HiBit);
9188 if (isGuaranteedNotToBePoison(N2.getOperand(0), ~EltMask))
9189 return N2.getOperand(0);
9190 } else if (isGuaranteedNotToBePoison(N2.getOperand(0)))
9191 return N2.getOperand(0);
9192 }
9193
9194 // If the inserted subvector is UNDEF, just use the input vector.
9195 // But not if skipping the insert could make the result more poisonous.
9196 if (N2.isUndef()) {
9197 if (VT.isFixedLengthVector()) {
9198 unsigned LoBit = N3->getAsZExtVal();
9199 unsigned HiBit = LoBit + N2VT.getVectorNumElements();
9200 APInt EltMask =
9201 APInt::getBitsSet(VT.getVectorNumElements(), LoBit, HiBit);
9202 if (isGuaranteedNotToBePoison(N1, EltMask))
9203 return N1;
9204 } else if (isGuaranteedNotToBePoison(N1))
9205 return N1;
9206 }
9207 break;
9208 }
9209 case ISD::BITCAST:
9210 // Fold bit_convert nodes from a type to themselves.
9211 if (N1.getValueType() == VT)
9212 return N1;
9213 break;
9214 case ISD::VP_TRUNCATE:
9215 case ISD::VP_SIGN_EXTEND:
9216 case ISD::VP_ZERO_EXTEND:
9217 // Don't create noop casts.
9218 if (N1.getValueType() == VT)
9219 return N1;
9220 break;
9221 case ISD::VECTOR_COMPRESS: {
9222 [[maybe_unused]] EVT VecVT = N1.getValueType();
9223 [[maybe_unused]] EVT MaskVT = N2.getValueType();
9224 [[maybe_unused]] EVT PassthruVT = N3.getValueType();
9225 assert(VT == VecVT && "Vector and result type don't match.");
9226 assert(VecVT.isVector() && MaskVT.isVector() && PassthruVT.isVector() &&
9227 "All inputs must be vectors.");
9228 assert(VecVT == PassthruVT && "Vector and passthru types don't match.");
9230 "Vector and mask must have same number of elements.");
9231
9232 if (N1.isUndef() || N2.isUndef())
9233 return N3;
9234
9235 break;
9236 }
9241 [[maybe_unused]] EVT AccVT = N1.getValueType();
9242 [[maybe_unused]] EVT Input1VT = N2.getValueType();
9243 [[maybe_unused]] EVT Input2VT = N3.getValueType();
9244 assert(Input1VT.isVector() && Input1VT == Input2VT &&
9245 "Expected the second and third operands of the PARTIAL_REDUCE_MLA "
9246 "node to have the same type!");
9247 assert(VT.isVector() && VT == AccVT &&
9248 "Expected the first operand of the PARTIAL_REDUCE_MLA node to have "
9249 "the same type as its result!");
9251 AccVT.getVectorElementCount()) &&
9252 "Expected the element count of the second and third operands of the "
9253 "PARTIAL_REDUCE_MLA node to be a positive integer multiple of the "
9254 "element count of the first operand and the result!");
9256 "Expected the second and third operands of the PARTIAL_REDUCE_MLA "
9257 "node to have an element type which is the same as or smaller than "
9258 "the element type of the first operand and result!");
9259 break;
9260 }
9261 }
9262
9263 // Perform trivial constant folding for arithmetic operators.
9264 switch (Opcode) {
9268 case ISD::FMA:
9269 case ISD::FMAD:
9270 case ISD::SETCC:
9271 case ISD::FSHL:
9272 case ISD::FSHR:
9273 if (SDValue SV =
9274 FoldConstantArithmetic(Opcode, DL, VT, {N1, N2, N3}, Flags))
9275 return SV;
9276 break;
9277 }
9278
9279 // Memoize node if it doesn't produce a glue result.
9280 SDNode *N;
9281 SDVTList VTs = getVTList(VT);
9282 SDValue Ops[] = {N1, N2, N3};
9283 if (VT != MVT::Glue) {
9285 AddNodeIDNode(ID, Opcode, VTs, Ops);
9286 void *IP = nullptr;
9287 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
9288 E->intersectFlagsWith(Flags);
9289 return SDValue(E, 0);
9290 }
9291
9292 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
9293 N->setFlags(Flags);
9294 createOperands(N, Ops);
9295 CSEMap.InsertNode(N, IP);
9296 } else {
9297 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
9298 createOperands(N, Ops);
9299 }
9300
9301 InsertNode(N);
9302 SDValue V = SDValue(N, 0);
9303 NewSDValueDbgMsg(V, "Creating new node: ", this);
9304 return V;
9305}
9306
9307SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
9308 SDValue N1, SDValue N2, SDValue N3, SDValue N4,
9309 const SDNodeFlags Flags) {
9310 SDValue Ops[] = { N1, N2, N3, N4 };
9311 return getNode(Opcode, DL, VT, Ops, Flags);
9312}
9313
9314SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
9315 SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
9316 SDNodeFlags Flags;
9317 if (Inserter)
9318 Flags = Inserter->getFlags();
9319 return getNode(Opcode, DL, VT, N1, N2, N3, N4, Flags);
9320}
9321
9322SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
9323 SDValue N1, SDValue N2, SDValue N3, SDValue N4,
9324 SDValue N5, const SDNodeFlags Flags) {
9325 SDValue Ops[] = { N1, N2, N3, N4, N5 };
9326 return getNode(Opcode, DL, VT, Ops, Flags);
9327}
9328
9329SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
9330 SDValue N1, SDValue N2, SDValue N3, SDValue N4,
9331 SDValue N5) {
9332 SDNodeFlags Flags;
9333 if (Inserter)
9334 Flags = Inserter->getFlags();
9335 return getNode(Opcode, DL, VT, N1, N2, N3, N4, N5, Flags);
9336}
9337
9338/// getStackArgumentTokenFactor - Compute a TokenFactor to force all
9339/// the incoming stack arguments to be loaded from the stack.
9341 SmallVector<SDValue, 8> ArgChains;
9342
9343 // Include the original chain at the beginning of the list. When this is
9344 // used by target LowerCall hooks, this helps legalize find the
9345 // CALLSEQ_BEGIN node.
9346 ArgChains.push_back(Chain);
9347
9348 // Add a chain value for each stack argument.
9349 for (SDNode *U : getEntryNode().getNode()->users())
9350 if (LoadSDNode *L = dyn_cast<LoadSDNode>(U))
9351 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
9352 if (FI->getIndex() < 0)
9353 ArgChains.push_back(SDValue(L, 1));
9354
9355 // Build a tokenfactor for all the chains.
9356 return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
9357}
9358
9359/// getMemsetValue - Vectorized representation of the memset value
9360/// operand.
9362 const SDLoc &dl) {
9363 assert(!Value.isUndef());
9364
9365 unsigned NumBits = VT.getScalarSizeInBits();
9367 assert(C->getAPIntValue().getBitWidth() == 8);
9368 APInt Val = APInt::getSplat(NumBits, C->getAPIntValue());
9369 if (VT.isInteger()) {
9370 bool IsOpaque = VT.getSizeInBits() > 64 ||
9371 !DAG.getTargetLoweringInfo().isLegalStoreImmediate(C->getSExtValue());
9372 return DAG.getConstant(Val, dl, VT, false, IsOpaque);
9373 }
9374 return DAG.getConstantFP(APFloat(VT.getFltSemantics(), Val), dl, VT);
9375 }
9376
9377 assert(Value.getValueType() == MVT::i8 && "memset with non-byte fill value?");
9378 EVT IntVT = VT.getScalarType();
9379 if (!IntVT.isInteger())
9380 IntVT = EVT::getIntegerVT(*DAG.getContext(), IntVT.getSizeInBits());
9381
9382 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, Value);
9383 if (NumBits > 8) {
9384 // Use a multiplication with 0x010101... to extend the input to the
9385 // required length.
9386 APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01));
9387 Value = DAG.getNode(ISD::MUL, dl, IntVT, Value,
9388 DAG.getConstant(Magic, dl, IntVT));
9389 }
9390
9391 if (VT != Value.getValueType() && !VT.isInteger())
9392 Value = DAG.getBitcast(VT.getScalarType(), Value);
9393 if (VT != Value.getValueType())
9394 Value = DAG.getSplatBuildVector(VT, dl, Value);
9395
9396 return Value;
9397}
9398
9399/// getMemsetStringVal - Similar to getMemsetValue. Except this is only
9400/// used when a memcpy is turned into a memset when the source is a constant
9401/// string ptr.
9403 const TargetLowering &TLI,
9404 const ConstantDataArraySlice &Slice) {
9405 // Handle vector with all elements zero.
9406 if (Slice.Array == nullptr) {
9407 if (VT.isInteger())
9408 return DAG.getConstant(0, dl, VT);
9409 return DAG.getNode(ISD::BITCAST, dl, VT,
9410 DAG.getConstant(0, dl, VT.changeTypeToInteger()));
9411 }
9412
9413 assert(!VT.isVector() && "Can't handle vector type here!");
9414 unsigned NumVTBits = VT.getSizeInBits();
9415 unsigned NumVTBytes = NumVTBits / 8;
9416 unsigned NumBytes = std::min(NumVTBytes, unsigned(Slice.Length));
9417
9418 APInt Val(NumVTBits, 0);
9419 if (DAG.getDataLayout().isLittleEndian()) {
9420 for (unsigned i = 0; i != NumBytes; ++i)
9421 Val |= (uint64_t)(unsigned char)Slice[i] << i*8;
9422 } else {
9423 for (unsigned i = 0; i != NumBytes; ++i)
9424 Val |= (uint64_t)(unsigned char)Slice[i] << (NumVTBytes-i-1)*8;
9425 }
9426
9427 // If the "cost" of materializing the integer immediate is less than the cost
9428 // of a load, then it is cost effective to turn the load into the immediate.
9429 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
9430 if (TLI.shouldConvertConstantLoadToIntImm(Val, Ty))
9431 return DAG.getConstant(Val, dl, VT);
9432 return SDValue();
9433}
9434
9436 const SDLoc &DL,
9437 const SDNodeFlags Flags) {
9438 SDValue Index = getTypeSize(DL, Base.getValueType(), Offset);
9439 return getMemBasePlusOffset(Base, Index, DL, Flags);
9440}
9441
9443 const SDLoc &DL,
9444 const SDNodeFlags Flags) {
9445 assert(Offset.getValueType().isInteger());
9446 EVT BasePtrVT = Ptr.getValueType();
9447 if (TLI->shouldPreservePtrArith(this->getMachineFunction().getFunction(),
9448 BasePtrVT))
9449 return getNode(ISD::PTRADD, DL, BasePtrVT, Ptr, Offset, Flags);
9450 // InBounds only applies to PTRADD, don't set it if we generate ADD.
9451 SDNodeFlags AddFlags = Flags;
9452 AddFlags.setInBounds(false);
9453 return getNode(ISD::ADD, DL, BasePtrVT, Ptr, Offset, AddFlags);
9454}
9455
9456/// Returns true if memcpy source is constant data.
9458 uint64_t SrcDelta = 0;
9459 GlobalAddressSDNode *G = nullptr;
9460 if (Src.getOpcode() == ISD::GlobalAddress)
9462 else if (Src->isAnyAdd() &&
9463 Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
9464 Src.getOperand(1).getOpcode() == ISD::Constant) {
9465 G = cast<GlobalAddressSDNode>(Src.getOperand(0));
9466 SrcDelta = Src.getConstantOperandVal(1);
9467 }
9468 if (!G)
9469 return false;
9470
9471 return getConstantDataArrayInfo(G->getGlobal(), Slice, 8,
9472 SrcDelta + G->getOffset());
9473}
9474
9476 SelectionDAG &DAG) {
9477 // On Darwin, -Os means optimize for size without hurting performance, so
9478 // only really optimize for size when -Oz (MinSize) is used.
9480 return MF.getFunction().hasMinSize();
9481 return DAG.shouldOptForSize();
9482}
9483
9485 SmallVector<SDValue, 32> &OutChains, unsigned From,
9486 unsigned To, SmallVector<SDValue, 16> &OutLoadChains,
9487 SmallVector<SDValue, 16> &OutStoreChains) {
9488 assert(OutLoadChains.size() && "Missing loads in memcpy inlining");
9489 assert(OutStoreChains.size() && "Missing stores in memcpy inlining");
9490 SmallVector<SDValue, 16> GluedLoadChains;
9491 for (unsigned i = From; i < To; ++i) {
9492 OutChains.push_back(OutLoadChains[i]);
9493 GluedLoadChains.push_back(OutLoadChains[i]);
9494 }
9495
9496 // Chain for all loads.
9497 SDValue LoadToken = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
9498 GluedLoadChains);
9499
9500 for (unsigned i = From; i < To; ++i) {
9501 StoreSDNode *ST = dyn_cast<StoreSDNode>(OutStoreChains[i]);
9502 SDValue NewStore = DAG.getTruncStore(LoadToken, dl, ST->getValue(),
9503 ST->getBasePtr(), ST->getMemoryVT(),
9504 ST->getMemOperand());
9505 OutChains.push_back(NewStore);
9506 }
9507}
9508
9509static SDValue
9511 SDValue Dst, SDValue Src, uint64_t Size, Align DstAlign,
9512 Align SrcAlign, bool isVol, bool AlwaysInline,
9513 MachinePointerInfo DstPtrInfo,
9514 MachinePointerInfo SrcPtrInfo, const AAMDNodes &AAInfo,
9515 BatchAAResults *BatchAA, const MDNode *DstMemCacheHint,
9516 const MDNode *SrcMemCacheHint) {
9517 // Turn a memcpy of undef to nop.
9518 // FIXME: We need to honor volatile even is Src is undef.
9519 if (Src.isUndef())
9520 return Chain;
9521
9522 // Expand memcpy to a series of load and store ops if the size operand falls
9523 // below a certain threshold.
9524 // TODO: In the AlwaysInline case, if the size is big then generate a loop
9525 // rather than maybe a humongous number of loads and stores.
9526 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9527 const DataLayout &DL = DAG.getDataLayout();
9528 LLVMContext &C = *DAG.getContext();
9529 std::vector<EVT> MemOps;
9530 bool DstAlignCanChange = false;
9532 MachineFrameInfo &MFI = MF.getFrameInfo();
9533 bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
9535 if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
9536 DstAlignCanChange = true;
9537 SrcAlign = std::max(SrcAlign, DAG.InferPtrAlign(Src).valueOrOne());
9539 // If marked as volatile, perform a copy even when marked as constant.
9540 bool CopyFromConstant = !isVol && isMemSrcFromConstant(Src, Slice);
9541 bool isZeroConstant = CopyFromConstant && Slice.Array == nullptr;
9542 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize);
9543 const MemOp Op = isZeroConstant
9544 ? MemOp::Set(Size, DstAlignCanChange, DstAlign,
9545 /*IsZeroMemset*/ true, isVol)
9546 : MemOp::Copy(Size, DstAlignCanChange, DstAlign,
9547 SrcAlign, isVol, CopyFromConstant);
9548 if (!TLI.findOptimalMemOpLowering(
9549 C, MemOps, Limit, Op, DstPtrInfo.getAddrSpace(),
9550 SrcPtrInfo.getAddrSpace(), MF.getFunction().getAttributes(), nullptr))
9551 return SDValue();
9552
9553 if (DstAlignCanChange) {
9554 Type *Ty = MemOps[0].getTypeForEVT(C);
9555 Align NewDstAlign = DL.getABITypeAlign(Ty);
9556
9557 // Don't promote to an alignment that would require dynamic stack
9558 // realignment which may conflict with optimizations such as tail call
9559 // optimization.
9561 if (!TRI->hasStackRealignment(MF))
9562 if (MaybeAlign StackAlign = DL.getStackAlignment())
9563 NewDstAlign = std::min(NewDstAlign, *StackAlign);
9564
9565 if (NewDstAlign > DstAlign) {
9566 // Give the stack frame object a larger alignment if needed.
9567 if (MFI.getObjectAlign(FI->getIndex()) < NewDstAlign)
9568 MFI.setObjectAlignment(FI->getIndex(), NewDstAlign);
9569 DstAlign = NewDstAlign;
9570 }
9571 }
9572
9573 // Prepare AAInfo for loads/stores after lowering this memcpy.
9574 AAMDNodes NewAAInfo = AAInfo;
9575 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
9576
9577 const Value *SrcVal = dyn_cast_if_present<const Value *>(SrcPtrInfo.V);
9578 bool isConstant =
9579 BatchAA && SrcVal &&
9580 BatchAA->pointsToConstantMemory(MemoryLocation(SrcVal, Size, AAInfo));
9581
9582 MachineMemOperand::Flags MMOFlags =
9584 SmallVector<SDValue, 16> OutLoadChains;
9585 SmallVector<SDValue, 16> OutStoreChains;
9586 SmallVector<SDValue, 32> OutChains;
9587 unsigned NumMemOps = MemOps.size();
9588 uint64_t SrcOff = 0, DstOff = 0;
9589 for (unsigned i = 0; i != NumMemOps; ++i) {
9590 EVT VT = MemOps[i];
9591 unsigned VTSize = VT.getSizeInBits() / 8;
9593
9594 if (VTSize > Size) {
9595 // Issuing an unaligned load / store pair that overlaps with the previous
9596 // pair. Adjust the offset accordingly.
9597 assert(i == NumMemOps-1 && i != 0);
9598 SrcOff -= VTSize - Size;
9599 DstOff -= VTSize - Size;
9600 }
9601
9602 if (CopyFromConstant &&
9603 (isZeroConstant || (VT.isInteger() && !VT.isVector()))) {
9604 // It's unlikely a store of a vector immediate can be done in a single
9605 // instruction. It would require a load from a constantpool first.
9606 // We only handle zero vectors here.
9607 // FIXME: Handle other cases where store of vector immediate is done in
9608 // a single instruction.
9609 ConstantDataArraySlice SubSlice;
9610 if (SrcOff < Slice.Length) {
9611 SubSlice = Slice;
9612 SubSlice.move(SrcOff);
9613 } else {
9614 // This is an out-of-bounds access and hence UB. Pretend we read zero.
9615 SubSlice.Array = nullptr;
9616 SubSlice.Offset = 0;
9617 SubSlice.Length = VTSize;
9618 }
9619 Value = getMemsetStringVal(VT, dl, DAG, TLI, SubSlice);
9620 if (Value.getNode()) {
9621 Store = DAG.getStore(
9622 Chain, dl, Value,
9623 DAG.getObjectPtrOffset(dl, Dst, TypeSize::getFixed(DstOff)),
9624 DstPtrInfo.getWithOffset(DstOff), DstAlign, MMOFlags,
9625 MMOMetadata(NewAAInfo, /*Ranges=*/nullptr, DstMemCacheHint));
9626 OutChains.push_back(Store);
9627 }
9628 }
9629
9630 if (!Store.getNode()) {
9631 // The type might not be legal for the target. This should only happen
9632 // if the type is smaller than a legal type, as on PPC, so the right
9633 // thing to do is generate a LoadExt/StoreTrunc pair. These simplify
9634 // to Load/Store if NVT==VT.
9635 // FIXME does the case above also need this?
9636 EVT NVT = TLI.getTypeToTransformTo(C, VT);
9637 assert(NVT.bitsGE(VT));
9638
9639 bool isDereferenceable =
9640 SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
9641 MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
9642 if (isDereferenceable)
9644 if (isConstant)
9645 SrcMMOFlags |= MachineMemOperand::MOInvariant;
9646
9647 Value = DAG.getExtLoad(
9648 ISD::EXTLOAD, dl, NVT, Chain,
9649 DAG.getObjectPtrOffset(dl, Src, TypeSize::getFixed(SrcOff)),
9650 SrcPtrInfo.getWithOffset(SrcOff), VT,
9651 commonAlignment(SrcAlign, SrcOff), SrcMMOFlags,
9652 MMOMetadata(NewAAInfo, /*Ranges=*/nullptr, SrcMemCacheHint));
9653 OutLoadChains.push_back(Value.getValue(1));
9654
9655 Store = DAG.getTruncStore(
9656 Chain, dl, Value,
9657 DAG.getObjectPtrOffset(dl, Dst, TypeSize::getFixed(DstOff)),
9658 DstPtrInfo.getWithOffset(DstOff), VT, DstAlign, MMOFlags,
9659 MMOMetadata(NewAAInfo, /*Ranges=*/nullptr, DstMemCacheHint));
9660 OutStoreChains.push_back(Store);
9661 }
9662 SrcOff += VTSize;
9663 DstOff += VTSize;
9664 Size -= VTSize;
9665 }
9666
9667 unsigned GluedLdStLimit = MaxLdStGlue == 0 ?
9669 unsigned NumLdStInMemcpy = OutStoreChains.size();
9670
9671 if (NumLdStInMemcpy) {
9672 // It may be that memcpy might be converted to memset if it's memcpy
9673 // of constants. In such a case, we won't have loads and stores, but
9674 // just stores. In the absence of loads, there is nothing to gang up.
9675 if ((GluedLdStLimit <= 1) || !EnableMemCpyDAGOpt) {
9676 // If target does not care, just leave as it.
9677 for (unsigned i = 0; i < NumLdStInMemcpy; ++i) {
9678 OutChains.push_back(OutLoadChains[i]);
9679 OutChains.push_back(OutStoreChains[i]);
9680 }
9681 } else {
9682 // Ld/St less than/equal limit set by target.
9683 if (NumLdStInMemcpy <= GluedLdStLimit) {
9684 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
9685 NumLdStInMemcpy, OutLoadChains,
9686 OutStoreChains);
9687 } else {
9688 unsigned NumberLdChain = NumLdStInMemcpy / GluedLdStLimit;
9689 unsigned RemainingLdStInMemcpy = NumLdStInMemcpy % GluedLdStLimit;
9690 unsigned GlueIter = 0;
9691
9692 // Residual ld/st.
9693 if (RemainingLdStInMemcpy) {
9695 DAG, dl, OutChains, NumLdStInMemcpy - RemainingLdStInMemcpy,
9696 NumLdStInMemcpy, OutLoadChains, OutStoreChains);
9697 }
9698
9699 for (unsigned cnt = 0; cnt < NumberLdChain; ++cnt) {
9700 unsigned IndexFrom = NumLdStInMemcpy - RemainingLdStInMemcpy -
9701 GlueIter - GluedLdStLimit;
9702 unsigned IndexTo = NumLdStInMemcpy - RemainingLdStInMemcpy - GlueIter;
9703 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, IndexFrom, IndexTo,
9704 OutLoadChains, OutStoreChains);
9705 GlueIter += GluedLdStLimit;
9706 }
9707 }
9708 }
9709 }
9710 return DAG.getTokenFactor(dl, OutChains);
9711}
9712
9714 SelectionDAG &DAG, const SDLoc &dl, SDValue Chain, SDValue Dst, SDValue Src,
9715 uint64_t Size, Align DstAlign, Align SrcAlign, bool isVol,
9716 bool AlwaysInline, MachinePointerInfo DstPtrInfo,
9717 MachinePointerInfo SrcPtrInfo, const AAMDNodes &AAInfo) {
9718 // Turn a memmove of undef to nop.
9719 // FIXME: We need to honor volatile even is Src is undef.
9720 if (Src.isUndef())
9721 return Chain;
9722
9723 // Expand memmove to a series of load and store ops if the size operand falls
9724 // below a certain threshold.
9725 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9726 const DataLayout &DL = DAG.getDataLayout();
9727 LLVMContext &C = *DAG.getContext();
9728 std::vector<EVT> MemOps;
9729 bool DstAlignCanChange = false;
9731 MachineFrameInfo &MFI = MF.getFrameInfo();
9732 bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
9734 if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
9735 DstAlignCanChange = true;
9736 SrcAlign = std::max(SrcAlign, DAG.InferPtrAlign(Src).valueOrOne());
9737 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize);
9738 if (!TLI.findOptimalMemOpLowering(
9739 C, MemOps, Limit,
9740 MemOp::Move(Size, DstAlignCanChange, DstAlign, SrcAlign, isVol),
9741 DstPtrInfo.getAddrSpace(), SrcPtrInfo.getAddrSpace(),
9742 MF.getFunction().getAttributes(), nullptr))
9743 return SDValue();
9744
9745 if (DstAlignCanChange) {
9746 Type *Ty = MemOps[0].getTypeForEVT(C);
9747 Align NewDstAlign = DL.getABITypeAlign(Ty);
9748
9749 // Don't promote to an alignment that would require dynamic stack
9750 // realignment which may conflict with optimizations such as tail call
9751 // optimization.
9753 if (!TRI->hasStackRealignment(MF))
9754 if (MaybeAlign StackAlign = DL.getStackAlignment())
9755 NewDstAlign = std::min(NewDstAlign, *StackAlign);
9756
9757 if (NewDstAlign > DstAlign) {
9758 // Give the stack frame object a larger alignment if needed.
9759 if (MFI.getObjectAlign(FI->getIndex()) < NewDstAlign)
9760 MFI.setObjectAlignment(FI->getIndex(), NewDstAlign);
9761 DstAlign = NewDstAlign;
9762 }
9763 }
9764
9765 // Prepare AAInfo for loads/stores after lowering this memmove.
9766 AAMDNodes NewAAInfo = AAInfo;
9767 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
9768
9769 MachineMemOperand::Flags MMOFlags =
9771 uint64_t SrcOff = 0;
9772 SmallVector<SDValue, 8> LoadValues;
9773 SmallVector<SDValue, 8> LoadChains;
9774 SmallVector<SDValue, 8> OutChains;
9775 unsigned NumMemOps = MemOps.size();
9776 for (unsigned i = 0; i < NumMemOps; i++) {
9777 EVT VT = MemOps[i];
9778 unsigned VTSize = VT.getSizeInBits() / 8;
9779 SDValue Value;
9780 bool IsOverlapping = false;
9781
9782 if (i == NumMemOps - 1 && i != 0 && VTSize > Size - SrcOff) {
9783 // Issuing an unaligned load / store pair that overlaps with the previous
9784 // pair. Adjust the offset accordingly.
9785 SrcOff = Size - VTSize;
9786 IsOverlapping = true;
9787 }
9788
9789 // Calculate the actual alignment at the current offset. The alignment at
9790 // SrcOff may be lower than the base alignment, especially when using
9791 // overlapping loads.
9792 Align SrcAlignAtOffset = commonAlignment(SrcAlign, SrcOff);
9793 if (IsOverlapping) {
9794 // Verify that the target allows misaligned memory accesses at the
9795 // adjusted offset when using overlapping loads.
9796 unsigned Fast;
9797 if (!TLI.allowsMisalignedMemoryAccesses(VT, SrcPtrInfo.getAddrSpace(),
9798 SrcAlignAtOffset, MMOFlags,
9799 &Fast) ||
9800 !Fast) {
9801 // This should have been caught by findOptimalMemOpLowering, but verify
9802 // here for safety.
9803 return SDValue();
9804 }
9805 }
9806
9807 bool isDereferenceable =
9808 SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
9809 MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
9810 if (isDereferenceable)
9812 Value =
9813 DAG.getLoad(VT, dl, Chain,
9814 DAG.getObjectPtrOffset(dl, Src, TypeSize::getFixed(SrcOff)),
9815 SrcPtrInfo.getWithOffset(SrcOff), SrcAlignAtOffset,
9816 SrcMMOFlags, NewAAInfo);
9817 LoadValues.push_back(Value);
9818 LoadChains.push_back(Value.getValue(1));
9819 SrcOff += VTSize;
9820 }
9821 Chain = DAG.getTokenFactor(dl, LoadChains);
9822 OutChains.clear();
9823 uint64_t DstOff = 0;
9824 for (unsigned i = 0; i < NumMemOps; i++) {
9825 EVT VT = MemOps[i];
9826 unsigned VTSize = VT.getSizeInBits() / 8;
9827 SDValue Store;
9828 bool IsOverlapping = false;
9829
9830 if (i == NumMemOps - 1 && i != 0 && VTSize > Size - DstOff) {
9831 // Issuing an unaligned load / store pair that overlaps with the previous
9832 // pair. Adjust the offset accordingly.
9833 DstOff = Size - VTSize;
9834 IsOverlapping = true;
9835 }
9836
9837 // Calculate the actual alignment at the current offset. The alignment at
9838 // DstOff may be lower than the base alignment, especially when using
9839 // overlapping stores.
9840 Align DstAlignAtOffset = commonAlignment(DstAlign, DstOff);
9841 if (IsOverlapping) {
9842 // Verify that the target allows misaligned memory accesses at the
9843 // adjusted offset when using overlapping stores.
9844 unsigned Fast;
9845 if (!TLI.allowsMisalignedMemoryAccesses(VT, DstPtrInfo.getAddrSpace(),
9846 DstAlignAtOffset, MMOFlags,
9847 &Fast) ||
9848 !Fast) {
9849 // This should have been caught by findOptimalMemOpLowering, but verify
9850 // here for safety.
9851 return SDValue();
9852 }
9853 }
9854 Store = DAG.getStore(
9855 Chain, dl, LoadValues[i],
9856 DAG.getObjectPtrOffset(dl, Dst, TypeSize::getFixed(DstOff)),
9857 DstPtrInfo.getWithOffset(DstOff), DstAlignAtOffset, MMOFlags,
9858 NewAAInfo);
9859 OutChains.push_back(Store);
9860 DstOff += VTSize;
9861 }
9862
9863 return DAG.getTokenFactor(dl, OutChains);
9864}
9865
9866/// Lower the call to 'memset' intrinsic function into a series of store
9867/// operations.
9868///
9869/// \param DAG Selection DAG where lowered code is placed.
9870/// \param dl Link to corresponding IR location.
9871/// \param Chain Control flow dependency.
9872/// \param Dst Pointer to destination memory location.
9873/// \param Src Value of byte to write into the memory.
9874/// \param Size Number of bytes to write.
9875/// \param Alignment Alignment of the destination in bytes.
9876/// \param isVol True if destination is volatile.
9877/// \param AlwaysInline Makes sure no function call is generated.
9878/// \param DstPtrInfo IR information on the memory pointer.
9879/// \returns New head in the control flow, if lowering was successful, empty
9880/// SDValue otherwise.
9881///
9882/// The function tries to replace 'llvm.memset' intrinsic with several store
9883/// operations and value calculation code. This is usually profitable for small
9884/// memory size or when the semantic requires inlining.
9886 SDValue Chain, SDValue Dst, SDValue Src,
9887 uint64_t Size, Align Alignment, bool isVol,
9888 bool AlwaysInline, MachinePointerInfo DstPtrInfo,
9889 const AAMDNodes &AAInfo) {
9890 // Turn a memset of undef to nop.
9891 // FIXME: We need to honor volatile even is Src is undef.
9892 if (Src.isUndef())
9893 return Chain;
9894
9895 // Expand memset to a series of load/store ops if the size operand
9896 // falls below a certain threshold.
9897 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9898 std::vector<EVT> MemOps;
9899 bool DstAlignCanChange = false;
9900 LLVMContext &C = *DAG.getContext();
9902 MachineFrameInfo &MFI = MF.getFrameInfo();
9903 bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
9905 if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
9906 DstAlignCanChange = true;
9907 bool IsZeroVal = isNullConstant(Src);
9908 unsigned Limit = AlwaysInline ? ~0 : TLI.getMaxStoresPerMemset(OptSize);
9909
9910 EVT LargestVT;
9911 if (!TLI.findOptimalMemOpLowering(
9912 C, MemOps, Limit,
9913 MemOp::Set(Size, DstAlignCanChange, Alignment, IsZeroVal, isVol),
9914 DstPtrInfo.getAddrSpace(), ~0u, MF.getFunction().getAttributes(),
9915 &LargestVT))
9916 return SDValue();
9917
9918 if (DstAlignCanChange) {
9919 Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
9920 const DataLayout &DL = DAG.getDataLayout();
9921 Align NewAlign = DL.getABITypeAlign(Ty);
9922
9923 // Don't promote to an alignment that would require dynamic stack
9924 // realignment which may conflict with optimizations such as tail call
9925 // optimization.
9927 if (!TRI->hasStackRealignment(MF))
9928 if (MaybeAlign StackAlign = DL.getStackAlignment())
9929 NewAlign = std::min(NewAlign, *StackAlign);
9930
9931 if (NewAlign > Alignment) {
9932 // Give the stack frame object a larger alignment if needed.
9933 if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
9934 MFI.setObjectAlignment(FI->getIndex(), NewAlign);
9935 Alignment = NewAlign;
9936 }
9937 }
9938
9939 SmallVector<SDValue, 8> OutChains;
9940 uint64_t DstOff = 0;
9941 unsigned NumMemOps = MemOps.size();
9942
9943 // Find the largest store and generate the bit pattern for it.
9944 // If target didn't set LargestVT, compute it from MemOps.
9945 if (!LargestVT.isSimple()) {
9946 LargestVT = MemOps[0];
9947 for (unsigned i = 1; i < NumMemOps; i++)
9948 if (MemOps[i].bitsGT(LargestVT))
9949 LargestVT = MemOps[i];
9950 }
9951 SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl);
9952
9953 // Prepare AAInfo for loads/stores after lowering this memset.
9954 AAMDNodes NewAAInfo = AAInfo;
9955 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
9956
9957 for (unsigned i = 0; i < NumMemOps; i++) {
9958 EVT VT = MemOps[i];
9959 unsigned VTSize = VT.getSizeInBits() / 8;
9960 // The target should specify store types that exactly cover the memset size
9961 // (with the last store potentially being oversized for overlapping stores).
9962 assert(Size > 0 && "Target specified more stores than needed in "
9963 "findOptimalMemOpLowering");
9964 if (VTSize > Size) {
9965 // Issuing an unaligned load / store pair that overlaps with the previous
9966 // pair. Adjust the offset accordingly.
9967 assert(i == NumMemOps-1 && i != 0);
9968 DstOff -= VTSize - Size;
9969 }
9970
9971 // If this store is smaller than the largest store see whether we can get
9972 // the smaller value for free with a truncate or extract vector element and
9973 // then store.
9974 SDValue Value = MemSetValue;
9975 if (VT.bitsLT(LargestVT)) {
9976 unsigned Index;
9977 unsigned NElts = LargestVT.getSizeInBits() / VT.getSizeInBits();
9978 EVT SVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), NElts);
9979 if (!LargestVT.isVector() && !VT.isVector() &&
9980 TLI.isTruncateFree(LargestVT, VT))
9981 Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue);
9982 else if (LargestVT.isVector() && !VT.isVector() &&
9984 LargestVT.getTypeForEVT(*DAG.getContext()),
9985 VT.getSizeInBits(), Index) &&
9986 TLI.isTypeLegal(SVT) &&
9987 LargestVT.getSizeInBits() == SVT.getSizeInBits()) {
9988 // Target which can combine store(extractelement VectorTy, Idx) can get
9989 // the smaller value for free.
9990 SDValue TailValue = DAG.getNode(ISD::BITCAST, dl, SVT, MemSetValue);
9991 Value = DAG.getExtractVectorElt(dl, VT, TailValue, Index);
9992 } else
9993 Value = getMemsetValue(Src, VT, DAG, dl);
9994 }
9995 assert(Value.getValueType() == VT && "Value with wrong type.");
9996 SDValue Store = DAG.getStore(
9997 Chain, dl, Value,
9998 DAG.getObjectPtrOffset(dl, Dst, TypeSize::getFixed(DstOff)),
9999 DstPtrInfo.getWithOffset(DstOff), Alignment,
10001 NewAAInfo);
10002 OutChains.push_back(Store);
10003 DstOff += VT.getSizeInBits() / 8;
10004 // For oversized overlapping stores, only subtract the remaining bytes.
10005 // For normal stores, subtract the full store size.
10006 if (VTSize > Size) {
10007 Size = 0;
10008 } else {
10009 Size -= VTSize;
10010 }
10011 }
10012
10013 // After processing all stores, Size should be exactly 0. Any remaining bytes
10014 // indicate a bug in the target's findOptimalMemOpLowering implementation.
10015 assert(Size == 0 && "Target's findOptimalMemOpLowering did not specify "
10016 "stores that exactly cover the memset size");
10017
10018 return DAG.getTokenFactor(dl, OutChains);
10019}
10020
10022 unsigned AS) {
10023 // Lowering memcpy / memset / memmove intrinsics to calls is only valid if all
10024 // pointer operands can be losslessly bitcasted to pointers of address space 0
10025 if (AS != 0 && !TLI->getTargetMachine().isNoopAddrSpaceCast(AS, 0)) {
10026 report_fatal_error("cannot lower memory intrinsic in address space " +
10027 Twine(AS));
10028 }
10029}
10030
10032 const SelectionDAG *SelDAG,
10033 bool AllowReturnsFirstArg) {
10034 if (!CI || !CI->isTailCall())
10035 return false;
10036 // TODO: Fix "returns-first-arg" determination so it doesn't depend on which
10037 // helper symbol we lower to.
10038 return isInTailCallPosition(*CI, SelDAG->getTarget(),
10039 AllowReturnsFirstArg &&
10041}
10042
10043static std::pair<SDValue, SDValue>
10046 const CallInst *CI, RTLIB::Libcall Call,
10047 SelectionDAG *DAG, const TargetLowering *TLI) {
10048 RTLIB::LibcallImpl LCImpl = DAG->getLibcalls().getLibcallImpl(Call);
10049
10050 if (LCImpl == RTLIB::Unsupported)
10051 return {};
10052
10054 bool IsTailCall =
10055 isInTailCallPositionWrapper(CI, DAG, /*AllowReturnsFirstArg=*/true) &&
10056 // Lowering doesn't support tail calling inside a function with
10057 // a swifterror argument yet.
10058 !DAG->hasSwiftErrorArg();
10059 SDValue Callee =
10060 DAG->getExternalSymbol(LCImpl, TLI->getPointerTy(DAG->getDataLayout()));
10061
10062 CLI.setDebugLoc(dl)
10063 .setChain(Chain)
10065 CI->getType(), Callee, std::move(Args))
10066 .setTailCall(IsTailCall);
10067
10068 return TLI->LowerCallTo(CLI);
10069}
10070
10071std::pair<SDValue, SDValue> SelectionDAG::getStrcmp(SDValue Chain,
10072 const SDLoc &dl, SDValue S1,
10073 SDValue S2,
10074 const CallInst *CI) {
10076 TargetLowering::ArgListTy Args = {{S1, PT}, {S2, PT}};
10077 return getRuntimeCallSDValueHelper(Chain, dl, std::move(Args), CI,
10078 RTLIB::STRCMP, this, TLI);
10079}
10080
10081std::pair<SDValue, SDValue> SelectionDAG::getStrstr(SDValue Chain,
10082 const SDLoc &dl, SDValue S1,
10083 SDValue S2,
10084 const CallInst *CI) {
10086 TargetLowering::ArgListTy Args = {{S1, PT}, {S2, PT}};
10087 return getRuntimeCallSDValueHelper(Chain, dl, std::move(Args), CI,
10088 RTLIB::STRSTR, this, TLI);
10089}
10090
10091std::pair<SDValue, SDValue> SelectionDAG::getMemccpy(SDValue Chain,
10092 const SDLoc &dl,
10093 SDValue Dst, SDValue Src,
10095 const CallInst *CI) {
10097
10099 {Dst, PT},
10100 {Src, PT},
10103 return getRuntimeCallSDValueHelper(Chain, dl, std::move(Args), CI,
10104 RTLIB::MEMCCPY, this, TLI);
10105}
10106
10107std::pair<SDValue, SDValue>
10109 SDValue Mem1, SDValue Size, const CallInst *CI) {
10112 {Mem0, PT},
10113 {Mem1, PT},
10115 return getRuntimeCallSDValueHelper(Chain, dl, std::move(Args), CI,
10116 RTLIB::MEMCMP, this, TLI);
10117}
10118
10119std::pair<SDValue, SDValue> SelectionDAG::getStrcpy(SDValue Chain,
10120 const SDLoc &dl,
10121 SDValue Dst, SDValue Src,
10122 const CallInst *CI) {
10124 TargetLowering::ArgListTy Args = {{Dst, PT}, {Src, PT}};
10125 return getRuntimeCallSDValueHelper(Chain, dl, std::move(Args), CI,
10126 RTLIB::STRCPY, this, TLI);
10127}
10128
10129std::pair<SDValue, SDValue> SelectionDAG::getStrlen(SDValue Chain,
10130 const SDLoc &dl,
10131 SDValue Src,
10132 const CallInst *CI) {
10133 // Emit a library call.
10136 return getRuntimeCallSDValueHelper(Chain, dl, std::move(Args), CI,
10137 RTLIB::STRLEN, this, TLI);
10138}
10139
10141 return TLI->supportSwiftError() &&
10142 MF->getFunction().getAttributes().hasAttrSomewhere(
10143 Attribute::SwiftError);
10144}
10145
10147 SDValue Chain, const SDLoc &dl, SDValue Dst, SDValue Src, SDValue Size,
10148 Align DstAlign, Align SrcAlign, bool isVol, bool AlwaysInline,
10149 const CallInst *CI, std::optional<bool> OverrideTailCall,
10150 MachinePointerInfo DstPtrInfo, MachinePointerInfo SrcPtrInfo,
10151 const AAMDNodes &AAInfo, BatchAAResults *BatchAA) {
10152 // Check to see if we should lower the memcpy to loads and stores first.
10153 // For cases within the target-specified limits, this is the best choice.
10154 const MDNode *DstMemCacheHint =
10155 CI ? getMemCacheHintMetadata(*CI, /*OperandNo=*/0) : nullptr;
10156 const MDNode *SrcMemCacheHint =
10157 CI ? getMemCacheHintMetadata(*CI, /*OperandNo=*/1) : nullptr;
10158
10160 if (ConstantSize) {
10161 // Memcpy with size zero? Just return the original chain.
10162 if (ConstantSize->isZero())
10163 return Chain;
10164
10166 *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), DstAlign,
10167 SrcAlign, isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo, BatchAA,
10168 DstMemCacheHint, SrcMemCacheHint);
10169 if (Result.getNode())
10170 return Result;
10171 }
10172
10173 // Then check to see if we should lower the memcpy with target-specific
10174 // code. If the target chooses to do this, this is the next best.
10175 if (TSI) {
10176 SDValue Result = TSI->EmitTargetCodeForMemcpy(
10177 *this, dl, Chain, Dst, Src, Size, DstAlign, SrcAlign, isVol,
10178 AlwaysInline, DstPtrInfo, SrcPtrInfo);
10179 if (Result.getNode())
10180 return Result;
10181 }
10182
10183 // If we really need inline code and the target declined to provide it,
10184 // use a (potentially long) sequence of loads and stores.
10185 if (AlwaysInline) {
10186 assert(ConstantSize && "AlwaysInline requires a constant size!");
10188 *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), DstAlign,
10189 SrcAlign, isVol, true, DstPtrInfo, SrcPtrInfo, AAInfo, BatchAA,
10190 DstMemCacheHint, SrcMemCacheHint);
10191 }
10192
10195
10196 // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc
10197 // memcpy is not guaranteed to be safe. libc memcpys aren't required to
10198 // respect volatile, so they may do things like read or write memory
10199 // beyond the given memory regions. But fixing this isn't easy, and most
10200 // people don't care.
10201
10202 // Emit a library call.
10205 Args.emplace_back(Dst, PtrTy);
10206 Args.emplace_back(Src, PtrTy);
10207 Args.emplace_back(Size, getDataLayout().getIntPtrType(*getContext()));
10208 // FIXME: pass in SDLoc
10210 bool IsTailCall = false;
10211 RTLIB::LibcallImpl MemCpyImpl = TLI->getMemcpyImpl();
10212
10213 if (OverrideTailCall.has_value()) {
10214 IsTailCall = *OverrideTailCall;
10215 } else {
10216 bool LowersToMemcpy = MemCpyImpl == RTLIB::impl_memcpy;
10217 IsTailCall = isInTailCallPositionWrapper(CI, this, LowersToMemcpy);
10218 }
10219 // Lowering doesn't support tail calling inside a function with a
10220 // swifterror argument yet.
10221 IsTailCall &= !hasSwiftErrorArg();
10222
10223 CLI.setDebugLoc(dl)
10224 .setChain(Chain)
10225 .setLibCallee(
10226 Libcalls->getLibcallImplCallingConv(MemCpyImpl),
10227 Dst.getValueType().getTypeForEVT(*getContext()),
10228 getExternalSymbol(MemCpyImpl, TLI->getPointerTy(getDataLayout())),
10229 std::move(Args))
10231 .setTailCall(IsTailCall);
10232
10233 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
10234 return CallResult.second;
10235}
10236
10238 SDValue Dst, SDValue Src, SDValue Size,
10239 Type *SizeTy, unsigned ElemSz,
10240 bool isTailCall,
10241 MachinePointerInfo DstPtrInfo,
10242 MachinePointerInfo SrcPtrInfo) {
10243 // Lowering doesn't support tail calling inside a function with a
10244 // swifterror argument yet.
10245 isTailCall &= !hasSwiftErrorArg();
10246
10247 // Emit a library call.
10250 Args.emplace_back(Dst, ArgTy);
10251 Args.emplace_back(Src, ArgTy);
10252 Args.emplace_back(Size, SizeTy);
10253
10254 RTLIB::Libcall LibraryCall =
10256 RTLIB::LibcallImpl LibcallImpl = Libcalls->getLibcallImpl(LibraryCall);
10257 if (LibcallImpl == RTLIB::Unsupported)
10258 report_fatal_error("Unsupported element size");
10259
10261 CLI.setDebugLoc(dl)
10262 .setChain(Chain)
10263 .setLibCallee(
10264 Libcalls->getLibcallImplCallingConv(LibcallImpl),
10266 getExternalSymbol(LibcallImpl, TLI->getPointerTy(getDataLayout())),
10267 std::move(Args))
10269 .setTailCall(isTailCall);
10270
10271 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
10272 return CallResult.second;
10273}
10274
10276 SDValue Src, SDValue Size, Align DstAlign,
10277 Align SrcAlign, bool isVol, const CallInst *CI,
10278 std::optional<bool> OverrideTailCall,
10279 MachinePointerInfo DstPtrInfo,
10280 MachinePointerInfo SrcPtrInfo,
10281 const AAMDNodes &AAInfo,
10282 BatchAAResults *BatchAA) {
10283 // Check to see if we should lower the memmove to loads and stores first.
10284 // For cases within the target-specified limits, this is the best choice.
10286 if (ConstantSize) {
10287 // Memmove with size zero? Just return the original chain.
10288 if (ConstantSize->isZero())
10289 return Chain;
10290
10292 *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), DstAlign,
10293 SrcAlign, isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo);
10294 if (Result.getNode())
10295 return Result;
10296 }
10297
10298 // Then check to see if we should lower the memmove with target-specific
10299 // code. If the target chooses to do this, this is the next best.
10300 if (TSI) {
10301 SDValue Result = TSI->EmitTargetCodeForMemmove(
10302 *this, dl, Chain, Dst, Src, Size, DstAlign, SrcAlign, isVol, DstPtrInfo,
10303 SrcPtrInfo);
10304 if (Result.getNode())
10305 return Result;
10306 }
10307
10310
10311 // FIXME: If the memmove is volatile, lowering it to plain libc memmove may
10312 // not be safe. See memcpy above for more details.
10313
10314 // Emit a library call.
10317 Args.emplace_back(Dst, PtrTy);
10318 Args.emplace_back(Src, PtrTy);
10319 Args.emplace_back(Size, getDataLayout().getIntPtrType(*getContext()));
10320 // FIXME: pass in SDLoc
10322
10323 RTLIB::LibcallImpl MemmoveImpl = Libcalls->getLibcallImpl(RTLIB::MEMMOVE);
10324
10325 bool IsTailCall = false;
10326 if (OverrideTailCall.has_value()) {
10327 IsTailCall = *OverrideTailCall;
10328 } else {
10329 bool LowersToMemmove = MemmoveImpl == RTLIB::impl_memmove;
10330 IsTailCall = isInTailCallPositionWrapper(CI, this, LowersToMemmove);
10331 }
10332 // Lowering doesn't support tail calling inside a function with a
10333 // swifterror argument yet.
10334 IsTailCall &= !hasSwiftErrorArg();
10335
10336 CLI.setDebugLoc(dl)
10337 .setChain(Chain)
10338 .setLibCallee(
10339 Libcalls->getLibcallImplCallingConv(MemmoveImpl),
10340 Dst.getValueType().getTypeForEVT(*getContext()),
10341 getExternalSymbol(MemmoveImpl, TLI->getPointerTy(getDataLayout())),
10342 std::move(Args))
10344 .setTailCall(IsTailCall);
10345
10346 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
10347 return CallResult.second;
10348}
10349
10351 SDValue Dst, SDValue Src, SDValue Size,
10352 Type *SizeTy, unsigned ElemSz,
10353 bool isTailCall,
10354 MachinePointerInfo DstPtrInfo,
10355 MachinePointerInfo SrcPtrInfo) {
10356 // Lowering doesn't support tail calling inside a function with a
10357 // swifterror argument yet.
10358 isTailCall &= !hasSwiftErrorArg();
10359
10360 // Emit a library call.
10363 Args.emplace_back(Dst, IntPtrTy);
10364 Args.emplace_back(Src, IntPtrTy);
10365 Args.emplace_back(Size, SizeTy);
10366
10367 RTLIB::Libcall LibraryCall =
10369 RTLIB::LibcallImpl LibcallImpl = Libcalls->getLibcallImpl(LibraryCall);
10370 if (LibcallImpl == RTLIB::Unsupported)
10371 report_fatal_error("Unsupported element size");
10372
10374 CLI.setDebugLoc(dl)
10375 .setChain(Chain)
10376 .setLibCallee(
10377 Libcalls->getLibcallImplCallingConv(LibcallImpl),
10379 getExternalSymbol(LibcallImpl, TLI->getPointerTy(getDataLayout())),
10380 std::move(Args))
10382 .setTailCall(isTailCall);
10383
10384 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
10385 return CallResult.second;
10386}
10387
10389 SDValue Src, SDValue Size, Align Alignment,
10390 bool isVol, bool AlwaysInline,
10391 const CallInst *CI,
10392 MachinePointerInfo DstPtrInfo,
10393 const AAMDNodes &AAInfo) {
10394 // Check to see if we should lower the memset to stores first.
10395 // For cases within the target-specified limits, this is the best choice.
10397 if (ConstantSize) {
10398 // Memset with size zero? Just return the original chain.
10399 if (ConstantSize->isZero())
10400 return Chain;
10401
10402 SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src,
10403 ConstantSize->getZExtValue(), Alignment,
10404 isVol, false, DstPtrInfo, AAInfo);
10405
10406 if (Result.getNode())
10407 return Result;
10408 }
10409
10410 // Then check to see if we should lower the memset with target-specific
10411 // code. If the target chooses to do this, this is the next best.
10412 if (TSI) {
10413 SDValue Result = TSI->EmitTargetCodeForMemset(
10414 *this, dl, Chain, Dst, Src, Size, Alignment, isVol, AlwaysInline, DstPtrInfo);
10415 if (Result.getNode())
10416 return Result;
10417 }
10418
10419 // If we really need inline code and the target declined to provide it,
10420 // use a (potentially long) sequence of loads and stores.
10421 if (AlwaysInline) {
10422 assert(ConstantSize && "AlwaysInline requires a constant size!");
10423 SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src,
10424 ConstantSize->getZExtValue(), Alignment,
10425 isVol, true, DstPtrInfo, AAInfo);
10426 assert(Result &&
10427 "getMemsetStores must return a valid sequence when AlwaysInline");
10428 return Result;
10429 }
10430
10432
10433 // Emit a library call.
10434 auto &Ctx = *getContext();
10435 const auto& DL = getDataLayout();
10436
10438 // FIXME: pass in SDLoc
10439 CLI.setDebugLoc(dl).setChain(Chain);
10440
10441 RTLIB::LibcallImpl BzeroImpl = Libcalls->getLibcallImpl(RTLIB::BZERO);
10442 bool UseBZero = BzeroImpl != RTLIB::Unsupported && isNullConstant(Src);
10443
10444 // If zeroing out and bzero is present, use it.
10445 if (UseBZero) {
10447 Args.emplace_back(Dst, PointerType::getUnqual(Ctx));
10448 Args.emplace_back(Size, DL.getIntPtrType(Ctx));
10449 CLI.setLibCallee(
10450 Libcalls->getLibcallImplCallingConv(BzeroImpl), Type::getVoidTy(Ctx),
10451 getExternalSymbol(BzeroImpl, TLI->getPointerTy(DL)), std::move(Args));
10452 } else {
10453 RTLIB::LibcallImpl MemsetImpl = Libcalls->getLibcallImpl(RTLIB::MEMSET);
10454
10456 Args.emplace_back(Dst, PointerType::getUnqual(Ctx));
10457 Args.emplace_back(Src, Src.getValueType().getTypeForEVT(Ctx));
10458 Args.emplace_back(Size, DL.getIntPtrType(Ctx));
10459 CLI.setLibCallee(Libcalls->getLibcallImplCallingConv(MemsetImpl),
10460 Dst.getValueType().getTypeForEVT(Ctx),
10461 getExternalSymbol(MemsetImpl, TLI->getPointerTy(DL)),
10462 std::move(Args));
10463 }
10464
10465 RTLIB::LibcallImpl MemsetImpl = Libcalls->getLibcallImpl(RTLIB::MEMSET);
10466 bool LowersToMemset = MemsetImpl == RTLIB::impl_memset;
10467
10468 // If we're going to use bzero, make sure not to tail call unless the
10469 // subsequent return doesn't need a value, as bzero doesn't return the first
10470 // arg unlike memset.
10471 bool ReturnsFirstArg = CI && funcReturnsFirstArgOfCall(*CI) && !UseBZero;
10472 bool IsTailCall = CI && CI->isTailCall() &&
10474 ReturnsFirstArg && LowersToMemset) &&
10475 // Lowering doesn't support tail calling inside a function
10476 // with a swifterror argument yet.
10478 CLI.setDiscardResult().setTailCall(IsTailCall);
10479
10480 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
10481 return CallResult.second;
10482}
10483
10486 Type *SizeTy, unsigned ElemSz,
10487 bool isTailCall,
10488 MachinePointerInfo DstPtrInfo) {
10489 // Lowering doesn't support tail calling inside a function with a
10490 // swifterror argument yet.
10491 isTailCall &= !hasSwiftErrorArg();
10492
10493 // Emit a library call.
10495 Args.emplace_back(Dst, getDataLayout().getIntPtrType(*getContext()));
10496 Args.emplace_back(Value, Type::getInt8Ty(*getContext()));
10497 Args.emplace_back(Size, SizeTy);
10498
10499 RTLIB::Libcall LibraryCall =
10501 RTLIB::LibcallImpl LibcallImpl = Libcalls->getLibcallImpl(LibraryCall);
10502 if (LibcallImpl == RTLIB::Unsupported)
10503 report_fatal_error("Unsupported element size");
10504
10506 CLI.setDebugLoc(dl)
10507 .setChain(Chain)
10508 .setLibCallee(
10509 Libcalls->getLibcallImplCallingConv(LibcallImpl),
10511 getExternalSymbol(LibcallImpl, TLI->getPointerTy(getDataLayout())),
10512 std::move(Args))
10514 .setTailCall(isTailCall);
10515
10516 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
10517 return CallResult.second;
10518}
10519
10520SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
10522 MachineMemOperand *MMO,
10523 ISD::LoadExtType ExtType) {
10525 AddNodeIDNode(ID, Opcode, VTList, Ops);
10526 ID.AddInteger(MemVT.getRawBits());
10527 ID.AddInteger(getSyntheticNodeSubclassData<AtomicSDNode>(
10528 dl.getIROrder(), Opcode, VTList, MemVT, MMO, ExtType));
10529 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
10530 ID.AddInteger(MMO->getFlags());
10531 void* IP = nullptr;
10532 if (auto *E = cast_or_null<AtomicSDNode>(FindNodeOrInsertPos(ID, dl, IP))) {
10533 E->refineAlignment(MMO);
10534 E->refineMMOMetadata(MMO);
10535 return SDValue(E, 0);
10536 }
10537
10538 auto *N = newSDNode<AtomicSDNode>(dl.getIROrder(), dl.getDebugLoc(), Opcode,
10539 VTList, MemVT, MMO, ExtType);
10540 createOperands(N, Ops);
10541
10542 CSEMap.InsertNode(N, IP);
10543 InsertNode(N);
10544 SDValue V(N, 0);
10545 NewSDValueDbgMsg(V, "Creating new node: ", this);
10546 return V;
10547}
10548
10550 EVT MemVT, SDVTList VTs, SDValue Chain,
10551 SDValue Ptr, SDValue Cmp, SDValue Swp,
10552 MachineMemOperand *MMO) {
10553 assert(Opcode == ISD::ATOMIC_CMP_SWAP ||
10555 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
10556
10557 SDValue Ops[] = {Chain, Ptr, Cmp, Swp};
10558 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
10559}
10560
10561SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
10562 SDValue Chain, SDValue Ptr, SDValue Val,
10563 MachineMemOperand *MMO) {
10564 assert((Opcode == ISD::ATOMIC_LOAD_ADD || Opcode == ISD::ATOMIC_LOAD_SUB ||
10565 Opcode == ISD::ATOMIC_LOAD_AND || Opcode == ISD::ATOMIC_LOAD_CLR ||
10566 Opcode == ISD::ATOMIC_LOAD_OR || Opcode == ISD::ATOMIC_LOAD_XOR ||
10567 Opcode == ISD::ATOMIC_LOAD_NAND || Opcode == ISD::ATOMIC_LOAD_MIN ||
10568 Opcode == ISD::ATOMIC_LOAD_MAX || Opcode == ISD::ATOMIC_LOAD_UMIN ||
10569 Opcode == ISD::ATOMIC_LOAD_UMAX || Opcode == ISD::ATOMIC_LOAD_FADD ||
10570 Opcode == ISD::ATOMIC_LOAD_FSUB || Opcode == ISD::ATOMIC_LOAD_FMAX ||
10571 Opcode == ISD::ATOMIC_LOAD_FMIN ||
10572 Opcode == ISD::ATOMIC_LOAD_FMINIMUM ||
10573 Opcode == ISD::ATOMIC_LOAD_FMAXIMUM ||
10574 Opcode == ISD::ATOMIC_LOAD_UINC_WRAP ||
10575 Opcode == ISD::ATOMIC_LOAD_UDEC_WRAP ||
10576 Opcode == ISD::ATOMIC_LOAD_USUB_COND ||
10577 Opcode == ISD::ATOMIC_LOAD_USUB_SAT || Opcode == ISD::ATOMIC_SWAP ||
10578 Opcode == ISD::ATOMIC_STORE) &&
10579 "Invalid Atomic Op");
10580
10581 EVT VT = Val.getValueType();
10582
10583 SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) :
10584 getVTList(VT, MVT::Other);
10585 SDValue Ops[] = {Chain, Ptr, Val};
10586 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
10587}
10588
10590 EVT MemVT, EVT VT, SDValue Chain,
10591 SDValue Ptr, MachineMemOperand *MMO) {
10592 SDVTList VTs = getVTList(VT, MVT::Other);
10593 SDValue Ops[] = {Chain, Ptr};
10594 return getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, VTs, Ops, MMO, ExtType);
10595}
10596
10597/// getMergeValues - Create a MERGE_VALUES node from the given operands.
10599 if (Ops.size() == 1)
10600 return Ops[0];
10601
10603 VTs.reserve(Ops.size());
10604 for (const SDValue &Op : Ops)
10605 VTs.push_back(Op.getValueType());
10606 return getNode(ISD::MERGE_VALUES, dl, getVTList(VTs), Ops);
10607}
10608
10610 SDValue Chain, const SDLoc &dl) {
10611 SmallVector<SDValue, 4> RetValues;
10612 RetValues.reserve(ResultTypes.size());
10613 for (EVT VT : ResultTypes)
10614 RetValues.push_back(VT == MVT::Other ? Chain : getPOISON(VT));
10615 return getMergeValues(RetValues, dl);
10616}
10617
10619 unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef<SDValue> Ops,
10620 EVT MemVT, MachinePointerInfo PtrInfo, Align Alignment,
10622 const AAMDNodes &AAInfo) {
10623 if (Size.hasValue() && !Size.getValue())
10625
10627 MachineMemOperand *MMO =
10628 MF.getMachineMemOperand(PtrInfo, Flags, Size, Alignment, AAInfo);
10629
10630 return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, MMO);
10631}
10632
10634 SDVTList VTList,
10635 ArrayRef<SDValue> Ops, EVT MemVT,
10636 MachineMemOperand *MMO) {
10637 return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, ArrayRef(MMO));
10638}
10639
10641 SDVTList VTList,
10642 ArrayRef<SDValue> Ops, EVT MemVT,
10644 assert(!MMOs.empty() && "Must have at least one MMO");
10645 assert(
10646 (Opcode == ISD::INTRINSIC_VOID || Opcode == ISD::INTRINSIC_W_CHAIN ||
10647 Opcode == ISD::PREFETCH ||
10648 (Opcode <= (unsigned)std::numeric_limits<int>::max() &&
10649 Opcode >= ISD::BUILTIN_OP_END && TSI->isTargetMemoryOpcode(Opcode))) &&
10650 "Opcode is not a memory-accessing opcode!");
10651
10653 if (MMOs.size() == 1) {
10654 MemRefs = MMOs[0];
10655 } else {
10656 // Allocate: [size_t count][MMO*][MMO*]...
10657 size_t AllocSize =
10658 sizeof(size_t) + MMOs.size() * sizeof(MachineMemOperand *);
10659 void *Buffer = Allocator.Allocate(AllocSize, alignof(size_t));
10660 size_t *CountPtr = static_cast<size_t *>(Buffer);
10661 *CountPtr = MMOs.size();
10662 MachineMemOperand **Array =
10663 reinterpret_cast<MachineMemOperand **>(CountPtr + 1);
10664 llvm::copy(MMOs, Array);
10665 MemRefs = Array;
10666 }
10667
10668 // Memoize the node unless it returns a glue result.
10670 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
10672 AddNodeIDNode(ID, Opcode, VTList, Ops);
10673 ID.AddInteger(getSyntheticNodeSubclassData<MemIntrinsicSDNode>(
10674 Opcode, dl.getIROrder(), VTList, MemVT, MemRefs));
10675 ID.AddInteger(MemVT.getRawBits());
10676 for (const MachineMemOperand *MMO : MMOs) {
10677 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
10678 ID.AddInteger(MMO->getFlags());
10679 }
10680 void *IP = nullptr;
10681 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
10682 cast<MemIntrinsicSDNode>(E)->refineAlignment(MMOs);
10683 return SDValue(E, 0);
10684 }
10685
10686 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
10687 VTList, MemVT, MemRefs);
10688 createOperands(N, Ops);
10689 CSEMap.InsertNode(N, IP);
10690 } else {
10691 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
10692 VTList, MemVT, MemRefs);
10693 createOperands(N, Ops);
10694 }
10695 InsertNode(N);
10696 SDValue V(N, 0);
10697 NewSDValueDbgMsg(V, "Creating new node: ", this);
10698 return V;
10699}
10700
10702 SDValue Chain, int FrameIndex) {
10703 const unsigned Opcode = IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END;
10704 const auto VTs = getVTList(MVT::Other);
10705 SDValue Ops[2] = {
10706 Chain,
10707 getFrameIndex(FrameIndex,
10708 getTargetLoweringInfo().getFrameIndexTy(getDataLayout()),
10709 true)};
10710
10712 AddNodeIDNode(ID, Opcode, VTs, Ops);
10713 ID.AddInteger(FrameIndex);
10714 void *IP = nullptr;
10715 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
10716 return SDValue(E, 0);
10717
10718 LifetimeSDNode *N =
10719 newSDNode<LifetimeSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), VTs);
10720 createOperands(N, Ops);
10721 CSEMap.InsertNode(N, IP);
10722 InsertNode(N);
10723 SDValue V(N, 0);
10724 NewSDValueDbgMsg(V, "Creating new node: ", this);
10725 return V;
10726}
10727
10729 uint64_t Guid, uint64_t Index,
10730 uint32_t Attr) {
10731 const unsigned Opcode = ISD::PSEUDO_PROBE;
10732 const auto VTs = getVTList(MVT::Other);
10733 SDValue Ops[] = {Chain};
10735 AddNodeIDNode(ID, Opcode, VTs, Ops);
10736 ID.AddInteger(Guid);
10737 ID.AddInteger(Index);
10738 void *IP = nullptr;
10739 if (SDNode *E = FindNodeOrInsertPos(ID, Dl, IP))
10740 return SDValue(E, 0);
10741
10742 auto *N = newSDNode<PseudoProbeSDNode>(
10743 Opcode, Dl.getIROrder(), Dl.getDebugLoc(), VTs, Guid, Index, Attr);
10744 createOperands(N, Ops);
10745 CSEMap.InsertNode(N, IP);
10746 InsertNode(N);
10747 SDValue V(N, 0);
10748 NewSDValueDbgMsg(V, "Creating new node: ", this);
10749 return V;
10750}
10751
10752/// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
10753/// MachinePointerInfo record from it. This is particularly useful because the
10754/// code generator has many cases where it doesn't bother passing in a
10755/// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
10757 SelectionDAG &DAG, SDValue Ptr,
10758 int64_t Offset = 0) {
10759 // If this is FI+Offset, we can model it.
10760 if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr))
10762 FI->getIndex(), Offset);
10763
10764 // If this is (FI+Offset1)+Offset2, we can model it.
10765 if (Ptr.getOpcode() != ISD::ADD ||
10768 return Info;
10769
10770 int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
10772 DAG.getMachineFunction(), FI,
10773 Offset + cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue());
10774}
10775
10776/// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
10777/// MachinePointerInfo record from it. This is particularly useful because the
10778/// code generator has many cases where it doesn't bother passing in a
10779/// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
10781 SelectionDAG &DAG, SDValue Ptr,
10782 SDValue OffsetOp) {
10783 // If the 'Offset' value isn't a constant, we can't handle this.
10785 return InferPointerInfo(Info, DAG, Ptr, OffsetNode->getSExtValue());
10786 if (OffsetOp.isUndef())
10787 return InferPointerInfo(Info, DAG, Ptr);
10788 return Info;
10789}
10790
10792 EVT VT, const SDLoc &dl, SDValue Chain,
10793 SDValue Ptr, SDValue Offset,
10794 MachinePointerInfo PtrInfo, EVT MemVT,
10795 Align Alignment,
10796 MachineMemOperand::Flags MMOFlags,
10797 const MMOMetadata &Metadata) {
10798 assert(Chain.getValueType() == MVT::Other &&
10799 "Invalid chain type");
10800
10801 MMOFlags |= MachineMemOperand::MOLoad;
10802 assert((MMOFlags & MachineMemOperand::MOStore) == 0);
10803 // If we don't have a PtrInfo, infer the trivial frame index case to simplify
10804 // clients.
10805 if (PtrInfo.V.isNull())
10806 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
10807
10808 TypeSize Size = MemVT.getStoreSize();
10810 MachineMemOperand *MMO =
10811 MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, Alignment, Metadata);
10812 return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO);
10813}
10814
10816 EVT VT, const SDLoc &dl, SDValue Chain,
10817 SDValue Ptr, SDValue Offset, EVT MemVT,
10818 MachineMemOperand *MMO) {
10819 if (VT == MemVT) {
10820 ExtType = ISD::NON_EXTLOAD;
10821 } else if (ExtType == ISD::NON_EXTLOAD) {
10822 assert(VT == MemVT && "Non-extending load from different memory type!");
10823 } else {
10824 // Extending load.
10825 assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) &&
10826 "Should only be an extending load, not truncating!");
10827 assert(VT.isInteger() == MemVT.isInteger() &&
10828 "Cannot convert from FP to Int or Int -> FP!");
10829 assert(VT.isVector() == MemVT.isVector() &&
10830 "Cannot use an ext load to convert to or from a vector!");
10831 assert((!VT.isVector() ||
10833 "Cannot use an ext load to change the number of vector elements!");
10834 }
10835
10836 assert((!MMO->getRanges() ||
10838 ->getBitWidth() == MemVT.getScalarSizeInBits() &&
10839 MemVT.isInteger())) &&
10840 "Range metadata and load type must match!");
10841
10842 bool Indexed = AM != ISD::UNINDEXED;
10843 assert((Indexed || Offset.getOpcode() == ISD::POISON) &&
10844 "Unindexed load with an offset!");
10845
10846 SDVTList VTs = Indexed ?
10847 getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
10848 SDValue Ops[] = { Chain, Ptr, Offset };
10850 AddNodeIDNode(ID, ISD::LOAD, VTs, Ops);
10851 ID.AddInteger(MemVT.getRawBits());
10852 ID.AddInteger(getSyntheticNodeSubclassData<LoadSDNode>(
10853 dl.getIROrder(), VTs, AM, ExtType, MemVT, MMO));
10854 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
10855 ID.AddInteger(MMO->getFlags());
10856 void *IP = nullptr;
10857 if (auto *E = cast_or_null<LoadSDNode>(FindNodeOrInsertPos(ID, dl, IP))) {
10858 E->refineAlignment(MMO);
10859 E->refineMMOMetadata(MMO);
10860 return SDValue(E, 0);
10861 }
10862 auto *N = newSDNode<LoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
10863 ExtType, MemVT, MMO);
10864 createOperands(N, Ops);
10865
10866 CSEMap.InsertNode(N, IP);
10867 InsertNode(N);
10868 SDValue V(N, 0);
10869 NewSDValueDbgMsg(V, "Creating new node: ", this);
10870 return V;
10871}
10872
10874 SDValue Ptr, MachinePointerInfo PtrInfo,
10875 MaybeAlign Alignment,
10876 MachineMemOperand::Flags MMOFlags,
10877 const MMOMetadata &Metadata) {
10879 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
10880 PtrInfo, VT, Alignment, MMOFlags, Metadata);
10881}
10882
10884 SDValue Ptr, MachineMemOperand *MMO) {
10886 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
10887 VT, MMO);
10888}
10889
10891 EVT VT, SDValue Chain, SDValue Ptr,
10892 MachinePointerInfo PtrInfo, EVT MemVT,
10893 MaybeAlign Alignment,
10894 MachineMemOperand::Flags MMOFlags,
10895 const MMOMetadata &Metadata) {
10897 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, PtrInfo,
10898 MemVT, Alignment, MMOFlags, Metadata);
10899}
10900
10902 EVT VT, SDValue Chain, SDValue Ptr, EVT MemVT,
10903 MachineMemOperand *MMO) {
10905 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef,
10906 MemVT, MMO);
10907}
10908
10912 LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
10913 assert(LD->getOffset().getOpcode() == ISD::POISON &&
10914 "Load is already a indexed load!");
10915 // Don't propagate the invariant or dereferenceable flags.
10916 auto MMOFlags =
10917 LD->getMemOperand()->getFlags() &
10919 return getLoad(
10920 AM, LD->getExtensionType(), OrigLoad.getValueType(), dl, LD->getChain(),
10921 Base, Offset, LD->getPointerInfo(), LD->getMemoryVT(), LD->getAlign(),
10922 MMOFlags,
10923 MMOMetadata(LD->getAAInfo(), LD->getRanges(), LD->getMemCacheHint()));
10924}
10925
10927 SDValue Ptr, MachinePointerInfo PtrInfo,
10928 Align Alignment,
10929 MachineMemOperand::Flags MMOFlags,
10930 const MMOMetadata &Metadata) {
10931 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
10932
10933 MMOFlags |= MachineMemOperand::MOStore;
10934 assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
10935 assert(!Metadata.Ranges && "range metadata is invalid for stores");
10936
10937 if (PtrInfo.V.isNull())
10938 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
10939
10942 MachineMemOperand *MMO =
10943 MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, Alignment, Metadata);
10944 return getStore(Chain, dl, Val, Ptr, MMO);
10945}
10946
10948 SDValue Ptr, MachineMemOperand *MMO) {
10950 return getStore(Chain, dl, Val, Ptr, Undef, Val.getValueType(), MMO,
10952}
10953
10955 SDValue Ptr, SDValue Offset, EVT SVT,
10957 bool IsTruncating) {
10958 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
10959 EVT VT = Val.getValueType();
10960 if (VT == SVT) {
10961 IsTruncating = false;
10962 } else if (!IsTruncating) {
10963 assert(VT == SVT && "No-truncating store from different memory type!");
10964 } else {
10966 "Should only be a truncating store, not extending!");
10967 assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!");
10968 assert(VT.isVector() == SVT.isVector() &&
10969 "Cannot use trunc store to convert to or from a vector!");
10970 assert((!VT.isVector() ||
10972 "Cannot use trunc store to change the number of vector elements!");
10973 }
10974
10975 bool Indexed = AM != ISD::UNINDEXED;
10976 assert((Indexed || Offset.getOpcode() == ISD::POISON) &&
10977 "Unindexed store with an offset!");
10978 SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other)
10979 : getVTList(MVT::Other);
10980 SDValue Ops[] = {Chain, Val, Ptr, Offset};
10982 AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
10983 ID.AddInteger(SVT.getRawBits());
10984 ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
10985 dl.getIROrder(), VTs, AM, IsTruncating, SVT, MMO));
10986 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
10987 ID.AddInteger(MMO->getFlags());
10988 void *IP = nullptr;
10989 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
10990 cast<StoreSDNode>(E)->refineAlignment(MMO);
10991 cast<StoreSDNode>(E)->refineMMOMetadata(MMO);
10992 return SDValue(E, 0);
10993 }
10994 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
10995 IsTruncating, SVT, MMO);
10996 createOperands(N, Ops);
10997
10998 CSEMap.InsertNode(N, IP);
10999 InsertNode(N);
11000 SDValue V(N, 0);
11001 NewSDValueDbgMsg(V, "Creating new node: ", this);
11002 return V;
11003}
11004
11006 SDValue Ptr, SDValue Offset,
11007 MachinePointerInfo PtrInfo, EVT SVT,
11008 Align Alignment,
11009 MachineMemOperand::Flags MMOFlags,
11010 const MMOMetadata &Metadata) {
11011 assert(Chain.getValueType() == MVT::Other &&
11012 "Invalid chain type");
11013
11014 MMOFlags |= MachineMemOperand::MOStore;
11015 assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
11016 assert(!Metadata.Ranges && "range metadata is invalid for stores");
11017
11018 if (PtrInfo.V.isNull())
11019 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
11020
11022 MachineMemOperand *MMO = MF.getMachineMemOperand(
11023 PtrInfo, MMOFlags, SVT.getStoreSize(), Alignment, Metadata);
11024 return getTruncStore(Chain, dl, Val, Ptr, Offset, SVT, MMO);
11025}
11026
11028 SDValue Ptr, MachinePointerInfo PtrInfo,
11029 EVT SVT, Align Alignment,
11030 MachineMemOperand::Flags MMOFlags,
11031 const MMOMetadata &Metadata) {
11032 return getTruncStore(Chain, dl, Val, Ptr, getPOISON(Ptr.getValueType()),
11033 PtrInfo, SVT, Alignment, MMOFlags, Metadata);
11034}
11035
11037 SDValue Ptr, SDValue Offset, EVT SVT,
11038 MachineMemOperand *MMO) {
11039 return getStore(Chain, dl, Val, Ptr, Offset, SVT, MMO, ISD::UNINDEXED, true);
11040}
11041
11043 SDValue Ptr, EVT SVT,
11044 MachineMemOperand *MMO) {
11045 return getStore(Chain, dl, Val, Ptr, getPOISON(Ptr.getValueType()), SVT, MMO,
11046 ISD::UNINDEXED, true);
11047}
11048
11052 StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
11053 assert(ST->getOffset().getOpcode() == ISD::POISON &&
11054 "Store is already a indexed store!");
11055 return getStore(ST->getChain(), dl, ST->getValue(), Base, Offset,
11056 ST->getMemoryVT(), ST->getMemOperand(), AM,
11057 ST->isTruncatingStore());
11058}
11059
11061 ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &dl,
11062 SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Mask, SDValue EVL,
11063 MachinePointerInfo PtrInfo, EVT MemVT, Align Alignment,
11064 MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
11065 const MDNode *Ranges, bool IsExpanding) {
11066 MMOFlags |= MachineMemOperand::MOLoad;
11067 assert((MMOFlags & MachineMemOperand::MOStore) == 0);
11068 // If we don't have a PtrInfo, infer the trivial frame index case to simplify
11069 // clients.
11070 if (PtrInfo.V.isNull())
11071 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
11072
11073 TypeSize Size = MemVT.getStoreSize();
11075 MachineMemOperand *MMO = MF.getMachineMemOperand(
11076 PtrInfo, MMOFlags, Size, Alignment, MMOMetadata(AAInfo, Ranges));
11077 return getLoadVP(AM, ExtType, VT, dl, Chain, Ptr, Offset, Mask, EVL, MemVT,
11078 MMO, IsExpanding);
11079}
11080
11082 ISD::LoadExtType ExtType, EVT VT,
11083 const SDLoc &dl, SDValue Chain, SDValue Ptr,
11084 SDValue Offset, SDValue Mask, SDValue EVL,
11085 EVT MemVT, MachineMemOperand *MMO,
11086 bool IsExpanding) {
11087 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
11088 assert(Mask.getValueType().getVectorElementCount() ==
11089 VT.getVectorElementCount() &&
11090 "Vector width mismatch between mask and data");
11091
11092 bool Indexed = AM != ISD::UNINDEXED;
11093 assert((Indexed || Offset.getOpcode() == ISD::POISON) &&
11094 "Unindexed load with an offset!");
11095
11096 SDVTList VTs = Indexed ? getVTList(VT, Ptr.getValueType(), MVT::Other)
11097 : getVTList(VT, MVT::Other);
11098 SDValue Ops[] = {Chain, Ptr, Offset, Mask, EVL};
11100 AddNodeIDNode(ID, ISD::VP_LOAD, VTs, Ops);
11101 ID.AddInteger(MemVT.getRawBits());
11102 ID.AddInteger(getSyntheticNodeSubclassData<VPLoadSDNode>(
11103 dl.getIROrder(), VTs, AM, ExtType, IsExpanding, MemVT, MMO));
11104 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11105 ID.AddInteger(MMO->getFlags());
11106 void *IP = nullptr;
11107 if (auto *E = cast_or_null<VPLoadSDNode>(FindNodeOrInsertPos(ID, dl, IP))) {
11108 E->refineAlignment(MMO);
11109 E->refineMMOMetadata(MMO);
11110 return SDValue(E, 0);
11111 }
11112 auto *N = newSDNode<VPLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
11113 ExtType, IsExpanding, MemVT, MMO);
11114 createOperands(N, Ops);
11115
11116 CSEMap.InsertNode(N, IP);
11117 InsertNode(N);
11118 SDValue V(N, 0);
11119 NewSDValueDbgMsg(V, "Creating new node: ", this);
11120 return V;
11121}
11122
11124 SDValue Ptr, SDValue Mask, SDValue EVL,
11125 MachinePointerInfo PtrInfo,
11126 MaybeAlign Alignment,
11127 MachineMemOperand::Flags MMOFlags,
11128 const AAMDNodes &AAInfo, const MDNode *Ranges,
11129 bool IsExpanding) {
11131 return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
11132 Mask, EVL, PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges,
11133 IsExpanding);
11134}
11135
11137 SDValue Ptr, SDValue Mask, SDValue EVL,
11138 MachineMemOperand *MMO, bool IsExpanding) {
11140 return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
11141 Mask, EVL, VT, MMO, IsExpanding);
11142}
11143
11145 EVT VT, SDValue Chain, SDValue Ptr,
11146 SDValue Mask, SDValue EVL,
11147 MachinePointerInfo PtrInfo, EVT MemVT,
11148 MaybeAlign Alignment,
11149 MachineMemOperand::Flags MMOFlags,
11150 const AAMDNodes &AAInfo, bool IsExpanding) {
11152 return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask,
11153 EVL, PtrInfo, MemVT, Alignment, MMOFlags, AAInfo, nullptr,
11154 IsExpanding);
11155}
11156
11158 EVT VT, SDValue Chain, SDValue Ptr,
11159 SDValue Mask, SDValue EVL, EVT MemVT,
11160 MachineMemOperand *MMO, bool IsExpanding) {
11162 return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask,
11163 EVL, MemVT, MMO, IsExpanding);
11164}
11165
11169 auto *LD = cast<VPLoadSDNode>(OrigLoad);
11170 assert(LD->getOffset().getOpcode() == ISD::POISON &&
11171 "Load is already a indexed load!");
11172 // Don't propagate the invariant or dereferenceable flags.
11173 auto MMOFlags =
11174 LD->getMemOperand()->getFlags() &
11176 return getLoadVP(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
11177 LD->getChain(), Base, Offset, LD->getMask(),
11178 LD->getVectorLength(), LD->getPointerInfo(),
11179 LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo(),
11180 nullptr, LD->isExpandingLoad());
11181}
11182
11184 SDValue Ptr, SDValue Offset, SDValue Mask,
11185 SDValue EVL, EVT MemVT, MachineMemOperand *MMO,
11186 ISD::MemIndexedMode AM, bool IsTruncating,
11187 bool IsCompressing) {
11188 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
11189 assert(Mask.getValueType().getVectorElementCount() ==
11191 "Vector width mismatch between mask and data");
11192
11193 bool Indexed = AM != ISD::UNINDEXED;
11194 assert((Indexed || Offset.getOpcode() == ISD::POISON) &&
11195 "Unindexed vp_store with an offset!");
11196 SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other)
11197 : getVTList(MVT::Other);
11198 SDValue Ops[] = {Chain, Val, Ptr, Offset, Mask, EVL};
11200 AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
11201 ID.AddInteger(MemVT.getRawBits());
11202 ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>(
11203 dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
11204 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11205 ID.AddInteger(MMO->getFlags());
11206 void *IP = nullptr;
11207 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
11208 cast<VPStoreSDNode>(E)->refineAlignment(MMO);
11209 return SDValue(E, 0);
11210 }
11211 auto *N = newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
11212 IsTruncating, IsCompressing, MemVT, MMO);
11213 createOperands(N, Ops);
11214
11215 CSEMap.InsertNode(N, IP);
11216 InsertNode(N);
11217 SDValue V(N, 0);
11218 NewSDValueDbgMsg(V, "Creating new node: ", this);
11219 return V;
11220}
11221
11223 SDValue Val, SDValue Ptr, SDValue Mask,
11224 SDValue EVL, MachinePointerInfo PtrInfo,
11225 EVT SVT, Align Alignment,
11226 MachineMemOperand::Flags MMOFlags,
11227 const AAMDNodes &AAInfo,
11228 bool IsCompressing) {
11229 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
11230
11231 MMOFlags |= MachineMemOperand::MOStore;
11232 assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
11233
11234 if (PtrInfo.V.isNull())
11235 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
11236
11238 MachineMemOperand *MMO = MF.getMachineMemOperand(
11239 PtrInfo, MMOFlags, SVT.getStoreSize(), Alignment, AAInfo);
11240 return getTruncStoreVP(Chain, dl, Val, Ptr, Mask, EVL, SVT, MMO,
11241 IsCompressing);
11242}
11243
11245 SDValue Val, SDValue Ptr, SDValue Mask,
11246 SDValue EVL, EVT SVT,
11247 MachineMemOperand *MMO,
11248 bool IsCompressing) {
11249 EVT VT = Val.getValueType();
11250
11251 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
11252 if (VT == SVT)
11253 return getStoreVP(Chain, dl, Val, Ptr, getPOISON(Ptr.getValueType()), Mask,
11254 EVL, VT, MMO, ISD::UNINDEXED,
11255 /*IsTruncating*/ false, IsCompressing);
11256
11258 "Should only be a truncating store, not extending!");
11259 assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!");
11260 assert(VT.isVector() == SVT.isVector() &&
11261 "Cannot use trunc store to convert to or from a vector!");
11262 assert((!VT.isVector() ||
11264 "Cannot use trunc store to change the number of vector elements!");
11265
11266 SDVTList VTs = getVTList(MVT::Other);
11268 SDValue Ops[] = {Chain, Val, Ptr, Undef, Mask, EVL};
11270 AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
11271 ID.AddInteger(SVT.getRawBits());
11272 ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>(
11273 dl.getIROrder(), VTs, ISD::UNINDEXED, true, IsCompressing, SVT, MMO));
11274 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11275 ID.AddInteger(MMO->getFlags());
11276 void *IP = nullptr;
11277 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
11278 cast<VPStoreSDNode>(E)->refineAlignment(MMO);
11279 return SDValue(E, 0);
11280 }
11281 auto *N =
11282 newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
11283 ISD::UNINDEXED, true, IsCompressing, SVT, MMO);
11284 createOperands(N, Ops);
11285
11286 CSEMap.InsertNode(N, IP);
11287 InsertNode(N);
11288 SDValue V(N, 0);
11289 NewSDValueDbgMsg(V, "Creating new node: ", this);
11290 return V;
11291}
11292
11296 auto *ST = cast<VPStoreSDNode>(OrigStore);
11297 assert(ST->getOffset().getOpcode() == ISD::POISON &&
11298 "Store is already an indexed store!");
11299 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
11300 SDValue Ops[] = {ST->getChain(), ST->getValue(), Base,
11301 Offset, ST->getMask(), ST->getVectorLength()};
11303 AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
11304 ID.AddInteger(ST->getMemoryVT().getRawBits());
11305 ID.AddInteger(ST->getRawSubclassData());
11306 ID.AddInteger(ST->getPointerInfo().getAddrSpace());
11307 ID.AddInteger(ST->getMemOperand()->getFlags());
11308 void *IP = nullptr;
11309 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
11310 return SDValue(E, 0);
11311
11312 auto *N = newSDNode<VPStoreSDNode>(
11313 dl.getIROrder(), dl.getDebugLoc(), VTs, AM, ST->isTruncatingStore(),
11314 ST->isCompressingStore(), ST->getMemoryVT(), ST->getMemOperand());
11315 createOperands(N, Ops);
11316
11317 CSEMap.InsertNode(N, IP);
11318 InsertNode(N);
11319 SDValue V(N, 0);
11320 NewSDValueDbgMsg(V, "Creating new node: ", this);
11321 return V;
11322}
11323
11325 ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &DL,
11326 SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Stride, SDValue Mask,
11327 SDValue EVL, EVT MemVT, MachineMemOperand *MMO, bool IsExpanding) {
11328 bool Indexed = AM != ISD::UNINDEXED;
11329 assert((Indexed || Offset.getOpcode() == ISD::POISON) &&
11330 "Unindexed load with an offset!");
11331
11332 SDValue Ops[] = {Chain, Ptr, Offset, Stride, Mask, EVL};
11333 SDVTList VTs = Indexed ? getVTList(VT, Ptr.getValueType(), MVT::Other)
11334 : getVTList(VT, MVT::Other);
11336 AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_LOAD, VTs, Ops);
11337 ID.AddInteger(VT.getRawBits());
11338 ID.AddInteger(getSyntheticNodeSubclassData<VPStridedLoadSDNode>(
11339 DL.getIROrder(), VTs, AM, ExtType, IsExpanding, MemVT, MMO));
11340 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11341
11342 void *IP = nullptr;
11343 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
11344 cast<VPStridedLoadSDNode>(E)->refineAlignment(MMO);
11345 return SDValue(E, 0);
11346 }
11347
11348 auto *N =
11349 newSDNode<VPStridedLoadSDNode>(DL.getIROrder(), DL.getDebugLoc(), VTs, AM,
11350 ExtType, IsExpanding, MemVT, MMO);
11351 createOperands(N, Ops);
11352 CSEMap.InsertNode(N, IP);
11353 InsertNode(N);
11354 SDValue V(N, 0);
11355 NewSDValueDbgMsg(V, "Creating new node: ", this);
11356 return V;
11357}
11358
11360 SDValue Ptr, SDValue Stride,
11361 SDValue Mask, SDValue EVL,
11362 MachineMemOperand *MMO,
11363 bool IsExpanding) {
11365 return getStridedLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, DL, Chain, Ptr,
11366 Undef, Stride, Mask, EVL, VT, MMO, IsExpanding);
11367}
11368
11370 ISD::LoadExtType ExtType, const SDLoc &DL, EVT VT, SDValue Chain,
11371 SDValue Ptr, SDValue Stride, SDValue Mask, SDValue EVL, EVT MemVT,
11372 MachineMemOperand *MMO, bool IsExpanding) {
11374 return getStridedLoadVP(ISD::UNINDEXED, ExtType, VT, DL, Chain, Ptr, Undef,
11375 Stride, Mask, EVL, MemVT, MMO, IsExpanding);
11376}
11377
11379 SDValue Val, SDValue Ptr,
11380 SDValue Offset, SDValue Stride,
11381 SDValue Mask, SDValue EVL, EVT MemVT,
11382 MachineMemOperand *MMO,
11384 bool IsTruncating, bool IsCompressing) {
11385 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
11386 bool Indexed = AM != ISD::UNINDEXED;
11387 assert((Indexed || Offset.getOpcode() == ISD::POISON) &&
11388 "Unindexed vp_store with an offset!");
11389 SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other)
11390 : getVTList(MVT::Other);
11391 SDValue Ops[] = {Chain, Val, Ptr, Offset, Stride, Mask, EVL};
11393 AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_STORE, VTs, Ops);
11394 ID.AddInteger(MemVT.getRawBits());
11395 ID.AddInteger(getSyntheticNodeSubclassData<VPStridedStoreSDNode>(
11396 DL.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
11397 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11398 void *IP = nullptr;
11399 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
11400 cast<VPStridedStoreSDNode>(E)->refineAlignment(MMO);
11401 return SDValue(E, 0);
11402 }
11403 auto *N = newSDNode<VPStridedStoreSDNode>(DL.getIROrder(), DL.getDebugLoc(),
11404 VTs, AM, IsTruncating,
11405 IsCompressing, MemVT, MMO);
11406 createOperands(N, Ops);
11407
11408 CSEMap.InsertNode(N, IP);
11409 InsertNode(N);
11410 SDValue V(N, 0);
11411 NewSDValueDbgMsg(V, "Creating new node: ", this);
11412 return V;
11413}
11414
11416 SDValue Val, SDValue Ptr,
11417 SDValue Stride, SDValue Mask,
11418 SDValue EVL, EVT SVT,
11419 MachineMemOperand *MMO,
11420 bool IsCompressing) {
11421 EVT VT = Val.getValueType();
11422
11423 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
11424 if (VT == SVT)
11425 return getStridedStoreVP(Chain, DL, Val, Ptr, getPOISON(Ptr.getValueType()),
11426 Stride, Mask, EVL, VT, MMO, ISD::UNINDEXED,
11427 /*IsTruncating*/ false, IsCompressing);
11428
11430 "Should only be a truncating store, not extending!");
11431 assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!");
11432 assert(VT.isVector() == SVT.isVector() &&
11433 "Cannot use trunc store to convert to or from a vector!");
11434 assert((!VT.isVector() ||
11436 "Cannot use trunc store to change the number of vector elements!");
11437
11438 SDVTList VTs = getVTList(MVT::Other);
11440 SDValue Ops[] = {Chain, Val, Ptr, Undef, Stride, Mask, EVL};
11442 AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_STORE, VTs, Ops);
11443 ID.AddInteger(SVT.getRawBits());
11444 ID.AddInteger(getSyntheticNodeSubclassData<VPStridedStoreSDNode>(
11445 DL.getIROrder(), VTs, ISD::UNINDEXED, true, IsCompressing, SVT, MMO));
11446 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11447 void *IP = nullptr;
11448 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
11449 cast<VPStridedStoreSDNode>(E)->refineAlignment(MMO);
11450 return SDValue(E, 0);
11451 }
11452 auto *N = newSDNode<VPStridedStoreSDNode>(DL.getIROrder(), DL.getDebugLoc(),
11453 VTs, ISD::UNINDEXED, true,
11454 IsCompressing, SVT, MMO);
11455 createOperands(N, Ops);
11456
11457 CSEMap.InsertNode(N, IP);
11458 InsertNode(N);
11459 SDValue V(N, 0);
11460 NewSDValueDbgMsg(V, "Creating new node: ", this);
11461 return V;
11462}
11463
11466 ISD::MemIndexType IndexType) {
11467 assert(Ops.size() == 6 && "Incompatible number of operands");
11468
11470 AddNodeIDNode(ID, ISD::VP_GATHER, VTs, Ops);
11471 ID.AddInteger(VT.getRawBits());
11472 ID.AddInteger(getSyntheticNodeSubclassData<VPGatherSDNode>(
11473 dl.getIROrder(), VTs, VT, MMO, IndexType));
11474 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11475 ID.AddInteger(MMO->getFlags());
11476 void *IP = nullptr;
11477 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
11478 cast<VPGatherSDNode>(E)->refineAlignment(MMO);
11479 return SDValue(E, 0);
11480 }
11481
11482 auto *N = newSDNode<VPGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
11483 VT, MMO, IndexType);
11484 createOperands(N, Ops);
11485
11486 assert(N->getMask().getValueType().getVectorElementCount() ==
11487 N->getValueType(0).getVectorElementCount() &&
11488 "Vector width mismatch between mask and data");
11489 assert(N->getIndex().getValueType().getVectorElementCount().isScalable() ==
11490 N->getValueType(0).getVectorElementCount().isScalable() &&
11491 "Scalable flags of index and data do not match");
11493 N->getIndex().getValueType().getVectorElementCount(),
11494 N->getValueType(0).getVectorElementCount()) &&
11495 "Vector width mismatch between index and data");
11496 assert(isa<ConstantSDNode>(N->getScale()) &&
11497 N->getScale()->getAsAPIntVal().isPowerOf2() &&
11498 "Scale should be a constant power of 2");
11499
11500 CSEMap.InsertNode(N, IP);
11501 InsertNode(N);
11502 SDValue V(N, 0);
11503 NewSDValueDbgMsg(V, "Creating new node: ", this);
11504 return V;
11505}
11506
11509 MachineMemOperand *MMO,
11510 ISD::MemIndexType IndexType) {
11511 assert(Ops.size() == 7 && "Incompatible number of operands");
11512
11514 AddNodeIDNode(ID, ISD::VP_SCATTER, VTs, Ops);
11515 ID.AddInteger(VT.getRawBits());
11516 ID.AddInteger(getSyntheticNodeSubclassData<VPScatterSDNode>(
11517 dl.getIROrder(), VTs, VT, MMO, IndexType));
11518 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11519 ID.AddInteger(MMO->getFlags());
11520 void *IP = nullptr;
11521 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
11522 cast<VPScatterSDNode>(E)->refineAlignment(MMO);
11523 return SDValue(E, 0);
11524 }
11525 auto *N = newSDNode<VPScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
11526 VT, MMO, IndexType);
11527 createOperands(N, Ops);
11528
11529 assert(N->getMask().getValueType().getVectorElementCount() ==
11530 N->getValue().getValueType().getVectorElementCount() &&
11531 "Vector width mismatch between mask and data");
11532 assert(
11533 N->getIndex().getValueType().getVectorElementCount().isScalable() ==
11534 N->getValue().getValueType().getVectorElementCount().isScalable() &&
11535 "Scalable flags of index and data do not match");
11537 N->getIndex().getValueType().getVectorElementCount(),
11538 N->getValue().getValueType().getVectorElementCount()) &&
11539 "Vector width mismatch between index and data");
11540 assert(isa<ConstantSDNode>(N->getScale()) &&
11541 N->getScale()->getAsAPIntVal().isPowerOf2() &&
11542 "Scale should be a constant power of 2");
11543
11544 CSEMap.InsertNode(N, IP);
11545 InsertNode(N);
11546 SDValue V(N, 0);
11547 NewSDValueDbgMsg(V, "Creating new node: ", this);
11548 return V;
11549}
11550
11553 SDValue PassThru, EVT MemVT,
11554 MachineMemOperand *MMO,
11556 ISD::LoadExtType ExtTy, bool isExpanding) {
11557 bool Indexed = AM != ISD::UNINDEXED;
11558 assert((Indexed || Offset.getOpcode() == ISD::POISON) &&
11559 "Unindexed masked load with an offset!");
11560 SDVTList VTs = Indexed ? getVTList(VT, Base.getValueType(), MVT::Other)
11561 : getVTList(VT, MVT::Other);
11562 SDValue Ops[] = {Chain, Base, Offset, Mask, PassThru};
11564 AddNodeIDNode(ID, ISD::MLOAD, VTs, Ops);
11565 ID.AddInteger(MemVT.getRawBits());
11566 ID.AddInteger(getSyntheticNodeSubclassData<MaskedLoadSDNode>(
11567 dl.getIROrder(), VTs, AM, ExtTy, isExpanding, MemVT, MMO));
11568 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11569 ID.AddInteger(MMO->getFlags());
11570 void *IP = nullptr;
11571 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
11572 cast<MaskedLoadSDNode>(E)->refineAlignment(MMO);
11573 return SDValue(E, 0);
11574 }
11575 auto *N = newSDNode<MaskedLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
11576 AM, ExtTy, isExpanding, MemVT, MMO);
11577 createOperands(N, Ops);
11578
11579 CSEMap.InsertNode(N, IP);
11580 InsertNode(N);
11581 SDValue V(N, 0);
11582 NewSDValueDbgMsg(V, "Creating new node: ", this);
11583 return V;
11584}
11585
11590 assert(LD->getOffset().getOpcode() == ISD::POISON &&
11591 "Masked load is already a indexed load!");
11592 return getMaskedLoad(OrigLoad.getValueType(), dl, LD->getChain(), Base,
11593 Offset, LD->getMask(), LD->getPassThru(),
11594 LD->getMemoryVT(), LD->getMemOperand(), AM,
11595 LD->getExtensionType(), LD->isExpandingLoad());
11596}
11597
11600 SDValue Mask, EVT MemVT,
11601 MachineMemOperand *MMO,
11602 ISD::MemIndexedMode AM, bool IsTruncating,
11603 bool IsCompressing) {
11604 assert(Chain.getValueType() == MVT::Other &&
11605 "Invalid chain type");
11606 bool Indexed = AM != ISD::UNINDEXED;
11607 assert((Indexed || Offset.getOpcode() == ISD::POISON) &&
11608 "Unindexed masked store with an offset!");
11609 SDVTList VTs = Indexed ? getVTList(Base.getValueType(), MVT::Other)
11610 : getVTList(MVT::Other);
11611 SDValue Ops[] = {Chain, Val, Base, Offset, Mask};
11613 AddNodeIDNode(ID, ISD::MSTORE, VTs, Ops);
11614 ID.AddInteger(MemVT.getRawBits());
11615 ID.AddInteger(getSyntheticNodeSubclassData<MaskedStoreSDNode>(
11616 dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
11617 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11618 ID.AddInteger(MMO->getFlags());
11619 void *IP = nullptr;
11620 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
11621 cast<MaskedStoreSDNode>(E)->refineAlignment(MMO);
11622 return SDValue(E, 0);
11623 }
11624 auto *N =
11625 newSDNode<MaskedStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
11626 IsTruncating, IsCompressing, MemVT, MMO);
11627 createOperands(N, Ops);
11628
11629 CSEMap.InsertNode(N, IP);
11630 InsertNode(N);
11631 SDValue V(N, 0);
11632 NewSDValueDbgMsg(V, "Creating new node: ", this);
11633 return V;
11634}
11635
11640 assert(ST->getOffset().getOpcode() == ISD::POISON &&
11641 "Masked store is already a indexed store!");
11642 return getMaskedStore(ST->getChain(), dl, ST->getValue(), Base, Offset,
11643 ST->getMask(), ST->getMemoryVT(), ST->getMemOperand(),
11644 AM, ST->isTruncatingStore(), ST->isCompressingStore());
11645}
11646
11649 MachineMemOperand *MMO,
11650 ISD::MemIndexType IndexType,
11651 ISD::LoadExtType ExtTy) {
11652 assert(Ops.size() == 6 && "Incompatible number of operands");
11653
11655 AddNodeIDNode(ID, ISD::MGATHER, VTs, Ops);
11656 ID.AddInteger(MemVT.getRawBits());
11657 ID.AddInteger(getSyntheticNodeSubclassData<MaskedGatherSDNode>(
11658 dl.getIROrder(), VTs, MemVT, MMO, IndexType, ExtTy));
11659 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11660 ID.AddInteger(MMO->getFlags());
11661 void *IP = nullptr;
11662 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
11663 cast<MaskedGatherSDNode>(E)->refineAlignment(MMO);
11664 return SDValue(E, 0);
11665 }
11666
11667 auto *N = newSDNode<MaskedGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(),
11668 VTs, MemVT, MMO, IndexType, ExtTy);
11669 createOperands(N, Ops);
11670
11671 assert(N->getPassThru().getValueType() == N->getValueType(0) &&
11672 "Incompatible type of the PassThru value in MaskedGatherSDNode");
11673 assert(N->getMask().getValueType().getVectorElementCount() ==
11674 N->getValueType(0).getVectorElementCount() &&
11675 "Vector width mismatch between mask and data");
11676 assert(N->getIndex().getValueType().getVectorElementCount().isScalable() ==
11677 N->getValueType(0).getVectorElementCount().isScalable() &&
11678 "Scalable flags of index and data do not match");
11680 N->getIndex().getValueType().getVectorElementCount(),
11681 N->getValueType(0).getVectorElementCount()) &&
11682 "Vector width mismatch between index and data");
11683 assert(isa<ConstantSDNode>(N->getScale()) &&
11684 N->getScale()->getAsAPIntVal().isPowerOf2() &&
11685 "Scale should be a constant power of 2");
11686
11687 CSEMap.InsertNode(N, IP);
11688 InsertNode(N);
11689 SDValue V(N, 0);
11690 NewSDValueDbgMsg(V, "Creating new node: ", this);
11691 return V;
11692}
11693
11696 MachineMemOperand *MMO,
11697 ISD::MemIndexType IndexType,
11698 bool IsTrunc) {
11699 assert(Ops.size() == 6 && "Incompatible number of operands");
11700
11702 AddNodeIDNode(ID, ISD::MSCATTER, VTs, Ops);
11703 ID.AddInteger(MemVT.getRawBits());
11704 ID.AddInteger(getSyntheticNodeSubclassData<MaskedScatterSDNode>(
11705 dl.getIROrder(), VTs, MemVT, MMO, IndexType, IsTrunc));
11706 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11707 ID.AddInteger(MMO->getFlags());
11708 void *IP = nullptr;
11709 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
11710 cast<MaskedScatterSDNode>(E)->refineAlignment(MMO);
11711 return SDValue(E, 0);
11712 }
11713
11714 auto *N = newSDNode<MaskedScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(),
11715 VTs, MemVT, MMO, IndexType, IsTrunc);
11716 createOperands(N, Ops);
11717
11718 assert(N->getMask().getValueType().getVectorElementCount() ==
11719 N->getValue().getValueType().getVectorElementCount() &&
11720 "Vector width mismatch between mask and data");
11721 assert(
11722 N->getIndex().getValueType().getVectorElementCount().isScalable() ==
11723 N->getValue().getValueType().getVectorElementCount().isScalable() &&
11724 "Scalable flags of index and data do not match");
11726 N->getIndex().getValueType().getVectorElementCount(),
11727 N->getValue().getValueType().getVectorElementCount()) &&
11728 "Vector width mismatch between index and data");
11729 assert(isa<ConstantSDNode>(N->getScale()) &&
11730 N->getScale()->getAsAPIntVal().isPowerOf2() &&
11731 "Scale should be a constant power of 2");
11732
11733 CSEMap.InsertNode(N, IP);
11734 InsertNode(N);
11735 SDValue V(N, 0);
11736 NewSDValueDbgMsg(V, "Creating new node: ", this);
11737 return V;
11738}
11739
11741 const SDLoc &dl, ArrayRef<SDValue> Ops,
11742 MachineMemOperand *MMO,
11743 ISD::MemIndexType IndexType) {
11744 assert(Ops.size() == 7 && "Incompatible number of operands");
11745
11748 ID.AddInteger(MemVT.getRawBits());
11749 ID.AddInteger(getSyntheticNodeSubclassData<MaskedHistogramSDNode>(
11750 dl.getIROrder(), VTs, MemVT, MMO, IndexType));
11751 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11752 ID.AddInteger(MMO->getFlags());
11753 void *IP = nullptr;
11754 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
11755 cast<MaskedGatherSDNode>(E)->refineAlignment(MMO);
11756 return SDValue(E, 0);
11757 }
11758
11759 auto *N = newSDNode<MaskedHistogramSDNode>(dl.getIROrder(), dl.getDebugLoc(),
11760 VTs, MemVT, MMO, IndexType);
11761 createOperands(N, Ops);
11762
11763 assert(N->getMask().getValueType().getVectorElementCount() ==
11764 N->getIndex().getValueType().getVectorElementCount() &&
11765 "Vector width mismatch between mask and data");
11766 assert(isa<ConstantSDNode>(N->getScale()) &&
11767 N->getScale()->getAsAPIntVal().isPowerOf2() &&
11768 "Scale should be a constant power of 2");
11769 assert(N->getInc().getValueType().isInteger() && "Non integer update value");
11770
11771 CSEMap.InsertNode(N, IP);
11772 InsertNode(N);
11773 SDValue V(N, 0);
11774 NewSDValueDbgMsg(V, "Creating new node: ", this);
11775 return V;
11776}
11777
11779 SDValue Ptr, SDValue Mask, SDValue EVL,
11780 MachineMemOperand *MMO) {
11781 SDVTList VTs = getVTList(VT, EVL.getValueType(), MVT::Other);
11782 SDValue Ops[] = {Chain, Ptr, Mask, EVL};
11784 AddNodeIDNode(ID, ISD::VP_LOAD_FF, VTs, Ops);
11785 ID.AddInteger(VT.getRawBits());
11786 ID.AddInteger(getSyntheticNodeSubclassData<VPLoadFFSDNode>(DL.getIROrder(),
11787 VTs, VT, MMO));
11788 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11789 ID.AddInteger(MMO->getFlags());
11790 void *IP = nullptr;
11791 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
11792 cast<VPLoadFFSDNode>(E)->refineAlignment(MMO);
11793 return SDValue(E, 0);
11794 }
11795 auto *N = newSDNode<VPLoadFFSDNode>(DL.getIROrder(), DL.getDebugLoc(), VTs,
11796 VT, MMO);
11797 createOperands(N, Ops);
11798
11799 CSEMap.InsertNode(N, IP);
11800 InsertNode(N);
11801 SDValue V(N, 0);
11802 NewSDValueDbgMsg(V, "Creating new node: ", this);
11803 return V;
11804}
11805
11807 EVT MemVT, MachineMemOperand *MMO) {
11808 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
11809 SDVTList VTs = getVTList(MVT::Other);
11810 SDValue Ops[] = {Chain, Ptr};
11813 ID.AddInteger(MemVT.getRawBits());
11814 ID.AddInteger(getSyntheticNodeSubclassData<FPStateAccessSDNode>(
11815 ISD::GET_FPENV_MEM, dl.getIROrder(), VTs, MemVT, MMO));
11816 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11817 ID.AddInteger(MMO->getFlags());
11818 void *IP = nullptr;
11819 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
11820 return SDValue(E, 0);
11821
11822 auto *N = newSDNode<FPStateAccessSDNode>(ISD::GET_FPENV_MEM, dl.getIROrder(),
11823 dl.getDebugLoc(), VTs, MemVT, MMO);
11824 createOperands(N, Ops);
11825
11826 CSEMap.InsertNode(N, IP);
11827 InsertNode(N);
11828 SDValue V(N, 0);
11829 NewSDValueDbgMsg(V, "Creating new node: ", this);
11830 return V;
11831}
11832
11834 EVT MemVT, MachineMemOperand *MMO) {
11835 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
11836 SDVTList VTs = getVTList(MVT::Other);
11837 SDValue Ops[] = {Chain, Ptr};
11840 ID.AddInteger(MemVT.getRawBits());
11841 ID.AddInteger(getSyntheticNodeSubclassData<FPStateAccessSDNode>(
11842 ISD::SET_FPENV_MEM, dl.getIROrder(), VTs, MemVT, MMO));
11843 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
11844 ID.AddInteger(MMO->getFlags());
11845 void *IP = nullptr;
11846 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
11847 return SDValue(E, 0);
11848
11849 auto *N = newSDNode<FPStateAccessSDNode>(ISD::SET_FPENV_MEM, dl.getIROrder(),
11850 dl.getDebugLoc(), VTs, MemVT, MMO);
11851 createOperands(N, Ops);
11852
11853 CSEMap.InsertNode(N, IP);
11854 InsertNode(N);
11855 SDValue V(N, 0);
11856 NewSDValueDbgMsg(V, "Creating new node: ", this);
11857 return V;
11858}
11859
11861 // select undef, T, F --> T (if T is a constant), otherwise F
11862 // select, ?, undef, F --> F
11863 // select, ?, T, undef --> T
11864 if (Cond.isUndef())
11865 return isConstantValueOfAnyType(T) ? T : F;
11866 if (T.isUndef())
11868 if (F.isUndef())
11870
11871 // select true, T, F --> T
11872 // select false, T, F --> F
11873 if (auto C = isBoolConstant(Cond))
11874 return *C ? T : F;
11875
11876 // select ?, T, T --> T
11877 if (T == F)
11878 return T;
11879
11880 return SDValue();
11881}
11882
11884 // shift undef, Y --> 0 (can always assume that the undef value is 0)
11885 if (X.isUndef())
11886 return getConstant(0, SDLoc(X.getNode()), X.getValueType());
11887 // shift X, undef --> undef (because it may shift by the bitwidth)
11888 if (Y.isUndef())
11889 return getUNDEF(X.getValueType());
11890
11891 // shift 0, Y --> 0
11892 // shift X, 0 --> X
11894 return X;
11895
11896 // shift X, C >= bitwidth(X) --> undef
11897 // All vector elements must be too big (or undef) to avoid partial undefs.
11898 auto isShiftTooBig = [X](ConstantSDNode *Val) {
11899 return !Val || Val->getAPIntValue().uge(X.getScalarValueSizeInBits());
11900 };
11901 if (ISD::matchUnaryPredicate(Y, isShiftTooBig, true))
11902 return getUNDEF(X.getValueType());
11903
11904 // shift i1/vXi1 X, Y --> X (any non-zero shift amount is undefined).
11905 if (X.getValueType().getScalarType() == MVT::i1)
11906 return X;
11907
11908 return SDValue();
11909}
11910
11912 SDNodeFlags Flags) {
11913 // If this operation has 'nnan' or 'ninf' and at least 1 disallowed operand
11914 // (an undef operand can be chosen to be Nan/Inf), then the result of this
11915 // operation is poison. That result can be relaxed to undef.
11916 ConstantFPSDNode *XC = isConstOrConstSplatFP(X, /* AllowUndefs */ true);
11917 ConstantFPSDNode *YC = isConstOrConstSplatFP(Y, /* AllowUndefs */ true);
11918 bool HasNan = (XC && XC->getValueAPF().isNaN()) ||
11919 (YC && YC->getValueAPF().isNaN());
11920 bool HasInf = (XC && XC->getValueAPF().isInfinity()) ||
11921 (YC && YC->getValueAPF().isInfinity());
11922
11923 if (Flags.hasNoNaNs() && (HasNan || X.isUndef() || Y.isUndef()))
11924 return getUNDEF(X.getValueType());
11925
11926 if (Flags.hasNoInfs() && (HasInf || X.isUndef() || Y.isUndef()))
11927 return getUNDEF(X.getValueType());
11928
11929 if (!YC)
11930 return SDValue();
11931
11932 // X + -0.0 --> X
11933 if (Opcode == ISD::FADD)
11934 if (YC->getValueAPF().isNegZero())
11935 return X;
11936
11937 // X - +0.0 --> X
11938 if (Opcode == ISD::FSUB)
11939 if (YC->getValueAPF().isPosZero())
11940 return X;
11941
11942 // X * 1.0 --> X
11943 // X / 1.0 --> X
11944 if (Opcode == ISD::FMUL || Opcode == ISD::FDIV)
11945 if (YC->getValueAPF().isOne())
11946 return X;
11947
11948 // X * 0.0 --> 0.0
11949 if (Opcode == ISD::FMUL && Flags.hasNoNaNs() && Flags.hasNoSignedZeros())
11950 if (YC->getValueAPF().isZero())
11951 return getConstantFP(0.0, SDLoc(Y), Y.getValueType());
11952
11953 return SDValue();
11954}
11955
11957 SDValue Ptr, SDValue SV, unsigned Align) {
11958 SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, dl, MVT::i32) };
11959 return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops);
11960}
11961
11962SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
11964 switch (Ops.size()) {
11965 case 0: return getNode(Opcode, DL, VT);
11966 case 1: return getNode(Opcode, DL, VT, Ops[0].get());
11967 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
11968 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
11969 default: break;
11970 }
11971
11972 // Copy from an SDUse array into an SDValue array for use with
11973 // the regular getNode logic.
11975 return getNode(Opcode, DL, VT, NewOps);
11976}
11977
11978SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
11980 SDNodeFlags Flags;
11981 if (Inserter)
11982 Flags = Inserter->getFlags();
11983 return getNode(Opcode, DL, VT, Ops, Flags);
11984}
11985
11986SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
11987 ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
11988 unsigned NumOps = Ops.size();
11989 switch (NumOps) {
11990 case 0: return getNode(Opcode, DL, VT);
11991 case 1: return getNode(Opcode, DL, VT, Ops[0], Flags);
11992 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Flags);
11993 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2], Flags);
11994 default: break;
11995 }
11996
11997#ifndef NDEBUG
11998 for (const auto &Op : Ops)
11999 assert(Op.getOpcode() != ISD::DELETED_NODE &&
12000 "Operand is DELETED_NODE!");
12001#endif
12002
12003 switch (Opcode) {
12004 default: break;
12005 case ISD::BUILD_VECTOR:
12006 // Attempt to simplify BUILD_VECTOR.
12007 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
12008 return V;
12009 break;
12011 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
12012 return V;
12013 break;
12014 case ISD::SELECT_CC:
12015 assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
12016 assert(Ops[0].getValueType() == Ops[1].getValueType() &&
12017 "LHS and RHS of condition must have same type!");
12018 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
12019 "True and False arms of SelectCC must have same type!");
12020 assert(Ops[2].getValueType() == VT &&
12021 "select_cc node must be of same type as true and false value!");
12022 assert((!Ops[0].getValueType().isVector() ||
12023 Ops[0].getValueType().getVectorElementCount() ==
12024 VT.getVectorElementCount()) &&
12025 "Expected select_cc with vector result to have the same sized "
12026 "comparison type!");
12027 break;
12028 case ISD::BR_CC:
12029 assert(NumOps == 5 && "BR_CC takes 5 operands!");
12030 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
12031 "LHS/RHS of comparison should match types!");
12032 break;
12033 case ISD::VP_ADD:
12034 case ISD::VP_SUB:
12035 // If it is VP_ADD/VP_SUB mask operation then turn it to VP_XOR
12036 if (VT.getScalarType() == MVT::i1)
12037 Opcode = ISD::VP_XOR;
12038 break;
12039 case ISD::VP_MUL:
12040 // If it is VP_MUL mask operation then turn it to VP_AND
12041 if (VT.getScalarType() == MVT::i1)
12042 Opcode = ISD::VP_AND;
12043 break;
12044 case ISD::VP_REDUCE_MUL:
12045 // If it is VP_REDUCE_MUL mask operation then turn it to VP_REDUCE_AND
12046 if (VT == MVT::i1)
12047 Opcode = ISD::VP_REDUCE_AND;
12048 break;
12049 case ISD::VP_REDUCE_ADD:
12050 // If it is VP_REDUCE_ADD mask operation then turn it to VP_REDUCE_XOR
12051 if (VT == MVT::i1)
12052 Opcode = ISD::VP_REDUCE_XOR;
12053 break;
12054 case ISD::VP_REDUCE_SMAX:
12055 case ISD::VP_REDUCE_UMIN:
12056 // If it is VP_REDUCE_SMAX/VP_REDUCE_UMIN mask operation then turn it to
12057 // VP_REDUCE_AND.
12058 if (VT == MVT::i1)
12059 Opcode = ISD::VP_REDUCE_AND;
12060 break;
12061 case ISD::VP_REDUCE_SMIN:
12062 case ISD::VP_REDUCE_UMAX:
12063 // If it is VP_REDUCE_SMIN/VP_REDUCE_UMAX mask operation then turn it to
12064 // VP_REDUCE_OR.
12065 if (VT == MVT::i1)
12066 Opcode = ISD::VP_REDUCE_OR;
12067 break;
12068 }
12069
12070 // Memoize nodes.
12071 SDNode *N;
12072 SDVTList VTs = getVTList(VT);
12073
12074 if (VT != MVT::Glue) {
12076 AddNodeIDNode(ID, Opcode, VTs, Ops);
12077 void *IP = nullptr;
12078
12079 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
12080 E->intersectFlagsWith(Flags);
12081 return SDValue(E, 0);
12082 }
12083
12084 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
12085 createOperands(N, Ops);
12086
12087 CSEMap.InsertNode(N, IP);
12088 } else {
12089 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
12090 createOperands(N, Ops);
12091 }
12092
12093 N->setFlags(Flags);
12094 InsertNode(N);
12095 SDValue V(N, 0);
12096 NewSDValueDbgMsg(V, "Creating new node: ", this);
12097 return V;
12098}
12099
12100SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
12101 ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) {
12102 SDNodeFlags Flags;
12103 if (Inserter)
12104 Flags = Inserter->getFlags();
12105 return getNode(Opcode, DL, getVTList(ResultTys), Ops, Flags);
12106}
12107
12108SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
12110 const SDNodeFlags Flags) {
12111 return getNode(Opcode, DL, getVTList(ResultTys), Ops, Flags);
12112}
12113
12114SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
12116 SDNodeFlags Flags;
12117 if (Inserter)
12118 Flags = Inserter->getFlags();
12119 return getNode(Opcode, DL, VTList, Ops, Flags);
12120}
12121
12122SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
12123 ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
12124 if (VTList.NumVTs == 1)
12125 return getNode(Opcode, DL, VTList.VTs[0], Ops, Flags);
12126
12127#ifndef NDEBUG
12128 for (const auto &Op : Ops)
12129 assert(Op.getOpcode() != ISD::DELETED_NODE &&
12130 "Operand is DELETED_NODE!");
12131#endif
12132
12133 switch (Opcode) {
12134 case ISD::SADDO:
12135 case ISD::UADDO:
12136 case ISD::SSUBO:
12137 case ISD::USUBO: {
12138 assert(VTList.NumVTs == 2 && Ops.size() == 2 &&
12139 "Invalid add/sub overflow op!");
12140 assert(VTList.VTs[0].isInteger() && VTList.VTs[1].isInteger() &&
12141 Ops[0].getValueType() == Ops[1].getValueType() &&
12142 Ops[0].getValueType() == VTList.VTs[0] &&
12143 "Binary operator types must match!");
12144 SDValue N1 = Ops[0], N2 = Ops[1];
12145 canonicalizeCommutativeBinop(Opcode, N1, N2);
12146
12147 // (X +- 0) -> X with zero-overflow.
12148 ConstantSDNode *N2CV = isConstOrConstSplat(N2, /*AllowUndefs*/ false,
12149 /*AllowTruncation*/ true);
12150 if (N2CV && N2CV->isZero()) {
12151 SDValue ZeroOverFlow = getConstant(0, DL, VTList.VTs[1]);
12152 return getNode(ISD::MERGE_VALUES, DL, VTList, {N1, ZeroOverFlow}, Flags);
12153 }
12154
12155 if (VTList.VTs[0].getScalarType() == MVT::i1 &&
12156 VTList.VTs[1].getScalarType() == MVT::i1) {
12157 SDValue F1 = getFreeze(N1);
12158 SDValue F2 = getFreeze(N2);
12159 // {vXi1,vXi1} (u/s)addo(vXi1 x, vXi1y) -> {xor(x,y),and(x,y)}
12160 if (Opcode == ISD::UADDO || Opcode == ISD::SADDO)
12161 return getNode(ISD::MERGE_VALUES, DL, VTList,
12162 {getNode(ISD::XOR, DL, VTList.VTs[0], F1, F2),
12163 getNode(ISD::AND, DL, VTList.VTs[1], F1, F2)},
12164 Flags);
12165 // {vXi1,vXi1} (u/s)subo(vXi1 x, vXi1y) -> {xor(x,y),and(~x,y)}
12166 if (Opcode == ISD::USUBO || Opcode == ISD::SSUBO) {
12167 SDValue NotF1 = getNOT(DL, F1, VTList.VTs[0]);
12168 return getNode(ISD::MERGE_VALUES, DL, VTList,
12169 {getNode(ISD::XOR, DL, VTList.VTs[0], F1, F2),
12170 getNode(ISD::AND, DL, VTList.VTs[1], NotF1, F2)},
12171 Flags);
12172 }
12173 }
12174 break;
12175 }
12176 case ISD::SADDO_CARRY:
12177 case ISD::UADDO_CARRY:
12178 case ISD::SSUBO_CARRY:
12179 case ISD::USUBO_CARRY:
12180 assert(VTList.NumVTs == 2 && Ops.size() == 3 &&
12181 "Invalid add/sub overflow op!");
12182 assert(VTList.VTs[0].isInteger() && VTList.VTs[1].isInteger() &&
12183 Ops[0].getValueType() == Ops[1].getValueType() &&
12184 Ops[0].getValueType() == VTList.VTs[0] &&
12185 Ops[2].getValueType() == VTList.VTs[1] &&
12186 "Binary operator types must match!");
12187 break;
12188 case ISD::SMUL_LOHI:
12189 case ISD::UMUL_LOHI: {
12190 assert(VTList.NumVTs == 2 && Ops.size() == 2 && "Invalid mul lo/hi op!");
12191 assert(VTList.VTs[0].isInteger() && VTList.VTs[0] == VTList.VTs[1] &&
12192 VTList.VTs[0] == Ops[0].getValueType() &&
12193 VTList.VTs[0] == Ops[1].getValueType() &&
12194 "Binary operator types must match!");
12195 // Constant fold.
12198 if (LHS && RHS) {
12199 unsigned Width = VTList.VTs[0].getScalarSizeInBits();
12200 unsigned OutWidth = Width * 2;
12201 APInt Val = LHS->getAPIntValue();
12202 APInt Mul = RHS->getAPIntValue();
12203 if (Opcode == ISD::SMUL_LOHI) {
12204 Val = Val.sext(OutWidth);
12205 Mul = Mul.sext(OutWidth);
12206 } else {
12207 Val = Val.zext(OutWidth);
12208 Mul = Mul.zext(OutWidth);
12209 }
12210 Val *= Mul;
12211
12212 SDValue Hi =
12213 getConstant(Val.extractBits(Width, Width), DL, VTList.VTs[0]);
12214 SDValue Lo = getConstant(Val.trunc(Width), DL, VTList.VTs[0]);
12215 return getNode(ISD::MERGE_VALUES, DL, VTList, {Lo, Hi}, Flags);
12216 }
12217 break;
12218 }
12219 case ISD::FFREXP: {
12220 assert(VTList.NumVTs == 2 && Ops.size() == 1 && "Invalid ffrexp op!");
12221 assert(VTList.VTs[0].isFloatingPoint() && VTList.VTs[1].isInteger() &&
12222 VTList.VTs[0] == Ops[0].getValueType() && "frexp type mismatch");
12223
12225 int FrexpExp;
12226 APFloat FrexpMant =
12227 frexp(C->getValueAPF(), FrexpExp, APFloat::rmNearestTiesToEven);
12228 SDValue Result0 = getConstantFP(FrexpMant, DL, VTList.VTs[0]);
12229 SDValue Result1 = getSignedConstant(FrexpMant.isFinite() ? FrexpExp : 0,
12230 DL, VTList.VTs[1]);
12231 return getNode(ISD::MERGE_VALUES, DL, VTList, {Result0, Result1}, Flags);
12232 }
12233
12234 break;
12235 }
12237 assert(VTList.NumVTs == 2 && Ops.size() == 2 &&
12238 "Invalid STRICT_FP_EXTEND!");
12239 assert(VTList.VTs[0].isFloatingPoint() &&
12240 Ops[1].getValueType().isFloatingPoint() && "Invalid FP cast!");
12241 assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
12242 "STRICT_FP_EXTEND result type should be vector iff the operand "
12243 "type is vector!");
12244 assert((!VTList.VTs[0].isVector() ||
12245 VTList.VTs[0].getVectorElementCount() ==
12246 Ops[1].getValueType().getVectorElementCount()) &&
12247 "Vector element count mismatch!");
12248 assert(Ops[1].getValueType().bitsLT(VTList.VTs[0]) &&
12249 "Invalid fpext node, dst <= src!");
12250 break;
12252 assert(VTList.NumVTs == 2 && Ops.size() == 3 && "Invalid STRICT_FP_ROUND!");
12253 assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
12254 "STRICT_FP_ROUND result type should be vector iff the operand "
12255 "type is vector!");
12256 assert((!VTList.VTs[0].isVector() ||
12257 VTList.VTs[0].getVectorElementCount() ==
12258 Ops[1].getValueType().getVectorElementCount()) &&
12259 "Vector element count mismatch!");
12260 assert(VTList.VTs[0].isFloatingPoint() &&
12261 Ops[1].getValueType().isFloatingPoint() &&
12262 VTList.VTs[0].bitsLT(Ops[1].getValueType()) &&
12263 Ops[2].getOpcode() == ISD::TargetConstant &&
12264 (Ops[2]->getAsZExtVal() == 0 || Ops[2]->getAsZExtVal() == 1) &&
12265 "Invalid STRICT_FP_ROUND!");
12266 break;
12267 }
12268
12269 // Memoize the node unless it returns a glue result.
12270 SDNode *N;
12271 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
12273 AddNodeIDNode(ID, Opcode, VTList, Ops);
12274 void *IP = nullptr;
12275 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
12276 E->intersectFlagsWith(Flags);
12277 return SDValue(E, 0);
12278 }
12279
12280 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
12281 createOperands(N, Ops);
12282 CSEMap.InsertNode(N, IP);
12283 } else {
12284 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
12285 createOperands(N, Ops);
12286 }
12287
12288 N->setFlags(Flags);
12289 InsertNode(N);
12290 SDValue V(N, 0);
12291 NewSDValueDbgMsg(V, "Creating new node: ", this);
12292 return V;
12293}
12294
12295SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
12296 SDVTList VTList) {
12297 return getNode(Opcode, DL, VTList, ArrayRef<SDValue>());
12298}
12299
12300SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
12301 SDValue N1) {
12302 SDValue Ops[] = { N1 };
12303 return getNode(Opcode, DL, VTList, Ops);
12304}
12305
12306SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
12307 SDValue N1, SDValue N2) {
12308 SDValue Ops[] = { N1, N2 };
12309 return getNode(Opcode, DL, VTList, Ops);
12310}
12311
12312SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
12313 SDValue N1, SDValue N2, SDValue N3) {
12314 SDValue Ops[] = { N1, N2, N3 };
12315 return getNode(Opcode, DL, VTList, Ops);
12316}
12317
12318SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
12319 SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
12320 SDValue Ops[] = { N1, N2, N3, N4 };
12321 return getNode(Opcode, DL, VTList, Ops);
12322}
12323
12324SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
12325 SDValue N1, SDValue N2, SDValue N3, SDValue N4,
12326 SDValue N5) {
12327 SDValue Ops[] = { N1, N2, N3, N4, N5 };
12328 return getNode(Opcode, DL, VTList, Ops);
12329}
12330
12332 if (!VT.isExtended())
12333 return makeVTList(SDNode::getValueTypeList(VT.getSimpleVT()), 1);
12334
12335 return makeVTList(&(*EVTs.insert(VT).first), 1);
12336}
12337
12340 ID.AddInteger(2U);
12341 ID.AddInteger(VT1.getRawBits());
12342 ID.AddInteger(VT2.getRawBits());
12343
12344 void *IP = nullptr;
12345 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
12346 if (!Result) {
12347 EVT *Array = Allocator.Allocate<EVT>(2);
12348 Array[0] = VT1;
12349 Array[1] = VT2;
12350 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 2);
12351 VTListMap.InsertNode(Result, IP);
12352 }
12353 return Result->getSDVTList();
12354}
12355
12358 ID.AddInteger(3U);
12359 ID.AddInteger(VT1.getRawBits());
12360 ID.AddInteger(VT2.getRawBits());
12361 ID.AddInteger(VT3.getRawBits());
12362
12363 void *IP = nullptr;
12364 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
12365 if (!Result) {
12366 EVT *Array = Allocator.Allocate<EVT>(3);
12367 Array[0] = VT1;
12368 Array[1] = VT2;
12369 Array[2] = VT3;
12370 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 3);
12371 VTListMap.InsertNode(Result, IP);
12372 }
12373 return Result->getSDVTList();
12374}
12375
12378 ID.AddInteger(4U);
12379 ID.AddInteger(VT1.getRawBits());
12380 ID.AddInteger(VT2.getRawBits());
12381 ID.AddInteger(VT3.getRawBits());
12382 ID.AddInteger(VT4.getRawBits());
12383
12384 void *IP = nullptr;
12385 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
12386 if (!Result) {
12387 EVT *Array = Allocator.Allocate<EVT>(4);
12388 Array[0] = VT1;
12389 Array[1] = VT2;
12390 Array[2] = VT3;
12391 Array[3] = VT4;
12392 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 4);
12393 VTListMap.InsertNode(Result, IP);
12394 }
12395 return Result->getSDVTList();
12396}
12397
12399 unsigned NumVTs = VTs.size();
12401 ID.AddInteger(NumVTs);
12402 for (unsigned index = 0; index < NumVTs; index++) {
12403 ID.AddInteger(VTs[index].getRawBits());
12404 }
12405
12406 void *IP = nullptr;
12407 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
12408 if (!Result) {
12409 EVT *Array = Allocator.Allocate<EVT>(NumVTs);
12410 llvm::copy(VTs, Array);
12411 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, NumVTs);
12412 VTListMap.InsertNode(Result, IP);
12413 }
12414 return Result->getSDVTList();
12415}
12416
12417
12418/// UpdateNodeOperands - *Mutate* the specified node in-place to have the
12419/// specified operands. If the resultant node already exists in the DAG,
12420/// this does not modify the specified node, instead it returns the node that
12421/// already exists. If the resultant node does not exist in the DAG, the
12422/// input node is returned. As a degenerate case, if you specify the same
12423/// input operands as the node already has, the input node is returned.
12425 assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
12426
12427 // Check to see if there is no change.
12428 if (Op == N->getOperand(0)) return N;
12429
12430 // See if the modified node already exists.
12431 void *InsertPos = nullptr;
12432 if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
12433 return Existing;
12434
12435 // Nope it doesn't. Remove the node from its current place in the maps.
12436 if (InsertPos)
12437 if (!RemoveNodeFromCSEMaps(N))
12438 InsertPos = nullptr;
12439
12440 // Now we update the operands.
12441 N->OperandList[0].set(Op);
12442
12444 // If this gets put into a CSE map, add it.
12445 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
12446 return N;
12447}
12448
12450 assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
12451
12452 // Check to see if there is no change.
12453 if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
12454 return N; // No operands changed, just return the input node.
12455
12456 // See if the modified node already exists.
12457 void *InsertPos = nullptr;
12458 if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
12459 return Existing;
12460
12461 // Nope it doesn't. Remove the node from its current place in the maps.
12462 if (InsertPos)
12463 if (!RemoveNodeFromCSEMaps(N))
12464 InsertPos = nullptr;
12465
12466 // Now we update the operands.
12467 if (N->OperandList[0] != Op1)
12468 N->OperandList[0].set(Op1);
12469 if (N->OperandList[1] != Op2)
12470 N->OperandList[1].set(Op2);
12471
12473 // If this gets put into a CSE map, add it.
12474 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
12475 return N;
12476}
12477
12480 SDValue Ops[] = { Op1, Op2, Op3 };
12481 return UpdateNodeOperands(N, Ops);
12482}
12483
12486 SDValue Op3, SDValue Op4) {
12487 SDValue Ops[] = { Op1, Op2, Op3, Op4 };
12488 return UpdateNodeOperands(N, Ops);
12489}
12490
12493 SDValue Op3, SDValue Op4, SDValue Op5) {
12494 SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 };
12495 return UpdateNodeOperands(N, Ops);
12496}
12497
12500 unsigned NumOps = Ops.size();
12501 assert(N->getNumOperands() == NumOps &&
12502 "Update with wrong number of operands");
12503
12504 // If no operands changed just return the input node.
12505 if (std::equal(Ops.begin(), Ops.end(), N->op_begin()))
12506 return N;
12507
12508 // See if the modified node already exists.
12509 void *InsertPos = nullptr;
12510 if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertPos))
12511 return Existing;
12512
12513 // Nope it doesn't. Remove the node from its current place in the maps.
12514 if (InsertPos)
12515 if (!RemoveNodeFromCSEMaps(N))
12516 InsertPos = nullptr;
12517
12518 // Now we update the operands.
12519 for (unsigned i = 0; i != NumOps; ++i)
12520 if (N->OperandList[i] != Ops[i])
12521 N->OperandList[i].set(Ops[i]);
12522
12524 // If this gets put into a CSE map, add it.
12525 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
12526 return N;
12527}
12528
12529/// DropOperands - Release the operands and set this node to have
12530/// zero operands.
12532 // Unlike the code in MorphNodeTo that does this, we don't need to
12533 // watch for dead nodes here.
12534 for (op_iterator I = op_begin(), E = op_end(); I != E; ) {
12535 SDUse &Use = *I++;
12536 Use.set(SDValue());
12537 }
12538}
12539
12541 ArrayRef<MachineMemOperand *> NewMemRefs) {
12542 if (NewMemRefs.empty()) {
12543 N->clearMemRefs();
12544 return;
12545 }
12546
12547 // Check if we can avoid allocating by storing a single reference directly.
12548 if (NewMemRefs.size() == 1) {
12549 N->MemRefs = NewMemRefs[0];
12550 N->NumMemRefs = 1;
12551 return;
12552 }
12553
12554 MachineMemOperand **MemRefsBuffer =
12555 Allocator.template Allocate<MachineMemOperand *>(NewMemRefs.size());
12556 llvm::copy(NewMemRefs, MemRefsBuffer);
12557 N->MemRefs = MemRefsBuffer;
12558 N->NumMemRefs = static_cast<int>(NewMemRefs.size());
12559}
12560
12561/// SelectNodeTo - These are wrappers around MorphNodeTo that accept a
12562/// machine opcode.
12563///
12565 EVT VT) {
12566 SDVTList VTs = getVTList(VT);
12567 return SelectNodeTo(N, MachineOpc, VTs, {});
12568}
12569
12571 EVT VT, SDValue Op1) {
12572 SDVTList VTs = getVTList(VT);
12573 SDValue Ops[] = { Op1 };
12574 return SelectNodeTo(N, MachineOpc, VTs, Ops);
12575}
12576
12578 EVT VT, SDValue Op1,
12579 SDValue Op2) {
12580 SDVTList VTs = getVTList(VT);
12581 SDValue Ops[] = { Op1, Op2 };
12582 return SelectNodeTo(N, MachineOpc, VTs, Ops);
12583}
12584
12586 EVT VT, SDValue Op1,
12587 SDValue Op2, SDValue Op3) {
12588 SDVTList VTs = getVTList(VT);
12589 SDValue Ops[] = { Op1, Op2, Op3 };
12590 return SelectNodeTo(N, MachineOpc, VTs, Ops);
12591}
12592
12595 SDVTList VTs = getVTList(VT);
12596 return SelectNodeTo(N, MachineOpc, VTs, Ops);
12597}
12598
12600 EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) {
12601 SDVTList VTs = getVTList(VT1, VT2);
12602 return SelectNodeTo(N, MachineOpc, VTs, Ops);
12603}
12604
12606 EVT VT1, EVT VT2) {
12607 SDVTList VTs = getVTList(VT1, VT2);
12608 return SelectNodeTo(N, MachineOpc, VTs, {});
12609}
12610
12612 EVT VT1, EVT VT2, EVT VT3,
12614 SDVTList VTs = getVTList(VT1, VT2, VT3);
12615 return SelectNodeTo(N, MachineOpc, VTs, Ops);
12616}
12617
12619 EVT VT1, EVT VT2,
12620 SDValue Op1, SDValue Op2) {
12621 SDVTList VTs = getVTList(VT1, VT2);
12622 SDValue Ops[] = { Op1, Op2 };
12623 return SelectNodeTo(N, MachineOpc, VTs, Ops);
12624}
12625
12628 SDNode *New = MorphNodeTo(N, ~MachineOpc, VTs, Ops);
12629 // Reset the NodeID to -1.
12630 New->setNodeId(-1);
12631 if (New != N) {
12632 ReplaceAllUsesWith(N, New);
12634 }
12635 return New;
12636}
12637
12638/// UpdateSDLocOnMergeSDNode - If the opt level is -O0 then it throws away
12639/// the line number information on the merged node since it is not possible to
12640/// preserve the information that operation is associated with multiple lines.
12641/// This will make the debugger working better at -O0, were there is a higher
12642/// probability having other instructions associated with that line.
12643///
12644/// For IROrder, we keep the smaller of the two
12645SDNode *SelectionDAG::UpdateSDLocOnMergeSDNode(SDNode *N, const SDLoc &OLoc) {
12646 DebugLoc NLoc = N->getDebugLoc();
12647 if (NLoc && OptLevel == CodeGenOptLevel::None && OLoc.getDebugLoc() != NLoc) {
12648 N->setDebugLoc(DebugLoc());
12649 }
12650 unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder());
12651 N->setIROrder(Order);
12652 return N;
12653}
12654
12655/// MorphNodeTo - This *mutates* the specified node to have the specified
12656/// return type, opcode, and operands.
12657///
12658/// Note that MorphNodeTo returns the resultant node. If there is already a
12659/// node of the specified opcode and operands, it returns that node instead of
12660/// the current one. Note that the SDLoc need not be the same.
12661///
12662/// Using MorphNodeTo is faster than creating a new node and swapping it in
12663/// with ReplaceAllUsesWith both because it often avoids allocating a new
12664/// node, and because it doesn't require CSE recalculation for any of
12665/// the node's users.
12666///
12667/// However, note that MorphNodeTo recursively deletes dead nodes from the DAG.
12668/// As a consequence it isn't appropriate to use from within the DAG combiner or
12669/// the legalizer which maintain worklists that would need to be updated when
12670/// deleting things.
12673 // If an identical node already exists, use it.
12674 void *IP = nullptr;
12675 if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) {
12677 AddNodeIDNode(ID, Opc, VTs, Ops);
12678 if (SDNode *ON = FindNodeOrInsertPos(ID, SDLoc(N), IP))
12679 return UpdateSDLocOnMergeSDNode(ON, SDLoc(N));
12680 }
12681
12682 if (!RemoveNodeFromCSEMaps(N))
12683 IP = nullptr;
12684
12685 // Start the morphing.
12686 N->NodeType = Opc;
12687 N->ValueList = VTs.VTs;
12688 N->NumValues = VTs.NumVTs;
12689
12690 // Clear the operands list, updating used nodes to remove this from their
12691 // use list. Keep track of any operands that become dead as a result.
12692 SmallPtrSet<SDNode*, 16> DeadNodeSet;
12693 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
12694 SDUse &Use = *I++;
12695 SDNode *Used = Use.getNode();
12696 Use.set(SDValue());
12697 if (Used->use_empty())
12698 DeadNodeSet.insert(Used);
12699 }
12700
12701 // For MachineNode, initialize the memory references information.
12703 MN->clearMemRefs();
12704
12705 // Swap for an appropriately sized array from the recycler.
12706 removeOperands(N);
12707 createOperands(N, Ops);
12708
12709 // Delete any nodes that are still dead after adding the uses for the
12710 // new operands.
12711 if (!DeadNodeSet.empty()) {
12712 SmallVector<SDNode *, 16> DeadNodes;
12713 for (SDNode *N : DeadNodeSet)
12714 if (N->use_empty())
12715 DeadNodes.push_back(N);
12716 RemoveDeadNodes(DeadNodes);
12717 }
12718
12719 if (IP)
12720 CSEMap.InsertNode(N, IP); // Memoize the new node.
12721 return N;
12722}
12723
12725 unsigned OrigOpc = Node->getOpcode();
12726 unsigned NewOpc;
12727 switch (OrigOpc) {
12728 default:
12729 llvm_unreachable("mutateStrictFPToFP called with unexpected opcode!");
12730#define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \
12731 case ISD::STRICT_##DAGN: NewOpc = ISD::DAGN; break;
12732#define CMP_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \
12733 case ISD::STRICT_##DAGN: NewOpc = ISD::SETCC; break;
12734#include "llvm/IR/ConstrainedOps.def"
12735 }
12736
12737 assert(Node->getNumValues() == 2 && "Unexpected number of results!");
12738
12739 // We're taking this node out of the chain, so we need to re-link things.
12740 SDValue InputChain = Node->getOperand(0);
12741 SDValue OutputChain = SDValue(Node, 1);
12742 ReplaceAllUsesOfValueWith(OutputChain, InputChain);
12743
12745 for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
12746 Ops.push_back(Node->getOperand(i));
12747
12748 SDVTList VTs = getVTList(Node->getValueType(0));
12749 SDNode *Res = MorphNodeTo(Node, NewOpc, VTs, Ops);
12750
12751 // MorphNodeTo can operate in two ways: if an existing node with the
12752 // specified operands exists, it can just return it. Otherwise, it
12753 // updates the node in place to have the requested operands.
12754 if (Res == Node) {
12755 // If we updated the node in place, reset the node ID. To the isel,
12756 // this should be just like a newly allocated machine node.
12757 Res->setNodeId(-1);
12758 } else {
12761 }
12762
12763 return Res;
12764}
12765
12766/// getMachineNode - These are used for target selectors to create a new node
12767/// with specified return type(s), MachineInstr opcode, and operands.
12768///
12769/// Note that getMachineNode returns the resultant node. If there is already a
12770/// node of the specified opcode and operands, it returns that node instead of
12771/// the current one.
12773 EVT VT) {
12774 SDVTList VTs = getVTList(VT);
12775 return getMachineNode(Opcode, dl, VTs, {});
12776}
12777
12779 EVT VT, SDValue Op1) {
12780 SDVTList VTs = getVTList(VT);
12781 SDValue Ops[] = { Op1 };
12782 return getMachineNode(Opcode, dl, VTs, Ops);
12783}
12784
12786 EVT VT, SDValue Op1, SDValue Op2) {
12787 SDVTList VTs = getVTList(VT);
12788 SDValue Ops[] = { Op1, Op2 };
12789 return getMachineNode(Opcode, dl, VTs, Ops);
12790}
12791
12793 EVT VT, SDValue Op1, SDValue Op2,
12794 SDValue Op3) {
12795 SDVTList VTs = getVTList(VT);
12796 SDValue Ops[] = { Op1, Op2, Op3 };
12797 return getMachineNode(Opcode, dl, VTs, Ops);
12798}
12799
12802 SDVTList VTs = getVTList(VT);
12803 return getMachineNode(Opcode, dl, VTs, Ops);
12804}
12805
12807 EVT VT1, EVT VT2, SDValue Op1,
12808 SDValue Op2) {
12809 SDVTList VTs = getVTList(VT1, VT2);
12810 SDValue Ops[] = { Op1, Op2 };
12811 return getMachineNode(Opcode, dl, VTs, Ops);
12812}
12813
12815 EVT VT1, EVT VT2, SDValue Op1,
12816 SDValue Op2, SDValue Op3) {
12817 SDVTList VTs = getVTList(VT1, VT2);
12818 SDValue Ops[] = { Op1, Op2, Op3 };
12819 return getMachineNode(Opcode, dl, VTs, Ops);
12820}
12821
12823 EVT VT1, EVT VT2,
12825 SDVTList VTs = getVTList(VT1, VT2);
12826 return getMachineNode(Opcode, dl, VTs, Ops);
12827}
12828
12830 EVT VT1, EVT VT2, EVT VT3,
12831 SDValue Op1, SDValue Op2) {
12832 SDVTList VTs = getVTList(VT1, VT2, VT3);
12833 SDValue Ops[] = { Op1, Op2 };
12834 return getMachineNode(Opcode, dl, VTs, Ops);
12835}
12836
12838 EVT VT1, EVT VT2, EVT VT3,
12839 SDValue Op1, SDValue Op2,
12840 SDValue Op3) {
12841 SDVTList VTs = getVTList(VT1, VT2, VT3);
12842 SDValue Ops[] = { Op1, Op2, Op3 };
12843 return getMachineNode(Opcode, dl, VTs, Ops);
12844}
12845
12847 EVT VT1, EVT VT2, EVT VT3,
12849 SDVTList VTs = getVTList(VT1, VT2, VT3);
12850 return getMachineNode(Opcode, dl, VTs, Ops);
12851}
12852
12854 ArrayRef<EVT> ResultTys,
12856 SDVTList VTs = getVTList(ResultTys);
12857 return getMachineNode(Opcode, dl, VTs, Ops);
12858}
12859
12861 SDVTList VTs,
12863 bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue;
12865 void *IP = nullptr;
12866
12867 if (DoCSE) {
12869 AddNodeIDNode(ID, ~Opcode, VTs, Ops);
12870 IP = nullptr;
12871 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
12872 return cast<MachineSDNode>(UpdateSDLocOnMergeSDNode(E, DL));
12873 }
12874 }
12875
12876 // Allocate a new MachineSDNode.
12877 N = newSDNode<MachineSDNode>(~Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
12878 createOperands(N, Ops);
12879
12880 if (DoCSE)
12881 CSEMap.InsertNode(N, IP);
12882
12883 InsertNode(N);
12884 NewSDValueDbgMsg(SDValue(N, 0), "Creating new machine node: ", this);
12885 return N;
12886}
12887
12888/// getTargetExtractSubreg - A convenience function for creating
12889/// TargetOpcode::EXTRACT_SUBREG nodes.
12891 SDValue Operand) {
12892 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
12893 SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,
12894 VT, Operand, SRIdxVal);
12895 return SDValue(Subreg, 0);
12896}
12897
12898/// getTargetInsertSubreg - A convenience function for creating
12899/// TargetOpcode::INSERT_SUBREG nodes.
12901 SDValue Operand, SDValue Subreg) {
12902 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
12903 SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL,
12904 VT, Operand, Subreg, SRIdxVal);
12905 return SDValue(Result, 0);
12906}
12907
12908/// getNodeIfExists - Get the specified node if it's already available, or
12909/// else return NULL.
12912 bool AllowCommute) {
12913 SDNodeFlags Flags;
12914 if (Inserter)
12915 Flags = Inserter->getFlags();
12916 return getNodeIfExists(Opcode, VTList, Ops, Flags, AllowCommute);
12917}
12918
12921 const SDNodeFlags Flags,
12922 bool AllowCommute) {
12923 if (VTList.VTs[VTList.NumVTs - 1] == MVT::Glue)
12924 return nullptr;
12925
12926 auto Lookup = [&](ArrayRef<SDValue> LookupOps) -> SDNode * {
12928 AddNodeIDNode(ID, Opcode, VTList, LookupOps);
12929 void *IP = nullptr;
12930 if (SDNode *E = FindNodeOrInsertPos(ID, IP)) {
12931 E->intersectFlagsWith(Flags);
12932 return E;
12933 }
12934 return nullptr;
12935 };
12936
12937 if (SDNode *Existing = Lookup(Ops))
12938 return Existing;
12939
12940 if (AllowCommute && TLI->isCommutativeBinOp(Opcode))
12941 return Lookup({Ops[1], Ops[0]});
12942
12943 return nullptr;
12944}
12945
12946/// doesNodeExist - Check if a node exists without modifying its flags.
12947bool SelectionDAG::doesNodeExist(unsigned Opcode, SDVTList VTList,
12949 if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
12951 AddNodeIDNode(ID, Opcode, VTList, Ops);
12952 void *IP = nullptr;
12953 if (FindNodeOrInsertPos(ID, SDLoc(), IP))
12954 return true;
12955 }
12956 return false;
12957}
12958
12959/// getDbgValue - Creates a SDDbgValue node.
12960///
12961/// SDNode
12963 SDNode *N, unsigned R, bool IsIndirect,
12964 const DebugLoc &DL, unsigned O) {
12965 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
12966 "Expected inlined-at fields to agree");
12967 return new (DbgInfo->getAlloc())
12968 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromNode(N, R),
12969 {}, IsIndirect, DL, O,
12970 /*IsVariadic=*/false);
12971}
12972
12973/// Constant
12975 DIExpression *Expr,
12976 const Value *C,
12977 const DebugLoc &DL, unsigned O) {
12978 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
12979 "Expected inlined-at fields to agree");
12980 return new (DbgInfo->getAlloc())
12981 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromConst(C), {},
12982 /*IsIndirect=*/false, DL, O,
12983 /*IsVariadic=*/false);
12984}
12985
12986/// FrameIndex
12988 DIExpression *Expr, unsigned FI,
12989 bool IsIndirect,
12990 const DebugLoc &DL,
12991 unsigned O) {
12992 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
12993 "Expected inlined-at fields to agree");
12994 return getFrameIndexDbgValue(Var, Expr, FI, {}, IsIndirect, DL, O);
12995}
12996
12997/// FrameIndex with dependencies
12999 DIExpression *Expr, unsigned FI,
13000 ArrayRef<SDNode *> Dependencies,
13001 bool IsIndirect,
13002 const DebugLoc &DL,
13003 unsigned O) {
13004 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
13005 "Expected inlined-at fields to agree");
13006 return new (DbgInfo->getAlloc())
13007 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromFrameIdx(FI),
13008 Dependencies, IsIndirect, DL, O,
13009 /*IsVariadic=*/false);
13010}
13011
13012/// VReg
13014 Register VReg, bool IsIndirect,
13015 const DebugLoc &DL, unsigned O) {
13016 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
13017 "Expected inlined-at fields to agree");
13018 return new (DbgInfo->getAlloc())
13019 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromVReg(VReg),
13020 {}, IsIndirect, DL, O,
13021 /*IsVariadic=*/false);
13022}
13023
13026 ArrayRef<SDNode *> Dependencies,
13027 bool IsIndirect, const DebugLoc &DL,
13028 unsigned O, bool IsVariadic) {
13029 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
13030 "Expected inlined-at fields to agree");
13031 return new (DbgInfo->getAlloc())
13032 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, Locs, Dependencies, IsIndirect,
13033 DL, O, IsVariadic);
13034}
13035
13037 unsigned OffsetInBits, unsigned SizeInBits,
13038 bool InvalidateDbg) {
13039 SDNode *FromNode = From.getNode();
13040 SDNode *ToNode = To.getNode();
13041 assert(FromNode && ToNode && "Can't modify dbg values");
13042
13043 // PR35338
13044 // TODO: assert(From != To && "Redundant dbg value transfer");
13045 // TODO: assert(FromNode != ToNode && "Intranode dbg value transfer");
13046 if (From == To || FromNode == ToNode)
13047 return;
13048
13049 if (!FromNode->getHasDebugValue())
13050 return;
13051
13052 SDDbgOperand FromLocOp =
13053 SDDbgOperand::fromNode(From.getNode(), From.getResNo());
13055
13057 for (SDDbgValue *Dbg : GetDbgValues(FromNode)) {
13058 if (Dbg->isInvalidated())
13059 continue;
13060
13061 // TODO: assert(!Dbg->isInvalidated() && "Transfer of invalid dbg value");
13062
13063 // Create a new location ops vector that is equal to the old vector, but
13064 // with each instance of FromLocOp replaced with ToLocOp.
13065 bool Changed = false;
13066 auto NewLocOps = Dbg->copyLocationOps();
13067 std::replace_if(
13068 NewLocOps.begin(), NewLocOps.end(),
13069 [&Changed, FromLocOp](const SDDbgOperand &Op) {
13070 bool Match = Op == FromLocOp;
13071 Changed |= Match;
13072 return Match;
13073 },
13074 ToLocOp);
13075 // Ignore this SDDbgValue if we didn't find a matching location.
13076 if (!Changed)
13077 continue;
13078
13079 DIVariable *Var = Dbg->getVariable();
13080 auto *Expr = Dbg->getExpression();
13081 // If a fragment is requested, update the expression.
13082 if (SizeInBits) {
13083 // When splitting a larger (e.g., sign-extended) value whose
13084 // lower bits are described with an SDDbgValue, do not attempt
13085 // to transfer the SDDbgValue to the upper bits.
13086 if (auto FI = Expr->getFragmentInfo())
13087 if (OffsetInBits + SizeInBits > FI->SizeInBits)
13088 continue;
13089 auto Fragment = DIExpression::createFragmentExpression(Expr, OffsetInBits,
13090 SizeInBits);
13091 if (!Fragment)
13092 continue;
13093 Expr = *Fragment;
13094 }
13095
13096 auto AdditionalDependencies = Dbg->getAdditionalDependencies();
13097 // Clone the SDDbgValue and move it to To.
13098 SDDbgValue *Clone = getDbgValueList(
13099 Var, Expr, NewLocOps, AdditionalDependencies, Dbg->isIndirect(),
13100 Dbg->getDebugLoc(), std::max(ToNode->getIROrder(), Dbg->getOrder()),
13101 Dbg->isVariadic());
13102 ClonedDVs.push_back(Clone);
13103
13104 if (InvalidateDbg) {
13105 // Invalidate value and indicate the SDDbgValue should not be emitted.
13106 Dbg->setIsInvalidated();
13107 Dbg->setIsEmitted();
13108 }
13109 }
13110
13111 for (SDDbgValue *Dbg : ClonedDVs) {
13112 assert(is_contained(Dbg->getSDNodes(), ToNode) &&
13113 "Transferred DbgValues should depend on the new SDNode");
13114 AddDbgValue(Dbg, false);
13115 }
13116}
13117
13119 if (!N.getHasDebugValue())
13120 return;
13121
13122 auto GetLocationOperand = [](SDNode *Node, unsigned ResNo) {
13123 if (auto *FISDN = dyn_cast<FrameIndexSDNode>(Node))
13124 return SDDbgOperand::fromFrameIdx(FISDN->getIndex());
13125 return SDDbgOperand::fromNode(Node, ResNo);
13126 };
13127
13129 for (auto *DV : GetDbgValues(&N)) {
13130 if (DV->isInvalidated())
13131 continue;
13132 switch (N.getOpcode()) {
13133 default:
13134 break;
13135 case ISD::ADD: {
13136 SDValue N0 = N.getOperand(0);
13137 SDValue N1 = N.getOperand(1);
13138 if (!isa<ConstantSDNode>(N0)) {
13139 bool RHSConstant = isa<ConstantSDNode>(N1);
13141 if (RHSConstant)
13142 Offset = N.getConstantOperandVal(1);
13143 // We are not allowed to turn indirect debug values variadic, so
13144 // don't salvage those.
13145 if (!RHSConstant && DV->isIndirect())
13146 continue;
13147
13148 // Rewrite an ADD constant node into a DIExpression. Since we are
13149 // performing arithmetic to compute the variable's *value* in the
13150 // DIExpression, we need to mark the expression with a
13151 // DW_OP_stack_value.
13152 auto *DIExpr = DV->getExpression();
13153 auto NewLocOps = DV->copyLocationOps();
13154 bool Changed = false;
13155 size_t OrigLocOpsSize = NewLocOps.size();
13156 for (size_t i = 0; i < OrigLocOpsSize; ++i) {
13157 // We're not given a ResNo to compare against because the whole
13158 // node is going away. We know that any ISD::ADD only has one
13159 // result, so we can assume any node match is using the result.
13160 if (NewLocOps[i].getKind() != SDDbgOperand::SDNODE ||
13161 NewLocOps[i].getSDNode() != &N)
13162 continue;
13163 NewLocOps[i] = GetLocationOperand(N0.getNode(), N0.getResNo());
13164 if (RHSConstant) {
13167 DIExpr = DIExpression::appendOpsToArg(DIExpr, ExprOps, i, true);
13168 } else {
13169 // Convert to a variadic expression (if not already).
13170 // convertToVariadicExpression() returns a const pointer, so we use
13171 // a temporary const variable here.
13172 const auto *TmpDIExpr =
13176 ExprOps.push_back(NewLocOps.size());
13177 ExprOps.push_back(dwarf::DW_OP_plus);
13178 SDDbgOperand RHS =
13180 NewLocOps.push_back(RHS);
13181 DIExpr = DIExpression::appendOpsToArg(TmpDIExpr, ExprOps, i, true);
13182 }
13183 Changed = true;
13184 }
13185 (void)Changed;
13186 assert(Changed && "Salvage target doesn't use N");
13187
13188 bool IsVariadic =
13189 DV->isVariadic() || OrigLocOpsSize != NewLocOps.size();
13190
13191 auto AdditionalDependencies = DV->getAdditionalDependencies();
13192 SDDbgValue *Clone = getDbgValueList(
13193 DV->getVariable(), DIExpr, NewLocOps, AdditionalDependencies,
13194 DV->isIndirect(), DV->getDebugLoc(), DV->getOrder(), IsVariadic);
13195 ClonedDVs.push_back(Clone);
13196 DV->setIsInvalidated();
13197 DV->setIsEmitted();
13198 LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting";
13199 N0.getNode()->dumprFull(this);
13200 dbgs() << " into " << *DIExpr << '\n');
13201 }
13202 break;
13203 }
13204 case ISD::TRUNCATE: {
13205 SDValue N0 = N.getOperand(0);
13206 TypeSize FromSize = N0.getValueSizeInBits();
13207 TypeSize ToSize = N.getValueSizeInBits(0);
13208
13209 DIExpression *DbgExpression = DV->getExpression();
13210 auto ExtOps = DIExpression::getExtOps(FromSize, ToSize, false);
13211 auto NewLocOps = DV->copyLocationOps();
13212 bool Changed = false;
13213 for (size_t i = 0; i < NewLocOps.size(); ++i) {
13214 if (NewLocOps[i].getKind() != SDDbgOperand::SDNODE ||
13215 NewLocOps[i].getSDNode() != &N)
13216 continue;
13217
13218 NewLocOps[i] = GetLocationOperand(N0.getNode(), N0.getResNo());
13219 DbgExpression = DIExpression::appendOpsToArg(DbgExpression, ExtOps, i);
13220 Changed = true;
13221 }
13222 assert(Changed && "Salvage target doesn't use N");
13223 (void)Changed;
13224
13225 SDDbgValue *Clone =
13226 getDbgValueList(DV->getVariable(), DbgExpression, NewLocOps,
13227 DV->getAdditionalDependencies(), DV->isIndirect(),
13228 DV->getDebugLoc(), DV->getOrder(), DV->isVariadic());
13229
13230 ClonedDVs.push_back(Clone);
13231 DV->setIsInvalidated();
13232 DV->setIsEmitted();
13233 LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting"; N0.getNode()->dumprFull(this);
13234 dbgs() << " into " << *DbgExpression << '\n');
13235 break;
13236 }
13237 }
13238 }
13239
13240 for (SDDbgValue *Dbg : ClonedDVs) {
13241 assert((!Dbg->getSDNodes().empty() ||
13242 llvm::any_of(Dbg->getLocationOps(),
13243 [&](const SDDbgOperand &Op) {
13244 return Op.getKind() == SDDbgOperand::FRAMEIX;
13245 })) &&
13246 "Salvaged DbgValue should depend on a new SDNode");
13247 AddDbgValue(Dbg, false);
13248 }
13249}
13250
13251/// Creates a SDDbgLabel node.
13253 const DebugLoc &DL, unsigned O) {
13254 assert(cast<DILabel>(Label)->isValidLocationForIntrinsic(DL) &&
13255 "Expected inlined-at fields to agree");
13256 return new (DbgInfo->getAlloc()) SDDbgLabel(Label, DL, O);
13257}
13258
13259namespace {
13260
13261/// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node
13262/// pointed to by a use iterator is deleted, increment the use iterator
13263/// so that it doesn't dangle.
13264///
13265class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener {
13268
13269 void NodeDeleted(SDNode *N, SDNode *E) override {
13270 // Increment the iterator as needed.
13271 while (UI != UE && N == UI->getUser())
13272 ++UI;
13273 }
13274
13275public:
13276 RAUWUpdateListener(SelectionDAG &d,
13279 : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {}
13280};
13281
13282} // end anonymous namespace
13283
13284/// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
13285/// This can cause recursive merging of nodes in the DAG.
13286///
13287/// This version assumes From has a single result value.
13288///
13290 SDNode *From = FromN.getNode();
13291 assert(From->getNumValues() == 1 && FromN.getResNo() == 0 &&
13292 "Cannot replace with this method!");
13293 assert(From != To.getNode() && "Cannot replace uses of with self");
13294
13295 // Preserve Debug Values
13296 transferDbgValues(FromN, To);
13297 // Preserve extra info.
13298 copyExtraInfo(From, To.getNode());
13299
13300 // Iterate over all the existing uses of From. New uses will be added
13301 // to the beginning of the use list, which we avoid visiting.
13302 // This specifically avoids visiting uses of From that arise while the
13303 // replacement is happening, because any such uses would be the result
13304 // of CSE: If an existing node looks like From after one of its operands
13305 // is replaced by To, we don't want to replace of all its users with To
13306 // too. See PR3018 for more info.
13307 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
13308 RAUWUpdateListener Listener(*this, UI, UE);
13309 while (UI != UE) {
13310 SDNode *User = UI->getUser();
13311
13312 // This node is about to morph, remove its old self from the CSE maps.
13313 RemoveNodeFromCSEMaps(User);
13314
13315 // A user can appear in a use list multiple times, and when this
13316 // happens the uses are usually next to each other in the list.
13317 // To help reduce the number of CSE recomputations, process all
13318 // the uses of this user that we can find this way.
13319 do {
13320 SDUse &Use = *UI;
13321 ++UI;
13322 Use.set(To);
13323 if (To->isDivergent() != From->isDivergent())
13325 } while (UI != UE && UI->getUser() == User);
13326 // Now that we have modified User, add it back to the CSE maps. If it
13327 // already exists there, recursively merge the results together.
13328 AddModifiedNodeToCSEMaps(User);
13329 }
13330
13331 // If we just RAUW'd the root, take note.
13332 if (FromN == getRoot())
13333 setRoot(To);
13334}
13335
13336/// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
13337/// This can cause recursive merging of nodes in the DAG.
13338///
13339/// This version assumes that for each value of From, there is a
13340/// corresponding value in To in the same position with the same type.
13341///
13343#ifndef NDEBUG
13344 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
13345 assert((!From->hasAnyUseOfValue(i) ||
13346 From->getValueType(i) == To->getValueType(i)) &&
13347 "Cannot use this version of ReplaceAllUsesWith!");
13348#endif
13349
13350 // Handle the trivial case.
13351 if (From == To)
13352 return;
13353
13354 // Preserve Debug Info. Only do this if there's a use.
13355 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
13356 if (From->hasAnyUseOfValue(i)) {
13357 assert((i < To->getNumValues()) && "Invalid To location");
13358 transferDbgValues(SDValue(From, i), SDValue(To, i));
13359 }
13360 // Preserve extra info.
13361 copyExtraInfo(From, To);
13362
13363 // Iterate over just the existing users of From. See the comments in
13364 // the ReplaceAllUsesWith above.
13365 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
13366 RAUWUpdateListener Listener(*this, UI, UE);
13367 while (UI != UE) {
13368 SDNode *User = UI->getUser();
13369
13370 // This node is about to morph, remove its old self from the CSE maps.
13371 RemoveNodeFromCSEMaps(User);
13372
13373 // A user can appear in a use list multiple times, and when this
13374 // happens the uses are usually next to each other in the list.
13375 // To help reduce the number of CSE recomputations, process all
13376 // the uses of this user that we can find this way.
13377 do {
13378 SDUse &Use = *UI;
13379 ++UI;
13380 Use.setNode(To);
13381 if (To->isDivergent() != From->isDivergent())
13383 } while (UI != UE && UI->getUser() == User);
13384
13385 // Now that we have modified User, add it back to the CSE maps. If it
13386 // already exists there, recursively merge the results together.
13387 AddModifiedNodeToCSEMaps(User);
13388 }
13389
13390 // If we just RAUW'd the root, take note.
13391 if (From == getRoot().getNode())
13392 setRoot(SDValue(To, getRoot().getResNo()));
13393}
13394
13395/// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
13396/// This can cause recursive merging of nodes in the DAG.
13397///
13398/// This version can replace From with any result values. To must match the
13399/// number and types of values returned by From.
13401 if (From->getNumValues() == 1) // Handle the simple case efficiently.
13402 return ReplaceAllUsesWith(SDValue(From, 0), To[0]);
13403
13404 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) {
13405 // Preserve Debug Info.
13406 transferDbgValues(SDValue(From, i), To[i]);
13407 // Preserve extra info.
13408 copyExtraInfo(From, To[i].getNode());
13409 }
13410
13411 // Iterate over just the existing users of From. See the comments in
13412 // the ReplaceAllUsesWith above.
13413 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
13414 RAUWUpdateListener Listener(*this, UI, UE);
13415 while (UI != UE) {
13416 SDNode *User = UI->getUser();
13417
13418 // This node is about to morph, remove its old self from the CSE maps.
13419 RemoveNodeFromCSEMaps(User);
13420
13421 // A user can appear in a use list multiple times, and when this happens the
13422 // uses are usually next to each other in the list. To help reduce the
13423 // number of CSE and divergence recomputations, process all the uses of this
13424 // user that we can find this way.
13425 bool To_IsDivergent = false;
13426 do {
13427 SDUse &Use = *UI;
13428 const SDValue &ToOp = To[Use.getResNo()];
13429 ++UI;
13430 Use.set(ToOp);
13431 if (ToOp.getValueType() != MVT::Other)
13432 To_IsDivergent |= ToOp->isDivergent();
13433 } while (UI != UE && UI->getUser() == User);
13434
13435 if (To_IsDivergent != From->isDivergent())
13437
13438 // Now that we have modified User, add it back to the CSE maps. If it
13439 // already exists there, recursively merge the results together.
13440 AddModifiedNodeToCSEMaps(User);
13441 }
13442
13443 // If we just RAUW'd the root, take note.
13444 if (From == getRoot().getNode())
13445 setRoot(SDValue(To[getRoot().getResNo()]));
13446}
13447
13448/// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
13449/// uses of other values produced by From.getNode() alone. The Deleted
13450/// vector is handled the same way as for ReplaceAllUsesWith.
13452 // Handle the really simple, really trivial case efficiently.
13453 if (From == To) return;
13454
13455 // Handle the simple, trivial, case efficiently.
13456 if (From.getNode()->getNumValues() == 1) {
13457 ReplaceAllUsesWith(From, To);
13458 return;
13459 }
13460
13461 // Preserve Debug Info.
13462 transferDbgValues(From, To);
13463 copyExtraInfo(From.getNode(), To.getNode());
13464
13465 // Iterate over just the existing users of From. See the comments in
13466 // the ReplaceAllUsesWith above.
13467 SDNode::use_iterator UI = From.getNode()->use_begin(),
13468 UE = From.getNode()->use_end();
13469 RAUWUpdateListener Listener(*this, UI, UE);
13470 while (UI != UE) {
13471 SDNode *User = UI->getUser();
13472 bool UserRemovedFromCSEMaps = false;
13473
13474 // A user can appear in a use list multiple times, and when this
13475 // happens the uses are usually next to each other in the list.
13476 // To help reduce the number of CSE recomputations, process all
13477 // the uses of this user that we can find this way.
13478 do {
13479 SDUse &Use = *UI;
13480
13481 // Skip uses of different values from the same node.
13482 if (Use.getResNo() != From.getResNo()) {
13483 ++UI;
13484 continue;
13485 }
13486
13487 // If this node hasn't been modified yet, it's still in the CSE maps,
13488 // so remove its old self from the CSE maps.
13489 if (!UserRemovedFromCSEMaps) {
13490 RemoveNodeFromCSEMaps(User);
13491 UserRemovedFromCSEMaps = true;
13492 }
13493
13494 ++UI;
13495 Use.set(To);
13496 if (To->isDivergent() != From->isDivergent())
13498 } while (UI != UE && UI->getUser() == User);
13499 // We are iterating over all uses of the From node, so if a use
13500 // doesn't use the specific value, no changes are made.
13501 if (!UserRemovedFromCSEMaps)
13502 continue;
13503
13504 // Now that we have modified User, add it back to the CSE maps. If it
13505 // already exists there, recursively merge the results together.
13506 AddModifiedNodeToCSEMaps(User);
13507 }
13508
13509 // If we just RAUW'd the root, take note.
13510 if (From == getRoot())
13511 setRoot(To);
13512}
13513
13514namespace {
13515
13516/// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith
13517/// to record information about a use.
13518struct UseMemo {
13519 SDNode *User;
13520 unsigned Index;
13521 SDUse *Use;
13522};
13523
13524/// operator< - Sort Memos by User.
13525bool operator<(const UseMemo &L, const UseMemo &R) {
13526 return (intptr_t)L.User < (intptr_t)R.User;
13527}
13528
13529/// RAUOVWUpdateListener - Helper for ReplaceAllUsesOfValuesWith - When the node
13530/// pointed to by a UseMemo is deleted, set the User to nullptr to indicate that
13531/// the node already has been taken care of recursively.
13532class RAUOVWUpdateListener : public SelectionDAG::DAGUpdateListener {
13533 SmallVectorImpl<UseMemo> &Uses;
13534
13535 void NodeDeleted(SDNode *N, SDNode *E) override {
13536 for (UseMemo &Memo : Uses)
13537 if (Memo.User == N)
13538 Memo.User = nullptr;
13539 }
13540
13541public:
13542 RAUOVWUpdateListener(SelectionDAG &d, SmallVectorImpl<UseMemo> &uses)
13543 : SelectionDAG::DAGUpdateListener(d), Uses(uses) {}
13544};
13545
13546} // end anonymous namespace
13547
13548/// Return true if a glue output should propagate divergence information.
13550 switch (Node->getOpcode()) {
13551 case ISD::CopyFromReg:
13552 case ISD::CopyToReg:
13553 return false;
13554 default:
13555 return true;
13556 }
13557
13558 llvm_unreachable("covered opcode switch");
13559}
13560
13562 if (TLI->isSDNodeAlwaysUniform(N)) {
13563 assert(!TLI->isSDNodeSourceOfDivergence(N, FLI, UA) &&
13564 "Conflicting divergence information!");
13565 return false;
13566 }
13567 if (TLI->isSDNodeSourceOfDivergence(N, FLI, UA))
13568 return true;
13569 for (const auto &Op : N->ops()) {
13570 EVT VT = Op.getValueType();
13571
13572 // Skip Chain. It does not carry divergence.
13573 if (VT != MVT::Other && Op.getNode()->isDivergent() &&
13574 (VT != MVT::Glue || gluePropagatesDivergence(Op.getNode())))
13575 return true;
13576 }
13577 return false;
13578}
13579
13581 SmallVector<SDNode *, 16> Worklist(1, N);
13582 do {
13583 N = Worklist.pop_back_val();
13584 bool IsDivergent = calculateDivergence(N);
13585 if (N->SDNodeBits.IsDivergent != IsDivergent) {
13586 N->SDNodeBits.IsDivergent = IsDivergent;
13587 llvm::append_range(Worklist, N->users());
13588 }
13589 } while (!Worklist.empty());
13590}
13591
13592void SelectionDAG::CreateTopologicalOrder(std::vector<SDNode *> &Order) {
13594 Order.reserve(AllNodes.size());
13595 for (auto &N : allnodes()) {
13596 unsigned NOps = N.getNumOperands();
13597 Degree[&N] = NOps;
13598 if (0 == NOps)
13599 Order.push_back(&N);
13600 }
13601 for (size_t I = 0; I != Order.size(); ++I) {
13602 SDNode *N = Order[I];
13603 for (auto *U : N->users()) {
13604 unsigned &UnsortedOps = Degree[U];
13605 if (0 == --UnsortedOps)
13606 Order.push_back(U);
13607 }
13608 }
13609}
13610
13611#if !defined(NDEBUG) && LLVM_ENABLE_ABI_BREAKING_CHECKS
13612void SelectionDAG::VerifyDAGDivergence() {
13613 std::vector<SDNode *> TopoOrder;
13614 CreateTopologicalOrder(TopoOrder);
13615 for (auto *N : TopoOrder) {
13616 assert(calculateDivergence(N) == N->isDivergent() &&
13617 "Divergence bit inconsistency detected");
13618 }
13619}
13620#endif
13621
13622/// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving
13623/// uses of other values produced by From.getNode() alone. The same value
13624/// may appear in both the From and To list. The Deleted vector is
13625/// handled the same way as for ReplaceAllUsesWith.
13627 const SDValue *To,
13628 unsigned Num){
13629 // Handle the simple, trivial case efficiently.
13630 if (Num == 1)
13631 return ReplaceAllUsesOfValueWith(*From, *To);
13632
13633 transferDbgValues(*From, *To);
13634 copyExtraInfo(From->getNode(), To->getNode());
13635
13636 // Read up all the uses and make records of them. This helps
13637 // processing new uses that are introduced during the
13638 // replacement process.
13640 for (unsigned i = 0; i != Num; ++i) {
13641 unsigned FromResNo = From[i].getResNo();
13642 SDNode *FromNode = From[i].getNode();
13643 for (SDUse &Use : FromNode->uses()) {
13644 if (Use.getResNo() == FromResNo) {
13645 UseMemo Memo = {Use.getUser(), i, &Use};
13646 Uses.push_back(Memo);
13647 }
13648 }
13649 }
13650
13651 // Sort the uses, so that all the uses from a given User are together.
13653 RAUOVWUpdateListener Listener(*this, Uses);
13654
13655 for (unsigned UseIndex = 0, UseIndexEnd = Uses.size();
13656 UseIndex != UseIndexEnd; ) {
13657 // We know that this user uses some value of From. If it is the right
13658 // value, update it.
13659 SDNode *User = Uses[UseIndex].User;
13660 // If the node has been deleted by recursive CSE updates when updating
13661 // another node, then just skip this entry.
13662 if (User == nullptr) {
13663 ++UseIndex;
13664 continue;
13665 }
13666
13667 // This node is about to morph, remove its old self from the CSE maps.
13668 RemoveNodeFromCSEMaps(User);
13669
13670 // The Uses array is sorted, so all the uses for a given User
13671 // are next to each other in the list.
13672 // To help reduce the number of CSE recomputations, process all
13673 // the uses of this user that we can find this way.
13674 do {
13675 unsigned i = Uses[UseIndex].Index;
13676 SDUse &Use = *Uses[UseIndex].Use;
13677 ++UseIndex;
13678
13679 Use.set(To[i]);
13680 } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User);
13681
13682 // Now that we have modified User, add it back to the CSE maps. If it
13683 // already exists there, recursively merge the results together.
13684 AddModifiedNodeToCSEMaps(User);
13685 }
13686}
13687
13688/// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
13689/// based on their topological order. It returns the maximum id and a vector
13690/// of the SDNodes* in assigned order by reference.
13692 unsigned DAGSize = 0;
13693
13694 // SortedPos tracks the progress of the algorithm. Nodes before it are
13695 // sorted, nodes after it are unsorted. When the algorithm completes
13696 // it is at the end of the list.
13697 allnodes_iterator SortedPos = allnodes_begin();
13698
13699 // Visit all the nodes. Move nodes with no operands to the front of
13700 // the list immediately. Annotate nodes that do have operands with their
13701 // operand count. Before we do this, the Node Id fields of the nodes
13702 // may contain arbitrary values. After, the Node Id fields for nodes
13703 // before SortedPos will contain the topological sort index, and the
13704 // Node Id fields for nodes At SortedPos and after will contain the
13705 // count of outstanding operands.
13707 checkForCycles(&N, this);
13708 unsigned Degree = N.getNumOperands();
13709 if (Degree == 0) {
13710 // A node with no uses, add it to the result array immediately.
13711 N.setNodeId(DAGSize++);
13712 allnodes_iterator Q(&N);
13713 if (Q != SortedPos)
13714 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q));
13715 assert(SortedPos != AllNodes.end() && "Overran node list");
13716 ++SortedPos;
13717 } else {
13718 // Temporarily use the Node Id as scratch space for the degree count.
13719 N.setNodeId(Degree);
13720 }
13721 }
13722
13723 // Visit all the nodes. As we iterate, move nodes into sorted order,
13724 // such that by the time the end is reached all nodes will be sorted.
13725 for (SDNode &Node : allnodes()) {
13726 SDNode *N = &Node;
13727 checkForCycles(N, this);
13728 // N is in sorted position, so all its uses have one less operand
13729 // that needs to be sorted.
13730 for (SDNode *P : N->users()) {
13731 unsigned Degree = P->getNodeId();
13732 assert(Degree != 0 && "Invalid node degree");
13733 --Degree;
13734 if (Degree == 0) {
13735 // All of P's operands are sorted, so P may sorted now.
13736 P->setNodeId(DAGSize++);
13737 if (P->getIterator() != SortedPos)
13738 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P));
13739 assert(SortedPos != AllNodes.end() && "Overran node list");
13740 ++SortedPos;
13741 } else {
13742 // Update P's outstanding operand count.
13743 P->setNodeId(Degree);
13744 }
13745 }
13746 if (Node.getIterator() == SortedPos) {
13747#ifndef NDEBUG
13749 SDNode *S = &*++I;
13750 dbgs() << "Overran sorted position:\n";
13751 S->dumprFull(this); dbgs() << "\n";
13752 dbgs() << "Checking if this is due to cycles\n";
13753 checkForCycles(this, true);
13754#endif
13755 llvm_unreachable(nullptr);
13756 }
13757 }
13758
13759 assert(SortedPos == AllNodes.end() &&
13760 "Topological sort incomplete!");
13761 assert(AllNodes.front().getOpcode() == ISD::EntryToken &&
13762 "First node in topological sort is not the entry token!");
13763 assert(AllNodes.front().getNodeId() == 0 &&
13764 "First node in topological sort has non-zero id!");
13765 assert(AllNodes.front().getNumOperands() == 0 &&
13766 "First node in topological sort has operands!");
13767 assert(AllNodes.back().getNodeId() == (int)DAGSize-1 &&
13768 "Last node in topologic sort has unexpected id!");
13769 assert(AllNodes.back().use_empty() &&
13770 "Last node in topologic sort has users!");
13771 assert(DAGSize == allnodes_size() && "Node count mismatch!");
13772 return DAGSize;
13773}
13774
13776 SmallVectorImpl<const SDNode *> &SortedNodes) const {
13777 SortedNodes.clear();
13778 // Node -> remaining number of outstanding operands.
13779 DenseMap<const SDNode *, unsigned> RemainingOperands;
13780
13781 // Put nodes without any operands into SortedNodes first.
13782 for (const SDNode &N : allnodes()) {
13783 checkForCycles(&N, this);
13784 unsigned NumOperands = N.getNumOperands();
13785 if (NumOperands == 0)
13786 SortedNodes.push_back(&N);
13787 else
13788 // Record their total number of outstanding operands.
13789 RemainingOperands[&N] = NumOperands;
13790 }
13791
13792 // A node is pushed into SortedNodes when all of its operands (predecessors in
13793 // the graph) are also in SortedNodes.
13794 for (unsigned i = 0U; i < SortedNodes.size(); ++i) {
13795 const SDNode *N = SortedNodes[i];
13796 for (const SDNode *U : N->users()) {
13797 // HandleSDNode is never part of a DAG and therefore has no entry in
13798 // RemainingOperands.
13799 if (U->getOpcode() == ISD::HANDLENODE)
13800 continue;
13801 unsigned &NumRemOperands = RemainingOperands[U];
13802 assert(NumRemOperands && "Invalid number of remaining operands");
13803 --NumRemOperands;
13804 if (!NumRemOperands)
13805 SortedNodes.push_back(U);
13806 }
13807 }
13808
13809 assert(SortedNodes.size() == AllNodes.size() && "Node count mismatch");
13810 assert(SortedNodes.front()->getOpcode() == ISD::EntryToken &&
13811 "First node in topological sort is not the entry token");
13812 assert(SortedNodes.front()->getNumOperands() == 0 &&
13813 "First node in topological sort has operands");
13814}
13815
13816/// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the
13817/// value is produced by SD.
13818void SelectionDAG::AddDbgValue(SDDbgValue *DB, bool isParameter) {
13819 for (SDNode *SD : DB->getSDNodes()) {
13820 if (!SD)
13821 continue;
13822 assert(DbgInfo->getSDDbgValues(SD).empty() || SD->getHasDebugValue());
13823 SD->setHasDebugValue(true);
13824 }
13825 DbgInfo->add(DB, isParameter);
13826}
13827
13828void SelectionDAG::AddDbgLabel(SDDbgLabel *DB) { DbgInfo->add(DB); }
13829
13831 SDValue NewMemOpChain) {
13832 assert(isa<MemSDNode>(NewMemOpChain) && "Expected a memop node");
13833 assert(NewMemOpChain.getValueType() == MVT::Other && "Expected a token VT");
13834 // The new memory operation must have the same position as the old load in
13835 // terms of memory dependency. Create a TokenFactor for the old load and new
13836 // memory operation and update uses of the old load's output chain to use that
13837 // TokenFactor.
13838 if (OldChain == NewMemOpChain || OldChain.use_empty())
13839 return NewMemOpChain;
13840
13841 SDValue TokenFactor = getNode(ISD::TokenFactor, SDLoc(OldChain), MVT::Other,
13842 OldChain, NewMemOpChain);
13843 ReplaceAllUsesOfValueWith(OldChain, TokenFactor);
13844 UpdateNodeOperands(TokenFactor.getNode(), OldChain, NewMemOpChain);
13845 return TokenFactor;
13846}
13847
13849 SDValue NewMemOp) {
13850 assert(isa<MemSDNode>(NewMemOp.getNode()) && "Expected a memop node");
13851 SDValue OldChain = SDValue(OldLoad, 1);
13852 SDValue NewMemOpChain = NewMemOp.getValue(1);
13853 return makeEquivalentMemoryOrdering(OldChain, NewMemOpChain);
13854}
13855
13857 Function **OutFunction) {
13858 assert(isa<ExternalSymbolSDNode>(Op) && "Node should be an ExternalSymbol");
13859
13860 auto *Symbol = cast<ExternalSymbolSDNode>(Op)->getSymbol();
13861 auto *Module = MF->getFunction().getParent();
13862 auto *Function = Module->getFunction(Symbol);
13863
13864 if (OutFunction != nullptr)
13865 *OutFunction = Function;
13866
13867 if (Function != nullptr) {
13868 auto PtrTy = TLI->getPointerTy(getDataLayout(), Function->getAddressSpace());
13869 return getGlobalAddress(Function, SDLoc(Op), PtrTy);
13870 }
13871
13872 std::string ErrorStr;
13873 raw_string_ostream ErrorFormatter(ErrorStr);
13874 ErrorFormatter << "Undefined external symbol ";
13875 ErrorFormatter << '"' << Symbol << '"';
13876 report_fatal_error(Twine(ErrorStr));
13877}
13878
13879//===----------------------------------------------------------------------===//
13880// SDNode Class
13881//===----------------------------------------------------------------------===//
13882
13885 return Const != nullptr && Const->isZero();
13886}
13887
13889 return V.isUndef() || isNullConstant(V);
13890}
13891
13894 return Const != nullptr && Const->isZero() && !Const->isNegative();
13895}
13896
13899 return Const != nullptr && Const->isAllOnes();
13900}
13901
13904 return Const != nullptr && Const->isOne();
13905}
13906
13909 return Const != nullptr && Const->isMinSignedValue();
13910}
13911
13913 SDValue V, unsigned OperandNo,
13914 unsigned Depth) const {
13915 APInt DemandedElts = getDemandAllEltsMask(V);
13916 return isIdentityElement(Opcode, Flags, V, DemandedElts, OperandNo, Depth);
13917}
13918
13920 SDValue V, const APInt &DemandedElts,
13921 unsigned OperandNo, unsigned Depth) const {
13922 // NOTE: The cases should match with IR's ConstantExpr::getBinOpIdentity().
13923 // TODO: Target-specific opcodes could be added.
13924 if (V.getValueType().isInteger()) {
13925 KnownBits Known = computeKnownBits(V, DemandedElts, Depth);
13926 if (Known.isConstant()) {
13927 const APInt &Const = Known.getConstant();
13928 switch (Opcode) {
13929 case ISD::ADD:
13930 case ISD::OR:
13931 case ISD::XOR:
13932 case ISD::UMAX:
13933 return Const.isZero();
13934 case ISD::MUL:
13935 return Const.isOne();
13936 case ISD::AND:
13937 case ISD::UMIN:
13938 return Const.isAllOnes();
13939 case ISD::SMAX:
13940 return Const.isMinSignedValue();
13941 case ISD::SMIN:
13942 return Const.isMaxSignedValue();
13943 case ISD::SUB:
13944 case ISD::SHL:
13945 case ISD::SRA:
13946 case ISD::SRL:
13947 return OperandNo == 1 && Const.isZero();
13948 case ISD::UDIV:
13949 case ISD::SDIV:
13950 return OperandNo == 1 && Const.isOne();
13951 }
13952 }
13953 } else if (auto *ConstFP = isConstOrConstSplatFP(V, DemandedElts)) {
13954 switch (Opcode) {
13955 case ISD::FADD:
13956 return ConstFP->isZero() &&
13957 (Flags.hasNoSignedZeros() || ConstFP->isNegative());
13958 case ISD::FSUB:
13959 return OperandNo == 1 && ConstFP->isZero() &&
13960 (Flags.hasNoSignedZeros() || !ConstFP->isNegative());
13961 case ISD::FMUL:
13962 return ConstFP->isOne();
13963 case ISD::FDIV:
13964 return OperandNo == 1 && ConstFP->isOne();
13965 case ISD::FMINNUM:
13966 case ISD::FMAXNUM: {
13967 // Neutral element for fminnum is NaN, Inf or FLT_MAX, depending on FMF.
13968 EVT VT = V.getValueType();
13969 const fltSemantics &Semantics = VT.getFltSemantics();
13970 APFloat NeutralAF = !Flags.hasNoNaNs() ? APFloat::getQNaN(Semantics)
13971 : !Flags.hasNoInfs() ? APFloat::getInf(Semantics)
13972 : APFloat::getLargest(Semantics);
13973 if (Opcode == ISD::FMAXNUM)
13974 NeutralAF.changeSign();
13975
13976 return ConstFP->isExactlyValue(NeutralAF);
13977 }
13978 case ISD::FMINIMUM:
13979 case ISD::FMAXIMUM: {
13980 // Neutral element for fminimum is Inf or FLT_MAX, depending on FMF.
13981 const APFloat &VAPF = ConstFP->getValueAPF();
13982 bool NeutralNegative = (Opcode == ISD::FMAXIMUM);
13983 if (Flags.hasNoInfs())
13984 return VAPF.isLargest() && VAPF.isNegative() == NeutralNegative;
13985 return VAPF.isInfinity() && VAPF.isNegative() == NeutralNegative;
13986 }
13987 }
13988 }
13989 return false;
13990}
13991
13993 while (V.getOpcode() == ISD::BITCAST)
13994 V = V.getOperand(0);
13995 return V;
13996}
13997
13999 while (V.getOpcode() == ISD::BITCAST && V.getOperand(0).hasOneUse())
14000 V = V.getOperand(0);
14001 return V;
14002}
14003
14005 while (V.getOpcode() == ISD::EXTRACT_SUBVECTOR)
14006 V = V.getOperand(0);
14007 return V;
14008}
14009
14011 while (V.getOpcode() == ISD::INSERT_VECTOR_ELT) {
14012 SDValue InVec = V.getOperand(0);
14013 SDValue EltNo = V.getOperand(2);
14014 EVT VT = InVec.getValueType();
14015 auto *IndexC = dyn_cast<ConstantSDNode>(EltNo);
14016 if (IndexC && VT.isFixedLengthVector() &&
14017 IndexC->getAPIntValue().ult(VT.getVectorNumElements()) &&
14018 !DemandedElts[IndexC->getZExtValue()]) {
14019 V = InVec;
14020 continue;
14021 }
14022 break;
14023 }
14024 return V;
14025}
14026
14028 while (V.getOpcode() == ISD::TRUNCATE)
14029 V = V.getOperand(0);
14030 return V;
14031}
14032
14033bool llvm::isBitwiseNot(SDValue V, bool AllowUndefs) {
14034 if (V.getOpcode() != ISD::XOR)
14035 return false;
14036 V = peekThroughBitcasts(V.getOperand(1));
14037 unsigned NumBits = V.getScalarValueSizeInBits();
14038 ConstantSDNode *C =
14039 isConstOrConstSplat(V, AllowUndefs, /*AllowTruncation*/ true);
14040 return C && (C->getAPIntValue().countr_one() >= NumBits);
14041}
14042
14044 bool AllowTruncation) {
14045 APInt DemandedElts = getDemandAllEltsMask(N);
14046 return isConstOrConstSplat(N, DemandedElts, AllowUndefs, AllowTruncation);
14047}
14048
14050 bool AllowUndefs,
14051 bool AllowTruncation) {
14053 return CN;
14054
14055 // SplatVectors can truncate their operands. Ignore that case here unless
14056 // AllowTruncation is set.
14057 if (N->getOpcode() == ISD::SPLAT_VECTOR) {
14058 EVT VecEltVT = N->getValueType(0).getVectorElementType();
14059 if (auto *CN = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
14060 EVT CVT = CN->getValueType(0);
14061 assert(CVT.bitsGE(VecEltVT) && "Illegal splat_vector element extension");
14062 if (AllowTruncation || CVT == VecEltVT)
14063 return CN;
14064 }
14065 }
14066
14068 BitVector UndefElements;
14069 ConstantSDNode *CN = BV->getConstantSplatNode(DemandedElts, &UndefElements);
14070
14071 // BuildVectors can truncate their operands. Ignore that case here unless
14072 // AllowTruncation is set.
14073 // TODO: Look into whether we should allow UndefElements in non-DemandedElts
14074 if (CN && (UndefElements.none() || AllowUndefs)) {
14075 EVT CVT = CN->getValueType(0);
14076 EVT NSVT = N.getValueType().getScalarType();
14077 assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension");
14078 if (AllowTruncation || (CVT == NSVT))
14079 return CN;
14080 }
14081 }
14082
14083 return nullptr;
14084}
14085
14087 APInt DemandedElts = getDemandAllEltsMask(N);
14088 return isConstOrConstSplatFP(N, DemandedElts, AllowUndefs);
14089}
14090
14092 const APInt &DemandedElts,
14093 bool AllowUndefs) {
14095 return CN;
14096
14098 BitVector UndefElements;
14099 ConstantFPSDNode *CN =
14100 BV->getConstantFPSplatNode(DemandedElts, &UndefElements);
14101 // TODO: Look into whether we should allow UndefElements in non-DemandedElts
14102 if (CN && (UndefElements.none() || AllowUndefs))
14103 return CN;
14104 }
14105
14106 if (N.getOpcode() == ISD::SPLAT_VECTOR)
14107 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N.getOperand(0)))
14108 return CN;
14109
14110 return nullptr;
14111}
14112
14113bool llvm::isNullOrNullSplat(SDValue N, bool AllowUndefs) {
14114 // TODO: may want to use peekThroughBitcast() here.
14115 ConstantSDNode *C =
14116 isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation=*/true);
14117 return C && C->isZero();
14118}
14119
14120bool llvm::isOneOrOneSplat(SDValue N, bool AllowUndefs) {
14121 ConstantSDNode *C =
14122 isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation*/ true);
14123 return C && C->isOne();
14124}
14125
14126bool llvm::isOneOrOneSplatFP(SDValue N, bool AllowUndefs) {
14127 ConstantFPSDNode *C = isConstOrConstSplatFP(N, AllowUndefs);
14128 return C && C->isOne();
14129}
14130
14131bool llvm::isAllOnesOrAllOnesSplat(SDValue N, bool AllowUndefs) {
14133 unsigned BitWidth = N.getScalarValueSizeInBits();
14134 ConstantSDNode *C =
14135 isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation=*/true);
14136 return C && C->getAPIntValue().countTrailingOnes() >= BitWidth;
14137}
14138
14139bool llvm::isOnesOrOnesSplat(SDValue N, bool AllowUndefs) {
14140 ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs);
14141 return C && APInt::isSameValue(C->getAPIntValue(),
14142 APInt(C->getAPIntValue().getBitWidth(), 1));
14143}
14144
14145bool llvm::isZeroOrZeroSplat(SDValue N, bool AllowUndefs) {
14147 ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs, true);
14148 return C && C->isZero();
14149}
14150
14151bool llvm::isZeroOrZeroSplatFP(SDValue N, bool AllowUndefs) {
14152 ConstantFPSDNode *C = isConstOrConstSplatFP(N, AllowUndefs);
14153 return C && C->isZero();
14154}
14155
14159
14161 unsigned Opc, unsigned Order, const DebugLoc &dl, SDVTList VTs, EVT memvt,
14163 : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MemRefs(memrefs) {
14164 bool IsVolatile = false;
14165 bool IsNonTemporal = false;
14166 bool IsDereferenceable = true;
14167 bool IsInvariant = true;
14168 for (const MachineMemOperand *MMO : memoperands()) {
14169 IsVolatile |= MMO->isVolatile();
14170 IsNonTemporal |= MMO->isNonTemporal();
14171 IsDereferenceable &= MMO->isDereferenceable();
14172 IsInvariant &= MMO->isInvariant();
14173 }
14174 MemSDNodeBits.IsVolatile = IsVolatile;
14175 MemSDNodeBits.IsNonTemporal = IsNonTemporal;
14176 MemSDNodeBits.IsDereferenceable = IsDereferenceable;
14177 MemSDNodeBits.IsInvariant = IsInvariant;
14178
14179 // For the single-MMO case, we check here that the size of the memory operand
14180 // fits within the size of the MMO. This is because the MMO might indicate
14181 // only a possible address range instead of specifying the affected memory
14182 // addresses precisely.
14185 getMemOperand()->getSize().getValue())) &&
14186 "Size mismatch!");
14187}
14188
14189/// Profile - Gather unique data for the node.
14190///
14192 AddNodeIDNode(ID, this);
14193}
14194
14195namespace {
14196
14197 struct EVTArray {
14198 std::vector<EVT> VTs;
14199
14200 EVTArray() {
14201 VTs.reserve(MVT::VALUETYPE_SIZE);
14202 for (unsigned i = 0; i < MVT::VALUETYPE_SIZE; ++i)
14203 VTs.push_back(MVT((MVT::SimpleValueType)i));
14204 }
14205 };
14206
14207} // end anonymous namespace
14208
14209/// getValueTypeList - Return a pointer to the specified value type.
14210///
14211const EVT *SDNode::getValueTypeList(MVT VT) {
14212 static EVTArray SimpleVTArray;
14213
14214 assert(VT < MVT::VALUETYPE_SIZE && "Value type out of range!");
14215 return &SimpleVTArray.VTs[VT.SimpleTy];
14216}
14217
14218/// hasAnyUseOfValue - Return true if there are any use of the indicated
14219/// value. This method ignores uses of other values defined by this operation.
14220bool SDNode::hasAnyUseOfValue(unsigned Value) const {
14221 assert(Value < getNumValues() && "Bad value!");
14222
14223 for (SDUse &U : uses())
14224 if (U.getResNo() == Value)
14225 return true;
14226
14227 return false;
14228}
14229
14230/// isOnlyUserOf - Return true if this node is the only use of N.
14231bool SDNode::isOnlyUserOf(const SDNode *N) const {
14232 bool Seen = false;
14233 for (const SDNode *User : N->users()) {
14234 if (User == this)
14235 Seen = true;
14236 else
14237 return false;
14238 }
14239
14240 return Seen;
14241}
14242
14243/// Return true if the only users of N are contained in Nodes.
14245 bool Seen = false;
14246 for (const SDNode *User : N->users()) {
14247 if (llvm::is_contained(Nodes, User))
14248 Seen = true;
14249 else
14250 return false;
14251 }
14252
14253 return Seen;
14254}
14255
14256/// Return true if the referenced return value is an operand of N.
14257bool SDValue::isOperandOf(const SDNode *N) const {
14258 return is_contained(N->op_values(), *this);
14259}
14260
14261bool SDNode::isOperandOf(const SDNode *N) const {
14262 return any_of(N->op_values(),
14263 [this](SDValue Op) { return this == Op.getNode(); });
14264}
14265
14266/// reachesChainWithoutSideEffects - Return true if this operand (which must
14267/// be a chain) reaches the specified operand without crossing any
14268/// side-effecting instructions on any chain path. In practice, this looks
14269/// through token factors and non-volatile loads. In order to remain efficient,
14270/// this only looks a couple of nodes in, it does not do an exhaustive search.
14271///
14272/// Note that we only need to examine chains when we're searching for
14273/// side-effects; SelectionDAG requires that all side-effects are represented
14274/// by chains, even if another operand would force a specific ordering. This
14275/// constraint is necessary to allow transformations like splitting loads.
14277 unsigned Depth) const {
14278 if (*this == Dest) return true;
14279
14280 // Don't search too deeply, we just want to be able to see through
14281 // TokenFactor's etc.
14282 if (Depth == 0) return false;
14283
14284 // If this is a token factor, all inputs to the TF happen in parallel.
14285 if (getOpcode() == ISD::TokenFactor) {
14286 // First, try a shallow search.
14287 if (is_contained((*this)->ops(), Dest)) {
14288 // We found the chain we want as an operand of this TokenFactor.
14289 // Essentially, we reach the chain without side-effects if we could
14290 // serialize the TokenFactor into a simple chain of operations with
14291 // Dest as the last operation. This is automatically true if the
14292 // chain has one use: there are no other ordering constraints.
14293 // If the chain has more than one use, we give up: some other
14294 // use of Dest might force a side-effect between Dest and the current
14295 // node.
14296 if (Dest.hasOneUse())
14297 return true;
14298 }
14299 // Next, try a deep search: check whether every operand of the TokenFactor
14300 // reaches Dest.
14301 return llvm::all_of((*this)->ops(), [=](SDValue Op) {
14302 return Op.reachesChainWithoutSideEffects(Dest, Depth - 1);
14303 });
14304 }
14305
14306 // Loads don't have side effects, look through them.
14307 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
14308 if (Ld->isUnordered())
14309 return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
14310 }
14311 return false;
14312}
14313
14314bool SDNode::hasPredecessor(const SDNode *N) const {
14317 Worklist.push_back(this);
14318 return hasPredecessorHelper(N, Visited, Worklist);
14319}
14320
14322 this->Flags &= Flags;
14323}
14324
14325SDValue
14327 ArrayRef<ISD::NodeType> CandidateBinOps,
14328 bool AllowPartials) {
14329 // The pattern must end in an extract from index 0.
14330 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
14331 !isNullConstant(Extract->getOperand(1)))
14332 return SDValue();
14333
14334 // Match against one of the candidate binary ops.
14335 SDValue Op = Extract->getOperand(0);
14336 if (llvm::none_of(CandidateBinOps, [Op](ISD::NodeType BinOp) {
14337 return Op.getOpcode() == unsigned(BinOp);
14338 }))
14339 return SDValue();
14340
14341 // Floating-point reductions may require relaxed constraints on the final step
14342 // of the reduction because they may reorder intermediate operations.
14343 unsigned CandidateBinOp = Op.getOpcode();
14344 if (Op.getValueType().isFloatingPoint()) {
14345 SDNodeFlags Flags = Op->getFlags();
14346 switch (CandidateBinOp) {
14347 case ISD::FADD:
14348 if (!Flags.hasNoSignedZeros() || !Flags.hasAllowReassociation())
14349 return SDValue();
14350 break;
14351 default:
14352 llvm_unreachable("Unhandled FP opcode for binop reduction");
14353 }
14354 }
14355
14356 // Matching failed - attempt to see if we did enough stages that a partial
14357 // reduction from a subvector is possible.
14358 auto PartialReduction = [&](SDValue Op, unsigned NumSubElts) {
14359 if (!AllowPartials || !Op)
14360 return SDValue();
14361 EVT OpVT = Op.getValueType();
14362 EVT OpSVT = OpVT.getScalarType();
14363 EVT SubVT = EVT::getVectorVT(*getContext(), OpSVT, NumSubElts);
14364 if (TLI->getExtractSubvectorCost(SubVT, OpVT, 0) >
14366 return SDValue();
14367 BinOp = (ISD::NodeType)CandidateBinOp;
14368 return getExtractSubvector(SDLoc(Op), SubVT, Op, 0);
14369 };
14370
14371 // At each stage, we're looking for something that looks like:
14372 // %s = shufflevector <8 x i32> %op, <8 x i32> undef,
14373 // <8 x i32> <i32 2, i32 3, i32 undef, i32 undef,
14374 // i32 undef, i32 undef, i32 undef, i32 undef>
14375 // %a = binop <8 x i32> %op, %s
14376 // Where the mask changes according to the stage. E.g. for a 3-stage pyramid,
14377 // we expect something like:
14378 // <4,5,6,7,u,u,u,u>
14379 // <2,3,u,u,u,u,u,u>
14380 // <1,u,u,u,u,u,u,u>
14381 // While a partial reduction match would be:
14382 // <2,3,u,u,u,u,u,u>
14383 // <1,u,u,u,u,u,u,u>
14384 unsigned Stages = Log2_32(Op.getValueType().getVectorNumElements());
14385 SDValue PrevOp;
14386 for (unsigned i = 0; i < Stages; ++i) {
14387 unsigned MaskEnd = (1 << i);
14388
14389 if (Op.getOpcode() != CandidateBinOp)
14390 return PartialReduction(PrevOp, MaskEnd);
14391
14392 SDValue Op0 = Op.getOperand(0);
14393 SDValue Op1 = Op.getOperand(1);
14394
14396 if (Shuffle) {
14397 Op = Op1;
14398 } else {
14399 Shuffle = dyn_cast<ShuffleVectorSDNode>(Op1);
14400 Op = Op0;
14401 }
14402
14403 // The first operand of the shuffle should be the same as the other operand
14404 // of the binop.
14405 if (!Shuffle || Shuffle->getOperand(0) != Op)
14406 return PartialReduction(PrevOp, MaskEnd);
14407
14408 // Verify the shuffle has the expected (at this stage of the pyramid) mask.
14409 for (int Index = 0; Index < (int)MaskEnd; ++Index)
14410 if (Shuffle->getMaskElt(Index) != (int)(MaskEnd + Index))
14411 return PartialReduction(PrevOp, MaskEnd);
14412
14413 PrevOp = Op;
14414 }
14415
14416 // Handle subvector reductions, which tend to appear after the shuffle
14417 // reduction stages.
14418 while (Op.getOpcode() == CandidateBinOp) {
14419 unsigned NumElts = Op.getValueType().getVectorNumElements();
14420 SDValue Op0 = Op.getOperand(0);
14421 SDValue Op1 = Op.getOperand(1);
14422 if (Op0.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
14424 Op0.getOperand(0) != Op1.getOperand(0))
14425 break;
14426 SDValue Src = Op0.getOperand(0);
14427 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
14428 if (NumSrcElts != (2 * NumElts))
14429 break;
14430 if (!(Op0.getConstantOperandAPInt(1) == 0 &&
14431 Op1.getConstantOperandAPInt(1) == NumElts) &&
14432 !(Op1.getConstantOperandAPInt(1) == 0 &&
14433 Op0.getConstantOperandAPInt(1) == NumElts))
14434 break;
14435 Op = Src;
14436 }
14437
14438 BinOp = (ISD::NodeType)CandidateBinOp;
14439 return Op;
14440}
14441
14443 EVT VT = N->getValueType(0);
14444 EVT EltVT = VT.getVectorElementType();
14445 unsigned NE = VT.getVectorNumElements();
14446
14447 SDLoc dl(N);
14448
14449 // If ResNE is 0, fully unroll the vector op.
14450 if (ResNE == 0)
14451 ResNE = NE;
14452 else if (NE > ResNE)
14453 NE = ResNE;
14454
14455 if (N->getNumValues() == 2) {
14456 SmallVector<SDValue, 8> Scalars0, Scalars1;
14457 SmallVector<SDValue, 4> Operands(N->getNumOperands());
14458 EVT VT1 = N->getValueType(1);
14459 EVT EltVT1 = VT1.getVectorElementType();
14460
14461 unsigned i;
14462 for (i = 0; i != NE; ++i) {
14463 for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) {
14464 SDValue Operand = N->getOperand(j);
14465 EVT OperandVT = Operand.getValueType();
14466
14467 // A vector operand; extract a single element.
14468 EVT OperandEltVT = OperandVT.getVectorElementType();
14469 Operands[j] = getExtractVectorElt(dl, OperandEltVT, Operand, i);
14470 }
14471
14472 SDValue EltOp = getNode(N->getOpcode(), dl, {EltVT, EltVT1}, Operands);
14473 Scalars0.push_back(EltOp);
14474 Scalars1.push_back(EltOp.getValue(1));
14475 }
14476
14477 for (; i < ResNE; ++i) {
14478 Scalars0.push_back(getUNDEF(EltVT));
14479 Scalars1.push_back(getUNDEF(EltVT1));
14480 }
14481
14482 EVT VecVT = EVT::getVectorVT(*getContext(), EltVT, ResNE);
14483 EVT VecVT1 = EVT::getVectorVT(*getContext(), EltVT1, ResNE);
14484 SDValue Vec0 = getBuildVector(VecVT, dl, Scalars0);
14485 SDValue Vec1 = getBuildVector(VecVT1, dl, Scalars1);
14486 return getMergeValues({Vec0, Vec1}, dl);
14487 }
14488
14489 assert(N->getNumValues() == 1 &&
14490 "Can't unroll a vector with multiple results!");
14491
14493 SmallVector<SDValue, 4> Operands(N->getNumOperands());
14494
14495 unsigned i;
14496 for (i= 0; i != NE; ++i) {
14497 for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) {
14498 SDValue Operand = N->getOperand(j);
14499 EVT OperandVT = Operand.getValueType();
14500 if (OperandVT.isVector()) {
14501 // A vector operand; extract a single element.
14502 EVT OperandEltVT = OperandVT.getVectorElementType();
14503 Operands[j] = getExtractVectorElt(dl, OperandEltVT, Operand, i);
14504 } else {
14505 // A scalar operand; just use it as is.
14506 Operands[j] = Operand;
14507 }
14508 }
14509
14510 switch (N->getOpcode()) {
14511 default: {
14512 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands,
14513 N->getFlags()));
14514 break;
14515 }
14516 case ISD::VSELECT:
14517 Scalars.push_back(
14518 getNode(ISD::SELECT, dl, EltVT, Operands, N->getFlags()));
14519 break;
14520 case ISD::SHL:
14521 case ISD::SRA:
14522 case ISD::SRL:
14523 case ISD::ROTL:
14524 case ISD::ROTR:
14525 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0],
14527 Operands[1])));
14528 break;
14530 EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType();
14531 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT,
14532 Operands[0],
14533 getValueType(ExtVT)));
14534 break;
14535 }
14536 case ISD::ADDRSPACECAST: {
14537 const auto *ASC = cast<AddrSpaceCastSDNode>(N);
14538 Scalars.push_back(getAddrSpaceCast(dl, EltVT, Operands[0],
14539 ASC->getSrcAddressSpace(),
14540 ASC->getDestAddressSpace()));
14541 break;
14542 }
14543 }
14544 }
14545
14546 for (; i < ResNE; ++i)
14547 Scalars.push_back(getUNDEF(EltVT));
14548
14549 EVT VecVT = EVT::getVectorVT(*getContext(), EltVT, ResNE);
14550 return getBuildVector(VecVT, dl, Scalars);
14551}
14552
14553std::pair<SDValue, SDValue> SelectionDAG::UnrollVectorOverflowOp(
14554 SDNode *N, unsigned ResNE) {
14555 unsigned Opcode = N->getOpcode();
14556 assert((Opcode == ISD::UADDO || Opcode == ISD::SADDO ||
14557 Opcode == ISD::USUBO || Opcode == ISD::SSUBO ||
14558 Opcode == ISD::UMULO || Opcode == ISD::SMULO) &&
14559 "Expected an overflow opcode");
14560
14561 EVT ResVT = N->getValueType(0);
14562 EVT OvVT = N->getValueType(1);
14563 EVT ResEltVT = ResVT.getVectorElementType();
14564 EVT OvEltVT = OvVT.getVectorElementType();
14565 SDLoc dl(N);
14566
14567 // If ResNE is 0, fully unroll the vector op.
14568 unsigned NE = ResVT.getVectorNumElements();
14569 if (ResNE == 0)
14570 ResNE = NE;
14571 else if (NE > ResNE)
14572 NE = ResNE;
14573
14574 SmallVector<SDValue, 8> LHSScalars;
14575 SmallVector<SDValue, 8> RHSScalars;
14576 ExtractVectorElements(N->getOperand(0), LHSScalars, 0, NE);
14577 ExtractVectorElements(N->getOperand(1), RHSScalars, 0, NE);
14578
14579 EVT SVT = TLI->getSetCCResultType(getDataLayout(), *getContext(), ResEltVT);
14580 SDVTList VTs = getVTList(ResEltVT, SVT);
14581 SmallVector<SDValue, 8> ResScalars;
14582 SmallVector<SDValue, 8> OvScalars;
14583 for (unsigned i = 0; i < NE; ++i) {
14584 SDValue Res = getNode(Opcode, dl, VTs, LHSScalars[i], RHSScalars[i]);
14585 SDValue Ov =
14586 getSelect(dl, OvEltVT, Res.getValue(1),
14587 getBoolConstant(true, dl, OvEltVT, ResVT),
14588 getConstant(0, dl, OvEltVT));
14589
14590 ResScalars.push_back(Res);
14591 OvScalars.push_back(Ov);
14592 }
14593
14594 ResScalars.append(ResNE - NE, getUNDEF(ResEltVT));
14595 OvScalars.append(ResNE - NE, getUNDEF(OvEltVT));
14596
14597 EVT NewResVT = EVT::getVectorVT(*getContext(), ResEltVT, ResNE);
14598 EVT NewOvVT = EVT::getVectorVT(*getContext(), OvEltVT, ResNE);
14599 return std::make_pair(getBuildVector(NewResVT, dl, ResScalars),
14600 getBuildVector(NewOvVT, dl, OvScalars));
14601}
14602
14605 unsigned Bytes,
14606 int Dist) const {
14607 if (LD->isVolatile() || Base->isVolatile())
14608 return false;
14609 // TODO: probably too restrictive for atomics, revisit
14610 if (!LD->isSimple())
14611 return false;
14612 if (LD->isIndexed() || Base->isIndexed())
14613 return false;
14614 if (LD->getChain() != Base->getChain())
14615 return false;
14616 EVT VT = LD->getMemoryVT();
14617 if (VT.getSizeInBits() / 8 != Bytes)
14618 return false;
14619
14620 auto BaseLocDecomp = BaseIndexOffset::match(Base, *this);
14621 auto LocDecomp = BaseIndexOffset::match(LD, *this);
14622
14623 int64_t Offset = 0;
14624 if (BaseLocDecomp.equalBaseIndex(LocDecomp, *this, Offset))
14625 return (Dist * (int64_t)Bytes == Offset);
14626 return false;
14627}
14628
14629/// InferPtrAlignment - Infer alignment of a load / store address. Return
14630/// std::nullopt if it cannot be inferred.
14632 // If this is a GlobalAddress + cst, return the alignment.
14633 const GlobalValue *GV = nullptr;
14634 int64_t GVOffset = 0;
14635 if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) {
14636 unsigned PtrWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
14637 KnownBits Known(PtrWidth);
14639 unsigned AlignBits = Known.countMinTrailingZeros();
14640 if (AlignBits)
14641 return commonAlignment(Align(1ull << std::min(31U, AlignBits)), GVOffset);
14642 }
14643
14644 // If this is a direct reference to a stack slot, use information about the
14645 // stack slot's alignment.
14646 int FrameIdx = INT_MIN;
14647 int64_t FrameOffset = 0;
14649 FrameIdx = FI->getIndex();
14650 } else if (isBaseWithConstantOffset(Ptr) &&
14652 // Handle FI+Cst
14653 FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
14654 FrameOffset = Ptr.getConstantOperandVal(1);
14655 }
14656
14657 if (FrameIdx != INT_MIN) {
14659 return commonAlignment(MFI.getObjectAlign(FrameIdx), FrameOffset);
14660 }
14661
14662 return std::nullopt;
14663}
14664
14665/// Split the scalar node with EXTRACT_ELEMENT using the provided
14666/// VTs and return the low/high part.
14667std::pair<SDValue, SDValue> SelectionDAG::SplitScalar(const SDValue &N,
14668 const SDLoc &DL,
14669 const EVT &LoVT,
14670 const EVT &HiVT) {
14671 assert(!LoVT.isVector() && !HiVT.isVector() && !N.getValueType().isVector() &&
14672 "Split node must be a scalar type");
14673 SDValue Lo =
14675 SDValue Hi =
14677 return std::make_pair(Lo, Hi);
14678}
14679
14680/// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type
14681/// which is split (or expanded) into two not necessarily identical pieces.
14682std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const {
14683 // Currently all types are split in half.
14684 EVT LoVT, HiVT;
14685 if (!VT.isVector())
14686 LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT);
14687 else
14688 LoVT = HiVT = VT.getHalfNumVectorElementsVT(*getContext());
14689
14690 return std::make_pair(LoVT, HiVT);
14691}
14692
14693/// GetDependentSplitDestVTs - Compute the VTs needed for the low/hi parts of a
14694/// type, dependent on an enveloping VT that has been split into two identical
14695/// pieces. Sets the HiIsEmpty flag when hi type has zero storage size.
14696std::pair<EVT, EVT>
14698 bool *HiIsEmpty) const {
14699 EVT EltTp = VT.getVectorElementType();
14700 // Examples:
14701 // custom VL=8 with enveloping VL=8/8 yields 8/0 (hi empty)
14702 // custom VL=9 with enveloping VL=8/8 yields 8/1
14703 // custom VL=10 with enveloping VL=8/8 yields 8/2
14704 // etc.
14705 ElementCount VTNumElts = VT.getVectorElementCount();
14706 ElementCount EnvNumElts = EnvVT.getVectorElementCount();
14707 assert(VTNumElts.isScalable() == EnvNumElts.isScalable() &&
14708 "Mixing fixed width and scalable vectors when enveloping a type");
14709 EVT LoVT, HiVT;
14710 if (VTNumElts.getKnownMinValue() > EnvNumElts.getKnownMinValue()) {
14711 LoVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts);
14712 HiVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts - EnvNumElts);
14713 *HiIsEmpty = false;
14714 } else {
14715 // Flag that hi type has zero storage size, but return split envelop type
14716 // (this would be easier if vector types with zero elements were allowed).
14717 LoVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts);
14718 HiVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts);
14719 *HiIsEmpty = true;
14720 }
14721 return std::make_pair(LoVT, HiVT);
14722}
14723
14724/// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the
14725/// low/high part.
14726std::pair<SDValue, SDValue>
14727SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT,
14728 const EVT &HiVT) {
14729 assert(LoVT.isScalableVector() == HiVT.isScalableVector() &&
14730 LoVT.isScalableVector() == N.getValueType().isScalableVector() &&
14731 "Splitting vector with an invalid mixture of fixed and scalable "
14732 "vector types");
14734 N.getValueType().getVectorMinNumElements() &&
14735 "More vector elements requested than available!");
14736 SDValue Lo, Hi;
14737 Lo = getExtractSubvector(DL, LoVT, N, 0);
14738 // For scalable vectors it is safe to use LoVT.getVectorMinNumElements()
14739 // (rather than having to use ElementCount), because EXTRACT_SUBVECTOR scales
14740 // IDX with the runtime scaling factor of the result vector type. For
14741 // fixed-width result vectors, that runtime scaling factor is 1.
14743 return std::make_pair(Lo, Hi);
14744}
14745
14746std::pair<SDValue, SDValue> SelectionDAG::SplitEVL(SDValue N, EVT VecVT,
14747 const SDLoc &DL) {
14748 // Split the vector length parameter.
14749 // %evl -> umin(%evl, %halfnumelts) and usubsat(%evl - %halfnumelts).
14750 EVT VT = N.getValueType();
14752 "Expecting the mask to be an evenly-sized vector");
14753 SDValue HalfNumElts = getElementCount(
14755 SDValue Lo = getNode(ISD::UMIN, DL, VT, N, HalfNumElts);
14756 SDValue Hi = getNode(ISD::USUBSAT, DL, VT, N, HalfNumElts);
14757 return std::make_pair(Lo, Hi);
14758}
14759
14760/// Widen the vector up to the next power of two using INSERT_SUBVECTOR.
14762 EVT VT = N.getValueType();
14765 return getInsertSubvector(DL, getPOISON(WideVT), N, 0);
14766}
14767
14770 unsigned Start, unsigned Count,
14771 EVT EltVT) {
14772 EVT VT = Op.getValueType();
14773 if (Count == 0)
14775 if (EltVT == EVT())
14776 EltVT = VT.getVectorElementType();
14777 SDLoc SL(Op);
14778 for (unsigned i = Start, e = Start + Count; i != e; ++i) {
14779 Args.push_back(getExtractVectorElt(SL, EltVT, Op, i));
14780 }
14781}
14782
14783// getAddressSpace - Return the address space this GlobalAddress belongs to.
14785 return getGlobal()->getType()->getAddressSpace();
14786}
14787
14790 return Val.MachineCPVal->getType();
14791 return Val.ConstVal->getType();
14792}
14793
14794bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue, APInt &SplatUndef,
14795 unsigned &SplatBitSize,
14796 bool &HasAnyUndefs,
14797 unsigned MinSplatBits,
14798 bool IsBigEndian) const {
14799 EVT VT = getValueType(0);
14800 assert(VT.isVector() && "Expected a vector type");
14801 unsigned VecWidth = VT.getSizeInBits();
14802 if (MinSplatBits > VecWidth)
14803 return false;
14804
14805 // FIXME: The widths are based on this node's type, but build vectors can
14806 // truncate their operands.
14807 SplatValue = APInt(VecWidth, 0);
14808 SplatUndef = APInt(VecWidth, 0);
14809
14810 // Get the bits. Bits with undefined values (when the corresponding element
14811 // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared
14812 // in SplatValue. If any of the values are not constant, give up and return
14813 // false.
14814 unsigned int NumOps = getNumOperands();
14815 assert(NumOps > 0 && "isConstantSplat has 0-size build vector");
14816 unsigned EltWidth = VT.getScalarSizeInBits();
14817
14818 for (unsigned j = 0; j < NumOps; ++j) {
14819 unsigned i = IsBigEndian ? NumOps - 1 - j : j;
14820 SDValue OpVal = getOperand(i);
14821 unsigned BitPos = j * EltWidth;
14822
14823 if (OpVal.isUndef())
14824 SplatUndef.setBits(BitPos, BitPos + EltWidth);
14825 else if (auto *CN = dyn_cast<ConstantSDNode>(OpVal))
14826 SplatValue.insertBits(CN->getAPIntValue().zextOrTrunc(EltWidth), BitPos);
14827 else if (auto *CN = dyn_cast<ConstantFPSDNode>(OpVal))
14828 SplatValue.insertBits(CN->getValueAPF().bitcastToAPInt(), BitPos);
14829 else
14830 return false;
14831 }
14832
14833 // The build_vector is all constants or undefs. Find the smallest element
14834 // size that splats the vector.
14835 HasAnyUndefs = (SplatUndef != 0);
14836
14837 // FIXME: This does not work for vectors with elements less than 8 bits.
14838 while (VecWidth > 8) {
14839 // If we can't split in half, stop here.
14840 if (VecWidth & 1)
14841 break;
14842
14843 unsigned HalfSize = VecWidth / 2;
14844 APInt HighValue = SplatValue.extractBits(HalfSize, HalfSize);
14845 APInt LowValue = SplatValue.extractBits(HalfSize, 0);
14846 APInt HighUndef = SplatUndef.extractBits(HalfSize, HalfSize);
14847 APInt LowUndef = SplatUndef.extractBits(HalfSize, 0);
14848
14849 // If the two halves do not match (ignoring undef bits), stop here.
14850 if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) ||
14851 MinSplatBits > HalfSize)
14852 break;
14853
14854 SplatValue = HighValue | LowValue;
14855 SplatUndef = HighUndef & LowUndef;
14856
14857 VecWidth = HalfSize;
14858 }
14859
14860 // FIXME: The loop above only tries to split in halves. But if the input
14861 // vector for example is <3 x i16> it wouldn't be able to detect a
14862 // SplatBitSize of 16. No idea if that is a design flaw currently limiting
14863 // optimizations. I guess that back in the days when this helper was created
14864 // vectors normally was power-of-2 sized.
14865
14866 SplatBitSize = VecWidth;
14867 return true;
14868}
14869
14871 BitVector *UndefElements) const {
14872 unsigned NumOps = getNumOperands();
14873 if (UndefElements) {
14874 UndefElements->clear();
14875 UndefElements->resize(NumOps);
14876 }
14877 assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size");
14878 if (!DemandedElts)
14879 return SDValue();
14880 SDValue Splatted;
14881 for (unsigned i = 0; i != NumOps; ++i) {
14882 if (!DemandedElts[i])
14883 continue;
14884 SDValue Op = getOperand(i);
14885 if (Op.isUndef()) {
14886 if (UndefElements)
14887 (*UndefElements)[i] = true;
14888 } else if (!Splatted) {
14889 Splatted = Op;
14890 } else if (Splatted != Op) {
14891 return SDValue();
14892 }
14893 }
14894
14895 if (!Splatted) {
14896 unsigned FirstDemandedIdx = DemandedElts.countr_zero();
14897 assert(getOperand(FirstDemandedIdx).isUndef() &&
14898 "Can only have a splat without a constant for all undefs.");
14899 return getOperand(FirstDemandedIdx);
14900 }
14901
14902 return Splatted;
14903}
14904
14906 APInt DemandedElts = APInt::getAllOnes(getNumOperands());
14907 return getSplatValue(DemandedElts, UndefElements);
14908}
14909
14911 SmallVectorImpl<SDValue> &Sequence,
14912 BitVector *UndefElements) const {
14913 unsigned NumOps = getNumOperands();
14914 Sequence.clear();
14915 if (UndefElements) {
14916 UndefElements->clear();
14917 UndefElements->resize(NumOps);
14918 }
14919 assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size");
14920 if (!DemandedElts || NumOps < 2 || !isPowerOf2_32(NumOps))
14921 return false;
14922
14923 // Set the undefs even if we don't find a sequence (like getSplatValue).
14924 if (UndefElements)
14925 for (unsigned I = 0; I != NumOps; ++I)
14926 if (DemandedElts[I] && getOperand(I).isUndef())
14927 (*UndefElements)[I] = true;
14928
14929 // Iteratively widen the sequence length looking for repetitions.
14930 for (unsigned SeqLen = 1; SeqLen < NumOps; SeqLen *= 2) {
14931 Sequence.append(SeqLen, SDValue());
14932 for (unsigned I = 0; I != NumOps; ++I) {
14933 if (!DemandedElts[I])
14934 continue;
14935 SDValue &SeqOp = Sequence[I % SeqLen];
14937 if (Op.isUndef()) {
14938 if (!SeqOp)
14939 SeqOp = Op;
14940 continue;
14941 }
14942 if (SeqOp && !SeqOp.isUndef() && SeqOp != Op) {
14943 Sequence.clear();
14944 break;
14945 }
14946 SeqOp = Op;
14947 }
14948 if (!Sequence.empty())
14949 return true;
14950 }
14951
14952 assert(Sequence.empty() && "Failed to empty non-repeating sequence pattern");
14953 return false;
14954}
14955
14957 BitVector *UndefElements) const {
14958 APInt DemandedElts = APInt::getAllOnes(getNumOperands());
14959 return getRepeatedSequence(DemandedElts, Sequence, UndefElements);
14960}
14961
14964 BitVector *UndefElements) const {
14966 getSplatValue(DemandedElts, UndefElements));
14967}
14968
14971 return dyn_cast_or_null<ConstantSDNode>(getSplatValue(UndefElements));
14972}
14973
14976 BitVector *UndefElements) const {
14978 getSplatValue(DemandedElts, UndefElements));
14979}
14980
14985
14986int32_t
14988 uint32_t BitWidth) const {
14989 if (ConstantFPSDNode *CN =
14991 bool IsExact;
14992 APSInt IntVal(BitWidth);
14993 const APFloat &APF = CN->getValueAPF();
14994 if (APF.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) !=
14995 APFloat::opOK ||
14996 !IsExact)
14997 return -1;
14998
14999 return IntVal.exactLogBase2();
15000 }
15001 return -1;
15002}
15003
15005 bool IsLittleEndian, unsigned DstEltSizeInBits,
15006 SmallVectorImpl<APInt> &RawBitElements, BitVector &UndefElements) const {
15007 // Early-out if this contains anything but Undef/Constant/ConstantFP.
15008 if (!isConstant())
15009 return false;
15010
15011 unsigned NumSrcOps = getNumOperands();
15012 unsigned SrcEltSizeInBits = getValueType(0).getScalarSizeInBits();
15013 assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 &&
15014 "Invalid bitcast scale");
15015
15016 // Extract raw src bits.
15017 SmallVector<APInt> SrcBitElements(NumSrcOps,
15018 APInt::getZero(SrcEltSizeInBits));
15019 BitVector SrcUndeElements(NumSrcOps, false);
15020
15021 for (unsigned I = 0; I != NumSrcOps; ++I) {
15023 if (Op.isUndef()) {
15024 SrcUndeElements.set(I);
15025 continue;
15026 }
15027 auto *CInt = dyn_cast<ConstantSDNode>(Op);
15028 auto *CFP = dyn_cast<ConstantFPSDNode>(Op);
15029 assert((CInt || CFP) && "Unknown constant");
15030 SrcBitElements[I] = CInt ? CInt->getAPIntValue().trunc(SrcEltSizeInBits)
15031 : CFP->getValueAPF().bitcastToAPInt();
15032 }
15033
15034 // Recast to dst width.
15035 recastRawBits(IsLittleEndian, DstEltSizeInBits, RawBitElements,
15036 SrcBitElements, UndefElements, SrcUndeElements);
15037 return true;
15038}
15039
15040void BuildVectorSDNode::recastRawBits(bool IsLittleEndian,
15041 unsigned DstEltSizeInBits,
15042 SmallVectorImpl<APInt> &DstBitElements,
15043 ArrayRef<APInt> SrcBitElements,
15044 BitVector &DstUndefElements,
15045 const BitVector &SrcUndefElements) {
15046 unsigned NumSrcOps = SrcBitElements.size();
15047 unsigned SrcEltSizeInBits = SrcBitElements[0].getBitWidth();
15048 assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 &&
15049 "Invalid bitcast scale");
15050 assert(NumSrcOps == SrcUndefElements.size() &&
15051 "Vector size mismatch");
15052
15053 unsigned NumDstOps = (NumSrcOps * SrcEltSizeInBits) / DstEltSizeInBits;
15054 DstUndefElements.clear();
15055 DstUndefElements.resize(NumDstOps, false);
15056 DstBitElements.assign(NumDstOps, APInt::getZero(DstEltSizeInBits));
15057
15058 // Concatenate src elements constant bits together into dst element.
15059 if (SrcEltSizeInBits <= DstEltSizeInBits) {
15060 unsigned Scale = DstEltSizeInBits / SrcEltSizeInBits;
15061 for (unsigned I = 0; I != NumDstOps; ++I) {
15062 DstUndefElements.set(I);
15063 APInt &DstBits = DstBitElements[I];
15064 for (unsigned J = 0; J != Scale; ++J) {
15065 unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1));
15066 if (SrcUndefElements[Idx])
15067 continue;
15068 DstUndefElements.reset(I);
15069 const APInt &SrcBits = SrcBitElements[Idx];
15070 assert(SrcBits.getBitWidth() == SrcEltSizeInBits &&
15071 "Illegal constant bitwidths");
15072 DstBits.insertBits(SrcBits, J * SrcEltSizeInBits);
15073 }
15074 }
15075 return;
15076 }
15077
15078 // Split src element constant bits into dst elements.
15079 unsigned Scale = SrcEltSizeInBits / DstEltSizeInBits;
15080 for (unsigned I = 0; I != NumSrcOps; ++I) {
15081 if (SrcUndefElements[I]) {
15082 DstUndefElements.set(I * Scale, (I + 1) * Scale);
15083 continue;
15084 }
15085 const APInt &SrcBits = SrcBitElements[I];
15086 for (unsigned J = 0; J != Scale; ++J) {
15087 unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1));
15088 APInt &DstBits = DstBitElements[Idx];
15089 DstBits = SrcBits.extractBits(DstEltSizeInBits, J * DstEltSizeInBits);
15090 }
15091 }
15092}
15093
15095 for (const SDValue &Op : op_values()) {
15096 unsigned Opc = Op.getOpcode();
15097 if (!Op.isUndef() && Opc != ISD::Constant && Opc != ISD::ConstantFP)
15098 return false;
15099 }
15100 return true;
15101}
15102
15103std::optional<std::pair<APInt, APInt>>
15105 unsigned NumOps = getNumOperands();
15106 if (NumOps < 2)
15107 return std::nullopt;
15108
15109 unsigned EltSize = getValueType(0).getScalarSizeInBits();
15110 APInt Start, Stride;
15111 int FirstIdx = -1, SecondIdx = -1;
15112
15113 // Find the first two non-undef constant elements to determine Start and
15114 // Stride, then verify all remaining elements match the sequence.
15115 for (unsigned I = 0; I < NumOps; ++I) {
15117 if (Op->isUndef())
15118 continue;
15119 if (!isa<ConstantSDNode>(Op))
15120 return std::nullopt;
15121
15122 APInt Val = getConstantOperandAPInt(I).trunc(EltSize);
15123 if (FirstIdx < 0) {
15124 FirstIdx = I;
15125 Start = Val;
15126 } else if (SecondIdx < 0) {
15127 SecondIdx = I;
15128 // Compute stride using modular arithmetic. Simple division would handle
15129 // common strides (1, 2, -1, etc.), but modular inverse maximizes matches.
15130 // Example: <0, poison, poison, 0xFF> has stride 0x55 since 3*0x55 = 0xFF
15131 // Note that modular arithmetic is agnostic to signed/unsigned.
15132 unsigned IdxDiff = I - FirstIdx;
15133 APInt ValDiff = Val - Start;
15134
15135 // Step 1: Factor out common powers of 2 from IdxDiff and ValDiff.
15136 unsigned CommonPow2Bits = llvm::countr_zero(IdxDiff);
15137 if (ValDiff.countr_zero() < CommonPow2Bits)
15138 return std::nullopt; // ValDiff not divisible by 2^CommonPow2Bits
15139 IdxDiff >>= CommonPow2Bits;
15140 ValDiff.lshrInPlace(CommonPow2Bits);
15141
15142 // Step 2: IdxDiff is now odd, so its inverse mod 2^EltSize exists.
15143 // TODO: There are 2^CommonPow2Bits valid strides; currently we only try
15144 // one, but we could try all candidates to handle more cases.
15145 Stride = ValDiff * APInt(EltSize, IdxDiff).multiplicativeInverse();
15146 if (Stride.isZero())
15147 return std::nullopt;
15148
15149 // Step 3: Adjust Start based on the first defined element's index.
15150 Start -= Stride * FirstIdx;
15151 } else {
15152 // Verify this element matches the sequence.
15153 if (Val != Start + Stride * I)
15154 return std::nullopt;
15155 }
15156 }
15157
15158 // Need at least two defined elements.
15159 if (SecondIdx < 0)
15160 return std::nullopt;
15161
15162 return std::make_pair(Start, Stride);
15163}
15164
15166 // Find the first non-undef value in the shuffle mask.
15167 unsigned i, e;
15168 for (i = 0, e = Mask.size(); i != e && Mask[i] < 0; ++i)
15169 /* search */;
15170
15171 // If all elements are undefined, this shuffle can be considered a splat
15172 // (although it should eventually get simplified away completely).
15173 if (i == e)
15174 return true;
15175
15176 // Make sure all remaining elements are either undef or the same as the first
15177 // non-undef value.
15178 for (int Idx = Mask[i]; i != e; ++i)
15179 if (Mask[i] >= 0 && Mask[i] != Idx)
15180 return false;
15181 return true;
15182}
15183
15184// Returns true if it is a constant integer BuildVector or constant integer,
15185// possibly hidden by a bitcast.
15187 SDValue N, bool AllowOpaques) const {
15189
15190 if (auto *C = dyn_cast<ConstantSDNode>(N))
15191 return AllowOpaques || !C->isOpaque();
15192
15194 return true;
15195
15196 // Treat a GlobalAddress supporting constant offset folding as a
15197 // constant integer.
15198 if (auto *GA = dyn_cast<GlobalAddressSDNode>(N))
15199 if (GA->getOpcode() == ISD::GlobalAddress &&
15200 TLI->isOffsetFoldingLegal(GA))
15201 return true;
15202
15203 if ((N.getOpcode() == ISD::SPLAT_VECTOR) &&
15204 isa<ConstantSDNode>(N.getOperand(0)))
15205 return true;
15206 return false;
15207}
15208
15209// Returns true if it is a constant float BuildVector or constant float.
15212 return true;
15213
15215 return true;
15216
15217 if ((N.getOpcode() == ISD::SPLAT_VECTOR) &&
15218 isa<ConstantFPSDNode>(N.getOperand(0)))
15219 return true;
15220
15221 return false;
15222}
15223
15224std::optional<bool> SelectionDAG::isBoolConstant(SDValue N) const {
15225 ConstantSDNode *Const =
15226 isConstOrConstSplat(N, false, /*AllowTruncation=*/true);
15227 if (!Const)
15228 return std::nullopt;
15229
15230 EVT VT = N->getValueType(0);
15231 const APInt CVal = Const->getAPIntValue().trunc(VT.getScalarSizeInBits());
15232 switch (TLI->getBooleanContents(N.getValueType())) {
15234 if (CVal.isOne())
15235 return true;
15236 if (CVal.isZero())
15237 return false;
15238 return std::nullopt;
15240 if (CVal.isAllOnes())
15241 return true;
15242 if (CVal.isZero())
15243 return false;
15244 return std::nullopt;
15246 return CVal[0];
15247 }
15248 llvm_unreachable("Unknown BooleanContent enum");
15249}
15250
15251void SelectionDAG::createOperands(SDNode *Node, ArrayRef<SDValue> Vals) {
15252 assert(!Node->OperandList && "Node already has operands");
15254 "too many operands to fit into SDNode");
15255 SDUse *Ops = OperandRecycler.allocate(
15256 ArrayRecycler<SDUse>::Capacity::get(Vals.size()), OperandAllocator);
15257
15258 bool IsDivergent = false;
15259 for (unsigned I = 0; I != Vals.size(); ++I) {
15260 Ops[I].setUser(Node);
15261 Ops[I].setInitial(Vals[I]);
15262 EVT VT = Ops[I].getValueType();
15263
15264 // Skip Chain. It does not carry divergence.
15265 if (VT != MVT::Other &&
15266 (VT != MVT::Glue || gluePropagatesDivergence(Ops[I].getNode())) &&
15267 Ops[I].getNode()->isDivergent()) {
15268 IsDivergent = true;
15269 }
15270 }
15271 Node->NumOperands = Vals.size();
15272 Node->OperandList = Ops;
15273 if (!TLI->isSDNodeAlwaysUniform(Node)) {
15274 IsDivergent |= TLI->isSDNodeSourceOfDivergence(Node, FLI, UA);
15275 Node->SDNodeBits.IsDivergent = IsDivergent;
15276 }
15277 checkForCycles(Node);
15278}
15279
15282 size_t Limit = SDNode::getMaxNumOperands();
15283 while (Vals.size() > Limit) {
15284 unsigned SliceIdx = Vals.size() - Limit;
15285 auto ExtractedTFs = ArrayRef<SDValue>(Vals).slice(SliceIdx, Limit);
15286 SDValue NewTF = getNode(ISD::TokenFactor, DL, MVT::Other, ExtractedTFs);
15287 Vals.erase(Vals.begin() + SliceIdx, Vals.end());
15288 Vals.emplace_back(NewTF);
15289 }
15290 return getNode(ISD::TokenFactor, DL, MVT::Other, Vals);
15291}
15292
15294 EVT VT, SDNodeFlags Flags) {
15295 switch (Opcode) {
15296 default:
15297 return SDValue();
15298 case ISD::ADD:
15299 case ISD::OR:
15300 case ISD::XOR:
15301 case ISD::UMAX:
15302 case ISD::MUL:
15303 case ISD::AND:
15304 case ISD::UMIN:
15305 case ISD::SMAX:
15306 case ISD::SMIN:
15308 VT);
15309 case ISD::FADD:
15310 // If flags allow, prefer positive zero since it's generally cheaper
15311 // to materialize on most targets.
15312 return getConstantFP(Flags.hasNoSignedZeros() ? 0.0 : -0.0, DL, VT);
15313 case ISD::FMUL:
15314 return getConstantFP(1.0, DL, VT);
15315 case ISD::FMINNUM:
15316 case ISD::FMAXNUM: {
15317 // Neutral element for fminnum is NaN, Inf or FLT_MAX, depending on FMF.
15318 const fltSemantics &Semantics = VT.getFltSemantics();
15319 APFloat NeutralAF = !Flags.hasNoNaNs() ? APFloat::getQNaN(Semantics) :
15320 !Flags.hasNoInfs() ? APFloat::getInf(Semantics) :
15321 APFloat::getLargest(Semantics);
15322 if (Opcode == ISD::FMAXNUM)
15323 NeutralAF.changeSign();
15324
15325 return getConstantFP(NeutralAF, DL, VT);
15326 }
15327 case ISD::FMINIMUM:
15328 case ISD::FMAXIMUM: {
15329 // Neutral element for fminimum is Inf or FLT_MAX, depending on FMF.
15330 const fltSemantics &Semantics = VT.getFltSemantics();
15331 APFloat NeutralAF = !Flags.hasNoInfs() ? APFloat::getInf(Semantics)
15332 : APFloat::getLargest(Semantics);
15333 if (Opcode == ISD::FMAXIMUM)
15334 NeutralAF.changeSign();
15335
15336 return getConstantFP(NeutralAF, DL, VT);
15337 }
15338
15339 }
15340}
15341
15343 SDValue Acc, SDValue LHS,
15344 SDValue RHS) {
15345 EVT AccVT = Acc.getValueType();
15346 if (AccVT.isFloatingPoint()) {
15347 assert(Opc == ISD::PARTIAL_REDUCE_FMLA && "Unexpected opcode");
15348 SDValue NegRHS = getNode(ISD::FNEG, DL, RHS.getValueType(), RHS);
15349 return getNode(Opc, DL, AccVT, Acc, LHS, NegRHS);
15350 }
15352 "Unexpected opcode");
15353 SDValue NegAcc = getNegative(Acc, DL, AccVT);
15354 SDValue MLA = getNode(Opc, DL, AccVT, NegAcc, LHS, RHS);
15355 return getNegative(MLA, DL, AccVT);
15356}
15357
15358/// Helper used to make a call to a library function that has one argument of
15359/// pointer type.
15360///
15361/// Such functions include 'fegetmode', 'fesetenv' and some others, which are
15362/// used to get or set floating-point state. They have one argument of pointer
15363/// type, which points to the memory region containing bits of the
15364/// floating-point state. The value returned by such function is ignored in the
15365/// created call.
15366///
15367/// \param LibFunc Reference to library function (value of RTLIB::Libcall).
15368/// \param Ptr Pointer used to save/load state.
15369/// \param InChain Ingoing token chain.
15370/// \returns Outgoing chain token.
15372 SDValue InChain,
15373 const SDLoc &DLoc) {
15374 assert(InChain.getValueType() == MVT::Other && "Expected token chain");
15376 Args.emplace_back(Ptr, Ptr.getValueType().getTypeForEVT(*getContext()));
15377 RTLIB::LibcallImpl LibcallImpl =
15378 Libcalls->getLibcallImpl(static_cast<RTLIB::Libcall>(LibFunc));
15379 if (LibcallImpl == RTLIB::Unsupported)
15380 reportFatalUsageError("emitting call to unsupported libcall");
15381
15382 SDValue Callee =
15383 getExternalSymbol(LibcallImpl, TLI->getPointerTy(getDataLayout()));
15385 CLI.setDebugLoc(DLoc).setChain(InChain).setLibCallee(
15386 Libcalls->getLibcallImplCallingConv(LibcallImpl),
15387 Type::getVoidTy(*getContext()), Callee, std::move(Args));
15388 return TLI->LowerCallTo(CLI).second;
15389}
15390
15392 assert(From && To && "Invalid SDNode; empty source SDValue?");
15393 auto I = SDEI.find(From);
15394 if (I == SDEI.end())
15395 return;
15396
15397 // Use of operator[] on the DenseMap may cause an insertion, which invalidates
15398 // the iterator, hence the need to make a copy to prevent a use-after-free.
15399 NodeExtraInfo NEI = I->second;
15400 if (LLVM_LIKELY(!NEI.PCSections)) {
15401 // No deep copy required for the types of extra info set.
15402 //
15403 // FIXME: Investigate if other types of extra info also need deep copy. This
15404 // depends on the types of nodes they can be attached to: if some extra info
15405 // is only ever attached to nodes where a replacement To node is always the
15406 // node where later use and propagation of the extra info has the intended
15407 // semantics, no deep copy is required.
15408 SDEI[To] = std::move(NEI);
15409 return;
15410 }
15411
15412 const SDNode *EntrySDN = getEntryNode().getNode();
15413
15414 // We need to copy NodeExtraInfo to all _new_ nodes that are being introduced
15415 // through the replacement of From with To. Otherwise, replacements of a node
15416 // (From) with more complex nodes (To and its operands) may result in lost
15417 // extra info where the root node (To) is insignificant in further propagating
15418 // and using extra info when further lowering to MIR.
15419 //
15420 // In the first step pre-populate the visited set with the nodes reachable
15421 // from the old From node. This avoids copying NodeExtraInfo to parts of the
15422 // DAG that is not new and should be left untouched.
15423 SmallVector<const SDNode *> Leafs{From}; // Leafs reachable with VisitFrom.
15424 DenseSet<const SDNode *> FromReach; // The set of nodes reachable from From.
15425 auto VisitFrom = [&](auto &&Self, const SDNode *N, int MaxDepth) {
15426 if (MaxDepth == 0) {
15427 // Remember this node in case we need to increase MaxDepth and continue
15428 // populating FromReach from this node.
15429 Leafs.emplace_back(N);
15430 return;
15431 }
15432 if (!FromReach.insert(N).second)
15433 return;
15434 for (const SDValue &Op : N->op_values())
15435 Self(Self, Op.getNode(), MaxDepth - 1);
15436 };
15437
15438 // Copy extra info to To and all its transitive operands (that are new).
15440 auto DeepCopyTo = [&](auto &&Self, const SDNode *N) {
15441 if (FromReach.contains(N))
15442 return true;
15443 if (!Visited.insert(N).second)
15444 return true;
15445 if (EntrySDN == N)
15446 return false;
15447 for (const SDValue &Op : N->op_values()) {
15448 if (N == To && Op.getNode() == EntrySDN) {
15449 // Special case: New node's operand is the entry node; just need to
15450 // copy extra info to new node.
15451 break;
15452 }
15453 if (!Self(Self, Op.getNode()))
15454 return false;
15455 }
15456 // Copy only if entry node was not reached.
15457 SDEI[N] = std::move(NEI);
15458 return true;
15459 };
15460
15461 // We first try with a lower MaxDepth, assuming that the path to common
15462 // operands between From and To is relatively short. This significantly
15463 // improves performance in the common case. The initial MaxDepth is big
15464 // enough to avoid retry in the common case; the last MaxDepth is large
15465 // enough to avoid having to use the fallback below (and protects from
15466 // potential stack exhaustion from recursion).
15467 for (int PrevDepth = 0, MaxDepth = 16; MaxDepth <= 1024;
15468 PrevDepth = MaxDepth, MaxDepth *= 2, Visited.clear()) {
15469 // StartFrom is the previous (or initial) set of leafs reachable at the
15470 // previous maximum depth.
15472 std::swap(StartFrom, Leafs);
15473 for (const SDNode *N : StartFrom)
15474 VisitFrom(VisitFrom, N, MaxDepth - PrevDepth);
15475 if (LLVM_LIKELY(DeepCopyTo(DeepCopyTo, To)))
15476 return;
15477 // This should happen very rarely (reached the entry node).
15478 LLVM_DEBUG(dbgs() << __func__ << ": MaxDepth=" << MaxDepth << " too low\n");
15479 assert(!Leafs.empty());
15480 }
15481
15482 // This should not happen - but if it did, that means the subgraph reachable
15483 // from From has depth greater or equal to maximum MaxDepth, and VisitFrom()
15484 // could not visit all reachable common operands. Consequently, we were able
15485 // to reach the entry node.
15486 errs() << "warning: incomplete propagation of SelectionDAG::NodeExtraInfo\n";
15487 assert(false && "From subgraph too complex - increase max. MaxDepth?");
15488 // Best-effort fallback if assertions disabled.
15489 SDEI[To] = std::move(NEI);
15490}
15491
15492#ifndef NDEBUG
15493static void checkForCyclesHelper(const SDNode *N,
15496 const llvm::SelectionDAG *DAG) {
15497 // If this node has already been checked, don't check it again.
15498 if (Checked.count(N))
15499 return;
15500
15501 // If a node has already been visited on this depth-first walk, reject it as
15502 // a cycle.
15503 if (!Visited.insert(N).second) {
15504 errs() << "Detected cycle in SelectionDAG\n";
15505 dbgs() << "Offending node:\n";
15506 N->dumprFull(DAG); dbgs() << "\n";
15507 abort();
15508 }
15509
15510 for (const SDValue &Op : N->op_values())
15511 checkForCyclesHelper(Op.getNode(), Visited, Checked, DAG);
15512
15513 Checked.insert(N);
15514 Visited.erase(N);
15515}
15516#endif
15517
15519 const llvm::SelectionDAG *DAG,
15520 bool force) {
15521#ifndef NDEBUG
15522 bool check = force;
15523#ifdef EXPENSIVE_CHECKS
15524 check = true;
15525#endif // EXPENSIVE_CHECKS
15526 if (check) {
15527 assert(N && "Checking nonexistent SDNode");
15530 checkForCyclesHelper(N, visited, checked, DAG);
15531 }
15532#endif // !NDEBUG
15533}
15534
15535void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) {
15536 checkForCycles(DAG->getRoot().getNode(), DAG, force);
15537}
return SDValue()
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
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:856
This file implements the BitVector class.
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static std::optional< bool > isBigEndian(const SmallDenseMap< int64_t, int64_t, 8 > &MemOffset2Idx, int64_t LowestIdx)
Given a map from byte offsets in memory to indices in a load/store, determine if that map corresponds...
#define __asan_unpoison_memory_region(p, size)
Definition Compiler.h:609
#define LLVM_LIKELY(EXPR)
Definition Compiler.h:343
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file defines the DenseSet and SmallDenseSet classes.
This file contains constants used for implementing Dwarf debug support.
This file defines a hash set that can be used to remove duplication of nodes in a graph.
static MaybeAlign getAlign(Value *Ptr)
iv users
Definition IVUsers.cpp:48
std::pair< Instruction::BinaryOps, Value * > OffsetOp
Find all possible pairs (BinOp, RHS) that BinOp V, RHS can be simplified.
static constexpr Value * getValue(Ty &ValueOrUse)
const size_t AbstractManglingParser< Derived, Alloc >::NumOps
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
static Register getMemsetValue(Register Val, LLT Ty, MachineIRBuilder &MIB)
static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT, AssumptionCache *AC)
Definition Lint.cpp:539
static Align getPrefTypeAlign(EVT VT, SelectionDAG &DAG)
static bool isConstantSplatVector(SDValue N, APInt &SplatValue, unsigned MinSizeInBits)
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define G(x, y, z)
Definition MD5.cpp:55
This file declares the MachineConstantPool class which is an abstract constant pool to keep track of ...
Register const TargetRegisterInfo * TRI
This file provides utility analysis objects describing memory locations.
This file contains the declarations for metadata subclasses.
#define T
static MCRegister getReg(const MCDisassembler *D, unsigned RC, unsigned RegNo)
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
#define P(N)
PowerPC Reduce CR logical Operation
const SmallVectorImpl< MachineOperand > & Cond
Remove Loads Into Fake Uses
static bool isValid(const char C)
Returns true if C is a valid mangled character: <0-9a-zA-Z_>.
Contains matchers for matching SelectionDAG nodes and values.
SI Fold Operands
static Type * getValueType(Value *V, bool LookThroughCmp=false)
Returns the "element type" of the given value/instruction V.
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 void AddNodeIDNode(FoldingSetNodeID &ID, unsigned OpC, SDVTList VTList, ArrayRef< SDValue > OpList)
static SDValue getMemsetStringVal(EVT VT, const SDLoc &dl, SelectionDAG &DAG, const TargetLowering &TLI, const ConstantDataArraySlice &Slice)
getMemsetStringVal - Similar to getMemsetValue.
static cl::opt< bool > EnableMemCpyDAGOpt("enable-memcpy-dag-opt", cl::Hidden, cl::init(true), cl::desc("Gang up loads and stores generated by inlining of memcpy"))
static bool haveNoCommonBitsSetCommutative(SDValue A, SDValue B)
static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList)
AddNodeIDValueTypes - Value type lists are intern'd so we can represent them solely with their pointe...
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 void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC)
AddNodeIDOpcode - Add the node opcode to the NodeID data.
static ISD::CondCode getSetCCInverseImpl(ISD::CondCode Op, bool isIntegerLike)
static bool doNotCSE(SDNode *N)
doNotCSE - Return true if CSE should not be performed for this node.
static cl::opt< int > MaxLdStGlue("ldstmemcpy-glue-max", cl::desc("Number limit for gluing ld/st of memcpy."), cl::Hidden, cl::init(0))
static void AddNodeIDOperands(FoldingSetNodeID &ID, ArrayRef< SDValue > Ops)
AddNodeIDOperands - Various routines for adding operands to the NodeID data.
static APInt getIntegerIdentity(unsigned Opcode, unsigned BitWidth)
static SDValue foldCONCAT_VECTORS(const SDLoc &DL, EVT VT, ArrayRef< SDValue > Ops, SelectionDAG &DAG)
Try to simplify vector concatenation to an input value, undef, or build vector.
static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info, SelectionDAG &DAG, SDValue Ptr, int64_t Offset=0)
InferPointerInfo - If the specified ptr/offset is a frame index, infer a MachinePointerInfo record fr...
static bool isInTailCallPositionWrapper(const CallInst *CI, const SelectionDAG *SelDAG, bool AllowReturnsFirstArg)
static void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N)
If this is an SDNode with special info, add this info to the NodeID data.
static bool gluePropagatesDivergence(const SDNode *Node)
Return true if a glue output should propagate divergence information.
static void NewSDValueDbgMsg(SDValue V, StringRef Msg, SelectionDAG *G)
static SDVTList makeVTList(const EVT *VTs, unsigned NumVTs)
makeVTList - Return an instance of the SDVTList struct initialized with the specified members.
static void checkForCyclesHelper(const SDNode *N, SmallPtrSetImpl< const SDNode * > &Visited, SmallPtrSetImpl< const SDNode * > &Checked, const llvm::SelectionDAG *DAG)
static void chainLoadsAndStoresForMemcpy(SelectionDAG &DAG, const SDLoc &dl, SmallVector< SDValue, 32 > &OutChains, unsigned From, unsigned To, SmallVector< SDValue, 16 > &OutLoadChains, SmallVector< SDValue, 16 > &OutStoreChains)
static int isSignedOp(ISD::CondCode Opcode)
For an integer comparison, return 1 if the comparison is a signed operation and 2 if the result is an...
static std::optional< APInt > FoldValue(unsigned Opcode, const APInt &C1, const APInt &C2)
static SDValue FoldBUILD_VECTOR(const SDLoc &DL, EVT VT, ArrayRef< SDValue > Ops, SelectionDAG &DAG)
static void checkAddrSpaceIsValidForLibcall(const TargetLowering *TLI, unsigned AS)
static cl::opt< unsigned > MaxSteps("has-predecessor-max-steps", cl::Hidden, cl::init(8192), cl::desc("DAG combiner limit number of steps when searching DAG " "for predecessor nodes"))
static APInt getDemandAllEltsMask(SDValue V)
Construct a DemandedElts mask which demands all elements of V.
static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl, SDValue Chain, SDValue Dst, SDValue Src, uint64_t Size, Align DstAlign, Align SrcAlign, bool isVol, bool AlwaysInline, MachinePointerInfo DstPtrInfo, MachinePointerInfo SrcPtrInfo, const AAMDNodes &AAInfo, BatchAAResults *BatchAA, const MDNode *DstMemCacheHint, const MDNode *SrcMemCacheHint)
static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl, SDValue Chain, SDValue Dst, SDValue Src, uint64_t Size, Align DstAlign, Align SrcAlign, bool isVol, bool AlwaysInline, MachinePointerInfo DstPtrInfo, MachinePointerInfo SrcPtrInfo, const AAMDNodes &AAInfo)
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
#define LLVM_DEBUG(...)
Definition Debug.h:119
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
This file describes how to lower LLVM code to machine code.
static void removeOperands(MachineInstr &MI, unsigned i)
static OverflowResult mapOverflowResult(ConstantRange::OverflowResult OR)
Convert ConstantRange OverflowResult into ValueTracking OverflowResult.
static int Lookup(ArrayRef< TableEntry > Table, unsigned Opcode)
static unsigned getSize(unsigned Kind)
static const fltSemantics & IEEEsingle()
Definition APFloat.h:304
cmpResult
IEEE-754R 5.11: Floating Point Comparison Relations.
Definition APFloat.h:343
static constexpr roundingMode rmTowardZero
Definition APFloat.h:357
static const fltSemantics & BFloat()
Definition APFloat.h:303
static const fltSemantics & IEEEquad()
Definition APFloat.h:306
static const fltSemantics & IEEEdouble()
Definition APFloat.h:305
static constexpr roundingMode rmTowardNegative
Definition APFloat.h:356
static constexpr roundingMode rmNearestTiesToEven
Definition APFloat.h:353
static constexpr roundingMode rmTowardPositive
Definition APFloat.h:355
static const fltSemantics & IEEEhalf()
Definition APFloat.h:302
opStatus
IEEE-754R 7: Default exception handling.
Definition APFloat.h:369
static APFloat getQNaN(const fltSemantics &Sem, bool Negative=false, const APInt *payload=nullptr)
Factory for QNaN values.
Definition APFloat.h:1216
opStatus divide(const APFloat &RHS, roundingMode RM)
Definition APFloat.h:1304
void copySign(const APFloat &RHS)
Definition APFloat.h:1398
LLVM_ABI opStatus convert(const fltSemantics &ToSemantics, roundingMode RM, bool *losesInfo)
Definition APFloat.cpp:5929
opStatus subtract(const APFloat &RHS, roundingMode RM)
Definition APFloat.h:1286
bool isNegative() const
Definition APFloat.h:1575
opStatus add(const APFloat &RHS, roundingMode RM)
Definition APFloat.h:1277
bool isFinite() const
Definition APFloat.h:1580
opStatus convertFromAPInt(const APInt &Input, bool IsSigned, roundingMode RM)
Definition APFloat.h:1443
opStatus multiply(const APFloat &RHS, roundingMode RM)
Definition APFloat.h:1295
bool isZero() const
Definition APFloat.h:1571
LLVM_READONLY bool isOne() const
Definition APFloat.h:1653
bool isLargest() const
Definition APFloat.h:1591
static APFloat getLargest(const fltSemantics &Sem, bool Negative=false)
Returns the largest finite number in the given semantics.
Definition APFloat.h:1234
opStatus convertToInteger(MutableArrayRef< integerPart > Input, unsigned int Width, bool IsSigned, roundingMode RM, bool *IsExact) const
Definition APFloat.h:1428
static APFloat getInf(const fltSemantics &Sem, bool Negative=false)
Factory for Positive and Negative Infinity.
Definition APFloat.h:1194
opStatus mod(const APFloat &RHS)
Definition APFloat.h:1322
bool isPosZero() const
Definition APFloat.h:1586
bool isNegZero() const
Definition APFloat.h:1587
void changeSign()
Definition APFloat.h:1393
static APFloat getNaN(const fltSemantics &Sem, bool Negative=false, uint64_t payload=0)
Factory for NaN values.
Definition APFloat.h:1205
bool isInfinity() const
Definition APFloat.h:1572
Class for arbitrary precision integers.
Definition APInt.h:78
LLVM_ABI APInt umul_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:2006
LLVM_ABI APInt usub_sat(const APInt &RHS) const
Definition APInt.cpp:2090
LLVM_ABI APInt udiv(const APInt &RHS) const
Unsigned division operation.
Definition APInt.cpp:1599
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
Definition APInt.h:235
void clearBit(unsigned BitPosition)
Set a given bit to 0.
Definition APInt.h:1431
LLVM_ABI APInt zext(unsigned width) const
Zero extend to a new width.
Definition APInt.cpp:1055
static APInt getSignMask(unsigned BitWidth)
Get the SignMask for a specific bit width.
Definition APInt.h:230
bool isMinSignedValue() const
Determine if this is the smallest signed value.
Definition APInt.h:424
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1565
unsigned popcount() const
Count the number of bits set.
Definition APInt.h:1695
LLVM_ABI APInt zextOrTrunc(unsigned width) const
Zero extend or truncate to width.
Definition APInt.cpp:1076
unsigned getActiveBits() const
Compute the number of active bits in the value.
Definition APInt.h:1537
LLVM_ABI APInt trunc(unsigned width) const
Truncate to new width.
Definition APInt.cpp:968
void setBit(unsigned BitPosition)
Set the given bit to 1 whose position is given as "bitPosition".
Definition APInt.h:1355
APInt abs() const
Get the absolute value.
Definition APInt.h:1820
LLVM_ABI APInt sadd_sat(const APInt &RHS) const
Definition APInt.cpp:2061
bool isAllOnes() const
Determine if all bits are set. This is true for zero-width values.
Definition APInt.h:372
bool ugt(const APInt &RHS) const
Unsigned greater than comparison.
Definition APInt.h:1191
static APInt getBitsSet(unsigned numBits, unsigned loBit, unsigned hiBit)
Get a value with a block of bits set.
Definition APInt.h:259
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition APInt.h:381
LLVM_ABI APInt urem(const APInt &RHS) const
Unsigned remainder operation.
Definition APInt.cpp:1692
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1513
bool ult(const APInt &RHS) const
Unsigned less than comparison.
Definition APInt.h:1120
static APInt getSignedMaxValue(unsigned numBits)
Gets maximum signed value of APInt for a specific bit width.
Definition APInt.h:210
bool isNegative() const
Determine sign of this APInt.
Definition APInt.h:330
LLVM_ABI APInt sdiv(const APInt &RHS) const
Signed division function for APInt.
Definition APInt.cpp:1670
LLVM_ABI APInt rotr(unsigned rotateAmt) const
Rotate right by rotateAmt.
Definition APInt.cpp:1197
LLVM_ABI APInt reverseBits() const
Definition APInt.cpp:790
void ashrInPlace(unsigned ShiftAmt)
Arithmetic right-shift this APInt by ShiftAmt in place.
Definition APInt.h:841
bool sle(const APInt &RHS) const
Signed less or equal comparison.
Definition APInt.h:1175
unsigned countr_zero() const
Count the number of trailing zero bits.
Definition APInt.h:1664
unsigned getNumSignBits() const
Computes the number of leading bits of this APInt that are equal to its sign bit.
Definition APInt.h:1653
unsigned countl_zero() const
The APInt version of std::countl_zero.
Definition APInt.h:1623
static LLVM_ABI APInt getSplat(unsigned NewLen, const APInt &V)
Return a value containing V broadcasted over NewLen bits.
Definition APInt.cpp:652
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
Definition APInt.h:220
LLVM_ABI APInt sshl_sat(const APInt &RHS) const
Definition APInt.cpp:2121
LLVM_ABI APInt ushl_sat(const APInt &RHS) const
Definition APInt.cpp:2135
LLVM_ABI APInt sextOrTrunc(unsigned width) const
Sign extend or truncate to width.
Definition APInt.cpp:1084
static bool isSameValue(const APInt &I1, const APInt &I2, bool SignedCompare=false)
Determine if two APInts have the same value, after zero-extending or sign-extending (if SignedCompare...
Definition APInt.h:555
LLVM_ABI APInt rotl(unsigned rotateAmt) const
Rotate left by rotateAmt.
Definition APInt.cpp:1184
LLVM_ABI void insertBits(const APInt &SubBits, unsigned bitPosition)
Insert the bits from a smaller APInt starting at bitPosition.
Definition APInt.cpp:398
unsigned logBase2() const
Definition APInt.h:1786
LLVM_ABI APInt uadd_sat(const APInt &RHS) const
Definition APInt.cpp:2071
APInt ashr(unsigned ShiftAmt) const
Arithmetic right-shift function.
Definition APInt.h:834
LLVM_ABI APInt multiplicativeInverse() const
Definition APInt.cpp:1300
LLVM_ABI APInt srem(const APInt &RHS) const
Function for signed remainder operation.
Definition APInt.cpp:1771
bool isNonNegative() const
Determine if this APInt Value is non-negative (>= 0)
Definition APInt.h:335
bool ule(const APInt &RHS) const
Unsigned less or equal comparison.
Definition APInt.h:1159
LLVM_ABI APInt sext(unsigned width) const
Sign extend to a new width.
Definition APInt.cpp:1028
void setBits(unsigned loBit, unsigned hiBit)
Set the bits from loBit (inclusive) to hiBit (exclusive) to 1.
Definition APInt.h:1392
APInt shl(unsigned shiftAmt) const
Left-shift function.
Definition APInt.h:880
LLVM_ABI APInt byteSwap() const
Definition APInt.cpp:768
bool isSubsetOf(const APInt &RHS) const
This operation checks that all bits set in this APInt are also set in RHS.
Definition APInt.h:1266
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
Definition APInt.h:441
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Constructs an APInt value that has the bottom loBitsSet bits set.
Definition APInt.h:307
void clearBits(unsigned LoBit, unsigned HiBit)
Clear the bits from LoBit (inclusive) to HiBit (exclusive) to 0.
Definition APInt.h:1442
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition APInt.h:201
LLVM_ABI APInt extractBits(unsigned numBits, unsigned bitPosition) const
Return an APInt with the extracted bits [bitPosition,bitPosition+numBits).
Definition APInt.cpp:483
bool sge(const APInt &RHS) const
Signed greater or equal comparison.
Definition APInt.h:1246
bool isOne() const
Determine if this is a value of 1.
Definition APInt.h:390
static APInt getBitsSetFrom(unsigned numBits, unsigned loBit)
Constructs an APInt value that has a contiguous range of bits set.
Definition APInt.h:287
static APInt getOneBitSet(unsigned numBits, unsigned BitNo)
Return an APInt with exactly one bit set in the result.
Definition APInt.h:240
void lshrInPlace(unsigned ShiftAmt)
Logical right-shift this APInt by ShiftAmt in place.
Definition APInt.h:865
APInt lshr(unsigned shiftAmt) const
Logical right-shift function.
Definition APInt.h:858
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
Definition APInt.h:1230
LLVM_ABI APInt ssub_sat(const APInt &RHS) const
Definition APInt.cpp:2080
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
This is an SDNode representing atomic operations.
static LLVM_ABI BaseIndexOffset match(const SDNode *N, const SelectionDAG &DAG)
Parses tree in N for base, index, offset addresses.
This class is a wrapper over an AAResults, and it is intended to be used only when there are no IR ch...
bool pointsToConstantMemory(const MemoryLocation &Loc, bool OrLocal=false)
BitVector & reset()
Reset all bits in the bitvector.
Definition BitVector.h:409
void resize(unsigned N, bool t=false)
Grow or shrink the bitvector.
Definition BitVector.h:355
void clear()
Removes all bits from the bitvector.
Definition BitVector.h:349
BitVector & set()
Set all bits in the bitvector.
Definition BitVector.h:366
bool none() const
Returns true if none of the bits are set.
Definition BitVector.h:207
size_type size() const
Returns the number of bits in this bitvector.
Definition BitVector.h:178
const BlockAddress * getBlockAddress() const
The address of a basic block.
Definition Constants.h:1088
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
A "pseudo-class" with methods for operating on BUILD_VECTORs.
LLVM_ABI bool getConstantRawBits(bool IsLittleEndian, unsigned DstEltSizeInBits, SmallVectorImpl< APInt > &RawBitElements, BitVector &UndefElements) const
Extract the raw bit data from a build vector of Undef, Constant or ConstantFP node elements.
static LLVM_ABI void recastRawBits(bool IsLittleEndian, unsigned DstEltSizeInBits, SmallVectorImpl< APInt > &DstBitElements, ArrayRef< APInt > SrcBitElements, BitVector &DstUndefElements, const BitVector &SrcUndefElements)
Recast bit data SrcBitElements to DstEltSizeInBits wide elements.
LLVM_ABI bool getRepeatedSequence(const APInt &DemandedElts, SmallVectorImpl< SDValue > &Sequence, BitVector *UndefElements=nullptr) const
Find the shortest repeating sequence of values in the build vector.
LLVM_ABI ConstantFPSDNode * getConstantFPSplatNode(const APInt &DemandedElts, BitVector *UndefElements=nullptr) const
Returns the demanded splatted constant FP or null if this is not a constant FP splat.
LLVM_ABI SDValue getSplatValue(const APInt &DemandedElts, BitVector *UndefElements=nullptr) const
Returns the demanded splatted value or a null value if this is not a splat.
LLVM_ABI bool isConstantSplat(APInt &SplatValue, APInt &SplatUndef, unsigned &SplatBitSize, bool &HasAnyUndefs, unsigned MinSplatBits=0, bool isBigEndian=false) const
Check if this is a constant splat, and if so, find the smallest element size that splats the vector.
LLVM_ABI ConstantSDNode * getConstantSplatNode(const APInt &DemandedElts, BitVector *UndefElements=nullptr) const
Returns the demanded splatted constant or null if this is not a constant splat.
LLVM_ABI int32_t getConstantFPSplatPow2ToLog2Int(BitVector *UndefElements, uint32_t BitWidth) const
If this is a constant FP splat and the splatted constant FP is an exact power or 2,...
LLVM_ABI std::optional< std::pair< APInt, APInt > > isArithmeticSequence() const
If this BuildVector is constant and represents an arithmetic sequence "<a, a+n, a+2n,...
LLVM_ABI bool isConstant() const
This class represents a function call, abstracting a target machine's calling convention.
bool isTailCall() const
static LLVM_ABI bool isValueValidForType(EVT VT, const APFloat &Val)
const APFloat & getValueAPF() const
bool isExactlyValue(double V) const
We don't rely on operator== working on double values, as it returns true for things that are clearly ...
ConstantFP - Floating Point Values [float, double].
Definition Constants.h:420
const APFloat & getValue() const
Definition Constants.h:464
This is the shared class of boolean and integer constants.
Definition Constants.h:87
unsigned getBitWidth() const
getBitWidth - Return the scalar bitwidth of this constant.
Definition Constants.h:162
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition Constants.h:159
MachineConstantPoolValue * getMachineCPVal() const
const Constant * getConstVal() const
LLVM_ABI Type * getType() const
This class represents a range of values.
PreferredRangeType
If represented precisely, the result of some range operations may consist of multiple disjoint ranges...
const APInt * getSingleElement() const
If this set contains a single element, return it, otherwise return null.
static LLVM_ABI ConstantRange fromKnownBits(const KnownBits &Known, bool IsSigned)
Initialize a range based on a known bits constraint.
LLVM_ABI OverflowResult unsignedSubMayOverflow(const ConstantRange &Other) const
Return whether unsigned sub of the two ranges always/never overflows.
LLVM_ABI OverflowResult unsignedAddMayOverflow(const ConstantRange &Other) const
Return whether unsigned add of the two ranges always/never overflows.
LLVM_ABI KnownBits toKnownBits() const
Return known bits for values in this range.
LLVM_ABI ConstantRange zeroExtend(uint32_t BitWidth) const
Return a new range in the specified integer type, which must be strictly larger than the current type...
LLVM_ABI APInt getSignedMin() const
Return the smallest signed value contained in the ConstantRange.
LLVM_ABI OverflowResult unsignedMulMayOverflow(const ConstantRange &Other) const
Return whether unsigned mul of the two ranges always/never overflows.
LLVM_ABI ConstantRange signExtend(uint32_t BitWidth) const
Return a new range in the specified integer type, which must be strictly larger than the current type...
LLVM_ABI ConstantRange multiply(const ConstantRange &Other, unsigned NoWrapKind=0) const
Return a new range representing the possible values resulting from a multiplication of a value in thi...
LLVM_ABI bool contains(const APInt &Val) const
Return true if the specified value is in the set.
LLVM_ABI APInt getUnsignedMax() const
Return the largest unsigned value contained in the ConstantRange.
LLVM_ABI ConstantRange intersectWith(const ConstantRange &CR, PreferredRangeType Type=Smallest) const
Return the range that results from the intersection of this range with another range.
LLVM_ABI APInt getSignedMax() const
Return the largest signed value contained in the ConstantRange.
OverflowResult
Represents whether an operation on the given constant range is known to always or never overflow.
@ AlwaysOverflowsHigh
Always overflows in the direction of signed/unsigned max value.
@ AlwaysOverflowsLow
Always overflows in the direction of signed/unsigned min value.
@ MayOverflow
May or may not overflow.
uint32_t getBitWidth() const
Get the bit width of this ConstantRange.
LLVM_ABI OverflowResult signedSubMayOverflow(const ConstantRange &Other) const
Return whether signed sub of the two ranges always/never overflows.
uint64_t getZExtValue() const
const APInt & getAPIntValue() const
This is an important base class in LLVM.
Definition Constant.h:43
LLVM_ABI Constant * getSplatValue(bool AllowPoison=false) const
If all elements of the vector constant have the same value, return that value.
LLVM_ABI Constant * getAggregateElement(unsigned Elt) const
For aggregates (struct/array/vector) return the constant that corresponds to the specified element if...
DWARF expression.
static LLVM_ABI ExtOps getExtOps(unsigned FromSize, unsigned ToSize, bool Signed)
Returns the ops for a zero- or sign-extension in a DIExpression.
static LLVM_ABI void appendOffset(SmallVectorImpl< uint64_t > &Ops, int64_t Offset)
Append Ops with operations to apply the Offset.
static LLVM_ABI DIExpression * appendOpsToArg(const DIExpression *Expr, ArrayRef< uint64_t > Ops, unsigned ArgNo, bool StackValue=false)
Create a copy of Expr by appending the given list of Ops to each instance of the operand DW_OP_LLVM_a...
static LLVM_ABI const DIExpression * convertToVariadicExpression(const DIExpression *Expr)
If Expr is a non-variadic expression (i.e.
static LLVM_ABI std::optional< DIExpression * > createFragmentExpression(const DIExpression *Expr, unsigned OffsetInBits, unsigned SizeInBits)
Create a DIExpression to describe one part of an aggregate variable that is fragmented across multipl...
Base class for variables.
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
bool isLittleEndian() const
Layout endianness...
Definition DataLayout.h:217
LLVM_ABI IntegerType * getIntPtrType(LLVMContext &C, unsigned AddressSpace=0) const
Returns an integer type with size at least as big as that of a pointer in the given address space.
LLVM_ABI Align getABITypeAlign(Type *Ty) const
Returns the minimum ABI-required alignment for the specified type.
LLVM_ABI unsigned getPointerTypeSizeInBits(Type *) const
The pointer representation size in bits for this type.
LLVM_ABI Align getPrefTypeAlign(Type *Ty) const
Returns the preferred stack/global alignment for the specified type.
A debug info location.
Definition DebugLoc.h:126
Implements a dense probed hash-table based set.
Definition DenseSet.h:281
const char * getSymbol() const
This class is used to gather all the unique data bits of a node.
Definition FoldingSet.h:208
void AddInteger(signed I)
Definition FoldingSet.h:237
void AddPointer(const void *Ptr)
Add* - Add various data types to Bit data.
Definition FoldingSet.h:228
Data structure describing the variable locations in a function.
bool hasMinSize() const
Optimize this function for minimum size (-Oz).
Definition Function.h:688
AttributeList getAttributes() const
Return the attribute list for this Function.
Definition Function.h:328
LLVM_ABI unsigned getAddressSpace() const
const GlobalValue * getGlobal() const
bool isThreadLocal() const
If the value is "Thread Local", its value isn't shared by the threads.
unsigned getAddressSpace() const
Module * getParent()
Get the module that this global value is contained inside of...
PointerType * getType() const
Global values are always pointers.
This class is used to form a handle around another node that is persistent and is updated across invo...
const SDValue & getValue() const
static LLVM_ABI bool compare(const APInt &LHS, const APInt &RHS, ICmpInst::Predicate Pred)
Return result of LHS Pred RHS comparison.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
Tracks which library functions to use for a particular subtarget.
CallingConv::ID getLibcallImplCallingConv(RTLIB::LibcallImpl Call) const
Get the CallingConv that should be used for the specified libcall.
RTLIB::LibcallImpl getLibcallImpl(RTLIB::Libcall Call) const
Return the lowering's selection of implementation call for Call.
This SDNode is used for LIFETIME_START/LIFETIME_END values.
This class is used to represent ISD::LOAD nodes.
static LocationSize precise(uint64_t Value)
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition MCSymbol.h:42
Metadata node.
Definition Metadata.h:1069
const MDOperand & getOperand(unsigned I) const
Definition Metadata.h:1426
Machine Value Type.
SimpleValueType SimpleTy
static MVT getIntegerVT(unsigned BitWidth)
Abstract base class for all machine specific constantpool value subclasses.
virtual void addSelectionDAGCSEId(FoldingSetNodeID &ID)=0
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted.
LLVM_ABI int CreateStackObject(uint64_t Size, Align Alignment, bool isSpillSlot, const AllocaInst *Alloca=nullptr, uint8_t ID=0)
Create a new statically sized stack object, returning a nonnegative identifier to represent it.
Align getObjectAlign(int ObjectIdx) const
Return the alignment of the specified stack object.
bool isFixedObjectIndex(int ObjectIdx) const
Returns true if the specified index corresponds to a fixed stack object.
void setObjectAlignment(int ObjectIdx, Align Alignment)
setObjectAlignment - Change the alignment of the specified stack object.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
Function & getFunction()
Return the LLVM function that this machine code represents.
const TargetMachine & getTarget() const
getTarget - Return the target machine this machine code is compiled with
A description of a memory reference used in the backend.
const MDNode * getRanges() const
Return the range tag for the memory reference.
Flags
Flags values. These may be or'd together.
@ MOVolatile
The memory access is volatile.
@ MODereferenceable
The memory access is dereferenceable (i.e., doesn't trap).
@ MOLoad
The memory access reads data.
@ MOInvariant
The memory access always returns the same value (or traps).
@ MOStore
The memory access writes data.
const MachinePointerInfo & getPointerInfo() const
Flags getFlags() const
Return the raw flags of the source value,.
This class contains meta information specific to a module.
An SDNode that represents everything that will be needed to construct a MachineInstr.
This class is used to represent an MGATHER node.
This class is used to represent an MLOAD node.
This class is used to represent an MSCATTER 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.
size_t getNumMemOperands() const
Return the number of memory operands.
LLVM_ABI MemSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl, SDVTList VTs, EVT memvt, PointerUnion< MachineMemOperand *, MachineMemOperand ** > memrefs)
Constructor that supports single or multiple MMOs.
PointerUnion< MachineMemOperand *, MachineMemOperand ** > MemRefs
Memory reference information.
MachineMemOperand * getMemOperand() const
Return the unique MachineMemOperand object describing the memory reference performed by operation.
const MachinePointerInfo & getPointerInfo() const
ArrayRef< MachineMemOperand * > memoperands() const
Return the memory operands for this node.
unsigned getRawSubclassData() const
Return the SubclassData value, without HasDebugValue.
EVT getMemoryVT() const
Return the type of the in-memory value.
Representation for a specific memory location.
Root of the metadata hierarchy.
Definition Metadata.h:64
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
Function * getFunction(StringRef Name) const
Look up the specified function in the module symbol table.
Definition Module.cpp:235
Represent a mutable reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:294
The optimization diagnostic interface.
Pass interface - Implemented by all 'passes'.
Definition Pass.h:99
Class to represent pointers.
static PointerType * getUnqual(LLVMContext &C)
This constructs an opaque pointer to an object in the default address space (address space zero).
static LLVM_ABI PointerType * get(LLVMContext &C, unsigned AddressSpace)
This constructs an opaque pointer to an object in a numbered address space.
Definition Type.cpp:911
unsigned getAddressSpace() const
Return the address space of the Pointer type.
A discriminated union of two or more pointer types, with the discriminator in the low bits of the poi...
bool isNull() const
Test if the pointer held in the union is null, regardless of which type it is.
Analysis providing profile information.
void Deallocate(SubClass *E)
Deallocate - Release storage for the pointed-to object.
Wrapper class representing virtual and physical registers.
Definition Register.h:20
Keeps track of dbg_value information through SDISel.
LLVM_ABI void add(SDDbgValue *V, bool isParameter)
LLVM_ABI void erase(const SDNode *Node)
Invalidate all DbgValues attached to the node and remove it from the Node-to-DbgValues map.
Holds the information from a dbg_label node through SDISel.
Holds the information for a single machine location through SDISel; either an SDNode,...
static SDDbgOperand fromNode(SDNode *Node, unsigned ResNo)
static SDDbgOperand fromFrameIdx(unsigned FrameIdx)
static SDDbgOperand fromVReg(Register VReg)
static SDDbgOperand fromConst(const Value *Const)
@ SDNODE
Value is the result of an expression.
Holds the information from a dbg_value node through SDISel.
Wrapper class for IR location info (IR ordering and DebugLoc) to be passed into SDNode creation funct...
const DebugLoc & getDebugLoc() const
unsigned getIROrder() const
This class provides iterator support for SDUse operands that use a specific SDNode.
Represents one node in the SelectionDAG.
ArrayRef< SDUse > ops() const
const APInt & getAsAPIntVal() const
Helper method returns the APInt value of a ConstantSDNode.
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
LLVM_ABI void Profile(FoldingSetNodeID &ID) const
Gather unique data for the node.
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 getVPZeroExtendInReg(SDValue Op, SDValue Mask, SDValue EVL, const SDLoc &DL, EVT VT)
Return the expression required to zero extend the Op value assuming it was the smaller SrcTy value.
LLVM_ABI SDValue getShiftAmountOperand(EVT LHSTy, SDValue Op)
Return the specified value casted to the target's desired shift amount type.
LLVM_ABI std::pair< SDValue, SDValue > getMemccpy(SDValue Chain, const SDLoc &dl, SDValue Dst, SDValue Src, SDValue C, SDValue Size, const CallInst *CI)
Lower a memccpy operation into a target library call and return the resulting chain and call result a...
LLVM_ABI bool isKnownNeverLogicalZero(SDValue Op, const APInt &DemandedElts, unsigned Depth=0) const
Test whether the given floating point SDValue (or all elements of it, if it is a vector) is known to ...
LLVM_ABI SDValue getExtLoadVP(ISD::LoadExtType ExtType, const SDLoc &dl, EVT VT, SDValue Chain, SDValue Ptr, SDValue Mask, SDValue EVL, MachinePointerInfo PtrInfo, EVT MemVT, MaybeAlign Alignment, MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo, bool IsExpanding=false)
SDValue getExtractVectorElt(const SDLoc &DL, EVT VT, SDValue Vec, unsigned Idx)
Extract element at Idx from Vec.
LLVM_ABI SDValue getSplatSourceVector(SDValue V, int &SplatIndex)
If V is a splatted value, return the source vector and its splat index.
LLVM_ABI SDValue getLabelNode(unsigned Opcode, const SDLoc &dl, SDValue Root, MCSymbol *Label)
LLVM_ABI OverflowKind computeOverflowForUnsignedSub(SDValue N0, SDValue N1) const
Determine if the result of the unsigned sub of 2 nodes can overflow.
LLVM_ABI unsigned ComputeMaxSignificantBits(SDValue Op, unsigned Depth=0) const
Get the upper bound on bit size for this Value Op as a signed integer.
const SDValue & getRoot() const
Return the root tag of the SelectionDAG.
LLVM_ABI std::pair< SDValue, SDValue > getStrlen(SDValue Chain, const SDLoc &dl, SDValue Src, const CallInst *CI)
Lower a strlen operation into a target library call and return the resulting chain and call result as...
LLVM_ABI SDValue getMaskedGather(SDVTList VTs, EVT MemVT, const SDLoc &dl, ArrayRef< SDValue > Ops, MachineMemOperand *MMO, ISD::MemIndexType IndexType, ISD::LoadExtType ExtTy)
LLVM_ABI SDValue getAddrSpaceCast(const SDLoc &dl, EVT VT, SDValue Ptr, unsigned SrcAS, unsigned DestAS)
Return an AddrSpaceCastSDNode.
LLVM_ABI SDValue FoldSetCC(EVT VT, SDValue N1, SDValue N2, ISD::CondCode Cond, const SDLoc &dl, SDNodeFlags Flags={})
Constant fold a setcc to true or false.
bool isKnownNeverSNaN(SDValue Op, const APInt &DemandedElts, unsigned Depth=0) const
LLVM_ABI std::optional< bool > isBoolConstant(SDValue N) const
Check if a value \op N is a constant using the target's BooleanContent for its type.
LLVM_ABI SDValue getStackArgumentTokenFactor(SDValue Chain)
Compute a TokenFactor to force all the incoming stack arguments to be loaded from the stack.
const TargetSubtargetInfo & getSubtarget() const
LLVM_ABI ConstantRange computeConstantRange(SDValue Op, bool ForSigned, unsigned Depth=0) const
Determine the possible constant range of an integer or vector of integers.
LLVM_ABI SDValue getMergeValues(ArrayRef< SDValue > Ops, const SDLoc &dl)
Create a MERGE_VALUES node from the given operands.
LLVM_ABI SDVTList getVTList(EVT VT)
Return an SDVTList that represents the list of values specified.
LLVM_ABI SDValue getShiftAmountConstant(uint64_t Val, EVT VT, const SDLoc &DL)
LLVM_ABI void updateDivergence(SDNode *N)
LLVM_ABI SDValue getSplatValue(SDValue V, bool LegalTypes=false)
If V is a splat vector, return its scalar source operand by extracting that element from the source v...
LLVM_ABI SDValue getAllOnesConstant(const SDLoc &DL, EVT VT, bool IsTarget=false, bool IsOpaque=false)
LLVM_ABI MachineSDNode * getMachineNode(unsigned Opcode, const SDLoc &dl, EVT VT)
These are used for target selectors to create a new node with specified return type(s),...
LLVM_ABI void ExtractVectorElements(SDValue Op, SmallVectorImpl< SDValue > &Args, unsigned Start=0, unsigned Count=0, EVT EltVT=EVT())
Append the extracted elements from Start to Count out of the vector Op in Args.
LLVM_ABI SDValue getAtomicMemset(SDValue Chain, const SDLoc &dl, SDValue Dst, SDValue Value, SDValue Size, Type *SizeTy, unsigned ElemSz, bool isTailCall, MachinePointerInfo DstPtrInfo)
LLVM_ABI SDValue getAtomicLoad(ISD::LoadExtType ExtType, const SDLoc &dl, EVT MemVT, EVT VT, SDValue Chain, SDValue Ptr, MachineMemOperand *MMO)
LLVM_ABI SDNode * getNodeIfExists(unsigned Opcode, SDVTList VTList, ArrayRef< SDValue > Ops, const SDNodeFlags Flags, bool AllowCommute=false)
Get the specified node if it's already available, or else return NULL.
LLVM_ABI SDValue getPseudoProbeNode(const SDLoc &Dl, SDValue Chain, uint64_t Guid, uint64_t Index, uint32_t Attr)
Creates a PseudoProbeSDNode with function GUID Guid and the index of the block Index it is probing,...
LLVM_ABI SDValue getFreeze(SDValue V)
Return a freeze using the SDLoc of the value operand.
LLVM_ABI SDNode * SelectNodeTo(SDNode *N, unsigned MachineOpc, EVT VT)
These are used for target selectors to mutate the specified node to have the specified return type,...
LLVM_ABI void init(MachineFunction &NewMF, OptimizationRemarkEmitter &NewORE, Pass *PassPtr, const TargetLibraryInfo *LibraryInfo, const LibcallLoweringInfo *LibcallsInfo, UniformityInfo *UA, ProfileSummaryInfo *PSIin, BlockFrequencyInfo *BFIin, MachineModuleInfo &MMI, FunctionVarLocs const *FnVarLocs)
Prepare this SelectionDAG to process code in the given MachineFunction.
LLVM_ABI SelectionDAG(const TargetMachine &TM, CodeGenOptLevel)
LLVM_ABI SDValue getMemset(SDValue Chain, const SDLoc &dl, SDValue Dst, SDValue Src, SDValue Size, Align Alignment, bool isVol, bool AlwaysInline, const CallInst *CI, MachinePointerInfo DstPtrInfo, const AAMDNodes &AAInfo=AAMDNodes())
LLVM_ABI SDValue getBitcastedSExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of integer type, to the integer type VT, by first bitcasting (from potentia...
LLVM_ABI SDValue getConstantPool(const Constant *C, EVT VT, MaybeAlign Align=std::nullopt, int Offs=0, bool isT=false, unsigned TargetFlags=0)
LLVM_ABI SDValue getStridedLoadVP(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &DL, SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Stride, SDValue Mask, SDValue EVL, EVT MemVT, MachineMemOperand *MMO, bool IsExpanding=false)
LLVM_ABI SDValue getAtomicCmpSwap(unsigned Opcode, const SDLoc &dl, EVT MemVT, SDVTList VTs, SDValue Chain, SDValue Ptr, SDValue Cmp, SDValue Swp, MachineMemOperand *MMO)
Gets a node for an atomic cmpxchg op.
LLVM_ABI SDValue makeEquivalentMemoryOrdering(SDValue OldChain, SDValue NewMemOpChain)
If an existing load has uses of its chain, create a token factor node with that chain and the new mem...
LLVM_ABI bool isConstantIntBuildVectorOrConstantInt(SDValue N, bool AllowOpaques=true) const
Test whether the given value is a constant int or similar node.
LLVM_ABI void ReplaceAllUsesOfValuesWith(const SDValue *From, const SDValue *To, unsigned Num)
Like ReplaceAllUsesOfValueWith, but for multiple values at once.
LLVM_ABI SDValue getJumpTableDebugInfo(int JTI, SDValue Chain, const SDLoc &DL)
LLVM_ABI SDValue getSymbolFunctionGlobalAddress(SDValue Op, Function **TargetFunction=nullptr)
Return a GlobalAddress of the function from the current module with name matching the given ExternalS...
LLVM_ABI std::optional< unsigned > getValidMaximumShiftAmount(SDValue V, const APInt &DemandedElts, unsigned Depth=0) const
If a SHL/SRA/SRL node V has shift amounts that are all less than the element bit-width of the shift n...
LLVM_ABI SDValue UnrollVectorOp(SDNode *N, unsigned ResNE=0)
Utility function used by legalize and lowering to "unroll" a vector operation by splitting out the sc...
LLVM_ABI SDValue getVScale(const SDLoc &DL, EVT VT, APInt MulImm)
Return a node that represents the runtime scaling 'MulImm * RuntimeVL'.
LLVM_ABI SDValue getConstantFP(double Val, const SDLoc &DL, EVT VT, bool isTarget=false)
Create a ConstantFPSDNode wrapping a constant value.
OverflowKind
Used to represent the possible overflow behavior of an operation.
static LLVM_ABI unsigned getHasPredecessorMaxSteps()
LLVM_ABI bool haveNoCommonBitsSet(SDValue A, SDValue B) const
Return true if A and B have no common bits set.
SDValue getExtractSubvector(const SDLoc &DL, EVT VT, SDValue Vec, unsigned Idx)
Return the VT typed sub-vector of Vec at Idx.
LLVM_ABI bool cannotBeOrderedNegativeFP(SDValue Op) const
Test whether the given float value is known to be positive.
LLVM_ABI SDValue getRegister(Register Reg, EVT VT)
LLVM_ABI bool calculateDivergence(SDNode *N)
LLVM_ABI std::pair< SDValue, SDValue > getStrcmp(SDValue Chain, const SDLoc &dl, SDValue S0, SDValue S1, const CallInst *CI)
Lower a strcmp operation into a target library call and return the resulting chain and call result as...
LLVM_ABI SDValue getGetFPEnv(SDValue Chain, const SDLoc &dl, SDValue Ptr, EVT MemVT, MachineMemOperand *MMO)
LLVM_ABI SDValue getAssertAlign(const SDLoc &DL, SDValue V, Align A)
Return an AssertAlignSDNode.
LLVM_ABI SDNode * mutateStrictFPToFP(SDNode *Node)
Mutate the specified strict FP node to its non-strict equivalent, unlinking the node from its chain a...
LLVM_ABI bool canIgnoreSignBitOfZero(const SDUse &Use) const
Check if a use of a float value is insensitive to signed zeros.
LLVM_ABI bool SignBitIsZeroFP(SDValue Op, unsigned Depth=0) const
Return true if the sign bit of Op is known to be zero, for a floating-point value.
LLVM_ABI SDValue getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef< SDValue > Ops, EVT MemVT, MachinePointerInfo PtrInfo, Align Alignment, MachineMemOperand::Flags Flags=MachineMemOperand::MOLoad|MachineMemOperand::MOStore, LocationSize Size=LocationSize::precise(0), const AAMDNodes &AAInfo=AAMDNodes())
Creates a MemIntrinsicNode that may produce a result and takes a list of operands.
SDValue getInsertSubvector(const SDLoc &DL, SDValue Vec, SDValue SubVec, unsigned Idx)
Insert SubVec at the Idx element of Vec.
LLVM_ABI SDValue getBitcastedZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of integer type, to the integer type VT, by first bitcasting (from potentia...
LLVM_ABI SDValue getStepVector(const SDLoc &DL, EVT ResVT, const APInt &StepVal)
Returns a vector of type ResVT whose elements contain the linear sequence <0, Step,...
SDValue getSetCC(const SDLoc &DL, EVT VT, SDValue LHS, SDValue RHS, ISD::CondCode Cond, SDValue Chain=SDValue(), bool IsSignaling=false, SDNodeFlags Flags={})
Helper function to make it easier to build SetCC's if you just have an ISD::CondCode instead of an SD...
LLVM_ABI SDValue getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT, SDValue Chain, SDValue Ptr, SDValue Val, MachineMemOperand *MMO)
Gets a node for an atomic op, produces result (if relevant) and chain and takes 2 operands.
LLVM_ABI Align getEVTAlign(EVT MemoryVT) const
Compute the default alignment value for the given type.
LLVM_ABI bool shouldOptForSize() const
bool hasSwiftErrorArg() const
LLVM_ABI SDValue getNOT(const SDLoc &DL, SDValue Val, EVT VT)
Create a bitwise NOT operation as (XOR Val, -1).
LLVM_ABI SDValue getVPZExtOrTrunc(const SDLoc &DL, EVT VT, SDValue Op, SDValue Mask, SDValue EVL)
Convert a vector-predicated Op, which must be an integer vector, to the vector-type VT,...
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 SDValue getStridedStoreVP(SDValue Chain, const SDLoc &DL, SDValue Val, SDValue Ptr, SDValue Offset, SDValue Stride, SDValue Mask, SDValue EVL, EVT MemVT, MachineMemOperand *MMO, ISD::MemIndexedMode AM, bool IsTruncating=false, bool IsCompressing=false)
bool isGuaranteedNotToBePoison(SDValue Op, unsigned Depth=0) const
Return true if this function can prove that Op is never poison.
LLVM_ABI SDValue getIdentityElement(unsigned Opcode, const SDLoc &DL, EVT VT, SDNodeFlags Flags)
Get the (commutative) identity element for the given opcode, if it exists.
LLVM_ABI SDValue expandVACopy(SDNode *Node)
Expand the specified ISD::VACOPY node as the Legalize pass would.
LLVM_ABI SDValue getIndexedMaskedLoad(SDValue OrigLoad, const SDLoc &dl, SDValue Base, SDValue Offset, ISD::MemIndexedMode AM)
LLVM_ABI APInt computeVectorKnownZeroElements(SDValue Op, const APInt &DemandedElts, unsigned Depth=0) const
For each demanded element of a vector, see if it is known to be zero.
LLVM_ABI void AddDbgValue(SDDbgValue *DB, bool isParameter)
Add a dbg_value SDNode.
bool NewNodesMustHaveLegalTypes
When true, additional steps are taken to ensure that getConstant() and similar functions return DAG n...
LLVM_ABI std::pair< EVT, EVT > GetSplitDestVTs(const EVT &VT) const
Compute the VTs needed for the low/hi parts of a type which is split (or expanded) into two not neces...
LLVM_ABI void salvageDebugInfo(SDNode &N)
To be invoked on an SDNode that is slated to be erased.
LLVM_ABI SDNode * MorphNodeTo(SDNode *N, unsigned Opc, SDVTList VTs, ArrayRef< SDValue > Ops)
This mutates the specified node to have the specified return type, opcode, and operands.
LLVM_ABI std::pair< SDValue, SDValue > UnrollVectorOverflowOp(SDNode *N, unsigned ResNE=0)
Like UnrollVectorOp(), but for the [US](ADD|SUB|MUL)O family of opcodes.
allnodes_const_iterator allnodes_begin() const
SDValue getUNDEF(EVT VT)
Return an UNDEF node. UNDEF does not have a useful SDLoc.
LLVM_ABI SDValue getGatherVP(SDVTList VTs, EVT VT, const SDLoc &dl, ArrayRef< SDValue > Ops, MachineMemOperand *MMO, ISD::MemIndexType IndexType)
SDValue getBuildVector(EVT VT, const SDLoc &DL, ArrayRef< SDValue > Ops)
Return an ISD::BUILD_VECTOR node.
LLVM_ABI SDValue getBitcastedAnyExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of integer type, to the integer type VT, by first bitcasting (from potentia...
LLVM_ABI bool isSplatValue(SDValue V, const APInt &DemandedElts, APInt &UndefElts, unsigned Depth=0) const
Test whether V has a splatted value for all the demanded elements.
LLVM_ABI void DeleteNode(SDNode *N)
Remove the specified node from the system.
LLVM_ABI SDValue getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val, SDValue Ptr, SDValue Offset, MachinePointerInfo PtrInfo, EVT SVT, Align Alignment, MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const MMOMetadata &Metadata=MMOMetadata())
LLVM_ABI SDValue getBitcast(EVT VT, SDValue V)
Return a bitcast using the SDLoc of the value operand, and casting to the provided type.
LLVM_ABI SDDbgValue * getDbgValueList(DIVariable *Var, DIExpression *Expr, ArrayRef< SDDbgOperand > Locs, ArrayRef< SDNode * > Dependencies, bool IsIndirect, const DebugLoc &DL, unsigned O, bool IsVariadic)
Creates a SDDbgValue node from a list of locations.
LLVM_ABI std::pair< SDValue, SDValue > getStrcpy(SDValue Chain, const SDLoc &dl, SDValue Dst, SDValue Src, const CallInst *CI)
Lower a strcpy operation into a target library call and return the resulting chain and call result as...
SDValue getSelect(const SDLoc &DL, EVT VT, SDValue Cond, SDValue LHS, SDValue RHS, SDNodeFlags Flags=SDNodeFlags())
Helper function to make it easier to build Select's if you just have operands and don't want to check...
LLVM_ABI SDValue getNegative(SDValue Val, const SDLoc &DL, EVT VT)
Create negative operation as (SUB 0, Val).
LLVM_ABI std::optional< unsigned > getValidShiftAmount(SDValue V, const APInt &DemandedElts, unsigned Depth=0) const
If a SHL/SRA/SRL node V has a uniform shift amount that is less than the element bit-width of the shi...
LLVM_ABI void setNodeMemRefs(MachineSDNode *N, ArrayRef< MachineMemOperand * > NewMemRefs)
Mutate the specified machine node's memory references to the provided list.
LLVM_ABI SDValue simplifySelect(SDValue Cond, SDValue TVal, SDValue FVal)
Try to simplify a select/vselect into 1 of its operands or a constant.
LLVM_ABI SDValue getZeroExtendInReg(SDValue Op, const SDLoc &DL, EVT VT)
Return the expression required to zero extend the Op value assuming it was the smaller SrcTy value.
LLVM_ABI bool isConstantFPBuildVectorOrConstantFP(SDValue N) const
Test whether the given value is a constant FP or similar node.
const DataLayout & getDataLayout() const
LLVM_ABI SDValue getPartialReduceMLS(unsigned Opc, const SDLoc &DL, SDValue Acc, SDValue LHS, SDValue RHS)
Get an expression that implements a partial multiply-subtract reduction.
LLVM_ABI SDValue expandVAArg(SDNode *Node)
Expand the specified ISD::VAARG node as the Legalize pass would.
LLVM_ABI SDValue getTokenFactor(const SDLoc &DL, SmallVectorImpl< SDValue > &Vals)
Creates a new TokenFactor containing Vals.
LLVM_ABI SDValue getStore(SDValue Chain, const SDLoc &dl, SDValue Val, SDValue Ptr, MachinePointerInfo PtrInfo, Align Alignment, MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const MMOMetadata &Metadata=MMOMetadata())
Helper function to build ISD::STORE nodes.
LLVM_ABI bool doesNodeExist(unsigned Opcode, SDVTList VTList, ArrayRef< SDValue > Ops)
Check if a node exists without modifying its flags.
LLVM_ABI ConstantRange computeConstantRangeIncludingKnownBits(SDValue Op, bool ForSigned, unsigned Depth=0) const
Combine constant ranges from computeConstantRange() and computeKnownBits().
const SelectionDAGTargetInfo & getSelectionDAGInfo() const
LLVM_ABI bool areNonVolatileConsecutiveLoads(LoadSDNode *LD, LoadSDNode *Base, unsigned Bytes, int Dist) const
Return true if loads are next to each other and can be merged.
LLVM_ABI SDValue getMaskedHistogram(SDVTList VTs, EVT MemVT, const SDLoc &dl, ArrayRef< SDValue > Ops, MachineMemOperand *MMO, ISD::MemIndexType IndexType)
LLVM_ABI SDDbgLabel * getDbgLabel(DILabel *Label, const DebugLoc &DL, unsigned O)
Creates a SDDbgLabel node.
LLVM_ABI SDValue getStoreVP(SDValue Chain, const SDLoc &dl, SDValue Val, SDValue Ptr, SDValue Offset, SDValue Mask, SDValue EVL, EVT MemVT, MachineMemOperand *MMO, ISD::MemIndexedMode AM, bool IsTruncating=false, bool IsCompressing=false)
LLVM_ABI OverflowKind computeOverflowForUnsignedMul(SDValue N0, SDValue N1) const
Determine if the result of the unsigned mul of 2 nodes can overflow.
LLVM_ABI void copyExtraInfo(SDNode *From, SDNode *To)
Copy extra info associated with one node to another.
LLVM_ABI SDValue getConstant(uint64_t Val, const SDLoc &DL, EVT VT, bool isTarget=false, bool isOpaque=false)
Create a ConstantSDNode wrapping a constant value.
LLVM_ABI SDValue getMemBasePlusOffset(SDValue Base, TypeSize Offset, const SDLoc &DL, const SDNodeFlags Flags=SDNodeFlags())
Returns sum of the base pointer and offset.
LLVM_ABI SDValue getGlobalAddress(const GlobalValue *GV, const SDLoc &DL, EVT VT, int64_t offset=0, bool isTargetGA=false, unsigned TargetFlags=0)
LLVM_ABI SDValue getVAArg(EVT VT, const SDLoc &dl, SDValue Chain, SDValue Ptr, SDValue SV, unsigned Align)
VAArg produces a result and token chain, and takes a pointer and a source value as input.
LLVM_ABI SDValue getLoadFFVP(EVT VT, const SDLoc &DL, SDValue Chain, SDValue Ptr, SDValue Mask, SDValue EVL, MachineMemOperand *MMO)
LLVM_ABI SDValue getTypeSize(const SDLoc &DL, EVT VT, TypeSize TS)
LLVM_ABI SDValue getMDNode(const MDNode *MD)
Return an MDNodeSDNode which holds an MDNode.
LLVM_ABI void clear()
Clear state and free memory necessary to make this SelectionDAG ready to process a new block.
LLVM_ABI std::pair< SDValue, SDValue > getMemcmp(SDValue Chain, const SDLoc &dl, SDValue Dst, SDValue Src, SDValue Size, const CallInst *CI)
Lower a memcmp operation into a target library call and return the resulting chain and call result as...
LLVM_ABI void ReplaceAllUsesWith(SDValue From, SDValue To)
Modify anything using 'From' to use 'To' instead.
LLVM_ABI SDValue getCommutedVectorShuffle(const ShuffleVectorSDNode &SV)
Returns an ISD::VECTOR_SHUFFLE node semantically equivalent to the shuffle node in input but with swa...
LLVM_ABI SDValue getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl, EVT VT, SDValue Chain, SDValue Ptr, MachinePointerInfo PtrInfo, EVT MemVT, MaybeAlign Alignment=MaybeAlign(), MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const MMOMetadata &Metadata=MMOMetadata())
LLVM_ABI std::pair< SDValue, SDValue > SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT, const EVT &HiVT)
Split the vector with EXTRACT_SUBVECTOR using the provided VTs and return the low/high part.
LLVM_ABI SDValue makeStateFunctionCall(unsigned LibFunc, SDValue Ptr, SDValue InChain, const SDLoc &DLoc)
Helper used to make a call to a library function that has one argument of pointer type.
LLVM_ABI SDValue getSignedConstant(int64_t Val, const SDLoc &DL, EVT VT, bool isTarget=false, bool isOpaque=false)
LLVM_ABI SDValue getIndexedLoadVP(SDValue OrigLoad, const SDLoc &dl, SDValue Base, SDValue Offset, ISD::MemIndexedMode AM)
LLVM_ABI SDValue getSrcValue(const Value *v)
Construct a node to track a Value* through the backend.
SDValue getSplatVector(EVT VT, const SDLoc &DL, SDValue Op)
LLVM_ABI SDValue getAtomicMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst, SDValue Src, SDValue Size, Type *SizeTy, unsigned ElemSz, bool isTailCall, MachinePointerInfo DstPtrInfo, MachinePointerInfo SrcPtrInfo)
LLVM_ABI OverflowKind computeOverflowForSignedMul(SDValue N0, SDValue N1) const
Determine if the result of the signed mul of 2 nodes can overflow.
LLVM_ABI MaybeAlign InferPtrAlign(SDValue Ptr) const
Infer alignment of a load / store address.
LLVM_ABI void dump() const
Dump the textual format of this DAG.
LLVM_ABI bool MaskedValueIsAllOnes(SDValue Op, const APInt &Mask, unsigned Depth=0) const
Return true if '(Op & Mask) == Mask'.
LLVM_ABI bool SignBitIsZero(SDValue Op, unsigned Depth=0) const
Return true if the sign bit of Op is known to be zero.
LLVM_ABI void RemoveDeadNodes()
This method deletes all unreachable nodes in the SelectionDAG.
LLVM_ABI void RemoveDeadNode(SDNode *N)
Remove the specified node from the system.
LLVM_ABI void AddDbgLabel(SDDbgLabel *DB)
Add a dbg_label SDNode.
bool isConstantValueOfAnyType(SDValue N) const
LLVM_ABI bool canCreateUndefOrPoison(SDValue Op, const APInt &DemandedElts, UndefPoisonKind Kind=UndefPoisonKind::UndefOrPoison, bool ConsiderFlags=true, unsigned Depth=0) const
Return true if Op can create undef or poison from non-undef & non-poison operands.
LLVM_ABI SDValue getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT, SDValue Operand)
A convenience function for creating TargetInstrInfo::EXTRACT_SUBREG nodes.
LLVM_ABI SDValue getBasicBlock(MachineBasicBlock *MBB)
LLVM_ABI SDValue getSExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of integer type, to the integer type VT, by either sign-extending or trunca...
LLVM_ABI SDDbgValue * getVRegDbgValue(DIVariable *Var, DIExpression *Expr, Register VReg, bool IsIndirect, const DebugLoc &DL, unsigned O)
Creates a VReg SDDbgValue node.
LLVM_ABI SDValue getLoad(EVT VT, const SDLoc &dl, SDValue Chain, SDValue Ptr, MachinePointerInfo PtrInfo, MaybeAlign Alignment=MaybeAlign(), MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const MMOMetadata &Metadata=MMOMetadata())
Loads are not normal binary operators: their result type is not determined by their operands,...
LLVM_ABI KnownFPClass computeKnownFPClass(SDValue Op, FPClassTest InterestedClasses, unsigned Depth=0) const
Determine floating-point class information about Op.
LLVM_ABI bool isIdentityElement(unsigned Opc, SDNodeFlags Flags, SDValue V, unsigned OperandNo, unsigned Depth=0) const
Returns true if V is an identity element of Opc with Flags.
LLVM_ABI SDValue getEHLabel(const SDLoc &dl, SDValue Root, MCSymbol *Label)
LLVM_ABI SDValue getIndexedStoreVP(SDValue OrigStore, const SDLoc &dl, SDValue Base, SDValue Offset, ISD::MemIndexedMode AM)
LLVM_ABI bool isGuaranteedNotToBeUndefOrPoison(SDValue Op, UndefPoisonKind Kind=UndefPoisonKind::UndefOrPoison, unsigned Depth=0) const
Return true if this function can prove that Op is never poison and, Kind can be used to track poison ...
LLVM_ABI bool isKnownNeverZero(SDValue Op, unsigned Depth=0) const
Test whether the given SDValue is known to contain non-zero value(s).
LLVM_ABI SDValue getIndexedStore(SDValue OrigStore, const SDLoc &dl, SDValue Base, SDValue Offset, ISD::MemIndexedMode AM)
LLVM_ABI SDValue FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL, EVT VT, ArrayRef< SDValue > Ops, SDNodeFlags Flags=SDNodeFlags())
LLVM_ABI std::optional< unsigned > getValidMinimumShiftAmount(SDValue V, const APInt &DemandedElts, unsigned Depth=0) const
If a SHL/SRA/SRL node V has shift amounts that are all less than the element bit-width of the shift n...
LLVM_ABI SDValue getSetFPEnv(SDValue Chain, const SDLoc &dl, SDValue Ptr, EVT MemVT, MachineMemOperand *MMO)
LLVM_ABI SDValue getBoolExtOrTrunc(SDValue Op, const SDLoc &SL, EVT VT, EVT OpVT)
Convert Op, which must be of integer type, to the integer type VT, by using an extension appropriate ...
LLVM_ABI SDValue getMaskedStore(SDValue Chain, const SDLoc &dl, SDValue Val, SDValue Base, SDValue Offset, SDValue Mask, EVT MemVT, MachineMemOperand *MMO, ISD::MemIndexedMode AM, bool IsTruncating=false, bool IsCompressing=false)
LLVM_ABI SDValue getExternalSymbol(const char *Sym, EVT VT)
const TargetMachine & getTarget() const
LLVM_ABI std::pair< SDValue, SDValue > getStrictFPExtendOrRound(SDValue Op, SDValue Chain, const SDLoc &DL, EVT VT)
Convert Op, which must be a STRICT operation of float type, to the float type VT, by either extending...
LLVM_ABI std::pair< SDValue, SDValue > SplitEVL(SDValue N, EVT VecVT, const SDLoc &DL)
Split the explicit vector length parameter of a VP operation.
LLVM_ABI SDValue getPtrExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of integer type, to the integer type VT, by either truncating it or perform...
LLVM_ABI SDValue getVPLogicalNOT(const SDLoc &DL, SDValue Val, SDValue Mask, SDValue EVL, EVT VT)
Create a vector-predicated logical NOT operation as (VP_XOR Val, BooleanOne, Mask,...
LLVM_ABI SDValue getMaskFromElementCount(const SDLoc &DL, EVT VT, ElementCount Len)
Return a vector with the first 'Len' lanes set to true and remaining lanes set to false.
LLVM_ABI SDValue getAnyExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of integer type, to the integer type VT, by either any-extending or truncat...
iterator_range< allnodes_iterator > allnodes()
LLVM_ABI SDValue getBlockAddress(const BlockAddress *BA, EVT VT, int64_t Offset=0, bool isTarget=false, unsigned TargetFlags=0)
LLVM_ABI SDValue WidenVector(const SDValue &N, const SDLoc &DL)
Widen the vector up to the next power of two using INSERT_SUBVECTOR.
const LibcallLoweringInfo & getLibcalls() const
LLVM_ABI SDValue getLoadVP(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &dl, SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Mask, SDValue EVL, MachinePointerInfo PtrInfo, EVT MemVT, Align Alignment, MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo, const MDNode *Ranges=nullptr, bool IsExpanding=false)
LLVM_ABI SDValue getIntPtrConstant(uint64_t Val, const SDLoc &DL, bool isTarget=false)
LLVM_ABI SDDbgValue * getConstantDbgValue(DIVariable *Var, DIExpression *Expr, const Value *C, const DebugLoc &DL, unsigned O)
Creates a constant SDDbgValue node.
LLVM_ABI SDValue getScatterVP(SDVTList VTs, EVT VT, const SDLoc &dl, ArrayRef< SDValue > Ops, MachineMemOperand *MMO, ISD::MemIndexType IndexType)
LLVM_ABI SDValue getValueType(EVT)
LLVM_ABI SDValue getLifetimeNode(bool IsStart, const SDLoc &dl, SDValue Chain, int FrameIndex)
Creates a LifetimeSDNode that starts (IsStart==true) or ends (IsStart==false) the lifetime of the Fra...
ArrayRef< SDDbgValue * > GetDbgValues(const SDNode *SD) const
Get the debug values which reference the given SDNode.
LLVM_ABI SDValue getNode(unsigned Opcode, const SDLoc &DL, EVT VT, ArrayRef< SDUse > Ops)
Gets or creates the specified node.
LLVM_ABI OverflowKind computeOverflowForSignedAdd(SDValue N0, SDValue N1) const
Determine if the result of the signed addition of 2 nodes can overflow.
LLVM_ABI SDValue getFPExtendOrRound(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of float type, to the float type VT, by either extending or rounding (by tr...
LLVM_ABI unsigned AssignTopologicalOrder()
Topological-sort the AllNodes list and a assign a unique node id for each node in the DAG based on th...
ilist< SDNode >::size_type allnodes_size() const
LLVM_ABI bool isKnownNeverNaN(SDValue Op, const APInt &DemandedElts, bool SNaN=false, unsigned Depth=0) const
Test whether the given SDValue (or all elements of it, if it is a vector) is known to never be NaN in...
LLVM_ABI SDValue FoldConstantBuildVector(BuildVectorSDNode *BV, const SDLoc &DL, EVT DstEltVT)
Fold BUILD_VECTOR of constants/undefs to the destination type BUILD_VECTOR of constants/undefs elemen...
LLVM_ABI SDValue getAtomicMemmove(SDValue Chain, const SDLoc &dl, SDValue Dst, SDValue Src, SDValue Size, Type *SizeTy, unsigned ElemSz, bool isTailCall, MachinePointerInfo DstPtrInfo, MachinePointerInfo SrcPtrInfo)
LLVM_ABI SDValue getIndexedMaskedStore(SDValue OrigStore, const SDLoc &dl, SDValue Base, SDValue Offset, ISD::MemIndexedMode AM)
LLVM_ABI SDValue getTruncStoreVP(SDValue Chain, const SDLoc &dl, SDValue Val, SDValue Ptr, SDValue Mask, SDValue EVL, MachinePointerInfo PtrInfo, EVT SVT, Align Alignment, MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo, bool IsCompressing=false)
SDValue getTargetConstant(uint64_t Val, const SDLoc &DL, EVT VT, bool isOpaque=false)
LLVM_ABI unsigned ComputeNumSignBits(SDValue Op, unsigned Depth=0) const
Return the number of times the sign bit of the register is replicated into the other bits.
LLVM_ABI bool MaskedVectorIsZero(SDValue Op, const APInt &DemandedElts, unsigned Depth=0) const
Return true if 'Op' is known to be zero in DemandedElts.
LLVM_ABI SDValue getBoolConstant(bool V, const SDLoc &DL, EVT VT, EVT OpVT)
Create a true or false constant of type VT using the target's BooleanContent for type OpVT.
LLVM_ABI SDDbgValue * getFrameIndexDbgValue(DIVariable *Var, DIExpression *Expr, unsigned FI, bool IsIndirect, const DebugLoc &DL, unsigned O)
Creates a FrameIndex SDDbgValue node.
LLVM_ABI SDValue getExtStridedLoadVP(ISD::LoadExtType ExtType, const SDLoc &DL, EVT VT, SDValue Chain, SDValue Ptr, SDValue Stride, SDValue Mask, SDValue EVL, EVT MemVT, MachineMemOperand *MMO, bool IsExpanding=false)
LLVM_ABI SDValue getMemmove(SDValue Chain, const SDLoc &dl, SDValue Dst, SDValue Src, SDValue Size, Align DstAlign, Align SrcAlign, bool isVol, const CallInst *CI, std::optional< bool > OverrideTailCall, MachinePointerInfo DstPtrInfo, MachinePointerInfo SrcPtrInfo, const AAMDNodes &AAInfo=AAMDNodes(), BatchAAResults *BatchAA=nullptr)
LLVM_ABI SDValue getJumpTable(int JTI, EVT VT, bool isTarget=false, unsigned TargetFlags=0)
LLVM_ABI bool isBaseWithConstantOffset(SDValue Op) const
Return true if the specified operand is an ISD::ADD with a ConstantSDNode on the right-hand side,...
LLVM_ABI SDValue getVPPtrExtOrTrunc(const SDLoc &DL, EVT VT, SDValue Op, SDValue Mask, SDValue EVL)
Convert a vector-predicated Op, which must be of integer type, to the vector-type integer type VT,...
LLVM_ABI SDValue getVectorIdxConstant(uint64_t Val, const SDLoc &DL, bool isTarget=false)
LLVM_ABI void getTopologicallyOrderedNodes(SmallVectorImpl< const SDNode * > &SortedNodes) const
Get all the nodes in their topological order without modifying any states.
LLVM_ABI void ReplaceAllUsesOfValueWith(SDValue From, SDValue To)
Replace any uses of From with To, leaving uses of other values produced by From.getNode() alone.
MachineFunction & getMachineFunction() const
LLVM_ABI std::pair< SDValue, SDValue > getStrstr(SDValue Chain, const SDLoc &dl, SDValue S0, SDValue S1, const CallInst *CI)
Lower a strstr operation into a target library call and return the resulting chain and call result as...
LLVM_ABI SDValue getPtrExtendInReg(SDValue Op, const SDLoc &DL, EVT VT)
Return the expression required to extend the Op as a pointer value assuming it was the smaller SrcTy ...
LLVM_ABI OverflowKind computeOverflowForUnsignedAdd(SDValue N0, SDValue N1) const
Determine if the result of the unsigned addition of 2 nodes can overflow.
SDValue getPOISON(EVT VT)
Return a POISON node. POISON does not have a useful SDLoc.
SDValue getSplatBuildVector(EVT VT, const SDLoc &DL, SDValue Op)
Return a splat ISD::BUILD_VECTOR node, consisting of Op splatted to all elements.
LLVM_ABI SDValue getErrorMergeValues(ArrayRef< EVT > ResultTypes, SDValue Chain, const SDLoc &dl)
Return poison values for each of ResultTypes, substituting Chain for any result of type MVT::Other,...
LLVM_ABI SDValue getFrameIndex(int FI, EVT VT, bool isTarget=false)
LLVM_ABI SDValue getTruncStridedStoreVP(SDValue Chain, const SDLoc &DL, SDValue Val, SDValue Ptr, SDValue Stride, SDValue Mask, SDValue EVL, EVT SVT, MachineMemOperand *MMO, bool IsCompressing=false)
LLVM_ABI void canonicalizeCommutativeBinop(unsigned Opcode, SDValue &N1, SDValue &N2) const
Swap N1 and N2 if Opcode is a commutative binary opcode and the canonical form expects the opposite o...
LLVM_ABI KnownBits computeKnownBits(SDValue Op, unsigned Depth=0) const
Determine which bits of Op are known to be either zero or one and return them in Known.
LLVM_ABI SDValue getRegisterMask(const uint32_t *RegMask)
LLVM_ABI SDValue getZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of integer type, to the integer type VT, by either zero-extending or trunca...
LLVM_ABI SDValue getCondCode(ISD::CondCode Cond)
LLVM_ABI bool MaskedValueIsZero(SDValue Op, const APInt &Mask, unsigned Depth=0) const
Return true if 'Op & Mask' is known to be zero.
LLVM_ABI bool isKnownToBeAPowerOfTwoFP(SDValue Val, unsigned Depth=0) const
Test if the given fp value is known to be an integer power-of-2, either positive or negative.
LLVM_ABI OverflowKind computeOverflowForSignedSub(SDValue N0, SDValue N1) const
Determine if the result of the signed sub of 2 nodes can overflow.
SDValue getObjectPtrOffset(const SDLoc &SL, SDValue Ptr, TypeSize Offset)
Create an add instruction with appropriate flags when used for addressing some offset of an object.
LLVMContext * getContext() const
LLVM_ABI SDValue simplifyFPBinop(unsigned Opcode, SDValue X, SDValue Y, SDNodeFlags Flags)
Try to simplify a floating-point binary operation into 1 of its operands or a constant.
const SDValue & setRoot(SDValue N)
Set the current root tag of the SelectionDAG.
LLVM_ABI bool isKnownToBeAPowerOfTwo(SDValue Val, bool OrZero=false, unsigned Depth=0) const
Test if the given value is known to have exactly one bit set.
LLVM_ABI SDValue getDeactivationSymbol(const GlobalValue *GV)
LLVM_ABI SDValue getTargetExternalSymbol(const char *Sym, EVT VT, unsigned TargetFlags=0)
LLVM_ABI SDValue getMCSymbol(MCSymbol *Sym, EVT VT)
LLVM_ABI bool isUndef(unsigned Opcode, ArrayRef< SDValue > Ops)
Return true if the result of this operation is always undefined.
LLVM_ABI SDValue CreateStackTemporary(TypeSize Bytes, Align Alignment)
Create a stack temporary based on the size in bytes and the alignment.
LLVM_ABI SDNode * UpdateNodeOperands(SDNode *N, SDValue Op)
Mutate the specified node in-place to have the specified operands.
LLVM_ABI std::pair< EVT, EVT > GetDependentSplitDestVTs(const EVT &VT, const EVT &EnvVT, bool *HiIsEmpty) const
Compute the VTs needed for the low/hi parts of a type, dependent on an enveloping VT that has been sp...
LLVM_ABI SDValue foldConstantFPMath(unsigned Opcode, const SDLoc &DL, EVT VT, ArrayRef< SDValue > Ops)
Fold floating-point operations when all operands are constants and/or undefined.
LLVM_ABI std::optional< ConstantRange > getValidShiftAmountRange(SDValue V, const APInt &DemandedElts, unsigned Depth) const
If a SHL/SRA/SRL node V has shift amounts that are all less than the element bit-width of the shift n...
LLVM_ABI SDValue FoldSymbolOffset(unsigned Opcode, EVT VT, const GlobalAddressSDNode *GA, const SDNode *N2)
LLVM_ABI SDValue getIndexedLoad(SDValue OrigLoad, const SDLoc &dl, SDValue Base, SDValue Offset, ISD::MemIndexedMode AM)
LLVM_ABI SDValue getTargetInsertSubreg(int SRIdx, const SDLoc &DL, EVT VT, SDValue Operand, SDValue Subreg)
A convenience function for creating TargetInstrInfo::INSERT_SUBREG nodes.
SDValue getEntryNode() const
Return the token chain corresponding to the entry of the function.
LLVM_ABI SDDbgValue * getDbgValue(DIVariable *Var, DIExpression *Expr, SDNode *N, unsigned R, bool IsIndirect, const DebugLoc &DL, unsigned O)
Creates a SDDbgValue node.
LLVM_ABI SDValue getMaskedLoad(EVT VT, const SDLoc &dl, SDValue Chain, SDValue Base, SDValue Offset, SDValue Mask, SDValue Src0, EVT MemVT, MachineMemOperand *MMO, ISD::MemIndexedMode AM, ISD::LoadExtType, bool IsExpanding=false)
DenormalMode getDenormalMode(EVT VT) const
Return the current function's default denormal handling kind for the given floating point type.
SDValue getSplat(EVT VT, const SDLoc &DL, SDValue Op)
Returns a node representing a splat of one value into all lanes of the provided vector type.
LLVM_ABI std::pair< SDValue, SDValue > SplitScalar(const SDValue &N, const SDLoc &DL, const EVT &LoVT, const EVT &HiVT)
Split the scalar node with EXTRACT_ELEMENT using the provided VTs and return the low/high part.
LLVM_ABI SDValue matchBinOpReduction(SDNode *Extract, ISD::NodeType &BinOp, ArrayRef< ISD::NodeType > CandidateBinOps, bool AllowPartials=false)
Match a binop + shuffle pyramid that represents a horizontal reduction over the elements of a vector ...
LLVM_ABI bool isADDLike(SDValue Op, bool NoWrap=false) const
Return true if the specified operand is an ISD::OR or ISD::XOR node that can be treated as an ISD::AD...
LLVM_ABI SDValue getVectorShuffle(EVT VT, const SDLoc &dl, SDValue N1, SDValue N2, ArrayRef< int > Mask)
Return an ISD::VECTOR_SHUFFLE node.
LLVM_ABI SDValue simplifyShift(SDValue X, SDValue Y)
Try to simplify a shift into 1 of its operands or a constant.
LLVM_ABI void transferDbgValues(SDValue From, SDValue To, unsigned OffsetInBits=0, unsigned SizeInBits=0, bool InvalidateDbg=true)
Transfer debug values from one node to another, while optionally generating fragment expressions for ...
LLVM_ABI SDValue getLogicalNOT(const SDLoc &DL, SDValue Val, EVT VT)
Create a logical NOT operation as (XOR Val, BooleanOne).
LLVM_ABI SDValue getMaskedScatter(SDVTList VTs, EVT MemVT, const SDLoc &dl, ArrayRef< SDValue > Ops, MachineMemOperand *MMO, ISD::MemIndexType IndexType, bool IsTruncating=false)
ilist< SDNode >::iterator allnodes_iterator
This SDNode is used to implement the code generator support for the llvm IR shufflevector instruction...
int getMaskElt(unsigned Idx) const
ArrayRef< int > getMask() const
static void commuteMask(MutableArrayRef< int > Mask)
Change values in a shuffle permute mask assuming the two vector operands have swapped position.
static LLVM_ABI bool isSplatMask(ArrayRef< int > Mask)
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
bool erase(PtrType Ptr)
Remove pointer from the set.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void assign(size_type NumElts, ValueParamT Elt)
reference emplace_back(ArgTypes &&... Args)
void reserve(size_type N)
iterator erase(const_iterator CI)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
This class is used to represent ISD::STORE nodes.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
constexpr const char * data() const
Get a pointer to the start of the string (which may not be null terminated).
Definition StringRef.h:138
Information about stack frame layout on the target.
virtual TargetStackID::Value getStackIDForScalableVectors() const
Returns the StackID that scalable vectors should be associated with.
Align getStackAlign() const
getStackAlignment - This method returns the number of bytes to which the stack pointer must be aligne...
Completely target-dependent object reference.
unsigned getTargetFlags() const
Provides information about what library functions are available for the current target.
virtual bool shouldConvertConstantLoadToIntImm(const APInt &Imm, Type *Ty) const
Return true if it is beneficial to convert a load of a constant to just the constant itself.
const TargetMachine & getTargetMachine() const
virtual bool isZExtFree(Type *FromTy, Type *ToTy) const
Return true if any actual instruction that defines a value of type FromTy implicitly zero-extends the...
unsigned getMaxStoresPerMemcpy(bool OptSize) const
Get maximum # of store operations permitted for llvm.memcpy.
unsigned getMaxStoresPerMemset(bool OptSize) const
Get maximum # of store operations permitted for llvm.memset.
virtual bool allowsMisalignedMemoryAccesses(EVT, unsigned AddrSpace=0, Align Alignment=Align(1), MachineMemOperand::Flags Flags=MachineMemOperand::MONone, unsigned *=nullptr) const
Determine if the target supports unaligned memory accesses.
virtual bool shallExtractConstSplatVectorElementToStore(Type *VectorTy, unsigned ElemSizeInBits, unsigned &Index) const
Return true if the target shall perform extract vector element and store given that the vector is kno...
virtual bool isTruncateFree(Type *FromTy, Type *ToTy) const
Return true if it's free to truncate a value of type FromTy to type ToTy.
virtual EVT getTypeToTransformTo(LLVMContext &Context, EVT VT) const
For types supported by the target, this is an identity function.
bool isTypeLegal(EVT VT) const
Return true if the target has native support for the specified value type.
virtual MVT getPointerTy(const DataLayout &DL, uint32_t AS=0) const
Return the pointer type for the given address space, defaults to the pointer type from the data layou...
BooleanContent
Enum that describes how the target represents true/false values.
virtual unsigned getMaxGluedStoresPerMemcpy() const
Get maximum # of store operations to be glued together.
std::vector< ArgListEntry > ArgListTy
unsigned getMaxStoresPerMemmove(bool OptSize) const
Get maximum # of store operations permitted for llvm.memmove.
virtual bool isLegalStoreImmediate(int64_t Value) const
Return true if the specified immediate is legal for the value input of a store instruction.
static ISD::NodeType getExtendForContent(BooleanContent Content)
This class defines information used to lower LLVM code to legal SelectionDAG operators that the targe...
virtual bool findOptimalMemOpLowering(LLVMContext &Context, std::vector< EVT > &MemOps, unsigned Limit, const MemOp &Op, unsigned DstAS, unsigned SrcAS, const AttributeList &FuncAttributes, EVT *LargestVT=nullptr) const
Determines the optimal series of memory ops to replace the memset / memcpy.
std::pair< SDValue, SDValue > LowerCallTo(CallLoweringInfo &CLI) const
This function lowers an abstract call to a function into an actual call.
Primary interface to the complete machine description for the target machine.
virtual bool isNoopAddrSpaceCast(unsigned SrcAS, unsigned DestAS) const
Returns true if a cast between SrcAS and DestAS is a noop.
const Triple & getTargetTriple() const
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
virtual const SelectionDAGTargetInfo * getSelectionDAGInfo() const
virtual const TargetRegisterInfo * getRegisterInfo() const =0
Return the target's register information.
virtual const TargetLowering * getTargetLowering() const
bool isOSDarwin() const
Is this a "Darwin" OS (macOS, iOS, tvOS, watchOS, DriverKit, XROS, or bridgeOS).
Definition Triple.h:721
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
static constexpr TypeSize getFixed(ScalarTy ExactSize)
Definition TypeSize.h:343
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:288
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:309
static LLVM_ABI Type * getVoidTy(LLVMContext &C)
Definition Type.cpp:282
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
Definition Type.cpp:307
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:197
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.cpp:232
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
LLVM_ABI unsigned getOperandNo() const
Return the operand # of this use in its User.
Definition Use.cpp:36
LLVM_ABI void set(Value *Val)
Definition Value.h:874
User * getUser() const
Returns the User that contains this Use.
Definition Use.h:61
Value * getOperand(unsigned i) const
Definition User.h:207
This class is used to represent an VP_GATHER node.
This class is used to represent a VP_LOAD node.
This class is used to represent an VP_SCATTER node.
This class is used to represent a VP_STORE node.
This class is used to represent an EXPERIMENTAL_VP_STRIDED_LOAD node.
This class is used to represent an EXPERIMENTAL_VP_STRIDED_STORE node.
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:255
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:209
bool contains(const_arg_type_t< ValueT > V) const
Check if the set contains the given element.
Definition DenseSet.h:182
constexpr bool hasKnownScalarFactor(const FixedOrScalableQuantity &RHS) const
Returns true if there exists a value X where RHS.multiplyCoefficientBy(X) will result in a value whos...
Definition TypeSize.h:269
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:200
static constexpr bool isKnownLE(const FixedOrScalableQuantity &LHS, const FixedOrScalableQuantity &RHS)
Definition TypeSize.h:230
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:168
constexpr bool isKnownEven() const
A return value of true indicates we know at compile time that the number of elements (vscale * Min) i...
Definition TypeSize.h:176
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
Definition TypeSize.h:165
constexpr LeafTy divideCoefficientBy(ScalarTy RHS) const
We do not provide the '/' operator here because division for polynomial types does not work in the sa...
Definition TypeSize.h:252
static constexpr bool isKnownGE(const FixedOrScalableQuantity &LHS, const FixedOrScalableQuantity &RHS)
Definition TypeSize.h:237
A raw_ostream that writes to an std::string.
CallInst * Call
Changed
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
LLVM_ABI APInt clmulr(const APInt &LHS, const APInt &RHS)
Perform a reversed carry-less multiply.
Definition APInt.cpp:3232
LLVM_ABI APInt mulhu(const APInt &C1, const APInt &C2)
Performs (2*N)-bit multiplication on zero-extended operands.
Definition APInt.cpp:3162
LLVM_ABI APInt avgCeilU(const APInt &C1, const APInt &C2)
Compute the ceil of the unsigned average of C1 and C2.
Definition APInt.cpp:3149
LLVM_ABI APInt avgFloorU(const APInt &C1, const APInt &C2)
Compute the floor of the unsigned average of C1 and C2.
Definition APInt.cpp:3139
LLVM_ABI APInt pext(const APInt &Val, const APInt &Mask)
Perform a "compress" operation, also known as pext or bext.
Definition APInt.cpp:3242
LLVM_ABI APInt fshr(const APInt &Hi, const APInt &Lo, const APInt &Shift)
Perform a funnel shift right.
Definition APInt.cpp:3213
LLVM_ABI APInt mulhs(const APInt &C1, const APInt &C2)
Performs (2*N)-bit multiplication on sign-extended operands.
Definition APInt.cpp:3154
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:3222
LLVM_ABI APInt pdep(const APInt &Val, const APInt &Mask)
Perform an "expand" operation, also known as pdep or bdep.
Definition APInt.cpp:3252
APInt abds(const APInt &A, const APInt &B)
Determine the absolute difference of two APInts considered to be signed.
Definition APInt.h:2299
LLVM_ABI APInt fshl(const APInt &Hi, const APInt &Lo, const APInt &Shift)
Perform a funnel shift left.
Definition APInt.cpp:3204
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:3040
LLVM_ABI APInt clmulh(const APInt &LHS, const APInt &RHS)
Perform a carry-less multiply, and return high-bits.
Definition APInt.cpp:3237
APInt abdu(const APInt &A, const APInt &B)
Determine the absolute difference of two APInts considered to be unsigned.
Definition APInt.h:2304
LLVM_ABI APInt avgFloorS(const APInt &C1, const APInt &C2)
Compute the floor of the signed average of C1 and C2.
Definition APInt.cpp:3134
LLVM_ABI APInt avgCeilS(const APInt &C1, const APInt &C2)
Compute the ceil of the signed average of C1 and C2.
Definition APInt.cpp:3144
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
LLVM_ABI CondCode getSetCCInverse(CondCode Operation, bool isIntegerLike)
Return the operation corresponding to !(X op Y), where 'op' is a valid SetCC operation.
ISD namespace - This namespace contains an enum which represents all of the SelectionDAG node types a...
Definition ISDOpcodes.h:24
LLVM_ABI CondCode getSetCCAndOperation(CondCode Op1, CondCode Op2, EVT Type)
Return the result of a logical AND between different comparisons of identical values: ((X op1 Y) & (X...
LLVM_ABI bool isConstantSplatVectorAllOnes(const SDNode *N, bool BuildVectorOnly=false)
Return true if the specified node is a BUILD_VECTOR or SPLAT_VECTOR where all of the elements are ~0 ...
bool isNON_EXTLoad(const SDNode *N)
Returns true if the specified node is a non-extending load.
NodeType
ISD::NodeType enum - This enum defines the target-independent operators for a SelectionDAG.
Definition ISDOpcodes.h:41
@ SETCC
SetCC operator - This evaluates to a true value iff the condition is true.
Definition ISDOpcodes.h:829
@ MERGE_VALUES
MERGE_VALUES - This node takes multiple discrete operands and returns them all as its individual resu...
Definition ISDOpcodes.h:261
@ TargetConstantPool
Definition ISDOpcodes.h:189
@ MDNODE_SDNODE
MDNODE_SDNODE - This is a node that holdes an MDNode*, which is used to reference metadata in the IR.
@ STRICT_FSETCC
STRICT_FSETCC/STRICT_FSETCCS - Constrained versions of SETCC, used for floating-point operands only.
Definition ISDOpcodes.h:513
@ PTRADD
PTRADD represents pointer arithmetic semantics, for targets that opt in using shouldPreservePtrArith(...
@ DELETED_NODE
DELETED_NODE - This is an illegal value that is used to catch errors.
Definition ISDOpcodes.h:45
@ POISON
POISON - A poison node.
Definition ISDOpcodes.h:236
@ PARTIAL_REDUCE_SMLA
PARTIAL_REDUCE_[U|S]MLA(Accumulator, Input1, Input2) The partial reduction nodes sign or zero extend ...
@ VECREDUCE_SEQ_FADD
Generic reduction nodes.
@ MLOAD
Masked load and store - consecutive vector load and store operations with additional mask operand tha...
@ FGETSIGN
INT = FGETSIGN(FP) - Return the sign bit of the specified floating point value as an integer 0/1 valu...
Definition ISDOpcodes.h:540
@ SMUL_LOHI
SMUL_LOHI/UMUL_LOHI - Multiply two integers of type iN, producing a signed/unsigned value of type i[2...
Definition ISDOpcodes.h:275
@ INSERT_SUBVECTOR
INSERT_SUBVECTOR(VECTOR1, VECTOR2, IDX) - Returns a vector with VECTOR2 inserted into VECTOR1.
Definition ISDOpcodes.h:602
@ JUMP_TABLE_DEBUG_INFO
JUMP_TABLE_DEBUG_INFO - Jumptable debug info.
@ BSWAP
Byte Swap and Counting operators.
Definition ISDOpcodes.h:789
@ TargetBlockAddress
Definition ISDOpcodes.h:191
@ DEACTIVATION_SYMBOL
Untyped node storing deactivation symbol reference (DeactivationSymbolSDNode).
@ ATOMIC_STORE
OUTCHAIN = ATOMIC_STORE(INCHAIN, val, ptr) This corresponds to "store atomic" instruction.
@ ADDC
Carry-setting nodes for multiple precision addition and subtraction.
Definition ISDOpcodes.h:294
@ FMAD
FMAD - Perform a * b + c, while getting the same result as the separately rounded operations.
Definition ISDOpcodes.h:524
@ ADD
Simple integer binary arithmetic operators.
Definition ISDOpcodes.h:264
@ LOAD
LOAD and STORE have token chains as their first operand, then the same operands as an LLVM load/store...
@ ANY_EXTEND
ANY_EXTEND - Used for integer types. The high bits are undefined.
Definition ISDOpcodes.h:863
@ ATOMIC_LOAD_USUB_COND
@ FMA
FMA - Perform a * b + c with no intermediate rounding step.
Definition ISDOpcodes.h:520
@ FATAN2
FATAN2 - atan2, inspired by libm.
@ INTRINSIC_VOID
OUTCHAIN = INTRINSIC_VOID(INCHAIN, INTRINSICID, arg1, arg2, ...) This node represents a target intrin...
Definition ISDOpcodes.h:220
@ GlobalAddress
Definition ISDOpcodes.h:88
@ ATOMIC_CMP_SWAP_WITH_SUCCESS
Val, Success, OUTCHAIN = ATOMIC_CMP_SWAP_WITH_SUCCESS(INCHAIN, ptr, cmp, swap) N.b.
@ SINT_TO_FP
[SU]INT_TO_FP - These operators convert integers (whose interpreted sign depends on the first letter)...
Definition ISDOpcodes.h:890
@ CONCAT_VECTORS
CONCAT_VECTORS(VECTOR0, VECTOR1, ...) - Given a number of values of vector type with the same length ...
Definition ISDOpcodes.h:586
@ VECREDUCE_FMAX
FMIN/FMAX nodes can have flags, for NaN/NoNaN variants.
@ FADD
Simple binary floating point operators.
Definition ISDOpcodes.h:417
@ VECREDUCE_FMAXIMUM
FMINIMUM/FMAXIMUM nodes propatate NaNs and signed zeroes using the llvm.minimum and llvm....
@ ABS
ABS - Determine the unsigned absolute value of a signed integer value of the same bitwidth.
Definition ISDOpcodes.h:749
@ SIGN_EXTEND_VECTOR_INREG
SIGN_EXTEND_VECTOR_INREG(Vector) - This operator represents an in-register sign-extension of the low ...
Definition ISDOpcodes.h:920
@ FP16_TO_FP
FP16_TO_FP, FP_TO_FP16 - These operators are used to perform promotions and truncation for half-preci...
@ FMULADD
FMULADD - Performs a * b + c, with, or without, intermediate rounding.
Definition ISDOpcodes.h:530
@ BITCAST
BITCAST - This operator converts between integer, vector and FP values, as if the value was stored to...
@ BUILD_PAIR
BUILD_PAIR - This is the opposite of EXTRACT_ELEMENT in some ways.
Definition ISDOpcodes.h:254
@ CLMUL
Carry-less multiplication operations.
Definition ISDOpcodes.h:780
@ FLDEXP
FLDEXP - ldexp, inspired by libm (op0 * 2**op1).
@ BUILTIN_OP_END
BUILTIN_OP_END - This must be the last enum value in this list.
@ GlobalTLSAddress
Definition ISDOpcodes.h:89
@ SRCVALUE
SRCVALUE - This is a node type that holds a Value* that is used to make reference to a value in the L...
@ EH_LABEL
EH_LABEL - Represents a label in mid basic block used to track locations needed for debug and excepti...
@ ATOMIC_LOAD_USUB_SAT
@ CTLZ_ZERO_POISON
Definition ISDOpcodes.h:798
@ PARTIAL_REDUCE_UMLA
@ SIGN_EXTEND
Conversion operators.
Definition ISDOpcodes.h:854
@ AVGCEILS
AVGCEILS/AVGCEILU - Rounding averaging add - Add two integers using an integer of type i[N+2],...
Definition ISDOpcodes.h:717
@ SCALAR_TO_VECTOR
SCALAR_TO_VECTOR(VAL) - This represents the operation of loading a scalar value into element 0 of the...
Definition ISDOpcodes.h:667
@ TargetExternalSymbol
Definition ISDOpcodes.h:190
@ VECREDUCE_FADD
These reductions have relaxed evaluation order semantics, and have a single vector operand.
@ TargetJumpTable
Definition ISDOpcodes.h:188
@ TargetIndex
TargetIndex - Like a constant pool entry, but with completely target-dependent semantics.
Definition ISDOpcodes.h:198
@ PARTIAL_REDUCE_FMLA
@ PREFETCH
PREFETCH - This corresponds to a prefetch intrinsic.
@ TRUNCATE_SSAT_U
Definition ISDOpcodes.h:883
@ SETCCCARRY
Like SetCC, ops #0 and #1 are the LHS and RHS operands to compare, but op #2 is a boolean indicating ...
Definition ISDOpcodes.h:837
@ FNEG
Perform various unary floating-point operations inspired by libm.
@ BR_CC
BR_CC - Conditional branch.
@ SSUBO
Same for subtraction.
Definition ISDOpcodes.h:352
@ STEP_VECTOR
STEP_VECTOR(IMM) - Returns a scalable vector whose lanes are comprised of a linear sequence of unsign...
Definition ISDOpcodes.h:693
@ FCANONICALIZE
Returns platform specific canonical encoding of a floating point number.
Definition ISDOpcodes.h:543
@ IS_FPCLASS
Performs a check of floating point class property, defined by IEEE-754.
Definition ISDOpcodes.h:550
@ SSUBSAT
RESULT = [US]SUBSAT(LHS, RHS) - Perform saturation subtraction on 2 integers with the same bit width ...
Definition ISDOpcodes.h:374
@ SELECT
Select(COND, TRUEVAL, FALSEVAL).
Definition ISDOpcodes.h:806
@ ATOMIC_LOAD
Val, OUTCHAIN = ATOMIC_LOAD(INCHAIN, ptr) This corresponds to "load atomic" instruction.
@ UNDEF
UNDEF - An undefined node.
Definition ISDOpcodes.h:233
@ EXTRACT_ELEMENT
EXTRACT_ELEMENT - This is used to get the lower or upper (determined by a Constant,...
Definition ISDOpcodes.h:247
@ SPLAT_VECTOR
SPLAT_VECTOR(VAL) - Returns a vector with the scalar value VAL duplicated in all lanes.
Definition ISDOpcodes.h:674
@ AssertAlign
AssertAlign - These nodes record if a register contains a value that has a known alignment and the tr...
Definition ISDOpcodes.h:69
@ GET_ACTIVE_LANE_MASK
GET_ACTIVE_LANE_MASK - this corrosponds to the llvm.get.active.lane.mask intrinsic.
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:81
@ CopyFromReg
CopyFromReg - This node indicates that the input value is a virtual or physical register that is defi...
Definition ISDOpcodes.h:230
@ SADDO
RESULT, BOOL = [SU]ADDO(LHS, RHS) - Overflow-aware nodes for addition.
Definition ISDOpcodes.h:348
@ TargetGlobalAddress
TargetGlobalAddress - Like GlobalAddress, but the DAG does no folding or anything else with this node...
Definition ISDOpcodes.h:185
@ ARITH_FENCE
ARITH_FENCE - This corresponds to a arithmetic fence intrinsic.
@ CTLS
Count leading redundant sign bits.
Definition ISDOpcodes.h:802
@ VECREDUCE_ADD
Integer reductions may have a result type larger than the vector element type.
@ MULHU
MULHU/MULHS - Multiply high - Multiply two integers of type iN, producing an unsigned/signed value of...
Definition ISDOpcodes.h:706
@ ATOMIC_LOAD_FMAXIMUM
@ SHL
Shift and rotation operations.
Definition ISDOpcodes.h:771
@ AssertNoFPClass
AssertNoFPClass - These nodes record if a register contains a float value that is known to be not som...
Definition ISDOpcodes.h:78
@ VECTOR_SHUFFLE
VECTOR_SHUFFLE(VEC1, VEC2) - Returns a vector, of the same type as VEC1/VEC2.
Definition ISDOpcodes.h:651
@ EXTRACT_SUBVECTOR
EXTRACT_SUBVECTOR(VECTOR, IDX) - Returns a subvector from VECTOR.
Definition ISDOpcodes.h:616
@ FMINNUM_IEEE
FMINNUM_IEEE/FMAXNUM_IEEE - Perform floating-point minimumNumber or maximumNumber on two values,...
@ EntryToken
EntryToken - This is the marker used to indicate the start of a region.
Definition ISDOpcodes.h:48
@ EXTRACT_VECTOR_ELT
EXTRACT_VECTOR_ELT(VECTOR, IDX) - Returns a single element from VECTOR identified by the (potentially...
Definition ISDOpcodes.h:578
@ CopyToReg
CopyToReg - This node has three operands: a chain, a register number to set to this value,...
Definition ISDOpcodes.h:224
@ ZERO_EXTEND
ZERO_EXTEND - Used for integer types, zeroing the new bits.
Definition ISDOpcodes.h:860
@ TargetConstantFP
Definition ISDOpcodes.h:180
@ SELECT_CC
Select with condition operator - This selects between a true value and a false value (ops #2 and #3) ...
Definition ISDOpcodes.h:821
@ VSCALE
VSCALE(IMM) - Returns the runtime scaling factor used to calculate the number of elements within a sc...
@ ATOMIC_CMP_SWAP
Val, OUTCHAIN = ATOMIC_CMP_SWAP(INCHAIN, ptr, cmp, swap) For double-word atomic operations: ValLo,...
@ FMINNUM
FMINNUM/FMAXNUM - Perform floating-point minimum maximum on two values, following IEEE-754 definition...
@ SSHLSAT
RESULT = [US]SHLSAT(LHS, RHS) - Perform saturation left shift.
Definition ISDOpcodes.h:386
@ SMULO
Same for multiplication.
Definition ISDOpcodes.h:356
@ ATOMIC_LOAD_FMINIMUM
@ TargetFrameIndex
Definition ISDOpcodes.h:187
@ VECTOR_SPLICE_LEFT
VECTOR_SPLICE_LEFT(VEC1, VEC2, OFFSET) - Shifts CONCAT_VECTORS(VEC1, VEC2) left by OFFSET elements an...
Definition ISDOpcodes.h:655
@ ANY_EXTEND_VECTOR_INREG
ANY_EXTEND_VECTOR_INREG(Vector) - This operator represents an in-register any-extension of the low la...
Definition ISDOpcodes.h:909
@ SIGN_EXTEND_INREG
SIGN_EXTEND_INREG - This operator atomically performs a SHL/SRA pair to sign extend a small value in ...
Definition ISDOpcodes.h:898
@ SMIN
[US]{MIN/MAX} - Binary minimum or maximum of signed or unsigned integers.
Definition ISDOpcodes.h:729
@ MASKED_UDIV
Masked vector arithmetic that returns poison on disabled lanes.
@ LIFETIME_START
This corresponds to the llvm.lifetime.
@ FP_EXTEND
X = FP_EXTEND(Y) - Extend a smaller FP type into a larger FP type.
Definition ISDOpcodes.h:988
@ VSELECT
Select with a vector condition (op #0) and two vector operands (ops #1 and #2), returning a vector re...
Definition ISDOpcodes.h:815
@ UADDO_CARRY
Carry-using nodes for multiple precision addition and subtraction.
Definition ISDOpcodes.h:328
@ MGATHER
Masked gather and scatter - load and store operations for a vector of random addresses with additiona...
@ HANDLENODE
HANDLENODE node - Used as a handle for various purposes.
@ BF16_TO_FP
BF16_TO_FP, FP_TO_BF16 - These operators are used to perform promotions and truncation for bfloat16.
@ ATOMIC_LOAD_UDEC_WRAP
@ PEXT
Parallel bit extract (compress) and parallel bit deposit (expand).
Definition ISDOpcodes.h:785
@ STRICT_FP_ROUND
X = STRICT_FP_ROUND(Y, TRUNC) - Rounding 'Y' from a larger floating point type down to the precision ...
Definition ISDOpcodes.h:502
@ FMINIMUM
FMINIMUM/FMAXIMUM - NaN-propagating minimum/maximum that also treat -0.0 as less than 0....
@ FP_TO_SINT
FP_TO_[US]INT - Convert a floating point value to a signed or unsigned integer.
Definition ISDOpcodes.h:936
@ TargetConstant
TargetConstant* - Like Constant*, but the DAG does not do any folding, simplification,...
Definition ISDOpcodes.h:179
@ STRICT_FP_EXTEND
X = STRICT_FP_EXTEND(Y) - Extend a smaller FP type into a larger FP type.
Definition ISDOpcodes.h:507
@ AND
Bitwise operators - logical and, logical or, logical xor.
Definition ISDOpcodes.h:741
@ INTRINSIC_WO_CHAIN
RESULT = INTRINSIC_WO_CHAIN(INTRINSICID, arg1, arg2, ...) This node represents a target intrinsic fun...
Definition ISDOpcodes.h:205
@ GET_FPENV_MEM
Gets the current floating-point environment.
@ PSEUDO_PROBE
Pseudo probe for AutoFDO, as a place holder in a basic block to improve the sample counts quality.
@ SCMP
[US]CMP - 3-way comparison of signed or unsigned integers.
Definition ISDOpcodes.h:737
@ AVGFLOORS
AVGFLOORS/AVGFLOORU - Averaging add - Add two integers using an integer of type i[N+1],...
Definition ISDOpcodes.h:712
@ VECTOR_SPLICE_RIGHT
VECTOR_SPLICE_RIGHT(VEC1, VEC2, OFFSET) - Shifts CONCAT_VECTORS(VEC1,VEC2) right by OFFSET elements a...
Definition ISDOpcodes.h:659
@ ADDE
Carry-using nodes for multiple precision addition and subtraction.
Definition ISDOpcodes.h:304
@ SPLAT_VECTOR_PARTS
SPLAT_VECTOR_PARTS(SCALAR1, SCALAR2, ...) - Returns a vector with the scalar values joined together a...
Definition ISDOpcodes.h:683
@ FREEZE
FREEZE - FREEZE(VAL) returns an arbitrary value if VAL is UNDEF (or is evaluated to UNDEF),...
Definition ISDOpcodes.h:241
@ INSERT_VECTOR_ELT
INSERT_VECTOR_ELT(VECTOR, VAL, IDX) - Returns VECTOR with the element at IDX replaced with VAL.
Definition ISDOpcodes.h:567
@ TokenFactor
TokenFactor - This node takes multiple tokens as input and produces a single token result.
Definition ISDOpcodes.h:53
@ ATOMIC_SWAP
Val, OUTCHAIN = ATOMIC_SWAP(INCHAIN, ptr, amt) Val, OUTCHAIN = ATOMIC_LOAD_[OpName](INCHAIN,...
@ CTTZ_ZERO_POISON
Bit counting operators with a poisoned result for zero inputs.
Definition ISDOpcodes.h:797
@ ExternalSymbol
Definition ISDOpcodes.h:93
@ FFREXP
FFREXP - frexp, extract fractional and exponent component of a floating-point value.
@ FP_ROUND
X = FP_ROUND(Y, TRUNC) - Rounding 'Y' from a larger floating point type down to the precision of the ...
Definition ISDOpcodes.h:969
@ VECTOR_COMPRESS
VECTOR_COMPRESS(Vec, Mask, Passthru) consecutively place vector elements based on mask e....
Definition ISDOpcodes.h:701
@ ZERO_EXTEND_VECTOR_INREG
ZERO_EXTEND_VECTOR_INREG(Vector) - This operator represents an in-register zero-extension of the low ...
Definition ISDOpcodes.h:931
@ ADDRSPACECAST
ADDRSPACECAST - This operator converts between pointers of different address spaces.
@ EXPERIMENTAL_VECTOR_HISTOGRAM
Experimental vector histogram intrinsic Operands: Input Chain, Inc, Mask, Base, Index,...
@ FP_TO_SINT_SAT
FP_TO_[US]INT_SAT - Convert floating point value in operand 0 to a signed or unsigned scalar integer ...
Definition ISDOpcodes.h:955
@ VECREDUCE_FMINIMUM
@ TRUNCATE
TRUNCATE - Completely drop the high bits.
Definition ISDOpcodes.h:866
@ VAARG
VAARG - VAARG has four operands: an input chain, a pointer, a SRCVALUE, and the alignment.
@ VECREDUCE_SEQ_FMUL
@ SHL_PARTS
SHL_PARTS/SRA_PARTS/SRL_PARTS - These operators are used for expanded integer shift operations.
Definition ISDOpcodes.h:843
@ AssertSext
AssertSext, AssertZext - These nodes record if a register contains a value that has already been zero...
Definition ISDOpcodes.h:62
@ ATOMIC_LOAD_UINC_WRAP
@ FCOPYSIGN
FCOPYSIGN(X, Y) - Return the value of X with the sign of Y.
Definition ISDOpcodes.h:536
@ PARTIAL_REDUCE_SUMLA
@ SADDSAT
RESULT = [US]ADDSAT(LHS, RHS) - Perform saturation addition on 2 integers with the same bit width (W)...
Definition ISDOpcodes.h:365
@ SET_FPENV_MEM
Sets the current floating point environment.
@ FMINIMUMNUM
FMINIMUMNUM/FMAXIMUMNUM - minimumnum/maximumnum that is same with FMINNUM_IEEE and FMAXNUM_IEEE besid...
@ TRUNCATE_SSAT_S
TRUNCATE_[SU]SAT_[SU] - Truncate for saturated operand [SU] located in middle, prefix for SAT means i...
Definition ISDOpcodes.h:881
@ ABDS
ABDS/ABDU - Absolute difference - Return the absolute difference between two numbers interpreted as s...
Definition ISDOpcodes.h:724
@ TRUNCATE_USAT_U
Definition ISDOpcodes.h:885
@ SADDO_CARRY
Carry-using overflow-aware nodes for multiple precision addition and subtraction.
Definition ISDOpcodes.h:338
@ INTRINSIC_W_CHAIN
RESULT,OUTCHAIN = INTRINSIC_W_CHAIN(INCHAIN, INTRINSICID, arg1, ...) This node represents a target in...
Definition ISDOpcodes.h:213
@ TargetGlobalTLSAddress
Definition ISDOpcodes.h:186
@ ABS_MIN_POISON
ABS with a poison result for INT_MIN.
Definition ISDOpcodes.h:753
@ BUILD_VECTOR
BUILD_VECTOR(ELT0, ELT1, ELT2, ELT3,...) - Return a fixed-width vector with the specified,...
Definition ISDOpcodes.h:558
LLVM_ABI NodeType getOppositeSignednessMinMaxOpcode(unsigned MinMaxOpc)
Given a MinMaxOpc of ISD::(U|S)MIN or ISD::(U|S)MAX, returns the corresponding opcode with the opposi...
LLVM_ABI bool isBuildVectorOfConstantSDNodes(const SDNode *N)
Return true if the specified node is a BUILD_VECTOR node of all ConstantSDNode or undef.
LLVM_ABI NodeType getExtForLoadExtType(bool IsFP, LoadExtType)
bool isZEXTLoad(const SDNode *N)
Returns true if the specified node is a ZEXTLOAD.
bool isExtOpcode(unsigned Opcode)
LLVM_ABI bool isConstantSplatVectorAllZeros(const SDNode *N, bool BuildVectorOnly=false)
Return true if the specified node is a BUILD_VECTOR or SPLAT_VECTOR where all of the elements are 0 o...
LLVM_ABI NodeType getUnmaskedBinOpOpcode(unsigned MaskedOpc)
Given a MaskedOpc of ISD::MASKED_(U|S)(DIV|REM), returns the unmasked ISD::(U|S)(DIV|REM).
LLVM_ABI bool isVectorShrinkable(const SDNode *N, unsigned NewEltSize, bool Signed)
Returns true if the specified node is a vector where all elements can be truncated to the specified e...
LLVM_ABI bool isVPBinaryOp(unsigned Opcode)
Whether this is a vector-predicated binary operation opcode.
LLVM_ABI CondCode getSetCCInverse(CondCode Operation, EVT Type)
Return the operation corresponding to !(X op Y), where 'op' is a valid SetCC operation.
LLVM_ABI std::optional< unsigned > getBaseOpcodeForVP(unsigned Opcode, bool hasFPExcept)
Translate this VP Opcode to its corresponding non-VP Opcode.
bool isBitwiseLogicOp(unsigned Opcode)
Whether this is bitwise logic opcode.
bool isTrueWhenEqual(CondCode Cond)
Return true if the specified condition returns true if the two operands to the condition are equal.
LLVM_ABI std::optional< unsigned > getVPMaskIdx(unsigned Opcode)
The operand position of the vector mask.
unsigned getUnorderedFlavor(CondCode Cond)
This function returns 0 if the condition is always false if an operand is a NaN, 1 if the condition i...
LLVM_ABI std::optional< unsigned > getVPExplicitVectorLengthIdx(unsigned Opcode)
The operand position of the explicit vector length parameter.
bool isEXTLoad(const SDNode *N)
Returns true if the specified node is a EXTLOAD.
LLVM_ABI bool allOperandsUndef(const SDNode *N)
Return true if the node has at least one operand and all operands of the specified node are ISD::UNDE...
LLVM_ABI bool isFreezeUndef(const SDNode *N)
Return true if the specified node is FREEZE(UNDEF).
LLVM_ABI CondCode getSetCCSwappedOperands(CondCode Operation)
Return the operation corresponding to (Y op X) when given the operation for (X op Y).
LLVM_ABI std::optional< unsigned > getVPForBaseOpcode(unsigned Opcode)
Translate this non-VP Opcode to its corresponding VP Opcode.
MemIndexType
MemIndexType enum - This enum defines how to interpret MGATHER/SCATTER's index parameter when calcula...
LLVM_ABI bool isBuildVectorAllZeros(const SDNode *N)
Return true if the specified node is a BUILD_VECTOR where all of the elements are 0 or undef.
bool matchUnaryPredicateImpl(SDValue Op, 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...
LLVM_ABI bool isConstantSplatVector(const SDNode *N, APInt &SplatValue)
Node predicates.
LLVM_ABI NodeType getInverseMinMaxOpcode(unsigned MinMaxOpc)
Given a MinMaxOpc of ISD::(U|S)MIN or ISD::(U|S)MAX, returns ISD::(U|S)MAX and ISD::(U|S)MIN,...
LLVM_ABI bool matchBinaryPredicate(SDValue LHS, SDValue RHS, 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...
LLVM_ABI bool isVPReduction(unsigned Opcode)
Whether this is a vector-predicated reduction opcode.
bool matchUnaryPredicate(SDValue Op, std::function< bool(ConstantSDNode *)> Match, bool AllowUndefs=false, bool AllowTruncation=false)
Hook for matching ConstantSDNode predicate.
MemIndexedMode
MemIndexedMode enum - This enum defines the load / store indexed addressing modes.
LLVM_ABI bool isBuildVectorOfConstantFPSDNodes(const SDNode *N)
Return true if the specified node is a BUILD_VECTOR node of all ConstantFPSDNode or undef.
bool isSEXTLoad(const SDNode *N)
Returns true if the specified node is a SEXTLOAD.
CondCode
ISD::CondCode enum - These are ordered carefully to make the bitfields below work out,...
LLVM_ABI bool isBuildVectorAllOnes(const SDNode *N)
Return true if the specified node is a BUILD_VECTOR where all of the elements are ~0 or undef.
LLVM_ABI NodeType getVecReduceBaseOpcode(unsigned VecReduceOpcode)
Get underlying scalar opcode for VECREDUCE opcode.
LoadExtType
LoadExtType enum - This enum defines the three variants of LOADEXT (load with extension).
LLVM_ABI bool isVPOpcode(unsigned Opcode)
Whether this is a vector-predicated Opcode.
LLVM_ABI CondCode getSetCCOrOperation(CondCode Op1, CondCode Op2, EVT Type)
Return the result of a logical OR between different comparisons of identical values: ((X op1 Y) | (X ...
BinaryOp_match< SpecificConstantMatch, SrcTy, TargetOpcode::G_SUB > m_Neg(const SrcTy &&Src)
Matches a register negated by a G_SUB.
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
match_deferred< Value > m_Deferred(Value *const &V)
Like m_Specific(), but works if the specific value to match is determined as part of the same match()...
auto m_Value()
Match an arbitrary value and ignore it.
BinaryOp_match< LHS, RHS, Instruction::Sub > m_Sub(const LHS &L, const RHS &R)
LLVM_ABI Libcall getMEMCPY_ELEMENT_UNORDERED_ATOMIC(uint64_t ElementSize)
getMEMCPY_ELEMENT_UNORDERED_ATOMIC - Return MEMCPY_ELEMENT_UNORDERED_ATOMIC_* value for the given ele...
LLVM_ABI Libcall getMEMSET_ELEMENT_UNORDERED_ATOMIC(uint64_t ElementSize)
getMEMSET_ELEMENT_UNORDERED_ATOMIC - Return MEMSET_ELEMENT_UNORDERED_ATOMIC_* value for the given ele...
LLVM_ABI Libcall getMEMMOVE_ELEMENT_UNORDERED_ATOMIC(uint64_t ElementSize)
getMEMMOVE_ELEMENT_UNORDERED_ATOMIC - Return MEMMOVE_ELEMENT_UNORDERED_ATOMIC_* value for the given e...
bool sd_match(SDNode *N, const SelectionDAG *DAG, Pattern &&P)
initializer< Ty > init(const Ty &Val)
@ DW_OP_LLVM_arg
Only used in LLVM metadata.
Definition Dwarf.h:149
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract(Y &&MD)
Extract a Value from Metadata.
Definition Metadata.h:668
NodeAddr< NodeBase * > Node
Definition RDFGraph.h:381
This is an optimization pass for GlobalISel generic memory operations.
GenericUniformityInfo< SSAContext > UniformityInfo
unsigned Log2_32_Ceil(uint32_t Value)
Return the ceil log base 2 of the specified value, 32 if the value is zero.
Definition MathExtras.h:345
@ Offset
Definition DWP.cpp:578
bool operator<(int64_t V1, const APSInt &V2)
Definition APSInt.h:360
LLVM_ABI ISD::CondCode getICmpCondCode(ICmpInst::Predicate Pred)
getICmpCondCode - Return the ISD condition code corresponding to the given LLVM IR integer condition ...
Definition Analysis.cpp:237
void fill(R &&Range, T &&Value)
Provide wrappers to std::fill which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1759
LLVM_ABI SDValue peekThroughExtractSubvectors(SDValue V)
Return the non-extracted vector source operand of V if it exists.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1739
LLVM_ABI bool isNullConstant(SDValue V)
Returns true if V is a constant integer zero.
LLVM_ABI bool isAllOnesOrAllOnesSplat(const MachineInstr &MI, const MachineRegisterInfo &MRI, bool AllowUndefs=false)
Return true if the value is a constant -1 integer or a splatted vector of a constant -1 integer (with...
Definition Utils.cpp:1557
LLVM_ABI SDValue getBitwiseNotOperand(SDValue V, SDValue Mask, bool AllowUndefs)
If V is a bitwise not, returns the inverted operand.
@ Known
Known to have no common set bits.
@ Undef
Value of the register doesn't matter.
LLVM_ABI SDValue peekThroughBitcasts(SDValue V)
Return the non-bitcasted source operand of V if it exists.
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2554
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
int countr_one(T Value)
Count the number of ones from the least significant bit to the first zero bit.
Definition bit.h:315
@ Store
The extracted value is stored (ExtractElement only).
bool isIntOrFPConstant(SDValue V)
Return true if V is either a integer or FP constant.
auto dyn_cast_if_present(const Y &Val)
dyn_cast_if_present<X> - Functionally identical to dyn_cast, except that a null (or none in the case ...
Definition Casting.h:732
LLVM_ABI bool getConstantDataArrayInfo(const Value *V, ConstantDataArraySlice &Slice, unsigned ElementSize, uint64_t Offset=0)
Returns true if the value V is a pointer into a ConstantDataArray.
LLVM_ABI bool isOneOrOneSplatFP(SDValue V, bool AllowUndefs=false)
Return true if the value is a constant floating-point value, or a splatted vector of a constant float...
int bit_width(T Value)
Returns the number of bits needed to represent Value if Value is nonzero.
Definition bit.h:325
LLVM_READONLY APFloat maximum(const APFloat &A, const APFloat &B)
Implements IEEE 754-2019 maximum semantics.
Definition APFloat.h:1793
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2208
constexpr bool isUIntN(unsigned N, uint64_t x)
Checks if an unsigned integer fits into the given (dynamic) bit width.
Definition MathExtras.h:244
LLVM_ABI bool shouldOptimizeForSize(const MachineFunction *MF, ProfileSummaryInfo *PSI, const MachineBlockFrequencyInfo *BFI, PGSOQueryType QueryType=PGSOQueryType::Other)
Returns true if machine function MF is suggested to be size-optimized based on the profile.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:633
auto cast_or_null(const Y &Val)
Definition Casting.h:714
LLVM_ABI bool isNullOrNullSplat(const MachineInstr &MI, const MachineRegisterInfo &MRI, bool AllowUndefs=false)
Return true if the value is a constant 0 integer or a splatted vector of a constant 0 integer (with n...
Definition Utils.cpp:1539
LLVM_ABI bool isMinSignedConstant(SDValue V)
Returns true if V is a constant min signed integer value.
LLVM_ABI ConstantFPSDNode * isConstOrConstSplatFP(SDValue N, bool AllowUndefs=false)
Returns the SDNode if it is a constant splat BuildVector or constant float.
LLVM_ABI ConstantRange getConstantRangeFromMetadata(const MDNode &RangeMD)
Parse out a conservative ConstantRange from !range metadata.
APFloat frexp(const APFloat &X, int &Exp, APFloat::roundingMode RM)
Equivalent of C standard library function.
Definition APFloat.h:1705
int countr_zero(T Val)
Count number of 0's from the least significant bit to the most stopping at the first 1.
Definition bit.h:204
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1746
LLVM_ABI bool getShuffleDemandedElts(int SrcWidth, ArrayRef< int > Mask, const APInt &DemandedElts, APInt &DemandedLHS, APInt &DemandedRHS, bool AllowUndefElts=false)
Transform a shuffle mask's output demanded element mask into demanded element masks for the 2 operand...
LLVM_READONLY APFloat maxnum(const APFloat &A, const APFloat &B)
Implements IEEE-754 2008 maxNum semantics.
Definition APFloat.h:1748
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:332
LLVM_ABI bool isBitwiseNot(SDValue V, bool AllowUndefs=false)
Returns true if V is a bitwise not operation.
LLVM_ABI SDValue peekThroughInsertVectorElt(SDValue V, const APInt &DemandedElts)
Recursively peek through INSERT_VECTOR_ELT nodes, returning the source vector operand of V,...
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition MathExtras.h:280
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
LLVM_ABI void checkForCycles(const SelectionDAG *DAG, bool force=false)
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1636
LLVM_READONLY APFloat minimumnum(const APFloat &A, const APFloat &B)
Implements IEEE 754-2019 minimumNumber semantics.
Definition APFloat.h:1779
FPClassTest
Floating-point class tests, supported by 'is_fpclass' intrinsic.
LLVM_ABI void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
LLVM_ABI const MDNode * getMemCacheHintMetadata(const Instruction &I, unsigned OperandNo=0)
Return the cache hint metadata node for memory operand OperandNo on I, or nullptr when the instructio...
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI SDValue peekThroughTruncates(SDValue V)
Return the non-truncated source operand of V if it exists.
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1753
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
constexpr std::underlying_type_t< Enum > to_underlying(Enum E)
Returns underlying integer value of an enum.
LLVM_ABI ConstantRange getVScaleRange(const Function *F, unsigned BitWidth)
Determine the possible constant range of vscale with the given bit width, based on the vscale_range f...
LLVM_ABI SDValue peekThroughOneUseBitcasts(SDValue V)
Return the non-bitcasted and one-use source operand of V if it exists.
CodeGenOptLevel
Code generation optimization level.
Definition CodeGen.h:149
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
bool includesPoison(UndefPoisonKind Kind)
Returns true if Kind includes the Poison bit.
Definition UndefPoison.h:27
LLVM_ABI bool isOneOrOneSplat(SDValue V, bool AllowUndefs=false)
Return true if the value is a constant 1 integer or a splatted vector of a constant 1 integer (with n...
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
@ Other
Any other memory.
Definition ModRef.h:68
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
Definition ModRef.h:74
bool includesUndef(UndefPoisonKind Kind)
Returns true if Kind includes the Undef bit.
Definition UndefPoison.h:33
LLVM_READONLY APFloat minnum(const APFloat &A, const APFloat &B)
Implements IEEE-754 2008 minNum semantics.
Definition APFloat.h:1729
@ Mul
Product of integers.
@ Sub
Subtraction of integers.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
LLVM_ABI bool isNullConstantOrUndef(SDValue V)
Returns true if V is a constant integer zero or an UNDEF node.
IntPtrTy
Definition InstrProf.h:82
LLVM_ABI bool isInTailCallPosition(const CallBase &Call, const TargetMachine &TM, bool ReturnsFirstArg=false)
Test if the given instruction is in a position to be optimized with a tail-call.
Definition Analysis.cpp:539
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
LLVM_ABI ConstantSDNode * isConstOrConstSplat(SDValue N, bool AllowUndefs=false, bool AllowTruncation=false)
Returns the SDNode if it is a constant splat BuildVector or constant int.
OutputIt copy(R &&Range, OutputIt Out)
Definition STLExtras.h:1885
constexpr unsigned BitWidth
LLVM_ABI bool funcReturnsFirstArgOfCall(const CallInst &CI)
Returns true if the parent of CI returns CI's first argument after calling CI.
Definition Analysis.cpp:719
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI bool isZeroOrZeroSplat(SDValue N, bool AllowUndefs=false)
Return true if the value is a constant 0 integer or a splatted vector of a constant 0 integer (with n...
LLVM_ABI bool isOneConstant(SDValue V)
Returns true if V is a constant integer one.
UndefPoisonKind
Enumeration to track whether we are interested in Undef, Poison, or both.
Definition UndefPoison.h:20
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1947
Align commonAlignment(Align A, uint64_t Offset)
Returns the alignment that satisfies both alignments.
Definition Alignment.h:201
LLVM_ABI bool isNullFPConstant(SDValue V)
Returns true if V is an FP constant with a value of positive zero.
constexpr int64_t SignExtend64(uint64_t x)
Sign-extend the number in the bottom B bits of X to a 64-bit integer.
Definition MathExtras.h:573
unsigned Log2(Align A)
Returns the log2 of the alignment.
Definition Alignment.h:197
LLVM_ABI bool isZeroOrZeroSplatFP(SDValue N, bool AllowUndefs=false)
Return true if the value is a constant (+/-)0.0 floating-point value or a splatted vector thereof (wi...
LLVM_ABI void computeKnownBitsFromRangeMetadata(const MDNode &Ranges, KnownBits &Known)
Compute known bits from the range metadata.
LLVM_READONLY APFloat minimum(const APFloat &A, const APFloat &B)
Implements IEEE 754-2019 minimum semantics.
Definition APFloat.h:1766
LLVM_READONLY APFloat maximumnum(const APFloat &A, const APFloat &B)
Implements IEEE 754-2019 maximumNumber semantics.
Definition APFloat.h:1806
LLVM_ABI bool isOnesOrOnesSplat(SDValue N, bool AllowUndefs=false)
Return true if the value is a constant 1 integer or a splatted vector of a constant 1 integer (with n...
LLVM_ABI bool isAllOnesConstant(SDValue V)
Returns true if V is an integer constant with all bits set.
constexpr uint64_t NextPowerOf2(uint64_t A)
Returns the next power of two (in 64-bits) that is strictly greater than A.
Definition MathExtras.h:374
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
Definition Error.cpp:177
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:880
#define N
A collection of metadata nodes that might be associated with a memory access used by the alias-analys...
Definition Metadata.h:763
MDNode * TBAAStruct
The tag for type-based alias analysis (tbaa struct).
Definition Metadata.h:783
MDNode * TBAA
The tag for type-based alias analysis.
Definition Metadata.h:780
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
constexpr uint64_t value() const
This is a hole in the type system and should not be abused.
Definition Alignment.h:77
Represents offset+length into a ConstantDataArray.
uint64_t Length
Length of the slice.
uint64_t Offset
Slice starts at this Offset.
void move(uint64_t Delta)
Moves the Offset and adjusts Length accordingly.
const ConstantDataArray * Array
ConstantDataArray pointer.
Extended Value Type.
Definition ValueTypes.h:35
TypeSize getStoreSize() const
Return the number of bytes overwritten by a store of the specified value type.
Definition ValueTypes.h:418
bool isSimple() const
Test if the given EVT is simple (as opposed to being extended).
Definition ValueTypes.h:145
intptr_t getRawBits() const
Definition ValueTypes.h:543
static EVT getVectorVT(LLVMContext &Context, EVT VT, unsigned NumElements, bool IsScalable=false)
Returns the EVT that represents a vector NumElements in length, where each element is of type VT.
Definition ValueTypes.h:70
EVT changeTypeToInteger() const
Return the type converted to an equivalently sized integer or vector with integer element type.
Definition ValueTypes.h:129
bool bitsGT(EVT VT) const
Return true if this has more bits than VT.
Definition ValueTypes.h:307
bool bitsLT(EVT VT) const
Return true if this has less bits than VT.
Definition ValueTypes.h:323
bool isFloatingPoint() const
Return true if this is a FP or a vector FP type.
Definition ValueTypes.h:155
ElementCount getVectorElementCount() const
Definition ValueTypes.h:373
TypeSize getSizeInBits() const
Return the size of the specified value type in bits.
Definition ValueTypes.h:396
unsigned getVectorMinNumElements() const
Given a vector type, return the minimum number of elements it contains.
Definition ValueTypes.h:382
uint64_t getScalarSizeInBits() const
Definition ValueTypes.h:408
MVT getSimpleVT() const
Return the SimpleValueType held in the specified simple EVT.
Definition ValueTypes.h:339
static EVT getIntegerVT(LLVMContext &Context, unsigned BitWidth)
Returns the EVT that represents an integer with the given number of bits.
Definition ValueTypes.h:61
bool isFixedLengthVector() const
Definition ValueTypes.h:199
bool isVector() const
Return true if this is a vector value type.
Definition ValueTypes.h:176
EVT getScalarType() const
If this is a vector type, return the element type, otherwise return this.
Definition ValueTypes.h:346
bool bitsGE(EVT VT) const
Return true if this has no less bits than VT.
Definition ValueTypes.h:315
bool bitsEq(EVT VT) const
Return true if this has the same number of bits as VT.
Definition ValueTypes.h:279
LLVM_ABI Type * getTypeForEVT(LLVMContext &Context) const
This method returns an LLVM type corresponding to the specified EVT.
bool isScalableVector() const
Return true if this is a vector type where the runtime length is machine dependent.
Definition ValueTypes.h:187
EVT getVectorElementType() const
Given a vector type, return the type of each element.
Definition ValueTypes.h:351
bool isExtended() const
Test if the given EVT is extended (as opposed to being simple).
Definition ValueTypes.h:150
LLVM_ABI const fltSemantics & getFltSemantics() const
Returns an APFloat semantics tag appropriate for the value type.
unsigned getVectorNumElements() const
Given a vector type, return the number of elements it contains.
Definition ValueTypes.h:359
bool bitsLE(EVT VT) const
Return true if this has no more bits than VT.
Definition ValueTypes.h:331
EVT getHalfNumVectorElementsVT(LLVMContext &Context) const
Definition ValueTypes.h:484
bool isInteger() const
Return true if this is an integer or a vector integer type.
Definition ValueTypes.h:160
static KnownBits makeConstant(const APInt &C)
Create known bits from a known constant.
Definition KnownBits.h:315
static LLVM_ABI KnownBits mulhu(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits from zero-extended multiply-hi.
static LLVM_ABI KnownBits smax(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for smax(LHS, RHS).
bool isNonNegative() const
Returns true if this value is known to be non-negative.
Definition KnownBits.h:106
bool isZero() const
Returns true if value is all zero.
Definition KnownBits.h:78
static LLVM_ABI KnownBits usub_sat(const KnownBits &LHS, const KnownBits &RHS)
Compute knownbits resulting from llvm.usub.sat(LHS, RHS)
static LLVM_ABI KnownBits ashr(const KnownBits &LHS, const KnownBits &RHS, bool ShAmtNonZero=false, bool Exact=false)
Compute known bits for ashr(LHS, RHS).
static LLVM_ABI KnownBits urem(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for urem(LHS, RHS).
unsigned countMaxTrailingZeros() const
Returns the maximum number of trailing zero bits possible.
Definition KnownBits.h:288
static LLVM_ABI std::optional< bool > ne(const KnownBits &LHS, const KnownBits &RHS)
Determine if these known bits always give the same ICMP_NE result.
KnownBits trunc(unsigned BitWidth) const
Return known bits for a truncation of the value we're tracking.
Definition KnownBits.h:165
KnownBits byteSwap() const
Definition KnownBits.h:559
static LLVM_ABI KnownBits fshl(const KnownBits &LHS, const KnownBits &RHS, const APInt &Amt)
Compute known bits for fshl(LHS, RHS, Amt).
unsigned countMaxPopulation() const
Returns the maximum number of bits that could be one.
Definition KnownBits.h:303
void setAllZero()
Make all bits known to be zero and discard any previous information.
Definition KnownBits.h:84
KnownBits reverseBits() const
Definition KnownBits.h:563
KnownBits concat(const KnownBits &Lo) const
Concatenate the bits from Lo onto the bottom of *this.
Definition KnownBits.h:247
unsigned getBitWidth() const
Get the bit width of this value.
Definition KnownBits.h:44
static LLVM_ABI KnownBits umax(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for umax(LHS, RHS).
KnownBits zext(unsigned BitWidth) const
Return known bits for a zero extension of the value we're tracking.
Definition KnownBits.h:176
void resetAll()
Resets the known state of all bits.
Definition KnownBits.h:72
static KnownBits add(const KnownBits &LHS, const KnownBits &RHS, bool NSW=false, bool NUW=false, bool SelfAdd=false)
Compute knownbits resulting from addition of LHS and RHS.
Definition KnownBits.h:361
static LLVM_ABI KnownBits lshr(const KnownBits &LHS, const KnownBits &RHS, bool ShAmtNonZero=false, bool Exact=false)
Compute known bits for lshr(LHS, RHS).
bool isNonZero() const
Returns true if this value is known to be non-zero.
Definition KnownBits.h:109
static LLVM_ABI KnownBits abdu(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for abdu(LHS, RHS).
KnownBits extractBits(unsigned NumBits, unsigned BitPosition) const
Return a subset of the known bits from [bitPosition,bitPosition+numBits).
Definition KnownBits.h:239
static LLVM_ABI KnownBits pdep(const KnownBits &Val, const KnownBits &Mask)
Compute known bits for pdep(Val, Mask).
static LLVM_ABI KnownBits avgFloorU(const KnownBits &LHS, const KnownBits &RHS)
Compute knownbits resulting from APIntOps::avgFloorU.
KnownBits sext(unsigned BitWidth) const
Return known bits for a sign extension of the value we're tracking.
Definition KnownBits.h:184
static LLVM_ABI KnownBits computeForSubBorrow(const KnownBits &LHS, KnownBits RHS, const KnownBits &Borrow)
Compute known bits results from subtracting RHS from LHS with 1-bit Borrow.
KnownBits zextOrTrunc(unsigned BitWidth) const
Return known bits for a zero extension or truncation of the value we're tracking.
Definition KnownBits.h:200
APInt getMaxValue() const
Return the maximal unsigned value possible given these KnownBits.
Definition KnownBits.h:146
static LLVM_ABI KnownBits fshr(const KnownBits &LHS, const KnownBits &RHS, const APInt &Amt)
Compute known bits for fshr(LHS, RHS, Amt).
static LLVM_ABI KnownBits abds(KnownBits LHS, KnownBits RHS)
Compute known bits for abds(LHS, RHS).
static LLVM_ABI KnownBits smin(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for smin(LHS, RHS).
static LLVM_ABI KnownBits mulhs(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits from sign-extended multiply-hi.
static LLVM_ABI KnownBits srem(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for srem(LHS, RHS).
static LLVM_ABI KnownBits udiv(const KnownBits &LHS, const KnownBits &RHS, bool Exact=false)
Compute known bits for udiv(LHS, RHS).
bool isStrictlyPositive() const
Returns true if this value is known to be positive.
Definition KnownBits.h:112
static LLVM_ABI KnownBits sdiv(const KnownBits &LHS, const KnownBits &RHS, bool Exact=false)
Compute known bits for sdiv(LHS, RHS).
static LLVM_ABI KnownBits avgFloorS(const KnownBits &LHS, const KnownBits &RHS)
Compute knownbits resulting from APIntOps::avgFloorS.
static bool haveNoCommonBitsSet(const KnownBits &LHS, const KnownBits &RHS)
Return true if LHS and RHS have no common bits set.
Definition KnownBits.h:340
bool isNegative() const
Returns true if this value is known to be negative.
Definition KnownBits.h:103
static LLVM_ABI KnownBits computeForAddCarry(const KnownBits &LHS, const KnownBits &RHS, const KnownBits &Carry)
Compute known bits resulting from adding LHS, RHS and a 1-bit Carry.
Definition KnownBits.cpp:54
static KnownBits sub(const KnownBits &LHS, const KnownBits &RHS, bool NSW=false, bool NUW=false)
Compute knownbits resulting from subtraction of LHS and RHS.
Definition KnownBits.h:376
unsigned countMaxLeadingZeros() const
Returns the maximum number of leading zero bits possible.
Definition KnownBits.h:294
static LLVM_ABI KnownBits avgCeilU(const KnownBits &LHS, const KnownBits &RHS)
Compute knownbits resulting from APIntOps::avgCeilU.
static LLVM_ABI KnownBits mul(const KnownBits &LHS, const KnownBits &RHS, bool NoUndefSelfMultiply=false)
Compute known bits resulting from multiplying LHS and RHS.
KnownBits anyext(unsigned BitWidth) const
Return known bits for an "any" extension of the value we're tracking, where we don't know anything ab...
Definition KnownBits.h:171
static LLVM_ABI KnownBits clmul(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for clmul(LHS, RHS).
LLVM_ABI KnownBits abs(bool IntMinIsPoison=false) const
Compute known bits for the absolute value.
static LLVM_ABI KnownBits shl(const KnownBits &LHS, const KnownBits &RHS, bool NUW=false, bool NSW=false, bool ShAmtNonZero=false)
Compute known bits for shl(LHS, RHS).
static LLVM_ABI KnownBits umin(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for umin(LHS, RHS).
static LLVM_ABI KnownBits pext(const KnownBits &Val, const KnownBits &Mask)
Compute known bits for pext(Val, Mask).
static LLVM_ABI KnownBits avgCeilS(const KnownBits &LHS, const KnownBits &RHS)
Compute knownbits resulting from APIntOps::avgCeilS.
bool isUnknown() const
KnownFPClass intersectWith(const KnownFPClass &RHS) const
static LLVM_ABI KnownFPClass bitcast(const fltSemantics &FltSemantics, const KnownBits &Bits)
Report known values for a bitcast into a float with provided semantics.
LLVM IR metadata carried by a MachineMemOperand.
This class contains a discriminated union of information about pointers in memory operands,...
LLVM_ABI bool isDereferenceable(unsigned Size, LLVMContext &C, const DataLayout &DL) const
Return true if memory region [V, V+Offset+Size) is known to be dereferenceable.
LLVM_ABI unsigned getAddrSpace() const
Return the LLVM IR address space number that this pointer points into.
PointerUnion< const Value *, const PseudoSourceValue * > V
This is the IR pointer value for the access, or it is null if unknown.
MachinePointerInfo getWithOffset(int64_t O) const
static LLVM_ABI MachinePointerInfo getFixedStack(MachineFunction &MF, int FI, int64_t Offset=0)
Return a MachinePointerInfo record that refers to the specified FrameIndex.
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
Definition Alignment.h:106
Align valueOrOne() const
For convenience, returns a valid alignment or 1 if undefined.
Definition Alignment.h:130
static MemOp Set(uint64_t Size, bool DstAlignCanChange, Align DstAlign, bool IsZeroMemset, bool IsVolatile)
static MemOp Copy(uint64_t Size, bool DstAlignCanChange, Align DstAlign, Align SrcAlign, bool IsVolatile, bool MemcpyStrSrc=false)
static MemOp Move(uint64_t Size, bool DstAlignCanChange, Align DstAlign, Align SrcAlign, bool IsVolatile)
static StringRef getLibcallImplName(RTLIB::LibcallImpl CallImpl)
Get the libcall routine name for the specified libcall implementation.
These are IR-level optimization flags that may be propagated to SDNodes.
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)