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/ManagedStatic.h"
64 #include "llvm/Support/MathExtras.h"
65 #include "llvm/Support/Mutex.h"
66 #include "llvm/Support/raw_ostream.h"
67 #include "llvm/Target/TargetMachine.h"
68 #include "llvm/Target/TargetOptions.h"
69 #include "llvm/Transforms/Utils/SizeOpts.h"
70 #include <algorithm>
71 #include <cassert>
72 #include <cstdint>
73 #include <cstdlib>
74 #include <limits>
75 #include <set>
76 #include <string>
77 #include <utility>
78 #include <vector>
79 
80 using namespace llvm;
81 
82 /// makeVTList - Return an instance of the SDVTList struct initialized with the
83 /// specified members.
84 static SDVTList makeVTList(const EVT *VTs, unsigned NumVTs) {
85   SDVTList Res = {VTs, NumVTs};
86   return Res;
87 }
88 
89 // Default null implementations of the callbacks.
90 void SelectionDAG::DAGUpdateListener::NodeDeleted(SDNode*, SDNode*) {}
91 void SelectionDAG::DAGUpdateListener::NodeUpdated(SDNode*) {}
92 void SelectionDAG::DAGUpdateListener::NodeInserted(SDNode *) {}
93 
94 void SelectionDAG::DAGNodeDeletedListener::anchor() {}
95 
96 #define DEBUG_TYPE "selectiondag"
97 
98 static cl::opt<bool> EnableMemCpyDAGOpt("enable-memcpy-dag-opt",
99        cl::Hidden, cl::init(true),
100        cl::desc("Gang up loads and stores generated by inlining of memcpy"));
101 
102 static cl::opt<int> MaxLdStGlue("ldstmemcpy-glue-max",
103        cl::desc("Number limit for gluing ld/st of memcpy."),
104        cl::Hidden, cl::init(0));
105 
106 static void NewSDValueDbgMsg(SDValue V, StringRef Msg, SelectionDAG *G) {
107   LLVM_DEBUG(dbgs() << Msg; V.getNode()->dump(G););
108 }
109 
110 //===----------------------------------------------------------------------===//
111 //                              ConstantFPSDNode Class
112 //===----------------------------------------------------------------------===//
113 
114 /// isExactlyValue - We don't rely on operator== working on double values, as
115 /// it returns true for things that are clearly not equal, like -0.0 and 0.0.
116 /// As such, this method can be used to do an exact bit-for-bit comparison of
117 /// two floating point values.
118 bool ConstantFPSDNode::isExactlyValue(const APFloat& V) const {
119   return getValueAPF().bitwiseIsEqual(V);
120 }
121 
122 bool ConstantFPSDNode::isValueValidForType(EVT VT,
123                                            const APFloat& Val) {
124   assert(VT.isFloatingPoint() && "Can only convert between FP types");
125 
126   // convert modifies in place, so make a copy.
127   APFloat Val2 = APFloat(Val);
128   bool losesInfo;
129   (void) Val2.convert(SelectionDAG::EVTToAPFloatSemantics(VT),
130                       APFloat::rmNearestTiesToEven,
131                       &losesInfo);
132   return !losesInfo;
133 }
134 
135 //===----------------------------------------------------------------------===//
136 //                              ISD Namespace
137 //===----------------------------------------------------------------------===//
138 
139 bool ISD::isConstantSplatVector(const SDNode *N, APInt &SplatVal) {
140   if (N->getOpcode() == ISD::SPLAT_VECTOR) {
141     unsigned EltSize =
142         N->getValueType(0).getVectorElementType().getSizeInBits();
143     if (auto *Op0 = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
144       SplatVal = Op0->getAPIntValue().trunc(EltSize);
145       return true;
146     }
147     if (auto *Op0 = dyn_cast<ConstantFPSDNode>(N->getOperand(0))) {
148       SplatVal = Op0->getValueAPF().bitcastToAPInt().trunc(EltSize);
149       return true;
150     }
151   }
152 
153   auto *BV = dyn_cast<BuildVectorSDNode>(N);
154   if (!BV)
155     return false;
156 
157   APInt SplatUndef;
158   unsigned SplatBitSize;
159   bool HasUndefs;
160   unsigned EltSize = N->getValueType(0).getVectorElementType().getSizeInBits();
161   return BV->isConstantSplat(SplatVal, SplatUndef, SplatBitSize, HasUndefs,
162                              EltSize) &&
163          EltSize == SplatBitSize;
164 }
165 
166 // FIXME: AllOnes and AllZeros duplicate a lot of code. Could these be
167 // specializations of the more general isConstantSplatVector()?
168 
169 bool ISD::isConstantSplatVectorAllOnes(const SDNode *N, bool BuildVectorOnly) {
170   // Look through a bit convert.
171   while (N->getOpcode() == ISD::BITCAST)
172     N = N->getOperand(0).getNode();
173 
174   if (!BuildVectorOnly && N->getOpcode() == ISD::SPLAT_VECTOR) {
175     APInt SplatVal;
176     return isConstantSplatVector(N, SplatVal) && SplatVal.isAllOnes();
177   }
178 
179   if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
180 
181   unsigned i = 0, e = N->getNumOperands();
182 
183   // Skip over all of the undef values.
184   while (i != e && N->getOperand(i).isUndef())
185     ++i;
186 
187   // Do not accept an all-undef vector.
188   if (i == e) return false;
189 
190   // Do not accept build_vectors that aren't all constants or which have non-~0
191   // elements. We have to be a bit careful here, as the type of the constant
192   // may not be the same as the type of the vector elements due to type
193   // legalization (the elements are promoted to a legal type for the target and
194   // a vector of a type may be legal when the base element type is not).
195   // We only want to check enough bits to cover the vector elements, because
196   // we care if the resultant vector is all ones, not whether the individual
197   // constants are.
198   SDValue NotZero = N->getOperand(i);
199   unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
200   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(NotZero)) {
201     if (CN->getAPIntValue().countTrailingOnes() < EltSize)
202       return false;
203   } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(NotZero)) {
204     if (CFPN->getValueAPF().bitcastToAPInt().countTrailingOnes() < EltSize)
205       return false;
206   } else
207     return false;
208 
209   // Okay, we have at least one ~0 value, check to see if the rest match or are
210   // undefs. Even with the above element type twiddling, this should be OK, as
211   // the same type legalization should have applied to all the elements.
212   for (++i; i != e; ++i)
213     if (N->getOperand(i) != NotZero && !N->getOperand(i).isUndef())
214       return false;
215   return true;
216 }
217 
218 bool ISD::isConstantSplatVectorAllZeros(const SDNode *N, bool BuildVectorOnly) {
219   // Look through a bit convert.
220   while (N->getOpcode() == ISD::BITCAST)
221     N = N->getOperand(0).getNode();
222 
223   if (!BuildVectorOnly && N->getOpcode() == ISD::SPLAT_VECTOR) {
224     APInt SplatVal;
225     return isConstantSplatVector(N, SplatVal) && SplatVal.isZero();
226   }
227 
228   if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
229 
230   bool IsAllUndef = true;
231   for (const SDValue &Op : N->op_values()) {
232     if (Op.isUndef())
233       continue;
234     IsAllUndef = false;
235     // Do not accept build_vectors that aren't all constants or which have non-0
236     // elements. We have to be a bit careful here, as the type of the constant
237     // may not be the same as the type of the vector elements due to type
238     // legalization (the elements are promoted to a legal type for the target
239     // and a vector of a type may be legal when the base element type is not).
240     // We only want to check enough bits to cover the vector elements, because
241     // we care if the resultant vector is all zeros, not whether the individual
242     // constants are.
243     unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
244     if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Op)) {
245       if (CN->getAPIntValue().countTrailingZeros() < EltSize)
246         return false;
247     } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(Op)) {
248       if (CFPN->getValueAPF().bitcastToAPInt().countTrailingZeros() < EltSize)
249         return false;
250     } else
251       return false;
252   }
253 
254   // Do not accept an all-undef vector.
255   if (IsAllUndef)
256     return false;
257   return true;
258 }
259 
260 bool ISD::isBuildVectorAllOnes(const SDNode *N) {
261   return isConstantSplatVectorAllOnes(N, /*BuildVectorOnly*/ true);
262 }
263 
264 bool ISD::isBuildVectorAllZeros(const SDNode *N) {
265   return isConstantSplatVectorAllZeros(N, /*BuildVectorOnly*/ true);
266 }
267 
268 bool ISD::isBuildVectorOfConstantSDNodes(const SDNode *N) {
269   if (N->getOpcode() != ISD::BUILD_VECTOR)
270     return false;
271 
272   for (const SDValue &Op : N->op_values()) {
273     if (Op.isUndef())
274       continue;
275     if (!isa<ConstantSDNode>(Op))
276       return false;
277   }
278   return true;
279 }
280 
281 bool ISD::isBuildVectorOfConstantFPSDNodes(const SDNode *N) {
282   if (N->getOpcode() != ISD::BUILD_VECTOR)
283     return false;
284 
285   for (const SDValue &Op : N->op_values()) {
286     if (Op.isUndef())
287       continue;
288     if (!isa<ConstantFPSDNode>(Op))
289       return false;
290   }
291   return true;
292 }
293 
294 bool ISD::allOperandsUndef(const SDNode *N) {
295   // Return false if the node has no operands.
296   // This is "logically inconsistent" with the definition of "all" but
297   // is probably the desired behavior.
298   if (N->getNumOperands() == 0)
299     return false;
300   return all_of(N->op_values(), [](SDValue Op) { return Op.isUndef(); });
301 }
302 
303 bool ISD::matchUnaryPredicate(SDValue Op,
304                               std::function<bool(ConstantSDNode *)> Match,
305                               bool AllowUndefs) {
306   // FIXME: Add support for scalar UNDEF cases?
307   if (auto *Cst = dyn_cast<ConstantSDNode>(Op))
308     return Match(Cst);
309 
310   // FIXME: Add support for vector UNDEF cases?
311   if (ISD::BUILD_VECTOR != Op.getOpcode() &&
312       ISD::SPLAT_VECTOR != Op.getOpcode())
313     return false;
314 
315   EVT SVT = Op.getValueType().getScalarType();
316   for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
317     if (AllowUndefs && Op.getOperand(i).isUndef()) {
318       if (!Match(nullptr))
319         return false;
320       continue;
321     }
322 
323     auto *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(i));
324     if (!Cst || Cst->getValueType(0) != SVT || !Match(Cst))
325       return false;
326   }
327   return true;
328 }
329 
330 bool ISD::matchBinaryPredicate(
331     SDValue LHS, SDValue RHS,
332     std::function<bool(ConstantSDNode *, ConstantSDNode *)> Match,
333     bool AllowUndefs, bool AllowTypeMismatch) {
334   if (!AllowTypeMismatch && LHS.getValueType() != RHS.getValueType())
335     return false;
336 
337   // TODO: Add support for scalar UNDEF cases?
338   if (auto *LHSCst = dyn_cast<ConstantSDNode>(LHS))
339     if (auto *RHSCst = dyn_cast<ConstantSDNode>(RHS))
340       return Match(LHSCst, RHSCst);
341 
342   // TODO: Add support for vector UNDEF cases?
343   if (LHS.getOpcode() != RHS.getOpcode() ||
344       (LHS.getOpcode() != ISD::BUILD_VECTOR &&
345        LHS.getOpcode() != ISD::SPLAT_VECTOR))
346     return false;
347 
348   EVT SVT = LHS.getValueType().getScalarType();
349   for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
350     SDValue LHSOp = LHS.getOperand(i);
351     SDValue RHSOp = RHS.getOperand(i);
352     bool LHSUndef = AllowUndefs && LHSOp.isUndef();
353     bool RHSUndef = AllowUndefs && RHSOp.isUndef();
354     auto *LHSCst = dyn_cast<ConstantSDNode>(LHSOp);
355     auto *RHSCst = dyn_cast<ConstantSDNode>(RHSOp);
356     if ((!LHSCst && !LHSUndef) || (!RHSCst && !RHSUndef))
357       return false;
358     if (!AllowTypeMismatch && (LHSOp.getValueType() != SVT ||
359                                LHSOp.getValueType() != RHSOp.getValueType()))
360       return false;
361     if (!Match(LHSCst, RHSCst))
362       return false;
363   }
364   return true;
365 }
366 
367 ISD::NodeType ISD::getVecReduceBaseOpcode(unsigned VecReduceOpcode) {
368   switch (VecReduceOpcode) {
369   default:
370     llvm_unreachable("Expected VECREDUCE opcode");
371   case ISD::VECREDUCE_FADD:
372   case ISD::VECREDUCE_SEQ_FADD:
373   case ISD::VP_REDUCE_FADD:
374   case ISD::VP_REDUCE_SEQ_FADD:
375     return ISD::FADD;
376   case ISD::VECREDUCE_FMUL:
377   case ISD::VECREDUCE_SEQ_FMUL:
378   case ISD::VP_REDUCE_FMUL:
379   case ISD::VP_REDUCE_SEQ_FMUL:
380     return ISD::FMUL;
381   case ISD::VECREDUCE_ADD:
382   case ISD::VP_REDUCE_ADD:
383     return ISD::ADD;
384   case ISD::VECREDUCE_MUL:
385   case ISD::VP_REDUCE_MUL:
386     return ISD::MUL;
387   case ISD::VECREDUCE_AND:
388   case ISD::VP_REDUCE_AND:
389     return ISD::AND;
390   case ISD::VECREDUCE_OR:
391   case ISD::VP_REDUCE_OR:
392     return ISD::OR;
393   case ISD::VECREDUCE_XOR:
394   case ISD::VP_REDUCE_XOR:
395     return ISD::XOR;
396   case ISD::VECREDUCE_SMAX:
397   case ISD::VP_REDUCE_SMAX:
398     return ISD::SMAX;
399   case ISD::VECREDUCE_SMIN:
400   case ISD::VP_REDUCE_SMIN:
401     return ISD::SMIN;
402   case ISD::VECREDUCE_UMAX:
403   case ISD::VP_REDUCE_UMAX:
404     return ISD::UMAX;
405   case ISD::VECREDUCE_UMIN:
406   case ISD::VP_REDUCE_UMIN:
407     return ISD::UMIN;
408   case ISD::VECREDUCE_FMAX:
409   case ISD::VP_REDUCE_FMAX:
410     return ISD::FMAXNUM;
411   case ISD::VECREDUCE_FMIN:
412   case ISD::VP_REDUCE_FMIN:
413     return ISD::FMINNUM;
414   }
415 }
416 
417 bool ISD::isVPOpcode(unsigned Opcode) {
418   switch (Opcode) {
419   default:
420     return false;
421 #define BEGIN_REGISTER_VP_SDNODE(VPSD, ...)                                    \
422   case ISD::VPSD:                                                              \
423     return true;
424 #include "llvm/IR/VPIntrinsics.def"
425   }
426 }
427 
428 bool ISD::isVPBinaryOp(unsigned Opcode) {
429   switch (Opcode) {
430   default:
431     break;
432 #define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) case ISD::VPSD:
433 #define VP_PROPERTY_BINARYOP return true;
434 #define END_REGISTER_VP_SDNODE(VPSD) break;
435 #include "llvm/IR/VPIntrinsics.def"
436   }
437   return false;
438 }
439 
440 bool ISD::isVPReduction(unsigned Opcode) {
441   switch (Opcode) {
442   default:
443     break;
444 #define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) case ISD::VPSD:
445 #define VP_PROPERTY_REDUCTION(STARTPOS, ...) return true;
446 #define END_REGISTER_VP_SDNODE(VPSD) break;
447 #include "llvm/IR/VPIntrinsics.def"
448   }
449   return false;
450 }
451 
452 /// The operand position of the vector mask.
453 Optional<unsigned> ISD::getVPMaskIdx(unsigned Opcode) {
454   switch (Opcode) {
455   default:
456     return None;
457 #define BEGIN_REGISTER_VP_SDNODE(VPSD, LEGALPOS, TDNAME, MASKPOS, ...)         \
458   case ISD::VPSD:                                                              \
459     return MASKPOS;
460 #include "llvm/IR/VPIntrinsics.def"
461   }
462 }
463 
464 /// The operand position of the explicit vector length parameter.
465 Optional<unsigned> ISD::getVPExplicitVectorLengthIdx(unsigned Opcode) {
466   switch (Opcode) {
467   default:
468     return None;
469 #define BEGIN_REGISTER_VP_SDNODE(VPSD, LEGALPOS, TDNAME, MASKPOS, EVLPOS)      \
470   case ISD::VPSD:                                                              \
471     return EVLPOS;
472 #include "llvm/IR/VPIntrinsics.def"
473   }
474 }
475 
476 ISD::NodeType ISD::getExtForLoadExtType(bool IsFP, ISD::LoadExtType ExtType) {
477   switch (ExtType) {
478   case ISD::EXTLOAD:
479     return IsFP ? ISD::FP_EXTEND : ISD::ANY_EXTEND;
480   case ISD::SEXTLOAD:
481     return ISD::SIGN_EXTEND;
482   case ISD::ZEXTLOAD:
483     return ISD::ZERO_EXTEND;
484   default:
485     break;
486   }
487 
488   llvm_unreachable("Invalid LoadExtType");
489 }
490 
491 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) {
492   // To perform this operation, we just need to swap the L and G bits of the
493   // operation.
494   unsigned OldL = (Operation >> 2) & 1;
495   unsigned OldG = (Operation >> 1) & 1;
496   return ISD::CondCode((Operation & ~6) |  // Keep the N, U, E bits
497                        (OldL << 1) |       // New G bit
498                        (OldG << 2));       // New L bit.
499 }
500 
501 static ISD::CondCode getSetCCInverseImpl(ISD::CondCode Op, bool isIntegerLike) {
502   unsigned Operation = Op;
503   if (isIntegerLike)
504     Operation ^= 7;   // Flip L, G, E bits, but not U.
505   else
506     Operation ^= 15;  // Flip all of the condition bits.
507 
508   if (Operation > ISD::SETTRUE2)
509     Operation &= ~8;  // Don't let N and U bits get set.
510 
511   return ISD::CondCode(Operation);
512 }
513 
514 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, EVT Type) {
515   return getSetCCInverseImpl(Op, Type.isInteger());
516 }
517 
518 ISD::CondCode ISD::GlobalISel::getSetCCInverse(ISD::CondCode Op,
519                                                bool isIntegerLike) {
520   return getSetCCInverseImpl(Op, isIntegerLike);
521 }
522 
523 /// For an integer comparison, return 1 if the comparison is a signed operation
524 /// and 2 if the result is an unsigned comparison. Return zero if the operation
525 /// does not depend on the sign of the input (setne and seteq).
526 static int isSignedOp(ISD::CondCode Opcode) {
527   switch (Opcode) {
528   default: llvm_unreachable("Illegal integer setcc operation!");
529   case ISD::SETEQ:
530   case ISD::SETNE: return 0;
531   case ISD::SETLT:
532   case ISD::SETLE:
533   case ISD::SETGT:
534   case ISD::SETGE: return 1;
535   case ISD::SETULT:
536   case ISD::SETULE:
537   case ISD::SETUGT:
538   case ISD::SETUGE: return 2;
539   }
540 }
541 
542 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2,
543                                        EVT Type) {
544   bool IsInteger = Type.isInteger();
545   if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
546     // Cannot fold a signed integer setcc with an unsigned integer setcc.
547     return ISD::SETCC_INVALID;
548 
549   unsigned Op = Op1 | Op2;  // Combine all of the condition bits.
550 
551   // If the N and U bits get set, then the resultant comparison DOES suddenly
552   // care about orderedness, and it is true when ordered.
553   if (Op > ISD::SETTRUE2)
554     Op &= ~16;     // Clear the U bit if the N bit is set.
555 
556   // Canonicalize illegal integer setcc's.
557   if (IsInteger && Op == ISD::SETUNE)  // e.g. SETUGT | SETULT
558     Op = ISD::SETNE;
559 
560   return ISD::CondCode(Op);
561 }
562 
563 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2,
564                                         EVT Type) {
565   bool IsInteger = Type.isInteger();
566   if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
567     // Cannot fold a signed setcc with an unsigned setcc.
568     return ISD::SETCC_INVALID;
569 
570   // Combine all of the condition bits.
571   ISD::CondCode Result = ISD::CondCode(Op1 & Op2);
572 
573   // Canonicalize illegal integer setcc's.
574   if (IsInteger) {
575     switch (Result) {
576     default: break;
577     case ISD::SETUO : Result = ISD::SETFALSE; break;  // SETUGT & SETULT
578     case ISD::SETOEQ:                                 // SETEQ  & SETU[LG]E
579     case ISD::SETUEQ: Result = ISD::SETEQ   ; break;  // SETUGE & SETULE
580     case ISD::SETOLT: Result = ISD::SETULT  ; break;  // SETULT & SETNE
581     case ISD::SETOGT: Result = ISD::SETUGT  ; break;  // SETUGT & SETNE
582     }
583   }
584 
585   return Result;
586 }
587 
588 //===----------------------------------------------------------------------===//
589 //                           SDNode Profile Support
590 //===----------------------------------------------------------------------===//
591 
592 /// AddNodeIDOpcode - Add the node opcode to the NodeID data.
593 static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC)  {
594   ID.AddInteger(OpC);
595 }
596 
597 /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them
598 /// solely with their pointer.
599 static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) {
600   ID.AddPointer(VTList.VTs);
601 }
602 
603 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
604 static void AddNodeIDOperands(FoldingSetNodeID &ID,
605                               ArrayRef<SDValue> Ops) {
606   for (auto& Op : Ops) {
607     ID.AddPointer(Op.getNode());
608     ID.AddInteger(Op.getResNo());
609   }
610 }
611 
612 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
613 static void AddNodeIDOperands(FoldingSetNodeID &ID,
614                               ArrayRef<SDUse> Ops) {
615   for (auto& Op : Ops) {
616     ID.AddPointer(Op.getNode());
617     ID.AddInteger(Op.getResNo());
618   }
619 }
620 
621 static void AddNodeIDNode(FoldingSetNodeID &ID, unsigned short OpC,
622                           SDVTList VTList, ArrayRef<SDValue> OpList) {
623   AddNodeIDOpcode(ID, OpC);
624   AddNodeIDValueTypes(ID, VTList);
625   AddNodeIDOperands(ID, OpList);
626 }
627 
628 /// If this is an SDNode with special info, add this info to the NodeID data.
629 static void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N) {
630   switch (N->getOpcode()) {
631   case ISD::TargetExternalSymbol:
632   case ISD::ExternalSymbol:
633   case ISD::MCSymbol:
634     llvm_unreachable("Should only be used on nodes with operands");
635   default: break;  // Normal nodes don't need extra info.
636   case ISD::TargetConstant:
637   case ISD::Constant: {
638     const ConstantSDNode *C = cast<ConstantSDNode>(N);
639     ID.AddPointer(C->getConstantIntValue());
640     ID.AddBoolean(C->isOpaque());
641     break;
642   }
643   case ISD::TargetConstantFP:
644   case ISD::ConstantFP:
645     ID.AddPointer(cast<ConstantFPSDNode>(N)->getConstantFPValue());
646     break;
647   case ISD::TargetGlobalAddress:
648   case ISD::GlobalAddress:
649   case ISD::TargetGlobalTLSAddress:
650   case ISD::GlobalTLSAddress: {
651     const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
652     ID.AddPointer(GA->getGlobal());
653     ID.AddInteger(GA->getOffset());
654     ID.AddInteger(GA->getTargetFlags());
655     break;
656   }
657   case ISD::BasicBlock:
658     ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock());
659     break;
660   case ISD::Register:
661     ID.AddInteger(cast<RegisterSDNode>(N)->getReg());
662     break;
663   case ISD::RegisterMask:
664     ID.AddPointer(cast<RegisterMaskSDNode>(N)->getRegMask());
665     break;
666   case ISD::SRCVALUE:
667     ID.AddPointer(cast<SrcValueSDNode>(N)->getValue());
668     break;
669   case ISD::FrameIndex:
670   case ISD::TargetFrameIndex:
671     ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex());
672     break;
673   case ISD::LIFETIME_START:
674   case ISD::LIFETIME_END:
675     if (cast<LifetimeSDNode>(N)->hasOffset()) {
676       ID.AddInteger(cast<LifetimeSDNode>(N)->getSize());
677       ID.AddInteger(cast<LifetimeSDNode>(N)->getOffset());
678     }
679     break;
680   case ISD::PSEUDO_PROBE:
681     ID.AddInteger(cast<PseudoProbeSDNode>(N)->getGuid());
682     ID.AddInteger(cast<PseudoProbeSDNode>(N)->getIndex());
683     ID.AddInteger(cast<PseudoProbeSDNode>(N)->getAttributes());
684     break;
685   case ISD::JumpTable:
686   case ISD::TargetJumpTable:
687     ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex());
688     ID.AddInteger(cast<JumpTableSDNode>(N)->getTargetFlags());
689     break;
690   case ISD::ConstantPool:
691   case ISD::TargetConstantPool: {
692     const ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N);
693     ID.AddInteger(CP->getAlign().value());
694     ID.AddInteger(CP->getOffset());
695     if (CP->isMachineConstantPoolEntry())
696       CP->getMachineCPVal()->addSelectionDAGCSEId(ID);
697     else
698       ID.AddPointer(CP->getConstVal());
699     ID.AddInteger(CP->getTargetFlags());
700     break;
701   }
702   case ISD::TargetIndex: {
703     const TargetIndexSDNode *TI = cast<TargetIndexSDNode>(N);
704     ID.AddInteger(TI->getIndex());
705     ID.AddInteger(TI->getOffset());
706     ID.AddInteger(TI->getTargetFlags());
707     break;
708   }
709   case ISD::LOAD: {
710     const LoadSDNode *LD = cast<LoadSDNode>(N);
711     ID.AddInteger(LD->getMemoryVT().getRawBits());
712     ID.AddInteger(LD->getRawSubclassData());
713     ID.AddInteger(LD->getPointerInfo().getAddrSpace());
714     ID.AddInteger(LD->getMemOperand()->getFlags());
715     break;
716   }
717   case ISD::STORE: {
718     const StoreSDNode *ST = cast<StoreSDNode>(N);
719     ID.AddInteger(ST->getMemoryVT().getRawBits());
720     ID.AddInteger(ST->getRawSubclassData());
721     ID.AddInteger(ST->getPointerInfo().getAddrSpace());
722     ID.AddInteger(ST->getMemOperand()->getFlags());
723     break;
724   }
725   case ISD::VP_LOAD: {
726     const VPLoadSDNode *ELD = cast<VPLoadSDNode>(N);
727     ID.AddInteger(ELD->getMemoryVT().getRawBits());
728     ID.AddInteger(ELD->getRawSubclassData());
729     ID.AddInteger(ELD->getPointerInfo().getAddrSpace());
730     ID.AddInteger(ELD->getMemOperand()->getFlags());
731     break;
732   }
733   case ISD::VP_STORE: {
734     const VPStoreSDNode *EST = cast<VPStoreSDNode>(N);
735     ID.AddInteger(EST->getMemoryVT().getRawBits());
736     ID.AddInteger(EST->getRawSubclassData());
737     ID.AddInteger(EST->getPointerInfo().getAddrSpace());
738     ID.AddInteger(EST->getMemOperand()->getFlags());
739     break;
740   }
741   case ISD::EXPERIMENTAL_VP_STRIDED_LOAD: {
742     const VPStridedLoadSDNode *SLD = cast<VPStridedLoadSDNode>(N);
743     ID.AddInteger(SLD->getMemoryVT().getRawBits());
744     ID.AddInteger(SLD->getRawSubclassData());
745     ID.AddInteger(SLD->getPointerInfo().getAddrSpace());
746     break;
747   }
748   case ISD::EXPERIMENTAL_VP_STRIDED_STORE: {
749     const VPStridedStoreSDNode *SST = cast<VPStridedStoreSDNode>(N);
750     ID.AddInteger(SST->getMemoryVT().getRawBits());
751     ID.AddInteger(SST->getRawSubclassData());
752     ID.AddInteger(SST->getPointerInfo().getAddrSpace());
753     break;
754   }
755   case ISD::VP_GATHER: {
756     const VPGatherSDNode *EG = cast<VPGatherSDNode>(N);
757     ID.AddInteger(EG->getMemoryVT().getRawBits());
758     ID.AddInteger(EG->getRawSubclassData());
759     ID.AddInteger(EG->getPointerInfo().getAddrSpace());
760     ID.AddInteger(EG->getMemOperand()->getFlags());
761     break;
762   }
763   case ISD::VP_SCATTER: {
764     const VPScatterSDNode *ES = cast<VPScatterSDNode>(N);
765     ID.AddInteger(ES->getMemoryVT().getRawBits());
766     ID.AddInteger(ES->getRawSubclassData());
767     ID.AddInteger(ES->getPointerInfo().getAddrSpace());
768     ID.AddInteger(ES->getMemOperand()->getFlags());
769     break;
770   }
771   case ISD::MLOAD: {
772     const MaskedLoadSDNode *MLD = cast<MaskedLoadSDNode>(N);
773     ID.AddInteger(MLD->getMemoryVT().getRawBits());
774     ID.AddInteger(MLD->getRawSubclassData());
775     ID.AddInteger(MLD->getPointerInfo().getAddrSpace());
776     ID.AddInteger(MLD->getMemOperand()->getFlags());
777     break;
778   }
779   case ISD::MSTORE: {
780     const MaskedStoreSDNode *MST = cast<MaskedStoreSDNode>(N);
781     ID.AddInteger(MST->getMemoryVT().getRawBits());
782     ID.AddInteger(MST->getRawSubclassData());
783     ID.AddInteger(MST->getPointerInfo().getAddrSpace());
784     ID.AddInteger(MST->getMemOperand()->getFlags());
785     break;
786   }
787   case ISD::MGATHER: {
788     const MaskedGatherSDNode *MG = cast<MaskedGatherSDNode>(N);
789     ID.AddInteger(MG->getMemoryVT().getRawBits());
790     ID.AddInteger(MG->getRawSubclassData());
791     ID.AddInteger(MG->getPointerInfo().getAddrSpace());
792     ID.AddInteger(MG->getMemOperand()->getFlags());
793     break;
794   }
795   case ISD::MSCATTER: {
796     const MaskedScatterSDNode *MS = cast<MaskedScatterSDNode>(N);
797     ID.AddInteger(MS->getMemoryVT().getRawBits());
798     ID.AddInteger(MS->getRawSubclassData());
799     ID.AddInteger(MS->getPointerInfo().getAddrSpace());
800     ID.AddInteger(MS->getMemOperand()->getFlags());
801     break;
802   }
803   case ISD::ATOMIC_CMP_SWAP:
804   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
805   case ISD::ATOMIC_SWAP:
806   case ISD::ATOMIC_LOAD_ADD:
807   case ISD::ATOMIC_LOAD_SUB:
808   case ISD::ATOMIC_LOAD_AND:
809   case ISD::ATOMIC_LOAD_CLR:
810   case ISD::ATOMIC_LOAD_OR:
811   case ISD::ATOMIC_LOAD_XOR:
812   case ISD::ATOMIC_LOAD_NAND:
813   case ISD::ATOMIC_LOAD_MIN:
814   case ISD::ATOMIC_LOAD_MAX:
815   case ISD::ATOMIC_LOAD_UMIN:
816   case ISD::ATOMIC_LOAD_UMAX:
817   case ISD::ATOMIC_LOAD:
818   case ISD::ATOMIC_STORE: {
819     const AtomicSDNode *AT = cast<AtomicSDNode>(N);
820     ID.AddInteger(AT->getMemoryVT().getRawBits());
821     ID.AddInteger(AT->getRawSubclassData());
822     ID.AddInteger(AT->getPointerInfo().getAddrSpace());
823     ID.AddInteger(AT->getMemOperand()->getFlags());
824     break;
825   }
826   case ISD::PREFETCH: {
827     const MemSDNode *PF = cast<MemSDNode>(N);
828     ID.AddInteger(PF->getPointerInfo().getAddrSpace());
829     ID.AddInteger(PF->getMemOperand()->getFlags());
830     break;
831   }
832   case ISD::VECTOR_SHUFFLE: {
833     const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
834     for (unsigned i = 0, e = N->getValueType(0).getVectorNumElements();
835          i != e; ++i)
836       ID.AddInteger(SVN->getMaskElt(i));
837     break;
838   }
839   case ISD::TargetBlockAddress:
840   case ISD::BlockAddress: {
841     const BlockAddressSDNode *BA = cast<BlockAddressSDNode>(N);
842     ID.AddPointer(BA->getBlockAddress());
843     ID.AddInteger(BA->getOffset());
844     ID.AddInteger(BA->getTargetFlags());
845     break;
846   }
847   case ISD::AssertAlign:
848     ID.AddInteger(cast<AssertAlignSDNode>(N)->getAlign().value());
849     break;
850   } // end switch (N->getOpcode())
851 
852   // Target specific memory nodes could also have address spaces and flags
853   // to check.
854   if (N->isTargetMemoryOpcode()) {
855     const MemSDNode *MN = cast<MemSDNode>(N);
856     ID.AddInteger(MN->getPointerInfo().getAddrSpace());
857     ID.AddInteger(MN->getMemOperand()->getFlags());
858   }
859 }
860 
861 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID
862 /// data.
863 static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) {
864   AddNodeIDOpcode(ID, N->getOpcode());
865   // Add the return value info.
866   AddNodeIDValueTypes(ID, N->getVTList());
867   // Add the operand info.
868   AddNodeIDOperands(ID, N->ops());
869 
870   // Handle SDNode leafs with special info.
871   AddNodeIDCustom(ID, N);
872 }
873 
874 //===----------------------------------------------------------------------===//
875 //                              SelectionDAG Class
876 //===----------------------------------------------------------------------===//
877 
878 /// doNotCSE - Return true if CSE should not be performed for this node.
879 static bool doNotCSE(SDNode *N) {
880   if (N->getValueType(0) == MVT::Glue)
881     return true; // Never CSE anything that produces a flag.
882 
883   switch (N->getOpcode()) {
884   default: break;
885   case ISD::HANDLENODE:
886   case ISD::EH_LABEL:
887     return true;   // Never CSE these nodes.
888   }
889 
890   // Check that remaining values produced are not flags.
891   for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
892     if (N->getValueType(i) == MVT::Glue)
893       return true; // Never CSE anything that produces a flag.
894 
895   return false;
896 }
897 
898 /// RemoveDeadNodes - This method deletes all unreachable nodes in the
899 /// SelectionDAG.
900 void SelectionDAG::RemoveDeadNodes() {
901   // Create a dummy node (which is not added to allnodes), that adds a reference
902   // to the root node, preventing it from being deleted.
903   HandleSDNode Dummy(getRoot());
904 
905   SmallVector<SDNode*, 128> DeadNodes;
906 
907   // Add all obviously-dead nodes to the DeadNodes worklist.
908   for (SDNode &Node : allnodes())
909     if (Node.use_empty())
910       DeadNodes.push_back(&Node);
911 
912   RemoveDeadNodes(DeadNodes);
913 
914   // If the root changed (e.g. it was a dead load, update the root).
915   setRoot(Dummy.getValue());
916 }
917 
918 /// RemoveDeadNodes - This method deletes the unreachable nodes in the
919 /// given list, and any nodes that become unreachable as a result.
920 void SelectionDAG::RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes) {
921 
922   // Process the worklist, deleting the nodes and adding their uses to the
923   // worklist.
924   while (!DeadNodes.empty()) {
925     SDNode *N = DeadNodes.pop_back_val();
926     // Skip to next node if we've already managed to delete the node. This could
927     // happen if replacing a node causes a node previously added to the node to
928     // be deleted.
929     if (N->getOpcode() == ISD::DELETED_NODE)
930       continue;
931 
932     for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
933       DUL->NodeDeleted(N, nullptr);
934 
935     // Take the node out of the appropriate CSE map.
936     RemoveNodeFromCSEMaps(N);
937 
938     // Next, brutally remove the operand list.  This is safe to do, as there are
939     // no cycles in the graph.
940     for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
941       SDUse &Use = *I++;
942       SDNode *Operand = Use.getNode();
943       Use.set(SDValue());
944 
945       // Now that we removed this operand, see if there are no uses of it left.
946       if (Operand->use_empty())
947         DeadNodes.push_back(Operand);
948     }
949 
950     DeallocateNode(N);
951   }
952 }
953 
954 void SelectionDAG::RemoveDeadNode(SDNode *N){
955   SmallVector<SDNode*, 16> DeadNodes(1, N);
956 
957   // Create a dummy node that adds a reference to the root node, preventing
958   // it from being deleted.  (This matters if the root is an operand of the
959   // dead node.)
960   HandleSDNode Dummy(getRoot());
961 
962   RemoveDeadNodes(DeadNodes);
963 }
964 
965 void SelectionDAG::DeleteNode(SDNode *N) {
966   // First take this out of the appropriate CSE map.
967   RemoveNodeFromCSEMaps(N);
968 
969   // Finally, remove uses due to operands of this node, remove from the
970   // AllNodes list, and delete the node.
971   DeleteNodeNotInCSEMaps(N);
972 }
973 
974 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
975   assert(N->getIterator() != AllNodes.begin() &&
976          "Cannot delete the entry node!");
977   assert(N->use_empty() && "Cannot delete a node that is not dead!");
978 
979   // Drop all of the operands and decrement used node's use counts.
980   N->DropOperands();
981 
982   DeallocateNode(N);
983 }
984 
985 void SDDbgInfo::add(SDDbgValue *V, bool isParameter) {
986   assert(!(V->isVariadic() && isParameter));
987   if (isParameter)
988     ByvalParmDbgValues.push_back(V);
989   else
990     DbgValues.push_back(V);
991   for (const SDNode *Node : V->getSDNodes())
992     if (Node)
993       DbgValMap[Node].push_back(V);
994 }
995 
996 void SDDbgInfo::erase(const SDNode *Node) {
997   DbgValMapType::iterator I = DbgValMap.find(Node);
998   if (I == DbgValMap.end())
999     return;
1000   for (auto &Val: I->second)
1001     Val->setIsInvalidated();
1002   DbgValMap.erase(I);
1003 }
1004 
1005 void SelectionDAG::DeallocateNode(SDNode *N) {
1006   // If we have operands, deallocate them.
1007   removeOperands(N);
1008 
1009   NodeAllocator.Deallocate(AllNodes.remove(N));
1010 
1011   // Set the opcode to DELETED_NODE to help catch bugs when node
1012   // memory is reallocated.
1013   // FIXME: There are places in SDag that have grown a dependency on the opcode
1014   // value in the released node.
1015   __asan_unpoison_memory_region(&N->NodeType, sizeof(N->NodeType));
1016   N->NodeType = ISD::DELETED_NODE;
1017 
1018   // If any of the SDDbgValue nodes refer to this SDNode, invalidate
1019   // them and forget about that node.
1020   DbgInfo->erase(N);
1021 }
1022 
1023 #ifndef NDEBUG
1024 /// VerifySDNode - Check the given SDNode.  Aborts if it is invalid.
1025 static void VerifySDNode(SDNode *N) {
1026   switch (N->getOpcode()) {
1027   default:
1028     break;
1029   case ISD::BUILD_PAIR: {
1030     EVT VT = N->getValueType(0);
1031     assert(N->getNumValues() == 1 && "Too many results!");
1032     assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) &&
1033            "Wrong return type!");
1034     assert(N->getNumOperands() == 2 && "Wrong number of operands!");
1035     assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() &&
1036            "Mismatched operand types!");
1037     assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() &&
1038            "Wrong operand type!");
1039     assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() &&
1040            "Wrong return type size");
1041     break;
1042   }
1043   case ISD::BUILD_VECTOR: {
1044     assert(N->getNumValues() == 1 && "Too many results!");
1045     assert(N->getValueType(0).isVector() && "Wrong return type!");
1046     assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() &&
1047            "Wrong number of operands!");
1048     EVT EltVT = N->getValueType(0).getVectorElementType();
1049     for (const SDUse &Op : N->ops()) {
1050       assert((Op.getValueType() == EltVT ||
1051               (EltVT.isInteger() && Op.getValueType().isInteger() &&
1052                EltVT.bitsLE(Op.getValueType()))) &&
1053              "Wrong operand type!");
1054       assert(Op.getValueType() == N->getOperand(0).getValueType() &&
1055              "Operands must all have the same type");
1056     }
1057     break;
1058   }
1059   }
1060 }
1061 #endif // NDEBUG
1062 
1063 /// Insert a newly allocated node into the DAG.
1064 ///
1065 /// Handles insertion into the all nodes list and CSE map, as well as
1066 /// verification and other common operations when a new node is allocated.
1067 void SelectionDAG::InsertNode(SDNode *N) {
1068   AllNodes.push_back(N);
1069 #ifndef NDEBUG
1070   N->PersistentId = NextPersistentId++;
1071   VerifySDNode(N);
1072 #endif
1073   for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1074     DUL->NodeInserted(N);
1075 }
1076 
1077 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
1078 /// correspond to it.  This is useful when we're about to delete or repurpose
1079 /// the node.  We don't want future request for structurally identical nodes
1080 /// to return N anymore.
1081 bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
1082   bool Erased = false;
1083   switch (N->getOpcode()) {
1084   case ISD::HANDLENODE: return false;  // noop.
1085   case ISD::CONDCODE:
1086     assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
1087            "Cond code doesn't exist!");
1088     Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != nullptr;
1089     CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = nullptr;
1090     break;
1091   case ISD::ExternalSymbol:
1092     Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
1093     break;
1094   case ISD::TargetExternalSymbol: {
1095     ExternalSymbolSDNode *ESN = cast<ExternalSymbolSDNode>(N);
1096     Erased = TargetExternalSymbols.erase(std::pair<std::string, unsigned>(
1097         ESN->getSymbol(), ESN->getTargetFlags()));
1098     break;
1099   }
1100   case ISD::MCSymbol: {
1101     auto *MCSN = cast<MCSymbolSDNode>(N);
1102     Erased = MCSymbols.erase(MCSN->getMCSymbol());
1103     break;
1104   }
1105   case ISD::VALUETYPE: {
1106     EVT VT = cast<VTSDNode>(N)->getVT();
1107     if (VT.isExtended()) {
1108       Erased = ExtendedValueTypeNodes.erase(VT);
1109     } else {
1110       Erased = ValueTypeNodes[VT.getSimpleVT().SimpleTy] != nullptr;
1111       ValueTypeNodes[VT.getSimpleVT().SimpleTy] = nullptr;
1112     }
1113     break;
1114   }
1115   default:
1116     // Remove it from the CSE Map.
1117     assert(N->getOpcode() != ISD::DELETED_NODE && "DELETED_NODE in CSEMap!");
1118     assert(N->getOpcode() != ISD::EntryToken && "EntryToken in CSEMap!");
1119     Erased = CSEMap.RemoveNode(N);
1120     break;
1121   }
1122 #ifndef NDEBUG
1123   // Verify that the node was actually in one of the CSE maps, unless it has a
1124   // flag result (which cannot be CSE'd) or is one of the special cases that are
1125   // not subject to CSE.
1126   if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Glue &&
1127       !N->isMachineOpcode() && !doNotCSE(N)) {
1128     N->dump(this);
1129     dbgs() << "\n";
1130     llvm_unreachable("Node is not in map!");
1131   }
1132 #endif
1133   return Erased;
1134 }
1135 
1136 /// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE
1137 /// maps and modified in place. Add it back to the CSE maps, unless an identical
1138 /// node already exists, in which case transfer all its users to the existing
1139 /// node. This transfer can potentially trigger recursive merging.
1140 void
1141 SelectionDAG::AddModifiedNodeToCSEMaps(SDNode *N) {
1142   // For node types that aren't CSE'd, just act as if no identical node
1143   // already exists.
1144   if (!doNotCSE(N)) {
1145     SDNode *Existing = CSEMap.GetOrInsertNode(N);
1146     if (Existing != N) {
1147       // If there was already an existing matching node, use ReplaceAllUsesWith
1148       // to replace the dead one with the existing one.  This can cause
1149       // recursive merging of other unrelated nodes down the line.
1150       ReplaceAllUsesWith(N, Existing);
1151 
1152       // N is now dead. Inform the listeners and delete it.
1153       for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1154         DUL->NodeDeleted(N, Existing);
1155       DeleteNodeNotInCSEMaps(N);
1156       return;
1157     }
1158   }
1159 
1160   // If the node doesn't already exist, we updated it.  Inform listeners.
1161   for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1162     DUL->NodeUpdated(N);
1163 }
1164 
1165 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1166 /// were replaced with those specified.  If this node is never memoized,
1167 /// return null, otherwise return a pointer to the slot it would take.  If a
1168 /// node already exists with these operands, the slot will be non-null.
1169 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op,
1170                                            void *&InsertPos) {
1171   if (doNotCSE(N))
1172     return nullptr;
1173 
1174   SDValue Ops[] = { Op };
1175   FoldingSetNodeID ID;
1176   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1177   AddNodeIDCustom(ID, N);
1178   SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1179   if (Node)
1180     Node->intersectFlagsWith(N->getFlags());
1181   return Node;
1182 }
1183 
1184 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1185 /// were replaced with those specified.  If this node is never memoized,
1186 /// return null, otherwise return a pointer to the slot it would take.  If a
1187 /// node already exists with these operands, the slot will be non-null.
1188 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
1189                                            SDValue Op1, SDValue Op2,
1190                                            void *&InsertPos) {
1191   if (doNotCSE(N))
1192     return nullptr;
1193 
1194   SDValue Ops[] = { Op1, Op2 };
1195   FoldingSetNodeID ID;
1196   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1197   AddNodeIDCustom(ID, N);
1198   SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1199   if (Node)
1200     Node->intersectFlagsWith(N->getFlags());
1201   return Node;
1202 }
1203 
1204 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1205 /// were replaced with those specified.  If this node is never memoized,
1206 /// return null, otherwise return a pointer to the slot it would take.  If a
1207 /// node already exists with these operands, the slot will be non-null.
1208 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, ArrayRef<SDValue> Ops,
1209                                            void *&InsertPos) {
1210   if (doNotCSE(N))
1211     return nullptr;
1212 
1213   FoldingSetNodeID ID;
1214   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1215   AddNodeIDCustom(ID, N);
1216   SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1217   if (Node)
1218     Node->intersectFlagsWith(N->getFlags());
1219   return Node;
1220 }
1221 
1222 Align SelectionDAG::getEVTAlign(EVT VT) const {
1223   Type *Ty = VT == MVT::iPTR ?
1224                    PointerType::get(Type::getInt8Ty(*getContext()), 0) :
1225                    VT.getTypeForEVT(*getContext());
1226 
1227   return getDataLayout().getABITypeAlign(Ty);
1228 }
1229 
1230 // EntryNode could meaningfully have debug info if we can find it...
1231 SelectionDAG::SelectionDAG(const TargetMachine &tm, CodeGenOpt::Level OL)
1232     : TM(tm), OptLevel(OL),
1233       EntryNode(ISD::EntryToken, 0, DebugLoc(), getVTList(MVT::Other)),
1234       Root(getEntryNode()) {
1235   InsertNode(&EntryNode);
1236   DbgInfo = new SDDbgInfo();
1237 }
1238 
1239 void SelectionDAG::init(MachineFunction &NewMF,
1240                         OptimizationRemarkEmitter &NewORE,
1241                         Pass *PassPtr, const TargetLibraryInfo *LibraryInfo,
1242                         LegacyDivergenceAnalysis * Divergence,
1243                         ProfileSummaryInfo *PSIin,
1244                         BlockFrequencyInfo *BFIin) {
1245   MF = &NewMF;
1246   SDAGISelPass = PassPtr;
1247   ORE = &NewORE;
1248   TLI = getSubtarget().getTargetLowering();
1249   TSI = getSubtarget().getSelectionDAGInfo();
1250   LibInfo = LibraryInfo;
1251   Context = &MF->getFunction().getContext();
1252   DA = Divergence;
1253   PSI = PSIin;
1254   BFI = BFIin;
1255 }
1256 
1257 SelectionDAG::~SelectionDAG() {
1258   assert(!UpdateListeners && "Dangling registered DAGUpdateListeners");
1259   allnodes_clear();
1260   OperandRecycler.clear(OperandAllocator);
1261   delete DbgInfo;
1262 }
1263 
1264 bool SelectionDAG::shouldOptForSize() const {
1265   return MF->getFunction().hasOptSize() ||
1266       llvm::shouldOptimizeForSize(FLI->MBB->getBasicBlock(), PSI, BFI);
1267 }
1268 
1269 void SelectionDAG::allnodes_clear() {
1270   assert(&*AllNodes.begin() == &EntryNode);
1271   AllNodes.remove(AllNodes.begin());
1272   while (!AllNodes.empty())
1273     DeallocateNode(&AllNodes.front());
1274 #ifndef NDEBUG
1275   NextPersistentId = 0;
1276 #endif
1277 }
1278 
1279 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
1280                                           void *&InsertPos) {
1281   SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
1282   if (N) {
1283     switch (N->getOpcode()) {
1284     default: break;
1285     case ISD::Constant:
1286     case ISD::ConstantFP:
1287       llvm_unreachable("Querying for Constant and ConstantFP nodes requires "
1288                        "debug location.  Use another overload.");
1289     }
1290   }
1291   return N;
1292 }
1293 
1294 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
1295                                           const SDLoc &DL, void *&InsertPos) {
1296   SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
1297   if (N) {
1298     switch (N->getOpcode()) {
1299     case ISD::Constant:
1300     case ISD::ConstantFP:
1301       // Erase debug location from the node if the node is used at several
1302       // different places. Do not propagate one location to all uses as it
1303       // will cause a worse single stepping debugging experience.
1304       if (N->getDebugLoc() != DL.getDebugLoc())
1305         N->setDebugLoc(DebugLoc());
1306       break;
1307     default:
1308       // When the node's point of use is located earlier in the instruction
1309       // sequence than its prior point of use, update its debug info to the
1310       // earlier location.
1311       if (DL.getIROrder() && DL.getIROrder() < N->getIROrder())
1312         N->setDebugLoc(DL.getDebugLoc());
1313       break;
1314     }
1315   }
1316   return N;
1317 }
1318 
1319 void SelectionDAG::clear() {
1320   allnodes_clear();
1321   OperandRecycler.clear(OperandAllocator);
1322   OperandAllocator.Reset();
1323   CSEMap.clear();
1324 
1325   ExtendedValueTypeNodes.clear();
1326   ExternalSymbols.clear();
1327   TargetExternalSymbols.clear();
1328   MCSymbols.clear();
1329   SDCallSiteDbgInfo.clear();
1330   std::fill(CondCodeNodes.begin(), CondCodeNodes.end(),
1331             static_cast<CondCodeSDNode*>(nullptr));
1332   std::fill(ValueTypeNodes.begin(), ValueTypeNodes.end(),
1333             static_cast<SDNode*>(nullptr));
1334 
1335   EntryNode.UseList = nullptr;
1336   InsertNode(&EntryNode);
1337   Root = getEntryNode();
1338   DbgInfo->clear();
1339 }
1340 
1341 SDValue SelectionDAG::getFPExtendOrRound(SDValue Op, const SDLoc &DL, EVT VT) {
1342   return VT.bitsGT(Op.getValueType())
1343              ? getNode(ISD::FP_EXTEND, DL, VT, Op)
1344              : getNode(ISD::FP_ROUND, DL, VT, Op, getIntPtrConstant(0, DL));
1345 }
1346 
1347 std::pair<SDValue, SDValue>
1348 SelectionDAG::getStrictFPExtendOrRound(SDValue Op, SDValue Chain,
1349                                        const SDLoc &DL, EVT VT) {
1350   assert(!VT.bitsEq(Op.getValueType()) &&
1351          "Strict no-op FP extend/round not allowed.");
1352   SDValue Res =
1353       VT.bitsGT(Op.getValueType())
1354           ? getNode(ISD::STRICT_FP_EXTEND, DL, {VT, MVT::Other}, {Chain, Op})
1355           : getNode(ISD::STRICT_FP_ROUND, DL, {VT, MVT::Other},
1356                     {Chain, Op, getIntPtrConstant(0, DL)});
1357 
1358   return std::pair<SDValue, SDValue>(Res, SDValue(Res.getNode(), 1));
1359 }
1360 
1361 SDValue SelectionDAG::getAnyExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1362   return VT.bitsGT(Op.getValueType()) ?
1363     getNode(ISD::ANY_EXTEND, DL, VT, Op) :
1364     getNode(ISD::TRUNCATE, DL, VT, Op);
1365 }
1366 
1367 SDValue SelectionDAG::getSExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1368   return VT.bitsGT(Op.getValueType()) ?
1369     getNode(ISD::SIGN_EXTEND, DL, VT, Op) :
1370     getNode(ISD::TRUNCATE, DL, VT, Op);
1371 }
1372 
1373 SDValue SelectionDAG::getZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1374   return VT.bitsGT(Op.getValueType()) ?
1375     getNode(ISD::ZERO_EXTEND, DL, VT, Op) :
1376     getNode(ISD::TRUNCATE, DL, VT, Op);
1377 }
1378 
1379 SDValue SelectionDAG::getBoolExtOrTrunc(SDValue Op, const SDLoc &SL, EVT VT,
1380                                         EVT OpVT) {
1381   if (VT.bitsLE(Op.getValueType()))
1382     return getNode(ISD::TRUNCATE, SL, VT, Op);
1383 
1384   TargetLowering::BooleanContent BType = TLI->getBooleanContents(OpVT);
1385   return getNode(TLI->getExtendForContent(BType), SL, VT, Op);
1386 }
1387 
1388 SDValue SelectionDAG::getZeroExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) {
1389   EVT OpVT = Op.getValueType();
1390   assert(VT.isInteger() && OpVT.isInteger() &&
1391          "Cannot getZeroExtendInReg FP types");
1392   assert(VT.isVector() == OpVT.isVector() &&
1393          "getZeroExtendInReg type should be vector iff the operand "
1394          "type is vector!");
1395   assert((!VT.isVector() ||
1396           VT.getVectorElementCount() == OpVT.getVectorElementCount()) &&
1397          "Vector element counts must match in getZeroExtendInReg");
1398   assert(VT.bitsLE(OpVT) && "Not extending!");
1399   if (OpVT == VT)
1400     return Op;
1401   APInt Imm = APInt::getLowBitsSet(OpVT.getScalarSizeInBits(),
1402                                    VT.getScalarSizeInBits());
1403   return getNode(ISD::AND, DL, OpVT, Op, getConstant(Imm, DL, OpVT));
1404 }
1405 
1406 SDValue SelectionDAG::getPtrExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1407   // Only unsigned pointer semantics are supported right now. In the future this
1408   // might delegate to TLI to check pointer signedness.
1409   return getZExtOrTrunc(Op, DL, VT);
1410 }
1411 
1412 SDValue SelectionDAG::getPtrExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) {
1413   // Only unsigned pointer semantics are supported right now. In the future this
1414   // might delegate to TLI to check pointer signedness.
1415   return getZeroExtendInReg(Op, DL, VT);
1416 }
1417 
1418 /// getNOT - Create a bitwise NOT operation as (XOR Val, -1).
1419 SDValue SelectionDAG::getNOT(const SDLoc &DL, SDValue Val, EVT VT) {
1420   return getNode(ISD::XOR, DL, VT, Val, getAllOnesConstant(DL, VT));
1421 }
1422 
1423 SDValue SelectionDAG::getLogicalNOT(const SDLoc &DL, SDValue Val, EVT VT) {
1424   SDValue TrueValue = getBoolConstant(true, DL, VT, VT);
1425   return getNode(ISD::XOR, DL, VT, Val, TrueValue);
1426 }
1427 
1428 SDValue SelectionDAG::getVPLogicalNOT(const SDLoc &DL, SDValue Val,
1429                                       SDValue Mask, SDValue EVL, EVT VT) {
1430   SDValue TrueValue = getBoolConstant(true, DL, VT, VT);
1431   return getNode(ISD::VP_XOR, DL, VT, Val, TrueValue, Mask, EVL);
1432 }
1433 
1434 SDValue SelectionDAG::getBoolConstant(bool V, const SDLoc &DL, EVT VT,
1435                                       EVT OpVT) {
1436   if (!V)
1437     return getConstant(0, DL, VT);
1438 
1439   switch (TLI->getBooleanContents(OpVT)) {
1440   case TargetLowering::ZeroOrOneBooleanContent:
1441   case TargetLowering::UndefinedBooleanContent:
1442     return getConstant(1, DL, VT);
1443   case TargetLowering::ZeroOrNegativeOneBooleanContent:
1444     return getAllOnesConstant(DL, VT);
1445   }
1446   llvm_unreachable("Unexpected boolean content enum!");
1447 }
1448 
1449 SDValue SelectionDAG::getConstant(uint64_t Val, const SDLoc &DL, EVT VT,
1450                                   bool isT, bool isO) {
1451   EVT EltVT = VT.getScalarType();
1452   assert((EltVT.getSizeInBits() >= 64 ||
1453           (uint64_t)((int64_t)Val >> EltVT.getSizeInBits()) + 1 < 2) &&
1454          "getConstant with a uint64_t value that doesn't fit in the type!");
1455   return getConstant(APInt(EltVT.getSizeInBits(), Val), DL, VT, isT, isO);
1456 }
1457 
1458 SDValue SelectionDAG::getConstant(const APInt &Val, const SDLoc &DL, EVT VT,
1459                                   bool isT, bool isO) {
1460   return getConstant(*ConstantInt::get(*Context, Val), DL, VT, isT, isO);
1461 }
1462 
1463 SDValue SelectionDAG::getConstant(const ConstantInt &Val, const SDLoc &DL,
1464                                   EVT VT, bool isT, bool isO) {
1465   assert(VT.isInteger() && "Cannot create FP integer constant!");
1466 
1467   EVT EltVT = VT.getScalarType();
1468   const ConstantInt *Elt = &Val;
1469 
1470   // In some cases the vector type is legal but the element type is illegal and
1471   // needs to be promoted, for example v8i8 on ARM.  In this case, promote the
1472   // inserted value (the type does not need to match the vector element type).
1473   // Any extra bits introduced will be truncated away.
1474   if (VT.isVector() && TLI->getTypeAction(*getContext(), EltVT) ==
1475                            TargetLowering::TypePromoteInteger) {
1476     EltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1477     APInt NewVal = Elt->getValue().zextOrTrunc(EltVT.getSizeInBits());
1478     Elt = ConstantInt::get(*getContext(), NewVal);
1479   }
1480   // In other cases the element type is illegal and needs to be expanded, for
1481   // example v2i64 on MIPS32. In this case, find the nearest legal type, split
1482   // the value into n parts and use a vector type with n-times the elements.
1483   // Then bitcast to the type requested.
1484   // Legalizing constants too early makes the DAGCombiner's job harder so we
1485   // only legalize if the DAG tells us we must produce legal types.
1486   else if (NewNodesMustHaveLegalTypes && VT.isVector() &&
1487            TLI->getTypeAction(*getContext(), EltVT) ==
1488                TargetLowering::TypeExpandInteger) {
1489     const APInt &NewVal = Elt->getValue();
1490     EVT ViaEltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1491     unsigned ViaEltSizeInBits = ViaEltVT.getSizeInBits();
1492 
1493     // For scalable vectors, try to use a SPLAT_VECTOR_PARTS node.
1494     if (VT.isScalableVector()) {
1495       assert(EltVT.getSizeInBits() % ViaEltSizeInBits == 0 &&
1496              "Can only handle an even split!");
1497       unsigned Parts = EltVT.getSizeInBits() / ViaEltSizeInBits;
1498 
1499       SmallVector<SDValue, 2> ScalarParts;
1500       for (unsigned i = 0; i != Parts; ++i)
1501         ScalarParts.push_back(getConstant(
1502             NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL,
1503             ViaEltVT, isT, isO));
1504 
1505       return getNode(ISD::SPLAT_VECTOR_PARTS, DL, VT, ScalarParts);
1506     }
1507 
1508     unsigned ViaVecNumElts = VT.getSizeInBits() / ViaEltSizeInBits;
1509     EVT ViaVecVT = EVT::getVectorVT(*getContext(), ViaEltVT, ViaVecNumElts);
1510 
1511     // Check the temporary vector is the correct size. If this fails then
1512     // getTypeToTransformTo() probably returned a type whose size (in bits)
1513     // isn't a power-of-2 factor of the requested type size.
1514     assert(ViaVecVT.getSizeInBits() == VT.getSizeInBits());
1515 
1516     SmallVector<SDValue, 2> EltParts;
1517     for (unsigned i = 0; i < ViaVecNumElts / VT.getVectorNumElements(); ++i)
1518       EltParts.push_back(getConstant(
1519           NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL,
1520           ViaEltVT, isT, isO));
1521 
1522     // EltParts is currently in little endian order. If we actually want
1523     // big-endian order then reverse it now.
1524     if (getDataLayout().isBigEndian())
1525       std::reverse(EltParts.begin(), EltParts.end());
1526 
1527     // The elements must be reversed when the element order is different
1528     // to the endianness of the elements (because the BITCAST is itself a
1529     // vector shuffle in this situation). However, we do not need any code to
1530     // perform this reversal because getConstant() is producing a vector
1531     // splat.
1532     // This situation occurs in MIPS MSA.
1533 
1534     SmallVector<SDValue, 8> Ops;
1535     for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
1536       llvm::append_range(Ops, EltParts);
1537 
1538     SDValue V =
1539         getNode(ISD::BITCAST, DL, VT, getBuildVector(ViaVecVT, DL, Ops));
1540     return V;
1541   }
1542 
1543   assert(Elt->getBitWidth() == EltVT.getSizeInBits() &&
1544          "APInt size does not match type size!");
1545   unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
1546   FoldingSetNodeID ID;
1547   AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
1548   ID.AddPointer(Elt);
1549   ID.AddBoolean(isO);
1550   void *IP = nullptr;
1551   SDNode *N = nullptr;
1552   if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1553     if (!VT.isVector())
1554       return SDValue(N, 0);
1555 
1556   if (!N) {
1557     N = newSDNode<ConstantSDNode>(isT, isO, Elt, EltVT);
1558     CSEMap.InsertNode(N, IP);
1559     InsertNode(N);
1560     NewSDValueDbgMsg(SDValue(N, 0), "Creating constant: ", this);
1561   }
1562 
1563   SDValue Result(N, 0);
1564   if (VT.isScalableVector())
1565     Result = getSplatVector(VT, DL, Result);
1566   else if (VT.isVector())
1567     Result = getSplatBuildVector(VT, DL, Result);
1568 
1569   return Result;
1570 }
1571 
1572 SDValue SelectionDAG::getIntPtrConstant(uint64_t Val, const SDLoc &DL,
1573                                         bool isTarget) {
1574   return getConstant(Val, DL, TLI->getPointerTy(getDataLayout()), isTarget);
1575 }
1576 
1577 SDValue SelectionDAG::getShiftAmountConstant(uint64_t Val, EVT VT,
1578                                              const SDLoc &DL, bool LegalTypes) {
1579   assert(VT.isInteger() && "Shift amount is not an integer type!");
1580   EVT ShiftVT = TLI->getShiftAmountTy(VT, getDataLayout(), LegalTypes);
1581   return getConstant(Val, DL, ShiftVT);
1582 }
1583 
1584 SDValue SelectionDAG::getVectorIdxConstant(uint64_t Val, const SDLoc &DL,
1585                                            bool isTarget) {
1586   return getConstant(Val, DL, TLI->getVectorIdxTy(getDataLayout()), isTarget);
1587 }
1588 
1589 SDValue SelectionDAG::getConstantFP(const APFloat &V, const SDLoc &DL, EVT VT,
1590                                     bool isTarget) {
1591   return getConstantFP(*ConstantFP::get(*getContext(), V), DL, VT, isTarget);
1592 }
1593 
1594 SDValue SelectionDAG::getConstantFP(const ConstantFP &V, const SDLoc &DL,
1595                                     EVT VT, bool isTarget) {
1596   assert(VT.isFloatingPoint() && "Cannot create integer FP constant!");
1597 
1598   EVT EltVT = VT.getScalarType();
1599 
1600   // Do the map lookup using the actual bit pattern for the floating point
1601   // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
1602   // we don't have issues with SNANs.
1603   unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
1604   FoldingSetNodeID ID;
1605   AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
1606   ID.AddPointer(&V);
1607   void *IP = nullptr;
1608   SDNode *N = nullptr;
1609   if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1610     if (!VT.isVector())
1611       return SDValue(N, 0);
1612 
1613   if (!N) {
1614     N = newSDNode<ConstantFPSDNode>(isTarget, &V, EltVT);
1615     CSEMap.InsertNode(N, IP);
1616     InsertNode(N);
1617   }
1618 
1619   SDValue Result(N, 0);
1620   if (VT.isScalableVector())
1621     Result = getSplatVector(VT, DL, Result);
1622   else if (VT.isVector())
1623     Result = getSplatBuildVector(VT, DL, Result);
1624   NewSDValueDbgMsg(Result, "Creating fp constant: ", this);
1625   return Result;
1626 }
1627 
1628 SDValue SelectionDAG::getConstantFP(double Val, const SDLoc &DL, EVT VT,
1629                                     bool isTarget) {
1630   EVT EltVT = VT.getScalarType();
1631   if (EltVT == MVT::f32)
1632     return getConstantFP(APFloat((float)Val), DL, VT, isTarget);
1633   if (EltVT == MVT::f64)
1634     return getConstantFP(APFloat(Val), DL, VT, isTarget);
1635   if (EltVT == MVT::f80 || EltVT == MVT::f128 || EltVT == MVT::ppcf128 ||
1636       EltVT == MVT::f16 || EltVT == MVT::bf16) {
1637     bool Ignored;
1638     APFloat APF = APFloat(Val);
1639     APF.convert(EVTToAPFloatSemantics(EltVT), APFloat::rmNearestTiesToEven,
1640                 &Ignored);
1641     return getConstantFP(APF, DL, VT, isTarget);
1642   }
1643   llvm_unreachable("Unsupported type in getConstantFP");
1644 }
1645 
1646 SDValue SelectionDAG::getGlobalAddress(const GlobalValue *GV, const SDLoc &DL,
1647                                        EVT VT, int64_t Offset, bool isTargetGA,
1648                                        unsigned TargetFlags) {
1649   assert((TargetFlags == 0 || isTargetGA) &&
1650          "Cannot set target flags on target-independent globals");
1651 
1652   // Truncate (with sign-extension) the offset value to the pointer size.
1653   unsigned BitWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
1654   if (BitWidth < 64)
1655     Offset = SignExtend64(Offset, BitWidth);
1656 
1657   unsigned Opc;
1658   if (GV->isThreadLocal())
1659     Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress;
1660   else
1661     Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress;
1662 
1663   FoldingSetNodeID ID;
1664   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1665   ID.AddPointer(GV);
1666   ID.AddInteger(Offset);
1667   ID.AddInteger(TargetFlags);
1668   void *IP = nullptr;
1669   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
1670     return SDValue(E, 0);
1671 
1672   auto *N = newSDNode<GlobalAddressSDNode>(
1673       Opc, DL.getIROrder(), DL.getDebugLoc(), GV, VT, Offset, TargetFlags);
1674   CSEMap.InsertNode(N, IP);
1675     InsertNode(N);
1676   return SDValue(N, 0);
1677 }
1678 
1679 SDValue SelectionDAG::getFrameIndex(int FI, EVT VT, bool isTarget) {
1680   unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
1681   FoldingSetNodeID ID;
1682   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1683   ID.AddInteger(FI);
1684   void *IP = nullptr;
1685   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1686     return SDValue(E, 0);
1687 
1688   auto *N = newSDNode<FrameIndexSDNode>(FI, VT, isTarget);
1689   CSEMap.InsertNode(N, IP);
1690   InsertNode(N);
1691   return SDValue(N, 0);
1692 }
1693 
1694 SDValue SelectionDAG::getJumpTable(int JTI, EVT VT, bool isTarget,
1695                                    unsigned TargetFlags) {
1696   assert((TargetFlags == 0 || isTarget) &&
1697          "Cannot set target flags on target-independent jump tables");
1698   unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
1699   FoldingSetNodeID ID;
1700   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1701   ID.AddInteger(JTI);
1702   ID.AddInteger(TargetFlags);
1703   void *IP = nullptr;
1704   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1705     return SDValue(E, 0);
1706 
1707   auto *N = newSDNode<JumpTableSDNode>(JTI, VT, isTarget, TargetFlags);
1708   CSEMap.InsertNode(N, IP);
1709   InsertNode(N);
1710   return SDValue(N, 0);
1711 }
1712 
1713 SDValue SelectionDAG::getConstantPool(const Constant *C, EVT VT,
1714                                       MaybeAlign Alignment, int Offset,
1715                                       bool isTarget, unsigned TargetFlags) {
1716   assert((TargetFlags == 0 || isTarget) &&
1717          "Cannot set target flags on target-independent globals");
1718   if (!Alignment)
1719     Alignment = shouldOptForSize()
1720                     ? getDataLayout().getABITypeAlign(C->getType())
1721                     : getDataLayout().getPrefTypeAlign(C->getType());
1722   unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1723   FoldingSetNodeID ID;
1724   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1725   ID.AddInteger(Alignment->value());
1726   ID.AddInteger(Offset);
1727   ID.AddPointer(C);
1728   ID.AddInteger(TargetFlags);
1729   void *IP = nullptr;
1730   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1731     return SDValue(E, 0);
1732 
1733   auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment,
1734                                           TargetFlags);
1735   CSEMap.InsertNode(N, IP);
1736   InsertNode(N);
1737   SDValue V = SDValue(N, 0);
1738   NewSDValueDbgMsg(V, "Creating new constant pool: ", this);
1739   return V;
1740 }
1741 
1742 SDValue SelectionDAG::getConstantPool(MachineConstantPoolValue *C, EVT VT,
1743                                       MaybeAlign Alignment, int Offset,
1744                                       bool isTarget, unsigned TargetFlags) {
1745   assert((TargetFlags == 0 || isTarget) &&
1746          "Cannot set target flags on target-independent globals");
1747   if (!Alignment)
1748     Alignment = getDataLayout().getPrefTypeAlign(C->getType());
1749   unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1750   FoldingSetNodeID ID;
1751   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1752   ID.AddInteger(Alignment->value());
1753   ID.AddInteger(Offset);
1754   C->addSelectionDAGCSEId(ID);
1755   ID.AddInteger(TargetFlags);
1756   void *IP = nullptr;
1757   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1758     return SDValue(E, 0);
1759 
1760   auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment,
1761                                           TargetFlags);
1762   CSEMap.InsertNode(N, IP);
1763   InsertNode(N);
1764   return SDValue(N, 0);
1765 }
1766 
1767 SDValue SelectionDAG::getTargetIndex(int Index, EVT VT, int64_t Offset,
1768                                      unsigned TargetFlags) {
1769   FoldingSetNodeID ID;
1770   AddNodeIDNode(ID, ISD::TargetIndex, getVTList(VT), None);
1771   ID.AddInteger(Index);
1772   ID.AddInteger(Offset);
1773   ID.AddInteger(TargetFlags);
1774   void *IP = nullptr;
1775   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1776     return SDValue(E, 0);
1777 
1778   auto *N = newSDNode<TargetIndexSDNode>(Index, VT, Offset, TargetFlags);
1779   CSEMap.InsertNode(N, IP);
1780   InsertNode(N);
1781   return SDValue(N, 0);
1782 }
1783 
1784 SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
1785   FoldingSetNodeID ID;
1786   AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), None);
1787   ID.AddPointer(MBB);
1788   void *IP = nullptr;
1789   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1790     return SDValue(E, 0);
1791 
1792   auto *N = newSDNode<BasicBlockSDNode>(MBB);
1793   CSEMap.InsertNode(N, IP);
1794   InsertNode(N);
1795   return SDValue(N, 0);
1796 }
1797 
1798 SDValue SelectionDAG::getValueType(EVT VT) {
1799   if (VT.isSimple() && (unsigned)VT.getSimpleVT().SimpleTy >=
1800       ValueTypeNodes.size())
1801     ValueTypeNodes.resize(VT.getSimpleVT().SimpleTy+1);
1802 
1803   SDNode *&N = VT.isExtended() ?
1804     ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT().SimpleTy];
1805 
1806   if (N) return SDValue(N, 0);
1807   N = newSDNode<VTSDNode>(VT);
1808   InsertNode(N);
1809   return SDValue(N, 0);
1810 }
1811 
1812 SDValue SelectionDAG::getExternalSymbol(const char *Sym, EVT VT) {
1813   SDNode *&N = ExternalSymbols[Sym];
1814   if (N) return SDValue(N, 0);
1815   N = newSDNode<ExternalSymbolSDNode>(false, Sym, 0, VT);
1816   InsertNode(N);
1817   return SDValue(N, 0);
1818 }
1819 
1820 SDValue SelectionDAG::getMCSymbol(MCSymbol *Sym, EVT VT) {
1821   SDNode *&N = MCSymbols[Sym];
1822   if (N)
1823     return SDValue(N, 0);
1824   N = newSDNode<MCSymbolSDNode>(Sym, VT);
1825   InsertNode(N);
1826   return SDValue(N, 0);
1827 }
1828 
1829 SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, EVT VT,
1830                                               unsigned TargetFlags) {
1831   SDNode *&N =
1832       TargetExternalSymbols[std::pair<std::string, unsigned>(Sym, TargetFlags)];
1833   if (N) return SDValue(N, 0);
1834   N = newSDNode<ExternalSymbolSDNode>(true, Sym, TargetFlags, VT);
1835   InsertNode(N);
1836   return SDValue(N, 0);
1837 }
1838 
1839 SDValue SelectionDAG::getCondCode(ISD::CondCode Cond) {
1840   if ((unsigned)Cond >= CondCodeNodes.size())
1841     CondCodeNodes.resize(Cond+1);
1842 
1843   if (!CondCodeNodes[Cond]) {
1844     auto *N = newSDNode<CondCodeSDNode>(Cond);
1845     CondCodeNodes[Cond] = N;
1846     InsertNode(N);
1847   }
1848 
1849   return SDValue(CondCodeNodes[Cond], 0);
1850 }
1851 
1852 SDValue SelectionDAG::getStepVector(const SDLoc &DL, EVT ResVT) {
1853   APInt One(ResVT.getScalarSizeInBits(), 1);
1854   return getStepVector(DL, ResVT, One);
1855 }
1856 
1857 SDValue SelectionDAG::getStepVector(const SDLoc &DL, EVT ResVT, APInt StepVal) {
1858   assert(ResVT.getScalarSizeInBits() == StepVal.getBitWidth());
1859   if (ResVT.isScalableVector())
1860     return getNode(
1861         ISD::STEP_VECTOR, DL, ResVT,
1862         getTargetConstant(StepVal, DL, ResVT.getVectorElementType()));
1863 
1864   SmallVector<SDValue, 16> OpsStepConstants;
1865   for (uint64_t i = 0; i < ResVT.getVectorNumElements(); i++)
1866     OpsStepConstants.push_back(
1867         getConstant(StepVal * i, DL, ResVT.getVectorElementType()));
1868   return getBuildVector(ResVT, DL, OpsStepConstants);
1869 }
1870 
1871 /// Swaps the values of N1 and N2. Swaps all indices in the shuffle mask M that
1872 /// point at N1 to point at N2 and indices that point at N2 to point at N1.
1873 static void commuteShuffle(SDValue &N1, SDValue &N2, MutableArrayRef<int> M) {
1874   std::swap(N1, N2);
1875   ShuffleVectorSDNode::commuteMask(M);
1876 }
1877 
1878 SDValue SelectionDAG::getVectorShuffle(EVT VT, const SDLoc &dl, SDValue N1,
1879                                        SDValue N2, ArrayRef<int> Mask) {
1880   assert(VT.getVectorNumElements() == Mask.size() &&
1881          "Must have the same number of vector elements as mask elements!");
1882   assert(VT == N1.getValueType() && VT == N2.getValueType() &&
1883          "Invalid VECTOR_SHUFFLE");
1884 
1885   // Canonicalize shuffle undef, undef -> undef
1886   if (N1.isUndef() && N2.isUndef())
1887     return getUNDEF(VT);
1888 
1889   // Validate that all indices in Mask are within the range of the elements
1890   // input to the shuffle.
1891   int NElts = Mask.size();
1892   assert(llvm::all_of(Mask,
1893                       [&](int M) { return M < (NElts * 2) && M >= -1; }) &&
1894          "Index out of range");
1895 
1896   // Copy the mask so we can do any needed cleanup.
1897   SmallVector<int, 8> MaskVec(Mask.begin(), Mask.end());
1898 
1899   // Canonicalize shuffle v, v -> v, undef
1900   if (N1 == N2) {
1901     N2 = getUNDEF(VT);
1902     for (int i = 0; i != NElts; ++i)
1903       if (MaskVec[i] >= NElts) MaskVec[i] -= NElts;
1904   }
1905 
1906   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
1907   if (N1.isUndef())
1908     commuteShuffle(N1, N2, MaskVec);
1909 
1910   if (TLI->hasVectorBlend()) {
1911     // If shuffling a splat, try to blend the splat instead. We do this here so
1912     // that even when this arises during lowering we don't have to re-handle it.
1913     auto BlendSplat = [&](BuildVectorSDNode *BV, int Offset) {
1914       BitVector UndefElements;
1915       SDValue Splat = BV->getSplatValue(&UndefElements);
1916       if (!Splat)
1917         return;
1918 
1919       for (int i = 0; i < NElts; ++i) {
1920         if (MaskVec[i] < Offset || MaskVec[i] >= (Offset + NElts))
1921           continue;
1922 
1923         // If this input comes from undef, mark it as such.
1924         if (UndefElements[MaskVec[i] - Offset]) {
1925           MaskVec[i] = -1;
1926           continue;
1927         }
1928 
1929         // If we can blend a non-undef lane, use that instead.
1930         if (!UndefElements[i])
1931           MaskVec[i] = i + Offset;
1932       }
1933     };
1934     if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
1935       BlendSplat(N1BV, 0);
1936     if (auto *N2BV = dyn_cast<BuildVectorSDNode>(N2))
1937       BlendSplat(N2BV, NElts);
1938   }
1939 
1940   // Canonicalize all index into lhs, -> shuffle lhs, undef
1941   // Canonicalize all index into rhs, -> shuffle rhs, undef
1942   bool AllLHS = true, AllRHS = true;
1943   bool N2Undef = N2.isUndef();
1944   for (int i = 0; i != NElts; ++i) {
1945     if (MaskVec[i] >= NElts) {
1946       if (N2Undef)
1947         MaskVec[i] = -1;
1948       else
1949         AllLHS = false;
1950     } else if (MaskVec[i] >= 0) {
1951       AllRHS = false;
1952     }
1953   }
1954   if (AllLHS && AllRHS)
1955     return getUNDEF(VT);
1956   if (AllLHS && !N2Undef)
1957     N2 = getUNDEF(VT);
1958   if (AllRHS) {
1959     N1 = getUNDEF(VT);
1960     commuteShuffle(N1, N2, MaskVec);
1961   }
1962   // Reset our undef status after accounting for the mask.
1963   N2Undef = N2.isUndef();
1964   // Re-check whether both sides ended up undef.
1965   if (N1.isUndef() && N2Undef)
1966     return getUNDEF(VT);
1967 
1968   // If Identity shuffle return that node.
1969   bool Identity = true, AllSame = true;
1970   for (int i = 0; i != NElts; ++i) {
1971     if (MaskVec[i] >= 0 && MaskVec[i] != i) Identity = false;
1972     if (MaskVec[i] != MaskVec[0]) AllSame = false;
1973   }
1974   if (Identity && NElts)
1975     return N1;
1976 
1977   // Shuffling a constant splat doesn't change the result.
1978   if (N2Undef) {
1979     SDValue V = N1;
1980 
1981     // Look through any bitcasts. We check that these don't change the number
1982     // (and size) of elements and just changes their types.
1983     while (V.getOpcode() == ISD::BITCAST)
1984       V = V->getOperand(0);
1985 
1986     // A splat should always show up as a build vector node.
1987     if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) {
1988       BitVector UndefElements;
1989       SDValue Splat = BV->getSplatValue(&UndefElements);
1990       // If this is a splat of an undef, shuffling it is also undef.
1991       if (Splat && Splat.isUndef())
1992         return getUNDEF(VT);
1993 
1994       bool SameNumElts =
1995           V.getValueType().getVectorNumElements() == VT.getVectorNumElements();
1996 
1997       // We only have a splat which can skip shuffles if there is a splatted
1998       // value and no undef lanes rearranged by the shuffle.
1999       if (Splat && UndefElements.none()) {
2000         // Splat of <x, x, ..., x>, return <x, x, ..., x>, provided that the
2001         // number of elements match or the value splatted is a zero constant.
2002         if (SameNumElts)
2003           return N1;
2004         if (auto *C = dyn_cast<ConstantSDNode>(Splat))
2005           if (C->isZero())
2006             return N1;
2007       }
2008 
2009       // If the shuffle itself creates a splat, build the vector directly.
2010       if (AllSame && SameNumElts) {
2011         EVT BuildVT = BV->getValueType(0);
2012         const SDValue &Splatted = BV->getOperand(MaskVec[0]);
2013         SDValue NewBV = getSplatBuildVector(BuildVT, dl, Splatted);
2014 
2015         // We may have jumped through bitcasts, so the type of the
2016         // BUILD_VECTOR may not match the type of the shuffle.
2017         if (BuildVT != VT)
2018           NewBV = getNode(ISD::BITCAST, dl, VT, NewBV);
2019         return NewBV;
2020       }
2021     }
2022   }
2023 
2024   FoldingSetNodeID ID;
2025   SDValue Ops[2] = { N1, N2 };
2026   AddNodeIDNode(ID, ISD::VECTOR_SHUFFLE, getVTList(VT), Ops);
2027   for (int i = 0; i != NElts; ++i)
2028     ID.AddInteger(MaskVec[i]);
2029 
2030   void* IP = nullptr;
2031   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
2032     return SDValue(E, 0);
2033 
2034   // Allocate the mask array for the node out of the BumpPtrAllocator, since
2035   // SDNode doesn't have access to it.  This memory will be "leaked" when
2036   // the node is deallocated, but recovered when the NodeAllocator is released.
2037   int *MaskAlloc = OperandAllocator.Allocate<int>(NElts);
2038   llvm::copy(MaskVec, MaskAlloc);
2039 
2040   auto *N = newSDNode<ShuffleVectorSDNode>(VT, dl.getIROrder(),
2041                                            dl.getDebugLoc(), MaskAlloc);
2042   createOperands(N, Ops);
2043 
2044   CSEMap.InsertNode(N, IP);
2045   InsertNode(N);
2046   SDValue V = SDValue(N, 0);
2047   NewSDValueDbgMsg(V, "Creating new node: ", this);
2048   return V;
2049 }
2050 
2051 SDValue SelectionDAG::getCommutedVectorShuffle(const ShuffleVectorSDNode &SV) {
2052   EVT VT = SV.getValueType(0);
2053   SmallVector<int, 8> MaskVec(SV.getMask().begin(), SV.getMask().end());
2054   ShuffleVectorSDNode::commuteMask(MaskVec);
2055 
2056   SDValue Op0 = SV.getOperand(0);
2057   SDValue Op1 = SV.getOperand(1);
2058   return getVectorShuffle(VT, SDLoc(&SV), Op1, Op0, MaskVec);
2059 }
2060 
2061 SDValue SelectionDAG::getRegister(unsigned RegNo, EVT VT) {
2062   FoldingSetNodeID ID;
2063   AddNodeIDNode(ID, ISD::Register, getVTList(VT), None);
2064   ID.AddInteger(RegNo);
2065   void *IP = nullptr;
2066   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2067     return SDValue(E, 0);
2068 
2069   auto *N = newSDNode<RegisterSDNode>(RegNo, VT);
2070   N->SDNodeBits.IsDivergent = TLI->isSDNodeSourceOfDivergence(N, FLI, DA);
2071   CSEMap.InsertNode(N, IP);
2072   InsertNode(N);
2073   return SDValue(N, 0);
2074 }
2075 
2076 SDValue SelectionDAG::getRegisterMask(const uint32_t *RegMask) {
2077   FoldingSetNodeID ID;
2078   AddNodeIDNode(ID, ISD::RegisterMask, getVTList(MVT::Untyped), None);
2079   ID.AddPointer(RegMask);
2080   void *IP = nullptr;
2081   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2082     return SDValue(E, 0);
2083 
2084   auto *N = newSDNode<RegisterMaskSDNode>(RegMask);
2085   CSEMap.InsertNode(N, IP);
2086   InsertNode(N);
2087   return SDValue(N, 0);
2088 }
2089 
2090 SDValue SelectionDAG::getEHLabel(const SDLoc &dl, SDValue Root,
2091                                  MCSymbol *Label) {
2092   return getLabelNode(ISD::EH_LABEL, dl, Root, Label);
2093 }
2094 
2095 SDValue SelectionDAG::getLabelNode(unsigned Opcode, const SDLoc &dl,
2096                                    SDValue Root, MCSymbol *Label) {
2097   FoldingSetNodeID ID;
2098   SDValue Ops[] = { Root };
2099   AddNodeIDNode(ID, Opcode, getVTList(MVT::Other), Ops);
2100   ID.AddPointer(Label);
2101   void *IP = nullptr;
2102   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2103     return SDValue(E, 0);
2104 
2105   auto *N =
2106       newSDNode<LabelSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), Label);
2107   createOperands(N, Ops);
2108 
2109   CSEMap.InsertNode(N, IP);
2110   InsertNode(N);
2111   return SDValue(N, 0);
2112 }
2113 
2114 SDValue SelectionDAG::getBlockAddress(const BlockAddress *BA, EVT VT,
2115                                       int64_t Offset, bool isTarget,
2116                                       unsigned TargetFlags) {
2117   unsigned Opc = isTarget ? ISD::TargetBlockAddress : ISD::BlockAddress;
2118 
2119   FoldingSetNodeID ID;
2120   AddNodeIDNode(ID, Opc, getVTList(VT), None);
2121   ID.AddPointer(BA);
2122   ID.AddInteger(Offset);
2123   ID.AddInteger(TargetFlags);
2124   void *IP = nullptr;
2125   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2126     return SDValue(E, 0);
2127 
2128   auto *N = newSDNode<BlockAddressSDNode>(Opc, VT, BA, Offset, TargetFlags);
2129   CSEMap.InsertNode(N, IP);
2130   InsertNode(N);
2131   return SDValue(N, 0);
2132 }
2133 
2134 SDValue SelectionDAG::getSrcValue(const Value *V) {
2135   FoldingSetNodeID ID;
2136   AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), None);
2137   ID.AddPointer(V);
2138 
2139   void *IP = nullptr;
2140   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2141     return SDValue(E, 0);
2142 
2143   auto *N = newSDNode<SrcValueSDNode>(V);
2144   CSEMap.InsertNode(N, IP);
2145   InsertNode(N);
2146   return SDValue(N, 0);
2147 }
2148 
2149 SDValue SelectionDAG::getMDNode(const MDNode *MD) {
2150   FoldingSetNodeID ID;
2151   AddNodeIDNode(ID, ISD::MDNODE_SDNODE, getVTList(MVT::Other), None);
2152   ID.AddPointer(MD);
2153 
2154   void *IP = nullptr;
2155   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2156     return SDValue(E, 0);
2157 
2158   auto *N = newSDNode<MDNodeSDNode>(MD);
2159   CSEMap.InsertNode(N, IP);
2160   InsertNode(N);
2161   return SDValue(N, 0);
2162 }
2163 
2164 SDValue SelectionDAG::getBitcast(EVT VT, SDValue V) {
2165   if (VT == V.getValueType())
2166     return V;
2167 
2168   return getNode(ISD::BITCAST, SDLoc(V), VT, V);
2169 }
2170 
2171 SDValue SelectionDAG::getAddrSpaceCast(const SDLoc &dl, EVT VT, SDValue Ptr,
2172                                        unsigned SrcAS, unsigned DestAS) {
2173   SDValue Ops[] = {Ptr};
2174   FoldingSetNodeID ID;
2175   AddNodeIDNode(ID, ISD::ADDRSPACECAST, getVTList(VT), Ops);
2176   ID.AddInteger(SrcAS);
2177   ID.AddInteger(DestAS);
2178 
2179   void *IP = nullptr;
2180   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
2181     return SDValue(E, 0);
2182 
2183   auto *N = newSDNode<AddrSpaceCastSDNode>(dl.getIROrder(), dl.getDebugLoc(),
2184                                            VT, SrcAS, DestAS);
2185   createOperands(N, Ops);
2186 
2187   CSEMap.InsertNode(N, IP);
2188   InsertNode(N);
2189   return SDValue(N, 0);
2190 }
2191 
2192 SDValue SelectionDAG::getFreeze(SDValue V) {
2193   return getNode(ISD::FREEZE, SDLoc(V), V.getValueType(), V);
2194 }
2195 
2196 /// getShiftAmountOperand - Return the specified value casted to
2197 /// the target's desired shift amount type.
2198 SDValue SelectionDAG::getShiftAmountOperand(EVT LHSTy, SDValue Op) {
2199   EVT OpTy = Op.getValueType();
2200   EVT ShTy = TLI->getShiftAmountTy(LHSTy, getDataLayout());
2201   if (OpTy == ShTy || OpTy.isVector()) return Op;
2202 
2203   return getZExtOrTrunc(Op, SDLoc(Op), ShTy);
2204 }
2205 
2206 SDValue SelectionDAG::expandVAArg(SDNode *Node) {
2207   SDLoc dl(Node);
2208   const TargetLowering &TLI = getTargetLoweringInfo();
2209   const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2210   EVT VT = Node->getValueType(0);
2211   SDValue Tmp1 = Node->getOperand(0);
2212   SDValue Tmp2 = Node->getOperand(1);
2213   const MaybeAlign MA(Node->getConstantOperandVal(3));
2214 
2215   SDValue VAListLoad = getLoad(TLI.getPointerTy(getDataLayout()), dl, Tmp1,
2216                                Tmp2, MachinePointerInfo(V));
2217   SDValue VAList = VAListLoad;
2218 
2219   if (MA && *MA > TLI.getMinStackArgumentAlignment()) {
2220     VAList = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
2221                      getConstant(MA->value() - 1, dl, VAList.getValueType()));
2222 
2223     VAList =
2224         getNode(ISD::AND, dl, VAList.getValueType(), VAList,
2225                 getConstant(-(int64_t)MA->value(), dl, VAList.getValueType()));
2226   }
2227 
2228   // Increment the pointer, VAList, to the next vaarg
2229   Tmp1 = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
2230                  getConstant(getDataLayout().getTypeAllocSize(
2231                                                VT.getTypeForEVT(*getContext())),
2232                              dl, VAList.getValueType()));
2233   // Store the incremented VAList to the legalized pointer
2234   Tmp1 =
2235       getStore(VAListLoad.getValue(1), dl, Tmp1, Tmp2, MachinePointerInfo(V));
2236   // Load the actual argument out of the pointer VAList
2237   return getLoad(VT, dl, Tmp1, VAList, MachinePointerInfo());
2238 }
2239 
2240 SDValue SelectionDAG::expandVACopy(SDNode *Node) {
2241   SDLoc dl(Node);
2242   const TargetLowering &TLI = getTargetLoweringInfo();
2243   // This defaults to loading a pointer from the input and storing it to the
2244   // output, returning the chain.
2245   const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue();
2246   const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue();
2247   SDValue Tmp1 =
2248       getLoad(TLI.getPointerTy(getDataLayout()), dl, Node->getOperand(0),
2249               Node->getOperand(2), MachinePointerInfo(VS));
2250   return getStore(Tmp1.getValue(1), dl, Tmp1, Node->getOperand(1),
2251                   MachinePointerInfo(VD));
2252 }
2253 
2254 Align SelectionDAG::getReducedAlign(EVT VT, bool UseABI) {
2255   const DataLayout &DL = getDataLayout();
2256   Type *Ty = VT.getTypeForEVT(*getContext());
2257   Align RedAlign = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty);
2258 
2259   if (TLI->isTypeLegal(VT) || !VT.isVector())
2260     return RedAlign;
2261 
2262   const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
2263   const Align StackAlign = TFI->getStackAlign();
2264 
2265   // See if we can choose a smaller ABI alignment in cases where it's an
2266   // illegal vector type that will get broken down.
2267   if (RedAlign > StackAlign) {
2268     EVT IntermediateVT;
2269     MVT RegisterVT;
2270     unsigned NumIntermediates;
2271     TLI->getVectorTypeBreakdown(*getContext(), VT, IntermediateVT,
2272                                 NumIntermediates, RegisterVT);
2273     Ty = IntermediateVT.getTypeForEVT(*getContext());
2274     Align RedAlign2 = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty);
2275     if (RedAlign2 < RedAlign)
2276       RedAlign = RedAlign2;
2277   }
2278 
2279   return RedAlign;
2280 }
2281 
2282 SDValue SelectionDAG::CreateStackTemporary(TypeSize Bytes, Align Alignment) {
2283   MachineFrameInfo &MFI = MF->getFrameInfo();
2284   const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
2285   int StackID = 0;
2286   if (Bytes.isScalable())
2287     StackID = TFI->getStackIDForScalableVectors();
2288   // The stack id gives an indication of whether the object is scalable or
2289   // not, so it's safe to pass in the minimum size here.
2290   int FrameIdx = MFI.CreateStackObject(Bytes.getKnownMinSize(), Alignment,
2291                                        false, nullptr, StackID);
2292   return getFrameIndex(FrameIdx, TLI->getFrameIndexTy(getDataLayout()));
2293 }
2294 
2295 SDValue SelectionDAG::CreateStackTemporary(EVT VT, unsigned minAlign) {
2296   Type *Ty = VT.getTypeForEVT(*getContext());
2297   Align StackAlign =
2298       std::max(getDataLayout().getPrefTypeAlign(Ty), Align(minAlign));
2299   return CreateStackTemporary(VT.getStoreSize(), StackAlign);
2300 }
2301 
2302 SDValue SelectionDAG::CreateStackTemporary(EVT VT1, EVT VT2) {
2303   TypeSize VT1Size = VT1.getStoreSize();
2304   TypeSize VT2Size = VT2.getStoreSize();
2305   assert(VT1Size.isScalable() == VT2Size.isScalable() &&
2306          "Don't know how to choose the maximum size when creating a stack "
2307          "temporary");
2308   TypeSize Bytes =
2309       VT1Size.getKnownMinSize() > VT2Size.getKnownMinSize() ? VT1Size : VT2Size;
2310 
2311   Type *Ty1 = VT1.getTypeForEVT(*getContext());
2312   Type *Ty2 = VT2.getTypeForEVT(*getContext());
2313   const DataLayout &DL = getDataLayout();
2314   Align Align = std::max(DL.getPrefTypeAlign(Ty1), DL.getPrefTypeAlign(Ty2));
2315   return CreateStackTemporary(Bytes, Align);
2316 }
2317 
2318 SDValue SelectionDAG::FoldSetCC(EVT VT, SDValue N1, SDValue N2,
2319                                 ISD::CondCode Cond, const SDLoc &dl) {
2320   EVT OpVT = N1.getValueType();
2321 
2322   // These setcc operations always fold.
2323   switch (Cond) {
2324   default: break;
2325   case ISD::SETFALSE:
2326   case ISD::SETFALSE2: return getBoolConstant(false, dl, VT, OpVT);
2327   case ISD::SETTRUE:
2328   case ISD::SETTRUE2: return getBoolConstant(true, dl, VT, OpVT);
2329 
2330   case ISD::SETOEQ:
2331   case ISD::SETOGT:
2332   case ISD::SETOGE:
2333   case ISD::SETOLT:
2334   case ISD::SETOLE:
2335   case ISD::SETONE:
2336   case ISD::SETO:
2337   case ISD::SETUO:
2338   case ISD::SETUEQ:
2339   case ISD::SETUNE:
2340     assert(!OpVT.isInteger() && "Illegal setcc for integer!");
2341     break;
2342   }
2343 
2344   if (OpVT.isInteger()) {
2345     // For EQ and NE, we can always pick a value for the undef to make the
2346     // predicate pass or fail, so we can return undef.
2347     // Matches behavior in llvm::ConstantFoldCompareInstruction.
2348     // icmp eq/ne X, undef -> undef.
2349     if ((N1.isUndef() || N2.isUndef()) &&
2350         (Cond == ISD::SETEQ || Cond == ISD::SETNE))
2351       return getUNDEF(VT);
2352 
2353     // If both operands are undef, we can return undef for int comparison.
2354     // icmp undef, undef -> undef.
2355     if (N1.isUndef() && N2.isUndef())
2356       return getUNDEF(VT);
2357 
2358     // icmp X, X -> true/false
2359     // icmp X, undef -> true/false because undef could be X.
2360     if (N1 == N2)
2361       return getBoolConstant(ISD::isTrueWhenEqual(Cond), dl, VT, OpVT);
2362   }
2363 
2364   if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2)) {
2365     const APInt &C2 = N2C->getAPIntValue();
2366     if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1)) {
2367       const APInt &C1 = N1C->getAPIntValue();
2368 
2369       return getBoolConstant(ICmpInst::compare(C1, C2, getICmpCondCode(Cond)),
2370                              dl, VT, OpVT);
2371     }
2372   }
2373 
2374   auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
2375   auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
2376 
2377   if (N1CFP && N2CFP) {
2378     APFloat::cmpResult R = N1CFP->getValueAPF().compare(N2CFP->getValueAPF());
2379     switch (Cond) {
2380     default: break;
2381     case ISD::SETEQ:  if (R==APFloat::cmpUnordered)
2382                         return getUNDEF(VT);
2383                       LLVM_FALLTHROUGH;
2384     case ISD::SETOEQ: return getBoolConstant(R==APFloat::cmpEqual, dl, VT,
2385                                              OpVT);
2386     case ISD::SETNE:  if (R==APFloat::cmpUnordered)
2387                         return getUNDEF(VT);
2388                       LLVM_FALLTHROUGH;
2389     case ISD::SETONE: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2390                                              R==APFloat::cmpLessThan, dl, VT,
2391                                              OpVT);
2392     case ISD::SETLT:  if (R==APFloat::cmpUnordered)
2393                         return getUNDEF(VT);
2394                       LLVM_FALLTHROUGH;
2395     case ISD::SETOLT: return getBoolConstant(R==APFloat::cmpLessThan, dl, VT,
2396                                              OpVT);
2397     case ISD::SETGT:  if (R==APFloat::cmpUnordered)
2398                         return getUNDEF(VT);
2399                       LLVM_FALLTHROUGH;
2400     case ISD::SETOGT: return getBoolConstant(R==APFloat::cmpGreaterThan, dl,
2401                                              VT, OpVT);
2402     case ISD::SETLE:  if (R==APFloat::cmpUnordered)
2403                         return getUNDEF(VT);
2404                       LLVM_FALLTHROUGH;
2405     case ISD::SETOLE: return getBoolConstant(R==APFloat::cmpLessThan ||
2406                                              R==APFloat::cmpEqual, dl, VT,
2407                                              OpVT);
2408     case ISD::SETGE:  if (R==APFloat::cmpUnordered)
2409                         return getUNDEF(VT);
2410                       LLVM_FALLTHROUGH;
2411     case ISD::SETOGE: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2412                                          R==APFloat::cmpEqual, dl, VT, OpVT);
2413     case ISD::SETO:   return getBoolConstant(R!=APFloat::cmpUnordered, dl, VT,
2414                                              OpVT);
2415     case ISD::SETUO:  return getBoolConstant(R==APFloat::cmpUnordered, dl, VT,
2416                                              OpVT);
2417     case ISD::SETUEQ: return getBoolConstant(R==APFloat::cmpUnordered ||
2418                                              R==APFloat::cmpEqual, dl, VT,
2419                                              OpVT);
2420     case ISD::SETUNE: return getBoolConstant(R!=APFloat::cmpEqual, dl, VT,
2421                                              OpVT);
2422     case ISD::SETULT: return getBoolConstant(R==APFloat::cmpUnordered ||
2423                                              R==APFloat::cmpLessThan, dl, VT,
2424                                              OpVT);
2425     case ISD::SETUGT: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2426                                              R==APFloat::cmpUnordered, dl, VT,
2427                                              OpVT);
2428     case ISD::SETULE: return getBoolConstant(R!=APFloat::cmpGreaterThan, dl,
2429                                              VT, OpVT);
2430     case ISD::SETUGE: return getBoolConstant(R!=APFloat::cmpLessThan, dl, VT,
2431                                              OpVT);
2432     }
2433   } else if (N1CFP && OpVT.isSimple() && !N2.isUndef()) {
2434     // Ensure that the constant occurs on the RHS.
2435     ISD::CondCode SwappedCond = ISD::getSetCCSwappedOperands(Cond);
2436     if (!TLI->isCondCodeLegal(SwappedCond, OpVT.getSimpleVT()))
2437       return SDValue();
2438     return getSetCC(dl, VT, N2, N1, SwappedCond);
2439   } else if ((N2CFP && N2CFP->getValueAPF().isNaN()) ||
2440              (OpVT.isFloatingPoint() && (N1.isUndef() || N2.isUndef()))) {
2441     // If an operand is known to be a nan (or undef that could be a nan), we can
2442     // fold it.
2443     // Choosing NaN for the undef will always make unordered comparison succeed
2444     // and ordered comparison fails.
2445     // Matches behavior in llvm::ConstantFoldCompareInstruction.
2446     switch (ISD::getUnorderedFlavor(Cond)) {
2447     default:
2448       llvm_unreachable("Unknown flavor!");
2449     case 0: // Known false.
2450       return getBoolConstant(false, dl, VT, OpVT);
2451     case 1: // Known true.
2452       return getBoolConstant(true, dl, VT, OpVT);
2453     case 2: // Undefined.
2454       return getUNDEF(VT);
2455     }
2456   }
2457 
2458   // Could not fold it.
2459   return SDValue();
2460 }
2461 
2462 /// See if the specified operand can be simplified with the knowledge that only
2463 /// the bits specified by DemandedBits are used.
2464 /// TODO: really we should be making this into the DAG equivalent of
2465 /// SimplifyMultipleUseDemandedBits and not generate any new nodes.
2466 SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &DemandedBits) {
2467   EVT VT = V.getValueType();
2468 
2469   if (VT.isScalableVector())
2470     return SDValue();
2471 
2472   switch (V.getOpcode()) {
2473   default:
2474     return TLI->SimplifyMultipleUseDemandedBits(V, DemandedBits, *this);
2475   case ISD::Constant: {
2476     const APInt &CVal = cast<ConstantSDNode>(V)->getAPIntValue();
2477     APInt NewVal = CVal & DemandedBits;
2478     if (NewVal != CVal)
2479       return getConstant(NewVal, SDLoc(V), V.getValueType());
2480     break;
2481   }
2482   case ISD::SRL:
2483     // Only look at single-use SRLs.
2484     if (!V.getNode()->hasOneUse())
2485       break;
2486     if (auto *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
2487       // See if we can recursively simplify the LHS.
2488       unsigned Amt = RHSC->getZExtValue();
2489 
2490       // Watch out for shift count overflow though.
2491       if (Amt >= DemandedBits.getBitWidth())
2492         break;
2493       APInt SrcDemandedBits = DemandedBits << Amt;
2494       if (SDValue SimplifyLHS = TLI->SimplifyMultipleUseDemandedBits(
2495               V.getOperand(0), SrcDemandedBits, *this))
2496         return getNode(ISD::SRL, SDLoc(V), V.getValueType(), SimplifyLHS,
2497                        V.getOperand(1));
2498     }
2499     break;
2500   }
2501   return SDValue();
2502 }
2503 
2504 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero.  We
2505 /// use this predicate to simplify operations downstream.
2506 bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const {
2507   unsigned BitWidth = Op.getScalarValueSizeInBits();
2508   return MaskedValueIsZero(Op, APInt::getSignMask(BitWidth), Depth);
2509 }
2510 
2511 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero.  We use
2512 /// this predicate to simplify operations downstream.  Mask is known to be zero
2513 /// for bits that V cannot have.
2514 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask,
2515                                      unsigned Depth) const {
2516   return Mask.isSubsetOf(computeKnownBits(V, Depth).Zero);
2517 }
2518 
2519 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero in
2520 /// DemandedElts.  We use this predicate to simplify operations downstream.
2521 /// Mask is known to be zero for bits that V cannot have.
2522 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask,
2523                                      const APInt &DemandedElts,
2524                                      unsigned Depth) const {
2525   return Mask.isSubsetOf(computeKnownBits(V, DemandedElts, Depth).Zero);
2526 }
2527 
2528 /// MaskedVectorIsZero - Return true if 'Op' is known to be zero in
2529 /// DemandedElts.  We use this predicate to simplify operations downstream.
2530 bool SelectionDAG::MaskedVectorIsZero(SDValue V, const APInt &DemandedElts,
2531                                       unsigned Depth /* = 0 */) const {
2532   APInt Mask = APInt::getAllOnes(V.getScalarValueSizeInBits());
2533   return Mask.isSubsetOf(computeKnownBits(V, DemandedElts, Depth).Zero);
2534 }
2535 
2536 /// MaskedValueIsAllOnes - Return true if '(Op & Mask) == Mask'.
2537 bool SelectionDAG::MaskedValueIsAllOnes(SDValue V, const APInt &Mask,
2538                                         unsigned Depth) const {
2539   return Mask.isSubsetOf(computeKnownBits(V, Depth).One);
2540 }
2541 
2542 /// isSplatValue - Return true if the vector V has the same value
2543 /// across all DemandedElts. For scalable vectors it does not make
2544 /// sense to specify which elements are demanded or undefined, therefore
2545 /// they are simply ignored.
2546 bool SelectionDAG::isSplatValue(SDValue V, const APInt &DemandedElts,
2547                                 APInt &UndefElts, unsigned Depth) const {
2548   unsigned Opcode = V.getOpcode();
2549   EVT VT = V.getValueType();
2550   assert(VT.isVector() && "Vector type expected");
2551 
2552   if (!VT.isScalableVector() && !DemandedElts)
2553     return false; // No demanded elts, better to assume we don't know anything.
2554 
2555   if (Depth >= MaxRecursionDepth)
2556     return false; // Limit search depth.
2557 
2558   // Deal with some common cases here that work for both fixed and scalable
2559   // vector types.
2560   switch (Opcode) {
2561   case ISD::SPLAT_VECTOR:
2562     UndefElts = V.getOperand(0).isUndef()
2563                     ? APInt::getAllOnes(DemandedElts.getBitWidth())
2564                     : APInt(DemandedElts.getBitWidth(), 0);
2565     return true;
2566   case ISD::ADD:
2567   case ISD::SUB:
2568   case ISD::AND:
2569   case ISD::XOR:
2570   case ISD::OR: {
2571     APInt UndefLHS, UndefRHS;
2572     SDValue LHS = V.getOperand(0);
2573     SDValue RHS = V.getOperand(1);
2574     if (isSplatValue(LHS, DemandedElts, UndefLHS, Depth + 1) &&
2575         isSplatValue(RHS, DemandedElts, UndefRHS, Depth + 1)) {
2576       UndefElts = UndefLHS | UndefRHS;
2577       return true;
2578     }
2579     return false;
2580   }
2581   case ISD::ABS:
2582   case ISD::TRUNCATE:
2583   case ISD::SIGN_EXTEND:
2584   case ISD::ZERO_EXTEND:
2585     return isSplatValue(V.getOperand(0), DemandedElts, UndefElts, Depth + 1);
2586   default:
2587     if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
2588         Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID)
2589       return TLI->isSplatValueForTargetNode(V, DemandedElts, UndefElts, Depth);
2590     break;
2591 }
2592 
2593   // We don't support other cases than those above for scalable vectors at
2594   // the moment.
2595   if (VT.isScalableVector())
2596     return false;
2597 
2598   unsigned NumElts = VT.getVectorNumElements();
2599   assert(NumElts == DemandedElts.getBitWidth() && "Vector size mismatch");
2600   UndefElts = APInt::getZero(NumElts);
2601 
2602   switch (Opcode) {
2603   case ISD::BUILD_VECTOR: {
2604     SDValue Scl;
2605     for (unsigned i = 0; i != NumElts; ++i) {
2606       SDValue Op = V.getOperand(i);
2607       if (Op.isUndef()) {
2608         UndefElts.setBit(i);
2609         continue;
2610       }
2611       if (!DemandedElts[i])
2612         continue;
2613       if (Scl && Scl != Op)
2614         return false;
2615       Scl = Op;
2616     }
2617     return true;
2618   }
2619   case ISD::VECTOR_SHUFFLE: {
2620     // Check if this is a shuffle node doing a splat or a shuffle of a splat.
2621     APInt DemandedLHS = APInt::getNullValue(NumElts);
2622     APInt DemandedRHS = APInt::getNullValue(NumElts);
2623     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(V)->getMask();
2624     for (int i = 0; i != (int)NumElts; ++i) {
2625       int M = Mask[i];
2626       if (M < 0) {
2627         UndefElts.setBit(i);
2628         continue;
2629       }
2630       if (!DemandedElts[i])
2631         continue;
2632       if (M < (int)NumElts)
2633         DemandedLHS.setBit(M);
2634       else
2635         DemandedRHS.setBit(M - NumElts);
2636     }
2637 
2638     // If we aren't demanding either op, assume there's no splat.
2639     // If we are demanding both ops, assume there's no splat.
2640     if ((DemandedLHS.isZero() && DemandedRHS.isZero()) ||
2641         (!DemandedLHS.isZero() && !DemandedRHS.isZero()))
2642       return false;
2643 
2644     // See if the demanded elts of the source op is a splat or we only demand
2645     // one element, which should always be a splat.
2646     // TODO: Handle source ops splats with undefs.
2647     auto CheckSplatSrc = [&](SDValue Src, const APInt &SrcElts) {
2648       APInt SrcUndefs;
2649       return (SrcElts.countPopulation() == 1) ||
2650              (isSplatValue(Src, SrcElts, SrcUndefs, Depth + 1) &&
2651               (SrcElts & SrcUndefs).isZero());
2652     };
2653     if (!DemandedLHS.isZero())
2654       return CheckSplatSrc(V.getOperand(0), DemandedLHS);
2655     return CheckSplatSrc(V.getOperand(1), DemandedRHS);
2656   }
2657   case ISD::EXTRACT_SUBVECTOR: {
2658     // Offset the demanded elts by the subvector index.
2659     SDValue Src = V.getOperand(0);
2660     // We don't support scalable vectors at the moment.
2661     if (Src.getValueType().isScalableVector())
2662       return false;
2663     uint64_t Idx = V.getConstantOperandVal(1);
2664     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2665     APInt UndefSrcElts;
2666     APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
2667     if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) {
2668       UndefElts = UndefSrcElts.extractBits(NumElts, Idx);
2669       return true;
2670     }
2671     break;
2672   }
2673   case ISD::ANY_EXTEND_VECTOR_INREG:
2674   case ISD::SIGN_EXTEND_VECTOR_INREG:
2675   case ISD::ZERO_EXTEND_VECTOR_INREG: {
2676     // Widen the demanded elts by the src element count.
2677     SDValue Src = V.getOperand(0);
2678     // We don't support scalable vectors at the moment.
2679     if (Src.getValueType().isScalableVector())
2680       return false;
2681     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2682     APInt UndefSrcElts;
2683     APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts);
2684     if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) {
2685       UndefElts = UndefSrcElts.trunc(NumElts);
2686       return true;
2687     }
2688     break;
2689   }
2690   case ISD::BITCAST: {
2691     SDValue Src = V.getOperand(0);
2692     EVT SrcVT = Src.getValueType();
2693     unsigned SrcBitWidth = SrcVT.getScalarSizeInBits();
2694     unsigned BitWidth = VT.getScalarSizeInBits();
2695 
2696     // Ignore bitcasts from unsupported types.
2697     // TODO: Add fp support?
2698     if (!SrcVT.isVector() || !SrcVT.isInteger() || !VT.isInteger())
2699       break;
2700 
2701     // Bitcast 'small element' vector to 'large element' vector.
2702     if ((BitWidth % SrcBitWidth) == 0) {
2703       // See if each sub element is a splat.
2704       unsigned Scale = BitWidth / SrcBitWidth;
2705       unsigned NumSrcElts = SrcVT.getVectorNumElements();
2706       APInt ScaledDemandedElts =
2707           APIntOps::ScaleBitMask(DemandedElts, NumSrcElts);
2708       for (unsigned I = 0; I != Scale; ++I) {
2709         APInt SubUndefElts;
2710         APInt SubDemandedElt = APInt::getOneBitSet(Scale, I);
2711         APInt SubDemandedElts = APInt::getSplat(NumSrcElts, SubDemandedElt);
2712         SubDemandedElts &= ScaledDemandedElts;
2713         if (!isSplatValue(Src, SubDemandedElts, SubUndefElts, Depth + 1))
2714           return false;
2715 
2716         // Here we can't do "MatchAnyBits" operation merge for undef bits.
2717         // Because some operation only use part value of the source.
2718         // Take llvm.fshl.* for example:
2719         // t1: v4i32 = Constant:i32<12>, undef:i32, Constant:i32<12>, undef:i32
2720         // t2: v2i64 = bitcast t1
2721         // t5: v2i64 = fshl t3, t4, t2
2722         // We can not convert t2 to {i64 undef, i64 undef}
2723         UndefElts |= APIntOps::ScaleBitMask(SubUndefElts, NumElts,
2724                                             /*MatchAllBits=*/true);
2725       }
2726       return true;
2727     }
2728     break;
2729   }
2730   }
2731 
2732   return false;
2733 }
2734 
2735 /// Helper wrapper to main isSplatValue function.
2736 bool SelectionDAG::isSplatValue(SDValue V, bool AllowUndefs) const {
2737   EVT VT = V.getValueType();
2738   assert(VT.isVector() && "Vector type expected");
2739 
2740   APInt UndefElts;
2741   APInt DemandedElts;
2742 
2743   // For now we don't support this with scalable vectors.
2744   if (!VT.isScalableVector())
2745     DemandedElts = APInt::getAllOnes(VT.getVectorNumElements());
2746   return isSplatValue(V, DemandedElts, UndefElts) &&
2747          (AllowUndefs || !UndefElts);
2748 }
2749 
2750 SDValue SelectionDAG::getSplatSourceVector(SDValue V, int &SplatIdx) {
2751   V = peekThroughExtractSubvectors(V);
2752 
2753   EVT VT = V.getValueType();
2754   unsigned Opcode = V.getOpcode();
2755   switch (Opcode) {
2756   default: {
2757     APInt UndefElts;
2758     APInt DemandedElts;
2759 
2760     if (!VT.isScalableVector())
2761       DemandedElts = APInt::getAllOnes(VT.getVectorNumElements());
2762 
2763     if (isSplatValue(V, DemandedElts, UndefElts)) {
2764       if (VT.isScalableVector()) {
2765         // DemandedElts and UndefElts are ignored for scalable vectors, since
2766         // the only supported cases are SPLAT_VECTOR nodes.
2767         SplatIdx = 0;
2768       } else {
2769         // Handle case where all demanded elements are UNDEF.
2770         if (DemandedElts.isSubsetOf(UndefElts)) {
2771           SplatIdx = 0;
2772           return getUNDEF(VT);
2773         }
2774         SplatIdx = (UndefElts & DemandedElts).countTrailingOnes();
2775       }
2776       return V;
2777     }
2778     break;
2779   }
2780   case ISD::SPLAT_VECTOR:
2781     SplatIdx = 0;
2782     return V;
2783   case ISD::VECTOR_SHUFFLE: {
2784     if (VT.isScalableVector())
2785       return SDValue();
2786 
2787     // Check if this is a shuffle node doing a splat.
2788     // TODO - remove this and rely purely on SelectionDAG::isSplatValue,
2789     // getTargetVShiftNode currently struggles without the splat source.
2790     auto *SVN = cast<ShuffleVectorSDNode>(V);
2791     if (!SVN->isSplat())
2792       break;
2793     int Idx = SVN->getSplatIndex();
2794     int NumElts = V.getValueType().getVectorNumElements();
2795     SplatIdx = Idx % NumElts;
2796     return V.getOperand(Idx / NumElts);
2797   }
2798   }
2799 
2800   return SDValue();
2801 }
2802 
2803 SDValue SelectionDAG::getSplatValue(SDValue V, bool LegalTypes) {
2804   int SplatIdx;
2805   if (SDValue SrcVector = getSplatSourceVector(V, SplatIdx)) {
2806     EVT SVT = SrcVector.getValueType().getScalarType();
2807     EVT LegalSVT = SVT;
2808     if (LegalTypes && !TLI->isTypeLegal(SVT)) {
2809       if (!SVT.isInteger())
2810         return SDValue();
2811       LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
2812       if (LegalSVT.bitsLT(SVT))
2813         return SDValue();
2814     }
2815     return getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(V), LegalSVT, SrcVector,
2816                    getVectorIdxConstant(SplatIdx, SDLoc(V)));
2817   }
2818   return SDValue();
2819 }
2820 
2821 const APInt *
2822 SelectionDAG::getValidShiftAmountConstant(SDValue V,
2823                                           const APInt &DemandedElts) const {
2824   assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
2825           V.getOpcode() == ISD::SRA) &&
2826          "Unknown shift node");
2827   unsigned BitWidth = V.getScalarValueSizeInBits();
2828   if (ConstantSDNode *SA = isConstOrConstSplat(V.getOperand(1), DemandedElts)) {
2829     // Shifting more than the bitwidth is not valid.
2830     const APInt &ShAmt = SA->getAPIntValue();
2831     if (ShAmt.ult(BitWidth))
2832       return &ShAmt;
2833   }
2834   return nullptr;
2835 }
2836 
2837 const APInt *SelectionDAG::getValidMinimumShiftAmountConstant(
2838     SDValue V, const APInt &DemandedElts) const {
2839   assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
2840           V.getOpcode() == ISD::SRA) &&
2841          "Unknown shift node");
2842   if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts))
2843     return ValidAmt;
2844   unsigned BitWidth = V.getScalarValueSizeInBits();
2845   auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1));
2846   if (!BV)
2847     return nullptr;
2848   const APInt *MinShAmt = nullptr;
2849   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
2850     if (!DemandedElts[i])
2851       continue;
2852     auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i));
2853     if (!SA)
2854       return nullptr;
2855     // Shifting more than the bitwidth is not valid.
2856     const APInt &ShAmt = SA->getAPIntValue();
2857     if (ShAmt.uge(BitWidth))
2858       return nullptr;
2859     if (MinShAmt && MinShAmt->ule(ShAmt))
2860       continue;
2861     MinShAmt = &ShAmt;
2862   }
2863   return MinShAmt;
2864 }
2865 
2866 const APInt *SelectionDAG::getValidMaximumShiftAmountConstant(
2867     SDValue V, const APInt &DemandedElts) const {
2868   assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
2869           V.getOpcode() == ISD::SRA) &&
2870          "Unknown shift node");
2871   if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts))
2872     return ValidAmt;
2873   unsigned BitWidth = V.getScalarValueSizeInBits();
2874   auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1));
2875   if (!BV)
2876     return nullptr;
2877   const APInt *MaxShAmt = nullptr;
2878   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
2879     if (!DemandedElts[i])
2880       continue;
2881     auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i));
2882     if (!SA)
2883       return nullptr;
2884     // Shifting more than the bitwidth is not valid.
2885     const APInt &ShAmt = SA->getAPIntValue();
2886     if (ShAmt.uge(BitWidth))
2887       return nullptr;
2888     if (MaxShAmt && MaxShAmt->uge(ShAmt))
2889       continue;
2890     MaxShAmt = &ShAmt;
2891   }
2892   return MaxShAmt;
2893 }
2894 
2895 /// Determine which bits of Op are known to be either zero or one and return
2896 /// them in Known. For vectors, the known bits are those that are shared by
2897 /// every vector element.
2898 KnownBits SelectionDAG::computeKnownBits(SDValue Op, unsigned Depth) const {
2899   EVT VT = Op.getValueType();
2900 
2901   // TOOD: Until we have a plan for how to represent demanded elements for
2902   // scalable vectors, we can just bail out for now.
2903   if (Op.getValueType().isScalableVector()) {
2904     unsigned BitWidth = Op.getScalarValueSizeInBits();
2905     return KnownBits(BitWidth);
2906   }
2907 
2908   APInt DemandedElts = VT.isVector()
2909                            ? APInt::getAllOnes(VT.getVectorNumElements())
2910                            : APInt(1, 1);
2911   return computeKnownBits(Op, DemandedElts, Depth);
2912 }
2913 
2914 /// Determine which bits of Op are known to be either zero or one and return
2915 /// them in Known. The DemandedElts argument allows us to only collect the known
2916 /// bits that are shared by the requested vector elements.
2917 KnownBits SelectionDAG::computeKnownBits(SDValue Op, const APInt &DemandedElts,
2918                                          unsigned Depth) const {
2919   unsigned BitWidth = Op.getScalarValueSizeInBits();
2920 
2921   KnownBits Known(BitWidth);   // Don't know anything.
2922 
2923   // TOOD: Until we have a plan for how to represent demanded elements for
2924   // scalable vectors, we can just bail out for now.
2925   if (Op.getValueType().isScalableVector())
2926     return Known;
2927 
2928   if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
2929     // We know all of the bits for a constant!
2930     return KnownBits::makeConstant(C->getAPIntValue());
2931   }
2932   if (auto *C = dyn_cast<ConstantFPSDNode>(Op)) {
2933     // We know all of the bits for a constant fp!
2934     return KnownBits::makeConstant(C->getValueAPF().bitcastToAPInt());
2935   }
2936 
2937   if (Depth >= MaxRecursionDepth)
2938     return Known;  // Limit search depth.
2939 
2940   KnownBits Known2;
2941   unsigned NumElts = DemandedElts.getBitWidth();
2942   assert((!Op.getValueType().isVector() ||
2943           NumElts == Op.getValueType().getVectorNumElements()) &&
2944          "Unexpected vector size");
2945 
2946   if (!DemandedElts)
2947     return Known;  // No demanded elts, better to assume we don't know anything.
2948 
2949   unsigned Opcode = Op.getOpcode();
2950   switch (Opcode) {
2951   case ISD::BUILD_VECTOR:
2952     // Collect the known bits that are shared by every demanded vector element.
2953     Known.Zero.setAllBits(); Known.One.setAllBits();
2954     for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
2955       if (!DemandedElts[i])
2956         continue;
2957 
2958       SDValue SrcOp = Op.getOperand(i);
2959       Known2 = computeKnownBits(SrcOp, Depth + 1);
2960 
2961       // BUILD_VECTOR can implicitly truncate sources, we must handle this.
2962       if (SrcOp.getValueSizeInBits() != BitWidth) {
2963         assert(SrcOp.getValueSizeInBits() > BitWidth &&
2964                "Expected BUILD_VECTOR implicit truncation");
2965         Known2 = Known2.trunc(BitWidth);
2966       }
2967 
2968       // Known bits are the values that are shared by every demanded element.
2969       Known = KnownBits::commonBits(Known, Known2);
2970 
2971       // If we don't know any bits, early out.
2972       if (Known.isUnknown())
2973         break;
2974     }
2975     break;
2976   case ISD::VECTOR_SHUFFLE: {
2977     // Collect the known bits that are shared by every vector element referenced
2978     // by the shuffle.
2979     APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
2980     Known.Zero.setAllBits(); Known.One.setAllBits();
2981     const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
2982     assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
2983     for (unsigned i = 0; i != NumElts; ++i) {
2984       if (!DemandedElts[i])
2985         continue;
2986 
2987       int M = SVN->getMaskElt(i);
2988       if (M < 0) {
2989         // For UNDEF elements, we don't know anything about the common state of
2990         // the shuffle result.
2991         Known.resetAll();
2992         DemandedLHS.clearAllBits();
2993         DemandedRHS.clearAllBits();
2994         break;
2995       }
2996 
2997       if ((unsigned)M < NumElts)
2998         DemandedLHS.setBit((unsigned)M % NumElts);
2999       else
3000         DemandedRHS.setBit((unsigned)M % NumElts);
3001     }
3002     // Known bits are the values that are shared by every demanded element.
3003     if (!!DemandedLHS) {
3004       SDValue LHS = Op.getOperand(0);
3005       Known2 = computeKnownBits(LHS, DemandedLHS, Depth + 1);
3006       Known = KnownBits::commonBits(Known, Known2);
3007     }
3008     // If we don't know any bits, early out.
3009     if (Known.isUnknown())
3010       break;
3011     if (!!DemandedRHS) {
3012       SDValue RHS = Op.getOperand(1);
3013       Known2 = computeKnownBits(RHS, DemandedRHS, Depth + 1);
3014       Known = KnownBits::commonBits(Known, Known2);
3015     }
3016     break;
3017   }
3018   case ISD::CONCAT_VECTORS: {
3019     // Split DemandedElts and test each of the demanded subvectors.
3020     Known.Zero.setAllBits(); Known.One.setAllBits();
3021     EVT SubVectorVT = Op.getOperand(0).getValueType();
3022     unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
3023     unsigned NumSubVectors = Op.getNumOperands();
3024     for (unsigned i = 0; i != NumSubVectors; ++i) {
3025       APInt DemandedSub =
3026           DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts);
3027       if (!!DemandedSub) {
3028         SDValue Sub = Op.getOperand(i);
3029         Known2 = computeKnownBits(Sub, DemandedSub, Depth + 1);
3030         Known = KnownBits::commonBits(Known, Known2);
3031       }
3032       // If we don't know any bits, early out.
3033       if (Known.isUnknown())
3034         break;
3035     }
3036     break;
3037   }
3038   case ISD::INSERT_SUBVECTOR: {
3039     // Demand any elements from the subvector and the remainder from the src its
3040     // inserted into.
3041     SDValue Src = Op.getOperand(0);
3042     SDValue Sub = Op.getOperand(1);
3043     uint64_t Idx = Op.getConstantOperandVal(2);
3044     unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
3045     APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
3046     APInt DemandedSrcElts = DemandedElts;
3047     DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx);
3048 
3049     Known.One.setAllBits();
3050     Known.Zero.setAllBits();
3051     if (!!DemandedSubElts) {
3052       Known = computeKnownBits(Sub, DemandedSubElts, Depth + 1);
3053       if (Known.isUnknown())
3054         break; // early-out.
3055     }
3056     if (!!DemandedSrcElts) {
3057       Known2 = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
3058       Known = KnownBits::commonBits(Known, Known2);
3059     }
3060     break;
3061   }
3062   case ISD::EXTRACT_SUBVECTOR: {
3063     // Offset the demanded elts by the subvector index.
3064     SDValue Src = Op.getOperand(0);
3065     // Bail until we can represent demanded elements for scalable vectors.
3066     if (Src.getValueType().isScalableVector())
3067       break;
3068     uint64_t Idx = Op.getConstantOperandVal(1);
3069     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
3070     APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
3071     Known = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
3072     break;
3073   }
3074   case ISD::SCALAR_TO_VECTOR: {
3075     // We know about scalar_to_vector as much as we know about it source,
3076     // which becomes the first element of otherwise unknown vector.
3077     if (DemandedElts != 1)
3078       break;
3079 
3080     SDValue N0 = Op.getOperand(0);
3081     Known = computeKnownBits(N0, Depth + 1);
3082     if (N0.getValueSizeInBits() != BitWidth)
3083       Known = Known.trunc(BitWidth);
3084 
3085     break;
3086   }
3087   case ISD::BITCAST: {
3088     SDValue N0 = Op.getOperand(0);
3089     EVT SubVT = N0.getValueType();
3090     unsigned SubBitWidth = SubVT.getScalarSizeInBits();
3091 
3092     // Ignore bitcasts from unsupported types.
3093     if (!(SubVT.isInteger() || SubVT.isFloatingPoint()))
3094       break;
3095 
3096     // Fast handling of 'identity' bitcasts.
3097     if (BitWidth == SubBitWidth) {
3098       Known = computeKnownBits(N0, DemandedElts, Depth + 1);
3099       break;
3100     }
3101 
3102     bool IsLE = getDataLayout().isLittleEndian();
3103 
3104     // Bitcast 'small element' vector to 'large element' scalar/vector.
3105     if ((BitWidth % SubBitWidth) == 0) {
3106       assert(N0.getValueType().isVector() && "Expected bitcast from vector");
3107 
3108       // Collect known bits for the (larger) output by collecting the known
3109       // bits from each set of sub elements and shift these into place.
3110       // We need to separately call computeKnownBits for each set of
3111       // sub elements as the knownbits for each is likely to be different.
3112       unsigned SubScale = BitWidth / SubBitWidth;
3113       APInt SubDemandedElts(NumElts * SubScale, 0);
3114       for (unsigned i = 0; i != NumElts; ++i)
3115         if (DemandedElts[i])
3116           SubDemandedElts.setBit(i * SubScale);
3117 
3118       for (unsigned i = 0; i != SubScale; ++i) {
3119         Known2 = computeKnownBits(N0, SubDemandedElts.shl(i),
3120                          Depth + 1);
3121         unsigned Shifts = IsLE ? i : SubScale - 1 - i;
3122         Known.insertBits(Known2, SubBitWidth * Shifts);
3123       }
3124     }
3125 
3126     // Bitcast 'large element' scalar/vector to 'small element' vector.
3127     if ((SubBitWidth % BitWidth) == 0) {
3128       assert(Op.getValueType().isVector() && "Expected bitcast to vector");
3129 
3130       // Collect known bits for the (smaller) output by collecting the known
3131       // bits from the overlapping larger input elements and extracting the
3132       // sub sections we actually care about.
3133       unsigned SubScale = SubBitWidth / BitWidth;
3134       APInt SubDemandedElts =
3135           APIntOps::ScaleBitMask(DemandedElts, NumElts / SubScale);
3136       Known2 = computeKnownBits(N0, SubDemandedElts, Depth + 1);
3137 
3138       Known.Zero.setAllBits(); Known.One.setAllBits();
3139       for (unsigned i = 0; i != NumElts; ++i)
3140         if (DemandedElts[i]) {
3141           unsigned Shifts = IsLE ? i : NumElts - 1 - i;
3142           unsigned Offset = (Shifts % SubScale) * BitWidth;
3143           Known = KnownBits::commonBits(Known,
3144                                         Known2.extractBits(BitWidth, Offset));
3145           // If we don't know any bits, early out.
3146           if (Known.isUnknown())
3147             break;
3148         }
3149     }
3150     break;
3151   }
3152   case ISD::AND:
3153     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3154     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3155 
3156     Known &= Known2;
3157     break;
3158   case ISD::OR:
3159     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3160     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3161 
3162     Known |= Known2;
3163     break;
3164   case ISD::XOR:
3165     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3166     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3167 
3168     Known ^= Known2;
3169     break;
3170   case ISD::MUL: {
3171     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3172     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3173     bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1);
3174     // TODO: SelfMultiply can be poison, but not undef.
3175     if (SelfMultiply)
3176       SelfMultiply &= isGuaranteedNotToBeUndefOrPoison(
3177           Op.getOperand(0), DemandedElts, false, Depth + 1);
3178     Known = KnownBits::mul(Known, Known2, SelfMultiply);
3179 
3180     // If the multiplication is known not to overflow, the product of a number
3181     // with itself is non-negative. Only do this if we didn't already computed
3182     // the opposite value for the sign bit.
3183     if (Op->getFlags().hasNoSignedWrap() &&
3184         Op.getOperand(0) == Op.getOperand(1) &&
3185         !Known.isNegative())
3186       Known.makeNonNegative();
3187     break;
3188   }
3189   case ISD::MULHU: {
3190     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3191     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3192     Known = KnownBits::mulhu(Known, Known2);
3193     break;
3194   }
3195   case ISD::MULHS: {
3196     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3197     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3198     Known = KnownBits::mulhs(Known, Known2);
3199     break;
3200   }
3201   case ISD::UMUL_LOHI: {
3202     assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3203     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3204     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3205     bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1);
3206     if (Op.getResNo() == 0)
3207       Known = KnownBits::mul(Known, Known2, SelfMultiply);
3208     else
3209       Known = KnownBits::mulhu(Known, Known2);
3210     break;
3211   }
3212   case ISD::SMUL_LOHI: {
3213     assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3214     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3215     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3216     bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1);
3217     if (Op.getResNo() == 0)
3218       Known = KnownBits::mul(Known, Known2, SelfMultiply);
3219     else
3220       Known = KnownBits::mulhs(Known, Known2);
3221     break;
3222   }
3223   case ISD::UDIV: {
3224     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3225     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3226     Known = KnownBits::udiv(Known, Known2);
3227     break;
3228   }
3229   case ISD::AVGCEILU: {
3230     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3231     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3232     Known = Known.zext(BitWidth + 1);
3233     Known2 = Known2.zext(BitWidth + 1);
3234     KnownBits One = KnownBits::makeConstant(APInt(1, 1));
3235     Known = KnownBits::computeForAddCarry(Known, Known2, One);
3236     Known = Known.extractBits(BitWidth, 1);
3237     break;
3238   }
3239   case ISD::SELECT:
3240   case ISD::VSELECT:
3241     Known = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
3242     // If we don't know any bits, early out.
3243     if (Known.isUnknown())
3244       break;
3245     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth+1);
3246 
3247     // Only known if known in both the LHS and RHS.
3248     Known = KnownBits::commonBits(Known, Known2);
3249     break;
3250   case ISD::SELECT_CC:
3251     Known = computeKnownBits(Op.getOperand(3), DemandedElts, Depth+1);
3252     // If we don't know any bits, early out.
3253     if (Known.isUnknown())
3254       break;
3255     Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
3256 
3257     // Only known if known in both the LHS and RHS.
3258     Known = KnownBits::commonBits(Known, Known2);
3259     break;
3260   case ISD::SMULO:
3261   case ISD::UMULO:
3262     if (Op.getResNo() != 1)
3263       break;
3264     // The boolean result conforms to getBooleanContents.
3265     // If we know the result of a setcc has the top bits zero, use this info.
3266     // We know that we have an integer-based boolean since these operations
3267     // are only available for integer.
3268     if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
3269             TargetLowering::ZeroOrOneBooleanContent &&
3270         BitWidth > 1)
3271       Known.Zero.setBitsFrom(1);
3272     break;
3273   case ISD::SETCC:
3274   case ISD::SETCCCARRY:
3275   case ISD::STRICT_FSETCC:
3276   case ISD::STRICT_FSETCCS: {
3277     unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
3278     // If we know the result of a setcc has the top bits zero, use this info.
3279     if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
3280             TargetLowering::ZeroOrOneBooleanContent &&
3281         BitWidth > 1)
3282       Known.Zero.setBitsFrom(1);
3283     break;
3284   }
3285   case ISD::SHL:
3286     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3287     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3288     Known = KnownBits::shl(Known, Known2);
3289 
3290     // Minimum shift low bits are known zero.
3291     if (const APInt *ShMinAmt =
3292             getValidMinimumShiftAmountConstant(Op, DemandedElts))
3293       Known.Zero.setLowBits(ShMinAmt->getZExtValue());
3294     break;
3295   case ISD::SRL:
3296     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3297     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3298     Known = KnownBits::lshr(Known, Known2);
3299 
3300     // Minimum shift high bits are known zero.
3301     if (const APInt *ShMinAmt =
3302             getValidMinimumShiftAmountConstant(Op, DemandedElts))
3303       Known.Zero.setHighBits(ShMinAmt->getZExtValue());
3304     break;
3305   case ISD::SRA:
3306     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3307     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3308     Known = KnownBits::ashr(Known, Known2);
3309     // TODO: Add minimum shift high known sign bits.
3310     break;
3311   case ISD::FSHL:
3312   case ISD::FSHR:
3313     if (ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(2), DemandedElts)) {
3314       unsigned Amt = C->getAPIntValue().urem(BitWidth);
3315 
3316       // For fshl, 0-shift returns the 1st arg.
3317       // For fshr, 0-shift returns the 2nd arg.
3318       if (Amt == 0) {
3319         Known = computeKnownBits(Op.getOperand(Opcode == ISD::FSHL ? 0 : 1),
3320                                  DemandedElts, Depth + 1);
3321         break;
3322       }
3323 
3324       // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
3325       // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
3326       Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3327       Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3328       if (Opcode == ISD::FSHL) {
3329         Known.One <<= Amt;
3330         Known.Zero <<= Amt;
3331         Known2.One.lshrInPlace(BitWidth - Amt);
3332         Known2.Zero.lshrInPlace(BitWidth - Amt);
3333       } else {
3334         Known.One <<= BitWidth - Amt;
3335         Known.Zero <<= BitWidth - Amt;
3336         Known2.One.lshrInPlace(Amt);
3337         Known2.Zero.lshrInPlace(Amt);
3338       }
3339       Known.One |= Known2.One;
3340       Known.Zero |= Known2.Zero;
3341     }
3342     break;
3343   case ISD::SIGN_EXTEND_INREG: {
3344     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3345     EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3346     Known = Known.sextInReg(EVT.getScalarSizeInBits());
3347     break;
3348   }
3349   case ISD::CTTZ:
3350   case ISD::CTTZ_ZERO_UNDEF: {
3351     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3352     // If we have a known 1, its position is our upper bound.
3353     unsigned PossibleTZ = Known2.countMaxTrailingZeros();
3354     unsigned LowBits = Log2_32(PossibleTZ) + 1;
3355     Known.Zero.setBitsFrom(LowBits);
3356     break;
3357   }
3358   case ISD::CTLZ:
3359   case ISD::CTLZ_ZERO_UNDEF: {
3360     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3361     // If we have a known 1, its position is our upper bound.
3362     unsigned PossibleLZ = Known2.countMaxLeadingZeros();
3363     unsigned LowBits = Log2_32(PossibleLZ) + 1;
3364     Known.Zero.setBitsFrom(LowBits);
3365     break;
3366   }
3367   case ISD::CTPOP: {
3368     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3369     // If we know some of the bits are zero, they can't be one.
3370     unsigned PossibleOnes = Known2.countMaxPopulation();
3371     Known.Zero.setBitsFrom(Log2_32(PossibleOnes) + 1);
3372     break;
3373   }
3374   case ISD::PARITY: {
3375     // Parity returns 0 everywhere but the LSB.
3376     Known.Zero.setBitsFrom(1);
3377     break;
3378   }
3379   case ISD::LOAD: {
3380     LoadSDNode *LD = cast<LoadSDNode>(Op);
3381     const Constant *Cst = TLI->getTargetConstantFromLoad(LD);
3382     if (ISD::isNON_EXTLoad(LD) && Cst) {
3383       // Determine any common known bits from the loaded constant pool value.
3384       Type *CstTy = Cst->getType();
3385       if ((NumElts * BitWidth) == CstTy->getPrimitiveSizeInBits()) {
3386         // If its a vector splat, then we can (quickly) reuse the scalar path.
3387         // NOTE: We assume all elements match and none are UNDEF.
3388         if (CstTy->isVectorTy()) {
3389           if (const Constant *Splat = Cst->getSplatValue()) {
3390             Cst = Splat;
3391             CstTy = Cst->getType();
3392           }
3393         }
3394         // TODO - do we need to handle different bitwidths?
3395         if (CstTy->isVectorTy() && BitWidth == CstTy->getScalarSizeInBits()) {
3396           // Iterate across all vector elements finding common known bits.
3397           Known.One.setAllBits();
3398           Known.Zero.setAllBits();
3399           for (unsigned i = 0; i != NumElts; ++i) {
3400             if (!DemandedElts[i])
3401               continue;
3402             if (Constant *Elt = Cst->getAggregateElement(i)) {
3403               if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
3404                 const APInt &Value = CInt->getValue();
3405                 Known.One &= Value;
3406                 Known.Zero &= ~Value;
3407                 continue;
3408               }
3409               if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
3410                 APInt Value = CFP->getValueAPF().bitcastToAPInt();
3411                 Known.One &= Value;
3412                 Known.Zero &= ~Value;
3413                 continue;
3414               }
3415             }
3416             Known.One.clearAllBits();
3417             Known.Zero.clearAllBits();
3418             break;
3419           }
3420         } else if (BitWidth == CstTy->getPrimitiveSizeInBits()) {
3421           if (auto *CInt = dyn_cast<ConstantInt>(Cst)) {
3422             Known = KnownBits::makeConstant(CInt->getValue());
3423           } else if (auto *CFP = dyn_cast<ConstantFP>(Cst)) {
3424             Known =
3425                 KnownBits::makeConstant(CFP->getValueAPF().bitcastToAPInt());
3426           }
3427         }
3428       }
3429     } else if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) {
3430       // If this is a ZEXTLoad and we are looking at the loaded value.
3431       EVT VT = LD->getMemoryVT();
3432       unsigned MemBits = VT.getScalarSizeInBits();
3433       Known.Zero.setBitsFrom(MemBits);
3434     } else if (const MDNode *Ranges = LD->getRanges()) {
3435       if (LD->getExtensionType() == ISD::NON_EXTLOAD)
3436         computeKnownBitsFromRangeMetadata(*Ranges, Known);
3437     }
3438     break;
3439   }
3440   case ISD::ZERO_EXTEND_VECTOR_INREG: {
3441     EVT InVT = Op.getOperand(0).getValueType();
3442     APInt InDemandedElts = DemandedElts.zext(InVT.getVectorNumElements());
3443     Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3444     Known = Known.zext(BitWidth);
3445     break;
3446   }
3447   case ISD::ZERO_EXTEND: {
3448     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3449     Known = Known.zext(BitWidth);
3450     break;
3451   }
3452   case ISD::SIGN_EXTEND_VECTOR_INREG: {
3453     EVT InVT = Op.getOperand(0).getValueType();
3454     APInt InDemandedElts = DemandedElts.zext(InVT.getVectorNumElements());
3455     Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3456     // If the sign bit is known to be zero or one, then sext will extend
3457     // it to the top bits, else it will just zext.
3458     Known = Known.sext(BitWidth);
3459     break;
3460   }
3461   case ISD::SIGN_EXTEND: {
3462     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3463     // If the sign bit is known to be zero or one, then sext will extend
3464     // it to the top bits, else it will just zext.
3465     Known = Known.sext(BitWidth);
3466     break;
3467   }
3468   case ISD::ANY_EXTEND_VECTOR_INREG: {
3469     EVT InVT = Op.getOperand(0).getValueType();
3470     APInt InDemandedElts = DemandedElts.zext(InVT.getVectorNumElements());
3471     Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3472     Known = Known.anyext(BitWidth);
3473     break;
3474   }
3475   case ISD::ANY_EXTEND: {
3476     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3477     Known = Known.anyext(BitWidth);
3478     break;
3479   }
3480   case ISD::TRUNCATE: {
3481     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3482     Known = Known.trunc(BitWidth);
3483     break;
3484   }
3485   case ISD::AssertZext: {
3486     EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3487     APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits());
3488     Known = computeKnownBits(Op.getOperand(0), Depth+1);
3489     Known.Zero |= (~InMask);
3490     Known.One  &= (~Known.Zero);
3491     break;
3492   }
3493   case ISD::AssertAlign: {
3494     unsigned LogOfAlign = Log2(cast<AssertAlignSDNode>(Op)->getAlign());
3495     assert(LogOfAlign != 0);
3496 
3497     // TODO: Should use maximum with source
3498     // If a node is guaranteed to be aligned, set low zero bits accordingly as
3499     // well as clearing one bits.
3500     Known.Zero.setLowBits(LogOfAlign);
3501     Known.One.clearLowBits(LogOfAlign);
3502     break;
3503   }
3504   case ISD::FGETSIGN:
3505     // All bits are zero except the low bit.
3506     Known.Zero.setBitsFrom(1);
3507     break;
3508   case ISD::USUBO:
3509   case ISD::SSUBO:
3510   case ISD::SUBCARRY:
3511   case ISD::SSUBO_CARRY:
3512     if (Op.getResNo() == 1) {
3513       // If we know the result of a setcc has the top bits zero, use this info.
3514       if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
3515               TargetLowering::ZeroOrOneBooleanContent &&
3516           BitWidth > 1)
3517         Known.Zero.setBitsFrom(1);
3518       break;
3519     }
3520     LLVM_FALLTHROUGH;
3521   case ISD::SUB:
3522   case ISD::SUBC: {
3523     assert(Op.getResNo() == 0 &&
3524            "We only compute knownbits for the difference here.");
3525 
3526     // TODO: Compute influence of the carry operand.
3527     if (Opcode == ISD::SUBCARRY || Opcode == ISD::SSUBO_CARRY)
3528       break;
3529 
3530     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3531     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3532     Known = KnownBits::computeForAddSub(/* Add */ false, /* NSW */ false,
3533                                         Known, Known2);
3534     break;
3535   }
3536   case ISD::UADDO:
3537   case ISD::SADDO:
3538   case ISD::ADDCARRY:
3539   case ISD::SADDO_CARRY:
3540     if (Op.getResNo() == 1) {
3541       // If we know the result of a setcc has the top bits zero, use this info.
3542       if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
3543               TargetLowering::ZeroOrOneBooleanContent &&
3544           BitWidth > 1)
3545         Known.Zero.setBitsFrom(1);
3546       break;
3547     }
3548     LLVM_FALLTHROUGH;
3549   case ISD::ADD:
3550   case ISD::ADDC:
3551   case ISD::ADDE: {
3552     assert(Op.getResNo() == 0 && "We only compute knownbits for the sum here.");
3553 
3554     // With ADDE and ADDCARRY, a carry bit may be added in.
3555     KnownBits Carry(1);
3556     if (Opcode == ISD::ADDE)
3557       // Can't track carry from glue, set carry to unknown.
3558       Carry.resetAll();
3559     else if (Opcode == ISD::ADDCARRY || Opcode == ISD::SADDO_CARRY)
3560       // TODO: Compute known bits for the carry operand. Not sure if it is worth
3561       // the trouble (how often will we find a known carry bit). And I haven't
3562       // tested this very much yet, but something like this might work:
3563       //   Carry = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1);
3564       //   Carry = Carry.zextOrTrunc(1, false);
3565       Carry.resetAll();
3566     else
3567       Carry.setAllZero();
3568 
3569     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3570     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3571     Known = KnownBits::computeForAddCarry(Known, Known2, Carry);
3572     break;
3573   }
3574   case ISD::SREM: {
3575     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3576     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3577     Known = KnownBits::srem(Known, Known2);
3578     break;
3579   }
3580   case ISD::UREM: {
3581     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3582     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3583     Known = KnownBits::urem(Known, Known2);
3584     break;
3585   }
3586   case ISD::EXTRACT_ELEMENT: {
3587     Known = computeKnownBits(Op.getOperand(0), Depth+1);
3588     const unsigned Index = Op.getConstantOperandVal(1);
3589     const unsigned EltBitWidth = Op.getValueSizeInBits();
3590 
3591     // Remove low part of known bits mask
3592     Known.Zero = Known.Zero.getHiBits(Known.getBitWidth() - Index * EltBitWidth);
3593     Known.One = Known.One.getHiBits(Known.getBitWidth() - Index * EltBitWidth);
3594 
3595     // Remove high part of known bit mask
3596     Known = Known.trunc(EltBitWidth);
3597     break;
3598   }
3599   case ISD::EXTRACT_VECTOR_ELT: {
3600     SDValue InVec = Op.getOperand(0);
3601     SDValue EltNo = Op.getOperand(1);
3602     EVT VecVT = InVec.getValueType();
3603     // computeKnownBits not yet implemented for scalable vectors.
3604     if (VecVT.isScalableVector())
3605       break;
3606     const unsigned EltBitWidth = VecVT.getScalarSizeInBits();
3607     const unsigned NumSrcElts = VecVT.getVectorNumElements();
3608 
3609     // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know
3610     // anything about the extended bits.
3611     if (BitWidth > EltBitWidth)
3612       Known = Known.trunc(EltBitWidth);
3613 
3614     // If we know the element index, just demand that vector element, else for
3615     // an unknown element index, ignore DemandedElts and demand them all.
3616     APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
3617     auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
3618     if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
3619       DemandedSrcElts =
3620           APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
3621 
3622     Known = computeKnownBits(InVec, DemandedSrcElts, Depth + 1);
3623     if (BitWidth > EltBitWidth)
3624       Known = Known.anyext(BitWidth);
3625     break;
3626   }
3627   case ISD::INSERT_VECTOR_ELT: {
3628     // If we know the element index, split the demand between the
3629     // source vector and the inserted element, otherwise assume we need
3630     // the original demanded vector elements and the value.
3631     SDValue InVec = Op.getOperand(0);
3632     SDValue InVal = Op.getOperand(1);
3633     SDValue EltNo = Op.getOperand(2);
3634     bool DemandedVal = true;
3635     APInt DemandedVecElts = DemandedElts;
3636     auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
3637     if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
3638       unsigned EltIdx = CEltNo->getZExtValue();
3639       DemandedVal = !!DemandedElts[EltIdx];
3640       DemandedVecElts.clearBit(EltIdx);
3641     }
3642     Known.One.setAllBits();
3643     Known.Zero.setAllBits();
3644     if (DemandedVal) {
3645       Known2 = computeKnownBits(InVal, Depth + 1);
3646       Known = KnownBits::commonBits(Known, Known2.zextOrTrunc(BitWidth));
3647     }
3648     if (!!DemandedVecElts) {
3649       Known2 = computeKnownBits(InVec, DemandedVecElts, Depth + 1);
3650       Known = KnownBits::commonBits(Known, Known2);
3651     }
3652     break;
3653   }
3654   case ISD::BITREVERSE: {
3655     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3656     Known = Known2.reverseBits();
3657     break;
3658   }
3659   case ISD::BSWAP: {
3660     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3661     Known = Known2.byteSwap();
3662     break;
3663   }
3664   case ISD::ABS: {
3665     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3666     Known = Known2.abs();
3667     break;
3668   }
3669   case ISD::USUBSAT: {
3670     // The result of usubsat will never be larger than the LHS.
3671     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3672     Known.Zero.setHighBits(Known2.countMinLeadingZeros());
3673     break;
3674   }
3675   case ISD::UMIN: {
3676     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3677     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3678     Known = KnownBits::umin(Known, Known2);
3679     break;
3680   }
3681   case ISD::UMAX: {
3682     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3683     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3684     Known = KnownBits::umax(Known, Known2);
3685     break;
3686   }
3687   case ISD::SMIN:
3688   case ISD::SMAX: {
3689     // If we have a clamp pattern, we know that the number of sign bits will be
3690     // the minimum of the clamp min/max range.
3691     bool IsMax = (Opcode == ISD::SMAX);
3692     ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
3693     if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
3694       if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
3695         CstHigh =
3696             isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
3697     if (CstLow && CstHigh) {
3698       if (!IsMax)
3699         std::swap(CstLow, CstHigh);
3700 
3701       const APInt &ValueLow = CstLow->getAPIntValue();
3702       const APInt &ValueHigh = CstHigh->getAPIntValue();
3703       if (ValueLow.sle(ValueHigh)) {
3704         unsigned LowSignBits = ValueLow.getNumSignBits();
3705         unsigned HighSignBits = ValueHigh.getNumSignBits();
3706         unsigned MinSignBits = std::min(LowSignBits, HighSignBits);
3707         if (ValueLow.isNegative() && ValueHigh.isNegative()) {
3708           Known.One.setHighBits(MinSignBits);
3709           break;
3710         }
3711         if (ValueLow.isNonNegative() && ValueHigh.isNonNegative()) {
3712           Known.Zero.setHighBits(MinSignBits);
3713           break;
3714         }
3715       }
3716     }
3717 
3718     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3719     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3720     if (IsMax)
3721       Known = KnownBits::smax(Known, Known2);
3722     else
3723       Known = KnownBits::smin(Known, Known2);
3724 
3725     // For SMAX, if CstLow is non-negative we know the result will be
3726     // non-negative and thus all sign bits are 0.
3727     // TODO: There's an equivalent of this for smin with negative constant for
3728     // known ones.
3729     if (IsMax && CstLow) {
3730       const APInt &ValueLow = CstLow->getAPIntValue();
3731       if (ValueLow.isNonNegative()) {
3732         unsigned SignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
3733         Known.Zero.setHighBits(std::min(SignBits, ValueLow.getNumSignBits()));
3734       }
3735     }
3736 
3737     break;
3738   }
3739   case ISD::FP_TO_UINT_SAT: {
3740     // FP_TO_UINT_SAT produces an unsigned value that fits in the saturating VT.
3741     EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3742     Known.Zero |= APInt::getBitsSetFrom(BitWidth, VT.getScalarSizeInBits());
3743     break;
3744   }
3745   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
3746     if (Op.getResNo() == 1) {
3747       // The boolean result conforms to getBooleanContents.
3748       // If we know the result of a setcc has the top bits zero, use this info.
3749       // We know that we have an integer-based boolean since these operations
3750       // are only available for integer.
3751       if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
3752               TargetLowering::ZeroOrOneBooleanContent &&
3753           BitWidth > 1)
3754         Known.Zero.setBitsFrom(1);
3755       break;
3756     }
3757     LLVM_FALLTHROUGH;
3758   case ISD::ATOMIC_CMP_SWAP:
3759   case ISD::ATOMIC_SWAP:
3760   case ISD::ATOMIC_LOAD_ADD:
3761   case ISD::ATOMIC_LOAD_SUB:
3762   case ISD::ATOMIC_LOAD_AND:
3763   case ISD::ATOMIC_LOAD_CLR:
3764   case ISD::ATOMIC_LOAD_OR:
3765   case ISD::ATOMIC_LOAD_XOR:
3766   case ISD::ATOMIC_LOAD_NAND:
3767   case ISD::ATOMIC_LOAD_MIN:
3768   case ISD::ATOMIC_LOAD_MAX:
3769   case ISD::ATOMIC_LOAD_UMIN:
3770   case ISD::ATOMIC_LOAD_UMAX:
3771   case ISD::ATOMIC_LOAD: {
3772     unsigned MemBits =
3773         cast<AtomicSDNode>(Op)->getMemoryVT().getScalarSizeInBits();
3774     // If we are looking at the loaded value.
3775     if (Op.getResNo() == 0) {
3776       if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND)
3777         Known.Zero.setBitsFrom(MemBits);
3778     }
3779     break;
3780   }
3781   case ISD::FrameIndex:
3782   case ISD::TargetFrameIndex:
3783     TLI->computeKnownBitsForFrameIndex(cast<FrameIndexSDNode>(Op)->getIndex(),
3784                                        Known, getMachineFunction());
3785     break;
3786 
3787   default:
3788     if (Opcode < ISD::BUILTIN_OP_END)
3789       break;
3790     LLVM_FALLTHROUGH;
3791   case ISD::INTRINSIC_WO_CHAIN:
3792   case ISD::INTRINSIC_W_CHAIN:
3793   case ISD::INTRINSIC_VOID:
3794     // Allow the target to implement this method for its nodes.
3795     TLI->computeKnownBitsForTargetNode(Op, Known, DemandedElts, *this, Depth);
3796     break;
3797   }
3798 
3799   assert(!Known.hasConflict() && "Bits known to be one AND zero?");
3800   return Known;
3801 }
3802 
3803 SelectionDAG::OverflowKind SelectionDAG::computeOverflowKind(SDValue N0,
3804                                                              SDValue N1) const {
3805   // X + 0 never overflow
3806   if (isNullConstant(N1))
3807     return OFK_Never;
3808 
3809   KnownBits N1Known = computeKnownBits(N1);
3810   if (N1Known.Zero.getBoolValue()) {
3811     KnownBits N0Known = computeKnownBits(N0);
3812 
3813     bool overflow;
3814     (void)N0Known.getMaxValue().uadd_ov(N1Known.getMaxValue(), overflow);
3815     if (!overflow)
3816       return OFK_Never;
3817   }
3818 
3819   // mulhi + 1 never overflow
3820   if (N0.getOpcode() == ISD::UMUL_LOHI && N0.getResNo() == 1 &&
3821       (N1Known.getMaxValue() & 0x01) == N1Known.getMaxValue())
3822     return OFK_Never;
3823 
3824   if (N1.getOpcode() == ISD::UMUL_LOHI && N1.getResNo() == 1) {
3825     KnownBits N0Known = computeKnownBits(N0);
3826 
3827     if ((N0Known.getMaxValue() & 0x01) == N0Known.getMaxValue())
3828       return OFK_Never;
3829   }
3830 
3831   return OFK_Sometime;
3832 }
3833 
3834 bool SelectionDAG::isKnownToBeAPowerOfTwo(SDValue Val) const {
3835   EVT OpVT = Val.getValueType();
3836   unsigned BitWidth = OpVT.getScalarSizeInBits();
3837 
3838   // Is the constant a known power of 2?
3839   if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Val))
3840     return Const->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
3841 
3842   // A left-shift of a constant one will have exactly one bit set because
3843   // shifting the bit off the end is undefined.
3844   if (Val.getOpcode() == ISD::SHL) {
3845     auto *C = isConstOrConstSplat(Val.getOperand(0));
3846     if (C && C->getAPIntValue() == 1)
3847       return true;
3848   }
3849 
3850   // Similarly, a logical right-shift of a constant sign-bit will have exactly
3851   // one bit set.
3852   if (Val.getOpcode() == ISD::SRL) {
3853     auto *C = isConstOrConstSplat(Val.getOperand(0));
3854     if (C && C->getAPIntValue().isSignMask())
3855       return true;
3856   }
3857 
3858   // Are all operands of a build vector constant powers of two?
3859   if (Val.getOpcode() == ISD::BUILD_VECTOR)
3860     if (llvm::all_of(Val->ops(), [BitWidth](SDValue E) {
3861           if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(E))
3862             return C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
3863           return false;
3864         }))
3865       return true;
3866 
3867   // Is the operand of a splat vector a constant power of two?
3868   if (Val.getOpcode() == ISD::SPLAT_VECTOR)
3869     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val->getOperand(0)))
3870       if (C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2())
3871         return true;
3872 
3873   // More could be done here, though the above checks are enough
3874   // to handle some common cases.
3875 
3876   // Fall back to computeKnownBits to catch other known cases.
3877   KnownBits Known = computeKnownBits(Val);
3878   return (Known.countMaxPopulation() == 1) && (Known.countMinPopulation() == 1);
3879 }
3880 
3881 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const {
3882   EVT VT = Op.getValueType();
3883 
3884   // TODO: Assume we don't know anything for now.
3885   if (VT.isScalableVector())
3886     return 1;
3887 
3888   APInt DemandedElts = VT.isVector()
3889                            ? APInt::getAllOnes(VT.getVectorNumElements())
3890                            : APInt(1, 1);
3891   return ComputeNumSignBits(Op, DemandedElts, Depth);
3892 }
3893 
3894 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, const APInt &DemandedElts,
3895                                           unsigned Depth) const {
3896   EVT VT = Op.getValueType();
3897   assert((VT.isInteger() || VT.isFloatingPoint()) && "Invalid VT!");
3898   unsigned VTBits = VT.getScalarSizeInBits();
3899   unsigned NumElts = DemandedElts.getBitWidth();
3900   unsigned Tmp, Tmp2;
3901   unsigned FirstAnswer = 1;
3902 
3903   if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
3904     const APInt &Val = C->getAPIntValue();
3905     return Val.getNumSignBits();
3906   }
3907 
3908   if (Depth >= MaxRecursionDepth)
3909     return 1;  // Limit search depth.
3910 
3911   if (!DemandedElts || VT.isScalableVector())
3912     return 1;  // No demanded elts, better to assume we don't know anything.
3913 
3914   unsigned Opcode = Op.getOpcode();
3915   switch (Opcode) {
3916   default: break;
3917   case ISD::AssertSext:
3918     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
3919     return VTBits-Tmp+1;
3920   case ISD::AssertZext:
3921     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
3922     return VTBits-Tmp;
3923 
3924   case ISD::BUILD_VECTOR:
3925     Tmp = VTBits;
3926     for (unsigned i = 0, e = Op.getNumOperands(); (i < e) && (Tmp > 1); ++i) {
3927       if (!DemandedElts[i])
3928         continue;
3929 
3930       SDValue SrcOp = Op.getOperand(i);
3931       Tmp2 = ComputeNumSignBits(SrcOp, Depth + 1);
3932 
3933       // BUILD_VECTOR can implicitly truncate sources, we must handle this.
3934       if (SrcOp.getValueSizeInBits() != VTBits) {
3935         assert(SrcOp.getValueSizeInBits() > VTBits &&
3936                "Expected BUILD_VECTOR implicit truncation");
3937         unsigned ExtraBits = SrcOp.getValueSizeInBits() - VTBits;
3938         Tmp2 = (Tmp2 > ExtraBits ? Tmp2 - ExtraBits : 1);
3939       }
3940       Tmp = std::min(Tmp, Tmp2);
3941     }
3942     return Tmp;
3943 
3944   case ISD::VECTOR_SHUFFLE: {
3945     // Collect the minimum number of sign bits that are shared by every vector
3946     // element referenced by the shuffle.
3947     APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
3948     const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
3949     assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
3950     for (unsigned i = 0; i != NumElts; ++i) {
3951       int M = SVN->getMaskElt(i);
3952       if (!DemandedElts[i])
3953         continue;
3954       // For UNDEF elements, we don't know anything about the common state of
3955       // the shuffle result.
3956       if (M < 0)
3957         return 1;
3958       if ((unsigned)M < NumElts)
3959         DemandedLHS.setBit((unsigned)M % NumElts);
3960       else
3961         DemandedRHS.setBit((unsigned)M % NumElts);
3962     }
3963     Tmp = std::numeric_limits<unsigned>::max();
3964     if (!!DemandedLHS)
3965       Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedLHS, Depth + 1);
3966     if (!!DemandedRHS) {
3967       Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedRHS, Depth + 1);
3968       Tmp = std::min(Tmp, Tmp2);
3969     }
3970     // If we don't know anything, early out and try computeKnownBits fall-back.
3971     if (Tmp == 1)
3972       break;
3973     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
3974     return Tmp;
3975   }
3976 
3977   case ISD::BITCAST: {
3978     SDValue N0 = Op.getOperand(0);
3979     EVT SrcVT = N0.getValueType();
3980     unsigned SrcBits = SrcVT.getScalarSizeInBits();
3981 
3982     // Ignore bitcasts from unsupported types..
3983     if (!(SrcVT.isInteger() || SrcVT.isFloatingPoint()))
3984       break;
3985 
3986     // Fast handling of 'identity' bitcasts.
3987     if (VTBits == SrcBits)
3988       return ComputeNumSignBits(N0, DemandedElts, Depth + 1);
3989 
3990     bool IsLE = getDataLayout().isLittleEndian();
3991 
3992     // Bitcast 'large element' scalar/vector to 'small element' vector.
3993     if ((SrcBits % VTBits) == 0) {
3994       assert(VT.isVector() && "Expected bitcast to vector");
3995 
3996       unsigned Scale = SrcBits / VTBits;
3997       APInt SrcDemandedElts =
3998           APIntOps::ScaleBitMask(DemandedElts, NumElts / Scale);
3999 
4000       // Fast case - sign splat can be simply split across the small elements.
4001       Tmp = ComputeNumSignBits(N0, SrcDemandedElts, Depth + 1);
4002       if (Tmp == SrcBits)
4003         return VTBits;
4004 
4005       // Slow case - determine how far the sign extends into each sub-element.
4006       Tmp2 = VTBits;
4007       for (unsigned i = 0; i != NumElts; ++i)
4008         if (DemandedElts[i]) {
4009           unsigned SubOffset = i % Scale;
4010           SubOffset = (IsLE ? ((Scale - 1) - SubOffset) : SubOffset);
4011           SubOffset = SubOffset * VTBits;
4012           if (Tmp <= SubOffset)
4013             return 1;
4014           Tmp2 = std::min(Tmp2, Tmp - SubOffset);
4015         }
4016       return Tmp2;
4017     }
4018     break;
4019   }
4020 
4021   case ISD::FP_TO_SINT_SAT:
4022     // FP_TO_SINT_SAT produces a signed value that fits in the saturating VT.
4023     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
4024     return VTBits - Tmp + 1;
4025   case ISD::SIGN_EXTEND:
4026     Tmp = VTBits - Op.getOperand(0).getScalarValueSizeInBits();
4027     return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1) + Tmp;
4028   case ISD::SIGN_EXTEND_INREG:
4029     // Max of the input and what this extends.
4030     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
4031     Tmp = VTBits-Tmp+1;
4032     Tmp2 = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
4033     return std::max(Tmp, Tmp2);
4034   case ISD::SIGN_EXTEND_VECTOR_INREG: {
4035     SDValue Src = Op.getOperand(0);
4036     EVT SrcVT = Src.getValueType();
4037     APInt DemandedSrcElts = DemandedElts.zext(SrcVT.getVectorNumElements());
4038     Tmp = VTBits - SrcVT.getScalarSizeInBits();
4039     return ComputeNumSignBits(Src, DemandedSrcElts, Depth+1) + Tmp;
4040   }
4041   case ISD::SRA:
4042     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4043     // SRA X, C -> adds C sign bits.
4044     if (const APInt *ShAmt =
4045             getValidMinimumShiftAmountConstant(Op, DemandedElts))
4046       Tmp = std::min<uint64_t>(Tmp + ShAmt->getZExtValue(), VTBits);
4047     return Tmp;
4048   case ISD::SHL:
4049     if (const APInt *ShAmt =
4050             getValidMaximumShiftAmountConstant(Op, DemandedElts)) {
4051       // shl destroys sign bits, ensure it doesn't shift out all sign bits.
4052       Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4053       if (ShAmt->ult(Tmp))
4054         return Tmp - ShAmt->getZExtValue();
4055     }
4056     break;
4057   case ISD::AND:
4058   case ISD::OR:
4059   case ISD::XOR:    // NOT is handled here.
4060     // Logical binary ops preserve the number of sign bits at the worst.
4061     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
4062     if (Tmp != 1) {
4063       Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
4064       FirstAnswer = std::min(Tmp, Tmp2);
4065       // We computed what we know about the sign bits as our first
4066       // answer. Now proceed to the generic code that uses
4067       // computeKnownBits, and pick whichever answer is better.
4068     }
4069     break;
4070 
4071   case ISD::SELECT:
4072   case ISD::VSELECT:
4073     Tmp = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
4074     if (Tmp == 1) return 1;  // Early out.
4075     Tmp2 = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
4076     return std::min(Tmp, Tmp2);
4077   case ISD::SELECT_CC:
4078     Tmp = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
4079     if (Tmp == 1) return 1;  // Early out.
4080     Tmp2 = ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth+1);
4081     return std::min(Tmp, Tmp2);
4082 
4083   case ISD::SMIN:
4084   case ISD::SMAX: {
4085     // If we have a clamp pattern, we know that the number of sign bits will be
4086     // the minimum of the clamp min/max range.
4087     bool IsMax = (Opcode == ISD::SMAX);
4088     ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
4089     if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
4090       if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
4091         CstHigh =
4092             isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
4093     if (CstLow && CstHigh) {
4094       if (!IsMax)
4095         std::swap(CstLow, CstHigh);
4096       if (CstLow->getAPIntValue().sle(CstHigh->getAPIntValue())) {
4097         Tmp = CstLow->getAPIntValue().getNumSignBits();
4098         Tmp2 = CstHigh->getAPIntValue().getNumSignBits();
4099         return std::min(Tmp, Tmp2);
4100       }
4101     }
4102 
4103     // Fallback - just get the minimum number of sign bits of the operands.
4104     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4105     if (Tmp == 1)
4106       return 1;  // Early out.
4107     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
4108     return std::min(Tmp, Tmp2);
4109   }
4110   case ISD::UMIN:
4111   case ISD::UMAX:
4112     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4113     if (Tmp == 1)
4114       return 1;  // Early out.
4115     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
4116     return std::min(Tmp, Tmp2);
4117   case ISD::SADDO:
4118   case ISD::UADDO:
4119   case ISD::SADDO_CARRY:
4120   case ISD::ADDCARRY:
4121   case ISD::SSUBO:
4122   case ISD::USUBO:
4123   case ISD::SSUBO_CARRY:
4124   case ISD::SUBCARRY:
4125   case ISD::SMULO:
4126   case ISD::UMULO:
4127     if (Op.getResNo() != 1)
4128       break;
4129     // The boolean result conforms to getBooleanContents.  Fall through.
4130     // If setcc returns 0/-1, all bits are sign bits.
4131     // We know that we have an integer-based boolean since these operations
4132     // are only available for integer.
4133     if (TLI->getBooleanContents(VT.isVector(), false) ==
4134         TargetLowering::ZeroOrNegativeOneBooleanContent)
4135       return VTBits;
4136     break;
4137   case ISD::SETCC:
4138   case ISD::SETCCCARRY:
4139   case ISD::STRICT_FSETCC:
4140   case ISD::STRICT_FSETCCS: {
4141     unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
4142     // If setcc returns 0/-1, all bits are sign bits.
4143     if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
4144         TargetLowering::ZeroOrNegativeOneBooleanContent)
4145       return VTBits;
4146     break;
4147   }
4148   case ISD::ROTL:
4149   case ISD::ROTR:
4150     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4151 
4152     // If we're rotating an 0/-1 value, then it stays an 0/-1 value.
4153     if (Tmp == VTBits)
4154       return VTBits;
4155 
4156     if (ConstantSDNode *C =
4157             isConstOrConstSplat(Op.getOperand(1), DemandedElts)) {
4158       unsigned RotAmt = C->getAPIntValue().urem(VTBits);
4159 
4160       // Handle rotate right by N like a rotate left by 32-N.
4161       if (Opcode == ISD::ROTR)
4162         RotAmt = (VTBits - RotAmt) % VTBits;
4163 
4164       // If we aren't rotating out all of the known-in sign bits, return the
4165       // number that are left.  This handles rotl(sext(x), 1) for example.
4166       if (Tmp > (RotAmt + 1)) return (Tmp - RotAmt);
4167     }
4168     break;
4169   case ISD::ADD:
4170   case ISD::ADDC:
4171     // Add can have at most one carry bit.  Thus we know that the output
4172     // is, at worst, one more bit than the inputs.
4173     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4174     if (Tmp == 1) return 1; // Early out.
4175 
4176     // Special case decrementing a value (ADD X, -1):
4177     if (ConstantSDNode *CRHS =
4178             isConstOrConstSplat(Op.getOperand(1), DemandedElts))
4179       if (CRHS->isAllOnes()) {
4180         KnownBits Known =
4181             computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4182 
4183         // If the input is known to be 0 or 1, the output is 0/-1, which is all
4184         // sign bits set.
4185         if ((Known.Zero | 1).isAllOnes())
4186           return VTBits;
4187 
4188         // If we are subtracting one from a positive number, there is no carry
4189         // out of the result.
4190         if (Known.isNonNegative())
4191           return Tmp;
4192       }
4193 
4194     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
4195     if (Tmp2 == 1) return 1; // Early out.
4196     return std::min(Tmp, Tmp2) - 1;
4197   case ISD::SUB:
4198     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
4199     if (Tmp2 == 1) return 1; // Early out.
4200 
4201     // Handle NEG.
4202     if (ConstantSDNode *CLHS =
4203             isConstOrConstSplat(Op.getOperand(0), DemandedElts))
4204       if (CLHS->isZero()) {
4205         KnownBits Known =
4206             computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4207         // If the input is known to be 0 or 1, the output is 0/-1, which is all
4208         // sign bits set.
4209         if ((Known.Zero | 1).isAllOnes())
4210           return VTBits;
4211 
4212         // If the input is known to be positive (the sign bit is known clear),
4213         // the output of the NEG has the same number of sign bits as the input.
4214         if (Known.isNonNegative())
4215           return Tmp2;
4216 
4217         // Otherwise, we treat this like a SUB.
4218       }
4219 
4220     // Sub can have at most one carry bit.  Thus we know that the output
4221     // is, at worst, one more bit than the inputs.
4222     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4223     if (Tmp == 1) return 1; // Early out.
4224     return std::min(Tmp, Tmp2) - 1;
4225   case ISD::MUL: {
4226     // The output of the Mul can be at most twice the valid bits in the inputs.
4227     unsigned SignBitsOp0 = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
4228     if (SignBitsOp0 == 1)
4229       break;
4230     unsigned SignBitsOp1 = ComputeNumSignBits(Op.getOperand(1), Depth + 1);
4231     if (SignBitsOp1 == 1)
4232       break;
4233     unsigned OutValidBits =
4234         (VTBits - SignBitsOp0 + 1) + (VTBits - SignBitsOp1 + 1);
4235     return OutValidBits > VTBits ? 1 : VTBits - OutValidBits + 1;
4236   }
4237   case ISD::SREM:
4238     // The sign bit is the LHS's sign bit, except when the result of the
4239     // remainder is zero. The magnitude of the result should be less than or
4240     // equal to the magnitude of the LHS. Therefore, the result should have
4241     // at least as many sign bits as the left hand side.
4242     return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4243   case ISD::TRUNCATE: {
4244     // Check if the sign bits of source go down as far as the truncated value.
4245     unsigned NumSrcBits = Op.getOperand(0).getScalarValueSizeInBits();
4246     unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
4247     if (NumSrcSignBits > (NumSrcBits - VTBits))
4248       return NumSrcSignBits - (NumSrcBits - VTBits);
4249     break;
4250   }
4251   case ISD::EXTRACT_ELEMENT: {
4252     const int KnownSign = ComputeNumSignBits(Op.getOperand(0), Depth+1);
4253     const int BitWidth = Op.getValueSizeInBits();
4254     const int Items = Op.getOperand(0).getValueSizeInBits() / BitWidth;
4255 
4256     // Get reverse index (starting from 1), Op1 value indexes elements from
4257     // little end. Sign starts at big end.
4258     const int rIndex = Items - 1 - Op.getConstantOperandVal(1);
4259 
4260     // If the sign portion ends in our element the subtraction gives correct
4261     // result. Otherwise it gives either negative or > bitwidth result
4262     return std::max(std::min(KnownSign - rIndex * BitWidth, BitWidth), 0);
4263   }
4264   case ISD::INSERT_VECTOR_ELT: {
4265     // If we know the element index, split the demand between the
4266     // source vector and the inserted element, otherwise assume we need
4267     // the original demanded vector elements and the value.
4268     SDValue InVec = Op.getOperand(0);
4269     SDValue InVal = Op.getOperand(1);
4270     SDValue EltNo = Op.getOperand(2);
4271     bool DemandedVal = true;
4272     APInt DemandedVecElts = DemandedElts;
4273     auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
4274     if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
4275       unsigned EltIdx = CEltNo->getZExtValue();
4276       DemandedVal = !!DemandedElts[EltIdx];
4277       DemandedVecElts.clearBit(EltIdx);
4278     }
4279     Tmp = std::numeric_limits<unsigned>::max();
4280     if (DemandedVal) {
4281       // TODO - handle implicit truncation of inserted elements.
4282       if (InVal.getScalarValueSizeInBits() != VTBits)
4283         break;
4284       Tmp2 = ComputeNumSignBits(InVal, Depth + 1);
4285       Tmp = std::min(Tmp, Tmp2);
4286     }
4287     if (!!DemandedVecElts) {
4288       Tmp2 = ComputeNumSignBits(InVec, DemandedVecElts, Depth + 1);
4289       Tmp = std::min(Tmp, Tmp2);
4290     }
4291     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
4292     return Tmp;
4293   }
4294   case ISD::EXTRACT_VECTOR_ELT: {
4295     SDValue InVec = Op.getOperand(0);
4296     SDValue EltNo = Op.getOperand(1);
4297     EVT VecVT = InVec.getValueType();
4298     // ComputeNumSignBits not yet implemented for scalable vectors.
4299     if (VecVT.isScalableVector())
4300       break;
4301     const unsigned BitWidth = Op.getValueSizeInBits();
4302     const unsigned EltBitWidth = Op.getOperand(0).getScalarValueSizeInBits();
4303     const unsigned NumSrcElts = VecVT.getVectorNumElements();
4304 
4305     // If BitWidth > EltBitWidth the value is anyext:ed, and we do not know
4306     // anything about sign bits. But if the sizes match we can derive knowledge
4307     // about sign bits from the vector operand.
4308     if (BitWidth != EltBitWidth)
4309       break;
4310 
4311     // If we know the element index, just demand that vector element, else for
4312     // an unknown element index, ignore DemandedElts and demand them all.
4313     APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
4314     auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
4315     if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
4316       DemandedSrcElts =
4317           APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
4318 
4319     return ComputeNumSignBits(InVec, DemandedSrcElts, Depth + 1);
4320   }
4321   case ISD::EXTRACT_SUBVECTOR: {
4322     // Offset the demanded elts by the subvector index.
4323     SDValue Src = Op.getOperand(0);
4324     // Bail until we can represent demanded elements for scalable vectors.
4325     if (Src.getValueType().isScalableVector())
4326       break;
4327     uint64_t Idx = Op.getConstantOperandVal(1);
4328     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
4329     APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
4330     return ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
4331   }
4332   case ISD::CONCAT_VECTORS: {
4333     // Determine the minimum number of sign bits across all demanded
4334     // elts of the input vectors. Early out if the result is already 1.
4335     Tmp = std::numeric_limits<unsigned>::max();
4336     EVT SubVectorVT = Op.getOperand(0).getValueType();
4337     unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
4338     unsigned NumSubVectors = Op.getNumOperands();
4339     for (unsigned i = 0; (i < NumSubVectors) && (Tmp > 1); ++i) {
4340       APInt DemandedSub =
4341           DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts);
4342       if (!DemandedSub)
4343         continue;
4344       Tmp2 = ComputeNumSignBits(Op.getOperand(i), DemandedSub, Depth + 1);
4345       Tmp = std::min(Tmp, Tmp2);
4346     }
4347     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
4348     return Tmp;
4349   }
4350   case ISD::INSERT_SUBVECTOR: {
4351     // Demand any elements from the subvector and the remainder from the src its
4352     // inserted into.
4353     SDValue Src = Op.getOperand(0);
4354     SDValue Sub = Op.getOperand(1);
4355     uint64_t Idx = Op.getConstantOperandVal(2);
4356     unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
4357     APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
4358     APInt DemandedSrcElts = DemandedElts;
4359     DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx);
4360 
4361     Tmp = std::numeric_limits<unsigned>::max();
4362     if (!!DemandedSubElts) {
4363       Tmp = ComputeNumSignBits(Sub, DemandedSubElts, Depth + 1);
4364       if (Tmp == 1)
4365         return 1; // early-out
4366     }
4367     if (!!DemandedSrcElts) {
4368       Tmp2 = ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
4369       Tmp = std::min(Tmp, Tmp2);
4370     }
4371     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
4372     return Tmp;
4373   }
4374   case ISD::ATOMIC_CMP_SWAP:
4375   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
4376   case ISD::ATOMIC_SWAP:
4377   case ISD::ATOMIC_LOAD_ADD:
4378   case ISD::ATOMIC_LOAD_SUB:
4379   case ISD::ATOMIC_LOAD_AND:
4380   case ISD::ATOMIC_LOAD_CLR:
4381   case ISD::ATOMIC_LOAD_OR:
4382   case ISD::ATOMIC_LOAD_XOR:
4383   case ISD::ATOMIC_LOAD_NAND:
4384   case ISD::ATOMIC_LOAD_MIN:
4385   case ISD::ATOMIC_LOAD_MAX:
4386   case ISD::ATOMIC_LOAD_UMIN:
4387   case ISD::ATOMIC_LOAD_UMAX:
4388   case ISD::ATOMIC_LOAD: {
4389     Tmp = cast<AtomicSDNode>(Op)->getMemoryVT().getScalarSizeInBits();
4390     // If we are looking at the loaded value.
4391     if (Op.getResNo() == 0) {
4392       if (Tmp == VTBits)
4393         return 1; // early-out
4394       if (TLI->getExtendForAtomicOps() == ISD::SIGN_EXTEND)
4395         return VTBits - Tmp + 1;
4396       if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND)
4397         return VTBits - Tmp;
4398     }
4399     break;
4400   }
4401   }
4402 
4403   // If we are looking at the loaded value of the SDNode.
4404   if (Op.getResNo() == 0) {
4405     // Handle LOADX separately here. EXTLOAD case will fallthrough.
4406     if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
4407       unsigned ExtType = LD->getExtensionType();
4408       switch (ExtType) {
4409       default: break;
4410       case ISD::SEXTLOAD: // e.g. i16->i32 = '17' bits known.
4411         Tmp = LD->getMemoryVT().getScalarSizeInBits();
4412         return VTBits - Tmp + 1;
4413       case ISD::ZEXTLOAD: // e.g. i16->i32 = '16' bits known.
4414         Tmp = LD->getMemoryVT().getScalarSizeInBits();
4415         return VTBits - Tmp;
4416       case ISD::NON_EXTLOAD:
4417         if (const Constant *Cst = TLI->getTargetConstantFromLoad(LD)) {
4418           // We only need to handle vectors - computeKnownBits should handle
4419           // scalar cases.
4420           Type *CstTy = Cst->getType();
4421           if (CstTy->isVectorTy() &&
4422               (NumElts * VTBits) == CstTy->getPrimitiveSizeInBits() &&
4423               VTBits == CstTy->getScalarSizeInBits()) {
4424             Tmp = VTBits;
4425             for (unsigned i = 0; i != NumElts; ++i) {
4426               if (!DemandedElts[i])
4427                 continue;
4428               if (Constant *Elt = Cst->getAggregateElement(i)) {
4429                 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
4430                   const APInt &Value = CInt->getValue();
4431                   Tmp = std::min(Tmp, Value.getNumSignBits());
4432                   continue;
4433                 }
4434                 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
4435                   APInt Value = CFP->getValueAPF().bitcastToAPInt();
4436                   Tmp = std::min(Tmp, Value.getNumSignBits());
4437                   continue;
4438                 }
4439               }
4440               // Unknown type. Conservatively assume no bits match sign bit.
4441               return 1;
4442             }
4443             return Tmp;
4444           }
4445         }
4446         break;
4447       }
4448     }
4449   }
4450 
4451   // Allow the target to implement this method for its nodes.
4452   if (Opcode >= ISD::BUILTIN_OP_END ||
4453       Opcode == ISD::INTRINSIC_WO_CHAIN ||
4454       Opcode == ISD::INTRINSIC_W_CHAIN ||
4455       Opcode == ISD::INTRINSIC_VOID) {
4456     unsigned NumBits =
4457         TLI->ComputeNumSignBitsForTargetNode(Op, DemandedElts, *this, Depth);
4458     if (NumBits > 1)
4459       FirstAnswer = std::max(FirstAnswer, NumBits);
4460   }
4461 
4462   // Finally, if we can prove that the top bits of the result are 0's or 1's,
4463   // use this information.
4464   KnownBits Known = computeKnownBits(Op, DemandedElts, Depth);
4465   return std::max(FirstAnswer, Known.countMinSignBits());
4466 }
4467 
4468 unsigned SelectionDAG::ComputeMaxSignificantBits(SDValue Op,
4469                                                  unsigned Depth) const {
4470   unsigned SignBits = ComputeNumSignBits(Op, Depth);
4471   return Op.getScalarValueSizeInBits() - SignBits + 1;
4472 }
4473 
4474 unsigned SelectionDAG::ComputeMaxSignificantBits(SDValue Op,
4475                                                  const APInt &DemandedElts,
4476                                                  unsigned Depth) const {
4477   unsigned SignBits = ComputeNumSignBits(Op, DemandedElts, Depth);
4478   return Op.getScalarValueSizeInBits() - SignBits + 1;
4479 }
4480 
4481 bool SelectionDAG::isGuaranteedNotToBeUndefOrPoison(SDValue Op, bool PoisonOnly,
4482                                                     unsigned Depth) const {
4483   // Early out for FREEZE.
4484   if (Op.getOpcode() == ISD::FREEZE)
4485     return true;
4486 
4487   // TODO: Assume we don't know anything for now.
4488   EVT VT = Op.getValueType();
4489   if (VT.isScalableVector())
4490     return false;
4491 
4492   APInt DemandedElts = VT.isVector()
4493                            ? APInt::getAllOnes(VT.getVectorNumElements())
4494                            : APInt(1, 1);
4495   return isGuaranteedNotToBeUndefOrPoison(Op, DemandedElts, PoisonOnly, Depth);
4496 }
4497 
4498 bool SelectionDAG::isGuaranteedNotToBeUndefOrPoison(SDValue Op,
4499                                                     const APInt &DemandedElts,
4500                                                     bool PoisonOnly,
4501                                                     unsigned Depth) const {
4502   unsigned Opcode = Op.getOpcode();
4503 
4504   // Early out for FREEZE.
4505   if (Opcode == ISD::FREEZE)
4506     return true;
4507 
4508   if (Depth >= MaxRecursionDepth)
4509     return false; // Limit search depth.
4510 
4511   if (isIntOrFPConstant(Op))
4512     return true;
4513 
4514   switch (Opcode) {
4515   case ISD::UNDEF:
4516     return PoisonOnly;
4517 
4518   case ISD::BUILD_VECTOR:
4519     // NOTE: BUILD_VECTOR has implicit truncation of wider scalar elements -
4520     // this shouldn't affect the result.
4521     for (unsigned i = 0, e = Op.getNumOperands(); i < e; ++i) {
4522       if (!DemandedElts[i])
4523         continue;
4524       if (!isGuaranteedNotToBeUndefOrPoison(Op.getOperand(i), PoisonOnly,
4525                                             Depth + 1))
4526         return false;
4527     }
4528     return true;
4529 
4530   // TODO: Search for noundef attributes from library functions.
4531 
4532   // TODO: Pointers dereferenced by ISD::LOAD/STORE ops are noundef.
4533 
4534   default:
4535     // Allow the target to implement this method for its nodes.
4536     if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
4537         Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID)
4538       return TLI->isGuaranteedNotToBeUndefOrPoisonForTargetNode(
4539           Op, DemandedElts, *this, PoisonOnly, Depth);
4540     break;
4541   }
4542 
4543   return false;
4544 }
4545 
4546 bool SelectionDAG::isBaseWithConstantOffset(SDValue Op) const {
4547   if ((Op.getOpcode() != ISD::ADD && Op.getOpcode() != ISD::OR) ||
4548       !isa<ConstantSDNode>(Op.getOperand(1)))
4549     return false;
4550 
4551   if (Op.getOpcode() == ISD::OR &&
4552       !MaskedValueIsZero(Op.getOperand(0), Op.getConstantOperandAPInt(1)))
4553     return false;
4554 
4555   return true;
4556 }
4557 
4558 bool SelectionDAG::isKnownNeverNaN(SDValue Op, bool SNaN, unsigned Depth) const {
4559   // If we're told that NaNs won't happen, assume they won't.
4560   if (getTarget().Options.NoNaNsFPMath || Op->getFlags().hasNoNaNs())
4561     return true;
4562 
4563   if (Depth >= MaxRecursionDepth)
4564     return false; // Limit search depth.
4565 
4566   // TODO: Handle vectors.
4567   // If the value is a constant, we can obviously see if it is a NaN or not.
4568   if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) {
4569     return !C->getValueAPF().isNaN() ||
4570            (SNaN && !C->getValueAPF().isSignaling());
4571   }
4572 
4573   unsigned Opcode = Op.getOpcode();
4574   switch (Opcode) {
4575   case ISD::FADD:
4576   case ISD::FSUB:
4577   case ISD::FMUL:
4578   case ISD::FDIV:
4579   case ISD::FREM:
4580   case ISD::FSIN:
4581   case ISD::FCOS: {
4582     if (SNaN)
4583       return true;
4584     // TODO: Need isKnownNeverInfinity
4585     return false;
4586   }
4587   case ISD::FCANONICALIZE:
4588   case ISD::FEXP:
4589   case ISD::FEXP2:
4590   case ISD::FTRUNC:
4591   case ISD::FFLOOR:
4592   case ISD::FCEIL:
4593   case ISD::FROUND:
4594   case ISD::FROUNDEVEN:
4595   case ISD::FRINT:
4596   case ISD::FNEARBYINT: {
4597     if (SNaN)
4598       return true;
4599     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4600   }
4601   case ISD::FABS:
4602   case ISD::FNEG:
4603   case ISD::FCOPYSIGN: {
4604     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4605   }
4606   case ISD::SELECT:
4607     return isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) &&
4608            isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1);
4609   case ISD::FP_EXTEND:
4610   case ISD::FP_ROUND: {
4611     if (SNaN)
4612       return true;
4613     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4614   }
4615   case ISD::SINT_TO_FP:
4616   case ISD::UINT_TO_FP:
4617     return true;
4618   case ISD::FMA:
4619   case ISD::FMAD: {
4620     if (SNaN)
4621       return true;
4622     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) &&
4623            isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) &&
4624            isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1);
4625   }
4626   case ISD::FSQRT: // Need is known positive
4627   case ISD::FLOG:
4628   case ISD::FLOG2:
4629   case ISD::FLOG10:
4630   case ISD::FPOWI:
4631   case ISD::FPOW: {
4632     if (SNaN)
4633       return true;
4634     // TODO: Refine on operand
4635     return false;
4636   }
4637   case ISD::FMINNUM:
4638   case ISD::FMAXNUM: {
4639     // Only one needs to be known not-nan, since it will be returned if the
4640     // other ends up being one.
4641     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) ||
4642            isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1);
4643   }
4644   case ISD::FMINNUM_IEEE:
4645   case ISD::FMAXNUM_IEEE: {
4646     if (SNaN)
4647       return true;
4648     // This can return a NaN if either operand is an sNaN, or if both operands
4649     // are NaN.
4650     return (isKnownNeverNaN(Op.getOperand(0), false, Depth + 1) &&
4651             isKnownNeverSNaN(Op.getOperand(1), Depth + 1)) ||
4652            (isKnownNeverNaN(Op.getOperand(1), false, Depth + 1) &&
4653             isKnownNeverSNaN(Op.getOperand(0), Depth + 1));
4654   }
4655   case ISD::FMINIMUM:
4656   case ISD::FMAXIMUM: {
4657     // TODO: Does this quiet or return the origina NaN as-is?
4658     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) &&
4659            isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1);
4660   }
4661   case ISD::EXTRACT_VECTOR_ELT: {
4662     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4663   }
4664   default:
4665     if (Opcode >= ISD::BUILTIN_OP_END ||
4666         Opcode == ISD::INTRINSIC_WO_CHAIN ||
4667         Opcode == ISD::INTRINSIC_W_CHAIN ||
4668         Opcode == ISD::INTRINSIC_VOID) {
4669       return TLI->isKnownNeverNaNForTargetNode(Op, *this, SNaN, Depth);
4670     }
4671 
4672     return false;
4673   }
4674 }
4675 
4676 bool SelectionDAG::isKnownNeverZeroFloat(SDValue Op) const {
4677   assert(Op.getValueType().isFloatingPoint() &&
4678          "Floating point type expected");
4679 
4680   // If the value is a constant, we can obviously see if it is a zero or not.
4681   // TODO: Add BuildVector support.
4682   if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
4683     return !C->isZero();
4684   return false;
4685 }
4686 
4687 bool SelectionDAG::isKnownNeverZero(SDValue Op) const {
4688   assert(!Op.getValueType().isFloatingPoint() &&
4689          "Floating point types unsupported - use isKnownNeverZeroFloat");
4690 
4691   // If the value is a constant, we can obviously see if it is a zero or not.
4692   if (ISD::matchUnaryPredicate(Op,
4693                                [](ConstantSDNode *C) { return !C->isZero(); }))
4694     return true;
4695 
4696   // TODO: Recognize more cases here.
4697   switch (Op.getOpcode()) {
4698   default: break;
4699   case ISD::OR:
4700     if (isKnownNeverZero(Op.getOperand(1)) ||
4701         isKnownNeverZero(Op.getOperand(0)))
4702       return true;
4703     break;
4704   }
4705 
4706   return false;
4707 }
4708 
4709 bool SelectionDAG::isEqualTo(SDValue A, SDValue B) const {
4710   // Check the obvious case.
4711   if (A == B) return true;
4712 
4713   // For for negative and positive zero.
4714   if (const ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A))
4715     if (const ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B))
4716       if (CA->isZero() && CB->isZero()) return true;
4717 
4718   // Otherwise they may not be equal.
4719   return false;
4720 }
4721 
4722 // Only bits set in Mask must be negated, other bits may be arbitrary.
4723 SDValue llvm::getBitwiseNotOperand(SDValue V, SDValue Mask, bool AllowUndefs) {
4724   if (isBitwiseNot(V, AllowUndefs))
4725     return V.getOperand(0);
4726 
4727   // Handle any_extend (not (truncate X)) pattern, where Mask only sets
4728   // bits in the non-extended part.
4729   ConstantSDNode *MaskC = isConstOrConstSplat(Mask);
4730   if (!MaskC || V.getOpcode() != ISD::ANY_EXTEND)
4731     return SDValue();
4732   SDValue ExtArg = V.getOperand(0);
4733   if (ExtArg.getScalarValueSizeInBits() >=
4734           MaskC->getAPIntValue().getActiveBits() &&
4735       isBitwiseNot(ExtArg, AllowUndefs) &&
4736       ExtArg.getOperand(0).getOpcode() == ISD::TRUNCATE &&
4737       ExtArg.getOperand(0).getOperand(0).getValueType() == V.getValueType())
4738     return ExtArg.getOperand(0).getOperand(0);
4739   return SDValue();
4740 }
4741 
4742 static bool haveNoCommonBitsSetCommutative(SDValue A, SDValue B) {
4743   // Match masked merge pattern (X & ~M) op (Y & M)
4744   // Including degenerate case (X & ~M) op M
4745   auto MatchNoCommonBitsPattern = [&](SDValue Not, SDValue Mask,
4746                                       SDValue Other) {
4747     if (SDValue NotOperand =
4748             getBitwiseNotOperand(Not, Mask, /* AllowUndefs */ true)) {
4749       if (Other == NotOperand)
4750         return true;
4751       if (Other->getOpcode() == ISD::AND)
4752         return NotOperand == Other->getOperand(0) ||
4753                NotOperand == Other->getOperand(1);
4754     }
4755     return false;
4756   };
4757   if (A->getOpcode() == ISD::AND)
4758     return MatchNoCommonBitsPattern(A->getOperand(0), A->getOperand(1), B) ||
4759            MatchNoCommonBitsPattern(A->getOperand(1), A->getOperand(0), B);
4760   return false;
4761 }
4762 
4763 // FIXME: unify with llvm::haveNoCommonBitsSet.
4764 bool SelectionDAG::haveNoCommonBitsSet(SDValue A, SDValue B) const {
4765   assert(A.getValueType() == B.getValueType() &&
4766          "Values must have the same type");
4767   if (haveNoCommonBitsSetCommutative(A, B) ||
4768       haveNoCommonBitsSetCommutative(B, A))
4769     return true;
4770   return KnownBits::haveNoCommonBitsSet(computeKnownBits(A),
4771                                         computeKnownBits(B));
4772 }
4773 
4774 static SDValue FoldSTEP_VECTOR(const SDLoc &DL, EVT VT, SDValue Step,
4775                                SelectionDAG &DAG) {
4776   if (cast<ConstantSDNode>(Step)->isZero())
4777     return DAG.getConstant(0, DL, VT);
4778 
4779   return SDValue();
4780 }
4781 
4782 static SDValue FoldBUILD_VECTOR(const SDLoc &DL, EVT VT,
4783                                 ArrayRef<SDValue> Ops,
4784                                 SelectionDAG &DAG) {
4785   int NumOps = Ops.size();
4786   assert(NumOps != 0 && "Can't build an empty vector!");
4787   assert(!VT.isScalableVector() &&
4788          "BUILD_VECTOR cannot be used with scalable types");
4789   assert(VT.getVectorNumElements() == (unsigned)NumOps &&
4790          "Incorrect element count in BUILD_VECTOR!");
4791 
4792   // BUILD_VECTOR of UNDEFs is UNDEF.
4793   if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
4794     return DAG.getUNDEF(VT);
4795 
4796   // BUILD_VECTOR of seq extract/insert from the same vector + type is Identity.
4797   SDValue IdentitySrc;
4798   bool IsIdentity = true;
4799   for (int i = 0; i != NumOps; ++i) {
4800     if (Ops[i].getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4801         Ops[i].getOperand(0).getValueType() != VT ||
4802         (IdentitySrc && Ops[i].getOperand(0) != IdentitySrc) ||
4803         !isa<ConstantSDNode>(Ops[i].getOperand(1)) ||
4804         cast<ConstantSDNode>(Ops[i].getOperand(1))->getAPIntValue() != i) {
4805       IsIdentity = false;
4806       break;
4807     }
4808     IdentitySrc = Ops[i].getOperand(0);
4809   }
4810   if (IsIdentity)
4811     return IdentitySrc;
4812 
4813   return SDValue();
4814 }
4815 
4816 /// Try to simplify vector concatenation to an input value, undef, or build
4817 /// vector.
4818 static SDValue foldCONCAT_VECTORS(const SDLoc &DL, EVT VT,
4819                                   ArrayRef<SDValue> Ops,
4820                                   SelectionDAG &DAG) {
4821   assert(!Ops.empty() && "Can't concatenate an empty list of vectors!");
4822   assert(llvm::all_of(Ops,
4823                       [Ops](SDValue Op) {
4824                         return Ops[0].getValueType() == Op.getValueType();
4825                       }) &&
4826          "Concatenation of vectors with inconsistent value types!");
4827   assert((Ops[0].getValueType().getVectorElementCount() * Ops.size()) ==
4828              VT.getVectorElementCount() &&
4829          "Incorrect element count in vector concatenation!");
4830 
4831   if (Ops.size() == 1)
4832     return Ops[0];
4833 
4834   // Concat of UNDEFs is UNDEF.
4835   if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
4836     return DAG.getUNDEF(VT);
4837 
4838   // Scan the operands and look for extract operations from a single source
4839   // that correspond to insertion at the same location via this concatenation:
4840   // concat (extract X, 0*subvec_elts), (extract X, 1*subvec_elts), ...
4841   SDValue IdentitySrc;
4842   bool IsIdentity = true;
4843   for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
4844     SDValue Op = Ops[i];
4845     unsigned IdentityIndex = i * Op.getValueType().getVectorMinNumElements();
4846     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
4847         Op.getOperand(0).getValueType() != VT ||
4848         (IdentitySrc && Op.getOperand(0) != IdentitySrc) ||
4849         Op.getConstantOperandVal(1) != IdentityIndex) {
4850       IsIdentity = false;
4851       break;
4852     }
4853     assert((!IdentitySrc || IdentitySrc == Op.getOperand(0)) &&
4854            "Unexpected identity source vector for concat of extracts");
4855     IdentitySrc = Op.getOperand(0);
4856   }
4857   if (IsIdentity) {
4858     assert(IdentitySrc && "Failed to set source vector of extracts");
4859     return IdentitySrc;
4860   }
4861 
4862   // The code below this point is only designed to work for fixed width
4863   // vectors, so we bail out for now.
4864   if (VT.isScalableVector())
4865     return SDValue();
4866 
4867   // A CONCAT_VECTOR with all UNDEF/BUILD_VECTOR operands can be
4868   // simplified to one big BUILD_VECTOR.
4869   // FIXME: Add support for SCALAR_TO_VECTOR as well.
4870   EVT SVT = VT.getScalarType();
4871   SmallVector<SDValue, 16> Elts;
4872   for (SDValue Op : Ops) {
4873     EVT OpVT = Op.getValueType();
4874     if (Op.isUndef())
4875       Elts.append(OpVT.getVectorNumElements(), DAG.getUNDEF(SVT));
4876     else if (Op.getOpcode() == ISD::BUILD_VECTOR)
4877       Elts.append(Op->op_begin(), Op->op_end());
4878     else
4879       return SDValue();
4880   }
4881 
4882   // BUILD_VECTOR requires all inputs to be of the same type, find the
4883   // maximum type and extend them all.
4884   for (SDValue Op : Elts)
4885     SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
4886 
4887   if (SVT.bitsGT(VT.getScalarType())) {
4888     for (SDValue &Op : Elts) {
4889       if (Op.isUndef())
4890         Op = DAG.getUNDEF(SVT);
4891       else
4892         Op = DAG.getTargetLoweringInfo().isZExtFree(Op.getValueType(), SVT)
4893                  ? DAG.getZExtOrTrunc(Op, DL, SVT)
4894                  : DAG.getSExtOrTrunc(Op, DL, SVT);
4895     }
4896   }
4897 
4898   SDValue V = DAG.getBuildVector(VT, DL, Elts);
4899   NewSDValueDbgMsg(V, "New node fold concat vectors: ", &DAG);
4900   return V;
4901 }
4902 
4903 /// Gets or creates the specified node.
4904 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT) {
4905   FoldingSetNodeID ID;
4906   AddNodeIDNode(ID, Opcode, getVTList(VT), None);
4907   void *IP = nullptr;
4908   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
4909     return SDValue(E, 0);
4910 
4911   auto *N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(),
4912                               getVTList(VT));
4913   CSEMap.InsertNode(N, IP);
4914 
4915   InsertNode(N);
4916   SDValue V = SDValue(N, 0);
4917   NewSDValueDbgMsg(V, "Creating new node: ", this);
4918   return V;
4919 }
4920 
4921 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4922                               SDValue Operand) {
4923   SDNodeFlags Flags;
4924   if (Inserter)
4925     Flags = Inserter->getFlags();
4926   return getNode(Opcode, DL, VT, Operand, Flags);
4927 }
4928 
4929 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4930                               SDValue Operand, const SDNodeFlags Flags) {
4931   assert(Operand.getOpcode() != ISD::DELETED_NODE &&
4932          "Operand is DELETED_NODE!");
4933   // Constant fold unary operations with an integer constant operand. Even
4934   // opaque constant will be folded, because the folding of unary operations
4935   // doesn't create new constants with different values. Nevertheless, the
4936   // opaque flag is preserved during folding to prevent future folding with
4937   // other constants.
4938   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand)) {
4939     const APInt &Val = C->getAPIntValue();
4940     switch (Opcode) {
4941     default: break;
4942     case ISD::SIGN_EXTEND:
4943       return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
4944                          C->isTargetOpcode(), C->isOpaque());
4945     case ISD::TRUNCATE:
4946       if (C->isOpaque())
4947         break;
4948       LLVM_FALLTHROUGH;
4949     case ISD::ZERO_EXTEND:
4950       return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
4951                          C->isTargetOpcode(), C->isOpaque());
4952     case ISD::ANY_EXTEND:
4953       // Some targets like RISCV prefer to sign extend some types.
4954       if (TLI->isSExtCheaperThanZExt(Operand.getValueType(), VT))
4955         return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
4956                            C->isTargetOpcode(), C->isOpaque());
4957       return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
4958                          C->isTargetOpcode(), C->isOpaque());
4959     case ISD::UINT_TO_FP:
4960     case ISD::SINT_TO_FP: {
4961       APFloat apf(EVTToAPFloatSemantics(VT),
4962                   APInt::getZero(VT.getSizeInBits()));
4963       (void)apf.convertFromAPInt(Val,
4964                                  Opcode==ISD::SINT_TO_FP,
4965                                  APFloat::rmNearestTiesToEven);
4966       return getConstantFP(apf, DL, VT);
4967     }
4968     case ISD::BITCAST:
4969       if (VT == MVT::f16 && C->getValueType(0) == MVT::i16)
4970         return getConstantFP(APFloat(APFloat::IEEEhalf(), Val), DL, VT);
4971       if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
4972         return getConstantFP(APFloat(APFloat::IEEEsingle(), Val), DL, VT);
4973       if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
4974         return getConstantFP(APFloat(APFloat::IEEEdouble(), Val), DL, VT);
4975       if (VT == MVT::f128 && C->getValueType(0) == MVT::i128)
4976         return getConstantFP(APFloat(APFloat::IEEEquad(), Val), DL, VT);
4977       break;
4978     case ISD::ABS:
4979       return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(),
4980                          C->isOpaque());
4981     case ISD::BITREVERSE:
4982       return getConstant(Val.reverseBits(), DL, VT, C->isTargetOpcode(),
4983                          C->isOpaque());
4984     case ISD::BSWAP:
4985       return getConstant(Val.byteSwap(), DL, VT, C->isTargetOpcode(),
4986                          C->isOpaque());
4987     case ISD::CTPOP:
4988       return getConstant(Val.countPopulation(), DL, VT, C->isTargetOpcode(),
4989                          C->isOpaque());
4990     case ISD::CTLZ:
4991     case ISD::CTLZ_ZERO_UNDEF:
4992       return getConstant(Val.countLeadingZeros(), DL, VT, C->isTargetOpcode(),
4993                          C->isOpaque());
4994     case ISD::CTTZ:
4995     case ISD::CTTZ_ZERO_UNDEF:
4996       return getConstant(Val.countTrailingZeros(), DL, VT, C->isTargetOpcode(),
4997                          C->isOpaque());
4998     case ISD::FP16_TO_FP:
4999     case ISD::BF16_TO_FP: {
5000       bool Ignored;
5001       APFloat FPV(Opcode == ISD::FP16_TO_FP ? APFloat::IEEEhalf()
5002                                             : APFloat::BFloat(),
5003                   (Val.getBitWidth() == 16) ? Val : Val.trunc(16));
5004 
5005       // This can return overflow, underflow, or inexact; we don't care.
5006       // FIXME need to be more flexible about rounding mode.
5007       (void)FPV.convert(EVTToAPFloatSemantics(VT),
5008                         APFloat::rmNearestTiesToEven, &Ignored);
5009       return getConstantFP(FPV, DL, VT);
5010     }
5011     case ISD::STEP_VECTOR: {
5012       if (SDValue V = FoldSTEP_VECTOR(DL, VT, Operand, *this))
5013         return V;
5014       break;
5015     }
5016     }
5017   }
5018 
5019   // Constant fold unary operations with a floating point constant operand.
5020   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand)) {
5021     APFloat V = C->getValueAPF();    // make copy
5022     switch (Opcode) {
5023     case ISD::FNEG:
5024       V.changeSign();
5025       return getConstantFP(V, DL, VT);
5026     case ISD::FABS:
5027       V.clearSign();
5028       return getConstantFP(V, DL, VT);
5029     case ISD::FCEIL: {
5030       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardPositive);
5031       if (fs == APFloat::opOK || fs == APFloat::opInexact)
5032         return getConstantFP(V, DL, VT);
5033       break;
5034     }
5035     case ISD::FTRUNC: {
5036       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardZero);
5037       if (fs == APFloat::opOK || fs == APFloat::opInexact)
5038         return getConstantFP(V, DL, VT);
5039       break;
5040     }
5041     case ISD::FFLOOR: {
5042       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardNegative);
5043       if (fs == APFloat::opOK || fs == APFloat::opInexact)
5044         return getConstantFP(V, DL, VT);
5045       break;
5046     }
5047     case ISD::FP_EXTEND: {
5048       bool ignored;
5049       // This can return overflow, underflow, or inexact; we don't care.
5050       // FIXME need to be more flexible about rounding mode.
5051       (void)V.convert(EVTToAPFloatSemantics(VT),
5052                       APFloat::rmNearestTiesToEven, &ignored);
5053       return getConstantFP(V, DL, VT);
5054     }
5055     case ISD::FP_TO_SINT:
5056     case ISD::FP_TO_UINT: {
5057       bool ignored;
5058       APSInt IntVal(VT.getSizeInBits(), Opcode == ISD::FP_TO_UINT);
5059       // FIXME need to be more flexible about rounding mode.
5060       APFloat::opStatus s =
5061           V.convertToInteger(IntVal, APFloat::rmTowardZero, &ignored);
5062       if (s == APFloat::opInvalidOp) // inexact is OK, in fact usual
5063         break;
5064       return getConstant(IntVal, DL, VT);
5065     }
5066     case ISD::BITCAST:
5067       if (VT == MVT::i16 && C->getValueType(0) == MVT::f16)
5068         return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
5069       if (VT == MVT::i16 && C->getValueType(0) == MVT::bf16)
5070         return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
5071       if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
5072         return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
5073       if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
5074         return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
5075       break;
5076     case ISD::FP_TO_FP16:
5077     case ISD::FP_TO_BF16: {
5078       bool Ignored;
5079       // This can return overflow, underflow, or inexact; we don't care.
5080       // FIXME need to be more flexible about rounding mode.
5081       (void)V.convert(Opcode == ISD::FP_TO_FP16 ? APFloat::IEEEhalf()
5082                                                 : APFloat::BFloat(),
5083                       APFloat::rmNearestTiesToEven, &Ignored);
5084       return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
5085     }
5086     }
5087   }
5088 
5089   // Constant fold unary operations with a vector integer or float operand.
5090   switch (Opcode) {
5091   default:
5092     // FIXME: Entirely reasonable to perform folding of other unary
5093     // operations here as the need arises.
5094     break;
5095   case ISD::FNEG:
5096   case ISD::FABS:
5097   case ISD::FCEIL:
5098   case ISD::FTRUNC:
5099   case ISD::FFLOOR:
5100   case ISD::FP_EXTEND:
5101   case ISD::FP_TO_SINT:
5102   case ISD::FP_TO_UINT:
5103   case ISD::TRUNCATE:
5104   case ISD::ANY_EXTEND:
5105   case ISD::ZERO_EXTEND:
5106   case ISD::SIGN_EXTEND:
5107   case ISD::UINT_TO_FP:
5108   case ISD::SINT_TO_FP:
5109   case ISD::ABS:
5110   case ISD::BITREVERSE:
5111   case ISD::BSWAP:
5112   case ISD::CTLZ:
5113   case ISD::CTLZ_ZERO_UNDEF:
5114   case ISD::CTTZ:
5115   case ISD::CTTZ_ZERO_UNDEF:
5116   case ISD::CTPOP: {
5117     SDValue Ops = {Operand};
5118     if (SDValue Fold = FoldConstantArithmetic(Opcode, DL, VT, Ops))
5119       return Fold;
5120   }
5121   }
5122 
5123   unsigned OpOpcode = Operand.getNode()->getOpcode();
5124   switch (Opcode) {
5125   case ISD::STEP_VECTOR:
5126     assert(VT.isScalableVector() &&
5127            "STEP_VECTOR can only be used with scalable types");
5128     assert(OpOpcode == ISD::TargetConstant &&
5129            VT.getVectorElementType() == Operand.getValueType() &&
5130            "Unexpected step operand");
5131     break;
5132   case ISD::FREEZE:
5133     assert(VT == Operand.getValueType() && "Unexpected VT!");
5134     if (isGuaranteedNotToBeUndefOrPoison(Operand))
5135       return Operand;
5136     break;
5137   case ISD::TokenFactor:
5138   case ISD::MERGE_VALUES:
5139   case ISD::CONCAT_VECTORS:
5140     return Operand;         // Factor, merge or concat of one node?  No need.
5141   case ISD::BUILD_VECTOR: {
5142     // Attempt to simplify BUILD_VECTOR.
5143     SDValue Ops[] = {Operand};
5144     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
5145       return V;
5146     break;
5147   }
5148   case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node");
5149   case ISD::FP_EXTEND:
5150     assert(VT.isFloatingPoint() &&
5151            Operand.getValueType().isFloatingPoint() && "Invalid FP cast!");
5152     if (Operand.getValueType() == VT) return Operand;  // noop conversion.
5153     assert((!VT.isVector() ||
5154             VT.getVectorElementCount() ==
5155             Operand.getValueType().getVectorElementCount()) &&
5156            "Vector element count mismatch!");
5157     assert(Operand.getValueType().bitsLT(VT) &&
5158            "Invalid fpext node, dst < src!");
5159     if (Operand.isUndef())
5160       return getUNDEF(VT);
5161     break;
5162   case ISD::FP_TO_SINT:
5163   case ISD::FP_TO_UINT:
5164     if (Operand.isUndef())
5165       return getUNDEF(VT);
5166     break;
5167   case ISD::SINT_TO_FP:
5168   case ISD::UINT_TO_FP:
5169     // [us]itofp(undef) = 0, because the result value is bounded.
5170     if (Operand.isUndef())
5171       return getConstantFP(0.0, DL, VT);
5172     break;
5173   case ISD::SIGN_EXTEND:
5174     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
5175            "Invalid SIGN_EXTEND!");
5176     assert(VT.isVector() == Operand.getValueType().isVector() &&
5177            "SIGN_EXTEND result type type should be vector iff the operand "
5178            "type is vector!");
5179     if (Operand.getValueType() == VT) return Operand;   // noop extension
5180     assert((!VT.isVector() ||
5181             VT.getVectorElementCount() ==
5182                 Operand.getValueType().getVectorElementCount()) &&
5183            "Vector element count mismatch!");
5184     assert(Operand.getValueType().bitsLT(VT) &&
5185            "Invalid sext node, dst < src!");
5186     if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
5187       return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
5188     if (OpOpcode == ISD::UNDEF)
5189       // sext(undef) = 0, because the top bits will all be the same.
5190       return getConstant(0, DL, VT);
5191     break;
5192   case ISD::ZERO_EXTEND:
5193     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
5194            "Invalid ZERO_EXTEND!");
5195     assert(VT.isVector() == Operand.getValueType().isVector() &&
5196            "ZERO_EXTEND result type type should be vector iff the operand "
5197            "type is vector!");
5198     if (Operand.getValueType() == VT) return Operand;   // noop extension
5199     assert((!VT.isVector() ||
5200             VT.getVectorElementCount() ==
5201                 Operand.getValueType().getVectorElementCount()) &&
5202            "Vector element count mismatch!");
5203     assert(Operand.getValueType().bitsLT(VT) &&
5204            "Invalid zext node, dst < src!");
5205     if (OpOpcode == ISD::ZERO_EXTEND)   // (zext (zext x)) -> (zext x)
5206       return getNode(ISD::ZERO_EXTEND, DL, VT, Operand.getOperand(0));
5207     if (OpOpcode == ISD::UNDEF)
5208       // zext(undef) = 0, because the top bits will be zero.
5209       return getConstant(0, DL, VT);
5210     break;
5211   case ISD::ANY_EXTEND:
5212     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
5213            "Invalid ANY_EXTEND!");
5214     assert(VT.isVector() == Operand.getValueType().isVector() &&
5215            "ANY_EXTEND result type type should be vector iff the operand "
5216            "type is vector!");
5217     if (Operand.getValueType() == VT) return Operand;   // noop extension
5218     assert((!VT.isVector() ||
5219             VT.getVectorElementCount() ==
5220                 Operand.getValueType().getVectorElementCount()) &&
5221            "Vector element count mismatch!");
5222     assert(Operand.getValueType().bitsLT(VT) &&
5223            "Invalid anyext node, dst < src!");
5224 
5225     if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
5226         OpOpcode == ISD::ANY_EXTEND)
5227       // (ext (zext x)) -> (zext x)  and  (ext (sext x)) -> (sext x)
5228       return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
5229     if (OpOpcode == ISD::UNDEF)
5230       return getUNDEF(VT);
5231 
5232     // (ext (trunc x)) -> x
5233     if (OpOpcode == ISD::TRUNCATE) {
5234       SDValue OpOp = Operand.getOperand(0);
5235       if (OpOp.getValueType() == VT) {
5236         transferDbgValues(Operand, OpOp);
5237         return OpOp;
5238       }
5239     }
5240     break;
5241   case ISD::TRUNCATE:
5242     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
5243            "Invalid TRUNCATE!");
5244     assert(VT.isVector() == Operand.getValueType().isVector() &&
5245            "TRUNCATE result type type should be vector iff the operand "
5246            "type is vector!");
5247     if (Operand.getValueType() == VT) return Operand;   // noop truncate
5248     assert((!VT.isVector() ||
5249             VT.getVectorElementCount() ==
5250                 Operand.getValueType().getVectorElementCount()) &&
5251            "Vector element count mismatch!");
5252     assert(Operand.getValueType().bitsGT(VT) &&
5253            "Invalid truncate node, src < dst!");
5254     if (OpOpcode == ISD::TRUNCATE)
5255       return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0));
5256     if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
5257         OpOpcode == ISD::ANY_EXTEND) {
5258       // If the source is smaller than the dest, we still need an extend.
5259       if (Operand.getOperand(0).getValueType().getScalarType()
5260             .bitsLT(VT.getScalarType()))
5261         return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
5262       if (Operand.getOperand(0).getValueType().bitsGT(VT))
5263         return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0));
5264       return Operand.getOperand(0);
5265     }
5266     if (OpOpcode == ISD::UNDEF)
5267       return getUNDEF(VT);
5268     if (OpOpcode == ISD::VSCALE && !NewNodesMustHaveLegalTypes)
5269       return getVScale(DL, VT, Operand.getConstantOperandAPInt(0));
5270     break;
5271   case ISD::ANY_EXTEND_VECTOR_INREG:
5272   case ISD::ZERO_EXTEND_VECTOR_INREG:
5273   case ISD::SIGN_EXTEND_VECTOR_INREG:
5274     assert(VT.isVector() && "This DAG node is restricted to vector types.");
5275     assert(Operand.getValueType().bitsLE(VT) &&
5276            "The input must be the same size or smaller than the result.");
5277     assert(VT.getVectorMinNumElements() <
5278                Operand.getValueType().getVectorMinNumElements() &&
5279            "The destination vector type must have fewer lanes than the input.");
5280     break;
5281   case ISD::ABS:
5282     assert(VT.isInteger() && VT == Operand.getValueType() &&
5283            "Invalid ABS!");
5284     if (OpOpcode == ISD::UNDEF)
5285       return getConstant(0, DL, VT);
5286     break;
5287   case ISD::BSWAP:
5288     assert(VT.isInteger() && VT == Operand.getValueType() &&
5289            "Invalid BSWAP!");
5290     assert((VT.getScalarSizeInBits() % 16 == 0) &&
5291            "BSWAP types must be a multiple of 16 bits!");
5292     if (OpOpcode == ISD::UNDEF)
5293       return getUNDEF(VT);
5294     // bswap(bswap(X)) -> X.
5295     if (OpOpcode == ISD::BSWAP)
5296       return Operand.getOperand(0);
5297     break;
5298   case ISD::BITREVERSE:
5299     assert(VT.isInteger() && VT == Operand.getValueType() &&
5300            "Invalid BITREVERSE!");
5301     if (OpOpcode == ISD::UNDEF)
5302       return getUNDEF(VT);
5303     break;
5304   case ISD::BITCAST:
5305     assert(VT.getSizeInBits() == Operand.getValueSizeInBits() &&
5306            "Cannot BITCAST between types of different sizes!");
5307     if (VT == Operand.getValueType()) return Operand;  // noop conversion.
5308     if (OpOpcode == ISD::BITCAST)  // bitconv(bitconv(x)) -> bitconv(x)
5309       return getNode(ISD::BITCAST, DL, VT, Operand.getOperand(0));
5310     if (OpOpcode == ISD::UNDEF)
5311       return getUNDEF(VT);
5312     break;
5313   case ISD::SCALAR_TO_VECTOR:
5314     assert(VT.isVector() && !Operand.getValueType().isVector() &&
5315            (VT.getVectorElementType() == Operand.getValueType() ||
5316             (VT.getVectorElementType().isInteger() &&
5317              Operand.getValueType().isInteger() &&
5318              VT.getVectorElementType().bitsLE(Operand.getValueType()))) &&
5319            "Illegal SCALAR_TO_VECTOR node!");
5320     if (OpOpcode == ISD::UNDEF)
5321       return getUNDEF(VT);
5322     // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
5323     if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
5324         isa<ConstantSDNode>(Operand.getOperand(1)) &&
5325         Operand.getConstantOperandVal(1) == 0 &&
5326         Operand.getOperand(0).getValueType() == VT)
5327       return Operand.getOperand(0);
5328     break;
5329   case ISD::FNEG:
5330     // Negation of an unknown bag of bits is still completely undefined.
5331     if (OpOpcode == ISD::UNDEF)
5332       return getUNDEF(VT);
5333 
5334     if (OpOpcode == ISD::FNEG)  // --X -> X
5335       return Operand.getOperand(0);
5336     break;
5337   case ISD::FABS:
5338     if (OpOpcode == ISD::FNEG)  // abs(-X) -> abs(X)
5339       return getNode(ISD::FABS, DL, VT, Operand.getOperand(0));
5340     break;
5341   case ISD::VSCALE:
5342     assert(VT == Operand.getValueType() && "Unexpected VT!");
5343     break;
5344   case ISD::CTPOP:
5345     if (Operand.getValueType().getScalarType() == MVT::i1)
5346       return Operand;
5347     break;
5348   case ISD::CTLZ:
5349   case ISD::CTTZ:
5350     if (Operand.getValueType().getScalarType() == MVT::i1)
5351       return getNOT(DL, Operand, Operand.getValueType());
5352     break;
5353   case ISD::VECREDUCE_ADD:
5354     if (Operand.getValueType().getScalarType() == MVT::i1)
5355       return getNode(ISD::VECREDUCE_XOR, DL, VT, Operand);
5356     break;
5357   case ISD::VECREDUCE_SMIN:
5358   case ISD::VECREDUCE_UMAX:
5359     if (Operand.getValueType().getScalarType() == MVT::i1)
5360       return getNode(ISD::VECREDUCE_OR, DL, VT, Operand);
5361     break;
5362   case ISD::VECREDUCE_SMAX:
5363   case ISD::VECREDUCE_UMIN:
5364     if (Operand.getValueType().getScalarType() == MVT::i1)
5365       return getNode(ISD::VECREDUCE_AND, DL, VT, Operand);
5366     break;
5367   }
5368 
5369   SDNode *N;
5370   SDVTList VTs = getVTList(VT);
5371   SDValue Ops[] = {Operand};
5372   if (VT != MVT::Glue) { // Don't CSE flag producing nodes
5373     FoldingSetNodeID ID;
5374     AddNodeIDNode(ID, Opcode, VTs, Ops);
5375     void *IP = nullptr;
5376     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
5377       E->intersectFlagsWith(Flags);
5378       return SDValue(E, 0);
5379     }
5380 
5381     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5382     N->setFlags(Flags);
5383     createOperands(N, Ops);
5384     CSEMap.InsertNode(N, IP);
5385   } else {
5386     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5387     createOperands(N, Ops);
5388   }
5389 
5390   InsertNode(N);
5391   SDValue V = SDValue(N, 0);
5392   NewSDValueDbgMsg(V, "Creating new node: ", this);
5393   return V;
5394 }
5395 
5396 static llvm::Optional<APInt> FoldValue(unsigned Opcode, const APInt &C1,
5397                                        const APInt &C2) {
5398   switch (Opcode) {
5399   case ISD::ADD:  return C1 + C2;
5400   case ISD::SUB:  return C1 - C2;
5401   case ISD::MUL:  return C1 * C2;
5402   case ISD::AND:  return C1 & C2;
5403   case ISD::OR:   return C1 | C2;
5404   case ISD::XOR:  return C1 ^ C2;
5405   case ISD::SHL:  return C1 << C2;
5406   case ISD::SRL:  return C1.lshr(C2);
5407   case ISD::SRA:  return C1.ashr(C2);
5408   case ISD::ROTL: return C1.rotl(C2);
5409   case ISD::ROTR: return C1.rotr(C2);
5410   case ISD::SMIN: return C1.sle(C2) ? C1 : C2;
5411   case ISD::SMAX: return C1.sge(C2) ? C1 : C2;
5412   case ISD::UMIN: return C1.ule(C2) ? C1 : C2;
5413   case ISD::UMAX: return C1.uge(C2) ? C1 : C2;
5414   case ISD::SADDSAT: return C1.sadd_sat(C2);
5415   case ISD::UADDSAT: return C1.uadd_sat(C2);
5416   case ISD::SSUBSAT: return C1.ssub_sat(C2);
5417   case ISD::USUBSAT: return C1.usub_sat(C2);
5418   case ISD::SSHLSAT: return C1.sshl_sat(C2);
5419   case ISD::USHLSAT: return C1.ushl_sat(C2);
5420   case ISD::UDIV:
5421     if (!C2.getBoolValue())
5422       break;
5423     return C1.udiv(C2);
5424   case ISD::UREM:
5425     if (!C2.getBoolValue())
5426       break;
5427     return C1.urem(C2);
5428   case ISD::SDIV:
5429     if (!C2.getBoolValue())
5430       break;
5431     return C1.sdiv(C2);
5432   case ISD::SREM:
5433     if (!C2.getBoolValue())
5434       break;
5435     return C1.srem(C2);
5436   case ISD::MULHS: {
5437     unsigned FullWidth = C1.getBitWidth() * 2;
5438     APInt C1Ext = C1.sext(FullWidth);
5439     APInt C2Ext = C2.sext(FullWidth);
5440     return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth());
5441   }
5442   case ISD::MULHU: {
5443     unsigned FullWidth = C1.getBitWidth() * 2;
5444     APInt C1Ext = C1.zext(FullWidth);
5445     APInt C2Ext = C2.zext(FullWidth);
5446     return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth());
5447   }
5448   case ISD::AVGFLOORS: {
5449     unsigned FullWidth = C1.getBitWidth() + 1;
5450     APInt C1Ext = C1.sext(FullWidth);
5451     APInt C2Ext = C2.sext(FullWidth);
5452     return (C1Ext + C2Ext).extractBits(C1.getBitWidth(), 1);
5453   }
5454   case ISD::AVGFLOORU: {
5455     unsigned FullWidth = C1.getBitWidth() + 1;
5456     APInt C1Ext = C1.zext(FullWidth);
5457     APInt C2Ext = C2.zext(FullWidth);
5458     return (C1Ext + C2Ext).extractBits(C1.getBitWidth(), 1);
5459   }
5460   case ISD::AVGCEILS: {
5461     unsigned FullWidth = C1.getBitWidth() + 1;
5462     APInt C1Ext = C1.sext(FullWidth);
5463     APInt C2Ext = C2.sext(FullWidth);
5464     return (C1Ext + C2Ext + 1).extractBits(C1.getBitWidth(), 1);
5465   }
5466   case ISD::AVGCEILU: {
5467     unsigned FullWidth = C1.getBitWidth() + 1;
5468     APInt C1Ext = C1.zext(FullWidth);
5469     APInt C2Ext = C2.zext(FullWidth);
5470     return (C1Ext + C2Ext + 1).extractBits(C1.getBitWidth(), 1);
5471   }
5472   }
5473   return llvm::None;
5474 }
5475 
5476 SDValue SelectionDAG::FoldSymbolOffset(unsigned Opcode, EVT VT,
5477                                        const GlobalAddressSDNode *GA,
5478                                        const SDNode *N2) {
5479   if (GA->getOpcode() != ISD::GlobalAddress)
5480     return SDValue();
5481   if (!TLI->isOffsetFoldingLegal(GA))
5482     return SDValue();
5483   auto *C2 = dyn_cast<ConstantSDNode>(N2);
5484   if (!C2)
5485     return SDValue();
5486   int64_t Offset = C2->getSExtValue();
5487   switch (Opcode) {
5488   case ISD::ADD: break;
5489   case ISD::SUB: Offset = -uint64_t(Offset); break;
5490   default: return SDValue();
5491   }
5492   return getGlobalAddress(GA->getGlobal(), SDLoc(C2), VT,
5493                           GA->getOffset() + uint64_t(Offset));
5494 }
5495 
5496 bool SelectionDAG::isUndef(unsigned Opcode, ArrayRef<SDValue> Ops) {
5497   switch (Opcode) {
5498   case ISD::SDIV:
5499   case ISD::UDIV:
5500   case ISD::SREM:
5501   case ISD::UREM: {
5502     // If a divisor is zero/undef or any element of a divisor vector is
5503     // zero/undef, the whole op is undef.
5504     assert(Ops.size() == 2 && "Div/rem should have 2 operands");
5505     SDValue Divisor = Ops[1];
5506     if (Divisor.isUndef() || isNullConstant(Divisor))
5507       return true;
5508 
5509     return ISD::isBuildVectorOfConstantSDNodes(Divisor.getNode()) &&
5510            llvm::any_of(Divisor->op_values(),
5511                         [](SDValue V) { return V.isUndef() ||
5512                                         isNullConstant(V); });
5513     // TODO: Handle signed overflow.
5514   }
5515   // TODO: Handle oversized shifts.
5516   default:
5517     return false;
5518   }
5519 }
5520 
5521 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL,
5522                                              EVT VT, ArrayRef<SDValue> Ops) {
5523   // If the opcode is a target-specific ISD node, there's nothing we can
5524   // do here and the operand rules may not line up with the below, so
5525   // bail early.
5526   // We can't create a scalar CONCAT_VECTORS so skip it. It will break
5527   // for concats involving SPLAT_VECTOR. Concats of BUILD_VECTORS are handled by
5528   // foldCONCAT_VECTORS in getNode before this is called.
5529   if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::CONCAT_VECTORS)
5530     return SDValue();
5531 
5532   unsigned NumOps = Ops.size();
5533   if (NumOps == 0)
5534     return SDValue();
5535 
5536   if (isUndef(Opcode, Ops))
5537     return getUNDEF(VT);
5538 
5539   // Handle binops special cases.
5540   if (NumOps == 2) {
5541     if (SDValue CFP = foldConstantFPMath(Opcode, DL, VT, Ops[0], Ops[1]))
5542       return CFP;
5543 
5544     if (auto *C1 = dyn_cast<ConstantSDNode>(Ops[0])) {
5545       if (auto *C2 = dyn_cast<ConstantSDNode>(Ops[1])) {
5546         if (C1->isOpaque() || C2->isOpaque())
5547           return SDValue();
5548 
5549         Optional<APInt> FoldAttempt =
5550             FoldValue(Opcode, C1->getAPIntValue(), C2->getAPIntValue());
5551         if (!FoldAttempt)
5552           return SDValue();
5553 
5554         SDValue Folded = getConstant(*FoldAttempt, DL, VT);
5555         assert((!Folded || !VT.isVector()) &&
5556                "Can't fold vectors ops with scalar operands");
5557         return Folded;
5558       }
5559     }
5560 
5561     // fold (add Sym, c) -> Sym+c
5562     if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ops[0]))
5563       return FoldSymbolOffset(Opcode, VT, GA, Ops[1].getNode());
5564     if (TLI->isCommutativeBinOp(Opcode))
5565       if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ops[1]))
5566         return FoldSymbolOffset(Opcode, VT, GA, Ops[0].getNode());
5567   }
5568 
5569   // This is for vector folding only from here on.
5570   if (!VT.isVector())
5571     return SDValue();
5572 
5573   ElementCount NumElts = VT.getVectorElementCount();
5574 
5575   // See if we can fold through bitcasted integer ops.
5576   // TODO: Can we handle undef elements?
5577   if (NumOps == 2 && VT.isFixedLengthVector() && VT.isInteger() &&
5578       Ops[0].getValueType() == VT && Ops[1].getValueType() == VT &&
5579       Ops[0].getOpcode() == ISD::BITCAST &&
5580       Ops[1].getOpcode() == ISD::BITCAST) {
5581     SDValue N1 = peekThroughBitcasts(Ops[0]);
5582     SDValue N2 = peekThroughBitcasts(Ops[1]);
5583     auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
5584     auto *BV2 = dyn_cast<BuildVectorSDNode>(N2);
5585     EVT BVVT = N1.getValueType();
5586     if (BV1 && BV2 && BVVT.isInteger() && BVVT == N2.getValueType()) {
5587       bool IsLE = getDataLayout().isLittleEndian();
5588       unsigned EltBits = VT.getScalarSizeInBits();
5589       SmallVector<APInt> RawBits1, RawBits2;
5590       BitVector UndefElts1, UndefElts2;
5591       if (BV1->getConstantRawBits(IsLE, EltBits, RawBits1, UndefElts1) &&
5592           BV2->getConstantRawBits(IsLE, EltBits, RawBits2, UndefElts2) &&
5593           UndefElts1.none() && UndefElts2.none()) {
5594         SmallVector<APInt> RawBits;
5595         for (unsigned I = 0, E = NumElts.getFixedValue(); I != E; ++I) {
5596           Optional<APInt> Fold = FoldValue(Opcode, RawBits1[I], RawBits2[I]);
5597           if (!Fold)
5598             break;
5599           RawBits.push_back(*Fold);
5600         }
5601         if (RawBits.size() == NumElts.getFixedValue()) {
5602           // We have constant folded, but we need to cast this again back to
5603           // the original (possibly legalized) type.
5604           SmallVector<APInt> DstBits;
5605           BitVector DstUndefs;
5606           BuildVectorSDNode::recastRawBits(IsLE, BVVT.getScalarSizeInBits(),
5607                                            DstBits, RawBits, DstUndefs,
5608                                            BitVector(RawBits.size(), false));
5609           EVT BVEltVT = BV1->getOperand(0).getValueType();
5610           unsigned BVEltBits = BVEltVT.getSizeInBits();
5611           SmallVector<SDValue> Ops(DstBits.size(), getUNDEF(BVEltVT));
5612           for (unsigned I = 0, E = DstBits.size(); I != E; ++I) {
5613             if (DstUndefs[I])
5614               continue;
5615             Ops[I] = getConstant(DstBits[I].sext(BVEltBits), DL, BVEltVT);
5616           }
5617           return getBitcast(VT, getBuildVector(BVVT, DL, Ops));
5618         }
5619       }
5620     }
5621   }
5622 
5623   // Fold (mul step_vector(C0), C1) to (step_vector(C0 * C1)).
5624   //      (shl step_vector(C0), C1) -> (step_vector(C0 << C1))
5625   if ((Opcode == ISD::MUL || Opcode == ISD::SHL) &&
5626       Ops[0].getOpcode() == ISD::STEP_VECTOR) {
5627     APInt RHSVal;
5628     if (ISD::isConstantSplatVector(Ops[1].getNode(), RHSVal)) {
5629       APInt NewStep = Opcode == ISD::MUL
5630                           ? Ops[0].getConstantOperandAPInt(0) * RHSVal
5631                           : Ops[0].getConstantOperandAPInt(0) << RHSVal;
5632       return getStepVector(DL, VT, NewStep);
5633     }
5634   }
5635 
5636   auto IsScalarOrSameVectorSize = [NumElts](const SDValue &Op) {
5637     return !Op.getValueType().isVector() ||
5638            Op.getValueType().getVectorElementCount() == NumElts;
5639   };
5640 
5641   auto IsBuildVectorSplatVectorOrUndef = [](const SDValue &Op) {
5642     return Op.isUndef() || Op.getOpcode() == ISD::CONDCODE ||
5643            Op.getOpcode() == ISD::BUILD_VECTOR ||
5644            Op.getOpcode() == ISD::SPLAT_VECTOR;
5645   };
5646 
5647   // All operands must be vector types with the same number of elements as
5648   // the result type and must be either UNDEF or a build/splat vector
5649   // or UNDEF scalars.
5650   if (!llvm::all_of(Ops, IsBuildVectorSplatVectorOrUndef) ||
5651       !llvm::all_of(Ops, IsScalarOrSameVectorSize))
5652     return SDValue();
5653 
5654   // If we are comparing vectors, then the result needs to be a i1 boolean that
5655   // is then extended back to the legal result type depending on how booleans
5656   // are represented.
5657   EVT SVT = (Opcode == ISD::SETCC ? MVT::i1 : VT.getScalarType());
5658   ISD::NodeType ExtendCode =
5659       (Opcode == ISD::SETCC && SVT != VT.getScalarType())
5660           ? TargetLowering::getExtendForContent(TLI->getBooleanContents(VT))
5661           : ISD::SIGN_EXTEND;
5662 
5663   // Find legal integer scalar type for constant promotion and
5664   // ensure that its scalar size is at least as large as source.
5665   EVT LegalSVT = VT.getScalarType();
5666   if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
5667     LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
5668     if (LegalSVT.bitsLT(VT.getScalarType()))
5669       return SDValue();
5670   }
5671 
5672   // For scalable vector types we know we're dealing with SPLAT_VECTORs. We
5673   // only have one operand to check. For fixed-length vector types we may have
5674   // a combination of BUILD_VECTOR and SPLAT_VECTOR.
5675   unsigned NumVectorElts = NumElts.isScalable() ? 1 : NumElts.getFixedValue();
5676 
5677   // Constant fold each scalar lane separately.
5678   SmallVector<SDValue, 4> ScalarResults;
5679   for (unsigned I = 0; I != NumVectorElts; I++) {
5680     SmallVector<SDValue, 4> ScalarOps;
5681     for (SDValue Op : Ops) {
5682       EVT InSVT = Op.getValueType().getScalarType();
5683       if (Op.getOpcode() != ISD::BUILD_VECTOR &&
5684           Op.getOpcode() != ISD::SPLAT_VECTOR) {
5685         if (Op.isUndef())
5686           ScalarOps.push_back(getUNDEF(InSVT));
5687         else
5688           ScalarOps.push_back(Op);
5689         continue;
5690       }
5691 
5692       SDValue ScalarOp =
5693           Op.getOperand(Op.getOpcode() == ISD::SPLAT_VECTOR ? 0 : I);
5694       EVT ScalarVT = ScalarOp.getValueType();
5695 
5696       // Build vector (integer) scalar operands may need implicit
5697       // truncation - do this before constant folding.
5698       if (ScalarVT.isInteger() && ScalarVT.bitsGT(InSVT)) {
5699         // Don't create illegally-typed nodes unless they're constants or undef
5700         // - if we fail to constant fold we can't guarantee the (dead) nodes
5701         // we're creating will be cleaned up before being visited for
5702         // legalization.
5703         if (NewNodesMustHaveLegalTypes && !ScalarOp.isUndef() &&
5704             !isa<ConstantSDNode>(ScalarOp) &&
5705             TLI->getTypeAction(*getContext(), InSVT) !=
5706                 TargetLowering::TypeLegal)
5707           return SDValue();
5708         ScalarOp = getNode(ISD::TRUNCATE, DL, InSVT, ScalarOp);
5709       }
5710 
5711       ScalarOps.push_back(ScalarOp);
5712     }
5713 
5714     // Constant fold the scalar operands.
5715     SDValue ScalarResult = getNode(Opcode, DL, SVT, ScalarOps);
5716 
5717     // Legalize the (integer) scalar constant if necessary.
5718     if (LegalSVT != SVT)
5719       ScalarResult = getNode(ExtendCode, DL, LegalSVT, ScalarResult);
5720 
5721     // Scalar folding only succeeded if the result is a constant or UNDEF.
5722     if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant &&
5723         ScalarResult.getOpcode() != ISD::ConstantFP)
5724       return SDValue();
5725     ScalarResults.push_back(ScalarResult);
5726   }
5727 
5728   SDValue V = NumElts.isScalable() ? getSplatVector(VT, DL, ScalarResults[0])
5729                                    : getBuildVector(VT, DL, ScalarResults);
5730   NewSDValueDbgMsg(V, "New node fold constant vector: ", this);
5731   return V;
5732 }
5733 
5734 SDValue SelectionDAG::foldConstantFPMath(unsigned Opcode, const SDLoc &DL,
5735                                          EVT VT, SDValue N1, SDValue N2) {
5736   // TODO: We don't do any constant folding for strict FP opcodes here, but we
5737   //       should. That will require dealing with a potentially non-default
5738   //       rounding mode, checking the "opStatus" return value from the APFloat
5739   //       math calculations, and possibly other variations.
5740   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1, /*AllowUndefs*/ false);
5741   ConstantFPSDNode *N2CFP = isConstOrConstSplatFP(N2, /*AllowUndefs*/ false);
5742   if (N1CFP && N2CFP) {
5743     APFloat C1 = N1CFP->getValueAPF(); // make copy
5744     const APFloat &C2 = N2CFP->getValueAPF();
5745     switch (Opcode) {
5746     case ISD::FADD:
5747       C1.add(C2, APFloat::rmNearestTiesToEven);
5748       return getConstantFP(C1, DL, VT);
5749     case ISD::FSUB:
5750       C1.subtract(C2, APFloat::rmNearestTiesToEven);
5751       return getConstantFP(C1, DL, VT);
5752     case ISD::FMUL:
5753       C1.multiply(C2, APFloat::rmNearestTiesToEven);
5754       return getConstantFP(C1, DL, VT);
5755     case ISD::FDIV:
5756       C1.divide(C2, APFloat::rmNearestTiesToEven);
5757       return getConstantFP(C1, DL, VT);
5758     case ISD::FREM:
5759       C1.mod(C2);
5760       return getConstantFP(C1, DL, VT);
5761     case ISD::FCOPYSIGN:
5762       C1.copySign(C2);
5763       return getConstantFP(C1, DL, VT);
5764     case ISD::FMINNUM:
5765       return getConstantFP(minnum(C1, C2), DL, VT);
5766     case ISD::FMAXNUM:
5767       return getConstantFP(maxnum(C1, C2), DL, VT);
5768     case ISD::FMINIMUM:
5769       return getConstantFP(minimum(C1, C2), DL, VT);
5770     case ISD::FMAXIMUM:
5771       return getConstantFP(maximum(C1, C2), DL, VT);
5772     default: break;
5773     }
5774   }
5775   if (N1CFP && Opcode == ISD::FP_ROUND) {
5776     APFloat C1 = N1CFP->getValueAPF();    // make copy
5777     bool Unused;
5778     // This can return overflow, underflow, or inexact; we don't care.
5779     // FIXME need to be more flexible about rounding mode.
5780     (void) C1.convert(EVTToAPFloatSemantics(VT), APFloat::rmNearestTiesToEven,
5781                       &Unused);
5782     return getConstantFP(C1, DL, VT);
5783   }
5784 
5785   switch (Opcode) {
5786   case ISD::FSUB:
5787     // -0.0 - undef --> undef (consistent with "fneg undef")
5788     if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1, /*AllowUndefs*/ true))
5789       if (N1C && N1C->getValueAPF().isNegZero() && N2.isUndef())
5790         return getUNDEF(VT);
5791     LLVM_FALLTHROUGH;
5792 
5793   case ISD::FADD:
5794   case ISD::FMUL:
5795   case ISD::FDIV:
5796   case ISD::FREM:
5797     // If both operands are undef, the result is undef. If 1 operand is undef,
5798     // the result is NaN. This should match the behavior of the IR optimizer.
5799     if (N1.isUndef() && N2.isUndef())
5800       return getUNDEF(VT);
5801     if (N1.isUndef() || N2.isUndef())
5802       return getConstantFP(APFloat::getNaN(EVTToAPFloatSemantics(VT)), DL, VT);
5803   }
5804   return SDValue();
5805 }
5806 
5807 SDValue SelectionDAG::getAssertAlign(const SDLoc &DL, SDValue Val, Align A) {
5808   assert(Val.getValueType().isInteger() && "Invalid AssertAlign!");
5809 
5810   // There's no need to assert on a byte-aligned pointer. All pointers are at
5811   // least byte aligned.
5812   if (A == Align(1))
5813     return Val;
5814 
5815   FoldingSetNodeID ID;
5816   AddNodeIDNode(ID, ISD::AssertAlign, getVTList(Val.getValueType()), {Val});
5817   ID.AddInteger(A.value());
5818 
5819   void *IP = nullptr;
5820   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
5821     return SDValue(E, 0);
5822 
5823   auto *N = newSDNode<AssertAlignSDNode>(DL.getIROrder(), DL.getDebugLoc(),
5824                                          Val.getValueType(), A);
5825   createOperands(N, {Val});
5826 
5827   CSEMap.InsertNode(N, IP);
5828   InsertNode(N);
5829 
5830   SDValue V(N, 0);
5831   NewSDValueDbgMsg(V, "Creating new node: ", this);
5832   return V;
5833 }
5834 
5835 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5836                               SDValue N1, SDValue N2) {
5837   SDNodeFlags Flags;
5838   if (Inserter)
5839     Flags = Inserter->getFlags();
5840   return getNode(Opcode, DL, VT, N1, N2, Flags);
5841 }
5842 
5843 void SelectionDAG::canonicalizeCommutativeBinop(unsigned Opcode, SDValue &N1,
5844                                                 SDValue &N2) const {
5845   if (!TLI->isCommutativeBinOp(Opcode))
5846     return;
5847 
5848   // Canonicalize:
5849   //   binop(const, nonconst) -> binop(nonconst, const)
5850   bool IsN1C = isConstantIntBuildVectorOrConstantInt(N1);
5851   bool IsN2C = isConstantIntBuildVectorOrConstantInt(N2);
5852   bool IsN1CFP = isConstantFPBuildVectorOrConstantFP(N1);
5853   bool IsN2CFP = isConstantFPBuildVectorOrConstantFP(N2);
5854   if ((IsN1C && !IsN2C) || (IsN1CFP && !IsN2CFP))
5855     std::swap(N1, N2);
5856 
5857   // Canonicalize:
5858   //  binop(splat(x), step_vector) -> binop(step_vector, splat(x))
5859   else if (N1.getOpcode() == ISD::SPLAT_VECTOR &&
5860            N2.getOpcode() == ISD::STEP_VECTOR)
5861     std::swap(N1, N2);
5862 }
5863 
5864 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5865                               SDValue N1, SDValue N2, const SDNodeFlags Flags) {
5866   assert(N1.getOpcode() != ISD::DELETED_NODE &&
5867          N2.getOpcode() != ISD::DELETED_NODE &&
5868          "Operand is DELETED_NODE!");
5869 
5870   canonicalizeCommutativeBinop(Opcode, N1, N2);
5871 
5872   auto *N1C = dyn_cast<ConstantSDNode>(N1);
5873   auto *N2C = dyn_cast<ConstantSDNode>(N2);
5874 
5875   // Don't allow undefs in vector splats - we might be returning N2 when folding
5876   // to zero etc.
5877   ConstantSDNode *N2CV =
5878       isConstOrConstSplat(N2, /*AllowUndefs*/ false, /*AllowTruncation*/ true);
5879 
5880   switch (Opcode) {
5881   default: break;
5882   case ISD::TokenFactor:
5883     assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
5884            N2.getValueType() == MVT::Other && "Invalid token factor!");
5885     // Fold trivial token factors.
5886     if (N1.getOpcode() == ISD::EntryToken) return N2;
5887     if (N2.getOpcode() == ISD::EntryToken) return N1;
5888     if (N1 == N2) return N1;
5889     break;
5890   case ISD::BUILD_VECTOR: {
5891     // Attempt to simplify BUILD_VECTOR.
5892     SDValue Ops[] = {N1, N2};
5893     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
5894       return V;
5895     break;
5896   }
5897   case ISD::CONCAT_VECTORS: {
5898     SDValue Ops[] = {N1, N2};
5899     if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
5900       return V;
5901     break;
5902   }
5903   case ISD::AND:
5904     assert(VT.isInteger() && "This operator does not apply to FP types!");
5905     assert(N1.getValueType() == N2.getValueType() &&
5906            N1.getValueType() == VT && "Binary operator types must match!");
5907     // (X & 0) -> 0.  This commonly occurs when legalizing i64 values, so it's
5908     // worth handling here.
5909     if (N2CV && N2CV->isZero())
5910       return N2;
5911     if (N2CV && N2CV->isAllOnes()) // X & -1 -> X
5912       return N1;
5913     break;
5914   case ISD::OR:
5915   case ISD::XOR:
5916   case ISD::ADD:
5917   case ISD::SUB:
5918     assert(VT.isInteger() && "This operator does not apply to FP types!");
5919     assert(N1.getValueType() == N2.getValueType() &&
5920            N1.getValueType() == VT && "Binary operator types must match!");
5921     // (X ^|+- 0) -> X.  This commonly occurs when legalizing i64 values, so
5922     // it's worth handling here.
5923     if (N2CV && N2CV->isZero())
5924       return N1;
5925     if ((Opcode == ISD::ADD || Opcode == ISD::SUB) && VT.isVector() &&
5926         VT.getVectorElementType() == MVT::i1)
5927       return getNode(ISD::XOR, DL, VT, N1, N2);
5928     break;
5929   case ISD::MUL:
5930     assert(VT.isInteger() && "This operator does not apply to FP types!");
5931     assert(N1.getValueType() == N2.getValueType() &&
5932            N1.getValueType() == VT && "Binary operator types must match!");
5933     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
5934       return getNode(ISD::AND, DL, VT, N1, N2);
5935     if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
5936       const APInt &MulImm = N1->getConstantOperandAPInt(0);
5937       const APInt &N2CImm = N2C->getAPIntValue();
5938       return getVScale(DL, VT, MulImm * N2CImm);
5939     }
5940     break;
5941   case ISD::UDIV:
5942   case ISD::UREM:
5943   case ISD::MULHU:
5944   case ISD::MULHS:
5945   case ISD::SDIV:
5946   case ISD::SREM:
5947   case ISD::SADDSAT:
5948   case ISD::SSUBSAT:
5949   case ISD::UADDSAT:
5950   case ISD::USUBSAT:
5951     assert(VT.isInteger() && "This operator does not apply to FP types!");
5952     assert(N1.getValueType() == N2.getValueType() &&
5953            N1.getValueType() == VT && "Binary operator types must match!");
5954     if (VT.isVector() && VT.getVectorElementType() == MVT::i1) {
5955       // fold (add_sat x, y) -> (or x, y) for bool types.
5956       if (Opcode == ISD::SADDSAT || Opcode == ISD::UADDSAT)
5957         return getNode(ISD::OR, DL, VT, N1, N2);
5958       // fold (sub_sat x, y) -> (and x, ~y) for bool types.
5959       if (Opcode == ISD::SSUBSAT || Opcode == ISD::USUBSAT)
5960         return getNode(ISD::AND, DL, VT, N1, getNOT(DL, N2, VT));
5961     }
5962     break;
5963   case ISD::SMIN:
5964   case ISD::UMAX:
5965     assert(VT.isInteger() && "This operator does not apply to FP types!");
5966     assert(N1.getValueType() == N2.getValueType() &&
5967            N1.getValueType() == VT && "Binary operator types must match!");
5968     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
5969       return getNode(ISD::OR, DL, VT, N1, N2);
5970     break;
5971   case ISD::SMAX:
5972   case ISD::UMIN:
5973     assert(VT.isInteger() && "This operator does not apply to FP types!");
5974     assert(N1.getValueType() == N2.getValueType() &&
5975            N1.getValueType() == VT && "Binary operator types must match!");
5976     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
5977       return getNode(ISD::AND, DL, VT, N1, N2);
5978     break;
5979   case ISD::FADD:
5980   case ISD::FSUB:
5981   case ISD::FMUL:
5982   case ISD::FDIV:
5983   case ISD::FREM:
5984     assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
5985     assert(N1.getValueType() == N2.getValueType() &&
5986            N1.getValueType() == VT && "Binary operator types must match!");
5987     if (SDValue V = simplifyFPBinop(Opcode, N1, N2, Flags))
5988       return V;
5989     break;
5990   case ISD::FCOPYSIGN:   // N1 and result must match.  N1/N2 need not match.
5991     assert(N1.getValueType() == VT &&
5992            N1.getValueType().isFloatingPoint() &&
5993            N2.getValueType().isFloatingPoint() &&
5994            "Invalid FCOPYSIGN!");
5995     break;
5996   case ISD::SHL:
5997     if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
5998       const APInt &MulImm = N1->getConstantOperandAPInt(0);
5999       const APInt &ShiftImm = N2C->getAPIntValue();
6000       return getVScale(DL, VT, MulImm << ShiftImm);
6001     }
6002     LLVM_FALLTHROUGH;
6003   case ISD::SRA:
6004   case ISD::SRL:
6005     if (SDValue V = simplifyShift(N1, N2))
6006       return V;
6007     LLVM_FALLTHROUGH;
6008   case ISD::ROTL:
6009   case ISD::ROTR:
6010     assert(VT == N1.getValueType() &&
6011            "Shift operators return type must be the same as their first arg");
6012     assert(VT.isInteger() && N2.getValueType().isInteger() &&
6013            "Shifts only work on integers");
6014     assert((!VT.isVector() || VT == N2.getValueType()) &&
6015            "Vector shift amounts must be in the same as their first arg");
6016     // Verify that the shift amount VT is big enough to hold valid shift
6017     // amounts.  This catches things like trying to shift an i1024 value by an
6018     // i8, which is easy to fall into in generic code that uses
6019     // TLI.getShiftAmount().
6020     assert(N2.getValueType().getScalarSizeInBits() >=
6021                Log2_32_Ceil(VT.getScalarSizeInBits()) &&
6022            "Invalid use of small shift amount with oversized value!");
6023 
6024     // Always fold shifts of i1 values so the code generator doesn't need to
6025     // handle them.  Since we know the size of the shift has to be less than the
6026     // size of the value, the shift/rotate count is guaranteed to be zero.
6027     if (VT == MVT::i1)
6028       return N1;
6029     if (N2CV && N2CV->isZero())
6030       return N1;
6031     break;
6032   case ISD::FP_ROUND:
6033     assert(VT.isFloatingPoint() &&
6034            N1.getValueType().isFloatingPoint() &&
6035            VT.bitsLE(N1.getValueType()) &&
6036            N2C && (N2C->getZExtValue() == 0 || N2C->getZExtValue() == 1) &&
6037            "Invalid FP_ROUND!");
6038     if (N1.getValueType() == VT) return N1;  // noop conversion.
6039     break;
6040   case ISD::AssertSext:
6041   case ISD::AssertZext: {
6042     EVT EVT = cast<VTSDNode>(N2)->getVT();
6043     assert(VT == N1.getValueType() && "Not an inreg extend!");
6044     assert(VT.isInteger() && EVT.isInteger() &&
6045            "Cannot *_EXTEND_INREG FP types");
6046     assert(!EVT.isVector() &&
6047            "AssertSExt/AssertZExt type should be the vector element type "
6048            "rather than the vector type!");
6049     assert(EVT.bitsLE(VT.getScalarType()) && "Not extending!");
6050     if (VT.getScalarType() == EVT) return N1; // noop assertion.
6051     break;
6052   }
6053   case ISD::SIGN_EXTEND_INREG: {
6054     EVT EVT = cast<VTSDNode>(N2)->getVT();
6055     assert(VT == N1.getValueType() && "Not an inreg extend!");
6056     assert(VT.isInteger() && EVT.isInteger() &&
6057            "Cannot *_EXTEND_INREG FP types");
6058     assert(EVT.isVector() == VT.isVector() &&
6059            "SIGN_EXTEND_INREG type should be vector iff the operand "
6060            "type is vector!");
6061     assert((!EVT.isVector() ||
6062             EVT.getVectorElementCount() == VT.getVectorElementCount()) &&
6063            "Vector element counts must match in SIGN_EXTEND_INREG");
6064     assert(EVT.bitsLE(VT) && "Not extending!");
6065     if (EVT == VT) return N1;  // Not actually extending
6066 
6067     auto SignExtendInReg = [&](APInt Val, llvm::EVT ConstantVT) {
6068       unsigned FromBits = EVT.getScalarSizeInBits();
6069       Val <<= Val.getBitWidth() - FromBits;
6070       Val.ashrInPlace(Val.getBitWidth() - FromBits);
6071       return getConstant(Val, DL, ConstantVT);
6072     };
6073 
6074     if (N1C) {
6075       const APInt &Val = N1C->getAPIntValue();
6076       return SignExtendInReg(Val, VT);
6077     }
6078 
6079     if (ISD::isBuildVectorOfConstantSDNodes(N1.getNode())) {
6080       SmallVector<SDValue, 8> Ops;
6081       llvm::EVT OpVT = N1.getOperand(0).getValueType();
6082       for (int i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
6083         SDValue Op = N1.getOperand(i);
6084         if (Op.isUndef()) {
6085           Ops.push_back(getUNDEF(OpVT));
6086           continue;
6087         }
6088         ConstantSDNode *C = cast<ConstantSDNode>(Op);
6089         APInt Val = C->getAPIntValue();
6090         Ops.push_back(SignExtendInReg(Val, OpVT));
6091       }
6092       return getBuildVector(VT, DL, Ops);
6093     }
6094     break;
6095   }
6096   case ISD::FP_TO_SINT_SAT:
6097   case ISD::FP_TO_UINT_SAT: {
6098     assert(VT.isInteger() && cast<VTSDNode>(N2)->getVT().isInteger() &&
6099            N1.getValueType().isFloatingPoint() && "Invalid FP_TO_*INT_SAT");
6100     assert(N1.getValueType().isVector() == VT.isVector() &&
6101            "FP_TO_*INT_SAT type should be vector iff the operand type is "
6102            "vector!");
6103     assert((!VT.isVector() || VT.getVectorNumElements() ==
6104                                   N1.getValueType().getVectorNumElements()) &&
6105            "Vector element counts must match in FP_TO_*INT_SAT");
6106     assert(!cast<VTSDNode>(N2)->getVT().isVector() &&
6107            "Type to saturate to must be a scalar.");
6108     assert(cast<VTSDNode>(N2)->getVT().bitsLE(VT.getScalarType()) &&
6109            "Not extending!");
6110     break;
6111   }
6112   case ISD::EXTRACT_VECTOR_ELT:
6113     assert(VT.getSizeInBits() >= N1.getValueType().getScalarSizeInBits() &&
6114            "The result of EXTRACT_VECTOR_ELT must be at least as wide as the \
6115              element type of the vector.");
6116 
6117     // Extract from an undefined value or using an undefined index is undefined.
6118     if (N1.isUndef() || N2.isUndef())
6119       return getUNDEF(VT);
6120 
6121     // EXTRACT_VECTOR_ELT of out-of-bounds element is an UNDEF for fixed length
6122     // vectors. For scalable vectors we will provide appropriate support for
6123     // dealing with arbitrary indices.
6124     if (N2C && N1.getValueType().isFixedLengthVector() &&
6125         N2C->getAPIntValue().uge(N1.getValueType().getVectorNumElements()))
6126       return getUNDEF(VT);
6127 
6128     // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
6129     // expanding copies of large vectors from registers. This only works for
6130     // fixed length vectors, since we need to know the exact number of
6131     // elements.
6132     if (N2C && N1.getOperand(0).getValueType().isFixedLengthVector() &&
6133         N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0) {
6134       unsigned Factor =
6135         N1.getOperand(0).getValueType().getVectorNumElements();
6136       return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
6137                      N1.getOperand(N2C->getZExtValue() / Factor),
6138                      getVectorIdxConstant(N2C->getZExtValue() % Factor, DL));
6139     }
6140 
6141     // EXTRACT_VECTOR_ELT of BUILD_VECTOR or SPLAT_VECTOR is often formed while
6142     // lowering is expanding large vector constants.
6143     if (N2C && (N1.getOpcode() == ISD::BUILD_VECTOR ||
6144                 N1.getOpcode() == ISD::SPLAT_VECTOR)) {
6145       assert((N1.getOpcode() != ISD::BUILD_VECTOR ||
6146               N1.getValueType().isFixedLengthVector()) &&
6147              "BUILD_VECTOR used for scalable vectors");
6148       unsigned Index =
6149           N1.getOpcode() == ISD::BUILD_VECTOR ? N2C->getZExtValue() : 0;
6150       SDValue Elt = N1.getOperand(Index);
6151 
6152       if (VT != Elt.getValueType())
6153         // If the vector element type is not legal, the BUILD_VECTOR operands
6154         // are promoted and implicitly truncated, and the result implicitly
6155         // extended. Make that explicit here.
6156         Elt = getAnyExtOrTrunc(Elt, DL, VT);
6157 
6158       return Elt;
6159     }
6160 
6161     // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
6162     // operations are lowered to scalars.
6163     if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) {
6164       // If the indices are the same, return the inserted element else
6165       // if the indices are known different, extract the element from
6166       // the original vector.
6167       SDValue N1Op2 = N1.getOperand(2);
6168       ConstantSDNode *N1Op2C = dyn_cast<ConstantSDNode>(N1Op2);
6169 
6170       if (N1Op2C && N2C) {
6171         if (N1Op2C->getZExtValue() == N2C->getZExtValue()) {
6172           if (VT == N1.getOperand(1).getValueType())
6173             return N1.getOperand(1);
6174           if (VT.isFloatingPoint()) {
6175             assert(VT.getSizeInBits() > N1.getOperand(1).getValueType().getSizeInBits());
6176             return getFPExtendOrRound(N1.getOperand(1), DL, VT);
6177           }
6178           return getSExtOrTrunc(N1.getOperand(1), DL, VT);
6179         }
6180         return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2);
6181       }
6182     }
6183 
6184     // EXTRACT_VECTOR_ELT of v1iX EXTRACT_SUBVECTOR could be formed
6185     // when vector types are scalarized and v1iX is legal.
6186     // vextract (v1iX extract_subvector(vNiX, Idx)) -> vextract(vNiX,Idx).
6187     // Here we are completely ignoring the extract element index (N2),
6188     // which is fine for fixed width vectors, since any index other than 0
6189     // is undefined anyway. However, this cannot be ignored for scalable
6190     // vectors - in theory we could support this, but we don't want to do this
6191     // without a profitability check.
6192     if (N1.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
6193         N1.getValueType().isFixedLengthVector() &&
6194         N1.getValueType().getVectorNumElements() == 1) {
6195       return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0),
6196                      N1.getOperand(1));
6197     }
6198     break;
6199   case ISD::EXTRACT_ELEMENT:
6200     assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!");
6201     assert(!N1.getValueType().isVector() && !VT.isVector() &&
6202            (N1.getValueType().isInteger() == VT.isInteger()) &&
6203            N1.getValueType() != VT &&
6204            "Wrong types for EXTRACT_ELEMENT!");
6205 
6206     // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
6207     // 64-bit integers into 32-bit parts.  Instead of building the extract of
6208     // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
6209     if (N1.getOpcode() == ISD::BUILD_PAIR)
6210       return N1.getOperand(N2C->getZExtValue());
6211 
6212     // EXTRACT_ELEMENT of a constant int is also very common.
6213     if (N1C) {
6214       unsigned ElementSize = VT.getSizeInBits();
6215       unsigned Shift = ElementSize * N2C->getZExtValue();
6216       const APInt &Val = N1C->getAPIntValue();
6217       return getConstant(Val.extractBits(ElementSize, Shift), DL, VT);
6218     }
6219     break;
6220   case ISD::EXTRACT_SUBVECTOR: {
6221     EVT N1VT = N1.getValueType();
6222     assert(VT.isVector() && N1VT.isVector() &&
6223            "Extract subvector VTs must be vectors!");
6224     assert(VT.getVectorElementType() == N1VT.getVectorElementType() &&
6225            "Extract subvector VTs must have the same element type!");
6226     assert((VT.isFixedLengthVector() || N1VT.isScalableVector()) &&
6227            "Cannot extract a scalable vector from a fixed length vector!");
6228     assert((VT.isScalableVector() != N1VT.isScalableVector() ||
6229             VT.getVectorMinNumElements() <= N1VT.getVectorMinNumElements()) &&
6230            "Extract subvector must be from larger vector to smaller vector!");
6231     assert(N2C && "Extract subvector index must be a constant");
6232     assert((VT.isScalableVector() != N1VT.isScalableVector() ||
6233             (VT.getVectorMinNumElements() + N2C->getZExtValue()) <=
6234                 N1VT.getVectorMinNumElements()) &&
6235            "Extract subvector overflow!");
6236     assert(N2C->getAPIntValue().getBitWidth() ==
6237                TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() &&
6238            "Constant index for EXTRACT_SUBVECTOR has an invalid size");
6239 
6240     // Trivial extraction.
6241     if (VT == N1VT)
6242       return N1;
6243 
6244     // EXTRACT_SUBVECTOR of an UNDEF is an UNDEF.
6245     if (N1.isUndef())
6246       return getUNDEF(VT);
6247 
6248     // EXTRACT_SUBVECTOR of CONCAT_VECTOR can be simplified if the pieces of
6249     // the concat have the same type as the extract.
6250     if (N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0 &&
6251         VT == N1.getOperand(0).getValueType()) {
6252       unsigned Factor = VT.getVectorMinNumElements();
6253       return N1.getOperand(N2C->getZExtValue() / Factor);
6254     }
6255 
6256     // EXTRACT_SUBVECTOR of INSERT_SUBVECTOR is often created
6257     // during shuffle legalization.
6258     if (N1.getOpcode() == ISD::INSERT_SUBVECTOR && N2 == N1.getOperand(2) &&
6259         VT == N1.getOperand(1).getValueType())
6260       return N1.getOperand(1);
6261     break;
6262   }
6263   }
6264 
6265   // Perform trivial constant folding.
6266   if (SDValue SV = FoldConstantArithmetic(Opcode, DL, VT, {N1, N2}))
6267     return SV;
6268 
6269   // Canonicalize an UNDEF to the RHS, even over a constant.
6270   if (N1.isUndef()) {
6271     if (TLI->isCommutativeBinOp(Opcode)) {
6272       std::swap(N1, N2);
6273     } else {
6274       switch (Opcode) {
6275       case ISD::SUB:
6276         return getUNDEF(VT);     // fold op(undef, arg2) -> undef
6277       case ISD::SIGN_EXTEND_INREG:
6278       case ISD::UDIV:
6279       case ISD::SDIV:
6280       case ISD::UREM:
6281       case ISD::SREM:
6282       case ISD::SSUBSAT:
6283       case ISD::USUBSAT:
6284         return getConstant(0, DL, VT);    // fold op(undef, arg2) -> 0
6285       }
6286     }
6287   }
6288 
6289   // Fold a bunch of operators when the RHS is undef.
6290   if (N2.isUndef()) {
6291     switch (Opcode) {
6292     case ISD::XOR:
6293       if (N1.isUndef())
6294         // Handle undef ^ undef -> 0 special case. This is a common
6295         // idiom (misuse).
6296         return getConstant(0, DL, VT);
6297       LLVM_FALLTHROUGH;
6298     case ISD::ADD:
6299     case ISD::SUB:
6300     case ISD::UDIV:
6301     case ISD::SDIV:
6302     case ISD::UREM:
6303     case ISD::SREM:
6304       return getUNDEF(VT);       // fold op(arg1, undef) -> undef
6305     case ISD::MUL:
6306     case ISD::AND:
6307     case ISD::SSUBSAT:
6308     case ISD::USUBSAT:
6309       return getConstant(0, DL, VT);  // fold op(arg1, undef) -> 0
6310     case ISD::OR:
6311     case ISD::SADDSAT:
6312     case ISD::UADDSAT:
6313       return getAllOnesConstant(DL, VT);
6314     }
6315   }
6316 
6317   // Memoize this node if possible.
6318   SDNode *N;
6319   SDVTList VTs = getVTList(VT);
6320   SDValue Ops[] = {N1, N2};
6321   if (VT != MVT::Glue) {
6322     FoldingSetNodeID ID;
6323     AddNodeIDNode(ID, Opcode, VTs, Ops);
6324     void *IP = nullptr;
6325     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
6326       E->intersectFlagsWith(Flags);
6327       return SDValue(E, 0);
6328     }
6329 
6330     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6331     N->setFlags(Flags);
6332     createOperands(N, Ops);
6333     CSEMap.InsertNode(N, IP);
6334   } else {
6335     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6336     createOperands(N, Ops);
6337   }
6338 
6339   InsertNode(N);
6340   SDValue V = SDValue(N, 0);
6341   NewSDValueDbgMsg(V, "Creating new node: ", this);
6342   return V;
6343 }
6344 
6345 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6346                               SDValue N1, SDValue N2, SDValue N3) {
6347   SDNodeFlags Flags;
6348   if (Inserter)
6349     Flags = Inserter->getFlags();
6350   return getNode(Opcode, DL, VT, N1, N2, N3, Flags);
6351 }
6352 
6353 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6354                               SDValue N1, SDValue N2, SDValue N3,
6355                               const SDNodeFlags Flags) {
6356   assert(N1.getOpcode() != ISD::DELETED_NODE &&
6357          N2.getOpcode() != ISD::DELETED_NODE &&
6358          N3.getOpcode() != ISD::DELETED_NODE &&
6359          "Operand is DELETED_NODE!");
6360   // Perform various simplifications.
6361   switch (Opcode) {
6362   case ISD::FMA: {
6363     assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
6364     assert(N1.getValueType() == VT && N2.getValueType() == VT &&
6365            N3.getValueType() == VT && "FMA types must match!");
6366     ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6367     ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
6368     ConstantFPSDNode *N3CFP = dyn_cast<ConstantFPSDNode>(N3);
6369     if (N1CFP && N2CFP && N3CFP) {
6370       APFloat  V1 = N1CFP->getValueAPF();
6371       const APFloat &V2 = N2CFP->getValueAPF();
6372       const APFloat &V3 = N3CFP->getValueAPF();
6373       V1.fusedMultiplyAdd(V2, V3, APFloat::rmNearestTiesToEven);
6374       return getConstantFP(V1, DL, VT);
6375     }
6376     break;
6377   }
6378   case ISD::BUILD_VECTOR: {
6379     // Attempt to simplify BUILD_VECTOR.
6380     SDValue Ops[] = {N1, N2, N3};
6381     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
6382       return V;
6383     break;
6384   }
6385   case ISD::CONCAT_VECTORS: {
6386     SDValue Ops[] = {N1, N2, N3};
6387     if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
6388       return V;
6389     break;
6390   }
6391   case ISD::SETCC: {
6392     assert(VT.isInteger() && "SETCC result type must be an integer!");
6393     assert(N1.getValueType() == N2.getValueType() &&
6394            "SETCC operands must have the same type!");
6395     assert(VT.isVector() == N1.getValueType().isVector() &&
6396            "SETCC type should be vector iff the operand type is vector!");
6397     assert((!VT.isVector() || VT.getVectorElementCount() ==
6398                                   N1.getValueType().getVectorElementCount()) &&
6399            "SETCC vector element counts must match!");
6400     // Use FoldSetCC to simplify SETCC's.
6401     if (SDValue V = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL))
6402       return V;
6403     // Vector constant folding.
6404     SDValue Ops[] = {N1, N2, N3};
6405     if (SDValue V = FoldConstantArithmetic(Opcode, DL, VT, Ops)) {
6406       NewSDValueDbgMsg(V, "New node vector constant folding: ", this);
6407       return V;
6408     }
6409     break;
6410   }
6411   case ISD::SELECT:
6412   case ISD::VSELECT:
6413     if (SDValue V = simplifySelect(N1, N2, N3))
6414       return V;
6415     break;
6416   case ISD::VECTOR_SHUFFLE:
6417     llvm_unreachable("should use getVectorShuffle constructor!");
6418   case ISD::VECTOR_SPLICE: {
6419     if (cast<ConstantSDNode>(N3)->isNullValue())
6420       return N1;
6421     break;
6422   }
6423   case ISD::INSERT_VECTOR_ELT: {
6424     ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3);
6425     // INSERT_VECTOR_ELT into out-of-bounds element is an UNDEF, except
6426     // for scalable vectors where we will generate appropriate code to
6427     // deal with out-of-bounds cases correctly.
6428     if (N3C && N1.getValueType().isFixedLengthVector() &&
6429         N3C->getZExtValue() >= N1.getValueType().getVectorNumElements())
6430       return getUNDEF(VT);
6431 
6432     // Undefined index can be assumed out-of-bounds, so that's UNDEF too.
6433     if (N3.isUndef())
6434       return getUNDEF(VT);
6435 
6436     // If the inserted element is an UNDEF, just use the input vector.
6437     if (N2.isUndef())
6438       return N1;
6439 
6440     break;
6441   }
6442   case ISD::INSERT_SUBVECTOR: {
6443     // Inserting undef into undef is still undef.
6444     if (N1.isUndef() && N2.isUndef())
6445       return getUNDEF(VT);
6446 
6447     EVT N2VT = N2.getValueType();
6448     assert(VT == N1.getValueType() &&
6449            "Dest and insert subvector source types must match!");
6450     assert(VT.isVector() && N2VT.isVector() &&
6451            "Insert subvector VTs must be vectors!");
6452     assert((VT.isScalableVector() || N2VT.isFixedLengthVector()) &&
6453            "Cannot insert a scalable vector into a fixed length vector!");
6454     assert((VT.isScalableVector() != N2VT.isScalableVector() ||
6455             VT.getVectorMinNumElements() >= N2VT.getVectorMinNumElements()) &&
6456            "Insert subvector must be from smaller vector to larger vector!");
6457     assert(isa<ConstantSDNode>(N3) &&
6458            "Insert subvector index must be constant");
6459     assert((VT.isScalableVector() != N2VT.isScalableVector() ||
6460             (N2VT.getVectorMinNumElements() +
6461              cast<ConstantSDNode>(N3)->getZExtValue()) <=
6462                 VT.getVectorMinNumElements()) &&
6463            "Insert subvector overflow!");
6464     assert(cast<ConstantSDNode>(N3)->getAPIntValue().getBitWidth() ==
6465                TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() &&
6466            "Constant index for INSERT_SUBVECTOR has an invalid size");
6467 
6468     // Trivial insertion.
6469     if (VT == N2VT)
6470       return N2;
6471 
6472     // If this is an insert of an extracted vector into an undef vector, we
6473     // can just use the input to the extract.
6474     if (N1.isUndef() && N2.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
6475         N2.getOperand(1) == N3 && N2.getOperand(0).getValueType() == VT)
6476       return N2.getOperand(0);
6477     break;
6478   }
6479   case ISD::BITCAST:
6480     // Fold bit_convert nodes from a type to themselves.
6481     if (N1.getValueType() == VT)
6482       return N1;
6483     break;
6484   }
6485 
6486   // Memoize node if it doesn't produce a flag.
6487   SDNode *N;
6488   SDVTList VTs = getVTList(VT);
6489   SDValue Ops[] = {N1, N2, N3};
6490   if (VT != MVT::Glue) {
6491     FoldingSetNodeID ID;
6492     AddNodeIDNode(ID, Opcode, VTs, Ops);
6493     void *IP = nullptr;
6494     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
6495       E->intersectFlagsWith(Flags);
6496       return SDValue(E, 0);
6497     }
6498 
6499     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6500     N->setFlags(Flags);
6501     createOperands(N, Ops);
6502     CSEMap.InsertNode(N, IP);
6503   } else {
6504     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6505     createOperands(N, Ops);
6506   }
6507 
6508   InsertNode(N);
6509   SDValue V = SDValue(N, 0);
6510   NewSDValueDbgMsg(V, "Creating new node: ", this);
6511   return V;
6512 }
6513 
6514 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6515                               SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
6516   SDValue Ops[] = { N1, N2, N3, N4 };
6517   return getNode(Opcode, DL, VT, Ops);
6518 }
6519 
6520 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6521                               SDValue N1, SDValue N2, SDValue N3, SDValue N4,
6522                               SDValue N5) {
6523   SDValue Ops[] = { N1, N2, N3, N4, N5 };
6524   return getNode(Opcode, DL, VT, Ops);
6525 }
6526 
6527 /// getStackArgumentTokenFactor - Compute a TokenFactor to force all
6528 /// the incoming stack arguments to be loaded from the stack.
6529 SDValue SelectionDAG::getStackArgumentTokenFactor(SDValue Chain) {
6530   SmallVector<SDValue, 8> ArgChains;
6531 
6532   // Include the original chain at the beginning of the list. When this is
6533   // used by target LowerCall hooks, this helps legalize find the
6534   // CALLSEQ_BEGIN node.
6535   ArgChains.push_back(Chain);
6536 
6537   // Add a chain value for each stack argument.
6538   for (SDNode *U : getEntryNode().getNode()->uses())
6539     if (LoadSDNode *L = dyn_cast<LoadSDNode>(U))
6540       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
6541         if (FI->getIndex() < 0)
6542           ArgChains.push_back(SDValue(L, 1));
6543 
6544   // Build a tokenfactor for all the chains.
6545   return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
6546 }
6547 
6548 /// getMemsetValue - Vectorized representation of the memset value
6549 /// operand.
6550 static SDValue getMemsetValue(SDValue Value, EVT VT, SelectionDAG &DAG,
6551                               const SDLoc &dl) {
6552   assert(!Value.isUndef());
6553 
6554   unsigned NumBits = VT.getScalarSizeInBits();
6555   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
6556     assert(C->getAPIntValue().getBitWidth() == 8);
6557     APInt Val = APInt::getSplat(NumBits, C->getAPIntValue());
6558     if (VT.isInteger()) {
6559       bool IsOpaque = VT.getSizeInBits() > 64 ||
6560           !DAG.getTargetLoweringInfo().isLegalStoreImmediate(C->getSExtValue());
6561       return DAG.getConstant(Val, dl, VT, false, IsOpaque);
6562     }
6563     return DAG.getConstantFP(APFloat(DAG.EVTToAPFloatSemantics(VT), Val), dl,
6564                              VT);
6565   }
6566 
6567   assert(Value.getValueType() == MVT::i8 && "memset with non-byte fill value?");
6568   EVT IntVT = VT.getScalarType();
6569   if (!IntVT.isInteger())
6570     IntVT = EVT::getIntegerVT(*DAG.getContext(), IntVT.getSizeInBits());
6571 
6572   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, Value);
6573   if (NumBits > 8) {
6574     // Use a multiplication with 0x010101... to extend the input to the
6575     // required length.
6576     APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01));
6577     Value = DAG.getNode(ISD::MUL, dl, IntVT, Value,
6578                         DAG.getConstant(Magic, dl, IntVT));
6579   }
6580 
6581   if (VT != Value.getValueType() && !VT.isInteger())
6582     Value = DAG.getBitcast(VT.getScalarType(), Value);
6583   if (VT != Value.getValueType())
6584     Value = DAG.getSplatBuildVector(VT, dl, Value);
6585 
6586   return Value;
6587 }
6588 
6589 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
6590 /// used when a memcpy is turned into a memset when the source is a constant
6591 /// string ptr.
6592 static SDValue getMemsetStringVal(EVT VT, const SDLoc &dl, SelectionDAG &DAG,
6593                                   const TargetLowering &TLI,
6594                                   const ConstantDataArraySlice &Slice) {
6595   // Handle vector with all elements zero.
6596   if (Slice.Array == nullptr) {
6597     if (VT.isInteger())
6598       return DAG.getConstant(0, dl, VT);
6599     if (VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128)
6600       return DAG.getConstantFP(0.0, dl, VT);
6601     if (VT.isVector()) {
6602       unsigned NumElts = VT.getVectorNumElements();
6603       MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
6604       return DAG.getNode(ISD::BITCAST, dl, VT,
6605                          DAG.getConstant(0, dl,
6606                                          EVT::getVectorVT(*DAG.getContext(),
6607                                                           EltVT, NumElts)));
6608     }
6609     llvm_unreachable("Expected type!");
6610   }
6611 
6612   assert(!VT.isVector() && "Can't handle vector type here!");
6613   unsigned NumVTBits = VT.getSizeInBits();
6614   unsigned NumVTBytes = NumVTBits / 8;
6615   unsigned NumBytes = std::min(NumVTBytes, unsigned(Slice.Length));
6616 
6617   APInt Val(NumVTBits, 0);
6618   if (DAG.getDataLayout().isLittleEndian()) {
6619     for (unsigned i = 0; i != NumBytes; ++i)
6620       Val |= (uint64_t)(unsigned char)Slice[i] << i*8;
6621   } else {
6622     for (unsigned i = 0; i != NumBytes; ++i)
6623       Val |= (uint64_t)(unsigned char)Slice[i] << (NumVTBytes-i-1)*8;
6624   }
6625 
6626   // If the "cost" of materializing the integer immediate is less than the cost
6627   // of a load, then it is cost effective to turn the load into the immediate.
6628   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
6629   if (TLI.shouldConvertConstantLoadToIntImm(Val, Ty))
6630     return DAG.getConstant(Val, dl, VT);
6631   return SDValue();
6632 }
6633 
6634 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Base, TypeSize Offset,
6635                                            const SDLoc &DL,
6636                                            const SDNodeFlags Flags) {
6637   EVT VT = Base.getValueType();
6638   SDValue Index;
6639 
6640   if (Offset.isScalable())
6641     Index = getVScale(DL, Base.getValueType(),
6642                       APInt(Base.getValueSizeInBits().getFixedSize(),
6643                             Offset.getKnownMinSize()));
6644   else
6645     Index = getConstant(Offset.getFixedSize(), DL, VT);
6646 
6647   return getMemBasePlusOffset(Base, Index, DL, Flags);
6648 }
6649 
6650 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Ptr, SDValue Offset,
6651                                            const SDLoc &DL,
6652                                            const SDNodeFlags Flags) {
6653   assert(Offset.getValueType().isInteger());
6654   EVT BasePtrVT = Ptr.getValueType();
6655   return getNode(ISD::ADD, DL, BasePtrVT, Ptr, Offset, Flags);
6656 }
6657 
6658 /// Returns true if memcpy source is constant data.
6659 static bool isMemSrcFromConstant(SDValue Src, ConstantDataArraySlice &Slice) {
6660   uint64_t SrcDelta = 0;
6661   GlobalAddressSDNode *G = nullptr;
6662   if (Src.getOpcode() == ISD::GlobalAddress)
6663     G = cast<GlobalAddressSDNode>(Src);
6664   else if (Src.getOpcode() == ISD::ADD &&
6665            Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
6666            Src.getOperand(1).getOpcode() == ISD::Constant) {
6667     G = cast<GlobalAddressSDNode>(Src.getOperand(0));
6668     SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue();
6669   }
6670   if (!G)
6671     return false;
6672 
6673   return getConstantDataArrayInfo(G->getGlobal(), Slice, 8,
6674                                   SrcDelta + G->getOffset());
6675 }
6676 
6677 static bool shouldLowerMemFuncForSize(const MachineFunction &MF,
6678                                       SelectionDAG &DAG) {
6679   // On Darwin, -Os means optimize for size without hurting performance, so
6680   // only really optimize for size when -Oz (MinSize) is used.
6681   if (MF.getTarget().getTargetTriple().isOSDarwin())
6682     return MF.getFunction().hasMinSize();
6683   return DAG.shouldOptForSize();
6684 }
6685 
6686 static void chainLoadsAndStoresForMemcpy(SelectionDAG &DAG, const SDLoc &dl,
6687                           SmallVector<SDValue, 32> &OutChains, unsigned From,
6688                           unsigned To, SmallVector<SDValue, 16> &OutLoadChains,
6689                           SmallVector<SDValue, 16> &OutStoreChains) {
6690   assert(OutLoadChains.size() && "Missing loads in memcpy inlining");
6691   assert(OutStoreChains.size() && "Missing stores in memcpy inlining");
6692   SmallVector<SDValue, 16> GluedLoadChains;
6693   for (unsigned i = From; i < To; ++i) {
6694     OutChains.push_back(OutLoadChains[i]);
6695     GluedLoadChains.push_back(OutLoadChains[i]);
6696   }
6697 
6698   // Chain for all loads.
6699   SDValue LoadToken = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6700                                   GluedLoadChains);
6701 
6702   for (unsigned i = From; i < To; ++i) {
6703     StoreSDNode *ST = dyn_cast<StoreSDNode>(OutStoreChains[i]);
6704     SDValue NewStore = DAG.getTruncStore(LoadToken, dl, ST->getValue(),
6705                                   ST->getBasePtr(), ST->getMemoryVT(),
6706                                   ST->getMemOperand());
6707     OutChains.push_back(NewStore);
6708   }
6709 }
6710 
6711 static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
6712                                        SDValue Chain, SDValue Dst, SDValue Src,
6713                                        uint64_t Size, Align Alignment,
6714                                        bool isVol, bool AlwaysInline,
6715                                        MachinePointerInfo DstPtrInfo,
6716                                        MachinePointerInfo SrcPtrInfo,
6717                                        const AAMDNodes &AAInfo) {
6718   // Turn a memcpy of undef to nop.
6719   // FIXME: We need to honor volatile even is Src is undef.
6720   if (Src.isUndef())
6721     return Chain;
6722 
6723   // Expand memcpy to a series of load and store ops if the size operand falls
6724   // below a certain threshold.
6725   // TODO: In the AlwaysInline case, if the size is big then generate a loop
6726   // rather than maybe a humongous number of loads and stores.
6727   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6728   const DataLayout &DL = DAG.getDataLayout();
6729   LLVMContext &C = *DAG.getContext();
6730   std::vector<EVT> MemOps;
6731   bool DstAlignCanChange = false;
6732   MachineFunction &MF = DAG.getMachineFunction();
6733   MachineFrameInfo &MFI = MF.getFrameInfo();
6734   bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
6735   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
6736   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
6737     DstAlignCanChange = true;
6738   MaybeAlign SrcAlign = DAG.InferPtrAlign(Src);
6739   if (!SrcAlign || Alignment > *SrcAlign)
6740     SrcAlign = Alignment;
6741   assert(SrcAlign && "SrcAlign must be set");
6742   ConstantDataArraySlice Slice;
6743   // If marked as volatile, perform a copy even when marked as constant.
6744   bool CopyFromConstant = !isVol && isMemSrcFromConstant(Src, Slice);
6745   bool isZeroConstant = CopyFromConstant && Slice.Array == nullptr;
6746   unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize);
6747   const MemOp Op = isZeroConstant
6748                        ? MemOp::Set(Size, DstAlignCanChange, Alignment,
6749                                     /*IsZeroMemset*/ true, isVol)
6750                        : MemOp::Copy(Size, DstAlignCanChange, Alignment,
6751                                      *SrcAlign, isVol, CopyFromConstant);
6752   if (!TLI.findOptimalMemOpLowering(
6753           MemOps, Limit, Op, DstPtrInfo.getAddrSpace(),
6754           SrcPtrInfo.getAddrSpace(), MF.getFunction().getAttributes()))
6755     return SDValue();
6756 
6757   if (DstAlignCanChange) {
6758     Type *Ty = MemOps[0].getTypeForEVT(C);
6759     Align NewAlign = DL.getABITypeAlign(Ty);
6760 
6761     // Don't promote to an alignment that would require dynamic stack
6762     // realignment.
6763     const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
6764     if (!TRI->hasStackRealignment(MF))
6765       while (NewAlign > Alignment && DL.exceedsNaturalStackAlignment(NewAlign))
6766         NewAlign = NewAlign.previous();
6767 
6768     if (NewAlign > Alignment) {
6769       // Give the stack frame object a larger alignment if needed.
6770       if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
6771         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
6772       Alignment = NewAlign;
6773     }
6774   }
6775 
6776   // Prepare AAInfo for loads/stores after lowering this memcpy.
6777   AAMDNodes NewAAInfo = AAInfo;
6778   NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
6779 
6780   MachineMemOperand::Flags MMOFlags =
6781       isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
6782   SmallVector<SDValue, 16> OutLoadChains;
6783   SmallVector<SDValue, 16> OutStoreChains;
6784   SmallVector<SDValue, 32> OutChains;
6785   unsigned NumMemOps = MemOps.size();
6786   uint64_t SrcOff = 0, DstOff = 0;
6787   for (unsigned i = 0; i != NumMemOps; ++i) {
6788     EVT VT = MemOps[i];
6789     unsigned VTSize = VT.getSizeInBits() / 8;
6790     SDValue Value, Store;
6791 
6792     if (VTSize > Size) {
6793       // Issuing an unaligned load / store pair  that overlaps with the previous
6794       // pair. Adjust the offset accordingly.
6795       assert(i == NumMemOps-1 && i != 0);
6796       SrcOff -= VTSize - Size;
6797       DstOff -= VTSize - Size;
6798     }
6799 
6800     if (CopyFromConstant &&
6801         (isZeroConstant || (VT.isInteger() && !VT.isVector()))) {
6802       // It's unlikely a store of a vector immediate can be done in a single
6803       // instruction. It would require a load from a constantpool first.
6804       // We only handle zero vectors here.
6805       // FIXME: Handle other cases where store of vector immediate is done in
6806       // a single instruction.
6807       ConstantDataArraySlice SubSlice;
6808       if (SrcOff < Slice.Length) {
6809         SubSlice = Slice;
6810         SubSlice.move(SrcOff);
6811       } else {
6812         // This is an out-of-bounds access and hence UB. Pretend we read zero.
6813         SubSlice.Array = nullptr;
6814         SubSlice.Offset = 0;
6815         SubSlice.Length = VTSize;
6816       }
6817       Value = getMemsetStringVal(VT, dl, DAG, TLI, SubSlice);
6818       if (Value.getNode()) {
6819         Store = DAG.getStore(
6820             Chain, dl, Value,
6821             DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6822             DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo);
6823         OutChains.push_back(Store);
6824       }
6825     }
6826 
6827     if (!Store.getNode()) {
6828       // The type might not be legal for the target.  This should only happen
6829       // if the type is smaller than a legal type, as on PPC, so the right
6830       // thing to do is generate a LoadExt/StoreTrunc pair.  These simplify
6831       // to Load/Store if NVT==VT.
6832       // FIXME does the case above also need this?
6833       EVT NVT = TLI.getTypeToTransformTo(C, VT);
6834       assert(NVT.bitsGE(VT));
6835 
6836       bool isDereferenceable =
6837         SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
6838       MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
6839       if (isDereferenceable)
6840         SrcMMOFlags |= MachineMemOperand::MODereferenceable;
6841 
6842       Value = DAG.getExtLoad(
6843           ISD::EXTLOAD, dl, NVT, Chain,
6844           DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl),
6845           SrcPtrInfo.getWithOffset(SrcOff), VT,
6846           commonAlignment(*SrcAlign, SrcOff), SrcMMOFlags, NewAAInfo);
6847       OutLoadChains.push_back(Value.getValue(1));
6848 
6849       Store = DAG.getTruncStore(
6850           Chain, dl, Value,
6851           DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6852           DstPtrInfo.getWithOffset(DstOff), VT, Alignment, MMOFlags, NewAAInfo);
6853       OutStoreChains.push_back(Store);
6854     }
6855     SrcOff += VTSize;
6856     DstOff += VTSize;
6857     Size -= VTSize;
6858   }
6859 
6860   unsigned GluedLdStLimit = MaxLdStGlue == 0 ?
6861                                 TLI.getMaxGluedStoresPerMemcpy() : MaxLdStGlue;
6862   unsigned NumLdStInMemcpy = OutStoreChains.size();
6863 
6864   if (NumLdStInMemcpy) {
6865     // It may be that memcpy might be converted to memset if it's memcpy
6866     // of constants. In such a case, we won't have loads and stores, but
6867     // just stores. In the absence of loads, there is nothing to gang up.
6868     if ((GluedLdStLimit <= 1) || !EnableMemCpyDAGOpt) {
6869       // If target does not care, just leave as it.
6870       for (unsigned i = 0; i < NumLdStInMemcpy; ++i) {
6871         OutChains.push_back(OutLoadChains[i]);
6872         OutChains.push_back(OutStoreChains[i]);
6873       }
6874     } else {
6875       // Ld/St less than/equal limit set by target.
6876       if (NumLdStInMemcpy <= GluedLdStLimit) {
6877           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
6878                                         NumLdStInMemcpy, OutLoadChains,
6879                                         OutStoreChains);
6880       } else {
6881         unsigned NumberLdChain =  NumLdStInMemcpy / GluedLdStLimit;
6882         unsigned RemainingLdStInMemcpy = NumLdStInMemcpy % GluedLdStLimit;
6883         unsigned GlueIter = 0;
6884 
6885         for (unsigned cnt = 0; cnt < NumberLdChain; ++cnt) {
6886           unsigned IndexFrom = NumLdStInMemcpy - GlueIter - GluedLdStLimit;
6887           unsigned IndexTo   = NumLdStInMemcpy - GlueIter;
6888 
6889           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, IndexFrom, IndexTo,
6890                                        OutLoadChains, OutStoreChains);
6891           GlueIter += GluedLdStLimit;
6892         }
6893 
6894         // Residual ld/st.
6895         if (RemainingLdStInMemcpy) {
6896           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
6897                                         RemainingLdStInMemcpy, OutLoadChains,
6898                                         OutStoreChains);
6899         }
6900       }
6901     }
6902   }
6903   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
6904 }
6905 
6906 static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
6907                                         SDValue Chain, SDValue Dst, SDValue Src,
6908                                         uint64_t Size, Align Alignment,
6909                                         bool isVol, bool AlwaysInline,
6910                                         MachinePointerInfo DstPtrInfo,
6911                                         MachinePointerInfo SrcPtrInfo,
6912                                         const AAMDNodes &AAInfo) {
6913   // Turn a memmove of undef to nop.
6914   // FIXME: We need to honor volatile even is Src is undef.
6915   if (Src.isUndef())
6916     return Chain;
6917 
6918   // Expand memmove to a series of load and store ops if the size operand falls
6919   // below a certain threshold.
6920   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6921   const DataLayout &DL = DAG.getDataLayout();
6922   LLVMContext &C = *DAG.getContext();
6923   std::vector<EVT> MemOps;
6924   bool DstAlignCanChange = false;
6925   MachineFunction &MF = DAG.getMachineFunction();
6926   MachineFrameInfo &MFI = MF.getFrameInfo();
6927   bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
6928   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
6929   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
6930     DstAlignCanChange = true;
6931   MaybeAlign SrcAlign = DAG.InferPtrAlign(Src);
6932   if (!SrcAlign || Alignment > *SrcAlign)
6933     SrcAlign = Alignment;
6934   assert(SrcAlign && "SrcAlign must be set");
6935   unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize);
6936   if (!TLI.findOptimalMemOpLowering(
6937           MemOps, Limit,
6938           MemOp::Copy(Size, DstAlignCanChange, Alignment, *SrcAlign,
6939                       /*IsVolatile*/ true),
6940           DstPtrInfo.getAddrSpace(), SrcPtrInfo.getAddrSpace(),
6941           MF.getFunction().getAttributes()))
6942     return SDValue();
6943 
6944   if (DstAlignCanChange) {
6945     Type *Ty = MemOps[0].getTypeForEVT(C);
6946     Align NewAlign = DL.getABITypeAlign(Ty);
6947     if (NewAlign > Alignment) {
6948       // Give the stack frame object a larger alignment if needed.
6949       if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
6950         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
6951       Alignment = NewAlign;
6952     }
6953   }
6954 
6955   // Prepare AAInfo for loads/stores after lowering this memmove.
6956   AAMDNodes NewAAInfo = AAInfo;
6957   NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
6958 
6959   MachineMemOperand::Flags MMOFlags =
6960       isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
6961   uint64_t SrcOff = 0, DstOff = 0;
6962   SmallVector<SDValue, 8> LoadValues;
6963   SmallVector<SDValue, 8> LoadChains;
6964   SmallVector<SDValue, 8> OutChains;
6965   unsigned NumMemOps = MemOps.size();
6966   for (unsigned i = 0; i < NumMemOps; i++) {
6967     EVT VT = MemOps[i];
6968     unsigned VTSize = VT.getSizeInBits() / 8;
6969     SDValue Value;
6970 
6971     bool isDereferenceable =
6972       SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
6973     MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
6974     if (isDereferenceable)
6975       SrcMMOFlags |= MachineMemOperand::MODereferenceable;
6976 
6977     Value = DAG.getLoad(
6978         VT, dl, Chain,
6979         DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl),
6980         SrcPtrInfo.getWithOffset(SrcOff), *SrcAlign, SrcMMOFlags, NewAAInfo);
6981     LoadValues.push_back(Value);
6982     LoadChains.push_back(Value.getValue(1));
6983     SrcOff += VTSize;
6984   }
6985   Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
6986   OutChains.clear();
6987   for (unsigned i = 0; i < NumMemOps; i++) {
6988     EVT VT = MemOps[i];
6989     unsigned VTSize = VT.getSizeInBits() / 8;
6990     SDValue Store;
6991 
6992     Store = DAG.getStore(
6993         Chain, dl, LoadValues[i],
6994         DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6995         DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo);
6996     OutChains.push_back(Store);
6997     DstOff += VTSize;
6998   }
6999 
7000   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
7001 }
7002 
7003 /// Lower the call to 'memset' intrinsic function into a series of store
7004 /// operations.
7005 ///
7006 /// \param DAG Selection DAG where lowered code is placed.
7007 /// \param dl Link to corresponding IR location.
7008 /// \param Chain Control flow dependency.
7009 /// \param Dst Pointer to destination memory location.
7010 /// \param Src Value of byte to write into the memory.
7011 /// \param Size Number of bytes to write.
7012 /// \param Alignment Alignment of the destination in bytes.
7013 /// \param isVol True if destination is volatile.
7014 /// \param AlwaysInline Makes sure no function call is generated.
7015 /// \param DstPtrInfo IR information on the memory pointer.
7016 /// \returns New head in the control flow, if lowering was successful, empty
7017 /// SDValue otherwise.
7018 ///
7019 /// The function tries to replace 'llvm.memset' intrinsic with several store
7020 /// operations and value calculation code. This is usually profitable for small
7021 /// memory size or when the semantic requires inlining.
7022 static SDValue getMemsetStores(SelectionDAG &DAG, const SDLoc &dl,
7023                                SDValue Chain, SDValue Dst, SDValue Src,
7024                                uint64_t Size, Align Alignment, bool isVol,
7025                                bool AlwaysInline, MachinePointerInfo DstPtrInfo,
7026                                const AAMDNodes &AAInfo) {
7027   // Turn a memset of undef to nop.
7028   // FIXME: We need to honor volatile even is Src is undef.
7029   if (Src.isUndef())
7030     return Chain;
7031 
7032   // Expand memset to a series of load/store ops if the size operand
7033   // falls below a certain threshold.
7034   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7035   std::vector<EVT> MemOps;
7036   bool DstAlignCanChange = false;
7037   MachineFunction &MF = DAG.getMachineFunction();
7038   MachineFrameInfo &MFI = MF.getFrameInfo();
7039   bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
7040   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
7041   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
7042     DstAlignCanChange = true;
7043   bool IsZeroVal =
7044       isa<ConstantSDNode>(Src) && cast<ConstantSDNode>(Src)->isZero();
7045   unsigned Limit = AlwaysInline ? ~0 : TLI.getMaxStoresPerMemset(OptSize);
7046 
7047   if (!TLI.findOptimalMemOpLowering(
7048           MemOps, Limit,
7049           MemOp::Set(Size, DstAlignCanChange, Alignment, IsZeroVal, isVol),
7050           DstPtrInfo.getAddrSpace(), ~0u, MF.getFunction().getAttributes()))
7051     return SDValue();
7052 
7053   if (DstAlignCanChange) {
7054     Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
7055     Align NewAlign = DAG.getDataLayout().getABITypeAlign(Ty);
7056     if (NewAlign > Alignment) {
7057       // Give the stack frame object a larger alignment if needed.
7058       if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
7059         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
7060       Alignment = NewAlign;
7061     }
7062   }
7063 
7064   SmallVector<SDValue, 8> OutChains;
7065   uint64_t DstOff = 0;
7066   unsigned NumMemOps = MemOps.size();
7067 
7068   // Find the largest store and generate the bit pattern for it.
7069   EVT LargestVT = MemOps[0];
7070   for (unsigned i = 1; i < NumMemOps; i++)
7071     if (MemOps[i].bitsGT(LargestVT))
7072       LargestVT = MemOps[i];
7073   SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl);
7074 
7075   // Prepare AAInfo for loads/stores after lowering this memset.
7076   AAMDNodes NewAAInfo = AAInfo;
7077   NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
7078 
7079   for (unsigned i = 0; i < NumMemOps; i++) {
7080     EVT VT = MemOps[i];
7081     unsigned VTSize = VT.getSizeInBits() / 8;
7082     if (VTSize > Size) {
7083       // Issuing an unaligned load / store pair  that overlaps with the previous
7084       // pair. Adjust the offset accordingly.
7085       assert(i == NumMemOps-1 && i != 0);
7086       DstOff -= VTSize - Size;
7087     }
7088 
7089     // If this store is smaller than the largest store see whether we can get
7090     // the smaller value for free with a truncate.
7091     SDValue Value = MemSetValue;
7092     if (VT.bitsLT(LargestVT)) {
7093       if (!LargestVT.isVector() && !VT.isVector() &&
7094           TLI.isTruncateFree(LargestVT, VT))
7095         Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue);
7096       else
7097         Value = getMemsetValue(Src, VT, DAG, dl);
7098     }
7099     assert(Value.getValueType() == VT && "Value with wrong type.");
7100     SDValue Store = DAG.getStore(
7101         Chain, dl, Value,
7102         DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
7103         DstPtrInfo.getWithOffset(DstOff), Alignment,
7104         isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone,
7105         NewAAInfo);
7106     OutChains.push_back(Store);
7107     DstOff += VT.getSizeInBits() / 8;
7108     Size -= VTSize;
7109   }
7110 
7111   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
7112 }
7113 
7114 static void checkAddrSpaceIsValidForLibcall(const TargetLowering *TLI,
7115                                             unsigned AS) {
7116   // Lowering memcpy / memset / memmove intrinsics to calls is only valid if all
7117   // pointer operands can be losslessly bitcasted to pointers of address space 0
7118   if (AS != 0 && !TLI->getTargetMachine().isNoopAddrSpaceCast(AS, 0)) {
7119     report_fatal_error("cannot lower memory intrinsic in address space " +
7120                        Twine(AS));
7121   }
7122 }
7123 
7124 SDValue SelectionDAG::getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst,
7125                                 SDValue Src, SDValue Size, Align Alignment,
7126                                 bool isVol, bool AlwaysInline, bool isTailCall,
7127                                 MachinePointerInfo DstPtrInfo,
7128                                 MachinePointerInfo SrcPtrInfo,
7129                                 const AAMDNodes &AAInfo) {
7130   // Check to see if we should lower the memcpy to loads and stores first.
7131   // For cases within the target-specified limits, this is the best choice.
7132   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
7133   if (ConstantSize) {
7134     // Memcpy with size zero? Just return the original chain.
7135     if (ConstantSize->isZero())
7136       return Chain;
7137 
7138     SDValue Result = getMemcpyLoadsAndStores(
7139         *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment,
7140         isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo);
7141     if (Result.getNode())
7142       return Result;
7143   }
7144 
7145   // Then check to see if we should lower the memcpy with target-specific
7146   // code. If the target chooses to do this, this is the next best.
7147   if (TSI) {
7148     SDValue Result = TSI->EmitTargetCodeForMemcpy(
7149         *this, dl, Chain, Dst, Src, Size, Alignment, isVol, AlwaysInline,
7150         DstPtrInfo, SrcPtrInfo);
7151     if (Result.getNode())
7152       return Result;
7153   }
7154 
7155   // If we really need inline code and the target declined to provide it,
7156   // use a (potentially long) sequence of loads and stores.
7157   if (AlwaysInline) {
7158     assert(ConstantSize && "AlwaysInline requires a constant size!");
7159     return getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
7160                                    ConstantSize->getZExtValue(), Alignment,
7161                                    isVol, true, DstPtrInfo, SrcPtrInfo, AAInfo);
7162   }
7163 
7164   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
7165   checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
7166 
7167   // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc
7168   // memcpy is not guaranteed to be safe. libc memcpys aren't required to
7169   // respect volatile, so they may do things like read or write memory
7170   // beyond the given memory regions. But fixing this isn't easy, and most
7171   // people don't care.
7172 
7173   // Emit a library call.
7174   TargetLowering::ArgListTy Args;
7175   TargetLowering::ArgListEntry Entry;
7176   Entry.Ty = Type::getInt8PtrTy(*getContext());
7177   Entry.Node = Dst; Args.push_back(Entry);
7178   Entry.Node = Src; Args.push_back(Entry);
7179 
7180   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7181   Entry.Node = Size; Args.push_back(Entry);
7182   // FIXME: pass in SDLoc
7183   TargetLowering::CallLoweringInfo CLI(*this);
7184   CLI.setDebugLoc(dl)
7185       .setChain(Chain)
7186       .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMCPY),
7187                     Dst.getValueType().getTypeForEVT(*getContext()),
7188                     getExternalSymbol(TLI->getLibcallName(RTLIB::MEMCPY),
7189                                       TLI->getPointerTy(getDataLayout())),
7190                     std::move(Args))
7191       .setDiscardResult()
7192       .setTailCall(isTailCall);
7193 
7194   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
7195   return CallResult.second;
7196 }
7197 
7198 SDValue SelectionDAG::getAtomicMemcpy(SDValue Chain, const SDLoc &dl,
7199                                       SDValue Dst, SDValue Src, SDValue Size,
7200                                       Type *SizeTy, unsigned ElemSz,
7201                                       bool isTailCall,
7202                                       MachinePointerInfo DstPtrInfo,
7203                                       MachinePointerInfo SrcPtrInfo) {
7204   // Emit a library call.
7205   TargetLowering::ArgListTy Args;
7206   TargetLowering::ArgListEntry Entry;
7207   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7208   Entry.Node = Dst;
7209   Args.push_back(Entry);
7210 
7211   Entry.Node = Src;
7212   Args.push_back(Entry);
7213 
7214   Entry.Ty = SizeTy;
7215   Entry.Node = Size;
7216   Args.push_back(Entry);
7217 
7218   RTLIB::Libcall LibraryCall =
7219       RTLIB::getMEMCPY_ELEMENT_UNORDERED_ATOMIC(ElemSz);
7220   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
7221     report_fatal_error("Unsupported element size");
7222 
7223   TargetLowering::CallLoweringInfo CLI(*this);
7224   CLI.setDebugLoc(dl)
7225       .setChain(Chain)
7226       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
7227                     Type::getVoidTy(*getContext()),
7228                     getExternalSymbol(TLI->getLibcallName(LibraryCall),
7229                                       TLI->getPointerTy(getDataLayout())),
7230                     std::move(Args))
7231       .setDiscardResult()
7232       .setTailCall(isTailCall);
7233 
7234   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
7235   return CallResult.second;
7236 }
7237 
7238 SDValue SelectionDAG::getMemmove(SDValue Chain, const SDLoc &dl, SDValue Dst,
7239                                  SDValue Src, SDValue Size, Align Alignment,
7240                                  bool isVol, bool isTailCall,
7241                                  MachinePointerInfo DstPtrInfo,
7242                                  MachinePointerInfo SrcPtrInfo,
7243                                  const AAMDNodes &AAInfo) {
7244   // Check to see if we should lower the memmove to loads and stores first.
7245   // For cases within the target-specified limits, this is the best choice.
7246   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
7247   if (ConstantSize) {
7248     // Memmove with size zero? Just return the original chain.
7249     if (ConstantSize->isZero())
7250       return Chain;
7251 
7252     SDValue Result = getMemmoveLoadsAndStores(
7253         *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment,
7254         isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo);
7255     if (Result.getNode())
7256       return Result;
7257   }
7258 
7259   // Then check to see if we should lower the memmove with target-specific
7260   // code. If the target chooses to do this, this is the next best.
7261   if (TSI) {
7262     SDValue Result =
7263         TSI->EmitTargetCodeForMemmove(*this, dl, Chain, Dst, Src, Size,
7264                                       Alignment, isVol, DstPtrInfo, SrcPtrInfo);
7265     if (Result.getNode())
7266       return Result;
7267   }
7268 
7269   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
7270   checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
7271 
7272   // FIXME: If the memmove is volatile, lowering it to plain libc memmove may
7273   // not be safe.  See memcpy above for more details.
7274 
7275   // Emit a library call.
7276   TargetLowering::ArgListTy Args;
7277   TargetLowering::ArgListEntry Entry;
7278   Entry.Ty = Type::getInt8PtrTy(*getContext());
7279   Entry.Node = Dst; Args.push_back(Entry);
7280   Entry.Node = Src; Args.push_back(Entry);
7281 
7282   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7283   Entry.Node = Size; Args.push_back(Entry);
7284   // FIXME:  pass in SDLoc
7285   TargetLowering::CallLoweringInfo CLI(*this);
7286   CLI.setDebugLoc(dl)
7287       .setChain(Chain)
7288       .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMMOVE),
7289                     Dst.getValueType().getTypeForEVT(*getContext()),
7290                     getExternalSymbol(TLI->getLibcallName(RTLIB::MEMMOVE),
7291                                       TLI->getPointerTy(getDataLayout())),
7292                     std::move(Args))
7293       .setDiscardResult()
7294       .setTailCall(isTailCall);
7295 
7296   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
7297   return CallResult.second;
7298 }
7299 
7300 SDValue SelectionDAG::getAtomicMemmove(SDValue Chain, const SDLoc &dl,
7301                                        SDValue Dst, SDValue Src, SDValue Size,
7302                                        Type *SizeTy, unsigned ElemSz,
7303                                        bool isTailCall,
7304                                        MachinePointerInfo DstPtrInfo,
7305                                        MachinePointerInfo SrcPtrInfo) {
7306   // Emit a library call.
7307   TargetLowering::ArgListTy Args;
7308   TargetLowering::ArgListEntry Entry;
7309   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7310   Entry.Node = Dst;
7311   Args.push_back(Entry);
7312 
7313   Entry.Node = Src;
7314   Args.push_back(Entry);
7315 
7316   Entry.Ty = SizeTy;
7317   Entry.Node = Size;
7318   Args.push_back(Entry);
7319 
7320   RTLIB::Libcall LibraryCall =
7321       RTLIB::getMEMMOVE_ELEMENT_UNORDERED_ATOMIC(ElemSz);
7322   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
7323     report_fatal_error("Unsupported element size");
7324 
7325   TargetLowering::CallLoweringInfo CLI(*this);
7326   CLI.setDebugLoc(dl)
7327       .setChain(Chain)
7328       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
7329                     Type::getVoidTy(*getContext()),
7330                     getExternalSymbol(TLI->getLibcallName(LibraryCall),
7331                                       TLI->getPointerTy(getDataLayout())),
7332                     std::move(Args))
7333       .setDiscardResult()
7334       .setTailCall(isTailCall);
7335 
7336   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
7337   return CallResult.second;
7338 }
7339 
7340 SDValue SelectionDAG::getMemset(SDValue Chain, const SDLoc &dl, SDValue Dst,
7341                                 SDValue Src, SDValue Size, Align Alignment,
7342                                 bool isVol, bool AlwaysInline, bool isTailCall,
7343                                 MachinePointerInfo DstPtrInfo,
7344                                 const AAMDNodes &AAInfo) {
7345   // Check to see if we should lower the memset to stores first.
7346   // For cases within the target-specified limits, this is the best choice.
7347   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
7348   if (ConstantSize) {
7349     // Memset with size zero? Just return the original chain.
7350     if (ConstantSize->isZero())
7351       return Chain;
7352 
7353     SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src,
7354                                      ConstantSize->getZExtValue(), Alignment,
7355                                      isVol, false, DstPtrInfo, AAInfo);
7356 
7357     if (Result.getNode())
7358       return Result;
7359   }
7360 
7361   // Then check to see if we should lower the memset with target-specific
7362   // code. If the target chooses to do this, this is the next best.
7363   if (TSI) {
7364     SDValue Result = TSI->EmitTargetCodeForMemset(
7365         *this, dl, Chain, Dst, Src, Size, Alignment, isVol, AlwaysInline, DstPtrInfo);
7366     if (Result.getNode())
7367       return Result;
7368   }
7369 
7370   // If we really need inline code and the target declined to provide it,
7371   // use a (potentially long) sequence of loads and stores.
7372   if (AlwaysInline) {
7373     assert(ConstantSize && "AlwaysInline requires a constant size!");
7374     SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src,
7375                                      ConstantSize->getZExtValue(), Alignment,
7376                                      isVol, true, DstPtrInfo, AAInfo);
7377     assert(Result &&
7378            "getMemsetStores must return a valid sequence when AlwaysInline");
7379     return Result;
7380   }
7381 
7382   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
7383 
7384   // Emit a library call.
7385   auto &Ctx = *getContext();
7386   const auto& DL = getDataLayout();
7387 
7388   TargetLowering::CallLoweringInfo CLI(*this);
7389   // FIXME: pass in SDLoc
7390   CLI.setDebugLoc(dl).setChain(Chain);
7391 
7392   ConstantSDNode *ConstantSrc = dyn_cast<ConstantSDNode>(Src);
7393   const bool SrcIsZero = ConstantSrc && ConstantSrc->isZero();
7394   const char *BzeroName = getTargetLoweringInfo().getLibcallName(RTLIB::BZERO);
7395 
7396   // Helper function to create an Entry from Node and Type.
7397   const auto CreateEntry = [](SDValue Node, Type *Ty) {
7398     TargetLowering::ArgListEntry Entry;
7399     Entry.Node = Node;
7400     Entry.Ty = Ty;
7401     return Entry;
7402   };
7403 
7404   // If zeroing out and bzero is present, use it.
7405   if (SrcIsZero && BzeroName) {
7406     TargetLowering::ArgListTy Args;
7407     Args.push_back(CreateEntry(Dst, Type::getInt8PtrTy(Ctx)));
7408     Args.push_back(CreateEntry(Size, DL.getIntPtrType(Ctx)));
7409     CLI.setLibCallee(
7410         TLI->getLibcallCallingConv(RTLIB::BZERO), Type::getVoidTy(Ctx),
7411         getExternalSymbol(BzeroName, TLI->getPointerTy(DL)), std::move(Args));
7412   } else {
7413     TargetLowering::ArgListTy Args;
7414     Args.push_back(CreateEntry(Dst, Type::getInt8PtrTy(Ctx)));
7415     Args.push_back(CreateEntry(Src, Src.getValueType().getTypeForEVT(Ctx)));
7416     Args.push_back(CreateEntry(Size, DL.getIntPtrType(Ctx)));
7417     CLI.setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMSET),
7418                      Dst.getValueType().getTypeForEVT(Ctx),
7419                      getExternalSymbol(TLI->getLibcallName(RTLIB::MEMSET),
7420                                        TLI->getPointerTy(DL)),
7421                      std::move(Args));
7422   }
7423 
7424   CLI.setDiscardResult().setTailCall(isTailCall);
7425 
7426   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
7427   return CallResult.second;
7428 }
7429 
7430 SDValue SelectionDAG::getAtomicMemset(SDValue Chain, const SDLoc &dl,
7431                                       SDValue Dst, SDValue Value, SDValue Size,
7432                                       Type *SizeTy, unsigned ElemSz,
7433                                       bool isTailCall,
7434                                       MachinePointerInfo DstPtrInfo) {
7435   // Emit a library call.
7436   TargetLowering::ArgListTy Args;
7437   TargetLowering::ArgListEntry Entry;
7438   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7439   Entry.Node = Dst;
7440   Args.push_back(Entry);
7441 
7442   Entry.Ty = Type::getInt8Ty(*getContext());
7443   Entry.Node = Value;
7444   Args.push_back(Entry);
7445 
7446   Entry.Ty = SizeTy;
7447   Entry.Node = Size;
7448   Args.push_back(Entry);
7449 
7450   RTLIB::Libcall LibraryCall =
7451       RTLIB::getMEMSET_ELEMENT_UNORDERED_ATOMIC(ElemSz);
7452   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
7453     report_fatal_error("Unsupported element size");
7454 
7455   TargetLowering::CallLoweringInfo CLI(*this);
7456   CLI.setDebugLoc(dl)
7457       .setChain(Chain)
7458       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
7459                     Type::getVoidTy(*getContext()),
7460                     getExternalSymbol(TLI->getLibcallName(LibraryCall),
7461                                       TLI->getPointerTy(getDataLayout())),
7462                     std::move(Args))
7463       .setDiscardResult()
7464       .setTailCall(isTailCall);
7465 
7466   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
7467   return CallResult.second;
7468 }
7469 
7470 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
7471                                 SDVTList VTList, ArrayRef<SDValue> Ops,
7472                                 MachineMemOperand *MMO) {
7473   FoldingSetNodeID ID;
7474   ID.AddInteger(MemVT.getRawBits());
7475   AddNodeIDNode(ID, Opcode, VTList, Ops);
7476   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7477   ID.AddInteger(MMO->getFlags());
7478   void* IP = nullptr;
7479   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7480     cast<AtomicSDNode>(E)->refineAlignment(MMO);
7481     return SDValue(E, 0);
7482   }
7483 
7484   auto *N = newSDNode<AtomicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
7485                                     VTList, MemVT, MMO);
7486   createOperands(N, Ops);
7487 
7488   CSEMap.InsertNode(N, IP);
7489   InsertNode(N);
7490   return SDValue(N, 0);
7491 }
7492 
7493 SDValue SelectionDAG::getAtomicCmpSwap(unsigned Opcode, const SDLoc &dl,
7494                                        EVT MemVT, SDVTList VTs, SDValue Chain,
7495                                        SDValue Ptr, SDValue Cmp, SDValue Swp,
7496                                        MachineMemOperand *MMO) {
7497   assert(Opcode == ISD::ATOMIC_CMP_SWAP ||
7498          Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
7499   assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
7500 
7501   SDValue Ops[] = {Chain, Ptr, Cmp, Swp};
7502   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
7503 }
7504 
7505 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
7506                                 SDValue Chain, SDValue Ptr, SDValue Val,
7507                                 MachineMemOperand *MMO) {
7508   assert((Opcode == ISD::ATOMIC_LOAD_ADD ||
7509           Opcode == ISD::ATOMIC_LOAD_SUB ||
7510           Opcode == ISD::ATOMIC_LOAD_AND ||
7511           Opcode == ISD::ATOMIC_LOAD_CLR ||
7512           Opcode == ISD::ATOMIC_LOAD_OR ||
7513           Opcode == ISD::ATOMIC_LOAD_XOR ||
7514           Opcode == ISD::ATOMIC_LOAD_NAND ||
7515           Opcode == ISD::ATOMIC_LOAD_MIN ||
7516           Opcode == ISD::ATOMIC_LOAD_MAX ||
7517           Opcode == ISD::ATOMIC_LOAD_UMIN ||
7518           Opcode == ISD::ATOMIC_LOAD_UMAX ||
7519           Opcode == ISD::ATOMIC_LOAD_FADD ||
7520           Opcode == ISD::ATOMIC_LOAD_FSUB ||
7521           Opcode == ISD::ATOMIC_LOAD_FMAX ||
7522           Opcode == ISD::ATOMIC_LOAD_FMIN ||
7523           Opcode == ISD::ATOMIC_SWAP ||
7524           Opcode == ISD::ATOMIC_STORE) &&
7525          "Invalid Atomic Op");
7526 
7527   EVT VT = Val.getValueType();
7528 
7529   SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) :
7530                                                getVTList(VT, MVT::Other);
7531   SDValue Ops[] = {Chain, Ptr, Val};
7532   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
7533 }
7534 
7535 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
7536                                 EVT VT, SDValue Chain, SDValue Ptr,
7537                                 MachineMemOperand *MMO) {
7538   assert(Opcode == ISD::ATOMIC_LOAD && "Invalid Atomic Op");
7539 
7540   SDVTList VTs = getVTList(VT, MVT::Other);
7541   SDValue Ops[] = {Chain, Ptr};
7542   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
7543 }
7544 
7545 /// getMergeValues - Create a MERGE_VALUES node from the given operands.
7546 SDValue SelectionDAG::getMergeValues(ArrayRef<SDValue> Ops, const SDLoc &dl) {
7547   if (Ops.size() == 1)
7548     return Ops[0];
7549 
7550   SmallVector<EVT, 4> VTs;
7551   VTs.reserve(Ops.size());
7552   for (const SDValue &Op : Ops)
7553     VTs.push_back(Op.getValueType());
7554   return getNode(ISD::MERGE_VALUES, dl, getVTList(VTs), Ops);
7555 }
7556 
7557 SDValue SelectionDAG::getMemIntrinsicNode(
7558     unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef<SDValue> Ops,
7559     EVT MemVT, MachinePointerInfo PtrInfo, Align Alignment,
7560     MachineMemOperand::Flags Flags, uint64_t Size, const AAMDNodes &AAInfo) {
7561   if (!Size && MemVT.isScalableVector())
7562     Size = MemoryLocation::UnknownSize;
7563   else if (!Size)
7564     Size = MemVT.getStoreSize();
7565 
7566   MachineFunction &MF = getMachineFunction();
7567   MachineMemOperand *MMO =
7568       MF.getMachineMemOperand(PtrInfo, Flags, Size, Alignment, AAInfo);
7569 
7570   return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, MMO);
7571 }
7572 
7573 SDValue SelectionDAG::getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl,
7574                                           SDVTList VTList,
7575                                           ArrayRef<SDValue> Ops, EVT MemVT,
7576                                           MachineMemOperand *MMO) {
7577   assert((Opcode == ISD::INTRINSIC_VOID ||
7578           Opcode == ISD::INTRINSIC_W_CHAIN ||
7579           Opcode == ISD::PREFETCH ||
7580           ((int)Opcode <= std::numeric_limits<int>::max() &&
7581            (int)Opcode >= ISD::FIRST_TARGET_MEMORY_OPCODE)) &&
7582          "Opcode is not a memory-accessing opcode!");
7583 
7584   // Memoize the node unless it returns a flag.
7585   MemIntrinsicSDNode *N;
7586   if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
7587     FoldingSetNodeID ID;
7588     AddNodeIDNode(ID, Opcode, VTList, Ops);
7589     ID.AddInteger(getSyntheticNodeSubclassData<MemIntrinsicSDNode>(
7590         Opcode, dl.getIROrder(), VTList, MemVT, MMO));
7591     ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7592     ID.AddInteger(MMO->getFlags());
7593     void *IP = nullptr;
7594     if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7595       cast<MemIntrinsicSDNode>(E)->refineAlignment(MMO);
7596       return SDValue(E, 0);
7597     }
7598 
7599     N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
7600                                       VTList, MemVT, MMO);
7601     createOperands(N, Ops);
7602 
7603   CSEMap.InsertNode(N, IP);
7604   } else {
7605     N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
7606                                       VTList, MemVT, MMO);
7607     createOperands(N, Ops);
7608   }
7609   InsertNode(N);
7610   SDValue V(N, 0);
7611   NewSDValueDbgMsg(V, "Creating new node: ", this);
7612   return V;
7613 }
7614 
7615 SDValue SelectionDAG::getLifetimeNode(bool IsStart, const SDLoc &dl,
7616                                       SDValue Chain, int FrameIndex,
7617                                       int64_t Size, int64_t Offset) {
7618   const unsigned Opcode = IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END;
7619   const auto VTs = getVTList(MVT::Other);
7620   SDValue Ops[2] = {
7621       Chain,
7622       getFrameIndex(FrameIndex,
7623                     getTargetLoweringInfo().getFrameIndexTy(getDataLayout()),
7624                     true)};
7625 
7626   FoldingSetNodeID ID;
7627   AddNodeIDNode(ID, Opcode, VTs, Ops);
7628   ID.AddInteger(FrameIndex);
7629   ID.AddInteger(Size);
7630   ID.AddInteger(Offset);
7631   void *IP = nullptr;
7632   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
7633     return SDValue(E, 0);
7634 
7635   LifetimeSDNode *N = newSDNode<LifetimeSDNode>(
7636       Opcode, dl.getIROrder(), dl.getDebugLoc(), VTs, Size, Offset);
7637   createOperands(N, Ops);
7638   CSEMap.InsertNode(N, IP);
7639   InsertNode(N);
7640   SDValue V(N, 0);
7641   NewSDValueDbgMsg(V, "Creating new node: ", this);
7642   return V;
7643 }
7644 
7645 SDValue SelectionDAG::getPseudoProbeNode(const SDLoc &Dl, SDValue Chain,
7646                                          uint64_t Guid, uint64_t Index,
7647                                          uint32_t Attr) {
7648   const unsigned Opcode = ISD::PSEUDO_PROBE;
7649   const auto VTs = getVTList(MVT::Other);
7650   SDValue Ops[] = {Chain};
7651   FoldingSetNodeID ID;
7652   AddNodeIDNode(ID, Opcode, VTs, Ops);
7653   ID.AddInteger(Guid);
7654   ID.AddInteger(Index);
7655   void *IP = nullptr;
7656   if (SDNode *E = FindNodeOrInsertPos(ID, Dl, IP))
7657     return SDValue(E, 0);
7658 
7659   auto *N = newSDNode<PseudoProbeSDNode>(
7660       Opcode, Dl.getIROrder(), Dl.getDebugLoc(), VTs, Guid, Index, Attr);
7661   createOperands(N, Ops);
7662   CSEMap.InsertNode(N, IP);
7663   InsertNode(N);
7664   SDValue V(N, 0);
7665   NewSDValueDbgMsg(V, "Creating new node: ", this);
7666   return V;
7667 }
7668 
7669 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
7670 /// MachinePointerInfo record from it.  This is particularly useful because the
7671 /// code generator has many cases where it doesn't bother passing in a
7672 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
7673 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info,
7674                                            SelectionDAG &DAG, SDValue Ptr,
7675                                            int64_t Offset = 0) {
7676   // If this is FI+Offset, we can model it.
7677   if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr))
7678     return MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
7679                                              FI->getIndex(), Offset);
7680 
7681   // If this is (FI+Offset1)+Offset2, we can model it.
7682   if (Ptr.getOpcode() != ISD::ADD ||
7683       !isa<ConstantSDNode>(Ptr.getOperand(1)) ||
7684       !isa<FrameIndexSDNode>(Ptr.getOperand(0)))
7685     return Info;
7686 
7687   int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
7688   return MachinePointerInfo::getFixedStack(
7689       DAG.getMachineFunction(), FI,
7690       Offset + cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue());
7691 }
7692 
7693 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
7694 /// MachinePointerInfo record from it.  This is particularly useful because the
7695 /// code generator has many cases where it doesn't bother passing in a
7696 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
7697 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info,
7698                                            SelectionDAG &DAG, SDValue Ptr,
7699                                            SDValue OffsetOp) {
7700   // If the 'Offset' value isn't a constant, we can't handle this.
7701   if (ConstantSDNode *OffsetNode = dyn_cast<ConstantSDNode>(OffsetOp))
7702     return InferPointerInfo(Info, DAG, Ptr, OffsetNode->getSExtValue());
7703   if (OffsetOp.isUndef())
7704     return InferPointerInfo(Info, DAG, Ptr);
7705   return Info;
7706 }
7707 
7708 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
7709                               EVT VT, const SDLoc &dl, SDValue Chain,
7710                               SDValue Ptr, SDValue Offset,
7711                               MachinePointerInfo PtrInfo, EVT MemVT,
7712                               Align Alignment,
7713                               MachineMemOperand::Flags MMOFlags,
7714                               const AAMDNodes &AAInfo, const MDNode *Ranges) {
7715   assert(Chain.getValueType() == MVT::Other &&
7716         "Invalid chain type");
7717 
7718   MMOFlags |= MachineMemOperand::MOLoad;
7719   assert((MMOFlags & MachineMemOperand::MOStore) == 0);
7720   // If we don't have a PtrInfo, infer the trivial frame index case to simplify
7721   // clients.
7722   if (PtrInfo.V.isNull())
7723     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
7724 
7725   uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize());
7726   MachineFunction &MF = getMachineFunction();
7727   MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size,
7728                                                    Alignment, AAInfo, Ranges);
7729   return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO);
7730 }
7731 
7732 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
7733                               EVT VT, const SDLoc &dl, SDValue Chain,
7734                               SDValue Ptr, SDValue Offset, EVT MemVT,
7735                               MachineMemOperand *MMO) {
7736   if (VT == MemVT) {
7737     ExtType = ISD::NON_EXTLOAD;
7738   } else if (ExtType == ISD::NON_EXTLOAD) {
7739     assert(VT == MemVT && "Non-extending load from different memory type!");
7740   } else {
7741     // Extending load.
7742     assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) &&
7743            "Should only be an extending load, not truncating!");
7744     assert(VT.isInteger() == MemVT.isInteger() &&
7745            "Cannot convert from FP to Int or Int -> FP!");
7746     assert(VT.isVector() == MemVT.isVector() &&
7747            "Cannot use an ext load to convert to or from a vector!");
7748     assert((!VT.isVector() ||
7749             VT.getVectorElementCount() == MemVT.getVectorElementCount()) &&
7750            "Cannot use an ext load to change the number of vector elements!");
7751   }
7752 
7753   bool Indexed = AM != ISD::UNINDEXED;
7754   assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
7755 
7756   SDVTList VTs = Indexed ?
7757     getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
7758   SDValue Ops[] = { Chain, Ptr, Offset };
7759   FoldingSetNodeID ID;
7760   AddNodeIDNode(ID, ISD::LOAD, VTs, Ops);
7761   ID.AddInteger(MemVT.getRawBits());
7762   ID.AddInteger(getSyntheticNodeSubclassData<LoadSDNode>(
7763       dl.getIROrder(), VTs, AM, ExtType, MemVT, MMO));
7764   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7765   ID.AddInteger(MMO->getFlags());
7766   void *IP = nullptr;
7767   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7768     cast<LoadSDNode>(E)->refineAlignment(MMO);
7769     return SDValue(E, 0);
7770   }
7771   auto *N = newSDNode<LoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
7772                                   ExtType, MemVT, MMO);
7773   createOperands(N, Ops);
7774 
7775   CSEMap.InsertNode(N, IP);
7776   InsertNode(N);
7777   SDValue V(N, 0);
7778   NewSDValueDbgMsg(V, "Creating new node: ", this);
7779   return V;
7780 }
7781 
7782 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
7783                               SDValue Ptr, MachinePointerInfo PtrInfo,
7784                               MaybeAlign Alignment,
7785                               MachineMemOperand::Flags MMOFlags,
7786                               const AAMDNodes &AAInfo, const MDNode *Ranges) {
7787   SDValue Undef = getUNDEF(Ptr.getValueType());
7788   return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7789                  PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges);
7790 }
7791 
7792 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
7793                               SDValue Ptr, MachineMemOperand *MMO) {
7794   SDValue Undef = getUNDEF(Ptr.getValueType());
7795   return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7796                  VT, MMO);
7797 }
7798 
7799 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
7800                                  EVT VT, SDValue Chain, SDValue Ptr,
7801                                  MachinePointerInfo PtrInfo, EVT MemVT,
7802                                  MaybeAlign Alignment,
7803                                  MachineMemOperand::Flags MMOFlags,
7804                                  const AAMDNodes &AAInfo) {
7805   SDValue Undef = getUNDEF(Ptr.getValueType());
7806   return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, PtrInfo,
7807                  MemVT, Alignment, MMOFlags, AAInfo);
7808 }
7809 
7810 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
7811                                  EVT VT, SDValue Chain, SDValue Ptr, EVT MemVT,
7812                                  MachineMemOperand *MMO) {
7813   SDValue Undef = getUNDEF(Ptr.getValueType());
7814   return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef,
7815                  MemVT, MMO);
7816 }
7817 
7818 SDValue SelectionDAG::getIndexedLoad(SDValue OrigLoad, const SDLoc &dl,
7819                                      SDValue Base, SDValue Offset,
7820                                      ISD::MemIndexedMode AM) {
7821   LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
7822   assert(LD->getOffset().isUndef() && "Load is already a indexed load!");
7823   // Don't propagate the invariant or dereferenceable flags.
7824   auto MMOFlags =
7825       LD->getMemOperand()->getFlags() &
7826       ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
7827   return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
7828                  LD->getChain(), Base, Offset, LD->getPointerInfo(),
7829                  LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo());
7830 }
7831 
7832 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7833                                SDValue Ptr, MachinePointerInfo PtrInfo,
7834                                Align Alignment,
7835                                MachineMemOperand::Flags MMOFlags,
7836                                const AAMDNodes &AAInfo) {
7837   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
7838 
7839   MMOFlags |= MachineMemOperand::MOStore;
7840   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
7841 
7842   if (PtrInfo.V.isNull())
7843     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
7844 
7845   MachineFunction &MF = getMachineFunction();
7846   uint64_t Size =
7847       MemoryLocation::getSizeOrUnknown(Val.getValueType().getStoreSize());
7848   MachineMemOperand *MMO =
7849       MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, Alignment, AAInfo);
7850   return getStore(Chain, dl, Val, Ptr, MMO);
7851 }
7852 
7853 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7854                                SDValue Ptr, MachineMemOperand *MMO) {
7855   assert(Chain.getValueType() == MVT::Other &&
7856         "Invalid chain type");
7857   EVT VT = Val.getValueType();
7858   SDVTList VTs = getVTList(MVT::Other);
7859   SDValue Undef = getUNDEF(Ptr.getValueType());
7860   SDValue Ops[] = { Chain, Val, Ptr, Undef };
7861   FoldingSetNodeID ID;
7862   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7863   ID.AddInteger(VT.getRawBits());
7864   ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
7865       dl.getIROrder(), VTs, ISD::UNINDEXED, false, VT, MMO));
7866   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7867   ID.AddInteger(MMO->getFlags());
7868   void *IP = nullptr;
7869   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7870     cast<StoreSDNode>(E)->refineAlignment(MMO);
7871     return SDValue(E, 0);
7872   }
7873   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7874                                    ISD::UNINDEXED, false, VT, MMO);
7875   createOperands(N, Ops);
7876 
7877   CSEMap.InsertNode(N, IP);
7878   InsertNode(N);
7879   SDValue V(N, 0);
7880   NewSDValueDbgMsg(V, "Creating new node: ", this);
7881   return V;
7882 }
7883 
7884 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7885                                     SDValue Ptr, MachinePointerInfo PtrInfo,
7886                                     EVT SVT, Align Alignment,
7887                                     MachineMemOperand::Flags MMOFlags,
7888                                     const AAMDNodes &AAInfo) {
7889   assert(Chain.getValueType() == MVT::Other &&
7890         "Invalid chain type");
7891 
7892   MMOFlags |= MachineMemOperand::MOStore;
7893   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
7894 
7895   if (PtrInfo.V.isNull())
7896     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
7897 
7898   MachineFunction &MF = getMachineFunction();
7899   MachineMemOperand *MMO = MF.getMachineMemOperand(
7900       PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()),
7901       Alignment, AAInfo);
7902   return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO);
7903 }
7904 
7905 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7906                                     SDValue Ptr, EVT SVT,
7907                                     MachineMemOperand *MMO) {
7908   EVT VT = Val.getValueType();
7909 
7910   assert(Chain.getValueType() == MVT::Other &&
7911         "Invalid chain type");
7912   if (VT == SVT)
7913     return getStore(Chain, dl, Val, Ptr, MMO);
7914 
7915   assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
7916          "Should only be a truncating store, not extending!");
7917   assert(VT.isInteger() == SVT.isInteger() &&
7918          "Can't do FP-INT conversion!");
7919   assert(VT.isVector() == SVT.isVector() &&
7920          "Cannot use trunc store to convert to or from a vector!");
7921   assert((!VT.isVector() ||
7922           VT.getVectorElementCount() == SVT.getVectorElementCount()) &&
7923          "Cannot use trunc store to change the number of vector elements!");
7924 
7925   SDVTList VTs = getVTList(MVT::Other);
7926   SDValue Undef = getUNDEF(Ptr.getValueType());
7927   SDValue Ops[] = { Chain, Val, Ptr, Undef };
7928   FoldingSetNodeID ID;
7929   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7930   ID.AddInteger(SVT.getRawBits());
7931   ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
7932       dl.getIROrder(), VTs, ISD::UNINDEXED, true, SVT, MMO));
7933   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7934   ID.AddInteger(MMO->getFlags());
7935   void *IP = nullptr;
7936   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7937     cast<StoreSDNode>(E)->refineAlignment(MMO);
7938     return SDValue(E, 0);
7939   }
7940   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7941                                    ISD::UNINDEXED, true, SVT, MMO);
7942   createOperands(N, Ops);
7943 
7944   CSEMap.InsertNode(N, IP);
7945   InsertNode(N);
7946   SDValue V(N, 0);
7947   NewSDValueDbgMsg(V, "Creating new node: ", this);
7948   return V;
7949 }
7950 
7951 SDValue SelectionDAG::getIndexedStore(SDValue OrigStore, const SDLoc &dl,
7952                                       SDValue Base, SDValue Offset,
7953                                       ISD::MemIndexedMode AM) {
7954   StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
7955   assert(ST->getOffset().isUndef() && "Store is already a indexed store!");
7956   SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
7957   SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
7958   FoldingSetNodeID ID;
7959   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7960   ID.AddInteger(ST->getMemoryVT().getRawBits());
7961   ID.AddInteger(ST->getRawSubclassData());
7962   ID.AddInteger(ST->getPointerInfo().getAddrSpace());
7963   ID.AddInteger(ST->getMemOperand()->getFlags());
7964   void *IP = nullptr;
7965   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
7966     return SDValue(E, 0);
7967 
7968   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
7969                                    ST->isTruncatingStore(), ST->getMemoryVT(),
7970                                    ST->getMemOperand());
7971   createOperands(N, Ops);
7972 
7973   CSEMap.InsertNode(N, IP);
7974   InsertNode(N);
7975   SDValue V(N, 0);
7976   NewSDValueDbgMsg(V, "Creating new node: ", this);
7977   return V;
7978 }
7979 
7980 SDValue SelectionDAG::getLoadVP(
7981     ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &dl,
7982     SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Mask, SDValue EVL,
7983     MachinePointerInfo PtrInfo, EVT MemVT, Align Alignment,
7984     MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
7985     const MDNode *Ranges, bool IsExpanding) {
7986   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
7987 
7988   MMOFlags |= MachineMemOperand::MOLoad;
7989   assert((MMOFlags & MachineMemOperand::MOStore) == 0);
7990   // If we don't have a PtrInfo, infer the trivial frame index case to simplify
7991   // clients.
7992   if (PtrInfo.V.isNull())
7993     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
7994 
7995   uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize());
7996   MachineFunction &MF = getMachineFunction();
7997   MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size,
7998                                                    Alignment, AAInfo, Ranges);
7999   return getLoadVP(AM, ExtType, VT, dl, Chain, Ptr, Offset, Mask, EVL, MemVT,
8000                    MMO, IsExpanding);
8001 }
8002 
8003 SDValue SelectionDAG::getLoadVP(ISD::MemIndexedMode AM,
8004                                 ISD::LoadExtType ExtType, EVT VT,
8005                                 const SDLoc &dl, SDValue Chain, SDValue Ptr,
8006                                 SDValue Offset, SDValue Mask, SDValue EVL,
8007                                 EVT MemVT, MachineMemOperand *MMO,
8008                                 bool IsExpanding) {
8009   bool Indexed = AM != ISD::UNINDEXED;
8010   assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
8011 
8012   SDVTList VTs = Indexed ? getVTList(VT, Ptr.getValueType(), MVT::Other)
8013                          : getVTList(VT, MVT::Other);
8014   SDValue Ops[] = {Chain, Ptr, Offset, Mask, EVL};
8015   FoldingSetNodeID ID;
8016   AddNodeIDNode(ID, ISD::VP_LOAD, VTs, Ops);
8017   ID.AddInteger(VT.getRawBits());
8018   ID.AddInteger(getSyntheticNodeSubclassData<VPLoadSDNode>(
8019       dl.getIROrder(), VTs, AM, ExtType, IsExpanding, MemVT, MMO));
8020   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8021   ID.AddInteger(MMO->getFlags());
8022   void *IP = nullptr;
8023   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8024     cast<VPLoadSDNode>(E)->refineAlignment(MMO);
8025     return SDValue(E, 0);
8026   }
8027   auto *N = newSDNode<VPLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
8028                                     ExtType, IsExpanding, MemVT, MMO);
8029   createOperands(N, Ops);
8030 
8031   CSEMap.InsertNode(N, IP);
8032   InsertNode(N);
8033   SDValue V(N, 0);
8034   NewSDValueDbgMsg(V, "Creating new node: ", this);
8035   return V;
8036 }
8037 
8038 SDValue SelectionDAG::getLoadVP(EVT VT, const SDLoc &dl, SDValue Chain,
8039                                 SDValue Ptr, SDValue Mask, SDValue EVL,
8040                                 MachinePointerInfo PtrInfo,
8041                                 MaybeAlign Alignment,
8042                                 MachineMemOperand::Flags MMOFlags,
8043                                 const AAMDNodes &AAInfo, const MDNode *Ranges,
8044                                 bool IsExpanding) {
8045   SDValue Undef = getUNDEF(Ptr.getValueType());
8046   return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
8047                    Mask, EVL, PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges,
8048                    IsExpanding);
8049 }
8050 
8051 SDValue SelectionDAG::getLoadVP(EVT VT, const SDLoc &dl, SDValue Chain,
8052                                 SDValue Ptr, SDValue Mask, SDValue EVL,
8053                                 MachineMemOperand *MMO, bool IsExpanding) {
8054   SDValue Undef = getUNDEF(Ptr.getValueType());
8055   return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
8056                    Mask, EVL, VT, MMO, IsExpanding);
8057 }
8058 
8059 SDValue SelectionDAG::getExtLoadVP(ISD::LoadExtType ExtType, const SDLoc &dl,
8060                                    EVT VT, SDValue Chain, SDValue Ptr,
8061                                    SDValue Mask, SDValue EVL,
8062                                    MachinePointerInfo PtrInfo, EVT MemVT,
8063                                    MaybeAlign Alignment,
8064                                    MachineMemOperand::Flags MMOFlags,
8065                                    const AAMDNodes &AAInfo, bool IsExpanding) {
8066   SDValue Undef = getUNDEF(Ptr.getValueType());
8067   return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask,
8068                    EVL, PtrInfo, MemVT, Alignment, MMOFlags, AAInfo, nullptr,
8069                    IsExpanding);
8070 }
8071 
8072 SDValue SelectionDAG::getExtLoadVP(ISD::LoadExtType ExtType, const SDLoc &dl,
8073                                    EVT VT, SDValue Chain, SDValue Ptr,
8074                                    SDValue Mask, SDValue EVL, EVT MemVT,
8075                                    MachineMemOperand *MMO, bool IsExpanding) {
8076   SDValue Undef = getUNDEF(Ptr.getValueType());
8077   return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask,
8078                    EVL, MemVT, MMO, IsExpanding);
8079 }
8080 
8081 SDValue SelectionDAG::getIndexedLoadVP(SDValue OrigLoad, const SDLoc &dl,
8082                                        SDValue Base, SDValue Offset,
8083                                        ISD::MemIndexedMode AM) {
8084   auto *LD = cast<VPLoadSDNode>(OrigLoad);
8085   assert(LD->getOffset().isUndef() && "Load is already a indexed load!");
8086   // Don't propagate the invariant or dereferenceable flags.
8087   auto MMOFlags =
8088       LD->getMemOperand()->getFlags() &
8089       ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
8090   return getLoadVP(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
8091                    LD->getChain(), Base, Offset, LD->getMask(),
8092                    LD->getVectorLength(), LD->getPointerInfo(),
8093                    LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo(),
8094                    nullptr, LD->isExpandingLoad());
8095 }
8096 
8097 SDValue SelectionDAG::getStoreVP(SDValue Chain, const SDLoc &dl, SDValue Val,
8098                                  SDValue Ptr, SDValue Offset, SDValue Mask,
8099                                  SDValue EVL, EVT MemVT, MachineMemOperand *MMO,
8100                                  ISD::MemIndexedMode AM, bool IsTruncating,
8101                                  bool IsCompressing) {
8102   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
8103   bool Indexed = AM != ISD::UNINDEXED;
8104   assert((Indexed || Offset.isUndef()) && "Unindexed vp_store with an offset!");
8105   SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other)
8106                          : getVTList(MVT::Other);
8107   SDValue Ops[] = {Chain, Val, Ptr, Offset, Mask, EVL};
8108   FoldingSetNodeID ID;
8109   AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
8110   ID.AddInteger(MemVT.getRawBits());
8111   ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>(
8112       dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
8113   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8114   ID.AddInteger(MMO->getFlags());
8115   void *IP = nullptr;
8116   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8117     cast<VPStoreSDNode>(E)->refineAlignment(MMO);
8118     return SDValue(E, 0);
8119   }
8120   auto *N = newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
8121                                      IsTruncating, IsCompressing, MemVT, MMO);
8122   createOperands(N, Ops);
8123 
8124   CSEMap.InsertNode(N, IP);
8125   InsertNode(N);
8126   SDValue V(N, 0);
8127   NewSDValueDbgMsg(V, "Creating new node: ", this);
8128   return V;
8129 }
8130 
8131 SDValue SelectionDAG::getTruncStoreVP(SDValue Chain, const SDLoc &dl,
8132                                       SDValue Val, SDValue Ptr, SDValue Mask,
8133                                       SDValue EVL, MachinePointerInfo PtrInfo,
8134                                       EVT SVT, Align Alignment,
8135                                       MachineMemOperand::Flags MMOFlags,
8136                                       const AAMDNodes &AAInfo,
8137                                       bool IsCompressing) {
8138   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
8139 
8140   MMOFlags |= MachineMemOperand::MOStore;
8141   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
8142 
8143   if (PtrInfo.V.isNull())
8144     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
8145 
8146   MachineFunction &MF = getMachineFunction();
8147   MachineMemOperand *MMO = MF.getMachineMemOperand(
8148       PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()),
8149       Alignment, AAInfo);
8150   return getTruncStoreVP(Chain, dl, Val, Ptr, Mask, EVL, SVT, MMO,
8151                          IsCompressing);
8152 }
8153 
8154 SDValue SelectionDAG::getTruncStoreVP(SDValue Chain, const SDLoc &dl,
8155                                       SDValue Val, SDValue Ptr, SDValue Mask,
8156                                       SDValue EVL, EVT SVT,
8157                                       MachineMemOperand *MMO,
8158                                       bool IsCompressing) {
8159   EVT VT = Val.getValueType();
8160 
8161   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
8162   if (VT == SVT)
8163     return getStoreVP(Chain, dl, Val, Ptr, getUNDEF(Ptr.getValueType()), Mask,
8164                       EVL, VT, MMO, ISD::UNINDEXED,
8165                       /*IsTruncating*/ false, IsCompressing);
8166 
8167   assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
8168          "Should only be a truncating store, not extending!");
8169   assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!");
8170   assert(VT.isVector() == SVT.isVector() &&
8171          "Cannot use trunc store to convert to or from a vector!");
8172   assert((!VT.isVector() ||
8173           VT.getVectorElementCount() == SVT.getVectorElementCount()) &&
8174          "Cannot use trunc store to change the number of vector elements!");
8175 
8176   SDVTList VTs = getVTList(MVT::Other);
8177   SDValue Undef = getUNDEF(Ptr.getValueType());
8178   SDValue Ops[] = {Chain, Val, Ptr, Undef, Mask, EVL};
8179   FoldingSetNodeID ID;
8180   AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
8181   ID.AddInteger(SVT.getRawBits());
8182   ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>(
8183       dl.getIROrder(), VTs, ISD::UNINDEXED, true, IsCompressing, SVT, MMO));
8184   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8185   ID.AddInteger(MMO->getFlags());
8186   void *IP = nullptr;
8187   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8188     cast<VPStoreSDNode>(E)->refineAlignment(MMO);
8189     return SDValue(E, 0);
8190   }
8191   auto *N =
8192       newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
8193                                ISD::UNINDEXED, true, IsCompressing, SVT, MMO);
8194   createOperands(N, Ops);
8195 
8196   CSEMap.InsertNode(N, IP);
8197   InsertNode(N);
8198   SDValue V(N, 0);
8199   NewSDValueDbgMsg(V, "Creating new node: ", this);
8200   return V;
8201 }
8202 
8203 SDValue SelectionDAG::getIndexedStoreVP(SDValue OrigStore, const SDLoc &dl,
8204                                         SDValue Base, SDValue Offset,
8205                                         ISD::MemIndexedMode AM) {
8206   auto *ST = cast<VPStoreSDNode>(OrigStore);
8207   assert(ST->getOffset().isUndef() && "Store is already an indexed store!");
8208   SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
8209   SDValue Ops[] = {ST->getChain(), ST->getValue(), Base,
8210                    Offset,         ST->getMask(),  ST->getVectorLength()};
8211   FoldingSetNodeID ID;
8212   AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
8213   ID.AddInteger(ST->getMemoryVT().getRawBits());
8214   ID.AddInteger(ST->getRawSubclassData());
8215   ID.AddInteger(ST->getPointerInfo().getAddrSpace());
8216   ID.AddInteger(ST->getMemOperand()->getFlags());
8217   void *IP = nullptr;
8218   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
8219     return SDValue(E, 0);
8220 
8221   auto *N = newSDNode<VPStoreSDNode>(
8222       dl.getIROrder(), dl.getDebugLoc(), VTs, AM, ST->isTruncatingStore(),
8223       ST->isCompressingStore(), ST->getMemoryVT(), ST->getMemOperand());
8224   createOperands(N, Ops);
8225 
8226   CSEMap.InsertNode(N, IP);
8227   InsertNode(N);
8228   SDValue V(N, 0);
8229   NewSDValueDbgMsg(V, "Creating new node: ", this);
8230   return V;
8231 }
8232 
8233 SDValue SelectionDAG::getStridedLoadVP(
8234     ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &DL,
8235     SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Stride, SDValue Mask,
8236     SDValue EVL, MachinePointerInfo PtrInfo, EVT MemVT, Align Alignment,
8237     MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
8238     const MDNode *Ranges, bool IsExpanding) {
8239   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
8240 
8241   MMOFlags |= MachineMemOperand::MOLoad;
8242   assert((MMOFlags & MachineMemOperand::MOStore) == 0);
8243   // If we don't have a PtrInfo, infer the trivial frame index case to simplify
8244   // clients.
8245   if (PtrInfo.V.isNull())
8246     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
8247 
8248   uint64_t Size = MemoryLocation::UnknownSize;
8249   MachineFunction &MF = getMachineFunction();
8250   MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size,
8251                                                    Alignment, AAInfo, Ranges);
8252   return getStridedLoadVP(AM, ExtType, VT, DL, Chain, Ptr, Offset, Stride, Mask,
8253                           EVL, MemVT, MMO, IsExpanding);
8254 }
8255 
8256 SDValue SelectionDAG::getStridedLoadVP(
8257     ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &DL,
8258     SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Stride, SDValue Mask,
8259     SDValue EVL, EVT MemVT, MachineMemOperand *MMO, bool IsExpanding) {
8260   bool Indexed = AM != ISD::UNINDEXED;
8261   assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
8262 
8263   SDValue Ops[] = {Chain, Ptr, Offset, Stride, Mask, EVL};
8264   SDVTList VTs = Indexed ? getVTList(VT, Ptr.getValueType(), MVT::Other)
8265                          : getVTList(VT, MVT::Other);
8266   FoldingSetNodeID ID;
8267   AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_LOAD, VTs, Ops);
8268   ID.AddInteger(VT.getRawBits());
8269   ID.AddInteger(getSyntheticNodeSubclassData<VPStridedLoadSDNode>(
8270       DL.getIROrder(), VTs, AM, ExtType, IsExpanding, MemVT, MMO));
8271   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8272 
8273   void *IP = nullptr;
8274   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
8275     cast<VPStridedLoadSDNode>(E)->refineAlignment(MMO);
8276     return SDValue(E, 0);
8277   }
8278 
8279   auto *N =
8280       newSDNode<VPStridedLoadSDNode>(DL.getIROrder(), DL.getDebugLoc(), VTs, AM,
8281                                      ExtType, IsExpanding, MemVT, MMO);
8282   createOperands(N, Ops);
8283   CSEMap.InsertNode(N, IP);
8284   InsertNode(N);
8285   SDValue V(N, 0);
8286   NewSDValueDbgMsg(V, "Creating new node: ", this);
8287   return V;
8288 }
8289 
8290 SDValue SelectionDAG::getStridedLoadVP(
8291     EVT VT, const SDLoc &DL, SDValue Chain, SDValue Ptr, SDValue Stride,
8292     SDValue Mask, SDValue EVL, MachinePointerInfo PtrInfo, MaybeAlign Alignment,
8293     MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
8294     const MDNode *Ranges, bool IsExpanding) {
8295   SDValue Undef = getUNDEF(Ptr.getValueType());
8296   return getStridedLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, DL, Chain, Ptr,
8297                           Undef, Stride, Mask, EVL, PtrInfo, VT, Alignment,
8298                           MMOFlags, AAInfo, Ranges, IsExpanding);
8299 }
8300 
8301 SDValue SelectionDAG::getStridedLoadVP(EVT VT, const SDLoc &DL, SDValue Chain,
8302                                        SDValue Ptr, SDValue Stride,
8303                                        SDValue Mask, SDValue EVL,
8304                                        MachineMemOperand *MMO,
8305                                        bool IsExpanding) {
8306   SDValue Undef = getUNDEF(Ptr.getValueType());
8307   return getStridedLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, DL, Chain, Ptr,
8308                           Undef, Stride, Mask, EVL, VT, MMO, IsExpanding);
8309 }
8310 
8311 SDValue SelectionDAG::getExtStridedLoadVP(
8312     ISD::LoadExtType ExtType, const SDLoc &DL, EVT VT, SDValue Chain,
8313     SDValue Ptr, SDValue Stride, SDValue Mask, SDValue EVL,
8314     MachinePointerInfo PtrInfo, EVT MemVT, MaybeAlign Alignment,
8315     MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
8316     bool IsExpanding) {
8317   SDValue Undef = getUNDEF(Ptr.getValueType());
8318   return getStridedLoadVP(ISD::UNINDEXED, ExtType, VT, DL, Chain, Ptr, Undef,
8319                           Stride, Mask, EVL, PtrInfo, MemVT, Alignment,
8320                           MMOFlags, AAInfo, nullptr, IsExpanding);
8321 }
8322 
8323 SDValue SelectionDAG::getExtStridedLoadVP(
8324     ISD::LoadExtType ExtType, const SDLoc &DL, EVT VT, SDValue Chain,
8325     SDValue Ptr, SDValue Stride, SDValue Mask, SDValue EVL, EVT MemVT,
8326     MachineMemOperand *MMO, bool IsExpanding) {
8327   SDValue Undef = getUNDEF(Ptr.getValueType());
8328   return getStridedLoadVP(ISD::UNINDEXED, ExtType, VT, DL, Chain, Ptr, Undef,
8329                           Stride, Mask, EVL, MemVT, MMO, IsExpanding);
8330 }
8331 
8332 SDValue SelectionDAG::getIndexedStridedLoadVP(SDValue OrigLoad, const SDLoc &DL,
8333                                               SDValue Base, SDValue Offset,
8334                                               ISD::MemIndexedMode AM) {
8335   auto *SLD = cast<VPStridedLoadSDNode>(OrigLoad);
8336   assert(SLD->getOffset().isUndef() &&
8337          "Strided load is already a indexed load!");
8338   // Don't propagate the invariant or dereferenceable flags.
8339   auto MMOFlags =
8340       SLD->getMemOperand()->getFlags() &
8341       ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
8342   return getStridedLoadVP(
8343       AM, SLD->getExtensionType(), OrigLoad.getValueType(), DL, SLD->getChain(),
8344       Base, Offset, SLD->getStride(), SLD->getMask(), SLD->getVectorLength(),
8345       SLD->getPointerInfo(), SLD->getMemoryVT(), SLD->getAlign(), MMOFlags,
8346       SLD->getAAInfo(), nullptr, SLD->isExpandingLoad());
8347 }
8348 
8349 SDValue SelectionDAG::getStridedStoreVP(SDValue Chain, const SDLoc &DL,
8350                                         SDValue Val, SDValue Ptr,
8351                                         SDValue Offset, SDValue Stride,
8352                                         SDValue Mask, SDValue EVL, EVT MemVT,
8353                                         MachineMemOperand *MMO,
8354                                         ISD::MemIndexedMode AM,
8355                                         bool IsTruncating, bool IsCompressing) {
8356   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
8357   bool Indexed = AM != ISD::UNINDEXED;
8358   assert((Indexed || Offset.isUndef()) && "Unindexed vp_store with an offset!");
8359   SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other)
8360                          : getVTList(MVT::Other);
8361   SDValue Ops[] = {Chain, Val, Ptr, Offset, Stride, Mask, EVL};
8362   FoldingSetNodeID ID;
8363   AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_STORE, VTs, Ops);
8364   ID.AddInteger(MemVT.getRawBits());
8365   ID.AddInteger(getSyntheticNodeSubclassData<VPStridedStoreSDNode>(
8366       DL.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
8367   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8368   void *IP = nullptr;
8369   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
8370     cast<VPStridedStoreSDNode>(E)->refineAlignment(MMO);
8371     return SDValue(E, 0);
8372   }
8373   auto *N = newSDNode<VPStridedStoreSDNode>(DL.getIROrder(), DL.getDebugLoc(),
8374                                             VTs, AM, IsTruncating,
8375                                             IsCompressing, MemVT, MMO);
8376   createOperands(N, Ops);
8377 
8378   CSEMap.InsertNode(N, IP);
8379   InsertNode(N);
8380   SDValue V(N, 0);
8381   NewSDValueDbgMsg(V, "Creating new node: ", this);
8382   return V;
8383 }
8384 
8385 SDValue SelectionDAG::getTruncStridedStoreVP(
8386     SDValue Chain, const SDLoc &DL, SDValue Val, SDValue Ptr, SDValue Stride,
8387     SDValue Mask, SDValue EVL, MachinePointerInfo PtrInfo, EVT SVT,
8388     Align Alignment, MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
8389     bool IsCompressing) {
8390   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
8391 
8392   MMOFlags |= MachineMemOperand::MOStore;
8393   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
8394 
8395   if (PtrInfo.V.isNull())
8396     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
8397 
8398   MachineFunction &MF = getMachineFunction();
8399   MachineMemOperand *MMO = MF.getMachineMemOperand(
8400       PtrInfo, MMOFlags, MemoryLocation::UnknownSize, Alignment, AAInfo);
8401   return getTruncStridedStoreVP(Chain, DL, Val, Ptr, Stride, Mask, EVL, SVT,
8402                                 MMO, IsCompressing);
8403 }
8404 
8405 SDValue SelectionDAG::getTruncStridedStoreVP(SDValue Chain, const SDLoc &DL,
8406                                              SDValue Val, SDValue Ptr,
8407                                              SDValue Stride, SDValue Mask,
8408                                              SDValue EVL, EVT SVT,
8409                                              MachineMemOperand *MMO,
8410                                              bool IsCompressing) {
8411   EVT VT = Val.getValueType();
8412 
8413   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
8414   if (VT == SVT)
8415     return getStridedStoreVP(Chain, DL, Val, Ptr, getUNDEF(Ptr.getValueType()),
8416                              Stride, Mask, EVL, VT, MMO, ISD::UNINDEXED,
8417                              /*IsTruncating*/ false, IsCompressing);
8418 
8419   assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
8420          "Should only be a truncating store, not extending!");
8421   assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!");
8422   assert(VT.isVector() == SVT.isVector() &&
8423          "Cannot use trunc store to convert to or from a vector!");
8424   assert((!VT.isVector() ||
8425           VT.getVectorElementCount() == SVT.getVectorElementCount()) &&
8426          "Cannot use trunc store to change the number of vector elements!");
8427 
8428   SDVTList VTs = getVTList(MVT::Other);
8429   SDValue Undef = getUNDEF(Ptr.getValueType());
8430   SDValue Ops[] = {Chain, Val, Ptr, Undef, Stride, Mask, EVL};
8431   FoldingSetNodeID ID;
8432   AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_STORE, VTs, Ops);
8433   ID.AddInteger(SVT.getRawBits());
8434   ID.AddInteger(getSyntheticNodeSubclassData<VPStridedStoreSDNode>(
8435       DL.getIROrder(), VTs, ISD::UNINDEXED, true, IsCompressing, SVT, MMO));
8436   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8437   void *IP = nullptr;
8438   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
8439     cast<VPStridedStoreSDNode>(E)->refineAlignment(MMO);
8440     return SDValue(E, 0);
8441   }
8442   auto *N = newSDNode<VPStridedStoreSDNode>(DL.getIROrder(), DL.getDebugLoc(),
8443                                             VTs, ISD::UNINDEXED, true,
8444                                             IsCompressing, SVT, MMO);
8445   createOperands(N, Ops);
8446 
8447   CSEMap.InsertNode(N, IP);
8448   InsertNode(N);
8449   SDValue V(N, 0);
8450   NewSDValueDbgMsg(V, "Creating new node: ", this);
8451   return V;
8452 }
8453 
8454 SDValue SelectionDAG::getIndexedStridedStoreVP(SDValue OrigStore,
8455                                                const SDLoc &DL, SDValue Base,
8456                                                SDValue Offset,
8457                                                ISD::MemIndexedMode AM) {
8458   auto *SST = cast<VPStridedStoreSDNode>(OrigStore);
8459   assert(SST->getOffset().isUndef() &&
8460          "Strided store is already an indexed store!");
8461   SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
8462   SDValue Ops[] = {
8463       SST->getChain(), SST->getValue(),       Base, Offset, SST->getStride(),
8464       SST->getMask(),  SST->getVectorLength()};
8465   FoldingSetNodeID ID;
8466   AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_STORE, VTs, Ops);
8467   ID.AddInteger(SST->getMemoryVT().getRawBits());
8468   ID.AddInteger(SST->getRawSubclassData());
8469   ID.AddInteger(SST->getPointerInfo().getAddrSpace());
8470   void *IP = nullptr;
8471   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
8472     return SDValue(E, 0);
8473 
8474   auto *N = newSDNode<VPStridedStoreSDNode>(
8475       DL.getIROrder(), DL.getDebugLoc(), VTs, AM, SST->isTruncatingStore(),
8476       SST->isCompressingStore(), SST->getMemoryVT(), SST->getMemOperand());
8477   createOperands(N, Ops);
8478 
8479   CSEMap.InsertNode(N, IP);
8480   InsertNode(N);
8481   SDValue V(N, 0);
8482   NewSDValueDbgMsg(V, "Creating new node: ", this);
8483   return V;
8484 }
8485 
8486 SDValue SelectionDAG::getGatherVP(SDVTList VTs, EVT VT, const SDLoc &dl,
8487                                   ArrayRef<SDValue> Ops, MachineMemOperand *MMO,
8488                                   ISD::MemIndexType IndexType) {
8489   assert(Ops.size() == 6 && "Incompatible number of operands");
8490 
8491   FoldingSetNodeID ID;
8492   AddNodeIDNode(ID, ISD::VP_GATHER, VTs, Ops);
8493   ID.AddInteger(VT.getRawBits());
8494   ID.AddInteger(getSyntheticNodeSubclassData<VPGatherSDNode>(
8495       dl.getIROrder(), VTs, VT, MMO, IndexType));
8496   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8497   ID.AddInteger(MMO->getFlags());
8498   void *IP = nullptr;
8499   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8500     cast<VPGatherSDNode>(E)->refineAlignment(MMO);
8501     return SDValue(E, 0);
8502   }
8503 
8504   auto *N = newSDNode<VPGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
8505                                       VT, MMO, IndexType);
8506   createOperands(N, Ops);
8507 
8508   assert(N->getMask().getValueType().getVectorElementCount() ==
8509              N->getValueType(0).getVectorElementCount() &&
8510          "Vector width mismatch between mask and data");
8511   assert(N->getIndex().getValueType().getVectorElementCount().isScalable() ==
8512              N->getValueType(0).getVectorElementCount().isScalable() &&
8513          "Scalable flags of index and data do not match");
8514   assert(ElementCount::isKnownGE(
8515              N->getIndex().getValueType().getVectorElementCount(),
8516              N->getValueType(0).getVectorElementCount()) &&
8517          "Vector width mismatch between index and data");
8518   assert(isa<ConstantSDNode>(N->getScale()) &&
8519          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
8520          "Scale should be a constant power of 2");
8521 
8522   CSEMap.InsertNode(N, IP);
8523   InsertNode(N);
8524   SDValue V(N, 0);
8525   NewSDValueDbgMsg(V, "Creating new node: ", this);
8526   return V;
8527 }
8528 
8529 SDValue SelectionDAG::getScatterVP(SDVTList VTs, EVT VT, const SDLoc &dl,
8530                                    ArrayRef<SDValue> Ops,
8531                                    MachineMemOperand *MMO,
8532                                    ISD::MemIndexType IndexType) {
8533   assert(Ops.size() == 7 && "Incompatible number of operands");
8534 
8535   FoldingSetNodeID ID;
8536   AddNodeIDNode(ID, ISD::VP_SCATTER, VTs, Ops);
8537   ID.AddInteger(VT.getRawBits());
8538   ID.AddInteger(getSyntheticNodeSubclassData<VPScatterSDNode>(
8539       dl.getIROrder(), VTs, VT, MMO, IndexType));
8540   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8541   ID.AddInteger(MMO->getFlags());
8542   void *IP = nullptr;
8543   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8544     cast<VPScatterSDNode>(E)->refineAlignment(MMO);
8545     return SDValue(E, 0);
8546   }
8547   auto *N = newSDNode<VPScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
8548                                        VT, MMO, IndexType);
8549   createOperands(N, Ops);
8550 
8551   assert(N->getMask().getValueType().getVectorElementCount() ==
8552              N->getValue().getValueType().getVectorElementCount() &&
8553          "Vector width mismatch between mask and data");
8554   assert(
8555       N->getIndex().getValueType().getVectorElementCount().isScalable() ==
8556           N->getValue().getValueType().getVectorElementCount().isScalable() &&
8557       "Scalable flags of index and data do not match");
8558   assert(ElementCount::isKnownGE(
8559              N->getIndex().getValueType().getVectorElementCount(),
8560              N->getValue().getValueType().getVectorElementCount()) &&
8561          "Vector width mismatch between index and data");
8562   assert(isa<ConstantSDNode>(N->getScale()) &&
8563          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
8564          "Scale should be a constant power of 2");
8565 
8566   CSEMap.InsertNode(N, IP);
8567   InsertNode(N);
8568   SDValue V(N, 0);
8569   NewSDValueDbgMsg(V, "Creating new node: ", this);
8570   return V;
8571 }
8572 
8573 SDValue SelectionDAG::getMaskedLoad(EVT VT, const SDLoc &dl, SDValue Chain,
8574                                     SDValue Base, SDValue Offset, SDValue Mask,
8575                                     SDValue PassThru, EVT MemVT,
8576                                     MachineMemOperand *MMO,
8577                                     ISD::MemIndexedMode AM,
8578                                     ISD::LoadExtType ExtTy, bool isExpanding) {
8579   bool Indexed = AM != ISD::UNINDEXED;
8580   assert((Indexed || Offset.isUndef()) &&
8581          "Unindexed masked load with an offset!");
8582   SDVTList VTs = Indexed ? getVTList(VT, Base.getValueType(), MVT::Other)
8583                          : getVTList(VT, MVT::Other);
8584   SDValue Ops[] = {Chain, Base, Offset, Mask, PassThru};
8585   FoldingSetNodeID ID;
8586   AddNodeIDNode(ID, ISD::MLOAD, VTs, Ops);
8587   ID.AddInteger(MemVT.getRawBits());
8588   ID.AddInteger(getSyntheticNodeSubclassData<MaskedLoadSDNode>(
8589       dl.getIROrder(), VTs, AM, ExtTy, isExpanding, MemVT, MMO));
8590   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8591   ID.AddInteger(MMO->getFlags());
8592   void *IP = nullptr;
8593   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8594     cast<MaskedLoadSDNode>(E)->refineAlignment(MMO);
8595     return SDValue(E, 0);
8596   }
8597   auto *N = newSDNode<MaskedLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
8598                                         AM, ExtTy, isExpanding, MemVT, MMO);
8599   createOperands(N, Ops);
8600 
8601   CSEMap.InsertNode(N, IP);
8602   InsertNode(N);
8603   SDValue V(N, 0);
8604   NewSDValueDbgMsg(V, "Creating new node: ", this);
8605   return V;
8606 }
8607 
8608 SDValue SelectionDAG::getIndexedMaskedLoad(SDValue OrigLoad, const SDLoc &dl,
8609                                            SDValue Base, SDValue Offset,
8610                                            ISD::MemIndexedMode AM) {
8611   MaskedLoadSDNode *LD = cast<MaskedLoadSDNode>(OrigLoad);
8612   assert(LD->getOffset().isUndef() && "Masked load is already a indexed load!");
8613   return getMaskedLoad(OrigLoad.getValueType(), dl, LD->getChain(), Base,
8614                        Offset, LD->getMask(), LD->getPassThru(),
8615                        LD->getMemoryVT(), LD->getMemOperand(), AM,
8616                        LD->getExtensionType(), LD->isExpandingLoad());
8617 }
8618 
8619 SDValue SelectionDAG::getMaskedStore(SDValue Chain, const SDLoc &dl,
8620                                      SDValue Val, SDValue Base, SDValue Offset,
8621                                      SDValue Mask, EVT MemVT,
8622                                      MachineMemOperand *MMO,
8623                                      ISD::MemIndexedMode AM, bool IsTruncating,
8624                                      bool IsCompressing) {
8625   assert(Chain.getValueType() == MVT::Other &&
8626         "Invalid chain type");
8627   bool Indexed = AM != ISD::UNINDEXED;
8628   assert((Indexed || Offset.isUndef()) &&
8629          "Unindexed masked store with an offset!");
8630   SDVTList VTs = Indexed ? getVTList(Base.getValueType(), MVT::Other)
8631                          : getVTList(MVT::Other);
8632   SDValue Ops[] = {Chain, Val, Base, Offset, Mask};
8633   FoldingSetNodeID ID;
8634   AddNodeIDNode(ID, ISD::MSTORE, VTs, Ops);
8635   ID.AddInteger(MemVT.getRawBits());
8636   ID.AddInteger(getSyntheticNodeSubclassData<MaskedStoreSDNode>(
8637       dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
8638   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8639   ID.AddInteger(MMO->getFlags());
8640   void *IP = nullptr;
8641   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8642     cast<MaskedStoreSDNode>(E)->refineAlignment(MMO);
8643     return SDValue(E, 0);
8644   }
8645   auto *N =
8646       newSDNode<MaskedStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
8647                                    IsTruncating, IsCompressing, MemVT, MMO);
8648   createOperands(N, Ops);
8649 
8650   CSEMap.InsertNode(N, IP);
8651   InsertNode(N);
8652   SDValue V(N, 0);
8653   NewSDValueDbgMsg(V, "Creating new node: ", this);
8654   return V;
8655 }
8656 
8657 SDValue SelectionDAG::getIndexedMaskedStore(SDValue OrigStore, const SDLoc &dl,
8658                                             SDValue Base, SDValue Offset,
8659                                             ISD::MemIndexedMode AM) {
8660   MaskedStoreSDNode *ST = cast<MaskedStoreSDNode>(OrigStore);
8661   assert(ST->getOffset().isUndef() &&
8662          "Masked store is already a indexed store!");
8663   return getMaskedStore(ST->getChain(), dl, ST->getValue(), Base, Offset,
8664                         ST->getMask(), ST->getMemoryVT(), ST->getMemOperand(),
8665                         AM, ST->isTruncatingStore(), ST->isCompressingStore());
8666 }
8667 
8668 SDValue SelectionDAG::getMaskedGather(SDVTList VTs, EVT MemVT, const SDLoc &dl,
8669                                       ArrayRef<SDValue> Ops,
8670                                       MachineMemOperand *MMO,
8671                                       ISD::MemIndexType IndexType,
8672                                       ISD::LoadExtType ExtTy) {
8673   assert(Ops.size() == 6 && "Incompatible number of operands");
8674 
8675   FoldingSetNodeID ID;
8676   AddNodeIDNode(ID, ISD::MGATHER, VTs, Ops);
8677   ID.AddInteger(MemVT.getRawBits());
8678   ID.AddInteger(getSyntheticNodeSubclassData<MaskedGatherSDNode>(
8679       dl.getIROrder(), VTs, MemVT, MMO, IndexType, ExtTy));
8680   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8681   ID.AddInteger(MMO->getFlags());
8682   void *IP = nullptr;
8683   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8684     cast<MaskedGatherSDNode>(E)->refineAlignment(MMO);
8685     return SDValue(E, 0);
8686   }
8687 
8688   auto *N = newSDNode<MaskedGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(),
8689                                           VTs, MemVT, MMO, IndexType, ExtTy);
8690   createOperands(N, Ops);
8691 
8692   assert(N->getPassThru().getValueType() == N->getValueType(0) &&
8693          "Incompatible type of the PassThru value in MaskedGatherSDNode");
8694   assert(N->getMask().getValueType().getVectorElementCount() ==
8695              N->getValueType(0).getVectorElementCount() &&
8696          "Vector width mismatch between mask and data");
8697   assert(N->getIndex().getValueType().getVectorElementCount().isScalable() ==
8698              N->getValueType(0).getVectorElementCount().isScalable() &&
8699          "Scalable flags of index and data do not match");
8700   assert(ElementCount::isKnownGE(
8701              N->getIndex().getValueType().getVectorElementCount(),
8702              N->getValueType(0).getVectorElementCount()) &&
8703          "Vector width mismatch between index and data");
8704   assert(isa<ConstantSDNode>(N->getScale()) &&
8705          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
8706          "Scale should be a constant power of 2");
8707 
8708   CSEMap.InsertNode(N, IP);
8709   InsertNode(N);
8710   SDValue V(N, 0);
8711   NewSDValueDbgMsg(V, "Creating new node: ", this);
8712   return V;
8713 }
8714 
8715 SDValue SelectionDAG::getMaskedScatter(SDVTList VTs, EVT MemVT, const SDLoc &dl,
8716                                        ArrayRef<SDValue> Ops,
8717                                        MachineMemOperand *MMO,
8718                                        ISD::MemIndexType IndexType,
8719                                        bool IsTrunc) {
8720   assert(Ops.size() == 6 && "Incompatible number of operands");
8721 
8722   FoldingSetNodeID ID;
8723   AddNodeIDNode(ID, ISD::MSCATTER, VTs, Ops);
8724   ID.AddInteger(MemVT.getRawBits());
8725   ID.AddInteger(getSyntheticNodeSubclassData<MaskedScatterSDNode>(
8726       dl.getIROrder(), VTs, MemVT, MMO, IndexType, IsTrunc));
8727   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8728   ID.AddInteger(MMO->getFlags());
8729   void *IP = nullptr;
8730   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8731     cast<MaskedScatterSDNode>(E)->refineAlignment(MMO);
8732     return SDValue(E, 0);
8733   }
8734 
8735   auto *N = newSDNode<MaskedScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(),
8736                                            VTs, MemVT, MMO, IndexType, IsTrunc);
8737   createOperands(N, Ops);
8738 
8739   assert(N->getMask().getValueType().getVectorElementCount() ==
8740              N->getValue().getValueType().getVectorElementCount() &&
8741          "Vector width mismatch between mask and data");
8742   assert(
8743       N->getIndex().getValueType().getVectorElementCount().isScalable() ==
8744           N->getValue().getValueType().getVectorElementCount().isScalable() &&
8745       "Scalable flags of index and data do not match");
8746   assert(ElementCount::isKnownGE(
8747              N->getIndex().getValueType().getVectorElementCount(),
8748              N->getValue().getValueType().getVectorElementCount()) &&
8749          "Vector width mismatch between index and data");
8750   assert(isa<ConstantSDNode>(N->getScale()) &&
8751          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
8752          "Scale should be a constant power of 2");
8753 
8754   CSEMap.InsertNode(N, IP);
8755   InsertNode(N);
8756   SDValue V(N, 0);
8757   NewSDValueDbgMsg(V, "Creating new node: ", this);
8758   return V;
8759 }
8760 
8761 SDValue SelectionDAG::simplifySelect(SDValue Cond, SDValue T, SDValue F) {
8762   // select undef, T, F --> T (if T is a constant), otherwise F
8763   // select, ?, undef, F --> F
8764   // select, ?, T, undef --> T
8765   if (Cond.isUndef())
8766     return isConstantValueOfAnyType(T) ? T : F;
8767   if (T.isUndef())
8768     return F;
8769   if (F.isUndef())
8770     return T;
8771 
8772   // select true, T, F --> T
8773   // select false, T, F --> F
8774   if (auto *CondC = dyn_cast<ConstantSDNode>(Cond))
8775     return CondC->isZero() ? F : T;
8776 
8777   // TODO: This should simplify VSELECT with constant condition using something
8778   // like this (but check boolean contents to be complete?):
8779   //  if (ISD::isBuildVectorAllOnes(Cond.getNode()))
8780   //    return T;
8781   //  if (ISD::isBuildVectorAllZeros(Cond.getNode()))
8782   //    return F;
8783 
8784   // select ?, T, T --> T
8785   if (T == F)
8786     return T;
8787 
8788   return SDValue();
8789 }
8790 
8791 SDValue SelectionDAG::simplifyShift(SDValue X, SDValue Y) {
8792   // shift undef, Y --> 0 (can always assume that the undef value is 0)
8793   if (X.isUndef())
8794     return getConstant(0, SDLoc(X.getNode()), X.getValueType());
8795   // shift X, undef --> undef (because it may shift by the bitwidth)
8796   if (Y.isUndef())
8797     return getUNDEF(X.getValueType());
8798 
8799   // shift 0, Y --> 0
8800   // shift X, 0 --> X
8801   if (isNullOrNullSplat(X) || isNullOrNullSplat(Y))
8802     return X;
8803 
8804   // shift X, C >= bitwidth(X) --> undef
8805   // All vector elements must be too big (or undef) to avoid partial undefs.
8806   auto isShiftTooBig = [X](ConstantSDNode *Val) {
8807     return !Val || Val->getAPIntValue().uge(X.getScalarValueSizeInBits());
8808   };
8809   if (ISD::matchUnaryPredicate(Y, isShiftTooBig, true))
8810     return getUNDEF(X.getValueType());
8811 
8812   return SDValue();
8813 }
8814 
8815 SDValue SelectionDAG::simplifyFPBinop(unsigned Opcode, SDValue X, SDValue Y,
8816                                       SDNodeFlags Flags) {
8817   // If this operation has 'nnan' or 'ninf' and at least 1 disallowed operand
8818   // (an undef operand can be chosen to be Nan/Inf), then the result of this
8819   // operation is poison. That result can be relaxed to undef.
8820   ConstantFPSDNode *XC = isConstOrConstSplatFP(X, /* AllowUndefs */ true);
8821   ConstantFPSDNode *YC = isConstOrConstSplatFP(Y, /* AllowUndefs */ true);
8822   bool HasNan = (XC && XC->getValueAPF().isNaN()) ||
8823                 (YC && YC->getValueAPF().isNaN());
8824   bool HasInf = (XC && XC->getValueAPF().isInfinity()) ||
8825                 (YC && YC->getValueAPF().isInfinity());
8826 
8827   if (Flags.hasNoNaNs() && (HasNan || X.isUndef() || Y.isUndef()))
8828     return getUNDEF(X.getValueType());
8829 
8830   if (Flags.hasNoInfs() && (HasInf || X.isUndef() || Y.isUndef()))
8831     return getUNDEF(X.getValueType());
8832 
8833   if (!YC)
8834     return SDValue();
8835 
8836   // X + -0.0 --> X
8837   if (Opcode == ISD::FADD)
8838     if (YC->getValueAPF().isNegZero())
8839       return X;
8840 
8841   // X - +0.0 --> X
8842   if (Opcode == ISD::FSUB)
8843     if (YC->getValueAPF().isPosZero())
8844       return X;
8845 
8846   // X * 1.0 --> X
8847   // X / 1.0 --> X
8848   if (Opcode == ISD::FMUL || Opcode == ISD::FDIV)
8849     if (YC->getValueAPF().isExactlyValue(1.0))
8850       return X;
8851 
8852   // X * 0.0 --> 0.0
8853   if (Opcode == ISD::FMUL && Flags.hasNoNaNs() && Flags.hasNoSignedZeros())
8854     if (YC->getValueAPF().isZero())
8855       return getConstantFP(0.0, SDLoc(Y), Y.getValueType());
8856 
8857   return SDValue();
8858 }
8859 
8860 SDValue SelectionDAG::getVAArg(EVT VT, const SDLoc &dl, SDValue Chain,
8861                                SDValue Ptr, SDValue SV, unsigned Align) {
8862   SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, dl, MVT::i32) };
8863   return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops);
8864 }
8865 
8866 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8867                               ArrayRef<SDUse> Ops) {
8868   switch (Ops.size()) {
8869   case 0: return getNode(Opcode, DL, VT);
8870   case 1: return getNode(Opcode, DL, VT, static_cast<const SDValue>(Ops[0]));
8871   case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
8872   case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
8873   default: break;
8874   }
8875 
8876   // Copy from an SDUse array into an SDValue array for use with
8877   // the regular getNode logic.
8878   SmallVector<SDValue, 8> NewOps(Ops.begin(), Ops.end());
8879   return getNode(Opcode, DL, VT, NewOps);
8880 }
8881 
8882 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8883                               ArrayRef<SDValue> Ops) {
8884   SDNodeFlags Flags;
8885   if (Inserter)
8886     Flags = Inserter->getFlags();
8887   return getNode(Opcode, DL, VT, Ops, Flags);
8888 }
8889 
8890 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8891                               ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
8892   unsigned NumOps = Ops.size();
8893   switch (NumOps) {
8894   case 0: return getNode(Opcode, DL, VT);
8895   case 1: return getNode(Opcode, DL, VT, Ops[0], Flags);
8896   case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Flags);
8897   case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2], Flags);
8898   default: break;
8899   }
8900 
8901 #ifndef NDEBUG
8902   for (auto &Op : Ops)
8903     assert(Op.getOpcode() != ISD::DELETED_NODE &&
8904            "Operand is DELETED_NODE!");
8905 #endif
8906 
8907   switch (Opcode) {
8908   default: break;
8909   case ISD::BUILD_VECTOR:
8910     // Attempt to simplify BUILD_VECTOR.
8911     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
8912       return V;
8913     break;
8914   case ISD::CONCAT_VECTORS:
8915     if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
8916       return V;
8917     break;
8918   case ISD::SELECT_CC:
8919     assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
8920     assert(Ops[0].getValueType() == Ops[1].getValueType() &&
8921            "LHS and RHS of condition must have same type!");
8922     assert(Ops[2].getValueType() == Ops[3].getValueType() &&
8923            "True and False arms of SelectCC must have same type!");
8924     assert(Ops[2].getValueType() == VT &&
8925            "select_cc node must be of same type as true and false value!");
8926     break;
8927   case ISD::BR_CC:
8928     assert(NumOps == 5 && "BR_CC takes 5 operands!");
8929     assert(Ops[2].getValueType() == Ops[3].getValueType() &&
8930            "LHS/RHS of comparison should match types!");
8931     break;
8932   case ISD::VP_ADD:
8933   case ISD::VP_SUB:
8934     // If it is VP_ADD/VP_SUB mask operation then turn it to VP_XOR
8935     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
8936       Opcode = ISD::VP_XOR;
8937     break;
8938   case ISD::VP_MUL:
8939     // If it is VP_MUL mask operation then turn it to VP_AND
8940     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
8941       Opcode = ISD::VP_AND;
8942     break;
8943   case ISD::VP_REDUCE_MUL:
8944     // If it is VP_REDUCE_MUL mask operation then turn it to VP_REDUCE_AND
8945     if (VT == MVT::i1)
8946       Opcode = ISD::VP_REDUCE_AND;
8947     break;
8948   case ISD::VP_REDUCE_ADD:
8949     // If it is VP_REDUCE_ADD mask operation then turn it to VP_REDUCE_XOR
8950     if (VT == MVT::i1)
8951       Opcode = ISD::VP_REDUCE_XOR;
8952     break;
8953   case ISD::VP_REDUCE_SMAX:
8954   case ISD::VP_REDUCE_UMIN:
8955     // If it is VP_REDUCE_SMAX/VP_REDUCE_UMIN mask operation then turn it to
8956     // VP_REDUCE_AND.
8957     if (VT == MVT::i1)
8958       Opcode = ISD::VP_REDUCE_AND;
8959     break;
8960   case ISD::VP_REDUCE_SMIN:
8961   case ISD::VP_REDUCE_UMAX:
8962     // If it is VP_REDUCE_SMIN/VP_REDUCE_UMAX mask operation then turn it to
8963     // VP_REDUCE_OR.
8964     if (VT == MVT::i1)
8965       Opcode = ISD::VP_REDUCE_OR;
8966     break;
8967   }
8968 
8969   // Memoize nodes.
8970   SDNode *N;
8971   SDVTList VTs = getVTList(VT);
8972 
8973   if (VT != MVT::Glue) {
8974     FoldingSetNodeID ID;
8975     AddNodeIDNode(ID, Opcode, VTs, Ops);
8976     void *IP = nullptr;
8977 
8978     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
8979       return SDValue(E, 0);
8980 
8981     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
8982     createOperands(N, Ops);
8983 
8984     CSEMap.InsertNode(N, IP);
8985   } else {
8986     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
8987     createOperands(N, Ops);
8988   }
8989 
8990   N->setFlags(Flags);
8991   InsertNode(N);
8992   SDValue V(N, 0);
8993   NewSDValueDbgMsg(V, "Creating new node: ", this);
8994   return V;
8995 }
8996 
8997 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
8998                               ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) {
8999   return getNode(Opcode, DL, getVTList(ResultTys), Ops);
9000 }
9001 
9002 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
9003                               ArrayRef<SDValue> Ops) {
9004   SDNodeFlags Flags;
9005   if (Inserter)
9006     Flags = Inserter->getFlags();
9007   return getNode(Opcode, DL, VTList, Ops, Flags);
9008 }
9009 
9010 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
9011                               ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
9012   if (VTList.NumVTs == 1)
9013     return getNode(Opcode, DL, VTList.VTs[0], Ops, Flags);
9014 
9015 #ifndef NDEBUG
9016   for (auto &Op : Ops)
9017     assert(Op.getOpcode() != ISD::DELETED_NODE &&
9018            "Operand is DELETED_NODE!");
9019 #endif
9020 
9021   switch (Opcode) {
9022   case ISD::STRICT_FP_EXTEND:
9023     assert(VTList.NumVTs == 2 && Ops.size() == 2 &&
9024            "Invalid STRICT_FP_EXTEND!");
9025     assert(VTList.VTs[0].isFloatingPoint() &&
9026            Ops[1].getValueType().isFloatingPoint() && "Invalid FP cast!");
9027     assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
9028            "STRICT_FP_EXTEND result type should be vector iff the operand "
9029            "type is vector!");
9030     assert((!VTList.VTs[0].isVector() ||
9031             VTList.VTs[0].getVectorNumElements() ==
9032             Ops[1].getValueType().getVectorNumElements()) &&
9033            "Vector element count mismatch!");
9034     assert(Ops[1].getValueType().bitsLT(VTList.VTs[0]) &&
9035            "Invalid fpext node, dst <= src!");
9036     break;
9037   case ISD::STRICT_FP_ROUND:
9038     assert(VTList.NumVTs == 2 && Ops.size() == 3 && "Invalid STRICT_FP_ROUND!");
9039     assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
9040            "STRICT_FP_ROUND result type should be vector iff the operand "
9041            "type is vector!");
9042     assert((!VTList.VTs[0].isVector() ||
9043             VTList.VTs[0].getVectorNumElements() ==
9044             Ops[1].getValueType().getVectorNumElements()) &&
9045            "Vector element count mismatch!");
9046     assert(VTList.VTs[0].isFloatingPoint() &&
9047            Ops[1].getValueType().isFloatingPoint() &&
9048            VTList.VTs[0].bitsLT(Ops[1].getValueType()) &&
9049            isa<ConstantSDNode>(Ops[2]) &&
9050            (cast<ConstantSDNode>(Ops[2])->getZExtValue() == 0 ||
9051             cast<ConstantSDNode>(Ops[2])->getZExtValue() == 1) &&
9052            "Invalid STRICT_FP_ROUND!");
9053     break;
9054 #if 0
9055   // FIXME: figure out how to safely handle things like
9056   // int foo(int x) { return 1 << (x & 255); }
9057   // int bar() { return foo(256); }
9058   case ISD::SRA_PARTS:
9059   case ISD::SRL_PARTS:
9060   case ISD::SHL_PARTS:
9061     if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
9062         cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
9063       return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
9064     else if (N3.getOpcode() == ISD::AND)
9065       if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
9066         // If the and is only masking out bits that cannot effect the shift,
9067         // eliminate the and.
9068         unsigned NumBits = VT.getScalarSizeInBits()*2;
9069         if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
9070           return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
9071       }
9072     break;
9073 #endif
9074   }
9075 
9076   // Memoize the node unless it returns a flag.
9077   SDNode *N;
9078   if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
9079     FoldingSetNodeID ID;
9080     AddNodeIDNode(ID, Opcode, VTList, Ops);
9081     void *IP = nullptr;
9082     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
9083       return SDValue(E, 0);
9084 
9085     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
9086     createOperands(N, Ops);
9087     CSEMap.InsertNode(N, IP);
9088   } else {
9089     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
9090     createOperands(N, Ops);
9091   }
9092 
9093   N->setFlags(Flags);
9094   InsertNode(N);
9095   SDValue V(N, 0);
9096   NewSDValueDbgMsg(V, "Creating new node: ", this);
9097   return V;
9098 }
9099 
9100 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
9101                               SDVTList VTList) {
9102   return getNode(Opcode, DL, VTList, None);
9103 }
9104 
9105 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
9106                               SDValue N1) {
9107   SDValue Ops[] = { N1 };
9108   return getNode(Opcode, DL, VTList, Ops);
9109 }
9110 
9111 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
9112                               SDValue N1, SDValue N2) {
9113   SDValue Ops[] = { N1, N2 };
9114   return getNode(Opcode, DL, VTList, Ops);
9115 }
9116 
9117 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
9118                               SDValue N1, SDValue N2, SDValue N3) {
9119   SDValue Ops[] = { N1, N2, N3 };
9120   return getNode(Opcode, DL, VTList, Ops);
9121 }
9122 
9123 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
9124                               SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
9125   SDValue Ops[] = { N1, N2, N3, N4 };
9126   return getNode(Opcode, DL, VTList, Ops);
9127 }
9128 
9129 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
9130                               SDValue N1, SDValue N2, SDValue N3, SDValue N4,
9131                               SDValue N5) {
9132   SDValue Ops[] = { N1, N2, N3, N4, N5 };
9133   return getNode(Opcode, DL, VTList, Ops);
9134 }
9135 
9136 SDVTList SelectionDAG::getVTList(EVT VT) {
9137   return makeVTList(SDNode::getValueTypeList(VT), 1);
9138 }
9139 
9140 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2) {
9141   FoldingSetNodeID ID;
9142   ID.AddInteger(2U);
9143   ID.AddInteger(VT1.getRawBits());
9144   ID.AddInteger(VT2.getRawBits());
9145 
9146   void *IP = nullptr;
9147   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
9148   if (!Result) {
9149     EVT *Array = Allocator.Allocate<EVT>(2);
9150     Array[0] = VT1;
9151     Array[1] = VT2;
9152     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 2);
9153     VTListMap.InsertNode(Result, IP);
9154   }
9155   return Result->getSDVTList();
9156 }
9157 
9158 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3) {
9159   FoldingSetNodeID ID;
9160   ID.AddInteger(3U);
9161   ID.AddInteger(VT1.getRawBits());
9162   ID.AddInteger(VT2.getRawBits());
9163   ID.AddInteger(VT3.getRawBits());
9164 
9165   void *IP = nullptr;
9166   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
9167   if (!Result) {
9168     EVT *Array = Allocator.Allocate<EVT>(3);
9169     Array[0] = VT1;
9170     Array[1] = VT2;
9171     Array[2] = VT3;
9172     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 3);
9173     VTListMap.InsertNode(Result, IP);
9174   }
9175   return Result->getSDVTList();
9176 }
9177 
9178 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4) {
9179   FoldingSetNodeID ID;
9180   ID.AddInteger(4U);
9181   ID.AddInteger(VT1.getRawBits());
9182   ID.AddInteger(VT2.getRawBits());
9183   ID.AddInteger(VT3.getRawBits());
9184   ID.AddInteger(VT4.getRawBits());
9185 
9186   void *IP = nullptr;
9187   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
9188   if (!Result) {
9189     EVT *Array = Allocator.Allocate<EVT>(4);
9190     Array[0] = VT1;
9191     Array[1] = VT2;
9192     Array[2] = VT3;
9193     Array[3] = VT4;
9194     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 4);
9195     VTListMap.InsertNode(Result, IP);
9196   }
9197   return Result->getSDVTList();
9198 }
9199 
9200 SDVTList SelectionDAG::getVTList(ArrayRef<EVT> VTs) {
9201   unsigned NumVTs = VTs.size();
9202   FoldingSetNodeID ID;
9203   ID.AddInteger(NumVTs);
9204   for (unsigned index = 0; index < NumVTs; index++) {
9205     ID.AddInteger(VTs[index].getRawBits());
9206   }
9207 
9208   void *IP = nullptr;
9209   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
9210   if (!Result) {
9211     EVT *Array = Allocator.Allocate<EVT>(NumVTs);
9212     llvm::copy(VTs, Array);
9213     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, NumVTs);
9214     VTListMap.InsertNode(Result, IP);
9215   }
9216   return Result->getSDVTList();
9217 }
9218 
9219 
9220 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
9221 /// specified operands.  If the resultant node already exists in the DAG,
9222 /// this does not modify the specified node, instead it returns the node that
9223 /// already exists.  If the resultant node does not exist in the DAG, the
9224 /// input node is returned.  As a degenerate case, if you specify the same
9225 /// input operands as the node already has, the input node is returned.
9226 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op) {
9227   assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
9228 
9229   // Check to see if there is no change.
9230   if (Op == N->getOperand(0)) return N;
9231 
9232   // See if the modified node already exists.
9233   void *InsertPos = nullptr;
9234   if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
9235     return Existing;
9236 
9237   // Nope it doesn't.  Remove the node from its current place in the maps.
9238   if (InsertPos)
9239     if (!RemoveNodeFromCSEMaps(N))
9240       InsertPos = nullptr;
9241 
9242   // Now we update the operands.
9243   N->OperandList[0].set(Op);
9244 
9245   updateDivergence(N);
9246   // If this gets put into a CSE map, add it.
9247   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
9248   return N;
9249 }
9250 
9251 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2) {
9252   assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
9253 
9254   // Check to see if there is no change.
9255   if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
9256     return N;   // No operands changed, just return the input node.
9257 
9258   // See if the modified node already exists.
9259   void *InsertPos = nullptr;
9260   if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
9261     return Existing;
9262 
9263   // Nope it doesn't.  Remove the node from its current place in the maps.
9264   if (InsertPos)
9265     if (!RemoveNodeFromCSEMaps(N))
9266       InsertPos = nullptr;
9267 
9268   // Now we update the operands.
9269   if (N->OperandList[0] != Op1)
9270     N->OperandList[0].set(Op1);
9271   if (N->OperandList[1] != Op2)
9272     N->OperandList[1].set(Op2);
9273 
9274   updateDivergence(N);
9275   // If this gets put into a CSE map, add it.
9276   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
9277   return N;
9278 }
9279 
9280 SDNode *SelectionDAG::
9281 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, SDValue Op3) {
9282   SDValue Ops[] = { Op1, Op2, Op3 };
9283   return UpdateNodeOperands(N, Ops);
9284 }
9285 
9286 SDNode *SelectionDAG::
9287 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
9288                    SDValue Op3, SDValue Op4) {
9289   SDValue Ops[] = { Op1, Op2, Op3, Op4 };
9290   return UpdateNodeOperands(N, Ops);
9291 }
9292 
9293 SDNode *SelectionDAG::
9294 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
9295                    SDValue Op3, SDValue Op4, SDValue Op5) {
9296   SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 };
9297   return UpdateNodeOperands(N, Ops);
9298 }
9299 
9300 SDNode *SelectionDAG::
9301 UpdateNodeOperands(SDNode *N, ArrayRef<SDValue> Ops) {
9302   unsigned NumOps = Ops.size();
9303   assert(N->getNumOperands() == NumOps &&
9304          "Update with wrong number of operands");
9305 
9306   // If no operands changed just return the input node.
9307   if (std::equal(Ops.begin(), Ops.end(), N->op_begin()))
9308     return N;
9309 
9310   // See if the modified node already exists.
9311   void *InsertPos = nullptr;
9312   if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertPos))
9313     return Existing;
9314 
9315   // Nope it doesn't.  Remove the node from its current place in the maps.
9316   if (InsertPos)
9317     if (!RemoveNodeFromCSEMaps(N))
9318       InsertPos = nullptr;
9319 
9320   // Now we update the operands.
9321   for (unsigned i = 0; i != NumOps; ++i)
9322     if (N->OperandList[i] != Ops[i])
9323       N->OperandList[i].set(Ops[i]);
9324 
9325   updateDivergence(N);
9326   // If this gets put into a CSE map, add it.
9327   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
9328   return N;
9329 }
9330 
9331 /// DropOperands - Release the operands and set this node to have
9332 /// zero operands.
9333 void SDNode::DropOperands() {
9334   // Unlike the code in MorphNodeTo that does this, we don't need to
9335   // watch for dead nodes here.
9336   for (op_iterator I = op_begin(), E = op_end(); I != E; ) {
9337     SDUse &Use = *I++;
9338     Use.set(SDValue());
9339   }
9340 }
9341 
9342 void SelectionDAG::setNodeMemRefs(MachineSDNode *N,
9343                                   ArrayRef<MachineMemOperand *> NewMemRefs) {
9344   if (NewMemRefs.empty()) {
9345     N->clearMemRefs();
9346     return;
9347   }
9348 
9349   // Check if we can avoid allocating by storing a single reference directly.
9350   if (NewMemRefs.size() == 1) {
9351     N->MemRefs = NewMemRefs[0];
9352     N->NumMemRefs = 1;
9353     return;
9354   }
9355 
9356   MachineMemOperand **MemRefsBuffer =
9357       Allocator.template Allocate<MachineMemOperand *>(NewMemRefs.size());
9358   llvm::copy(NewMemRefs, MemRefsBuffer);
9359   N->MemRefs = MemRefsBuffer;
9360   N->NumMemRefs = static_cast<int>(NewMemRefs.size());
9361 }
9362 
9363 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a
9364 /// machine opcode.
9365 ///
9366 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9367                                    EVT VT) {
9368   SDVTList VTs = getVTList(VT);
9369   return SelectNodeTo(N, MachineOpc, VTs, None);
9370 }
9371 
9372 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9373                                    EVT VT, SDValue Op1) {
9374   SDVTList VTs = getVTList(VT);
9375   SDValue Ops[] = { Op1 };
9376   return SelectNodeTo(N, MachineOpc, VTs, Ops);
9377 }
9378 
9379 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9380                                    EVT VT, SDValue Op1,
9381                                    SDValue Op2) {
9382   SDVTList VTs = getVTList(VT);
9383   SDValue Ops[] = { Op1, Op2 };
9384   return SelectNodeTo(N, MachineOpc, VTs, Ops);
9385 }
9386 
9387 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9388                                    EVT VT, SDValue Op1,
9389                                    SDValue Op2, SDValue Op3) {
9390   SDVTList VTs = getVTList(VT);
9391   SDValue Ops[] = { Op1, Op2, Op3 };
9392   return SelectNodeTo(N, MachineOpc, VTs, Ops);
9393 }
9394 
9395 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9396                                    EVT VT, ArrayRef<SDValue> Ops) {
9397   SDVTList VTs = getVTList(VT);
9398   return SelectNodeTo(N, MachineOpc, VTs, Ops);
9399 }
9400 
9401 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9402                                    EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) {
9403   SDVTList VTs = getVTList(VT1, VT2);
9404   return SelectNodeTo(N, MachineOpc, VTs, Ops);
9405 }
9406 
9407 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9408                                    EVT VT1, EVT VT2) {
9409   SDVTList VTs = getVTList(VT1, VT2);
9410   return SelectNodeTo(N, MachineOpc, VTs, None);
9411 }
9412 
9413 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9414                                    EVT VT1, EVT VT2, EVT VT3,
9415                                    ArrayRef<SDValue> Ops) {
9416   SDVTList VTs = getVTList(VT1, VT2, VT3);
9417   return SelectNodeTo(N, MachineOpc, VTs, Ops);
9418 }
9419 
9420 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9421                                    EVT VT1, EVT VT2,
9422                                    SDValue Op1, SDValue Op2) {
9423   SDVTList VTs = getVTList(VT1, VT2);
9424   SDValue Ops[] = { Op1, Op2 };
9425   return SelectNodeTo(N, MachineOpc, VTs, Ops);
9426 }
9427 
9428 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9429                                    SDVTList VTs,ArrayRef<SDValue> Ops) {
9430   SDNode *New = MorphNodeTo(N, ~MachineOpc, VTs, Ops);
9431   // Reset the NodeID to -1.
9432   New->setNodeId(-1);
9433   if (New != N) {
9434     ReplaceAllUsesWith(N, New);
9435     RemoveDeadNode(N);
9436   }
9437   return New;
9438 }
9439 
9440 /// UpdateSDLocOnMergeSDNode - If the opt level is -O0 then it throws away
9441 /// the line number information on the merged node since it is not possible to
9442 /// preserve the information that operation is associated with multiple lines.
9443 /// This will make the debugger working better at -O0, were there is a higher
9444 /// probability having other instructions associated with that line.
9445 ///
9446 /// For IROrder, we keep the smaller of the two
9447 SDNode *SelectionDAG::UpdateSDLocOnMergeSDNode(SDNode *N, const SDLoc &OLoc) {
9448   DebugLoc NLoc = N->getDebugLoc();
9449   if (NLoc && OptLevel == CodeGenOpt::None && OLoc.getDebugLoc() != NLoc) {
9450     N->setDebugLoc(DebugLoc());
9451   }
9452   unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder());
9453   N->setIROrder(Order);
9454   return N;
9455 }
9456 
9457 /// MorphNodeTo - This *mutates* the specified node to have the specified
9458 /// return type, opcode, and operands.
9459 ///
9460 /// Note that MorphNodeTo returns the resultant node.  If there is already a
9461 /// node of the specified opcode and operands, it returns that node instead of
9462 /// the current one.  Note that the SDLoc need not be the same.
9463 ///
9464 /// Using MorphNodeTo is faster than creating a new node and swapping it in
9465 /// with ReplaceAllUsesWith both because it often avoids allocating a new
9466 /// node, and because it doesn't require CSE recalculation for any of
9467 /// the node's users.
9468 ///
9469 /// However, note that MorphNodeTo recursively deletes dead nodes from the DAG.
9470 /// As a consequence it isn't appropriate to use from within the DAG combiner or
9471 /// the legalizer which maintain worklists that would need to be updated when
9472 /// deleting things.
9473 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
9474                                   SDVTList VTs, ArrayRef<SDValue> Ops) {
9475   // If an identical node already exists, use it.
9476   void *IP = nullptr;
9477   if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) {
9478     FoldingSetNodeID ID;
9479     AddNodeIDNode(ID, Opc, VTs, Ops);
9480     if (SDNode *ON = FindNodeOrInsertPos(ID, SDLoc(N), IP))
9481       return UpdateSDLocOnMergeSDNode(ON, SDLoc(N));
9482   }
9483 
9484   if (!RemoveNodeFromCSEMaps(N))
9485     IP = nullptr;
9486 
9487   // Start the morphing.
9488   N->NodeType = Opc;
9489   N->ValueList = VTs.VTs;
9490   N->NumValues = VTs.NumVTs;
9491 
9492   // Clear the operands list, updating used nodes to remove this from their
9493   // use list.  Keep track of any operands that become dead as a result.
9494   SmallPtrSet<SDNode*, 16> DeadNodeSet;
9495   for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
9496     SDUse &Use = *I++;
9497     SDNode *Used = Use.getNode();
9498     Use.set(SDValue());
9499     if (Used->use_empty())
9500       DeadNodeSet.insert(Used);
9501   }
9502 
9503   // For MachineNode, initialize the memory references information.
9504   if (MachineSDNode *MN = dyn_cast<MachineSDNode>(N))
9505     MN->clearMemRefs();
9506 
9507   // Swap for an appropriately sized array from the recycler.
9508   removeOperands(N);
9509   createOperands(N, Ops);
9510 
9511   // Delete any nodes that are still dead after adding the uses for the
9512   // new operands.
9513   if (!DeadNodeSet.empty()) {
9514     SmallVector<SDNode *, 16> DeadNodes;
9515     for (SDNode *N : DeadNodeSet)
9516       if (N->use_empty())
9517         DeadNodes.push_back(N);
9518     RemoveDeadNodes(DeadNodes);
9519   }
9520 
9521   if (IP)
9522     CSEMap.InsertNode(N, IP);   // Memoize the new node.
9523   return N;
9524 }
9525 
9526 SDNode* SelectionDAG::mutateStrictFPToFP(SDNode *Node) {
9527   unsigned OrigOpc = Node->getOpcode();
9528   unsigned NewOpc;
9529   switch (OrigOpc) {
9530   default:
9531     llvm_unreachable("mutateStrictFPToFP called with unexpected opcode!");
9532 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
9533   case ISD::STRICT_##DAGN: NewOpc = ISD::DAGN; break;
9534 #define CMP_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
9535   case ISD::STRICT_##DAGN: NewOpc = ISD::SETCC; break;
9536 #include "llvm/IR/ConstrainedOps.def"
9537   }
9538 
9539   assert(Node->getNumValues() == 2 && "Unexpected number of results!");
9540 
9541   // We're taking this node out of the chain, so we need to re-link things.
9542   SDValue InputChain = Node->getOperand(0);
9543   SDValue OutputChain = SDValue(Node, 1);
9544   ReplaceAllUsesOfValueWith(OutputChain, InputChain);
9545 
9546   SmallVector<SDValue, 3> Ops;
9547   for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
9548     Ops.push_back(Node->getOperand(i));
9549 
9550   SDVTList VTs = getVTList(Node->getValueType(0));
9551   SDNode *Res = MorphNodeTo(Node, NewOpc, VTs, Ops);
9552 
9553   // MorphNodeTo can operate in two ways: if an existing node with the
9554   // specified operands exists, it can just return it.  Otherwise, it
9555   // updates the node in place to have the requested operands.
9556   if (Res == Node) {
9557     // If we updated the node in place, reset the node ID.  To the isel,
9558     // this should be just like a newly allocated machine node.
9559     Res->setNodeId(-1);
9560   } else {
9561     ReplaceAllUsesWith(Node, Res);
9562     RemoveDeadNode(Node);
9563   }
9564 
9565   return Res;
9566 }
9567 
9568 /// getMachineNode - These are used for target selectors to create a new node
9569 /// with specified return type(s), MachineInstr opcode, and operands.
9570 ///
9571 /// Note that getMachineNode returns the resultant node.  If there is already a
9572 /// node of the specified opcode and operands, it returns that node instead of
9573 /// the current one.
9574 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9575                                             EVT VT) {
9576   SDVTList VTs = getVTList(VT);
9577   return getMachineNode(Opcode, dl, VTs, None);
9578 }
9579 
9580 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9581                                             EVT VT, SDValue Op1) {
9582   SDVTList VTs = getVTList(VT);
9583   SDValue Ops[] = { Op1 };
9584   return getMachineNode(Opcode, dl, VTs, Ops);
9585 }
9586 
9587 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9588                                             EVT VT, SDValue Op1, SDValue Op2) {
9589   SDVTList VTs = getVTList(VT);
9590   SDValue Ops[] = { Op1, Op2 };
9591   return getMachineNode(Opcode, dl, VTs, Ops);
9592 }
9593 
9594 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9595                                             EVT VT, SDValue Op1, SDValue Op2,
9596                                             SDValue Op3) {
9597   SDVTList VTs = getVTList(VT);
9598   SDValue Ops[] = { Op1, Op2, Op3 };
9599   return getMachineNode(Opcode, dl, VTs, Ops);
9600 }
9601 
9602 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9603                                             EVT VT, ArrayRef<SDValue> Ops) {
9604   SDVTList VTs = getVTList(VT);
9605   return getMachineNode(Opcode, dl, VTs, Ops);
9606 }
9607 
9608 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9609                                             EVT VT1, EVT VT2, SDValue Op1,
9610                                             SDValue Op2) {
9611   SDVTList VTs = getVTList(VT1, VT2);
9612   SDValue Ops[] = { Op1, Op2 };
9613   return getMachineNode(Opcode, dl, VTs, Ops);
9614 }
9615 
9616 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9617                                             EVT VT1, EVT VT2, SDValue Op1,
9618                                             SDValue Op2, SDValue Op3) {
9619   SDVTList VTs = getVTList(VT1, VT2);
9620   SDValue Ops[] = { Op1, Op2, Op3 };
9621   return getMachineNode(Opcode, dl, VTs, Ops);
9622 }
9623 
9624 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9625                                             EVT VT1, EVT VT2,
9626                                             ArrayRef<SDValue> Ops) {
9627   SDVTList VTs = getVTList(VT1, VT2);
9628   return getMachineNode(Opcode, dl, VTs, Ops);
9629 }
9630 
9631 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9632                                             EVT VT1, EVT VT2, EVT VT3,
9633                                             SDValue Op1, SDValue Op2) {
9634   SDVTList VTs = getVTList(VT1, VT2, VT3);
9635   SDValue Ops[] = { Op1, Op2 };
9636   return getMachineNode(Opcode, dl, VTs, Ops);
9637 }
9638 
9639 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9640                                             EVT VT1, EVT VT2, EVT VT3,
9641                                             SDValue Op1, SDValue Op2,
9642                                             SDValue Op3) {
9643   SDVTList VTs = getVTList(VT1, VT2, VT3);
9644   SDValue Ops[] = { Op1, Op2, Op3 };
9645   return getMachineNode(Opcode, dl, VTs, Ops);
9646 }
9647 
9648 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9649                                             EVT VT1, EVT VT2, EVT VT3,
9650                                             ArrayRef<SDValue> Ops) {
9651   SDVTList VTs = getVTList(VT1, VT2, VT3);
9652   return getMachineNode(Opcode, dl, VTs, Ops);
9653 }
9654 
9655 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9656                                             ArrayRef<EVT> ResultTys,
9657                                             ArrayRef<SDValue> Ops) {
9658   SDVTList VTs = getVTList(ResultTys);
9659   return getMachineNode(Opcode, dl, VTs, Ops);
9660 }
9661 
9662 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &DL,
9663                                             SDVTList VTs,
9664                                             ArrayRef<SDValue> Ops) {
9665   bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue;
9666   MachineSDNode *N;
9667   void *IP = nullptr;
9668 
9669   if (DoCSE) {
9670     FoldingSetNodeID ID;
9671     AddNodeIDNode(ID, ~Opcode, VTs, Ops);
9672     IP = nullptr;
9673     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
9674       return cast<MachineSDNode>(UpdateSDLocOnMergeSDNode(E, DL));
9675     }
9676   }
9677 
9678   // Allocate a new MachineSDNode.
9679   N = newSDNode<MachineSDNode>(~Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
9680   createOperands(N, Ops);
9681 
9682   if (DoCSE)
9683     CSEMap.InsertNode(N, IP);
9684 
9685   InsertNode(N);
9686   NewSDValueDbgMsg(SDValue(N, 0), "Creating new machine node: ", this);
9687   return N;
9688 }
9689 
9690 /// getTargetExtractSubreg - A convenience function for creating
9691 /// TargetOpcode::EXTRACT_SUBREG nodes.
9692 SDValue SelectionDAG::getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT,
9693                                              SDValue Operand) {
9694   SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
9695   SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,
9696                                   VT, Operand, SRIdxVal);
9697   return SDValue(Subreg, 0);
9698 }
9699 
9700 /// getTargetInsertSubreg - A convenience function for creating
9701 /// TargetOpcode::INSERT_SUBREG nodes.
9702 SDValue SelectionDAG::getTargetInsertSubreg(int SRIdx, const SDLoc &DL, EVT VT,
9703                                             SDValue Operand, SDValue Subreg) {
9704   SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
9705   SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL,
9706                                   VT, Operand, Subreg, SRIdxVal);
9707   return SDValue(Result, 0);
9708 }
9709 
9710 /// getNodeIfExists - Get the specified node if it's already available, or
9711 /// else return NULL.
9712 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
9713                                       ArrayRef<SDValue> Ops) {
9714   SDNodeFlags Flags;
9715   if (Inserter)
9716     Flags = Inserter->getFlags();
9717   return getNodeIfExists(Opcode, VTList, Ops, Flags);
9718 }
9719 
9720 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
9721                                       ArrayRef<SDValue> Ops,
9722                                       const SDNodeFlags Flags) {
9723   if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
9724     FoldingSetNodeID ID;
9725     AddNodeIDNode(ID, Opcode, VTList, Ops);
9726     void *IP = nullptr;
9727     if (SDNode *E = FindNodeOrInsertPos(ID, SDLoc(), IP)) {
9728       E->intersectFlagsWith(Flags);
9729       return E;
9730     }
9731   }
9732   return nullptr;
9733 }
9734 
9735 /// doesNodeExist - Check if a node exists without modifying its flags.
9736 bool SelectionDAG::doesNodeExist(unsigned Opcode, SDVTList VTList,
9737                                  ArrayRef<SDValue> Ops) {
9738   if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
9739     FoldingSetNodeID ID;
9740     AddNodeIDNode(ID, Opcode, VTList, Ops);
9741     void *IP = nullptr;
9742     if (FindNodeOrInsertPos(ID, SDLoc(), IP))
9743       return true;
9744   }
9745   return false;
9746 }
9747 
9748 /// getDbgValue - Creates a SDDbgValue node.
9749 ///
9750 /// SDNode
9751 SDDbgValue *SelectionDAG::getDbgValue(DIVariable *Var, DIExpression *Expr,
9752                                       SDNode *N, unsigned R, bool IsIndirect,
9753                                       const DebugLoc &DL, unsigned O) {
9754   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9755          "Expected inlined-at fields to agree");
9756   return new (DbgInfo->getAlloc())
9757       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromNode(N, R),
9758                  {}, IsIndirect, DL, O,
9759                  /*IsVariadic=*/false);
9760 }
9761 
9762 /// Constant
9763 SDDbgValue *SelectionDAG::getConstantDbgValue(DIVariable *Var,
9764                                               DIExpression *Expr,
9765                                               const Value *C,
9766                                               const DebugLoc &DL, unsigned O) {
9767   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9768          "Expected inlined-at fields to agree");
9769   return new (DbgInfo->getAlloc())
9770       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromConst(C), {},
9771                  /*IsIndirect=*/false, DL, O,
9772                  /*IsVariadic=*/false);
9773 }
9774 
9775 /// FrameIndex
9776 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var,
9777                                                 DIExpression *Expr, unsigned FI,
9778                                                 bool IsIndirect,
9779                                                 const DebugLoc &DL,
9780                                                 unsigned O) {
9781   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9782          "Expected inlined-at fields to agree");
9783   return getFrameIndexDbgValue(Var, Expr, FI, {}, IsIndirect, DL, O);
9784 }
9785 
9786 /// FrameIndex with dependencies
9787 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var,
9788                                                 DIExpression *Expr, unsigned FI,
9789                                                 ArrayRef<SDNode *> Dependencies,
9790                                                 bool IsIndirect,
9791                                                 const DebugLoc &DL,
9792                                                 unsigned O) {
9793   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9794          "Expected inlined-at fields to agree");
9795   return new (DbgInfo->getAlloc())
9796       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromFrameIdx(FI),
9797                  Dependencies, IsIndirect, DL, O,
9798                  /*IsVariadic=*/false);
9799 }
9800 
9801 /// VReg
9802 SDDbgValue *SelectionDAG::getVRegDbgValue(DIVariable *Var, DIExpression *Expr,
9803                                           unsigned VReg, bool IsIndirect,
9804                                           const DebugLoc &DL, unsigned O) {
9805   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9806          "Expected inlined-at fields to agree");
9807   return new (DbgInfo->getAlloc())
9808       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromVReg(VReg),
9809                  {}, IsIndirect, DL, O,
9810                  /*IsVariadic=*/false);
9811 }
9812 
9813 SDDbgValue *SelectionDAG::getDbgValueList(DIVariable *Var, DIExpression *Expr,
9814                                           ArrayRef<SDDbgOperand> Locs,
9815                                           ArrayRef<SDNode *> Dependencies,
9816                                           bool IsIndirect, const DebugLoc &DL,
9817                                           unsigned O, bool IsVariadic) {
9818   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9819          "Expected inlined-at fields to agree");
9820   return new (DbgInfo->getAlloc())
9821       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, Locs, Dependencies, IsIndirect,
9822                  DL, O, IsVariadic);
9823 }
9824 
9825 void SelectionDAG::transferDbgValues(SDValue From, SDValue To,
9826                                      unsigned OffsetInBits, unsigned SizeInBits,
9827                                      bool InvalidateDbg) {
9828   SDNode *FromNode = From.getNode();
9829   SDNode *ToNode = To.getNode();
9830   assert(FromNode && ToNode && "Can't modify dbg values");
9831 
9832   // PR35338
9833   // TODO: assert(From != To && "Redundant dbg value transfer");
9834   // TODO: assert(FromNode != ToNode && "Intranode dbg value transfer");
9835   if (From == To || FromNode == ToNode)
9836     return;
9837 
9838   if (!FromNode->getHasDebugValue())
9839     return;
9840 
9841   SDDbgOperand FromLocOp =
9842       SDDbgOperand::fromNode(From.getNode(), From.getResNo());
9843   SDDbgOperand ToLocOp = SDDbgOperand::fromNode(To.getNode(), To.getResNo());
9844 
9845   SmallVector<SDDbgValue *, 2> ClonedDVs;
9846   for (SDDbgValue *Dbg : GetDbgValues(FromNode)) {
9847     if (Dbg->isInvalidated())
9848       continue;
9849 
9850     // TODO: assert(!Dbg->isInvalidated() && "Transfer of invalid dbg value");
9851 
9852     // Create a new location ops vector that is equal to the old vector, but
9853     // with each instance of FromLocOp replaced with ToLocOp.
9854     bool Changed = false;
9855     auto NewLocOps = Dbg->copyLocationOps();
9856     std::replace_if(
9857         NewLocOps.begin(), NewLocOps.end(),
9858         [&Changed, FromLocOp](const SDDbgOperand &Op) {
9859           bool Match = Op == FromLocOp;
9860           Changed |= Match;
9861           return Match;
9862         },
9863         ToLocOp);
9864     // Ignore this SDDbgValue if we didn't find a matching location.
9865     if (!Changed)
9866       continue;
9867 
9868     DIVariable *Var = Dbg->getVariable();
9869     auto *Expr = Dbg->getExpression();
9870     // If a fragment is requested, update the expression.
9871     if (SizeInBits) {
9872       // When splitting a larger (e.g., sign-extended) value whose
9873       // lower bits are described with an SDDbgValue, do not attempt
9874       // to transfer the SDDbgValue to the upper bits.
9875       if (auto FI = Expr->getFragmentInfo())
9876         if (OffsetInBits + SizeInBits > FI->SizeInBits)
9877           continue;
9878       auto Fragment = DIExpression::createFragmentExpression(Expr, OffsetInBits,
9879                                                              SizeInBits);
9880       if (!Fragment)
9881         continue;
9882       Expr = *Fragment;
9883     }
9884 
9885     auto AdditionalDependencies = Dbg->getAdditionalDependencies();
9886     // Clone the SDDbgValue and move it to To.
9887     SDDbgValue *Clone = getDbgValueList(
9888         Var, Expr, NewLocOps, AdditionalDependencies, Dbg->isIndirect(),
9889         Dbg->getDebugLoc(), std::max(ToNode->getIROrder(), Dbg->getOrder()),
9890         Dbg->isVariadic());
9891     ClonedDVs.push_back(Clone);
9892 
9893     if (InvalidateDbg) {
9894       // Invalidate value and indicate the SDDbgValue should not be emitted.
9895       Dbg->setIsInvalidated();
9896       Dbg->setIsEmitted();
9897     }
9898   }
9899 
9900   for (SDDbgValue *Dbg : ClonedDVs) {
9901     assert(is_contained(Dbg->getSDNodes(), ToNode) &&
9902            "Transferred DbgValues should depend on the new SDNode");
9903     AddDbgValue(Dbg, false);
9904   }
9905 }
9906 
9907 void SelectionDAG::salvageDebugInfo(SDNode &N) {
9908   if (!N.getHasDebugValue())
9909     return;
9910 
9911   SmallVector<SDDbgValue *, 2> ClonedDVs;
9912   for (auto DV : GetDbgValues(&N)) {
9913     if (DV->isInvalidated())
9914       continue;
9915     switch (N.getOpcode()) {
9916     default:
9917       break;
9918     case ISD::ADD:
9919       SDValue N0 = N.getOperand(0);
9920       SDValue N1 = N.getOperand(1);
9921       if (!isConstantIntBuildVectorOrConstantInt(N0) &&
9922           isConstantIntBuildVectorOrConstantInt(N1)) {
9923         uint64_t Offset = N.getConstantOperandVal(1);
9924 
9925         // Rewrite an ADD constant node into a DIExpression. Since we are
9926         // performing arithmetic to compute the variable's *value* in the
9927         // DIExpression, we need to mark the expression with a
9928         // DW_OP_stack_value.
9929         auto *DIExpr = DV->getExpression();
9930         auto NewLocOps = DV->copyLocationOps();
9931         bool Changed = false;
9932         for (size_t i = 0; i < NewLocOps.size(); ++i) {
9933           // We're not given a ResNo to compare against because the whole
9934           // node is going away. We know that any ISD::ADD only has one
9935           // result, so we can assume any node match is using the result.
9936           if (NewLocOps[i].getKind() != SDDbgOperand::SDNODE ||
9937               NewLocOps[i].getSDNode() != &N)
9938             continue;
9939           NewLocOps[i] = SDDbgOperand::fromNode(N0.getNode(), N0.getResNo());
9940           SmallVector<uint64_t, 3> ExprOps;
9941           DIExpression::appendOffset(ExprOps, Offset);
9942           DIExpr = DIExpression::appendOpsToArg(DIExpr, ExprOps, i, true);
9943           Changed = true;
9944         }
9945         (void)Changed;
9946         assert(Changed && "Salvage target doesn't use N");
9947 
9948         auto AdditionalDependencies = DV->getAdditionalDependencies();
9949         SDDbgValue *Clone = getDbgValueList(DV->getVariable(), DIExpr,
9950                                             NewLocOps, AdditionalDependencies,
9951                                             DV->isIndirect(), DV->getDebugLoc(),
9952                                             DV->getOrder(), DV->isVariadic());
9953         ClonedDVs.push_back(Clone);
9954         DV->setIsInvalidated();
9955         DV->setIsEmitted();
9956         LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting";
9957                    N0.getNode()->dumprFull(this);
9958                    dbgs() << " into " << *DIExpr << '\n');
9959       }
9960     }
9961   }
9962 
9963   for (SDDbgValue *Dbg : ClonedDVs) {
9964     assert(!Dbg->getSDNodes().empty() &&
9965            "Salvaged DbgValue should depend on a new SDNode");
9966     AddDbgValue(Dbg, false);
9967   }
9968 }
9969 
9970 /// Creates a SDDbgLabel node.
9971 SDDbgLabel *SelectionDAG::getDbgLabel(DILabel *Label,
9972                                       const DebugLoc &DL, unsigned O) {
9973   assert(cast<DILabel>(Label)->isValidLocationForIntrinsic(DL) &&
9974          "Expected inlined-at fields to agree");
9975   return new (DbgInfo->getAlloc()) SDDbgLabel(Label, DL, O);
9976 }
9977 
9978 namespace {
9979 
9980 /// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node
9981 /// pointed to by a use iterator is deleted, increment the use iterator
9982 /// so that it doesn't dangle.
9983 ///
9984 class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener {
9985   SDNode::use_iterator &UI;
9986   SDNode::use_iterator &UE;
9987 
9988   void NodeDeleted(SDNode *N, SDNode *E) override {
9989     // Increment the iterator as needed.
9990     while (UI != UE && N == *UI)
9991       ++UI;
9992   }
9993 
9994 public:
9995   RAUWUpdateListener(SelectionDAG &d,
9996                      SDNode::use_iterator &ui,
9997                      SDNode::use_iterator &ue)
9998     : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {}
9999 };
10000 
10001 } // end anonymous namespace
10002 
10003 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
10004 /// This can cause recursive merging of nodes in the DAG.
10005 ///
10006 /// This version assumes From has a single result value.
10007 ///
10008 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To) {
10009   SDNode *From = FromN.getNode();
10010   assert(From->getNumValues() == 1 && FromN.getResNo() == 0 &&
10011          "Cannot replace with this method!");
10012   assert(From != To.getNode() && "Cannot replace uses of with self");
10013 
10014   // Preserve Debug Values
10015   transferDbgValues(FromN, To);
10016 
10017   // Iterate over all the existing uses of From. New uses will be added
10018   // to the beginning of the use list, which we avoid visiting.
10019   // This specifically avoids visiting uses of From that arise while the
10020   // replacement is happening, because any such uses would be the result
10021   // of CSE: If an existing node looks like From after one of its operands
10022   // is replaced by To, we don't want to replace of all its users with To
10023   // too. See PR3018 for more info.
10024   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
10025   RAUWUpdateListener Listener(*this, UI, UE);
10026   while (UI != UE) {
10027     SDNode *User = *UI;
10028 
10029     // This node is about to morph, remove its old self from the CSE maps.
10030     RemoveNodeFromCSEMaps(User);
10031 
10032     // A user can appear in a use list multiple times, and when this
10033     // happens the uses are usually next to each other in the list.
10034     // To help reduce the number of CSE recomputations, process all
10035     // the uses of this user that we can find this way.
10036     do {
10037       SDUse &Use = UI.getUse();
10038       ++UI;
10039       Use.set(To);
10040       if (To->isDivergent() != From->isDivergent())
10041         updateDivergence(User);
10042     } while (UI != UE && *UI == User);
10043     // Now that we have modified User, add it back to the CSE maps.  If it
10044     // already exists there, recursively merge the results together.
10045     AddModifiedNodeToCSEMaps(User);
10046   }
10047 
10048   // If we just RAUW'd the root, take note.
10049   if (FromN == getRoot())
10050     setRoot(To);
10051 }
10052 
10053 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
10054 /// This can cause recursive merging of nodes in the DAG.
10055 ///
10056 /// This version assumes that for each value of From, there is a
10057 /// corresponding value in To in the same position with the same type.
10058 ///
10059 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To) {
10060 #ifndef NDEBUG
10061   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
10062     assert((!From->hasAnyUseOfValue(i) ||
10063             From->getValueType(i) == To->getValueType(i)) &&
10064            "Cannot use this version of ReplaceAllUsesWith!");
10065 #endif
10066 
10067   // Handle the trivial case.
10068   if (From == To)
10069     return;
10070 
10071   // Preserve Debug Info. Only do this if there's a use.
10072   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
10073     if (From->hasAnyUseOfValue(i)) {
10074       assert((i < To->getNumValues()) && "Invalid To location");
10075       transferDbgValues(SDValue(From, i), SDValue(To, i));
10076     }
10077 
10078   // Iterate over just the existing users of From. See the comments in
10079   // the ReplaceAllUsesWith above.
10080   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
10081   RAUWUpdateListener Listener(*this, UI, UE);
10082   while (UI != UE) {
10083     SDNode *User = *UI;
10084 
10085     // This node is about to morph, remove its old self from the CSE maps.
10086     RemoveNodeFromCSEMaps(User);
10087 
10088     // A user can appear in a use list multiple times, and when this
10089     // happens the uses are usually next to each other in the list.
10090     // To help reduce the number of CSE recomputations, process all
10091     // the uses of this user that we can find this way.
10092     do {
10093       SDUse &Use = UI.getUse();
10094       ++UI;
10095       Use.setNode(To);
10096       if (To->isDivergent() != From->isDivergent())
10097         updateDivergence(User);
10098     } while (UI != UE && *UI == User);
10099 
10100     // Now that we have modified User, add it back to the CSE maps.  If it
10101     // already exists there, recursively merge the results together.
10102     AddModifiedNodeToCSEMaps(User);
10103   }
10104 
10105   // If we just RAUW'd the root, take note.
10106   if (From == getRoot().getNode())
10107     setRoot(SDValue(To, getRoot().getResNo()));
10108 }
10109 
10110 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
10111 /// This can cause recursive merging of nodes in the DAG.
10112 ///
10113 /// This version can replace From with any result values.  To must match the
10114 /// number and types of values returned by From.
10115 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, const SDValue *To) {
10116   if (From->getNumValues() == 1)  // Handle the simple case efficiently.
10117     return ReplaceAllUsesWith(SDValue(From, 0), To[0]);
10118 
10119   // Preserve Debug Info.
10120   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
10121     transferDbgValues(SDValue(From, i), To[i]);
10122 
10123   // Iterate over just the existing users of From. See the comments in
10124   // the ReplaceAllUsesWith above.
10125   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
10126   RAUWUpdateListener Listener(*this, UI, UE);
10127   while (UI != UE) {
10128     SDNode *User = *UI;
10129 
10130     // This node is about to morph, remove its old self from the CSE maps.
10131     RemoveNodeFromCSEMaps(User);
10132 
10133     // A user can appear in a use list multiple times, and when this happens the
10134     // uses are usually next to each other in the list.  To help reduce the
10135     // number of CSE and divergence recomputations, process all the uses of this
10136     // user that we can find this way.
10137     bool To_IsDivergent = false;
10138     do {
10139       SDUse &Use = UI.getUse();
10140       const SDValue &ToOp = To[Use.getResNo()];
10141       ++UI;
10142       Use.set(ToOp);
10143       To_IsDivergent |= ToOp->isDivergent();
10144     } while (UI != UE && *UI == User);
10145 
10146     if (To_IsDivergent != From->isDivergent())
10147       updateDivergence(User);
10148 
10149     // Now that we have modified User, add it back to the CSE maps.  If it
10150     // already exists there, recursively merge the results together.
10151     AddModifiedNodeToCSEMaps(User);
10152   }
10153 
10154   // If we just RAUW'd the root, take note.
10155   if (From == getRoot().getNode())
10156     setRoot(SDValue(To[getRoot().getResNo()]));
10157 }
10158 
10159 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
10160 /// uses of other values produced by From.getNode() alone.  The Deleted
10161 /// vector is handled the same way as for ReplaceAllUsesWith.
10162 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To){
10163   // Handle the really simple, really trivial case efficiently.
10164   if (From == To) return;
10165 
10166   // Handle the simple, trivial, case efficiently.
10167   if (From.getNode()->getNumValues() == 1) {
10168     ReplaceAllUsesWith(From, To);
10169     return;
10170   }
10171 
10172   // Preserve Debug Info.
10173   transferDbgValues(From, To);
10174 
10175   // Iterate over just the existing users of From. See the comments in
10176   // the ReplaceAllUsesWith above.
10177   SDNode::use_iterator UI = From.getNode()->use_begin(),
10178                        UE = From.getNode()->use_end();
10179   RAUWUpdateListener Listener(*this, UI, UE);
10180   while (UI != UE) {
10181     SDNode *User = *UI;
10182     bool UserRemovedFromCSEMaps = false;
10183 
10184     // A user can appear in a use list multiple times, and when this
10185     // happens the uses are usually next to each other in the list.
10186     // To help reduce the number of CSE recomputations, process all
10187     // the uses of this user that we can find this way.
10188     do {
10189       SDUse &Use = UI.getUse();
10190 
10191       // Skip uses of different values from the same node.
10192       if (Use.getResNo() != From.getResNo()) {
10193         ++UI;
10194         continue;
10195       }
10196 
10197       // If this node hasn't been modified yet, it's still in the CSE maps,
10198       // so remove its old self from the CSE maps.
10199       if (!UserRemovedFromCSEMaps) {
10200         RemoveNodeFromCSEMaps(User);
10201         UserRemovedFromCSEMaps = true;
10202       }
10203 
10204       ++UI;
10205       Use.set(To);
10206       if (To->isDivergent() != From->isDivergent())
10207         updateDivergence(User);
10208     } while (UI != UE && *UI == User);
10209     // We are iterating over all uses of the From node, so if a use
10210     // doesn't use the specific value, no changes are made.
10211     if (!UserRemovedFromCSEMaps)
10212       continue;
10213 
10214     // Now that we have modified User, add it back to the CSE maps.  If it
10215     // already exists there, recursively merge the results together.
10216     AddModifiedNodeToCSEMaps(User);
10217   }
10218 
10219   // If we just RAUW'd the root, take note.
10220   if (From == getRoot())
10221     setRoot(To);
10222 }
10223 
10224 namespace {
10225 
10226 /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith
10227 /// to record information about a use.
10228 struct UseMemo {
10229   SDNode *User;
10230   unsigned Index;
10231   SDUse *Use;
10232 };
10233 
10234 /// operator< - Sort Memos by User.
10235 bool operator<(const UseMemo &L, const UseMemo &R) {
10236   return (intptr_t)L.User < (intptr_t)R.User;
10237 }
10238 
10239 /// RAUOVWUpdateListener - Helper for ReplaceAllUsesOfValuesWith - When the node
10240 /// pointed to by a UseMemo is deleted, set the User to nullptr to indicate that
10241 /// the node already has been taken care of recursively.
10242 class RAUOVWUpdateListener : public SelectionDAG::DAGUpdateListener {
10243   SmallVector<UseMemo, 4> &Uses;
10244 
10245   void NodeDeleted(SDNode *N, SDNode *E) override {
10246     for (UseMemo &Memo : Uses)
10247       if (Memo.User == N)
10248         Memo.User = nullptr;
10249   }
10250 
10251 public:
10252   RAUOVWUpdateListener(SelectionDAG &d, SmallVector<UseMemo, 4> &uses)
10253       : SelectionDAG::DAGUpdateListener(d), Uses(uses) {}
10254 };
10255 
10256 } // end anonymous namespace
10257 
10258 bool SelectionDAG::calculateDivergence(SDNode *N) {
10259   if (TLI->isSDNodeAlwaysUniform(N)) {
10260     assert(!TLI->isSDNodeSourceOfDivergence(N, FLI, DA) &&
10261            "Conflicting divergence information!");
10262     return false;
10263   }
10264   if (TLI->isSDNodeSourceOfDivergence(N, FLI, DA))
10265     return true;
10266   for (auto &Op : N->ops()) {
10267     if (Op.Val.getValueType() != MVT::Other && Op.getNode()->isDivergent())
10268       return true;
10269   }
10270   return false;
10271 }
10272 
10273 void SelectionDAG::updateDivergence(SDNode *N) {
10274   SmallVector<SDNode *, 16> Worklist(1, N);
10275   do {
10276     N = Worklist.pop_back_val();
10277     bool IsDivergent = calculateDivergence(N);
10278     if (N->SDNodeBits.IsDivergent != IsDivergent) {
10279       N->SDNodeBits.IsDivergent = IsDivergent;
10280       llvm::append_range(Worklist, N->uses());
10281     }
10282   } while (!Worklist.empty());
10283 }
10284 
10285 void SelectionDAG::CreateTopologicalOrder(std::vector<SDNode *> &Order) {
10286   DenseMap<SDNode *, unsigned> Degree;
10287   Order.reserve(AllNodes.size());
10288   for (auto &N : allnodes()) {
10289     unsigned NOps = N.getNumOperands();
10290     Degree[&N] = NOps;
10291     if (0 == NOps)
10292       Order.push_back(&N);
10293   }
10294   for (size_t I = 0; I != Order.size(); ++I) {
10295     SDNode *N = Order[I];
10296     for (auto U : N->uses()) {
10297       unsigned &UnsortedOps = Degree[U];
10298       if (0 == --UnsortedOps)
10299         Order.push_back(U);
10300     }
10301   }
10302 }
10303 
10304 #ifndef NDEBUG
10305 void SelectionDAG::VerifyDAGDivergence() {
10306   std::vector<SDNode *> TopoOrder;
10307   CreateTopologicalOrder(TopoOrder);
10308   for (auto *N : TopoOrder) {
10309     assert(calculateDivergence(N) == N->isDivergent() &&
10310            "Divergence bit inconsistency detected");
10311   }
10312 }
10313 #endif
10314 
10315 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving
10316 /// uses of other values produced by From.getNode() alone.  The same value
10317 /// may appear in both the From and To list.  The Deleted vector is
10318 /// handled the same way as for ReplaceAllUsesWith.
10319 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From,
10320                                               const SDValue *To,
10321                                               unsigned Num){
10322   // Handle the simple, trivial case efficiently.
10323   if (Num == 1)
10324     return ReplaceAllUsesOfValueWith(*From, *To);
10325 
10326   transferDbgValues(*From, *To);
10327 
10328   // Read up all the uses and make records of them. This helps
10329   // processing new uses that are introduced during the
10330   // replacement process.
10331   SmallVector<UseMemo, 4> Uses;
10332   for (unsigned i = 0; i != Num; ++i) {
10333     unsigned FromResNo = From[i].getResNo();
10334     SDNode *FromNode = From[i].getNode();
10335     for (SDNode::use_iterator UI = FromNode->use_begin(),
10336          E = FromNode->use_end(); UI != E; ++UI) {
10337       SDUse &Use = UI.getUse();
10338       if (Use.getResNo() == FromResNo) {
10339         UseMemo Memo = { *UI, i, &Use };
10340         Uses.push_back(Memo);
10341       }
10342     }
10343   }
10344 
10345   // Sort the uses, so that all the uses from a given User are together.
10346   llvm::sort(Uses);
10347   RAUOVWUpdateListener Listener(*this, Uses);
10348 
10349   for (unsigned UseIndex = 0, UseIndexEnd = Uses.size();
10350        UseIndex != UseIndexEnd; ) {
10351     // We know that this user uses some value of From.  If it is the right
10352     // value, update it.
10353     SDNode *User = Uses[UseIndex].User;
10354     // If the node has been deleted by recursive CSE updates when updating
10355     // another node, then just skip this entry.
10356     if (User == nullptr) {
10357       ++UseIndex;
10358       continue;
10359     }
10360 
10361     // This node is about to morph, remove its old self from the CSE maps.
10362     RemoveNodeFromCSEMaps(User);
10363 
10364     // The Uses array is sorted, so all the uses for a given User
10365     // are next to each other in the list.
10366     // To help reduce the number of CSE recomputations, process all
10367     // the uses of this user that we can find this way.
10368     do {
10369       unsigned i = Uses[UseIndex].Index;
10370       SDUse &Use = *Uses[UseIndex].Use;
10371       ++UseIndex;
10372 
10373       Use.set(To[i]);
10374     } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User);
10375 
10376     // Now that we have modified User, add it back to the CSE maps.  If it
10377     // already exists there, recursively merge the results together.
10378     AddModifiedNodeToCSEMaps(User);
10379   }
10380 }
10381 
10382 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
10383 /// based on their topological order. It returns the maximum id and a vector
10384 /// of the SDNodes* in assigned order by reference.
10385 unsigned SelectionDAG::AssignTopologicalOrder() {
10386   unsigned DAGSize = 0;
10387 
10388   // SortedPos tracks the progress of the algorithm. Nodes before it are
10389   // sorted, nodes after it are unsorted. When the algorithm completes
10390   // it is at the end of the list.
10391   allnodes_iterator SortedPos = allnodes_begin();
10392 
10393   // Visit all the nodes. Move nodes with no operands to the front of
10394   // the list immediately. Annotate nodes that do have operands with their
10395   // operand count. Before we do this, the Node Id fields of the nodes
10396   // may contain arbitrary values. After, the Node Id fields for nodes
10397   // before SortedPos will contain the topological sort index, and the
10398   // Node Id fields for nodes At SortedPos and after will contain the
10399   // count of outstanding operands.
10400   for (SDNode &N : llvm::make_early_inc_range(allnodes())) {
10401     checkForCycles(&N, this);
10402     unsigned Degree = N.getNumOperands();
10403     if (Degree == 0) {
10404       // A node with no uses, add it to the result array immediately.
10405       N.setNodeId(DAGSize++);
10406       allnodes_iterator Q(&N);
10407       if (Q != SortedPos)
10408         SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q));
10409       assert(SortedPos != AllNodes.end() && "Overran node list");
10410       ++SortedPos;
10411     } else {
10412       // Temporarily use the Node Id as scratch space for the degree count.
10413       N.setNodeId(Degree);
10414     }
10415   }
10416 
10417   // Visit all the nodes. As we iterate, move nodes into sorted order,
10418   // such that by the time the end is reached all nodes will be sorted.
10419   for (SDNode &Node : allnodes()) {
10420     SDNode *N = &Node;
10421     checkForCycles(N, this);
10422     // N is in sorted position, so all its uses have one less operand
10423     // that needs to be sorted.
10424     for (SDNode *P : N->uses()) {
10425       unsigned Degree = P->getNodeId();
10426       assert(Degree != 0 && "Invalid node degree");
10427       --Degree;
10428       if (Degree == 0) {
10429         // All of P's operands are sorted, so P may sorted now.
10430         P->setNodeId(DAGSize++);
10431         if (P->getIterator() != SortedPos)
10432           SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P));
10433         assert(SortedPos != AllNodes.end() && "Overran node list");
10434         ++SortedPos;
10435       } else {
10436         // Update P's outstanding operand count.
10437         P->setNodeId(Degree);
10438       }
10439     }
10440     if (Node.getIterator() == SortedPos) {
10441 #ifndef NDEBUG
10442       allnodes_iterator I(N);
10443       SDNode *S = &*++I;
10444       dbgs() << "Overran sorted position:\n";
10445       S->dumprFull(this); dbgs() << "\n";
10446       dbgs() << "Checking if this is due to cycles\n";
10447       checkForCycles(this, true);
10448 #endif
10449       llvm_unreachable(nullptr);
10450     }
10451   }
10452 
10453   assert(SortedPos == AllNodes.end() &&
10454          "Topological sort incomplete!");
10455   assert(AllNodes.front().getOpcode() == ISD::EntryToken &&
10456          "First node in topological sort is not the entry token!");
10457   assert(AllNodes.front().getNodeId() == 0 &&
10458          "First node in topological sort has non-zero id!");
10459   assert(AllNodes.front().getNumOperands() == 0 &&
10460          "First node in topological sort has operands!");
10461   assert(AllNodes.back().getNodeId() == (int)DAGSize-1 &&
10462          "Last node in topologic sort has unexpected id!");
10463   assert(AllNodes.back().use_empty() &&
10464          "Last node in topologic sort has users!");
10465   assert(DAGSize == allnodes_size() && "Node count mismatch!");
10466   return DAGSize;
10467 }
10468 
10469 /// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the
10470 /// value is produced by SD.
10471 void SelectionDAG::AddDbgValue(SDDbgValue *DB, bool isParameter) {
10472   for (SDNode *SD : DB->getSDNodes()) {
10473     if (!SD)
10474       continue;
10475     assert(DbgInfo->getSDDbgValues(SD).empty() || SD->getHasDebugValue());
10476     SD->setHasDebugValue(true);
10477   }
10478   DbgInfo->add(DB, isParameter);
10479 }
10480 
10481 void SelectionDAG::AddDbgLabel(SDDbgLabel *DB) { DbgInfo->add(DB); }
10482 
10483 SDValue SelectionDAG::makeEquivalentMemoryOrdering(SDValue OldChain,
10484                                                    SDValue NewMemOpChain) {
10485   assert(isa<MemSDNode>(NewMemOpChain) && "Expected a memop node");
10486   assert(NewMemOpChain.getValueType() == MVT::Other && "Expected a token VT");
10487   // The new memory operation must have the same position as the old load in
10488   // terms of memory dependency. Create a TokenFactor for the old load and new
10489   // memory operation and update uses of the old load's output chain to use that
10490   // TokenFactor.
10491   if (OldChain == NewMemOpChain || OldChain.use_empty())
10492     return NewMemOpChain;
10493 
10494   SDValue TokenFactor = getNode(ISD::TokenFactor, SDLoc(OldChain), MVT::Other,
10495                                 OldChain, NewMemOpChain);
10496   ReplaceAllUsesOfValueWith(OldChain, TokenFactor);
10497   UpdateNodeOperands(TokenFactor.getNode(), OldChain, NewMemOpChain);
10498   return TokenFactor;
10499 }
10500 
10501 SDValue SelectionDAG::makeEquivalentMemoryOrdering(LoadSDNode *OldLoad,
10502                                                    SDValue NewMemOp) {
10503   assert(isa<MemSDNode>(NewMemOp.getNode()) && "Expected a memop node");
10504   SDValue OldChain = SDValue(OldLoad, 1);
10505   SDValue NewMemOpChain = NewMemOp.getValue(1);
10506   return makeEquivalentMemoryOrdering(OldChain, NewMemOpChain);
10507 }
10508 
10509 SDValue SelectionDAG::getSymbolFunctionGlobalAddress(SDValue Op,
10510                                                      Function **OutFunction) {
10511   assert(isa<ExternalSymbolSDNode>(Op) && "Node should be an ExternalSymbol");
10512 
10513   auto *Symbol = cast<ExternalSymbolSDNode>(Op)->getSymbol();
10514   auto *Module = MF->getFunction().getParent();
10515   auto *Function = Module->getFunction(Symbol);
10516 
10517   if (OutFunction != nullptr)
10518       *OutFunction = Function;
10519 
10520   if (Function != nullptr) {
10521     auto PtrTy = TLI->getPointerTy(getDataLayout(), Function->getAddressSpace());
10522     return getGlobalAddress(Function, SDLoc(Op), PtrTy);
10523   }
10524 
10525   std::string ErrorStr;
10526   raw_string_ostream ErrorFormatter(ErrorStr);
10527   ErrorFormatter << "Undefined external symbol ";
10528   ErrorFormatter << '"' << Symbol << '"';
10529   report_fatal_error(Twine(ErrorFormatter.str()));
10530 }
10531 
10532 //===----------------------------------------------------------------------===//
10533 //                              SDNode Class
10534 //===----------------------------------------------------------------------===//
10535 
10536 bool llvm::isNullConstant(SDValue V) {
10537   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
10538   return Const != nullptr && Const->isZero();
10539 }
10540 
10541 bool llvm::isNullFPConstant(SDValue V) {
10542   ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V);
10543   return Const != nullptr && Const->isZero() && !Const->isNegative();
10544 }
10545 
10546 bool llvm::isAllOnesConstant(SDValue V) {
10547   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
10548   return Const != nullptr && Const->isAllOnes();
10549 }
10550 
10551 bool llvm::isOneConstant(SDValue V) {
10552   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
10553   return Const != nullptr && Const->isOne();
10554 }
10555 
10556 bool llvm::isMinSignedConstant(SDValue V) {
10557   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
10558   return Const != nullptr && Const->isMinSignedValue();
10559 }
10560 
10561 SDValue llvm::peekThroughBitcasts(SDValue V) {
10562   while (V.getOpcode() == ISD::BITCAST)
10563     V = V.getOperand(0);
10564   return V;
10565 }
10566 
10567 SDValue llvm::peekThroughOneUseBitcasts(SDValue V) {
10568   while (V.getOpcode() == ISD::BITCAST && V.getOperand(0).hasOneUse())
10569     V = V.getOperand(0);
10570   return V;
10571 }
10572 
10573 SDValue llvm::peekThroughExtractSubvectors(SDValue V) {
10574   while (V.getOpcode() == ISD::EXTRACT_SUBVECTOR)
10575     V = V.getOperand(0);
10576   return V;
10577 }
10578 
10579 bool llvm::isBitwiseNot(SDValue V, bool AllowUndefs) {
10580   if (V.getOpcode() != ISD::XOR)
10581     return false;
10582   V = peekThroughBitcasts(V.getOperand(1));
10583   unsigned NumBits = V.getScalarValueSizeInBits();
10584   ConstantSDNode *C =
10585       isConstOrConstSplat(V, AllowUndefs, /*AllowTruncation*/ true);
10586   return C && (C->getAPIntValue().countTrailingOnes() >= NumBits);
10587 }
10588 
10589 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, bool AllowUndefs,
10590                                           bool AllowTruncation) {
10591   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
10592     return CN;
10593 
10594   // SplatVectors can truncate their operands. Ignore that case here unless
10595   // AllowTruncation is set.
10596   if (N->getOpcode() == ISD::SPLAT_VECTOR) {
10597     EVT VecEltVT = N->getValueType(0).getVectorElementType();
10598     if (auto *CN = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
10599       EVT CVT = CN->getValueType(0);
10600       assert(CVT.bitsGE(VecEltVT) && "Illegal splat_vector element extension");
10601       if (AllowTruncation || CVT == VecEltVT)
10602         return CN;
10603     }
10604   }
10605 
10606   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
10607     BitVector UndefElements;
10608     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
10609 
10610     // BuildVectors can truncate their operands. Ignore that case here unless
10611     // AllowTruncation is set.
10612     if (CN && (UndefElements.none() || AllowUndefs)) {
10613       EVT CVT = CN->getValueType(0);
10614       EVT NSVT = N.getValueType().getScalarType();
10615       assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension");
10616       if (AllowTruncation || (CVT == NSVT))
10617         return CN;
10618     }
10619   }
10620 
10621   return nullptr;
10622 }
10623 
10624 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, const APInt &DemandedElts,
10625                                           bool AllowUndefs,
10626                                           bool AllowTruncation) {
10627   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
10628     return CN;
10629 
10630   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
10631     BitVector UndefElements;
10632     ConstantSDNode *CN = BV->getConstantSplatNode(DemandedElts, &UndefElements);
10633 
10634     // BuildVectors can truncate their operands. Ignore that case here unless
10635     // AllowTruncation is set.
10636     if (CN && (UndefElements.none() || AllowUndefs)) {
10637       EVT CVT = CN->getValueType(0);
10638       EVT NSVT = N.getValueType().getScalarType();
10639       assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension");
10640       if (AllowTruncation || (CVT == NSVT))
10641         return CN;
10642     }
10643   }
10644 
10645   return nullptr;
10646 }
10647 
10648 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N, bool AllowUndefs) {
10649   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
10650     return CN;
10651 
10652   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
10653     BitVector UndefElements;
10654     ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
10655     if (CN && (UndefElements.none() || AllowUndefs))
10656       return CN;
10657   }
10658 
10659   if (N.getOpcode() == ISD::SPLAT_VECTOR)
10660     if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N.getOperand(0)))
10661       return CN;
10662 
10663   return nullptr;
10664 }
10665 
10666 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N,
10667                                               const APInt &DemandedElts,
10668                                               bool AllowUndefs) {
10669   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
10670     return CN;
10671 
10672   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
10673     BitVector UndefElements;
10674     ConstantFPSDNode *CN =
10675         BV->getConstantFPSplatNode(DemandedElts, &UndefElements);
10676     if (CN && (UndefElements.none() || AllowUndefs))
10677       return CN;
10678   }
10679 
10680   return nullptr;
10681 }
10682 
10683 bool llvm::isNullOrNullSplat(SDValue N, bool AllowUndefs) {
10684   // TODO: may want to use peekThroughBitcast() here.
10685   ConstantSDNode *C =
10686       isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation=*/true);
10687   return C && C->isZero();
10688 }
10689 
10690 bool llvm::isOneOrOneSplat(SDValue N, bool AllowUndefs) {
10691   ConstantSDNode *C =
10692       isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation*/ true);
10693   return C && C->isOne();
10694 }
10695 
10696 bool llvm::isAllOnesOrAllOnesSplat(SDValue N, bool AllowUndefs) {
10697   N = peekThroughBitcasts(N);
10698   unsigned BitWidth = N.getScalarValueSizeInBits();
10699   ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs);
10700   return C && C->isAllOnes() && C->getValueSizeInBits(0) == BitWidth;
10701 }
10702 
10703 HandleSDNode::~HandleSDNode() {
10704   DropOperands();
10705 }
10706 
10707 GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, unsigned Order,
10708                                          const DebugLoc &DL,
10709                                          const GlobalValue *GA, EVT VT,
10710                                          int64_t o, unsigned TF)
10711     : SDNode(Opc, Order, DL, getSDVTList(VT)), Offset(o), TargetFlags(TF) {
10712   TheGlobal = GA;
10713 }
10714 
10715 AddrSpaceCastSDNode::AddrSpaceCastSDNode(unsigned Order, const DebugLoc &dl,
10716                                          EVT VT, unsigned SrcAS,
10717                                          unsigned DestAS)
10718     : SDNode(ISD::ADDRSPACECAST, Order, dl, getSDVTList(VT)),
10719       SrcAddrSpace(SrcAS), DestAddrSpace(DestAS) {}
10720 
10721 MemSDNode::MemSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl,
10722                      SDVTList VTs, EVT memvt, MachineMemOperand *mmo)
10723     : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MMO(mmo) {
10724   MemSDNodeBits.IsVolatile = MMO->isVolatile();
10725   MemSDNodeBits.IsNonTemporal = MMO->isNonTemporal();
10726   MemSDNodeBits.IsDereferenceable = MMO->isDereferenceable();
10727   MemSDNodeBits.IsInvariant = MMO->isInvariant();
10728 
10729   // We check here that the size of the memory operand fits within the size of
10730   // the MMO. This is because the MMO might indicate only a possible address
10731   // range instead of specifying the affected memory addresses precisely.
10732   // TODO: Make MachineMemOperands aware of scalable vectors.
10733   assert(memvt.getStoreSize().getKnownMinSize() <= MMO->getSize() &&
10734          "Size mismatch!");
10735 }
10736 
10737 /// Profile - Gather unique data for the node.
10738 ///
10739 void SDNode::Profile(FoldingSetNodeID &ID) const {
10740   AddNodeIDNode(ID, this);
10741 }
10742 
10743 namespace {
10744 
10745   struct EVTArray {
10746     std::vector<EVT> VTs;
10747 
10748     EVTArray() {
10749       VTs.reserve(MVT::VALUETYPE_SIZE);
10750       for (unsigned i = 0; i < MVT::VALUETYPE_SIZE; ++i)
10751         VTs.push_back(MVT((MVT::SimpleValueType)i));
10752     }
10753   };
10754 
10755 } // end anonymous namespace
10756 
10757 static ManagedStatic<std::set<EVT, EVT::compareRawBits>> EVTs;
10758 static ManagedStatic<EVTArray> SimpleVTArray;
10759 static ManagedStatic<sys::SmartMutex<true>> VTMutex;
10760 
10761 /// getValueTypeList - Return a pointer to the specified value type.
10762 ///
10763 const EVT *SDNode::getValueTypeList(EVT VT) {
10764   if (VT.isExtended()) {
10765     sys::SmartScopedLock<true> Lock(*VTMutex);
10766     return &(*EVTs->insert(VT).first);
10767   }
10768   assert(VT.getSimpleVT() < MVT::VALUETYPE_SIZE && "Value type out of range!");
10769   return &SimpleVTArray->VTs[VT.getSimpleVT().SimpleTy];
10770 }
10771 
10772 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
10773 /// indicated value.  This method ignores uses of other values defined by this
10774 /// operation.
10775 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
10776   assert(Value < getNumValues() && "Bad value!");
10777 
10778   // TODO: Only iterate over uses of a given value of the node
10779   for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
10780     if (UI.getUse().getResNo() == Value) {
10781       if (NUses == 0)
10782         return false;
10783       --NUses;
10784     }
10785   }
10786 
10787   // Found exactly the right number of uses?
10788   return NUses == 0;
10789 }
10790 
10791 /// hasAnyUseOfValue - Return true if there are any use of the indicated
10792 /// value. This method ignores uses of other values defined by this operation.
10793 bool SDNode::hasAnyUseOfValue(unsigned Value) const {
10794   assert(Value < getNumValues() && "Bad value!");
10795 
10796   for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI)
10797     if (UI.getUse().getResNo() == Value)
10798       return true;
10799 
10800   return false;
10801 }
10802 
10803 /// isOnlyUserOf - Return true if this node is the only use of N.
10804 bool SDNode::isOnlyUserOf(const SDNode *N) const {
10805   bool Seen = false;
10806   for (const SDNode *User : N->uses()) {
10807     if (User == this)
10808       Seen = true;
10809     else
10810       return false;
10811   }
10812 
10813   return Seen;
10814 }
10815 
10816 /// Return true if the only users of N are contained in Nodes.
10817 bool SDNode::areOnlyUsersOf(ArrayRef<const SDNode *> Nodes, const SDNode *N) {
10818   bool Seen = false;
10819   for (const SDNode *User : N->uses()) {
10820     if (llvm::is_contained(Nodes, User))
10821       Seen = true;
10822     else
10823       return false;
10824   }
10825 
10826   return Seen;
10827 }
10828 
10829 /// isOperand - Return true if this node is an operand of N.
10830 bool SDValue::isOperandOf(const SDNode *N) const {
10831   return is_contained(N->op_values(), *this);
10832 }
10833 
10834 bool SDNode::isOperandOf(const SDNode *N) const {
10835   return any_of(N->op_values(),
10836                 [this](SDValue Op) { return this == Op.getNode(); });
10837 }
10838 
10839 /// reachesChainWithoutSideEffects - Return true if this operand (which must
10840 /// be a chain) reaches the specified operand without crossing any
10841 /// side-effecting instructions on any chain path.  In practice, this looks
10842 /// through token factors and non-volatile loads.  In order to remain efficient,
10843 /// this only looks a couple of nodes in, it does not do an exhaustive search.
10844 ///
10845 /// Note that we only need to examine chains when we're searching for
10846 /// side-effects; SelectionDAG requires that all side-effects are represented
10847 /// by chains, even if another operand would force a specific ordering. This
10848 /// constraint is necessary to allow transformations like splitting loads.
10849 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest,
10850                                              unsigned Depth) const {
10851   if (*this == Dest) return true;
10852 
10853   // Don't search too deeply, we just want to be able to see through
10854   // TokenFactor's etc.
10855   if (Depth == 0) return false;
10856 
10857   // If this is a token factor, all inputs to the TF happen in parallel.
10858   if (getOpcode() == ISD::TokenFactor) {
10859     // First, try a shallow search.
10860     if (is_contained((*this)->ops(), Dest)) {
10861       // We found the chain we want as an operand of this TokenFactor.
10862       // Essentially, we reach the chain without side-effects if we could
10863       // serialize the TokenFactor into a simple chain of operations with
10864       // Dest as the last operation. This is automatically true if the
10865       // chain has one use: there are no other ordering constraints.
10866       // If the chain has more than one use, we give up: some other
10867       // use of Dest might force a side-effect between Dest and the current
10868       // node.
10869       if (Dest.hasOneUse())
10870         return true;
10871     }
10872     // Next, try a deep search: check whether every operand of the TokenFactor
10873     // reaches Dest.
10874     return llvm::all_of((*this)->ops(), [=](SDValue Op) {
10875       return Op.reachesChainWithoutSideEffects(Dest, Depth - 1);
10876     });
10877   }
10878 
10879   // Loads don't have side effects, look through them.
10880   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
10881     if (Ld->isUnordered())
10882       return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
10883   }
10884   return false;
10885 }
10886 
10887 bool SDNode::hasPredecessor(const SDNode *N) const {
10888   SmallPtrSet<const SDNode *, 32> Visited;
10889   SmallVector<const SDNode *, 16> Worklist;
10890   Worklist.push_back(this);
10891   return hasPredecessorHelper(N, Visited, Worklist);
10892 }
10893 
10894 void SDNode::intersectFlagsWith(const SDNodeFlags Flags) {
10895   this->Flags.intersectWith(Flags);
10896 }
10897 
10898 SDValue
10899 SelectionDAG::matchBinOpReduction(SDNode *Extract, ISD::NodeType &BinOp,
10900                                   ArrayRef<ISD::NodeType> CandidateBinOps,
10901                                   bool AllowPartials) {
10902   // The pattern must end in an extract from index 0.
10903   if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10904       !isNullConstant(Extract->getOperand(1)))
10905     return SDValue();
10906 
10907   // Match against one of the candidate binary ops.
10908   SDValue Op = Extract->getOperand(0);
10909   if (llvm::none_of(CandidateBinOps, [Op](ISD::NodeType BinOp) {
10910         return Op.getOpcode() == unsigned(BinOp);
10911       }))
10912     return SDValue();
10913 
10914   // Floating-point reductions may require relaxed constraints on the final step
10915   // of the reduction because they may reorder intermediate operations.
10916   unsigned CandidateBinOp = Op.getOpcode();
10917   if (Op.getValueType().isFloatingPoint()) {
10918     SDNodeFlags Flags = Op->getFlags();
10919     switch (CandidateBinOp) {
10920     case ISD::FADD:
10921       if (!Flags.hasNoSignedZeros() || !Flags.hasAllowReassociation())
10922         return SDValue();
10923       break;
10924     default:
10925       llvm_unreachable("Unhandled FP opcode for binop reduction");
10926     }
10927   }
10928 
10929   // Matching failed - attempt to see if we did enough stages that a partial
10930   // reduction from a subvector is possible.
10931   auto PartialReduction = [&](SDValue Op, unsigned NumSubElts) {
10932     if (!AllowPartials || !Op)
10933       return SDValue();
10934     EVT OpVT = Op.getValueType();
10935     EVT OpSVT = OpVT.getScalarType();
10936     EVT SubVT = EVT::getVectorVT(*getContext(), OpSVT, NumSubElts);
10937     if (!TLI->isExtractSubvectorCheap(SubVT, OpVT, 0))
10938       return SDValue();
10939     BinOp = (ISD::NodeType)CandidateBinOp;
10940     return getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(Op), SubVT, Op,
10941                    getVectorIdxConstant(0, SDLoc(Op)));
10942   };
10943 
10944   // At each stage, we're looking for something that looks like:
10945   // %s = shufflevector <8 x i32> %op, <8 x i32> undef,
10946   //                    <8 x i32> <i32 2, i32 3, i32 undef, i32 undef,
10947   //                               i32 undef, i32 undef, i32 undef, i32 undef>
10948   // %a = binop <8 x i32> %op, %s
10949   // Where the mask changes according to the stage. E.g. for a 3-stage pyramid,
10950   // we expect something like:
10951   // <4,5,6,7,u,u,u,u>
10952   // <2,3,u,u,u,u,u,u>
10953   // <1,u,u,u,u,u,u,u>
10954   // While a partial reduction match would be:
10955   // <2,3,u,u,u,u,u,u>
10956   // <1,u,u,u,u,u,u,u>
10957   unsigned Stages = Log2_32(Op.getValueType().getVectorNumElements());
10958   SDValue PrevOp;
10959   for (unsigned i = 0; i < Stages; ++i) {
10960     unsigned MaskEnd = (1 << i);
10961 
10962     if (Op.getOpcode() != CandidateBinOp)
10963       return PartialReduction(PrevOp, MaskEnd);
10964 
10965     SDValue Op0 = Op.getOperand(0);
10966     SDValue Op1 = Op.getOperand(1);
10967 
10968     ShuffleVectorSDNode *Shuffle = dyn_cast<ShuffleVectorSDNode>(Op0);
10969     if (Shuffle) {
10970       Op = Op1;
10971     } else {
10972       Shuffle = dyn_cast<ShuffleVectorSDNode>(Op1);
10973       Op = Op0;
10974     }
10975 
10976     // The first operand of the shuffle should be the same as the other operand
10977     // of the binop.
10978     if (!Shuffle || Shuffle->getOperand(0) != Op)
10979       return PartialReduction(PrevOp, MaskEnd);
10980 
10981     // Verify the shuffle has the expected (at this stage of the pyramid) mask.
10982     for (int Index = 0; Index < (int)MaskEnd; ++Index)
10983       if (Shuffle->getMaskElt(Index) != (int)(MaskEnd + Index))
10984         return PartialReduction(PrevOp, MaskEnd);
10985 
10986     PrevOp = Op;
10987   }
10988 
10989   // Handle subvector reductions, which tend to appear after the shuffle
10990   // reduction stages.
10991   while (Op.getOpcode() == CandidateBinOp) {
10992     unsigned NumElts = Op.getValueType().getVectorNumElements();
10993     SDValue Op0 = Op.getOperand(0);
10994     SDValue Op1 = Op.getOperand(1);
10995     if (Op0.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
10996         Op1.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
10997         Op0.getOperand(0) != Op1.getOperand(0))
10998       break;
10999     SDValue Src = Op0.getOperand(0);
11000     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
11001     if (NumSrcElts != (2 * NumElts))
11002       break;
11003     if (!(Op0.getConstantOperandAPInt(1) == 0 &&
11004           Op1.getConstantOperandAPInt(1) == NumElts) &&
11005         !(Op1.getConstantOperandAPInt(1) == 0 &&
11006           Op0.getConstantOperandAPInt(1) == NumElts))
11007       break;
11008     Op = Src;
11009   }
11010 
11011   BinOp = (ISD::NodeType)CandidateBinOp;
11012   return Op;
11013 }
11014 
11015 SDValue SelectionDAG::UnrollVectorOp(SDNode *N, unsigned ResNE) {
11016   assert(N->getNumValues() == 1 &&
11017          "Can't unroll a vector with multiple results!");
11018 
11019   EVT VT = N->getValueType(0);
11020   unsigned NE = VT.getVectorNumElements();
11021   EVT EltVT = VT.getVectorElementType();
11022   SDLoc dl(N);
11023 
11024   SmallVector<SDValue, 8> Scalars;
11025   SmallVector<SDValue, 4> Operands(N->getNumOperands());
11026 
11027   // If ResNE is 0, fully unroll the vector op.
11028   if (ResNE == 0)
11029     ResNE = NE;
11030   else if (NE > ResNE)
11031     NE = ResNE;
11032 
11033   unsigned i;
11034   for (i= 0; i != NE; ++i) {
11035     for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) {
11036       SDValue Operand = N->getOperand(j);
11037       EVT OperandVT = Operand.getValueType();
11038       if (OperandVT.isVector()) {
11039         // A vector operand; extract a single element.
11040         EVT OperandEltVT = OperandVT.getVectorElementType();
11041         Operands[j] = getNode(ISD::EXTRACT_VECTOR_ELT, dl, OperandEltVT,
11042                               Operand, getVectorIdxConstant(i, dl));
11043       } else {
11044         // A scalar operand; just use it as is.
11045         Operands[j] = Operand;
11046       }
11047     }
11048 
11049     switch (N->getOpcode()) {
11050     default: {
11051       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands,
11052                                 N->getFlags()));
11053       break;
11054     }
11055     case ISD::VSELECT:
11056       Scalars.push_back(getNode(ISD::SELECT, dl, EltVT, Operands));
11057       break;
11058     case ISD::SHL:
11059     case ISD::SRA:
11060     case ISD::SRL:
11061     case ISD::ROTL:
11062     case ISD::ROTR:
11063       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0],
11064                                getShiftAmountOperand(Operands[0].getValueType(),
11065                                                      Operands[1])));
11066       break;
11067     case ISD::SIGN_EXTEND_INREG: {
11068       EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType();
11069       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT,
11070                                 Operands[0],
11071                                 getValueType(ExtVT)));
11072     }
11073     }
11074   }
11075 
11076   for (; i < ResNE; ++i)
11077     Scalars.push_back(getUNDEF(EltVT));
11078 
11079   EVT VecVT = EVT::getVectorVT(*getContext(), EltVT, ResNE);
11080   return getBuildVector(VecVT, dl, Scalars);
11081 }
11082 
11083 std::pair<SDValue, SDValue> SelectionDAG::UnrollVectorOverflowOp(
11084     SDNode *N, unsigned ResNE) {
11085   unsigned Opcode = N->getOpcode();
11086   assert((Opcode == ISD::UADDO || Opcode == ISD::SADDO ||
11087           Opcode == ISD::USUBO || Opcode == ISD::SSUBO ||
11088           Opcode == ISD::UMULO || Opcode == ISD::SMULO) &&
11089          "Expected an overflow opcode");
11090 
11091   EVT ResVT = N->getValueType(0);
11092   EVT OvVT = N->getValueType(1);
11093   EVT ResEltVT = ResVT.getVectorElementType();
11094   EVT OvEltVT = OvVT.getVectorElementType();
11095   SDLoc dl(N);
11096 
11097   // If ResNE is 0, fully unroll the vector op.
11098   unsigned NE = ResVT.getVectorNumElements();
11099   if (ResNE == 0)
11100     ResNE = NE;
11101   else if (NE > ResNE)
11102     NE = ResNE;
11103 
11104   SmallVector<SDValue, 8> LHSScalars;
11105   SmallVector<SDValue, 8> RHSScalars;
11106   ExtractVectorElements(N->getOperand(0), LHSScalars, 0, NE);
11107   ExtractVectorElements(N->getOperand(1), RHSScalars, 0, NE);
11108 
11109   EVT SVT = TLI->getSetCCResultType(getDataLayout(), *getContext(), ResEltVT);
11110   SDVTList VTs = getVTList(ResEltVT, SVT);
11111   SmallVector<SDValue, 8> ResScalars;
11112   SmallVector<SDValue, 8> OvScalars;
11113   for (unsigned i = 0; i < NE; ++i) {
11114     SDValue Res = getNode(Opcode, dl, VTs, LHSScalars[i], RHSScalars[i]);
11115     SDValue Ov =
11116         getSelect(dl, OvEltVT, Res.getValue(1),
11117                   getBoolConstant(true, dl, OvEltVT, ResVT),
11118                   getConstant(0, dl, OvEltVT));
11119 
11120     ResScalars.push_back(Res);
11121     OvScalars.push_back(Ov);
11122   }
11123 
11124   ResScalars.append(ResNE - NE, getUNDEF(ResEltVT));
11125   OvScalars.append(ResNE - NE, getUNDEF(OvEltVT));
11126 
11127   EVT NewResVT = EVT::getVectorVT(*getContext(), ResEltVT, ResNE);
11128   EVT NewOvVT = EVT::getVectorVT(*getContext(), OvEltVT, ResNE);
11129   return std::make_pair(getBuildVector(NewResVT, dl, ResScalars),
11130                         getBuildVector(NewOvVT, dl, OvScalars));
11131 }
11132 
11133 bool SelectionDAG::areNonVolatileConsecutiveLoads(LoadSDNode *LD,
11134                                                   LoadSDNode *Base,
11135                                                   unsigned Bytes,
11136                                                   int Dist) const {
11137   if (LD->isVolatile() || Base->isVolatile())
11138     return false;
11139   // TODO: probably too restrictive for atomics, revisit
11140   if (!LD->isSimple())
11141     return false;
11142   if (LD->isIndexed() || Base->isIndexed())
11143     return false;
11144   if (LD->getChain() != Base->getChain())
11145     return false;
11146   EVT VT = LD->getValueType(0);
11147   if (VT.getSizeInBits() / 8 != Bytes)
11148     return false;
11149 
11150   auto BaseLocDecomp = BaseIndexOffset::match(Base, *this);
11151   auto LocDecomp = BaseIndexOffset::match(LD, *this);
11152 
11153   int64_t Offset = 0;
11154   if (BaseLocDecomp.equalBaseIndex(LocDecomp, *this, Offset))
11155     return (Dist * Bytes == Offset);
11156   return false;
11157 }
11158 
11159 /// InferPtrAlignment - Infer alignment of a load / store address. Return None
11160 /// if it cannot be inferred.
11161 MaybeAlign SelectionDAG::InferPtrAlign(SDValue Ptr) const {
11162   // If this is a GlobalAddress + cst, return the alignment.
11163   const GlobalValue *GV = nullptr;
11164   int64_t GVOffset = 0;
11165   if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) {
11166     unsigned PtrWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
11167     KnownBits Known(PtrWidth);
11168     llvm::computeKnownBits(GV, Known, getDataLayout());
11169     unsigned AlignBits = Known.countMinTrailingZeros();
11170     if (AlignBits)
11171       return commonAlignment(Align(1ull << std::min(31U, AlignBits)), GVOffset);
11172   }
11173 
11174   // If this is a direct reference to a stack slot, use information about the
11175   // stack slot's alignment.
11176   int FrameIdx = INT_MIN;
11177   int64_t FrameOffset = 0;
11178   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) {
11179     FrameIdx = FI->getIndex();
11180   } else if (isBaseWithConstantOffset(Ptr) &&
11181              isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
11182     // Handle FI+Cst
11183     FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
11184     FrameOffset = Ptr.getConstantOperandVal(1);
11185   }
11186 
11187   if (FrameIdx != INT_MIN) {
11188     const MachineFrameInfo &MFI = getMachineFunction().getFrameInfo();
11189     return commonAlignment(MFI.getObjectAlign(FrameIdx), FrameOffset);
11190   }
11191 
11192   return None;
11193 }
11194 
11195 /// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type
11196 /// which is split (or expanded) into two not necessarily identical pieces.
11197 std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const {
11198   // Currently all types are split in half.
11199   EVT LoVT, HiVT;
11200   if (!VT.isVector())
11201     LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT);
11202   else
11203     LoVT = HiVT = VT.getHalfNumVectorElementsVT(*getContext());
11204 
11205   return std::make_pair(LoVT, HiVT);
11206 }
11207 
11208 /// GetDependentSplitDestVTs - Compute the VTs needed for the low/hi parts of a
11209 /// type, dependent on an enveloping VT that has been split into two identical
11210 /// pieces. Sets the HiIsEmpty flag when hi type has zero storage size.
11211 std::pair<EVT, EVT>
11212 SelectionDAG::GetDependentSplitDestVTs(const EVT &VT, const EVT &EnvVT,
11213                                        bool *HiIsEmpty) const {
11214   EVT EltTp = VT.getVectorElementType();
11215   // Examples:
11216   //   custom VL=8  with enveloping VL=8/8 yields 8/0 (hi empty)
11217   //   custom VL=9  with enveloping VL=8/8 yields 8/1
11218   //   custom VL=10 with enveloping VL=8/8 yields 8/2
11219   //   etc.
11220   ElementCount VTNumElts = VT.getVectorElementCount();
11221   ElementCount EnvNumElts = EnvVT.getVectorElementCount();
11222   assert(VTNumElts.isScalable() == EnvNumElts.isScalable() &&
11223          "Mixing fixed width and scalable vectors when enveloping a type");
11224   EVT LoVT, HiVT;
11225   if (VTNumElts.getKnownMinValue() > EnvNumElts.getKnownMinValue()) {
11226     LoVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts);
11227     HiVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts - EnvNumElts);
11228     *HiIsEmpty = false;
11229   } else {
11230     // Flag that hi type has zero storage size, but return split envelop type
11231     // (this would be easier if vector types with zero elements were allowed).
11232     LoVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts);
11233     HiVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts);
11234     *HiIsEmpty = true;
11235   }
11236   return std::make_pair(LoVT, HiVT);
11237 }
11238 
11239 /// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the
11240 /// low/high part.
11241 std::pair<SDValue, SDValue>
11242 SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT,
11243                           const EVT &HiVT) {
11244   assert(LoVT.isScalableVector() == HiVT.isScalableVector() &&
11245          LoVT.isScalableVector() == N.getValueType().isScalableVector() &&
11246          "Splitting vector with an invalid mixture of fixed and scalable "
11247          "vector types");
11248   assert(LoVT.getVectorMinNumElements() + HiVT.getVectorMinNumElements() <=
11249              N.getValueType().getVectorMinNumElements() &&
11250          "More vector elements requested than available!");
11251   SDValue Lo, Hi;
11252   Lo =
11253       getNode(ISD::EXTRACT_SUBVECTOR, DL, LoVT, N, getVectorIdxConstant(0, DL));
11254   // For scalable vectors it is safe to use LoVT.getVectorMinNumElements()
11255   // (rather than having to use ElementCount), because EXTRACT_SUBVECTOR scales
11256   // IDX with the runtime scaling factor of the result vector type. For
11257   // fixed-width result vectors, that runtime scaling factor is 1.
11258   Hi = getNode(ISD::EXTRACT_SUBVECTOR, DL, HiVT, N,
11259                getVectorIdxConstant(LoVT.getVectorMinNumElements(), DL));
11260   return std::make_pair(Lo, Hi);
11261 }
11262 
11263 std::pair<SDValue, SDValue> SelectionDAG::SplitEVL(SDValue N, EVT VecVT,
11264                                                    const SDLoc &DL) {
11265   // Split the vector length parameter.
11266   // %evl -> umin(%evl, %halfnumelts) and usubsat(%evl - %halfnumelts).
11267   EVT VT = N.getValueType();
11268   assert(VecVT.getVectorElementCount().isKnownEven() &&
11269          "Expecting the mask to be an evenly-sized vector");
11270   unsigned HalfMinNumElts = VecVT.getVectorMinNumElements() / 2;
11271   SDValue HalfNumElts =
11272       VecVT.isFixedLengthVector()
11273           ? getConstant(HalfMinNumElts, DL, VT)
11274           : getVScale(DL, VT, APInt(VT.getScalarSizeInBits(), HalfMinNumElts));
11275   SDValue Lo = getNode(ISD::UMIN, DL, VT, N, HalfNumElts);
11276   SDValue Hi = getNode(ISD::USUBSAT, DL, VT, N, HalfNumElts);
11277   return std::make_pair(Lo, Hi);
11278 }
11279 
11280 /// Widen the vector up to the next power of two using INSERT_SUBVECTOR.
11281 SDValue SelectionDAG::WidenVector(const SDValue &N, const SDLoc &DL) {
11282   EVT VT = N.getValueType();
11283   EVT WideVT = EVT::getVectorVT(*getContext(), VT.getVectorElementType(),
11284                                 NextPowerOf2(VT.getVectorNumElements()));
11285   return getNode(ISD::INSERT_SUBVECTOR, DL, WideVT, getUNDEF(WideVT), N,
11286                  getVectorIdxConstant(0, DL));
11287 }
11288 
11289 void SelectionDAG::ExtractVectorElements(SDValue Op,
11290                                          SmallVectorImpl<SDValue> &Args,
11291                                          unsigned Start, unsigned Count,
11292                                          EVT EltVT) {
11293   EVT VT = Op.getValueType();
11294   if (Count == 0)
11295     Count = VT.getVectorNumElements();
11296   if (EltVT == EVT())
11297     EltVT = VT.getVectorElementType();
11298   SDLoc SL(Op);
11299   for (unsigned i = Start, e = Start + Count; i != e; ++i) {
11300     Args.push_back(getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Op,
11301                            getVectorIdxConstant(i, SL)));
11302   }
11303 }
11304 
11305 // getAddressSpace - Return the address space this GlobalAddress belongs to.
11306 unsigned GlobalAddressSDNode::getAddressSpace() const {
11307   return getGlobal()->getType()->getAddressSpace();
11308 }
11309 
11310 Type *ConstantPoolSDNode::getType() const {
11311   if (isMachineConstantPoolEntry())
11312     return Val.MachineCPVal->getType();
11313   return Val.ConstVal->getType();
11314 }
11315 
11316 bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue, APInt &SplatUndef,
11317                                         unsigned &SplatBitSize,
11318                                         bool &HasAnyUndefs,
11319                                         unsigned MinSplatBits,
11320                                         bool IsBigEndian) const {
11321   EVT VT = getValueType(0);
11322   assert(VT.isVector() && "Expected a vector type");
11323   unsigned VecWidth = VT.getSizeInBits();
11324   if (MinSplatBits > VecWidth)
11325     return false;
11326 
11327   // FIXME: The widths are based on this node's type, but build vectors can
11328   // truncate their operands.
11329   SplatValue = APInt(VecWidth, 0);
11330   SplatUndef = APInt(VecWidth, 0);
11331 
11332   // Get the bits. Bits with undefined values (when the corresponding element
11333   // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared
11334   // in SplatValue. If any of the values are not constant, give up and return
11335   // false.
11336   unsigned int NumOps = getNumOperands();
11337   assert(NumOps > 0 && "isConstantSplat has 0-size build vector");
11338   unsigned EltWidth = VT.getScalarSizeInBits();
11339 
11340   for (unsigned j = 0; j < NumOps; ++j) {
11341     unsigned i = IsBigEndian ? NumOps - 1 - j : j;
11342     SDValue OpVal = getOperand(i);
11343     unsigned BitPos = j * EltWidth;
11344 
11345     if (OpVal.isUndef())
11346       SplatUndef.setBits(BitPos, BitPos + EltWidth);
11347     else if (auto *CN = dyn_cast<ConstantSDNode>(OpVal))
11348       SplatValue.insertBits(CN->getAPIntValue().zextOrTrunc(EltWidth), BitPos);
11349     else if (auto *CN = dyn_cast<ConstantFPSDNode>(OpVal))
11350       SplatValue.insertBits(CN->getValueAPF().bitcastToAPInt(), BitPos);
11351     else
11352       return false;
11353   }
11354 
11355   // The build_vector is all constants or undefs. Find the smallest element
11356   // size that splats the vector.
11357   HasAnyUndefs = (SplatUndef != 0);
11358 
11359   // FIXME: This does not work for vectors with elements less than 8 bits.
11360   while (VecWidth > 8) {
11361     unsigned HalfSize = VecWidth / 2;
11362     APInt HighValue = SplatValue.extractBits(HalfSize, HalfSize);
11363     APInt LowValue = SplatValue.extractBits(HalfSize, 0);
11364     APInt HighUndef = SplatUndef.extractBits(HalfSize, HalfSize);
11365     APInt LowUndef = SplatUndef.extractBits(HalfSize, 0);
11366 
11367     // If the two halves do not match (ignoring undef bits), stop here.
11368     if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) ||
11369         MinSplatBits > HalfSize)
11370       break;
11371 
11372     SplatValue = HighValue | LowValue;
11373     SplatUndef = HighUndef & LowUndef;
11374 
11375     VecWidth = HalfSize;
11376   }
11377 
11378   SplatBitSize = VecWidth;
11379   return true;
11380 }
11381 
11382 SDValue BuildVectorSDNode::getSplatValue(const APInt &DemandedElts,
11383                                          BitVector *UndefElements) const {
11384   unsigned NumOps = getNumOperands();
11385   if (UndefElements) {
11386     UndefElements->clear();
11387     UndefElements->resize(NumOps);
11388   }
11389   assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size");
11390   if (!DemandedElts)
11391     return SDValue();
11392   SDValue Splatted;
11393   for (unsigned i = 0; i != NumOps; ++i) {
11394     if (!DemandedElts[i])
11395       continue;
11396     SDValue Op = getOperand(i);
11397     if (Op.isUndef()) {
11398       if (UndefElements)
11399         (*UndefElements)[i] = true;
11400     } else if (!Splatted) {
11401       Splatted = Op;
11402     } else if (Splatted != Op) {
11403       return SDValue();
11404     }
11405   }
11406 
11407   if (!Splatted) {
11408     unsigned FirstDemandedIdx = DemandedElts.countTrailingZeros();
11409     assert(getOperand(FirstDemandedIdx).isUndef() &&
11410            "Can only have a splat without a constant for all undefs.");
11411     return getOperand(FirstDemandedIdx);
11412   }
11413 
11414   return Splatted;
11415 }
11416 
11417 SDValue BuildVectorSDNode::getSplatValue(BitVector *UndefElements) const {
11418   APInt DemandedElts = APInt::getAllOnes(getNumOperands());
11419   return getSplatValue(DemandedElts, UndefElements);
11420 }
11421 
11422 bool BuildVectorSDNode::getRepeatedSequence(const APInt &DemandedElts,
11423                                             SmallVectorImpl<SDValue> &Sequence,
11424                                             BitVector *UndefElements) const {
11425   unsigned NumOps = getNumOperands();
11426   Sequence.clear();
11427   if (UndefElements) {
11428     UndefElements->clear();
11429     UndefElements->resize(NumOps);
11430   }
11431   assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size");
11432   if (!DemandedElts || NumOps < 2 || !isPowerOf2_32(NumOps))
11433     return false;
11434 
11435   // Set the undefs even if we don't find a sequence (like getSplatValue).
11436   if (UndefElements)
11437     for (unsigned I = 0; I != NumOps; ++I)
11438       if (DemandedElts[I] && getOperand(I).isUndef())
11439         (*UndefElements)[I] = true;
11440 
11441   // Iteratively widen the sequence length looking for repetitions.
11442   for (unsigned SeqLen = 1; SeqLen < NumOps; SeqLen *= 2) {
11443     Sequence.append(SeqLen, SDValue());
11444     for (unsigned I = 0; I != NumOps; ++I) {
11445       if (!DemandedElts[I])
11446         continue;
11447       SDValue &SeqOp = Sequence[I % SeqLen];
11448       SDValue Op = getOperand(I);
11449       if (Op.isUndef()) {
11450         if (!SeqOp)
11451           SeqOp = Op;
11452         continue;
11453       }
11454       if (SeqOp && !SeqOp.isUndef() && SeqOp != Op) {
11455         Sequence.clear();
11456         break;
11457       }
11458       SeqOp = Op;
11459     }
11460     if (!Sequence.empty())
11461       return true;
11462   }
11463 
11464   assert(Sequence.empty() && "Failed to empty non-repeating sequence pattern");
11465   return false;
11466 }
11467 
11468 bool BuildVectorSDNode::getRepeatedSequence(SmallVectorImpl<SDValue> &Sequence,
11469                                             BitVector *UndefElements) const {
11470   APInt DemandedElts = APInt::getAllOnes(getNumOperands());
11471   return getRepeatedSequence(DemandedElts, Sequence, UndefElements);
11472 }
11473 
11474 ConstantSDNode *
11475 BuildVectorSDNode::getConstantSplatNode(const APInt &DemandedElts,
11476                                         BitVector *UndefElements) const {
11477   return dyn_cast_or_null<ConstantSDNode>(
11478       getSplatValue(DemandedElts, UndefElements));
11479 }
11480 
11481 ConstantSDNode *
11482 BuildVectorSDNode::getConstantSplatNode(BitVector *UndefElements) const {
11483   return dyn_cast_or_null<ConstantSDNode>(getSplatValue(UndefElements));
11484 }
11485 
11486 ConstantFPSDNode *
11487 BuildVectorSDNode::getConstantFPSplatNode(const APInt &DemandedElts,
11488                                           BitVector *UndefElements) const {
11489   return dyn_cast_or_null<ConstantFPSDNode>(
11490       getSplatValue(DemandedElts, UndefElements));
11491 }
11492 
11493 ConstantFPSDNode *
11494 BuildVectorSDNode::getConstantFPSplatNode(BitVector *UndefElements) const {
11495   return dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements));
11496 }
11497 
11498 int32_t
11499 BuildVectorSDNode::getConstantFPSplatPow2ToLog2Int(BitVector *UndefElements,
11500                                                    uint32_t BitWidth) const {
11501   if (ConstantFPSDNode *CN =
11502           dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements))) {
11503     bool IsExact;
11504     APSInt IntVal(BitWidth);
11505     const APFloat &APF = CN->getValueAPF();
11506     if (APF.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) !=
11507             APFloat::opOK ||
11508         !IsExact)
11509       return -1;
11510 
11511     return IntVal.exactLogBase2();
11512   }
11513   return -1;
11514 }
11515 
11516 bool BuildVectorSDNode::getConstantRawBits(
11517     bool IsLittleEndian, unsigned DstEltSizeInBits,
11518     SmallVectorImpl<APInt> &RawBitElements, BitVector &UndefElements) const {
11519   // Early-out if this contains anything but Undef/Constant/ConstantFP.
11520   if (!isConstant())
11521     return false;
11522 
11523   unsigned NumSrcOps = getNumOperands();
11524   unsigned SrcEltSizeInBits = getValueType(0).getScalarSizeInBits();
11525   assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 &&
11526          "Invalid bitcast scale");
11527 
11528   // Extract raw src bits.
11529   SmallVector<APInt> SrcBitElements(NumSrcOps,
11530                                     APInt::getNullValue(SrcEltSizeInBits));
11531   BitVector SrcUndeElements(NumSrcOps, false);
11532 
11533   for (unsigned I = 0; I != NumSrcOps; ++I) {
11534     SDValue Op = getOperand(I);
11535     if (Op.isUndef()) {
11536       SrcUndeElements.set(I);
11537       continue;
11538     }
11539     auto *CInt = dyn_cast<ConstantSDNode>(Op);
11540     auto *CFP = dyn_cast<ConstantFPSDNode>(Op);
11541     assert((CInt || CFP) && "Unknown constant");
11542     SrcBitElements[I] = CInt ? CInt->getAPIntValue().trunc(SrcEltSizeInBits)
11543                              : CFP->getValueAPF().bitcastToAPInt();
11544   }
11545 
11546   // Recast to dst width.
11547   recastRawBits(IsLittleEndian, DstEltSizeInBits, RawBitElements,
11548                 SrcBitElements, UndefElements, SrcUndeElements);
11549   return true;
11550 }
11551 
11552 void BuildVectorSDNode::recastRawBits(bool IsLittleEndian,
11553                                       unsigned DstEltSizeInBits,
11554                                       SmallVectorImpl<APInt> &DstBitElements,
11555                                       ArrayRef<APInt> SrcBitElements,
11556                                       BitVector &DstUndefElements,
11557                                       const BitVector &SrcUndefElements) {
11558   unsigned NumSrcOps = SrcBitElements.size();
11559   unsigned SrcEltSizeInBits = SrcBitElements[0].getBitWidth();
11560   assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 &&
11561          "Invalid bitcast scale");
11562   assert(NumSrcOps == SrcUndefElements.size() &&
11563          "Vector size mismatch");
11564 
11565   unsigned NumDstOps = (NumSrcOps * SrcEltSizeInBits) / DstEltSizeInBits;
11566   DstUndefElements.clear();
11567   DstUndefElements.resize(NumDstOps, false);
11568   DstBitElements.assign(NumDstOps, APInt::getNullValue(DstEltSizeInBits));
11569 
11570   // Concatenate src elements constant bits together into dst element.
11571   if (SrcEltSizeInBits <= DstEltSizeInBits) {
11572     unsigned Scale = DstEltSizeInBits / SrcEltSizeInBits;
11573     for (unsigned I = 0; I != NumDstOps; ++I) {
11574       DstUndefElements.set(I);
11575       APInt &DstBits = DstBitElements[I];
11576       for (unsigned J = 0; J != Scale; ++J) {
11577         unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1));
11578         if (SrcUndefElements[Idx])
11579           continue;
11580         DstUndefElements.reset(I);
11581         const APInt &SrcBits = SrcBitElements[Idx];
11582         assert(SrcBits.getBitWidth() == SrcEltSizeInBits &&
11583                "Illegal constant bitwidths");
11584         DstBits.insertBits(SrcBits, J * SrcEltSizeInBits);
11585       }
11586     }
11587     return;
11588   }
11589 
11590   // Split src element constant bits into dst elements.
11591   unsigned Scale = SrcEltSizeInBits / DstEltSizeInBits;
11592   for (unsigned I = 0; I != NumSrcOps; ++I) {
11593     if (SrcUndefElements[I]) {
11594       DstUndefElements.set(I * Scale, (I + 1) * Scale);
11595       continue;
11596     }
11597     const APInt &SrcBits = SrcBitElements[I];
11598     for (unsigned J = 0; J != Scale; ++J) {
11599       unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1));
11600       APInt &DstBits = DstBitElements[Idx];
11601       DstBits = SrcBits.extractBits(DstEltSizeInBits, J * DstEltSizeInBits);
11602     }
11603   }
11604 }
11605 
11606 bool BuildVectorSDNode::isConstant() const {
11607   for (const SDValue &Op : op_values()) {
11608     unsigned Opc = Op.getOpcode();
11609     if (Opc != ISD::UNDEF && Opc != ISD::Constant && Opc != ISD::ConstantFP)
11610       return false;
11611   }
11612   return true;
11613 }
11614 
11615 bool ShuffleVectorSDNode::isSplatMask(const int *Mask, EVT VT) {
11616   // Find the first non-undef value in the shuffle mask.
11617   unsigned i, e;
11618   for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i)
11619     /* search */;
11620 
11621   // If all elements are undefined, this shuffle can be considered a splat
11622   // (although it should eventually get simplified away completely).
11623   if (i == e)
11624     return true;
11625 
11626   // Make sure all remaining elements are either undef or the same as the first
11627   // non-undef value.
11628   for (int Idx = Mask[i]; i != e; ++i)
11629     if (Mask[i] >= 0 && Mask[i] != Idx)
11630       return false;
11631   return true;
11632 }
11633 
11634 // Returns the SDNode if it is a constant integer BuildVector
11635 // or constant integer.
11636 SDNode *SelectionDAG::isConstantIntBuildVectorOrConstantInt(SDValue N) const {
11637   if (isa<ConstantSDNode>(N))
11638     return N.getNode();
11639   if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
11640     return N.getNode();
11641   // Treat a GlobalAddress supporting constant offset folding as a
11642   // constant integer.
11643   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N))
11644     if (GA->getOpcode() == ISD::GlobalAddress &&
11645         TLI->isOffsetFoldingLegal(GA))
11646       return GA;
11647   if ((N.getOpcode() == ISD::SPLAT_VECTOR) &&
11648       isa<ConstantSDNode>(N.getOperand(0)))
11649     return N.getNode();
11650   return nullptr;
11651 }
11652 
11653 // Returns the SDNode if it is a constant float BuildVector
11654 // or constant float.
11655 SDNode *SelectionDAG::isConstantFPBuildVectorOrConstantFP(SDValue N) const {
11656   if (isa<ConstantFPSDNode>(N))
11657     return N.getNode();
11658 
11659   if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
11660     return N.getNode();
11661 
11662   if ((N.getOpcode() == ISD::SPLAT_VECTOR) &&
11663       isa<ConstantFPSDNode>(N.getOperand(0)))
11664     return N.getNode();
11665 
11666   return nullptr;
11667 }
11668 
11669 void SelectionDAG::createOperands(SDNode *Node, ArrayRef<SDValue> Vals) {
11670   assert(!Node->OperandList && "Node already has operands");
11671   assert(SDNode::getMaxNumOperands() >= Vals.size() &&
11672          "too many operands to fit into SDNode");
11673   SDUse *Ops = OperandRecycler.allocate(
11674       ArrayRecycler<SDUse>::Capacity::get(Vals.size()), OperandAllocator);
11675 
11676   bool IsDivergent = false;
11677   for (unsigned I = 0; I != Vals.size(); ++I) {
11678     Ops[I].setUser(Node);
11679     Ops[I].setInitial(Vals[I]);
11680     if (Ops[I].Val.getValueType() != MVT::Other) // Skip Chain. It does not carry divergence.
11681       IsDivergent |= Ops[I].getNode()->isDivergent();
11682   }
11683   Node->NumOperands = Vals.size();
11684   Node->OperandList = Ops;
11685   if (!TLI->isSDNodeAlwaysUniform(Node)) {
11686     IsDivergent |= TLI->isSDNodeSourceOfDivergence(Node, FLI, DA);
11687     Node->SDNodeBits.IsDivergent = IsDivergent;
11688   }
11689   checkForCycles(Node);
11690 }
11691 
11692 SDValue SelectionDAG::getTokenFactor(const SDLoc &DL,
11693                                      SmallVectorImpl<SDValue> &Vals) {
11694   size_t Limit = SDNode::getMaxNumOperands();
11695   while (Vals.size() > Limit) {
11696     unsigned SliceIdx = Vals.size() - Limit;
11697     auto ExtractedTFs = ArrayRef<SDValue>(Vals).slice(SliceIdx, Limit);
11698     SDValue NewTF = getNode(ISD::TokenFactor, DL, MVT::Other, ExtractedTFs);
11699     Vals.erase(Vals.begin() + SliceIdx, Vals.end());
11700     Vals.emplace_back(NewTF);
11701   }
11702   return getNode(ISD::TokenFactor, DL, MVT::Other, Vals);
11703 }
11704 
11705 SDValue SelectionDAG::getNeutralElement(unsigned Opcode, const SDLoc &DL,
11706                                         EVT VT, SDNodeFlags Flags) {
11707   switch (Opcode) {
11708   default:
11709     return SDValue();
11710   case ISD::ADD:
11711   case ISD::OR:
11712   case ISD::XOR:
11713   case ISD::UMAX:
11714     return getConstant(0, DL, VT);
11715   case ISD::MUL:
11716     return getConstant(1, DL, VT);
11717   case ISD::AND:
11718   case ISD::UMIN:
11719     return getAllOnesConstant(DL, VT);
11720   case ISD::SMAX:
11721     return getConstant(APInt::getSignedMinValue(VT.getSizeInBits()), DL, VT);
11722   case ISD::SMIN:
11723     return getConstant(APInt::getSignedMaxValue(VT.getSizeInBits()), DL, VT);
11724   case ISD::FADD:
11725     return getConstantFP(-0.0, DL, VT);
11726   case ISD::FMUL:
11727     return getConstantFP(1.0, DL, VT);
11728   case ISD::FMINNUM:
11729   case ISD::FMAXNUM: {
11730     // Neutral element for fminnum is NaN, Inf or FLT_MAX, depending on FMF.
11731     const fltSemantics &Semantics = EVTToAPFloatSemantics(VT);
11732     APFloat NeutralAF = !Flags.hasNoNaNs() ? APFloat::getQNaN(Semantics) :
11733                         !Flags.hasNoInfs() ? APFloat::getInf(Semantics) :
11734                         APFloat::getLargest(Semantics);
11735     if (Opcode == ISD::FMAXNUM)
11736       NeutralAF.changeSign();
11737 
11738     return getConstantFP(NeutralAF, DL, VT);
11739   }
11740   }
11741 }
11742 
11743 #ifndef NDEBUG
11744 static void checkForCyclesHelper(const SDNode *N,
11745                                  SmallPtrSetImpl<const SDNode*> &Visited,
11746                                  SmallPtrSetImpl<const SDNode*> &Checked,
11747                                  const llvm::SelectionDAG *DAG) {
11748   // If this node has already been checked, don't check it again.
11749   if (Checked.count(N))
11750     return;
11751 
11752   // If a node has already been visited on this depth-first walk, reject it as
11753   // a cycle.
11754   if (!Visited.insert(N).second) {
11755     errs() << "Detected cycle in SelectionDAG\n";
11756     dbgs() << "Offending node:\n";
11757     N->dumprFull(DAG); dbgs() << "\n";
11758     abort();
11759   }
11760 
11761   for (const SDValue &Op : N->op_values())
11762     checkForCyclesHelper(Op.getNode(), Visited, Checked, DAG);
11763 
11764   Checked.insert(N);
11765   Visited.erase(N);
11766 }
11767 #endif
11768 
11769 void llvm::checkForCycles(const llvm::SDNode *N,
11770                           const llvm::SelectionDAG *DAG,
11771                           bool force) {
11772 #ifndef NDEBUG
11773   bool check = force;
11774 #ifdef EXPENSIVE_CHECKS
11775   check = true;
11776 #endif  // EXPENSIVE_CHECKS
11777   if (check) {
11778     assert(N && "Checking nonexistent SDNode");
11779     SmallPtrSet<const SDNode*, 32> visited;
11780     SmallPtrSet<const SDNode*, 32> checked;
11781     checkForCyclesHelper(N, visited, checked, DAG);
11782   }
11783 #endif  // !NDEBUG
11784 }
11785 
11786 void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) {
11787   checkForCycles(DAG->getRoot().getNode(), DAG, force);
11788 }
11789