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(VPSD, ...)                                    \
410   case ISD::VPSD:                                                              \
411     return true;
412 #include "llvm/IR/VPIntrinsics.def"
413   }
414 }
415 
416 bool ISD::isVPBinaryOp(unsigned Opcode) {
417   switch (Opcode) {
418   default:
419     break;
420 #define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) case ISD::VPSD:
421 #define VP_PROPERTY_BINARYOP return true;
422 #define END_REGISTER_VP_SDNODE(VPSD) break;
423 #include "llvm/IR/VPIntrinsics.def"
424   }
425   return false;
426 }
427 
428 bool ISD::isVPReduction(unsigned Opcode) {
429   switch (Opcode) {
430   default:
431     break;
432 #define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) case ISD::VPSD:
433 #define VP_PROPERTY_REDUCTION(STARTPOS, ...) return true;
434 #define END_REGISTER_VP_SDNODE(VPSD) break;
435 #include "llvm/IR/VPIntrinsics.def"
436   }
437   return false;
438 }
439 
440 /// The operand position of the vector mask.
441 Optional<unsigned> ISD::getVPMaskIdx(unsigned Opcode) {
442   switch (Opcode) {
443   default:
444     return None;
445 #define BEGIN_REGISTER_VP_SDNODE(VPSD, LEGALPOS, TDNAME, MASKPOS, ...)         \
446   case ISD::VPSD:                                                              \
447     return MASKPOS;
448 #include "llvm/IR/VPIntrinsics.def"
449   }
450 }
451 
452 /// The operand position of the explicit vector length parameter.
453 Optional<unsigned> ISD::getVPExplicitVectorLengthIdx(unsigned Opcode) {
454   switch (Opcode) {
455   default:
456     return None;
457 #define BEGIN_REGISTER_VP_SDNODE(VPSD, LEGALPOS, TDNAME, MASKPOS, EVLPOS)      \
458   case ISD::VPSD:                                                              \
459     return EVLPOS;
460 #include "llvm/IR/VPIntrinsics.def"
461   }
462 }
463 
464 ISD::NodeType ISD::getExtForLoadExtType(bool IsFP, ISD::LoadExtType ExtType) {
465   switch (ExtType) {
466   case ISD::EXTLOAD:
467     return IsFP ? ISD::FP_EXTEND : ISD::ANY_EXTEND;
468   case ISD::SEXTLOAD:
469     return ISD::SIGN_EXTEND;
470   case ISD::ZEXTLOAD:
471     return ISD::ZERO_EXTEND;
472   default:
473     break;
474   }
475 
476   llvm_unreachable("Invalid LoadExtType");
477 }
478 
479 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) {
480   // To perform this operation, we just need to swap the L and G bits of the
481   // operation.
482   unsigned OldL = (Operation >> 2) & 1;
483   unsigned OldG = (Operation >> 1) & 1;
484   return ISD::CondCode((Operation & ~6) |  // Keep the N, U, E bits
485                        (OldL << 1) |       // New G bit
486                        (OldG << 2));       // New L bit.
487 }
488 
489 static ISD::CondCode getSetCCInverseImpl(ISD::CondCode Op, bool isIntegerLike) {
490   unsigned Operation = Op;
491   if (isIntegerLike)
492     Operation ^= 7;   // Flip L, G, E bits, but not U.
493   else
494     Operation ^= 15;  // Flip all of the condition bits.
495 
496   if (Operation > ISD::SETTRUE2)
497     Operation &= ~8;  // Don't let N and U bits get set.
498 
499   return ISD::CondCode(Operation);
500 }
501 
502 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, EVT Type) {
503   return getSetCCInverseImpl(Op, Type.isInteger());
504 }
505 
506 ISD::CondCode ISD::GlobalISel::getSetCCInverse(ISD::CondCode Op,
507                                                bool isIntegerLike) {
508   return getSetCCInverseImpl(Op, isIntegerLike);
509 }
510 
511 /// For an integer comparison, return 1 if the comparison is a signed operation
512 /// and 2 if the result is an unsigned comparison. Return zero if the operation
513 /// does not depend on the sign of the input (setne and seteq).
514 static int isSignedOp(ISD::CondCode Opcode) {
515   switch (Opcode) {
516   default: llvm_unreachable("Illegal integer setcc operation!");
517   case ISD::SETEQ:
518   case ISD::SETNE: return 0;
519   case ISD::SETLT:
520   case ISD::SETLE:
521   case ISD::SETGT:
522   case ISD::SETGE: return 1;
523   case ISD::SETULT:
524   case ISD::SETULE:
525   case ISD::SETUGT:
526   case ISD::SETUGE: return 2;
527   }
528 }
529 
530 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2,
531                                        EVT Type) {
532   bool IsInteger = Type.isInteger();
533   if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
534     // Cannot fold a signed integer setcc with an unsigned integer setcc.
535     return ISD::SETCC_INVALID;
536 
537   unsigned Op = Op1 | Op2;  // Combine all of the condition bits.
538 
539   // If the N and U bits get set, then the resultant comparison DOES suddenly
540   // care about orderedness, and it is true when ordered.
541   if (Op > ISD::SETTRUE2)
542     Op &= ~16;     // Clear the U bit if the N bit is set.
543 
544   // Canonicalize illegal integer setcc's.
545   if (IsInteger && Op == ISD::SETUNE)  // e.g. SETUGT | SETULT
546     Op = ISD::SETNE;
547 
548   return ISD::CondCode(Op);
549 }
550 
551 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2,
552                                         EVT Type) {
553   bool IsInteger = Type.isInteger();
554   if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
555     // Cannot fold a signed setcc with an unsigned setcc.
556     return ISD::SETCC_INVALID;
557 
558   // Combine all of the condition bits.
559   ISD::CondCode Result = ISD::CondCode(Op1 & Op2);
560 
561   // Canonicalize illegal integer setcc's.
562   if (IsInteger) {
563     switch (Result) {
564     default: break;
565     case ISD::SETUO : Result = ISD::SETFALSE; break;  // SETUGT & SETULT
566     case ISD::SETOEQ:                                 // SETEQ  & SETU[LG]E
567     case ISD::SETUEQ: Result = ISD::SETEQ   ; break;  // SETUGE & SETULE
568     case ISD::SETOLT: Result = ISD::SETULT  ; break;  // SETULT & SETNE
569     case ISD::SETOGT: Result = ISD::SETUGT  ; break;  // SETUGT & SETNE
570     }
571   }
572 
573   return Result;
574 }
575 
576 //===----------------------------------------------------------------------===//
577 //                           SDNode Profile Support
578 //===----------------------------------------------------------------------===//
579 
580 /// AddNodeIDOpcode - Add the node opcode to the NodeID data.
581 static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC)  {
582   ID.AddInteger(OpC);
583 }
584 
585 /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them
586 /// solely with their pointer.
587 static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) {
588   ID.AddPointer(VTList.VTs);
589 }
590 
591 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
592 static void AddNodeIDOperands(FoldingSetNodeID &ID,
593                               ArrayRef<SDValue> Ops) {
594   for (auto& Op : Ops) {
595     ID.AddPointer(Op.getNode());
596     ID.AddInteger(Op.getResNo());
597   }
598 }
599 
600 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
601 static void AddNodeIDOperands(FoldingSetNodeID &ID,
602                               ArrayRef<SDUse> Ops) {
603   for (auto& Op : Ops) {
604     ID.AddPointer(Op.getNode());
605     ID.AddInteger(Op.getResNo());
606   }
607 }
608 
609 static void AddNodeIDNode(FoldingSetNodeID &ID, unsigned short OpC,
610                           SDVTList VTList, ArrayRef<SDValue> OpList) {
611   AddNodeIDOpcode(ID, OpC);
612   AddNodeIDValueTypes(ID, VTList);
613   AddNodeIDOperands(ID, OpList);
614 }
615 
616 /// If this is an SDNode with special info, add this info to the NodeID data.
617 static void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N) {
618   switch (N->getOpcode()) {
619   case ISD::TargetExternalSymbol:
620   case ISD::ExternalSymbol:
621   case ISD::MCSymbol:
622     llvm_unreachable("Should only be used on nodes with operands");
623   default: break;  // Normal nodes don't need extra info.
624   case ISD::TargetConstant:
625   case ISD::Constant: {
626     const ConstantSDNode *C = cast<ConstantSDNode>(N);
627     ID.AddPointer(C->getConstantIntValue());
628     ID.AddBoolean(C->isOpaque());
629     break;
630   }
631   case ISD::TargetConstantFP:
632   case ISD::ConstantFP:
633     ID.AddPointer(cast<ConstantFPSDNode>(N)->getConstantFPValue());
634     break;
635   case ISD::TargetGlobalAddress:
636   case ISD::GlobalAddress:
637   case ISD::TargetGlobalTLSAddress:
638   case ISD::GlobalTLSAddress: {
639     const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
640     ID.AddPointer(GA->getGlobal());
641     ID.AddInteger(GA->getOffset());
642     ID.AddInteger(GA->getTargetFlags());
643     break;
644   }
645   case ISD::BasicBlock:
646     ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock());
647     break;
648   case ISD::Register:
649     ID.AddInteger(cast<RegisterSDNode>(N)->getReg());
650     break;
651   case ISD::RegisterMask:
652     ID.AddPointer(cast<RegisterMaskSDNode>(N)->getRegMask());
653     break;
654   case ISD::SRCVALUE:
655     ID.AddPointer(cast<SrcValueSDNode>(N)->getValue());
656     break;
657   case ISD::FrameIndex:
658   case ISD::TargetFrameIndex:
659     ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex());
660     break;
661   case ISD::LIFETIME_START:
662   case ISD::LIFETIME_END:
663     if (cast<LifetimeSDNode>(N)->hasOffset()) {
664       ID.AddInteger(cast<LifetimeSDNode>(N)->getSize());
665       ID.AddInteger(cast<LifetimeSDNode>(N)->getOffset());
666     }
667     break;
668   case ISD::PSEUDO_PROBE:
669     ID.AddInteger(cast<PseudoProbeSDNode>(N)->getGuid());
670     ID.AddInteger(cast<PseudoProbeSDNode>(N)->getIndex());
671     ID.AddInteger(cast<PseudoProbeSDNode>(N)->getAttributes());
672     break;
673   case ISD::JumpTable:
674   case ISD::TargetJumpTable:
675     ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex());
676     ID.AddInteger(cast<JumpTableSDNode>(N)->getTargetFlags());
677     break;
678   case ISD::ConstantPool:
679   case ISD::TargetConstantPool: {
680     const ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N);
681     ID.AddInteger(CP->getAlign().value());
682     ID.AddInteger(CP->getOffset());
683     if (CP->isMachineConstantPoolEntry())
684       CP->getMachineCPVal()->addSelectionDAGCSEId(ID);
685     else
686       ID.AddPointer(CP->getConstVal());
687     ID.AddInteger(CP->getTargetFlags());
688     break;
689   }
690   case ISD::TargetIndex: {
691     const TargetIndexSDNode *TI = cast<TargetIndexSDNode>(N);
692     ID.AddInteger(TI->getIndex());
693     ID.AddInteger(TI->getOffset());
694     ID.AddInteger(TI->getTargetFlags());
695     break;
696   }
697   case ISD::LOAD: {
698     const LoadSDNode *LD = cast<LoadSDNode>(N);
699     ID.AddInteger(LD->getMemoryVT().getRawBits());
700     ID.AddInteger(LD->getRawSubclassData());
701     ID.AddInteger(LD->getPointerInfo().getAddrSpace());
702     break;
703   }
704   case ISD::STORE: {
705     const StoreSDNode *ST = cast<StoreSDNode>(N);
706     ID.AddInteger(ST->getMemoryVT().getRawBits());
707     ID.AddInteger(ST->getRawSubclassData());
708     ID.AddInteger(ST->getPointerInfo().getAddrSpace());
709     break;
710   }
711   case ISD::VP_LOAD: {
712     const VPLoadSDNode *ELD = cast<VPLoadSDNode>(N);
713     ID.AddInteger(ELD->getMemoryVT().getRawBits());
714     ID.AddInteger(ELD->getRawSubclassData());
715     ID.AddInteger(ELD->getPointerInfo().getAddrSpace());
716     break;
717   }
718   case ISD::VP_STORE: {
719     const VPStoreSDNode *EST = cast<VPStoreSDNode>(N);
720     ID.AddInteger(EST->getMemoryVT().getRawBits());
721     ID.AddInteger(EST->getRawSubclassData());
722     ID.AddInteger(EST->getPointerInfo().getAddrSpace());
723     break;
724   }
725   case ISD::VP_GATHER: {
726     const VPGatherSDNode *EG = cast<VPGatherSDNode>(N);
727     ID.AddInteger(EG->getMemoryVT().getRawBits());
728     ID.AddInteger(EG->getRawSubclassData());
729     ID.AddInteger(EG->getPointerInfo().getAddrSpace());
730     break;
731   }
732   case ISD::VP_SCATTER: {
733     const VPScatterSDNode *ES = cast<VPScatterSDNode>(N);
734     ID.AddInteger(ES->getMemoryVT().getRawBits());
735     ID.AddInteger(ES->getRawSubclassData());
736     ID.AddInteger(ES->getPointerInfo().getAddrSpace());
737     break;
738   }
739   case ISD::MLOAD: {
740     const MaskedLoadSDNode *MLD = cast<MaskedLoadSDNode>(N);
741     ID.AddInteger(MLD->getMemoryVT().getRawBits());
742     ID.AddInteger(MLD->getRawSubclassData());
743     ID.AddInteger(MLD->getPointerInfo().getAddrSpace());
744     break;
745   }
746   case ISD::MSTORE: {
747     const MaskedStoreSDNode *MST = cast<MaskedStoreSDNode>(N);
748     ID.AddInteger(MST->getMemoryVT().getRawBits());
749     ID.AddInteger(MST->getRawSubclassData());
750     ID.AddInteger(MST->getPointerInfo().getAddrSpace());
751     break;
752   }
753   case ISD::MGATHER: {
754     const MaskedGatherSDNode *MG = cast<MaskedGatherSDNode>(N);
755     ID.AddInteger(MG->getMemoryVT().getRawBits());
756     ID.AddInteger(MG->getRawSubclassData());
757     ID.AddInteger(MG->getPointerInfo().getAddrSpace());
758     break;
759   }
760   case ISD::MSCATTER: {
761     const MaskedScatterSDNode *MS = cast<MaskedScatterSDNode>(N);
762     ID.AddInteger(MS->getMemoryVT().getRawBits());
763     ID.AddInteger(MS->getRawSubclassData());
764     ID.AddInteger(MS->getPointerInfo().getAddrSpace());
765     break;
766   }
767   case ISD::ATOMIC_CMP_SWAP:
768   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
769   case ISD::ATOMIC_SWAP:
770   case ISD::ATOMIC_LOAD_ADD:
771   case ISD::ATOMIC_LOAD_SUB:
772   case ISD::ATOMIC_LOAD_AND:
773   case ISD::ATOMIC_LOAD_CLR:
774   case ISD::ATOMIC_LOAD_OR:
775   case ISD::ATOMIC_LOAD_XOR:
776   case ISD::ATOMIC_LOAD_NAND:
777   case ISD::ATOMIC_LOAD_MIN:
778   case ISD::ATOMIC_LOAD_MAX:
779   case ISD::ATOMIC_LOAD_UMIN:
780   case ISD::ATOMIC_LOAD_UMAX:
781   case ISD::ATOMIC_LOAD:
782   case ISD::ATOMIC_STORE: {
783     const AtomicSDNode *AT = cast<AtomicSDNode>(N);
784     ID.AddInteger(AT->getMemoryVT().getRawBits());
785     ID.AddInteger(AT->getRawSubclassData());
786     ID.AddInteger(AT->getPointerInfo().getAddrSpace());
787     break;
788   }
789   case ISD::PREFETCH: {
790     const MemSDNode *PF = cast<MemSDNode>(N);
791     ID.AddInteger(PF->getPointerInfo().getAddrSpace());
792     break;
793   }
794   case ISD::VECTOR_SHUFFLE: {
795     const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
796     for (unsigned i = 0, e = N->getValueType(0).getVectorNumElements();
797          i != e; ++i)
798       ID.AddInteger(SVN->getMaskElt(i));
799     break;
800   }
801   case ISD::TargetBlockAddress:
802   case ISD::BlockAddress: {
803     const BlockAddressSDNode *BA = cast<BlockAddressSDNode>(N);
804     ID.AddPointer(BA->getBlockAddress());
805     ID.AddInteger(BA->getOffset());
806     ID.AddInteger(BA->getTargetFlags());
807     break;
808   }
809   } // end switch (N->getOpcode())
810 
811   // Target specific memory nodes could also have address spaces to check.
812   if (N->isTargetMemoryOpcode())
813     ID.AddInteger(cast<MemSDNode>(N)->getPointerInfo().getAddrSpace());
814 }
815 
816 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID
817 /// data.
818 static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) {
819   AddNodeIDOpcode(ID, N->getOpcode());
820   // Add the return value info.
821   AddNodeIDValueTypes(ID, N->getVTList());
822   // Add the operand info.
823   AddNodeIDOperands(ID, N->ops());
824 
825   // Handle SDNode leafs with special info.
826   AddNodeIDCustom(ID, N);
827 }
828 
829 //===----------------------------------------------------------------------===//
830 //                              SelectionDAG Class
831 //===----------------------------------------------------------------------===//
832 
833 /// doNotCSE - Return true if CSE should not be performed for this node.
834 static bool doNotCSE(SDNode *N) {
835   if (N->getValueType(0) == MVT::Glue)
836     return true; // Never CSE anything that produces a flag.
837 
838   switch (N->getOpcode()) {
839   default: break;
840   case ISD::HANDLENODE:
841   case ISD::EH_LABEL:
842     return true;   // Never CSE these nodes.
843   }
844 
845   // Check that remaining values produced are not flags.
846   for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
847     if (N->getValueType(i) == MVT::Glue)
848       return true; // Never CSE anything that produces a flag.
849 
850   return false;
851 }
852 
853 /// RemoveDeadNodes - This method deletes all unreachable nodes in the
854 /// SelectionDAG.
855 void SelectionDAG::RemoveDeadNodes() {
856   // Create a dummy node (which is not added to allnodes), that adds a reference
857   // to the root node, preventing it from being deleted.
858   HandleSDNode Dummy(getRoot());
859 
860   SmallVector<SDNode*, 128> DeadNodes;
861 
862   // Add all obviously-dead nodes to the DeadNodes worklist.
863   for (SDNode &Node : allnodes())
864     if (Node.use_empty())
865       DeadNodes.push_back(&Node);
866 
867   RemoveDeadNodes(DeadNodes);
868 
869   // If the root changed (e.g. it was a dead load, update the root).
870   setRoot(Dummy.getValue());
871 }
872 
873 /// RemoveDeadNodes - This method deletes the unreachable nodes in the
874 /// given list, and any nodes that become unreachable as a result.
875 void SelectionDAG::RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes) {
876 
877   // Process the worklist, deleting the nodes and adding their uses to the
878   // worklist.
879   while (!DeadNodes.empty()) {
880     SDNode *N = DeadNodes.pop_back_val();
881     // Skip to next node if we've already managed to delete the node. This could
882     // happen if replacing a node causes a node previously added to the node to
883     // be deleted.
884     if (N->getOpcode() == ISD::DELETED_NODE)
885       continue;
886 
887     for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
888       DUL->NodeDeleted(N, nullptr);
889 
890     // Take the node out of the appropriate CSE map.
891     RemoveNodeFromCSEMaps(N);
892 
893     // Next, brutally remove the operand list.  This is safe to do, as there are
894     // no cycles in the graph.
895     for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
896       SDUse &Use = *I++;
897       SDNode *Operand = Use.getNode();
898       Use.set(SDValue());
899 
900       // Now that we removed this operand, see if there are no uses of it left.
901       if (Operand->use_empty())
902         DeadNodes.push_back(Operand);
903     }
904 
905     DeallocateNode(N);
906   }
907 }
908 
909 void SelectionDAG::RemoveDeadNode(SDNode *N){
910   SmallVector<SDNode*, 16> DeadNodes(1, N);
911 
912   // Create a dummy node that adds a reference to the root node, preventing
913   // it from being deleted.  (This matters if the root is an operand of the
914   // dead node.)
915   HandleSDNode Dummy(getRoot());
916 
917   RemoveDeadNodes(DeadNodes);
918 }
919 
920 void SelectionDAG::DeleteNode(SDNode *N) {
921   // First take this out of the appropriate CSE map.
922   RemoveNodeFromCSEMaps(N);
923 
924   // Finally, remove uses due to operands of this node, remove from the
925   // AllNodes list, and delete the node.
926   DeleteNodeNotInCSEMaps(N);
927 }
928 
929 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
930   assert(N->getIterator() != AllNodes.begin() &&
931          "Cannot delete the entry node!");
932   assert(N->use_empty() && "Cannot delete a node that is not dead!");
933 
934   // Drop all of the operands and decrement used node's use counts.
935   N->DropOperands();
936 
937   DeallocateNode(N);
938 }
939 
940 void SDDbgInfo::add(SDDbgValue *V, bool isParameter) {
941   assert(!(V->isVariadic() && isParameter));
942   if (isParameter)
943     ByvalParmDbgValues.push_back(V);
944   else
945     DbgValues.push_back(V);
946   for (const SDNode *Node : V->getSDNodes())
947     if (Node)
948       DbgValMap[Node].push_back(V);
949 }
950 
951 void SDDbgInfo::erase(const SDNode *Node) {
952   DbgValMapType::iterator I = DbgValMap.find(Node);
953   if (I == DbgValMap.end())
954     return;
955   for (auto &Val: I->second)
956     Val->setIsInvalidated();
957   DbgValMap.erase(I);
958 }
959 
960 void SelectionDAG::DeallocateNode(SDNode *N) {
961   // If we have operands, deallocate them.
962   removeOperands(N);
963 
964   NodeAllocator.Deallocate(AllNodes.remove(N));
965 
966   // Set the opcode to DELETED_NODE to help catch bugs when node
967   // memory is reallocated.
968   // FIXME: There are places in SDag that have grown a dependency on the opcode
969   // value in the released node.
970   __asan_unpoison_memory_region(&N->NodeType, sizeof(N->NodeType));
971   N->NodeType = ISD::DELETED_NODE;
972 
973   // If any of the SDDbgValue nodes refer to this SDNode, invalidate
974   // them and forget about that node.
975   DbgInfo->erase(N);
976 }
977 
978 #ifndef NDEBUG
979 /// VerifySDNode - Sanity check the given SDNode.  Aborts if it is invalid.
980 static void VerifySDNode(SDNode *N) {
981   switch (N->getOpcode()) {
982   default:
983     break;
984   case ISD::BUILD_PAIR: {
985     EVT VT = N->getValueType(0);
986     assert(N->getNumValues() == 1 && "Too many results!");
987     assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) &&
988            "Wrong return type!");
989     assert(N->getNumOperands() == 2 && "Wrong number of operands!");
990     assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() &&
991            "Mismatched operand types!");
992     assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() &&
993            "Wrong operand type!");
994     assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() &&
995            "Wrong return type size");
996     break;
997   }
998   case ISD::BUILD_VECTOR: {
999     assert(N->getNumValues() == 1 && "Too many results!");
1000     assert(N->getValueType(0).isVector() && "Wrong return type!");
1001     assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() &&
1002            "Wrong number of operands!");
1003     EVT EltVT = N->getValueType(0).getVectorElementType();
1004     for (const SDUse &Op : N->ops()) {
1005       assert((Op.getValueType() == EltVT ||
1006               (EltVT.isInteger() && Op.getValueType().isInteger() &&
1007                EltVT.bitsLE(Op.getValueType()))) &&
1008              "Wrong operand type!");
1009       assert(Op.getValueType() == N->getOperand(0).getValueType() &&
1010              "Operands must all have the same type");
1011     }
1012     break;
1013   }
1014   }
1015 }
1016 #endif // NDEBUG
1017 
1018 /// Insert a newly allocated node into the DAG.
1019 ///
1020 /// Handles insertion into the all nodes list and CSE map, as well as
1021 /// verification and other common operations when a new node is allocated.
1022 void SelectionDAG::InsertNode(SDNode *N) {
1023   AllNodes.push_back(N);
1024 #ifndef NDEBUG
1025   N->PersistentId = NextPersistentId++;
1026   VerifySDNode(N);
1027 #endif
1028   for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1029     DUL->NodeInserted(N);
1030 }
1031 
1032 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
1033 /// correspond to it.  This is useful when we're about to delete or repurpose
1034 /// the node.  We don't want future request for structurally identical nodes
1035 /// to return N anymore.
1036 bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
1037   bool Erased = false;
1038   switch (N->getOpcode()) {
1039   case ISD::HANDLENODE: return false;  // noop.
1040   case ISD::CONDCODE:
1041     assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
1042            "Cond code doesn't exist!");
1043     Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != nullptr;
1044     CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = nullptr;
1045     break;
1046   case ISD::ExternalSymbol:
1047     Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
1048     break;
1049   case ISD::TargetExternalSymbol: {
1050     ExternalSymbolSDNode *ESN = cast<ExternalSymbolSDNode>(N);
1051     Erased = TargetExternalSymbols.erase(std::pair<std::string, unsigned>(
1052         ESN->getSymbol(), ESN->getTargetFlags()));
1053     break;
1054   }
1055   case ISD::MCSymbol: {
1056     auto *MCSN = cast<MCSymbolSDNode>(N);
1057     Erased = MCSymbols.erase(MCSN->getMCSymbol());
1058     break;
1059   }
1060   case ISD::VALUETYPE: {
1061     EVT VT = cast<VTSDNode>(N)->getVT();
1062     if (VT.isExtended()) {
1063       Erased = ExtendedValueTypeNodes.erase(VT);
1064     } else {
1065       Erased = ValueTypeNodes[VT.getSimpleVT().SimpleTy] != nullptr;
1066       ValueTypeNodes[VT.getSimpleVT().SimpleTy] = nullptr;
1067     }
1068     break;
1069   }
1070   default:
1071     // Remove it from the CSE Map.
1072     assert(N->getOpcode() != ISD::DELETED_NODE && "DELETED_NODE in CSEMap!");
1073     assert(N->getOpcode() != ISD::EntryToken && "EntryToken in CSEMap!");
1074     Erased = CSEMap.RemoveNode(N);
1075     break;
1076   }
1077 #ifndef NDEBUG
1078   // Verify that the node was actually in one of the CSE maps, unless it has a
1079   // flag result (which cannot be CSE'd) or is one of the special cases that are
1080   // not subject to CSE.
1081   if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Glue &&
1082       !N->isMachineOpcode() && !doNotCSE(N)) {
1083     N->dump(this);
1084     dbgs() << "\n";
1085     llvm_unreachable("Node is not in map!");
1086   }
1087 #endif
1088   return Erased;
1089 }
1090 
1091 /// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE
1092 /// maps and modified in place. Add it back to the CSE maps, unless an identical
1093 /// node already exists, in which case transfer all its users to the existing
1094 /// node. This transfer can potentially trigger recursive merging.
1095 void
1096 SelectionDAG::AddModifiedNodeToCSEMaps(SDNode *N) {
1097   // For node types that aren't CSE'd, just act as if no identical node
1098   // already exists.
1099   if (!doNotCSE(N)) {
1100     SDNode *Existing = CSEMap.GetOrInsertNode(N);
1101     if (Existing != N) {
1102       // If there was already an existing matching node, use ReplaceAllUsesWith
1103       // to replace the dead one with the existing one.  This can cause
1104       // recursive merging of other unrelated nodes down the line.
1105       ReplaceAllUsesWith(N, Existing);
1106 
1107       // N is now dead. Inform the listeners and delete it.
1108       for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1109         DUL->NodeDeleted(N, Existing);
1110       DeleteNodeNotInCSEMaps(N);
1111       return;
1112     }
1113   }
1114 
1115   // If the node doesn't already exist, we updated it.  Inform listeners.
1116   for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1117     DUL->NodeUpdated(N);
1118 }
1119 
1120 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1121 /// were replaced with those specified.  If this node is never memoized,
1122 /// return null, otherwise return a pointer to the slot it would take.  If a
1123 /// node already exists with these operands, the slot will be non-null.
1124 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op,
1125                                            void *&InsertPos) {
1126   if (doNotCSE(N))
1127     return nullptr;
1128 
1129   SDValue Ops[] = { Op };
1130   FoldingSetNodeID ID;
1131   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1132   AddNodeIDCustom(ID, N);
1133   SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1134   if (Node)
1135     Node->intersectFlagsWith(N->getFlags());
1136   return Node;
1137 }
1138 
1139 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1140 /// were replaced with those specified.  If this node is never memoized,
1141 /// return null, otherwise return a pointer to the slot it would take.  If a
1142 /// node already exists with these operands, the slot will be non-null.
1143 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
1144                                            SDValue Op1, SDValue Op2,
1145                                            void *&InsertPos) {
1146   if (doNotCSE(N))
1147     return nullptr;
1148 
1149   SDValue Ops[] = { Op1, Op2 };
1150   FoldingSetNodeID ID;
1151   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1152   AddNodeIDCustom(ID, N);
1153   SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1154   if (Node)
1155     Node->intersectFlagsWith(N->getFlags());
1156   return Node;
1157 }
1158 
1159 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1160 /// were replaced with those specified.  If this node is never memoized,
1161 /// return null, otherwise return a pointer to the slot it would take.  If a
1162 /// node already exists with these operands, the slot will be non-null.
1163 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, ArrayRef<SDValue> Ops,
1164                                            void *&InsertPos) {
1165   if (doNotCSE(N))
1166     return nullptr;
1167 
1168   FoldingSetNodeID ID;
1169   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1170   AddNodeIDCustom(ID, N);
1171   SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1172   if (Node)
1173     Node->intersectFlagsWith(N->getFlags());
1174   return Node;
1175 }
1176 
1177 Align SelectionDAG::getEVTAlign(EVT VT) const {
1178   Type *Ty = VT == MVT::iPTR ?
1179                    PointerType::get(Type::getInt8Ty(*getContext()), 0) :
1180                    VT.getTypeForEVT(*getContext());
1181 
1182   return getDataLayout().getABITypeAlign(Ty);
1183 }
1184 
1185 // EntryNode could meaningfully have debug info if we can find it...
1186 SelectionDAG::SelectionDAG(const TargetMachine &tm, CodeGenOpt::Level OL)
1187     : TM(tm), OptLevel(OL),
1188       EntryNode(ISD::EntryToken, 0, DebugLoc(), getVTList(MVT::Other)),
1189       Root(getEntryNode()) {
1190   InsertNode(&EntryNode);
1191   DbgInfo = new SDDbgInfo();
1192 }
1193 
1194 void SelectionDAG::init(MachineFunction &NewMF,
1195                         OptimizationRemarkEmitter &NewORE,
1196                         Pass *PassPtr, const TargetLibraryInfo *LibraryInfo,
1197                         LegacyDivergenceAnalysis * Divergence,
1198                         ProfileSummaryInfo *PSIin,
1199                         BlockFrequencyInfo *BFIin) {
1200   MF = &NewMF;
1201   SDAGISelPass = PassPtr;
1202   ORE = &NewORE;
1203   TLI = getSubtarget().getTargetLowering();
1204   TSI = getSubtarget().getSelectionDAGInfo();
1205   LibInfo = LibraryInfo;
1206   Context = &MF->getFunction().getContext();
1207   DA = Divergence;
1208   PSI = PSIin;
1209   BFI = BFIin;
1210 }
1211 
1212 SelectionDAG::~SelectionDAG() {
1213   assert(!UpdateListeners && "Dangling registered DAGUpdateListeners");
1214   allnodes_clear();
1215   OperandRecycler.clear(OperandAllocator);
1216   delete DbgInfo;
1217 }
1218 
1219 bool SelectionDAG::shouldOptForSize() const {
1220   return MF->getFunction().hasOptSize() ||
1221       llvm::shouldOptimizeForSize(FLI->MBB->getBasicBlock(), PSI, BFI);
1222 }
1223 
1224 void SelectionDAG::allnodes_clear() {
1225   assert(&*AllNodes.begin() == &EntryNode);
1226   AllNodes.remove(AllNodes.begin());
1227   while (!AllNodes.empty())
1228     DeallocateNode(&AllNodes.front());
1229 #ifndef NDEBUG
1230   NextPersistentId = 0;
1231 #endif
1232 }
1233 
1234 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
1235                                           void *&InsertPos) {
1236   SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
1237   if (N) {
1238     switch (N->getOpcode()) {
1239     default: break;
1240     case ISD::Constant:
1241     case ISD::ConstantFP:
1242       llvm_unreachable("Querying for Constant and ConstantFP nodes requires "
1243                        "debug location.  Use another overload.");
1244     }
1245   }
1246   return N;
1247 }
1248 
1249 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
1250                                           const SDLoc &DL, void *&InsertPos) {
1251   SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
1252   if (N) {
1253     switch (N->getOpcode()) {
1254     case ISD::Constant:
1255     case ISD::ConstantFP:
1256       // Erase debug location from the node if the node is used at several
1257       // different places. Do not propagate one location to all uses as it
1258       // will cause a worse single stepping debugging experience.
1259       if (N->getDebugLoc() != DL.getDebugLoc())
1260         N->setDebugLoc(DebugLoc());
1261       break;
1262     default:
1263       // When the node's point of use is located earlier in the instruction
1264       // sequence than its prior point of use, update its debug info to the
1265       // earlier location.
1266       if (DL.getIROrder() && DL.getIROrder() < N->getIROrder())
1267         N->setDebugLoc(DL.getDebugLoc());
1268       break;
1269     }
1270   }
1271   return N;
1272 }
1273 
1274 void SelectionDAG::clear() {
1275   allnodes_clear();
1276   OperandRecycler.clear(OperandAllocator);
1277   OperandAllocator.Reset();
1278   CSEMap.clear();
1279 
1280   ExtendedValueTypeNodes.clear();
1281   ExternalSymbols.clear();
1282   TargetExternalSymbols.clear();
1283   MCSymbols.clear();
1284   SDCallSiteDbgInfo.clear();
1285   std::fill(CondCodeNodes.begin(), CondCodeNodes.end(),
1286             static_cast<CondCodeSDNode*>(nullptr));
1287   std::fill(ValueTypeNodes.begin(), ValueTypeNodes.end(),
1288             static_cast<SDNode*>(nullptr));
1289 
1290   EntryNode.UseList = nullptr;
1291   InsertNode(&EntryNode);
1292   Root = getEntryNode();
1293   DbgInfo->clear();
1294 }
1295 
1296 SDValue SelectionDAG::getFPExtendOrRound(SDValue Op, const SDLoc &DL, EVT VT) {
1297   return VT.bitsGT(Op.getValueType())
1298              ? getNode(ISD::FP_EXTEND, DL, VT, Op)
1299              : getNode(ISD::FP_ROUND, DL, VT, Op, getIntPtrConstant(0, DL));
1300 }
1301 
1302 std::pair<SDValue, SDValue>
1303 SelectionDAG::getStrictFPExtendOrRound(SDValue Op, SDValue Chain,
1304                                        const SDLoc &DL, EVT VT) {
1305   assert(!VT.bitsEq(Op.getValueType()) &&
1306          "Strict no-op FP extend/round not allowed.");
1307   SDValue Res =
1308       VT.bitsGT(Op.getValueType())
1309           ? getNode(ISD::STRICT_FP_EXTEND, DL, {VT, MVT::Other}, {Chain, Op})
1310           : getNode(ISD::STRICT_FP_ROUND, DL, {VT, MVT::Other},
1311                     {Chain, Op, getIntPtrConstant(0, DL)});
1312 
1313   return std::pair<SDValue, SDValue>(Res, SDValue(Res.getNode(), 1));
1314 }
1315 
1316 SDValue SelectionDAG::getAnyExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1317   return VT.bitsGT(Op.getValueType()) ?
1318     getNode(ISD::ANY_EXTEND, DL, VT, Op) :
1319     getNode(ISD::TRUNCATE, DL, VT, Op);
1320 }
1321 
1322 SDValue SelectionDAG::getSExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1323   return VT.bitsGT(Op.getValueType()) ?
1324     getNode(ISD::SIGN_EXTEND, DL, VT, Op) :
1325     getNode(ISD::TRUNCATE, DL, VT, Op);
1326 }
1327 
1328 SDValue SelectionDAG::getZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1329   return VT.bitsGT(Op.getValueType()) ?
1330     getNode(ISD::ZERO_EXTEND, DL, VT, Op) :
1331     getNode(ISD::TRUNCATE, DL, VT, Op);
1332 }
1333 
1334 SDValue SelectionDAG::getBoolExtOrTrunc(SDValue Op, const SDLoc &SL, EVT VT,
1335                                         EVT OpVT) {
1336   if (VT.bitsLE(Op.getValueType()))
1337     return getNode(ISD::TRUNCATE, SL, VT, Op);
1338 
1339   TargetLowering::BooleanContent BType = TLI->getBooleanContents(OpVT);
1340   return getNode(TLI->getExtendForContent(BType), SL, VT, Op);
1341 }
1342 
1343 SDValue SelectionDAG::getZeroExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) {
1344   EVT OpVT = Op.getValueType();
1345   assert(VT.isInteger() && OpVT.isInteger() &&
1346          "Cannot getZeroExtendInReg FP types");
1347   assert(VT.isVector() == OpVT.isVector() &&
1348          "getZeroExtendInReg type should be vector iff the operand "
1349          "type is vector!");
1350   assert((!VT.isVector() ||
1351           VT.getVectorElementCount() == OpVT.getVectorElementCount()) &&
1352          "Vector element counts must match in getZeroExtendInReg");
1353   assert(VT.bitsLE(OpVT) && "Not extending!");
1354   if (OpVT == VT)
1355     return Op;
1356   APInt Imm = APInt::getLowBitsSet(OpVT.getScalarSizeInBits(),
1357                                    VT.getScalarSizeInBits());
1358   return getNode(ISD::AND, DL, OpVT, Op, getConstant(Imm, DL, OpVT));
1359 }
1360 
1361 SDValue SelectionDAG::getPtrExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1362   // Only unsigned pointer semantics are supported right now. In the future this
1363   // might delegate to TLI to check pointer signedness.
1364   return getZExtOrTrunc(Op, DL, VT);
1365 }
1366 
1367 SDValue SelectionDAG::getPtrExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) {
1368   // Only unsigned pointer semantics are supported right now. In the future this
1369   // might delegate to TLI to check pointer signedness.
1370   return getZeroExtendInReg(Op, DL, VT);
1371 }
1372 
1373 /// getNOT - Create a bitwise NOT operation as (XOR Val, -1).
1374 SDValue SelectionDAG::getNOT(const SDLoc &DL, SDValue Val, EVT VT) {
1375   return getNode(ISD::XOR, DL, VT, Val, getAllOnesConstant(DL, VT));
1376 }
1377 
1378 SDValue SelectionDAG::getLogicalNOT(const SDLoc &DL, SDValue Val, EVT VT) {
1379   SDValue TrueValue = getBoolConstant(true, DL, VT, VT);
1380   return getNode(ISD::XOR, DL, VT, Val, TrueValue);
1381 }
1382 
1383 SDValue SelectionDAG::getBoolConstant(bool V, const SDLoc &DL, EVT VT,
1384                                       EVT OpVT) {
1385   if (!V)
1386     return getConstant(0, DL, VT);
1387 
1388   switch (TLI->getBooleanContents(OpVT)) {
1389   case TargetLowering::ZeroOrOneBooleanContent:
1390   case TargetLowering::UndefinedBooleanContent:
1391     return getConstant(1, DL, VT);
1392   case TargetLowering::ZeroOrNegativeOneBooleanContent:
1393     return getAllOnesConstant(DL, VT);
1394   }
1395   llvm_unreachable("Unexpected boolean content enum!");
1396 }
1397 
1398 SDValue SelectionDAG::getConstant(uint64_t Val, const SDLoc &DL, EVT VT,
1399                                   bool isT, bool isO) {
1400   EVT EltVT = VT.getScalarType();
1401   assert((EltVT.getSizeInBits() >= 64 ||
1402           (uint64_t)((int64_t)Val >> EltVT.getSizeInBits()) + 1 < 2) &&
1403          "getConstant with a uint64_t value that doesn't fit in the type!");
1404   return getConstant(APInt(EltVT.getSizeInBits(), Val), DL, VT, isT, isO);
1405 }
1406 
1407 SDValue SelectionDAG::getConstant(const APInt &Val, const SDLoc &DL, EVT VT,
1408                                   bool isT, bool isO) {
1409   return getConstant(*ConstantInt::get(*Context, Val), DL, VT, isT, isO);
1410 }
1411 
1412 SDValue SelectionDAG::getConstant(const ConstantInt &Val, const SDLoc &DL,
1413                                   EVT VT, bool isT, bool isO) {
1414   assert(VT.isInteger() && "Cannot create FP integer constant!");
1415 
1416   EVT EltVT = VT.getScalarType();
1417   const ConstantInt *Elt = &Val;
1418 
1419   // In some cases the vector type is legal but the element type is illegal and
1420   // needs to be promoted, for example v8i8 on ARM.  In this case, promote the
1421   // inserted value (the type does not need to match the vector element type).
1422   // Any extra bits introduced will be truncated away.
1423   if (VT.isVector() && TLI->getTypeAction(*getContext(), EltVT) ==
1424                            TargetLowering::TypePromoteInteger) {
1425     EltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1426     APInt NewVal = Elt->getValue().zextOrTrunc(EltVT.getSizeInBits());
1427     Elt = ConstantInt::get(*getContext(), NewVal);
1428   }
1429   // In other cases the element type is illegal and needs to be expanded, for
1430   // example v2i64 on MIPS32. In this case, find the nearest legal type, split
1431   // the value into n parts and use a vector type with n-times the elements.
1432   // Then bitcast to the type requested.
1433   // Legalizing constants too early makes the DAGCombiner's job harder so we
1434   // only legalize if the DAG tells us we must produce legal types.
1435   else if (NewNodesMustHaveLegalTypes && VT.isVector() &&
1436            TLI->getTypeAction(*getContext(), EltVT) ==
1437                TargetLowering::TypeExpandInteger) {
1438     const APInt &NewVal = Elt->getValue();
1439     EVT ViaEltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1440     unsigned ViaEltSizeInBits = ViaEltVT.getSizeInBits();
1441 
1442     // For scalable vectors, try to use a SPLAT_VECTOR_PARTS node.
1443     if (VT.isScalableVector()) {
1444       assert(EltVT.getSizeInBits() % ViaEltSizeInBits == 0 &&
1445              "Can only handle an even split!");
1446       unsigned Parts = EltVT.getSizeInBits() / ViaEltSizeInBits;
1447 
1448       SmallVector<SDValue, 2> ScalarParts;
1449       for (unsigned i = 0; i != Parts; ++i)
1450         ScalarParts.push_back(getConstant(
1451             NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL,
1452             ViaEltVT, isT, isO));
1453 
1454       return getNode(ISD::SPLAT_VECTOR_PARTS, DL, VT, ScalarParts);
1455     }
1456 
1457     unsigned ViaVecNumElts = VT.getSizeInBits() / ViaEltSizeInBits;
1458     EVT ViaVecVT = EVT::getVectorVT(*getContext(), ViaEltVT, ViaVecNumElts);
1459 
1460     // Check the temporary vector is the correct size. If this fails then
1461     // getTypeToTransformTo() probably returned a type whose size (in bits)
1462     // isn't a power-of-2 factor of the requested type size.
1463     assert(ViaVecVT.getSizeInBits() == VT.getSizeInBits());
1464 
1465     SmallVector<SDValue, 2> EltParts;
1466     for (unsigned i = 0; i < ViaVecNumElts / VT.getVectorNumElements(); ++i)
1467       EltParts.push_back(getConstant(
1468           NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL,
1469           ViaEltVT, isT, isO));
1470 
1471     // EltParts is currently in little endian order. If we actually want
1472     // big-endian order then reverse it now.
1473     if (getDataLayout().isBigEndian())
1474       std::reverse(EltParts.begin(), EltParts.end());
1475 
1476     // The elements must be reversed when the element order is different
1477     // to the endianness of the elements (because the BITCAST is itself a
1478     // vector shuffle in this situation). However, we do not need any code to
1479     // perform this reversal because getConstant() is producing a vector
1480     // splat.
1481     // This situation occurs in MIPS MSA.
1482 
1483     SmallVector<SDValue, 8> Ops;
1484     for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
1485       llvm::append_range(Ops, EltParts);
1486 
1487     SDValue V =
1488         getNode(ISD::BITCAST, DL, VT, getBuildVector(ViaVecVT, DL, Ops));
1489     return V;
1490   }
1491 
1492   assert(Elt->getBitWidth() == EltVT.getSizeInBits() &&
1493          "APInt size does not match type size!");
1494   unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
1495   FoldingSetNodeID ID;
1496   AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
1497   ID.AddPointer(Elt);
1498   ID.AddBoolean(isO);
1499   void *IP = nullptr;
1500   SDNode *N = nullptr;
1501   if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1502     if (!VT.isVector())
1503       return SDValue(N, 0);
1504 
1505   if (!N) {
1506     N = newSDNode<ConstantSDNode>(isT, isO, Elt, EltVT);
1507     CSEMap.InsertNode(N, IP);
1508     InsertNode(N);
1509     NewSDValueDbgMsg(SDValue(N, 0), "Creating constant: ", this);
1510   }
1511 
1512   SDValue Result(N, 0);
1513   if (VT.isScalableVector())
1514     Result = getSplatVector(VT, DL, Result);
1515   else if (VT.isVector())
1516     Result = getSplatBuildVector(VT, DL, Result);
1517 
1518   return Result;
1519 }
1520 
1521 SDValue SelectionDAG::getIntPtrConstant(uint64_t Val, const SDLoc &DL,
1522                                         bool isTarget) {
1523   return getConstant(Val, DL, TLI->getPointerTy(getDataLayout()), isTarget);
1524 }
1525 
1526 SDValue SelectionDAG::getShiftAmountConstant(uint64_t Val, EVT VT,
1527                                              const SDLoc &DL, bool LegalTypes) {
1528   assert(VT.isInteger() && "Shift amount is not an integer type!");
1529   EVT ShiftVT = TLI->getShiftAmountTy(VT, getDataLayout(), LegalTypes);
1530   return getConstant(Val, DL, ShiftVT);
1531 }
1532 
1533 SDValue SelectionDAG::getVectorIdxConstant(uint64_t Val, const SDLoc &DL,
1534                                            bool isTarget) {
1535   return getConstant(Val, DL, TLI->getVectorIdxTy(getDataLayout()), isTarget);
1536 }
1537 
1538 SDValue SelectionDAG::getConstantFP(const APFloat &V, const SDLoc &DL, EVT VT,
1539                                     bool isTarget) {
1540   return getConstantFP(*ConstantFP::get(*getContext(), V), DL, VT, isTarget);
1541 }
1542 
1543 SDValue SelectionDAG::getConstantFP(const ConstantFP &V, const SDLoc &DL,
1544                                     EVT VT, bool isTarget) {
1545   assert(VT.isFloatingPoint() && "Cannot create integer FP constant!");
1546 
1547   EVT EltVT = VT.getScalarType();
1548 
1549   // Do the map lookup using the actual bit pattern for the floating point
1550   // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
1551   // we don't have issues with SNANs.
1552   unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
1553   FoldingSetNodeID ID;
1554   AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
1555   ID.AddPointer(&V);
1556   void *IP = nullptr;
1557   SDNode *N = nullptr;
1558   if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1559     if (!VT.isVector())
1560       return SDValue(N, 0);
1561 
1562   if (!N) {
1563     N = newSDNode<ConstantFPSDNode>(isTarget, &V, EltVT);
1564     CSEMap.InsertNode(N, IP);
1565     InsertNode(N);
1566   }
1567 
1568   SDValue Result(N, 0);
1569   if (VT.isScalableVector())
1570     Result = getSplatVector(VT, DL, Result);
1571   else if (VT.isVector())
1572     Result = getSplatBuildVector(VT, DL, Result);
1573   NewSDValueDbgMsg(Result, "Creating fp constant: ", this);
1574   return Result;
1575 }
1576 
1577 SDValue SelectionDAG::getConstantFP(double Val, const SDLoc &DL, EVT VT,
1578                                     bool isTarget) {
1579   EVT EltVT = VT.getScalarType();
1580   if (EltVT == MVT::f32)
1581     return getConstantFP(APFloat((float)Val), DL, VT, isTarget);
1582   if (EltVT == MVT::f64)
1583     return getConstantFP(APFloat(Val), DL, VT, isTarget);
1584   if (EltVT == MVT::f80 || EltVT == MVT::f128 || EltVT == MVT::ppcf128 ||
1585       EltVT == MVT::f16 || EltVT == MVT::bf16) {
1586     bool Ignored;
1587     APFloat APF = APFloat(Val);
1588     APF.convert(EVTToAPFloatSemantics(EltVT), APFloat::rmNearestTiesToEven,
1589                 &Ignored);
1590     return getConstantFP(APF, DL, VT, isTarget);
1591   }
1592   llvm_unreachable("Unsupported type in getConstantFP");
1593 }
1594 
1595 SDValue SelectionDAG::getGlobalAddress(const GlobalValue *GV, const SDLoc &DL,
1596                                        EVT VT, int64_t Offset, bool isTargetGA,
1597                                        unsigned TargetFlags) {
1598   assert((TargetFlags == 0 || isTargetGA) &&
1599          "Cannot set target flags on target-independent globals");
1600 
1601   // Truncate (with sign-extension) the offset value to the pointer size.
1602   unsigned BitWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
1603   if (BitWidth < 64)
1604     Offset = SignExtend64(Offset, BitWidth);
1605 
1606   unsigned Opc;
1607   if (GV->isThreadLocal())
1608     Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress;
1609   else
1610     Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress;
1611 
1612   FoldingSetNodeID ID;
1613   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1614   ID.AddPointer(GV);
1615   ID.AddInteger(Offset);
1616   ID.AddInteger(TargetFlags);
1617   void *IP = nullptr;
1618   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
1619     return SDValue(E, 0);
1620 
1621   auto *N = newSDNode<GlobalAddressSDNode>(
1622       Opc, DL.getIROrder(), DL.getDebugLoc(), GV, VT, Offset, TargetFlags);
1623   CSEMap.InsertNode(N, IP);
1624     InsertNode(N);
1625   return SDValue(N, 0);
1626 }
1627 
1628 SDValue SelectionDAG::getFrameIndex(int FI, EVT VT, bool isTarget) {
1629   unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
1630   FoldingSetNodeID ID;
1631   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1632   ID.AddInteger(FI);
1633   void *IP = nullptr;
1634   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1635     return SDValue(E, 0);
1636 
1637   auto *N = newSDNode<FrameIndexSDNode>(FI, VT, isTarget);
1638   CSEMap.InsertNode(N, IP);
1639   InsertNode(N);
1640   return SDValue(N, 0);
1641 }
1642 
1643 SDValue SelectionDAG::getJumpTable(int JTI, EVT VT, bool isTarget,
1644                                    unsigned TargetFlags) {
1645   assert((TargetFlags == 0 || isTarget) &&
1646          "Cannot set target flags on target-independent jump tables");
1647   unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
1648   FoldingSetNodeID ID;
1649   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1650   ID.AddInteger(JTI);
1651   ID.AddInteger(TargetFlags);
1652   void *IP = nullptr;
1653   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1654     return SDValue(E, 0);
1655 
1656   auto *N = newSDNode<JumpTableSDNode>(JTI, VT, isTarget, TargetFlags);
1657   CSEMap.InsertNode(N, IP);
1658   InsertNode(N);
1659   return SDValue(N, 0);
1660 }
1661 
1662 SDValue SelectionDAG::getConstantPool(const Constant *C, EVT VT,
1663                                       MaybeAlign Alignment, int Offset,
1664                                       bool isTarget, unsigned TargetFlags) {
1665   assert((TargetFlags == 0 || isTarget) &&
1666          "Cannot set target flags on target-independent globals");
1667   if (!Alignment)
1668     Alignment = shouldOptForSize()
1669                     ? getDataLayout().getABITypeAlign(C->getType())
1670                     : getDataLayout().getPrefTypeAlign(C->getType());
1671   unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1672   FoldingSetNodeID ID;
1673   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1674   ID.AddInteger(Alignment->value());
1675   ID.AddInteger(Offset);
1676   ID.AddPointer(C);
1677   ID.AddInteger(TargetFlags);
1678   void *IP = nullptr;
1679   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1680     return SDValue(E, 0);
1681 
1682   auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment,
1683                                           TargetFlags);
1684   CSEMap.InsertNode(N, IP);
1685   InsertNode(N);
1686   SDValue V = SDValue(N, 0);
1687   NewSDValueDbgMsg(V, "Creating new constant pool: ", this);
1688   return V;
1689 }
1690 
1691 SDValue SelectionDAG::getConstantPool(MachineConstantPoolValue *C, EVT VT,
1692                                       MaybeAlign Alignment, int Offset,
1693                                       bool isTarget, unsigned TargetFlags) {
1694   assert((TargetFlags == 0 || isTarget) &&
1695          "Cannot set target flags on target-independent globals");
1696   if (!Alignment)
1697     Alignment = getDataLayout().getPrefTypeAlign(C->getType());
1698   unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1699   FoldingSetNodeID ID;
1700   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1701   ID.AddInteger(Alignment->value());
1702   ID.AddInteger(Offset);
1703   C->addSelectionDAGCSEId(ID);
1704   ID.AddInteger(TargetFlags);
1705   void *IP = nullptr;
1706   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1707     return SDValue(E, 0);
1708 
1709   auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment,
1710                                           TargetFlags);
1711   CSEMap.InsertNode(N, IP);
1712   InsertNode(N);
1713   return SDValue(N, 0);
1714 }
1715 
1716 SDValue SelectionDAG::getTargetIndex(int Index, EVT VT, int64_t Offset,
1717                                      unsigned TargetFlags) {
1718   FoldingSetNodeID ID;
1719   AddNodeIDNode(ID, ISD::TargetIndex, getVTList(VT), None);
1720   ID.AddInteger(Index);
1721   ID.AddInteger(Offset);
1722   ID.AddInteger(TargetFlags);
1723   void *IP = nullptr;
1724   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1725     return SDValue(E, 0);
1726 
1727   auto *N = newSDNode<TargetIndexSDNode>(Index, VT, Offset, TargetFlags);
1728   CSEMap.InsertNode(N, IP);
1729   InsertNode(N);
1730   return SDValue(N, 0);
1731 }
1732 
1733 SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
1734   FoldingSetNodeID ID;
1735   AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), None);
1736   ID.AddPointer(MBB);
1737   void *IP = nullptr;
1738   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1739     return SDValue(E, 0);
1740 
1741   auto *N = newSDNode<BasicBlockSDNode>(MBB);
1742   CSEMap.InsertNode(N, IP);
1743   InsertNode(N);
1744   return SDValue(N, 0);
1745 }
1746 
1747 SDValue SelectionDAG::getValueType(EVT VT) {
1748   if (VT.isSimple() && (unsigned)VT.getSimpleVT().SimpleTy >=
1749       ValueTypeNodes.size())
1750     ValueTypeNodes.resize(VT.getSimpleVT().SimpleTy+1);
1751 
1752   SDNode *&N = VT.isExtended() ?
1753     ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT().SimpleTy];
1754 
1755   if (N) return SDValue(N, 0);
1756   N = newSDNode<VTSDNode>(VT);
1757   InsertNode(N);
1758   return SDValue(N, 0);
1759 }
1760 
1761 SDValue SelectionDAG::getExternalSymbol(const char *Sym, EVT VT) {
1762   SDNode *&N = ExternalSymbols[Sym];
1763   if (N) return SDValue(N, 0);
1764   N = newSDNode<ExternalSymbolSDNode>(false, Sym, 0, VT);
1765   InsertNode(N);
1766   return SDValue(N, 0);
1767 }
1768 
1769 SDValue SelectionDAG::getMCSymbol(MCSymbol *Sym, EVT VT) {
1770   SDNode *&N = MCSymbols[Sym];
1771   if (N)
1772     return SDValue(N, 0);
1773   N = newSDNode<MCSymbolSDNode>(Sym, VT);
1774   InsertNode(N);
1775   return SDValue(N, 0);
1776 }
1777 
1778 SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, EVT VT,
1779                                               unsigned TargetFlags) {
1780   SDNode *&N =
1781       TargetExternalSymbols[std::pair<std::string, unsigned>(Sym, TargetFlags)];
1782   if (N) return SDValue(N, 0);
1783   N = newSDNode<ExternalSymbolSDNode>(true, Sym, TargetFlags, VT);
1784   InsertNode(N);
1785   return SDValue(N, 0);
1786 }
1787 
1788 SDValue SelectionDAG::getCondCode(ISD::CondCode Cond) {
1789   if ((unsigned)Cond >= CondCodeNodes.size())
1790     CondCodeNodes.resize(Cond+1);
1791 
1792   if (!CondCodeNodes[Cond]) {
1793     auto *N = newSDNode<CondCodeSDNode>(Cond);
1794     CondCodeNodes[Cond] = N;
1795     InsertNode(N);
1796   }
1797 
1798   return SDValue(CondCodeNodes[Cond], 0);
1799 }
1800 
1801 SDValue SelectionDAG::getStepVector(const SDLoc &DL, EVT ResVT) {
1802   APInt One(ResVT.getScalarSizeInBits(), 1);
1803   return getStepVector(DL, ResVT, One);
1804 }
1805 
1806 SDValue SelectionDAG::getStepVector(const SDLoc &DL, EVT ResVT, APInt StepVal) {
1807   assert(ResVT.getScalarSizeInBits() == StepVal.getBitWidth());
1808   if (ResVT.isScalableVector())
1809     return getNode(
1810         ISD::STEP_VECTOR, DL, ResVT,
1811         getTargetConstant(StepVal, DL, ResVT.getVectorElementType()));
1812 
1813   SmallVector<SDValue, 16> OpsStepConstants;
1814   for (uint64_t i = 0; i < ResVT.getVectorNumElements(); i++)
1815     OpsStepConstants.push_back(
1816         getConstant(StepVal * i, DL, ResVT.getVectorElementType()));
1817   return getBuildVector(ResVT, DL, OpsStepConstants);
1818 }
1819 
1820 /// Swaps the values of N1 and N2. Swaps all indices in the shuffle mask M that
1821 /// point at N1 to point at N2 and indices that point at N2 to point at N1.
1822 static void commuteShuffle(SDValue &N1, SDValue &N2, MutableArrayRef<int> M) {
1823   std::swap(N1, N2);
1824   ShuffleVectorSDNode::commuteMask(M);
1825 }
1826 
1827 SDValue SelectionDAG::getVectorShuffle(EVT VT, const SDLoc &dl, SDValue N1,
1828                                        SDValue N2, ArrayRef<int> Mask) {
1829   assert(VT.getVectorNumElements() == Mask.size() &&
1830          "Must have the same number of vector elements as mask elements!");
1831   assert(VT == N1.getValueType() && VT == N2.getValueType() &&
1832          "Invalid VECTOR_SHUFFLE");
1833 
1834   // Canonicalize shuffle undef, undef -> undef
1835   if (N1.isUndef() && N2.isUndef())
1836     return getUNDEF(VT);
1837 
1838   // Validate that all indices in Mask are within the range of the elements
1839   // input to the shuffle.
1840   int NElts = Mask.size();
1841   assert(llvm::all_of(Mask,
1842                       [&](int M) { return M < (NElts * 2) && M >= -1; }) &&
1843          "Index out of range");
1844 
1845   // Copy the mask so we can do any needed cleanup.
1846   SmallVector<int, 8> MaskVec(Mask.begin(), Mask.end());
1847 
1848   // Canonicalize shuffle v, v -> v, undef
1849   if (N1 == N2) {
1850     N2 = getUNDEF(VT);
1851     for (int i = 0; i != NElts; ++i)
1852       if (MaskVec[i] >= NElts) MaskVec[i] -= NElts;
1853   }
1854 
1855   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
1856   if (N1.isUndef())
1857     commuteShuffle(N1, N2, MaskVec);
1858 
1859   if (TLI->hasVectorBlend()) {
1860     // If shuffling a splat, try to blend the splat instead. We do this here so
1861     // that even when this arises during lowering we don't have to re-handle it.
1862     auto BlendSplat = [&](BuildVectorSDNode *BV, int Offset) {
1863       BitVector UndefElements;
1864       SDValue Splat = BV->getSplatValue(&UndefElements);
1865       if (!Splat)
1866         return;
1867 
1868       for (int i = 0; i < NElts; ++i) {
1869         if (MaskVec[i] < Offset || MaskVec[i] >= (Offset + NElts))
1870           continue;
1871 
1872         // If this input comes from undef, mark it as such.
1873         if (UndefElements[MaskVec[i] - Offset]) {
1874           MaskVec[i] = -1;
1875           continue;
1876         }
1877 
1878         // If we can blend a non-undef lane, use that instead.
1879         if (!UndefElements[i])
1880           MaskVec[i] = i + Offset;
1881       }
1882     };
1883     if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
1884       BlendSplat(N1BV, 0);
1885     if (auto *N2BV = dyn_cast<BuildVectorSDNode>(N2))
1886       BlendSplat(N2BV, NElts);
1887   }
1888 
1889   // Canonicalize all index into lhs, -> shuffle lhs, undef
1890   // Canonicalize all index into rhs, -> shuffle rhs, undef
1891   bool AllLHS = true, AllRHS = true;
1892   bool N2Undef = N2.isUndef();
1893   for (int i = 0; i != NElts; ++i) {
1894     if (MaskVec[i] >= NElts) {
1895       if (N2Undef)
1896         MaskVec[i] = -1;
1897       else
1898         AllLHS = false;
1899     } else if (MaskVec[i] >= 0) {
1900       AllRHS = false;
1901     }
1902   }
1903   if (AllLHS && AllRHS)
1904     return getUNDEF(VT);
1905   if (AllLHS && !N2Undef)
1906     N2 = getUNDEF(VT);
1907   if (AllRHS) {
1908     N1 = getUNDEF(VT);
1909     commuteShuffle(N1, N2, MaskVec);
1910   }
1911   // Reset our undef status after accounting for the mask.
1912   N2Undef = N2.isUndef();
1913   // Re-check whether both sides ended up undef.
1914   if (N1.isUndef() && N2Undef)
1915     return getUNDEF(VT);
1916 
1917   // If Identity shuffle return that node.
1918   bool Identity = true, AllSame = true;
1919   for (int i = 0; i != NElts; ++i) {
1920     if (MaskVec[i] >= 0 && MaskVec[i] != i) Identity = false;
1921     if (MaskVec[i] != MaskVec[0]) AllSame = false;
1922   }
1923   if (Identity && NElts)
1924     return N1;
1925 
1926   // Shuffling a constant splat doesn't change the result.
1927   if (N2Undef) {
1928     SDValue V = N1;
1929 
1930     // Look through any bitcasts. We check that these don't change the number
1931     // (and size) of elements and just changes their types.
1932     while (V.getOpcode() == ISD::BITCAST)
1933       V = V->getOperand(0);
1934 
1935     // A splat should always show up as a build vector node.
1936     if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) {
1937       BitVector UndefElements;
1938       SDValue Splat = BV->getSplatValue(&UndefElements);
1939       // If this is a splat of an undef, shuffling it is also undef.
1940       if (Splat && Splat.isUndef())
1941         return getUNDEF(VT);
1942 
1943       bool SameNumElts =
1944           V.getValueType().getVectorNumElements() == VT.getVectorNumElements();
1945 
1946       // We only have a splat which can skip shuffles if there is a splatted
1947       // value and no undef lanes rearranged by the shuffle.
1948       if (Splat && UndefElements.none()) {
1949         // Splat of <x, x, ..., x>, return <x, x, ..., x>, provided that the
1950         // number of elements match or the value splatted is a zero constant.
1951         if (SameNumElts)
1952           return N1;
1953         if (auto *C = dyn_cast<ConstantSDNode>(Splat))
1954           if (C->isZero())
1955             return N1;
1956       }
1957 
1958       // If the shuffle itself creates a splat, build the vector directly.
1959       if (AllSame && SameNumElts) {
1960         EVT BuildVT = BV->getValueType(0);
1961         const SDValue &Splatted = BV->getOperand(MaskVec[0]);
1962         SDValue NewBV = getSplatBuildVector(BuildVT, dl, Splatted);
1963 
1964         // We may have jumped through bitcasts, so the type of the
1965         // BUILD_VECTOR may not match the type of the shuffle.
1966         if (BuildVT != VT)
1967           NewBV = getNode(ISD::BITCAST, dl, VT, NewBV);
1968         return NewBV;
1969       }
1970     }
1971   }
1972 
1973   FoldingSetNodeID ID;
1974   SDValue Ops[2] = { N1, N2 };
1975   AddNodeIDNode(ID, ISD::VECTOR_SHUFFLE, getVTList(VT), Ops);
1976   for (int i = 0; i != NElts; ++i)
1977     ID.AddInteger(MaskVec[i]);
1978 
1979   void* IP = nullptr;
1980   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
1981     return SDValue(E, 0);
1982 
1983   // Allocate the mask array for the node out of the BumpPtrAllocator, since
1984   // SDNode doesn't have access to it.  This memory will be "leaked" when
1985   // the node is deallocated, but recovered when the NodeAllocator is released.
1986   int *MaskAlloc = OperandAllocator.Allocate<int>(NElts);
1987   llvm::copy(MaskVec, MaskAlloc);
1988 
1989   auto *N = newSDNode<ShuffleVectorSDNode>(VT, dl.getIROrder(),
1990                                            dl.getDebugLoc(), MaskAlloc);
1991   createOperands(N, Ops);
1992 
1993   CSEMap.InsertNode(N, IP);
1994   InsertNode(N);
1995   SDValue V = SDValue(N, 0);
1996   NewSDValueDbgMsg(V, "Creating new node: ", this);
1997   return V;
1998 }
1999 
2000 SDValue SelectionDAG::getCommutedVectorShuffle(const ShuffleVectorSDNode &SV) {
2001   EVT VT = SV.getValueType(0);
2002   SmallVector<int, 8> MaskVec(SV.getMask().begin(), SV.getMask().end());
2003   ShuffleVectorSDNode::commuteMask(MaskVec);
2004 
2005   SDValue Op0 = SV.getOperand(0);
2006   SDValue Op1 = SV.getOperand(1);
2007   return getVectorShuffle(VT, SDLoc(&SV), Op1, Op0, MaskVec);
2008 }
2009 
2010 SDValue SelectionDAG::getRegister(unsigned RegNo, EVT VT) {
2011   FoldingSetNodeID ID;
2012   AddNodeIDNode(ID, ISD::Register, getVTList(VT), None);
2013   ID.AddInteger(RegNo);
2014   void *IP = nullptr;
2015   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2016     return SDValue(E, 0);
2017 
2018   auto *N = newSDNode<RegisterSDNode>(RegNo, VT);
2019   N->SDNodeBits.IsDivergent = TLI->isSDNodeSourceOfDivergence(N, FLI, DA);
2020   CSEMap.InsertNode(N, IP);
2021   InsertNode(N);
2022   return SDValue(N, 0);
2023 }
2024 
2025 SDValue SelectionDAG::getRegisterMask(const uint32_t *RegMask) {
2026   FoldingSetNodeID ID;
2027   AddNodeIDNode(ID, ISD::RegisterMask, getVTList(MVT::Untyped), None);
2028   ID.AddPointer(RegMask);
2029   void *IP = nullptr;
2030   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2031     return SDValue(E, 0);
2032 
2033   auto *N = newSDNode<RegisterMaskSDNode>(RegMask);
2034   CSEMap.InsertNode(N, IP);
2035   InsertNode(N);
2036   return SDValue(N, 0);
2037 }
2038 
2039 SDValue SelectionDAG::getEHLabel(const SDLoc &dl, SDValue Root,
2040                                  MCSymbol *Label) {
2041   return getLabelNode(ISD::EH_LABEL, dl, Root, Label);
2042 }
2043 
2044 SDValue SelectionDAG::getLabelNode(unsigned Opcode, const SDLoc &dl,
2045                                    SDValue Root, MCSymbol *Label) {
2046   FoldingSetNodeID ID;
2047   SDValue Ops[] = { Root };
2048   AddNodeIDNode(ID, Opcode, getVTList(MVT::Other), Ops);
2049   ID.AddPointer(Label);
2050   void *IP = nullptr;
2051   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2052     return SDValue(E, 0);
2053 
2054   auto *N =
2055       newSDNode<LabelSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), Label);
2056   createOperands(N, Ops);
2057 
2058   CSEMap.InsertNode(N, IP);
2059   InsertNode(N);
2060   return SDValue(N, 0);
2061 }
2062 
2063 SDValue SelectionDAG::getBlockAddress(const BlockAddress *BA, EVT VT,
2064                                       int64_t Offset, bool isTarget,
2065                                       unsigned TargetFlags) {
2066   unsigned Opc = isTarget ? ISD::TargetBlockAddress : ISD::BlockAddress;
2067 
2068   FoldingSetNodeID ID;
2069   AddNodeIDNode(ID, Opc, getVTList(VT), None);
2070   ID.AddPointer(BA);
2071   ID.AddInteger(Offset);
2072   ID.AddInteger(TargetFlags);
2073   void *IP = nullptr;
2074   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2075     return SDValue(E, 0);
2076 
2077   auto *N = newSDNode<BlockAddressSDNode>(Opc, VT, BA, Offset, TargetFlags);
2078   CSEMap.InsertNode(N, IP);
2079   InsertNode(N);
2080   return SDValue(N, 0);
2081 }
2082 
2083 SDValue SelectionDAG::getSrcValue(const Value *V) {
2084   FoldingSetNodeID ID;
2085   AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), None);
2086   ID.AddPointer(V);
2087 
2088   void *IP = nullptr;
2089   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2090     return SDValue(E, 0);
2091 
2092   auto *N = newSDNode<SrcValueSDNode>(V);
2093   CSEMap.InsertNode(N, IP);
2094   InsertNode(N);
2095   return SDValue(N, 0);
2096 }
2097 
2098 SDValue SelectionDAG::getMDNode(const MDNode *MD) {
2099   FoldingSetNodeID ID;
2100   AddNodeIDNode(ID, ISD::MDNODE_SDNODE, getVTList(MVT::Other), None);
2101   ID.AddPointer(MD);
2102 
2103   void *IP = nullptr;
2104   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2105     return SDValue(E, 0);
2106 
2107   auto *N = newSDNode<MDNodeSDNode>(MD);
2108   CSEMap.InsertNode(N, IP);
2109   InsertNode(N);
2110   return SDValue(N, 0);
2111 }
2112 
2113 SDValue SelectionDAG::getBitcast(EVT VT, SDValue V) {
2114   if (VT == V.getValueType())
2115     return V;
2116 
2117   return getNode(ISD::BITCAST, SDLoc(V), VT, V);
2118 }
2119 
2120 SDValue SelectionDAG::getAddrSpaceCast(const SDLoc &dl, EVT VT, SDValue Ptr,
2121                                        unsigned SrcAS, unsigned DestAS) {
2122   SDValue Ops[] = {Ptr};
2123   FoldingSetNodeID ID;
2124   AddNodeIDNode(ID, ISD::ADDRSPACECAST, getVTList(VT), Ops);
2125   ID.AddInteger(SrcAS);
2126   ID.AddInteger(DestAS);
2127 
2128   void *IP = nullptr;
2129   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
2130     return SDValue(E, 0);
2131 
2132   auto *N = newSDNode<AddrSpaceCastSDNode>(dl.getIROrder(), dl.getDebugLoc(),
2133                                            VT, SrcAS, DestAS);
2134   createOperands(N, Ops);
2135 
2136   CSEMap.InsertNode(N, IP);
2137   InsertNode(N);
2138   return SDValue(N, 0);
2139 }
2140 
2141 SDValue SelectionDAG::getFreeze(SDValue V) {
2142   return getNode(ISD::FREEZE, SDLoc(V), V.getValueType(), V);
2143 }
2144 
2145 /// getShiftAmountOperand - Return the specified value casted to
2146 /// the target's desired shift amount type.
2147 SDValue SelectionDAG::getShiftAmountOperand(EVT LHSTy, SDValue Op) {
2148   EVT OpTy = Op.getValueType();
2149   EVT ShTy = TLI->getShiftAmountTy(LHSTy, getDataLayout());
2150   if (OpTy == ShTy || OpTy.isVector()) return Op;
2151 
2152   return getZExtOrTrunc(Op, SDLoc(Op), ShTy);
2153 }
2154 
2155 SDValue SelectionDAG::expandVAArg(SDNode *Node) {
2156   SDLoc dl(Node);
2157   const TargetLowering &TLI = getTargetLoweringInfo();
2158   const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2159   EVT VT = Node->getValueType(0);
2160   SDValue Tmp1 = Node->getOperand(0);
2161   SDValue Tmp2 = Node->getOperand(1);
2162   const MaybeAlign MA(Node->getConstantOperandVal(3));
2163 
2164   SDValue VAListLoad = getLoad(TLI.getPointerTy(getDataLayout()), dl, Tmp1,
2165                                Tmp2, MachinePointerInfo(V));
2166   SDValue VAList = VAListLoad;
2167 
2168   if (MA && *MA > TLI.getMinStackArgumentAlignment()) {
2169     VAList = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
2170                      getConstant(MA->value() - 1, dl, VAList.getValueType()));
2171 
2172     VAList =
2173         getNode(ISD::AND, dl, VAList.getValueType(), VAList,
2174                 getConstant(-(int64_t)MA->value(), dl, VAList.getValueType()));
2175   }
2176 
2177   // Increment the pointer, VAList, to the next vaarg
2178   Tmp1 = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
2179                  getConstant(getDataLayout().getTypeAllocSize(
2180                                                VT.getTypeForEVT(*getContext())),
2181                              dl, VAList.getValueType()));
2182   // Store the incremented VAList to the legalized pointer
2183   Tmp1 =
2184       getStore(VAListLoad.getValue(1), dl, Tmp1, Tmp2, MachinePointerInfo(V));
2185   // Load the actual argument out of the pointer VAList
2186   return getLoad(VT, dl, Tmp1, VAList, MachinePointerInfo());
2187 }
2188 
2189 SDValue SelectionDAG::expandVACopy(SDNode *Node) {
2190   SDLoc dl(Node);
2191   const TargetLowering &TLI = getTargetLoweringInfo();
2192   // This defaults to loading a pointer from the input and storing it to the
2193   // output, returning the chain.
2194   const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue();
2195   const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue();
2196   SDValue Tmp1 =
2197       getLoad(TLI.getPointerTy(getDataLayout()), dl, Node->getOperand(0),
2198               Node->getOperand(2), MachinePointerInfo(VS));
2199   return getStore(Tmp1.getValue(1), dl, Tmp1, Node->getOperand(1),
2200                   MachinePointerInfo(VD));
2201 }
2202 
2203 Align SelectionDAG::getReducedAlign(EVT VT, bool UseABI) {
2204   const DataLayout &DL = getDataLayout();
2205   Type *Ty = VT.getTypeForEVT(*getContext());
2206   Align RedAlign = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty);
2207 
2208   if (TLI->isTypeLegal(VT) || !VT.isVector())
2209     return RedAlign;
2210 
2211   const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
2212   const Align StackAlign = TFI->getStackAlign();
2213 
2214   // See if we can choose a smaller ABI alignment in cases where it's an
2215   // illegal vector type that will get broken down.
2216   if (RedAlign > StackAlign) {
2217     EVT IntermediateVT;
2218     MVT RegisterVT;
2219     unsigned NumIntermediates;
2220     TLI->getVectorTypeBreakdown(*getContext(), VT, IntermediateVT,
2221                                 NumIntermediates, RegisterVT);
2222     Ty = IntermediateVT.getTypeForEVT(*getContext());
2223     Align RedAlign2 = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty);
2224     if (RedAlign2 < RedAlign)
2225       RedAlign = RedAlign2;
2226   }
2227 
2228   return RedAlign;
2229 }
2230 
2231 SDValue SelectionDAG::CreateStackTemporary(TypeSize Bytes, Align Alignment) {
2232   MachineFrameInfo &MFI = MF->getFrameInfo();
2233   const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
2234   int StackID = 0;
2235   if (Bytes.isScalable())
2236     StackID = TFI->getStackIDForScalableVectors();
2237   // The stack id gives an indication of whether the object is scalable or
2238   // not, so it's safe to pass in the minimum size here.
2239   int FrameIdx = MFI.CreateStackObject(Bytes.getKnownMinSize(), Alignment,
2240                                        false, nullptr, StackID);
2241   return getFrameIndex(FrameIdx, TLI->getFrameIndexTy(getDataLayout()));
2242 }
2243 
2244 SDValue SelectionDAG::CreateStackTemporary(EVT VT, unsigned minAlign) {
2245   Type *Ty = VT.getTypeForEVT(*getContext());
2246   Align StackAlign =
2247       std::max(getDataLayout().getPrefTypeAlign(Ty), Align(minAlign));
2248   return CreateStackTemporary(VT.getStoreSize(), StackAlign);
2249 }
2250 
2251 SDValue SelectionDAG::CreateStackTemporary(EVT VT1, EVT VT2) {
2252   TypeSize VT1Size = VT1.getStoreSize();
2253   TypeSize VT2Size = VT2.getStoreSize();
2254   assert(VT1Size.isScalable() == VT2Size.isScalable() &&
2255          "Don't know how to choose the maximum size when creating a stack "
2256          "temporary");
2257   TypeSize Bytes =
2258       VT1Size.getKnownMinSize() > VT2Size.getKnownMinSize() ? VT1Size : VT2Size;
2259 
2260   Type *Ty1 = VT1.getTypeForEVT(*getContext());
2261   Type *Ty2 = VT2.getTypeForEVT(*getContext());
2262   const DataLayout &DL = getDataLayout();
2263   Align Align = std::max(DL.getPrefTypeAlign(Ty1), DL.getPrefTypeAlign(Ty2));
2264   return CreateStackTemporary(Bytes, Align);
2265 }
2266 
2267 SDValue SelectionDAG::FoldSetCC(EVT VT, SDValue N1, SDValue N2,
2268                                 ISD::CondCode Cond, const SDLoc &dl) {
2269   EVT OpVT = N1.getValueType();
2270 
2271   // These setcc operations always fold.
2272   switch (Cond) {
2273   default: break;
2274   case ISD::SETFALSE:
2275   case ISD::SETFALSE2: return getBoolConstant(false, dl, VT, OpVT);
2276   case ISD::SETTRUE:
2277   case ISD::SETTRUE2: return getBoolConstant(true, dl, VT, OpVT);
2278 
2279   case ISD::SETOEQ:
2280   case ISD::SETOGT:
2281   case ISD::SETOGE:
2282   case ISD::SETOLT:
2283   case ISD::SETOLE:
2284   case ISD::SETONE:
2285   case ISD::SETO:
2286   case ISD::SETUO:
2287   case ISD::SETUEQ:
2288   case ISD::SETUNE:
2289     assert(!OpVT.isInteger() && "Illegal setcc for integer!");
2290     break;
2291   }
2292 
2293   if (OpVT.isInteger()) {
2294     // For EQ and NE, we can always pick a value for the undef to make the
2295     // predicate pass or fail, so we can return undef.
2296     // Matches behavior in llvm::ConstantFoldCompareInstruction.
2297     // icmp eq/ne X, undef -> undef.
2298     if ((N1.isUndef() || N2.isUndef()) &&
2299         (Cond == ISD::SETEQ || Cond == ISD::SETNE))
2300       return getUNDEF(VT);
2301 
2302     // If both operands are undef, we can return undef for int comparison.
2303     // icmp undef, undef -> undef.
2304     if (N1.isUndef() && N2.isUndef())
2305       return getUNDEF(VT);
2306 
2307     // icmp X, X -> true/false
2308     // icmp X, undef -> true/false because undef could be X.
2309     if (N1 == N2)
2310       return getBoolConstant(ISD::isTrueWhenEqual(Cond), dl, VT, OpVT);
2311   }
2312 
2313   if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2)) {
2314     const APInt &C2 = N2C->getAPIntValue();
2315     if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1)) {
2316       const APInt &C1 = N1C->getAPIntValue();
2317 
2318       return getBoolConstant(ICmpInst::compare(C1, C2, getICmpCondCode(Cond)),
2319                              dl, VT, OpVT);
2320     }
2321   }
2322 
2323   auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
2324   auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
2325 
2326   if (N1CFP && N2CFP) {
2327     APFloat::cmpResult R = N1CFP->getValueAPF().compare(N2CFP->getValueAPF());
2328     switch (Cond) {
2329     default: break;
2330     case ISD::SETEQ:  if (R==APFloat::cmpUnordered)
2331                         return getUNDEF(VT);
2332                       LLVM_FALLTHROUGH;
2333     case ISD::SETOEQ: return getBoolConstant(R==APFloat::cmpEqual, dl, VT,
2334                                              OpVT);
2335     case ISD::SETNE:  if (R==APFloat::cmpUnordered)
2336                         return getUNDEF(VT);
2337                       LLVM_FALLTHROUGH;
2338     case ISD::SETONE: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2339                                              R==APFloat::cmpLessThan, dl, VT,
2340                                              OpVT);
2341     case ISD::SETLT:  if (R==APFloat::cmpUnordered)
2342                         return getUNDEF(VT);
2343                       LLVM_FALLTHROUGH;
2344     case ISD::SETOLT: return getBoolConstant(R==APFloat::cmpLessThan, dl, VT,
2345                                              OpVT);
2346     case ISD::SETGT:  if (R==APFloat::cmpUnordered)
2347                         return getUNDEF(VT);
2348                       LLVM_FALLTHROUGH;
2349     case ISD::SETOGT: return getBoolConstant(R==APFloat::cmpGreaterThan, dl,
2350                                              VT, OpVT);
2351     case ISD::SETLE:  if (R==APFloat::cmpUnordered)
2352                         return getUNDEF(VT);
2353                       LLVM_FALLTHROUGH;
2354     case ISD::SETOLE: return getBoolConstant(R==APFloat::cmpLessThan ||
2355                                              R==APFloat::cmpEqual, dl, VT,
2356                                              OpVT);
2357     case ISD::SETGE:  if (R==APFloat::cmpUnordered)
2358                         return getUNDEF(VT);
2359                       LLVM_FALLTHROUGH;
2360     case ISD::SETOGE: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2361                                          R==APFloat::cmpEqual, dl, VT, OpVT);
2362     case ISD::SETO:   return getBoolConstant(R!=APFloat::cmpUnordered, dl, VT,
2363                                              OpVT);
2364     case ISD::SETUO:  return getBoolConstant(R==APFloat::cmpUnordered, dl, VT,
2365                                              OpVT);
2366     case ISD::SETUEQ: return getBoolConstant(R==APFloat::cmpUnordered ||
2367                                              R==APFloat::cmpEqual, dl, VT,
2368                                              OpVT);
2369     case ISD::SETUNE: return getBoolConstant(R!=APFloat::cmpEqual, dl, VT,
2370                                              OpVT);
2371     case ISD::SETULT: return getBoolConstant(R==APFloat::cmpUnordered ||
2372                                              R==APFloat::cmpLessThan, dl, VT,
2373                                              OpVT);
2374     case ISD::SETUGT: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2375                                              R==APFloat::cmpUnordered, dl, VT,
2376                                              OpVT);
2377     case ISD::SETULE: return getBoolConstant(R!=APFloat::cmpGreaterThan, dl,
2378                                              VT, OpVT);
2379     case ISD::SETUGE: return getBoolConstant(R!=APFloat::cmpLessThan, dl, VT,
2380                                              OpVT);
2381     }
2382   } else if (N1CFP && OpVT.isSimple() && !N2.isUndef()) {
2383     // Ensure that the constant occurs on the RHS.
2384     ISD::CondCode SwappedCond = ISD::getSetCCSwappedOperands(Cond);
2385     if (!TLI->isCondCodeLegal(SwappedCond, OpVT.getSimpleVT()))
2386       return SDValue();
2387     return getSetCC(dl, VT, N2, N1, SwappedCond);
2388   } else if ((N2CFP && N2CFP->getValueAPF().isNaN()) ||
2389              (OpVT.isFloatingPoint() && (N1.isUndef() || N2.isUndef()))) {
2390     // If an operand is known to be a nan (or undef that could be a nan), we can
2391     // fold it.
2392     // Choosing NaN for the undef will always make unordered comparison succeed
2393     // and ordered comparison fails.
2394     // Matches behavior in llvm::ConstantFoldCompareInstruction.
2395     switch (ISD::getUnorderedFlavor(Cond)) {
2396     default:
2397       llvm_unreachable("Unknown flavor!");
2398     case 0: // Known false.
2399       return getBoolConstant(false, dl, VT, OpVT);
2400     case 1: // Known true.
2401       return getBoolConstant(true, dl, VT, OpVT);
2402     case 2: // Undefined.
2403       return getUNDEF(VT);
2404     }
2405   }
2406 
2407   // Could not fold it.
2408   return SDValue();
2409 }
2410 
2411 /// See if the specified operand can be simplified with the knowledge that only
2412 /// the bits specified by DemandedBits are used.
2413 /// TODO: really we should be making this into the DAG equivalent of
2414 /// SimplifyMultipleUseDemandedBits and not generate any new nodes.
2415 SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &DemandedBits) {
2416   EVT VT = V.getValueType();
2417 
2418   if (VT.isScalableVector())
2419     return SDValue();
2420 
2421   APInt DemandedElts = VT.isVector()
2422                            ? APInt::getAllOnes(VT.getVectorNumElements())
2423                            : APInt(1, 1);
2424   return GetDemandedBits(V, DemandedBits, DemandedElts);
2425 }
2426 
2427 /// See if the specified operand can be simplified with the knowledge that only
2428 /// the bits specified by DemandedBits are used in the elements specified by
2429 /// DemandedElts.
2430 /// TODO: really we should be making this into the DAG equivalent of
2431 /// SimplifyMultipleUseDemandedBits and not generate any new nodes.
2432 SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &DemandedBits,
2433                                       const APInt &DemandedElts) {
2434   switch (V.getOpcode()) {
2435   default:
2436     return TLI->SimplifyMultipleUseDemandedBits(V, DemandedBits, DemandedElts,
2437                                                 *this, 0);
2438   case ISD::Constant: {
2439     const APInt &CVal = cast<ConstantSDNode>(V)->getAPIntValue();
2440     APInt NewVal = CVal & DemandedBits;
2441     if (NewVal != CVal)
2442       return getConstant(NewVal, SDLoc(V), V.getValueType());
2443     break;
2444   }
2445   case ISD::SRL:
2446     // Only look at single-use SRLs.
2447     if (!V.getNode()->hasOneUse())
2448       break;
2449     if (auto *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
2450       // See if we can recursively simplify the LHS.
2451       unsigned Amt = RHSC->getZExtValue();
2452 
2453       // Watch out for shift count overflow though.
2454       if (Amt >= DemandedBits.getBitWidth())
2455         break;
2456       APInt SrcDemandedBits = DemandedBits << Amt;
2457       if (SDValue SimplifyLHS =
2458               GetDemandedBits(V.getOperand(0), SrcDemandedBits))
2459         return getNode(ISD::SRL, SDLoc(V), V.getValueType(), SimplifyLHS,
2460                        V.getOperand(1));
2461     }
2462     break;
2463   }
2464   return SDValue();
2465 }
2466 
2467 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero.  We
2468 /// use this predicate to simplify operations downstream.
2469 bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const {
2470   unsigned BitWidth = Op.getScalarValueSizeInBits();
2471   return MaskedValueIsZero(Op, APInt::getSignMask(BitWidth), Depth);
2472 }
2473 
2474 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero.  We use
2475 /// this predicate to simplify operations downstream.  Mask is known to be zero
2476 /// for bits that V cannot have.
2477 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask,
2478                                      unsigned Depth) const {
2479   return Mask.isSubsetOf(computeKnownBits(V, Depth).Zero);
2480 }
2481 
2482 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero in
2483 /// DemandedElts.  We use this predicate to simplify operations downstream.
2484 /// Mask is known to be zero for bits that V cannot have.
2485 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask,
2486                                      const APInt &DemandedElts,
2487                                      unsigned Depth) const {
2488   return Mask.isSubsetOf(computeKnownBits(V, DemandedElts, Depth).Zero);
2489 }
2490 
2491 /// MaskedValueIsAllOnes - Return true if '(Op & Mask) == Mask'.
2492 bool SelectionDAG::MaskedValueIsAllOnes(SDValue V, const APInt &Mask,
2493                                         unsigned Depth) const {
2494   return Mask.isSubsetOf(computeKnownBits(V, Depth).One);
2495 }
2496 
2497 /// isSplatValue - Return true if the vector V has the same value
2498 /// across all DemandedElts. For scalable vectors it does not make
2499 /// sense to specify which elements are demanded or undefined, therefore
2500 /// they are simply ignored.
2501 bool SelectionDAG::isSplatValue(SDValue V, const APInt &DemandedElts,
2502                                 APInt &UndefElts, unsigned Depth) {
2503   EVT VT = V.getValueType();
2504   assert(VT.isVector() && "Vector type expected");
2505 
2506   if (!VT.isScalableVector() && !DemandedElts)
2507     return false; // No demanded elts, better to assume we don't know anything.
2508 
2509   if (Depth >= MaxRecursionDepth)
2510     return false; // Limit search depth.
2511 
2512   // Deal with some common cases here that work for both fixed and scalable
2513   // vector types.
2514   switch (V.getOpcode()) {
2515   case ISD::SPLAT_VECTOR:
2516     UndefElts = V.getOperand(0).isUndef()
2517                     ? APInt::getAllOnes(DemandedElts.getBitWidth())
2518                     : APInt(DemandedElts.getBitWidth(), 0);
2519     return true;
2520   case ISD::ADD:
2521   case ISD::SUB:
2522   case ISD::AND:
2523   case ISD::XOR:
2524   case ISD::OR: {
2525     APInt UndefLHS, UndefRHS;
2526     SDValue LHS = V.getOperand(0);
2527     SDValue RHS = V.getOperand(1);
2528     if (isSplatValue(LHS, DemandedElts, UndefLHS, Depth + 1) &&
2529         isSplatValue(RHS, DemandedElts, UndefRHS, Depth + 1)) {
2530       UndefElts = UndefLHS | UndefRHS;
2531       return true;
2532     }
2533     return false;
2534   }
2535   case ISD::ABS:
2536   case ISD::TRUNCATE:
2537   case ISD::SIGN_EXTEND:
2538   case ISD::ZERO_EXTEND:
2539     return isSplatValue(V.getOperand(0), DemandedElts, UndefElts, Depth + 1);
2540   }
2541 
2542   // We don't support other cases than those above for scalable vectors at
2543   // the moment.
2544   if (VT.isScalableVector())
2545     return false;
2546 
2547   unsigned NumElts = VT.getVectorNumElements();
2548   assert(NumElts == DemandedElts.getBitWidth() && "Vector size mismatch");
2549   UndefElts = APInt::getZero(NumElts);
2550 
2551   switch (V.getOpcode()) {
2552   case ISD::BUILD_VECTOR: {
2553     SDValue Scl;
2554     for (unsigned i = 0; i != NumElts; ++i) {
2555       SDValue Op = V.getOperand(i);
2556       if (Op.isUndef()) {
2557         UndefElts.setBit(i);
2558         continue;
2559       }
2560       if (!DemandedElts[i])
2561         continue;
2562       if (Scl && Scl != Op)
2563         return false;
2564       Scl = Op;
2565     }
2566     return true;
2567   }
2568   case ISD::VECTOR_SHUFFLE: {
2569     // Check if this is a shuffle node doing a splat.
2570     // TODO: Do we need to handle shuffle(splat, undef, mask)?
2571     int SplatIndex = -1;
2572     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(V)->getMask();
2573     for (int i = 0; i != (int)NumElts; ++i) {
2574       int M = Mask[i];
2575       if (M < 0) {
2576         UndefElts.setBit(i);
2577         continue;
2578       }
2579       if (!DemandedElts[i])
2580         continue;
2581       if (0 <= SplatIndex && SplatIndex != M)
2582         return false;
2583       SplatIndex = M;
2584     }
2585     return true;
2586   }
2587   case ISD::EXTRACT_SUBVECTOR: {
2588     // Offset the demanded elts by the subvector index.
2589     SDValue Src = V.getOperand(0);
2590     // We don't support scalable vectors at the moment.
2591     if (Src.getValueType().isScalableVector())
2592       return false;
2593     uint64_t Idx = V.getConstantOperandVal(1);
2594     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2595     APInt UndefSrcElts;
2596     APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
2597     if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) {
2598       UndefElts = UndefSrcElts.extractBits(NumElts, Idx);
2599       return true;
2600     }
2601     break;
2602   }
2603   }
2604 
2605   return false;
2606 }
2607 
2608 /// Helper wrapper to main isSplatValue function.
2609 bool SelectionDAG::isSplatValue(SDValue V, bool AllowUndefs) {
2610   EVT VT = V.getValueType();
2611   assert(VT.isVector() && "Vector type expected");
2612 
2613   APInt UndefElts;
2614   APInt DemandedElts;
2615 
2616   // For now we don't support this with scalable vectors.
2617   if (!VT.isScalableVector())
2618     DemandedElts = APInt::getAllOnes(VT.getVectorNumElements());
2619   return isSplatValue(V, DemandedElts, UndefElts) &&
2620          (AllowUndefs || !UndefElts);
2621 }
2622 
2623 SDValue SelectionDAG::getSplatSourceVector(SDValue V, int &SplatIdx) {
2624   V = peekThroughExtractSubvectors(V);
2625 
2626   EVT VT = V.getValueType();
2627   unsigned Opcode = V.getOpcode();
2628   switch (Opcode) {
2629   default: {
2630     APInt UndefElts;
2631     APInt DemandedElts;
2632 
2633     if (!VT.isScalableVector())
2634       DemandedElts = APInt::getAllOnes(VT.getVectorNumElements());
2635 
2636     if (isSplatValue(V, DemandedElts, UndefElts)) {
2637       if (VT.isScalableVector()) {
2638         // DemandedElts and UndefElts are ignored for scalable vectors, since
2639         // the only supported cases are SPLAT_VECTOR nodes.
2640         SplatIdx = 0;
2641       } else {
2642         // Handle case where all demanded elements are UNDEF.
2643         if (DemandedElts.isSubsetOf(UndefElts)) {
2644           SplatIdx = 0;
2645           return getUNDEF(VT);
2646         }
2647         SplatIdx = (UndefElts & DemandedElts).countTrailingOnes();
2648       }
2649       return V;
2650     }
2651     break;
2652   }
2653   case ISD::SPLAT_VECTOR:
2654     SplatIdx = 0;
2655     return V;
2656   case ISD::VECTOR_SHUFFLE: {
2657     if (VT.isScalableVector())
2658       return SDValue();
2659 
2660     // Check if this is a shuffle node doing a splat.
2661     // TODO - remove this and rely purely on SelectionDAG::isSplatValue,
2662     // getTargetVShiftNode currently struggles without the splat source.
2663     auto *SVN = cast<ShuffleVectorSDNode>(V);
2664     if (!SVN->isSplat())
2665       break;
2666     int Idx = SVN->getSplatIndex();
2667     int NumElts = V.getValueType().getVectorNumElements();
2668     SplatIdx = Idx % NumElts;
2669     return V.getOperand(Idx / NumElts);
2670   }
2671   }
2672 
2673   return SDValue();
2674 }
2675 
2676 SDValue SelectionDAG::getSplatValue(SDValue V, bool LegalTypes) {
2677   int SplatIdx;
2678   if (SDValue SrcVector = getSplatSourceVector(V, SplatIdx)) {
2679     EVT SVT = SrcVector.getValueType().getScalarType();
2680     EVT LegalSVT = SVT;
2681     if (LegalTypes && !TLI->isTypeLegal(SVT)) {
2682       if (!SVT.isInteger())
2683         return SDValue();
2684       LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
2685       if (LegalSVT.bitsLT(SVT))
2686         return SDValue();
2687     }
2688     return getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(V), LegalSVT, SrcVector,
2689                    getVectorIdxConstant(SplatIdx, SDLoc(V)));
2690   }
2691   return SDValue();
2692 }
2693 
2694 const APInt *
2695 SelectionDAG::getValidShiftAmountConstant(SDValue V,
2696                                           const APInt &DemandedElts) const {
2697   assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
2698           V.getOpcode() == ISD::SRA) &&
2699          "Unknown shift node");
2700   unsigned BitWidth = V.getScalarValueSizeInBits();
2701   if (ConstantSDNode *SA = isConstOrConstSplat(V.getOperand(1), DemandedElts)) {
2702     // Shifting more than the bitwidth is not valid.
2703     const APInt &ShAmt = SA->getAPIntValue();
2704     if (ShAmt.ult(BitWidth))
2705       return &ShAmt;
2706   }
2707   return nullptr;
2708 }
2709 
2710 const APInt *SelectionDAG::getValidMinimumShiftAmountConstant(
2711     SDValue V, const APInt &DemandedElts) const {
2712   assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
2713           V.getOpcode() == ISD::SRA) &&
2714          "Unknown shift node");
2715   if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts))
2716     return ValidAmt;
2717   unsigned BitWidth = V.getScalarValueSizeInBits();
2718   auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1));
2719   if (!BV)
2720     return nullptr;
2721   const APInt *MinShAmt = nullptr;
2722   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
2723     if (!DemandedElts[i])
2724       continue;
2725     auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i));
2726     if (!SA)
2727       return nullptr;
2728     // Shifting more than the bitwidth is not valid.
2729     const APInt &ShAmt = SA->getAPIntValue();
2730     if (ShAmt.uge(BitWidth))
2731       return nullptr;
2732     if (MinShAmt && MinShAmt->ule(ShAmt))
2733       continue;
2734     MinShAmt = &ShAmt;
2735   }
2736   return MinShAmt;
2737 }
2738 
2739 const APInt *SelectionDAG::getValidMaximumShiftAmountConstant(
2740     SDValue V, const APInt &DemandedElts) const {
2741   assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
2742           V.getOpcode() == ISD::SRA) &&
2743          "Unknown shift node");
2744   if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts))
2745     return ValidAmt;
2746   unsigned BitWidth = V.getScalarValueSizeInBits();
2747   auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1));
2748   if (!BV)
2749     return nullptr;
2750   const APInt *MaxShAmt = nullptr;
2751   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
2752     if (!DemandedElts[i])
2753       continue;
2754     auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i));
2755     if (!SA)
2756       return nullptr;
2757     // Shifting more than the bitwidth is not valid.
2758     const APInt &ShAmt = SA->getAPIntValue();
2759     if (ShAmt.uge(BitWidth))
2760       return nullptr;
2761     if (MaxShAmt && MaxShAmt->uge(ShAmt))
2762       continue;
2763     MaxShAmt = &ShAmt;
2764   }
2765   return MaxShAmt;
2766 }
2767 
2768 /// Determine which bits of Op are known to be either zero or one and return
2769 /// them in Known. For vectors, the known bits are those that are shared by
2770 /// every vector element.
2771 KnownBits SelectionDAG::computeKnownBits(SDValue Op, unsigned Depth) const {
2772   EVT VT = Op.getValueType();
2773 
2774   // TOOD: Until we have a plan for how to represent demanded elements for
2775   // scalable vectors, we can just bail out for now.
2776   if (Op.getValueType().isScalableVector()) {
2777     unsigned BitWidth = Op.getScalarValueSizeInBits();
2778     return KnownBits(BitWidth);
2779   }
2780 
2781   APInt DemandedElts = VT.isVector()
2782                            ? APInt::getAllOnes(VT.getVectorNumElements())
2783                            : APInt(1, 1);
2784   return computeKnownBits(Op, DemandedElts, Depth);
2785 }
2786 
2787 /// Determine which bits of Op are known to be either zero or one and return
2788 /// them in Known. The DemandedElts argument allows us to only collect the known
2789 /// bits that are shared by the requested vector elements.
2790 KnownBits SelectionDAG::computeKnownBits(SDValue Op, const APInt &DemandedElts,
2791                                          unsigned Depth) const {
2792   unsigned BitWidth = Op.getScalarValueSizeInBits();
2793 
2794   KnownBits Known(BitWidth);   // Don't know anything.
2795 
2796   // TOOD: Until we have a plan for how to represent demanded elements for
2797   // scalable vectors, we can just bail out for now.
2798   if (Op.getValueType().isScalableVector())
2799     return Known;
2800 
2801   if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
2802     // We know all of the bits for a constant!
2803     return KnownBits::makeConstant(C->getAPIntValue());
2804   }
2805   if (auto *C = dyn_cast<ConstantFPSDNode>(Op)) {
2806     // We know all of the bits for a constant fp!
2807     return KnownBits::makeConstant(C->getValueAPF().bitcastToAPInt());
2808   }
2809 
2810   if (Depth >= MaxRecursionDepth)
2811     return Known;  // Limit search depth.
2812 
2813   KnownBits Known2;
2814   unsigned NumElts = DemandedElts.getBitWidth();
2815   assert((!Op.getValueType().isVector() ||
2816           NumElts == Op.getValueType().getVectorNumElements()) &&
2817          "Unexpected vector size");
2818 
2819   if (!DemandedElts)
2820     return Known;  // No demanded elts, better to assume we don't know anything.
2821 
2822   unsigned Opcode = Op.getOpcode();
2823   switch (Opcode) {
2824   case ISD::BUILD_VECTOR:
2825     // Collect the known bits that are shared by every demanded vector element.
2826     Known.Zero.setAllBits(); Known.One.setAllBits();
2827     for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
2828       if (!DemandedElts[i])
2829         continue;
2830 
2831       SDValue SrcOp = Op.getOperand(i);
2832       Known2 = computeKnownBits(SrcOp, Depth + 1);
2833 
2834       // BUILD_VECTOR can implicitly truncate sources, we must handle this.
2835       if (SrcOp.getValueSizeInBits() != BitWidth) {
2836         assert(SrcOp.getValueSizeInBits() > BitWidth &&
2837                "Expected BUILD_VECTOR implicit truncation");
2838         Known2 = Known2.trunc(BitWidth);
2839       }
2840 
2841       // Known bits are the values that are shared by every demanded element.
2842       Known = KnownBits::commonBits(Known, Known2);
2843 
2844       // If we don't know any bits, early out.
2845       if (Known.isUnknown())
2846         break;
2847     }
2848     break;
2849   case ISD::VECTOR_SHUFFLE: {
2850     // Collect the known bits that are shared by every vector element referenced
2851     // by the shuffle.
2852     APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
2853     Known.Zero.setAllBits(); Known.One.setAllBits();
2854     const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
2855     assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
2856     for (unsigned i = 0; i != NumElts; ++i) {
2857       if (!DemandedElts[i])
2858         continue;
2859 
2860       int M = SVN->getMaskElt(i);
2861       if (M < 0) {
2862         // For UNDEF elements, we don't know anything about the common state of
2863         // the shuffle result.
2864         Known.resetAll();
2865         DemandedLHS.clearAllBits();
2866         DemandedRHS.clearAllBits();
2867         break;
2868       }
2869 
2870       if ((unsigned)M < NumElts)
2871         DemandedLHS.setBit((unsigned)M % NumElts);
2872       else
2873         DemandedRHS.setBit((unsigned)M % NumElts);
2874     }
2875     // Known bits are the values that are shared by every demanded element.
2876     if (!!DemandedLHS) {
2877       SDValue LHS = Op.getOperand(0);
2878       Known2 = computeKnownBits(LHS, DemandedLHS, Depth + 1);
2879       Known = KnownBits::commonBits(Known, Known2);
2880     }
2881     // If we don't know any bits, early out.
2882     if (Known.isUnknown())
2883       break;
2884     if (!!DemandedRHS) {
2885       SDValue RHS = Op.getOperand(1);
2886       Known2 = computeKnownBits(RHS, DemandedRHS, Depth + 1);
2887       Known = KnownBits::commonBits(Known, Known2);
2888     }
2889     break;
2890   }
2891   case ISD::CONCAT_VECTORS: {
2892     // Split DemandedElts and test each of the demanded subvectors.
2893     Known.Zero.setAllBits(); Known.One.setAllBits();
2894     EVT SubVectorVT = Op.getOperand(0).getValueType();
2895     unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
2896     unsigned NumSubVectors = Op.getNumOperands();
2897     for (unsigned i = 0; i != NumSubVectors; ++i) {
2898       APInt DemandedSub =
2899           DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts);
2900       if (!!DemandedSub) {
2901         SDValue Sub = Op.getOperand(i);
2902         Known2 = computeKnownBits(Sub, DemandedSub, Depth + 1);
2903         Known = KnownBits::commonBits(Known, Known2);
2904       }
2905       // If we don't know any bits, early out.
2906       if (Known.isUnknown())
2907         break;
2908     }
2909     break;
2910   }
2911   case ISD::INSERT_SUBVECTOR: {
2912     // Demand any elements from the subvector and the remainder from the src its
2913     // inserted into.
2914     SDValue Src = Op.getOperand(0);
2915     SDValue Sub = Op.getOperand(1);
2916     uint64_t Idx = Op.getConstantOperandVal(2);
2917     unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
2918     APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
2919     APInt DemandedSrcElts = DemandedElts;
2920     DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx);
2921 
2922     Known.One.setAllBits();
2923     Known.Zero.setAllBits();
2924     if (!!DemandedSubElts) {
2925       Known = computeKnownBits(Sub, DemandedSubElts, Depth + 1);
2926       if (Known.isUnknown())
2927         break; // early-out.
2928     }
2929     if (!!DemandedSrcElts) {
2930       Known2 = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
2931       Known = KnownBits::commonBits(Known, Known2);
2932     }
2933     break;
2934   }
2935   case ISD::EXTRACT_SUBVECTOR: {
2936     // Offset the demanded elts by the subvector index.
2937     SDValue Src = Op.getOperand(0);
2938     // Bail until we can represent demanded elements for scalable vectors.
2939     if (Src.getValueType().isScalableVector())
2940       break;
2941     uint64_t Idx = Op.getConstantOperandVal(1);
2942     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2943     APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
2944     Known = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
2945     break;
2946   }
2947   case ISD::SCALAR_TO_VECTOR: {
2948     // We know about scalar_to_vector as much as we know about it source,
2949     // which becomes the first element of otherwise unknown vector.
2950     if (DemandedElts != 1)
2951       break;
2952 
2953     SDValue N0 = Op.getOperand(0);
2954     Known = computeKnownBits(N0, Depth + 1);
2955     if (N0.getValueSizeInBits() != BitWidth)
2956       Known = Known.trunc(BitWidth);
2957 
2958     break;
2959   }
2960   case ISD::BITCAST: {
2961     SDValue N0 = Op.getOperand(0);
2962     EVT SubVT = N0.getValueType();
2963     unsigned SubBitWidth = SubVT.getScalarSizeInBits();
2964 
2965     // Ignore bitcasts from unsupported types.
2966     if (!(SubVT.isInteger() || SubVT.isFloatingPoint()))
2967       break;
2968 
2969     // Fast handling of 'identity' bitcasts.
2970     if (BitWidth == SubBitWidth) {
2971       Known = computeKnownBits(N0, DemandedElts, Depth + 1);
2972       break;
2973     }
2974 
2975     bool IsLE = getDataLayout().isLittleEndian();
2976 
2977     // Bitcast 'small element' vector to 'large element' scalar/vector.
2978     if ((BitWidth % SubBitWidth) == 0) {
2979       assert(N0.getValueType().isVector() && "Expected bitcast from vector");
2980 
2981       // Collect known bits for the (larger) output by collecting the known
2982       // bits from each set of sub elements and shift these into place.
2983       // We need to separately call computeKnownBits for each set of
2984       // sub elements as the knownbits for each is likely to be different.
2985       unsigned SubScale = BitWidth / SubBitWidth;
2986       APInt SubDemandedElts(NumElts * SubScale, 0);
2987       for (unsigned i = 0; i != NumElts; ++i)
2988         if (DemandedElts[i])
2989           SubDemandedElts.setBit(i * SubScale);
2990 
2991       for (unsigned i = 0; i != SubScale; ++i) {
2992         Known2 = computeKnownBits(N0, SubDemandedElts.shl(i),
2993                          Depth + 1);
2994         unsigned Shifts = IsLE ? i : SubScale - 1 - i;
2995         Known.insertBits(Known2, SubBitWidth * Shifts);
2996       }
2997     }
2998 
2999     // Bitcast 'large element' scalar/vector to 'small element' vector.
3000     if ((SubBitWidth % BitWidth) == 0) {
3001       assert(Op.getValueType().isVector() && "Expected bitcast to vector");
3002 
3003       // Collect known bits for the (smaller) output by collecting the known
3004       // bits from the overlapping larger input elements and extracting the
3005       // sub sections we actually care about.
3006       unsigned SubScale = SubBitWidth / BitWidth;
3007       APInt SubDemandedElts =
3008           APIntOps::ScaleBitMask(DemandedElts, NumElts / SubScale);
3009       Known2 = computeKnownBits(N0, SubDemandedElts, Depth + 1);
3010 
3011       Known.Zero.setAllBits(); Known.One.setAllBits();
3012       for (unsigned i = 0; i != NumElts; ++i)
3013         if (DemandedElts[i]) {
3014           unsigned Shifts = IsLE ? i : NumElts - 1 - i;
3015           unsigned Offset = (Shifts % SubScale) * BitWidth;
3016           Known = KnownBits::commonBits(Known,
3017                                         Known2.extractBits(BitWidth, Offset));
3018           // If we don't know any bits, early out.
3019           if (Known.isUnknown())
3020             break;
3021         }
3022     }
3023     break;
3024   }
3025   case ISD::AND:
3026     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3027     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3028 
3029     Known &= Known2;
3030     break;
3031   case ISD::OR:
3032     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3033     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3034 
3035     Known |= Known2;
3036     break;
3037   case ISD::XOR:
3038     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3039     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3040 
3041     Known ^= Known2;
3042     break;
3043   case ISD::MUL: {
3044     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3045     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3046     Known = KnownBits::mul(Known, Known2);
3047     break;
3048   }
3049   case ISD::MULHU: {
3050     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3051     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3052     Known = KnownBits::mulhu(Known, Known2);
3053     break;
3054   }
3055   case ISD::MULHS: {
3056     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3057     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3058     Known = KnownBits::mulhs(Known, Known2);
3059     break;
3060   }
3061   case ISD::UMUL_LOHI: {
3062     assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3063     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3064     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3065     if (Op.getResNo() == 0)
3066       Known = KnownBits::mul(Known, Known2);
3067     else
3068       Known = KnownBits::mulhu(Known, Known2);
3069     break;
3070   }
3071   case ISD::SMUL_LOHI: {
3072     assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3073     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3074     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3075     if (Op.getResNo() == 0)
3076       Known = KnownBits::mul(Known, Known2);
3077     else
3078       Known = KnownBits::mulhs(Known, Known2);
3079     break;
3080   }
3081   case ISD::UDIV: {
3082     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3083     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3084     Known = KnownBits::udiv(Known, Known2);
3085     break;
3086   }
3087   case ISD::SELECT:
3088   case ISD::VSELECT:
3089     Known = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
3090     // If we don't know any bits, early out.
3091     if (Known.isUnknown())
3092       break;
3093     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth+1);
3094 
3095     // Only known if known in both the LHS and RHS.
3096     Known = KnownBits::commonBits(Known, Known2);
3097     break;
3098   case ISD::SELECT_CC:
3099     Known = computeKnownBits(Op.getOperand(3), DemandedElts, Depth+1);
3100     // If we don't know any bits, early out.
3101     if (Known.isUnknown())
3102       break;
3103     Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
3104 
3105     // Only known if known in both the LHS and RHS.
3106     Known = KnownBits::commonBits(Known, Known2);
3107     break;
3108   case ISD::SMULO:
3109   case ISD::UMULO:
3110     if (Op.getResNo() != 1)
3111       break;
3112     // The boolean result conforms to getBooleanContents.
3113     // If we know the result of a setcc has the top bits zero, use this info.
3114     // We know that we have an integer-based boolean since these operations
3115     // are only available for integer.
3116     if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
3117             TargetLowering::ZeroOrOneBooleanContent &&
3118         BitWidth > 1)
3119       Known.Zero.setBitsFrom(1);
3120     break;
3121   case ISD::SETCC:
3122   case ISD::STRICT_FSETCC:
3123   case ISD::STRICT_FSETCCS: {
3124     unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
3125     // If we know the result of a setcc has the top bits zero, use this info.
3126     if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
3127             TargetLowering::ZeroOrOneBooleanContent &&
3128         BitWidth > 1)
3129       Known.Zero.setBitsFrom(1);
3130     break;
3131   }
3132   case ISD::SHL:
3133     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3134     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3135     Known = KnownBits::shl(Known, Known2);
3136 
3137     // Minimum shift low bits are known zero.
3138     if (const APInt *ShMinAmt =
3139             getValidMinimumShiftAmountConstant(Op, DemandedElts))
3140       Known.Zero.setLowBits(ShMinAmt->getZExtValue());
3141     break;
3142   case ISD::SRL:
3143     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3144     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3145     Known = KnownBits::lshr(Known, Known2);
3146 
3147     // Minimum shift high bits are known zero.
3148     if (const APInt *ShMinAmt =
3149             getValidMinimumShiftAmountConstant(Op, DemandedElts))
3150       Known.Zero.setHighBits(ShMinAmt->getZExtValue());
3151     break;
3152   case ISD::SRA:
3153     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3154     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3155     Known = KnownBits::ashr(Known, Known2);
3156     // TODO: Add minimum shift high known sign bits.
3157     break;
3158   case ISD::FSHL:
3159   case ISD::FSHR:
3160     if (ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(2), DemandedElts)) {
3161       unsigned Amt = C->getAPIntValue().urem(BitWidth);
3162 
3163       // For fshl, 0-shift returns the 1st arg.
3164       // For fshr, 0-shift returns the 2nd arg.
3165       if (Amt == 0) {
3166         Known = computeKnownBits(Op.getOperand(Opcode == ISD::FSHL ? 0 : 1),
3167                                  DemandedElts, Depth + 1);
3168         break;
3169       }
3170 
3171       // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
3172       // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
3173       Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3174       Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3175       if (Opcode == ISD::FSHL) {
3176         Known.One <<= Amt;
3177         Known.Zero <<= Amt;
3178         Known2.One.lshrInPlace(BitWidth - Amt);
3179         Known2.Zero.lshrInPlace(BitWidth - Amt);
3180       } else {
3181         Known.One <<= BitWidth - Amt;
3182         Known.Zero <<= BitWidth - Amt;
3183         Known2.One.lshrInPlace(Amt);
3184         Known2.Zero.lshrInPlace(Amt);
3185       }
3186       Known.One |= Known2.One;
3187       Known.Zero |= Known2.Zero;
3188     }
3189     break;
3190   case ISD::SIGN_EXTEND_INREG: {
3191     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3192     EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3193     Known = Known.sextInReg(EVT.getScalarSizeInBits());
3194     break;
3195   }
3196   case ISD::CTTZ:
3197   case ISD::CTTZ_ZERO_UNDEF: {
3198     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3199     // If we have a known 1, its position is our upper bound.
3200     unsigned PossibleTZ = Known2.countMaxTrailingZeros();
3201     unsigned LowBits = Log2_32(PossibleTZ) + 1;
3202     Known.Zero.setBitsFrom(LowBits);
3203     break;
3204   }
3205   case ISD::CTLZ:
3206   case ISD::CTLZ_ZERO_UNDEF: {
3207     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3208     // If we have a known 1, its position is our upper bound.
3209     unsigned PossibleLZ = Known2.countMaxLeadingZeros();
3210     unsigned LowBits = Log2_32(PossibleLZ) + 1;
3211     Known.Zero.setBitsFrom(LowBits);
3212     break;
3213   }
3214   case ISD::CTPOP: {
3215     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3216     // If we know some of the bits are zero, they can't be one.
3217     unsigned PossibleOnes = Known2.countMaxPopulation();
3218     Known.Zero.setBitsFrom(Log2_32(PossibleOnes) + 1);
3219     break;
3220   }
3221   case ISD::PARITY: {
3222     // Parity returns 0 everywhere but the LSB.
3223     Known.Zero.setBitsFrom(1);
3224     break;
3225   }
3226   case ISD::LOAD: {
3227     LoadSDNode *LD = cast<LoadSDNode>(Op);
3228     const Constant *Cst = TLI->getTargetConstantFromLoad(LD);
3229     if (ISD::isNON_EXTLoad(LD) && Cst) {
3230       // Determine any common known bits from the loaded constant pool value.
3231       Type *CstTy = Cst->getType();
3232       if ((NumElts * BitWidth) == CstTy->getPrimitiveSizeInBits()) {
3233         // If its a vector splat, then we can (quickly) reuse the scalar path.
3234         // NOTE: We assume all elements match and none are UNDEF.
3235         if (CstTy->isVectorTy()) {
3236           if (const Constant *Splat = Cst->getSplatValue()) {
3237             Cst = Splat;
3238             CstTy = Cst->getType();
3239           }
3240         }
3241         // TODO - do we need to handle different bitwidths?
3242         if (CstTy->isVectorTy() && BitWidth == CstTy->getScalarSizeInBits()) {
3243           // Iterate across all vector elements finding common known bits.
3244           Known.One.setAllBits();
3245           Known.Zero.setAllBits();
3246           for (unsigned i = 0; i != NumElts; ++i) {
3247             if (!DemandedElts[i])
3248               continue;
3249             if (Constant *Elt = Cst->getAggregateElement(i)) {
3250               if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
3251                 const APInt &Value = CInt->getValue();
3252                 Known.One &= Value;
3253                 Known.Zero &= ~Value;
3254                 continue;
3255               }
3256               if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
3257                 APInt Value = CFP->getValueAPF().bitcastToAPInt();
3258                 Known.One &= Value;
3259                 Known.Zero &= ~Value;
3260                 continue;
3261               }
3262             }
3263             Known.One.clearAllBits();
3264             Known.Zero.clearAllBits();
3265             break;
3266           }
3267         } else if (BitWidth == CstTy->getPrimitiveSizeInBits()) {
3268           if (auto *CInt = dyn_cast<ConstantInt>(Cst)) {
3269             Known = KnownBits::makeConstant(CInt->getValue());
3270           } else if (auto *CFP = dyn_cast<ConstantFP>(Cst)) {
3271             Known =
3272                 KnownBits::makeConstant(CFP->getValueAPF().bitcastToAPInt());
3273           }
3274         }
3275       }
3276     } else if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) {
3277       // If this is a ZEXTLoad and we are looking at the loaded value.
3278       EVT VT = LD->getMemoryVT();
3279       unsigned MemBits = VT.getScalarSizeInBits();
3280       Known.Zero.setBitsFrom(MemBits);
3281     } else if (const MDNode *Ranges = LD->getRanges()) {
3282       if (LD->getExtensionType() == ISD::NON_EXTLOAD)
3283         computeKnownBitsFromRangeMetadata(*Ranges, Known);
3284     }
3285     break;
3286   }
3287   case ISD::ZERO_EXTEND_VECTOR_INREG: {
3288     EVT InVT = Op.getOperand(0).getValueType();
3289     APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements());
3290     Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3291     Known = Known.zext(BitWidth);
3292     break;
3293   }
3294   case ISD::ZERO_EXTEND: {
3295     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3296     Known = Known.zext(BitWidth);
3297     break;
3298   }
3299   case ISD::SIGN_EXTEND_VECTOR_INREG: {
3300     EVT InVT = Op.getOperand(0).getValueType();
3301     APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements());
3302     Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3303     // If the sign bit is known to be zero or one, then sext will extend
3304     // it to the top bits, else it will just zext.
3305     Known = Known.sext(BitWidth);
3306     break;
3307   }
3308   case ISD::SIGN_EXTEND: {
3309     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3310     // If the sign bit is known to be zero or one, then sext will extend
3311     // it to the top bits, else it will just zext.
3312     Known = Known.sext(BitWidth);
3313     break;
3314   }
3315   case ISD::ANY_EXTEND_VECTOR_INREG: {
3316     EVT InVT = Op.getOperand(0).getValueType();
3317     APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements());
3318     Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3319     Known = Known.anyext(BitWidth);
3320     break;
3321   }
3322   case ISD::ANY_EXTEND: {
3323     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3324     Known = Known.anyext(BitWidth);
3325     break;
3326   }
3327   case ISD::TRUNCATE: {
3328     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3329     Known = Known.trunc(BitWidth);
3330     break;
3331   }
3332   case ISD::AssertZext: {
3333     EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3334     APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits());
3335     Known = computeKnownBits(Op.getOperand(0), Depth+1);
3336     Known.Zero |= (~InMask);
3337     Known.One  &= (~Known.Zero);
3338     break;
3339   }
3340   case ISD::AssertAlign: {
3341     unsigned LogOfAlign = Log2(cast<AssertAlignSDNode>(Op)->getAlign());
3342     assert(LogOfAlign != 0);
3343     // If a node is guaranteed to be aligned, set low zero bits accordingly as
3344     // well as clearing one bits.
3345     Known.Zero.setLowBits(LogOfAlign);
3346     Known.One.clearLowBits(LogOfAlign);
3347     break;
3348   }
3349   case ISD::FGETSIGN:
3350     // All bits are zero except the low bit.
3351     Known.Zero.setBitsFrom(1);
3352     break;
3353   case ISD::USUBO:
3354   case ISD::SSUBO:
3355     if (Op.getResNo() == 1) {
3356       // If we know the result of a setcc has the top bits zero, use this info.
3357       if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
3358               TargetLowering::ZeroOrOneBooleanContent &&
3359           BitWidth > 1)
3360         Known.Zero.setBitsFrom(1);
3361       break;
3362     }
3363     LLVM_FALLTHROUGH;
3364   case ISD::SUB:
3365   case ISD::SUBC: {
3366     assert(Op.getResNo() == 0 &&
3367            "We only compute knownbits for the difference here.");
3368 
3369     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3370     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3371     Known = KnownBits::computeForAddSub(/* Add */ false, /* NSW */ false,
3372                                         Known, Known2);
3373     break;
3374   }
3375   case ISD::UADDO:
3376   case ISD::SADDO:
3377   case ISD::ADDCARRY:
3378     if (Op.getResNo() == 1) {
3379       // If we know the result of a setcc has the top bits zero, use this info.
3380       if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
3381               TargetLowering::ZeroOrOneBooleanContent &&
3382           BitWidth > 1)
3383         Known.Zero.setBitsFrom(1);
3384       break;
3385     }
3386     LLVM_FALLTHROUGH;
3387   case ISD::ADD:
3388   case ISD::ADDC:
3389   case ISD::ADDE: {
3390     assert(Op.getResNo() == 0 && "We only compute knownbits for the sum here.");
3391 
3392     // With ADDE and ADDCARRY, a carry bit may be added in.
3393     KnownBits Carry(1);
3394     if (Opcode == ISD::ADDE)
3395       // Can't track carry from glue, set carry to unknown.
3396       Carry.resetAll();
3397     else if (Opcode == ISD::ADDCARRY)
3398       // TODO: Compute known bits for the carry operand. Not sure if it is worth
3399       // the trouble (how often will we find a known carry bit). And I haven't
3400       // tested this very much yet, but something like this might work:
3401       //   Carry = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1);
3402       //   Carry = Carry.zextOrTrunc(1, false);
3403       Carry.resetAll();
3404     else
3405       Carry.setAllZero();
3406 
3407     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3408     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3409     Known = KnownBits::computeForAddCarry(Known, Known2, Carry);
3410     break;
3411   }
3412   case ISD::SREM: {
3413     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3414     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3415     Known = KnownBits::srem(Known, Known2);
3416     break;
3417   }
3418   case ISD::UREM: {
3419     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3420     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3421     Known = KnownBits::urem(Known, Known2);
3422     break;
3423   }
3424   case ISD::EXTRACT_ELEMENT: {
3425     Known = computeKnownBits(Op.getOperand(0), Depth+1);
3426     const unsigned Index = Op.getConstantOperandVal(1);
3427     const unsigned EltBitWidth = Op.getValueSizeInBits();
3428 
3429     // Remove low part of known bits mask
3430     Known.Zero = Known.Zero.getHiBits(Known.getBitWidth() - Index * EltBitWidth);
3431     Known.One = Known.One.getHiBits(Known.getBitWidth() - Index * EltBitWidth);
3432 
3433     // Remove high part of known bit mask
3434     Known = Known.trunc(EltBitWidth);
3435     break;
3436   }
3437   case ISD::EXTRACT_VECTOR_ELT: {
3438     SDValue InVec = Op.getOperand(0);
3439     SDValue EltNo = Op.getOperand(1);
3440     EVT VecVT = InVec.getValueType();
3441     // computeKnownBits not yet implemented for scalable vectors.
3442     if (VecVT.isScalableVector())
3443       break;
3444     const unsigned EltBitWidth = VecVT.getScalarSizeInBits();
3445     const unsigned NumSrcElts = VecVT.getVectorNumElements();
3446 
3447     // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know
3448     // anything about the extended bits.
3449     if (BitWidth > EltBitWidth)
3450       Known = Known.trunc(EltBitWidth);
3451 
3452     // If we know the element index, just demand that vector element, else for
3453     // an unknown element index, ignore DemandedElts and demand them all.
3454     APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
3455     auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
3456     if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
3457       DemandedSrcElts =
3458           APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
3459 
3460     Known = computeKnownBits(InVec, DemandedSrcElts, Depth + 1);
3461     if (BitWidth > EltBitWidth)
3462       Known = Known.anyext(BitWidth);
3463     break;
3464   }
3465   case ISD::INSERT_VECTOR_ELT: {
3466     // If we know the element index, split the demand between the
3467     // source vector and the inserted element, otherwise assume we need
3468     // the original demanded vector elements and the value.
3469     SDValue InVec = Op.getOperand(0);
3470     SDValue InVal = Op.getOperand(1);
3471     SDValue EltNo = Op.getOperand(2);
3472     bool DemandedVal = true;
3473     APInt DemandedVecElts = DemandedElts;
3474     auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
3475     if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
3476       unsigned EltIdx = CEltNo->getZExtValue();
3477       DemandedVal = !!DemandedElts[EltIdx];
3478       DemandedVecElts.clearBit(EltIdx);
3479     }
3480     Known.One.setAllBits();
3481     Known.Zero.setAllBits();
3482     if (DemandedVal) {
3483       Known2 = computeKnownBits(InVal, Depth + 1);
3484       Known = KnownBits::commonBits(Known, Known2.zextOrTrunc(BitWidth));
3485     }
3486     if (!!DemandedVecElts) {
3487       Known2 = computeKnownBits(InVec, DemandedVecElts, Depth + 1);
3488       Known = KnownBits::commonBits(Known, Known2);
3489     }
3490     break;
3491   }
3492   case ISD::BITREVERSE: {
3493     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3494     Known = Known2.reverseBits();
3495     break;
3496   }
3497   case ISD::BSWAP: {
3498     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3499     Known = Known2.byteSwap();
3500     break;
3501   }
3502   case ISD::ABS: {
3503     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3504     Known = Known2.abs();
3505     break;
3506   }
3507   case ISD::USUBSAT: {
3508     // The result of usubsat will never be larger than the LHS.
3509     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3510     Known.Zero.setHighBits(Known2.countMinLeadingZeros());
3511     break;
3512   }
3513   case ISD::UMIN: {
3514     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3515     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3516     Known = KnownBits::umin(Known, Known2);
3517     break;
3518   }
3519   case ISD::UMAX: {
3520     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3521     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3522     Known = KnownBits::umax(Known, Known2);
3523     break;
3524   }
3525   case ISD::SMIN:
3526   case ISD::SMAX: {
3527     // If we have a clamp pattern, we know that the number of sign bits will be
3528     // the minimum of the clamp min/max range.
3529     bool IsMax = (Opcode == ISD::SMAX);
3530     ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
3531     if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
3532       if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
3533         CstHigh =
3534             isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
3535     if (CstLow && CstHigh) {
3536       if (!IsMax)
3537         std::swap(CstLow, CstHigh);
3538 
3539       const APInt &ValueLow = CstLow->getAPIntValue();
3540       const APInt &ValueHigh = CstHigh->getAPIntValue();
3541       if (ValueLow.sle(ValueHigh)) {
3542         unsigned LowSignBits = ValueLow.getNumSignBits();
3543         unsigned HighSignBits = ValueHigh.getNumSignBits();
3544         unsigned MinSignBits = std::min(LowSignBits, HighSignBits);
3545         if (ValueLow.isNegative() && ValueHigh.isNegative()) {
3546           Known.One.setHighBits(MinSignBits);
3547           break;
3548         }
3549         if (ValueLow.isNonNegative() && ValueHigh.isNonNegative()) {
3550           Known.Zero.setHighBits(MinSignBits);
3551           break;
3552         }
3553       }
3554     }
3555 
3556     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3557     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3558     if (IsMax)
3559       Known = KnownBits::smax(Known, Known2);
3560     else
3561       Known = KnownBits::smin(Known, Known2);
3562     break;
3563   }
3564   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
3565     if (Op.getResNo() == 1) {
3566       // The boolean result conforms to getBooleanContents.
3567       // If we know the result of a setcc has the top bits zero, use this info.
3568       // We know that we have an integer-based boolean since these operations
3569       // are only available for integer.
3570       if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
3571               TargetLowering::ZeroOrOneBooleanContent &&
3572           BitWidth > 1)
3573         Known.Zero.setBitsFrom(1);
3574       break;
3575     }
3576     LLVM_FALLTHROUGH;
3577   case ISD::ATOMIC_CMP_SWAP:
3578   case ISD::ATOMIC_SWAP:
3579   case ISD::ATOMIC_LOAD_ADD:
3580   case ISD::ATOMIC_LOAD_SUB:
3581   case ISD::ATOMIC_LOAD_AND:
3582   case ISD::ATOMIC_LOAD_CLR:
3583   case ISD::ATOMIC_LOAD_OR:
3584   case ISD::ATOMIC_LOAD_XOR:
3585   case ISD::ATOMIC_LOAD_NAND:
3586   case ISD::ATOMIC_LOAD_MIN:
3587   case ISD::ATOMIC_LOAD_MAX:
3588   case ISD::ATOMIC_LOAD_UMIN:
3589   case ISD::ATOMIC_LOAD_UMAX:
3590   case ISD::ATOMIC_LOAD: {
3591     unsigned MemBits =
3592         cast<AtomicSDNode>(Op)->getMemoryVT().getScalarSizeInBits();
3593     // If we are looking at the loaded value.
3594     if (Op.getResNo() == 0) {
3595       if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND)
3596         Known.Zero.setBitsFrom(MemBits);
3597     }
3598     break;
3599   }
3600   case ISD::FrameIndex:
3601   case ISD::TargetFrameIndex:
3602     TLI->computeKnownBitsForFrameIndex(cast<FrameIndexSDNode>(Op)->getIndex(),
3603                                        Known, getMachineFunction());
3604     break;
3605 
3606   default:
3607     if (Opcode < ISD::BUILTIN_OP_END)
3608       break;
3609     LLVM_FALLTHROUGH;
3610   case ISD::INTRINSIC_WO_CHAIN:
3611   case ISD::INTRINSIC_W_CHAIN:
3612   case ISD::INTRINSIC_VOID:
3613     // Allow the target to implement this method for its nodes.
3614     TLI->computeKnownBitsForTargetNode(Op, Known, DemandedElts, *this, Depth);
3615     break;
3616   }
3617 
3618   assert(!Known.hasConflict() && "Bits known to be one AND zero?");
3619   return Known;
3620 }
3621 
3622 SelectionDAG::OverflowKind SelectionDAG::computeOverflowKind(SDValue N0,
3623                                                              SDValue N1) const {
3624   // X + 0 never overflow
3625   if (isNullConstant(N1))
3626     return OFK_Never;
3627 
3628   KnownBits N1Known = computeKnownBits(N1);
3629   if (N1Known.Zero.getBoolValue()) {
3630     KnownBits N0Known = computeKnownBits(N0);
3631 
3632     bool overflow;
3633     (void)N0Known.getMaxValue().uadd_ov(N1Known.getMaxValue(), overflow);
3634     if (!overflow)
3635       return OFK_Never;
3636   }
3637 
3638   // mulhi + 1 never overflow
3639   if (N0.getOpcode() == ISD::UMUL_LOHI && N0.getResNo() == 1 &&
3640       (N1Known.getMaxValue() & 0x01) == N1Known.getMaxValue())
3641     return OFK_Never;
3642 
3643   if (N1.getOpcode() == ISD::UMUL_LOHI && N1.getResNo() == 1) {
3644     KnownBits N0Known = computeKnownBits(N0);
3645 
3646     if ((N0Known.getMaxValue() & 0x01) == N0Known.getMaxValue())
3647       return OFK_Never;
3648   }
3649 
3650   return OFK_Sometime;
3651 }
3652 
3653 bool SelectionDAG::isKnownToBeAPowerOfTwo(SDValue Val) const {
3654   EVT OpVT = Val.getValueType();
3655   unsigned BitWidth = OpVT.getScalarSizeInBits();
3656 
3657   // Is the constant a known power of 2?
3658   if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Val))
3659     return Const->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
3660 
3661   // A left-shift of a constant one will have exactly one bit set because
3662   // shifting the bit off the end is undefined.
3663   if (Val.getOpcode() == ISD::SHL) {
3664     auto *C = isConstOrConstSplat(Val.getOperand(0));
3665     if (C && C->getAPIntValue() == 1)
3666       return true;
3667   }
3668 
3669   // Similarly, a logical right-shift of a constant sign-bit will have exactly
3670   // one bit set.
3671   if (Val.getOpcode() == ISD::SRL) {
3672     auto *C = isConstOrConstSplat(Val.getOperand(0));
3673     if (C && C->getAPIntValue().isSignMask())
3674       return true;
3675   }
3676 
3677   // Are all operands of a build vector constant powers of two?
3678   if (Val.getOpcode() == ISD::BUILD_VECTOR)
3679     if (llvm::all_of(Val->ops(), [BitWidth](SDValue E) {
3680           if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(E))
3681             return C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
3682           return false;
3683         }))
3684       return true;
3685 
3686   // Is the operand of a splat vector a constant power of two?
3687   if (Val.getOpcode() == ISD::SPLAT_VECTOR)
3688     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val->getOperand(0)))
3689       if (C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2())
3690         return true;
3691 
3692   // More could be done here, though the above checks are enough
3693   // to handle some common cases.
3694 
3695   // Fall back to computeKnownBits to catch other known cases.
3696   KnownBits Known = computeKnownBits(Val);
3697   return (Known.countMaxPopulation() == 1) && (Known.countMinPopulation() == 1);
3698 }
3699 
3700 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const {
3701   EVT VT = Op.getValueType();
3702 
3703   // TODO: Assume we don't know anything for now.
3704   if (VT.isScalableVector())
3705     return 1;
3706 
3707   APInt DemandedElts = VT.isVector()
3708                            ? APInt::getAllOnes(VT.getVectorNumElements())
3709                            : APInt(1, 1);
3710   return ComputeNumSignBits(Op, DemandedElts, Depth);
3711 }
3712 
3713 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, const APInt &DemandedElts,
3714                                           unsigned Depth) const {
3715   EVT VT = Op.getValueType();
3716   assert((VT.isInteger() || VT.isFloatingPoint()) && "Invalid VT!");
3717   unsigned VTBits = VT.getScalarSizeInBits();
3718   unsigned NumElts = DemandedElts.getBitWidth();
3719   unsigned Tmp, Tmp2;
3720   unsigned FirstAnswer = 1;
3721 
3722   if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
3723     const APInt &Val = C->getAPIntValue();
3724     return Val.getNumSignBits();
3725   }
3726 
3727   if (Depth >= MaxRecursionDepth)
3728     return 1;  // Limit search depth.
3729 
3730   if (!DemandedElts || VT.isScalableVector())
3731     return 1;  // No demanded elts, better to assume we don't know anything.
3732 
3733   unsigned Opcode = Op.getOpcode();
3734   switch (Opcode) {
3735   default: break;
3736   case ISD::AssertSext:
3737     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
3738     return VTBits-Tmp+1;
3739   case ISD::AssertZext:
3740     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
3741     return VTBits-Tmp;
3742 
3743   case ISD::BUILD_VECTOR:
3744     Tmp = VTBits;
3745     for (unsigned i = 0, e = Op.getNumOperands(); (i < e) && (Tmp > 1); ++i) {
3746       if (!DemandedElts[i])
3747         continue;
3748 
3749       SDValue SrcOp = Op.getOperand(i);
3750       Tmp2 = ComputeNumSignBits(SrcOp, Depth + 1);
3751 
3752       // BUILD_VECTOR can implicitly truncate sources, we must handle this.
3753       if (SrcOp.getValueSizeInBits() != VTBits) {
3754         assert(SrcOp.getValueSizeInBits() > VTBits &&
3755                "Expected BUILD_VECTOR implicit truncation");
3756         unsigned ExtraBits = SrcOp.getValueSizeInBits() - VTBits;
3757         Tmp2 = (Tmp2 > ExtraBits ? Tmp2 - ExtraBits : 1);
3758       }
3759       Tmp = std::min(Tmp, Tmp2);
3760     }
3761     return Tmp;
3762 
3763   case ISD::VECTOR_SHUFFLE: {
3764     // Collect the minimum number of sign bits that are shared by every vector
3765     // element referenced by the shuffle.
3766     APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
3767     const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
3768     assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
3769     for (unsigned i = 0; i != NumElts; ++i) {
3770       int M = SVN->getMaskElt(i);
3771       if (!DemandedElts[i])
3772         continue;
3773       // For UNDEF elements, we don't know anything about the common state of
3774       // the shuffle result.
3775       if (M < 0)
3776         return 1;
3777       if ((unsigned)M < NumElts)
3778         DemandedLHS.setBit((unsigned)M % NumElts);
3779       else
3780         DemandedRHS.setBit((unsigned)M % NumElts);
3781     }
3782     Tmp = std::numeric_limits<unsigned>::max();
3783     if (!!DemandedLHS)
3784       Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedLHS, Depth + 1);
3785     if (!!DemandedRHS) {
3786       Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedRHS, Depth + 1);
3787       Tmp = std::min(Tmp, Tmp2);
3788     }
3789     // If we don't know anything, early out and try computeKnownBits fall-back.
3790     if (Tmp == 1)
3791       break;
3792     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
3793     return Tmp;
3794   }
3795 
3796   case ISD::BITCAST: {
3797     SDValue N0 = Op.getOperand(0);
3798     EVT SrcVT = N0.getValueType();
3799     unsigned SrcBits = SrcVT.getScalarSizeInBits();
3800 
3801     // Ignore bitcasts from unsupported types..
3802     if (!(SrcVT.isInteger() || SrcVT.isFloatingPoint()))
3803       break;
3804 
3805     // Fast handling of 'identity' bitcasts.
3806     if (VTBits == SrcBits)
3807       return ComputeNumSignBits(N0, DemandedElts, Depth + 1);
3808 
3809     bool IsLE = getDataLayout().isLittleEndian();
3810 
3811     // Bitcast 'large element' scalar/vector to 'small element' vector.
3812     if ((SrcBits % VTBits) == 0) {
3813       assert(VT.isVector() && "Expected bitcast to vector");
3814 
3815       unsigned Scale = SrcBits / VTBits;
3816       APInt SrcDemandedElts =
3817           APIntOps::ScaleBitMask(DemandedElts, NumElts / Scale);
3818 
3819       // Fast case - sign splat can be simply split across the small elements.
3820       Tmp = ComputeNumSignBits(N0, SrcDemandedElts, Depth + 1);
3821       if (Tmp == SrcBits)
3822         return VTBits;
3823 
3824       // Slow case - determine how far the sign extends into each sub-element.
3825       Tmp2 = VTBits;
3826       for (unsigned i = 0; i != NumElts; ++i)
3827         if (DemandedElts[i]) {
3828           unsigned SubOffset = i % Scale;
3829           SubOffset = (IsLE ? ((Scale - 1) - SubOffset) : SubOffset);
3830           SubOffset = SubOffset * VTBits;
3831           if (Tmp <= SubOffset)
3832             return 1;
3833           Tmp2 = std::min(Tmp2, Tmp - SubOffset);
3834         }
3835       return Tmp2;
3836     }
3837     break;
3838   }
3839 
3840   case ISD::SIGN_EXTEND:
3841     Tmp = VTBits - Op.getOperand(0).getScalarValueSizeInBits();
3842     return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1) + Tmp;
3843   case ISD::SIGN_EXTEND_INREG:
3844     // Max of the input and what this extends.
3845     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
3846     Tmp = VTBits-Tmp+1;
3847     Tmp2 = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
3848     return std::max(Tmp, Tmp2);
3849   case ISD::SIGN_EXTEND_VECTOR_INREG: {
3850     SDValue Src = Op.getOperand(0);
3851     EVT SrcVT = Src.getValueType();
3852     APInt DemandedSrcElts = DemandedElts.zextOrSelf(SrcVT.getVectorNumElements());
3853     Tmp = VTBits - SrcVT.getScalarSizeInBits();
3854     return ComputeNumSignBits(Src, DemandedSrcElts, Depth+1) + Tmp;
3855   }
3856   case ISD::SRA:
3857     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3858     // SRA X, C -> adds C sign bits.
3859     if (const APInt *ShAmt =
3860             getValidMinimumShiftAmountConstant(Op, DemandedElts))
3861       Tmp = std::min<uint64_t>(Tmp + ShAmt->getZExtValue(), VTBits);
3862     return Tmp;
3863   case ISD::SHL:
3864     if (const APInt *ShAmt =
3865             getValidMaximumShiftAmountConstant(Op, DemandedElts)) {
3866       // shl destroys sign bits, ensure it doesn't shift out all sign bits.
3867       Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3868       if (ShAmt->ult(Tmp))
3869         return Tmp - ShAmt->getZExtValue();
3870     }
3871     break;
3872   case ISD::AND:
3873   case ISD::OR:
3874   case ISD::XOR:    // NOT is handled here.
3875     // Logical binary ops preserve the number of sign bits at the worst.
3876     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
3877     if (Tmp != 1) {
3878       Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
3879       FirstAnswer = std::min(Tmp, Tmp2);
3880       // We computed what we know about the sign bits as our first
3881       // answer. Now proceed to the generic code that uses
3882       // computeKnownBits, and pick whichever answer is better.
3883     }
3884     break;
3885 
3886   case ISD::SELECT:
3887   case ISD::VSELECT:
3888     Tmp = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
3889     if (Tmp == 1) return 1;  // Early out.
3890     Tmp2 = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
3891     return std::min(Tmp, Tmp2);
3892   case ISD::SELECT_CC:
3893     Tmp = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
3894     if (Tmp == 1) return 1;  // Early out.
3895     Tmp2 = ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth+1);
3896     return std::min(Tmp, Tmp2);
3897 
3898   case ISD::SMIN:
3899   case ISD::SMAX: {
3900     // If we have a clamp pattern, we know that the number of sign bits will be
3901     // the minimum of the clamp min/max range.
3902     bool IsMax = (Opcode == ISD::SMAX);
3903     ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
3904     if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
3905       if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
3906         CstHigh =
3907             isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
3908     if (CstLow && CstHigh) {
3909       if (!IsMax)
3910         std::swap(CstLow, CstHigh);
3911       if (CstLow->getAPIntValue().sle(CstHigh->getAPIntValue())) {
3912         Tmp = CstLow->getAPIntValue().getNumSignBits();
3913         Tmp2 = CstHigh->getAPIntValue().getNumSignBits();
3914         return std::min(Tmp, Tmp2);
3915       }
3916     }
3917 
3918     // Fallback - just get the minimum number of sign bits of the operands.
3919     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3920     if (Tmp == 1)
3921       return 1;  // Early out.
3922     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
3923     return std::min(Tmp, Tmp2);
3924   }
3925   case ISD::UMIN:
3926   case ISD::UMAX:
3927     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3928     if (Tmp == 1)
3929       return 1;  // Early out.
3930     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
3931     return std::min(Tmp, Tmp2);
3932   case ISD::SADDO:
3933   case ISD::UADDO:
3934   case ISD::SSUBO:
3935   case ISD::USUBO:
3936   case ISD::SMULO:
3937   case ISD::UMULO:
3938     if (Op.getResNo() != 1)
3939       break;
3940     // The boolean result conforms to getBooleanContents.  Fall through.
3941     // If setcc returns 0/-1, all bits are sign bits.
3942     // We know that we have an integer-based boolean since these operations
3943     // are only available for integer.
3944     if (TLI->getBooleanContents(VT.isVector(), false) ==
3945         TargetLowering::ZeroOrNegativeOneBooleanContent)
3946       return VTBits;
3947     break;
3948   case ISD::SETCC:
3949   case ISD::STRICT_FSETCC:
3950   case ISD::STRICT_FSETCCS: {
3951     unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
3952     // If setcc returns 0/-1, all bits are sign bits.
3953     if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
3954         TargetLowering::ZeroOrNegativeOneBooleanContent)
3955       return VTBits;
3956     break;
3957   }
3958   case ISD::ROTL:
3959   case ISD::ROTR:
3960     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3961 
3962     // If we're rotating an 0/-1 value, then it stays an 0/-1 value.
3963     if (Tmp == VTBits)
3964       return VTBits;
3965 
3966     if (ConstantSDNode *C =
3967             isConstOrConstSplat(Op.getOperand(1), DemandedElts)) {
3968       unsigned RotAmt = C->getAPIntValue().urem(VTBits);
3969 
3970       // Handle rotate right by N like a rotate left by 32-N.
3971       if (Opcode == ISD::ROTR)
3972         RotAmt = (VTBits - RotAmt) % VTBits;
3973 
3974       // If we aren't rotating out all of the known-in sign bits, return the
3975       // number that are left.  This handles rotl(sext(x), 1) for example.
3976       if (Tmp > (RotAmt + 1)) return (Tmp - RotAmt);
3977     }
3978     break;
3979   case ISD::ADD:
3980   case ISD::ADDC:
3981     // Add can have at most one carry bit.  Thus we know that the output
3982     // is, at worst, one more bit than the inputs.
3983     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3984     if (Tmp == 1) return 1; // Early out.
3985 
3986     // Special case decrementing a value (ADD X, -1):
3987     if (ConstantSDNode *CRHS =
3988             isConstOrConstSplat(Op.getOperand(1), DemandedElts))
3989       if (CRHS->isAllOnes()) {
3990         KnownBits Known =
3991             computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3992 
3993         // If the input is known to be 0 or 1, the output is 0/-1, which is all
3994         // sign bits set.
3995         if ((Known.Zero | 1).isAllOnes())
3996           return VTBits;
3997 
3998         // If we are subtracting one from a positive number, there is no carry
3999         // out of the result.
4000         if (Known.isNonNegative())
4001           return Tmp;
4002       }
4003 
4004     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
4005     if (Tmp2 == 1) return 1; // Early out.
4006     return std::min(Tmp, Tmp2) - 1;
4007   case ISD::SUB:
4008     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
4009     if (Tmp2 == 1) return 1; // Early out.
4010 
4011     // Handle NEG.
4012     if (ConstantSDNode *CLHS =
4013             isConstOrConstSplat(Op.getOperand(0), DemandedElts))
4014       if (CLHS->isZero()) {
4015         KnownBits Known =
4016             computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4017         // If the input is known to be 0 or 1, the output is 0/-1, which is all
4018         // sign bits set.
4019         if ((Known.Zero | 1).isAllOnes())
4020           return VTBits;
4021 
4022         // If the input is known to be positive (the sign bit is known clear),
4023         // the output of the NEG has the same number of sign bits as the input.
4024         if (Known.isNonNegative())
4025           return Tmp2;
4026 
4027         // Otherwise, we treat this like a SUB.
4028       }
4029 
4030     // Sub can have at most one carry bit.  Thus we know that the output
4031     // is, at worst, one more bit than the inputs.
4032     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4033     if (Tmp == 1) return 1; // Early out.
4034     return std::min(Tmp, Tmp2) - 1;
4035   case ISD::MUL: {
4036     // The output of the Mul can be at most twice the valid bits in the inputs.
4037     unsigned SignBitsOp0 = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
4038     if (SignBitsOp0 == 1)
4039       break;
4040     unsigned SignBitsOp1 = ComputeNumSignBits(Op.getOperand(1), Depth + 1);
4041     if (SignBitsOp1 == 1)
4042       break;
4043     unsigned OutValidBits =
4044         (VTBits - SignBitsOp0 + 1) + (VTBits - SignBitsOp1 + 1);
4045     return OutValidBits > VTBits ? 1 : VTBits - OutValidBits + 1;
4046   }
4047   case ISD::SREM:
4048     // The sign bit is the LHS's sign bit, except when the result of the
4049     // remainder is zero. The magnitude of the result should be less than or
4050     // equal to the magnitude of the LHS. Therefore, the result should have
4051     // at least as many sign bits as the left hand side.
4052     return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4053   case ISD::TRUNCATE: {
4054     // Check if the sign bits of source go down as far as the truncated value.
4055     unsigned NumSrcBits = Op.getOperand(0).getScalarValueSizeInBits();
4056     unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
4057     if (NumSrcSignBits > (NumSrcBits - VTBits))
4058       return NumSrcSignBits - (NumSrcBits - VTBits);
4059     break;
4060   }
4061   case ISD::EXTRACT_ELEMENT: {
4062     const int KnownSign = ComputeNumSignBits(Op.getOperand(0), Depth+1);
4063     const int BitWidth = Op.getValueSizeInBits();
4064     const int Items = Op.getOperand(0).getValueSizeInBits() / BitWidth;
4065 
4066     // Get reverse index (starting from 1), Op1 value indexes elements from
4067     // little end. Sign starts at big end.
4068     const int rIndex = Items - 1 - Op.getConstantOperandVal(1);
4069 
4070     // If the sign portion ends in our element the subtraction gives correct
4071     // result. Otherwise it gives either negative or > bitwidth result
4072     return std::max(std::min(KnownSign - rIndex * BitWidth, BitWidth), 0);
4073   }
4074   case ISD::INSERT_VECTOR_ELT: {
4075     // If we know the element index, split the demand between the
4076     // source vector and the inserted element, otherwise assume we need
4077     // the original demanded vector elements and the value.
4078     SDValue InVec = Op.getOperand(0);
4079     SDValue InVal = Op.getOperand(1);
4080     SDValue EltNo = Op.getOperand(2);
4081     bool DemandedVal = true;
4082     APInt DemandedVecElts = DemandedElts;
4083     auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
4084     if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
4085       unsigned EltIdx = CEltNo->getZExtValue();
4086       DemandedVal = !!DemandedElts[EltIdx];
4087       DemandedVecElts.clearBit(EltIdx);
4088     }
4089     Tmp = std::numeric_limits<unsigned>::max();
4090     if (DemandedVal) {
4091       // TODO - handle implicit truncation of inserted elements.
4092       if (InVal.getScalarValueSizeInBits() != VTBits)
4093         break;
4094       Tmp2 = ComputeNumSignBits(InVal, Depth + 1);
4095       Tmp = std::min(Tmp, Tmp2);
4096     }
4097     if (!!DemandedVecElts) {
4098       Tmp2 = ComputeNumSignBits(InVec, DemandedVecElts, Depth + 1);
4099       Tmp = std::min(Tmp, Tmp2);
4100     }
4101     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
4102     return Tmp;
4103   }
4104   case ISD::EXTRACT_VECTOR_ELT: {
4105     SDValue InVec = Op.getOperand(0);
4106     SDValue EltNo = Op.getOperand(1);
4107     EVT VecVT = InVec.getValueType();
4108     // ComputeNumSignBits not yet implemented for scalable vectors.
4109     if (VecVT.isScalableVector())
4110       break;
4111     const unsigned BitWidth = Op.getValueSizeInBits();
4112     const unsigned EltBitWidth = Op.getOperand(0).getScalarValueSizeInBits();
4113     const unsigned NumSrcElts = VecVT.getVectorNumElements();
4114 
4115     // If BitWidth > EltBitWidth the value is anyext:ed, and we do not know
4116     // anything about sign bits. But if the sizes match we can derive knowledge
4117     // about sign bits from the vector operand.
4118     if (BitWidth != EltBitWidth)
4119       break;
4120 
4121     // If we know the element index, just demand that vector element, else for
4122     // an unknown element index, ignore DemandedElts and demand them all.
4123     APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
4124     auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
4125     if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
4126       DemandedSrcElts =
4127           APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
4128 
4129     return ComputeNumSignBits(InVec, DemandedSrcElts, Depth + 1);
4130   }
4131   case ISD::EXTRACT_SUBVECTOR: {
4132     // Offset the demanded elts by the subvector index.
4133     SDValue Src = Op.getOperand(0);
4134     // Bail until we can represent demanded elements for scalable vectors.
4135     if (Src.getValueType().isScalableVector())
4136       break;
4137     uint64_t Idx = Op.getConstantOperandVal(1);
4138     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
4139     APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
4140     return ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
4141   }
4142   case ISD::CONCAT_VECTORS: {
4143     // Determine the minimum number of sign bits across all demanded
4144     // elts of the input vectors. Early out if the result is already 1.
4145     Tmp = std::numeric_limits<unsigned>::max();
4146     EVT SubVectorVT = Op.getOperand(0).getValueType();
4147     unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
4148     unsigned NumSubVectors = Op.getNumOperands();
4149     for (unsigned i = 0; (i < NumSubVectors) && (Tmp > 1); ++i) {
4150       APInt DemandedSub =
4151           DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts);
4152       if (!DemandedSub)
4153         continue;
4154       Tmp2 = ComputeNumSignBits(Op.getOperand(i), DemandedSub, Depth + 1);
4155       Tmp = std::min(Tmp, Tmp2);
4156     }
4157     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
4158     return Tmp;
4159   }
4160   case ISD::INSERT_SUBVECTOR: {
4161     // Demand any elements from the subvector and the remainder from the src its
4162     // inserted into.
4163     SDValue Src = Op.getOperand(0);
4164     SDValue Sub = Op.getOperand(1);
4165     uint64_t Idx = Op.getConstantOperandVal(2);
4166     unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
4167     APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
4168     APInt DemandedSrcElts = DemandedElts;
4169     DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx);
4170 
4171     Tmp = std::numeric_limits<unsigned>::max();
4172     if (!!DemandedSubElts) {
4173       Tmp = ComputeNumSignBits(Sub, DemandedSubElts, Depth + 1);
4174       if (Tmp == 1)
4175         return 1; // early-out
4176     }
4177     if (!!DemandedSrcElts) {
4178       Tmp2 = ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
4179       Tmp = std::min(Tmp, Tmp2);
4180     }
4181     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
4182     return Tmp;
4183   }
4184   case ISD::ATOMIC_CMP_SWAP:
4185   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
4186   case ISD::ATOMIC_SWAP:
4187   case ISD::ATOMIC_LOAD_ADD:
4188   case ISD::ATOMIC_LOAD_SUB:
4189   case ISD::ATOMIC_LOAD_AND:
4190   case ISD::ATOMIC_LOAD_CLR:
4191   case ISD::ATOMIC_LOAD_OR:
4192   case ISD::ATOMIC_LOAD_XOR:
4193   case ISD::ATOMIC_LOAD_NAND:
4194   case ISD::ATOMIC_LOAD_MIN:
4195   case ISD::ATOMIC_LOAD_MAX:
4196   case ISD::ATOMIC_LOAD_UMIN:
4197   case ISD::ATOMIC_LOAD_UMAX:
4198   case ISD::ATOMIC_LOAD: {
4199     Tmp = cast<AtomicSDNode>(Op)->getMemoryVT().getScalarSizeInBits();
4200     // If we are looking at the loaded value.
4201     if (Op.getResNo() == 0) {
4202       if (Tmp == VTBits)
4203         return 1; // early-out
4204       if (TLI->getExtendForAtomicOps() == ISD::SIGN_EXTEND)
4205         return VTBits - Tmp + 1;
4206       if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND)
4207         return VTBits - Tmp;
4208     }
4209     break;
4210   }
4211   }
4212 
4213   // If we are looking at the loaded value of the SDNode.
4214   if (Op.getResNo() == 0) {
4215     // Handle LOADX separately here. EXTLOAD case will fallthrough.
4216     if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
4217       unsigned ExtType = LD->getExtensionType();
4218       switch (ExtType) {
4219       default: break;
4220       case ISD::SEXTLOAD: // e.g. i16->i32 = '17' bits known.
4221         Tmp = LD->getMemoryVT().getScalarSizeInBits();
4222         return VTBits - Tmp + 1;
4223       case ISD::ZEXTLOAD: // e.g. i16->i32 = '16' bits known.
4224         Tmp = LD->getMemoryVT().getScalarSizeInBits();
4225         return VTBits - Tmp;
4226       case ISD::NON_EXTLOAD:
4227         if (const Constant *Cst = TLI->getTargetConstantFromLoad(LD)) {
4228           // We only need to handle vectors - computeKnownBits should handle
4229           // scalar cases.
4230           Type *CstTy = Cst->getType();
4231           if (CstTy->isVectorTy() &&
4232               (NumElts * VTBits) == CstTy->getPrimitiveSizeInBits()) {
4233             Tmp = VTBits;
4234             for (unsigned i = 0; i != NumElts; ++i) {
4235               if (!DemandedElts[i])
4236                 continue;
4237               if (Constant *Elt = Cst->getAggregateElement(i)) {
4238                 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
4239                   const APInt &Value = CInt->getValue();
4240                   Tmp = std::min(Tmp, Value.getNumSignBits());
4241                   continue;
4242                 }
4243                 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
4244                   APInt Value = CFP->getValueAPF().bitcastToAPInt();
4245                   Tmp = std::min(Tmp, Value.getNumSignBits());
4246                   continue;
4247                 }
4248               }
4249               // Unknown type. Conservatively assume no bits match sign bit.
4250               return 1;
4251             }
4252             return Tmp;
4253           }
4254         }
4255         break;
4256       }
4257     }
4258   }
4259 
4260   // Allow the target to implement this method for its nodes.
4261   if (Opcode >= ISD::BUILTIN_OP_END ||
4262       Opcode == ISD::INTRINSIC_WO_CHAIN ||
4263       Opcode == ISD::INTRINSIC_W_CHAIN ||
4264       Opcode == ISD::INTRINSIC_VOID) {
4265     unsigned NumBits =
4266         TLI->ComputeNumSignBitsForTargetNode(Op, DemandedElts, *this, Depth);
4267     if (NumBits > 1)
4268       FirstAnswer = std::max(FirstAnswer, NumBits);
4269   }
4270 
4271   // Finally, if we can prove that the top bits of the result are 0's or 1's,
4272   // use this information.
4273   KnownBits Known = computeKnownBits(Op, DemandedElts, Depth);
4274 
4275   APInt Mask;
4276   if (Known.isNonNegative()) {        // sign bit is 0
4277     Mask = Known.Zero;
4278   } else if (Known.isNegative()) {  // sign bit is 1;
4279     Mask = Known.One;
4280   } else {
4281     // Nothing known.
4282     return FirstAnswer;
4283   }
4284 
4285   // Okay, we know that the sign bit in Mask is set.  Use CLO to determine
4286   // the number of identical bits in the top of the input value.
4287   Mask <<= Mask.getBitWidth()-VTBits;
4288   return std::max(FirstAnswer, Mask.countLeadingOnes());
4289 }
4290 
4291 unsigned SelectionDAG::ComputeMinSignedBits(SDValue Op, unsigned Depth) const {
4292   unsigned SignBits = ComputeNumSignBits(Op, Depth);
4293   return Op.getScalarValueSizeInBits() - SignBits + 1;
4294 }
4295 
4296 unsigned SelectionDAG::ComputeMinSignedBits(SDValue Op,
4297                                             const APInt &DemandedElts,
4298                                             unsigned Depth) const {
4299   unsigned SignBits = ComputeNumSignBits(Op, DemandedElts, Depth);
4300   return Op.getScalarValueSizeInBits() - SignBits + 1;
4301 }
4302 
4303 bool SelectionDAG::isGuaranteedNotToBeUndefOrPoison(SDValue Op, bool PoisonOnly,
4304                                                     unsigned Depth) const {
4305   // Early out for FREEZE.
4306   if (Op.getOpcode() == ISD::FREEZE)
4307     return true;
4308 
4309   // TODO: Assume we don't know anything for now.
4310   EVT VT = Op.getValueType();
4311   if (VT.isScalableVector())
4312     return false;
4313 
4314   APInt DemandedElts = VT.isVector()
4315                            ? APInt::getAllOnes(VT.getVectorNumElements())
4316                            : APInt(1, 1);
4317   return isGuaranteedNotToBeUndefOrPoison(Op, DemandedElts, PoisonOnly, Depth);
4318 }
4319 
4320 bool SelectionDAG::isGuaranteedNotToBeUndefOrPoison(SDValue Op,
4321                                                     const APInt &DemandedElts,
4322                                                     bool PoisonOnly,
4323                                                     unsigned Depth) const {
4324   unsigned Opcode = Op.getOpcode();
4325 
4326   // Early out for FREEZE.
4327   if (Opcode == ISD::FREEZE)
4328     return true;
4329 
4330   if (Depth >= MaxRecursionDepth)
4331     return false; // Limit search depth.
4332 
4333   if (isIntOrFPConstant(Op))
4334     return true;
4335 
4336   switch (Opcode) {
4337   case ISD::UNDEF:
4338     return PoisonOnly;
4339 
4340   case ISD::BUILD_VECTOR:
4341     // NOTE: BUILD_VECTOR has implicit truncation of wider scalar elements -
4342     // this shouldn't affect the result.
4343     for (unsigned i = 0, e = Op.getNumOperands(); i < e; ++i) {
4344       if (!DemandedElts[i])
4345         continue;
4346       if (!isGuaranteedNotToBeUndefOrPoison(Op.getOperand(i), PoisonOnly,
4347                                             Depth + 1))
4348         return false;
4349     }
4350     return true;
4351 
4352   // TODO: Search for noundef attributes from library functions.
4353 
4354   // TODO: Pointers dereferenced by ISD::LOAD/STORE ops are noundef.
4355 
4356   default:
4357     // Allow the target to implement this method for its nodes.
4358     if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
4359         Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID)
4360       return TLI->isGuaranteedNotToBeUndefOrPoisonForTargetNode(
4361           Op, DemandedElts, *this, PoisonOnly, Depth);
4362     break;
4363   }
4364 
4365   return false;
4366 }
4367 
4368 bool SelectionDAG::isBaseWithConstantOffset(SDValue Op) const {
4369   if ((Op.getOpcode() != ISD::ADD && Op.getOpcode() != ISD::OR) ||
4370       !isa<ConstantSDNode>(Op.getOperand(1)))
4371     return false;
4372 
4373   if (Op.getOpcode() == ISD::OR &&
4374       !MaskedValueIsZero(Op.getOperand(0), Op.getConstantOperandAPInt(1)))
4375     return false;
4376 
4377   return true;
4378 }
4379 
4380 bool SelectionDAG::isKnownNeverNaN(SDValue Op, bool SNaN, unsigned Depth) const {
4381   // If we're told that NaNs won't happen, assume they won't.
4382   if (getTarget().Options.NoNaNsFPMath || Op->getFlags().hasNoNaNs())
4383     return true;
4384 
4385   if (Depth >= MaxRecursionDepth)
4386     return false; // Limit search depth.
4387 
4388   // TODO: Handle vectors.
4389   // If the value is a constant, we can obviously see if it is a NaN or not.
4390   if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) {
4391     return !C->getValueAPF().isNaN() ||
4392            (SNaN && !C->getValueAPF().isSignaling());
4393   }
4394 
4395   unsigned Opcode = Op.getOpcode();
4396   switch (Opcode) {
4397   case ISD::FADD:
4398   case ISD::FSUB:
4399   case ISD::FMUL:
4400   case ISD::FDIV:
4401   case ISD::FREM:
4402   case ISD::FSIN:
4403   case ISD::FCOS: {
4404     if (SNaN)
4405       return true;
4406     // TODO: Need isKnownNeverInfinity
4407     return false;
4408   }
4409   case ISD::FCANONICALIZE:
4410   case ISD::FEXP:
4411   case ISD::FEXP2:
4412   case ISD::FTRUNC:
4413   case ISD::FFLOOR:
4414   case ISD::FCEIL:
4415   case ISD::FROUND:
4416   case ISD::FROUNDEVEN:
4417   case ISD::FRINT:
4418   case ISD::FNEARBYINT: {
4419     if (SNaN)
4420       return true;
4421     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4422   }
4423   case ISD::FABS:
4424   case ISD::FNEG:
4425   case ISD::FCOPYSIGN: {
4426     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4427   }
4428   case ISD::SELECT:
4429     return isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) &&
4430            isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1);
4431   case ISD::FP_EXTEND:
4432   case ISD::FP_ROUND: {
4433     if (SNaN)
4434       return true;
4435     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4436   }
4437   case ISD::SINT_TO_FP:
4438   case ISD::UINT_TO_FP:
4439     return true;
4440   case ISD::FMA:
4441   case ISD::FMAD: {
4442     if (SNaN)
4443       return true;
4444     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) &&
4445            isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) &&
4446            isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1);
4447   }
4448   case ISD::FSQRT: // Need is known positive
4449   case ISD::FLOG:
4450   case ISD::FLOG2:
4451   case ISD::FLOG10:
4452   case ISD::FPOWI:
4453   case ISD::FPOW: {
4454     if (SNaN)
4455       return true;
4456     // TODO: Refine on operand
4457     return false;
4458   }
4459   case ISD::FMINNUM:
4460   case ISD::FMAXNUM: {
4461     // Only one needs to be known not-nan, since it will be returned if the
4462     // other ends up being one.
4463     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) ||
4464            isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1);
4465   }
4466   case ISD::FMINNUM_IEEE:
4467   case ISD::FMAXNUM_IEEE: {
4468     if (SNaN)
4469       return true;
4470     // This can return a NaN if either operand is an sNaN, or if both operands
4471     // are NaN.
4472     return (isKnownNeverNaN(Op.getOperand(0), false, Depth + 1) &&
4473             isKnownNeverSNaN(Op.getOperand(1), Depth + 1)) ||
4474            (isKnownNeverNaN(Op.getOperand(1), false, Depth + 1) &&
4475             isKnownNeverSNaN(Op.getOperand(0), Depth + 1));
4476   }
4477   case ISD::FMINIMUM:
4478   case ISD::FMAXIMUM: {
4479     // TODO: Does this quiet or return the origina NaN as-is?
4480     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) &&
4481            isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1);
4482   }
4483   case ISD::EXTRACT_VECTOR_ELT: {
4484     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4485   }
4486   default:
4487     if (Opcode >= ISD::BUILTIN_OP_END ||
4488         Opcode == ISD::INTRINSIC_WO_CHAIN ||
4489         Opcode == ISD::INTRINSIC_W_CHAIN ||
4490         Opcode == ISD::INTRINSIC_VOID) {
4491       return TLI->isKnownNeverNaNForTargetNode(Op, *this, SNaN, Depth);
4492     }
4493 
4494     return false;
4495   }
4496 }
4497 
4498 bool SelectionDAG::isKnownNeverZeroFloat(SDValue Op) const {
4499   assert(Op.getValueType().isFloatingPoint() &&
4500          "Floating point type expected");
4501 
4502   // If the value is a constant, we can obviously see if it is a zero or not.
4503   // TODO: Add BuildVector support.
4504   if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
4505     return !C->isZero();
4506   return false;
4507 }
4508 
4509 bool SelectionDAG::isKnownNeverZero(SDValue Op) const {
4510   assert(!Op.getValueType().isFloatingPoint() &&
4511          "Floating point types unsupported - use isKnownNeverZeroFloat");
4512 
4513   // If the value is a constant, we can obviously see if it is a zero or not.
4514   if (ISD::matchUnaryPredicate(Op,
4515                                [](ConstantSDNode *C) { return !C->isZero(); }))
4516     return true;
4517 
4518   // TODO: Recognize more cases here.
4519   switch (Op.getOpcode()) {
4520   default: break;
4521   case ISD::OR:
4522     if (isKnownNeverZero(Op.getOperand(1)) ||
4523         isKnownNeverZero(Op.getOperand(0)))
4524       return true;
4525     break;
4526   }
4527 
4528   return false;
4529 }
4530 
4531 bool SelectionDAG::isEqualTo(SDValue A, SDValue B) const {
4532   // Check the obvious case.
4533   if (A == B) return true;
4534 
4535   // For for negative and positive zero.
4536   if (const ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A))
4537     if (const ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B))
4538       if (CA->isZero() && CB->isZero()) return true;
4539 
4540   // Otherwise they may not be equal.
4541   return false;
4542 }
4543 
4544 // FIXME: unify with llvm::haveNoCommonBitsSet.
4545 // FIXME: could also handle masked merge pattern (X & ~M) op (Y & M)
4546 bool SelectionDAG::haveNoCommonBitsSet(SDValue A, SDValue B) const {
4547   assert(A.getValueType() == B.getValueType() &&
4548          "Values must have the same type");
4549   return KnownBits::haveNoCommonBitsSet(computeKnownBits(A),
4550                                         computeKnownBits(B));
4551 }
4552 
4553 static SDValue FoldSTEP_VECTOR(const SDLoc &DL, EVT VT, SDValue Step,
4554                                SelectionDAG &DAG) {
4555   if (cast<ConstantSDNode>(Step)->isZero())
4556     return DAG.getConstant(0, DL, VT);
4557 
4558   return SDValue();
4559 }
4560 
4561 static SDValue FoldBUILD_VECTOR(const SDLoc &DL, EVT VT,
4562                                 ArrayRef<SDValue> Ops,
4563                                 SelectionDAG &DAG) {
4564   int NumOps = Ops.size();
4565   assert(NumOps != 0 && "Can't build an empty vector!");
4566   assert(!VT.isScalableVector() &&
4567          "BUILD_VECTOR cannot be used with scalable types");
4568   assert(VT.getVectorNumElements() == (unsigned)NumOps &&
4569          "Incorrect element count in BUILD_VECTOR!");
4570 
4571   // BUILD_VECTOR of UNDEFs is UNDEF.
4572   if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
4573     return DAG.getUNDEF(VT);
4574 
4575   // BUILD_VECTOR of seq extract/insert from the same vector + type is Identity.
4576   SDValue IdentitySrc;
4577   bool IsIdentity = true;
4578   for (int i = 0; i != NumOps; ++i) {
4579     if (Ops[i].getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4580         Ops[i].getOperand(0).getValueType() != VT ||
4581         (IdentitySrc && Ops[i].getOperand(0) != IdentitySrc) ||
4582         !isa<ConstantSDNode>(Ops[i].getOperand(1)) ||
4583         cast<ConstantSDNode>(Ops[i].getOperand(1))->getAPIntValue() != i) {
4584       IsIdentity = false;
4585       break;
4586     }
4587     IdentitySrc = Ops[i].getOperand(0);
4588   }
4589   if (IsIdentity)
4590     return IdentitySrc;
4591 
4592   return SDValue();
4593 }
4594 
4595 /// Try to simplify vector concatenation to an input value, undef, or build
4596 /// vector.
4597 static SDValue foldCONCAT_VECTORS(const SDLoc &DL, EVT VT,
4598                                   ArrayRef<SDValue> Ops,
4599                                   SelectionDAG &DAG) {
4600   assert(!Ops.empty() && "Can't concatenate an empty list of vectors!");
4601   assert(llvm::all_of(Ops,
4602                       [Ops](SDValue Op) {
4603                         return Ops[0].getValueType() == Op.getValueType();
4604                       }) &&
4605          "Concatenation of vectors with inconsistent value types!");
4606   assert((Ops[0].getValueType().getVectorElementCount() * Ops.size()) ==
4607              VT.getVectorElementCount() &&
4608          "Incorrect element count in vector concatenation!");
4609 
4610   if (Ops.size() == 1)
4611     return Ops[0];
4612 
4613   // Concat of UNDEFs is UNDEF.
4614   if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
4615     return DAG.getUNDEF(VT);
4616 
4617   // Scan the operands and look for extract operations from a single source
4618   // that correspond to insertion at the same location via this concatenation:
4619   // concat (extract X, 0*subvec_elts), (extract X, 1*subvec_elts), ...
4620   SDValue IdentitySrc;
4621   bool IsIdentity = true;
4622   for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
4623     SDValue Op = Ops[i];
4624     unsigned IdentityIndex = i * Op.getValueType().getVectorMinNumElements();
4625     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
4626         Op.getOperand(0).getValueType() != VT ||
4627         (IdentitySrc && Op.getOperand(0) != IdentitySrc) ||
4628         Op.getConstantOperandVal(1) != IdentityIndex) {
4629       IsIdentity = false;
4630       break;
4631     }
4632     assert((!IdentitySrc || IdentitySrc == Op.getOperand(0)) &&
4633            "Unexpected identity source vector for concat of extracts");
4634     IdentitySrc = Op.getOperand(0);
4635   }
4636   if (IsIdentity) {
4637     assert(IdentitySrc && "Failed to set source vector of extracts");
4638     return IdentitySrc;
4639   }
4640 
4641   // The code below this point is only designed to work for fixed width
4642   // vectors, so we bail out for now.
4643   if (VT.isScalableVector())
4644     return SDValue();
4645 
4646   // A CONCAT_VECTOR with all UNDEF/BUILD_VECTOR operands can be
4647   // simplified to one big BUILD_VECTOR.
4648   // FIXME: Add support for SCALAR_TO_VECTOR as well.
4649   EVT SVT = VT.getScalarType();
4650   SmallVector<SDValue, 16> Elts;
4651   for (SDValue Op : Ops) {
4652     EVT OpVT = Op.getValueType();
4653     if (Op.isUndef())
4654       Elts.append(OpVT.getVectorNumElements(), DAG.getUNDEF(SVT));
4655     else if (Op.getOpcode() == ISD::BUILD_VECTOR)
4656       Elts.append(Op->op_begin(), Op->op_end());
4657     else
4658       return SDValue();
4659   }
4660 
4661   // BUILD_VECTOR requires all inputs to be of the same type, find the
4662   // maximum type and extend them all.
4663   for (SDValue Op : Elts)
4664     SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
4665 
4666   if (SVT.bitsGT(VT.getScalarType())) {
4667     for (SDValue &Op : Elts) {
4668       if (Op.isUndef())
4669         Op = DAG.getUNDEF(SVT);
4670       else
4671         Op = DAG.getTargetLoweringInfo().isZExtFree(Op.getValueType(), SVT)
4672                  ? DAG.getZExtOrTrunc(Op, DL, SVT)
4673                  : DAG.getSExtOrTrunc(Op, DL, SVT);
4674     }
4675   }
4676 
4677   SDValue V = DAG.getBuildVector(VT, DL, Elts);
4678   NewSDValueDbgMsg(V, "New node fold concat vectors: ", &DAG);
4679   return V;
4680 }
4681 
4682 /// Gets or creates the specified node.
4683 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT) {
4684   FoldingSetNodeID ID;
4685   AddNodeIDNode(ID, Opcode, getVTList(VT), None);
4686   void *IP = nullptr;
4687   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
4688     return SDValue(E, 0);
4689 
4690   auto *N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(),
4691                               getVTList(VT));
4692   CSEMap.InsertNode(N, IP);
4693 
4694   InsertNode(N);
4695   SDValue V = SDValue(N, 0);
4696   NewSDValueDbgMsg(V, "Creating new node: ", this);
4697   return V;
4698 }
4699 
4700 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4701                               SDValue Operand) {
4702   SDNodeFlags Flags;
4703   if (Inserter)
4704     Flags = Inserter->getFlags();
4705   return getNode(Opcode, DL, VT, Operand, Flags);
4706 }
4707 
4708 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4709                               SDValue Operand, const SDNodeFlags Flags) {
4710   assert(Operand.getOpcode() != ISD::DELETED_NODE &&
4711          "Operand is DELETED_NODE!");
4712   // Constant fold unary operations with an integer constant operand. Even
4713   // opaque constant will be folded, because the folding of unary operations
4714   // doesn't create new constants with different values. Nevertheless, the
4715   // opaque flag is preserved during folding to prevent future folding with
4716   // other constants.
4717   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand)) {
4718     const APInt &Val = C->getAPIntValue();
4719     switch (Opcode) {
4720     default: break;
4721     case ISD::SIGN_EXTEND:
4722       return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
4723                          C->isTargetOpcode(), C->isOpaque());
4724     case ISD::TRUNCATE:
4725       if (C->isOpaque())
4726         break;
4727       LLVM_FALLTHROUGH;
4728     case ISD::ZERO_EXTEND:
4729       return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
4730                          C->isTargetOpcode(), C->isOpaque());
4731     case ISD::ANY_EXTEND:
4732       // Some targets like RISCV prefer to sign extend some types.
4733       if (TLI->isSExtCheaperThanZExt(Operand.getValueType(), VT))
4734         return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
4735                            C->isTargetOpcode(), C->isOpaque());
4736       return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
4737                          C->isTargetOpcode(), C->isOpaque());
4738     case ISD::UINT_TO_FP:
4739     case ISD::SINT_TO_FP: {
4740       APFloat apf(EVTToAPFloatSemantics(VT),
4741                   APInt::getZero(VT.getSizeInBits()));
4742       (void)apf.convertFromAPInt(Val,
4743                                  Opcode==ISD::SINT_TO_FP,
4744                                  APFloat::rmNearestTiesToEven);
4745       return getConstantFP(apf, DL, VT);
4746     }
4747     case ISD::BITCAST:
4748       if (VT == MVT::f16 && C->getValueType(0) == MVT::i16)
4749         return getConstantFP(APFloat(APFloat::IEEEhalf(), Val), DL, VT);
4750       if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
4751         return getConstantFP(APFloat(APFloat::IEEEsingle(), Val), DL, VT);
4752       if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
4753         return getConstantFP(APFloat(APFloat::IEEEdouble(), Val), DL, VT);
4754       if (VT == MVT::f128 && C->getValueType(0) == MVT::i128)
4755         return getConstantFP(APFloat(APFloat::IEEEquad(), Val), DL, VT);
4756       break;
4757     case ISD::ABS:
4758       return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(),
4759                          C->isOpaque());
4760     case ISD::BITREVERSE:
4761       return getConstant(Val.reverseBits(), DL, VT, C->isTargetOpcode(),
4762                          C->isOpaque());
4763     case ISD::BSWAP:
4764       return getConstant(Val.byteSwap(), DL, VT, C->isTargetOpcode(),
4765                          C->isOpaque());
4766     case ISD::CTPOP:
4767       return getConstant(Val.countPopulation(), DL, VT, C->isTargetOpcode(),
4768                          C->isOpaque());
4769     case ISD::CTLZ:
4770     case ISD::CTLZ_ZERO_UNDEF:
4771       return getConstant(Val.countLeadingZeros(), DL, VT, C->isTargetOpcode(),
4772                          C->isOpaque());
4773     case ISD::CTTZ:
4774     case ISD::CTTZ_ZERO_UNDEF:
4775       return getConstant(Val.countTrailingZeros(), DL, VT, C->isTargetOpcode(),
4776                          C->isOpaque());
4777     case ISD::FP16_TO_FP: {
4778       bool Ignored;
4779       APFloat FPV(APFloat::IEEEhalf(),
4780                   (Val.getBitWidth() == 16) ? Val : Val.trunc(16));
4781 
4782       // This can return overflow, underflow, or inexact; we don't care.
4783       // FIXME need to be more flexible about rounding mode.
4784       (void)FPV.convert(EVTToAPFloatSemantics(VT),
4785                         APFloat::rmNearestTiesToEven, &Ignored);
4786       return getConstantFP(FPV, DL, VT);
4787     }
4788     case ISD::STEP_VECTOR: {
4789       if (SDValue V = FoldSTEP_VECTOR(DL, VT, Operand, *this))
4790         return V;
4791       break;
4792     }
4793     }
4794   }
4795 
4796   // Constant fold unary operations with a floating point constant operand.
4797   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand)) {
4798     APFloat V = C->getValueAPF();    // make copy
4799     switch (Opcode) {
4800     case ISD::FNEG:
4801       V.changeSign();
4802       return getConstantFP(V, DL, VT);
4803     case ISD::FABS:
4804       V.clearSign();
4805       return getConstantFP(V, DL, VT);
4806     case ISD::FCEIL: {
4807       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardPositive);
4808       if (fs == APFloat::opOK || fs == APFloat::opInexact)
4809         return getConstantFP(V, DL, VT);
4810       break;
4811     }
4812     case ISD::FTRUNC: {
4813       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardZero);
4814       if (fs == APFloat::opOK || fs == APFloat::opInexact)
4815         return getConstantFP(V, DL, VT);
4816       break;
4817     }
4818     case ISD::FFLOOR: {
4819       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardNegative);
4820       if (fs == APFloat::opOK || fs == APFloat::opInexact)
4821         return getConstantFP(V, DL, VT);
4822       break;
4823     }
4824     case ISD::FP_EXTEND: {
4825       bool ignored;
4826       // This can return overflow, underflow, or inexact; we don't care.
4827       // FIXME need to be more flexible about rounding mode.
4828       (void)V.convert(EVTToAPFloatSemantics(VT),
4829                       APFloat::rmNearestTiesToEven, &ignored);
4830       return getConstantFP(V, DL, VT);
4831     }
4832     case ISD::FP_TO_SINT:
4833     case ISD::FP_TO_UINT: {
4834       bool ignored;
4835       APSInt IntVal(VT.getSizeInBits(), Opcode == ISD::FP_TO_UINT);
4836       // FIXME need to be more flexible about rounding mode.
4837       APFloat::opStatus s =
4838           V.convertToInteger(IntVal, APFloat::rmTowardZero, &ignored);
4839       if (s == APFloat::opInvalidOp) // inexact is OK, in fact usual
4840         break;
4841       return getConstant(IntVal, DL, VT);
4842     }
4843     case ISD::BITCAST:
4844       if (VT == MVT::i16 && C->getValueType(0) == MVT::f16)
4845         return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
4846       if (VT == MVT::i16 && C->getValueType(0) == MVT::bf16)
4847         return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
4848       if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
4849         return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
4850       if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
4851         return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
4852       break;
4853     case ISD::FP_TO_FP16: {
4854       bool Ignored;
4855       // This can return overflow, underflow, or inexact; we don't care.
4856       // FIXME need to be more flexible about rounding mode.
4857       (void)V.convert(APFloat::IEEEhalf(),
4858                       APFloat::rmNearestTiesToEven, &Ignored);
4859       return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
4860     }
4861     }
4862   }
4863 
4864   // Constant fold unary operations with a vector integer or float operand.
4865   switch (Opcode) {
4866   default:
4867     // FIXME: Entirely reasonable to perform folding of other unary
4868     // operations here as the need arises.
4869     break;
4870   case ISD::FNEG:
4871   case ISD::FABS:
4872   case ISD::FCEIL:
4873   case ISD::FTRUNC:
4874   case ISD::FFLOOR:
4875   case ISD::FP_EXTEND:
4876   case ISD::FP_TO_SINT:
4877   case ISD::FP_TO_UINT:
4878   case ISD::TRUNCATE:
4879   case ISD::ANY_EXTEND:
4880   case ISD::ZERO_EXTEND:
4881   case ISD::SIGN_EXTEND:
4882   case ISD::UINT_TO_FP:
4883   case ISD::SINT_TO_FP:
4884   case ISD::ABS:
4885   case ISD::BITREVERSE:
4886   case ISD::BSWAP:
4887   case ISD::CTLZ:
4888   case ISD::CTLZ_ZERO_UNDEF:
4889   case ISD::CTTZ:
4890   case ISD::CTTZ_ZERO_UNDEF:
4891   case ISD::CTPOP: {
4892     SDValue Ops = {Operand};
4893     if (SDValue Fold = FoldConstantArithmetic(Opcode, DL, VT, Ops))
4894       return Fold;
4895   }
4896   }
4897 
4898   unsigned OpOpcode = Operand.getNode()->getOpcode();
4899   switch (Opcode) {
4900   case ISD::STEP_VECTOR:
4901     assert(VT.isScalableVector() &&
4902            "STEP_VECTOR can only be used with scalable types");
4903     assert(OpOpcode == ISD::TargetConstant &&
4904            VT.getVectorElementType() == Operand.getValueType() &&
4905            "Unexpected step operand");
4906     break;
4907   case ISD::FREEZE:
4908     assert(VT == Operand.getValueType() && "Unexpected VT!");
4909     break;
4910   case ISD::TokenFactor:
4911   case ISD::MERGE_VALUES:
4912   case ISD::CONCAT_VECTORS:
4913     return Operand;         // Factor, merge or concat of one node?  No need.
4914   case ISD::BUILD_VECTOR: {
4915     // Attempt to simplify BUILD_VECTOR.
4916     SDValue Ops[] = {Operand};
4917     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
4918       return V;
4919     break;
4920   }
4921   case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node");
4922   case ISD::FP_EXTEND:
4923     assert(VT.isFloatingPoint() &&
4924            Operand.getValueType().isFloatingPoint() && "Invalid FP cast!");
4925     if (Operand.getValueType() == VT) return Operand;  // noop conversion.
4926     assert((!VT.isVector() ||
4927             VT.getVectorElementCount() ==
4928             Operand.getValueType().getVectorElementCount()) &&
4929            "Vector element count mismatch!");
4930     assert(Operand.getValueType().bitsLT(VT) &&
4931            "Invalid fpext node, dst < src!");
4932     if (Operand.isUndef())
4933       return getUNDEF(VT);
4934     break;
4935   case ISD::FP_TO_SINT:
4936   case ISD::FP_TO_UINT:
4937     if (Operand.isUndef())
4938       return getUNDEF(VT);
4939     break;
4940   case ISD::SINT_TO_FP:
4941   case ISD::UINT_TO_FP:
4942     // [us]itofp(undef) = 0, because the result value is bounded.
4943     if (Operand.isUndef())
4944       return getConstantFP(0.0, DL, VT);
4945     break;
4946   case ISD::SIGN_EXTEND:
4947     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
4948            "Invalid SIGN_EXTEND!");
4949     assert(VT.isVector() == Operand.getValueType().isVector() &&
4950            "SIGN_EXTEND result type type should be vector iff the operand "
4951            "type is vector!");
4952     if (Operand.getValueType() == VT) return Operand;   // noop extension
4953     assert((!VT.isVector() ||
4954             VT.getVectorElementCount() ==
4955                 Operand.getValueType().getVectorElementCount()) &&
4956            "Vector element count mismatch!");
4957     assert(Operand.getValueType().bitsLT(VT) &&
4958            "Invalid sext node, dst < src!");
4959     if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
4960       return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
4961     if (OpOpcode == ISD::UNDEF)
4962       // sext(undef) = 0, because the top bits will all be the same.
4963       return getConstant(0, DL, VT);
4964     break;
4965   case ISD::ZERO_EXTEND:
4966     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
4967            "Invalid ZERO_EXTEND!");
4968     assert(VT.isVector() == Operand.getValueType().isVector() &&
4969            "ZERO_EXTEND result type type should be vector iff the operand "
4970            "type is vector!");
4971     if (Operand.getValueType() == VT) return Operand;   // noop extension
4972     assert((!VT.isVector() ||
4973             VT.getVectorElementCount() ==
4974                 Operand.getValueType().getVectorElementCount()) &&
4975            "Vector element count mismatch!");
4976     assert(Operand.getValueType().bitsLT(VT) &&
4977            "Invalid zext node, dst < src!");
4978     if (OpOpcode == ISD::ZERO_EXTEND)   // (zext (zext x)) -> (zext x)
4979       return getNode(ISD::ZERO_EXTEND, DL, VT, Operand.getOperand(0));
4980     if (OpOpcode == ISD::UNDEF)
4981       // zext(undef) = 0, because the top bits will be zero.
4982       return getConstant(0, DL, VT);
4983     break;
4984   case ISD::ANY_EXTEND:
4985     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
4986            "Invalid ANY_EXTEND!");
4987     assert(VT.isVector() == Operand.getValueType().isVector() &&
4988            "ANY_EXTEND result type type should be vector iff the operand "
4989            "type is vector!");
4990     if (Operand.getValueType() == VT) return Operand;   // noop extension
4991     assert((!VT.isVector() ||
4992             VT.getVectorElementCount() ==
4993                 Operand.getValueType().getVectorElementCount()) &&
4994            "Vector element count mismatch!");
4995     assert(Operand.getValueType().bitsLT(VT) &&
4996            "Invalid anyext node, dst < src!");
4997 
4998     if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
4999         OpOpcode == ISD::ANY_EXTEND)
5000       // (ext (zext x)) -> (zext x)  and  (ext (sext x)) -> (sext x)
5001       return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
5002     if (OpOpcode == ISD::UNDEF)
5003       return getUNDEF(VT);
5004 
5005     // (ext (trunc x)) -> x
5006     if (OpOpcode == ISD::TRUNCATE) {
5007       SDValue OpOp = Operand.getOperand(0);
5008       if (OpOp.getValueType() == VT) {
5009         transferDbgValues(Operand, OpOp);
5010         return OpOp;
5011       }
5012     }
5013     break;
5014   case ISD::TRUNCATE:
5015     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
5016            "Invalid TRUNCATE!");
5017     assert(VT.isVector() == Operand.getValueType().isVector() &&
5018            "TRUNCATE result type type should be vector iff the operand "
5019            "type is vector!");
5020     if (Operand.getValueType() == VT) return Operand;   // noop truncate
5021     assert((!VT.isVector() ||
5022             VT.getVectorElementCount() ==
5023                 Operand.getValueType().getVectorElementCount()) &&
5024            "Vector element count mismatch!");
5025     assert(Operand.getValueType().bitsGT(VT) &&
5026            "Invalid truncate node, src < dst!");
5027     if (OpOpcode == ISD::TRUNCATE)
5028       return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0));
5029     if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
5030         OpOpcode == ISD::ANY_EXTEND) {
5031       // If the source is smaller than the dest, we still need an extend.
5032       if (Operand.getOperand(0).getValueType().getScalarType()
5033             .bitsLT(VT.getScalarType()))
5034         return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
5035       if (Operand.getOperand(0).getValueType().bitsGT(VT))
5036         return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0));
5037       return Operand.getOperand(0);
5038     }
5039     if (OpOpcode == ISD::UNDEF)
5040       return getUNDEF(VT);
5041     if (OpOpcode == ISD::VSCALE && !NewNodesMustHaveLegalTypes)
5042       return getVScale(DL, VT, Operand.getConstantOperandAPInt(0));
5043     break;
5044   case ISD::ANY_EXTEND_VECTOR_INREG:
5045   case ISD::ZERO_EXTEND_VECTOR_INREG:
5046   case ISD::SIGN_EXTEND_VECTOR_INREG:
5047     assert(VT.isVector() && "This DAG node is restricted to vector types.");
5048     assert(Operand.getValueType().bitsLE(VT) &&
5049            "The input must be the same size or smaller than the result.");
5050     assert(VT.getVectorMinNumElements() <
5051                Operand.getValueType().getVectorMinNumElements() &&
5052            "The destination vector type must have fewer lanes than the input.");
5053     break;
5054   case ISD::ABS:
5055     assert(VT.isInteger() && VT == Operand.getValueType() &&
5056            "Invalid ABS!");
5057     if (OpOpcode == ISD::UNDEF)
5058       return getUNDEF(VT);
5059     break;
5060   case ISD::BSWAP:
5061     assert(VT.isInteger() && VT == Operand.getValueType() &&
5062            "Invalid BSWAP!");
5063     assert((VT.getScalarSizeInBits() % 16 == 0) &&
5064            "BSWAP types must be a multiple of 16 bits!");
5065     if (OpOpcode == ISD::UNDEF)
5066       return getUNDEF(VT);
5067     break;
5068   case ISD::BITREVERSE:
5069     assert(VT.isInteger() && VT == Operand.getValueType() &&
5070            "Invalid BITREVERSE!");
5071     if (OpOpcode == ISD::UNDEF)
5072       return getUNDEF(VT);
5073     break;
5074   case ISD::BITCAST:
5075     // Basic sanity checking.
5076     assert(VT.getSizeInBits() == Operand.getValueSizeInBits() &&
5077            "Cannot BITCAST between types of different sizes!");
5078     if (VT == Operand.getValueType()) return Operand;  // noop conversion.
5079     if (OpOpcode == ISD::BITCAST)  // bitconv(bitconv(x)) -> bitconv(x)
5080       return getNode(ISD::BITCAST, DL, VT, Operand.getOperand(0));
5081     if (OpOpcode == ISD::UNDEF)
5082       return getUNDEF(VT);
5083     break;
5084   case ISD::SCALAR_TO_VECTOR:
5085     assert(VT.isVector() && !Operand.getValueType().isVector() &&
5086            (VT.getVectorElementType() == Operand.getValueType() ||
5087             (VT.getVectorElementType().isInteger() &&
5088              Operand.getValueType().isInteger() &&
5089              VT.getVectorElementType().bitsLE(Operand.getValueType()))) &&
5090            "Illegal SCALAR_TO_VECTOR node!");
5091     if (OpOpcode == ISD::UNDEF)
5092       return getUNDEF(VT);
5093     // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
5094     if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
5095         isa<ConstantSDNode>(Operand.getOperand(1)) &&
5096         Operand.getConstantOperandVal(1) == 0 &&
5097         Operand.getOperand(0).getValueType() == VT)
5098       return Operand.getOperand(0);
5099     break;
5100   case ISD::FNEG:
5101     // Negation of an unknown bag of bits is still completely undefined.
5102     if (OpOpcode == ISD::UNDEF)
5103       return getUNDEF(VT);
5104 
5105     if (OpOpcode == ISD::FNEG)  // --X -> X
5106       return Operand.getOperand(0);
5107     break;
5108   case ISD::FABS:
5109     if (OpOpcode == ISD::FNEG)  // abs(-X) -> abs(X)
5110       return getNode(ISD::FABS, DL, VT, Operand.getOperand(0));
5111     break;
5112   case ISD::VSCALE:
5113     assert(VT == Operand.getValueType() && "Unexpected VT!");
5114     break;
5115   case ISD::CTPOP:
5116     if (Operand.getValueType().getScalarType() == MVT::i1)
5117       return Operand;
5118     break;
5119   case ISD::CTLZ:
5120   case ISD::CTTZ:
5121     if (Operand.getValueType().getScalarType() == MVT::i1)
5122       return getNOT(DL, Operand, Operand.getValueType());
5123     break;
5124   case ISD::VECREDUCE_SMIN:
5125   case ISD::VECREDUCE_UMAX:
5126     if (Operand.getValueType().getScalarType() == MVT::i1)
5127       return getNode(ISD::VECREDUCE_OR, DL, VT, Operand);
5128     break;
5129   case ISD::VECREDUCE_SMAX:
5130   case ISD::VECREDUCE_UMIN:
5131     if (Operand.getValueType().getScalarType() == MVT::i1)
5132       return getNode(ISD::VECREDUCE_AND, DL, VT, Operand);
5133     break;
5134   }
5135 
5136   SDNode *N;
5137   SDVTList VTs = getVTList(VT);
5138   SDValue Ops[] = {Operand};
5139   if (VT != MVT::Glue) { // Don't CSE flag producing nodes
5140     FoldingSetNodeID ID;
5141     AddNodeIDNode(ID, Opcode, VTs, Ops);
5142     void *IP = nullptr;
5143     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
5144       E->intersectFlagsWith(Flags);
5145       return SDValue(E, 0);
5146     }
5147 
5148     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5149     N->setFlags(Flags);
5150     createOperands(N, Ops);
5151     CSEMap.InsertNode(N, IP);
5152   } else {
5153     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5154     createOperands(N, Ops);
5155   }
5156 
5157   InsertNode(N);
5158   SDValue V = SDValue(N, 0);
5159   NewSDValueDbgMsg(V, "Creating new node: ", this);
5160   return V;
5161 }
5162 
5163 static llvm::Optional<APInt> FoldValue(unsigned Opcode, const APInt &C1,
5164                                        const APInt &C2) {
5165   switch (Opcode) {
5166   case ISD::ADD:  return C1 + C2;
5167   case ISD::SUB:  return C1 - C2;
5168   case ISD::MUL:  return C1 * C2;
5169   case ISD::AND:  return C1 & C2;
5170   case ISD::OR:   return C1 | C2;
5171   case ISD::XOR:  return C1 ^ C2;
5172   case ISD::SHL:  return C1 << C2;
5173   case ISD::SRL:  return C1.lshr(C2);
5174   case ISD::SRA:  return C1.ashr(C2);
5175   case ISD::ROTL: return C1.rotl(C2);
5176   case ISD::ROTR: return C1.rotr(C2);
5177   case ISD::SMIN: return C1.sle(C2) ? C1 : C2;
5178   case ISD::SMAX: return C1.sge(C2) ? C1 : C2;
5179   case ISD::UMIN: return C1.ule(C2) ? C1 : C2;
5180   case ISD::UMAX: return C1.uge(C2) ? C1 : C2;
5181   case ISD::SADDSAT: return C1.sadd_sat(C2);
5182   case ISD::UADDSAT: return C1.uadd_sat(C2);
5183   case ISD::SSUBSAT: return C1.ssub_sat(C2);
5184   case ISD::USUBSAT: return C1.usub_sat(C2);
5185   case ISD::UDIV:
5186     if (!C2.getBoolValue())
5187       break;
5188     return C1.udiv(C2);
5189   case ISD::UREM:
5190     if (!C2.getBoolValue())
5191       break;
5192     return C1.urem(C2);
5193   case ISD::SDIV:
5194     if (!C2.getBoolValue())
5195       break;
5196     return C1.sdiv(C2);
5197   case ISD::SREM:
5198     if (!C2.getBoolValue())
5199       break;
5200     return C1.srem(C2);
5201   case ISD::MULHS: {
5202     unsigned FullWidth = C1.getBitWidth() * 2;
5203     APInt C1Ext = C1.sext(FullWidth);
5204     APInt C2Ext = C2.sext(FullWidth);
5205     return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth());
5206   }
5207   case ISD::MULHU: {
5208     unsigned FullWidth = C1.getBitWidth() * 2;
5209     APInt C1Ext = C1.zext(FullWidth);
5210     APInt C2Ext = C2.zext(FullWidth);
5211     return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth());
5212   }
5213   }
5214   return llvm::None;
5215 }
5216 
5217 SDValue SelectionDAG::FoldSymbolOffset(unsigned Opcode, EVT VT,
5218                                        const GlobalAddressSDNode *GA,
5219                                        const SDNode *N2) {
5220   if (GA->getOpcode() != ISD::GlobalAddress)
5221     return SDValue();
5222   if (!TLI->isOffsetFoldingLegal(GA))
5223     return SDValue();
5224   auto *C2 = dyn_cast<ConstantSDNode>(N2);
5225   if (!C2)
5226     return SDValue();
5227   int64_t Offset = C2->getSExtValue();
5228   switch (Opcode) {
5229   case ISD::ADD: break;
5230   case ISD::SUB: Offset = -uint64_t(Offset); break;
5231   default: return SDValue();
5232   }
5233   return getGlobalAddress(GA->getGlobal(), SDLoc(C2), VT,
5234                           GA->getOffset() + uint64_t(Offset));
5235 }
5236 
5237 bool SelectionDAG::isUndef(unsigned Opcode, ArrayRef<SDValue> Ops) {
5238   switch (Opcode) {
5239   case ISD::SDIV:
5240   case ISD::UDIV:
5241   case ISD::SREM:
5242   case ISD::UREM: {
5243     // If a divisor is zero/undef or any element of a divisor vector is
5244     // zero/undef, the whole op is undef.
5245     assert(Ops.size() == 2 && "Div/rem should have 2 operands");
5246     SDValue Divisor = Ops[1];
5247     if (Divisor.isUndef() || isNullConstant(Divisor))
5248       return true;
5249 
5250     return ISD::isBuildVectorOfConstantSDNodes(Divisor.getNode()) &&
5251            llvm::any_of(Divisor->op_values(),
5252                         [](SDValue V) { return V.isUndef() ||
5253                                         isNullConstant(V); });
5254     // TODO: Handle signed overflow.
5255   }
5256   // TODO: Handle oversized shifts.
5257   default:
5258     return false;
5259   }
5260 }
5261 
5262 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL,
5263                                              EVT VT, ArrayRef<SDValue> Ops) {
5264   // If the opcode is a target-specific ISD node, there's nothing we can
5265   // do here and the operand rules may not line up with the below, so
5266   // bail early.
5267   // We can't create a scalar CONCAT_VECTORS so skip it. It will break
5268   // for concats involving SPLAT_VECTOR. Concats of BUILD_VECTORS are handled by
5269   // foldCONCAT_VECTORS in getNode before this is called.
5270   if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::CONCAT_VECTORS)
5271     return SDValue();
5272 
5273   unsigned NumOps = Ops.size();
5274   if (NumOps == 0)
5275     return SDValue();
5276 
5277   if (isUndef(Opcode, Ops))
5278     return getUNDEF(VT);
5279 
5280   // Handle the case of two scalars.
5281   if (NumOps == 2) {
5282     // TODO: Move foldConstantFPMath here?
5283 
5284     if (auto *C1 = dyn_cast<ConstantSDNode>(Ops[0])) {
5285       if (auto *C2 = dyn_cast<ConstantSDNode>(Ops[1])) {
5286         if (C1->isOpaque() || C2->isOpaque())
5287           return SDValue();
5288 
5289         Optional<APInt> FoldAttempt =
5290             FoldValue(Opcode, C1->getAPIntValue(), C2->getAPIntValue());
5291         if (!FoldAttempt)
5292           return SDValue();
5293 
5294         SDValue Folded = getConstant(FoldAttempt.getValue(), DL, VT);
5295         assert((!Folded || !VT.isVector()) &&
5296                "Can't fold vectors ops with scalar operands");
5297         return Folded;
5298       }
5299     }
5300 
5301     // fold (add Sym, c) -> Sym+c
5302     if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ops[0]))
5303       return FoldSymbolOffset(Opcode, VT, GA, Ops[1].getNode());
5304     if (TLI->isCommutativeBinOp(Opcode))
5305       if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ops[1]))
5306         return FoldSymbolOffset(Opcode, VT, GA, Ops[0].getNode());
5307   }
5308 
5309   // This is for vector folding only from here on.
5310   if (!VT.isVector())
5311     return SDValue();
5312 
5313   ElementCount NumElts = VT.getVectorElementCount();
5314 
5315   // See if we can fold through bitcasted integer ops.
5316   // TODO: Can we handle undef elements?
5317   if (NumOps == 2 && VT.isFixedLengthVector() && VT.isInteger() &&
5318       Ops[0].getValueType() == VT && Ops[1].getValueType() == VT &&
5319       Ops[0].getOpcode() == ISD::BITCAST &&
5320       Ops[1].getOpcode() == ISD::BITCAST) {
5321     SDValue N1 = peekThroughBitcasts(Ops[0]);
5322     SDValue N2 = peekThroughBitcasts(Ops[1]);
5323     auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
5324     auto *BV2 = dyn_cast<BuildVectorSDNode>(N2);
5325     EVT BVVT = N1.getValueType();
5326     if (BV1 && BV2 && BVVT.isInteger() && BVVT == N2.getValueType()) {
5327       bool IsLE = getDataLayout().isLittleEndian();
5328       unsigned EltBits = VT.getScalarSizeInBits();
5329       SmallVector<APInt> RawBits1, RawBits2;
5330       BitVector UndefElts1, UndefElts2;
5331       if (BV1->getConstantRawBits(IsLE, EltBits, RawBits1, UndefElts1) &&
5332           BV2->getConstantRawBits(IsLE, EltBits, RawBits2, UndefElts2) &&
5333           UndefElts1.none() && UndefElts2.none()) {
5334         SmallVector<APInt> RawBits;
5335         for (unsigned I = 0, E = NumElts.getFixedValue(); I != E; ++I) {
5336           Optional<APInt> Fold = FoldValue(Opcode, RawBits1[I], RawBits2[I]);
5337           if (!Fold)
5338             break;
5339           RawBits.push_back(Fold.getValue());
5340         }
5341         if (RawBits.size() == NumElts.getFixedValue()) {
5342           // We have constant folded, but we need to cast this again back to
5343           // the original (possibly legalized) type.
5344           SmallVector<APInt> DstBits;
5345           BitVector DstUndefs;
5346           BuildVectorSDNode::recastRawBits(IsLE, BVVT.getScalarSizeInBits(),
5347                                            DstBits, RawBits, DstUndefs,
5348                                            BitVector(RawBits.size(), false));
5349           EVT BVEltVT = BV1->getOperand(0).getValueType();
5350           unsigned BVEltBits = BVEltVT.getSizeInBits();
5351           SmallVector<SDValue> Ops(DstBits.size(), getUNDEF(BVEltVT));
5352           for (unsigned I = 0, E = DstBits.size(); I != E; ++I) {
5353             if (DstUndefs[I])
5354               continue;
5355             Ops[I] = getConstant(DstBits[I].sextOrSelf(BVEltBits), DL, BVEltVT);
5356           }
5357           return getBitcast(VT, getBuildVector(BVVT, DL, Ops));
5358         }
5359       }
5360     }
5361   }
5362 
5363   auto IsScalarOrSameVectorSize = [NumElts](const SDValue &Op) {
5364     return !Op.getValueType().isVector() ||
5365            Op.getValueType().getVectorElementCount() == NumElts;
5366   };
5367 
5368   auto IsBuildVectorSplatVectorOrUndef = [](const SDValue &Op) {
5369     return Op.isUndef() || Op.getOpcode() == ISD::CONDCODE ||
5370            Op.getOpcode() == ISD::BUILD_VECTOR ||
5371            Op.getOpcode() == ISD::SPLAT_VECTOR;
5372   };
5373 
5374   // All operands must be vector types with the same number of elements as
5375   // the result type and must be either UNDEF or a build/splat vector
5376   // or UNDEF scalars.
5377   if (!llvm::all_of(Ops, IsBuildVectorSplatVectorOrUndef) ||
5378       !llvm::all_of(Ops, IsScalarOrSameVectorSize))
5379     return SDValue();
5380 
5381   // If we are comparing vectors, then the result needs to be a i1 boolean
5382   // that is then sign-extended back to the legal result type.
5383   EVT SVT = (Opcode == ISD::SETCC ? MVT::i1 : VT.getScalarType());
5384 
5385   // Find legal integer scalar type for constant promotion and
5386   // ensure that its scalar size is at least as large as source.
5387   EVT LegalSVT = VT.getScalarType();
5388   if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
5389     LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
5390     if (LegalSVT.bitsLT(VT.getScalarType()))
5391       return SDValue();
5392   }
5393 
5394   // For scalable vector types we know we're dealing with SPLAT_VECTORs. We
5395   // only have one operand to check. For fixed-length vector types we may have
5396   // a combination of BUILD_VECTOR and SPLAT_VECTOR.
5397   unsigned NumVectorElts = NumElts.isScalable() ? 1 : NumElts.getFixedValue();
5398 
5399   // Constant fold each scalar lane separately.
5400   SmallVector<SDValue, 4> ScalarResults;
5401   for (unsigned I = 0; I != NumVectorElts; I++) {
5402     SmallVector<SDValue, 4> ScalarOps;
5403     for (SDValue Op : Ops) {
5404       EVT InSVT = Op.getValueType().getScalarType();
5405       if (Op.getOpcode() != ISD::BUILD_VECTOR &&
5406           Op.getOpcode() != ISD::SPLAT_VECTOR) {
5407         if (Op.isUndef())
5408           ScalarOps.push_back(getUNDEF(InSVT));
5409         else
5410           ScalarOps.push_back(Op);
5411         continue;
5412       }
5413 
5414       SDValue ScalarOp =
5415           Op.getOperand(Op.getOpcode() == ISD::SPLAT_VECTOR ? 0 : I);
5416       EVT ScalarVT = ScalarOp.getValueType();
5417 
5418       // Build vector (integer) scalar operands may need implicit
5419       // truncation - do this before constant folding.
5420       if (ScalarVT.isInteger() && ScalarVT.bitsGT(InSVT))
5421         ScalarOp = getNode(ISD::TRUNCATE, DL, InSVT, ScalarOp);
5422 
5423       ScalarOps.push_back(ScalarOp);
5424     }
5425 
5426     // Constant fold the scalar operands.
5427     SDValue ScalarResult = getNode(Opcode, DL, SVT, ScalarOps);
5428 
5429     // Legalize the (integer) scalar constant if necessary.
5430     if (LegalSVT != SVT)
5431       ScalarResult = getNode(ISD::SIGN_EXTEND, DL, LegalSVT, ScalarResult);
5432 
5433     // Scalar folding only succeeded if the result is a constant or UNDEF.
5434     if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant &&
5435         ScalarResult.getOpcode() != ISD::ConstantFP)
5436       return SDValue();
5437     ScalarResults.push_back(ScalarResult);
5438   }
5439 
5440   SDValue V = NumElts.isScalable() ? getSplatVector(VT, DL, ScalarResults[0])
5441                                    : getBuildVector(VT, DL, ScalarResults);
5442   NewSDValueDbgMsg(V, "New node fold constant vector: ", this);
5443   return V;
5444 }
5445 
5446 SDValue SelectionDAG::foldConstantFPMath(unsigned Opcode, const SDLoc &DL,
5447                                          EVT VT, SDValue N1, SDValue N2) {
5448   // TODO: We don't do any constant folding for strict FP opcodes here, but we
5449   //       should. That will require dealing with a potentially non-default
5450   //       rounding mode, checking the "opStatus" return value from the APFloat
5451   //       math calculations, and possibly other variations.
5452   auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1.getNode());
5453   auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2.getNode());
5454   if (N1CFP && N2CFP) {
5455     APFloat C1 = N1CFP->getValueAPF(), C2 = N2CFP->getValueAPF();
5456     switch (Opcode) {
5457     case ISD::FADD:
5458       C1.add(C2, APFloat::rmNearestTiesToEven);
5459       return getConstantFP(C1, DL, VT);
5460     case ISD::FSUB:
5461       C1.subtract(C2, APFloat::rmNearestTiesToEven);
5462       return getConstantFP(C1, DL, VT);
5463     case ISD::FMUL:
5464       C1.multiply(C2, APFloat::rmNearestTiesToEven);
5465       return getConstantFP(C1, DL, VT);
5466     case ISD::FDIV:
5467       C1.divide(C2, APFloat::rmNearestTiesToEven);
5468       return getConstantFP(C1, DL, VT);
5469     case ISD::FREM:
5470       C1.mod(C2);
5471       return getConstantFP(C1, DL, VT);
5472     case ISD::FCOPYSIGN:
5473       C1.copySign(C2);
5474       return getConstantFP(C1, DL, VT);
5475     default: break;
5476     }
5477   }
5478   if (N1CFP && Opcode == ISD::FP_ROUND) {
5479     APFloat C1 = N1CFP->getValueAPF();    // make copy
5480     bool Unused;
5481     // This can return overflow, underflow, or inexact; we don't care.
5482     // FIXME need to be more flexible about rounding mode.
5483     (void) C1.convert(EVTToAPFloatSemantics(VT), APFloat::rmNearestTiesToEven,
5484                       &Unused);
5485     return getConstantFP(C1, DL, VT);
5486   }
5487 
5488   switch (Opcode) {
5489   case ISD::FSUB:
5490     // -0.0 - undef --> undef (consistent with "fneg undef")
5491     if (N1CFP && N1CFP->getValueAPF().isNegZero() && N2.isUndef())
5492       return getUNDEF(VT);
5493     LLVM_FALLTHROUGH;
5494 
5495   case ISD::FADD:
5496   case ISD::FMUL:
5497   case ISD::FDIV:
5498   case ISD::FREM:
5499     // If both operands are undef, the result is undef. If 1 operand is undef,
5500     // the result is NaN. This should match the behavior of the IR optimizer.
5501     if (N1.isUndef() && N2.isUndef())
5502       return getUNDEF(VT);
5503     if (N1.isUndef() || N2.isUndef())
5504       return getConstantFP(APFloat::getNaN(EVTToAPFloatSemantics(VT)), DL, VT);
5505   }
5506   return SDValue();
5507 }
5508 
5509 SDValue SelectionDAG::getAssertAlign(const SDLoc &DL, SDValue Val, Align A) {
5510   assert(Val.getValueType().isInteger() && "Invalid AssertAlign!");
5511 
5512   // There's no need to assert on a byte-aligned pointer. All pointers are at
5513   // least byte aligned.
5514   if (A == Align(1))
5515     return Val;
5516 
5517   FoldingSetNodeID ID;
5518   AddNodeIDNode(ID, ISD::AssertAlign, getVTList(Val.getValueType()), {Val});
5519   ID.AddInteger(A.value());
5520 
5521   void *IP = nullptr;
5522   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
5523     return SDValue(E, 0);
5524 
5525   auto *N = newSDNode<AssertAlignSDNode>(DL.getIROrder(), DL.getDebugLoc(),
5526                                          Val.getValueType(), A);
5527   createOperands(N, {Val});
5528 
5529   CSEMap.InsertNode(N, IP);
5530   InsertNode(N);
5531 
5532   SDValue V(N, 0);
5533   NewSDValueDbgMsg(V, "Creating new node: ", this);
5534   return V;
5535 }
5536 
5537 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5538                               SDValue N1, SDValue N2) {
5539   SDNodeFlags Flags;
5540   if (Inserter)
5541     Flags = Inserter->getFlags();
5542   return getNode(Opcode, DL, VT, N1, N2, Flags);
5543 }
5544 
5545 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5546                               SDValue N1, SDValue N2, const SDNodeFlags Flags) {
5547   assert(N1.getOpcode() != ISD::DELETED_NODE &&
5548          N2.getOpcode() != ISD::DELETED_NODE &&
5549          "Operand is DELETED_NODE!");
5550   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
5551   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
5552   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5553   ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
5554 
5555   // Canonicalize constant to RHS if commutative.
5556   if (TLI->isCommutativeBinOp(Opcode)) {
5557     if (N1C && !N2C) {
5558       std::swap(N1C, N2C);
5559       std::swap(N1, N2);
5560     } else if (N1CFP && !N2CFP) {
5561       std::swap(N1CFP, N2CFP);
5562       std::swap(N1, N2);
5563     }
5564   }
5565 
5566   switch (Opcode) {
5567   default: break;
5568   case ISD::TokenFactor:
5569     assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
5570            N2.getValueType() == MVT::Other && "Invalid token factor!");
5571     // Fold trivial token factors.
5572     if (N1.getOpcode() == ISD::EntryToken) return N2;
5573     if (N2.getOpcode() == ISD::EntryToken) return N1;
5574     if (N1 == N2) return N1;
5575     break;
5576   case ISD::BUILD_VECTOR: {
5577     // Attempt to simplify BUILD_VECTOR.
5578     SDValue Ops[] = {N1, N2};
5579     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
5580       return V;
5581     break;
5582   }
5583   case ISD::CONCAT_VECTORS: {
5584     SDValue Ops[] = {N1, N2};
5585     if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
5586       return V;
5587     break;
5588   }
5589   case ISD::AND:
5590     assert(VT.isInteger() && "This operator does not apply to FP types!");
5591     assert(N1.getValueType() == N2.getValueType() &&
5592            N1.getValueType() == VT && "Binary operator types must match!");
5593     // (X & 0) -> 0.  This commonly occurs when legalizing i64 values, so it's
5594     // worth handling here.
5595     if (N2C && N2C->isZero())
5596       return N2;
5597     if (N2C && N2C->isAllOnes()) // X & -1 -> X
5598       return N1;
5599     break;
5600   case ISD::OR:
5601   case ISD::XOR:
5602   case ISD::ADD:
5603   case ISD::SUB:
5604     assert(VT.isInteger() && "This operator does not apply to FP types!");
5605     assert(N1.getValueType() == N2.getValueType() &&
5606            N1.getValueType() == VT && "Binary operator types must match!");
5607     // (X ^|+- 0) -> X.  This commonly occurs when legalizing i64 values, so
5608     // it's worth handling here.
5609     if (N2C && N2C->isZero())
5610       return N1;
5611     if ((Opcode == ISD::ADD || Opcode == ISD::SUB) && VT.isVector() &&
5612         VT.getVectorElementType() == MVT::i1)
5613       return getNode(ISD::XOR, DL, VT, N1, N2);
5614     break;
5615   case ISD::MUL:
5616     assert(VT.isInteger() && "This operator does not apply to FP types!");
5617     assert(N1.getValueType() == N2.getValueType() &&
5618            N1.getValueType() == VT && "Binary operator types must match!");
5619     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
5620       return getNode(ISD::AND, DL, VT, N1, N2);
5621     if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
5622       const APInt &MulImm = N1->getConstantOperandAPInt(0);
5623       const APInt &N2CImm = N2C->getAPIntValue();
5624       return getVScale(DL, VT, MulImm * N2CImm);
5625     }
5626     break;
5627   case ISD::UDIV:
5628   case ISD::UREM:
5629   case ISD::MULHU:
5630   case ISD::MULHS:
5631   case ISD::SDIV:
5632   case ISD::SREM:
5633   case ISD::SADDSAT:
5634   case ISD::SSUBSAT:
5635   case ISD::UADDSAT:
5636   case ISD::USUBSAT:
5637     assert(VT.isInteger() && "This operator does not apply to FP types!");
5638     assert(N1.getValueType() == N2.getValueType() &&
5639            N1.getValueType() == VT && "Binary operator types must match!");
5640     if (VT.isVector() && VT.getVectorElementType() == MVT::i1) {
5641       // fold (add_sat x, y) -> (or x, y) for bool types.
5642       if (Opcode == ISD::SADDSAT || Opcode == ISD::UADDSAT)
5643         return getNode(ISD::OR, DL, VT, N1, N2);
5644       // fold (sub_sat x, y) -> (and x, ~y) for bool types.
5645       if (Opcode == ISD::SSUBSAT || Opcode == ISD::USUBSAT)
5646         return getNode(ISD::AND, DL, VT, N1, getNOT(DL, N2, VT));
5647     }
5648     break;
5649   case ISD::SMIN:
5650   case ISD::UMAX:
5651     assert(VT.isInteger() && "This operator does not apply to FP types!");
5652     assert(N1.getValueType() == N2.getValueType() &&
5653            N1.getValueType() == VT && "Binary operator types must match!");
5654     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
5655       return getNode(ISD::OR, DL, VT, N1, N2);
5656     break;
5657   case ISD::SMAX:
5658   case ISD::UMIN:
5659     assert(VT.isInteger() && "This operator does not apply to FP types!");
5660     assert(N1.getValueType() == N2.getValueType() &&
5661            N1.getValueType() == VT && "Binary operator types must match!");
5662     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
5663       return getNode(ISD::AND, DL, VT, N1, N2);
5664     break;
5665   case ISD::FADD:
5666   case ISD::FSUB:
5667   case ISD::FMUL:
5668   case ISD::FDIV:
5669   case ISD::FREM:
5670     assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
5671     assert(N1.getValueType() == N2.getValueType() &&
5672            N1.getValueType() == VT && "Binary operator types must match!");
5673     if (SDValue V = simplifyFPBinop(Opcode, N1, N2, Flags))
5674       return V;
5675     break;
5676   case ISD::FCOPYSIGN:   // N1 and result must match.  N1/N2 need not match.
5677     assert(N1.getValueType() == VT &&
5678            N1.getValueType().isFloatingPoint() &&
5679            N2.getValueType().isFloatingPoint() &&
5680            "Invalid FCOPYSIGN!");
5681     break;
5682   case ISD::SHL:
5683     if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
5684       const APInt &MulImm = N1->getConstantOperandAPInt(0);
5685       const APInt &ShiftImm = N2C->getAPIntValue();
5686       return getVScale(DL, VT, MulImm << ShiftImm);
5687     }
5688     LLVM_FALLTHROUGH;
5689   case ISD::SRA:
5690   case ISD::SRL:
5691     if (SDValue V = simplifyShift(N1, N2))
5692       return V;
5693     LLVM_FALLTHROUGH;
5694   case ISD::ROTL:
5695   case ISD::ROTR:
5696     assert(VT == N1.getValueType() &&
5697            "Shift operators return type must be the same as their first arg");
5698     assert(VT.isInteger() && N2.getValueType().isInteger() &&
5699            "Shifts only work on integers");
5700     assert((!VT.isVector() || VT == N2.getValueType()) &&
5701            "Vector shift amounts must be in the same as their first arg");
5702     // Verify that the shift amount VT is big enough to hold valid shift
5703     // amounts.  This catches things like trying to shift an i1024 value by an
5704     // i8, which is easy to fall into in generic code that uses
5705     // TLI.getShiftAmount().
5706     assert(N2.getValueType().getScalarSizeInBits() >=
5707                Log2_32_Ceil(VT.getScalarSizeInBits()) &&
5708            "Invalid use of small shift amount with oversized value!");
5709 
5710     // Always fold shifts of i1 values so the code generator doesn't need to
5711     // handle them.  Since we know the size of the shift has to be less than the
5712     // size of the value, the shift/rotate count is guaranteed to be zero.
5713     if (VT == MVT::i1)
5714       return N1;
5715     if (N2C && N2C->isZero())
5716       return N1;
5717     break;
5718   case ISD::FP_ROUND:
5719     assert(VT.isFloatingPoint() &&
5720            N1.getValueType().isFloatingPoint() &&
5721            VT.bitsLE(N1.getValueType()) &&
5722            N2C && (N2C->getZExtValue() == 0 || N2C->getZExtValue() == 1) &&
5723            "Invalid FP_ROUND!");
5724     if (N1.getValueType() == VT) return N1;  // noop conversion.
5725     break;
5726   case ISD::AssertSext:
5727   case ISD::AssertZext: {
5728     EVT EVT = cast<VTSDNode>(N2)->getVT();
5729     assert(VT == N1.getValueType() && "Not an inreg extend!");
5730     assert(VT.isInteger() && EVT.isInteger() &&
5731            "Cannot *_EXTEND_INREG FP types");
5732     assert(!EVT.isVector() &&
5733            "AssertSExt/AssertZExt type should be the vector element type "
5734            "rather than the vector type!");
5735     assert(EVT.bitsLE(VT.getScalarType()) && "Not extending!");
5736     if (VT.getScalarType() == EVT) return N1; // noop assertion.
5737     break;
5738   }
5739   case ISD::SIGN_EXTEND_INREG: {
5740     EVT EVT = cast<VTSDNode>(N2)->getVT();
5741     assert(VT == N1.getValueType() && "Not an inreg extend!");
5742     assert(VT.isInteger() && EVT.isInteger() &&
5743            "Cannot *_EXTEND_INREG FP types");
5744     assert(EVT.isVector() == VT.isVector() &&
5745            "SIGN_EXTEND_INREG type should be vector iff the operand "
5746            "type is vector!");
5747     assert((!EVT.isVector() ||
5748             EVT.getVectorElementCount() == VT.getVectorElementCount()) &&
5749            "Vector element counts must match in SIGN_EXTEND_INREG");
5750     assert(EVT.bitsLE(VT) && "Not extending!");
5751     if (EVT == VT) return N1;  // Not actually extending
5752 
5753     auto SignExtendInReg = [&](APInt Val, llvm::EVT ConstantVT) {
5754       unsigned FromBits = EVT.getScalarSizeInBits();
5755       Val <<= Val.getBitWidth() - FromBits;
5756       Val.ashrInPlace(Val.getBitWidth() - FromBits);
5757       return getConstant(Val, DL, ConstantVT);
5758     };
5759 
5760     if (N1C) {
5761       const APInt &Val = N1C->getAPIntValue();
5762       return SignExtendInReg(Val, VT);
5763     }
5764 
5765     if (ISD::isBuildVectorOfConstantSDNodes(N1.getNode())) {
5766       SmallVector<SDValue, 8> Ops;
5767       llvm::EVT OpVT = N1.getOperand(0).getValueType();
5768       for (int i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
5769         SDValue Op = N1.getOperand(i);
5770         if (Op.isUndef()) {
5771           Ops.push_back(getUNDEF(OpVT));
5772           continue;
5773         }
5774         ConstantSDNode *C = cast<ConstantSDNode>(Op);
5775         APInt Val = C->getAPIntValue();
5776         Ops.push_back(SignExtendInReg(Val, OpVT));
5777       }
5778       return getBuildVector(VT, DL, Ops);
5779     }
5780     break;
5781   }
5782   case ISD::FP_TO_SINT_SAT:
5783   case ISD::FP_TO_UINT_SAT: {
5784     assert(VT.isInteger() && cast<VTSDNode>(N2)->getVT().isInteger() &&
5785            N1.getValueType().isFloatingPoint() && "Invalid FP_TO_*INT_SAT");
5786     assert(N1.getValueType().isVector() == VT.isVector() &&
5787            "FP_TO_*INT_SAT type should be vector iff the operand type is "
5788            "vector!");
5789     assert((!VT.isVector() || VT.getVectorNumElements() ==
5790                                   N1.getValueType().getVectorNumElements()) &&
5791            "Vector element counts must match in FP_TO_*INT_SAT");
5792     assert(!cast<VTSDNode>(N2)->getVT().isVector() &&
5793            "Type to saturate to must be a scalar.");
5794     assert(cast<VTSDNode>(N2)->getVT().bitsLE(VT.getScalarType()) &&
5795            "Not extending!");
5796     break;
5797   }
5798   case ISD::EXTRACT_VECTOR_ELT:
5799     assert(VT.getSizeInBits() >= N1.getValueType().getScalarSizeInBits() &&
5800            "The result of EXTRACT_VECTOR_ELT must be at least as wide as the \
5801              element type of the vector.");
5802 
5803     // Extract from an undefined value or using an undefined index is undefined.
5804     if (N1.isUndef() || N2.isUndef())
5805       return getUNDEF(VT);
5806 
5807     // EXTRACT_VECTOR_ELT of out-of-bounds element is an UNDEF for fixed length
5808     // vectors. For scalable vectors we will provide appropriate support for
5809     // dealing with arbitrary indices.
5810     if (N2C && N1.getValueType().isFixedLengthVector() &&
5811         N2C->getAPIntValue().uge(N1.getValueType().getVectorNumElements()))
5812       return getUNDEF(VT);
5813 
5814     // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
5815     // expanding copies of large vectors from registers. This only works for
5816     // fixed length vectors, since we need to know the exact number of
5817     // elements.
5818     if (N2C && N1.getOperand(0).getValueType().isFixedLengthVector() &&
5819         N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0) {
5820       unsigned Factor =
5821         N1.getOperand(0).getValueType().getVectorNumElements();
5822       return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
5823                      N1.getOperand(N2C->getZExtValue() / Factor),
5824                      getVectorIdxConstant(N2C->getZExtValue() % Factor, DL));
5825     }
5826 
5827     // EXTRACT_VECTOR_ELT of BUILD_VECTOR or SPLAT_VECTOR is often formed while
5828     // lowering is expanding large vector constants.
5829     if (N2C && (N1.getOpcode() == ISD::BUILD_VECTOR ||
5830                 N1.getOpcode() == ISD::SPLAT_VECTOR)) {
5831       assert((N1.getOpcode() != ISD::BUILD_VECTOR ||
5832               N1.getValueType().isFixedLengthVector()) &&
5833              "BUILD_VECTOR used for scalable vectors");
5834       unsigned Index =
5835           N1.getOpcode() == ISD::BUILD_VECTOR ? N2C->getZExtValue() : 0;
5836       SDValue Elt = N1.getOperand(Index);
5837 
5838       if (VT != Elt.getValueType())
5839         // If the vector element type is not legal, the BUILD_VECTOR operands
5840         // are promoted and implicitly truncated, and the result implicitly
5841         // extended. Make that explicit here.
5842         Elt = getAnyExtOrTrunc(Elt, DL, VT);
5843 
5844       return Elt;
5845     }
5846 
5847     // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
5848     // operations are lowered to scalars.
5849     if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) {
5850       // If the indices are the same, return the inserted element else
5851       // if the indices are known different, extract the element from
5852       // the original vector.
5853       SDValue N1Op2 = N1.getOperand(2);
5854       ConstantSDNode *N1Op2C = dyn_cast<ConstantSDNode>(N1Op2);
5855 
5856       if (N1Op2C && N2C) {
5857         if (N1Op2C->getZExtValue() == N2C->getZExtValue()) {
5858           if (VT == N1.getOperand(1).getValueType())
5859             return N1.getOperand(1);
5860           return getSExtOrTrunc(N1.getOperand(1), DL, VT);
5861         }
5862         return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2);
5863       }
5864     }
5865 
5866     // EXTRACT_VECTOR_ELT of v1iX EXTRACT_SUBVECTOR could be formed
5867     // when vector types are scalarized and v1iX is legal.
5868     // vextract (v1iX extract_subvector(vNiX, Idx)) -> vextract(vNiX,Idx).
5869     // Here we are completely ignoring the extract element index (N2),
5870     // which is fine for fixed width vectors, since any index other than 0
5871     // is undefined anyway. However, this cannot be ignored for scalable
5872     // vectors - in theory we could support this, but we don't want to do this
5873     // without a profitability check.
5874     if (N1.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
5875         N1.getValueType().isFixedLengthVector() &&
5876         N1.getValueType().getVectorNumElements() == 1) {
5877       return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0),
5878                      N1.getOperand(1));
5879     }
5880     break;
5881   case ISD::EXTRACT_ELEMENT:
5882     assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!");
5883     assert(!N1.getValueType().isVector() && !VT.isVector() &&
5884            (N1.getValueType().isInteger() == VT.isInteger()) &&
5885            N1.getValueType() != VT &&
5886            "Wrong types for EXTRACT_ELEMENT!");
5887 
5888     // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
5889     // 64-bit integers into 32-bit parts.  Instead of building the extract of
5890     // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
5891     if (N1.getOpcode() == ISD::BUILD_PAIR)
5892       return N1.getOperand(N2C->getZExtValue());
5893 
5894     // EXTRACT_ELEMENT of a constant int is also very common.
5895     if (N1C) {
5896       unsigned ElementSize = VT.getSizeInBits();
5897       unsigned Shift = ElementSize * N2C->getZExtValue();
5898       const APInt &Val = N1C->getAPIntValue();
5899       return getConstant(Val.extractBits(ElementSize, Shift), DL, VT);
5900     }
5901     break;
5902   case ISD::EXTRACT_SUBVECTOR: {
5903     EVT N1VT = N1.getValueType();
5904     assert(VT.isVector() && N1VT.isVector() &&
5905            "Extract subvector VTs must be vectors!");
5906     assert(VT.getVectorElementType() == N1VT.getVectorElementType() &&
5907            "Extract subvector VTs must have the same element type!");
5908     assert((VT.isFixedLengthVector() || N1VT.isScalableVector()) &&
5909            "Cannot extract a scalable vector from a fixed length vector!");
5910     assert((VT.isScalableVector() != N1VT.isScalableVector() ||
5911             VT.getVectorMinNumElements() <= N1VT.getVectorMinNumElements()) &&
5912            "Extract subvector must be from larger vector to smaller vector!");
5913     assert(N2C && "Extract subvector index must be a constant");
5914     assert((VT.isScalableVector() != N1VT.isScalableVector() ||
5915             (VT.getVectorMinNumElements() + N2C->getZExtValue()) <=
5916                 N1VT.getVectorMinNumElements()) &&
5917            "Extract subvector overflow!");
5918     assert(N2C->getAPIntValue().getBitWidth() ==
5919                TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() &&
5920            "Constant index for EXTRACT_SUBVECTOR has an invalid size");
5921 
5922     // Trivial extraction.
5923     if (VT == N1VT)
5924       return N1;
5925 
5926     // EXTRACT_SUBVECTOR of an UNDEF is an UNDEF.
5927     if (N1.isUndef())
5928       return getUNDEF(VT);
5929 
5930     // EXTRACT_SUBVECTOR of CONCAT_VECTOR can be simplified if the pieces of
5931     // the concat have the same type as the extract.
5932     if (N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0 &&
5933         VT == N1.getOperand(0).getValueType()) {
5934       unsigned Factor = VT.getVectorMinNumElements();
5935       return N1.getOperand(N2C->getZExtValue() / Factor);
5936     }
5937 
5938     // EXTRACT_SUBVECTOR of INSERT_SUBVECTOR is often created
5939     // during shuffle legalization.
5940     if (N1.getOpcode() == ISD::INSERT_SUBVECTOR && N2 == N1.getOperand(2) &&
5941         VT == N1.getOperand(1).getValueType())
5942       return N1.getOperand(1);
5943     break;
5944   }
5945   }
5946 
5947   // Perform trivial constant folding.
5948   if (SDValue SV = FoldConstantArithmetic(Opcode, DL, VT, {N1, N2}))
5949     return SV;
5950 
5951   if (SDValue V = foldConstantFPMath(Opcode, DL, VT, N1, N2))
5952     return V;
5953 
5954   // Canonicalize an UNDEF to the RHS, even over a constant.
5955   if (N1.isUndef()) {
5956     if (TLI->isCommutativeBinOp(Opcode)) {
5957       std::swap(N1, N2);
5958     } else {
5959       switch (Opcode) {
5960       case ISD::SIGN_EXTEND_INREG:
5961       case ISD::SUB:
5962         return getUNDEF(VT);     // fold op(undef, arg2) -> undef
5963       case ISD::UDIV:
5964       case ISD::SDIV:
5965       case ISD::UREM:
5966       case ISD::SREM:
5967       case ISD::SSUBSAT:
5968       case ISD::USUBSAT:
5969         return getConstant(0, DL, VT);    // fold op(undef, arg2) -> 0
5970       }
5971     }
5972   }
5973 
5974   // Fold a bunch of operators when the RHS is undef.
5975   if (N2.isUndef()) {
5976     switch (Opcode) {
5977     case ISD::XOR:
5978       if (N1.isUndef())
5979         // Handle undef ^ undef -> 0 special case. This is a common
5980         // idiom (misuse).
5981         return getConstant(0, DL, VT);
5982       LLVM_FALLTHROUGH;
5983     case ISD::ADD:
5984     case ISD::SUB:
5985     case ISD::UDIV:
5986     case ISD::SDIV:
5987     case ISD::UREM:
5988     case ISD::SREM:
5989       return getUNDEF(VT);       // fold op(arg1, undef) -> undef
5990     case ISD::MUL:
5991     case ISD::AND:
5992     case ISD::SSUBSAT:
5993     case ISD::USUBSAT:
5994       return getConstant(0, DL, VT);  // fold op(arg1, undef) -> 0
5995     case ISD::OR:
5996     case ISD::SADDSAT:
5997     case ISD::UADDSAT:
5998       return getAllOnesConstant(DL, VT);
5999     }
6000   }
6001 
6002   // Memoize this node if possible.
6003   SDNode *N;
6004   SDVTList VTs = getVTList(VT);
6005   SDValue Ops[] = {N1, N2};
6006   if (VT != MVT::Glue) {
6007     FoldingSetNodeID ID;
6008     AddNodeIDNode(ID, Opcode, VTs, Ops);
6009     void *IP = nullptr;
6010     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
6011       E->intersectFlagsWith(Flags);
6012       return SDValue(E, 0);
6013     }
6014 
6015     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6016     N->setFlags(Flags);
6017     createOperands(N, Ops);
6018     CSEMap.InsertNode(N, IP);
6019   } else {
6020     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6021     createOperands(N, Ops);
6022   }
6023 
6024   InsertNode(N);
6025   SDValue V = SDValue(N, 0);
6026   NewSDValueDbgMsg(V, "Creating new node: ", this);
6027   return V;
6028 }
6029 
6030 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6031                               SDValue N1, SDValue N2, SDValue N3) {
6032   SDNodeFlags Flags;
6033   if (Inserter)
6034     Flags = Inserter->getFlags();
6035   return getNode(Opcode, DL, VT, N1, N2, N3, Flags);
6036 }
6037 
6038 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6039                               SDValue N1, SDValue N2, SDValue N3,
6040                               const SDNodeFlags Flags) {
6041   assert(N1.getOpcode() != ISD::DELETED_NODE &&
6042          N2.getOpcode() != ISD::DELETED_NODE &&
6043          N3.getOpcode() != ISD::DELETED_NODE &&
6044          "Operand is DELETED_NODE!");
6045   // Perform various simplifications.
6046   switch (Opcode) {
6047   case ISD::FMA: {
6048     assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
6049     assert(N1.getValueType() == VT && N2.getValueType() == VT &&
6050            N3.getValueType() == VT && "FMA types must match!");
6051     ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6052     ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
6053     ConstantFPSDNode *N3CFP = dyn_cast<ConstantFPSDNode>(N3);
6054     if (N1CFP && N2CFP && N3CFP) {
6055       APFloat  V1 = N1CFP->getValueAPF();
6056       const APFloat &V2 = N2CFP->getValueAPF();
6057       const APFloat &V3 = N3CFP->getValueAPF();
6058       V1.fusedMultiplyAdd(V2, V3, APFloat::rmNearestTiesToEven);
6059       return getConstantFP(V1, DL, VT);
6060     }
6061     break;
6062   }
6063   case ISD::BUILD_VECTOR: {
6064     // Attempt to simplify BUILD_VECTOR.
6065     SDValue Ops[] = {N1, N2, N3};
6066     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
6067       return V;
6068     break;
6069   }
6070   case ISD::CONCAT_VECTORS: {
6071     SDValue Ops[] = {N1, N2, N3};
6072     if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
6073       return V;
6074     break;
6075   }
6076   case ISD::SETCC: {
6077     assert(VT.isInteger() && "SETCC result type must be an integer!");
6078     assert(N1.getValueType() == N2.getValueType() &&
6079            "SETCC operands must have the same type!");
6080     assert(VT.isVector() == N1.getValueType().isVector() &&
6081            "SETCC type should be vector iff the operand type is vector!");
6082     assert((!VT.isVector() || VT.getVectorElementCount() ==
6083                                   N1.getValueType().getVectorElementCount()) &&
6084            "SETCC vector element counts must match!");
6085     // Use FoldSetCC to simplify SETCC's.
6086     if (SDValue V = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL))
6087       return V;
6088     // Vector constant folding.
6089     SDValue Ops[] = {N1, N2, N3};
6090     if (SDValue V = FoldConstantArithmetic(Opcode, DL, VT, Ops)) {
6091       NewSDValueDbgMsg(V, "New node vector constant folding: ", this);
6092       return V;
6093     }
6094     break;
6095   }
6096   case ISD::SELECT:
6097   case ISD::VSELECT:
6098     if (SDValue V = simplifySelect(N1, N2, N3))
6099       return V;
6100     break;
6101   case ISD::VECTOR_SHUFFLE:
6102     llvm_unreachable("should use getVectorShuffle constructor!");
6103   case ISD::VECTOR_SPLICE: {
6104     if (cast<ConstantSDNode>(N3)->isNullValue())
6105       return N1;
6106     break;
6107   }
6108   case ISD::INSERT_VECTOR_ELT: {
6109     ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3);
6110     // INSERT_VECTOR_ELT into out-of-bounds element is an UNDEF, except
6111     // for scalable vectors where we will generate appropriate code to
6112     // deal with out-of-bounds cases correctly.
6113     if (N3C && N1.getValueType().isFixedLengthVector() &&
6114         N3C->getZExtValue() >= N1.getValueType().getVectorNumElements())
6115       return getUNDEF(VT);
6116 
6117     // Undefined index can be assumed out-of-bounds, so that's UNDEF too.
6118     if (N3.isUndef())
6119       return getUNDEF(VT);
6120 
6121     // If the inserted element is an UNDEF, just use the input vector.
6122     if (N2.isUndef())
6123       return N1;
6124 
6125     break;
6126   }
6127   case ISD::INSERT_SUBVECTOR: {
6128     // Inserting undef into undef is still undef.
6129     if (N1.isUndef() && N2.isUndef())
6130       return getUNDEF(VT);
6131 
6132     EVT N2VT = N2.getValueType();
6133     assert(VT == N1.getValueType() &&
6134            "Dest and insert subvector source types must match!");
6135     assert(VT.isVector() && N2VT.isVector() &&
6136            "Insert subvector VTs must be vectors!");
6137     assert((VT.isScalableVector() || N2VT.isFixedLengthVector()) &&
6138            "Cannot insert a scalable vector into a fixed length vector!");
6139     assert((VT.isScalableVector() != N2VT.isScalableVector() ||
6140             VT.getVectorMinNumElements() >= N2VT.getVectorMinNumElements()) &&
6141            "Insert subvector must be from smaller vector to larger vector!");
6142     assert(isa<ConstantSDNode>(N3) &&
6143            "Insert subvector index must be constant");
6144     assert((VT.isScalableVector() != N2VT.isScalableVector() ||
6145             (N2VT.getVectorMinNumElements() +
6146              cast<ConstantSDNode>(N3)->getZExtValue()) <=
6147                 VT.getVectorMinNumElements()) &&
6148            "Insert subvector overflow!");
6149     assert(cast<ConstantSDNode>(N3)->getAPIntValue().getBitWidth() ==
6150                TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() &&
6151            "Constant index for INSERT_SUBVECTOR has an invalid size");
6152 
6153     // Trivial insertion.
6154     if (VT == N2VT)
6155       return N2;
6156 
6157     // If this is an insert of an extracted vector into an undef vector, we
6158     // can just use the input to the extract.
6159     if (N1.isUndef() && N2.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
6160         N2.getOperand(1) == N3 && N2.getOperand(0).getValueType() == VT)
6161       return N2.getOperand(0);
6162     break;
6163   }
6164   case ISD::BITCAST:
6165     // Fold bit_convert nodes from a type to themselves.
6166     if (N1.getValueType() == VT)
6167       return N1;
6168     break;
6169   }
6170 
6171   // Memoize node if it doesn't produce a flag.
6172   SDNode *N;
6173   SDVTList VTs = getVTList(VT);
6174   SDValue Ops[] = {N1, N2, N3};
6175   if (VT != MVT::Glue) {
6176     FoldingSetNodeID ID;
6177     AddNodeIDNode(ID, Opcode, VTs, Ops);
6178     void *IP = nullptr;
6179     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
6180       E->intersectFlagsWith(Flags);
6181       return SDValue(E, 0);
6182     }
6183 
6184     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6185     N->setFlags(Flags);
6186     createOperands(N, Ops);
6187     CSEMap.InsertNode(N, IP);
6188   } else {
6189     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6190     createOperands(N, Ops);
6191   }
6192 
6193   InsertNode(N);
6194   SDValue V = SDValue(N, 0);
6195   NewSDValueDbgMsg(V, "Creating new node: ", this);
6196   return V;
6197 }
6198 
6199 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6200                               SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
6201   SDValue Ops[] = { N1, N2, N3, N4 };
6202   return getNode(Opcode, DL, VT, Ops);
6203 }
6204 
6205 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6206                               SDValue N1, SDValue N2, SDValue N3, SDValue N4,
6207                               SDValue N5) {
6208   SDValue Ops[] = { N1, N2, N3, N4, N5 };
6209   return getNode(Opcode, DL, VT, Ops);
6210 }
6211 
6212 /// getStackArgumentTokenFactor - Compute a TokenFactor to force all
6213 /// the incoming stack arguments to be loaded from the stack.
6214 SDValue SelectionDAG::getStackArgumentTokenFactor(SDValue Chain) {
6215   SmallVector<SDValue, 8> ArgChains;
6216 
6217   // Include the original chain at the beginning of the list. When this is
6218   // used by target LowerCall hooks, this helps legalize find the
6219   // CALLSEQ_BEGIN node.
6220   ArgChains.push_back(Chain);
6221 
6222   // Add a chain value for each stack argument.
6223   for (SDNode *U : getEntryNode().getNode()->uses())
6224     if (LoadSDNode *L = dyn_cast<LoadSDNode>(U))
6225       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
6226         if (FI->getIndex() < 0)
6227           ArgChains.push_back(SDValue(L, 1));
6228 
6229   // Build a tokenfactor for all the chains.
6230   return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
6231 }
6232 
6233 /// getMemsetValue - Vectorized representation of the memset value
6234 /// operand.
6235 static SDValue getMemsetValue(SDValue Value, EVT VT, SelectionDAG &DAG,
6236                               const SDLoc &dl) {
6237   assert(!Value.isUndef());
6238 
6239   unsigned NumBits = VT.getScalarSizeInBits();
6240   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
6241     assert(C->getAPIntValue().getBitWidth() == 8);
6242     APInt Val = APInt::getSplat(NumBits, C->getAPIntValue());
6243     if (VT.isInteger()) {
6244       bool IsOpaque = VT.getSizeInBits() > 64 ||
6245           !DAG.getTargetLoweringInfo().isLegalStoreImmediate(C->getSExtValue());
6246       return DAG.getConstant(Val, dl, VT, false, IsOpaque);
6247     }
6248     return DAG.getConstantFP(APFloat(DAG.EVTToAPFloatSemantics(VT), Val), dl,
6249                              VT);
6250   }
6251 
6252   assert(Value.getValueType() == MVT::i8 && "memset with non-byte fill value?");
6253   EVT IntVT = VT.getScalarType();
6254   if (!IntVT.isInteger())
6255     IntVT = EVT::getIntegerVT(*DAG.getContext(), IntVT.getSizeInBits());
6256 
6257   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, Value);
6258   if (NumBits > 8) {
6259     // Use a multiplication with 0x010101... to extend the input to the
6260     // required length.
6261     APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01));
6262     Value = DAG.getNode(ISD::MUL, dl, IntVT, Value,
6263                         DAG.getConstant(Magic, dl, IntVT));
6264   }
6265 
6266   if (VT != Value.getValueType() && !VT.isInteger())
6267     Value = DAG.getBitcast(VT.getScalarType(), Value);
6268   if (VT != Value.getValueType())
6269     Value = DAG.getSplatBuildVector(VT, dl, Value);
6270 
6271   return Value;
6272 }
6273 
6274 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
6275 /// used when a memcpy is turned into a memset when the source is a constant
6276 /// string ptr.
6277 static SDValue getMemsetStringVal(EVT VT, const SDLoc &dl, SelectionDAG &DAG,
6278                                   const TargetLowering &TLI,
6279                                   const ConstantDataArraySlice &Slice) {
6280   // Handle vector with all elements zero.
6281   if (Slice.Array == nullptr) {
6282     if (VT.isInteger())
6283       return DAG.getConstant(0, dl, VT);
6284     if (VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128)
6285       return DAG.getConstantFP(0.0, dl, VT);
6286     if (VT.isVector()) {
6287       unsigned NumElts = VT.getVectorNumElements();
6288       MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
6289       return DAG.getNode(ISD::BITCAST, dl, VT,
6290                          DAG.getConstant(0, dl,
6291                                          EVT::getVectorVT(*DAG.getContext(),
6292                                                           EltVT, NumElts)));
6293     }
6294     llvm_unreachable("Expected type!");
6295   }
6296 
6297   assert(!VT.isVector() && "Can't handle vector type here!");
6298   unsigned NumVTBits = VT.getSizeInBits();
6299   unsigned NumVTBytes = NumVTBits / 8;
6300   unsigned NumBytes = std::min(NumVTBytes, unsigned(Slice.Length));
6301 
6302   APInt Val(NumVTBits, 0);
6303   if (DAG.getDataLayout().isLittleEndian()) {
6304     for (unsigned i = 0; i != NumBytes; ++i)
6305       Val |= (uint64_t)(unsigned char)Slice[i] << i*8;
6306   } else {
6307     for (unsigned i = 0; i != NumBytes; ++i)
6308       Val |= (uint64_t)(unsigned char)Slice[i] << (NumVTBytes-i-1)*8;
6309   }
6310 
6311   // If the "cost" of materializing the integer immediate is less than the cost
6312   // of a load, then it is cost effective to turn the load into the immediate.
6313   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
6314   if (TLI.shouldConvertConstantLoadToIntImm(Val, Ty))
6315     return DAG.getConstant(Val, dl, VT);
6316   return SDValue(nullptr, 0);
6317 }
6318 
6319 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Base, TypeSize Offset,
6320                                            const SDLoc &DL,
6321                                            const SDNodeFlags Flags) {
6322   EVT VT = Base.getValueType();
6323   SDValue Index;
6324 
6325   if (Offset.isScalable())
6326     Index = getVScale(DL, Base.getValueType(),
6327                       APInt(Base.getValueSizeInBits().getFixedSize(),
6328                             Offset.getKnownMinSize()));
6329   else
6330     Index = getConstant(Offset.getFixedSize(), DL, VT);
6331 
6332   return getMemBasePlusOffset(Base, Index, DL, Flags);
6333 }
6334 
6335 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Ptr, SDValue Offset,
6336                                            const SDLoc &DL,
6337                                            const SDNodeFlags Flags) {
6338   assert(Offset.getValueType().isInteger());
6339   EVT BasePtrVT = Ptr.getValueType();
6340   return getNode(ISD::ADD, DL, BasePtrVT, Ptr, Offset, Flags);
6341 }
6342 
6343 /// Returns true if memcpy source is constant data.
6344 static bool isMemSrcFromConstant(SDValue Src, ConstantDataArraySlice &Slice) {
6345   uint64_t SrcDelta = 0;
6346   GlobalAddressSDNode *G = nullptr;
6347   if (Src.getOpcode() == ISD::GlobalAddress)
6348     G = cast<GlobalAddressSDNode>(Src);
6349   else if (Src.getOpcode() == ISD::ADD &&
6350            Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
6351            Src.getOperand(1).getOpcode() == ISD::Constant) {
6352     G = cast<GlobalAddressSDNode>(Src.getOperand(0));
6353     SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue();
6354   }
6355   if (!G)
6356     return false;
6357 
6358   return getConstantDataArrayInfo(G->getGlobal(), Slice, 8,
6359                                   SrcDelta + G->getOffset());
6360 }
6361 
6362 static bool shouldLowerMemFuncForSize(const MachineFunction &MF,
6363                                       SelectionDAG &DAG) {
6364   // On Darwin, -Os means optimize for size without hurting performance, so
6365   // only really optimize for size when -Oz (MinSize) is used.
6366   if (MF.getTarget().getTargetTriple().isOSDarwin())
6367     return MF.getFunction().hasMinSize();
6368   return DAG.shouldOptForSize();
6369 }
6370 
6371 static void chainLoadsAndStoresForMemcpy(SelectionDAG &DAG, const SDLoc &dl,
6372                           SmallVector<SDValue, 32> &OutChains, unsigned From,
6373                           unsigned To, SmallVector<SDValue, 16> &OutLoadChains,
6374                           SmallVector<SDValue, 16> &OutStoreChains) {
6375   assert(OutLoadChains.size() && "Missing loads in memcpy inlining");
6376   assert(OutStoreChains.size() && "Missing stores in memcpy inlining");
6377   SmallVector<SDValue, 16> GluedLoadChains;
6378   for (unsigned i = From; i < To; ++i) {
6379     OutChains.push_back(OutLoadChains[i]);
6380     GluedLoadChains.push_back(OutLoadChains[i]);
6381   }
6382 
6383   // Chain for all loads.
6384   SDValue LoadToken = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6385                                   GluedLoadChains);
6386 
6387   for (unsigned i = From; i < To; ++i) {
6388     StoreSDNode *ST = dyn_cast<StoreSDNode>(OutStoreChains[i]);
6389     SDValue NewStore = DAG.getTruncStore(LoadToken, dl, ST->getValue(),
6390                                   ST->getBasePtr(), ST->getMemoryVT(),
6391                                   ST->getMemOperand());
6392     OutChains.push_back(NewStore);
6393   }
6394 }
6395 
6396 static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
6397                                        SDValue Chain, SDValue Dst, SDValue Src,
6398                                        uint64_t Size, Align Alignment,
6399                                        bool isVol, bool AlwaysInline,
6400                                        MachinePointerInfo DstPtrInfo,
6401                                        MachinePointerInfo SrcPtrInfo,
6402                                        const AAMDNodes &AAInfo) {
6403   // Turn a memcpy of undef to nop.
6404   // FIXME: We need to honor volatile even is Src is undef.
6405   if (Src.isUndef())
6406     return Chain;
6407 
6408   // Expand memcpy to a series of load and store ops if the size operand falls
6409   // below a certain threshold.
6410   // TODO: In the AlwaysInline case, if the size is big then generate a loop
6411   // rather than maybe a humongous number of loads and stores.
6412   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6413   const DataLayout &DL = DAG.getDataLayout();
6414   LLVMContext &C = *DAG.getContext();
6415   std::vector<EVT> MemOps;
6416   bool DstAlignCanChange = false;
6417   MachineFunction &MF = DAG.getMachineFunction();
6418   MachineFrameInfo &MFI = MF.getFrameInfo();
6419   bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
6420   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
6421   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
6422     DstAlignCanChange = true;
6423   MaybeAlign SrcAlign = DAG.InferPtrAlign(Src);
6424   if (!SrcAlign || Alignment > *SrcAlign)
6425     SrcAlign = Alignment;
6426   assert(SrcAlign && "SrcAlign must be set");
6427   ConstantDataArraySlice Slice;
6428   // If marked as volatile, perform a copy even when marked as constant.
6429   bool CopyFromConstant = !isVol && isMemSrcFromConstant(Src, Slice);
6430   bool isZeroConstant = CopyFromConstant && Slice.Array == nullptr;
6431   unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize);
6432   const MemOp Op = isZeroConstant
6433                        ? MemOp::Set(Size, DstAlignCanChange, Alignment,
6434                                     /*IsZeroMemset*/ true, isVol)
6435                        : MemOp::Copy(Size, DstAlignCanChange, Alignment,
6436                                      *SrcAlign, isVol, CopyFromConstant);
6437   if (!TLI.findOptimalMemOpLowering(
6438           MemOps, Limit, Op, DstPtrInfo.getAddrSpace(),
6439           SrcPtrInfo.getAddrSpace(), MF.getFunction().getAttributes()))
6440     return SDValue();
6441 
6442   if (DstAlignCanChange) {
6443     Type *Ty = MemOps[0].getTypeForEVT(C);
6444     Align NewAlign = DL.getABITypeAlign(Ty);
6445 
6446     // Don't promote to an alignment that would require dynamic stack
6447     // realignment.
6448     const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
6449     if (!TRI->hasStackRealignment(MF))
6450       while (NewAlign > Alignment && DL.exceedsNaturalStackAlignment(NewAlign))
6451         NewAlign = NewAlign / 2;
6452 
6453     if (NewAlign > Alignment) {
6454       // Give the stack frame object a larger alignment if needed.
6455       if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
6456         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
6457       Alignment = NewAlign;
6458     }
6459   }
6460 
6461   // Prepare AAInfo for loads/stores after lowering this memcpy.
6462   AAMDNodes NewAAInfo = AAInfo;
6463   NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
6464 
6465   MachineMemOperand::Flags MMOFlags =
6466       isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
6467   SmallVector<SDValue, 16> OutLoadChains;
6468   SmallVector<SDValue, 16> OutStoreChains;
6469   SmallVector<SDValue, 32> OutChains;
6470   unsigned NumMemOps = MemOps.size();
6471   uint64_t SrcOff = 0, DstOff = 0;
6472   for (unsigned i = 0; i != NumMemOps; ++i) {
6473     EVT VT = MemOps[i];
6474     unsigned VTSize = VT.getSizeInBits() / 8;
6475     SDValue Value, Store;
6476 
6477     if (VTSize > Size) {
6478       // Issuing an unaligned load / store pair  that overlaps with the previous
6479       // pair. Adjust the offset accordingly.
6480       assert(i == NumMemOps-1 && i != 0);
6481       SrcOff -= VTSize - Size;
6482       DstOff -= VTSize - Size;
6483     }
6484 
6485     if (CopyFromConstant &&
6486         (isZeroConstant || (VT.isInteger() && !VT.isVector()))) {
6487       // It's unlikely a store of a vector immediate can be done in a single
6488       // instruction. It would require a load from a constantpool first.
6489       // We only handle zero vectors here.
6490       // FIXME: Handle other cases where store of vector immediate is done in
6491       // a single instruction.
6492       ConstantDataArraySlice SubSlice;
6493       if (SrcOff < Slice.Length) {
6494         SubSlice = Slice;
6495         SubSlice.move(SrcOff);
6496       } else {
6497         // This is an out-of-bounds access and hence UB. Pretend we read zero.
6498         SubSlice.Array = nullptr;
6499         SubSlice.Offset = 0;
6500         SubSlice.Length = VTSize;
6501       }
6502       Value = getMemsetStringVal(VT, dl, DAG, TLI, SubSlice);
6503       if (Value.getNode()) {
6504         Store = DAG.getStore(
6505             Chain, dl, Value,
6506             DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6507             DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo);
6508         OutChains.push_back(Store);
6509       }
6510     }
6511 
6512     if (!Store.getNode()) {
6513       // The type might not be legal for the target.  This should only happen
6514       // if the type is smaller than a legal type, as on PPC, so the right
6515       // thing to do is generate a LoadExt/StoreTrunc pair.  These simplify
6516       // to Load/Store if NVT==VT.
6517       // FIXME does the case above also need this?
6518       EVT NVT = TLI.getTypeToTransformTo(C, VT);
6519       assert(NVT.bitsGE(VT));
6520 
6521       bool isDereferenceable =
6522         SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
6523       MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
6524       if (isDereferenceable)
6525         SrcMMOFlags |= MachineMemOperand::MODereferenceable;
6526 
6527       Value = DAG.getExtLoad(
6528           ISD::EXTLOAD, dl, NVT, Chain,
6529           DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl),
6530           SrcPtrInfo.getWithOffset(SrcOff), VT,
6531           commonAlignment(*SrcAlign, SrcOff), SrcMMOFlags, NewAAInfo);
6532       OutLoadChains.push_back(Value.getValue(1));
6533 
6534       Store = DAG.getTruncStore(
6535           Chain, dl, Value,
6536           DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6537           DstPtrInfo.getWithOffset(DstOff), VT, Alignment, MMOFlags, NewAAInfo);
6538       OutStoreChains.push_back(Store);
6539     }
6540     SrcOff += VTSize;
6541     DstOff += VTSize;
6542     Size -= VTSize;
6543   }
6544 
6545   unsigned GluedLdStLimit = MaxLdStGlue == 0 ?
6546                                 TLI.getMaxGluedStoresPerMemcpy() : MaxLdStGlue;
6547   unsigned NumLdStInMemcpy = OutStoreChains.size();
6548 
6549   if (NumLdStInMemcpy) {
6550     // It may be that memcpy might be converted to memset if it's memcpy
6551     // of constants. In such a case, we won't have loads and stores, but
6552     // just stores. In the absence of loads, there is nothing to gang up.
6553     if ((GluedLdStLimit <= 1) || !EnableMemCpyDAGOpt) {
6554       // If target does not care, just leave as it.
6555       for (unsigned i = 0; i < NumLdStInMemcpy; ++i) {
6556         OutChains.push_back(OutLoadChains[i]);
6557         OutChains.push_back(OutStoreChains[i]);
6558       }
6559     } else {
6560       // Ld/St less than/equal limit set by target.
6561       if (NumLdStInMemcpy <= GluedLdStLimit) {
6562           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
6563                                         NumLdStInMemcpy, OutLoadChains,
6564                                         OutStoreChains);
6565       } else {
6566         unsigned NumberLdChain =  NumLdStInMemcpy / GluedLdStLimit;
6567         unsigned RemainingLdStInMemcpy = NumLdStInMemcpy % GluedLdStLimit;
6568         unsigned GlueIter = 0;
6569 
6570         for (unsigned cnt = 0; cnt < NumberLdChain; ++cnt) {
6571           unsigned IndexFrom = NumLdStInMemcpy - GlueIter - GluedLdStLimit;
6572           unsigned IndexTo   = NumLdStInMemcpy - GlueIter;
6573 
6574           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, IndexFrom, IndexTo,
6575                                        OutLoadChains, OutStoreChains);
6576           GlueIter += GluedLdStLimit;
6577         }
6578 
6579         // Residual ld/st.
6580         if (RemainingLdStInMemcpy) {
6581           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
6582                                         RemainingLdStInMemcpy, OutLoadChains,
6583                                         OutStoreChains);
6584         }
6585       }
6586     }
6587   }
6588   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
6589 }
6590 
6591 static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
6592                                         SDValue Chain, SDValue Dst, SDValue Src,
6593                                         uint64_t Size, Align Alignment,
6594                                         bool isVol, bool AlwaysInline,
6595                                         MachinePointerInfo DstPtrInfo,
6596                                         MachinePointerInfo SrcPtrInfo,
6597                                         const AAMDNodes &AAInfo) {
6598   // Turn a memmove of undef to nop.
6599   // FIXME: We need to honor volatile even is Src is undef.
6600   if (Src.isUndef())
6601     return Chain;
6602 
6603   // Expand memmove to a series of load and store ops if the size operand falls
6604   // below a certain threshold.
6605   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6606   const DataLayout &DL = DAG.getDataLayout();
6607   LLVMContext &C = *DAG.getContext();
6608   std::vector<EVT> MemOps;
6609   bool DstAlignCanChange = false;
6610   MachineFunction &MF = DAG.getMachineFunction();
6611   MachineFrameInfo &MFI = MF.getFrameInfo();
6612   bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
6613   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
6614   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
6615     DstAlignCanChange = true;
6616   MaybeAlign SrcAlign = DAG.InferPtrAlign(Src);
6617   if (!SrcAlign || Alignment > *SrcAlign)
6618     SrcAlign = Alignment;
6619   assert(SrcAlign && "SrcAlign must be set");
6620   unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize);
6621   if (!TLI.findOptimalMemOpLowering(
6622           MemOps, Limit,
6623           MemOp::Copy(Size, DstAlignCanChange, Alignment, *SrcAlign,
6624                       /*IsVolatile*/ true),
6625           DstPtrInfo.getAddrSpace(), SrcPtrInfo.getAddrSpace(),
6626           MF.getFunction().getAttributes()))
6627     return SDValue();
6628 
6629   if (DstAlignCanChange) {
6630     Type *Ty = MemOps[0].getTypeForEVT(C);
6631     Align NewAlign = DL.getABITypeAlign(Ty);
6632     if (NewAlign > Alignment) {
6633       // Give the stack frame object a larger alignment if needed.
6634       if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
6635         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
6636       Alignment = NewAlign;
6637     }
6638   }
6639 
6640   // Prepare AAInfo for loads/stores after lowering this memmove.
6641   AAMDNodes NewAAInfo = AAInfo;
6642   NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
6643 
6644   MachineMemOperand::Flags MMOFlags =
6645       isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
6646   uint64_t SrcOff = 0, DstOff = 0;
6647   SmallVector<SDValue, 8> LoadValues;
6648   SmallVector<SDValue, 8> LoadChains;
6649   SmallVector<SDValue, 8> OutChains;
6650   unsigned NumMemOps = MemOps.size();
6651   for (unsigned i = 0; i < NumMemOps; i++) {
6652     EVT VT = MemOps[i];
6653     unsigned VTSize = VT.getSizeInBits() / 8;
6654     SDValue Value;
6655 
6656     bool isDereferenceable =
6657       SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
6658     MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
6659     if (isDereferenceable)
6660       SrcMMOFlags |= MachineMemOperand::MODereferenceable;
6661 
6662     Value = DAG.getLoad(
6663         VT, dl, Chain,
6664         DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl),
6665         SrcPtrInfo.getWithOffset(SrcOff), *SrcAlign, SrcMMOFlags, NewAAInfo);
6666     LoadValues.push_back(Value);
6667     LoadChains.push_back(Value.getValue(1));
6668     SrcOff += VTSize;
6669   }
6670   Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
6671   OutChains.clear();
6672   for (unsigned i = 0; i < NumMemOps; i++) {
6673     EVT VT = MemOps[i];
6674     unsigned VTSize = VT.getSizeInBits() / 8;
6675     SDValue Store;
6676 
6677     Store = DAG.getStore(
6678         Chain, dl, LoadValues[i],
6679         DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6680         DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo);
6681     OutChains.push_back(Store);
6682     DstOff += VTSize;
6683   }
6684 
6685   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
6686 }
6687 
6688 /// Lower the call to 'memset' intrinsic function into a series of store
6689 /// operations.
6690 ///
6691 /// \param DAG Selection DAG where lowered code is placed.
6692 /// \param dl Link to corresponding IR location.
6693 /// \param Chain Control flow dependency.
6694 /// \param Dst Pointer to destination memory location.
6695 /// \param Src Value of byte to write into the memory.
6696 /// \param Size Number of bytes to write.
6697 /// \param Alignment Alignment of the destination in bytes.
6698 /// \param isVol True if destination is volatile.
6699 /// \param DstPtrInfo IR information on the memory pointer.
6700 /// \returns New head in the control flow, if lowering was successful, empty
6701 /// SDValue otherwise.
6702 ///
6703 /// The function tries to replace 'llvm.memset' intrinsic with several store
6704 /// operations and value calculation code. This is usually profitable for small
6705 /// memory size.
6706 static SDValue getMemsetStores(SelectionDAG &DAG, const SDLoc &dl,
6707                                SDValue Chain, SDValue Dst, SDValue Src,
6708                                uint64_t Size, Align Alignment, bool isVol,
6709                                MachinePointerInfo DstPtrInfo,
6710                                const AAMDNodes &AAInfo) {
6711   // Turn a memset of undef to nop.
6712   // FIXME: We need to honor volatile even is Src is undef.
6713   if (Src.isUndef())
6714     return Chain;
6715 
6716   // Expand memset to a series of load/store ops if the size operand
6717   // falls below a certain threshold.
6718   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6719   std::vector<EVT> MemOps;
6720   bool DstAlignCanChange = false;
6721   MachineFunction &MF = DAG.getMachineFunction();
6722   MachineFrameInfo &MFI = MF.getFrameInfo();
6723   bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
6724   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
6725   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
6726     DstAlignCanChange = true;
6727   bool IsZeroVal =
6728       isa<ConstantSDNode>(Src) && cast<ConstantSDNode>(Src)->isZero();
6729   if (!TLI.findOptimalMemOpLowering(
6730           MemOps, TLI.getMaxStoresPerMemset(OptSize),
6731           MemOp::Set(Size, DstAlignCanChange, Alignment, IsZeroVal, isVol),
6732           DstPtrInfo.getAddrSpace(), ~0u, MF.getFunction().getAttributes()))
6733     return SDValue();
6734 
6735   if (DstAlignCanChange) {
6736     Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
6737     Align NewAlign = DAG.getDataLayout().getABITypeAlign(Ty);
6738     if (NewAlign > Alignment) {
6739       // Give the stack frame object a larger alignment if needed.
6740       if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
6741         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
6742       Alignment = NewAlign;
6743     }
6744   }
6745 
6746   SmallVector<SDValue, 8> OutChains;
6747   uint64_t DstOff = 0;
6748   unsigned NumMemOps = MemOps.size();
6749 
6750   // Find the largest store and generate the bit pattern for it.
6751   EVT LargestVT = MemOps[0];
6752   for (unsigned i = 1; i < NumMemOps; i++)
6753     if (MemOps[i].bitsGT(LargestVT))
6754       LargestVT = MemOps[i];
6755   SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl);
6756 
6757   // Prepare AAInfo for loads/stores after lowering this memset.
6758   AAMDNodes NewAAInfo = AAInfo;
6759   NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
6760 
6761   for (unsigned i = 0; i < NumMemOps; i++) {
6762     EVT VT = MemOps[i];
6763     unsigned VTSize = VT.getSizeInBits() / 8;
6764     if (VTSize > Size) {
6765       // Issuing an unaligned load / store pair  that overlaps with the previous
6766       // pair. Adjust the offset accordingly.
6767       assert(i == NumMemOps-1 && i != 0);
6768       DstOff -= VTSize - Size;
6769     }
6770 
6771     // If this store is smaller than the largest store see whether we can get
6772     // the smaller value for free with a truncate.
6773     SDValue Value = MemSetValue;
6774     if (VT.bitsLT(LargestVT)) {
6775       if (!LargestVT.isVector() && !VT.isVector() &&
6776           TLI.isTruncateFree(LargestVT, VT))
6777         Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue);
6778       else
6779         Value = getMemsetValue(Src, VT, DAG, dl);
6780     }
6781     assert(Value.getValueType() == VT && "Value with wrong type.");
6782     SDValue Store = DAG.getStore(
6783         Chain, dl, Value,
6784         DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6785         DstPtrInfo.getWithOffset(DstOff), Alignment,
6786         isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone,
6787         NewAAInfo);
6788     OutChains.push_back(Store);
6789     DstOff += VT.getSizeInBits() / 8;
6790     Size -= VTSize;
6791   }
6792 
6793   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
6794 }
6795 
6796 static void checkAddrSpaceIsValidForLibcall(const TargetLowering *TLI,
6797                                             unsigned AS) {
6798   // Lowering memcpy / memset / memmove intrinsics to calls is only valid if all
6799   // pointer operands can be losslessly bitcasted to pointers of address space 0
6800   if (AS != 0 && !TLI->getTargetMachine().isNoopAddrSpaceCast(AS, 0)) {
6801     report_fatal_error("cannot lower memory intrinsic in address space " +
6802                        Twine(AS));
6803   }
6804 }
6805 
6806 SDValue SelectionDAG::getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst,
6807                                 SDValue Src, SDValue Size, Align Alignment,
6808                                 bool isVol, bool AlwaysInline, bool isTailCall,
6809                                 MachinePointerInfo DstPtrInfo,
6810                                 MachinePointerInfo SrcPtrInfo,
6811                                 const AAMDNodes &AAInfo) {
6812   // Check to see if we should lower the memcpy to loads and stores first.
6813   // For cases within the target-specified limits, this is the best choice.
6814   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6815   if (ConstantSize) {
6816     // Memcpy with size zero? Just return the original chain.
6817     if (ConstantSize->isZero())
6818       return Chain;
6819 
6820     SDValue Result = getMemcpyLoadsAndStores(
6821         *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment,
6822         isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo);
6823     if (Result.getNode())
6824       return Result;
6825   }
6826 
6827   // Then check to see if we should lower the memcpy with target-specific
6828   // code. If the target chooses to do this, this is the next best.
6829   if (TSI) {
6830     SDValue Result = TSI->EmitTargetCodeForMemcpy(
6831         *this, dl, Chain, Dst, Src, Size, Alignment, isVol, AlwaysInline,
6832         DstPtrInfo, SrcPtrInfo);
6833     if (Result.getNode())
6834       return Result;
6835   }
6836 
6837   // If we really need inline code and the target declined to provide it,
6838   // use a (potentially long) sequence of loads and stores.
6839   if (AlwaysInline) {
6840     assert(ConstantSize && "AlwaysInline requires a constant size!");
6841     return getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
6842                                    ConstantSize->getZExtValue(), Alignment,
6843                                    isVol, true, DstPtrInfo, SrcPtrInfo, AAInfo);
6844   }
6845 
6846   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
6847   checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
6848 
6849   // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc
6850   // memcpy is not guaranteed to be safe. libc memcpys aren't required to
6851   // respect volatile, so they may do things like read or write memory
6852   // beyond the given memory regions. But fixing this isn't easy, and most
6853   // people don't care.
6854 
6855   // Emit a library call.
6856   TargetLowering::ArgListTy Args;
6857   TargetLowering::ArgListEntry Entry;
6858   Entry.Ty = Type::getInt8PtrTy(*getContext());
6859   Entry.Node = Dst; Args.push_back(Entry);
6860   Entry.Node = Src; Args.push_back(Entry);
6861 
6862   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6863   Entry.Node = Size; Args.push_back(Entry);
6864   // FIXME: pass in SDLoc
6865   TargetLowering::CallLoweringInfo CLI(*this);
6866   CLI.setDebugLoc(dl)
6867       .setChain(Chain)
6868       .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMCPY),
6869                     Dst.getValueType().getTypeForEVT(*getContext()),
6870                     getExternalSymbol(TLI->getLibcallName(RTLIB::MEMCPY),
6871                                       TLI->getPointerTy(getDataLayout())),
6872                     std::move(Args))
6873       .setDiscardResult()
6874       .setTailCall(isTailCall);
6875 
6876   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
6877   return CallResult.second;
6878 }
6879 
6880 SDValue SelectionDAG::getAtomicMemcpy(SDValue Chain, const SDLoc &dl,
6881                                       SDValue Dst, unsigned DstAlign,
6882                                       SDValue Src, unsigned SrcAlign,
6883                                       SDValue Size, Type *SizeTy,
6884                                       unsigned ElemSz, bool isTailCall,
6885                                       MachinePointerInfo DstPtrInfo,
6886                                       MachinePointerInfo SrcPtrInfo) {
6887   // Emit a library call.
6888   TargetLowering::ArgListTy Args;
6889   TargetLowering::ArgListEntry Entry;
6890   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6891   Entry.Node = Dst;
6892   Args.push_back(Entry);
6893 
6894   Entry.Node = Src;
6895   Args.push_back(Entry);
6896 
6897   Entry.Ty = SizeTy;
6898   Entry.Node = Size;
6899   Args.push_back(Entry);
6900 
6901   RTLIB::Libcall LibraryCall =
6902       RTLIB::getMEMCPY_ELEMENT_UNORDERED_ATOMIC(ElemSz);
6903   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
6904     report_fatal_error("Unsupported element size");
6905 
6906   TargetLowering::CallLoweringInfo CLI(*this);
6907   CLI.setDebugLoc(dl)
6908       .setChain(Chain)
6909       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
6910                     Type::getVoidTy(*getContext()),
6911                     getExternalSymbol(TLI->getLibcallName(LibraryCall),
6912                                       TLI->getPointerTy(getDataLayout())),
6913                     std::move(Args))
6914       .setDiscardResult()
6915       .setTailCall(isTailCall);
6916 
6917   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
6918   return CallResult.second;
6919 }
6920 
6921 SDValue SelectionDAG::getMemmove(SDValue Chain, const SDLoc &dl, SDValue Dst,
6922                                  SDValue Src, SDValue Size, Align Alignment,
6923                                  bool isVol, bool isTailCall,
6924                                  MachinePointerInfo DstPtrInfo,
6925                                  MachinePointerInfo SrcPtrInfo,
6926                                  const AAMDNodes &AAInfo) {
6927   // Check to see if we should lower the memmove to loads and stores first.
6928   // For cases within the target-specified limits, this is the best choice.
6929   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6930   if (ConstantSize) {
6931     // Memmove with size zero? Just return the original chain.
6932     if (ConstantSize->isZero())
6933       return Chain;
6934 
6935     SDValue Result = getMemmoveLoadsAndStores(
6936         *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment,
6937         isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo);
6938     if (Result.getNode())
6939       return Result;
6940   }
6941 
6942   // Then check to see if we should lower the memmove with target-specific
6943   // code. If the target chooses to do this, this is the next best.
6944   if (TSI) {
6945     SDValue Result =
6946         TSI->EmitTargetCodeForMemmove(*this, dl, Chain, Dst, Src, Size,
6947                                       Alignment, isVol, DstPtrInfo, SrcPtrInfo);
6948     if (Result.getNode())
6949       return Result;
6950   }
6951 
6952   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
6953   checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
6954 
6955   // FIXME: If the memmove is volatile, lowering it to plain libc memmove may
6956   // not be safe.  See memcpy above for more details.
6957 
6958   // Emit a library call.
6959   TargetLowering::ArgListTy Args;
6960   TargetLowering::ArgListEntry Entry;
6961   Entry.Ty = Type::getInt8PtrTy(*getContext());
6962   Entry.Node = Dst; Args.push_back(Entry);
6963   Entry.Node = Src; Args.push_back(Entry);
6964 
6965   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6966   Entry.Node = Size; Args.push_back(Entry);
6967   // FIXME:  pass in SDLoc
6968   TargetLowering::CallLoweringInfo CLI(*this);
6969   CLI.setDebugLoc(dl)
6970       .setChain(Chain)
6971       .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMMOVE),
6972                     Dst.getValueType().getTypeForEVT(*getContext()),
6973                     getExternalSymbol(TLI->getLibcallName(RTLIB::MEMMOVE),
6974                                       TLI->getPointerTy(getDataLayout())),
6975                     std::move(Args))
6976       .setDiscardResult()
6977       .setTailCall(isTailCall);
6978 
6979   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
6980   return CallResult.second;
6981 }
6982 
6983 SDValue SelectionDAG::getAtomicMemmove(SDValue Chain, const SDLoc &dl,
6984                                        SDValue Dst, unsigned DstAlign,
6985                                        SDValue Src, unsigned SrcAlign,
6986                                        SDValue Size, Type *SizeTy,
6987                                        unsigned ElemSz, bool isTailCall,
6988                                        MachinePointerInfo DstPtrInfo,
6989                                        MachinePointerInfo SrcPtrInfo) {
6990   // Emit a library call.
6991   TargetLowering::ArgListTy Args;
6992   TargetLowering::ArgListEntry Entry;
6993   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6994   Entry.Node = Dst;
6995   Args.push_back(Entry);
6996 
6997   Entry.Node = Src;
6998   Args.push_back(Entry);
6999 
7000   Entry.Ty = SizeTy;
7001   Entry.Node = Size;
7002   Args.push_back(Entry);
7003 
7004   RTLIB::Libcall LibraryCall =
7005       RTLIB::getMEMMOVE_ELEMENT_UNORDERED_ATOMIC(ElemSz);
7006   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
7007     report_fatal_error("Unsupported element size");
7008 
7009   TargetLowering::CallLoweringInfo CLI(*this);
7010   CLI.setDebugLoc(dl)
7011       .setChain(Chain)
7012       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
7013                     Type::getVoidTy(*getContext()),
7014                     getExternalSymbol(TLI->getLibcallName(LibraryCall),
7015                                       TLI->getPointerTy(getDataLayout())),
7016                     std::move(Args))
7017       .setDiscardResult()
7018       .setTailCall(isTailCall);
7019 
7020   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
7021   return CallResult.second;
7022 }
7023 
7024 SDValue SelectionDAG::getMemset(SDValue Chain, const SDLoc &dl, SDValue Dst,
7025                                 SDValue Src, SDValue Size, Align Alignment,
7026                                 bool isVol, bool isTailCall,
7027                                 MachinePointerInfo DstPtrInfo,
7028                                 const AAMDNodes &AAInfo) {
7029   // Check to see if we should lower the memset to stores first.
7030   // For cases within the target-specified limits, this is the best choice.
7031   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
7032   if (ConstantSize) {
7033     // Memset with size zero? Just return the original chain.
7034     if (ConstantSize->isZero())
7035       return Chain;
7036 
7037     SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src,
7038                                      ConstantSize->getZExtValue(), Alignment,
7039                                      isVol, DstPtrInfo, AAInfo);
7040 
7041     if (Result.getNode())
7042       return Result;
7043   }
7044 
7045   // Then check to see if we should lower the memset with target-specific
7046   // code. If the target chooses to do this, this is the next best.
7047   if (TSI) {
7048     SDValue Result = TSI->EmitTargetCodeForMemset(
7049         *this, dl, Chain, Dst, Src, Size, Alignment, isVol, DstPtrInfo);
7050     if (Result.getNode())
7051       return Result;
7052   }
7053 
7054   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
7055 
7056   // Emit a library call.
7057   TargetLowering::ArgListTy Args;
7058   TargetLowering::ArgListEntry Entry;
7059   Entry.Node = Dst; Entry.Ty = Type::getInt8PtrTy(*getContext());
7060   Args.push_back(Entry);
7061   Entry.Node = Src;
7062   Entry.Ty = Src.getValueType().getTypeForEVT(*getContext());
7063   Args.push_back(Entry);
7064   Entry.Node = Size;
7065   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7066   Args.push_back(Entry);
7067 
7068   // FIXME: pass in SDLoc
7069   TargetLowering::CallLoweringInfo CLI(*this);
7070   CLI.setDebugLoc(dl)
7071       .setChain(Chain)
7072       .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMSET),
7073                     Dst.getValueType().getTypeForEVT(*getContext()),
7074                     getExternalSymbol(TLI->getLibcallName(RTLIB::MEMSET),
7075                                       TLI->getPointerTy(getDataLayout())),
7076                     std::move(Args))
7077       .setDiscardResult()
7078       .setTailCall(isTailCall);
7079 
7080   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
7081   return CallResult.second;
7082 }
7083 
7084 SDValue SelectionDAG::getAtomicMemset(SDValue Chain, const SDLoc &dl,
7085                                       SDValue Dst, unsigned DstAlign,
7086                                       SDValue Value, SDValue Size, Type *SizeTy,
7087                                       unsigned ElemSz, bool isTailCall,
7088                                       MachinePointerInfo DstPtrInfo) {
7089   // Emit a library call.
7090   TargetLowering::ArgListTy Args;
7091   TargetLowering::ArgListEntry Entry;
7092   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7093   Entry.Node = Dst;
7094   Args.push_back(Entry);
7095 
7096   Entry.Ty = Type::getInt8Ty(*getContext());
7097   Entry.Node = Value;
7098   Args.push_back(Entry);
7099 
7100   Entry.Ty = SizeTy;
7101   Entry.Node = Size;
7102   Args.push_back(Entry);
7103 
7104   RTLIB::Libcall LibraryCall =
7105       RTLIB::getMEMSET_ELEMENT_UNORDERED_ATOMIC(ElemSz);
7106   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
7107     report_fatal_error("Unsupported element size");
7108 
7109   TargetLowering::CallLoweringInfo CLI(*this);
7110   CLI.setDebugLoc(dl)
7111       .setChain(Chain)
7112       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
7113                     Type::getVoidTy(*getContext()),
7114                     getExternalSymbol(TLI->getLibcallName(LibraryCall),
7115                                       TLI->getPointerTy(getDataLayout())),
7116                     std::move(Args))
7117       .setDiscardResult()
7118       .setTailCall(isTailCall);
7119 
7120   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
7121   return CallResult.second;
7122 }
7123 
7124 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
7125                                 SDVTList VTList, ArrayRef<SDValue> Ops,
7126                                 MachineMemOperand *MMO) {
7127   FoldingSetNodeID ID;
7128   ID.AddInteger(MemVT.getRawBits());
7129   AddNodeIDNode(ID, Opcode, VTList, Ops);
7130   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7131   void* IP = nullptr;
7132   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7133     cast<AtomicSDNode>(E)->refineAlignment(MMO);
7134     return SDValue(E, 0);
7135   }
7136 
7137   auto *N = newSDNode<AtomicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
7138                                     VTList, MemVT, MMO);
7139   createOperands(N, Ops);
7140 
7141   CSEMap.InsertNode(N, IP);
7142   InsertNode(N);
7143   return SDValue(N, 0);
7144 }
7145 
7146 SDValue SelectionDAG::getAtomicCmpSwap(unsigned Opcode, const SDLoc &dl,
7147                                        EVT MemVT, SDVTList VTs, SDValue Chain,
7148                                        SDValue Ptr, SDValue Cmp, SDValue Swp,
7149                                        MachineMemOperand *MMO) {
7150   assert(Opcode == ISD::ATOMIC_CMP_SWAP ||
7151          Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
7152   assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
7153 
7154   SDValue Ops[] = {Chain, Ptr, Cmp, Swp};
7155   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
7156 }
7157 
7158 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
7159                                 SDValue Chain, SDValue Ptr, SDValue Val,
7160                                 MachineMemOperand *MMO) {
7161   assert((Opcode == ISD::ATOMIC_LOAD_ADD ||
7162           Opcode == ISD::ATOMIC_LOAD_SUB ||
7163           Opcode == ISD::ATOMIC_LOAD_AND ||
7164           Opcode == ISD::ATOMIC_LOAD_CLR ||
7165           Opcode == ISD::ATOMIC_LOAD_OR ||
7166           Opcode == ISD::ATOMIC_LOAD_XOR ||
7167           Opcode == ISD::ATOMIC_LOAD_NAND ||
7168           Opcode == ISD::ATOMIC_LOAD_MIN ||
7169           Opcode == ISD::ATOMIC_LOAD_MAX ||
7170           Opcode == ISD::ATOMIC_LOAD_UMIN ||
7171           Opcode == ISD::ATOMIC_LOAD_UMAX ||
7172           Opcode == ISD::ATOMIC_LOAD_FADD ||
7173           Opcode == ISD::ATOMIC_LOAD_FSUB ||
7174           Opcode == ISD::ATOMIC_SWAP ||
7175           Opcode == ISD::ATOMIC_STORE) &&
7176          "Invalid Atomic Op");
7177 
7178   EVT VT = Val.getValueType();
7179 
7180   SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) :
7181                                                getVTList(VT, MVT::Other);
7182   SDValue Ops[] = {Chain, Ptr, Val};
7183   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
7184 }
7185 
7186 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
7187                                 EVT VT, SDValue Chain, SDValue Ptr,
7188                                 MachineMemOperand *MMO) {
7189   assert(Opcode == ISD::ATOMIC_LOAD && "Invalid Atomic Op");
7190 
7191   SDVTList VTs = getVTList(VT, MVT::Other);
7192   SDValue Ops[] = {Chain, Ptr};
7193   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
7194 }
7195 
7196 /// getMergeValues - Create a MERGE_VALUES node from the given operands.
7197 SDValue SelectionDAG::getMergeValues(ArrayRef<SDValue> Ops, const SDLoc &dl) {
7198   if (Ops.size() == 1)
7199     return Ops[0];
7200 
7201   SmallVector<EVT, 4> VTs;
7202   VTs.reserve(Ops.size());
7203   for (const SDValue &Op : Ops)
7204     VTs.push_back(Op.getValueType());
7205   return getNode(ISD::MERGE_VALUES, dl, getVTList(VTs), Ops);
7206 }
7207 
7208 SDValue SelectionDAG::getMemIntrinsicNode(
7209     unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef<SDValue> Ops,
7210     EVT MemVT, MachinePointerInfo PtrInfo, Align Alignment,
7211     MachineMemOperand::Flags Flags, uint64_t Size, const AAMDNodes &AAInfo) {
7212   if (!Size && MemVT.isScalableVector())
7213     Size = MemoryLocation::UnknownSize;
7214   else if (!Size)
7215     Size = MemVT.getStoreSize();
7216 
7217   MachineFunction &MF = getMachineFunction();
7218   MachineMemOperand *MMO =
7219       MF.getMachineMemOperand(PtrInfo, Flags, Size, Alignment, AAInfo);
7220 
7221   return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, MMO);
7222 }
7223 
7224 SDValue SelectionDAG::getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl,
7225                                           SDVTList VTList,
7226                                           ArrayRef<SDValue> Ops, EVT MemVT,
7227                                           MachineMemOperand *MMO) {
7228   assert((Opcode == ISD::INTRINSIC_VOID ||
7229           Opcode == ISD::INTRINSIC_W_CHAIN ||
7230           Opcode == ISD::PREFETCH ||
7231           ((int)Opcode <= std::numeric_limits<int>::max() &&
7232            (int)Opcode >= ISD::FIRST_TARGET_MEMORY_OPCODE)) &&
7233          "Opcode is not a memory-accessing opcode!");
7234 
7235   // Memoize the node unless it returns a flag.
7236   MemIntrinsicSDNode *N;
7237   if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
7238     FoldingSetNodeID ID;
7239     AddNodeIDNode(ID, Opcode, VTList, Ops);
7240     ID.AddInteger(getSyntheticNodeSubclassData<MemIntrinsicSDNode>(
7241         Opcode, dl.getIROrder(), VTList, MemVT, MMO));
7242     ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7243     void *IP = nullptr;
7244     if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7245       cast<MemIntrinsicSDNode>(E)->refineAlignment(MMO);
7246       return SDValue(E, 0);
7247     }
7248 
7249     N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
7250                                       VTList, MemVT, MMO);
7251     createOperands(N, Ops);
7252 
7253   CSEMap.InsertNode(N, IP);
7254   } else {
7255     N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
7256                                       VTList, MemVT, MMO);
7257     createOperands(N, Ops);
7258   }
7259   InsertNode(N);
7260   SDValue V(N, 0);
7261   NewSDValueDbgMsg(V, "Creating new node: ", this);
7262   return V;
7263 }
7264 
7265 SDValue SelectionDAG::getLifetimeNode(bool IsStart, const SDLoc &dl,
7266                                       SDValue Chain, int FrameIndex,
7267                                       int64_t Size, int64_t Offset) {
7268   const unsigned Opcode = IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END;
7269   const auto VTs = getVTList(MVT::Other);
7270   SDValue Ops[2] = {
7271       Chain,
7272       getFrameIndex(FrameIndex,
7273                     getTargetLoweringInfo().getFrameIndexTy(getDataLayout()),
7274                     true)};
7275 
7276   FoldingSetNodeID ID;
7277   AddNodeIDNode(ID, Opcode, VTs, Ops);
7278   ID.AddInteger(FrameIndex);
7279   ID.AddInteger(Size);
7280   ID.AddInteger(Offset);
7281   void *IP = nullptr;
7282   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
7283     return SDValue(E, 0);
7284 
7285   LifetimeSDNode *N = newSDNode<LifetimeSDNode>(
7286       Opcode, dl.getIROrder(), dl.getDebugLoc(), VTs, Size, Offset);
7287   createOperands(N, Ops);
7288   CSEMap.InsertNode(N, IP);
7289   InsertNode(N);
7290   SDValue V(N, 0);
7291   NewSDValueDbgMsg(V, "Creating new node: ", this);
7292   return V;
7293 }
7294 
7295 SDValue SelectionDAG::getPseudoProbeNode(const SDLoc &Dl, SDValue Chain,
7296                                          uint64_t Guid, uint64_t Index,
7297                                          uint32_t Attr) {
7298   const unsigned Opcode = ISD::PSEUDO_PROBE;
7299   const auto VTs = getVTList(MVT::Other);
7300   SDValue Ops[] = {Chain};
7301   FoldingSetNodeID ID;
7302   AddNodeIDNode(ID, Opcode, VTs, Ops);
7303   ID.AddInteger(Guid);
7304   ID.AddInteger(Index);
7305   void *IP = nullptr;
7306   if (SDNode *E = FindNodeOrInsertPos(ID, Dl, IP))
7307     return SDValue(E, 0);
7308 
7309   auto *N = newSDNode<PseudoProbeSDNode>(
7310       Opcode, Dl.getIROrder(), Dl.getDebugLoc(), VTs, Guid, Index, Attr);
7311   createOperands(N, Ops);
7312   CSEMap.InsertNode(N, IP);
7313   InsertNode(N);
7314   SDValue V(N, 0);
7315   NewSDValueDbgMsg(V, "Creating new node: ", this);
7316   return V;
7317 }
7318 
7319 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
7320 /// MachinePointerInfo record from it.  This is particularly useful because the
7321 /// code generator has many cases where it doesn't bother passing in a
7322 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
7323 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info,
7324                                            SelectionDAG &DAG, SDValue Ptr,
7325                                            int64_t Offset = 0) {
7326   // If this is FI+Offset, we can model it.
7327   if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr))
7328     return MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
7329                                              FI->getIndex(), Offset);
7330 
7331   // If this is (FI+Offset1)+Offset2, we can model it.
7332   if (Ptr.getOpcode() != ISD::ADD ||
7333       !isa<ConstantSDNode>(Ptr.getOperand(1)) ||
7334       !isa<FrameIndexSDNode>(Ptr.getOperand(0)))
7335     return Info;
7336 
7337   int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
7338   return MachinePointerInfo::getFixedStack(
7339       DAG.getMachineFunction(), FI,
7340       Offset + cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue());
7341 }
7342 
7343 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
7344 /// MachinePointerInfo record from it.  This is particularly useful because the
7345 /// code generator has many cases where it doesn't bother passing in a
7346 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
7347 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info,
7348                                            SelectionDAG &DAG, SDValue Ptr,
7349                                            SDValue OffsetOp) {
7350   // If the 'Offset' value isn't a constant, we can't handle this.
7351   if (ConstantSDNode *OffsetNode = dyn_cast<ConstantSDNode>(OffsetOp))
7352     return InferPointerInfo(Info, DAG, Ptr, OffsetNode->getSExtValue());
7353   if (OffsetOp.isUndef())
7354     return InferPointerInfo(Info, DAG, Ptr);
7355   return Info;
7356 }
7357 
7358 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
7359                               EVT VT, const SDLoc &dl, SDValue Chain,
7360                               SDValue Ptr, SDValue Offset,
7361                               MachinePointerInfo PtrInfo, EVT MemVT,
7362                               Align Alignment,
7363                               MachineMemOperand::Flags MMOFlags,
7364                               const AAMDNodes &AAInfo, const MDNode *Ranges) {
7365   assert(Chain.getValueType() == MVT::Other &&
7366         "Invalid chain type");
7367 
7368   MMOFlags |= MachineMemOperand::MOLoad;
7369   assert((MMOFlags & MachineMemOperand::MOStore) == 0);
7370   // If we don't have a PtrInfo, infer the trivial frame index case to simplify
7371   // clients.
7372   if (PtrInfo.V.isNull())
7373     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
7374 
7375   uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize());
7376   MachineFunction &MF = getMachineFunction();
7377   MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size,
7378                                                    Alignment, AAInfo, Ranges);
7379   return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO);
7380 }
7381 
7382 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
7383                               EVT VT, const SDLoc &dl, SDValue Chain,
7384                               SDValue Ptr, SDValue Offset, EVT MemVT,
7385                               MachineMemOperand *MMO) {
7386   if (VT == MemVT) {
7387     ExtType = ISD::NON_EXTLOAD;
7388   } else if (ExtType == ISD::NON_EXTLOAD) {
7389     assert(VT == MemVT && "Non-extending load from different memory type!");
7390   } else {
7391     // Extending load.
7392     assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) &&
7393            "Should only be an extending load, not truncating!");
7394     assert(VT.isInteger() == MemVT.isInteger() &&
7395            "Cannot convert from FP to Int or Int -> FP!");
7396     assert(VT.isVector() == MemVT.isVector() &&
7397            "Cannot use an ext load to convert to or from a vector!");
7398     assert((!VT.isVector() ||
7399             VT.getVectorElementCount() == MemVT.getVectorElementCount()) &&
7400            "Cannot use an ext load to change the number of vector elements!");
7401   }
7402 
7403   bool Indexed = AM != ISD::UNINDEXED;
7404   assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
7405 
7406   SDVTList VTs = Indexed ?
7407     getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
7408   SDValue Ops[] = { Chain, Ptr, Offset };
7409   FoldingSetNodeID ID;
7410   AddNodeIDNode(ID, ISD::LOAD, VTs, Ops);
7411   ID.AddInteger(MemVT.getRawBits());
7412   ID.AddInteger(getSyntheticNodeSubclassData<LoadSDNode>(
7413       dl.getIROrder(), VTs, AM, ExtType, MemVT, MMO));
7414   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7415   void *IP = nullptr;
7416   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7417     cast<LoadSDNode>(E)->refineAlignment(MMO);
7418     return SDValue(E, 0);
7419   }
7420   auto *N = newSDNode<LoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
7421                                   ExtType, MemVT, MMO);
7422   createOperands(N, Ops);
7423 
7424   CSEMap.InsertNode(N, IP);
7425   InsertNode(N);
7426   SDValue V(N, 0);
7427   NewSDValueDbgMsg(V, "Creating new node: ", this);
7428   return V;
7429 }
7430 
7431 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
7432                               SDValue Ptr, MachinePointerInfo PtrInfo,
7433                               MaybeAlign Alignment,
7434                               MachineMemOperand::Flags MMOFlags,
7435                               const AAMDNodes &AAInfo, const MDNode *Ranges) {
7436   SDValue Undef = getUNDEF(Ptr.getValueType());
7437   return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7438                  PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges);
7439 }
7440 
7441 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
7442                               SDValue Ptr, MachineMemOperand *MMO) {
7443   SDValue Undef = getUNDEF(Ptr.getValueType());
7444   return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7445                  VT, MMO);
7446 }
7447 
7448 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
7449                                  EVT VT, SDValue Chain, SDValue Ptr,
7450                                  MachinePointerInfo PtrInfo, EVT MemVT,
7451                                  MaybeAlign Alignment,
7452                                  MachineMemOperand::Flags MMOFlags,
7453                                  const AAMDNodes &AAInfo) {
7454   SDValue Undef = getUNDEF(Ptr.getValueType());
7455   return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, PtrInfo,
7456                  MemVT, Alignment, MMOFlags, AAInfo);
7457 }
7458 
7459 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
7460                                  EVT VT, SDValue Chain, SDValue Ptr, EVT MemVT,
7461                                  MachineMemOperand *MMO) {
7462   SDValue Undef = getUNDEF(Ptr.getValueType());
7463   return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef,
7464                  MemVT, MMO);
7465 }
7466 
7467 SDValue SelectionDAG::getIndexedLoad(SDValue OrigLoad, const SDLoc &dl,
7468                                      SDValue Base, SDValue Offset,
7469                                      ISD::MemIndexedMode AM) {
7470   LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
7471   assert(LD->getOffset().isUndef() && "Load is already a indexed load!");
7472   // Don't propagate the invariant or dereferenceable flags.
7473   auto MMOFlags =
7474       LD->getMemOperand()->getFlags() &
7475       ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
7476   return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
7477                  LD->getChain(), Base, Offset, LD->getPointerInfo(),
7478                  LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo());
7479 }
7480 
7481 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7482                                SDValue Ptr, MachinePointerInfo PtrInfo,
7483                                Align Alignment,
7484                                MachineMemOperand::Flags MMOFlags,
7485                                const AAMDNodes &AAInfo) {
7486   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
7487 
7488   MMOFlags |= MachineMemOperand::MOStore;
7489   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
7490 
7491   if (PtrInfo.V.isNull())
7492     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
7493 
7494   MachineFunction &MF = getMachineFunction();
7495   uint64_t Size =
7496       MemoryLocation::getSizeOrUnknown(Val.getValueType().getStoreSize());
7497   MachineMemOperand *MMO =
7498       MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, Alignment, AAInfo);
7499   return getStore(Chain, dl, Val, Ptr, MMO);
7500 }
7501 
7502 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7503                                SDValue Ptr, MachineMemOperand *MMO) {
7504   assert(Chain.getValueType() == MVT::Other &&
7505         "Invalid chain type");
7506   EVT VT = Val.getValueType();
7507   SDVTList VTs = getVTList(MVT::Other);
7508   SDValue Undef = getUNDEF(Ptr.getValueType());
7509   SDValue Ops[] = { Chain, Val, Ptr, Undef };
7510   FoldingSetNodeID ID;
7511   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7512   ID.AddInteger(VT.getRawBits());
7513   ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
7514       dl.getIROrder(), VTs, ISD::UNINDEXED, false, VT, MMO));
7515   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7516   void *IP = nullptr;
7517   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7518     cast<StoreSDNode>(E)->refineAlignment(MMO);
7519     return SDValue(E, 0);
7520   }
7521   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7522                                    ISD::UNINDEXED, false, VT, MMO);
7523   createOperands(N, Ops);
7524 
7525   CSEMap.InsertNode(N, IP);
7526   InsertNode(N);
7527   SDValue V(N, 0);
7528   NewSDValueDbgMsg(V, "Creating new node: ", this);
7529   return V;
7530 }
7531 
7532 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7533                                     SDValue Ptr, MachinePointerInfo PtrInfo,
7534                                     EVT SVT, Align Alignment,
7535                                     MachineMemOperand::Flags MMOFlags,
7536                                     const AAMDNodes &AAInfo) {
7537   assert(Chain.getValueType() == MVT::Other &&
7538         "Invalid chain type");
7539 
7540   MMOFlags |= MachineMemOperand::MOStore;
7541   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
7542 
7543   if (PtrInfo.V.isNull())
7544     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
7545 
7546   MachineFunction &MF = getMachineFunction();
7547   MachineMemOperand *MMO = MF.getMachineMemOperand(
7548       PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()),
7549       Alignment, AAInfo);
7550   return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO);
7551 }
7552 
7553 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7554                                     SDValue Ptr, EVT SVT,
7555                                     MachineMemOperand *MMO) {
7556   EVT VT = Val.getValueType();
7557 
7558   assert(Chain.getValueType() == MVT::Other &&
7559         "Invalid chain type");
7560   if (VT == SVT)
7561     return getStore(Chain, dl, Val, Ptr, MMO);
7562 
7563   assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
7564          "Should only be a truncating store, not extending!");
7565   assert(VT.isInteger() == SVT.isInteger() &&
7566          "Can't do FP-INT conversion!");
7567   assert(VT.isVector() == SVT.isVector() &&
7568          "Cannot use trunc store to convert to or from a vector!");
7569   assert((!VT.isVector() ||
7570           VT.getVectorElementCount() == SVT.getVectorElementCount()) &&
7571          "Cannot use trunc store to change the number of vector elements!");
7572 
7573   SDVTList VTs = getVTList(MVT::Other);
7574   SDValue Undef = getUNDEF(Ptr.getValueType());
7575   SDValue Ops[] = { Chain, Val, Ptr, Undef };
7576   FoldingSetNodeID ID;
7577   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7578   ID.AddInteger(SVT.getRawBits());
7579   ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
7580       dl.getIROrder(), VTs, ISD::UNINDEXED, true, SVT, MMO));
7581   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7582   void *IP = nullptr;
7583   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7584     cast<StoreSDNode>(E)->refineAlignment(MMO);
7585     return SDValue(E, 0);
7586   }
7587   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7588                                    ISD::UNINDEXED, true, SVT, MMO);
7589   createOperands(N, Ops);
7590 
7591   CSEMap.InsertNode(N, IP);
7592   InsertNode(N);
7593   SDValue V(N, 0);
7594   NewSDValueDbgMsg(V, "Creating new node: ", this);
7595   return V;
7596 }
7597 
7598 SDValue SelectionDAG::getIndexedStore(SDValue OrigStore, const SDLoc &dl,
7599                                       SDValue Base, SDValue Offset,
7600                                       ISD::MemIndexedMode AM) {
7601   StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
7602   assert(ST->getOffset().isUndef() && "Store is already a indexed store!");
7603   SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
7604   SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
7605   FoldingSetNodeID ID;
7606   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7607   ID.AddInteger(ST->getMemoryVT().getRawBits());
7608   ID.AddInteger(ST->getRawSubclassData());
7609   ID.AddInteger(ST->getPointerInfo().getAddrSpace());
7610   void *IP = nullptr;
7611   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
7612     return SDValue(E, 0);
7613 
7614   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
7615                                    ST->isTruncatingStore(), ST->getMemoryVT(),
7616                                    ST->getMemOperand());
7617   createOperands(N, Ops);
7618 
7619   CSEMap.InsertNode(N, IP);
7620   InsertNode(N);
7621   SDValue V(N, 0);
7622   NewSDValueDbgMsg(V, "Creating new node: ", this);
7623   return V;
7624 }
7625 
7626 SDValue SelectionDAG::getLoadVP(
7627     ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &dl,
7628     SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Mask, SDValue EVL,
7629     MachinePointerInfo PtrInfo, EVT MemVT, Align Alignment,
7630     MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
7631     const MDNode *Ranges, bool IsExpanding) {
7632   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
7633 
7634   MMOFlags |= MachineMemOperand::MOLoad;
7635   assert((MMOFlags & MachineMemOperand::MOStore) == 0);
7636   // If we don't have a PtrInfo, infer the trivial frame index case to simplify
7637   // clients.
7638   if (PtrInfo.V.isNull())
7639     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
7640 
7641   uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize());
7642   MachineFunction &MF = getMachineFunction();
7643   MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size,
7644                                                    Alignment, AAInfo, Ranges);
7645   return getLoadVP(AM, ExtType, VT, dl, Chain, Ptr, Offset, Mask, EVL, MemVT,
7646                    MMO, IsExpanding);
7647 }
7648 
7649 SDValue SelectionDAG::getLoadVP(ISD::MemIndexedMode AM,
7650                                 ISD::LoadExtType ExtType, EVT VT,
7651                                 const SDLoc &dl, SDValue Chain, SDValue Ptr,
7652                                 SDValue Offset, SDValue Mask, SDValue EVL,
7653                                 EVT MemVT, MachineMemOperand *MMO,
7654                                 bool IsExpanding) {
7655   if (VT == MemVT) {
7656     ExtType = ISD::NON_EXTLOAD;
7657   } else if (ExtType == ISD::NON_EXTLOAD) {
7658     assert(VT == MemVT && "Non-extending load from different memory type!");
7659   } else {
7660     // Extending load.
7661     assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) &&
7662            "Should only be an extending load, not truncating!");
7663     assert(VT.isInteger() == MemVT.isInteger() &&
7664            "Cannot convert from FP to Int or Int -> FP!");
7665     assert(VT.isVector() == MemVT.isVector() &&
7666            "Cannot use an ext load to convert to or from a vector!");
7667     assert((!VT.isVector() ||
7668             VT.getVectorElementCount() == MemVT.getVectorElementCount()) &&
7669            "Cannot use an ext load to change the number of vector elements!");
7670   }
7671 
7672   bool Indexed = AM != ISD::UNINDEXED;
7673   assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
7674 
7675   SDVTList VTs = Indexed ? getVTList(VT, Ptr.getValueType(), MVT::Other)
7676                          : getVTList(VT, MVT::Other);
7677   SDValue Ops[] = {Chain, Ptr, Offset, Mask, EVL};
7678   FoldingSetNodeID ID;
7679   AddNodeIDNode(ID, ISD::VP_LOAD, VTs, Ops);
7680   ID.AddInteger(VT.getRawBits());
7681   ID.AddInteger(getSyntheticNodeSubclassData<VPLoadSDNode>(
7682       dl.getIROrder(), VTs, AM, ExtType, IsExpanding, MemVT, MMO));
7683   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7684   void *IP = nullptr;
7685   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7686     cast<VPLoadSDNode>(E)->refineAlignment(MMO);
7687     return SDValue(E, 0);
7688   }
7689   auto *N = newSDNode<VPLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
7690                                     ExtType, IsExpanding, MemVT, MMO);
7691   createOperands(N, Ops);
7692 
7693   CSEMap.InsertNode(N, IP);
7694   InsertNode(N);
7695   SDValue V(N, 0);
7696   NewSDValueDbgMsg(V, "Creating new node: ", this);
7697   return V;
7698 }
7699 
7700 SDValue SelectionDAG::getLoadVP(EVT VT, const SDLoc &dl, SDValue Chain,
7701                                 SDValue Ptr, SDValue Mask, SDValue EVL,
7702                                 MachinePointerInfo PtrInfo,
7703                                 MaybeAlign Alignment,
7704                                 MachineMemOperand::Flags MMOFlags,
7705                                 const AAMDNodes &AAInfo, const MDNode *Ranges,
7706                                 bool IsExpanding) {
7707   SDValue Undef = getUNDEF(Ptr.getValueType());
7708   return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7709                    Mask, EVL, PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges,
7710                    IsExpanding);
7711 }
7712 
7713 SDValue SelectionDAG::getLoadVP(EVT VT, const SDLoc &dl, SDValue Chain,
7714                                 SDValue Ptr, SDValue Mask, SDValue EVL,
7715                                 MachineMemOperand *MMO, bool IsExpanding) {
7716   SDValue Undef = getUNDEF(Ptr.getValueType());
7717   return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7718                    Mask, EVL, VT, MMO, IsExpanding);
7719 }
7720 
7721 SDValue SelectionDAG::getExtLoadVP(ISD::LoadExtType ExtType, const SDLoc &dl,
7722                                    EVT VT, SDValue Chain, SDValue Ptr,
7723                                    SDValue Mask, SDValue EVL,
7724                                    MachinePointerInfo PtrInfo, EVT MemVT,
7725                                    MaybeAlign Alignment,
7726                                    MachineMemOperand::Flags MMOFlags,
7727                                    const AAMDNodes &AAInfo, bool IsExpanding) {
7728   SDValue Undef = getUNDEF(Ptr.getValueType());
7729   return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask,
7730                    EVL, PtrInfo, MemVT, Alignment, MMOFlags, AAInfo, nullptr,
7731                    IsExpanding);
7732 }
7733 
7734 SDValue SelectionDAG::getExtLoadVP(ISD::LoadExtType ExtType, const SDLoc &dl,
7735                                    EVT VT, SDValue Chain, SDValue Ptr,
7736                                    SDValue Mask, SDValue EVL, EVT MemVT,
7737                                    MachineMemOperand *MMO, bool IsExpanding) {
7738   SDValue Undef = getUNDEF(Ptr.getValueType());
7739   return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask,
7740                    EVL, MemVT, MMO, IsExpanding);
7741 }
7742 
7743 SDValue SelectionDAG::getIndexedLoadVP(SDValue OrigLoad, const SDLoc &dl,
7744                                        SDValue Base, SDValue Offset,
7745                                        ISD::MemIndexedMode AM) {
7746   auto *LD = cast<VPLoadSDNode>(OrigLoad);
7747   assert(LD->getOffset().isUndef() && "Load is already a indexed load!");
7748   // Don't propagate the invariant or dereferenceable flags.
7749   auto MMOFlags =
7750       LD->getMemOperand()->getFlags() &
7751       ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
7752   return getLoadVP(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
7753                    LD->getChain(), Base, Offset, LD->getMask(),
7754                    LD->getVectorLength(), LD->getPointerInfo(),
7755                    LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo(),
7756                    nullptr, LD->isExpandingLoad());
7757 }
7758 
7759 SDValue SelectionDAG::getStoreVP(SDValue Chain, const SDLoc &dl, SDValue Val,
7760                                  SDValue Ptr, SDValue Mask, SDValue EVL,
7761                                  MachinePointerInfo PtrInfo, Align Alignment,
7762                                  MachineMemOperand::Flags MMOFlags,
7763                                  const AAMDNodes &AAInfo, bool IsCompressing) {
7764   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
7765 
7766   MMOFlags |= MachineMemOperand::MOStore;
7767   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
7768 
7769   if (PtrInfo.V.isNull())
7770     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
7771 
7772   MachineFunction &MF = getMachineFunction();
7773   uint64_t Size =
7774       MemoryLocation::getSizeOrUnknown(Val.getValueType().getStoreSize());
7775   MachineMemOperand *MMO =
7776       MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, Alignment, AAInfo);
7777   return getStoreVP(Chain, dl, Val, Ptr, Mask, EVL, MMO, IsCompressing);
7778 }
7779 
7780 SDValue SelectionDAG::getStoreVP(SDValue Chain, const SDLoc &dl, SDValue Val,
7781                                  SDValue Ptr, SDValue Mask, SDValue EVL,
7782                                  MachineMemOperand *MMO, bool IsCompressing) {
7783   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
7784   EVT VT = Val.getValueType();
7785   SDVTList VTs = getVTList(MVT::Other);
7786   SDValue Undef = getUNDEF(Ptr.getValueType());
7787   SDValue Ops[] = {Chain, Val, Ptr, Undef, Mask, EVL};
7788   FoldingSetNodeID ID;
7789   AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
7790   ID.AddInteger(VT.getRawBits());
7791   ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>(
7792       dl.getIROrder(), VTs, ISD::UNINDEXED, false, IsCompressing, VT, MMO));
7793   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7794   void *IP = nullptr;
7795   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7796     cast<VPStoreSDNode>(E)->refineAlignment(MMO);
7797     return SDValue(E, 0);
7798   }
7799   auto *N =
7800       newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7801                                ISD::UNINDEXED, false, IsCompressing, VT, MMO);
7802   createOperands(N, Ops);
7803 
7804   CSEMap.InsertNode(N, IP);
7805   InsertNode(N);
7806   SDValue V(N, 0);
7807   NewSDValueDbgMsg(V, "Creating new node: ", this);
7808   return V;
7809 }
7810 
7811 SDValue SelectionDAG::getTruncStoreVP(SDValue Chain, const SDLoc &dl,
7812                                       SDValue Val, SDValue Ptr, SDValue Mask,
7813                                       SDValue EVL, MachinePointerInfo PtrInfo,
7814                                       EVT SVT, Align Alignment,
7815                                       MachineMemOperand::Flags MMOFlags,
7816                                       const AAMDNodes &AAInfo,
7817                                       bool IsCompressing) {
7818   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
7819 
7820   MMOFlags |= MachineMemOperand::MOStore;
7821   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
7822 
7823   if (PtrInfo.V.isNull())
7824     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
7825 
7826   MachineFunction &MF = getMachineFunction();
7827   MachineMemOperand *MMO = MF.getMachineMemOperand(
7828       PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()),
7829       Alignment, AAInfo);
7830   return getTruncStoreVP(Chain, dl, Val, Ptr, Mask, EVL, SVT, MMO,
7831                          IsCompressing);
7832 }
7833 
7834 SDValue SelectionDAG::getTruncStoreVP(SDValue Chain, const SDLoc &dl,
7835                                       SDValue Val, SDValue Ptr, SDValue Mask,
7836                                       SDValue EVL, EVT SVT,
7837                                       MachineMemOperand *MMO,
7838                                       bool IsCompressing) {
7839   EVT VT = Val.getValueType();
7840 
7841   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
7842   if (VT == SVT)
7843     return getStoreVP(Chain, dl, Val, Ptr, Mask, EVL, MMO, IsCompressing);
7844 
7845   assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
7846          "Should only be a truncating store, not extending!");
7847   assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!");
7848   assert(VT.isVector() == SVT.isVector() &&
7849          "Cannot use trunc store to convert to or from a vector!");
7850   assert((!VT.isVector() ||
7851           VT.getVectorElementCount() == SVT.getVectorElementCount()) &&
7852          "Cannot use trunc store to change the number of vector elements!");
7853 
7854   SDVTList VTs = getVTList(MVT::Other);
7855   SDValue Undef = getUNDEF(Ptr.getValueType());
7856   SDValue Ops[] = {Chain, Val, Ptr, Undef, Mask, EVL};
7857   FoldingSetNodeID ID;
7858   AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
7859   ID.AddInteger(SVT.getRawBits());
7860   ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>(
7861       dl.getIROrder(), VTs, ISD::UNINDEXED, true, IsCompressing, SVT, MMO));
7862   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7863   void *IP = nullptr;
7864   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7865     cast<VPStoreSDNode>(E)->refineAlignment(MMO);
7866     return SDValue(E, 0);
7867   }
7868   auto *N =
7869       newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7870                                ISD::UNINDEXED, true, IsCompressing, SVT, MMO);
7871   createOperands(N, Ops);
7872 
7873   CSEMap.InsertNode(N, IP);
7874   InsertNode(N);
7875   SDValue V(N, 0);
7876   NewSDValueDbgMsg(V, "Creating new node: ", this);
7877   return V;
7878 }
7879 
7880 SDValue SelectionDAG::getIndexedStoreVP(SDValue OrigStore, const SDLoc &dl,
7881                                         SDValue Base, SDValue Offset,
7882                                         ISD::MemIndexedMode AM) {
7883   auto *ST = cast<VPStoreSDNode>(OrigStore);
7884   assert(ST->getOffset().isUndef() && "Store is already an indexed store!");
7885   SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
7886   SDValue Ops[] = {ST->getChain(), ST->getValue(), Base,
7887                    Offset,         ST->getMask(),  ST->getVectorLength()};
7888   FoldingSetNodeID ID;
7889   AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
7890   ID.AddInteger(ST->getMemoryVT().getRawBits());
7891   ID.AddInteger(ST->getRawSubclassData());
7892   ID.AddInteger(ST->getPointerInfo().getAddrSpace());
7893   void *IP = nullptr;
7894   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
7895     return SDValue(E, 0);
7896 
7897   auto *N = newSDNode<VPStoreSDNode>(
7898       dl.getIROrder(), dl.getDebugLoc(), VTs, AM, ST->isTruncatingStore(),
7899       ST->isCompressingStore(), ST->getMemoryVT(), ST->getMemOperand());
7900   createOperands(N, Ops);
7901 
7902   CSEMap.InsertNode(N, IP);
7903   InsertNode(N);
7904   SDValue V(N, 0);
7905   NewSDValueDbgMsg(V, "Creating new node: ", this);
7906   return V;
7907 }
7908 
7909 SDValue SelectionDAG::getGatherVP(SDVTList VTs, EVT VT, const SDLoc &dl,
7910                                   ArrayRef<SDValue> Ops, MachineMemOperand *MMO,
7911                                   ISD::MemIndexType IndexType) {
7912   assert(Ops.size() == 6 && "Incompatible number of operands");
7913 
7914   FoldingSetNodeID ID;
7915   AddNodeIDNode(ID, ISD::VP_GATHER, VTs, Ops);
7916   ID.AddInteger(VT.getRawBits());
7917   ID.AddInteger(getSyntheticNodeSubclassData<VPGatherSDNode>(
7918       dl.getIROrder(), VTs, VT, MMO, IndexType));
7919   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7920   void *IP = nullptr;
7921   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7922     cast<VPGatherSDNode>(E)->refineAlignment(MMO);
7923     return SDValue(E, 0);
7924   }
7925 
7926   auto *N = newSDNode<VPGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7927                                       VT, MMO, IndexType);
7928   createOperands(N, Ops);
7929 
7930   assert(N->getMask().getValueType().getVectorElementCount() ==
7931              N->getValueType(0).getVectorElementCount() &&
7932          "Vector width mismatch between mask and data");
7933   assert(N->getIndex().getValueType().getVectorElementCount().isScalable() ==
7934              N->getValueType(0).getVectorElementCount().isScalable() &&
7935          "Scalable flags of index and data do not match");
7936   assert(ElementCount::isKnownGE(
7937              N->getIndex().getValueType().getVectorElementCount(),
7938              N->getValueType(0).getVectorElementCount()) &&
7939          "Vector width mismatch between index and data");
7940   assert(isa<ConstantSDNode>(N->getScale()) &&
7941          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
7942          "Scale should be a constant power of 2");
7943 
7944   CSEMap.InsertNode(N, IP);
7945   InsertNode(N);
7946   SDValue V(N, 0);
7947   NewSDValueDbgMsg(V, "Creating new node: ", this);
7948   return V;
7949 }
7950 
7951 SDValue SelectionDAG::getScatterVP(SDVTList VTs, EVT VT, const SDLoc &dl,
7952                                    ArrayRef<SDValue> Ops,
7953                                    MachineMemOperand *MMO,
7954                                    ISD::MemIndexType IndexType) {
7955   assert(Ops.size() == 7 && "Incompatible number of operands");
7956 
7957   FoldingSetNodeID ID;
7958   AddNodeIDNode(ID, ISD::VP_SCATTER, VTs, Ops);
7959   ID.AddInteger(VT.getRawBits());
7960   ID.AddInteger(getSyntheticNodeSubclassData<VPScatterSDNode>(
7961       dl.getIROrder(), VTs, VT, MMO, IndexType));
7962   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7963   void *IP = nullptr;
7964   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7965     cast<VPScatterSDNode>(E)->refineAlignment(MMO);
7966     return SDValue(E, 0);
7967   }
7968   auto *N = newSDNode<VPScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7969                                        VT, MMO, IndexType);
7970   createOperands(N, Ops);
7971 
7972   assert(N->getMask().getValueType().getVectorElementCount() ==
7973              N->getValue().getValueType().getVectorElementCount() &&
7974          "Vector width mismatch between mask and data");
7975   assert(
7976       N->getIndex().getValueType().getVectorElementCount().isScalable() ==
7977           N->getValue().getValueType().getVectorElementCount().isScalable() &&
7978       "Scalable flags of index and data do not match");
7979   assert(ElementCount::isKnownGE(
7980              N->getIndex().getValueType().getVectorElementCount(),
7981              N->getValue().getValueType().getVectorElementCount()) &&
7982          "Vector width mismatch between index and data");
7983   assert(isa<ConstantSDNode>(N->getScale()) &&
7984          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
7985          "Scale should be a constant power of 2");
7986 
7987   CSEMap.InsertNode(N, IP);
7988   InsertNode(N);
7989   SDValue V(N, 0);
7990   NewSDValueDbgMsg(V, "Creating new node: ", this);
7991   return V;
7992 }
7993 
7994 SDValue SelectionDAG::getMaskedLoad(EVT VT, const SDLoc &dl, SDValue Chain,
7995                                     SDValue Base, SDValue Offset, SDValue Mask,
7996                                     SDValue PassThru, EVT MemVT,
7997                                     MachineMemOperand *MMO,
7998                                     ISD::MemIndexedMode AM,
7999                                     ISD::LoadExtType ExtTy, bool isExpanding) {
8000   bool Indexed = AM != ISD::UNINDEXED;
8001   assert((Indexed || Offset.isUndef()) &&
8002          "Unindexed masked load with an offset!");
8003   SDVTList VTs = Indexed ? getVTList(VT, Base.getValueType(), MVT::Other)
8004                          : getVTList(VT, MVT::Other);
8005   SDValue Ops[] = {Chain, Base, Offset, Mask, PassThru};
8006   FoldingSetNodeID ID;
8007   AddNodeIDNode(ID, ISD::MLOAD, VTs, Ops);
8008   ID.AddInteger(MemVT.getRawBits());
8009   ID.AddInteger(getSyntheticNodeSubclassData<MaskedLoadSDNode>(
8010       dl.getIROrder(), VTs, AM, ExtTy, isExpanding, MemVT, MMO));
8011   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8012   void *IP = nullptr;
8013   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8014     cast<MaskedLoadSDNode>(E)->refineAlignment(MMO);
8015     return SDValue(E, 0);
8016   }
8017   auto *N = newSDNode<MaskedLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
8018                                         AM, ExtTy, isExpanding, MemVT, MMO);
8019   createOperands(N, Ops);
8020 
8021   CSEMap.InsertNode(N, IP);
8022   InsertNode(N);
8023   SDValue V(N, 0);
8024   NewSDValueDbgMsg(V, "Creating new node: ", this);
8025   return V;
8026 }
8027 
8028 SDValue SelectionDAG::getIndexedMaskedLoad(SDValue OrigLoad, const SDLoc &dl,
8029                                            SDValue Base, SDValue Offset,
8030                                            ISD::MemIndexedMode AM) {
8031   MaskedLoadSDNode *LD = cast<MaskedLoadSDNode>(OrigLoad);
8032   assert(LD->getOffset().isUndef() && "Masked load is already a indexed load!");
8033   return getMaskedLoad(OrigLoad.getValueType(), dl, LD->getChain(), Base,
8034                        Offset, LD->getMask(), LD->getPassThru(),
8035                        LD->getMemoryVT(), LD->getMemOperand(), AM,
8036                        LD->getExtensionType(), LD->isExpandingLoad());
8037 }
8038 
8039 SDValue SelectionDAG::getMaskedStore(SDValue Chain, const SDLoc &dl,
8040                                      SDValue Val, SDValue Base, SDValue Offset,
8041                                      SDValue Mask, EVT MemVT,
8042                                      MachineMemOperand *MMO,
8043                                      ISD::MemIndexedMode AM, bool IsTruncating,
8044                                      bool IsCompressing) {
8045   assert(Chain.getValueType() == MVT::Other &&
8046         "Invalid chain type");
8047   bool Indexed = AM != ISD::UNINDEXED;
8048   assert((Indexed || Offset.isUndef()) &&
8049          "Unindexed masked store with an offset!");
8050   SDVTList VTs = Indexed ? getVTList(Base.getValueType(), MVT::Other)
8051                          : getVTList(MVT::Other);
8052   SDValue Ops[] = {Chain, Val, Base, Offset, Mask};
8053   FoldingSetNodeID ID;
8054   AddNodeIDNode(ID, ISD::MSTORE, VTs, Ops);
8055   ID.AddInteger(MemVT.getRawBits());
8056   ID.AddInteger(getSyntheticNodeSubclassData<MaskedStoreSDNode>(
8057       dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
8058   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8059   void *IP = nullptr;
8060   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8061     cast<MaskedStoreSDNode>(E)->refineAlignment(MMO);
8062     return SDValue(E, 0);
8063   }
8064   auto *N =
8065       newSDNode<MaskedStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
8066                                    IsTruncating, IsCompressing, MemVT, MMO);
8067   createOperands(N, Ops);
8068 
8069   CSEMap.InsertNode(N, IP);
8070   InsertNode(N);
8071   SDValue V(N, 0);
8072   NewSDValueDbgMsg(V, "Creating new node: ", this);
8073   return V;
8074 }
8075 
8076 SDValue SelectionDAG::getIndexedMaskedStore(SDValue OrigStore, const SDLoc &dl,
8077                                             SDValue Base, SDValue Offset,
8078                                             ISD::MemIndexedMode AM) {
8079   MaskedStoreSDNode *ST = cast<MaskedStoreSDNode>(OrigStore);
8080   assert(ST->getOffset().isUndef() &&
8081          "Masked store is already a indexed store!");
8082   return getMaskedStore(ST->getChain(), dl, ST->getValue(), Base, Offset,
8083                         ST->getMask(), ST->getMemoryVT(), ST->getMemOperand(),
8084                         AM, ST->isTruncatingStore(), ST->isCompressingStore());
8085 }
8086 
8087 SDValue SelectionDAG::getMaskedGather(SDVTList VTs, EVT MemVT, const SDLoc &dl,
8088                                       ArrayRef<SDValue> Ops,
8089                                       MachineMemOperand *MMO,
8090                                       ISD::MemIndexType IndexType,
8091                                       ISD::LoadExtType ExtTy) {
8092   assert(Ops.size() == 6 && "Incompatible number of operands");
8093 
8094   FoldingSetNodeID ID;
8095   AddNodeIDNode(ID, ISD::MGATHER, VTs, Ops);
8096   ID.AddInteger(MemVT.getRawBits());
8097   ID.AddInteger(getSyntheticNodeSubclassData<MaskedGatherSDNode>(
8098       dl.getIROrder(), VTs, MemVT, MMO, IndexType, ExtTy));
8099   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8100   void *IP = nullptr;
8101   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8102     cast<MaskedGatherSDNode>(E)->refineAlignment(MMO);
8103     return SDValue(E, 0);
8104   }
8105 
8106   IndexType = TLI->getCanonicalIndexType(IndexType, MemVT, Ops[4]);
8107   auto *N = newSDNode<MaskedGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(),
8108                                           VTs, MemVT, MMO, IndexType, ExtTy);
8109   createOperands(N, Ops);
8110 
8111   assert(N->getPassThru().getValueType() == N->getValueType(0) &&
8112          "Incompatible type of the PassThru value in MaskedGatherSDNode");
8113   assert(N->getMask().getValueType().getVectorElementCount() ==
8114              N->getValueType(0).getVectorElementCount() &&
8115          "Vector width mismatch between mask and data");
8116   assert(N->getIndex().getValueType().getVectorElementCount().isScalable() ==
8117              N->getValueType(0).getVectorElementCount().isScalable() &&
8118          "Scalable flags of index and data do not match");
8119   assert(ElementCount::isKnownGE(
8120              N->getIndex().getValueType().getVectorElementCount(),
8121              N->getValueType(0).getVectorElementCount()) &&
8122          "Vector width mismatch between index and data");
8123   assert(isa<ConstantSDNode>(N->getScale()) &&
8124          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
8125          "Scale should be a constant power of 2");
8126 
8127   CSEMap.InsertNode(N, IP);
8128   InsertNode(N);
8129   SDValue V(N, 0);
8130   NewSDValueDbgMsg(V, "Creating new node: ", this);
8131   return V;
8132 }
8133 
8134 SDValue SelectionDAG::getMaskedScatter(SDVTList VTs, EVT MemVT, const SDLoc &dl,
8135                                        ArrayRef<SDValue> Ops,
8136                                        MachineMemOperand *MMO,
8137                                        ISD::MemIndexType IndexType,
8138                                        bool IsTrunc) {
8139   assert(Ops.size() == 6 && "Incompatible number of operands");
8140 
8141   FoldingSetNodeID ID;
8142   AddNodeIDNode(ID, ISD::MSCATTER, VTs, Ops);
8143   ID.AddInteger(MemVT.getRawBits());
8144   ID.AddInteger(getSyntheticNodeSubclassData<MaskedScatterSDNode>(
8145       dl.getIROrder(), VTs, MemVT, MMO, IndexType, IsTrunc));
8146   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8147   void *IP = nullptr;
8148   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8149     cast<MaskedScatterSDNode>(E)->refineAlignment(MMO);
8150     return SDValue(E, 0);
8151   }
8152 
8153   IndexType = TLI->getCanonicalIndexType(IndexType, MemVT, Ops[4]);
8154   auto *N = newSDNode<MaskedScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(),
8155                                            VTs, MemVT, MMO, IndexType, IsTrunc);
8156   createOperands(N, Ops);
8157 
8158   assert(N->getMask().getValueType().getVectorElementCount() ==
8159              N->getValue().getValueType().getVectorElementCount() &&
8160          "Vector width mismatch between mask and data");
8161   assert(
8162       N->getIndex().getValueType().getVectorElementCount().isScalable() ==
8163           N->getValue().getValueType().getVectorElementCount().isScalable() &&
8164       "Scalable flags of index and data do not match");
8165   assert(ElementCount::isKnownGE(
8166              N->getIndex().getValueType().getVectorElementCount(),
8167              N->getValue().getValueType().getVectorElementCount()) &&
8168          "Vector width mismatch between index and data");
8169   assert(isa<ConstantSDNode>(N->getScale()) &&
8170          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
8171          "Scale should be a constant power of 2");
8172 
8173   CSEMap.InsertNode(N, IP);
8174   InsertNode(N);
8175   SDValue V(N, 0);
8176   NewSDValueDbgMsg(V, "Creating new node: ", this);
8177   return V;
8178 }
8179 
8180 SDValue SelectionDAG::simplifySelect(SDValue Cond, SDValue T, SDValue F) {
8181   // select undef, T, F --> T (if T is a constant), otherwise F
8182   // select, ?, undef, F --> F
8183   // select, ?, T, undef --> T
8184   if (Cond.isUndef())
8185     return isConstantValueOfAnyType(T) ? T : F;
8186   if (T.isUndef())
8187     return F;
8188   if (F.isUndef())
8189     return T;
8190 
8191   // select true, T, F --> T
8192   // select false, T, F --> F
8193   if (auto *CondC = dyn_cast<ConstantSDNode>(Cond))
8194     return CondC->isZero() ? F : T;
8195 
8196   // TODO: This should simplify VSELECT with constant condition using something
8197   // like this (but check boolean contents to be complete?):
8198   //  if (ISD::isBuildVectorAllOnes(Cond.getNode()))
8199   //    return T;
8200   //  if (ISD::isBuildVectorAllZeros(Cond.getNode()))
8201   //    return F;
8202 
8203   // select ?, T, T --> T
8204   if (T == F)
8205     return T;
8206 
8207   return SDValue();
8208 }
8209 
8210 SDValue SelectionDAG::simplifyShift(SDValue X, SDValue Y) {
8211   // shift undef, Y --> 0 (can always assume that the undef value is 0)
8212   if (X.isUndef())
8213     return getConstant(0, SDLoc(X.getNode()), X.getValueType());
8214   // shift X, undef --> undef (because it may shift by the bitwidth)
8215   if (Y.isUndef())
8216     return getUNDEF(X.getValueType());
8217 
8218   // shift 0, Y --> 0
8219   // shift X, 0 --> X
8220   if (isNullOrNullSplat(X) || isNullOrNullSplat(Y))
8221     return X;
8222 
8223   // shift X, C >= bitwidth(X) --> undef
8224   // All vector elements must be too big (or undef) to avoid partial undefs.
8225   auto isShiftTooBig = [X](ConstantSDNode *Val) {
8226     return !Val || Val->getAPIntValue().uge(X.getScalarValueSizeInBits());
8227   };
8228   if (ISD::matchUnaryPredicate(Y, isShiftTooBig, true))
8229     return getUNDEF(X.getValueType());
8230 
8231   return SDValue();
8232 }
8233 
8234 SDValue SelectionDAG::simplifyFPBinop(unsigned Opcode, SDValue X, SDValue Y,
8235                                       SDNodeFlags Flags) {
8236   // If this operation has 'nnan' or 'ninf' and at least 1 disallowed operand
8237   // (an undef operand can be chosen to be Nan/Inf), then the result of this
8238   // operation is poison. That result can be relaxed to undef.
8239   ConstantFPSDNode *XC = isConstOrConstSplatFP(X, /* AllowUndefs */ true);
8240   ConstantFPSDNode *YC = isConstOrConstSplatFP(Y, /* AllowUndefs */ true);
8241   bool HasNan = (XC && XC->getValueAPF().isNaN()) ||
8242                 (YC && YC->getValueAPF().isNaN());
8243   bool HasInf = (XC && XC->getValueAPF().isInfinity()) ||
8244                 (YC && YC->getValueAPF().isInfinity());
8245 
8246   if (Flags.hasNoNaNs() && (HasNan || X.isUndef() || Y.isUndef()))
8247     return getUNDEF(X.getValueType());
8248 
8249   if (Flags.hasNoInfs() && (HasInf || X.isUndef() || Y.isUndef()))
8250     return getUNDEF(X.getValueType());
8251 
8252   if (!YC)
8253     return SDValue();
8254 
8255   // X + -0.0 --> X
8256   if (Opcode == ISD::FADD)
8257     if (YC->getValueAPF().isNegZero())
8258       return X;
8259 
8260   // X - +0.0 --> X
8261   if (Opcode == ISD::FSUB)
8262     if (YC->getValueAPF().isPosZero())
8263       return X;
8264 
8265   // X * 1.0 --> X
8266   // X / 1.0 --> X
8267   if (Opcode == ISD::FMUL || Opcode == ISD::FDIV)
8268     if (YC->getValueAPF().isExactlyValue(1.0))
8269       return X;
8270 
8271   // X * 0.0 --> 0.0
8272   if (Opcode == ISD::FMUL && Flags.hasNoNaNs() && Flags.hasNoSignedZeros())
8273     if (YC->getValueAPF().isZero())
8274       return getConstantFP(0.0, SDLoc(Y), Y.getValueType());
8275 
8276   return SDValue();
8277 }
8278 
8279 SDValue SelectionDAG::getVAArg(EVT VT, const SDLoc &dl, SDValue Chain,
8280                                SDValue Ptr, SDValue SV, unsigned Align) {
8281   SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, dl, MVT::i32) };
8282   return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops);
8283 }
8284 
8285 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8286                               ArrayRef<SDUse> Ops) {
8287   switch (Ops.size()) {
8288   case 0: return getNode(Opcode, DL, VT);
8289   case 1: return getNode(Opcode, DL, VT, static_cast<const SDValue>(Ops[0]));
8290   case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
8291   case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
8292   default: break;
8293   }
8294 
8295   // Copy from an SDUse array into an SDValue array for use with
8296   // the regular getNode logic.
8297   SmallVector<SDValue, 8> NewOps(Ops.begin(), Ops.end());
8298   return getNode(Opcode, DL, VT, NewOps);
8299 }
8300 
8301 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8302                               ArrayRef<SDValue> Ops) {
8303   SDNodeFlags Flags;
8304   if (Inserter)
8305     Flags = Inserter->getFlags();
8306   return getNode(Opcode, DL, VT, Ops, Flags);
8307 }
8308 
8309 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8310                               ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
8311   unsigned NumOps = Ops.size();
8312   switch (NumOps) {
8313   case 0: return getNode(Opcode, DL, VT);
8314   case 1: return getNode(Opcode, DL, VT, Ops[0], Flags);
8315   case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Flags);
8316   case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2], Flags);
8317   default: break;
8318   }
8319 
8320 #ifndef NDEBUG
8321   for (auto &Op : Ops)
8322     assert(Op.getOpcode() != ISD::DELETED_NODE &&
8323            "Operand is DELETED_NODE!");
8324 #endif
8325 
8326   switch (Opcode) {
8327   default: break;
8328   case ISD::BUILD_VECTOR:
8329     // Attempt to simplify BUILD_VECTOR.
8330     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
8331       return V;
8332     break;
8333   case ISD::CONCAT_VECTORS:
8334     if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
8335       return V;
8336     break;
8337   case ISD::SELECT_CC:
8338     assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
8339     assert(Ops[0].getValueType() == Ops[1].getValueType() &&
8340            "LHS and RHS of condition must have same type!");
8341     assert(Ops[2].getValueType() == Ops[3].getValueType() &&
8342            "True and False arms of SelectCC must have same type!");
8343     assert(Ops[2].getValueType() == VT &&
8344            "select_cc node must be of same type as true and false value!");
8345     break;
8346   case ISD::BR_CC:
8347     assert(NumOps == 5 && "BR_CC takes 5 operands!");
8348     assert(Ops[2].getValueType() == Ops[3].getValueType() &&
8349            "LHS/RHS of comparison should match types!");
8350     break;
8351   }
8352 
8353   // Memoize nodes.
8354   SDNode *N;
8355   SDVTList VTs = getVTList(VT);
8356 
8357   if (VT != MVT::Glue) {
8358     FoldingSetNodeID ID;
8359     AddNodeIDNode(ID, Opcode, VTs, Ops);
8360     void *IP = nullptr;
8361 
8362     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
8363       return SDValue(E, 0);
8364 
8365     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
8366     createOperands(N, Ops);
8367 
8368     CSEMap.InsertNode(N, IP);
8369   } else {
8370     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
8371     createOperands(N, Ops);
8372   }
8373 
8374   N->setFlags(Flags);
8375   InsertNode(N);
8376   SDValue V(N, 0);
8377   NewSDValueDbgMsg(V, "Creating new node: ", this);
8378   return V;
8379 }
8380 
8381 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
8382                               ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) {
8383   return getNode(Opcode, DL, getVTList(ResultTys), Ops);
8384 }
8385 
8386 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8387                               ArrayRef<SDValue> Ops) {
8388   SDNodeFlags Flags;
8389   if (Inserter)
8390     Flags = Inserter->getFlags();
8391   return getNode(Opcode, DL, VTList, Ops, Flags);
8392 }
8393 
8394 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8395                               ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
8396   if (VTList.NumVTs == 1)
8397     return getNode(Opcode, DL, VTList.VTs[0], Ops);
8398 
8399 #ifndef NDEBUG
8400   for (auto &Op : Ops)
8401     assert(Op.getOpcode() != ISD::DELETED_NODE &&
8402            "Operand is DELETED_NODE!");
8403 #endif
8404 
8405   switch (Opcode) {
8406   case ISD::STRICT_FP_EXTEND:
8407     assert(VTList.NumVTs == 2 && Ops.size() == 2 &&
8408            "Invalid STRICT_FP_EXTEND!");
8409     assert(VTList.VTs[0].isFloatingPoint() &&
8410            Ops[1].getValueType().isFloatingPoint() && "Invalid FP cast!");
8411     assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
8412            "STRICT_FP_EXTEND result type should be vector iff the operand "
8413            "type is vector!");
8414     assert((!VTList.VTs[0].isVector() ||
8415             VTList.VTs[0].getVectorNumElements() ==
8416             Ops[1].getValueType().getVectorNumElements()) &&
8417            "Vector element count mismatch!");
8418     assert(Ops[1].getValueType().bitsLT(VTList.VTs[0]) &&
8419            "Invalid fpext node, dst <= src!");
8420     break;
8421   case ISD::STRICT_FP_ROUND:
8422     assert(VTList.NumVTs == 2 && Ops.size() == 3 && "Invalid STRICT_FP_ROUND!");
8423     assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
8424            "STRICT_FP_ROUND result type should be vector iff the operand "
8425            "type is vector!");
8426     assert((!VTList.VTs[0].isVector() ||
8427             VTList.VTs[0].getVectorNumElements() ==
8428             Ops[1].getValueType().getVectorNumElements()) &&
8429            "Vector element count mismatch!");
8430     assert(VTList.VTs[0].isFloatingPoint() &&
8431            Ops[1].getValueType().isFloatingPoint() &&
8432            VTList.VTs[0].bitsLT(Ops[1].getValueType()) &&
8433            isa<ConstantSDNode>(Ops[2]) &&
8434            (cast<ConstantSDNode>(Ops[2])->getZExtValue() == 0 ||
8435             cast<ConstantSDNode>(Ops[2])->getZExtValue() == 1) &&
8436            "Invalid STRICT_FP_ROUND!");
8437     break;
8438 #if 0
8439   // FIXME: figure out how to safely handle things like
8440   // int foo(int x) { return 1 << (x & 255); }
8441   // int bar() { return foo(256); }
8442   case ISD::SRA_PARTS:
8443   case ISD::SRL_PARTS:
8444   case ISD::SHL_PARTS:
8445     if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
8446         cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
8447       return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
8448     else if (N3.getOpcode() == ISD::AND)
8449       if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
8450         // If the and is only masking out bits that cannot effect the shift,
8451         // eliminate the and.
8452         unsigned NumBits = VT.getScalarSizeInBits()*2;
8453         if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
8454           return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
8455       }
8456     break;
8457 #endif
8458   }
8459 
8460   // Memoize the node unless it returns a flag.
8461   SDNode *N;
8462   if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
8463     FoldingSetNodeID ID;
8464     AddNodeIDNode(ID, Opcode, VTList, Ops);
8465     void *IP = nullptr;
8466     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
8467       return SDValue(E, 0);
8468 
8469     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
8470     createOperands(N, Ops);
8471     CSEMap.InsertNode(N, IP);
8472   } else {
8473     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
8474     createOperands(N, Ops);
8475   }
8476 
8477   N->setFlags(Flags);
8478   InsertNode(N);
8479   SDValue V(N, 0);
8480   NewSDValueDbgMsg(V, "Creating new node: ", this);
8481   return V;
8482 }
8483 
8484 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
8485                               SDVTList VTList) {
8486   return getNode(Opcode, DL, VTList, None);
8487 }
8488 
8489 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8490                               SDValue N1) {
8491   SDValue Ops[] = { N1 };
8492   return getNode(Opcode, DL, VTList, Ops);
8493 }
8494 
8495 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8496                               SDValue N1, SDValue N2) {
8497   SDValue Ops[] = { N1, N2 };
8498   return getNode(Opcode, DL, VTList, Ops);
8499 }
8500 
8501 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8502                               SDValue N1, SDValue N2, SDValue N3) {
8503   SDValue Ops[] = { N1, N2, N3 };
8504   return getNode(Opcode, DL, VTList, Ops);
8505 }
8506 
8507 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8508                               SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
8509   SDValue Ops[] = { N1, N2, N3, N4 };
8510   return getNode(Opcode, DL, VTList, Ops);
8511 }
8512 
8513 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8514                               SDValue N1, SDValue N2, SDValue N3, SDValue N4,
8515                               SDValue N5) {
8516   SDValue Ops[] = { N1, N2, N3, N4, N5 };
8517   return getNode(Opcode, DL, VTList, Ops);
8518 }
8519 
8520 SDVTList SelectionDAG::getVTList(EVT VT) {
8521   return makeVTList(SDNode::getValueTypeList(VT), 1);
8522 }
8523 
8524 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2) {
8525   FoldingSetNodeID ID;
8526   ID.AddInteger(2U);
8527   ID.AddInteger(VT1.getRawBits());
8528   ID.AddInteger(VT2.getRawBits());
8529 
8530   void *IP = nullptr;
8531   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
8532   if (!Result) {
8533     EVT *Array = Allocator.Allocate<EVT>(2);
8534     Array[0] = VT1;
8535     Array[1] = VT2;
8536     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 2);
8537     VTListMap.InsertNode(Result, IP);
8538   }
8539   return Result->getSDVTList();
8540 }
8541 
8542 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3) {
8543   FoldingSetNodeID ID;
8544   ID.AddInteger(3U);
8545   ID.AddInteger(VT1.getRawBits());
8546   ID.AddInteger(VT2.getRawBits());
8547   ID.AddInteger(VT3.getRawBits());
8548 
8549   void *IP = nullptr;
8550   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
8551   if (!Result) {
8552     EVT *Array = Allocator.Allocate<EVT>(3);
8553     Array[0] = VT1;
8554     Array[1] = VT2;
8555     Array[2] = VT3;
8556     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 3);
8557     VTListMap.InsertNode(Result, IP);
8558   }
8559   return Result->getSDVTList();
8560 }
8561 
8562 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4) {
8563   FoldingSetNodeID ID;
8564   ID.AddInteger(4U);
8565   ID.AddInteger(VT1.getRawBits());
8566   ID.AddInteger(VT2.getRawBits());
8567   ID.AddInteger(VT3.getRawBits());
8568   ID.AddInteger(VT4.getRawBits());
8569 
8570   void *IP = nullptr;
8571   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
8572   if (!Result) {
8573     EVT *Array = Allocator.Allocate<EVT>(4);
8574     Array[0] = VT1;
8575     Array[1] = VT2;
8576     Array[2] = VT3;
8577     Array[3] = VT4;
8578     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 4);
8579     VTListMap.InsertNode(Result, IP);
8580   }
8581   return Result->getSDVTList();
8582 }
8583 
8584 SDVTList SelectionDAG::getVTList(ArrayRef<EVT> VTs) {
8585   unsigned NumVTs = VTs.size();
8586   FoldingSetNodeID ID;
8587   ID.AddInteger(NumVTs);
8588   for (unsigned index = 0; index < NumVTs; index++) {
8589     ID.AddInteger(VTs[index].getRawBits());
8590   }
8591 
8592   void *IP = nullptr;
8593   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
8594   if (!Result) {
8595     EVT *Array = Allocator.Allocate<EVT>(NumVTs);
8596     llvm::copy(VTs, Array);
8597     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, NumVTs);
8598     VTListMap.InsertNode(Result, IP);
8599   }
8600   return Result->getSDVTList();
8601 }
8602 
8603 
8604 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
8605 /// specified operands.  If the resultant node already exists in the DAG,
8606 /// this does not modify the specified node, instead it returns the node that
8607 /// already exists.  If the resultant node does not exist in the DAG, the
8608 /// input node is returned.  As a degenerate case, if you specify the same
8609 /// input operands as the node already has, the input node is returned.
8610 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op) {
8611   assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
8612 
8613   // Check to see if there is no change.
8614   if (Op == N->getOperand(0)) return N;
8615 
8616   // See if the modified node already exists.
8617   void *InsertPos = nullptr;
8618   if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
8619     return Existing;
8620 
8621   // Nope it doesn't.  Remove the node from its current place in the maps.
8622   if (InsertPos)
8623     if (!RemoveNodeFromCSEMaps(N))
8624       InsertPos = nullptr;
8625 
8626   // Now we update the operands.
8627   N->OperandList[0].set(Op);
8628 
8629   updateDivergence(N);
8630   // If this gets put into a CSE map, add it.
8631   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
8632   return N;
8633 }
8634 
8635 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2) {
8636   assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
8637 
8638   // Check to see if there is no change.
8639   if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
8640     return N;   // No operands changed, just return the input node.
8641 
8642   // See if the modified node already exists.
8643   void *InsertPos = nullptr;
8644   if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
8645     return Existing;
8646 
8647   // Nope it doesn't.  Remove the node from its current place in the maps.
8648   if (InsertPos)
8649     if (!RemoveNodeFromCSEMaps(N))
8650       InsertPos = nullptr;
8651 
8652   // Now we update the operands.
8653   if (N->OperandList[0] != Op1)
8654     N->OperandList[0].set(Op1);
8655   if (N->OperandList[1] != Op2)
8656     N->OperandList[1].set(Op2);
8657 
8658   updateDivergence(N);
8659   // If this gets put into a CSE map, add it.
8660   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
8661   return N;
8662 }
8663 
8664 SDNode *SelectionDAG::
8665 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, SDValue Op3) {
8666   SDValue Ops[] = { Op1, Op2, Op3 };
8667   return UpdateNodeOperands(N, Ops);
8668 }
8669 
8670 SDNode *SelectionDAG::
8671 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
8672                    SDValue Op3, SDValue Op4) {
8673   SDValue Ops[] = { Op1, Op2, Op3, Op4 };
8674   return UpdateNodeOperands(N, Ops);
8675 }
8676 
8677 SDNode *SelectionDAG::
8678 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
8679                    SDValue Op3, SDValue Op4, SDValue Op5) {
8680   SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 };
8681   return UpdateNodeOperands(N, Ops);
8682 }
8683 
8684 SDNode *SelectionDAG::
8685 UpdateNodeOperands(SDNode *N, ArrayRef<SDValue> Ops) {
8686   unsigned NumOps = Ops.size();
8687   assert(N->getNumOperands() == NumOps &&
8688          "Update with wrong number of operands");
8689 
8690   // If no operands changed just return the input node.
8691   if (std::equal(Ops.begin(), Ops.end(), N->op_begin()))
8692     return N;
8693 
8694   // See if the modified node already exists.
8695   void *InsertPos = nullptr;
8696   if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertPos))
8697     return Existing;
8698 
8699   // Nope it doesn't.  Remove the node from its current place in the maps.
8700   if (InsertPos)
8701     if (!RemoveNodeFromCSEMaps(N))
8702       InsertPos = nullptr;
8703 
8704   // Now we update the operands.
8705   for (unsigned i = 0; i != NumOps; ++i)
8706     if (N->OperandList[i] != Ops[i])
8707       N->OperandList[i].set(Ops[i]);
8708 
8709   updateDivergence(N);
8710   // If this gets put into a CSE map, add it.
8711   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
8712   return N;
8713 }
8714 
8715 /// DropOperands - Release the operands and set this node to have
8716 /// zero operands.
8717 void SDNode::DropOperands() {
8718   // Unlike the code in MorphNodeTo that does this, we don't need to
8719   // watch for dead nodes here.
8720   for (op_iterator I = op_begin(), E = op_end(); I != E; ) {
8721     SDUse &Use = *I++;
8722     Use.set(SDValue());
8723   }
8724 }
8725 
8726 void SelectionDAG::setNodeMemRefs(MachineSDNode *N,
8727                                   ArrayRef<MachineMemOperand *> NewMemRefs) {
8728   if (NewMemRefs.empty()) {
8729     N->clearMemRefs();
8730     return;
8731   }
8732 
8733   // Check if we can avoid allocating by storing a single reference directly.
8734   if (NewMemRefs.size() == 1) {
8735     N->MemRefs = NewMemRefs[0];
8736     N->NumMemRefs = 1;
8737     return;
8738   }
8739 
8740   MachineMemOperand **MemRefsBuffer =
8741       Allocator.template Allocate<MachineMemOperand *>(NewMemRefs.size());
8742   llvm::copy(NewMemRefs, MemRefsBuffer);
8743   N->MemRefs = MemRefsBuffer;
8744   N->NumMemRefs = static_cast<int>(NewMemRefs.size());
8745 }
8746 
8747 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a
8748 /// machine opcode.
8749 ///
8750 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8751                                    EVT VT) {
8752   SDVTList VTs = getVTList(VT);
8753   return SelectNodeTo(N, MachineOpc, VTs, None);
8754 }
8755 
8756 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8757                                    EVT VT, SDValue Op1) {
8758   SDVTList VTs = getVTList(VT);
8759   SDValue Ops[] = { Op1 };
8760   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8761 }
8762 
8763 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8764                                    EVT VT, SDValue Op1,
8765                                    SDValue Op2) {
8766   SDVTList VTs = getVTList(VT);
8767   SDValue Ops[] = { Op1, Op2 };
8768   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8769 }
8770 
8771 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8772                                    EVT VT, SDValue Op1,
8773                                    SDValue Op2, SDValue Op3) {
8774   SDVTList VTs = getVTList(VT);
8775   SDValue Ops[] = { Op1, Op2, Op3 };
8776   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8777 }
8778 
8779 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8780                                    EVT VT, ArrayRef<SDValue> Ops) {
8781   SDVTList VTs = getVTList(VT);
8782   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8783 }
8784 
8785 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8786                                    EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) {
8787   SDVTList VTs = getVTList(VT1, VT2);
8788   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8789 }
8790 
8791 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8792                                    EVT VT1, EVT VT2) {
8793   SDVTList VTs = getVTList(VT1, VT2);
8794   return SelectNodeTo(N, MachineOpc, VTs, None);
8795 }
8796 
8797 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8798                                    EVT VT1, EVT VT2, EVT VT3,
8799                                    ArrayRef<SDValue> Ops) {
8800   SDVTList VTs = getVTList(VT1, VT2, VT3);
8801   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8802 }
8803 
8804 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8805                                    EVT VT1, EVT VT2,
8806                                    SDValue Op1, SDValue Op2) {
8807   SDVTList VTs = getVTList(VT1, VT2);
8808   SDValue Ops[] = { Op1, Op2 };
8809   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8810 }
8811 
8812 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8813                                    SDVTList VTs,ArrayRef<SDValue> Ops) {
8814   SDNode *New = MorphNodeTo(N, ~MachineOpc, VTs, Ops);
8815   // Reset the NodeID to -1.
8816   New->setNodeId(-1);
8817   if (New != N) {
8818     ReplaceAllUsesWith(N, New);
8819     RemoveDeadNode(N);
8820   }
8821   return New;
8822 }
8823 
8824 /// UpdateSDLocOnMergeSDNode - If the opt level is -O0 then it throws away
8825 /// the line number information on the merged node since it is not possible to
8826 /// preserve the information that operation is associated with multiple lines.
8827 /// This will make the debugger working better at -O0, were there is a higher
8828 /// probability having other instructions associated with that line.
8829 ///
8830 /// For IROrder, we keep the smaller of the two
8831 SDNode *SelectionDAG::UpdateSDLocOnMergeSDNode(SDNode *N, const SDLoc &OLoc) {
8832   DebugLoc NLoc = N->getDebugLoc();
8833   if (NLoc && OptLevel == CodeGenOpt::None && OLoc.getDebugLoc() != NLoc) {
8834     N->setDebugLoc(DebugLoc());
8835   }
8836   unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder());
8837   N->setIROrder(Order);
8838   return N;
8839 }
8840 
8841 /// MorphNodeTo - This *mutates* the specified node to have the specified
8842 /// return type, opcode, and operands.
8843 ///
8844 /// Note that MorphNodeTo returns the resultant node.  If there is already a
8845 /// node of the specified opcode and operands, it returns that node instead of
8846 /// the current one.  Note that the SDLoc need not be the same.
8847 ///
8848 /// Using MorphNodeTo is faster than creating a new node and swapping it in
8849 /// with ReplaceAllUsesWith both because it often avoids allocating a new
8850 /// node, and because it doesn't require CSE recalculation for any of
8851 /// the node's users.
8852 ///
8853 /// However, note that MorphNodeTo recursively deletes dead nodes from the DAG.
8854 /// As a consequence it isn't appropriate to use from within the DAG combiner or
8855 /// the legalizer which maintain worklists that would need to be updated when
8856 /// deleting things.
8857 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
8858                                   SDVTList VTs, ArrayRef<SDValue> Ops) {
8859   // If an identical node already exists, use it.
8860   void *IP = nullptr;
8861   if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) {
8862     FoldingSetNodeID ID;
8863     AddNodeIDNode(ID, Opc, VTs, Ops);
8864     if (SDNode *ON = FindNodeOrInsertPos(ID, SDLoc(N), IP))
8865       return UpdateSDLocOnMergeSDNode(ON, SDLoc(N));
8866   }
8867 
8868   if (!RemoveNodeFromCSEMaps(N))
8869     IP = nullptr;
8870 
8871   // Start the morphing.
8872   N->NodeType = Opc;
8873   N->ValueList = VTs.VTs;
8874   N->NumValues = VTs.NumVTs;
8875 
8876   // Clear the operands list, updating used nodes to remove this from their
8877   // use list.  Keep track of any operands that become dead as a result.
8878   SmallPtrSet<SDNode*, 16> DeadNodeSet;
8879   for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
8880     SDUse &Use = *I++;
8881     SDNode *Used = Use.getNode();
8882     Use.set(SDValue());
8883     if (Used->use_empty())
8884       DeadNodeSet.insert(Used);
8885   }
8886 
8887   // For MachineNode, initialize the memory references information.
8888   if (MachineSDNode *MN = dyn_cast<MachineSDNode>(N))
8889     MN->clearMemRefs();
8890 
8891   // Swap for an appropriately sized array from the recycler.
8892   removeOperands(N);
8893   createOperands(N, Ops);
8894 
8895   // Delete any nodes that are still dead after adding the uses for the
8896   // new operands.
8897   if (!DeadNodeSet.empty()) {
8898     SmallVector<SDNode *, 16> DeadNodes;
8899     for (SDNode *N : DeadNodeSet)
8900       if (N->use_empty())
8901         DeadNodes.push_back(N);
8902     RemoveDeadNodes(DeadNodes);
8903   }
8904 
8905   if (IP)
8906     CSEMap.InsertNode(N, IP);   // Memoize the new node.
8907   return N;
8908 }
8909 
8910 SDNode* SelectionDAG::mutateStrictFPToFP(SDNode *Node) {
8911   unsigned OrigOpc = Node->getOpcode();
8912   unsigned NewOpc;
8913   switch (OrigOpc) {
8914   default:
8915     llvm_unreachable("mutateStrictFPToFP called with unexpected opcode!");
8916 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
8917   case ISD::STRICT_##DAGN: NewOpc = ISD::DAGN; break;
8918 #define CMP_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
8919   case ISD::STRICT_##DAGN: NewOpc = ISD::SETCC; break;
8920 #include "llvm/IR/ConstrainedOps.def"
8921   }
8922 
8923   assert(Node->getNumValues() == 2 && "Unexpected number of results!");
8924 
8925   // We're taking this node out of the chain, so we need to re-link things.
8926   SDValue InputChain = Node->getOperand(0);
8927   SDValue OutputChain = SDValue(Node, 1);
8928   ReplaceAllUsesOfValueWith(OutputChain, InputChain);
8929 
8930   SmallVector<SDValue, 3> Ops;
8931   for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
8932     Ops.push_back(Node->getOperand(i));
8933 
8934   SDVTList VTs = getVTList(Node->getValueType(0));
8935   SDNode *Res = MorphNodeTo(Node, NewOpc, VTs, Ops);
8936 
8937   // MorphNodeTo can operate in two ways: if an existing node with the
8938   // specified operands exists, it can just return it.  Otherwise, it
8939   // updates the node in place to have the requested operands.
8940   if (Res == Node) {
8941     // If we updated the node in place, reset the node ID.  To the isel,
8942     // this should be just like a newly allocated machine node.
8943     Res->setNodeId(-1);
8944   } else {
8945     ReplaceAllUsesWith(Node, Res);
8946     RemoveDeadNode(Node);
8947   }
8948 
8949   return Res;
8950 }
8951 
8952 /// getMachineNode - These are used for target selectors to create a new node
8953 /// with specified return type(s), MachineInstr opcode, and operands.
8954 ///
8955 /// Note that getMachineNode returns the resultant node.  If there is already a
8956 /// node of the specified opcode and operands, it returns that node instead of
8957 /// the current one.
8958 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8959                                             EVT VT) {
8960   SDVTList VTs = getVTList(VT);
8961   return getMachineNode(Opcode, dl, VTs, None);
8962 }
8963 
8964 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8965                                             EVT VT, SDValue Op1) {
8966   SDVTList VTs = getVTList(VT);
8967   SDValue Ops[] = { Op1 };
8968   return getMachineNode(Opcode, dl, VTs, Ops);
8969 }
8970 
8971 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8972                                             EVT VT, SDValue Op1, SDValue Op2) {
8973   SDVTList VTs = getVTList(VT);
8974   SDValue Ops[] = { Op1, Op2 };
8975   return getMachineNode(Opcode, dl, VTs, Ops);
8976 }
8977 
8978 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8979                                             EVT VT, SDValue Op1, SDValue Op2,
8980                                             SDValue Op3) {
8981   SDVTList VTs = getVTList(VT);
8982   SDValue Ops[] = { Op1, Op2, Op3 };
8983   return getMachineNode(Opcode, dl, VTs, Ops);
8984 }
8985 
8986 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8987                                             EVT VT, ArrayRef<SDValue> Ops) {
8988   SDVTList VTs = getVTList(VT);
8989   return getMachineNode(Opcode, dl, VTs, Ops);
8990 }
8991 
8992 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8993                                             EVT VT1, EVT VT2, SDValue Op1,
8994                                             SDValue Op2) {
8995   SDVTList VTs = getVTList(VT1, VT2);
8996   SDValue Ops[] = { Op1, Op2 };
8997   return getMachineNode(Opcode, dl, VTs, Ops);
8998 }
8999 
9000 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9001                                             EVT VT1, EVT VT2, SDValue Op1,
9002                                             SDValue Op2, SDValue Op3) {
9003   SDVTList VTs = getVTList(VT1, VT2);
9004   SDValue Ops[] = { Op1, Op2, Op3 };
9005   return getMachineNode(Opcode, dl, VTs, Ops);
9006 }
9007 
9008 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9009                                             EVT VT1, EVT VT2,
9010                                             ArrayRef<SDValue> Ops) {
9011   SDVTList VTs = getVTList(VT1, VT2);
9012   return getMachineNode(Opcode, dl, VTs, Ops);
9013 }
9014 
9015 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9016                                             EVT VT1, EVT VT2, EVT VT3,
9017                                             SDValue Op1, SDValue Op2) {
9018   SDVTList VTs = getVTList(VT1, VT2, VT3);
9019   SDValue Ops[] = { Op1, Op2 };
9020   return getMachineNode(Opcode, dl, VTs, Ops);
9021 }
9022 
9023 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9024                                             EVT VT1, EVT VT2, EVT VT3,
9025                                             SDValue Op1, SDValue Op2,
9026                                             SDValue Op3) {
9027   SDVTList VTs = getVTList(VT1, VT2, VT3);
9028   SDValue Ops[] = { Op1, Op2, Op3 };
9029   return getMachineNode(Opcode, dl, VTs, Ops);
9030 }
9031 
9032 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9033                                             EVT VT1, EVT VT2, EVT VT3,
9034                                             ArrayRef<SDValue> Ops) {
9035   SDVTList VTs = getVTList(VT1, VT2, VT3);
9036   return getMachineNode(Opcode, dl, VTs, Ops);
9037 }
9038 
9039 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9040                                             ArrayRef<EVT> ResultTys,
9041                                             ArrayRef<SDValue> Ops) {
9042   SDVTList VTs = getVTList(ResultTys);
9043   return getMachineNode(Opcode, dl, VTs, Ops);
9044 }
9045 
9046 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &DL,
9047                                             SDVTList VTs,
9048                                             ArrayRef<SDValue> Ops) {
9049   bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue;
9050   MachineSDNode *N;
9051   void *IP = nullptr;
9052 
9053   if (DoCSE) {
9054     FoldingSetNodeID ID;
9055     AddNodeIDNode(ID, ~Opcode, VTs, Ops);
9056     IP = nullptr;
9057     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
9058       return cast<MachineSDNode>(UpdateSDLocOnMergeSDNode(E, DL));
9059     }
9060   }
9061 
9062   // Allocate a new MachineSDNode.
9063   N = newSDNode<MachineSDNode>(~Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
9064   createOperands(N, Ops);
9065 
9066   if (DoCSE)
9067     CSEMap.InsertNode(N, IP);
9068 
9069   InsertNode(N);
9070   NewSDValueDbgMsg(SDValue(N, 0), "Creating new machine node: ", this);
9071   return N;
9072 }
9073 
9074 /// getTargetExtractSubreg - A convenience function for creating
9075 /// TargetOpcode::EXTRACT_SUBREG nodes.
9076 SDValue SelectionDAG::getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT,
9077                                              SDValue Operand) {
9078   SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
9079   SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,
9080                                   VT, Operand, SRIdxVal);
9081   return SDValue(Subreg, 0);
9082 }
9083 
9084 /// getTargetInsertSubreg - A convenience function for creating
9085 /// TargetOpcode::INSERT_SUBREG nodes.
9086 SDValue SelectionDAG::getTargetInsertSubreg(int SRIdx, const SDLoc &DL, EVT VT,
9087                                             SDValue Operand, SDValue Subreg) {
9088   SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
9089   SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL,
9090                                   VT, Operand, Subreg, SRIdxVal);
9091   return SDValue(Result, 0);
9092 }
9093 
9094 /// getNodeIfExists - Get the specified node if it's already available, or
9095 /// else return NULL.
9096 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
9097                                       ArrayRef<SDValue> Ops) {
9098   SDNodeFlags Flags;
9099   if (Inserter)
9100     Flags = Inserter->getFlags();
9101   return getNodeIfExists(Opcode, VTList, Ops, Flags);
9102 }
9103 
9104 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
9105                                       ArrayRef<SDValue> Ops,
9106                                       const SDNodeFlags Flags) {
9107   if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
9108     FoldingSetNodeID ID;
9109     AddNodeIDNode(ID, Opcode, VTList, Ops);
9110     void *IP = nullptr;
9111     if (SDNode *E = FindNodeOrInsertPos(ID, SDLoc(), IP)) {
9112       E->intersectFlagsWith(Flags);
9113       return E;
9114     }
9115   }
9116   return nullptr;
9117 }
9118 
9119 /// doesNodeExist - Check if a node exists without modifying its flags.
9120 bool SelectionDAG::doesNodeExist(unsigned Opcode, SDVTList VTList,
9121                                  ArrayRef<SDValue> Ops) {
9122   if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
9123     FoldingSetNodeID ID;
9124     AddNodeIDNode(ID, Opcode, VTList, Ops);
9125     void *IP = nullptr;
9126     if (FindNodeOrInsertPos(ID, SDLoc(), IP))
9127       return true;
9128   }
9129   return false;
9130 }
9131 
9132 /// getDbgValue - Creates a SDDbgValue node.
9133 ///
9134 /// SDNode
9135 SDDbgValue *SelectionDAG::getDbgValue(DIVariable *Var, DIExpression *Expr,
9136                                       SDNode *N, unsigned R, bool IsIndirect,
9137                                       const DebugLoc &DL, unsigned O) {
9138   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9139          "Expected inlined-at fields to agree");
9140   return new (DbgInfo->getAlloc())
9141       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromNode(N, R),
9142                  {}, IsIndirect, DL, O,
9143                  /*IsVariadic=*/false);
9144 }
9145 
9146 /// Constant
9147 SDDbgValue *SelectionDAG::getConstantDbgValue(DIVariable *Var,
9148                                               DIExpression *Expr,
9149                                               const Value *C,
9150                                               const DebugLoc &DL, unsigned O) {
9151   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9152          "Expected inlined-at fields to agree");
9153   return new (DbgInfo->getAlloc())
9154       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromConst(C), {},
9155                  /*IsIndirect=*/false, DL, O,
9156                  /*IsVariadic=*/false);
9157 }
9158 
9159 /// FrameIndex
9160 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var,
9161                                                 DIExpression *Expr, unsigned FI,
9162                                                 bool IsIndirect,
9163                                                 const DebugLoc &DL,
9164                                                 unsigned O) {
9165   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9166          "Expected inlined-at fields to agree");
9167   return getFrameIndexDbgValue(Var, Expr, FI, {}, IsIndirect, DL, O);
9168 }
9169 
9170 /// FrameIndex with dependencies
9171 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var,
9172                                                 DIExpression *Expr, unsigned FI,
9173                                                 ArrayRef<SDNode *> Dependencies,
9174                                                 bool IsIndirect,
9175                                                 const DebugLoc &DL,
9176                                                 unsigned O) {
9177   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9178          "Expected inlined-at fields to agree");
9179   return new (DbgInfo->getAlloc())
9180       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromFrameIdx(FI),
9181                  Dependencies, IsIndirect, DL, O,
9182                  /*IsVariadic=*/false);
9183 }
9184 
9185 /// VReg
9186 SDDbgValue *SelectionDAG::getVRegDbgValue(DIVariable *Var, DIExpression *Expr,
9187                                           unsigned VReg, bool IsIndirect,
9188                                           const DebugLoc &DL, unsigned O) {
9189   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9190          "Expected inlined-at fields to agree");
9191   return new (DbgInfo->getAlloc())
9192       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromVReg(VReg),
9193                  {}, IsIndirect, DL, O,
9194                  /*IsVariadic=*/false);
9195 }
9196 
9197 SDDbgValue *SelectionDAG::getDbgValueList(DIVariable *Var, DIExpression *Expr,
9198                                           ArrayRef<SDDbgOperand> Locs,
9199                                           ArrayRef<SDNode *> Dependencies,
9200                                           bool IsIndirect, const DebugLoc &DL,
9201                                           unsigned O, bool IsVariadic) {
9202   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9203          "Expected inlined-at fields to agree");
9204   return new (DbgInfo->getAlloc())
9205       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, Locs, Dependencies, IsIndirect,
9206                  DL, O, IsVariadic);
9207 }
9208 
9209 void SelectionDAG::transferDbgValues(SDValue From, SDValue To,
9210                                      unsigned OffsetInBits, unsigned SizeInBits,
9211                                      bool InvalidateDbg) {
9212   SDNode *FromNode = From.getNode();
9213   SDNode *ToNode = To.getNode();
9214   assert(FromNode && ToNode && "Can't modify dbg values");
9215 
9216   // PR35338
9217   // TODO: assert(From != To && "Redundant dbg value transfer");
9218   // TODO: assert(FromNode != ToNode && "Intranode dbg value transfer");
9219   if (From == To || FromNode == ToNode)
9220     return;
9221 
9222   if (!FromNode->getHasDebugValue())
9223     return;
9224 
9225   SDDbgOperand FromLocOp =
9226       SDDbgOperand::fromNode(From.getNode(), From.getResNo());
9227   SDDbgOperand ToLocOp = SDDbgOperand::fromNode(To.getNode(), To.getResNo());
9228 
9229   SmallVector<SDDbgValue *, 2> ClonedDVs;
9230   for (SDDbgValue *Dbg : GetDbgValues(FromNode)) {
9231     if (Dbg->isInvalidated())
9232       continue;
9233 
9234     // TODO: assert(!Dbg->isInvalidated() && "Transfer of invalid dbg value");
9235 
9236     // Create a new location ops vector that is equal to the old vector, but
9237     // with each instance of FromLocOp replaced with ToLocOp.
9238     bool Changed = false;
9239     auto NewLocOps = Dbg->copyLocationOps();
9240     std::replace_if(
9241         NewLocOps.begin(), NewLocOps.end(),
9242         [&Changed, FromLocOp](const SDDbgOperand &Op) {
9243           bool Match = Op == FromLocOp;
9244           Changed |= Match;
9245           return Match;
9246         },
9247         ToLocOp);
9248     // Ignore this SDDbgValue if we didn't find a matching location.
9249     if (!Changed)
9250       continue;
9251 
9252     DIVariable *Var = Dbg->getVariable();
9253     auto *Expr = Dbg->getExpression();
9254     // If a fragment is requested, update the expression.
9255     if (SizeInBits) {
9256       // When splitting a larger (e.g., sign-extended) value whose
9257       // lower bits are described with an SDDbgValue, do not attempt
9258       // to transfer the SDDbgValue to the upper bits.
9259       if (auto FI = Expr->getFragmentInfo())
9260         if (OffsetInBits + SizeInBits > FI->SizeInBits)
9261           continue;
9262       auto Fragment = DIExpression::createFragmentExpression(Expr, OffsetInBits,
9263                                                              SizeInBits);
9264       if (!Fragment)
9265         continue;
9266       Expr = *Fragment;
9267     }
9268 
9269     auto AdditionalDependencies = Dbg->getAdditionalDependencies();
9270     // Clone the SDDbgValue and move it to To.
9271     SDDbgValue *Clone = getDbgValueList(
9272         Var, Expr, NewLocOps, AdditionalDependencies, Dbg->isIndirect(),
9273         Dbg->getDebugLoc(), std::max(ToNode->getIROrder(), Dbg->getOrder()),
9274         Dbg->isVariadic());
9275     ClonedDVs.push_back(Clone);
9276 
9277     if (InvalidateDbg) {
9278       // Invalidate value and indicate the SDDbgValue should not be emitted.
9279       Dbg->setIsInvalidated();
9280       Dbg->setIsEmitted();
9281     }
9282   }
9283 
9284   for (SDDbgValue *Dbg : ClonedDVs) {
9285     assert(is_contained(Dbg->getSDNodes(), ToNode) &&
9286            "Transferred DbgValues should depend on the new SDNode");
9287     AddDbgValue(Dbg, false);
9288   }
9289 }
9290 
9291 void SelectionDAG::salvageDebugInfo(SDNode &N) {
9292   if (!N.getHasDebugValue())
9293     return;
9294 
9295   SmallVector<SDDbgValue *, 2> ClonedDVs;
9296   for (auto DV : GetDbgValues(&N)) {
9297     if (DV->isInvalidated())
9298       continue;
9299     switch (N.getOpcode()) {
9300     default:
9301       break;
9302     case ISD::ADD:
9303       SDValue N0 = N.getOperand(0);
9304       SDValue N1 = N.getOperand(1);
9305       if (!isConstantIntBuildVectorOrConstantInt(N0) &&
9306           isConstantIntBuildVectorOrConstantInt(N1)) {
9307         uint64_t Offset = N.getConstantOperandVal(1);
9308 
9309         // Rewrite an ADD constant node into a DIExpression. Since we are
9310         // performing arithmetic to compute the variable's *value* in the
9311         // DIExpression, we need to mark the expression with a
9312         // DW_OP_stack_value.
9313         auto *DIExpr = DV->getExpression();
9314         auto NewLocOps = DV->copyLocationOps();
9315         bool Changed = false;
9316         for (size_t i = 0; i < NewLocOps.size(); ++i) {
9317           // We're not given a ResNo to compare against because the whole
9318           // node is going away. We know that any ISD::ADD only has one
9319           // result, so we can assume any node match is using the result.
9320           if (NewLocOps[i].getKind() != SDDbgOperand::SDNODE ||
9321               NewLocOps[i].getSDNode() != &N)
9322             continue;
9323           NewLocOps[i] = SDDbgOperand::fromNode(N0.getNode(), N0.getResNo());
9324           SmallVector<uint64_t, 3> ExprOps;
9325           DIExpression::appendOffset(ExprOps, Offset);
9326           DIExpr = DIExpression::appendOpsToArg(DIExpr, ExprOps, i, true);
9327           Changed = true;
9328         }
9329         (void)Changed;
9330         assert(Changed && "Salvage target doesn't use N");
9331 
9332         auto AdditionalDependencies = DV->getAdditionalDependencies();
9333         SDDbgValue *Clone = getDbgValueList(DV->getVariable(), DIExpr,
9334                                             NewLocOps, AdditionalDependencies,
9335                                             DV->isIndirect(), DV->getDebugLoc(),
9336                                             DV->getOrder(), DV->isVariadic());
9337         ClonedDVs.push_back(Clone);
9338         DV->setIsInvalidated();
9339         DV->setIsEmitted();
9340         LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting";
9341                    N0.getNode()->dumprFull(this);
9342                    dbgs() << " into " << *DIExpr << '\n');
9343       }
9344     }
9345   }
9346 
9347   for (SDDbgValue *Dbg : ClonedDVs) {
9348     assert(!Dbg->getSDNodes().empty() &&
9349            "Salvaged DbgValue should depend on a new SDNode");
9350     AddDbgValue(Dbg, false);
9351   }
9352 }
9353 
9354 /// Creates a SDDbgLabel node.
9355 SDDbgLabel *SelectionDAG::getDbgLabel(DILabel *Label,
9356                                       const DebugLoc &DL, unsigned O) {
9357   assert(cast<DILabel>(Label)->isValidLocationForIntrinsic(DL) &&
9358          "Expected inlined-at fields to agree");
9359   return new (DbgInfo->getAlloc()) SDDbgLabel(Label, DL, O);
9360 }
9361 
9362 namespace {
9363 
9364 /// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node
9365 /// pointed to by a use iterator is deleted, increment the use iterator
9366 /// so that it doesn't dangle.
9367 ///
9368 class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener {
9369   SDNode::use_iterator &UI;
9370   SDNode::use_iterator &UE;
9371 
9372   void NodeDeleted(SDNode *N, SDNode *E) override {
9373     // Increment the iterator as needed.
9374     while (UI != UE && N == *UI)
9375       ++UI;
9376   }
9377 
9378 public:
9379   RAUWUpdateListener(SelectionDAG &d,
9380                      SDNode::use_iterator &ui,
9381                      SDNode::use_iterator &ue)
9382     : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {}
9383 };
9384 
9385 } // end anonymous namespace
9386 
9387 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
9388 /// This can cause recursive merging of nodes in the DAG.
9389 ///
9390 /// This version assumes From has a single result value.
9391 ///
9392 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To) {
9393   SDNode *From = FromN.getNode();
9394   assert(From->getNumValues() == 1 && FromN.getResNo() == 0 &&
9395          "Cannot replace with this method!");
9396   assert(From != To.getNode() && "Cannot replace uses of with self");
9397 
9398   // Preserve Debug Values
9399   transferDbgValues(FromN, To);
9400 
9401   // Iterate over all the existing uses of From. New uses will be added
9402   // to the beginning of the use list, which we avoid visiting.
9403   // This specifically avoids visiting uses of From that arise while the
9404   // replacement is happening, because any such uses would be the result
9405   // of CSE: If an existing node looks like From after one of its operands
9406   // is replaced by To, we don't want to replace of all its users with To
9407   // too. See PR3018 for more info.
9408   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
9409   RAUWUpdateListener Listener(*this, UI, UE);
9410   while (UI != UE) {
9411     SDNode *User = *UI;
9412 
9413     // This node is about to morph, remove its old self from the CSE maps.
9414     RemoveNodeFromCSEMaps(User);
9415 
9416     // A user can appear in a use list multiple times, and when this
9417     // happens the uses are usually next to each other in the list.
9418     // To help reduce the number of CSE recomputations, process all
9419     // the uses of this user that we can find this way.
9420     do {
9421       SDUse &Use = UI.getUse();
9422       ++UI;
9423       Use.set(To);
9424       if (To->isDivergent() != From->isDivergent())
9425         updateDivergence(User);
9426     } while (UI != UE && *UI == User);
9427     // Now that we have modified User, add it back to the CSE maps.  If it
9428     // already exists there, recursively merge the results together.
9429     AddModifiedNodeToCSEMaps(User);
9430   }
9431 
9432   // If we just RAUW'd the root, take note.
9433   if (FromN == getRoot())
9434     setRoot(To);
9435 }
9436 
9437 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
9438 /// This can cause recursive merging of nodes in the DAG.
9439 ///
9440 /// This version assumes that for each value of From, there is a
9441 /// corresponding value in To in the same position with the same type.
9442 ///
9443 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To) {
9444 #ifndef NDEBUG
9445   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
9446     assert((!From->hasAnyUseOfValue(i) ||
9447             From->getValueType(i) == To->getValueType(i)) &&
9448            "Cannot use this version of ReplaceAllUsesWith!");
9449 #endif
9450 
9451   // Handle the trivial case.
9452   if (From == To)
9453     return;
9454 
9455   // Preserve Debug Info. Only do this if there's a use.
9456   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
9457     if (From->hasAnyUseOfValue(i)) {
9458       assert((i < To->getNumValues()) && "Invalid To location");
9459       transferDbgValues(SDValue(From, i), SDValue(To, i));
9460     }
9461 
9462   // Iterate over just the existing users of From. See the comments in
9463   // the ReplaceAllUsesWith above.
9464   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
9465   RAUWUpdateListener Listener(*this, UI, UE);
9466   while (UI != UE) {
9467     SDNode *User = *UI;
9468 
9469     // This node is about to morph, remove its old self from the CSE maps.
9470     RemoveNodeFromCSEMaps(User);
9471 
9472     // A user can appear in a use list multiple times, and when this
9473     // happens the uses are usually next to each other in the list.
9474     // To help reduce the number of CSE recomputations, process all
9475     // the uses of this user that we can find this way.
9476     do {
9477       SDUse &Use = UI.getUse();
9478       ++UI;
9479       Use.setNode(To);
9480       if (To->isDivergent() != From->isDivergent())
9481         updateDivergence(User);
9482     } while (UI != UE && *UI == User);
9483 
9484     // Now that we have modified User, add it back to the CSE maps.  If it
9485     // already exists there, recursively merge the results together.
9486     AddModifiedNodeToCSEMaps(User);
9487   }
9488 
9489   // If we just RAUW'd the root, take note.
9490   if (From == getRoot().getNode())
9491     setRoot(SDValue(To, getRoot().getResNo()));
9492 }
9493 
9494 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
9495 /// This can cause recursive merging of nodes in the DAG.
9496 ///
9497 /// This version can replace From with any result values.  To must match the
9498 /// number and types of values returned by From.
9499 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, const SDValue *To) {
9500   if (From->getNumValues() == 1)  // Handle the simple case efficiently.
9501     return ReplaceAllUsesWith(SDValue(From, 0), To[0]);
9502 
9503   // Preserve Debug Info.
9504   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
9505     transferDbgValues(SDValue(From, i), To[i]);
9506 
9507   // Iterate over just the existing users of From. See the comments in
9508   // the ReplaceAllUsesWith above.
9509   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
9510   RAUWUpdateListener Listener(*this, UI, UE);
9511   while (UI != UE) {
9512     SDNode *User = *UI;
9513 
9514     // This node is about to morph, remove its old self from the CSE maps.
9515     RemoveNodeFromCSEMaps(User);
9516 
9517     // A user can appear in a use list multiple times, and when this happens the
9518     // uses are usually next to each other in the list.  To help reduce the
9519     // number of CSE and divergence recomputations, process all the uses of this
9520     // user that we can find this way.
9521     bool To_IsDivergent = false;
9522     do {
9523       SDUse &Use = UI.getUse();
9524       const SDValue &ToOp = To[Use.getResNo()];
9525       ++UI;
9526       Use.set(ToOp);
9527       To_IsDivergent |= ToOp->isDivergent();
9528     } while (UI != UE && *UI == User);
9529 
9530     if (To_IsDivergent != From->isDivergent())
9531       updateDivergence(User);
9532 
9533     // Now that we have modified User, add it back to the CSE maps.  If it
9534     // already exists there, recursively merge the results together.
9535     AddModifiedNodeToCSEMaps(User);
9536   }
9537 
9538   // If we just RAUW'd the root, take note.
9539   if (From == getRoot().getNode())
9540     setRoot(SDValue(To[getRoot().getResNo()]));
9541 }
9542 
9543 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
9544 /// uses of other values produced by From.getNode() alone.  The Deleted
9545 /// vector is handled the same way as for ReplaceAllUsesWith.
9546 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To){
9547   // Handle the really simple, really trivial case efficiently.
9548   if (From == To) return;
9549 
9550   // Handle the simple, trivial, case efficiently.
9551   if (From.getNode()->getNumValues() == 1) {
9552     ReplaceAllUsesWith(From, To);
9553     return;
9554   }
9555 
9556   // Preserve Debug Info.
9557   transferDbgValues(From, To);
9558 
9559   // Iterate over just the existing users of From. See the comments in
9560   // the ReplaceAllUsesWith above.
9561   SDNode::use_iterator UI = From.getNode()->use_begin(),
9562                        UE = From.getNode()->use_end();
9563   RAUWUpdateListener Listener(*this, UI, UE);
9564   while (UI != UE) {
9565     SDNode *User = *UI;
9566     bool UserRemovedFromCSEMaps = false;
9567 
9568     // A user can appear in a use list multiple times, and when this
9569     // happens the uses are usually next to each other in the list.
9570     // To help reduce the number of CSE recomputations, process all
9571     // the uses of this user that we can find this way.
9572     do {
9573       SDUse &Use = UI.getUse();
9574 
9575       // Skip uses of different values from the same node.
9576       if (Use.getResNo() != From.getResNo()) {
9577         ++UI;
9578         continue;
9579       }
9580 
9581       // If this node hasn't been modified yet, it's still in the CSE maps,
9582       // so remove its old self from the CSE maps.
9583       if (!UserRemovedFromCSEMaps) {
9584         RemoveNodeFromCSEMaps(User);
9585         UserRemovedFromCSEMaps = true;
9586       }
9587 
9588       ++UI;
9589       Use.set(To);
9590       if (To->isDivergent() != From->isDivergent())
9591         updateDivergence(User);
9592     } while (UI != UE && *UI == User);
9593     // We are iterating over all uses of the From node, so if a use
9594     // doesn't use the specific value, no changes are made.
9595     if (!UserRemovedFromCSEMaps)
9596       continue;
9597 
9598     // Now that we have modified User, add it back to the CSE maps.  If it
9599     // already exists there, recursively merge the results together.
9600     AddModifiedNodeToCSEMaps(User);
9601   }
9602 
9603   // If we just RAUW'd the root, take note.
9604   if (From == getRoot())
9605     setRoot(To);
9606 }
9607 
9608 namespace {
9609 
9610   /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith
9611   /// to record information about a use.
9612   struct UseMemo {
9613     SDNode *User;
9614     unsigned Index;
9615     SDUse *Use;
9616   };
9617 
9618   /// operator< - Sort Memos by User.
9619   bool operator<(const UseMemo &L, const UseMemo &R) {
9620     return (intptr_t)L.User < (intptr_t)R.User;
9621   }
9622 
9623 } // end anonymous namespace
9624 
9625 bool SelectionDAG::calculateDivergence(SDNode *N) {
9626   if (TLI->isSDNodeAlwaysUniform(N)) {
9627     assert(!TLI->isSDNodeSourceOfDivergence(N, FLI, DA) &&
9628            "Conflicting divergence information!");
9629     return false;
9630   }
9631   if (TLI->isSDNodeSourceOfDivergence(N, FLI, DA))
9632     return true;
9633   for (auto &Op : N->ops()) {
9634     if (Op.Val.getValueType() != MVT::Other && Op.getNode()->isDivergent())
9635       return true;
9636   }
9637   return false;
9638 }
9639 
9640 void SelectionDAG::updateDivergence(SDNode *N) {
9641   SmallVector<SDNode *, 16> Worklist(1, N);
9642   do {
9643     N = Worklist.pop_back_val();
9644     bool IsDivergent = calculateDivergence(N);
9645     if (N->SDNodeBits.IsDivergent != IsDivergent) {
9646       N->SDNodeBits.IsDivergent = IsDivergent;
9647       llvm::append_range(Worklist, N->uses());
9648     }
9649   } while (!Worklist.empty());
9650 }
9651 
9652 void SelectionDAG::CreateTopologicalOrder(std::vector<SDNode *> &Order) {
9653   DenseMap<SDNode *, unsigned> Degree;
9654   Order.reserve(AllNodes.size());
9655   for (auto &N : allnodes()) {
9656     unsigned NOps = N.getNumOperands();
9657     Degree[&N] = NOps;
9658     if (0 == NOps)
9659       Order.push_back(&N);
9660   }
9661   for (size_t I = 0; I != Order.size(); ++I) {
9662     SDNode *N = Order[I];
9663     for (auto U : N->uses()) {
9664       unsigned &UnsortedOps = Degree[U];
9665       if (0 == --UnsortedOps)
9666         Order.push_back(U);
9667     }
9668   }
9669 }
9670 
9671 #ifndef NDEBUG
9672 void SelectionDAG::VerifyDAGDivergence() {
9673   std::vector<SDNode *> TopoOrder;
9674   CreateTopologicalOrder(TopoOrder);
9675   for (auto *N : TopoOrder) {
9676     assert(calculateDivergence(N) == N->isDivergent() &&
9677            "Divergence bit inconsistency detected");
9678   }
9679 }
9680 #endif
9681 
9682 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving
9683 /// uses of other values produced by From.getNode() alone.  The same value
9684 /// may appear in both the From and To list.  The Deleted vector is
9685 /// handled the same way as for ReplaceAllUsesWith.
9686 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From,
9687                                               const SDValue *To,
9688                                               unsigned Num){
9689   // Handle the simple, trivial case efficiently.
9690   if (Num == 1)
9691     return ReplaceAllUsesOfValueWith(*From, *To);
9692 
9693   transferDbgValues(*From, *To);
9694 
9695   // Read up all the uses and make records of them. This helps
9696   // processing new uses that are introduced during the
9697   // replacement process.
9698   SmallVector<UseMemo, 4> Uses;
9699   for (unsigned i = 0; i != Num; ++i) {
9700     unsigned FromResNo = From[i].getResNo();
9701     SDNode *FromNode = From[i].getNode();
9702     for (SDNode::use_iterator UI = FromNode->use_begin(),
9703          E = FromNode->use_end(); UI != E; ++UI) {
9704       SDUse &Use = UI.getUse();
9705       if (Use.getResNo() == FromResNo) {
9706         UseMemo Memo = { *UI, i, &Use };
9707         Uses.push_back(Memo);
9708       }
9709     }
9710   }
9711 
9712   // Sort the uses, so that all the uses from a given User are together.
9713   llvm::sort(Uses);
9714 
9715   for (unsigned UseIndex = 0, UseIndexEnd = Uses.size();
9716        UseIndex != UseIndexEnd; ) {
9717     // We know that this user uses some value of From.  If it is the right
9718     // value, update it.
9719     SDNode *User = Uses[UseIndex].User;
9720 
9721     // This node is about to morph, remove its old self from the CSE maps.
9722     RemoveNodeFromCSEMaps(User);
9723 
9724     // The Uses array is sorted, so all the uses for a given User
9725     // are next to each other in the list.
9726     // To help reduce the number of CSE recomputations, process all
9727     // the uses of this user that we can find this way.
9728     do {
9729       unsigned i = Uses[UseIndex].Index;
9730       SDUse &Use = *Uses[UseIndex].Use;
9731       ++UseIndex;
9732 
9733       Use.set(To[i]);
9734     } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User);
9735 
9736     // Now that we have modified User, add it back to the CSE maps.  If it
9737     // already exists there, recursively merge the results together.
9738     AddModifiedNodeToCSEMaps(User);
9739   }
9740 }
9741 
9742 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
9743 /// based on their topological order. It returns the maximum id and a vector
9744 /// of the SDNodes* in assigned order by reference.
9745 unsigned SelectionDAG::AssignTopologicalOrder() {
9746   unsigned DAGSize = 0;
9747 
9748   // SortedPos tracks the progress of the algorithm. Nodes before it are
9749   // sorted, nodes after it are unsorted. When the algorithm completes
9750   // it is at the end of the list.
9751   allnodes_iterator SortedPos = allnodes_begin();
9752 
9753   // Visit all the nodes. Move nodes with no operands to the front of
9754   // the list immediately. Annotate nodes that do have operands with their
9755   // operand count. Before we do this, the Node Id fields of the nodes
9756   // may contain arbitrary values. After, the Node Id fields for nodes
9757   // before SortedPos will contain the topological sort index, and the
9758   // Node Id fields for nodes At SortedPos and after will contain the
9759   // count of outstanding operands.
9760   for (SDNode &N : llvm::make_early_inc_range(allnodes())) {
9761     checkForCycles(&N, this);
9762     unsigned Degree = N.getNumOperands();
9763     if (Degree == 0) {
9764       // A node with no uses, add it to the result array immediately.
9765       N.setNodeId(DAGSize++);
9766       allnodes_iterator Q(&N);
9767       if (Q != SortedPos)
9768         SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q));
9769       assert(SortedPos != AllNodes.end() && "Overran node list");
9770       ++SortedPos;
9771     } else {
9772       // Temporarily use the Node Id as scratch space for the degree count.
9773       N.setNodeId(Degree);
9774     }
9775   }
9776 
9777   // Visit all the nodes. As we iterate, move nodes into sorted order,
9778   // such that by the time the end is reached all nodes will be sorted.
9779   for (SDNode &Node : allnodes()) {
9780     SDNode *N = &Node;
9781     checkForCycles(N, this);
9782     // N is in sorted position, so all its uses have one less operand
9783     // that needs to be sorted.
9784     for (SDNode *P : N->uses()) {
9785       unsigned Degree = P->getNodeId();
9786       assert(Degree != 0 && "Invalid node degree");
9787       --Degree;
9788       if (Degree == 0) {
9789         // All of P's operands are sorted, so P may sorted now.
9790         P->setNodeId(DAGSize++);
9791         if (P->getIterator() != SortedPos)
9792           SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P));
9793         assert(SortedPos != AllNodes.end() && "Overran node list");
9794         ++SortedPos;
9795       } else {
9796         // Update P's outstanding operand count.
9797         P->setNodeId(Degree);
9798       }
9799     }
9800     if (Node.getIterator() == SortedPos) {
9801 #ifndef NDEBUG
9802       allnodes_iterator I(N);
9803       SDNode *S = &*++I;
9804       dbgs() << "Overran sorted position:\n";
9805       S->dumprFull(this); dbgs() << "\n";
9806       dbgs() << "Checking if this is due to cycles\n";
9807       checkForCycles(this, true);
9808 #endif
9809       llvm_unreachable(nullptr);
9810     }
9811   }
9812 
9813   assert(SortedPos == AllNodes.end() &&
9814          "Topological sort incomplete!");
9815   assert(AllNodes.front().getOpcode() == ISD::EntryToken &&
9816          "First node in topological sort is not the entry token!");
9817   assert(AllNodes.front().getNodeId() == 0 &&
9818          "First node in topological sort has non-zero id!");
9819   assert(AllNodes.front().getNumOperands() == 0 &&
9820          "First node in topological sort has operands!");
9821   assert(AllNodes.back().getNodeId() == (int)DAGSize-1 &&
9822          "Last node in topologic sort has unexpected id!");
9823   assert(AllNodes.back().use_empty() &&
9824          "Last node in topologic sort has users!");
9825   assert(DAGSize == allnodes_size() && "Node count mismatch!");
9826   return DAGSize;
9827 }
9828 
9829 /// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the
9830 /// value is produced by SD.
9831 void SelectionDAG::AddDbgValue(SDDbgValue *DB, bool isParameter) {
9832   for (SDNode *SD : DB->getSDNodes()) {
9833     if (!SD)
9834       continue;
9835     assert(DbgInfo->getSDDbgValues(SD).empty() || SD->getHasDebugValue());
9836     SD->setHasDebugValue(true);
9837   }
9838   DbgInfo->add(DB, isParameter);
9839 }
9840 
9841 void SelectionDAG::AddDbgLabel(SDDbgLabel *DB) { DbgInfo->add(DB); }
9842 
9843 SDValue SelectionDAG::makeEquivalentMemoryOrdering(SDValue OldChain,
9844                                                    SDValue NewMemOpChain) {
9845   assert(isa<MemSDNode>(NewMemOpChain) && "Expected a memop node");
9846   assert(NewMemOpChain.getValueType() == MVT::Other && "Expected a token VT");
9847   // The new memory operation must have the same position as the old load in
9848   // terms of memory dependency. Create a TokenFactor for the old load and new
9849   // memory operation and update uses of the old load's output chain to use that
9850   // TokenFactor.
9851   if (OldChain == NewMemOpChain || OldChain.use_empty())
9852     return NewMemOpChain;
9853 
9854   SDValue TokenFactor = getNode(ISD::TokenFactor, SDLoc(OldChain), MVT::Other,
9855                                 OldChain, NewMemOpChain);
9856   ReplaceAllUsesOfValueWith(OldChain, TokenFactor);
9857   UpdateNodeOperands(TokenFactor.getNode(), OldChain, NewMemOpChain);
9858   return TokenFactor;
9859 }
9860 
9861 SDValue SelectionDAG::makeEquivalentMemoryOrdering(LoadSDNode *OldLoad,
9862                                                    SDValue NewMemOp) {
9863   assert(isa<MemSDNode>(NewMemOp.getNode()) && "Expected a memop node");
9864   SDValue OldChain = SDValue(OldLoad, 1);
9865   SDValue NewMemOpChain = NewMemOp.getValue(1);
9866   return makeEquivalentMemoryOrdering(OldChain, NewMemOpChain);
9867 }
9868 
9869 SDValue SelectionDAG::getSymbolFunctionGlobalAddress(SDValue Op,
9870                                                      Function **OutFunction) {
9871   assert(isa<ExternalSymbolSDNode>(Op) && "Node should be an ExternalSymbol");
9872 
9873   auto *Symbol = cast<ExternalSymbolSDNode>(Op)->getSymbol();
9874   auto *Module = MF->getFunction().getParent();
9875   auto *Function = Module->getFunction(Symbol);
9876 
9877   if (OutFunction != nullptr)
9878       *OutFunction = Function;
9879 
9880   if (Function != nullptr) {
9881     auto PtrTy = TLI->getPointerTy(getDataLayout(), Function->getAddressSpace());
9882     return getGlobalAddress(Function, SDLoc(Op), PtrTy);
9883   }
9884 
9885   std::string ErrorStr;
9886   raw_string_ostream ErrorFormatter(ErrorStr);
9887   ErrorFormatter << "Undefined external symbol ";
9888   ErrorFormatter << '"' << Symbol << '"';
9889   report_fatal_error(Twine(ErrorFormatter.str()));
9890 }
9891 
9892 //===----------------------------------------------------------------------===//
9893 //                              SDNode Class
9894 //===----------------------------------------------------------------------===//
9895 
9896 bool llvm::isNullConstant(SDValue V) {
9897   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
9898   return Const != nullptr && Const->isZero();
9899 }
9900 
9901 bool llvm::isNullFPConstant(SDValue V) {
9902   ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V);
9903   return Const != nullptr && Const->isZero() && !Const->isNegative();
9904 }
9905 
9906 bool llvm::isAllOnesConstant(SDValue V) {
9907   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
9908   return Const != nullptr && Const->isAllOnes();
9909 }
9910 
9911 bool llvm::isOneConstant(SDValue V) {
9912   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
9913   return Const != nullptr && Const->isOne();
9914 }
9915 
9916 SDValue llvm::peekThroughBitcasts(SDValue V) {
9917   while (V.getOpcode() == ISD::BITCAST)
9918     V = V.getOperand(0);
9919   return V;
9920 }
9921 
9922 SDValue llvm::peekThroughOneUseBitcasts(SDValue V) {
9923   while (V.getOpcode() == ISD::BITCAST && V.getOperand(0).hasOneUse())
9924     V = V.getOperand(0);
9925   return V;
9926 }
9927 
9928 SDValue llvm::peekThroughExtractSubvectors(SDValue V) {
9929   while (V.getOpcode() == ISD::EXTRACT_SUBVECTOR)
9930     V = V.getOperand(0);
9931   return V;
9932 }
9933 
9934 bool llvm::isBitwiseNot(SDValue V, bool AllowUndefs) {
9935   if (V.getOpcode() != ISD::XOR)
9936     return false;
9937   V = peekThroughBitcasts(V.getOperand(1));
9938   unsigned NumBits = V.getScalarValueSizeInBits();
9939   ConstantSDNode *C =
9940       isConstOrConstSplat(V, AllowUndefs, /*AllowTruncation*/ true);
9941   return C && (C->getAPIntValue().countTrailingOnes() >= NumBits);
9942 }
9943 
9944 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, bool AllowUndefs,
9945                                           bool AllowTruncation) {
9946   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
9947     return CN;
9948 
9949   // SplatVectors can truncate their operands. Ignore that case here unless
9950   // AllowTruncation is set.
9951   if (N->getOpcode() == ISD::SPLAT_VECTOR) {
9952     EVT VecEltVT = N->getValueType(0).getVectorElementType();
9953     if (auto *CN = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
9954       EVT CVT = CN->getValueType(0);
9955       assert(CVT.bitsGE(VecEltVT) && "Illegal splat_vector element extension");
9956       if (AllowTruncation || CVT == VecEltVT)
9957         return CN;
9958     }
9959   }
9960 
9961   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
9962     BitVector UndefElements;
9963     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
9964 
9965     // BuildVectors can truncate their operands. Ignore that case here unless
9966     // AllowTruncation is set.
9967     if (CN && (UndefElements.none() || AllowUndefs)) {
9968       EVT CVT = CN->getValueType(0);
9969       EVT NSVT = N.getValueType().getScalarType();
9970       assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension");
9971       if (AllowTruncation || (CVT == NSVT))
9972         return CN;
9973     }
9974   }
9975 
9976   return nullptr;
9977 }
9978 
9979 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, const APInt &DemandedElts,
9980                                           bool AllowUndefs,
9981                                           bool AllowTruncation) {
9982   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
9983     return CN;
9984 
9985   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
9986     BitVector UndefElements;
9987     ConstantSDNode *CN = BV->getConstantSplatNode(DemandedElts, &UndefElements);
9988 
9989     // BuildVectors can truncate their operands. Ignore that case here unless
9990     // AllowTruncation is set.
9991     if (CN && (UndefElements.none() || AllowUndefs)) {
9992       EVT CVT = CN->getValueType(0);
9993       EVT NSVT = N.getValueType().getScalarType();
9994       assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension");
9995       if (AllowTruncation || (CVT == NSVT))
9996         return CN;
9997     }
9998   }
9999 
10000   return nullptr;
10001 }
10002 
10003 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N, bool AllowUndefs) {
10004   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
10005     return CN;
10006 
10007   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
10008     BitVector UndefElements;
10009     ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
10010     if (CN && (UndefElements.none() || AllowUndefs))
10011       return CN;
10012   }
10013 
10014   if (N.getOpcode() == ISD::SPLAT_VECTOR)
10015     if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N.getOperand(0)))
10016       return CN;
10017 
10018   return nullptr;
10019 }
10020 
10021 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N,
10022                                               const APInt &DemandedElts,
10023                                               bool AllowUndefs) {
10024   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
10025     return CN;
10026 
10027   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
10028     BitVector UndefElements;
10029     ConstantFPSDNode *CN =
10030         BV->getConstantFPSplatNode(DemandedElts, &UndefElements);
10031     if (CN && (UndefElements.none() || AllowUndefs))
10032       return CN;
10033   }
10034 
10035   return nullptr;
10036 }
10037 
10038 bool llvm::isNullOrNullSplat(SDValue N, bool AllowUndefs) {
10039   // TODO: may want to use peekThroughBitcast() here.
10040   ConstantSDNode *C =
10041       isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation=*/true);
10042   return C && C->isZero();
10043 }
10044 
10045 bool llvm::isOneOrOneSplat(SDValue N, bool AllowUndefs) {
10046   // TODO: may want to use peekThroughBitcast() here.
10047   unsigned BitWidth = N.getScalarValueSizeInBits();
10048   ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs);
10049   return C && C->isOne() && C->getValueSizeInBits(0) == BitWidth;
10050 }
10051 
10052 bool llvm::isAllOnesOrAllOnesSplat(SDValue N, bool AllowUndefs) {
10053   N = peekThroughBitcasts(N);
10054   unsigned BitWidth = N.getScalarValueSizeInBits();
10055   ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs);
10056   return C && C->isAllOnes() && C->getValueSizeInBits(0) == BitWidth;
10057 }
10058 
10059 HandleSDNode::~HandleSDNode() {
10060   DropOperands();
10061 }
10062 
10063 GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, unsigned Order,
10064                                          const DebugLoc &DL,
10065                                          const GlobalValue *GA, EVT VT,
10066                                          int64_t o, unsigned TF)
10067     : SDNode(Opc, Order, DL, getSDVTList(VT)), Offset(o), TargetFlags(TF) {
10068   TheGlobal = GA;
10069 }
10070 
10071 AddrSpaceCastSDNode::AddrSpaceCastSDNode(unsigned Order, const DebugLoc &dl,
10072                                          EVT VT, unsigned SrcAS,
10073                                          unsigned DestAS)
10074     : SDNode(ISD::ADDRSPACECAST, Order, dl, getSDVTList(VT)),
10075       SrcAddrSpace(SrcAS), DestAddrSpace(DestAS) {}
10076 
10077 MemSDNode::MemSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl,
10078                      SDVTList VTs, EVT memvt, MachineMemOperand *mmo)
10079     : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MMO(mmo) {
10080   MemSDNodeBits.IsVolatile = MMO->isVolatile();
10081   MemSDNodeBits.IsNonTemporal = MMO->isNonTemporal();
10082   MemSDNodeBits.IsDereferenceable = MMO->isDereferenceable();
10083   MemSDNodeBits.IsInvariant = MMO->isInvariant();
10084 
10085   // We check here that the size of the memory operand fits within the size of
10086   // the MMO. This is because the MMO might indicate only a possible address
10087   // range instead of specifying the affected memory addresses precisely.
10088   // TODO: Make MachineMemOperands aware of scalable vectors.
10089   assert(memvt.getStoreSize().getKnownMinSize() <= MMO->getSize() &&
10090          "Size mismatch!");
10091 }
10092 
10093 /// Profile - Gather unique data for the node.
10094 ///
10095 void SDNode::Profile(FoldingSetNodeID &ID) const {
10096   AddNodeIDNode(ID, this);
10097 }
10098 
10099 namespace {
10100 
10101   struct EVTArray {
10102     std::vector<EVT> VTs;
10103 
10104     EVTArray() {
10105       VTs.reserve(MVT::VALUETYPE_SIZE);
10106       for (unsigned i = 0; i < MVT::VALUETYPE_SIZE; ++i)
10107         VTs.push_back(MVT((MVT::SimpleValueType)i));
10108     }
10109   };
10110 
10111 } // end anonymous namespace
10112 
10113 static ManagedStatic<std::set<EVT, EVT::compareRawBits>> EVTs;
10114 static ManagedStatic<EVTArray> SimpleVTArray;
10115 static ManagedStatic<sys::SmartMutex<true>> VTMutex;
10116 
10117 /// getValueTypeList - Return a pointer to the specified value type.
10118 ///
10119 const EVT *SDNode::getValueTypeList(EVT VT) {
10120   if (VT.isExtended()) {
10121     sys::SmartScopedLock<true> Lock(*VTMutex);
10122     return &(*EVTs->insert(VT).first);
10123   }
10124   assert(VT.getSimpleVT() < MVT::VALUETYPE_SIZE && "Value type out of range!");
10125   return &SimpleVTArray->VTs[VT.getSimpleVT().SimpleTy];
10126 }
10127 
10128 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
10129 /// indicated value.  This method ignores uses of other values defined by this
10130 /// operation.
10131 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
10132   assert(Value < getNumValues() && "Bad value!");
10133 
10134   // TODO: Only iterate over uses of a given value of the node
10135   for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
10136     if (UI.getUse().getResNo() == Value) {
10137       if (NUses == 0)
10138         return false;
10139       --NUses;
10140     }
10141   }
10142 
10143   // Found exactly the right number of uses?
10144   return NUses == 0;
10145 }
10146 
10147 /// hasAnyUseOfValue - Return true if there are any use of the indicated
10148 /// value. This method ignores uses of other values defined by this operation.
10149 bool SDNode::hasAnyUseOfValue(unsigned Value) const {
10150   assert(Value < getNumValues() && "Bad value!");
10151 
10152   for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI)
10153     if (UI.getUse().getResNo() == Value)
10154       return true;
10155 
10156   return false;
10157 }
10158 
10159 /// isOnlyUserOf - Return true if this node is the only use of N.
10160 bool SDNode::isOnlyUserOf(const SDNode *N) const {
10161   bool Seen = false;
10162   for (const SDNode *User : N->uses()) {
10163     if (User == this)
10164       Seen = true;
10165     else
10166       return false;
10167   }
10168 
10169   return Seen;
10170 }
10171 
10172 /// Return true if the only users of N are contained in Nodes.
10173 bool SDNode::areOnlyUsersOf(ArrayRef<const SDNode *> Nodes, const SDNode *N) {
10174   bool Seen = false;
10175   for (const SDNode *User : N->uses()) {
10176     if (llvm::is_contained(Nodes, User))
10177       Seen = true;
10178     else
10179       return false;
10180   }
10181 
10182   return Seen;
10183 }
10184 
10185 /// isOperand - Return true if this node is an operand of N.
10186 bool SDValue::isOperandOf(const SDNode *N) const {
10187   return is_contained(N->op_values(), *this);
10188 }
10189 
10190 bool SDNode::isOperandOf(const SDNode *N) const {
10191   return any_of(N->op_values(),
10192                 [this](SDValue Op) { return this == Op.getNode(); });
10193 }
10194 
10195 /// reachesChainWithoutSideEffects - Return true if this operand (which must
10196 /// be a chain) reaches the specified operand without crossing any
10197 /// side-effecting instructions on any chain path.  In practice, this looks
10198 /// through token factors and non-volatile loads.  In order to remain efficient,
10199 /// this only looks a couple of nodes in, it does not do an exhaustive search.
10200 ///
10201 /// Note that we only need to examine chains when we're searching for
10202 /// side-effects; SelectionDAG requires that all side-effects are represented
10203 /// by chains, even if another operand would force a specific ordering. This
10204 /// constraint is necessary to allow transformations like splitting loads.
10205 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest,
10206                                              unsigned Depth) const {
10207   if (*this == Dest) return true;
10208 
10209   // Don't search too deeply, we just want to be able to see through
10210   // TokenFactor's etc.
10211   if (Depth == 0) return false;
10212 
10213   // If this is a token factor, all inputs to the TF happen in parallel.
10214   if (getOpcode() == ISD::TokenFactor) {
10215     // First, try a shallow search.
10216     if (is_contained((*this)->ops(), Dest)) {
10217       // We found the chain we want as an operand of this TokenFactor.
10218       // Essentially, we reach the chain without side-effects if we could
10219       // serialize the TokenFactor into a simple chain of operations with
10220       // Dest as the last operation. This is automatically true if the
10221       // chain has one use: there are no other ordering constraints.
10222       // If the chain has more than one use, we give up: some other
10223       // use of Dest might force a side-effect between Dest and the current
10224       // node.
10225       if (Dest.hasOneUse())
10226         return true;
10227     }
10228     // Next, try a deep search: check whether every operand of the TokenFactor
10229     // reaches Dest.
10230     return llvm::all_of((*this)->ops(), [=](SDValue Op) {
10231       return Op.reachesChainWithoutSideEffects(Dest, Depth - 1);
10232     });
10233   }
10234 
10235   // Loads don't have side effects, look through them.
10236   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
10237     if (Ld->isUnordered())
10238       return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
10239   }
10240   return false;
10241 }
10242 
10243 bool SDNode::hasPredecessor(const SDNode *N) const {
10244   SmallPtrSet<const SDNode *, 32> Visited;
10245   SmallVector<const SDNode *, 16> Worklist;
10246   Worklist.push_back(this);
10247   return hasPredecessorHelper(N, Visited, Worklist);
10248 }
10249 
10250 void SDNode::intersectFlagsWith(const SDNodeFlags Flags) {
10251   this->Flags.intersectWith(Flags);
10252 }
10253 
10254 SDValue
10255 SelectionDAG::matchBinOpReduction(SDNode *Extract, ISD::NodeType &BinOp,
10256                                   ArrayRef<ISD::NodeType> CandidateBinOps,
10257                                   bool AllowPartials) {
10258   // The pattern must end in an extract from index 0.
10259   if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10260       !isNullConstant(Extract->getOperand(1)))
10261     return SDValue();
10262 
10263   // Match against one of the candidate binary ops.
10264   SDValue Op = Extract->getOperand(0);
10265   if (llvm::none_of(CandidateBinOps, [Op](ISD::NodeType BinOp) {
10266         return Op.getOpcode() == unsigned(BinOp);
10267       }))
10268     return SDValue();
10269 
10270   // Floating-point reductions may require relaxed constraints on the final step
10271   // of the reduction because they may reorder intermediate operations.
10272   unsigned CandidateBinOp = Op.getOpcode();
10273   if (Op.getValueType().isFloatingPoint()) {
10274     SDNodeFlags Flags = Op->getFlags();
10275     switch (CandidateBinOp) {
10276     case ISD::FADD:
10277       if (!Flags.hasNoSignedZeros() || !Flags.hasAllowReassociation())
10278         return SDValue();
10279       break;
10280     default:
10281       llvm_unreachable("Unhandled FP opcode for binop reduction");
10282     }
10283   }
10284 
10285   // Matching failed - attempt to see if we did enough stages that a partial
10286   // reduction from a subvector is possible.
10287   auto PartialReduction = [&](SDValue Op, unsigned NumSubElts) {
10288     if (!AllowPartials || !Op)
10289       return SDValue();
10290     EVT OpVT = Op.getValueType();
10291     EVT OpSVT = OpVT.getScalarType();
10292     EVT SubVT = EVT::getVectorVT(*getContext(), OpSVT, NumSubElts);
10293     if (!TLI->isExtractSubvectorCheap(SubVT, OpVT, 0))
10294       return SDValue();
10295     BinOp = (ISD::NodeType)CandidateBinOp;
10296     return getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(Op), SubVT, Op,
10297                    getVectorIdxConstant(0, SDLoc(Op)));
10298   };
10299 
10300   // At each stage, we're looking for something that looks like:
10301   // %s = shufflevector <8 x i32> %op, <8 x i32> undef,
10302   //                    <8 x i32> <i32 2, i32 3, i32 undef, i32 undef,
10303   //                               i32 undef, i32 undef, i32 undef, i32 undef>
10304   // %a = binop <8 x i32> %op, %s
10305   // Where the mask changes according to the stage. E.g. for a 3-stage pyramid,
10306   // we expect something like:
10307   // <4,5,6,7,u,u,u,u>
10308   // <2,3,u,u,u,u,u,u>
10309   // <1,u,u,u,u,u,u,u>
10310   // While a partial reduction match would be:
10311   // <2,3,u,u,u,u,u,u>
10312   // <1,u,u,u,u,u,u,u>
10313   unsigned Stages = Log2_32(Op.getValueType().getVectorNumElements());
10314   SDValue PrevOp;
10315   for (unsigned i = 0; i < Stages; ++i) {
10316     unsigned MaskEnd = (1 << i);
10317 
10318     if (Op.getOpcode() != CandidateBinOp)
10319       return PartialReduction(PrevOp, MaskEnd);
10320 
10321     SDValue Op0 = Op.getOperand(0);
10322     SDValue Op1 = Op.getOperand(1);
10323 
10324     ShuffleVectorSDNode *Shuffle = dyn_cast<ShuffleVectorSDNode>(Op0);
10325     if (Shuffle) {
10326       Op = Op1;
10327     } else {
10328       Shuffle = dyn_cast<ShuffleVectorSDNode>(Op1);
10329       Op = Op0;
10330     }
10331 
10332     // The first operand of the shuffle should be the same as the other operand
10333     // of the binop.
10334     if (!Shuffle || Shuffle->getOperand(0) != Op)
10335       return PartialReduction(PrevOp, MaskEnd);
10336 
10337     // Verify the shuffle has the expected (at this stage of the pyramid) mask.
10338     for (int Index = 0; Index < (int)MaskEnd; ++Index)
10339       if (Shuffle->getMaskElt(Index) != (int)(MaskEnd + Index))
10340         return PartialReduction(PrevOp, MaskEnd);
10341 
10342     PrevOp = Op;
10343   }
10344 
10345   // Handle subvector reductions, which tend to appear after the shuffle
10346   // reduction stages.
10347   while (Op.getOpcode() == CandidateBinOp) {
10348     unsigned NumElts = Op.getValueType().getVectorNumElements();
10349     SDValue Op0 = Op.getOperand(0);
10350     SDValue Op1 = Op.getOperand(1);
10351     if (Op0.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
10352         Op1.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
10353         Op0.getOperand(0) != Op1.getOperand(0))
10354       break;
10355     SDValue Src = Op0.getOperand(0);
10356     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
10357     if (NumSrcElts != (2 * NumElts))
10358       break;
10359     if (!(Op0.getConstantOperandAPInt(1) == 0 &&
10360           Op1.getConstantOperandAPInt(1) == NumElts) &&
10361         !(Op1.getConstantOperandAPInt(1) == 0 &&
10362           Op0.getConstantOperandAPInt(1) == NumElts))
10363       break;
10364     Op = Src;
10365   }
10366 
10367   BinOp = (ISD::NodeType)CandidateBinOp;
10368   return Op;
10369 }
10370 
10371 SDValue SelectionDAG::UnrollVectorOp(SDNode *N, unsigned ResNE) {
10372   assert(N->getNumValues() == 1 &&
10373          "Can't unroll a vector with multiple results!");
10374 
10375   EVT VT = N->getValueType(0);
10376   unsigned NE = VT.getVectorNumElements();
10377   EVT EltVT = VT.getVectorElementType();
10378   SDLoc dl(N);
10379 
10380   SmallVector<SDValue, 8> Scalars;
10381   SmallVector<SDValue, 4> Operands(N->getNumOperands());
10382 
10383   // If ResNE is 0, fully unroll the vector op.
10384   if (ResNE == 0)
10385     ResNE = NE;
10386   else if (NE > ResNE)
10387     NE = ResNE;
10388 
10389   unsigned i;
10390   for (i= 0; i != NE; ++i) {
10391     for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) {
10392       SDValue Operand = N->getOperand(j);
10393       EVT OperandVT = Operand.getValueType();
10394       if (OperandVT.isVector()) {
10395         // A vector operand; extract a single element.
10396         EVT OperandEltVT = OperandVT.getVectorElementType();
10397         Operands[j] = getNode(ISD::EXTRACT_VECTOR_ELT, dl, OperandEltVT,
10398                               Operand, getVectorIdxConstant(i, dl));
10399       } else {
10400         // A scalar operand; just use it as is.
10401         Operands[j] = Operand;
10402       }
10403     }
10404 
10405     switch (N->getOpcode()) {
10406     default: {
10407       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands,
10408                                 N->getFlags()));
10409       break;
10410     }
10411     case ISD::VSELECT:
10412       Scalars.push_back(getNode(ISD::SELECT, dl, EltVT, Operands));
10413       break;
10414     case ISD::SHL:
10415     case ISD::SRA:
10416     case ISD::SRL:
10417     case ISD::ROTL:
10418     case ISD::ROTR:
10419       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0],
10420                                getShiftAmountOperand(Operands[0].getValueType(),
10421                                                      Operands[1])));
10422       break;
10423     case ISD::SIGN_EXTEND_INREG: {
10424       EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType();
10425       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT,
10426                                 Operands[0],
10427                                 getValueType(ExtVT)));
10428     }
10429     }
10430   }
10431 
10432   for (; i < ResNE; ++i)
10433     Scalars.push_back(getUNDEF(EltVT));
10434 
10435   EVT VecVT = EVT::getVectorVT(*getContext(), EltVT, ResNE);
10436   return getBuildVector(VecVT, dl, Scalars);
10437 }
10438 
10439 std::pair<SDValue, SDValue> SelectionDAG::UnrollVectorOverflowOp(
10440     SDNode *N, unsigned ResNE) {
10441   unsigned Opcode = N->getOpcode();
10442   assert((Opcode == ISD::UADDO || Opcode == ISD::SADDO ||
10443           Opcode == ISD::USUBO || Opcode == ISD::SSUBO ||
10444           Opcode == ISD::UMULO || Opcode == ISD::SMULO) &&
10445          "Expected an overflow opcode");
10446 
10447   EVT ResVT = N->getValueType(0);
10448   EVT OvVT = N->getValueType(1);
10449   EVT ResEltVT = ResVT.getVectorElementType();
10450   EVT OvEltVT = OvVT.getVectorElementType();
10451   SDLoc dl(N);
10452 
10453   // If ResNE is 0, fully unroll the vector op.
10454   unsigned NE = ResVT.getVectorNumElements();
10455   if (ResNE == 0)
10456     ResNE = NE;
10457   else if (NE > ResNE)
10458     NE = ResNE;
10459 
10460   SmallVector<SDValue, 8> LHSScalars;
10461   SmallVector<SDValue, 8> RHSScalars;
10462   ExtractVectorElements(N->getOperand(0), LHSScalars, 0, NE);
10463   ExtractVectorElements(N->getOperand(1), RHSScalars, 0, NE);
10464 
10465   EVT SVT = TLI->getSetCCResultType(getDataLayout(), *getContext(), ResEltVT);
10466   SDVTList VTs = getVTList(ResEltVT, SVT);
10467   SmallVector<SDValue, 8> ResScalars;
10468   SmallVector<SDValue, 8> OvScalars;
10469   for (unsigned i = 0; i < NE; ++i) {
10470     SDValue Res = getNode(Opcode, dl, VTs, LHSScalars[i], RHSScalars[i]);
10471     SDValue Ov =
10472         getSelect(dl, OvEltVT, Res.getValue(1),
10473                   getBoolConstant(true, dl, OvEltVT, ResVT),
10474                   getConstant(0, dl, OvEltVT));
10475 
10476     ResScalars.push_back(Res);
10477     OvScalars.push_back(Ov);
10478   }
10479 
10480   ResScalars.append(ResNE - NE, getUNDEF(ResEltVT));
10481   OvScalars.append(ResNE - NE, getUNDEF(OvEltVT));
10482 
10483   EVT NewResVT = EVT::getVectorVT(*getContext(), ResEltVT, ResNE);
10484   EVT NewOvVT = EVT::getVectorVT(*getContext(), OvEltVT, ResNE);
10485   return std::make_pair(getBuildVector(NewResVT, dl, ResScalars),
10486                         getBuildVector(NewOvVT, dl, OvScalars));
10487 }
10488 
10489 bool SelectionDAG::areNonVolatileConsecutiveLoads(LoadSDNode *LD,
10490                                                   LoadSDNode *Base,
10491                                                   unsigned Bytes,
10492                                                   int Dist) const {
10493   if (LD->isVolatile() || Base->isVolatile())
10494     return false;
10495   // TODO: probably too restrictive for atomics, revisit
10496   if (!LD->isSimple())
10497     return false;
10498   if (LD->isIndexed() || Base->isIndexed())
10499     return false;
10500   if (LD->getChain() != Base->getChain())
10501     return false;
10502   EVT VT = LD->getValueType(0);
10503   if (VT.getSizeInBits() / 8 != Bytes)
10504     return false;
10505 
10506   auto BaseLocDecomp = BaseIndexOffset::match(Base, *this);
10507   auto LocDecomp = BaseIndexOffset::match(LD, *this);
10508 
10509   int64_t Offset = 0;
10510   if (BaseLocDecomp.equalBaseIndex(LocDecomp, *this, Offset))
10511     return (Dist * Bytes == Offset);
10512   return false;
10513 }
10514 
10515 /// InferPtrAlignment - Infer alignment of a load / store address. Return None
10516 /// if it cannot be inferred.
10517 MaybeAlign SelectionDAG::InferPtrAlign(SDValue Ptr) const {
10518   // If this is a GlobalAddress + cst, return the alignment.
10519   const GlobalValue *GV = nullptr;
10520   int64_t GVOffset = 0;
10521   if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) {
10522     unsigned PtrWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
10523     KnownBits Known(PtrWidth);
10524     llvm::computeKnownBits(GV, Known, getDataLayout());
10525     unsigned AlignBits = Known.countMinTrailingZeros();
10526     if (AlignBits)
10527       return commonAlignment(Align(1ull << std::min(31U, AlignBits)), GVOffset);
10528   }
10529 
10530   // If this is a direct reference to a stack slot, use information about the
10531   // stack slot's alignment.
10532   int FrameIdx = INT_MIN;
10533   int64_t FrameOffset = 0;
10534   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) {
10535     FrameIdx = FI->getIndex();
10536   } else if (isBaseWithConstantOffset(Ptr) &&
10537              isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
10538     // Handle FI+Cst
10539     FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
10540     FrameOffset = Ptr.getConstantOperandVal(1);
10541   }
10542 
10543   if (FrameIdx != INT_MIN) {
10544     const MachineFrameInfo &MFI = getMachineFunction().getFrameInfo();
10545     return commonAlignment(MFI.getObjectAlign(FrameIdx), FrameOffset);
10546   }
10547 
10548   return None;
10549 }
10550 
10551 /// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type
10552 /// which is split (or expanded) into two not necessarily identical pieces.
10553 std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const {
10554   // Currently all types are split in half.
10555   EVT LoVT, HiVT;
10556   if (!VT.isVector())
10557     LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT);
10558   else
10559     LoVT = HiVT = VT.getHalfNumVectorElementsVT(*getContext());
10560 
10561   return std::make_pair(LoVT, HiVT);
10562 }
10563 
10564 /// GetDependentSplitDestVTs - Compute the VTs needed for the low/hi parts of a
10565 /// type, dependent on an enveloping VT that has been split into two identical
10566 /// pieces. Sets the HiIsEmpty flag when hi type has zero storage size.
10567 std::pair<EVT, EVT>
10568 SelectionDAG::GetDependentSplitDestVTs(const EVT &VT, const EVT &EnvVT,
10569                                        bool *HiIsEmpty) const {
10570   EVT EltTp = VT.getVectorElementType();
10571   // Examples:
10572   //   custom VL=8  with enveloping VL=8/8 yields 8/0 (hi empty)
10573   //   custom VL=9  with enveloping VL=8/8 yields 8/1
10574   //   custom VL=10 with enveloping VL=8/8 yields 8/2
10575   //   etc.
10576   ElementCount VTNumElts = VT.getVectorElementCount();
10577   ElementCount EnvNumElts = EnvVT.getVectorElementCount();
10578   assert(VTNumElts.isScalable() == EnvNumElts.isScalable() &&
10579          "Mixing fixed width and scalable vectors when enveloping a type");
10580   EVT LoVT, HiVT;
10581   if (VTNumElts.getKnownMinValue() > EnvNumElts.getKnownMinValue()) {
10582     LoVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts);
10583     HiVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts - EnvNumElts);
10584     *HiIsEmpty = false;
10585   } else {
10586     // Flag that hi type has zero storage size, but return split envelop type
10587     // (this would be easier if vector types with zero elements were allowed).
10588     LoVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts);
10589     HiVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts);
10590     *HiIsEmpty = true;
10591   }
10592   return std::make_pair(LoVT, HiVT);
10593 }
10594 
10595 /// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the
10596 /// low/high part.
10597 std::pair<SDValue, SDValue>
10598 SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT,
10599                           const EVT &HiVT) {
10600   assert(LoVT.isScalableVector() == HiVT.isScalableVector() &&
10601          LoVT.isScalableVector() == N.getValueType().isScalableVector() &&
10602          "Splitting vector with an invalid mixture of fixed and scalable "
10603          "vector types");
10604   assert(LoVT.getVectorMinNumElements() + HiVT.getVectorMinNumElements() <=
10605              N.getValueType().getVectorMinNumElements() &&
10606          "More vector elements requested than available!");
10607   SDValue Lo, Hi;
10608   Lo =
10609       getNode(ISD::EXTRACT_SUBVECTOR, DL, LoVT, N, getVectorIdxConstant(0, DL));
10610   // For scalable vectors it is safe to use LoVT.getVectorMinNumElements()
10611   // (rather than having to use ElementCount), because EXTRACT_SUBVECTOR scales
10612   // IDX with the runtime scaling factor of the result vector type. For
10613   // fixed-width result vectors, that runtime scaling factor is 1.
10614   Hi = getNode(ISD::EXTRACT_SUBVECTOR, DL, HiVT, N,
10615                getVectorIdxConstant(LoVT.getVectorMinNumElements(), DL));
10616   return std::make_pair(Lo, Hi);
10617 }
10618 
10619 /// Widen the vector up to the next power of two using INSERT_SUBVECTOR.
10620 SDValue SelectionDAG::WidenVector(const SDValue &N, const SDLoc &DL) {
10621   EVT VT = N.getValueType();
10622   EVT WideVT = EVT::getVectorVT(*getContext(), VT.getVectorElementType(),
10623                                 NextPowerOf2(VT.getVectorNumElements()));
10624   return getNode(ISD::INSERT_SUBVECTOR, DL, WideVT, getUNDEF(WideVT), N,
10625                  getVectorIdxConstant(0, DL));
10626 }
10627 
10628 void SelectionDAG::ExtractVectorElements(SDValue Op,
10629                                          SmallVectorImpl<SDValue> &Args,
10630                                          unsigned Start, unsigned Count,
10631                                          EVT EltVT) {
10632   EVT VT = Op.getValueType();
10633   if (Count == 0)
10634     Count = VT.getVectorNumElements();
10635   if (EltVT == EVT())
10636     EltVT = VT.getVectorElementType();
10637   SDLoc SL(Op);
10638   for (unsigned i = Start, e = Start + Count; i != e; ++i) {
10639     Args.push_back(getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Op,
10640                            getVectorIdxConstant(i, SL)));
10641   }
10642 }
10643 
10644 // getAddressSpace - Return the address space this GlobalAddress belongs to.
10645 unsigned GlobalAddressSDNode::getAddressSpace() const {
10646   return getGlobal()->getType()->getAddressSpace();
10647 }
10648 
10649 Type *ConstantPoolSDNode::getType() const {
10650   if (isMachineConstantPoolEntry())
10651     return Val.MachineCPVal->getType();
10652   return Val.ConstVal->getType();
10653 }
10654 
10655 bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue, APInt &SplatUndef,
10656                                         unsigned &SplatBitSize,
10657                                         bool &HasAnyUndefs,
10658                                         unsigned MinSplatBits,
10659                                         bool IsBigEndian) const {
10660   EVT VT = getValueType(0);
10661   assert(VT.isVector() && "Expected a vector type");
10662   unsigned VecWidth = VT.getSizeInBits();
10663   if (MinSplatBits > VecWidth)
10664     return false;
10665 
10666   // FIXME: The widths are based on this node's type, but build vectors can
10667   // truncate their operands.
10668   SplatValue = APInt(VecWidth, 0);
10669   SplatUndef = APInt(VecWidth, 0);
10670 
10671   // Get the bits. Bits with undefined values (when the corresponding element
10672   // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared
10673   // in SplatValue. If any of the values are not constant, give up and return
10674   // false.
10675   unsigned int NumOps = getNumOperands();
10676   assert(NumOps > 0 && "isConstantSplat has 0-size build vector");
10677   unsigned EltWidth = VT.getScalarSizeInBits();
10678 
10679   for (unsigned j = 0; j < NumOps; ++j) {
10680     unsigned i = IsBigEndian ? NumOps - 1 - j : j;
10681     SDValue OpVal = getOperand(i);
10682     unsigned BitPos = j * EltWidth;
10683 
10684     if (OpVal.isUndef())
10685       SplatUndef.setBits(BitPos, BitPos + EltWidth);
10686     else if (auto *CN = dyn_cast<ConstantSDNode>(OpVal))
10687       SplatValue.insertBits(CN->getAPIntValue().zextOrTrunc(EltWidth), BitPos);
10688     else if (auto *CN = dyn_cast<ConstantFPSDNode>(OpVal))
10689       SplatValue.insertBits(CN->getValueAPF().bitcastToAPInt(), BitPos);
10690     else
10691       return false;
10692   }
10693 
10694   // The build_vector is all constants or undefs. Find the smallest element
10695   // size that splats the vector.
10696   HasAnyUndefs = (SplatUndef != 0);
10697 
10698   // FIXME: This does not work for vectors with elements less than 8 bits.
10699   while (VecWidth > 8) {
10700     unsigned HalfSize = VecWidth / 2;
10701     APInt HighValue = SplatValue.extractBits(HalfSize, HalfSize);
10702     APInt LowValue = SplatValue.extractBits(HalfSize, 0);
10703     APInt HighUndef = SplatUndef.extractBits(HalfSize, HalfSize);
10704     APInt LowUndef = SplatUndef.extractBits(HalfSize, 0);
10705 
10706     // If the two halves do not match (ignoring undef bits), stop here.
10707     if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) ||
10708         MinSplatBits > HalfSize)
10709       break;
10710 
10711     SplatValue = HighValue | LowValue;
10712     SplatUndef = HighUndef & LowUndef;
10713 
10714     VecWidth = HalfSize;
10715   }
10716 
10717   SplatBitSize = VecWidth;
10718   return true;
10719 }
10720 
10721 SDValue BuildVectorSDNode::getSplatValue(const APInt &DemandedElts,
10722                                          BitVector *UndefElements) const {
10723   unsigned NumOps = getNumOperands();
10724   if (UndefElements) {
10725     UndefElements->clear();
10726     UndefElements->resize(NumOps);
10727   }
10728   assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size");
10729   if (!DemandedElts)
10730     return SDValue();
10731   SDValue Splatted;
10732   for (unsigned i = 0; i != NumOps; ++i) {
10733     if (!DemandedElts[i])
10734       continue;
10735     SDValue Op = getOperand(i);
10736     if (Op.isUndef()) {
10737       if (UndefElements)
10738         (*UndefElements)[i] = true;
10739     } else if (!Splatted) {
10740       Splatted = Op;
10741     } else if (Splatted != Op) {
10742       return SDValue();
10743     }
10744   }
10745 
10746   if (!Splatted) {
10747     unsigned FirstDemandedIdx = DemandedElts.countTrailingZeros();
10748     assert(getOperand(FirstDemandedIdx).isUndef() &&
10749            "Can only have a splat without a constant for all undefs.");
10750     return getOperand(FirstDemandedIdx);
10751   }
10752 
10753   return Splatted;
10754 }
10755 
10756 SDValue BuildVectorSDNode::getSplatValue(BitVector *UndefElements) const {
10757   APInt DemandedElts = APInt::getAllOnes(getNumOperands());
10758   return getSplatValue(DemandedElts, UndefElements);
10759 }
10760 
10761 bool BuildVectorSDNode::getRepeatedSequence(const APInt &DemandedElts,
10762                                             SmallVectorImpl<SDValue> &Sequence,
10763                                             BitVector *UndefElements) const {
10764   unsigned NumOps = getNumOperands();
10765   Sequence.clear();
10766   if (UndefElements) {
10767     UndefElements->clear();
10768     UndefElements->resize(NumOps);
10769   }
10770   assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size");
10771   if (!DemandedElts || NumOps < 2 || !isPowerOf2_32(NumOps))
10772     return false;
10773 
10774   // Set the undefs even if we don't find a sequence (like getSplatValue).
10775   if (UndefElements)
10776     for (unsigned I = 0; I != NumOps; ++I)
10777       if (DemandedElts[I] && getOperand(I).isUndef())
10778         (*UndefElements)[I] = true;
10779 
10780   // Iteratively widen the sequence length looking for repetitions.
10781   for (unsigned SeqLen = 1; SeqLen < NumOps; SeqLen *= 2) {
10782     Sequence.append(SeqLen, SDValue());
10783     for (unsigned I = 0; I != NumOps; ++I) {
10784       if (!DemandedElts[I])
10785         continue;
10786       SDValue &SeqOp = Sequence[I % SeqLen];
10787       SDValue Op = getOperand(I);
10788       if (Op.isUndef()) {
10789         if (!SeqOp)
10790           SeqOp = Op;
10791         continue;
10792       }
10793       if (SeqOp && !SeqOp.isUndef() && SeqOp != Op) {
10794         Sequence.clear();
10795         break;
10796       }
10797       SeqOp = Op;
10798     }
10799     if (!Sequence.empty())
10800       return true;
10801   }
10802 
10803   assert(Sequence.empty() && "Failed to empty non-repeating sequence pattern");
10804   return false;
10805 }
10806 
10807 bool BuildVectorSDNode::getRepeatedSequence(SmallVectorImpl<SDValue> &Sequence,
10808                                             BitVector *UndefElements) const {
10809   APInt DemandedElts = APInt::getAllOnes(getNumOperands());
10810   return getRepeatedSequence(DemandedElts, Sequence, UndefElements);
10811 }
10812 
10813 ConstantSDNode *
10814 BuildVectorSDNode::getConstantSplatNode(const APInt &DemandedElts,
10815                                         BitVector *UndefElements) const {
10816   return dyn_cast_or_null<ConstantSDNode>(
10817       getSplatValue(DemandedElts, UndefElements));
10818 }
10819 
10820 ConstantSDNode *
10821 BuildVectorSDNode::getConstantSplatNode(BitVector *UndefElements) const {
10822   return dyn_cast_or_null<ConstantSDNode>(getSplatValue(UndefElements));
10823 }
10824 
10825 ConstantFPSDNode *
10826 BuildVectorSDNode::getConstantFPSplatNode(const APInt &DemandedElts,
10827                                           BitVector *UndefElements) const {
10828   return dyn_cast_or_null<ConstantFPSDNode>(
10829       getSplatValue(DemandedElts, UndefElements));
10830 }
10831 
10832 ConstantFPSDNode *
10833 BuildVectorSDNode::getConstantFPSplatNode(BitVector *UndefElements) const {
10834   return dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements));
10835 }
10836 
10837 int32_t
10838 BuildVectorSDNode::getConstantFPSplatPow2ToLog2Int(BitVector *UndefElements,
10839                                                    uint32_t BitWidth) const {
10840   if (ConstantFPSDNode *CN =
10841           dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements))) {
10842     bool IsExact;
10843     APSInt IntVal(BitWidth);
10844     const APFloat &APF = CN->getValueAPF();
10845     if (APF.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) !=
10846             APFloat::opOK ||
10847         !IsExact)
10848       return -1;
10849 
10850     return IntVal.exactLogBase2();
10851   }
10852   return -1;
10853 }
10854 
10855 bool BuildVectorSDNode::getConstantRawBits(
10856     bool IsLittleEndian, unsigned DstEltSizeInBits,
10857     SmallVectorImpl<APInt> &RawBitElements, BitVector &UndefElements) const {
10858   // Early-out if this contains anything but Undef/Constant/ConstantFP.
10859   if (!isConstant())
10860     return false;
10861 
10862   unsigned NumSrcOps = getNumOperands();
10863   unsigned SrcEltSizeInBits = getValueType(0).getScalarSizeInBits();
10864   assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 &&
10865          "Invalid bitcast scale");
10866 
10867   // Extract raw src bits.
10868   SmallVector<APInt> SrcBitElements(NumSrcOps,
10869                                     APInt::getNullValue(SrcEltSizeInBits));
10870   BitVector SrcUndeElements(NumSrcOps, false);
10871 
10872   for (unsigned I = 0; I != NumSrcOps; ++I) {
10873     SDValue Op = getOperand(I);
10874     if (Op.isUndef()) {
10875       SrcUndeElements.set(I);
10876       continue;
10877     }
10878     auto *CInt = dyn_cast<ConstantSDNode>(Op);
10879     auto *CFP = dyn_cast<ConstantFPSDNode>(Op);
10880     assert((CInt || CFP) && "Unknown constant");
10881     SrcBitElements[I] =
10882         CInt ? CInt->getAPIntValue().truncOrSelf(SrcEltSizeInBits)
10883              : CFP->getValueAPF().bitcastToAPInt();
10884   }
10885 
10886   // Recast to dst width.
10887   recastRawBits(IsLittleEndian, DstEltSizeInBits, RawBitElements,
10888                 SrcBitElements, UndefElements, SrcUndeElements);
10889   return true;
10890 }
10891 
10892 void BuildVectorSDNode::recastRawBits(bool IsLittleEndian,
10893                                       unsigned DstEltSizeInBits,
10894                                       SmallVectorImpl<APInt> &DstBitElements,
10895                                       ArrayRef<APInt> SrcBitElements,
10896                                       BitVector &DstUndefElements,
10897                                       const BitVector &SrcUndefElements) {
10898   unsigned NumSrcOps = SrcBitElements.size();
10899   unsigned SrcEltSizeInBits = SrcBitElements[0].getBitWidth();
10900   assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 &&
10901          "Invalid bitcast scale");
10902   assert(NumSrcOps == SrcUndefElements.size() &&
10903          "Vector size mismatch");
10904 
10905   unsigned NumDstOps = (NumSrcOps * SrcEltSizeInBits) / DstEltSizeInBits;
10906   DstUndefElements.clear();
10907   DstUndefElements.resize(NumDstOps, false);
10908   DstBitElements.assign(NumDstOps, APInt::getNullValue(DstEltSizeInBits));
10909 
10910   // Concatenate src elements constant bits together into dst element.
10911   if (SrcEltSizeInBits <= DstEltSizeInBits) {
10912     unsigned Scale = DstEltSizeInBits / SrcEltSizeInBits;
10913     for (unsigned I = 0; I != NumDstOps; ++I) {
10914       DstUndefElements.set(I);
10915       APInt &DstBits = DstBitElements[I];
10916       for (unsigned J = 0; J != Scale; ++J) {
10917         unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1));
10918         if (SrcUndefElements[Idx])
10919           continue;
10920         DstUndefElements.reset(I);
10921         const APInt &SrcBits = SrcBitElements[Idx];
10922         assert(SrcBits.getBitWidth() == SrcEltSizeInBits &&
10923                "Illegal constant bitwidths");
10924         DstBits.insertBits(SrcBits, J * SrcEltSizeInBits);
10925       }
10926     }
10927     return;
10928   }
10929 
10930   // Split src element constant bits into dst elements.
10931   unsigned Scale = SrcEltSizeInBits / DstEltSizeInBits;
10932   for (unsigned I = 0; I != NumSrcOps; ++I) {
10933     if (SrcUndefElements[I]) {
10934       DstUndefElements.set(I * Scale, (I + 1) * Scale);
10935       continue;
10936     }
10937     const APInt &SrcBits = SrcBitElements[I];
10938     for (unsigned J = 0; J != Scale; ++J) {
10939       unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1));
10940       APInt &DstBits = DstBitElements[Idx];
10941       DstBits = SrcBits.extractBits(DstEltSizeInBits, J * DstEltSizeInBits);
10942     }
10943   }
10944 }
10945 
10946 bool BuildVectorSDNode::isConstant() const {
10947   for (const SDValue &Op : op_values()) {
10948     unsigned Opc = Op.getOpcode();
10949     if (Opc != ISD::UNDEF && Opc != ISD::Constant && Opc != ISD::ConstantFP)
10950       return false;
10951   }
10952   return true;
10953 }
10954 
10955 bool ShuffleVectorSDNode::isSplatMask(const int *Mask, EVT VT) {
10956   // Find the first non-undef value in the shuffle mask.
10957   unsigned i, e;
10958   for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i)
10959     /* search */;
10960 
10961   // If all elements are undefined, this shuffle can be considered a splat
10962   // (although it should eventually get simplified away completely).
10963   if (i == e)
10964     return true;
10965 
10966   // Make sure all remaining elements are either undef or the same as the first
10967   // non-undef value.
10968   for (int Idx = Mask[i]; i != e; ++i)
10969     if (Mask[i] >= 0 && Mask[i] != Idx)
10970       return false;
10971   return true;
10972 }
10973 
10974 // Returns the SDNode if it is a constant integer BuildVector
10975 // or constant integer.
10976 SDNode *SelectionDAG::isConstantIntBuildVectorOrConstantInt(SDValue N) const {
10977   if (isa<ConstantSDNode>(N))
10978     return N.getNode();
10979   if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
10980     return N.getNode();
10981   // Treat a GlobalAddress supporting constant offset folding as a
10982   // constant integer.
10983   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N))
10984     if (GA->getOpcode() == ISD::GlobalAddress &&
10985         TLI->isOffsetFoldingLegal(GA))
10986       return GA;
10987   if ((N.getOpcode() == ISD::SPLAT_VECTOR) &&
10988       isa<ConstantSDNode>(N.getOperand(0)))
10989     return N.getNode();
10990   return nullptr;
10991 }
10992 
10993 // Returns the SDNode if it is a constant float BuildVector
10994 // or constant float.
10995 SDNode *SelectionDAG::isConstantFPBuildVectorOrConstantFP(SDValue N) const {
10996   if (isa<ConstantFPSDNode>(N))
10997     return N.getNode();
10998 
10999   if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
11000     return N.getNode();
11001 
11002   return nullptr;
11003 }
11004 
11005 void SelectionDAG::createOperands(SDNode *Node, ArrayRef<SDValue> Vals) {
11006   assert(!Node->OperandList && "Node already has operands");
11007   assert(SDNode::getMaxNumOperands() >= Vals.size() &&
11008          "too many operands to fit into SDNode");
11009   SDUse *Ops = OperandRecycler.allocate(
11010       ArrayRecycler<SDUse>::Capacity::get(Vals.size()), OperandAllocator);
11011 
11012   bool IsDivergent = false;
11013   for (unsigned I = 0; I != Vals.size(); ++I) {
11014     Ops[I].setUser(Node);
11015     Ops[I].setInitial(Vals[I]);
11016     if (Ops[I].Val.getValueType() != MVT::Other) // Skip Chain. It does not carry divergence.
11017       IsDivergent |= Ops[I].getNode()->isDivergent();
11018   }
11019   Node->NumOperands = Vals.size();
11020   Node->OperandList = Ops;
11021   if (!TLI->isSDNodeAlwaysUniform(Node)) {
11022     IsDivergent |= TLI->isSDNodeSourceOfDivergence(Node, FLI, DA);
11023     Node->SDNodeBits.IsDivergent = IsDivergent;
11024   }
11025   checkForCycles(Node);
11026 }
11027 
11028 SDValue SelectionDAG::getTokenFactor(const SDLoc &DL,
11029                                      SmallVectorImpl<SDValue> &Vals) {
11030   size_t Limit = SDNode::getMaxNumOperands();
11031   while (Vals.size() > Limit) {
11032     unsigned SliceIdx = Vals.size() - Limit;
11033     auto ExtractedTFs = ArrayRef<SDValue>(Vals).slice(SliceIdx, Limit);
11034     SDValue NewTF = getNode(ISD::TokenFactor, DL, MVT::Other, ExtractedTFs);
11035     Vals.erase(Vals.begin() + SliceIdx, Vals.end());
11036     Vals.emplace_back(NewTF);
11037   }
11038   return getNode(ISD::TokenFactor, DL, MVT::Other, Vals);
11039 }
11040 
11041 SDValue SelectionDAG::getNeutralElement(unsigned Opcode, const SDLoc &DL,
11042                                         EVT VT, SDNodeFlags Flags) {
11043   switch (Opcode) {
11044   default:
11045     return SDValue();
11046   case ISD::ADD:
11047   case ISD::OR:
11048   case ISD::XOR:
11049   case ISD::UMAX:
11050     return getConstant(0, DL, VT);
11051   case ISD::MUL:
11052     return getConstant(1, DL, VT);
11053   case ISD::AND:
11054   case ISD::UMIN:
11055     return getAllOnesConstant(DL, VT);
11056   case ISD::SMAX:
11057     return getConstant(APInt::getSignedMinValue(VT.getSizeInBits()), DL, VT);
11058   case ISD::SMIN:
11059     return getConstant(APInt::getSignedMaxValue(VT.getSizeInBits()), DL, VT);
11060   case ISD::FADD:
11061     return getConstantFP(-0.0, DL, VT);
11062   case ISD::FMUL:
11063     return getConstantFP(1.0, DL, VT);
11064   case ISD::FMINNUM:
11065   case ISD::FMAXNUM: {
11066     // Neutral element for fminnum is NaN, Inf or FLT_MAX, depending on FMF.
11067     const fltSemantics &Semantics = EVTToAPFloatSemantics(VT);
11068     APFloat NeutralAF = !Flags.hasNoNaNs() ? APFloat::getQNaN(Semantics) :
11069                         !Flags.hasNoInfs() ? APFloat::getInf(Semantics) :
11070                         APFloat::getLargest(Semantics);
11071     if (Opcode == ISD::FMAXNUM)
11072       NeutralAF.changeSign();
11073 
11074     return getConstantFP(NeutralAF, DL, VT);
11075   }
11076   }
11077 }
11078 
11079 #ifndef NDEBUG
11080 static void checkForCyclesHelper(const SDNode *N,
11081                                  SmallPtrSetImpl<const SDNode*> &Visited,
11082                                  SmallPtrSetImpl<const SDNode*> &Checked,
11083                                  const llvm::SelectionDAG *DAG) {
11084   // If this node has already been checked, don't check it again.
11085   if (Checked.count(N))
11086     return;
11087 
11088   // If a node has already been visited on this depth-first walk, reject it as
11089   // a cycle.
11090   if (!Visited.insert(N).second) {
11091     errs() << "Detected cycle in SelectionDAG\n";
11092     dbgs() << "Offending node:\n";
11093     N->dumprFull(DAG); dbgs() << "\n";
11094     abort();
11095   }
11096 
11097   for (const SDValue &Op : N->op_values())
11098     checkForCyclesHelper(Op.getNode(), Visited, Checked, DAG);
11099 
11100   Checked.insert(N);
11101   Visited.erase(N);
11102 }
11103 #endif
11104 
11105 void llvm::checkForCycles(const llvm::SDNode *N,
11106                           const llvm::SelectionDAG *DAG,
11107                           bool force) {
11108 #ifndef NDEBUG
11109   bool check = force;
11110 #ifdef EXPENSIVE_CHECKS
11111   check = true;
11112 #endif  // EXPENSIVE_CHECKS
11113   if (check) {
11114     assert(N && "Checking nonexistent SDNode");
11115     SmallPtrSet<const SDNode*, 32> visited;
11116     SmallPtrSet<const SDNode*, 32> checked;
11117     checkForCyclesHelper(N, visited, checked, DAG);
11118   }
11119 #endif  // !NDEBUG
11120 }
11121 
11122 void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) {
11123   checkForCycles(DAG->getRoot().getNode(), DAG, force);
11124 }
11125