xref: /freebsd/contrib/llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAG.cpp (revision 5e801ac66d24704442eba426ed13c3effb8a34e7)
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/BlockFrequencyInfo.h"
28 #include "llvm/Analysis/MemoryLocation.h"
29 #include "llvm/Analysis/ProfileSummaryInfo.h"
30 #include "llvm/Analysis/ValueTracking.h"
31 #include "llvm/CodeGen/Analysis.h"
32 #include "llvm/CodeGen/FunctionLoweringInfo.h"
33 #include "llvm/CodeGen/ISDOpcodes.h"
34 #include "llvm/CodeGen/MachineBasicBlock.h"
35 #include "llvm/CodeGen/MachineConstantPool.h"
36 #include "llvm/CodeGen/MachineFrameInfo.h"
37 #include "llvm/CodeGen/MachineFunction.h"
38 #include "llvm/CodeGen/MachineMemOperand.h"
39 #include "llvm/CodeGen/RuntimeLibcalls.h"
40 #include "llvm/CodeGen/SelectionDAGAddressAnalysis.h"
41 #include "llvm/CodeGen/SelectionDAGNodes.h"
42 #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
43 #include "llvm/CodeGen/TargetFrameLowering.h"
44 #include "llvm/CodeGen/TargetLowering.h"
45 #include "llvm/CodeGen/TargetRegisterInfo.h"
46 #include "llvm/CodeGen/TargetSubtargetInfo.h"
47 #include "llvm/CodeGen/ValueTypes.h"
48 #include "llvm/IR/Constant.h"
49 #include "llvm/IR/Constants.h"
50 #include "llvm/IR/DataLayout.h"
51 #include "llvm/IR/DebugInfoMetadata.h"
52 #include "llvm/IR/DebugLoc.h"
53 #include "llvm/IR/DerivedTypes.h"
54 #include "llvm/IR/Function.h"
55 #include "llvm/IR/GlobalValue.h"
56 #include "llvm/IR/Metadata.h"
57 #include "llvm/IR/Type.h"
58 #include "llvm/IR/Value.h"
59 #include "llvm/Support/Casting.h"
60 #include "llvm/Support/CodeGen.h"
61 #include "llvm/Support/Compiler.h"
62 #include "llvm/Support/Debug.h"
63 #include "llvm/Support/ErrorHandling.h"
64 #include "llvm/Support/KnownBits.h"
65 #include "llvm/Support/MachineValueType.h"
66 #include "llvm/Support/ManagedStatic.h"
67 #include "llvm/Support/MathExtras.h"
68 #include "llvm/Support/Mutex.h"
69 #include "llvm/Support/raw_ostream.h"
70 #include "llvm/Target/TargetMachine.h"
71 #include "llvm/Target/TargetOptions.h"
72 #include "llvm/Transforms/Utils/SizeOpts.h"
73 #include <algorithm>
74 #include <cassert>
75 #include <cstdint>
76 #include <cstdlib>
77 #include <limits>
78 #include <set>
79 #include <string>
80 #include <utility>
81 #include <vector>
82 
83 using namespace llvm;
84 
85 /// makeVTList - Return an instance of the SDVTList struct initialized with the
86 /// specified members.
87 static SDVTList makeVTList(const EVT *VTs, unsigned NumVTs) {
88   SDVTList Res = {VTs, NumVTs};
89   return Res;
90 }
91 
92 // Default null implementations of the callbacks.
93 void SelectionDAG::DAGUpdateListener::NodeDeleted(SDNode*, SDNode*) {}
94 void SelectionDAG::DAGUpdateListener::NodeUpdated(SDNode*) {}
95 void SelectionDAG::DAGUpdateListener::NodeInserted(SDNode *) {}
96 
97 void SelectionDAG::DAGNodeDeletedListener::anchor() {}
98 
99 #define DEBUG_TYPE "selectiondag"
100 
101 static cl::opt<bool> EnableMemCpyDAGOpt("enable-memcpy-dag-opt",
102        cl::Hidden, cl::init(true),
103        cl::desc("Gang up loads and stores generated by inlining of memcpy"));
104 
105 static cl::opt<int> MaxLdStGlue("ldstmemcpy-glue-max",
106        cl::desc("Number limit for gluing ld/st of memcpy."),
107        cl::Hidden, cl::init(0));
108 
109 static void NewSDValueDbgMsg(SDValue V, StringRef Msg, SelectionDAG *G) {
110   LLVM_DEBUG(dbgs() << Msg; V.getNode()->dump(G););
111 }
112 
113 //===----------------------------------------------------------------------===//
114 //                              ConstantFPSDNode Class
115 //===----------------------------------------------------------------------===//
116 
117 /// isExactlyValue - We don't rely on operator== working on double values, as
118 /// it returns true for things that are clearly not equal, like -0.0 and 0.0.
119 /// As such, this method can be used to do an exact bit-for-bit comparison of
120 /// two floating point values.
121 bool ConstantFPSDNode::isExactlyValue(const APFloat& V) const {
122   return getValueAPF().bitwiseIsEqual(V);
123 }
124 
125 bool ConstantFPSDNode::isValueValidForType(EVT VT,
126                                            const APFloat& Val) {
127   assert(VT.isFloatingPoint() && "Can only convert between FP types");
128 
129   // convert modifies in place, so make a copy.
130   APFloat Val2 = APFloat(Val);
131   bool losesInfo;
132   (void) Val2.convert(SelectionDAG::EVTToAPFloatSemantics(VT),
133                       APFloat::rmNearestTiesToEven,
134                       &losesInfo);
135   return !losesInfo;
136 }
137 
138 //===----------------------------------------------------------------------===//
139 //                              ISD Namespace
140 //===----------------------------------------------------------------------===//
141 
142 bool ISD::isConstantSplatVector(const SDNode *N, APInt &SplatVal) {
143   if (N->getOpcode() == ISD::SPLAT_VECTOR) {
144     unsigned EltSize =
145         N->getValueType(0).getVectorElementType().getSizeInBits();
146     if (auto *Op0 = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
147       SplatVal = Op0->getAPIntValue().truncOrSelf(EltSize);
148       return true;
149     }
150     if (auto *Op0 = dyn_cast<ConstantFPSDNode>(N->getOperand(0))) {
151       SplatVal = Op0->getValueAPF().bitcastToAPInt().truncOrSelf(EltSize);
152       return true;
153     }
154   }
155 
156   auto *BV = dyn_cast<BuildVectorSDNode>(N);
157   if (!BV)
158     return false;
159 
160   APInt SplatUndef;
161   unsigned SplatBitSize;
162   bool HasUndefs;
163   unsigned EltSize = N->getValueType(0).getVectorElementType().getSizeInBits();
164   return BV->isConstantSplat(SplatVal, SplatUndef, SplatBitSize, HasUndefs,
165                              EltSize) &&
166          EltSize == SplatBitSize;
167 }
168 
169 // FIXME: AllOnes and AllZeros duplicate a lot of code. Could these be
170 // specializations of the more general isConstantSplatVector()?
171 
172 bool ISD::isConstantSplatVectorAllOnes(const SDNode *N, bool BuildVectorOnly) {
173   // Look through a bit convert.
174   while (N->getOpcode() == ISD::BITCAST)
175     N = N->getOperand(0).getNode();
176 
177   if (!BuildVectorOnly && N->getOpcode() == ISD::SPLAT_VECTOR) {
178     APInt SplatVal;
179     return isConstantSplatVector(N, SplatVal) && SplatVal.isAllOnes();
180   }
181 
182   if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
183 
184   unsigned i = 0, e = N->getNumOperands();
185 
186   // Skip over all of the undef values.
187   while (i != e && N->getOperand(i).isUndef())
188     ++i;
189 
190   // Do not accept an all-undef vector.
191   if (i == e) return false;
192 
193   // Do not accept build_vectors that aren't all constants or which have non-~0
194   // elements. We have to be a bit careful here, as the type of the constant
195   // may not be the same as the type of the vector elements due to type
196   // legalization (the elements are promoted to a legal type for the target and
197   // a vector of a type may be legal when the base element type is not).
198   // We only want to check enough bits to cover the vector elements, because
199   // we care if the resultant vector is all ones, not whether the individual
200   // constants are.
201   SDValue NotZero = N->getOperand(i);
202   unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
203   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(NotZero)) {
204     if (CN->getAPIntValue().countTrailingOnes() < EltSize)
205       return false;
206   } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(NotZero)) {
207     if (CFPN->getValueAPF().bitcastToAPInt().countTrailingOnes() < EltSize)
208       return false;
209   } else
210     return false;
211 
212   // Okay, we have at least one ~0 value, check to see if the rest match or are
213   // undefs. Even with the above element type twiddling, this should be OK, as
214   // the same type legalization should have applied to all the elements.
215   for (++i; i != e; ++i)
216     if (N->getOperand(i) != NotZero && !N->getOperand(i).isUndef())
217       return false;
218   return true;
219 }
220 
221 bool ISD::isConstantSplatVectorAllZeros(const SDNode *N, bool BuildVectorOnly) {
222   // Look through a bit convert.
223   while (N->getOpcode() == ISD::BITCAST)
224     N = N->getOperand(0).getNode();
225 
226   if (!BuildVectorOnly && N->getOpcode() == ISD::SPLAT_VECTOR) {
227     APInt SplatVal;
228     return isConstantSplatVector(N, SplatVal) && SplatVal.isZero();
229   }
230 
231   if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
232 
233   bool IsAllUndef = true;
234   for (const SDValue &Op : N->op_values()) {
235     if (Op.isUndef())
236       continue;
237     IsAllUndef = false;
238     // Do not accept build_vectors that aren't all constants or which have non-0
239     // elements. We have to be a bit careful here, as the type of the constant
240     // may not be the same as the type of the vector elements due to type
241     // legalization (the elements are promoted to a legal type for the target
242     // and a vector of a type may be legal when the base element type is not).
243     // We only want to check enough bits to cover the vector elements, because
244     // we care if the resultant vector is all zeros, not whether the individual
245     // constants are.
246     unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
247     if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Op)) {
248       if (CN->getAPIntValue().countTrailingZeros() < EltSize)
249         return false;
250     } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(Op)) {
251       if (CFPN->getValueAPF().bitcastToAPInt().countTrailingZeros() < EltSize)
252         return false;
253     } else
254       return false;
255   }
256 
257   // Do not accept an all-undef vector.
258   if (IsAllUndef)
259     return false;
260   return true;
261 }
262 
263 bool ISD::isBuildVectorAllOnes(const SDNode *N) {
264   return isConstantSplatVectorAllOnes(N, /*BuildVectorOnly*/ true);
265 }
266 
267 bool ISD::isBuildVectorAllZeros(const SDNode *N) {
268   return isConstantSplatVectorAllZeros(N, /*BuildVectorOnly*/ true);
269 }
270 
271 bool ISD::isBuildVectorOfConstantSDNodes(const SDNode *N) {
272   if (N->getOpcode() != ISD::BUILD_VECTOR)
273     return false;
274 
275   for (const SDValue &Op : N->op_values()) {
276     if (Op.isUndef())
277       continue;
278     if (!isa<ConstantSDNode>(Op))
279       return false;
280   }
281   return true;
282 }
283 
284 bool ISD::isBuildVectorOfConstantFPSDNodes(const SDNode *N) {
285   if (N->getOpcode() != ISD::BUILD_VECTOR)
286     return false;
287 
288   for (const SDValue &Op : N->op_values()) {
289     if (Op.isUndef())
290       continue;
291     if (!isa<ConstantFPSDNode>(Op))
292       return false;
293   }
294   return true;
295 }
296 
297 bool ISD::allOperandsUndef(const SDNode *N) {
298   // Return false if the node has no operands.
299   // This is "logically inconsistent" with the definition of "all" but
300   // is probably the desired behavior.
301   if (N->getNumOperands() == 0)
302     return false;
303   return all_of(N->op_values(), [](SDValue Op) { return Op.isUndef(); });
304 }
305 
306 bool ISD::matchUnaryPredicate(SDValue Op,
307                               std::function<bool(ConstantSDNode *)> Match,
308                               bool AllowUndefs) {
309   // FIXME: Add support for scalar UNDEF cases?
310   if (auto *Cst = dyn_cast<ConstantSDNode>(Op))
311     return Match(Cst);
312 
313   // FIXME: Add support for vector UNDEF cases?
314   if (ISD::BUILD_VECTOR != Op.getOpcode() &&
315       ISD::SPLAT_VECTOR != Op.getOpcode())
316     return false;
317 
318   EVT SVT = Op.getValueType().getScalarType();
319   for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
320     if (AllowUndefs && Op.getOperand(i).isUndef()) {
321       if (!Match(nullptr))
322         return false;
323       continue;
324     }
325 
326     auto *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(i));
327     if (!Cst || Cst->getValueType(0) != SVT || !Match(Cst))
328       return false;
329   }
330   return true;
331 }
332 
333 bool ISD::matchBinaryPredicate(
334     SDValue LHS, SDValue RHS,
335     std::function<bool(ConstantSDNode *, ConstantSDNode *)> Match,
336     bool AllowUndefs, bool AllowTypeMismatch) {
337   if (!AllowTypeMismatch && LHS.getValueType() != RHS.getValueType())
338     return false;
339 
340   // TODO: Add support for scalar UNDEF cases?
341   if (auto *LHSCst = dyn_cast<ConstantSDNode>(LHS))
342     if (auto *RHSCst = dyn_cast<ConstantSDNode>(RHS))
343       return Match(LHSCst, RHSCst);
344 
345   // TODO: Add support for vector UNDEF cases?
346   if (LHS.getOpcode() != RHS.getOpcode() ||
347       (LHS.getOpcode() != ISD::BUILD_VECTOR &&
348        LHS.getOpcode() != ISD::SPLAT_VECTOR))
349     return false;
350 
351   EVT SVT = LHS.getValueType().getScalarType();
352   for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
353     SDValue LHSOp = LHS.getOperand(i);
354     SDValue RHSOp = RHS.getOperand(i);
355     bool LHSUndef = AllowUndefs && LHSOp.isUndef();
356     bool RHSUndef = AllowUndefs && RHSOp.isUndef();
357     auto *LHSCst = dyn_cast<ConstantSDNode>(LHSOp);
358     auto *RHSCst = dyn_cast<ConstantSDNode>(RHSOp);
359     if ((!LHSCst && !LHSUndef) || (!RHSCst && !RHSUndef))
360       return false;
361     if (!AllowTypeMismatch && (LHSOp.getValueType() != SVT ||
362                                LHSOp.getValueType() != RHSOp.getValueType()))
363       return false;
364     if (!Match(LHSCst, RHSCst))
365       return false;
366   }
367   return true;
368 }
369 
370 ISD::NodeType ISD::getVecReduceBaseOpcode(unsigned VecReduceOpcode) {
371   switch (VecReduceOpcode) {
372   default:
373     llvm_unreachable("Expected VECREDUCE opcode");
374   case ISD::VECREDUCE_FADD:
375   case ISD::VECREDUCE_SEQ_FADD:
376     return ISD::FADD;
377   case ISD::VECREDUCE_FMUL:
378   case ISD::VECREDUCE_SEQ_FMUL:
379     return ISD::FMUL;
380   case ISD::VECREDUCE_ADD:
381     return ISD::ADD;
382   case ISD::VECREDUCE_MUL:
383     return ISD::MUL;
384   case ISD::VECREDUCE_AND:
385     return ISD::AND;
386   case ISD::VECREDUCE_OR:
387     return ISD::OR;
388   case ISD::VECREDUCE_XOR:
389     return ISD::XOR;
390   case ISD::VECREDUCE_SMAX:
391     return ISD::SMAX;
392   case ISD::VECREDUCE_SMIN:
393     return ISD::SMIN;
394   case ISD::VECREDUCE_UMAX:
395     return ISD::UMAX;
396   case ISD::VECREDUCE_UMIN:
397     return ISD::UMIN;
398   case ISD::VECREDUCE_FMAX:
399     return ISD::FMAXNUM;
400   case ISD::VECREDUCE_FMIN:
401     return ISD::FMINNUM;
402   }
403 }
404 
405 bool ISD::isVPOpcode(unsigned Opcode) {
406   switch (Opcode) {
407   default:
408     return false;
409 #define BEGIN_REGISTER_VP_SDNODE(SDOPC, ...)                                   \
410   case ISD::SDOPC:                                                             \
411     return true;
412 #include "llvm/IR/VPIntrinsics.def"
413   }
414 }
415 
416 bool ISD::isVPBinaryOp(unsigned Opcode) {
417   switch (Opcode) {
418   default:
419     return false;
420 #define PROPERTY_VP_BINARYOP_SDNODE(SDOPC)                                     \
421   case ISD::SDOPC:                                                             \
422     return true;
423 #include "llvm/IR/VPIntrinsics.def"
424   }
425 }
426 
427 bool ISD::isVPReduction(unsigned Opcode) {
428   switch (Opcode) {
429   default:
430     return false;
431 #define PROPERTY_VP_REDUCTION_SDNODE(SDOPC)                                    \
432   case ISD::SDOPC:                                                             \
433     return true;
434 #include "llvm/IR/VPIntrinsics.def"
435   }
436 }
437 
438 /// The operand position of the vector mask.
439 Optional<unsigned> ISD::getVPMaskIdx(unsigned Opcode) {
440   switch (Opcode) {
441   default:
442     return None;
443 #define BEGIN_REGISTER_VP_SDNODE(SDOPC, LEGALPOS, TDNAME, MASKPOS, ...)        \
444   case ISD::SDOPC:                                                             \
445     return MASKPOS;
446 #include "llvm/IR/VPIntrinsics.def"
447   }
448 }
449 
450 /// The operand position of the explicit vector length parameter.
451 Optional<unsigned> ISD::getVPExplicitVectorLengthIdx(unsigned Opcode) {
452   switch (Opcode) {
453   default:
454     return None;
455 #define BEGIN_REGISTER_VP_SDNODE(SDOPC, LEGALPOS, TDNAME, MASKPOS, EVLPOS)     \
456   case ISD::SDOPC:                                                             \
457     return EVLPOS;
458 #include "llvm/IR/VPIntrinsics.def"
459   }
460 }
461 
462 ISD::NodeType ISD::getExtForLoadExtType(bool IsFP, ISD::LoadExtType ExtType) {
463   switch (ExtType) {
464   case ISD::EXTLOAD:
465     return IsFP ? ISD::FP_EXTEND : ISD::ANY_EXTEND;
466   case ISD::SEXTLOAD:
467     return ISD::SIGN_EXTEND;
468   case ISD::ZEXTLOAD:
469     return ISD::ZERO_EXTEND;
470   default:
471     break;
472   }
473 
474   llvm_unreachable("Invalid LoadExtType");
475 }
476 
477 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) {
478   // To perform this operation, we just need to swap the L and G bits of the
479   // operation.
480   unsigned OldL = (Operation >> 2) & 1;
481   unsigned OldG = (Operation >> 1) & 1;
482   return ISD::CondCode((Operation & ~6) |  // Keep the N, U, E bits
483                        (OldL << 1) |       // New G bit
484                        (OldG << 2));       // New L bit.
485 }
486 
487 static ISD::CondCode getSetCCInverseImpl(ISD::CondCode Op, bool isIntegerLike) {
488   unsigned Operation = Op;
489   if (isIntegerLike)
490     Operation ^= 7;   // Flip L, G, E bits, but not U.
491   else
492     Operation ^= 15;  // Flip all of the condition bits.
493 
494   if (Operation > ISD::SETTRUE2)
495     Operation &= ~8;  // Don't let N and U bits get set.
496 
497   return ISD::CondCode(Operation);
498 }
499 
500 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, EVT Type) {
501   return getSetCCInverseImpl(Op, Type.isInteger());
502 }
503 
504 ISD::CondCode ISD::GlobalISel::getSetCCInverse(ISD::CondCode Op,
505                                                bool isIntegerLike) {
506   return getSetCCInverseImpl(Op, isIntegerLike);
507 }
508 
509 /// For an integer comparison, return 1 if the comparison is a signed operation
510 /// and 2 if the result is an unsigned comparison. Return zero if the operation
511 /// does not depend on the sign of the input (setne and seteq).
512 static int isSignedOp(ISD::CondCode Opcode) {
513   switch (Opcode) {
514   default: llvm_unreachable("Illegal integer setcc operation!");
515   case ISD::SETEQ:
516   case ISD::SETNE: return 0;
517   case ISD::SETLT:
518   case ISD::SETLE:
519   case ISD::SETGT:
520   case ISD::SETGE: return 1;
521   case ISD::SETULT:
522   case ISD::SETULE:
523   case ISD::SETUGT:
524   case ISD::SETUGE: return 2;
525   }
526 }
527 
528 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2,
529                                        EVT Type) {
530   bool IsInteger = Type.isInteger();
531   if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
532     // Cannot fold a signed integer setcc with an unsigned integer setcc.
533     return ISD::SETCC_INVALID;
534 
535   unsigned Op = Op1 | Op2;  // Combine all of the condition bits.
536 
537   // If the N and U bits get set, then the resultant comparison DOES suddenly
538   // care about orderedness, and it is true when ordered.
539   if (Op > ISD::SETTRUE2)
540     Op &= ~16;     // Clear the U bit if the N bit is set.
541 
542   // Canonicalize illegal integer setcc's.
543   if (IsInteger && Op == ISD::SETUNE)  // e.g. SETUGT | SETULT
544     Op = ISD::SETNE;
545 
546   return ISD::CondCode(Op);
547 }
548 
549 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2,
550                                         EVT Type) {
551   bool IsInteger = Type.isInteger();
552   if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
553     // Cannot fold a signed setcc with an unsigned setcc.
554     return ISD::SETCC_INVALID;
555 
556   // Combine all of the condition bits.
557   ISD::CondCode Result = ISD::CondCode(Op1 & Op2);
558 
559   // Canonicalize illegal integer setcc's.
560   if (IsInteger) {
561     switch (Result) {
562     default: break;
563     case ISD::SETUO : Result = ISD::SETFALSE; break;  // SETUGT & SETULT
564     case ISD::SETOEQ:                                 // SETEQ  & SETU[LG]E
565     case ISD::SETUEQ: Result = ISD::SETEQ   ; break;  // SETUGE & SETULE
566     case ISD::SETOLT: Result = ISD::SETULT  ; break;  // SETULT & SETNE
567     case ISD::SETOGT: Result = ISD::SETUGT  ; break;  // SETUGT & SETNE
568     }
569   }
570 
571   return Result;
572 }
573 
574 //===----------------------------------------------------------------------===//
575 //                           SDNode Profile Support
576 //===----------------------------------------------------------------------===//
577 
578 /// AddNodeIDOpcode - Add the node opcode to the NodeID data.
579 static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC)  {
580   ID.AddInteger(OpC);
581 }
582 
583 /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them
584 /// solely with their pointer.
585 static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) {
586   ID.AddPointer(VTList.VTs);
587 }
588 
589 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
590 static void AddNodeIDOperands(FoldingSetNodeID &ID,
591                               ArrayRef<SDValue> Ops) {
592   for (auto& Op : Ops) {
593     ID.AddPointer(Op.getNode());
594     ID.AddInteger(Op.getResNo());
595   }
596 }
597 
598 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
599 static void AddNodeIDOperands(FoldingSetNodeID &ID,
600                               ArrayRef<SDUse> Ops) {
601   for (auto& Op : Ops) {
602     ID.AddPointer(Op.getNode());
603     ID.AddInteger(Op.getResNo());
604   }
605 }
606 
607 static void AddNodeIDNode(FoldingSetNodeID &ID, unsigned short OpC,
608                           SDVTList VTList, ArrayRef<SDValue> OpList) {
609   AddNodeIDOpcode(ID, OpC);
610   AddNodeIDValueTypes(ID, VTList);
611   AddNodeIDOperands(ID, OpList);
612 }
613 
614 /// If this is an SDNode with special info, add this info to the NodeID data.
615 static void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N) {
616   switch (N->getOpcode()) {
617   case ISD::TargetExternalSymbol:
618   case ISD::ExternalSymbol:
619   case ISD::MCSymbol:
620     llvm_unreachable("Should only be used on nodes with operands");
621   default: break;  // Normal nodes don't need extra info.
622   case ISD::TargetConstant:
623   case ISD::Constant: {
624     const ConstantSDNode *C = cast<ConstantSDNode>(N);
625     ID.AddPointer(C->getConstantIntValue());
626     ID.AddBoolean(C->isOpaque());
627     break;
628   }
629   case ISD::TargetConstantFP:
630   case ISD::ConstantFP:
631     ID.AddPointer(cast<ConstantFPSDNode>(N)->getConstantFPValue());
632     break;
633   case ISD::TargetGlobalAddress:
634   case ISD::GlobalAddress:
635   case ISD::TargetGlobalTLSAddress:
636   case ISD::GlobalTLSAddress: {
637     const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
638     ID.AddPointer(GA->getGlobal());
639     ID.AddInteger(GA->getOffset());
640     ID.AddInteger(GA->getTargetFlags());
641     break;
642   }
643   case ISD::BasicBlock:
644     ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock());
645     break;
646   case ISD::Register:
647     ID.AddInteger(cast<RegisterSDNode>(N)->getReg());
648     break;
649   case ISD::RegisterMask:
650     ID.AddPointer(cast<RegisterMaskSDNode>(N)->getRegMask());
651     break;
652   case ISD::SRCVALUE:
653     ID.AddPointer(cast<SrcValueSDNode>(N)->getValue());
654     break;
655   case ISD::FrameIndex:
656   case ISD::TargetFrameIndex:
657     ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex());
658     break;
659   case ISD::LIFETIME_START:
660   case ISD::LIFETIME_END:
661     if (cast<LifetimeSDNode>(N)->hasOffset()) {
662       ID.AddInteger(cast<LifetimeSDNode>(N)->getSize());
663       ID.AddInteger(cast<LifetimeSDNode>(N)->getOffset());
664     }
665     break;
666   case ISD::PSEUDO_PROBE:
667     ID.AddInteger(cast<PseudoProbeSDNode>(N)->getGuid());
668     ID.AddInteger(cast<PseudoProbeSDNode>(N)->getIndex());
669     ID.AddInteger(cast<PseudoProbeSDNode>(N)->getAttributes());
670     break;
671   case ISD::JumpTable:
672   case ISD::TargetJumpTable:
673     ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex());
674     ID.AddInteger(cast<JumpTableSDNode>(N)->getTargetFlags());
675     break;
676   case ISD::ConstantPool:
677   case ISD::TargetConstantPool: {
678     const ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N);
679     ID.AddInteger(CP->getAlign().value());
680     ID.AddInteger(CP->getOffset());
681     if (CP->isMachineConstantPoolEntry())
682       CP->getMachineCPVal()->addSelectionDAGCSEId(ID);
683     else
684       ID.AddPointer(CP->getConstVal());
685     ID.AddInteger(CP->getTargetFlags());
686     break;
687   }
688   case ISD::TargetIndex: {
689     const TargetIndexSDNode *TI = cast<TargetIndexSDNode>(N);
690     ID.AddInteger(TI->getIndex());
691     ID.AddInteger(TI->getOffset());
692     ID.AddInteger(TI->getTargetFlags());
693     break;
694   }
695   case ISD::LOAD: {
696     const LoadSDNode *LD = cast<LoadSDNode>(N);
697     ID.AddInteger(LD->getMemoryVT().getRawBits());
698     ID.AddInteger(LD->getRawSubclassData());
699     ID.AddInteger(LD->getPointerInfo().getAddrSpace());
700     break;
701   }
702   case ISD::STORE: {
703     const StoreSDNode *ST = cast<StoreSDNode>(N);
704     ID.AddInteger(ST->getMemoryVT().getRawBits());
705     ID.AddInteger(ST->getRawSubclassData());
706     ID.AddInteger(ST->getPointerInfo().getAddrSpace());
707     break;
708   }
709   case ISD::VP_LOAD: {
710     const VPLoadSDNode *ELD = cast<VPLoadSDNode>(N);
711     ID.AddInteger(ELD->getMemoryVT().getRawBits());
712     ID.AddInteger(ELD->getRawSubclassData());
713     ID.AddInteger(ELD->getPointerInfo().getAddrSpace());
714     break;
715   }
716   case ISD::VP_STORE: {
717     const VPStoreSDNode *EST = cast<VPStoreSDNode>(N);
718     ID.AddInteger(EST->getMemoryVT().getRawBits());
719     ID.AddInteger(EST->getRawSubclassData());
720     ID.AddInteger(EST->getPointerInfo().getAddrSpace());
721     break;
722   }
723   case ISD::VP_GATHER: {
724     const VPGatherSDNode *EG = cast<VPGatherSDNode>(N);
725     ID.AddInteger(EG->getMemoryVT().getRawBits());
726     ID.AddInteger(EG->getRawSubclassData());
727     ID.AddInteger(EG->getPointerInfo().getAddrSpace());
728     break;
729   }
730   case ISD::VP_SCATTER: {
731     const VPScatterSDNode *ES = cast<VPScatterSDNode>(N);
732     ID.AddInteger(ES->getMemoryVT().getRawBits());
733     ID.AddInteger(ES->getRawSubclassData());
734     ID.AddInteger(ES->getPointerInfo().getAddrSpace());
735     break;
736   }
737   case ISD::MLOAD: {
738     const MaskedLoadSDNode *MLD = cast<MaskedLoadSDNode>(N);
739     ID.AddInteger(MLD->getMemoryVT().getRawBits());
740     ID.AddInteger(MLD->getRawSubclassData());
741     ID.AddInteger(MLD->getPointerInfo().getAddrSpace());
742     break;
743   }
744   case ISD::MSTORE: {
745     const MaskedStoreSDNode *MST = cast<MaskedStoreSDNode>(N);
746     ID.AddInteger(MST->getMemoryVT().getRawBits());
747     ID.AddInteger(MST->getRawSubclassData());
748     ID.AddInteger(MST->getPointerInfo().getAddrSpace());
749     break;
750   }
751   case ISD::MGATHER: {
752     const MaskedGatherSDNode *MG = cast<MaskedGatherSDNode>(N);
753     ID.AddInteger(MG->getMemoryVT().getRawBits());
754     ID.AddInteger(MG->getRawSubclassData());
755     ID.AddInteger(MG->getPointerInfo().getAddrSpace());
756     break;
757   }
758   case ISD::MSCATTER: {
759     const MaskedScatterSDNode *MS = cast<MaskedScatterSDNode>(N);
760     ID.AddInteger(MS->getMemoryVT().getRawBits());
761     ID.AddInteger(MS->getRawSubclassData());
762     ID.AddInteger(MS->getPointerInfo().getAddrSpace());
763     break;
764   }
765   case ISD::ATOMIC_CMP_SWAP:
766   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
767   case ISD::ATOMIC_SWAP:
768   case ISD::ATOMIC_LOAD_ADD:
769   case ISD::ATOMIC_LOAD_SUB:
770   case ISD::ATOMIC_LOAD_AND:
771   case ISD::ATOMIC_LOAD_CLR:
772   case ISD::ATOMIC_LOAD_OR:
773   case ISD::ATOMIC_LOAD_XOR:
774   case ISD::ATOMIC_LOAD_NAND:
775   case ISD::ATOMIC_LOAD_MIN:
776   case ISD::ATOMIC_LOAD_MAX:
777   case ISD::ATOMIC_LOAD_UMIN:
778   case ISD::ATOMIC_LOAD_UMAX:
779   case ISD::ATOMIC_LOAD:
780   case ISD::ATOMIC_STORE: {
781     const AtomicSDNode *AT = cast<AtomicSDNode>(N);
782     ID.AddInteger(AT->getMemoryVT().getRawBits());
783     ID.AddInteger(AT->getRawSubclassData());
784     ID.AddInteger(AT->getPointerInfo().getAddrSpace());
785     break;
786   }
787   case ISD::PREFETCH: {
788     const MemSDNode *PF = cast<MemSDNode>(N);
789     ID.AddInteger(PF->getPointerInfo().getAddrSpace());
790     break;
791   }
792   case ISD::VECTOR_SHUFFLE: {
793     const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
794     for (unsigned i = 0, e = N->getValueType(0).getVectorNumElements();
795          i != e; ++i)
796       ID.AddInteger(SVN->getMaskElt(i));
797     break;
798   }
799   case ISD::TargetBlockAddress:
800   case ISD::BlockAddress: {
801     const BlockAddressSDNode *BA = cast<BlockAddressSDNode>(N);
802     ID.AddPointer(BA->getBlockAddress());
803     ID.AddInteger(BA->getOffset());
804     ID.AddInteger(BA->getTargetFlags());
805     break;
806   }
807   } // end switch (N->getOpcode())
808 
809   // Target specific memory nodes could also have address spaces to check.
810   if (N->isTargetMemoryOpcode())
811     ID.AddInteger(cast<MemSDNode>(N)->getPointerInfo().getAddrSpace());
812 }
813 
814 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID
815 /// data.
816 static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) {
817   AddNodeIDOpcode(ID, N->getOpcode());
818   // Add the return value info.
819   AddNodeIDValueTypes(ID, N->getVTList());
820   // Add the operand info.
821   AddNodeIDOperands(ID, N->ops());
822 
823   // Handle SDNode leafs with special info.
824   AddNodeIDCustom(ID, N);
825 }
826 
827 //===----------------------------------------------------------------------===//
828 //                              SelectionDAG Class
829 //===----------------------------------------------------------------------===//
830 
831 /// doNotCSE - Return true if CSE should not be performed for this node.
832 static bool doNotCSE(SDNode *N) {
833   if (N->getValueType(0) == MVT::Glue)
834     return true; // Never CSE anything that produces a flag.
835 
836   switch (N->getOpcode()) {
837   default: break;
838   case ISD::HANDLENODE:
839   case ISD::EH_LABEL:
840     return true;   // Never CSE these nodes.
841   }
842 
843   // Check that remaining values produced are not flags.
844   for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
845     if (N->getValueType(i) == MVT::Glue)
846       return true; // Never CSE anything that produces a flag.
847 
848   return false;
849 }
850 
851 /// RemoveDeadNodes - This method deletes all unreachable nodes in the
852 /// SelectionDAG.
853 void SelectionDAG::RemoveDeadNodes() {
854   // Create a dummy node (which is not added to allnodes), that adds a reference
855   // to the root node, preventing it from being deleted.
856   HandleSDNode Dummy(getRoot());
857 
858   SmallVector<SDNode*, 128> DeadNodes;
859 
860   // Add all obviously-dead nodes to the DeadNodes worklist.
861   for (SDNode &Node : allnodes())
862     if (Node.use_empty())
863       DeadNodes.push_back(&Node);
864 
865   RemoveDeadNodes(DeadNodes);
866 
867   // If the root changed (e.g. it was a dead load, update the root).
868   setRoot(Dummy.getValue());
869 }
870 
871 /// RemoveDeadNodes - This method deletes the unreachable nodes in the
872 /// given list, and any nodes that become unreachable as a result.
873 void SelectionDAG::RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes) {
874 
875   // Process the worklist, deleting the nodes and adding their uses to the
876   // worklist.
877   while (!DeadNodes.empty()) {
878     SDNode *N = DeadNodes.pop_back_val();
879     // Skip to next node if we've already managed to delete the node. This could
880     // happen if replacing a node causes a node previously added to the node to
881     // be deleted.
882     if (N->getOpcode() == ISD::DELETED_NODE)
883       continue;
884 
885     for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
886       DUL->NodeDeleted(N, nullptr);
887 
888     // Take the node out of the appropriate CSE map.
889     RemoveNodeFromCSEMaps(N);
890 
891     // Next, brutally remove the operand list.  This is safe to do, as there are
892     // no cycles in the graph.
893     for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
894       SDUse &Use = *I++;
895       SDNode *Operand = Use.getNode();
896       Use.set(SDValue());
897 
898       // Now that we removed this operand, see if there are no uses of it left.
899       if (Operand->use_empty())
900         DeadNodes.push_back(Operand);
901     }
902 
903     DeallocateNode(N);
904   }
905 }
906 
907 void SelectionDAG::RemoveDeadNode(SDNode *N){
908   SmallVector<SDNode*, 16> DeadNodes(1, N);
909 
910   // Create a dummy node that adds a reference to the root node, preventing
911   // it from being deleted.  (This matters if the root is an operand of the
912   // dead node.)
913   HandleSDNode Dummy(getRoot());
914 
915   RemoveDeadNodes(DeadNodes);
916 }
917 
918 void SelectionDAG::DeleteNode(SDNode *N) {
919   // First take this out of the appropriate CSE map.
920   RemoveNodeFromCSEMaps(N);
921 
922   // Finally, remove uses due to operands of this node, remove from the
923   // AllNodes list, and delete the node.
924   DeleteNodeNotInCSEMaps(N);
925 }
926 
927 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
928   assert(N->getIterator() != AllNodes.begin() &&
929          "Cannot delete the entry node!");
930   assert(N->use_empty() && "Cannot delete a node that is not dead!");
931 
932   // Drop all of the operands and decrement used node's use counts.
933   N->DropOperands();
934 
935   DeallocateNode(N);
936 }
937 
938 void SDDbgInfo::add(SDDbgValue *V, bool isParameter) {
939   assert(!(V->isVariadic() && isParameter));
940   if (isParameter)
941     ByvalParmDbgValues.push_back(V);
942   else
943     DbgValues.push_back(V);
944   for (const SDNode *Node : V->getSDNodes())
945     if (Node)
946       DbgValMap[Node].push_back(V);
947 }
948 
949 void SDDbgInfo::erase(const SDNode *Node) {
950   DbgValMapType::iterator I = DbgValMap.find(Node);
951   if (I == DbgValMap.end())
952     return;
953   for (auto &Val: I->second)
954     Val->setIsInvalidated();
955   DbgValMap.erase(I);
956 }
957 
958 void SelectionDAG::DeallocateNode(SDNode *N) {
959   // If we have operands, deallocate them.
960   removeOperands(N);
961 
962   NodeAllocator.Deallocate(AllNodes.remove(N));
963 
964   // Set the opcode to DELETED_NODE to help catch bugs when node
965   // memory is reallocated.
966   // FIXME: There are places in SDag that have grown a dependency on the opcode
967   // value in the released node.
968   __asan_unpoison_memory_region(&N->NodeType, sizeof(N->NodeType));
969   N->NodeType = ISD::DELETED_NODE;
970 
971   // If any of the SDDbgValue nodes refer to this SDNode, invalidate
972   // them and forget about that node.
973   DbgInfo->erase(N);
974 }
975 
976 #ifndef NDEBUG
977 /// VerifySDNode - Sanity check the given SDNode.  Aborts if it is invalid.
978 static void VerifySDNode(SDNode *N) {
979   switch (N->getOpcode()) {
980   default:
981     break;
982   case ISD::BUILD_PAIR: {
983     EVT VT = N->getValueType(0);
984     assert(N->getNumValues() == 1 && "Too many results!");
985     assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) &&
986            "Wrong return type!");
987     assert(N->getNumOperands() == 2 && "Wrong number of operands!");
988     assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() &&
989            "Mismatched operand types!");
990     assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() &&
991            "Wrong operand type!");
992     assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() &&
993            "Wrong return type size");
994     break;
995   }
996   case ISD::BUILD_VECTOR: {
997     assert(N->getNumValues() == 1 && "Too many results!");
998     assert(N->getValueType(0).isVector() && "Wrong return type!");
999     assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() &&
1000            "Wrong number of operands!");
1001     EVT EltVT = N->getValueType(0).getVectorElementType();
1002     for (const SDUse &Op : N->ops()) {
1003       assert((Op.getValueType() == EltVT ||
1004               (EltVT.isInteger() && Op.getValueType().isInteger() &&
1005                EltVT.bitsLE(Op.getValueType()))) &&
1006              "Wrong operand type!");
1007       assert(Op.getValueType() == N->getOperand(0).getValueType() &&
1008              "Operands must all have the same type");
1009     }
1010     break;
1011   }
1012   }
1013 }
1014 #endif // NDEBUG
1015 
1016 /// Insert a newly allocated node into the DAG.
1017 ///
1018 /// Handles insertion into the all nodes list and CSE map, as well as
1019 /// verification and other common operations when a new node is allocated.
1020 void SelectionDAG::InsertNode(SDNode *N) {
1021   AllNodes.push_back(N);
1022 #ifndef NDEBUG
1023   N->PersistentId = NextPersistentId++;
1024   VerifySDNode(N);
1025 #endif
1026   for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1027     DUL->NodeInserted(N);
1028 }
1029 
1030 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
1031 /// correspond to it.  This is useful when we're about to delete or repurpose
1032 /// the node.  We don't want future request for structurally identical nodes
1033 /// to return N anymore.
1034 bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
1035   bool Erased = false;
1036   switch (N->getOpcode()) {
1037   case ISD::HANDLENODE: return false;  // noop.
1038   case ISD::CONDCODE:
1039     assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
1040            "Cond code doesn't exist!");
1041     Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != nullptr;
1042     CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = nullptr;
1043     break;
1044   case ISD::ExternalSymbol:
1045     Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
1046     break;
1047   case ISD::TargetExternalSymbol: {
1048     ExternalSymbolSDNode *ESN = cast<ExternalSymbolSDNode>(N);
1049     Erased = TargetExternalSymbols.erase(std::pair<std::string, unsigned>(
1050         ESN->getSymbol(), ESN->getTargetFlags()));
1051     break;
1052   }
1053   case ISD::MCSymbol: {
1054     auto *MCSN = cast<MCSymbolSDNode>(N);
1055     Erased = MCSymbols.erase(MCSN->getMCSymbol());
1056     break;
1057   }
1058   case ISD::VALUETYPE: {
1059     EVT VT = cast<VTSDNode>(N)->getVT();
1060     if (VT.isExtended()) {
1061       Erased = ExtendedValueTypeNodes.erase(VT);
1062     } else {
1063       Erased = ValueTypeNodes[VT.getSimpleVT().SimpleTy] != nullptr;
1064       ValueTypeNodes[VT.getSimpleVT().SimpleTy] = nullptr;
1065     }
1066     break;
1067   }
1068   default:
1069     // Remove it from the CSE Map.
1070     assert(N->getOpcode() != ISD::DELETED_NODE && "DELETED_NODE in CSEMap!");
1071     assert(N->getOpcode() != ISD::EntryToken && "EntryToken in CSEMap!");
1072     Erased = CSEMap.RemoveNode(N);
1073     break;
1074   }
1075 #ifndef NDEBUG
1076   // Verify that the node was actually in one of the CSE maps, unless it has a
1077   // flag result (which cannot be CSE'd) or is one of the special cases that are
1078   // not subject to CSE.
1079   if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Glue &&
1080       !N->isMachineOpcode() && !doNotCSE(N)) {
1081     N->dump(this);
1082     dbgs() << "\n";
1083     llvm_unreachable("Node is not in map!");
1084   }
1085 #endif
1086   return Erased;
1087 }
1088 
1089 /// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE
1090 /// maps and modified in place. Add it back to the CSE maps, unless an identical
1091 /// node already exists, in which case transfer all its users to the existing
1092 /// node. This transfer can potentially trigger recursive merging.
1093 void
1094 SelectionDAG::AddModifiedNodeToCSEMaps(SDNode *N) {
1095   // For node types that aren't CSE'd, just act as if no identical node
1096   // already exists.
1097   if (!doNotCSE(N)) {
1098     SDNode *Existing = CSEMap.GetOrInsertNode(N);
1099     if (Existing != N) {
1100       // If there was already an existing matching node, use ReplaceAllUsesWith
1101       // to replace the dead one with the existing one.  This can cause
1102       // recursive merging of other unrelated nodes down the line.
1103       ReplaceAllUsesWith(N, Existing);
1104 
1105       // N is now dead. Inform the listeners and delete it.
1106       for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1107         DUL->NodeDeleted(N, Existing);
1108       DeleteNodeNotInCSEMaps(N);
1109       return;
1110     }
1111   }
1112 
1113   // If the node doesn't already exist, we updated it.  Inform listeners.
1114   for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1115     DUL->NodeUpdated(N);
1116 }
1117 
1118 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1119 /// were replaced with those specified.  If this node is never memoized,
1120 /// return null, otherwise return a pointer to the slot it would take.  If a
1121 /// node already exists with these operands, the slot will be non-null.
1122 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op,
1123                                            void *&InsertPos) {
1124   if (doNotCSE(N))
1125     return nullptr;
1126 
1127   SDValue Ops[] = { Op };
1128   FoldingSetNodeID ID;
1129   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1130   AddNodeIDCustom(ID, N);
1131   SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1132   if (Node)
1133     Node->intersectFlagsWith(N->getFlags());
1134   return Node;
1135 }
1136 
1137 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1138 /// were replaced with those specified.  If this node is never memoized,
1139 /// return null, otherwise return a pointer to the slot it would take.  If a
1140 /// node already exists with these operands, the slot will be non-null.
1141 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
1142                                            SDValue Op1, SDValue Op2,
1143                                            void *&InsertPos) {
1144   if (doNotCSE(N))
1145     return nullptr;
1146 
1147   SDValue Ops[] = { Op1, Op2 };
1148   FoldingSetNodeID ID;
1149   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1150   AddNodeIDCustom(ID, N);
1151   SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1152   if (Node)
1153     Node->intersectFlagsWith(N->getFlags());
1154   return Node;
1155 }
1156 
1157 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1158 /// were replaced with those specified.  If this node is never memoized,
1159 /// return null, otherwise return a pointer to the slot it would take.  If a
1160 /// node already exists with these operands, the slot will be non-null.
1161 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, ArrayRef<SDValue> Ops,
1162                                            void *&InsertPos) {
1163   if (doNotCSE(N))
1164     return nullptr;
1165 
1166   FoldingSetNodeID ID;
1167   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1168   AddNodeIDCustom(ID, N);
1169   SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1170   if (Node)
1171     Node->intersectFlagsWith(N->getFlags());
1172   return Node;
1173 }
1174 
1175 Align SelectionDAG::getEVTAlign(EVT VT) const {
1176   Type *Ty = VT == MVT::iPTR ?
1177                    PointerType::get(Type::getInt8Ty(*getContext()), 0) :
1178                    VT.getTypeForEVT(*getContext());
1179 
1180   return getDataLayout().getABITypeAlign(Ty);
1181 }
1182 
1183 // EntryNode could meaningfully have debug info if we can find it...
1184 SelectionDAG::SelectionDAG(const TargetMachine &tm, CodeGenOpt::Level OL)
1185     : TM(tm), OptLevel(OL),
1186       EntryNode(ISD::EntryToken, 0, DebugLoc(), getVTList(MVT::Other)),
1187       Root(getEntryNode()) {
1188   InsertNode(&EntryNode);
1189   DbgInfo = new SDDbgInfo();
1190 }
1191 
1192 void SelectionDAG::init(MachineFunction &NewMF,
1193                         OptimizationRemarkEmitter &NewORE,
1194                         Pass *PassPtr, const TargetLibraryInfo *LibraryInfo,
1195                         LegacyDivergenceAnalysis * Divergence,
1196                         ProfileSummaryInfo *PSIin,
1197                         BlockFrequencyInfo *BFIin) {
1198   MF = &NewMF;
1199   SDAGISelPass = PassPtr;
1200   ORE = &NewORE;
1201   TLI = getSubtarget().getTargetLowering();
1202   TSI = getSubtarget().getSelectionDAGInfo();
1203   LibInfo = LibraryInfo;
1204   Context = &MF->getFunction().getContext();
1205   DA = Divergence;
1206   PSI = PSIin;
1207   BFI = BFIin;
1208 }
1209 
1210 SelectionDAG::~SelectionDAG() {
1211   assert(!UpdateListeners && "Dangling registered DAGUpdateListeners");
1212   allnodes_clear();
1213   OperandRecycler.clear(OperandAllocator);
1214   delete DbgInfo;
1215 }
1216 
1217 bool SelectionDAG::shouldOptForSize() const {
1218   return MF->getFunction().hasOptSize() ||
1219       llvm::shouldOptimizeForSize(FLI->MBB->getBasicBlock(), PSI, BFI);
1220 }
1221 
1222 void SelectionDAG::allnodes_clear() {
1223   assert(&*AllNodes.begin() == &EntryNode);
1224   AllNodes.remove(AllNodes.begin());
1225   while (!AllNodes.empty())
1226     DeallocateNode(&AllNodes.front());
1227 #ifndef NDEBUG
1228   NextPersistentId = 0;
1229 #endif
1230 }
1231 
1232 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
1233                                           void *&InsertPos) {
1234   SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
1235   if (N) {
1236     switch (N->getOpcode()) {
1237     default: break;
1238     case ISD::Constant:
1239     case ISD::ConstantFP:
1240       llvm_unreachable("Querying for Constant and ConstantFP nodes requires "
1241                        "debug location.  Use another overload.");
1242     }
1243   }
1244   return N;
1245 }
1246 
1247 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
1248                                           const SDLoc &DL, void *&InsertPos) {
1249   SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
1250   if (N) {
1251     switch (N->getOpcode()) {
1252     case ISD::Constant:
1253     case ISD::ConstantFP:
1254       // Erase debug location from the node if the node is used at several
1255       // different places. Do not propagate one location to all uses as it
1256       // will cause a worse single stepping debugging experience.
1257       if (N->getDebugLoc() != DL.getDebugLoc())
1258         N->setDebugLoc(DebugLoc());
1259       break;
1260     default:
1261       // When the node's point of use is located earlier in the instruction
1262       // sequence than its prior point of use, update its debug info to the
1263       // earlier location.
1264       if (DL.getIROrder() && DL.getIROrder() < N->getIROrder())
1265         N->setDebugLoc(DL.getDebugLoc());
1266       break;
1267     }
1268   }
1269   return N;
1270 }
1271 
1272 void SelectionDAG::clear() {
1273   allnodes_clear();
1274   OperandRecycler.clear(OperandAllocator);
1275   OperandAllocator.Reset();
1276   CSEMap.clear();
1277 
1278   ExtendedValueTypeNodes.clear();
1279   ExternalSymbols.clear();
1280   TargetExternalSymbols.clear();
1281   MCSymbols.clear();
1282   SDCallSiteDbgInfo.clear();
1283   std::fill(CondCodeNodes.begin(), CondCodeNodes.end(),
1284             static_cast<CondCodeSDNode*>(nullptr));
1285   std::fill(ValueTypeNodes.begin(), ValueTypeNodes.end(),
1286             static_cast<SDNode*>(nullptr));
1287 
1288   EntryNode.UseList = nullptr;
1289   InsertNode(&EntryNode);
1290   Root = getEntryNode();
1291   DbgInfo->clear();
1292 }
1293 
1294 SDValue SelectionDAG::getFPExtendOrRound(SDValue Op, const SDLoc &DL, EVT VT) {
1295   return VT.bitsGT(Op.getValueType())
1296              ? getNode(ISD::FP_EXTEND, DL, VT, Op)
1297              : getNode(ISD::FP_ROUND, DL, VT, Op, getIntPtrConstant(0, DL));
1298 }
1299 
1300 std::pair<SDValue, SDValue>
1301 SelectionDAG::getStrictFPExtendOrRound(SDValue Op, SDValue Chain,
1302                                        const SDLoc &DL, EVT VT) {
1303   assert(!VT.bitsEq(Op.getValueType()) &&
1304          "Strict no-op FP extend/round not allowed.");
1305   SDValue Res =
1306       VT.bitsGT(Op.getValueType())
1307           ? getNode(ISD::STRICT_FP_EXTEND, DL, {VT, MVT::Other}, {Chain, Op})
1308           : getNode(ISD::STRICT_FP_ROUND, DL, {VT, MVT::Other},
1309                     {Chain, Op, getIntPtrConstant(0, DL)});
1310 
1311   return std::pair<SDValue, SDValue>(Res, SDValue(Res.getNode(), 1));
1312 }
1313 
1314 SDValue SelectionDAG::getAnyExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1315   return VT.bitsGT(Op.getValueType()) ?
1316     getNode(ISD::ANY_EXTEND, DL, VT, Op) :
1317     getNode(ISD::TRUNCATE, DL, VT, Op);
1318 }
1319 
1320 SDValue SelectionDAG::getSExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1321   return VT.bitsGT(Op.getValueType()) ?
1322     getNode(ISD::SIGN_EXTEND, DL, VT, Op) :
1323     getNode(ISD::TRUNCATE, DL, VT, Op);
1324 }
1325 
1326 SDValue SelectionDAG::getZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1327   return VT.bitsGT(Op.getValueType()) ?
1328     getNode(ISD::ZERO_EXTEND, DL, VT, Op) :
1329     getNode(ISD::TRUNCATE, DL, VT, Op);
1330 }
1331 
1332 SDValue SelectionDAG::getBoolExtOrTrunc(SDValue Op, const SDLoc &SL, EVT VT,
1333                                         EVT OpVT) {
1334   if (VT.bitsLE(Op.getValueType()))
1335     return getNode(ISD::TRUNCATE, SL, VT, Op);
1336 
1337   TargetLowering::BooleanContent BType = TLI->getBooleanContents(OpVT);
1338   return getNode(TLI->getExtendForContent(BType), SL, VT, Op);
1339 }
1340 
1341 SDValue SelectionDAG::getZeroExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) {
1342   EVT OpVT = Op.getValueType();
1343   assert(VT.isInteger() && OpVT.isInteger() &&
1344          "Cannot getZeroExtendInReg FP types");
1345   assert(VT.isVector() == OpVT.isVector() &&
1346          "getZeroExtendInReg type should be vector iff the operand "
1347          "type is vector!");
1348   assert((!VT.isVector() ||
1349           VT.getVectorElementCount() == OpVT.getVectorElementCount()) &&
1350          "Vector element counts must match in getZeroExtendInReg");
1351   assert(VT.bitsLE(OpVT) && "Not extending!");
1352   if (OpVT == VT)
1353     return Op;
1354   APInt Imm = APInt::getLowBitsSet(OpVT.getScalarSizeInBits(),
1355                                    VT.getScalarSizeInBits());
1356   return getNode(ISD::AND, DL, OpVT, Op, getConstant(Imm, DL, OpVT));
1357 }
1358 
1359 SDValue SelectionDAG::getPtrExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1360   // Only unsigned pointer semantics are supported right now. In the future this
1361   // might delegate to TLI to check pointer signedness.
1362   return getZExtOrTrunc(Op, DL, VT);
1363 }
1364 
1365 SDValue SelectionDAG::getPtrExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) {
1366   // Only unsigned pointer semantics are supported right now. In the future this
1367   // might delegate to TLI to check pointer signedness.
1368   return getZeroExtendInReg(Op, DL, VT);
1369 }
1370 
1371 /// getNOT - Create a bitwise NOT operation as (XOR Val, -1).
1372 SDValue SelectionDAG::getNOT(const SDLoc &DL, SDValue Val, EVT VT) {
1373   return getNode(ISD::XOR, DL, VT, Val, getAllOnesConstant(DL, VT));
1374 }
1375 
1376 SDValue SelectionDAG::getLogicalNOT(const SDLoc &DL, SDValue Val, EVT VT) {
1377   SDValue TrueValue = getBoolConstant(true, DL, VT, VT);
1378   return getNode(ISD::XOR, DL, VT, Val, TrueValue);
1379 }
1380 
1381 SDValue SelectionDAG::getBoolConstant(bool V, const SDLoc &DL, EVT VT,
1382                                       EVT OpVT) {
1383   if (!V)
1384     return getConstant(0, DL, VT);
1385 
1386   switch (TLI->getBooleanContents(OpVT)) {
1387   case TargetLowering::ZeroOrOneBooleanContent:
1388   case TargetLowering::UndefinedBooleanContent:
1389     return getConstant(1, DL, VT);
1390   case TargetLowering::ZeroOrNegativeOneBooleanContent:
1391     return getAllOnesConstant(DL, VT);
1392   }
1393   llvm_unreachable("Unexpected boolean content enum!");
1394 }
1395 
1396 SDValue SelectionDAG::getConstant(uint64_t Val, const SDLoc &DL, EVT VT,
1397                                   bool isT, bool isO) {
1398   EVT EltVT = VT.getScalarType();
1399   assert((EltVT.getSizeInBits() >= 64 ||
1400           (uint64_t)((int64_t)Val >> EltVT.getSizeInBits()) + 1 < 2) &&
1401          "getConstant with a uint64_t value that doesn't fit in the type!");
1402   return getConstant(APInt(EltVT.getSizeInBits(), Val), DL, VT, isT, isO);
1403 }
1404 
1405 SDValue SelectionDAG::getConstant(const APInt &Val, const SDLoc &DL, EVT VT,
1406                                   bool isT, bool isO) {
1407   return getConstant(*ConstantInt::get(*Context, Val), DL, VT, isT, isO);
1408 }
1409 
1410 SDValue SelectionDAG::getConstant(const ConstantInt &Val, const SDLoc &DL,
1411                                   EVT VT, bool isT, bool isO) {
1412   assert(VT.isInteger() && "Cannot create FP integer constant!");
1413 
1414   EVT EltVT = VT.getScalarType();
1415   const ConstantInt *Elt = &Val;
1416 
1417   // In some cases the vector type is legal but the element type is illegal and
1418   // needs to be promoted, for example v8i8 on ARM.  In this case, promote the
1419   // inserted value (the type does not need to match the vector element type).
1420   // Any extra bits introduced will be truncated away.
1421   if (VT.isVector() && TLI->getTypeAction(*getContext(), EltVT) ==
1422                            TargetLowering::TypePromoteInteger) {
1423     EltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1424     APInt NewVal = Elt->getValue().zextOrTrunc(EltVT.getSizeInBits());
1425     Elt = ConstantInt::get(*getContext(), NewVal);
1426   }
1427   // In other cases the element type is illegal and needs to be expanded, for
1428   // example v2i64 on MIPS32. In this case, find the nearest legal type, split
1429   // the value into n parts and use a vector type with n-times the elements.
1430   // Then bitcast to the type requested.
1431   // Legalizing constants too early makes the DAGCombiner's job harder so we
1432   // only legalize if the DAG tells us we must produce legal types.
1433   else if (NewNodesMustHaveLegalTypes && VT.isVector() &&
1434            TLI->getTypeAction(*getContext(), EltVT) ==
1435                TargetLowering::TypeExpandInteger) {
1436     const APInt &NewVal = Elt->getValue();
1437     EVT ViaEltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1438     unsigned ViaEltSizeInBits = ViaEltVT.getSizeInBits();
1439 
1440     // For scalable vectors, try to use a SPLAT_VECTOR_PARTS node.
1441     if (VT.isScalableVector()) {
1442       assert(EltVT.getSizeInBits() % ViaEltSizeInBits == 0 &&
1443              "Can only handle an even split!");
1444       unsigned Parts = EltVT.getSizeInBits() / ViaEltSizeInBits;
1445 
1446       SmallVector<SDValue, 2> ScalarParts;
1447       for (unsigned i = 0; i != Parts; ++i)
1448         ScalarParts.push_back(getConstant(
1449             NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL,
1450             ViaEltVT, isT, isO));
1451 
1452       return getNode(ISD::SPLAT_VECTOR_PARTS, DL, VT, ScalarParts);
1453     }
1454 
1455     unsigned ViaVecNumElts = VT.getSizeInBits() / ViaEltSizeInBits;
1456     EVT ViaVecVT = EVT::getVectorVT(*getContext(), ViaEltVT, ViaVecNumElts);
1457 
1458     // Check the temporary vector is the correct size. If this fails then
1459     // getTypeToTransformTo() probably returned a type whose size (in bits)
1460     // isn't a power-of-2 factor of the requested type size.
1461     assert(ViaVecVT.getSizeInBits() == VT.getSizeInBits());
1462 
1463     SmallVector<SDValue, 2> EltParts;
1464     for (unsigned i = 0; i < ViaVecNumElts / VT.getVectorNumElements(); ++i)
1465       EltParts.push_back(getConstant(
1466           NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL,
1467           ViaEltVT, isT, isO));
1468 
1469     // EltParts is currently in little endian order. If we actually want
1470     // big-endian order then reverse it now.
1471     if (getDataLayout().isBigEndian())
1472       std::reverse(EltParts.begin(), EltParts.end());
1473 
1474     // The elements must be reversed when the element order is different
1475     // to the endianness of the elements (because the BITCAST is itself a
1476     // vector shuffle in this situation). However, we do not need any code to
1477     // perform this reversal because getConstant() is producing a vector
1478     // splat.
1479     // This situation occurs in MIPS MSA.
1480 
1481     SmallVector<SDValue, 8> Ops;
1482     for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
1483       llvm::append_range(Ops, EltParts);
1484 
1485     SDValue V =
1486         getNode(ISD::BITCAST, DL, VT, getBuildVector(ViaVecVT, DL, Ops));
1487     return V;
1488   }
1489 
1490   assert(Elt->getBitWidth() == EltVT.getSizeInBits() &&
1491          "APInt size does not match type size!");
1492   unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
1493   FoldingSetNodeID ID;
1494   AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
1495   ID.AddPointer(Elt);
1496   ID.AddBoolean(isO);
1497   void *IP = nullptr;
1498   SDNode *N = nullptr;
1499   if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1500     if (!VT.isVector())
1501       return SDValue(N, 0);
1502 
1503   if (!N) {
1504     N = newSDNode<ConstantSDNode>(isT, isO, Elt, EltVT);
1505     CSEMap.InsertNode(N, IP);
1506     InsertNode(N);
1507     NewSDValueDbgMsg(SDValue(N, 0), "Creating constant: ", this);
1508   }
1509 
1510   SDValue Result(N, 0);
1511   if (VT.isScalableVector())
1512     Result = getSplatVector(VT, DL, Result);
1513   else if (VT.isVector())
1514     Result = getSplatBuildVector(VT, DL, Result);
1515 
1516   return Result;
1517 }
1518 
1519 SDValue SelectionDAG::getIntPtrConstant(uint64_t Val, const SDLoc &DL,
1520                                         bool isTarget) {
1521   return getConstant(Val, DL, TLI->getPointerTy(getDataLayout()), isTarget);
1522 }
1523 
1524 SDValue SelectionDAG::getShiftAmountConstant(uint64_t Val, EVT VT,
1525                                              const SDLoc &DL, bool LegalTypes) {
1526   assert(VT.isInteger() && "Shift amount is not an integer type!");
1527   EVT ShiftVT = TLI->getShiftAmountTy(VT, getDataLayout(), LegalTypes);
1528   return getConstant(Val, DL, ShiftVT);
1529 }
1530 
1531 SDValue SelectionDAG::getVectorIdxConstant(uint64_t Val, const SDLoc &DL,
1532                                            bool isTarget) {
1533   return getConstant(Val, DL, TLI->getVectorIdxTy(getDataLayout()), isTarget);
1534 }
1535 
1536 SDValue SelectionDAG::getConstantFP(const APFloat &V, const SDLoc &DL, EVT VT,
1537                                     bool isTarget) {
1538   return getConstantFP(*ConstantFP::get(*getContext(), V), DL, VT, isTarget);
1539 }
1540 
1541 SDValue SelectionDAG::getConstantFP(const ConstantFP &V, const SDLoc &DL,
1542                                     EVT VT, bool isTarget) {
1543   assert(VT.isFloatingPoint() && "Cannot create integer FP constant!");
1544 
1545   EVT EltVT = VT.getScalarType();
1546 
1547   // Do the map lookup using the actual bit pattern for the floating point
1548   // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
1549   // we don't have issues with SNANs.
1550   unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
1551   FoldingSetNodeID ID;
1552   AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
1553   ID.AddPointer(&V);
1554   void *IP = nullptr;
1555   SDNode *N = nullptr;
1556   if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1557     if (!VT.isVector())
1558       return SDValue(N, 0);
1559 
1560   if (!N) {
1561     N = newSDNode<ConstantFPSDNode>(isTarget, &V, EltVT);
1562     CSEMap.InsertNode(N, IP);
1563     InsertNode(N);
1564   }
1565 
1566   SDValue Result(N, 0);
1567   if (VT.isScalableVector())
1568     Result = getSplatVector(VT, DL, Result);
1569   else if (VT.isVector())
1570     Result = getSplatBuildVector(VT, DL, Result);
1571   NewSDValueDbgMsg(Result, "Creating fp constant: ", this);
1572   return Result;
1573 }
1574 
1575 SDValue SelectionDAG::getConstantFP(double Val, const SDLoc &DL, EVT VT,
1576                                     bool isTarget) {
1577   EVT EltVT = VT.getScalarType();
1578   if (EltVT == MVT::f32)
1579     return getConstantFP(APFloat((float)Val), DL, VT, isTarget);
1580   if (EltVT == MVT::f64)
1581     return getConstantFP(APFloat(Val), DL, VT, isTarget);
1582   if (EltVT == MVT::f80 || EltVT == MVT::f128 || EltVT == MVT::ppcf128 ||
1583       EltVT == MVT::f16 || EltVT == MVT::bf16) {
1584     bool Ignored;
1585     APFloat APF = APFloat(Val);
1586     APF.convert(EVTToAPFloatSemantics(EltVT), APFloat::rmNearestTiesToEven,
1587                 &Ignored);
1588     return getConstantFP(APF, DL, VT, isTarget);
1589   }
1590   llvm_unreachable("Unsupported type in getConstantFP");
1591 }
1592 
1593 SDValue SelectionDAG::getGlobalAddress(const GlobalValue *GV, const SDLoc &DL,
1594                                        EVT VT, int64_t Offset, bool isTargetGA,
1595                                        unsigned TargetFlags) {
1596   assert((TargetFlags == 0 || isTargetGA) &&
1597          "Cannot set target flags on target-independent globals");
1598 
1599   // Truncate (with sign-extension) the offset value to the pointer size.
1600   unsigned BitWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
1601   if (BitWidth < 64)
1602     Offset = SignExtend64(Offset, BitWidth);
1603 
1604   unsigned Opc;
1605   if (GV->isThreadLocal())
1606     Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress;
1607   else
1608     Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress;
1609 
1610   FoldingSetNodeID ID;
1611   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1612   ID.AddPointer(GV);
1613   ID.AddInteger(Offset);
1614   ID.AddInteger(TargetFlags);
1615   void *IP = nullptr;
1616   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
1617     return SDValue(E, 0);
1618 
1619   auto *N = newSDNode<GlobalAddressSDNode>(
1620       Opc, DL.getIROrder(), DL.getDebugLoc(), GV, VT, Offset, TargetFlags);
1621   CSEMap.InsertNode(N, IP);
1622     InsertNode(N);
1623   return SDValue(N, 0);
1624 }
1625 
1626 SDValue SelectionDAG::getFrameIndex(int FI, EVT VT, bool isTarget) {
1627   unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
1628   FoldingSetNodeID ID;
1629   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1630   ID.AddInteger(FI);
1631   void *IP = nullptr;
1632   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1633     return SDValue(E, 0);
1634 
1635   auto *N = newSDNode<FrameIndexSDNode>(FI, VT, isTarget);
1636   CSEMap.InsertNode(N, IP);
1637   InsertNode(N);
1638   return SDValue(N, 0);
1639 }
1640 
1641 SDValue SelectionDAG::getJumpTable(int JTI, EVT VT, bool isTarget,
1642                                    unsigned TargetFlags) {
1643   assert((TargetFlags == 0 || isTarget) &&
1644          "Cannot set target flags on target-independent jump tables");
1645   unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
1646   FoldingSetNodeID ID;
1647   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1648   ID.AddInteger(JTI);
1649   ID.AddInteger(TargetFlags);
1650   void *IP = nullptr;
1651   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1652     return SDValue(E, 0);
1653 
1654   auto *N = newSDNode<JumpTableSDNode>(JTI, VT, isTarget, TargetFlags);
1655   CSEMap.InsertNode(N, IP);
1656   InsertNode(N);
1657   return SDValue(N, 0);
1658 }
1659 
1660 SDValue SelectionDAG::getConstantPool(const Constant *C, EVT VT,
1661                                       MaybeAlign Alignment, int Offset,
1662                                       bool isTarget, unsigned TargetFlags) {
1663   assert((TargetFlags == 0 || isTarget) &&
1664          "Cannot set target flags on target-independent globals");
1665   if (!Alignment)
1666     Alignment = shouldOptForSize()
1667                     ? getDataLayout().getABITypeAlign(C->getType())
1668                     : getDataLayout().getPrefTypeAlign(C->getType());
1669   unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1670   FoldingSetNodeID ID;
1671   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1672   ID.AddInteger(Alignment->value());
1673   ID.AddInteger(Offset);
1674   ID.AddPointer(C);
1675   ID.AddInteger(TargetFlags);
1676   void *IP = nullptr;
1677   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1678     return SDValue(E, 0);
1679 
1680   auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment,
1681                                           TargetFlags);
1682   CSEMap.InsertNode(N, IP);
1683   InsertNode(N);
1684   SDValue V = SDValue(N, 0);
1685   NewSDValueDbgMsg(V, "Creating new constant pool: ", this);
1686   return V;
1687 }
1688 
1689 SDValue SelectionDAG::getConstantPool(MachineConstantPoolValue *C, EVT VT,
1690                                       MaybeAlign Alignment, int Offset,
1691                                       bool isTarget, unsigned TargetFlags) {
1692   assert((TargetFlags == 0 || isTarget) &&
1693          "Cannot set target flags on target-independent globals");
1694   if (!Alignment)
1695     Alignment = getDataLayout().getPrefTypeAlign(C->getType());
1696   unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1697   FoldingSetNodeID ID;
1698   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1699   ID.AddInteger(Alignment->value());
1700   ID.AddInteger(Offset);
1701   C->addSelectionDAGCSEId(ID);
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<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment,
1708                                           TargetFlags);
1709   CSEMap.InsertNode(N, IP);
1710   InsertNode(N);
1711   return SDValue(N, 0);
1712 }
1713 
1714 SDValue SelectionDAG::getTargetIndex(int Index, EVT VT, int64_t Offset,
1715                                      unsigned TargetFlags) {
1716   FoldingSetNodeID ID;
1717   AddNodeIDNode(ID, ISD::TargetIndex, getVTList(VT), None);
1718   ID.AddInteger(Index);
1719   ID.AddInteger(Offset);
1720   ID.AddInteger(TargetFlags);
1721   void *IP = nullptr;
1722   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1723     return SDValue(E, 0);
1724 
1725   auto *N = newSDNode<TargetIndexSDNode>(Index, VT, Offset, TargetFlags);
1726   CSEMap.InsertNode(N, IP);
1727   InsertNode(N);
1728   return SDValue(N, 0);
1729 }
1730 
1731 SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
1732   FoldingSetNodeID ID;
1733   AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), None);
1734   ID.AddPointer(MBB);
1735   void *IP = nullptr;
1736   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1737     return SDValue(E, 0);
1738 
1739   auto *N = newSDNode<BasicBlockSDNode>(MBB);
1740   CSEMap.InsertNode(N, IP);
1741   InsertNode(N);
1742   return SDValue(N, 0);
1743 }
1744 
1745 SDValue SelectionDAG::getValueType(EVT VT) {
1746   if (VT.isSimple() && (unsigned)VT.getSimpleVT().SimpleTy >=
1747       ValueTypeNodes.size())
1748     ValueTypeNodes.resize(VT.getSimpleVT().SimpleTy+1);
1749 
1750   SDNode *&N = VT.isExtended() ?
1751     ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT().SimpleTy];
1752 
1753   if (N) return SDValue(N, 0);
1754   N = newSDNode<VTSDNode>(VT);
1755   InsertNode(N);
1756   return SDValue(N, 0);
1757 }
1758 
1759 SDValue SelectionDAG::getExternalSymbol(const char *Sym, EVT VT) {
1760   SDNode *&N = ExternalSymbols[Sym];
1761   if (N) return SDValue(N, 0);
1762   N = newSDNode<ExternalSymbolSDNode>(false, Sym, 0, VT);
1763   InsertNode(N);
1764   return SDValue(N, 0);
1765 }
1766 
1767 SDValue SelectionDAG::getMCSymbol(MCSymbol *Sym, EVT VT) {
1768   SDNode *&N = MCSymbols[Sym];
1769   if (N)
1770     return SDValue(N, 0);
1771   N = newSDNode<MCSymbolSDNode>(Sym, VT);
1772   InsertNode(N);
1773   return SDValue(N, 0);
1774 }
1775 
1776 SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, EVT VT,
1777                                               unsigned TargetFlags) {
1778   SDNode *&N =
1779       TargetExternalSymbols[std::pair<std::string, unsigned>(Sym, TargetFlags)];
1780   if (N) return SDValue(N, 0);
1781   N = newSDNode<ExternalSymbolSDNode>(true, Sym, TargetFlags, VT);
1782   InsertNode(N);
1783   return SDValue(N, 0);
1784 }
1785 
1786 SDValue SelectionDAG::getCondCode(ISD::CondCode Cond) {
1787   if ((unsigned)Cond >= CondCodeNodes.size())
1788     CondCodeNodes.resize(Cond+1);
1789 
1790   if (!CondCodeNodes[Cond]) {
1791     auto *N = newSDNode<CondCodeSDNode>(Cond);
1792     CondCodeNodes[Cond] = N;
1793     InsertNode(N);
1794   }
1795 
1796   return SDValue(CondCodeNodes[Cond], 0);
1797 }
1798 
1799 SDValue SelectionDAG::getStepVector(const SDLoc &DL, EVT ResVT) {
1800   APInt One(ResVT.getScalarSizeInBits(), 1);
1801   return getStepVector(DL, ResVT, One);
1802 }
1803 
1804 SDValue SelectionDAG::getStepVector(const SDLoc &DL, EVT ResVT, APInt StepVal) {
1805   assert(ResVT.getScalarSizeInBits() == StepVal.getBitWidth());
1806   if (ResVT.isScalableVector())
1807     return getNode(
1808         ISD::STEP_VECTOR, DL, ResVT,
1809         getTargetConstant(StepVal, DL, ResVT.getVectorElementType()));
1810 
1811   SmallVector<SDValue, 16> OpsStepConstants;
1812   for (uint64_t i = 0; i < ResVT.getVectorNumElements(); i++)
1813     OpsStepConstants.push_back(
1814         getConstant(StepVal * i, DL, ResVT.getVectorElementType()));
1815   return getBuildVector(ResVT, DL, OpsStepConstants);
1816 }
1817 
1818 /// Swaps the values of N1 and N2. Swaps all indices in the shuffle mask M that
1819 /// point at N1 to point at N2 and indices that point at N2 to point at N1.
1820 static void commuteShuffle(SDValue &N1, SDValue &N2, MutableArrayRef<int> M) {
1821   std::swap(N1, N2);
1822   ShuffleVectorSDNode::commuteMask(M);
1823 }
1824 
1825 SDValue SelectionDAG::getVectorShuffle(EVT VT, const SDLoc &dl, SDValue N1,
1826                                        SDValue N2, ArrayRef<int> Mask) {
1827   assert(VT.getVectorNumElements() == Mask.size() &&
1828          "Must have the same number of vector elements as mask elements!");
1829   assert(VT == N1.getValueType() && VT == N2.getValueType() &&
1830          "Invalid VECTOR_SHUFFLE");
1831 
1832   // Canonicalize shuffle undef, undef -> undef
1833   if (N1.isUndef() && N2.isUndef())
1834     return getUNDEF(VT);
1835 
1836   // Validate that all indices in Mask are within the range of the elements
1837   // input to the shuffle.
1838   int NElts = Mask.size();
1839   assert(llvm::all_of(Mask,
1840                       [&](int M) { return M < (NElts * 2) && M >= -1; }) &&
1841          "Index out of range");
1842 
1843   // Copy the mask so we can do any needed cleanup.
1844   SmallVector<int, 8> MaskVec(Mask.begin(), Mask.end());
1845 
1846   // Canonicalize shuffle v, v -> v, undef
1847   if (N1 == N2) {
1848     N2 = getUNDEF(VT);
1849     for (int i = 0; i != NElts; ++i)
1850       if (MaskVec[i] >= NElts) MaskVec[i] -= NElts;
1851   }
1852 
1853   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
1854   if (N1.isUndef())
1855     commuteShuffle(N1, N2, MaskVec);
1856 
1857   if (TLI->hasVectorBlend()) {
1858     // If shuffling a splat, try to blend the splat instead. We do this here so
1859     // that even when this arises during lowering we don't have to re-handle it.
1860     auto BlendSplat = [&](BuildVectorSDNode *BV, int Offset) {
1861       BitVector UndefElements;
1862       SDValue Splat = BV->getSplatValue(&UndefElements);
1863       if (!Splat)
1864         return;
1865 
1866       for (int i = 0; i < NElts; ++i) {
1867         if (MaskVec[i] < Offset || MaskVec[i] >= (Offset + NElts))
1868           continue;
1869 
1870         // If this input comes from undef, mark it as such.
1871         if (UndefElements[MaskVec[i] - Offset]) {
1872           MaskVec[i] = -1;
1873           continue;
1874         }
1875 
1876         // If we can blend a non-undef lane, use that instead.
1877         if (!UndefElements[i])
1878           MaskVec[i] = i + Offset;
1879       }
1880     };
1881     if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
1882       BlendSplat(N1BV, 0);
1883     if (auto *N2BV = dyn_cast<BuildVectorSDNode>(N2))
1884       BlendSplat(N2BV, NElts);
1885   }
1886 
1887   // Canonicalize all index into lhs, -> shuffle lhs, undef
1888   // Canonicalize all index into rhs, -> shuffle rhs, undef
1889   bool AllLHS = true, AllRHS = true;
1890   bool N2Undef = N2.isUndef();
1891   for (int i = 0; i != NElts; ++i) {
1892     if (MaskVec[i] >= NElts) {
1893       if (N2Undef)
1894         MaskVec[i] = -1;
1895       else
1896         AllLHS = false;
1897     } else if (MaskVec[i] >= 0) {
1898       AllRHS = false;
1899     }
1900   }
1901   if (AllLHS && AllRHS)
1902     return getUNDEF(VT);
1903   if (AllLHS && !N2Undef)
1904     N2 = getUNDEF(VT);
1905   if (AllRHS) {
1906     N1 = getUNDEF(VT);
1907     commuteShuffle(N1, N2, MaskVec);
1908   }
1909   // Reset our undef status after accounting for the mask.
1910   N2Undef = N2.isUndef();
1911   // Re-check whether both sides ended up undef.
1912   if (N1.isUndef() && N2Undef)
1913     return getUNDEF(VT);
1914 
1915   // If Identity shuffle return that node.
1916   bool Identity = true, AllSame = true;
1917   for (int i = 0; i != NElts; ++i) {
1918     if (MaskVec[i] >= 0 && MaskVec[i] != i) Identity = false;
1919     if (MaskVec[i] != MaskVec[0]) AllSame = false;
1920   }
1921   if (Identity && NElts)
1922     return N1;
1923 
1924   // Shuffling a constant splat doesn't change the result.
1925   if (N2Undef) {
1926     SDValue V = N1;
1927 
1928     // Look through any bitcasts. We check that these don't change the number
1929     // (and size) of elements and just changes their types.
1930     while (V.getOpcode() == ISD::BITCAST)
1931       V = V->getOperand(0);
1932 
1933     // A splat should always show up as a build vector node.
1934     if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) {
1935       BitVector UndefElements;
1936       SDValue Splat = BV->getSplatValue(&UndefElements);
1937       // If this is a splat of an undef, shuffling it is also undef.
1938       if (Splat && Splat.isUndef())
1939         return getUNDEF(VT);
1940 
1941       bool SameNumElts =
1942           V.getValueType().getVectorNumElements() == VT.getVectorNumElements();
1943 
1944       // We only have a splat which can skip shuffles if there is a splatted
1945       // value and no undef lanes rearranged by the shuffle.
1946       if (Splat && UndefElements.none()) {
1947         // Splat of <x, x, ..., x>, return <x, x, ..., x>, provided that the
1948         // number of elements match or the value splatted is a zero constant.
1949         if (SameNumElts)
1950           return N1;
1951         if (auto *C = dyn_cast<ConstantSDNode>(Splat))
1952           if (C->isZero())
1953             return N1;
1954       }
1955 
1956       // If the shuffle itself creates a splat, build the vector directly.
1957       if (AllSame && SameNumElts) {
1958         EVT BuildVT = BV->getValueType(0);
1959         const SDValue &Splatted = BV->getOperand(MaskVec[0]);
1960         SDValue NewBV = getSplatBuildVector(BuildVT, dl, Splatted);
1961 
1962         // We may have jumped through bitcasts, so the type of the
1963         // BUILD_VECTOR may not match the type of the shuffle.
1964         if (BuildVT != VT)
1965           NewBV = getNode(ISD::BITCAST, dl, VT, NewBV);
1966         return NewBV;
1967       }
1968     }
1969   }
1970 
1971   FoldingSetNodeID ID;
1972   SDValue Ops[2] = { N1, N2 };
1973   AddNodeIDNode(ID, ISD::VECTOR_SHUFFLE, getVTList(VT), Ops);
1974   for (int i = 0; i != NElts; ++i)
1975     ID.AddInteger(MaskVec[i]);
1976 
1977   void* IP = nullptr;
1978   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
1979     return SDValue(E, 0);
1980 
1981   // Allocate the mask array for the node out of the BumpPtrAllocator, since
1982   // SDNode doesn't have access to it.  This memory will be "leaked" when
1983   // the node is deallocated, but recovered when the NodeAllocator is released.
1984   int *MaskAlloc = OperandAllocator.Allocate<int>(NElts);
1985   llvm::copy(MaskVec, MaskAlloc);
1986 
1987   auto *N = newSDNode<ShuffleVectorSDNode>(VT, dl.getIROrder(),
1988                                            dl.getDebugLoc(), MaskAlloc);
1989   createOperands(N, Ops);
1990 
1991   CSEMap.InsertNode(N, IP);
1992   InsertNode(N);
1993   SDValue V = SDValue(N, 0);
1994   NewSDValueDbgMsg(V, "Creating new node: ", this);
1995   return V;
1996 }
1997 
1998 SDValue SelectionDAG::getCommutedVectorShuffle(const ShuffleVectorSDNode &SV) {
1999   EVT VT = SV.getValueType(0);
2000   SmallVector<int, 8> MaskVec(SV.getMask().begin(), SV.getMask().end());
2001   ShuffleVectorSDNode::commuteMask(MaskVec);
2002 
2003   SDValue Op0 = SV.getOperand(0);
2004   SDValue Op1 = SV.getOperand(1);
2005   return getVectorShuffle(VT, SDLoc(&SV), Op1, Op0, MaskVec);
2006 }
2007 
2008 SDValue SelectionDAG::getRegister(unsigned RegNo, EVT VT) {
2009   FoldingSetNodeID ID;
2010   AddNodeIDNode(ID, ISD::Register, getVTList(VT), None);
2011   ID.AddInteger(RegNo);
2012   void *IP = nullptr;
2013   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2014     return SDValue(E, 0);
2015 
2016   auto *N = newSDNode<RegisterSDNode>(RegNo, VT);
2017   N->SDNodeBits.IsDivergent = TLI->isSDNodeSourceOfDivergence(N, FLI, DA);
2018   CSEMap.InsertNode(N, IP);
2019   InsertNode(N);
2020   return SDValue(N, 0);
2021 }
2022 
2023 SDValue SelectionDAG::getRegisterMask(const uint32_t *RegMask) {
2024   FoldingSetNodeID ID;
2025   AddNodeIDNode(ID, ISD::RegisterMask, getVTList(MVT::Untyped), None);
2026   ID.AddPointer(RegMask);
2027   void *IP = nullptr;
2028   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2029     return SDValue(E, 0);
2030 
2031   auto *N = newSDNode<RegisterMaskSDNode>(RegMask);
2032   CSEMap.InsertNode(N, IP);
2033   InsertNode(N);
2034   return SDValue(N, 0);
2035 }
2036 
2037 SDValue SelectionDAG::getEHLabel(const SDLoc &dl, SDValue Root,
2038                                  MCSymbol *Label) {
2039   return getLabelNode(ISD::EH_LABEL, dl, Root, Label);
2040 }
2041 
2042 SDValue SelectionDAG::getLabelNode(unsigned Opcode, const SDLoc &dl,
2043                                    SDValue Root, MCSymbol *Label) {
2044   FoldingSetNodeID ID;
2045   SDValue Ops[] = { Root };
2046   AddNodeIDNode(ID, Opcode, getVTList(MVT::Other), Ops);
2047   ID.AddPointer(Label);
2048   void *IP = nullptr;
2049   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2050     return SDValue(E, 0);
2051 
2052   auto *N =
2053       newSDNode<LabelSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), Label);
2054   createOperands(N, Ops);
2055 
2056   CSEMap.InsertNode(N, IP);
2057   InsertNode(N);
2058   return SDValue(N, 0);
2059 }
2060 
2061 SDValue SelectionDAG::getBlockAddress(const BlockAddress *BA, EVT VT,
2062                                       int64_t Offset, bool isTarget,
2063                                       unsigned TargetFlags) {
2064   unsigned Opc = isTarget ? ISD::TargetBlockAddress : ISD::BlockAddress;
2065 
2066   FoldingSetNodeID ID;
2067   AddNodeIDNode(ID, Opc, getVTList(VT), None);
2068   ID.AddPointer(BA);
2069   ID.AddInteger(Offset);
2070   ID.AddInteger(TargetFlags);
2071   void *IP = nullptr;
2072   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2073     return SDValue(E, 0);
2074 
2075   auto *N = newSDNode<BlockAddressSDNode>(Opc, VT, BA, Offset, TargetFlags);
2076   CSEMap.InsertNode(N, IP);
2077   InsertNode(N);
2078   return SDValue(N, 0);
2079 }
2080 
2081 SDValue SelectionDAG::getSrcValue(const Value *V) {
2082   FoldingSetNodeID ID;
2083   AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), None);
2084   ID.AddPointer(V);
2085 
2086   void *IP = nullptr;
2087   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2088     return SDValue(E, 0);
2089 
2090   auto *N = newSDNode<SrcValueSDNode>(V);
2091   CSEMap.InsertNode(N, IP);
2092   InsertNode(N);
2093   return SDValue(N, 0);
2094 }
2095 
2096 SDValue SelectionDAG::getMDNode(const MDNode *MD) {
2097   FoldingSetNodeID ID;
2098   AddNodeIDNode(ID, ISD::MDNODE_SDNODE, getVTList(MVT::Other), None);
2099   ID.AddPointer(MD);
2100 
2101   void *IP = nullptr;
2102   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2103     return SDValue(E, 0);
2104 
2105   auto *N = newSDNode<MDNodeSDNode>(MD);
2106   CSEMap.InsertNode(N, IP);
2107   InsertNode(N);
2108   return SDValue(N, 0);
2109 }
2110 
2111 SDValue SelectionDAG::getBitcast(EVT VT, SDValue V) {
2112   if (VT == V.getValueType())
2113     return V;
2114 
2115   return getNode(ISD::BITCAST, SDLoc(V), VT, V);
2116 }
2117 
2118 SDValue SelectionDAG::getAddrSpaceCast(const SDLoc &dl, EVT VT, SDValue Ptr,
2119                                        unsigned SrcAS, unsigned DestAS) {
2120   SDValue Ops[] = {Ptr};
2121   FoldingSetNodeID ID;
2122   AddNodeIDNode(ID, ISD::ADDRSPACECAST, getVTList(VT), Ops);
2123   ID.AddInteger(SrcAS);
2124   ID.AddInteger(DestAS);
2125 
2126   void *IP = nullptr;
2127   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
2128     return SDValue(E, 0);
2129 
2130   auto *N = newSDNode<AddrSpaceCastSDNode>(dl.getIROrder(), dl.getDebugLoc(),
2131                                            VT, SrcAS, DestAS);
2132   createOperands(N, Ops);
2133 
2134   CSEMap.InsertNode(N, IP);
2135   InsertNode(N);
2136   return SDValue(N, 0);
2137 }
2138 
2139 SDValue SelectionDAG::getFreeze(SDValue V) {
2140   return getNode(ISD::FREEZE, SDLoc(V), V.getValueType(), V);
2141 }
2142 
2143 /// getShiftAmountOperand - Return the specified value casted to
2144 /// the target's desired shift amount type.
2145 SDValue SelectionDAG::getShiftAmountOperand(EVT LHSTy, SDValue Op) {
2146   EVT OpTy = Op.getValueType();
2147   EVT ShTy = TLI->getShiftAmountTy(LHSTy, getDataLayout());
2148   if (OpTy == ShTy || OpTy.isVector()) return Op;
2149 
2150   return getZExtOrTrunc(Op, SDLoc(Op), ShTy);
2151 }
2152 
2153 SDValue SelectionDAG::expandVAArg(SDNode *Node) {
2154   SDLoc dl(Node);
2155   const TargetLowering &TLI = getTargetLoweringInfo();
2156   const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2157   EVT VT = Node->getValueType(0);
2158   SDValue Tmp1 = Node->getOperand(0);
2159   SDValue Tmp2 = Node->getOperand(1);
2160   const MaybeAlign MA(Node->getConstantOperandVal(3));
2161 
2162   SDValue VAListLoad = getLoad(TLI.getPointerTy(getDataLayout()), dl, Tmp1,
2163                                Tmp2, MachinePointerInfo(V));
2164   SDValue VAList = VAListLoad;
2165 
2166   if (MA && *MA > TLI.getMinStackArgumentAlignment()) {
2167     VAList = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
2168                      getConstant(MA->value() - 1, dl, VAList.getValueType()));
2169 
2170     VAList =
2171         getNode(ISD::AND, dl, VAList.getValueType(), VAList,
2172                 getConstant(-(int64_t)MA->value(), dl, VAList.getValueType()));
2173   }
2174 
2175   // Increment the pointer, VAList, to the next vaarg
2176   Tmp1 = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
2177                  getConstant(getDataLayout().getTypeAllocSize(
2178                                                VT.getTypeForEVT(*getContext())),
2179                              dl, VAList.getValueType()));
2180   // Store the incremented VAList to the legalized pointer
2181   Tmp1 =
2182       getStore(VAListLoad.getValue(1), dl, Tmp1, Tmp2, MachinePointerInfo(V));
2183   // Load the actual argument out of the pointer VAList
2184   return getLoad(VT, dl, Tmp1, VAList, MachinePointerInfo());
2185 }
2186 
2187 SDValue SelectionDAG::expandVACopy(SDNode *Node) {
2188   SDLoc dl(Node);
2189   const TargetLowering &TLI = getTargetLoweringInfo();
2190   // This defaults to loading a pointer from the input and storing it to the
2191   // output, returning the chain.
2192   const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue();
2193   const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue();
2194   SDValue Tmp1 =
2195       getLoad(TLI.getPointerTy(getDataLayout()), dl, Node->getOperand(0),
2196               Node->getOperand(2), MachinePointerInfo(VS));
2197   return getStore(Tmp1.getValue(1), dl, Tmp1, Node->getOperand(1),
2198                   MachinePointerInfo(VD));
2199 }
2200 
2201 Align SelectionDAG::getReducedAlign(EVT VT, bool UseABI) {
2202   const DataLayout &DL = getDataLayout();
2203   Type *Ty = VT.getTypeForEVT(*getContext());
2204   Align RedAlign = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty);
2205 
2206   if (TLI->isTypeLegal(VT) || !VT.isVector())
2207     return RedAlign;
2208 
2209   const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
2210   const Align StackAlign = TFI->getStackAlign();
2211 
2212   // See if we can choose a smaller ABI alignment in cases where it's an
2213   // illegal vector type that will get broken down.
2214   if (RedAlign > StackAlign) {
2215     EVT IntermediateVT;
2216     MVT RegisterVT;
2217     unsigned NumIntermediates;
2218     TLI->getVectorTypeBreakdown(*getContext(), VT, IntermediateVT,
2219                                 NumIntermediates, RegisterVT);
2220     Ty = IntermediateVT.getTypeForEVT(*getContext());
2221     Align RedAlign2 = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty);
2222     if (RedAlign2 < RedAlign)
2223       RedAlign = RedAlign2;
2224   }
2225 
2226   return RedAlign;
2227 }
2228 
2229 SDValue SelectionDAG::CreateStackTemporary(TypeSize Bytes, Align Alignment) {
2230   MachineFrameInfo &MFI = MF->getFrameInfo();
2231   const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
2232   int StackID = 0;
2233   if (Bytes.isScalable())
2234     StackID = TFI->getStackIDForScalableVectors();
2235   // The stack id gives an indication of whether the object is scalable or
2236   // not, so it's safe to pass in the minimum size here.
2237   int FrameIdx = MFI.CreateStackObject(Bytes.getKnownMinSize(), Alignment,
2238                                        false, nullptr, StackID);
2239   return getFrameIndex(FrameIdx, TLI->getFrameIndexTy(getDataLayout()));
2240 }
2241 
2242 SDValue SelectionDAG::CreateStackTemporary(EVT VT, unsigned minAlign) {
2243   Type *Ty = VT.getTypeForEVT(*getContext());
2244   Align StackAlign =
2245       std::max(getDataLayout().getPrefTypeAlign(Ty), Align(minAlign));
2246   return CreateStackTemporary(VT.getStoreSize(), StackAlign);
2247 }
2248 
2249 SDValue SelectionDAG::CreateStackTemporary(EVT VT1, EVT VT2) {
2250   TypeSize VT1Size = VT1.getStoreSize();
2251   TypeSize VT2Size = VT2.getStoreSize();
2252   assert(VT1Size.isScalable() == VT2Size.isScalable() &&
2253          "Don't know how to choose the maximum size when creating a stack "
2254          "temporary");
2255   TypeSize Bytes =
2256       VT1Size.getKnownMinSize() > VT2Size.getKnownMinSize() ? VT1Size : VT2Size;
2257 
2258   Type *Ty1 = VT1.getTypeForEVT(*getContext());
2259   Type *Ty2 = VT2.getTypeForEVT(*getContext());
2260   const DataLayout &DL = getDataLayout();
2261   Align Align = std::max(DL.getPrefTypeAlign(Ty1), DL.getPrefTypeAlign(Ty2));
2262   return CreateStackTemporary(Bytes, Align);
2263 }
2264 
2265 SDValue SelectionDAG::FoldSetCC(EVT VT, SDValue N1, SDValue N2,
2266                                 ISD::CondCode Cond, const SDLoc &dl) {
2267   EVT OpVT = N1.getValueType();
2268 
2269   // These setcc operations always fold.
2270   switch (Cond) {
2271   default: break;
2272   case ISD::SETFALSE:
2273   case ISD::SETFALSE2: return getBoolConstant(false, dl, VT, OpVT);
2274   case ISD::SETTRUE:
2275   case ISD::SETTRUE2: return getBoolConstant(true, dl, VT, OpVT);
2276 
2277   case ISD::SETOEQ:
2278   case ISD::SETOGT:
2279   case ISD::SETOGE:
2280   case ISD::SETOLT:
2281   case ISD::SETOLE:
2282   case ISD::SETONE:
2283   case ISD::SETO:
2284   case ISD::SETUO:
2285   case ISD::SETUEQ:
2286   case ISD::SETUNE:
2287     assert(!OpVT.isInteger() && "Illegal setcc for integer!");
2288     break;
2289   }
2290 
2291   if (OpVT.isInteger()) {
2292     // For EQ and NE, we can always pick a value for the undef to make the
2293     // predicate pass or fail, so we can return undef.
2294     // Matches behavior in llvm::ConstantFoldCompareInstruction.
2295     // icmp eq/ne X, undef -> undef.
2296     if ((N1.isUndef() || N2.isUndef()) &&
2297         (Cond == ISD::SETEQ || Cond == ISD::SETNE))
2298       return getUNDEF(VT);
2299 
2300     // If both operands are undef, we can return undef for int comparison.
2301     // icmp undef, undef -> undef.
2302     if (N1.isUndef() && N2.isUndef())
2303       return getUNDEF(VT);
2304 
2305     // icmp X, X -> true/false
2306     // icmp X, undef -> true/false because undef could be X.
2307     if (N1 == N2)
2308       return getBoolConstant(ISD::isTrueWhenEqual(Cond), dl, VT, OpVT);
2309   }
2310 
2311   if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2)) {
2312     const APInt &C2 = N2C->getAPIntValue();
2313     if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1)) {
2314       const APInt &C1 = N1C->getAPIntValue();
2315 
2316       return getBoolConstant(ICmpInst::compare(C1, C2, getICmpCondCode(Cond)),
2317                              dl, VT, OpVT);
2318     }
2319   }
2320 
2321   auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
2322   auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
2323 
2324   if (N1CFP && N2CFP) {
2325     APFloat::cmpResult R = N1CFP->getValueAPF().compare(N2CFP->getValueAPF());
2326     switch (Cond) {
2327     default: break;
2328     case ISD::SETEQ:  if (R==APFloat::cmpUnordered)
2329                         return getUNDEF(VT);
2330                       LLVM_FALLTHROUGH;
2331     case ISD::SETOEQ: return getBoolConstant(R==APFloat::cmpEqual, dl, VT,
2332                                              OpVT);
2333     case ISD::SETNE:  if (R==APFloat::cmpUnordered)
2334                         return getUNDEF(VT);
2335                       LLVM_FALLTHROUGH;
2336     case ISD::SETONE: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2337                                              R==APFloat::cmpLessThan, dl, VT,
2338                                              OpVT);
2339     case ISD::SETLT:  if (R==APFloat::cmpUnordered)
2340                         return getUNDEF(VT);
2341                       LLVM_FALLTHROUGH;
2342     case ISD::SETOLT: return getBoolConstant(R==APFloat::cmpLessThan, dl, VT,
2343                                              OpVT);
2344     case ISD::SETGT:  if (R==APFloat::cmpUnordered)
2345                         return getUNDEF(VT);
2346                       LLVM_FALLTHROUGH;
2347     case ISD::SETOGT: return getBoolConstant(R==APFloat::cmpGreaterThan, dl,
2348                                              VT, OpVT);
2349     case ISD::SETLE:  if (R==APFloat::cmpUnordered)
2350                         return getUNDEF(VT);
2351                       LLVM_FALLTHROUGH;
2352     case ISD::SETOLE: return getBoolConstant(R==APFloat::cmpLessThan ||
2353                                              R==APFloat::cmpEqual, dl, VT,
2354                                              OpVT);
2355     case ISD::SETGE:  if (R==APFloat::cmpUnordered)
2356                         return getUNDEF(VT);
2357                       LLVM_FALLTHROUGH;
2358     case ISD::SETOGE: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2359                                          R==APFloat::cmpEqual, dl, VT, OpVT);
2360     case ISD::SETO:   return getBoolConstant(R!=APFloat::cmpUnordered, dl, VT,
2361                                              OpVT);
2362     case ISD::SETUO:  return getBoolConstant(R==APFloat::cmpUnordered, dl, VT,
2363                                              OpVT);
2364     case ISD::SETUEQ: return getBoolConstant(R==APFloat::cmpUnordered ||
2365                                              R==APFloat::cmpEqual, dl, VT,
2366                                              OpVT);
2367     case ISD::SETUNE: return getBoolConstant(R!=APFloat::cmpEqual, dl, VT,
2368                                              OpVT);
2369     case ISD::SETULT: return getBoolConstant(R==APFloat::cmpUnordered ||
2370                                              R==APFloat::cmpLessThan, dl, VT,
2371                                              OpVT);
2372     case ISD::SETUGT: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2373                                              R==APFloat::cmpUnordered, dl, VT,
2374                                              OpVT);
2375     case ISD::SETULE: return getBoolConstant(R!=APFloat::cmpGreaterThan, dl,
2376                                              VT, OpVT);
2377     case ISD::SETUGE: return getBoolConstant(R!=APFloat::cmpLessThan, dl, VT,
2378                                              OpVT);
2379     }
2380   } else if (N1CFP && OpVT.isSimple() && !N2.isUndef()) {
2381     // Ensure that the constant occurs on the RHS.
2382     ISD::CondCode SwappedCond = ISD::getSetCCSwappedOperands(Cond);
2383     if (!TLI->isCondCodeLegal(SwappedCond, OpVT.getSimpleVT()))
2384       return SDValue();
2385     return getSetCC(dl, VT, N2, N1, SwappedCond);
2386   } else if ((N2CFP && N2CFP->getValueAPF().isNaN()) ||
2387              (OpVT.isFloatingPoint() && (N1.isUndef() || N2.isUndef()))) {
2388     // If an operand is known to be a nan (or undef that could be a nan), we can
2389     // fold it.
2390     // Choosing NaN for the undef will always make unordered comparison succeed
2391     // and ordered comparison fails.
2392     // Matches behavior in llvm::ConstantFoldCompareInstruction.
2393     switch (ISD::getUnorderedFlavor(Cond)) {
2394     default:
2395       llvm_unreachable("Unknown flavor!");
2396     case 0: // Known false.
2397       return getBoolConstant(false, dl, VT, OpVT);
2398     case 1: // Known true.
2399       return getBoolConstant(true, dl, VT, OpVT);
2400     case 2: // Undefined.
2401       return getUNDEF(VT);
2402     }
2403   }
2404 
2405   // Could not fold it.
2406   return SDValue();
2407 }
2408 
2409 /// See if the specified operand can be simplified with the knowledge that only
2410 /// the bits specified by DemandedBits are used.
2411 /// TODO: really we should be making this into the DAG equivalent of
2412 /// SimplifyMultipleUseDemandedBits and not generate any new nodes.
2413 SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &DemandedBits) {
2414   EVT VT = V.getValueType();
2415 
2416   if (VT.isScalableVector())
2417     return SDValue();
2418 
2419   APInt DemandedElts = VT.isVector()
2420                            ? APInt::getAllOnes(VT.getVectorNumElements())
2421                            : APInt(1, 1);
2422   return GetDemandedBits(V, DemandedBits, DemandedElts);
2423 }
2424 
2425 /// See if the specified operand can be simplified with the knowledge that only
2426 /// the bits specified by DemandedBits are used in the elements specified by
2427 /// DemandedElts.
2428 /// TODO: really we should be making this into the DAG equivalent of
2429 /// SimplifyMultipleUseDemandedBits and not generate any new nodes.
2430 SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &DemandedBits,
2431                                       const APInt &DemandedElts) {
2432   switch (V.getOpcode()) {
2433   default:
2434     return TLI->SimplifyMultipleUseDemandedBits(V, DemandedBits, DemandedElts,
2435                                                 *this, 0);
2436   case ISD::Constant: {
2437     const APInt &CVal = cast<ConstantSDNode>(V)->getAPIntValue();
2438     APInt NewVal = CVal & DemandedBits;
2439     if (NewVal != CVal)
2440       return getConstant(NewVal, SDLoc(V), V.getValueType());
2441     break;
2442   }
2443   case ISD::SRL:
2444     // Only look at single-use SRLs.
2445     if (!V.getNode()->hasOneUse())
2446       break;
2447     if (auto *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
2448       // See if we can recursively simplify the LHS.
2449       unsigned Amt = RHSC->getZExtValue();
2450 
2451       // Watch out for shift count overflow though.
2452       if (Amt >= DemandedBits.getBitWidth())
2453         break;
2454       APInt SrcDemandedBits = DemandedBits << Amt;
2455       if (SDValue SimplifyLHS =
2456               GetDemandedBits(V.getOperand(0), SrcDemandedBits))
2457         return getNode(ISD::SRL, SDLoc(V), V.getValueType(), SimplifyLHS,
2458                        V.getOperand(1));
2459     }
2460     break;
2461   }
2462   return SDValue();
2463 }
2464 
2465 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero.  We
2466 /// use this predicate to simplify operations downstream.
2467 bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const {
2468   unsigned BitWidth = Op.getScalarValueSizeInBits();
2469   return MaskedValueIsZero(Op, APInt::getSignMask(BitWidth), Depth);
2470 }
2471 
2472 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero.  We use
2473 /// this predicate to simplify operations downstream.  Mask is known to be zero
2474 /// for bits that V cannot have.
2475 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask,
2476                                      unsigned Depth) const {
2477   return Mask.isSubsetOf(computeKnownBits(V, Depth).Zero);
2478 }
2479 
2480 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero in
2481 /// DemandedElts.  We use this predicate to simplify operations downstream.
2482 /// Mask is known to be zero for bits that V cannot have.
2483 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask,
2484                                      const APInt &DemandedElts,
2485                                      unsigned Depth) const {
2486   return Mask.isSubsetOf(computeKnownBits(V, DemandedElts, Depth).Zero);
2487 }
2488 
2489 /// MaskedValueIsAllOnes - Return true if '(Op & Mask) == Mask'.
2490 bool SelectionDAG::MaskedValueIsAllOnes(SDValue V, const APInt &Mask,
2491                                         unsigned Depth) const {
2492   return Mask.isSubsetOf(computeKnownBits(V, Depth).One);
2493 }
2494 
2495 /// isSplatValue - Return true if the vector V has the same value
2496 /// across all DemandedElts. For scalable vectors it does not make
2497 /// sense to specify which elements are demanded or undefined, therefore
2498 /// they are simply ignored.
2499 bool SelectionDAG::isSplatValue(SDValue V, const APInt &DemandedElts,
2500                                 APInt &UndefElts, unsigned Depth) {
2501   EVT VT = V.getValueType();
2502   assert(VT.isVector() && "Vector type expected");
2503 
2504   if (!VT.isScalableVector() && !DemandedElts)
2505     return false; // No demanded elts, better to assume we don't know anything.
2506 
2507   if (Depth >= MaxRecursionDepth)
2508     return false; // Limit search depth.
2509 
2510   // Deal with some common cases here that work for both fixed and scalable
2511   // vector types.
2512   switch (V.getOpcode()) {
2513   case ISD::SPLAT_VECTOR:
2514     UndefElts = V.getOperand(0).isUndef()
2515                     ? APInt::getAllOnes(DemandedElts.getBitWidth())
2516                     : APInt(DemandedElts.getBitWidth(), 0);
2517     return true;
2518   case ISD::ADD:
2519   case ISD::SUB:
2520   case ISD::AND:
2521   case ISD::XOR:
2522   case ISD::OR: {
2523     APInt UndefLHS, UndefRHS;
2524     SDValue LHS = V.getOperand(0);
2525     SDValue RHS = V.getOperand(1);
2526     if (isSplatValue(LHS, DemandedElts, UndefLHS, Depth + 1) &&
2527         isSplatValue(RHS, DemandedElts, UndefRHS, Depth + 1)) {
2528       UndefElts = UndefLHS | UndefRHS;
2529       return true;
2530     }
2531     return false;
2532   }
2533   case ISD::ABS:
2534   case ISD::TRUNCATE:
2535   case ISD::SIGN_EXTEND:
2536   case ISD::ZERO_EXTEND:
2537     return isSplatValue(V.getOperand(0), DemandedElts, UndefElts, Depth + 1);
2538   }
2539 
2540   // We don't support other cases than those above for scalable vectors at
2541   // the moment.
2542   if (VT.isScalableVector())
2543     return false;
2544 
2545   unsigned NumElts = VT.getVectorNumElements();
2546   assert(NumElts == DemandedElts.getBitWidth() && "Vector size mismatch");
2547   UndefElts = APInt::getZero(NumElts);
2548 
2549   switch (V.getOpcode()) {
2550   case ISD::BUILD_VECTOR: {
2551     SDValue Scl;
2552     for (unsigned i = 0; i != NumElts; ++i) {
2553       SDValue Op = V.getOperand(i);
2554       if (Op.isUndef()) {
2555         UndefElts.setBit(i);
2556         continue;
2557       }
2558       if (!DemandedElts[i])
2559         continue;
2560       if (Scl && Scl != Op)
2561         return false;
2562       Scl = Op;
2563     }
2564     return true;
2565   }
2566   case ISD::VECTOR_SHUFFLE: {
2567     // Check if this is a shuffle node doing a splat.
2568     // TODO: Do we need to handle shuffle(splat, undef, mask)?
2569     int SplatIndex = -1;
2570     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(V)->getMask();
2571     for (int i = 0; i != (int)NumElts; ++i) {
2572       int M = Mask[i];
2573       if (M < 0) {
2574         UndefElts.setBit(i);
2575         continue;
2576       }
2577       if (!DemandedElts[i])
2578         continue;
2579       if (0 <= SplatIndex && SplatIndex != M)
2580         return false;
2581       SplatIndex = M;
2582     }
2583     return true;
2584   }
2585   case ISD::EXTRACT_SUBVECTOR: {
2586     // Offset the demanded elts by the subvector index.
2587     SDValue Src = V.getOperand(0);
2588     // We don't support scalable vectors at the moment.
2589     if (Src.getValueType().isScalableVector())
2590       return false;
2591     uint64_t Idx = V.getConstantOperandVal(1);
2592     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2593     APInt UndefSrcElts;
2594     APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
2595     if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) {
2596       UndefElts = UndefSrcElts.extractBits(NumElts, Idx);
2597       return true;
2598     }
2599     break;
2600   }
2601   }
2602 
2603   return false;
2604 }
2605 
2606 /// Helper wrapper to main isSplatValue function.
2607 bool SelectionDAG::isSplatValue(SDValue V, bool AllowUndefs) {
2608   EVT VT = V.getValueType();
2609   assert(VT.isVector() && "Vector type expected");
2610 
2611   APInt UndefElts;
2612   APInt DemandedElts;
2613 
2614   // For now we don't support this with scalable vectors.
2615   if (!VT.isScalableVector())
2616     DemandedElts = APInt::getAllOnes(VT.getVectorNumElements());
2617   return isSplatValue(V, DemandedElts, UndefElts) &&
2618          (AllowUndefs || !UndefElts);
2619 }
2620 
2621 SDValue SelectionDAG::getSplatSourceVector(SDValue V, int &SplatIdx) {
2622   V = peekThroughExtractSubvectors(V);
2623 
2624   EVT VT = V.getValueType();
2625   unsigned Opcode = V.getOpcode();
2626   switch (Opcode) {
2627   default: {
2628     APInt UndefElts;
2629     APInt DemandedElts;
2630 
2631     if (!VT.isScalableVector())
2632       DemandedElts = APInt::getAllOnes(VT.getVectorNumElements());
2633 
2634     if (isSplatValue(V, DemandedElts, UndefElts)) {
2635       if (VT.isScalableVector()) {
2636         // DemandedElts and UndefElts are ignored for scalable vectors, since
2637         // the only supported cases are SPLAT_VECTOR nodes.
2638         SplatIdx = 0;
2639       } else {
2640         // Handle case where all demanded elements are UNDEF.
2641         if (DemandedElts.isSubsetOf(UndefElts)) {
2642           SplatIdx = 0;
2643           return getUNDEF(VT);
2644         }
2645         SplatIdx = (UndefElts & DemandedElts).countTrailingOnes();
2646       }
2647       return V;
2648     }
2649     break;
2650   }
2651   case ISD::SPLAT_VECTOR:
2652     SplatIdx = 0;
2653     return V;
2654   case ISD::VECTOR_SHUFFLE: {
2655     if (VT.isScalableVector())
2656       return SDValue();
2657 
2658     // Check if this is a shuffle node doing a splat.
2659     // TODO - remove this and rely purely on SelectionDAG::isSplatValue,
2660     // getTargetVShiftNode currently struggles without the splat source.
2661     auto *SVN = cast<ShuffleVectorSDNode>(V);
2662     if (!SVN->isSplat())
2663       break;
2664     int Idx = SVN->getSplatIndex();
2665     int NumElts = V.getValueType().getVectorNumElements();
2666     SplatIdx = Idx % NumElts;
2667     return V.getOperand(Idx / NumElts);
2668   }
2669   }
2670 
2671   return SDValue();
2672 }
2673 
2674 SDValue SelectionDAG::getSplatValue(SDValue V, bool LegalTypes) {
2675   int SplatIdx;
2676   if (SDValue SrcVector = getSplatSourceVector(V, SplatIdx)) {
2677     EVT SVT = SrcVector.getValueType().getScalarType();
2678     EVT LegalSVT = SVT;
2679     if (LegalTypes && !TLI->isTypeLegal(SVT)) {
2680       if (!SVT.isInteger())
2681         return SDValue();
2682       LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
2683       if (LegalSVT.bitsLT(SVT))
2684         return SDValue();
2685     }
2686     return getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(V), LegalSVT, SrcVector,
2687                    getVectorIdxConstant(SplatIdx, SDLoc(V)));
2688   }
2689   return SDValue();
2690 }
2691 
2692 const APInt *
2693 SelectionDAG::getValidShiftAmountConstant(SDValue V,
2694                                           const APInt &DemandedElts) const {
2695   assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
2696           V.getOpcode() == ISD::SRA) &&
2697          "Unknown shift node");
2698   unsigned BitWidth = V.getScalarValueSizeInBits();
2699   if (ConstantSDNode *SA = isConstOrConstSplat(V.getOperand(1), DemandedElts)) {
2700     // Shifting more than the bitwidth is not valid.
2701     const APInt &ShAmt = SA->getAPIntValue();
2702     if (ShAmt.ult(BitWidth))
2703       return &ShAmt;
2704   }
2705   return nullptr;
2706 }
2707 
2708 const APInt *SelectionDAG::getValidMinimumShiftAmountConstant(
2709     SDValue V, const APInt &DemandedElts) const {
2710   assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
2711           V.getOpcode() == ISD::SRA) &&
2712          "Unknown shift node");
2713   if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts))
2714     return ValidAmt;
2715   unsigned BitWidth = V.getScalarValueSizeInBits();
2716   auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1));
2717   if (!BV)
2718     return nullptr;
2719   const APInt *MinShAmt = nullptr;
2720   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
2721     if (!DemandedElts[i])
2722       continue;
2723     auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i));
2724     if (!SA)
2725       return nullptr;
2726     // Shifting more than the bitwidth is not valid.
2727     const APInt &ShAmt = SA->getAPIntValue();
2728     if (ShAmt.uge(BitWidth))
2729       return nullptr;
2730     if (MinShAmt && MinShAmt->ule(ShAmt))
2731       continue;
2732     MinShAmt = &ShAmt;
2733   }
2734   return MinShAmt;
2735 }
2736 
2737 const APInt *SelectionDAG::getValidMaximumShiftAmountConstant(
2738     SDValue V, const APInt &DemandedElts) const {
2739   assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
2740           V.getOpcode() == ISD::SRA) &&
2741          "Unknown shift node");
2742   if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts))
2743     return ValidAmt;
2744   unsigned BitWidth = V.getScalarValueSizeInBits();
2745   auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1));
2746   if (!BV)
2747     return nullptr;
2748   const APInt *MaxShAmt = nullptr;
2749   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
2750     if (!DemandedElts[i])
2751       continue;
2752     auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i));
2753     if (!SA)
2754       return nullptr;
2755     // Shifting more than the bitwidth is not valid.
2756     const APInt &ShAmt = SA->getAPIntValue();
2757     if (ShAmt.uge(BitWidth))
2758       return nullptr;
2759     if (MaxShAmt && MaxShAmt->uge(ShAmt))
2760       continue;
2761     MaxShAmt = &ShAmt;
2762   }
2763   return MaxShAmt;
2764 }
2765 
2766 /// Determine which bits of Op are known to be either zero or one and return
2767 /// them in Known. For vectors, the known bits are those that are shared by
2768 /// every vector element.
2769 KnownBits SelectionDAG::computeKnownBits(SDValue Op, unsigned Depth) const {
2770   EVT VT = Op.getValueType();
2771 
2772   // TOOD: Until we have a plan for how to represent demanded elements for
2773   // scalable vectors, we can just bail out for now.
2774   if (Op.getValueType().isScalableVector()) {
2775     unsigned BitWidth = Op.getScalarValueSizeInBits();
2776     return KnownBits(BitWidth);
2777   }
2778 
2779   APInt DemandedElts = VT.isVector()
2780                            ? APInt::getAllOnes(VT.getVectorNumElements())
2781                            : APInt(1, 1);
2782   return computeKnownBits(Op, DemandedElts, Depth);
2783 }
2784 
2785 /// Determine which bits of Op are known to be either zero or one and return
2786 /// them in Known. The DemandedElts argument allows us to only collect the known
2787 /// bits that are shared by the requested vector elements.
2788 KnownBits SelectionDAG::computeKnownBits(SDValue Op, const APInt &DemandedElts,
2789                                          unsigned Depth) const {
2790   unsigned BitWidth = Op.getScalarValueSizeInBits();
2791 
2792   KnownBits Known(BitWidth);   // Don't know anything.
2793 
2794   // TOOD: Until we have a plan for how to represent demanded elements for
2795   // scalable vectors, we can just bail out for now.
2796   if (Op.getValueType().isScalableVector())
2797     return Known;
2798 
2799   if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
2800     // We know all of the bits for a constant!
2801     return KnownBits::makeConstant(C->getAPIntValue());
2802   }
2803   if (auto *C = dyn_cast<ConstantFPSDNode>(Op)) {
2804     // We know all of the bits for a constant fp!
2805     return KnownBits::makeConstant(C->getValueAPF().bitcastToAPInt());
2806   }
2807 
2808   if (Depth >= MaxRecursionDepth)
2809     return Known;  // Limit search depth.
2810 
2811   KnownBits Known2;
2812   unsigned NumElts = DemandedElts.getBitWidth();
2813   assert((!Op.getValueType().isVector() ||
2814           NumElts == Op.getValueType().getVectorNumElements()) &&
2815          "Unexpected vector size");
2816 
2817   if (!DemandedElts)
2818     return Known;  // No demanded elts, better to assume we don't know anything.
2819 
2820   unsigned Opcode = Op.getOpcode();
2821   switch (Opcode) {
2822   case ISD::BUILD_VECTOR:
2823     // Collect the known bits that are shared by every demanded vector element.
2824     Known.Zero.setAllBits(); Known.One.setAllBits();
2825     for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
2826       if (!DemandedElts[i])
2827         continue;
2828 
2829       SDValue SrcOp = Op.getOperand(i);
2830       Known2 = computeKnownBits(SrcOp, Depth + 1);
2831 
2832       // BUILD_VECTOR can implicitly truncate sources, we must handle this.
2833       if (SrcOp.getValueSizeInBits() != BitWidth) {
2834         assert(SrcOp.getValueSizeInBits() > BitWidth &&
2835                "Expected BUILD_VECTOR implicit truncation");
2836         Known2 = Known2.trunc(BitWidth);
2837       }
2838 
2839       // Known bits are the values that are shared by every demanded element.
2840       Known = KnownBits::commonBits(Known, Known2);
2841 
2842       // If we don't know any bits, early out.
2843       if (Known.isUnknown())
2844         break;
2845     }
2846     break;
2847   case ISD::VECTOR_SHUFFLE: {
2848     // Collect the known bits that are shared by every vector element referenced
2849     // by the shuffle.
2850     APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
2851     Known.Zero.setAllBits(); Known.One.setAllBits();
2852     const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
2853     assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
2854     for (unsigned i = 0; i != NumElts; ++i) {
2855       if (!DemandedElts[i])
2856         continue;
2857 
2858       int M = SVN->getMaskElt(i);
2859       if (M < 0) {
2860         // For UNDEF elements, we don't know anything about the common state of
2861         // the shuffle result.
2862         Known.resetAll();
2863         DemandedLHS.clearAllBits();
2864         DemandedRHS.clearAllBits();
2865         break;
2866       }
2867 
2868       if ((unsigned)M < NumElts)
2869         DemandedLHS.setBit((unsigned)M % NumElts);
2870       else
2871         DemandedRHS.setBit((unsigned)M % NumElts);
2872     }
2873     // Known bits are the values that are shared by every demanded element.
2874     if (!!DemandedLHS) {
2875       SDValue LHS = Op.getOperand(0);
2876       Known2 = computeKnownBits(LHS, DemandedLHS, Depth + 1);
2877       Known = KnownBits::commonBits(Known, Known2);
2878     }
2879     // If we don't know any bits, early out.
2880     if (Known.isUnknown())
2881       break;
2882     if (!!DemandedRHS) {
2883       SDValue RHS = Op.getOperand(1);
2884       Known2 = computeKnownBits(RHS, DemandedRHS, Depth + 1);
2885       Known = KnownBits::commonBits(Known, Known2);
2886     }
2887     break;
2888   }
2889   case ISD::CONCAT_VECTORS: {
2890     // Split DemandedElts and test each of the demanded subvectors.
2891     Known.Zero.setAllBits(); Known.One.setAllBits();
2892     EVT SubVectorVT = Op.getOperand(0).getValueType();
2893     unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
2894     unsigned NumSubVectors = Op.getNumOperands();
2895     for (unsigned i = 0; i != NumSubVectors; ++i) {
2896       APInt DemandedSub =
2897           DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts);
2898       if (!!DemandedSub) {
2899         SDValue Sub = Op.getOperand(i);
2900         Known2 = computeKnownBits(Sub, DemandedSub, Depth + 1);
2901         Known = KnownBits::commonBits(Known, Known2);
2902       }
2903       // If we don't know any bits, early out.
2904       if (Known.isUnknown())
2905         break;
2906     }
2907     break;
2908   }
2909   case ISD::INSERT_SUBVECTOR: {
2910     // Demand any elements from the subvector and the remainder from the src its
2911     // inserted into.
2912     SDValue Src = Op.getOperand(0);
2913     SDValue Sub = Op.getOperand(1);
2914     uint64_t Idx = Op.getConstantOperandVal(2);
2915     unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
2916     APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
2917     APInt DemandedSrcElts = DemandedElts;
2918     DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx);
2919 
2920     Known.One.setAllBits();
2921     Known.Zero.setAllBits();
2922     if (!!DemandedSubElts) {
2923       Known = computeKnownBits(Sub, DemandedSubElts, Depth + 1);
2924       if (Known.isUnknown())
2925         break; // early-out.
2926     }
2927     if (!!DemandedSrcElts) {
2928       Known2 = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
2929       Known = KnownBits::commonBits(Known, Known2);
2930     }
2931     break;
2932   }
2933   case ISD::EXTRACT_SUBVECTOR: {
2934     // Offset the demanded elts by the subvector index.
2935     SDValue Src = Op.getOperand(0);
2936     // Bail until we can represent demanded elements for scalable vectors.
2937     if (Src.getValueType().isScalableVector())
2938       break;
2939     uint64_t Idx = Op.getConstantOperandVal(1);
2940     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2941     APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
2942     Known = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
2943     break;
2944   }
2945   case ISD::SCALAR_TO_VECTOR: {
2946     // We know about scalar_to_vector as much as we know about it source,
2947     // which becomes the first element of otherwise unknown vector.
2948     if (DemandedElts != 1)
2949       break;
2950 
2951     SDValue N0 = Op.getOperand(0);
2952     Known = computeKnownBits(N0, Depth + 1);
2953     if (N0.getValueSizeInBits() != BitWidth)
2954       Known = Known.trunc(BitWidth);
2955 
2956     break;
2957   }
2958   case ISD::BITCAST: {
2959     SDValue N0 = Op.getOperand(0);
2960     EVT SubVT = N0.getValueType();
2961     unsigned SubBitWidth = SubVT.getScalarSizeInBits();
2962 
2963     // Ignore bitcasts from unsupported types.
2964     if (!(SubVT.isInteger() || SubVT.isFloatingPoint()))
2965       break;
2966 
2967     // Fast handling of 'identity' bitcasts.
2968     if (BitWidth == SubBitWidth) {
2969       Known = computeKnownBits(N0, DemandedElts, Depth + 1);
2970       break;
2971     }
2972 
2973     bool IsLE = getDataLayout().isLittleEndian();
2974 
2975     // Bitcast 'small element' vector to 'large element' scalar/vector.
2976     if ((BitWidth % SubBitWidth) == 0) {
2977       assert(N0.getValueType().isVector() && "Expected bitcast from vector");
2978 
2979       // Collect known bits for the (larger) output by collecting the known
2980       // bits from each set of sub elements and shift these into place.
2981       // We need to separately call computeKnownBits for each set of
2982       // sub elements as the knownbits for each is likely to be different.
2983       unsigned SubScale = BitWidth / SubBitWidth;
2984       APInt SubDemandedElts(NumElts * SubScale, 0);
2985       for (unsigned i = 0; i != NumElts; ++i)
2986         if (DemandedElts[i])
2987           SubDemandedElts.setBit(i * SubScale);
2988 
2989       for (unsigned i = 0; i != SubScale; ++i) {
2990         Known2 = computeKnownBits(N0, SubDemandedElts.shl(i),
2991                          Depth + 1);
2992         unsigned Shifts = IsLE ? i : SubScale - 1 - i;
2993         Known.insertBits(Known2, SubBitWidth * Shifts);
2994       }
2995     }
2996 
2997     // Bitcast 'large element' scalar/vector to 'small element' vector.
2998     if ((SubBitWidth % BitWidth) == 0) {
2999       assert(Op.getValueType().isVector() && "Expected bitcast to vector");
3000 
3001       // Collect known bits for the (smaller) output by collecting the known
3002       // bits from the overlapping larger input elements and extracting the
3003       // sub sections we actually care about.
3004       unsigned SubScale = SubBitWidth / BitWidth;
3005       APInt SubDemandedElts =
3006           APIntOps::ScaleBitMask(DemandedElts, NumElts / SubScale);
3007       Known2 = computeKnownBits(N0, SubDemandedElts, Depth + 1);
3008 
3009       Known.Zero.setAllBits(); Known.One.setAllBits();
3010       for (unsigned i = 0; i != NumElts; ++i)
3011         if (DemandedElts[i]) {
3012           unsigned Shifts = IsLE ? i : NumElts - 1 - i;
3013           unsigned Offset = (Shifts % SubScale) * BitWidth;
3014           Known = KnownBits::commonBits(Known,
3015                                         Known2.extractBits(BitWidth, Offset));
3016           // If we don't know any bits, early out.
3017           if (Known.isUnknown())
3018             break;
3019         }
3020     }
3021     break;
3022   }
3023   case ISD::AND:
3024     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3025     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3026 
3027     Known &= Known2;
3028     break;
3029   case ISD::OR:
3030     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3031     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3032 
3033     Known |= Known2;
3034     break;
3035   case ISD::XOR:
3036     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3037     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3038 
3039     Known ^= Known2;
3040     break;
3041   case ISD::MUL: {
3042     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3043     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3044     Known = KnownBits::mul(Known, Known2);
3045     break;
3046   }
3047   case ISD::MULHU: {
3048     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3049     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3050     Known = KnownBits::mulhu(Known, Known2);
3051     break;
3052   }
3053   case ISD::MULHS: {
3054     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3055     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3056     Known = KnownBits::mulhs(Known, Known2);
3057     break;
3058   }
3059   case ISD::UMUL_LOHI: {
3060     assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3061     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3062     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3063     if (Op.getResNo() == 0)
3064       Known = KnownBits::mul(Known, Known2);
3065     else
3066       Known = KnownBits::mulhu(Known, Known2);
3067     break;
3068   }
3069   case ISD::SMUL_LOHI: {
3070     assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3071     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3072     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3073     if (Op.getResNo() == 0)
3074       Known = KnownBits::mul(Known, Known2);
3075     else
3076       Known = KnownBits::mulhs(Known, Known2);
3077     break;
3078   }
3079   case ISD::UDIV: {
3080     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3081     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3082     Known = KnownBits::udiv(Known, Known2);
3083     break;
3084   }
3085   case ISD::SELECT:
3086   case ISD::VSELECT:
3087     Known = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
3088     // If we don't know any bits, early out.
3089     if (Known.isUnknown())
3090       break;
3091     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth+1);
3092 
3093     // Only known if known in both the LHS and RHS.
3094     Known = KnownBits::commonBits(Known, Known2);
3095     break;
3096   case ISD::SELECT_CC:
3097     Known = computeKnownBits(Op.getOperand(3), DemandedElts, Depth+1);
3098     // If we don't know any bits, early out.
3099     if (Known.isUnknown())
3100       break;
3101     Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
3102 
3103     // Only known if known in both the LHS and RHS.
3104     Known = KnownBits::commonBits(Known, Known2);
3105     break;
3106   case ISD::SMULO:
3107   case ISD::UMULO:
3108     if (Op.getResNo() != 1)
3109       break;
3110     // The boolean result conforms to getBooleanContents.
3111     // If we know the result of a setcc has the top bits zero, use this info.
3112     // We know that we have an integer-based boolean since these operations
3113     // are only available for integer.
3114     if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
3115             TargetLowering::ZeroOrOneBooleanContent &&
3116         BitWidth > 1)
3117       Known.Zero.setBitsFrom(1);
3118     break;
3119   case ISD::SETCC:
3120   case ISD::STRICT_FSETCC:
3121   case ISD::STRICT_FSETCCS: {
3122     unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
3123     // If we know the result of a setcc has the top bits zero, use this info.
3124     if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
3125             TargetLowering::ZeroOrOneBooleanContent &&
3126         BitWidth > 1)
3127       Known.Zero.setBitsFrom(1);
3128     break;
3129   }
3130   case ISD::SHL:
3131     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3132     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3133     Known = KnownBits::shl(Known, Known2);
3134 
3135     // Minimum shift low bits are known zero.
3136     if (const APInt *ShMinAmt =
3137             getValidMinimumShiftAmountConstant(Op, DemandedElts))
3138       Known.Zero.setLowBits(ShMinAmt->getZExtValue());
3139     break;
3140   case ISD::SRL:
3141     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3142     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3143     Known = KnownBits::lshr(Known, Known2);
3144 
3145     // Minimum shift high bits are known zero.
3146     if (const APInt *ShMinAmt =
3147             getValidMinimumShiftAmountConstant(Op, DemandedElts))
3148       Known.Zero.setHighBits(ShMinAmt->getZExtValue());
3149     break;
3150   case ISD::SRA:
3151     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3152     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3153     Known = KnownBits::ashr(Known, Known2);
3154     // TODO: Add minimum shift high known sign bits.
3155     break;
3156   case ISD::FSHL:
3157   case ISD::FSHR:
3158     if (ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(2), DemandedElts)) {
3159       unsigned Amt = C->getAPIntValue().urem(BitWidth);
3160 
3161       // For fshl, 0-shift returns the 1st arg.
3162       // For fshr, 0-shift returns the 2nd arg.
3163       if (Amt == 0) {
3164         Known = computeKnownBits(Op.getOperand(Opcode == ISD::FSHL ? 0 : 1),
3165                                  DemandedElts, Depth + 1);
3166         break;
3167       }
3168 
3169       // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
3170       // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
3171       Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3172       Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3173       if (Opcode == ISD::FSHL) {
3174         Known.One <<= Amt;
3175         Known.Zero <<= Amt;
3176         Known2.One.lshrInPlace(BitWidth - Amt);
3177         Known2.Zero.lshrInPlace(BitWidth - Amt);
3178       } else {
3179         Known.One <<= BitWidth - Amt;
3180         Known.Zero <<= BitWidth - Amt;
3181         Known2.One.lshrInPlace(Amt);
3182         Known2.Zero.lshrInPlace(Amt);
3183       }
3184       Known.One |= Known2.One;
3185       Known.Zero |= Known2.Zero;
3186     }
3187     break;
3188   case ISD::SIGN_EXTEND_INREG: {
3189     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3190     EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3191     Known = Known.sextInReg(EVT.getScalarSizeInBits());
3192     break;
3193   }
3194   case ISD::CTTZ:
3195   case ISD::CTTZ_ZERO_UNDEF: {
3196     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3197     // If we have a known 1, its position is our upper bound.
3198     unsigned PossibleTZ = Known2.countMaxTrailingZeros();
3199     unsigned LowBits = Log2_32(PossibleTZ) + 1;
3200     Known.Zero.setBitsFrom(LowBits);
3201     break;
3202   }
3203   case ISD::CTLZ:
3204   case ISD::CTLZ_ZERO_UNDEF: {
3205     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3206     // If we have a known 1, its position is our upper bound.
3207     unsigned PossibleLZ = Known2.countMaxLeadingZeros();
3208     unsigned LowBits = Log2_32(PossibleLZ) + 1;
3209     Known.Zero.setBitsFrom(LowBits);
3210     break;
3211   }
3212   case ISD::CTPOP: {
3213     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3214     // If we know some of the bits are zero, they can't be one.
3215     unsigned PossibleOnes = Known2.countMaxPopulation();
3216     Known.Zero.setBitsFrom(Log2_32(PossibleOnes) + 1);
3217     break;
3218   }
3219   case ISD::PARITY: {
3220     // Parity returns 0 everywhere but the LSB.
3221     Known.Zero.setBitsFrom(1);
3222     break;
3223   }
3224   case ISD::LOAD: {
3225     LoadSDNode *LD = cast<LoadSDNode>(Op);
3226     const Constant *Cst = TLI->getTargetConstantFromLoad(LD);
3227     if (ISD::isNON_EXTLoad(LD) && Cst) {
3228       // Determine any common known bits from the loaded constant pool value.
3229       Type *CstTy = Cst->getType();
3230       if ((NumElts * BitWidth) == CstTy->getPrimitiveSizeInBits()) {
3231         // If its a vector splat, then we can (quickly) reuse the scalar path.
3232         // NOTE: We assume all elements match and none are UNDEF.
3233         if (CstTy->isVectorTy()) {
3234           if (const Constant *Splat = Cst->getSplatValue()) {
3235             Cst = Splat;
3236             CstTy = Cst->getType();
3237           }
3238         }
3239         // TODO - do we need to handle different bitwidths?
3240         if (CstTy->isVectorTy() && BitWidth == CstTy->getScalarSizeInBits()) {
3241           // Iterate across all vector elements finding common known bits.
3242           Known.One.setAllBits();
3243           Known.Zero.setAllBits();
3244           for (unsigned i = 0; i != NumElts; ++i) {
3245             if (!DemandedElts[i])
3246               continue;
3247             if (Constant *Elt = Cst->getAggregateElement(i)) {
3248               if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
3249                 const APInt &Value = CInt->getValue();
3250                 Known.One &= Value;
3251                 Known.Zero &= ~Value;
3252                 continue;
3253               }
3254               if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
3255                 APInt Value = CFP->getValueAPF().bitcastToAPInt();
3256                 Known.One &= Value;
3257                 Known.Zero &= ~Value;
3258                 continue;
3259               }
3260             }
3261             Known.One.clearAllBits();
3262             Known.Zero.clearAllBits();
3263             break;
3264           }
3265         } else if (BitWidth == CstTy->getPrimitiveSizeInBits()) {
3266           if (auto *CInt = dyn_cast<ConstantInt>(Cst)) {
3267             Known = KnownBits::makeConstant(CInt->getValue());
3268           } else if (auto *CFP = dyn_cast<ConstantFP>(Cst)) {
3269             Known =
3270                 KnownBits::makeConstant(CFP->getValueAPF().bitcastToAPInt());
3271           }
3272         }
3273       }
3274     } else if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) {
3275       // If this is a ZEXTLoad and we are looking at the loaded value.
3276       EVT VT = LD->getMemoryVT();
3277       unsigned MemBits = VT.getScalarSizeInBits();
3278       Known.Zero.setBitsFrom(MemBits);
3279     } else if (const MDNode *Ranges = LD->getRanges()) {
3280       if (LD->getExtensionType() == ISD::NON_EXTLOAD)
3281         computeKnownBitsFromRangeMetadata(*Ranges, Known);
3282     }
3283     break;
3284   }
3285   case ISD::ZERO_EXTEND_VECTOR_INREG: {
3286     EVT InVT = Op.getOperand(0).getValueType();
3287     APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements());
3288     Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3289     Known = Known.zext(BitWidth);
3290     break;
3291   }
3292   case ISD::ZERO_EXTEND: {
3293     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3294     Known = Known.zext(BitWidth);
3295     break;
3296   }
3297   case ISD::SIGN_EXTEND_VECTOR_INREG: {
3298     EVT InVT = Op.getOperand(0).getValueType();
3299     APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements());
3300     Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3301     // If the sign bit is known to be zero or one, then sext will extend
3302     // it to the top bits, else it will just zext.
3303     Known = Known.sext(BitWidth);
3304     break;
3305   }
3306   case ISD::SIGN_EXTEND: {
3307     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3308     // If the sign bit is known to be zero or one, then sext will extend
3309     // it to the top bits, else it will just zext.
3310     Known = Known.sext(BitWidth);
3311     break;
3312   }
3313   case ISD::ANY_EXTEND_VECTOR_INREG: {
3314     EVT InVT = Op.getOperand(0).getValueType();
3315     APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements());
3316     Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3317     Known = Known.anyext(BitWidth);
3318     break;
3319   }
3320   case ISD::ANY_EXTEND: {
3321     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3322     Known = Known.anyext(BitWidth);
3323     break;
3324   }
3325   case ISD::TRUNCATE: {
3326     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3327     Known = Known.trunc(BitWidth);
3328     break;
3329   }
3330   case ISD::AssertZext: {
3331     EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3332     APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits());
3333     Known = computeKnownBits(Op.getOperand(0), Depth+1);
3334     Known.Zero |= (~InMask);
3335     Known.One  &= (~Known.Zero);
3336     break;
3337   }
3338   case ISD::AssertAlign: {
3339     unsigned LogOfAlign = Log2(cast<AssertAlignSDNode>(Op)->getAlign());
3340     assert(LogOfAlign != 0);
3341     // If a node is guaranteed to be aligned, set low zero bits accordingly as
3342     // well as clearing one bits.
3343     Known.Zero.setLowBits(LogOfAlign);
3344     Known.One.clearLowBits(LogOfAlign);
3345     break;
3346   }
3347   case ISD::FGETSIGN:
3348     // All bits are zero except the low bit.
3349     Known.Zero.setBitsFrom(1);
3350     break;
3351   case ISD::USUBO:
3352   case ISD::SSUBO:
3353     if (Op.getResNo() == 1) {
3354       // If we know the result of a setcc has the top bits zero, use this info.
3355       if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
3356               TargetLowering::ZeroOrOneBooleanContent &&
3357           BitWidth > 1)
3358         Known.Zero.setBitsFrom(1);
3359       break;
3360     }
3361     LLVM_FALLTHROUGH;
3362   case ISD::SUB:
3363   case ISD::SUBC: {
3364     assert(Op.getResNo() == 0 &&
3365            "We only compute knownbits for the difference here.");
3366 
3367     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3368     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3369     Known = KnownBits::computeForAddSub(/* Add */ false, /* NSW */ false,
3370                                         Known, Known2);
3371     break;
3372   }
3373   case ISD::UADDO:
3374   case ISD::SADDO:
3375   case ISD::ADDCARRY:
3376     if (Op.getResNo() == 1) {
3377       // If we know the result of a setcc has the top bits zero, use this info.
3378       if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
3379               TargetLowering::ZeroOrOneBooleanContent &&
3380           BitWidth > 1)
3381         Known.Zero.setBitsFrom(1);
3382       break;
3383     }
3384     LLVM_FALLTHROUGH;
3385   case ISD::ADD:
3386   case ISD::ADDC:
3387   case ISD::ADDE: {
3388     assert(Op.getResNo() == 0 && "We only compute knownbits for the sum here.");
3389 
3390     // With ADDE and ADDCARRY, a carry bit may be added in.
3391     KnownBits Carry(1);
3392     if (Opcode == ISD::ADDE)
3393       // Can't track carry from glue, set carry to unknown.
3394       Carry.resetAll();
3395     else if (Opcode == ISD::ADDCARRY)
3396       // TODO: Compute known bits for the carry operand. Not sure if it is worth
3397       // the trouble (how often will we find a known carry bit). And I haven't
3398       // tested this very much yet, but something like this might work:
3399       //   Carry = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1);
3400       //   Carry = Carry.zextOrTrunc(1, false);
3401       Carry.resetAll();
3402     else
3403       Carry.setAllZero();
3404 
3405     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3406     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3407     Known = KnownBits::computeForAddCarry(Known, Known2, Carry);
3408     break;
3409   }
3410   case ISD::SREM: {
3411     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3412     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3413     Known = KnownBits::srem(Known, Known2);
3414     break;
3415   }
3416   case ISD::UREM: {
3417     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3418     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3419     Known = KnownBits::urem(Known, Known2);
3420     break;
3421   }
3422   case ISD::EXTRACT_ELEMENT: {
3423     Known = computeKnownBits(Op.getOperand(0), Depth+1);
3424     const unsigned Index = Op.getConstantOperandVal(1);
3425     const unsigned EltBitWidth = Op.getValueSizeInBits();
3426 
3427     // Remove low part of known bits mask
3428     Known.Zero = Known.Zero.getHiBits(Known.getBitWidth() - Index * EltBitWidth);
3429     Known.One = Known.One.getHiBits(Known.getBitWidth() - Index * EltBitWidth);
3430 
3431     // Remove high part of known bit mask
3432     Known = Known.trunc(EltBitWidth);
3433     break;
3434   }
3435   case ISD::EXTRACT_VECTOR_ELT: {
3436     SDValue InVec = Op.getOperand(0);
3437     SDValue EltNo = Op.getOperand(1);
3438     EVT VecVT = InVec.getValueType();
3439     // computeKnownBits not yet implemented for scalable vectors.
3440     if (VecVT.isScalableVector())
3441       break;
3442     const unsigned EltBitWidth = VecVT.getScalarSizeInBits();
3443     const unsigned NumSrcElts = VecVT.getVectorNumElements();
3444 
3445     // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know
3446     // anything about the extended bits.
3447     if (BitWidth > EltBitWidth)
3448       Known = Known.trunc(EltBitWidth);
3449 
3450     // If we know the element index, just demand that vector element, else for
3451     // an unknown element index, ignore DemandedElts and demand them all.
3452     APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
3453     auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
3454     if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
3455       DemandedSrcElts =
3456           APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
3457 
3458     Known = computeKnownBits(InVec, DemandedSrcElts, Depth + 1);
3459     if (BitWidth > EltBitWidth)
3460       Known = Known.anyext(BitWidth);
3461     break;
3462   }
3463   case ISD::INSERT_VECTOR_ELT: {
3464     // If we know the element index, split the demand between the
3465     // source vector and the inserted element, otherwise assume we need
3466     // the original demanded vector elements and the value.
3467     SDValue InVec = Op.getOperand(0);
3468     SDValue InVal = Op.getOperand(1);
3469     SDValue EltNo = Op.getOperand(2);
3470     bool DemandedVal = true;
3471     APInt DemandedVecElts = DemandedElts;
3472     auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
3473     if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
3474       unsigned EltIdx = CEltNo->getZExtValue();
3475       DemandedVal = !!DemandedElts[EltIdx];
3476       DemandedVecElts.clearBit(EltIdx);
3477     }
3478     Known.One.setAllBits();
3479     Known.Zero.setAllBits();
3480     if (DemandedVal) {
3481       Known2 = computeKnownBits(InVal, Depth + 1);
3482       Known = KnownBits::commonBits(Known, Known2.zextOrTrunc(BitWidth));
3483     }
3484     if (!!DemandedVecElts) {
3485       Known2 = computeKnownBits(InVec, DemandedVecElts, Depth + 1);
3486       Known = KnownBits::commonBits(Known, Known2);
3487     }
3488     break;
3489   }
3490   case ISD::BITREVERSE: {
3491     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3492     Known = Known2.reverseBits();
3493     break;
3494   }
3495   case ISD::BSWAP: {
3496     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3497     Known = Known2.byteSwap();
3498     break;
3499   }
3500   case ISD::ABS: {
3501     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3502     Known = Known2.abs();
3503     break;
3504   }
3505   case ISD::USUBSAT: {
3506     // The result of usubsat will never be larger than the LHS.
3507     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3508     Known.Zero.setHighBits(Known2.countMinLeadingZeros());
3509     break;
3510   }
3511   case ISD::UMIN: {
3512     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3513     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3514     Known = KnownBits::umin(Known, Known2);
3515     break;
3516   }
3517   case ISD::UMAX: {
3518     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3519     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3520     Known = KnownBits::umax(Known, Known2);
3521     break;
3522   }
3523   case ISD::SMIN:
3524   case ISD::SMAX: {
3525     // If we have a clamp pattern, we know that the number of sign bits will be
3526     // the minimum of the clamp min/max range.
3527     bool IsMax = (Opcode == ISD::SMAX);
3528     ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
3529     if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
3530       if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
3531         CstHigh =
3532             isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
3533     if (CstLow && CstHigh) {
3534       if (!IsMax)
3535         std::swap(CstLow, CstHigh);
3536 
3537       const APInt &ValueLow = CstLow->getAPIntValue();
3538       const APInt &ValueHigh = CstHigh->getAPIntValue();
3539       if (ValueLow.sle(ValueHigh)) {
3540         unsigned LowSignBits = ValueLow.getNumSignBits();
3541         unsigned HighSignBits = ValueHigh.getNumSignBits();
3542         unsigned MinSignBits = std::min(LowSignBits, HighSignBits);
3543         if (ValueLow.isNegative() && ValueHigh.isNegative()) {
3544           Known.One.setHighBits(MinSignBits);
3545           break;
3546         }
3547         if (ValueLow.isNonNegative() && ValueHigh.isNonNegative()) {
3548           Known.Zero.setHighBits(MinSignBits);
3549           break;
3550         }
3551       }
3552     }
3553 
3554     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3555     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3556     if (IsMax)
3557       Known = KnownBits::smax(Known, Known2);
3558     else
3559       Known = KnownBits::smin(Known, Known2);
3560     break;
3561   }
3562   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
3563     if (Op.getResNo() == 1) {
3564       // The boolean result conforms to getBooleanContents.
3565       // If we know the result of a setcc has the top bits zero, use this info.
3566       // We know that we have an integer-based boolean since these operations
3567       // are only available for integer.
3568       if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
3569               TargetLowering::ZeroOrOneBooleanContent &&
3570           BitWidth > 1)
3571         Known.Zero.setBitsFrom(1);
3572       break;
3573     }
3574     LLVM_FALLTHROUGH;
3575   case ISD::ATOMIC_CMP_SWAP:
3576   case ISD::ATOMIC_SWAP:
3577   case ISD::ATOMIC_LOAD_ADD:
3578   case ISD::ATOMIC_LOAD_SUB:
3579   case ISD::ATOMIC_LOAD_AND:
3580   case ISD::ATOMIC_LOAD_CLR:
3581   case ISD::ATOMIC_LOAD_OR:
3582   case ISD::ATOMIC_LOAD_XOR:
3583   case ISD::ATOMIC_LOAD_NAND:
3584   case ISD::ATOMIC_LOAD_MIN:
3585   case ISD::ATOMIC_LOAD_MAX:
3586   case ISD::ATOMIC_LOAD_UMIN:
3587   case ISD::ATOMIC_LOAD_UMAX:
3588   case ISD::ATOMIC_LOAD: {
3589     unsigned MemBits =
3590         cast<AtomicSDNode>(Op)->getMemoryVT().getScalarSizeInBits();
3591     // If we are looking at the loaded value.
3592     if (Op.getResNo() == 0) {
3593       if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND)
3594         Known.Zero.setBitsFrom(MemBits);
3595     }
3596     break;
3597   }
3598   case ISD::FrameIndex:
3599   case ISD::TargetFrameIndex:
3600     TLI->computeKnownBitsForFrameIndex(cast<FrameIndexSDNode>(Op)->getIndex(),
3601                                        Known, getMachineFunction());
3602     break;
3603 
3604   default:
3605     if (Opcode < ISD::BUILTIN_OP_END)
3606       break;
3607     LLVM_FALLTHROUGH;
3608   case ISD::INTRINSIC_WO_CHAIN:
3609   case ISD::INTRINSIC_W_CHAIN:
3610   case ISD::INTRINSIC_VOID:
3611     // Allow the target to implement this method for its nodes.
3612     TLI->computeKnownBitsForTargetNode(Op, Known, DemandedElts, *this, Depth);
3613     break;
3614   }
3615 
3616   assert(!Known.hasConflict() && "Bits known to be one AND zero?");
3617   return Known;
3618 }
3619 
3620 SelectionDAG::OverflowKind SelectionDAG::computeOverflowKind(SDValue N0,
3621                                                              SDValue N1) const {
3622   // X + 0 never overflow
3623   if (isNullConstant(N1))
3624     return OFK_Never;
3625 
3626   KnownBits N1Known = computeKnownBits(N1);
3627   if (N1Known.Zero.getBoolValue()) {
3628     KnownBits N0Known = computeKnownBits(N0);
3629 
3630     bool overflow;
3631     (void)N0Known.getMaxValue().uadd_ov(N1Known.getMaxValue(), overflow);
3632     if (!overflow)
3633       return OFK_Never;
3634   }
3635 
3636   // mulhi + 1 never overflow
3637   if (N0.getOpcode() == ISD::UMUL_LOHI && N0.getResNo() == 1 &&
3638       (N1Known.getMaxValue() & 0x01) == N1Known.getMaxValue())
3639     return OFK_Never;
3640 
3641   if (N1.getOpcode() == ISD::UMUL_LOHI && N1.getResNo() == 1) {
3642     KnownBits N0Known = computeKnownBits(N0);
3643 
3644     if ((N0Known.getMaxValue() & 0x01) == N0Known.getMaxValue())
3645       return OFK_Never;
3646   }
3647 
3648   return OFK_Sometime;
3649 }
3650 
3651 bool SelectionDAG::isKnownToBeAPowerOfTwo(SDValue Val) const {
3652   EVT OpVT = Val.getValueType();
3653   unsigned BitWidth = OpVT.getScalarSizeInBits();
3654 
3655   // Is the constant a known power of 2?
3656   if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Val))
3657     return Const->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
3658 
3659   // A left-shift of a constant one will have exactly one bit set because
3660   // shifting the bit off the end is undefined.
3661   if (Val.getOpcode() == ISD::SHL) {
3662     auto *C = isConstOrConstSplat(Val.getOperand(0));
3663     if (C && C->getAPIntValue() == 1)
3664       return true;
3665   }
3666 
3667   // Similarly, a logical right-shift of a constant sign-bit will have exactly
3668   // one bit set.
3669   if (Val.getOpcode() == ISD::SRL) {
3670     auto *C = isConstOrConstSplat(Val.getOperand(0));
3671     if (C && C->getAPIntValue().isSignMask())
3672       return true;
3673   }
3674 
3675   // Are all operands of a build vector constant powers of two?
3676   if (Val.getOpcode() == ISD::BUILD_VECTOR)
3677     if (llvm::all_of(Val->ops(), [BitWidth](SDValue E) {
3678           if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(E))
3679             return C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
3680           return false;
3681         }))
3682       return true;
3683 
3684   // Is the operand of a splat vector a constant power of two?
3685   if (Val.getOpcode() == ISD::SPLAT_VECTOR)
3686     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val->getOperand(0)))
3687       if (C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2())
3688         return true;
3689 
3690   // More could be done here, though the above checks are enough
3691   // to handle some common cases.
3692 
3693   // Fall back to computeKnownBits to catch other known cases.
3694   KnownBits Known = computeKnownBits(Val);
3695   return (Known.countMaxPopulation() == 1) && (Known.countMinPopulation() == 1);
3696 }
3697 
3698 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const {
3699   EVT VT = Op.getValueType();
3700 
3701   // TODO: Assume we don't know anything for now.
3702   if (VT.isScalableVector())
3703     return 1;
3704 
3705   APInt DemandedElts = VT.isVector()
3706                            ? APInt::getAllOnes(VT.getVectorNumElements())
3707                            : APInt(1, 1);
3708   return ComputeNumSignBits(Op, DemandedElts, Depth);
3709 }
3710 
3711 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, const APInt &DemandedElts,
3712                                           unsigned Depth) const {
3713   EVT VT = Op.getValueType();
3714   assert((VT.isInteger() || VT.isFloatingPoint()) && "Invalid VT!");
3715   unsigned VTBits = VT.getScalarSizeInBits();
3716   unsigned NumElts = DemandedElts.getBitWidth();
3717   unsigned Tmp, Tmp2;
3718   unsigned FirstAnswer = 1;
3719 
3720   if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
3721     const APInt &Val = C->getAPIntValue();
3722     return Val.getNumSignBits();
3723   }
3724 
3725   if (Depth >= MaxRecursionDepth)
3726     return 1;  // Limit search depth.
3727 
3728   if (!DemandedElts || VT.isScalableVector())
3729     return 1;  // No demanded elts, better to assume we don't know anything.
3730 
3731   unsigned Opcode = Op.getOpcode();
3732   switch (Opcode) {
3733   default: break;
3734   case ISD::AssertSext:
3735     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
3736     return VTBits-Tmp+1;
3737   case ISD::AssertZext:
3738     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
3739     return VTBits-Tmp;
3740 
3741   case ISD::BUILD_VECTOR:
3742     Tmp = VTBits;
3743     for (unsigned i = 0, e = Op.getNumOperands(); (i < e) && (Tmp > 1); ++i) {
3744       if (!DemandedElts[i])
3745         continue;
3746 
3747       SDValue SrcOp = Op.getOperand(i);
3748       Tmp2 = ComputeNumSignBits(SrcOp, Depth + 1);
3749 
3750       // BUILD_VECTOR can implicitly truncate sources, we must handle this.
3751       if (SrcOp.getValueSizeInBits() != VTBits) {
3752         assert(SrcOp.getValueSizeInBits() > VTBits &&
3753                "Expected BUILD_VECTOR implicit truncation");
3754         unsigned ExtraBits = SrcOp.getValueSizeInBits() - VTBits;
3755         Tmp2 = (Tmp2 > ExtraBits ? Tmp2 - ExtraBits : 1);
3756       }
3757       Tmp = std::min(Tmp, Tmp2);
3758     }
3759     return Tmp;
3760 
3761   case ISD::VECTOR_SHUFFLE: {
3762     // Collect the minimum number of sign bits that are shared by every vector
3763     // element referenced by the shuffle.
3764     APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
3765     const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
3766     assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
3767     for (unsigned i = 0; i != NumElts; ++i) {
3768       int M = SVN->getMaskElt(i);
3769       if (!DemandedElts[i])
3770         continue;
3771       // For UNDEF elements, we don't know anything about the common state of
3772       // the shuffle result.
3773       if (M < 0)
3774         return 1;
3775       if ((unsigned)M < NumElts)
3776         DemandedLHS.setBit((unsigned)M % NumElts);
3777       else
3778         DemandedRHS.setBit((unsigned)M % NumElts);
3779     }
3780     Tmp = std::numeric_limits<unsigned>::max();
3781     if (!!DemandedLHS)
3782       Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedLHS, Depth + 1);
3783     if (!!DemandedRHS) {
3784       Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedRHS, Depth + 1);
3785       Tmp = std::min(Tmp, Tmp2);
3786     }
3787     // If we don't know anything, early out and try computeKnownBits fall-back.
3788     if (Tmp == 1)
3789       break;
3790     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
3791     return Tmp;
3792   }
3793 
3794   case ISD::BITCAST: {
3795     SDValue N0 = Op.getOperand(0);
3796     EVT SrcVT = N0.getValueType();
3797     unsigned SrcBits = SrcVT.getScalarSizeInBits();
3798 
3799     // Ignore bitcasts from unsupported types..
3800     if (!(SrcVT.isInteger() || SrcVT.isFloatingPoint()))
3801       break;
3802 
3803     // Fast handling of 'identity' bitcasts.
3804     if (VTBits == SrcBits)
3805       return ComputeNumSignBits(N0, DemandedElts, Depth + 1);
3806 
3807     bool IsLE = getDataLayout().isLittleEndian();
3808 
3809     // Bitcast 'large element' scalar/vector to 'small element' vector.
3810     if ((SrcBits % VTBits) == 0) {
3811       assert(VT.isVector() && "Expected bitcast to vector");
3812 
3813       unsigned Scale = SrcBits / VTBits;
3814       APInt SrcDemandedElts =
3815           APIntOps::ScaleBitMask(DemandedElts, NumElts / Scale);
3816 
3817       // Fast case - sign splat can be simply split across the small elements.
3818       Tmp = ComputeNumSignBits(N0, SrcDemandedElts, Depth + 1);
3819       if (Tmp == SrcBits)
3820         return VTBits;
3821 
3822       // Slow case - determine how far the sign extends into each sub-element.
3823       Tmp2 = VTBits;
3824       for (unsigned i = 0; i != NumElts; ++i)
3825         if (DemandedElts[i]) {
3826           unsigned SubOffset = i % Scale;
3827           SubOffset = (IsLE ? ((Scale - 1) - SubOffset) : SubOffset);
3828           SubOffset = SubOffset * VTBits;
3829           if (Tmp <= SubOffset)
3830             return 1;
3831           Tmp2 = std::min(Tmp2, Tmp - SubOffset);
3832         }
3833       return Tmp2;
3834     }
3835     break;
3836   }
3837 
3838   case ISD::SIGN_EXTEND:
3839     Tmp = VTBits - Op.getOperand(0).getScalarValueSizeInBits();
3840     return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1) + Tmp;
3841   case ISD::SIGN_EXTEND_INREG:
3842     // Max of the input and what this extends.
3843     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
3844     Tmp = VTBits-Tmp+1;
3845     Tmp2 = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
3846     return std::max(Tmp, Tmp2);
3847   case ISD::SIGN_EXTEND_VECTOR_INREG: {
3848     SDValue Src = Op.getOperand(0);
3849     EVT SrcVT = Src.getValueType();
3850     APInt DemandedSrcElts = DemandedElts.zextOrSelf(SrcVT.getVectorNumElements());
3851     Tmp = VTBits - SrcVT.getScalarSizeInBits();
3852     return ComputeNumSignBits(Src, DemandedSrcElts, Depth+1) + Tmp;
3853   }
3854   case ISD::SRA:
3855     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3856     // SRA X, C -> adds C sign bits.
3857     if (const APInt *ShAmt =
3858             getValidMinimumShiftAmountConstant(Op, DemandedElts))
3859       Tmp = std::min<uint64_t>(Tmp + ShAmt->getZExtValue(), VTBits);
3860     return Tmp;
3861   case ISD::SHL:
3862     if (const APInt *ShAmt =
3863             getValidMaximumShiftAmountConstant(Op, DemandedElts)) {
3864       // shl destroys sign bits, ensure it doesn't shift out all sign bits.
3865       Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3866       if (ShAmt->ult(Tmp))
3867         return Tmp - ShAmt->getZExtValue();
3868     }
3869     break;
3870   case ISD::AND:
3871   case ISD::OR:
3872   case ISD::XOR:    // NOT is handled here.
3873     // Logical binary ops preserve the number of sign bits at the worst.
3874     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
3875     if (Tmp != 1) {
3876       Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
3877       FirstAnswer = std::min(Tmp, Tmp2);
3878       // We computed what we know about the sign bits as our first
3879       // answer. Now proceed to the generic code that uses
3880       // computeKnownBits, and pick whichever answer is better.
3881     }
3882     break;
3883 
3884   case ISD::SELECT:
3885   case ISD::VSELECT:
3886     Tmp = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
3887     if (Tmp == 1) return 1;  // Early out.
3888     Tmp2 = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
3889     return std::min(Tmp, Tmp2);
3890   case ISD::SELECT_CC:
3891     Tmp = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
3892     if (Tmp == 1) return 1;  // Early out.
3893     Tmp2 = ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth+1);
3894     return std::min(Tmp, Tmp2);
3895 
3896   case ISD::SMIN:
3897   case ISD::SMAX: {
3898     // If we have a clamp pattern, we know that the number of sign bits will be
3899     // the minimum of the clamp min/max range.
3900     bool IsMax = (Opcode == ISD::SMAX);
3901     ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
3902     if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
3903       if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
3904         CstHigh =
3905             isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
3906     if (CstLow && CstHigh) {
3907       if (!IsMax)
3908         std::swap(CstLow, CstHigh);
3909       if (CstLow->getAPIntValue().sle(CstHigh->getAPIntValue())) {
3910         Tmp = CstLow->getAPIntValue().getNumSignBits();
3911         Tmp2 = CstHigh->getAPIntValue().getNumSignBits();
3912         return std::min(Tmp, Tmp2);
3913       }
3914     }
3915 
3916     // Fallback - just get the minimum number of sign bits of the operands.
3917     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3918     if (Tmp == 1)
3919       return 1;  // Early out.
3920     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
3921     return std::min(Tmp, Tmp2);
3922   }
3923   case ISD::UMIN:
3924   case ISD::UMAX:
3925     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3926     if (Tmp == 1)
3927       return 1;  // Early out.
3928     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
3929     return std::min(Tmp, Tmp2);
3930   case ISD::SADDO:
3931   case ISD::UADDO:
3932   case ISD::SSUBO:
3933   case ISD::USUBO:
3934   case ISD::SMULO:
3935   case ISD::UMULO:
3936     if (Op.getResNo() != 1)
3937       break;
3938     // The boolean result conforms to getBooleanContents.  Fall through.
3939     // If setcc returns 0/-1, all bits are sign bits.
3940     // We know that we have an integer-based boolean since these operations
3941     // are only available for integer.
3942     if (TLI->getBooleanContents(VT.isVector(), false) ==
3943         TargetLowering::ZeroOrNegativeOneBooleanContent)
3944       return VTBits;
3945     break;
3946   case ISD::SETCC:
3947   case ISD::STRICT_FSETCC:
3948   case ISD::STRICT_FSETCCS: {
3949     unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
3950     // If setcc returns 0/-1, all bits are sign bits.
3951     if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
3952         TargetLowering::ZeroOrNegativeOneBooleanContent)
3953       return VTBits;
3954     break;
3955   }
3956   case ISD::ROTL:
3957   case ISD::ROTR:
3958     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3959 
3960     // If we're rotating an 0/-1 value, then it stays an 0/-1 value.
3961     if (Tmp == VTBits)
3962       return VTBits;
3963 
3964     if (ConstantSDNode *C =
3965             isConstOrConstSplat(Op.getOperand(1), DemandedElts)) {
3966       unsigned RotAmt = C->getAPIntValue().urem(VTBits);
3967 
3968       // Handle rotate right by N like a rotate left by 32-N.
3969       if (Opcode == ISD::ROTR)
3970         RotAmt = (VTBits - RotAmt) % VTBits;
3971 
3972       // If we aren't rotating out all of the known-in sign bits, return the
3973       // number that are left.  This handles rotl(sext(x), 1) for example.
3974       if (Tmp > (RotAmt + 1)) return (Tmp - RotAmt);
3975     }
3976     break;
3977   case ISD::ADD:
3978   case ISD::ADDC:
3979     // Add can have at most one carry bit.  Thus we know that the output
3980     // is, at worst, one more bit than the inputs.
3981     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3982     if (Tmp == 1) return 1; // Early out.
3983 
3984     // Special case decrementing a value (ADD X, -1):
3985     if (ConstantSDNode *CRHS =
3986             isConstOrConstSplat(Op.getOperand(1), DemandedElts))
3987       if (CRHS->isAllOnes()) {
3988         KnownBits Known =
3989             computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3990 
3991         // If the input is known to be 0 or 1, the output is 0/-1, which is all
3992         // sign bits set.
3993         if ((Known.Zero | 1).isAllOnes())
3994           return VTBits;
3995 
3996         // If we are subtracting one from a positive number, there is no carry
3997         // out of the result.
3998         if (Known.isNonNegative())
3999           return Tmp;
4000       }
4001 
4002     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
4003     if (Tmp2 == 1) return 1; // Early out.
4004     return std::min(Tmp, Tmp2) - 1;
4005   case ISD::SUB:
4006     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
4007     if (Tmp2 == 1) return 1; // Early out.
4008 
4009     // Handle NEG.
4010     if (ConstantSDNode *CLHS =
4011             isConstOrConstSplat(Op.getOperand(0), DemandedElts))
4012       if (CLHS->isZero()) {
4013         KnownBits Known =
4014             computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4015         // If the input is known to be 0 or 1, the output is 0/-1, which is all
4016         // sign bits set.
4017         if ((Known.Zero | 1).isAllOnes())
4018           return VTBits;
4019 
4020         // If the input is known to be positive (the sign bit is known clear),
4021         // the output of the NEG has the same number of sign bits as the input.
4022         if (Known.isNonNegative())
4023           return Tmp2;
4024 
4025         // Otherwise, we treat this like a SUB.
4026       }
4027 
4028     // Sub can have at most one carry bit.  Thus we know that the output
4029     // is, at worst, one more bit than the inputs.
4030     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4031     if (Tmp == 1) return 1; // Early out.
4032     return std::min(Tmp, Tmp2) - 1;
4033   case ISD::MUL: {
4034     // The output of the Mul can be at most twice the valid bits in the inputs.
4035     unsigned SignBitsOp0 = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
4036     if (SignBitsOp0 == 1)
4037       break;
4038     unsigned SignBitsOp1 = ComputeNumSignBits(Op.getOperand(1), Depth + 1);
4039     if (SignBitsOp1 == 1)
4040       break;
4041     unsigned OutValidBits =
4042         (VTBits - SignBitsOp0 + 1) + (VTBits - SignBitsOp1 + 1);
4043     return OutValidBits > VTBits ? 1 : VTBits - OutValidBits + 1;
4044   }
4045   case ISD::SREM:
4046     // The sign bit is the LHS's sign bit, except when the result of the
4047     // remainder is zero. The magnitude of the result should be less than or
4048     // equal to the magnitude of the LHS. Therefore, the result should have
4049     // at least as many sign bits as the left hand side.
4050     return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4051   case ISD::TRUNCATE: {
4052     // Check if the sign bits of source go down as far as the truncated value.
4053     unsigned NumSrcBits = Op.getOperand(0).getScalarValueSizeInBits();
4054     unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
4055     if (NumSrcSignBits > (NumSrcBits - VTBits))
4056       return NumSrcSignBits - (NumSrcBits - VTBits);
4057     break;
4058   }
4059   case ISD::EXTRACT_ELEMENT: {
4060     const int KnownSign = ComputeNumSignBits(Op.getOperand(0), Depth+1);
4061     const int BitWidth = Op.getValueSizeInBits();
4062     const int Items = Op.getOperand(0).getValueSizeInBits() / BitWidth;
4063 
4064     // Get reverse index (starting from 1), Op1 value indexes elements from
4065     // little end. Sign starts at big end.
4066     const int rIndex = Items - 1 - Op.getConstantOperandVal(1);
4067 
4068     // If the sign portion ends in our element the subtraction gives correct
4069     // result. Otherwise it gives either negative or > bitwidth result
4070     return std::max(std::min(KnownSign - rIndex * BitWidth, BitWidth), 0);
4071   }
4072   case ISD::INSERT_VECTOR_ELT: {
4073     // If we know the element index, split the demand between the
4074     // source vector and the inserted element, otherwise assume we need
4075     // the original demanded vector elements and the value.
4076     SDValue InVec = Op.getOperand(0);
4077     SDValue InVal = Op.getOperand(1);
4078     SDValue EltNo = Op.getOperand(2);
4079     bool DemandedVal = true;
4080     APInt DemandedVecElts = DemandedElts;
4081     auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
4082     if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
4083       unsigned EltIdx = CEltNo->getZExtValue();
4084       DemandedVal = !!DemandedElts[EltIdx];
4085       DemandedVecElts.clearBit(EltIdx);
4086     }
4087     Tmp = std::numeric_limits<unsigned>::max();
4088     if (DemandedVal) {
4089       // TODO - handle implicit truncation of inserted elements.
4090       if (InVal.getScalarValueSizeInBits() != VTBits)
4091         break;
4092       Tmp2 = ComputeNumSignBits(InVal, Depth + 1);
4093       Tmp = std::min(Tmp, Tmp2);
4094     }
4095     if (!!DemandedVecElts) {
4096       Tmp2 = ComputeNumSignBits(InVec, DemandedVecElts, Depth + 1);
4097       Tmp = std::min(Tmp, Tmp2);
4098     }
4099     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
4100     return Tmp;
4101   }
4102   case ISD::EXTRACT_VECTOR_ELT: {
4103     SDValue InVec = Op.getOperand(0);
4104     SDValue EltNo = Op.getOperand(1);
4105     EVT VecVT = InVec.getValueType();
4106     // ComputeNumSignBits not yet implemented for scalable vectors.
4107     if (VecVT.isScalableVector())
4108       break;
4109     const unsigned BitWidth = Op.getValueSizeInBits();
4110     const unsigned EltBitWidth = Op.getOperand(0).getScalarValueSizeInBits();
4111     const unsigned NumSrcElts = VecVT.getVectorNumElements();
4112 
4113     // If BitWidth > EltBitWidth the value is anyext:ed, and we do not know
4114     // anything about sign bits. But if the sizes match we can derive knowledge
4115     // about sign bits from the vector operand.
4116     if (BitWidth != EltBitWidth)
4117       break;
4118 
4119     // If we know the element index, just demand that vector element, else for
4120     // an unknown element index, ignore DemandedElts and demand them all.
4121     APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
4122     auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
4123     if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
4124       DemandedSrcElts =
4125           APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
4126 
4127     return ComputeNumSignBits(InVec, DemandedSrcElts, Depth + 1);
4128   }
4129   case ISD::EXTRACT_SUBVECTOR: {
4130     // Offset the demanded elts by the subvector index.
4131     SDValue Src = Op.getOperand(0);
4132     // Bail until we can represent demanded elements for scalable vectors.
4133     if (Src.getValueType().isScalableVector())
4134       break;
4135     uint64_t Idx = Op.getConstantOperandVal(1);
4136     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
4137     APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
4138     return ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
4139   }
4140   case ISD::CONCAT_VECTORS: {
4141     // Determine the minimum number of sign bits across all demanded
4142     // elts of the input vectors. Early out if the result is already 1.
4143     Tmp = std::numeric_limits<unsigned>::max();
4144     EVT SubVectorVT = Op.getOperand(0).getValueType();
4145     unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
4146     unsigned NumSubVectors = Op.getNumOperands();
4147     for (unsigned i = 0; (i < NumSubVectors) && (Tmp > 1); ++i) {
4148       APInt DemandedSub =
4149           DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts);
4150       if (!DemandedSub)
4151         continue;
4152       Tmp2 = ComputeNumSignBits(Op.getOperand(i), DemandedSub, Depth + 1);
4153       Tmp = std::min(Tmp, Tmp2);
4154     }
4155     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
4156     return Tmp;
4157   }
4158   case ISD::INSERT_SUBVECTOR: {
4159     // Demand any elements from the subvector and the remainder from the src its
4160     // inserted into.
4161     SDValue Src = Op.getOperand(0);
4162     SDValue Sub = Op.getOperand(1);
4163     uint64_t Idx = Op.getConstantOperandVal(2);
4164     unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
4165     APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
4166     APInt DemandedSrcElts = DemandedElts;
4167     DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx);
4168 
4169     Tmp = std::numeric_limits<unsigned>::max();
4170     if (!!DemandedSubElts) {
4171       Tmp = ComputeNumSignBits(Sub, DemandedSubElts, Depth + 1);
4172       if (Tmp == 1)
4173         return 1; // early-out
4174     }
4175     if (!!DemandedSrcElts) {
4176       Tmp2 = ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
4177       Tmp = std::min(Tmp, Tmp2);
4178     }
4179     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
4180     return Tmp;
4181   }
4182   case ISD::ATOMIC_CMP_SWAP:
4183   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
4184   case ISD::ATOMIC_SWAP:
4185   case ISD::ATOMIC_LOAD_ADD:
4186   case ISD::ATOMIC_LOAD_SUB:
4187   case ISD::ATOMIC_LOAD_AND:
4188   case ISD::ATOMIC_LOAD_CLR:
4189   case ISD::ATOMIC_LOAD_OR:
4190   case ISD::ATOMIC_LOAD_XOR:
4191   case ISD::ATOMIC_LOAD_NAND:
4192   case ISD::ATOMIC_LOAD_MIN:
4193   case ISD::ATOMIC_LOAD_MAX:
4194   case ISD::ATOMIC_LOAD_UMIN:
4195   case ISD::ATOMIC_LOAD_UMAX:
4196   case ISD::ATOMIC_LOAD: {
4197     Tmp = cast<AtomicSDNode>(Op)->getMemoryVT().getScalarSizeInBits();
4198     // If we are looking at the loaded value.
4199     if (Op.getResNo() == 0) {
4200       if (Tmp == VTBits)
4201         return 1; // early-out
4202       if (TLI->getExtendForAtomicOps() == ISD::SIGN_EXTEND)
4203         return VTBits - Tmp + 1;
4204       if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND)
4205         return VTBits - Tmp;
4206     }
4207     break;
4208   }
4209   }
4210 
4211   // If we are looking at the loaded value of the SDNode.
4212   if (Op.getResNo() == 0) {
4213     // Handle LOADX separately here. EXTLOAD case will fallthrough.
4214     if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
4215       unsigned ExtType = LD->getExtensionType();
4216       switch (ExtType) {
4217       default: break;
4218       case ISD::SEXTLOAD: // e.g. i16->i32 = '17' bits known.
4219         Tmp = LD->getMemoryVT().getScalarSizeInBits();
4220         return VTBits - Tmp + 1;
4221       case ISD::ZEXTLOAD: // e.g. i16->i32 = '16' bits known.
4222         Tmp = LD->getMemoryVT().getScalarSizeInBits();
4223         return VTBits - Tmp;
4224       case ISD::NON_EXTLOAD:
4225         if (const Constant *Cst = TLI->getTargetConstantFromLoad(LD)) {
4226           // We only need to handle vectors - computeKnownBits should handle
4227           // scalar cases.
4228           Type *CstTy = Cst->getType();
4229           if (CstTy->isVectorTy() &&
4230               (NumElts * VTBits) == CstTy->getPrimitiveSizeInBits()) {
4231             Tmp = VTBits;
4232             for (unsigned i = 0; i != NumElts; ++i) {
4233               if (!DemandedElts[i])
4234                 continue;
4235               if (Constant *Elt = Cst->getAggregateElement(i)) {
4236                 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
4237                   const APInt &Value = CInt->getValue();
4238                   Tmp = std::min(Tmp, Value.getNumSignBits());
4239                   continue;
4240                 }
4241                 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
4242                   APInt Value = CFP->getValueAPF().bitcastToAPInt();
4243                   Tmp = std::min(Tmp, Value.getNumSignBits());
4244                   continue;
4245                 }
4246               }
4247               // Unknown type. Conservatively assume no bits match sign bit.
4248               return 1;
4249             }
4250             return Tmp;
4251           }
4252         }
4253         break;
4254       }
4255     }
4256   }
4257 
4258   // Allow the target to implement this method for its nodes.
4259   if (Opcode >= ISD::BUILTIN_OP_END ||
4260       Opcode == ISD::INTRINSIC_WO_CHAIN ||
4261       Opcode == ISD::INTRINSIC_W_CHAIN ||
4262       Opcode == ISD::INTRINSIC_VOID) {
4263     unsigned NumBits =
4264         TLI->ComputeNumSignBitsForTargetNode(Op, DemandedElts, *this, Depth);
4265     if (NumBits > 1)
4266       FirstAnswer = std::max(FirstAnswer, NumBits);
4267   }
4268 
4269   // Finally, if we can prove that the top bits of the result are 0's or 1's,
4270   // use this information.
4271   KnownBits Known = computeKnownBits(Op, DemandedElts, Depth);
4272 
4273   APInt Mask;
4274   if (Known.isNonNegative()) {        // sign bit is 0
4275     Mask = Known.Zero;
4276   } else if (Known.isNegative()) {  // sign bit is 1;
4277     Mask = Known.One;
4278   } else {
4279     // Nothing known.
4280     return FirstAnswer;
4281   }
4282 
4283   // Okay, we know that the sign bit in Mask is set.  Use CLO to determine
4284   // the number of identical bits in the top of the input value.
4285   Mask <<= Mask.getBitWidth()-VTBits;
4286   return std::max(FirstAnswer, Mask.countLeadingOnes());
4287 }
4288 
4289 unsigned SelectionDAG::ComputeMinSignedBits(SDValue Op, unsigned Depth) const {
4290   unsigned SignBits = ComputeNumSignBits(Op, Depth);
4291   return Op.getScalarValueSizeInBits() - SignBits + 1;
4292 }
4293 
4294 unsigned SelectionDAG::ComputeMinSignedBits(SDValue Op,
4295                                             const APInt &DemandedElts,
4296                                             unsigned Depth) const {
4297   unsigned SignBits = ComputeNumSignBits(Op, DemandedElts, Depth);
4298   return Op.getScalarValueSizeInBits() - SignBits + 1;
4299 }
4300 
4301 bool SelectionDAG::isGuaranteedNotToBeUndefOrPoison(SDValue Op, bool PoisonOnly,
4302                                                     unsigned Depth) const {
4303   // Early out for FREEZE.
4304   if (Op.getOpcode() == ISD::FREEZE)
4305     return true;
4306 
4307   // TODO: Assume we don't know anything for now.
4308   EVT VT = Op.getValueType();
4309   if (VT.isScalableVector())
4310     return false;
4311 
4312   APInt DemandedElts = VT.isVector()
4313                            ? APInt::getAllOnes(VT.getVectorNumElements())
4314                            : APInt(1, 1);
4315   return isGuaranteedNotToBeUndefOrPoison(Op, DemandedElts, PoisonOnly, Depth);
4316 }
4317 
4318 bool SelectionDAG::isGuaranteedNotToBeUndefOrPoison(SDValue Op,
4319                                                     const APInt &DemandedElts,
4320                                                     bool PoisonOnly,
4321                                                     unsigned Depth) const {
4322   unsigned Opcode = Op.getOpcode();
4323 
4324   // Early out for FREEZE.
4325   if (Opcode == ISD::FREEZE)
4326     return true;
4327 
4328   if (Depth >= MaxRecursionDepth)
4329     return false; // Limit search depth.
4330 
4331   if (isIntOrFPConstant(Op))
4332     return true;
4333 
4334   switch (Opcode) {
4335   case ISD::UNDEF:
4336     return PoisonOnly;
4337 
4338   case ISD::BUILD_VECTOR:
4339     // NOTE: BUILD_VECTOR has implicit truncation of wider scalar elements -
4340     // this shouldn't affect the result.
4341     for (unsigned i = 0, e = Op.getNumOperands(); i < e; ++i) {
4342       if (!DemandedElts[i])
4343         continue;
4344       if (!isGuaranteedNotToBeUndefOrPoison(Op.getOperand(i), PoisonOnly,
4345                                             Depth + 1))
4346         return false;
4347     }
4348     return true;
4349 
4350   // TODO: Search for noundef attributes from library functions.
4351 
4352   // TODO: Pointers dereferenced by ISD::LOAD/STORE ops are noundef.
4353 
4354   default:
4355     // Allow the target to implement this method for its nodes.
4356     if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
4357         Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID)
4358       return TLI->isGuaranteedNotToBeUndefOrPoisonForTargetNode(
4359           Op, DemandedElts, *this, PoisonOnly, Depth);
4360     break;
4361   }
4362 
4363   return false;
4364 }
4365 
4366 bool SelectionDAG::isBaseWithConstantOffset(SDValue Op) const {
4367   if ((Op.getOpcode() != ISD::ADD && Op.getOpcode() != ISD::OR) ||
4368       !isa<ConstantSDNode>(Op.getOperand(1)))
4369     return false;
4370 
4371   if (Op.getOpcode() == ISD::OR &&
4372       !MaskedValueIsZero(Op.getOperand(0), Op.getConstantOperandAPInt(1)))
4373     return false;
4374 
4375   return true;
4376 }
4377 
4378 bool SelectionDAG::isKnownNeverNaN(SDValue Op, bool SNaN, unsigned Depth) const {
4379   // If we're told that NaNs won't happen, assume they won't.
4380   if (getTarget().Options.NoNaNsFPMath || Op->getFlags().hasNoNaNs())
4381     return true;
4382 
4383   if (Depth >= MaxRecursionDepth)
4384     return false; // Limit search depth.
4385 
4386   // TODO: Handle vectors.
4387   // If the value is a constant, we can obviously see if it is a NaN or not.
4388   if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) {
4389     return !C->getValueAPF().isNaN() ||
4390            (SNaN && !C->getValueAPF().isSignaling());
4391   }
4392 
4393   unsigned Opcode = Op.getOpcode();
4394   switch (Opcode) {
4395   case ISD::FADD:
4396   case ISD::FSUB:
4397   case ISD::FMUL:
4398   case ISD::FDIV:
4399   case ISD::FREM:
4400   case ISD::FSIN:
4401   case ISD::FCOS: {
4402     if (SNaN)
4403       return true;
4404     // TODO: Need isKnownNeverInfinity
4405     return false;
4406   }
4407   case ISD::FCANONICALIZE:
4408   case ISD::FEXP:
4409   case ISD::FEXP2:
4410   case ISD::FTRUNC:
4411   case ISD::FFLOOR:
4412   case ISD::FCEIL:
4413   case ISD::FROUND:
4414   case ISD::FROUNDEVEN:
4415   case ISD::FRINT:
4416   case ISD::FNEARBYINT: {
4417     if (SNaN)
4418       return true;
4419     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4420   }
4421   case ISD::FABS:
4422   case ISD::FNEG:
4423   case ISD::FCOPYSIGN: {
4424     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4425   }
4426   case ISD::SELECT:
4427     return isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) &&
4428            isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1);
4429   case ISD::FP_EXTEND:
4430   case ISD::FP_ROUND: {
4431     if (SNaN)
4432       return true;
4433     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4434   }
4435   case ISD::SINT_TO_FP:
4436   case ISD::UINT_TO_FP:
4437     return true;
4438   case ISD::FMA:
4439   case ISD::FMAD: {
4440     if (SNaN)
4441       return true;
4442     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) &&
4443            isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) &&
4444            isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1);
4445   }
4446   case ISD::FSQRT: // Need is known positive
4447   case ISD::FLOG:
4448   case ISD::FLOG2:
4449   case ISD::FLOG10:
4450   case ISD::FPOWI:
4451   case ISD::FPOW: {
4452     if (SNaN)
4453       return true;
4454     // TODO: Refine on operand
4455     return false;
4456   }
4457   case ISD::FMINNUM:
4458   case ISD::FMAXNUM: {
4459     // Only one needs to be known not-nan, since it will be returned if the
4460     // other ends up being one.
4461     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) ||
4462            isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1);
4463   }
4464   case ISD::FMINNUM_IEEE:
4465   case ISD::FMAXNUM_IEEE: {
4466     if (SNaN)
4467       return true;
4468     // This can return a NaN if either operand is an sNaN, or if both operands
4469     // are NaN.
4470     return (isKnownNeverNaN(Op.getOperand(0), false, Depth + 1) &&
4471             isKnownNeverSNaN(Op.getOperand(1), Depth + 1)) ||
4472            (isKnownNeverNaN(Op.getOperand(1), false, Depth + 1) &&
4473             isKnownNeverSNaN(Op.getOperand(0), Depth + 1));
4474   }
4475   case ISD::FMINIMUM:
4476   case ISD::FMAXIMUM: {
4477     // TODO: Does this quiet or return the origina NaN as-is?
4478     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) &&
4479            isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1);
4480   }
4481   case ISD::EXTRACT_VECTOR_ELT: {
4482     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4483   }
4484   default:
4485     if (Opcode >= ISD::BUILTIN_OP_END ||
4486         Opcode == ISD::INTRINSIC_WO_CHAIN ||
4487         Opcode == ISD::INTRINSIC_W_CHAIN ||
4488         Opcode == ISD::INTRINSIC_VOID) {
4489       return TLI->isKnownNeverNaNForTargetNode(Op, *this, SNaN, Depth);
4490     }
4491 
4492     return false;
4493   }
4494 }
4495 
4496 bool SelectionDAG::isKnownNeverZeroFloat(SDValue Op) const {
4497   assert(Op.getValueType().isFloatingPoint() &&
4498          "Floating point type expected");
4499 
4500   // If the value is a constant, we can obviously see if it is a zero or not.
4501   // TODO: Add BuildVector support.
4502   if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
4503     return !C->isZero();
4504   return false;
4505 }
4506 
4507 bool SelectionDAG::isKnownNeverZero(SDValue Op) const {
4508   assert(!Op.getValueType().isFloatingPoint() &&
4509          "Floating point types unsupported - use isKnownNeverZeroFloat");
4510 
4511   // If the value is a constant, we can obviously see if it is a zero or not.
4512   if (ISD::matchUnaryPredicate(Op,
4513                                [](ConstantSDNode *C) { return !C->isZero(); }))
4514     return true;
4515 
4516   // TODO: Recognize more cases here.
4517   switch (Op.getOpcode()) {
4518   default: break;
4519   case ISD::OR:
4520     if (isKnownNeverZero(Op.getOperand(1)) ||
4521         isKnownNeverZero(Op.getOperand(0)))
4522       return true;
4523     break;
4524   }
4525 
4526   return false;
4527 }
4528 
4529 bool SelectionDAG::isEqualTo(SDValue A, SDValue B) const {
4530   // Check the obvious case.
4531   if (A == B) return true;
4532 
4533   // For for negative and positive zero.
4534   if (const ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A))
4535     if (const ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B))
4536       if (CA->isZero() && CB->isZero()) return true;
4537 
4538   // Otherwise they may not be equal.
4539   return false;
4540 }
4541 
4542 // FIXME: unify with llvm::haveNoCommonBitsSet.
4543 // FIXME: could also handle masked merge pattern (X & ~M) op (Y & M)
4544 bool SelectionDAG::haveNoCommonBitsSet(SDValue A, SDValue B) const {
4545   assert(A.getValueType() == B.getValueType() &&
4546          "Values must have the same type");
4547   return KnownBits::haveNoCommonBitsSet(computeKnownBits(A),
4548                                         computeKnownBits(B));
4549 }
4550 
4551 static SDValue FoldSTEP_VECTOR(const SDLoc &DL, EVT VT, SDValue Step,
4552                                SelectionDAG &DAG) {
4553   if (cast<ConstantSDNode>(Step)->isZero())
4554     return DAG.getConstant(0, DL, VT);
4555 
4556   return SDValue();
4557 }
4558 
4559 static SDValue FoldBUILD_VECTOR(const SDLoc &DL, EVT VT,
4560                                 ArrayRef<SDValue> Ops,
4561                                 SelectionDAG &DAG) {
4562   int NumOps = Ops.size();
4563   assert(NumOps != 0 && "Can't build an empty vector!");
4564   assert(!VT.isScalableVector() &&
4565          "BUILD_VECTOR cannot be used with scalable types");
4566   assert(VT.getVectorNumElements() == (unsigned)NumOps &&
4567          "Incorrect element count in BUILD_VECTOR!");
4568 
4569   // BUILD_VECTOR of UNDEFs is UNDEF.
4570   if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
4571     return DAG.getUNDEF(VT);
4572 
4573   // BUILD_VECTOR of seq extract/insert from the same vector + type is Identity.
4574   SDValue IdentitySrc;
4575   bool IsIdentity = true;
4576   for (int i = 0; i != NumOps; ++i) {
4577     if (Ops[i].getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4578         Ops[i].getOperand(0).getValueType() != VT ||
4579         (IdentitySrc && Ops[i].getOperand(0) != IdentitySrc) ||
4580         !isa<ConstantSDNode>(Ops[i].getOperand(1)) ||
4581         cast<ConstantSDNode>(Ops[i].getOperand(1))->getAPIntValue() != i) {
4582       IsIdentity = false;
4583       break;
4584     }
4585     IdentitySrc = Ops[i].getOperand(0);
4586   }
4587   if (IsIdentity)
4588     return IdentitySrc;
4589 
4590   return SDValue();
4591 }
4592 
4593 /// Try to simplify vector concatenation to an input value, undef, or build
4594 /// vector.
4595 static SDValue foldCONCAT_VECTORS(const SDLoc &DL, EVT VT,
4596                                   ArrayRef<SDValue> Ops,
4597                                   SelectionDAG &DAG) {
4598   assert(!Ops.empty() && "Can't concatenate an empty list of vectors!");
4599   assert(llvm::all_of(Ops,
4600                       [Ops](SDValue Op) {
4601                         return Ops[0].getValueType() == Op.getValueType();
4602                       }) &&
4603          "Concatenation of vectors with inconsistent value types!");
4604   assert((Ops[0].getValueType().getVectorElementCount() * Ops.size()) ==
4605              VT.getVectorElementCount() &&
4606          "Incorrect element count in vector concatenation!");
4607 
4608   if (Ops.size() == 1)
4609     return Ops[0];
4610 
4611   // Concat of UNDEFs is UNDEF.
4612   if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
4613     return DAG.getUNDEF(VT);
4614 
4615   // Scan the operands and look for extract operations from a single source
4616   // that correspond to insertion at the same location via this concatenation:
4617   // concat (extract X, 0*subvec_elts), (extract X, 1*subvec_elts), ...
4618   SDValue IdentitySrc;
4619   bool IsIdentity = true;
4620   for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
4621     SDValue Op = Ops[i];
4622     unsigned IdentityIndex = i * Op.getValueType().getVectorMinNumElements();
4623     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
4624         Op.getOperand(0).getValueType() != VT ||
4625         (IdentitySrc && Op.getOperand(0) != IdentitySrc) ||
4626         Op.getConstantOperandVal(1) != IdentityIndex) {
4627       IsIdentity = false;
4628       break;
4629     }
4630     assert((!IdentitySrc || IdentitySrc == Op.getOperand(0)) &&
4631            "Unexpected identity source vector for concat of extracts");
4632     IdentitySrc = Op.getOperand(0);
4633   }
4634   if (IsIdentity) {
4635     assert(IdentitySrc && "Failed to set source vector of extracts");
4636     return IdentitySrc;
4637   }
4638 
4639   // The code below this point is only designed to work for fixed width
4640   // vectors, so we bail out for now.
4641   if (VT.isScalableVector())
4642     return SDValue();
4643 
4644   // A CONCAT_VECTOR with all UNDEF/BUILD_VECTOR operands can be
4645   // simplified to one big BUILD_VECTOR.
4646   // FIXME: Add support for SCALAR_TO_VECTOR as well.
4647   EVT SVT = VT.getScalarType();
4648   SmallVector<SDValue, 16> Elts;
4649   for (SDValue Op : Ops) {
4650     EVT OpVT = Op.getValueType();
4651     if (Op.isUndef())
4652       Elts.append(OpVT.getVectorNumElements(), DAG.getUNDEF(SVT));
4653     else if (Op.getOpcode() == ISD::BUILD_VECTOR)
4654       Elts.append(Op->op_begin(), Op->op_end());
4655     else
4656       return SDValue();
4657   }
4658 
4659   // BUILD_VECTOR requires all inputs to be of the same type, find the
4660   // maximum type and extend them all.
4661   for (SDValue Op : Elts)
4662     SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
4663 
4664   if (SVT.bitsGT(VT.getScalarType())) {
4665     for (SDValue &Op : Elts) {
4666       if (Op.isUndef())
4667         Op = DAG.getUNDEF(SVT);
4668       else
4669         Op = DAG.getTargetLoweringInfo().isZExtFree(Op.getValueType(), SVT)
4670                  ? DAG.getZExtOrTrunc(Op, DL, SVT)
4671                  : DAG.getSExtOrTrunc(Op, DL, SVT);
4672     }
4673   }
4674 
4675   SDValue V = DAG.getBuildVector(VT, DL, Elts);
4676   NewSDValueDbgMsg(V, "New node fold concat vectors: ", &DAG);
4677   return V;
4678 }
4679 
4680 /// Gets or creates the specified node.
4681 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT) {
4682   FoldingSetNodeID ID;
4683   AddNodeIDNode(ID, Opcode, getVTList(VT), None);
4684   void *IP = nullptr;
4685   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
4686     return SDValue(E, 0);
4687 
4688   auto *N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(),
4689                               getVTList(VT));
4690   CSEMap.InsertNode(N, IP);
4691 
4692   InsertNode(N);
4693   SDValue V = SDValue(N, 0);
4694   NewSDValueDbgMsg(V, "Creating new node: ", this);
4695   return V;
4696 }
4697 
4698 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4699                               SDValue Operand) {
4700   SDNodeFlags Flags;
4701   if (Inserter)
4702     Flags = Inserter->getFlags();
4703   return getNode(Opcode, DL, VT, Operand, Flags);
4704 }
4705 
4706 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4707                               SDValue Operand, const SDNodeFlags Flags) {
4708   assert(Operand.getOpcode() != ISD::DELETED_NODE &&
4709          "Operand is DELETED_NODE!");
4710   // Constant fold unary operations with an integer constant operand. Even
4711   // opaque constant will be folded, because the folding of unary operations
4712   // doesn't create new constants with different values. Nevertheless, the
4713   // opaque flag is preserved during folding to prevent future folding with
4714   // other constants.
4715   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand)) {
4716     const APInt &Val = C->getAPIntValue();
4717     switch (Opcode) {
4718     default: break;
4719     case ISD::SIGN_EXTEND:
4720       return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
4721                          C->isTargetOpcode(), C->isOpaque());
4722     case ISD::TRUNCATE:
4723       if (C->isOpaque())
4724         break;
4725       LLVM_FALLTHROUGH;
4726     case ISD::ZERO_EXTEND:
4727       return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
4728                          C->isTargetOpcode(), C->isOpaque());
4729     case ISD::ANY_EXTEND:
4730       // Some targets like RISCV prefer to sign extend some types.
4731       if (TLI->isSExtCheaperThanZExt(Operand.getValueType(), VT))
4732         return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
4733                            C->isTargetOpcode(), C->isOpaque());
4734       return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
4735                          C->isTargetOpcode(), C->isOpaque());
4736     case ISD::UINT_TO_FP:
4737     case ISD::SINT_TO_FP: {
4738       APFloat apf(EVTToAPFloatSemantics(VT),
4739                   APInt::getZero(VT.getSizeInBits()));
4740       (void)apf.convertFromAPInt(Val,
4741                                  Opcode==ISD::SINT_TO_FP,
4742                                  APFloat::rmNearestTiesToEven);
4743       return getConstantFP(apf, DL, VT);
4744     }
4745     case ISD::BITCAST:
4746       if (VT == MVT::f16 && C->getValueType(0) == MVT::i16)
4747         return getConstantFP(APFloat(APFloat::IEEEhalf(), Val), DL, VT);
4748       if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
4749         return getConstantFP(APFloat(APFloat::IEEEsingle(), Val), DL, VT);
4750       if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
4751         return getConstantFP(APFloat(APFloat::IEEEdouble(), Val), DL, VT);
4752       if (VT == MVT::f128 && C->getValueType(0) == MVT::i128)
4753         return getConstantFP(APFloat(APFloat::IEEEquad(), Val), DL, VT);
4754       break;
4755     case ISD::ABS:
4756       return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(),
4757                          C->isOpaque());
4758     case ISD::BITREVERSE:
4759       return getConstant(Val.reverseBits(), DL, VT, C->isTargetOpcode(),
4760                          C->isOpaque());
4761     case ISD::BSWAP:
4762       return getConstant(Val.byteSwap(), DL, VT, C->isTargetOpcode(),
4763                          C->isOpaque());
4764     case ISD::CTPOP:
4765       return getConstant(Val.countPopulation(), DL, VT, C->isTargetOpcode(),
4766                          C->isOpaque());
4767     case ISD::CTLZ:
4768     case ISD::CTLZ_ZERO_UNDEF:
4769       return getConstant(Val.countLeadingZeros(), DL, VT, C->isTargetOpcode(),
4770                          C->isOpaque());
4771     case ISD::CTTZ:
4772     case ISD::CTTZ_ZERO_UNDEF:
4773       return getConstant(Val.countTrailingZeros(), DL, VT, C->isTargetOpcode(),
4774                          C->isOpaque());
4775     case ISD::FP16_TO_FP: {
4776       bool Ignored;
4777       APFloat FPV(APFloat::IEEEhalf(),
4778                   (Val.getBitWidth() == 16) ? Val : Val.trunc(16));
4779 
4780       // This can return overflow, underflow, or inexact; we don't care.
4781       // FIXME need to be more flexible about rounding mode.
4782       (void)FPV.convert(EVTToAPFloatSemantics(VT),
4783                         APFloat::rmNearestTiesToEven, &Ignored);
4784       return getConstantFP(FPV, DL, VT);
4785     }
4786     case ISD::STEP_VECTOR: {
4787       if (SDValue V = FoldSTEP_VECTOR(DL, VT, Operand, *this))
4788         return V;
4789       break;
4790     }
4791     }
4792   }
4793 
4794   // Constant fold unary operations with a floating point constant operand.
4795   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand)) {
4796     APFloat V = C->getValueAPF();    // make copy
4797     switch (Opcode) {
4798     case ISD::FNEG:
4799       V.changeSign();
4800       return getConstantFP(V, DL, VT);
4801     case ISD::FABS:
4802       V.clearSign();
4803       return getConstantFP(V, DL, VT);
4804     case ISD::FCEIL: {
4805       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardPositive);
4806       if (fs == APFloat::opOK || fs == APFloat::opInexact)
4807         return getConstantFP(V, DL, VT);
4808       break;
4809     }
4810     case ISD::FTRUNC: {
4811       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardZero);
4812       if (fs == APFloat::opOK || fs == APFloat::opInexact)
4813         return getConstantFP(V, DL, VT);
4814       break;
4815     }
4816     case ISD::FFLOOR: {
4817       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardNegative);
4818       if (fs == APFloat::opOK || fs == APFloat::opInexact)
4819         return getConstantFP(V, DL, VT);
4820       break;
4821     }
4822     case ISD::FP_EXTEND: {
4823       bool ignored;
4824       // This can return overflow, underflow, or inexact; we don't care.
4825       // FIXME need to be more flexible about rounding mode.
4826       (void)V.convert(EVTToAPFloatSemantics(VT),
4827                       APFloat::rmNearestTiesToEven, &ignored);
4828       return getConstantFP(V, DL, VT);
4829     }
4830     case ISD::FP_TO_SINT:
4831     case ISD::FP_TO_UINT: {
4832       bool ignored;
4833       APSInt IntVal(VT.getSizeInBits(), Opcode == ISD::FP_TO_UINT);
4834       // FIXME need to be more flexible about rounding mode.
4835       APFloat::opStatus s =
4836           V.convertToInteger(IntVal, APFloat::rmTowardZero, &ignored);
4837       if (s == APFloat::opInvalidOp) // inexact is OK, in fact usual
4838         break;
4839       return getConstant(IntVal, DL, VT);
4840     }
4841     case ISD::BITCAST:
4842       if (VT == MVT::i16 && C->getValueType(0) == MVT::f16)
4843         return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
4844       if (VT == MVT::i16 && C->getValueType(0) == MVT::bf16)
4845         return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
4846       if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
4847         return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
4848       if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
4849         return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
4850       break;
4851     case ISD::FP_TO_FP16: {
4852       bool Ignored;
4853       // This can return overflow, underflow, or inexact; we don't care.
4854       // FIXME need to be more flexible about rounding mode.
4855       (void)V.convert(APFloat::IEEEhalf(),
4856                       APFloat::rmNearestTiesToEven, &Ignored);
4857       return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
4858     }
4859     }
4860   }
4861 
4862   // Constant fold unary operations with a vector integer or float operand.
4863   switch (Opcode) {
4864   default:
4865     // FIXME: Entirely reasonable to perform folding of other unary
4866     // operations here as the need arises.
4867     break;
4868   case ISD::FNEG:
4869   case ISD::FABS:
4870   case ISD::FCEIL:
4871   case ISD::FTRUNC:
4872   case ISD::FFLOOR:
4873   case ISD::FP_EXTEND:
4874   case ISD::FP_TO_SINT:
4875   case ISD::FP_TO_UINT:
4876   case ISD::TRUNCATE:
4877   case ISD::ANY_EXTEND:
4878   case ISD::ZERO_EXTEND:
4879   case ISD::SIGN_EXTEND:
4880   case ISD::UINT_TO_FP:
4881   case ISD::SINT_TO_FP:
4882   case ISD::ABS:
4883   case ISD::BITREVERSE:
4884   case ISD::BSWAP:
4885   case ISD::CTLZ:
4886   case ISD::CTLZ_ZERO_UNDEF:
4887   case ISD::CTTZ:
4888   case ISD::CTTZ_ZERO_UNDEF:
4889   case ISD::CTPOP: {
4890     SDValue Ops = {Operand};
4891     if (SDValue Fold = FoldConstantArithmetic(Opcode, DL, VT, Ops))
4892       return Fold;
4893   }
4894   }
4895 
4896   unsigned OpOpcode = Operand.getNode()->getOpcode();
4897   switch (Opcode) {
4898   case ISD::STEP_VECTOR:
4899     assert(VT.isScalableVector() &&
4900            "STEP_VECTOR can only be used with scalable types");
4901     assert(OpOpcode == ISD::TargetConstant &&
4902            VT.getVectorElementType() == Operand.getValueType() &&
4903            "Unexpected step operand");
4904     break;
4905   case ISD::FREEZE:
4906     assert(VT == Operand.getValueType() && "Unexpected VT!");
4907     break;
4908   case ISD::TokenFactor:
4909   case ISD::MERGE_VALUES:
4910   case ISD::CONCAT_VECTORS:
4911     return Operand;         // Factor, merge or concat of one node?  No need.
4912   case ISD::BUILD_VECTOR: {
4913     // Attempt to simplify BUILD_VECTOR.
4914     SDValue Ops[] = {Operand};
4915     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
4916       return V;
4917     break;
4918   }
4919   case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node");
4920   case ISD::FP_EXTEND:
4921     assert(VT.isFloatingPoint() &&
4922            Operand.getValueType().isFloatingPoint() && "Invalid FP cast!");
4923     if (Operand.getValueType() == VT) return Operand;  // noop conversion.
4924     assert((!VT.isVector() ||
4925             VT.getVectorElementCount() ==
4926             Operand.getValueType().getVectorElementCount()) &&
4927            "Vector element count mismatch!");
4928     assert(Operand.getValueType().bitsLT(VT) &&
4929            "Invalid fpext node, dst < src!");
4930     if (Operand.isUndef())
4931       return getUNDEF(VT);
4932     break;
4933   case ISD::FP_TO_SINT:
4934   case ISD::FP_TO_UINT:
4935     if (Operand.isUndef())
4936       return getUNDEF(VT);
4937     break;
4938   case ISD::SINT_TO_FP:
4939   case ISD::UINT_TO_FP:
4940     // [us]itofp(undef) = 0, because the result value is bounded.
4941     if (Operand.isUndef())
4942       return getConstantFP(0.0, DL, VT);
4943     break;
4944   case ISD::SIGN_EXTEND:
4945     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
4946            "Invalid SIGN_EXTEND!");
4947     assert(VT.isVector() == Operand.getValueType().isVector() &&
4948            "SIGN_EXTEND result type type should be vector iff the operand "
4949            "type is vector!");
4950     if (Operand.getValueType() == VT) return Operand;   // noop extension
4951     assert((!VT.isVector() ||
4952             VT.getVectorElementCount() ==
4953                 Operand.getValueType().getVectorElementCount()) &&
4954            "Vector element count mismatch!");
4955     assert(Operand.getValueType().bitsLT(VT) &&
4956            "Invalid sext node, dst < src!");
4957     if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
4958       return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
4959     if (OpOpcode == ISD::UNDEF)
4960       // sext(undef) = 0, because the top bits will all be the same.
4961       return getConstant(0, DL, VT);
4962     break;
4963   case ISD::ZERO_EXTEND:
4964     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
4965            "Invalid ZERO_EXTEND!");
4966     assert(VT.isVector() == Operand.getValueType().isVector() &&
4967            "ZERO_EXTEND result type type should be vector iff the operand "
4968            "type is vector!");
4969     if (Operand.getValueType() == VT) return Operand;   // noop extension
4970     assert((!VT.isVector() ||
4971             VT.getVectorElementCount() ==
4972                 Operand.getValueType().getVectorElementCount()) &&
4973            "Vector element count mismatch!");
4974     assert(Operand.getValueType().bitsLT(VT) &&
4975            "Invalid zext node, dst < src!");
4976     if (OpOpcode == ISD::ZERO_EXTEND)   // (zext (zext x)) -> (zext x)
4977       return getNode(ISD::ZERO_EXTEND, DL, VT, Operand.getOperand(0));
4978     if (OpOpcode == ISD::UNDEF)
4979       // zext(undef) = 0, because the top bits will be zero.
4980       return getConstant(0, DL, VT);
4981     break;
4982   case ISD::ANY_EXTEND:
4983     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
4984            "Invalid ANY_EXTEND!");
4985     assert(VT.isVector() == Operand.getValueType().isVector() &&
4986            "ANY_EXTEND result type type should be vector iff the operand "
4987            "type is vector!");
4988     if (Operand.getValueType() == VT) return Operand;   // noop extension
4989     assert((!VT.isVector() ||
4990             VT.getVectorElementCount() ==
4991                 Operand.getValueType().getVectorElementCount()) &&
4992            "Vector element count mismatch!");
4993     assert(Operand.getValueType().bitsLT(VT) &&
4994            "Invalid anyext node, dst < src!");
4995 
4996     if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
4997         OpOpcode == ISD::ANY_EXTEND)
4998       // (ext (zext x)) -> (zext x)  and  (ext (sext x)) -> (sext x)
4999       return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
5000     if (OpOpcode == ISD::UNDEF)
5001       return getUNDEF(VT);
5002 
5003     // (ext (trunc x)) -> x
5004     if (OpOpcode == ISD::TRUNCATE) {
5005       SDValue OpOp = Operand.getOperand(0);
5006       if (OpOp.getValueType() == VT) {
5007         transferDbgValues(Operand, OpOp);
5008         return OpOp;
5009       }
5010     }
5011     break;
5012   case ISD::TRUNCATE:
5013     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
5014            "Invalid TRUNCATE!");
5015     assert(VT.isVector() == Operand.getValueType().isVector() &&
5016            "TRUNCATE result type type should be vector iff the operand "
5017            "type is vector!");
5018     if (Operand.getValueType() == VT) return Operand;   // noop truncate
5019     assert((!VT.isVector() ||
5020             VT.getVectorElementCount() ==
5021                 Operand.getValueType().getVectorElementCount()) &&
5022            "Vector element count mismatch!");
5023     assert(Operand.getValueType().bitsGT(VT) &&
5024            "Invalid truncate node, src < dst!");
5025     if (OpOpcode == ISD::TRUNCATE)
5026       return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0));
5027     if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
5028         OpOpcode == ISD::ANY_EXTEND) {
5029       // If the source is smaller than the dest, we still need an extend.
5030       if (Operand.getOperand(0).getValueType().getScalarType()
5031             .bitsLT(VT.getScalarType()))
5032         return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
5033       if (Operand.getOperand(0).getValueType().bitsGT(VT))
5034         return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0));
5035       return Operand.getOperand(0);
5036     }
5037     if (OpOpcode == ISD::UNDEF)
5038       return getUNDEF(VT);
5039     if (OpOpcode == ISD::VSCALE && !NewNodesMustHaveLegalTypes)
5040       return getVScale(DL, VT, Operand.getConstantOperandAPInt(0));
5041     break;
5042   case ISD::ANY_EXTEND_VECTOR_INREG:
5043   case ISD::ZERO_EXTEND_VECTOR_INREG:
5044   case ISD::SIGN_EXTEND_VECTOR_INREG:
5045     assert(VT.isVector() && "This DAG node is restricted to vector types.");
5046     assert(Operand.getValueType().bitsLE(VT) &&
5047            "The input must be the same size or smaller than the result.");
5048     assert(VT.getVectorMinNumElements() <
5049                Operand.getValueType().getVectorMinNumElements() &&
5050            "The destination vector type must have fewer lanes than the input.");
5051     break;
5052   case ISD::ABS:
5053     assert(VT.isInteger() && VT == Operand.getValueType() &&
5054            "Invalid ABS!");
5055     if (OpOpcode == ISD::UNDEF)
5056       return getUNDEF(VT);
5057     break;
5058   case ISD::BSWAP:
5059     assert(VT.isInteger() && VT == Operand.getValueType() &&
5060            "Invalid BSWAP!");
5061     assert((VT.getScalarSizeInBits() % 16 == 0) &&
5062            "BSWAP types must be a multiple of 16 bits!");
5063     if (OpOpcode == ISD::UNDEF)
5064       return getUNDEF(VT);
5065     break;
5066   case ISD::BITREVERSE:
5067     assert(VT.isInteger() && VT == Operand.getValueType() &&
5068            "Invalid BITREVERSE!");
5069     if (OpOpcode == ISD::UNDEF)
5070       return getUNDEF(VT);
5071     break;
5072   case ISD::BITCAST:
5073     // Basic sanity checking.
5074     assert(VT.getSizeInBits() == Operand.getValueSizeInBits() &&
5075            "Cannot BITCAST between types of different sizes!");
5076     if (VT == Operand.getValueType()) return Operand;  // noop conversion.
5077     if (OpOpcode == ISD::BITCAST)  // bitconv(bitconv(x)) -> bitconv(x)
5078       return getNode(ISD::BITCAST, DL, VT, Operand.getOperand(0));
5079     if (OpOpcode == ISD::UNDEF)
5080       return getUNDEF(VT);
5081     break;
5082   case ISD::SCALAR_TO_VECTOR:
5083     assert(VT.isVector() && !Operand.getValueType().isVector() &&
5084            (VT.getVectorElementType() == Operand.getValueType() ||
5085             (VT.getVectorElementType().isInteger() &&
5086              Operand.getValueType().isInteger() &&
5087              VT.getVectorElementType().bitsLE(Operand.getValueType()))) &&
5088            "Illegal SCALAR_TO_VECTOR node!");
5089     if (OpOpcode == ISD::UNDEF)
5090       return getUNDEF(VT);
5091     // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
5092     if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
5093         isa<ConstantSDNode>(Operand.getOperand(1)) &&
5094         Operand.getConstantOperandVal(1) == 0 &&
5095         Operand.getOperand(0).getValueType() == VT)
5096       return Operand.getOperand(0);
5097     break;
5098   case ISD::FNEG:
5099     // Negation of an unknown bag of bits is still completely undefined.
5100     if (OpOpcode == ISD::UNDEF)
5101       return getUNDEF(VT);
5102 
5103     if (OpOpcode == ISD::FNEG)  // --X -> X
5104       return Operand.getOperand(0);
5105     break;
5106   case ISD::FABS:
5107     if (OpOpcode == ISD::FNEG)  // abs(-X) -> abs(X)
5108       return getNode(ISD::FABS, DL, VT, Operand.getOperand(0));
5109     break;
5110   case ISD::VSCALE:
5111     assert(VT == Operand.getValueType() && "Unexpected VT!");
5112     break;
5113   case ISD::CTPOP:
5114     if (Operand.getValueType().getScalarType() == MVT::i1)
5115       return Operand;
5116     break;
5117   case ISD::CTLZ:
5118   case ISD::CTTZ:
5119     if (Operand.getValueType().getScalarType() == MVT::i1)
5120       return getNOT(DL, Operand, Operand.getValueType());
5121     break;
5122   case ISD::VECREDUCE_SMIN:
5123   case ISD::VECREDUCE_UMAX:
5124     if (Operand.getValueType().getScalarType() == MVT::i1)
5125       return getNode(ISD::VECREDUCE_OR, DL, VT, Operand);
5126     break;
5127   case ISD::VECREDUCE_SMAX:
5128   case ISD::VECREDUCE_UMIN:
5129     if (Operand.getValueType().getScalarType() == MVT::i1)
5130       return getNode(ISD::VECREDUCE_AND, DL, VT, Operand);
5131     break;
5132   }
5133 
5134   SDNode *N;
5135   SDVTList VTs = getVTList(VT);
5136   SDValue Ops[] = {Operand};
5137   if (VT != MVT::Glue) { // Don't CSE flag producing nodes
5138     FoldingSetNodeID ID;
5139     AddNodeIDNode(ID, Opcode, VTs, Ops);
5140     void *IP = nullptr;
5141     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
5142       E->intersectFlagsWith(Flags);
5143       return SDValue(E, 0);
5144     }
5145 
5146     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5147     N->setFlags(Flags);
5148     createOperands(N, Ops);
5149     CSEMap.InsertNode(N, IP);
5150   } else {
5151     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5152     createOperands(N, Ops);
5153   }
5154 
5155   InsertNode(N);
5156   SDValue V = SDValue(N, 0);
5157   NewSDValueDbgMsg(V, "Creating new node: ", this);
5158   return V;
5159 }
5160 
5161 static llvm::Optional<APInt> FoldValue(unsigned Opcode, const APInt &C1,
5162                                        const APInt &C2) {
5163   switch (Opcode) {
5164   case ISD::ADD:  return C1 + C2;
5165   case ISD::SUB:  return C1 - C2;
5166   case ISD::MUL:  return C1 * C2;
5167   case ISD::AND:  return C1 & C2;
5168   case ISD::OR:   return C1 | C2;
5169   case ISD::XOR:  return C1 ^ C2;
5170   case ISD::SHL:  return C1 << C2;
5171   case ISD::SRL:  return C1.lshr(C2);
5172   case ISD::SRA:  return C1.ashr(C2);
5173   case ISD::ROTL: return C1.rotl(C2);
5174   case ISD::ROTR: return C1.rotr(C2);
5175   case ISD::SMIN: return C1.sle(C2) ? C1 : C2;
5176   case ISD::SMAX: return C1.sge(C2) ? C1 : C2;
5177   case ISD::UMIN: return C1.ule(C2) ? C1 : C2;
5178   case ISD::UMAX: return C1.uge(C2) ? C1 : C2;
5179   case ISD::SADDSAT: return C1.sadd_sat(C2);
5180   case ISD::UADDSAT: return C1.uadd_sat(C2);
5181   case ISD::SSUBSAT: return C1.ssub_sat(C2);
5182   case ISD::USUBSAT: return C1.usub_sat(C2);
5183   case ISD::UDIV:
5184     if (!C2.getBoolValue())
5185       break;
5186     return C1.udiv(C2);
5187   case ISD::UREM:
5188     if (!C2.getBoolValue())
5189       break;
5190     return C1.urem(C2);
5191   case ISD::SDIV:
5192     if (!C2.getBoolValue())
5193       break;
5194     return C1.sdiv(C2);
5195   case ISD::SREM:
5196     if (!C2.getBoolValue())
5197       break;
5198     return C1.srem(C2);
5199   case ISD::MULHS: {
5200     unsigned FullWidth = C1.getBitWidth() * 2;
5201     APInt C1Ext = C1.sext(FullWidth);
5202     APInt C2Ext = C2.sext(FullWidth);
5203     return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth());
5204   }
5205   case ISD::MULHU: {
5206     unsigned FullWidth = C1.getBitWidth() * 2;
5207     APInt C1Ext = C1.zext(FullWidth);
5208     APInt C2Ext = C2.zext(FullWidth);
5209     return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth());
5210   }
5211   }
5212   return llvm::None;
5213 }
5214 
5215 SDValue SelectionDAG::FoldSymbolOffset(unsigned Opcode, EVT VT,
5216                                        const GlobalAddressSDNode *GA,
5217                                        const SDNode *N2) {
5218   if (GA->getOpcode() != ISD::GlobalAddress)
5219     return SDValue();
5220   if (!TLI->isOffsetFoldingLegal(GA))
5221     return SDValue();
5222   auto *C2 = dyn_cast<ConstantSDNode>(N2);
5223   if (!C2)
5224     return SDValue();
5225   int64_t Offset = C2->getSExtValue();
5226   switch (Opcode) {
5227   case ISD::ADD: break;
5228   case ISD::SUB: Offset = -uint64_t(Offset); break;
5229   default: return SDValue();
5230   }
5231   return getGlobalAddress(GA->getGlobal(), SDLoc(C2), VT,
5232                           GA->getOffset() + uint64_t(Offset));
5233 }
5234 
5235 bool SelectionDAG::isUndef(unsigned Opcode, ArrayRef<SDValue> Ops) {
5236   switch (Opcode) {
5237   case ISD::SDIV:
5238   case ISD::UDIV:
5239   case ISD::SREM:
5240   case ISD::UREM: {
5241     // If a divisor is zero/undef or any element of a divisor vector is
5242     // zero/undef, the whole op is undef.
5243     assert(Ops.size() == 2 && "Div/rem should have 2 operands");
5244     SDValue Divisor = Ops[1];
5245     if (Divisor.isUndef() || isNullConstant(Divisor))
5246       return true;
5247 
5248     return ISD::isBuildVectorOfConstantSDNodes(Divisor.getNode()) &&
5249            llvm::any_of(Divisor->op_values(),
5250                         [](SDValue V) { return V.isUndef() ||
5251                                         isNullConstant(V); });
5252     // TODO: Handle signed overflow.
5253   }
5254   // TODO: Handle oversized shifts.
5255   default:
5256     return false;
5257   }
5258 }
5259 
5260 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL,
5261                                              EVT VT, ArrayRef<SDValue> Ops) {
5262   // If the opcode is a target-specific ISD node, there's nothing we can
5263   // do here and the operand rules may not line up with the below, so
5264   // bail early.
5265   // We can't create a scalar CONCAT_VECTORS so skip it. It will break
5266   // for concats involving SPLAT_VECTOR. Concats of BUILD_VECTORS are handled by
5267   // foldCONCAT_VECTORS in getNode before this is called.
5268   if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::CONCAT_VECTORS)
5269     return SDValue();
5270 
5271   unsigned NumOps = Ops.size();
5272   if (NumOps == 0)
5273     return SDValue();
5274 
5275   if (isUndef(Opcode, Ops))
5276     return getUNDEF(VT);
5277 
5278   // Handle the case of two scalars.
5279   if (NumOps == 2) {
5280     // TODO: Move foldConstantFPMath here?
5281 
5282     if (auto *C1 = dyn_cast<ConstantSDNode>(Ops[0])) {
5283       if (auto *C2 = dyn_cast<ConstantSDNode>(Ops[1])) {
5284         if (C1->isOpaque() || C2->isOpaque())
5285           return SDValue();
5286 
5287         Optional<APInt> FoldAttempt =
5288             FoldValue(Opcode, C1->getAPIntValue(), C2->getAPIntValue());
5289         if (!FoldAttempt)
5290           return SDValue();
5291 
5292         SDValue Folded = getConstant(FoldAttempt.getValue(), DL, VT);
5293         assert((!Folded || !VT.isVector()) &&
5294                "Can't fold vectors ops with scalar operands");
5295         return Folded;
5296       }
5297     }
5298 
5299     // fold (add Sym, c) -> Sym+c
5300     if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ops[0]))
5301       return FoldSymbolOffset(Opcode, VT, GA, Ops[1].getNode());
5302     if (TLI->isCommutativeBinOp(Opcode))
5303       if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ops[1]))
5304         return FoldSymbolOffset(Opcode, VT, GA, Ops[0].getNode());
5305   }
5306 
5307   // This is for vector folding only from here on.
5308   if (!VT.isVector())
5309     return SDValue();
5310 
5311   ElementCount NumElts = VT.getVectorElementCount();
5312 
5313   // See if we can fold through bitcasted integer ops.
5314   // TODO: Can we handle undef elements?
5315   if (NumOps == 2 && VT.isFixedLengthVector() && VT.isInteger() &&
5316       Ops[0].getValueType() == VT && Ops[1].getValueType() == VT &&
5317       Ops[0].getOpcode() == ISD::BITCAST &&
5318       Ops[1].getOpcode() == ISD::BITCAST) {
5319     SDValue N1 = peekThroughBitcasts(Ops[0]);
5320     SDValue N2 = peekThroughBitcasts(Ops[1]);
5321     auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
5322     auto *BV2 = dyn_cast<BuildVectorSDNode>(N2);
5323     EVT BVVT = N1.getValueType();
5324     if (BV1 && BV2 && BVVT.isInteger() && BVVT == N2.getValueType()) {
5325       bool IsLE = getDataLayout().isLittleEndian();
5326       unsigned EltBits = VT.getScalarSizeInBits();
5327       SmallVector<APInt> RawBits1, RawBits2;
5328       BitVector UndefElts1, UndefElts2;
5329       if (BV1->getConstantRawBits(IsLE, EltBits, RawBits1, UndefElts1) &&
5330           BV2->getConstantRawBits(IsLE, EltBits, RawBits2, UndefElts2) &&
5331           UndefElts1.none() && UndefElts2.none()) {
5332         SmallVector<APInt> RawBits;
5333         for (unsigned I = 0, E = NumElts.getFixedValue(); I != E; ++I) {
5334           Optional<APInt> Fold = FoldValue(Opcode, RawBits1[I], RawBits2[I]);
5335           if (!Fold)
5336             break;
5337           RawBits.push_back(Fold.getValue());
5338         }
5339         if (RawBits.size() == NumElts.getFixedValue()) {
5340           // We have constant folded, but we need to cast this again back to
5341           // the original (possibly legalized) type.
5342           SmallVector<APInt> DstBits;
5343           BitVector DstUndefs;
5344           BuildVectorSDNode::recastRawBits(IsLE, BVVT.getScalarSizeInBits(),
5345                                            DstBits, RawBits, DstUndefs,
5346                                            BitVector(RawBits.size(), false));
5347           EVT BVEltVT = BV1->getOperand(0).getValueType();
5348           unsigned BVEltBits = BVEltVT.getSizeInBits();
5349           SmallVector<SDValue> Ops(DstBits.size(), getUNDEF(BVEltVT));
5350           for (unsigned I = 0, E = DstBits.size(); I != E; ++I) {
5351             if (DstUndefs[I])
5352               continue;
5353             Ops[I] = getConstant(DstBits[I].sextOrSelf(BVEltBits), DL, BVEltVT);
5354           }
5355           return getBitcast(VT, getBuildVector(BVVT, DL, Ops));
5356         }
5357       }
5358     }
5359   }
5360 
5361   auto IsScalarOrSameVectorSize = [NumElts](const SDValue &Op) {
5362     return !Op.getValueType().isVector() ||
5363            Op.getValueType().getVectorElementCount() == NumElts;
5364   };
5365 
5366   auto IsBuildVectorSplatVectorOrUndef = [](const SDValue &Op) {
5367     return Op.isUndef() || Op.getOpcode() == ISD::CONDCODE ||
5368            Op.getOpcode() == ISD::BUILD_VECTOR ||
5369            Op.getOpcode() == ISD::SPLAT_VECTOR;
5370   };
5371 
5372   // All operands must be vector types with the same number of elements as
5373   // the result type and must be either UNDEF or a build/splat vector
5374   // or UNDEF scalars.
5375   if (!llvm::all_of(Ops, IsBuildVectorSplatVectorOrUndef) ||
5376       !llvm::all_of(Ops, IsScalarOrSameVectorSize))
5377     return SDValue();
5378 
5379   // If we are comparing vectors, then the result needs to be a i1 boolean
5380   // that is then sign-extended back to the legal result type.
5381   EVT SVT = (Opcode == ISD::SETCC ? MVT::i1 : VT.getScalarType());
5382 
5383   // Find legal integer scalar type for constant promotion and
5384   // ensure that its scalar size is at least as large as source.
5385   EVT LegalSVT = VT.getScalarType();
5386   if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
5387     LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
5388     if (LegalSVT.bitsLT(VT.getScalarType()))
5389       return SDValue();
5390   }
5391 
5392   // For scalable vector types we know we're dealing with SPLAT_VECTORs. We
5393   // only have one operand to check. For fixed-length vector types we may have
5394   // a combination of BUILD_VECTOR and SPLAT_VECTOR.
5395   unsigned NumVectorElts = NumElts.isScalable() ? 1 : NumElts.getFixedValue();
5396 
5397   // Constant fold each scalar lane separately.
5398   SmallVector<SDValue, 4> ScalarResults;
5399   for (unsigned I = 0; I != NumVectorElts; I++) {
5400     SmallVector<SDValue, 4> ScalarOps;
5401     for (SDValue Op : Ops) {
5402       EVT InSVT = Op.getValueType().getScalarType();
5403       if (Op.getOpcode() != ISD::BUILD_VECTOR &&
5404           Op.getOpcode() != ISD::SPLAT_VECTOR) {
5405         if (Op.isUndef())
5406           ScalarOps.push_back(getUNDEF(InSVT));
5407         else
5408           ScalarOps.push_back(Op);
5409         continue;
5410       }
5411 
5412       SDValue ScalarOp =
5413           Op.getOperand(Op.getOpcode() == ISD::SPLAT_VECTOR ? 0 : I);
5414       EVT ScalarVT = ScalarOp.getValueType();
5415 
5416       // Build vector (integer) scalar operands may need implicit
5417       // truncation - do this before constant folding.
5418       if (ScalarVT.isInteger() && ScalarVT.bitsGT(InSVT))
5419         ScalarOp = getNode(ISD::TRUNCATE, DL, InSVT, ScalarOp);
5420 
5421       ScalarOps.push_back(ScalarOp);
5422     }
5423 
5424     // Constant fold the scalar operands.
5425     SDValue ScalarResult = getNode(Opcode, DL, SVT, ScalarOps);
5426 
5427     // Legalize the (integer) scalar constant if necessary.
5428     if (LegalSVT != SVT)
5429       ScalarResult = getNode(ISD::SIGN_EXTEND, DL, LegalSVT, ScalarResult);
5430 
5431     // Scalar folding only succeeded if the result is a constant or UNDEF.
5432     if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant &&
5433         ScalarResult.getOpcode() != ISD::ConstantFP)
5434       return SDValue();
5435     ScalarResults.push_back(ScalarResult);
5436   }
5437 
5438   SDValue V = NumElts.isScalable() ? getSplatVector(VT, DL, ScalarResults[0])
5439                                    : getBuildVector(VT, DL, ScalarResults);
5440   NewSDValueDbgMsg(V, "New node fold constant vector: ", this);
5441   return V;
5442 }
5443 
5444 SDValue SelectionDAG::foldConstantFPMath(unsigned Opcode, const SDLoc &DL,
5445                                          EVT VT, SDValue N1, SDValue N2) {
5446   // TODO: We don't do any constant folding for strict FP opcodes here, but we
5447   //       should. That will require dealing with a potentially non-default
5448   //       rounding mode, checking the "opStatus" return value from the APFloat
5449   //       math calculations, and possibly other variations.
5450   auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1.getNode());
5451   auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2.getNode());
5452   if (N1CFP && N2CFP) {
5453     APFloat C1 = N1CFP->getValueAPF(), C2 = N2CFP->getValueAPF();
5454     switch (Opcode) {
5455     case ISD::FADD:
5456       C1.add(C2, APFloat::rmNearestTiesToEven);
5457       return getConstantFP(C1, DL, VT);
5458     case ISD::FSUB:
5459       C1.subtract(C2, APFloat::rmNearestTiesToEven);
5460       return getConstantFP(C1, DL, VT);
5461     case ISD::FMUL:
5462       C1.multiply(C2, APFloat::rmNearestTiesToEven);
5463       return getConstantFP(C1, DL, VT);
5464     case ISD::FDIV:
5465       C1.divide(C2, APFloat::rmNearestTiesToEven);
5466       return getConstantFP(C1, DL, VT);
5467     case ISD::FREM:
5468       C1.mod(C2);
5469       return getConstantFP(C1, DL, VT);
5470     case ISD::FCOPYSIGN:
5471       C1.copySign(C2);
5472       return getConstantFP(C1, DL, VT);
5473     default: break;
5474     }
5475   }
5476   if (N1CFP && Opcode == ISD::FP_ROUND) {
5477     APFloat C1 = N1CFP->getValueAPF();    // make copy
5478     bool Unused;
5479     // This can return overflow, underflow, or inexact; we don't care.
5480     // FIXME need to be more flexible about rounding mode.
5481     (void) C1.convert(EVTToAPFloatSemantics(VT), APFloat::rmNearestTiesToEven,
5482                       &Unused);
5483     return getConstantFP(C1, DL, VT);
5484   }
5485 
5486   switch (Opcode) {
5487   case ISD::FSUB:
5488     // -0.0 - undef --> undef (consistent with "fneg undef")
5489     if (N1CFP && N1CFP->getValueAPF().isNegZero() && N2.isUndef())
5490       return getUNDEF(VT);
5491     LLVM_FALLTHROUGH;
5492 
5493   case ISD::FADD:
5494   case ISD::FMUL:
5495   case ISD::FDIV:
5496   case ISD::FREM:
5497     // If both operands are undef, the result is undef. If 1 operand is undef,
5498     // the result is NaN. This should match the behavior of the IR optimizer.
5499     if (N1.isUndef() && N2.isUndef())
5500       return getUNDEF(VT);
5501     if (N1.isUndef() || N2.isUndef())
5502       return getConstantFP(APFloat::getNaN(EVTToAPFloatSemantics(VT)), DL, VT);
5503   }
5504   return SDValue();
5505 }
5506 
5507 SDValue SelectionDAG::getAssertAlign(const SDLoc &DL, SDValue Val, Align A) {
5508   assert(Val.getValueType().isInteger() && "Invalid AssertAlign!");
5509 
5510   // There's no need to assert on a byte-aligned pointer. All pointers are at
5511   // least byte aligned.
5512   if (A == Align(1))
5513     return Val;
5514 
5515   FoldingSetNodeID ID;
5516   AddNodeIDNode(ID, ISD::AssertAlign, getVTList(Val.getValueType()), {Val});
5517   ID.AddInteger(A.value());
5518 
5519   void *IP = nullptr;
5520   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
5521     return SDValue(E, 0);
5522 
5523   auto *N = newSDNode<AssertAlignSDNode>(DL.getIROrder(), DL.getDebugLoc(),
5524                                          Val.getValueType(), A);
5525   createOperands(N, {Val});
5526 
5527   CSEMap.InsertNode(N, IP);
5528   InsertNode(N);
5529 
5530   SDValue V(N, 0);
5531   NewSDValueDbgMsg(V, "Creating new node: ", this);
5532   return V;
5533 }
5534 
5535 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5536                               SDValue N1, SDValue N2) {
5537   SDNodeFlags Flags;
5538   if (Inserter)
5539     Flags = Inserter->getFlags();
5540   return getNode(Opcode, DL, VT, N1, N2, Flags);
5541 }
5542 
5543 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5544                               SDValue N1, SDValue N2, const SDNodeFlags Flags) {
5545   assert(N1.getOpcode() != ISD::DELETED_NODE &&
5546          N2.getOpcode() != ISD::DELETED_NODE &&
5547          "Operand is DELETED_NODE!");
5548   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
5549   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
5550   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5551   ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
5552 
5553   // Canonicalize constant to RHS if commutative.
5554   if (TLI->isCommutativeBinOp(Opcode)) {
5555     if (N1C && !N2C) {
5556       std::swap(N1C, N2C);
5557       std::swap(N1, N2);
5558     } else if (N1CFP && !N2CFP) {
5559       std::swap(N1CFP, N2CFP);
5560       std::swap(N1, N2);
5561     }
5562   }
5563 
5564   switch (Opcode) {
5565   default: break;
5566   case ISD::TokenFactor:
5567     assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
5568            N2.getValueType() == MVT::Other && "Invalid token factor!");
5569     // Fold trivial token factors.
5570     if (N1.getOpcode() == ISD::EntryToken) return N2;
5571     if (N2.getOpcode() == ISD::EntryToken) return N1;
5572     if (N1 == N2) return N1;
5573     break;
5574   case ISD::BUILD_VECTOR: {
5575     // Attempt to simplify BUILD_VECTOR.
5576     SDValue Ops[] = {N1, N2};
5577     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
5578       return V;
5579     break;
5580   }
5581   case ISD::CONCAT_VECTORS: {
5582     SDValue Ops[] = {N1, N2};
5583     if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
5584       return V;
5585     break;
5586   }
5587   case ISD::AND:
5588     assert(VT.isInteger() && "This operator does not apply to FP types!");
5589     assert(N1.getValueType() == N2.getValueType() &&
5590            N1.getValueType() == VT && "Binary operator types must match!");
5591     // (X & 0) -> 0.  This commonly occurs when legalizing i64 values, so it's
5592     // worth handling here.
5593     if (N2C && N2C->isZero())
5594       return N2;
5595     if (N2C && N2C->isAllOnes()) // X & -1 -> X
5596       return N1;
5597     break;
5598   case ISD::OR:
5599   case ISD::XOR:
5600   case ISD::ADD:
5601   case ISD::SUB:
5602     assert(VT.isInteger() && "This operator does not apply to FP types!");
5603     assert(N1.getValueType() == N2.getValueType() &&
5604            N1.getValueType() == VT && "Binary operator types must match!");
5605     // (X ^|+- 0) -> X.  This commonly occurs when legalizing i64 values, so
5606     // it's worth handling here.
5607     if (N2C && N2C->isZero())
5608       return N1;
5609     if ((Opcode == ISD::ADD || Opcode == ISD::SUB) && VT.isVector() &&
5610         VT.getVectorElementType() == MVT::i1)
5611       return getNode(ISD::XOR, DL, VT, N1, N2);
5612     break;
5613   case ISD::MUL:
5614     assert(VT.isInteger() && "This operator does not apply to FP types!");
5615     assert(N1.getValueType() == N2.getValueType() &&
5616            N1.getValueType() == VT && "Binary operator types must match!");
5617     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
5618       return getNode(ISD::AND, DL, VT, N1, N2);
5619     if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
5620       const APInt &MulImm = N1->getConstantOperandAPInt(0);
5621       const APInt &N2CImm = N2C->getAPIntValue();
5622       return getVScale(DL, VT, MulImm * N2CImm);
5623     }
5624     break;
5625   case ISD::UDIV:
5626   case ISD::UREM:
5627   case ISD::MULHU:
5628   case ISD::MULHS:
5629   case ISD::SDIV:
5630   case ISD::SREM:
5631   case ISD::SADDSAT:
5632   case ISD::SSUBSAT:
5633   case ISD::UADDSAT:
5634   case ISD::USUBSAT:
5635     assert(VT.isInteger() && "This operator does not apply to FP types!");
5636     assert(N1.getValueType() == N2.getValueType() &&
5637            N1.getValueType() == VT && "Binary operator types must match!");
5638     if (VT.isVector() && VT.getVectorElementType() == MVT::i1) {
5639       // fold (add_sat x, y) -> (or x, y) for bool types.
5640       if (Opcode == ISD::SADDSAT || Opcode == ISD::UADDSAT)
5641         return getNode(ISD::OR, DL, VT, N1, N2);
5642       // fold (sub_sat x, y) -> (and x, ~y) for bool types.
5643       if (Opcode == ISD::SSUBSAT || Opcode == ISD::USUBSAT)
5644         return getNode(ISD::AND, DL, VT, N1, getNOT(DL, N2, VT));
5645     }
5646     break;
5647   case ISD::SMIN:
5648   case ISD::UMAX:
5649     assert(VT.isInteger() && "This operator does not apply to FP types!");
5650     assert(N1.getValueType() == N2.getValueType() &&
5651            N1.getValueType() == VT && "Binary operator types must match!");
5652     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
5653       return getNode(ISD::OR, DL, VT, N1, N2);
5654     break;
5655   case ISD::SMAX:
5656   case ISD::UMIN:
5657     assert(VT.isInteger() && "This operator does not apply to FP types!");
5658     assert(N1.getValueType() == N2.getValueType() &&
5659            N1.getValueType() == VT && "Binary operator types must match!");
5660     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
5661       return getNode(ISD::AND, DL, VT, N1, N2);
5662     break;
5663   case ISD::FADD:
5664   case ISD::FSUB:
5665   case ISD::FMUL:
5666   case ISD::FDIV:
5667   case ISD::FREM:
5668     assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
5669     assert(N1.getValueType() == N2.getValueType() &&
5670            N1.getValueType() == VT && "Binary operator types must match!");
5671     if (SDValue V = simplifyFPBinop(Opcode, N1, N2, Flags))
5672       return V;
5673     break;
5674   case ISD::FCOPYSIGN:   // N1 and result must match.  N1/N2 need not match.
5675     assert(N1.getValueType() == VT &&
5676            N1.getValueType().isFloatingPoint() &&
5677            N2.getValueType().isFloatingPoint() &&
5678            "Invalid FCOPYSIGN!");
5679     break;
5680   case ISD::SHL:
5681     if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
5682       const APInt &MulImm = N1->getConstantOperandAPInt(0);
5683       const APInt &ShiftImm = N2C->getAPIntValue();
5684       return getVScale(DL, VT, MulImm << ShiftImm);
5685     }
5686     LLVM_FALLTHROUGH;
5687   case ISD::SRA:
5688   case ISD::SRL:
5689     if (SDValue V = simplifyShift(N1, N2))
5690       return V;
5691     LLVM_FALLTHROUGH;
5692   case ISD::ROTL:
5693   case ISD::ROTR:
5694     assert(VT == N1.getValueType() &&
5695            "Shift operators return type must be the same as their first arg");
5696     assert(VT.isInteger() && N2.getValueType().isInteger() &&
5697            "Shifts only work on integers");
5698     assert((!VT.isVector() || VT == N2.getValueType()) &&
5699            "Vector shift amounts must be in the same as their first arg");
5700     // Verify that the shift amount VT is big enough to hold valid shift
5701     // amounts.  This catches things like trying to shift an i1024 value by an
5702     // i8, which is easy to fall into in generic code that uses
5703     // TLI.getShiftAmount().
5704     assert(N2.getValueType().getScalarSizeInBits() >=
5705                Log2_32_Ceil(VT.getScalarSizeInBits()) &&
5706            "Invalid use of small shift amount with oversized value!");
5707 
5708     // Always fold shifts of i1 values so the code generator doesn't need to
5709     // handle them.  Since we know the size of the shift has to be less than the
5710     // size of the value, the shift/rotate count is guaranteed to be zero.
5711     if (VT == MVT::i1)
5712       return N1;
5713     if (N2C && N2C->isZero())
5714       return N1;
5715     break;
5716   case ISD::FP_ROUND:
5717     assert(VT.isFloatingPoint() &&
5718            N1.getValueType().isFloatingPoint() &&
5719            VT.bitsLE(N1.getValueType()) &&
5720            N2C && (N2C->getZExtValue() == 0 || N2C->getZExtValue() == 1) &&
5721            "Invalid FP_ROUND!");
5722     if (N1.getValueType() == VT) return N1;  // noop conversion.
5723     break;
5724   case ISD::AssertSext:
5725   case ISD::AssertZext: {
5726     EVT EVT = cast<VTSDNode>(N2)->getVT();
5727     assert(VT == N1.getValueType() && "Not an inreg extend!");
5728     assert(VT.isInteger() && EVT.isInteger() &&
5729            "Cannot *_EXTEND_INREG FP types");
5730     assert(!EVT.isVector() &&
5731            "AssertSExt/AssertZExt type should be the vector element type "
5732            "rather than the vector type!");
5733     assert(EVT.bitsLE(VT.getScalarType()) && "Not extending!");
5734     if (VT.getScalarType() == EVT) return N1; // noop assertion.
5735     break;
5736   }
5737   case ISD::SIGN_EXTEND_INREG: {
5738     EVT EVT = cast<VTSDNode>(N2)->getVT();
5739     assert(VT == N1.getValueType() && "Not an inreg extend!");
5740     assert(VT.isInteger() && EVT.isInteger() &&
5741            "Cannot *_EXTEND_INREG FP types");
5742     assert(EVT.isVector() == VT.isVector() &&
5743            "SIGN_EXTEND_INREG type should be vector iff the operand "
5744            "type is vector!");
5745     assert((!EVT.isVector() ||
5746             EVT.getVectorElementCount() == VT.getVectorElementCount()) &&
5747            "Vector element counts must match in SIGN_EXTEND_INREG");
5748     assert(EVT.bitsLE(VT) && "Not extending!");
5749     if (EVT == VT) return N1;  // Not actually extending
5750 
5751     auto SignExtendInReg = [&](APInt Val, llvm::EVT ConstantVT) {
5752       unsigned FromBits = EVT.getScalarSizeInBits();
5753       Val <<= Val.getBitWidth() - FromBits;
5754       Val.ashrInPlace(Val.getBitWidth() - FromBits);
5755       return getConstant(Val, DL, ConstantVT);
5756     };
5757 
5758     if (N1C) {
5759       const APInt &Val = N1C->getAPIntValue();
5760       return SignExtendInReg(Val, VT);
5761     }
5762 
5763     if (ISD::isBuildVectorOfConstantSDNodes(N1.getNode())) {
5764       SmallVector<SDValue, 8> Ops;
5765       llvm::EVT OpVT = N1.getOperand(0).getValueType();
5766       for (int i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
5767         SDValue Op = N1.getOperand(i);
5768         if (Op.isUndef()) {
5769           Ops.push_back(getUNDEF(OpVT));
5770           continue;
5771         }
5772         ConstantSDNode *C = cast<ConstantSDNode>(Op);
5773         APInt Val = C->getAPIntValue();
5774         Ops.push_back(SignExtendInReg(Val, OpVT));
5775       }
5776       return getBuildVector(VT, DL, Ops);
5777     }
5778     break;
5779   }
5780   case ISD::FP_TO_SINT_SAT:
5781   case ISD::FP_TO_UINT_SAT: {
5782     assert(VT.isInteger() && cast<VTSDNode>(N2)->getVT().isInteger() &&
5783            N1.getValueType().isFloatingPoint() && "Invalid FP_TO_*INT_SAT");
5784     assert(N1.getValueType().isVector() == VT.isVector() &&
5785            "FP_TO_*INT_SAT type should be vector iff the operand type is "
5786            "vector!");
5787     assert((!VT.isVector() || VT.getVectorNumElements() ==
5788                                   N1.getValueType().getVectorNumElements()) &&
5789            "Vector element counts must match in FP_TO_*INT_SAT");
5790     assert(!cast<VTSDNode>(N2)->getVT().isVector() &&
5791            "Type to saturate to must be a scalar.");
5792     assert(cast<VTSDNode>(N2)->getVT().bitsLE(VT.getScalarType()) &&
5793            "Not extending!");
5794     break;
5795   }
5796   case ISD::EXTRACT_VECTOR_ELT:
5797     assert(VT.getSizeInBits() >= N1.getValueType().getScalarSizeInBits() &&
5798            "The result of EXTRACT_VECTOR_ELT must be at least as wide as the \
5799              element type of the vector.");
5800 
5801     // Extract from an undefined value or using an undefined index is undefined.
5802     if (N1.isUndef() || N2.isUndef())
5803       return getUNDEF(VT);
5804 
5805     // EXTRACT_VECTOR_ELT of out-of-bounds element is an UNDEF for fixed length
5806     // vectors. For scalable vectors we will provide appropriate support for
5807     // dealing with arbitrary indices.
5808     if (N2C && N1.getValueType().isFixedLengthVector() &&
5809         N2C->getAPIntValue().uge(N1.getValueType().getVectorNumElements()))
5810       return getUNDEF(VT);
5811 
5812     // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
5813     // expanding copies of large vectors from registers. This only works for
5814     // fixed length vectors, since we need to know the exact number of
5815     // elements.
5816     if (N2C && N1.getOperand(0).getValueType().isFixedLengthVector() &&
5817         N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0) {
5818       unsigned Factor =
5819         N1.getOperand(0).getValueType().getVectorNumElements();
5820       return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
5821                      N1.getOperand(N2C->getZExtValue() / Factor),
5822                      getVectorIdxConstant(N2C->getZExtValue() % Factor, DL));
5823     }
5824 
5825     // EXTRACT_VECTOR_ELT of BUILD_VECTOR or SPLAT_VECTOR is often formed while
5826     // lowering is expanding large vector constants.
5827     if (N2C && (N1.getOpcode() == ISD::BUILD_VECTOR ||
5828                 N1.getOpcode() == ISD::SPLAT_VECTOR)) {
5829       assert((N1.getOpcode() != ISD::BUILD_VECTOR ||
5830               N1.getValueType().isFixedLengthVector()) &&
5831              "BUILD_VECTOR used for scalable vectors");
5832       unsigned Index =
5833           N1.getOpcode() == ISD::BUILD_VECTOR ? N2C->getZExtValue() : 0;
5834       SDValue Elt = N1.getOperand(Index);
5835 
5836       if (VT != Elt.getValueType())
5837         // If the vector element type is not legal, the BUILD_VECTOR operands
5838         // are promoted and implicitly truncated, and the result implicitly
5839         // extended. Make that explicit here.
5840         Elt = getAnyExtOrTrunc(Elt, DL, VT);
5841 
5842       return Elt;
5843     }
5844 
5845     // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
5846     // operations are lowered to scalars.
5847     if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) {
5848       // If the indices are the same, return the inserted element else
5849       // if the indices are known different, extract the element from
5850       // the original vector.
5851       SDValue N1Op2 = N1.getOperand(2);
5852       ConstantSDNode *N1Op2C = dyn_cast<ConstantSDNode>(N1Op2);
5853 
5854       if (N1Op2C && N2C) {
5855         if (N1Op2C->getZExtValue() == N2C->getZExtValue()) {
5856           if (VT == N1.getOperand(1).getValueType())
5857             return N1.getOperand(1);
5858           return getSExtOrTrunc(N1.getOperand(1), DL, VT);
5859         }
5860         return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2);
5861       }
5862     }
5863 
5864     // EXTRACT_VECTOR_ELT of v1iX EXTRACT_SUBVECTOR could be formed
5865     // when vector types are scalarized and v1iX is legal.
5866     // vextract (v1iX extract_subvector(vNiX, Idx)) -> vextract(vNiX,Idx).
5867     // Here we are completely ignoring the extract element index (N2),
5868     // which is fine for fixed width vectors, since any index other than 0
5869     // is undefined anyway. However, this cannot be ignored for scalable
5870     // vectors - in theory we could support this, but we don't want to do this
5871     // without a profitability check.
5872     if (N1.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
5873         N1.getValueType().isFixedLengthVector() &&
5874         N1.getValueType().getVectorNumElements() == 1) {
5875       return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0),
5876                      N1.getOperand(1));
5877     }
5878     break;
5879   case ISD::EXTRACT_ELEMENT:
5880     assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!");
5881     assert(!N1.getValueType().isVector() && !VT.isVector() &&
5882            (N1.getValueType().isInteger() == VT.isInteger()) &&
5883            N1.getValueType() != VT &&
5884            "Wrong types for EXTRACT_ELEMENT!");
5885 
5886     // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
5887     // 64-bit integers into 32-bit parts.  Instead of building the extract of
5888     // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
5889     if (N1.getOpcode() == ISD::BUILD_PAIR)
5890       return N1.getOperand(N2C->getZExtValue());
5891 
5892     // EXTRACT_ELEMENT of a constant int is also very common.
5893     if (N1C) {
5894       unsigned ElementSize = VT.getSizeInBits();
5895       unsigned Shift = ElementSize * N2C->getZExtValue();
5896       const APInt &Val = N1C->getAPIntValue();
5897       return getConstant(Val.extractBits(ElementSize, Shift), DL, VT);
5898     }
5899     break;
5900   case ISD::EXTRACT_SUBVECTOR: {
5901     EVT N1VT = N1.getValueType();
5902     assert(VT.isVector() && N1VT.isVector() &&
5903            "Extract subvector VTs must be vectors!");
5904     assert(VT.getVectorElementType() == N1VT.getVectorElementType() &&
5905            "Extract subvector VTs must have the same element type!");
5906     assert((VT.isFixedLengthVector() || N1VT.isScalableVector()) &&
5907            "Cannot extract a scalable vector from a fixed length vector!");
5908     assert((VT.isScalableVector() != N1VT.isScalableVector() ||
5909             VT.getVectorMinNumElements() <= N1VT.getVectorMinNumElements()) &&
5910            "Extract subvector must be from larger vector to smaller vector!");
5911     assert(N2C && "Extract subvector index must be a constant");
5912     assert((VT.isScalableVector() != N1VT.isScalableVector() ||
5913             (VT.getVectorMinNumElements() + N2C->getZExtValue()) <=
5914                 N1VT.getVectorMinNumElements()) &&
5915            "Extract subvector overflow!");
5916     assert(N2C->getAPIntValue().getBitWidth() ==
5917                TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() &&
5918            "Constant index for EXTRACT_SUBVECTOR has an invalid size");
5919 
5920     // Trivial extraction.
5921     if (VT == N1VT)
5922       return N1;
5923 
5924     // EXTRACT_SUBVECTOR of an UNDEF is an UNDEF.
5925     if (N1.isUndef())
5926       return getUNDEF(VT);
5927 
5928     // EXTRACT_SUBVECTOR of CONCAT_VECTOR can be simplified if the pieces of
5929     // the concat have the same type as the extract.
5930     if (N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0 &&
5931         VT == N1.getOperand(0).getValueType()) {
5932       unsigned Factor = VT.getVectorMinNumElements();
5933       return N1.getOperand(N2C->getZExtValue() / Factor);
5934     }
5935 
5936     // EXTRACT_SUBVECTOR of INSERT_SUBVECTOR is often created
5937     // during shuffle legalization.
5938     if (N1.getOpcode() == ISD::INSERT_SUBVECTOR && N2 == N1.getOperand(2) &&
5939         VT == N1.getOperand(1).getValueType())
5940       return N1.getOperand(1);
5941     break;
5942   }
5943   }
5944 
5945   // Perform trivial constant folding.
5946   if (SDValue SV = FoldConstantArithmetic(Opcode, DL, VT, {N1, N2}))
5947     return SV;
5948 
5949   if (SDValue V = foldConstantFPMath(Opcode, DL, VT, N1, N2))
5950     return V;
5951 
5952   // Canonicalize an UNDEF to the RHS, even over a constant.
5953   if (N1.isUndef()) {
5954     if (TLI->isCommutativeBinOp(Opcode)) {
5955       std::swap(N1, N2);
5956     } else {
5957       switch (Opcode) {
5958       case ISD::SIGN_EXTEND_INREG:
5959       case ISD::SUB:
5960         return getUNDEF(VT);     // fold op(undef, arg2) -> undef
5961       case ISD::UDIV:
5962       case ISD::SDIV:
5963       case ISD::UREM:
5964       case ISD::SREM:
5965       case ISD::SSUBSAT:
5966       case ISD::USUBSAT:
5967         return getConstant(0, DL, VT);    // fold op(undef, arg2) -> 0
5968       }
5969     }
5970   }
5971 
5972   // Fold a bunch of operators when the RHS is undef.
5973   if (N2.isUndef()) {
5974     switch (Opcode) {
5975     case ISD::XOR:
5976       if (N1.isUndef())
5977         // Handle undef ^ undef -> 0 special case. This is a common
5978         // idiom (misuse).
5979         return getConstant(0, DL, VT);
5980       LLVM_FALLTHROUGH;
5981     case ISD::ADD:
5982     case ISD::SUB:
5983     case ISD::UDIV:
5984     case ISD::SDIV:
5985     case ISD::UREM:
5986     case ISD::SREM:
5987       return getUNDEF(VT);       // fold op(arg1, undef) -> undef
5988     case ISD::MUL:
5989     case ISD::AND:
5990     case ISD::SSUBSAT:
5991     case ISD::USUBSAT:
5992       return getConstant(0, DL, VT);  // fold op(arg1, undef) -> 0
5993     case ISD::OR:
5994     case ISD::SADDSAT:
5995     case ISD::UADDSAT:
5996       return getAllOnesConstant(DL, VT);
5997     }
5998   }
5999 
6000   // Memoize this node if possible.
6001   SDNode *N;
6002   SDVTList VTs = getVTList(VT);
6003   SDValue Ops[] = {N1, N2};
6004   if (VT != MVT::Glue) {
6005     FoldingSetNodeID ID;
6006     AddNodeIDNode(ID, Opcode, VTs, Ops);
6007     void *IP = nullptr;
6008     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
6009       E->intersectFlagsWith(Flags);
6010       return SDValue(E, 0);
6011     }
6012 
6013     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6014     N->setFlags(Flags);
6015     createOperands(N, Ops);
6016     CSEMap.InsertNode(N, IP);
6017   } else {
6018     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6019     createOperands(N, Ops);
6020   }
6021 
6022   InsertNode(N);
6023   SDValue V = SDValue(N, 0);
6024   NewSDValueDbgMsg(V, "Creating new node: ", this);
6025   return V;
6026 }
6027 
6028 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6029                               SDValue N1, SDValue N2, SDValue N3) {
6030   SDNodeFlags Flags;
6031   if (Inserter)
6032     Flags = Inserter->getFlags();
6033   return getNode(Opcode, DL, VT, N1, N2, N3, Flags);
6034 }
6035 
6036 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6037                               SDValue N1, SDValue N2, SDValue N3,
6038                               const SDNodeFlags Flags) {
6039   assert(N1.getOpcode() != ISD::DELETED_NODE &&
6040          N2.getOpcode() != ISD::DELETED_NODE &&
6041          N3.getOpcode() != ISD::DELETED_NODE &&
6042          "Operand is DELETED_NODE!");
6043   // Perform various simplifications.
6044   switch (Opcode) {
6045   case ISD::FMA: {
6046     assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
6047     assert(N1.getValueType() == VT && N2.getValueType() == VT &&
6048            N3.getValueType() == VT && "FMA types must match!");
6049     ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6050     ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
6051     ConstantFPSDNode *N3CFP = dyn_cast<ConstantFPSDNode>(N3);
6052     if (N1CFP && N2CFP && N3CFP) {
6053       APFloat  V1 = N1CFP->getValueAPF();
6054       const APFloat &V2 = N2CFP->getValueAPF();
6055       const APFloat &V3 = N3CFP->getValueAPF();
6056       V1.fusedMultiplyAdd(V2, V3, APFloat::rmNearestTiesToEven);
6057       return getConstantFP(V1, DL, VT);
6058     }
6059     break;
6060   }
6061   case ISD::BUILD_VECTOR: {
6062     // Attempt to simplify BUILD_VECTOR.
6063     SDValue Ops[] = {N1, N2, N3};
6064     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
6065       return V;
6066     break;
6067   }
6068   case ISD::CONCAT_VECTORS: {
6069     SDValue Ops[] = {N1, N2, N3};
6070     if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
6071       return V;
6072     break;
6073   }
6074   case ISD::SETCC: {
6075     assert(VT.isInteger() && "SETCC result type must be an integer!");
6076     assert(N1.getValueType() == N2.getValueType() &&
6077            "SETCC operands must have the same type!");
6078     assert(VT.isVector() == N1.getValueType().isVector() &&
6079            "SETCC type should be vector iff the operand type is vector!");
6080     assert((!VT.isVector() || VT.getVectorElementCount() ==
6081                                   N1.getValueType().getVectorElementCount()) &&
6082            "SETCC vector element counts must match!");
6083     // Use FoldSetCC to simplify SETCC's.
6084     if (SDValue V = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL))
6085       return V;
6086     // Vector constant folding.
6087     SDValue Ops[] = {N1, N2, N3};
6088     if (SDValue V = FoldConstantArithmetic(Opcode, DL, VT, Ops)) {
6089       NewSDValueDbgMsg(V, "New node vector constant folding: ", this);
6090       return V;
6091     }
6092     break;
6093   }
6094   case ISD::SELECT:
6095   case ISD::VSELECT:
6096     if (SDValue V = simplifySelect(N1, N2, N3))
6097       return V;
6098     break;
6099   case ISD::VECTOR_SHUFFLE:
6100     llvm_unreachable("should use getVectorShuffle constructor!");
6101   case ISD::VECTOR_SPLICE: {
6102     if (cast<ConstantSDNode>(N3)->isNullValue())
6103       return N1;
6104     break;
6105   }
6106   case ISD::INSERT_VECTOR_ELT: {
6107     ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3);
6108     // INSERT_VECTOR_ELT into out-of-bounds element is an UNDEF, except
6109     // for scalable vectors where we will generate appropriate code to
6110     // deal with out-of-bounds cases correctly.
6111     if (N3C && N1.getValueType().isFixedLengthVector() &&
6112         N3C->getZExtValue() >= N1.getValueType().getVectorNumElements())
6113       return getUNDEF(VT);
6114 
6115     // Undefined index can be assumed out-of-bounds, so that's UNDEF too.
6116     if (N3.isUndef())
6117       return getUNDEF(VT);
6118 
6119     // If the inserted element is an UNDEF, just use the input vector.
6120     if (N2.isUndef())
6121       return N1;
6122 
6123     break;
6124   }
6125   case ISD::INSERT_SUBVECTOR: {
6126     // Inserting undef into undef is still undef.
6127     if (N1.isUndef() && N2.isUndef())
6128       return getUNDEF(VT);
6129 
6130     EVT N2VT = N2.getValueType();
6131     assert(VT == N1.getValueType() &&
6132            "Dest and insert subvector source types must match!");
6133     assert(VT.isVector() && N2VT.isVector() &&
6134            "Insert subvector VTs must be vectors!");
6135     assert((VT.isScalableVector() || N2VT.isFixedLengthVector()) &&
6136            "Cannot insert a scalable vector into a fixed length vector!");
6137     assert((VT.isScalableVector() != N2VT.isScalableVector() ||
6138             VT.getVectorMinNumElements() >= N2VT.getVectorMinNumElements()) &&
6139            "Insert subvector must be from smaller vector to larger vector!");
6140     assert(isa<ConstantSDNode>(N3) &&
6141            "Insert subvector index must be constant");
6142     assert((VT.isScalableVector() != N2VT.isScalableVector() ||
6143             (N2VT.getVectorMinNumElements() +
6144              cast<ConstantSDNode>(N3)->getZExtValue()) <=
6145                 VT.getVectorMinNumElements()) &&
6146            "Insert subvector overflow!");
6147     assert(cast<ConstantSDNode>(N3)->getAPIntValue().getBitWidth() ==
6148                TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() &&
6149            "Constant index for INSERT_SUBVECTOR has an invalid size");
6150 
6151     // Trivial insertion.
6152     if (VT == N2VT)
6153       return N2;
6154 
6155     // If this is an insert of an extracted vector into an undef vector, we
6156     // can just use the input to the extract.
6157     if (N1.isUndef() && N2.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
6158         N2.getOperand(1) == N3 && N2.getOperand(0).getValueType() == VT)
6159       return N2.getOperand(0);
6160     break;
6161   }
6162   case ISD::BITCAST:
6163     // Fold bit_convert nodes from a type to themselves.
6164     if (N1.getValueType() == VT)
6165       return N1;
6166     break;
6167   }
6168 
6169   // Memoize node if it doesn't produce a flag.
6170   SDNode *N;
6171   SDVTList VTs = getVTList(VT);
6172   SDValue Ops[] = {N1, N2, N3};
6173   if (VT != MVT::Glue) {
6174     FoldingSetNodeID ID;
6175     AddNodeIDNode(ID, Opcode, VTs, Ops);
6176     void *IP = nullptr;
6177     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
6178       E->intersectFlagsWith(Flags);
6179       return SDValue(E, 0);
6180     }
6181 
6182     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6183     N->setFlags(Flags);
6184     createOperands(N, Ops);
6185     CSEMap.InsertNode(N, IP);
6186   } else {
6187     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6188     createOperands(N, Ops);
6189   }
6190 
6191   InsertNode(N);
6192   SDValue V = SDValue(N, 0);
6193   NewSDValueDbgMsg(V, "Creating new node: ", this);
6194   return V;
6195 }
6196 
6197 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6198                               SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
6199   SDValue Ops[] = { N1, N2, N3, N4 };
6200   return getNode(Opcode, DL, VT, Ops);
6201 }
6202 
6203 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6204                               SDValue N1, SDValue N2, SDValue N3, SDValue N4,
6205                               SDValue N5) {
6206   SDValue Ops[] = { N1, N2, N3, N4, N5 };
6207   return getNode(Opcode, DL, VT, Ops);
6208 }
6209 
6210 /// getStackArgumentTokenFactor - Compute a TokenFactor to force all
6211 /// the incoming stack arguments to be loaded from the stack.
6212 SDValue SelectionDAG::getStackArgumentTokenFactor(SDValue Chain) {
6213   SmallVector<SDValue, 8> ArgChains;
6214 
6215   // Include the original chain at the beginning of the list. When this is
6216   // used by target LowerCall hooks, this helps legalize find the
6217   // CALLSEQ_BEGIN node.
6218   ArgChains.push_back(Chain);
6219 
6220   // Add a chain value for each stack argument.
6221   for (SDNode *U : getEntryNode().getNode()->uses())
6222     if (LoadSDNode *L = dyn_cast<LoadSDNode>(U))
6223       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
6224         if (FI->getIndex() < 0)
6225           ArgChains.push_back(SDValue(L, 1));
6226 
6227   // Build a tokenfactor for all the chains.
6228   return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
6229 }
6230 
6231 /// getMemsetValue - Vectorized representation of the memset value
6232 /// operand.
6233 static SDValue getMemsetValue(SDValue Value, EVT VT, SelectionDAG &DAG,
6234                               const SDLoc &dl) {
6235   assert(!Value.isUndef());
6236 
6237   unsigned NumBits = VT.getScalarSizeInBits();
6238   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
6239     assert(C->getAPIntValue().getBitWidth() == 8);
6240     APInt Val = APInt::getSplat(NumBits, C->getAPIntValue());
6241     if (VT.isInteger()) {
6242       bool IsOpaque = VT.getSizeInBits() > 64 ||
6243           !DAG.getTargetLoweringInfo().isLegalStoreImmediate(C->getSExtValue());
6244       return DAG.getConstant(Val, dl, VT, false, IsOpaque);
6245     }
6246     return DAG.getConstantFP(APFloat(DAG.EVTToAPFloatSemantics(VT), Val), dl,
6247                              VT);
6248   }
6249 
6250   assert(Value.getValueType() == MVT::i8 && "memset with non-byte fill value?");
6251   EVT IntVT = VT.getScalarType();
6252   if (!IntVT.isInteger())
6253     IntVT = EVT::getIntegerVT(*DAG.getContext(), IntVT.getSizeInBits());
6254 
6255   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, Value);
6256   if (NumBits > 8) {
6257     // Use a multiplication with 0x010101... to extend the input to the
6258     // required length.
6259     APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01));
6260     Value = DAG.getNode(ISD::MUL, dl, IntVT, Value,
6261                         DAG.getConstant(Magic, dl, IntVT));
6262   }
6263 
6264   if (VT != Value.getValueType() && !VT.isInteger())
6265     Value = DAG.getBitcast(VT.getScalarType(), Value);
6266   if (VT != Value.getValueType())
6267     Value = DAG.getSplatBuildVector(VT, dl, Value);
6268 
6269   return Value;
6270 }
6271 
6272 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
6273 /// used when a memcpy is turned into a memset when the source is a constant
6274 /// string ptr.
6275 static SDValue getMemsetStringVal(EVT VT, const SDLoc &dl, SelectionDAG &DAG,
6276                                   const TargetLowering &TLI,
6277                                   const ConstantDataArraySlice &Slice) {
6278   // Handle vector with all elements zero.
6279   if (Slice.Array == nullptr) {
6280     if (VT.isInteger())
6281       return DAG.getConstant(0, dl, VT);
6282     if (VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128)
6283       return DAG.getConstantFP(0.0, dl, VT);
6284     if (VT.isVector()) {
6285       unsigned NumElts = VT.getVectorNumElements();
6286       MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
6287       return DAG.getNode(ISD::BITCAST, dl, VT,
6288                          DAG.getConstant(0, dl,
6289                                          EVT::getVectorVT(*DAG.getContext(),
6290                                                           EltVT, NumElts)));
6291     }
6292     llvm_unreachable("Expected type!");
6293   }
6294 
6295   assert(!VT.isVector() && "Can't handle vector type here!");
6296   unsigned NumVTBits = VT.getSizeInBits();
6297   unsigned NumVTBytes = NumVTBits / 8;
6298   unsigned NumBytes = std::min(NumVTBytes, unsigned(Slice.Length));
6299 
6300   APInt Val(NumVTBits, 0);
6301   if (DAG.getDataLayout().isLittleEndian()) {
6302     for (unsigned i = 0; i != NumBytes; ++i)
6303       Val |= (uint64_t)(unsigned char)Slice[i] << i*8;
6304   } else {
6305     for (unsigned i = 0; i != NumBytes; ++i)
6306       Val |= (uint64_t)(unsigned char)Slice[i] << (NumVTBytes-i-1)*8;
6307   }
6308 
6309   // If the "cost" of materializing the integer immediate is less than the cost
6310   // of a load, then it is cost effective to turn the load into the immediate.
6311   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
6312   if (TLI.shouldConvertConstantLoadToIntImm(Val, Ty))
6313     return DAG.getConstant(Val, dl, VT);
6314   return SDValue(nullptr, 0);
6315 }
6316 
6317 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Base, TypeSize Offset,
6318                                            const SDLoc &DL,
6319                                            const SDNodeFlags Flags) {
6320   EVT VT = Base.getValueType();
6321   SDValue Index;
6322 
6323   if (Offset.isScalable())
6324     Index = getVScale(DL, Base.getValueType(),
6325                       APInt(Base.getValueSizeInBits().getFixedSize(),
6326                             Offset.getKnownMinSize()));
6327   else
6328     Index = getConstant(Offset.getFixedSize(), DL, VT);
6329 
6330   return getMemBasePlusOffset(Base, Index, DL, Flags);
6331 }
6332 
6333 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Ptr, SDValue Offset,
6334                                            const SDLoc &DL,
6335                                            const SDNodeFlags Flags) {
6336   assert(Offset.getValueType().isInteger());
6337   EVT BasePtrVT = Ptr.getValueType();
6338   return getNode(ISD::ADD, DL, BasePtrVT, Ptr, Offset, Flags);
6339 }
6340 
6341 /// Returns true if memcpy source is constant data.
6342 static bool isMemSrcFromConstant(SDValue Src, ConstantDataArraySlice &Slice) {
6343   uint64_t SrcDelta = 0;
6344   GlobalAddressSDNode *G = nullptr;
6345   if (Src.getOpcode() == ISD::GlobalAddress)
6346     G = cast<GlobalAddressSDNode>(Src);
6347   else if (Src.getOpcode() == ISD::ADD &&
6348            Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
6349            Src.getOperand(1).getOpcode() == ISD::Constant) {
6350     G = cast<GlobalAddressSDNode>(Src.getOperand(0));
6351     SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue();
6352   }
6353   if (!G)
6354     return false;
6355 
6356   return getConstantDataArrayInfo(G->getGlobal(), Slice, 8,
6357                                   SrcDelta + G->getOffset());
6358 }
6359 
6360 static bool shouldLowerMemFuncForSize(const MachineFunction &MF,
6361                                       SelectionDAG &DAG) {
6362   // On Darwin, -Os means optimize for size without hurting performance, so
6363   // only really optimize for size when -Oz (MinSize) is used.
6364   if (MF.getTarget().getTargetTriple().isOSDarwin())
6365     return MF.getFunction().hasMinSize();
6366   return DAG.shouldOptForSize();
6367 }
6368 
6369 static void chainLoadsAndStoresForMemcpy(SelectionDAG &DAG, const SDLoc &dl,
6370                           SmallVector<SDValue, 32> &OutChains, unsigned From,
6371                           unsigned To, SmallVector<SDValue, 16> &OutLoadChains,
6372                           SmallVector<SDValue, 16> &OutStoreChains) {
6373   assert(OutLoadChains.size() && "Missing loads in memcpy inlining");
6374   assert(OutStoreChains.size() && "Missing stores in memcpy inlining");
6375   SmallVector<SDValue, 16> GluedLoadChains;
6376   for (unsigned i = From; i < To; ++i) {
6377     OutChains.push_back(OutLoadChains[i]);
6378     GluedLoadChains.push_back(OutLoadChains[i]);
6379   }
6380 
6381   // Chain for all loads.
6382   SDValue LoadToken = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6383                                   GluedLoadChains);
6384 
6385   for (unsigned i = From; i < To; ++i) {
6386     StoreSDNode *ST = dyn_cast<StoreSDNode>(OutStoreChains[i]);
6387     SDValue NewStore = DAG.getTruncStore(LoadToken, dl, ST->getValue(),
6388                                   ST->getBasePtr(), ST->getMemoryVT(),
6389                                   ST->getMemOperand());
6390     OutChains.push_back(NewStore);
6391   }
6392 }
6393 
6394 static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
6395                                        SDValue Chain, SDValue Dst, SDValue Src,
6396                                        uint64_t Size, Align Alignment,
6397                                        bool isVol, bool AlwaysInline,
6398                                        MachinePointerInfo DstPtrInfo,
6399                                        MachinePointerInfo SrcPtrInfo,
6400                                        const AAMDNodes &AAInfo) {
6401   // Turn a memcpy of undef to nop.
6402   // FIXME: We need to honor volatile even is Src is undef.
6403   if (Src.isUndef())
6404     return Chain;
6405 
6406   // Expand memcpy to a series of load and store ops if the size operand falls
6407   // below a certain threshold.
6408   // TODO: In the AlwaysInline case, if the size is big then generate a loop
6409   // rather than maybe a humongous number of loads and stores.
6410   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6411   const DataLayout &DL = DAG.getDataLayout();
6412   LLVMContext &C = *DAG.getContext();
6413   std::vector<EVT> MemOps;
6414   bool DstAlignCanChange = false;
6415   MachineFunction &MF = DAG.getMachineFunction();
6416   MachineFrameInfo &MFI = MF.getFrameInfo();
6417   bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
6418   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
6419   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
6420     DstAlignCanChange = true;
6421   MaybeAlign SrcAlign = DAG.InferPtrAlign(Src);
6422   if (!SrcAlign || Alignment > *SrcAlign)
6423     SrcAlign = Alignment;
6424   assert(SrcAlign && "SrcAlign must be set");
6425   ConstantDataArraySlice Slice;
6426   // If marked as volatile, perform a copy even when marked as constant.
6427   bool CopyFromConstant = !isVol && isMemSrcFromConstant(Src, Slice);
6428   bool isZeroConstant = CopyFromConstant && Slice.Array == nullptr;
6429   unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize);
6430   const MemOp Op = isZeroConstant
6431                        ? MemOp::Set(Size, DstAlignCanChange, Alignment,
6432                                     /*IsZeroMemset*/ true, isVol)
6433                        : MemOp::Copy(Size, DstAlignCanChange, Alignment,
6434                                      *SrcAlign, isVol, CopyFromConstant);
6435   if (!TLI.findOptimalMemOpLowering(
6436           MemOps, Limit, Op, DstPtrInfo.getAddrSpace(),
6437           SrcPtrInfo.getAddrSpace(), MF.getFunction().getAttributes()))
6438     return SDValue();
6439 
6440   if (DstAlignCanChange) {
6441     Type *Ty = MemOps[0].getTypeForEVT(C);
6442     Align NewAlign = DL.getABITypeAlign(Ty);
6443 
6444     // Don't promote to an alignment that would require dynamic stack
6445     // realignment.
6446     const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
6447     if (!TRI->hasStackRealignment(MF))
6448       while (NewAlign > Alignment && DL.exceedsNaturalStackAlignment(NewAlign))
6449         NewAlign = NewAlign / 2;
6450 
6451     if (NewAlign > Alignment) {
6452       // Give the stack frame object a larger alignment if needed.
6453       if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
6454         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
6455       Alignment = NewAlign;
6456     }
6457   }
6458 
6459   // Prepare AAInfo for loads/stores after lowering this memcpy.
6460   AAMDNodes NewAAInfo = AAInfo;
6461   NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
6462 
6463   MachineMemOperand::Flags MMOFlags =
6464       isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
6465   SmallVector<SDValue, 16> OutLoadChains;
6466   SmallVector<SDValue, 16> OutStoreChains;
6467   SmallVector<SDValue, 32> OutChains;
6468   unsigned NumMemOps = MemOps.size();
6469   uint64_t SrcOff = 0, DstOff = 0;
6470   for (unsigned i = 0; i != NumMemOps; ++i) {
6471     EVT VT = MemOps[i];
6472     unsigned VTSize = VT.getSizeInBits() / 8;
6473     SDValue Value, Store;
6474 
6475     if (VTSize > Size) {
6476       // Issuing an unaligned load / store pair  that overlaps with the previous
6477       // pair. Adjust the offset accordingly.
6478       assert(i == NumMemOps-1 && i != 0);
6479       SrcOff -= VTSize - Size;
6480       DstOff -= VTSize - Size;
6481     }
6482 
6483     if (CopyFromConstant &&
6484         (isZeroConstant || (VT.isInteger() && !VT.isVector()))) {
6485       // It's unlikely a store of a vector immediate can be done in a single
6486       // instruction. It would require a load from a constantpool first.
6487       // We only handle zero vectors here.
6488       // FIXME: Handle other cases where store of vector immediate is done in
6489       // a single instruction.
6490       ConstantDataArraySlice SubSlice;
6491       if (SrcOff < Slice.Length) {
6492         SubSlice = Slice;
6493         SubSlice.move(SrcOff);
6494       } else {
6495         // This is an out-of-bounds access and hence UB. Pretend we read zero.
6496         SubSlice.Array = nullptr;
6497         SubSlice.Offset = 0;
6498         SubSlice.Length = VTSize;
6499       }
6500       Value = getMemsetStringVal(VT, dl, DAG, TLI, SubSlice);
6501       if (Value.getNode()) {
6502         Store = DAG.getStore(
6503             Chain, dl, Value,
6504             DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6505             DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo);
6506         OutChains.push_back(Store);
6507       }
6508     }
6509 
6510     if (!Store.getNode()) {
6511       // The type might not be legal for the target.  This should only happen
6512       // if the type is smaller than a legal type, as on PPC, so the right
6513       // thing to do is generate a LoadExt/StoreTrunc pair.  These simplify
6514       // to Load/Store if NVT==VT.
6515       // FIXME does the case above also need this?
6516       EVT NVT = TLI.getTypeToTransformTo(C, VT);
6517       assert(NVT.bitsGE(VT));
6518 
6519       bool isDereferenceable =
6520         SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
6521       MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
6522       if (isDereferenceable)
6523         SrcMMOFlags |= MachineMemOperand::MODereferenceable;
6524 
6525       Value = DAG.getExtLoad(
6526           ISD::EXTLOAD, dl, NVT, Chain,
6527           DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl),
6528           SrcPtrInfo.getWithOffset(SrcOff), VT,
6529           commonAlignment(*SrcAlign, SrcOff), SrcMMOFlags, NewAAInfo);
6530       OutLoadChains.push_back(Value.getValue(1));
6531 
6532       Store = DAG.getTruncStore(
6533           Chain, dl, Value,
6534           DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6535           DstPtrInfo.getWithOffset(DstOff), VT, Alignment, MMOFlags, NewAAInfo);
6536       OutStoreChains.push_back(Store);
6537     }
6538     SrcOff += VTSize;
6539     DstOff += VTSize;
6540     Size -= VTSize;
6541   }
6542 
6543   unsigned GluedLdStLimit = MaxLdStGlue == 0 ?
6544                                 TLI.getMaxGluedStoresPerMemcpy() : MaxLdStGlue;
6545   unsigned NumLdStInMemcpy = OutStoreChains.size();
6546 
6547   if (NumLdStInMemcpy) {
6548     // It may be that memcpy might be converted to memset if it's memcpy
6549     // of constants. In such a case, we won't have loads and stores, but
6550     // just stores. In the absence of loads, there is nothing to gang up.
6551     if ((GluedLdStLimit <= 1) || !EnableMemCpyDAGOpt) {
6552       // If target does not care, just leave as it.
6553       for (unsigned i = 0; i < NumLdStInMemcpy; ++i) {
6554         OutChains.push_back(OutLoadChains[i]);
6555         OutChains.push_back(OutStoreChains[i]);
6556       }
6557     } else {
6558       // Ld/St less than/equal limit set by target.
6559       if (NumLdStInMemcpy <= GluedLdStLimit) {
6560           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
6561                                         NumLdStInMemcpy, OutLoadChains,
6562                                         OutStoreChains);
6563       } else {
6564         unsigned NumberLdChain =  NumLdStInMemcpy / GluedLdStLimit;
6565         unsigned RemainingLdStInMemcpy = NumLdStInMemcpy % GluedLdStLimit;
6566         unsigned GlueIter = 0;
6567 
6568         for (unsigned cnt = 0; cnt < NumberLdChain; ++cnt) {
6569           unsigned IndexFrom = NumLdStInMemcpy - GlueIter - GluedLdStLimit;
6570           unsigned IndexTo   = NumLdStInMemcpy - GlueIter;
6571 
6572           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, IndexFrom, IndexTo,
6573                                        OutLoadChains, OutStoreChains);
6574           GlueIter += GluedLdStLimit;
6575         }
6576 
6577         // Residual ld/st.
6578         if (RemainingLdStInMemcpy) {
6579           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
6580                                         RemainingLdStInMemcpy, OutLoadChains,
6581                                         OutStoreChains);
6582         }
6583       }
6584     }
6585   }
6586   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
6587 }
6588 
6589 static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
6590                                         SDValue Chain, SDValue Dst, SDValue Src,
6591                                         uint64_t Size, Align Alignment,
6592                                         bool isVol, bool AlwaysInline,
6593                                         MachinePointerInfo DstPtrInfo,
6594                                         MachinePointerInfo SrcPtrInfo,
6595                                         const AAMDNodes &AAInfo) {
6596   // Turn a memmove of undef to nop.
6597   // FIXME: We need to honor volatile even is Src is undef.
6598   if (Src.isUndef())
6599     return Chain;
6600 
6601   // Expand memmove to a series of load and store ops if the size operand falls
6602   // below a certain threshold.
6603   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6604   const DataLayout &DL = DAG.getDataLayout();
6605   LLVMContext &C = *DAG.getContext();
6606   std::vector<EVT> MemOps;
6607   bool DstAlignCanChange = false;
6608   MachineFunction &MF = DAG.getMachineFunction();
6609   MachineFrameInfo &MFI = MF.getFrameInfo();
6610   bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
6611   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
6612   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
6613     DstAlignCanChange = true;
6614   MaybeAlign SrcAlign = DAG.InferPtrAlign(Src);
6615   if (!SrcAlign || Alignment > *SrcAlign)
6616     SrcAlign = Alignment;
6617   assert(SrcAlign && "SrcAlign must be set");
6618   unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize);
6619   if (!TLI.findOptimalMemOpLowering(
6620           MemOps, Limit,
6621           MemOp::Copy(Size, DstAlignCanChange, Alignment, *SrcAlign,
6622                       /*IsVolatile*/ true),
6623           DstPtrInfo.getAddrSpace(), SrcPtrInfo.getAddrSpace(),
6624           MF.getFunction().getAttributes()))
6625     return SDValue();
6626 
6627   if (DstAlignCanChange) {
6628     Type *Ty = MemOps[0].getTypeForEVT(C);
6629     Align NewAlign = DL.getABITypeAlign(Ty);
6630     if (NewAlign > Alignment) {
6631       // Give the stack frame object a larger alignment if needed.
6632       if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
6633         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
6634       Alignment = NewAlign;
6635     }
6636   }
6637 
6638   // Prepare AAInfo for loads/stores after lowering this memmove.
6639   AAMDNodes NewAAInfo = AAInfo;
6640   NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
6641 
6642   MachineMemOperand::Flags MMOFlags =
6643       isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
6644   uint64_t SrcOff = 0, DstOff = 0;
6645   SmallVector<SDValue, 8> LoadValues;
6646   SmallVector<SDValue, 8> LoadChains;
6647   SmallVector<SDValue, 8> OutChains;
6648   unsigned NumMemOps = MemOps.size();
6649   for (unsigned i = 0; i < NumMemOps; i++) {
6650     EVT VT = MemOps[i];
6651     unsigned VTSize = VT.getSizeInBits() / 8;
6652     SDValue Value;
6653 
6654     bool isDereferenceable =
6655       SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
6656     MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
6657     if (isDereferenceable)
6658       SrcMMOFlags |= MachineMemOperand::MODereferenceable;
6659 
6660     Value = DAG.getLoad(
6661         VT, dl, Chain,
6662         DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl),
6663         SrcPtrInfo.getWithOffset(SrcOff), *SrcAlign, SrcMMOFlags, NewAAInfo);
6664     LoadValues.push_back(Value);
6665     LoadChains.push_back(Value.getValue(1));
6666     SrcOff += VTSize;
6667   }
6668   Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
6669   OutChains.clear();
6670   for (unsigned i = 0; i < NumMemOps; i++) {
6671     EVT VT = MemOps[i];
6672     unsigned VTSize = VT.getSizeInBits() / 8;
6673     SDValue Store;
6674 
6675     Store = DAG.getStore(
6676         Chain, dl, LoadValues[i],
6677         DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6678         DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo);
6679     OutChains.push_back(Store);
6680     DstOff += VTSize;
6681   }
6682 
6683   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
6684 }
6685 
6686 /// Lower the call to 'memset' intrinsic function into a series of store
6687 /// operations.
6688 ///
6689 /// \param DAG Selection DAG where lowered code is placed.
6690 /// \param dl Link to corresponding IR location.
6691 /// \param Chain Control flow dependency.
6692 /// \param Dst Pointer to destination memory location.
6693 /// \param Src Value of byte to write into the memory.
6694 /// \param Size Number of bytes to write.
6695 /// \param Alignment Alignment of the destination in bytes.
6696 /// \param isVol True if destination is volatile.
6697 /// \param DstPtrInfo IR information on the memory pointer.
6698 /// \returns New head in the control flow, if lowering was successful, empty
6699 /// SDValue otherwise.
6700 ///
6701 /// The function tries to replace 'llvm.memset' intrinsic with several store
6702 /// operations and value calculation code. This is usually profitable for small
6703 /// memory size.
6704 static SDValue getMemsetStores(SelectionDAG &DAG, const SDLoc &dl,
6705                                SDValue Chain, SDValue Dst, SDValue Src,
6706                                uint64_t Size, Align Alignment, bool isVol,
6707                                MachinePointerInfo DstPtrInfo,
6708                                const AAMDNodes &AAInfo) {
6709   // Turn a memset of undef to nop.
6710   // FIXME: We need to honor volatile even is Src is undef.
6711   if (Src.isUndef())
6712     return Chain;
6713 
6714   // Expand memset to a series of load/store ops if the size operand
6715   // falls below a certain threshold.
6716   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6717   std::vector<EVT> MemOps;
6718   bool DstAlignCanChange = false;
6719   MachineFunction &MF = DAG.getMachineFunction();
6720   MachineFrameInfo &MFI = MF.getFrameInfo();
6721   bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
6722   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
6723   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
6724     DstAlignCanChange = true;
6725   bool IsZeroVal =
6726       isa<ConstantSDNode>(Src) && cast<ConstantSDNode>(Src)->isZero();
6727   if (!TLI.findOptimalMemOpLowering(
6728           MemOps, TLI.getMaxStoresPerMemset(OptSize),
6729           MemOp::Set(Size, DstAlignCanChange, Alignment, IsZeroVal, isVol),
6730           DstPtrInfo.getAddrSpace(), ~0u, MF.getFunction().getAttributes()))
6731     return SDValue();
6732 
6733   if (DstAlignCanChange) {
6734     Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
6735     Align NewAlign = DAG.getDataLayout().getABITypeAlign(Ty);
6736     if (NewAlign > Alignment) {
6737       // Give the stack frame object a larger alignment if needed.
6738       if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
6739         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
6740       Alignment = NewAlign;
6741     }
6742   }
6743 
6744   SmallVector<SDValue, 8> OutChains;
6745   uint64_t DstOff = 0;
6746   unsigned NumMemOps = MemOps.size();
6747 
6748   // Find the largest store and generate the bit pattern for it.
6749   EVT LargestVT = MemOps[0];
6750   for (unsigned i = 1; i < NumMemOps; i++)
6751     if (MemOps[i].bitsGT(LargestVT))
6752       LargestVT = MemOps[i];
6753   SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl);
6754 
6755   // Prepare AAInfo for loads/stores after lowering this memset.
6756   AAMDNodes NewAAInfo = AAInfo;
6757   NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
6758 
6759   for (unsigned i = 0; i < NumMemOps; i++) {
6760     EVT VT = MemOps[i];
6761     unsigned VTSize = VT.getSizeInBits() / 8;
6762     if (VTSize > Size) {
6763       // Issuing an unaligned load / store pair  that overlaps with the previous
6764       // pair. Adjust the offset accordingly.
6765       assert(i == NumMemOps-1 && i != 0);
6766       DstOff -= VTSize - Size;
6767     }
6768 
6769     // If this store is smaller than the largest store see whether we can get
6770     // the smaller value for free with a truncate.
6771     SDValue Value = MemSetValue;
6772     if (VT.bitsLT(LargestVT)) {
6773       if (!LargestVT.isVector() && !VT.isVector() &&
6774           TLI.isTruncateFree(LargestVT, VT))
6775         Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue);
6776       else
6777         Value = getMemsetValue(Src, VT, DAG, dl);
6778     }
6779     assert(Value.getValueType() == VT && "Value with wrong type.");
6780     SDValue Store = DAG.getStore(
6781         Chain, dl, Value,
6782         DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6783         DstPtrInfo.getWithOffset(DstOff), Alignment,
6784         isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone,
6785         NewAAInfo);
6786     OutChains.push_back(Store);
6787     DstOff += VT.getSizeInBits() / 8;
6788     Size -= VTSize;
6789   }
6790 
6791   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
6792 }
6793 
6794 static void checkAddrSpaceIsValidForLibcall(const TargetLowering *TLI,
6795                                             unsigned AS) {
6796   // Lowering memcpy / memset / memmove intrinsics to calls is only valid if all
6797   // pointer operands can be losslessly bitcasted to pointers of address space 0
6798   if (AS != 0 && !TLI->getTargetMachine().isNoopAddrSpaceCast(AS, 0)) {
6799     report_fatal_error("cannot lower memory intrinsic in address space " +
6800                        Twine(AS));
6801   }
6802 }
6803 
6804 SDValue SelectionDAG::getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst,
6805                                 SDValue Src, SDValue Size, Align Alignment,
6806                                 bool isVol, bool AlwaysInline, bool isTailCall,
6807                                 MachinePointerInfo DstPtrInfo,
6808                                 MachinePointerInfo SrcPtrInfo,
6809                                 const AAMDNodes &AAInfo) {
6810   // Check to see if we should lower the memcpy to loads and stores first.
6811   // For cases within the target-specified limits, this is the best choice.
6812   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6813   if (ConstantSize) {
6814     // Memcpy with size zero? Just return the original chain.
6815     if (ConstantSize->isZero())
6816       return Chain;
6817 
6818     SDValue Result = getMemcpyLoadsAndStores(
6819         *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment,
6820         isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo);
6821     if (Result.getNode())
6822       return Result;
6823   }
6824 
6825   // Then check to see if we should lower the memcpy with target-specific
6826   // code. If the target chooses to do this, this is the next best.
6827   if (TSI) {
6828     SDValue Result = TSI->EmitTargetCodeForMemcpy(
6829         *this, dl, Chain, Dst, Src, Size, Alignment, isVol, AlwaysInline,
6830         DstPtrInfo, SrcPtrInfo);
6831     if (Result.getNode())
6832       return Result;
6833   }
6834 
6835   // If we really need inline code and the target declined to provide it,
6836   // use a (potentially long) sequence of loads and stores.
6837   if (AlwaysInline) {
6838     assert(ConstantSize && "AlwaysInline requires a constant size!");
6839     return getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
6840                                    ConstantSize->getZExtValue(), Alignment,
6841                                    isVol, true, DstPtrInfo, SrcPtrInfo, AAInfo);
6842   }
6843 
6844   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
6845   checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
6846 
6847   // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc
6848   // memcpy is not guaranteed to be safe. libc memcpys aren't required to
6849   // respect volatile, so they may do things like read or write memory
6850   // beyond the given memory regions. But fixing this isn't easy, and most
6851   // people don't care.
6852 
6853   // Emit a library call.
6854   TargetLowering::ArgListTy Args;
6855   TargetLowering::ArgListEntry Entry;
6856   Entry.Ty = Type::getInt8PtrTy(*getContext());
6857   Entry.Node = Dst; Args.push_back(Entry);
6858   Entry.Node = Src; Args.push_back(Entry);
6859 
6860   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6861   Entry.Node = Size; Args.push_back(Entry);
6862   // FIXME: pass in SDLoc
6863   TargetLowering::CallLoweringInfo CLI(*this);
6864   CLI.setDebugLoc(dl)
6865       .setChain(Chain)
6866       .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMCPY),
6867                     Dst.getValueType().getTypeForEVT(*getContext()),
6868                     getExternalSymbol(TLI->getLibcallName(RTLIB::MEMCPY),
6869                                       TLI->getPointerTy(getDataLayout())),
6870                     std::move(Args))
6871       .setDiscardResult()
6872       .setTailCall(isTailCall);
6873 
6874   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
6875   return CallResult.second;
6876 }
6877 
6878 SDValue SelectionDAG::getAtomicMemcpy(SDValue Chain, const SDLoc &dl,
6879                                       SDValue Dst, unsigned DstAlign,
6880                                       SDValue Src, unsigned SrcAlign,
6881                                       SDValue Size, Type *SizeTy,
6882                                       unsigned ElemSz, bool isTailCall,
6883                                       MachinePointerInfo DstPtrInfo,
6884                                       MachinePointerInfo SrcPtrInfo) {
6885   // Emit a library call.
6886   TargetLowering::ArgListTy Args;
6887   TargetLowering::ArgListEntry Entry;
6888   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6889   Entry.Node = Dst;
6890   Args.push_back(Entry);
6891 
6892   Entry.Node = Src;
6893   Args.push_back(Entry);
6894 
6895   Entry.Ty = SizeTy;
6896   Entry.Node = Size;
6897   Args.push_back(Entry);
6898 
6899   RTLIB::Libcall LibraryCall =
6900       RTLIB::getMEMCPY_ELEMENT_UNORDERED_ATOMIC(ElemSz);
6901   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
6902     report_fatal_error("Unsupported element size");
6903 
6904   TargetLowering::CallLoweringInfo CLI(*this);
6905   CLI.setDebugLoc(dl)
6906       .setChain(Chain)
6907       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
6908                     Type::getVoidTy(*getContext()),
6909                     getExternalSymbol(TLI->getLibcallName(LibraryCall),
6910                                       TLI->getPointerTy(getDataLayout())),
6911                     std::move(Args))
6912       .setDiscardResult()
6913       .setTailCall(isTailCall);
6914 
6915   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
6916   return CallResult.second;
6917 }
6918 
6919 SDValue SelectionDAG::getMemmove(SDValue Chain, const SDLoc &dl, SDValue Dst,
6920                                  SDValue Src, SDValue Size, Align Alignment,
6921                                  bool isVol, bool isTailCall,
6922                                  MachinePointerInfo DstPtrInfo,
6923                                  MachinePointerInfo SrcPtrInfo,
6924                                  const AAMDNodes &AAInfo) {
6925   // Check to see if we should lower the memmove to loads and stores first.
6926   // For cases within the target-specified limits, this is the best choice.
6927   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6928   if (ConstantSize) {
6929     // Memmove with size zero? Just return the original chain.
6930     if (ConstantSize->isZero())
6931       return Chain;
6932 
6933     SDValue Result = getMemmoveLoadsAndStores(
6934         *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment,
6935         isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo);
6936     if (Result.getNode())
6937       return Result;
6938   }
6939 
6940   // Then check to see if we should lower the memmove with target-specific
6941   // code. If the target chooses to do this, this is the next best.
6942   if (TSI) {
6943     SDValue Result =
6944         TSI->EmitTargetCodeForMemmove(*this, dl, Chain, Dst, Src, Size,
6945                                       Alignment, isVol, DstPtrInfo, SrcPtrInfo);
6946     if (Result.getNode())
6947       return Result;
6948   }
6949 
6950   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
6951   checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
6952 
6953   // FIXME: If the memmove is volatile, lowering it to plain libc memmove may
6954   // not be safe.  See memcpy above for more details.
6955 
6956   // Emit a library call.
6957   TargetLowering::ArgListTy Args;
6958   TargetLowering::ArgListEntry Entry;
6959   Entry.Ty = Type::getInt8PtrTy(*getContext());
6960   Entry.Node = Dst; Args.push_back(Entry);
6961   Entry.Node = Src; Args.push_back(Entry);
6962 
6963   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6964   Entry.Node = Size; Args.push_back(Entry);
6965   // FIXME:  pass in SDLoc
6966   TargetLowering::CallLoweringInfo CLI(*this);
6967   CLI.setDebugLoc(dl)
6968       .setChain(Chain)
6969       .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMMOVE),
6970                     Dst.getValueType().getTypeForEVT(*getContext()),
6971                     getExternalSymbol(TLI->getLibcallName(RTLIB::MEMMOVE),
6972                                       TLI->getPointerTy(getDataLayout())),
6973                     std::move(Args))
6974       .setDiscardResult()
6975       .setTailCall(isTailCall);
6976 
6977   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
6978   return CallResult.second;
6979 }
6980 
6981 SDValue SelectionDAG::getAtomicMemmove(SDValue Chain, const SDLoc &dl,
6982                                        SDValue Dst, unsigned DstAlign,
6983                                        SDValue Src, unsigned SrcAlign,
6984                                        SDValue Size, Type *SizeTy,
6985                                        unsigned ElemSz, bool isTailCall,
6986                                        MachinePointerInfo DstPtrInfo,
6987                                        MachinePointerInfo SrcPtrInfo) {
6988   // Emit a library call.
6989   TargetLowering::ArgListTy Args;
6990   TargetLowering::ArgListEntry Entry;
6991   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6992   Entry.Node = Dst;
6993   Args.push_back(Entry);
6994 
6995   Entry.Node = Src;
6996   Args.push_back(Entry);
6997 
6998   Entry.Ty = SizeTy;
6999   Entry.Node = Size;
7000   Args.push_back(Entry);
7001 
7002   RTLIB::Libcall LibraryCall =
7003       RTLIB::getMEMMOVE_ELEMENT_UNORDERED_ATOMIC(ElemSz);
7004   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
7005     report_fatal_error("Unsupported element size");
7006 
7007   TargetLowering::CallLoweringInfo CLI(*this);
7008   CLI.setDebugLoc(dl)
7009       .setChain(Chain)
7010       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
7011                     Type::getVoidTy(*getContext()),
7012                     getExternalSymbol(TLI->getLibcallName(LibraryCall),
7013                                       TLI->getPointerTy(getDataLayout())),
7014                     std::move(Args))
7015       .setDiscardResult()
7016       .setTailCall(isTailCall);
7017 
7018   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
7019   return CallResult.second;
7020 }
7021 
7022 SDValue SelectionDAG::getMemset(SDValue Chain, const SDLoc &dl, SDValue Dst,
7023                                 SDValue Src, SDValue Size, Align Alignment,
7024                                 bool isVol, bool isTailCall,
7025                                 MachinePointerInfo DstPtrInfo,
7026                                 const AAMDNodes &AAInfo) {
7027   // Check to see if we should lower the memset to stores first.
7028   // For cases within the target-specified limits, this is the best choice.
7029   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
7030   if (ConstantSize) {
7031     // Memset with size zero? Just return the original chain.
7032     if (ConstantSize->isZero())
7033       return Chain;
7034 
7035     SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src,
7036                                      ConstantSize->getZExtValue(), Alignment,
7037                                      isVol, DstPtrInfo, AAInfo);
7038 
7039     if (Result.getNode())
7040       return Result;
7041   }
7042 
7043   // Then check to see if we should lower the memset with target-specific
7044   // code. If the target chooses to do this, this is the next best.
7045   if (TSI) {
7046     SDValue Result = TSI->EmitTargetCodeForMemset(
7047         *this, dl, Chain, Dst, Src, Size, Alignment, isVol, DstPtrInfo);
7048     if (Result.getNode())
7049       return Result;
7050   }
7051 
7052   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
7053 
7054   // Emit a library call.
7055   TargetLowering::ArgListTy Args;
7056   TargetLowering::ArgListEntry Entry;
7057   Entry.Node = Dst; Entry.Ty = Type::getInt8PtrTy(*getContext());
7058   Args.push_back(Entry);
7059   Entry.Node = Src;
7060   Entry.Ty = Src.getValueType().getTypeForEVT(*getContext());
7061   Args.push_back(Entry);
7062   Entry.Node = Size;
7063   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7064   Args.push_back(Entry);
7065 
7066   // FIXME: pass in SDLoc
7067   TargetLowering::CallLoweringInfo CLI(*this);
7068   CLI.setDebugLoc(dl)
7069       .setChain(Chain)
7070       .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMSET),
7071                     Dst.getValueType().getTypeForEVT(*getContext()),
7072                     getExternalSymbol(TLI->getLibcallName(RTLIB::MEMSET),
7073                                       TLI->getPointerTy(getDataLayout())),
7074                     std::move(Args))
7075       .setDiscardResult()
7076       .setTailCall(isTailCall);
7077 
7078   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
7079   return CallResult.second;
7080 }
7081 
7082 SDValue SelectionDAG::getAtomicMemset(SDValue Chain, const SDLoc &dl,
7083                                       SDValue Dst, unsigned DstAlign,
7084                                       SDValue Value, SDValue Size, Type *SizeTy,
7085                                       unsigned ElemSz, bool isTailCall,
7086                                       MachinePointerInfo DstPtrInfo) {
7087   // Emit a library call.
7088   TargetLowering::ArgListTy Args;
7089   TargetLowering::ArgListEntry Entry;
7090   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7091   Entry.Node = Dst;
7092   Args.push_back(Entry);
7093 
7094   Entry.Ty = Type::getInt8Ty(*getContext());
7095   Entry.Node = Value;
7096   Args.push_back(Entry);
7097 
7098   Entry.Ty = SizeTy;
7099   Entry.Node = Size;
7100   Args.push_back(Entry);
7101 
7102   RTLIB::Libcall LibraryCall =
7103       RTLIB::getMEMSET_ELEMENT_UNORDERED_ATOMIC(ElemSz);
7104   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
7105     report_fatal_error("Unsupported element size");
7106 
7107   TargetLowering::CallLoweringInfo CLI(*this);
7108   CLI.setDebugLoc(dl)
7109       .setChain(Chain)
7110       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
7111                     Type::getVoidTy(*getContext()),
7112                     getExternalSymbol(TLI->getLibcallName(LibraryCall),
7113                                       TLI->getPointerTy(getDataLayout())),
7114                     std::move(Args))
7115       .setDiscardResult()
7116       .setTailCall(isTailCall);
7117 
7118   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
7119   return CallResult.second;
7120 }
7121 
7122 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
7123                                 SDVTList VTList, ArrayRef<SDValue> Ops,
7124                                 MachineMemOperand *MMO) {
7125   FoldingSetNodeID ID;
7126   ID.AddInteger(MemVT.getRawBits());
7127   AddNodeIDNode(ID, Opcode, VTList, Ops);
7128   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7129   void* IP = nullptr;
7130   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7131     cast<AtomicSDNode>(E)->refineAlignment(MMO);
7132     return SDValue(E, 0);
7133   }
7134 
7135   auto *N = newSDNode<AtomicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
7136                                     VTList, MemVT, MMO);
7137   createOperands(N, Ops);
7138 
7139   CSEMap.InsertNode(N, IP);
7140   InsertNode(N);
7141   return SDValue(N, 0);
7142 }
7143 
7144 SDValue SelectionDAG::getAtomicCmpSwap(unsigned Opcode, const SDLoc &dl,
7145                                        EVT MemVT, SDVTList VTs, SDValue Chain,
7146                                        SDValue Ptr, SDValue Cmp, SDValue Swp,
7147                                        MachineMemOperand *MMO) {
7148   assert(Opcode == ISD::ATOMIC_CMP_SWAP ||
7149          Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
7150   assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
7151 
7152   SDValue Ops[] = {Chain, Ptr, Cmp, Swp};
7153   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
7154 }
7155 
7156 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
7157                                 SDValue Chain, SDValue Ptr, SDValue Val,
7158                                 MachineMemOperand *MMO) {
7159   assert((Opcode == ISD::ATOMIC_LOAD_ADD ||
7160           Opcode == ISD::ATOMIC_LOAD_SUB ||
7161           Opcode == ISD::ATOMIC_LOAD_AND ||
7162           Opcode == ISD::ATOMIC_LOAD_CLR ||
7163           Opcode == ISD::ATOMIC_LOAD_OR ||
7164           Opcode == ISD::ATOMIC_LOAD_XOR ||
7165           Opcode == ISD::ATOMIC_LOAD_NAND ||
7166           Opcode == ISD::ATOMIC_LOAD_MIN ||
7167           Opcode == ISD::ATOMIC_LOAD_MAX ||
7168           Opcode == ISD::ATOMIC_LOAD_UMIN ||
7169           Opcode == ISD::ATOMIC_LOAD_UMAX ||
7170           Opcode == ISD::ATOMIC_LOAD_FADD ||
7171           Opcode == ISD::ATOMIC_LOAD_FSUB ||
7172           Opcode == ISD::ATOMIC_SWAP ||
7173           Opcode == ISD::ATOMIC_STORE) &&
7174          "Invalid Atomic Op");
7175 
7176   EVT VT = Val.getValueType();
7177 
7178   SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) :
7179                                                getVTList(VT, MVT::Other);
7180   SDValue Ops[] = {Chain, Ptr, Val};
7181   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
7182 }
7183 
7184 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
7185                                 EVT VT, SDValue Chain, SDValue Ptr,
7186                                 MachineMemOperand *MMO) {
7187   assert(Opcode == ISD::ATOMIC_LOAD && "Invalid Atomic Op");
7188 
7189   SDVTList VTs = getVTList(VT, MVT::Other);
7190   SDValue Ops[] = {Chain, Ptr};
7191   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
7192 }
7193 
7194 /// getMergeValues - Create a MERGE_VALUES node from the given operands.
7195 SDValue SelectionDAG::getMergeValues(ArrayRef<SDValue> Ops, const SDLoc &dl) {
7196   if (Ops.size() == 1)
7197     return Ops[0];
7198 
7199   SmallVector<EVT, 4> VTs;
7200   VTs.reserve(Ops.size());
7201   for (const SDValue &Op : Ops)
7202     VTs.push_back(Op.getValueType());
7203   return getNode(ISD::MERGE_VALUES, dl, getVTList(VTs), Ops);
7204 }
7205 
7206 SDValue SelectionDAG::getMemIntrinsicNode(
7207     unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef<SDValue> Ops,
7208     EVT MemVT, MachinePointerInfo PtrInfo, Align Alignment,
7209     MachineMemOperand::Flags Flags, uint64_t Size, const AAMDNodes &AAInfo) {
7210   if (!Size && MemVT.isScalableVector())
7211     Size = MemoryLocation::UnknownSize;
7212   else if (!Size)
7213     Size = MemVT.getStoreSize();
7214 
7215   MachineFunction &MF = getMachineFunction();
7216   MachineMemOperand *MMO =
7217       MF.getMachineMemOperand(PtrInfo, Flags, Size, Alignment, AAInfo);
7218 
7219   return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, MMO);
7220 }
7221 
7222 SDValue SelectionDAG::getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl,
7223                                           SDVTList VTList,
7224                                           ArrayRef<SDValue> Ops, EVT MemVT,
7225                                           MachineMemOperand *MMO) {
7226   assert((Opcode == ISD::INTRINSIC_VOID ||
7227           Opcode == ISD::INTRINSIC_W_CHAIN ||
7228           Opcode == ISD::PREFETCH ||
7229           ((int)Opcode <= std::numeric_limits<int>::max() &&
7230            (int)Opcode >= ISD::FIRST_TARGET_MEMORY_OPCODE)) &&
7231          "Opcode is not a memory-accessing opcode!");
7232 
7233   // Memoize the node unless it returns a flag.
7234   MemIntrinsicSDNode *N;
7235   if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
7236     FoldingSetNodeID ID;
7237     AddNodeIDNode(ID, Opcode, VTList, Ops);
7238     ID.AddInteger(getSyntheticNodeSubclassData<MemIntrinsicSDNode>(
7239         Opcode, dl.getIROrder(), VTList, MemVT, MMO));
7240     ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7241     void *IP = nullptr;
7242     if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7243       cast<MemIntrinsicSDNode>(E)->refineAlignment(MMO);
7244       return SDValue(E, 0);
7245     }
7246 
7247     N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
7248                                       VTList, MemVT, MMO);
7249     createOperands(N, Ops);
7250 
7251   CSEMap.InsertNode(N, IP);
7252   } else {
7253     N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
7254                                       VTList, MemVT, MMO);
7255     createOperands(N, Ops);
7256   }
7257   InsertNode(N);
7258   SDValue V(N, 0);
7259   NewSDValueDbgMsg(V, "Creating new node: ", this);
7260   return V;
7261 }
7262 
7263 SDValue SelectionDAG::getLifetimeNode(bool IsStart, const SDLoc &dl,
7264                                       SDValue Chain, int FrameIndex,
7265                                       int64_t Size, int64_t Offset) {
7266   const unsigned Opcode = IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END;
7267   const auto VTs = getVTList(MVT::Other);
7268   SDValue Ops[2] = {
7269       Chain,
7270       getFrameIndex(FrameIndex,
7271                     getTargetLoweringInfo().getFrameIndexTy(getDataLayout()),
7272                     true)};
7273 
7274   FoldingSetNodeID ID;
7275   AddNodeIDNode(ID, Opcode, VTs, Ops);
7276   ID.AddInteger(FrameIndex);
7277   ID.AddInteger(Size);
7278   ID.AddInteger(Offset);
7279   void *IP = nullptr;
7280   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
7281     return SDValue(E, 0);
7282 
7283   LifetimeSDNode *N = newSDNode<LifetimeSDNode>(
7284       Opcode, dl.getIROrder(), dl.getDebugLoc(), VTs, Size, Offset);
7285   createOperands(N, Ops);
7286   CSEMap.InsertNode(N, IP);
7287   InsertNode(N);
7288   SDValue V(N, 0);
7289   NewSDValueDbgMsg(V, "Creating new node: ", this);
7290   return V;
7291 }
7292 
7293 SDValue SelectionDAG::getPseudoProbeNode(const SDLoc &Dl, SDValue Chain,
7294                                          uint64_t Guid, uint64_t Index,
7295                                          uint32_t Attr) {
7296   const unsigned Opcode = ISD::PSEUDO_PROBE;
7297   const auto VTs = getVTList(MVT::Other);
7298   SDValue Ops[] = {Chain};
7299   FoldingSetNodeID ID;
7300   AddNodeIDNode(ID, Opcode, VTs, Ops);
7301   ID.AddInteger(Guid);
7302   ID.AddInteger(Index);
7303   void *IP = nullptr;
7304   if (SDNode *E = FindNodeOrInsertPos(ID, Dl, IP))
7305     return SDValue(E, 0);
7306 
7307   auto *N = newSDNode<PseudoProbeSDNode>(
7308       Opcode, Dl.getIROrder(), Dl.getDebugLoc(), VTs, Guid, Index, Attr);
7309   createOperands(N, Ops);
7310   CSEMap.InsertNode(N, IP);
7311   InsertNode(N);
7312   SDValue V(N, 0);
7313   NewSDValueDbgMsg(V, "Creating new node: ", this);
7314   return V;
7315 }
7316 
7317 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
7318 /// MachinePointerInfo record from it.  This is particularly useful because the
7319 /// code generator has many cases where it doesn't bother passing in a
7320 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
7321 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info,
7322                                            SelectionDAG &DAG, SDValue Ptr,
7323                                            int64_t Offset = 0) {
7324   // If this is FI+Offset, we can model it.
7325   if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr))
7326     return MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
7327                                              FI->getIndex(), Offset);
7328 
7329   // If this is (FI+Offset1)+Offset2, we can model it.
7330   if (Ptr.getOpcode() != ISD::ADD ||
7331       !isa<ConstantSDNode>(Ptr.getOperand(1)) ||
7332       !isa<FrameIndexSDNode>(Ptr.getOperand(0)))
7333     return Info;
7334 
7335   int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
7336   return MachinePointerInfo::getFixedStack(
7337       DAG.getMachineFunction(), FI,
7338       Offset + cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue());
7339 }
7340 
7341 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
7342 /// MachinePointerInfo record from it.  This is particularly useful because the
7343 /// code generator has many cases where it doesn't bother passing in a
7344 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
7345 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info,
7346                                            SelectionDAG &DAG, SDValue Ptr,
7347                                            SDValue OffsetOp) {
7348   // If the 'Offset' value isn't a constant, we can't handle this.
7349   if (ConstantSDNode *OffsetNode = dyn_cast<ConstantSDNode>(OffsetOp))
7350     return InferPointerInfo(Info, DAG, Ptr, OffsetNode->getSExtValue());
7351   if (OffsetOp.isUndef())
7352     return InferPointerInfo(Info, DAG, Ptr);
7353   return Info;
7354 }
7355 
7356 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
7357                               EVT VT, const SDLoc &dl, SDValue Chain,
7358                               SDValue Ptr, SDValue Offset,
7359                               MachinePointerInfo PtrInfo, EVT MemVT,
7360                               Align Alignment,
7361                               MachineMemOperand::Flags MMOFlags,
7362                               const AAMDNodes &AAInfo, const MDNode *Ranges) {
7363   assert(Chain.getValueType() == MVT::Other &&
7364         "Invalid chain type");
7365 
7366   MMOFlags |= MachineMemOperand::MOLoad;
7367   assert((MMOFlags & MachineMemOperand::MOStore) == 0);
7368   // If we don't have a PtrInfo, infer the trivial frame index case to simplify
7369   // clients.
7370   if (PtrInfo.V.isNull())
7371     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
7372 
7373   uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize());
7374   MachineFunction &MF = getMachineFunction();
7375   MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size,
7376                                                    Alignment, AAInfo, Ranges);
7377   return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO);
7378 }
7379 
7380 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
7381                               EVT VT, const SDLoc &dl, SDValue Chain,
7382                               SDValue Ptr, SDValue Offset, EVT MemVT,
7383                               MachineMemOperand *MMO) {
7384   if (VT == MemVT) {
7385     ExtType = ISD::NON_EXTLOAD;
7386   } else if (ExtType == ISD::NON_EXTLOAD) {
7387     assert(VT == MemVT && "Non-extending load from different memory type!");
7388   } else {
7389     // Extending load.
7390     assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) &&
7391            "Should only be an extending load, not truncating!");
7392     assert(VT.isInteger() == MemVT.isInteger() &&
7393            "Cannot convert from FP to Int or Int -> FP!");
7394     assert(VT.isVector() == MemVT.isVector() &&
7395            "Cannot use an ext load to convert to or from a vector!");
7396     assert((!VT.isVector() ||
7397             VT.getVectorElementCount() == MemVT.getVectorElementCount()) &&
7398            "Cannot use an ext load to change the number of vector elements!");
7399   }
7400 
7401   bool Indexed = AM != ISD::UNINDEXED;
7402   assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
7403 
7404   SDVTList VTs = Indexed ?
7405     getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
7406   SDValue Ops[] = { Chain, Ptr, Offset };
7407   FoldingSetNodeID ID;
7408   AddNodeIDNode(ID, ISD::LOAD, VTs, Ops);
7409   ID.AddInteger(MemVT.getRawBits());
7410   ID.AddInteger(getSyntheticNodeSubclassData<LoadSDNode>(
7411       dl.getIROrder(), VTs, AM, ExtType, MemVT, MMO));
7412   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7413   void *IP = nullptr;
7414   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7415     cast<LoadSDNode>(E)->refineAlignment(MMO);
7416     return SDValue(E, 0);
7417   }
7418   auto *N = newSDNode<LoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
7419                                   ExtType, MemVT, MMO);
7420   createOperands(N, Ops);
7421 
7422   CSEMap.InsertNode(N, IP);
7423   InsertNode(N);
7424   SDValue V(N, 0);
7425   NewSDValueDbgMsg(V, "Creating new node: ", this);
7426   return V;
7427 }
7428 
7429 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
7430                               SDValue Ptr, MachinePointerInfo PtrInfo,
7431                               MaybeAlign Alignment,
7432                               MachineMemOperand::Flags MMOFlags,
7433                               const AAMDNodes &AAInfo, const MDNode *Ranges) {
7434   SDValue Undef = getUNDEF(Ptr.getValueType());
7435   return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7436                  PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges);
7437 }
7438 
7439 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
7440                               SDValue Ptr, MachineMemOperand *MMO) {
7441   SDValue Undef = getUNDEF(Ptr.getValueType());
7442   return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7443                  VT, MMO);
7444 }
7445 
7446 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
7447                                  EVT VT, SDValue Chain, SDValue Ptr,
7448                                  MachinePointerInfo PtrInfo, EVT MemVT,
7449                                  MaybeAlign Alignment,
7450                                  MachineMemOperand::Flags MMOFlags,
7451                                  const AAMDNodes &AAInfo) {
7452   SDValue Undef = getUNDEF(Ptr.getValueType());
7453   return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, PtrInfo,
7454                  MemVT, Alignment, MMOFlags, AAInfo);
7455 }
7456 
7457 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
7458                                  EVT VT, SDValue Chain, SDValue Ptr, EVT MemVT,
7459                                  MachineMemOperand *MMO) {
7460   SDValue Undef = getUNDEF(Ptr.getValueType());
7461   return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef,
7462                  MemVT, MMO);
7463 }
7464 
7465 SDValue SelectionDAG::getIndexedLoad(SDValue OrigLoad, const SDLoc &dl,
7466                                      SDValue Base, SDValue Offset,
7467                                      ISD::MemIndexedMode AM) {
7468   LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
7469   assert(LD->getOffset().isUndef() && "Load is already a indexed load!");
7470   // Don't propagate the invariant or dereferenceable flags.
7471   auto MMOFlags =
7472       LD->getMemOperand()->getFlags() &
7473       ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
7474   return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
7475                  LD->getChain(), Base, Offset, LD->getPointerInfo(),
7476                  LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo());
7477 }
7478 
7479 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7480                                SDValue Ptr, MachinePointerInfo PtrInfo,
7481                                Align Alignment,
7482                                MachineMemOperand::Flags MMOFlags,
7483                                const AAMDNodes &AAInfo) {
7484   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
7485 
7486   MMOFlags |= MachineMemOperand::MOStore;
7487   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
7488 
7489   if (PtrInfo.V.isNull())
7490     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
7491 
7492   MachineFunction &MF = getMachineFunction();
7493   uint64_t Size =
7494       MemoryLocation::getSizeOrUnknown(Val.getValueType().getStoreSize());
7495   MachineMemOperand *MMO =
7496       MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, Alignment, AAInfo);
7497   return getStore(Chain, dl, Val, Ptr, MMO);
7498 }
7499 
7500 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7501                                SDValue Ptr, MachineMemOperand *MMO) {
7502   assert(Chain.getValueType() == MVT::Other &&
7503         "Invalid chain type");
7504   EVT VT = Val.getValueType();
7505   SDVTList VTs = getVTList(MVT::Other);
7506   SDValue Undef = getUNDEF(Ptr.getValueType());
7507   SDValue Ops[] = { Chain, Val, Ptr, Undef };
7508   FoldingSetNodeID ID;
7509   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7510   ID.AddInteger(VT.getRawBits());
7511   ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
7512       dl.getIROrder(), VTs, ISD::UNINDEXED, false, VT, MMO));
7513   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7514   void *IP = nullptr;
7515   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7516     cast<StoreSDNode>(E)->refineAlignment(MMO);
7517     return SDValue(E, 0);
7518   }
7519   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7520                                    ISD::UNINDEXED, false, VT, MMO);
7521   createOperands(N, Ops);
7522 
7523   CSEMap.InsertNode(N, IP);
7524   InsertNode(N);
7525   SDValue V(N, 0);
7526   NewSDValueDbgMsg(V, "Creating new node: ", this);
7527   return V;
7528 }
7529 
7530 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7531                                     SDValue Ptr, MachinePointerInfo PtrInfo,
7532                                     EVT SVT, Align Alignment,
7533                                     MachineMemOperand::Flags MMOFlags,
7534                                     const AAMDNodes &AAInfo) {
7535   assert(Chain.getValueType() == MVT::Other &&
7536         "Invalid chain type");
7537 
7538   MMOFlags |= MachineMemOperand::MOStore;
7539   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
7540 
7541   if (PtrInfo.V.isNull())
7542     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
7543 
7544   MachineFunction &MF = getMachineFunction();
7545   MachineMemOperand *MMO = MF.getMachineMemOperand(
7546       PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()),
7547       Alignment, AAInfo);
7548   return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO);
7549 }
7550 
7551 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7552                                     SDValue Ptr, EVT SVT,
7553                                     MachineMemOperand *MMO) {
7554   EVT VT = Val.getValueType();
7555 
7556   assert(Chain.getValueType() == MVT::Other &&
7557         "Invalid chain type");
7558   if (VT == SVT)
7559     return getStore(Chain, dl, Val, Ptr, MMO);
7560 
7561   assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
7562          "Should only be a truncating store, not extending!");
7563   assert(VT.isInteger() == SVT.isInteger() &&
7564          "Can't do FP-INT conversion!");
7565   assert(VT.isVector() == SVT.isVector() &&
7566          "Cannot use trunc store to convert to or from a vector!");
7567   assert((!VT.isVector() ||
7568           VT.getVectorElementCount() == SVT.getVectorElementCount()) &&
7569          "Cannot use trunc store to change the number of vector elements!");
7570 
7571   SDVTList VTs = getVTList(MVT::Other);
7572   SDValue Undef = getUNDEF(Ptr.getValueType());
7573   SDValue Ops[] = { Chain, Val, Ptr, Undef };
7574   FoldingSetNodeID ID;
7575   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7576   ID.AddInteger(SVT.getRawBits());
7577   ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
7578       dl.getIROrder(), VTs, ISD::UNINDEXED, true, SVT, MMO));
7579   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7580   void *IP = nullptr;
7581   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7582     cast<StoreSDNode>(E)->refineAlignment(MMO);
7583     return SDValue(E, 0);
7584   }
7585   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7586                                    ISD::UNINDEXED, true, SVT, MMO);
7587   createOperands(N, Ops);
7588 
7589   CSEMap.InsertNode(N, IP);
7590   InsertNode(N);
7591   SDValue V(N, 0);
7592   NewSDValueDbgMsg(V, "Creating new node: ", this);
7593   return V;
7594 }
7595 
7596 SDValue SelectionDAG::getIndexedStore(SDValue OrigStore, const SDLoc &dl,
7597                                       SDValue Base, SDValue Offset,
7598                                       ISD::MemIndexedMode AM) {
7599   StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
7600   assert(ST->getOffset().isUndef() && "Store is already a indexed store!");
7601   SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
7602   SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
7603   FoldingSetNodeID ID;
7604   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7605   ID.AddInteger(ST->getMemoryVT().getRawBits());
7606   ID.AddInteger(ST->getRawSubclassData());
7607   ID.AddInteger(ST->getPointerInfo().getAddrSpace());
7608   void *IP = nullptr;
7609   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
7610     return SDValue(E, 0);
7611 
7612   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
7613                                    ST->isTruncatingStore(), ST->getMemoryVT(),
7614                                    ST->getMemOperand());
7615   createOperands(N, Ops);
7616 
7617   CSEMap.InsertNode(N, IP);
7618   InsertNode(N);
7619   SDValue V(N, 0);
7620   NewSDValueDbgMsg(V, "Creating new node: ", this);
7621   return V;
7622 }
7623 
7624 SDValue SelectionDAG::getLoadVP(
7625     ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &dl,
7626     SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Mask, SDValue EVL,
7627     MachinePointerInfo PtrInfo, EVT MemVT, Align Alignment,
7628     MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
7629     const MDNode *Ranges, bool IsExpanding) {
7630   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
7631 
7632   MMOFlags |= MachineMemOperand::MOLoad;
7633   assert((MMOFlags & MachineMemOperand::MOStore) == 0);
7634   // If we don't have a PtrInfo, infer the trivial frame index case to simplify
7635   // clients.
7636   if (PtrInfo.V.isNull())
7637     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
7638 
7639   uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize());
7640   MachineFunction &MF = getMachineFunction();
7641   MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size,
7642                                                    Alignment, AAInfo, Ranges);
7643   return getLoadVP(AM, ExtType, VT, dl, Chain, Ptr, Offset, Mask, EVL, MemVT,
7644                    MMO, IsExpanding);
7645 }
7646 
7647 SDValue SelectionDAG::getLoadVP(ISD::MemIndexedMode AM,
7648                                 ISD::LoadExtType ExtType, EVT VT,
7649                                 const SDLoc &dl, SDValue Chain, SDValue Ptr,
7650                                 SDValue Offset, SDValue Mask, SDValue EVL,
7651                                 EVT MemVT, MachineMemOperand *MMO,
7652                                 bool IsExpanding) {
7653   if (VT == MemVT) {
7654     ExtType = ISD::NON_EXTLOAD;
7655   } else if (ExtType == ISD::NON_EXTLOAD) {
7656     assert(VT == MemVT && "Non-extending load from different memory type!");
7657   } else {
7658     // Extending load.
7659     assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) &&
7660            "Should only be an extending load, not truncating!");
7661     assert(VT.isInteger() == MemVT.isInteger() &&
7662            "Cannot convert from FP to Int or Int -> FP!");
7663     assert(VT.isVector() == MemVT.isVector() &&
7664            "Cannot use an ext load to convert to or from a vector!");
7665     assert((!VT.isVector() ||
7666             VT.getVectorElementCount() == MemVT.getVectorElementCount()) &&
7667            "Cannot use an ext load to change the number of vector elements!");
7668   }
7669 
7670   bool Indexed = AM != ISD::UNINDEXED;
7671   assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
7672 
7673   SDVTList VTs = Indexed ? getVTList(VT, Ptr.getValueType(), MVT::Other)
7674                          : getVTList(VT, MVT::Other);
7675   SDValue Ops[] = {Chain, Ptr, Offset, Mask, EVL};
7676   FoldingSetNodeID ID;
7677   AddNodeIDNode(ID, ISD::VP_LOAD, VTs, Ops);
7678   ID.AddInteger(VT.getRawBits());
7679   ID.AddInteger(getSyntheticNodeSubclassData<VPLoadSDNode>(
7680       dl.getIROrder(), VTs, AM, ExtType, IsExpanding, MemVT, MMO));
7681   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7682   void *IP = nullptr;
7683   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7684     cast<VPLoadSDNode>(E)->refineAlignment(MMO);
7685     return SDValue(E, 0);
7686   }
7687   auto *N = newSDNode<VPLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
7688                                     ExtType, IsExpanding, MemVT, MMO);
7689   createOperands(N, Ops);
7690 
7691   CSEMap.InsertNode(N, IP);
7692   InsertNode(N);
7693   SDValue V(N, 0);
7694   NewSDValueDbgMsg(V, "Creating new node: ", this);
7695   return V;
7696 }
7697 
7698 SDValue SelectionDAG::getLoadVP(EVT VT, const SDLoc &dl, SDValue Chain,
7699                                 SDValue Ptr, SDValue Mask, SDValue EVL,
7700                                 MachinePointerInfo PtrInfo,
7701                                 MaybeAlign Alignment,
7702                                 MachineMemOperand::Flags MMOFlags,
7703                                 const AAMDNodes &AAInfo, const MDNode *Ranges,
7704                                 bool IsExpanding) {
7705   SDValue Undef = getUNDEF(Ptr.getValueType());
7706   return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7707                    Mask, EVL, PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges,
7708                    IsExpanding);
7709 }
7710 
7711 SDValue SelectionDAG::getLoadVP(EVT VT, const SDLoc &dl, SDValue Chain,
7712                                 SDValue Ptr, SDValue Mask, SDValue EVL,
7713                                 MachineMemOperand *MMO, bool IsExpanding) {
7714   SDValue Undef = getUNDEF(Ptr.getValueType());
7715   return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7716                    Mask, EVL, VT, MMO, IsExpanding);
7717 }
7718 
7719 SDValue SelectionDAG::getExtLoadVP(ISD::LoadExtType ExtType, const SDLoc &dl,
7720                                    EVT VT, SDValue Chain, SDValue Ptr,
7721                                    SDValue Mask, SDValue EVL,
7722                                    MachinePointerInfo PtrInfo, EVT MemVT,
7723                                    MaybeAlign Alignment,
7724                                    MachineMemOperand::Flags MMOFlags,
7725                                    const AAMDNodes &AAInfo, bool IsExpanding) {
7726   SDValue Undef = getUNDEF(Ptr.getValueType());
7727   return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask,
7728                    EVL, PtrInfo, MemVT, Alignment, MMOFlags, AAInfo, nullptr,
7729                    IsExpanding);
7730 }
7731 
7732 SDValue SelectionDAG::getExtLoadVP(ISD::LoadExtType ExtType, const SDLoc &dl,
7733                                    EVT VT, SDValue Chain, SDValue Ptr,
7734                                    SDValue Mask, SDValue EVL, EVT MemVT,
7735                                    MachineMemOperand *MMO, bool IsExpanding) {
7736   SDValue Undef = getUNDEF(Ptr.getValueType());
7737   return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask,
7738                    EVL, MemVT, MMO, IsExpanding);
7739 }
7740 
7741 SDValue SelectionDAG::getIndexedLoadVP(SDValue OrigLoad, const SDLoc &dl,
7742                                        SDValue Base, SDValue Offset,
7743                                        ISD::MemIndexedMode AM) {
7744   auto *LD = cast<VPLoadSDNode>(OrigLoad);
7745   assert(LD->getOffset().isUndef() && "Load is already a indexed load!");
7746   // Don't propagate the invariant or dereferenceable flags.
7747   auto MMOFlags =
7748       LD->getMemOperand()->getFlags() &
7749       ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
7750   return getLoadVP(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
7751                    LD->getChain(), Base, Offset, LD->getMask(),
7752                    LD->getVectorLength(), LD->getPointerInfo(),
7753                    LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo(),
7754                    nullptr, LD->isExpandingLoad());
7755 }
7756 
7757 SDValue SelectionDAG::getStoreVP(SDValue Chain, const SDLoc &dl, SDValue Val,
7758                                  SDValue Ptr, SDValue Mask, SDValue EVL,
7759                                  MachinePointerInfo PtrInfo, Align Alignment,
7760                                  MachineMemOperand::Flags MMOFlags,
7761                                  const AAMDNodes &AAInfo, bool IsCompressing) {
7762   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
7763 
7764   MMOFlags |= MachineMemOperand::MOStore;
7765   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
7766 
7767   if (PtrInfo.V.isNull())
7768     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
7769 
7770   MachineFunction &MF = getMachineFunction();
7771   uint64_t Size =
7772       MemoryLocation::getSizeOrUnknown(Val.getValueType().getStoreSize());
7773   MachineMemOperand *MMO =
7774       MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, Alignment, AAInfo);
7775   return getStoreVP(Chain, dl, Val, Ptr, Mask, EVL, MMO, IsCompressing);
7776 }
7777 
7778 SDValue SelectionDAG::getStoreVP(SDValue Chain, const SDLoc &dl, SDValue Val,
7779                                  SDValue Ptr, SDValue Mask, SDValue EVL,
7780                                  MachineMemOperand *MMO, bool IsCompressing) {
7781   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
7782   EVT VT = Val.getValueType();
7783   SDVTList VTs = getVTList(MVT::Other);
7784   SDValue Undef = getUNDEF(Ptr.getValueType());
7785   SDValue Ops[] = {Chain, Val, Ptr, Undef, Mask, EVL};
7786   FoldingSetNodeID ID;
7787   AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
7788   ID.AddInteger(VT.getRawBits());
7789   ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>(
7790       dl.getIROrder(), VTs, ISD::UNINDEXED, false, IsCompressing, VT, MMO));
7791   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7792   void *IP = nullptr;
7793   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7794     cast<VPStoreSDNode>(E)->refineAlignment(MMO);
7795     return SDValue(E, 0);
7796   }
7797   auto *N =
7798       newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7799                                ISD::UNINDEXED, false, IsCompressing, VT, MMO);
7800   createOperands(N, Ops);
7801 
7802   CSEMap.InsertNode(N, IP);
7803   InsertNode(N);
7804   SDValue V(N, 0);
7805   NewSDValueDbgMsg(V, "Creating new node: ", this);
7806   return V;
7807 }
7808 
7809 SDValue SelectionDAG::getTruncStoreVP(SDValue Chain, const SDLoc &dl,
7810                                       SDValue Val, SDValue Ptr, SDValue Mask,
7811                                       SDValue EVL, MachinePointerInfo PtrInfo,
7812                                       EVT SVT, Align Alignment,
7813                                       MachineMemOperand::Flags MMOFlags,
7814                                       const AAMDNodes &AAInfo,
7815                                       bool IsCompressing) {
7816   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
7817 
7818   MMOFlags |= MachineMemOperand::MOStore;
7819   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
7820 
7821   if (PtrInfo.V.isNull())
7822     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
7823 
7824   MachineFunction &MF = getMachineFunction();
7825   MachineMemOperand *MMO = MF.getMachineMemOperand(
7826       PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()),
7827       Alignment, AAInfo);
7828   return getTruncStoreVP(Chain, dl, Val, Ptr, Mask, EVL, SVT, MMO,
7829                          IsCompressing);
7830 }
7831 
7832 SDValue SelectionDAG::getTruncStoreVP(SDValue Chain, const SDLoc &dl,
7833                                       SDValue Val, SDValue Ptr, SDValue Mask,
7834                                       SDValue EVL, EVT SVT,
7835                                       MachineMemOperand *MMO,
7836                                       bool IsCompressing) {
7837   EVT VT = Val.getValueType();
7838 
7839   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
7840   if (VT == SVT)
7841     return getStoreVP(Chain, dl, Val, Ptr, Mask, EVL, MMO, IsCompressing);
7842 
7843   assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
7844          "Should only be a truncating store, not extending!");
7845   assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!");
7846   assert(VT.isVector() == SVT.isVector() &&
7847          "Cannot use trunc store to convert to or from a vector!");
7848   assert((!VT.isVector() ||
7849           VT.getVectorElementCount() == SVT.getVectorElementCount()) &&
7850          "Cannot use trunc store to change the number of vector elements!");
7851 
7852   SDVTList VTs = getVTList(MVT::Other);
7853   SDValue Undef = getUNDEF(Ptr.getValueType());
7854   SDValue Ops[] = {Chain, Val, Ptr, Undef, Mask, EVL};
7855   FoldingSetNodeID ID;
7856   AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
7857   ID.AddInteger(SVT.getRawBits());
7858   ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>(
7859       dl.getIROrder(), VTs, ISD::UNINDEXED, true, IsCompressing, SVT, MMO));
7860   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7861   void *IP = nullptr;
7862   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7863     cast<VPStoreSDNode>(E)->refineAlignment(MMO);
7864     return SDValue(E, 0);
7865   }
7866   auto *N =
7867       newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7868                                ISD::UNINDEXED, true, IsCompressing, SVT, MMO);
7869   createOperands(N, Ops);
7870 
7871   CSEMap.InsertNode(N, IP);
7872   InsertNode(N);
7873   SDValue V(N, 0);
7874   NewSDValueDbgMsg(V, "Creating new node: ", this);
7875   return V;
7876 }
7877 
7878 SDValue SelectionDAG::getIndexedStoreVP(SDValue OrigStore, const SDLoc &dl,
7879                                         SDValue Base, SDValue Offset,
7880                                         ISD::MemIndexedMode AM) {
7881   auto *ST = cast<VPStoreSDNode>(OrigStore);
7882   assert(ST->getOffset().isUndef() && "Store is already an indexed store!");
7883   SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
7884   SDValue Ops[] = {ST->getChain(), ST->getValue(), Base,
7885                    Offset,         ST->getMask(),  ST->getVectorLength()};
7886   FoldingSetNodeID ID;
7887   AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
7888   ID.AddInteger(ST->getMemoryVT().getRawBits());
7889   ID.AddInteger(ST->getRawSubclassData());
7890   ID.AddInteger(ST->getPointerInfo().getAddrSpace());
7891   void *IP = nullptr;
7892   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
7893     return SDValue(E, 0);
7894 
7895   auto *N = newSDNode<VPStoreSDNode>(
7896       dl.getIROrder(), dl.getDebugLoc(), VTs, AM, ST->isTruncatingStore(),
7897       ST->isCompressingStore(), ST->getMemoryVT(), ST->getMemOperand());
7898   createOperands(N, Ops);
7899 
7900   CSEMap.InsertNode(N, IP);
7901   InsertNode(N);
7902   SDValue V(N, 0);
7903   NewSDValueDbgMsg(V, "Creating new node: ", this);
7904   return V;
7905 }
7906 
7907 SDValue SelectionDAG::getGatherVP(SDVTList VTs, EVT VT, const SDLoc &dl,
7908                                   ArrayRef<SDValue> Ops, MachineMemOperand *MMO,
7909                                   ISD::MemIndexType IndexType) {
7910   assert(Ops.size() == 6 && "Incompatible number of operands");
7911 
7912   FoldingSetNodeID ID;
7913   AddNodeIDNode(ID, ISD::VP_GATHER, VTs, Ops);
7914   ID.AddInteger(VT.getRawBits());
7915   ID.AddInteger(getSyntheticNodeSubclassData<VPGatherSDNode>(
7916       dl.getIROrder(), VTs, VT, MMO, IndexType));
7917   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7918   void *IP = nullptr;
7919   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7920     cast<VPGatherSDNode>(E)->refineAlignment(MMO);
7921     return SDValue(E, 0);
7922   }
7923 
7924   auto *N = newSDNode<VPGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7925                                       VT, MMO, IndexType);
7926   createOperands(N, Ops);
7927 
7928   assert(N->getMask().getValueType().getVectorElementCount() ==
7929              N->getValueType(0).getVectorElementCount() &&
7930          "Vector width mismatch between mask and data");
7931   assert(N->getIndex().getValueType().getVectorElementCount().isScalable() ==
7932              N->getValueType(0).getVectorElementCount().isScalable() &&
7933          "Scalable flags of index and data do not match");
7934   assert(ElementCount::isKnownGE(
7935              N->getIndex().getValueType().getVectorElementCount(),
7936              N->getValueType(0).getVectorElementCount()) &&
7937          "Vector width mismatch between index and data");
7938   assert(isa<ConstantSDNode>(N->getScale()) &&
7939          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
7940          "Scale should be a constant power of 2");
7941 
7942   CSEMap.InsertNode(N, IP);
7943   InsertNode(N);
7944   SDValue V(N, 0);
7945   NewSDValueDbgMsg(V, "Creating new node: ", this);
7946   return V;
7947 }
7948 
7949 SDValue SelectionDAG::getScatterVP(SDVTList VTs, EVT VT, const SDLoc &dl,
7950                                    ArrayRef<SDValue> Ops,
7951                                    MachineMemOperand *MMO,
7952                                    ISD::MemIndexType IndexType) {
7953   assert(Ops.size() == 7 && "Incompatible number of operands");
7954 
7955   FoldingSetNodeID ID;
7956   AddNodeIDNode(ID, ISD::VP_SCATTER, VTs, Ops);
7957   ID.AddInteger(VT.getRawBits());
7958   ID.AddInteger(getSyntheticNodeSubclassData<VPScatterSDNode>(
7959       dl.getIROrder(), VTs, VT, MMO, IndexType));
7960   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7961   void *IP = nullptr;
7962   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7963     cast<VPScatterSDNode>(E)->refineAlignment(MMO);
7964     return SDValue(E, 0);
7965   }
7966   auto *N = newSDNode<VPScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7967                                        VT, MMO, IndexType);
7968   createOperands(N, Ops);
7969 
7970   assert(N->getMask().getValueType().getVectorElementCount() ==
7971              N->getValue().getValueType().getVectorElementCount() &&
7972          "Vector width mismatch between mask and data");
7973   assert(
7974       N->getIndex().getValueType().getVectorElementCount().isScalable() ==
7975           N->getValue().getValueType().getVectorElementCount().isScalable() &&
7976       "Scalable flags of index and data do not match");
7977   assert(ElementCount::isKnownGE(
7978              N->getIndex().getValueType().getVectorElementCount(),
7979              N->getValue().getValueType().getVectorElementCount()) &&
7980          "Vector width mismatch between index and data");
7981   assert(isa<ConstantSDNode>(N->getScale()) &&
7982          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
7983          "Scale should be a constant power of 2");
7984 
7985   CSEMap.InsertNode(N, IP);
7986   InsertNode(N);
7987   SDValue V(N, 0);
7988   NewSDValueDbgMsg(V, "Creating new node: ", this);
7989   return V;
7990 }
7991 
7992 SDValue SelectionDAG::getMaskedLoad(EVT VT, const SDLoc &dl, SDValue Chain,
7993                                     SDValue Base, SDValue Offset, SDValue Mask,
7994                                     SDValue PassThru, EVT MemVT,
7995                                     MachineMemOperand *MMO,
7996                                     ISD::MemIndexedMode AM,
7997                                     ISD::LoadExtType ExtTy, bool isExpanding) {
7998   bool Indexed = AM != ISD::UNINDEXED;
7999   assert((Indexed || Offset.isUndef()) &&
8000          "Unindexed masked load with an offset!");
8001   SDVTList VTs = Indexed ? getVTList(VT, Base.getValueType(), MVT::Other)
8002                          : getVTList(VT, MVT::Other);
8003   SDValue Ops[] = {Chain, Base, Offset, Mask, PassThru};
8004   FoldingSetNodeID ID;
8005   AddNodeIDNode(ID, ISD::MLOAD, VTs, Ops);
8006   ID.AddInteger(MemVT.getRawBits());
8007   ID.AddInteger(getSyntheticNodeSubclassData<MaskedLoadSDNode>(
8008       dl.getIROrder(), VTs, AM, ExtTy, isExpanding, MemVT, MMO));
8009   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8010   void *IP = nullptr;
8011   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8012     cast<MaskedLoadSDNode>(E)->refineAlignment(MMO);
8013     return SDValue(E, 0);
8014   }
8015   auto *N = newSDNode<MaskedLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
8016                                         AM, ExtTy, isExpanding, MemVT, MMO);
8017   createOperands(N, Ops);
8018 
8019   CSEMap.InsertNode(N, IP);
8020   InsertNode(N);
8021   SDValue V(N, 0);
8022   NewSDValueDbgMsg(V, "Creating new node: ", this);
8023   return V;
8024 }
8025 
8026 SDValue SelectionDAG::getIndexedMaskedLoad(SDValue OrigLoad, const SDLoc &dl,
8027                                            SDValue Base, SDValue Offset,
8028                                            ISD::MemIndexedMode AM) {
8029   MaskedLoadSDNode *LD = cast<MaskedLoadSDNode>(OrigLoad);
8030   assert(LD->getOffset().isUndef() && "Masked load is already a indexed load!");
8031   return getMaskedLoad(OrigLoad.getValueType(), dl, LD->getChain(), Base,
8032                        Offset, LD->getMask(), LD->getPassThru(),
8033                        LD->getMemoryVT(), LD->getMemOperand(), AM,
8034                        LD->getExtensionType(), LD->isExpandingLoad());
8035 }
8036 
8037 SDValue SelectionDAG::getMaskedStore(SDValue Chain, const SDLoc &dl,
8038                                      SDValue Val, SDValue Base, SDValue Offset,
8039                                      SDValue Mask, EVT MemVT,
8040                                      MachineMemOperand *MMO,
8041                                      ISD::MemIndexedMode AM, bool IsTruncating,
8042                                      bool IsCompressing) {
8043   assert(Chain.getValueType() == MVT::Other &&
8044         "Invalid chain type");
8045   bool Indexed = AM != ISD::UNINDEXED;
8046   assert((Indexed || Offset.isUndef()) &&
8047          "Unindexed masked store with an offset!");
8048   SDVTList VTs = Indexed ? getVTList(Base.getValueType(), MVT::Other)
8049                          : getVTList(MVT::Other);
8050   SDValue Ops[] = {Chain, Val, Base, Offset, Mask};
8051   FoldingSetNodeID ID;
8052   AddNodeIDNode(ID, ISD::MSTORE, VTs, Ops);
8053   ID.AddInteger(MemVT.getRawBits());
8054   ID.AddInteger(getSyntheticNodeSubclassData<MaskedStoreSDNode>(
8055       dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
8056   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8057   void *IP = nullptr;
8058   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8059     cast<MaskedStoreSDNode>(E)->refineAlignment(MMO);
8060     return SDValue(E, 0);
8061   }
8062   auto *N =
8063       newSDNode<MaskedStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
8064                                    IsTruncating, IsCompressing, MemVT, MMO);
8065   createOperands(N, Ops);
8066 
8067   CSEMap.InsertNode(N, IP);
8068   InsertNode(N);
8069   SDValue V(N, 0);
8070   NewSDValueDbgMsg(V, "Creating new node: ", this);
8071   return V;
8072 }
8073 
8074 SDValue SelectionDAG::getIndexedMaskedStore(SDValue OrigStore, const SDLoc &dl,
8075                                             SDValue Base, SDValue Offset,
8076                                             ISD::MemIndexedMode AM) {
8077   MaskedStoreSDNode *ST = cast<MaskedStoreSDNode>(OrigStore);
8078   assert(ST->getOffset().isUndef() &&
8079          "Masked store is already a indexed store!");
8080   return getMaskedStore(ST->getChain(), dl, ST->getValue(), Base, Offset,
8081                         ST->getMask(), ST->getMemoryVT(), ST->getMemOperand(),
8082                         AM, ST->isTruncatingStore(), ST->isCompressingStore());
8083 }
8084 
8085 SDValue SelectionDAG::getMaskedGather(SDVTList VTs, EVT MemVT, const SDLoc &dl,
8086                                       ArrayRef<SDValue> Ops,
8087                                       MachineMemOperand *MMO,
8088                                       ISD::MemIndexType IndexType,
8089                                       ISD::LoadExtType ExtTy) {
8090   assert(Ops.size() == 6 && "Incompatible number of operands");
8091 
8092   FoldingSetNodeID ID;
8093   AddNodeIDNode(ID, ISD::MGATHER, VTs, Ops);
8094   ID.AddInteger(MemVT.getRawBits());
8095   ID.AddInteger(getSyntheticNodeSubclassData<MaskedGatherSDNode>(
8096       dl.getIROrder(), VTs, MemVT, MMO, IndexType, ExtTy));
8097   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8098   void *IP = nullptr;
8099   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8100     cast<MaskedGatherSDNode>(E)->refineAlignment(MMO);
8101     return SDValue(E, 0);
8102   }
8103 
8104   IndexType = TLI->getCanonicalIndexType(IndexType, MemVT, Ops[4]);
8105   auto *N = newSDNode<MaskedGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(),
8106                                           VTs, MemVT, MMO, IndexType, ExtTy);
8107   createOperands(N, Ops);
8108 
8109   assert(N->getPassThru().getValueType() == N->getValueType(0) &&
8110          "Incompatible type of the PassThru value in MaskedGatherSDNode");
8111   assert(N->getMask().getValueType().getVectorElementCount() ==
8112              N->getValueType(0).getVectorElementCount() &&
8113          "Vector width mismatch between mask and data");
8114   assert(N->getIndex().getValueType().getVectorElementCount().isScalable() ==
8115              N->getValueType(0).getVectorElementCount().isScalable() &&
8116          "Scalable flags of index and data do not match");
8117   assert(ElementCount::isKnownGE(
8118              N->getIndex().getValueType().getVectorElementCount(),
8119              N->getValueType(0).getVectorElementCount()) &&
8120          "Vector width mismatch between index and data");
8121   assert(isa<ConstantSDNode>(N->getScale()) &&
8122          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
8123          "Scale should be a constant power of 2");
8124 
8125   CSEMap.InsertNode(N, IP);
8126   InsertNode(N);
8127   SDValue V(N, 0);
8128   NewSDValueDbgMsg(V, "Creating new node: ", this);
8129   return V;
8130 }
8131 
8132 SDValue SelectionDAG::getMaskedScatter(SDVTList VTs, EVT MemVT, const SDLoc &dl,
8133                                        ArrayRef<SDValue> Ops,
8134                                        MachineMemOperand *MMO,
8135                                        ISD::MemIndexType IndexType,
8136                                        bool IsTrunc) {
8137   assert(Ops.size() == 6 && "Incompatible number of operands");
8138 
8139   FoldingSetNodeID ID;
8140   AddNodeIDNode(ID, ISD::MSCATTER, VTs, Ops);
8141   ID.AddInteger(MemVT.getRawBits());
8142   ID.AddInteger(getSyntheticNodeSubclassData<MaskedScatterSDNode>(
8143       dl.getIROrder(), VTs, MemVT, MMO, IndexType, IsTrunc));
8144   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8145   void *IP = nullptr;
8146   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8147     cast<MaskedScatterSDNode>(E)->refineAlignment(MMO);
8148     return SDValue(E, 0);
8149   }
8150 
8151   IndexType = TLI->getCanonicalIndexType(IndexType, MemVT, Ops[4]);
8152   auto *N = newSDNode<MaskedScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(),
8153                                            VTs, MemVT, MMO, IndexType, IsTrunc);
8154   createOperands(N, Ops);
8155 
8156   assert(N->getMask().getValueType().getVectorElementCount() ==
8157              N->getValue().getValueType().getVectorElementCount() &&
8158          "Vector width mismatch between mask and data");
8159   assert(
8160       N->getIndex().getValueType().getVectorElementCount().isScalable() ==
8161           N->getValue().getValueType().getVectorElementCount().isScalable() &&
8162       "Scalable flags of index and data do not match");
8163   assert(ElementCount::isKnownGE(
8164              N->getIndex().getValueType().getVectorElementCount(),
8165              N->getValue().getValueType().getVectorElementCount()) &&
8166          "Vector width mismatch between index and data");
8167   assert(isa<ConstantSDNode>(N->getScale()) &&
8168          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
8169          "Scale should be a constant power of 2");
8170 
8171   CSEMap.InsertNode(N, IP);
8172   InsertNode(N);
8173   SDValue V(N, 0);
8174   NewSDValueDbgMsg(V, "Creating new node: ", this);
8175   return V;
8176 }
8177 
8178 SDValue SelectionDAG::simplifySelect(SDValue Cond, SDValue T, SDValue F) {
8179   // select undef, T, F --> T (if T is a constant), otherwise F
8180   // select, ?, undef, F --> F
8181   // select, ?, T, undef --> T
8182   if (Cond.isUndef())
8183     return isConstantValueOfAnyType(T) ? T : F;
8184   if (T.isUndef())
8185     return F;
8186   if (F.isUndef())
8187     return T;
8188 
8189   // select true, T, F --> T
8190   // select false, T, F --> F
8191   if (auto *CondC = dyn_cast<ConstantSDNode>(Cond))
8192     return CondC->isZero() ? F : T;
8193 
8194   // TODO: This should simplify VSELECT with constant condition using something
8195   // like this (but check boolean contents to be complete?):
8196   //  if (ISD::isBuildVectorAllOnes(Cond.getNode()))
8197   //    return T;
8198   //  if (ISD::isBuildVectorAllZeros(Cond.getNode()))
8199   //    return F;
8200 
8201   // select ?, T, T --> T
8202   if (T == F)
8203     return T;
8204 
8205   return SDValue();
8206 }
8207 
8208 SDValue SelectionDAG::simplifyShift(SDValue X, SDValue Y) {
8209   // shift undef, Y --> 0 (can always assume that the undef value is 0)
8210   if (X.isUndef())
8211     return getConstant(0, SDLoc(X.getNode()), X.getValueType());
8212   // shift X, undef --> undef (because it may shift by the bitwidth)
8213   if (Y.isUndef())
8214     return getUNDEF(X.getValueType());
8215 
8216   // shift 0, Y --> 0
8217   // shift X, 0 --> X
8218   if (isNullOrNullSplat(X) || isNullOrNullSplat(Y))
8219     return X;
8220 
8221   // shift X, C >= bitwidth(X) --> undef
8222   // All vector elements must be too big (or undef) to avoid partial undefs.
8223   auto isShiftTooBig = [X](ConstantSDNode *Val) {
8224     return !Val || Val->getAPIntValue().uge(X.getScalarValueSizeInBits());
8225   };
8226   if (ISD::matchUnaryPredicate(Y, isShiftTooBig, true))
8227     return getUNDEF(X.getValueType());
8228 
8229   return SDValue();
8230 }
8231 
8232 SDValue SelectionDAG::simplifyFPBinop(unsigned Opcode, SDValue X, SDValue Y,
8233                                       SDNodeFlags Flags) {
8234   // If this operation has 'nnan' or 'ninf' and at least 1 disallowed operand
8235   // (an undef operand can be chosen to be Nan/Inf), then the result of this
8236   // operation is poison. That result can be relaxed to undef.
8237   ConstantFPSDNode *XC = isConstOrConstSplatFP(X, /* AllowUndefs */ true);
8238   ConstantFPSDNode *YC = isConstOrConstSplatFP(Y, /* AllowUndefs */ true);
8239   bool HasNan = (XC && XC->getValueAPF().isNaN()) ||
8240                 (YC && YC->getValueAPF().isNaN());
8241   bool HasInf = (XC && XC->getValueAPF().isInfinity()) ||
8242                 (YC && YC->getValueAPF().isInfinity());
8243 
8244   if (Flags.hasNoNaNs() && (HasNan || X.isUndef() || Y.isUndef()))
8245     return getUNDEF(X.getValueType());
8246 
8247   if (Flags.hasNoInfs() && (HasInf || X.isUndef() || Y.isUndef()))
8248     return getUNDEF(X.getValueType());
8249 
8250   if (!YC)
8251     return SDValue();
8252 
8253   // X + -0.0 --> X
8254   if (Opcode == ISD::FADD)
8255     if (YC->getValueAPF().isNegZero())
8256       return X;
8257 
8258   // X - +0.0 --> X
8259   if (Opcode == ISD::FSUB)
8260     if (YC->getValueAPF().isPosZero())
8261       return X;
8262 
8263   // X * 1.0 --> X
8264   // X / 1.0 --> X
8265   if (Opcode == ISD::FMUL || Opcode == ISD::FDIV)
8266     if (YC->getValueAPF().isExactlyValue(1.0))
8267       return X;
8268 
8269   // X * 0.0 --> 0.0
8270   if (Opcode == ISD::FMUL && Flags.hasNoNaNs() && Flags.hasNoSignedZeros())
8271     if (YC->getValueAPF().isZero())
8272       return getConstantFP(0.0, SDLoc(Y), Y.getValueType());
8273 
8274   return SDValue();
8275 }
8276 
8277 SDValue SelectionDAG::getVAArg(EVT VT, const SDLoc &dl, SDValue Chain,
8278                                SDValue Ptr, SDValue SV, unsigned Align) {
8279   SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, dl, MVT::i32) };
8280   return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops);
8281 }
8282 
8283 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8284                               ArrayRef<SDUse> Ops) {
8285   switch (Ops.size()) {
8286   case 0: return getNode(Opcode, DL, VT);
8287   case 1: return getNode(Opcode, DL, VT, static_cast<const SDValue>(Ops[0]));
8288   case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
8289   case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
8290   default: break;
8291   }
8292 
8293   // Copy from an SDUse array into an SDValue array for use with
8294   // the regular getNode logic.
8295   SmallVector<SDValue, 8> NewOps(Ops.begin(), Ops.end());
8296   return getNode(Opcode, DL, VT, NewOps);
8297 }
8298 
8299 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8300                               ArrayRef<SDValue> Ops) {
8301   SDNodeFlags Flags;
8302   if (Inserter)
8303     Flags = Inserter->getFlags();
8304   return getNode(Opcode, DL, VT, Ops, Flags);
8305 }
8306 
8307 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8308                               ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
8309   unsigned NumOps = Ops.size();
8310   switch (NumOps) {
8311   case 0: return getNode(Opcode, DL, VT);
8312   case 1: return getNode(Opcode, DL, VT, Ops[0], Flags);
8313   case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Flags);
8314   case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2], Flags);
8315   default: break;
8316   }
8317 
8318 #ifndef NDEBUG
8319   for (auto &Op : Ops)
8320     assert(Op.getOpcode() != ISD::DELETED_NODE &&
8321            "Operand is DELETED_NODE!");
8322 #endif
8323 
8324   switch (Opcode) {
8325   default: break;
8326   case ISD::BUILD_VECTOR:
8327     // Attempt to simplify BUILD_VECTOR.
8328     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
8329       return V;
8330     break;
8331   case ISD::CONCAT_VECTORS:
8332     if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
8333       return V;
8334     break;
8335   case ISD::SELECT_CC:
8336     assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
8337     assert(Ops[0].getValueType() == Ops[1].getValueType() &&
8338            "LHS and RHS of condition must have same type!");
8339     assert(Ops[2].getValueType() == Ops[3].getValueType() &&
8340            "True and False arms of SelectCC must have same type!");
8341     assert(Ops[2].getValueType() == VT &&
8342            "select_cc node must be of same type as true and false value!");
8343     break;
8344   case ISD::BR_CC:
8345     assert(NumOps == 5 && "BR_CC takes 5 operands!");
8346     assert(Ops[2].getValueType() == Ops[3].getValueType() &&
8347            "LHS/RHS of comparison should match types!");
8348     break;
8349   }
8350 
8351   // Memoize nodes.
8352   SDNode *N;
8353   SDVTList VTs = getVTList(VT);
8354 
8355   if (VT != MVT::Glue) {
8356     FoldingSetNodeID ID;
8357     AddNodeIDNode(ID, Opcode, VTs, Ops);
8358     void *IP = nullptr;
8359 
8360     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
8361       return SDValue(E, 0);
8362 
8363     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
8364     createOperands(N, Ops);
8365 
8366     CSEMap.InsertNode(N, IP);
8367   } else {
8368     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
8369     createOperands(N, Ops);
8370   }
8371 
8372   N->setFlags(Flags);
8373   InsertNode(N);
8374   SDValue V(N, 0);
8375   NewSDValueDbgMsg(V, "Creating new node: ", this);
8376   return V;
8377 }
8378 
8379 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
8380                               ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) {
8381   return getNode(Opcode, DL, getVTList(ResultTys), Ops);
8382 }
8383 
8384 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8385                               ArrayRef<SDValue> Ops) {
8386   SDNodeFlags Flags;
8387   if (Inserter)
8388     Flags = Inserter->getFlags();
8389   return getNode(Opcode, DL, VTList, Ops, Flags);
8390 }
8391 
8392 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8393                               ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
8394   if (VTList.NumVTs == 1)
8395     return getNode(Opcode, DL, VTList.VTs[0], Ops);
8396 
8397 #ifndef NDEBUG
8398   for (auto &Op : Ops)
8399     assert(Op.getOpcode() != ISD::DELETED_NODE &&
8400            "Operand is DELETED_NODE!");
8401 #endif
8402 
8403   switch (Opcode) {
8404   case ISD::STRICT_FP_EXTEND:
8405     assert(VTList.NumVTs == 2 && Ops.size() == 2 &&
8406            "Invalid STRICT_FP_EXTEND!");
8407     assert(VTList.VTs[0].isFloatingPoint() &&
8408            Ops[1].getValueType().isFloatingPoint() && "Invalid FP cast!");
8409     assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
8410            "STRICT_FP_EXTEND result type should be vector iff the operand "
8411            "type is vector!");
8412     assert((!VTList.VTs[0].isVector() ||
8413             VTList.VTs[0].getVectorNumElements() ==
8414             Ops[1].getValueType().getVectorNumElements()) &&
8415            "Vector element count mismatch!");
8416     assert(Ops[1].getValueType().bitsLT(VTList.VTs[0]) &&
8417            "Invalid fpext node, dst <= src!");
8418     break;
8419   case ISD::STRICT_FP_ROUND:
8420     assert(VTList.NumVTs == 2 && Ops.size() == 3 && "Invalid STRICT_FP_ROUND!");
8421     assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
8422            "STRICT_FP_ROUND result type should be vector iff the operand "
8423            "type is vector!");
8424     assert((!VTList.VTs[0].isVector() ||
8425             VTList.VTs[0].getVectorNumElements() ==
8426             Ops[1].getValueType().getVectorNumElements()) &&
8427            "Vector element count mismatch!");
8428     assert(VTList.VTs[0].isFloatingPoint() &&
8429            Ops[1].getValueType().isFloatingPoint() &&
8430            VTList.VTs[0].bitsLT(Ops[1].getValueType()) &&
8431            isa<ConstantSDNode>(Ops[2]) &&
8432            (cast<ConstantSDNode>(Ops[2])->getZExtValue() == 0 ||
8433             cast<ConstantSDNode>(Ops[2])->getZExtValue() == 1) &&
8434            "Invalid STRICT_FP_ROUND!");
8435     break;
8436 #if 0
8437   // FIXME: figure out how to safely handle things like
8438   // int foo(int x) { return 1 << (x & 255); }
8439   // int bar() { return foo(256); }
8440   case ISD::SRA_PARTS:
8441   case ISD::SRL_PARTS:
8442   case ISD::SHL_PARTS:
8443     if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
8444         cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
8445       return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
8446     else if (N3.getOpcode() == ISD::AND)
8447       if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
8448         // If the and is only masking out bits that cannot effect the shift,
8449         // eliminate the and.
8450         unsigned NumBits = VT.getScalarSizeInBits()*2;
8451         if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
8452           return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
8453       }
8454     break;
8455 #endif
8456   }
8457 
8458   // Memoize the node unless it returns a flag.
8459   SDNode *N;
8460   if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
8461     FoldingSetNodeID ID;
8462     AddNodeIDNode(ID, Opcode, VTList, Ops);
8463     void *IP = nullptr;
8464     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
8465       return SDValue(E, 0);
8466 
8467     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
8468     createOperands(N, Ops);
8469     CSEMap.InsertNode(N, IP);
8470   } else {
8471     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
8472     createOperands(N, Ops);
8473   }
8474 
8475   N->setFlags(Flags);
8476   InsertNode(N);
8477   SDValue V(N, 0);
8478   NewSDValueDbgMsg(V, "Creating new node: ", this);
8479   return V;
8480 }
8481 
8482 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
8483                               SDVTList VTList) {
8484   return getNode(Opcode, DL, VTList, None);
8485 }
8486 
8487 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8488                               SDValue N1) {
8489   SDValue Ops[] = { N1 };
8490   return getNode(Opcode, DL, VTList, Ops);
8491 }
8492 
8493 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8494                               SDValue N1, SDValue N2) {
8495   SDValue Ops[] = { N1, N2 };
8496   return getNode(Opcode, DL, VTList, Ops);
8497 }
8498 
8499 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8500                               SDValue N1, SDValue N2, SDValue N3) {
8501   SDValue Ops[] = { N1, N2, N3 };
8502   return getNode(Opcode, DL, VTList, Ops);
8503 }
8504 
8505 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8506                               SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
8507   SDValue Ops[] = { N1, N2, N3, N4 };
8508   return getNode(Opcode, DL, VTList, Ops);
8509 }
8510 
8511 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8512                               SDValue N1, SDValue N2, SDValue N3, SDValue N4,
8513                               SDValue N5) {
8514   SDValue Ops[] = { N1, N2, N3, N4, N5 };
8515   return getNode(Opcode, DL, VTList, Ops);
8516 }
8517 
8518 SDVTList SelectionDAG::getVTList(EVT VT) {
8519   return makeVTList(SDNode::getValueTypeList(VT), 1);
8520 }
8521 
8522 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2) {
8523   FoldingSetNodeID ID;
8524   ID.AddInteger(2U);
8525   ID.AddInteger(VT1.getRawBits());
8526   ID.AddInteger(VT2.getRawBits());
8527 
8528   void *IP = nullptr;
8529   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
8530   if (!Result) {
8531     EVT *Array = Allocator.Allocate<EVT>(2);
8532     Array[0] = VT1;
8533     Array[1] = VT2;
8534     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 2);
8535     VTListMap.InsertNode(Result, IP);
8536   }
8537   return Result->getSDVTList();
8538 }
8539 
8540 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3) {
8541   FoldingSetNodeID ID;
8542   ID.AddInteger(3U);
8543   ID.AddInteger(VT1.getRawBits());
8544   ID.AddInteger(VT2.getRawBits());
8545   ID.AddInteger(VT3.getRawBits());
8546 
8547   void *IP = nullptr;
8548   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
8549   if (!Result) {
8550     EVT *Array = Allocator.Allocate<EVT>(3);
8551     Array[0] = VT1;
8552     Array[1] = VT2;
8553     Array[2] = VT3;
8554     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 3);
8555     VTListMap.InsertNode(Result, IP);
8556   }
8557   return Result->getSDVTList();
8558 }
8559 
8560 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4) {
8561   FoldingSetNodeID ID;
8562   ID.AddInteger(4U);
8563   ID.AddInteger(VT1.getRawBits());
8564   ID.AddInteger(VT2.getRawBits());
8565   ID.AddInteger(VT3.getRawBits());
8566   ID.AddInteger(VT4.getRawBits());
8567 
8568   void *IP = nullptr;
8569   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
8570   if (!Result) {
8571     EVT *Array = Allocator.Allocate<EVT>(4);
8572     Array[0] = VT1;
8573     Array[1] = VT2;
8574     Array[2] = VT3;
8575     Array[3] = VT4;
8576     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 4);
8577     VTListMap.InsertNode(Result, IP);
8578   }
8579   return Result->getSDVTList();
8580 }
8581 
8582 SDVTList SelectionDAG::getVTList(ArrayRef<EVT> VTs) {
8583   unsigned NumVTs = VTs.size();
8584   FoldingSetNodeID ID;
8585   ID.AddInteger(NumVTs);
8586   for (unsigned index = 0; index < NumVTs; index++) {
8587     ID.AddInteger(VTs[index].getRawBits());
8588   }
8589 
8590   void *IP = nullptr;
8591   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
8592   if (!Result) {
8593     EVT *Array = Allocator.Allocate<EVT>(NumVTs);
8594     llvm::copy(VTs, Array);
8595     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, NumVTs);
8596     VTListMap.InsertNode(Result, IP);
8597   }
8598   return Result->getSDVTList();
8599 }
8600 
8601 
8602 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
8603 /// specified operands.  If the resultant node already exists in the DAG,
8604 /// this does not modify the specified node, instead it returns the node that
8605 /// already exists.  If the resultant node does not exist in the DAG, the
8606 /// input node is returned.  As a degenerate case, if you specify the same
8607 /// input operands as the node already has, the input node is returned.
8608 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op) {
8609   assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
8610 
8611   // Check to see if there is no change.
8612   if (Op == N->getOperand(0)) return N;
8613 
8614   // See if the modified node already exists.
8615   void *InsertPos = nullptr;
8616   if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
8617     return Existing;
8618 
8619   // Nope it doesn't.  Remove the node from its current place in the maps.
8620   if (InsertPos)
8621     if (!RemoveNodeFromCSEMaps(N))
8622       InsertPos = nullptr;
8623 
8624   // Now we update the operands.
8625   N->OperandList[0].set(Op);
8626 
8627   updateDivergence(N);
8628   // If this gets put into a CSE map, add it.
8629   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
8630   return N;
8631 }
8632 
8633 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2) {
8634   assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
8635 
8636   // Check to see if there is no change.
8637   if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
8638     return N;   // No operands changed, just return the input node.
8639 
8640   // See if the modified node already exists.
8641   void *InsertPos = nullptr;
8642   if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
8643     return Existing;
8644 
8645   // Nope it doesn't.  Remove the node from its current place in the maps.
8646   if (InsertPos)
8647     if (!RemoveNodeFromCSEMaps(N))
8648       InsertPos = nullptr;
8649 
8650   // Now we update the operands.
8651   if (N->OperandList[0] != Op1)
8652     N->OperandList[0].set(Op1);
8653   if (N->OperandList[1] != Op2)
8654     N->OperandList[1].set(Op2);
8655 
8656   updateDivergence(N);
8657   // If this gets put into a CSE map, add it.
8658   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
8659   return N;
8660 }
8661 
8662 SDNode *SelectionDAG::
8663 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, SDValue Op3) {
8664   SDValue Ops[] = { Op1, Op2, Op3 };
8665   return UpdateNodeOperands(N, Ops);
8666 }
8667 
8668 SDNode *SelectionDAG::
8669 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
8670                    SDValue Op3, SDValue Op4) {
8671   SDValue Ops[] = { Op1, Op2, Op3, Op4 };
8672   return UpdateNodeOperands(N, Ops);
8673 }
8674 
8675 SDNode *SelectionDAG::
8676 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
8677                    SDValue Op3, SDValue Op4, SDValue Op5) {
8678   SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 };
8679   return UpdateNodeOperands(N, Ops);
8680 }
8681 
8682 SDNode *SelectionDAG::
8683 UpdateNodeOperands(SDNode *N, ArrayRef<SDValue> Ops) {
8684   unsigned NumOps = Ops.size();
8685   assert(N->getNumOperands() == NumOps &&
8686          "Update with wrong number of operands");
8687 
8688   // If no operands changed just return the input node.
8689   if (std::equal(Ops.begin(), Ops.end(), N->op_begin()))
8690     return N;
8691 
8692   // See if the modified node already exists.
8693   void *InsertPos = nullptr;
8694   if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertPos))
8695     return Existing;
8696 
8697   // Nope it doesn't.  Remove the node from its current place in the maps.
8698   if (InsertPos)
8699     if (!RemoveNodeFromCSEMaps(N))
8700       InsertPos = nullptr;
8701 
8702   // Now we update the operands.
8703   for (unsigned i = 0; i != NumOps; ++i)
8704     if (N->OperandList[i] != Ops[i])
8705       N->OperandList[i].set(Ops[i]);
8706 
8707   updateDivergence(N);
8708   // If this gets put into a CSE map, add it.
8709   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
8710   return N;
8711 }
8712 
8713 /// DropOperands - Release the operands and set this node to have
8714 /// zero operands.
8715 void SDNode::DropOperands() {
8716   // Unlike the code in MorphNodeTo that does this, we don't need to
8717   // watch for dead nodes here.
8718   for (op_iterator I = op_begin(), E = op_end(); I != E; ) {
8719     SDUse &Use = *I++;
8720     Use.set(SDValue());
8721   }
8722 }
8723 
8724 void SelectionDAG::setNodeMemRefs(MachineSDNode *N,
8725                                   ArrayRef<MachineMemOperand *> NewMemRefs) {
8726   if (NewMemRefs.empty()) {
8727     N->clearMemRefs();
8728     return;
8729   }
8730 
8731   // Check if we can avoid allocating by storing a single reference directly.
8732   if (NewMemRefs.size() == 1) {
8733     N->MemRefs = NewMemRefs[0];
8734     N->NumMemRefs = 1;
8735     return;
8736   }
8737 
8738   MachineMemOperand **MemRefsBuffer =
8739       Allocator.template Allocate<MachineMemOperand *>(NewMemRefs.size());
8740   llvm::copy(NewMemRefs, MemRefsBuffer);
8741   N->MemRefs = MemRefsBuffer;
8742   N->NumMemRefs = static_cast<int>(NewMemRefs.size());
8743 }
8744 
8745 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a
8746 /// machine opcode.
8747 ///
8748 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8749                                    EVT VT) {
8750   SDVTList VTs = getVTList(VT);
8751   return SelectNodeTo(N, MachineOpc, VTs, None);
8752 }
8753 
8754 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8755                                    EVT VT, SDValue Op1) {
8756   SDVTList VTs = getVTList(VT);
8757   SDValue Ops[] = { Op1 };
8758   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8759 }
8760 
8761 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8762                                    EVT VT, SDValue Op1,
8763                                    SDValue Op2) {
8764   SDVTList VTs = getVTList(VT);
8765   SDValue Ops[] = { Op1, Op2 };
8766   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8767 }
8768 
8769 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8770                                    EVT VT, SDValue Op1,
8771                                    SDValue Op2, SDValue Op3) {
8772   SDVTList VTs = getVTList(VT);
8773   SDValue Ops[] = { Op1, Op2, Op3 };
8774   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8775 }
8776 
8777 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8778                                    EVT VT, ArrayRef<SDValue> Ops) {
8779   SDVTList VTs = getVTList(VT);
8780   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8781 }
8782 
8783 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8784                                    EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) {
8785   SDVTList VTs = getVTList(VT1, VT2);
8786   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8787 }
8788 
8789 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8790                                    EVT VT1, EVT VT2) {
8791   SDVTList VTs = getVTList(VT1, VT2);
8792   return SelectNodeTo(N, MachineOpc, VTs, None);
8793 }
8794 
8795 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8796                                    EVT VT1, EVT VT2, EVT VT3,
8797                                    ArrayRef<SDValue> Ops) {
8798   SDVTList VTs = getVTList(VT1, VT2, VT3);
8799   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8800 }
8801 
8802 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8803                                    EVT VT1, EVT VT2,
8804                                    SDValue Op1, SDValue Op2) {
8805   SDVTList VTs = getVTList(VT1, VT2);
8806   SDValue Ops[] = { Op1, Op2 };
8807   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8808 }
8809 
8810 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8811                                    SDVTList VTs,ArrayRef<SDValue> Ops) {
8812   SDNode *New = MorphNodeTo(N, ~MachineOpc, VTs, Ops);
8813   // Reset the NodeID to -1.
8814   New->setNodeId(-1);
8815   if (New != N) {
8816     ReplaceAllUsesWith(N, New);
8817     RemoveDeadNode(N);
8818   }
8819   return New;
8820 }
8821 
8822 /// UpdateSDLocOnMergeSDNode - If the opt level is -O0 then it throws away
8823 /// the line number information on the merged node since it is not possible to
8824 /// preserve the information that operation is associated with multiple lines.
8825 /// This will make the debugger working better at -O0, were there is a higher
8826 /// probability having other instructions associated with that line.
8827 ///
8828 /// For IROrder, we keep the smaller of the two
8829 SDNode *SelectionDAG::UpdateSDLocOnMergeSDNode(SDNode *N, const SDLoc &OLoc) {
8830   DebugLoc NLoc = N->getDebugLoc();
8831   if (NLoc && OptLevel == CodeGenOpt::None && OLoc.getDebugLoc() != NLoc) {
8832     N->setDebugLoc(DebugLoc());
8833   }
8834   unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder());
8835   N->setIROrder(Order);
8836   return N;
8837 }
8838 
8839 /// MorphNodeTo - This *mutates* the specified node to have the specified
8840 /// return type, opcode, and operands.
8841 ///
8842 /// Note that MorphNodeTo returns the resultant node.  If there is already a
8843 /// node of the specified opcode and operands, it returns that node instead of
8844 /// the current one.  Note that the SDLoc need not be the same.
8845 ///
8846 /// Using MorphNodeTo is faster than creating a new node and swapping it in
8847 /// with ReplaceAllUsesWith both because it often avoids allocating a new
8848 /// node, and because it doesn't require CSE recalculation for any of
8849 /// the node's users.
8850 ///
8851 /// However, note that MorphNodeTo recursively deletes dead nodes from the DAG.
8852 /// As a consequence it isn't appropriate to use from within the DAG combiner or
8853 /// the legalizer which maintain worklists that would need to be updated when
8854 /// deleting things.
8855 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
8856                                   SDVTList VTs, ArrayRef<SDValue> Ops) {
8857   // If an identical node already exists, use it.
8858   void *IP = nullptr;
8859   if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) {
8860     FoldingSetNodeID ID;
8861     AddNodeIDNode(ID, Opc, VTs, Ops);
8862     if (SDNode *ON = FindNodeOrInsertPos(ID, SDLoc(N), IP))
8863       return UpdateSDLocOnMergeSDNode(ON, SDLoc(N));
8864   }
8865 
8866   if (!RemoveNodeFromCSEMaps(N))
8867     IP = nullptr;
8868 
8869   // Start the morphing.
8870   N->NodeType = Opc;
8871   N->ValueList = VTs.VTs;
8872   N->NumValues = VTs.NumVTs;
8873 
8874   // Clear the operands list, updating used nodes to remove this from their
8875   // use list.  Keep track of any operands that become dead as a result.
8876   SmallPtrSet<SDNode*, 16> DeadNodeSet;
8877   for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
8878     SDUse &Use = *I++;
8879     SDNode *Used = Use.getNode();
8880     Use.set(SDValue());
8881     if (Used->use_empty())
8882       DeadNodeSet.insert(Used);
8883   }
8884 
8885   // For MachineNode, initialize the memory references information.
8886   if (MachineSDNode *MN = dyn_cast<MachineSDNode>(N))
8887     MN->clearMemRefs();
8888 
8889   // Swap for an appropriately sized array from the recycler.
8890   removeOperands(N);
8891   createOperands(N, Ops);
8892 
8893   // Delete any nodes that are still dead after adding the uses for the
8894   // new operands.
8895   if (!DeadNodeSet.empty()) {
8896     SmallVector<SDNode *, 16> DeadNodes;
8897     for (SDNode *N : DeadNodeSet)
8898       if (N->use_empty())
8899         DeadNodes.push_back(N);
8900     RemoveDeadNodes(DeadNodes);
8901   }
8902 
8903   if (IP)
8904     CSEMap.InsertNode(N, IP);   // Memoize the new node.
8905   return N;
8906 }
8907 
8908 SDNode* SelectionDAG::mutateStrictFPToFP(SDNode *Node) {
8909   unsigned OrigOpc = Node->getOpcode();
8910   unsigned NewOpc;
8911   switch (OrigOpc) {
8912   default:
8913     llvm_unreachable("mutateStrictFPToFP called with unexpected opcode!");
8914 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
8915   case ISD::STRICT_##DAGN: NewOpc = ISD::DAGN; break;
8916 #define CMP_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
8917   case ISD::STRICT_##DAGN: NewOpc = ISD::SETCC; break;
8918 #include "llvm/IR/ConstrainedOps.def"
8919   }
8920 
8921   assert(Node->getNumValues() == 2 && "Unexpected number of results!");
8922 
8923   // We're taking this node out of the chain, so we need to re-link things.
8924   SDValue InputChain = Node->getOperand(0);
8925   SDValue OutputChain = SDValue(Node, 1);
8926   ReplaceAllUsesOfValueWith(OutputChain, InputChain);
8927 
8928   SmallVector<SDValue, 3> Ops;
8929   for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
8930     Ops.push_back(Node->getOperand(i));
8931 
8932   SDVTList VTs = getVTList(Node->getValueType(0));
8933   SDNode *Res = MorphNodeTo(Node, NewOpc, VTs, Ops);
8934 
8935   // MorphNodeTo can operate in two ways: if an existing node with the
8936   // specified operands exists, it can just return it.  Otherwise, it
8937   // updates the node in place to have the requested operands.
8938   if (Res == Node) {
8939     // If we updated the node in place, reset the node ID.  To the isel,
8940     // this should be just like a newly allocated machine node.
8941     Res->setNodeId(-1);
8942   } else {
8943     ReplaceAllUsesWith(Node, Res);
8944     RemoveDeadNode(Node);
8945   }
8946 
8947   return Res;
8948 }
8949 
8950 /// getMachineNode - These are used for target selectors to create a new node
8951 /// with specified return type(s), MachineInstr opcode, and operands.
8952 ///
8953 /// Note that getMachineNode returns the resultant node.  If there is already a
8954 /// node of the specified opcode and operands, it returns that node instead of
8955 /// the current one.
8956 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8957                                             EVT VT) {
8958   SDVTList VTs = getVTList(VT);
8959   return getMachineNode(Opcode, dl, VTs, None);
8960 }
8961 
8962 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8963                                             EVT VT, SDValue Op1) {
8964   SDVTList VTs = getVTList(VT);
8965   SDValue Ops[] = { Op1 };
8966   return getMachineNode(Opcode, dl, VTs, Ops);
8967 }
8968 
8969 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8970                                             EVT VT, SDValue Op1, SDValue Op2) {
8971   SDVTList VTs = getVTList(VT);
8972   SDValue Ops[] = { Op1, Op2 };
8973   return getMachineNode(Opcode, dl, VTs, Ops);
8974 }
8975 
8976 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8977                                             EVT VT, SDValue Op1, SDValue Op2,
8978                                             SDValue Op3) {
8979   SDVTList VTs = getVTList(VT);
8980   SDValue Ops[] = { Op1, Op2, Op3 };
8981   return getMachineNode(Opcode, dl, VTs, Ops);
8982 }
8983 
8984 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8985                                             EVT VT, ArrayRef<SDValue> Ops) {
8986   SDVTList VTs = getVTList(VT);
8987   return getMachineNode(Opcode, dl, VTs, Ops);
8988 }
8989 
8990 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8991                                             EVT VT1, EVT VT2, SDValue Op1,
8992                                             SDValue Op2) {
8993   SDVTList VTs = getVTList(VT1, VT2);
8994   SDValue Ops[] = { Op1, Op2 };
8995   return getMachineNode(Opcode, dl, VTs, Ops);
8996 }
8997 
8998 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8999                                             EVT VT1, EVT VT2, SDValue Op1,
9000                                             SDValue Op2, SDValue Op3) {
9001   SDVTList VTs = getVTList(VT1, VT2);
9002   SDValue Ops[] = { Op1, Op2, Op3 };
9003   return getMachineNode(Opcode, dl, VTs, Ops);
9004 }
9005 
9006 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9007                                             EVT VT1, EVT VT2,
9008                                             ArrayRef<SDValue> Ops) {
9009   SDVTList VTs = getVTList(VT1, VT2);
9010   return getMachineNode(Opcode, dl, VTs, Ops);
9011 }
9012 
9013 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9014                                             EVT VT1, EVT VT2, EVT VT3,
9015                                             SDValue Op1, SDValue Op2) {
9016   SDVTList VTs = getVTList(VT1, VT2, VT3);
9017   SDValue Ops[] = { Op1, Op2 };
9018   return getMachineNode(Opcode, dl, VTs, Ops);
9019 }
9020 
9021 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9022                                             EVT VT1, EVT VT2, EVT VT3,
9023                                             SDValue Op1, SDValue Op2,
9024                                             SDValue Op3) {
9025   SDVTList VTs = getVTList(VT1, VT2, VT3);
9026   SDValue Ops[] = { Op1, Op2, Op3 };
9027   return getMachineNode(Opcode, dl, VTs, Ops);
9028 }
9029 
9030 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9031                                             EVT VT1, EVT VT2, EVT VT3,
9032                                             ArrayRef<SDValue> Ops) {
9033   SDVTList VTs = getVTList(VT1, VT2, VT3);
9034   return getMachineNode(Opcode, dl, VTs, Ops);
9035 }
9036 
9037 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9038                                             ArrayRef<EVT> ResultTys,
9039                                             ArrayRef<SDValue> Ops) {
9040   SDVTList VTs = getVTList(ResultTys);
9041   return getMachineNode(Opcode, dl, VTs, Ops);
9042 }
9043 
9044 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &DL,
9045                                             SDVTList VTs,
9046                                             ArrayRef<SDValue> Ops) {
9047   bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue;
9048   MachineSDNode *N;
9049   void *IP = nullptr;
9050 
9051   if (DoCSE) {
9052     FoldingSetNodeID ID;
9053     AddNodeIDNode(ID, ~Opcode, VTs, Ops);
9054     IP = nullptr;
9055     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
9056       return cast<MachineSDNode>(UpdateSDLocOnMergeSDNode(E, DL));
9057     }
9058   }
9059 
9060   // Allocate a new MachineSDNode.
9061   N = newSDNode<MachineSDNode>(~Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
9062   createOperands(N, Ops);
9063 
9064   if (DoCSE)
9065     CSEMap.InsertNode(N, IP);
9066 
9067   InsertNode(N);
9068   NewSDValueDbgMsg(SDValue(N, 0), "Creating new machine node: ", this);
9069   return N;
9070 }
9071 
9072 /// getTargetExtractSubreg - A convenience function for creating
9073 /// TargetOpcode::EXTRACT_SUBREG nodes.
9074 SDValue SelectionDAG::getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT,
9075                                              SDValue Operand) {
9076   SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
9077   SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,
9078                                   VT, Operand, SRIdxVal);
9079   return SDValue(Subreg, 0);
9080 }
9081 
9082 /// getTargetInsertSubreg - A convenience function for creating
9083 /// TargetOpcode::INSERT_SUBREG nodes.
9084 SDValue SelectionDAG::getTargetInsertSubreg(int SRIdx, const SDLoc &DL, EVT VT,
9085                                             SDValue Operand, SDValue Subreg) {
9086   SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
9087   SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL,
9088                                   VT, Operand, Subreg, SRIdxVal);
9089   return SDValue(Result, 0);
9090 }
9091 
9092 /// getNodeIfExists - Get the specified node if it's already available, or
9093 /// else return NULL.
9094 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
9095                                       ArrayRef<SDValue> Ops) {
9096   SDNodeFlags Flags;
9097   if (Inserter)
9098     Flags = Inserter->getFlags();
9099   return getNodeIfExists(Opcode, VTList, Ops, Flags);
9100 }
9101 
9102 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
9103                                       ArrayRef<SDValue> Ops,
9104                                       const SDNodeFlags Flags) {
9105   if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
9106     FoldingSetNodeID ID;
9107     AddNodeIDNode(ID, Opcode, VTList, Ops);
9108     void *IP = nullptr;
9109     if (SDNode *E = FindNodeOrInsertPos(ID, SDLoc(), IP)) {
9110       E->intersectFlagsWith(Flags);
9111       return E;
9112     }
9113   }
9114   return nullptr;
9115 }
9116 
9117 /// doesNodeExist - Check if a node exists without modifying its flags.
9118 bool SelectionDAG::doesNodeExist(unsigned Opcode, SDVTList VTList,
9119                                  ArrayRef<SDValue> Ops) {
9120   if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
9121     FoldingSetNodeID ID;
9122     AddNodeIDNode(ID, Opcode, VTList, Ops);
9123     void *IP = nullptr;
9124     if (FindNodeOrInsertPos(ID, SDLoc(), IP))
9125       return true;
9126   }
9127   return false;
9128 }
9129 
9130 /// getDbgValue - Creates a SDDbgValue node.
9131 ///
9132 /// SDNode
9133 SDDbgValue *SelectionDAG::getDbgValue(DIVariable *Var, DIExpression *Expr,
9134                                       SDNode *N, unsigned R, bool IsIndirect,
9135                                       const DebugLoc &DL, unsigned O) {
9136   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9137          "Expected inlined-at fields to agree");
9138   return new (DbgInfo->getAlloc())
9139       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromNode(N, R),
9140                  {}, IsIndirect, DL, O,
9141                  /*IsVariadic=*/false);
9142 }
9143 
9144 /// Constant
9145 SDDbgValue *SelectionDAG::getConstantDbgValue(DIVariable *Var,
9146                                               DIExpression *Expr,
9147                                               const Value *C,
9148                                               const DebugLoc &DL, unsigned O) {
9149   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9150          "Expected inlined-at fields to agree");
9151   return new (DbgInfo->getAlloc())
9152       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromConst(C), {},
9153                  /*IsIndirect=*/false, DL, O,
9154                  /*IsVariadic=*/false);
9155 }
9156 
9157 /// FrameIndex
9158 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var,
9159                                                 DIExpression *Expr, unsigned FI,
9160                                                 bool IsIndirect,
9161                                                 const DebugLoc &DL,
9162                                                 unsigned O) {
9163   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9164          "Expected inlined-at fields to agree");
9165   return getFrameIndexDbgValue(Var, Expr, FI, {}, IsIndirect, DL, O);
9166 }
9167 
9168 /// FrameIndex with dependencies
9169 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var,
9170                                                 DIExpression *Expr, unsigned FI,
9171                                                 ArrayRef<SDNode *> Dependencies,
9172                                                 bool IsIndirect,
9173                                                 const DebugLoc &DL,
9174                                                 unsigned O) {
9175   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9176          "Expected inlined-at fields to agree");
9177   return new (DbgInfo->getAlloc())
9178       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromFrameIdx(FI),
9179                  Dependencies, IsIndirect, DL, O,
9180                  /*IsVariadic=*/false);
9181 }
9182 
9183 /// VReg
9184 SDDbgValue *SelectionDAG::getVRegDbgValue(DIVariable *Var, DIExpression *Expr,
9185                                           unsigned VReg, bool IsIndirect,
9186                                           const DebugLoc &DL, unsigned O) {
9187   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9188          "Expected inlined-at fields to agree");
9189   return new (DbgInfo->getAlloc())
9190       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromVReg(VReg),
9191                  {}, IsIndirect, DL, O,
9192                  /*IsVariadic=*/false);
9193 }
9194 
9195 SDDbgValue *SelectionDAG::getDbgValueList(DIVariable *Var, DIExpression *Expr,
9196                                           ArrayRef<SDDbgOperand> Locs,
9197                                           ArrayRef<SDNode *> Dependencies,
9198                                           bool IsIndirect, const DebugLoc &DL,
9199                                           unsigned O, bool IsVariadic) {
9200   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9201          "Expected inlined-at fields to agree");
9202   return new (DbgInfo->getAlloc())
9203       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, Locs, Dependencies, IsIndirect,
9204                  DL, O, IsVariadic);
9205 }
9206 
9207 void SelectionDAG::transferDbgValues(SDValue From, SDValue To,
9208                                      unsigned OffsetInBits, unsigned SizeInBits,
9209                                      bool InvalidateDbg) {
9210   SDNode *FromNode = From.getNode();
9211   SDNode *ToNode = To.getNode();
9212   assert(FromNode && ToNode && "Can't modify dbg values");
9213 
9214   // PR35338
9215   // TODO: assert(From != To && "Redundant dbg value transfer");
9216   // TODO: assert(FromNode != ToNode && "Intranode dbg value transfer");
9217   if (From == To || FromNode == ToNode)
9218     return;
9219 
9220   if (!FromNode->getHasDebugValue())
9221     return;
9222 
9223   SDDbgOperand FromLocOp =
9224       SDDbgOperand::fromNode(From.getNode(), From.getResNo());
9225   SDDbgOperand ToLocOp = SDDbgOperand::fromNode(To.getNode(), To.getResNo());
9226 
9227   SmallVector<SDDbgValue *, 2> ClonedDVs;
9228   for (SDDbgValue *Dbg : GetDbgValues(FromNode)) {
9229     if (Dbg->isInvalidated())
9230       continue;
9231 
9232     // TODO: assert(!Dbg->isInvalidated() && "Transfer of invalid dbg value");
9233 
9234     // Create a new location ops vector that is equal to the old vector, but
9235     // with each instance of FromLocOp replaced with ToLocOp.
9236     bool Changed = false;
9237     auto NewLocOps = Dbg->copyLocationOps();
9238     std::replace_if(
9239         NewLocOps.begin(), NewLocOps.end(),
9240         [&Changed, FromLocOp](const SDDbgOperand &Op) {
9241           bool Match = Op == FromLocOp;
9242           Changed |= Match;
9243           return Match;
9244         },
9245         ToLocOp);
9246     // Ignore this SDDbgValue if we didn't find a matching location.
9247     if (!Changed)
9248       continue;
9249 
9250     DIVariable *Var = Dbg->getVariable();
9251     auto *Expr = Dbg->getExpression();
9252     // If a fragment is requested, update the expression.
9253     if (SizeInBits) {
9254       // When splitting a larger (e.g., sign-extended) value whose
9255       // lower bits are described with an SDDbgValue, do not attempt
9256       // to transfer the SDDbgValue to the upper bits.
9257       if (auto FI = Expr->getFragmentInfo())
9258         if (OffsetInBits + SizeInBits > FI->SizeInBits)
9259           continue;
9260       auto Fragment = DIExpression::createFragmentExpression(Expr, OffsetInBits,
9261                                                              SizeInBits);
9262       if (!Fragment)
9263         continue;
9264       Expr = *Fragment;
9265     }
9266 
9267     auto AdditionalDependencies = Dbg->getAdditionalDependencies();
9268     // Clone the SDDbgValue and move it to To.
9269     SDDbgValue *Clone = getDbgValueList(
9270         Var, Expr, NewLocOps, AdditionalDependencies, Dbg->isIndirect(),
9271         Dbg->getDebugLoc(), std::max(ToNode->getIROrder(), Dbg->getOrder()),
9272         Dbg->isVariadic());
9273     ClonedDVs.push_back(Clone);
9274 
9275     if (InvalidateDbg) {
9276       // Invalidate value and indicate the SDDbgValue should not be emitted.
9277       Dbg->setIsInvalidated();
9278       Dbg->setIsEmitted();
9279     }
9280   }
9281 
9282   for (SDDbgValue *Dbg : ClonedDVs) {
9283     assert(is_contained(Dbg->getSDNodes(), ToNode) &&
9284            "Transferred DbgValues should depend on the new SDNode");
9285     AddDbgValue(Dbg, false);
9286   }
9287 }
9288 
9289 void SelectionDAG::salvageDebugInfo(SDNode &N) {
9290   if (!N.getHasDebugValue())
9291     return;
9292 
9293   SmallVector<SDDbgValue *, 2> ClonedDVs;
9294   for (auto DV : GetDbgValues(&N)) {
9295     if (DV->isInvalidated())
9296       continue;
9297     switch (N.getOpcode()) {
9298     default:
9299       break;
9300     case ISD::ADD:
9301       SDValue N0 = N.getOperand(0);
9302       SDValue N1 = N.getOperand(1);
9303       if (!isConstantIntBuildVectorOrConstantInt(N0) &&
9304           isConstantIntBuildVectorOrConstantInt(N1)) {
9305         uint64_t Offset = N.getConstantOperandVal(1);
9306 
9307         // Rewrite an ADD constant node into a DIExpression. Since we are
9308         // performing arithmetic to compute the variable's *value* in the
9309         // DIExpression, we need to mark the expression with a
9310         // DW_OP_stack_value.
9311         auto *DIExpr = DV->getExpression();
9312         auto NewLocOps = DV->copyLocationOps();
9313         bool Changed = false;
9314         for (size_t i = 0; i < NewLocOps.size(); ++i) {
9315           // We're not given a ResNo to compare against because the whole
9316           // node is going away. We know that any ISD::ADD only has one
9317           // result, so we can assume any node match is using the result.
9318           if (NewLocOps[i].getKind() != SDDbgOperand::SDNODE ||
9319               NewLocOps[i].getSDNode() != &N)
9320             continue;
9321           NewLocOps[i] = SDDbgOperand::fromNode(N0.getNode(), N0.getResNo());
9322           SmallVector<uint64_t, 3> ExprOps;
9323           DIExpression::appendOffset(ExprOps, Offset);
9324           DIExpr = DIExpression::appendOpsToArg(DIExpr, ExprOps, i, true);
9325           Changed = true;
9326         }
9327         (void)Changed;
9328         assert(Changed && "Salvage target doesn't use N");
9329 
9330         auto AdditionalDependencies = DV->getAdditionalDependencies();
9331         SDDbgValue *Clone = getDbgValueList(DV->getVariable(), DIExpr,
9332                                             NewLocOps, AdditionalDependencies,
9333                                             DV->isIndirect(), DV->getDebugLoc(),
9334                                             DV->getOrder(), DV->isVariadic());
9335         ClonedDVs.push_back(Clone);
9336         DV->setIsInvalidated();
9337         DV->setIsEmitted();
9338         LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting";
9339                    N0.getNode()->dumprFull(this);
9340                    dbgs() << " into " << *DIExpr << '\n');
9341       }
9342     }
9343   }
9344 
9345   for (SDDbgValue *Dbg : ClonedDVs) {
9346     assert(!Dbg->getSDNodes().empty() &&
9347            "Salvaged DbgValue should depend on a new SDNode");
9348     AddDbgValue(Dbg, false);
9349   }
9350 }
9351 
9352 /// Creates a SDDbgLabel node.
9353 SDDbgLabel *SelectionDAG::getDbgLabel(DILabel *Label,
9354                                       const DebugLoc &DL, unsigned O) {
9355   assert(cast<DILabel>(Label)->isValidLocationForIntrinsic(DL) &&
9356          "Expected inlined-at fields to agree");
9357   return new (DbgInfo->getAlloc()) SDDbgLabel(Label, DL, O);
9358 }
9359 
9360 namespace {
9361 
9362 /// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node
9363 /// pointed to by a use iterator is deleted, increment the use iterator
9364 /// so that it doesn't dangle.
9365 ///
9366 class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener {
9367   SDNode::use_iterator &UI;
9368   SDNode::use_iterator &UE;
9369 
9370   void NodeDeleted(SDNode *N, SDNode *E) override {
9371     // Increment the iterator as needed.
9372     while (UI != UE && N == *UI)
9373       ++UI;
9374   }
9375 
9376 public:
9377   RAUWUpdateListener(SelectionDAG &d,
9378                      SDNode::use_iterator &ui,
9379                      SDNode::use_iterator &ue)
9380     : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {}
9381 };
9382 
9383 } // end anonymous namespace
9384 
9385 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
9386 /// This can cause recursive merging of nodes in the DAG.
9387 ///
9388 /// This version assumes From has a single result value.
9389 ///
9390 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To) {
9391   SDNode *From = FromN.getNode();
9392   assert(From->getNumValues() == 1 && FromN.getResNo() == 0 &&
9393          "Cannot replace with this method!");
9394   assert(From != To.getNode() && "Cannot replace uses of with self");
9395 
9396   // Preserve Debug Values
9397   transferDbgValues(FromN, To);
9398 
9399   // Iterate over all the existing uses of From. New uses will be added
9400   // to the beginning of the use list, which we avoid visiting.
9401   // This specifically avoids visiting uses of From that arise while the
9402   // replacement is happening, because any such uses would be the result
9403   // of CSE: If an existing node looks like From after one of its operands
9404   // is replaced by To, we don't want to replace of all its users with To
9405   // too. See PR3018 for more info.
9406   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
9407   RAUWUpdateListener Listener(*this, UI, UE);
9408   while (UI != UE) {
9409     SDNode *User = *UI;
9410 
9411     // This node is about to morph, remove its old self from the CSE maps.
9412     RemoveNodeFromCSEMaps(User);
9413 
9414     // A user can appear in a use list multiple times, and when this
9415     // happens the uses are usually next to each other in the list.
9416     // To help reduce the number of CSE recomputations, process all
9417     // the uses of this user that we can find this way.
9418     do {
9419       SDUse &Use = UI.getUse();
9420       ++UI;
9421       Use.set(To);
9422       if (To->isDivergent() != From->isDivergent())
9423         updateDivergence(User);
9424     } while (UI != UE && *UI == User);
9425     // Now that we have modified User, add it back to the CSE maps.  If it
9426     // already exists there, recursively merge the results together.
9427     AddModifiedNodeToCSEMaps(User);
9428   }
9429 
9430   // If we just RAUW'd the root, take note.
9431   if (FromN == getRoot())
9432     setRoot(To);
9433 }
9434 
9435 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
9436 /// This can cause recursive merging of nodes in the DAG.
9437 ///
9438 /// This version assumes that for each value of From, there is a
9439 /// corresponding value in To in the same position with the same type.
9440 ///
9441 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To) {
9442 #ifndef NDEBUG
9443   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
9444     assert((!From->hasAnyUseOfValue(i) ||
9445             From->getValueType(i) == To->getValueType(i)) &&
9446            "Cannot use this version of ReplaceAllUsesWith!");
9447 #endif
9448 
9449   // Handle the trivial case.
9450   if (From == To)
9451     return;
9452 
9453   // Preserve Debug Info. Only do this if there's a use.
9454   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
9455     if (From->hasAnyUseOfValue(i)) {
9456       assert((i < To->getNumValues()) && "Invalid To location");
9457       transferDbgValues(SDValue(From, i), SDValue(To, i));
9458     }
9459 
9460   // Iterate over just the existing users of From. See the comments in
9461   // the ReplaceAllUsesWith above.
9462   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
9463   RAUWUpdateListener Listener(*this, UI, UE);
9464   while (UI != UE) {
9465     SDNode *User = *UI;
9466 
9467     // This node is about to morph, remove its old self from the CSE maps.
9468     RemoveNodeFromCSEMaps(User);
9469 
9470     // A user can appear in a use list multiple times, and when this
9471     // happens the uses are usually next to each other in the list.
9472     // To help reduce the number of CSE recomputations, process all
9473     // the uses of this user that we can find this way.
9474     do {
9475       SDUse &Use = UI.getUse();
9476       ++UI;
9477       Use.setNode(To);
9478       if (To->isDivergent() != From->isDivergent())
9479         updateDivergence(User);
9480     } while (UI != UE && *UI == User);
9481 
9482     // Now that we have modified User, add it back to the CSE maps.  If it
9483     // already exists there, recursively merge the results together.
9484     AddModifiedNodeToCSEMaps(User);
9485   }
9486 
9487   // If we just RAUW'd the root, take note.
9488   if (From == getRoot().getNode())
9489     setRoot(SDValue(To, getRoot().getResNo()));
9490 }
9491 
9492 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
9493 /// This can cause recursive merging of nodes in the DAG.
9494 ///
9495 /// This version can replace From with any result values.  To must match the
9496 /// number and types of values returned by From.
9497 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, const SDValue *To) {
9498   if (From->getNumValues() == 1)  // Handle the simple case efficiently.
9499     return ReplaceAllUsesWith(SDValue(From, 0), To[0]);
9500 
9501   // Preserve Debug Info.
9502   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
9503     transferDbgValues(SDValue(From, i), To[i]);
9504 
9505   // Iterate over just the existing users of From. See the comments in
9506   // the ReplaceAllUsesWith above.
9507   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
9508   RAUWUpdateListener Listener(*this, UI, UE);
9509   while (UI != UE) {
9510     SDNode *User = *UI;
9511 
9512     // This node is about to morph, remove its old self from the CSE maps.
9513     RemoveNodeFromCSEMaps(User);
9514 
9515     // A user can appear in a use list multiple times, and when this happens the
9516     // uses are usually next to each other in the list.  To help reduce the
9517     // number of CSE and divergence recomputations, process all the uses of this
9518     // user that we can find this way.
9519     bool To_IsDivergent = false;
9520     do {
9521       SDUse &Use = UI.getUse();
9522       const SDValue &ToOp = To[Use.getResNo()];
9523       ++UI;
9524       Use.set(ToOp);
9525       To_IsDivergent |= ToOp->isDivergent();
9526     } while (UI != UE && *UI == User);
9527 
9528     if (To_IsDivergent != From->isDivergent())
9529       updateDivergence(User);
9530 
9531     // Now that we have modified User, add it back to the CSE maps.  If it
9532     // already exists there, recursively merge the results together.
9533     AddModifiedNodeToCSEMaps(User);
9534   }
9535 
9536   // If we just RAUW'd the root, take note.
9537   if (From == getRoot().getNode())
9538     setRoot(SDValue(To[getRoot().getResNo()]));
9539 }
9540 
9541 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
9542 /// uses of other values produced by From.getNode() alone.  The Deleted
9543 /// vector is handled the same way as for ReplaceAllUsesWith.
9544 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To){
9545   // Handle the really simple, really trivial case efficiently.
9546   if (From == To) return;
9547 
9548   // Handle the simple, trivial, case efficiently.
9549   if (From.getNode()->getNumValues() == 1) {
9550     ReplaceAllUsesWith(From, To);
9551     return;
9552   }
9553 
9554   // Preserve Debug Info.
9555   transferDbgValues(From, To);
9556 
9557   // Iterate over just the existing users of From. See the comments in
9558   // the ReplaceAllUsesWith above.
9559   SDNode::use_iterator UI = From.getNode()->use_begin(),
9560                        UE = From.getNode()->use_end();
9561   RAUWUpdateListener Listener(*this, UI, UE);
9562   while (UI != UE) {
9563     SDNode *User = *UI;
9564     bool UserRemovedFromCSEMaps = false;
9565 
9566     // A user can appear in a use list multiple times, and when this
9567     // happens the uses are usually next to each other in the list.
9568     // To help reduce the number of CSE recomputations, process all
9569     // the uses of this user that we can find this way.
9570     do {
9571       SDUse &Use = UI.getUse();
9572 
9573       // Skip uses of different values from the same node.
9574       if (Use.getResNo() != From.getResNo()) {
9575         ++UI;
9576         continue;
9577       }
9578 
9579       // If this node hasn't been modified yet, it's still in the CSE maps,
9580       // so remove its old self from the CSE maps.
9581       if (!UserRemovedFromCSEMaps) {
9582         RemoveNodeFromCSEMaps(User);
9583         UserRemovedFromCSEMaps = true;
9584       }
9585 
9586       ++UI;
9587       Use.set(To);
9588       if (To->isDivergent() != From->isDivergent())
9589         updateDivergence(User);
9590     } while (UI != UE && *UI == User);
9591     // We are iterating over all uses of the From node, so if a use
9592     // doesn't use the specific value, no changes are made.
9593     if (!UserRemovedFromCSEMaps)
9594       continue;
9595 
9596     // Now that we have modified User, add it back to the CSE maps.  If it
9597     // already exists there, recursively merge the results together.
9598     AddModifiedNodeToCSEMaps(User);
9599   }
9600 
9601   // If we just RAUW'd the root, take note.
9602   if (From == getRoot())
9603     setRoot(To);
9604 }
9605 
9606 namespace {
9607 
9608   /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith
9609   /// to record information about a use.
9610   struct UseMemo {
9611     SDNode *User;
9612     unsigned Index;
9613     SDUse *Use;
9614   };
9615 
9616   /// operator< - Sort Memos by User.
9617   bool operator<(const UseMemo &L, const UseMemo &R) {
9618     return (intptr_t)L.User < (intptr_t)R.User;
9619   }
9620 
9621 } // end anonymous namespace
9622 
9623 bool SelectionDAG::calculateDivergence(SDNode *N) {
9624   if (TLI->isSDNodeAlwaysUniform(N)) {
9625     assert(!TLI->isSDNodeSourceOfDivergence(N, FLI, DA) &&
9626            "Conflicting divergence information!");
9627     return false;
9628   }
9629   if (TLI->isSDNodeSourceOfDivergence(N, FLI, DA))
9630     return true;
9631   for (auto &Op : N->ops()) {
9632     if (Op.Val.getValueType() != MVT::Other && Op.getNode()->isDivergent())
9633       return true;
9634   }
9635   return false;
9636 }
9637 
9638 void SelectionDAG::updateDivergence(SDNode *N) {
9639   SmallVector<SDNode *, 16> Worklist(1, N);
9640   do {
9641     N = Worklist.pop_back_val();
9642     bool IsDivergent = calculateDivergence(N);
9643     if (N->SDNodeBits.IsDivergent != IsDivergent) {
9644       N->SDNodeBits.IsDivergent = IsDivergent;
9645       llvm::append_range(Worklist, N->uses());
9646     }
9647   } while (!Worklist.empty());
9648 }
9649 
9650 void SelectionDAG::CreateTopologicalOrder(std::vector<SDNode *> &Order) {
9651   DenseMap<SDNode *, unsigned> Degree;
9652   Order.reserve(AllNodes.size());
9653   for (auto &N : allnodes()) {
9654     unsigned NOps = N.getNumOperands();
9655     Degree[&N] = NOps;
9656     if (0 == NOps)
9657       Order.push_back(&N);
9658   }
9659   for (size_t I = 0; I != Order.size(); ++I) {
9660     SDNode *N = Order[I];
9661     for (auto U : N->uses()) {
9662       unsigned &UnsortedOps = Degree[U];
9663       if (0 == --UnsortedOps)
9664         Order.push_back(U);
9665     }
9666   }
9667 }
9668 
9669 #ifndef NDEBUG
9670 void SelectionDAG::VerifyDAGDivergence() {
9671   std::vector<SDNode *> TopoOrder;
9672   CreateTopologicalOrder(TopoOrder);
9673   for (auto *N : TopoOrder) {
9674     assert(calculateDivergence(N) == N->isDivergent() &&
9675            "Divergence bit inconsistency detected");
9676   }
9677 }
9678 #endif
9679 
9680 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving
9681 /// uses of other values produced by From.getNode() alone.  The same value
9682 /// may appear in both the From and To list.  The Deleted vector is
9683 /// handled the same way as for ReplaceAllUsesWith.
9684 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From,
9685                                               const SDValue *To,
9686                                               unsigned Num){
9687   // Handle the simple, trivial case efficiently.
9688   if (Num == 1)
9689     return ReplaceAllUsesOfValueWith(*From, *To);
9690 
9691   transferDbgValues(*From, *To);
9692 
9693   // Read up all the uses and make records of them. This helps
9694   // processing new uses that are introduced during the
9695   // replacement process.
9696   SmallVector<UseMemo, 4> Uses;
9697   for (unsigned i = 0; i != Num; ++i) {
9698     unsigned FromResNo = From[i].getResNo();
9699     SDNode *FromNode = From[i].getNode();
9700     for (SDNode::use_iterator UI = FromNode->use_begin(),
9701          E = FromNode->use_end(); UI != E; ++UI) {
9702       SDUse &Use = UI.getUse();
9703       if (Use.getResNo() == FromResNo) {
9704         UseMemo Memo = { *UI, i, &Use };
9705         Uses.push_back(Memo);
9706       }
9707     }
9708   }
9709 
9710   // Sort the uses, so that all the uses from a given User are together.
9711   llvm::sort(Uses);
9712 
9713   for (unsigned UseIndex = 0, UseIndexEnd = Uses.size();
9714        UseIndex != UseIndexEnd; ) {
9715     // We know that this user uses some value of From.  If it is the right
9716     // value, update it.
9717     SDNode *User = Uses[UseIndex].User;
9718 
9719     // This node is about to morph, remove its old self from the CSE maps.
9720     RemoveNodeFromCSEMaps(User);
9721 
9722     // The Uses array is sorted, so all the uses for a given User
9723     // are next to each other in the list.
9724     // To help reduce the number of CSE recomputations, process all
9725     // the uses of this user that we can find this way.
9726     do {
9727       unsigned i = Uses[UseIndex].Index;
9728       SDUse &Use = *Uses[UseIndex].Use;
9729       ++UseIndex;
9730 
9731       Use.set(To[i]);
9732     } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User);
9733 
9734     // Now that we have modified User, add it back to the CSE maps.  If it
9735     // already exists there, recursively merge the results together.
9736     AddModifiedNodeToCSEMaps(User);
9737   }
9738 }
9739 
9740 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
9741 /// based on their topological order. It returns the maximum id and a vector
9742 /// of the SDNodes* in assigned order by reference.
9743 unsigned SelectionDAG::AssignTopologicalOrder() {
9744   unsigned DAGSize = 0;
9745 
9746   // SortedPos tracks the progress of the algorithm. Nodes before it are
9747   // sorted, nodes after it are unsorted. When the algorithm completes
9748   // it is at the end of the list.
9749   allnodes_iterator SortedPos = allnodes_begin();
9750 
9751   // Visit all the nodes. Move nodes with no operands to the front of
9752   // the list immediately. Annotate nodes that do have operands with their
9753   // operand count. Before we do this, the Node Id fields of the nodes
9754   // may contain arbitrary values. After, the Node Id fields for nodes
9755   // before SortedPos will contain the topological sort index, and the
9756   // Node Id fields for nodes At SortedPos and after will contain the
9757   // count of outstanding operands.
9758   for (SDNode &N : llvm::make_early_inc_range(allnodes())) {
9759     checkForCycles(&N, this);
9760     unsigned Degree = N.getNumOperands();
9761     if (Degree == 0) {
9762       // A node with no uses, add it to the result array immediately.
9763       N.setNodeId(DAGSize++);
9764       allnodes_iterator Q(&N);
9765       if (Q != SortedPos)
9766         SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q));
9767       assert(SortedPos != AllNodes.end() && "Overran node list");
9768       ++SortedPos;
9769     } else {
9770       // Temporarily use the Node Id as scratch space for the degree count.
9771       N.setNodeId(Degree);
9772     }
9773   }
9774 
9775   // Visit all the nodes. As we iterate, move nodes into sorted order,
9776   // such that by the time the end is reached all nodes will be sorted.
9777   for (SDNode &Node : allnodes()) {
9778     SDNode *N = &Node;
9779     checkForCycles(N, this);
9780     // N is in sorted position, so all its uses have one less operand
9781     // that needs to be sorted.
9782     for (SDNode *P : N->uses()) {
9783       unsigned Degree = P->getNodeId();
9784       assert(Degree != 0 && "Invalid node degree");
9785       --Degree;
9786       if (Degree == 0) {
9787         // All of P's operands are sorted, so P may sorted now.
9788         P->setNodeId(DAGSize++);
9789         if (P->getIterator() != SortedPos)
9790           SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P));
9791         assert(SortedPos != AllNodes.end() && "Overran node list");
9792         ++SortedPos;
9793       } else {
9794         // Update P's outstanding operand count.
9795         P->setNodeId(Degree);
9796       }
9797     }
9798     if (Node.getIterator() == SortedPos) {
9799 #ifndef NDEBUG
9800       allnodes_iterator I(N);
9801       SDNode *S = &*++I;
9802       dbgs() << "Overran sorted position:\n";
9803       S->dumprFull(this); dbgs() << "\n";
9804       dbgs() << "Checking if this is due to cycles\n";
9805       checkForCycles(this, true);
9806 #endif
9807       llvm_unreachable(nullptr);
9808     }
9809   }
9810 
9811   assert(SortedPos == AllNodes.end() &&
9812          "Topological sort incomplete!");
9813   assert(AllNodes.front().getOpcode() == ISD::EntryToken &&
9814          "First node in topological sort is not the entry token!");
9815   assert(AllNodes.front().getNodeId() == 0 &&
9816          "First node in topological sort has non-zero id!");
9817   assert(AllNodes.front().getNumOperands() == 0 &&
9818          "First node in topological sort has operands!");
9819   assert(AllNodes.back().getNodeId() == (int)DAGSize-1 &&
9820          "Last node in topologic sort has unexpected id!");
9821   assert(AllNodes.back().use_empty() &&
9822          "Last node in topologic sort has users!");
9823   assert(DAGSize == allnodes_size() && "Node count mismatch!");
9824   return DAGSize;
9825 }
9826 
9827 /// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the
9828 /// value is produced by SD.
9829 void SelectionDAG::AddDbgValue(SDDbgValue *DB, bool isParameter) {
9830   for (SDNode *SD : DB->getSDNodes()) {
9831     if (!SD)
9832       continue;
9833     assert(DbgInfo->getSDDbgValues(SD).empty() || SD->getHasDebugValue());
9834     SD->setHasDebugValue(true);
9835   }
9836   DbgInfo->add(DB, isParameter);
9837 }
9838 
9839 void SelectionDAG::AddDbgLabel(SDDbgLabel *DB) { DbgInfo->add(DB); }
9840 
9841 SDValue SelectionDAG::makeEquivalentMemoryOrdering(SDValue OldChain,
9842                                                    SDValue NewMemOpChain) {
9843   assert(isa<MemSDNode>(NewMemOpChain) && "Expected a memop node");
9844   assert(NewMemOpChain.getValueType() == MVT::Other && "Expected a token VT");
9845   // The new memory operation must have the same position as the old load in
9846   // terms of memory dependency. Create a TokenFactor for the old load and new
9847   // memory operation and update uses of the old load's output chain to use that
9848   // TokenFactor.
9849   if (OldChain == NewMemOpChain || OldChain.use_empty())
9850     return NewMemOpChain;
9851 
9852   SDValue TokenFactor = getNode(ISD::TokenFactor, SDLoc(OldChain), MVT::Other,
9853                                 OldChain, NewMemOpChain);
9854   ReplaceAllUsesOfValueWith(OldChain, TokenFactor);
9855   UpdateNodeOperands(TokenFactor.getNode(), OldChain, NewMemOpChain);
9856   return TokenFactor;
9857 }
9858 
9859 SDValue SelectionDAG::makeEquivalentMemoryOrdering(LoadSDNode *OldLoad,
9860                                                    SDValue NewMemOp) {
9861   assert(isa<MemSDNode>(NewMemOp.getNode()) && "Expected a memop node");
9862   SDValue OldChain = SDValue(OldLoad, 1);
9863   SDValue NewMemOpChain = NewMemOp.getValue(1);
9864   return makeEquivalentMemoryOrdering(OldChain, NewMemOpChain);
9865 }
9866 
9867 SDValue SelectionDAG::getSymbolFunctionGlobalAddress(SDValue Op,
9868                                                      Function **OutFunction) {
9869   assert(isa<ExternalSymbolSDNode>(Op) && "Node should be an ExternalSymbol");
9870 
9871   auto *Symbol = cast<ExternalSymbolSDNode>(Op)->getSymbol();
9872   auto *Module = MF->getFunction().getParent();
9873   auto *Function = Module->getFunction(Symbol);
9874 
9875   if (OutFunction != nullptr)
9876       *OutFunction = Function;
9877 
9878   if (Function != nullptr) {
9879     auto PtrTy = TLI->getPointerTy(getDataLayout(), Function->getAddressSpace());
9880     return getGlobalAddress(Function, SDLoc(Op), PtrTy);
9881   }
9882 
9883   std::string ErrorStr;
9884   raw_string_ostream ErrorFormatter(ErrorStr);
9885   ErrorFormatter << "Undefined external symbol ";
9886   ErrorFormatter << '"' << Symbol << '"';
9887   report_fatal_error(Twine(ErrorFormatter.str()));
9888 }
9889 
9890 //===----------------------------------------------------------------------===//
9891 //                              SDNode Class
9892 //===----------------------------------------------------------------------===//
9893 
9894 bool llvm::isNullConstant(SDValue V) {
9895   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
9896   return Const != nullptr && Const->isZero();
9897 }
9898 
9899 bool llvm::isNullFPConstant(SDValue V) {
9900   ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V);
9901   return Const != nullptr && Const->isZero() && !Const->isNegative();
9902 }
9903 
9904 bool llvm::isAllOnesConstant(SDValue V) {
9905   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
9906   return Const != nullptr && Const->isAllOnes();
9907 }
9908 
9909 bool llvm::isOneConstant(SDValue V) {
9910   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
9911   return Const != nullptr && Const->isOne();
9912 }
9913 
9914 SDValue llvm::peekThroughBitcasts(SDValue V) {
9915   while (V.getOpcode() == ISD::BITCAST)
9916     V = V.getOperand(0);
9917   return V;
9918 }
9919 
9920 SDValue llvm::peekThroughOneUseBitcasts(SDValue V) {
9921   while (V.getOpcode() == ISD::BITCAST && V.getOperand(0).hasOneUse())
9922     V = V.getOperand(0);
9923   return V;
9924 }
9925 
9926 SDValue llvm::peekThroughExtractSubvectors(SDValue V) {
9927   while (V.getOpcode() == ISD::EXTRACT_SUBVECTOR)
9928     V = V.getOperand(0);
9929   return V;
9930 }
9931 
9932 bool llvm::isBitwiseNot(SDValue V, bool AllowUndefs) {
9933   if (V.getOpcode() != ISD::XOR)
9934     return false;
9935   V = peekThroughBitcasts(V.getOperand(1));
9936   unsigned NumBits = V.getScalarValueSizeInBits();
9937   ConstantSDNode *C =
9938       isConstOrConstSplat(V, AllowUndefs, /*AllowTruncation*/ true);
9939   return C && (C->getAPIntValue().countTrailingOnes() >= NumBits);
9940 }
9941 
9942 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, bool AllowUndefs,
9943                                           bool AllowTruncation) {
9944   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
9945     return CN;
9946 
9947   // SplatVectors can truncate their operands. Ignore that case here unless
9948   // AllowTruncation is set.
9949   if (N->getOpcode() == ISD::SPLAT_VECTOR) {
9950     EVT VecEltVT = N->getValueType(0).getVectorElementType();
9951     if (auto *CN = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
9952       EVT CVT = CN->getValueType(0);
9953       assert(CVT.bitsGE(VecEltVT) && "Illegal splat_vector element extension");
9954       if (AllowTruncation || CVT == VecEltVT)
9955         return CN;
9956     }
9957   }
9958 
9959   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
9960     BitVector UndefElements;
9961     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
9962 
9963     // BuildVectors can truncate their operands. Ignore that case here unless
9964     // AllowTruncation is set.
9965     if (CN && (UndefElements.none() || AllowUndefs)) {
9966       EVT CVT = CN->getValueType(0);
9967       EVT NSVT = N.getValueType().getScalarType();
9968       assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension");
9969       if (AllowTruncation || (CVT == NSVT))
9970         return CN;
9971     }
9972   }
9973 
9974   return nullptr;
9975 }
9976 
9977 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, const APInt &DemandedElts,
9978                                           bool AllowUndefs,
9979                                           bool AllowTruncation) {
9980   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
9981     return CN;
9982 
9983   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
9984     BitVector UndefElements;
9985     ConstantSDNode *CN = BV->getConstantSplatNode(DemandedElts, &UndefElements);
9986 
9987     // BuildVectors can truncate their operands. Ignore that case here unless
9988     // AllowTruncation is set.
9989     if (CN && (UndefElements.none() || AllowUndefs)) {
9990       EVT CVT = CN->getValueType(0);
9991       EVT NSVT = N.getValueType().getScalarType();
9992       assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension");
9993       if (AllowTruncation || (CVT == NSVT))
9994         return CN;
9995     }
9996   }
9997 
9998   return nullptr;
9999 }
10000 
10001 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N, bool AllowUndefs) {
10002   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
10003     return CN;
10004 
10005   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
10006     BitVector UndefElements;
10007     ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
10008     if (CN && (UndefElements.none() || AllowUndefs))
10009       return CN;
10010   }
10011 
10012   if (N.getOpcode() == ISD::SPLAT_VECTOR)
10013     if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N.getOperand(0)))
10014       return CN;
10015 
10016   return nullptr;
10017 }
10018 
10019 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N,
10020                                               const APInt &DemandedElts,
10021                                               bool AllowUndefs) {
10022   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
10023     return CN;
10024 
10025   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
10026     BitVector UndefElements;
10027     ConstantFPSDNode *CN =
10028         BV->getConstantFPSplatNode(DemandedElts, &UndefElements);
10029     if (CN && (UndefElements.none() || AllowUndefs))
10030       return CN;
10031   }
10032 
10033   return nullptr;
10034 }
10035 
10036 bool llvm::isNullOrNullSplat(SDValue N, bool AllowUndefs) {
10037   // TODO: may want to use peekThroughBitcast() here.
10038   ConstantSDNode *C =
10039       isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation=*/true);
10040   return C && C->isZero();
10041 }
10042 
10043 bool llvm::isOneOrOneSplat(SDValue N, bool AllowUndefs) {
10044   // TODO: may want to use peekThroughBitcast() here.
10045   unsigned BitWidth = N.getScalarValueSizeInBits();
10046   ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs);
10047   return C && C->isOne() && C->getValueSizeInBits(0) == BitWidth;
10048 }
10049 
10050 bool llvm::isAllOnesOrAllOnesSplat(SDValue N, bool AllowUndefs) {
10051   N = peekThroughBitcasts(N);
10052   unsigned BitWidth = N.getScalarValueSizeInBits();
10053   ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs);
10054   return C && C->isAllOnes() && C->getValueSizeInBits(0) == BitWidth;
10055 }
10056 
10057 HandleSDNode::~HandleSDNode() {
10058   DropOperands();
10059 }
10060 
10061 GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, unsigned Order,
10062                                          const DebugLoc &DL,
10063                                          const GlobalValue *GA, EVT VT,
10064                                          int64_t o, unsigned TF)
10065     : SDNode(Opc, Order, DL, getSDVTList(VT)), Offset(o), TargetFlags(TF) {
10066   TheGlobal = GA;
10067 }
10068 
10069 AddrSpaceCastSDNode::AddrSpaceCastSDNode(unsigned Order, const DebugLoc &dl,
10070                                          EVT VT, unsigned SrcAS,
10071                                          unsigned DestAS)
10072     : SDNode(ISD::ADDRSPACECAST, Order, dl, getSDVTList(VT)),
10073       SrcAddrSpace(SrcAS), DestAddrSpace(DestAS) {}
10074 
10075 MemSDNode::MemSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl,
10076                      SDVTList VTs, EVT memvt, MachineMemOperand *mmo)
10077     : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MMO(mmo) {
10078   MemSDNodeBits.IsVolatile = MMO->isVolatile();
10079   MemSDNodeBits.IsNonTemporal = MMO->isNonTemporal();
10080   MemSDNodeBits.IsDereferenceable = MMO->isDereferenceable();
10081   MemSDNodeBits.IsInvariant = MMO->isInvariant();
10082 
10083   // We check here that the size of the memory operand fits within the size of
10084   // the MMO. This is because the MMO might indicate only a possible address
10085   // range instead of specifying the affected memory addresses precisely.
10086   // TODO: Make MachineMemOperands aware of scalable vectors.
10087   assert(memvt.getStoreSize().getKnownMinSize() <= MMO->getSize() &&
10088          "Size mismatch!");
10089 }
10090 
10091 /// Profile - Gather unique data for the node.
10092 ///
10093 void SDNode::Profile(FoldingSetNodeID &ID) const {
10094   AddNodeIDNode(ID, this);
10095 }
10096 
10097 namespace {
10098 
10099   struct EVTArray {
10100     std::vector<EVT> VTs;
10101 
10102     EVTArray() {
10103       VTs.reserve(MVT::VALUETYPE_SIZE);
10104       for (unsigned i = 0; i < MVT::VALUETYPE_SIZE; ++i)
10105         VTs.push_back(MVT((MVT::SimpleValueType)i));
10106     }
10107   };
10108 
10109 } // end anonymous namespace
10110 
10111 static ManagedStatic<std::set<EVT, EVT::compareRawBits>> EVTs;
10112 static ManagedStatic<EVTArray> SimpleVTArray;
10113 static ManagedStatic<sys::SmartMutex<true>> VTMutex;
10114 
10115 /// getValueTypeList - Return a pointer to the specified value type.
10116 ///
10117 const EVT *SDNode::getValueTypeList(EVT VT) {
10118   if (VT.isExtended()) {
10119     sys::SmartScopedLock<true> Lock(*VTMutex);
10120     return &(*EVTs->insert(VT).first);
10121   }
10122   assert(VT.getSimpleVT() < MVT::VALUETYPE_SIZE && "Value type out of range!");
10123   return &SimpleVTArray->VTs[VT.getSimpleVT().SimpleTy];
10124 }
10125 
10126 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
10127 /// indicated value.  This method ignores uses of other values defined by this
10128 /// operation.
10129 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
10130   assert(Value < getNumValues() && "Bad value!");
10131 
10132   // TODO: Only iterate over uses of a given value of the node
10133   for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
10134     if (UI.getUse().getResNo() == Value) {
10135       if (NUses == 0)
10136         return false;
10137       --NUses;
10138     }
10139   }
10140 
10141   // Found exactly the right number of uses?
10142   return NUses == 0;
10143 }
10144 
10145 /// hasAnyUseOfValue - Return true if there are any use of the indicated
10146 /// value. This method ignores uses of other values defined by this operation.
10147 bool SDNode::hasAnyUseOfValue(unsigned Value) const {
10148   assert(Value < getNumValues() && "Bad value!");
10149 
10150   for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI)
10151     if (UI.getUse().getResNo() == Value)
10152       return true;
10153 
10154   return false;
10155 }
10156 
10157 /// isOnlyUserOf - Return true if this node is the only use of N.
10158 bool SDNode::isOnlyUserOf(const SDNode *N) const {
10159   bool Seen = false;
10160   for (const SDNode *User : N->uses()) {
10161     if (User == this)
10162       Seen = true;
10163     else
10164       return false;
10165   }
10166 
10167   return Seen;
10168 }
10169 
10170 /// Return true if the only users of N are contained in Nodes.
10171 bool SDNode::areOnlyUsersOf(ArrayRef<const SDNode *> Nodes, const SDNode *N) {
10172   bool Seen = false;
10173   for (const SDNode *User : N->uses()) {
10174     if (llvm::is_contained(Nodes, User))
10175       Seen = true;
10176     else
10177       return false;
10178   }
10179 
10180   return Seen;
10181 }
10182 
10183 /// isOperand - Return true if this node is an operand of N.
10184 bool SDValue::isOperandOf(const SDNode *N) const {
10185   return is_contained(N->op_values(), *this);
10186 }
10187 
10188 bool SDNode::isOperandOf(const SDNode *N) const {
10189   return any_of(N->op_values(),
10190                 [this](SDValue Op) { return this == Op.getNode(); });
10191 }
10192 
10193 /// reachesChainWithoutSideEffects - Return true if this operand (which must
10194 /// be a chain) reaches the specified operand without crossing any
10195 /// side-effecting instructions on any chain path.  In practice, this looks
10196 /// through token factors and non-volatile loads.  In order to remain efficient,
10197 /// this only looks a couple of nodes in, it does not do an exhaustive search.
10198 ///
10199 /// Note that we only need to examine chains when we're searching for
10200 /// side-effects; SelectionDAG requires that all side-effects are represented
10201 /// by chains, even if another operand would force a specific ordering. This
10202 /// constraint is necessary to allow transformations like splitting loads.
10203 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest,
10204                                              unsigned Depth) const {
10205   if (*this == Dest) return true;
10206 
10207   // Don't search too deeply, we just want to be able to see through
10208   // TokenFactor's etc.
10209   if (Depth == 0) return false;
10210 
10211   // If this is a token factor, all inputs to the TF happen in parallel.
10212   if (getOpcode() == ISD::TokenFactor) {
10213     // First, try a shallow search.
10214     if (is_contained((*this)->ops(), Dest)) {
10215       // We found the chain we want as an operand of this TokenFactor.
10216       // Essentially, we reach the chain without side-effects if we could
10217       // serialize the TokenFactor into a simple chain of operations with
10218       // Dest as the last operation. This is automatically true if the
10219       // chain has one use: there are no other ordering constraints.
10220       // If the chain has more than one use, we give up: some other
10221       // use of Dest might force a side-effect between Dest and the current
10222       // node.
10223       if (Dest.hasOneUse())
10224         return true;
10225     }
10226     // Next, try a deep search: check whether every operand of the TokenFactor
10227     // reaches Dest.
10228     return llvm::all_of((*this)->ops(), [=](SDValue Op) {
10229       return Op.reachesChainWithoutSideEffects(Dest, Depth - 1);
10230     });
10231   }
10232 
10233   // Loads don't have side effects, look through them.
10234   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
10235     if (Ld->isUnordered())
10236       return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
10237   }
10238   return false;
10239 }
10240 
10241 bool SDNode::hasPredecessor(const SDNode *N) const {
10242   SmallPtrSet<const SDNode *, 32> Visited;
10243   SmallVector<const SDNode *, 16> Worklist;
10244   Worklist.push_back(this);
10245   return hasPredecessorHelper(N, Visited, Worklist);
10246 }
10247 
10248 void SDNode::intersectFlagsWith(const SDNodeFlags Flags) {
10249   this->Flags.intersectWith(Flags);
10250 }
10251 
10252 SDValue
10253 SelectionDAG::matchBinOpReduction(SDNode *Extract, ISD::NodeType &BinOp,
10254                                   ArrayRef<ISD::NodeType> CandidateBinOps,
10255                                   bool AllowPartials) {
10256   // The pattern must end in an extract from index 0.
10257   if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10258       !isNullConstant(Extract->getOperand(1)))
10259     return SDValue();
10260 
10261   // Match against one of the candidate binary ops.
10262   SDValue Op = Extract->getOperand(0);
10263   if (llvm::none_of(CandidateBinOps, [Op](ISD::NodeType BinOp) {
10264         return Op.getOpcode() == unsigned(BinOp);
10265       }))
10266     return SDValue();
10267 
10268   // Floating-point reductions may require relaxed constraints on the final step
10269   // of the reduction because they may reorder intermediate operations.
10270   unsigned CandidateBinOp = Op.getOpcode();
10271   if (Op.getValueType().isFloatingPoint()) {
10272     SDNodeFlags Flags = Op->getFlags();
10273     switch (CandidateBinOp) {
10274     case ISD::FADD:
10275       if (!Flags.hasNoSignedZeros() || !Flags.hasAllowReassociation())
10276         return SDValue();
10277       break;
10278     default:
10279       llvm_unreachable("Unhandled FP opcode for binop reduction");
10280     }
10281   }
10282 
10283   // Matching failed - attempt to see if we did enough stages that a partial
10284   // reduction from a subvector is possible.
10285   auto PartialReduction = [&](SDValue Op, unsigned NumSubElts) {
10286     if (!AllowPartials || !Op)
10287       return SDValue();
10288     EVT OpVT = Op.getValueType();
10289     EVT OpSVT = OpVT.getScalarType();
10290     EVT SubVT = EVT::getVectorVT(*getContext(), OpSVT, NumSubElts);
10291     if (!TLI->isExtractSubvectorCheap(SubVT, OpVT, 0))
10292       return SDValue();
10293     BinOp = (ISD::NodeType)CandidateBinOp;
10294     return getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(Op), SubVT, Op,
10295                    getVectorIdxConstant(0, SDLoc(Op)));
10296   };
10297 
10298   // At each stage, we're looking for something that looks like:
10299   // %s = shufflevector <8 x i32> %op, <8 x i32> undef,
10300   //                    <8 x i32> <i32 2, i32 3, i32 undef, i32 undef,
10301   //                               i32 undef, i32 undef, i32 undef, i32 undef>
10302   // %a = binop <8 x i32> %op, %s
10303   // Where the mask changes according to the stage. E.g. for a 3-stage pyramid,
10304   // we expect something like:
10305   // <4,5,6,7,u,u,u,u>
10306   // <2,3,u,u,u,u,u,u>
10307   // <1,u,u,u,u,u,u,u>
10308   // While a partial reduction match would be:
10309   // <2,3,u,u,u,u,u,u>
10310   // <1,u,u,u,u,u,u,u>
10311   unsigned Stages = Log2_32(Op.getValueType().getVectorNumElements());
10312   SDValue PrevOp;
10313   for (unsigned i = 0; i < Stages; ++i) {
10314     unsigned MaskEnd = (1 << i);
10315 
10316     if (Op.getOpcode() != CandidateBinOp)
10317       return PartialReduction(PrevOp, MaskEnd);
10318 
10319     SDValue Op0 = Op.getOperand(0);
10320     SDValue Op1 = Op.getOperand(1);
10321 
10322     ShuffleVectorSDNode *Shuffle = dyn_cast<ShuffleVectorSDNode>(Op0);
10323     if (Shuffle) {
10324       Op = Op1;
10325     } else {
10326       Shuffle = dyn_cast<ShuffleVectorSDNode>(Op1);
10327       Op = Op0;
10328     }
10329 
10330     // The first operand of the shuffle should be the same as the other operand
10331     // of the binop.
10332     if (!Shuffle || Shuffle->getOperand(0) != Op)
10333       return PartialReduction(PrevOp, MaskEnd);
10334 
10335     // Verify the shuffle has the expected (at this stage of the pyramid) mask.
10336     for (int Index = 0; Index < (int)MaskEnd; ++Index)
10337       if (Shuffle->getMaskElt(Index) != (int)(MaskEnd + Index))
10338         return PartialReduction(PrevOp, MaskEnd);
10339 
10340     PrevOp = Op;
10341   }
10342 
10343   // Handle subvector reductions, which tend to appear after the shuffle
10344   // reduction stages.
10345   while (Op.getOpcode() == CandidateBinOp) {
10346     unsigned NumElts = Op.getValueType().getVectorNumElements();
10347     SDValue Op0 = Op.getOperand(0);
10348     SDValue Op1 = Op.getOperand(1);
10349     if (Op0.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
10350         Op1.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
10351         Op0.getOperand(0) != Op1.getOperand(0))
10352       break;
10353     SDValue Src = Op0.getOperand(0);
10354     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
10355     if (NumSrcElts != (2 * NumElts))
10356       break;
10357     if (!(Op0.getConstantOperandAPInt(1) == 0 &&
10358           Op1.getConstantOperandAPInt(1) == NumElts) &&
10359         !(Op1.getConstantOperandAPInt(1) == 0 &&
10360           Op0.getConstantOperandAPInt(1) == NumElts))
10361       break;
10362     Op = Src;
10363   }
10364 
10365   BinOp = (ISD::NodeType)CandidateBinOp;
10366   return Op;
10367 }
10368 
10369 SDValue SelectionDAG::UnrollVectorOp(SDNode *N, unsigned ResNE) {
10370   assert(N->getNumValues() == 1 &&
10371          "Can't unroll a vector with multiple results!");
10372 
10373   EVT VT = N->getValueType(0);
10374   unsigned NE = VT.getVectorNumElements();
10375   EVT EltVT = VT.getVectorElementType();
10376   SDLoc dl(N);
10377 
10378   SmallVector<SDValue, 8> Scalars;
10379   SmallVector<SDValue, 4> Operands(N->getNumOperands());
10380 
10381   // If ResNE is 0, fully unroll the vector op.
10382   if (ResNE == 0)
10383     ResNE = NE;
10384   else if (NE > ResNE)
10385     NE = ResNE;
10386 
10387   unsigned i;
10388   for (i= 0; i != NE; ++i) {
10389     for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) {
10390       SDValue Operand = N->getOperand(j);
10391       EVT OperandVT = Operand.getValueType();
10392       if (OperandVT.isVector()) {
10393         // A vector operand; extract a single element.
10394         EVT OperandEltVT = OperandVT.getVectorElementType();
10395         Operands[j] = getNode(ISD::EXTRACT_VECTOR_ELT, dl, OperandEltVT,
10396                               Operand, getVectorIdxConstant(i, dl));
10397       } else {
10398         // A scalar operand; just use it as is.
10399         Operands[j] = Operand;
10400       }
10401     }
10402 
10403     switch (N->getOpcode()) {
10404     default: {
10405       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands,
10406                                 N->getFlags()));
10407       break;
10408     }
10409     case ISD::VSELECT:
10410       Scalars.push_back(getNode(ISD::SELECT, dl, EltVT, Operands));
10411       break;
10412     case ISD::SHL:
10413     case ISD::SRA:
10414     case ISD::SRL:
10415     case ISD::ROTL:
10416     case ISD::ROTR:
10417       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0],
10418                                getShiftAmountOperand(Operands[0].getValueType(),
10419                                                      Operands[1])));
10420       break;
10421     case ISD::SIGN_EXTEND_INREG: {
10422       EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType();
10423       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT,
10424                                 Operands[0],
10425                                 getValueType(ExtVT)));
10426     }
10427     }
10428   }
10429 
10430   for (; i < ResNE; ++i)
10431     Scalars.push_back(getUNDEF(EltVT));
10432 
10433   EVT VecVT = EVT::getVectorVT(*getContext(), EltVT, ResNE);
10434   return getBuildVector(VecVT, dl, Scalars);
10435 }
10436 
10437 std::pair<SDValue, SDValue> SelectionDAG::UnrollVectorOverflowOp(
10438     SDNode *N, unsigned ResNE) {
10439   unsigned Opcode = N->getOpcode();
10440   assert((Opcode == ISD::UADDO || Opcode == ISD::SADDO ||
10441           Opcode == ISD::USUBO || Opcode == ISD::SSUBO ||
10442           Opcode == ISD::UMULO || Opcode == ISD::SMULO) &&
10443          "Expected an overflow opcode");
10444 
10445   EVT ResVT = N->getValueType(0);
10446   EVT OvVT = N->getValueType(1);
10447   EVT ResEltVT = ResVT.getVectorElementType();
10448   EVT OvEltVT = OvVT.getVectorElementType();
10449   SDLoc dl(N);
10450 
10451   // If ResNE is 0, fully unroll the vector op.
10452   unsigned NE = ResVT.getVectorNumElements();
10453   if (ResNE == 0)
10454     ResNE = NE;
10455   else if (NE > ResNE)
10456     NE = ResNE;
10457 
10458   SmallVector<SDValue, 8> LHSScalars;
10459   SmallVector<SDValue, 8> RHSScalars;
10460   ExtractVectorElements(N->getOperand(0), LHSScalars, 0, NE);
10461   ExtractVectorElements(N->getOperand(1), RHSScalars, 0, NE);
10462 
10463   EVT SVT = TLI->getSetCCResultType(getDataLayout(), *getContext(), ResEltVT);
10464   SDVTList VTs = getVTList(ResEltVT, SVT);
10465   SmallVector<SDValue, 8> ResScalars;
10466   SmallVector<SDValue, 8> OvScalars;
10467   for (unsigned i = 0; i < NE; ++i) {
10468     SDValue Res = getNode(Opcode, dl, VTs, LHSScalars[i], RHSScalars[i]);
10469     SDValue Ov =
10470         getSelect(dl, OvEltVT, Res.getValue(1),
10471                   getBoolConstant(true, dl, OvEltVT, ResVT),
10472                   getConstant(0, dl, OvEltVT));
10473 
10474     ResScalars.push_back(Res);
10475     OvScalars.push_back(Ov);
10476   }
10477 
10478   ResScalars.append(ResNE - NE, getUNDEF(ResEltVT));
10479   OvScalars.append(ResNE - NE, getUNDEF(OvEltVT));
10480 
10481   EVT NewResVT = EVT::getVectorVT(*getContext(), ResEltVT, ResNE);
10482   EVT NewOvVT = EVT::getVectorVT(*getContext(), OvEltVT, ResNE);
10483   return std::make_pair(getBuildVector(NewResVT, dl, ResScalars),
10484                         getBuildVector(NewOvVT, dl, OvScalars));
10485 }
10486 
10487 bool SelectionDAG::areNonVolatileConsecutiveLoads(LoadSDNode *LD,
10488                                                   LoadSDNode *Base,
10489                                                   unsigned Bytes,
10490                                                   int Dist) const {
10491   if (LD->isVolatile() || Base->isVolatile())
10492     return false;
10493   // TODO: probably too restrictive for atomics, revisit
10494   if (!LD->isSimple())
10495     return false;
10496   if (LD->isIndexed() || Base->isIndexed())
10497     return false;
10498   if (LD->getChain() != Base->getChain())
10499     return false;
10500   EVT VT = LD->getValueType(0);
10501   if (VT.getSizeInBits() / 8 != Bytes)
10502     return false;
10503 
10504   auto BaseLocDecomp = BaseIndexOffset::match(Base, *this);
10505   auto LocDecomp = BaseIndexOffset::match(LD, *this);
10506 
10507   int64_t Offset = 0;
10508   if (BaseLocDecomp.equalBaseIndex(LocDecomp, *this, Offset))
10509     return (Dist * Bytes == Offset);
10510   return false;
10511 }
10512 
10513 /// InferPtrAlignment - Infer alignment of a load / store address. Return None
10514 /// if it cannot be inferred.
10515 MaybeAlign SelectionDAG::InferPtrAlign(SDValue Ptr) const {
10516   // If this is a GlobalAddress + cst, return the alignment.
10517   const GlobalValue *GV = nullptr;
10518   int64_t GVOffset = 0;
10519   if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) {
10520     unsigned PtrWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
10521     KnownBits Known(PtrWidth);
10522     llvm::computeKnownBits(GV, Known, getDataLayout());
10523     unsigned AlignBits = Known.countMinTrailingZeros();
10524     if (AlignBits)
10525       return commonAlignment(Align(1ull << std::min(31U, AlignBits)), GVOffset);
10526   }
10527 
10528   // If this is a direct reference to a stack slot, use information about the
10529   // stack slot's alignment.
10530   int FrameIdx = INT_MIN;
10531   int64_t FrameOffset = 0;
10532   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) {
10533     FrameIdx = FI->getIndex();
10534   } else if (isBaseWithConstantOffset(Ptr) &&
10535              isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
10536     // Handle FI+Cst
10537     FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
10538     FrameOffset = Ptr.getConstantOperandVal(1);
10539   }
10540 
10541   if (FrameIdx != INT_MIN) {
10542     const MachineFrameInfo &MFI = getMachineFunction().getFrameInfo();
10543     return commonAlignment(MFI.getObjectAlign(FrameIdx), FrameOffset);
10544   }
10545 
10546   return None;
10547 }
10548 
10549 /// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type
10550 /// which is split (or expanded) into two not necessarily identical pieces.
10551 std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const {
10552   // Currently all types are split in half.
10553   EVT LoVT, HiVT;
10554   if (!VT.isVector())
10555     LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT);
10556   else
10557     LoVT = HiVT = VT.getHalfNumVectorElementsVT(*getContext());
10558 
10559   return std::make_pair(LoVT, HiVT);
10560 }
10561 
10562 /// GetDependentSplitDestVTs - Compute the VTs needed for the low/hi parts of a
10563 /// type, dependent on an enveloping VT that has been split into two identical
10564 /// pieces. Sets the HiIsEmpty flag when hi type has zero storage size.
10565 std::pair<EVT, EVT>
10566 SelectionDAG::GetDependentSplitDestVTs(const EVT &VT, const EVT &EnvVT,
10567                                        bool *HiIsEmpty) const {
10568   EVT EltTp = VT.getVectorElementType();
10569   // Examples:
10570   //   custom VL=8  with enveloping VL=8/8 yields 8/0 (hi empty)
10571   //   custom VL=9  with enveloping VL=8/8 yields 8/1
10572   //   custom VL=10 with enveloping VL=8/8 yields 8/2
10573   //   etc.
10574   ElementCount VTNumElts = VT.getVectorElementCount();
10575   ElementCount EnvNumElts = EnvVT.getVectorElementCount();
10576   assert(VTNumElts.isScalable() == EnvNumElts.isScalable() &&
10577          "Mixing fixed width and scalable vectors when enveloping a type");
10578   EVT LoVT, HiVT;
10579   if (VTNumElts.getKnownMinValue() > EnvNumElts.getKnownMinValue()) {
10580     LoVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts);
10581     HiVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts - EnvNumElts);
10582     *HiIsEmpty = false;
10583   } else {
10584     // Flag that hi type has zero storage size, but return split envelop type
10585     // (this would be easier if vector types with zero elements were allowed).
10586     LoVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts);
10587     HiVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts);
10588     *HiIsEmpty = true;
10589   }
10590   return std::make_pair(LoVT, HiVT);
10591 }
10592 
10593 /// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the
10594 /// low/high part.
10595 std::pair<SDValue, SDValue>
10596 SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT,
10597                           const EVT &HiVT) {
10598   assert(LoVT.isScalableVector() == HiVT.isScalableVector() &&
10599          LoVT.isScalableVector() == N.getValueType().isScalableVector() &&
10600          "Splitting vector with an invalid mixture of fixed and scalable "
10601          "vector types");
10602   assert(LoVT.getVectorMinNumElements() + HiVT.getVectorMinNumElements() <=
10603              N.getValueType().getVectorMinNumElements() &&
10604          "More vector elements requested than available!");
10605   SDValue Lo, Hi;
10606   Lo =
10607       getNode(ISD::EXTRACT_SUBVECTOR, DL, LoVT, N, getVectorIdxConstant(0, DL));
10608   // For scalable vectors it is safe to use LoVT.getVectorMinNumElements()
10609   // (rather than having to use ElementCount), because EXTRACT_SUBVECTOR scales
10610   // IDX with the runtime scaling factor of the result vector type. For
10611   // fixed-width result vectors, that runtime scaling factor is 1.
10612   Hi = getNode(ISD::EXTRACT_SUBVECTOR, DL, HiVT, N,
10613                getVectorIdxConstant(LoVT.getVectorMinNumElements(), DL));
10614   return std::make_pair(Lo, Hi);
10615 }
10616 
10617 /// Widen the vector up to the next power of two using INSERT_SUBVECTOR.
10618 SDValue SelectionDAG::WidenVector(const SDValue &N, const SDLoc &DL) {
10619   EVT VT = N.getValueType();
10620   EVT WideVT = EVT::getVectorVT(*getContext(), VT.getVectorElementType(),
10621                                 NextPowerOf2(VT.getVectorNumElements()));
10622   return getNode(ISD::INSERT_SUBVECTOR, DL, WideVT, getUNDEF(WideVT), N,
10623                  getVectorIdxConstant(0, DL));
10624 }
10625 
10626 void SelectionDAG::ExtractVectorElements(SDValue Op,
10627                                          SmallVectorImpl<SDValue> &Args,
10628                                          unsigned Start, unsigned Count,
10629                                          EVT EltVT) {
10630   EVT VT = Op.getValueType();
10631   if (Count == 0)
10632     Count = VT.getVectorNumElements();
10633   if (EltVT == EVT())
10634     EltVT = VT.getVectorElementType();
10635   SDLoc SL(Op);
10636   for (unsigned i = Start, e = Start + Count; i != e; ++i) {
10637     Args.push_back(getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Op,
10638                            getVectorIdxConstant(i, SL)));
10639   }
10640 }
10641 
10642 // getAddressSpace - Return the address space this GlobalAddress belongs to.
10643 unsigned GlobalAddressSDNode::getAddressSpace() const {
10644   return getGlobal()->getType()->getAddressSpace();
10645 }
10646 
10647 Type *ConstantPoolSDNode::getType() const {
10648   if (isMachineConstantPoolEntry())
10649     return Val.MachineCPVal->getType();
10650   return Val.ConstVal->getType();
10651 }
10652 
10653 bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue, APInt &SplatUndef,
10654                                         unsigned &SplatBitSize,
10655                                         bool &HasAnyUndefs,
10656                                         unsigned MinSplatBits,
10657                                         bool IsBigEndian) const {
10658   EVT VT = getValueType(0);
10659   assert(VT.isVector() && "Expected a vector type");
10660   unsigned VecWidth = VT.getSizeInBits();
10661   if (MinSplatBits > VecWidth)
10662     return false;
10663 
10664   // FIXME: The widths are based on this node's type, but build vectors can
10665   // truncate their operands.
10666   SplatValue = APInt(VecWidth, 0);
10667   SplatUndef = APInt(VecWidth, 0);
10668 
10669   // Get the bits. Bits with undefined values (when the corresponding element
10670   // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared
10671   // in SplatValue. If any of the values are not constant, give up and return
10672   // false.
10673   unsigned int NumOps = getNumOperands();
10674   assert(NumOps > 0 && "isConstantSplat has 0-size build vector");
10675   unsigned EltWidth = VT.getScalarSizeInBits();
10676 
10677   for (unsigned j = 0; j < NumOps; ++j) {
10678     unsigned i = IsBigEndian ? NumOps - 1 - j : j;
10679     SDValue OpVal = getOperand(i);
10680     unsigned BitPos = j * EltWidth;
10681 
10682     if (OpVal.isUndef())
10683       SplatUndef.setBits(BitPos, BitPos + EltWidth);
10684     else if (auto *CN = dyn_cast<ConstantSDNode>(OpVal))
10685       SplatValue.insertBits(CN->getAPIntValue().zextOrTrunc(EltWidth), BitPos);
10686     else if (auto *CN = dyn_cast<ConstantFPSDNode>(OpVal))
10687       SplatValue.insertBits(CN->getValueAPF().bitcastToAPInt(), BitPos);
10688     else
10689       return false;
10690   }
10691 
10692   // The build_vector is all constants or undefs. Find the smallest element
10693   // size that splats the vector.
10694   HasAnyUndefs = (SplatUndef != 0);
10695 
10696   // FIXME: This does not work for vectors with elements less than 8 bits.
10697   while (VecWidth > 8) {
10698     unsigned HalfSize = VecWidth / 2;
10699     APInt HighValue = SplatValue.extractBits(HalfSize, HalfSize);
10700     APInt LowValue = SplatValue.extractBits(HalfSize, 0);
10701     APInt HighUndef = SplatUndef.extractBits(HalfSize, HalfSize);
10702     APInt LowUndef = SplatUndef.extractBits(HalfSize, 0);
10703 
10704     // If the two halves do not match (ignoring undef bits), stop here.
10705     if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) ||
10706         MinSplatBits > HalfSize)
10707       break;
10708 
10709     SplatValue = HighValue | LowValue;
10710     SplatUndef = HighUndef & LowUndef;
10711 
10712     VecWidth = HalfSize;
10713   }
10714 
10715   SplatBitSize = VecWidth;
10716   return true;
10717 }
10718 
10719 SDValue BuildVectorSDNode::getSplatValue(const APInt &DemandedElts,
10720                                          BitVector *UndefElements) const {
10721   unsigned NumOps = getNumOperands();
10722   if (UndefElements) {
10723     UndefElements->clear();
10724     UndefElements->resize(NumOps);
10725   }
10726   assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size");
10727   if (!DemandedElts)
10728     return SDValue();
10729   SDValue Splatted;
10730   for (unsigned i = 0; i != NumOps; ++i) {
10731     if (!DemandedElts[i])
10732       continue;
10733     SDValue Op = getOperand(i);
10734     if (Op.isUndef()) {
10735       if (UndefElements)
10736         (*UndefElements)[i] = true;
10737     } else if (!Splatted) {
10738       Splatted = Op;
10739     } else if (Splatted != Op) {
10740       return SDValue();
10741     }
10742   }
10743 
10744   if (!Splatted) {
10745     unsigned FirstDemandedIdx = DemandedElts.countTrailingZeros();
10746     assert(getOperand(FirstDemandedIdx).isUndef() &&
10747            "Can only have a splat without a constant for all undefs.");
10748     return getOperand(FirstDemandedIdx);
10749   }
10750 
10751   return Splatted;
10752 }
10753 
10754 SDValue BuildVectorSDNode::getSplatValue(BitVector *UndefElements) const {
10755   APInt DemandedElts = APInt::getAllOnes(getNumOperands());
10756   return getSplatValue(DemandedElts, UndefElements);
10757 }
10758 
10759 bool BuildVectorSDNode::getRepeatedSequence(const APInt &DemandedElts,
10760                                             SmallVectorImpl<SDValue> &Sequence,
10761                                             BitVector *UndefElements) const {
10762   unsigned NumOps = getNumOperands();
10763   Sequence.clear();
10764   if (UndefElements) {
10765     UndefElements->clear();
10766     UndefElements->resize(NumOps);
10767   }
10768   assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size");
10769   if (!DemandedElts || NumOps < 2 || !isPowerOf2_32(NumOps))
10770     return false;
10771 
10772   // Set the undefs even if we don't find a sequence (like getSplatValue).
10773   if (UndefElements)
10774     for (unsigned I = 0; I != NumOps; ++I)
10775       if (DemandedElts[I] && getOperand(I).isUndef())
10776         (*UndefElements)[I] = true;
10777 
10778   // Iteratively widen the sequence length looking for repetitions.
10779   for (unsigned SeqLen = 1; SeqLen < NumOps; SeqLen *= 2) {
10780     Sequence.append(SeqLen, SDValue());
10781     for (unsigned I = 0; I != NumOps; ++I) {
10782       if (!DemandedElts[I])
10783         continue;
10784       SDValue &SeqOp = Sequence[I % SeqLen];
10785       SDValue Op = getOperand(I);
10786       if (Op.isUndef()) {
10787         if (!SeqOp)
10788           SeqOp = Op;
10789         continue;
10790       }
10791       if (SeqOp && !SeqOp.isUndef() && SeqOp != Op) {
10792         Sequence.clear();
10793         break;
10794       }
10795       SeqOp = Op;
10796     }
10797     if (!Sequence.empty())
10798       return true;
10799   }
10800 
10801   assert(Sequence.empty() && "Failed to empty non-repeating sequence pattern");
10802   return false;
10803 }
10804 
10805 bool BuildVectorSDNode::getRepeatedSequence(SmallVectorImpl<SDValue> &Sequence,
10806                                             BitVector *UndefElements) const {
10807   APInt DemandedElts = APInt::getAllOnes(getNumOperands());
10808   return getRepeatedSequence(DemandedElts, Sequence, UndefElements);
10809 }
10810 
10811 ConstantSDNode *
10812 BuildVectorSDNode::getConstantSplatNode(const APInt &DemandedElts,
10813                                         BitVector *UndefElements) const {
10814   return dyn_cast_or_null<ConstantSDNode>(
10815       getSplatValue(DemandedElts, UndefElements));
10816 }
10817 
10818 ConstantSDNode *
10819 BuildVectorSDNode::getConstantSplatNode(BitVector *UndefElements) const {
10820   return dyn_cast_or_null<ConstantSDNode>(getSplatValue(UndefElements));
10821 }
10822 
10823 ConstantFPSDNode *
10824 BuildVectorSDNode::getConstantFPSplatNode(const APInt &DemandedElts,
10825                                           BitVector *UndefElements) const {
10826   return dyn_cast_or_null<ConstantFPSDNode>(
10827       getSplatValue(DemandedElts, UndefElements));
10828 }
10829 
10830 ConstantFPSDNode *
10831 BuildVectorSDNode::getConstantFPSplatNode(BitVector *UndefElements) const {
10832   return dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements));
10833 }
10834 
10835 int32_t
10836 BuildVectorSDNode::getConstantFPSplatPow2ToLog2Int(BitVector *UndefElements,
10837                                                    uint32_t BitWidth) const {
10838   if (ConstantFPSDNode *CN =
10839           dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements))) {
10840     bool IsExact;
10841     APSInt IntVal(BitWidth);
10842     const APFloat &APF = CN->getValueAPF();
10843     if (APF.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) !=
10844             APFloat::opOK ||
10845         !IsExact)
10846       return -1;
10847 
10848     return IntVal.exactLogBase2();
10849   }
10850   return -1;
10851 }
10852 
10853 bool BuildVectorSDNode::getConstantRawBits(
10854     bool IsLittleEndian, unsigned DstEltSizeInBits,
10855     SmallVectorImpl<APInt> &RawBitElements, BitVector &UndefElements) const {
10856   // Early-out if this contains anything but Undef/Constant/ConstantFP.
10857   if (!isConstant())
10858     return false;
10859 
10860   unsigned NumSrcOps = getNumOperands();
10861   unsigned SrcEltSizeInBits = getValueType(0).getScalarSizeInBits();
10862   assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 &&
10863          "Invalid bitcast scale");
10864 
10865   // Extract raw src bits.
10866   SmallVector<APInt> SrcBitElements(NumSrcOps,
10867                                     APInt::getNullValue(SrcEltSizeInBits));
10868   BitVector SrcUndeElements(NumSrcOps, false);
10869 
10870   for (unsigned I = 0; I != NumSrcOps; ++I) {
10871     SDValue Op = getOperand(I);
10872     if (Op.isUndef()) {
10873       SrcUndeElements.set(I);
10874       continue;
10875     }
10876     auto *CInt = dyn_cast<ConstantSDNode>(Op);
10877     auto *CFP = dyn_cast<ConstantFPSDNode>(Op);
10878     assert((CInt || CFP) && "Unknown constant");
10879     SrcBitElements[I] =
10880         CInt ? CInt->getAPIntValue().truncOrSelf(SrcEltSizeInBits)
10881              : CFP->getValueAPF().bitcastToAPInt();
10882   }
10883 
10884   // Recast to dst width.
10885   recastRawBits(IsLittleEndian, DstEltSizeInBits, RawBitElements,
10886                 SrcBitElements, UndefElements, SrcUndeElements);
10887   return true;
10888 }
10889 
10890 void BuildVectorSDNode::recastRawBits(bool IsLittleEndian,
10891                                       unsigned DstEltSizeInBits,
10892                                       SmallVectorImpl<APInt> &DstBitElements,
10893                                       ArrayRef<APInt> SrcBitElements,
10894                                       BitVector &DstUndefElements,
10895                                       const BitVector &SrcUndefElements) {
10896   unsigned NumSrcOps = SrcBitElements.size();
10897   unsigned SrcEltSizeInBits = SrcBitElements[0].getBitWidth();
10898   assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 &&
10899          "Invalid bitcast scale");
10900   assert(NumSrcOps == SrcUndefElements.size() &&
10901          "Vector size mismatch");
10902 
10903   unsigned NumDstOps = (NumSrcOps * SrcEltSizeInBits) / DstEltSizeInBits;
10904   DstUndefElements.clear();
10905   DstUndefElements.resize(NumDstOps, false);
10906   DstBitElements.assign(NumDstOps, APInt::getNullValue(DstEltSizeInBits));
10907 
10908   // Concatenate src elements constant bits together into dst element.
10909   if (SrcEltSizeInBits <= DstEltSizeInBits) {
10910     unsigned Scale = DstEltSizeInBits / SrcEltSizeInBits;
10911     for (unsigned I = 0; I != NumDstOps; ++I) {
10912       DstUndefElements.set(I);
10913       APInt &DstBits = DstBitElements[I];
10914       for (unsigned J = 0; J != Scale; ++J) {
10915         unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1));
10916         if (SrcUndefElements[Idx])
10917           continue;
10918         DstUndefElements.reset(I);
10919         const APInt &SrcBits = SrcBitElements[Idx];
10920         assert(SrcBits.getBitWidth() == SrcEltSizeInBits &&
10921                "Illegal constant bitwidths");
10922         DstBits.insertBits(SrcBits, J * SrcEltSizeInBits);
10923       }
10924     }
10925     return;
10926   }
10927 
10928   // Split src element constant bits into dst elements.
10929   unsigned Scale = SrcEltSizeInBits / DstEltSizeInBits;
10930   for (unsigned I = 0; I != NumSrcOps; ++I) {
10931     if (SrcUndefElements[I]) {
10932       DstUndefElements.set(I * Scale, (I + 1) * Scale);
10933       continue;
10934     }
10935     const APInt &SrcBits = SrcBitElements[I];
10936     for (unsigned J = 0; J != Scale; ++J) {
10937       unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1));
10938       APInt &DstBits = DstBitElements[Idx];
10939       DstBits = SrcBits.extractBits(DstEltSizeInBits, J * DstEltSizeInBits);
10940     }
10941   }
10942 }
10943 
10944 bool BuildVectorSDNode::isConstant() const {
10945   for (const SDValue &Op : op_values()) {
10946     unsigned Opc = Op.getOpcode();
10947     if (Opc != ISD::UNDEF && Opc != ISD::Constant && Opc != ISD::ConstantFP)
10948       return false;
10949   }
10950   return true;
10951 }
10952 
10953 bool ShuffleVectorSDNode::isSplatMask(const int *Mask, EVT VT) {
10954   // Find the first non-undef value in the shuffle mask.
10955   unsigned i, e;
10956   for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i)
10957     /* search */;
10958 
10959   // If all elements are undefined, this shuffle can be considered a splat
10960   // (although it should eventually get simplified away completely).
10961   if (i == e)
10962     return true;
10963 
10964   // Make sure all remaining elements are either undef or the same as the first
10965   // non-undef value.
10966   for (int Idx = Mask[i]; i != e; ++i)
10967     if (Mask[i] >= 0 && Mask[i] != Idx)
10968       return false;
10969   return true;
10970 }
10971 
10972 // Returns the SDNode if it is a constant integer BuildVector
10973 // or constant integer.
10974 SDNode *SelectionDAG::isConstantIntBuildVectorOrConstantInt(SDValue N) const {
10975   if (isa<ConstantSDNode>(N))
10976     return N.getNode();
10977   if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
10978     return N.getNode();
10979   // Treat a GlobalAddress supporting constant offset folding as a
10980   // constant integer.
10981   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N))
10982     if (GA->getOpcode() == ISD::GlobalAddress &&
10983         TLI->isOffsetFoldingLegal(GA))
10984       return GA;
10985   if ((N.getOpcode() == ISD::SPLAT_VECTOR) &&
10986       isa<ConstantSDNode>(N.getOperand(0)))
10987     return N.getNode();
10988   return nullptr;
10989 }
10990 
10991 // Returns the SDNode if it is a constant float BuildVector
10992 // or constant float.
10993 SDNode *SelectionDAG::isConstantFPBuildVectorOrConstantFP(SDValue N) const {
10994   if (isa<ConstantFPSDNode>(N))
10995     return N.getNode();
10996 
10997   if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
10998     return N.getNode();
10999 
11000   return nullptr;
11001 }
11002 
11003 void SelectionDAG::createOperands(SDNode *Node, ArrayRef<SDValue> Vals) {
11004   assert(!Node->OperandList && "Node already has operands");
11005   assert(SDNode::getMaxNumOperands() >= Vals.size() &&
11006          "too many operands to fit into SDNode");
11007   SDUse *Ops = OperandRecycler.allocate(
11008       ArrayRecycler<SDUse>::Capacity::get(Vals.size()), OperandAllocator);
11009 
11010   bool IsDivergent = false;
11011   for (unsigned I = 0; I != Vals.size(); ++I) {
11012     Ops[I].setUser(Node);
11013     Ops[I].setInitial(Vals[I]);
11014     if (Ops[I].Val.getValueType() != MVT::Other) // Skip Chain. It does not carry divergence.
11015       IsDivergent |= Ops[I].getNode()->isDivergent();
11016   }
11017   Node->NumOperands = Vals.size();
11018   Node->OperandList = Ops;
11019   if (!TLI->isSDNodeAlwaysUniform(Node)) {
11020     IsDivergent |= TLI->isSDNodeSourceOfDivergence(Node, FLI, DA);
11021     Node->SDNodeBits.IsDivergent = IsDivergent;
11022   }
11023   checkForCycles(Node);
11024 }
11025 
11026 SDValue SelectionDAG::getTokenFactor(const SDLoc &DL,
11027                                      SmallVectorImpl<SDValue> &Vals) {
11028   size_t Limit = SDNode::getMaxNumOperands();
11029   while (Vals.size() > Limit) {
11030     unsigned SliceIdx = Vals.size() - Limit;
11031     auto ExtractedTFs = ArrayRef<SDValue>(Vals).slice(SliceIdx, Limit);
11032     SDValue NewTF = getNode(ISD::TokenFactor, DL, MVT::Other, ExtractedTFs);
11033     Vals.erase(Vals.begin() + SliceIdx, Vals.end());
11034     Vals.emplace_back(NewTF);
11035   }
11036   return getNode(ISD::TokenFactor, DL, MVT::Other, Vals);
11037 }
11038 
11039 SDValue SelectionDAG::getNeutralElement(unsigned Opcode, const SDLoc &DL,
11040                                         EVT VT, SDNodeFlags Flags) {
11041   switch (Opcode) {
11042   default:
11043     return SDValue();
11044   case ISD::ADD:
11045   case ISD::OR:
11046   case ISD::XOR:
11047   case ISD::UMAX:
11048     return getConstant(0, DL, VT);
11049   case ISD::MUL:
11050     return getConstant(1, DL, VT);
11051   case ISD::AND:
11052   case ISD::UMIN:
11053     return getAllOnesConstant(DL, VT);
11054   case ISD::SMAX:
11055     return getConstant(APInt::getSignedMinValue(VT.getSizeInBits()), DL, VT);
11056   case ISD::SMIN:
11057     return getConstant(APInt::getSignedMaxValue(VT.getSizeInBits()), DL, VT);
11058   case ISD::FADD:
11059     return getConstantFP(-0.0, DL, VT);
11060   case ISD::FMUL:
11061     return getConstantFP(1.0, DL, VT);
11062   case ISD::FMINNUM:
11063   case ISD::FMAXNUM: {
11064     // Neutral element for fminnum is NaN, Inf or FLT_MAX, depending on FMF.
11065     const fltSemantics &Semantics = EVTToAPFloatSemantics(VT);
11066     APFloat NeutralAF = !Flags.hasNoNaNs() ? APFloat::getQNaN(Semantics) :
11067                         !Flags.hasNoInfs() ? APFloat::getInf(Semantics) :
11068                         APFloat::getLargest(Semantics);
11069     if (Opcode == ISD::FMAXNUM)
11070       NeutralAF.changeSign();
11071 
11072     return getConstantFP(NeutralAF, DL, VT);
11073   }
11074   }
11075 }
11076 
11077 #ifndef NDEBUG
11078 static void checkForCyclesHelper(const SDNode *N,
11079                                  SmallPtrSetImpl<const SDNode*> &Visited,
11080                                  SmallPtrSetImpl<const SDNode*> &Checked,
11081                                  const llvm::SelectionDAG *DAG) {
11082   // If this node has already been checked, don't check it again.
11083   if (Checked.count(N))
11084     return;
11085 
11086   // If a node has already been visited on this depth-first walk, reject it as
11087   // a cycle.
11088   if (!Visited.insert(N).second) {
11089     errs() << "Detected cycle in SelectionDAG\n";
11090     dbgs() << "Offending node:\n";
11091     N->dumprFull(DAG); dbgs() << "\n";
11092     abort();
11093   }
11094 
11095   for (const SDValue &Op : N->op_values())
11096     checkForCyclesHelper(Op.getNode(), Visited, Checked, DAG);
11097 
11098   Checked.insert(N);
11099   Visited.erase(N);
11100 }
11101 #endif
11102 
11103 void llvm::checkForCycles(const llvm::SDNode *N,
11104                           const llvm::SelectionDAG *DAG,
11105                           bool force) {
11106 #ifndef NDEBUG
11107   bool check = force;
11108 #ifdef EXPENSIVE_CHECKS
11109   check = true;
11110 #endif  // EXPENSIVE_CHECKS
11111   if (check) {
11112     assert(N && "Checking nonexistent SDNode");
11113     SmallPtrSet<const SDNode*, 32> visited;
11114     SmallPtrSet<const SDNode*, 32> checked;
11115     checkForCyclesHelper(N, visited, checked, DAG);
11116   }
11117 #endif  // !NDEBUG
11118 }
11119 
11120 void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) {
11121   checkForCycles(DAG->getRoot().getNode(), DAG, force);
11122 }
11123