xref: /freebsd-src/contrib/llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAG.cpp (revision 753f127f3ace09432b2baeffd71a308760641a62)
1 //===- SelectionDAG.cpp - Implement the SelectionDAG data structures ------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This implements the SelectionDAG class.
10 //
11 //===----------------------------------------------------------------------===//
12 
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/MemoryLocation.h"
28 #include "llvm/Analysis/ValueTracking.h"
29 #include "llvm/CodeGen/Analysis.h"
30 #include "llvm/CodeGen/FunctionLoweringInfo.h"
31 #include "llvm/CodeGen/ISDOpcodes.h"
32 #include "llvm/CodeGen/MachineBasicBlock.h"
33 #include "llvm/CodeGen/MachineConstantPool.h"
34 #include "llvm/CodeGen/MachineFrameInfo.h"
35 #include "llvm/CodeGen/MachineFunction.h"
36 #include "llvm/CodeGen/MachineMemOperand.h"
37 #include "llvm/CodeGen/RuntimeLibcalls.h"
38 #include "llvm/CodeGen/SelectionDAGAddressAnalysis.h"
39 #include "llvm/CodeGen/SelectionDAGNodes.h"
40 #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
41 #include "llvm/CodeGen/TargetFrameLowering.h"
42 #include "llvm/CodeGen/TargetLowering.h"
43 #include "llvm/CodeGen/TargetRegisterInfo.h"
44 #include "llvm/CodeGen/TargetSubtargetInfo.h"
45 #include "llvm/CodeGen/ValueTypes.h"
46 #include "llvm/IR/Constant.h"
47 #include "llvm/IR/Constants.h"
48 #include "llvm/IR/DataLayout.h"
49 #include "llvm/IR/DebugInfoMetadata.h"
50 #include "llvm/IR/DebugLoc.h"
51 #include "llvm/IR/DerivedTypes.h"
52 #include "llvm/IR/Function.h"
53 #include "llvm/IR/GlobalValue.h"
54 #include "llvm/IR/Metadata.h"
55 #include "llvm/IR/Type.h"
56 #include "llvm/Support/Casting.h"
57 #include "llvm/Support/CodeGen.h"
58 #include "llvm/Support/Compiler.h"
59 #include "llvm/Support/Debug.h"
60 #include "llvm/Support/ErrorHandling.h"
61 #include "llvm/Support/KnownBits.h"
62 #include "llvm/Support/MachineValueType.h"
63 #include "llvm/Support/MathExtras.h"
64 #include "llvm/Support/Mutex.h"
65 #include "llvm/Support/raw_ostream.h"
66 #include "llvm/Target/TargetMachine.h"
67 #include "llvm/Target/TargetOptions.h"
68 #include "llvm/Transforms/Utils/SizeOpts.h"
69 #include <algorithm>
70 #include <cassert>
71 #include <cstdint>
72 #include <cstdlib>
73 #include <limits>
74 #include <set>
75 #include <string>
76 #include <utility>
77 #include <vector>
78 
79 using namespace llvm;
80 
81 /// makeVTList - Return an instance of the SDVTList struct initialized with the
82 /// specified members.
83 static SDVTList makeVTList(const EVT *VTs, unsigned NumVTs) {
84   SDVTList Res = {VTs, NumVTs};
85   return Res;
86 }
87 
88 // Default null implementations of the callbacks.
89 void SelectionDAG::DAGUpdateListener::NodeDeleted(SDNode*, SDNode*) {}
90 void SelectionDAG::DAGUpdateListener::NodeUpdated(SDNode*) {}
91 void SelectionDAG::DAGUpdateListener::NodeInserted(SDNode *) {}
92 
93 void SelectionDAG::DAGNodeDeletedListener::anchor() {}
94 
95 #define DEBUG_TYPE "selectiondag"
96 
97 static cl::opt<bool> EnableMemCpyDAGOpt("enable-memcpy-dag-opt",
98        cl::Hidden, cl::init(true),
99        cl::desc("Gang up loads and stores generated by inlining of memcpy"));
100 
101 static cl::opt<int> MaxLdStGlue("ldstmemcpy-glue-max",
102        cl::desc("Number limit for gluing ld/st of memcpy."),
103        cl::Hidden, cl::init(0));
104 
105 static void NewSDValueDbgMsg(SDValue V, StringRef Msg, SelectionDAG *G) {
106   LLVM_DEBUG(dbgs() << Msg; V.getNode()->dump(G););
107 }
108 
109 //===----------------------------------------------------------------------===//
110 //                              ConstantFPSDNode Class
111 //===----------------------------------------------------------------------===//
112 
113 /// isExactlyValue - We don't rely on operator== working on double values, as
114 /// it returns true for things that are clearly not equal, like -0.0 and 0.0.
115 /// As such, this method can be used to do an exact bit-for-bit comparison of
116 /// two floating point values.
117 bool ConstantFPSDNode::isExactlyValue(const APFloat& V) const {
118   return getValueAPF().bitwiseIsEqual(V);
119 }
120 
121 bool ConstantFPSDNode::isValueValidForType(EVT VT,
122                                            const APFloat& Val) {
123   assert(VT.isFloatingPoint() && "Can only convert between FP types");
124 
125   // convert modifies in place, so make a copy.
126   APFloat Val2 = APFloat(Val);
127   bool losesInfo;
128   (void) Val2.convert(SelectionDAG::EVTToAPFloatSemantics(VT),
129                       APFloat::rmNearestTiesToEven,
130                       &losesInfo);
131   return !losesInfo;
132 }
133 
134 //===----------------------------------------------------------------------===//
135 //                              ISD Namespace
136 //===----------------------------------------------------------------------===//
137 
138 bool ISD::isConstantSplatVector(const SDNode *N, APInt &SplatVal) {
139   if (N->getOpcode() == ISD::SPLAT_VECTOR) {
140     unsigned EltSize =
141         N->getValueType(0).getVectorElementType().getSizeInBits();
142     if (auto *Op0 = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
143       SplatVal = Op0->getAPIntValue().trunc(EltSize);
144       return true;
145     }
146     if (auto *Op0 = dyn_cast<ConstantFPSDNode>(N->getOperand(0))) {
147       SplatVal = Op0->getValueAPF().bitcastToAPInt().trunc(EltSize);
148       return true;
149     }
150   }
151 
152   auto *BV = dyn_cast<BuildVectorSDNode>(N);
153   if (!BV)
154     return false;
155 
156   APInt SplatUndef;
157   unsigned SplatBitSize;
158   bool HasUndefs;
159   unsigned EltSize = N->getValueType(0).getVectorElementType().getSizeInBits();
160   return BV->isConstantSplat(SplatVal, SplatUndef, SplatBitSize, HasUndefs,
161                              EltSize) &&
162          EltSize == SplatBitSize;
163 }
164 
165 // FIXME: AllOnes and AllZeros duplicate a lot of code. Could these be
166 // specializations of the more general isConstantSplatVector()?
167 
168 bool ISD::isConstantSplatVectorAllOnes(const SDNode *N, bool BuildVectorOnly) {
169   // Look through a bit convert.
170   while (N->getOpcode() == ISD::BITCAST)
171     N = N->getOperand(0).getNode();
172 
173   if (!BuildVectorOnly && N->getOpcode() == ISD::SPLAT_VECTOR) {
174     APInt SplatVal;
175     return isConstantSplatVector(N, SplatVal) && SplatVal.isAllOnes();
176   }
177 
178   if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
179 
180   unsigned i = 0, e = N->getNumOperands();
181 
182   // Skip over all of the undef values.
183   while (i != e && N->getOperand(i).isUndef())
184     ++i;
185 
186   // Do not accept an all-undef vector.
187   if (i == e) return false;
188 
189   // Do not accept build_vectors that aren't all constants or which have non-~0
190   // elements. We have to be a bit careful here, as the type of the constant
191   // may not be the same as the type of the vector elements due to type
192   // legalization (the elements are promoted to a legal type for the target and
193   // a vector of a type may be legal when the base element type is not).
194   // We only want to check enough bits to cover the vector elements, because
195   // we care if the resultant vector is all ones, not whether the individual
196   // constants are.
197   SDValue NotZero = N->getOperand(i);
198   unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
199   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(NotZero)) {
200     if (CN->getAPIntValue().countTrailingOnes() < EltSize)
201       return false;
202   } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(NotZero)) {
203     if (CFPN->getValueAPF().bitcastToAPInt().countTrailingOnes() < EltSize)
204       return false;
205   } else
206     return false;
207 
208   // Okay, we have at least one ~0 value, check to see if the rest match or are
209   // undefs. Even with the above element type twiddling, this should be OK, as
210   // the same type legalization should have applied to all the elements.
211   for (++i; i != e; ++i)
212     if (N->getOperand(i) != NotZero && !N->getOperand(i).isUndef())
213       return false;
214   return true;
215 }
216 
217 bool ISD::isConstantSplatVectorAllZeros(const SDNode *N, bool BuildVectorOnly) {
218   // Look through a bit convert.
219   while (N->getOpcode() == ISD::BITCAST)
220     N = N->getOperand(0).getNode();
221 
222   if (!BuildVectorOnly && N->getOpcode() == ISD::SPLAT_VECTOR) {
223     APInt SplatVal;
224     return isConstantSplatVector(N, SplatVal) && SplatVal.isZero();
225   }
226 
227   if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
228 
229   bool IsAllUndef = true;
230   for (const SDValue &Op : N->op_values()) {
231     if (Op.isUndef())
232       continue;
233     IsAllUndef = false;
234     // Do not accept build_vectors that aren't all constants or which have non-0
235     // elements. We have to be a bit careful here, as the type of the constant
236     // may not be the same as the type of the vector elements due to type
237     // legalization (the elements are promoted to a legal type for the target
238     // and a vector of a type may be legal when the base element type is not).
239     // We only want to check enough bits to cover the vector elements, because
240     // we care if the resultant vector is all zeros, not whether the individual
241     // constants are.
242     unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
243     if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Op)) {
244       if (CN->getAPIntValue().countTrailingZeros() < EltSize)
245         return false;
246     } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(Op)) {
247       if (CFPN->getValueAPF().bitcastToAPInt().countTrailingZeros() < EltSize)
248         return false;
249     } else
250       return false;
251   }
252 
253   // Do not accept an all-undef vector.
254   if (IsAllUndef)
255     return false;
256   return true;
257 }
258 
259 bool ISD::isBuildVectorAllOnes(const SDNode *N) {
260   return isConstantSplatVectorAllOnes(N, /*BuildVectorOnly*/ true);
261 }
262 
263 bool ISD::isBuildVectorAllZeros(const SDNode *N) {
264   return isConstantSplatVectorAllZeros(N, /*BuildVectorOnly*/ true);
265 }
266 
267 bool ISD::isBuildVectorOfConstantSDNodes(const SDNode *N) {
268   if (N->getOpcode() != ISD::BUILD_VECTOR)
269     return false;
270 
271   for (const SDValue &Op : N->op_values()) {
272     if (Op.isUndef())
273       continue;
274     if (!isa<ConstantSDNode>(Op))
275       return false;
276   }
277   return true;
278 }
279 
280 bool ISD::isBuildVectorOfConstantFPSDNodes(const SDNode *N) {
281   if (N->getOpcode() != ISD::BUILD_VECTOR)
282     return false;
283 
284   for (const SDValue &Op : N->op_values()) {
285     if (Op.isUndef())
286       continue;
287     if (!isa<ConstantFPSDNode>(Op))
288       return false;
289   }
290   return true;
291 }
292 
293 bool ISD::allOperandsUndef(const SDNode *N) {
294   // Return false if the node has no operands.
295   // This is "logically inconsistent" with the definition of "all" but
296   // is probably the desired behavior.
297   if (N->getNumOperands() == 0)
298     return false;
299   return all_of(N->op_values(), [](SDValue Op) { return Op.isUndef(); });
300 }
301 
302 bool ISD::matchUnaryPredicate(SDValue Op,
303                               std::function<bool(ConstantSDNode *)> Match,
304                               bool AllowUndefs) {
305   // FIXME: Add support for scalar UNDEF cases?
306   if (auto *Cst = dyn_cast<ConstantSDNode>(Op))
307     return Match(Cst);
308 
309   // FIXME: Add support for vector UNDEF cases?
310   if (ISD::BUILD_VECTOR != Op.getOpcode() &&
311       ISD::SPLAT_VECTOR != Op.getOpcode())
312     return false;
313 
314   EVT SVT = Op.getValueType().getScalarType();
315   for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
316     if (AllowUndefs && Op.getOperand(i).isUndef()) {
317       if (!Match(nullptr))
318         return false;
319       continue;
320     }
321 
322     auto *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(i));
323     if (!Cst || Cst->getValueType(0) != SVT || !Match(Cst))
324       return false;
325   }
326   return true;
327 }
328 
329 bool ISD::matchBinaryPredicate(
330     SDValue LHS, SDValue RHS,
331     std::function<bool(ConstantSDNode *, ConstantSDNode *)> Match,
332     bool AllowUndefs, bool AllowTypeMismatch) {
333   if (!AllowTypeMismatch && LHS.getValueType() != RHS.getValueType())
334     return false;
335 
336   // TODO: Add support for scalar UNDEF cases?
337   if (auto *LHSCst = dyn_cast<ConstantSDNode>(LHS))
338     if (auto *RHSCst = dyn_cast<ConstantSDNode>(RHS))
339       return Match(LHSCst, RHSCst);
340 
341   // TODO: Add support for vector UNDEF cases?
342   if (LHS.getOpcode() != RHS.getOpcode() ||
343       (LHS.getOpcode() != ISD::BUILD_VECTOR &&
344        LHS.getOpcode() != ISD::SPLAT_VECTOR))
345     return false;
346 
347   EVT SVT = LHS.getValueType().getScalarType();
348   for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
349     SDValue LHSOp = LHS.getOperand(i);
350     SDValue RHSOp = RHS.getOperand(i);
351     bool LHSUndef = AllowUndefs && LHSOp.isUndef();
352     bool RHSUndef = AllowUndefs && RHSOp.isUndef();
353     auto *LHSCst = dyn_cast<ConstantSDNode>(LHSOp);
354     auto *RHSCst = dyn_cast<ConstantSDNode>(RHSOp);
355     if ((!LHSCst && !LHSUndef) || (!RHSCst && !RHSUndef))
356       return false;
357     if (!AllowTypeMismatch && (LHSOp.getValueType() != SVT ||
358                                LHSOp.getValueType() != RHSOp.getValueType()))
359       return false;
360     if (!Match(LHSCst, RHSCst))
361       return false;
362   }
363   return true;
364 }
365 
366 ISD::NodeType ISD::getVecReduceBaseOpcode(unsigned VecReduceOpcode) {
367   switch (VecReduceOpcode) {
368   default:
369     llvm_unreachable("Expected VECREDUCE opcode");
370   case ISD::VECREDUCE_FADD:
371   case ISD::VECREDUCE_SEQ_FADD:
372   case ISD::VP_REDUCE_FADD:
373   case ISD::VP_REDUCE_SEQ_FADD:
374     return ISD::FADD;
375   case ISD::VECREDUCE_FMUL:
376   case ISD::VECREDUCE_SEQ_FMUL:
377   case ISD::VP_REDUCE_FMUL:
378   case ISD::VP_REDUCE_SEQ_FMUL:
379     return ISD::FMUL;
380   case ISD::VECREDUCE_ADD:
381   case ISD::VP_REDUCE_ADD:
382     return ISD::ADD;
383   case ISD::VECREDUCE_MUL:
384   case ISD::VP_REDUCE_MUL:
385     return ISD::MUL;
386   case ISD::VECREDUCE_AND:
387   case ISD::VP_REDUCE_AND:
388     return ISD::AND;
389   case ISD::VECREDUCE_OR:
390   case ISD::VP_REDUCE_OR:
391     return ISD::OR;
392   case ISD::VECREDUCE_XOR:
393   case ISD::VP_REDUCE_XOR:
394     return ISD::XOR;
395   case ISD::VECREDUCE_SMAX:
396   case ISD::VP_REDUCE_SMAX:
397     return ISD::SMAX;
398   case ISD::VECREDUCE_SMIN:
399   case ISD::VP_REDUCE_SMIN:
400     return ISD::SMIN;
401   case ISD::VECREDUCE_UMAX:
402   case ISD::VP_REDUCE_UMAX:
403     return ISD::UMAX;
404   case ISD::VECREDUCE_UMIN:
405   case ISD::VP_REDUCE_UMIN:
406     return ISD::UMIN;
407   case ISD::VECREDUCE_FMAX:
408   case ISD::VP_REDUCE_FMAX:
409     return ISD::FMAXNUM;
410   case ISD::VECREDUCE_FMIN:
411   case ISD::VP_REDUCE_FMIN:
412     return ISD::FMINNUM;
413   }
414 }
415 
416 bool ISD::isVPOpcode(unsigned Opcode) {
417   switch (Opcode) {
418   default:
419     return false;
420 #define BEGIN_REGISTER_VP_SDNODE(VPSD, ...)                                    \
421   case ISD::VPSD:                                                              \
422     return true;
423 #include "llvm/IR/VPIntrinsics.def"
424   }
425 }
426 
427 bool ISD::isVPBinaryOp(unsigned Opcode) {
428   switch (Opcode) {
429   default:
430     break;
431 #define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) case ISD::VPSD:
432 #define VP_PROPERTY_BINARYOP return true;
433 #define END_REGISTER_VP_SDNODE(VPSD) break;
434 #include "llvm/IR/VPIntrinsics.def"
435   }
436   return false;
437 }
438 
439 bool ISD::isVPReduction(unsigned Opcode) {
440   switch (Opcode) {
441   default:
442     break;
443 #define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) case ISD::VPSD:
444 #define VP_PROPERTY_REDUCTION(STARTPOS, ...) return true;
445 #define END_REGISTER_VP_SDNODE(VPSD) break;
446 #include "llvm/IR/VPIntrinsics.def"
447   }
448   return false;
449 }
450 
451 /// The operand position of the vector mask.
452 Optional<unsigned> ISD::getVPMaskIdx(unsigned Opcode) {
453   switch (Opcode) {
454   default:
455     return None;
456 #define BEGIN_REGISTER_VP_SDNODE(VPSD, LEGALPOS, TDNAME, MASKPOS, ...)         \
457   case ISD::VPSD:                                                              \
458     return MASKPOS;
459 #include "llvm/IR/VPIntrinsics.def"
460   }
461 }
462 
463 /// The operand position of the explicit vector length parameter.
464 Optional<unsigned> ISD::getVPExplicitVectorLengthIdx(unsigned Opcode) {
465   switch (Opcode) {
466   default:
467     return None;
468 #define BEGIN_REGISTER_VP_SDNODE(VPSD, LEGALPOS, TDNAME, MASKPOS, EVLPOS)      \
469   case ISD::VPSD:                                                              \
470     return EVLPOS;
471 #include "llvm/IR/VPIntrinsics.def"
472   }
473 }
474 
475 ISD::NodeType ISD::getExtForLoadExtType(bool IsFP, ISD::LoadExtType ExtType) {
476   switch (ExtType) {
477   case ISD::EXTLOAD:
478     return IsFP ? ISD::FP_EXTEND : ISD::ANY_EXTEND;
479   case ISD::SEXTLOAD:
480     return ISD::SIGN_EXTEND;
481   case ISD::ZEXTLOAD:
482     return ISD::ZERO_EXTEND;
483   default:
484     break;
485   }
486 
487   llvm_unreachable("Invalid LoadExtType");
488 }
489 
490 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) {
491   // To perform this operation, we just need to swap the L and G bits of the
492   // operation.
493   unsigned OldL = (Operation >> 2) & 1;
494   unsigned OldG = (Operation >> 1) & 1;
495   return ISD::CondCode((Operation & ~6) |  // Keep the N, U, E bits
496                        (OldL << 1) |       // New G bit
497                        (OldG << 2));       // New L bit.
498 }
499 
500 static ISD::CondCode getSetCCInverseImpl(ISD::CondCode Op, bool isIntegerLike) {
501   unsigned Operation = Op;
502   if (isIntegerLike)
503     Operation ^= 7;   // Flip L, G, E bits, but not U.
504   else
505     Operation ^= 15;  // Flip all of the condition bits.
506 
507   if (Operation > ISD::SETTRUE2)
508     Operation &= ~8;  // Don't let N and U bits get set.
509 
510   return ISD::CondCode(Operation);
511 }
512 
513 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, EVT Type) {
514   return getSetCCInverseImpl(Op, Type.isInteger());
515 }
516 
517 ISD::CondCode ISD::GlobalISel::getSetCCInverse(ISD::CondCode Op,
518                                                bool isIntegerLike) {
519   return getSetCCInverseImpl(Op, isIntegerLike);
520 }
521 
522 /// For an integer comparison, return 1 if the comparison is a signed operation
523 /// and 2 if the result is an unsigned comparison. Return zero if the operation
524 /// does not depend on the sign of the input (setne and seteq).
525 static int isSignedOp(ISD::CondCode Opcode) {
526   switch (Opcode) {
527   default: llvm_unreachable("Illegal integer setcc operation!");
528   case ISD::SETEQ:
529   case ISD::SETNE: return 0;
530   case ISD::SETLT:
531   case ISD::SETLE:
532   case ISD::SETGT:
533   case ISD::SETGE: return 1;
534   case ISD::SETULT:
535   case ISD::SETULE:
536   case ISD::SETUGT:
537   case ISD::SETUGE: return 2;
538   }
539 }
540 
541 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2,
542                                        EVT Type) {
543   bool IsInteger = Type.isInteger();
544   if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
545     // Cannot fold a signed integer setcc with an unsigned integer setcc.
546     return ISD::SETCC_INVALID;
547 
548   unsigned Op = Op1 | Op2;  // Combine all of the condition bits.
549 
550   // If the N and U bits get set, then the resultant comparison DOES suddenly
551   // care about orderedness, and it is true when ordered.
552   if (Op > ISD::SETTRUE2)
553     Op &= ~16;     // Clear the U bit if the N bit is set.
554 
555   // Canonicalize illegal integer setcc's.
556   if (IsInteger && Op == ISD::SETUNE)  // e.g. SETUGT | SETULT
557     Op = ISD::SETNE;
558 
559   return ISD::CondCode(Op);
560 }
561 
562 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2,
563                                         EVT Type) {
564   bool IsInteger = Type.isInteger();
565   if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
566     // Cannot fold a signed setcc with an unsigned setcc.
567     return ISD::SETCC_INVALID;
568 
569   // Combine all of the condition bits.
570   ISD::CondCode Result = ISD::CondCode(Op1 & Op2);
571 
572   // Canonicalize illegal integer setcc's.
573   if (IsInteger) {
574     switch (Result) {
575     default: break;
576     case ISD::SETUO : Result = ISD::SETFALSE; break;  // SETUGT & SETULT
577     case ISD::SETOEQ:                                 // SETEQ  & SETU[LG]E
578     case ISD::SETUEQ: Result = ISD::SETEQ   ; break;  // SETUGE & SETULE
579     case ISD::SETOLT: Result = ISD::SETULT  ; break;  // SETULT & SETNE
580     case ISD::SETOGT: Result = ISD::SETUGT  ; break;  // SETUGT & SETNE
581     }
582   }
583 
584   return Result;
585 }
586 
587 //===----------------------------------------------------------------------===//
588 //                           SDNode Profile Support
589 //===----------------------------------------------------------------------===//
590 
591 /// AddNodeIDOpcode - Add the node opcode to the NodeID data.
592 static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC)  {
593   ID.AddInteger(OpC);
594 }
595 
596 /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them
597 /// solely with their pointer.
598 static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) {
599   ID.AddPointer(VTList.VTs);
600 }
601 
602 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
603 static void AddNodeIDOperands(FoldingSetNodeID &ID,
604                               ArrayRef<SDValue> Ops) {
605   for (auto& Op : Ops) {
606     ID.AddPointer(Op.getNode());
607     ID.AddInteger(Op.getResNo());
608   }
609 }
610 
611 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
612 static void AddNodeIDOperands(FoldingSetNodeID &ID,
613                               ArrayRef<SDUse> Ops) {
614   for (auto& Op : Ops) {
615     ID.AddPointer(Op.getNode());
616     ID.AddInteger(Op.getResNo());
617   }
618 }
619 
620 static void AddNodeIDNode(FoldingSetNodeID &ID, unsigned short OpC,
621                           SDVTList VTList, ArrayRef<SDValue> OpList) {
622   AddNodeIDOpcode(ID, OpC);
623   AddNodeIDValueTypes(ID, VTList);
624   AddNodeIDOperands(ID, OpList);
625 }
626 
627 /// If this is an SDNode with special info, add this info to the NodeID data.
628 static void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N) {
629   switch (N->getOpcode()) {
630   case ISD::TargetExternalSymbol:
631   case ISD::ExternalSymbol:
632   case ISD::MCSymbol:
633     llvm_unreachable("Should only be used on nodes with operands");
634   default: break;  // Normal nodes don't need extra info.
635   case ISD::TargetConstant:
636   case ISD::Constant: {
637     const ConstantSDNode *C = cast<ConstantSDNode>(N);
638     ID.AddPointer(C->getConstantIntValue());
639     ID.AddBoolean(C->isOpaque());
640     break;
641   }
642   case ISD::TargetConstantFP:
643   case ISD::ConstantFP:
644     ID.AddPointer(cast<ConstantFPSDNode>(N)->getConstantFPValue());
645     break;
646   case ISD::TargetGlobalAddress:
647   case ISD::GlobalAddress:
648   case ISD::TargetGlobalTLSAddress:
649   case ISD::GlobalTLSAddress: {
650     const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
651     ID.AddPointer(GA->getGlobal());
652     ID.AddInteger(GA->getOffset());
653     ID.AddInteger(GA->getTargetFlags());
654     break;
655   }
656   case ISD::BasicBlock:
657     ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock());
658     break;
659   case ISD::Register:
660     ID.AddInteger(cast<RegisterSDNode>(N)->getReg());
661     break;
662   case ISD::RegisterMask:
663     ID.AddPointer(cast<RegisterMaskSDNode>(N)->getRegMask());
664     break;
665   case ISD::SRCVALUE:
666     ID.AddPointer(cast<SrcValueSDNode>(N)->getValue());
667     break;
668   case ISD::FrameIndex:
669   case ISD::TargetFrameIndex:
670     ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex());
671     break;
672   case ISD::LIFETIME_START:
673   case ISD::LIFETIME_END:
674     if (cast<LifetimeSDNode>(N)->hasOffset()) {
675       ID.AddInteger(cast<LifetimeSDNode>(N)->getSize());
676       ID.AddInteger(cast<LifetimeSDNode>(N)->getOffset());
677     }
678     break;
679   case ISD::PSEUDO_PROBE:
680     ID.AddInteger(cast<PseudoProbeSDNode>(N)->getGuid());
681     ID.AddInteger(cast<PseudoProbeSDNode>(N)->getIndex());
682     ID.AddInteger(cast<PseudoProbeSDNode>(N)->getAttributes());
683     break;
684   case ISD::JumpTable:
685   case ISD::TargetJumpTable:
686     ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex());
687     ID.AddInteger(cast<JumpTableSDNode>(N)->getTargetFlags());
688     break;
689   case ISD::ConstantPool:
690   case ISD::TargetConstantPool: {
691     const ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N);
692     ID.AddInteger(CP->getAlign().value());
693     ID.AddInteger(CP->getOffset());
694     if (CP->isMachineConstantPoolEntry())
695       CP->getMachineCPVal()->addSelectionDAGCSEId(ID);
696     else
697       ID.AddPointer(CP->getConstVal());
698     ID.AddInteger(CP->getTargetFlags());
699     break;
700   }
701   case ISD::TargetIndex: {
702     const TargetIndexSDNode *TI = cast<TargetIndexSDNode>(N);
703     ID.AddInteger(TI->getIndex());
704     ID.AddInteger(TI->getOffset());
705     ID.AddInteger(TI->getTargetFlags());
706     break;
707   }
708   case ISD::LOAD: {
709     const LoadSDNode *LD = cast<LoadSDNode>(N);
710     ID.AddInteger(LD->getMemoryVT().getRawBits());
711     ID.AddInteger(LD->getRawSubclassData());
712     ID.AddInteger(LD->getPointerInfo().getAddrSpace());
713     ID.AddInteger(LD->getMemOperand()->getFlags());
714     break;
715   }
716   case ISD::STORE: {
717     const StoreSDNode *ST = cast<StoreSDNode>(N);
718     ID.AddInteger(ST->getMemoryVT().getRawBits());
719     ID.AddInteger(ST->getRawSubclassData());
720     ID.AddInteger(ST->getPointerInfo().getAddrSpace());
721     ID.AddInteger(ST->getMemOperand()->getFlags());
722     break;
723   }
724   case ISD::VP_LOAD: {
725     const VPLoadSDNode *ELD = cast<VPLoadSDNode>(N);
726     ID.AddInteger(ELD->getMemoryVT().getRawBits());
727     ID.AddInteger(ELD->getRawSubclassData());
728     ID.AddInteger(ELD->getPointerInfo().getAddrSpace());
729     ID.AddInteger(ELD->getMemOperand()->getFlags());
730     break;
731   }
732   case ISD::VP_STORE: {
733     const VPStoreSDNode *EST = cast<VPStoreSDNode>(N);
734     ID.AddInteger(EST->getMemoryVT().getRawBits());
735     ID.AddInteger(EST->getRawSubclassData());
736     ID.AddInteger(EST->getPointerInfo().getAddrSpace());
737     ID.AddInteger(EST->getMemOperand()->getFlags());
738     break;
739   }
740   case ISD::EXPERIMENTAL_VP_STRIDED_LOAD: {
741     const VPStridedLoadSDNode *SLD = cast<VPStridedLoadSDNode>(N);
742     ID.AddInteger(SLD->getMemoryVT().getRawBits());
743     ID.AddInteger(SLD->getRawSubclassData());
744     ID.AddInteger(SLD->getPointerInfo().getAddrSpace());
745     break;
746   }
747   case ISD::EXPERIMENTAL_VP_STRIDED_STORE: {
748     const VPStridedStoreSDNode *SST = cast<VPStridedStoreSDNode>(N);
749     ID.AddInteger(SST->getMemoryVT().getRawBits());
750     ID.AddInteger(SST->getRawSubclassData());
751     ID.AddInteger(SST->getPointerInfo().getAddrSpace());
752     break;
753   }
754   case ISD::VP_GATHER: {
755     const VPGatherSDNode *EG = cast<VPGatherSDNode>(N);
756     ID.AddInteger(EG->getMemoryVT().getRawBits());
757     ID.AddInteger(EG->getRawSubclassData());
758     ID.AddInteger(EG->getPointerInfo().getAddrSpace());
759     ID.AddInteger(EG->getMemOperand()->getFlags());
760     break;
761   }
762   case ISD::VP_SCATTER: {
763     const VPScatterSDNode *ES = cast<VPScatterSDNode>(N);
764     ID.AddInteger(ES->getMemoryVT().getRawBits());
765     ID.AddInteger(ES->getRawSubclassData());
766     ID.AddInteger(ES->getPointerInfo().getAddrSpace());
767     ID.AddInteger(ES->getMemOperand()->getFlags());
768     break;
769   }
770   case ISD::MLOAD: {
771     const MaskedLoadSDNode *MLD = cast<MaskedLoadSDNode>(N);
772     ID.AddInteger(MLD->getMemoryVT().getRawBits());
773     ID.AddInteger(MLD->getRawSubclassData());
774     ID.AddInteger(MLD->getPointerInfo().getAddrSpace());
775     ID.AddInteger(MLD->getMemOperand()->getFlags());
776     break;
777   }
778   case ISD::MSTORE: {
779     const MaskedStoreSDNode *MST = cast<MaskedStoreSDNode>(N);
780     ID.AddInteger(MST->getMemoryVT().getRawBits());
781     ID.AddInteger(MST->getRawSubclassData());
782     ID.AddInteger(MST->getPointerInfo().getAddrSpace());
783     ID.AddInteger(MST->getMemOperand()->getFlags());
784     break;
785   }
786   case ISD::MGATHER: {
787     const MaskedGatherSDNode *MG = cast<MaskedGatherSDNode>(N);
788     ID.AddInteger(MG->getMemoryVT().getRawBits());
789     ID.AddInteger(MG->getRawSubclassData());
790     ID.AddInteger(MG->getPointerInfo().getAddrSpace());
791     ID.AddInteger(MG->getMemOperand()->getFlags());
792     break;
793   }
794   case ISD::MSCATTER: {
795     const MaskedScatterSDNode *MS = cast<MaskedScatterSDNode>(N);
796     ID.AddInteger(MS->getMemoryVT().getRawBits());
797     ID.AddInteger(MS->getRawSubclassData());
798     ID.AddInteger(MS->getPointerInfo().getAddrSpace());
799     ID.AddInteger(MS->getMemOperand()->getFlags());
800     break;
801   }
802   case ISD::ATOMIC_CMP_SWAP:
803   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
804   case ISD::ATOMIC_SWAP:
805   case ISD::ATOMIC_LOAD_ADD:
806   case ISD::ATOMIC_LOAD_SUB:
807   case ISD::ATOMIC_LOAD_AND:
808   case ISD::ATOMIC_LOAD_CLR:
809   case ISD::ATOMIC_LOAD_OR:
810   case ISD::ATOMIC_LOAD_XOR:
811   case ISD::ATOMIC_LOAD_NAND:
812   case ISD::ATOMIC_LOAD_MIN:
813   case ISD::ATOMIC_LOAD_MAX:
814   case ISD::ATOMIC_LOAD_UMIN:
815   case ISD::ATOMIC_LOAD_UMAX:
816   case ISD::ATOMIC_LOAD:
817   case ISD::ATOMIC_STORE: {
818     const AtomicSDNode *AT = cast<AtomicSDNode>(N);
819     ID.AddInteger(AT->getMemoryVT().getRawBits());
820     ID.AddInteger(AT->getRawSubclassData());
821     ID.AddInteger(AT->getPointerInfo().getAddrSpace());
822     ID.AddInteger(AT->getMemOperand()->getFlags());
823     break;
824   }
825   case ISD::PREFETCH: {
826     const MemSDNode *PF = cast<MemSDNode>(N);
827     ID.AddInteger(PF->getPointerInfo().getAddrSpace());
828     ID.AddInteger(PF->getMemOperand()->getFlags());
829     break;
830   }
831   case ISD::VECTOR_SHUFFLE: {
832     const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
833     for (unsigned i = 0, e = N->getValueType(0).getVectorNumElements();
834          i != e; ++i)
835       ID.AddInteger(SVN->getMaskElt(i));
836     break;
837   }
838   case ISD::TargetBlockAddress:
839   case ISD::BlockAddress: {
840     const BlockAddressSDNode *BA = cast<BlockAddressSDNode>(N);
841     ID.AddPointer(BA->getBlockAddress());
842     ID.AddInteger(BA->getOffset());
843     ID.AddInteger(BA->getTargetFlags());
844     break;
845   }
846   case ISD::AssertAlign:
847     ID.AddInteger(cast<AssertAlignSDNode>(N)->getAlign().value());
848     break;
849   } // end switch (N->getOpcode())
850 
851   // Target specific memory nodes could also have address spaces and flags
852   // to check.
853   if (N->isTargetMemoryOpcode()) {
854     const MemSDNode *MN = cast<MemSDNode>(N);
855     ID.AddInteger(MN->getPointerInfo().getAddrSpace());
856     ID.AddInteger(MN->getMemOperand()->getFlags());
857   }
858 }
859 
860 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID
861 /// data.
862 static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) {
863   AddNodeIDOpcode(ID, N->getOpcode());
864   // Add the return value info.
865   AddNodeIDValueTypes(ID, N->getVTList());
866   // Add the operand info.
867   AddNodeIDOperands(ID, N->ops());
868 
869   // Handle SDNode leafs with special info.
870   AddNodeIDCustom(ID, N);
871 }
872 
873 //===----------------------------------------------------------------------===//
874 //                              SelectionDAG Class
875 //===----------------------------------------------------------------------===//
876 
877 /// doNotCSE - Return true if CSE should not be performed for this node.
878 static bool doNotCSE(SDNode *N) {
879   if (N->getValueType(0) == MVT::Glue)
880     return true; // Never CSE anything that produces a flag.
881 
882   switch (N->getOpcode()) {
883   default: break;
884   case ISD::HANDLENODE:
885   case ISD::EH_LABEL:
886     return true;   // Never CSE these nodes.
887   }
888 
889   // Check that remaining values produced are not flags.
890   for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
891     if (N->getValueType(i) == MVT::Glue)
892       return true; // Never CSE anything that produces a flag.
893 
894   return false;
895 }
896 
897 /// RemoveDeadNodes - This method deletes all unreachable nodes in the
898 /// SelectionDAG.
899 void SelectionDAG::RemoveDeadNodes() {
900   // Create a dummy node (which is not added to allnodes), that adds a reference
901   // to the root node, preventing it from being deleted.
902   HandleSDNode Dummy(getRoot());
903 
904   SmallVector<SDNode*, 128> DeadNodes;
905 
906   // Add all obviously-dead nodes to the DeadNodes worklist.
907   for (SDNode &Node : allnodes())
908     if (Node.use_empty())
909       DeadNodes.push_back(&Node);
910 
911   RemoveDeadNodes(DeadNodes);
912 
913   // If the root changed (e.g. it was a dead load, update the root).
914   setRoot(Dummy.getValue());
915 }
916 
917 /// RemoveDeadNodes - This method deletes the unreachable nodes in the
918 /// given list, and any nodes that become unreachable as a result.
919 void SelectionDAG::RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes) {
920 
921   // Process the worklist, deleting the nodes and adding their uses to the
922   // worklist.
923   while (!DeadNodes.empty()) {
924     SDNode *N = DeadNodes.pop_back_val();
925     // Skip to next node if we've already managed to delete the node. This could
926     // happen if replacing a node causes a node previously added to the node to
927     // be deleted.
928     if (N->getOpcode() == ISD::DELETED_NODE)
929       continue;
930 
931     for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
932       DUL->NodeDeleted(N, nullptr);
933 
934     // Take the node out of the appropriate CSE map.
935     RemoveNodeFromCSEMaps(N);
936 
937     // Next, brutally remove the operand list.  This is safe to do, as there are
938     // no cycles in the graph.
939     for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
940       SDUse &Use = *I++;
941       SDNode *Operand = Use.getNode();
942       Use.set(SDValue());
943 
944       // Now that we removed this operand, see if there are no uses of it left.
945       if (Operand->use_empty())
946         DeadNodes.push_back(Operand);
947     }
948 
949     DeallocateNode(N);
950   }
951 }
952 
953 void SelectionDAG::RemoveDeadNode(SDNode *N){
954   SmallVector<SDNode*, 16> DeadNodes(1, N);
955 
956   // Create a dummy node that adds a reference to the root node, preventing
957   // it from being deleted.  (This matters if the root is an operand of the
958   // dead node.)
959   HandleSDNode Dummy(getRoot());
960 
961   RemoveDeadNodes(DeadNodes);
962 }
963 
964 void SelectionDAG::DeleteNode(SDNode *N) {
965   // First take this out of the appropriate CSE map.
966   RemoveNodeFromCSEMaps(N);
967 
968   // Finally, remove uses due to operands of this node, remove from the
969   // AllNodes list, and delete the node.
970   DeleteNodeNotInCSEMaps(N);
971 }
972 
973 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
974   assert(N->getIterator() != AllNodes.begin() &&
975          "Cannot delete the entry node!");
976   assert(N->use_empty() && "Cannot delete a node that is not dead!");
977 
978   // Drop all of the operands and decrement used node's use counts.
979   N->DropOperands();
980 
981   DeallocateNode(N);
982 }
983 
984 void SDDbgInfo::add(SDDbgValue *V, bool isParameter) {
985   assert(!(V->isVariadic() && isParameter));
986   if (isParameter)
987     ByvalParmDbgValues.push_back(V);
988   else
989     DbgValues.push_back(V);
990   for (const SDNode *Node : V->getSDNodes())
991     if (Node)
992       DbgValMap[Node].push_back(V);
993 }
994 
995 void SDDbgInfo::erase(const SDNode *Node) {
996   DbgValMapType::iterator I = DbgValMap.find(Node);
997   if (I == DbgValMap.end())
998     return;
999   for (auto &Val: I->second)
1000     Val->setIsInvalidated();
1001   DbgValMap.erase(I);
1002 }
1003 
1004 void SelectionDAG::DeallocateNode(SDNode *N) {
1005   // If we have operands, deallocate them.
1006   removeOperands(N);
1007 
1008   NodeAllocator.Deallocate(AllNodes.remove(N));
1009 
1010   // Set the opcode to DELETED_NODE to help catch bugs when node
1011   // memory is reallocated.
1012   // FIXME: There are places in SDag that have grown a dependency on the opcode
1013   // value in the released node.
1014   __asan_unpoison_memory_region(&N->NodeType, sizeof(N->NodeType));
1015   N->NodeType = ISD::DELETED_NODE;
1016 
1017   // If any of the SDDbgValue nodes refer to this SDNode, invalidate
1018   // them and forget about that node.
1019   DbgInfo->erase(N);
1020 }
1021 
1022 #ifndef NDEBUG
1023 /// VerifySDNode - Check the given SDNode.  Aborts if it is invalid.
1024 static void VerifySDNode(SDNode *N) {
1025   switch (N->getOpcode()) {
1026   default:
1027     break;
1028   case ISD::BUILD_PAIR: {
1029     EVT VT = N->getValueType(0);
1030     assert(N->getNumValues() == 1 && "Too many results!");
1031     assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) &&
1032            "Wrong return type!");
1033     assert(N->getNumOperands() == 2 && "Wrong number of operands!");
1034     assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() &&
1035            "Mismatched operand types!");
1036     assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() &&
1037            "Wrong operand type!");
1038     assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() &&
1039            "Wrong return type size");
1040     break;
1041   }
1042   case ISD::BUILD_VECTOR: {
1043     assert(N->getNumValues() == 1 && "Too many results!");
1044     assert(N->getValueType(0).isVector() && "Wrong return type!");
1045     assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() &&
1046            "Wrong number of operands!");
1047     EVT EltVT = N->getValueType(0).getVectorElementType();
1048     for (const SDUse &Op : N->ops()) {
1049       assert((Op.getValueType() == EltVT ||
1050               (EltVT.isInteger() && Op.getValueType().isInteger() &&
1051                EltVT.bitsLE(Op.getValueType()))) &&
1052              "Wrong operand type!");
1053       assert(Op.getValueType() == N->getOperand(0).getValueType() &&
1054              "Operands must all have the same type");
1055     }
1056     break;
1057   }
1058   }
1059 }
1060 #endif // NDEBUG
1061 
1062 /// Insert a newly allocated node into the DAG.
1063 ///
1064 /// Handles insertion into the all nodes list and CSE map, as well as
1065 /// verification and other common operations when a new node is allocated.
1066 void SelectionDAG::InsertNode(SDNode *N) {
1067   AllNodes.push_back(N);
1068 #ifndef NDEBUG
1069   N->PersistentId = NextPersistentId++;
1070   VerifySDNode(N);
1071 #endif
1072   for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1073     DUL->NodeInserted(N);
1074 }
1075 
1076 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
1077 /// correspond to it.  This is useful when we're about to delete or repurpose
1078 /// the node.  We don't want future request for structurally identical nodes
1079 /// to return N anymore.
1080 bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
1081   bool Erased = false;
1082   switch (N->getOpcode()) {
1083   case ISD::HANDLENODE: return false;  // noop.
1084   case ISD::CONDCODE:
1085     assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
1086            "Cond code doesn't exist!");
1087     Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != nullptr;
1088     CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = nullptr;
1089     break;
1090   case ISD::ExternalSymbol:
1091     Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
1092     break;
1093   case ISD::TargetExternalSymbol: {
1094     ExternalSymbolSDNode *ESN = cast<ExternalSymbolSDNode>(N);
1095     Erased = TargetExternalSymbols.erase(std::pair<std::string, unsigned>(
1096         ESN->getSymbol(), ESN->getTargetFlags()));
1097     break;
1098   }
1099   case ISD::MCSymbol: {
1100     auto *MCSN = cast<MCSymbolSDNode>(N);
1101     Erased = MCSymbols.erase(MCSN->getMCSymbol());
1102     break;
1103   }
1104   case ISD::VALUETYPE: {
1105     EVT VT = cast<VTSDNode>(N)->getVT();
1106     if (VT.isExtended()) {
1107       Erased = ExtendedValueTypeNodes.erase(VT);
1108     } else {
1109       Erased = ValueTypeNodes[VT.getSimpleVT().SimpleTy] != nullptr;
1110       ValueTypeNodes[VT.getSimpleVT().SimpleTy] = nullptr;
1111     }
1112     break;
1113   }
1114   default:
1115     // Remove it from the CSE Map.
1116     assert(N->getOpcode() != ISD::DELETED_NODE && "DELETED_NODE in CSEMap!");
1117     assert(N->getOpcode() != ISD::EntryToken && "EntryToken in CSEMap!");
1118     Erased = CSEMap.RemoveNode(N);
1119     break;
1120   }
1121 #ifndef NDEBUG
1122   // Verify that the node was actually in one of the CSE maps, unless it has a
1123   // flag result (which cannot be CSE'd) or is one of the special cases that are
1124   // not subject to CSE.
1125   if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Glue &&
1126       !N->isMachineOpcode() && !doNotCSE(N)) {
1127     N->dump(this);
1128     dbgs() << "\n";
1129     llvm_unreachable("Node is not in map!");
1130   }
1131 #endif
1132   return Erased;
1133 }
1134 
1135 /// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE
1136 /// maps and modified in place. Add it back to the CSE maps, unless an identical
1137 /// node already exists, in which case transfer all its users to the existing
1138 /// node. This transfer can potentially trigger recursive merging.
1139 void
1140 SelectionDAG::AddModifiedNodeToCSEMaps(SDNode *N) {
1141   // For node types that aren't CSE'd, just act as if no identical node
1142   // already exists.
1143   if (!doNotCSE(N)) {
1144     SDNode *Existing = CSEMap.GetOrInsertNode(N);
1145     if (Existing != N) {
1146       // If there was already an existing matching node, use ReplaceAllUsesWith
1147       // to replace the dead one with the existing one.  This can cause
1148       // recursive merging of other unrelated nodes down the line.
1149       ReplaceAllUsesWith(N, Existing);
1150 
1151       // N is now dead. Inform the listeners and delete it.
1152       for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1153         DUL->NodeDeleted(N, Existing);
1154       DeleteNodeNotInCSEMaps(N);
1155       return;
1156     }
1157   }
1158 
1159   // If the node doesn't already exist, we updated it.  Inform listeners.
1160   for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1161     DUL->NodeUpdated(N);
1162 }
1163 
1164 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1165 /// were replaced with those specified.  If this node is never memoized,
1166 /// return null, otherwise return a pointer to the slot it would take.  If a
1167 /// node already exists with these operands, the slot will be non-null.
1168 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op,
1169                                            void *&InsertPos) {
1170   if (doNotCSE(N))
1171     return nullptr;
1172 
1173   SDValue Ops[] = { Op };
1174   FoldingSetNodeID ID;
1175   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1176   AddNodeIDCustom(ID, N);
1177   SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1178   if (Node)
1179     Node->intersectFlagsWith(N->getFlags());
1180   return Node;
1181 }
1182 
1183 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1184 /// were replaced with those specified.  If this node is never memoized,
1185 /// return null, otherwise return a pointer to the slot it would take.  If a
1186 /// node already exists with these operands, the slot will be non-null.
1187 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
1188                                            SDValue Op1, SDValue Op2,
1189                                            void *&InsertPos) {
1190   if (doNotCSE(N))
1191     return nullptr;
1192 
1193   SDValue Ops[] = { Op1, Op2 };
1194   FoldingSetNodeID ID;
1195   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1196   AddNodeIDCustom(ID, N);
1197   SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1198   if (Node)
1199     Node->intersectFlagsWith(N->getFlags());
1200   return Node;
1201 }
1202 
1203 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1204 /// were replaced with those specified.  If this node is never memoized,
1205 /// return null, otherwise return a pointer to the slot it would take.  If a
1206 /// node already exists with these operands, the slot will be non-null.
1207 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, ArrayRef<SDValue> Ops,
1208                                            void *&InsertPos) {
1209   if (doNotCSE(N))
1210     return nullptr;
1211 
1212   FoldingSetNodeID ID;
1213   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1214   AddNodeIDCustom(ID, N);
1215   SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1216   if (Node)
1217     Node->intersectFlagsWith(N->getFlags());
1218   return Node;
1219 }
1220 
1221 Align SelectionDAG::getEVTAlign(EVT VT) const {
1222   Type *Ty = VT == MVT::iPTR ?
1223                    PointerType::get(Type::getInt8Ty(*getContext()), 0) :
1224                    VT.getTypeForEVT(*getContext());
1225 
1226   return getDataLayout().getABITypeAlign(Ty);
1227 }
1228 
1229 // EntryNode could meaningfully have debug info if we can find it...
1230 SelectionDAG::SelectionDAG(const TargetMachine &tm, CodeGenOpt::Level OL)
1231     : TM(tm), OptLevel(OL),
1232       EntryNode(ISD::EntryToken, 0, DebugLoc(), getVTList(MVT::Other)),
1233       Root(getEntryNode()) {
1234   InsertNode(&EntryNode);
1235   DbgInfo = new SDDbgInfo();
1236 }
1237 
1238 void SelectionDAG::init(MachineFunction &NewMF,
1239                         OptimizationRemarkEmitter &NewORE,
1240                         Pass *PassPtr, const TargetLibraryInfo *LibraryInfo,
1241                         LegacyDivergenceAnalysis * Divergence,
1242                         ProfileSummaryInfo *PSIin,
1243                         BlockFrequencyInfo *BFIin) {
1244   MF = &NewMF;
1245   SDAGISelPass = PassPtr;
1246   ORE = &NewORE;
1247   TLI = getSubtarget().getTargetLowering();
1248   TSI = getSubtarget().getSelectionDAGInfo();
1249   LibInfo = LibraryInfo;
1250   Context = &MF->getFunction().getContext();
1251   DA = Divergence;
1252   PSI = PSIin;
1253   BFI = BFIin;
1254 }
1255 
1256 SelectionDAG::~SelectionDAG() {
1257   assert(!UpdateListeners && "Dangling registered DAGUpdateListeners");
1258   allnodes_clear();
1259   OperandRecycler.clear(OperandAllocator);
1260   delete DbgInfo;
1261 }
1262 
1263 bool SelectionDAG::shouldOptForSize() const {
1264   return MF->getFunction().hasOptSize() ||
1265       llvm::shouldOptimizeForSize(FLI->MBB->getBasicBlock(), PSI, BFI);
1266 }
1267 
1268 void SelectionDAG::allnodes_clear() {
1269   assert(&*AllNodes.begin() == &EntryNode);
1270   AllNodes.remove(AllNodes.begin());
1271   while (!AllNodes.empty())
1272     DeallocateNode(&AllNodes.front());
1273 #ifndef NDEBUG
1274   NextPersistentId = 0;
1275 #endif
1276 }
1277 
1278 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
1279                                           void *&InsertPos) {
1280   SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
1281   if (N) {
1282     switch (N->getOpcode()) {
1283     default: break;
1284     case ISD::Constant:
1285     case ISD::ConstantFP:
1286       llvm_unreachable("Querying for Constant and ConstantFP nodes requires "
1287                        "debug location.  Use another overload.");
1288     }
1289   }
1290   return N;
1291 }
1292 
1293 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
1294                                           const SDLoc &DL, void *&InsertPos) {
1295   SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
1296   if (N) {
1297     switch (N->getOpcode()) {
1298     case ISD::Constant:
1299     case ISD::ConstantFP:
1300       // Erase debug location from the node if the node is used at several
1301       // different places. Do not propagate one location to all uses as it
1302       // will cause a worse single stepping debugging experience.
1303       if (N->getDebugLoc() != DL.getDebugLoc())
1304         N->setDebugLoc(DebugLoc());
1305       break;
1306     default:
1307       // When the node's point of use is located earlier in the instruction
1308       // sequence than its prior point of use, update its debug info to the
1309       // earlier location.
1310       if (DL.getIROrder() && DL.getIROrder() < N->getIROrder())
1311         N->setDebugLoc(DL.getDebugLoc());
1312       break;
1313     }
1314   }
1315   return N;
1316 }
1317 
1318 void SelectionDAG::clear() {
1319   allnodes_clear();
1320   OperandRecycler.clear(OperandAllocator);
1321   OperandAllocator.Reset();
1322   CSEMap.clear();
1323 
1324   ExtendedValueTypeNodes.clear();
1325   ExternalSymbols.clear();
1326   TargetExternalSymbols.clear();
1327   MCSymbols.clear();
1328   SDCallSiteDbgInfo.clear();
1329   std::fill(CondCodeNodes.begin(), CondCodeNodes.end(),
1330             static_cast<CondCodeSDNode*>(nullptr));
1331   std::fill(ValueTypeNodes.begin(), ValueTypeNodes.end(),
1332             static_cast<SDNode*>(nullptr));
1333 
1334   EntryNode.UseList = nullptr;
1335   InsertNode(&EntryNode);
1336   Root = getEntryNode();
1337   DbgInfo->clear();
1338 }
1339 
1340 SDValue SelectionDAG::getFPExtendOrRound(SDValue Op, const SDLoc &DL, EVT VT) {
1341   return VT.bitsGT(Op.getValueType())
1342              ? getNode(ISD::FP_EXTEND, DL, VT, Op)
1343              : getNode(ISD::FP_ROUND, DL, VT, Op, getIntPtrConstant(0, DL));
1344 }
1345 
1346 std::pair<SDValue, SDValue>
1347 SelectionDAG::getStrictFPExtendOrRound(SDValue Op, SDValue Chain,
1348                                        const SDLoc &DL, EVT VT) {
1349   assert(!VT.bitsEq(Op.getValueType()) &&
1350          "Strict no-op FP extend/round not allowed.");
1351   SDValue Res =
1352       VT.bitsGT(Op.getValueType())
1353           ? getNode(ISD::STRICT_FP_EXTEND, DL, {VT, MVT::Other}, {Chain, Op})
1354           : getNode(ISD::STRICT_FP_ROUND, DL, {VT, MVT::Other},
1355                     {Chain, Op, getIntPtrConstant(0, DL)});
1356 
1357   return std::pair<SDValue, SDValue>(Res, SDValue(Res.getNode(), 1));
1358 }
1359 
1360 SDValue SelectionDAG::getAnyExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1361   return VT.bitsGT(Op.getValueType()) ?
1362     getNode(ISD::ANY_EXTEND, DL, VT, Op) :
1363     getNode(ISD::TRUNCATE, DL, VT, Op);
1364 }
1365 
1366 SDValue SelectionDAG::getSExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1367   return VT.bitsGT(Op.getValueType()) ?
1368     getNode(ISD::SIGN_EXTEND, DL, VT, Op) :
1369     getNode(ISD::TRUNCATE, DL, VT, Op);
1370 }
1371 
1372 SDValue SelectionDAG::getZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1373   return VT.bitsGT(Op.getValueType()) ?
1374     getNode(ISD::ZERO_EXTEND, DL, VT, Op) :
1375     getNode(ISD::TRUNCATE, DL, VT, Op);
1376 }
1377 
1378 SDValue SelectionDAG::getBoolExtOrTrunc(SDValue Op, const SDLoc &SL, EVT VT,
1379                                         EVT OpVT) {
1380   if (VT.bitsLE(Op.getValueType()))
1381     return getNode(ISD::TRUNCATE, SL, VT, Op);
1382 
1383   TargetLowering::BooleanContent BType = TLI->getBooleanContents(OpVT);
1384   return getNode(TLI->getExtendForContent(BType), SL, VT, Op);
1385 }
1386 
1387 SDValue SelectionDAG::getZeroExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) {
1388   EVT OpVT = Op.getValueType();
1389   assert(VT.isInteger() && OpVT.isInteger() &&
1390          "Cannot getZeroExtendInReg FP types");
1391   assert(VT.isVector() == OpVT.isVector() &&
1392          "getZeroExtendInReg type should be vector iff the operand "
1393          "type is vector!");
1394   assert((!VT.isVector() ||
1395           VT.getVectorElementCount() == OpVT.getVectorElementCount()) &&
1396          "Vector element counts must match in getZeroExtendInReg");
1397   assert(VT.bitsLE(OpVT) && "Not extending!");
1398   if (OpVT == VT)
1399     return Op;
1400   APInt Imm = APInt::getLowBitsSet(OpVT.getScalarSizeInBits(),
1401                                    VT.getScalarSizeInBits());
1402   return getNode(ISD::AND, DL, OpVT, Op, getConstant(Imm, DL, OpVT));
1403 }
1404 
1405 SDValue SelectionDAG::getPtrExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1406   // Only unsigned pointer semantics are supported right now. In the future this
1407   // might delegate to TLI to check pointer signedness.
1408   return getZExtOrTrunc(Op, DL, VT);
1409 }
1410 
1411 SDValue SelectionDAG::getPtrExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) {
1412   // Only unsigned pointer semantics are supported right now. In the future this
1413   // might delegate to TLI to check pointer signedness.
1414   return getZeroExtendInReg(Op, DL, VT);
1415 }
1416 
1417 /// getNOT - Create a bitwise NOT operation as (XOR Val, -1).
1418 SDValue SelectionDAG::getNOT(const SDLoc &DL, SDValue Val, EVT VT) {
1419   return getNode(ISD::XOR, DL, VT, Val, getAllOnesConstant(DL, VT));
1420 }
1421 
1422 SDValue SelectionDAG::getLogicalNOT(const SDLoc &DL, SDValue Val, EVT VT) {
1423   SDValue TrueValue = getBoolConstant(true, DL, VT, VT);
1424   return getNode(ISD::XOR, DL, VT, Val, TrueValue);
1425 }
1426 
1427 SDValue SelectionDAG::getVPLogicalNOT(const SDLoc &DL, SDValue Val,
1428                                       SDValue Mask, SDValue EVL, EVT VT) {
1429   SDValue TrueValue = getBoolConstant(true, DL, VT, VT);
1430   return getNode(ISD::VP_XOR, DL, VT, Val, TrueValue, Mask, EVL);
1431 }
1432 
1433 SDValue SelectionDAG::getBoolConstant(bool V, const SDLoc &DL, EVT VT,
1434                                       EVT OpVT) {
1435   if (!V)
1436     return getConstant(0, DL, VT);
1437 
1438   switch (TLI->getBooleanContents(OpVT)) {
1439   case TargetLowering::ZeroOrOneBooleanContent:
1440   case TargetLowering::UndefinedBooleanContent:
1441     return getConstant(1, DL, VT);
1442   case TargetLowering::ZeroOrNegativeOneBooleanContent:
1443     return getAllOnesConstant(DL, VT);
1444   }
1445   llvm_unreachable("Unexpected boolean content enum!");
1446 }
1447 
1448 SDValue SelectionDAG::getConstant(uint64_t Val, const SDLoc &DL, EVT VT,
1449                                   bool isT, bool isO) {
1450   EVT EltVT = VT.getScalarType();
1451   assert((EltVT.getSizeInBits() >= 64 ||
1452           (uint64_t)((int64_t)Val >> EltVT.getSizeInBits()) + 1 < 2) &&
1453          "getConstant with a uint64_t value that doesn't fit in the type!");
1454   return getConstant(APInt(EltVT.getSizeInBits(), Val), DL, VT, isT, isO);
1455 }
1456 
1457 SDValue SelectionDAG::getConstant(const APInt &Val, const SDLoc &DL, EVT VT,
1458                                   bool isT, bool isO) {
1459   return getConstant(*ConstantInt::get(*Context, Val), DL, VT, isT, isO);
1460 }
1461 
1462 SDValue SelectionDAG::getConstant(const ConstantInt &Val, const SDLoc &DL,
1463                                   EVT VT, bool isT, bool isO) {
1464   assert(VT.isInteger() && "Cannot create FP integer constant!");
1465 
1466   EVT EltVT = VT.getScalarType();
1467   const ConstantInt *Elt = &Val;
1468 
1469   // In some cases the vector type is legal but the element type is illegal and
1470   // needs to be promoted, for example v8i8 on ARM.  In this case, promote the
1471   // inserted value (the type does not need to match the vector element type).
1472   // Any extra bits introduced will be truncated away.
1473   if (VT.isVector() && TLI->getTypeAction(*getContext(), EltVT) ==
1474                            TargetLowering::TypePromoteInteger) {
1475     EltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1476     APInt NewVal = Elt->getValue().zextOrTrunc(EltVT.getSizeInBits());
1477     Elt = ConstantInt::get(*getContext(), NewVal);
1478   }
1479   // In other cases the element type is illegal and needs to be expanded, for
1480   // example v2i64 on MIPS32. In this case, find the nearest legal type, split
1481   // the value into n parts and use a vector type with n-times the elements.
1482   // Then bitcast to the type requested.
1483   // Legalizing constants too early makes the DAGCombiner's job harder so we
1484   // only legalize if the DAG tells us we must produce legal types.
1485   else if (NewNodesMustHaveLegalTypes && VT.isVector() &&
1486            TLI->getTypeAction(*getContext(), EltVT) ==
1487                TargetLowering::TypeExpandInteger) {
1488     const APInt &NewVal = Elt->getValue();
1489     EVT ViaEltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1490     unsigned ViaEltSizeInBits = ViaEltVT.getSizeInBits();
1491 
1492     // For scalable vectors, try to use a SPLAT_VECTOR_PARTS node.
1493     if (VT.isScalableVector()) {
1494       assert(EltVT.getSizeInBits() % ViaEltSizeInBits == 0 &&
1495              "Can only handle an even split!");
1496       unsigned Parts = EltVT.getSizeInBits() / ViaEltSizeInBits;
1497 
1498       SmallVector<SDValue, 2> ScalarParts;
1499       for (unsigned i = 0; i != Parts; ++i)
1500         ScalarParts.push_back(getConstant(
1501             NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL,
1502             ViaEltVT, isT, isO));
1503 
1504       return getNode(ISD::SPLAT_VECTOR_PARTS, DL, VT, ScalarParts);
1505     }
1506 
1507     unsigned ViaVecNumElts = VT.getSizeInBits() / ViaEltSizeInBits;
1508     EVT ViaVecVT = EVT::getVectorVT(*getContext(), ViaEltVT, ViaVecNumElts);
1509 
1510     // Check the temporary vector is the correct size. If this fails then
1511     // getTypeToTransformTo() probably returned a type whose size (in bits)
1512     // isn't a power-of-2 factor of the requested type size.
1513     assert(ViaVecVT.getSizeInBits() == VT.getSizeInBits());
1514 
1515     SmallVector<SDValue, 2> EltParts;
1516     for (unsigned i = 0; i < ViaVecNumElts / VT.getVectorNumElements(); ++i)
1517       EltParts.push_back(getConstant(
1518           NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL,
1519           ViaEltVT, isT, isO));
1520 
1521     // EltParts is currently in little endian order. If we actually want
1522     // big-endian order then reverse it now.
1523     if (getDataLayout().isBigEndian())
1524       std::reverse(EltParts.begin(), EltParts.end());
1525 
1526     // The elements must be reversed when the element order is different
1527     // to the endianness of the elements (because the BITCAST is itself a
1528     // vector shuffle in this situation). However, we do not need any code to
1529     // perform this reversal because getConstant() is producing a vector
1530     // splat.
1531     // This situation occurs in MIPS MSA.
1532 
1533     SmallVector<SDValue, 8> Ops;
1534     for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
1535       llvm::append_range(Ops, EltParts);
1536 
1537     SDValue V =
1538         getNode(ISD::BITCAST, DL, VT, getBuildVector(ViaVecVT, DL, Ops));
1539     return V;
1540   }
1541 
1542   assert(Elt->getBitWidth() == EltVT.getSizeInBits() &&
1543          "APInt size does not match type size!");
1544   unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
1545   FoldingSetNodeID ID;
1546   AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
1547   ID.AddPointer(Elt);
1548   ID.AddBoolean(isO);
1549   void *IP = nullptr;
1550   SDNode *N = nullptr;
1551   if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1552     if (!VT.isVector())
1553       return SDValue(N, 0);
1554 
1555   if (!N) {
1556     N = newSDNode<ConstantSDNode>(isT, isO, Elt, EltVT);
1557     CSEMap.InsertNode(N, IP);
1558     InsertNode(N);
1559     NewSDValueDbgMsg(SDValue(N, 0), "Creating constant: ", this);
1560   }
1561 
1562   SDValue Result(N, 0);
1563   if (VT.isScalableVector())
1564     Result = getSplatVector(VT, DL, Result);
1565   else if (VT.isVector())
1566     Result = getSplatBuildVector(VT, DL, Result);
1567 
1568   return Result;
1569 }
1570 
1571 SDValue SelectionDAG::getIntPtrConstant(uint64_t Val, const SDLoc &DL,
1572                                         bool isTarget) {
1573   return getConstant(Val, DL, TLI->getPointerTy(getDataLayout()), isTarget);
1574 }
1575 
1576 SDValue SelectionDAG::getShiftAmountConstant(uint64_t Val, EVT VT,
1577                                              const SDLoc &DL, bool LegalTypes) {
1578   assert(VT.isInteger() && "Shift amount is not an integer type!");
1579   EVT ShiftVT = TLI->getShiftAmountTy(VT, getDataLayout(), LegalTypes);
1580   return getConstant(Val, DL, ShiftVT);
1581 }
1582 
1583 SDValue SelectionDAG::getVectorIdxConstant(uint64_t Val, const SDLoc &DL,
1584                                            bool isTarget) {
1585   return getConstant(Val, DL, TLI->getVectorIdxTy(getDataLayout()), isTarget);
1586 }
1587 
1588 SDValue SelectionDAG::getConstantFP(const APFloat &V, const SDLoc &DL, EVT VT,
1589                                     bool isTarget) {
1590   return getConstantFP(*ConstantFP::get(*getContext(), V), DL, VT, isTarget);
1591 }
1592 
1593 SDValue SelectionDAG::getConstantFP(const ConstantFP &V, const SDLoc &DL,
1594                                     EVT VT, bool isTarget) {
1595   assert(VT.isFloatingPoint() && "Cannot create integer FP constant!");
1596 
1597   EVT EltVT = VT.getScalarType();
1598 
1599   // Do the map lookup using the actual bit pattern for the floating point
1600   // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
1601   // we don't have issues with SNANs.
1602   unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
1603   FoldingSetNodeID ID;
1604   AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
1605   ID.AddPointer(&V);
1606   void *IP = nullptr;
1607   SDNode *N = nullptr;
1608   if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1609     if (!VT.isVector())
1610       return SDValue(N, 0);
1611 
1612   if (!N) {
1613     N = newSDNode<ConstantFPSDNode>(isTarget, &V, EltVT);
1614     CSEMap.InsertNode(N, IP);
1615     InsertNode(N);
1616   }
1617 
1618   SDValue Result(N, 0);
1619   if (VT.isScalableVector())
1620     Result = getSplatVector(VT, DL, Result);
1621   else if (VT.isVector())
1622     Result = getSplatBuildVector(VT, DL, Result);
1623   NewSDValueDbgMsg(Result, "Creating fp constant: ", this);
1624   return Result;
1625 }
1626 
1627 SDValue SelectionDAG::getConstantFP(double Val, const SDLoc &DL, EVT VT,
1628                                     bool isTarget) {
1629   EVT EltVT = VT.getScalarType();
1630   if (EltVT == MVT::f32)
1631     return getConstantFP(APFloat((float)Val), DL, VT, isTarget);
1632   if (EltVT == MVT::f64)
1633     return getConstantFP(APFloat(Val), DL, VT, isTarget);
1634   if (EltVT == MVT::f80 || EltVT == MVT::f128 || EltVT == MVT::ppcf128 ||
1635       EltVT == MVT::f16 || EltVT == MVT::bf16) {
1636     bool Ignored;
1637     APFloat APF = APFloat(Val);
1638     APF.convert(EVTToAPFloatSemantics(EltVT), APFloat::rmNearestTiesToEven,
1639                 &Ignored);
1640     return getConstantFP(APF, DL, VT, isTarget);
1641   }
1642   llvm_unreachable("Unsupported type in getConstantFP");
1643 }
1644 
1645 SDValue SelectionDAG::getGlobalAddress(const GlobalValue *GV, const SDLoc &DL,
1646                                        EVT VT, int64_t Offset, bool isTargetGA,
1647                                        unsigned TargetFlags) {
1648   assert((TargetFlags == 0 || isTargetGA) &&
1649          "Cannot set target flags on target-independent globals");
1650 
1651   // Truncate (with sign-extension) the offset value to the pointer size.
1652   unsigned BitWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
1653   if (BitWidth < 64)
1654     Offset = SignExtend64(Offset, BitWidth);
1655 
1656   unsigned Opc;
1657   if (GV->isThreadLocal())
1658     Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress;
1659   else
1660     Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress;
1661 
1662   FoldingSetNodeID ID;
1663   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1664   ID.AddPointer(GV);
1665   ID.AddInteger(Offset);
1666   ID.AddInteger(TargetFlags);
1667   void *IP = nullptr;
1668   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
1669     return SDValue(E, 0);
1670 
1671   auto *N = newSDNode<GlobalAddressSDNode>(
1672       Opc, DL.getIROrder(), DL.getDebugLoc(), GV, VT, Offset, TargetFlags);
1673   CSEMap.InsertNode(N, IP);
1674     InsertNode(N);
1675   return SDValue(N, 0);
1676 }
1677 
1678 SDValue SelectionDAG::getFrameIndex(int FI, EVT VT, bool isTarget) {
1679   unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
1680   FoldingSetNodeID ID;
1681   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1682   ID.AddInteger(FI);
1683   void *IP = nullptr;
1684   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1685     return SDValue(E, 0);
1686 
1687   auto *N = newSDNode<FrameIndexSDNode>(FI, VT, isTarget);
1688   CSEMap.InsertNode(N, IP);
1689   InsertNode(N);
1690   return SDValue(N, 0);
1691 }
1692 
1693 SDValue SelectionDAG::getJumpTable(int JTI, EVT VT, bool isTarget,
1694                                    unsigned TargetFlags) {
1695   assert((TargetFlags == 0 || isTarget) &&
1696          "Cannot set target flags on target-independent jump tables");
1697   unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
1698   FoldingSetNodeID ID;
1699   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1700   ID.AddInteger(JTI);
1701   ID.AddInteger(TargetFlags);
1702   void *IP = nullptr;
1703   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1704     return SDValue(E, 0);
1705 
1706   auto *N = newSDNode<JumpTableSDNode>(JTI, VT, isTarget, TargetFlags);
1707   CSEMap.InsertNode(N, IP);
1708   InsertNode(N);
1709   return SDValue(N, 0);
1710 }
1711 
1712 SDValue SelectionDAG::getConstantPool(const Constant *C, EVT VT,
1713                                       MaybeAlign Alignment, int Offset,
1714                                       bool isTarget, unsigned TargetFlags) {
1715   assert((TargetFlags == 0 || isTarget) &&
1716          "Cannot set target flags on target-independent globals");
1717   if (!Alignment)
1718     Alignment = shouldOptForSize()
1719                     ? getDataLayout().getABITypeAlign(C->getType())
1720                     : getDataLayout().getPrefTypeAlign(C->getType());
1721   unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1722   FoldingSetNodeID ID;
1723   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1724   ID.AddInteger(Alignment->value());
1725   ID.AddInteger(Offset);
1726   ID.AddPointer(C);
1727   ID.AddInteger(TargetFlags);
1728   void *IP = nullptr;
1729   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1730     return SDValue(E, 0);
1731 
1732   auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment,
1733                                           TargetFlags);
1734   CSEMap.InsertNode(N, IP);
1735   InsertNode(N);
1736   SDValue V = SDValue(N, 0);
1737   NewSDValueDbgMsg(V, "Creating new constant pool: ", this);
1738   return V;
1739 }
1740 
1741 SDValue SelectionDAG::getConstantPool(MachineConstantPoolValue *C, EVT VT,
1742                                       MaybeAlign Alignment, int Offset,
1743                                       bool isTarget, unsigned TargetFlags) {
1744   assert((TargetFlags == 0 || isTarget) &&
1745          "Cannot set target flags on target-independent globals");
1746   if (!Alignment)
1747     Alignment = getDataLayout().getPrefTypeAlign(C->getType());
1748   unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1749   FoldingSetNodeID ID;
1750   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1751   ID.AddInteger(Alignment->value());
1752   ID.AddInteger(Offset);
1753   C->addSelectionDAGCSEId(ID);
1754   ID.AddInteger(TargetFlags);
1755   void *IP = nullptr;
1756   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1757     return SDValue(E, 0);
1758 
1759   auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment,
1760                                           TargetFlags);
1761   CSEMap.InsertNode(N, IP);
1762   InsertNode(N);
1763   return SDValue(N, 0);
1764 }
1765 
1766 SDValue SelectionDAG::getTargetIndex(int Index, EVT VT, int64_t Offset,
1767                                      unsigned TargetFlags) {
1768   FoldingSetNodeID ID;
1769   AddNodeIDNode(ID, ISD::TargetIndex, getVTList(VT), None);
1770   ID.AddInteger(Index);
1771   ID.AddInteger(Offset);
1772   ID.AddInteger(TargetFlags);
1773   void *IP = nullptr;
1774   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1775     return SDValue(E, 0);
1776 
1777   auto *N = newSDNode<TargetIndexSDNode>(Index, VT, Offset, TargetFlags);
1778   CSEMap.InsertNode(N, IP);
1779   InsertNode(N);
1780   return SDValue(N, 0);
1781 }
1782 
1783 SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
1784   FoldingSetNodeID ID;
1785   AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), None);
1786   ID.AddPointer(MBB);
1787   void *IP = nullptr;
1788   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1789     return SDValue(E, 0);
1790 
1791   auto *N = newSDNode<BasicBlockSDNode>(MBB);
1792   CSEMap.InsertNode(N, IP);
1793   InsertNode(N);
1794   return SDValue(N, 0);
1795 }
1796 
1797 SDValue SelectionDAG::getValueType(EVT VT) {
1798   if (VT.isSimple() && (unsigned)VT.getSimpleVT().SimpleTy >=
1799       ValueTypeNodes.size())
1800     ValueTypeNodes.resize(VT.getSimpleVT().SimpleTy+1);
1801 
1802   SDNode *&N = VT.isExtended() ?
1803     ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT().SimpleTy];
1804 
1805   if (N) return SDValue(N, 0);
1806   N = newSDNode<VTSDNode>(VT);
1807   InsertNode(N);
1808   return SDValue(N, 0);
1809 }
1810 
1811 SDValue SelectionDAG::getExternalSymbol(const char *Sym, EVT VT) {
1812   SDNode *&N = ExternalSymbols[Sym];
1813   if (N) return SDValue(N, 0);
1814   N = newSDNode<ExternalSymbolSDNode>(false, Sym, 0, VT);
1815   InsertNode(N);
1816   return SDValue(N, 0);
1817 }
1818 
1819 SDValue SelectionDAG::getMCSymbol(MCSymbol *Sym, EVT VT) {
1820   SDNode *&N = MCSymbols[Sym];
1821   if (N)
1822     return SDValue(N, 0);
1823   N = newSDNode<MCSymbolSDNode>(Sym, VT);
1824   InsertNode(N);
1825   return SDValue(N, 0);
1826 }
1827 
1828 SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, EVT VT,
1829                                               unsigned TargetFlags) {
1830   SDNode *&N =
1831       TargetExternalSymbols[std::pair<std::string, unsigned>(Sym, TargetFlags)];
1832   if (N) return SDValue(N, 0);
1833   N = newSDNode<ExternalSymbolSDNode>(true, Sym, TargetFlags, VT);
1834   InsertNode(N);
1835   return SDValue(N, 0);
1836 }
1837 
1838 SDValue SelectionDAG::getCondCode(ISD::CondCode Cond) {
1839   if ((unsigned)Cond >= CondCodeNodes.size())
1840     CondCodeNodes.resize(Cond+1);
1841 
1842   if (!CondCodeNodes[Cond]) {
1843     auto *N = newSDNode<CondCodeSDNode>(Cond);
1844     CondCodeNodes[Cond] = N;
1845     InsertNode(N);
1846   }
1847 
1848   return SDValue(CondCodeNodes[Cond], 0);
1849 }
1850 
1851 SDValue SelectionDAG::getStepVector(const SDLoc &DL, EVT ResVT) {
1852   APInt One(ResVT.getScalarSizeInBits(), 1);
1853   return getStepVector(DL, ResVT, One);
1854 }
1855 
1856 SDValue SelectionDAG::getStepVector(const SDLoc &DL, EVT ResVT, APInt StepVal) {
1857   assert(ResVT.getScalarSizeInBits() == StepVal.getBitWidth());
1858   if (ResVT.isScalableVector())
1859     return getNode(
1860         ISD::STEP_VECTOR, DL, ResVT,
1861         getTargetConstant(StepVal, DL, ResVT.getVectorElementType()));
1862 
1863   SmallVector<SDValue, 16> OpsStepConstants;
1864   for (uint64_t i = 0; i < ResVT.getVectorNumElements(); i++)
1865     OpsStepConstants.push_back(
1866         getConstant(StepVal * i, DL, ResVT.getVectorElementType()));
1867   return getBuildVector(ResVT, DL, OpsStepConstants);
1868 }
1869 
1870 /// Swaps the values of N1 and N2. Swaps all indices in the shuffle mask M that
1871 /// point at N1 to point at N2 and indices that point at N2 to point at N1.
1872 static void commuteShuffle(SDValue &N1, SDValue &N2, MutableArrayRef<int> M) {
1873   std::swap(N1, N2);
1874   ShuffleVectorSDNode::commuteMask(M);
1875 }
1876 
1877 SDValue SelectionDAG::getVectorShuffle(EVT VT, const SDLoc &dl, SDValue N1,
1878                                        SDValue N2, ArrayRef<int> Mask) {
1879   assert(VT.getVectorNumElements() == Mask.size() &&
1880          "Must have the same number of vector elements as mask elements!");
1881   assert(VT == N1.getValueType() && VT == N2.getValueType() &&
1882          "Invalid VECTOR_SHUFFLE");
1883 
1884   // Canonicalize shuffle undef, undef -> undef
1885   if (N1.isUndef() && N2.isUndef())
1886     return getUNDEF(VT);
1887 
1888   // Validate that all indices in Mask are within the range of the elements
1889   // input to the shuffle.
1890   int NElts = Mask.size();
1891   assert(llvm::all_of(Mask,
1892                       [&](int M) { return M < (NElts * 2) && M >= -1; }) &&
1893          "Index out of range");
1894 
1895   // Copy the mask so we can do any needed cleanup.
1896   SmallVector<int, 8> MaskVec(Mask.begin(), Mask.end());
1897 
1898   // Canonicalize shuffle v, v -> v, undef
1899   if (N1 == N2) {
1900     N2 = getUNDEF(VT);
1901     for (int i = 0; i != NElts; ++i)
1902       if (MaskVec[i] >= NElts) MaskVec[i] -= NElts;
1903   }
1904 
1905   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
1906   if (N1.isUndef())
1907     commuteShuffle(N1, N2, MaskVec);
1908 
1909   if (TLI->hasVectorBlend()) {
1910     // If shuffling a splat, try to blend the splat instead. We do this here so
1911     // that even when this arises during lowering we don't have to re-handle it.
1912     auto BlendSplat = [&](BuildVectorSDNode *BV, int Offset) {
1913       BitVector UndefElements;
1914       SDValue Splat = BV->getSplatValue(&UndefElements);
1915       if (!Splat)
1916         return;
1917 
1918       for (int i = 0; i < NElts; ++i) {
1919         if (MaskVec[i] < Offset || MaskVec[i] >= (Offset + NElts))
1920           continue;
1921 
1922         // If this input comes from undef, mark it as such.
1923         if (UndefElements[MaskVec[i] - Offset]) {
1924           MaskVec[i] = -1;
1925           continue;
1926         }
1927 
1928         // If we can blend a non-undef lane, use that instead.
1929         if (!UndefElements[i])
1930           MaskVec[i] = i + Offset;
1931       }
1932     };
1933     if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
1934       BlendSplat(N1BV, 0);
1935     if (auto *N2BV = dyn_cast<BuildVectorSDNode>(N2))
1936       BlendSplat(N2BV, NElts);
1937   }
1938 
1939   // Canonicalize all index into lhs, -> shuffle lhs, undef
1940   // Canonicalize all index into rhs, -> shuffle rhs, undef
1941   bool AllLHS = true, AllRHS = true;
1942   bool N2Undef = N2.isUndef();
1943   for (int i = 0; i != NElts; ++i) {
1944     if (MaskVec[i] >= NElts) {
1945       if (N2Undef)
1946         MaskVec[i] = -1;
1947       else
1948         AllLHS = false;
1949     } else if (MaskVec[i] >= 0) {
1950       AllRHS = false;
1951     }
1952   }
1953   if (AllLHS && AllRHS)
1954     return getUNDEF(VT);
1955   if (AllLHS && !N2Undef)
1956     N2 = getUNDEF(VT);
1957   if (AllRHS) {
1958     N1 = getUNDEF(VT);
1959     commuteShuffle(N1, N2, MaskVec);
1960   }
1961   // Reset our undef status after accounting for the mask.
1962   N2Undef = N2.isUndef();
1963   // Re-check whether both sides ended up undef.
1964   if (N1.isUndef() && N2Undef)
1965     return getUNDEF(VT);
1966 
1967   // If Identity shuffle return that node.
1968   bool Identity = true, AllSame = true;
1969   for (int i = 0; i != NElts; ++i) {
1970     if (MaskVec[i] >= 0 && MaskVec[i] != i) Identity = false;
1971     if (MaskVec[i] != MaskVec[0]) AllSame = false;
1972   }
1973   if (Identity && NElts)
1974     return N1;
1975 
1976   // Shuffling a constant splat doesn't change the result.
1977   if (N2Undef) {
1978     SDValue V = N1;
1979 
1980     // Look through any bitcasts. We check that these don't change the number
1981     // (and size) of elements and just changes their types.
1982     while (V.getOpcode() == ISD::BITCAST)
1983       V = V->getOperand(0);
1984 
1985     // A splat should always show up as a build vector node.
1986     if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) {
1987       BitVector UndefElements;
1988       SDValue Splat = BV->getSplatValue(&UndefElements);
1989       // If this is a splat of an undef, shuffling it is also undef.
1990       if (Splat && Splat.isUndef())
1991         return getUNDEF(VT);
1992 
1993       bool SameNumElts =
1994           V.getValueType().getVectorNumElements() == VT.getVectorNumElements();
1995 
1996       // We only have a splat which can skip shuffles if there is a splatted
1997       // value and no undef lanes rearranged by the shuffle.
1998       if (Splat && UndefElements.none()) {
1999         // Splat of <x, x, ..., x>, return <x, x, ..., x>, provided that the
2000         // number of elements match or the value splatted is a zero constant.
2001         if (SameNumElts)
2002           return N1;
2003         if (auto *C = dyn_cast<ConstantSDNode>(Splat))
2004           if (C->isZero())
2005             return N1;
2006       }
2007 
2008       // If the shuffle itself creates a splat, build the vector directly.
2009       if (AllSame && SameNumElts) {
2010         EVT BuildVT = BV->getValueType(0);
2011         const SDValue &Splatted = BV->getOperand(MaskVec[0]);
2012         SDValue NewBV = getSplatBuildVector(BuildVT, dl, Splatted);
2013 
2014         // We may have jumped through bitcasts, so the type of the
2015         // BUILD_VECTOR may not match the type of the shuffle.
2016         if (BuildVT != VT)
2017           NewBV = getNode(ISD::BITCAST, dl, VT, NewBV);
2018         return NewBV;
2019       }
2020     }
2021   }
2022 
2023   FoldingSetNodeID ID;
2024   SDValue Ops[2] = { N1, N2 };
2025   AddNodeIDNode(ID, ISD::VECTOR_SHUFFLE, getVTList(VT), Ops);
2026   for (int i = 0; i != NElts; ++i)
2027     ID.AddInteger(MaskVec[i]);
2028 
2029   void* IP = nullptr;
2030   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
2031     return SDValue(E, 0);
2032 
2033   // Allocate the mask array for the node out of the BumpPtrAllocator, since
2034   // SDNode doesn't have access to it.  This memory will be "leaked" when
2035   // the node is deallocated, but recovered when the NodeAllocator is released.
2036   int *MaskAlloc = OperandAllocator.Allocate<int>(NElts);
2037   llvm::copy(MaskVec, MaskAlloc);
2038 
2039   auto *N = newSDNode<ShuffleVectorSDNode>(VT, dl.getIROrder(),
2040                                            dl.getDebugLoc(), MaskAlloc);
2041   createOperands(N, Ops);
2042 
2043   CSEMap.InsertNode(N, IP);
2044   InsertNode(N);
2045   SDValue V = SDValue(N, 0);
2046   NewSDValueDbgMsg(V, "Creating new node: ", this);
2047   return V;
2048 }
2049 
2050 SDValue SelectionDAG::getCommutedVectorShuffle(const ShuffleVectorSDNode &SV) {
2051   EVT VT = SV.getValueType(0);
2052   SmallVector<int, 8> MaskVec(SV.getMask().begin(), SV.getMask().end());
2053   ShuffleVectorSDNode::commuteMask(MaskVec);
2054 
2055   SDValue Op0 = SV.getOperand(0);
2056   SDValue Op1 = SV.getOperand(1);
2057   return getVectorShuffle(VT, SDLoc(&SV), Op1, Op0, MaskVec);
2058 }
2059 
2060 SDValue SelectionDAG::getRegister(unsigned RegNo, EVT VT) {
2061   FoldingSetNodeID ID;
2062   AddNodeIDNode(ID, ISD::Register, getVTList(VT), None);
2063   ID.AddInteger(RegNo);
2064   void *IP = nullptr;
2065   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2066     return SDValue(E, 0);
2067 
2068   auto *N = newSDNode<RegisterSDNode>(RegNo, VT);
2069   N->SDNodeBits.IsDivergent = TLI->isSDNodeSourceOfDivergence(N, FLI, DA);
2070   CSEMap.InsertNode(N, IP);
2071   InsertNode(N);
2072   return SDValue(N, 0);
2073 }
2074 
2075 SDValue SelectionDAG::getRegisterMask(const uint32_t *RegMask) {
2076   FoldingSetNodeID ID;
2077   AddNodeIDNode(ID, ISD::RegisterMask, getVTList(MVT::Untyped), None);
2078   ID.AddPointer(RegMask);
2079   void *IP = nullptr;
2080   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2081     return SDValue(E, 0);
2082 
2083   auto *N = newSDNode<RegisterMaskSDNode>(RegMask);
2084   CSEMap.InsertNode(N, IP);
2085   InsertNode(N);
2086   return SDValue(N, 0);
2087 }
2088 
2089 SDValue SelectionDAG::getEHLabel(const SDLoc &dl, SDValue Root,
2090                                  MCSymbol *Label) {
2091   return getLabelNode(ISD::EH_LABEL, dl, Root, Label);
2092 }
2093 
2094 SDValue SelectionDAG::getLabelNode(unsigned Opcode, const SDLoc &dl,
2095                                    SDValue Root, MCSymbol *Label) {
2096   FoldingSetNodeID ID;
2097   SDValue Ops[] = { Root };
2098   AddNodeIDNode(ID, Opcode, getVTList(MVT::Other), Ops);
2099   ID.AddPointer(Label);
2100   void *IP = nullptr;
2101   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2102     return SDValue(E, 0);
2103 
2104   auto *N =
2105       newSDNode<LabelSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), Label);
2106   createOperands(N, Ops);
2107 
2108   CSEMap.InsertNode(N, IP);
2109   InsertNode(N);
2110   return SDValue(N, 0);
2111 }
2112 
2113 SDValue SelectionDAG::getBlockAddress(const BlockAddress *BA, EVT VT,
2114                                       int64_t Offset, bool isTarget,
2115                                       unsigned TargetFlags) {
2116   unsigned Opc = isTarget ? ISD::TargetBlockAddress : ISD::BlockAddress;
2117 
2118   FoldingSetNodeID ID;
2119   AddNodeIDNode(ID, Opc, getVTList(VT), None);
2120   ID.AddPointer(BA);
2121   ID.AddInteger(Offset);
2122   ID.AddInteger(TargetFlags);
2123   void *IP = nullptr;
2124   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2125     return SDValue(E, 0);
2126 
2127   auto *N = newSDNode<BlockAddressSDNode>(Opc, VT, BA, Offset, TargetFlags);
2128   CSEMap.InsertNode(N, IP);
2129   InsertNode(N);
2130   return SDValue(N, 0);
2131 }
2132 
2133 SDValue SelectionDAG::getSrcValue(const Value *V) {
2134   FoldingSetNodeID ID;
2135   AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), None);
2136   ID.AddPointer(V);
2137 
2138   void *IP = nullptr;
2139   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2140     return SDValue(E, 0);
2141 
2142   auto *N = newSDNode<SrcValueSDNode>(V);
2143   CSEMap.InsertNode(N, IP);
2144   InsertNode(N);
2145   return SDValue(N, 0);
2146 }
2147 
2148 SDValue SelectionDAG::getMDNode(const MDNode *MD) {
2149   FoldingSetNodeID ID;
2150   AddNodeIDNode(ID, ISD::MDNODE_SDNODE, getVTList(MVT::Other), None);
2151   ID.AddPointer(MD);
2152 
2153   void *IP = nullptr;
2154   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2155     return SDValue(E, 0);
2156 
2157   auto *N = newSDNode<MDNodeSDNode>(MD);
2158   CSEMap.InsertNode(N, IP);
2159   InsertNode(N);
2160   return SDValue(N, 0);
2161 }
2162 
2163 SDValue SelectionDAG::getBitcast(EVT VT, SDValue V) {
2164   if (VT == V.getValueType())
2165     return V;
2166 
2167   return getNode(ISD::BITCAST, SDLoc(V), VT, V);
2168 }
2169 
2170 SDValue SelectionDAG::getAddrSpaceCast(const SDLoc &dl, EVT VT, SDValue Ptr,
2171                                        unsigned SrcAS, unsigned DestAS) {
2172   SDValue Ops[] = {Ptr};
2173   FoldingSetNodeID ID;
2174   AddNodeIDNode(ID, ISD::ADDRSPACECAST, getVTList(VT), Ops);
2175   ID.AddInteger(SrcAS);
2176   ID.AddInteger(DestAS);
2177 
2178   void *IP = nullptr;
2179   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
2180     return SDValue(E, 0);
2181 
2182   auto *N = newSDNode<AddrSpaceCastSDNode>(dl.getIROrder(), dl.getDebugLoc(),
2183                                            VT, SrcAS, DestAS);
2184   createOperands(N, Ops);
2185 
2186   CSEMap.InsertNode(N, IP);
2187   InsertNode(N);
2188   return SDValue(N, 0);
2189 }
2190 
2191 SDValue SelectionDAG::getFreeze(SDValue V) {
2192   return getNode(ISD::FREEZE, SDLoc(V), V.getValueType(), V);
2193 }
2194 
2195 /// getShiftAmountOperand - Return the specified value casted to
2196 /// the target's desired shift amount type.
2197 SDValue SelectionDAG::getShiftAmountOperand(EVT LHSTy, SDValue Op) {
2198   EVT OpTy = Op.getValueType();
2199   EVT ShTy = TLI->getShiftAmountTy(LHSTy, getDataLayout());
2200   if (OpTy == ShTy || OpTy.isVector()) return Op;
2201 
2202   return getZExtOrTrunc(Op, SDLoc(Op), ShTy);
2203 }
2204 
2205 SDValue SelectionDAG::expandVAArg(SDNode *Node) {
2206   SDLoc dl(Node);
2207   const TargetLowering &TLI = getTargetLoweringInfo();
2208   const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2209   EVT VT = Node->getValueType(0);
2210   SDValue Tmp1 = Node->getOperand(0);
2211   SDValue Tmp2 = Node->getOperand(1);
2212   const MaybeAlign MA(Node->getConstantOperandVal(3));
2213 
2214   SDValue VAListLoad = getLoad(TLI.getPointerTy(getDataLayout()), dl, Tmp1,
2215                                Tmp2, MachinePointerInfo(V));
2216   SDValue VAList = VAListLoad;
2217 
2218   if (MA && *MA > TLI.getMinStackArgumentAlignment()) {
2219     VAList = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
2220                      getConstant(MA->value() - 1, dl, VAList.getValueType()));
2221 
2222     VAList =
2223         getNode(ISD::AND, dl, VAList.getValueType(), VAList,
2224                 getConstant(-(int64_t)MA->value(), dl, VAList.getValueType()));
2225   }
2226 
2227   // Increment the pointer, VAList, to the next vaarg
2228   Tmp1 = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
2229                  getConstant(getDataLayout().getTypeAllocSize(
2230                                                VT.getTypeForEVT(*getContext())),
2231                              dl, VAList.getValueType()));
2232   // Store the incremented VAList to the legalized pointer
2233   Tmp1 =
2234       getStore(VAListLoad.getValue(1), dl, Tmp1, Tmp2, MachinePointerInfo(V));
2235   // Load the actual argument out of the pointer VAList
2236   return getLoad(VT, dl, Tmp1, VAList, MachinePointerInfo());
2237 }
2238 
2239 SDValue SelectionDAG::expandVACopy(SDNode *Node) {
2240   SDLoc dl(Node);
2241   const TargetLowering &TLI = getTargetLoweringInfo();
2242   // This defaults to loading a pointer from the input and storing it to the
2243   // output, returning the chain.
2244   const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue();
2245   const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue();
2246   SDValue Tmp1 =
2247       getLoad(TLI.getPointerTy(getDataLayout()), dl, Node->getOperand(0),
2248               Node->getOperand(2), MachinePointerInfo(VS));
2249   return getStore(Tmp1.getValue(1), dl, Tmp1, Node->getOperand(1),
2250                   MachinePointerInfo(VD));
2251 }
2252 
2253 Align SelectionDAG::getReducedAlign(EVT VT, bool UseABI) {
2254   const DataLayout &DL = getDataLayout();
2255   Type *Ty = VT.getTypeForEVT(*getContext());
2256   Align RedAlign = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty);
2257 
2258   if (TLI->isTypeLegal(VT) || !VT.isVector())
2259     return RedAlign;
2260 
2261   const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
2262   const Align StackAlign = TFI->getStackAlign();
2263 
2264   // See if we can choose a smaller ABI alignment in cases where it's an
2265   // illegal vector type that will get broken down.
2266   if (RedAlign > StackAlign) {
2267     EVT IntermediateVT;
2268     MVT RegisterVT;
2269     unsigned NumIntermediates;
2270     TLI->getVectorTypeBreakdown(*getContext(), VT, IntermediateVT,
2271                                 NumIntermediates, RegisterVT);
2272     Ty = IntermediateVT.getTypeForEVT(*getContext());
2273     Align RedAlign2 = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty);
2274     if (RedAlign2 < RedAlign)
2275       RedAlign = RedAlign2;
2276   }
2277 
2278   return RedAlign;
2279 }
2280 
2281 SDValue SelectionDAG::CreateStackTemporary(TypeSize Bytes, Align Alignment) {
2282   MachineFrameInfo &MFI = MF->getFrameInfo();
2283   const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
2284   int StackID = 0;
2285   if (Bytes.isScalable())
2286     StackID = TFI->getStackIDForScalableVectors();
2287   // The stack id gives an indication of whether the object is scalable or
2288   // not, so it's safe to pass in the minimum size here.
2289   int FrameIdx = MFI.CreateStackObject(Bytes.getKnownMinSize(), Alignment,
2290                                        false, nullptr, StackID);
2291   return getFrameIndex(FrameIdx, TLI->getFrameIndexTy(getDataLayout()));
2292 }
2293 
2294 SDValue SelectionDAG::CreateStackTemporary(EVT VT, unsigned minAlign) {
2295   Type *Ty = VT.getTypeForEVT(*getContext());
2296   Align StackAlign =
2297       std::max(getDataLayout().getPrefTypeAlign(Ty), Align(minAlign));
2298   return CreateStackTemporary(VT.getStoreSize(), StackAlign);
2299 }
2300 
2301 SDValue SelectionDAG::CreateStackTemporary(EVT VT1, EVT VT2) {
2302   TypeSize VT1Size = VT1.getStoreSize();
2303   TypeSize VT2Size = VT2.getStoreSize();
2304   assert(VT1Size.isScalable() == VT2Size.isScalable() &&
2305          "Don't know how to choose the maximum size when creating a stack "
2306          "temporary");
2307   TypeSize Bytes =
2308       VT1Size.getKnownMinSize() > VT2Size.getKnownMinSize() ? VT1Size : VT2Size;
2309 
2310   Type *Ty1 = VT1.getTypeForEVT(*getContext());
2311   Type *Ty2 = VT2.getTypeForEVT(*getContext());
2312   const DataLayout &DL = getDataLayout();
2313   Align Align = std::max(DL.getPrefTypeAlign(Ty1), DL.getPrefTypeAlign(Ty2));
2314   return CreateStackTemporary(Bytes, Align);
2315 }
2316 
2317 SDValue SelectionDAG::FoldSetCC(EVT VT, SDValue N1, SDValue N2,
2318                                 ISD::CondCode Cond, const SDLoc &dl) {
2319   EVT OpVT = N1.getValueType();
2320 
2321   // These setcc operations always fold.
2322   switch (Cond) {
2323   default: break;
2324   case ISD::SETFALSE:
2325   case ISD::SETFALSE2: return getBoolConstant(false, dl, VT, OpVT);
2326   case ISD::SETTRUE:
2327   case ISD::SETTRUE2: return getBoolConstant(true, dl, VT, OpVT);
2328 
2329   case ISD::SETOEQ:
2330   case ISD::SETOGT:
2331   case ISD::SETOGE:
2332   case ISD::SETOLT:
2333   case ISD::SETOLE:
2334   case ISD::SETONE:
2335   case ISD::SETO:
2336   case ISD::SETUO:
2337   case ISD::SETUEQ:
2338   case ISD::SETUNE:
2339     assert(!OpVT.isInteger() && "Illegal setcc for integer!");
2340     break;
2341   }
2342 
2343   if (OpVT.isInteger()) {
2344     // For EQ and NE, we can always pick a value for the undef to make the
2345     // predicate pass or fail, so we can return undef.
2346     // Matches behavior in llvm::ConstantFoldCompareInstruction.
2347     // icmp eq/ne X, undef -> undef.
2348     if ((N1.isUndef() || N2.isUndef()) &&
2349         (Cond == ISD::SETEQ || Cond == ISD::SETNE))
2350       return getUNDEF(VT);
2351 
2352     // If both operands are undef, we can return undef for int comparison.
2353     // icmp undef, undef -> undef.
2354     if (N1.isUndef() && N2.isUndef())
2355       return getUNDEF(VT);
2356 
2357     // icmp X, X -> true/false
2358     // icmp X, undef -> true/false because undef could be X.
2359     if (N1 == N2)
2360       return getBoolConstant(ISD::isTrueWhenEqual(Cond), dl, VT, OpVT);
2361   }
2362 
2363   if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2)) {
2364     const APInt &C2 = N2C->getAPIntValue();
2365     if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1)) {
2366       const APInt &C1 = N1C->getAPIntValue();
2367 
2368       return getBoolConstant(ICmpInst::compare(C1, C2, getICmpCondCode(Cond)),
2369                              dl, VT, OpVT);
2370     }
2371   }
2372 
2373   auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
2374   auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
2375 
2376   if (N1CFP && N2CFP) {
2377     APFloat::cmpResult R = N1CFP->getValueAPF().compare(N2CFP->getValueAPF());
2378     switch (Cond) {
2379     default: break;
2380     case ISD::SETEQ:  if (R==APFloat::cmpUnordered)
2381                         return getUNDEF(VT);
2382                       LLVM_FALLTHROUGH;
2383     case ISD::SETOEQ: return getBoolConstant(R==APFloat::cmpEqual, dl, VT,
2384                                              OpVT);
2385     case ISD::SETNE:  if (R==APFloat::cmpUnordered)
2386                         return getUNDEF(VT);
2387                       LLVM_FALLTHROUGH;
2388     case ISD::SETONE: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2389                                              R==APFloat::cmpLessThan, dl, VT,
2390                                              OpVT);
2391     case ISD::SETLT:  if (R==APFloat::cmpUnordered)
2392                         return getUNDEF(VT);
2393                       LLVM_FALLTHROUGH;
2394     case ISD::SETOLT: return getBoolConstant(R==APFloat::cmpLessThan, dl, VT,
2395                                              OpVT);
2396     case ISD::SETGT:  if (R==APFloat::cmpUnordered)
2397                         return getUNDEF(VT);
2398                       LLVM_FALLTHROUGH;
2399     case ISD::SETOGT: return getBoolConstant(R==APFloat::cmpGreaterThan, dl,
2400                                              VT, OpVT);
2401     case ISD::SETLE:  if (R==APFloat::cmpUnordered)
2402                         return getUNDEF(VT);
2403                       LLVM_FALLTHROUGH;
2404     case ISD::SETOLE: return getBoolConstant(R==APFloat::cmpLessThan ||
2405                                              R==APFloat::cmpEqual, dl, VT,
2406                                              OpVT);
2407     case ISD::SETGE:  if (R==APFloat::cmpUnordered)
2408                         return getUNDEF(VT);
2409                       LLVM_FALLTHROUGH;
2410     case ISD::SETOGE: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2411                                          R==APFloat::cmpEqual, dl, VT, OpVT);
2412     case ISD::SETO:   return getBoolConstant(R!=APFloat::cmpUnordered, dl, VT,
2413                                              OpVT);
2414     case ISD::SETUO:  return getBoolConstant(R==APFloat::cmpUnordered, dl, VT,
2415                                              OpVT);
2416     case ISD::SETUEQ: return getBoolConstant(R==APFloat::cmpUnordered ||
2417                                              R==APFloat::cmpEqual, dl, VT,
2418                                              OpVT);
2419     case ISD::SETUNE: return getBoolConstant(R!=APFloat::cmpEqual, dl, VT,
2420                                              OpVT);
2421     case ISD::SETULT: return getBoolConstant(R==APFloat::cmpUnordered ||
2422                                              R==APFloat::cmpLessThan, dl, VT,
2423                                              OpVT);
2424     case ISD::SETUGT: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2425                                              R==APFloat::cmpUnordered, dl, VT,
2426                                              OpVT);
2427     case ISD::SETULE: return getBoolConstant(R!=APFloat::cmpGreaterThan, dl,
2428                                              VT, OpVT);
2429     case ISD::SETUGE: return getBoolConstant(R!=APFloat::cmpLessThan, dl, VT,
2430                                              OpVT);
2431     }
2432   } else if (N1CFP && OpVT.isSimple() && !N2.isUndef()) {
2433     // Ensure that the constant occurs on the RHS.
2434     ISD::CondCode SwappedCond = ISD::getSetCCSwappedOperands(Cond);
2435     if (!TLI->isCondCodeLegal(SwappedCond, OpVT.getSimpleVT()))
2436       return SDValue();
2437     return getSetCC(dl, VT, N2, N1, SwappedCond);
2438   } else if ((N2CFP && N2CFP->getValueAPF().isNaN()) ||
2439              (OpVT.isFloatingPoint() && (N1.isUndef() || N2.isUndef()))) {
2440     // If an operand is known to be a nan (or undef that could be a nan), we can
2441     // fold it.
2442     // Choosing NaN for the undef will always make unordered comparison succeed
2443     // and ordered comparison fails.
2444     // Matches behavior in llvm::ConstantFoldCompareInstruction.
2445     switch (ISD::getUnorderedFlavor(Cond)) {
2446     default:
2447       llvm_unreachable("Unknown flavor!");
2448     case 0: // Known false.
2449       return getBoolConstant(false, dl, VT, OpVT);
2450     case 1: // Known true.
2451       return getBoolConstant(true, dl, VT, OpVT);
2452     case 2: // Undefined.
2453       return getUNDEF(VT);
2454     }
2455   }
2456 
2457   // Could not fold it.
2458   return SDValue();
2459 }
2460 
2461 /// See if the specified operand can be simplified with the knowledge that only
2462 /// the bits specified by DemandedBits are used.
2463 /// TODO: really we should be making this into the DAG equivalent of
2464 /// SimplifyMultipleUseDemandedBits and not generate any new nodes.
2465 SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &DemandedBits) {
2466   EVT VT = V.getValueType();
2467 
2468   if (VT.isScalableVector())
2469     return SDValue();
2470 
2471   switch (V.getOpcode()) {
2472   default:
2473     return TLI->SimplifyMultipleUseDemandedBits(V, DemandedBits, *this);
2474   case ISD::Constant: {
2475     const APInt &CVal = cast<ConstantSDNode>(V)->getAPIntValue();
2476     APInt NewVal = CVal & DemandedBits;
2477     if (NewVal != CVal)
2478       return getConstant(NewVal, SDLoc(V), V.getValueType());
2479     break;
2480   }
2481   case ISD::SRL:
2482     // Only look at single-use SRLs.
2483     if (!V.getNode()->hasOneUse())
2484       break;
2485     if (auto *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
2486       // See if we can recursively simplify the LHS.
2487       unsigned Amt = RHSC->getZExtValue();
2488 
2489       // Watch out for shift count overflow though.
2490       if (Amt >= DemandedBits.getBitWidth())
2491         break;
2492       APInt SrcDemandedBits = DemandedBits << Amt;
2493       if (SDValue SimplifyLHS = TLI->SimplifyMultipleUseDemandedBits(
2494               V.getOperand(0), SrcDemandedBits, *this))
2495         return getNode(ISD::SRL, SDLoc(V), V.getValueType(), SimplifyLHS,
2496                        V.getOperand(1));
2497     }
2498     break;
2499   }
2500   return SDValue();
2501 }
2502 
2503 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero.  We
2504 /// use this predicate to simplify operations downstream.
2505 bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const {
2506   unsigned BitWidth = Op.getScalarValueSizeInBits();
2507   return MaskedValueIsZero(Op, APInt::getSignMask(BitWidth), Depth);
2508 }
2509 
2510 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero.  We use
2511 /// this predicate to simplify operations downstream.  Mask is known to be zero
2512 /// for bits that V cannot have.
2513 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask,
2514                                      unsigned Depth) const {
2515   return Mask.isSubsetOf(computeKnownBits(V, Depth).Zero);
2516 }
2517 
2518 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero in
2519 /// DemandedElts.  We use this predicate to simplify operations downstream.
2520 /// Mask is known to be zero for bits that V cannot have.
2521 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask,
2522                                      const APInt &DemandedElts,
2523                                      unsigned Depth) const {
2524   return Mask.isSubsetOf(computeKnownBits(V, DemandedElts, Depth).Zero);
2525 }
2526 
2527 /// MaskedVectorIsZero - Return true if 'Op' is known to be zero in
2528 /// DemandedElts.  We use this predicate to simplify operations downstream.
2529 bool SelectionDAG::MaskedVectorIsZero(SDValue V, const APInt &DemandedElts,
2530                                       unsigned Depth /* = 0 */) const {
2531   APInt Mask = APInt::getAllOnes(V.getScalarValueSizeInBits());
2532   return Mask.isSubsetOf(computeKnownBits(V, DemandedElts, Depth).Zero);
2533 }
2534 
2535 /// MaskedValueIsAllOnes - Return true if '(Op & Mask) == Mask'.
2536 bool SelectionDAG::MaskedValueIsAllOnes(SDValue V, const APInt &Mask,
2537                                         unsigned Depth) const {
2538   return Mask.isSubsetOf(computeKnownBits(V, Depth).One);
2539 }
2540 
2541 /// isSplatValue - Return true if the vector V has the same value
2542 /// across all DemandedElts. For scalable vectors it does not make
2543 /// sense to specify which elements are demanded or undefined, therefore
2544 /// they are simply ignored.
2545 bool SelectionDAG::isSplatValue(SDValue V, const APInt &DemandedElts,
2546                                 APInt &UndefElts, unsigned Depth) const {
2547   unsigned Opcode = V.getOpcode();
2548   EVT VT = V.getValueType();
2549   assert(VT.isVector() && "Vector type expected");
2550 
2551   if (!VT.isScalableVector() && !DemandedElts)
2552     return false; // No demanded elts, better to assume we don't know anything.
2553 
2554   if (Depth >= MaxRecursionDepth)
2555     return false; // Limit search depth.
2556 
2557   // Deal with some common cases here that work for both fixed and scalable
2558   // vector types.
2559   switch (Opcode) {
2560   case ISD::SPLAT_VECTOR:
2561     UndefElts = V.getOperand(0).isUndef()
2562                     ? APInt::getAllOnes(DemandedElts.getBitWidth())
2563                     : APInt(DemandedElts.getBitWidth(), 0);
2564     return true;
2565   case ISD::ADD:
2566   case ISD::SUB:
2567   case ISD::AND:
2568   case ISD::XOR:
2569   case ISD::OR: {
2570     APInt UndefLHS, UndefRHS;
2571     SDValue LHS = V.getOperand(0);
2572     SDValue RHS = V.getOperand(1);
2573     if (isSplatValue(LHS, DemandedElts, UndefLHS, Depth + 1) &&
2574         isSplatValue(RHS, DemandedElts, UndefRHS, Depth + 1)) {
2575       UndefElts = UndefLHS | UndefRHS;
2576       return true;
2577     }
2578     return false;
2579   }
2580   case ISD::ABS:
2581   case ISD::TRUNCATE:
2582   case ISD::SIGN_EXTEND:
2583   case ISD::ZERO_EXTEND:
2584     return isSplatValue(V.getOperand(0), DemandedElts, UndefElts, Depth + 1);
2585   default:
2586     if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
2587         Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID)
2588       return TLI->isSplatValueForTargetNode(V, DemandedElts, UndefElts, Depth);
2589     break;
2590 }
2591 
2592   // We don't support other cases than those above for scalable vectors at
2593   // the moment.
2594   if (VT.isScalableVector())
2595     return false;
2596 
2597   unsigned NumElts = VT.getVectorNumElements();
2598   assert(NumElts == DemandedElts.getBitWidth() && "Vector size mismatch");
2599   UndefElts = APInt::getZero(NumElts);
2600 
2601   switch (Opcode) {
2602   case ISD::BUILD_VECTOR: {
2603     SDValue Scl;
2604     for (unsigned i = 0; i != NumElts; ++i) {
2605       SDValue Op = V.getOperand(i);
2606       if (Op.isUndef()) {
2607         UndefElts.setBit(i);
2608         continue;
2609       }
2610       if (!DemandedElts[i])
2611         continue;
2612       if (Scl && Scl != Op)
2613         return false;
2614       Scl = Op;
2615     }
2616     return true;
2617   }
2618   case ISD::VECTOR_SHUFFLE: {
2619     // Check if this is a shuffle node doing a splat or a shuffle of a splat.
2620     APInt DemandedLHS = APInt::getNullValue(NumElts);
2621     APInt DemandedRHS = APInt::getNullValue(NumElts);
2622     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(V)->getMask();
2623     for (int i = 0; i != (int)NumElts; ++i) {
2624       int M = Mask[i];
2625       if (M < 0) {
2626         UndefElts.setBit(i);
2627         continue;
2628       }
2629       if (!DemandedElts[i])
2630         continue;
2631       if (M < (int)NumElts)
2632         DemandedLHS.setBit(M);
2633       else
2634         DemandedRHS.setBit(M - NumElts);
2635     }
2636 
2637     // If we aren't demanding either op, assume there's no splat.
2638     // If we are demanding both ops, assume there's no splat.
2639     if ((DemandedLHS.isZero() && DemandedRHS.isZero()) ||
2640         (!DemandedLHS.isZero() && !DemandedRHS.isZero()))
2641       return false;
2642 
2643     // See if the demanded elts of the source op is a splat or we only demand
2644     // one element, which should always be a splat.
2645     // TODO: Handle source ops splats with undefs.
2646     auto CheckSplatSrc = [&](SDValue Src, const APInt &SrcElts) {
2647       APInt SrcUndefs;
2648       return (SrcElts.countPopulation() == 1) ||
2649              (isSplatValue(Src, SrcElts, SrcUndefs, Depth + 1) &&
2650               (SrcElts & SrcUndefs).isZero());
2651     };
2652     if (!DemandedLHS.isZero())
2653       return CheckSplatSrc(V.getOperand(0), DemandedLHS);
2654     return CheckSplatSrc(V.getOperand(1), DemandedRHS);
2655   }
2656   case ISD::EXTRACT_SUBVECTOR: {
2657     // Offset the demanded elts by the subvector index.
2658     SDValue Src = V.getOperand(0);
2659     // We don't support scalable vectors at the moment.
2660     if (Src.getValueType().isScalableVector())
2661       return false;
2662     uint64_t Idx = V.getConstantOperandVal(1);
2663     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2664     APInt UndefSrcElts;
2665     APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
2666     if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) {
2667       UndefElts = UndefSrcElts.extractBits(NumElts, Idx);
2668       return true;
2669     }
2670     break;
2671   }
2672   case ISD::ANY_EXTEND_VECTOR_INREG:
2673   case ISD::SIGN_EXTEND_VECTOR_INREG:
2674   case ISD::ZERO_EXTEND_VECTOR_INREG: {
2675     // Widen the demanded elts by the src element count.
2676     SDValue Src = V.getOperand(0);
2677     // We don't support scalable vectors at the moment.
2678     if (Src.getValueType().isScalableVector())
2679       return false;
2680     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2681     APInt UndefSrcElts;
2682     APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts);
2683     if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) {
2684       UndefElts = UndefSrcElts.trunc(NumElts);
2685       return true;
2686     }
2687     break;
2688   }
2689   case ISD::BITCAST: {
2690     SDValue Src = V.getOperand(0);
2691     EVT SrcVT = Src.getValueType();
2692     unsigned SrcBitWidth = SrcVT.getScalarSizeInBits();
2693     unsigned BitWidth = VT.getScalarSizeInBits();
2694 
2695     // Ignore bitcasts from unsupported types.
2696     // TODO: Add fp support?
2697     if (!SrcVT.isVector() || !SrcVT.isInteger() || !VT.isInteger())
2698       break;
2699 
2700     // Bitcast 'small element' vector to 'large element' vector.
2701     if ((BitWidth % SrcBitWidth) == 0) {
2702       // See if each sub element is a splat.
2703       unsigned Scale = BitWidth / SrcBitWidth;
2704       unsigned NumSrcElts = SrcVT.getVectorNumElements();
2705       APInt ScaledDemandedElts =
2706           APIntOps::ScaleBitMask(DemandedElts, NumSrcElts);
2707       for (unsigned I = 0; I != Scale; ++I) {
2708         APInt SubUndefElts;
2709         APInt SubDemandedElt = APInt::getOneBitSet(Scale, I);
2710         APInt SubDemandedElts = APInt::getSplat(NumSrcElts, SubDemandedElt);
2711         SubDemandedElts &= ScaledDemandedElts;
2712         if (!isSplatValue(Src, SubDemandedElts, SubUndefElts, Depth + 1))
2713           return false;
2714 
2715         // Here we can't do "MatchAnyBits" operation merge for undef bits.
2716         // Because some operation only use part value of the source.
2717         // Take llvm.fshl.* for example:
2718         // t1: v4i32 = Constant:i32<12>, undef:i32, Constant:i32<12>, undef:i32
2719         // t2: v2i64 = bitcast t1
2720         // t5: v2i64 = fshl t3, t4, t2
2721         // We can not convert t2 to {i64 undef, i64 undef}
2722         UndefElts |= APIntOps::ScaleBitMask(SubUndefElts, NumElts,
2723                                             /*MatchAllBits=*/true);
2724       }
2725       return true;
2726     }
2727     break;
2728   }
2729   }
2730 
2731   return false;
2732 }
2733 
2734 /// Helper wrapper to main isSplatValue function.
2735 bool SelectionDAG::isSplatValue(SDValue V, bool AllowUndefs) const {
2736   EVT VT = V.getValueType();
2737   assert(VT.isVector() && "Vector type expected");
2738 
2739   APInt UndefElts;
2740   APInt DemandedElts;
2741 
2742   // For now we don't support this with scalable vectors.
2743   if (!VT.isScalableVector())
2744     DemandedElts = APInt::getAllOnes(VT.getVectorNumElements());
2745   return isSplatValue(V, DemandedElts, UndefElts) &&
2746          (AllowUndefs || !UndefElts);
2747 }
2748 
2749 SDValue SelectionDAG::getSplatSourceVector(SDValue V, int &SplatIdx) {
2750   V = peekThroughExtractSubvectors(V);
2751 
2752   EVT VT = V.getValueType();
2753   unsigned Opcode = V.getOpcode();
2754   switch (Opcode) {
2755   default: {
2756     APInt UndefElts;
2757     APInt DemandedElts;
2758 
2759     if (!VT.isScalableVector())
2760       DemandedElts = APInt::getAllOnes(VT.getVectorNumElements());
2761 
2762     if (isSplatValue(V, DemandedElts, UndefElts)) {
2763       if (VT.isScalableVector()) {
2764         // DemandedElts and UndefElts are ignored for scalable vectors, since
2765         // the only supported cases are SPLAT_VECTOR nodes.
2766         SplatIdx = 0;
2767       } else {
2768         // Handle case where all demanded elements are UNDEF.
2769         if (DemandedElts.isSubsetOf(UndefElts)) {
2770           SplatIdx = 0;
2771           return getUNDEF(VT);
2772         }
2773         SplatIdx = (UndefElts & DemandedElts).countTrailingOnes();
2774       }
2775       return V;
2776     }
2777     break;
2778   }
2779   case ISD::SPLAT_VECTOR:
2780     SplatIdx = 0;
2781     return V;
2782   case ISD::VECTOR_SHUFFLE: {
2783     if (VT.isScalableVector())
2784       return SDValue();
2785 
2786     // Check if this is a shuffle node doing a splat.
2787     // TODO - remove this and rely purely on SelectionDAG::isSplatValue,
2788     // getTargetVShiftNode currently struggles without the splat source.
2789     auto *SVN = cast<ShuffleVectorSDNode>(V);
2790     if (!SVN->isSplat())
2791       break;
2792     int Idx = SVN->getSplatIndex();
2793     int NumElts = V.getValueType().getVectorNumElements();
2794     SplatIdx = Idx % NumElts;
2795     return V.getOperand(Idx / NumElts);
2796   }
2797   }
2798 
2799   return SDValue();
2800 }
2801 
2802 SDValue SelectionDAG::getSplatValue(SDValue V, bool LegalTypes) {
2803   int SplatIdx;
2804   if (SDValue SrcVector = getSplatSourceVector(V, SplatIdx)) {
2805     EVT SVT = SrcVector.getValueType().getScalarType();
2806     EVT LegalSVT = SVT;
2807     if (LegalTypes && !TLI->isTypeLegal(SVT)) {
2808       if (!SVT.isInteger())
2809         return SDValue();
2810       LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
2811       if (LegalSVT.bitsLT(SVT))
2812         return SDValue();
2813     }
2814     return getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(V), LegalSVT, SrcVector,
2815                    getVectorIdxConstant(SplatIdx, SDLoc(V)));
2816   }
2817   return SDValue();
2818 }
2819 
2820 const APInt *
2821 SelectionDAG::getValidShiftAmountConstant(SDValue V,
2822                                           const APInt &DemandedElts) const {
2823   assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
2824           V.getOpcode() == ISD::SRA) &&
2825          "Unknown shift node");
2826   unsigned BitWidth = V.getScalarValueSizeInBits();
2827   if (ConstantSDNode *SA = isConstOrConstSplat(V.getOperand(1), DemandedElts)) {
2828     // Shifting more than the bitwidth is not valid.
2829     const APInt &ShAmt = SA->getAPIntValue();
2830     if (ShAmt.ult(BitWidth))
2831       return &ShAmt;
2832   }
2833   return nullptr;
2834 }
2835 
2836 const APInt *SelectionDAG::getValidMinimumShiftAmountConstant(
2837     SDValue V, const APInt &DemandedElts) const {
2838   assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
2839           V.getOpcode() == ISD::SRA) &&
2840          "Unknown shift node");
2841   if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts))
2842     return ValidAmt;
2843   unsigned BitWidth = V.getScalarValueSizeInBits();
2844   auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1));
2845   if (!BV)
2846     return nullptr;
2847   const APInt *MinShAmt = nullptr;
2848   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
2849     if (!DemandedElts[i])
2850       continue;
2851     auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i));
2852     if (!SA)
2853       return nullptr;
2854     // Shifting more than the bitwidth is not valid.
2855     const APInt &ShAmt = SA->getAPIntValue();
2856     if (ShAmt.uge(BitWidth))
2857       return nullptr;
2858     if (MinShAmt && MinShAmt->ule(ShAmt))
2859       continue;
2860     MinShAmt = &ShAmt;
2861   }
2862   return MinShAmt;
2863 }
2864 
2865 const APInt *SelectionDAG::getValidMaximumShiftAmountConstant(
2866     SDValue V, const APInt &DemandedElts) const {
2867   assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
2868           V.getOpcode() == ISD::SRA) &&
2869          "Unknown shift node");
2870   if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts))
2871     return ValidAmt;
2872   unsigned BitWidth = V.getScalarValueSizeInBits();
2873   auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1));
2874   if (!BV)
2875     return nullptr;
2876   const APInt *MaxShAmt = nullptr;
2877   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
2878     if (!DemandedElts[i])
2879       continue;
2880     auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i));
2881     if (!SA)
2882       return nullptr;
2883     // Shifting more than the bitwidth is not valid.
2884     const APInt &ShAmt = SA->getAPIntValue();
2885     if (ShAmt.uge(BitWidth))
2886       return nullptr;
2887     if (MaxShAmt && MaxShAmt->uge(ShAmt))
2888       continue;
2889     MaxShAmt = &ShAmt;
2890   }
2891   return MaxShAmt;
2892 }
2893 
2894 /// Determine which bits of Op are known to be either zero or one and return
2895 /// them in Known. For vectors, the known bits are those that are shared by
2896 /// every vector element.
2897 KnownBits SelectionDAG::computeKnownBits(SDValue Op, unsigned Depth) const {
2898   EVT VT = Op.getValueType();
2899 
2900   // TOOD: Until we have a plan for how to represent demanded elements for
2901   // scalable vectors, we can just bail out for now.
2902   if (Op.getValueType().isScalableVector()) {
2903     unsigned BitWidth = Op.getScalarValueSizeInBits();
2904     return KnownBits(BitWidth);
2905   }
2906 
2907   APInt DemandedElts = VT.isVector()
2908                            ? APInt::getAllOnes(VT.getVectorNumElements())
2909                            : APInt(1, 1);
2910   return computeKnownBits(Op, DemandedElts, Depth);
2911 }
2912 
2913 /// Determine which bits of Op are known to be either zero or one and return
2914 /// them in Known. The DemandedElts argument allows us to only collect the known
2915 /// bits that are shared by the requested vector elements.
2916 KnownBits SelectionDAG::computeKnownBits(SDValue Op, const APInt &DemandedElts,
2917                                          unsigned Depth) const {
2918   unsigned BitWidth = Op.getScalarValueSizeInBits();
2919 
2920   KnownBits Known(BitWidth);   // Don't know anything.
2921 
2922   // TOOD: Until we have a plan for how to represent demanded elements for
2923   // scalable vectors, we can just bail out for now.
2924   if (Op.getValueType().isScalableVector())
2925     return Known;
2926 
2927   if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
2928     // We know all of the bits for a constant!
2929     return KnownBits::makeConstant(C->getAPIntValue());
2930   }
2931   if (auto *C = dyn_cast<ConstantFPSDNode>(Op)) {
2932     // We know all of the bits for a constant fp!
2933     return KnownBits::makeConstant(C->getValueAPF().bitcastToAPInt());
2934   }
2935 
2936   if (Depth >= MaxRecursionDepth)
2937     return Known;  // Limit search depth.
2938 
2939   KnownBits Known2;
2940   unsigned NumElts = DemandedElts.getBitWidth();
2941   assert((!Op.getValueType().isVector() ||
2942           NumElts == Op.getValueType().getVectorNumElements()) &&
2943          "Unexpected vector size");
2944 
2945   if (!DemandedElts)
2946     return Known;  // No demanded elts, better to assume we don't know anything.
2947 
2948   unsigned Opcode = Op.getOpcode();
2949   switch (Opcode) {
2950   case ISD::BUILD_VECTOR:
2951     // Collect the known bits that are shared by every demanded vector element.
2952     Known.Zero.setAllBits(); Known.One.setAllBits();
2953     for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
2954       if (!DemandedElts[i])
2955         continue;
2956 
2957       SDValue SrcOp = Op.getOperand(i);
2958       Known2 = computeKnownBits(SrcOp, Depth + 1);
2959 
2960       // BUILD_VECTOR can implicitly truncate sources, we must handle this.
2961       if (SrcOp.getValueSizeInBits() != BitWidth) {
2962         assert(SrcOp.getValueSizeInBits() > BitWidth &&
2963                "Expected BUILD_VECTOR implicit truncation");
2964         Known2 = Known2.trunc(BitWidth);
2965       }
2966 
2967       // Known bits are the values that are shared by every demanded element.
2968       Known = KnownBits::commonBits(Known, Known2);
2969 
2970       // If we don't know any bits, early out.
2971       if (Known.isUnknown())
2972         break;
2973     }
2974     break;
2975   case ISD::VECTOR_SHUFFLE: {
2976     // Collect the known bits that are shared by every vector element referenced
2977     // by the shuffle.
2978     APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
2979     Known.Zero.setAllBits(); Known.One.setAllBits();
2980     const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
2981     assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
2982     for (unsigned i = 0; i != NumElts; ++i) {
2983       if (!DemandedElts[i])
2984         continue;
2985 
2986       int M = SVN->getMaskElt(i);
2987       if (M < 0) {
2988         // For UNDEF elements, we don't know anything about the common state of
2989         // the shuffle result.
2990         Known.resetAll();
2991         DemandedLHS.clearAllBits();
2992         DemandedRHS.clearAllBits();
2993         break;
2994       }
2995 
2996       if ((unsigned)M < NumElts)
2997         DemandedLHS.setBit((unsigned)M % NumElts);
2998       else
2999         DemandedRHS.setBit((unsigned)M % NumElts);
3000     }
3001     // Known bits are the values that are shared by every demanded element.
3002     if (!!DemandedLHS) {
3003       SDValue LHS = Op.getOperand(0);
3004       Known2 = computeKnownBits(LHS, DemandedLHS, Depth + 1);
3005       Known = KnownBits::commonBits(Known, Known2);
3006     }
3007     // If we don't know any bits, early out.
3008     if (Known.isUnknown())
3009       break;
3010     if (!!DemandedRHS) {
3011       SDValue RHS = Op.getOperand(1);
3012       Known2 = computeKnownBits(RHS, DemandedRHS, Depth + 1);
3013       Known = KnownBits::commonBits(Known, Known2);
3014     }
3015     break;
3016   }
3017   case ISD::CONCAT_VECTORS: {
3018     // Split DemandedElts and test each of the demanded subvectors.
3019     Known.Zero.setAllBits(); Known.One.setAllBits();
3020     EVT SubVectorVT = Op.getOperand(0).getValueType();
3021     unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
3022     unsigned NumSubVectors = Op.getNumOperands();
3023     for (unsigned i = 0; i != NumSubVectors; ++i) {
3024       APInt DemandedSub =
3025           DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts);
3026       if (!!DemandedSub) {
3027         SDValue Sub = Op.getOperand(i);
3028         Known2 = computeKnownBits(Sub, DemandedSub, Depth + 1);
3029         Known = KnownBits::commonBits(Known, Known2);
3030       }
3031       // If we don't know any bits, early out.
3032       if (Known.isUnknown())
3033         break;
3034     }
3035     break;
3036   }
3037   case ISD::INSERT_SUBVECTOR: {
3038     // Demand any elements from the subvector and the remainder from the src its
3039     // inserted into.
3040     SDValue Src = Op.getOperand(0);
3041     SDValue Sub = Op.getOperand(1);
3042     uint64_t Idx = Op.getConstantOperandVal(2);
3043     unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
3044     APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
3045     APInt DemandedSrcElts = DemandedElts;
3046     DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx);
3047 
3048     Known.One.setAllBits();
3049     Known.Zero.setAllBits();
3050     if (!!DemandedSubElts) {
3051       Known = computeKnownBits(Sub, DemandedSubElts, Depth + 1);
3052       if (Known.isUnknown())
3053         break; // early-out.
3054     }
3055     if (!!DemandedSrcElts) {
3056       Known2 = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
3057       Known = KnownBits::commonBits(Known, Known2);
3058     }
3059     break;
3060   }
3061   case ISD::EXTRACT_SUBVECTOR: {
3062     // Offset the demanded elts by the subvector index.
3063     SDValue Src = Op.getOperand(0);
3064     // Bail until we can represent demanded elements for scalable vectors.
3065     if (Src.getValueType().isScalableVector())
3066       break;
3067     uint64_t Idx = Op.getConstantOperandVal(1);
3068     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
3069     APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
3070     Known = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
3071     break;
3072   }
3073   case ISD::SCALAR_TO_VECTOR: {
3074     // We know about scalar_to_vector as much as we know about it source,
3075     // which becomes the first element of otherwise unknown vector.
3076     if (DemandedElts != 1)
3077       break;
3078 
3079     SDValue N0 = Op.getOperand(0);
3080     Known = computeKnownBits(N0, Depth + 1);
3081     if (N0.getValueSizeInBits() != BitWidth)
3082       Known = Known.trunc(BitWidth);
3083 
3084     break;
3085   }
3086   case ISD::BITCAST: {
3087     SDValue N0 = Op.getOperand(0);
3088     EVT SubVT = N0.getValueType();
3089     unsigned SubBitWidth = SubVT.getScalarSizeInBits();
3090 
3091     // Ignore bitcasts from unsupported types.
3092     if (!(SubVT.isInteger() || SubVT.isFloatingPoint()))
3093       break;
3094 
3095     // Fast handling of 'identity' bitcasts.
3096     if (BitWidth == SubBitWidth) {
3097       Known = computeKnownBits(N0, DemandedElts, Depth + 1);
3098       break;
3099     }
3100 
3101     bool IsLE = getDataLayout().isLittleEndian();
3102 
3103     // Bitcast 'small element' vector to 'large element' scalar/vector.
3104     if ((BitWidth % SubBitWidth) == 0) {
3105       assert(N0.getValueType().isVector() && "Expected bitcast from vector");
3106 
3107       // Collect known bits for the (larger) output by collecting the known
3108       // bits from each set of sub elements and shift these into place.
3109       // We need to separately call computeKnownBits for each set of
3110       // sub elements as the knownbits for each is likely to be different.
3111       unsigned SubScale = BitWidth / SubBitWidth;
3112       APInt SubDemandedElts(NumElts * SubScale, 0);
3113       for (unsigned i = 0; i != NumElts; ++i)
3114         if (DemandedElts[i])
3115           SubDemandedElts.setBit(i * SubScale);
3116 
3117       for (unsigned i = 0; i != SubScale; ++i) {
3118         Known2 = computeKnownBits(N0, SubDemandedElts.shl(i),
3119                          Depth + 1);
3120         unsigned Shifts = IsLE ? i : SubScale - 1 - i;
3121         Known.insertBits(Known2, SubBitWidth * Shifts);
3122       }
3123     }
3124 
3125     // Bitcast 'large element' scalar/vector to 'small element' vector.
3126     if ((SubBitWidth % BitWidth) == 0) {
3127       assert(Op.getValueType().isVector() && "Expected bitcast to vector");
3128 
3129       // Collect known bits for the (smaller) output by collecting the known
3130       // bits from the overlapping larger input elements and extracting the
3131       // sub sections we actually care about.
3132       unsigned SubScale = SubBitWidth / BitWidth;
3133       APInt SubDemandedElts =
3134           APIntOps::ScaleBitMask(DemandedElts, NumElts / SubScale);
3135       Known2 = computeKnownBits(N0, SubDemandedElts, Depth + 1);
3136 
3137       Known.Zero.setAllBits(); Known.One.setAllBits();
3138       for (unsigned i = 0; i != NumElts; ++i)
3139         if (DemandedElts[i]) {
3140           unsigned Shifts = IsLE ? i : NumElts - 1 - i;
3141           unsigned Offset = (Shifts % SubScale) * BitWidth;
3142           Known = KnownBits::commonBits(Known,
3143                                         Known2.extractBits(BitWidth, Offset));
3144           // If we don't know any bits, early out.
3145           if (Known.isUnknown())
3146             break;
3147         }
3148     }
3149     break;
3150   }
3151   case ISD::AND:
3152     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3153     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3154 
3155     Known &= Known2;
3156     break;
3157   case ISD::OR:
3158     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3159     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3160 
3161     Known |= Known2;
3162     break;
3163   case ISD::XOR:
3164     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3165     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3166 
3167     Known ^= Known2;
3168     break;
3169   case ISD::MUL: {
3170     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3171     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3172     bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1);
3173     // TODO: SelfMultiply can be poison, but not undef.
3174     if (SelfMultiply)
3175       SelfMultiply &= isGuaranteedNotToBeUndefOrPoison(
3176           Op.getOperand(0), DemandedElts, false, Depth + 1);
3177     Known = KnownBits::mul(Known, Known2, SelfMultiply);
3178 
3179     // If the multiplication is known not to overflow, the product of a number
3180     // with itself is non-negative. Only do this if we didn't already computed
3181     // the opposite value for the sign bit.
3182     if (Op->getFlags().hasNoSignedWrap() &&
3183         Op.getOperand(0) == Op.getOperand(1) &&
3184         !Known.isNegative())
3185       Known.makeNonNegative();
3186     break;
3187   }
3188   case ISD::MULHU: {
3189     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3190     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3191     Known = KnownBits::mulhu(Known, Known2);
3192     break;
3193   }
3194   case ISD::MULHS: {
3195     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3196     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3197     Known = KnownBits::mulhs(Known, Known2);
3198     break;
3199   }
3200   case ISD::UMUL_LOHI: {
3201     assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3202     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3203     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3204     bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1);
3205     if (Op.getResNo() == 0)
3206       Known = KnownBits::mul(Known, Known2, SelfMultiply);
3207     else
3208       Known = KnownBits::mulhu(Known, Known2);
3209     break;
3210   }
3211   case ISD::SMUL_LOHI: {
3212     assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3213     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3214     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3215     bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1);
3216     if (Op.getResNo() == 0)
3217       Known = KnownBits::mul(Known, Known2, SelfMultiply);
3218     else
3219       Known = KnownBits::mulhs(Known, Known2);
3220     break;
3221   }
3222   case ISD::UDIV: {
3223     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3224     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3225     Known = KnownBits::udiv(Known, Known2);
3226     break;
3227   }
3228   case ISD::AVGCEILU: {
3229     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3230     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3231     Known = Known.zext(BitWidth + 1);
3232     Known2 = Known2.zext(BitWidth + 1);
3233     KnownBits One = KnownBits::makeConstant(APInt(1, 1));
3234     Known = KnownBits::computeForAddCarry(Known, Known2, One);
3235     Known = Known.extractBits(BitWidth, 1);
3236     break;
3237   }
3238   case ISD::SELECT:
3239   case ISD::VSELECT:
3240     Known = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
3241     // If we don't know any bits, early out.
3242     if (Known.isUnknown())
3243       break;
3244     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth+1);
3245 
3246     // Only known if known in both the LHS and RHS.
3247     Known = KnownBits::commonBits(Known, Known2);
3248     break;
3249   case ISD::SELECT_CC:
3250     Known = computeKnownBits(Op.getOperand(3), DemandedElts, Depth+1);
3251     // If we don't know any bits, early out.
3252     if (Known.isUnknown())
3253       break;
3254     Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
3255 
3256     // Only known if known in both the LHS and RHS.
3257     Known = KnownBits::commonBits(Known, Known2);
3258     break;
3259   case ISD::SMULO:
3260   case ISD::UMULO:
3261     if (Op.getResNo() != 1)
3262       break;
3263     // The boolean result conforms to getBooleanContents.
3264     // If we know the result of a setcc has the top bits zero, use this info.
3265     // We know that we have an integer-based boolean since these operations
3266     // are only available for integer.
3267     if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
3268             TargetLowering::ZeroOrOneBooleanContent &&
3269         BitWidth > 1)
3270       Known.Zero.setBitsFrom(1);
3271     break;
3272   case ISD::SETCC:
3273   case ISD::SETCCCARRY:
3274   case ISD::STRICT_FSETCC:
3275   case ISD::STRICT_FSETCCS: {
3276     unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
3277     // If we know the result of a setcc has the top bits zero, use this info.
3278     if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
3279             TargetLowering::ZeroOrOneBooleanContent &&
3280         BitWidth > 1)
3281       Known.Zero.setBitsFrom(1);
3282     break;
3283   }
3284   case ISD::SHL:
3285     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3286     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3287     Known = KnownBits::shl(Known, Known2);
3288 
3289     // Minimum shift low bits are known zero.
3290     if (const APInt *ShMinAmt =
3291             getValidMinimumShiftAmountConstant(Op, DemandedElts))
3292       Known.Zero.setLowBits(ShMinAmt->getZExtValue());
3293     break;
3294   case ISD::SRL:
3295     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3296     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3297     Known = KnownBits::lshr(Known, Known2);
3298 
3299     // Minimum shift high bits are known zero.
3300     if (const APInt *ShMinAmt =
3301             getValidMinimumShiftAmountConstant(Op, DemandedElts))
3302       Known.Zero.setHighBits(ShMinAmt->getZExtValue());
3303     break;
3304   case ISD::SRA:
3305     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3306     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3307     Known = KnownBits::ashr(Known, Known2);
3308     // TODO: Add minimum shift high known sign bits.
3309     break;
3310   case ISD::FSHL:
3311   case ISD::FSHR:
3312     if (ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(2), DemandedElts)) {
3313       unsigned Amt = C->getAPIntValue().urem(BitWidth);
3314 
3315       // For fshl, 0-shift returns the 1st arg.
3316       // For fshr, 0-shift returns the 2nd arg.
3317       if (Amt == 0) {
3318         Known = computeKnownBits(Op.getOperand(Opcode == ISD::FSHL ? 0 : 1),
3319                                  DemandedElts, Depth + 1);
3320         break;
3321       }
3322 
3323       // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
3324       // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
3325       Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3326       Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3327       if (Opcode == ISD::FSHL) {
3328         Known.One <<= Amt;
3329         Known.Zero <<= Amt;
3330         Known2.One.lshrInPlace(BitWidth - Amt);
3331         Known2.Zero.lshrInPlace(BitWidth - Amt);
3332       } else {
3333         Known.One <<= BitWidth - Amt;
3334         Known.Zero <<= BitWidth - Amt;
3335         Known2.One.lshrInPlace(Amt);
3336         Known2.Zero.lshrInPlace(Amt);
3337       }
3338       Known.One |= Known2.One;
3339       Known.Zero |= Known2.Zero;
3340     }
3341     break;
3342   case ISD::SIGN_EXTEND_INREG: {
3343     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3344     EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3345     Known = Known.sextInReg(EVT.getScalarSizeInBits());
3346     break;
3347   }
3348   case ISD::CTTZ:
3349   case ISD::CTTZ_ZERO_UNDEF: {
3350     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3351     // If we have a known 1, its position is our upper bound.
3352     unsigned PossibleTZ = Known2.countMaxTrailingZeros();
3353     unsigned LowBits = Log2_32(PossibleTZ) + 1;
3354     Known.Zero.setBitsFrom(LowBits);
3355     break;
3356   }
3357   case ISD::CTLZ:
3358   case ISD::CTLZ_ZERO_UNDEF: {
3359     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3360     // If we have a known 1, its position is our upper bound.
3361     unsigned PossibleLZ = Known2.countMaxLeadingZeros();
3362     unsigned LowBits = Log2_32(PossibleLZ) + 1;
3363     Known.Zero.setBitsFrom(LowBits);
3364     break;
3365   }
3366   case ISD::CTPOP: {
3367     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3368     // If we know some of the bits are zero, they can't be one.
3369     unsigned PossibleOnes = Known2.countMaxPopulation();
3370     Known.Zero.setBitsFrom(Log2_32(PossibleOnes) + 1);
3371     break;
3372   }
3373   case ISD::PARITY: {
3374     // Parity returns 0 everywhere but the LSB.
3375     Known.Zero.setBitsFrom(1);
3376     break;
3377   }
3378   case ISD::LOAD: {
3379     LoadSDNode *LD = cast<LoadSDNode>(Op);
3380     const Constant *Cst = TLI->getTargetConstantFromLoad(LD);
3381     if (ISD::isNON_EXTLoad(LD) && Cst) {
3382       // Determine any common known bits from the loaded constant pool value.
3383       Type *CstTy = Cst->getType();
3384       if ((NumElts * BitWidth) == CstTy->getPrimitiveSizeInBits()) {
3385         // If its a vector splat, then we can (quickly) reuse the scalar path.
3386         // NOTE: We assume all elements match and none are UNDEF.
3387         if (CstTy->isVectorTy()) {
3388           if (const Constant *Splat = Cst->getSplatValue()) {
3389             Cst = Splat;
3390             CstTy = Cst->getType();
3391           }
3392         }
3393         // TODO - do we need to handle different bitwidths?
3394         if (CstTy->isVectorTy() && BitWidth == CstTy->getScalarSizeInBits()) {
3395           // Iterate across all vector elements finding common known bits.
3396           Known.One.setAllBits();
3397           Known.Zero.setAllBits();
3398           for (unsigned i = 0; i != NumElts; ++i) {
3399             if (!DemandedElts[i])
3400               continue;
3401             if (Constant *Elt = Cst->getAggregateElement(i)) {
3402               if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
3403                 const APInt &Value = CInt->getValue();
3404                 Known.One &= Value;
3405                 Known.Zero &= ~Value;
3406                 continue;
3407               }
3408               if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
3409                 APInt Value = CFP->getValueAPF().bitcastToAPInt();
3410                 Known.One &= Value;
3411                 Known.Zero &= ~Value;
3412                 continue;
3413               }
3414             }
3415             Known.One.clearAllBits();
3416             Known.Zero.clearAllBits();
3417             break;
3418           }
3419         } else if (BitWidth == CstTy->getPrimitiveSizeInBits()) {
3420           if (auto *CInt = dyn_cast<ConstantInt>(Cst)) {
3421             Known = KnownBits::makeConstant(CInt->getValue());
3422           } else if (auto *CFP = dyn_cast<ConstantFP>(Cst)) {
3423             Known =
3424                 KnownBits::makeConstant(CFP->getValueAPF().bitcastToAPInt());
3425           }
3426         }
3427       }
3428     } else if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) {
3429       // If this is a ZEXTLoad and we are looking at the loaded value.
3430       EVT VT = LD->getMemoryVT();
3431       unsigned MemBits = VT.getScalarSizeInBits();
3432       Known.Zero.setBitsFrom(MemBits);
3433     } else if (const MDNode *Ranges = LD->getRanges()) {
3434       if (LD->getExtensionType() == ISD::NON_EXTLOAD)
3435         computeKnownBitsFromRangeMetadata(*Ranges, Known);
3436     }
3437     break;
3438   }
3439   case ISD::ZERO_EXTEND_VECTOR_INREG: {
3440     EVT InVT = Op.getOperand(0).getValueType();
3441     APInt InDemandedElts = DemandedElts.zext(InVT.getVectorNumElements());
3442     Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3443     Known = Known.zext(BitWidth);
3444     break;
3445   }
3446   case ISD::ZERO_EXTEND: {
3447     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3448     Known = Known.zext(BitWidth);
3449     break;
3450   }
3451   case ISD::SIGN_EXTEND_VECTOR_INREG: {
3452     EVT InVT = Op.getOperand(0).getValueType();
3453     APInt InDemandedElts = DemandedElts.zext(InVT.getVectorNumElements());
3454     Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3455     // If the sign bit is known to be zero or one, then sext will extend
3456     // it to the top bits, else it will just zext.
3457     Known = Known.sext(BitWidth);
3458     break;
3459   }
3460   case ISD::SIGN_EXTEND: {
3461     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3462     // If the sign bit is known to be zero or one, then sext will extend
3463     // it to the top bits, else it will just zext.
3464     Known = Known.sext(BitWidth);
3465     break;
3466   }
3467   case ISD::ANY_EXTEND_VECTOR_INREG: {
3468     EVT InVT = Op.getOperand(0).getValueType();
3469     APInt InDemandedElts = DemandedElts.zext(InVT.getVectorNumElements());
3470     Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3471     Known = Known.anyext(BitWidth);
3472     break;
3473   }
3474   case ISD::ANY_EXTEND: {
3475     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3476     Known = Known.anyext(BitWidth);
3477     break;
3478   }
3479   case ISD::TRUNCATE: {
3480     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3481     Known = Known.trunc(BitWidth);
3482     break;
3483   }
3484   case ISD::AssertZext: {
3485     EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3486     APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits());
3487     Known = computeKnownBits(Op.getOperand(0), Depth+1);
3488     Known.Zero |= (~InMask);
3489     Known.One  &= (~Known.Zero);
3490     break;
3491   }
3492   case ISD::AssertAlign: {
3493     unsigned LogOfAlign = Log2(cast<AssertAlignSDNode>(Op)->getAlign());
3494     assert(LogOfAlign != 0);
3495 
3496     // TODO: Should use maximum with source
3497     // If a node is guaranteed to be aligned, set low zero bits accordingly as
3498     // well as clearing one bits.
3499     Known.Zero.setLowBits(LogOfAlign);
3500     Known.One.clearLowBits(LogOfAlign);
3501     break;
3502   }
3503   case ISD::FGETSIGN:
3504     // All bits are zero except the low bit.
3505     Known.Zero.setBitsFrom(1);
3506     break;
3507   case ISD::USUBO:
3508   case ISD::SSUBO:
3509   case ISD::SUBCARRY:
3510   case ISD::SSUBO_CARRY:
3511     if (Op.getResNo() == 1) {
3512       // If we know the result of a setcc has the top bits zero, use this info.
3513       if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
3514               TargetLowering::ZeroOrOneBooleanContent &&
3515           BitWidth > 1)
3516         Known.Zero.setBitsFrom(1);
3517       break;
3518     }
3519     LLVM_FALLTHROUGH;
3520   case ISD::SUB:
3521   case ISD::SUBC: {
3522     assert(Op.getResNo() == 0 &&
3523            "We only compute knownbits for the difference here.");
3524 
3525     // TODO: Compute influence of the carry operand.
3526     if (Opcode == ISD::SUBCARRY || Opcode == ISD::SSUBO_CARRY)
3527       break;
3528 
3529     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3530     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3531     Known = KnownBits::computeForAddSub(/* Add */ false, /* NSW */ false,
3532                                         Known, Known2);
3533     break;
3534   }
3535   case ISD::UADDO:
3536   case ISD::SADDO:
3537   case ISD::ADDCARRY:
3538   case ISD::SADDO_CARRY:
3539     if (Op.getResNo() == 1) {
3540       // If we know the result of a setcc has the top bits zero, use this info.
3541       if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
3542               TargetLowering::ZeroOrOneBooleanContent &&
3543           BitWidth > 1)
3544         Known.Zero.setBitsFrom(1);
3545       break;
3546     }
3547     LLVM_FALLTHROUGH;
3548   case ISD::ADD:
3549   case ISD::ADDC:
3550   case ISD::ADDE: {
3551     assert(Op.getResNo() == 0 && "We only compute knownbits for the sum here.");
3552 
3553     // With ADDE and ADDCARRY, a carry bit may be added in.
3554     KnownBits Carry(1);
3555     if (Opcode == ISD::ADDE)
3556       // Can't track carry from glue, set carry to unknown.
3557       Carry.resetAll();
3558     else if (Opcode == ISD::ADDCARRY || Opcode == ISD::SADDO_CARRY)
3559       // TODO: Compute known bits for the carry operand. Not sure if it is worth
3560       // the trouble (how often will we find a known carry bit). And I haven't
3561       // tested this very much yet, but something like this might work:
3562       //   Carry = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1);
3563       //   Carry = Carry.zextOrTrunc(1, false);
3564       Carry.resetAll();
3565     else
3566       Carry.setAllZero();
3567 
3568     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3569     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3570     Known = KnownBits::computeForAddCarry(Known, Known2, Carry);
3571     break;
3572   }
3573   case ISD::SREM: {
3574     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3575     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3576     Known = KnownBits::srem(Known, Known2);
3577     break;
3578   }
3579   case ISD::UREM: {
3580     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3581     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3582     Known = KnownBits::urem(Known, Known2);
3583     break;
3584   }
3585   case ISD::EXTRACT_ELEMENT: {
3586     Known = computeKnownBits(Op.getOperand(0), Depth+1);
3587     const unsigned Index = Op.getConstantOperandVal(1);
3588     const unsigned EltBitWidth = Op.getValueSizeInBits();
3589 
3590     // Remove low part of known bits mask
3591     Known.Zero = Known.Zero.getHiBits(Known.getBitWidth() - Index * EltBitWidth);
3592     Known.One = Known.One.getHiBits(Known.getBitWidth() - Index * EltBitWidth);
3593 
3594     // Remove high part of known bit mask
3595     Known = Known.trunc(EltBitWidth);
3596     break;
3597   }
3598   case ISD::EXTRACT_VECTOR_ELT: {
3599     SDValue InVec = Op.getOperand(0);
3600     SDValue EltNo = Op.getOperand(1);
3601     EVT VecVT = InVec.getValueType();
3602     // computeKnownBits not yet implemented for scalable vectors.
3603     if (VecVT.isScalableVector())
3604       break;
3605     const unsigned EltBitWidth = VecVT.getScalarSizeInBits();
3606     const unsigned NumSrcElts = VecVT.getVectorNumElements();
3607 
3608     // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know
3609     // anything about the extended bits.
3610     if (BitWidth > EltBitWidth)
3611       Known = Known.trunc(EltBitWidth);
3612 
3613     // If we know the element index, just demand that vector element, else for
3614     // an unknown element index, ignore DemandedElts and demand them all.
3615     APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
3616     auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
3617     if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
3618       DemandedSrcElts =
3619           APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
3620 
3621     Known = computeKnownBits(InVec, DemandedSrcElts, Depth + 1);
3622     if (BitWidth > EltBitWidth)
3623       Known = Known.anyext(BitWidth);
3624     break;
3625   }
3626   case ISD::INSERT_VECTOR_ELT: {
3627     // If we know the element index, split the demand between the
3628     // source vector and the inserted element, otherwise assume we need
3629     // the original demanded vector elements and the value.
3630     SDValue InVec = Op.getOperand(0);
3631     SDValue InVal = Op.getOperand(1);
3632     SDValue EltNo = Op.getOperand(2);
3633     bool DemandedVal = true;
3634     APInt DemandedVecElts = DemandedElts;
3635     auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
3636     if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
3637       unsigned EltIdx = CEltNo->getZExtValue();
3638       DemandedVal = !!DemandedElts[EltIdx];
3639       DemandedVecElts.clearBit(EltIdx);
3640     }
3641     Known.One.setAllBits();
3642     Known.Zero.setAllBits();
3643     if (DemandedVal) {
3644       Known2 = computeKnownBits(InVal, Depth + 1);
3645       Known = KnownBits::commonBits(Known, Known2.zextOrTrunc(BitWidth));
3646     }
3647     if (!!DemandedVecElts) {
3648       Known2 = computeKnownBits(InVec, DemandedVecElts, Depth + 1);
3649       Known = KnownBits::commonBits(Known, Known2);
3650     }
3651     break;
3652   }
3653   case ISD::BITREVERSE: {
3654     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3655     Known = Known2.reverseBits();
3656     break;
3657   }
3658   case ISD::BSWAP: {
3659     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3660     Known = Known2.byteSwap();
3661     break;
3662   }
3663   case ISD::ABS: {
3664     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3665     Known = Known2.abs();
3666     break;
3667   }
3668   case ISD::USUBSAT: {
3669     // The result of usubsat will never be larger than the LHS.
3670     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3671     Known.Zero.setHighBits(Known2.countMinLeadingZeros());
3672     break;
3673   }
3674   case ISD::UMIN: {
3675     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3676     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3677     Known = KnownBits::umin(Known, Known2);
3678     break;
3679   }
3680   case ISD::UMAX: {
3681     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3682     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3683     Known = KnownBits::umax(Known, Known2);
3684     break;
3685   }
3686   case ISD::SMIN:
3687   case ISD::SMAX: {
3688     // If we have a clamp pattern, we know that the number of sign bits will be
3689     // the minimum of the clamp min/max range.
3690     bool IsMax = (Opcode == ISD::SMAX);
3691     ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
3692     if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
3693       if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
3694         CstHigh =
3695             isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
3696     if (CstLow && CstHigh) {
3697       if (!IsMax)
3698         std::swap(CstLow, CstHigh);
3699 
3700       const APInt &ValueLow = CstLow->getAPIntValue();
3701       const APInt &ValueHigh = CstHigh->getAPIntValue();
3702       if (ValueLow.sle(ValueHigh)) {
3703         unsigned LowSignBits = ValueLow.getNumSignBits();
3704         unsigned HighSignBits = ValueHigh.getNumSignBits();
3705         unsigned MinSignBits = std::min(LowSignBits, HighSignBits);
3706         if (ValueLow.isNegative() && ValueHigh.isNegative()) {
3707           Known.One.setHighBits(MinSignBits);
3708           break;
3709         }
3710         if (ValueLow.isNonNegative() && ValueHigh.isNonNegative()) {
3711           Known.Zero.setHighBits(MinSignBits);
3712           break;
3713         }
3714       }
3715     }
3716 
3717     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3718     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3719     if (IsMax)
3720       Known = KnownBits::smax(Known, Known2);
3721     else
3722       Known = KnownBits::smin(Known, Known2);
3723 
3724     // For SMAX, if CstLow is non-negative we know the result will be
3725     // non-negative and thus all sign bits are 0.
3726     // TODO: There's an equivalent of this for smin with negative constant for
3727     // known ones.
3728     if (IsMax && CstLow) {
3729       const APInt &ValueLow = CstLow->getAPIntValue();
3730       if (ValueLow.isNonNegative()) {
3731         unsigned SignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
3732         Known.Zero.setHighBits(std::min(SignBits, ValueLow.getNumSignBits()));
3733       }
3734     }
3735 
3736     break;
3737   }
3738   case ISD::FP_TO_UINT_SAT: {
3739     // FP_TO_UINT_SAT produces an unsigned value that fits in the saturating VT.
3740     EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3741     Known.Zero |= APInt::getBitsSetFrom(BitWidth, VT.getScalarSizeInBits());
3742     break;
3743   }
3744   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
3745     if (Op.getResNo() == 1) {
3746       // The boolean result conforms to getBooleanContents.
3747       // If we know the result of a setcc has the top bits zero, use this info.
3748       // We know that we have an integer-based boolean since these operations
3749       // are only available for integer.
3750       if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
3751               TargetLowering::ZeroOrOneBooleanContent &&
3752           BitWidth > 1)
3753         Known.Zero.setBitsFrom(1);
3754       break;
3755     }
3756     LLVM_FALLTHROUGH;
3757   case ISD::ATOMIC_CMP_SWAP:
3758   case ISD::ATOMIC_SWAP:
3759   case ISD::ATOMIC_LOAD_ADD:
3760   case ISD::ATOMIC_LOAD_SUB:
3761   case ISD::ATOMIC_LOAD_AND:
3762   case ISD::ATOMIC_LOAD_CLR:
3763   case ISD::ATOMIC_LOAD_OR:
3764   case ISD::ATOMIC_LOAD_XOR:
3765   case ISD::ATOMIC_LOAD_NAND:
3766   case ISD::ATOMIC_LOAD_MIN:
3767   case ISD::ATOMIC_LOAD_MAX:
3768   case ISD::ATOMIC_LOAD_UMIN:
3769   case ISD::ATOMIC_LOAD_UMAX:
3770   case ISD::ATOMIC_LOAD: {
3771     unsigned MemBits =
3772         cast<AtomicSDNode>(Op)->getMemoryVT().getScalarSizeInBits();
3773     // If we are looking at the loaded value.
3774     if (Op.getResNo() == 0) {
3775       if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND)
3776         Known.Zero.setBitsFrom(MemBits);
3777     }
3778     break;
3779   }
3780   case ISD::FrameIndex:
3781   case ISD::TargetFrameIndex:
3782     TLI->computeKnownBitsForFrameIndex(cast<FrameIndexSDNode>(Op)->getIndex(),
3783                                        Known, getMachineFunction());
3784     break;
3785 
3786   default:
3787     if (Opcode < ISD::BUILTIN_OP_END)
3788       break;
3789     LLVM_FALLTHROUGH;
3790   case ISD::INTRINSIC_WO_CHAIN:
3791   case ISD::INTRINSIC_W_CHAIN:
3792   case ISD::INTRINSIC_VOID:
3793     // Allow the target to implement this method for its nodes.
3794     TLI->computeKnownBitsForTargetNode(Op, Known, DemandedElts, *this, Depth);
3795     break;
3796   }
3797 
3798   assert(!Known.hasConflict() && "Bits known to be one AND zero?");
3799   return Known;
3800 }
3801 
3802 SelectionDAG::OverflowKind SelectionDAG::computeOverflowKind(SDValue N0,
3803                                                              SDValue N1) const {
3804   // X + 0 never overflow
3805   if (isNullConstant(N1))
3806     return OFK_Never;
3807 
3808   KnownBits N1Known = computeKnownBits(N1);
3809   if (N1Known.Zero.getBoolValue()) {
3810     KnownBits N0Known = computeKnownBits(N0);
3811 
3812     bool overflow;
3813     (void)N0Known.getMaxValue().uadd_ov(N1Known.getMaxValue(), overflow);
3814     if (!overflow)
3815       return OFK_Never;
3816   }
3817 
3818   // mulhi + 1 never overflow
3819   if (N0.getOpcode() == ISD::UMUL_LOHI && N0.getResNo() == 1 &&
3820       (N1Known.getMaxValue() & 0x01) == N1Known.getMaxValue())
3821     return OFK_Never;
3822 
3823   if (N1.getOpcode() == ISD::UMUL_LOHI && N1.getResNo() == 1) {
3824     KnownBits N0Known = computeKnownBits(N0);
3825 
3826     if ((N0Known.getMaxValue() & 0x01) == N0Known.getMaxValue())
3827       return OFK_Never;
3828   }
3829 
3830   return OFK_Sometime;
3831 }
3832 
3833 bool SelectionDAG::isKnownToBeAPowerOfTwo(SDValue Val) const {
3834   EVT OpVT = Val.getValueType();
3835   unsigned BitWidth = OpVT.getScalarSizeInBits();
3836 
3837   // Is the constant a known power of 2?
3838   if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Val))
3839     return Const->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
3840 
3841   // A left-shift of a constant one will have exactly one bit set because
3842   // shifting the bit off the end is undefined.
3843   if (Val.getOpcode() == ISD::SHL) {
3844     auto *C = isConstOrConstSplat(Val.getOperand(0));
3845     if (C && C->getAPIntValue() == 1)
3846       return true;
3847   }
3848 
3849   // Similarly, a logical right-shift of a constant sign-bit will have exactly
3850   // one bit set.
3851   if (Val.getOpcode() == ISD::SRL) {
3852     auto *C = isConstOrConstSplat(Val.getOperand(0));
3853     if (C && C->getAPIntValue().isSignMask())
3854       return true;
3855   }
3856 
3857   // Are all operands of a build vector constant powers of two?
3858   if (Val.getOpcode() == ISD::BUILD_VECTOR)
3859     if (llvm::all_of(Val->ops(), [BitWidth](SDValue E) {
3860           if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(E))
3861             return C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
3862           return false;
3863         }))
3864       return true;
3865 
3866   // Is the operand of a splat vector a constant power of two?
3867   if (Val.getOpcode() == ISD::SPLAT_VECTOR)
3868     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val->getOperand(0)))
3869       if (C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2())
3870         return true;
3871 
3872   // vscale(power-of-two) is a power-of-two for some targets
3873   if (Val.getOpcode() == ISD::VSCALE &&
3874       getTargetLoweringInfo().isVScaleKnownToBeAPowerOfTwo() &&
3875       isKnownToBeAPowerOfTwo(Val.getOperand(0)))
3876     return true;
3877 
3878   // More could be done here, though the above checks are enough
3879   // to handle some common cases.
3880 
3881   // Fall back to computeKnownBits to catch other known cases.
3882   KnownBits Known = computeKnownBits(Val);
3883   return (Known.countMaxPopulation() == 1) && (Known.countMinPopulation() == 1);
3884 }
3885 
3886 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const {
3887   EVT VT = Op.getValueType();
3888 
3889   // TODO: Assume we don't know anything for now.
3890   if (VT.isScalableVector())
3891     return 1;
3892 
3893   APInt DemandedElts = VT.isVector()
3894                            ? APInt::getAllOnes(VT.getVectorNumElements())
3895                            : APInt(1, 1);
3896   return ComputeNumSignBits(Op, DemandedElts, Depth);
3897 }
3898 
3899 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, const APInt &DemandedElts,
3900                                           unsigned Depth) const {
3901   EVT VT = Op.getValueType();
3902   assert((VT.isInteger() || VT.isFloatingPoint()) && "Invalid VT!");
3903   unsigned VTBits = VT.getScalarSizeInBits();
3904   unsigned NumElts = DemandedElts.getBitWidth();
3905   unsigned Tmp, Tmp2;
3906   unsigned FirstAnswer = 1;
3907 
3908   if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
3909     const APInt &Val = C->getAPIntValue();
3910     return Val.getNumSignBits();
3911   }
3912 
3913   if (Depth >= MaxRecursionDepth)
3914     return 1;  // Limit search depth.
3915 
3916   if (!DemandedElts || VT.isScalableVector())
3917     return 1;  // No demanded elts, better to assume we don't know anything.
3918 
3919   unsigned Opcode = Op.getOpcode();
3920   switch (Opcode) {
3921   default: break;
3922   case ISD::AssertSext:
3923     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
3924     return VTBits-Tmp+1;
3925   case ISD::AssertZext:
3926     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
3927     return VTBits-Tmp;
3928 
3929   case ISD::BUILD_VECTOR:
3930     Tmp = VTBits;
3931     for (unsigned i = 0, e = Op.getNumOperands(); (i < e) && (Tmp > 1); ++i) {
3932       if (!DemandedElts[i])
3933         continue;
3934 
3935       SDValue SrcOp = Op.getOperand(i);
3936       Tmp2 = ComputeNumSignBits(SrcOp, Depth + 1);
3937 
3938       // BUILD_VECTOR can implicitly truncate sources, we must handle this.
3939       if (SrcOp.getValueSizeInBits() != VTBits) {
3940         assert(SrcOp.getValueSizeInBits() > VTBits &&
3941                "Expected BUILD_VECTOR implicit truncation");
3942         unsigned ExtraBits = SrcOp.getValueSizeInBits() - VTBits;
3943         Tmp2 = (Tmp2 > ExtraBits ? Tmp2 - ExtraBits : 1);
3944       }
3945       Tmp = std::min(Tmp, Tmp2);
3946     }
3947     return Tmp;
3948 
3949   case ISD::VECTOR_SHUFFLE: {
3950     // Collect the minimum number of sign bits that are shared by every vector
3951     // element referenced by the shuffle.
3952     APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
3953     const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
3954     assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
3955     for (unsigned i = 0; i != NumElts; ++i) {
3956       int M = SVN->getMaskElt(i);
3957       if (!DemandedElts[i])
3958         continue;
3959       // For UNDEF elements, we don't know anything about the common state of
3960       // the shuffle result.
3961       if (M < 0)
3962         return 1;
3963       if ((unsigned)M < NumElts)
3964         DemandedLHS.setBit((unsigned)M % NumElts);
3965       else
3966         DemandedRHS.setBit((unsigned)M % NumElts);
3967     }
3968     Tmp = std::numeric_limits<unsigned>::max();
3969     if (!!DemandedLHS)
3970       Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedLHS, Depth + 1);
3971     if (!!DemandedRHS) {
3972       Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedRHS, Depth + 1);
3973       Tmp = std::min(Tmp, Tmp2);
3974     }
3975     // If we don't know anything, early out and try computeKnownBits fall-back.
3976     if (Tmp == 1)
3977       break;
3978     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
3979     return Tmp;
3980   }
3981 
3982   case ISD::BITCAST: {
3983     SDValue N0 = Op.getOperand(0);
3984     EVT SrcVT = N0.getValueType();
3985     unsigned SrcBits = SrcVT.getScalarSizeInBits();
3986 
3987     // Ignore bitcasts from unsupported types..
3988     if (!(SrcVT.isInteger() || SrcVT.isFloatingPoint()))
3989       break;
3990 
3991     // Fast handling of 'identity' bitcasts.
3992     if (VTBits == SrcBits)
3993       return ComputeNumSignBits(N0, DemandedElts, Depth + 1);
3994 
3995     bool IsLE = getDataLayout().isLittleEndian();
3996 
3997     // Bitcast 'large element' scalar/vector to 'small element' vector.
3998     if ((SrcBits % VTBits) == 0) {
3999       assert(VT.isVector() && "Expected bitcast to vector");
4000 
4001       unsigned Scale = SrcBits / VTBits;
4002       APInt SrcDemandedElts =
4003           APIntOps::ScaleBitMask(DemandedElts, NumElts / Scale);
4004 
4005       // Fast case - sign splat can be simply split across the small elements.
4006       Tmp = ComputeNumSignBits(N0, SrcDemandedElts, Depth + 1);
4007       if (Tmp == SrcBits)
4008         return VTBits;
4009 
4010       // Slow case - determine how far the sign extends into each sub-element.
4011       Tmp2 = VTBits;
4012       for (unsigned i = 0; i != NumElts; ++i)
4013         if (DemandedElts[i]) {
4014           unsigned SubOffset = i % Scale;
4015           SubOffset = (IsLE ? ((Scale - 1) - SubOffset) : SubOffset);
4016           SubOffset = SubOffset * VTBits;
4017           if (Tmp <= SubOffset)
4018             return 1;
4019           Tmp2 = std::min(Tmp2, Tmp - SubOffset);
4020         }
4021       return Tmp2;
4022     }
4023     break;
4024   }
4025 
4026   case ISD::FP_TO_SINT_SAT:
4027     // FP_TO_SINT_SAT produces a signed value that fits in the saturating VT.
4028     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
4029     return VTBits - Tmp + 1;
4030   case ISD::SIGN_EXTEND:
4031     Tmp = VTBits - Op.getOperand(0).getScalarValueSizeInBits();
4032     return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1) + Tmp;
4033   case ISD::SIGN_EXTEND_INREG:
4034     // Max of the input and what this extends.
4035     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
4036     Tmp = VTBits-Tmp+1;
4037     Tmp2 = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
4038     return std::max(Tmp, Tmp2);
4039   case ISD::SIGN_EXTEND_VECTOR_INREG: {
4040     SDValue Src = Op.getOperand(0);
4041     EVT SrcVT = Src.getValueType();
4042     APInt DemandedSrcElts = DemandedElts.zext(SrcVT.getVectorNumElements());
4043     Tmp = VTBits - SrcVT.getScalarSizeInBits();
4044     return ComputeNumSignBits(Src, DemandedSrcElts, Depth+1) + Tmp;
4045   }
4046   case ISD::SRA:
4047     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4048     // SRA X, C -> adds C sign bits.
4049     if (const APInt *ShAmt =
4050             getValidMinimumShiftAmountConstant(Op, DemandedElts))
4051       Tmp = std::min<uint64_t>(Tmp + ShAmt->getZExtValue(), VTBits);
4052     return Tmp;
4053   case ISD::SHL:
4054     if (const APInt *ShAmt =
4055             getValidMaximumShiftAmountConstant(Op, DemandedElts)) {
4056       // shl destroys sign bits, ensure it doesn't shift out all sign bits.
4057       Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4058       if (ShAmt->ult(Tmp))
4059         return Tmp - ShAmt->getZExtValue();
4060     }
4061     break;
4062   case ISD::AND:
4063   case ISD::OR:
4064   case ISD::XOR:    // NOT is handled here.
4065     // Logical binary ops preserve the number of sign bits at the worst.
4066     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
4067     if (Tmp != 1) {
4068       Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
4069       FirstAnswer = std::min(Tmp, Tmp2);
4070       // We computed what we know about the sign bits as our first
4071       // answer. Now proceed to the generic code that uses
4072       // computeKnownBits, and pick whichever answer is better.
4073     }
4074     break;
4075 
4076   case ISD::SELECT:
4077   case ISD::VSELECT:
4078     Tmp = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
4079     if (Tmp == 1) return 1;  // Early out.
4080     Tmp2 = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
4081     return std::min(Tmp, Tmp2);
4082   case ISD::SELECT_CC:
4083     Tmp = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
4084     if (Tmp == 1) return 1;  // Early out.
4085     Tmp2 = ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth+1);
4086     return std::min(Tmp, Tmp2);
4087 
4088   case ISD::SMIN:
4089   case ISD::SMAX: {
4090     // If we have a clamp pattern, we know that the number of sign bits will be
4091     // the minimum of the clamp min/max range.
4092     bool IsMax = (Opcode == ISD::SMAX);
4093     ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
4094     if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
4095       if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
4096         CstHigh =
4097             isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
4098     if (CstLow && CstHigh) {
4099       if (!IsMax)
4100         std::swap(CstLow, CstHigh);
4101       if (CstLow->getAPIntValue().sle(CstHigh->getAPIntValue())) {
4102         Tmp = CstLow->getAPIntValue().getNumSignBits();
4103         Tmp2 = CstHigh->getAPIntValue().getNumSignBits();
4104         return std::min(Tmp, Tmp2);
4105       }
4106     }
4107 
4108     // Fallback - just get the minimum number of sign bits of the operands.
4109     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4110     if (Tmp == 1)
4111       return 1;  // Early out.
4112     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
4113     return std::min(Tmp, Tmp2);
4114   }
4115   case ISD::UMIN:
4116   case ISD::UMAX:
4117     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4118     if (Tmp == 1)
4119       return 1;  // Early out.
4120     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
4121     return std::min(Tmp, Tmp2);
4122   case ISD::SADDO:
4123   case ISD::UADDO:
4124   case ISD::SADDO_CARRY:
4125   case ISD::ADDCARRY:
4126   case ISD::SSUBO:
4127   case ISD::USUBO:
4128   case ISD::SSUBO_CARRY:
4129   case ISD::SUBCARRY:
4130   case ISD::SMULO:
4131   case ISD::UMULO:
4132     if (Op.getResNo() != 1)
4133       break;
4134     // The boolean result conforms to getBooleanContents.  Fall through.
4135     // If setcc returns 0/-1, all bits are sign bits.
4136     // We know that we have an integer-based boolean since these operations
4137     // are only available for integer.
4138     if (TLI->getBooleanContents(VT.isVector(), false) ==
4139         TargetLowering::ZeroOrNegativeOneBooleanContent)
4140       return VTBits;
4141     break;
4142   case ISD::SETCC:
4143   case ISD::SETCCCARRY:
4144   case ISD::STRICT_FSETCC:
4145   case ISD::STRICT_FSETCCS: {
4146     unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
4147     // If setcc returns 0/-1, all bits are sign bits.
4148     if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
4149         TargetLowering::ZeroOrNegativeOneBooleanContent)
4150       return VTBits;
4151     break;
4152   }
4153   case ISD::ROTL:
4154   case ISD::ROTR:
4155     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4156 
4157     // If we're rotating an 0/-1 value, then it stays an 0/-1 value.
4158     if (Tmp == VTBits)
4159       return VTBits;
4160 
4161     if (ConstantSDNode *C =
4162             isConstOrConstSplat(Op.getOperand(1), DemandedElts)) {
4163       unsigned RotAmt = C->getAPIntValue().urem(VTBits);
4164 
4165       // Handle rotate right by N like a rotate left by 32-N.
4166       if (Opcode == ISD::ROTR)
4167         RotAmt = (VTBits - RotAmt) % VTBits;
4168 
4169       // If we aren't rotating out all of the known-in sign bits, return the
4170       // number that are left.  This handles rotl(sext(x), 1) for example.
4171       if (Tmp > (RotAmt + 1)) return (Tmp - RotAmt);
4172     }
4173     break;
4174   case ISD::ADD:
4175   case ISD::ADDC:
4176     // Add can have at most one carry bit.  Thus we know that the output
4177     // is, at worst, one more bit than the inputs.
4178     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4179     if (Tmp == 1) return 1; // Early out.
4180 
4181     // Special case decrementing a value (ADD X, -1):
4182     if (ConstantSDNode *CRHS =
4183             isConstOrConstSplat(Op.getOperand(1), DemandedElts))
4184       if (CRHS->isAllOnes()) {
4185         KnownBits Known =
4186             computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4187 
4188         // If the input is known to be 0 or 1, the output is 0/-1, which is all
4189         // sign bits set.
4190         if ((Known.Zero | 1).isAllOnes())
4191           return VTBits;
4192 
4193         // If we are subtracting one from a positive number, there is no carry
4194         // out of the result.
4195         if (Known.isNonNegative())
4196           return Tmp;
4197       }
4198 
4199     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
4200     if (Tmp2 == 1) return 1; // Early out.
4201     return std::min(Tmp, Tmp2) - 1;
4202   case ISD::SUB:
4203     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
4204     if (Tmp2 == 1) return 1; // Early out.
4205 
4206     // Handle NEG.
4207     if (ConstantSDNode *CLHS =
4208             isConstOrConstSplat(Op.getOperand(0), DemandedElts))
4209       if (CLHS->isZero()) {
4210         KnownBits Known =
4211             computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4212         // If the input is known to be 0 or 1, the output is 0/-1, which is all
4213         // sign bits set.
4214         if ((Known.Zero | 1).isAllOnes())
4215           return VTBits;
4216 
4217         // If the input is known to be positive (the sign bit is known clear),
4218         // the output of the NEG has the same number of sign bits as the input.
4219         if (Known.isNonNegative())
4220           return Tmp2;
4221 
4222         // Otherwise, we treat this like a SUB.
4223       }
4224 
4225     // Sub can have at most one carry bit.  Thus we know that the output
4226     // is, at worst, one more bit than the inputs.
4227     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4228     if (Tmp == 1) return 1; // Early out.
4229     return std::min(Tmp, Tmp2) - 1;
4230   case ISD::MUL: {
4231     // The output of the Mul can be at most twice the valid bits in the inputs.
4232     unsigned SignBitsOp0 = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
4233     if (SignBitsOp0 == 1)
4234       break;
4235     unsigned SignBitsOp1 = ComputeNumSignBits(Op.getOperand(1), Depth + 1);
4236     if (SignBitsOp1 == 1)
4237       break;
4238     unsigned OutValidBits =
4239         (VTBits - SignBitsOp0 + 1) + (VTBits - SignBitsOp1 + 1);
4240     return OutValidBits > VTBits ? 1 : VTBits - OutValidBits + 1;
4241   }
4242   case ISD::SREM:
4243     // The sign bit is the LHS's sign bit, except when the result of the
4244     // remainder is zero. The magnitude of the result should be less than or
4245     // equal to the magnitude of the LHS. Therefore, the result should have
4246     // at least as many sign bits as the left hand side.
4247     return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4248   case ISD::TRUNCATE: {
4249     // Check if the sign bits of source go down as far as the truncated value.
4250     unsigned NumSrcBits = Op.getOperand(0).getScalarValueSizeInBits();
4251     unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
4252     if (NumSrcSignBits > (NumSrcBits - VTBits))
4253       return NumSrcSignBits - (NumSrcBits - VTBits);
4254     break;
4255   }
4256   case ISD::EXTRACT_ELEMENT: {
4257     const int KnownSign = ComputeNumSignBits(Op.getOperand(0), Depth+1);
4258     const int BitWidth = Op.getValueSizeInBits();
4259     const int Items = Op.getOperand(0).getValueSizeInBits() / BitWidth;
4260 
4261     // Get reverse index (starting from 1), Op1 value indexes elements from
4262     // little end. Sign starts at big end.
4263     const int rIndex = Items - 1 - Op.getConstantOperandVal(1);
4264 
4265     // If the sign portion ends in our element the subtraction gives correct
4266     // result. Otherwise it gives either negative or > bitwidth result
4267     return std::max(std::min(KnownSign - rIndex * BitWidth, BitWidth), 0);
4268   }
4269   case ISD::INSERT_VECTOR_ELT: {
4270     // If we know the element index, split the demand between the
4271     // source vector and the inserted element, otherwise assume we need
4272     // the original demanded vector elements and the value.
4273     SDValue InVec = Op.getOperand(0);
4274     SDValue InVal = Op.getOperand(1);
4275     SDValue EltNo = Op.getOperand(2);
4276     bool DemandedVal = true;
4277     APInt DemandedVecElts = DemandedElts;
4278     auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
4279     if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
4280       unsigned EltIdx = CEltNo->getZExtValue();
4281       DemandedVal = !!DemandedElts[EltIdx];
4282       DemandedVecElts.clearBit(EltIdx);
4283     }
4284     Tmp = std::numeric_limits<unsigned>::max();
4285     if (DemandedVal) {
4286       // TODO - handle implicit truncation of inserted elements.
4287       if (InVal.getScalarValueSizeInBits() != VTBits)
4288         break;
4289       Tmp2 = ComputeNumSignBits(InVal, Depth + 1);
4290       Tmp = std::min(Tmp, Tmp2);
4291     }
4292     if (!!DemandedVecElts) {
4293       Tmp2 = ComputeNumSignBits(InVec, DemandedVecElts, Depth + 1);
4294       Tmp = std::min(Tmp, Tmp2);
4295     }
4296     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
4297     return Tmp;
4298   }
4299   case ISD::EXTRACT_VECTOR_ELT: {
4300     SDValue InVec = Op.getOperand(0);
4301     SDValue EltNo = Op.getOperand(1);
4302     EVT VecVT = InVec.getValueType();
4303     // ComputeNumSignBits not yet implemented for scalable vectors.
4304     if (VecVT.isScalableVector())
4305       break;
4306     const unsigned BitWidth = Op.getValueSizeInBits();
4307     const unsigned EltBitWidth = Op.getOperand(0).getScalarValueSizeInBits();
4308     const unsigned NumSrcElts = VecVT.getVectorNumElements();
4309 
4310     // If BitWidth > EltBitWidth the value is anyext:ed, and we do not know
4311     // anything about sign bits. But if the sizes match we can derive knowledge
4312     // about sign bits from the vector operand.
4313     if (BitWidth != EltBitWidth)
4314       break;
4315 
4316     // If we know the element index, just demand that vector element, else for
4317     // an unknown element index, ignore DemandedElts and demand them all.
4318     APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
4319     auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
4320     if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
4321       DemandedSrcElts =
4322           APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
4323 
4324     return ComputeNumSignBits(InVec, DemandedSrcElts, Depth + 1);
4325   }
4326   case ISD::EXTRACT_SUBVECTOR: {
4327     // Offset the demanded elts by the subvector index.
4328     SDValue Src = Op.getOperand(0);
4329     // Bail until we can represent demanded elements for scalable vectors.
4330     if (Src.getValueType().isScalableVector())
4331       break;
4332     uint64_t Idx = Op.getConstantOperandVal(1);
4333     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
4334     APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
4335     return ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
4336   }
4337   case ISD::CONCAT_VECTORS: {
4338     // Determine the minimum number of sign bits across all demanded
4339     // elts of the input vectors. Early out if the result is already 1.
4340     Tmp = std::numeric_limits<unsigned>::max();
4341     EVT SubVectorVT = Op.getOperand(0).getValueType();
4342     unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
4343     unsigned NumSubVectors = Op.getNumOperands();
4344     for (unsigned i = 0; (i < NumSubVectors) && (Tmp > 1); ++i) {
4345       APInt DemandedSub =
4346           DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts);
4347       if (!DemandedSub)
4348         continue;
4349       Tmp2 = ComputeNumSignBits(Op.getOperand(i), DemandedSub, Depth + 1);
4350       Tmp = std::min(Tmp, Tmp2);
4351     }
4352     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
4353     return Tmp;
4354   }
4355   case ISD::INSERT_SUBVECTOR: {
4356     // Demand any elements from the subvector and the remainder from the src its
4357     // inserted into.
4358     SDValue Src = Op.getOperand(0);
4359     SDValue Sub = Op.getOperand(1);
4360     uint64_t Idx = Op.getConstantOperandVal(2);
4361     unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
4362     APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
4363     APInt DemandedSrcElts = DemandedElts;
4364     DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx);
4365 
4366     Tmp = std::numeric_limits<unsigned>::max();
4367     if (!!DemandedSubElts) {
4368       Tmp = ComputeNumSignBits(Sub, DemandedSubElts, Depth + 1);
4369       if (Tmp == 1)
4370         return 1; // early-out
4371     }
4372     if (!!DemandedSrcElts) {
4373       Tmp2 = ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
4374       Tmp = std::min(Tmp, Tmp2);
4375     }
4376     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
4377     return Tmp;
4378   }
4379   case ISD::ATOMIC_CMP_SWAP:
4380   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
4381   case ISD::ATOMIC_SWAP:
4382   case ISD::ATOMIC_LOAD_ADD:
4383   case ISD::ATOMIC_LOAD_SUB:
4384   case ISD::ATOMIC_LOAD_AND:
4385   case ISD::ATOMIC_LOAD_CLR:
4386   case ISD::ATOMIC_LOAD_OR:
4387   case ISD::ATOMIC_LOAD_XOR:
4388   case ISD::ATOMIC_LOAD_NAND:
4389   case ISD::ATOMIC_LOAD_MIN:
4390   case ISD::ATOMIC_LOAD_MAX:
4391   case ISD::ATOMIC_LOAD_UMIN:
4392   case ISD::ATOMIC_LOAD_UMAX:
4393   case ISD::ATOMIC_LOAD: {
4394     Tmp = cast<AtomicSDNode>(Op)->getMemoryVT().getScalarSizeInBits();
4395     // If we are looking at the loaded value.
4396     if (Op.getResNo() == 0) {
4397       if (Tmp == VTBits)
4398         return 1; // early-out
4399       if (TLI->getExtendForAtomicOps() == ISD::SIGN_EXTEND)
4400         return VTBits - Tmp + 1;
4401       if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND)
4402         return VTBits - Tmp;
4403     }
4404     break;
4405   }
4406   }
4407 
4408   // If we are looking at the loaded value of the SDNode.
4409   if (Op.getResNo() == 0) {
4410     // Handle LOADX separately here. EXTLOAD case will fallthrough.
4411     if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
4412       unsigned ExtType = LD->getExtensionType();
4413       switch (ExtType) {
4414       default: break;
4415       case ISD::SEXTLOAD: // e.g. i16->i32 = '17' bits known.
4416         Tmp = LD->getMemoryVT().getScalarSizeInBits();
4417         return VTBits - Tmp + 1;
4418       case ISD::ZEXTLOAD: // e.g. i16->i32 = '16' bits known.
4419         Tmp = LD->getMemoryVT().getScalarSizeInBits();
4420         return VTBits - Tmp;
4421       case ISD::NON_EXTLOAD:
4422         if (const Constant *Cst = TLI->getTargetConstantFromLoad(LD)) {
4423           // We only need to handle vectors - computeKnownBits should handle
4424           // scalar cases.
4425           Type *CstTy = Cst->getType();
4426           if (CstTy->isVectorTy() &&
4427               (NumElts * VTBits) == CstTy->getPrimitiveSizeInBits() &&
4428               VTBits == CstTy->getScalarSizeInBits()) {
4429             Tmp = VTBits;
4430             for (unsigned i = 0; i != NumElts; ++i) {
4431               if (!DemandedElts[i])
4432                 continue;
4433               if (Constant *Elt = Cst->getAggregateElement(i)) {
4434                 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
4435                   const APInt &Value = CInt->getValue();
4436                   Tmp = std::min(Tmp, Value.getNumSignBits());
4437                   continue;
4438                 }
4439                 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
4440                   APInt Value = CFP->getValueAPF().bitcastToAPInt();
4441                   Tmp = std::min(Tmp, Value.getNumSignBits());
4442                   continue;
4443                 }
4444               }
4445               // Unknown type. Conservatively assume no bits match sign bit.
4446               return 1;
4447             }
4448             return Tmp;
4449           }
4450         }
4451         break;
4452       }
4453     }
4454   }
4455 
4456   // Allow the target to implement this method for its nodes.
4457   if (Opcode >= ISD::BUILTIN_OP_END ||
4458       Opcode == ISD::INTRINSIC_WO_CHAIN ||
4459       Opcode == ISD::INTRINSIC_W_CHAIN ||
4460       Opcode == ISD::INTRINSIC_VOID) {
4461     unsigned NumBits =
4462         TLI->ComputeNumSignBitsForTargetNode(Op, DemandedElts, *this, Depth);
4463     if (NumBits > 1)
4464       FirstAnswer = std::max(FirstAnswer, NumBits);
4465   }
4466 
4467   // Finally, if we can prove that the top bits of the result are 0's or 1's,
4468   // use this information.
4469   KnownBits Known = computeKnownBits(Op, DemandedElts, Depth);
4470   return std::max(FirstAnswer, Known.countMinSignBits());
4471 }
4472 
4473 unsigned SelectionDAG::ComputeMaxSignificantBits(SDValue Op,
4474                                                  unsigned Depth) const {
4475   unsigned SignBits = ComputeNumSignBits(Op, Depth);
4476   return Op.getScalarValueSizeInBits() - SignBits + 1;
4477 }
4478 
4479 unsigned SelectionDAG::ComputeMaxSignificantBits(SDValue Op,
4480                                                  const APInt &DemandedElts,
4481                                                  unsigned Depth) const {
4482   unsigned SignBits = ComputeNumSignBits(Op, DemandedElts, Depth);
4483   return Op.getScalarValueSizeInBits() - SignBits + 1;
4484 }
4485 
4486 bool SelectionDAG::isGuaranteedNotToBeUndefOrPoison(SDValue Op, bool PoisonOnly,
4487                                                     unsigned Depth) const {
4488   // Early out for FREEZE.
4489   if (Op.getOpcode() == ISD::FREEZE)
4490     return true;
4491 
4492   // TODO: Assume we don't know anything for now.
4493   EVT VT = Op.getValueType();
4494   if (VT.isScalableVector())
4495     return false;
4496 
4497   APInt DemandedElts = VT.isVector()
4498                            ? APInt::getAllOnes(VT.getVectorNumElements())
4499                            : APInt(1, 1);
4500   return isGuaranteedNotToBeUndefOrPoison(Op, DemandedElts, PoisonOnly, Depth);
4501 }
4502 
4503 bool SelectionDAG::isGuaranteedNotToBeUndefOrPoison(SDValue Op,
4504                                                     const APInt &DemandedElts,
4505                                                     bool PoisonOnly,
4506                                                     unsigned Depth) const {
4507   unsigned Opcode = Op.getOpcode();
4508 
4509   // Early out for FREEZE.
4510   if (Opcode == ISD::FREEZE)
4511     return true;
4512 
4513   if (Depth >= MaxRecursionDepth)
4514     return false; // Limit search depth.
4515 
4516   if (isIntOrFPConstant(Op))
4517     return true;
4518 
4519   switch (Opcode) {
4520   case ISD::UNDEF:
4521     return PoisonOnly;
4522 
4523   case ISD::BUILD_VECTOR:
4524     // NOTE: BUILD_VECTOR has implicit truncation of wider scalar elements -
4525     // this shouldn't affect the result.
4526     for (unsigned i = 0, e = Op.getNumOperands(); i < e; ++i) {
4527       if (!DemandedElts[i])
4528         continue;
4529       if (!isGuaranteedNotToBeUndefOrPoison(Op.getOperand(i), PoisonOnly,
4530                                             Depth + 1))
4531         return false;
4532     }
4533     return true;
4534 
4535   // TODO: Search for noundef attributes from library functions.
4536 
4537   // TODO: Pointers dereferenced by ISD::LOAD/STORE ops are noundef.
4538 
4539   default:
4540     // Allow the target to implement this method for its nodes.
4541     if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
4542         Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID)
4543       return TLI->isGuaranteedNotToBeUndefOrPoisonForTargetNode(
4544           Op, DemandedElts, *this, PoisonOnly, Depth);
4545     break;
4546   }
4547 
4548   return false;
4549 }
4550 
4551 bool SelectionDAG::isBaseWithConstantOffset(SDValue Op) const {
4552   if ((Op.getOpcode() != ISD::ADD && Op.getOpcode() != ISD::OR) ||
4553       !isa<ConstantSDNode>(Op.getOperand(1)))
4554     return false;
4555 
4556   if (Op.getOpcode() == ISD::OR &&
4557       !MaskedValueIsZero(Op.getOperand(0), Op.getConstantOperandAPInt(1)))
4558     return false;
4559 
4560   return true;
4561 }
4562 
4563 bool SelectionDAG::isKnownNeverNaN(SDValue Op, bool SNaN, unsigned Depth) const {
4564   // If we're told that NaNs won't happen, assume they won't.
4565   if (getTarget().Options.NoNaNsFPMath || Op->getFlags().hasNoNaNs())
4566     return true;
4567 
4568   if (Depth >= MaxRecursionDepth)
4569     return false; // Limit search depth.
4570 
4571   // TODO: Handle vectors.
4572   // If the value is a constant, we can obviously see if it is a NaN or not.
4573   if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) {
4574     return !C->getValueAPF().isNaN() ||
4575            (SNaN && !C->getValueAPF().isSignaling());
4576   }
4577 
4578   unsigned Opcode = Op.getOpcode();
4579   switch (Opcode) {
4580   case ISD::FADD:
4581   case ISD::FSUB:
4582   case ISD::FMUL:
4583   case ISD::FDIV:
4584   case ISD::FREM:
4585   case ISD::FSIN:
4586   case ISD::FCOS: {
4587     if (SNaN)
4588       return true;
4589     // TODO: Need isKnownNeverInfinity
4590     return false;
4591   }
4592   case ISD::FCANONICALIZE:
4593   case ISD::FEXP:
4594   case ISD::FEXP2:
4595   case ISD::FTRUNC:
4596   case ISD::FFLOOR:
4597   case ISD::FCEIL:
4598   case ISD::FROUND:
4599   case ISD::FROUNDEVEN:
4600   case ISD::FRINT:
4601   case ISD::FNEARBYINT: {
4602     if (SNaN)
4603       return true;
4604     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4605   }
4606   case ISD::FABS:
4607   case ISD::FNEG:
4608   case ISD::FCOPYSIGN: {
4609     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4610   }
4611   case ISD::SELECT:
4612     return isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) &&
4613            isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1);
4614   case ISD::FP_EXTEND:
4615   case ISD::FP_ROUND: {
4616     if (SNaN)
4617       return true;
4618     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4619   }
4620   case ISD::SINT_TO_FP:
4621   case ISD::UINT_TO_FP:
4622     return true;
4623   case ISD::FMA:
4624   case ISD::FMAD: {
4625     if (SNaN)
4626       return true;
4627     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) &&
4628            isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) &&
4629            isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1);
4630   }
4631   case ISD::FSQRT: // Need is known positive
4632   case ISD::FLOG:
4633   case ISD::FLOG2:
4634   case ISD::FLOG10:
4635   case ISD::FPOWI:
4636   case ISD::FPOW: {
4637     if (SNaN)
4638       return true;
4639     // TODO: Refine on operand
4640     return false;
4641   }
4642   case ISD::FMINNUM:
4643   case ISD::FMAXNUM: {
4644     // Only one needs to be known not-nan, since it will be returned if the
4645     // other ends up being one.
4646     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) ||
4647            isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1);
4648   }
4649   case ISD::FMINNUM_IEEE:
4650   case ISD::FMAXNUM_IEEE: {
4651     if (SNaN)
4652       return true;
4653     // This can return a NaN if either operand is an sNaN, or if both operands
4654     // are NaN.
4655     return (isKnownNeverNaN(Op.getOperand(0), false, Depth + 1) &&
4656             isKnownNeverSNaN(Op.getOperand(1), Depth + 1)) ||
4657            (isKnownNeverNaN(Op.getOperand(1), false, Depth + 1) &&
4658             isKnownNeverSNaN(Op.getOperand(0), Depth + 1));
4659   }
4660   case ISD::FMINIMUM:
4661   case ISD::FMAXIMUM: {
4662     // TODO: Does this quiet or return the origina NaN as-is?
4663     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) &&
4664            isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1);
4665   }
4666   case ISD::EXTRACT_VECTOR_ELT: {
4667     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4668   }
4669   default:
4670     if (Opcode >= ISD::BUILTIN_OP_END ||
4671         Opcode == ISD::INTRINSIC_WO_CHAIN ||
4672         Opcode == ISD::INTRINSIC_W_CHAIN ||
4673         Opcode == ISD::INTRINSIC_VOID) {
4674       return TLI->isKnownNeverNaNForTargetNode(Op, *this, SNaN, Depth);
4675     }
4676 
4677     return false;
4678   }
4679 }
4680 
4681 bool SelectionDAG::isKnownNeverZeroFloat(SDValue Op) const {
4682   assert(Op.getValueType().isFloatingPoint() &&
4683          "Floating point type expected");
4684 
4685   // If the value is a constant, we can obviously see if it is a zero or not.
4686   // TODO: Add BuildVector support.
4687   if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
4688     return !C->isZero();
4689   return false;
4690 }
4691 
4692 bool SelectionDAG::isKnownNeverZero(SDValue Op) const {
4693   assert(!Op.getValueType().isFloatingPoint() &&
4694          "Floating point types unsupported - use isKnownNeverZeroFloat");
4695 
4696   // If the value is a constant, we can obviously see if it is a zero or not.
4697   if (ISD::matchUnaryPredicate(Op,
4698                                [](ConstantSDNode *C) { return !C->isZero(); }))
4699     return true;
4700 
4701   // TODO: Recognize more cases here.
4702   switch (Op.getOpcode()) {
4703   default: break;
4704   case ISD::OR:
4705     if (isKnownNeverZero(Op.getOperand(1)) ||
4706         isKnownNeverZero(Op.getOperand(0)))
4707       return true;
4708     break;
4709   }
4710 
4711   return false;
4712 }
4713 
4714 bool SelectionDAG::isEqualTo(SDValue A, SDValue B) const {
4715   // Check the obvious case.
4716   if (A == B) return true;
4717 
4718   // For for negative and positive zero.
4719   if (const ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A))
4720     if (const ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B))
4721       if (CA->isZero() && CB->isZero()) return true;
4722 
4723   // Otherwise they may not be equal.
4724   return false;
4725 }
4726 
4727 // Only bits set in Mask must be negated, other bits may be arbitrary.
4728 SDValue llvm::getBitwiseNotOperand(SDValue V, SDValue Mask, bool AllowUndefs) {
4729   if (isBitwiseNot(V, AllowUndefs))
4730     return V.getOperand(0);
4731 
4732   // Handle any_extend (not (truncate X)) pattern, where Mask only sets
4733   // bits in the non-extended part.
4734   ConstantSDNode *MaskC = isConstOrConstSplat(Mask);
4735   if (!MaskC || V.getOpcode() != ISD::ANY_EXTEND)
4736     return SDValue();
4737   SDValue ExtArg = V.getOperand(0);
4738   if (ExtArg.getScalarValueSizeInBits() >=
4739           MaskC->getAPIntValue().getActiveBits() &&
4740       isBitwiseNot(ExtArg, AllowUndefs) &&
4741       ExtArg.getOperand(0).getOpcode() == ISD::TRUNCATE &&
4742       ExtArg.getOperand(0).getOperand(0).getValueType() == V.getValueType())
4743     return ExtArg.getOperand(0).getOperand(0);
4744   return SDValue();
4745 }
4746 
4747 static bool haveNoCommonBitsSetCommutative(SDValue A, SDValue B) {
4748   // Match masked merge pattern (X & ~M) op (Y & M)
4749   // Including degenerate case (X & ~M) op M
4750   auto MatchNoCommonBitsPattern = [&](SDValue Not, SDValue Mask,
4751                                       SDValue Other) {
4752     if (SDValue NotOperand =
4753             getBitwiseNotOperand(Not, Mask, /* AllowUndefs */ true)) {
4754       if (Other == NotOperand)
4755         return true;
4756       if (Other->getOpcode() == ISD::AND)
4757         return NotOperand == Other->getOperand(0) ||
4758                NotOperand == Other->getOperand(1);
4759     }
4760     return false;
4761   };
4762   if (A->getOpcode() == ISD::AND)
4763     return MatchNoCommonBitsPattern(A->getOperand(0), A->getOperand(1), B) ||
4764            MatchNoCommonBitsPattern(A->getOperand(1), A->getOperand(0), B);
4765   return false;
4766 }
4767 
4768 // FIXME: unify with llvm::haveNoCommonBitsSet.
4769 bool SelectionDAG::haveNoCommonBitsSet(SDValue A, SDValue B) const {
4770   assert(A.getValueType() == B.getValueType() &&
4771          "Values must have the same type");
4772   if (haveNoCommonBitsSetCommutative(A, B) ||
4773       haveNoCommonBitsSetCommutative(B, A))
4774     return true;
4775   return KnownBits::haveNoCommonBitsSet(computeKnownBits(A),
4776                                         computeKnownBits(B));
4777 }
4778 
4779 static SDValue FoldSTEP_VECTOR(const SDLoc &DL, EVT VT, SDValue Step,
4780                                SelectionDAG &DAG) {
4781   if (cast<ConstantSDNode>(Step)->isZero())
4782     return DAG.getConstant(0, DL, VT);
4783 
4784   return SDValue();
4785 }
4786 
4787 static SDValue FoldBUILD_VECTOR(const SDLoc &DL, EVT VT,
4788                                 ArrayRef<SDValue> Ops,
4789                                 SelectionDAG &DAG) {
4790   int NumOps = Ops.size();
4791   assert(NumOps != 0 && "Can't build an empty vector!");
4792   assert(!VT.isScalableVector() &&
4793          "BUILD_VECTOR cannot be used with scalable types");
4794   assert(VT.getVectorNumElements() == (unsigned)NumOps &&
4795          "Incorrect element count in BUILD_VECTOR!");
4796 
4797   // BUILD_VECTOR of UNDEFs is UNDEF.
4798   if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
4799     return DAG.getUNDEF(VT);
4800 
4801   // BUILD_VECTOR of seq extract/insert from the same vector + type is Identity.
4802   SDValue IdentitySrc;
4803   bool IsIdentity = true;
4804   for (int i = 0; i != NumOps; ++i) {
4805     if (Ops[i].getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4806         Ops[i].getOperand(0).getValueType() != VT ||
4807         (IdentitySrc && Ops[i].getOperand(0) != IdentitySrc) ||
4808         !isa<ConstantSDNode>(Ops[i].getOperand(1)) ||
4809         cast<ConstantSDNode>(Ops[i].getOperand(1))->getAPIntValue() != i) {
4810       IsIdentity = false;
4811       break;
4812     }
4813     IdentitySrc = Ops[i].getOperand(0);
4814   }
4815   if (IsIdentity)
4816     return IdentitySrc;
4817 
4818   return SDValue();
4819 }
4820 
4821 /// Try to simplify vector concatenation to an input value, undef, or build
4822 /// vector.
4823 static SDValue foldCONCAT_VECTORS(const SDLoc &DL, EVT VT,
4824                                   ArrayRef<SDValue> Ops,
4825                                   SelectionDAG &DAG) {
4826   assert(!Ops.empty() && "Can't concatenate an empty list of vectors!");
4827   assert(llvm::all_of(Ops,
4828                       [Ops](SDValue Op) {
4829                         return Ops[0].getValueType() == Op.getValueType();
4830                       }) &&
4831          "Concatenation of vectors with inconsistent value types!");
4832   assert((Ops[0].getValueType().getVectorElementCount() * Ops.size()) ==
4833              VT.getVectorElementCount() &&
4834          "Incorrect element count in vector concatenation!");
4835 
4836   if (Ops.size() == 1)
4837     return Ops[0];
4838 
4839   // Concat of UNDEFs is UNDEF.
4840   if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
4841     return DAG.getUNDEF(VT);
4842 
4843   // Scan the operands and look for extract operations from a single source
4844   // that correspond to insertion at the same location via this concatenation:
4845   // concat (extract X, 0*subvec_elts), (extract X, 1*subvec_elts), ...
4846   SDValue IdentitySrc;
4847   bool IsIdentity = true;
4848   for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
4849     SDValue Op = Ops[i];
4850     unsigned IdentityIndex = i * Op.getValueType().getVectorMinNumElements();
4851     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
4852         Op.getOperand(0).getValueType() != VT ||
4853         (IdentitySrc && Op.getOperand(0) != IdentitySrc) ||
4854         Op.getConstantOperandVal(1) != IdentityIndex) {
4855       IsIdentity = false;
4856       break;
4857     }
4858     assert((!IdentitySrc || IdentitySrc == Op.getOperand(0)) &&
4859            "Unexpected identity source vector for concat of extracts");
4860     IdentitySrc = Op.getOperand(0);
4861   }
4862   if (IsIdentity) {
4863     assert(IdentitySrc && "Failed to set source vector of extracts");
4864     return IdentitySrc;
4865   }
4866 
4867   // The code below this point is only designed to work for fixed width
4868   // vectors, so we bail out for now.
4869   if (VT.isScalableVector())
4870     return SDValue();
4871 
4872   // A CONCAT_VECTOR with all UNDEF/BUILD_VECTOR operands can be
4873   // simplified to one big BUILD_VECTOR.
4874   // FIXME: Add support for SCALAR_TO_VECTOR as well.
4875   EVT SVT = VT.getScalarType();
4876   SmallVector<SDValue, 16> Elts;
4877   for (SDValue Op : Ops) {
4878     EVT OpVT = Op.getValueType();
4879     if (Op.isUndef())
4880       Elts.append(OpVT.getVectorNumElements(), DAG.getUNDEF(SVT));
4881     else if (Op.getOpcode() == ISD::BUILD_VECTOR)
4882       Elts.append(Op->op_begin(), Op->op_end());
4883     else
4884       return SDValue();
4885   }
4886 
4887   // BUILD_VECTOR requires all inputs to be of the same type, find the
4888   // maximum type and extend them all.
4889   for (SDValue Op : Elts)
4890     SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
4891 
4892   if (SVT.bitsGT(VT.getScalarType())) {
4893     for (SDValue &Op : Elts) {
4894       if (Op.isUndef())
4895         Op = DAG.getUNDEF(SVT);
4896       else
4897         Op = DAG.getTargetLoweringInfo().isZExtFree(Op.getValueType(), SVT)
4898                  ? DAG.getZExtOrTrunc(Op, DL, SVT)
4899                  : DAG.getSExtOrTrunc(Op, DL, SVT);
4900     }
4901   }
4902 
4903   SDValue V = DAG.getBuildVector(VT, DL, Elts);
4904   NewSDValueDbgMsg(V, "New node fold concat vectors: ", &DAG);
4905   return V;
4906 }
4907 
4908 /// Gets or creates the specified node.
4909 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT) {
4910   FoldingSetNodeID ID;
4911   AddNodeIDNode(ID, Opcode, getVTList(VT), None);
4912   void *IP = nullptr;
4913   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
4914     return SDValue(E, 0);
4915 
4916   auto *N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(),
4917                               getVTList(VT));
4918   CSEMap.InsertNode(N, IP);
4919 
4920   InsertNode(N);
4921   SDValue V = SDValue(N, 0);
4922   NewSDValueDbgMsg(V, "Creating new node: ", this);
4923   return V;
4924 }
4925 
4926 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4927                               SDValue Operand) {
4928   SDNodeFlags Flags;
4929   if (Inserter)
4930     Flags = Inserter->getFlags();
4931   return getNode(Opcode, DL, VT, Operand, Flags);
4932 }
4933 
4934 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4935                               SDValue Operand, const SDNodeFlags Flags) {
4936   assert(Operand.getOpcode() != ISD::DELETED_NODE &&
4937          "Operand is DELETED_NODE!");
4938   // Constant fold unary operations with an integer constant operand. Even
4939   // opaque constant will be folded, because the folding of unary operations
4940   // doesn't create new constants with different values. Nevertheless, the
4941   // opaque flag is preserved during folding to prevent future folding with
4942   // other constants.
4943   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand)) {
4944     const APInt &Val = C->getAPIntValue();
4945     switch (Opcode) {
4946     default: break;
4947     case ISD::SIGN_EXTEND:
4948       return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
4949                          C->isTargetOpcode(), C->isOpaque());
4950     case ISD::TRUNCATE:
4951       if (C->isOpaque())
4952         break;
4953       LLVM_FALLTHROUGH;
4954     case ISD::ZERO_EXTEND:
4955       return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
4956                          C->isTargetOpcode(), C->isOpaque());
4957     case ISD::ANY_EXTEND:
4958       // Some targets like RISCV prefer to sign extend some types.
4959       if (TLI->isSExtCheaperThanZExt(Operand.getValueType(), VT))
4960         return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
4961                            C->isTargetOpcode(), C->isOpaque());
4962       return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
4963                          C->isTargetOpcode(), C->isOpaque());
4964     case ISD::UINT_TO_FP:
4965     case ISD::SINT_TO_FP: {
4966       APFloat apf(EVTToAPFloatSemantics(VT),
4967                   APInt::getZero(VT.getSizeInBits()));
4968       (void)apf.convertFromAPInt(Val,
4969                                  Opcode==ISD::SINT_TO_FP,
4970                                  APFloat::rmNearestTiesToEven);
4971       return getConstantFP(apf, DL, VT);
4972     }
4973     case ISD::BITCAST:
4974       if (VT == MVT::f16 && C->getValueType(0) == MVT::i16)
4975         return getConstantFP(APFloat(APFloat::IEEEhalf(), Val), DL, VT);
4976       if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
4977         return getConstantFP(APFloat(APFloat::IEEEsingle(), Val), DL, VT);
4978       if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
4979         return getConstantFP(APFloat(APFloat::IEEEdouble(), Val), DL, VT);
4980       if (VT == MVT::f128 && C->getValueType(0) == MVT::i128)
4981         return getConstantFP(APFloat(APFloat::IEEEquad(), Val), DL, VT);
4982       break;
4983     case ISD::ABS:
4984       return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(),
4985                          C->isOpaque());
4986     case ISD::BITREVERSE:
4987       return getConstant(Val.reverseBits(), DL, VT, C->isTargetOpcode(),
4988                          C->isOpaque());
4989     case ISD::BSWAP:
4990       return getConstant(Val.byteSwap(), DL, VT, C->isTargetOpcode(),
4991                          C->isOpaque());
4992     case ISD::CTPOP:
4993       return getConstant(Val.countPopulation(), DL, VT, C->isTargetOpcode(),
4994                          C->isOpaque());
4995     case ISD::CTLZ:
4996     case ISD::CTLZ_ZERO_UNDEF:
4997       return getConstant(Val.countLeadingZeros(), DL, VT, C->isTargetOpcode(),
4998                          C->isOpaque());
4999     case ISD::CTTZ:
5000     case ISD::CTTZ_ZERO_UNDEF:
5001       return getConstant(Val.countTrailingZeros(), DL, VT, C->isTargetOpcode(),
5002                          C->isOpaque());
5003     case ISD::FP16_TO_FP:
5004     case ISD::BF16_TO_FP: {
5005       bool Ignored;
5006       APFloat FPV(Opcode == ISD::FP16_TO_FP ? APFloat::IEEEhalf()
5007                                             : APFloat::BFloat(),
5008                   (Val.getBitWidth() == 16) ? Val : Val.trunc(16));
5009 
5010       // This can return overflow, underflow, or inexact; we don't care.
5011       // FIXME need to be more flexible about rounding mode.
5012       (void)FPV.convert(EVTToAPFloatSemantics(VT),
5013                         APFloat::rmNearestTiesToEven, &Ignored);
5014       return getConstantFP(FPV, DL, VT);
5015     }
5016     case ISD::STEP_VECTOR: {
5017       if (SDValue V = FoldSTEP_VECTOR(DL, VT, Operand, *this))
5018         return V;
5019       break;
5020     }
5021     }
5022   }
5023 
5024   // Constant fold unary operations with a floating point constant operand.
5025   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand)) {
5026     APFloat V = C->getValueAPF();    // make copy
5027     switch (Opcode) {
5028     case ISD::FNEG:
5029       V.changeSign();
5030       return getConstantFP(V, DL, VT);
5031     case ISD::FABS:
5032       V.clearSign();
5033       return getConstantFP(V, DL, VT);
5034     case ISD::FCEIL: {
5035       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardPositive);
5036       if (fs == APFloat::opOK || fs == APFloat::opInexact)
5037         return getConstantFP(V, DL, VT);
5038       break;
5039     }
5040     case ISD::FTRUNC: {
5041       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardZero);
5042       if (fs == APFloat::opOK || fs == APFloat::opInexact)
5043         return getConstantFP(V, DL, VT);
5044       break;
5045     }
5046     case ISD::FFLOOR: {
5047       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardNegative);
5048       if (fs == APFloat::opOK || fs == APFloat::opInexact)
5049         return getConstantFP(V, DL, VT);
5050       break;
5051     }
5052     case ISD::FP_EXTEND: {
5053       bool ignored;
5054       // This can return overflow, underflow, or inexact; we don't care.
5055       // FIXME need to be more flexible about rounding mode.
5056       (void)V.convert(EVTToAPFloatSemantics(VT),
5057                       APFloat::rmNearestTiesToEven, &ignored);
5058       return getConstantFP(V, DL, VT);
5059     }
5060     case ISD::FP_TO_SINT:
5061     case ISD::FP_TO_UINT: {
5062       bool ignored;
5063       APSInt IntVal(VT.getSizeInBits(), Opcode == ISD::FP_TO_UINT);
5064       // FIXME need to be more flexible about rounding mode.
5065       APFloat::opStatus s =
5066           V.convertToInteger(IntVal, APFloat::rmTowardZero, &ignored);
5067       if (s == APFloat::opInvalidOp) // inexact is OK, in fact usual
5068         break;
5069       return getConstant(IntVal, DL, VT);
5070     }
5071     case ISD::BITCAST:
5072       if (VT == MVT::i16 && C->getValueType(0) == MVT::f16)
5073         return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
5074       if (VT == MVT::i16 && C->getValueType(0) == MVT::bf16)
5075         return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
5076       if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
5077         return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
5078       if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
5079         return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
5080       break;
5081     case ISD::FP_TO_FP16:
5082     case ISD::FP_TO_BF16: {
5083       bool Ignored;
5084       // This can return overflow, underflow, or inexact; we don't care.
5085       // FIXME need to be more flexible about rounding mode.
5086       (void)V.convert(Opcode == ISD::FP_TO_FP16 ? APFloat::IEEEhalf()
5087                                                 : APFloat::BFloat(),
5088                       APFloat::rmNearestTiesToEven, &Ignored);
5089       return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
5090     }
5091     }
5092   }
5093 
5094   // Constant fold unary operations with a vector integer or float operand.
5095   switch (Opcode) {
5096   default:
5097     // FIXME: Entirely reasonable to perform folding of other unary
5098     // operations here as the need arises.
5099     break;
5100   case ISD::FNEG:
5101   case ISD::FABS:
5102   case ISD::FCEIL:
5103   case ISD::FTRUNC:
5104   case ISD::FFLOOR:
5105   case ISD::FP_EXTEND:
5106   case ISD::FP_TO_SINT:
5107   case ISD::FP_TO_UINT:
5108   case ISD::TRUNCATE:
5109   case ISD::ANY_EXTEND:
5110   case ISD::ZERO_EXTEND:
5111   case ISD::SIGN_EXTEND:
5112   case ISD::UINT_TO_FP:
5113   case ISD::SINT_TO_FP:
5114   case ISD::ABS:
5115   case ISD::BITREVERSE:
5116   case ISD::BSWAP:
5117   case ISD::CTLZ:
5118   case ISD::CTLZ_ZERO_UNDEF:
5119   case ISD::CTTZ:
5120   case ISD::CTTZ_ZERO_UNDEF:
5121   case ISD::CTPOP: {
5122     SDValue Ops = {Operand};
5123     if (SDValue Fold = FoldConstantArithmetic(Opcode, DL, VT, Ops))
5124       return Fold;
5125   }
5126   }
5127 
5128   unsigned OpOpcode = Operand.getNode()->getOpcode();
5129   switch (Opcode) {
5130   case ISD::STEP_VECTOR:
5131     assert(VT.isScalableVector() &&
5132            "STEP_VECTOR can only be used with scalable types");
5133     assert(OpOpcode == ISD::TargetConstant &&
5134            VT.getVectorElementType() == Operand.getValueType() &&
5135            "Unexpected step operand");
5136     break;
5137   case ISD::FREEZE:
5138     assert(VT == Operand.getValueType() && "Unexpected VT!");
5139     if (isGuaranteedNotToBeUndefOrPoison(Operand))
5140       return Operand;
5141     break;
5142   case ISD::TokenFactor:
5143   case ISD::MERGE_VALUES:
5144   case ISD::CONCAT_VECTORS:
5145     return Operand;         // Factor, merge or concat of one node?  No need.
5146   case ISD::BUILD_VECTOR: {
5147     // Attempt to simplify BUILD_VECTOR.
5148     SDValue Ops[] = {Operand};
5149     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
5150       return V;
5151     break;
5152   }
5153   case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node");
5154   case ISD::FP_EXTEND:
5155     assert(VT.isFloatingPoint() &&
5156            Operand.getValueType().isFloatingPoint() && "Invalid FP cast!");
5157     if (Operand.getValueType() == VT) return Operand;  // noop conversion.
5158     assert((!VT.isVector() ||
5159             VT.getVectorElementCount() ==
5160             Operand.getValueType().getVectorElementCount()) &&
5161            "Vector element count mismatch!");
5162     assert(Operand.getValueType().bitsLT(VT) &&
5163            "Invalid fpext node, dst < src!");
5164     if (Operand.isUndef())
5165       return getUNDEF(VT);
5166     break;
5167   case ISD::FP_TO_SINT:
5168   case ISD::FP_TO_UINT:
5169     if (Operand.isUndef())
5170       return getUNDEF(VT);
5171     break;
5172   case ISD::SINT_TO_FP:
5173   case ISD::UINT_TO_FP:
5174     // [us]itofp(undef) = 0, because the result value is bounded.
5175     if (Operand.isUndef())
5176       return getConstantFP(0.0, DL, VT);
5177     break;
5178   case ISD::SIGN_EXTEND:
5179     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
5180            "Invalid SIGN_EXTEND!");
5181     assert(VT.isVector() == Operand.getValueType().isVector() &&
5182            "SIGN_EXTEND result type type should be vector iff the operand "
5183            "type is vector!");
5184     if (Operand.getValueType() == VT) return Operand;   // noop extension
5185     assert((!VT.isVector() ||
5186             VT.getVectorElementCount() ==
5187                 Operand.getValueType().getVectorElementCount()) &&
5188            "Vector element count mismatch!");
5189     assert(Operand.getValueType().bitsLT(VT) &&
5190            "Invalid sext node, dst < src!");
5191     if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
5192       return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
5193     if (OpOpcode == ISD::UNDEF)
5194       // sext(undef) = 0, because the top bits will all be the same.
5195       return getConstant(0, DL, VT);
5196     break;
5197   case ISD::ZERO_EXTEND:
5198     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
5199            "Invalid ZERO_EXTEND!");
5200     assert(VT.isVector() == Operand.getValueType().isVector() &&
5201            "ZERO_EXTEND result type type should be vector iff the operand "
5202            "type is vector!");
5203     if (Operand.getValueType() == VT) return Operand;   // noop extension
5204     assert((!VT.isVector() ||
5205             VT.getVectorElementCount() ==
5206                 Operand.getValueType().getVectorElementCount()) &&
5207            "Vector element count mismatch!");
5208     assert(Operand.getValueType().bitsLT(VT) &&
5209            "Invalid zext node, dst < src!");
5210     if (OpOpcode == ISD::ZERO_EXTEND)   // (zext (zext x)) -> (zext x)
5211       return getNode(ISD::ZERO_EXTEND, DL, VT, Operand.getOperand(0));
5212     if (OpOpcode == ISD::UNDEF)
5213       // zext(undef) = 0, because the top bits will be zero.
5214       return getConstant(0, DL, VT);
5215     break;
5216   case ISD::ANY_EXTEND:
5217     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
5218            "Invalid ANY_EXTEND!");
5219     assert(VT.isVector() == Operand.getValueType().isVector() &&
5220            "ANY_EXTEND result type type should be vector iff the operand "
5221            "type is vector!");
5222     if (Operand.getValueType() == VT) return Operand;   // noop extension
5223     assert((!VT.isVector() ||
5224             VT.getVectorElementCount() ==
5225                 Operand.getValueType().getVectorElementCount()) &&
5226            "Vector element count mismatch!");
5227     assert(Operand.getValueType().bitsLT(VT) &&
5228            "Invalid anyext node, dst < src!");
5229 
5230     if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
5231         OpOpcode == ISD::ANY_EXTEND)
5232       // (ext (zext x)) -> (zext x)  and  (ext (sext x)) -> (sext x)
5233       return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
5234     if (OpOpcode == ISD::UNDEF)
5235       return getUNDEF(VT);
5236 
5237     // (ext (trunc x)) -> x
5238     if (OpOpcode == ISD::TRUNCATE) {
5239       SDValue OpOp = Operand.getOperand(0);
5240       if (OpOp.getValueType() == VT) {
5241         transferDbgValues(Operand, OpOp);
5242         return OpOp;
5243       }
5244     }
5245     break;
5246   case ISD::TRUNCATE:
5247     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
5248            "Invalid TRUNCATE!");
5249     assert(VT.isVector() == Operand.getValueType().isVector() &&
5250            "TRUNCATE result type type should be vector iff the operand "
5251            "type is vector!");
5252     if (Operand.getValueType() == VT) return Operand;   // noop truncate
5253     assert((!VT.isVector() ||
5254             VT.getVectorElementCount() ==
5255                 Operand.getValueType().getVectorElementCount()) &&
5256            "Vector element count mismatch!");
5257     assert(Operand.getValueType().bitsGT(VT) &&
5258            "Invalid truncate node, src < dst!");
5259     if (OpOpcode == ISD::TRUNCATE)
5260       return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0));
5261     if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
5262         OpOpcode == ISD::ANY_EXTEND) {
5263       // If the source is smaller than the dest, we still need an extend.
5264       if (Operand.getOperand(0).getValueType().getScalarType()
5265             .bitsLT(VT.getScalarType()))
5266         return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
5267       if (Operand.getOperand(0).getValueType().bitsGT(VT))
5268         return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0));
5269       return Operand.getOperand(0);
5270     }
5271     if (OpOpcode == ISD::UNDEF)
5272       return getUNDEF(VT);
5273     if (OpOpcode == ISD::VSCALE && !NewNodesMustHaveLegalTypes)
5274       return getVScale(DL, VT, Operand.getConstantOperandAPInt(0));
5275     break;
5276   case ISD::ANY_EXTEND_VECTOR_INREG:
5277   case ISD::ZERO_EXTEND_VECTOR_INREG:
5278   case ISD::SIGN_EXTEND_VECTOR_INREG:
5279     assert(VT.isVector() && "This DAG node is restricted to vector types.");
5280     assert(Operand.getValueType().bitsLE(VT) &&
5281            "The input must be the same size or smaller than the result.");
5282     assert(VT.getVectorMinNumElements() <
5283                Operand.getValueType().getVectorMinNumElements() &&
5284            "The destination vector type must have fewer lanes than the input.");
5285     break;
5286   case ISD::ABS:
5287     assert(VT.isInteger() && VT == Operand.getValueType() &&
5288            "Invalid ABS!");
5289     if (OpOpcode == ISD::UNDEF)
5290       return getConstant(0, DL, VT);
5291     break;
5292   case ISD::BSWAP:
5293     assert(VT.isInteger() && VT == Operand.getValueType() &&
5294            "Invalid BSWAP!");
5295     assert((VT.getScalarSizeInBits() % 16 == 0) &&
5296            "BSWAP types must be a multiple of 16 bits!");
5297     if (OpOpcode == ISD::UNDEF)
5298       return getUNDEF(VT);
5299     // bswap(bswap(X)) -> X.
5300     if (OpOpcode == ISD::BSWAP)
5301       return Operand.getOperand(0);
5302     break;
5303   case ISD::BITREVERSE:
5304     assert(VT.isInteger() && VT == Operand.getValueType() &&
5305            "Invalid BITREVERSE!");
5306     if (OpOpcode == ISD::UNDEF)
5307       return getUNDEF(VT);
5308     break;
5309   case ISD::BITCAST:
5310     assert(VT.getSizeInBits() == Operand.getValueSizeInBits() &&
5311            "Cannot BITCAST between types of different sizes!");
5312     if (VT == Operand.getValueType()) return Operand;  // noop conversion.
5313     if (OpOpcode == ISD::BITCAST)  // bitconv(bitconv(x)) -> bitconv(x)
5314       return getNode(ISD::BITCAST, DL, VT, Operand.getOperand(0));
5315     if (OpOpcode == ISD::UNDEF)
5316       return getUNDEF(VT);
5317     break;
5318   case ISD::SCALAR_TO_VECTOR:
5319     assert(VT.isVector() && !Operand.getValueType().isVector() &&
5320            (VT.getVectorElementType() == Operand.getValueType() ||
5321             (VT.getVectorElementType().isInteger() &&
5322              Operand.getValueType().isInteger() &&
5323              VT.getVectorElementType().bitsLE(Operand.getValueType()))) &&
5324            "Illegal SCALAR_TO_VECTOR node!");
5325     if (OpOpcode == ISD::UNDEF)
5326       return getUNDEF(VT);
5327     // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
5328     if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
5329         isa<ConstantSDNode>(Operand.getOperand(1)) &&
5330         Operand.getConstantOperandVal(1) == 0 &&
5331         Operand.getOperand(0).getValueType() == VT)
5332       return Operand.getOperand(0);
5333     break;
5334   case ISD::FNEG:
5335     // Negation of an unknown bag of bits is still completely undefined.
5336     if (OpOpcode == ISD::UNDEF)
5337       return getUNDEF(VT);
5338 
5339     if (OpOpcode == ISD::FNEG)  // --X -> X
5340       return Operand.getOperand(0);
5341     break;
5342   case ISD::FABS:
5343     if (OpOpcode == ISD::FNEG)  // abs(-X) -> abs(X)
5344       return getNode(ISD::FABS, DL, VT, Operand.getOperand(0));
5345     break;
5346   case ISD::VSCALE:
5347     assert(VT == Operand.getValueType() && "Unexpected VT!");
5348     break;
5349   case ISD::CTPOP:
5350     if (Operand.getValueType().getScalarType() == MVT::i1)
5351       return Operand;
5352     break;
5353   case ISD::CTLZ:
5354   case ISD::CTTZ:
5355     if (Operand.getValueType().getScalarType() == MVT::i1)
5356       return getNOT(DL, Operand, Operand.getValueType());
5357     break;
5358   case ISD::VECREDUCE_ADD:
5359     if (Operand.getValueType().getScalarType() == MVT::i1)
5360       return getNode(ISD::VECREDUCE_XOR, DL, VT, Operand);
5361     break;
5362   case ISD::VECREDUCE_SMIN:
5363   case ISD::VECREDUCE_UMAX:
5364     if (Operand.getValueType().getScalarType() == MVT::i1)
5365       return getNode(ISD::VECREDUCE_OR, DL, VT, Operand);
5366     break;
5367   case ISD::VECREDUCE_SMAX:
5368   case ISD::VECREDUCE_UMIN:
5369     if (Operand.getValueType().getScalarType() == MVT::i1)
5370       return getNode(ISD::VECREDUCE_AND, DL, VT, Operand);
5371     break;
5372   }
5373 
5374   SDNode *N;
5375   SDVTList VTs = getVTList(VT);
5376   SDValue Ops[] = {Operand};
5377   if (VT != MVT::Glue) { // Don't CSE flag producing nodes
5378     FoldingSetNodeID ID;
5379     AddNodeIDNode(ID, Opcode, VTs, Ops);
5380     void *IP = nullptr;
5381     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
5382       E->intersectFlagsWith(Flags);
5383       return SDValue(E, 0);
5384     }
5385 
5386     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5387     N->setFlags(Flags);
5388     createOperands(N, Ops);
5389     CSEMap.InsertNode(N, IP);
5390   } else {
5391     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5392     createOperands(N, Ops);
5393   }
5394 
5395   InsertNode(N);
5396   SDValue V = SDValue(N, 0);
5397   NewSDValueDbgMsg(V, "Creating new node: ", this);
5398   return V;
5399 }
5400 
5401 static llvm::Optional<APInt> FoldValue(unsigned Opcode, const APInt &C1,
5402                                        const APInt &C2) {
5403   switch (Opcode) {
5404   case ISD::ADD:  return C1 + C2;
5405   case ISD::SUB:  return C1 - C2;
5406   case ISD::MUL:  return C1 * C2;
5407   case ISD::AND:  return C1 & C2;
5408   case ISD::OR:   return C1 | C2;
5409   case ISD::XOR:  return C1 ^ C2;
5410   case ISD::SHL:  return C1 << C2;
5411   case ISD::SRL:  return C1.lshr(C2);
5412   case ISD::SRA:  return C1.ashr(C2);
5413   case ISD::ROTL: return C1.rotl(C2);
5414   case ISD::ROTR: return C1.rotr(C2);
5415   case ISD::SMIN: return C1.sle(C2) ? C1 : C2;
5416   case ISD::SMAX: return C1.sge(C2) ? C1 : C2;
5417   case ISD::UMIN: return C1.ule(C2) ? C1 : C2;
5418   case ISD::UMAX: return C1.uge(C2) ? C1 : C2;
5419   case ISD::SADDSAT: return C1.sadd_sat(C2);
5420   case ISD::UADDSAT: return C1.uadd_sat(C2);
5421   case ISD::SSUBSAT: return C1.ssub_sat(C2);
5422   case ISD::USUBSAT: return C1.usub_sat(C2);
5423   case ISD::SSHLSAT: return C1.sshl_sat(C2);
5424   case ISD::USHLSAT: return C1.ushl_sat(C2);
5425   case ISD::UDIV:
5426     if (!C2.getBoolValue())
5427       break;
5428     return C1.udiv(C2);
5429   case ISD::UREM:
5430     if (!C2.getBoolValue())
5431       break;
5432     return C1.urem(C2);
5433   case ISD::SDIV:
5434     if (!C2.getBoolValue())
5435       break;
5436     return C1.sdiv(C2);
5437   case ISD::SREM:
5438     if (!C2.getBoolValue())
5439       break;
5440     return C1.srem(C2);
5441   case ISD::MULHS: {
5442     unsigned FullWidth = C1.getBitWidth() * 2;
5443     APInt C1Ext = C1.sext(FullWidth);
5444     APInt C2Ext = C2.sext(FullWidth);
5445     return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth());
5446   }
5447   case ISD::MULHU: {
5448     unsigned FullWidth = C1.getBitWidth() * 2;
5449     APInt C1Ext = C1.zext(FullWidth);
5450     APInt C2Ext = C2.zext(FullWidth);
5451     return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth());
5452   }
5453   case ISD::AVGFLOORS: {
5454     unsigned FullWidth = C1.getBitWidth() + 1;
5455     APInt C1Ext = C1.sext(FullWidth);
5456     APInt C2Ext = C2.sext(FullWidth);
5457     return (C1Ext + C2Ext).extractBits(C1.getBitWidth(), 1);
5458   }
5459   case ISD::AVGFLOORU: {
5460     unsigned FullWidth = C1.getBitWidth() + 1;
5461     APInt C1Ext = C1.zext(FullWidth);
5462     APInt C2Ext = C2.zext(FullWidth);
5463     return (C1Ext + C2Ext).extractBits(C1.getBitWidth(), 1);
5464   }
5465   case ISD::AVGCEILS: {
5466     unsigned FullWidth = C1.getBitWidth() + 1;
5467     APInt C1Ext = C1.sext(FullWidth);
5468     APInt C2Ext = C2.sext(FullWidth);
5469     return (C1Ext + C2Ext + 1).extractBits(C1.getBitWidth(), 1);
5470   }
5471   case ISD::AVGCEILU: {
5472     unsigned FullWidth = C1.getBitWidth() + 1;
5473     APInt C1Ext = C1.zext(FullWidth);
5474     APInt C2Ext = C2.zext(FullWidth);
5475     return (C1Ext + C2Ext + 1).extractBits(C1.getBitWidth(), 1);
5476   }
5477   }
5478   return llvm::None;
5479 }
5480 
5481 SDValue SelectionDAG::FoldSymbolOffset(unsigned Opcode, EVT VT,
5482                                        const GlobalAddressSDNode *GA,
5483                                        const SDNode *N2) {
5484   if (GA->getOpcode() != ISD::GlobalAddress)
5485     return SDValue();
5486   if (!TLI->isOffsetFoldingLegal(GA))
5487     return SDValue();
5488   auto *C2 = dyn_cast<ConstantSDNode>(N2);
5489   if (!C2)
5490     return SDValue();
5491   int64_t Offset = C2->getSExtValue();
5492   switch (Opcode) {
5493   case ISD::ADD: break;
5494   case ISD::SUB: Offset = -uint64_t(Offset); break;
5495   default: return SDValue();
5496   }
5497   return getGlobalAddress(GA->getGlobal(), SDLoc(C2), VT,
5498                           GA->getOffset() + uint64_t(Offset));
5499 }
5500 
5501 bool SelectionDAG::isUndef(unsigned Opcode, ArrayRef<SDValue> Ops) {
5502   switch (Opcode) {
5503   case ISD::SDIV:
5504   case ISD::UDIV:
5505   case ISD::SREM:
5506   case ISD::UREM: {
5507     // If a divisor is zero/undef or any element of a divisor vector is
5508     // zero/undef, the whole op is undef.
5509     assert(Ops.size() == 2 && "Div/rem should have 2 operands");
5510     SDValue Divisor = Ops[1];
5511     if (Divisor.isUndef() || isNullConstant(Divisor))
5512       return true;
5513 
5514     return ISD::isBuildVectorOfConstantSDNodes(Divisor.getNode()) &&
5515            llvm::any_of(Divisor->op_values(),
5516                         [](SDValue V) { return V.isUndef() ||
5517                                         isNullConstant(V); });
5518     // TODO: Handle signed overflow.
5519   }
5520   // TODO: Handle oversized shifts.
5521   default:
5522     return false;
5523   }
5524 }
5525 
5526 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL,
5527                                              EVT VT, ArrayRef<SDValue> Ops) {
5528   // If the opcode is a target-specific ISD node, there's nothing we can
5529   // do here and the operand rules may not line up with the below, so
5530   // bail early.
5531   // We can't create a scalar CONCAT_VECTORS so skip it. It will break
5532   // for concats involving SPLAT_VECTOR. Concats of BUILD_VECTORS are handled by
5533   // foldCONCAT_VECTORS in getNode before this is called.
5534   if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::CONCAT_VECTORS)
5535     return SDValue();
5536 
5537   unsigned NumOps = Ops.size();
5538   if (NumOps == 0)
5539     return SDValue();
5540 
5541   if (isUndef(Opcode, Ops))
5542     return getUNDEF(VT);
5543 
5544   // Handle binops special cases.
5545   if (NumOps == 2) {
5546     if (SDValue CFP = foldConstantFPMath(Opcode, DL, VT, Ops[0], Ops[1]))
5547       return CFP;
5548 
5549     if (auto *C1 = dyn_cast<ConstantSDNode>(Ops[0])) {
5550       if (auto *C2 = dyn_cast<ConstantSDNode>(Ops[1])) {
5551         if (C1->isOpaque() || C2->isOpaque())
5552           return SDValue();
5553 
5554         Optional<APInt> FoldAttempt =
5555             FoldValue(Opcode, C1->getAPIntValue(), C2->getAPIntValue());
5556         if (!FoldAttempt)
5557           return SDValue();
5558 
5559         SDValue Folded = getConstant(*FoldAttempt, DL, VT);
5560         assert((!Folded || !VT.isVector()) &&
5561                "Can't fold vectors ops with scalar operands");
5562         return Folded;
5563       }
5564     }
5565 
5566     // fold (add Sym, c) -> Sym+c
5567     if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ops[0]))
5568       return FoldSymbolOffset(Opcode, VT, GA, Ops[1].getNode());
5569     if (TLI->isCommutativeBinOp(Opcode))
5570       if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ops[1]))
5571         return FoldSymbolOffset(Opcode, VT, GA, Ops[0].getNode());
5572   }
5573 
5574   // This is for vector folding only from here on.
5575   if (!VT.isVector())
5576     return SDValue();
5577 
5578   ElementCount NumElts = VT.getVectorElementCount();
5579 
5580   // See if we can fold through bitcasted integer ops.
5581   // TODO: Can we handle undef elements?
5582   if (NumOps == 2 && VT.isFixedLengthVector() && VT.isInteger() &&
5583       Ops[0].getValueType() == VT && Ops[1].getValueType() == VT &&
5584       Ops[0].getOpcode() == ISD::BITCAST &&
5585       Ops[1].getOpcode() == ISD::BITCAST) {
5586     SDValue N1 = peekThroughBitcasts(Ops[0]);
5587     SDValue N2 = peekThroughBitcasts(Ops[1]);
5588     auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
5589     auto *BV2 = dyn_cast<BuildVectorSDNode>(N2);
5590     EVT BVVT = N1.getValueType();
5591     if (BV1 && BV2 && BVVT.isInteger() && BVVT == N2.getValueType()) {
5592       bool IsLE = getDataLayout().isLittleEndian();
5593       unsigned EltBits = VT.getScalarSizeInBits();
5594       SmallVector<APInt> RawBits1, RawBits2;
5595       BitVector UndefElts1, UndefElts2;
5596       if (BV1->getConstantRawBits(IsLE, EltBits, RawBits1, UndefElts1) &&
5597           BV2->getConstantRawBits(IsLE, EltBits, RawBits2, UndefElts2) &&
5598           UndefElts1.none() && UndefElts2.none()) {
5599         SmallVector<APInt> RawBits;
5600         for (unsigned I = 0, E = NumElts.getFixedValue(); I != E; ++I) {
5601           Optional<APInt> Fold = FoldValue(Opcode, RawBits1[I], RawBits2[I]);
5602           if (!Fold)
5603             break;
5604           RawBits.push_back(*Fold);
5605         }
5606         if (RawBits.size() == NumElts.getFixedValue()) {
5607           // We have constant folded, but we need to cast this again back to
5608           // the original (possibly legalized) type.
5609           SmallVector<APInt> DstBits;
5610           BitVector DstUndefs;
5611           BuildVectorSDNode::recastRawBits(IsLE, BVVT.getScalarSizeInBits(),
5612                                            DstBits, RawBits, DstUndefs,
5613                                            BitVector(RawBits.size(), false));
5614           EVT BVEltVT = BV1->getOperand(0).getValueType();
5615           unsigned BVEltBits = BVEltVT.getSizeInBits();
5616           SmallVector<SDValue> Ops(DstBits.size(), getUNDEF(BVEltVT));
5617           for (unsigned I = 0, E = DstBits.size(); I != E; ++I) {
5618             if (DstUndefs[I])
5619               continue;
5620             Ops[I] = getConstant(DstBits[I].sext(BVEltBits), DL, BVEltVT);
5621           }
5622           return getBitcast(VT, getBuildVector(BVVT, DL, Ops));
5623         }
5624       }
5625     }
5626   }
5627 
5628   // Fold (mul step_vector(C0), C1) to (step_vector(C0 * C1)).
5629   //      (shl step_vector(C0), C1) -> (step_vector(C0 << C1))
5630   if ((Opcode == ISD::MUL || Opcode == ISD::SHL) &&
5631       Ops[0].getOpcode() == ISD::STEP_VECTOR) {
5632     APInt RHSVal;
5633     if (ISD::isConstantSplatVector(Ops[1].getNode(), RHSVal)) {
5634       APInt NewStep = Opcode == ISD::MUL
5635                           ? Ops[0].getConstantOperandAPInt(0) * RHSVal
5636                           : Ops[0].getConstantOperandAPInt(0) << RHSVal;
5637       return getStepVector(DL, VT, NewStep);
5638     }
5639   }
5640 
5641   auto IsScalarOrSameVectorSize = [NumElts](const SDValue &Op) {
5642     return !Op.getValueType().isVector() ||
5643            Op.getValueType().getVectorElementCount() == NumElts;
5644   };
5645 
5646   auto IsBuildVectorSplatVectorOrUndef = [](const SDValue &Op) {
5647     return Op.isUndef() || Op.getOpcode() == ISD::CONDCODE ||
5648            Op.getOpcode() == ISD::BUILD_VECTOR ||
5649            Op.getOpcode() == ISD::SPLAT_VECTOR;
5650   };
5651 
5652   // All operands must be vector types with the same number of elements as
5653   // the result type and must be either UNDEF or a build/splat vector
5654   // or UNDEF scalars.
5655   if (!llvm::all_of(Ops, IsBuildVectorSplatVectorOrUndef) ||
5656       !llvm::all_of(Ops, IsScalarOrSameVectorSize))
5657     return SDValue();
5658 
5659   // If we are comparing vectors, then the result needs to be a i1 boolean that
5660   // is then extended back to the legal result type depending on how booleans
5661   // are represented.
5662   EVT SVT = (Opcode == ISD::SETCC ? MVT::i1 : VT.getScalarType());
5663   ISD::NodeType ExtendCode =
5664       (Opcode == ISD::SETCC && SVT != VT.getScalarType())
5665           ? TargetLowering::getExtendForContent(TLI->getBooleanContents(VT))
5666           : ISD::SIGN_EXTEND;
5667 
5668   // Find legal integer scalar type for constant promotion and
5669   // ensure that its scalar size is at least as large as source.
5670   EVT LegalSVT = VT.getScalarType();
5671   if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
5672     LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
5673     if (LegalSVT.bitsLT(VT.getScalarType()))
5674       return SDValue();
5675   }
5676 
5677   // For scalable vector types we know we're dealing with SPLAT_VECTORs. We
5678   // only have one operand to check. For fixed-length vector types we may have
5679   // a combination of BUILD_VECTOR and SPLAT_VECTOR.
5680   unsigned NumVectorElts = NumElts.isScalable() ? 1 : NumElts.getFixedValue();
5681 
5682   // Constant fold each scalar lane separately.
5683   SmallVector<SDValue, 4> ScalarResults;
5684   for (unsigned I = 0; I != NumVectorElts; I++) {
5685     SmallVector<SDValue, 4> ScalarOps;
5686     for (SDValue Op : Ops) {
5687       EVT InSVT = Op.getValueType().getScalarType();
5688       if (Op.getOpcode() != ISD::BUILD_VECTOR &&
5689           Op.getOpcode() != ISD::SPLAT_VECTOR) {
5690         if (Op.isUndef())
5691           ScalarOps.push_back(getUNDEF(InSVT));
5692         else
5693           ScalarOps.push_back(Op);
5694         continue;
5695       }
5696 
5697       SDValue ScalarOp =
5698           Op.getOperand(Op.getOpcode() == ISD::SPLAT_VECTOR ? 0 : I);
5699       EVT ScalarVT = ScalarOp.getValueType();
5700 
5701       // Build vector (integer) scalar operands may need implicit
5702       // truncation - do this before constant folding.
5703       if (ScalarVT.isInteger() && ScalarVT.bitsGT(InSVT)) {
5704         // Don't create illegally-typed nodes unless they're constants or undef
5705         // - if we fail to constant fold we can't guarantee the (dead) nodes
5706         // we're creating will be cleaned up before being visited for
5707         // legalization.
5708         if (NewNodesMustHaveLegalTypes && !ScalarOp.isUndef() &&
5709             !isa<ConstantSDNode>(ScalarOp) &&
5710             TLI->getTypeAction(*getContext(), InSVT) !=
5711                 TargetLowering::TypeLegal)
5712           return SDValue();
5713         ScalarOp = getNode(ISD::TRUNCATE, DL, InSVT, ScalarOp);
5714       }
5715 
5716       ScalarOps.push_back(ScalarOp);
5717     }
5718 
5719     // Constant fold the scalar operands.
5720     SDValue ScalarResult = getNode(Opcode, DL, SVT, ScalarOps);
5721 
5722     // Legalize the (integer) scalar constant if necessary.
5723     if (LegalSVT != SVT)
5724       ScalarResult = getNode(ExtendCode, DL, LegalSVT, ScalarResult);
5725 
5726     // Scalar folding only succeeded if the result is a constant or UNDEF.
5727     if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant &&
5728         ScalarResult.getOpcode() != ISD::ConstantFP)
5729       return SDValue();
5730     ScalarResults.push_back(ScalarResult);
5731   }
5732 
5733   SDValue V = NumElts.isScalable() ? getSplatVector(VT, DL, ScalarResults[0])
5734                                    : getBuildVector(VT, DL, ScalarResults);
5735   NewSDValueDbgMsg(V, "New node fold constant vector: ", this);
5736   return V;
5737 }
5738 
5739 SDValue SelectionDAG::foldConstantFPMath(unsigned Opcode, const SDLoc &DL,
5740                                          EVT VT, SDValue N1, SDValue N2) {
5741   // TODO: We don't do any constant folding for strict FP opcodes here, but we
5742   //       should. That will require dealing with a potentially non-default
5743   //       rounding mode, checking the "opStatus" return value from the APFloat
5744   //       math calculations, and possibly other variations.
5745   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1, /*AllowUndefs*/ false);
5746   ConstantFPSDNode *N2CFP = isConstOrConstSplatFP(N2, /*AllowUndefs*/ false);
5747   if (N1CFP && N2CFP) {
5748     APFloat C1 = N1CFP->getValueAPF(); // make copy
5749     const APFloat &C2 = N2CFP->getValueAPF();
5750     switch (Opcode) {
5751     case ISD::FADD:
5752       C1.add(C2, APFloat::rmNearestTiesToEven);
5753       return getConstantFP(C1, DL, VT);
5754     case ISD::FSUB:
5755       C1.subtract(C2, APFloat::rmNearestTiesToEven);
5756       return getConstantFP(C1, DL, VT);
5757     case ISD::FMUL:
5758       C1.multiply(C2, APFloat::rmNearestTiesToEven);
5759       return getConstantFP(C1, DL, VT);
5760     case ISD::FDIV:
5761       C1.divide(C2, APFloat::rmNearestTiesToEven);
5762       return getConstantFP(C1, DL, VT);
5763     case ISD::FREM:
5764       C1.mod(C2);
5765       return getConstantFP(C1, DL, VT);
5766     case ISD::FCOPYSIGN:
5767       C1.copySign(C2);
5768       return getConstantFP(C1, DL, VT);
5769     case ISD::FMINNUM:
5770       return getConstantFP(minnum(C1, C2), DL, VT);
5771     case ISD::FMAXNUM:
5772       return getConstantFP(maxnum(C1, C2), DL, VT);
5773     case ISD::FMINIMUM:
5774       return getConstantFP(minimum(C1, C2), DL, VT);
5775     case ISD::FMAXIMUM:
5776       return getConstantFP(maximum(C1, C2), DL, VT);
5777     default: break;
5778     }
5779   }
5780   if (N1CFP && Opcode == ISD::FP_ROUND) {
5781     APFloat C1 = N1CFP->getValueAPF();    // make copy
5782     bool Unused;
5783     // This can return overflow, underflow, or inexact; we don't care.
5784     // FIXME need to be more flexible about rounding mode.
5785     (void) C1.convert(EVTToAPFloatSemantics(VT), APFloat::rmNearestTiesToEven,
5786                       &Unused);
5787     return getConstantFP(C1, DL, VT);
5788   }
5789 
5790   switch (Opcode) {
5791   case ISD::FSUB:
5792     // -0.0 - undef --> undef (consistent with "fneg undef")
5793     if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1, /*AllowUndefs*/ true))
5794       if (N1C && N1C->getValueAPF().isNegZero() && N2.isUndef())
5795         return getUNDEF(VT);
5796     LLVM_FALLTHROUGH;
5797 
5798   case ISD::FADD:
5799   case ISD::FMUL:
5800   case ISD::FDIV:
5801   case ISD::FREM:
5802     // If both operands are undef, the result is undef. If 1 operand is undef,
5803     // the result is NaN. This should match the behavior of the IR optimizer.
5804     if (N1.isUndef() && N2.isUndef())
5805       return getUNDEF(VT);
5806     if (N1.isUndef() || N2.isUndef())
5807       return getConstantFP(APFloat::getNaN(EVTToAPFloatSemantics(VT)), DL, VT);
5808   }
5809   return SDValue();
5810 }
5811 
5812 SDValue SelectionDAG::getAssertAlign(const SDLoc &DL, SDValue Val, Align A) {
5813   assert(Val.getValueType().isInteger() && "Invalid AssertAlign!");
5814 
5815   // There's no need to assert on a byte-aligned pointer. All pointers are at
5816   // least byte aligned.
5817   if (A == Align(1))
5818     return Val;
5819 
5820   FoldingSetNodeID ID;
5821   AddNodeIDNode(ID, ISD::AssertAlign, getVTList(Val.getValueType()), {Val});
5822   ID.AddInteger(A.value());
5823 
5824   void *IP = nullptr;
5825   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
5826     return SDValue(E, 0);
5827 
5828   auto *N = newSDNode<AssertAlignSDNode>(DL.getIROrder(), DL.getDebugLoc(),
5829                                          Val.getValueType(), A);
5830   createOperands(N, {Val});
5831 
5832   CSEMap.InsertNode(N, IP);
5833   InsertNode(N);
5834 
5835   SDValue V(N, 0);
5836   NewSDValueDbgMsg(V, "Creating new node: ", this);
5837   return V;
5838 }
5839 
5840 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5841                               SDValue N1, SDValue N2) {
5842   SDNodeFlags Flags;
5843   if (Inserter)
5844     Flags = Inserter->getFlags();
5845   return getNode(Opcode, DL, VT, N1, N2, Flags);
5846 }
5847 
5848 void SelectionDAG::canonicalizeCommutativeBinop(unsigned Opcode, SDValue &N1,
5849                                                 SDValue &N2) const {
5850   if (!TLI->isCommutativeBinOp(Opcode))
5851     return;
5852 
5853   // Canonicalize:
5854   //   binop(const, nonconst) -> binop(nonconst, const)
5855   bool IsN1C = isConstantIntBuildVectorOrConstantInt(N1);
5856   bool IsN2C = isConstantIntBuildVectorOrConstantInt(N2);
5857   bool IsN1CFP = isConstantFPBuildVectorOrConstantFP(N1);
5858   bool IsN2CFP = isConstantFPBuildVectorOrConstantFP(N2);
5859   if ((IsN1C && !IsN2C) || (IsN1CFP && !IsN2CFP))
5860     std::swap(N1, N2);
5861 
5862   // Canonicalize:
5863   //  binop(splat(x), step_vector) -> binop(step_vector, splat(x))
5864   else if (N1.getOpcode() == ISD::SPLAT_VECTOR &&
5865            N2.getOpcode() == ISD::STEP_VECTOR)
5866     std::swap(N1, N2);
5867 }
5868 
5869 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5870                               SDValue N1, SDValue N2, const SDNodeFlags Flags) {
5871   assert(N1.getOpcode() != ISD::DELETED_NODE &&
5872          N2.getOpcode() != ISD::DELETED_NODE &&
5873          "Operand is DELETED_NODE!");
5874 
5875   canonicalizeCommutativeBinop(Opcode, N1, N2);
5876 
5877   auto *N1C = dyn_cast<ConstantSDNode>(N1);
5878   auto *N2C = dyn_cast<ConstantSDNode>(N2);
5879 
5880   // Don't allow undefs in vector splats - we might be returning N2 when folding
5881   // to zero etc.
5882   ConstantSDNode *N2CV =
5883       isConstOrConstSplat(N2, /*AllowUndefs*/ false, /*AllowTruncation*/ true);
5884 
5885   switch (Opcode) {
5886   default: break;
5887   case ISD::TokenFactor:
5888     assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
5889            N2.getValueType() == MVT::Other && "Invalid token factor!");
5890     // Fold trivial token factors.
5891     if (N1.getOpcode() == ISD::EntryToken) return N2;
5892     if (N2.getOpcode() == ISD::EntryToken) return N1;
5893     if (N1 == N2) return N1;
5894     break;
5895   case ISD::BUILD_VECTOR: {
5896     // Attempt to simplify BUILD_VECTOR.
5897     SDValue Ops[] = {N1, N2};
5898     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
5899       return V;
5900     break;
5901   }
5902   case ISD::CONCAT_VECTORS: {
5903     SDValue Ops[] = {N1, N2};
5904     if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
5905       return V;
5906     break;
5907   }
5908   case ISD::AND:
5909     assert(VT.isInteger() && "This operator does not apply to FP types!");
5910     assert(N1.getValueType() == N2.getValueType() &&
5911            N1.getValueType() == VT && "Binary operator types must match!");
5912     // (X & 0) -> 0.  This commonly occurs when legalizing i64 values, so it's
5913     // worth handling here.
5914     if (N2CV && N2CV->isZero())
5915       return N2;
5916     if (N2CV && N2CV->isAllOnes()) // X & -1 -> X
5917       return N1;
5918     break;
5919   case ISD::OR:
5920   case ISD::XOR:
5921   case ISD::ADD:
5922   case ISD::SUB:
5923     assert(VT.isInteger() && "This operator does not apply to FP types!");
5924     assert(N1.getValueType() == N2.getValueType() &&
5925            N1.getValueType() == VT && "Binary operator types must match!");
5926     // (X ^|+- 0) -> X.  This commonly occurs when legalizing i64 values, so
5927     // it's worth handling here.
5928     if (N2CV && N2CV->isZero())
5929       return N1;
5930     if ((Opcode == ISD::ADD || Opcode == ISD::SUB) && VT.isVector() &&
5931         VT.getVectorElementType() == MVT::i1)
5932       return getNode(ISD::XOR, DL, VT, N1, N2);
5933     break;
5934   case ISD::MUL:
5935     assert(VT.isInteger() && "This operator does not apply to FP types!");
5936     assert(N1.getValueType() == N2.getValueType() &&
5937            N1.getValueType() == VT && "Binary operator types must match!");
5938     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
5939       return getNode(ISD::AND, DL, VT, N1, N2);
5940     if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
5941       const APInt &MulImm = N1->getConstantOperandAPInt(0);
5942       const APInt &N2CImm = N2C->getAPIntValue();
5943       return getVScale(DL, VT, MulImm * N2CImm);
5944     }
5945     break;
5946   case ISD::UDIV:
5947   case ISD::UREM:
5948   case ISD::MULHU:
5949   case ISD::MULHS:
5950   case ISD::SDIV:
5951   case ISD::SREM:
5952   case ISD::SADDSAT:
5953   case ISD::SSUBSAT:
5954   case ISD::UADDSAT:
5955   case ISD::USUBSAT:
5956     assert(VT.isInteger() && "This operator does not apply to FP types!");
5957     assert(N1.getValueType() == N2.getValueType() &&
5958            N1.getValueType() == VT && "Binary operator types must match!");
5959     if (VT.isVector() && VT.getVectorElementType() == MVT::i1) {
5960       // fold (add_sat x, y) -> (or x, y) for bool types.
5961       if (Opcode == ISD::SADDSAT || Opcode == ISD::UADDSAT)
5962         return getNode(ISD::OR, DL, VT, N1, N2);
5963       // fold (sub_sat x, y) -> (and x, ~y) for bool types.
5964       if (Opcode == ISD::SSUBSAT || Opcode == ISD::USUBSAT)
5965         return getNode(ISD::AND, DL, VT, N1, getNOT(DL, N2, VT));
5966     }
5967     break;
5968   case ISD::SMIN:
5969   case ISD::UMAX:
5970     assert(VT.isInteger() && "This operator does not apply to FP types!");
5971     assert(N1.getValueType() == N2.getValueType() &&
5972            N1.getValueType() == VT && "Binary operator types must match!");
5973     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
5974       return getNode(ISD::OR, DL, VT, N1, N2);
5975     break;
5976   case ISD::SMAX:
5977   case ISD::UMIN:
5978     assert(VT.isInteger() && "This operator does not apply to FP types!");
5979     assert(N1.getValueType() == N2.getValueType() &&
5980            N1.getValueType() == VT && "Binary operator types must match!");
5981     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
5982       return getNode(ISD::AND, DL, VT, N1, N2);
5983     break;
5984   case ISD::FADD:
5985   case ISD::FSUB:
5986   case ISD::FMUL:
5987   case ISD::FDIV:
5988   case ISD::FREM:
5989     assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
5990     assert(N1.getValueType() == N2.getValueType() &&
5991            N1.getValueType() == VT && "Binary operator types must match!");
5992     if (SDValue V = simplifyFPBinop(Opcode, N1, N2, Flags))
5993       return V;
5994     break;
5995   case ISD::FCOPYSIGN:   // N1 and result must match.  N1/N2 need not match.
5996     assert(N1.getValueType() == VT &&
5997            N1.getValueType().isFloatingPoint() &&
5998            N2.getValueType().isFloatingPoint() &&
5999            "Invalid FCOPYSIGN!");
6000     break;
6001   case ISD::SHL:
6002     if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
6003       const APInt &MulImm = N1->getConstantOperandAPInt(0);
6004       const APInt &ShiftImm = N2C->getAPIntValue();
6005       return getVScale(DL, VT, MulImm << ShiftImm);
6006     }
6007     LLVM_FALLTHROUGH;
6008   case ISD::SRA:
6009   case ISD::SRL:
6010     if (SDValue V = simplifyShift(N1, N2))
6011       return V;
6012     LLVM_FALLTHROUGH;
6013   case ISD::ROTL:
6014   case ISD::ROTR:
6015     assert(VT == N1.getValueType() &&
6016            "Shift operators return type must be the same as their first arg");
6017     assert(VT.isInteger() && N2.getValueType().isInteger() &&
6018            "Shifts only work on integers");
6019     assert((!VT.isVector() || VT == N2.getValueType()) &&
6020            "Vector shift amounts must be in the same as their first arg");
6021     // Verify that the shift amount VT is big enough to hold valid shift
6022     // amounts.  This catches things like trying to shift an i1024 value by an
6023     // i8, which is easy to fall into in generic code that uses
6024     // TLI.getShiftAmount().
6025     assert(N2.getValueType().getScalarSizeInBits() >=
6026                Log2_32_Ceil(VT.getScalarSizeInBits()) &&
6027            "Invalid use of small shift amount with oversized value!");
6028 
6029     // Always fold shifts of i1 values so the code generator doesn't need to
6030     // handle them.  Since we know the size of the shift has to be less than the
6031     // size of the value, the shift/rotate count is guaranteed to be zero.
6032     if (VT == MVT::i1)
6033       return N1;
6034     if (N2CV && N2CV->isZero())
6035       return N1;
6036     break;
6037   case ISD::FP_ROUND:
6038     assert(VT.isFloatingPoint() &&
6039            N1.getValueType().isFloatingPoint() &&
6040            VT.bitsLE(N1.getValueType()) &&
6041            N2C && (N2C->getZExtValue() == 0 || N2C->getZExtValue() == 1) &&
6042            "Invalid FP_ROUND!");
6043     if (N1.getValueType() == VT) return N1;  // noop conversion.
6044     break;
6045   case ISD::AssertSext:
6046   case ISD::AssertZext: {
6047     EVT EVT = cast<VTSDNode>(N2)->getVT();
6048     assert(VT == N1.getValueType() && "Not an inreg extend!");
6049     assert(VT.isInteger() && EVT.isInteger() &&
6050            "Cannot *_EXTEND_INREG FP types");
6051     assert(!EVT.isVector() &&
6052            "AssertSExt/AssertZExt type should be the vector element type "
6053            "rather than the vector type!");
6054     assert(EVT.bitsLE(VT.getScalarType()) && "Not extending!");
6055     if (VT.getScalarType() == EVT) return N1; // noop assertion.
6056     break;
6057   }
6058   case ISD::SIGN_EXTEND_INREG: {
6059     EVT EVT = cast<VTSDNode>(N2)->getVT();
6060     assert(VT == N1.getValueType() && "Not an inreg extend!");
6061     assert(VT.isInteger() && EVT.isInteger() &&
6062            "Cannot *_EXTEND_INREG FP types");
6063     assert(EVT.isVector() == VT.isVector() &&
6064            "SIGN_EXTEND_INREG type should be vector iff the operand "
6065            "type is vector!");
6066     assert((!EVT.isVector() ||
6067             EVT.getVectorElementCount() == VT.getVectorElementCount()) &&
6068            "Vector element counts must match in SIGN_EXTEND_INREG");
6069     assert(EVT.bitsLE(VT) && "Not extending!");
6070     if (EVT == VT) return N1;  // Not actually extending
6071 
6072     auto SignExtendInReg = [&](APInt Val, llvm::EVT ConstantVT) {
6073       unsigned FromBits = EVT.getScalarSizeInBits();
6074       Val <<= Val.getBitWidth() - FromBits;
6075       Val.ashrInPlace(Val.getBitWidth() - FromBits);
6076       return getConstant(Val, DL, ConstantVT);
6077     };
6078 
6079     if (N1C) {
6080       const APInt &Val = N1C->getAPIntValue();
6081       return SignExtendInReg(Val, VT);
6082     }
6083 
6084     if (ISD::isBuildVectorOfConstantSDNodes(N1.getNode())) {
6085       SmallVector<SDValue, 8> Ops;
6086       llvm::EVT OpVT = N1.getOperand(0).getValueType();
6087       for (int i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
6088         SDValue Op = N1.getOperand(i);
6089         if (Op.isUndef()) {
6090           Ops.push_back(getUNDEF(OpVT));
6091           continue;
6092         }
6093         ConstantSDNode *C = cast<ConstantSDNode>(Op);
6094         APInt Val = C->getAPIntValue();
6095         Ops.push_back(SignExtendInReg(Val, OpVT));
6096       }
6097       return getBuildVector(VT, DL, Ops);
6098     }
6099     break;
6100   }
6101   case ISD::FP_TO_SINT_SAT:
6102   case ISD::FP_TO_UINT_SAT: {
6103     assert(VT.isInteger() && cast<VTSDNode>(N2)->getVT().isInteger() &&
6104            N1.getValueType().isFloatingPoint() && "Invalid FP_TO_*INT_SAT");
6105     assert(N1.getValueType().isVector() == VT.isVector() &&
6106            "FP_TO_*INT_SAT type should be vector iff the operand type is "
6107            "vector!");
6108     assert((!VT.isVector() || VT.getVectorNumElements() ==
6109                                   N1.getValueType().getVectorNumElements()) &&
6110            "Vector element counts must match in FP_TO_*INT_SAT");
6111     assert(!cast<VTSDNode>(N2)->getVT().isVector() &&
6112            "Type to saturate to must be a scalar.");
6113     assert(cast<VTSDNode>(N2)->getVT().bitsLE(VT.getScalarType()) &&
6114            "Not extending!");
6115     break;
6116   }
6117   case ISD::EXTRACT_VECTOR_ELT:
6118     assert(VT.getSizeInBits() >= N1.getValueType().getScalarSizeInBits() &&
6119            "The result of EXTRACT_VECTOR_ELT must be at least as wide as the \
6120              element type of the vector.");
6121 
6122     // Extract from an undefined value or using an undefined index is undefined.
6123     if (N1.isUndef() || N2.isUndef())
6124       return getUNDEF(VT);
6125 
6126     // EXTRACT_VECTOR_ELT of out-of-bounds element is an UNDEF for fixed length
6127     // vectors. For scalable vectors we will provide appropriate support for
6128     // dealing with arbitrary indices.
6129     if (N2C && N1.getValueType().isFixedLengthVector() &&
6130         N2C->getAPIntValue().uge(N1.getValueType().getVectorNumElements()))
6131       return getUNDEF(VT);
6132 
6133     // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
6134     // expanding copies of large vectors from registers. This only works for
6135     // fixed length vectors, since we need to know the exact number of
6136     // elements.
6137     if (N2C && N1.getOperand(0).getValueType().isFixedLengthVector() &&
6138         N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0) {
6139       unsigned Factor =
6140         N1.getOperand(0).getValueType().getVectorNumElements();
6141       return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
6142                      N1.getOperand(N2C->getZExtValue() / Factor),
6143                      getVectorIdxConstant(N2C->getZExtValue() % Factor, DL));
6144     }
6145 
6146     // EXTRACT_VECTOR_ELT of BUILD_VECTOR or SPLAT_VECTOR is often formed while
6147     // lowering is expanding large vector constants.
6148     if (N2C && (N1.getOpcode() == ISD::BUILD_VECTOR ||
6149                 N1.getOpcode() == ISD::SPLAT_VECTOR)) {
6150       assert((N1.getOpcode() != ISD::BUILD_VECTOR ||
6151               N1.getValueType().isFixedLengthVector()) &&
6152              "BUILD_VECTOR used for scalable vectors");
6153       unsigned Index =
6154           N1.getOpcode() == ISD::BUILD_VECTOR ? N2C->getZExtValue() : 0;
6155       SDValue Elt = N1.getOperand(Index);
6156 
6157       if (VT != Elt.getValueType())
6158         // If the vector element type is not legal, the BUILD_VECTOR operands
6159         // are promoted and implicitly truncated, and the result implicitly
6160         // extended. Make that explicit here.
6161         Elt = getAnyExtOrTrunc(Elt, DL, VT);
6162 
6163       return Elt;
6164     }
6165 
6166     // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
6167     // operations are lowered to scalars.
6168     if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) {
6169       // If the indices are the same, return the inserted element else
6170       // if the indices are known different, extract the element from
6171       // the original vector.
6172       SDValue N1Op2 = N1.getOperand(2);
6173       ConstantSDNode *N1Op2C = dyn_cast<ConstantSDNode>(N1Op2);
6174 
6175       if (N1Op2C && N2C) {
6176         if (N1Op2C->getZExtValue() == N2C->getZExtValue()) {
6177           if (VT == N1.getOperand(1).getValueType())
6178             return N1.getOperand(1);
6179           if (VT.isFloatingPoint()) {
6180             assert(VT.getSizeInBits() > N1.getOperand(1).getValueType().getSizeInBits());
6181             return getFPExtendOrRound(N1.getOperand(1), DL, VT);
6182           }
6183           return getSExtOrTrunc(N1.getOperand(1), DL, VT);
6184         }
6185         return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2);
6186       }
6187     }
6188 
6189     // EXTRACT_VECTOR_ELT of v1iX EXTRACT_SUBVECTOR could be formed
6190     // when vector types are scalarized and v1iX is legal.
6191     // vextract (v1iX extract_subvector(vNiX, Idx)) -> vextract(vNiX,Idx).
6192     // Here we are completely ignoring the extract element index (N2),
6193     // which is fine for fixed width vectors, since any index other than 0
6194     // is undefined anyway. However, this cannot be ignored for scalable
6195     // vectors - in theory we could support this, but we don't want to do this
6196     // without a profitability check.
6197     if (N1.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
6198         N1.getValueType().isFixedLengthVector() &&
6199         N1.getValueType().getVectorNumElements() == 1) {
6200       return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0),
6201                      N1.getOperand(1));
6202     }
6203     break;
6204   case ISD::EXTRACT_ELEMENT:
6205     assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!");
6206     assert(!N1.getValueType().isVector() && !VT.isVector() &&
6207            (N1.getValueType().isInteger() == VT.isInteger()) &&
6208            N1.getValueType() != VT &&
6209            "Wrong types for EXTRACT_ELEMENT!");
6210 
6211     // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
6212     // 64-bit integers into 32-bit parts.  Instead of building the extract of
6213     // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
6214     if (N1.getOpcode() == ISD::BUILD_PAIR)
6215       return N1.getOperand(N2C->getZExtValue());
6216 
6217     // EXTRACT_ELEMENT of a constant int is also very common.
6218     if (N1C) {
6219       unsigned ElementSize = VT.getSizeInBits();
6220       unsigned Shift = ElementSize * N2C->getZExtValue();
6221       const APInt &Val = N1C->getAPIntValue();
6222       return getConstant(Val.extractBits(ElementSize, Shift), DL, VT);
6223     }
6224     break;
6225   case ISD::EXTRACT_SUBVECTOR: {
6226     EVT N1VT = N1.getValueType();
6227     assert(VT.isVector() && N1VT.isVector() &&
6228            "Extract subvector VTs must be vectors!");
6229     assert(VT.getVectorElementType() == N1VT.getVectorElementType() &&
6230            "Extract subvector VTs must have the same element type!");
6231     assert((VT.isFixedLengthVector() || N1VT.isScalableVector()) &&
6232            "Cannot extract a scalable vector from a fixed length vector!");
6233     assert((VT.isScalableVector() != N1VT.isScalableVector() ||
6234             VT.getVectorMinNumElements() <= N1VT.getVectorMinNumElements()) &&
6235            "Extract subvector must be from larger vector to smaller vector!");
6236     assert(N2C && "Extract subvector index must be a constant");
6237     assert((VT.isScalableVector() != N1VT.isScalableVector() ||
6238             (VT.getVectorMinNumElements() + N2C->getZExtValue()) <=
6239                 N1VT.getVectorMinNumElements()) &&
6240            "Extract subvector overflow!");
6241     assert(N2C->getAPIntValue().getBitWidth() ==
6242                TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() &&
6243            "Constant index for EXTRACT_SUBVECTOR has an invalid size");
6244 
6245     // Trivial extraction.
6246     if (VT == N1VT)
6247       return N1;
6248 
6249     // EXTRACT_SUBVECTOR of an UNDEF is an UNDEF.
6250     if (N1.isUndef())
6251       return getUNDEF(VT);
6252 
6253     // EXTRACT_SUBVECTOR of CONCAT_VECTOR can be simplified if the pieces of
6254     // the concat have the same type as the extract.
6255     if (N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0 &&
6256         VT == N1.getOperand(0).getValueType()) {
6257       unsigned Factor = VT.getVectorMinNumElements();
6258       return N1.getOperand(N2C->getZExtValue() / Factor);
6259     }
6260 
6261     // EXTRACT_SUBVECTOR of INSERT_SUBVECTOR is often created
6262     // during shuffle legalization.
6263     if (N1.getOpcode() == ISD::INSERT_SUBVECTOR && N2 == N1.getOperand(2) &&
6264         VT == N1.getOperand(1).getValueType())
6265       return N1.getOperand(1);
6266     break;
6267   }
6268   }
6269 
6270   // Perform trivial constant folding.
6271   if (SDValue SV = FoldConstantArithmetic(Opcode, DL, VT, {N1, N2}))
6272     return SV;
6273 
6274   // Canonicalize an UNDEF to the RHS, even over a constant.
6275   if (N1.isUndef()) {
6276     if (TLI->isCommutativeBinOp(Opcode)) {
6277       std::swap(N1, N2);
6278     } else {
6279       switch (Opcode) {
6280       case ISD::SUB:
6281         return getUNDEF(VT);     // fold op(undef, arg2) -> undef
6282       case ISD::SIGN_EXTEND_INREG:
6283       case ISD::UDIV:
6284       case ISD::SDIV:
6285       case ISD::UREM:
6286       case ISD::SREM:
6287       case ISD::SSUBSAT:
6288       case ISD::USUBSAT:
6289         return getConstant(0, DL, VT);    // fold op(undef, arg2) -> 0
6290       }
6291     }
6292   }
6293 
6294   // Fold a bunch of operators when the RHS is undef.
6295   if (N2.isUndef()) {
6296     switch (Opcode) {
6297     case ISD::XOR:
6298       if (N1.isUndef())
6299         // Handle undef ^ undef -> 0 special case. This is a common
6300         // idiom (misuse).
6301         return getConstant(0, DL, VT);
6302       LLVM_FALLTHROUGH;
6303     case ISD::ADD:
6304     case ISD::SUB:
6305     case ISD::UDIV:
6306     case ISD::SDIV:
6307     case ISD::UREM:
6308     case ISD::SREM:
6309       return getUNDEF(VT);       // fold op(arg1, undef) -> undef
6310     case ISD::MUL:
6311     case ISD::AND:
6312     case ISD::SSUBSAT:
6313     case ISD::USUBSAT:
6314       return getConstant(0, DL, VT);  // fold op(arg1, undef) -> 0
6315     case ISD::OR:
6316     case ISD::SADDSAT:
6317     case ISD::UADDSAT:
6318       return getAllOnesConstant(DL, VT);
6319     }
6320   }
6321 
6322   // Memoize this node if possible.
6323   SDNode *N;
6324   SDVTList VTs = getVTList(VT);
6325   SDValue Ops[] = {N1, N2};
6326   if (VT != MVT::Glue) {
6327     FoldingSetNodeID ID;
6328     AddNodeIDNode(ID, Opcode, VTs, Ops);
6329     void *IP = nullptr;
6330     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
6331       E->intersectFlagsWith(Flags);
6332       return SDValue(E, 0);
6333     }
6334 
6335     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6336     N->setFlags(Flags);
6337     createOperands(N, Ops);
6338     CSEMap.InsertNode(N, IP);
6339   } else {
6340     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6341     createOperands(N, Ops);
6342   }
6343 
6344   InsertNode(N);
6345   SDValue V = SDValue(N, 0);
6346   NewSDValueDbgMsg(V, "Creating new node: ", this);
6347   return V;
6348 }
6349 
6350 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6351                               SDValue N1, SDValue N2, SDValue N3) {
6352   SDNodeFlags Flags;
6353   if (Inserter)
6354     Flags = Inserter->getFlags();
6355   return getNode(Opcode, DL, VT, N1, N2, N3, Flags);
6356 }
6357 
6358 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6359                               SDValue N1, SDValue N2, SDValue N3,
6360                               const SDNodeFlags Flags) {
6361   assert(N1.getOpcode() != ISD::DELETED_NODE &&
6362          N2.getOpcode() != ISD::DELETED_NODE &&
6363          N3.getOpcode() != ISD::DELETED_NODE &&
6364          "Operand is DELETED_NODE!");
6365   // Perform various simplifications.
6366   switch (Opcode) {
6367   case ISD::FMA: {
6368     assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
6369     assert(N1.getValueType() == VT && N2.getValueType() == VT &&
6370            N3.getValueType() == VT && "FMA types must match!");
6371     ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6372     ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
6373     ConstantFPSDNode *N3CFP = dyn_cast<ConstantFPSDNode>(N3);
6374     if (N1CFP && N2CFP && N3CFP) {
6375       APFloat  V1 = N1CFP->getValueAPF();
6376       const APFloat &V2 = N2CFP->getValueAPF();
6377       const APFloat &V3 = N3CFP->getValueAPF();
6378       V1.fusedMultiplyAdd(V2, V3, APFloat::rmNearestTiesToEven);
6379       return getConstantFP(V1, DL, VT);
6380     }
6381     break;
6382   }
6383   case ISD::BUILD_VECTOR: {
6384     // Attempt to simplify BUILD_VECTOR.
6385     SDValue Ops[] = {N1, N2, N3};
6386     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
6387       return V;
6388     break;
6389   }
6390   case ISD::CONCAT_VECTORS: {
6391     SDValue Ops[] = {N1, N2, N3};
6392     if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
6393       return V;
6394     break;
6395   }
6396   case ISD::SETCC: {
6397     assert(VT.isInteger() && "SETCC result type must be an integer!");
6398     assert(N1.getValueType() == N2.getValueType() &&
6399            "SETCC operands must have the same type!");
6400     assert(VT.isVector() == N1.getValueType().isVector() &&
6401            "SETCC type should be vector iff the operand type is vector!");
6402     assert((!VT.isVector() || VT.getVectorElementCount() ==
6403                                   N1.getValueType().getVectorElementCount()) &&
6404            "SETCC vector element counts must match!");
6405     // Use FoldSetCC to simplify SETCC's.
6406     if (SDValue V = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL))
6407       return V;
6408     // Vector constant folding.
6409     SDValue Ops[] = {N1, N2, N3};
6410     if (SDValue V = FoldConstantArithmetic(Opcode, DL, VT, Ops)) {
6411       NewSDValueDbgMsg(V, "New node vector constant folding: ", this);
6412       return V;
6413     }
6414     break;
6415   }
6416   case ISD::SELECT:
6417   case ISD::VSELECT:
6418     if (SDValue V = simplifySelect(N1, N2, N3))
6419       return V;
6420     break;
6421   case ISD::VECTOR_SHUFFLE:
6422     llvm_unreachable("should use getVectorShuffle constructor!");
6423   case ISD::VECTOR_SPLICE: {
6424     if (cast<ConstantSDNode>(N3)->isNullValue())
6425       return N1;
6426     break;
6427   }
6428   case ISD::INSERT_VECTOR_ELT: {
6429     ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3);
6430     // INSERT_VECTOR_ELT into out-of-bounds element is an UNDEF, except
6431     // for scalable vectors where we will generate appropriate code to
6432     // deal with out-of-bounds cases correctly.
6433     if (N3C && N1.getValueType().isFixedLengthVector() &&
6434         N3C->getZExtValue() >= N1.getValueType().getVectorNumElements())
6435       return getUNDEF(VT);
6436 
6437     // Undefined index can be assumed out-of-bounds, so that's UNDEF too.
6438     if (N3.isUndef())
6439       return getUNDEF(VT);
6440 
6441     // If the inserted element is an UNDEF, just use the input vector.
6442     if (N2.isUndef())
6443       return N1;
6444 
6445     break;
6446   }
6447   case ISD::INSERT_SUBVECTOR: {
6448     // Inserting undef into undef is still undef.
6449     if (N1.isUndef() && N2.isUndef())
6450       return getUNDEF(VT);
6451 
6452     EVT N2VT = N2.getValueType();
6453     assert(VT == N1.getValueType() &&
6454            "Dest and insert subvector source types must match!");
6455     assert(VT.isVector() && N2VT.isVector() &&
6456            "Insert subvector VTs must be vectors!");
6457     assert((VT.isScalableVector() || N2VT.isFixedLengthVector()) &&
6458            "Cannot insert a scalable vector into a fixed length vector!");
6459     assert((VT.isScalableVector() != N2VT.isScalableVector() ||
6460             VT.getVectorMinNumElements() >= N2VT.getVectorMinNumElements()) &&
6461            "Insert subvector must be from smaller vector to larger vector!");
6462     assert(isa<ConstantSDNode>(N3) &&
6463            "Insert subvector index must be constant");
6464     assert((VT.isScalableVector() != N2VT.isScalableVector() ||
6465             (N2VT.getVectorMinNumElements() +
6466              cast<ConstantSDNode>(N3)->getZExtValue()) <=
6467                 VT.getVectorMinNumElements()) &&
6468            "Insert subvector overflow!");
6469     assert(cast<ConstantSDNode>(N3)->getAPIntValue().getBitWidth() ==
6470                TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() &&
6471            "Constant index for INSERT_SUBVECTOR has an invalid size");
6472 
6473     // Trivial insertion.
6474     if (VT == N2VT)
6475       return N2;
6476 
6477     // If this is an insert of an extracted vector into an undef vector, we
6478     // can just use the input to the extract.
6479     if (N1.isUndef() && N2.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
6480         N2.getOperand(1) == N3 && N2.getOperand(0).getValueType() == VT)
6481       return N2.getOperand(0);
6482     break;
6483   }
6484   case ISD::BITCAST:
6485     // Fold bit_convert nodes from a type to themselves.
6486     if (N1.getValueType() == VT)
6487       return N1;
6488     break;
6489   }
6490 
6491   // Memoize node if it doesn't produce a flag.
6492   SDNode *N;
6493   SDVTList VTs = getVTList(VT);
6494   SDValue Ops[] = {N1, N2, N3};
6495   if (VT != MVT::Glue) {
6496     FoldingSetNodeID ID;
6497     AddNodeIDNode(ID, Opcode, VTs, Ops);
6498     void *IP = nullptr;
6499     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
6500       E->intersectFlagsWith(Flags);
6501       return SDValue(E, 0);
6502     }
6503 
6504     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6505     N->setFlags(Flags);
6506     createOperands(N, Ops);
6507     CSEMap.InsertNode(N, IP);
6508   } else {
6509     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6510     createOperands(N, Ops);
6511   }
6512 
6513   InsertNode(N);
6514   SDValue V = SDValue(N, 0);
6515   NewSDValueDbgMsg(V, "Creating new node: ", this);
6516   return V;
6517 }
6518 
6519 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6520                               SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
6521   SDValue Ops[] = { N1, N2, N3, N4 };
6522   return getNode(Opcode, DL, VT, Ops);
6523 }
6524 
6525 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6526                               SDValue N1, SDValue N2, SDValue N3, SDValue N4,
6527                               SDValue N5) {
6528   SDValue Ops[] = { N1, N2, N3, N4, N5 };
6529   return getNode(Opcode, DL, VT, Ops);
6530 }
6531 
6532 /// getStackArgumentTokenFactor - Compute a TokenFactor to force all
6533 /// the incoming stack arguments to be loaded from the stack.
6534 SDValue SelectionDAG::getStackArgumentTokenFactor(SDValue Chain) {
6535   SmallVector<SDValue, 8> ArgChains;
6536 
6537   // Include the original chain at the beginning of the list. When this is
6538   // used by target LowerCall hooks, this helps legalize find the
6539   // CALLSEQ_BEGIN node.
6540   ArgChains.push_back(Chain);
6541 
6542   // Add a chain value for each stack argument.
6543   for (SDNode *U : getEntryNode().getNode()->uses())
6544     if (LoadSDNode *L = dyn_cast<LoadSDNode>(U))
6545       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
6546         if (FI->getIndex() < 0)
6547           ArgChains.push_back(SDValue(L, 1));
6548 
6549   // Build a tokenfactor for all the chains.
6550   return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
6551 }
6552 
6553 /// getMemsetValue - Vectorized representation of the memset value
6554 /// operand.
6555 static SDValue getMemsetValue(SDValue Value, EVT VT, SelectionDAG &DAG,
6556                               const SDLoc &dl) {
6557   assert(!Value.isUndef());
6558 
6559   unsigned NumBits = VT.getScalarSizeInBits();
6560   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
6561     assert(C->getAPIntValue().getBitWidth() == 8);
6562     APInt Val = APInt::getSplat(NumBits, C->getAPIntValue());
6563     if (VT.isInteger()) {
6564       bool IsOpaque = VT.getSizeInBits() > 64 ||
6565           !DAG.getTargetLoweringInfo().isLegalStoreImmediate(C->getSExtValue());
6566       return DAG.getConstant(Val, dl, VT, false, IsOpaque);
6567     }
6568     return DAG.getConstantFP(APFloat(DAG.EVTToAPFloatSemantics(VT), Val), dl,
6569                              VT);
6570   }
6571 
6572   assert(Value.getValueType() == MVT::i8 && "memset with non-byte fill value?");
6573   EVT IntVT = VT.getScalarType();
6574   if (!IntVT.isInteger())
6575     IntVT = EVT::getIntegerVT(*DAG.getContext(), IntVT.getSizeInBits());
6576 
6577   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, Value);
6578   if (NumBits > 8) {
6579     // Use a multiplication with 0x010101... to extend the input to the
6580     // required length.
6581     APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01));
6582     Value = DAG.getNode(ISD::MUL, dl, IntVT, Value,
6583                         DAG.getConstant(Magic, dl, IntVT));
6584   }
6585 
6586   if (VT != Value.getValueType() && !VT.isInteger())
6587     Value = DAG.getBitcast(VT.getScalarType(), Value);
6588   if (VT != Value.getValueType())
6589     Value = DAG.getSplatBuildVector(VT, dl, Value);
6590 
6591   return Value;
6592 }
6593 
6594 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
6595 /// used when a memcpy is turned into a memset when the source is a constant
6596 /// string ptr.
6597 static SDValue getMemsetStringVal(EVT VT, const SDLoc &dl, SelectionDAG &DAG,
6598                                   const TargetLowering &TLI,
6599                                   const ConstantDataArraySlice &Slice) {
6600   // Handle vector with all elements zero.
6601   if (Slice.Array == nullptr) {
6602     if (VT.isInteger())
6603       return DAG.getConstant(0, dl, VT);
6604     if (VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128)
6605       return DAG.getConstantFP(0.0, dl, VT);
6606     if (VT.isVector()) {
6607       unsigned NumElts = VT.getVectorNumElements();
6608       MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
6609       return DAG.getNode(ISD::BITCAST, dl, VT,
6610                          DAG.getConstant(0, dl,
6611                                          EVT::getVectorVT(*DAG.getContext(),
6612                                                           EltVT, NumElts)));
6613     }
6614     llvm_unreachable("Expected type!");
6615   }
6616 
6617   assert(!VT.isVector() && "Can't handle vector type here!");
6618   unsigned NumVTBits = VT.getSizeInBits();
6619   unsigned NumVTBytes = NumVTBits / 8;
6620   unsigned NumBytes = std::min(NumVTBytes, unsigned(Slice.Length));
6621 
6622   APInt Val(NumVTBits, 0);
6623   if (DAG.getDataLayout().isLittleEndian()) {
6624     for (unsigned i = 0; i != NumBytes; ++i)
6625       Val |= (uint64_t)(unsigned char)Slice[i] << i*8;
6626   } else {
6627     for (unsigned i = 0; i != NumBytes; ++i)
6628       Val |= (uint64_t)(unsigned char)Slice[i] << (NumVTBytes-i-1)*8;
6629   }
6630 
6631   // If the "cost" of materializing the integer immediate is less than the cost
6632   // of a load, then it is cost effective to turn the load into the immediate.
6633   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
6634   if (TLI.shouldConvertConstantLoadToIntImm(Val, Ty))
6635     return DAG.getConstant(Val, dl, VT);
6636   return SDValue();
6637 }
6638 
6639 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Base, TypeSize Offset,
6640                                            const SDLoc &DL,
6641                                            const SDNodeFlags Flags) {
6642   EVT VT = Base.getValueType();
6643   SDValue Index;
6644 
6645   if (Offset.isScalable())
6646     Index = getVScale(DL, Base.getValueType(),
6647                       APInt(Base.getValueSizeInBits().getFixedSize(),
6648                             Offset.getKnownMinSize()));
6649   else
6650     Index = getConstant(Offset.getFixedSize(), DL, VT);
6651 
6652   return getMemBasePlusOffset(Base, Index, DL, Flags);
6653 }
6654 
6655 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Ptr, SDValue Offset,
6656                                            const SDLoc &DL,
6657                                            const SDNodeFlags Flags) {
6658   assert(Offset.getValueType().isInteger());
6659   EVT BasePtrVT = Ptr.getValueType();
6660   return getNode(ISD::ADD, DL, BasePtrVT, Ptr, Offset, Flags);
6661 }
6662 
6663 /// Returns true if memcpy source is constant data.
6664 static bool isMemSrcFromConstant(SDValue Src, ConstantDataArraySlice &Slice) {
6665   uint64_t SrcDelta = 0;
6666   GlobalAddressSDNode *G = nullptr;
6667   if (Src.getOpcode() == ISD::GlobalAddress)
6668     G = cast<GlobalAddressSDNode>(Src);
6669   else if (Src.getOpcode() == ISD::ADD &&
6670            Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
6671            Src.getOperand(1).getOpcode() == ISD::Constant) {
6672     G = cast<GlobalAddressSDNode>(Src.getOperand(0));
6673     SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue();
6674   }
6675   if (!G)
6676     return false;
6677 
6678   return getConstantDataArrayInfo(G->getGlobal(), Slice, 8,
6679                                   SrcDelta + G->getOffset());
6680 }
6681 
6682 static bool shouldLowerMemFuncForSize(const MachineFunction &MF,
6683                                       SelectionDAG &DAG) {
6684   // On Darwin, -Os means optimize for size without hurting performance, so
6685   // only really optimize for size when -Oz (MinSize) is used.
6686   if (MF.getTarget().getTargetTriple().isOSDarwin())
6687     return MF.getFunction().hasMinSize();
6688   return DAG.shouldOptForSize();
6689 }
6690 
6691 static void chainLoadsAndStoresForMemcpy(SelectionDAG &DAG, const SDLoc &dl,
6692                           SmallVector<SDValue, 32> &OutChains, unsigned From,
6693                           unsigned To, SmallVector<SDValue, 16> &OutLoadChains,
6694                           SmallVector<SDValue, 16> &OutStoreChains) {
6695   assert(OutLoadChains.size() && "Missing loads in memcpy inlining");
6696   assert(OutStoreChains.size() && "Missing stores in memcpy inlining");
6697   SmallVector<SDValue, 16> GluedLoadChains;
6698   for (unsigned i = From; i < To; ++i) {
6699     OutChains.push_back(OutLoadChains[i]);
6700     GluedLoadChains.push_back(OutLoadChains[i]);
6701   }
6702 
6703   // Chain for all loads.
6704   SDValue LoadToken = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6705                                   GluedLoadChains);
6706 
6707   for (unsigned i = From; i < To; ++i) {
6708     StoreSDNode *ST = dyn_cast<StoreSDNode>(OutStoreChains[i]);
6709     SDValue NewStore = DAG.getTruncStore(LoadToken, dl, ST->getValue(),
6710                                   ST->getBasePtr(), ST->getMemoryVT(),
6711                                   ST->getMemOperand());
6712     OutChains.push_back(NewStore);
6713   }
6714 }
6715 
6716 static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
6717                                        SDValue Chain, SDValue Dst, SDValue Src,
6718                                        uint64_t Size, Align Alignment,
6719                                        bool isVol, bool AlwaysInline,
6720                                        MachinePointerInfo DstPtrInfo,
6721                                        MachinePointerInfo SrcPtrInfo,
6722                                        const AAMDNodes &AAInfo) {
6723   // Turn a memcpy of undef to nop.
6724   // FIXME: We need to honor volatile even is Src is undef.
6725   if (Src.isUndef())
6726     return Chain;
6727 
6728   // Expand memcpy to a series of load and store ops if the size operand falls
6729   // below a certain threshold.
6730   // TODO: In the AlwaysInline case, if the size is big then generate a loop
6731   // rather than maybe a humongous number of loads and stores.
6732   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6733   const DataLayout &DL = DAG.getDataLayout();
6734   LLVMContext &C = *DAG.getContext();
6735   std::vector<EVT> MemOps;
6736   bool DstAlignCanChange = false;
6737   MachineFunction &MF = DAG.getMachineFunction();
6738   MachineFrameInfo &MFI = MF.getFrameInfo();
6739   bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
6740   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
6741   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
6742     DstAlignCanChange = true;
6743   MaybeAlign SrcAlign = DAG.InferPtrAlign(Src);
6744   if (!SrcAlign || Alignment > *SrcAlign)
6745     SrcAlign = Alignment;
6746   assert(SrcAlign && "SrcAlign must be set");
6747   ConstantDataArraySlice Slice;
6748   // If marked as volatile, perform a copy even when marked as constant.
6749   bool CopyFromConstant = !isVol && isMemSrcFromConstant(Src, Slice);
6750   bool isZeroConstant = CopyFromConstant && Slice.Array == nullptr;
6751   unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize);
6752   const MemOp Op = isZeroConstant
6753                        ? MemOp::Set(Size, DstAlignCanChange, Alignment,
6754                                     /*IsZeroMemset*/ true, isVol)
6755                        : MemOp::Copy(Size, DstAlignCanChange, Alignment,
6756                                      *SrcAlign, isVol, CopyFromConstant);
6757   if (!TLI.findOptimalMemOpLowering(
6758           MemOps, Limit, Op, DstPtrInfo.getAddrSpace(),
6759           SrcPtrInfo.getAddrSpace(), MF.getFunction().getAttributes()))
6760     return SDValue();
6761 
6762   if (DstAlignCanChange) {
6763     Type *Ty = MemOps[0].getTypeForEVT(C);
6764     Align NewAlign = DL.getABITypeAlign(Ty);
6765 
6766     // Don't promote to an alignment that would require dynamic stack
6767     // realignment.
6768     const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
6769     if (!TRI->hasStackRealignment(MF))
6770       while (NewAlign > Alignment && DL.exceedsNaturalStackAlignment(NewAlign))
6771         NewAlign = NewAlign.previous();
6772 
6773     if (NewAlign > Alignment) {
6774       // Give the stack frame object a larger alignment if needed.
6775       if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
6776         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
6777       Alignment = NewAlign;
6778     }
6779   }
6780 
6781   // Prepare AAInfo for loads/stores after lowering this memcpy.
6782   AAMDNodes NewAAInfo = AAInfo;
6783   NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
6784 
6785   MachineMemOperand::Flags MMOFlags =
6786       isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
6787   SmallVector<SDValue, 16> OutLoadChains;
6788   SmallVector<SDValue, 16> OutStoreChains;
6789   SmallVector<SDValue, 32> OutChains;
6790   unsigned NumMemOps = MemOps.size();
6791   uint64_t SrcOff = 0, DstOff = 0;
6792   for (unsigned i = 0; i != NumMemOps; ++i) {
6793     EVT VT = MemOps[i];
6794     unsigned VTSize = VT.getSizeInBits() / 8;
6795     SDValue Value, Store;
6796 
6797     if (VTSize > Size) {
6798       // Issuing an unaligned load / store pair  that overlaps with the previous
6799       // pair. Adjust the offset accordingly.
6800       assert(i == NumMemOps-1 && i != 0);
6801       SrcOff -= VTSize - Size;
6802       DstOff -= VTSize - Size;
6803     }
6804 
6805     if (CopyFromConstant &&
6806         (isZeroConstant || (VT.isInteger() && !VT.isVector()))) {
6807       // It's unlikely a store of a vector immediate can be done in a single
6808       // instruction. It would require a load from a constantpool first.
6809       // We only handle zero vectors here.
6810       // FIXME: Handle other cases where store of vector immediate is done in
6811       // a single instruction.
6812       ConstantDataArraySlice SubSlice;
6813       if (SrcOff < Slice.Length) {
6814         SubSlice = Slice;
6815         SubSlice.move(SrcOff);
6816       } else {
6817         // This is an out-of-bounds access and hence UB. Pretend we read zero.
6818         SubSlice.Array = nullptr;
6819         SubSlice.Offset = 0;
6820         SubSlice.Length = VTSize;
6821       }
6822       Value = getMemsetStringVal(VT, dl, DAG, TLI, SubSlice);
6823       if (Value.getNode()) {
6824         Store = DAG.getStore(
6825             Chain, dl, Value,
6826             DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6827             DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo);
6828         OutChains.push_back(Store);
6829       }
6830     }
6831 
6832     if (!Store.getNode()) {
6833       // The type might not be legal for the target.  This should only happen
6834       // if the type is smaller than a legal type, as on PPC, so the right
6835       // thing to do is generate a LoadExt/StoreTrunc pair.  These simplify
6836       // to Load/Store if NVT==VT.
6837       // FIXME does the case above also need this?
6838       EVT NVT = TLI.getTypeToTransformTo(C, VT);
6839       assert(NVT.bitsGE(VT));
6840 
6841       bool isDereferenceable =
6842         SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
6843       MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
6844       if (isDereferenceable)
6845         SrcMMOFlags |= MachineMemOperand::MODereferenceable;
6846 
6847       Value = DAG.getExtLoad(
6848           ISD::EXTLOAD, dl, NVT, Chain,
6849           DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl),
6850           SrcPtrInfo.getWithOffset(SrcOff), VT,
6851           commonAlignment(*SrcAlign, SrcOff), SrcMMOFlags, NewAAInfo);
6852       OutLoadChains.push_back(Value.getValue(1));
6853 
6854       Store = DAG.getTruncStore(
6855           Chain, dl, Value,
6856           DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6857           DstPtrInfo.getWithOffset(DstOff), VT, Alignment, MMOFlags, NewAAInfo);
6858       OutStoreChains.push_back(Store);
6859     }
6860     SrcOff += VTSize;
6861     DstOff += VTSize;
6862     Size -= VTSize;
6863   }
6864 
6865   unsigned GluedLdStLimit = MaxLdStGlue == 0 ?
6866                                 TLI.getMaxGluedStoresPerMemcpy() : MaxLdStGlue;
6867   unsigned NumLdStInMemcpy = OutStoreChains.size();
6868 
6869   if (NumLdStInMemcpy) {
6870     // It may be that memcpy might be converted to memset if it's memcpy
6871     // of constants. In such a case, we won't have loads and stores, but
6872     // just stores. In the absence of loads, there is nothing to gang up.
6873     if ((GluedLdStLimit <= 1) || !EnableMemCpyDAGOpt) {
6874       // If target does not care, just leave as it.
6875       for (unsigned i = 0; i < NumLdStInMemcpy; ++i) {
6876         OutChains.push_back(OutLoadChains[i]);
6877         OutChains.push_back(OutStoreChains[i]);
6878       }
6879     } else {
6880       // Ld/St less than/equal limit set by target.
6881       if (NumLdStInMemcpy <= GluedLdStLimit) {
6882           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
6883                                         NumLdStInMemcpy, OutLoadChains,
6884                                         OutStoreChains);
6885       } else {
6886         unsigned NumberLdChain =  NumLdStInMemcpy / GluedLdStLimit;
6887         unsigned RemainingLdStInMemcpy = NumLdStInMemcpy % GluedLdStLimit;
6888         unsigned GlueIter = 0;
6889 
6890         for (unsigned cnt = 0; cnt < NumberLdChain; ++cnt) {
6891           unsigned IndexFrom = NumLdStInMemcpy - GlueIter - GluedLdStLimit;
6892           unsigned IndexTo   = NumLdStInMemcpy - GlueIter;
6893 
6894           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, IndexFrom, IndexTo,
6895                                        OutLoadChains, OutStoreChains);
6896           GlueIter += GluedLdStLimit;
6897         }
6898 
6899         // Residual ld/st.
6900         if (RemainingLdStInMemcpy) {
6901           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
6902                                         RemainingLdStInMemcpy, OutLoadChains,
6903                                         OutStoreChains);
6904         }
6905       }
6906     }
6907   }
6908   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
6909 }
6910 
6911 static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
6912                                         SDValue Chain, SDValue Dst, SDValue Src,
6913                                         uint64_t Size, Align Alignment,
6914                                         bool isVol, bool AlwaysInline,
6915                                         MachinePointerInfo DstPtrInfo,
6916                                         MachinePointerInfo SrcPtrInfo,
6917                                         const AAMDNodes &AAInfo) {
6918   // Turn a memmove of undef to nop.
6919   // FIXME: We need to honor volatile even is Src is undef.
6920   if (Src.isUndef())
6921     return Chain;
6922 
6923   // Expand memmove to a series of load and store ops if the size operand falls
6924   // below a certain threshold.
6925   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6926   const DataLayout &DL = DAG.getDataLayout();
6927   LLVMContext &C = *DAG.getContext();
6928   std::vector<EVT> MemOps;
6929   bool DstAlignCanChange = false;
6930   MachineFunction &MF = DAG.getMachineFunction();
6931   MachineFrameInfo &MFI = MF.getFrameInfo();
6932   bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
6933   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
6934   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
6935     DstAlignCanChange = true;
6936   MaybeAlign SrcAlign = DAG.InferPtrAlign(Src);
6937   if (!SrcAlign || Alignment > *SrcAlign)
6938     SrcAlign = Alignment;
6939   assert(SrcAlign && "SrcAlign must be set");
6940   unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize);
6941   if (!TLI.findOptimalMemOpLowering(
6942           MemOps, Limit,
6943           MemOp::Copy(Size, DstAlignCanChange, Alignment, *SrcAlign,
6944                       /*IsVolatile*/ true),
6945           DstPtrInfo.getAddrSpace(), SrcPtrInfo.getAddrSpace(),
6946           MF.getFunction().getAttributes()))
6947     return SDValue();
6948 
6949   if (DstAlignCanChange) {
6950     Type *Ty = MemOps[0].getTypeForEVT(C);
6951     Align NewAlign = DL.getABITypeAlign(Ty);
6952     if (NewAlign > Alignment) {
6953       // Give the stack frame object a larger alignment if needed.
6954       if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
6955         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
6956       Alignment = NewAlign;
6957     }
6958   }
6959 
6960   // Prepare AAInfo for loads/stores after lowering this memmove.
6961   AAMDNodes NewAAInfo = AAInfo;
6962   NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
6963 
6964   MachineMemOperand::Flags MMOFlags =
6965       isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
6966   uint64_t SrcOff = 0, DstOff = 0;
6967   SmallVector<SDValue, 8> LoadValues;
6968   SmallVector<SDValue, 8> LoadChains;
6969   SmallVector<SDValue, 8> OutChains;
6970   unsigned NumMemOps = MemOps.size();
6971   for (unsigned i = 0; i < NumMemOps; i++) {
6972     EVT VT = MemOps[i];
6973     unsigned VTSize = VT.getSizeInBits() / 8;
6974     SDValue Value;
6975 
6976     bool isDereferenceable =
6977       SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
6978     MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
6979     if (isDereferenceable)
6980       SrcMMOFlags |= MachineMemOperand::MODereferenceable;
6981 
6982     Value = DAG.getLoad(
6983         VT, dl, Chain,
6984         DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl),
6985         SrcPtrInfo.getWithOffset(SrcOff), *SrcAlign, SrcMMOFlags, NewAAInfo);
6986     LoadValues.push_back(Value);
6987     LoadChains.push_back(Value.getValue(1));
6988     SrcOff += VTSize;
6989   }
6990   Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
6991   OutChains.clear();
6992   for (unsigned i = 0; i < NumMemOps; i++) {
6993     EVT VT = MemOps[i];
6994     unsigned VTSize = VT.getSizeInBits() / 8;
6995     SDValue Store;
6996 
6997     Store = DAG.getStore(
6998         Chain, dl, LoadValues[i],
6999         DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
7000         DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo);
7001     OutChains.push_back(Store);
7002     DstOff += VTSize;
7003   }
7004 
7005   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
7006 }
7007 
7008 /// Lower the call to 'memset' intrinsic function into a series of store
7009 /// operations.
7010 ///
7011 /// \param DAG Selection DAG where lowered code is placed.
7012 /// \param dl Link to corresponding IR location.
7013 /// \param Chain Control flow dependency.
7014 /// \param Dst Pointer to destination memory location.
7015 /// \param Src Value of byte to write into the memory.
7016 /// \param Size Number of bytes to write.
7017 /// \param Alignment Alignment of the destination in bytes.
7018 /// \param isVol True if destination is volatile.
7019 /// \param AlwaysInline Makes sure no function call is generated.
7020 /// \param DstPtrInfo IR information on the memory pointer.
7021 /// \returns New head in the control flow, if lowering was successful, empty
7022 /// SDValue otherwise.
7023 ///
7024 /// The function tries to replace 'llvm.memset' intrinsic with several store
7025 /// operations and value calculation code. This is usually profitable for small
7026 /// memory size or when the semantic requires inlining.
7027 static SDValue getMemsetStores(SelectionDAG &DAG, const SDLoc &dl,
7028                                SDValue Chain, SDValue Dst, SDValue Src,
7029                                uint64_t Size, Align Alignment, bool isVol,
7030                                bool AlwaysInline, MachinePointerInfo DstPtrInfo,
7031                                const AAMDNodes &AAInfo) {
7032   // Turn a memset of undef to nop.
7033   // FIXME: We need to honor volatile even is Src is undef.
7034   if (Src.isUndef())
7035     return Chain;
7036 
7037   // Expand memset to a series of load/store ops if the size operand
7038   // falls below a certain threshold.
7039   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7040   std::vector<EVT> MemOps;
7041   bool DstAlignCanChange = false;
7042   MachineFunction &MF = DAG.getMachineFunction();
7043   MachineFrameInfo &MFI = MF.getFrameInfo();
7044   bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
7045   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
7046   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
7047     DstAlignCanChange = true;
7048   bool IsZeroVal =
7049       isa<ConstantSDNode>(Src) && cast<ConstantSDNode>(Src)->isZero();
7050   unsigned Limit = AlwaysInline ? ~0 : TLI.getMaxStoresPerMemset(OptSize);
7051 
7052   if (!TLI.findOptimalMemOpLowering(
7053           MemOps, Limit,
7054           MemOp::Set(Size, DstAlignCanChange, Alignment, IsZeroVal, isVol),
7055           DstPtrInfo.getAddrSpace(), ~0u, MF.getFunction().getAttributes()))
7056     return SDValue();
7057 
7058   if (DstAlignCanChange) {
7059     Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
7060     Align NewAlign = DAG.getDataLayout().getABITypeAlign(Ty);
7061     if (NewAlign > Alignment) {
7062       // Give the stack frame object a larger alignment if needed.
7063       if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
7064         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
7065       Alignment = NewAlign;
7066     }
7067   }
7068 
7069   SmallVector<SDValue, 8> OutChains;
7070   uint64_t DstOff = 0;
7071   unsigned NumMemOps = MemOps.size();
7072 
7073   // Find the largest store and generate the bit pattern for it.
7074   EVT LargestVT = MemOps[0];
7075   for (unsigned i = 1; i < NumMemOps; i++)
7076     if (MemOps[i].bitsGT(LargestVT))
7077       LargestVT = MemOps[i];
7078   SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl);
7079 
7080   // Prepare AAInfo for loads/stores after lowering this memset.
7081   AAMDNodes NewAAInfo = AAInfo;
7082   NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
7083 
7084   for (unsigned i = 0; i < NumMemOps; i++) {
7085     EVT VT = MemOps[i];
7086     unsigned VTSize = VT.getSizeInBits() / 8;
7087     if (VTSize > Size) {
7088       // Issuing an unaligned load / store pair  that overlaps with the previous
7089       // pair. Adjust the offset accordingly.
7090       assert(i == NumMemOps-1 && i != 0);
7091       DstOff -= VTSize - Size;
7092     }
7093 
7094     // If this store is smaller than the largest store see whether we can get
7095     // the smaller value for free with a truncate.
7096     SDValue Value = MemSetValue;
7097     if (VT.bitsLT(LargestVT)) {
7098       if (!LargestVT.isVector() && !VT.isVector() &&
7099           TLI.isTruncateFree(LargestVT, VT))
7100         Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue);
7101       else
7102         Value = getMemsetValue(Src, VT, DAG, dl);
7103     }
7104     assert(Value.getValueType() == VT && "Value with wrong type.");
7105     SDValue Store = DAG.getStore(
7106         Chain, dl, Value,
7107         DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
7108         DstPtrInfo.getWithOffset(DstOff), Alignment,
7109         isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone,
7110         NewAAInfo);
7111     OutChains.push_back(Store);
7112     DstOff += VT.getSizeInBits() / 8;
7113     Size -= VTSize;
7114   }
7115 
7116   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
7117 }
7118 
7119 static void checkAddrSpaceIsValidForLibcall(const TargetLowering *TLI,
7120                                             unsigned AS) {
7121   // Lowering memcpy / memset / memmove intrinsics to calls is only valid if all
7122   // pointer operands can be losslessly bitcasted to pointers of address space 0
7123   if (AS != 0 && !TLI->getTargetMachine().isNoopAddrSpaceCast(AS, 0)) {
7124     report_fatal_error("cannot lower memory intrinsic in address space " +
7125                        Twine(AS));
7126   }
7127 }
7128 
7129 SDValue SelectionDAG::getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst,
7130                                 SDValue Src, SDValue Size, Align Alignment,
7131                                 bool isVol, bool AlwaysInline, bool isTailCall,
7132                                 MachinePointerInfo DstPtrInfo,
7133                                 MachinePointerInfo SrcPtrInfo,
7134                                 const AAMDNodes &AAInfo) {
7135   // Check to see if we should lower the memcpy to loads and stores first.
7136   // For cases within the target-specified limits, this is the best choice.
7137   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
7138   if (ConstantSize) {
7139     // Memcpy with size zero? Just return the original chain.
7140     if (ConstantSize->isZero())
7141       return Chain;
7142 
7143     SDValue Result = getMemcpyLoadsAndStores(
7144         *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment,
7145         isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo);
7146     if (Result.getNode())
7147       return Result;
7148   }
7149 
7150   // Then check to see if we should lower the memcpy with target-specific
7151   // code. If the target chooses to do this, this is the next best.
7152   if (TSI) {
7153     SDValue Result = TSI->EmitTargetCodeForMemcpy(
7154         *this, dl, Chain, Dst, Src, Size, Alignment, isVol, AlwaysInline,
7155         DstPtrInfo, SrcPtrInfo);
7156     if (Result.getNode())
7157       return Result;
7158   }
7159 
7160   // If we really need inline code and the target declined to provide it,
7161   // use a (potentially long) sequence of loads and stores.
7162   if (AlwaysInline) {
7163     assert(ConstantSize && "AlwaysInline requires a constant size!");
7164     return getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
7165                                    ConstantSize->getZExtValue(), Alignment,
7166                                    isVol, true, DstPtrInfo, SrcPtrInfo, AAInfo);
7167   }
7168 
7169   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
7170   checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
7171 
7172   // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc
7173   // memcpy is not guaranteed to be safe. libc memcpys aren't required to
7174   // respect volatile, so they may do things like read or write memory
7175   // beyond the given memory regions. But fixing this isn't easy, and most
7176   // people don't care.
7177 
7178   // Emit a library call.
7179   TargetLowering::ArgListTy Args;
7180   TargetLowering::ArgListEntry Entry;
7181   Entry.Ty = Type::getInt8PtrTy(*getContext());
7182   Entry.Node = Dst; Args.push_back(Entry);
7183   Entry.Node = Src; Args.push_back(Entry);
7184 
7185   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7186   Entry.Node = Size; Args.push_back(Entry);
7187   // FIXME: pass in SDLoc
7188   TargetLowering::CallLoweringInfo CLI(*this);
7189   CLI.setDebugLoc(dl)
7190       .setChain(Chain)
7191       .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMCPY),
7192                     Dst.getValueType().getTypeForEVT(*getContext()),
7193                     getExternalSymbol(TLI->getLibcallName(RTLIB::MEMCPY),
7194                                       TLI->getPointerTy(getDataLayout())),
7195                     std::move(Args))
7196       .setDiscardResult()
7197       .setTailCall(isTailCall);
7198 
7199   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
7200   return CallResult.second;
7201 }
7202 
7203 SDValue SelectionDAG::getAtomicMemcpy(SDValue Chain, const SDLoc &dl,
7204                                       SDValue Dst, SDValue Src, SDValue Size,
7205                                       Type *SizeTy, unsigned ElemSz,
7206                                       bool isTailCall,
7207                                       MachinePointerInfo DstPtrInfo,
7208                                       MachinePointerInfo SrcPtrInfo) {
7209   // Emit a library call.
7210   TargetLowering::ArgListTy Args;
7211   TargetLowering::ArgListEntry Entry;
7212   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7213   Entry.Node = Dst;
7214   Args.push_back(Entry);
7215 
7216   Entry.Node = Src;
7217   Args.push_back(Entry);
7218 
7219   Entry.Ty = SizeTy;
7220   Entry.Node = Size;
7221   Args.push_back(Entry);
7222 
7223   RTLIB::Libcall LibraryCall =
7224       RTLIB::getMEMCPY_ELEMENT_UNORDERED_ATOMIC(ElemSz);
7225   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
7226     report_fatal_error("Unsupported element size");
7227 
7228   TargetLowering::CallLoweringInfo CLI(*this);
7229   CLI.setDebugLoc(dl)
7230       .setChain(Chain)
7231       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
7232                     Type::getVoidTy(*getContext()),
7233                     getExternalSymbol(TLI->getLibcallName(LibraryCall),
7234                                       TLI->getPointerTy(getDataLayout())),
7235                     std::move(Args))
7236       .setDiscardResult()
7237       .setTailCall(isTailCall);
7238 
7239   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
7240   return CallResult.second;
7241 }
7242 
7243 SDValue SelectionDAG::getMemmove(SDValue Chain, const SDLoc &dl, SDValue Dst,
7244                                  SDValue Src, SDValue Size, Align Alignment,
7245                                  bool isVol, bool isTailCall,
7246                                  MachinePointerInfo DstPtrInfo,
7247                                  MachinePointerInfo SrcPtrInfo,
7248                                  const AAMDNodes &AAInfo) {
7249   // Check to see if we should lower the memmove to loads and stores first.
7250   // For cases within the target-specified limits, this is the best choice.
7251   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
7252   if (ConstantSize) {
7253     // Memmove with size zero? Just return the original chain.
7254     if (ConstantSize->isZero())
7255       return Chain;
7256 
7257     SDValue Result = getMemmoveLoadsAndStores(
7258         *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment,
7259         isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo);
7260     if (Result.getNode())
7261       return Result;
7262   }
7263 
7264   // Then check to see if we should lower the memmove with target-specific
7265   // code. If the target chooses to do this, this is the next best.
7266   if (TSI) {
7267     SDValue Result =
7268         TSI->EmitTargetCodeForMemmove(*this, dl, Chain, Dst, Src, Size,
7269                                       Alignment, isVol, DstPtrInfo, SrcPtrInfo);
7270     if (Result.getNode())
7271       return Result;
7272   }
7273 
7274   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
7275   checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
7276 
7277   // FIXME: If the memmove is volatile, lowering it to plain libc memmove may
7278   // not be safe.  See memcpy above for more details.
7279 
7280   // Emit a library call.
7281   TargetLowering::ArgListTy Args;
7282   TargetLowering::ArgListEntry Entry;
7283   Entry.Ty = Type::getInt8PtrTy(*getContext());
7284   Entry.Node = Dst; Args.push_back(Entry);
7285   Entry.Node = Src; Args.push_back(Entry);
7286 
7287   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7288   Entry.Node = Size; Args.push_back(Entry);
7289   // FIXME:  pass in SDLoc
7290   TargetLowering::CallLoweringInfo CLI(*this);
7291   CLI.setDebugLoc(dl)
7292       .setChain(Chain)
7293       .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMMOVE),
7294                     Dst.getValueType().getTypeForEVT(*getContext()),
7295                     getExternalSymbol(TLI->getLibcallName(RTLIB::MEMMOVE),
7296                                       TLI->getPointerTy(getDataLayout())),
7297                     std::move(Args))
7298       .setDiscardResult()
7299       .setTailCall(isTailCall);
7300 
7301   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
7302   return CallResult.second;
7303 }
7304 
7305 SDValue SelectionDAG::getAtomicMemmove(SDValue Chain, const SDLoc &dl,
7306                                        SDValue Dst, SDValue Src, SDValue Size,
7307                                        Type *SizeTy, unsigned ElemSz,
7308                                        bool isTailCall,
7309                                        MachinePointerInfo DstPtrInfo,
7310                                        MachinePointerInfo SrcPtrInfo) {
7311   // Emit a library call.
7312   TargetLowering::ArgListTy Args;
7313   TargetLowering::ArgListEntry Entry;
7314   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7315   Entry.Node = Dst;
7316   Args.push_back(Entry);
7317 
7318   Entry.Node = Src;
7319   Args.push_back(Entry);
7320 
7321   Entry.Ty = SizeTy;
7322   Entry.Node = Size;
7323   Args.push_back(Entry);
7324 
7325   RTLIB::Libcall LibraryCall =
7326       RTLIB::getMEMMOVE_ELEMENT_UNORDERED_ATOMIC(ElemSz);
7327   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
7328     report_fatal_error("Unsupported element size");
7329 
7330   TargetLowering::CallLoweringInfo CLI(*this);
7331   CLI.setDebugLoc(dl)
7332       .setChain(Chain)
7333       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
7334                     Type::getVoidTy(*getContext()),
7335                     getExternalSymbol(TLI->getLibcallName(LibraryCall),
7336                                       TLI->getPointerTy(getDataLayout())),
7337                     std::move(Args))
7338       .setDiscardResult()
7339       .setTailCall(isTailCall);
7340 
7341   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
7342   return CallResult.second;
7343 }
7344 
7345 SDValue SelectionDAG::getMemset(SDValue Chain, const SDLoc &dl, SDValue Dst,
7346                                 SDValue Src, SDValue Size, Align Alignment,
7347                                 bool isVol, bool AlwaysInline, bool isTailCall,
7348                                 MachinePointerInfo DstPtrInfo,
7349                                 const AAMDNodes &AAInfo) {
7350   // Check to see if we should lower the memset to stores first.
7351   // For cases within the target-specified limits, this is the best choice.
7352   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
7353   if (ConstantSize) {
7354     // Memset with size zero? Just return the original chain.
7355     if (ConstantSize->isZero())
7356       return Chain;
7357 
7358     SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src,
7359                                      ConstantSize->getZExtValue(), Alignment,
7360                                      isVol, false, DstPtrInfo, AAInfo);
7361 
7362     if (Result.getNode())
7363       return Result;
7364   }
7365 
7366   // Then check to see if we should lower the memset with target-specific
7367   // code. If the target chooses to do this, this is the next best.
7368   if (TSI) {
7369     SDValue Result = TSI->EmitTargetCodeForMemset(
7370         *this, dl, Chain, Dst, Src, Size, Alignment, isVol, AlwaysInline, DstPtrInfo);
7371     if (Result.getNode())
7372       return Result;
7373   }
7374 
7375   // If we really need inline code and the target declined to provide it,
7376   // use a (potentially long) sequence of loads and stores.
7377   if (AlwaysInline) {
7378     assert(ConstantSize && "AlwaysInline requires a constant size!");
7379     SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src,
7380                                      ConstantSize->getZExtValue(), Alignment,
7381                                      isVol, true, DstPtrInfo, AAInfo);
7382     assert(Result &&
7383            "getMemsetStores must return a valid sequence when AlwaysInline");
7384     return Result;
7385   }
7386 
7387   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
7388 
7389   // Emit a library call.
7390   auto &Ctx = *getContext();
7391   const auto& DL = getDataLayout();
7392 
7393   TargetLowering::CallLoweringInfo CLI(*this);
7394   // FIXME: pass in SDLoc
7395   CLI.setDebugLoc(dl).setChain(Chain);
7396 
7397   ConstantSDNode *ConstantSrc = dyn_cast<ConstantSDNode>(Src);
7398   const bool SrcIsZero = ConstantSrc && ConstantSrc->isZero();
7399   const char *BzeroName = getTargetLoweringInfo().getLibcallName(RTLIB::BZERO);
7400 
7401   // Helper function to create an Entry from Node and Type.
7402   const auto CreateEntry = [](SDValue Node, Type *Ty) {
7403     TargetLowering::ArgListEntry Entry;
7404     Entry.Node = Node;
7405     Entry.Ty = Ty;
7406     return Entry;
7407   };
7408 
7409   // If zeroing out and bzero is present, use it.
7410   if (SrcIsZero && BzeroName) {
7411     TargetLowering::ArgListTy Args;
7412     Args.push_back(CreateEntry(Dst, Type::getInt8PtrTy(Ctx)));
7413     Args.push_back(CreateEntry(Size, DL.getIntPtrType(Ctx)));
7414     CLI.setLibCallee(
7415         TLI->getLibcallCallingConv(RTLIB::BZERO), Type::getVoidTy(Ctx),
7416         getExternalSymbol(BzeroName, TLI->getPointerTy(DL)), std::move(Args));
7417   } else {
7418     TargetLowering::ArgListTy Args;
7419     Args.push_back(CreateEntry(Dst, Type::getInt8PtrTy(Ctx)));
7420     Args.push_back(CreateEntry(Src, Src.getValueType().getTypeForEVT(Ctx)));
7421     Args.push_back(CreateEntry(Size, DL.getIntPtrType(Ctx)));
7422     CLI.setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMSET),
7423                      Dst.getValueType().getTypeForEVT(Ctx),
7424                      getExternalSymbol(TLI->getLibcallName(RTLIB::MEMSET),
7425                                        TLI->getPointerTy(DL)),
7426                      std::move(Args));
7427   }
7428 
7429   CLI.setDiscardResult().setTailCall(isTailCall);
7430 
7431   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
7432   return CallResult.second;
7433 }
7434 
7435 SDValue SelectionDAG::getAtomicMemset(SDValue Chain, const SDLoc &dl,
7436                                       SDValue Dst, SDValue Value, SDValue Size,
7437                                       Type *SizeTy, unsigned ElemSz,
7438                                       bool isTailCall,
7439                                       MachinePointerInfo DstPtrInfo) {
7440   // Emit a library call.
7441   TargetLowering::ArgListTy Args;
7442   TargetLowering::ArgListEntry Entry;
7443   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7444   Entry.Node = Dst;
7445   Args.push_back(Entry);
7446 
7447   Entry.Ty = Type::getInt8Ty(*getContext());
7448   Entry.Node = Value;
7449   Args.push_back(Entry);
7450 
7451   Entry.Ty = SizeTy;
7452   Entry.Node = Size;
7453   Args.push_back(Entry);
7454 
7455   RTLIB::Libcall LibraryCall =
7456       RTLIB::getMEMSET_ELEMENT_UNORDERED_ATOMIC(ElemSz);
7457   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
7458     report_fatal_error("Unsupported element size");
7459 
7460   TargetLowering::CallLoweringInfo CLI(*this);
7461   CLI.setDebugLoc(dl)
7462       .setChain(Chain)
7463       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
7464                     Type::getVoidTy(*getContext()),
7465                     getExternalSymbol(TLI->getLibcallName(LibraryCall),
7466                                       TLI->getPointerTy(getDataLayout())),
7467                     std::move(Args))
7468       .setDiscardResult()
7469       .setTailCall(isTailCall);
7470 
7471   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
7472   return CallResult.second;
7473 }
7474 
7475 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
7476                                 SDVTList VTList, ArrayRef<SDValue> Ops,
7477                                 MachineMemOperand *MMO) {
7478   FoldingSetNodeID ID;
7479   ID.AddInteger(MemVT.getRawBits());
7480   AddNodeIDNode(ID, Opcode, VTList, Ops);
7481   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7482   ID.AddInteger(MMO->getFlags());
7483   void* IP = nullptr;
7484   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7485     cast<AtomicSDNode>(E)->refineAlignment(MMO);
7486     return SDValue(E, 0);
7487   }
7488 
7489   auto *N = newSDNode<AtomicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
7490                                     VTList, MemVT, MMO);
7491   createOperands(N, Ops);
7492 
7493   CSEMap.InsertNode(N, IP);
7494   InsertNode(N);
7495   return SDValue(N, 0);
7496 }
7497 
7498 SDValue SelectionDAG::getAtomicCmpSwap(unsigned Opcode, const SDLoc &dl,
7499                                        EVT MemVT, SDVTList VTs, SDValue Chain,
7500                                        SDValue Ptr, SDValue Cmp, SDValue Swp,
7501                                        MachineMemOperand *MMO) {
7502   assert(Opcode == ISD::ATOMIC_CMP_SWAP ||
7503          Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
7504   assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
7505 
7506   SDValue Ops[] = {Chain, Ptr, Cmp, Swp};
7507   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
7508 }
7509 
7510 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
7511                                 SDValue Chain, SDValue Ptr, SDValue Val,
7512                                 MachineMemOperand *MMO) {
7513   assert((Opcode == ISD::ATOMIC_LOAD_ADD ||
7514           Opcode == ISD::ATOMIC_LOAD_SUB ||
7515           Opcode == ISD::ATOMIC_LOAD_AND ||
7516           Opcode == ISD::ATOMIC_LOAD_CLR ||
7517           Opcode == ISD::ATOMIC_LOAD_OR ||
7518           Opcode == ISD::ATOMIC_LOAD_XOR ||
7519           Opcode == ISD::ATOMIC_LOAD_NAND ||
7520           Opcode == ISD::ATOMIC_LOAD_MIN ||
7521           Opcode == ISD::ATOMIC_LOAD_MAX ||
7522           Opcode == ISD::ATOMIC_LOAD_UMIN ||
7523           Opcode == ISD::ATOMIC_LOAD_UMAX ||
7524           Opcode == ISD::ATOMIC_LOAD_FADD ||
7525           Opcode == ISD::ATOMIC_LOAD_FSUB ||
7526           Opcode == ISD::ATOMIC_LOAD_FMAX ||
7527           Opcode == ISD::ATOMIC_LOAD_FMIN ||
7528           Opcode == ISD::ATOMIC_SWAP ||
7529           Opcode == ISD::ATOMIC_STORE) &&
7530          "Invalid Atomic Op");
7531 
7532   EVT VT = Val.getValueType();
7533 
7534   SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) :
7535                                                getVTList(VT, MVT::Other);
7536   SDValue Ops[] = {Chain, Ptr, Val};
7537   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
7538 }
7539 
7540 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
7541                                 EVT VT, SDValue Chain, SDValue Ptr,
7542                                 MachineMemOperand *MMO) {
7543   assert(Opcode == ISD::ATOMIC_LOAD && "Invalid Atomic Op");
7544 
7545   SDVTList VTs = getVTList(VT, MVT::Other);
7546   SDValue Ops[] = {Chain, Ptr};
7547   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
7548 }
7549 
7550 /// getMergeValues - Create a MERGE_VALUES node from the given operands.
7551 SDValue SelectionDAG::getMergeValues(ArrayRef<SDValue> Ops, const SDLoc &dl) {
7552   if (Ops.size() == 1)
7553     return Ops[0];
7554 
7555   SmallVector<EVT, 4> VTs;
7556   VTs.reserve(Ops.size());
7557   for (const SDValue &Op : Ops)
7558     VTs.push_back(Op.getValueType());
7559   return getNode(ISD::MERGE_VALUES, dl, getVTList(VTs), Ops);
7560 }
7561 
7562 SDValue SelectionDAG::getMemIntrinsicNode(
7563     unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef<SDValue> Ops,
7564     EVT MemVT, MachinePointerInfo PtrInfo, Align Alignment,
7565     MachineMemOperand::Flags Flags, uint64_t Size, const AAMDNodes &AAInfo) {
7566   if (!Size && MemVT.isScalableVector())
7567     Size = MemoryLocation::UnknownSize;
7568   else if (!Size)
7569     Size = MemVT.getStoreSize();
7570 
7571   MachineFunction &MF = getMachineFunction();
7572   MachineMemOperand *MMO =
7573       MF.getMachineMemOperand(PtrInfo, Flags, Size, Alignment, AAInfo);
7574 
7575   return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, MMO);
7576 }
7577 
7578 SDValue SelectionDAG::getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl,
7579                                           SDVTList VTList,
7580                                           ArrayRef<SDValue> Ops, EVT MemVT,
7581                                           MachineMemOperand *MMO) {
7582   assert((Opcode == ISD::INTRINSIC_VOID ||
7583           Opcode == ISD::INTRINSIC_W_CHAIN ||
7584           Opcode == ISD::PREFETCH ||
7585           ((int)Opcode <= std::numeric_limits<int>::max() &&
7586            (int)Opcode >= ISD::FIRST_TARGET_MEMORY_OPCODE)) &&
7587          "Opcode is not a memory-accessing opcode!");
7588 
7589   // Memoize the node unless it returns a flag.
7590   MemIntrinsicSDNode *N;
7591   if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
7592     FoldingSetNodeID ID;
7593     AddNodeIDNode(ID, Opcode, VTList, Ops);
7594     ID.AddInteger(getSyntheticNodeSubclassData<MemIntrinsicSDNode>(
7595         Opcode, dl.getIROrder(), VTList, MemVT, MMO));
7596     ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7597     ID.AddInteger(MMO->getFlags());
7598     void *IP = nullptr;
7599     if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7600       cast<MemIntrinsicSDNode>(E)->refineAlignment(MMO);
7601       return SDValue(E, 0);
7602     }
7603 
7604     N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
7605                                       VTList, MemVT, MMO);
7606     createOperands(N, Ops);
7607 
7608   CSEMap.InsertNode(N, IP);
7609   } else {
7610     N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
7611                                       VTList, MemVT, MMO);
7612     createOperands(N, Ops);
7613   }
7614   InsertNode(N);
7615   SDValue V(N, 0);
7616   NewSDValueDbgMsg(V, "Creating new node: ", this);
7617   return V;
7618 }
7619 
7620 SDValue SelectionDAG::getLifetimeNode(bool IsStart, const SDLoc &dl,
7621                                       SDValue Chain, int FrameIndex,
7622                                       int64_t Size, int64_t Offset) {
7623   const unsigned Opcode = IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END;
7624   const auto VTs = getVTList(MVT::Other);
7625   SDValue Ops[2] = {
7626       Chain,
7627       getFrameIndex(FrameIndex,
7628                     getTargetLoweringInfo().getFrameIndexTy(getDataLayout()),
7629                     true)};
7630 
7631   FoldingSetNodeID ID;
7632   AddNodeIDNode(ID, Opcode, VTs, Ops);
7633   ID.AddInteger(FrameIndex);
7634   ID.AddInteger(Size);
7635   ID.AddInteger(Offset);
7636   void *IP = nullptr;
7637   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
7638     return SDValue(E, 0);
7639 
7640   LifetimeSDNode *N = newSDNode<LifetimeSDNode>(
7641       Opcode, dl.getIROrder(), dl.getDebugLoc(), VTs, Size, Offset);
7642   createOperands(N, Ops);
7643   CSEMap.InsertNode(N, IP);
7644   InsertNode(N);
7645   SDValue V(N, 0);
7646   NewSDValueDbgMsg(V, "Creating new node: ", this);
7647   return V;
7648 }
7649 
7650 SDValue SelectionDAG::getPseudoProbeNode(const SDLoc &Dl, SDValue Chain,
7651                                          uint64_t Guid, uint64_t Index,
7652                                          uint32_t Attr) {
7653   const unsigned Opcode = ISD::PSEUDO_PROBE;
7654   const auto VTs = getVTList(MVT::Other);
7655   SDValue Ops[] = {Chain};
7656   FoldingSetNodeID ID;
7657   AddNodeIDNode(ID, Opcode, VTs, Ops);
7658   ID.AddInteger(Guid);
7659   ID.AddInteger(Index);
7660   void *IP = nullptr;
7661   if (SDNode *E = FindNodeOrInsertPos(ID, Dl, IP))
7662     return SDValue(E, 0);
7663 
7664   auto *N = newSDNode<PseudoProbeSDNode>(
7665       Opcode, Dl.getIROrder(), Dl.getDebugLoc(), VTs, Guid, Index, Attr);
7666   createOperands(N, Ops);
7667   CSEMap.InsertNode(N, IP);
7668   InsertNode(N);
7669   SDValue V(N, 0);
7670   NewSDValueDbgMsg(V, "Creating new node: ", this);
7671   return V;
7672 }
7673 
7674 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
7675 /// MachinePointerInfo record from it.  This is particularly useful because the
7676 /// code generator has many cases where it doesn't bother passing in a
7677 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
7678 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info,
7679                                            SelectionDAG &DAG, SDValue Ptr,
7680                                            int64_t Offset = 0) {
7681   // If this is FI+Offset, we can model it.
7682   if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr))
7683     return MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
7684                                              FI->getIndex(), Offset);
7685 
7686   // If this is (FI+Offset1)+Offset2, we can model it.
7687   if (Ptr.getOpcode() != ISD::ADD ||
7688       !isa<ConstantSDNode>(Ptr.getOperand(1)) ||
7689       !isa<FrameIndexSDNode>(Ptr.getOperand(0)))
7690     return Info;
7691 
7692   int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
7693   return MachinePointerInfo::getFixedStack(
7694       DAG.getMachineFunction(), FI,
7695       Offset + cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue());
7696 }
7697 
7698 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
7699 /// MachinePointerInfo record from it.  This is particularly useful because the
7700 /// code generator has many cases where it doesn't bother passing in a
7701 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
7702 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info,
7703                                            SelectionDAG &DAG, SDValue Ptr,
7704                                            SDValue OffsetOp) {
7705   // If the 'Offset' value isn't a constant, we can't handle this.
7706   if (ConstantSDNode *OffsetNode = dyn_cast<ConstantSDNode>(OffsetOp))
7707     return InferPointerInfo(Info, DAG, Ptr, OffsetNode->getSExtValue());
7708   if (OffsetOp.isUndef())
7709     return InferPointerInfo(Info, DAG, Ptr);
7710   return Info;
7711 }
7712 
7713 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
7714                               EVT VT, const SDLoc &dl, SDValue Chain,
7715                               SDValue Ptr, SDValue Offset,
7716                               MachinePointerInfo PtrInfo, EVT MemVT,
7717                               Align Alignment,
7718                               MachineMemOperand::Flags MMOFlags,
7719                               const AAMDNodes &AAInfo, const MDNode *Ranges) {
7720   assert(Chain.getValueType() == MVT::Other &&
7721         "Invalid chain type");
7722 
7723   MMOFlags |= MachineMemOperand::MOLoad;
7724   assert((MMOFlags & MachineMemOperand::MOStore) == 0);
7725   // If we don't have a PtrInfo, infer the trivial frame index case to simplify
7726   // clients.
7727   if (PtrInfo.V.isNull())
7728     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
7729 
7730   uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize());
7731   MachineFunction &MF = getMachineFunction();
7732   MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size,
7733                                                    Alignment, AAInfo, Ranges);
7734   return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO);
7735 }
7736 
7737 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
7738                               EVT VT, const SDLoc &dl, SDValue Chain,
7739                               SDValue Ptr, SDValue Offset, EVT MemVT,
7740                               MachineMemOperand *MMO) {
7741   if (VT == MemVT) {
7742     ExtType = ISD::NON_EXTLOAD;
7743   } else if (ExtType == ISD::NON_EXTLOAD) {
7744     assert(VT == MemVT && "Non-extending load from different memory type!");
7745   } else {
7746     // Extending load.
7747     assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) &&
7748            "Should only be an extending load, not truncating!");
7749     assert(VT.isInteger() == MemVT.isInteger() &&
7750            "Cannot convert from FP to Int or Int -> FP!");
7751     assert(VT.isVector() == MemVT.isVector() &&
7752            "Cannot use an ext load to convert to or from a vector!");
7753     assert((!VT.isVector() ||
7754             VT.getVectorElementCount() == MemVT.getVectorElementCount()) &&
7755            "Cannot use an ext load to change the number of vector elements!");
7756   }
7757 
7758   bool Indexed = AM != ISD::UNINDEXED;
7759   assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
7760 
7761   SDVTList VTs = Indexed ?
7762     getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
7763   SDValue Ops[] = { Chain, Ptr, Offset };
7764   FoldingSetNodeID ID;
7765   AddNodeIDNode(ID, ISD::LOAD, VTs, Ops);
7766   ID.AddInteger(MemVT.getRawBits());
7767   ID.AddInteger(getSyntheticNodeSubclassData<LoadSDNode>(
7768       dl.getIROrder(), VTs, AM, ExtType, MemVT, MMO));
7769   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7770   ID.AddInteger(MMO->getFlags());
7771   void *IP = nullptr;
7772   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7773     cast<LoadSDNode>(E)->refineAlignment(MMO);
7774     return SDValue(E, 0);
7775   }
7776   auto *N = newSDNode<LoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
7777                                   ExtType, MemVT, MMO);
7778   createOperands(N, Ops);
7779 
7780   CSEMap.InsertNode(N, IP);
7781   InsertNode(N);
7782   SDValue V(N, 0);
7783   NewSDValueDbgMsg(V, "Creating new node: ", this);
7784   return V;
7785 }
7786 
7787 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
7788                               SDValue Ptr, MachinePointerInfo PtrInfo,
7789                               MaybeAlign Alignment,
7790                               MachineMemOperand::Flags MMOFlags,
7791                               const AAMDNodes &AAInfo, const MDNode *Ranges) {
7792   SDValue Undef = getUNDEF(Ptr.getValueType());
7793   return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7794                  PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges);
7795 }
7796 
7797 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
7798                               SDValue Ptr, MachineMemOperand *MMO) {
7799   SDValue Undef = getUNDEF(Ptr.getValueType());
7800   return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7801                  VT, MMO);
7802 }
7803 
7804 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
7805                                  EVT VT, SDValue Chain, SDValue Ptr,
7806                                  MachinePointerInfo PtrInfo, EVT MemVT,
7807                                  MaybeAlign Alignment,
7808                                  MachineMemOperand::Flags MMOFlags,
7809                                  const AAMDNodes &AAInfo) {
7810   SDValue Undef = getUNDEF(Ptr.getValueType());
7811   return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, PtrInfo,
7812                  MemVT, Alignment, MMOFlags, AAInfo);
7813 }
7814 
7815 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
7816                                  EVT VT, SDValue Chain, SDValue Ptr, EVT MemVT,
7817                                  MachineMemOperand *MMO) {
7818   SDValue Undef = getUNDEF(Ptr.getValueType());
7819   return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef,
7820                  MemVT, MMO);
7821 }
7822 
7823 SDValue SelectionDAG::getIndexedLoad(SDValue OrigLoad, const SDLoc &dl,
7824                                      SDValue Base, SDValue Offset,
7825                                      ISD::MemIndexedMode AM) {
7826   LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
7827   assert(LD->getOffset().isUndef() && "Load is already a indexed load!");
7828   // Don't propagate the invariant or dereferenceable flags.
7829   auto MMOFlags =
7830       LD->getMemOperand()->getFlags() &
7831       ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
7832   return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
7833                  LD->getChain(), Base, Offset, LD->getPointerInfo(),
7834                  LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo());
7835 }
7836 
7837 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7838                                SDValue Ptr, MachinePointerInfo PtrInfo,
7839                                Align Alignment,
7840                                MachineMemOperand::Flags MMOFlags,
7841                                const AAMDNodes &AAInfo) {
7842   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
7843 
7844   MMOFlags |= MachineMemOperand::MOStore;
7845   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
7846 
7847   if (PtrInfo.V.isNull())
7848     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
7849 
7850   MachineFunction &MF = getMachineFunction();
7851   uint64_t Size =
7852       MemoryLocation::getSizeOrUnknown(Val.getValueType().getStoreSize());
7853   MachineMemOperand *MMO =
7854       MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, Alignment, AAInfo);
7855   return getStore(Chain, dl, Val, Ptr, MMO);
7856 }
7857 
7858 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7859                                SDValue Ptr, MachineMemOperand *MMO) {
7860   assert(Chain.getValueType() == MVT::Other &&
7861         "Invalid chain type");
7862   EVT VT = Val.getValueType();
7863   SDVTList VTs = getVTList(MVT::Other);
7864   SDValue Undef = getUNDEF(Ptr.getValueType());
7865   SDValue Ops[] = { Chain, Val, Ptr, Undef };
7866   FoldingSetNodeID ID;
7867   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7868   ID.AddInteger(VT.getRawBits());
7869   ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
7870       dl.getIROrder(), VTs, ISD::UNINDEXED, false, VT, MMO));
7871   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7872   ID.AddInteger(MMO->getFlags());
7873   void *IP = nullptr;
7874   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7875     cast<StoreSDNode>(E)->refineAlignment(MMO);
7876     return SDValue(E, 0);
7877   }
7878   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7879                                    ISD::UNINDEXED, false, VT, MMO);
7880   createOperands(N, Ops);
7881 
7882   CSEMap.InsertNode(N, IP);
7883   InsertNode(N);
7884   SDValue V(N, 0);
7885   NewSDValueDbgMsg(V, "Creating new node: ", this);
7886   return V;
7887 }
7888 
7889 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7890                                     SDValue Ptr, MachinePointerInfo PtrInfo,
7891                                     EVT SVT, Align Alignment,
7892                                     MachineMemOperand::Flags MMOFlags,
7893                                     const AAMDNodes &AAInfo) {
7894   assert(Chain.getValueType() == MVT::Other &&
7895         "Invalid chain type");
7896 
7897   MMOFlags |= MachineMemOperand::MOStore;
7898   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
7899 
7900   if (PtrInfo.V.isNull())
7901     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
7902 
7903   MachineFunction &MF = getMachineFunction();
7904   MachineMemOperand *MMO = MF.getMachineMemOperand(
7905       PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()),
7906       Alignment, AAInfo);
7907   return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO);
7908 }
7909 
7910 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7911                                     SDValue Ptr, EVT SVT,
7912                                     MachineMemOperand *MMO) {
7913   EVT VT = Val.getValueType();
7914 
7915   assert(Chain.getValueType() == MVT::Other &&
7916         "Invalid chain type");
7917   if (VT == SVT)
7918     return getStore(Chain, dl, Val, Ptr, MMO);
7919 
7920   assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
7921          "Should only be a truncating store, not extending!");
7922   assert(VT.isInteger() == SVT.isInteger() &&
7923          "Can't do FP-INT conversion!");
7924   assert(VT.isVector() == SVT.isVector() &&
7925          "Cannot use trunc store to convert to or from a vector!");
7926   assert((!VT.isVector() ||
7927           VT.getVectorElementCount() == SVT.getVectorElementCount()) &&
7928          "Cannot use trunc store to change the number of vector elements!");
7929 
7930   SDVTList VTs = getVTList(MVT::Other);
7931   SDValue Undef = getUNDEF(Ptr.getValueType());
7932   SDValue Ops[] = { Chain, Val, Ptr, Undef };
7933   FoldingSetNodeID ID;
7934   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7935   ID.AddInteger(SVT.getRawBits());
7936   ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
7937       dl.getIROrder(), VTs, ISD::UNINDEXED, true, SVT, MMO));
7938   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7939   ID.AddInteger(MMO->getFlags());
7940   void *IP = nullptr;
7941   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7942     cast<StoreSDNode>(E)->refineAlignment(MMO);
7943     return SDValue(E, 0);
7944   }
7945   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7946                                    ISD::UNINDEXED, true, SVT, MMO);
7947   createOperands(N, Ops);
7948 
7949   CSEMap.InsertNode(N, IP);
7950   InsertNode(N);
7951   SDValue V(N, 0);
7952   NewSDValueDbgMsg(V, "Creating new node: ", this);
7953   return V;
7954 }
7955 
7956 SDValue SelectionDAG::getIndexedStore(SDValue OrigStore, const SDLoc &dl,
7957                                       SDValue Base, SDValue Offset,
7958                                       ISD::MemIndexedMode AM) {
7959   StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
7960   assert(ST->getOffset().isUndef() && "Store is already a indexed store!");
7961   SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
7962   SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
7963   FoldingSetNodeID ID;
7964   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7965   ID.AddInteger(ST->getMemoryVT().getRawBits());
7966   ID.AddInteger(ST->getRawSubclassData());
7967   ID.AddInteger(ST->getPointerInfo().getAddrSpace());
7968   ID.AddInteger(ST->getMemOperand()->getFlags());
7969   void *IP = nullptr;
7970   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
7971     return SDValue(E, 0);
7972 
7973   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
7974                                    ST->isTruncatingStore(), ST->getMemoryVT(),
7975                                    ST->getMemOperand());
7976   createOperands(N, Ops);
7977 
7978   CSEMap.InsertNode(N, IP);
7979   InsertNode(N);
7980   SDValue V(N, 0);
7981   NewSDValueDbgMsg(V, "Creating new node: ", this);
7982   return V;
7983 }
7984 
7985 SDValue SelectionDAG::getLoadVP(
7986     ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &dl,
7987     SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Mask, SDValue EVL,
7988     MachinePointerInfo PtrInfo, EVT MemVT, Align Alignment,
7989     MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
7990     const MDNode *Ranges, bool IsExpanding) {
7991   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
7992 
7993   MMOFlags |= MachineMemOperand::MOLoad;
7994   assert((MMOFlags & MachineMemOperand::MOStore) == 0);
7995   // If we don't have a PtrInfo, infer the trivial frame index case to simplify
7996   // clients.
7997   if (PtrInfo.V.isNull())
7998     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
7999 
8000   uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize());
8001   MachineFunction &MF = getMachineFunction();
8002   MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size,
8003                                                    Alignment, AAInfo, Ranges);
8004   return getLoadVP(AM, ExtType, VT, dl, Chain, Ptr, Offset, Mask, EVL, MemVT,
8005                    MMO, IsExpanding);
8006 }
8007 
8008 SDValue SelectionDAG::getLoadVP(ISD::MemIndexedMode AM,
8009                                 ISD::LoadExtType ExtType, EVT VT,
8010                                 const SDLoc &dl, SDValue Chain, SDValue Ptr,
8011                                 SDValue Offset, SDValue Mask, SDValue EVL,
8012                                 EVT MemVT, MachineMemOperand *MMO,
8013                                 bool IsExpanding) {
8014   bool Indexed = AM != ISD::UNINDEXED;
8015   assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
8016 
8017   SDVTList VTs = Indexed ? getVTList(VT, Ptr.getValueType(), MVT::Other)
8018                          : getVTList(VT, MVT::Other);
8019   SDValue Ops[] = {Chain, Ptr, Offset, Mask, EVL};
8020   FoldingSetNodeID ID;
8021   AddNodeIDNode(ID, ISD::VP_LOAD, VTs, Ops);
8022   ID.AddInteger(VT.getRawBits());
8023   ID.AddInteger(getSyntheticNodeSubclassData<VPLoadSDNode>(
8024       dl.getIROrder(), VTs, AM, ExtType, IsExpanding, MemVT, MMO));
8025   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8026   ID.AddInteger(MMO->getFlags());
8027   void *IP = nullptr;
8028   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8029     cast<VPLoadSDNode>(E)->refineAlignment(MMO);
8030     return SDValue(E, 0);
8031   }
8032   auto *N = newSDNode<VPLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
8033                                     ExtType, IsExpanding, MemVT, MMO);
8034   createOperands(N, Ops);
8035 
8036   CSEMap.InsertNode(N, IP);
8037   InsertNode(N);
8038   SDValue V(N, 0);
8039   NewSDValueDbgMsg(V, "Creating new node: ", this);
8040   return V;
8041 }
8042 
8043 SDValue SelectionDAG::getLoadVP(EVT VT, const SDLoc &dl, SDValue Chain,
8044                                 SDValue Ptr, SDValue Mask, SDValue EVL,
8045                                 MachinePointerInfo PtrInfo,
8046                                 MaybeAlign Alignment,
8047                                 MachineMemOperand::Flags MMOFlags,
8048                                 const AAMDNodes &AAInfo, const MDNode *Ranges,
8049                                 bool IsExpanding) {
8050   SDValue Undef = getUNDEF(Ptr.getValueType());
8051   return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
8052                    Mask, EVL, PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges,
8053                    IsExpanding);
8054 }
8055 
8056 SDValue SelectionDAG::getLoadVP(EVT VT, const SDLoc &dl, SDValue Chain,
8057                                 SDValue Ptr, SDValue Mask, SDValue EVL,
8058                                 MachineMemOperand *MMO, bool IsExpanding) {
8059   SDValue Undef = getUNDEF(Ptr.getValueType());
8060   return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
8061                    Mask, EVL, VT, MMO, IsExpanding);
8062 }
8063 
8064 SDValue SelectionDAG::getExtLoadVP(ISD::LoadExtType ExtType, const SDLoc &dl,
8065                                    EVT VT, SDValue Chain, SDValue Ptr,
8066                                    SDValue Mask, SDValue EVL,
8067                                    MachinePointerInfo PtrInfo, EVT MemVT,
8068                                    MaybeAlign Alignment,
8069                                    MachineMemOperand::Flags MMOFlags,
8070                                    const AAMDNodes &AAInfo, bool IsExpanding) {
8071   SDValue Undef = getUNDEF(Ptr.getValueType());
8072   return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask,
8073                    EVL, PtrInfo, MemVT, Alignment, MMOFlags, AAInfo, nullptr,
8074                    IsExpanding);
8075 }
8076 
8077 SDValue SelectionDAG::getExtLoadVP(ISD::LoadExtType ExtType, const SDLoc &dl,
8078                                    EVT VT, SDValue Chain, SDValue Ptr,
8079                                    SDValue Mask, SDValue EVL, EVT MemVT,
8080                                    MachineMemOperand *MMO, bool IsExpanding) {
8081   SDValue Undef = getUNDEF(Ptr.getValueType());
8082   return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask,
8083                    EVL, MemVT, MMO, IsExpanding);
8084 }
8085 
8086 SDValue SelectionDAG::getIndexedLoadVP(SDValue OrigLoad, const SDLoc &dl,
8087                                        SDValue Base, SDValue Offset,
8088                                        ISD::MemIndexedMode AM) {
8089   auto *LD = cast<VPLoadSDNode>(OrigLoad);
8090   assert(LD->getOffset().isUndef() && "Load is already a indexed load!");
8091   // Don't propagate the invariant or dereferenceable flags.
8092   auto MMOFlags =
8093       LD->getMemOperand()->getFlags() &
8094       ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
8095   return getLoadVP(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
8096                    LD->getChain(), Base, Offset, LD->getMask(),
8097                    LD->getVectorLength(), LD->getPointerInfo(),
8098                    LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo(),
8099                    nullptr, LD->isExpandingLoad());
8100 }
8101 
8102 SDValue SelectionDAG::getStoreVP(SDValue Chain, const SDLoc &dl, SDValue Val,
8103                                  SDValue Ptr, SDValue Offset, SDValue Mask,
8104                                  SDValue EVL, EVT MemVT, MachineMemOperand *MMO,
8105                                  ISD::MemIndexedMode AM, bool IsTruncating,
8106                                  bool IsCompressing) {
8107   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
8108   bool Indexed = AM != ISD::UNINDEXED;
8109   assert((Indexed || Offset.isUndef()) && "Unindexed vp_store with an offset!");
8110   SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other)
8111                          : getVTList(MVT::Other);
8112   SDValue Ops[] = {Chain, Val, Ptr, Offset, Mask, EVL};
8113   FoldingSetNodeID ID;
8114   AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
8115   ID.AddInteger(MemVT.getRawBits());
8116   ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>(
8117       dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
8118   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8119   ID.AddInteger(MMO->getFlags());
8120   void *IP = nullptr;
8121   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8122     cast<VPStoreSDNode>(E)->refineAlignment(MMO);
8123     return SDValue(E, 0);
8124   }
8125   auto *N = newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
8126                                      IsTruncating, IsCompressing, MemVT, MMO);
8127   createOperands(N, Ops);
8128 
8129   CSEMap.InsertNode(N, IP);
8130   InsertNode(N);
8131   SDValue V(N, 0);
8132   NewSDValueDbgMsg(V, "Creating new node: ", this);
8133   return V;
8134 }
8135 
8136 SDValue SelectionDAG::getTruncStoreVP(SDValue Chain, const SDLoc &dl,
8137                                       SDValue Val, SDValue Ptr, SDValue Mask,
8138                                       SDValue EVL, MachinePointerInfo PtrInfo,
8139                                       EVT SVT, Align Alignment,
8140                                       MachineMemOperand::Flags MMOFlags,
8141                                       const AAMDNodes &AAInfo,
8142                                       bool IsCompressing) {
8143   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
8144 
8145   MMOFlags |= MachineMemOperand::MOStore;
8146   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
8147 
8148   if (PtrInfo.V.isNull())
8149     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
8150 
8151   MachineFunction &MF = getMachineFunction();
8152   MachineMemOperand *MMO = MF.getMachineMemOperand(
8153       PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()),
8154       Alignment, AAInfo);
8155   return getTruncStoreVP(Chain, dl, Val, Ptr, Mask, EVL, SVT, MMO,
8156                          IsCompressing);
8157 }
8158 
8159 SDValue SelectionDAG::getTruncStoreVP(SDValue Chain, const SDLoc &dl,
8160                                       SDValue Val, SDValue Ptr, SDValue Mask,
8161                                       SDValue EVL, EVT SVT,
8162                                       MachineMemOperand *MMO,
8163                                       bool IsCompressing) {
8164   EVT VT = Val.getValueType();
8165 
8166   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
8167   if (VT == SVT)
8168     return getStoreVP(Chain, dl, Val, Ptr, getUNDEF(Ptr.getValueType()), Mask,
8169                       EVL, VT, MMO, ISD::UNINDEXED,
8170                       /*IsTruncating*/ false, IsCompressing);
8171 
8172   assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
8173          "Should only be a truncating store, not extending!");
8174   assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!");
8175   assert(VT.isVector() == SVT.isVector() &&
8176          "Cannot use trunc store to convert to or from a vector!");
8177   assert((!VT.isVector() ||
8178           VT.getVectorElementCount() == SVT.getVectorElementCount()) &&
8179          "Cannot use trunc store to change the number of vector elements!");
8180 
8181   SDVTList VTs = getVTList(MVT::Other);
8182   SDValue Undef = getUNDEF(Ptr.getValueType());
8183   SDValue Ops[] = {Chain, Val, Ptr, Undef, Mask, EVL};
8184   FoldingSetNodeID ID;
8185   AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
8186   ID.AddInteger(SVT.getRawBits());
8187   ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>(
8188       dl.getIROrder(), VTs, ISD::UNINDEXED, true, IsCompressing, SVT, MMO));
8189   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8190   ID.AddInteger(MMO->getFlags());
8191   void *IP = nullptr;
8192   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8193     cast<VPStoreSDNode>(E)->refineAlignment(MMO);
8194     return SDValue(E, 0);
8195   }
8196   auto *N =
8197       newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
8198                                ISD::UNINDEXED, true, IsCompressing, SVT, MMO);
8199   createOperands(N, Ops);
8200 
8201   CSEMap.InsertNode(N, IP);
8202   InsertNode(N);
8203   SDValue V(N, 0);
8204   NewSDValueDbgMsg(V, "Creating new node: ", this);
8205   return V;
8206 }
8207 
8208 SDValue SelectionDAG::getIndexedStoreVP(SDValue OrigStore, const SDLoc &dl,
8209                                         SDValue Base, SDValue Offset,
8210                                         ISD::MemIndexedMode AM) {
8211   auto *ST = cast<VPStoreSDNode>(OrigStore);
8212   assert(ST->getOffset().isUndef() && "Store is already an indexed store!");
8213   SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
8214   SDValue Ops[] = {ST->getChain(), ST->getValue(), Base,
8215                    Offset,         ST->getMask(),  ST->getVectorLength()};
8216   FoldingSetNodeID ID;
8217   AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
8218   ID.AddInteger(ST->getMemoryVT().getRawBits());
8219   ID.AddInteger(ST->getRawSubclassData());
8220   ID.AddInteger(ST->getPointerInfo().getAddrSpace());
8221   ID.AddInteger(ST->getMemOperand()->getFlags());
8222   void *IP = nullptr;
8223   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
8224     return SDValue(E, 0);
8225 
8226   auto *N = newSDNode<VPStoreSDNode>(
8227       dl.getIROrder(), dl.getDebugLoc(), VTs, AM, ST->isTruncatingStore(),
8228       ST->isCompressingStore(), ST->getMemoryVT(), ST->getMemOperand());
8229   createOperands(N, Ops);
8230 
8231   CSEMap.InsertNode(N, IP);
8232   InsertNode(N);
8233   SDValue V(N, 0);
8234   NewSDValueDbgMsg(V, "Creating new node: ", this);
8235   return V;
8236 }
8237 
8238 SDValue SelectionDAG::getStridedLoadVP(
8239     ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &DL,
8240     SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Stride, SDValue Mask,
8241     SDValue EVL, MachinePointerInfo PtrInfo, EVT MemVT, Align Alignment,
8242     MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
8243     const MDNode *Ranges, bool IsExpanding) {
8244   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
8245 
8246   MMOFlags |= MachineMemOperand::MOLoad;
8247   assert((MMOFlags & MachineMemOperand::MOStore) == 0);
8248   // If we don't have a PtrInfo, infer the trivial frame index case to simplify
8249   // clients.
8250   if (PtrInfo.V.isNull())
8251     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
8252 
8253   uint64_t Size = MemoryLocation::UnknownSize;
8254   MachineFunction &MF = getMachineFunction();
8255   MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size,
8256                                                    Alignment, AAInfo, Ranges);
8257   return getStridedLoadVP(AM, ExtType, VT, DL, Chain, Ptr, Offset, Stride, Mask,
8258                           EVL, MemVT, MMO, IsExpanding);
8259 }
8260 
8261 SDValue SelectionDAG::getStridedLoadVP(
8262     ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &DL,
8263     SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Stride, SDValue Mask,
8264     SDValue EVL, EVT MemVT, MachineMemOperand *MMO, bool IsExpanding) {
8265   bool Indexed = AM != ISD::UNINDEXED;
8266   assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
8267 
8268   SDValue Ops[] = {Chain, Ptr, Offset, Stride, Mask, EVL};
8269   SDVTList VTs = Indexed ? getVTList(VT, Ptr.getValueType(), MVT::Other)
8270                          : getVTList(VT, MVT::Other);
8271   FoldingSetNodeID ID;
8272   AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_LOAD, VTs, Ops);
8273   ID.AddInteger(VT.getRawBits());
8274   ID.AddInteger(getSyntheticNodeSubclassData<VPStridedLoadSDNode>(
8275       DL.getIROrder(), VTs, AM, ExtType, IsExpanding, MemVT, MMO));
8276   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8277 
8278   void *IP = nullptr;
8279   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
8280     cast<VPStridedLoadSDNode>(E)->refineAlignment(MMO);
8281     return SDValue(E, 0);
8282   }
8283 
8284   auto *N =
8285       newSDNode<VPStridedLoadSDNode>(DL.getIROrder(), DL.getDebugLoc(), VTs, AM,
8286                                      ExtType, IsExpanding, MemVT, MMO);
8287   createOperands(N, Ops);
8288   CSEMap.InsertNode(N, IP);
8289   InsertNode(N);
8290   SDValue V(N, 0);
8291   NewSDValueDbgMsg(V, "Creating new node: ", this);
8292   return V;
8293 }
8294 
8295 SDValue SelectionDAG::getStridedLoadVP(
8296     EVT VT, const SDLoc &DL, SDValue Chain, SDValue Ptr, SDValue Stride,
8297     SDValue Mask, SDValue EVL, MachinePointerInfo PtrInfo, MaybeAlign Alignment,
8298     MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
8299     const MDNode *Ranges, bool IsExpanding) {
8300   SDValue Undef = getUNDEF(Ptr.getValueType());
8301   return getStridedLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, DL, Chain, Ptr,
8302                           Undef, Stride, Mask, EVL, PtrInfo, VT, Alignment,
8303                           MMOFlags, AAInfo, Ranges, IsExpanding);
8304 }
8305 
8306 SDValue SelectionDAG::getStridedLoadVP(EVT VT, const SDLoc &DL, SDValue Chain,
8307                                        SDValue Ptr, SDValue Stride,
8308                                        SDValue Mask, SDValue EVL,
8309                                        MachineMemOperand *MMO,
8310                                        bool IsExpanding) {
8311   SDValue Undef = getUNDEF(Ptr.getValueType());
8312   return getStridedLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, DL, Chain, Ptr,
8313                           Undef, Stride, Mask, EVL, VT, MMO, IsExpanding);
8314 }
8315 
8316 SDValue SelectionDAG::getExtStridedLoadVP(
8317     ISD::LoadExtType ExtType, const SDLoc &DL, EVT VT, SDValue Chain,
8318     SDValue Ptr, SDValue Stride, SDValue Mask, SDValue EVL,
8319     MachinePointerInfo PtrInfo, EVT MemVT, MaybeAlign Alignment,
8320     MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
8321     bool IsExpanding) {
8322   SDValue Undef = getUNDEF(Ptr.getValueType());
8323   return getStridedLoadVP(ISD::UNINDEXED, ExtType, VT, DL, Chain, Ptr, Undef,
8324                           Stride, Mask, EVL, PtrInfo, MemVT, Alignment,
8325                           MMOFlags, AAInfo, nullptr, IsExpanding);
8326 }
8327 
8328 SDValue SelectionDAG::getExtStridedLoadVP(
8329     ISD::LoadExtType ExtType, const SDLoc &DL, EVT VT, SDValue Chain,
8330     SDValue Ptr, SDValue Stride, SDValue Mask, SDValue EVL, EVT MemVT,
8331     MachineMemOperand *MMO, bool IsExpanding) {
8332   SDValue Undef = getUNDEF(Ptr.getValueType());
8333   return getStridedLoadVP(ISD::UNINDEXED, ExtType, VT, DL, Chain, Ptr, Undef,
8334                           Stride, Mask, EVL, MemVT, MMO, IsExpanding);
8335 }
8336 
8337 SDValue SelectionDAG::getIndexedStridedLoadVP(SDValue OrigLoad, const SDLoc &DL,
8338                                               SDValue Base, SDValue Offset,
8339                                               ISD::MemIndexedMode AM) {
8340   auto *SLD = cast<VPStridedLoadSDNode>(OrigLoad);
8341   assert(SLD->getOffset().isUndef() &&
8342          "Strided load is already a indexed load!");
8343   // Don't propagate the invariant or dereferenceable flags.
8344   auto MMOFlags =
8345       SLD->getMemOperand()->getFlags() &
8346       ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
8347   return getStridedLoadVP(
8348       AM, SLD->getExtensionType(), OrigLoad.getValueType(), DL, SLD->getChain(),
8349       Base, Offset, SLD->getStride(), SLD->getMask(), SLD->getVectorLength(),
8350       SLD->getPointerInfo(), SLD->getMemoryVT(), SLD->getAlign(), MMOFlags,
8351       SLD->getAAInfo(), nullptr, SLD->isExpandingLoad());
8352 }
8353 
8354 SDValue SelectionDAG::getStridedStoreVP(SDValue Chain, const SDLoc &DL,
8355                                         SDValue Val, SDValue Ptr,
8356                                         SDValue Offset, SDValue Stride,
8357                                         SDValue Mask, SDValue EVL, EVT MemVT,
8358                                         MachineMemOperand *MMO,
8359                                         ISD::MemIndexedMode AM,
8360                                         bool IsTruncating, bool IsCompressing) {
8361   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
8362   bool Indexed = AM != ISD::UNINDEXED;
8363   assert((Indexed || Offset.isUndef()) && "Unindexed vp_store with an offset!");
8364   SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other)
8365                          : getVTList(MVT::Other);
8366   SDValue Ops[] = {Chain, Val, Ptr, Offset, Stride, Mask, EVL};
8367   FoldingSetNodeID ID;
8368   AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_STORE, VTs, Ops);
8369   ID.AddInteger(MemVT.getRawBits());
8370   ID.AddInteger(getSyntheticNodeSubclassData<VPStridedStoreSDNode>(
8371       DL.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
8372   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8373   void *IP = nullptr;
8374   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
8375     cast<VPStridedStoreSDNode>(E)->refineAlignment(MMO);
8376     return SDValue(E, 0);
8377   }
8378   auto *N = newSDNode<VPStridedStoreSDNode>(DL.getIROrder(), DL.getDebugLoc(),
8379                                             VTs, AM, IsTruncating,
8380                                             IsCompressing, MemVT, MMO);
8381   createOperands(N, Ops);
8382 
8383   CSEMap.InsertNode(N, IP);
8384   InsertNode(N);
8385   SDValue V(N, 0);
8386   NewSDValueDbgMsg(V, "Creating new node: ", this);
8387   return V;
8388 }
8389 
8390 SDValue SelectionDAG::getTruncStridedStoreVP(
8391     SDValue Chain, const SDLoc &DL, SDValue Val, SDValue Ptr, SDValue Stride,
8392     SDValue Mask, SDValue EVL, MachinePointerInfo PtrInfo, EVT SVT,
8393     Align Alignment, MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
8394     bool IsCompressing) {
8395   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
8396 
8397   MMOFlags |= MachineMemOperand::MOStore;
8398   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
8399 
8400   if (PtrInfo.V.isNull())
8401     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
8402 
8403   MachineFunction &MF = getMachineFunction();
8404   MachineMemOperand *MMO = MF.getMachineMemOperand(
8405       PtrInfo, MMOFlags, MemoryLocation::UnknownSize, Alignment, AAInfo);
8406   return getTruncStridedStoreVP(Chain, DL, Val, Ptr, Stride, Mask, EVL, SVT,
8407                                 MMO, IsCompressing);
8408 }
8409 
8410 SDValue SelectionDAG::getTruncStridedStoreVP(SDValue Chain, const SDLoc &DL,
8411                                              SDValue Val, SDValue Ptr,
8412                                              SDValue Stride, SDValue Mask,
8413                                              SDValue EVL, EVT SVT,
8414                                              MachineMemOperand *MMO,
8415                                              bool IsCompressing) {
8416   EVT VT = Val.getValueType();
8417 
8418   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
8419   if (VT == SVT)
8420     return getStridedStoreVP(Chain, DL, Val, Ptr, getUNDEF(Ptr.getValueType()),
8421                              Stride, Mask, EVL, VT, MMO, ISD::UNINDEXED,
8422                              /*IsTruncating*/ false, IsCompressing);
8423 
8424   assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
8425          "Should only be a truncating store, not extending!");
8426   assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!");
8427   assert(VT.isVector() == SVT.isVector() &&
8428          "Cannot use trunc store to convert to or from a vector!");
8429   assert((!VT.isVector() ||
8430           VT.getVectorElementCount() == SVT.getVectorElementCount()) &&
8431          "Cannot use trunc store to change the number of vector elements!");
8432 
8433   SDVTList VTs = getVTList(MVT::Other);
8434   SDValue Undef = getUNDEF(Ptr.getValueType());
8435   SDValue Ops[] = {Chain, Val, Ptr, Undef, Stride, Mask, EVL};
8436   FoldingSetNodeID ID;
8437   AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_STORE, VTs, Ops);
8438   ID.AddInteger(SVT.getRawBits());
8439   ID.AddInteger(getSyntheticNodeSubclassData<VPStridedStoreSDNode>(
8440       DL.getIROrder(), VTs, ISD::UNINDEXED, true, IsCompressing, SVT, MMO));
8441   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8442   void *IP = nullptr;
8443   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
8444     cast<VPStridedStoreSDNode>(E)->refineAlignment(MMO);
8445     return SDValue(E, 0);
8446   }
8447   auto *N = newSDNode<VPStridedStoreSDNode>(DL.getIROrder(), DL.getDebugLoc(),
8448                                             VTs, ISD::UNINDEXED, true,
8449                                             IsCompressing, SVT, MMO);
8450   createOperands(N, Ops);
8451 
8452   CSEMap.InsertNode(N, IP);
8453   InsertNode(N);
8454   SDValue V(N, 0);
8455   NewSDValueDbgMsg(V, "Creating new node: ", this);
8456   return V;
8457 }
8458 
8459 SDValue SelectionDAG::getIndexedStridedStoreVP(SDValue OrigStore,
8460                                                const SDLoc &DL, SDValue Base,
8461                                                SDValue Offset,
8462                                                ISD::MemIndexedMode AM) {
8463   auto *SST = cast<VPStridedStoreSDNode>(OrigStore);
8464   assert(SST->getOffset().isUndef() &&
8465          "Strided store is already an indexed store!");
8466   SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
8467   SDValue Ops[] = {
8468       SST->getChain(), SST->getValue(),       Base, Offset, SST->getStride(),
8469       SST->getMask(),  SST->getVectorLength()};
8470   FoldingSetNodeID ID;
8471   AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_STORE, VTs, Ops);
8472   ID.AddInteger(SST->getMemoryVT().getRawBits());
8473   ID.AddInteger(SST->getRawSubclassData());
8474   ID.AddInteger(SST->getPointerInfo().getAddrSpace());
8475   void *IP = nullptr;
8476   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
8477     return SDValue(E, 0);
8478 
8479   auto *N = newSDNode<VPStridedStoreSDNode>(
8480       DL.getIROrder(), DL.getDebugLoc(), VTs, AM, SST->isTruncatingStore(),
8481       SST->isCompressingStore(), SST->getMemoryVT(), SST->getMemOperand());
8482   createOperands(N, Ops);
8483 
8484   CSEMap.InsertNode(N, IP);
8485   InsertNode(N);
8486   SDValue V(N, 0);
8487   NewSDValueDbgMsg(V, "Creating new node: ", this);
8488   return V;
8489 }
8490 
8491 SDValue SelectionDAG::getGatherVP(SDVTList VTs, EVT VT, const SDLoc &dl,
8492                                   ArrayRef<SDValue> Ops, MachineMemOperand *MMO,
8493                                   ISD::MemIndexType IndexType) {
8494   assert(Ops.size() == 6 && "Incompatible number of operands");
8495 
8496   FoldingSetNodeID ID;
8497   AddNodeIDNode(ID, ISD::VP_GATHER, VTs, Ops);
8498   ID.AddInteger(VT.getRawBits());
8499   ID.AddInteger(getSyntheticNodeSubclassData<VPGatherSDNode>(
8500       dl.getIROrder(), VTs, VT, MMO, IndexType));
8501   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8502   ID.AddInteger(MMO->getFlags());
8503   void *IP = nullptr;
8504   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8505     cast<VPGatherSDNode>(E)->refineAlignment(MMO);
8506     return SDValue(E, 0);
8507   }
8508 
8509   auto *N = newSDNode<VPGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
8510                                       VT, MMO, IndexType);
8511   createOperands(N, Ops);
8512 
8513   assert(N->getMask().getValueType().getVectorElementCount() ==
8514              N->getValueType(0).getVectorElementCount() &&
8515          "Vector width mismatch between mask and data");
8516   assert(N->getIndex().getValueType().getVectorElementCount().isScalable() ==
8517              N->getValueType(0).getVectorElementCount().isScalable() &&
8518          "Scalable flags of index and data do not match");
8519   assert(ElementCount::isKnownGE(
8520              N->getIndex().getValueType().getVectorElementCount(),
8521              N->getValueType(0).getVectorElementCount()) &&
8522          "Vector width mismatch between index and data");
8523   assert(isa<ConstantSDNode>(N->getScale()) &&
8524          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
8525          "Scale should be a constant power of 2");
8526 
8527   CSEMap.InsertNode(N, IP);
8528   InsertNode(N);
8529   SDValue V(N, 0);
8530   NewSDValueDbgMsg(V, "Creating new node: ", this);
8531   return V;
8532 }
8533 
8534 SDValue SelectionDAG::getScatterVP(SDVTList VTs, EVT VT, const SDLoc &dl,
8535                                    ArrayRef<SDValue> Ops,
8536                                    MachineMemOperand *MMO,
8537                                    ISD::MemIndexType IndexType) {
8538   assert(Ops.size() == 7 && "Incompatible number of operands");
8539 
8540   FoldingSetNodeID ID;
8541   AddNodeIDNode(ID, ISD::VP_SCATTER, VTs, Ops);
8542   ID.AddInteger(VT.getRawBits());
8543   ID.AddInteger(getSyntheticNodeSubclassData<VPScatterSDNode>(
8544       dl.getIROrder(), VTs, VT, MMO, IndexType));
8545   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8546   ID.AddInteger(MMO->getFlags());
8547   void *IP = nullptr;
8548   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8549     cast<VPScatterSDNode>(E)->refineAlignment(MMO);
8550     return SDValue(E, 0);
8551   }
8552   auto *N = newSDNode<VPScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
8553                                        VT, MMO, IndexType);
8554   createOperands(N, Ops);
8555 
8556   assert(N->getMask().getValueType().getVectorElementCount() ==
8557              N->getValue().getValueType().getVectorElementCount() &&
8558          "Vector width mismatch between mask and data");
8559   assert(
8560       N->getIndex().getValueType().getVectorElementCount().isScalable() ==
8561           N->getValue().getValueType().getVectorElementCount().isScalable() &&
8562       "Scalable flags of index and data do not match");
8563   assert(ElementCount::isKnownGE(
8564              N->getIndex().getValueType().getVectorElementCount(),
8565              N->getValue().getValueType().getVectorElementCount()) &&
8566          "Vector width mismatch between index and data");
8567   assert(isa<ConstantSDNode>(N->getScale()) &&
8568          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
8569          "Scale should be a constant power of 2");
8570 
8571   CSEMap.InsertNode(N, IP);
8572   InsertNode(N);
8573   SDValue V(N, 0);
8574   NewSDValueDbgMsg(V, "Creating new node: ", this);
8575   return V;
8576 }
8577 
8578 SDValue SelectionDAG::getMaskedLoad(EVT VT, const SDLoc &dl, SDValue Chain,
8579                                     SDValue Base, SDValue Offset, SDValue Mask,
8580                                     SDValue PassThru, EVT MemVT,
8581                                     MachineMemOperand *MMO,
8582                                     ISD::MemIndexedMode AM,
8583                                     ISD::LoadExtType ExtTy, bool isExpanding) {
8584   bool Indexed = AM != ISD::UNINDEXED;
8585   assert((Indexed || Offset.isUndef()) &&
8586          "Unindexed masked load with an offset!");
8587   SDVTList VTs = Indexed ? getVTList(VT, Base.getValueType(), MVT::Other)
8588                          : getVTList(VT, MVT::Other);
8589   SDValue Ops[] = {Chain, Base, Offset, Mask, PassThru};
8590   FoldingSetNodeID ID;
8591   AddNodeIDNode(ID, ISD::MLOAD, VTs, Ops);
8592   ID.AddInteger(MemVT.getRawBits());
8593   ID.AddInteger(getSyntheticNodeSubclassData<MaskedLoadSDNode>(
8594       dl.getIROrder(), VTs, AM, ExtTy, isExpanding, MemVT, MMO));
8595   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8596   ID.AddInteger(MMO->getFlags());
8597   void *IP = nullptr;
8598   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8599     cast<MaskedLoadSDNode>(E)->refineAlignment(MMO);
8600     return SDValue(E, 0);
8601   }
8602   auto *N = newSDNode<MaskedLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
8603                                         AM, ExtTy, isExpanding, MemVT, MMO);
8604   createOperands(N, Ops);
8605 
8606   CSEMap.InsertNode(N, IP);
8607   InsertNode(N);
8608   SDValue V(N, 0);
8609   NewSDValueDbgMsg(V, "Creating new node: ", this);
8610   return V;
8611 }
8612 
8613 SDValue SelectionDAG::getIndexedMaskedLoad(SDValue OrigLoad, const SDLoc &dl,
8614                                            SDValue Base, SDValue Offset,
8615                                            ISD::MemIndexedMode AM) {
8616   MaskedLoadSDNode *LD = cast<MaskedLoadSDNode>(OrigLoad);
8617   assert(LD->getOffset().isUndef() && "Masked load is already a indexed load!");
8618   return getMaskedLoad(OrigLoad.getValueType(), dl, LD->getChain(), Base,
8619                        Offset, LD->getMask(), LD->getPassThru(),
8620                        LD->getMemoryVT(), LD->getMemOperand(), AM,
8621                        LD->getExtensionType(), LD->isExpandingLoad());
8622 }
8623 
8624 SDValue SelectionDAG::getMaskedStore(SDValue Chain, const SDLoc &dl,
8625                                      SDValue Val, SDValue Base, SDValue Offset,
8626                                      SDValue Mask, EVT MemVT,
8627                                      MachineMemOperand *MMO,
8628                                      ISD::MemIndexedMode AM, bool IsTruncating,
8629                                      bool IsCompressing) {
8630   assert(Chain.getValueType() == MVT::Other &&
8631         "Invalid chain type");
8632   bool Indexed = AM != ISD::UNINDEXED;
8633   assert((Indexed || Offset.isUndef()) &&
8634          "Unindexed masked store with an offset!");
8635   SDVTList VTs = Indexed ? getVTList(Base.getValueType(), MVT::Other)
8636                          : getVTList(MVT::Other);
8637   SDValue Ops[] = {Chain, Val, Base, Offset, Mask};
8638   FoldingSetNodeID ID;
8639   AddNodeIDNode(ID, ISD::MSTORE, VTs, Ops);
8640   ID.AddInteger(MemVT.getRawBits());
8641   ID.AddInteger(getSyntheticNodeSubclassData<MaskedStoreSDNode>(
8642       dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
8643   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8644   ID.AddInteger(MMO->getFlags());
8645   void *IP = nullptr;
8646   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8647     cast<MaskedStoreSDNode>(E)->refineAlignment(MMO);
8648     return SDValue(E, 0);
8649   }
8650   auto *N =
8651       newSDNode<MaskedStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
8652                                    IsTruncating, IsCompressing, MemVT, MMO);
8653   createOperands(N, Ops);
8654 
8655   CSEMap.InsertNode(N, IP);
8656   InsertNode(N);
8657   SDValue V(N, 0);
8658   NewSDValueDbgMsg(V, "Creating new node: ", this);
8659   return V;
8660 }
8661 
8662 SDValue SelectionDAG::getIndexedMaskedStore(SDValue OrigStore, const SDLoc &dl,
8663                                             SDValue Base, SDValue Offset,
8664                                             ISD::MemIndexedMode AM) {
8665   MaskedStoreSDNode *ST = cast<MaskedStoreSDNode>(OrigStore);
8666   assert(ST->getOffset().isUndef() &&
8667          "Masked store is already a indexed store!");
8668   return getMaskedStore(ST->getChain(), dl, ST->getValue(), Base, Offset,
8669                         ST->getMask(), ST->getMemoryVT(), ST->getMemOperand(),
8670                         AM, ST->isTruncatingStore(), ST->isCompressingStore());
8671 }
8672 
8673 SDValue SelectionDAG::getMaskedGather(SDVTList VTs, EVT MemVT, const SDLoc &dl,
8674                                       ArrayRef<SDValue> Ops,
8675                                       MachineMemOperand *MMO,
8676                                       ISD::MemIndexType IndexType,
8677                                       ISD::LoadExtType ExtTy) {
8678   assert(Ops.size() == 6 && "Incompatible number of operands");
8679 
8680   FoldingSetNodeID ID;
8681   AddNodeIDNode(ID, ISD::MGATHER, VTs, Ops);
8682   ID.AddInteger(MemVT.getRawBits());
8683   ID.AddInteger(getSyntheticNodeSubclassData<MaskedGatherSDNode>(
8684       dl.getIROrder(), VTs, MemVT, MMO, IndexType, ExtTy));
8685   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8686   ID.AddInteger(MMO->getFlags());
8687   void *IP = nullptr;
8688   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8689     cast<MaskedGatherSDNode>(E)->refineAlignment(MMO);
8690     return SDValue(E, 0);
8691   }
8692 
8693   auto *N = newSDNode<MaskedGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(),
8694                                           VTs, MemVT, MMO, IndexType, ExtTy);
8695   createOperands(N, Ops);
8696 
8697   assert(N->getPassThru().getValueType() == N->getValueType(0) &&
8698          "Incompatible type of the PassThru value in MaskedGatherSDNode");
8699   assert(N->getMask().getValueType().getVectorElementCount() ==
8700              N->getValueType(0).getVectorElementCount() &&
8701          "Vector width mismatch between mask and data");
8702   assert(N->getIndex().getValueType().getVectorElementCount().isScalable() ==
8703              N->getValueType(0).getVectorElementCount().isScalable() &&
8704          "Scalable flags of index and data do not match");
8705   assert(ElementCount::isKnownGE(
8706              N->getIndex().getValueType().getVectorElementCount(),
8707              N->getValueType(0).getVectorElementCount()) &&
8708          "Vector width mismatch between index and data");
8709   assert(isa<ConstantSDNode>(N->getScale()) &&
8710          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
8711          "Scale should be a constant power of 2");
8712 
8713   CSEMap.InsertNode(N, IP);
8714   InsertNode(N);
8715   SDValue V(N, 0);
8716   NewSDValueDbgMsg(V, "Creating new node: ", this);
8717   return V;
8718 }
8719 
8720 SDValue SelectionDAG::getMaskedScatter(SDVTList VTs, EVT MemVT, const SDLoc &dl,
8721                                        ArrayRef<SDValue> Ops,
8722                                        MachineMemOperand *MMO,
8723                                        ISD::MemIndexType IndexType,
8724                                        bool IsTrunc) {
8725   assert(Ops.size() == 6 && "Incompatible number of operands");
8726 
8727   FoldingSetNodeID ID;
8728   AddNodeIDNode(ID, ISD::MSCATTER, VTs, Ops);
8729   ID.AddInteger(MemVT.getRawBits());
8730   ID.AddInteger(getSyntheticNodeSubclassData<MaskedScatterSDNode>(
8731       dl.getIROrder(), VTs, MemVT, MMO, IndexType, IsTrunc));
8732   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8733   ID.AddInteger(MMO->getFlags());
8734   void *IP = nullptr;
8735   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8736     cast<MaskedScatterSDNode>(E)->refineAlignment(MMO);
8737     return SDValue(E, 0);
8738   }
8739 
8740   auto *N = newSDNode<MaskedScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(),
8741                                            VTs, MemVT, MMO, IndexType, IsTrunc);
8742   createOperands(N, Ops);
8743 
8744   assert(N->getMask().getValueType().getVectorElementCount() ==
8745              N->getValue().getValueType().getVectorElementCount() &&
8746          "Vector width mismatch between mask and data");
8747   assert(
8748       N->getIndex().getValueType().getVectorElementCount().isScalable() ==
8749           N->getValue().getValueType().getVectorElementCount().isScalable() &&
8750       "Scalable flags of index and data do not match");
8751   assert(ElementCount::isKnownGE(
8752              N->getIndex().getValueType().getVectorElementCount(),
8753              N->getValue().getValueType().getVectorElementCount()) &&
8754          "Vector width mismatch between index and data");
8755   assert(isa<ConstantSDNode>(N->getScale()) &&
8756          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
8757          "Scale should be a constant power of 2");
8758 
8759   CSEMap.InsertNode(N, IP);
8760   InsertNode(N);
8761   SDValue V(N, 0);
8762   NewSDValueDbgMsg(V, "Creating new node: ", this);
8763   return V;
8764 }
8765 
8766 SDValue SelectionDAG::simplifySelect(SDValue Cond, SDValue T, SDValue F) {
8767   // select undef, T, F --> T (if T is a constant), otherwise F
8768   // select, ?, undef, F --> F
8769   // select, ?, T, undef --> T
8770   if (Cond.isUndef())
8771     return isConstantValueOfAnyType(T) ? T : F;
8772   if (T.isUndef())
8773     return F;
8774   if (F.isUndef())
8775     return T;
8776 
8777   // select true, T, F --> T
8778   // select false, T, F --> F
8779   if (auto *CondC = dyn_cast<ConstantSDNode>(Cond))
8780     return CondC->isZero() ? F : T;
8781 
8782   // TODO: This should simplify VSELECT with constant condition using something
8783   // like this (but check boolean contents to be complete?):
8784   //  if (ISD::isBuildVectorAllOnes(Cond.getNode()))
8785   //    return T;
8786   //  if (ISD::isBuildVectorAllZeros(Cond.getNode()))
8787   //    return F;
8788 
8789   // select ?, T, T --> T
8790   if (T == F)
8791     return T;
8792 
8793   return SDValue();
8794 }
8795 
8796 SDValue SelectionDAG::simplifyShift(SDValue X, SDValue Y) {
8797   // shift undef, Y --> 0 (can always assume that the undef value is 0)
8798   if (X.isUndef())
8799     return getConstant(0, SDLoc(X.getNode()), X.getValueType());
8800   // shift X, undef --> undef (because it may shift by the bitwidth)
8801   if (Y.isUndef())
8802     return getUNDEF(X.getValueType());
8803 
8804   // shift 0, Y --> 0
8805   // shift X, 0 --> X
8806   if (isNullOrNullSplat(X) || isNullOrNullSplat(Y))
8807     return X;
8808 
8809   // shift X, C >= bitwidth(X) --> undef
8810   // All vector elements must be too big (or undef) to avoid partial undefs.
8811   auto isShiftTooBig = [X](ConstantSDNode *Val) {
8812     return !Val || Val->getAPIntValue().uge(X.getScalarValueSizeInBits());
8813   };
8814   if (ISD::matchUnaryPredicate(Y, isShiftTooBig, true))
8815     return getUNDEF(X.getValueType());
8816 
8817   return SDValue();
8818 }
8819 
8820 SDValue SelectionDAG::simplifyFPBinop(unsigned Opcode, SDValue X, SDValue Y,
8821                                       SDNodeFlags Flags) {
8822   // If this operation has 'nnan' or 'ninf' and at least 1 disallowed operand
8823   // (an undef operand can be chosen to be Nan/Inf), then the result of this
8824   // operation is poison. That result can be relaxed to undef.
8825   ConstantFPSDNode *XC = isConstOrConstSplatFP(X, /* AllowUndefs */ true);
8826   ConstantFPSDNode *YC = isConstOrConstSplatFP(Y, /* AllowUndefs */ true);
8827   bool HasNan = (XC && XC->getValueAPF().isNaN()) ||
8828                 (YC && YC->getValueAPF().isNaN());
8829   bool HasInf = (XC && XC->getValueAPF().isInfinity()) ||
8830                 (YC && YC->getValueAPF().isInfinity());
8831 
8832   if (Flags.hasNoNaNs() && (HasNan || X.isUndef() || Y.isUndef()))
8833     return getUNDEF(X.getValueType());
8834 
8835   if (Flags.hasNoInfs() && (HasInf || X.isUndef() || Y.isUndef()))
8836     return getUNDEF(X.getValueType());
8837 
8838   if (!YC)
8839     return SDValue();
8840 
8841   // X + -0.0 --> X
8842   if (Opcode == ISD::FADD)
8843     if (YC->getValueAPF().isNegZero())
8844       return X;
8845 
8846   // X - +0.0 --> X
8847   if (Opcode == ISD::FSUB)
8848     if (YC->getValueAPF().isPosZero())
8849       return X;
8850 
8851   // X * 1.0 --> X
8852   // X / 1.0 --> X
8853   if (Opcode == ISD::FMUL || Opcode == ISD::FDIV)
8854     if (YC->getValueAPF().isExactlyValue(1.0))
8855       return X;
8856 
8857   // X * 0.0 --> 0.0
8858   if (Opcode == ISD::FMUL && Flags.hasNoNaNs() && Flags.hasNoSignedZeros())
8859     if (YC->getValueAPF().isZero())
8860       return getConstantFP(0.0, SDLoc(Y), Y.getValueType());
8861 
8862   return SDValue();
8863 }
8864 
8865 SDValue SelectionDAG::getVAArg(EVT VT, const SDLoc &dl, SDValue Chain,
8866                                SDValue Ptr, SDValue SV, unsigned Align) {
8867   SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, dl, MVT::i32) };
8868   return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops);
8869 }
8870 
8871 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8872                               ArrayRef<SDUse> Ops) {
8873   switch (Ops.size()) {
8874   case 0: return getNode(Opcode, DL, VT);
8875   case 1: return getNode(Opcode, DL, VT, static_cast<const SDValue>(Ops[0]));
8876   case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
8877   case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
8878   default: break;
8879   }
8880 
8881   // Copy from an SDUse array into an SDValue array for use with
8882   // the regular getNode logic.
8883   SmallVector<SDValue, 8> NewOps(Ops.begin(), Ops.end());
8884   return getNode(Opcode, DL, VT, NewOps);
8885 }
8886 
8887 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8888                               ArrayRef<SDValue> Ops) {
8889   SDNodeFlags Flags;
8890   if (Inserter)
8891     Flags = Inserter->getFlags();
8892   return getNode(Opcode, DL, VT, Ops, Flags);
8893 }
8894 
8895 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8896                               ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
8897   unsigned NumOps = Ops.size();
8898   switch (NumOps) {
8899   case 0: return getNode(Opcode, DL, VT);
8900   case 1: return getNode(Opcode, DL, VT, Ops[0], Flags);
8901   case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Flags);
8902   case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2], Flags);
8903   default: break;
8904   }
8905 
8906 #ifndef NDEBUG
8907   for (auto &Op : Ops)
8908     assert(Op.getOpcode() != ISD::DELETED_NODE &&
8909            "Operand is DELETED_NODE!");
8910 #endif
8911 
8912   switch (Opcode) {
8913   default: break;
8914   case ISD::BUILD_VECTOR:
8915     // Attempt to simplify BUILD_VECTOR.
8916     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
8917       return V;
8918     break;
8919   case ISD::CONCAT_VECTORS:
8920     if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
8921       return V;
8922     break;
8923   case ISD::SELECT_CC:
8924     assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
8925     assert(Ops[0].getValueType() == Ops[1].getValueType() &&
8926            "LHS and RHS of condition must have same type!");
8927     assert(Ops[2].getValueType() == Ops[3].getValueType() &&
8928            "True and False arms of SelectCC must have same type!");
8929     assert(Ops[2].getValueType() == VT &&
8930            "select_cc node must be of same type as true and false value!");
8931     break;
8932   case ISD::BR_CC:
8933     assert(NumOps == 5 && "BR_CC takes 5 operands!");
8934     assert(Ops[2].getValueType() == Ops[3].getValueType() &&
8935            "LHS/RHS of comparison should match types!");
8936     break;
8937   case ISD::VP_ADD:
8938   case ISD::VP_SUB:
8939     // If it is VP_ADD/VP_SUB mask operation then turn it to VP_XOR
8940     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
8941       Opcode = ISD::VP_XOR;
8942     break;
8943   case ISD::VP_MUL:
8944     // If it is VP_MUL mask operation then turn it to VP_AND
8945     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
8946       Opcode = ISD::VP_AND;
8947     break;
8948   case ISD::VP_REDUCE_MUL:
8949     // If it is VP_REDUCE_MUL mask operation then turn it to VP_REDUCE_AND
8950     if (VT == MVT::i1)
8951       Opcode = ISD::VP_REDUCE_AND;
8952     break;
8953   case ISD::VP_REDUCE_ADD:
8954     // If it is VP_REDUCE_ADD mask operation then turn it to VP_REDUCE_XOR
8955     if (VT == MVT::i1)
8956       Opcode = ISD::VP_REDUCE_XOR;
8957     break;
8958   case ISD::VP_REDUCE_SMAX:
8959   case ISD::VP_REDUCE_UMIN:
8960     // If it is VP_REDUCE_SMAX/VP_REDUCE_UMIN mask operation then turn it to
8961     // VP_REDUCE_AND.
8962     if (VT == MVT::i1)
8963       Opcode = ISD::VP_REDUCE_AND;
8964     break;
8965   case ISD::VP_REDUCE_SMIN:
8966   case ISD::VP_REDUCE_UMAX:
8967     // If it is VP_REDUCE_SMIN/VP_REDUCE_UMAX mask operation then turn it to
8968     // VP_REDUCE_OR.
8969     if (VT == MVT::i1)
8970       Opcode = ISD::VP_REDUCE_OR;
8971     break;
8972   }
8973 
8974   // Memoize nodes.
8975   SDNode *N;
8976   SDVTList VTs = getVTList(VT);
8977 
8978   if (VT != MVT::Glue) {
8979     FoldingSetNodeID ID;
8980     AddNodeIDNode(ID, Opcode, VTs, Ops);
8981     void *IP = nullptr;
8982 
8983     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
8984       return SDValue(E, 0);
8985 
8986     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
8987     createOperands(N, Ops);
8988 
8989     CSEMap.InsertNode(N, IP);
8990   } else {
8991     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
8992     createOperands(N, Ops);
8993   }
8994 
8995   N->setFlags(Flags);
8996   InsertNode(N);
8997   SDValue V(N, 0);
8998   NewSDValueDbgMsg(V, "Creating new node: ", this);
8999   return V;
9000 }
9001 
9002 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
9003                               ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) {
9004   return getNode(Opcode, DL, getVTList(ResultTys), Ops);
9005 }
9006 
9007 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
9008                               ArrayRef<SDValue> Ops) {
9009   SDNodeFlags Flags;
9010   if (Inserter)
9011     Flags = Inserter->getFlags();
9012   return getNode(Opcode, DL, VTList, Ops, Flags);
9013 }
9014 
9015 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
9016                               ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
9017   if (VTList.NumVTs == 1)
9018     return getNode(Opcode, DL, VTList.VTs[0], Ops, Flags);
9019 
9020 #ifndef NDEBUG
9021   for (auto &Op : Ops)
9022     assert(Op.getOpcode() != ISD::DELETED_NODE &&
9023            "Operand is DELETED_NODE!");
9024 #endif
9025 
9026   switch (Opcode) {
9027   case ISD::STRICT_FP_EXTEND:
9028     assert(VTList.NumVTs == 2 && Ops.size() == 2 &&
9029            "Invalid STRICT_FP_EXTEND!");
9030     assert(VTList.VTs[0].isFloatingPoint() &&
9031            Ops[1].getValueType().isFloatingPoint() && "Invalid FP cast!");
9032     assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
9033            "STRICT_FP_EXTEND result type should be vector iff the operand "
9034            "type is vector!");
9035     assert((!VTList.VTs[0].isVector() ||
9036             VTList.VTs[0].getVectorNumElements() ==
9037             Ops[1].getValueType().getVectorNumElements()) &&
9038            "Vector element count mismatch!");
9039     assert(Ops[1].getValueType().bitsLT(VTList.VTs[0]) &&
9040            "Invalid fpext node, dst <= src!");
9041     break;
9042   case ISD::STRICT_FP_ROUND:
9043     assert(VTList.NumVTs == 2 && Ops.size() == 3 && "Invalid STRICT_FP_ROUND!");
9044     assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
9045            "STRICT_FP_ROUND result type should be vector iff the operand "
9046            "type is vector!");
9047     assert((!VTList.VTs[0].isVector() ||
9048             VTList.VTs[0].getVectorNumElements() ==
9049             Ops[1].getValueType().getVectorNumElements()) &&
9050            "Vector element count mismatch!");
9051     assert(VTList.VTs[0].isFloatingPoint() &&
9052            Ops[1].getValueType().isFloatingPoint() &&
9053            VTList.VTs[0].bitsLT(Ops[1].getValueType()) &&
9054            isa<ConstantSDNode>(Ops[2]) &&
9055            (cast<ConstantSDNode>(Ops[2])->getZExtValue() == 0 ||
9056             cast<ConstantSDNode>(Ops[2])->getZExtValue() == 1) &&
9057            "Invalid STRICT_FP_ROUND!");
9058     break;
9059 #if 0
9060   // FIXME: figure out how to safely handle things like
9061   // int foo(int x) { return 1 << (x & 255); }
9062   // int bar() { return foo(256); }
9063   case ISD::SRA_PARTS:
9064   case ISD::SRL_PARTS:
9065   case ISD::SHL_PARTS:
9066     if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
9067         cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
9068       return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
9069     else if (N3.getOpcode() == ISD::AND)
9070       if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
9071         // If the and is only masking out bits that cannot effect the shift,
9072         // eliminate the and.
9073         unsigned NumBits = VT.getScalarSizeInBits()*2;
9074         if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
9075           return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
9076       }
9077     break;
9078 #endif
9079   }
9080 
9081   // Memoize the node unless it returns a flag.
9082   SDNode *N;
9083   if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
9084     FoldingSetNodeID ID;
9085     AddNodeIDNode(ID, Opcode, VTList, Ops);
9086     void *IP = nullptr;
9087     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
9088       return SDValue(E, 0);
9089 
9090     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
9091     createOperands(N, Ops);
9092     CSEMap.InsertNode(N, IP);
9093   } else {
9094     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
9095     createOperands(N, Ops);
9096   }
9097 
9098   N->setFlags(Flags);
9099   InsertNode(N);
9100   SDValue V(N, 0);
9101   NewSDValueDbgMsg(V, "Creating new node: ", this);
9102   return V;
9103 }
9104 
9105 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
9106                               SDVTList VTList) {
9107   return getNode(Opcode, DL, VTList, None);
9108 }
9109 
9110 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
9111                               SDValue N1) {
9112   SDValue Ops[] = { N1 };
9113   return getNode(Opcode, DL, VTList, Ops);
9114 }
9115 
9116 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
9117                               SDValue N1, SDValue N2) {
9118   SDValue Ops[] = { N1, N2 };
9119   return getNode(Opcode, DL, VTList, Ops);
9120 }
9121 
9122 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
9123                               SDValue N1, SDValue N2, SDValue N3) {
9124   SDValue Ops[] = { N1, N2, N3 };
9125   return getNode(Opcode, DL, VTList, Ops);
9126 }
9127 
9128 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
9129                               SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
9130   SDValue Ops[] = { N1, N2, N3, N4 };
9131   return getNode(Opcode, DL, VTList, Ops);
9132 }
9133 
9134 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
9135                               SDValue N1, SDValue N2, SDValue N3, SDValue N4,
9136                               SDValue N5) {
9137   SDValue Ops[] = { N1, N2, N3, N4, N5 };
9138   return getNode(Opcode, DL, VTList, Ops);
9139 }
9140 
9141 SDVTList SelectionDAG::getVTList(EVT VT) {
9142   return makeVTList(SDNode::getValueTypeList(VT), 1);
9143 }
9144 
9145 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2) {
9146   FoldingSetNodeID ID;
9147   ID.AddInteger(2U);
9148   ID.AddInteger(VT1.getRawBits());
9149   ID.AddInteger(VT2.getRawBits());
9150 
9151   void *IP = nullptr;
9152   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
9153   if (!Result) {
9154     EVT *Array = Allocator.Allocate<EVT>(2);
9155     Array[0] = VT1;
9156     Array[1] = VT2;
9157     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 2);
9158     VTListMap.InsertNode(Result, IP);
9159   }
9160   return Result->getSDVTList();
9161 }
9162 
9163 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3) {
9164   FoldingSetNodeID ID;
9165   ID.AddInteger(3U);
9166   ID.AddInteger(VT1.getRawBits());
9167   ID.AddInteger(VT2.getRawBits());
9168   ID.AddInteger(VT3.getRawBits());
9169 
9170   void *IP = nullptr;
9171   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
9172   if (!Result) {
9173     EVT *Array = Allocator.Allocate<EVT>(3);
9174     Array[0] = VT1;
9175     Array[1] = VT2;
9176     Array[2] = VT3;
9177     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 3);
9178     VTListMap.InsertNode(Result, IP);
9179   }
9180   return Result->getSDVTList();
9181 }
9182 
9183 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4) {
9184   FoldingSetNodeID ID;
9185   ID.AddInteger(4U);
9186   ID.AddInteger(VT1.getRawBits());
9187   ID.AddInteger(VT2.getRawBits());
9188   ID.AddInteger(VT3.getRawBits());
9189   ID.AddInteger(VT4.getRawBits());
9190 
9191   void *IP = nullptr;
9192   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
9193   if (!Result) {
9194     EVT *Array = Allocator.Allocate<EVT>(4);
9195     Array[0] = VT1;
9196     Array[1] = VT2;
9197     Array[2] = VT3;
9198     Array[3] = VT4;
9199     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 4);
9200     VTListMap.InsertNode(Result, IP);
9201   }
9202   return Result->getSDVTList();
9203 }
9204 
9205 SDVTList SelectionDAG::getVTList(ArrayRef<EVT> VTs) {
9206   unsigned NumVTs = VTs.size();
9207   FoldingSetNodeID ID;
9208   ID.AddInteger(NumVTs);
9209   for (unsigned index = 0; index < NumVTs; index++) {
9210     ID.AddInteger(VTs[index].getRawBits());
9211   }
9212 
9213   void *IP = nullptr;
9214   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
9215   if (!Result) {
9216     EVT *Array = Allocator.Allocate<EVT>(NumVTs);
9217     llvm::copy(VTs, Array);
9218     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, NumVTs);
9219     VTListMap.InsertNode(Result, IP);
9220   }
9221   return Result->getSDVTList();
9222 }
9223 
9224 
9225 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
9226 /// specified operands.  If the resultant node already exists in the DAG,
9227 /// this does not modify the specified node, instead it returns the node that
9228 /// already exists.  If the resultant node does not exist in the DAG, the
9229 /// input node is returned.  As a degenerate case, if you specify the same
9230 /// input operands as the node already has, the input node is returned.
9231 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op) {
9232   assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
9233 
9234   // Check to see if there is no change.
9235   if (Op == N->getOperand(0)) return N;
9236 
9237   // See if the modified node already exists.
9238   void *InsertPos = nullptr;
9239   if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
9240     return Existing;
9241 
9242   // Nope it doesn't.  Remove the node from its current place in the maps.
9243   if (InsertPos)
9244     if (!RemoveNodeFromCSEMaps(N))
9245       InsertPos = nullptr;
9246 
9247   // Now we update the operands.
9248   N->OperandList[0].set(Op);
9249 
9250   updateDivergence(N);
9251   // If this gets put into a CSE map, add it.
9252   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
9253   return N;
9254 }
9255 
9256 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2) {
9257   assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
9258 
9259   // Check to see if there is no change.
9260   if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
9261     return N;   // No operands changed, just return the input node.
9262 
9263   // See if the modified node already exists.
9264   void *InsertPos = nullptr;
9265   if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
9266     return Existing;
9267 
9268   // Nope it doesn't.  Remove the node from its current place in the maps.
9269   if (InsertPos)
9270     if (!RemoveNodeFromCSEMaps(N))
9271       InsertPos = nullptr;
9272 
9273   // Now we update the operands.
9274   if (N->OperandList[0] != Op1)
9275     N->OperandList[0].set(Op1);
9276   if (N->OperandList[1] != Op2)
9277     N->OperandList[1].set(Op2);
9278 
9279   updateDivergence(N);
9280   // If this gets put into a CSE map, add it.
9281   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
9282   return N;
9283 }
9284 
9285 SDNode *SelectionDAG::
9286 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, SDValue Op3) {
9287   SDValue Ops[] = { Op1, Op2, Op3 };
9288   return UpdateNodeOperands(N, Ops);
9289 }
9290 
9291 SDNode *SelectionDAG::
9292 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
9293                    SDValue Op3, SDValue Op4) {
9294   SDValue Ops[] = { Op1, Op2, Op3, Op4 };
9295   return UpdateNodeOperands(N, Ops);
9296 }
9297 
9298 SDNode *SelectionDAG::
9299 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
9300                    SDValue Op3, SDValue Op4, SDValue Op5) {
9301   SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 };
9302   return UpdateNodeOperands(N, Ops);
9303 }
9304 
9305 SDNode *SelectionDAG::
9306 UpdateNodeOperands(SDNode *N, ArrayRef<SDValue> Ops) {
9307   unsigned NumOps = Ops.size();
9308   assert(N->getNumOperands() == NumOps &&
9309          "Update with wrong number of operands");
9310 
9311   // If no operands changed just return the input node.
9312   if (std::equal(Ops.begin(), Ops.end(), N->op_begin()))
9313     return N;
9314 
9315   // See if the modified node already exists.
9316   void *InsertPos = nullptr;
9317   if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertPos))
9318     return Existing;
9319 
9320   // Nope it doesn't.  Remove the node from its current place in the maps.
9321   if (InsertPos)
9322     if (!RemoveNodeFromCSEMaps(N))
9323       InsertPos = nullptr;
9324 
9325   // Now we update the operands.
9326   for (unsigned i = 0; i != NumOps; ++i)
9327     if (N->OperandList[i] != Ops[i])
9328       N->OperandList[i].set(Ops[i]);
9329 
9330   updateDivergence(N);
9331   // If this gets put into a CSE map, add it.
9332   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
9333   return N;
9334 }
9335 
9336 /// DropOperands - Release the operands and set this node to have
9337 /// zero operands.
9338 void SDNode::DropOperands() {
9339   // Unlike the code in MorphNodeTo that does this, we don't need to
9340   // watch for dead nodes here.
9341   for (op_iterator I = op_begin(), E = op_end(); I != E; ) {
9342     SDUse &Use = *I++;
9343     Use.set(SDValue());
9344   }
9345 }
9346 
9347 void SelectionDAG::setNodeMemRefs(MachineSDNode *N,
9348                                   ArrayRef<MachineMemOperand *> NewMemRefs) {
9349   if (NewMemRefs.empty()) {
9350     N->clearMemRefs();
9351     return;
9352   }
9353 
9354   // Check if we can avoid allocating by storing a single reference directly.
9355   if (NewMemRefs.size() == 1) {
9356     N->MemRefs = NewMemRefs[0];
9357     N->NumMemRefs = 1;
9358     return;
9359   }
9360 
9361   MachineMemOperand **MemRefsBuffer =
9362       Allocator.template Allocate<MachineMemOperand *>(NewMemRefs.size());
9363   llvm::copy(NewMemRefs, MemRefsBuffer);
9364   N->MemRefs = MemRefsBuffer;
9365   N->NumMemRefs = static_cast<int>(NewMemRefs.size());
9366 }
9367 
9368 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a
9369 /// machine opcode.
9370 ///
9371 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9372                                    EVT VT) {
9373   SDVTList VTs = getVTList(VT);
9374   return SelectNodeTo(N, MachineOpc, VTs, None);
9375 }
9376 
9377 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9378                                    EVT VT, SDValue Op1) {
9379   SDVTList VTs = getVTList(VT);
9380   SDValue Ops[] = { Op1 };
9381   return SelectNodeTo(N, MachineOpc, VTs, Ops);
9382 }
9383 
9384 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9385                                    EVT VT, SDValue Op1,
9386                                    SDValue Op2) {
9387   SDVTList VTs = getVTList(VT);
9388   SDValue Ops[] = { Op1, Op2 };
9389   return SelectNodeTo(N, MachineOpc, VTs, Ops);
9390 }
9391 
9392 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9393                                    EVT VT, SDValue Op1,
9394                                    SDValue Op2, SDValue Op3) {
9395   SDVTList VTs = getVTList(VT);
9396   SDValue Ops[] = { Op1, Op2, Op3 };
9397   return SelectNodeTo(N, MachineOpc, VTs, Ops);
9398 }
9399 
9400 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9401                                    EVT VT, ArrayRef<SDValue> Ops) {
9402   SDVTList VTs = getVTList(VT);
9403   return SelectNodeTo(N, MachineOpc, VTs, Ops);
9404 }
9405 
9406 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9407                                    EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) {
9408   SDVTList VTs = getVTList(VT1, VT2);
9409   return SelectNodeTo(N, MachineOpc, VTs, Ops);
9410 }
9411 
9412 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9413                                    EVT VT1, EVT VT2) {
9414   SDVTList VTs = getVTList(VT1, VT2);
9415   return SelectNodeTo(N, MachineOpc, VTs, None);
9416 }
9417 
9418 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9419                                    EVT VT1, EVT VT2, EVT VT3,
9420                                    ArrayRef<SDValue> Ops) {
9421   SDVTList VTs = getVTList(VT1, VT2, VT3);
9422   return SelectNodeTo(N, MachineOpc, VTs, Ops);
9423 }
9424 
9425 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9426                                    EVT VT1, EVT VT2,
9427                                    SDValue Op1, SDValue Op2) {
9428   SDVTList VTs = getVTList(VT1, VT2);
9429   SDValue Ops[] = { Op1, Op2 };
9430   return SelectNodeTo(N, MachineOpc, VTs, Ops);
9431 }
9432 
9433 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9434                                    SDVTList VTs,ArrayRef<SDValue> Ops) {
9435   SDNode *New = MorphNodeTo(N, ~MachineOpc, VTs, Ops);
9436   // Reset the NodeID to -1.
9437   New->setNodeId(-1);
9438   if (New != N) {
9439     ReplaceAllUsesWith(N, New);
9440     RemoveDeadNode(N);
9441   }
9442   return New;
9443 }
9444 
9445 /// UpdateSDLocOnMergeSDNode - If the opt level is -O0 then it throws away
9446 /// the line number information on the merged node since it is not possible to
9447 /// preserve the information that operation is associated with multiple lines.
9448 /// This will make the debugger working better at -O0, were there is a higher
9449 /// probability having other instructions associated with that line.
9450 ///
9451 /// For IROrder, we keep the smaller of the two
9452 SDNode *SelectionDAG::UpdateSDLocOnMergeSDNode(SDNode *N, const SDLoc &OLoc) {
9453   DebugLoc NLoc = N->getDebugLoc();
9454   if (NLoc && OptLevel == CodeGenOpt::None && OLoc.getDebugLoc() != NLoc) {
9455     N->setDebugLoc(DebugLoc());
9456   }
9457   unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder());
9458   N->setIROrder(Order);
9459   return N;
9460 }
9461 
9462 /// MorphNodeTo - This *mutates* the specified node to have the specified
9463 /// return type, opcode, and operands.
9464 ///
9465 /// Note that MorphNodeTo returns the resultant node.  If there is already a
9466 /// node of the specified opcode and operands, it returns that node instead of
9467 /// the current one.  Note that the SDLoc need not be the same.
9468 ///
9469 /// Using MorphNodeTo is faster than creating a new node and swapping it in
9470 /// with ReplaceAllUsesWith both because it often avoids allocating a new
9471 /// node, and because it doesn't require CSE recalculation for any of
9472 /// the node's users.
9473 ///
9474 /// However, note that MorphNodeTo recursively deletes dead nodes from the DAG.
9475 /// As a consequence it isn't appropriate to use from within the DAG combiner or
9476 /// the legalizer which maintain worklists that would need to be updated when
9477 /// deleting things.
9478 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
9479                                   SDVTList VTs, ArrayRef<SDValue> Ops) {
9480   // If an identical node already exists, use it.
9481   void *IP = nullptr;
9482   if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) {
9483     FoldingSetNodeID ID;
9484     AddNodeIDNode(ID, Opc, VTs, Ops);
9485     if (SDNode *ON = FindNodeOrInsertPos(ID, SDLoc(N), IP))
9486       return UpdateSDLocOnMergeSDNode(ON, SDLoc(N));
9487   }
9488 
9489   if (!RemoveNodeFromCSEMaps(N))
9490     IP = nullptr;
9491 
9492   // Start the morphing.
9493   N->NodeType = Opc;
9494   N->ValueList = VTs.VTs;
9495   N->NumValues = VTs.NumVTs;
9496 
9497   // Clear the operands list, updating used nodes to remove this from their
9498   // use list.  Keep track of any operands that become dead as a result.
9499   SmallPtrSet<SDNode*, 16> DeadNodeSet;
9500   for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
9501     SDUse &Use = *I++;
9502     SDNode *Used = Use.getNode();
9503     Use.set(SDValue());
9504     if (Used->use_empty())
9505       DeadNodeSet.insert(Used);
9506   }
9507 
9508   // For MachineNode, initialize the memory references information.
9509   if (MachineSDNode *MN = dyn_cast<MachineSDNode>(N))
9510     MN->clearMemRefs();
9511 
9512   // Swap for an appropriately sized array from the recycler.
9513   removeOperands(N);
9514   createOperands(N, Ops);
9515 
9516   // Delete any nodes that are still dead after adding the uses for the
9517   // new operands.
9518   if (!DeadNodeSet.empty()) {
9519     SmallVector<SDNode *, 16> DeadNodes;
9520     for (SDNode *N : DeadNodeSet)
9521       if (N->use_empty())
9522         DeadNodes.push_back(N);
9523     RemoveDeadNodes(DeadNodes);
9524   }
9525 
9526   if (IP)
9527     CSEMap.InsertNode(N, IP);   // Memoize the new node.
9528   return N;
9529 }
9530 
9531 SDNode* SelectionDAG::mutateStrictFPToFP(SDNode *Node) {
9532   unsigned OrigOpc = Node->getOpcode();
9533   unsigned NewOpc;
9534   switch (OrigOpc) {
9535   default:
9536     llvm_unreachable("mutateStrictFPToFP called with unexpected opcode!");
9537 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
9538   case ISD::STRICT_##DAGN: NewOpc = ISD::DAGN; break;
9539 #define CMP_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
9540   case ISD::STRICT_##DAGN: NewOpc = ISD::SETCC; break;
9541 #include "llvm/IR/ConstrainedOps.def"
9542   }
9543 
9544   assert(Node->getNumValues() == 2 && "Unexpected number of results!");
9545 
9546   // We're taking this node out of the chain, so we need to re-link things.
9547   SDValue InputChain = Node->getOperand(0);
9548   SDValue OutputChain = SDValue(Node, 1);
9549   ReplaceAllUsesOfValueWith(OutputChain, InputChain);
9550 
9551   SmallVector<SDValue, 3> Ops;
9552   for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
9553     Ops.push_back(Node->getOperand(i));
9554 
9555   SDVTList VTs = getVTList(Node->getValueType(0));
9556   SDNode *Res = MorphNodeTo(Node, NewOpc, VTs, Ops);
9557 
9558   // MorphNodeTo can operate in two ways: if an existing node with the
9559   // specified operands exists, it can just return it.  Otherwise, it
9560   // updates the node in place to have the requested operands.
9561   if (Res == Node) {
9562     // If we updated the node in place, reset the node ID.  To the isel,
9563     // this should be just like a newly allocated machine node.
9564     Res->setNodeId(-1);
9565   } else {
9566     ReplaceAllUsesWith(Node, Res);
9567     RemoveDeadNode(Node);
9568   }
9569 
9570   return Res;
9571 }
9572 
9573 /// getMachineNode - These are used for target selectors to create a new node
9574 /// with specified return type(s), MachineInstr opcode, and operands.
9575 ///
9576 /// Note that getMachineNode returns the resultant node.  If there is already a
9577 /// node of the specified opcode and operands, it returns that node instead of
9578 /// the current one.
9579 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9580                                             EVT VT) {
9581   SDVTList VTs = getVTList(VT);
9582   return getMachineNode(Opcode, dl, VTs, None);
9583 }
9584 
9585 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9586                                             EVT VT, SDValue Op1) {
9587   SDVTList VTs = getVTList(VT);
9588   SDValue Ops[] = { Op1 };
9589   return getMachineNode(Opcode, dl, VTs, Ops);
9590 }
9591 
9592 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9593                                             EVT VT, SDValue Op1, SDValue Op2) {
9594   SDVTList VTs = getVTList(VT);
9595   SDValue Ops[] = { Op1, Op2 };
9596   return getMachineNode(Opcode, dl, VTs, Ops);
9597 }
9598 
9599 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9600                                             EVT VT, SDValue Op1, SDValue Op2,
9601                                             SDValue Op3) {
9602   SDVTList VTs = getVTList(VT);
9603   SDValue Ops[] = { Op1, Op2, Op3 };
9604   return getMachineNode(Opcode, dl, VTs, Ops);
9605 }
9606 
9607 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9608                                             EVT VT, ArrayRef<SDValue> Ops) {
9609   SDVTList VTs = getVTList(VT);
9610   return getMachineNode(Opcode, dl, VTs, Ops);
9611 }
9612 
9613 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9614                                             EVT VT1, EVT VT2, SDValue Op1,
9615                                             SDValue Op2) {
9616   SDVTList VTs = getVTList(VT1, VT2);
9617   SDValue Ops[] = { Op1, Op2 };
9618   return getMachineNode(Opcode, dl, VTs, Ops);
9619 }
9620 
9621 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9622                                             EVT VT1, EVT VT2, SDValue Op1,
9623                                             SDValue Op2, SDValue Op3) {
9624   SDVTList VTs = getVTList(VT1, VT2);
9625   SDValue Ops[] = { Op1, Op2, Op3 };
9626   return getMachineNode(Opcode, dl, VTs, Ops);
9627 }
9628 
9629 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9630                                             EVT VT1, EVT VT2,
9631                                             ArrayRef<SDValue> Ops) {
9632   SDVTList VTs = getVTList(VT1, VT2);
9633   return getMachineNode(Opcode, dl, VTs, Ops);
9634 }
9635 
9636 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9637                                             EVT VT1, EVT VT2, EVT VT3,
9638                                             SDValue Op1, SDValue Op2) {
9639   SDVTList VTs = getVTList(VT1, VT2, VT3);
9640   SDValue Ops[] = { Op1, Op2 };
9641   return getMachineNode(Opcode, dl, VTs, Ops);
9642 }
9643 
9644 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9645                                             EVT VT1, EVT VT2, EVT VT3,
9646                                             SDValue Op1, SDValue Op2,
9647                                             SDValue Op3) {
9648   SDVTList VTs = getVTList(VT1, VT2, VT3);
9649   SDValue Ops[] = { Op1, Op2, Op3 };
9650   return getMachineNode(Opcode, dl, VTs, Ops);
9651 }
9652 
9653 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9654                                             EVT VT1, EVT VT2, EVT VT3,
9655                                             ArrayRef<SDValue> Ops) {
9656   SDVTList VTs = getVTList(VT1, VT2, VT3);
9657   return getMachineNode(Opcode, dl, VTs, Ops);
9658 }
9659 
9660 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9661                                             ArrayRef<EVT> ResultTys,
9662                                             ArrayRef<SDValue> Ops) {
9663   SDVTList VTs = getVTList(ResultTys);
9664   return getMachineNode(Opcode, dl, VTs, Ops);
9665 }
9666 
9667 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &DL,
9668                                             SDVTList VTs,
9669                                             ArrayRef<SDValue> Ops) {
9670   bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue;
9671   MachineSDNode *N;
9672   void *IP = nullptr;
9673 
9674   if (DoCSE) {
9675     FoldingSetNodeID ID;
9676     AddNodeIDNode(ID, ~Opcode, VTs, Ops);
9677     IP = nullptr;
9678     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
9679       return cast<MachineSDNode>(UpdateSDLocOnMergeSDNode(E, DL));
9680     }
9681   }
9682 
9683   // Allocate a new MachineSDNode.
9684   N = newSDNode<MachineSDNode>(~Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
9685   createOperands(N, Ops);
9686 
9687   if (DoCSE)
9688     CSEMap.InsertNode(N, IP);
9689 
9690   InsertNode(N);
9691   NewSDValueDbgMsg(SDValue(N, 0), "Creating new machine node: ", this);
9692   return N;
9693 }
9694 
9695 /// getTargetExtractSubreg - A convenience function for creating
9696 /// TargetOpcode::EXTRACT_SUBREG nodes.
9697 SDValue SelectionDAG::getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT,
9698                                              SDValue Operand) {
9699   SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
9700   SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,
9701                                   VT, Operand, SRIdxVal);
9702   return SDValue(Subreg, 0);
9703 }
9704 
9705 /// getTargetInsertSubreg - A convenience function for creating
9706 /// TargetOpcode::INSERT_SUBREG nodes.
9707 SDValue SelectionDAG::getTargetInsertSubreg(int SRIdx, const SDLoc &DL, EVT VT,
9708                                             SDValue Operand, SDValue Subreg) {
9709   SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
9710   SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL,
9711                                   VT, Operand, Subreg, SRIdxVal);
9712   return SDValue(Result, 0);
9713 }
9714 
9715 /// getNodeIfExists - Get the specified node if it's already available, or
9716 /// else return NULL.
9717 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
9718                                       ArrayRef<SDValue> Ops) {
9719   SDNodeFlags Flags;
9720   if (Inserter)
9721     Flags = Inserter->getFlags();
9722   return getNodeIfExists(Opcode, VTList, Ops, Flags);
9723 }
9724 
9725 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
9726                                       ArrayRef<SDValue> Ops,
9727                                       const SDNodeFlags Flags) {
9728   if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
9729     FoldingSetNodeID ID;
9730     AddNodeIDNode(ID, Opcode, VTList, Ops);
9731     void *IP = nullptr;
9732     if (SDNode *E = FindNodeOrInsertPos(ID, SDLoc(), IP)) {
9733       E->intersectFlagsWith(Flags);
9734       return E;
9735     }
9736   }
9737   return nullptr;
9738 }
9739 
9740 /// doesNodeExist - Check if a node exists without modifying its flags.
9741 bool SelectionDAG::doesNodeExist(unsigned Opcode, SDVTList VTList,
9742                                  ArrayRef<SDValue> Ops) {
9743   if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
9744     FoldingSetNodeID ID;
9745     AddNodeIDNode(ID, Opcode, VTList, Ops);
9746     void *IP = nullptr;
9747     if (FindNodeOrInsertPos(ID, SDLoc(), IP))
9748       return true;
9749   }
9750   return false;
9751 }
9752 
9753 /// getDbgValue - Creates a SDDbgValue node.
9754 ///
9755 /// SDNode
9756 SDDbgValue *SelectionDAG::getDbgValue(DIVariable *Var, DIExpression *Expr,
9757                                       SDNode *N, unsigned R, bool IsIndirect,
9758                                       const DebugLoc &DL, unsigned O) {
9759   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9760          "Expected inlined-at fields to agree");
9761   return new (DbgInfo->getAlloc())
9762       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromNode(N, R),
9763                  {}, IsIndirect, DL, O,
9764                  /*IsVariadic=*/false);
9765 }
9766 
9767 /// Constant
9768 SDDbgValue *SelectionDAG::getConstantDbgValue(DIVariable *Var,
9769                                               DIExpression *Expr,
9770                                               const Value *C,
9771                                               const DebugLoc &DL, unsigned O) {
9772   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9773          "Expected inlined-at fields to agree");
9774   return new (DbgInfo->getAlloc())
9775       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromConst(C), {},
9776                  /*IsIndirect=*/false, DL, O,
9777                  /*IsVariadic=*/false);
9778 }
9779 
9780 /// FrameIndex
9781 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var,
9782                                                 DIExpression *Expr, unsigned FI,
9783                                                 bool IsIndirect,
9784                                                 const DebugLoc &DL,
9785                                                 unsigned O) {
9786   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9787          "Expected inlined-at fields to agree");
9788   return getFrameIndexDbgValue(Var, Expr, FI, {}, IsIndirect, DL, O);
9789 }
9790 
9791 /// FrameIndex with dependencies
9792 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var,
9793                                                 DIExpression *Expr, unsigned FI,
9794                                                 ArrayRef<SDNode *> Dependencies,
9795                                                 bool IsIndirect,
9796                                                 const DebugLoc &DL,
9797                                                 unsigned O) {
9798   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9799          "Expected inlined-at fields to agree");
9800   return new (DbgInfo->getAlloc())
9801       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromFrameIdx(FI),
9802                  Dependencies, IsIndirect, DL, O,
9803                  /*IsVariadic=*/false);
9804 }
9805 
9806 /// VReg
9807 SDDbgValue *SelectionDAG::getVRegDbgValue(DIVariable *Var, DIExpression *Expr,
9808                                           unsigned VReg, bool IsIndirect,
9809                                           const DebugLoc &DL, unsigned O) {
9810   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9811          "Expected inlined-at fields to agree");
9812   return new (DbgInfo->getAlloc())
9813       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromVReg(VReg),
9814                  {}, IsIndirect, DL, O,
9815                  /*IsVariadic=*/false);
9816 }
9817 
9818 SDDbgValue *SelectionDAG::getDbgValueList(DIVariable *Var, DIExpression *Expr,
9819                                           ArrayRef<SDDbgOperand> Locs,
9820                                           ArrayRef<SDNode *> Dependencies,
9821                                           bool IsIndirect, const DebugLoc &DL,
9822                                           unsigned O, bool IsVariadic) {
9823   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9824          "Expected inlined-at fields to agree");
9825   return new (DbgInfo->getAlloc())
9826       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, Locs, Dependencies, IsIndirect,
9827                  DL, O, IsVariadic);
9828 }
9829 
9830 void SelectionDAG::transferDbgValues(SDValue From, SDValue To,
9831                                      unsigned OffsetInBits, unsigned SizeInBits,
9832                                      bool InvalidateDbg) {
9833   SDNode *FromNode = From.getNode();
9834   SDNode *ToNode = To.getNode();
9835   assert(FromNode && ToNode && "Can't modify dbg values");
9836 
9837   // PR35338
9838   // TODO: assert(From != To && "Redundant dbg value transfer");
9839   // TODO: assert(FromNode != ToNode && "Intranode dbg value transfer");
9840   if (From == To || FromNode == ToNode)
9841     return;
9842 
9843   if (!FromNode->getHasDebugValue())
9844     return;
9845 
9846   SDDbgOperand FromLocOp =
9847       SDDbgOperand::fromNode(From.getNode(), From.getResNo());
9848   SDDbgOperand ToLocOp = SDDbgOperand::fromNode(To.getNode(), To.getResNo());
9849 
9850   SmallVector<SDDbgValue *, 2> ClonedDVs;
9851   for (SDDbgValue *Dbg : GetDbgValues(FromNode)) {
9852     if (Dbg->isInvalidated())
9853       continue;
9854 
9855     // TODO: assert(!Dbg->isInvalidated() && "Transfer of invalid dbg value");
9856 
9857     // Create a new location ops vector that is equal to the old vector, but
9858     // with each instance of FromLocOp replaced with ToLocOp.
9859     bool Changed = false;
9860     auto NewLocOps = Dbg->copyLocationOps();
9861     std::replace_if(
9862         NewLocOps.begin(), NewLocOps.end(),
9863         [&Changed, FromLocOp](const SDDbgOperand &Op) {
9864           bool Match = Op == FromLocOp;
9865           Changed |= Match;
9866           return Match;
9867         },
9868         ToLocOp);
9869     // Ignore this SDDbgValue if we didn't find a matching location.
9870     if (!Changed)
9871       continue;
9872 
9873     DIVariable *Var = Dbg->getVariable();
9874     auto *Expr = Dbg->getExpression();
9875     // If a fragment is requested, update the expression.
9876     if (SizeInBits) {
9877       // When splitting a larger (e.g., sign-extended) value whose
9878       // lower bits are described with an SDDbgValue, do not attempt
9879       // to transfer the SDDbgValue to the upper bits.
9880       if (auto FI = Expr->getFragmentInfo())
9881         if (OffsetInBits + SizeInBits > FI->SizeInBits)
9882           continue;
9883       auto Fragment = DIExpression::createFragmentExpression(Expr, OffsetInBits,
9884                                                              SizeInBits);
9885       if (!Fragment)
9886         continue;
9887       Expr = *Fragment;
9888     }
9889 
9890     auto AdditionalDependencies = Dbg->getAdditionalDependencies();
9891     // Clone the SDDbgValue and move it to To.
9892     SDDbgValue *Clone = getDbgValueList(
9893         Var, Expr, NewLocOps, AdditionalDependencies, Dbg->isIndirect(),
9894         Dbg->getDebugLoc(), std::max(ToNode->getIROrder(), Dbg->getOrder()),
9895         Dbg->isVariadic());
9896     ClonedDVs.push_back(Clone);
9897 
9898     if (InvalidateDbg) {
9899       // Invalidate value and indicate the SDDbgValue should not be emitted.
9900       Dbg->setIsInvalidated();
9901       Dbg->setIsEmitted();
9902     }
9903   }
9904 
9905   for (SDDbgValue *Dbg : ClonedDVs) {
9906     assert(is_contained(Dbg->getSDNodes(), ToNode) &&
9907            "Transferred DbgValues should depend on the new SDNode");
9908     AddDbgValue(Dbg, false);
9909   }
9910 }
9911 
9912 void SelectionDAG::salvageDebugInfo(SDNode &N) {
9913   if (!N.getHasDebugValue())
9914     return;
9915 
9916   SmallVector<SDDbgValue *, 2> ClonedDVs;
9917   for (auto DV : GetDbgValues(&N)) {
9918     if (DV->isInvalidated())
9919       continue;
9920     switch (N.getOpcode()) {
9921     default:
9922       break;
9923     case ISD::ADD:
9924       SDValue N0 = N.getOperand(0);
9925       SDValue N1 = N.getOperand(1);
9926       if (!isConstantIntBuildVectorOrConstantInt(N0) &&
9927           isConstantIntBuildVectorOrConstantInt(N1)) {
9928         uint64_t Offset = N.getConstantOperandVal(1);
9929 
9930         // Rewrite an ADD constant node into a DIExpression. Since we are
9931         // performing arithmetic to compute the variable's *value* in the
9932         // DIExpression, we need to mark the expression with a
9933         // DW_OP_stack_value.
9934         auto *DIExpr = DV->getExpression();
9935         auto NewLocOps = DV->copyLocationOps();
9936         bool Changed = false;
9937         for (size_t i = 0; i < NewLocOps.size(); ++i) {
9938           // We're not given a ResNo to compare against because the whole
9939           // node is going away. We know that any ISD::ADD only has one
9940           // result, so we can assume any node match is using the result.
9941           if (NewLocOps[i].getKind() != SDDbgOperand::SDNODE ||
9942               NewLocOps[i].getSDNode() != &N)
9943             continue;
9944           NewLocOps[i] = SDDbgOperand::fromNode(N0.getNode(), N0.getResNo());
9945           SmallVector<uint64_t, 3> ExprOps;
9946           DIExpression::appendOffset(ExprOps, Offset);
9947           DIExpr = DIExpression::appendOpsToArg(DIExpr, ExprOps, i, true);
9948           Changed = true;
9949         }
9950         (void)Changed;
9951         assert(Changed && "Salvage target doesn't use N");
9952 
9953         auto AdditionalDependencies = DV->getAdditionalDependencies();
9954         SDDbgValue *Clone = getDbgValueList(DV->getVariable(), DIExpr,
9955                                             NewLocOps, AdditionalDependencies,
9956                                             DV->isIndirect(), DV->getDebugLoc(),
9957                                             DV->getOrder(), DV->isVariadic());
9958         ClonedDVs.push_back(Clone);
9959         DV->setIsInvalidated();
9960         DV->setIsEmitted();
9961         LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting";
9962                    N0.getNode()->dumprFull(this);
9963                    dbgs() << " into " << *DIExpr << '\n');
9964       }
9965     }
9966   }
9967 
9968   for (SDDbgValue *Dbg : ClonedDVs) {
9969     assert(!Dbg->getSDNodes().empty() &&
9970            "Salvaged DbgValue should depend on a new SDNode");
9971     AddDbgValue(Dbg, false);
9972   }
9973 }
9974 
9975 /// Creates a SDDbgLabel node.
9976 SDDbgLabel *SelectionDAG::getDbgLabel(DILabel *Label,
9977                                       const DebugLoc &DL, unsigned O) {
9978   assert(cast<DILabel>(Label)->isValidLocationForIntrinsic(DL) &&
9979          "Expected inlined-at fields to agree");
9980   return new (DbgInfo->getAlloc()) SDDbgLabel(Label, DL, O);
9981 }
9982 
9983 namespace {
9984 
9985 /// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node
9986 /// pointed to by a use iterator is deleted, increment the use iterator
9987 /// so that it doesn't dangle.
9988 ///
9989 class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener {
9990   SDNode::use_iterator &UI;
9991   SDNode::use_iterator &UE;
9992 
9993   void NodeDeleted(SDNode *N, SDNode *E) override {
9994     // Increment the iterator as needed.
9995     while (UI != UE && N == *UI)
9996       ++UI;
9997   }
9998 
9999 public:
10000   RAUWUpdateListener(SelectionDAG &d,
10001                      SDNode::use_iterator &ui,
10002                      SDNode::use_iterator &ue)
10003     : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {}
10004 };
10005 
10006 } // end anonymous namespace
10007 
10008 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
10009 /// This can cause recursive merging of nodes in the DAG.
10010 ///
10011 /// This version assumes From has a single result value.
10012 ///
10013 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To) {
10014   SDNode *From = FromN.getNode();
10015   assert(From->getNumValues() == 1 && FromN.getResNo() == 0 &&
10016          "Cannot replace with this method!");
10017   assert(From != To.getNode() && "Cannot replace uses of with self");
10018 
10019   // Preserve Debug Values
10020   transferDbgValues(FromN, To);
10021 
10022   // Iterate over all the existing uses of From. New uses will be added
10023   // to the beginning of the use list, which we avoid visiting.
10024   // This specifically avoids visiting uses of From that arise while the
10025   // replacement is happening, because any such uses would be the result
10026   // of CSE: If an existing node looks like From after one of its operands
10027   // is replaced by To, we don't want to replace of all its users with To
10028   // too. See PR3018 for more info.
10029   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
10030   RAUWUpdateListener Listener(*this, UI, UE);
10031   while (UI != UE) {
10032     SDNode *User = *UI;
10033 
10034     // This node is about to morph, remove its old self from the CSE maps.
10035     RemoveNodeFromCSEMaps(User);
10036 
10037     // A user can appear in a use list multiple times, and when this
10038     // happens the uses are usually next to each other in the list.
10039     // To help reduce the number of CSE recomputations, process all
10040     // the uses of this user that we can find this way.
10041     do {
10042       SDUse &Use = UI.getUse();
10043       ++UI;
10044       Use.set(To);
10045       if (To->isDivergent() != From->isDivergent())
10046         updateDivergence(User);
10047     } while (UI != UE && *UI == User);
10048     // Now that we have modified User, add it back to the CSE maps.  If it
10049     // already exists there, recursively merge the results together.
10050     AddModifiedNodeToCSEMaps(User);
10051   }
10052 
10053   // If we just RAUW'd the root, take note.
10054   if (FromN == getRoot())
10055     setRoot(To);
10056 }
10057 
10058 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
10059 /// This can cause recursive merging of nodes in the DAG.
10060 ///
10061 /// This version assumes that for each value of From, there is a
10062 /// corresponding value in To in the same position with the same type.
10063 ///
10064 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To) {
10065 #ifndef NDEBUG
10066   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
10067     assert((!From->hasAnyUseOfValue(i) ||
10068             From->getValueType(i) == To->getValueType(i)) &&
10069            "Cannot use this version of ReplaceAllUsesWith!");
10070 #endif
10071 
10072   // Handle the trivial case.
10073   if (From == To)
10074     return;
10075 
10076   // Preserve Debug Info. Only do this if there's a use.
10077   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
10078     if (From->hasAnyUseOfValue(i)) {
10079       assert((i < To->getNumValues()) && "Invalid To location");
10080       transferDbgValues(SDValue(From, i), SDValue(To, i));
10081     }
10082 
10083   // Iterate over just the existing users of From. See the comments in
10084   // the ReplaceAllUsesWith above.
10085   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
10086   RAUWUpdateListener Listener(*this, UI, UE);
10087   while (UI != UE) {
10088     SDNode *User = *UI;
10089 
10090     // This node is about to morph, remove its old self from the CSE maps.
10091     RemoveNodeFromCSEMaps(User);
10092 
10093     // A user can appear in a use list multiple times, and when this
10094     // happens the uses are usually next to each other in the list.
10095     // To help reduce the number of CSE recomputations, process all
10096     // the uses of this user that we can find this way.
10097     do {
10098       SDUse &Use = UI.getUse();
10099       ++UI;
10100       Use.setNode(To);
10101       if (To->isDivergent() != From->isDivergent())
10102         updateDivergence(User);
10103     } while (UI != UE && *UI == User);
10104 
10105     // Now that we have modified User, add it back to the CSE maps.  If it
10106     // already exists there, recursively merge the results together.
10107     AddModifiedNodeToCSEMaps(User);
10108   }
10109 
10110   // If we just RAUW'd the root, take note.
10111   if (From == getRoot().getNode())
10112     setRoot(SDValue(To, getRoot().getResNo()));
10113 }
10114 
10115 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
10116 /// This can cause recursive merging of nodes in the DAG.
10117 ///
10118 /// This version can replace From with any result values.  To must match the
10119 /// number and types of values returned by From.
10120 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, const SDValue *To) {
10121   if (From->getNumValues() == 1)  // Handle the simple case efficiently.
10122     return ReplaceAllUsesWith(SDValue(From, 0), To[0]);
10123 
10124   // Preserve Debug Info.
10125   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
10126     transferDbgValues(SDValue(From, i), To[i]);
10127 
10128   // Iterate over just the existing users of From. See the comments in
10129   // the ReplaceAllUsesWith above.
10130   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
10131   RAUWUpdateListener Listener(*this, UI, UE);
10132   while (UI != UE) {
10133     SDNode *User = *UI;
10134 
10135     // This node is about to morph, remove its old self from the CSE maps.
10136     RemoveNodeFromCSEMaps(User);
10137 
10138     // A user can appear in a use list multiple times, and when this happens the
10139     // uses are usually next to each other in the list.  To help reduce the
10140     // number of CSE and divergence recomputations, process all the uses of this
10141     // user that we can find this way.
10142     bool To_IsDivergent = false;
10143     do {
10144       SDUse &Use = UI.getUse();
10145       const SDValue &ToOp = To[Use.getResNo()];
10146       ++UI;
10147       Use.set(ToOp);
10148       To_IsDivergent |= ToOp->isDivergent();
10149     } while (UI != UE && *UI == User);
10150 
10151     if (To_IsDivergent != From->isDivergent())
10152       updateDivergence(User);
10153 
10154     // Now that we have modified User, add it back to the CSE maps.  If it
10155     // already exists there, recursively merge the results together.
10156     AddModifiedNodeToCSEMaps(User);
10157   }
10158 
10159   // If we just RAUW'd the root, take note.
10160   if (From == getRoot().getNode())
10161     setRoot(SDValue(To[getRoot().getResNo()]));
10162 }
10163 
10164 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
10165 /// uses of other values produced by From.getNode() alone.  The Deleted
10166 /// vector is handled the same way as for ReplaceAllUsesWith.
10167 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To){
10168   // Handle the really simple, really trivial case efficiently.
10169   if (From == To) return;
10170 
10171   // Handle the simple, trivial, case efficiently.
10172   if (From.getNode()->getNumValues() == 1) {
10173     ReplaceAllUsesWith(From, To);
10174     return;
10175   }
10176 
10177   // Preserve Debug Info.
10178   transferDbgValues(From, To);
10179 
10180   // Iterate over just the existing users of From. See the comments in
10181   // the ReplaceAllUsesWith above.
10182   SDNode::use_iterator UI = From.getNode()->use_begin(),
10183                        UE = From.getNode()->use_end();
10184   RAUWUpdateListener Listener(*this, UI, UE);
10185   while (UI != UE) {
10186     SDNode *User = *UI;
10187     bool UserRemovedFromCSEMaps = false;
10188 
10189     // A user can appear in a use list multiple times, and when this
10190     // happens the uses are usually next to each other in the list.
10191     // To help reduce the number of CSE recomputations, process all
10192     // the uses of this user that we can find this way.
10193     do {
10194       SDUse &Use = UI.getUse();
10195 
10196       // Skip uses of different values from the same node.
10197       if (Use.getResNo() != From.getResNo()) {
10198         ++UI;
10199         continue;
10200       }
10201 
10202       // If this node hasn't been modified yet, it's still in the CSE maps,
10203       // so remove its old self from the CSE maps.
10204       if (!UserRemovedFromCSEMaps) {
10205         RemoveNodeFromCSEMaps(User);
10206         UserRemovedFromCSEMaps = true;
10207       }
10208 
10209       ++UI;
10210       Use.set(To);
10211       if (To->isDivergent() != From->isDivergent())
10212         updateDivergence(User);
10213     } while (UI != UE && *UI == User);
10214     // We are iterating over all uses of the From node, so if a use
10215     // doesn't use the specific value, no changes are made.
10216     if (!UserRemovedFromCSEMaps)
10217       continue;
10218 
10219     // Now that we have modified User, add it back to the CSE maps.  If it
10220     // already exists there, recursively merge the results together.
10221     AddModifiedNodeToCSEMaps(User);
10222   }
10223 
10224   // If we just RAUW'd the root, take note.
10225   if (From == getRoot())
10226     setRoot(To);
10227 }
10228 
10229 namespace {
10230 
10231 /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith
10232 /// to record information about a use.
10233 struct UseMemo {
10234   SDNode *User;
10235   unsigned Index;
10236   SDUse *Use;
10237 };
10238 
10239 /// operator< - Sort Memos by User.
10240 bool operator<(const UseMemo &L, const UseMemo &R) {
10241   return (intptr_t)L.User < (intptr_t)R.User;
10242 }
10243 
10244 /// RAUOVWUpdateListener - Helper for ReplaceAllUsesOfValuesWith - When the node
10245 /// pointed to by a UseMemo is deleted, set the User to nullptr to indicate that
10246 /// the node already has been taken care of recursively.
10247 class RAUOVWUpdateListener : public SelectionDAG::DAGUpdateListener {
10248   SmallVector<UseMemo, 4> &Uses;
10249 
10250   void NodeDeleted(SDNode *N, SDNode *E) override {
10251     for (UseMemo &Memo : Uses)
10252       if (Memo.User == N)
10253         Memo.User = nullptr;
10254   }
10255 
10256 public:
10257   RAUOVWUpdateListener(SelectionDAG &d, SmallVector<UseMemo, 4> &uses)
10258       : SelectionDAG::DAGUpdateListener(d), Uses(uses) {}
10259 };
10260 
10261 } // end anonymous namespace
10262 
10263 bool SelectionDAG::calculateDivergence(SDNode *N) {
10264   if (TLI->isSDNodeAlwaysUniform(N)) {
10265     assert(!TLI->isSDNodeSourceOfDivergence(N, FLI, DA) &&
10266            "Conflicting divergence information!");
10267     return false;
10268   }
10269   if (TLI->isSDNodeSourceOfDivergence(N, FLI, DA))
10270     return true;
10271   for (auto &Op : N->ops()) {
10272     if (Op.Val.getValueType() != MVT::Other && Op.getNode()->isDivergent())
10273       return true;
10274   }
10275   return false;
10276 }
10277 
10278 void SelectionDAG::updateDivergence(SDNode *N) {
10279   SmallVector<SDNode *, 16> Worklist(1, N);
10280   do {
10281     N = Worklist.pop_back_val();
10282     bool IsDivergent = calculateDivergence(N);
10283     if (N->SDNodeBits.IsDivergent != IsDivergent) {
10284       N->SDNodeBits.IsDivergent = IsDivergent;
10285       llvm::append_range(Worklist, N->uses());
10286     }
10287   } while (!Worklist.empty());
10288 }
10289 
10290 void SelectionDAG::CreateTopologicalOrder(std::vector<SDNode *> &Order) {
10291   DenseMap<SDNode *, unsigned> Degree;
10292   Order.reserve(AllNodes.size());
10293   for (auto &N : allnodes()) {
10294     unsigned NOps = N.getNumOperands();
10295     Degree[&N] = NOps;
10296     if (0 == NOps)
10297       Order.push_back(&N);
10298   }
10299   for (size_t I = 0; I != Order.size(); ++I) {
10300     SDNode *N = Order[I];
10301     for (auto U : N->uses()) {
10302       unsigned &UnsortedOps = Degree[U];
10303       if (0 == --UnsortedOps)
10304         Order.push_back(U);
10305     }
10306   }
10307 }
10308 
10309 #ifndef NDEBUG
10310 void SelectionDAG::VerifyDAGDivergence() {
10311   std::vector<SDNode *> TopoOrder;
10312   CreateTopologicalOrder(TopoOrder);
10313   for (auto *N : TopoOrder) {
10314     assert(calculateDivergence(N) == N->isDivergent() &&
10315            "Divergence bit inconsistency detected");
10316   }
10317 }
10318 #endif
10319 
10320 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving
10321 /// uses of other values produced by From.getNode() alone.  The same value
10322 /// may appear in both the From and To list.  The Deleted vector is
10323 /// handled the same way as for ReplaceAllUsesWith.
10324 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From,
10325                                               const SDValue *To,
10326                                               unsigned Num){
10327   // Handle the simple, trivial case efficiently.
10328   if (Num == 1)
10329     return ReplaceAllUsesOfValueWith(*From, *To);
10330 
10331   transferDbgValues(*From, *To);
10332 
10333   // Read up all the uses and make records of them. This helps
10334   // processing new uses that are introduced during the
10335   // replacement process.
10336   SmallVector<UseMemo, 4> Uses;
10337   for (unsigned i = 0; i != Num; ++i) {
10338     unsigned FromResNo = From[i].getResNo();
10339     SDNode *FromNode = From[i].getNode();
10340     for (SDNode::use_iterator UI = FromNode->use_begin(),
10341          E = FromNode->use_end(); UI != E; ++UI) {
10342       SDUse &Use = UI.getUse();
10343       if (Use.getResNo() == FromResNo) {
10344         UseMemo Memo = { *UI, i, &Use };
10345         Uses.push_back(Memo);
10346       }
10347     }
10348   }
10349 
10350   // Sort the uses, so that all the uses from a given User are together.
10351   llvm::sort(Uses);
10352   RAUOVWUpdateListener Listener(*this, Uses);
10353 
10354   for (unsigned UseIndex = 0, UseIndexEnd = Uses.size();
10355        UseIndex != UseIndexEnd; ) {
10356     // We know that this user uses some value of From.  If it is the right
10357     // value, update it.
10358     SDNode *User = Uses[UseIndex].User;
10359     // If the node has been deleted by recursive CSE updates when updating
10360     // another node, then just skip this entry.
10361     if (User == nullptr) {
10362       ++UseIndex;
10363       continue;
10364     }
10365 
10366     // This node is about to morph, remove its old self from the CSE maps.
10367     RemoveNodeFromCSEMaps(User);
10368 
10369     // The Uses array is sorted, so all the uses for a given User
10370     // are next to each other in the list.
10371     // To help reduce the number of CSE recomputations, process all
10372     // the uses of this user that we can find this way.
10373     do {
10374       unsigned i = Uses[UseIndex].Index;
10375       SDUse &Use = *Uses[UseIndex].Use;
10376       ++UseIndex;
10377 
10378       Use.set(To[i]);
10379     } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User);
10380 
10381     // Now that we have modified User, add it back to the CSE maps.  If it
10382     // already exists there, recursively merge the results together.
10383     AddModifiedNodeToCSEMaps(User);
10384   }
10385 }
10386 
10387 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
10388 /// based on their topological order. It returns the maximum id and a vector
10389 /// of the SDNodes* in assigned order by reference.
10390 unsigned SelectionDAG::AssignTopologicalOrder() {
10391   unsigned DAGSize = 0;
10392 
10393   // SortedPos tracks the progress of the algorithm. Nodes before it are
10394   // sorted, nodes after it are unsorted. When the algorithm completes
10395   // it is at the end of the list.
10396   allnodes_iterator SortedPos = allnodes_begin();
10397 
10398   // Visit all the nodes. Move nodes with no operands to the front of
10399   // the list immediately. Annotate nodes that do have operands with their
10400   // operand count. Before we do this, the Node Id fields of the nodes
10401   // may contain arbitrary values. After, the Node Id fields for nodes
10402   // before SortedPos will contain the topological sort index, and the
10403   // Node Id fields for nodes At SortedPos and after will contain the
10404   // count of outstanding operands.
10405   for (SDNode &N : llvm::make_early_inc_range(allnodes())) {
10406     checkForCycles(&N, this);
10407     unsigned Degree = N.getNumOperands();
10408     if (Degree == 0) {
10409       // A node with no uses, add it to the result array immediately.
10410       N.setNodeId(DAGSize++);
10411       allnodes_iterator Q(&N);
10412       if (Q != SortedPos)
10413         SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q));
10414       assert(SortedPos != AllNodes.end() && "Overran node list");
10415       ++SortedPos;
10416     } else {
10417       // Temporarily use the Node Id as scratch space for the degree count.
10418       N.setNodeId(Degree);
10419     }
10420   }
10421 
10422   // Visit all the nodes. As we iterate, move nodes into sorted order,
10423   // such that by the time the end is reached all nodes will be sorted.
10424   for (SDNode &Node : allnodes()) {
10425     SDNode *N = &Node;
10426     checkForCycles(N, this);
10427     // N is in sorted position, so all its uses have one less operand
10428     // that needs to be sorted.
10429     for (SDNode *P : N->uses()) {
10430       unsigned Degree = P->getNodeId();
10431       assert(Degree != 0 && "Invalid node degree");
10432       --Degree;
10433       if (Degree == 0) {
10434         // All of P's operands are sorted, so P may sorted now.
10435         P->setNodeId(DAGSize++);
10436         if (P->getIterator() != SortedPos)
10437           SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P));
10438         assert(SortedPos != AllNodes.end() && "Overran node list");
10439         ++SortedPos;
10440       } else {
10441         // Update P's outstanding operand count.
10442         P->setNodeId(Degree);
10443       }
10444     }
10445     if (Node.getIterator() == SortedPos) {
10446 #ifndef NDEBUG
10447       allnodes_iterator I(N);
10448       SDNode *S = &*++I;
10449       dbgs() << "Overran sorted position:\n";
10450       S->dumprFull(this); dbgs() << "\n";
10451       dbgs() << "Checking if this is due to cycles\n";
10452       checkForCycles(this, true);
10453 #endif
10454       llvm_unreachable(nullptr);
10455     }
10456   }
10457 
10458   assert(SortedPos == AllNodes.end() &&
10459          "Topological sort incomplete!");
10460   assert(AllNodes.front().getOpcode() == ISD::EntryToken &&
10461          "First node in topological sort is not the entry token!");
10462   assert(AllNodes.front().getNodeId() == 0 &&
10463          "First node in topological sort has non-zero id!");
10464   assert(AllNodes.front().getNumOperands() == 0 &&
10465          "First node in topological sort has operands!");
10466   assert(AllNodes.back().getNodeId() == (int)DAGSize-1 &&
10467          "Last node in topologic sort has unexpected id!");
10468   assert(AllNodes.back().use_empty() &&
10469          "Last node in topologic sort has users!");
10470   assert(DAGSize == allnodes_size() && "Node count mismatch!");
10471   return DAGSize;
10472 }
10473 
10474 /// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the
10475 /// value is produced by SD.
10476 void SelectionDAG::AddDbgValue(SDDbgValue *DB, bool isParameter) {
10477   for (SDNode *SD : DB->getSDNodes()) {
10478     if (!SD)
10479       continue;
10480     assert(DbgInfo->getSDDbgValues(SD).empty() || SD->getHasDebugValue());
10481     SD->setHasDebugValue(true);
10482   }
10483   DbgInfo->add(DB, isParameter);
10484 }
10485 
10486 void SelectionDAG::AddDbgLabel(SDDbgLabel *DB) { DbgInfo->add(DB); }
10487 
10488 SDValue SelectionDAG::makeEquivalentMemoryOrdering(SDValue OldChain,
10489                                                    SDValue NewMemOpChain) {
10490   assert(isa<MemSDNode>(NewMemOpChain) && "Expected a memop node");
10491   assert(NewMemOpChain.getValueType() == MVT::Other && "Expected a token VT");
10492   // The new memory operation must have the same position as the old load in
10493   // terms of memory dependency. Create a TokenFactor for the old load and new
10494   // memory operation and update uses of the old load's output chain to use that
10495   // TokenFactor.
10496   if (OldChain == NewMemOpChain || OldChain.use_empty())
10497     return NewMemOpChain;
10498 
10499   SDValue TokenFactor = getNode(ISD::TokenFactor, SDLoc(OldChain), MVT::Other,
10500                                 OldChain, NewMemOpChain);
10501   ReplaceAllUsesOfValueWith(OldChain, TokenFactor);
10502   UpdateNodeOperands(TokenFactor.getNode(), OldChain, NewMemOpChain);
10503   return TokenFactor;
10504 }
10505 
10506 SDValue SelectionDAG::makeEquivalentMemoryOrdering(LoadSDNode *OldLoad,
10507                                                    SDValue NewMemOp) {
10508   assert(isa<MemSDNode>(NewMemOp.getNode()) && "Expected a memop node");
10509   SDValue OldChain = SDValue(OldLoad, 1);
10510   SDValue NewMemOpChain = NewMemOp.getValue(1);
10511   return makeEquivalentMemoryOrdering(OldChain, NewMemOpChain);
10512 }
10513 
10514 SDValue SelectionDAG::getSymbolFunctionGlobalAddress(SDValue Op,
10515                                                      Function **OutFunction) {
10516   assert(isa<ExternalSymbolSDNode>(Op) && "Node should be an ExternalSymbol");
10517 
10518   auto *Symbol = cast<ExternalSymbolSDNode>(Op)->getSymbol();
10519   auto *Module = MF->getFunction().getParent();
10520   auto *Function = Module->getFunction(Symbol);
10521 
10522   if (OutFunction != nullptr)
10523       *OutFunction = Function;
10524 
10525   if (Function != nullptr) {
10526     auto PtrTy = TLI->getPointerTy(getDataLayout(), Function->getAddressSpace());
10527     return getGlobalAddress(Function, SDLoc(Op), PtrTy);
10528   }
10529 
10530   std::string ErrorStr;
10531   raw_string_ostream ErrorFormatter(ErrorStr);
10532   ErrorFormatter << "Undefined external symbol ";
10533   ErrorFormatter << '"' << Symbol << '"';
10534   report_fatal_error(Twine(ErrorFormatter.str()));
10535 }
10536 
10537 //===----------------------------------------------------------------------===//
10538 //                              SDNode Class
10539 //===----------------------------------------------------------------------===//
10540 
10541 bool llvm::isNullConstant(SDValue V) {
10542   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
10543   return Const != nullptr && Const->isZero();
10544 }
10545 
10546 bool llvm::isNullFPConstant(SDValue V) {
10547   ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V);
10548   return Const != nullptr && Const->isZero() && !Const->isNegative();
10549 }
10550 
10551 bool llvm::isAllOnesConstant(SDValue V) {
10552   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
10553   return Const != nullptr && Const->isAllOnes();
10554 }
10555 
10556 bool llvm::isOneConstant(SDValue V) {
10557   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
10558   return Const != nullptr && Const->isOne();
10559 }
10560 
10561 bool llvm::isMinSignedConstant(SDValue V) {
10562   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
10563   return Const != nullptr && Const->isMinSignedValue();
10564 }
10565 
10566 SDValue llvm::peekThroughBitcasts(SDValue V) {
10567   while (V.getOpcode() == ISD::BITCAST)
10568     V = V.getOperand(0);
10569   return V;
10570 }
10571 
10572 SDValue llvm::peekThroughOneUseBitcasts(SDValue V) {
10573   while (V.getOpcode() == ISD::BITCAST && V.getOperand(0).hasOneUse())
10574     V = V.getOperand(0);
10575   return V;
10576 }
10577 
10578 SDValue llvm::peekThroughExtractSubvectors(SDValue V) {
10579   while (V.getOpcode() == ISD::EXTRACT_SUBVECTOR)
10580     V = V.getOperand(0);
10581   return V;
10582 }
10583 
10584 bool llvm::isBitwiseNot(SDValue V, bool AllowUndefs) {
10585   if (V.getOpcode() != ISD::XOR)
10586     return false;
10587   V = peekThroughBitcasts(V.getOperand(1));
10588   unsigned NumBits = V.getScalarValueSizeInBits();
10589   ConstantSDNode *C =
10590       isConstOrConstSplat(V, AllowUndefs, /*AllowTruncation*/ true);
10591   return C && (C->getAPIntValue().countTrailingOnes() >= NumBits);
10592 }
10593 
10594 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, bool AllowUndefs,
10595                                           bool AllowTruncation) {
10596   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
10597     return CN;
10598 
10599   // SplatVectors can truncate their operands. Ignore that case here unless
10600   // AllowTruncation is set.
10601   if (N->getOpcode() == ISD::SPLAT_VECTOR) {
10602     EVT VecEltVT = N->getValueType(0).getVectorElementType();
10603     if (auto *CN = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
10604       EVT CVT = CN->getValueType(0);
10605       assert(CVT.bitsGE(VecEltVT) && "Illegal splat_vector element extension");
10606       if (AllowTruncation || CVT == VecEltVT)
10607         return CN;
10608     }
10609   }
10610 
10611   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
10612     BitVector UndefElements;
10613     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
10614 
10615     // BuildVectors can truncate their operands. Ignore that case here unless
10616     // AllowTruncation is set.
10617     if (CN && (UndefElements.none() || AllowUndefs)) {
10618       EVT CVT = CN->getValueType(0);
10619       EVT NSVT = N.getValueType().getScalarType();
10620       assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension");
10621       if (AllowTruncation || (CVT == NSVT))
10622         return CN;
10623     }
10624   }
10625 
10626   return nullptr;
10627 }
10628 
10629 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, const APInt &DemandedElts,
10630                                           bool AllowUndefs,
10631                                           bool AllowTruncation) {
10632   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
10633     return CN;
10634 
10635   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
10636     BitVector UndefElements;
10637     ConstantSDNode *CN = BV->getConstantSplatNode(DemandedElts, &UndefElements);
10638 
10639     // BuildVectors can truncate their operands. Ignore that case here unless
10640     // AllowTruncation is set.
10641     if (CN && (UndefElements.none() || AllowUndefs)) {
10642       EVT CVT = CN->getValueType(0);
10643       EVT NSVT = N.getValueType().getScalarType();
10644       assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension");
10645       if (AllowTruncation || (CVT == NSVT))
10646         return CN;
10647     }
10648   }
10649 
10650   return nullptr;
10651 }
10652 
10653 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N, bool AllowUndefs) {
10654   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
10655     return CN;
10656 
10657   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
10658     BitVector UndefElements;
10659     ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
10660     if (CN && (UndefElements.none() || AllowUndefs))
10661       return CN;
10662   }
10663 
10664   if (N.getOpcode() == ISD::SPLAT_VECTOR)
10665     if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N.getOperand(0)))
10666       return CN;
10667 
10668   return nullptr;
10669 }
10670 
10671 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N,
10672                                               const APInt &DemandedElts,
10673                                               bool AllowUndefs) {
10674   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
10675     return CN;
10676 
10677   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
10678     BitVector UndefElements;
10679     ConstantFPSDNode *CN =
10680         BV->getConstantFPSplatNode(DemandedElts, &UndefElements);
10681     if (CN && (UndefElements.none() || AllowUndefs))
10682       return CN;
10683   }
10684 
10685   return nullptr;
10686 }
10687 
10688 bool llvm::isNullOrNullSplat(SDValue N, bool AllowUndefs) {
10689   // TODO: may want to use peekThroughBitcast() here.
10690   ConstantSDNode *C =
10691       isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation=*/true);
10692   return C && C->isZero();
10693 }
10694 
10695 bool llvm::isOneOrOneSplat(SDValue N, bool AllowUndefs) {
10696   ConstantSDNode *C =
10697       isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation*/ true);
10698   return C && C->isOne();
10699 }
10700 
10701 bool llvm::isAllOnesOrAllOnesSplat(SDValue N, bool AllowUndefs) {
10702   N = peekThroughBitcasts(N);
10703   unsigned BitWidth = N.getScalarValueSizeInBits();
10704   ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs);
10705   return C && C->isAllOnes() && C->getValueSizeInBits(0) == BitWidth;
10706 }
10707 
10708 HandleSDNode::~HandleSDNode() {
10709   DropOperands();
10710 }
10711 
10712 GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, unsigned Order,
10713                                          const DebugLoc &DL,
10714                                          const GlobalValue *GA, EVT VT,
10715                                          int64_t o, unsigned TF)
10716     : SDNode(Opc, Order, DL, getSDVTList(VT)), Offset(o), TargetFlags(TF) {
10717   TheGlobal = GA;
10718 }
10719 
10720 AddrSpaceCastSDNode::AddrSpaceCastSDNode(unsigned Order, const DebugLoc &dl,
10721                                          EVT VT, unsigned SrcAS,
10722                                          unsigned DestAS)
10723     : SDNode(ISD::ADDRSPACECAST, Order, dl, getSDVTList(VT)),
10724       SrcAddrSpace(SrcAS), DestAddrSpace(DestAS) {}
10725 
10726 MemSDNode::MemSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl,
10727                      SDVTList VTs, EVT memvt, MachineMemOperand *mmo)
10728     : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MMO(mmo) {
10729   MemSDNodeBits.IsVolatile = MMO->isVolatile();
10730   MemSDNodeBits.IsNonTemporal = MMO->isNonTemporal();
10731   MemSDNodeBits.IsDereferenceable = MMO->isDereferenceable();
10732   MemSDNodeBits.IsInvariant = MMO->isInvariant();
10733 
10734   // We check here that the size of the memory operand fits within the size of
10735   // the MMO. This is because the MMO might indicate only a possible address
10736   // range instead of specifying the affected memory addresses precisely.
10737   // TODO: Make MachineMemOperands aware of scalable vectors.
10738   assert(memvt.getStoreSize().getKnownMinSize() <= MMO->getSize() &&
10739          "Size mismatch!");
10740 }
10741 
10742 /// Profile - Gather unique data for the node.
10743 ///
10744 void SDNode::Profile(FoldingSetNodeID &ID) const {
10745   AddNodeIDNode(ID, this);
10746 }
10747 
10748 namespace {
10749 
10750   struct EVTArray {
10751     std::vector<EVT> VTs;
10752 
10753     EVTArray() {
10754       VTs.reserve(MVT::VALUETYPE_SIZE);
10755       for (unsigned i = 0; i < MVT::VALUETYPE_SIZE; ++i)
10756         VTs.push_back(MVT((MVT::SimpleValueType)i));
10757     }
10758   };
10759 
10760 } // end anonymous namespace
10761 
10762 /// getValueTypeList - Return a pointer to the specified value type.
10763 ///
10764 const EVT *SDNode::getValueTypeList(EVT VT) {
10765   static std::set<EVT, EVT::compareRawBits> EVTs;
10766   static EVTArray SimpleVTArray;
10767   static sys::SmartMutex<true> VTMutex;
10768 
10769   if (VT.isExtended()) {
10770     sys::SmartScopedLock<true> Lock(VTMutex);
10771     return &(*EVTs.insert(VT).first);
10772   }
10773   assert(VT.getSimpleVT() < MVT::VALUETYPE_SIZE && "Value type out of range!");
10774   return &SimpleVTArray.VTs[VT.getSimpleVT().SimpleTy];
10775 }
10776 
10777 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
10778 /// indicated value.  This method ignores uses of other values defined by this
10779 /// operation.
10780 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
10781   assert(Value < getNumValues() && "Bad value!");
10782 
10783   // TODO: Only iterate over uses of a given value of the node
10784   for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
10785     if (UI.getUse().getResNo() == Value) {
10786       if (NUses == 0)
10787         return false;
10788       --NUses;
10789     }
10790   }
10791 
10792   // Found exactly the right number of uses?
10793   return NUses == 0;
10794 }
10795 
10796 /// hasAnyUseOfValue - Return true if there are any use of the indicated
10797 /// value. This method ignores uses of other values defined by this operation.
10798 bool SDNode::hasAnyUseOfValue(unsigned Value) const {
10799   assert(Value < getNumValues() && "Bad value!");
10800 
10801   for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI)
10802     if (UI.getUse().getResNo() == Value)
10803       return true;
10804 
10805   return false;
10806 }
10807 
10808 /// isOnlyUserOf - Return true if this node is the only use of N.
10809 bool SDNode::isOnlyUserOf(const SDNode *N) const {
10810   bool Seen = false;
10811   for (const SDNode *User : N->uses()) {
10812     if (User == this)
10813       Seen = true;
10814     else
10815       return false;
10816   }
10817 
10818   return Seen;
10819 }
10820 
10821 /// Return true if the only users of N are contained in Nodes.
10822 bool SDNode::areOnlyUsersOf(ArrayRef<const SDNode *> Nodes, const SDNode *N) {
10823   bool Seen = false;
10824   for (const SDNode *User : N->uses()) {
10825     if (llvm::is_contained(Nodes, User))
10826       Seen = true;
10827     else
10828       return false;
10829   }
10830 
10831   return Seen;
10832 }
10833 
10834 /// isOperand - Return true if this node is an operand of N.
10835 bool SDValue::isOperandOf(const SDNode *N) const {
10836   return is_contained(N->op_values(), *this);
10837 }
10838 
10839 bool SDNode::isOperandOf(const SDNode *N) const {
10840   return any_of(N->op_values(),
10841                 [this](SDValue Op) { return this == Op.getNode(); });
10842 }
10843 
10844 /// reachesChainWithoutSideEffects - Return true if this operand (which must
10845 /// be a chain) reaches the specified operand without crossing any
10846 /// side-effecting instructions on any chain path.  In practice, this looks
10847 /// through token factors and non-volatile loads.  In order to remain efficient,
10848 /// this only looks a couple of nodes in, it does not do an exhaustive search.
10849 ///
10850 /// Note that we only need to examine chains when we're searching for
10851 /// side-effects; SelectionDAG requires that all side-effects are represented
10852 /// by chains, even if another operand would force a specific ordering. This
10853 /// constraint is necessary to allow transformations like splitting loads.
10854 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest,
10855                                              unsigned Depth) const {
10856   if (*this == Dest) return true;
10857 
10858   // Don't search too deeply, we just want to be able to see through
10859   // TokenFactor's etc.
10860   if (Depth == 0) return false;
10861 
10862   // If this is a token factor, all inputs to the TF happen in parallel.
10863   if (getOpcode() == ISD::TokenFactor) {
10864     // First, try a shallow search.
10865     if (is_contained((*this)->ops(), Dest)) {
10866       // We found the chain we want as an operand of this TokenFactor.
10867       // Essentially, we reach the chain without side-effects if we could
10868       // serialize the TokenFactor into a simple chain of operations with
10869       // Dest as the last operation. This is automatically true if the
10870       // chain has one use: there are no other ordering constraints.
10871       // If the chain has more than one use, we give up: some other
10872       // use of Dest might force a side-effect between Dest and the current
10873       // node.
10874       if (Dest.hasOneUse())
10875         return true;
10876     }
10877     // Next, try a deep search: check whether every operand of the TokenFactor
10878     // reaches Dest.
10879     return llvm::all_of((*this)->ops(), [=](SDValue Op) {
10880       return Op.reachesChainWithoutSideEffects(Dest, Depth - 1);
10881     });
10882   }
10883 
10884   // Loads don't have side effects, look through them.
10885   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
10886     if (Ld->isUnordered())
10887       return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
10888   }
10889   return false;
10890 }
10891 
10892 bool SDNode::hasPredecessor(const SDNode *N) const {
10893   SmallPtrSet<const SDNode *, 32> Visited;
10894   SmallVector<const SDNode *, 16> Worklist;
10895   Worklist.push_back(this);
10896   return hasPredecessorHelper(N, Visited, Worklist);
10897 }
10898 
10899 void SDNode::intersectFlagsWith(const SDNodeFlags Flags) {
10900   this->Flags.intersectWith(Flags);
10901 }
10902 
10903 SDValue
10904 SelectionDAG::matchBinOpReduction(SDNode *Extract, ISD::NodeType &BinOp,
10905                                   ArrayRef<ISD::NodeType> CandidateBinOps,
10906                                   bool AllowPartials) {
10907   // The pattern must end in an extract from index 0.
10908   if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10909       !isNullConstant(Extract->getOperand(1)))
10910     return SDValue();
10911 
10912   // Match against one of the candidate binary ops.
10913   SDValue Op = Extract->getOperand(0);
10914   if (llvm::none_of(CandidateBinOps, [Op](ISD::NodeType BinOp) {
10915         return Op.getOpcode() == unsigned(BinOp);
10916       }))
10917     return SDValue();
10918 
10919   // Floating-point reductions may require relaxed constraints on the final step
10920   // of the reduction because they may reorder intermediate operations.
10921   unsigned CandidateBinOp = Op.getOpcode();
10922   if (Op.getValueType().isFloatingPoint()) {
10923     SDNodeFlags Flags = Op->getFlags();
10924     switch (CandidateBinOp) {
10925     case ISD::FADD:
10926       if (!Flags.hasNoSignedZeros() || !Flags.hasAllowReassociation())
10927         return SDValue();
10928       break;
10929     default:
10930       llvm_unreachable("Unhandled FP opcode for binop reduction");
10931     }
10932   }
10933 
10934   // Matching failed - attempt to see if we did enough stages that a partial
10935   // reduction from a subvector is possible.
10936   auto PartialReduction = [&](SDValue Op, unsigned NumSubElts) {
10937     if (!AllowPartials || !Op)
10938       return SDValue();
10939     EVT OpVT = Op.getValueType();
10940     EVT OpSVT = OpVT.getScalarType();
10941     EVT SubVT = EVT::getVectorVT(*getContext(), OpSVT, NumSubElts);
10942     if (!TLI->isExtractSubvectorCheap(SubVT, OpVT, 0))
10943       return SDValue();
10944     BinOp = (ISD::NodeType)CandidateBinOp;
10945     return getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(Op), SubVT, Op,
10946                    getVectorIdxConstant(0, SDLoc(Op)));
10947   };
10948 
10949   // At each stage, we're looking for something that looks like:
10950   // %s = shufflevector <8 x i32> %op, <8 x i32> undef,
10951   //                    <8 x i32> <i32 2, i32 3, i32 undef, i32 undef,
10952   //                               i32 undef, i32 undef, i32 undef, i32 undef>
10953   // %a = binop <8 x i32> %op, %s
10954   // Where the mask changes according to the stage. E.g. for a 3-stage pyramid,
10955   // we expect something like:
10956   // <4,5,6,7,u,u,u,u>
10957   // <2,3,u,u,u,u,u,u>
10958   // <1,u,u,u,u,u,u,u>
10959   // While a partial reduction match would be:
10960   // <2,3,u,u,u,u,u,u>
10961   // <1,u,u,u,u,u,u,u>
10962   unsigned Stages = Log2_32(Op.getValueType().getVectorNumElements());
10963   SDValue PrevOp;
10964   for (unsigned i = 0; i < Stages; ++i) {
10965     unsigned MaskEnd = (1 << i);
10966 
10967     if (Op.getOpcode() != CandidateBinOp)
10968       return PartialReduction(PrevOp, MaskEnd);
10969 
10970     SDValue Op0 = Op.getOperand(0);
10971     SDValue Op1 = Op.getOperand(1);
10972 
10973     ShuffleVectorSDNode *Shuffle = dyn_cast<ShuffleVectorSDNode>(Op0);
10974     if (Shuffle) {
10975       Op = Op1;
10976     } else {
10977       Shuffle = dyn_cast<ShuffleVectorSDNode>(Op1);
10978       Op = Op0;
10979     }
10980 
10981     // The first operand of the shuffle should be the same as the other operand
10982     // of the binop.
10983     if (!Shuffle || Shuffle->getOperand(0) != Op)
10984       return PartialReduction(PrevOp, MaskEnd);
10985 
10986     // Verify the shuffle has the expected (at this stage of the pyramid) mask.
10987     for (int Index = 0; Index < (int)MaskEnd; ++Index)
10988       if (Shuffle->getMaskElt(Index) != (int)(MaskEnd + Index))
10989         return PartialReduction(PrevOp, MaskEnd);
10990 
10991     PrevOp = Op;
10992   }
10993 
10994   // Handle subvector reductions, which tend to appear after the shuffle
10995   // reduction stages.
10996   while (Op.getOpcode() == CandidateBinOp) {
10997     unsigned NumElts = Op.getValueType().getVectorNumElements();
10998     SDValue Op0 = Op.getOperand(0);
10999     SDValue Op1 = Op.getOperand(1);
11000     if (Op0.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
11001         Op1.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
11002         Op0.getOperand(0) != Op1.getOperand(0))
11003       break;
11004     SDValue Src = Op0.getOperand(0);
11005     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
11006     if (NumSrcElts != (2 * NumElts))
11007       break;
11008     if (!(Op0.getConstantOperandAPInt(1) == 0 &&
11009           Op1.getConstantOperandAPInt(1) == NumElts) &&
11010         !(Op1.getConstantOperandAPInt(1) == 0 &&
11011           Op0.getConstantOperandAPInt(1) == NumElts))
11012       break;
11013     Op = Src;
11014   }
11015 
11016   BinOp = (ISD::NodeType)CandidateBinOp;
11017   return Op;
11018 }
11019 
11020 SDValue SelectionDAG::UnrollVectorOp(SDNode *N, unsigned ResNE) {
11021   assert(N->getNumValues() == 1 &&
11022          "Can't unroll a vector with multiple results!");
11023 
11024   EVT VT = N->getValueType(0);
11025   unsigned NE = VT.getVectorNumElements();
11026   EVT EltVT = VT.getVectorElementType();
11027   SDLoc dl(N);
11028 
11029   SmallVector<SDValue, 8> Scalars;
11030   SmallVector<SDValue, 4> Operands(N->getNumOperands());
11031 
11032   // If ResNE is 0, fully unroll the vector op.
11033   if (ResNE == 0)
11034     ResNE = NE;
11035   else if (NE > ResNE)
11036     NE = ResNE;
11037 
11038   unsigned i;
11039   for (i= 0; i != NE; ++i) {
11040     for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) {
11041       SDValue Operand = N->getOperand(j);
11042       EVT OperandVT = Operand.getValueType();
11043       if (OperandVT.isVector()) {
11044         // A vector operand; extract a single element.
11045         EVT OperandEltVT = OperandVT.getVectorElementType();
11046         Operands[j] = getNode(ISD::EXTRACT_VECTOR_ELT, dl, OperandEltVT,
11047                               Operand, getVectorIdxConstant(i, dl));
11048       } else {
11049         // A scalar operand; just use it as is.
11050         Operands[j] = Operand;
11051       }
11052     }
11053 
11054     switch (N->getOpcode()) {
11055     default: {
11056       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands,
11057                                 N->getFlags()));
11058       break;
11059     }
11060     case ISD::VSELECT:
11061       Scalars.push_back(getNode(ISD::SELECT, dl, EltVT, Operands));
11062       break;
11063     case ISD::SHL:
11064     case ISD::SRA:
11065     case ISD::SRL:
11066     case ISD::ROTL:
11067     case ISD::ROTR:
11068       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0],
11069                                getShiftAmountOperand(Operands[0].getValueType(),
11070                                                      Operands[1])));
11071       break;
11072     case ISD::SIGN_EXTEND_INREG: {
11073       EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType();
11074       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT,
11075                                 Operands[0],
11076                                 getValueType(ExtVT)));
11077     }
11078     }
11079   }
11080 
11081   for (; i < ResNE; ++i)
11082     Scalars.push_back(getUNDEF(EltVT));
11083 
11084   EVT VecVT = EVT::getVectorVT(*getContext(), EltVT, ResNE);
11085   return getBuildVector(VecVT, dl, Scalars);
11086 }
11087 
11088 std::pair<SDValue, SDValue> SelectionDAG::UnrollVectorOverflowOp(
11089     SDNode *N, unsigned ResNE) {
11090   unsigned Opcode = N->getOpcode();
11091   assert((Opcode == ISD::UADDO || Opcode == ISD::SADDO ||
11092           Opcode == ISD::USUBO || Opcode == ISD::SSUBO ||
11093           Opcode == ISD::UMULO || Opcode == ISD::SMULO) &&
11094          "Expected an overflow opcode");
11095 
11096   EVT ResVT = N->getValueType(0);
11097   EVT OvVT = N->getValueType(1);
11098   EVT ResEltVT = ResVT.getVectorElementType();
11099   EVT OvEltVT = OvVT.getVectorElementType();
11100   SDLoc dl(N);
11101 
11102   // If ResNE is 0, fully unroll the vector op.
11103   unsigned NE = ResVT.getVectorNumElements();
11104   if (ResNE == 0)
11105     ResNE = NE;
11106   else if (NE > ResNE)
11107     NE = ResNE;
11108 
11109   SmallVector<SDValue, 8> LHSScalars;
11110   SmallVector<SDValue, 8> RHSScalars;
11111   ExtractVectorElements(N->getOperand(0), LHSScalars, 0, NE);
11112   ExtractVectorElements(N->getOperand(1), RHSScalars, 0, NE);
11113 
11114   EVT SVT = TLI->getSetCCResultType(getDataLayout(), *getContext(), ResEltVT);
11115   SDVTList VTs = getVTList(ResEltVT, SVT);
11116   SmallVector<SDValue, 8> ResScalars;
11117   SmallVector<SDValue, 8> OvScalars;
11118   for (unsigned i = 0; i < NE; ++i) {
11119     SDValue Res = getNode(Opcode, dl, VTs, LHSScalars[i], RHSScalars[i]);
11120     SDValue Ov =
11121         getSelect(dl, OvEltVT, Res.getValue(1),
11122                   getBoolConstant(true, dl, OvEltVT, ResVT),
11123                   getConstant(0, dl, OvEltVT));
11124 
11125     ResScalars.push_back(Res);
11126     OvScalars.push_back(Ov);
11127   }
11128 
11129   ResScalars.append(ResNE - NE, getUNDEF(ResEltVT));
11130   OvScalars.append(ResNE - NE, getUNDEF(OvEltVT));
11131 
11132   EVT NewResVT = EVT::getVectorVT(*getContext(), ResEltVT, ResNE);
11133   EVT NewOvVT = EVT::getVectorVT(*getContext(), OvEltVT, ResNE);
11134   return std::make_pair(getBuildVector(NewResVT, dl, ResScalars),
11135                         getBuildVector(NewOvVT, dl, OvScalars));
11136 }
11137 
11138 bool SelectionDAG::areNonVolatileConsecutiveLoads(LoadSDNode *LD,
11139                                                   LoadSDNode *Base,
11140                                                   unsigned Bytes,
11141                                                   int Dist) const {
11142   if (LD->isVolatile() || Base->isVolatile())
11143     return false;
11144   // TODO: probably too restrictive for atomics, revisit
11145   if (!LD->isSimple())
11146     return false;
11147   if (LD->isIndexed() || Base->isIndexed())
11148     return false;
11149   if (LD->getChain() != Base->getChain())
11150     return false;
11151   EVT VT = LD->getValueType(0);
11152   if (VT.getSizeInBits() / 8 != Bytes)
11153     return false;
11154 
11155   auto BaseLocDecomp = BaseIndexOffset::match(Base, *this);
11156   auto LocDecomp = BaseIndexOffset::match(LD, *this);
11157 
11158   int64_t Offset = 0;
11159   if (BaseLocDecomp.equalBaseIndex(LocDecomp, *this, Offset))
11160     return (Dist * Bytes == Offset);
11161   return false;
11162 }
11163 
11164 /// InferPtrAlignment - Infer alignment of a load / store address. Return None
11165 /// if it cannot be inferred.
11166 MaybeAlign SelectionDAG::InferPtrAlign(SDValue Ptr) const {
11167   // If this is a GlobalAddress + cst, return the alignment.
11168   const GlobalValue *GV = nullptr;
11169   int64_t GVOffset = 0;
11170   if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) {
11171     unsigned PtrWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
11172     KnownBits Known(PtrWidth);
11173     llvm::computeKnownBits(GV, Known, getDataLayout());
11174     unsigned AlignBits = Known.countMinTrailingZeros();
11175     if (AlignBits)
11176       return commonAlignment(Align(1ull << std::min(31U, AlignBits)), GVOffset);
11177   }
11178 
11179   // If this is a direct reference to a stack slot, use information about the
11180   // stack slot's alignment.
11181   int FrameIdx = INT_MIN;
11182   int64_t FrameOffset = 0;
11183   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) {
11184     FrameIdx = FI->getIndex();
11185   } else if (isBaseWithConstantOffset(Ptr) &&
11186              isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
11187     // Handle FI+Cst
11188     FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
11189     FrameOffset = Ptr.getConstantOperandVal(1);
11190   }
11191 
11192   if (FrameIdx != INT_MIN) {
11193     const MachineFrameInfo &MFI = getMachineFunction().getFrameInfo();
11194     return commonAlignment(MFI.getObjectAlign(FrameIdx), FrameOffset);
11195   }
11196 
11197   return None;
11198 }
11199 
11200 /// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type
11201 /// which is split (or expanded) into two not necessarily identical pieces.
11202 std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const {
11203   // Currently all types are split in half.
11204   EVT LoVT, HiVT;
11205   if (!VT.isVector())
11206     LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT);
11207   else
11208     LoVT = HiVT = VT.getHalfNumVectorElementsVT(*getContext());
11209 
11210   return std::make_pair(LoVT, HiVT);
11211 }
11212 
11213 /// GetDependentSplitDestVTs - Compute the VTs needed for the low/hi parts of a
11214 /// type, dependent on an enveloping VT that has been split into two identical
11215 /// pieces. Sets the HiIsEmpty flag when hi type has zero storage size.
11216 std::pair<EVT, EVT>
11217 SelectionDAG::GetDependentSplitDestVTs(const EVT &VT, const EVT &EnvVT,
11218                                        bool *HiIsEmpty) const {
11219   EVT EltTp = VT.getVectorElementType();
11220   // Examples:
11221   //   custom VL=8  with enveloping VL=8/8 yields 8/0 (hi empty)
11222   //   custom VL=9  with enveloping VL=8/8 yields 8/1
11223   //   custom VL=10 with enveloping VL=8/8 yields 8/2
11224   //   etc.
11225   ElementCount VTNumElts = VT.getVectorElementCount();
11226   ElementCount EnvNumElts = EnvVT.getVectorElementCount();
11227   assert(VTNumElts.isScalable() == EnvNumElts.isScalable() &&
11228          "Mixing fixed width and scalable vectors when enveloping a type");
11229   EVT LoVT, HiVT;
11230   if (VTNumElts.getKnownMinValue() > EnvNumElts.getKnownMinValue()) {
11231     LoVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts);
11232     HiVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts - EnvNumElts);
11233     *HiIsEmpty = false;
11234   } else {
11235     // Flag that hi type has zero storage size, but return split envelop type
11236     // (this would be easier if vector types with zero elements were allowed).
11237     LoVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts);
11238     HiVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts);
11239     *HiIsEmpty = true;
11240   }
11241   return std::make_pair(LoVT, HiVT);
11242 }
11243 
11244 /// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the
11245 /// low/high part.
11246 std::pair<SDValue, SDValue>
11247 SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT,
11248                           const EVT &HiVT) {
11249   assert(LoVT.isScalableVector() == HiVT.isScalableVector() &&
11250          LoVT.isScalableVector() == N.getValueType().isScalableVector() &&
11251          "Splitting vector with an invalid mixture of fixed and scalable "
11252          "vector types");
11253   assert(LoVT.getVectorMinNumElements() + HiVT.getVectorMinNumElements() <=
11254              N.getValueType().getVectorMinNumElements() &&
11255          "More vector elements requested than available!");
11256   SDValue Lo, Hi;
11257   Lo =
11258       getNode(ISD::EXTRACT_SUBVECTOR, DL, LoVT, N, getVectorIdxConstant(0, DL));
11259   // For scalable vectors it is safe to use LoVT.getVectorMinNumElements()
11260   // (rather than having to use ElementCount), because EXTRACT_SUBVECTOR scales
11261   // IDX with the runtime scaling factor of the result vector type. For
11262   // fixed-width result vectors, that runtime scaling factor is 1.
11263   Hi = getNode(ISD::EXTRACT_SUBVECTOR, DL, HiVT, N,
11264                getVectorIdxConstant(LoVT.getVectorMinNumElements(), DL));
11265   return std::make_pair(Lo, Hi);
11266 }
11267 
11268 std::pair<SDValue, SDValue> SelectionDAG::SplitEVL(SDValue N, EVT VecVT,
11269                                                    const SDLoc &DL) {
11270   // Split the vector length parameter.
11271   // %evl -> umin(%evl, %halfnumelts) and usubsat(%evl - %halfnumelts).
11272   EVT VT = N.getValueType();
11273   assert(VecVT.getVectorElementCount().isKnownEven() &&
11274          "Expecting the mask to be an evenly-sized vector");
11275   unsigned HalfMinNumElts = VecVT.getVectorMinNumElements() / 2;
11276   SDValue HalfNumElts =
11277       VecVT.isFixedLengthVector()
11278           ? getConstant(HalfMinNumElts, DL, VT)
11279           : getVScale(DL, VT, APInt(VT.getScalarSizeInBits(), HalfMinNumElts));
11280   SDValue Lo = getNode(ISD::UMIN, DL, VT, N, HalfNumElts);
11281   SDValue Hi = getNode(ISD::USUBSAT, DL, VT, N, HalfNumElts);
11282   return std::make_pair(Lo, Hi);
11283 }
11284 
11285 /// Widen the vector up to the next power of two using INSERT_SUBVECTOR.
11286 SDValue SelectionDAG::WidenVector(const SDValue &N, const SDLoc &DL) {
11287   EVT VT = N.getValueType();
11288   EVT WideVT = EVT::getVectorVT(*getContext(), VT.getVectorElementType(),
11289                                 NextPowerOf2(VT.getVectorNumElements()));
11290   return getNode(ISD::INSERT_SUBVECTOR, DL, WideVT, getUNDEF(WideVT), N,
11291                  getVectorIdxConstant(0, DL));
11292 }
11293 
11294 void SelectionDAG::ExtractVectorElements(SDValue Op,
11295                                          SmallVectorImpl<SDValue> &Args,
11296                                          unsigned Start, unsigned Count,
11297                                          EVT EltVT) {
11298   EVT VT = Op.getValueType();
11299   if (Count == 0)
11300     Count = VT.getVectorNumElements();
11301   if (EltVT == EVT())
11302     EltVT = VT.getVectorElementType();
11303   SDLoc SL(Op);
11304   for (unsigned i = Start, e = Start + Count; i != e; ++i) {
11305     Args.push_back(getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Op,
11306                            getVectorIdxConstant(i, SL)));
11307   }
11308 }
11309 
11310 // getAddressSpace - Return the address space this GlobalAddress belongs to.
11311 unsigned GlobalAddressSDNode::getAddressSpace() const {
11312   return getGlobal()->getType()->getAddressSpace();
11313 }
11314 
11315 Type *ConstantPoolSDNode::getType() const {
11316   if (isMachineConstantPoolEntry())
11317     return Val.MachineCPVal->getType();
11318   return Val.ConstVal->getType();
11319 }
11320 
11321 bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue, APInt &SplatUndef,
11322                                         unsigned &SplatBitSize,
11323                                         bool &HasAnyUndefs,
11324                                         unsigned MinSplatBits,
11325                                         bool IsBigEndian) const {
11326   EVT VT = getValueType(0);
11327   assert(VT.isVector() && "Expected a vector type");
11328   unsigned VecWidth = VT.getSizeInBits();
11329   if (MinSplatBits > VecWidth)
11330     return false;
11331 
11332   // FIXME: The widths are based on this node's type, but build vectors can
11333   // truncate their operands.
11334   SplatValue = APInt(VecWidth, 0);
11335   SplatUndef = APInt(VecWidth, 0);
11336 
11337   // Get the bits. Bits with undefined values (when the corresponding element
11338   // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared
11339   // in SplatValue. If any of the values are not constant, give up and return
11340   // false.
11341   unsigned int NumOps = getNumOperands();
11342   assert(NumOps > 0 && "isConstantSplat has 0-size build vector");
11343   unsigned EltWidth = VT.getScalarSizeInBits();
11344 
11345   for (unsigned j = 0; j < NumOps; ++j) {
11346     unsigned i = IsBigEndian ? NumOps - 1 - j : j;
11347     SDValue OpVal = getOperand(i);
11348     unsigned BitPos = j * EltWidth;
11349 
11350     if (OpVal.isUndef())
11351       SplatUndef.setBits(BitPos, BitPos + EltWidth);
11352     else if (auto *CN = dyn_cast<ConstantSDNode>(OpVal))
11353       SplatValue.insertBits(CN->getAPIntValue().zextOrTrunc(EltWidth), BitPos);
11354     else if (auto *CN = dyn_cast<ConstantFPSDNode>(OpVal))
11355       SplatValue.insertBits(CN->getValueAPF().bitcastToAPInt(), BitPos);
11356     else
11357       return false;
11358   }
11359 
11360   // The build_vector is all constants or undefs. Find the smallest element
11361   // size that splats the vector.
11362   HasAnyUndefs = (SplatUndef != 0);
11363 
11364   // FIXME: This does not work for vectors with elements less than 8 bits.
11365   while (VecWidth > 8) {
11366     unsigned HalfSize = VecWidth / 2;
11367     APInt HighValue = SplatValue.extractBits(HalfSize, HalfSize);
11368     APInt LowValue = SplatValue.extractBits(HalfSize, 0);
11369     APInt HighUndef = SplatUndef.extractBits(HalfSize, HalfSize);
11370     APInt LowUndef = SplatUndef.extractBits(HalfSize, 0);
11371 
11372     // If the two halves do not match (ignoring undef bits), stop here.
11373     if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) ||
11374         MinSplatBits > HalfSize)
11375       break;
11376 
11377     SplatValue = HighValue | LowValue;
11378     SplatUndef = HighUndef & LowUndef;
11379 
11380     VecWidth = HalfSize;
11381   }
11382 
11383   SplatBitSize = VecWidth;
11384   return true;
11385 }
11386 
11387 SDValue BuildVectorSDNode::getSplatValue(const APInt &DemandedElts,
11388                                          BitVector *UndefElements) const {
11389   unsigned NumOps = getNumOperands();
11390   if (UndefElements) {
11391     UndefElements->clear();
11392     UndefElements->resize(NumOps);
11393   }
11394   assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size");
11395   if (!DemandedElts)
11396     return SDValue();
11397   SDValue Splatted;
11398   for (unsigned i = 0; i != NumOps; ++i) {
11399     if (!DemandedElts[i])
11400       continue;
11401     SDValue Op = getOperand(i);
11402     if (Op.isUndef()) {
11403       if (UndefElements)
11404         (*UndefElements)[i] = true;
11405     } else if (!Splatted) {
11406       Splatted = Op;
11407     } else if (Splatted != Op) {
11408       return SDValue();
11409     }
11410   }
11411 
11412   if (!Splatted) {
11413     unsigned FirstDemandedIdx = DemandedElts.countTrailingZeros();
11414     assert(getOperand(FirstDemandedIdx).isUndef() &&
11415            "Can only have a splat without a constant for all undefs.");
11416     return getOperand(FirstDemandedIdx);
11417   }
11418 
11419   return Splatted;
11420 }
11421 
11422 SDValue BuildVectorSDNode::getSplatValue(BitVector *UndefElements) const {
11423   APInt DemandedElts = APInt::getAllOnes(getNumOperands());
11424   return getSplatValue(DemandedElts, UndefElements);
11425 }
11426 
11427 bool BuildVectorSDNode::getRepeatedSequence(const APInt &DemandedElts,
11428                                             SmallVectorImpl<SDValue> &Sequence,
11429                                             BitVector *UndefElements) const {
11430   unsigned NumOps = getNumOperands();
11431   Sequence.clear();
11432   if (UndefElements) {
11433     UndefElements->clear();
11434     UndefElements->resize(NumOps);
11435   }
11436   assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size");
11437   if (!DemandedElts || NumOps < 2 || !isPowerOf2_32(NumOps))
11438     return false;
11439 
11440   // Set the undefs even if we don't find a sequence (like getSplatValue).
11441   if (UndefElements)
11442     for (unsigned I = 0; I != NumOps; ++I)
11443       if (DemandedElts[I] && getOperand(I).isUndef())
11444         (*UndefElements)[I] = true;
11445 
11446   // Iteratively widen the sequence length looking for repetitions.
11447   for (unsigned SeqLen = 1; SeqLen < NumOps; SeqLen *= 2) {
11448     Sequence.append(SeqLen, SDValue());
11449     for (unsigned I = 0; I != NumOps; ++I) {
11450       if (!DemandedElts[I])
11451         continue;
11452       SDValue &SeqOp = Sequence[I % SeqLen];
11453       SDValue Op = getOperand(I);
11454       if (Op.isUndef()) {
11455         if (!SeqOp)
11456           SeqOp = Op;
11457         continue;
11458       }
11459       if (SeqOp && !SeqOp.isUndef() && SeqOp != Op) {
11460         Sequence.clear();
11461         break;
11462       }
11463       SeqOp = Op;
11464     }
11465     if (!Sequence.empty())
11466       return true;
11467   }
11468 
11469   assert(Sequence.empty() && "Failed to empty non-repeating sequence pattern");
11470   return false;
11471 }
11472 
11473 bool BuildVectorSDNode::getRepeatedSequence(SmallVectorImpl<SDValue> &Sequence,
11474                                             BitVector *UndefElements) const {
11475   APInt DemandedElts = APInt::getAllOnes(getNumOperands());
11476   return getRepeatedSequence(DemandedElts, Sequence, UndefElements);
11477 }
11478 
11479 ConstantSDNode *
11480 BuildVectorSDNode::getConstantSplatNode(const APInt &DemandedElts,
11481                                         BitVector *UndefElements) const {
11482   return dyn_cast_or_null<ConstantSDNode>(
11483       getSplatValue(DemandedElts, UndefElements));
11484 }
11485 
11486 ConstantSDNode *
11487 BuildVectorSDNode::getConstantSplatNode(BitVector *UndefElements) const {
11488   return dyn_cast_or_null<ConstantSDNode>(getSplatValue(UndefElements));
11489 }
11490 
11491 ConstantFPSDNode *
11492 BuildVectorSDNode::getConstantFPSplatNode(const APInt &DemandedElts,
11493                                           BitVector *UndefElements) const {
11494   return dyn_cast_or_null<ConstantFPSDNode>(
11495       getSplatValue(DemandedElts, UndefElements));
11496 }
11497 
11498 ConstantFPSDNode *
11499 BuildVectorSDNode::getConstantFPSplatNode(BitVector *UndefElements) const {
11500   return dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements));
11501 }
11502 
11503 int32_t
11504 BuildVectorSDNode::getConstantFPSplatPow2ToLog2Int(BitVector *UndefElements,
11505                                                    uint32_t BitWidth) const {
11506   if (ConstantFPSDNode *CN =
11507           dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements))) {
11508     bool IsExact;
11509     APSInt IntVal(BitWidth);
11510     const APFloat &APF = CN->getValueAPF();
11511     if (APF.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) !=
11512             APFloat::opOK ||
11513         !IsExact)
11514       return -1;
11515 
11516     return IntVal.exactLogBase2();
11517   }
11518   return -1;
11519 }
11520 
11521 bool BuildVectorSDNode::getConstantRawBits(
11522     bool IsLittleEndian, unsigned DstEltSizeInBits,
11523     SmallVectorImpl<APInt> &RawBitElements, BitVector &UndefElements) const {
11524   // Early-out if this contains anything but Undef/Constant/ConstantFP.
11525   if (!isConstant())
11526     return false;
11527 
11528   unsigned NumSrcOps = getNumOperands();
11529   unsigned SrcEltSizeInBits = getValueType(0).getScalarSizeInBits();
11530   assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 &&
11531          "Invalid bitcast scale");
11532 
11533   // Extract raw src bits.
11534   SmallVector<APInt> SrcBitElements(NumSrcOps,
11535                                     APInt::getNullValue(SrcEltSizeInBits));
11536   BitVector SrcUndeElements(NumSrcOps, false);
11537 
11538   for (unsigned I = 0; I != NumSrcOps; ++I) {
11539     SDValue Op = getOperand(I);
11540     if (Op.isUndef()) {
11541       SrcUndeElements.set(I);
11542       continue;
11543     }
11544     auto *CInt = dyn_cast<ConstantSDNode>(Op);
11545     auto *CFP = dyn_cast<ConstantFPSDNode>(Op);
11546     assert((CInt || CFP) && "Unknown constant");
11547     SrcBitElements[I] = CInt ? CInt->getAPIntValue().trunc(SrcEltSizeInBits)
11548                              : CFP->getValueAPF().bitcastToAPInt();
11549   }
11550 
11551   // Recast to dst width.
11552   recastRawBits(IsLittleEndian, DstEltSizeInBits, RawBitElements,
11553                 SrcBitElements, UndefElements, SrcUndeElements);
11554   return true;
11555 }
11556 
11557 void BuildVectorSDNode::recastRawBits(bool IsLittleEndian,
11558                                       unsigned DstEltSizeInBits,
11559                                       SmallVectorImpl<APInt> &DstBitElements,
11560                                       ArrayRef<APInt> SrcBitElements,
11561                                       BitVector &DstUndefElements,
11562                                       const BitVector &SrcUndefElements) {
11563   unsigned NumSrcOps = SrcBitElements.size();
11564   unsigned SrcEltSizeInBits = SrcBitElements[0].getBitWidth();
11565   assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 &&
11566          "Invalid bitcast scale");
11567   assert(NumSrcOps == SrcUndefElements.size() &&
11568          "Vector size mismatch");
11569 
11570   unsigned NumDstOps = (NumSrcOps * SrcEltSizeInBits) / DstEltSizeInBits;
11571   DstUndefElements.clear();
11572   DstUndefElements.resize(NumDstOps, false);
11573   DstBitElements.assign(NumDstOps, APInt::getNullValue(DstEltSizeInBits));
11574 
11575   // Concatenate src elements constant bits together into dst element.
11576   if (SrcEltSizeInBits <= DstEltSizeInBits) {
11577     unsigned Scale = DstEltSizeInBits / SrcEltSizeInBits;
11578     for (unsigned I = 0; I != NumDstOps; ++I) {
11579       DstUndefElements.set(I);
11580       APInt &DstBits = DstBitElements[I];
11581       for (unsigned J = 0; J != Scale; ++J) {
11582         unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1));
11583         if (SrcUndefElements[Idx])
11584           continue;
11585         DstUndefElements.reset(I);
11586         const APInt &SrcBits = SrcBitElements[Idx];
11587         assert(SrcBits.getBitWidth() == SrcEltSizeInBits &&
11588                "Illegal constant bitwidths");
11589         DstBits.insertBits(SrcBits, J * SrcEltSizeInBits);
11590       }
11591     }
11592     return;
11593   }
11594 
11595   // Split src element constant bits into dst elements.
11596   unsigned Scale = SrcEltSizeInBits / DstEltSizeInBits;
11597   for (unsigned I = 0; I != NumSrcOps; ++I) {
11598     if (SrcUndefElements[I]) {
11599       DstUndefElements.set(I * Scale, (I + 1) * Scale);
11600       continue;
11601     }
11602     const APInt &SrcBits = SrcBitElements[I];
11603     for (unsigned J = 0; J != Scale; ++J) {
11604       unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1));
11605       APInt &DstBits = DstBitElements[Idx];
11606       DstBits = SrcBits.extractBits(DstEltSizeInBits, J * DstEltSizeInBits);
11607     }
11608   }
11609 }
11610 
11611 bool BuildVectorSDNode::isConstant() const {
11612   for (const SDValue &Op : op_values()) {
11613     unsigned Opc = Op.getOpcode();
11614     if (Opc != ISD::UNDEF && Opc != ISD::Constant && Opc != ISD::ConstantFP)
11615       return false;
11616   }
11617   return true;
11618 }
11619 
11620 bool ShuffleVectorSDNode::isSplatMask(const int *Mask, EVT VT) {
11621   // Find the first non-undef value in the shuffle mask.
11622   unsigned i, e;
11623   for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i)
11624     /* search */;
11625 
11626   // If all elements are undefined, this shuffle can be considered a splat
11627   // (although it should eventually get simplified away completely).
11628   if (i == e)
11629     return true;
11630 
11631   // Make sure all remaining elements are either undef or the same as the first
11632   // non-undef value.
11633   for (int Idx = Mask[i]; i != e; ++i)
11634     if (Mask[i] >= 0 && Mask[i] != Idx)
11635       return false;
11636   return true;
11637 }
11638 
11639 // Returns the SDNode if it is a constant integer BuildVector
11640 // or constant integer.
11641 SDNode *SelectionDAG::isConstantIntBuildVectorOrConstantInt(SDValue N) const {
11642   if (isa<ConstantSDNode>(N))
11643     return N.getNode();
11644   if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
11645     return N.getNode();
11646   // Treat a GlobalAddress supporting constant offset folding as a
11647   // constant integer.
11648   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N))
11649     if (GA->getOpcode() == ISD::GlobalAddress &&
11650         TLI->isOffsetFoldingLegal(GA))
11651       return GA;
11652   if ((N.getOpcode() == ISD::SPLAT_VECTOR) &&
11653       isa<ConstantSDNode>(N.getOperand(0)))
11654     return N.getNode();
11655   return nullptr;
11656 }
11657 
11658 // Returns the SDNode if it is a constant float BuildVector
11659 // or constant float.
11660 SDNode *SelectionDAG::isConstantFPBuildVectorOrConstantFP(SDValue N) const {
11661   if (isa<ConstantFPSDNode>(N))
11662     return N.getNode();
11663 
11664   if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
11665     return N.getNode();
11666 
11667   if ((N.getOpcode() == ISD::SPLAT_VECTOR) &&
11668       isa<ConstantFPSDNode>(N.getOperand(0)))
11669     return N.getNode();
11670 
11671   return nullptr;
11672 }
11673 
11674 void SelectionDAG::createOperands(SDNode *Node, ArrayRef<SDValue> Vals) {
11675   assert(!Node->OperandList && "Node already has operands");
11676   assert(SDNode::getMaxNumOperands() >= Vals.size() &&
11677          "too many operands to fit into SDNode");
11678   SDUse *Ops = OperandRecycler.allocate(
11679       ArrayRecycler<SDUse>::Capacity::get(Vals.size()), OperandAllocator);
11680 
11681   bool IsDivergent = false;
11682   for (unsigned I = 0; I != Vals.size(); ++I) {
11683     Ops[I].setUser(Node);
11684     Ops[I].setInitial(Vals[I]);
11685     if (Ops[I].Val.getValueType() != MVT::Other) // Skip Chain. It does not carry divergence.
11686       IsDivergent |= Ops[I].getNode()->isDivergent();
11687   }
11688   Node->NumOperands = Vals.size();
11689   Node->OperandList = Ops;
11690   if (!TLI->isSDNodeAlwaysUniform(Node)) {
11691     IsDivergent |= TLI->isSDNodeSourceOfDivergence(Node, FLI, DA);
11692     Node->SDNodeBits.IsDivergent = IsDivergent;
11693   }
11694   checkForCycles(Node);
11695 }
11696 
11697 SDValue SelectionDAG::getTokenFactor(const SDLoc &DL,
11698                                      SmallVectorImpl<SDValue> &Vals) {
11699   size_t Limit = SDNode::getMaxNumOperands();
11700   while (Vals.size() > Limit) {
11701     unsigned SliceIdx = Vals.size() - Limit;
11702     auto ExtractedTFs = ArrayRef<SDValue>(Vals).slice(SliceIdx, Limit);
11703     SDValue NewTF = getNode(ISD::TokenFactor, DL, MVT::Other, ExtractedTFs);
11704     Vals.erase(Vals.begin() + SliceIdx, Vals.end());
11705     Vals.emplace_back(NewTF);
11706   }
11707   return getNode(ISD::TokenFactor, DL, MVT::Other, Vals);
11708 }
11709 
11710 SDValue SelectionDAG::getNeutralElement(unsigned Opcode, const SDLoc &DL,
11711                                         EVT VT, SDNodeFlags Flags) {
11712   switch (Opcode) {
11713   default:
11714     return SDValue();
11715   case ISD::ADD:
11716   case ISD::OR:
11717   case ISD::XOR:
11718   case ISD::UMAX:
11719     return getConstant(0, DL, VT);
11720   case ISD::MUL:
11721     return getConstant(1, DL, VT);
11722   case ISD::AND:
11723   case ISD::UMIN:
11724     return getAllOnesConstant(DL, VT);
11725   case ISD::SMAX:
11726     return getConstant(APInt::getSignedMinValue(VT.getSizeInBits()), DL, VT);
11727   case ISD::SMIN:
11728     return getConstant(APInt::getSignedMaxValue(VT.getSizeInBits()), DL, VT);
11729   case ISD::FADD:
11730     return getConstantFP(-0.0, DL, VT);
11731   case ISD::FMUL:
11732     return getConstantFP(1.0, DL, VT);
11733   case ISD::FMINNUM:
11734   case ISD::FMAXNUM: {
11735     // Neutral element for fminnum is NaN, Inf or FLT_MAX, depending on FMF.
11736     const fltSemantics &Semantics = EVTToAPFloatSemantics(VT);
11737     APFloat NeutralAF = !Flags.hasNoNaNs() ? APFloat::getQNaN(Semantics) :
11738                         !Flags.hasNoInfs() ? APFloat::getInf(Semantics) :
11739                         APFloat::getLargest(Semantics);
11740     if (Opcode == ISD::FMAXNUM)
11741       NeutralAF.changeSign();
11742 
11743     return getConstantFP(NeutralAF, DL, VT);
11744   }
11745   }
11746 }
11747 
11748 #ifndef NDEBUG
11749 static void checkForCyclesHelper(const SDNode *N,
11750                                  SmallPtrSetImpl<const SDNode*> &Visited,
11751                                  SmallPtrSetImpl<const SDNode*> &Checked,
11752                                  const llvm::SelectionDAG *DAG) {
11753   // If this node has already been checked, don't check it again.
11754   if (Checked.count(N))
11755     return;
11756 
11757   // If a node has already been visited on this depth-first walk, reject it as
11758   // a cycle.
11759   if (!Visited.insert(N).second) {
11760     errs() << "Detected cycle in SelectionDAG\n";
11761     dbgs() << "Offending node:\n";
11762     N->dumprFull(DAG); dbgs() << "\n";
11763     abort();
11764   }
11765 
11766   for (const SDValue &Op : N->op_values())
11767     checkForCyclesHelper(Op.getNode(), Visited, Checked, DAG);
11768 
11769   Checked.insert(N);
11770   Visited.erase(N);
11771 }
11772 #endif
11773 
11774 void llvm::checkForCycles(const llvm::SDNode *N,
11775                           const llvm::SelectionDAG *DAG,
11776                           bool force) {
11777 #ifndef NDEBUG
11778   bool check = force;
11779 #ifdef EXPENSIVE_CHECKS
11780   check = true;
11781 #endif  // EXPENSIVE_CHECKS
11782   if (check) {
11783     assert(N && "Checking nonexistent SDNode");
11784     SmallPtrSet<const SDNode*, 32> visited;
11785     SmallPtrSet<const SDNode*, 32> checked;
11786     checkForCyclesHelper(N, visited, checked, DAG);
11787   }
11788 #endif  // !NDEBUG
11789 }
11790 
11791 void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) {
11792   checkForCycles(DAG->getRoot().getNode(), DAG, force);
11793 }
11794