[sanitizer] Improve FreeBSD ASLR detection
[llvm-project.git] / llvm / lib / CodeGen / SelectionDAG / SelectionDAG.cpp
blob71fb1e33dd4ce349c77bc6784c1921b63fd7c428
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.
11 //===----------------------------------------------------------------------===//
13 #include "llvm/CodeGen/SelectionDAG.h"
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/FoldingSet.h"
21 #include "llvm/ADT/None.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/ADT/SmallPtrSet.h"
24 #include "llvm/ADT/SmallVector.h"
25 #include "llvm/ADT/Triple.h"
26 #include "llvm/ADT/Twine.h"
27 #include "llvm/Analysis/BlockFrequencyInfo.h"
28 #include "llvm/Analysis/MemoryLocation.h"
29 #include "llvm/Analysis/ProfileSummaryInfo.h"
30 #include "llvm/Analysis/ValueTracking.h"
31 #include "llvm/CodeGen/Analysis.h"
32 #include "llvm/CodeGen/FunctionLoweringInfo.h"
33 #include "llvm/CodeGen/ISDOpcodes.h"
34 #include "llvm/CodeGen/MachineBasicBlock.h"
35 #include "llvm/CodeGen/MachineConstantPool.h"
36 #include "llvm/CodeGen/MachineFrameInfo.h"
37 #include "llvm/CodeGen/MachineFunction.h"
38 #include "llvm/CodeGen/MachineMemOperand.h"
39 #include "llvm/CodeGen/RuntimeLibcalls.h"
40 #include "llvm/CodeGen/SelectionDAGAddressAnalysis.h"
41 #include "llvm/CodeGen/SelectionDAGNodes.h"
42 #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
43 #include "llvm/CodeGen/TargetFrameLowering.h"
44 #include "llvm/CodeGen/TargetLowering.h"
45 #include "llvm/CodeGen/TargetRegisterInfo.h"
46 #include "llvm/CodeGen/TargetSubtargetInfo.h"
47 #include "llvm/CodeGen/ValueTypes.h"
48 #include "llvm/IR/Constant.h"
49 #include "llvm/IR/Constants.h"
50 #include "llvm/IR/DataLayout.h"
51 #include "llvm/IR/DebugInfoMetadata.h"
52 #include "llvm/IR/DebugLoc.h"
53 #include "llvm/IR/DerivedTypes.h"
54 #include "llvm/IR/Function.h"
55 #include "llvm/IR/GlobalValue.h"
56 #include "llvm/IR/Metadata.h"
57 #include "llvm/IR/Type.h"
58 #include "llvm/IR/Value.h"
59 #include "llvm/Support/Casting.h"
60 #include "llvm/Support/CodeGen.h"
61 #include "llvm/Support/Compiler.h"
62 #include "llvm/Support/Debug.h"
63 #include "llvm/Support/ErrorHandling.h"
64 #include "llvm/Support/KnownBits.h"
65 #include "llvm/Support/MachineValueType.h"
66 #include "llvm/Support/ManagedStatic.h"
67 #include "llvm/Support/MathExtras.h"
68 #include "llvm/Support/Mutex.h"
69 #include "llvm/Support/raw_ostream.h"
70 #include "llvm/Target/TargetMachine.h"
71 #include "llvm/Target/TargetOptions.h"
72 #include "llvm/Transforms/Utils/SizeOpts.h"
73 #include <algorithm>
74 #include <cassert>
75 #include <cstdint>
76 #include <cstdlib>
77 #include <limits>
78 #include <set>
79 #include <string>
80 #include <utility>
81 #include <vector>
83 using namespace llvm;
85 /// makeVTList - Return an instance of the SDVTList struct initialized with the
86 /// specified members.
87 static SDVTList makeVTList(const EVT *VTs, unsigned NumVTs) {
88 SDVTList Res = {VTs, NumVTs};
89 return Res;
92 // Default null implementations of the callbacks.
93 void SelectionDAG::DAGUpdateListener::NodeDeleted(SDNode*, SDNode*) {}
94 void SelectionDAG::DAGUpdateListener::NodeUpdated(SDNode*) {}
95 void SelectionDAG::DAGUpdateListener::NodeInserted(SDNode *) {}
97 void SelectionDAG::DAGNodeDeletedListener::anchor() {}
99 #define DEBUG_TYPE "selectiondag"
101 static cl::opt<bool> EnableMemCpyDAGOpt("enable-memcpy-dag-opt",
102 cl::Hidden, cl::init(true),
103 cl::desc("Gang up loads and stores generated by inlining of memcpy"));
105 static cl::opt<int> MaxLdStGlue("ldstmemcpy-glue-max",
106 cl::desc("Number limit for gluing ld/st of memcpy."),
107 cl::Hidden, cl::init(0));
109 static void NewSDValueDbgMsg(SDValue V, StringRef Msg, SelectionDAG *G) {
110 LLVM_DEBUG(dbgs() << Msg; V.getNode()->dump(G););
113 //===----------------------------------------------------------------------===//
114 // ConstantFPSDNode Class
115 //===----------------------------------------------------------------------===//
117 /// isExactlyValue - We don't rely on operator== working on double values, as
118 /// it returns true for things that are clearly not equal, like -0.0 and 0.0.
119 /// As such, this method can be used to do an exact bit-for-bit comparison of
120 /// two floating point values.
121 bool ConstantFPSDNode::isExactlyValue(const APFloat& V) const {
122 return getValueAPF().bitwiseIsEqual(V);
125 bool ConstantFPSDNode::isValueValidForType(EVT VT,
126 const APFloat& Val) {
127 assert(VT.isFloatingPoint() && "Can only convert between FP types");
129 // convert modifies in place, so make a copy.
130 APFloat Val2 = APFloat(Val);
131 bool losesInfo;
132 (void) Val2.convert(SelectionDAG::EVTToAPFloatSemantics(VT),
133 APFloat::rmNearestTiesToEven,
134 &losesInfo);
135 return !losesInfo;
138 //===----------------------------------------------------------------------===//
139 // ISD Namespace
140 //===----------------------------------------------------------------------===//
142 bool ISD::isConstantSplatVector(const SDNode *N, APInt &SplatVal) {
143 if (N->getOpcode() == ISD::SPLAT_VECTOR) {
144 unsigned EltSize =
145 N->getValueType(0).getVectorElementType().getSizeInBits();
146 if (auto *Op0 = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
147 SplatVal = Op0->getAPIntValue().truncOrSelf(EltSize);
148 return true;
150 if (auto *Op0 = dyn_cast<ConstantFPSDNode>(N->getOperand(0))) {
151 SplatVal = Op0->getValueAPF().bitcastToAPInt().truncOrSelf(EltSize);
152 return true;
156 auto *BV = dyn_cast<BuildVectorSDNode>(N);
157 if (!BV)
158 return false;
160 APInt SplatUndef;
161 unsigned SplatBitSize;
162 bool HasUndefs;
163 unsigned EltSize = N->getValueType(0).getVectorElementType().getSizeInBits();
164 return BV->isConstantSplat(SplatVal, SplatUndef, SplatBitSize, HasUndefs,
165 EltSize) &&
166 EltSize == SplatBitSize;
169 // FIXME: AllOnes and AllZeros duplicate a lot of code. Could these be
170 // specializations of the more general isConstantSplatVector()?
172 bool ISD::isConstantSplatVectorAllOnes(const SDNode *N, bool BuildVectorOnly) {
173 // Look through a bit convert.
174 while (N->getOpcode() == ISD::BITCAST)
175 N = N->getOperand(0).getNode();
177 if (!BuildVectorOnly && N->getOpcode() == ISD::SPLAT_VECTOR) {
178 APInt SplatVal;
179 return isConstantSplatVector(N, SplatVal) && SplatVal.isAllOnes();
182 if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
184 unsigned i = 0, e = N->getNumOperands();
186 // Skip over all of the undef values.
187 while (i != e && N->getOperand(i).isUndef())
188 ++i;
190 // Do not accept an all-undef vector.
191 if (i == e) return false;
193 // Do not accept build_vectors that aren't all constants or which have non-~0
194 // elements. We have to be a bit careful here, as the type of the constant
195 // may not be the same as the type of the vector elements due to type
196 // legalization (the elements are promoted to a legal type for the target and
197 // a vector of a type may be legal when the base element type is not).
198 // We only want to check enough bits to cover the vector elements, because
199 // we care if the resultant vector is all ones, not whether the individual
200 // constants are.
201 SDValue NotZero = N->getOperand(i);
202 unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
203 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(NotZero)) {
204 if (CN->getAPIntValue().countTrailingOnes() < EltSize)
205 return false;
206 } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(NotZero)) {
207 if (CFPN->getValueAPF().bitcastToAPInt().countTrailingOnes() < EltSize)
208 return false;
209 } else
210 return false;
212 // Okay, we have at least one ~0 value, check to see if the rest match or are
213 // undefs. Even with the above element type twiddling, this should be OK, as
214 // the same type legalization should have applied to all the elements.
215 for (++i; i != e; ++i)
216 if (N->getOperand(i) != NotZero && !N->getOperand(i).isUndef())
217 return false;
218 return true;
221 bool ISD::isConstantSplatVectorAllZeros(const SDNode *N, bool BuildVectorOnly) {
222 // Look through a bit convert.
223 while (N->getOpcode() == ISD::BITCAST)
224 N = N->getOperand(0).getNode();
226 if (!BuildVectorOnly && N->getOpcode() == ISD::SPLAT_VECTOR) {
227 APInt SplatVal;
228 return isConstantSplatVector(N, SplatVal) && SplatVal.isZero();
231 if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
233 bool IsAllUndef = true;
234 for (const SDValue &Op : N->op_values()) {
235 if (Op.isUndef())
236 continue;
237 IsAllUndef = false;
238 // Do not accept build_vectors that aren't all constants or which have non-0
239 // elements. We have to be a bit careful here, as the type of the constant
240 // may not be the same as the type of the vector elements due to type
241 // legalization (the elements are promoted to a legal type for the target
242 // and a vector of a type may be legal when the base element type is not).
243 // We only want to check enough bits to cover the vector elements, because
244 // we care if the resultant vector is all zeros, not whether the individual
245 // constants are.
246 unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
247 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Op)) {
248 if (CN->getAPIntValue().countTrailingZeros() < EltSize)
249 return false;
250 } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(Op)) {
251 if (CFPN->getValueAPF().bitcastToAPInt().countTrailingZeros() < EltSize)
252 return false;
253 } else
254 return false;
257 // Do not accept an all-undef vector.
258 if (IsAllUndef)
259 return false;
260 return true;
263 bool ISD::isBuildVectorAllOnes(const SDNode *N) {
264 return isConstantSplatVectorAllOnes(N, /*BuildVectorOnly*/ true);
267 bool ISD::isBuildVectorAllZeros(const SDNode *N) {
268 return isConstantSplatVectorAllZeros(N, /*BuildVectorOnly*/ true);
271 bool ISD::isBuildVectorOfConstantSDNodes(const SDNode *N) {
272 if (N->getOpcode() != ISD::BUILD_VECTOR)
273 return false;
275 for (const SDValue &Op : N->op_values()) {
276 if (Op.isUndef())
277 continue;
278 if (!isa<ConstantSDNode>(Op))
279 return false;
281 return true;
284 bool ISD::isBuildVectorOfConstantFPSDNodes(const SDNode *N) {
285 if (N->getOpcode() != ISD::BUILD_VECTOR)
286 return false;
288 for (const SDValue &Op : N->op_values()) {
289 if (Op.isUndef())
290 continue;
291 if (!isa<ConstantFPSDNode>(Op))
292 return false;
294 return true;
297 bool ISD::allOperandsUndef(const SDNode *N) {
298 // Return false if the node has no operands.
299 // This is "logically inconsistent" with the definition of "all" but
300 // is probably the desired behavior.
301 if (N->getNumOperands() == 0)
302 return false;
303 return all_of(N->op_values(), [](SDValue Op) { return Op.isUndef(); });
306 bool ISD::matchUnaryPredicate(SDValue Op,
307 std::function<bool(ConstantSDNode *)> Match,
308 bool AllowUndefs) {
309 // FIXME: Add support for scalar UNDEF cases?
310 if (auto *Cst = dyn_cast<ConstantSDNode>(Op))
311 return Match(Cst);
313 // FIXME: Add support for vector UNDEF cases?
314 if (ISD::BUILD_VECTOR != Op.getOpcode() &&
315 ISD::SPLAT_VECTOR != Op.getOpcode())
316 return false;
318 EVT SVT = Op.getValueType().getScalarType();
319 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
320 if (AllowUndefs && Op.getOperand(i).isUndef()) {
321 if (!Match(nullptr))
322 return false;
323 continue;
326 auto *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(i));
327 if (!Cst || Cst->getValueType(0) != SVT || !Match(Cst))
328 return false;
330 return true;
333 bool ISD::matchBinaryPredicate(
334 SDValue LHS, SDValue RHS,
335 std::function<bool(ConstantSDNode *, ConstantSDNode *)> Match,
336 bool AllowUndefs, bool AllowTypeMismatch) {
337 if (!AllowTypeMismatch && LHS.getValueType() != RHS.getValueType())
338 return false;
340 // TODO: Add support for scalar UNDEF cases?
341 if (auto *LHSCst = dyn_cast<ConstantSDNode>(LHS))
342 if (auto *RHSCst = dyn_cast<ConstantSDNode>(RHS))
343 return Match(LHSCst, RHSCst);
345 // TODO: Add support for vector UNDEF cases?
346 if (LHS.getOpcode() != RHS.getOpcode() ||
347 (LHS.getOpcode() != ISD::BUILD_VECTOR &&
348 LHS.getOpcode() != ISD::SPLAT_VECTOR))
349 return false;
351 EVT SVT = LHS.getValueType().getScalarType();
352 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
353 SDValue LHSOp = LHS.getOperand(i);
354 SDValue RHSOp = RHS.getOperand(i);
355 bool LHSUndef = AllowUndefs && LHSOp.isUndef();
356 bool RHSUndef = AllowUndefs && RHSOp.isUndef();
357 auto *LHSCst = dyn_cast<ConstantSDNode>(LHSOp);
358 auto *RHSCst = dyn_cast<ConstantSDNode>(RHSOp);
359 if ((!LHSCst && !LHSUndef) || (!RHSCst && !RHSUndef))
360 return false;
361 if (!AllowTypeMismatch && (LHSOp.getValueType() != SVT ||
362 LHSOp.getValueType() != RHSOp.getValueType()))
363 return false;
364 if (!Match(LHSCst, RHSCst))
365 return false;
367 return true;
370 ISD::NodeType ISD::getVecReduceBaseOpcode(unsigned VecReduceOpcode) {
371 switch (VecReduceOpcode) {
372 default:
373 llvm_unreachable("Expected VECREDUCE opcode");
374 case ISD::VECREDUCE_FADD:
375 case ISD::VECREDUCE_SEQ_FADD:
376 case ISD::VP_REDUCE_FADD:
377 case ISD::VP_REDUCE_SEQ_FADD:
378 return ISD::FADD;
379 case ISD::VECREDUCE_FMUL:
380 case ISD::VECREDUCE_SEQ_FMUL:
381 case ISD::VP_REDUCE_FMUL:
382 case ISD::VP_REDUCE_SEQ_FMUL:
383 return ISD::FMUL;
384 case ISD::VECREDUCE_ADD:
385 case ISD::VP_REDUCE_ADD:
386 return ISD::ADD;
387 case ISD::VECREDUCE_MUL:
388 case ISD::VP_REDUCE_MUL:
389 return ISD::MUL;
390 case ISD::VECREDUCE_AND:
391 case ISD::VP_REDUCE_AND:
392 return ISD::AND;
393 case ISD::VECREDUCE_OR:
394 case ISD::VP_REDUCE_OR:
395 return ISD::OR;
396 case ISD::VECREDUCE_XOR:
397 case ISD::VP_REDUCE_XOR:
398 return ISD::XOR;
399 case ISD::VECREDUCE_SMAX:
400 case ISD::VP_REDUCE_SMAX:
401 return ISD::SMAX;
402 case ISD::VECREDUCE_SMIN:
403 case ISD::VP_REDUCE_SMIN:
404 return ISD::SMIN;
405 case ISD::VECREDUCE_UMAX:
406 case ISD::VP_REDUCE_UMAX:
407 return ISD::UMAX;
408 case ISD::VECREDUCE_UMIN:
409 case ISD::VP_REDUCE_UMIN:
410 return ISD::UMIN;
411 case ISD::VECREDUCE_FMAX:
412 case ISD::VP_REDUCE_FMAX:
413 return ISD::FMAXNUM;
414 case ISD::VECREDUCE_FMIN:
415 case ISD::VP_REDUCE_FMIN:
416 return ISD::FMINNUM;
420 bool ISD::isVPOpcode(unsigned Opcode) {
421 switch (Opcode) {
422 default:
423 return false;
424 #define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) \
425 case ISD::VPSD: \
426 return true;
427 #include "llvm/IR/VPIntrinsics.def"
431 bool ISD::isVPBinaryOp(unsigned Opcode) {
432 switch (Opcode) {
433 default:
434 break;
435 #define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) case ISD::VPSD:
436 #define VP_PROPERTY_BINARYOP return true;
437 #define END_REGISTER_VP_SDNODE(VPSD) break;
438 #include "llvm/IR/VPIntrinsics.def"
440 return false;
443 bool ISD::isVPReduction(unsigned Opcode) {
444 switch (Opcode) {
445 default:
446 break;
447 #define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) case ISD::VPSD:
448 #define VP_PROPERTY_REDUCTION(STARTPOS, ...) return true;
449 #define END_REGISTER_VP_SDNODE(VPSD) break;
450 #include "llvm/IR/VPIntrinsics.def"
452 return false;
455 /// The operand position of the vector mask.
456 Optional<unsigned> ISD::getVPMaskIdx(unsigned Opcode) {
457 switch (Opcode) {
458 default:
459 return None;
460 #define BEGIN_REGISTER_VP_SDNODE(VPSD, LEGALPOS, TDNAME, MASKPOS, ...) \
461 case ISD::VPSD: \
462 return MASKPOS;
463 #include "llvm/IR/VPIntrinsics.def"
467 /// The operand position of the explicit vector length parameter.
468 Optional<unsigned> ISD::getVPExplicitVectorLengthIdx(unsigned Opcode) {
469 switch (Opcode) {
470 default:
471 return None;
472 #define BEGIN_REGISTER_VP_SDNODE(VPSD, LEGALPOS, TDNAME, MASKPOS, EVLPOS) \
473 case ISD::VPSD: \
474 return EVLPOS;
475 #include "llvm/IR/VPIntrinsics.def"
479 ISD::NodeType ISD::getExtForLoadExtType(bool IsFP, ISD::LoadExtType ExtType) {
480 switch (ExtType) {
481 case ISD::EXTLOAD:
482 return IsFP ? ISD::FP_EXTEND : ISD::ANY_EXTEND;
483 case ISD::SEXTLOAD:
484 return ISD::SIGN_EXTEND;
485 case ISD::ZEXTLOAD:
486 return ISD::ZERO_EXTEND;
487 default:
488 break;
491 llvm_unreachable("Invalid LoadExtType");
494 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) {
495 // To perform this operation, we just need to swap the L and G bits of the
496 // operation.
497 unsigned OldL = (Operation >> 2) & 1;
498 unsigned OldG = (Operation >> 1) & 1;
499 return ISD::CondCode((Operation & ~6) | // Keep the N, U, E bits
500 (OldL << 1) | // New G bit
501 (OldG << 2)); // New L bit.
504 static ISD::CondCode getSetCCInverseImpl(ISD::CondCode Op, bool isIntegerLike) {
505 unsigned Operation = Op;
506 if (isIntegerLike)
507 Operation ^= 7; // Flip L, G, E bits, but not U.
508 else
509 Operation ^= 15; // Flip all of the condition bits.
511 if (Operation > ISD::SETTRUE2)
512 Operation &= ~8; // Don't let N and U bits get set.
514 return ISD::CondCode(Operation);
517 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, EVT Type) {
518 return getSetCCInverseImpl(Op, Type.isInteger());
521 ISD::CondCode ISD::GlobalISel::getSetCCInverse(ISD::CondCode Op,
522 bool isIntegerLike) {
523 return getSetCCInverseImpl(Op, isIntegerLike);
526 /// For an integer comparison, return 1 if the comparison is a signed operation
527 /// and 2 if the result is an unsigned comparison. Return zero if the operation
528 /// does not depend on the sign of the input (setne and seteq).
529 static int isSignedOp(ISD::CondCode Opcode) {
530 switch (Opcode) {
531 default: llvm_unreachable("Illegal integer setcc operation!");
532 case ISD::SETEQ:
533 case ISD::SETNE: return 0;
534 case ISD::SETLT:
535 case ISD::SETLE:
536 case ISD::SETGT:
537 case ISD::SETGE: return 1;
538 case ISD::SETULT:
539 case ISD::SETULE:
540 case ISD::SETUGT:
541 case ISD::SETUGE: return 2;
545 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2,
546 EVT Type) {
547 bool IsInteger = Type.isInteger();
548 if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
549 // Cannot fold a signed integer setcc with an unsigned integer setcc.
550 return ISD::SETCC_INVALID;
552 unsigned Op = Op1 | Op2; // Combine all of the condition bits.
554 // If the N and U bits get set, then the resultant comparison DOES suddenly
555 // care about orderedness, and it is true when ordered.
556 if (Op > ISD::SETTRUE2)
557 Op &= ~16; // Clear the U bit if the N bit is set.
559 // Canonicalize illegal integer setcc's.
560 if (IsInteger && Op == ISD::SETUNE) // e.g. SETUGT | SETULT
561 Op = ISD::SETNE;
563 return ISD::CondCode(Op);
566 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2,
567 EVT Type) {
568 bool IsInteger = Type.isInteger();
569 if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
570 // Cannot fold a signed setcc with an unsigned setcc.
571 return ISD::SETCC_INVALID;
573 // Combine all of the condition bits.
574 ISD::CondCode Result = ISD::CondCode(Op1 & Op2);
576 // Canonicalize illegal integer setcc's.
577 if (IsInteger) {
578 switch (Result) {
579 default: break;
580 case ISD::SETUO : Result = ISD::SETFALSE; break; // SETUGT & SETULT
581 case ISD::SETOEQ: // SETEQ & SETU[LG]E
582 case ISD::SETUEQ: Result = ISD::SETEQ ; break; // SETUGE & SETULE
583 case ISD::SETOLT: Result = ISD::SETULT ; break; // SETULT & SETNE
584 case ISD::SETOGT: Result = ISD::SETUGT ; break; // SETUGT & SETNE
588 return Result;
591 //===----------------------------------------------------------------------===//
592 // SDNode Profile Support
593 //===----------------------------------------------------------------------===//
595 /// AddNodeIDOpcode - Add the node opcode to the NodeID data.
596 static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC) {
597 ID.AddInteger(OpC);
600 /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them
601 /// solely with their pointer.
602 static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) {
603 ID.AddPointer(VTList.VTs);
606 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
607 static void AddNodeIDOperands(FoldingSetNodeID &ID,
608 ArrayRef<SDValue> Ops) {
609 for (auto& Op : Ops) {
610 ID.AddPointer(Op.getNode());
611 ID.AddInteger(Op.getResNo());
615 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
616 static void AddNodeIDOperands(FoldingSetNodeID &ID,
617 ArrayRef<SDUse> Ops) {
618 for (auto& Op : Ops) {
619 ID.AddPointer(Op.getNode());
620 ID.AddInteger(Op.getResNo());
624 static void AddNodeIDNode(FoldingSetNodeID &ID, unsigned short OpC,
625 SDVTList VTList, ArrayRef<SDValue> OpList) {
626 AddNodeIDOpcode(ID, OpC);
627 AddNodeIDValueTypes(ID, VTList);
628 AddNodeIDOperands(ID, OpList);
631 /// If this is an SDNode with special info, add this info to the NodeID data.
632 static void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N) {
633 switch (N->getOpcode()) {
634 case ISD::TargetExternalSymbol:
635 case ISD::ExternalSymbol:
636 case ISD::MCSymbol:
637 llvm_unreachable("Should only be used on nodes with operands");
638 default: break; // Normal nodes don't need extra info.
639 case ISD::TargetConstant:
640 case ISD::Constant: {
641 const ConstantSDNode *C = cast<ConstantSDNode>(N);
642 ID.AddPointer(C->getConstantIntValue());
643 ID.AddBoolean(C->isOpaque());
644 break;
646 case ISD::TargetConstantFP:
647 case ISD::ConstantFP:
648 ID.AddPointer(cast<ConstantFPSDNode>(N)->getConstantFPValue());
649 break;
650 case ISD::TargetGlobalAddress:
651 case ISD::GlobalAddress:
652 case ISD::TargetGlobalTLSAddress:
653 case ISD::GlobalTLSAddress: {
654 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
655 ID.AddPointer(GA->getGlobal());
656 ID.AddInteger(GA->getOffset());
657 ID.AddInteger(GA->getTargetFlags());
658 break;
660 case ISD::BasicBlock:
661 ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock());
662 break;
663 case ISD::Register:
664 ID.AddInteger(cast<RegisterSDNode>(N)->getReg());
665 break;
666 case ISD::RegisterMask:
667 ID.AddPointer(cast<RegisterMaskSDNode>(N)->getRegMask());
668 break;
669 case ISD::SRCVALUE:
670 ID.AddPointer(cast<SrcValueSDNode>(N)->getValue());
671 break;
672 case ISD::FrameIndex:
673 case ISD::TargetFrameIndex:
674 ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex());
675 break;
676 case ISD::LIFETIME_START:
677 case ISD::LIFETIME_END:
678 if (cast<LifetimeSDNode>(N)->hasOffset()) {
679 ID.AddInteger(cast<LifetimeSDNode>(N)->getSize());
680 ID.AddInteger(cast<LifetimeSDNode>(N)->getOffset());
682 break;
683 case ISD::PSEUDO_PROBE:
684 ID.AddInteger(cast<PseudoProbeSDNode>(N)->getGuid());
685 ID.AddInteger(cast<PseudoProbeSDNode>(N)->getIndex());
686 ID.AddInteger(cast<PseudoProbeSDNode>(N)->getAttributes());
687 break;
688 case ISD::JumpTable:
689 case ISD::TargetJumpTable:
690 ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex());
691 ID.AddInteger(cast<JumpTableSDNode>(N)->getTargetFlags());
692 break;
693 case ISD::ConstantPool:
694 case ISD::TargetConstantPool: {
695 const ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N);
696 ID.AddInteger(CP->getAlign().value());
697 ID.AddInteger(CP->getOffset());
698 if (CP->isMachineConstantPoolEntry())
699 CP->getMachineCPVal()->addSelectionDAGCSEId(ID);
700 else
701 ID.AddPointer(CP->getConstVal());
702 ID.AddInteger(CP->getTargetFlags());
703 break;
705 case ISD::TargetIndex: {
706 const TargetIndexSDNode *TI = cast<TargetIndexSDNode>(N);
707 ID.AddInteger(TI->getIndex());
708 ID.AddInteger(TI->getOffset());
709 ID.AddInteger(TI->getTargetFlags());
710 break;
712 case ISD::LOAD: {
713 const LoadSDNode *LD = cast<LoadSDNode>(N);
714 ID.AddInteger(LD->getMemoryVT().getRawBits());
715 ID.AddInteger(LD->getRawSubclassData());
716 ID.AddInteger(LD->getPointerInfo().getAddrSpace());
717 break;
719 case ISD::STORE: {
720 const StoreSDNode *ST = cast<StoreSDNode>(N);
721 ID.AddInteger(ST->getMemoryVT().getRawBits());
722 ID.AddInteger(ST->getRawSubclassData());
723 ID.AddInteger(ST->getPointerInfo().getAddrSpace());
724 break;
726 case ISD::VP_LOAD: {
727 const VPLoadSDNode *ELD = cast<VPLoadSDNode>(N);
728 ID.AddInteger(ELD->getMemoryVT().getRawBits());
729 ID.AddInteger(ELD->getRawSubclassData());
730 ID.AddInteger(ELD->getPointerInfo().getAddrSpace());
731 break;
733 case ISD::VP_STORE: {
734 const VPStoreSDNode *EST = cast<VPStoreSDNode>(N);
735 ID.AddInteger(EST->getMemoryVT().getRawBits());
736 ID.AddInteger(EST->getRawSubclassData());
737 ID.AddInteger(EST->getPointerInfo().getAddrSpace());
738 break;
740 case ISD::VP_GATHER: {
741 const VPGatherSDNode *EG = cast<VPGatherSDNode>(N);
742 ID.AddInteger(EG->getMemoryVT().getRawBits());
743 ID.AddInteger(EG->getRawSubclassData());
744 ID.AddInteger(EG->getPointerInfo().getAddrSpace());
745 break;
747 case ISD::VP_SCATTER: {
748 const VPScatterSDNode *ES = cast<VPScatterSDNode>(N);
749 ID.AddInteger(ES->getMemoryVT().getRawBits());
750 ID.AddInteger(ES->getRawSubclassData());
751 ID.AddInteger(ES->getPointerInfo().getAddrSpace());
752 break;
754 case ISD::MLOAD: {
755 const MaskedLoadSDNode *MLD = cast<MaskedLoadSDNode>(N);
756 ID.AddInteger(MLD->getMemoryVT().getRawBits());
757 ID.AddInteger(MLD->getRawSubclassData());
758 ID.AddInteger(MLD->getPointerInfo().getAddrSpace());
759 break;
761 case ISD::MSTORE: {
762 const MaskedStoreSDNode *MST = cast<MaskedStoreSDNode>(N);
763 ID.AddInteger(MST->getMemoryVT().getRawBits());
764 ID.AddInteger(MST->getRawSubclassData());
765 ID.AddInteger(MST->getPointerInfo().getAddrSpace());
766 break;
768 case ISD::MGATHER: {
769 const MaskedGatherSDNode *MG = cast<MaskedGatherSDNode>(N);
770 ID.AddInteger(MG->getMemoryVT().getRawBits());
771 ID.AddInteger(MG->getRawSubclassData());
772 ID.AddInteger(MG->getPointerInfo().getAddrSpace());
773 break;
775 case ISD::MSCATTER: {
776 const MaskedScatterSDNode *MS = cast<MaskedScatterSDNode>(N);
777 ID.AddInteger(MS->getMemoryVT().getRawBits());
778 ID.AddInteger(MS->getRawSubclassData());
779 ID.AddInteger(MS->getPointerInfo().getAddrSpace());
780 break;
782 case ISD::ATOMIC_CMP_SWAP:
783 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
784 case ISD::ATOMIC_SWAP:
785 case ISD::ATOMIC_LOAD_ADD:
786 case ISD::ATOMIC_LOAD_SUB:
787 case ISD::ATOMIC_LOAD_AND:
788 case ISD::ATOMIC_LOAD_CLR:
789 case ISD::ATOMIC_LOAD_OR:
790 case ISD::ATOMIC_LOAD_XOR:
791 case ISD::ATOMIC_LOAD_NAND:
792 case ISD::ATOMIC_LOAD_MIN:
793 case ISD::ATOMIC_LOAD_MAX:
794 case ISD::ATOMIC_LOAD_UMIN:
795 case ISD::ATOMIC_LOAD_UMAX:
796 case ISD::ATOMIC_LOAD:
797 case ISD::ATOMIC_STORE: {
798 const AtomicSDNode *AT = cast<AtomicSDNode>(N);
799 ID.AddInteger(AT->getMemoryVT().getRawBits());
800 ID.AddInteger(AT->getRawSubclassData());
801 ID.AddInteger(AT->getPointerInfo().getAddrSpace());
802 break;
804 case ISD::PREFETCH: {
805 const MemSDNode *PF = cast<MemSDNode>(N);
806 ID.AddInteger(PF->getPointerInfo().getAddrSpace());
807 break;
809 case ISD::VECTOR_SHUFFLE: {
810 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
811 for (unsigned i = 0, e = N->getValueType(0).getVectorNumElements();
812 i != e; ++i)
813 ID.AddInteger(SVN->getMaskElt(i));
814 break;
816 case ISD::TargetBlockAddress:
817 case ISD::BlockAddress: {
818 const BlockAddressSDNode *BA = cast<BlockAddressSDNode>(N);
819 ID.AddPointer(BA->getBlockAddress());
820 ID.AddInteger(BA->getOffset());
821 ID.AddInteger(BA->getTargetFlags());
822 break;
824 } // end switch (N->getOpcode())
826 // Target specific memory nodes could also have address spaces to check.
827 if (N->isTargetMemoryOpcode())
828 ID.AddInteger(cast<MemSDNode>(N)->getPointerInfo().getAddrSpace());
831 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID
832 /// data.
833 static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) {
834 AddNodeIDOpcode(ID, N->getOpcode());
835 // Add the return value info.
836 AddNodeIDValueTypes(ID, N->getVTList());
837 // Add the operand info.
838 AddNodeIDOperands(ID, N->ops());
840 // Handle SDNode leafs with special info.
841 AddNodeIDCustom(ID, N);
844 //===----------------------------------------------------------------------===//
845 // SelectionDAG Class
846 //===----------------------------------------------------------------------===//
848 /// doNotCSE - Return true if CSE should not be performed for this node.
849 static bool doNotCSE(SDNode *N) {
850 if (N->getValueType(0) == MVT::Glue)
851 return true; // Never CSE anything that produces a flag.
853 switch (N->getOpcode()) {
854 default: break;
855 case ISD::HANDLENODE:
856 case ISD::EH_LABEL:
857 return true; // Never CSE these nodes.
860 // Check that remaining values produced are not flags.
861 for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
862 if (N->getValueType(i) == MVT::Glue)
863 return true; // Never CSE anything that produces a flag.
865 return false;
868 /// RemoveDeadNodes - This method deletes all unreachable nodes in the
869 /// SelectionDAG.
870 void SelectionDAG::RemoveDeadNodes() {
871 // Create a dummy node (which is not added to allnodes), that adds a reference
872 // to the root node, preventing it from being deleted.
873 HandleSDNode Dummy(getRoot());
875 SmallVector<SDNode*, 128> DeadNodes;
877 // Add all obviously-dead nodes to the DeadNodes worklist.
878 for (SDNode &Node : allnodes())
879 if (Node.use_empty())
880 DeadNodes.push_back(&Node);
882 RemoveDeadNodes(DeadNodes);
884 // If the root changed (e.g. it was a dead load, update the root).
885 setRoot(Dummy.getValue());
888 /// RemoveDeadNodes - This method deletes the unreachable nodes in the
889 /// given list, and any nodes that become unreachable as a result.
890 void SelectionDAG::RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes) {
892 // Process the worklist, deleting the nodes and adding their uses to the
893 // worklist.
894 while (!DeadNodes.empty()) {
895 SDNode *N = DeadNodes.pop_back_val();
896 // Skip to next node if we've already managed to delete the node. This could
897 // happen if replacing a node causes a node previously added to the node to
898 // be deleted.
899 if (N->getOpcode() == ISD::DELETED_NODE)
900 continue;
902 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
903 DUL->NodeDeleted(N, nullptr);
905 // Take the node out of the appropriate CSE map.
906 RemoveNodeFromCSEMaps(N);
908 // Next, brutally remove the operand list. This is safe to do, as there are
909 // no cycles in the graph.
910 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
911 SDUse &Use = *I++;
912 SDNode *Operand = Use.getNode();
913 Use.set(SDValue());
915 // Now that we removed this operand, see if there are no uses of it left.
916 if (Operand->use_empty())
917 DeadNodes.push_back(Operand);
920 DeallocateNode(N);
924 void SelectionDAG::RemoveDeadNode(SDNode *N){
925 SmallVector<SDNode*, 16> DeadNodes(1, N);
927 // Create a dummy node that adds a reference to the root node, preventing
928 // it from being deleted. (This matters if the root is an operand of the
929 // dead node.)
930 HandleSDNode Dummy(getRoot());
932 RemoveDeadNodes(DeadNodes);
935 void SelectionDAG::DeleteNode(SDNode *N) {
936 // First take this out of the appropriate CSE map.
937 RemoveNodeFromCSEMaps(N);
939 // Finally, remove uses due to operands of this node, remove from the
940 // AllNodes list, and delete the node.
941 DeleteNodeNotInCSEMaps(N);
944 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
945 assert(N->getIterator() != AllNodes.begin() &&
946 "Cannot delete the entry node!");
947 assert(N->use_empty() && "Cannot delete a node that is not dead!");
949 // Drop all of the operands and decrement used node's use counts.
950 N->DropOperands();
952 DeallocateNode(N);
955 void SDDbgInfo::add(SDDbgValue *V, bool isParameter) {
956 assert(!(V->isVariadic() && isParameter));
957 if (isParameter)
958 ByvalParmDbgValues.push_back(V);
959 else
960 DbgValues.push_back(V);
961 for (const SDNode *Node : V->getSDNodes())
962 if (Node)
963 DbgValMap[Node].push_back(V);
966 void SDDbgInfo::erase(const SDNode *Node) {
967 DbgValMapType::iterator I = DbgValMap.find(Node);
968 if (I == DbgValMap.end())
969 return;
970 for (auto &Val: I->second)
971 Val->setIsInvalidated();
972 DbgValMap.erase(I);
975 void SelectionDAG::DeallocateNode(SDNode *N) {
976 // If we have operands, deallocate them.
977 removeOperands(N);
979 NodeAllocator.Deallocate(AllNodes.remove(N));
981 // Set the opcode to DELETED_NODE to help catch bugs when node
982 // memory is reallocated.
983 // FIXME: There are places in SDag that have grown a dependency on the opcode
984 // value in the released node.
985 __asan_unpoison_memory_region(&N->NodeType, sizeof(N->NodeType));
986 N->NodeType = ISD::DELETED_NODE;
988 // If any of the SDDbgValue nodes refer to this SDNode, invalidate
989 // them and forget about that node.
990 DbgInfo->erase(N);
993 #ifndef NDEBUG
994 /// VerifySDNode - Check the given SDNode. Aborts if it is invalid.
995 static void VerifySDNode(SDNode *N) {
996 switch (N->getOpcode()) {
997 default:
998 break;
999 case ISD::BUILD_PAIR: {
1000 EVT VT = N->getValueType(0);
1001 assert(N->getNumValues() == 1 && "Too many results!");
1002 assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) &&
1003 "Wrong return type!");
1004 assert(N->getNumOperands() == 2 && "Wrong number of operands!");
1005 assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() &&
1006 "Mismatched operand types!");
1007 assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() &&
1008 "Wrong operand type!");
1009 assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() &&
1010 "Wrong return type size");
1011 break;
1013 case ISD::BUILD_VECTOR: {
1014 assert(N->getNumValues() == 1 && "Too many results!");
1015 assert(N->getValueType(0).isVector() && "Wrong return type!");
1016 assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() &&
1017 "Wrong number of operands!");
1018 EVT EltVT = N->getValueType(0).getVectorElementType();
1019 for (const SDUse &Op : N->ops()) {
1020 assert((Op.getValueType() == EltVT ||
1021 (EltVT.isInteger() && Op.getValueType().isInteger() &&
1022 EltVT.bitsLE(Op.getValueType()))) &&
1023 "Wrong operand type!");
1024 assert(Op.getValueType() == N->getOperand(0).getValueType() &&
1025 "Operands must all have the same type");
1027 break;
1031 #endif // NDEBUG
1033 /// Insert a newly allocated node into the DAG.
1035 /// Handles insertion into the all nodes list and CSE map, as well as
1036 /// verification and other common operations when a new node is allocated.
1037 void SelectionDAG::InsertNode(SDNode *N) {
1038 AllNodes.push_back(N);
1039 #ifndef NDEBUG
1040 N->PersistentId = NextPersistentId++;
1041 VerifySDNode(N);
1042 #endif
1043 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1044 DUL->NodeInserted(N);
1047 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
1048 /// correspond to it. This is useful when we're about to delete or repurpose
1049 /// the node. We don't want future request for structurally identical nodes
1050 /// to return N anymore.
1051 bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
1052 bool Erased = false;
1053 switch (N->getOpcode()) {
1054 case ISD::HANDLENODE: return false; // noop.
1055 case ISD::CONDCODE:
1056 assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
1057 "Cond code doesn't exist!");
1058 Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != nullptr;
1059 CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = nullptr;
1060 break;
1061 case ISD::ExternalSymbol:
1062 Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
1063 break;
1064 case ISD::TargetExternalSymbol: {
1065 ExternalSymbolSDNode *ESN = cast<ExternalSymbolSDNode>(N);
1066 Erased = TargetExternalSymbols.erase(std::pair<std::string, unsigned>(
1067 ESN->getSymbol(), ESN->getTargetFlags()));
1068 break;
1070 case ISD::MCSymbol: {
1071 auto *MCSN = cast<MCSymbolSDNode>(N);
1072 Erased = MCSymbols.erase(MCSN->getMCSymbol());
1073 break;
1075 case ISD::VALUETYPE: {
1076 EVT VT = cast<VTSDNode>(N)->getVT();
1077 if (VT.isExtended()) {
1078 Erased = ExtendedValueTypeNodes.erase(VT);
1079 } else {
1080 Erased = ValueTypeNodes[VT.getSimpleVT().SimpleTy] != nullptr;
1081 ValueTypeNodes[VT.getSimpleVT().SimpleTy] = nullptr;
1083 break;
1085 default:
1086 // Remove it from the CSE Map.
1087 assert(N->getOpcode() != ISD::DELETED_NODE && "DELETED_NODE in CSEMap!");
1088 assert(N->getOpcode() != ISD::EntryToken && "EntryToken in CSEMap!");
1089 Erased = CSEMap.RemoveNode(N);
1090 break;
1092 #ifndef NDEBUG
1093 // Verify that the node was actually in one of the CSE maps, unless it has a
1094 // flag result (which cannot be CSE'd) or is one of the special cases that are
1095 // not subject to CSE.
1096 if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Glue &&
1097 !N->isMachineOpcode() && !doNotCSE(N)) {
1098 N->dump(this);
1099 dbgs() << "\n";
1100 llvm_unreachable("Node is not in map!");
1102 #endif
1103 return Erased;
1106 /// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE
1107 /// maps and modified in place. Add it back to the CSE maps, unless an identical
1108 /// node already exists, in which case transfer all its users to the existing
1109 /// node. This transfer can potentially trigger recursive merging.
1110 void
1111 SelectionDAG::AddModifiedNodeToCSEMaps(SDNode *N) {
1112 // For node types that aren't CSE'd, just act as if no identical node
1113 // already exists.
1114 if (!doNotCSE(N)) {
1115 SDNode *Existing = CSEMap.GetOrInsertNode(N);
1116 if (Existing != N) {
1117 // If there was already an existing matching node, use ReplaceAllUsesWith
1118 // to replace the dead one with the existing one. This can cause
1119 // recursive merging of other unrelated nodes down the line.
1120 ReplaceAllUsesWith(N, Existing);
1122 // N is now dead. Inform the listeners and delete it.
1123 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1124 DUL->NodeDeleted(N, Existing);
1125 DeleteNodeNotInCSEMaps(N);
1126 return;
1130 // If the node doesn't already exist, we updated it. Inform listeners.
1131 for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1132 DUL->NodeUpdated(N);
1135 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1136 /// were replaced with those specified. If this node is never memoized,
1137 /// return null, otherwise return a pointer to the slot it would take. If a
1138 /// node already exists with these operands, the slot will be non-null.
1139 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op,
1140 void *&InsertPos) {
1141 if (doNotCSE(N))
1142 return nullptr;
1144 SDValue Ops[] = { Op };
1145 FoldingSetNodeID ID;
1146 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1147 AddNodeIDCustom(ID, N);
1148 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1149 if (Node)
1150 Node->intersectFlagsWith(N->getFlags());
1151 return Node;
1154 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1155 /// were replaced with those specified. If this node is never memoized,
1156 /// return null, otherwise return a pointer to the slot it would take. If a
1157 /// node already exists with these operands, the slot will be non-null.
1158 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
1159 SDValue Op1, SDValue Op2,
1160 void *&InsertPos) {
1161 if (doNotCSE(N))
1162 return nullptr;
1164 SDValue Ops[] = { Op1, Op2 };
1165 FoldingSetNodeID ID;
1166 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1167 AddNodeIDCustom(ID, N);
1168 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1169 if (Node)
1170 Node->intersectFlagsWith(N->getFlags());
1171 return Node;
1174 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1175 /// were replaced with those specified. If this node is never memoized,
1176 /// return null, otherwise return a pointer to the slot it would take. If a
1177 /// node already exists with these operands, the slot will be non-null.
1178 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, ArrayRef<SDValue> Ops,
1179 void *&InsertPos) {
1180 if (doNotCSE(N))
1181 return nullptr;
1183 FoldingSetNodeID ID;
1184 AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1185 AddNodeIDCustom(ID, N);
1186 SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1187 if (Node)
1188 Node->intersectFlagsWith(N->getFlags());
1189 return Node;
1192 Align SelectionDAG::getEVTAlign(EVT VT) const {
1193 Type *Ty = VT == MVT::iPTR ?
1194 PointerType::get(Type::getInt8Ty(*getContext()), 0) :
1195 VT.getTypeForEVT(*getContext());
1197 return getDataLayout().getABITypeAlign(Ty);
1200 // EntryNode could meaningfully have debug info if we can find it...
1201 SelectionDAG::SelectionDAG(const TargetMachine &tm, CodeGenOpt::Level OL)
1202 : TM(tm), OptLevel(OL),
1203 EntryNode(ISD::EntryToken, 0, DebugLoc(), getVTList(MVT::Other)),
1204 Root(getEntryNode()) {
1205 InsertNode(&EntryNode);
1206 DbgInfo = new SDDbgInfo();
1209 void SelectionDAG::init(MachineFunction &NewMF,
1210 OptimizationRemarkEmitter &NewORE,
1211 Pass *PassPtr, const TargetLibraryInfo *LibraryInfo,
1212 LegacyDivergenceAnalysis * Divergence,
1213 ProfileSummaryInfo *PSIin,
1214 BlockFrequencyInfo *BFIin) {
1215 MF = &NewMF;
1216 SDAGISelPass = PassPtr;
1217 ORE = &NewORE;
1218 TLI = getSubtarget().getTargetLowering();
1219 TSI = getSubtarget().getSelectionDAGInfo();
1220 LibInfo = LibraryInfo;
1221 Context = &MF->getFunction().getContext();
1222 DA = Divergence;
1223 PSI = PSIin;
1224 BFI = BFIin;
1227 SelectionDAG::~SelectionDAG() {
1228 assert(!UpdateListeners && "Dangling registered DAGUpdateListeners");
1229 allnodes_clear();
1230 OperandRecycler.clear(OperandAllocator);
1231 delete DbgInfo;
1234 bool SelectionDAG::shouldOptForSize() const {
1235 return MF->getFunction().hasOptSize() ||
1236 llvm::shouldOptimizeForSize(FLI->MBB->getBasicBlock(), PSI, BFI);
1239 void SelectionDAG::allnodes_clear() {
1240 assert(&*AllNodes.begin() == &EntryNode);
1241 AllNodes.remove(AllNodes.begin());
1242 while (!AllNodes.empty())
1243 DeallocateNode(&AllNodes.front());
1244 #ifndef NDEBUG
1245 NextPersistentId = 0;
1246 #endif
1249 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
1250 void *&InsertPos) {
1251 SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
1252 if (N) {
1253 switch (N->getOpcode()) {
1254 default: break;
1255 case ISD::Constant:
1256 case ISD::ConstantFP:
1257 llvm_unreachable("Querying for Constant and ConstantFP nodes requires "
1258 "debug location. Use another overload.");
1261 return N;
1264 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
1265 const SDLoc &DL, void *&InsertPos) {
1266 SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
1267 if (N) {
1268 switch (N->getOpcode()) {
1269 case ISD::Constant:
1270 case ISD::ConstantFP:
1271 // Erase debug location from the node if the node is used at several
1272 // different places. Do not propagate one location to all uses as it
1273 // will cause a worse single stepping debugging experience.
1274 if (N->getDebugLoc() != DL.getDebugLoc())
1275 N->setDebugLoc(DebugLoc());
1276 break;
1277 default:
1278 // When the node's point of use is located earlier in the instruction
1279 // sequence than its prior point of use, update its debug info to the
1280 // earlier location.
1281 if (DL.getIROrder() && DL.getIROrder() < N->getIROrder())
1282 N->setDebugLoc(DL.getDebugLoc());
1283 break;
1286 return N;
1289 void SelectionDAG::clear() {
1290 allnodes_clear();
1291 OperandRecycler.clear(OperandAllocator);
1292 OperandAllocator.Reset();
1293 CSEMap.clear();
1295 ExtendedValueTypeNodes.clear();
1296 ExternalSymbols.clear();
1297 TargetExternalSymbols.clear();
1298 MCSymbols.clear();
1299 SDCallSiteDbgInfo.clear();
1300 std::fill(CondCodeNodes.begin(), CondCodeNodes.end(),
1301 static_cast<CondCodeSDNode*>(nullptr));
1302 std::fill(ValueTypeNodes.begin(), ValueTypeNodes.end(),
1303 static_cast<SDNode*>(nullptr));
1305 EntryNode.UseList = nullptr;
1306 InsertNode(&EntryNode);
1307 Root = getEntryNode();
1308 DbgInfo->clear();
1311 SDValue SelectionDAG::getFPExtendOrRound(SDValue Op, const SDLoc &DL, EVT VT) {
1312 return VT.bitsGT(Op.getValueType())
1313 ? getNode(ISD::FP_EXTEND, DL, VT, Op)
1314 : getNode(ISD::FP_ROUND, DL, VT, Op, getIntPtrConstant(0, DL));
1317 std::pair<SDValue, SDValue>
1318 SelectionDAG::getStrictFPExtendOrRound(SDValue Op, SDValue Chain,
1319 const SDLoc &DL, EVT VT) {
1320 assert(!VT.bitsEq(Op.getValueType()) &&
1321 "Strict no-op FP extend/round not allowed.");
1322 SDValue Res =
1323 VT.bitsGT(Op.getValueType())
1324 ? getNode(ISD::STRICT_FP_EXTEND, DL, {VT, MVT::Other}, {Chain, Op})
1325 : getNode(ISD::STRICT_FP_ROUND, DL, {VT, MVT::Other},
1326 {Chain, Op, getIntPtrConstant(0, DL)});
1328 return std::pair<SDValue, SDValue>(Res, SDValue(Res.getNode(), 1));
1331 SDValue SelectionDAG::getAnyExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1332 return VT.bitsGT(Op.getValueType()) ?
1333 getNode(ISD::ANY_EXTEND, DL, VT, Op) :
1334 getNode(ISD::TRUNCATE, DL, VT, Op);
1337 SDValue SelectionDAG::getSExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1338 return VT.bitsGT(Op.getValueType()) ?
1339 getNode(ISD::SIGN_EXTEND, DL, VT, Op) :
1340 getNode(ISD::TRUNCATE, DL, VT, Op);
1343 SDValue SelectionDAG::getZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1344 return VT.bitsGT(Op.getValueType()) ?
1345 getNode(ISD::ZERO_EXTEND, DL, VT, Op) :
1346 getNode(ISD::TRUNCATE, DL, VT, Op);
1349 SDValue SelectionDAG::getBoolExtOrTrunc(SDValue Op, const SDLoc &SL, EVT VT,
1350 EVT OpVT) {
1351 if (VT.bitsLE(Op.getValueType()))
1352 return getNode(ISD::TRUNCATE, SL, VT, Op);
1354 TargetLowering::BooleanContent BType = TLI->getBooleanContents(OpVT);
1355 return getNode(TLI->getExtendForContent(BType), SL, VT, Op);
1358 SDValue SelectionDAG::getZeroExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) {
1359 EVT OpVT = Op.getValueType();
1360 assert(VT.isInteger() && OpVT.isInteger() &&
1361 "Cannot getZeroExtendInReg FP types");
1362 assert(VT.isVector() == OpVT.isVector() &&
1363 "getZeroExtendInReg type should be vector iff the operand "
1364 "type is vector!");
1365 assert((!VT.isVector() ||
1366 VT.getVectorElementCount() == OpVT.getVectorElementCount()) &&
1367 "Vector element counts must match in getZeroExtendInReg");
1368 assert(VT.bitsLE(OpVT) && "Not extending!");
1369 if (OpVT == VT)
1370 return Op;
1371 APInt Imm = APInt::getLowBitsSet(OpVT.getScalarSizeInBits(),
1372 VT.getScalarSizeInBits());
1373 return getNode(ISD::AND, DL, OpVT, Op, getConstant(Imm, DL, OpVT));
1376 SDValue SelectionDAG::getPtrExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1377 // Only unsigned pointer semantics are supported right now. In the future this
1378 // might delegate to TLI to check pointer signedness.
1379 return getZExtOrTrunc(Op, DL, VT);
1382 SDValue SelectionDAG::getPtrExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) {
1383 // Only unsigned pointer semantics are supported right now. In the future this
1384 // might delegate to TLI to check pointer signedness.
1385 return getZeroExtendInReg(Op, DL, VT);
1388 /// getNOT - Create a bitwise NOT operation as (XOR Val, -1).
1389 SDValue SelectionDAG::getNOT(const SDLoc &DL, SDValue Val, EVT VT) {
1390 return getNode(ISD::XOR, DL, VT, Val, getAllOnesConstant(DL, VT));
1393 SDValue SelectionDAG::getLogicalNOT(const SDLoc &DL, SDValue Val, EVT VT) {
1394 SDValue TrueValue = getBoolConstant(true, DL, VT, VT);
1395 return getNode(ISD::XOR, DL, VT, Val, TrueValue);
1398 SDValue SelectionDAG::getBoolConstant(bool V, const SDLoc &DL, EVT VT,
1399 EVT OpVT) {
1400 if (!V)
1401 return getConstant(0, DL, VT);
1403 switch (TLI->getBooleanContents(OpVT)) {
1404 case TargetLowering::ZeroOrOneBooleanContent:
1405 case TargetLowering::UndefinedBooleanContent:
1406 return getConstant(1, DL, VT);
1407 case TargetLowering::ZeroOrNegativeOneBooleanContent:
1408 return getAllOnesConstant(DL, VT);
1410 llvm_unreachable("Unexpected boolean content enum!");
1413 SDValue SelectionDAG::getConstant(uint64_t Val, const SDLoc &DL, EVT VT,
1414 bool isT, bool isO) {
1415 EVT EltVT = VT.getScalarType();
1416 assert((EltVT.getSizeInBits() >= 64 ||
1417 (uint64_t)((int64_t)Val >> EltVT.getSizeInBits()) + 1 < 2) &&
1418 "getConstant with a uint64_t value that doesn't fit in the type!");
1419 return getConstant(APInt(EltVT.getSizeInBits(), Val), DL, VT, isT, isO);
1422 SDValue SelectionDAG::getConstant(const APInt &Val, const SDLoc &DL, EVT VT,
1423 bool isT, bool isO) {
1424 return getConstant(*ConstantInt::get(*Context, Val), DL, VT, isT, isO);
1427 SDValue SelectionDAG::getConstant(const ConstantInt &Val, const SDLoc &DL,
1428 EVT VT, bool isT, bool isO) {
1429 assert(VT.isInteger() && "Cannot create FP integer constant!");
1431 EVT EltVT = VT.getScalarType();
1432 const ConstantInt *Elt = &Val;
1434 // In some cases the vector type is legal but the element type is illegal and
1435 // needs to be promoted, for example v8i8 on ARM. In this case, promote the
1436 // inserted value (the type does not need to match the vector element type).
1437 // Any extra bits introduced will be truncated away.
1438 if (VT.isVector() && TLI->getTypeAction(*getContext(), EltVT) ==
1439 TargetLowering::TypePromoteInteger) {
1440 EltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1441 APInt NewVal = Elt->getValue().zextOrTrunc(EltVT.getSizeInBits());
1442 Elt = ConstantInt::get(*getContext(), NewVal);
1444 // In other cases the element type is illegal and needs to be expanded, for
1445 // example v2i64 on MIPS32. In this case, find the nearest legal type, split
1446 // the value into n parts and use a vector type with n-times the elements.
1447 // Then bitcast to the type requested.
1448 // Legalizing constants too early makes the DAGCombiner's job harder so we
1449 // only legalize if the DAG tells us we must produce legal types.
1450 else if (NewNodesMustHaveLegalTypes && VT.isVector() &&
1451 TLI->getTypeAction(*getContext(), EltVT) ==
1452 TargetLowering::TypeExpandInteger) {
1453 const APInt &NewVal = Elt->getValue();
1454 EVT ViaEltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1455 unsigned ViaEltSizeInBits = ViaEltVT.getSizeInBits();
1457 // For scalable vectors, try to use a SPLAT_VECTOR_PARTS node.
1458 if (VT.isScalableVector()) {
1459 assert(EltVT.getSizeInBits() % ViaEltSizeInBits == 0 &&
1460 "Can only handle an even split!");
1461 unsigned Parts = EltVT.getSizeInBits() / ViaEltSizeInBits;
1463 SmallVector<SDValue, 2> ScalarParts;
1464 for (unsigned i = 0; i != Parts; ++i)
1465 ScalarParts.push_back(getConstant(
1466 NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL,
1467 ViaEltVT, isT, isO));
1469 return getNode(ISD::SPLAT_VECTOR_PARTS, DL, VT, ScalarParts);
1472 unsigned ViaVecNumElts = VT.getSizeInBits() / ViaEltSizeInBits;
1473 EVT ViaVecVT = EVT::getVectorVT(*getContext(), ViaEltVT, ViaVecNumElts);
1475 // Check the temporary vector is the correct size. If this fails then
1476 // getTypeToTransformTo() probably returned a type whose size (in bits)
1477 // isn't a power-of-2 factor of the requested type size.
1478 assert(ViaVecVT.getSizeInBits() == VT.getSizeInBits());
1480 SmallVector<SDValue, 2> EltParts;
1481 for (unsigned i = 0; i < ViaVecNumElts / VT.getVectorNumElements(); ++i)
1482 EltParts.push_back(getConstant(
1483 NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL,
1484 ViaEltVT, isT, isO));
1486 // EltParts is currently in little endian order. If we actually want
1487 // big-endian order then reverse it now.
1488 if (getDataLayout().isBigEndian())
1489 std::reverse(EltParts.begin(), EltParts.end());
1491 // The elements must be reversed when the element order is different
1492 // to the endianness of the elements (because the BITCAST is itself a
1493 // vector shuffle in this situation). However, we do not need any code to
1494 // perform this reversal because getConstant() is producing a vector
1495 // splat.
1496 // This situation occurs in MIPS MSA.
1498 SmallVector<SDValue, 8> Ops;
1499 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
1500 llvm::append_range(Ops, EltParts);
1502 SDValue V =
1503 getNode(ISD::BITCAST, DL, VT, getBuildVector(ViaVecVT, DL, Ops));
1504 return V;
1507 assert(Elt->getBitWidth() == EltVT.getSizeInBits() &&
1508 "APInt size does not match type size!");
1509 unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
1510 FoldingSetNodeID ID;
1511 AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
1512 ID.AddPointer(Elt);
1513 ID.AddBoolean(isO);
1514 void *IP = nullptr;
1515 SDNode *N = nullptr;
1516 if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1517 if (!VT.isVector())
1518 return SDValue(N, 0);
1520 if (!N) {
1521 N = newSDNode<ConstantSDNode>(isT, isO, Elt, EltVT);
1522 CSEMap.InsertNode(N, IP);
1523 InsertNode(N);
1524 NewSDValueDbgMsg(SDValue(N, 0), "Creating constant: ", this);
1527 SDValue Result(N, 0);
1528 if (VT.isScalableVector())
1529 Result = getSplatVector(VT, DL, Result);
1530 else if (VT.isVector())
1531 Result = getSplatBuildVector(VT, DL, Result);
1533 return Result;
1536 SDValue SelectionDAG::getIntPtrConstant(uint64_t Val, const SDLoc &DL,
1537 bool isTarget) {
1538 return getConstant(Val, DL, TLI->getPointerTy(getDataLayout()), isTarget);
1541 SDValue SelectionDAG::getShiftAmountConstant(uint64_t Val, EVT VT,
1542 const SDLoc &DL, bool LegalTypes) {
1543 assert(VT.isInteger() && "Shift amount is not an integer type!");
1544 EVT ShiftVT = TLI->getShiftAmountTy(VT, getDataLayout(), LegalTypes);
1545 return getConstant(Val, DL, ShiftVT);
1548 SDValue SelectionDAG::getVectorIdxConstant(uint64_t Val, const SDLoc &DL,
1549 bool isTarget) {
1550 return getConstant(Val, DL, TLI->getVectorIdxTy(getDataLayout()), isTarget);
1553 SDValue SelectionDAG::getConstantFP(const APFloat &V, const SDLoc &DL, EVT VT,
1554 bool isTarget) {
1555 return getConstantFP(*ConstantFP::get(*getContext(), V), DL, VT, isTarget);
1558 SDValue SelectionDAG::getConstantFP(const ConstantFP &V, const SDLoc &DL,
1559 EVT VT, bool isTarget) {
1560 assert(VT.isFloatingPoint() && "Cannot create integer FP constant!");
1562 EVT EltVT = VT.getScalarType();
1564 // Do the map lookup using the actual bit pattern for the floating point
1565 // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
1566 // we don't have issues with SNANs.
1567 unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
1568 FoldingSetNodeID ID;
1569 AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
1570 ID.AddPointer(&V);
1571 void *IP = nullptr;
1572 SDNode *N = nullptr;
1573 if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1574 if (!VT.isVector())
1575 return SDValue(N, 0);
1577 if (!N) {
1578 N = newSDNode<ConstantFPSDNode>(isTarget, &V, EltVT);
1579 CSEMap.InsertNode(N, IP);
1580 InsertNode(N);
1583 SDValue Result(N, 0);
1584 if (VT.isScalableVector())
1585 Result = getSplatVector(VT, DL, Result);
1586 else if (VT.isVector())
1587 Result = getSplatBuildVector(VT, DL, Result);
1588 NewSDValueDbgMsg(Result, "Creating fp constant: ", this);
1589 return Result;
1592 SDValue SelectionDAG::getConstantFP(double Val, const SDLoc &DL, EVT VT,
1593 bool isTarget) {
1594 EVT EltVT = VT.getScalarType();
1595 if (EltVT == MVT::f32)
1596 return getConstantFP(APFloat((float)Val), DL, VT, isTarget);
1597 if (EltVT == MVT::f64)
1598 return getConstantFP(APFloat(Val), DL, VT, isTarget);
1599 if (EltVT == MVT::f80 || EltVT == MVT::f128 || EltVT == MVT::ppcf128 ||
1600 EltVT == MVT::f16 || EltVT == MVT::bf16) {
1601 bool Ignored;
1602 APFloat APF = APFloat(Val);
1603 APF.convert(EVTToAPFloatSemantics(EltVT), APFloat::rmNearestTiesToEven,
1604 &Ignored);
1605 return getConstantFP(APF, DL, VT, isTarget);
1607 llvm_unreachable("Unsupported type in getConstantFP");
1610 SDValue SelectionDAG::getGlobalAddress(const GlobalValue *GV, const SDLoc &DL,
1611 EVT VT, int64_t Offset, bool isTargetGA,
1612 unsigned TargetFlags) {
1613 assert((TargetFlags == 0 || isTargetGA) &&
1614 "Cannot set target flags on target-independent globals");
1616 // Truncate (with sign-extension) the offset value to the pointer size.
1617 unsigned BitWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
1618 if (BitWidth < 64)
1619 Offset = SignExtend64(Offset, BitWidth);
1621 unsigned Opc;
1622 if (GV->isThreadLocal())
1623 Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress;
1624 else
1625 Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress;
1627 FoldingSetNodeID ID;
1628 AddNodeIDNode(ID, Opc, getVTList(VT), None);
1629 ID.AddPointer(GV);
1630 ID.AddInteger(Offset);
1631 ID.AddInteger(TargetFlags);
1632 void *IP = nullptr;
1633 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
1634 return SDValue(E, 0);
1636 auto *N = newSDNode<GlobalAddressSDNode>(
1637 Opc, DL.getIROrder(), DL.getDebugLoc(), GV, VT, Offset, TargetFlags);
1638 CSEMap.InsertNode(N, IP);
1639 InsertNode(N);
1640 return SDValue(N, 0);
1643 SDValue SelectionDAG::getFrameIndex(int FI, EVT VT, bool isTarget) {
1644 unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
1645 FoldingSetNodeID ID;
1646 AddNodeIDNode(ID, Opc, getVTList(VT), None);
1647 ID.AddInteger(FI);
1648 void *IP = nullptr;
1649 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1650 return SDValue(E, 0);
1652 auto *N = newSDNode<FrameIndexSDNode>(FI, VT, isTarget);
1653 CSEMap.InsertNode(N, IP);
1654 InsertNode(N);
1655 return SDValue(N, 0);
1658 SDValue SelectionDAG::getJumpTable(int JTI, EVT VT, bool isTarget,
1659 unsigned TargetFlags) {
1660 assert((TargetFlags == 0 || isTarget) &&
1661 "Cannot set target flags on target-independent jump tables");
1662 unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
1663 FoldingSetNodeID ID;
1664 AddNodeIDNode(ID, Opc, getVTList(VT), None);
1665 ID.AddInteger(JTI);
1666 ID.AddInteger(TargetFlags);
1667 void *IP = nullptr;
1668 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1669 return SDValue(E, 0);
1671 auto *N = newSDNode<JumpTableSDNode>(JTI, VT, isTarget, TargetFlags);
1672 CSEMap.InsertNode(N, IP);
1673 InsertNode(N);
1674 return SDValue(N, 0);
1677 SDValue SelectionDAG::getConstantPool(const Constant *C, EVT VT,
1678 MaybeAlign Alignment, int Offset,
1679 bool isTarget, unsigned TargetFlags) {
1680 assert((TargetFlags == 0 || isTarget) &&
1681 "Cannot set target flags on target-independent globals");
1682 if (!Alignment)
1683 Alignment = shouldOptForSize()
1684 ? getDataLayout().getABITypeAlign(C->getType())
1685 : getDataLayout().getPrefTypeAlign(C->getType());
1686 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1687 FoldingSetNodeID ID;
1688 AddNodeIDNode(ID, Opc, getVTList(VT), None);
1689 ID.AddInteger(Alignment->value());
1690 ID.AddInteger(Offset);
1691 ID.AddPointer(C);
1692 ID.AddInteger(TargetFlags);
1693 void *IP = nullptr;
1694 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1695 return SDValue(E, 0);
1697 auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment,
1698 TargetFlags);
1699 CSEMap.InsertNode(N, IP);
1700 InsertNode(N);
1701 SDValue V = SDValue(N, 0);
1702 NewSDValueDbgMsg(V, "Creating new constant pool: ", this);
1703 return V;
1706 SDValue SelectionDAG::getConstantPool(MachineConstantPoolValue *C, EVT VT,
1707 MaybeAlign Alignment, int Offset,
1708 bool isTarget, unsigned TargetFlags) {
1709 assert((TargetFlags == 0 || isTarget) &&
1710 "Cannot set target flags on target-independent globals");
1711 if (!Alignment)
1712 Alignment = getDataLayout().getPrefTypeAlign(C->getType());
1713 unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1714 FoldingSetNodeID ID;
1715 AddNodeIDNode(ID, Opc, getVTList(VT), None);
1716 ID.AddInteger(Alignment->value());
1717 ID.AddInteger(Offset);
1718 C->addSelectionDAGCSEId(ID);
1719 ID.AddInteger(TargetFlags);
1720 void *IP = nullptr;
1721 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1722 return SDValue(E, 0);
1724 auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment,
1725 TargetFlags);
1726 CSEMap.InsertNode(N, IP);
1727 InsertNode(N);
1728 return SDValue(N, 0);
1731 SDValue SelectionDAG::getTargetIndex(int Index, EVT VT, int64_t Offset,
1732 unsigned TargetFlags) {
1733 FoldingSetNodeID ID;
1734 AddNodeIDNode(ID, ISD::TargetIndex, getVTList(VT), None);
1735 ID.AddInteger(Index);
1736 ID.AddInteger(Offset);
1737 ID.AddInteger(TargetFlags);
1738 void *IP = nullptr;
1739 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1740 return SDValue(E, 0);
1742 auto *N = newSDNode<TargetIndexSDNode>(Index, VT, Offset, TargetFlags);
1743 CSEMap.InsertNode(N, IP);
1744 InsertNode(N);
1745 return SDValue(N, 0);
1748 SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
1749 FoldingSetNodeID ID;
1750 AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), None);
1751 ID.AddPointer(MBB);
1752 void *IP = nullptr;
1753 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1754 return SDValue(E, 0);
1756 auto *N = newSDNode<BasicBlockSDNode>(MBB);
1757 CSEMap.InsertNode(N, IP);
1758 InsertNode(N);
1759 return SDValue(N, 0);
1762 SDValue SelectionDAG::getValueType(EVT VT) {
1763 if (VT.isSimple() && (unsigned)VT.getSimpleVT().SimpleTy >=
1764 ValueTypeNodes.size())
1765 ValueTypeNodes.resize(VT.getSimpleVT().SimpleTy+1);
1767 SDNode *&N = VT.isExtended() ?
1768 ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT().SimpleTy];
1770 if (N) return SDValue(N, 0);
1771 N = newSDNode<VTSDNode>(VT);
1772 InsertNode(N);
1773 return SDValue(N, 0);
1776 SDValue SelectionDAG::getExternalSymbol(const char *Sym, EVT VT) {
1777 SDNode *&N = ExternalSymbols[Sym];
1778 if (N) return SDValue(N, 0);
1779 N = newSDNode<ExternalSymbolSDNode>(false, Sym, 0, VT);
1780 InsertNode(N);
1781 return SDValue(N, 0);
1784 SDValue SelectionDAG::getMCSymbol(MCSymbol *Sym, EVT VT) {
1785 SDNode *&N = MCSymbols[Sym];
1786 if (N)
1787 return SDValue(N, 0);
1788 N = newSDNode<MCSymbolSDNode>(Sym, VT);
1789 InsertNode(N);
1790 return SDValue(N, 0);
1793 SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, EVT VT,
1794 unsigned TargetFlags) {
1795 SDNode *&N =
1796 TargetExternalSymbols[std::pair<std::string, unsigned>(Sym, TargetFlags)];
1797 if (N) return SDValue(N, 0);
1798 N = newSDNode<ExternalSymbolSDNode>(true, Sym, TargetFlags, VT);
1799 InsertNode(N);
1800 return SDValue(N, 0);
1803 SDValue SelectionDAG::getCondCode(ISD::CondCode Cond) {
1804 if ((unsigned)Cond >= CondCodeNodes.size())
1805 CondCodeNodes.resize(Cond+1);
1807 if (!CondCodeNodes[Cond]) {
1808 auto *N = newSDNode<CondCodeSDNode>(Cond);
1809 CondCodeNodes[Cond] = N;
1810 InsertNode(N);
1813 return SDValue(CondCodeNodes[Cond], 0);
1816 SDValue SelectionDAG::getStepVector(const SDLoc &DL, EVT ResVT) {
1817 APInt One(ResVT.getScalarSizeInBits(), 1);
1818 return getStepVector(DL, ResVT, One);
1821 SDValue SelectionDAG::getStepVector(const SDLoc &DL, EVT ResVT, APInt StepVal) {
1822 assert(ResVT.getScalarSizeInBits() == StepVal.getBitWidth());
1823 if (ResVT.isScalableVector())
1824 return getNode(
1825 ISD::STEP_VECTOR, DL, ResVT,
1826 getTargetConstant(StepVal, DL, ResVT.getVectorElementType()));
1828 SmallVector<SDValue, 16> OpsStepConstants;
1829 for (uint64_t i = 0; i < ResVT.getVectorNumElements(); i++)
1830 OpsStepConstants.push_back(
1831 getConstant(StepVal * i, DL, ResVT.getVectorElementType()));
1832 return getBuildVector(ResVT, DL, OpsStepConstants);
1835 /// Swaps the values of N1 and N2. Swaps all indices in the shuffle mask M that
1836 /// point at N1 to point at N2 and indices that point at N2 to point at N1.
1837 static void commuteShuffle(SDValue &N1, SDValue &N2, MutableArrayRef<int> M) {
1838 std::swap(N1, N2);
1839 ShuffleVectorSDNode::commuteMask(M);
1842 SDValue SelectionDAG::getVectorShuffle(EVT VT, const SDLoc &dl, SDValue N1,
1843 SDValue N2, ArrayRef<int> Mask) {
1844 assert(VT.getVectorNumElements() == Mask.size() &&
1845 "Must have the same number of vector elements as mask elements!");
1846 assert(VT == N1.getValueType() && VT == N2.getValueType() &&
1847 "Invalid VECTOR_SHUFFLE");
1849 // Canonicalize shuffle undef, undef -> undef
1850 if (N1.isUndef() && N2.isUndef())
1851 return getUNDEF(VT);
1853 // Validate that all indices in Mask are within the range of the elements
1854 // input to the shuffle.
1855 int NElts = Mask.size();
1856 assert(llvm::all_of(Mask,
1857 [&](int M) { return M < (NElts * 2) && M >= -1; }) &&
1858 "Index out of range");
1860 // Copy the mask so we can do any needed cleanup.
1861 SmallVector<int, 8> MaskVec(Mask.begin(), Mask.end());
1863 // Canonicalize shuffle v, v -> v, undef
1864 if (N1 == N2) {
1865 N2 = getUNDEF(VT);
1866 for (int i = 0; i != NElts; ++i)
1867 if (MaskVec[i] >= NElts) MaskVec[i] -= NElts;
1870 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
1871 if (N1.isUndef())
1872 commuteShuffle(N1, N2, MaskVec);
1874 if (TLI->hasVectorBlend()) {
1875 // If shuffling a splat, try to blend the splat instead. We do this here so
1876 // that even when this arises during lowering we don't have to re-handle it.
1877 auto BlendSplat = [&](BuildVectorSDNode *BV, int Offset) {
1878 BitVector UndefElements;
1879 SDValue Splat = BV->getSplatValue(&UndefElements);
1880 if (!Splat)
1881 return;
1883 for (int i = 0; i < NElts; ++i) {
1884 if (MaskVec[i] < Offset || MaskVec[i] >= (Offset + NElts))
1885 continue;
1887 // If this input comes from undef, mark it as such.
1888 if (UndefElements[MaskVec[i] - Offset]) {
1889 MaskVec[i] = -1;
1890 continue;
1893 // If we can blend a non-undef lane, use that instead.
1894 if (!UndefElements[i])
1895 MaskVec[i] = i + Offset;
1898 if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
1899 BlendSplat(N1BV, 0);
1900 if (auto *N2BV = dyn_cast<BuildVectorSDNode>(N2))
1901 BlendSplat(N2BV, NElts);
1904 // Canonicalize all index into lhs, -> shuffle lhs, undef
1905 // Canonicalize all index into rhs, -> shuffle rhs, undef
1906 bool AllLHS = true, AllRHS = true;
1907 bool N2Undef = N2.isUndef();
1908 for (int i = 0; i != NElts; ++i) {
1909 if (MaskVec[i] >= NElts) {
1910 if (N2Undef)
1911 MaskVec[i] = -1;
1912 else
1913 AllLHS = false;
1914 } else if (MaskVec[i] >= 0) {
1915 AllRHS = false;
1918 if (AllLHS && AllRHS)
1919 return getUNDEF(VT);
1920 if (AllLHS && !N2Undef)
1921 N2 = getUNDEF(VT);
1922 if (AllRHS) {
1923 N1 = getUNDEF(VT);
1924 commuteShuffle(N1, N2, MaskVec);
1926 // Reset our undef status after accounting for the mask.
1927 N2Undef = N2.isUndef();
1928 // Re-check whether both sides ended up undef.
1929 if (N1.isUndef() && N2Undef)
1930 return getUNDEF(VT);
1932 // If Identity shuffle return that node.
1933 bool Identity = true, AllSame = true;
1934 for (int i = 0; i != NElts; ++i) {
1935 if (MaskVec[i] >= 0 && MaskVec[i] != i) Identity = false;
1936 if (MaskVec[i] != MaskVec[0]) AllSame = false;
1938 if (Identity && NElts)
1939 return N1;
1941 // Shuffling a constant splat doesn't change the result.
1942 if (N2Undef) {
1943 SDValue V = N1;
1945 // Look through any bitcasts. We check that these don't change the number
1946 // (and size) of elements and just changes their types.
1947 while (V.getOpcode() == ISD::BITCAST)
1948 V = V->getOperand(0);
1950 // A splat should always show up as a build vector node.
1951 if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) {
1952 BitVector UndefElements;
1953 SDValue Splat = BV->getSplatValue(&UndefElements);
1954 // If this is a splat of an undef, shuffling it is also undef.
1955 if (Splat && Splat.isUndef())
1956 return getUNDEF(VT);
1958 bool SameNumElts =
1959 V.getValueType().getVectorNumElements() == VT.getVectorNumElements();
1961 // We only have a splat which can skip shuffles if there is a splatted
1962 // value and no undef lanes rearranged by the shuffle.
1963 if (Splat && UndefElements.none()) {
1964 // Splat of <x, x, ..., x>, return <x, x, ..., x>, provided that the
1965 // number of elements match or the value splatted is a zero constant.
1966 if (SameNumElts)
1967 return N1;
1968 if (auto *C = dyn_cast<ConstantSDNode>(Splat))
1969 if (C->isZero())
1970 return N1;
1973 // If the shuffle itself creates a splat, build the vector directly.
1974 if (AllSame && SameNumElts) {
1975 EVT BuildVT = BV->getValueType(0);
1976 const SDValue &Splatted = BV->getOperand(MaskVec[0]);
1977 SDValue NewBV = getSplatBuildVector(BuildVT, dl, Splatted);
1979 // We may have jumped through bitcasts, so the type of the
1980 // BUILD_VECTOR may not match the type of the shuffle.
1981 if (BuildVT != VT)
1982 NewBV = getNode(ISD::BITCAST, dl, VT, NewBV);
1983 return NewBV;
1988 FoldingSetNodeID ID;
1989 SDValue Ops[2] = { N1, N2 };
1990 AddNodeIDNode(ID, ISD::VECTOR_SHUFFLE, getVTList(VT), Ops);
1991 for (int i = 0; i != NElts; ++i)
1992 ID.AddInteger(MaskVec[i]);
1994 void* IP = nullptr;
1995 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
1996 return SDValue(E, 0);
1998 // Allocate the mask array for the node out of the BumpPtrAllocator, since
1999 // SDNode doesn't have access to it. This memory will be "leaked" when
2000 // the node is deallocated, but recovered when the NodeAllocator is released.
2001 int *MaskAlloc = OperandAllocator.Allocate<int>(NElts);
2002 llvm::copy(MaskVec, MaskAlloc);
2004 auto *N = newSDNode<ShuffleVectorSDNode>(VT, dl.getIROrder(),
2005 dl.getDebugLoc(), MaskAlloc);
2006 createOperands(N, Ops);
2008 CSEMap.InsertNode(N, IP);
2009 InsertNode(N);
2010 SDValue V = SDValue(N, 0);
2011 NewSDValueDbgMsg(V, "Creating new node: ", this);
2012 return V;
2015 SDValue SelectionDAG::getCommutedVectorShuffle(const ShuffleVectorSDNode &SV) {
2016 EVT VT = SV.getValueType(0);
2017 SmallVector<int, 8> MaskVec(SV.getMask().begin(), SV.getMask().end());
2018 ShuffleVectorSDNode::commuteMask(MaskVec);
2020 SDValue Op0 = SV.getOperand(0);
2021 SDValue Op1 = SV.getOperand(1);
2022 return getVectorShuffle(VT, SDLoc(&SV), Op1, Op0, MaskVec);
2025 SDValue SelectionDAG::getRegister(unsigned RegNo, EVT VT) {
2026 FoldingSetNodeID ID;
2027 AddNodeIDNode(ID, ISD::Register, getVTList(VT), None);
2028 ID.AddInteger(RegNo);
2029 void *IP = nullptr;
2030 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2031 return SDValue(E, 0);
2033 auto *N = newSDNode<RegisterSDNode>(RegNo, VT);
2034 N->SDNodeBits.IsDivergent = TLI->isSDNodeSourceOfDivergence(N, FLI, DA);
2035 CSEMap.InsertNode(N, IP);
2036 InsertNode(N);
2037 return SDValue(N, 0);
2040 SDValue SelectionDAG::getRegisterMask(const uint32_t *RegMask) {
2041 FoldingSetNodeID ID;
2042 AddNodeIDNode(ID, ISD::RegisterMask, getVTList(MVT::Untyped), None);
2043 ID.AddPointer(RegMask);
2044 void *IP = nullptr;
2045 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2046 return SDValue(E, 0);
2048 auto *N = newSDNode<RegisterMaskSDNode>(RegMask);
2049 CSEMap.InsertNode(N, IP);
2050 InsertNode(N);
2051 return SDValue(N, 0);
2054 SDValue SelectionDAG::getEHLabel(const SDLoc &dl, SDValue Root,
2055 MCSymbol *Label) {
2056 return getLabelNode(ISD::EH_LABEL, dl, Root, Label);
2059 SDValue SelectionDAG::getLabelNode(unsigned Opcode, const SDLoc &dl,
2060 SDValue Root, MCSymbol *Label) {
2061 FoldingSetNodeID ID;
2062 SDValue Ops[] = { Root };
2063 AddNodeIDNode(ID, Opcode, getVTList(MVT::Other), Ops);
2064 ID.AddPointer(Label);
2065 void *IP = nullptr;
2066 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2067 return SDValue(E, 0);
2069 auto *N =
2070 newSDNode<LabelSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), Label);
2071 createOperands(N, Ops);
2073 CSEMap.InsertNode(N, IP);
2074 InsertNode(N);
2075 return SDValue(N, 0);
2078 SDValue SelectionDAG::getBlockAddress(const BlockAddress *BA, EVT VT,
2079 int64_t Offset, bool isTarget,
2080 unsigned TargetFlags) {
2081 unsigned Opc = isTarget ? ISD::TargetBlockAddress : ISD::BlockAddress;
2083 FoldingSetNodeID ID;
2084 AddNodeIDNode(ID, Opc, getVTList(VT), None);
2085 ID.AddPointer(BA);
2086 ID.AddInteger(Offset);
2087 ID.AddInteger(TargetFlags);
2088 void *IP = nullptr;
2089 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2090 return SDValue(E, 0);
2092 auto *N = newSDNode<BlockAddressSDNode>(Opc, VT, BA, Offset, TargetFlags);
2093 CSEMap.InsertNode(N, IP);
2094 InsertNode(N);
2095 return SDValue(N, 0);
2098 SDValue SelectionDAG::getSrcValue(const Value *V) {
2099 FoldingSetNodeID ID;
2100 AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), None);
2101 ID.AddPointer(V);
2103 void *IP = nullptr;
2104 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2105 return SDValue(E, 0);
2107 auto *N = newSDNode<SrcValueSDNode>(V);
2108 CSEMap.InsertNode(N, IP);
2109 InsertNode(N);
2110 return SDValue(N, 0);
2113 SDValue SelectionDAG::getMDNode(const MDNode *MD) {
2114 FoldingSetNodeID ID;
2115 AddNodeIDNode(ID, ISD::MDNODE_SDNODE, getVTList(MVT::Other), None);
2116 ID.AddPointer(MD);
2118 void *IP = nullptr;
2119 if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2120 return SDValue(E, 0);
2122 auto *N = newSDNode<MDNodeSDNode>(MD);
2123 CSEMap.InsertNode(N, IP);
2124 InsertNode(N);
2125 return SDValue(N, 0);
2128 SDValue SelectionDAG::getBitcast(EVT VT, SDValue V) {
2129 if (VT == V.getValueType())
2130 return V;
2132 return getNode(ISD::BITCAST, SDLoc(V), VT, V);
2135 SDValue SelectionDAG::getAddrSpaceCast(const SDLoc &dl, EVT VT, SDValue Ptr,
2136 unsigned SrcAS, unsigned DestAS) {
2137 SDValue Ops[] = {Ptr};
2138 FoldingSetNodeID ID;
2139 AddNodeIDNode(ID, ISD::ADDRSPACECAST, getVTList(VT), Ops);
2140 ID.AddInteger(SrcAS);
2141 ID.AddInteger(DestAS);
2143 void *IP = nullptr;
2144 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
2145 return SDValue(E, 0);
2147 auto *N = newSDNode<AddrSpaceCastSDNode>(dl.getIROrder(), dl.getDebugLoc(),
2148 VT, SrcAS, DestAS);
2149 createOperands(N, Ops);
2151 CSEMap.InsertNode(N, IP);
2152 InsertNode(N);
2153 return SDValue(N, 0);
2156 SDValue SelectionDAG::getFreeze(SDValue V) {
2157 return getNode(ISD::FREEZE, SDLoc(V), V.getValueType(), V);
2160 /// getShiftAmountOperand - Return the specified value casted to
2161 /// the target's desired shift amount type.
2162 SDValue SelectionDAG::getShiftAmountOperand(EVT LHSTy, SDValue Op) {
2163 EVT OpTy = Op.getValueType();
2164 EVT ShTy = TLI->getShiftAmountTy(LHSTy, getDataLayout());
2165 if (OpTy == ShTy || OpTy.isVector()) return Op;
2167 return getZExtOrTrunc(Op, SDLoc(Op), ShTy);
2170 SDValue SelectionDAG::expandVAArg(SDNode *Node) {
2171 SDLoc dl(Node);
2172 const TargetLowering &TLI = getTargetLoweringInfo();
2173 const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2174 EVT VT = Node->getValueType(0);
2175 SDValue Tmp1 = Node->getOperand(0);
2176 SDValue Tmp2 = Node->getOperand(1);
2177 const MaybeAlign MA(Node->getConstantOperandVal(3));
2179 SDValue VAListLoad = getLoad(TLI.getPointerTy(getDataLayout()), dl, Tmp1,
2180 Tmp2, MachinePointerInfo(V));
2181 SDValue VAList = VAListLoad;
2183 if (MA && *MA > TLI.getMinStackArgumentAlignment()) {
2184 VAList = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
2185 getConstant(MA->value() - 1, dl, VAList.getValueType()));
2187 VAList =
2188 getNode(ISD::AND, dl, VAList.getValueType(), VAList,
2189 getConstant(-(int64_t)MA->value(), dl, VAList.getValueType()));
2192 // Increment the pointer, VAList, to the next vaarg
2193 Tmp1 = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
2194 getConstant(getDataLayout().getTypeAllocSize(
2195 VT.getTypeForEVT(*getContext())),
2196 dl, VAList.getValueType()));
2197 // Store the incremented VAList to the legalized pointer
2198 Tmp1 =
2199 getStore(VAListLoad.getValue(1), dl, Tmp1, Tmp2, MachinePointerInfo(V));
2200 // Load the actual argument out of the pointer VAList
2201 return getLoad(VT, dl, Tmp1, VAList, MachinePointerInfo());
2204 SDValue SelectionDAG::expandVACopy(SDNode *Node) {
2205 SDLoc dl(Node);
2206 const TargetLowering &TLI = getTargetLoweringInfo();
2207 // This defaults to loading a pointer from the input and storing it to the
2208 // output, returning the chain.
2209 const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue();
2210 const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue();
2211 SDValue Tmp1 =
2212 getLoad(TLI.getPointerTy(getDataLayout()), dl, Node->getOperand(0),
2213 Node->getOperand(2), MachinePointerInfo(VS));
2214 return getStore(Tmp1.getValue(1), dl, Tmp1, Node->getOperand(1),
2215 MachinePointerInfo(VD));
2218 Align SelectionDAG::getReducedAlign(EVT VT, bool UseABI) {
2219 const DataLayout &DL = getDataLayout();
2220 Type *Ty = VT.getTypeForEVT(*getContext());
2221 Align RedAlign = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty);
2223 if (TLI->isTypeLegal(VT) || !VT.isVector())
2224 return RedAlign;
2226 const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
2227 const Align StackAlign = TFI->getStackAlign();
2229 // See if we can choose a smaller ABI alignment in cases where it's an
2230 // illegal vector type that will get broken down.
2231 if (RedAlign > StackAlign) {
2232 EVT IntermediateVT;
2233 MVT RegisterVT;
2234 unsigned NumIntermediates;
2235 TLI->getVectorTypeBreakdown(*getContext(), VT, IntermediateVT,
2236 NumIntermediates, RegisterVT);
2237 Ty = IntermediateVT.getTypeForEVT(*getContext());
2238 Align RedAlign2 = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty);
2239 if (RedAlign2 < RedAlign)
2240 RedAlign = RedAlign2;
2243 return RedAlign;
2246 SDValue SelectionDAG::CreateStackTemporary(TypeSize Bytes, Align Alignment) {
2247 MachineFrameInfo &MFI = MF->getFrameInfo();
2248 const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
2249 int StackID = 0;
2250 if (Bytes.isScalable())
2251 StackID = TFI->getStackIDForScalableVectors();
2252 // The stack id gives an indication of whether the object is scalable or
2253 // not, so it's safe to pass in the minimum size here.
2254 int FrameIdx = MFI.CreateStackObject(Bytes.getKnownMinSize(), Alignment,
2255 false, nullptr, StackID);
2256 return getFrameIndex(FrameIdx, TLI->getFrameIndexTy(getDataLayout()));
2259 SDValue SelectionDAG::CreateStackTemporary(EVT VT, unsigned minAlign) {
2260 Type *Ty = VT.getTypeForEVT(*getContext());
2261 Align StackAlign =
2262 std::max(getDataLayout().getPrefTypeAlign(Ty), Align(minAlign));
2263 return CreateStackTemporary(VT.getStoreSize(), StackAlign);
2266 SDValue SelectionDAG::CreateStackTemporary(EVT VT1, EVT VT2) {
2267 TypeSize VT1Size = VT1.getStoreSize();
2268 TypeSize VT2Size = VT2.getStoreSize();
2269 assert(VT1Size.isScalable() == VT2Size.isScalable() &&
2270 "Don't know how to choose the maximum size when creating a stack "
2271 "temporary");
2272 TypeSize Bytes =
2273 VT1Size.getKnownMinSize() > VT2Size.getKnownMinSize() ? VT1Size : VT2Size;
2275 Type *Ty1 = VT1.getTypeForEVT(*getContext());
2276 Type *Ty2 = VT2.getTypeForEVT(*getContext());
2277 const DataLayout &DL = getDataLayout();
2278 Align Align = std::max(DL.getPrefTypeAlign(Ty1), DL.getPrefTypeAlign(Ty2));
2279 return CreateStackTemporary(Bytes, Align);
2282 SDValue SelectionDAG::FoldSetCC(EVT VT, SDValue N1, SDValue N2,
2283 ISD::CondCode Cond, const SDLoc &dl) {
2284 EVT OpVT = N1.getValueType();
2286 // These setcc operations always fold.
2287 switch (Cond) {
2288 default: break;
2289 case ISD::SETFALSE:
2290 case ISD::SETFALSE2: return getBoolConstant(false, dl, VT, OpVT);
2291 case ISD::SETTRUE:
2292 case ISD::SETTRUE2: return getBoolConstant(true, dl, VT, OpVT);
2294 case ISD::SETOEQ:
2295 case ISD::SETOGT:
2296 case ISD::SETOGE:
2297 case ISD::SETOLT:
2298 case ISD::SETOLE:
2299 case ISD::SETONE:
2300 case ISD::SETO:
2301 case ISD::SETUO:
2302 case ISD::SETUEQ:
2303 case ISD::SETUNE:
2304 assert(!OpVT.isInteger() && "Illegal setcc for integer!");
2305 break;
2308 if (OpVT.isInteger()) {
2309 // For EQ and NE, we can always pick a value for the undef to make the
2310 // predicate pass or fail, so we can return undef.
2311 // Matches behavior in llvm::ConstantFoldCompareInstruction.
2312 // icmp eq/ne X, undef -> undef.
2313 if ((N1.isUndef() || N2.isUndef()) &&
2314 (Cond == ISD::SETEQ || Cond == ISD::SETNE))
2315 return getUNDEF(VT);
2317 // If both operands are undef, we can return undef for int comparison.
2318 // icmp undef, undef -> undef.
2319 if (N1.isUndef() && N2.isUndef())
2320 return getUNDEF(VT);
2322 // icmp X, X -> true/false
2323 // icmp X, undef -> true/false because undef could be X.
2324 if (N1 == N2)
2325 return getBoolConstant(ISD::isTrueWhenEqual(Cond), dl, VT, OpVT);
2328 if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2)) {
2329 const APInt &C2 = N2C->getAPIntValue();
2330 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1)) {
2331 const APInt &C1 = N1C->getAPIntValue();
2333 return getBoolConstant(ICmpInst::compare(C1, C2, getICmpCondCode(Cond)),
2334 dl, VT, OpVT);
2338 auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
2339 auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
2341 if (N1CFP && N2CFP) {
2342 APFloat::cmpResult R = N1CFP->getValueAPF().compare(N2CFP->getValueAPF());
2343 switch (Cond) {
2344 default: break;
2345 case ISD::SETEQ: if (R==APFloat::cmpUnordered)
2346 return getUNDEF(VT);
2347 LLVM_FALLTHROUGH;
2348 case ISD::SETOEQ: return getBoolConstant(R==APFloat::cmpEqual, dl, VT,
2349 OpVT);
2350 case ISD::SETNE: if (R==APFloat::cmpUnordered)
2351 return getUNDEF(VT);
2352 LLVM_FALLTHROUGH;
2353 case ISD::SETONE: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2354 R==APFloat::cmpLessThan, dl, VT,
2355 OpVT);
2356 case ISD::SETLT: if (R==APFloat::cmpUnordered)
2357 return getUNDEF(VT);
2358 LLVM_FALLTHROUGH;
2359 case ISD::SETOLT: return getBoolConstant(R==APFloat::cmpLessThan, dl, VT,
2360 OpVT);
2361 case ISD::SETGT: if (R==APFloat::cmpUnordered)
2362 return getUNDEF(VT);
2363 LLVM_FALLTHROUGH;
2364 case ISD::SETOGT: return getBoolConstant(R==APFloat::cmpGreaterThan, dl,
2365 VT, OpVT);
2366 case ISD::SETLE: if (R==APFloat::cmpUnordered)
2367 return getUNDEF(VT);
2368 LLVM_FALLTHROUGH;
2369 case ISD::SETOLE: return getBoolConstant(R==APFloat::cmpLessThan ||
2370 R==APFloat::cmpEqual, dl, VT,
2371 OpVT);
2372 case ISD::SETGE: if (R==APFloat::cmpUnordered)
2373 return getUNDEF(VT);
2374 LLVM_FALLTHROUGH;
2375 case ISD::SETOGE: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2376 R==APFloat::cmpEqual, dl, VT, OpVT);
2377 case ISD::SETO: return getBoolConstant(R!=APFloat::cmpUnordered, dl, VT,
2378 OpVT);
2379 case ISD::SETUO: return getBoolConstant(R==APFloat::cmpUnordered, dl, VT,
2380 OpVT);
2381 case ISD::SETUEQ: return getBoolConstant(R==APFloat::cmpUnordered ||
2382 R==APFloat::cmpEqual, dl, VT,
2383 OpVT);
2384 case ISD::SETUNE: return getBoolConstant(R!=APFloat::cmpEqual, dl, VT,
2385 OpVT);
2386 case ISD::SETULT: return getBoolConstant(R==APFloat::cmpUnordered ||
2387 R==APFloat::cmpLessThan, dl, VT,
2388 OpVT);
2389 case ISD::SETUGT: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2390 R==APFloat::cmpUnordered, dl, VT,
2391 OpVT);
2392 case ISD::SETULE: return getBoolConstant(R!=APFloat::cmpGreaterThan, dl,
2393 VT, OpVT);
2394 case ISD::SETUGE: return getBoolConstant(R!=APFloat::cmpLessThan, dl, VT,
2395 OpVT);
2397 } else if (N1CFP && OpVT.isSimple() && !N2.isUndef()) {
2398 // Ensure that the constant occurs on the RHS.
2399 ISD::CondCode SwappedCond = ISD::getSetCCSwappedOperands(Cond);
2400 if (!TLI->isCondCodeLegal(SwappedCond, OpVT.getSimpleVT()))
2401 return SDValue();
2402 return getSetCC(dl, VT, N2, N1, SwappedCond);
2403 } else if ((N2CFP && N2CFP->getValueAPF().isNaN()) ||
2404 (OpVT.isFloatingPoint() && (N1.isUndef() || N2.isUndef()))) {
2405 // If an operand is known to be a nan (or undef that could be a nan), we can
2406 // fold it.
2407 // Choosing NaN for the undef will always make unordered comparison succeed
2408 // and ordered comparison fails.
2409 // Matches behavior in llvm::ConstantFoldCompareInstruction.
2410 switch (ISD::getUnorderedFlavor(Cond)) {
2411 default:
2412 llvm_unreachable("Unknown flavor!");
2413 case 0: // Known false.
2414 return getBoolConstant(false, dl, VT, OpVT);
2415 case 1: // Known true.
2416 return getBoolConstant(true, dl, VT, OpVT);
2417 case 2: // Undefined.
2418 return getUNDEF(VT);
2422 // Could not fold it.
2423 return SDValue();
2426 /// See if the specified operand can be simplified with the knowledge that only
2427 /// the bits specified by DemandedBits are used.
2428 /// TODO: really we should be making this into the DAG equivalent of
2429 /// SimplifyMultipleUseDemandedBits and not generate any new nodes.
2430 SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &DemandedBits) {
2431 EVT VT = V.getValueType();
2433 if (VT.isScalableVector())
2434 return SDValue();
2436 APInt DemandedElts = VT.isVector()
2437 ? APInt::getAllOnes(VT.getVectorNumElements())
2438 : APInt(1, 1);
2439 return GetDemandedBits(V, DemandedBits, DemandedElts);
2442 /// See if the specified operand can be simplified with the knowledge that only
2443 /// the bits specified by DemandedBits are used in the elements specified by
2444 /// DemandedElts.
2445 /// TODO: really we should be making this into the DAG equivalent of
2446 /// SimplifyMultipleUseDemandedBits and not generate any new nodes.
2447 SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &DemandedBits,
2448 const APInt &DemandedElts) {
2449 switch (V.getOpcode()) {
2450 default:
2451 return TLI->SimplifyMultipleUseDemandedBits(V, DemandedBits, DemandedElts,
2452 *this, 0);
2453 case ISD::Constant: {
2454 const APInt &CVal = cast<ConstantSDNode>(V)->getAPIntValue();
2455 APInt NewVal = CVal & DemandedBits;
2456 if (NewVal != CVal)
2457 return getConstant(NewVal, SDLoc(V), V.getValueType());
2458 break;
2460 case ISD::SRL:
2461 // Only look at single-use SRLs.
2462 if (!V.getNode()->hasOneUse())
2463 break;
2464 if (auto *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
2465 // See if we can recursively simplify the LHS.
2466 unsigned Amt = RHSC->getZExtValue();
2468 // Watch out for shift count overflow though.
2469 if (Amt >= DemandedBits.getBitWidth())
2470 break;
2471 APInt SrcDemandedBits = DemandedBits << Amt;
2472 if (SDValue SimplifyLHS =
2473 GetDemandedBits(V.getOperand(0), SrcDemandedBits))
2474 return getNode(ISD::SRL, SDLoc(V), V.getValueType(), SimplifyLHS,
2475 V.getOperand(1));
2477 break;
2479 return SDValue();
2482 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero. We
2483 /// use this predicate to simplify operations downstream.
2484 bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const {
2485 unsigned BitWidth = Op.getScalarValueSizeInBits();
2486 return MaskedValueIsZero(Op, APInt::getSignMask(BitWidth), Depth);
2489 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
2490 /// this predicate to simplify operations downstream. Mask is known to be zero
2491 /// for bits that V cannot have.
2492 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask,
2493 unsigned Depth) const {
2494 return Mask.isSubsetOf(computeKnownBits(V, Depth).Zero);
2497 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero in
2498 /// DemandedElts. We use this predicate to simplify operations downstream.
2499 /// Mask is known to be zero for bits that V cannot have.
2500 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask,
2501 const APInt &DemandedElts,
2502 unsigned Depth) const {
2503 return Mask.isSubsetOf(computeKnownBits(V, DemandedElts, Depth).Zero);
2506 /// MaskedValueIsAllOnes - Return true if '(Op & Mask) == Mask'.
2507 bool SelectionDAG::MaskedValueIsAllOnes(SDValue V, const APInt &Mask,
2508 unsigned Depth) const {
2509 return Mask.isSubsetOf(computeKnownBits(V, Depth).One);
2512 /// isSplatValue - Return true if the vector V has the same value
2513 /// across all DemandedElts. For scalable vectors it does not make
2514 /// sense to specify which elements are demanded or undefined, therefore
2515 /// they are simply ignored.
2516 bool SelectionDAG::isSplatValue(SDValue V, const APInt &DemandedElts,
2517 APInt &UndefElts, unsigned Depth) const {
2518 unsigned Opcode = V.getOpcode();
2519 EVT VT = V.getValueType();
2520 assert(VT.isVector() && "Vector type expected");
2522 if (!VT.isScalableVector() && !DemandedElts)
2523 return false; // No demanded elts, better to assume we don't know anything.
2525 if (Depth >= MaxRecursionDepth)
2526 return false; // Limit search depth.
2528 // Deal with some common cases here that work for both fixed and scalable
2529 // vector types.
2530 switch (Opcode) {
2531 case ISD::SPLAT_VECTOR:
2532 UndefElts = V.getOperand(0).isUndef()
2533 ? APInt::getAllOnes(DemandedElts.getBitWidth())
2534 : APInt(DemandedElts.getBitWidth(), 0);
2535 return true;
2536 case ISD::ADD:
2537 case ISD::SUB:
2538 case ISD::AND:
2539 case ISD::XOR:
2540 case ISD::OR: {
2541 APInt UndefLHS, UndefRHS;
2542 SDValue LHS = V.getOperand(0);
2543 SDValue RHS = V.getOperand(1);
2544 if (isSplatValue(LHS, DemandedElts, UndefLHS, Depth + 1) &&
2545 isSplatValue(RHS, DemandedElts, UndefRHS, Depth + 1)) {
2546 UndefElts = UndefLHS | UndefRHS;
2547 return true;
2549 return false;
2551 case ISD::ABS:
2552 case ISD::TRUNCATE:
2553 case ISD::SIGN_EXTEND:
2554 case ISD::ZERO_EXTEND:
2555 return isSplatValue(V.getOperand(0), DemandedElts, UndefElts, Depth + 1);
2556 default:
2557 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
2558 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID)
2559 return TLI->isSplatValueForTargetNode(V, DemandedElts, UndefElts, Depth);
2560 break;
2563 // We don't support other cases than those above for scalable vectors at
2564 // the moment.
2565 if (VT.isScalableVector())
2566 return false;
2568 unsigned NumElts = VT.getVectorNumElements();
2569 assert(NumElts == DemandedElts.getBitWidth() && "Vector size mismatch");
2570 UndefElts = APInt::getZero(NumElts);
2572 switch (Opcode) {
2573 case ISD::BUILD_VECTOR: {
2574 SDValue Scl;
2575 for (unsigned i = 0; i != NumElts; ++i) {
2576 SDValue Op = V.getOperand(i);
2577 if (Op.isUndef()) {
2578 UndefElts.setBit(i);
2579 continue;
2581 if (!DemandedElts[i])
2582 continue;
2583 if (Scl && Scl != Op)
2584 return false;
2585 Scl = Op;
2587 return true;
2589 case ISD::VECTOR_SHUFFLE: {
2590 // Check if this is a shuffle node doing a splat.
2591 // TODO: Do we need to handle shuffle(splat, undef, mask)?
2592 int SplatIndex = -1;
2593 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(V)->getMask();
2594 for (int i = 0; i != (int)NumElts; ++i) {
2595 int M = Mask[i];
2596 if (M < 0) {
2597 UndefElts.setBit(i);
2598 continue;
2600 if (!DemandedElts[i])
2601 continue;
2602 if (0 <= SplatIndex && SplatIndex != M)
2603 return false;
2604 SplatIndex = M;
2606 return true;
2608 case ISD::EXTRACT_SUBVECTOR: {
2609 // Offset the demanded elts by the subvector index.
2610 SDValue Src = V.getOperand(0);
2611 // We don't support scalable vectors at the moment.
2612 if (Src.getValueType().isScalableVector())
2613 return false;
2614 uint64_t Idx = V.getConstantOperandVal(1);
2615 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2616 APInt UndefSrcElts;
2617 APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
2618 if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) {
2619 UndefElts = UndefSrcElts.extractBits(NumElts, Idx);
2620 return true;
2622 break;
2624 case ISD::ANY_EXTEND_VECTOR_INREG:
2625 case ISD::SIGN_EXTEND_VECTOR_INREG:
2626 case ISD::ZERO_EXTEND_VECTOR_INREG: {
2627 // Widen the demanded elts by the src element count.
2628 SDValue Src = V.getOperand(0);
2629 // We don't support scalable vectors at the moment.
2630 if (Src.getValueType().isScalableVector())
2631 return false;
2632 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2633 APInt UndefSrcElts;
2634 APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts);
2635 if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) {
2636 UndefElts = UndefSrcElts.truncOrSelf(NumElts);
2637 return true;
2639 break;
2643 return false;
2646 /// Helper wrapper to main isSplatValue function.
2647 bool SelectionDAG::isSplatValue(SDValue V, bool AllowUndefs) const {
2648 EVT VT = V.getValueType();
2649 assert(VT.isVector() && "Vector type expected");
2651 APInt UndefElts;
2652 APInt DemandedElts;
2654 // For now we don't support this with scalable vectors.
2655 if (!VT.isScalableVector())
2656 DemandedElts = APInt::getAllOnes(VT.getVectorNumElements());
2657 return isSplatValue(V, DemandedElts, UndefElts) &&
2658 (AllowUndefs || !UndefElts);
2661 SDValue SelectionDAG::getSplatSourceVector(SDValue V, int &SplatIdx) {
2662 V = peekThroughExtractSubvectors(V);
2664 EVT VT = V.getValueType();
2665 unsigned Opcode = V.getOpcode();
2666 switch (Opcode) {
2667 default: {
2668 APInt UndefElts;
2669 APInt DemandedElts;
2671 if (!VT.isScalableVector())
2672 DemandedElts = APInt::getAllOnes(VT.getVectorNumElements());
2674 if (isSplatValue(V, DemandedElts, UndefElts)) {
2675 if (VT.isScalableVector()) {
2676 // DemandedElts and UndefElts are ignored for scalable vectors, since
2677 // the only supported cases are SPLAT_VECTOR nodes.
2678 SplatIdx = 0;
2679 } else {
2680 // Handle case where all demanded elements are UNDEF.
2681 if (DemandedElts.isSubsetOf(UndefElts)) {
2682 SplatIdx = 0;
2683 return getUNDEF(VT);
2685 SplatIdx = (UndefElts & DemandedElts).countTrailingOnes();
2687 return V;
2689 break;
2691 case ISD::SPLAT_VECTOR:
2692 SplatIdx = 0;
2693 return V;
2694 case ISD::VECTOR_SHUFFLE: {
2695 if (VT.isScalableVector())
2696 return SDValue();
2698 // Check if this is a shuffle node doing a splat.
2699 // TODO - remove this and rely purely on SelectionDAG::isSplatValue,
2700 // getTargetVShiftNode currently struggles without the splat source.
2701 auto *SVN = cast<ShuffleVectorSDNode>(V);
2702 if (!SVN->isSplat())
2703 break;
2704 int Idx = SVN->getSplatIndex();
2705 int NumElts = V.getValueType().getVectorNumElements();
2706 SplatIdx = Idx % NumElts;
2707 return V.getOperand(Idx / NumElts);
2711 return SDValue();
2714 SDValue SelectionDAG::getSplatValue(SDValue V, bool LegalTypes) {
2715 int SplatIdx;
2716 if (SDValue SrcVector = getSplatSourceVector(V, SplatIdx)) {
2717 EVT SVT = SrcVector.getValueType().getScalarType();
2718 EVT LegalSVT = SVT;
2719 if (LegalTypes && !TLI->isTypeLegal(SVT)) {
2720 if (!SVT.isInteger())
2721 return SDValue();
2722 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
2723 if (LegalSVT.bitsLT(SVT))
2724 return SDValue();
2726 return getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(V), LegalSVT, SrcVector,
2727 getVectorIdxConstant(SplatIdx, SDLoc(V)));
2729 return SDValue();
2732 const APInt *
2733 SelectionDAG::getValidShiftAmountConstant(SDValue V,
2734 const APInt &DemandedElts) const {
2735 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
2736 V.getOpcode() == ISD::SRA) &&
2737 "Unknown shift node");
2738 unsigned BitWidth = V.getScalarValueSizeInBits();
2739 if (ConstantSDNode *SA = isConstOrConstSplat(V.getOperand(1), DemandedElts)) {
2740 // Shifting more than the bitwidth is not valid.
2741 const APInt &ShAmt = SA->getAPIntValue();
2742 if (ShAmt.ult(BitWidth))
2743 return &ShAmt;
2745 return nullptr;
2748 const APInt *SelectionDAG::getValidMinimumShiftAmountConstant(
2749 SDValue V, const APInt &DemandedElts) const {
2750 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
2751 V.getOpcode() == ISD::SRA) &&
2752 "Unknown shift node");
2753 if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts))
2754 return ValidAmt;
2755 unsigned BitWidth = V.getScalarValueSizeInBits();
2756 auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1));
2757 if (!BV)
2758 return nullptr;
2759 const APInt *MinShAmt = nullptr;
2760 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
2761 if (!DemandedElts[i])
2762 continue;
2763 auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i));
2764 if (!SA)
2765 return nullptr;
2766 // Shifting more than the bitwidth is not valid.
2767 const APInt &ShAmt = SA->getAPIntValue();
2768 if (ShAmt.uge(BitWidth))
2769 return nullptr;
2770 if (MinShAmt && MinShAmt->ule(ShAmt))
2771 continue;
2772 MinShAmt = &ShAmt;
2774 return MinShAmt;
2777 const APInt *SelectionDAG::getValidMaximumShiftAmountConstant(
2778 SDValue V, const APInt &DemandedElts) const {
2779 assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
2780 V.getOpcode() == ISD::SRA) &&
2781 "Unknown shift node");
2782 if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts))
2783 return ValidAmt;
2784 unsigned BitWidth = V.getScalarValueSizeInBits();
2785 auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1));
2786 if (!BV)
2787 return nullptr;
2788 const APInt *MaxShAmt = nullptr;
2789 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
2790 if (!DemandedElts[i])
2791 continue;
2792 auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i));
2793 if (!SA)
2794 return nullptr;
2795 // Shifting more than the bitwidth is not valid.
2796 const APInt &ShAmt = SA->getAPIntValue();
2797 if (ShAmt.uge(BitWidth))
2798 return nullptr;
2799 if (MaxShAmt && MaxShAmt->uge(ShAmt))
2800 continue;
2801 MaxShAmt = &ShAmt;
2803 return MaxShAmt;
2806 /// Determine which bits of Op are known to be either zero or one and return
2807 /// them in Known. For vectors, the known bits are those that are shared by
2808 /// every vector element.
2809 KnownBits SelectionDAG::computeKnownBits(SDValue Op, unsigned Depth) const {
2810 EVT VT = Op.getValueType();
2812 // TOOD: Until we have a plan for how to represent demanded elements for
2813 // scalable vectors, we can just bail out for now.
2814 if (Op.getValueType().isScalableVector()) {
2815 unsigned BitWidth = Op.getScalarValueSizeInBits();
2816 return KnownBits(BitWidth);
2819 APInt DemandedElts = VT.isVector()
2820 ? APInt::getAllOnes(VT.getVectorNumElements())
2821 : APInt(1, 1);
2822 return computeKnownBits(Op, DemandedElts, Depth);
2825 /// Determine which bits of Op are known to be either zero or one and return
2826 /// them in Known. The DemandedElts argument allows us to only collect the known
2827 /// bits that are shared by the requested vector elements.
2828 KnownBits SelectionDAG::computeKnownBits(SDValue Op, const APInt &DemandedElts,
2829 unsigned Depth) const {
2830 unsigned BitWidth = Op.getScalarValueSizeInBits();
2832 KnownBits Known(BitWidth); // Don't know anything.
2834 // TOOD: Until we have a plan for how to represent demanded elements for
2835 // scalable vectors, we can just bail out for now.
2836 if (Op.getValueType().isScalableVector())
2837 return Known;
2839 if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
2840 // We know all of the bits for a constant!
2841 return KnownBits::makeConstant(C->getAPIntValue());
2843 if (auto *C = dyn_cast<ConstantFPSDNode>(Op)) {
2844 // We know all of the bits for a constant fp!
2845 return KnownBits::makeConstant(C->getValueAPF().bitcastToAPInt());
2848 if (Depth >= MaxRecursionDepth)
2849 return Known; // Limit search depth.
2851 KnownBits Known2;
2852 unsigned NumElts = DemandedElts.getBitWidth();
2853 assert((!Op.getValueType().isVector() ||
2854 NumElts == Op.getValueType().getVectorNumElements()) &&
2855 "Unexpected vector size");
2857 if (!DemandedElts)
2858 return Known; // No demanded elts, better to assume we don't know anything.
2860 unsigned Opcode = Op.getOpcode();
2861 switch (Opcode) {
2862 case ISD::BUILD_VECTOR:
2863 // Collect the known bits that are shared by every demanded vector element.
2864 Known.Zero.setAllBits(); Known.One.setAllBits();
2865 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
2866 if (!DemandedElts[i])
2867 continue;
2869 SDValue SrcOp = Op.getOperand(i);
2870 Known2 = computeKnownBits(SrcOp, Depth + 1);
2872 // BUILD_VECTOR can implicitly truncate sources, we must handle this.
2873 if (SrcOp.getValueSizeInBits() != BitWidth) {
2874 assert(SrcOp.getValueSizeInBits() > BitWidth &&
2875 "Expected BUILD_VECTOR implicit truncation");
2876 Known2 = Known2.trunc(BitWidth);
2879 // Known bits are the values that are shared by every demanded element.
2880 Known = KnownBits::commonBits(Known, Known2);
2882 // If we don't know any bits, early out.
2883 if (Known.isUnknown())
2884 break;
2886 break;
2887 case ISD::VECTOR_SHUFFLE: {
2888 // Collect the known bits that are shared by every vector element referenced
2889 // by the shuffle.
2890 APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
2891 Known.Zero.setAllBits(); Known.One.setAllBits();
2892 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
2893 assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
2894 for (unsigned i = 0; i != NumElts; ++i) {
2895 if (!DemandedElts[i])
2896 continue;
2898 int M = SVN->getMaskElt(i);
2899 if (M < 0) {
2900 // For UNDEF elements, we don't know anything about the common state of
2901 // the shuffle result.
2902 Known.resetAll();
2903 DemandedLHS.clearAllBits();
2904 DemandedRHS.clearAllBits();
2905 break;
2908 if ((unsigned)M < NumElts)
2909 DemandedLHS.setBit((unsigned)M % NumElts);
2910 else
2911 DemandedRHS.setBit((unsigned)M % NumElts);
2913 // Known bits are the values that are shared by every demanded element.
2914 if (!!DemandedLHS) {
2915 SDValue LHS = Op.getOperand(0);
2916 Known2 = computeKnownBits(LHS, DemandedLHS, Depth + 1);
2917 Known = KnownBits::commonBits(Known, Known2);
2919 // If we don't know any bits, early out.
2920 if (Known.isUnknown())
2921 break;
2922 if (!!DemandedRHS) {
2923 SDValue RHS = Op.getOperand(1);
2924 Known2 = computeKnownBits(RHS, DemandedRHS, Depth + 1);
2925 Known = KnownBits::commonBits(Known, Known2);
2927 break;
2929 case ISD::CONCAT_VECTORS: {
2930 // Split DemandedElts and test each of the demanded subvectors.
2931 Known.Zero.setAllBits(); Known.One.setAllBits();
2932 EVT SubVectorVT = Op.getOperand(0).getValueType();
2933 unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
2934 unsigned NumSubVectors = Op.getNumOperands();
2935 for (unsigned i = 0; i != NumSubVectors; ++i) {
2936 APInt DemandedSub =
2937 DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts);
2938 if (!!DemandedSub) {
2939 SDValue Sub = Op.getOperand(i);
2940 Known2 = computeKnownBits(Sub, DemandedSub, Depth + 1);
2941 Known = KnownBits::commonBits(Known, Known2);
2943 // If we don't know any bits, early out.
2944 if (Known.isUnknown())
2945 break;
2947 break;
2949 case ISD::INSERT_SUBVECTOR: {
2950 // Demand any elements from the subvector and the remainder from the src its
2951 // inserted into.
2952 SDValue Src = Op.getOperand(0);
2953 SDValue Sub = Op.getOperand(1);
2954 uint64_t Idx = Op.getConstantOperandVal(2);
2955 unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
2956 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
2957 APInt DemandedSrcElts = DemandedElts;
2958 DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx);
2960 Known.One.setAllBits();
2961 Known.Zero.setAllBits();
2962 if (!!DemandedSubElts) {
2963 Known = computeKnownBits(Sub, DemandedSubElts, Depth + 1);
2964 if (Known.isUnknown())
2965 break; // early-out.
2967 if (!!DemandedSrcElts) {
2968 Known2 = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
2969 Known = KnownBits::commonBits(Known, Known2);
2971 break;
2973 case ISD::EXTRACT_SUBVECTOR: {
2974 // Offset the demanded elts by the subvector index.
2975 SDValue Src = Op.getOperand(0);
2976 // Bail until we can represent demanded elements for scalable vectors.
2977 if (Src.getValueType().isScalableVector())
2978 break;
2979 uint64_t Idx = Op.getConstantOperandVal(1);
2980 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2981 APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
2982 Known = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
2983 break;
2985 case ISD::SCALAR_TO_VECTOR: {
2986 // We know about scalar_to_vector as much as we know about it source,
2987 // which becomes the first element of otherwise unknown vector.
2988 if (DemandedElts != 1)
2989 break;
2991 SDValue N0 = Op.getOperand(0);
2992 Known = computeKnownBits(N0, Depth + 1);
2993 if (N0.getValueSizeInBits() != BitWidth)
2994 Known = Known.trunc(BitWidth);
2996 break;
2998 case ISD::BITCAST: {
2999 SDValue N0 = Op.getOperand(0);
3000 EVT SubVT = N0.getValueType();
3001 unsigned SubBitWidth = SubVT.getScalarSizeInBits();
3003 // Ignore bitcasts from unsupported types.
3004 if (!(SubVT.isInteger() || SubVT.isFloatingPoint()))
3005 break;
3007 // Fast handling of 'identity' bitcasts.
3008 if (BitWidth == SubBitWidth) {
3009 Known = computeKnownBits(N0, DemandedElts, Depth + 1);
3010 break;
3013 bool IsLE = getDataLayout().isLittleEndian();
3015 // Bitcast 'small element' vector to 'large element' scalar/vector.
3016 if ((BitWidth % SubBitWidth) == 0) {
3017 assert(N0.getValueType().isVector() && "Expected bitcast from vector");
3019 // Collect known bits for the (larger) output by collecting the known
3020 // bits from each set of sub elements and shift these into place.
3021 // We need to separately call computeKnownBits for each set of
3022 // sub elements as the knownbits for each is likely to be different.
3023 unsigned SubScale = BitWidth / SubBitWidth;
3024 APInt SubDemandedElts(NumElts * SubScale, 0);
3025 for (unsigned i = 0; i != NumElts; ++i)
3026 if (DemandedElts[i])
3027 SubDemandedElts.setBit(i * SubScale);
3029 for (unsigned i = 0; i != SubScale; ++i) {
3030 Known2 = computeKnownBits(N0, SubDemandedElts.shl(i),
3031 Depth + 1);
3032 unsigned Shifts = IsLE ? i : SubScale - 1 - i;
3033 Known.insertBits(Known2, SubBitWidth * Shifts);
3037 // Bitcast 'large element' scalar/vector to 'small element' vector.
3038 if ((SubBitWidth % BitWidth) == 0) {
3039 assert(Op.getValueType().isVector() && "Expected bitcast to vector");
3041 // Collect known bits for the (smaller) output by collecting the known
3042 // bits from the overlapping larger input elements and extracting the
3043 // sub sections we actually care about.
3044 unsigned SubScale = SubBitWidth / BitWidth;
3045 APInt SubDemandedElts =
3046 APIntOps::ScaleBitMask(DemandedElts, NumElts / SubScale);
3047 Known2 = computeKnownBits(N0, SubDemandedElts, Depth + 1);
3049 Known.Zero.setAllBits(); Known.One.setAllBits();
3050 for (unsigned i = 0; i != NumElts; ++i)
3051 if (DemandedElts[i]) {
3052 unsigned Shifts = IsLE ? i : NumElts - 1 - i;
3053 unsigned Offset = (Shifts % SubScale) * BitWidth;
3054 Known = KnownBits::commonBits(Known,
3055 Known2.extractBits(BitWidth, Offset));
3056 // If we don't know any bits, early out.
3057 if (Known.isUnknown())
3058 break;
3061 break;
3063 case ISD::AND:
3064 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3065 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3067 Known &= Known2;
3068 break;
3069 case ISD::OR:
3070 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3071 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3073 Known |= Known2;
3074 break;
3075 case ISD::XOR:
3076 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3077 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3079 Known ^= Known2;
3080 break;
3081 case ISD::MUL: {
3082 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3083 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3084 Known = KnownBits::mul(Known, Known2);
3085 break;
3087 case ISD::MULHU: {
3088 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3089 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3090 Known = KnownBits::mulhu(Known, Known2);
3091 break;
3093 case ISD::MULHS: {
3094 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3095 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3096 Known = KnownBits::mulhs(Known, Known2);
3097 break;
3099 case ISD::UMUL_LOHI: {
3100 assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3101 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3102 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3103 if (Op.getResNo() == 0)
3104 Known = KnownBits::mul(Known, Known2);
3105 else
3106 Known = KnownBits::mulhu(Known, Known2);
3107 break;
3109 case ISD::SMUL_LOHI: {
3110 assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3111 Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3112 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3113 if (Op.getResNo() == 0)
3114 Known = KnownBits::mul(Known, Known2);
3115 else
3116 Known = KnownBits::mulhs(Known, Known2);
3117 break;
3119 case ISD::UDIV: {
3120 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3121 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3122 Known = KnownBits::udiv(Known, Known2);
3123 break;
3125 case ISD::SELECT:
3126 case ISD::VSELECT:
3127 Known = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
3128 // If we don't know any bits, early out.
3129 if (Known.isUnknown())
3130 break;
3131 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth+1);
3133 // Only known if known in both the LHS and RHS.
3134 Known = KnownBits::commonBits(Known, Known2);
3135 break;
3136 case ISD::SELECT_CC:
3137 Known = computeKnownBits(Op.getOperand(3), DemandedElts, Depth+1);
3138 // If we don't know any bits, early out.
3139 if (Known.isUnknown())
3140 break;
3141 Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
3143 // Only known if known in both the LHS and RHS.
3144 Known = KnownBits::commonBits(Known, Known2);
3145 break;
3146 case ISD::SMULO:
3147 case ISD::UMULO:
3148 if (Op.getResNo() != 1)
3149 break;
3150 // The boolean result conforms to getBooleanContents.
3151 // If we know the result of a setcc has the top bits zero, use this info.
3152 // We know that we have an integer-based boolean since these operations
3153 // are only available for integer.
3154 if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
3155 TargetLowering::ZeroOrOneBooleanContent &&
3156 BitWidth > 1)
3157 Known.Zero.setBitsFrom(1);
3158 break;
3159 case ISD::SETCC:
3160 case ISD::STRICT_FSETCC:
3161 case ISD::STRICT_FSETCCS: {
3162 unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
3163 // If we know the result of a setcc has the top bits zero, use this info.
3164 if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
3165 TargetLowering::ZeroOrOneBooleanContent &&
3166 BitWidth > 1)
3167 Known.Zero.setBitsFrom(1);
3168 break;
3170 case ISD::SHL:
3171 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3172 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3173 Known = KnownBits::shl(Known, Known2);
3175 // Minimum shift low bits are known zero.
3176 if (const APInt *ShMinAmt =
3177 getValidMinimumShiftAmountConstant(Op, DemandedElts))
3178 Known.Zero.setLowBits(ShMinAmt->getZExtValue());
3179 break;
3180 case ISD::SRL:
3181 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3182 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3183 Known = KnownBits::lshr(Known, Known2);
3185 // Minimum shift high bits are known zero.
3186 if (const APInt *ShMinAmt =
3187 getValidMinimumShiftAmountConstant(Op, DemandedElts))
3188 Known.Zero.setHighBits(ShMinAmt->getZExtValue());
3189 break;
3190 case ISD::SRA:
3191 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3192 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3193 Known = KnownBits::ashr(Known, Known2);
3194 // TODO: Add minimum shift high known sign bits.
3195 break;
3196 case ISD::FSHL:
3197 case ISD::FSHR:
3198 if (ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(2), DemandedElts)) {
3199 unsigned Amt = C->getAPIntValue().urem(BitWidth);
3201 // For fshl, 0-shift returns the 1st arg.
3202 // For fshr, 0-shift returns the 2nd arg.
3203 if (Amt == 0) {
3204 Known = computeKnownBits(Op.getOperand(Opcode == ISD::FSHL ? 0 : 1),
3205 DemandedElts, Depth + 1);
3206 break;
3209 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
3210 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
3211 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3212 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3213 if (Opcode == ISD::FSHL) {
3214 Known.One <<= Amt;
3215 Known.Zero <<= Amt;
3216 Known2.One.lshrInPlace(BitWidth - Amt);
3217 Known2.Zero.lshrInPlace(BitWidth - Amt);
3218 } else {
3219 Known.One <<= BitWidth - Amt;
3220 Known.Zero <<= BitWidth - Amt;
3221 Known2.One.lshrInPlace(Amt);
3222 Known2.Zero.lshrInPlace(Amt);
3224 Known.One |= Known2.One;
3225 Known.Zero |= Known2.Zero;
3227 break;
3228 case ISD::SIGN_EXTEND_INREG: {
3229 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3230 EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3231 Known = Known.sextInReg(EVT.getScalarSizeInBits());
3232 break;
3234 case ISD::CTTZ:
3235 case ISD::CTTZ_ZERO_UNDEF: {
3236 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3237 // If we have a known 1, its position is our upper bound.
3238 unsigned PossibleTZ = Known2.countMaxTrailingZeros();
3239 unsigned LowBits = Log2_32(PossibleTZ) + 1;
3240 Known.Zero.setBitsFrom(LowBits);
3241 break;
3243 case ISD::CTLZ:
3244 case ISD::CTLZ_ZERO_UNDEF: {
3245 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3246 // If we have a known 1, its position is our upper bound.
3247 unsigned PossibleLZ = Known2.countMaxLeadingZeros();
3248 unsigned LowBits = Log2_32(PossibleLZ) + 1;
3249 Known.Zero.setBitsFrom(LowBits);
3250 break;
3252 case ISD::CTPOP: {
3253 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3254 // If we know some of the bits are zero, they can't be one.
3255 unsigned PossibleOnes = Known2.countMaxPopulation();
3256 Known.Zero.setBitsFrom(Log2_32(PossibleOnes) + 1);
3257 break;
3259 case ISD::PARITY: {
3260 // Parity returns 0 everywhere but the LSB.
3261 Known.Zero.setBitsFrom(1);
3262 break;
3264 case ISD::LOAD: {
3265 LoadSDNode *LD = cast<LoadSDNode>(Op);
3266 const Constant *Cst = TLI->getTargetConstantFromLoad(LD);
3267 if (ISD::isNON_EXTLoad(LD) && Cst) {
3268 // Determine any common known bits from the loaded constant pool value.
3269 Type *CstTy = Cst->getType();
3270 if ((NumElts * BitWidth) == CstTy->getPrimitiveSizeInBits()) {
3271 // If its a vector splat, then we can (quickly) reuse the scalar path.
3272 // NOTE: We assume all elements match and none are UNDEF.
3273 if (CstTy->isVectorTy()) {
3274 if (const Constant *Splat = Cst->getSplatValue()) {
3275 Cst = Splat;
3276 CstTy = Cst->getType();
3279 // TODO - do we need to handle different bitwidths?
3280 if (CstTy->isVectorTy() && BitWidth == CstTy->getScalarSizeInBits()) {
3281 // Iterate across all vector elements finding common known bits.
3282 Known.One.setAllBits();
3283 Known.Zero.setAllBits();
3284 for (unsigned i = 0; i != NumElts; ++i) {
3285 if (!DemandedElts[i])
3286 continue;
3287 if (Constant *Elt = Cst->getAggregateElement(i)) {
3288 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
3289 const APInt &Value = CInt->getValue();
3290 Known.One &= Value;
3291 Known.Zero &= ~Value;
3292 continue;
3294 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
3295 APInt Value = CFP->getValueAPF().bitcastToAPInt();
3296 Known.One &= Value;
3297 Known.Zero &= ~Value;
3298 continue;
3301 Known.One.clearAllBits();
3302 Known.Zero.clearAllBits();
3303 break;
3305 } else if (BitWidth == CstTy->getPrimitiveSizeInBits()) {
3306 if (auto *CInt = dyn_cast<ConstantInt>(Cst)) {
3307 Known = KnownBits::makeConstant(CInt->getValue());
3308 } else if (auto *CFP = dyn_cast<ConstantFP>(Cst)) {
3309 Known =
3310 KnownBits::makeConstant(CFP->getValueAPF().bitcastToAPInt());
3314 } else if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) {
3315 // If this is a ZEXTLoad and we are looking at the loaded value.
3316 EVT VT = LD->getMemoryVT();
3317 unsigned MemBits = VT.getScalarSizeInBits();
3318 Known.Zero.setBitsFrom(MemBits);
3319 } else if (const MDNode *Ranges = LD->getRanges()) {
3320 if (LD->getExtensionType() == ISD::NON_EXTLOAD)
3321 computeKnownBitsFromRangeMetadata(*Ranges, Known);
3323 break;
3325 case ISD::ZERO_EXTEND_VECTOR_INREG: {
3326 EVT InVT = Op.getOperand(0).getValueType();
3327 APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements());
3328 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3329 Known = Known.zext(BitWidth);
3330 break;
3332 case ISD::ZERO_EXTEND: {
3333 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3334 Known = Known.zext(BitWidth);
3335 break;
3337 case ISD::SIGN_EXTEND_VECTOR_INREG: {
3338 EVT InVT = Op.getOperand(0).getValueType();
3339 APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements());
3340 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3341 // If the sign bit is known to be zero or one, then sext will extend
3342 // it to the top bits, else it will just zext.
3343 Known = Known.sext(BitWidth);
3344 break;
3346 case ISD::SIGN_EXTEND: {
3347 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3348 // If the sign bit is known to be zero or one, then sext will extend
3349 // it to the top bits, else it will just zext.
3350 Known = Known.sext(BitWidth);
3351 break;
3353 case ISD::ANY_EXTEND_VECTOR_INREG: {
3354 EVT InVT = Op.getOperand(0).getValueType();
3355 APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements());
3356 Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3357 Known = Known.anyext(BitWidth);
3358 break;
3360 case ISD::ANY_EXTEND: {
3361 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3362 Known = Known.anyext(BitWidth);
3363 break;
3365 case ISD::TRUNCATE: {
3366 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3367 Known = Known.trunc(BitWidth);
3368 break;
3370 case ISD::AssertZext: {
3371 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3372 APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits());
3373 Known = computeKnownBits(Op.getOperand(0), Depth+1);
3374 Known.Zero |= (~InMask);
3375 Known.One &= (~Known.Zero);
3376 break;
3378 case ISD::AssertAlign: {
3379 unsigned LogOfAlign = Log2(cast<AssertAlignSDNode>(Op)->getAlign());
3380 assert(LogOfAlign != 0);
3381 // If a node is guaranteed to be aligned, set low zero bits accordingly as
3382 // well as clearing one bits.
3383 Known.Zero.setLowBits(LogOfAlign);
3384 Known.One.clearLowBits(LogOfAlign);
3385 break;
3387 case ISD::FGETSIGN:
3388 // All bits are zero except the low bit.
3389 Known.Zero.setBitsFrom(1);
3390 break;
3391 case ISD::USUBO:
3392 case ISD::SSUBO:
3393 if (Op.getResNo() == 1) {
3394 // If we know the result of a setcc has the top bits zero, use this info.
3395 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
3396 TargetLowering::ZeroOrOneBooleanContent &&
3397 BitWidth > 1)
3398 Known.Zero.setBitsFrom(1);
3399 break;
3401 LLVM_FALLTHROUGH;
3402 case ISD::SUB:
3403 case ISD::SUBC: {
3404 assert(Op.getResNo() == 0 &&
3405 "We only compute knownbits for the difference here.");
3407 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3408 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3409 Known = KnownBits::computeForAddSub(/* Add */ false, /* NSW */ false,
3410 Known, Known2);
3411 break;
3413 case ISD::UADDO:
3414 case ISD::SADDO:
3415 case ISD::ADDCARRY:
3416 if (Op.getResNo() == 1) {
3417 // If we know the result of a setcc has the top bits zero, use this info.
3418 if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
3419 TargetLowering::ZeroOrOneBooleanContent &&
3420 BitWidth > 1)
3421 Known.Zero.setBitsFrom(1);
3422 break;
3424 LLVM_FALLTHROUGH;
3425 case ISD::ADD:
3426 case ISD::ADDC:
3427 case ISD::ADDE: {
3428 assert(Op.getResNo() == 0 && "We only compute knownbits for the sum here.");
3430 // With ADDE and ADDCARRY, a carry bit may be added in.
3431 KnownBits Carry(1);
3432 if (Opcode == ISD::ADDE)
3433 // Can't track carry from glue, set carry to unknown.
3434 Carry.resetAll();
3435 else if (Opcode == ISD::ADDCARRY)
3436 // TODO: Compute known bits for the carry operand. Not sure if it is worth
3437 // the trouble (how often will we find a known carry bit). And I haven't
3438 // tested this very much yet, but something like this might work:
3439 // Carry = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1);
3440 // Carry = Carry.zextOrTrunc(1, false);
3441 Carry.resetAll();
3442 else
3443 Carry.setAllZero();
3445 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3446 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3447 Known = KnownBits::computeForAddCarry(Known, Known2, Carry);
3448 break;
3450 case ISD::SREM: {
3451 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3452 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3453 Known = KnownBits::srem(Known, Known2);
3454 break;
3456 case ISD::UREM: {
3457 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3458 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3459 Known = KnownBits::urem(Known, Known2);
3460 break;
3462 case ISD::EXTRACT_ELEMENT: {
3463 Known = computeKnownBits(Op.getOperand(0), Depth+1);
3464 const unsigned Index = Op.getConstantOperandVal(1);
3465 const unsigned EltBitWidth = Op.getValueSizeInBits();
3467 // Remove low part of known bits mask
3468 Known.Zero = Known.Zero.getHiBits(Known.getBitWidth() - Index * EltBitWidth);
3469 Known.One = Known.One.getHiBits(Known.getBitWidth() - Index * EltBitWidth);
3471 // Remove high part of known bit mask
3472 Known = Known.trunc(EltBitWidth);
3473 break;
3475 case ISD::EXTRACT_VECTOR_ELT: {
3476 SDValue InVec = Op.getOperand(0);
3477 SDValue EltNo = Op.getOperand(1);
3478 EVT VecVT = InVec.getValueType();
3479 // computeKnownBits not yet implemented for scalable vectors.
3480 if (VecVT.isScalableVector())
3481 break;
3482 const unsigned EltBitWidth = VecVT.getScalarSizeInBits();
3483 const unsigned NumSrcElts = VecVT.getVectorNumElements();
3485 // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know
3486 // anything about the extended bits.
3487 if (BitWidth > EltBitWidth)
3488 Known = Known.trunc(EltBitWidth);
3490 // If we know the element index, just demand that vector element, else for
3491 // an unknown element index, ignore DemandedElts and demand them all.
3492 APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
3493 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
3494 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
3495 DemandedSrcElts =
3496 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
3498 Known = computeKnownBits(InVec, DemandedSrcElts, Depth + 1);
3499 if (BitWidth > EltBitWidth)
3500 Known = Known.anyext(BitWidth);
3501 break;
3503 case ISD::INSERT_VECTOR_ELT: {
3504 // If we know the element index, split the demand between the
3505 // source vector and the inserted element, otherwise assume we need
3506 // the original demanded vector elements and the value.
3507 SDValue InVec = Op.getOperand(0);
3508 SDValue InVal = Op.getOperand(1);
3509 SDValue EltNo = Op.getOperand(2);
3510 bool DemandedVal = true;
3511 APInt DemandedVecElts = DemandedElts;
3512 auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
3513 if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
3514 unsigned EltIdx = CEltNo->getZExtValue();
3515 DemandedVal = !!DemandedElts[EltIdx];
3516 DemandedVecElts.clearBit(EltIdx);
3518 Known.One.setAllBits();
3519 Known.Zero.setAllBits();
3520 if (DemandedVal) {
3521 Known2 = computeKnownBits(InVal, Depth + 1);
3522 Known = KnownBits::commonBits(Known, Known2.zextOrTrunc(BitWidth));
3524 if (!!DemandedVecElts) {
3525 Known2 = computeKnownBits(InVec, DemandedVecElts, Depth + 1);
3526 Known = KnownBits::commonBits(Known, Known2);
3528 break;
3530 case ISD::BITREVERSE: {
3531 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3532 Known = Known2.reverseBits();
3533 break;
3535 case ISD::BSWAP: {
3536 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3537 Known = Known2.byteSwap();
3538 break;
3540 case ISD::ABS: {
3541 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3542 Known = Known2.abs();
3543 break;
3545 case ISD::USUBSAT: {
3546 // The result of usubsat will never be larger than the LHS.
3547 Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3548 Known.Zero.setHighBits(Known2.countMinLeadingZeros());
3549 break;
3551 case ISD::UMIN: {
3552 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3553 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3554 Known = KnownBits::umin(Known, Known2);
3555 break;
3557 case ISD::UMAX: {
3558 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3559 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3560 Known = KnownBits::umax(Known, Known2);
3561 break;
3563 case ISD::SMIN:
3564 case ISD::SMAX: {
3565 // If we have a clamp pattern, we know that the number of sign bits will be
3566 // the minimum of the clamp min/max range.
3567 bool IsMax = (Opcode == ISD::SMAX);
3568 ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
3569 if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
3570 if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
3571 CstHigh =
3572 isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
3573 if (CstLow && CstHigh) {
3574 if (!IsMax)
3575 std::swap(CstLow, CstHigh);
3577 const APInt &ValueLow = CstLow->getAPIntValue();
3578 const APInt &ValueHigh = CstHigh->getAPIntValue();
3579 if (ValueLow.sle(ValueHigh)) {
3580 unsigned LowSignBits = ValueLow.getNumSignBits();
3581 unsigned HighSignBits = ValueHigh.getNumSignBits();
3582 unsigned MinSignBits = std::min(LowSignBits, HighSignBits);
3583 if (ValueLow.isNegative() && ValueHigh.isNegative()) {
3584 Known.One.setHighBits(MinSignBits);
3585 break;
3587 if (ValueLow.isNonNegative() && ValueHigh.isNonNegative()) {
3588 Known.Zero.setHighBits(MinSignBits);
3589 break;
3594 Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3595 Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3596 if (IsMax)
3597 Known = KnownBits::smax(Known, Known2);
3598 else
3599 Known = KnownBits::smin(Known, Known2);
3600 break;
3602 case ISD::FP_TO_UINT_SAT: {
3603 // FP_TO_UINT_SAT produces an unsigned value that fits in the saturating VT.
3604 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3605 Known.Zero |= APInt::getBitsSetFrom(BitWidth, VT.getScalarSizeInBits());
3606 break;
3608 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
3609 if (Op.getResNo() == 1) {
3610 // The boolean result conforms to getBooleanContents.
3611 // If we know the result of a setcc has the top bits zero, use this info.
3612 // We know that we have an integer-based boolean since these operations
3613 // are only available for integer.
3614 if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
3615 TargetLowering::ZeroOrOneBooleanContent &&
3616 BitWidth > 1)
3617 Known.Zero.setBitsFrom(1);
3618 break;
3620 LLVM_FALLTHROUGH;
3621 case ISD::ATOMIC_CMP_SWAP:
3622 case ISD::ATOMIC_SWAP:
3623 case ISD::ATOMIC_LOAD_ADD:
3624 case ISD::ATOMIC_LOAD_SUB:
3625 case ISD::ATOMIC_LOAD_AND:
3626 case ISD::ATOMIC_LOAD_CLR:
3627 case ISD::ATOMIC_LOAD_OR:
3628 case ISD::ATOMIC_LOAD_XOR:
3629 case ISD::ATOMIC_LOAD_NAND:
3630 case ISD::ATOMIC_LOAD_MIN:
3631 case ISD::ATOMIC_LOAD_MAX:
3632 case ISD::ATOMIC_LOAD_UMIN:
3633 case ISD::ATOMIC_LOAD_UMAX:
3634 case ISD::ATOMIC_LOAD: {
3635 unsigned MemBits =
3636 cast<AtomicSDNode>(Op)->getMemoryVT().getScalarSizeInBits();
3637 // If we are looking at the loaded value.
3638 if (Op.getResNo() == 0) {
3639 if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND)
3640 Known.Zero.setBitsFrom(MemBits);
3642 break;
3644 case ISD::FrameIndex:
3645 case ISD::TargetFrameIndex:
3646 TLI->computeKnownBitsForFrameIndex(cast<FrameIndexSDNode>(Op)->getIndex(),
3647 Known, getMachineFunction());
3648 break;
3650 default:
3651 if (Opcode < ISD::BUILTIN_OP_END)
3652 break;
3653 LLVM_FALLTHROUGH;
3654 case ISD::INTRINSIC_WO_CHAIN:
3655 case ISD::INTRINSIC_W_CHAIN:
3656 case ISD::INTRINSIC_VOID:
3657 // Allow the target to implement this method for its nodes.
3658 TLI->computeKnownBitsForTargetNode(Op, Known, DemandedElts, *this, Depth);
3659 break;
3662 assert(!Known.hasConflict() && "Bits known to be one AND zero?");
3663 return Known;
3666 SelectionDAG::OverflowKind SelectionDAG::computeOverflowKind(SDValue N0,
3667 SDValue N1) const {
3668 // X + 0 never overflow
3669 if (isNullConstant(N1))
3670 return OFK_Never;
3672 KnownBits N1Known = computeKnownBits(N1);
3673 if (N1Known.Zero.getBoolValue()) {
3674 KnownBits N0Known = computeKnownBits(N0);
3676 bool overflow;
3677 (void)N0Known.getMaxValue().uadd_ov(N1Known.getMaxValue(), overflow);
3678 if (!overflow)
3679 return OFK_Never;
3682 // mulhi + 1 never overflow
3683 if (N0.getOpcode() == ISD::UMUL_LOHI && N0.getResNo() == 1 &&
3684 (N1Known.getMaxValue() & 0x01) == N1Known.getMaxValue())
3685 return OFK_Never;
3687 if (N1.getOpcode() == ISD::UMUL_LOHI && N1.getResNo() == 1) {
3688 KnownBits N0Known = computeKnownBits(N0);
3690 if ((N0Known.getMaxValue() & 0x01) == N0Known.getMaxValue())
3691 return OFK_Never;
3694 return OFK_Sometime;
3697 bool SelectionDAG::isKnownToBeAPowerOfTwo(SDValue Val) const {
3698 EVT OpVT = Val.getValueType();
3699 unsigned BitWidth = OpVT.getScalarSizeInBits();
3701 // Is the constant a known power of 2?
3702 if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Val))
3703 return Const->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
3705 // A left-shift of a constant one will have exactly one bit set because
3706 // shifting the bit off the end is undefined.
3707 if (Val.getOpcode() == ISD::SHL) {
3708 auto *C = isConstOrConstSplat(Val.getOperand(0));
3709 if (C && C->getAPIntValue() == 1)
3710 return true;
3713 // Similarly, a logical right-shift of a constant sign-bit will have exactly
3714 // one bit set.
3715 if (Val.getOpcode() == ISD::SRL) {
3716 auto *C = isConstOrConstSplat(Val.getOperand(0));
3717 if (C && C->getAPIntValue().isSignMask())
3718 return true;
3721 // Are all operands of a build vector constant powers of two?
3722 if (Val.getOpcode() == ISD::BUILD_VECTOR)
3723 if (llvm::all_of(Val->ops(), [BitWidth](SDValue E) {
3724 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(E))
3725 return C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
3726 return false;
3728 return true;
3730 // Is the operand of a splat vector a constant power of two?
3731 if (Val.getOpcode() == ISD::SPLAT_VECTOR)
3732 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val->getOperand(0)))
3733 if (C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2())
3734 return true;
3736 // More could be done here, though the above checks are enough
3737 // to handle some common cases.
3739 // Fall back to computeKnownBits to catch other known cases.
3740 KnownBits Known = computeKnownBits(Val);
3741 return (Known.countMaxPopulation() == 1) && (Known.countMinPopulation() == 1);
3744 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const {
3745 EVT VT = Op.getValueType();
3747 // TODO: Assume we don't know anything for now.
3748 if (VT.isScalableVector())
3749 return 1;
3751 APInt DemandedElts = VT.isVector()
3752 ? APInt::getAllOnes(VT.getVectorNumElements())
3753 : APInt(1, 1);
3754 return ComputeNumSignBits(Op, DemandedElts, Depth);
3757 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, const APInt &DemandedElts,
3758 unsigned Depth) const {
3759 EVT VT = Op.getValueType();
3760 assert((VT.isInteger() || VT.isFloatingPoint()) && "Invalid VT!");
3761 unsigned VTBits = VT.getScalarSizeInBits();
3762 unsigned NumElts = DemandedElts.getBitWidth();
3763 unsigned Tmp, Tmp2;
3764 unsigned FirstAnswer = 1;
3766 if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
3767 const APInt &Val = C->getAPIntValue();
3768 return Val.getNumSignBits();
3771 if (Depth >= MaxRecursionDepth)
3772 return 1; // Limit search depth.
3774 if (!DemandedElts || VT.isScalableVector())
3775 return 1; // No demanded elts, better to assume we don't know anything.
3777 unsigned Opcode = Op.getOpcode();
3778 switch (Opcode) {
3779 default: break;
3780 case ISD::AssertSext:
3781 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
3782 return VTBits-Tmp+1;
3783 case ISD::AssertZext:
3784 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
3785 return VTBits-Tmp;
3787 case ISD::BUILD_VECTOR:
3788 Tmp = VTBits;
3789 for (unsigned i = 0, e = Op.getNumOperands(); (i < e) && (Tmp > 1); ++i) {
3790 if (!DemandedElts[i])
3791 continue;
3793 SDValue SrcOp = Op.getOperand(i);
3794 Tmp2 = ComputeNumSignBits(SrcOp, Depth + 1);
3796 // BUILD_VECTOR can implicitly truncate sources, we must handle this.
3797 if (SrcOp.getValueSizeInBits() != VTBits) {
3798 assert(SrcOp.getValueSizeInBits() > VTBits &&
3799 "Expected BUILD_VECTOR implicit truncation");
3800 unsigned ExtraBits = SrcOp.getValueSizeInBits() - VTBits;
3801 Tmp2 = (Tmp2 > ExtraBits ? Tmp2 - ExtraBits : 1);
3803 Tmp = std::min(Tmp, Tmp2);
3805 return Tmp;
3807 case ISD::VECTOR_SHUFFLE: {
3808 // Collect the minimum number of sign bits that are shared by every vector
3809 // element referenced by the shuffle.
3810 APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
3811 const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
3812 assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
3813 for (unsigned i = 0; i != NumElts; ++i) {
3814 int M = SVN->getMaskElt(i);
3815 if (!DemandedElts[i])
3816 continue;
3817 // For UNDEF elements, we don't know anything about the common state of
3818 // the shuffle result.
3819 if (M < 0)
3820 return 1;
3821 if ((unsigned)M < NumElts)
3822 DemandedLHS.setBit((unsigned)M % NumElts);
3823 else
3824 DemandedRHS.setBit((unsigned)M % NumElts);
3826 Tmp = std::numeric_limits<unsigned>::max();
3827 if (!!DemandedLHS)
3828 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedLHS, Depth + 1);
3829 if (!!DemandedRHS) {
3830 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedRHS, Depth + 1);
3831 Tmp = std::min(Tmp, Tmp2);
3833 // If we don't know anything, early out and try computeKnownBits fall-back.
3834 if (Tmp == 1)
3835 break;
3836 assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
3837 return Tmp;
3840 case ISD::BITCAST: {
3841 SDValue N0 = Op.getOperand(0);
3842 EVT SrcVT = N0.getValueType();
3843 unsigned SrcBits = SrcVT.getScalarSizeInBits();
3845 // Ignore bitcasts from unsupported types..
3846 if (!(SrcVT.isInteger() || SrcVT.isFloatingPoint()))
3847 break;
3849 // Fast handling of 'identity' bitcasts.
3850 if (VTBits == SrcBits)
3851 return ComputeNumSignBits(N0, DemandedElts, Depth + 1);
3853 bool IsLE = getDataLayout().isLittleEndian();
3855 // Bitcast 'large element' scalar/vector to 'small element' vector.
3856 if ((SrcBits % VTBits) == 0) {
3857 assert(VT.isVector() && "Expected bitcast to vector");
3859 unsigned Scale = SrcBits / VTBits;
3860 APInt SrcDemandedElts =
3861 APIntOps::ScaleBitMask(DemandedElts, NumElts / Scale);
3863 // Fast case - sign splat can be simply split across the small elements.
3864 Tmp = ComputeNumSignBits(N0, SrcDemandedElts, Depth + 1);
3865 if (Tmp == SrcBits)
3866 return VTBits;
3868 // Slow case - determine how far the sign extends into each sub-element.
3869 Tmp2 = VTBits;
3870 for (unsigned i = 0; i != NumElts; ++i)
3871 if (DemandedElts[i]) {
3872 unsigned SubOffset = i % Scale;
3873 SubOffset = (IsLE ? ((Scale - 1) - SubOffset) : SubOffset);
3874 SubOffset = SubOffset * VTBits;
3875 if (Tmp <= SubOffset)
3876 return 1;
3877 Tmp2 = std::min(Tmp2, Tmp - SubOffset);
3879 return Tmp2;
3881 break;
3884 case ISD::FP_TO_SINT_SAT:
3885 // FP_TO_SINT_SAT produces a signed value that fits in the saturating VT.
3886 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
3887 return VTBits - Tmp + 1;
3888 case ISD::SIGN_EXTEND:
3889 Tmp = VTBits - Op.getOperand(0).getScalarValueSizeInBits();
3890 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1) + Tmp;
3891 case ISD::SIGN_EXTEND_INREG:
3892 // Max of the input and what this extends.
3893 Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
3894 Tmp = VTBits-Tmp+1;
3895 Tmp2 = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
3896 return std::max(Tmp, Tmp2);
3897 case ISD::SIGN_EXTEND_VECTOR_INREG: {
3898 SDValue Src = Op.getOperand(0);
3899 EVT SrcVT = Src.getValueType();
3900 APInt DemandedSrcElts = DemandedElts.zextOrSelf(SrcVT.getVectorNumElements());
3901 Tmp = VTBits - SrcVT.getScalarSizeInBits();
3902 return ComputeNumSignBits(Src, DemandedSrcElts, Depth+1) + Tmp;
3904 case ISD::SRA:
3905 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3906 // SRA X, C -> adds C sign bits.
3907 if (const APInt *ShAmt =
3908 getValidMinimumShiftAmountConstant(Op, DemandedElts))
3909 Tmp = std::min<uint64_t>(Tmp + ShAmt->getZExtValue(), VTBits);
3910 return Tmp;
3911 case ISD::SHL:
3912 if (const APInt *ShAmt =
3913 getValidMaximumShiftAmountConstant(Op, DemandedElts)) {
3914 // shl destroys sign bits, ensure it doesn't shift out all sign bits.
3915 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3916 if (ShAmt->ult(Tmp))
3917 return Tmp - ShAmt->getZExtValue();
3919 break;
3920 case ISD::AND:
3921 case ISD::OR:
3922 case ISD::XOR: // NOT is handled here.
3923 // Logical binary ops preserve the number of sign bits at the worst.
3924 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
3925 if (Tmp != 1) {
3926 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
3927 FirstAnswer = std::min(Tmp, Tmp2);
3928 // We computed what we know about the sign bits as our first
3929 // answer. Now proceed to the generic code that uses
3930 // computeKnownBits, and pick whichever answer is better.
3932 break;
3934 case ISD::SELECT:
3935 case ISD::VSELECT:
3936 Tmp = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
3937 if (Tmp == 1) return 1; // Early out.
3938 Tmp2 = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
3939 return std::min(Tmp, Tmp2);
3940 case ISD::SELECT_CC:
3941 Tmp = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
3942 if (Tmp == 1) return 1; // Early out.
3943 Tmp2 = ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth+1);
3944 return std::min(Tmp, Tmp2);
3946 case ISD::SMIN:
3947 case ISD::SMAX: {
3948 // If we have a clamp pattern, we know that the number of sign bits will be
3949 // the minimum of the clamp min/max range.
3950 bool IsMax = (Opcode == ISD::SMAX);
3951 ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
3952 if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
3953 if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
3954 CstHigh =
3955 isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
3956 if (CstLow && CstHigh) {
3957 if (!IsMax)
3958 std::swap(CstLow, CstHigh);
3959 if (CstLow->getAPIntValue().sle(CstHigh->getAPIntValue())) {
3960 Tmp = CstLow->getAPIntValue().getNumSignBits();
3961 Tmp2 = CstHigh->getAPIntValue().getNumSignBits();
3962 return std::min(Tmp, Tmp2);
3966 // Fallback - just get the minimum number of sign bits of the operands.
3967 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3968 if (Tmp == 1)
3969 return 1; // Early out.
3970 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
3971 return std::min(Tmp, Tmp2);
3973 case ISD::UMIN:
3974 case ISD::UMAX:
3975 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3976 if (Tmp == 1)
3977 return 1; // Early out.
3978 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
3979 return std::min(Tmp, Tmp2);
3980 case ISD::SADDO:
3981 case ISD::UADDO:
3982 case ISD::SSUBO:
3983 case ISD::USUBO:
3984 case ISD::SMULO:
3985 case ISD::UMULO:
3986 if (Op.getResNo() != 1)
3987 break;
3988 // The boolean result conforms to getBooleanContents. Fall through.
3989 // If setcc returns 0/-1, all bits are sign bits.
3990 // We know that we have an integer-based boolean since these operations
3991 // are only available for integer.
3992 if (TLI->getBooleanContents(VT.isVector(), false) ==
3993 TargetLowering::ZeroOrNegativeOneBooleanContent)
3994 return VTBits;
3995 break;
3996 case ISD::SETCC:
3997 case ISD::STRICT_FSETCC:
3998 case ISD::STRICT_FSETCCS: {
3999 unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
4000 // If setcc returns 0/-1, all bits are sign bits.
4001 if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
4002 TargetLowering::ZeroOrNegativeOneBooleanContent)
4003 return VTBits;
4004 break;
4006 case ISD::ROTL:
4007 case ISD::ROTR:
4008 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4010 // If we're rotating an 0/-1 value, then it stays an 0/-1 value.
4011 if (Tmp == VTBits)
4012 return VTBits;
4014 if (ConstantSDNode *C =
4015 isConstOrConstSplat(Op.getOperand(1), DemandedElts)) {
4016 unsigned RotAmt = C->getAPIntValue().urem(VTBits);
4018 // Handle rotate right by N like a rotate left by 32-N.
4019 if (Opcode == ISD::ROTR)
4020 RotAmt = (VTBits - RotAmt) % VTBits;
4022 // If we aren't rotating out all of the known-in sign bits, return the
4023 // number that are left. This handles rotl(sext(x), 1) for example.
4024 if (Tmp > (RotAmt + 1)) return (Tmp - RotAmt);
4026 break;
4027 case ISD::ADD:
4028 case ISD::ADDC:
4029 // Add can have at most one carry bit. Thus we know that the output
4030 // is, at worst, one more bit than the inputs.
4031 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4032 if (Tmp == 1) return 1; // Early out.
4034 // Special case decrementing a value (ADD X, -1):
4035 if (ConstantSDNode *CRHS =
4036 isConstOrConstSplat(Op.getOperand(1), DemandedElts))
4037 if (CRHS->isAllOnes()) {
4038 KnownBits Known =
4039 computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4041 // If the input is known to be 0 or 1, the output is 0/-1, which is all
4042 // sign bits set.
4043 if ((Known.Zero | 1).isAllOnes())
4044 return VTBits;
4046 // If we are subtracting one from a positive number, there is no carry
4047 // out of the result.
4048 if (Known.isNonNegative())
4049 return Tmp;
4052 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
4053 if (Tmp2 == 1) return 1; // Early out.
4054 return std::min(Tmp, Tmp2) - 1;
4055 case ISD::SUB:
4056 Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
4057 if (Tmp2 == 1) return 1; // Early out.
4059 // Handle NEG.
4060 if (ConstantSDNode *CLHS =
4061 isConstOrConstSplat(Op.getOperand(0), DemandedElts))
4062 if (CLHS->isZero()) {
4063 KnownBits Known =
4064 computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4065 // If the input is known to be 0 or 1, the output is 0/-1, which is all
4066 // sign bits set.
4067 if ((Known.Zero | 1).isAllOnes())
4068 return VTBits;
4070 // If the input is known to be positive (the sign bit is known clear),
4071 // the output of the NEG has the same number of sign bits as the input.
4072 if (Known.isNonNegative())
4073 return Tmp2;
4075 // Otherwise, we treat this like a SUB.
4078 // Sub can have at most one carry bit. Thus we know that the output
4079 // is, at worst, one more bit than the inputs.
4080 Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4081 if (Tmp == 1) return 1; // Early out.
4082 return std::min(Tmp, Tmp2) - 1;
4083 case ISD::MUL: {
4084 // The output of the Mul can be at most twice the valid bits in the inputs.
4085 unsigned SignBitsOp0 = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
4086 if (SignBitsOp0 == 1)
4087 break;
4088 unsigned SignBitsOp1 = ComputeNumSignBits(Op.getOperand(1), Depth + 1);
4089 if (SignBitsOp1 == 1)
4090 break;
4091 unsigned OutValidBits =
4092 (VTBits - SignBitsOp0 + 1) + (VTBits - SignBitsOp1 + 1);
4093 return OutValidBits > VTBits ? 1 : VTBits - OutValidBits + 1;
4095 case ISD::SREM:
4096 // The sign bit is the LHS's sign bit, except when the result of the
4097 // remainder is zero. The magnitude of the result should be less than or
4098 // equal to the magnitude of the LHS. Therefore, the result should have
4099 // at least as many sign bits as the left hand side.
4100 return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4101 case ISD::TRUNCATE: {
4102 // Check if the sign bits of source go down as far as the truncated value.
4103 unsigned NumSrcBits = Op.getOperand(0).getScalarValueSizeInBits();
4104 unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
4105 if (NumSrcSignBits > (NumSrcBits - VTBits))
4106 return NumSrcSignBits - (NumSrcBits - VTBits);
4107 break;
4109 case ISD::EXTRACT_ELEMENT: {
4110 const int KnownSign = ComputeNumSignBits(Op.getOperand(0), Depth+1);
4111 const int BitWidth = Op.getValueSizeInBits();
4112 const int Items = Op.getOperand(0).getValueSizeInBits() / BitWidth;
4114 // Get reverse index (starting from 1), Op1 value indexes elements from
4115 // little end. Sign starts at big end.
4116 const int rIndex = Items - 1 - Op.getConstantOperandVal(1);
4118 // If the sign portion ends in our element the subtraction gives correct
4119 // result. Otherwise it gives either negative or > bitwidth result
4120 return std::max(std::min(KnownSign - rIndex * BitWidth, BitWidth), 0);
4122 case ISD::INSERT_VECTOR_ELT: {
4123 // If we know the element index, split the demand between the
4124 // source vector and the inserted element, otherwise assume we need
4125 // the original demanded vector elements and the value.
4126 SDValue InVec = Op.getOperand(0);
4127 SDValue InVal = Op.getOperand(1);
4128 SDValue EltNo = Op.getOperand(2);
4129 bool DemandedVal = true;
4130 APInt DemandedVecElts = DemandedElts;
4131 auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
4132 if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
4133 unsigned EltIdx = CEltNo->getZExtValue();
4134 DemandedVal = !!DemandedElts[EltIdx];
4135 DemandedVecElts.clearBit(EltIdx);
4137 Tmp = std::numeric_limits<unsigned>::max();
4138 if (DemandedVal) {
4139 // TODO - handle implicit truncation of inserted elements.
4140 if (InVal.getScalarValueSizeInBits() != VTBits)
4141 break;
4142 Tmp2 = ComputeNumSignBits(InVal, Depth + 1);
4143 Tmp = std::min(Tmp, Tmp2);
4145 if (!!DemandedVecElts) {
4146 Tmp2 = ComputeNumSignBits(InVec, DemandedVecElts, Depth + 1);
4147 Tmp = std::min(Tmp, Tmp2);
4149 assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
4150 return Tmp;
4152 case ISD::EXTRACT_VECTOR_ELT: {
4153 SDValue InVec = Op.getOperand(0);
4154 SDValue EltNo = Op.getOperand(1);
4155 EVT VecVT = InVec.getValueType();
4156 // ComputeNumSignBits not yet implemented for scalable vectors.
4157 if (VecVT.isScalableVector())
4158 break;
4159 const unsigned BitWidth = Op.getValueSizeInBits();
4160 const unsigned EltBitWidth = Op.getOperand(0).getScalarValueSizeInBits();
4161 const unsigned NumSrcElts = VecVT.getVectorNumElements();
4163 // If BitWidth > EltBitWidth the value is anyext:ed, and we do not know
4164 // anything about sign bits. But if the sizes match we can derive knowledge
4165 // about sign bits from the vector operand.
4166 if (BitWidth != EltBitWidth)
4167 break;
4169 // If we know the element index, just demand that vector element, else for
4170 // an unknown element index, ignore DemandedElts and demand them all.
4171 APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
4172 auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
4173 if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
4174 DemandedSrcElts =
4175 APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
4177 return ComputeNumSignBits(InVec, DemandedSrcElts, Depth + 1);
4179 case ISD::EXTRACT_SUBVECTOR: {
4180 // Offset the demanded elts by the subvector index.
4181 SDValue Src = Op.getOperand(0);
4182 // Bail until we can represent demanded elements for scalable vectors.
4183 if (Src.getValueType().isScalableVector())
4184 break;
4185 uint64_t Idx = Op.getConstantOperandVal(1);
4186 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
4187 APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
4188 return ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
4190 case ISD::CONCAT_VECTORS: {
4191 // Determine the minimum number of sign bits across all demanded
4192 // elts of the input vectors. Early out if the result is already 1.
4193 Tmp = std::numeric_limits<unsigned>::max();
4194 EVT SubVectorVT = Op.getOperand(0).getValueType();
4195 unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
4196 unsigned NumSubVectors = Op.getNumOperands();
4197 for (unsigned i = 0; (i < NumSubVectors) && (Tmp > 1); ++i) {
4198 APInt DemandedSub =
4199 DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts);
4200 if (!DemandedSub)
4201 continue;
4202 Tmp2 = ComputeNumSignBits(Op.getOperand(i), DemandedSub, Depth + 1);
4203 Tmp = std::min(Tmp, Tmp2);
4205 assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
4206 return Tmp;
4208 case ISD::INSERT_SUBVECTOR: {
4209 // Demand any elements from the subvector and the remainder from the src its
4210 // inserted into.
4211 SDValue Src = Op.getOperand(0);
4212 SDValue Sub = Op.getOperand(1);
4213 uint64_t Idx = Op.getConstantOperandVal(2);
4214 unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
4215 APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
4216 APInt DemandedSrcElts = DemandedElts;
4217 DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx);
4219 Tmp = std::numeric_limits<unsigned>::max();
4220 if (!!DemandedSubElts) {
4221 Tmp = ComputeNumSignBits(Sub, DemandedSubElts, Depth + 1);
4222 if (Tmp == 1)
4223 return 1; // early-out
4225 if (!!DemandedSrcElts) {
4226 Tmp2 = ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
4227 Tmp = std::min(Tmp, Tmp2);
4229 assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
4230 return Tmp;
4232 case ISD::ATOMIC_CMP_SWAP:
4233 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
4234 case ISD::ATOMIC_SWAP:
4235 case ISD::ATOMIC_LOAD_ADD:
4236 case ISD::ATOMIC_LOAD_SUB:
4237 case ISD::ATOMIC_LOAD_AND:
4238 case ISD::ATOMIC_LOAD_CLR:
4239 case ISD::ATOMIC_LOAD_OR:
4240 case ISD::ATOMIC_LOAD_XOR:
4241 case ISD::ATOMIC_LOAD_NAND:
4242 case ISD::ATOMIC_LOAD_MIN:
4243 case ISD::ATOMIC_LOAD_MAX:
4244 case ISD::ATOMIC_LOAD_UMIN:
4245 case ISD::ATOMIC_LOAD_UMAX:
4246 case ISD::ATOMIC_LOAD: {
4247 Tmp = cast<AtomicSDNode>(Op)->getMemoryVT().getScalarSizeInBits();
4248 // If we are looking at the loaded value.
4249 if (Op.getResNo() == 0) {
4250 if (Tmp == VTBits)
4251 return 1; // early-out
4252 if (TLI->getExtendForAtomicOps() == ISD::SIGN_EXTEND)
4253 return VTBits - Tmp + 1;
4254 if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND)
4255 return VTBits - Tmp;
4257 break;
4261 // If we are looking at the loaded value of the SDNode.
4262 if (Op.getResNo() == 0) {
4263 // Handle LOADX separately here. EXTLOAD case will fallthrough.
4264 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
4265 unsigned ExtType = LD->getExtensionType();
4266 switch (ExtType) {
4267 default: break;
4268 case ISD::SEXTLOAD: // e.g. i16->i32 = '17' bits known.
4269 Tmp = LD->getMemoryVT().getScalarSizeInBits();
4270 return VTBits - Tmp + 1;
4271 case ISD::ZEXTLOAD: // e.g. i16->i32 = '16' bits known.
4272 Tmp = LD->getMemoryVT().getScalarSizeInBits();
4273 return VTBits - Tmp;
4274 case ISD::NON_EXTLOAD:
4275 if (const Constant *Cst = TLI->getTargetConstantFromLoad(LD)) {
4276 // We only need to handle vectors - computeKnownBits should handle
4277 // scalar cases.
4278 Type *CstTy = Cst->getType();
4279 if (CstTy->isVectorTy() &&
4280 (NumElts * VTBits) == CstTy->getPrimitiveSizeInBits()) {
4281 Tmp = VTBits;
4282 for (unsigned i = 0; i != NumElts; ++i) {
4283 if (!DemandedElts[i])
4284 continue;
4285 if (Constant *Elt = Cst->getAggregateElement(i)) {
4286 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
4287 const APInt &Value = CInt->getValue();
4288 Tmp = std::min(Tmp, Value.getNumSignBits());
4289 continue;
4291 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
4292 APInt Value = CFP->getValueAPF().bitcastToAPInt();
4293 Tmp = std::min(Tmp, Value.getNumSignBits());
4294 continue;
4297 // Unknown type. Conservatively assume no bits match sign bit.
4298 return 1;
4300 return Tmp;
4303 break;
4308 // Allow the target to implement this method for its nodes.
4309 if (Opcode >= ISD::BUILTIN_OP_END ||
4310 Opcode == ISD::INTRINSIC_WO_CHAIN ||
4311 Opcode == ISD::INTRINSIC_W_CHAIN ||
4312 Opcode == ISD::INTRINSIC_VOID) {
4313 unsigned NumBits =
4314 TLI->ComputeNumSignBitsForTargetNode(Op, DemandedElts, *this, Depth);
4315 if (NumBits > 1)
4316 FirstAnswer = std::max(FirstAnswer, NumBits);
4319 // Finally, if we can prove that the top bits of the result are 0's or 1's,
4320 // use this information.
4321 KnownBits Known = computeKnownBits(Op, DemandedElts, Depth);
4322 return std::max(FirstAnswer, Known.countMinSignBits());
4325 unsigned SelectionDAG::ComputeMaxSignificantBits(SDValue Op,
4326 unsigned Depth) const {
4327 unsigned SignBits = ComputeNumSignBits(Op, Depth);
4328 return Op.getScalarValueSizeInBits() - SignBits + 1;
4331 unsigned SelectionDAG::ComputeMaxSignificantBits(SDValue Op,
4332 const APInt &DemandedElts,
4333 unsigned Depth) const {
4334 unsigned SignBits = ComputeNumSignBits(Op, DemandedElts, Depth);
4335 return Op.getScalarValueSizeInBits() - SignBits + 1;
4338 bool SelectionDAG::isGuaranteedNotToBeUndefOrPoison(SDValue Op, bool PoisonOnly,
4339 unsigned Depth) const {
4340 // Early out for FREEZE.
4341 if (Op.getOpcode() == ISD::FREEZE)
4342 return true;
4344 // TODO: Assume we don't know anything for now.
4345 EVT VT = Op.getValueType();
4346 if (VT.isScalableVector())
4347 return false;
4349 APInt DemandedElts = VT.isVector()
4350 ? APInt::getAllOnes(VT.getVectorNumElements())
4351 : APInt(1, 1);
4352 return isGuaranteedNotToBeUndefOrPoison(Op, DemandedElts, PoisonOnly, Depth);
4355 bool SelectionDAG::isGuaranteedNotToBeUndefOrPoison(SDValue Op,
4356 const APInt &DemandedElts,
4357 bool PoisonOnly,
4358 unsigned Depth) const {
4359 unsigned Opcode = Op.getOpcode();
4361 // Early out for FREEZE.
4362 if (Opcode == ISD::FREEZE)
4363 return true;
4365 if (Depth >= MaxRecursionDepth)
4366 return false; // Limit search depth.
4368 if (isIntOrFPConstant(Op))
4369 return true;
4371 switch (Opcode) {
4372 case ISD::UNDEF:
4373 return PoisonOnly;
4375 case ISD::BUILD_VECTOR:
4376 // NOTE: BUILD_VECTOR has implicit truncation of wider scalar elements -
4377 // this shouldn't affect the result.
4378 for (unsigned i = 0, e = Op.getNumOperands(); i < e; ++i) {
4379 if (!DemandedElts[i])
4380 continue;
4381 if (!isGuaranteedNotToBeUndefOrPoison(Op.getOperand(i), PoisonOnly,
4382 Depth + 1))
4383 return false;
4385 return true;
4387 // TODO: Search for noundef attributes from library functions.
4389 // TODO: Pointers dereferenced by ISD::LOAD/STORE ops are noundef.
4391 default:
4392 // Allow the target to implement this method for its nodes.
4393 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
4394 Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID)
4395 return TLI->isGuaranteedNotToBeUndefOrPoisonForTargetNode(
4396 Op, DemandedElts, *this, PoisonOnly, Depth);
4397 break;
4400 return false;
4403 bool SelectionDAG::isBaseWithConstantOffset(SDValue Op) const {
4404 if ((Op.getOpcode() != ISD::ADD && Op.getOpcode() != ISD::OR) ||
4405 !isa<ConstantSDNode>(Op.getOperand(1)))
4406 return false;
4408 if (Op.getOpcode() == ISD::OR &&
4409 !MaskedValueIsZero(Op.getOperand(0), Op.getConstantOperandAPInt(1)))
4410 return false;
4412 return true;
4415 bool SelectionDAG::isKnownNeverNaN(SDValue Op, bool SNaN, unsigned Depth) const {
4416 // If we're told that NaNs won't happen, assume they won't.
4417 if (getTarget().Options.NoNaNsFPMath || Op->getFlags().hasNoNaNs())
4418 return true;
4420 if (Depth >= MaxRecursionDepth)
4421 return false; // Limit search depth.
4423 // TODO: Handle vectors.
4424 // If the value is a constant, we can obviously see if it is a NaN or not.
4425 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) {
4426 return !C->getValueAPF().isNaN() ||
4427 (SNaN && !C->getValueAPF().isSignaling());
4430 unsigned Opcode = Op.getOpcode();
4431 switch (Opcode) {
4432 case ISD::FADD:
4433 case ISD::FSUB:
4434 case ISD::FMUL:
4435 case ISD::FDIV:
4436 case ISD::FREM:
4437 case ISD::FSIN:
4438 case ISD::FCOS: {
4439 if (SNaN)
4440 return true;
4441 // TODO: Need isKnownNeverInfinity
4442 return false;
4444 case ISD::FCANONICALIZE:
4445 case ISD::FEXP:
4446 case ISD::FEXP2:
4447 case ISD::FTRUNC:
4448 case ISD::FFLOOR:
4449 case ISD::FCEIL:
4450 case ISD::FROUND:
4451 case ISD::FROUNDEVEN:
4452 case ISD::FRINT:
4453 case ISD::FNEARBYINT: {
4454 if (SNaN)
4455 return true;
4456 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4458 case ISD::FABS:
4459 case ISD::FNEG:
4460 case ISD::FCOPYSIGN: {
4461 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4463 case ISD::SELECT:
4464 return isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) &&
4465 isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1);
4466 case ISD::FP_EXTEND:
4467 case ISD::FP_ROUND: {
4468 if (SNaN)
4469 return true;
4470 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4472 case ISD::SINT_TO_FP:
4473 case ISD::UINT_TO_FP:
4474 return true;
4475 case ISD::FMA:
4476 case ISD::FMAD: {
4477 if (SNaN)
4478 return true;
4479 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) &&
4480 isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) &&
4481 isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1);
4483 case ISD::FSQRT: // Need is known positive
4484 case ISD::FLOG:
4485 case ISD::FLOG2:
4486 case ISD::FLOG10:
4487 case ISD::FPOWI:
4488 case ISD::FPOW: {
4489 if (SNaN)
4490 return true;
4491 // TODO: Refine on operand
4492 return false;
4494 case ISD::FMINNUM:
4495 case ISD::FMAXNUM: {
4496 // Only one needs to be known not-nan, since it will be returned if the
4497 // other ends up being one.
4498 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) ||
4499 isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1);
4501 case ISD::FMINNUM_IEEE:
4502 case ISD::FMAXNUM_IEEE: {
4503 if (SNaN)
4504 return true;
4505 // This can return a NaN if either operand is an sNaN, or if both operands
4506 // are NaN.
4507 return (isKnownNeverNaN(Op.getOperand(0), false, Depth + 1) &&
4508 isKnownNeverSNaN(Op.getOperand(1), Depth + 1)) ||
4509 (isKnownNeverNaN(Op.getOperand(1), false, Depth + 1) &&
4510 isKnownNeverSNaN(Op.getOperand(0), Depth + 1));
4512 case ISD::FMINIMUM:
4513 case ISD::FMAXIMUM: {
4514 // TODO: Does this quiet or return the origina NaN as-is?
4515 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) &&
4516 isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1);
4518 case ISD::EXTRACT_VECTOR_ELT: {
4519 return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4521 default:
4522 if (Opcode >= ISD::BUILTIN_OP_END ||
4523 Opcode == ISD::INTRINSIC_WO_CHAIN ||
4524 Opcode == ISD::INTRINSIC_W_CHAIN ||
4525 Opcode == ISD::INTRINSIC_VOID) {
4526 return TLI->isKnownNeverNaNForTargetNode(Op, *this, SNaN, Depth);
4529 return false;
4533 bool SelectionDAG::isKnownNeverZeroFloat(SDValue Op) const {
4534 assert(Op.getValueType().isFloatingPoint() &&
4535 "Floating point type expected");
4537 // If the value is a constant, we can obviously see if it is a zero or not.
4538 // TODO: Add BuildVector support.
4539 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
4540 return !C->isZero();
4541 return false;
4544 bool SelectionDAG::isKnownNeverZero(SDValue Op) const {
4545 assert(!Op.getValueType().isFloatingPoint() &&
4546 "Floating point types unsupported - use isKnownNeverZeroFloat");
4548 // If the value is a constant, we can obviously see if it is a zero or not.
4549 if (ISD::matchUnaryPredicate(Op,
4550 [](ConstantSDNode *C) { return !C->isZero(); }))
4551 return true;
4553 // TODO: Recognize more cases here.
4554 switch (Op.getOpcode()) {
4555 default: break;
4556 case ISD::OR:
4557 if (isKnownNeverZero(Op.getOperand(1)) ||
4558 isKnownNeverZero(Op.getOperand(0)))
4559 return true;
4560 break;
4563 return false;
4566 bool SelectionDAG::isEqualTo(SDValue A, SDValue B) const {
4567 // Check the obvious case.
4568 if (A == B) return true;
4570 // For for negative and positive zero.
4571 if (const ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A))
4572 if (const ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B))
4573 if (CA->isZero() && CB->isZero()) return true;
4575 // Otherwise they may not be equal.
4576 return false;
4579 // FIXME: unify with llvm::haveNoCommonBitsSet.
4580 bool SelectionDAG::haveNoCommonBitsSet(SDValue A, SDValue B) const {
4581 assert(A.getValueType() == B.getValueType() &&
4582 "Values must have the same type");
4583 // Match masked merge pattern (X & ~M) op (Y & M)
4584 if (A->getOpcode() == ISD::AND && B->getOpcode() == ISD::AND) {
4585 auto MatchNoCommonBitsPattern = [&](SDValue NotM, SDValue And) {
4586 if (isBitwiseNot(NotM, true)) {
4587 SDValue NotOperand = NotM->getOperand(0);
4588 return NotOperand == And->getOperand(0) ||
4589 NotOperand == And->getOperand(1);
4591 return false;
4593 if (MatchNoCommonBitsPattern(A->getOperand(0), B) ||
4594 MatchNoCommonBitsPattern(A->getOperand(1), B) ||
4595 MatchNoCommonBitsPattern(B->getOperand(0), A) ||
4596 MatchNoCommonBitsPattern(B->getOperand(1), A))
4597 return true;
4599 return KnownBits::haveNoCommonBitsSet(computeKnownBits(A),
4600 computeKnownBits(B));
4603 static SDValue FoldSTEP_VECTOR(const SDLoc &DL, EVT VT, SDValue Step,
4604 SelectionDAG &DAG) {
4605 if (cast<ConstantSDNode>(Step)->isZero())
4606 return DAG.getConstant(0, DL, VT);
4608 return SDValue();
4611 static SDValue FoldBUILD_VECTOR(const SDLoc &DL, EVT VT,
4612 ArrayRef<SDValue> Ops,
4613 SelectionDAG &DAG) {
4614 int NumOps = Ops.size();
4615 assert(NumOps != 0 && "Can't build an empty vector!");
4616 assert(!VT.isScalableVector() &&
4617 "BUILD_VECTOR cannot be used with scalable types");
4618 assert(VT.getVectorNumElements() == (unsigned)NumOps &&
4619 "Incorrect element count in BUILD_VECTOR!");
4621 // BUILD_VECTOR of UNDEFs is UNDEF.
4622 if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
4623 return DAG.getUNDEF(VT);
4625 // BUILD_VECTOR of seq extract/insert from the same vector + type is Identity.
4626 SDValue IdentitySrc;
4627 bool IsIdentity = true;
4628 for (int i = 0; i != NumOps; ++i) {
4629 if (Ops[i].getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4630 Ops[i].getOperand(0).getValueType() != VT ||
4631 (IdentitySrc && Ops[i].getOperand(0) != IdentitySrc) ||
4632 !isa<ConstantSDNode>(Ops[i].getOperand(1)) ||
4633 cast<ConstantSDNode>(Ops[i].getOperand(1))->getAPIntValue() != i) {
4634 IsIdentity = false;
4635 break;
4637 IdentitySrc = Ops[i].getOperand(0);
4639 if (IsIdentity)
4640 return IdentitySrc;
4642 return SDValue();
4645 /// Try to simplify vector concatenation to an input value, undef, or build
4646 /// vector.
4647 static SDValue foldCONCAT_VECTORS(const SDLoc &DL, EVT VT,
4648 ArrayRef<SDValue> Ops,
4649 SelectionDAG &DAG) {
4650 assert(!Ops.empty() && "Can't concatenate an empty list of vectors!");
4651 assert(llvm::all_of(Ops,
4652 [Ops](SDValue Op) {
4653 return Ops[0].getValueType() == Op.getValueType();
4654 }) &&
4655 "Concatenation of vectors with inconsistent value types!");
4656 assert((Ops[0].getValueType().getVectorElementCount() * Ops.size()) ==
4657 VT.getVectorElementCount() &&
4658 "Incorrect element count in vector concatenation!");
4660 if (Ops.size() == 1)
4661 return Ops[0];
4663 // Concat of UNDEFs is UNDEF.
4664 if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
4665 return DAG.getUNDEF(VT);
4667 // Scan the operands and look for extract operations from a single source
4668 // that correspond to insertion at the same location via this concatenation:
4669 // concat (extract X, 0*subvec_elts), (extract X, 1*subvec_elts), ...
4670 SDValue IdentitySrc;
4671 bool IsIdentity = true;
4672 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
4673 SDValue Op = Ops[i];
4674 unsigned IdentityIndex = i * Op.getValueType().getVectorMinNumElements();
4675 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
4676 Op.getOperand(0).getValueType() != VT ||
4677 (IdentitySrc && Op.getOperand(0) != IdentitySrc) ||
4678 Op.getConstantOperandVal(1) != IdentityIndex) {
4679 IsIdentity = false;
4680 break;
4682 assert((!IdentitySrc || IdentitySrc == Op.getOperand(0)) &&
4683 "Unexpected identity source vector for concat of extracts");
4684 IdentitySrc = Op.getOperand(0);
4686 if (IsIdentity) {
4687 assert(IdentitySrc && "Failed to set source vector of extracts");
4688 return IdentitySrc;
4691 // The code below this point is only designed to work for fixed width
4692 // vectors, so we bail out for now.
4693 if (VT.isScalableVector())
4694 return SDValue();
4696 // A CONCAT_VECTOR with all UNDEF/BUILD_VECTOR operands can be
4697 // simplified to one big BUILD_VECTOR.
4698 // FIXME: Add support for SCALAR_TO_VECTOR as well.
4699 EVT SVT = VT.getScalarType();
4700 SmallVector<SDValue, 16> Elts;
4701 for (SDValue Op : Ops) {
4702 EVT OpVT = Op.getValueType();
4703 if (Op.isUndef())
4704 Elts.append(OpVT.getVectorNumElements(), DAG.getUNDEF(SVT));
4705 else if (Op.getOpcode() == ISD::BUILD_VECTOR)
4706 Elts.append(Op->op_begin(), Op->op_end());
4707 else
4708 return SDValue();
4711 // BUILD_VECTOR requires all inputs to be of the same type, find the
4712 // maximum type and extend them all.
4713 for (SDValue Op : Elts)
4714 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
4716 if (SVT.bitsGT(VT.getScalarType())) {
4717 for (SDValue &Op : Elts) {
4718 if (Op.isUndef())
4719 Op = DAG.getUNDEF(SVT);
4720 else
4721 Op = DAG.getTargetLoweringInfo().isZExtFree(Op.getValueType(), SVT)
4722 ? DAG.getZExtOrTrunc(Op, DL, SVT)
4723 : DAG.getSExtOrTrunc(Op, DL, SVT);
4727 SDValue V = DAG.getBuildVector(VT, DL, Elts);
4728 NewSDValueDbgMsg(V, "New node fold concat vectors: ", &DAG);
4729 return V;
4732 /// Gets or creates the specified node.
4733 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT) {
4734 FoldingSetNodeID ID;
4735 AddNodeIDNode(ID, Opcode, getVTList(VT), None);
4736 void *IP = nullptr;
4737 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
4738 return SDValue(E, 0);
4740 auto *N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(),
4741 getVTList(VT));
4742 CSEMap.InsertNode(N, IP);
4744 InsertNode(N);
4745 SDValue V = SDValue(N, 0);
4746 NewSDValueDbgMsg(V, "Creating new node: ", this);
4747 return V;
4750 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4751 SDValue Operand) {
4752 SDNodeFlags Flags;
4753 if (Inserter)
4754 Flags = Inserter->getFlags();
4755 return getNode(Opcode, DL, VT, Operand, Flags);
4758 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4759 SDValue Operand, const SDNodeFlags Flags) {
4760 assert(Operand.getOpcode() != ISD::DELETED_NODE &&
4761 "Operand is DELETED_NODE!");
4762 // Constant fold unary operations with an integer constant operand. Even
4763 // opaque constant will be folded, because the folding of unary operations
4764 // doesn't create new constants with different values. Nevertheless, the
4765 // opaque flag is preserved during folding to prevent future folding with
4766 // other constants.
4767 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand)) {
4768 const APInt &Val = C->getAPIntValue();
4769 switch (Opcode) {
4770 default: break;
4771 case ISD::SIGN_EXTEND:
4772 return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
4773 C->isTargetOpcode(), C->isOpaque());
4774 case ISD::TRUNCATE:
4775 if (C->isOpaque())
4776 break;
4777 LLVM_FALLTHROUGH;
4778 case ISD::ZERO_EXTEND:
4779 return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
4780 C->isTargetOpcode(), C->isOpaque());
4781 case ISD::ANY_EXTEND:
4782 // Some targets like RISCV prefer to sign extend some types.
4783 if (TLI->isSExtCheaperThanZExt(Operand.getValueType(), VT))
4784 return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
4785 C->isTargetOpcode(), C->isOpaque());
4786 return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
4787 C->isTargetOpcode(), C->isOpaque());
4788 case ISD::UINT_TO_FP:
4789 case ISD::SINT_TO_FP: {
4790 APFloat apf(EVTToAPFloatSemantics(VT),
4791 APInt::getZero(VT.getSizeInBits()));
4792 (void)apf.convertFromAPInt(Val,
4793 Opcode==ISD::SINT_TO_FP,
4794 APFloat::rmNearestTiesToEven);
4795 return getConstantFP(apf, DL, VT);
4797 case ISD::BITCAST:
4798 if (VT == MVT::f16 && C->getValueType(0) == MVT::i16)
4799 return getConstantFP(APFloat(APFloat::IEEEhalf(), Val), DL, VT);
4800 if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
4801 return getConstantFP(APFloat(APFloat::IEEEsingle(), Val), DL, VT);
4802 if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
4803 return getConstantFP(APFloat(APFloat::IEEEdouble(), Val), DL, VT);
4804 if (VT == MVT::f128 && C->getValueType(0) == MVT::i128)
4805 return getConstantFP(APFloat(APFloat::IEEEquad(), Val), DL, VT);
4806 break;
4807 case ISD::ABS:
4808 return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(),
4809 C->isOpaque());
4810 case ISD::BITREVERSE:
4811 return getConstant(Val.reverseBits(), DL, VT, C->isTargetOpcode(),
4812 C->isOpaque());
4813 case ISD::BSWAP:
4814 return getConstant(Val.byteSwap(), DL, VT, C->isTargetOpcode(),
4815 C->isOpaque());
4816 case ISD::CTPOP:
4817 return getConstant(Val.countPopulation(), DL, VT, C->isTargetOpcode(),
4818 C->isOpaque());
4819 case ISD::CTLZ:
4820 case ISD::CTLZ_ZERO_UNDEF:
4821 return getConstant(Val.countLeadingZeros(), DL, VT, C->isTargetOpcode(),
4822 C->isOpaque());
4823 case ISD::CTTZ:
4824 case ISD::CTTZ_ZERO_UNDEF:
4825 return getConstant(Val.countTrailingZeros(), DL, VT, C->isTargetOpcode(),
4826 C->isOpaque());
4827 case ISD::FP16_TO_FP: {
4828 bool Ignored;
4829 APFloat FPV(APFloat::IEEEhalf(),
4830 (Val.getBitWidth() == 16) ? Val : Val.trunc(16));
4832 // This can return overflow, underflow, or inexact; we don't care.
4833 // FIXME need to be more flexible about rounding mode.
4834 (void)FPV.convert(EVTToAPFloatSemantics(VT),
4835 APFloat::rmNearestTiesToEven, &Ignored);
4836 return getConstantFP(FPV, DL, VT);
4838 case ISD::STEP_VECTOR: {
4839 if (SDValue V = FoldSTEP_VECTOR(DL, VT, Operand, *this))
4840 return V;
4841 break;
4846 // Constant fold unary operations with a floating point constant operand.
4847 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand)) {
4848 APFloat V = C->getValueAPF(); // make copy
4849 switch (Opcode) {
4850 case ISD::FNEG:
4851 V.changeSign();
4852 return getConstantFP(V, DL, VT);
4853 case ISD::FABS:
4854 V.clearSign();
4855 return getConstantFP(V, DL, VT);
4856 case ISD::FCEIL: {
4857 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardPositive);
4858 if (fs == APFloat::opOK || fs == APFloat::opInexact)
4859 return getConstantFP(V, DL, VT);
4860 break;
4862 case ISD::FTRUNC: {
4863 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardZero);
4864 if (fs == APFloat::opOK || fs == APFloat::opInexact)
4865 return getConstantFP(V, DL, VT);
4866 break;
4868 case ISD::FFLOOR: {
4869 APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardNegative);
4870 if (fs == APFloat::opOK || fs == APFloat::opInexact)
4871 return getConstantFP(V, DL, VT);
4872 break;
4874 case ISD::FP_EXTEND: {
4875 bool ignored;
4876 // This can return overflow, underflow, or inexact; we don't care.
4877 // FIXME need to be more flexible about rounding mode.
4878 (void)V.convert(EVTToAPFloatSemantics(VT),
4879 APFloat::rmNearestTiesToEven, &ignored);
4880 return getConstantFP(V, DL, VT);
4882 case ISD::FP_TO_SINT:
4883 case ISD::FP_TO_UINT: {
4884 bool ignored;
4885 APSInt IntVal(VT.getSizeInBits(), Opcode == ISD::FP_TO_UINT);
4886 // FIXME need to be more flexible about rounding mode.
4887 APFloat::opStatus s =
4888 V.convertToInteger(IntVal, APFloat::rmTowardZero, &ignored);
4889 if (s == APFloat::opInvalidOp) // inexact is OK, in fact usual
4890 break;
4891 return getConstant(IntVal, DL, VT);
4893 case ISD::BITCAST:
4894 if (VT == MVT::i16 && C->getValueType(0) == MVT::f16)
4895 return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
4896 if (VT == MVT::i16 && C->getValueType(0) == MVT::bf16)
4897 return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
4898 if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
4899 return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
4900 if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
4901 return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
4902 break;
4903 case ISD::FP_TO_FP16: {
4904 bool Ignored;
4905 // This can return overflow, underflow, or inexact; we don't care.
4906 // FIXME need to be more flexible about rounding mode.
4907 (void)V.convert(APFloat::IEEEhalf(),
4908 APFloat::rmNearestTiesToEven, &Ignored);
4909 return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
4914 // Constant fold unary operations with a vector integer or float operand.
4915 switch (Opcode) {
4916 default:
4917 // FIXME: Entirely reasonable to perform folding of other unary
4918 // operations here as the need arises.
4919 break;
4920 case ISD::FNEG:
4921 case ISD::FABS:
4922 case ISD::FCEIL:
4923 case ISD::FTRUNC:
4924 case ISD::FFLOOR:
4925 case ISD::FP_EXTEND:
4926 case ISD::FP_TO_SINT:
4927 case ISD::FP_TO_UINT:
4928 case ISD::TRUNCATE:
4929 case ISD::ANY_EXTEND:
4930 case ISD::ZERO_EXTEND:
4931 case ISD::SIGN_EXTEND:
4932 case ISD::UINT_TO_FP:
4933 case ISD::SINT_TO_FP:
4934 case ISD::ABS:
4935 case ISD::BITREVERSE:
4936 case ISD::BSWAP:
4937 case ISD::CTLZ:
4938 case ISD::CTLZ_ZERO_UNDEF:
4939 case ISD::CTTZ:
4940 case ISD::CTTZ_ZERO_UNDEF:
4941 case ISD::CTPOP: {
4942 SDValue Ops = {Operand};
4943 if (SDValue Fold = FoldConstantArithmetic(Opcode, DL, VT, Ops))
4944 return Fold;
4948 unsigned OpOpcode = Operand.getNode()->getOpcode();
4949 switch (Opcode) {
4950 case ISD::STEP_VECTOR:
4951 assert(VT.isScalableVector() &&
4952 "STEP_VECTOR can only be used with scalable types");
4953 assert(OpOpcode == ISD::TargetConstant &&
4954 VT.getVectorElementType() == Operand.getValueType() &&
4955 "Unexpected step operand");
4956 break;
4957 case ISD::FREEZE:
4958 assert(VT == Operand.getValueType() && "Unexpected VT!");
4959 break;
4960 case ISD::TokenFactor:
4961 case ISD::MERGE_VALUES:
4962 case ISD::CONCAT_VECTORS:
4963 return Operand; // Factor, merge or concat of one node? No need.
4964 case ISD::BUILD_VECTOR: {
4965 // Attempt to simplify BUILD_VECTOR.
4966 SDValue Ops[] = {Operand};
4967 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
4968 return V;
4969 break;
4971 case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node");
4972 case ISD::FP_EXTEND:
4973 assert(VT.isFloatingPoint() &&
4974 Operand.getValueType().isFloatingPoint() && "Invalid FP cast!");
4975 if (Operand.getValueType() == VT) return Operand; // noop conversion.
4976 assert((!VT.isVector() ||
4977 VT.getVectorElementCount() ==
4978 Operand.getValueType().getVectorElementCount()) &&
4979 "Vector element count mismatch!");
4980 assert(Operand.getValueType().bitsLT(VT) &&
4981 "Invalid fpext node, dst < src!");
4982 if (Operand.isUndef())
4983 return getUNDEF(VT);
4984 break;
4985 case ISD::FP_TO_SINT:
4986 case ISD::FP_TO_UINT:
4987 if (Operand.isUndef())
4988 return getUNDEF(VT);
4989 break;
4990 case ISD::SINT_TO_FP:
4991 case ISD::UINT_TO_FP:
4992 // [us]itofp(undef) = 0, because the result value is bounded.
4993 if (Operand.isUndef())
4994 return getConstantFP(0.0, DL, VT);
4995 break;
4996 case ISD::SIGN_EXTEND:
4997 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
4998 "Invalid SIGN_EXTEND!");
4999 assert(VT.isVector() == Operand.getValueType().isVector() &&
5000 "SIGN_EXTEND result type type should be vector iff the operand "
5001 "type is vector!");
5002 if (Operand.getValueType() == VT) return Operand; // noop extension
5003 assert((!VT.isVector() ||
5004 VT.getVectorElementCount() ==
5005 Operand.getValueType().getVectorElementCount()) &&
5006 "Vector element count mismatch!");
5007 assert(Operand.getValueType().bitsLT(VT) &&
5008 "Invalid sext node, dst < src!");
5009 if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
5010 return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
5011 if (OpOpcode == ISD::UNDEF)
5012 // sext(undef) = 0, because the top bits will all be the same.
5013 return getConstant(0, DL, VT);
5014 break;
5015 case ISD::ZERO_EXTEND:
5016 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
5017 "Invalid ZERO_EXTEND!");
5018 assert(VT.isVector() == Operand.getValueType().isVector() &&
5019 "ZERO_EXTEND result type type should be vector iff the operand "
5020 "type is vector!");
5021 if (Operand.getValueType() == VT) return Operand; // noop extension
5022 assert((!VT.isVector() ||
5023 VT.getVectorElementCount() ==
5024 Operand.getValueType().getVectorElementCount()) &&
5025 "Vector element count mismatch!");
5026 assert(Operand.getValueType().bitsLT(VT) &&
5027 "Invalid zext node, dst < src!");
5028 if (OpOpcode == ISD::ZERO_EXTEND) // (zext (zext x)) -> (zext x)
5029 return getNode(ISD::ZERO_EXTEND, DL, VT, Operand.getOperand(0));
5030 if (OpOpcode == ISD::UNDEF)
5031 // zext(undef) = 0, because the top bits will be zero.
5032 return getConstant(0, DL, VT);
5033 break;
5034 case ISD::ANY_EXTEND:
5035 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
5036 "Invalid ANY_EXTEND!");
5037 assert(VT.isVector() == Operand.getValueType().isVector() &&
5038 "ANY_EXTEND result type type should be vector iff the operand "
5039 "type is vector!");
5040 if (Operand.getValueType() == VT) return Operand; // noop extension
5041 assert((!VT.isVector() ||
5042 VT.getVectorElementCount() ==
5043 Operand.getValueType().getVectorElementCount()) &&
5044 "Vector element count mismatch!");
5045 assert(Operand.getValueType().bitsLT(VT) &&
5046 "Invalid anyext node, dst < src!");
5048 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
5049 OpOpcode == ISD::ANY_EXTEND)
5050 // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x)
5051 return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
5052 if (OpOpcode == ISD::UNDEF)
5053 return getUNDEF(VT);
5055 // (ext (trunc x)) -> x
5056 if (OpOpcode == ISD::TRUNCATE) {
5057 SDValue OpOp = Operand.getOperand(0);
5058 if (OpOp.getValueType() == VT) {
5059 transferDbgValues(Operand, OpOp);
5060 return OpOp;
5063 break;
5064 case ISD::TRUNCATE:
5065 assert(VT.isInteger() && Operand.getValueType().isInteger() &&
5066 "Invalid TRUNCATE!");
5067 assert(VT.isVector() == Operand.getValueType().isVector() &&
5068 "TRUNCATE result type type should be vector iff the operand "
5069 "type is vector!");
5070 if (Operand.getValueType() == VT) return Operand; // noop truncate
5071 assert((!VT.isVector() ||
5072 VT.getVectorElementCount() ==
5073 Operand.getValueType().getVectorElementCount()) &&
5074 "Vector element count mismatch!");
5075 assert(Operand.getValueType().bitsGT(VT) &&
5076 "Invalid truncate node, src < dst!");
5077 if (OpOpcode == ISD::TRUNCATE)
5078 return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0));
5079 if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
5080 OpOpcode == ISD::ANY_EXTEND) {
5081 // If the source is smaller than the dest, we still need an extend.
5082 if (Operand.getOperand(0).getValueType().getScalarType()
5083 .bitsLT(VT.getScalarType()))
5084 return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
5085 if (Operand.getOperand(0).getValueType().bitsGT(VT))
5086 return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0));
5087 return Operand.getOperand(0);
5089 if (OpOpcode == ISD::UNDEF)
5090 return getUNDEF(VT);
5091 if (OpOpcode == ISD::VSCALE && !NewNodesMustHaveLegalTypes)
5092 return getVScale(DL, VT, Operand.getConstantOperandAPInt(0));
5093 break;
5094 case ISD::ANY_EXTEND_VECTOR_INREG:
5095 case ISD::ZERO_EXTEND_VECTOR_INREG:
5096 case ISD::SIGN_EXTEND_VECTOR_INREG:
5097 assert(VT.isVector() && "This DAG node is restricted to vector types.");
5098 assert(Operand.getValueType().bitsLE(VT) &&
5099 "The input must be the same size or smaller than the result.");
5100 assert(VT.getVectorMinNumElements() <
5101 Operand.getValueType().getVectorMinNumElements() &&
5102 "The destination vector type must have fewer lanes than the input.");
5103 break;
5104 case ISD::ABS:
5105 assert(VT.isInteger() && VT == Operand.getValueType() &&
5106 "Invalid ABS!");
5107 if (OpOpcode == ISD::UNDEF)
5108 return getUNDEF(VT);
5109 break;
5110 case ISD::BSWAP:
5111 assert(VT.isInteger() && VT == Operand.getValueType() &&
5112 "Invalid BSWAP!");
5113 assert((VT.getScalarSizeInBits() % 16 == 0) &&
5114 "BSWAP types must be a multiple of 16 bits!");
5115 if (OpOpcode == ISD::UNDEF)
5116 return getUNDEF(VT);
5117 break;
5118 case ISD::BITREVERSE:
5119 assert(VT.isInteger() && VT == Operand.getValueType() &&
5120 "Invalid BITREVERSE!");
5121 if (OpOpcode == ISD::UNDEF)
5122 return getUNDEF(VT);
5123 break;
5124 case ISD::BITCAST:
5125 assert(VT.getSizeInBits() == Operand.getValueSizeInBits() &&
5126 "Cannot BITCAST between types of different sizes!");
5127 if (VT == Operand.getValueType()) return Operand; // noop conversion.
5128 if (OpOpcode == ISD::BITCAST) // bitconv(bitconv(x)) -> bitconv(x)
5129 return getNode(ISD::BITCAST, DL, VT, Operand.getOperand(0));
5130 if (OpOpcode == ISD::UNDEF)
5131 return getUNDEF(VT);
5132 break;
5133 case ISD::SCALAR_TO_VECTOR:
5134 assert(VT.isVector() && !Operand.getValueType().isVector() &&
5135 (VT.getVectorElementType() == Operand.getValueType() ||
5136 (VT.getVectorElementType().isInteger() &&
5137 Operand.getValueType().isInteger() &&
5138 VT.getVectorElementType().bitsLE(Operand.getValueType()))) &&
5139 "Illegal SCALAR_TO_VECTOR node!");
5140 if (OpOpcode == ISD::UNDEF)
5141 return getUNDEF(VT);
5142 // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
5143 if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
5144 isa<ConstantSDNode>(Operand.getOperand(1)) &&
5145 Operand.getConstantOperandVal(1) == 0 &&
5146 Operand.getOperand(0).getValueType() == VT)
5147 return Operand.getOperand(0);
5148 break;
5149 case ISD::FNEG:
5150 // Negation of an unknown bag of bits is still completely undefined.
5151 if (OpOpcode == ISD::UNDEF)
5152 return getUNDEF(VT);
5154 if (OpOpcode == ISD::FNEG) // --X -> X
5155 return Operand.getOperand(0);
5156 break;
5157 case ISD::FABS:
5158 if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X)
5159 return getNode(ISD::FABS, DL, VT, Operand.getOperand(0));
5160 break;
5161 case ISD::VSCALE:
5162 assert(VT == Operand.getValueType() && "Unexpected VT!");
5163 break;
5164 case ISD::CTPOP:
5165 if (Operand.getValueType().getScalarType() == MVT::i1)
5166 return Operand;
5167 break;
5168 case ISD::CTLZ:
5169 case ISD::CTTZ:
5170 if (Operand.getValueType().getScalarType() == MVT::i1)
5171 return getNOT(DL, Operand, Operand.getValueType());
5172 break;
5173 case ISD::VECREDUCE_SMIN:
5174 case ISD::VECREDUCE_UMAX:
5175 if (Operand.getValueType().getScalarType() == MVT::i1)
5176 return getNode(ISD::VECREDUCE_OR, DL, VT, Operand);
5177 break;
5178 case ISD::VECREDUCE_SMAX:
5179 case ISD::VECREDUCE_UMIN:
5180 if (Operand.getValueType().getScalarType() == MVT::i1)
5181 return getNode(ISD::VECREDUCE_AND, DL, VT, Operand);
5182 break;
5185 SDNode *N;
5186 SDVTList VTs = getVTList(VT);
5187 SDValue Ops[] = {Operand};
5188 if (VT != MVT::Glue) { // Don't CSE flag producing nodes
5189 FoldingSetNodeID ID;
5190 AddNodeIDNode(ID, Opcode, VTs, Ops);
5191 void *IP = nullptr;
5192 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
5193 E->intersectFlagsWith(Flags);
5194 return SDValue(E, 0);
5197 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5198 N->setFlags(Flags);
5199 createOperands(N, Ops);
5200 CSEMap.InsertNode(N, IP);
5201 } else {
5202 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5203 createOperands(N, Ops);
5206 InsertNode(N);
5207 SDValue V = SDValue(N, 0);
5208 NewSDValueDbgMsg(V, "Creating new node: ", this);
5209 return V;
5212 static llvm::Optional<APInt> FoldValue(unsigned Opcode, const APInt &C1,
5213 const APInt &C2) {
5214 switch (Opcode) {
5215 case ISD::ADD: return C1 + C2;
5216 case ISD::SUB: return C1 - C2;
5217 case ISD::MUL: return C1 * C2;
5218 case ISD::AND: return C1 & C2;
5219 case ISD::OR: return C1 | C2;
5220 case ISD::XOR: return C1 ^ C2;
5221 case ISD::SHL: return C1 << C2;
5222 case ISD::SRL: return C1.lshr(C2);
5223 case ISD::SRA: return C1.ashr(C2);
5224 case ISD::ROTL: return C1.rotl(C2);
5225 case ISD::ROTR: return C1.rotr(C2);
5226 case ISD::SMIN: return C1.sle(C2) ? C1 : C2;
5227 case ISD::SMAX: return C1.sge(C2) ? C1 : C2;
5228 case ISD::UMIN: return C1.ule(C2) ? C1 : C2;
5229 case ISD::UMAX: return C1.uge(C2) ? C1 : C2;
5230 case ISD::SADDSAT: return C1.sadd_sat(C2);
5231 case ISD::UADDSAT: return C1.uadd_sat(C2);
5232 case ISD::SSUBSAT: return C1.ssub_sat(C2);
5233 case ISD::USUBSAT: return C1.usub_sat(C2);
5234 case ISD::UDIV:
5235 if (!C2.getBoolValue())
5236 break;
5237 return C1.udiv(C2);
5238 case ISD::UREM:
5239 if (!C2.getBoolValue())
5240 break;
5241 return C1.urem(C2);
5242 case ISD::SDIV:
5243 if (!C2.getBoolValue())
5244 break;
5245 return C1.sdiv(C2);
5246 case ISD::SREM:
5247 if (!C2.getBoolValue())
5248 break;
5249 return C1.srem(C2);
5250 case ISD::MULHS: {
5251 unsigned FullWidth = C1.getBitWidth() * 2;
5252 APInt C1Ext = C1.sext(FullWidth);
5253 APInt C2Ext = C2.sext(FullWidth);
5254 return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth());
5256 case ISD::MULHU: {
5257 unsigned FullWidth = C1.getBitWidth() * 2;
5258 APInt C1Ext = C1.zext(FullWidth);
5259 APInt C2Ext = C2.zext(FullWidth);
5260 return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth());
5263 return llvm::None;
5266 SDValue SelectionDAG::FoldSymbolOffset(unsigned Opcode, EVT VT,
5267 const GlobalAddressSDNode *GA,
5268 const SDNode *N2) {
5269 if (GA->getOpcode() != ISD::GlobalAddress)
5270 return SDValue();
5271 if (!TLI->isOffsetFoldingLegal(GA))
5272 return SDValue();
5273 auto *C2 = dyn_cast<ConstantSDNode>(N2);
5274 if (!C2)
5275 return SDValue();
5276 int64_t Offset = C2->getSExtValue();
5277 switch (Opcode) {
5278 case ISD::ADD: break;
5279 case ISD::SUB: Offset = -uint64_t(Offset); break;
5280 default: return SDValue();
5282 return getGlobalAddress(GA->getGlobal(), SDLoc(C2), VT,
5283 GA->getOffset() + uint64_t(Offset));
5286 bool SelectionDAG::isUndef(unsigned Opcode, ArrayRef<SDValue> Ops) {
5287 switch (Opcode) {
5288 case ISD::SDIV:
5289 case ISD::UDIV:
5290 case ISD::SREM:
5291 case ISD::UREM: {
5292 // If a divisor is zero/undef or any element of a divisor vector is
5293 // zero/undef, the whole op is undef.
5294 assert(Ops.size() == 2 && "Div/rem should have 2 operands");
5295 SDValue Divisor = Ops[1];
5296 if (Divisor.isUndef() || isNullConstant(Divisor))
5297 return true;
5299 return ISD::isBuildVectorOfConstantSDNodes(Divisor.getNode()) &&
5300 llvm::any_of(Divisor->op_values(),
5301 [](SDValue V) { return V.isUndef() ||
5302 isNullConstant(V); });
5303 // TODO: Handle signed overflow.
5305 // TODO: Handle oversized shifts.
5306 default:
5307 return false;
5311 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL,
5312 EVT VT, ArrayRef<SDValue> Ops) {
5313 // If the opcode is a target-specific ISD node, there's nothing we can
5314 // do here and the operand rules may not line up with the below, so
5315 // bail early.
5316 // We can't create a scalar CONCAT_VECTORS so skip it. It will break
5317 // for concats involving SPLAT_VECTOR. Concats of BUILD_VECTORS are handled by
5318 // foldCONCAT_VECTORS in getNode before this is called.
5319 if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::CONCAT_VECTORS)
5320 return SDValue();
5322 unsigned NumOps = Ops.size();
5323 if (NumOps == 0)
5324 return SDValue();
5326 if (isUndef(Opcode, Ops))
5327 return getUNDEF(VT);
5329 // Handle binops special cases.
5330 if (NumOps == 2) {
5331 if (SDValue CFP = foldConstantFPMath(Opcode, DL, VT, Ops[0], Ops[1]))
5332 return CFP;
5334 if (auto *C1 = dyn_cast<ConstantSDNode>(Ops[0])) {
5335 if (auto *C2 = dyn_cast<ConstantSDNode>(Ops[1])) {
5336 if (C1->isOpaque() || C2->isOpaque())
5337 return SDValue();
5339 Optional<APInt> FoldAttempt =
5340 FoldValue(Opcode, C1->getAPIntValue(), C2->getAPIntValue());
5341 if (!FoldAttempt)
5342 return SDValue();
5344 SDValue Folded = getConstant(FoldAttempt.getValue(), DL, VT);
5345 assert((!Folded || !VT.isVector()) &&
5346 "Can't fold vectors ops with scalar operands");
5347 return Folded;
5351 // fold (add Sym, c) -> Sym+c
5352 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ops[0]))
5353 return FoldSymbolOffset(Opcode, VT, GA, Ops[1].getNode());
5354 if (TLI->isCommutativeBinOp(Opcode))
5355 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ops[1]))
5356 return FoldSymbolOffset(Opcode, VT, GA, Ops[0].getNode());
5359 // This is for vector folding only from here on.
5360 if (!VT.isVector())
5361 return SDValue();
5363 ElementCount NumElts = VT.getVectorElementCount();
5365 // See if we can fold through bitcasted integer ops.
5366 // TODO: Can we handle undef elements?
5367 if (NumOps == 2 && VT.isFixedLengthVector() && VT.isInteger() &&
5368 Ops[0].getValueType() == VT && Ops[1].getValueType() == VT &&
5369 Ops[0].getOpcode() == ISD::BITCAST &&
5370 Ops[1].getOpcode() == ISD::BITCAST) {
5371 SDValue N1 = peekThroughBitcasts(Ops[0]);
5372 SDValue N2 = peekThroughBitcasts(Ops[1]);
5373 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
5374 auto *BV2 = dyn_cast<BuildVectorSDNode>(N2);
5375 EVT BVVT = N1.getValueType();
5376 if (BV1 && BV2 && BVVT.isInteger() && BVVT == N2.getValueType()) {
5377 bool IsLE = getDataLayout().isLittleEndian();
5378 unsigned EltBits = VT.getScalarSizeInBits();
5379 SmallVector<APInt> RawBits1, RawBits2;
5380 BitVector UndefElts1, UndefElts2;
5381 if (BV1->getConstantRawBits(IsLE, EltBits, RawBits1, UndefElts1) &&
5382 BV2->getConstantRawBits(IsLE, EltBits, RawBits2, UndefElts2) &&
5383 UndefElts1.none() && UndefElts2.none()) {
5384 SmallVector<APInt> RawBits;
5385 for (unsigned I = 0, E = NumElts.getFixedValue(); I != E; ++I) {
5386 Optional<APInt> Fold = FoldValue(Opcode, RawBits1[I], RawBits2[I]);
5387 if (!Fold)
5388 break;
5389 RawBits.push_back(Fold.getValue());
5391 if (RawBits.size() == NumElts.getFixedValue()) {
5392 // We have constant folded, but we need to cast this again back to
5393 // the original (possibly legalized) type.
5394 SmallVector<APInt> DstBits;
5395 BitVector DstUndefs;
5396 BuildVectorSDNode::recastRawBits(IsLE, BVVT.getScalarSizeInBits(),
5397 DstBits, RawBits, DstUndefs,
5398 BitVector(RawBits.size(), false));
5399 EVT BVEltVT = BV1->getOperand(0).getValueType();
5400 unsigned BVEltBits = BVEltVT.getSizeInBits();
5401 SmallVector<SDValue> Ops(DstBits.size(), getUNDEF(BVEltVT));
5402 for (unsigned I = 0, E = DstBits.size(); I != E; ++I) {
5403 if (DstUndefs[I])
5404 continue;
5405 Ops[I] = getConstant(DstBits[I].sextOrSelf(BVEltBits), DL, BVEltVT);
5407 return getBitcast(VT, getBuildVector(BVVT, DL, Ops));
5413 auto IsScalarOrSameVectorSize = [NumElts](const SDValue &Op) {
5414 return !Op.getValueType().isVector() ||
5415 Op.getValueType().getVectorElementCount() == NumElts;
5418 auto IsBuildVectorSplatVectorOrUndef = [](const SDValue &Op) {
5419 return Op.isUndef() || Op.getOpcode() == ISD::CONDCODE ||
5420 Op.getOpcode() == ISD::BUILD_VECTOR ||
5421 Op.getOpcode() == ISD::SPLAT_VECTOR;
5424 // All operands must be vector types with the same number of elements as
5425 // the result type and must be either UNDEF or a build/splat vector
5426 // or UNDEF scalars.
5427 if (!llvm::all_of(Ops, IsBuildVectorSplatVectorOrUndef) ||
5428 !llvm::all_of(Ops, IsScalarOrSameVectorSize))
5429 return SDValue();
5431 // If we are comparing vectors, then the result needs to be a i1 boolean
5432 // that is then sign-extended back to the legal result type.
5433 EVT SVT = (Opcode == ISD::SETCC ? MVT::i1 : VT.getScalarType());
5435 // Find legal integer scalar type for constant promotion and
5436 // ensure that its scalar size is at least as large as source.
5437 EVT LegalSVT = VT.getScalarType();
5438 if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
5439 LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
5440 if (LegalSVT.bitsLT(VT.getScalarType()))
5441 return SDValue();
5444 // For scalable vector types we know we're dealing with SPLAT_VECTORs. We
5445 // only have one operand to check. For fixed-length vector types we may have
5446 // a combination of BUILD_VECTOR and SPLAT_VECTOR.
5447 unsigned NumVectorElts = NumElts.isScalable() ? 1 : NumElts.getFixedValue();
5449 // Constant fold each scalar lane separately.
5450 SmallVector<SDValue, 4> ScalarResults;
5451 for (unsigned I = 0; I != NumVectorElts; I++) {
5452 SmallVector<SDValue, 4> ScalarOps;
5453 for (SDValue Op : Ops) {
5454 EVT InSVT = Op.getValueType().getScalarType();
5455 if (Op.getOpcode() != ISD::BUILD_VECTOR &&
5456 Op.getOpcode() != ISD::SPLAT_VECTOR) {
5457 if (Op.isUndef())
5458 ScalarOps.push_back(getUNDEF(InSVT));
5459 else
5460 ScalarOps.push_back(Op);
5461 continue;
5464 SDValue ScalarOp =
5465 Op.getOperand(Op.getOpcode() == ISD::SPLAT_VECTOR ? 0 : I);
5466 EVT ScalarVT = ScalarOp.getValueType();
5468 // Build vector (integer) scalar operands may need implicit
5469 // truncation - do this before constant folding.
5470 if (ScalarVT.isInteger() && ScalarVT.bitsGT(InSVT))
5471 ScalarOp = getNode(ISD::TRUNCATE, DL, InSVT, ScalarOp);
5473 ScalarOps.push_back(ScalarOp);
5476 // Constant fold the scalar operands.
5477 SDValue ScalarResult = getNode(Opcode, DL, SVT, ScalarOps);
5479 // Legalize the (integer) scalar constant if necessary.
5480 if (LegalSVT != SVT)
5481 ScalarResult = getNode(ISD::SIGN_EXTEND, DL, LegalSVT, ScalarResult);
5483 // Scalar folding only succeeded if the result is a constant or UNDEF.
5484 if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant &&
5485 ScalarResult.getOpcode() != ISD::ConstantFP)
5486 return SDValue();
5487 ScalarResults.push_back(ScalarResult);
5490 SDValue V = NumElts.isScalable() ? getSplatVector(VT, DL, ScalarResults[0])
5491 : getBuildVector(VT, DL, ScalarResults);
5492 NewSDValueDbgMsg(V, "New node fold constant vector: ", this);
5493 return V;
5496 SDValue SelectionDAG::foldConstantFPMath(unsigned Opcode, const SDLoc &DL,
5497 EVT VT, SDValue N1, SDValue N2) {
5498 // TODO: We don't do any constant folding for strict FP opcodes here, but we
5499 // should. That will require dealing with a potentially non-default
5500 // rounding mode, checking the "opStatus" return value from the APFloat
5501 // math calculations, and possibly other variations.
5502 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1, /*AllowUndefs*/ false);
5503 ConstantFPSDNode *N2CFP = isConstOrConstSplatFP(N2, /*AllowUndefs*/ false);
5504 if (N1CFP && N2CFP) {
5505 APFloat C1 = N1CFP->getValueAPF(); // make copy
5506 const APFloat &C2 = N2CFP->getValueAPF();
5507 switch (Opcode) {
5508 case ISD::FADD:
5509 C1.add(C2, APFloat::rmNearestTiesToEven);
5510 return getConstantFP(C1, DL, VT);
5511 case ISD::FSUB:
5512 C1.subtract(C2, APFloat::rmNearestTiesToEven);
5513 return getConstantFP(C1, DL, VT);
5514 case ISD::FMUL:
5515 C1.multiply(C2, APFloat::rmNearestTiesToEven);
5516 return getConstantFP(C1, DL, VT);
5517 case ISD::FDIV:
5518 C1.divide(C2, APFloat::rmNearestTiesToEven);
5519 return getConstantFP(C1, DL, VT);
5520 case ISD::FREM:
5521 C1.mod(C2);
5522 return getConstantFP(C1, DL, VT);
5523 case ISD::FCOPYSIGN:
5524 C1.copySign(C2);
5525 return getConstantFP(C1, DL, VT);
5526 case ISD::FMINNUM:
5527 return getConstantFP(minnum(C1, C2), DL, VT);
5528 case ISD::FMAXNUM:
5529 return getConstantFP(maxnum(C1, C2), DL, VT);
5530 case ISD::FMINIMUM:
5531 return getConstantFP(minimum(C1, C2), DL, VT);
5532 case ISD::FMAXIMUM:
5533 return getConstantFP(maximum(C1, C2), DL, VT);
5534 default: break;
5537 if (N1CFP && Opcode == ISD::FP_ROUND) {
5538 APFloat C1 = N1CFP->getValueAPF(); // make copy
5539 bool Unused;
5540 // This can return overflow, underflow, or inexact; we don't care.
5541 // FIXME need to be more flexible about rounding mode.
5542 (void) C1.convert(EVTToAPFloatSemantics(VT), APFloat::rmNearestTiesToEven,
5543 &Unused);
5544 return getConstantFP(C1, DL, VT);
5547 switch (Opcode) {
5548 case ISD::FSUB:
5549 // -0.0 - undef --> undef (consistent with "fneg undef")
5550 if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1, /*AllowUndefs*/ true))
5551 if (N1C && N1C->getValueAPF().isNegZero() && N2.isUndef())
5552 return getUNDEF(VT);
5553 LLVM_FALLTHROUGH;
5555 case ISD::FADD:
5556 case ISD::FMUL:
5557 case ISD::FDIV:
5558 case ISD::FREM:
5559 // If both operands are undef, the result is undef. If 1 operand is undef,
5560 // the result is NaN. This should match the behavior of the IR optimizer.
5561 if (N1.isUndef() && N2.isUndef())
5562 return getUNDEF(VT);
5563 if (N1.isUndef() || N2.isUndef())
5564 return getConstantFP(APFloat::getNaN(EVTToAPFloatSemantics(VT)), DL, VT);
5566 return SDValue();
5569 SDValue SelectionDAG::getAssertAlign(const SDLoc &DL, SDValue Val, Align A) {
5570 assert(Val.getValueType().isInteger() && "Invalid AssertAlign!");
5572 // There's no need to assert on a byte-aligned pointer. All pointers are at
5573 // least byte aligned.
5574 if (A == Align(1))
5575 return Val;
5577 FoldingSetNodeID ID;
5578 AddNodeIDNode(ID, ISD::AssertAlign, getVTList(Val.getValueType()), {Val});
5579 ID.AddInteger(A.value());
5581 void *IP = nullptr;
5582 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
5583 return SDValue(E, 0);
5585 auto *N = newSDNode<AssertAlignSDNode>(DL.getIROrder(), DL.getDebugLoc(),
5586 Val.getValueType(), A);
5587 createOperands(N, {Val});
5589 CSEMap.InsertNode(N, IP);
5590 InsertNode(N);
5592 SDValue V(N, 0);
5593 NewSDValueDbgMsg(V, "Creating new node: ", this);
5594 return V;
5597 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5598 SDValue N1, SDValue N2) {
5599 SDNodeFlags Flags;
5600 if (Inserter)
5601 Flags = Inserter->getFlags();
5602 return getNode(Opcode, DL, VT, N1, N2, Flags);
5605 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5606 SDValue N1, SDValue N2, const SDNodeFlags Flags) {
5607 assert(N1.getOpcode() != ISD::DELETED_NODE &&
5608 N2.getOpcode() != ISD::DELETED_NODE &&
5609 "Operand is DELETED_NODE!");
5610 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
5611 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
5612 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5613 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
5615 // Canonicalize constant to RHS if commutative.
5616 if (TLI->isCommutativeBinOp(Opcode)) {
5617 if (N1C && !N2C) {
5618 std::swap(N1C, N2C);
5619 std::swap(N1, N2);
5620 } else if (N1CFP && !N2CFP) {
5621 std::swap(N1CFP, N2CFP);
5622 std::swap(N1, N2);
5626 switch (Opcode) {
5627 default: break;
5628 case ISD::TokenFactor:
5629 assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
5630 N2.getValueType() == MVT::Other && "Invalid token factor!");
5631 // Fold trivial token factors.
5632 if (N1.getOpcode() == ISD::EntryToken) return N2;
5633 if (N2.getOpcode() == ISD::EntryToken) return N1;
5634 if (N1 == N2) return N1;
5635 break;
5636 case ISD::BUILD_VECTOR: {
5637 // Attempt to simplify BUILD_VECTOR.
5638 SDValue Ops[] = {N1, N2};
5639 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
5640 return V;
5641 break;
5643 case ISD::CONCAT_VECTORS: {
5644 SDValue Ops[] = {N1, N2};
5645 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
5646 return V;
5647 break;
5649 case ISD::AND:
5650 assert(VT.isInteger() && "This operator does not apply to FP types!");
5651 assert(N1.getValueType() == N2.getValueType() &&
5652 N1.getValueType() == VT && "Binary operator types must match!");
5653 // (X & 0) -> 0. This commonly occurs when legalizing i64 values, so it's
5654 // worth handling here.
5655 if (N2C && N2C->isZero())
5656 return N2;
5657 if (N2C && N2C->isAllOnes()) // X & -1 -> X
5658 return N1;
5659 break;
5660 case ISD::OR:
5661 case ISD::XOR:
5662 case ISD::ADD:
5663 case ISD::SUB:
5664 assert(VT.isInteger() && "This operator does not apply to FP types!");
5665 assert(N1.getValueType() == N2.getValueType() &&
5666 N1.getValueType() == VT && "Binary operator types must match!");
5667 // (X ^|+- 0) -> X. This commonly occurs when legalizing i64 values, so
5668 // it's worth handling here.
5669 if (N2C && N2C->isZero())
5670 return N1;
5671 if ((Opcode == ISD::ADD || Opcode == ISD::SUB) && VT.isVector() &&
5672 VT.getVectorElementType() == MVT::i1)
5673 return getNode(ISD::XOR, DL, VT, N1, N2);
5674 break;
5675 case ISD::MUL:
5676 assert(VT.isInteger() && "This operator does not apply to FP types!");
5677 assert(N1.getValueType() == N2.getValueType() &&
5678 N1.getValueType() == VT && "Binary operator types must match!");
5679 if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
5680 return getNode(ISD::AND, DL, VT, N1, N2);
5681 if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
5682 const APInt &MulImm = N1->getConstantOperandAPInt(0);
5683 const APInt &N2CImm = N2C->getAPIntValue();
5684 return getVScale(DL, VT, MulImm * N2CImm);
5686 break;
5687 case ISD::UDIV:
5688 case ISD::UREM:
5689 case ISD::MULHU:
5690 case ISD::MULHS:
5691 case ISD::SDIV:
5692 case ISD::SREM:
5693 case ISD::SADDSAT:
5694 case ISD::SSUBSAT:
5695 case ISD::UADDSAT:
5696 case ISD::USUBSAT:
5697 assert(VT.isInteger() && "This operator does not apply to FP types!");
5698 assert(N1.getValueType() == N2.getValueType() &&
5699 N1.getValueType() == VT && "Binary operator types must match!");
5700 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) {
5701 // fold (add_sat x, y) -> (or x, y) for bool types.
5702 if (Opcode == ISD::SADDSAT || Opcode == ISD::UADDSAT)
5703 return getNode(ISD::OR, DL, VT, N1, N2);
5704 // fold (sub_sat x, y) -> (and x, ~y) for bool types.
5705 if (Opcode == ISD::SSUBSAT || Opcode == ISD::USUBSAT)
5706 return getNode(ISD::AND, DL, VT, N1, getNOT(DL, N2, VT));
5708 break;
5709 case ISD::SMIN:
5710 case ISD::UMAX:
5711 assert(VT.isInteger() && "This operator does not apply to FP types!");
5712 assert(N1.getValueType() == N2.getValueType() &&
5713 N1.getValueType() == VT && "Binary operator types must match!");
5714 if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
5715 return getNode(ISD::OR, DL, VT, N1, N2);
5716 break;
5717 case ISD::SMAX:
5718 case ISD::UMIN:
5719 assert(VT.isInteger() && "This operator does not apply to FP types!");
5720 assert(N1.getValueType() == N2.getValueType() &&
5721 N1.getValueType() == VT && "Binary operator types must match!");
5722 if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
5723 return getNode(ISD::AND, DL, VT, N1, N2);
5724 break;
5725 case ISD::FADD:
5726 case ISD::FSUB:
5727 case ISD::FMUL:
5728 case ISD::FDIV:
5729 case ISD::FREM:
5730 assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
5731 assert(N1.getValueType() == N2.getValueType() &&
5732 N1.getValueType() == VT && "Binary operator types must match!");
5733 if (SDValue V = simplifyFPBinop(Opcode, N1, N2, Flags))
5734 return V;
5735 break;
5736 case ISD::FCOPYSIGN: // N1 and result must match. N1/N2 need not match.
5737 assert(N1.getValueType() == VT &&
5738 N1.getValueType().isFloatingPoint() &&
5739 N2.getValueType().isFloatingPoint() &&
5740 "Invalid FCOPYSIGN!");
5741 break;
5742 case ISD::SHL:
5743 if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
5744 const APInt &MulImm = N1->getConstantOperandAPInt(0);
5745 const APInt &ShiftImm = N2C->getAPIntValue();
5746 return getVScale(DL, VT, MulImm << ShiftImm);
5748 LLVM_FALLTHROUGH;
5749 case ISD::SRA:
5750 case ISD::SRL:
5751 if (SDValue V = simplifyShift(N1, N2))
5752 return V;
5753 LLVM_FALLTHROUGH;
5754 case ISD::ROTL:
5755 case ISD::ROTR:
5756 assert(VT == N1.getValueType() &&
5757 "Shift operators return type must be the same as their first arg");
5758 assert(VT.isInteger() && N2.getValueType().isInteger() &&
5759 "Shifts only work on integers");
5760 assert((!VT.isVector() || VT == N2.getValueType()) &&
5761 "Vector shift amounts must be in the same as their first arg");
5762 // Verify that the shift amount VT is big enough to hold valid shift
5763 // amounts. This catches things like trying to shift an i1024 value by an
5764 // i8, which is easy to fall into in generic code that uses
5765 // TLI.getShiftAmount().
5766 assert(N2.getValueType().getScalarSizeInBits() >=
5767 Log2_32_Ceil(VT.getScalarSizeInBits()) &&
5768 "Invalid use of small shift amount with oversized value!");
5770 // Always fold shifts of i1 values so the code generator doesn't need to
5771 // handle them. Since we know the size of the shift has to be less than the
5772 // size of the value, the shift/rotate count is guaranteed to be zero.
5773 if (VT == MVT::i1)
5774 return N1;
5775 if (N2C && N2C->isZero())
5776 return N1;
5777 break;
5778 case ISD::FP_ROUND:
5779 assert(VT.isFloatingPoint() &&
5780 N1.getValueType().isFloatingPoint() &&
5781 VT.bitsLE(N1.getValueType()) &&
5782 N2C && (N2C->getZExtValue() == 0 || N2C->getZExtValue() == 1) &&
5783 "Invalid FP_ROUND!");
5784 if (N1.getValueType() == VT) return N1; // noop conversion.
5785 break;
5786 case ISD::AssertSext:
5787 case ISD::AssertZext: {
5788 EVT EVT = cast<VTSDNode>(N2)->getVT();
5789 assert(VT == N1.getValueType() && "Not an inreg extend!");
5790 assert(VT.isInteger() && EVT.isInteger() &&
5791 "Cannot *_EXTEND_INREG FP types");
5792 assert(!EVT.isVector() &&
5793 "AssertSExt/AssertZExt type should be the vector element type "
5794 "rather than the vector type!");
5795 assert(EVT.bitsLE(VT.getScalarType()) && "Not extending!");
5796 if (VT.getScalarType() == EVT) return N1; // noop assertion.
5797 break;
5799 case ISD::SIGN_EXTEND_INREG: {
5800 EVT EVT = cast<VTSDNode>(N2)->getVT();
5801 assert(VT == N1.getValueType() && "Not an inreg extend!");
5802 assert(VT.isInteger() && EVT.isInteger() &&
5803 "Cannot *_EXTEND_INREG FP types");
5804 assert(EVT.isVector() == VT.isVector() &&
5805 "SIGN_EXTEND_INREG type should be vector iff the operand "
5806 "type is vector!");
5807 assert((!EVT.isVector() ||
5808 EVT.getVectorElementCount() == VT.getVectorElementCount()) &&
5809 "Vector element counts must match in SIGN_EXTEND_INREG");
5810 assert(EVT.bitsLE(VT) && "Not extending!");
5811 if (EVT == VT) return N1; // Not actually extending
5813 auto SignExtendInReg = [&](APInt Val, llvm::EVT ConstantVT) {
5814 unsigned FromBits = EVT.getScalarSizeInBits();
5815 Val <<= Val.getBitWidth() - FromBits;
5816 Val.ashrInPlace(Val.getBitWidth() - FromBits);
5817 return getConstant(Val, DL, ConstantVT);
5820 if (N1C) {
5821 const APInt &Val = N1C->getAPIntValue();
5822 return SignExtendInReg(Val, VT);
5825 if (ISD::isBuildVectorOfConstantSDNodes(N1.getNode())) {
5826 SmallVector<SDValue, 8> Ops;
5827 llvm::EVT OpVT = N1.getOperand(0).getValueType();
5828 for (int i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
5829 SDValue Op = N1.getOperand(i);
5830 if (Op.isUndef()) {
5831 Ops.push_back(getUNDEF(OpVT));
5832 continue;
5834 ConstantSDNode *C = cast<ConstantSDNode>(Op);
5835 APInt Val = C->getAPIntValue();
5836 Ops.push_back(SignExtendInReg(Val, OpVT));
5838 return getBuildVector(VT, DL, Ops);
5840 break;
5842 case ISD::FP_TO_SINT_SAT:
5843 case ISD::FP_TO_UINT_SAT: {
5844 assert(VT.isInteger() && cast<VTSDNode>(N2)->getVT().isInteger() &&
5845 N1.getValueType().isFloatingPoint() && "Invalid FP_TO_*INT_SAT");
5846 assert(N1.getValueType().isVector() == VT.isVector() &&
5847 "FP_TO_*INT_SAT type should be vector iff the operand type is "
5848 "vector!");
5849 assert((!VT.isVector() || VT.getVectorNumElements() ==
5850 N1.getValueType().getVectorNumElements()) &&
5851 "Vector element counts must match in FP_TO_*INT_SAT");
5852 assert(!cast<VTSDNode>(N2)->getVT().isVector() &&
5853 "Type to saturate to must be a scalar.");
5854 assert(cast<VTSDNode>(N2)->getVT().bitsLE(VT.getScalarType()) &&
5855 "Not extending!");
5856 break;
5858 case ISD::EXTRACT_VECTOR_ELT:
5859 assert(VT.getSizeInBits() >= N1.getValueType().getScalarSizeInBits() &&
5860 "The result of EXTRACT_VECTOR_ELT must be at least as wide as the \
5861 element type of the vector.");
5863 // Extract from an undefined value or using an undefined index is undefined.
5864 if (N1.isUndef() || N2.isUndef())
5865 return getUNDEF(VT);
5867 // EXTRACT_VECTOR_ELT of out-of-bounds element is an UNDEF for fixed length
5868 // vectors. For scalable vectors we will provide appropriate support for
5869 // dealing with arbitrary indices.
5870 if (N2C && N1.getValueType().isFixedLengthVector() &&
5871 N2C->getAPIntValue().uge(N1.getValueType().getVectorNumElements()))
5872 return getUNDEF(VT);
5874 // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
5875 // expanding copies of large vectors from registers. This only works for
5876 // fixed length vectors, since we need to know the exact number of
5877 // elements.
5878 if (N2C && N1.getOperand(0).getValueType().isFixedLengthVector() &&
5879 N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0) {
5880 unsigned Factor =
5881 N1.getOperand(0).getValueType().getVectorNumElements();
5882 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
5883 N1.getOperand(N2C->getZExtValue() / Factor),
5884 getVectorIdxConstant(N2C->getZExtValue() % Factor, DL));
5887 // EXTRACT_VECTOR_ELT of BUILD_VECTOR or SPLAT_VECTOR is often formed while
5888 // lowering is expanding large vector constants.
5889 if (N2C && (N1.getOpcode() == ISD::BUILD_VECTOR ||
5890 N1.getOpcode() == ISD::SPLAT_VECTOR)) {
5891 assert((N1.getOpcode() != ISD::BUILD_VECTOR ||
5892 N1.getValueType().isFixedLengthVector()) &&
5893 "BUILD_VECTOR used for scalable vectors");
5894 unsigned Index =
5895 N1.getOpcode() == ISD::BUILD_VECTOR ? N2C->getZExtValue() : 0;
5896 SDValue Elt = N1.getOperand(Index);
5898 if (VT != Elt.getValueType())
5899 // If the vector element type is not legal, the BUILD_VECTOR operands
5900 // are promoted and implicitly truncated, and the result implicitly
5901 // extended. Make that explicit here.
5902 Elt = getAnyExtOrTrunc(Elt, DL, VT);
5904 return Elt;
5907 // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
5908 // operations are lowered to scalars.
5909 if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) {
5910 // If the indices are the same, return the inserted element else
5911 // if the indices are known different, extract the element from
5912 // the original vector.
5913 SDValue N1Op2 = N1.getOperand(2);
5914 ConstantSDNode *N1Op2C = dyn_cast<ConstantSDNode>(N1Op2);
5916 if (N1Op2C && N2C) {
5917 if (N1Op2C->getZExtValue() == N2C->getZExtValue()) {
5918 if (VT == N1.getOperand(1).getValueType())
5919 return N1.getOperand(1);
5920 return getSExtOrTrunc(N1.getOperand(1), DL, VT);
5922 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2);
5926 // EXTRACT_VECTOR_ELT of v1iX EXTRACT_SUBVECTOR could be formed
5927 // when vector types are scalarized and v1iX is legal.
5928 // vextract (v1iX extract_subvector(vNiX, Idx)) -> vextract(vNiX,Idx).
5929 // Here we are completely ignoring the extract element index (N2),
5930 // which is fine for fixed width vectors, since any index other than 0
5931 // is undefined anyway. However, this cannot be ignored for scalable
5932 // vectors - in theory we could support this, but we don't want to do this
5933 // without a profitability check.
5934 if (N1.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
5935 N1.getValueType().isFixedLengthVector() &&
5936 N1.getValueType().getVectorNumElements() == 1) {
5937 return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0),
5938 N1.getOperand(1));
5940 break;
5941 case ISD::EXTRACT_ELEMENT:
5942 assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!");
5943 assert(!N1.getValueType().isVector() && !VT.isVector() &&
5944 (N1.getValueType().isInteger() == VT.isInteger()) &&
5945 N1.getValueType() != VT &&
5946 "Wrong types for EXTRACT_ELEMENT!");
5948 // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
5949 // 64-bit integers into 32-bit parts. Instead of building the extract of
5950 // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
5951 if (N1.getOpcode() == ISD::BUILD_PAIR)
5952 return N1.getOperand(N2C->getZExtValue());
5954 // EXTRACT_ELEMENT of a constant int is also very common.
5955 if (N1C) {
5956 unsigned ElementSize = VT.getSizeInBits();
5957 unsigned Shift = ElementSize * N2C->getZExtValue();
5958 const APInt &Val = N1C->getAPIntValue();
5959 return getConstant(Val.extractBits(ElementSize, Shift), DL, VT);
5961 break;
5962 case ISD::EXTRACT_SUBVECTOR: {
5963 EVT N1VT = N1.getValueType();
5964 assert(VT.isVector() && N1VT.isVector() &&
5965 "Extract subvector VTs must be vectors!");
5966 assert(VT.getVectorElementType() == N1VT.getVectorElementType() &&
5967 "Extract subvector VTs must have the same element type!");
5968 assert((VT.isFixedLengthVector() || N1VT.isScalableVector()) &&
5969 "Cannot extract a scalable vector from a fixed length vector!");
5970 assert((VT.isScalableVector() != N1VT.isScalableVector() ||
5971 VT.getVectorMinNumElements() <= N1VT.getVectorMinNumElements()) &&
5972 "Extract subvector must be from larger vector to smaller vector!");
5973 assert(N2C && "Extract subvector index must be a constant");
5974 assert((VT.isScalableVector() != N1VT.isScalableVector() ||
5975 (VT.getVectorMinNumElements() + N2C->getZExtValue()) <=
5976 N1VT.getVectorMinNumElements()) &&
5977 "Extract subvector overflow!");
5978 assert(N2C->getAPIntValue().getBitWidth() ==
5979 TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() &&
5980 "Constant index for EXTRACT_SUBVECTOR has an invalid size");
5982 // Trivial extraction.
5983 if (VT == N1VT)
5984 return N1;
5986 // EXTRACT_SUBVECTOR of an UNDEF is an UNDEF.
5987 if (N1.isUndef())
5988 return getUNDEF(VT);
5990 // EXTRACT_SUBVECTOR of CONCAT_VECTOR can be simplified if the pieces of
5991 // the concat have the same type as the extract.
5992 if (N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0 &&
5993 VT == N1.getOperand(0).getValueType()) {
5994 unsigned Factor = VT.getVectorMinNumElements();
5995 return N1.getOperand(N2C->getZExtValue() / Factor);
5998 // EXTRACT_SUBVECTOR of INSERT_SUBVECTOR is often created
5999 // during shuffle legalization.
6000 if (N1.getOpcode() == ISD::INSERT_SUBVECTOR && N2 == N1.getOperand(2) &&
6001 VT == N1.getOperand(1).getValueType())
6002 return N1.getOperand(1);
6003 break;
6007 // Perform trivial constant folding.
6008 if (SDValue SV = FoldConstantArithmetic(Opcode, DL, VT, {N1, N2}))
6009 return SV;
6011 // Canonicalize an UNDEF to the RHS, even over a constant.
6012 if (N1.isUndef()) {
6013 if (TLI->isCommutativeBinOp(Opcode)) {
6014 std::swap(N1, N2);
6015 } else {
6016 switch (Opcode) {
6017 case ISD::SIGN_EXTEND_INREG:
6018 case ISD::SUB:
6019 return getUNDEF(VT); // fold op(undef, arg2) -> undef
6020 case ISD::UDIV:
6021 case ISD::SDIV:
6022 case ISD::UREM:
6023 case ISD::SREM:
6024 case ISD::SSUBSAT:
6025 case ISD::USUBSAT:
6026 return getConstant(0, DL, VT); // fold op(undef, arg2) -> 0
6031 // Fold a bunch of operators when the RHS is undef.
6032 if (N2.isUndef()) {
6033 switch (Opcode) {
6034 case ISD::XOR:
6035 if (N1.isUndef())
6036 // Handle undef ^ undef -> 0 special case. This is a common
6037 // idiom (misuse).
6038 return getConstant(0, DL, VT);
6039 LLVM_FALLTHROUGH;
6040 case ISD::ADD:
6041 case ISD::SUB:
6042 case ISD::UDIV:
6043 case ISD::SDIV:
6044 case ISD::UREM:
6045 case ISD::SREM:
6046 return getUNDEF(VT); // fold op(arg1, undef) -> undef
6047 case ISD::MUL:
6048 case ISD::AND:
6049 case ISD::SSUBSAT:
6050 case ISD::USUBSAT:
6051 return getConstant(0, DL, VT); // fold op(arg1, undef) -> 0
6052 case ISD::OR:
6053 case ISD::SADDSAT:
6054 case ISD::UADDSAT:
6055 return getAllOnesConstant(DL, VT);
6059 // Memoize this node if possible.
6060 SDNode *N;
6061 SDVTList VTs = getVTList(VT);
6062 SDValue Ops[] = {N1, N2};
6063 if (VT != MVT::Glue) {
6064 FoldingSetNodeID ID;
6065 AddNodeIDNode(ID, Opcode, VTs, Ops);
6066 void *IP = nullptr;
6067 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
6068 E->intersectFlagsWith(Flags);
6069 return SDValue(E, 0);
6072 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6073 N->setFlags(Flags);
6074 createOperands(N, Ops);
6075 CSEMap.InsertNode(N, IP);
6076 } else {
6077 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6078 createOperands(N, Ops);
6081 InsertNode(N);
6082 SDValue V = SDValue(N, 0);
6083 NewSDValueDbgMsg(V, "Creating new node: ", this);
6084 return V;
6087 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6088 SDValue N1, SDValue N2, SDValue N3) {
6089 SDNodeFlags Flags;
6090 if (Inserter)
6091 Flags = Inserter->getFlags();
6092 return getNode(Opcode, DL, VT, N1, N2, N3, Flags);
6095 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6096 SDValue N1, SDValue N2, SDValue N3,
6097 const SDNodeFlags Flags) {
6098 assert(N1.getOpcode() != ISD::DELETED_NODE &&
6099 N2.getOpcode() != ISD::DELETED_NODE &&
6100 N3.getOpcode() != ISD::DELETED_NODE &&
6101 "Operand is DELETED_NODE!");
6102 // Perform various simplifications.
6103 switch (Opcode) {
6104 case ISD::FMA: {
6105 assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
6106 assert(N1.getValueType() == VT && N2.getValueType() == VT &&
6107 N3.getValueType() == VT && "FMA types must match!");
6108 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6109 ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
6110 ConstantFPSDNode *N3CFP = dyn_cast<ConstantFPSDNode>(N3);
6111 if (N1CFP && N2CFP && N3CFP) {
6112 APFloat V1 = N1CFP->getValueAPF();
6113 const APFloat &V2 = N2CFP->getValueAPF();
6114 const APFloat &V3 = N3CFP->getValueAPF();
6115 V1.fusedMultiplyAdd(V2, V3, APFloat::rmNearestTiesToEven);
6116 return getConstantFP(V1, DL, VT);
6118 break;
6120 case ISD::BUILD_VECTOR: {
6121 // Attempt to simplify BUILD_VECTOR.
6122 SDValue Ops[] = {N1, N2, N3};
6123 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
6124 return V;
6125 break;
6127 case ISD::CONCAT_VECTORS: {
6128 SDValue Ops[] = {N1, N2, N3};
6129 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
6130 return V;
6131 break;
6133 case ISD::SETCC: {
6134 assert(VT.isInteger() && "SETCC result type must be an integer!");
6135 assert(N1.getValueType() == N2.getValueType() &&
6136 "SETCC operands must have the same type!");
6137 assert(VT.isVector() == N1.getValueType().isVector() &&
6138 "SETCC type should be vector iff the operand type is vector!");
6139 assert((!VT.isVector() || VT.getVectorElementCount() ==
6140 N1.getValueType().getVectorElementCount()) &&
6141 "SETCC vector element counts must match!");
6142 // Use FoldSetCC to simplify SETCC's.
6143 if (SDValue V = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL))
6144 return V;
6145 // Vector constant folding.
6146 SDValue Ops[] = {N1, N2, N3};
6147 if (SDValue V = FoldConstantArithmetic(Opcode, DL, VT, Ops)) {
6148 NewSDValueDbgMsg(V, "New node vector constant folding: ", this);
6149 return V;
6151 break;
6153 case ISD::SELECT:
6154 case ISD::VSELECT:
6155 if (SDValue V = simplifySelect(N1, N2, N3))
6156 return V;
6157 break;
6158 case ISD::VECTOR_SHUFFLE:
6159 llvm_unreachable("should use getVectorShuffle constructor!");
6160 case ISD::VECTOR_SPLICE: {
6161 if (cast<ConstantSDNode>(N3)->isNullValue())
6162 return N1;
6163 break;
6165 case ISD::INSERT_VECTOR_ELT: {
6166 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3);
6167 // INSERT_VECTOR_ELT into out-of-bounds element is an UNDEF, except
6168 // for scalable vectors where we will generate appropriate code to
6169 // deal with out-of-bounds cases correctly.
6170 if (N3C && N1.getValueType().isFixedLengthVector() &&
6171 N3C->getZExtValue() >= N1.getValueType().getVectorNumElements())
6172 return getUNDEF(VT);
6174 // Undefined index can be assumed out-of-bounds, so that's UNDEF too.
6175 if (N3.isUndef())
6176 return getUNDEF(VT);
6178 // If the inserted element is an UNDEF, just use the input vector.
6179 if (N2.isUndef())
6180 return N1;
6182 break;
6184 case ISD::INSERT_SUBVECTOR: {
6185 // Inserting undef into undef is still undef.
6186 if (N1.isUndef() && N2.isUndef())
6187 return getUNDEF(VT);
6189 EVT N2VT = N2.getValueType();
6190 assert(VT == N1.getValueType() &&
6191 "Dest and insert subvector source types must match!");
6192 assert(VT.isVector() && N2VT.isVector() &&
6193 "Insert subvector VTs must be vectors!");
6194 assert((VT.isScalableVector() || N2VT.isFixedLengthVector()) &&
6195 "Cannot insert a scalable vector into a fixed length vector!");
6196 assert((VT.isScalableVector() != N2VT.isScalableVector() ||
6197 VT.getVectorMinNumElements() >= N2VT.getVectorMinNumElements()) &&
6198 "Insert subvector must be from smaller vector to larger vector!");
6199 assert(isa<ConstantSDNode>(N3) &&
6200 "Insert subvector index must be constant");
6201 assert((VT.isScalableVector() != N2VT.isScalableVector() ||
6202 (N2VT.getVectorMinNumElements() +
6203 cast<ConstantSDNode>(N3)->getZExtValue()) <=
6204 VT.getVectorMinNumElements()) &&
6205 "Insert subvector overflow!");
6206 assert(cast<ConstantSDNode>(N3)->getAPIntValue().getBitWidth() ==
6207 TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() &&
6208 "Constant index for INSERT_SUBVECTOR has an invalid size");
6210 // Trivial insertion.
6211 if (VT == N2VT)
6212 return N2;
6214 // If this is an insert of an extracted vector into an undef vector, we
6215 // can just use the input to the extract.
6216 if (N1.isUndef() && N2.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
6217 N2.getOperand(1) == N3 && N2.getOperand(0).getValueType() == VT)
6218 return N2.getOperand(0);
6219 break;
6221 case ISD::BITCAST:
6222 // Fold bit_convert nodes from a type to themselves.
6223 if (N1.getValueType() == VT)
6224 return N1;
6225 break;
6228 // Memoize node if it doesn't produce a flag.
6229 SDNode *N;
6230 SDVTList VTs = getVTList(VT);
6231 SDValue Ops[] = {N1, N2, N3};
6232 if (VT != MVT::Glue) {
6233 FoldingSetNodeID ID;
6234 AddNodeIDNode(ID, Opcode, VTs, Ops);
6235 void *IP = nullptr;
6236 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
6237 E->intersectFlagsWith(Flags);
6238 return SDValue(E, 0);
6241 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6242 N->setFlags(Flags);
6243 createOperands(N, Ops);
6244 CSEMap.InsertNode(N, IP);
6245 } else {
6246 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6247 createOperands(N, Ops);
6250 InsertNode(N);
6251 SDValue V = SDValue(N, 0);
6252 NewSDValueDbgMsg(V, "Creating new node: ", this);
6253 return V;
6256 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6257 SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
6258 SDValue Ops[] = { N1, N2, N3, N4 };
6259 return getNode(Opcode, DL, VT, Ops);
6262 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6263 SDValue N1, SDValue N2, SDValue N3, SDValue N4,
6264 SDValue N5) {
6265 SDValue Ops[] = { N1, N2, N3, N4, N5 };
6266 return getNode(Opcode, DL, VT, Ops);
6269 /// getStackArgumentTokenFactor - Compute a TokenFactor to force all
6270 /// the incoming stack arguments to be loaded from the stack.
6271 SDValue SelectionDAG::getStackArgumentTokenFactor(SDValue Chain) {
6272 SmallVector<SDValue, 8> ArgChains;
6274 // Include the original chain at the beginning of the list. When this is
6275 // used by target LowerCall hooks, this helps legalize find the
6276 // CALLSEQ_BEGIN node.
6277 ArgChains.push_back(Chain);
6279 // Add a chain value for each stack argument.
6280 for (SDNode *U : getEntryNode().getNode()->uses())
6281 if (LoadSDNode *L = dyn_cast<LoadSDNode>(U))
6282 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
6283 if (FI->getIndex() < 0)
6284 ArgChains.push_back(SDValue(L, 1));
6286 // Build a tokenfactor for all the chains.
6287 return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
6290 /// getMemsetValue - Vectorized representation of the memset value
6291 /// operand.
6292 static SDValue getMemsetValue(SDValue Value, EVT VT, SelectionDAG &DAG,
6293 const SDLoc &dl) {
6294 assert(!Value.isUndef());
6296 unsigned NumBits = VT.getScalarSizeInBits();
6297 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
6298 assert(C->getAPIntValue().getBitWidth() == 8);
6299 APInt Val = APInt::getSplat(NumBits, C->getAPIntValue());
6300 if (VT.isInteger()) {
6301 bool IsOpaque = VT.getSizeInBits() > 64 ||
6302 !DAG.getTargetLoweringInfo().isLegalStoreImmediate(C->getSExtValue());
6303 return DAG.getConstant(Val, dl, VT, false, IsOpaque);
6305 return DAG.getConstantFP(APFloat(DAG.EVTToAPFloatSemantics(VT), Val), dl,
6306 VT);
6309 assert(Value.getValueType() == MVT::i8 && "memset with non-byte fill value?");
6310 EVT IntVT = VT.getScalarType();
6311 if (!IntVT.isInteger())
6312 IntVT = EVT::getIntegerVT(*DAG.getContext(), IntVT.getSizeInBits());
6314 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, Value);
6315 if (NumBits > 8) {
6316 // Use a multiplication with 0x010101... to extend the input to the
6317 // required length.
6318 APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01));
6319 Value = DAG.getNode(ISD::MUL, dl, IntVT, Value,
6320 DAG.getConstant(Magic, dl, IntVT));
6323 if (VT != Value.getValueType() && !VT.isInteger())
6324 Value = DAG.getBitcast(VT.getScalarType(), Value);
6325 if (VT != Value.getValueType())
6326 Value = DAG.getSplatBuildVector(VT, dl, Value);
6328 return Value;
6331 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
6332 /// used when a memcpy is turned into a memset when the source is a constant
6333 /// string ptr.
6334 static SDValue getMemsetStringVal(EVT VT, const SDLoc &dl, SelectionDAG &DAG,
6335 const TargetLowering &TLI,
6336 const ConstantDataArraySlice &Slice) {
6337 // Handle vector with all elements zero.
6338 if (Slice.Array == nullptr) {
6339 if (VT.isInteger())
6340 return DAG.getConstant(0, dl, VT);
6341 if (VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128)
6342 return DAG.getConstantFP(0.0, dl, VT);
6343 if (VT.isVector()) {
6344 unsigned NumElts = VT.getVectorNumElements();
6345 MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
6346 return DAG.getNode(ISD::BITCAST, dl, VT,
6347 DAG.getConstant(0, dl,
6348 EVT::getVectorVT(*DAG.getContext(),
6349 EltVT, NumElts)));
6351 llvm_unreachable("Expected type!");
6354 assert(!VT.isVector() && "Can't handle vector type here!");
6355 unsigned NumVTBits = VT.getSizeInBits();
6356 unsigned NumVTBytes = NumVTBits / 8;
6357 unsigned NumBytes = std::min(NumVTBytes, unsigned(Slice.Length));
6359 APInt Val(NumVTBits, 0);
6360 if (DAG.getDataLayout().isLittleEndian()) {
6361 for (unsigned i = 0; i != NumBytes; ++i)
6362 Val |= (uint64_t)(unsigned char)Slice[i] << i*8;
6363 } else {
6364 for (unsigned i = 0; i != NumBytes; ++i)
6365 Val |= (uint64_t)(unsigned char)Slice[i] << (NumVTBytes-i-1)*8;
6368 // If the "cost" of materializing the integer immediate is less than the cost
6369 // of a load, then it is cost effective to turn the load into the immediate.
6370 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
6371 if (TLI.shouldConvertConstantLoadToIntImm(Val, Ty))
6372 return DAG.getConstant(Val, dl, VT);
6373 return SDValue();
6376 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Base, TypeSize Offset,
6377 const SDLoc &DL,
6378 const SDNodeFlags Flags) {
6379 EVT VT = Base.getValueType();
6380 SDValue Index;
6382 if (Offset.isScalable())
6383 Index = getVScale(DL, Base.getValueType(),
6384 APInt(Base.getValueSizeInBits().getFixedSize(),
6385 Offset.getKnownMinSize()));
6386 else
6387 Index = getConstant(Offset.getFixedSize(), DL, VT);
6389 return getMemBasePlusOffset(Base, Index, DL, Flags);
6392 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Ptr, SDValue Offset,
6393 const SDLoc &DL,
6394 const SDNodeFlags Flags) {
6395 assert(Offset.getValueType().isInteger());
6396 EVT BasePtrVT = Ptr.getValueType();
6397 return getNode(ISD::ADD, DL, BasePtrVT, Ptr, Offset, Flags);
6400 /// Returns true if memcpy source is constant data.
6401 static bool isMemSrcFromConstant(SDValue Src, ConstantDataArraySlice &Slice) {
6402 uint64_t SrcDelta = 0;
6403 GlobalAddressSDNode *G = nullptr;
6404 if (Src.getOpcode() == ISD::GlobalAddress)
6405 G = cast<GlobalAddressSDNode>(Src);
6406 else if (Src.getOpcode() == ISD::ADD &&
6407 Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
6408 Src.getOperand(1).getOpcode() == ISD::Constant) {
6409 G = cast<GlobalAddressSDNode>(Src.getOperand(0));
6410 SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue();
6412 if (!G)
6413 return false;
6415 return getConstantDataArrayInfo(G->getGlobal(), Slice, 8,
6416 SrcDelta + G->getOffset());
6419 static bool shouldLowerMemFuncForSize(const MachineFunction &MF,
6420 SelectionDAG &DAG) {
6421 // On Darwin, -Os means optimize for size without hurting performance, so
6422 // only really optimize for size when -Oz (MinSize) is used.
6423 if (MF.getTarget().getTargetTriple().isOSDarwin())
6424 return MF.getFunction().hasMinSize();
6425 return DAG.shouldOptForSize();
6428 static void chainLoadsAndStoresForMemcpy(SelectionDAG &DAG, const SDLoc &dl,
6429 SmallVector<SDValue, 32> &OutChains, unsigned From,
6430 unsigned To, SmallVector<SDValue, 16> &OutLoadChains,
6431 SmallVector<SDValue, 16> &OutStoreChains) {
6432 assert(OutLoadChains.size() && "Missing loads in memcpy inlining");
6433 assert(OutStoreChains.size() && "Missing stores in memcpy inlining");
6434 SmallVector<SDValue, 16> GluedLoadChains;
6435 for (unsigned i = From; i < To; ++i) {
6436 OutChains.push_back(OutLoadChains[i]);
6437 GluedLoadChains.push_back(OutLoadChains[i]);
6440 // Chain for all loads.
6441 SDValue LoadToken = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6442 GluedLoadChains);
6444 for (unsigned i = From; i < To; ++i) {
6445 StoreSDNode *ST = dyn_cast<StoreSDNode>(OutStoreChains[i]);
6446 SDValue NewStore = DAG.getTruncStore(LoadToken, dl, ST->getValue(),
6447 ST->getBasePtr(), ST->getMemoryVT(),
6448 ST->getMemOperand());
6449 OutChains.push_back(NewStore);
6453 static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
6454 SDValue Chain, SDValue Dst, SDValue Src,
6455 uint64_t Size, Align Alignment,
6456 bool isVol, bool AlwaysInline,
6457 MachinePointerInfo DstPtrInfo,
6458 MachinePointerInfo SrcPtrInfo,
6459 const AAMDNodes &AAInfo) {
6460 // Turn a memcpy of undef to nop.
6461 // FIXME: We need to honor volatile even is Src is undef.
6462 if (Src.isUndef())
6463 return Chain;
6465 // Expand memcpy to a series of load and store ops if the size operand falls
6466 // below a certain threshold.
6467 // TODO: In the AlwaysInline case, if the size is big then generate a loop
6468 // rather than maybe a humongous number of loads and stores.
6469 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6470 const DataLayout &DL = DAG.getDataLayout();
6471 LLVMContext &C = *DAG.getContext();
6472 std::vector<EVT> MemOps;
6473 bool DstAlignCanChange = false;
6474 MachineFunction &MF = DAG.getMachineFunction();
6475 MachineFrameInfo &MFI = MF.getFrameInfo();
6476 bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
6477 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
6478 if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
6479 DstAlignCanChange = true;
6480 MaybeAlign SrcAlign = DAG.InferPtrAlign(Src);
6481 if (!SrcAlign || Alignment > *SrcAlign)
6482 SrcAlign = Alignment;
6483 assert(SrcAlign && "SrcAlign must be set");
6484 ConstantDataArraySlice Slice;
6485 // If marked as volatile, perform a copy even when marked as constant.
6486 bool CopyFromConstant = !isVol && isMemSrcFromConstant(Src, Slice);
6487 bool isZeroConstant = CopyFromConstant && Slice.Array == nullptr;
6488 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize);
6489 const MemOp Op = isZeroConstant
6490 ? MemOp::Set(Size, DstAlignCanChange, Alignment,
6491 /*IsZeroMemset*/ true, isVol)
6492 : MemOp::Copy(Size, DstAlignCanChange, Alignment,
6493 *SrcAlign, isVol, CopyFromConstant);
6494 if (!TLI.findOptimalMemOpLowering(
6495 MemOps, Limit, Op, DstPtrInfo.getAddrSpace(),
6496 SrcPtrInfo.getAddrSpace(), MF.getFunction().getAttributes()))
6497 return SDValue();
6499 if (DstAlignCanChange) {
6500 Type *Ty = MemOps[0].getTypeForEVT(C);
6501 Align NewAlign = DL.getABITypeAlign(Ty);
6503 // Don't promote to an alignment that would require dynamic stack
6504 // realignment.
6505 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
6506 if (!TRI->hasStackRealignment(MF))
6507 while (NewAlign > Alignment && DL.exceedsNaturalStackAlignment(NewAlign))
6508 NewAlign = NewAlign / 2;
6510 if (NewAlign > Alignment) {
6511 // Give the stack frame object a larger alignment if needed.
6512 if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
6513 MFI.setObjectAlignment(FI->getIndex(), NewAlign);
6514 Alignment = NewAlign;
6518 // Prepare AAInfo for loads/stores after lowering this memcpy.
6519 AAMDNodes NewAAInfo = AAInfo;
6520 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
6522 MachineMemOperand::Flags MMOFlags =
6523 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
6524 SmallVector<SDValue, 16> OutLoadChains;
6525 SmallVector<SDValue, 16> OutStoreChains;
6526 SmallVector<SDValue, 32> OutChains;
6527 unsigned NumMemOps = MemOps.size();
6528 uint64_t SrcOff = 0, DstOff = 0;
6529 for (unsigned i = 0; i != NumMemOps; ++i) {
6530 EVT VT = MemOps[i];
6531 unsigned VTSize = VT.getSizeInBits() / 8;
6532 SDValue Value, Store;
6534 if (VTSize > Size) {
6535 // Issuing an unaligned load / store pair that overlaps with the previous
6536 // pair. Adjust the offset accordingly.
6537 assert(i == NumMemOps-1 && i != 0);
6538 SrcOff -= VTSize - Size;
6539 DstOff -= VTSize - Size;
6542 if (CopyFromConstant &&
6543 (isZeroConstant || (VT.isInteger() && !VT.isVector()))) {
6544 // It's unlikely a store of a vector immediate can be done in a single
6545 // instruction. It would require a load from a constantpool first.
6546 // We only handle zero vectors here.
6547 // FIXME: Handle other cases where store of vector immediate is done in
6548 // a single instruction.
6549 ConstantDataArraySlice SubSlice;
6550 if (SrcOff < Slice.Length) {
6551 SubSlice = Slice;
6552 SubSlice.move(SrcOff);
6553 } else {
6554 // This is an out-of-bounds access and hence UB. Pretend we read zero.
6555 SubSlice.Array = nullptr;
6556 SubSlice.Offset = 0;
6557 SubSlice.Length = VTSize;
6559 Value = getMemsetStringVal(VT, dl, DAG, TLI, SubSlice);
6560 if (Value.getNode()) {
6561 Store = DAG.getStore(
6562 Chain, dl, Value,
6563 DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6564 DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo);
6565 OutChains.push_back(Store);
6569 if (!Store.getNode()) {
6570 // The type might not be legal for the target. This should only happen
6571 // if the type is smaller than a legal type, as on PPC, so the right
6572 // thing to do is generate a LoadExt/StoreTrunc pair. These simplify
6573 // to Load/Store if NVT==VT.
6574 // FIXME does the case above also need this?
6575 EVT NVT = TLI.getTypeToTransformTo(C, VT);
6576 assert(NVT.bitsGE(VT));
6578 bool isDereferenceable =
6579 SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
6580 MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
6581 if (isDereferenceable)
6582 SrcMMOFlags |= MachineMemOperand::MODereferenceable;
6584 Value = DAG.getExtLoad(
6585 ISD::EXTLOAD, dl, NVT, Chain,
6586 DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl),
6587 SrcPtrInfo.getWithOffset(SrcOff), VT,
6588 commonAlignment(*SrcAlign, SrcOff), SrcMMOFlags, NewAAInfo);
6589 OutLoadChains.push_back(Value.getValue(1));
6591 Store = DAG.getTruncStore(
6592 Chain, dl, Value,
6593 DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6594 DstPtrInfo.getWithOffset(DstOff), VT, Alignment, MMOFlags, NewAAInfo);
6595 OutStoreChains.push_back(Store);
6597 SrcOff += VTSize;
6598 DstOff += VTSize;
6599 Size -= VTSize;
6602 unsigned GluedLdStLimit = MaxLdStGlue == 0 ?
6603 TLI.getMaxGluedStoresPerMemcpy() : MaxLdStGlue;
6604 unsigned NumLdStInMemcpy = OutStoreChains.size();
6606 if (NumLdStInMemcpy) {
6607 // It may be that memcpy might be converted to memset if it's memcpy
6608 // of constants. In such a case, we won't have loads and stores, but
6609 // just stores. In the absence of loads, there is nothing to gang up.
6610 if ((GluedLdStLimit <= 1) || !EnableMemCpyDAGOpt) {
6611 // If target does not care, just leave as it.
6612 for (unsigned i = 0; i < NumLdStInMemcpy; ++i) {
6613 OutChains.push_back(OutLoadChains[i]);
6614 OutChains.push_back(OutStoreChains[i]);
6616 } else {
6617 // Ld/St less than/equal limit set by target.
6618 if (NumLdStInMemcpy <= GluedLdStLimit) {
6619 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
6620 NumLdStInMemcpy, OutLoadChains,
6621 OutStoreChains);
6622 } else {
6623 unsigned NumberLdChain = NumLdStInMemcpy / GluedLdStLimit;
6624 unsigned RemainingLdStInMemcpy = NumLdStInMemcpy % GluedLdStLimit;
6625 unsigned GlueIter = 0;
6627 for (unsigned cnt = 0; cnt < NumberLdChain; ++cnt) {
6628 unsigned IndexFrom = NumLdStInMemcpy - GlueIter - GluedLdStLimit;
6629 unsigned IndexTo = NumLdStInMemcpy - GlueIter;
6631 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, IndexFrom, IndexTo,
6632 OutLoadChains, OutStoreChains);
6633 GlueIter += GluedLdStLimit;
6636 // Residual ld/st.
6637 if (RemainingLdStInMemcpy) {
6638 chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
6639 RemainingLdStInMemcpy, OutLoadChains,
6640 OutStoreChains);
6645 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
6648 static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
6649 SDValue Chain, SDValue Dst, SDValue Src,
6650 uint64_t Size, Align Alignment,
6651 bool isVol, bool AlwaysInline,
6652 MachinePointerInfo DstPtrInfo,
6653 MachinePointerInfo SrcPtrInfo,
6654 const AAMDNodes &AAInfo) {
6655 // Turn a memmove of undef to nop.
6656 // FIXME: We need to honor volatile even is Src is undef.
6657 if (Src.isUndef())
6658 return Chain;
6660 // Expand memmove to a series of load and store ops if the size operand falls
6661 // below a certain threshold.
6662 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6663 const DataLayout &DL = DAG.getDataLayout();
6664 LLVMContext &C = *DAG.getContext();
6665 std::vector<EVT> MemOps;
6666 bool DstAlignCanChange = false;
6667 MachineFunction &MF = DAG.getMachineFunction();
6668 MachineFrameInfo &MFI = MF.getFrameInfo();
6669 bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
6670 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
6671 if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
6672 DstAlignCanChange = true;
6673 MaybeAlign SrcAlign = DAG.InferPtrAlign(Src);
6674 if (!SrcAlign || Alignment > *SrcAlign)
6675 SrcAlign = Alignment;
6676 assert(SrcAlign && "SrcAlign must be set");
6677 unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize);
6678 if (!TLI.findOptimalMemOpLowering(
6679 MemOps, Limit,
6680 MemOp::Copy(Size, DstAlignCanChange, Alignment, *SrcAlign,
6681 /*IsVolatile*/ true),
6682 DstPtrInfo.getAddrSpace(), SrcPtrInfo.getAddrSpace(),
6683 MF.getFunction().getAttributes()))
6684 return SDValue();
6686 if (DstAlignCanChange) {
6687 Type *Ty = MemOps[0].getTypeForEVT(C);
6688 Align NewAlign = DL.getABITypeAlign(Ty);
6689 if (NewAlign > Alignment) {
6690 // Give the stack frame object a larger alignment if needed.
6691 if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
6692 MFI.setObjectAlignment(FI->getIndex(), NewAlign);
6693 Alignment = NewAlign;
6697 // Prepare AAInfo for loads/stores after lowering this memmove.
6698 AAMDNodes NewAAInfo = AAInfo;
6699 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
6701 MachineMemOperand::Flags MMOFlags =
6702 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
6703 uint64_t SrcOff = 0, DstOff = 0;
6704 SmallVector<SDValue, 8> LoadValues;
6705 SmallVector<SDValue, 8> LoadChains;
6706 SmallVector<SDValue, 8> OutChains;
6707 unsigned NumMemOps = MemOps.size();
6708 for (unsigned i = 0; i < NumMemOps; i++) {
6709 EVT VT = MemOps[i];
6710 unsigned VTSize = VT.getSizeInBits() / 8;
6711 SDValue Value;
6713 bool isDereferenceable =
6714 SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
6715 MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
6716 if (isDereferenceable)
6717 SrcMMOFlags |= MachineMemOperand::MODereferenceable;
6719 Value = DAG.getLoad(
6720 VT, dl, Chain,
6721 DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl),
6722 SrcPtrInfo.getWithOffset(SrcOff), *SrcAlign, SrcMMOFlags, NewAAInfo);
6723 LoadValues.push_back(Value);
6724 LoadChains.push_back(Value.getValue(1));
6725 SrcOff += VTSize;
6727 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
6728 OutChains.clear();
6729 for (unsigned i = 0; i < NumMemOps; i++) {
6730 EVT VT = MemOps[i];
6731 unsigned VTSize = VT.getSizeInBits() / 8;
6732 SDValue Store;
6734 Store = DAG.getStore(
6735 Chain, dl, LoadValues[i],
6736 DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6737 DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo);
6738 OutChains.push_back(Store);
6739 DstOff += VTSize;
6742 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
6745 /// Lower the call to 'memset' intrinsic function into a series of store
6746 /// operations.
6748 /// \param DAG Selection DAG where lowered code is placed.
6749 /// \param dl Link to corresponding IR location.
6750 /// \param Chain Control flow dependency.
6751 /// \param Dst Pointer to destination memory location.
6752 /// \param Src Value of byte to write into the memory.
6753 /// \param Size Number of bytes to write.
6754 /// \param Alignment Alignment of the destination in bytes.
6755 /// \param isVol True if destination is volatile.
6756 /// \param DstPtrInfo IR information on the memory pointer.
6757 /// \returns New head in the control flow, if lowering was successful, empty
6758 /// SDValue otherwise.
6760 /// The function tries to replace 'llvm.memset' intrinsic with several store
6761 /// operations and value calculation code. This is usually profitable for small
6762 /// memory size.
6763 static SDValue getMemsetStores(SelectionDAG &DAG, const SDLoc &dl,
6764 SDValue Chain, SDValue Dst, SDValue Src,
6765 uint64_t Size, Align Alignment, bool isVol,
6766 MachinePointerInfo DstPtrInfo,
6767 const AAMDNodes &AAInfo) {
6768 // Turn a memset of undef to nop.
6769 // FIXME: We need to honor volatile even is Src is undef.
6770 if (Src.isUndef())
6771 return Chain;
6773 // Expand memset to a series of load/store ops if the size operand
6774 // falls below a certain threshold.
6775 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6776 std::vector<EVT> MemOps;
6777 bool DstAlignCanChange = false;
6778 MachineFunction &MF = DAG.getMachineFunction();
6779 MachineFrameInfo &MFI = MF.getFrameInfo();
6780 bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
6781 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
6782 if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
6783 DstAlignCanChange = true;
6784 bool IsZeroVal =
6785 isa<ConstantSDNode>(Src) && cast<ConstantSDNode>(Src)->isZero();
6786 if (!TLI.findOptimalMemOpLowering(
6787 MemOps, TLI.getMaxStoresPerMemset(OptSize),
6788 MemOp::Set(Size, DstAlignCanChange, Alignment, IsZeroVal, isVol),
6789 DstPtrInfo.getAddrSpace(), ~0u, MF.getFunction().getAttributes()))
6790 return SDValue();
6792 if (DstAlignCanChange) {
6793 Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
6794 Align NewAlign = DAG.getDataLayout().getABITypeAlign(Ty);
6795 if (NewAlign > Alignment) {
6796 // Give the stack frame object a larger alignment if needed.
6797 if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
6798 MFI.setObjectAlignment(FI->getIndex(), NewAlign);
6799 Alignment = NewAlign;
6803 SmallVector<SDValue, 8> OutChains;
6804 uint64_t DstOff = 0;
6805 unsigned NumMemOps = MemOps.size();
6807 // Find the largest store and generate the bit pattern for it.
6808 EVT LargestVT = MemOps[0];
6809 for (unsigned i = 1; i < NumMemOps; i++)
6810 if (MemOps[i].bitsGT(LargestVT))
6811 LargestVT = MemOps[i];
6812 SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl);
6814 // Prepare AAInfo for loads/stores after lowering this memset.
6815 AAMDNodes NewAAInfo = AAInfo;
6816 NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
6818 for (unsigned i = 0; i < NumMemOps; i++) {
6819 EVT VT = MemOps[i];
6820 unsigned VTSize = VT.getSizeInBits() / 8;
6821 if (VTSize > Size) {
6822 // Issuing an unaligned load / store pair that overlaps with the previous
6823 // pair. Adjust the offset accordingly.
6824 assert(i == NumMemOps-1 && i != 0);
6825 DstOff -= VTSize - Size;
6828 // If this store is smaller than the largest store see whether we can get
6829 // the smaller value for free with a truncate.
6830 SDValue Value = MemSetValue;
6831 if (VT.bitsLT(LargestVT)) {
6832 if (!LargestVT.isVector() && !VT.isVector() &&
6833 TLI.isTruncateFree(LargestVT, VT))
6834 Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue);
6835 else
6836 Value = getMemsetValue(Src, VT, DAG, dl);
6838 assert(Value.getValueType() == VT && "Value with wrong type.");
6839 SDValue Store = DAG.getStore(
6840 Chain, dl, Value,
6841 DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6842 DstPtrInfo.getWithOffset(DstOff), Alignment,
6843 isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone,
6844 NewAAInfo);
6845 OutChains.push_back(Store);
6846 DstOff += VT.getSizeInBits() / 8;
6847 Size -= VTSize;
6850 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
6853 static void checkAddrSpaceIsValidForLibcall(const TargetLowering *TLI,
6854 unsigned AS) {
6855 // Lowering memcpy / memset / memmove intrinsics to calls is only valid if all
6856 // pointer operands can be losslessly bitcasted to pointers of address space 0
6857 if (AS != 0 && !TLI->getTargetMachine().isNoopAddrSpaceCast(AS, 0)) {
6858 report_fatal_error("cannot lower memory intrinsic in address space " +
6859 Twine(AS));
6863 SDValue SelectionDAG::getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst,
6864 SDValue Src, SDValue Size, Align Alignment,
6865 bool isVol, bool AlwaysInline, bool isTailCall,
6866 MachinePointerInfo DstPtrInfo,
6867 MachinePointerInfo SrcPtrInfo,
6868 const AAMDNodes &AAInfo) {
6869 // Check to see if we should lower the memcpy to loads and stores first.
6870 // For cases within the target-specified limits, this is the best choice.
6871 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6872 if (ConstantSize) {
6873 // Memcpy with size zero? Just return the original chain.
6874 if (ConstantSize->isZero())
6875 return Chain;
6877 SDValue Result = getMemcpyLoadsAndStores(
6878 *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment,
6879 isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo);
6880 if (Result.getNode())
6881 return Result;
6884 // Then check to see if we should lower the memcpy with target-specific
6885 // code. If the target chooses to do this, this is the next best.
6886 if (TSI) {
6887 SDValue Result = TSI->EmitTargetCodeForMemcpy(
6888 *this, dl, Chain, Dst, Src, Size, Alignment, isVol, AlwaysInline,
6889 DstPtrInfo, SrcPtrInfo);
6890 if (Result.getNode())
6891 return Result;
6894 // If we really need inline code and the target declined to provide it,
6895 // use a (potentially long) sequence of loads and stores.
6896 if (AlwaysInline) {
6897 assert(ConstantSize && "AlwaysInline requires a constant size!");
6898 return getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
6899 ConstantSize->getZExtValue(), Alignment,
6900 isVol, true, DstPtrInfo, SrcPtrInfo, AAInfo);
6903 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
6904 checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
6906 // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc
6907 // memcpy is not guaranteed to be safe. libc memcpys aren't required to
6908 // respect volatile, so they may do things like read or write memory
6909 // beyond the given memory regions. But fixing this isn't easy, and most
6910 // people don't care.
6912 // Emit a library call.
6913 TargetLowering::ArgListTy Args;
6914 TargetLowering::ArgListEntry Entry;
6915 Entry.Ty = Type::getInt8PtrTy(*getContext());
6916 Entry.Node = Dst; Args.push_back(Entry);
6917 Entry.Node = Src; Args.push_back(Entry);
6919 Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6920 Entry.Node = Size; Args.push_back(Entry);
6921 // FIXME: pass in SDLoc
6922 TargetLowering::CallLoweringInfo CLI(*this);
6923 CLI.setDebugLoc(dl)
6924 .setChain(Chain)
6925 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMCPY),
6926 Dst.getValueType().getTypeForEVT(*getContext()),
6927 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMCPY),
6928 TLI->getPointerTy(getDataLayout())),
6929 std::move(Args))
6930 .setDiscardResult()
6931 .setTailCall(isTailCall);
6933 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
6934 return CallResult.second;
6937 SDValue SelectionDAG::getAtomicMemcpy(SDValue Chain, const SDLoc &dl,
6938 SDValue Dst, unsigned DstAlign,
6939 SDValue Src, unsigned SrcAlign,
6940 SDValue Size, Type *SizeTy,
6941 unsigned ElemSz, bool isTailCall,
6942 MachinePointerInfo DstPtrInfo,
6943 MachinePointerInfo SrcPtrInfo) {
6944 // Emit a library call.
6945 TargetLowering::ArgListTy Args;
6946 TargetLowering::ArgListEntry Entry;
6947 Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6948 Entry.Node = Dst;
6949 Args.push_back(Entry);
6951 Entry.Node = Src;
6952 Args.push_back(Entry);
6954 Entry.Ty = SizeTy;
6955 Entry.Node = Size;
6956 Args.push_back(Entry);
6958 RTLIB::Libcall LibraryCall =
6959 RTLIB::getMEMCPY_ELEMENT_UNORDERED_ATOMIC(ElemSz);
6960 if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
6961 report_fatal_error("Unsupported element size");
6963 TargetLowering::CallLoweringInfo CLI(*this);
6964 CLI.setDebugLoc(dl)
6965 .setChain(Chain)
6966 .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
6967 Type::getVoidTy(*getContext()),
6968 getExternalSymbol(TLI->getLibcallName(LibraryCall),
6969 TLI->getPointerTy(getDataLayout())),
6970 std::move(Args))
6971 .setDiscardResult()
6972 .setTailCall(isTailCall);
6974 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
6975 return CallResult.second;
6978 SDValue SelectionDAG::getMemmove(SDValue Chain, const SDLoc &dl, SDValue Dst,
6979 SDValue Src, SDValue Size, Align Alignment,
6980 bool isVol, bool isTailCall,
6981 MachinePointerInfo DstPtrInfo,
6982 MachinePointerInfo SrcPtrInfo,
6983 const AAMDNodes &AAInfo) {
6984 // Check to see if we should lower the memmove to loads and stores first.
6985 // For cases within the target-specified limits, this is the best choice.
6986 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6987 if (ConstantSize) {
6988 // Memmove with size zero? Just return the original chain.
6989 if (ConstantSize->isZero())
6990 return Chain;
6992 SDValue Result = getMemmoveLoadsAndStores(
6993 *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment,
6994 isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo);
6995 if (Result.getNode())
6996 return Result;
6999 // Then check to see if we should lower the memmove with target-specific
7000 // code. If the target chooses to do this, this is the next best.
7001 if (TSI) {
7002 SDValue Result =
7003 TSI->EmitTargetCodeForMemmove(*this, dl, Chain, Dst, Src, Size,
7004 Alignment, isVol, DstPtrInfo, SrcPtrInfo);
7005 if (Result.getNode())
7006 return Result;
7009 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
7010 checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
7012 // FIXME: If the memmove is volatile, lowering it to plain libc memmove may
7013 // not be safe. See memcpy above for more details.
7015 // Emit a library call.
7016 TargetLowering::ArgListTy Args;
7017 TargetLowering::ArgListEntry Entry;
7018 Entry.Ty = Type::getInt8PtrTy(*getContext());
7019 Entry.Node = Dst; Args.push_back(Entry);
7020 Entry.Node = Src; Args.push_back(Entry);
7022 Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7023 Entry.Node = Size; Args.push_back(Entry);
7024 // FIXME: pass in SDLoc
7025 TargetLowering::CallLoweringInfo CLI(*this);
7026 CLI.setDebugLoc(dl)
7027 .setChain(Chain)
7028 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMMOVE),
7029 Dst.getValueType().getTypeForEVT(*getContext()),
7030 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMMOVE),
7031 TLI->getPointerTy(getDataLayout())),
7032 std::move(Args))
7033 .setDiscardResult()
7034 .setTailCall(isTailCall);
7036 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
7037 return CallResult.second;
7040 SDValue SelectionDAG::getAtomicMemmove(SDValue Chain, const SDLoc &dl,
7041 SDValue Dst, unsigned DstAlign,
7042 SDValue Src, unsigned SrcAlign,
7043 SDValue Size, Type *SizeTy,
7044 unsigned ElemSz, bool isTailCall,
7045 MachinePointerInfo DstPtrInfo,
7046 MachinePointerInfo SrcPtrInfo) {
7047 // Emit a library call.
7048 TargetLowering::ArgListTy Args;
7049 TargetLowering::ArgListEntry Entry;
7050 Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7051 Entry.Node = Dst;
7052 Args.push_back(Entry);
7054 Entry.Node = Src;
7055 Args.push_back(Entry);
7057 Entry.Ty = SizeTy;
7058 Entry.Node = Size;
7059 Args.push_back(Entry);
7061 RTLIB::Libcall LibraryCall =
7062 RTLIB::getMEMMOVE_ELEMENT_UNORDERED_ATOMIC(ElemSz);
7063 if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
7064 report_fatal_error("Unsupported element size");
7066 TargetLowering::CallLoweringInfo CLI(*this);
7067 CLI.setDebugLoc(dl)
7068 .setChain(Chain)
7069 .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
7070 Type::getVoidTy(*getContext()),
7071 getExternalSymbol(TLI->getLibcallName(LibraryCall),
7072 TLI->getPointerTy(getDataLayout())),
7073 std::move(Args))
7074 .setDiscardResult()
7075 .setTailCall(isTailCall);
7077 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
7078 return CallResult.second;
7081 SDValue SelectionDAG::getMemset(SDValue Chain, const SDLoc &dl, SDValue Dst,
7082 SDValue Src, SDValue Size, Align Alignment,
7083 bool isVol, bool isTailCall,
7084 MachinePointerInfo DstPtrInfo,
7085 const AAMDNodes &AAInfo) {
7086 // Check to see if we should lower the memset to stores first.
7087 // For cases within the target-specified limits, this is the best choice.
7088 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
7089 if (ConstantSize) {
7090 // Memset with size zero? Just return the original chain.
7091 if (ConstantSize->isZero())
7092 return Chain;
7094 SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src,
7095 ConstantSize->getZExtValue(), Alignment,
7096 isVol, DstPtrInfo, AAInfo);
7098 if (Result.getNode())
7099 return Result;
7102 // Then check to see if we should lower the memset with target-specific
7103 // code. If the target chooses to do this, this is the next best.
7104 if (TSI) {
7105 SDValue Result = TSI->EmitTargetCodeForMemset(
7106 *this, dl, Chain, Dst, Src, Size, Alignment, isVol, DstPtrInfo);
7107 if (Result.getNode())
7108 return Result;
7111 checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
7113 // Emit a library call.
7114 TargetLowering::ArgListTy Args;
7115 TargetLowering::ArgListEntry Entry;
7116 Entry.Node = Dst; Entry.Ty = Type::getInt8PtrTy(*getContext());
7117 Args.push_back(Entry);
7118 Entry.Node = Src;
7119 Entry.Ty = Src.getValueType().getTypeForEVT(*getContext());
7120 Args.push_back(Entry);
7121 Entry.Node = Size;
7122 Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7123 Args.push_back(Entry);
7125 // FIXME: pass in SDLoc
7126 TargetLowering::CallLoweringInfo CLI(*this);
7127 CLI.setDebugLoc(dl)
7128 .setChain(Chain)
7129 .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMSET),
7130 Dst.getValueType().getTypeForEVT(*getContext()),
7131 getExternalSymbol(TLI->getLibcallName(RTLIB::MEMSET),
7132 TLI->getPointerTy(getDataLayout())),
7133 std::move(Args))
7134 .setDiscardResult()
7135 .setTailCall(isTailCall);
7137 std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
7138 return CallResult.second;
7141 SDValue SelectionDAG::getAtomicMemset(SDValue Chain, const SDLoc &dl,
7142 SDValue Dst, unsigned DstAlign,
7143 SDValue Value, SDValue Size, Type *SizeTy,
7144 unsigned ElemSz, bool isTailCall,
7145 MachinePointerInfo DstPtrInfo) {
7146 // Emit a library call.
7147 TargetLowering::ArgListTy Args;
7148 TargetLowering::ArgListEntry Entry;
7149 Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7150 Entry.Node = Dst;
7151 Args.push_back(Entry);
7153 Entry.Ty = Type::getInt8Ty(*getContext());
7154 Entry.Node = Value;
7155 Args.push_back(Entry);
7157 Entry.Ty = SizeTy;
7158 Entry.Node = Size;
7159 Args.push_back(Entry);
7161 RTLIB::Libcall LibraryCall =
7162 RTLIB::getMEMSET_ELEMENT_UNORDERED_ATOMIC(ElemSz);
7163 if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
7164 report_fatal_error("Unsupported element size");
7166 TargetLowering::CallLoweringInfo CLI(*this);
7167 CLI.setDebugLoc(dl)
7168 .setChain(Chain)
7169 .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
7170 Type::getVoidTy(*getContext()),
7171 getExternalSymbol(TLI->getLibcallName(LibraryCall),
7172 TLI->getPointerTy(getDataLayout())),
7173 std::move(Args))
7174 .setDiscardResult()
7175 .setTailCall(isTailCall);
7177 std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
7178 return CallResult.second;
7181 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
7182 SDVTList VTList, ArrayRef<SDValue> Ops,
7183 MachineMemOperand *MMO) {
7184 FoldingSetNodeID ID;
7185 ID.AddInteger(MemVT.getRawBits());
7186 AddNodeIDNode(ID, Opcode, VTList, Ops);
7187 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7188 void* IP = nullptr;
7189 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7190 cast<AtomicSDNode>(E)->refineAlignment(MMO);
7191 return SDValue(E, 0);
7194 auto *N = newSDNode<AtomicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
7195 VTList, MemVT, MMO);
7196 createOperands(N, Ops);
7198 CSEMap.InsertNode(N, IP);
7199 InsertNode(N);
7200 return SDValue(N, 0);
7203 SDValue SelectionDAG::getAtomicCmpSwap(unsigned Opcode, const SDLoc &dl,
7204 EVT MemVT, SDVTList VTs, SDValue Chain,
7205 SDValue Ptr, SDValue Cmp, SDValue Swp,
7206 MachineMemOperand *MMO) {
7207 assert(Opcode == ISD::ATOMIC_CMP_SWAP ||
7208 Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
7209 assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
7211 SDValue Ops[] = {Chain, Ptr, Cmp, Swp};
7212 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
7215 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
7216 SDValue Chain, SDValue Ptr, SDValue Val,
7217 MachineMemOperand *MMO) {
7218 assert((Opcode == ISD::ATOMIC_LOAD_ADD ||
7219 Opcode == ISD::ATOMIC_LOAD_SUB ||
7220 Opcode == ISD::ATOMIC_LOAD_AND ||
7221 Opcode == ISD::ATOMIC_LOAD_CLR ||
7222 Opcode == ISD::ATOMIC_LOAD_OR ||
7223 Opcode == ISD::ATOMIC_LOAD_XOR ||
7224 Opcode == ISD::ATOMIC_LOAD_NAND ||
7225 Opcode == ISD::ATOMIC_LOAD_MIN ||
7226 Opcode == ISD::ATOMIC_LOAD_MAX ||
7227 Opcode == ISD::ATOMIC_LOAD_UMIN ||
7228 Opcode == ISD::ATOMIC_LOAD_UMAX ||
7229 Opcode == ISD::ATOMIC_LOAD_FADD ||
7230 Opcode == ISD::ATOMIC_LOAD_FSUB ||
7231 Opcode == ISD::ATOMIC_SWAP ||
7232 Opcode == ISD::ATOMIC_STORE) &&
7233 "Invalid Atomic Op");
7235 EVT VT = Val.getValueType();
7237 SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) :
7238 getVTList(VT, MVT::Other);
7239 SDValue Ops[] = {Chain, Ptr, Val};
7240 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
7243 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
7244 EVT VT, SDValue Chain, SDValue Ptr,
7245 MachineMemOperand *MMO) {
7246 assert(Opcode == ISD::ATOMIC_LOAD && "Invalid Atomic Op");
7248 SDVTList VTs = getVTList(VT, MVT::Other);
7249 SDValue Ops[] = {Chain, Ptr};
7250 return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
7253 /// getMergeValues - Create a MERGE_VALUES node from the given operands.
7254 SDValue SelectionDAG::getMergeValues(ArrayRef<SDValue> Ops, const SDLoc &dl) {
7255 if (Ops.size() == 1)
7256 return Ops[0];
7258 SmallVector<EVT, 4> VTs;
7259 VTs.reserve(Ops.size());
7260 for (const SDValue &Op : Ops)
7261 VTs.push_back(Op.getValueType());
7262 return getNode(ISD::MERGE_VALUES, dl, getVTList(VTs), Ops);
7265 SDValue SelectionDAG::getMemIntrinsicNode(
7266 unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef<SDValue> Ops,
7267 EVT MemVT, MachinePointerInfo PtrInfo, Align Alignment,
7268 MachineMemOperand::Flags Flags, uint64_t Size, const AAMDNodes &AAInfo) {
7269 if (!Size && MemVT.isScalableVector())
7270 Size = MemoryLocation::UnknownSize;
7271 else if (!Size)
7272 Size = MemVT.getStoreSize();
7274 MachineFunction &MF = getMachineFunction();
7275 MachineMemOperand *MMO =
7276 MF.getMachineMemOperand(PtrInfo, Flags, Size, Alignment, AAInfo);
7278 return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, MMO);
7281 SDValue SelectionDAG::getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl,
7282 SDVTList VTList,
7283 ArrayRef<SDValue> Ops, EVT MemVT,
7284 MachineMemOperand *MMO) {
7285 assert((Opcode == ISD::INTRINSIC_VOID ||
7286 Opcode == ISD::INTRINSIC_W_CHAIN ||
7287 Opcode == ISD::PREFETCH ||
7288 ((int)Opcode <= std::numeric_limits<int>::max() &&
7289 (int)Opcode >= ISD::FIRST_TARGET_MEMORY_OPCODE)) &&
7290 "Opcode is not a memory-accessing opcode!");
7292 // Memoize the node unless it returns a flag.
7293 MemIntrinsicSDNode *N;
7294 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
7295 FoldingSetNodeID ID;
7296 AddNodeIDNode(ID, Opcode, VTList, Ops);
7297 ID.AddInteger(getSyntheticNodeSubclassData<MemIntrinsicSDNode>(
7298 Opcode, dl.getIROrder(), VTList, MemVT, MMO));
7299 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7300 void *IP = nullptr;
7301 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7302 cast<MemIntrinsicSDNode>(E)->refineAlignment(MMO);
7303 return SDValue(E, 0);
7306 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
7307 VTList, MemVT, MMO);
7308 createOperands(N, Ops);
7310 CSEMap.InsertNode(N, IP);
7311 } else {
7312 N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
7313 VTList, MemVT, MMO);
7314 createOperands(N, Ops);
7316 InsertNode(N);
7317 SDValue V(N, 0);
7318 NewSDValueDbgMsg(V, "Creating new node: ", this);
7319 return V;
7322 SDValue SelectionDAG::getLifetimeNode(bool IsStart, const SDLoc &dl,
7323 SDValue Chain, int FrameIndex,
7324 int64_t Size, int64_t Offset) {
7325 const unsigned Opcode = IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END;
7326 const auto VTs = getVTList(MVT::Other);
7327 SDValue Ops[2] = {
7328 Chain,
7329 getFrameIndex(FrameIndex,
7330 getTargetLoweringInfo().getFrameIndexTy(getDataLayout()),
7331 true)};
7333 FoldingSetNodeID ID;
7334 AddNodeIDNode(ID, Opcode, VTs, Ops);
7335 ID.AddInteger(FrameIndex);
7336 ID.AddInteger(Size);
7337 ID.AddInteger(Offset);
7338 void *IP = nullptr;
7339 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
7340 return SDValue(E, 0);
7342 LifetimeSDNode *N = newSDNode<LifetimeSDNode>(
7343 Opcode, dl.getIROrder(), dl.getDebugLoc(), VTs, Size, Offset);
7344 createOperands(N, Ops);
7345 CSEMap.InsertNode(N, IP);
7346 InsertNode(N);
7347 SDValue V(N, 0);
7348 NewSDValueDbgMsg(V, "Creating new node: ", this);
7349 return V;
7352 SDValue SelectionDAG::getPseudoProbeNode(const SDLoc &Dl, SDValue Chain,
7353 uint64_t Guid, uint64_t Index,
7354 uint32_t Attr) {
7355 const unsigned Opcode = ISD::PSEUDO_PROBE;
7356 const auto VTs = getVTList(MVT::Other);
7357 SDValue Ops[] = {Chain};
7358 FoldingSetNodeID ID;
7359 AddNodeIDNode(ID, Opcode, VTs, Ops);
7360 ID.AddInteger(Guid);
7361 ID.AddInteger(Index);
7362 void *IP = nullptr;
7363 if (SDNode *E = FindNodeOrInsertPos(ID, Dl, IP))
7364 return SDValue(E, 0);
7366 auto *N = newSDNode<PseudoProbeSDNode>(
7367 Opcode, Dl.getIROrder(), Dl.getDebugLoc(), VTs, Guid, Index, Attr);
7368 createOperands(N, Ops);
7369 CSEMap.InsertNode(N, IP);
7370 InsertNode(N);
7371 SDValue V(N, 0);
7372 NewSDValueDbgMsg(V, "Creating new node: ", this);
7373 return V;
7376 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
7377 /// MachinePointerInfo record from it. This is particularly useful because the
7378 /// code generator has many cases where it doesn't bother passing in a
7379 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
7380 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info,
7381 SelectionDAG &DAG, SDValue Ptr,
7382 int64_t Offset = 0) {
7383 // If this is FI+Offset, we can model it.
7384 if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr))
7385 return MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
7386 FI->getIndex(), Offset);
7388 // If this is (FI+Offset1)+Offset2, we can model it.
7389 if (Ptr.getOpcode() != ISD::ADD ||
7390 !isa<ConstantSDNode>(Ptr.getOperand(1)) ||
7391 !isa<FrameIndexSDNode>(Ptr.getOperand(0)))
7392 return Info;
7394 int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
7395 return MachinePointerInfo::getFixedStack(
7396 DAG.getMachineFunction(), FI,
7397 Offset + cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue());
7400 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
7401 /// MachinePointerInfo record from it. This is particularly useful because the
7402 /// code generator has many cases where it doesn't bother passing in a
7403 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
7404 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info,
7405 SelectionDAG &DAG, SDValue Ptr,
7406 SDValue OffsetOp) {
7407 // If the 'Offset' value isn't a constant, we can't handle this.
7408 if (ConstantSDNode *OffsetNode = dyn_cast<ConstantSDNode>(OffsetOp))
7409 return InferPointerInfo(Info, DAG, Ptr, OffsetNode->getSExtValue());
7410 if (OffsetOp.isUndef())
7411 return InferPointerInfo(Info, DAG, Ptr);
7412 return Info;
7415 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
7416 EVT VT, const SDLoc &dl, SDValue Chain,
7417 SDValue Ptr, SDValue Offset,
7418 MachinePointerInfo PtrInfo, EVT MemVT,
7419 Align Alignment,
7420 MachineMemOperand::Flags MMOFlags,
7421 const AAMDNodes &AAInfo, const MDNode *Ranges) {
7422 assert(Chain.getValueType() == MVT::Other &&
7423 "Invalid chain type");
7425 MMOFlags |= MachineMemOperand::MOLoad;
7426 assert((MMOFlags & MachineMemOperand::MOStore) == 0);
7427 // If we don't have a PtrInfo, infer the trivial frame index case to simplify
7428 // clients.
7429 if (PtrInfo.V.isNull())
7430 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
7432 uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize());
7433 MachineFunction &MF = getMachineFunction();
7434 MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size,
7435 Alignment, AAInfo, Ranges);
7436 return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO);
7439 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
7440 EVT VT, const SDLoc &dl, SDValue Chain,
7441 SDValue Ptr, SDValue Offset, EVT MemVT,
7442 MachineMemOperand *MMO) {
7443 if (VT == MemVT) {
7444 ExtType = ISD::NON_EXTLOAD;
7445 } else if (ExtType == ISD::NON_EXTLOAD) {
7446 assert(VT == MemVT && "Non-extending load from different memory type!");
7447 } else {
7448 // Extending load.
7449 assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) &&
7450 "Should only be an extending load, not truncating!");
7451 assert(VT.isInteger() == MemVT.isInteger() &&
7452 "Cannot convert from FP to Int or Int -> FP!");
7453 assert(VT.isVector() == MemVT.isVector() &&
7454 "Cannot use an ext load to convert to or from a vector!");
7455 assert((!VT.isVector() ||
7456 VT.getVectorElementCount() == MemVT.getVectorElementCount()) &&
7457 "Cannot use an ext load to change the number of vector elements!");
7460 bool Indexed = AM != ISD::UNINDEXED;
7461 assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
7463 SDVTList VTs = Indexed ?
7464 getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
7465 SDValue Ops[] = { Chain, Ptr, Offset };
7466 FoldingSetNodeID ID;
7467 AddNodeIDNode(ID, ISD::LOAD, VTs, Ops);
7468 ID.AddInteger(MemVT.getRawBits());
7469 ID.AddInteger(getSyntheticNodeSubclassData<LoadSDNode>(
7470 dl.getIROrder(), VTs, AM, ExtType, MemVT, MMO));
7471 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7472 void *IP = nullptr;
7473 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7474 cast<LoadSDNode>(E)->refineAlignment(MMO);
7475 return SDValue(E, 0);
7477 auto *N = newSDNode<LoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
7478 ExtType, MemVT, MMO);
7479 createOperands(N, Ops);
7481 CSEMap.InsertNode(N, IP);
7482 InsertNode(N);
7483 SDValue V(N, 0);
7484 NewSDValueDbgMsg(V, "Creating new node: ", this);
7485 return V;
7488 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
7489 SDValue Ptr, MachinePointerInfo PtrInfo,
7490 MaybeAlign Alignment,
7491 MachineMemOperand::Flags MMOFlags,
7492 const AAMDNodes &AAInfo, const MDNode *Ranges) {
7493 SDValue Undef = getUNDEF(Ptr.getValueType());
7494 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7495 PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges);
7498 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
7499 SDValue Ptr, MachineMemOperand *MMO) {
7500 SDValue Undef = getUNDEF(Ptr.getValueType());
7501 return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7502 VT, MMO);
7505 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
7506 EVT VT, SDValue Chain, SDValue Ptr,
7507 MachinePointerInfo PtrInfo, EVT MemVT,
7508 MaybeAlign Alignment,
7509 MachineMemOperand::Flags MMOFlags,
7510 const AAMDNodes &AAInfo) {
7511 SDValue Undef = getUNDEF(Ptr.getValueType());
7512 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, PtrInfo,
7513 MemVT, Alignment, MMOFlags, AAInfo);
7516 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
7517 EVT VT, SDValue Chain, SDValue Ptr, EVT MemVT,
7518 MachineMemOperand *MMO) {
7519 SDValue Undef = getUNDEF(Ptr.getValueType());
7520 return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef,
7521 MemVT, MMO);
7524 SDValue SelectionDAG::getIndexedLoad(SDValue OrigLoad, const SDLoc &dl,
7525 SDValue Base, SDValue Offset,
7526 ISD::MemIndexedMode AM) {
7527 LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
7528 assert(LD->getOffset().isUndef() && "Load is already a indexed load!");
7529 // Don't propagate the invariant or dereferenceable flags.
7530 auto MMOFlags =
7531 LD->getMemOperand()->getFlags() &
7532 ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
7533 return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
7534 LD->getChain(), Base, Offset, LD->getPointerInfo(),
7535 LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo());
7538 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7539 SDValue Ptr, MachinePointerInfo PtrInfo,
7540 Align Alignment,
7541 MachineMemOperand::Flags MMOFlags,
7542 const AAMDNodes &AAInfo) {
7543 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
7545 MMOFlags |= MachineMemOperand::MOStore;
7546 assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
7548 if (PtrInfo.V.isNull())
7549 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
7551 MachineFunction &MF = getMachineFunction();
7552 uint64_t Size =
7553 MemoryLocation::getSizeOrUnknown(Val.getValueType().getStoreSize());
7554 MachineMemOperand *MMO =
7555 MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, Alignment, AAInfo);
7556 return getStore(Chain, dl, Val, Ptr, MMO);
7559 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7560 SDValue Ptr, MachineMemOperand *MMO) {
7561 assert(Chain.getValueType() == MVT::Other &&
7562 "Invalid chain type");
7563 EVT VT = Val.getValueType();
7564 SDVTList VTs = getVTList(MVT::Other);
7565 SDValue Undef = getUNDEF(Ptr.getValueType());
7566 SDValue Ops[] = { Chain, Val, Ptr, Undef };
7567 FoldingSetNodeID ID;
7568 AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7569 ID.AddInteger(VT.getRawBits());
7570 ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
7571 dl.getIROrder(), VTs, ISD::UNINDEXED, false, VT, MMO));
7572 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7573 void *IP = nullptr;
7574 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7575 cast<StoreSDNode>(E)->refineAlignment(MMO);
7576 return SDValue(E, 0);
7578 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7579 ISD::UNINDEXED, false, VT, MMO);
7580 createOperands(N, Ops);
7582 CSEMap.InsertNode(N, IP);
7583 InsertNode(N);
7584 SDValue V(N, 0);
7585 NewSDValueDbgMsg(V, "Creating new node: ", this);
7586 return V;
7589 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7590 SDValue Ptr, MachinePointerInfo PtrInfo,
7591 EVT SVT, Align Alignment,
7592 MachineMemOperand::Flags MMOFlags,
7593 const AAMDNodes &AAInfo) {
7594 assert(Chain.getValueType() == MVT::Other &&
7595 "Invalid chain type");
7597 MMOFlags |= MachineMemOperand::MOStore;
7598 assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
7600 if (PtrInfo.V.isNull())
7601 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
7603 MachineFunction &MF = getMachineFunction();
7604 MachineMemOperand *MMO = MF.getMachineMemOperand(
7605 PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()),
7606 Alignment, AAInfo);
7607 return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO);
7610 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7611 SDValue Ptr, EVT SVT,
7612 MachineMemOperand *MMO) {
7613 EVT VT = Val.getValueType();
7615 assert(Chain.getValueType() == MVT::Other &&
7616 "Invalid chain type");
7617 if (VT == SVT)
7618 return getStore(Chain, dl, Val, Ptr, MMO);
7620 assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
7621 "Should only be a truncating store, not extending!");
7622 assert(VT.isInteger() == SVT.isInteger() &&
7623 "Can't do FP-INT conversion!");
7624 assert(VT.isVector() == SVT.isVector() &&
7625 "Cannot use trunc store to convert to or from a vector!");
7626 assert((!VT.isVector() ||
7627 VT.getVectorElementCount() == SVT.getVectorElementCount()) &&
7628 "Cannot use trunc store to change the number of vector elements!");
7630 SDVTList VTs = getVTList(MVT::Other);
7631 SDValue Undef = getUNDEF(Ptr.getValueType());
7632 SDValue Ops[] = { Chain, Val, Ptr, Undef };
7633 FoldingSetNodeID ID;
7634 AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7635 ID.AddInteger(SVT.getRawBits());
7636 ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
7637 dl.getIROrder(), VTs, ISD::UNINDEXED, true, SVT, MMO));
7638 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7639 void *IP = nullptr;
7640 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7641 cast<StoreSDNode>(E)->refineAlignment(MMO);
7642 return SDValue(E, 0);
7644 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7645 ISD::UNINDEXED, true, SVT, MMO);
7646 createOperands(N, Ops);
7648 CSEMap.InsertNode(N, IP);
7649 InsertNode(N);
7650 SDValue V(N, 0);
7651 NewSDValueDbgMsg(V, "Creating new node: ", this);
7652 return V;
7655 SDValue SelectionDAG::getIndexedStore(SDValue OrigStore, const SDLoc &dl,
7656 SDValue Base, SDValue Offset,
7657 ISD::MemIndexedMode AM) {
7658 StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
7659 assert(ST->getOffset().isUndef() && "Store is already a indexed store!");
7660 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
7661 SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
7662 FoldingSetNodeID ID;
7663 AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7664 ID.AddInteger(ST->getMemoryVT().getRawBits());
7665 ID.AddInteger(ST->getRawSubclassData());
7666 ID.AddInteger(ST->getPointerInfo().getAddrSpace());
7667 void *IP = nullptr;
7668 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
7669 return SDValue(E, 0);
7671 auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
7672 ST->isTruncatingStore(), ST->getMemoryVT(),
7673 ST->getMemOperand());
7674 createOperands(N, Ops);
7676 CSEMap.InsertNode(N, IP);
7677 InsertNode(N);
7678 SDValue V(N, 0);
7679 NewSDValueDbgMsg(V, "Creating new node: ", this);
7680 return V;
7683 SDValue SelectionDAG::getLoadVP(
7684 ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &dl,
7685 SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Mask, SDValue EVL,
7686 MachinePointerInfo PtrInfo, EVT MemVT, Align Alignment,
7687 MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
7688 const MDNode *Ranges, bool IsExpanding) {
7689 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
7691 MMOFlags |= MachineMemOperand::MOLoad;
7692 assert((MMOFlags & MachineMemOperand::MOStore) == 0);
7693 // If we don't have a PtrInfo, infer the trivial frame index case to simplify
7694 // clients.
7695 if (PtrInfo.V.isNull())
7696 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
7698 uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize());
7699 MachineFunction &MF = getMachineFunction();
7700 MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size,
7701 Alignment, AAInfo, Ranges);
7702 return getLoadVP(AM, ExtType, VT, dl, Chain, Ptr, Offset, Mask, EVL, MemVT,
7703 MMO, IsExpanding);
7706 SDValue SelectionDAG::getLoadVP(ISD::MemIndexedMode AM,
7707 ISD::LoadExtType ExtType, EVT VT,
7708 const SDLoc &dl, SDValue Chain, SDValue Ptr,
7709 SDValue Offset, SDValue Mask, SDValue EVL,
7710 EVT MemVT, MachineMemOperand *MMO,
7711 bool IsExpanding) {
7712 bool Indexed = AM != ISD::UNINDEXED;
7713 assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
7715 SDVTList VTs = Indexed ? getVTList(VT, Ptr.getValueType(), MVT::Other)
7716 : getVTList(VT, MVT::Other);
7717 SDValue Ops[] = {Chain, Ptr, Offset, Mask, EVL};
7718 FoldingSetNodeID ID;
7719 AddNodeIDNode(ID, ISD::VP_LOAD, VTs, Ops);
7720 ID.AddInteger(VT.getRawBits());
7721 ID.AddInteger(getSyntheticNodeSubclassData<VPLoadSDNode>(
7722 dl.getIROrder(), VTs, AM, ExtType, IsExpanding, MemVT, MMO));
7723 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7724 void *IP = nullptr;
7725 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7726 cast<VPLoadSDNode>(E)->refineAlignment(MMO);
7727 return SDValue(E, 0);
7729 auto *N = newSDNode<VPLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
7730 ExtType, IsExpanding, MemVT, MMO);
7731 createOperands(N, Ops);
7733 CSEMap.InsertNode(N, IP);
7734 InsertNode(N);
7735 SDValue V(N, 0);
7736 NewSDValueDbgMsg(V, "Creating new node: ", this);
7737 return V;
7740 SDValue SelectionDAG::getLoadVP(EVT VT, const SDLoc &dl, SDValue Chain,
7741 SDValue Ptr, SDValue Mask, SDValue EVL,
7742 MachinePointerInfo PtrInfo,
7743 MaybeAlign Alignment,
7744 MachineMemOperand::Flags MMOFlags,
7745 const AAMDNodes &AAInfo, const MDNode *Ranges,
7746 bool IsExpanding) {
7747 SDValue Undef = getUNDEF(Ptr.getValueType());
7748 return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7749 Mask, EVL, PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges,
7750 IsExpanding);
7753 SDValue SelectionDAG::getLoadVP(EVT VT, const SDLoc &dl, SDValue Chain,
7754 SDValue Ptr, SDValue Mask, SDValue EVL,
7755 MachineMemOperand *MMO, bool IsExpanding) {
7756 SDValue Undef = getUNDEF(Ptr.getValueType());
7757 return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7758 Mask, EVL, VT, MMO, IsExpanding);
7761 SDValue SelectionDAG::getExtLoadVP(ISD::LoadExtType ExtType, const SDLoc &dl,
7762 EVT VT, SDValue Chain, SDValue Ptr,
7763 SDValue Mask, SDValue EVL,
7764 MachinePointerInfo PtrInfo, EVT MemVT,
7765 MaybeAlign Alignment,
7766 MachineMemOperand::Flags MMOFlags,
7767 const AAMDNodes &AAInfo, bool IsExpanding) {
7768 SDValue Undef = getUNDEF(Ptr.getValueType());
7769 return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask,
7770 EVL, PtrInfo, MemVT, Alignment, MMOFlags, AAInfo, nullptr,
7771 IsExpanding);
7774 SDValue SelectionDAG::getExtLoadVP(ISD::LoadExtType ExtType, const SDLoc &dl,
7775 EVT VT, SDValue Chain, SDValue Ptr,
7776 SDValue Mask, SDValue EVL, EVT MemVT,
7777 MachineMemOperand *MMO, bool IsExpanding) {
7778 SDValue Undef = getUNDEF(Ptr.getValueType());
7779 return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask,
7780 EVL, MemVT, MMO, IsExpanding);
7783 SDValue SelectionDAG::getIndexedLoadVP(SDValue OrigLoad, const SDLoc &dl,
7784 SDValue Base, SDValue Offset,
7785 ISD::MemIndexedMode AM) {
7786 auto *LD = cast<VPLoadSDNode>(OrigLoad);
7787 assert(LD->getOffset().isUndef() && "Load is already a indexed load!");
7788 // Don't propagate the invariant or dereferenceable flags.
7789 auto MMOFlags =
7790 LD->getMemOperand()->getFlags() &
7791 ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
7792 return getLoadVP(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
7793 LD->getChain(), Base, Offset, LD->getMask(),
7794 LD->getVectorLength(), LD->getPointerInfo(),
7795 LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo(),
7796 nullptr, LD->isExpandingLoad());
7799 SDValue SelectionDAG::getStoreVP(SDValue Chain, const SDLoc &dl, SDValue Val,
7800 SDValue Ptr, SDValue Offset, SDValue Mask,
7801 SDValue EVL, EVT MemVT, MachineMemOperand *MMO,
7802 ISD::MemIndexedMode AM, bool IsTruncating,
7803 bool IsCompressing) {
7804 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
7805 bool Indexed = AM != ISD::UNINDEXED;
7806 assert((Indexed || Offset.isUndef()) && "Unindexed vp_store with an offset!");
7807 SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other)
7808 : getVTList(MVT::Other);
7809 SDValue Ops[] = {Chain, Val, Ptr, Offset, Mask, EVL};
7810 FoldingSetNodeID ID;
7811 AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
7812 ID.AddInteger(MemVT.getRawBits());
7813 ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>(
7814 dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
7815 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7816 void *IP = nullptr;
7817 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7818 cast<VPStoreSDNode>(E)->refineAlignment(MMO);
7819 return SDValue(E, 0);
7821 auto *N = newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
7822 IsTruncating, IsCompressing, MemVT, MMO);
7823 createOperands(N, Ops);
7825 CSEMap.InsertNode(N, IP);
7826 InsertNode(N);
7827 SDValue V(N, 0);
7828 NewSDValueDbgMsg(V, "Creating new node: ", this);
7829 return V;
7832 SDValue SelectionDAG::getTruncStoreVP(SDValue Chain, const SDLoc &dl,
7833 SDValue Val, SDValue Ptr, SDValue Mask,
7834 SDValue EVL, MachinePointerInfo PtrInfo,
7835 EVT SVT, Align Alignment,
7836 MachineMemOperand::Flags MMOFlags,
7837 const AAMDNodes &AAInfo,
7838 bool IsCompressing) {
7839 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
7841 MMOFlags |= MachineMemOperand::MOStore;
7842 assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
7844 if (PtrInfo.V.isNull())
7845 PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
7847 MachineFunction &MF = getMachineFunction();
7848 MachineMemOperand *MMO = MF.getMachineMemOperand(
7849 PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()),
7850 Alignment, AAInfo);
7851 return getTruncStoreVP(Chain, dl, Val, Ptr, Mask, EVL, SVT, MMO,
7852 IsCompressing);
7855 SDValue SelectionDAG::getTruncStoreVP(SDValue Chain, const SDLoc &dl,
7856 SDValue Val, SDValue Ptr, SDValue Mask,
7857 SDValue EVL, EVT SVT,
7858 MachineMemOperand *MMO,
7859 bool IsCompressing) {
7860 EVT VT = Val.getValueType();
7862 assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
7863 if (VT == SVT)
7864 return getStoreVP(Chain, dl, Val, Ptr, getUNDEF(Ptr.getValueType()), Mask,
7865 EVL, VT, MMO, ISD::UNINDEXED,
7866 /*IsTruncating*/ false, IsCompressing);
7868 assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
7869 "Should only be a truncating store, not extending!");
7870 assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!");
7871 assert(VT.isVector() == SVT.isVector() &&
7872 "Cannot use trunc store to convert to or from a vector!");
7873 assert((!VT.isVector() ||
7874 VT.getVectorElementCount() == SVT.getVectorElementCount()) &&
7875 "Cannot use trunc store to change the number of vector elements!");
7877 SDVTList VTs = getVTList(MVT::Other);
7878 SDValue Undef = getUNDEF(Ptr.getValueType());
7879 SDValue Ops[] = {Chain, Val, Ptr, Undef, Mask, EVL};
7880 FoldingSetNodeID ID;
7881 AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
7882 ID.AddInteger(SVT.getRawBits());
7883 ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>(
7884 dl.getIROrder(), VTs, ISD::UNINDEXED, true, IsCompressing, SVT, MMO));
7885 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7886 void *IP = nullptr;
7887 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7888 cast<VPStoreSDNode>(E)->refineAlignment(MMO);
7889 return SDValue(E, 0);
7891 auto *N =
7892 newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7893 ISD::UNINDEXED, true, IsCompressing, SVT, MMO);
7894 createOperands(N, Ops);
7896 CSEMap.InsertNode(N, IP);
7897 InsertNode(N);
7898 SDValue V(N, 0);
7899 NewSDValueDbgMsg(V, "Creating new node: ", this);
7900 return V;
7903 SDValue SelectionDAG::getIndexedStoreVP(SDValue OrigStore, const SDLoc &dl,
7904 SDValue Base, SDValue Offset,
7905 ISD::MemIndexedMode AM) {
7906 auto *ST = cast<VPStoreSDNode>(OrigStore);
7907 assert(ST->getOffset().isUndef() && "Store is already an indexed store!");
7908 SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
7909 SDValue Ops[] = {ST->getChain(), ST->getValue(), Base,
7910 Offset, ST->getMask(), ST->getVectorLength()};
7911 FoldingSetNodeID ID;
7912 AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
7913 ID.AddInteger(ST->getMemoryVT().getRawBits());
7914 ID.AddInteger(ST->getRawSubclassData());
7915 ID.AddInteger(ST->getPointerInfo().getAddrSpace());
7916 void *IP = nullptr;
7917 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
7918 return SDValue(E, 0);
7920 auto *N = newSDNode<VPStoreSDNode>(
7921 dl.getIROrder(), dl.getDebugLoc(), VTs, AM, ST->isTruncatingStore(),
7922 ST->isCompressingStore(), ST->getMemoryVT(), ST->getMemOperand());
7923 createOperands(N, Ops);
7925 CSEMap.InsertNode(N, IP);
7926 InsertNode(N);
7927 SDValue V(N, 0);
7928 NewSDValueDbgMsg(V, "Creating new node: ", this);
7929 return V;
7932 SDValue SelectionDAG::getGatherVP(SDVTList VTs, EVT VT, const SDLoc &dl,
7933 ArrayRef<SDValue> Ops, MachineMemOperand *MMO,
7934 ISD::MemIndexType IndexType) {
7935 assert(Ops.size() == 6 && "Incompatible number of operands");
7937 FoldingSetNodeID ID;
7938 AddNodeIDNode(ID, ISD::VP_GATHER, VTs, Ops);
7939 ID.AddInteger(VT.getRawBits());
7940 ID.AddInteger(getSyntheticNodeSubclassData<VPGatherSDNode>(
7941 dl.getIROrder(), VTs, VT, MMO, IndexType));
7942 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7943 void *IP = nullptr;
7944 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7945 cast<VPGatherSDNode>(E)->refineAlignment(MMO);
7946 return SDValue(E, 0);
7949 auto *N = newSDNode<VPGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7950 VT, MMO, IndexType);
7951 createOperands(N, Ops);
7953 assert(N->getMask().getValueType().getVectorElementCount() ==
7954 N->getValueType(0).getVectorElementCount() &&
7955 "Vector width mismatch between mask and data");
7956 assert(N->getIndex().getValueType().getVectorElementCount().isScalable() ==
7957 N->getValueType(0).getVectorElementCount().isScalable() &&
7958 "Scalable flags of index and data do not match");
7959 assert(ElementCount::isKnownGE(
7960 N->getIndex().getValueType().getVectorElementCount(),
7961 N->getValueType(0).getVectorElementCount()) &&
7962 "Vector width mismatch between index and data");
7963 assert(isa<ConstantSDNode>(N->getScale()) &&
7964 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
7965 "Scale should be a constant power of 2");
7967 CSEMap.InsertNode(N, IP);
7968 InsertNode(N);
7969 SDValue V(N, 0);
7970 NewSDValueDbgMsg(V, "Creating new node: ", this);
7971 return V;
7974 SDValue SelectionDAG::getScatterVP(SDVTList VTs, EVT VT, const SDLoc &dl,
7975 ArrayRef<SDValue> Ops,
7976 MachineMemOperand *MMO,
7977 ISD::MemIndexType IndexType) {
7978 assert(Ops.size() == 7 && "Incompatible number of operands");
7980 FoldingSetNodeID ID;
7981 AddNodeIDNode(ID, ISD::VP_SCATTER, VTs, Ops);
7982 ID.AddInteger(VT.getRawBits());
7983 ID.AddInteger(getSyntheticNodeSubclassData<VPScatterSDNode>(
7984 dl.getIROrder(), VTs, VT, MMO, IndexType));
7985 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7986 void *IP = nullptr;
7987 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7988 cast<VPScatterSDNode>(E)->refineAlignment(MMO);
7989 return SDValue(E, 0);
7991 auto *N = newSDNode<VPScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7992 VT, MMO, IndexType);
7993 createOperands(N, Ops);
7995 assert(N->getMask().getValueType().getVectorElementCount() ==
7996 N->getValue().getValueType().getVectorElementCount() &&
7997 "Vector width mismatch between mask and data");
7998 assert(
7999 N->getIndex().getValueType().getVectorElementCount().isScalable() ==
8000 N->getValue().getValueType().getVectorElementCount().isScalable() &&
8001 "Scalable flags of index and data do not match");
8002 assert(ElementCount::isKnownGE(
8003 N->getIndex().getValueType().getVectorElementCount(),
8004 N->getValue().getValueType().getVectorElementCount()) &&
8005 "Vector width mismatch between index and data");
8006 assert(isa<ConstantSDNode>(N->getScale()) &&
8007 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
8008 "Scale should be a constant power of 2");
8010 CSEMap.InsertNode(N, IP);
8011 InsertNode(N);
8012 SDValue V(N, 0);
8013 NewSDValueDbgMsg(V, "Creating new node: ", this);
8014 return V;
8017 SDValue SelectionDAG::getMaskedLoad(EVT VT, const SDLoc &dl, SDValue Chain,
8018 SDValue Base, SDValue Offset, SDValue Mask,
8019 SDValue PassThru, EVT MemVT,
8020 MachineMemOperand *MMO,
8021 ISD::MemIndexedMode AM,
8022 ISD::LoadExtType ExtTy, bool isExpanding) {
8023 bool Indexed = AM != ISD::UNINDEXED;
8024 assert((Indexed || Offset.isUndef()) &&
8025 "Unindexed masked load with an offset!");
8026 SDVTList VTs = Indexed ? getVTList(VT, Base.getValueType(), MVT::Other)
8027 : getVTList(VT, MVT::Other);
8028 SDValue Ops[] = {Chain, Base, Offset, Mask, PassThru};
8029 FoldingSetNodeID ID;
8030 AddNodeIDNode(ID, ISD::MLOAD, VTs, Ops);
8031 ID.AddInteger(MemVT.getRawBits());
8032 ID.AddInteger(getSyntheticNodeSubclassData<MaskedLoadSDNode>(
8033 dl.getIROrder(), VTs, AM, ExtTy, isExpanding, MemVT, MMO));
8034 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8035 void *IP = nullptr;
8036 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8037 cast<MaskedLoadSDNode>(E)->refineAlignment(MMO);
8038 return SDValue(E, 0);
8040 auto *N = newSDNode<MaskedLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
8041 AM, ExtTy, isExpanding, MemVT, MMO);
8042 createOperands(N, Ops);
8044 CSEMap.InsertNode(N, IP);
8045 InsertNode(N);
8046 SDValue V(N, 0);
8047 NewSDValueDbgMsg(V, "Creating new node: ", this);
8048 return V;
8051 SDValue SelectionDAG::getIndexedMaskedLoad(SDValue OrigLoad, const SDLoc &dl,
8052 SDValue Base, SDValue Offset,
8053 ISD::MemIndexedMode AM) {
8054 MaskedLoadSDNode *LD = cast<MaskedLoadSDNode>(OrigLoad);
8055 assert(LD->getOffset().isUndef() && "Masked load is already a indexed load!");
8056 return getMaskedLoad(OrigLoad.getValueType(), dl, LD->getChain(), Base,
8057 Offset, LD->getMask(), LD->getPassThru(),
8058 LD->getMemoryVT(), LD->getMemOperand(), AM,
8059 LD->getExtensionType(), LD->isExpandingLoad());
8062 SDValue SelectionDAG::getMaskedStore(SDValue Chain, const SDLoc &dl,
8063 SDValue Val, SDValue Base, SDValue Offset,
8064 SDValue Mask, EVT MemVT,
8065 MachineMemOperand *MMO,
8066 ISD::MemIndexedMode AM, bool IsTruncating,
8067 bool IsCompressing) {
8068 assert(Chain.getValueType() == MVT::Other &&
8069 "Invalid chain type");
8070 bool Indexed = AM != ISD::UNINDEXED;
8071 assert((Indexed || Offset.isUndef()) &&
8072 "Unindexed masked store with an offset!");
8073 SDVTList VTs = Indexed ? getVTList(Base.getValueType(), MVT::Other)
8074 : getVTList(MVT::Other);
8075 SDValue Ops[] = {Chain, Val, Base, Offset, Mask};
8076 FoldingSetNodeID ID;
8077 AddNodeIDNode(ID, ISD::MSTORE, VTs, Ops);
8078 ID.AddInteger(MemVT.getRawBits());
8079 ID.AddInteger(getSyntheticNodeSubclassData<MaskedStoreSDNode>(
8080 dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
8081 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8082 void *IP = nullptr;
8083 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8084 cast<MaskedStoreSDNode>(E)->refineAlignment(MMO);
8085 return SDValue(E, 0);
8087 auto *N =
8088 newSDNode<MaskedStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
8089 IsTruncating, IsCompressing, MemVT, MMO);
8090 createOperands(N, Ops);
8092 CSEMap.InsertNode(N, IP);
8093 InsertNode(N);
8094 SDValue V(N, 0);
8095 NewSDValueDbgMsg(V, "Creating new node: ", this);
8096 return V;
8099 SDValue SelectionDAG::getIndexedMaskedStore(SDValue OrigStore, const SDLoc &dl,
8100 SDValue Base, SDValue Offset,
8101 ISD::MemIndexedMode AM) {
8102 MaskedStoreSDNode *ST = cast<MaskedStoreSDNode>(OrigStore);
8103 assert(ST->getOffset().isUndef() &&
8104 "Masked store is already a indexed store!");
8105 return getMaskedStore(ST->getChain(), dl, ST->getValue(), Base, Offset,
8106 ST->getMask(), ST->getMemoryVT(), ST->getMemOperand(),
8107 AM, ST->isTruncatingStore(), ST->isCompressingStore());
8110 SDValue SelectionDAG::getMaskedGather(SDVTList VTs, EVT MemVT, const SDLoc &dl,
8111 ArrayRef<SDValue> Ops,
8112 MachineMemOperand *MMO,
8113 ISD::MemIndexType IndexType,
8114 ISD::LoadExtType ExtTy) {
8115 assert(Ops.size() == 6 && "Incompatible number of operands");
8117 FoldingSetNodeID ID;
8118 AddNodeIDNode(ID, ISD::MGATHER, VTs, Ops);
8119 ID.AddInteger(MemVT.getRawBits());
8120 ID.AddInteger(getSyntheticNodeSubclassData<MaskedGatherSDNode>(
8121 dl.getIROrder(), VTs, MemVT, MMO, IndexType, ExtTy));
8122 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8123 void *IP = nullptr;
8124 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8125 cast<MaskedGatherSDNode>(E)->refineAlignment(MMO);
8126 return SDValue(E, 0);
8129 IndexType = TLI->getCanonicalIndexType(IndexType, MemVT, Ops[4]);
8130 auto *N = newSDNode<MaskedGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(),
8131 VTs, MemVT, MMO, IndexType, ExtTy);
8132 createOperands(N, Ops);
8134 assert(N->getPassThru().getValueType() == N->getValueType(0) &&
8135 "Incompatible type of the PassThru value in MaskedGatherSDNode");
8136 assert(N->getMask().getValueType().getVectorElementCount() ==
8137 N->getValueType(0).getVectorElementCount() &&
8138 "Vector width mismatch between mask and data");
8139 assert(N->getIndex().getValueType().getVectorElementCount().isScalable() ==
8140 N->getValueType(0).getVectorElementCount().isScalable() &&
8141 "Scalable flags of index and data do not match");
8142 assert(ElementCount::isKnownGE(
8143 N->getIndex().getValueType().getVectorElementCount(),
8144 N->getValueType(0).getVectorElementCount()) &&
8145 "Vector width mismatch between index and data");
8146 assert(isa<ConstantSDNode>(N->getScale()) &&
8147 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
8148 "Scale should be a constant power of 2");
8150 CSEMap.InsertNode(N, IP);
8151 InsertNode(N);
8152 SDValue V(N, 0);
8153 NewSDValueDbgMsg(V, "Creating new node: ", this);
8154 return V;
8157 SDValue SelectionDAG::getMaskedScatter(SDVTList VTs, EVT MemVT, const SDLoc &dl,
8158 ArrayRef<SDValue> Ops,
8159 MachineMemOperand *MMO,
8160 ISD::MemIndexType IndexType,
8161 bool IsTrunc) {
8162 assert(Ops.size() == 6 && "Incompatible number of operands");
8164 FoldingSetNodeID ID;
8165 AddNodeIDNode(ID, ISD::MSCATTER, VTs, Ops);
8166 ID.AddInteger(MemVT.getRawBits());
8167 ID.AddInteger(getSyntheticNodeSubclassData<MaskedScatterSDNode>(
8168 dl.getIROrder(), VTs, MemVT, MMO, IndexType, IsTrunc));
8169 ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8170 void *IP = nullptr;
8171 if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8172 cast<MaskedScatterSDNode>(E)->refineAlignment(MMO);
8173 return SDValue(E, 0);
8176 IndexType = TLI->getCanonicalIndexType(IndexType, MemVT, Ops[4]);
8177 auto *N = newSDNode<MaskedScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(),
8178 VTs, MemVT, MMO, IndexType, IsTrunc);
8179 createOperands(N, Ops);
8181 assert(N->getMask().getValueType().getVectorElementCount() ==
8182 N->getValue().getValueType().getVectorElementCount() &&
8183 "Vector width mismatch between mask and data");
8184 assert(
8185 N->getIndex().getValueType().getVectorElementCount().isScalable() ==
8186 N->getValue().getValueType().getVectorElementCount().isScalable() &&
8187 "Scalable flags of index and data do not match");
8188 assert(ElementCount::isKnownGE(
8189 N->getIndex().getValueType().getVectorElementCount(),
8190 N->getValue().getValueType().getVectorElementCount()) &&
8191 "Vector width mismatch between index and data");
8192 assert(isa<ConstantSDNode>(N->getScale()) &&
8193 cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
8194 "Scale should be a constant power of 2");
8196 CSEMap.InsertNode(N, IP);
8197 InsertNode(N);
8198 SDValue V(N, 0);
8199 NewSDValueDbgMsg(V, "Creating new node: ", this);
8200 return V;
8203 SDValue SelectionDAG::simplifySelect(SDValue Cond, SDValue T, SDValue F) {
8204 // select undef, T, F --> T (if T is a constant), otherwise F
8205 // select, ?, undef, F --> F
8206 // select, ?, T, undef --> T
8207 if (Cond.isUndef())
8208 return isConstantValueOfAnyType(T) ? T : F;
8209 if (T.isUndef())
8210 return F;
8211 if (F.isUndef())
8212 return T;
8214 // select true, T, F --> T
8215 // select false, T, F --> F
8216 if (auto *CondC = dyn_cast<ConstantSDNode>(Cond))
8217 return CondC->isZero() ? F : T;
8219 // TODO: This should simplify VSELECT with constant condition using something
8220 // like this (but check boolean contents to be complete?):
8221 // if (ISD::isBuildVectorAllOnes(Cond.getNode()))
8222 // return T;
8223 // if (ISD::isBuildVectorAllZeros(Cond.getNode()))
8224 // return F;
8226 // select ?, T, T --> T
8227 if (T == F)
8228 return T;
8230 return SDValue();
8233 SDValue SelectionDAG::simplifyShift(SDValue X, SDValue Y) {
8234 // shift undef, Y --> 0 (can always assume that the undef value is 0)
8235 if (X.isUndef())
8236 return getConstant(0, SDLoc(X.getNode()), X.getValueType());
8237 // shift X, undef --> undef (because it may shift by the bitwidth)
8238 if (Y.isUndef())
8239 return getUNDEF(X.getValueType());
8241 // shift 0, Y --> 0
8242 // shift X, 0 --> X
8243 if (isNullOrNullSplat(X) || isNullOrNullSplat(Y))
8244 return X;
8246 // shift X, C >= bitwidth(X) --> undef
8247 // All vector elements must be too big (or undef) to avoid partial undefs.
8248 auto isShiftTooBig = [X](ConstantSDNode *Val) {
8249 return !Val || Val->getAPIntValue().uge(X.getScalarValueSizeInBits());
8251 if (ISD::matchUnaryPredicate(Y, isShiftTooBig, true))
8252 return getUNDEF(X.getValueType());
8254 return SDValue();
8257 SDValue SelectionDAG::simplifyFPBinop(unsigned Opcode, SDValue X, SDValue Y,
8258 SDNodeFlags Flags) {
8259 // If this operation has 'nnan' or 'ninf' and at least 1 disallowed operand
8260 // (an undef operand can be chosen to be Nan/Inf), then the result of this
8261 // operation is poison. That result can be relaxed to undef.
8262 ConstantFPSDNode *XC = isConstOrConstSplatFP(X, /* AllowUndefs */ true);
8263 ConstantFPSDNode *YC = isConstOrConstSplatFP(Y, /* AllowUndefs */ true);
8264 bool HasNan = (XC && XC->getValueAPF().isNaN()) ||
8265 (YC && YC->getValueAPF().isNaN());
8266 bool HasInf = (XC && XC->getValueAPF().isInfinity()) ||
8267 (YC && YC->getValueAPF().isInfinity());
8269 if (Flags.hasNoNaNs() && (HasNan || X.isUndef() || Y.isUndef()))
8270 return getUNDEF(X.getValueType());
8272 if (Flags.hasNoInfs() && (HasInf || X.isUndef() || Y.isUndef()))
8273 return getUNDEF(X.getValueType());
8275 if (!YC)
8276 return SDValue();
8278 // X + -0.0 --> X
8279 if (Opcode == ISD::FADD)
8280 if (YC->getValueAPF().isNegZero())
8281 return X;
8283 // X - +0.0 --> X
8284 if (Opcode == ISD::FSUB)
8285 if (YC->getValueAPF().isPosZero())
8286 return X;
8288 // X * 1.0 --> X
8289 // X / 1.0 --> X
8290 if (Opcode == ISD::FMUL || Opcode == ISD::FDIV)
8291 if (YC->getValueAPF().isExactlyValue(1.0))
8292 return X;
8294 // X * 0.0 --> 0.0
8295 if (Opcode == ISD::FMUL && Flags.hasNoNaNs() && Flags.hasNoSignedZeros())
8296 if (YC->getValueAPF().isZero())
8297 return getConstantFP(0.0, SDLoc(Y), Y.getValueType());
8299 return SDValue();
8302 SDValue SelectionDAG::getVAArg(EVT VT, const SDLoc &dl, SDValue Chain,
8303 SDValue Ptr, SDValue SV, unsigned Align) {
8304 SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, dl, MVT::i32) };
8305 return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops);
8308 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8309 ArrayRef<SDUse> Ops) {
8310 switch (Ops.size()) {
8311 case 0: return getNode(Opcode, DL, VT);
8312 case 1: return getNode(Opcode, DL, VT, static_cast<const SDValue>(Ops[0]));
8313 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
8314 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
8315 default: break;
8318 // Copy from an SDUse array into an SDValue array for use with
8319 // the regular getNode logic.
8320 SmallVector<SDValue, 8> NewOps(Ops.begin(), Ops.end());
8321 return getNode(Opcode, DL, VT, NewOps);
8324 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8325 ArrayRef<SDValue> Ops) {
8326 SDNodeFlags Flags;
8327 if (Inserter)
8328 Flags = Inserter->getFlags();
8329 return getNode(Opcode, DL, VT, Ops, Flags);
8332 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8333 ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
8334 unsigned NumOps = Ops.size();
8335 switch (NumOps) {
8336 case 0: return getNode(Opcode, DL, VT);
8337 case 1: return getNode(Opcode, DL, VT, Ops[0], Flags);
8338 case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Flags);
8339 case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2], Flags);
8340 default: break;
8343 #ifndef NDEBUG
8344 for (auto &Op : Ops)
8345 assert(Op.getOpcode() != ISD::DELETED_NODE &&
8346 "Operand is DELETED_NODE!");
8347 #endif
8349 switch (Opcode) {
8350 default: break;
8351 case ISD::BUILD_VECTOR:
8352 // Attempt to simplify BUILD_VECTOR.
8353 if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
8354 return V;
8355 break;
8356 case ISD::CONCAT_VECTORS:
8357 if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
8358 return V;
8359 break;
8360 case ISD::SELECT_CC:
8361 assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
8362 assert(Ops[0].getValueType() == Ops[1].getValueType() &&
8363 "LHS and RHS of condition must have same type!");
8364 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
8365 "True and False arms of SelectCC must have same type!");
8366 assert(Ops[2].getValueType() == VT &&
8367 "select_cc node must be of same type as true and false value!");
8368 break;
8369 case ISD::BR_CC:
8370 assert(NumOps == 5 && "BR_CC takes 5 operands!");
8371 assert(Ops[2].getValueType() == Ops[3].getValueType() &&
8372 "LHS/RHS of comparison should match types!");
8373 break;
8376 // Memoize nodes.
8377 SDNode *N;
8378 SDVTList VTs = getVTList(VT);
8380 if (VT != MVT::Glue) {
8381 FoldingSetNodeID ID;
8382 AddNodeIDNode(ID, Opcode, VTs, Ops);
8383 void *IP = nullptr;
8385 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
8386 return SDValue(E, 0);
8388 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
8389 createOperands(N, Ops);
8391 CSEMap.InsertNode(N, IP);
8392 } else {
8393 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
8394 createOperands(N, Ops);
8397 N->setFlags(Flags);
8398 InsertNode(N);
8399 SDValue V(N, 0);
8400 NewSDValueDbgMsg(V, "Creating new node: ", this);
8401 return V;
8404 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
8405 ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) {
8406 return getNode(Opcode, DL, getVTList(ResultTys), Ops);
8409 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8410 ArrayRef<SDValue> Ops) {
8411 SDNodeFlags Flags;
8412 if (Inserter)
8413 Flags = Inserter->getFlags();
8414 return getNode(Opcode, DL, VTList, Ops, Flags);
8417 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8418 ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
8419 if (VTList.NumVTs == 1)
8420 return getNode(Opcode, DL, VTList.VTs[0], Ops);
8422 #ifndef NDEBUG
8423 for (auto &Op : Ops)
8424 assert(Op.getOpcode() != ISD::DELETED_NODE &&
8425 "Operand is DELETED_NODE!");
8426 #endif
8428 switch (Opcode) {
8429 case ISD::STRICT_FP_EXTEND:
8430 assert(VTList.NumVTs == 2 && Ops.size() == 2 &&
8431 "Invalid STRICT_FP_EXTEND!");
8432 assert(VTList.VTs[0].isFloatingPoint() &&
8433 Ops[1].getValueType().isFloatingPoint() && "Invalid FP cast!");
8434 assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
8435 "STRICT_FP_EXTEND result type should be vector iff the operand "
8436 "type is vector!");
8437 assert((!VTList.VTs[0].isVector() ||
8438 VTList.VTs[0].getVectorNumElements() ==
8439 Ops[1].getValueType().getVectorNumElements()) &&
8440 "Vector element count mismatch!");
8441 assert(Ops[1].getValueType().bitsLT(VTList.VTs[0]) &&
8442 "Invalid fpext node, dst <= src!");
8443 break;
8444 case ISD::STRICT_FP_ROUND:
8445 assert(VTList.NumVTs == 2 && Ops.size() == 3 && "Invalid STRICT_FP_ROUND!");
8446 assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
8447 "STRICT_FP_ROUND result type should be vector iff the operand "
8448 "type is vector!");
8449 assert((!VTList.VTs[0].isVector() ||
8450 VTList.VTs[0].getVectorNumElements() ==
8451 Ops[1].getValueType().getVectorNumElements()) &&
8452 "Vector element count mismatch!");
8453 assert(VTList.VTs[0].isFloatingPoint() &&
8454 Ops[1].getValueType().isFloatingPoint() &&
8455 VTList.VTs[0].bitsLT(Ops[1].getValueType()) &&
8456 isa<ConstantSDNode>(Ops[2]) &&
8457 (cast<ConstantSDNode>(Ops[2])->getZExtValue() == 0 ||
8458 cast<ConstantSDNode>(Ops[2])->getZExtValue() == 1) &&
8459 "Invalid STRICT_FP_ROUND!");
8460 break;
8461 #if 0
8462 // FIXME: figure out how to safely handle things like
8463 // int foo(int x) { return 1 << (x & 255); }
8464 // int bar() { return foo(256); }
8465 case ISD::SRA_PARTS:
8466 case ISD::SRL_PARTS:
8467 case ISD::SHL_PARTS:
8468 if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
8469 cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
8470 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
8471 else if (N3.getOpcode() == ISD::AND)
8472 if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
8473 // If the and is only masking out bits that cannot effect the shift,
8474 // eliminate the and.
8475 unsigned NumBits = VT.getScalarSizeInBits()*2;
8476 if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
8477 return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
8479 break;
8480 #endif
8483 // Memoize the node unless it returns a flag.
8484 SDNode *N;
8485 if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
8486 FoldingSetNodeID ID;
8487 AddNodeIDNode(ID, Opcode, VTList, Ops);
8488 void *IP = nullptr;
8489 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
8490 return SDValue(E, 0);
8492 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
8493 createOperands(N, Ops);
8494 CSEMap.InsertNode(N, IP);
8495 } else {
8496 N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
8497 createOperands(N, Ops);
8500 N->setFlags(Flags);
8501 InsertNode(N);
8502 SDValue V(N, 0);
8503 NewSDValueDbgMsg(V, "Creating new node: ", this);
8504 return V;
8507 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
8508 SDVTList VTList) {
8509 return getNode(Opcode, DL, VTList, None);
8512 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8513 SDValue N1) {
8514 SDValue Ops[] = { N1 };
8515 return getNode(Opcode, DL, VTList, Ops);
8518 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8519 SDValue N1, SDValue N2) {
8520 SDValue Ops[] = { N1, N2 };
8521 return getNode(Opcode, DL, VTList, Ops);
8524 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8525 SDValue N1, SDValue N2, SDValue N3) {
8526 SDValue Ops[] = { N1, N2, N3 };
8527 return getNode(Opcode, DL, VTList, Ops);
8530 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8531 SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
8532 SDValue Ops[] = { N1, N2, N3, N4 };
8533 return getNode(Opcode, DL, VTList, Ops);
8536 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8537 SDValue N1, SDValue N2, SDValue N3, SDValue N4,
8538 SDValue N5) {
8539 SDValue Ops[] = { N1, N2, N3, N4, N5 };
8540 return getNode(Opcode, DL, VTList, Ops);
8543 SDVTList SelectionDAG::getVTList(EVT VT) {
8544 return makeVTList(SDNode::getValueTypeList(VT), 1);
8547 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2) {
8548 FoldingSetNodeID ID;
8549 ID.AddInteger(2U);
8550 ID.AddInteger(VT1.getRawBits());
8551 ID.AddInteger(VT2.getRawBits());
8553 void *IP = nullptr;
8554 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
8555 if (!Result) {
8556 EVT *Array = Allocator.Allocate<EVT>(2);
8557 Array[0] = VT1;
8558 Array[1] = VT2;
8559 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 2);
8560 VTListMap.InsertNode(Result, IP);
8562 return Result->getSDVTList();
8565 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3) {
8566 FoldingSetNodeID ID;
8567 ID.AddInteger(3U);
8568 ID.AddInteger(VT1.getRawBits());
8569 ID.AddInteger(VT2.getRawBits());
8570 ID.AddInteger(VT3.getRawBits());
8572 void *IP = nullptr;
8573 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
8574 if (!Result) {
8575 EVT *Array = Allocator.Allocate<EVT>(3);
8576 Array[0] = VT1;
8577 Array[1] = VT2;
8578 Array[2] = VT3;
8579 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 3);
8580 VTListMap.InsertNode(Result, IP);
8582 return Result->getSDVTList();
8585 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4) {
8586 FoldingSetNodeID ID;
8587 ID.AddInteger(4U);
8588 ID.AddInteger(VT1.getRawBits());
8589 ID.AddInteger(VT2.getRawBits());
8590 ID.AddInteger(VT3.getRawBits());
8591 ID.AddInteger(VT4.getRawBits());
8593 void *IP = nullptr;
8594 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
8595 if (!Result) {
8596 EVT *Array = Allocator.Allocate<EVT>(4);
8597 Array[0] = VT1;
8598 Array[1] = VT2;
8599 Array[2] = VT3;
8600 Array[3] = VT4;
8601 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 4);
8602 VTListMap.InsertNode(Result, IP);
8604 return Result->getSDVTList();
8607 SDVTList SelectionDAG::getVTList(ArrayRef<EVT> VTs) {
8608 unsigned NumVTs = VTs.size();
8609 FoldingSetNodeID ID;
8610 ID.AddInteger(NumVTs);
8611 for (unsigned index = 0; index < NumVTs; index++) {
8612 ID.AddInteger(VTs[index].getRawBits());
8615 void *IP = nullptr;
8616 SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
8617 if (!Result) {
8618 EVT *Array = Allocator.Allocate<EVT>(NumVTs);
8619 llvm::copy(VTs, Array);
8620 Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, NumVTs);
8621 VTListMap.InsertNode(Result, IP);
8623 return Result->getSDVTList();
8627 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
8628 /// specified operands. If the resultant node already exists in the DAG,
8629 /// this does not modify the specified node, instead it returns the node that
8630 /// already exists. If the resultant node does not exist in the DAG, the
8631 /// input node is returned. As a degenerate case, if you specify the same
8632 /// input operands as the node already has, the input node is returned.
8633 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op) {
8634 assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
8636 // Check to see if there is no change.
8637 if (Op == N->getOperand(0)) return N;
8639 // See if the modified node already exists.
8640 void *InsertPos = nullptr;
8641 if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
8642 return Existing;
8644 // Nope it doesn't. Remove the node from its current place in the maps.
8645 if (InsertPos)
8646 if (!RemoveNodeFromCSEMaps(N))
8647 InsertPos = nullptr;
8649 // Now we update the operands.
8650 N->OperandList[0].set(Op);
8652 updateDivergence(N);
8653 // If this gets put into a CSE map, add it.
8654 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
8655 return N;
8658 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2) {
8659 assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
8661 // Check to see if there is no change.
8662 if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
8663 return N; // No operands changed, just return the input node.
8665 // See if the modified node already exists.
8666 void *InsertPos = nullptr;
8667 if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
8668 return Existing;
8670 // Nope it doesn't. Remove the node from its current place in the maps.
8671 if (InsertPos)
8672 if (!RemoveNodeFromCSEMaps(N))
8673 InsertPos = nullptr;
8675 // Now we update the operands.
8676 if (N->OperandList[0] != Op1)
8677 N->OperandList[0].set(Op1);
8678 if (N->OperandList[1] != Op2)
8679 N->OperandList[1].set(Op2);
8681 updateDivergence(N);
8682 // If this gets put into a CSE map, add it.
8683 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
8684 return N;
8687 SDNode *SelectionDAG::
8688 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, SDValue Op3) {
8689 SDValue Ops[] = { Op1, Op2, Op3 };
8690 return UpdateNodeOperands(N, Ops);
8693 SDNode *SelectionDAG::
8694 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
8695 SDValue Op3, SDValue Op4) {
8696 SDValue Ops[] = { Op1, Op2, Op3, Op4 };
8697 return UpdateNodeOperands(N, Ops);
8700 SDNode *SelectionDAG::
8701 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
8702 SDValue Op3, SDValue Op4, SDValue Op5) {
8703 SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 };
8704 return UpdateNodeOperands(N, Ops);
8707 SDNode *SelectionDAG::
8708 UpdateNodeOperands(SDNode *N, ArrayRef<SDValue> Ops) {
8709 unsigned NumOps = Ops.size();
8710 assert(N->getNumOperands() == NumOps &&
8711 "Update with wrong number of operands");
8713 // If no operands changed just return the input node.
8714 if (std::equal(Ops.begin(), Ops.end(), N->op_begin()))
8715 return N;
8717 // See if the modified node already exists.
8718 void *InsertPos = nullptr;
8719 if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertPos))
8720 return Existing;
8722 // Nope it doesn't. Remove the node from its current place in the maps.
8723 if (InsertPos)
8724 if (!RemoveNodeFromCSEMaps(N))
8725 InsertPos = nullptr;
8727 // Now we update the operands.
8728 for (unsigned i = 0; i != NumOps; ++i)
8729 if (N->OperandList[i] != Ops[i])
8730 N->OperandList[i].set(Ops[i]);
8732 updateDivergence(N);
8733 // If this gets put into a CSE map, add it.
8734 if (InsertPos) CSEMap.InsertNode(N, InsertPos);
8735 return N;
8738 /// DropOperands - Release the operands and set this node to have
8739 /// zero operands.
8740 void SDNode::DropOperands() {
8741 // Unlike the code in MorphNodeTo that does this, we don't need to
8742 // watch for dead nodes here.
8743 for (op_iterator I = op_begin(), E = op_end(); I != E; ) {
8744 SDUse &Use = *I++;
8745 Use.set(SDValue());
8749 void SelectionDAG::setNodeMemRefs(MachineSDNode *N,
8750 ArrayRef<MachineMemOperand *> NewMemRefs) {
8751 if (NewMemRefs.empty()) {
8752 N->clearMemRefs();
8753 return;
8756 // Check if we can avoid allocating by storing a single reference directly.
8757 if (NewMemRefs.size() == 1) {
8758 N->MemRefs = NewMemRefs[0];
8759 N->NumMemRefs = 1;
8760 return;
8763 MachineMemOperand **MemRefsBuffer =
8764 Allocator.template Allocate<MachineMemOperand *>(NewMemRefs.size());
8765 llvm::copy(NewMemRefs, MemRefsBuffer);
8766 N->MemRefs = MemRefsBuffer;
8767 N->NumMemRefs = static_cast<int>(NewMemRefs.size());
8770 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a
8771 /// machine opcode.
8773 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8774 EVT VT) {
8775 SDVTList VTs = getVTList(VT);
8776 return SelectNodeTo(N, MachineOpc, VTs, None);
8779 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8780 EVT VT, SDValue Op1) {
8781 SDVTList VTs = getVTList(VT);
8782 SDValue Ops[] = { Op1 };
8783 return SelectNodeTo(N, MachineOpc, VTs, Ops);
8786 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8787 EVT VT, SDValue Op1,
8788 SDValue Op2) {
8789 SDVTList VTs = getVTList(VT);
8790 SDValue Ops[] = { Op1, Op2 };
8791 return SelectNodeTo(N, MachineOpc, VTs, Ops);
8794 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8795 EVT VT, SDValue Op1,
8796 SDValue Op2, SDValue Op3) {
8797 SDVTList VTs = getVTList(VT);
8798 SDValue Ops[] = { Op1, Op2, Op3 };
8799 return SelectNodeTo(N, MachineOpc, VTs, Ops);
8802 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8803 EVT VT, ArrayRef<SDValue> Ops) {
8804 SDVTList VTs = getVTList(VT);
8805 return SelectNodeTo(N, MachineOpc, VTs, Ops);
8808 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8809 EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) {
8810 SDVTList VTs = getVTList(VT1, VT2);
8811 return SelectNodeTo(N, MachineOpc, VTs, Ops);
8814 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8815 EVT VT1, EVT VT2) {
8816 SDVTList VTs = getVTList(VT1, VT2);
8817 return SelectNodeTo(N, MachineOpc, VTs, None);
8820 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8821 EVT VT1, EVT VT2, EVT VT3,
8822 ArrayRef<SDValue> Ops) {
8823 SDVTList VTs = getVTList(VT1, VT2, VT3);
8824 return SelectNodeTo(N, MachineOpc, VTs, Ops);
8827 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8828 EVT VT1, EVT VT2,
8829 SDValue Op1, SDValue Op2) {
8830 SDVTList VTs = getVTList(VT1, VT2);
8831 SDValue Ops[] = { Op1, Op2 };
8832 return SelectNodeTo(N, MachineOpc, VTs, Ops);
8835 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8836 SDVTList VTs,ArrayRef<SDValue> Ops) {
8837 SDNode *New = MorphNodeTo(N, ~MachineOpc, VTs, Ops);
8838 // Reset the NodeID to -1.
8839 New->setNodeId(-1);
8840 if (New != N) {
8841 ReplaceAllUsesWith(N, New);
8842 RemoveDeadNode(N);
8844 return New;
8847 /// UpdateSDLocOnMergeSDNode - If the opt level is -O0 then it throws away
8848 /// the line number information on the merged node since it is not possible to
8849 /// preserve the information that operation is associated with multiple lines.
8850 /// This will make the debugger working better at -O0, were there is a higher
8851 /// probability having other instructions associated with that line.
8853 /// For IROrder, we keep the smaller of the two
8854 SDNode *SelectionDAG::UpdateSDLocOnMergeSDNode(SDNode *N, const SDLoc &OLoc) {
8855 DebugLoc NLoc = N->getDebugLoc();
8856 if (NLoc && OptLevel == CodeGenOpt::None && OLoc.getDebugLoc() != NLoc) {
8857 N->setDebugLoc(DebugLoc());
8859 unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder());
8860 N->setIROrder(Order);
8861 return N;
8864 /// MorphNodeTo - This *mutates* the specified node to have the specified
8865 /// return type, opcode, and operands.
8867 /// Note that MorphNodeTo returns the resultant node. If there is already a
8868 /// node of the specified opcode and operands, it returns that node instead of
8869 /// the current one. Note that the SDLoc need not be the same.
8871 /// Using MorphNodeTo is faster than creating a new node and swapping it in
8872 /// with ReplaceAllUsesWith both because it often avoids allocating a new
8873 /// node, and because it doesn't require CSE recalculation for any of
8874 /// the node's users.
8876 /// However, note that MorphNodeTo recursively deletes dead nodes from the DAG.
8877 /// As a consequence it isn't appropriate to use from within the DAG combiner or
8878 /// the legalizer which maintain worklists that would need to be updated when
8879 /// deleting things.
8880 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
8881 SDVTList VTs, ArrayRef<SDValue> Ops) {
8882 // If an identical node already exists, use it.
8883 void *IP = nullptr;
8884 if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) {
8885 FoldingSetNodeID ID;
8886 AddNodeIDNode(ID, Opc, VTs, Ops);
8887 if (SDNode *ON = FindNodeOrInsertPos(ID, SDLoc(N), IP))
8888 return UpdateSDLocOnMergeSDNode(ON, SDLoc(N));
8891 if (!RemoveNodeFromCSEMaps(N))
8892 IP = nullptr;
8894 // Start the morphing.
8895 N->NodeType = Opc;
8896 N->ValueList = VTs.VTs;
8897 N->NumValues = VTs.NumVTs;
8899 // Clear the operands list, updating used nodes to remove this from their
8900 // use list. Keep track of any operands that become dead as a result.
8901 SmallPtrSet<SDNode*, 16> DeadNodeSet;
8902 for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
8903 SDUse &Use = *I++;
8904 SDNode *Used = Use.getNode();
8905 Use.set(SDValue());
8906 if (Used->use_empty())
8907 DeadNodeSet.insert(Used);
8910 // For MachineNode, initialize the memory references information.
8911 if (MachineSDNode *MN = dyn_cast<MachineSDNode>(N))
8912 MN->clearMemRefs();
8914 // Swap for an appropriately sized array from the recycler.
8915 removeOperands(N);
8916 createOperands(N, Ops);
8918 // Delete any nodes that are still dead after adding the uses for the
8919 // new operands.
8920 if (!DeadNodeSet.empty()) {
8921 SmallVector<SDNode *, 16> DeadNodes;
8922 for (SDNode *N : DeadNodeSet)
8923 if (N->use_empty())
8924 DeadNodes.push_back(N);
8925 RemoveDeadNodes(DeadNodes);
8928 if (IP)
8929 CSEMap.InsertNode(N, IP); // Memoize the new node.
8930 return N;
8933 SDNode* SelectionDAG::mutateStrictFPToFP(SDNode *Node) {
8934 unsigned OrigOpc = Node->getOpcode();
8935 unsigned NewOpc;
8936 switch (OrigOpc) {
8937 default:
8938 llvm_unreachable("mutateStrictFPToFP called with unexpected opcode!");
8939 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \
8940 case ISD::STRICT_##DAGN: NewOpc = ISD::DAGN; break;
8941 #define CMP_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \
8942 case ISD::STRICT_##DAGN: NewOpc = ISD::SETCC; break;
8943 #include "llvm/IR/ConstrainedOps.def"
8946 assert(Node->getNumValues() == 2 && "Unexpected number of results!");
8948 // We're taking this node out of the chain, so we need to re-link things.
8949 SDValue InputChain = Node->getOperand(0);
8950 SDValue OutputChain = SDValue(Node, 1);
8951 ReplaceAllUsesOfValueWith(OutputChain, InputChain);
8953 SmallVector<SDValue, 3> Ops;
8954 for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
8955 Ops.push_back(Node->getOperand(i));
8957 SDVTList VTs = getVTList(Node->getValueType(0));
8958 SDNode *Res = MorphNodeTo(Node, NewOpc, VTs, Ops);
8960 // MorphNodeTo can operate in two ways: if an existing node with the
8961 // specified operands exists, it can just return it. Otherwise, it
8962 // updates the node in place to have the requested operands.
8963 if (Res == Node) {
8964 // If we updated the node in place, reset the node ID. To the isel,
8965 // this should be just like a newly allocated machine node.
8966 Res->setNodeId(-1);
8967 } else {
8968 ReplaceAllUsesWith(Node, Res);
8969 RemoveDeadNode(Node);
8972 return Res;
8975 /// getMachineNode - These are used for target selectors to create a new node
8976 /// with specified return type(s), MachineInstr opcode, and operands.
8978 /// Note that getMachineNode returns the resultant node. If there is already a
8979 /// node of the specified opcode and operands, it returns that node instead of
8980 /// the current one.
8981 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8982 EVT VT) {
8983 SDVTList VTs = getVTList(VT);
8984 return getMachineNode(Opcode, dl, VTs, None);
8987 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8988 EVT VT, SDValue Op1) {
8989 SDVTList VTs = getVTList(VT);
8990 SDValue Ops[] = { Op1 };
8991 return getMachineNode(Opcode, dl, VTs, Ops);
8994 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8995 EVT VT, SDValue Op1, SDValue Op2) {
8996 SDVTList VTs = getVTList(VT);
8997 SDValue Ops[] = { Op1, Op2 };
8998 return getMachineNode(Opcode, dl, VTs, Ops);
9001 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9002 EVT VT, SDValue Op1, SDValue Op2,
9003 SDValue Op3) {
9004 SDVTList VTs = getVTList(VT);
9005 SDValue Ops[] = { Op1, Op2, Op3 };
9006 return getMachineNode(Opcode, dl, VTs, Ops);
9009 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9010 EVT VT, ArrayRef<SDValue> Ops) {
9011 SDVTList VTs = getVTList(VT);
9012 return getMachineNode(Opcode, dl, VTs, Ops);
9015 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9016 EVT VT1, EVT VT2, SDValue Op1,
9017 SDValue Op2) {
9018 SDVTList VTs = getVTList(VT1, VT2);
9019 SDValue Ops[] = { Op1, Op2 };
9020 return getMachineNode(Opcode, dl, VTs, Ops);
9023 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9024 EVT VT1, EVT VT2, SDValue Op1,
9025 SDValue Op2, SDValue Op3) {
9026 SDVTList VTs = getVTList(VT1, VT2);
9027 SDValue Ops[] = { Op1, Op2, Op3 };
9028 return getMachineNode(Opcode, dl, VTs, Ops);
9031 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9032 EVT VT1, EVT VT2,
9033 ArrayRef<SDValue> Ops) {
9034 SDVTList VTs = getVTList(VT1, VT2);
9035 return getMachineNode(Opcode, dl, VTs, Ops);
9038 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9039 EVT VT1, EVT VT2, EVT VT3,
9040 SDValue Op1, SDValue Op2) {
9041 SDVTList VTs = getVTList(VT1, VT2, VT3);
9042 SDValue Ops[] = { Op1, Op2 };
9043 return getMachineNode(Opcode, dl, VTs, Ops);
9046 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9047 EVT VT1, EVT VT2, EVT VT3,
9048 SDValue Op1, SDValue Op2,
9049 SDValue Op3) {
9050 SDVTList VTs = getVTList(VT1, VT2, VT3);
9051 SDValue Ops[] = { Op1, Op2, Op3 };
9052 return getMachineNode(Opcode, dl, VTs, Ops);
9055 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9056 EVT VT1, EVT VT2, EVT VT3,
9057 ArrayRef<SDValue> Ops) {
9058 SDVTList VTs = getVTList(VT1, VT2, VT3);
9059 return getMachineNode(Opcode, dl, VTs, Ops);
9062 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9063 ArrayRef<EVT> ResultTys,
9064 ArrayRef<SDValue> Ops) {
9065 SDVTList VTs = getVTList(ResultTys);
9066 return getMachineNode(Opcode, dl, VTs, Ops);
9069 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &DL,
9070 SDVTList VTs,
9071 ArrayRef<SDValue> Ops) {
9072 bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue;
9073 MachineSDNode *N;
9074 void *IP = nullptr;
9076 if (DoCSE) {
9077 FoldingSetNodeID ID;
9078 AddNodeIDNode(ID, ~Opcode, VTs, Ops);
9079 IP = nullptr;
9080 if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
9081 return cast<MachineSDNode>(UpdateSDLocOnMergeSDNode(E, DL));
9085 // Allocate a new MachineSDNode.
9086 N = newSDNode<MachineSDNode>(~Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
9087 createOperands(N, Ops);
9089 if (DoCSE)
9090 CSEMap.InsertNode(N, IP);
9092 InsertNode(N);
9093 NewSDValueDbgMsg(SDValue(N, 0), "Creating new machine node: ", this);
9094 return N;
9097 /// getTargetExtractSubreg - A convenience function for creating
9098 /// TargetOpcode::EXTRACT_SUBREG nodes.
9099 SDValue SelectionDAG::getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT,
9100 SDValue Operand) {
9101 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
9102 SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,
9103 VT, Operand, SRIdxVal);
9104 return SDValue(Subreg, 0);
9107 /// getTargetInsertSubreg - A convenience function for creating
9108 /// TargetOpcode::INSERT_SUBREG nodes.
9109 SDValue SelectionDAG::getTargetInsertSubreg(int SRIdx, const SDLoc &DL, EVT VT,
9110 SDValue Operand, SDValue Subreg) {
9111 SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
9112 SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL,
9113 VT, Operand, Subreg, SRIdxVal);
9114 return SDValue(Result, 0);
9117 /// getNodeIfExists - Get the specified node if it's already available, or
9118 /// else return NULL.
9119 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
9120 ArrayRef<SDValue> Ops) {
9121 SDNodeFlags Flags;
9122 if (Inserter)
9123 Flags = Inserter->getFlags();
9124 return getNodeIfExists(Opcode, VTList, Ops, Flags);
9127 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
9128 ArrayRef<SDValue> Ops,
9129 const SDNodeFlags Flags) {
9130 if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
9131 FoldingSetNodeID ID;
9132 AddNodeIDNode(ID, Opcode, VTList, Ops);
9133 void *IP = nullptr;
9134 if (SDNode *E = FindNodeOrInsertPos(ID, SDLoc(), IP)) {
9135 E->intersectFlagsWith(Flags);
9136 return E;
9139 return nullptr;
9142 /// doesNodeExist - Check if a node exists without modifying its flags.
9143 bool SelectionDAG::doesNodeExist(unsigned Opcode, SDVTList VTList,
9144 ArrayRef<SDValue> Ops) {
9145 if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
9146 FoldingSetNodeID ID;
9147 AddNodeIDNode(ID, Opcode, VTList, Ops);
9148 void *IP = nullptr;
9149 if (FindNodeOrInsertPos(ID, SDLoc(), IP))
9150 return true;
9152 return false;
9155 /// getDbgValue - Creates a SDDbgValue node.
9157 /// SDNode
9158 SDDbgValue *SelectionDAG::getDbgValue(DIVariable *Var, DIExpression *Expr,
9159 SDNode *N, unsigned R, bool IsIndirect,
9160 const DebugLoc &DL, unsigned O) {
9161 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9162 "Expected inlined-at fields to agree");
9163 return new (DbgInfo->getAlloc())
9164 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromNode(N, R),
9165 {}, IsIndirect, DL, O,
9166 /*IsVariadic=*/false);
9169 /// Constant
9170 SDDbgValue *SelectionDAG::getConstantDbgValue(DIVariable *Var,
9171 DIExpression *Expr,
9172 const Value *C,
9173 const DebugLoc &DL, unsigned O) {
9174 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9175 "Expected inlined-at fields to agree");
9176 return new (DbgInfo->getAlloc())
9177 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromConst(C), {},
9178 /*IsIndirect=*/false, DL, O,
9179 /*IsVariadic=*/false);
9182 /// FrameIndex
9183 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var,
9184 DIExpression *Expr, unsigned FI,
9185 bool IsIndirect,
9186 const DebugLoc &DL,
9187 unsigned O) {
9188 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9189 "Expected inlined-at fields to agree");
9190 return getFrameIndexDbgValue(Var, Expr, FI, {}, IsIndirect, DL, O);
9193 /// FrameIndex with dependencies
9194 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var,
9195 DIExpression *Expr, unsigned FI,
9196 ArrayRef<SDNode *> Dependencies,
9197 bool IsIndirect,
9198 const DebugLoc &DL,
9199 unsigned O) {
9200 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9201 "Expected inlined-at fields to agree");
9202 return new (DbgInfo->getAlloc())
9203 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromFrameIdx(FI),
9204 Dependencies, IsIndirect, DL, O,
9205 /*IsVariadic=*/false);
9208 /// VReg
9209 SDDbgValue *SelectionDAG::getVRegDbgValue(DIVariable *Var, DIExpression *Expr,
9210 unsigned VReg, bool IsIndirect,
9211 const DebugLoc &DL, unsigned O) {
9212 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9213 "Expected inlined-at fields to agree");
9214 return new (DbgInfo->getAlloc())
9215 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromVReg(VReg),
9216 {}, IsIndirect, DL, O,
9217 /*IsVariadic=*/false);
9220 SDDbgValue *SelectionDAG::getDbgValueList(DIVariable *Var, DIExpression *Expr,
9221 ArrayRef<SDDbgOperand> Locs,
9222 ArrayRef<SDNode *> Dependencies,
9223 bool IsIndirect, const DebugLoc &DL,
9224 unsigned O, bool IsVariadic) {
9225 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9226 "Expected inlined-at fields to agree");
9227 return new (DbgInfo->getAlloc())
9228 SDDbgValue(DbgInfo->getAlloc(), Var, Expr, Locs, Dependencies, IsIndirect,
9229 DL, O, IsVariadic);
9232 void SelectionDAG::transferDbgValues(SDValue From, SDValue To,
9233 unsigned OffsetInBits, unsigned SizeInBits,
9234 bool InvalidateDbg) {
9235 SDNode *FromNode = From.getNode();
9236 SDNode *ToNode = To.getNode();
9237 assert(FromNode && ToNode && "Can't modify dbg values");
9239 // PR35338
9240 // TODO: assert(From != To && "Redundant dbg value transfer");
9241 // TODO: assert(FromNode != ToNode && "Intranode dbg value transfer");
9242 if (From == To || FromNode == ToNode)
9243 return;
9245 if (!FromNode->getHasDebugValue())
9246 return;
9248 SDDbgOperand FromLocOp =
9249 SDDbgOperand::fromNode(From.getNode(), From.getResNo());
9250 SDDbgOperand ToLocOp = SDDbgOperand::fromNode(To.getNode(), To.getResNo());
9252 SmallVector<SDDbgValue *, 2> ClonedDVs;
9253 for (SDDbgValue *Dbg : GetDbgValues(FromNode)) {
9254 if (Dbg->isInvalidated())
9255 continue;
9257 // TODO: assert(!Dbg->isInvalidated() && "Transfer of invalid dbg value");
9259 // Create a new location ops vector that is equal to the old vector, but
9260 // with each instance of FromLocOp replaced with ToLocOp.
9261 bool Changed = false;
9262 auto NewLocOps = Dbg->copyLocationOps();
9263 std::replace_if(
9264 NewLocOps.begin(), NewLocOps.end(),
9265 [&Changed, FromLocOp](const SDDbgOperand &Op) {
9266 bool Match = Op == FromLocOp;
9267 Changed |= Match;
9268 return Match;
9270 ToLocOp);
9271 // Ignore this SDDbgValue if we didn't find a matching location.
9272 if (!Changed)
9273 continue;
9275 DIVariable *Var = Dbg->getVariable();
9276 auto *Expr = Dbg->getExpression();
9277 // If a fragment is requested, update the expression.
9278 if (SizeInBits) {
9279 // When splitting a larger (e.g., sign-extended) value whose
9280 // lower bits are described with an SDDbgValue, do not attempt
9281 // to transfer the SDDbgValue to the upper bits.
9282 if (auto FI = Expr->getFragmentInfo())
9283 if (OffsetInBits + SizeInBits > FI->SizeInBits)
9284 continue;
9285 auto Fragment = DIExpression::createFragmentExpression(Expr, OffsetInBits,
9286 SizeInBits);
9287 if (!Fragment)
9288 continue;
9289 Expr = *Fragment;
9292 auto AdditionalDependencies = Dbg->getAdditionalDependencies();
9293 // Clone the SDDbgValue and move it to To.
9294 SDDbgValue *Clone = getDbgValueList(
9295 Var, Expr, NewLocOps, AdditionalDependencies, Dbg->isIndirect(),
9296 Dbg->getDebugLoc(), std::max(ToNode->getIROrder(), Dbg->getOrder()),
9297 Dbg->isVariadic());
9298 ClonedDVs.push_back(Clone);
9300 if (InvalidateDbg) {
9301 // Invalidate value and indicate the SDDbgValue should not be emitted.
9302 Dbg->setIsInvalidated();
9303 Dbg->setIsEmitted();
9307 for (SDDbgValue *Dbg : ClonedDVs) {
9308 assert(is_contained(Dbg->getSDNodes(), ToNode) &&
9309 "Transferred DbgValues should depend on the new SDNode");
9310 AddDbgValue(Dbg, false);
9314 void SelectionDAG::salvageDebugInfo(SDNode &N) {
9315 if (!N.getHasDebugValue())
9316 return;
9318 SmallVector<SDDbgValue *, 2> ClonedDVs;
9319 for (auto DV : GetDbgValues(&N)) {
9320 if (DV->isInvalidated())
9321 continue;
9322 switch (N.getOpcode()) {
9323 default:
9324 break;
9325 case ISD::ADD:
9326 SDValue N0 = N.getOperand(0);
9327 SDValue N1 = N.getOperand(1);
9328 if (!isConstantIntBuildVectorOrConstantInt(N0) &&
9329 isConstantIntBuildVectorOrConstantInt(N1)) {
9330 uint64_t Offset = N.getConstantOperandVal(1);
9332 // Rewrite an ADD constant node into a DIExpression. Since we are
9333 // performing arithmetic to compute the variable's *value* in the
9334 // DIExpression, we need to mark the expression with a
9335 // DW_OP_stack_value.
9336 auto *DIExpr = DV->getExpression();
9337 auto NewLocOps = DV->copyLocationOps();
9338 bool Changed = false;
9339 for (size_t i = 0; i < NewLocOps.size(); ++i) {
9340 // We're not given a ResNo to compare against because the whole
9341 // node is going away. We know that any ISD::ADD only has one
9342 // result, so we can assume any node match is using the result.
9343 if (NewLocOps[i].getKind() != SDDbgOperand::SDNODE ||
9344 NewLocOps[i].getSDNode() != &N)
9345 continue;
9346 NewLocOps[i] = SDDbgOperand::fromNode(N0.getNode(), N0.getResNo());
9347 SmallVector<uint64_t, 3> ExprOps;
9348 DIExpression::appendOffset(ExprOps, Offset);
9349 DIExpr = DIExpression::appendOpsToArg(DIExpr, ExprOps, i, true);
9350 Changed = true;
9352 (void)Changed;
9353 assert(Changed && "Salvage target doesn't use N");
9355 auto AdditionalDependencies = DV->getAdditionalDependencies();
9356 SDDbgValue *Clone = getDbgValueList(DV->getVariable(), DIExpr,
9357 NewLocOps, AdditionalDependencies,
9358 DV->isIndirect(), DV->getDebugLoc(),
9359 DV->getOrder(), DV->isVariadic());
9360 ClonedDVs.push_back(Clone);
9361 DV->setIsInvalidated();
9362 DV->setIsEmitted();
9363 LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting";
9364 N0.getNode()->dumprFull(this);
9365 dbgs() << " into " << *DIExpr << '\n');
9370 for (SDDbgValue *Dbg : ClonedDVs) {
9371 assert(!Dbg->getSDNodes().empty() &&
9372 "Salvaged DbgValue should depend on a new SDNode");
9373 AddDbgValue(Dbg, false);
9377 /// Creates a SDDbgLabel node.
9378 SDDbgLabel *SelectionDAG::getDbgLabel(DILabel *Label,
9379 const DebugLoc &DL, unsigned O) {
9380 assert(cast<DILabel>(Label)->isValidLocationForIntrinsic(DL) &&
9381 "Expected inlined-at fields to agree");
9382 return new (DbgInfo->getAlloc()) SDDbgLabel(Label, DL, O);
9385 namespace {
9387 /// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node
9388 /// pointed to by a use iterator is deleted, increment the use iterator
9389 /// so that it doesn't dangle.
9391 class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener {
9392 SDNode::use_iterator &UI;
9393 SDNode::use_iterator &UE;
9395 void NodeDeleted(SDNode *N, SDNode *E) override {
9396 // Increment the iterator as needed.
9397 while (UI != UE && N == *UI)
9398 ++UI;
9401 public:
9402 RAUWUpdateListener(SelectionDAG &d,
9403 SDNode::use_iterator &ui,
9404 SDNode::use_iterator &ue)
9405 : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {}
9408 } // end anonymous namespace
9410 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
9411 /// This can cause recursive merging of nodes in the DAG.
9413 /// This version assumes From has a single result value.
9415 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To) {
9416 SDNode *From = FromN.getNode();
9417 assert(From->getNumValues() == 1 && FromN.getResNo() == 0 &&
9418 "Cannot replace with this method!");
9419 assert(From != To.getNode() && "Cannot replace uses of with self");
9421 // Preserve Debug Values
9422 transferDbgValues(FromN, To);
9424 // Iterate over all the existing uses of From. New uses will be added
9425 // to the beginning of the use list, which we avoid visiting.
9426 // This specifically avoids visiting uses of From that arise while the
9427 // replacement is happening, because any such uses would be the result
9428 // of CSE: If an existing node looks like From after one of its operands
9429 // is replaced by To, we don't want to replace of all its users with To
9430 // too. See PR3018 for more info.
9431 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
9432 RAUWUpdateListener Listener(*this, UI, UE);
9433 while (UI != UE) {
9434 SDNode *User = *UI;
9436 // This node is about to morph, remove its old self from the CSE maps.
9437 RemoveNodeFromCSEMaps(User);
9439 // A user can appear in a use list multiple times, and when this
9440 // happens the uses are usually next to each other in the list.
9441 // To help reduce the number of CSE recomputations, process all
9442 // the uses of this user that we can find this way.
9443 do {
9444 SDUse &Use = UI.getUse();
9445 ++UI;
9446 Use.set(To);
9447 if (To->isDivergent() != From->isDivergent())
9448 updateDivergence(User);
9449 } while (UI != UE && *UI == User);
9450 // Now that we have modified User, add it back to the CSE maps. If it
9451 // already exists there, recursively merge the results together.
9452 AddModifiedNodeToCSEMaps(User);
9455 // If we just RAUW'd the root, take note.
9456 if (FromN == getRoot())
9457 setRoot(To);
9460 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
9461 /// This can cause recursive merging of nodes in the DAG.
9463 /// This version assumes that for each value of From, there is a
9464 /// corresponding value in To in the same position with the same type.
9466 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To) {
9467 #ifndef NDEBUG
9468 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
9469 assert((!From->hasAnyUseOfValue(i) ||
9470 From->getValueType(i) == To->getValueType(i)) &&
9471 "Cannot use this version of ReplaceAllUsesWith!");
9472 #endif
9474 // Handle the trivial case.
9475 if (From == To)
9476 return;
9478 // Preserve Debug Info. Only do this if there's a use.
9479 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
9480 if (From->hasAnyUseOfValue(i)) {
9481 assert((i < To->getNumValues()) && "Invalid To location");
9482 transferDbgValues(SDValue(From, i), SDValue(To, i));
9485 // Iterate over just the existing users of From. See the comments in
9486 // the ReplaceAllUsesWith above.
9487 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
9488 RAUWUpdateListener Listener(*this, UI, UE);
9489 while (UI != UE) {
9490 SDNode *User = *UI;
9492 // This node is about to morph, remove its old self from the CSE maps.
9493 RemoveNodeFromCSEMaps(User);
9495 // A user can appear in a use list multiple times, and when this
9496 // happens the uses are usually next to each other in the list.
9497 // To help reduce the number of CSE recomputations, process all
9498 // the uses of this user that we can find this way.
9499 do {
9500 SDUse &Use = UI.getUse();
9501 ++UI;
9502 Use.setNode(To);
9503 if (To->isDivergent() != From->isDivergent())
9504 updateDivergence(User);
9505 } while (UI != UE && *UI == User);
9507 // Now that we have modified User, add it back to the CSE maps. If it
9508 // already exists there, recursively merge the results together.
9509 AddModifiedNodeToCSEMaps(User);
9512 // If we just RAUW'd the root, take note.
9513 if (From == getRoot().getNode())
9514 setRoot(SDValue(To, getRoot().getResNo()));
9517 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
9518 /// This can cause recursive merging of nodes in the DAG.
9520 /// This version can replace From with any result values. To must match the
9521 /// number and types of values returned by From.
9522 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, const SDValue *To) {
9523 if (From->getNumValues() == 1) // Handle the simple case efficiently.
9524 return ReplaceAllUsesWith(SDValue(From, 0), To[0]);
9526 // Preserve Debug Info.
9527 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
9528 transferDbgValues(SDValue(From, i), To[i]);
9530 // Iterate over just the existing users of From. See the comments in
9531 // the ReplaceAllUsesWith above.
9532 SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
9533 RAUWUpdateListener Listener(*this, UI, UE);
9534 while (UI != UE) {
9535 SDNode *User = *UI;
9537 // This node is about to morph, remove its old self from the CSE maps.
9538 RemoveNodeFromCSEMaps(User);
9540 // A user can appear in a use list multiple times, and when this happens the
9541 // uses are usually next to each other in the list. To help reduce the
9542 // number of CSE and divergence recomputations, process all the uses of this
9543 // user that we can find this way.
9544 bool To_IsDivergent = false;
9545 do {
9546 SDUse &Use = UI.getUse();
9547 const SDValue &ToOp = To[Use.getResNo()];
9548 ++UI;
9549 Use.set(ToOp);
9550 To_IsDivergent |= ToOp->isDivergent();
9551 } while (UI != UE && *UI == User);
9553 if (To_IsDivergent != From->isDivergent())
9554 updateDivergence(User);
9556 // Now that we have modified User, add it back to the CSE maps. If it
9557 // already exists there, recursively merge the results together.
9558 AddModifiedNodeToCSEMaps(User);
9561 // If we just RAUW'd the root, take note.
9562 if (From == getRoot().getNode())
9563 setRoot(SDValue(To[getRoot().getResNo()]));
9566 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
9567 /// uses of other values produced by From.getNode() alone. The Deleted
9568 /// vector is handled the same way as for ReplaceAllUsesWith.
9569 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To){
9570 // Handle the really simple, really trivial case efficiently.
9571 if (From == To) return;
9573 // Handle the simple, trivial, case efficiently.
9574 if (From.getNode()->getNumValues() == 1) {
9575 ReplaceAllUsesWith(From, To);
9576 return;
9579 // Preserve Debug Info.
9580 transferDbgValues(From, To);
9582 // Iterate over just the existing users of From. See the comments in
9583 // the ReplaceAllUsesWith above.
9584 SDNode::use_iterator UI = From.getNode()->use_begin(),
9585 UE = From.getNode()->use_end();
9586 RAUWUpdateListener Listener(*this, UI, UE);
9587 while (UI != UE) {
9588 SDNode *User = *UI;
9589 bool UserRemovedFromCSEMaps = false;
9591 // A user can appear in a use list multiple times, and when this
9592 // happens the uses are usually next to each other in the list.
9593 // To help reduce the number of CSE recomputations, process all
9594 // the uses of this user that we can find this way.
9595 do {
9596 SDUse &Use = UI.getUse();
9598 // Skip uses of different values from the same node.
9599 if (Use.getResNo() != From.getResNo()) {
9600 ++UI;
9601 continue;
9604 // If this node hasn't been modified yet, it's still in the CSE maps,
9605 // so remove its old self from the CSE maps.
9606 if (!UserRemovedFromCSEMaps) {
9607 RemoveNodeFromCSEMaps(User);
9608 UserRemovedFromCSEMaps = true;
9611 ++UI;
9612 Use.set(To);
9613 if (To->isDivergent() != From->isDivergent())
9614 updateDivergence(User);
9615 } while (UI != UE && *UI == User);
9616 // We are iterating over all uses of the From node, so if a use
9617 // doesn't use the specific value, no changes are made.
9618 if (!UserRemovedFromCSEMaps)
9619 continue;
9621 // Now that we have modified User, add it back to the CSE maps. If it
9622 // already exists there, recursively merge the results together.
9623 AddModifiedNodeToCSEMaps(User);
9626 // If we just RAUW'd the root, take note.
9627 if (From == getRoot())
9628 setRoot(To);
9631 namespace {
9633 /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith
9634 /// to record information about a use.
9635 struct UseMemo {
9636 SDNode *User;
9637 unsigned Index;
9638 SDUse *Use;
9641 /// operator< - Sort Memos by User.
9642 bool operator<(const UseMemo &L, const UseMemo &R) {
9643 return (intptr_t)L.User < (intptr_t)R.User;
9646 } // end anonymous namespace
9648 bool SelectionDAG::calculateDivergence(SDNode *N) {
9649 if (TLI->isSDNodeAlwaysUniform(N)) {
9650 assert(!TLI->isSDNodeSourceOfDivergence(N, FLI, DA) &&
9651 "Conflicting divergence information!");
9652 return false;
9654 if (TLI->isSDNodeSourceOfDivergence(N, FLI, DA))
9655 return true;
9656 for (auto &Op : N->ops()) {
9657 if (Op.Val.getValueType() != MVT::Other && Op.getNode()->isDivergent())
9658 return true;
9660 return false;
9663 void SelectionDAG::updateDivergence(SDNode *N) {
9664 SmallVector<SDNode *, 16> Worklist(1, N);
9665 do {
9666 N = Worklist.pop_back_val();
9667 bool IsDivergent = calculateDivergence(N);
9668 if (N->SDNodeBits.IsDivergent != IsDivergent) {
9669 N->SDNodeBits.IsDivergent = IsDivergent;
9670 llvm::append_range(Worklist, N->uses());
9672 } while (!Worklist.empty());
9675 void SelectionDAG::CreateTopologicalOrder(std::vector<SDNode *> &Order) {
9676 DenseMap<SDNode *, unsigned> Degree;
9677 Order.reserve(AllNodes.size());
9678 for (auto &N : allnodes()) {
9679 unsigned NOps = N.getNumOperands();
9680 Degree[&N] = NOps;
9681 if (0 == NOps)
9682 Order.push_back(&N);
9684 for (size_t I = 0; I != Order.size(); ++I) {
9685 SDNode *N = Order[I];
9686 for (auto U : N->uses()) {
9687 unsigned &UnsortedOps = Degree[U];
9688 if (0 == --UnsortedOps)
9689 Order.push_back(U);
9694 #ifndef NDEBUG
9695 void SelectionDAG::VerifyDAGDivergence() {
9696 std::vector<SDNode *> TopoOrder;
9697 CreateTopologicalOrder(TopoOrder);
9698 for (auto *N : TopoOrder) {
9699 assert(calculateDivergence(N) == N->isDivergent() &&
9700 "Divergence bit inconsistency detected");
9703 #endif
9705 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving
9706 /// uses of other values produced by From.getNode() alone. The same value
9707 /// may appear in both the From and To list. The Deleted vector is
9708 /// handled the same way as for ReplaceAllUsesWith.
9709 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From,
9710 const SDValue *To,
9711 unsigned Num){
9712 // Handle the simple, trivial case efficiently.
9713 if (Num == 1)
9714 return ReplaceAllUsesOfValueWith(*From, *To);
9716 transferDbgValues(*From, *To);
9718 // Read up all the uses and make records of them. This helps
9719 // processing new uses that are introduced during the
9720 // replacement process.
9721 SmallVector<UseMemo, 4> Uses;
9722 for (unsigned i = 0; i != Num; ++i) {
9723 unsigned FromResNo = From[i].getResNo();
9724 SDNode *FromNode = From[i].getNode();
9725 for (SDNode::use_iterator UI = FromNode->use_begin(),
9726 E = FromNode->use_end(); UI != E; ++UI) {
9727 SDUse &Use = UI.getUse();
9728 if (Use.getResNo() == FromResNo) {
9729 UseMemo Memo = { *UI, i, &Use };
9730 Uses.push_back(Memo);
9735 // Sort the uses, so that all the uses from a given User are together.
9736 llvm::sort(Uses);
9738 for (unsigned UseIndex = 0, UseIndexEnd = Uses.size();
9739 UseIndex != UseIndexEnd; ) {
9740 // We know that this user uses some value of From. If it is the right
9741 // value, update it.
9742 SDNode *User = Uses[UseIndex].User;
9744 // This node is about to morph, remove its old self from the CSE maps.
9745 RemoveNodeFromCSEMaps(User);
9747 // The Uses array is sorted, so all the uses for a given User
9748 // are next to each other in the list.
9749 // To help reduce the number of CSE recomputations, process all
9750 // the uses of this user that we can find this way.
9751 do {
9752 unsigned i = Uses[UseIndex].Index;
9753 SDUse &Use = *Uses[UseIndex].Use;
9754 ++UseIndex;
9756 Use.set(To[i]);
9757 } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User);
9759 // Now that we have modified User, add it back to the CSE maps. If it
9760 // already exists there, recursively merge the results together.
9761 AddModifiedNodeToCSEMaps(User);
9765 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
9766 /// based on their topological order. It returns the maximum id and a vector
9767 /// of the SDNodes* in assigned order by reference.
9768 unsigned SelectionDAG::AssignTopologicalOrder() {
9769 unsigned DAGSize = 0;
9771 // SortedPos tracks the progress of the algorithm. Nodes before it are
9772 // sorted, nodes after it are unsorted. When the algorithm completes
9773 // it is at the end of the list.
9774 allnodes_iterator SortedPos = allnodes_begin();
9776 // Visit all the nodes. Move nodes with no operands to the front of
9777 // the list immediately. Annotate nodes that do have operands with their
9778 // operand count. Before we do this, the Node Id fields of the nodes
9779 // may contain arbitrary values. After, the Node Id fields for nodes
9780 // before SortedPos will contain the topological sort index, and the
9781 // Node Id fields for nodes At SortedPos and after will contain the
9782 // count of outstanding operands.
9783 for (SDNode &N : llvm::make_early_inc_range(allnodes())) {
9784 checkForCycles(&N, this);
9785 unsigned Degree = N.getNumOperands();
9786 if (Degree == 0) {
9787 // A node with no uses, add it to the result array immediately.
9788 N.setNodeId(DAGSize++);
9789 allnodes_iterator Q(&N);
9790 if (Q != SortedPos)
9791 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q));
9792 assert(SortedPos != AllNodes.end() && "Overran node list");
9793 ++SortedPos;
9794 } else {
9795 // Temporarily use the Node Id as scratch space for the degree count.
9796 N.setNodeId(Degree);
9800 // Visit all the nodes. As we iterate, move nodes into sorted order,
9801 // such that by the time the end is reached all nodes will be sorted.
9802 for (SDNode &Node : allnodes()) {
9803 SDNode *N = &Node;
9804 checkForCycles(N, this);
9805 // N is in sorted position, so all its uses have one less operand
9806 // that needs to be sorted.
9807 for (SDNode *P : N->uses()) {
9808 unsigned Degree = P->getNodeId();
9809 assert(Degree != 0 && "Invalid node degree");
9810 --Degree;
9811 if (Degree == 0) {
9812 // All of P's operands are sorted, so P may sorted now.
9813 P->setNodeId(DAGSize++);
9814 if (P->getIterator() != SortedPos)
9815 SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P));
9816 assert(SortedPos != AllNodes.end() && "Overran node list");
9817 ++SortedPos;
9818 } else {
9819 // Update P's outstanding operand count.
9820 P->setNodeId(Degree);
9823 if (Node.getIterator() == SortedPos) {
9824 #ifndef NDEBUG
9825 allnodes_iterator I(N);
9826 SDNode *S = &*++I;
9827 dbgs() << "Overran sorted position:\n";
9828 S->dumprFull(this); dbgs() << "\n";
9829 dbgs() << "Checking if this is due to cycles\n";
9830 checkForCycles(this, true);
9831 #endif
9832 llvm_unreachable(nullptr);
9836 assert(SortedPos == AllNodes.end() &&
9837 "Topological sort incomplete!");
9838 assert(AllNodes.front().getOpcode() == ISD::EntryToken &&
9839 "First node in topological sort is not the entry token!");
9840 assert(AllNodes.front().getNodeId() == 0 &&
9841 "First node in topological sort has non-zero id!");
9842 assert(AllNodes.front().getNumOperands() == 0 &&
9843 "First node in topological sort has operands!");
9844 assert(AllNodes.back().getNodeId() == (int)DAGSize-1 &&
9845 "Last node in topologic sort has unexpected id!");
9846 assert(AllNodes.back().use_empty() &&
9847 "Last node in topologic sort has users!");
9848 assert(DAGSize == allnodes_size() && "Node count mismatch!");
9849 return DAGSize;
9852 /// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the
9853 /// value is produced by SD.
9854 void SelectionDAG::AddDbgValue(SDDbgValue *DB, bool isParameter) {
9855 for (SDNode *SD : DB->getSDNodes()) {
9856 if (!SD)
9857 continue;
9858 assert(DbgInfo->getSDDbgValues(SD).empty() || SD->getHasDebugValue());
9859 SD->setHasDebugValue(true);
9861 DbgInfo->add(DB, isParameter);
9864 void SelectionDAG::AddDbgLabel(SDDbgLabel *DB) { DbgInfo->add(DB); }
9866 SDValue SelectionDAG::makeEquivalentMemoryOrdering(SDValue OldChain,
9867 SDValue NewMemOpChain) {
9868 assert(isa<MemSDNode>(NewMemOpChain) && "Expected a memop node");
9869 assert(NewMemOpChain.getValueType() == MVT::Other && "Expected a token VT");
9870 // The new memory operation must have the same position as the old load in
9871 // terms of memory dependency. Create a TokenFactor for the old load and new
9872 // memory operation and update uses of the old load's output chain to use that
9873 // TokenFactor.
9874 if (OldChain == NewMemOpChain || OldChain.use_empty())
9875 return NewMemOpChain;
9877 SDValue TokenFactor = getNode(ISD::TokenFactor, SDLoc(OldChain), MVT::Other,
9878 OldChain, NewMemOpChain);
9879 ReplaceAllUsesOfValueWith(OldChain, TokenFactor);
9880 UpdateNodeOperands(TokenFactor.getNode(), OldChain, NewMemOpChain);
9881 return TokenFactor;
9884 SDValue SelectionDAG::makeEquivalentMemoryOrdering(LoadSDNode *OldLoad,
9885 SDValue NewMemOp) {
9886 assert(isa<MemSDNode>(NewMemOp.getNode()) && "Expected a memop node");
9887 SDValue OldChain = SDValue(OldLoad, 1);
9888 SDValue NewMemOpChain = NewMemOp.getValue(1);
9889 return makeEquivalentMemoryOrdering(OldChain, NewMemOpChain);
9892 SDValue SelectionDAG::getSymbolFunctionGlobalAddress(SDValue Op,
9893 Function **OutFunction) {
9894 assert(isa<ExternalSymbolSDNode>(Op) && "Node should be an ExternalSymbol");
9896 auto *Symbol = cast<ExternalSymbolSDNode>(Op)->getSymbol();
9897 auto *Module = MF->getFunction().getParent();
9898 auto *Function = Module->getFunction(Symbol);
9900 if (OutFunction != nullptr)
9901 *OutFunction = Function;
9903 if (Function != nullptr) {
9904 auto PtrTy = TLI->getPointerTy(getDataLayout(), Function->getAddressSpace());
9905 return getGlobalAddress(Function, SDLoc(Op), PtrTy);
9908 std::string ErrorStr;
9909 raw_string_ostream ErrorFormatter(ErrorStr);
9910 ErrorFormatter << "Undefined external symbol ";
9911 ErrorFormatter << '"' << Symbol << '"';
9912 report_fatal_error(Twine(ErrorFormatter.str()));
9915 //===----------------------------------------------------------------------===//
9916 // SDNode Class
9917 //===----------------------------------------------------------------------===//
9919 bool llvm::isNullConstant(SDValue V) {
9920 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
9921 return Const != nullptr && Const->isZero();
9924 bool llvm::isNullFPConstant(SDValue V) {
9925 ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V);
9926 return Const != nullptr && Const->isZero() && !Const->isNegative();
9929 bool llvm::isAllOnesConstant(SDValue V) {
9930 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
9931 return Const != nullptr && Const->isAllOnes();
9934 bool llvm::isOneConstant(SDValue V) {
9935 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
9936 return Const != nullptr && Const->isOne();
9939 SDValue llvm::peekThroughBitcasts(SDValue V) {
9940 while (V.getOpcode() == ISD::BITCAST)
9941 V = V.getOperand(0);
9942 return V;
9945 SDValue llvm::peekThroughOneUseBitcasts(SDValue V) {
9946 while (V.getOpcode() == ISD::BITCAST && V.getOperand(0).hasOneUse())
9947 V = V.getOperand(0);
9948 return V;
9951 SDValue llvm::peekThroughExtractSubvectors(SDValue V) {
9952 while (V.getOpcode() == ISD::EXTRACT_SUBVECTOR)
9953 V = V.getOperand(0);
9954 return V;
9957 bool llvm::isBitwiseNot(SDValue V, bool AllowUndefs) {
9958 if (V.getOpcode() != ISD::XOR)
9959 return false;
9960 V = peekThroughBitcasts(V.getOperand(1));
9961 unsigned NumBits = V.getScalarValueSizeInBits();
9962 ConstantSDNode *C =
9963 isConstOrConstSplat(V, AllowUndefs, /*AllowTruncation*/ true);
9964 return C && (C->getAPIntValue().countTrailingOnes() >= NumBits);
9967 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, bool AllowUndefs,
9968 bool AllowTruncation) {
9969 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
9970 return CN;
9972 // SplatVectors can truncate their operands. Ignore that case here unless
9973 // AllowTruncation is set.
9974 if (N->getOpcode() == ISD::SPLAT_VECTOR) {
9975 EVT VecEltVT = N->getValueType(0).getVectorElementType();
9976 if (auto *CN = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
9977 EVT CVT = CN->getValueType(0);
9978 assert(CVT.bitsGE(VecEltVT) && "Illegal splat_vector element extension");
9979 if (AllowTruncation || CVT == VecEltVT)
9980 return CN;
9984 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
9985 BitVector UndefElements;
9986 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
9988 // BuildVectors can truncate their operands. Ignore that case here unless
9989 // AllowTruncation is set.
9990 if (CN && (UndefElements.none() || AllowUndefs)) {
9991 EVT CVT = CN->getValueType(0);
9992 EVT NSVT = N.getValueType().getScalarType();
9993 assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension");
9994 if (AllowTruncation || (CVT == NSVT))
9995 return CN;
9999 return nullptr;
10002 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, const APInt &DemandedElts,
10003 bool AllowUndefs,
10004 bool AllowTruncation) {
10005 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
10006 return CN;
10008 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
10009 BitVector UndefElements;
10010 ConstantSDNode *CN = BV->getConstantSplatNode(DemandedElts, &UndefElements);
10012 // BuildVectors can truncate their operands. Ignore that case here unless
10013 // AllowTruncation is set.
10014 if (CN && (UndefElements.none() || AllowUndefs)) {
10015 EVT CVT = CN->getValueType(0);
10016 EVT NSVT = N.getValueType().getScalarType();
10017 assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension");
10018 if (AllowTruncation || (CVT == NSVT))
10019 return CN;
10023 return nullptr;
10026 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N, bool AllowUndefs) {
10027 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
10028 return CN;
10030 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
10031 BitVector UndefElements;
10032 ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
10033 if (CN && (UndefElements.none() || AllowUndefs))
10034 return CN;
10037 if (N.getOpcode() == ISD::SPLAT_VECTOR)
10038 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N.getOperand(0)))
10039 return CN;
10041 return nullptr;
10044 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N,
10045 const APInt &DemandedElts,
10046 bool AllowUndefs) {
10047 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
10048 return CN;
10050 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
10051 BitVector UndefElements;
10052 ConstantFPSDNode *CN =
10053 BV->getConstantFPSplatNode(DemandedElts, &UndefElements);
10054 if (CN && (UndefElements.none() || AllowUndefs))
10055 return CN;
10058 return nullptr;
10061 bool llvm::isNullOrNullSplat(SDValue N, bool AllowUndefs) {
10062 // TODO: may want to use peekThroughBitcast() here.
10063 ConstantSDNode *C =
10064 isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation=*/true);
10065 return C && C->isZero();
10068 bool llvm::isOneOrOneSplat(SDValue N, bool AllowUndefs) {
10069 // TODO: may want to use peekThroughBitcast() here.
10070 unsigned BitWidth = N.getScalarValueSizeInBits();
10071 ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs);
10072 return C && C->isOne() && C->getValueSizeInBits(0) == BitWidth;
10075 bool llvm::isAllOnesOrAllOnesSplat(SDValue N, bool AllowUndefs) {
10076 N = peekThroughBitcasts(N);
10077 unsigned BitWidth = N.getScalarValueSizeInBits();
10078 ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs);
10079 return C && C->isAllOnes() && C->getValueSizeInBits(0) == BitWidth;
10082 HandleSDNode::~HandleSDNode() {
10083 DropOperands();
10086 GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, unsigned Order,
10087 const DebugLoc &DL,
10088 const GlobalValue *GA, EVT VT,
10089 int64_t o, unsigned TF)
10090 : SDNode(Opc, Order, DL, getSDVTList(VT)), Offset(o), TargetFlags(TF) {
10091 TheGlobal = GA;
10094 AddrSpaceCastSDNode::AddrSpaceCastSDNode(unsigned Order, const DebugLoc &dl,
10095 EVT VT, unsigned SrcAS,
10096 unsigned DestAS)
10097 : SDNode(ISD::ADDRSPACECAST, Order, dl, getSDVTList(VT)),
10098 SrcAddrSpace(SrcAS), DestAddrSpace(DestAS) {}
10100 MemSDNode::MemSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl,
10101 SDVTList VTs, EVT memvt, MachineMemOperand *mmo)
10102 : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MMO(mmo) {
10103 MemSDNodeBits.IsVolatile = MMO->isVolatile();
10104 MemSDNodeBits.IsNonTemporal = MMO->isNonTemporal();
10105 MemSDNodeBits.IsDereferenceable = MMO->isDereferenceable();
10106 MemSDNodeBits.IsInvariant = MMO->isInvariant();
10108 // We check here that the size of the memory operand fits within the size of
10109 // the MMO. This is because the MMO might indicate only a possible address
10110 // range instead of specifying the affected memory addresses precisely.
10111 // TODO: Make MachineMemOperands aware of scalable vectors.
10112 assert(memvt.getStoreSize().getKnownMinSize() <= MMO->getSize() &&
10113 "Size mismatch!");
10116 /// Profile - Gather unique data for the node.
10118 void SDNode::Profile(FoldingSetNodeID &ID) const {
10119 AddNodeIDNode(ID, this);
10122 namespace {
10124 struct EVTArray {
10125 std::vector<EVT> VTs;
10127 EVTArray() {
10128 VTs.reserve(MVT::VALUETYPE_SIZE);
10129 for (unsigned i = 0; i < MVT::VALUETYPE_SIZE; ++i)
10130 VTs.push_back(MVT((MVT::SimpleValueType)i));
10134 } // end anonymous namespace
10136 static ManagedStatic<std::set<EVT, EVT::compareRawBits>> EVTs;
10137 static ManagedStatic<EVTArray> SimpleVTArray;
10138 static ManagedStatic<sys::SmartMutex<true>> VTMutex;
10140 /// getValueTypeList - Return a pointer to the specified value type.
10142 const EVT *SDNode::getValueTypeList(EVT VT) {
10143 if (VT.isExtended()) {
10144 sys::SmartScopedLock<true> Lock(*VTMutex);
10145 return &(*EVTs->insert(VT).first);
10147 assert(VT.getSimpleVT() < MVT::VALUETYPE_SIZE && "Value type out of range!");
10148 return &SimpleVTArray->VTs[VT.getSimpleVT().SimpleTy];
10151 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
10152 /// indicated value. This method ignores uses of other values defined by this
10153 /// operation.
10154 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
10155 assert(Value < getNumValues() && "Bad value!");
10157 // TODO: Only iterate over uses of a given value of the node
10158 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
10159 if (UI.getUse().getResNo() == Value) {
10160 if (NUses == 0)
10161 return false;
10162 --NUses;
10166 // Found exactly the right number of uses?
10167 return NUses == 0;
10170 /// hasAnyUseOfValue - Return true if there are any use of the indicated
10171 /// value. This method ignores uses of other values defined by this operation.
10172 bool SDNode::hasAnyUseOfValue(unsigned Value) const {
10173 assert(Value < getNumValues() && "Bad value!");
10175 for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI)
10176 if (UI.getUse().getResNo() == Value)
10177 return true;
10179 return false;
10182 /// isOnlyUserOf - Return true if this node is the only use of N.
10183 bool SDNode::isOnlyUserOf(const SDNode *N) const {
10184 bool Seen = false;
10185 for (const SDNode *User : N->uses()) {
10186 if (User == this)
10187 Seen = true;
10188 else
10189 return false;
10192 return Seen;
10195 /// Return true if the only users of N are contained in Nodes.
10196 bool SDNode::areOnlyUsersOf(ArrayRef<const SDNode *> Nodes, const SDNode *N) {
10197 bool Seen = false;
10198 for (const SDNode *User : N->uses()) {
10199 if (llvm::is_contained(Nodes, User))
10200 Seen = true;
10201 else
10202 return false;
10205 return Seen;
10208 /// isOperand - Return true if this node is an operand of N.
10209 bool SDValue::isOperandOf(const SDNode *N) const {
10210 return is_contained(N->op_values(), *this);
10213 bool SDNode::isOperandOf(const SDNode *N) const {
10214 return any_of(N->op_values(),
10215 [this](SDValue Op) { return this == Op.getNode(); });
10218 /// reachesChainWithoutSideEffects - Return true if this operand (which must
10219 /// be a chain) reaches the specified operand without crossing any
10220 /// side-effecting instructions on any chain path. In practice, this looks
10221 /// through token factors and non-volatile loads. In order to remain efficient,
10222 /// this only looks a couple of nodes in, it does not do an exhaustive search.
10224 /// Note that we only need to examine chains when we're searching for
10225 /// side-effects; SelectionDAG requires that all side-effects are represented
10226 /// by chains, even if another operand would force a specific ordering. This
10227 /// constraint is necessary to allow transformations like splitting loads.
10228 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest,
10229 unsigned Depth) const {
10230 if (*this == Dest) return true;
10232 // Don't search too deeply, we just want to be able to see through
10233 // TokenFactor's etc.
10234 if (Depth == 0) return false;
10236 // If this is a token factor, all inputs to the TF happen in parallel.
10237 if (getOpcode() == ISD::TokenFactor) {
10238 // First, try a shallow search.
10239 if (is_contained((*this)->ops(), Dest)) {
10240 // We found the chain we want as an operand of this TokenFactor.
10241 // Essentially, we reach the chain without side-effects if we could
10242 // serialize the TokenFactor into a simple chain of operations with
10243 // Dest as the last operation. This is automatically true if the
10244 // chain has one use: there are no other ordering constraints.
10245 // If the chain has more than one use, we give up: some other
10246 // use of Dest might force a side-effect between Dest and the current
10247 // node.
10248 if (Dest.hasOneUse())
10249 return true;
10251 // Next, try a deep search: check whether every operand of the TokenFactor
10252 // reaches Dest.
10253 return llvm::all_of((*this)->ops(), [=](SDValue Op) {
10254 return Op.reachesChainWithoutSideEffects(Dest, Depth - 1);
10258 // Loads don't have side effects, look through them.
10259 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
10260 if (Ld->isUnordered())
10261 return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
10263 return false;
10266 bool SDNode::hasPredecessor(const SDNode *N) const {
10267 SmallPtrSet<const SDNode *, 32> Visited;
10268 SmallVector<const SDNode *, 16> Worklist;
10269 Worklist.push_back(this);
10270 return hasPredecessorHelper(N, Visited, Worklist);
10273 void SDNode::intersectFlagsWith(const SDNodeFlags Flags) {
10274 this->Flags.intersectWith(Flags);
10277 SDValue
10278 SelectionDAG::matchBinOpReduction(SDNode *Extract, ISD::NodeType &BinOp,
10279 ArrayRef<ISD::NodeType> CandidateBinOps,
10280 bool AllowPartials) {
10281 // The pattern must end in an extract from index 0.
10282 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10283 !isNullConstant(Extract->getOperand(1)))
10284 return SDValue();
10286 // Match against one of the candidate binary ops.
10287 SDValue Op = Extract->getOperand(0);
10288 if (llvm::none_of(CandidateBinOps, [Op](ISD::NodeType BinOp) {
10289 return Op.getOpcode() == unsigned(BinOp);
10291 return SDValue();
10293 // Floating-point reductions may require relaxed constraints on the final step
10294 // of the reduction because they may reorder intermediate operations.
10295 unsigned CandidateBinOp = Op.getOpcode();
10296 if (Op.getValueType().isFloatingPoint()) {
10297 SDNodeFlags Flags = Op->getFlags();
10298 switch (CandidateBinOp) {
10299 case ISD::FADD:
10300 if (!Flags.hasNoSignedZeros() || !Flags.hasAllowReassociation())
10301 return SDValue();
10302 break;
10303 default:
10304 llvm_unreachable("Unhandled FP opcode for binop reduction");
10308 // Matching failed - attempt to see if we did enough stages that a partial
10309 // reduction from a subvector is possible.
10310 auto PartialReduction = [&](SDValue Op, unsigned NumSubElts) {
10311 if (!AllowPartials || !Op)
10312 return SDValue();
10313 EVT OpVT = Op.getValueType();
10314 EVT OpSVT = OpVT.getScalarType();
10315 EVT SubVT = EVT::getVectorVT(*getContext(), OpSVT, NumSubElts);
10316 if (!TLI->isExtractSubvectorCheap(SubVT, OpVT, 0))
10317 return SDValue();
10318 BinOp = (ISD::NodeType)CandidateBinOp;
10319 return getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(Op), SubVT, Op,
10320 getVectorIdxConstant(0, SDLoc(Op)));
10323 // At each stage, we're looking for something that looks like:
10324 // %s = shufflevector <8 x i32> %op, <8 x i32> undef,
10325 // <8 x i32> <i32 2, i32 3, i32 undef, i32 undef,
10326 // i32 undef, i32 undef, i32 undef, i32 undef>
10327 // %a = binop <8 x i32> %op, %s
10328 // Where the mask changes according to the stage. E.g. for a 3-stage pyramid,
10329 // we expect something like:
10330 // <4,5,6,7,u,u,u,u>
10331 // <2,3,u,u,u,u,u,u>
10332 // <1,u,u,u,u,u,u,u>
10333 // While a partial reduction match would be:
10334 // <2,3,u,u,u,u,u,u>
10335 // <1,u,u,u,u,u,u,u>
10336 unsigned Stages = Log2_32(Op.getValueType().getVectorNumElements());
10337 SDValue PrevOp;
10338 for (unsigned i = 0; i < Stages; ++i) {
10339 unsigned MaskEnd = (1 << i);
10341 if (Op.getOpcode() != CandidateBinOp)
10342 return PartialReduction(PrevOp, MaskEnd);
10344 SDValue Op0 = Op.getOperand(0);
10345 SDValue Op1 = Op.getOperand(1);
10347 ShuffleVectorSDNode *Shuffle = dyn_cast<ShuffleVectorSDNode>(Op0);
10348 if (Shuffle) {
10349 Op = Op1;
10350 } else {
10351 Shuffle = dyn_cast<ShuffleVectorSDNode>(Op1);
10352 Op = Op0;
10355 // The first operand of the shuffle should be the same as the other operand
10356 // of the binop.
10357 if (!Shuffle || Shuffle->getOperand(0) != Op)
10358 return PartialReduction(PrevOp, MaskEnd);
10360 // Verify the shuffle has the expected (at this stage of the pyramid) mask.
10361 for (int Index = 0; Index < (int)MaskEnd; ++Index)
10362 if (Shuffle->getMaskElt(Index) != (int)(MaskEnd + Index))
10363 return PartialReduction(PrevOp, MaskEnd);
10365 PrevOp = Op;
10368 // Handle subvector reductions, which tend to appear after the shuffle
10369 // reduction stages.
10370 while (Op.getOpcode() == CandidateBinOp) {
10371 unsigned NumElts = Op.getValueType().getVectorNumElements();
10372 SDValue Op0 = Op.getOperand(0);
10373 SDValue Op1 = Op.getOperand(1);
10374 if (Op0.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
10375 Op1.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
10376 Op0.getOperand(0) != Op1.getOperand(0))
10377 break;
10378 SDValue Src = Op0.getOperand(0);
10379 unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
10380 if (NumSrcElts != (2 * NumElts))
10381 break;
10382 if (!(Op0.getConstantOperandAPInt(1) == 0 &&
10383 Op1.getConstantOperandAPInt(1) == NumElts) &&
10384 !(Op1.getConstantOperandAPInt(1) == 0 &&
10385 Op0.getConstantOperandAPInt(1) == NumElts))
10386 break;
10387 Op = Src;
10390 BinOp = (ISD::NodeType)CandidateBinOp;
10391 return Op;
10394 SDValue SelectionDAG::UnrollVectorOp(SDNode *N, unsigned ResNE) {
10395 assert(N->getNumValues() == 1 &&
10396 "Can't unroll a vector with multiple results!");
10398 EVT VT = N->getValueType(0);
10399 unsigned NE = VT.getVectorNumElements();
10400 EVT EltVT = VT.getVectorElementType();
10401 SDLoc dl(N);
10403 SmallVector<SDValue, 8> Scalars;
10404 SmallVector<SDValue, 4> Operands(N->getNumOperands());
10406 // If ResNE is 0, fully unroll the vector op.
10407 if (ResNE == 0)
10408 ResNE = NE;
10409 else if (NE > ResNE)
10410 NE = ResNE;
10412 unsigned i;
10413 for (i= 0; i != NE; ++i) {
10414 for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) {
10415 SDValue Operand = N->getOperand(j);
10416 EVT OperandVT = Operand.getValueType();
10417 if (OperandVT.isVector()) {
10418 // A vector operand; extract a single element.
10419 EVT OperandEltVT = OperandVT.getVectorElementType();
10420 Operands[j] = getNode(ISD::EXTRACT_VECTOR_ELT, dl, OperandEltVT,
10421 Operand, getVectorIdxConstant(i, dl));
10422 } else {
10423 // A scalar operand; just use it as is.
10424 Operands[j] = Operand;
10428 switch (N->getOpcode()) {
10429 default: {
10430 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands,
10431 N->getFlags()));
10432 break;
10434 case ISD::VSELECT:
10435 Scalars.push_back(getNode(ISD::SELECT, dl, EltVT, Operands));
10436 break;
10437 case ISD::SHL:
10438 case ISD::SRA:
10439 case ISD::SRL:
10440 case ISD::ROTL:
10441 case ISD::ROTR:
10442 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0],
10443 getShiftAmountOperand(Operands[0].getValueType(),
10444 Operands[1])));
10445 break;
10446 case ISD::SIGN_EXTEND_INREG: {
10447 EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType();
10448 Scalars.push_back(getNode(N->getOpcode(), dl, EltVT,
10449 Operands[0],
10450 getValueType(ExtVT)));
10455 for (; i < ResNE; ++i)
10456 Scalars.push_back(getUNDEF(EltVT));
10458 EVT VecVT = EVT::getVectorVT(*getContext(), EltVT, ResNE);
10459 return getBuildVector(VecVT, dl, Scalars);
10462 std::pair<SDValue, SDValue> SelectionDAG::UnrollVectorOverflowOp(
10463 SDNode *N, unsigned ResNE) {
10464 unsigned Opcode = N->getOpcode();
10465 assert((Opcode == ISD::UADDO || Opcode == ISD::SADDO ||
10466 Opcode == ISD::USUBO || Opcode == ISD::SSUBO ||
10467 Opcode == ISD::UMULO || Opcode == ISD::SMULO) &&
10468 "Expected an overflow opcode");
10470 EVT ResVT = N->getValueType(0);
10471 EVT OvVT = N->getValueType(1);
10472 EVT ResEltVT = ResVT.getVectorElementType();
10473 EVT OvEltVT = OvVT.getVectorElementType();
10474 SDLoc dl(N);
10476 // If ResNE is 0, fully unroll the vector op.
10477 unsigned NE = ResVT.getVectorNumElements();
10478 if (ResNE == 0)
10479 ResNE = NE;
10480 else if (NE > ResNE)
10481 NE = ResNE;
10483 SmallVector<SDValue, 8> LHSScalars;
10484 SmallVector<SDValue, 8> RHSScalars;
10485 ExtractVectorElements(N->getOperand(0), LHSScalars, 0, NE);
10486 ExtractVectorElements(N->getOperand(1), RHSScalars, 0, NE);
10488 EVT SVT = TLI->getSetCCResultType(getDataLayout(), *getContext(), ResEltVT);
10489 SDVTList VTs = getVTList(ResEltVT, SVT);
10490 SmallVector<SDValue, 8> ResScalars;
10491 SmallVector<SDValue, 8> OvScalars;
10492 for (unsigned i = 0; i < NE; ++i) {
10493 SDValue Res = getNode(Opcode, dl, VTs, LHSScalars[i], RHSScalars[i]);
10494 SDValue Ov =
10495 getSelect(dl, OvEltVT, Res.getValue(1),
10496 getBoolConstant(true, dl, OvEltVT, ResVT),
10497 getConstant(0, dl, OvEltVT));
10499 ResScalars.push_back(Res);
10500 OvScalars.push_back(Ov);
10503 ResScalars.append(ResNE - NE, getUNDEF(ResEltVT));
10504 OvScalars.append(ResNE - NE, getUNDEF(OvEltVT));
10506 EVT NewResVT = EVT::getVectorVT(*getContext(), ResEltVT, ResNE);
10507 EVT NewOvVT = EVT::getVectorVT(*getContext(), OvEltVT, ResNE);
10508 return std::make_pair(getBuildVector(NewResVT, dl, ResScalars),
10509 getBuildVector(NewOvVT, dl, OvScalars));
10512 bool SelectionDAG::areNonVolatileConsecutiveLoads(LoadSDNode *LD,
10513 LoadSDNode *Base,
10514 unsigned Bytes,
10515 int Dist) const {
10516 if (LD->isVolatile() || Base->isVolatile())
10517 return false;
10518 // TODO: probably too restrictive for atomics, revisit
10519 if (!LD->isSimple())
10520 return false;
10521 if (LD->isIndexed() || Base->isIndexed())
10522 return false;
10523 if (LD->getChain() != Base->getChain())
10524 return false;
10525 EVT VT = LD->getValueType(0);
10526 if (VT.getSizeInBits() / 8 != Bytes)
10527 return false;
10529 auto BaseLocDecomp = BaseIndexOffset::match(Base, *this);
10530 auto LocDecomp = BaseIndexOffset::match(LD, *this);
10532 int64_t Offset = 0;
10533 if (BaseLocDecomp.equalBaseIndex(LocDecomp, *this, Offset))
10534 return (Dist * Bytes == Offset);
10535 return false;
10538 /// InferPtrAlignment - Infer alignment of a load / store address. Return None
10539 /// if it cannot be inferred.
10540 MaybeAlign SelectionDAG::InferPtrAlign(SDValue Ptr) const {
10541 // If this is a GlobalAddress + cst, return the alignment.
10542 const GlobalValue *GV = nullptr;
10543 int64_t GVOffset = 0;
10544 if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) {
10545 unsigned PtrWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
10546 KnownBits Known(PtrWidth);
10547 llvm::computeKnownBits(GV, Known, getDataLayout());
10548 unsigned AlignBits = Known.countMinTrailingZeros();
10549 if (AlignBits)
10550 return commonAlignment(Align(1ull << std::min(31U, AlignBits)), GVOffset);
10553 // If this is a direct reference to a stack slot, use information about the
10554 // stack slot's alignment.
10555 int FrameIdx = INT_MIN;
10556 int64_t FrameOffset = 0;
10557 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) {
10558 FrameIdx = FI->getIndex();
10559 } else if (isBaseWithConstantOffset(Ptr) &&
10560 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
10561 // Handle FI+Cst
10562 FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
10563 FrameOffset = Ptr.getConstantOperandVal(1);
10566 if (FrameIdx != INT_MIN) {
10567 const MachineFrameInfo &MFI = getMachineFunction().getFrameInfo();
10568 return commonAlignment(MFI.getObjectAlign(FrameIdx), FrameOffset);
10571 return None;
10574 /// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type
10575 /// which is split (or expanded) into two not necessarily identical pieces.
10576 std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const {
10577 // Currently all types are split in half.
10578 EVT LoVT, HiVT;
10579 if (!VT.isVector())
10580 LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT);
10581 else
10582 LoVT = HiVT = VT.getHalfNumVectorElementsVT(*getContext());
10584 return std::make_pair(LoVT, HiVT);
10587 /// GetDependentSplitDestVTs - Compute the VTs needed for the low/hi parts of a
10588 /// type, dependent on an enveloping VT that has been split into two identical
10589 /// pieces. Sets the HiIsEmpty flag when hi type has zero storage size.
10590 std::pair<EVT, EVT>
10591 SelectionDAG::GetDependentSplitDestVTs(const EVT &VT, const EVT &EnvVT,
10592 bool *HiIsEmpty) const {
10593 EVT EltTp = VT.getVectorElementType();
10594 // Examples:
10595 // custom VL=8 with enveloping VL=8/8 yields 8/0 (hi empty)
10596 // custom VL=9 with enveloping VL=8/8 yields 8/1
10597 // custom VL=10 with enveloping VL=8/8 yields 8/2
10598 // etc.
10599 ElementCount VTNumElts = VT.getVectorElementCount();
10600 ElementCount EnvNumElts = EnvVT.getVectorElementCount();
10601 assert(VTNumElts.isScalable() == EnvNumElts.isScalable() &&
10602 "Mixing fixed width and scalable vectors when enveloping a type");
10603 EVT LoVT, HiVT;
10604 if (VTNumElts.getKnownMinValue() > EnvNumElts.getKnownMinValue()) {
10605 LoVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts);
10606 HiVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts - EnvNumElts);
10607 *HiIsEmpty = false;
10608 } else {
10609 // Flag that hi type has zero storage size, but return split envelop type
10610 // (this would be easier if vector types with zero elements were allowed).
10611 LoVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts);
10612 HiVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts);
10613 *HiIsEmpty = true;
10615 return std::make_pair(LoVT, HiVT);
10618 /// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the
10619 /// low/high part.
10620 std::pair<SDValue, SDValue>
10621 SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT,
10622 const EVT &HiVT) {
10623 assert(LoVT.isScalableVector() == HiVT.isScalableVector() &&
10624 LoVT.isScalableVector() == N.getValueType().isScalableVector() &&
10625 "Splitting vector with an invalid mixture of fixed and scalable "
10626 "vector types");
10627 assert(LoVT.getVectorMinNumElements() + HiVT.getVectorMinNumElements() <=
10628 N.getValueType().getVectorMinNumElements() &&
10629 "More vector elements requested than available!");
10630 SDValue Lo, Hi;
10631 Lo =
10632 getNode(ISD::EXTRACT_SUBVECTOR, DL, LoVT, N, getVectorIdxConstant(0, DL));
10633 // For scalable vectors it is safe to use LoVT.getVectorMinNumElements()
10634 // (rather than having to use ElementCount), because EXTRACT_SUBVECTOR scales
10635 // IDX with the runtime scaling factor of the result vector type. For
10636 // fixed-width result vectors, that runtime scaling factor is 1.
10637 Hi = getNode(ISD::EXTRACT_SUBVECTOR, DL, HiVT, N,
10638 getVectorIdxConstant(LoVT.getVectorMinNumElements(), DL));
10639 return std::make_pair(Lo, Hi);
10642 std::pair<SDValue, SDValue> SelectionDAG::SplitEVL(SDValue N, EVT VecVT,
10643 const SDLoc &DL) {
10644 // Split the vector length parameter.
10645 // %evl -> umin(%evl, %halfnumelts) and usubsat(%evl - %halfnumelts).
10646 EVT VT = N.getValueType();
10647 assert(VecVT.getVectorElementCount().isKnownEven() &&
10648 "Expecting the mask to be an evenly-sized vector");
10649 unsigned HalfMinNumElts = VecVT.getVectorMinNumElements() / 2;
10650 SDValue HalfNumElts =
10651 VecVT.isFixedLengthVector()
10652 ? getConstant(HalfMinNumElts, DL, VT)
10653 : getVScale(DL, VT, APInt(VT.getScalarSizeInBits(), HalfMinNumElts));
10654 SDValue Lo = getNode(ISD::UMIN, DL, VT, N, HalfNumElts);
10655 SDValue Hi = getNode(ISD::USUBSAT, DL, VT, N, HalfNumElts);
10656 return std::make_pair(Lo, Hi);
10659 /// Widen the vector up to the next power of two using INSERT_SUBVECTOR.
10660 SDValue SelectionDAG::WidenVector(const SDValue &N, const SDLoc &DL) {
10661 EVT VT = N.getValueType();
10662 EVT WideVT = EVT::getVectorVT(*getContext(), VT.getVectorElementType(),
10663 NextPowerOf2(VT.getVectorNumElements()));
10664 return getNode(ISD::INSERT_SUBVECTOR, DL, WideVT, getUNDEF(WideVT), N,
10665 getVectorIdxConstant(0, DL));
10668 void SelectionDAG::ExtractVectorElements(SDValue Op,
10669 SmallVectorImpl<SDValue> &Args,
10670 unsigned Start, unsigned Count,
10671 EVT EltVT) {
10672 EVT VT = Op.getValueType();
10673 if (Count == 0)
10674 Count = VT.getVectorNumElements();
10675 if (EltVT == EVT())
10676 EltVT = VT.getVectorElementType();
10677 SDLoc SL(Op);
10678 for (unsigned i = Start, e = Start + Count; i != e; ++i) {
10679 Args.push_back(getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Op,
10680 getVectorIdxConstant(i, SL)));
10684 // getAddressSpace - Return the address space this GlobalAddress belongs to.
10685 unsigned GlobalAddressSDNode::getAddressSpace() const {
10686 return getGlobal()->getType()->getAddressSpace();
10689 Type *ConstantPoolSDNode::getType() const {
10690 if (isMachineConstantPoolEntry())
10691 return Val.MachineCPVal->getType();
10692 return Val.ConstVal->getType();
10695 bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue, APInt &SplatUndef,
10696 unsigned &SplatBitSize,
10697 bool &HasAnyUndefs,
10698 unsigned MinSplatBits,
10699 bool IsBigEndian) const {
10700 EVT VT = getValueType(0);
10701 assert(VT.isVector() && "Expected a vector type");
10702 unsigned VecWidth = VT.getSizeInBits();
10703 if (MinSplatBits > VecWidth)
10704 return false;
10706 // FIXME: The widths are based on this node's type, but build vectors can
10707 // truncate their operands.
10708 SplatValue = APInt(VecWidth, 0);
10709 SplatUndef = APInt(VecWidth, 0);
10711 // Get the bits. Bits with undefined values (when the corresponding element
10712 // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared
10713 // in SplatValue. If any of the values are not constant, give up and return
10714 // false.
10715 unsigned int NumOps = getNumOperands();
10716 assert(NumOps > 0 && "isConstantSplat has 0-size build vector");
10717 unsigned EltWidth = VT.getScalarSizeInBits();
10719 for (unsigned j = 0; j < NumOps; ++j) {
10720 unsigned i = IsBigEndian ? NumOps - 1 - j : j;
10721 SDValue OpVal = getOperand(i);
10722 unsigned BitPos = j * EltWidth;
10724 if (OpVal.isUndef())
10725 SplatUndef.setBits(BitPos, BitPos + EltWidth);
10726 else if (auto *CN = dyn_cast<ConstantSDNode>(OpVal))
10727 SplatValue.insertBits(CN->getAPIntValue().zextOrTrunc(EltWidth), BitPos);
10728 else if (auto *CN = dyn_cast<ConstantFPSDNode>(OpVal))
10729 SplatValue.insertBits(CN->getValueAPF().bitcastToAPInt(), BitPos);
10730 else
10731 return false;
10734 // The build_vector is all constants or undefs. Find the smallest element
10735 // size that splats the vector.
10736 HasAnyUndefs = (SplatUndef != 0);
10738 // FIXME: This does not work for vectors with elements less than 8 bits.
10739 while (VecWidth > 8) {
10740 unsigned HalfSize = VecWidth / 2;
10741 APInt HighValue = SplatValue.extractBits(HalfSize, HalfSize);
10742 APInt LowValue = SplatValue.extractBits(HalfSize, 0);
10743 APInt HighUndef = SplatUndef.extractBits(HalfSize, HalfSize);
10744 APInt LowUndef = SplatUndef.extractBits(HalfSize, 0);
10746 // If the two halves do not match (ignoring undef bits), stop here.
10747 if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) ||
10748 MinSplatBits > HalfSize)
10749 break;
10751 SplatValue = HighValue | LowValue;
10752 SplatUndef = HighUndef & LowUndef;
10754 VecWidth = HalfSize;
10757 SplatBitSize = VecWidth;
10758 return true;
10761 SDValue BuildVectorSDNode::getSplatValue(const APInt &DemandedElts,
10762 BitVector *UndefElements) const {
10763 unsigned NumOps = getNumOperands();
10764 if (UndefElements) {
10765 UndefElements->clear();
10766 UndefElements->resize(NumOps);
10768 assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size");
10769 if (!DemandedElts)
10770 return SDValue();
10771 SDValue Splatted;
10772 for (unsigned i = 0; i != NumOps; ++i) {
10773 if (!DemandedElts[i])
10774 continue;
10775 SDValue Op = getOperand(i);
10776 if (Op.isUndef()) {
10777 if (UndefElements)
10778 (*UndefElements)[i] = true;
10779 } else if (!Splatted) {
10780 Splatted = Op;
10781 } else if (Splatted != Op) {
10782 return SDValue();
10786 if (!Splatted) {
10787 unsigned FirstDemandedIdx = DemandedElts.countTrailingZeros();
10788 assert(getOperand(FirstDemandedIdx).isUndef() &&
10789 "Can only have a splat without a constant for all undefs.");
10790 return getOperand(FirstDemandedIdx);
10793 return Splatted;
10796 SDValue BuildVectorSDNode::getSplatValue(BitVector *UndefElements) const {
10797 APInt DemandedElts = APInt::getAllOnes(getNumOperands());
10798 return getSplatValue(DemandedElts, UndefElements);
10801 bool BuildVectorSDNode::getRepeatedSequence(const APInt &DemandedElts,
10802 SmallVectorImpl<SDValue> &Sequence,
10803 BitVector *UndefElements) const {
10804 unsigned NumOps = getNumOperands();
10805 Sequence.clear();
10806 if (UndefElements) {
10807 UndefElements->clear();
10808 UndefElements->resize(NumOps);
10810 assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size");
10811 if (!DemandedElts || NumOps < 2 || !isPowerOf2_32(NumOps))
10812 return false;
10814 // Set the undefs even if we don't find a sequence (like getSplatValue).
10815 if (UndefElements)
10816 for (unsigned I = 0; I != NumOps; ++I)
10817 if (DemandedElts[I] && getOperand(I).isUndef())
10818 (*UndefElements)[I] = true;
10820 // Iteratively widen the sequence length looking for repetitions.
10821 for (unsigned SeqLen = 1; SeqLen < NumOps; SeqLen *= 2) {
10822 Sequence.append(SeqLen, SDValue());
10823 for (unsigned I = 0; I != NumOps; ++I) {
10824 if (!DemandedElts[I])
10825 continue;
10826 SDValue &SeqOp = Sequence[I % SeqLen];
10827 SDValue Op = getOperand(I);
10828 if (Op.isUndef()) {
10829 if (!SeqOp)
10830 SeqOp = Op;
10831 continue;
10833 if (SeqOp && !SeqOp.isUndef() && SeqOp != Op) {
10834 Sequence.clear();
10835 break;
10837 SeqOp = Op;
10839 if (!Sequence.empty())
10840 return true;
10843 assert(Sequence.empty() && "Failed to empty non-repeating sequence pattern");
10844 return false;
10847 bool BuildVectorSDNode::getRepeatedSequence(SmallVectorImpl<SDValue> &Sequence,
10848 BitVector *UndefElements) const {
10849 APInt DemandedElts = APInt::getAllOnes(getNumOperands());
10850 return getRepeatedSequence(DemandedElts, Sequence, UndefElements);
10853 ConstantSDNode *
10854 BuildVectorSDNode::getConstantSplatNode(const APInt &DemandedElts,
10855 BitVector *UndefElements) const {
10856 return dyn_cast_or_null<ConstantSDNode>(
10857 getSplatValue(DemandedElts, UndefElements));
10860 ConstantSDNode *
10861 BuildVectorSDNode::getConstantSplatNode(BitVector *UndefElements) const {
10862 return dyn_cast_or_null<ConstantSDNode>(getSplatValue(UndefElements));
10865 ConstantFPSDNode *
10866 BuildVectorSDNode::getConstantFPSplatNode(const APInt &DemandedElts,
10867 BitVector *UndefElements) const {
10868 return dyn_cast_or_null<ConstantFPSDNode>(
10869 getSplatValue(DemandedElts, UndefElements));
10872 ConstantFPSDNode *
10873 BuildVectorSDNode::getConstantFPSplatNode(BitVector *UndefElements) const {
10874 return dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements));
10877 int32_t
10878 BuildVectorSDNode::getConstantFPSplatPow2ToLog2Int(BitVector *UndefElements,
10879 uint32_t BitWidth) const {
10880 if (ConstantFPSDNode *CN =
10881 dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements))) {
10882 bool IsExact;
10883 APSInt IntVal(BitWidth);
10884 const APFloat &APF = CN->getValueAPF();
10885 if (APF.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) !=
10886 APFloat::opOK ||
10887 !IsExact)
10888 return -1;
10890 return IntVal.exactLogBase2();
10892 return -1;
10895 bool BuildVectorSDNode::getConstantRawBits(
10896 bool IsLittleEndian, unsigned DstEltSizeInBits,
10897 SmallVectorImpl<APInt> &RawBitElements, BitVector &UndefElements) const {
10898 // Early-out if this contains anything but Undef/Constant/ConstantFP.
10899 if (!isConstant())
10900 return false;
10902 unsigned NumSrcOps = getNumOperands();
10903 unsigned SrcEltSizeInBits = getValueType(0).getScalarSizeInBits();
10904 assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 &&
10905 "Invalid bitcast scale");
10907 // Extract raw src bits.
10908 SmallVector<APInt> SrcBitElements(NumSrcOps,
10909 APInt::getNullValue(SrcEltSizeInBits));
10910 BitVector SrcUndeElements(NumSrcOps, false);
10912 for (unsigned I = 0; I != NumSrcOps; ++I) {
10913 SDValue Op = getOperand(I);
10914 if (Op.isUndef()) {
10915 SrcUndeElements.set(I);
10916 continue;
10918 auto *CInt = dyn_cast<ConstantSDNode>(Op);
10919 auto *CFP = dyn_cast<ConstantFPSDNode>(Op);
10920 assert((CInt || CFP) && "Unknown constant");
10921 SrcBitElements[I] =
10922 CInt ? CInt->getAPIntValue().truncOrSelf(SrcEltSizeInBits)
10923 : CFP->getValueAPF().bitcastToAPInt();
10926 // Recast to dst width.
10927 recastRawBits(IsLittleEndian, DstEltSizeInBits, RawBitElements,
10928 SrcBitElements, UndefElements, SrcUndeElements);
10929 return true;
10932 void BuildVectorSDNode::recastRawBits(bool IsLittleEndian,
10933 unsigned DstEltSizeInBits,
10934 SmallVectorImpl<APInt> &DstBitElements,
10935 ArrayRef<APInt> SrcBitElements,
10936 BitVector &DstUndefElements,
10937 const BitVector &SrcUndefElements) {
10938 unsigned NumSrcOps = SrcBitElements.size();
10939 unsigned SrcEltSizeInBits = SrcBitElements[0].getBitWidth();
10940 assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 &&
10941 "Invalid bitcast scale");
10942 assert(NumSrcOps == SrcUndefElements.size() &&
10943 "Vector size mismatch");
10945 unsigned NumDstOps = (NumSrcOps * SrcEltSizeInBits) / DstEltSizeInBits;
10946 DstUndefElements.clear();
10947 DstUndefElements.resize(NumDstOps, false);
10948 DstBitElements.assign(NumDstOps, APInt::getNullValue(DstEltSizeInBits));
10950 // Concatenate src elements constant bits together into dst element.
10951 if (SrcEltSizeInBits <= DstEltSizeInBits) {
10952 unsigned Scale = DstEltSizeInBits / SrcEltSizeInBits;
10953 for (unsigned I = 0; I != NumDstOps; ++I) {
10954 DstUndefElements.set(I);
10955 APInt &DstBits = DstBitElements[I];
10956 for (unsigned J = 0; J != Scale; ++J) {
10957 unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1));
10958 if (SrcUndefElements[Idx])
10959 continue;
10960 DstUndefElements.reset(I);
10961 const APInt &SrcBits = SrcBitElements[Idx];
10962 assert(SrcBits.getBitWidth() == SrcEltSizeInBits &&
10963 "Illegal constant bitwidths");
10964 DstBits.insertBits(SrcBits, J * SrcEltSizeInBits);
10967 return;
10970 // Split src element constant bits into dst elements.
10971 unsigned Scale = SrcEltSizeInBits / DstEltSizeInBits;
10972 for (unsigned I = 0; I != NumSrcOps; ++I) {
10973 if (SrcUndefElements[I]) {
10974 DstUndefElements.set(I * Scale, (I + 1) * Scale);
10975 continue;
10977 const APInt &SrcBits = SrcBitElements[I];
10978 for (unsigned J = 0; J != Scale; ++J) {
10979 unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1));
10980 APInt &DstBits = DstBitElements[Idx];
10981 DstBits = SrcBits.extractBits(DstEltSizeInBits, J * DstEltSizeInBits);
10986 bool BuildVectorSDNode::isConstant() const {
10987 for (const SDValue &Op : op_values()) {
10988 unsigned Opc = Op.getOpcode();
10989 if (Opc != ISD::UNDEF && Opc != ISD::Constant && Opc != ISD::ConstantFP)
10990 return false;
10992 return true;
10995 bool ShuffleVectorSDNode::isSplatMask(const int *Mask, EVT VT) {
10996 // Find the first non-undef value in the shuffle mask.
10997 unsigned i, e;
10998 for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i)
10999 /* search */;
11001 // If all elements are undefined, this shuffle can be considered a splat
11002 // (although it should eventually get simplified away completely).
11003 if (i == e)
11004 return true;
11006 // Make sure all remaining elements are either undef or the same as the first
11007 // non-undef value.
11008 for (int Idx = Mask[i]; i != e; ++i)
11009 if (Mask[i] >= 0 && Mask[i] != Idx)
11010 return false;
11011 return true;
11014 // Returns the SDNode if it is a constant integer BuildVector
11015 // or constant integer.
11016 SDNode *SelectionDAG::isConstantIntBuildVectorOrConstantInt(SDValue N) const {
11017 if (isa<ConstantSDNode>(N))
11018 return N.getNode();
11019 if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
11020 return N.getNode();
11021 // Treat a GlobalAddress supporting constant offset folding as a
11022 // constant integer.
11023 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N))
11024 if (GA->getOpcode() == ISD::GlobalAddress &&
11025 TLI->isOffsetFoldingLegal(GA))
11026 return GA;
11027 if ((N.getOpcode() == ISD::SPLAT_VECTOR) &&
11028 isa<ConstantSDNode>(N.getOperand(0)))
11029 return N.getNode();
11030 return nullptr;
11033 // Returns the SDNode if it is a constant float BuildVector
11034 // or constant float.
11035 SDNode *SelectionDAG::isConstantFPBuildVectorOrConstantFP(SDValue N) const {
11036 if (isa<ConstantFPSDNode>(N))
11037 return N.getNode();
11039 if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
11040 return N.getNode();
11042 return nullptr;
11045 void SelectionDAG::createOperands(SDNode *Node, ArrayRef<SDValue> Vals) {
11046 assert(!Node->OperandList && "Node already has operands");
11047 assert(SDNode::getMaxNumOperands() >= Vals.size() &&
11048 "too many operands to fit into SDNode");
11049 SDUse *Ops = OperandRecycler.allocate(
11050 ArrayRecycler<SDUse>::Capacity::get(Vals.size()), OperandAllocator);
11052 bool IsDivergent = false;
11053 for (unsigned I = 0; I != Vals.size(); ++I) {
11054 Ops[I].setUser(Node);
11055 Ops[I].setInitial(Vals[I]);
11056 if (Ops[I].Val.getValueType() != MVT::Other) // Skip Chain. It does not carry divergence.
11057 IsDivergent |= Ops[I].getNode()->isDivergent();
11059 Node->NumOperands = Vals.size();
11060 Node->OperandList = Ops;
11061 if (!TLI->isSDNodeAlwaysUniform(Node)) {
11062 IsDivergent |= TLI->isSDNodeSourceOfDivergence(Node, FLI, DA);
11063 Node->SDNodeBits.IsDivergent = IsDivergent;
11065 checkForCycles(Node);
11068 SDValue SelectionDAG::getTokenFactor(const SDLoc &DL,
11069 SmallVectorImpl<SDValue> &Vals) {
11070 size_t Limit = SDNode::getMaxNumOperands();
11071 while (Vals.size() > Limit) {
11072 unsigned SliceIdx = Vals.size() - Limit;
11073 auto ExtractedTFs = ArrayRef<SDValue>(Vals).slice(SliceIdx, Limit);
11074 SDValue NewTF = getNode(ISD::TokenFactor, DL, MVT::Other, ExtractedTFs);
11075 Vals.erase(Vals.begin() + SliceIdx, Vals.end());
11076 Vals.emplace_back(NewTF);
11078 return getNode(ISD::TokenFactor, DL, MVT::Other, Vals);
11081 SDValue SelectionDAG::getNeutralElement(unsigned Opcode, const SDLoc &DL,
11082 EVT VT, SDNodeFlags Flags) {
11083 switch (Opcode) {
11084 default:
11085 return SDValue();
11086 case ISD::ADD:
11087 case ISD::OR:
11088 case ISD::XOR:
11089 case ISD::UMAX:
11090 return getConstant(0, DL, VT);
11091 case ISD::MUL:
11092 return getConstant(1, DL, VT);
11093 case ISD::AND:
11094 case ISD::UMIN:
11095 return getAllOnesConstant(DL, VT);
11096 case ISD::SMAX:
11097 return getConstant(APInt::getSignedMinValue(VT.getSizeInBits()), DL, VT);
11098 case ISD::SMIN:
11099 return getConstant(APInt::getSignedMaxValue(VT.getSizeInBits()), DL, VT);
11100 case ISD::FADD:
11101 return getConstantFP(-0.0, DL, VT);
11102 case ISD::FMUL:
11103 return getConstantFP(1.0, DL, VT);
11104 case ISD::FMINNUM:
11105 case ISD::FMAXNUM: {
11106 // Neutral element for fminnum is NaN, Inf or FLT_MAX, depending on FMF.
11107 const fltSemantics &Semantics = EVTToAPFloatSemantics(VT);
11108 APFloat NeutralAF = !Flags.hasNoNaNs() ? APFloat::getQNaN(Semantics) :
11109 !Flags.hasNoInfs() ? APFloat::getInf(Semantics) :
11110 APFloat::getLargest(Semantics);
11111 if (Opcode == ISD::FMAXNUM)
11112 NeutralAF.changeSign();
11114 return getConstantFP(NeutralAF, DL, VT);
11119 #ifndef NDEBUG
11120 static void checkForCyclesHelper(const SDNode *N,
11121 SmallPtrSetImpl<const SDNode*> &Visited,
11122 SmallPtrSetImpl<const SDNode*> &Checked,
11123 const llvm::SelectionDAG *DAG) {
11124 // If this node has already been checked, don't check it again.
11125 if (Checked.count(N))
11126 return;
11128 // If a node has already been visited on this depth-first walk, reject it as
11129 // a cycle.
11130 if (!Visited.insert(N).second) {
11131 errs() << "Detected cycle in SelectionDAG\n";
11132 dbgs() << "Offending node:\n";
11133 N->dumprFull(DAG); dbgs() << "\n";
11134 abort();
11137 for (const SDValue &Op : N->op_values())
11138 checkForCyclesHelper(Op.getNode(), Visited, Checked, DAG);
11140 Checked.insert(N);
11141 Visited.erase(N);
11143 #endif
11145 void llvm::checkForCycles(const llvm::SDNode *N,
11146 const llvm::SelectionDAG *DAG,
11147 bool force) {
11148 #ifndef NDEBUG
11149 bool check = force;
11150 #ifdef EXPENSIVE_CHECKS
11151 check = true;
11152 #endif // EXPENSIVE_CHECKS
11153 if (check) {
11154 assert(N && "Checking nonexistent SDNode");
11155 SmallPtrSet<const SDNode*, 32> visited;
11156 SmallPtrSet<const SDNode*, 32> checked;
11157 checkForCyclesHelper(N, visited, checked, DAG);
11159 #endif // !NDEBUG
11162 void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) {
11163 checkForCycles(DAG->getRoot().getNode(), DAG, force);