1 //===- SelectionDAG.cpp - Implement the SelectionDAG data structures ------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This implements the SelectionDAG class.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/CodeGen/SelectionDAG.h"
14 #include "SDNodeDbgValue.h"
15 #include "llvm/ADT/APFloat.h"
16 #include "llvm/ADT/APInt.h"
17 #include "llvm/ADT/APSInt.h"
18 #include "llvm/ADT/ArrayRef.h"
19 #include "llvm/ADT/BitVector.h"
20 #include "llvm/ADT/FoldingSet.h"
21 #include "llvm/ADT/None.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/ADT/SmallPtrSet.h"
24 #include "llvm/ADT/SmallVector.h"
25 #include "llvm/ADT/Triple.h"
26 #include "llvm/ADT/Twine.h"
27 #include "llvm/Analysis/MemoryLocation.h"
28 #include "llvm/Analysis/ValueTracking.h"
29 #include "llvm/CodeGen/Analysis.h"
30 #include "llvm/CodeGen/FunctionLoweringInfo.h"
31 #include "llvm/CodeGen/ISDOpcodes.h"
32 #include "llvm/CodeGen/MachineBasicBlock.h"
33 #include "llvm/CodeGen/MachineConstantPool.h"
34 #include "llvm/CodeGen/MachineFrameInfo.h"
35 #include "llvm/CodeGen/MachineFunction.h"
36 #include "llvm/CodeGen/MachineMemOperand.h"
37 #include "llvm/CodeGen/RuntimeLibcalls.h"
38 #include "llvm/CodeGen/SelectionDAGAddressAnalysis.h"
39 #include "llvm/CodeGen/SelectionDAGNodes.h"
40 #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
41 #include "llvm/CodeGen/TargetFrameLowering.h"
42 #include "llvm/CodeGen/TargetLowering.h"
43 #include "llvm/CodeGen/TargetRegisterInfo.h"
44 #include "llvm/CodeGen/TargetSubtargetInfo.h"
45 #include "llvm/CodeGen/ValueTypes.h"
46 #include "llvm/IR/Constant.h"
47 #include "llvm/IR/Constants.h"
48 #include "llvm/IR/DataLayout.h"
49 #include "llvm/IR/DebugInfoMetadata.h"
50 #include "llvm/IR/DebugLoc.h"
51 #include "llvm/IR/DerivedTypes.h"
52 #include "llvm/IR/Function.h"
53 #include "llvm/IR/GlobalValue.h"
54 #include "llvm/IR/Metadata.h"
55 #include "llvm/IR/Type.h"
56 #include "llvm/Support/Casting.h"
57 #include "llvm/Support/CodeGen.h"
58 #include "llvm/Support/Compiler.h"
59 #include "llvm/Support/Debug.h"
60 #include "llvm/Support/ErrorHandling.h"
61 #include "llvm/Support/KnownBits.h"
62 #include "llvm/Support/MachineValueType.h"
63 #include "llvm/Support/ManagedStatic.h"
64 #include "llvm/Support/MathExtras.h"
65 #include "llvm/Support/Mutex.h"
66 #include "llvm/Support/raw_ostream.h"
67 #include "llvm/Target/TargetMachine.h"
68 #include "llvm/Target/TargetOptions.h"
69 #include "llvm/Transforms/Utils/SizeOpts.h"
70 #include <algorithm>
71 #include <cassert>
72 #include <cstdint>
73 #include <cstdlib>
74 #include <limits>
75 #include <set>
76 #include <string>
77 #include <utility>
78 #include <vector>
79 
80 using namespace llvm;
81 
82 /// makeVTList - Return an instance of the SDVTList struct initialized with the
83 /// specified members.
84 static SDVTList makeVTList(const EVT *VTs, unsigned NumVTs) {
85   SDVTList Res = {VTs, NumVTs};
86   return Res;
87 }
88 
89 // Default null implementations of the callbacks.
90 void SelectionDAG::DAGUpdateListener::NodeDeleted(SDNode*, SDNode*) {}
91 void SelectionDAG::DAGUpdateListener::NodeUpdated(SDNode*) {}
92 void SelectionDAG::DAGUpdateListener::NodeInserted(SDNode *) {}
93 
94 void SelectionDAG::DAGNodeDeletedListener::anchor() {}
95 
96 #define DEBUG_TYPE "selectiondag"
97 
98 static cl::opt<bool> EnableMemCpyDAGOpt("enable-memcpy-dag-opt",
99        cl::Hidden, cl::init(true),
100        cl::desc("Gang up loads and stores generated by inlining of memcpy"));
101 
102 static cl::opt<int> MaxLdStGlue("ldstmemcpy-glue-max",
103        cl::desc("Number limit for gluing ld/st of memcpy."),
104        cl::Hidden, cl::init(0));
105 
106 static void NewSDValueDbgMsg(SDValue V, StringRef Msg, SelectionDAG *G) {
107   LLVM_DEBUG(dbgs() << Msg; V.getNode()->dump(G););
108 }
109 
110 //===----------------------------------------------------------------------===//
111 //                              ConstantFPSDNode Class
112 //===----------------------------------------------------------------------===//
113 
114 /// isExactlyValue - We don't rely on operator== working on double values, as
115 /// it returns true for things that are clearly not equal, like -0.0 and 0.0.
116 /// As such, this method can be used to do an exact bit-for-bit comparison of
117 /// two floating point values.
118 bool ConstantFPSDNode::isExactlyValue(const APFloat& V) const {
119   return getValueAPF().bitwiseIsEqual(V);
120 }
121 
122 bool ConstantFPSDNode::isValueValidForType(EVT VT,
123                                            const APFloat& Val) {
124   assert(VT.isFloatingPoint() && "Can only convert between FP types");
125 
126   // convert modifies in place, so make a copy.
127   APFloat Val2 = APFloat(Val);
128   bool losesInfo;
129   (void) Val2.convert(SelectionDAG::EVTToAPFloatSemantics(VT),
130                       APFloat::rmNearestTiesToEven,
131                       &losesInfo);
132   return !losesInfo;
133 }
134 
135 //===----------------------------------------------------------------------===//
136 //                              ISD Namespace
137 //===----------------------------------------------------------------------===//
138 
139 bool ISD::isConstantSplatVector(const SDNode *N, APInt &SplatVal) {
140   if (N->getOpcode() == ISD::SPLAT_VECTOR) {
141     unsigned EltSize =
142         N->getValueType(0).getVectorElementType().getSizeInBits();
143     if (auto *Op0 = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
144       SplatVal = Op0->getAPIntValue().trunc(EltSize);
145       return true;
146     }
147     if (auto *Op0 = dyn_cast<ConstantFPSDNode>(N->getOperand(0))) {
148       SplatVal = Op0->getValueAPF().bitcastToAPInt().trunc(EltSize);
149       return true;
150     }
151   }
152 
153   auto *BV = dyn_cast<BuildVectorSDNode>(N);
154   if (!BV)
155     return false;
156 
157   APInt SplatUndef;
158   unsigned SplatBitSize;
159   bool HasUndefs;
160   unsigned EltSize = N->getValueType(0).getVectorElementType().getSizeInBits();
161   return BV->isConstantSplat(SplatVal, SplatUndef, SplatBitSize, HasUndefs,
162                              EltSize) &&
163          EltSize == SplatBitSize;
164 }
165 
166 // FIXME: AllOnes and AllZeros duplicate a lot of code. Could these be
167 // specializations of the more general isConstantSplatVector()?
168 
169 bool ISD::isConstantSplatVectorAllOnes(const SDNode *N, bool BuildVectorOnly) {
170   // Look through a bit convert.
171   while (N->getOpcode() == ISD::BITCAST)
172     N = N->getOperand(0).getNode();
173 
174   if (!BuildVectorOnly && N->getOpcode() == ISD::SPLAT_VECTOR) {
175     APInt SplatVal;
176     return isConstantSplatVector(N, SplatVal) && SplatVal.isAllOnes();
177   }
178 
179   if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
180 
181   unsigned i = 0, e = N->getNumOperands();
182 
183   // Skip over all of the undef values.
184   while (i != e && N->getOperand(i).isUndef())
185     ++i;
186 
187   // Do not accept an all-undef vector.
188   if (i == e) return false;
189 
190   // Do not accept build_vectors that aren't all constants or which have non-~0
191   // elements. We have to be a bit careful here, as the type of the constant
192   // may not be the same as the type of the vector elements due to type
193   // legalization (the elements are promoted to a legal type for the target and
194   // a vector of a type may be legal when the base element type is not).
195   // We only want to check enough bits to cover the vector elements, because
196   // we care if the resultant vector is all ones, not whether the individual
197   // constants are.
198   SDValue NotZero = N->getOperand(i);
199   unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
200   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(NotZero)) {
201     if (CN->getAPIntValue().countTrailingOnes() < EltSize)
202       return false;
203   } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(NotZero)) {
204     if (CFPN->getValueAPF().bitcastToAPInt().countTrailingOnes() < EltSize)
205       return false;
206   } else
207     return false;
208 
209   // Okay, we have at least one ~0 value, check to see if the rest match or are
210   // undefs. Even with the above element type twiddling, this should be OK, as
211   // the same type legalization should have applied to all the elements.
212   for (++i; i != e; ++i)
213     if (N->getOperand(i) != NotZero && !N->getOperand(i).isUndef())
214       return false;
215   return true;
216 }
217 
218 bool ISD::isConstantSplatVectorAllZeros(const SDNode *N, bool BuildVectorOnly) {
219   // Look through a bit convert.
220   while (N->getOpcode() == ISD::BITCAST)
221     N = N->getOperand(0).getNode();
222 
223   if (!BuildVectorOnly && N->getOpcode() == ISD::SPLAT_VECTOR) {
224     APInt SplatVal;
225     return isConstantSplatVector(N, SplatVal) && SplatVal.isZero();
226   }
227 
228   if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
229 
230   bool IsAllUndef = true;
231   for (const SDValue &Op : N->op_values()) {
232     if (Op.isUndef())
233       continue;
234     IsAllUndef = false;
235     // Do not accept build_vectors that aren't all constants or which have non-0
236     // elements. We have to be a bit careful here, as the type of the constant
237     // may not be the same as the type of the vector elements due to type
238     // legalization (the elements are promoted to a legal type for the target
239     // and a vector of a type may be legal when the base element type is not).
240     // We only want to check enough bits to cover the vector elements, because
241     // we care if the resultant vector is all zeros, not whether the individual
242     // constants are.
243     unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
244     if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Op)) {
245       if (CN->getAPIntValue().countTrailingZeros() < EltSize)
246         return false;
247     } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(Op)) {
248       if (CFPN->getValueAPF().bitcastToAPInt().countTrailingZeros() < EltSize)
249         return false;
250     } else
251       return false;
252   }
253 
254   // Do not accept an all-undef vector.
255   if (IsAllUndef)
256     return false;
257   return true;
258 }
259 
260 bool ISD::isBuildVectorAllOnes(const SDNode *N) {
261   return isConstantSplatVectorAllOnes(N, /*BuildVectorOnly*/ true);
262 }
263 
264 bool ISD::isBuildVectorAllZeros(const SDNode *N) {
265   return isConstantSplatVectorAllZeros(N, /*BuildVectorOnly*/ true);
266 }
267 
268 bool ISD::isBuildVectorOfConstantSDNodes(const SDNode *N) {
269   if (N->getOpcode() != ISD::BUILD_VECTOR)
270     return false;
271 
272   for (const SDValue &Op : N->op_values()) {
273     if (Op.isUndef())
274       continue;
275     if (!isa<ConstantSDNode>(Op))
276       return false;
277   }
278   return true;
279 }
280 
281 bool ISD::isBuildVectorOfConstantFPSDNodes(const SDNode *N) {
282   if (N->getOpcode() != ISD::BUILD_VECTOR)
283     return false;
284 
285   for (const SDValue &Op : N->op_values()) {
286     if (Op.isUndef())
287       continue;
288     if (!isa<ConstantFPSDNode>(Op))
289       return false;
290   }
291   return true;
292 }
293 
294 bool ISD::allOperandsUndef(const SDNode *N) {
295   // Return false if the node has no operands.
296   // This is "logically inconsistent" with the definition of "all" but
297   // is probably the desired behavior.
298   if (N->getNumOperands() == 0)
299     return false;
300   return all_of(N->op_values(), [](SDValue Op) { return Op.isUndef(); });
301 }
302 
303 bool ISD::matchUnaryPredicate(SDValue Op,
304                               std::function<bool(ConstantSDNode *)> Match,
305                               bool AllowUndefs) {
306   // FIXME: Add support for scalar UNDEF cases?
307   if (auto *Cst = dyn_cast<ConstantSDNode>(Op))
308     return Match(Cst);
309 
310   // FIXME: Add support for vector UNDEF cases?
311   if (ISD::BUILD_VECTOR != Op.getOpcode() &&
312       ISD::SPLAT_VECTOR != Op.getOpcode())
313     return false;
314 
315   EVT SVT = Op.getValueType().getScalarType();
316   for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
317     if (AllowUndefs && Op.getOperand(i).isUndef()) {
318       if (!Match(nullptr))
319         return false;
320       continue;
321     }
322 
323     auto *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(i));
324     if (!Cst || Cst->getValueType(0) != SVT || !Match(Cst))
325       return false;
326   }
327   return true;
328 }
329 
330 bool ISD::matchBinaryPredicate(
331     SDValue LHS, SDValue RHS,
332     std::function<bool(ConstantSDNode *, ConstantSDNode *)> Match,
333     bool AllowUndefs, bool AllowTypeMismatch) {
334   if (!AllowTypeMismatch && LHS.getValueType() != RHS.getValueType())
335     return false;
336 
337   // TODO: Add support for scalar UNDEF cases?
338   if (auto *LHSCst = dyn_cast<ConstantSDNode>(LHS))
339     if (auto *RHSCst = dyn_cast<ConstantSDNode>(RHS))
340       return Match(LHSCst, RHSCst);
341 
342   // TODO: Add support for vector UNDEF cases?
343   if (LHS.getOpcode() != RHS.getOpcode() ||
344       (LHS.getOpcode() != ISD::BUILD_VECTOR &&
345        LHS.getOpcode() != ISD::SPLAT_VECTOR))
346     return false;
347 
348   EVT SVT = LHS.getValueType().getScalarType();
349   for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
350     SDValue LHSOp = LHS.getOperand(i);
351     SDValue RHSOp = RHS.getOperand(i);
352     bool LHSUndef = AllowUndefs && LHSOp.isUndef();
353     bool RHSUndef = AllowUndefs && RHSOp.isUndef();
354     auto *LHSCst = dyn_cast<ConstantSDNode>(LHSOp);
355     auto *RHSCst = dyn_cast<ConstantSDNode>(RHSOp);
356     if ((!LHSCst && !LHSUndef) || (!RHSCst && !RHSUndef))
357       return false;
358     if (!AllowTypeMismatch && (LHSOp.getValueType() != SVT ||
359                                LHSOp.getValueType() != RHSOp.getValueType()))
360       return false;
361     if (!Match(LHSCst, RHSCst))
362       return false;
363   }
364   return true;
365 }
366 
367 ISD::NodeType ISD::getVecReduceBaseOpcode(unsigned VecReduceOpcode) {
368   switch (VecReduceOpcode) {
369   default:
370     llvm_unreachable("Expected VECREDUCE opcode");
371   case ISD::VECREDUCE_FADD:
372   case ISD::VECREDUCE_SEQ_FADD:
373   case ISD::VP_REDUCE_FADD:
374   case ISD::VP_REDUCE_SEQ_FADD:
375     return ISD::FADD;
376   case ISD::VECREDUCE_FMUL:
377   case ISD::VECREDUCE_SEQ_FMUL:
378   case ISD::VP_REDUCE_FMUL:
379   case ISD::VP_REDUCE_SEQ_FMUL:
380     return ISD::FMUL;
381   case ISD::VECREDUCE_ADD:
382   case ISD::VP_REDUCE_ADD:
383     return ISD::ADD;
384   case ISD::VECREDUCE_MUL:
385   case ISD::VP_REDUCE_MUL:
386     return ISD::MUL;
387   case ISD::VECREDUCE_AND:
388   case ISD::VP_REDUCE_AND:
389     return ISD::AND;
390   case ISD::VECREDUCE_OR:
391   case ISD::VP_REDUCE_OR:
392     return ISD::OR;
393   case ISD::VECREDUCE_XOR:
394   case ISD::VP_REDUCE_XOR:
395     return ISD::XOR;
396   case ISD::VECREDUCE_SMAX:
397   case ISD::VP_REDUCE_SMAX:
398     return ISD::SMAX;
399   case ISD::VECREDUCE_SMIN:
400   case ISD::VP_REDUCE_SMIN:
401     return ISD::SMIN;
402   case ISD::VECREDUCE_UMAX:
403   case ISD::VP_REDUCE_UMAX:
404     return ISD::UMAX;
405   case ISD::VECREDUCE_UMIN:
406   case ISD::VP_REDUCE_UMIN:
407     return ISD::UMIN;
408   case ISD::VECREDUCE_FMAX:
409   case ISD::VP_REDUCE_FMAX:
410     return ISD::FMAXNUM;
411   case ISD::VECREDUCE_FMIN:
412   case ISD::VP_REDUCE_FMIN:
413     return ISD::FMINNUM;
414   }
415 }
416 
417 bool ISD::isVPOpcode(unsigned Opcode) {
418   switch (Opcode) {
419   default:
420     return false;
421 #define BEGIN_REGISTER_VP_SDNODE(VPSD, ...)                                    \
422   case ISD::VPSD:                                                              \
423     return true;
424 #include "llvm/IR/VPIntrinsics.def"
425   }
426 }
427 
428 bool ISD::isVPBinaryOp(unsigned Opcode) {
429   switch (Opcode) {
430   default:
431     break;
432 #define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) case ISD::VPSD:
433 #define VP_PROPERTY_BINARYOP return true;
434 #define END_REGISTER_VP_SDNODE(VPSD) break;
435 #include "llvm/IR/VPIntrinsics.def"
436   }
437   return false;
438 }
439 
440 bool ISD::isVPReduction(unsigned Opcode) {
441   switch (Opcode) {
442   default:
443     break;
444 #define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) case ISD::VPSD:
445 #define VP_PROPERTY_REDUCTION(STARTPOS, ...) return true;
446 #define END_REGISTER_VP_SDNODE(VPSD) break;
447 #include "llvm/IR/VPIntrinsics.def"
448   }
449   return false;
450 }
451 
452 /// The operand position of the vector mask.
453 Optional<unsigned> ISD::getVPMaskIdx(unsigned Opcode) {
454   switch (Opcode) {
455   default:
456     return None;
457 #define BEGIN_REGISTER_VP_SDNODE(VPSD, LEGALPOS, TDNAME, MASKPOS, ...)         \
458   case ISD::VPSD:                                                              \
459     return MASKPOS;
460 #include "llvm/IR/VPIntrinsics.def"
461   }
462 }
463 
464 /// The operand position of the explicit vector length parameter.
465 Optional<unsigned> ISD::getVPExplicitVectorLengthIdx(unsigned Opcode) {
466   switch (Opcode) {
467   default:
468     return None;
469 #define BEGIN_REGISTER_VP_SDNODE(VPSD, LEGALPOS, TDNAME, MASKPOS, EVLPOS)      \
470   case ISD::VPSD:                                                              \
471     return EVLPOS;
472 #include "llvm/IR/VPIntrinsics.def"
473   }
474 }
475 
476 ISD::NodeType ISD::getExtForLoadExtType(bool IsFP, ISD::LoadExtType ExtType) {
477   switch (ExtType) {
478   case ISD::EXTLOAD:
479     return IsFP ? ISD::FP_EXTEND : ISD::ANY_EXTEND;
480   case ISD::SEXTLOAD:
481     return ISD::SIGN_EXTEND;
482   case ISD::ZEXTLOAD:
483     return ISD::ZERO_EXTEND;
484   default:
485     break;
486   }
487 
488   llvm_unreachable("Invalid LoadExtType");
489 }
490 
491 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) {
492   // To perform this operation, we just need to swap the L and G bits of the
493   // operation.
494   unsigned OldL = (Operation >> 2) & 1;
495   unsigned OldG = (Operation >> 1) & 1;
496   return ISD::CondCode((Operation & ~6) |  // Keep the N, U, E bits
497                        (OldL << 1) |       // New G bit
498                        (OldG << 2));       // New L bit.
499 }
500 
501 static ISD::CondCode getSetCCInverseImpl(ISD::CondCode Op, bool isIntegerLike) {
502   unsigned Operation = Op;
503   if (isIntegerLike)
504     Operation ^= 7;   // Flip L, G, E bits, but not U.
505   else
506     Operation ^= 15;  // Flip all of the condition bits.
507 
508   if (Operation > ISD::SETTRUE2)
509     Operation &= ~8;  // Don't let N and U bits get set.
510 
511   return ISD::CondCode(Operation);
512 }
513 
514 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, EVT Type) {
515   return getSetCCInverseImpl(Op, Type.isInteger());
516 }
517 
518 ISD::CondCode ISD::GlobalISel::getSetCCInverse(ISD::CondCode Op,
519                                                bool isIntegerLike) {
520   return getSetCCInverseImpl(Op, isIntegerLike);
521 }
522 
523 /// For an integer comparison, return 1 if the comparison is a signed operation
524 /// and 2 if the result is an unsigned comparison. Return zero if the operation
525 /// does not depend on the sign of the input (setne and seteq).
526 static int isSignedOp(ISD::CondCode Opcode) {
527   switch (Opcode) {
528   default: llvm_unreachable("Illegal integer setcc operation!");
529   case ISD::SETEQ:
530   case ISD::SETNE: return 0;
531   case ISD::SETLT:
532   case ISD::SETLE:
533   case ISD::SETGT:
534   case ISD::SETGE: return 1;
535   case ISD::SETULT:
536   case ISD::SETULE:
537   case ISD::SETUGT:
538   case ISD::SETUGE: return 2;
539   }
540 }
541 
542 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2,
543                                        EVT Type) {
544   bool IsInteger = Type.isInteger();
545   if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
546     // Cannot fold a signed integer setcc with an unsigned integer setcc.
547     return ISD::SETCC_INVALID;
548 
549   unsigned Op = Op1 | Op2;  // Combine all of the condition bits.
550 
551   // If the N and U bits get set, then the resultant comparison DOES suddenly
552   // care about orderedness, and it is true when ordered.
553   if (Op > ISD::SETTRUE2)
554     Op &= ~16;     // Clear the U bit if the N bit is set.
555 
556   // Canonicalize illegal integer setcc's.
557   if (IsInteger && Op == ISD::SETUNE)  // e.g. SETUGT | SETULT
558     Op = ISD::SETNE;
559 
560   return ISD::CondCode(Op);
561 }
562 
563 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2,
564                                         EVT Type) {
565   bool IsInteger = Type.isInteger();
566   if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
567     // Cannot fold a signed setcc with an unsigned setcc.
568     return ISD::SETCC_INVALID;
569 
570   // Combine all of the condition bits.
571   ISD::CondCode Result = ISD::CondCode(Op1 & Op2);
572 
573   // Canonicalize illegal integer setcc's.
574   if (IsInteger) {
575     switch (Result) {
576     default: break;
577     case ISD::SETUO : Result = ISD::SETFALSE; break;  // SETUGT & SETULT
578     case ISD::SETOEQ:                                 // SETEQ  & SETU[LG]E
579     case ISD::SETUEQ: Result = ISD::SETEQ   ; break;  // SETUGE & SETULE
580     case ISD::SETOLT: Result = ISD::SETULT  ; break;  // SETULT & SETNE
581     case ISD::SETOGT: Result = ISD::SETUGT  ; break;  // SETUGT & SETNE
582     }
583   }
584 
585   return Result;
586 }
587 
588 //===----------------------------------------------------------------------===//
589 //                           SDNode Profile Support
590 //===----------------------------------------------------------------------===//
591 
592 /// AddNodeIDOpcode - Add the node opcode to the NodeID data.
593 static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC)  {
594   ID.AddInteger(OpC);
595 }
596 
597 /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them
598 /// solely with their pointer.
599 static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) {
600   ID.AddPointer(VTList.VTs);
601 }
602 
603 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
604 static void AddNodeIDOperands(FoldingSetNodeID &ID,
605                               ArrayRef<SDValue> Ops) {
606   for (auto& Op : Ops) {
607     ID.AddPointer(Op.getNode());
608     ID.AddInteger(Op.getResNo());
609   }
610 }
611 
612 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
613 static void AddNodeIDOperands(FoldingSetNodeID &ID,
614                               ArrayRef<SDUse> Ops) {
615   for (auto& Op : Ops) {
616     ID.AddPointer(Op.getNode());
617     ID.AddInteger(Op.getResNo());
618   }
619 }
620 
621 static void AddNodeIDNode(FoldingSetNodeID &ID, unsigned short OpC,
622                           SDVTList VTList, ArrayRef<SDValue> OpList) {
623   AddNodeIDOpcode(ID, OpC);
624   AddNodeIDValueTypes(ID, VTList);
625   AddNodeIDOperands(ID, OpList);
626 }
627 
628 /// If this is an SDNode with special info, add this info to the NodeID data.
629 static void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N) {
630   switch (N->getOpcode()) {
631   case ISD::TargetExternalSymbol:
632   case ISD::ExternalSymbol:
633   case ISD::MCSymbol:
634     llvm_unreachable("Should only be used on nodes with operands");
635   default: break;  // Normal nodes don't need extra info.
636   case ISD::TargetConstant:
637   case ISD::Constant: {
638     const ConstantSDNode *C = cast<ConstantSDNode>(N);
639     ID.AddPointer(C->getConstantIntValue());
640     ID.AddBoolean(C->isOpaque());
641     break;
642   }
643   case ISD::TargetConstantFP:
644   case ISD::ConstantFP:
645     ID.AddPointer(cast<ConstantFPSDNode>(N)->getConstantFPValue());
646     break;
647   case ISD::TargetGlobalAddress:
648   case ISD::GlobalAddress:
649   case ISD::TargetGlobalTLSAddress:
650   case ISD::GlobalTLSAddress: {
651     const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
652     ID.AddPointer(GA->getGlobal());
653     ID.AddInteger(GA->getOffset());
654     ID.AddInteger(GA->getTargetFlags());
655     break;
656   }
657   case ISD::BasicBlock:
658     ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock());
659     break;
660   case ISD::Register:
661     ID.AddInteger(cast<RegisterSDNode>(N)->getReg());
662     break;
663   case ISD::RegisterMask:
664     ID.AddPointer(cast<RegisterMaskSDNode>(N)->getRegMask());
665     break;
666   case ISD::SRCVALUE:
667     ID.AddPointer(cast<SrcValueSDNode>(N)->getValue());
668     break;
669   case ISD::FrameIndex:
670   case ISD::TargetFrameIndex:
671     ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex());
672     break;
673   case ISD::LIFETIME_START:
674   case ISD::LIFETIME_END:
675     if (cast<LifetimeSDNode>(N)->hasOffset()) {
676       ID.AddInteger(cast<LifetimeSDNode>(N)->getSize());
677       ID.AddInteger(cast<LifetimeSDNode>(N)->getOffset());
678     }
679     break;
680   case ISD::PSEUDO_PROBE:
681     ID.AddInteger(cast<PseudoProbeSDNode>(N)->getGuid());
682     ID.AddInteger(cast<PseudoProbeSDNode>(N)->getIndex());
683     ID.AddInteger(cast<PseudoProbeSDNode>(N)->getAttributes());
684     break;
685   case ISD::JumpTable:
686   case ISD::TargetJumpTable:
687     ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex());
688     ID.AddInteger(cast<JumpTableSDNode>(N)->getTargetFlags());
689     break;
690   case ISD::ConstantPool:
691   case ISD::TargetConstantPool: {
692     const ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N);
693     ID.AddInteger(CP->getAlign().value());
694     ID.AddInteger(CP->getOffset());
695     if (CP->isMachineConstantPoolEntry())
696       CP->getMachineCPVal()->addSelectionDAGCSEId(ID);
697     else
698       ID.AddPointer(CP->getConstVal());
699     ID.AddInteger(CP->getTargetFlags());
700     break;
701   }
702   case ISD::TargetIndex: {
703     const TargetIndexSDNode *TI = cast<TargetIndexSDNode>(N);
704     ID.AddInteger(TI->getIndex());
705     ID.AddInteger(TI->getOffset());
706     ID.AddInteger(TI->getTargetFlags());
707     break;
708   }
709   case ISD::LOAD: {
710     const LoadSDNode *LD = cast<LoadSDNode>(N);
711     ID.AddInteger(LD->getMemoryVT().getRawBits());
712     ID.AddInteger(LD->getRawSubclassData());
713     ID.AddInteger(LD->getPointerInfo().getAddrSpace());
714     ID.AddInteger(LD->getMemOperand()->getFlags());
715     break;
716   }
717   case ISD::STORE: {
718     const StoreSDNode *ST = cast<StoreSDNode>(N);
719     ID.AddInteger(ST->getMemoryVT().getRawBits());
720     ID.AddInteger(ST->getRawSubclassData());
721     ID.AddInteger(ST->getPointerInfo().getAddrSpace());
722     ID.AddInteger(ST->getMemOperand()->getFlags());
723     break;
724   }
725   case ISD::VP_LOAD: {
726     const VPLoadSDNode *ELD = cast<VPLoadSDNode>(N);
727     ID.AddInteger(ELD->getMemoryVT().getRawBits());
728     ID.AddInteger(ELD->getRawSubclassData());
729     ID.AddInteger(ELD->getPointerInfo().getAddrSpace());
730     ID.AddInteger(ELD->getMemOperand()->getFlags());
731     break;
732   }
733   case ISD::VP_STORE: {
734     const VPStoreSDNode *EST = cast<VPStoreSDNode>(N);
735     ID.AddInteger(EST->getMemoryVT().getRawBits());
736     ID.AddInteger(EST->getRawSubclassData());
737     ID.AddInteger(EST->getPointerInfo().getAddrSpace());
738     ID.AddInteger(EST->getMemOperand()->getFlags());
739     break;
740   }
741   case ISD::EXPERIMENTAL_VP_STRIDED_LOAD: {
742     const VPStridedLoadSDNode *SLD = cast<VPStridedLoadSDNode>(N);
743     ID.AddInteger(SLD->getMemoryVT().getRawBits());
744     ID.AddInteger(SLD->getRawSubclassData());
745     ID.AddInteger(SLD->getPointerInfo().getAddrSpace());
746     break;
747   }
748   case ISD::EXPERIMENTAL_VP_STRIDED_STORE: {
749     const VPStridedStoreSDNode *SST = cast<VPStridedStoreSDNode>(N);
750     ID.AddInteger(SST->getMemoryVT().getRawBits());
751     ID.AddInteger(SST->getRawSubclassData());
752     ID.AddInteger(SST->getPointerInfo().getAddrSpace());
753     break;
754   }
755   case ISD::VP_GATHER: {
756     const VPGatherSDNode *EG = cast<VPGatherSDNode>(N);
757     ID.AddInteger(EG->getMemoryVT().getRawBits());
758     ID.AddInteger(EG->getRawSubclassData());
759     ID.AddInteger(EG->getPointerInfo().getAddrSpace());
760     ID.AddInteger(EG->getMemOperand()->getFlags());
761     break;
762   }
763   case ISD::VP_SCATTER: {
764     const VPScatterSDNode *ES = cast<VPScatterSDNode>(N);
765     ID.AddInteger(ES->getMemoryVT().getRawBits());
766     ID.AddInteger(ES->getRawSubclassData());
767     ID.AddInteger(ES->getPointerInfo().getAddrSpace());
768     ID.AddInteger(ES->getMemOperand()->getFlags());
769     break;
770   }
771   case ISD::MLOAD: {
772     const MaskedLoadSDNode *MLD = cast<MaskedLoadSDNode>(N);
773     ID.AddInteger(MLD->getMemoryVT().getRawBits());
774     ID.AddInteger(MLD->getRawSubclassData());
775     ID.AddInteger(MLD->getPointerInfo().getAddrSpace());
776     ID.AddInteger(MLD->getMemOperand()->getFlags());
777     break;
778   }
779   case ISD::MSTORE: {
780     const MaskedStoreSDNode *MST = cast<MaskedStoreSDNode>(N);
781     ID.AddInteger(MST->getMemoryVT().getRawBits());
782     ID.AddInteger(MST->getRawSubclassData());
783     ID.AddInteger(MST->getPointerInfo().getAddrSpace());
784     ID.AddInteger(MST->getMemOperand()->getFlags());
785     break;
786   }
787   case ISD::MGATHER: {
788     const MaskedGatherSDNode *MG = cast<MaskedGatherSDNode>(N);
789     ID.AddInteger(MG->getMemoryVT().getRawBits());
790     ID.AddInteger(MG->getRawSubclassData());
791     ID.AddInteger(MG->getPointerInfo().getAddrSpace());
792     ID.AddInteger(MG->getMemOperand()->getFlags());
793     break;
794   }
795   case ISD::MSCATTER: {
796     const MaskedScatterSDNode *MS = cast<MaskedScatterSDNode>(N);
797     ID.AddInteger(MS->getMemoryVT().getRawBits());
798     ID.AddInteger(MS->getRawSubclassData());
799     ID.AddInteger(MS->getPointerInfo().getAddrSpace());
800     ID.AddInteger(MS->getMemOperand()->getFlags());
801     break;
802   }
803   case ISD::ATOMIC_CMP_SWAP:
804   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
805   case ISD::ATOMIC_SWAP:
806   case ISD::ATOMIC_LOAD_ADD:
807   case ISD::ATOMIC_LOAD_SUB:
808   case ISD::ATOMIC_LOAD_AND:
809   case ISD::ATOMIC_LOAD_CLR:
810   case ISD::ATOMIC_LOAD_OR:
811   case ISD::ATOMIC_LOAD_XOR:
812   case ISD::ATOMIC_LOAD_NAND:
813   case ISD::ATOMIC_LOAD_MIN:
814   case ISD::ATOMIC_LOAD_MAX:
815   case ISD::ATOMIC_LOAD_UMIN:
816   case ISD::ATOMIC_LOAD_UMAX:
817   case ISD::ATOMIC_LOAD:
818   case ISD::ATOMIC_STORE: {
819     const AtomicSDNode *AT = cast<AtomicSDNode>(N);
820     ID.AddInteger(AT->getMemoryVT().getRawBits());
821     ID.AddInteger(AT->getRawSubclassData());
822     ID.AddInteger(AT->getPointerInfo().getAddrSpace());
823     ID.AddInteger(AT->getMemOperand()->getFlags());
824     break;
825   }
826   case ISD::PREFETCH: {
827     const MemSDNode *PF = cast<MemSDNode>(N);
828     ID.AddInteger(PF->getPointerInfo().getAddrSpace());
829     ID.AddInteger(PF->getMemOperand()->getFlags());
830     break;
831   }
832   case ISD::VECTOR_SHUFFLE: {
833     const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
834     for (unsigned i = 0, e = N->getValueType(0).getVectorNumElements();
835          i != e; ++i)
836       ID.AddInteger(SVN->getMaskElt(i));
837     break;
838   }
839   case ISD::TargetBlockAddress:
840   case ISD::BlockAddress: {
841     const BlockAddressSDNode *BA = cast<BlockAddressSDNode>(N);
842     ID.AddPointer(BA->getBlockAddress());
843     ID.AddInteger(BA->getOffset());
844     ID.AddInteger(BA->getTargetFlags());
845     break;
846   }
847   case ISD::AssertAlign:
848     ID.AddInteger(cast<AssertAlignSDNode>(N)->getAlign().value());
849     break;
850   } // end switch (N->getOpcode())
851 
852   // Target specific memory nodes could also have address spaces and flags
853   // to check.
854   if (N->isTargetMemoryOpcode()) {
855     const MemSDNode *MN = cast<MemSDNode>(N);
856     ID.AddInteger(MN->getPointerInfo().getAddrSpace());
857     ID.AddInteger(MN->getMemOperand()->getFlags());
858   }
859 }
860 
861 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID
862 /// data.
863 static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) {
864   AddNodeIDOpcode(ID, N->getOpcode());
865   // Add the return value info.
866   AddNodeIDValueTypes(ID, N->getVTList());
867   // Add the operand info.
868   AddNodeIDOperands(ID, N->ops());
869 
870   // Handle SDNode leafs with special info.
871   AddNodeIDCustom(ID, N);
872 }
873 
874 //===----------------------------------------------------------------------===//
875 //                              SelectionDAG Class
876 //===----------------------------------------------------------------------===//
877 
878 /// doNotCSE - Return true if CSE should not be performed for this node.
879 static bool doNotCSE(SDNode *N) {
880   if (N->getValueType(0) == MVT::Glue)
881     return true; // Never CSE anything that produces a flag.
882 
883   switch (N->getOpcode()) {
884   default: break;
885   case ISD::HANDLENODE:
886   case ISD::EH_LABEL:
887     return true;   // Never CSE these nodes.
888   }
889 
890   // Check that remaining values produced are not flags.
891   for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
892     if (N->getValueType(i) == MVT::Glue)
893       return true; // Never CSE anything that produces a flag.
894 
895   return false;
896 }
897 
898 /// RemoveDeadNodes - This method deletes all unreachable nodes in the
899 /// SelectionDAG.
900 void SelectionDAG::RemoveDeadNodes() {
901   // Create a dummy node (which is not added to allnodes), that adds a reference
902   // to the root node, preventing it from being deleted.
903   HandleSDNode Dummy(getRoot());
904 
905   SmallVector<SDNode*, 128> DeadNodes;
906 
907   // Add all obviously-dead nodes to the DeadNodes worklist.
908   for (SDNode &Node : allnodes())
909     if (Node.use_empty())
910       DeadNodes.push_back(&Node);
911 
912   RemoveDeadNodes(DeadNodes);
913 
914   // If the root changed (e.g. it was a dead load, update the root).
915   setRoot(Dummy.getValue());
916 }
917 
918 /// RemoveDeadNodes - This method deletes the unreachable nodes in the
919 /// given list, and any nodes that become unreachable as a result.
920 void SelectionDAG::RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes) {
921 
922   // Process the worklist, deleting the nodes and adding their uses to the
923   // worklist.
924   while (!DeadNodes.empty()) {
925     SDNode *N = DeadNodes.pop_back_val();
926     // Skip to next node if we've already managed to delete the node. This could
927     // happen if replacing a node causes a node previously added to the node to
928     // be deleted.
929     if (N->getOpcode() == ISD::DELETED_NODE)
930       continue;
931 
932     for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
933       DUL->NodeDeleted(N, nullptr);
934 
935     // Take the node out of the appropriate CSE map.
936     RemoveNodeFromCSEMaps(N);
937 
938     // Next, brutally remove the operand list.  This is safe to do, as there are
939     // no cycles in the graph.
940     for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
941       SDUse &Use = *I++;
942       SDNode *Operand = Use.getNode();
943       Use.set(SDValue());
944 
945       // Now that we removed this operand, see if there are no uses of it left.
946       if (Operand->use_empty())
947         DeadNodes.push_back(Operand);
948     }
949 
950     DeallocateNode(N);
951   }
952 }
953 
954 void SelectionDAG::RemoveDeadNode(SDNode *N){
955   SmallVector<SDNode*, 16> DeadNodes(1, N);
956 
957   // Create a dummy node that adds a reference to the root node, preventing
958   // it from being deleted.  (This matters if the root is an operand of the
959   // dead node.)
960   HandleSDNode Dummy(getRoot());
961 
962   RemoveDeadNodes(DeadNodes);
963 }
964 
965 void SelectionDAG::DeleteNode(SDNode *N) {
966   // First take this out of the appropriate CSE map.
967   RemoveNodeFromCSEMaps(N);
968 
969   // Finally, remove uses due to operands of this node, remove from the
970   // AllNodes list, and delete the node.
971   DeleteNodeNotInCSEMaps(N);
972 }
973 
974 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
975   assert(N->getIterator() != AllNodes.begin() &&
976          "Cannot delete the entry node!");
977   assert(N->use_empty() && "Cannot delete a node that is not dead!");
978 
979   // Drop all of the operands and decrement used node's use counts.
980   N->DropOperands();
981 
982   DeallocateNode(N);
983 }
984 
985 void SDDbgInfo::add(SDDbgValue *V, bool isParameter) {
986   assert(!(V->isVariadic() && isParameter));
987   if (isParameter)
988     ByvalParmDbgValues.push_back(V);
989   else
990     DbgValues.push_back(V);
991   for (const SDNode *Node : V->getSDNodes())
992     if (Node)
993       DbgValMap[Node].push_back(V);
994 }
995 
996 void SDDbgInfo::erase(const SDNode *Node) {
997   DbgValMapType::iterator I = DbgValMap.find(Node);
998   if (I == DbgValMap.end())
999     return;
1000   for (auto &Val: I->second)
1001     Val->setIsInvalidated();
1002   DbgValMap.erase(I);
1003 }
1004 
1005 void SelectionDAG::DeallocateNode(SDNode *N) {
1006   // If we have operands, deallocate them.
1007   removeOperands(N);
1008 
1009   NodeAllocator.Deallocate(AllNodes.remove(N));
1010 
1011   // Set the opcode to DELETED_NODE to help catch bugs when node
1012   // memory is reallocated.
1013   // FIXME: There are places in SDag that have grown a dependency on the opcode
1014   // value in the released node.
1015   __asan_unpoison_memory_region(&N->NodeType, sizeof(N->NodeType));
1016   N->NodeType = ISD::DELETED_NODE;
1017 
1018   // If any of the SDDbgValue nodes refer to this SDNode, invalidate
1019   // them and forget about that node.
1020   DbgInfo->erase(N);
1021 }
1022 
1023 #ifndef NDEBUG
1024 /// VerifySDNode - Check the given SDNode.  Aborts if it is invalid.
1025 static void VerifySDNode(SDNode *N) {
1026   switch (N->getOpcode()) {
1027   default:
1028     break;
1029   case ISD::BUILD_PAIR: {
1030     EVT VT = N->getValueType(0);
1031     assert(N->getNumValues() == 1 && "Too many results!");
1032     assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) &&
1033            "Wrong return type!");
1034     assert(N->getNumOperands() == 2 && "Wrong number of operands!");
1035     assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() &&
1036            "Mismatched operand types!");
1037     assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() &&
1038            "Wrong operand type!");
1039     assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() &&
1040            "Wrong return type size");
1041     break;
1042   }
1043   case ISD::BUILD_VECTOR: {
1044     assert(N->getNumValues() == 1 && "Too many results!");
1045     assert(N->getValueType(0).isVector() && "Wrong return type!");
1046     assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() &&
1047            "Wrong number of operands!");
1048     EVT EltVT = N->getValueType(0).getVectorElementType();
1049     for (const SDUse &Op : N->ops()) {
1050       assert((Op.getValueType() == EltVT ||
1051               (EltVT.isInteger() && Op.getValueType().isInteger() &&
1052                EltVT.bitsLE(Op.getValueType()))) &&
1053              "Wrong operand type!");
1054       assert(Op.getValueType() == N->getOperand(0).getValueType() &&
1055              "Operands must all have the same type");
1056     }
1057     break;
1058   }
1059   }
1060 }
1061 #endif // NDEBUG
1062 
1063 /// Insert a newly allocated node into the DAG.
1064 ///
1065 /// Handles insertion into the all nodes list and CSE map, as well as
1066 /// verification and other common operations when a new node is allocated.
1067 void SelectionDAG::InsertNode(SDNode *N) {
1068   AllNodes.push_back(N);
1069 #ifndef NDEBUG
1070   N->PersistentId = NextPersistentId++;
1071   VerifySDNode(N);
1072 #endif
1073   for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1074     DUL->NodeInserted(N);
1075 }
1076 
1077 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
1078 /// correspond to it.  This is useful when we're about to delete or repurpose
1079 /// the node.  We don't want future request for structurally identical nodes
1080 /// to return N anymore.
1081 bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
1082   bool Erased = false;
1083   switch (N->getOpcode()) {
1084   case ISD::HANDLENODE: return false;  // noop.
1085   case ISD::CONDCODE:
1086     assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
1087            "Cond code doesn't exist!");
1088     Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != nullptr;
1089     CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = nullptr;
1090     break;
1091   case ISD::ExternalSymbol:
1092     Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
1093     break;
1094   case ISD::TargetExternalSymbol: {
1095     ExternalSymbolSDNode *ESN = cast<ExternalSymbolSDNode>(N);
1096     Erased = TargetExternalSymbols.erase(std::pair<std::string, unsigned>(
1097         ESN->getSymbol(), ESN->getTargetFlags()));
1098     break;
1099   }
1100   case ISD::MCSymbol: {
1101     auto *MCSN = cast<MCSymbolSDNode>(N);
1102     Erased = MCSymbols.erase(MCSN->getMCSymbol());
1103     break;
1104   }
1105   case ISD::VALUETYPE: {
1106     EVT VT = cast<VTSDNode>(N)->getVT();
1107     if (VT.isExtended()) {
1108       Erased = ExtendedValueTypeNodes.erase(VT);
1109     } else {
1110       Erased = ValueTypeNodes[VT.getSimpleVT().SimpleTy] != nullptr;
1111       ValueTypeNodes[VT.getSimpleVT().SimpleTy] = nullptr;
1112     }
1113     break;
1114   }
1115   default:
1116     // Remove it from the CSE Map.
1117     assert(N->getOpcode() != ISD::DELETED_NODE && "DELETED_NODE in CSEMap!");
1118     assert(N->getOpcode() != ISD::EntryToken && "EntryToken in CSEMap!");
1119     Erased = CSEMap.RemoveNode(N);
1120     break;
1121   }
1122 #ifndef NDEBUG
1123   // Verify that the node was actually in one of the CSE maps, unless it has a
1124   // flag result (which cannot be CSE'd) or is one of the special cases that are
1125   // not subject to CSE.
1126   if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Glue &&
1127       !N->isMachineOpcode() && !doNotCSE(N)) {
1128     N->dump(this);
1129     dbgs() << "\n";
1130     llvm_unreachable("Node is not in map!");
1131   }
1132 #endif
1133   return Erased;
1134 }
1135 
1136 /// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE
1137 /// maps and modified in place. Add it back to the CSE maps, unless an identical
1138 /// node already exists, in which case transfer all its users to the existing
1139 /// node. This transfer can potentially trigger recursive merging.
1140 void
1141 SelectionDAG::AddModifiedNodeToCSEMaps(SDNode *N) {
1142   // For node types that aren't CSE'd, just act as if no identical node
1143   // already exists.
1144   if (!doNotCSE(N)) {
1145     SDNode *Existing = CSEMap.GetOrInsertNode(N);
1146     if (Existing != N) {
1147       // If there was already an existing matching node, use ReplaceAllUsesWith
1148       // to replace the dead one with the existing one.  This can cause
1149       // recursive merging of other unrelated nodes down the line.
1150       ReplaceAllUsesWith(N, Existing);
1151 
1152       // N is now dead. Inform the listeners and delete it.
1153       for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1154         DUL->NodeDeleted(N, Existing);
1155       DeleteNodeNotInCSEMaps(N);
1156       return;
1157     }
1158   }
1159 
1160   // If the node doesn't already exist, we updated it.  Inform listeners.
1161   for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1162     DUL->NodeUpdated(N);
1163 }
1164 
1165 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1166 /// were replaced with those specified.  If this node is never memoized,
1167 /// return null, otherwise return a pointer to the slot it would take.  If a
1168 /// node already exists with these operands, the slot will be non-null.
1169 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op,
1170                                            void *&InsertPos) {
1171   if (doNotCSE(N))
1172     return nullptr;
1173 
1174   SDValue Ops[] = { Op };
1175   FoldingSetNodeID ID;
1176   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1177   AddNodeIDCustom(ID, N);
1178   SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1179   if (Node)
1180     Node->intersectFlagsWith(N->getFlags());
1181   return Node;
1182 }
1183 
1184 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1185 /// were replaced with those specified.  If this node is never memoized,
1186 /// return null, otherwise return a pointer to the slot it would take.  If a
1187 /// node already exists with these operands, the slot will be non-null.
1188 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
1189                                            SDValue Op1, SDValue Op2,
1190                                            void *&InsertPos) {
1191   if (doNotCSE(N))
1192     return nullptr;
1193 
1194   SDValue Ops[] = { Op1, Op2 };
1195   FoldingSetNodeID ID;
1196   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1197   AddNodeIDCustom(ID, N);
1198   SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1199   if (Node)
1200     Node->intersectFlagsWith(N->getFlags());
1201   return Node;
1202 }
1203 
1204 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1205 /// were replaced with those specified.  If this node is never memoized,
1206 /// return null, otherwise return a pointer to the slot it would take.  If a
1207 /// node already exists with these operands, the slot will be non-null.
1208 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, ArrayRef<SDValue> Ops,
1209                                            void *&InsertPos) {
1210   if (doNotCSE(N))
1211     return nullptr;
1212 
1213   FoldingSetNodeID ID;
1214   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1215   AddNodeIDCustom(ID, N);
1216   SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1217   if (Node)
1218     Node->intersectFlagsWith(N->getFlags());
1219   return Node;
1220 }
1221 
1222 Align SelectionDAG::getEVTAlign(EVT VT) const {
1223   Type *Ty = VT == MVT::iPTR ?
1224                    PointerType::get(Type::getInt8Ty(*getContext()), 0) :
1225                    VT.getTypeForEVT(*getContext());
1226 
1227   return getDataLayout().getABITypeAlign(Ty);
1228 }
1229 
1230 // EntryNode could meaningfully have debug info if we can find it...
1231 SelectionDAG::SelectionDAG(const TargetMachine &tm, CodeGenOpt::Level OL)
1232     : TM(tm), OptLevel(OL),
1233       EntryNode(ISD::EntryToken, 0, DebugLoc(), getVTList(MVT::Other)),
1234       Root(getEntryNode()) {
1235   InsertNode(&EntryNode);
1236   DbgInfo = new SDDbgInfo();
1237 }
1238 
1239 void SelectionDAG::init(MachineFunction &NewMF,
1240                         OptimizationRemarkEmitter &NewORE,
1241                         Pass *PassPtr, const TargetLibraryInfo *LibraryInfo,
1242                         LegacyDivergenceAnalysis * Divergence,
1243                         ProfileSummaryInfo *PSIin,
1244                         BlockFrequencyInfo *BFIin) {
1245   MF = &NewMF;
1246   SDAGISelPass = PassPtr;
1247   ORE = &NewORE;
1248   TLI = getSubtarget().getTargetLowering();
1249   TSI = getSubtarget().getSelectionDAGInfo();
1250   LibInfo = LibraryInfo;
1251   Context = &MF->getFunction().getContext();
1252   DA = Divergence;
1253   PSI = PSIin;
1254   BFI = BFIin;
1255 }
1256 
1257 SelectionDAG::~SelectionDAG() {
1258   assert(!UpdateListeners && "Dangling registered DAGUpdateListeners");
1259   allnodes_clear();
1260   OperandRecycler.clear(OperandAllocator);
1261   delete DbgInfo;
1262 }
1263 
1264 bool SelectionDAG::shouldOptForSize() const {
1265   return MF->getFunction().hasOptSize() ||
1266       llvm::shouldOptimizeForSize(FLI->MBB->getBasicBlock(), PSI, BFI);
1267 }
1268 
1269 void SelectionDAG::allnodes_clear() {
1270   assert(&*AllNodes.begin() == &EntryNode);
1271   AllNodes.remove(AllNodes.begin());
1272   while (!AllNodes.empty())
1273     DeallocateNode(&AllNodes.front());
1274 #ifndef NDEBUG
1275   NextPersistentId = 0;
1276 #endif
1277 }
1278 
1279 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
1280                                           void *&InsertPos) {
1281   SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
1282   if (N) {
1283     switch (N->getOpcode()) {
1284     default: break;
1285     case ISD::Constant:
1286     case ISD::ConstantFP:
1287       llvm_unreachable("Querying for Constant and ConstantFP nodes requires "
1288                        "debug location.  Use another overload.");
1289     }
1290   }
1291   return N;
1292 }
1293 
1294 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
1295                                           const SDLoc &DL, void *&InsertPos) {
1296   SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
1297   if (N) {
1298     switch (N->getOpcode()) {
1299     case ISD::Constant:
1300     case ISD::ConstantFP:
1301       // Erase debug location from the node if the node is used at several
1302       // different places. Do not propagate one location to all uses as it
1303       // will cause a worse single stepping debugging experience.
1304       if (N->getDebugLoc() != DL.getDebugLoc())
1305         N->setDebugLoc(DebugLoc());
1306       break;
1307     default:
1308       // When the node's point of use is located earlier in the instruction
1309       // sequence than its prior point of use, update its debug info to the
1310       // earlier location.
1311       if (DL.getIROrder() && DL.getIROrder() < N->getIROrder())
1312         N->setDebugLoc(DL.getDebugLoc());
1313       break;
1314     }
1315   }
1316   return N;
1317 }
1318 
1319 void SelectionDAG::clear() {
1320   allnodes_clear();
1321   OperandRecycler.clear(OperandAllocator);
1322   OperandAllocator.Reset();
1323   CSEMap.clear();
1324 
1325   ExtendedValueTypeNodes.clear();
1326   ExternalSymbols.clear();
1327   TargetExternalSymbols.clear();
1328   MCSymbols.clear();
1329   SDCallSiteDbgInfo.clear();
1330   std::fill(CondCodeNodes.begin(), CondCodeNodes.end(),
1331             static_cast<CondCodeSDNode*>(nullptr));
1332   std::fill(ValueTypeNodes.begin(), ValueTypeNodes.end(),
1333             static_cast<SDNode*>(nullptr));
1334 
1335   EntryNode.UseList = nullptr;
1336   InsertNode(&EntryNode);
1337   Root = getEntryNode();
1338   DbgInfo->clear();
1339 }
1340 
1341 SDValue SelectionDAG::getFPExtendOrRound(SDValue Op, const SDLoc &DL, EVT VT) {
1342   return VT.bitsGT(Op.getValueType())
1343              ? getNode(ISD::FP_EXTEND, DL, VT, Op)
1344              : getNode(ISD::FP_ROUND, DL, VT, Op, getIntPtrConstant(0, DL));
1345 }
1346 
1347 std::pair<SDValue, SDValue>
1348 SelectionDAG::getStrictFPExtendOrRound(SDValue Op, SDValue Chain,
1349                                        const SDLoc &DL, EVT VT) {
1350   assert(!VT.bitsEq(Op.getValueType()) &&
1351          "Strict no-op FP extend/round not allowed.");
1352   SDValue Res =
1353       VT.bitsGT(Op.getValueType())
1354           ? getNode(ISD::STRICT_FP_EXTEND, DL, {VT, MVT::Other}, {Chain, Op})
1355           : getNode(ISD::STRICT_FP_ROUND, DL, {VT, MVT::Other},
1356                     {Chain, Op, getIntPtrConstant(0, DL)});
1357 
1358   return std::pair<SDValue, SDValue>(Res, SDValue(Res.getNode(), 1));
1359 }
1360 
1361 SDValue SelectionDAG::getAnyExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1362   return VT.bitsGT(Op.getValueType()) ?
1363     getNode(ISD::ANY_EXTEND, DL, VT, Op) :
1364     getNode(ISD::TRUNCATE, DL, VT, Op);
1365 }
1366 
1367 SDValue SelectionDAG::getSExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1368   return VT.bitsGT(Op.getValueType()) ?
1369     getNode(ISD::SIGN_EXTEND, DL, VT, Op) :
1370     getNode(ISD::TRUNCATE, DL, VT, Op);
1371 }
1372 
1373 SDValue SelectionDAG::getZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1374   return VT.bitsGT(Op.getValueType()) ?
1375     getNode(ISD::ZERO_EXTEND, DL, VT, Op) :
1376     getNode(ISD::TRUNCATE, DL, VT, Op);
1377 }
1378 
1379 SDValue SelectionDAG::getBoolExtOrTrunc(SDValue Op, const SDLoc &SL, EVT VT,
1380                                         EVT OpVT) {
1381   if (VT.bitsLE(Op.getValueType()))
1382     return getNode(ISD::TRUNCATE, SL, VT, Op);
1383 
1384   TargetLowering::BooleanContent BType = TLI->getBooleanContents(OpVT);
1385   return getNode(TLI->getExtendForContent(BType), SL, VT, Op);
1386 }
1387 
1388 SDValue SelectionDAG::getZeroExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) {
1389   EVT OpVT = Op.getValueType();
1390   assert(VT.isInteger() && OpVT.isInteger() &&
1391          "Cannot getZeroExtendInReg FP types");
1392   assert(VT.isVector() == OpVT.isVector() &&
1393          "getZeroExtendInReg type should be vector iff the operand "
1394          "type is vector!");
1395   assert((!VT.isVector() ||
1396           VT.getVectorElementCount() == OpVT.getVectorElementCount()) &&
1397          "Vector element counts must match in getZeroExtendInReg");
1398   assert(VT.bitsLE(OpVT) && "Not extending!");
1399   if (OpVT == VT)
1400     return Op;
1401   APInt Imm = APInt::getLowBitsSet(OpVT.getScalarSizeInBits(),
1402                                    VT.getScalarSizeInBits());
1403   return getNode(ISD::AND, DL, OpVT, Op, getConstant(Imm, DL, OpVT));
1404 }
1405 
1406 SDValue SelectionDAG::getPtrExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1407   // Only unsigned pointer semantics are supported right now. In the future this
1408   // might delegate to TLI to check pointer signedness.
1409   return getZExtOrTrunc(Op, DL, VT);
1410 }
1411 
1412 SDValue SelectionDAG::getPtrExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) {
1413   // Only unsigned pointer semantics are supported right now. In the future this
1414   // might delegate to TLI to check pointer signedness.
1415   return getZeroExtendInReg(Op, DL, VT);
1416 }
1417 
1418 /// getNOT - Create a bitwise NOT operation as (XOR Val, -1).
1419 SDValue SelectionDAG::getNOT(const SDLoc &DL, SDValue Val, EVT VT) {
1420   return getNode(ISD::XOR, DL, VT, Val, getAllOnesConstant(DL, VT));
1421 }
1422 
1423 SDValue SelectionDAG::getLogicalNOT(const SDLoc &DL, SDValue Val, EVT VT) {
1424   SDValue TrueValue = getBoolConstant(true, DL, VT, VT);
1425   return getNode(ISD::XOR, DL, VT, Val, TrueValue);
1426 }
1427 
1428 SDValue SelectionDAG::getVPLogicalNOT(const SDLoc &DL, SDValue Val,
1429                                       SDValue Mask, SDValue EVL, EVT VT) {
1430   SDValue TrueValue = getBoolConstant(true, DL, VT, VT);
1431   return getNode(ISD::VP_XOR, DL, VT, Val, TrueValue, Mask, EVL);
1432 }
1433 
1434 SDValue SelectionDAG::getBoolConstant(bool V, const SDLoc &DL, EVT VT,
1435                                       EVT OpVT) {
1436   if (!V)
1437     return getConstant(0, DL, VT);
1438 
1439   switch (TLI->getBooleanContents(OpVT)) {
1440   case TargetLowering::ZeroOrOneBooleanContent:
1441   case TargetLowering::UndefinedBooleanContent:
1442     return getConstant(1, DL, VT);
1443   case TargetLowering::ZeroOrNegativeOneBooleanContent:
1444     return getAllOnesConstant(DL, VT);
1445   }
1446   llvm_unreachable("Unexpected boolean content enum!");
1447 }
1448 
1449 SDValue SelectionDAG::getConstant(uint64_t Val, const SDLoc &DL, EVT VT,
1450                                   bool isT, bool isO) {
1451   EVT EltVT = VT.getScalarType();
1452   assert((EltVT.getSizeInBits() >= 64 ||
1453           (uint64_t)((int64_t)Val >> EltVT.getSizeInBits()) + 1 < 2) &&
1454          "getConstant with a uint64_t value that doesn't fit in the type!");
1455   return getConstant(APInt(EltVT.getSizeInBits(), Val), DL, VT, isT, isO);
1456 }
1457 
1458 SDValue SelectionDAG::getConstant(const APInt &Val, const SDLoc &DL, EVT VT,
1459                                   bool isT, bool isO) {
1460   return getConstant(*ConstantInt::get(*Context, Val), DL, VT, isT, isO);
1461 }
1462 
1463 SDValue SelectionDAG::getConstant(const ConstantInt &Val, const SDLoc &DL,
1464                                   EVT VT, bool isT, bool isO) {
1465   assert(VT.isInteger() && "Cannot create FP integer constant!");
1466 
1467   EVT EltVT = VT.getScalarType();
1468   const ConstantInt *Elt = &Val;
1469 
1470   // In some cases the vector type is legal but the element type is illegal and
1471   // needs to be promoted, for example v8i8 on ARM.  In this case, promote the
1472   // inserted value (the type does not need to match the vector element type).
1473   // Any extra bits introduced will be truncated away.
1474   if (VT.isVector() && TLI->getTypeAction(*getContext(), EltVT) ==
1475                            TargetLowering::TypePromoteInteger) {
1476     EltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1477     APInt NewVal = Elt->getValue().zextOrTrunc(EltVT.getSizeInBits());
1478     Elt = ConstantInt::get(*getContext(), NewVal);
1479   }
1480   // In other cases the element type is illegal and needs to be expanded, for
1481   // example v2i64 on MIPS32. In this case, find the nearest legal type, split
1482   // the value into n parts and use a vector type with n-times the elements.
1483   // Then bitcast to the type requested.
1484   // Legalizing constants too early makes the DAGCombiner's job harder so we
1485   // only legalize if the DAG tells us we must produce legal types.
1486   else if (NewNodesMustHaveLegalTypes && VT.isVector() &&
1487            TLI->getTypeAction(*getContext(), EltVT) ==
1488                TargetLowering::TypeExpandInteger) {
1489     const APInt &NewVal = Elt->getValue();
1490     EVT ViaEltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1491     unsigned ViaEltSizeInBits = ViaEltVT.getSizeInBits();
1492 
1493     // For scalable vectors, try to use a SPLAT_VECTOR_PARTS node.
1494     if (VT.isScalableVector()) {
1495       assert(EltVT.getSizeInBits() % ViaEltSizeInBits == 0 &&
1496              "Can only handle an even split!");
1497       unsigned Parts = EltVT.getSizeInBits() / ViaEltSizeInBits;
1498 
1499       SmallVector<SDValue, 2> ScalarParts;
1500       for (unsigned i = 0; i != Parts; ++i)
1501         ScalarParts.push_back(getConstant(
1502             NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL,
1503             ViaEltVT, isT, isO));
1504 
1505       return getNode(ISD::SPLAT_VECTOR_PARTS, DL, VT, ScalarParts);
1506     }
1507 
1508     unsigned ViaVecNumElts = VT.getSizeInBits() / ViaEltSizeInBits;
1509     EVT ViaVecVT = EVT::getVectorVT(*getContext(), ViaEltVT, ViaVecNumElts);
1510 
1511     // Check the temporary vector is the correct size. If this fails then
1512     // getTypeToTransformTo() probably returned a type whose size (in bits)
1513     // isn't a power-of-2 factor of the requested type size.
1514     assert(ViaVecVT.getSizeInBits() == VT.getSizeInBits());
1515 
1516     SmallVector<SDValue, 2> EltParts;
1517     for (unsigned i = 0; i < ViaVecNumElts / VT.getVectorNumElements(); ++i)
1518       EltParts.push_back(getConstant(
1519           NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL,
1520           ViaEltVT, isT, isO));
1521 
1522     // EltParts is currently in little endian order. If we actually want
1523     // big-endian order then reverse it now.
1524     if (getDataLayout().isBigEndian())
1525       std::reverse(EltParts.begin(), EltParts.end());
1526 
1527     // The elements must be reversed when the element order is different
1528     // to the endianness of the elements (because the BITCAST is itself a
1529     // vector shuffle in this situation). However, we do not need any code to
1530     // perform this reversal because getConstant() is producing a vector
1531     // splat.
1532     // This situation occurs in MIPS MSA.
1533 
1534     SmallVector<SDValue, 8> Ops;
1535     for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
1536       llvm::append_range(Ops, EltParts);
1537 
1538     SDValue V =
1539         getNode(ISD::BITCAST, DL, VT, getBuildVector(ViaVecVT, DL, Ops));
1540     return V;
1541   }
1542 
1543   assert(Elt->getBitWidth() == EltVT.getSizeInBits() &&
1544          "APInt size does not match type size!");
1545   unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
1546   FoldingSetNodeID ID;
1547   AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
1548   ID.AddPointer(Elt);
1549   ID.AddBoolean(isO);
1550   void *IP = nullptr;
1551   SDNode *N = nullptr;
1552   if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1553     if (!VT.isVector())
1554       return SDValue(N, 0);
1555 
1556   if (!N) {
1557     N = newSDNode<ConstantSDNode>(isT, isO, Elt, EltVT);
1558     CSEMap.InsertNode(N, IP);
1559     InsertNode(N);
1560     NewSDValueDbgMsg(SDValue(N, 0), "Creating constant: ", this);
1561   }
1562 
1563   SDValue Result(N, 0);
1564   if (VT.isScalableVector())
1565     Result = getSplatVector(VT, DL, Result);
1566   else if (VT.isVector())
1567     Result = getSplatBuildVector(VT, DL, Result);
1568 
1569   return Result;
1570 }
1571 
1572 SDValue SelectionDAG::getIntPtrConstant(uint64_t Val, const SDLoc &DL,
1573                                         bool isTarget) {
1574   return getConstant(Val, DL, TLI->getPointerTy(getDataLayout()), isTarget);
1575 }
1576 
1577 SDValue SelectionDAG::getShiftAmountConstant(uint64_t Val, EVT VT,
1578                                              const SDLoc &DL, bool LegalTypes) {
1579   assert(VT.isInteger() && "Shift amount is not an integer type!");
1580   EVT ShiftVT = TLI->getShiftAmountTy(VT, getDataLayout(), LegalTypes);
1581   return getConstant(Val, DL, ShiftVT);
1582 }
1583 
1584 SDValue SelectionDAG::getVectorIdxConstant(uint64_t Val, const SDLoc &DL,
1585                                            bool isTarget) {
1586   return getConstant(Val, DL, TLI->getVectorIdxTy(getDataLayout()), isTarget);
1587 }
1588 
1589 SDValue SelectionDAG::getConstantFP(const APFloat &V, const SDLoc &DL, EVT VT,
1590                                     bool isTarget) {
1591   return getConstantFP(*ConstantFP::get(*getContext(), V), DL, VT, isTarget);
1592 }
1593 
1594 SDValue SelectionDAG::getConstantFP(const ConstantFP &V, const SDLoc &DL,
1595                                     EVT VT, bool isTarget) {
1596   assert(VT.isFloatingPoint() && "Cannot create integer FP constant!");
1597 
1598   EVT EltVT = VT.getScalarType();
1599 
1600   // Do the map lookup using the actual bit pattern for the floating point
1601   // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
1602   // we don't have issues with SNANs.
1603   unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
1604   FoldingSetNodeID ID;
1605   AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
1606   ID.AddPointer(&V);
1607   void *IP = nullptr;
1608   SDNode *N = nullptr;
1609   if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1610     if (!VT.isVector())
1611       return SDValue(N, 0);
1612 
1613   if (!N) {
1614     N = newSDNode<ConstantFPSDNode>(isTarget, &V, EltVT);
1615     CSEMap.InsertNode(N, IP);
1616     InsertNode(N);
1617   }
1618 
1619   SDValue Result(N, 0);
1620   if (VT.isScalableVector())
1621     Result = getSplatVector(VT, DL, Result);
1622   else if (VT.isVector())
1623     Result = getSplatBuildVector(VT, DL, Result);
1624   NewSDValueDbgMsg(Result, "Creating fp constant: ", this);
1625   return Result;
1626 }
1627 
1628 SDValue SelectionDAG::getConstantFP(double Val, const SDLoc &DL, EVT VT,
1629                                     bool isTarget) {
1630   EVT EltVT = VT.getScalarType();
1631   if (EltVT == MVT::f32)
1632     return getConstantFP(APFloat((float)Val), DL, VT, isTarget);
1633   if (EltVT == MVT::f64)
1634     return getConstantFP(APFloat(Val), DL, VT, isTarget);
1635   if (EltVT == MVT::f80 || EltVT == MVT::f128 || EltVT == MVT::ppcf128 ||
1636       EltVT == MVT::f16 || EltVT == MVT::bf16) {
1637     bool Ignored;
1638     APFloat APF = APFloat(Val);
1639     APF.convert(EVTToAPFloatSemantics(EltVT), APFloat::rmNearestTiesToEven,
1640                 &Ignored);
1641     return getConstantFP(APF, DL, VT, isTarget);
1642   }
1643   llvm_unreachable("Unsupported type in getConstantFP");
1644 }
1645 
1646 SDValue SelectionDAG::getGlobalAddress(const GlobalValue *GV, const SDLoc &DL,
1647                                        EVT VT, int64_t Offset, bool isTargetGA,
1648                                        unsigned TargetFlags) {
1649   assert((TargetFlags == 0 || isTargetGA) &&
1650          "Cannot set target flags on target-independent globals");
1651 
1652   // Truncate (with sign-extension) the offset value to the pointer size.
1653   unsigned BitWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
1654   if (BitWidth < 64)
1655     Offset = SignExtend64(Offset, BitWidth);
1656 
1657   unsigned Opc;
1658   if (GV->isThreadLocal())
1659     Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress;
1660   else
1661     Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress;
1662 
1663   FoldingSetNodeID ID;
1664   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1665   ID.AddPointer(GV);
1666   ID.AddInteger(Offset);
1667   ID.AddInteger(TargetFlags);
1668   void *IP = nullptr;
1669   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
1670     return SDValue(E, 0);
1671 
1672   auto *N = newSDNode<GlobalAddressSDNode>(
1673       Opc, DL.getIROrder(), DL.getDebugLoc(), GV, VT, Offset, TargetFlags);
1674   CSEMap.InsertNode(N, IP);
1675     InsertNode(N);
1676   return SDValue(N, 0);
1677 }
1678 
1679 SDValue SelectionDAG::getFrameIndex(int FI, EVT VT, bool isTarget) {
1680   unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
1681   FoldingSetNodeID ID;
1682   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1683   ID.AddInteger(FI);
1684   void *IP = nullptr;
1685   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1686     return SDValue(E, 0);
1687 
1688   auto *N = newSDNode<FrameIndexSDNode>(FI, VT, isTarget);
1689   CSEMap.InsertNode(N, IP);
1690   InsertNode(N);
1691   return SDValue(N, 0);
1692 }
1693 
1694 SDValue SelectionDAG::getJumpTable(int JTI, EVT VT, bool isTarget,
1695                                    unsigned TargetFlags) {
1696   assert((TargetFlags == 0 || isTarget) &&
1697          "Cannot set target flags on target-independent jump tables");
1698   unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
1699   FoldingSetNodeID ID;
1700   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1701   ID.AddInteger(JTI);
1702   ID.AddInteger(TargetFlags);
1703   void *IP = nullptr;
1704   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1705     return SDValue(E, 0);
1706 
1707   auto *N = newSDNode<JumpTableSDNode>(JTI, VT, isTarget, TargetFlags);
1708   CSEMap.InsertNode(N, IP);
1709   InsertNode(N);
1710   return SDValue(N, 0);
1711 }
1712 
1713 SDValue SelectionDAG::getConstantPool(const Constant *C, EVT VT,
1714                                       MaybeAlign Alignment, int Offset,
1715                                       bool isTarget, unsigned TargetFlags) {
1716   assert((TargetFlags == 0 || isTarget) &&
1717          "Cannot set target flags on target-independent globals");
1718   if (!Alignment)
1719     Alignment = shouldOptForSize()
1720                     ? getDataLayout().getABITypeAlign(C->getType())
1721                     : getDataLayout().getPrefTypeAlign(C->getType());
1722   unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1723   FoldingSetNodeID ID;
1724   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1725   ID.AddInteger(Alignment->value());
1726   ID.AddInteger(Offset);
1727   ID.AddPointer(C);
1728   ID.AddInteger(TargetFlags);
1729   void *IP = nullptr;
1730   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1731     return SDValue(E, 0);
1732 
1733   auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment,
1734                                           TargetFlags);
1735   CSEMap.InsertNode(N, IP);
1736   InsertNode(N);
1737   SDValue V = SDValue(N, 0);
1738   NewSDValueDbgMsg(V, "Creating new constant pool: ", this);
1739   return V;
1740 }
1741 
1742 SDValue SelectionDAG::getConstantPool(MachineConstantPoolValue *C, EVT VT,
1743                                       MaybeAlign Alignment, int Offset,
1744                                       bool isTarget, unsigned TargetFlags) {
1745   assert((TargetFlags == 0 || isTarget) &&
1746          "Cannot set target flags on target-independent globals");
1747   if (!Alignment)
1748     Alignment = getDataLayout().getPrefTypeAlign(C->getType());
1749   unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1750   FoldingSetNodeID ID;
1751   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1752   ID.AddInteger(Alignment->value());
1753   ID.AddInteger(Offset);
1754   C->addSelectionDAGCSEId(ID);
1755   ID.AddInteger(TargetFlags);
1756   void *IP = nullptr;
1757   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1758     return SDValue(E, 0);
1759 
1760   auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment,
1761                                           TargetFlags);
1762   CSEMap.InsertNode(N, IP);
1763   InsertNode(N);
1764   return SDValue(N, 0);
1765 }
1766 
1767 SDValue SelectionDAG::getTargetIndex(int Index, EVT VT, int64_t Offset,
1768                                      unsigned TargetFlags) {
1769   FoldingSetNodeID ID;
1770   AddNodeIDNode(ID, ISD::TargetIndex, getVTList(VT), None);
1771   ID.AddInteger(Index);
1772   ID.AddInteger(Offset);
1773   ID.AddInteger(TargetFlags);
1774   void *IP = nullptr;
1775   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1776     return SDValue(E, 0);
1777 
1778   auto *N = newSDNode<TargetIndexSDNode>(Index, VT, Offset, TargetFlags);
1779   CSEMap.InsertNode(N, IP);
1780   InsertNode(N);
1781   return SDValue(N, 0);
1782 }
1783 
1784 SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
1785   FoldingSetNodeID ID;
1786   AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), None);
1787   ID.AddPointer(MBB);
1788   void *IP = nullptr;
1789   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1790     return SDValue(E, 0);
1791 
1792   auto *N = newSDNode<BasicBlockSDNode>(MBB);
1793   CSEMap.InsertNode(N, IP);
1794   InsertNode(N);
1795   return SDValue(N, 0);
1796 }
1797 
1798 SDValue SelectionDAG::getValueType(EVT VT) {
1799   if (VT.isSimple() && (unsigned)VT.getSimpleVT().SimpleTy >=
1800       ValueTypeNodes.size())
1801     ValueTypeNodes.resize(VT.getSimpleVT().SimpleTy+1);
1802 
1803   SDNode *&N = VT.isExtended() ?
1804     ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT().SimpleTy];
1805 
1806   if (N) return SDValue(N, 0);
1807   N = newSDNode<VTSDNode>(VT);
1808   InsertNode(N);
1809   return SDValue(N, 0);
1810 }
1811 
1812 SDValue SelectionDAG::getExternalSymbol(const char *Sym, EVT VT) {
1813   SDNode *&N = ExternalSymbols[Sym];
1814   if (N) return SDValue(N, 0);
1815   N = newSDNode<ExternalSymbolSDNode>(false, Sym, 0, VT);
1816   InsertNode(N);
1817   return SDValue(N, 0);
1818 }
1819 
1820 SDValue SelectionDAG::getMCSymbol(MCSymbol *Sym, EVT VT) {
1821   SDNode *&N = MCSymbols[Sym];
1822   if (N)
1823     return SDValue(N, 0);
1824   N = newSDNode<MCSymbolSDNode>(Sym, VT);
1825   InsertNode(N);
1826   return SDValue(N, 0);
1827 }
1828 
1829 SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, EVT VT,
1830                                               unsigned TargetFlags) {
1831   SDNode *&N =
1832       TargetExternalSymbols[std::pair<std::string, unsigned>(Sym, TargetFlags)];
1833   if (N) return SDValue(N, 0);
1834   N = newSDNode<ExternalSymbolSDNode>(true, Sym, TargetFlags, VT);
1835   InsertNode(N);
1836   return SDValue(N, 0);
1837 }
1838 
1839 SDValue SelectionDAG::getCondCode(ISD::CondCode Cond) {
1840   if ((unsigned)Cond >= CondCodeNodes.size())
1841     CondCodeNodes.resize(Cond+1);
1842 
1843   if (!CondCodeNodes[Cond]) {
1844     auto *N = newSDNode<CondCodeSDNode>(Cond);
1845     CondCodeNodes[Cond] = N;
1846     InsertNode(N);
1847   }
1848 
1849   return SDValue(CondCodeNodes[Cond], 0);
1850 }
1851 
1852 SDValue SelectionDAG::getStepVector(const SDLoc &DL, EVT ResVT) {
1853   APInt One(ResVT.getScalarSizeInBits(), 1);
1854   return getStepVector(DL, ResVT, One);
1855 }
1856 
1857 SDValue SelectionDAG::getStepVector(const SDLoc &DL, EVT ResVT, APInt StepVal) {
1858   assert(ResVT.getScalarSizeInBits() == StepVal.getBitWidth());
1859   if (ResVT.isScalableVector())
1860     return getNode(
1861         ISD::STEP_VECTOR, DL, ResVT,
1862         getTargetConstant(StepVal, DL, ResVT.getVectorElementType()));
1863 
1864   SmallVector<SDValue, 16> OpsStepConstants;
1865   for (uint64_t i = 0; i < ResVT.getVectorNumElements(); i++)
1866     OpsStepConstants.push_back(
1867         getConstant(StepVal * i, DL, ResVT.getVectorElementType()));
1868   return getBuildVector(ResVT, DL, OpsStepConstants);
1869 }
1870 
1871 /// Swaps the values of N1 and N2. Swaps all indices in the shuffle mask M that
1872 /// point at N1 to point at N2 and indices that point at N2 to point at N1.
1873 static void commuteShuffle(SDValue &N1, SDValue &N2, MutableArrayRef<int> M) {
1874   std::swap(N1, N2);
1875   ShuffleVectorSDNode::commuteMask(M);
1876 }
1877 
1878 SDValue SelectionDAG::getVectorShuffle(EVT VT, const SDLoc &dl, SDValue N1,
1879                                        SDValue N2, ArrayRef<int> Mask) {
1880   assert(VT.getVectorNumElements() == Mask.size() &&
1881          "Must have the same number of vector elements as mask elements!");
1882   assert(VT == N1.getValueType() && VT == N2.getValueType() &&
1883          "Invalid VECTOR_SHUFFLE");
1884 
1885   // Canonicalize shuffle undef, undef -> undef
1886   if (N1.isUndef() && N2.isUndef())
1887     return getUNDEF(VT);
1888 
1889   // Validate that all indices in Mask are within the range of the elements
1890   // input to the shuffle.
1891   int NElts = Mask.size();
1892   assert(llvm::all_of(Mask,
1893                       [&](int M) { return M < (NElts * 2) && M >= -1; }) &&
1894          "Index out of range");
1895 
1896   // Copy the mask so we can do any needed cleanup.
1897   SmallVector<int, 8> MaskVec(Mask.begin(), Mask.end());
1898 
1899   // Canonicalize shuffle v, v -> v, undef
1900   if (N1 == N2) {
1901     N2 = getUNDEF(VT);
1902     for (int i = 0; i != NElts; ++i)
1903       if (MaskVec[i] >= NElts) MaskVec[i] -= NElts;
1904   }
1905 
1906   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
1907   if (N1.isUndef())
1908     commuteShuffle(N1, N2, MaskVec);
1909 
1910   if (TLI->hasVectorBlend()) {
1911     // If shuffling a splat, try to blend the splat instead. We do this here so
1912     // that even when this arises during lowering we don't have to re-handle it.
1913     auto BlendSplat = [&](BuildVectorSDNode *BV, int Offset) {
1914       BitVector UndefElements;
1915       SDValue Splat = BV->getSplatValue(&UndefElements);
1916       if (!Splat)
1917         return;
1918 
1919       for (int i = 0; i < NElts; ++i) {
1920         if (MaskVec[i] < Offset || MaskVec[i] >= (Offset + NElts))
1921           continue;
1922 
1923         // If this input comes from undef, mark it as such.
1924         if (UndefElements[MaskVec[i] - Offset]) {
1925           MaskVec[i] = -1;
1926           continue;
1927         }
1928 
1929         // If we can blend a non-undef lane, use that instead.
1930         if (!UndefElements[i])
1931           MaskVec[i] = i + Offset;
1932       }
1933     };
1934     if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
1935       BlendSplat(N1BV, 0);
1936     if (auto *N2BV = dyn_cast<BuildVectorSDNode>(N2))
1937       BlendSplat(N2BV, NElts);
1938   }
1939 
1940   // Canonicalize all index into lhs, -> shuffle lhs, undef
1941   // Canonicalize all index into rhs, -> shuffle rhs, undef
1942   bool AllLHS = true, AllRHS = true;
1943   bool N2Undef = N2.isUndef();
1944   for (int i = 0; i != NElts; ++i) {
1945     if (MaskVec[i] >= NElts) {
1946       if (N2Undef)
1947         MaskVec[i] = -1;
1948       else
1949         AllLHS = false;
1950     } else if (MaskVec[i] >= 0) {
1951       AllRHS = false;
1952     }
1953   }
1954   if (AllLHS && AllRHS)
1955     return getUNDEF(VT);
1956   if (AllLHS && !N2Undef)
1957     N2 = getUNDEF(VT);
1958   if (AllRHS) {
1959     N1 = getUNDEF(VT);
1960     commuteShuffle(N1, N2, MaskVec);
1961   }
1962   // Reset our undef status after accounting for the mask.
1963   N2Undef = N2.isUndef();
1964   // Re-check whether both sides ended up undef.
1965   if (N1.isUndef() && N2Undef)
1966     return getUNDEF(VT);
1967 
1968   // If Identity shuffle return that node.
1969   bool Identity = true, AllSame = true;
1970   for (int i = 0; i != NElts; ++i) {
1971     if (MaskVec[i] >= 0 && MaskVec[i] != i) Identity = false;
1972     if (MaskVec[i] != MaskVec[0]) AllSame = false;
1973   }
1974   if (Identity && NElts)
1975     return N1;
1976 
1977   // Shuffling a constant splat doesn't change the result.
1978   if (N2Undef) {
1979     SDValue V = N1;
1980 
1981     // Look through any bitcasts. We check that these don't change the number
1982     // (and size) of elements and just changes their types.
1983     while (V.getOpcode() == ISD::BITCAST)
1984       V = V->getOperand(0);
1985 
1986     // A splat should always show up as a build vector node.
1987     if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) {
1988       BitVector UndefElements;
1989       SDValue Splat = BV->getSplatValue(&UndefElements);
1990       // If this is a splat of an undef, shuffling it is also undef.
1991       if (Splat && Splat.isUndef())
1992         return getUNDEF(VT);
1993 
1994       bool SameNumElts =
1995           V.getValueType().getVectorNumElements() == VT.getVectorNumElements();
1996 
1997       // We only have a splat which can skip shuffles if there is a splatted
1998       // value and no undef lanes rearranged by the shuffle.
1999       if (Splat && UndefElements.none()) {
2000         // Splat of <x, x, ..., x>, return <x, x, ..., x>, provided that the
2001         // number of elements match or the value splatted is a zero constant.
2002         if (SameNumElts)
2003           return N1;
2004         if (auto *C = dyn_cast<ConstantSDNode>(Splat))
2005           if (C->isZero())
2006             return N1;
2007       }
2008 
2009       // If the shuffle itself creates a splat, build the vector directly.
2010       if (AllSame && SameNumElts) {
2011         EVT BuildVT = BV->getValueType(0);
2012         const SDValue &Splatted = BV->getOperand(MaskVec[0]);
2013         SDValue NewBV = getSplatBuildVector(BuildVT, dl, Splatted);
2014 
2015         // We may have jumped through bitcasts, so the type of the
2016         // BUILD_VECTOR may not match the type of the shuffle.
2017         if (BuildVT != VT)
2018           NewBV = getNode(ISD::BITCAST, dl, VT, NewBV);
2019         return NewBV;
2020       }
2021     }
2022   }
2023 
2024   FoldingSetNodeID ID;
2025   SDValue Ops[2] = { N1, N2 };
2026   AddNodeIDNode(ID, ISD::VECTOR_SHUFFLE, getVTList(VT), Ops);
2027   for (int i = 0; i != NElts; ++i)
2028     ID.AddInteger(MaskVec[i]);
2029 
2030   void* IP = nullptr;
2031   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
2032     return SDValue(E, 0);
2033 
2034   // Allocate the mask array for the node out of the BumpPtrAllocator, since
2035   // SDNode doesn't have access to it.  This memory will be "leaked" when
2036   // the node is deallocated, but recovered when the NodeAllocator is released.
2037   int *MaskAlloc = OperandAllocator.Allocate<int>(NElts);
2038   llvm::copy(MaskVec, MaskAlloc);
2039 
2040   auto *N = newSDNode<ShuffleVectorSDNode>(VT, dl.getIROrder(),
2041                                            dl.getDebugLoc(), MaskAlloc);
2042   createOperands(N, Ops);
2043 
2044   CSEMap.InsertNode(N, IP);
2045   InsertNode(N);
2046   SDValue V = SDValue(N, 0);
2047   NewSDValueDbgMsg(V, "Creating new node: ", this);
2048   return V;
2049 }
2050 
2051 SDValue SelectionDAG::getCommutedVectorShuffle(const ShuffleVectorSDNode &SV) {
2052   EVT VT = SV.getValueType(0);
2053   SmallVector<int, 8> MaskVec(SV.getMask().begin(), SV.getMask().end());
2054   ShuffleVectorSDNode::commuteMask(MaskVec);
2055 
2056   SDValue Op0 = SV.getOperand(0);
2057   SDValue Op1 = SV.getOperand(1);
2058   return getVectorShuffle(VT, SDLoc(&SV), Op1, Op0, MaskVec);
2059 }
2060 
2061 SDValue SelectionDAG::getRegister(unsigned RegNo, EVT VT) {
2062   FoldingSetNodeID ID;
2063   AddNodeIDNode(ID, ISD::Register, getVTList(VT), None);
2064   ID.AddInteger(RegNo);
2065   void *IP = nullptr;
2066   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2067     return SDValue(E, 0);
2068 
2069   auto *N = newSDNode<RegisterSDNode>(RegNo, VT);
2070   N->SDNodeBits.IsDivergent = TLI->isSDNodeSourceOfDivergence(N, FLI, DA);
2071   CSEMap.InsertNode(N, IP);
2072   InsertNode(N);
2073   return SDValue(N, 0);
2074 }
2075 
2076 SDValue SelectionDAG::getRegisterMask(const uint32_t *RegMask) {
2077   FoldingSetNodeID ID;
2078   AddNodeIDNode(ID, ISD::RegisterMask, getVTList(MVT::Untyped), None);
2079   ID.AddPointer(RegMask);
2080   void *IP = nullptr;
2081   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2082     return SDValue(E, 0);
2083 
2084   auto *N = newSDNode<RegisterMaskSDNode>(RegMask);
2085   CSEMap.InsertNode(N, IP);
2086   InsertNode(N);
2087   return SDValue(N, 0);
2088 }
2089 
2090 SDValue SelectionDAG::getEHLabel(const SDLoc &dl, SDValue Root,
2091                                  MCSymbol *Label) {
2092   return getLabelNode(ISD::EH_LABEL, dl, Root, Label);
2093 }
2094 
2095 SDValue SelectionDAG::getLabelNode(unsigned Opcode, const SDLoc &dl,
2096                                    SDValue Root, MCSymbol *Label) {
2097   FoldingSetNodeID ID;
2098   SDValue Ops[] = { Root };
2099   AddNodeIDNode(ID, Opcode, getVTList(MVT::Other), Ops);
2100   ID.AddPointer(Label);
2101   void *IP = nullptr;
2102   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2103     return SDValue(E, 0);
2104 
2105   auto *N =
2106       newSDNode<LabelSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), Label);
2107   createOperands(N, Ops);
2108 
2109   CSEMap.InsertNode(N, IP);
2110   InsertNode(N);
2111   return SDValue(N, 0);
2112 }
2113 
2114 SDValue SelectionDAG::getBlockAddress(const BlockAddress *BA, EVT VT,
2115                                       int64_t Offset, bool isTarget,
2116                                       unsigned TargetFlags) {
2117   unsigned Opc = isTarget ? ISD::TargetBlockAddress : ISD::BlockAddress;
2118 
2119   FoldingSetNodeID ID;
2120   AddNodeIDNode(ID, Opc, getVTList(VT), None);
2121   ID.AddPointer(BA);
2122   ID.AddInteger(Offset);
2123   ID.AddInteger(TargetFlags);
2124   void *IP = nullptr;
2125   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2126     return SDValue(E, 0);
2127 
2128   auto *N = newSDNode<BlockAddressSDNode>(Opc, VT, BA, Offset, TargetFlags);
2129   CSEMap.InsertNode(N, IP);
2130   InsertNode(N);
2131   return SDValue(N, 0);
2132 }
2133 
2134 SDValue SelectionDAG::getSrcValue(const Value *V) {
2135   FoldingSetNodeID ID;
2136   AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), None);
2137   ID.AddPointer(V);
2138 
2139   void *IP = nullptr;
2140   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2141     return SDValue(E, 0);
2142 
2143   auto *N = newSDNode<SrcValueSDNode>(V);
2144   CSEMap.InsertNode(N, IP);
2145   InsertNode(N);
2146   return SDValue(N, 0);
2147 }
2148 
2149 SDValue SelectionDAG::getMDNode(const MDNode *MD) {
2150   FoldingSetNodeID ID;
2151   AddNodeIDNode(ID, ISD::MDNODE_SDNODE, getVTList(MVT::Other), None);
2152   ID.AddPointer(MD);
2153 
2154   void *IP = nullptr;
2155   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2156     return SDValue(E, 0);
2157 
2158   auto *N = newSDNode<MDNodeSDNode>(MD);
2159   CSEMap.InsertNode(N, IP);
2160   InsertNode(N);
2161   return SDValue(N, 0);
2162 }
2163 
2164 SDValue SelectionDAG::getBitcast(EVT VT, SDValue V) {
2165   if (VT == V.getValueType())
2166     return V;
2167 
2168   return getNode(ISD::BITCAST, SDLoc(V), VT, V);
2169 }
2170 
2171 SDValue SelectionDAG::getAddrSpaceCast(const SDLoc &dl, EVT VT, SDValue Ptr,
2172                                        unsigned SrcAS, unsigned DestAS) {
2173   SDValue Ops[] = {Ptr};
2174   FoldingSetNodeID ID;
2175   AddNodeIDNode(ID, ISD::ADDRSPACECAST, getVTList(VT), Ops);
2176   ID.AddInteger(SrcAS);
2177   ID.AddInteger(DestAS);
2178 
2179   void *IP = nullptr;
2180   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
2181     return SDValue(E, 0);
2182 
2183   auto *N = newSDNode<AddrSpaceCastSDNode>(dl.getIROrder(), dl.getDebugLoc(),
2184                                            VT, SrcAS, DestAS);
2185   createOperands(N, Ops);
2186 
2187   CSEMap.InsertNode(N, IP);
2188   InsertNode(N);
2189   return SDValue(N, 0);
2190 }
2191 
2192 SDValue SelectionDAG::getFreeze(SDValue V) {
2193   return getNode(ISD::FREEZE, SDLoc(V), V.getValueType(), V);
2194 }
2195 
2196 /// getShiftAmountOperand - Return the specified value casted to
2197 /// the target's desired shift amount type.
2198 SDValue SelectionDAG::getShiftAmountOperand(EVT LHSTy, SDValue Op) {
2199   EVT OpTy = Op.getValueType();
2200   EVT ShTy = TLI->getShiftAmountTy(LHSTy, getDataLayout());
2201   if (OpTy == ShTy || OpTy.isVector()) return Op;
2202 
2203   return getZExtOrTrunc(Op, SDLoc(Op), ShTy);
2204 }
2205 
2206 SDValue SelectionDAG::expandVAArg(SDNode *Node) {
2207   SDLoc dl(Node);
2208   const TargetLowering &TLI = getTargetLoweringInfo();
2209   const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2210   EVT VT = Node->getValueType(0);
2211   SDValue Tmp1 = Node->getOperand(0);
2212   SDValue Tmp2 = Node->getOperand(1);
2213   const MaybeAlign MA(Node->getConstantOperandVal(3));
2214 
2215   SDValue VAListLoad = getLoad(TLI.getPointerTy(getDataLayout()), dl, Tmp1,
2216                                Tmp2, MachinePointerInfo(V));
2217   SDValue VAList = VAListLoad;
2218 
2219   if (MA && *MA > TLI.getMinStackArgumentAlignment()) {
2220     VAList = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
2221                      getConstant(MA->value() - 1, dl, VAList.getValueType()));
2222 
2223     VAList =
2224         getNode(ISD::AND, dl, VAList.getValueType(), VAList,
2225                 getConstant(-(int64_t)MA->value(), dl, VAList.getValueType()));
2226   }
2227 
2228   // Increment the pointer, VAList, to the next vaarg
2229   Tmp1 = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
2230                  getConstant(getDataLayout().getTypeAllocSize(
2231                                                VT.getTypeForEVT(*getContext())),
2232                              dl, VAList.getValueType()));
2233   // Store the incremented VAList to the legalized pointer
2234   Tmp1 =
2235       getStore(VAListLoad.getValue(1), dl, Tmp1, Tmp2, MachinePointerInfo(V));
2236   // Load the actual argument out of the pointer VAList
2237   return getLoad(VT, dl, Tmp1, VAList, MachinePointerInfo());
2238 }
2239 
2240 SDValue SelectionDAG::expandVACopy(SDNode *Node) {
2241   SDLoc dl(Node);
2242   const TargetLowering &TLI = getTargetLoweringInfo();
2243   // This defaults to loading a pointer from the input and storing it to the
2244   // output, returning the chain.
2245   const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue();
2246   const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue();
2247   SDValue Tmp1 =
2248       getLoad(TLI.getPointerTy(getDataLayout()), dl, Node->getOperand(0),
2249               Node->getOperand(2), MachinePointerInfo(VS));
2250   return getStore(Tmp1.getValue(1), dl, Tmp1, Node->getOperand(1),
2251                   MachinePointerInfo(VD));
2252 }
2253 
2254 Align SelectionDAG::getReducedAlign(EVT VT, bool UseABI) {
2255   const DataLayout &DL = getDataLayout();
2256   Type *Ty = VT.getTypeForEVT(*getContext());
2257   Align RedAlign = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty);
2258 
2259   if (TLI->isTypeLegal(VT) || !VT.isVector())
2260     return RedAlign;
2261 
2262   const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
2263   const Align StackAlign = TFI->getStackAlign();
2264 
2265   // See if we can choose a smaller ABI alignment in cases where it's an
2266   // illegal vector type that will get broken down.
2267   if (RedAlign > StackAlign) {
2268     EVT IntermediateVT;
2269     MVT RegisterVT;
2270     unsigned NumIntermediates;
2271     TLI->getVectorTypeBreakdown(*getContext(), VT, IntermediateVT,
2272                                 NumIntermediates, RegisterVT);
2273     Ty = IntermediateVT.getTypeForEVT(*getContext());
2274     Align RedAlign2 = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty);
2275     if (RedAlign2 < RedAlign)
2276       RedAlign = RedAlign2;
2277   }
2278 
2279   return RedAlign;
2280 }
2281 
2282 SDValue SelectionDAG::CreateStackTemporary(TypeSize Bytes, Align Alignment) {
2283   MachineFrameInfo &MFI = MF->getFrameInfo();
2284   const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
2285   int StackID = 0;
2286   if (Bytes.isScalable())
2287     StackID = TFI->getStackIDForScalableVectors();
2288   // The stack id gives an indication of whether the object is scalable or
2289   // not, so it's safe to pass in the minimum size here.
2290   int FrameIdx = MFI.CreateStackObject(Bytes.getKnownMinSize(), Alignment,
2291                                        false, nullptr, StackID);
2292   return getFrameIndex(FrameIdx, TLI->getFrameIndexTy(getDataLayout()));
2293 }
2294 
2295 SDValue SelectionDAG::CreateStackTemporary(EVT VT, unsigned minAlign) {
2296   Type *Ty = VT.getTypeForEVT(*getContext());
2297   Align StackAlign =
2298       std::max(getDataLayout().getPrefTypeAlign(Ty), Align(minAlign));
2299   return CreateStackTemporary(VT.getStoreSize(), StackAlign);
2300 }
2301 
2302 SDValue SelectionDAG::CreateStackTemporary(EVT VT1, EVT VT2) {
2303   TypeSize VT1Size = VT1.getStoreSize();
2304   TypeSize VT2Size = VT2.getStoreSize();
2305   assert(VT1Size.isScalable() == VT2Size.isScalable() &&
2306          "Don't know how to choose the maximum size when creating a stack "
2307          "temporary");
2308   TypeSize Bytes =
2309       VT1Size.getKnownMinSize() > VT2Size.getKnownMinSize() ? VT1Size : VT2Size;
2310 
2311   Type *Ty1 = VT1.getTypeForEVT(*getContext());
2312   Type *Ty2 = VT2.getTypeForEVT(*getContext());
2313   const DataLayout &DL = getDataLayout();
2314   Align Align = std::max(DL.getPrefTypeAlign(Ty1), DL.getPrefTypeAlign(Ty2));
2315   return CreateStackTemporary(Bytes, Align);
2316 }
2317 
2318 SDValue SelectionDAG::FoldSetCC(EVT VT, SDValue N1, SDValue N2,
2319                                 ISD::CondCode Cond, const SDLoc &dl) {
2320   EVT OpVT = N1.getValueType();
2321 
2322   // These setcc operations always fold.
2323   switch (Cond) {
2324   default: break;
2325   case ISD::SETFALSE:
2326   case ISD::SETFALSE2: return getBoolConstant(false, dl, VT, OpVT);
2327   case ISD::SETTRUE:
2328   case ISD::SETTRUE2: return getBoolConstant(true, dl, VT, OpVT);
2329 
2330   case ISD::SETOEQ:
2331   case ISD::SETOGT:
2332   case ISD::SETOGE:
2333   case ISD::SETOLT:
2334   case ISD::SETOLE:
2335   case ISD::SETONE:
2336   case ISD::SETO:
2337   case ISD::SETUO:
2338   case ISD::SETUEQ:
2339   case ISD::SETUNE:
2340     assert(!OpVT.isInteger() && "Illegal setcc for integer!");
2341     break;
2342   }
2343 
2344   if (OpVT.isInteger()) {
2345     // For EQ and NE, we can always pick a value for the undef to make the
2346     // predicate pass or fail, so we can return undef.
2347     // Matches behavior in llvm::ConstantFoldCompareInstruction.
2348     // icmp eq/ne X, undef -> undef.
2349     if ((N1.isUndef() || N2.isUndef()) &&
2350         (Cond == ISD::SETEQ || Cond == ISD::SETNE))
2351       return getUNDEF(VT);
2352 
2353     // If both operands are undef, we can return undef for int comparison.
2354     // icmp undef, undef -> undef.
2355     if (N1.isUndef() && N2.isUndef())
2356       return getUNDEF(VT);
2357 
2358     // icmp X, X -> true/false
2359     // icmp X, undef -> true/false because undef could be X.
2360     if (N1 == N2)
2361       return getBoolConstant(ISD::isTrueWhenEqual(Cond), dl, VT, OpVT);
2362   }
2363 
2364   if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2)) {
2365     const APInt &C2 = N2C->getAPIntValue();
2366     if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1)) {
2367       const APInt &C1 = N1C->getAPIntValue();
2368 
2369       return getBoolConstant(ICmpInst::compare(C1, C2, getICmpCondCode(Cond)),
2370                              dl, VT, OpVT);
2371     }
2372   }
2373 
2374   auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
2375   auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
2376 
2377   if (N1CFP && N2CFP) {
2378     APFloat::cmpResult R = N1CFP->getValueAPF().compare(N2CFP->getValueAPF());
2379     switch (Cond) {
2380     default: break;
2381     case ISD::SETEQ:  if (R==APFloat::cmpUnordered)
2382                         return getUNDEF(VT);
2383                       LLVM_FALLTHROUGH;
2384     case ISD::SETOEQ: return getBoolConstant(R==APFloat::cmpEqual, dl, VT,
2385                                              OpVT);
2386     case ISD::SETNE:  if (R==APFloat::cmpUnordered)
2387                         return getUNDEF(VT);
2388                       LLVM_FALLTHROUGH;
2389     case ISD::SETONE: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2390                                              R==APFloat::cmpLessThan, dl, VT,
2391                                              OpVT);
2392     case ISD::SETLT:  if (R==APFloat::cmpUnordered)
2393                         return getUNDEF(VT);
2394                       LLVM_FALLTHROUGH;
2395     case ISD::SETOLT: return getBoolConstant(R==APFloat::cmpLessThan, dl, VT,
2396                                              OpVT);
2397     case ISD::SETGT:  if (R==APFloat::cmpUnordered)
2398                         return getUNDEF(VT);
2399                       LLVM_FALLTHROUGH;
2400     case ISD::SETOGT: return getBoolConstant(R==APFloat::cmpGreaterThan, dl,
2401                                              VT, OpVT);
2402     case ISD::SETLE:  if (R==APFloat::cmpUnordered)
2403                         return getUNDEF(VT);
2404                       LLVM_FALLTHROUGH;
2405     case ISD::SETOLE: return getBoolConstant(R==APFloat::cmpLessThan ||
2406                                              R==APFloat::cmpEqual, dl, VT,
2407                                              OpVT);
2408     case ISD::SETGE:  if (R==APFloat::cmpUnordered)
2409                         return getUNDEF(VT);
2410                       LLVM_FALLTHROUGH;
2411     case ISD::SETOGE: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2412                                          R==APFloat::cmpEqual, dl, VT, OpVT);
2413     case ISD::SETO:   return getBoolConstant(R!=APFloat::cmpUnordered, dl, VT,
2414                                              OpVT);
2415     case ISD::SETUO:  return getBoolConstant(R==APFloat::cmpUnordered, dl, VT,
2416                                              OpVT);
2417     case ISD::SETUEQ: return getBoolConstant(R==APFloat::cmpUnordered ||
2418                                              R==APFloat::cmpEqual, dl, VT,
2419                                              OpVT);
2420     case ISD::SETUNE: return getBoolConstant(R!=APFloat::cmpEqual, dl, VT,
2421                                              OpVT);
2422     case ISD::SETULT: return getBoolConstant(R==APFloat::cmpUnordered ||
2423                                              R==APFloat::cmpLessThan, dl, VT,
2424                                              OpVT);
2425     case ISD::SETUGT: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2426                                              R==APFloat::cmpUnordered, dl, VT,
2427                                              OpVT);
2428     case ISD::SETULE: return getBoolConstant(R!=APFloat::cmpGreaterThan, dl,
2429                                              VT, OpVT);
2430     case ISD::SETUGE: return getBoolConstant(R!=APFloat::cmpLessThan, dl, VT,
2431                                              OpVT);
2432     }
2433   } else if (N1CFP && OpVT.isSimple() && !N2.isUndef()) {
2434     // Ensure that the constant occurs on the RHS.
2435     ISD::CondCode SwappedCond = ISD::getSetCCSwappedOperands(Cond);
2436     if (!TLI->isCondCodeLegal(SwappedCond, OpVT.getSimpleVT()))
2437       return SDValue();
2438     return getSetCC(dl, VT, N2, N1, SwappedCond);
2439   } else if ((N2CFP && N2CFP->getValueAPF().isNaN()) ||
2440              (OpVT.isFloatingPoint() && (N1.isUndef() || N2.isUndef()))) {
2441     // If an operand is known to be a nan (or undef that could be a nan), we can
2442     // fold it.
2443     // Choosing NaN for the undef will always make unordered comparison succeed
2444     // and ordered comparison fails.
2445     // Matches behavior in llvm::ConstantFoldCompareInstruction.
2446     switch (ISD::getUnorderedFlavor(Cond)) {
2447     default:
2448       llvm_unreachable("Unknown flavor!");
2449     case 0: // Known false.
2450       return getBoolConstant(false, dl, VT, OpVT);
2451     case 1: // Known true.
2452       return getBoolConstant(true, dl, VT, OpVT);
2453     case 2: // Undefined.
2454       return getUNDEF(VT);
2455     }
2456   }
2457 
2458   // Could not fold it.
2459   return SDValue();
2460 }
2461 
2462 /// See if the specified operand can be simplified with the knowledge that only
2463 /// the bits specified by DemandedBits are used.
2464 /// TODO: really we should be making this into the DAG equivalent of
2465 /// SimplifyMultipleUseDemandedBits and not generate any new nodes.
2466 SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &DemandedBits) {
2467   EVT VT = V.getValueType();
2468 
2469   if (VT.isScalableVector())
2470     return SDValue();
2471 
2472   APInt DemandedElts = VT.isVector()
2473                            ? APInt::getAllOnes(VT.getVectorNumElements())
2474                            : APInt(1, 1);
2475   return GetDemandedBits(V, DemandedBits, DemandedElts);
2476 }
2477 
2478 /// See if the specified operand can be simplified with the knowledge that only
2479 /// the bits specified by DemandedBits are used in the elements specified by
2480 /// DemandedElts.
2481 /// TODO: really we should be making this into the DAG equivalent of
2482 /// SimplifyMultipleUseDemandedBits and not generate any new nodes.
2483 SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &DemandedBits,
2484                                       const APInt &DemandedElts) {
2485   switch (V.getOpcode()) {
2486   default:
2487     return TLI->SimplifyMultipleUseDemandedBits(V, DemandedBits, DemandedElts,
2488                                                 *this);
2489   case ISD::Constant: {
2490     const APInt &CVal = cast<ConstantSDNode>(V)->getAPIntValue();
2491     APInt NewVal = CVal & DemandedBits;
2492     if (NewVal != CVal)
2493       return getConstant(NewVal, SDLoc(V), V.getValueType());
2494     break;
2495   }
2496   case ISD::SRL:
2497     // Only look at single-use SRLs.
2498     if (!V.getNode()->hasOneUse())
2499       break;
2500     if (auto *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
2501       // See if we can recursively simplify the LHS.
2502       unsigned Amt = RHSC->getZExtValue();
2503 
2504       // Watch out for shift count overflow though.
2505       if (Amt >= DemandedBits.getBitWidth())
2506         break;
2507       APInt SrcDemandedBits = DemandedBits << Amt;
2508       if (SDValue SimplifyLHS =
2509               GetDemandedBits(V.getOperand(0), SrcDemandedBits))
2510         return getNode(ISD::SRL, SDLoc(V), V.getValueType(), SimplifyLHS,
2511                        V.getOperand(1));
2512     }
2513     break;
2514   }
2515   return SDValue();
2516 }
2517 
2518 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero.  We
2519 /// use this predicate to simplify operations downstream.
2520 bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const {
2521   unsigned BitWidth = Op.getScalarValueSizeInBits();
2522   return MaskedValueIsZero(Op, APInt::getSignMask(BitWidth), Depth);
2523 }
2524 
2525 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero.  We use
2526 /// this predicate to simplify operations downstream.  Mask is known to be zero
2527 /// for bits that V cannot have.
2528 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask,
2529                                      unsigned Depth) const {
2530   return Mask.isSubsetOf(computeKnownBits(V, Depth).Zero);
2531 }
2532 
2533 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero in
2534 /// DemandedElts.  We use this predicate to simplify operations downstream.
2535 /// Mask is known to be zero for bits that V cannot have.
2536 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask,
2537                                      const APInt &DemandedElts,
2538                                      unsigned Depth) const {
2539   return Mask.isSubsetOf(computeKnownBits(V, DemandedElts, Depth).Zero);
2540 }
2541 
2542 /// MaskedValueIsAllOnes - Return true if '(Op & Mask) == Mask'.
2543 bool SelectionDAG::MaskedValueIsAllOnes(SDValue V, const APInt &Mask,
2544                                         unsigned Depth) const {
2545   return Mask.isSubsetOf(computeKnownBits(V, Depth).One);
2546 }
2547 
2548 /// isSplatValue - Return true if the vector V has the same value
2549 /// across all DemandedElts. For scalable vectors it does not make
2550 /// sense to specify which elements are demanded or undefined, therefore
2551 /// they are simply ignored.
2552 bool SelectionDAG::isSplatValue(SDValue V, const APInt &DemandedElts,
2553                                 APInt &UndefElts, unsigned Depth) const {
2554   unsigned Opcode = V.getOpcode();
2555   EVT VT = V.getValueType();
2556   assert(VT.isVector() && "Vector type expected");
2557 
2558   if (!VT.isScalableVector() && !DemandedElts)
2559     return false; // No demanded elts, better to assume we don't know anything.
2560 
2561   if (Depth >= MaxRecursionDepth)
2562     return false; // Limit search depth.
2563 
2564   // Deal with some common cases here that work for both fixed and scalable
2565   // vector types.
2566   switch (Opcode) {
2567   case ISD::SPLAT_VECTOR:
2568     UndefElts = V.getOperand(0).isUndef()
2569                     ? APInt::getAllOnes(DemandedElts.getBitWidth())
2570                     : APInt(DemandedElts.getBitWidth(), 0);
2571     return true;
2572   case ISD::ADD:
2573   case ISD::SUB:
2574   case ISD::AND:
2575   case ISD::XOR:
2576   case ISD::OR: {
2577     APInt UndefLHS, UndefRHS;
2578     SDValue LHS = V.getOperand(0);
2579     SDValue RHS = V.getOperand(1);
2580     if (isSplatValue(LHS, DemandedElts, UndefLHS, Depth + 1) &&
2581         isSplatValue(RHS, DemandedElts, UndefRHS, Depth + 1)) {
2582       UndefElts = UndefLHS | UndefRHS;
2583       return true;
2584     }
2585     return false;
2586   }
2587   case ISD::ABS:
2588   case ISD::TRUNCATE:
2589   case ISD::SIGN_EXTEND:
2590   case ISD::ZERO_EXTEND:
2591     return isSplatValue(V.getOperand(0), DemandedElts, UndefElts, Depth + 1);
2592   default:
2593     if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
2594         Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID)
2595       return TLI->isSplatValueForTargetNode(V, DemandedElts, UndefElts, Depth);
2596     break;
2597 }
2598 
2599   // We don't support other cases than those above for scalable vectors at
2600   // the moment.
2601   if (VT.isScalableVector())
2602     return false;
2603 
2604   unsigned NumElts = VT.getVectorNumElements();
2605   assert(NumElts == DemandedElts.getBitWidth() && "Vector size mismatch");
2606   UndefElts = APInt::getZero(NumElts);
2607 
2608   switch (Opcode) {
2609   case ISD::BUILD_VECTOR: {
2610     SDValue Scl;
2611     for (unsigned i = 0; i != NumElts; ++i) {
2612       SDValue Op = V.getOperand(i);
2613       if (Op.isUndef()) {
2614         UndefElts.setBit(i);
2615         continue;
2616       }
2617       if (!DemandedElts[i])
2618         continue;
2619       if (Scl && Scl != Op)
2620         return false;
2621       Scl = Op;
2622     }
2623     return true;
2624   }
2625   case ISD::VECTOR_SHUFFLE: {
2626     // Check if this is a shuffle node doing a splat or a shuffle of a splat.
2627     APInt DemandedLHS = APInt::getNullValue(NumElts);
2628     APInt DemandedRHS = APInt::getNullValue(NumElts);
2629     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(V)->getMask();
2630     for (int i = 0; i != (int)NumElts; ++i) {
2631       int M = Mask[i];
2632       if (M < 0) {
2633         UndefElts.setBit(i);
2634         continue;
2635       }
2636       if (!DemandedElts[i])
2637         continue;
2638       if (M < (int)NumElts)
2639         DemandedLHS.setBit(M);
2640       else
2641         DemandedRHS.setBit(M - NumElts);
2642     }
2643 
2644     // If we aren't demanding either op, assume there's no splat.
2645     // If we are demanding both ops, assume there's no splat.
2646     if ((DemandedLHS.isZero() && DemandedRHS.isZero()) ||
2647         (!DemandedLHS.isZero() && !DemandedRHS.isZero()))
2648       return false;
2649 
2650     // See if the demanded elts of the source op is a splat or we only demand
2651     // one element, which should always be a splat.
2652     // TODO: Handle source ops splats with undefs.
2653     auto CheckSplatSrc = [&](SDValue Src, const APInt &SrcElts) {
2654       APInt SrcUndefs;
2655       return (SrcElts.countPopulation() == 1) ||
2656              (isSplatValue(Src, SrcElts, SrcUndefs, Depth + 1) &&
2657               (SrcElts & SrcUndefs).isZero());
2658     };
2659     if (!DemandedLHS.isZero())
2660       return CheckSplatSrc(V.getOperand(0), DemandedLHS);
2661     return CheckSplatSrc(V.getOperand(1), DemandedRHS);
2662   }
2663   case ISD::EXTRACT_SUBVECTOR: {
2664     // Offset the demanded elts by the subvector index.
2665     SDValue Src = V.getOperand(0);
2666     // We don't support scalable vectors at the moment.
2667     if (Src.getValueType().isScalableVector())
2668       return false;
2669     uint64_t Idx = V.getConstantOperandVal(1);
2670     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2671     APInt UndefSrcElts;
2672     APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
2673     if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) {
2674       UndefElts = UndefSrcElts.extractBits(NumElts, Idx);
2675       return true;
2676     }
2677     break;
2678   }
2679   case ISD::ANY_EXTEND_VECTOR_INREG:
2680   case ISD::SIGN_EXTEND_VECTOR_INREG:
2681   case ISD::ZERO_EXTEND_VECTOR_INREG: {
2682     // Widen the demanded elts by the src element count.
2683     SDValue Src = V.getOperand(0);
2684     // We don't support scalable vectors at the moment.
2685     if (Src.getValueType().isScalableVector())
2686       return false;
2687     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2688     APInt UndefSrcElts;
2689     APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts);
2690     if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) {
2691       UndefElts = UndefSrcElts.trunc(NumElts);
2692       return true;
2693     }
2694     break;
2695   }
2696   case ISD::BITCAST: {
2697     SDValue Src = V.getOperand(0);
2698     EVT SrcVT = Src.getValueType();
2699     unsigned SrcBitWidth = SrcVT.getScalarSizeInBits();
2700     unsigned BitWidth = VT.getScalarSizeInBits();
2701 
2702     // Ignore bitcasts from unsupported types.
2703     // TODO: Add fp support?
2704     if (!SrcVT.isVector() || !SrcVT.isInteger() || !VT.isInteger())
2705       break;
2706 
2707     // Bitcast 'small element' vector to 'large element' vector.
2708     if ((BitWidth % SrcBitWidth) == 0) {
2709       // See if each sub element is a splat.
2710       unsigned Scale = BitWidth / SrcBitWidth;
2711       unsigned NumSrcElts = SrcVT.getVectorNumElements();
2712       APInt ScaledDemandedElts =
2713           APIntOps::ScaleBitMask(DemandedElts, NumSrcElts);
2714       for (unsigned I = 0; I != Scale; ++I) {
2715         APInt SubUndefElts;
2716         APInt SubDemandedElt = APInt::getOneBitSet(Scale, I);
2717         APInt SubDemandedElts = APInt::getSplat(NumSrcElts, SubDemandedElt);
2718         SubDemandedElts &= ScaledDemandedElts;
2719         if (!isSplatValue(Src, SubDemandedElts, SubUndefElts, Depth + 1))
2720           return false;
2721         UndefElts |= APIntOps::ScaleBitMask(SubUndefElts, NumElts);
2722       }
2723       return true;
2724     }
2725     break;
2726   }
2727   }
2728 
2729   return false;
2730 }
2731 
2732 /// Helper wrapper to main isSplatValue function.
2733 bool SelectionDAG::isSplatValue(SDValue V, bool AllowUndefs) const {
2734   EVT VT = V.getValueType();
2735   assert(VT.isVector() && "Vector type expected");
2736 
2737   APInt UndefElts;
2738   APInt DemandedElts;
2739 
2740   // For now we don't support this with scalable vectors.
2741   if (!VT.isScalableVector())
2742     DemandedElts = APInt::getAllOnes(VT.getVectorNumElements());
2743   return isSplatValue(V, DemandedElts, UndefElts) &&
2744          (AllowUndefs || !UndefElts);
2745 }
2746 
2747 SDValue SelectionDAG::getSplatSourceVector(SDValue V, int &SplatIdx) {
2748   V = peekThroughExtractSubvectors(V);
2749 
2750   EVT VT = V.getValueType();
2751   unsigned Opcode = V.getOpcode();
2752   switch (Opcode) {
2753   default: {
2754     APInt UndefElts;
2755     APInt DemandedElts;
2756 
2757     if (!VT.isScalableVector())
2758       DemandedElts = APInt::getAllOnes(VT.getVectorNumElements());
2759 
2760     if (isSplatValue(V, DemandedElts, UndefElts)) {
2761       if (VT.isScalableVector()) {
2762         // DemandedElts and UndefElts are ignored for scalable vectors, since
2763         // the only supported cases are SPLAT_VECTOR nodes.
2764         SplatIdx = 0;
2765       } else {
2766         // Handle case where all demanded elements are UNDEF.
2767         if (DemandedElts.isSubsetOf(UndefElts)) {
2768           SplatIdx = 0;
2769           return getUNDEF(VT);
2770         }
2771         SplatIdx = (UndefElts & DemandedElts).countTrailingOnes();
2772       }
2773       return V;
2774     }
2775     break;
2776   }
2777   case ISD::SPLAT_VECTOR:
2778     SplatIdx = 0;
2779     return V;
2780   case ISD::VECTOR_SHUFFLE: {
2781     if (VT.isScalableVector())
2782       return SDValue();
2783 
2784     // Check if this is a shuffle node doing a splat.
2785     // TODO - remove this and rely purely on SelectionDAG::isSplatValue,
2786     // getTargetVShiftNode currently struggles without the splat source.
2787     auto *SVN = cast<ShuffleVectorSDNode>(V);
2788     if (!SVN->isSplat())
2789       break;
2790     int Idx = SVN->getSplatIndex();
2791     int NumElts = V.getValueType().getVectorNumElements();
2792     SplatIdx = Idx % NumElts;
2793     return V.getOperand(Idx / NumElts);
2794   }
2795   }
2796 
2797   return SDValue();
2798 }
2799 
2800 SDValue SelectionDAG::getSplatValue(SDValue V, bool LegalTypes) {
2801   int SplatIdx;
2802   if (SDValue SrcVector = getSplatSourceVector(V, SplatIdx)) {
2803     EVT SVT = SrcVector.getValueType().getScalarType();
2804     EVT LegalSVT = SVT;
2805     if (LegalTypes && !TLI->isTypeLegal(SVT)) {
2806       if (!SVT.isInteger())
2807         return SDValue();
2808       LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
2809       if (LegalSVT.bitsLT(SVT))
2810         return SDValue();
2811     }
2812     return getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(V), LegalSVT, SrcVector,
2813                    getVectorIdxConstant(SplatIdx, SDLoc(V)));
2814   }
2815   return SDValue();
2816 }
2817 
2818 const APInt *
2819 SelectionDAG::getValidShiftAmountConstant(SDValue V,
2820                                           const APInt &DemandedElts) const {
2821   assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
2822           V.getOpcode() == ISD::SRA) &&
2823          "Unknown shift node");
2824   unsigned BitWidth = V.getScalarValueSizeInBits();
2825   if (ConstantSDNode *SA = isConstOrConstSplat(V.getOperand(1), DemandedElts)) {
2826     // Shifting more than the bitwidth is not valid.
2827     const APInt &ShAmt = SA->getAPIntValue();
2828     if (ShAmt.ult(BitWidth))
2829       return &ShAmt;
2830   }
2831   return nullptr;
2832 }
2833 
2834 const APInt *SelectionDAG::getValidMinimumShiftAmountConstant(
2835     SDValue V, const APInt &DemandedElts) const {
2836   assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
2837           V.getOpcode() == ISD::SRA) &&
2838          "Unknown shift node");
2839   if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts))
2840     return ValidAmt;
2841   unsigned BitWidth = V.getScalarValueSizeInBits();
2842   auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1));
2843   if (!BV)
2844     return nullptr;
2845   const APInt *MinShAmt = nullptr;
2846   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
2847     if (!DemandedElts[i])
2848       continue;
2849     auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i));
2850     if (!SA)
2851       return nullptr;
2852     // Shifting more than the bitwidth is not valid.
2853     const APInt &ShAmt = SA->getAPIntValue();
2854     if (ShAmt.uge(BitWidth))
2855       return nullptr;
2856     if (MinShAmt && MinShAmt->ule(ShAmt))
2857       continue;
2858     MinShAmt = &ShAmt;
2859   }
2860   return MinShAmt;
2861 }
2862 
2863 const APInt *SelectionDAG::getValidMaximumShiftAmountConstant(
2864     SDValue V, const APInt &DemandedElts) const {
2865   assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
2866           V.getOpcode() == ISD::SRA) &&
2867          "Unknown shift node");
2868   if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts))
2869     return ValidAmt;
2870   unsigned BitWidth = V.getScalarValueSizeInBits();
2871   auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1));
2872   if (!BV)
2873     return nullptr;
2874   const APInt *MaxShAmt = nullptr;
2875   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
2876     if (!DemandedElts[i])
2877       continue;
2878     auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i));
2879     if (!SA)
2880       return nullptr;
2881     // Shifting more than the bitwidth is not valid.
2882     const APInt &ShAmt = SA->getAPIntValue();
2883     if (ShAmt.uge(BitWidth))
2884       return nullptr;
2885     if (MaxShAmt && MaxShAmt->uge(ShAmt))
2886       continue;
2887     MaxShAmt = &ShAmt;
2888   }
2889   return MaxShAmt;
2890 }
2891 
2892 /// Determine which bits of Op are known to be either zero or one and return
2893 /// them in Known. For vectors, the known bits are those that are shared by
2894 /// every vector element.
2895 KnownBits SelectionDAG::computeKnownBits(SDValue Op, unsigned Depth) const {
2896   EVT VT = Op.getValueType();
2897 
2898   // TOOD: Until we have a plan for how to represent demanded elements for
2899   // scalable vectors, we can just bail out for now.
2900   if (Op.getValueType().isScalableVector()) {
2901     unsigned BitWidth = Op.getScalarValueSizeInBits();
2902     return KnownBits(BitWidth);
2903   }
2904 
2905   APInt DemandedElts = VT.isVector()
2906                            ? APInt::getAllOnes(VT.getVectorNumElements())
2907                            : APInt(1, 1);
2908   return computeKnownBits(Op, DemandedElts, Depth);
2909 }
2910 
2911 /// Determine which bits of Op are known to be either zero or one and return
2912 /// them in Known. The DemandedElts argument allows us to only collect the known
2913 /// bits that are shared by the requested vector elements.
2914 KnownBits SelectionDAG::computeKnownBits(SDValue Op, const APInt &DemandedElts,
2915                                          unsigned Depth) const {
2916   unsigned BitWidth = Op.getScalarValueSizeInBits();
2917 
2918   KnownBits Known(BitWidth);   // Don't know anything.
2919 
2920   // TOOD: Until we have a plan for how to represent demanded elements for
2921   // scalable vectors, we can just bail out for now.
2922   if (Op.getValueType().isScalableVector())
2923     return Known;
2924 
2925   if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
2926     // We know all of the bits for a constant!
2927     return KnownBits::makeConstant(C->getAPIntValue());
2928   }
2929   if (auto *C = dyn_cast<ConstantFPSDNode>(Op)) {
2930     // We know all of the bits for a constant fp!
2931     return KnownBits::makeConstant(C->getValueAPF().bitcastToAPInt());
2932   }
2933 
2934   if (Depth >= MaxRecursionDepth)
2935     return Known;  // Limit search depth.
2936 
2937   KnownBits Known2;
2938   unsigned NumElts = DemandedElts.getBitWidth();
2939   assert((!Op.getValueType().isVector() ||
2940           NumElts == Op.getValueType().getVectorNumElements()) &&
2941          "Unexpected vector size");
2942 
2943   if (!DemandedElts)
2944     return Known;  // No demanded elts, better to assume we don't know anything.
2945 
2946   unsigned Opcode = Op.getOpcode();
2947   switch (Opcode) {
2948   case ISD::BUILD_VECTOR:
2949     // Collect the known bits that are shared by every demanded vector element.
2950     Known.Zero.setAllBits(); Known.One.setAllBits();
2951     for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
2952       if (!DemandedElts[i])
2953         continue;
2954 
2955       SDValue SrcOp = Op.getOperand(i);
2956       Known2 = computeKnownBits(SrcOp, Depth + 1);
2957 
2958       // BUILD_VECTOR can implicitly truncate sources, we must handle this.
2959       if (SrcOp.getValueSizeInBits() != BitWidth) {
2960         assert(SrcOp.getValueSizeInBits() > BitWidth &&
2961                "Expected BUILD_VECTOR implicit truncation");
2962         Known2 = Known2.trunc(BitWidth);
2963       }
2964 
2965       // Known bits are the values that are shared by every demanded element.
2966       Known = KnownBits::commonBits(Known, Known2);
2967 
2968       // If we don't know any bits, early out.
2969       if (Known.isUnknown())
2970         break;
2971     }
2972     break;
2973   case ISD::VECTOR_SHUFFLE: {
2974     // Collect the known bits that are shared by every vector element referenced
2975     // by the shuffle.
2976     APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
2977     Known.Zero.setAllBits(); Known.One.setAllBits();
2978     const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
2979     assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
2980     for (unsigned i = 0; i != NumElts; ++i) {
2981       if (!DemandedElts[i])
2982         continue;
2983 
2984       int M = SVN->getMaskElt(i);
2985       if (M < 0) {
2986         // For UNDEF elements, we don't know anything about the common state of
2987         // the shuffle result.
2988         Known.resetAll();
2989         DemandedLHS.clearAllBits();
2990         DemandedRHS.clearAllBits();
2991         break;
2992       }
2993 
2994       if ((unsigned)M < NumElts)
2995         DemandedLHS.setBit((unsigned)M % NumElts);
2996       else
2997         DemandedRHS.setBit((unsigned)M % NumElts);
2998     }
2999     // Known bits are the values that are shared by every demanded element.
3000     if (!!DemandedLHS) {
3001       SDValue LHS = Op.getOperand(0);
3002       Known2 = computeKnownBits(LHS, DemandedLHS, Depth + 1);
3003       Known = KnownBits::commonBits(Known, Known2);
3004     }
3005     // If we don't know any bits, early out.
3006     if (Known.isUnknown())
3007       break;
3008     if (!!DemandedRHS) {
3009       SDValue RHS = Op.getOperand(1);
3010       Known2 = computeKnownBits(RHS, DemandedRHS, Depth + 1);
3011       Known = KnownBits::commonBits(Known, Known2);
3012     }
3013     break;
3014   }
3015   case ISD::CONCAT_VECTORS: {
3016     // Split DemandedElts and test each of the demanded subvectors.
3017     Known.Zero.setAllBits(); Known.One.setAllBits();
3018     EVT SubVectorVT = Op.getOperand(0).getValueType();
3019     unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
3020     unsigned NumSubVectors = Op.getNumOperands();
3021     for (unsigned i = 0; i != NumSubVectors; ++i) {
3022       APInt DemandedSub =
3023           DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts);
3024       if (!!DemandedSub) {
3025         SDValue Sub = Op.getOperand(i);
3026         Known2 = computeKnownBits(Sub, DemandedSub, Depth + 1);
3027         Known = KnownBits::commonBits(Known, Known2);
3028       }
3029       // If we don't know any bits, early out.
3030       if (Known.isUnknown())
3031         break;
3032     }
3033     break;
3034   }
3035   case ISD::INSERT_SUBVECTOR: {
3036     // Demand any elements from the subvector and the remainder from the src its
3037     // inserted into.
3038     SDValue Src = Op.getOperand(0);
3039     SDValue Sub = Op.getOperand(1);
3040     uint64_t Idx = Op.getConstantOperandVal(2);
3041     unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
3042     APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
3043     APInt DemandedSrcElts = DemandedElts;
3044     DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx);
3045 
3046     Known.One.setAllBits();
3047     Known.Zero.setAllBits();
3048     if (!!DemandedSubElts) {
3049       Known = computeKnownBits(Sub, DemandedSubElts, Depth + 1);
3050       if (Known.isUnknown())
3051         break; // early-out.
3052     }
3053     if (!!DemandedSrcElts) {
3054       Known2 = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
3055       Known = KnownBits::commonBits(Known, Known2);
3056     }
3057     break;
3058   }
3059   case ISD::EXTRACT_SUBVECTOR: {
3060     // Offset the demanded elts by the subvector index.
3061     SDValue Src = Op.getOperand(0);
3062     // Bail until we can represent demanded elements for scalable vectors.
3063     if (Src.getValueType().isScalableVector())
3064       break;
3065     uint64_t Idx = Op.getConstantOperandVal(1);
3066     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
3067     APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
3068     Known = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
3069     break;
3070   }
3071   case ISD::SCALAR_TO_VECTOR: {
3072     // We know about scalar_to_vector as much as we know about it source,
3073     // which becomes the first element of otherwise unknown vector.
3074     if (DemandedElts != 1)
3075       break;
3076 
3077     SDValue N0 = Op.getOperand(0);
3078     Known = computeKnownBits(N0, Depth + 1);
3079     if (N0.getValueSizeInBits() != BitWidth)
3080       Known = Known.trunc(BitWidth);
3081 
3082     break;
3083   }
3084   case ISD::BITCAST: {
3085     SDValue N0 = Op.getOperand(0);
3086     EVT SubVT = N0.getValueType();
3087     unsigned SubBitWidth = SubVT.getScalarSizeInBits();
3088 
3089     // Ignore bitcasts from unsupported types.
3090     if (!(SubVT.isInteger() || SubVT.isFloatingPoint()))
3091       break;
3092 
3093     // Fast handling of 'identity' bitcasts.
3094     if (BitWidth == SubBitWidth) {
3095       Known = computeKnownBits(N0, DemandedElts, Depth + 1);
3096       break;
3097     }
3098 
3099     bool IsLE = getDataLayout().isLittleEndian();
3100 
3101     // Bitcast 'small element' vector to 'large element' scalar/vector.
3102     if ((BitWidth % SubBitWidth) == 0) {
3103       assert(N0.getValueType().isVector() && "Expected bitcast from vector");
3104 
3105       // Collect known bits for the (larger) output by collecting the known
3106       // bits from each set of sub elements and shift these into place.
3107       // We need to separately call computeKnownBits for each set of
3108       // sub elements as the knownbits for each is likely to be different.
3109       unsigned SubScale = BitWidth / SubBitWidth;
3110       APInt SubDemandedElts(NumElts * SubScale, 0);
3111       for (unsigned i = 0; i != NumElts; ++i)
3112         if (DemandedElts[i])
3113           SubDemandedElts.setBit(i * SubScale);
3114 
3115       for (unsigned i = 0; i != SubScale; ++i) {
3116         Known2 = computeKnownBits(N0, SubDemandedElts.shl(i),
3117                          Depth + 1);
3118         unsigned Shifts = IsLE ? i : SubScale - 1 - i;
3119         Known.insertBits(Known2, SubBitWidth * Shifts);
3120       }
3121     }
3122 
3123     // Bitcast 'large element' scalar/vector to 'small element' vector.
3124     if ((SubBitWidth % BitWidth) == 0) {
3125       assert(Op.getValueType().isVector() && "Expected bitcast to vector");
3126 
3127       // Collect known bits for the (smaller) output by collecting the known
3128       // bits from the overlapping larger input elements and extracting the
3129       // sub sections we actually care about.
3130       unsigned SubScale = SubBitWidth / BitWidth;
3131       APInt SubDemandedElts =
3132           APIntOps::ScaleBitMask(DemandedElts, NumElts / SubScale);
3133       Known2 = computeKnownBits(N0, SubDemandedElts, Depth + 1);
3134 
3135       Known.Zero.setAllBits(); Known.One.setAllBits();
3136       for (unsigned i = 0; i != NumElts; ++i)
3137         if (DemandedElts[i]) {
3138           unsigned Shifts = IsLE ? i : NumElts - 1 - i;
3139           unsigned Offset = (Shifts % SubScale) * BitWidth;
3140           Known = KnownBits::commonBits(Known,
3141                                         Known2.extractBits(BitWidth, Offset));
3142           // If we don't know any bits, early out.
3143           if (Known.isUnknown())
3144             break;
3145         }
3146     }
3147     break;
3148   }
3149   case ISD::AND:
3150     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3151     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3152 
3153     Known &= Known2;
3154     break;
3155   case ISD::OR:
3156     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3157     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3158 
3159     Known |= Known2;
3160     break;
3161   case ISD::XOR:
3162     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3163     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3164 
3165     Known ^= Known2;
3166     break;
3167   case ISD::MUL: {
3168     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3169     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3170     bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1);
3171     // TODO: SelfMultiply can be poison, but not undef.
3172     if (SelfMultiply)
3173       SelfMultiply &= isGuaranteedNotToBeUndefOrPoison(
3174           Op.getOperand(0), DemandedElts, false, Depth + 1);
3175     Known = KnownBits::mul(Known, Known2, SelfMultiply);
3176 
3177     // If the multiplication is known not to overflow, the product of a number
3178     // with itself is non-negative. Only do this if we didn't already computed
3179     // the opposite value for the sign bit.
3180     if (Op->getFlags().hasNoSignedWrap() &&
3181         Op.getOperand(0) == Op.getOperand(1) &&
3182         !Known.isNegative())
3183       Known.makeNonNegative();
3184     break;
3185   }
3186   case ISD::MULHU: {
3187     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3188     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3189     Known = KnownBits::mulhu(Known, Known2);
3190     break;
3191   }
3192   case ISD::MULHS: {
3193     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3194     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3195     Known = KnownBits::mulhs(Known, Known2);
3196     break;
3197   }
3198   case ISD::UMUL_LOHI: {
3199     assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3200     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3201     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3202     bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1);
3203     if (Op.getResNo() == 0)
3204       Known = KnownBits::mul(Known, Known2, SelfMultiply);
3205     else
3206       Known = KnownBits::mulhu(Known, Known2);
3207     break;
3208   }
3209   case ISD::SMUL_LOHI: {
3210     assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3211     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3212     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3213     bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1);
3214     if (Op.getResNo() == 0)
3215       Known = KnownBits::mul(Known, Known2, SelfMultiply);
3216     else
3217       Known = KnownBits::mulhs(Known, Known2);
3218     break;
3219   }
3220   case ISD::UDIV: {
3221     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3222     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3223     Known = KnownBits::udiv(Known, Known2);
3224     break;
3225   }
3226   case ISD::AVGCEILU: {
3227     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3228     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3229     Known = Known.zext(BitWidth + 1);
3230     Known2 = Known2.zext(BitWidth + 1);
3231     KnownBits One = KnownBits::makeConstant(APInt(1, 1));
3232     Known = KnownBits::computeForAddCarry(Known, Known2, One);
3233     Known = Known.extractBits(BitWidth, 1);
3234     break;
3235   }
3236   case ISD::SELECT:
3237   case ISD::VSELECT:
3238     Known = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
3239     // If we don't know any bits, early out.
3240     if (Known.isUnknown())
3241       break;
3242     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth+1);
3243 
3244     // Only known if known in both the LHS and RHS.
3245     Known = KnownBits::commonBits(Known, Known2);
3246     break;
3247   case ISD::SELECT_CC:
3248     Known = computeKnownBits(Op.getOperand(3), DemandedElts, Depth+1);
3249     // If we don't know any bits, early out.
3250     if (Known.isUnknown())
3251       break;
3252     Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
3253 
3254     // Only known if known in both the LHS and RHS.
3255     Known = KnownBits::commonBits(Known, Known2);
3256     break;
3257   case ISD::SMULO:
3258   case ISD::UMULO:
3259     if (Op.getResNo() != 1)
3260       break;
3261     // The boolean result conforms to getBooleanContents.
3262     // If we know the result of a setcc has the top bits zero, use this info.
3263     // We know that we have an integer-based boolean since these operations
3264     // are only available for integer.
3265     if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
3266             TargetLowering::ZeroOrOneBooleanContent &&
3267         BitWidth > 1)
3268       Known.Zero.setBitsFrom(1);
3269     break;
3270   case ISD::SETCC:
3271   case ISD::STRICT_FSETCC:
3272   case ISD::STRICT_FSETCCS: {
3273     unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
3274     // If we know the result of a setcc has the top bits zero, use this info.
3275     if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
3276             TargetLowering::ZeroOrOneBooleanContent &&
3277         BitWidth > 1)
3278       Known.Zero.setBitsFrom(1);
3279     break;
3280   }
3281   case ISD::SHL:
3282     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3283     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3284     Known = KnownBits::shl(Known, Known2);
3285 
3286     // Minimum shift low bits are known zero.
3287     if (const APInt *ShMinAmt =
3288             getValidMinimumShiftAmountConstant(Op, DemandedElts))
3289       Known.Zero.setLowBits(ShMinAmt->getZExtValue());
3290     break;
3291   case ISD::SRL:
3292     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3293     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3294     Known = KnownBits::lshr(Known, Known2);
3295 
3296     // Minimum shift high bits are known zero.
3297     if (const APInt *ShMinAmt =
3298             getValidMinimumShiftAmountConstant(Op, DemandedElts))
3299       Known.Zero.setHighBits(ShMinAmt->getZExtValue());
3300     break;
3301   case ISD::SRA:
3302     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3303     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3304     Known = KnownBits::ashr(Known, Known2);
3305     // TODO: Add minimum shift high known sign bits.
3306     break;
3307   case ISD::FSHL:
3308   case ISD::FSHR:
3309     if (ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(2), DemandedElts)) {
3310       unsigned Amt = C->getAPIntValue().urem(BitWidth);
3311 
3312       // For fshl, 0-shift returns the 1st arg.
3313       // For fshr, 0-shift returns the 2nd arg.
3314       if (Amt == 0) {
3315         Known = computeKnownBits(Op.getOperand(Opcode == ISD::FSHL ? 0 : 1),
3316                                  DemandedElts, Depth + 1);
3317         break;
3318       }
3319 
3320       // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
3321       // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
3322       Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3323       Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3324       if (Opcode == ISD::FSHL) {
3325         Known.One <<= Amt;
3326         Known.Zero <<= Amt;
3327         Known2.One.lshrInPlace(BitWidth - Amt);
3328         Known2.Zero.lshrInPlace(BitWidth - Amt);
3329       } else {
3330         Known.One <<= BitWidth - Amt;
3331         Known.Zero <<= BitWidth - Amt;
3332         Known2.One.lshrInPlace(Amt);
3333         Known2.Zero.lshrInPlace(Amt);
3334       }
3335       Known.One |= Known2.One;
3336       Known.Zero |= Known2.Zero;
3337     }
3338     break;
3339   case ISD::SIGN_EXTEND_INREG: {
3340     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3341     EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3342     Known = Known.sextInReg(EVT.getScalarSizeInBits());
3343     break;
3344   }
3345   case ISD::CTTZ:
3346   case ISD::CTTZ_ZERO_UNDEF: {
3347     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3348     // If we have a known 1, its position is our upper bound.
3349     unsigned PossibleTZ = Known2.countMaxTrailingZeros();
3350     unsigned LowBits = Log2_32(PossibleTZ) + 1;
3351     Known.Zero.setBitsFrom(LowBits);
3352     break;
3353   }
3354   case ISD::CTLZ:
3355   case ISD::CTLZ_ZERO_UNDEF: {
3356     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3357     // If we have a known 1, its position is our upper bound.
3358     unsigned PossibleLZ = Known2.countMaxLeadingZeros();
3359     unsigned LowBits = Log2_32(PossibleLZ) + 1;
3360     Known.Zero.setBitsFrom(LowBits);
3361     break;
3362   }
3363   case ISD::CTPOP: {
3364     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3365     // If we know some of the bits are zero, they can't be one.
3366     unsigned PossibleOnes = Known2.countMaxPopulation();
3367     Known.Zero.setBitsFrom(Log2_32(PossibleOnes) + 1);
3368     break;
3369   }
3370   case ISD::PARITY: {
3371     // Parity returns 0 everywhere but the LSB.
3372     Known.Zero.setBitsFrom(1);
3373     break;
3374   }
3375   case ISD::LOAD: {
3376     LoadSDNode *LD = cast<LoadSDNode>(Op);
3377     const Constant *Cst = TLI->getTargetConstantFromLoad(LD);
3378     if (ISD::isNON_EXTLoad(LD) && Cst) {
3379       // Determine any common known bits from the loaded constant pool value.
3380       Type *CstTy = Cst->getType();
3381       if ((NumElts * BitWidth) == CstTy->getPrimitiveSizeInBits()) {
3382         // If its a vector splat, then we can (quickly) reuse the scalar path.
3383         // NOTE: We assume all elements match and none are UNDEF.
3384         if (CstTy->isVectorTy()) {
3385           if (const Constant *Splat = Cst->getSplatValue()) {
3386             Cst = Splat;
3387             CstTy = Cst->getType();
3388           }
3389         }
3390         // TODO - do we need to handle different bitwidths?
3391         if (CstTy->isVectorTy() && BitWidth == CstTy->getScalarSizeInBits()) {
3392           // Iterate across all vector elements finding common known bits.
3393           Known.One.setAllBits();
3394           Known.Zero.setAllBits();
3395           for (unsigned i = 0; i != NumElts; ++i) {
3396             if (!DemandedElts[i])
3397               continue;
3398             if (Constant *Elt = Cst->getAggregateElement(i)) {
3399               if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
3400                 const APInt &Value = CInt->getValue();
3401                 Known.One &= Value;
3402                 Known.Zero &= ~Value;
3403                 continue;
3404               }
3405               if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
3406                 APInt Value = CFP->getValueAPF().bitcastToAPInt();
3407                 Known.One &= Value;
3408                 Known.Zero &= ~Value;
3409                 continue;
3410               }
3411             }
3412             Known.One.clearAllBits();
3413             Known.Zero.clearAllBits();
3414             break;
3415           }
3416         } else if (BitWidth == CstTy->getPrimitiveSizeInBits()) {
3417           if (auto *CInt = dyn_cast<ConstantInt>(Cst)) {
3418             Known = KnownBits::makeConstant(CInt->getValue());
3419           } else if (auto *CFP = dyn_cast<ConstantFP>(Cst)) {
3420             Known =
3421                 KnownBits::makeConstant(CFP->getValueAPF().bitcastToAPInt());
3422           }
3423         }
3424       }
3425     } else if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) {
3426       // If this is a ZEXTLoad and we are looking at the loaded value.
3427       EVT VT = LD->getMemoryVT();
3428       unsigned MemBits = VT.getScalarSizeInBits();
3429       Known.Zero.setBitsFrom(MemBits);
3430     } else if (const MDNode *Ranges = LD->getRanges()) {
3431       if (LD->getExtensionType() == ISD::NON_EXTLOAD)
3432         computeKnownBitsFromRangeMetadata(*Ranges, Known);
3433     }
3434     break;
3435   }
3436   case ISD::ZERO_EXTEND_VECTOR_INREG: {
3437     EVT InVT = Op.getOperand(0).getValueType();
3438     APInt InDemandedElts = DemandedElts.zext(InVT.getVectorNumElements());
3439     Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3440     Known = Known.zext(BitWidth);
3441     break;
3442   }
3443   case ISD::ZERO_EXTEND: {
3444     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3445     Known = Known.zext(BitWidth);
3446     break;
3447   }
3448   case ISD::SIGN_EXTEND_VECTOR_INREG: {
3449     EVT InVT = Op.getOperand(0).getValueType();
3450     APInt InDemandedElts = DemandedElts.zext(InVT.getVectorNumElements());
3451     Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3452     // If the sign bit is known to be zero or one, then sext will extend
3453     // it to the top bits, else it will just zext.
3454     Known = Known.sext(BitWidth);
3455     break;
3456   }
3457   case ISD::SIGN_EXTEND: {
3458     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3459     // If the sign bit is known to be zero or one, then sext will extend
3460     // it to the top bits, else it will just zext.
3461     Known = Known.sext(BitWidth);
3462     break;
3463   }
3464   case ISD::ANY_EXTEND_VECTOR_INREG: {
3465     EVT InVT = Op.getOperand(0).getValueType();
3466     APInt InDemandedElts = DemandedElts.zext(InVT.getVectorNumElements());
3467     Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3468     Known = Known.anyext(BitWidth);
3469     break;
3470   }
3471   case ISD::ANY_EXTEND: {
3472     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3473     Known = Known.anyext(BitWidth);
3474     break;
3475   }
3476   case ISD::TRUNCATE: {
3477     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3478     Known = Known.trunc(BitWidth);
3479     break;
3480   }
3481   case ISD::AssertZext: {
3482     EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3483     APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits());
3484     Known = computeKnownBits(Op.getOperand(0), Depth+1);
3485     Known.Zero |= (~InMask);
3486     Known.One  &= (~Known.Zero);
3487     break;
3488   }
3489   case ISD::AssertAlign: {
3490     unsigned LogOfAlign = Log2(cast<AssertAlignSDNode>(Op)->getAlign());
3491     assert(LogOfAlign != 0);
3492 
3493     // TODO: Should use maximum with source
3494     // If a node is guaranteed to be aligned, set low zero bits accordingly as
3495     // well as clearing one bits.
3496     Known.Zero.setLowBits(LogOfAlign);
3497     Known.One.clearLowBits(LogOfAlign);
3498     break;
3499   }
3500   case ISD::FGETSIGN:
3501     // All bits are zero except the low bit.
3502     Known.Zero.setBitsFrom(1);
3503     break;
3504   case ISD::USUBO:
3505   case ISD::SSUBO:
3506     if (Op.getResNo() == 1) {
3507       // If we know the result of a setcc has the top bits zero, use this info.
3508       if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
3509               TargetLowering::ZeroOrOneBooleanContent &&
3510           BitWidth > 1)
3511         Known.Zero.setBitsFrom(1);
3512       break;
3513     }
3514     LLVM_FALLTHROUGH;
3515   case ISD::SUB:
3516   case ISD::SUBC: {
3517     assert(Op.getResNo() == 0 &&
3518            "We only compute knownbits for the difference here.");
3519 
3520     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3521     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3522     Known = KnownBits::computeForAddSub(/* Add */ false, /* NSW */ false,
3523                                         Known, Known2);
3524     break;
3525   }
3526   case ISD::UADDO:
3527   case ISD::SADDO:
3528   case ISD::ADDCARRY:
3529     if (Op.getResNo() == 1) {
3530       // If we know the result of a setcc has the top bits zero, use this info.
3531       if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
3532               TargetLowering::ZeroOrOneBooleanContent &&
3533           BitWidth > 1)
3534         Known.Zero.setBitsFrom(1);
3535       break;
3536     }
3537     LLVM_FALLTHROUGH;
3538   case ISD::ADD:
3539   case ISD::ADDC:
3540   case ISD::ADDE: {
3541     assert(Op.getResNo() == 0 && "We only compute knownbits for the sum here.");
3542 
3543     // With ADDE and ADDCARRY, a carry bit may be added in.
3544     KnownBits Carry(1);
3545     if (Opcode == ISD::ADDE)
3546       // Can't track carry from glue, set carry to unknown.
3547       Carry.resetAll();
3548     else if (Opcode == ISD::ADDCARRY)
3549       // TODO: Compute known bits for the carry operand. Not sure if it is worth
3550       // the trouble (how often will we find a known carry bit). And I haven't
3551       // tested this very much yet, but something like this might work:
3552       //   Carry = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1);
3553       //   Carry = Carry.zextOrTrunc(1, false);
3554       Carry.resetAll();
3555     else
3556       Carry.setAllZero();
3557 
3558     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3559     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3560     Known = KnownBits::computeForAddCarry(Known, Known2, Carry);
3561     break;
3562   }
3563   case ISD::SREM: {
3564     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3565     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3566     Known = KnownBits::srem(Known, Known2);
3567     break;
3568   }
3569   case ISD::UREM: {
3570     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3571     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3572     Known = KnownBits::urem(Known, Known2);
3573     break;
3574   }
3575   case ISD::EXTRACT_ELEMENT: {
3576     Known = computeKnownBits(Op.getOperand(0), Depth+1);
3577     const unsigned Index = Op.getConstantOperandVal(1);
3578     const unsigned EltBitWidth = Op.getValueSizeInBits();
3579 
3580     // Remove low part of known bits mask
3581     Known.Zero = Known.Zero.getHiBits(Known.getBitWidth() - Index * EltBitWidth);
3582     Known.One = Known.One.getHiBits(Known.getBitWidth() - Index * EltBitWidth);
3583 
3584     // Remove high part of known bit mask
3585     Known = Known.trunc(EltBitWidth);
3586     break;
3587   }
3588   case ISD::EXTRACT_VECTOR_ELT: {
3589     SDValue InVec = Op.getOperand(0);
3590     SDValue EltNo = Op.getOperand(1);
3591     EVT VecVT = InVec.getValueType();
3592     // computeKnownBits not yet implemented for scalable vectors.
3593     if (VecVT.isScalableVector())
3594       break;
3595     const unsigned EltBitWidth = VecVT.getScalarSizeInBits();
3596     const unsigned NumSrcElts = VecVT.getVectorNumElements();
3597 
3598     // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know
3599     // anything about the extended bits.
3600     if (BitWidth > EltBitWidth)
3601       Known = Known.trunc(EltBitWidth);
3602 
3603     // If we know the element index, just demand that vector element, else for
3604     // an unknown element index, ignore DemandedElts and demand them all.
3605     APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
3606     auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
3607     if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
3608       DemandedSrcElts =
3609           APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
3610 
3611     Known = computeKnownBits(InVec, DemandedSrcElts, Depth + 1);
3612     if (BitWidth > EltBitWidth)
3613       Known = Known.anyext(BitWidth);
3614     break;
3615   }
3616   case ISD::INSERT_VECTOR_ELT: {
3617     // If we know the element index, split the demand between the
3618     // source vector and the inserted element, otherwise assume we need
3619     // the original demanded vector elements and the value.
3620     SDValue InVec = Op.getOperand(0);
3621     SDValue InVal = Op.getOperand(1);
3622     SDValue EltNo = Op.getOperand(2);
3623     bool DemandedVal = true;
3624     APInt DemandedVecElts = DemandedElts;
3625     auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
3626     if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
3627       unsigned EltIdx = CEltNo->getZExtValue();
3628       DemandedVal = !!DemandedElts[EltIdx];
3629       DemandedVecElts.clearBit(EltIdx);
3630     }
3631     Known.One.setAllBits();
3632     Known.Zero.setAllBits();
3633     if (DemandedVal) {
3634       Known2 = computeKnownBits(InVal, Depth + 1);
3635       Known = KnownBits::commonBits(Known, Known2.zextOrTrunc(BitWidth));
3636     }
3637     if (!!DemandedVecElts) {
3638       Known2 = computeKnownBits(InVec, DemandedVecElts, Depth + 1);
3639       Known = KnownBits::commonBits(Known, Known2);
3640     }
3641     break;
3642   }
3643   case ISD::BITREVERSE: {
3644     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3645     Known = Known2.reverseBits();
3646     break;
3647   }
3648   case ISD::BSWAP: {
3649     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3650     Known = Known2.byteSwap();
3651     break;
3652   }
3653   case ISD::ABS: {
3654     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3655     Known = Known2.abs();
3656     break;
3657   }
3658   case ISD::USUBSAT: {
3659     // The result of usubsat will never be larger than the LHS.
3660     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3661     Known.Zero.setHighBits(Known2.countMinLeadingZeros());
3662     break;
3663   }
3664   case ISD::UMIN: {
3665     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3666     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3667     Known = KnownBits::umin(Known, Known2);
3668     break;
3669   }
3670   case ISD::UMAX: {
3671     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3672     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3673     Known = KnownBits::umax(Known, Known2);
3674     break;
3675   }
3676   case ISD::SMIN:
3677   case ISD::SMAX: {
3678     // If we have a clamp pattern, we know that the number of sign bits will be
3679     // the minimum of the clamp min/max range.
3680     bool IsMax = (Opcode == ISD::SMAX);
3681     ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
3682     if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
3683       if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
3684         CstHigh =
3685             isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
3686     if (CstLow && CstHigh) {
3687       if (!IsMax)
3688         std::swap(CstLow, CstHigh);
3689 
3690       const APInt &ValueLow = CstLow->getAPIntValue();
3691       const APInt &ValueHigh = CstHigh->getAPIntValue();
3692       if (ValueLow.sle(ValueHigh)) {
3693         unsigned LowSignBits = ValueLow.getNumSignBits();
3694         unsigned HighSignBits = ValueHigh.getNumSignBits();
3695         unsigned MinSignBits = std::min(LowSignBits, HighSignBits);
3696         if (ValueLow.isNegative() && ValueHigh.isNegative()) {
3697           Known.One.setHighBits(MinSignBits);
3698           break;
3699         }
3700         if (ValueLow.isNonNegative() && ValueHigh.isNonNegative()) {
3701           Known.Zero.setHighBits(MinSignBits);
3702           break;
3703         }
3704       }
3705     }
3706 
3707     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3708     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3709     if (IsMax)
3710       Known = KnownBits::smax(Known, Known2);
3711     else
3712       Known = KnownBits::smin(Known, Known2);
3713 
3714     // For SMAX, if CstLow is non-negative we know the result will be
3715     // non-negative and thus all sign bits are 0.
3716     // TODO: There's an equivalent of this for smin with negative constant for
3717     // known ones.
3718     if (IsMax && CstLow) {
3719       const APInt &ValueLow = CstLow->getAPIntValue();
3720       if (ValueLow.isNonNegative()) {
3721         unsigned SignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
3722         Known.Zero.setHighBits(std::min(SignBits, ValueLow.getNumSignBits()));
3723       }
3724     }
3725 
3726     break;
3727   }
3728   case ISD::FP_TO_UINT_SAT: {
3729     // FP_TO_UINT_SAT produces an unsigned value that fits in the saturating VT.
3730     EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3731     Known.Zero |= APInt::getBitsSetFrom(BitWidth, VT.getScalarSizeInBits());
3732     break;
3733   }
3734   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
3735     if (Op.getResNo() == 1) {
3736       // The boolean result conforms to getBooleanContents.
3737       // If we know the result of a setcc has the top bits zero, use this info.
3738       // We know that we have an integer-based boolean since these operations
3739       // are only available for integer.
3740       if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
3741               TargetLowering::ZeroOrOneBooleanContent &&
3742           BitWidth > 1)
3743         Known.Zero.setBitsFrom(1);
3744       break;
3745     }
3746     LLVM_FALLTHROUGH;
3747   case ISD::ATOMIC_CMP_SWAP:
3748   case ISD::ATOMIC_SWAP:
3749   case ISD::ATOMIC_LOAD_ADD:
3750   case ISD::ATOMIC_LOAD_SUB:
3751   case ISD::ATOMIC_LOAD_AND:
3752   case ISD::ATOMIC_LOAD_CLR:
3753   case ISD::ATOMIC_LOAD_OR:
3754   case ISD::ATOMIC_LOAD_XOR:
3755   case ISD::ATOMIC_LOAD_NAND:
3756   case ISD::ATOMIC_LOAD_MIN:
3757   case ISD::ATOMIC_LOAD_MAX:
3758   case ISD::ATOMIC_LOAD_UMIN:
3759   case ISD::ATOMIC_LOAD_UMAX:
3760   case ISD::ATOMIC_LOAD: {
3761     unsigned MemBits =
3762         cast<AtomicSDNode>(Op)->getMemoryVT().getScalarSizeInBits();
3763     // If we are looking at the loaded value.
3764     if (Op.getResNo() == 0) {
3765       if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND)
3766         Known.Zero.setBitsFrom(MemBits);
3767     }
3768     break;
3769   }
3770   case ISD::FrameIndex:
3771   case ISD::TargetFrameIndex:
3772     TLI->computeKnownBitsForFrameIndex(cast<FrameIndexSDNode>(Op)->getIndex(),
3773                                        Known, getMachineFunction());
3774     break;
3775 
3776   default:
3777     if (Opcode < ISD::BUILTIN_OP_END)
3778       break;
3779     LLVM_FALLTHROUGH;
3780   case ISD::INTRINSIC_WO_CHAIN:
3781   case ISD::INTRINSIC_W_CHAIN:
3782   case ISD::INTRINSIC_VOID:
3783     // Allow the target to implement this method for its nodes.
3784     TLI->computeKnownBitsForTargetNode(Op, Known, DemandedElts, *this, Depth);
3785     break;
3786   }
3787 
3788   assert(!Known.hasConflict() && "Bits known to be one AND zero?");
3789   return Known;
3790 }
3791 
3792 SelectionDAG::OverflowKind SelectionDAG::computeOverflowKind(SDValue N0,
3793                                                              SDValue N1) const {
3794   // X + 0 never overflow
3795   if (isNullConstant(N1))
3796     return OFK_Never;
3797 
3798   KnownBits N1Known = computeKnownBits(N1);
3799   if (N1Known.Zero.getBoolValue()) {
3800     KnownBits N0Known = computeKnownBits(N0);
3801 
3802     bool overflow;
3803     (void)N0Known.getMaxValue().uadd_ov(N1Known.getMaxValue(), overflow);
3804     if (!overflow)
3805       return OFK_Never;
3806   }
3807 
3808   // mulhi + 1 never overflow
3809   if (N0.getOpcode() == ISD::UMUL_LOHI && N0.getResNo() == 1 &&
3810       (N1Known.getMaxValue() & 0x01) == N1Known.getMaxValue())
3811     return OFK_Never;
3812 
3813   if (N1.getOpcode() == ISD::UMUL_LOHI && N1.getResNo() == 1) {
3814     KnownBits N0Known = computeKnownBits(N0);
3815 
3816     if ((N0Known.getMaxValue() & 0x01) == N0Known.getMaxValue())
3817       return OFK_Never;
3818   }
3819 
3820   return OFK_Sometime;
3821 }
3822 
3823 bool SelectionDAG::isKnownToBeAPowerOfTwo(SDValue Val) const {
3824   EVT OpVT = Val.getValueType();
3825   unsigned BitWidth = OpVT.getScalarSizeInBits();
3826 
3827   // Is the constant a known power of 2?
3828   if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Val))
3829     return Const->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
3830 
3831   // A left-shift of a constant one will have exactly one bit set because
3832   // shifting the bit off the end is undefined.
3833   if (Val.getOpcode() == ISD::SHL) {
3834     auto *C = isConstOrConstSplat(Val.getOperand(0));
3835     if (C && C->getAPIntValue() == 1)
3836       return true;
3837   }
3838 
3839   // Similarly, a logical right-shift of a constant sign-bit will have exactly
3840   // one bit set.
3841   if (Val.getOpcode() == ISD::SRL) {
3842     auto *C = isConstOrConstSplat(Val.getOperand(0));
3843     if (C && C->getAPIntValue().isSignMask())
3844       return true;
3845   }
3846 
3847   // Are all operands of a build vector constant powers of two?
3848   if (Val.getOpcode() == ISD::BUILD_VECTOR)
3849     if (llvm::all_of(Val->ops(), [BitWidth](SDValue E) {
3850           if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(E))
3851             return C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
3852           return false;
3853         }))
3854       return true;
3855 
3856   // Is the operand of a splat vector a constant power of two?
3857   if (Val.getOpcode() == ISD::SPLAT_VECTOR)
3858     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val->getOperand(0)))
3859       if (C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2())
3860         return true;
3861 
3862   // More could be done here, though the above checks are enough
3863   // to handle some common cases.
3864 
3865   // Fall back to computeKnownBits to catch other known cases.
3866   KnownBits Known = computeKnownBits(Val);
3867   return (Known.countMaxPopulation() == 1) && (Known.countMinPopulation() == 1);
3868 }
3869 
3870 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const {
3871   EVT VT = Op.getValueType();
3872 
3873   // TODO: Assume we don't know anything for now.
3874   if (VT.isScalableVector())
3875     return 1;
3876 
3877   APInt DemandedElts = VT.isVector()
3878                            ? APInt::getAllOnes(VT.getVectorNumElements())
3879                            : APInt(1, 1);
3880   return ComputeNumSignBits(Op, DemandedElts, Depth);
3881 }
3882 
3883 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, const APInt &DemandedElts,
3884                                           unsigned Depth) const {
3885   EVT VT = Op.getValueType();
3886   assert((VT.isInteger() || VT.isFloatingPoint()) && "Invalid VT!");
3887   unsigned VTBits = VT.getScalarSizeInBits();
3888   unsigned NumElts = DemandedElts.getBitWidth();
3889   unsigned Tmp, Tmp2;
3890   unsigned FirstAnswer = 1;
3891 
3892   if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
3893     const APInt &Val = C->getAPIntValue();
3894     return Val.getNumSignBits();
3895   }
3896 
3897   if (Depth >= MaxRecursionDepth)
3898     return 1;  // Limit search depth.
3899 
3900   if (!DemandedElts || VT.isScalableVector())
3901     return 1;  // No demanded elts, better to assume we don't know anything.
3902 
3903   unsigned Opcode = Op.getOpcode();
3904   switch (Opcode) {
3905   default: break;
3906   case ISD::AssertSext:
3907     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
3908     return VTBits-Tmp+1;
3909   case ISD::AssertZext:
3910     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
3911     return VTBits-Tmp;
3912 
3913   case ISD::BUILD_VECTOR:
3914     Tmp = VTBits;
3915     for (unsigned i = 0, e = Op.getNumOperands(); (i < e) && (Tmp > 1); ++i) {
3916       if (!DemandedElts[i])
3917         continue;
3918 
3919       SDValue SrcOp = Op.getOperand(i);
3920       Tmp2 = ComputeNumSignBits(SrcOp, Depth + 1);
3921 
3922       // BUILD_VECTOR can implicitly truncate sources, we must handle this.
3923       if (SrcOp.getValueSizeInBits() != VTBits) {
3924         assert(SrcOp.getValueSizeInBits() > VTBits &&
3925                "Expected BUILD_VECTOR implicit truncation");
3926         unsigned ExtraBits = SrcOp.getValueSizeInBits() - VTBits;
3927         Tmp2 = (Tmp2 > ExtraBits ? Tmp2 - ExtraBits : 1);
3928       }
3929       Tmp = std::min(Tmp, Tmp2);
3930     }
3931     return Tmp;
3932 
3933   case ISD::VECTOR_SHUFFLE: {
3934     // Collect the minimum number of sign bits that are shared by every vector
3935     // element referenced by the shuffle.
3936     APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
3937     const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
3938     assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
3939     for (unsigned i = 0; i != NumElts; ++i) {
3940       int M = SVN->getMaskElt(i);
3941       if (!DemandedElts[i])
3942         continue;
3943       // For UNDEF elements, we don't know anything about the common state of
3944       // the shuffle result.
3945       if (M < 0)
3946         return 1;
3947       if ((unsigned)M < NumElts)
3948         DemandedLHS.setBit((unsigned)M % NumElts);
3949       else
3950         DemandedRHS.setBit((unsigned)M % NumElts);
3951     }
3952     Tmp = std::numeric_limits<unsigned>::max();
3953     if (!!DemandedLHS)
3954       Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedLHS, Depth + 1);
3955     if (!!DemandedRHS) {
3956       Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedRHS, Depth + 1);
3957       Tmp = std::min(Tmp, Tmp2);
3958     }
3959     // If we don't know anything, early out and try computeKnownBits fall-back.
3960     if (Tmp == 1)
3961       break;
3962     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
3963     return Tmp;
3964   }
3965 
3966   case ISD::BITCAST: {
3967     SDValue N0 = Op.getOperand(0);
3968     EVT SrcVT = N0.getValueType();
3969     unsigned SrcBits = SrcVT.getScalarSizeInBits();
3970 
3971     // Ignore bitcasts from unsupported types..
3972     if (!(SrcVT.isInteger() || SrcVT.isFloatingPoint()))
3973       break;
3974 
3975     // Fast handling of 'identity' bitcasts.
3976     if (VTBits == SrcBits)
3977       return ComputeNumSignBits(N0, DemandedElts, Depth + 1);
3978 
3979     bool IsLE = getDataLayout().isLittleEndian();
3980 
3981     // Bitcast 'large element' scalar/vector to 'small element' vector.
3982     if ((SrcBits % VTBits) == 0) {
3983       assert(VT.isVector() && "Expected bitcast to vector");
3984 
3985       unsigned Scale = SrcBits / VTBits;
3986       APInt SrcDemandedElts =
3987           APIntOps::ScaleBitMask(DemandedElts, NumElts / Scale);
3988 
3989       // Fast case - sign splat can be simply split across the small elements.
3990       Tmp = ComputeNumSignBits(N0, SrcDemandedElts, Depth + 1);
3991       if (Tmp == SrcBits)
3992         return VTBits;
3993 
3994       // Slow case - determine how far the sign extends into each sub-element.
3995       Tmp2 = VTBits;
3996       for (unsigned i = 0; i != NumElts; ++i)
3997         if (DemandedElts[i]) {
3998           unsigned SubOffset = i % Scale;
3999           SubOffset = (IsLE ? ((Scale - 1) - SubOffset) : SubOffset);
4000           SubOffset = SubOffset * VTBits;
4001           if (Tmp <= SubOffset)
4002             return 1;
4003           Tmp2 = std::min(Tmp2, Tmp - SubOffset);
4004         }
4005       return Tmp2;
4006     }
4007     break;
4008   }
4009 
4010   case ISD::FP_TO_SINT_SAT:
4011     // FP_TO_SINT_SAT produces a signed value that fits in the saturating VT.
4012     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
4013     return VTBits - Tmp + 1;
4014   case ISD::SIGN_EXTEND:
4015     Tmp = VTBits - Op.getOperand(0).getScalarValueSizeInBits();
4016     return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1) + Tmp;
4017   case ISD::SIGN_EXTEND_INREG:
4018     // Max of the input and what this extends.
4019     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
4020     Tmp = VTBits-Tmp+1;
4021     Tmp2 = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
4022     return std::max(Tmp, Tmp2);
4023   case ISD::SIGN_EXTEND_VECTOR_INREG: {
4024     SDValue Src = Op.getOperand(0);
4025     EVT SrcVT = Src.getValueType();
4026     APInt DemandedSrcElts = DemandedElts.zext(SrcVT.getVectorNumElements());
4027     Tmp = VTBits - SrcVT.getScalarSizeInBits();
4028     return ComputeNumSignBits(Src, DemandedSrcElts, Depth+1) + Tmp;
4029   }
4030   case ISD::SRA:
4031     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4032     // SRA X, C -> adds C sign bits.
4033     if (const APInt *ShAmt =
4034             getValidMinimumShiftAmountConstant(Op, DemandedElts))
4035       Tmp = std::min<uint64_t>(Tmp + ShAmt->getZExtValue(), VTBits);
4036     return Tmp;
4037   case ISD::SHL:
4038     if (const APInt *ShAmt =
4039             getValidMaximumShiftAmountConstant(Op, DemandedElts)) {
4040       // shl destroys sign bits, ensure it doesn't shift out all sign bits.
4041       Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4042       if (ShAmt->ult(Tmp))
4043         return Tmp - ShAmt->getZExtValue();
4044     }
4045     break;
4046   case ISD::AND:
4047   case ISD::OR:
4048   case ISD::XOR:    // NOT is handled here.
4049     // Logical binary ops preserve the number of sign bits at the worst.
4050     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
4051     if (Tmp != 1) {
4052       Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
4053       FirstAnswer = std::min(Tmp, Tmp2);
4054       // We computed what we know about the sign bits as our first
4055       // answer. Now proceed to the generic code that uses
4056       // computeKnownBits, and pick whichever answer is better.
4057     }
4058     break;
4059 
4060   case ISD::SELECT:
4061   case ISD::VSELECT:
4062     Tmp = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
4063     if (Tmp == 1) return 1;  // Early out.
4064     Tmp2 = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
4065     return std::min(Tmp, Tmp2);
4066   case ISD::SELECT_CC:
4067     Tmp = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
4068     if (Tmp == 1) return 1;  // Early out.
4069     Tmp2 = ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth+1);
4070     return std::min(Tmp, Tmp2);
4071 
4072   case ISD::SMIN:
4073   case ISD::SMAX: {
4074     // If we have a clamp pattern, we know that the number of sign bits will be
4075     // the minimum of the clamp min/max range.
4076     bool IsMax = (Opcode == ISD::SMAX);
4077     ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
4078     if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
4079       if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
4080         CstHigh =
4081             isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
4082     if (CstLow && CstHigh) {
4083       if (!IsMax)
4084         std::swap(CstLow, CstHigh);
4085       if (CstLow->getAPIntValue().sle(CstHigh->getAPIntValue())) {
4086         Tmp = CstLow->getAPIntValue().getNumSignBits();
4087         Tmp2 = CstHigh->getAPIntValue().getNumSignBits();
4088         return std::min(Tmp, Tmp2);
4089       }
4090     }
4091 
4092     // Fallback - just get the minimum number of sign bits of the operands.
4093     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4094     if (Tmp == 1)
4095       return 1;  // Early out.
4096     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
4097     return std::min(Tmp, Tmp2);
4098   }
4099   case ISD::UMIN:
4100   case ISD::UMAX:
4101     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4102     if (Tmp == 1)
4103       return 1;  // Early out.
4104     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
4105     return std::min(Tmp, Tmp2);
4106   case ISD::SADDO:
4107   case ISD::UADDO:
4108   case ISD::SSUBO:
4109   case ISD::USUBO:
4110   case ISD::SMULO:
4111   case ISD::UMULO:
4112     if (Op.getResNo() != 1)
4113       break;
4114     // The boolean result conforms to getBooleanContents.  Fall through.
4115     // If setcc returns 0/-1, all bits are sign bits.
4116     // We know that we have an integer-based boolean since these operations
4117     // are only available for integer.
4118     if (TLI->getBooleanContents(VT.isVector(), false) ==
4119         TargetLowering::ZeroOrNegativeOneBooleanContent)
4120       return VTBits;
4121     break;
4122   case ISD::SETCC:
4123   case ISD::STRICT_FSETCC:
4124   case ISD::STRICT_FSETCCS: {
4125     unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
4126     // If setcc returns 0/-1, all bits are sign bits.
4127     if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
4128         TargetLowering::ZeroOrNegativeOneBooleanContent)
4129       return VTBits;
4130     break;
4131   }
4132   case ISD::ROTL:
4133   case ISD::ROTR:
4134     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4135 
4136     // If we're rotating an 0/-1 value, then it stays an 0/-1 value.
4137     if (Tmp == VTBits)
4138       return VTBits;
4139 
4140     if (ConstantSDNode *C =
4141             isConstOrConstSplat(Op.getOperand(1), DemandedElts)) {
4142       unsigned RotAmt = C->getAPIntValue().urem(VTBits);
4143 
4144       // Handle rotate right by N like a rotate left by 32-N.
4145       if (Opcode == ISD::ROTR)
4146         RotAmt = (VTBits - RotAmt) % VTBits;
4147 
4148       // If we aren't rotating out all of the known-in sign bits, return the
4149       // number that are left.  This handles rotl(sext(x), 1) for example.
4150       if (Tmp > (RotAmt + 1)) return (Tmp - RotAmt);
4151     }
4152     break;
4153   case ISD::ADD:
4154   case ISD::ADDC:
4155     // Add can have at most one carry bit.  Thus we know that the output
4156     // is, at worst, one more bit than the inputs.
4157     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4158     if (Tmp == 1) return 1; // Early out.
4159 
4160     // Special case decrementing a value (ADD X, -1):
4161     if (ConstantSDNode *CRHS =
4162             isConstOrConstSplat(Op.getOperand(1), DemandedElts))
4163       if (CRHS->isAllOnes()) {
4164         KnownBits Known =
4165             computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4166 
4167         // If the input is known to be 0 or 1, the output is 0/-1, which is all
4168         // sign bits set.
4169         if ((Known.Zero | 1).isAllOnes())
4170           return VTBits;
4171 
4172         // If we are subtracting one from a positive number, there is no carry
4173         // out of the result.
4174         if (Known.isNonNegative())
4175           return Tmp;
4176       }
4177 
4178     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
4179     if (Tmp2 == 1) return 1; // Early out.
4180     return std::min(Tmp, Tmp2) - 1;
4181   case ISD::SUB:
4182     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
4183     if (Tmp2 == 1) return 1; // Early out.
4184 
4185     // Handle NEG.
4186     if (ConstantSDNode *CLHS =
4187             isConstOrConstSplat(Op.getOperand(0), DemandedElts))
4188       if (CLHS->isZero()) {
4189         KnownBits Known =
4190             computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4191         // If the input is known to be 0 or 1, the output is 0/-1, which is all
4192         // sign bits set.
4193         if ((Known.Zero | 1).isAllOnes())
4194           return VTBits;
4195 
4196         // If the input is known to be positive (the sign bit is known clear),
4197         // the output of the NEG has the same number of sign bits as the input.
4198         if (Known.isNonNegative())
4199           return Tmp2;
4200 
4201         // Otherwise, we treat this like a SUB.
4202       }
4203 
4204     // Sub can have at most one carry bit.  Thus we know that the output
4205     // is, at worst, one more bit than the inputs.
4206     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4207     if (Tmp == 1) return 1; // Early out.
4208     return std::min(Tmp, Tmp2) - 1;
4209   case ISD::MUL: {
4210     // The output of the Mul can be at most twice the valid bits in the inputs.
4211     unsigned SignBitsOp0 = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
4212     if (SignBitsOp0 == 1)
4213       break;
4214     unsigned SignBitsOp1 = ComputeNumSignBits(Op.getOperand(1), Depth + 1);
4215     if (SignBitsOp1 == 1)
4216       break;
4217     unsigned OutValidBits =
4218         (VTBits - SignBitsOp0 + 1) + (VTBits - SignBitsOp1 + 1);
4219     return OutValidBits > VTBits ? 1 : VTBits - OutValidBits + 1;
4220   }
4221   case ISD::SREM:
4222     // The sign bit is the LHS's sign bit, except when the result of the
4223     // remainder is zero. The magnitude of the result should be less than or
4224     // equal to the magnitude of the LHS. Therefore, the result should have
4225     // at least as many sign bits as the left hand side.
4226     return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4227   case ISD::TRUNCATE: {
4228     // Check if the sign bits of source go down as far as the truncated value.
4229     unsigned NumSrcBits = Op.getOperand(0).getScalarValueSizeInBits();
4230     unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
4231     if (NumSrcSignBits > (NumSrcBits - VTBits))
4232       return NumSrcSignBits - (NumSrcBits - VTBits);
4233     break;
4234   }
4235   case ISD::EXTRACT_ELEMENT: {
4236     const int KnownSign = ComputeNumSignBits(Op.getOperand(0), Depth+1);
4237     const int BitWidth = Op.getValueSizeInBits();
4238     const int Items = Op.getOperand(0).getValueSizeInBits() / BitWidth;
4239 
4240     // Get reverse index (starting from 1), Op1 value indexes elements from
4241     // little end. Sign starts at big end.
4242     const int rIndex = Items - 1 - Op.getConstantOperandVal(1);
4243 
4244     // If the sign portion ends in our element the subtraction gives correct
4245     // result. Otherwise it gives either negative or > bitwidth result
4246     return std::max(std::min(KnownSign - rIndex * BitWidth, BitWidth), 0);
4247   }
4248   case ISD::INSERT_VECTOR_ELT: {
4249     // If we know the element index, split the demand between the
4250     // source vector and the inserted element, otherwise assume we need
4251     // the original demanded vector elements and the value.
4252     SDValue InVec = Op.getOperand(0);
4253     SDValue InVal = Op.getOperand(1);
4254     SDValue EltNo = Op.getOperand(2);
4255     bool DemandedVal = true;
4256     APInt DemandedVecElts = DemandedElts;
4257     auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
4258     if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
4259       unsigned EltIdx = CEltNo->getZExtValue();
4260       DemandedVal = !!DemandedElts[EltIdx];
4261       DemandedVecElts.clearBit(EltIdx);
4262     }
4263     Tmp = std::numeric_limits<unsigned>::max();
4264     if (DemandedVal) {
4265       // TODO - handle implicit truncation of inserted elements.
4266       if (InVal.getScalarValueSizeInBits() != VTBits)
4267         break;
4268       Tmp2 = ComputeNumSignBits(InVal, Depth + 1);
4269       Tmp = std::min(Tmp, Tmp2);
4270     }
4271     if (!!DemandedVecElts) {
4272       Tmp2 = ComputeNumSignBits(InVec, DemandedVecElts, Depth + 1);
4273       Tmp = std::min(Tmp, Tmp2);
4274     }
4275     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
4276     return Tmp;
4277   }
4278   case ISD::EXTRACT_VECTOR_ELT: {
4279     SDValue InVec = Op.getOperand(0);
4280     SDValue EltNo = Op.getOperand(1);
4281     EVT VecVT = InVec.getValueType();
4282     // ComputeNumSignBits not yet implemented for scalable vectors.
4283     if (VecVT.isScalableVector())
4284       break;
4285     const unsigned BitWidth = Op.getValueSizeInBits();
4286     const unsigned EltBitWidth = Op.getOperand(0).getScalarValueSizeInBits();
4287     const unsigned NumSrcElts = VecVT.getVectorNumElements();
4288 
4289     // If BitWidth > EltBitWidth the value is anyext:ed, and we do not know
4290     // anything about sign bits. But if the sizes match we can derive knowledge
4291     // about sign bits from the vector operand.
4292     if (BitWidth != EltBitWidth)
4293       break;
4294 
4295     // If we know the element index, just demand that vector element, else for
4296     // an unknown element index, ignore DemandedElts and demand them all.
4297     APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
4298     auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
4299     if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
4300       DemandedSrcElts =
4301           APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
4302 
4303     return ComputeNumSignBits(InVec, DemandedSrcElts, Depth + 1);
4304   }
4305   case ISD::EXTRACT_SUBVECTOR: {
4306     // Offset the demanded elts by the subvector index.
4307     SDValue Src = Op.getOperand(0);
4308     // Bail until we can represent demanded elements for scalable vectors.
4309     if (Src.getValueType().isScalableVector())
4310       break;
4311     uint64_t Idx = Op.getConstantOperandVal(1);
4312     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
4313     APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
4314     return ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
4315   }
4316   case ISD::CONCAT_VECTORS: {
4317     // Determine the minimum number of sign bits across all demanded
4318     // elts of the input vectors. Early out if the result is already 1.
4319     Tmp = std::numeric_limits<unsigned>::max();
4320     EVT SubVectorVT = Op.getOperand(0).getValueType();
4321     unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
4322     unsigned NumSubVectors = Op.getNumOperands();
4323     for (unsigned i = 0; (i < NumSubVectors) && (Tmp > 1); ++i) {
4324       APInt DemandedSub =
4325           DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts);
4326       if (!DemandedSub)
4327         continue;
4328       Tmp2 = ComputeNumSignBits(Op.getOperand(i), DemandedSub, Depth + 1);
4329       Tmp = std::min(Tmp, Tmp2);
4330     }
4331     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
4332     return Tmp;
4333   }
4334   case ISD::INSERT_SUBVECTOR: {
4335     // Demand any elements from the subvector and the remainder from the src its
4336     // inserted into.
4337     SDValue Src = Op.getOperand(0);
4338     SDValue Sub = Op.getOperand(1);
4339     uint64_t Idx = Op.getConstantOperandVal(2);
4340     unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
4341     APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
4342     APInt DemandedSrcElts = DemandedElts;
4343     DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx);
4344 
4345     Tmp = std::numeric_limits<unsigned>::max();
4346     if (!!DemandedSubElts) {
4347       Tmp = ComputeNumSignBits(Sub, DemandedSubElts, Depth + 1);
4348       if (Tmp == 1)
4349         return 1; // early-out
4350     }
4351     if (!!DemandedSrcElts) {
4352       Tmp2 = ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
4353       Tmp = std::min(Tmp, Tmp2);
4354     }
4355     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
4356     return Tmp;
4357   }
4358   case ISD::ATOMIC_CMP_SWAP:
4359   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
4360   case ISD::ATOMIC_SWAP:
4361   case ISD::ATOMIC_LOAD_ADD:
4362   case ISD::ATOMIC_LOAD_SUB:
4363   case ISD::ATOMIC_LOAD_AND:
4364   case ISD::ATOMIC_LOAD_CLR:
4365   case ISD::ATOMIC_LOAD_OR:
4366   case ISD::ATOMIC_LOAD_XOR:
4367   case ISD::ATOMIC_LOAD_NAND:
4368   case ISD::ATOMIC_LOAD_MIN:
4369   case ISD::ATOMIC_LOAD_MAX:
4370   case ISD::ATOMIC_LOAD_UMIN:
4371   case ISD::ATOMIC_LOAD_UMAX:
4372   case ISD::ATOMIC_LOAD: {
4373     Tmp = cast<AtomicSDNode>(Op)->getMemoryVT().getScalarSizeInBits();
4374     // If we are looking at the loaded value.
4375     if (Op.getResNo() == 0) {
4376       if (Tmp == VTBits)
4377         return 1; // early-out
4378       if (TLI->getExtendForAtomicOps() == ISD::SIGN_EXTEND)
4379         return VTBits - Tmp + 1;
4380       if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND)
4381         return VTBits - Tmp;
4382     }
4383     break;
4384   }
4385   }
4386 
4387   // If we are looking at the loaded value of the SDNode.
4388   if (Op.getResNo() == 0) {
4389     // Handle LOADX separately here. EXTLOAD case will fallthrough.
4390     if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
4391       unsigned ExtType = LD->getExtensionType();
4392       switch (ExtType) {
4393       default: break;
4394       case ISD::SEXTLOAD: // e.g. i16->i32 = '17' bits known.
4395         Tmp = LD->getMemoryVT().getScalarSizeInBits();
4396         return VTBits - Tmp + 1;
4397       case ISD::ZEXTLOAD: // e.g. i16->i32 = '16' bits known.
4398         Tmp = LD->getMemoryVT().getScalarSizeInBits();
4399         return VTBits - Tmp;
4400       case ISD::NON_EXTLOAD:
4401         if (const Constant *Cst = TLI->getTargetConstantFromLoad(LD)) {
4402           // We only need to handle vectors - computeKnownBits should handle
4403           // scalar cases.
4404           Type *CstTy = Cst->getType();
4405           if (CstTy->isVectorTy() &&
4406               (NumElts * VTBits) == CstTy->getPrimitiveSizeInBits() &&
4407               VTBits == CstTy->getScalarSizeInBits()) {
4408             Tmp = VTBits;
4409             for (unsigned i = 0; i != NumElts; ++i) {
4410               if (!DemandedElts[i])
4411                 continue;
4412               if (Constant *Elt = Cst->getAggregateElement(i)) {
4413                 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
4414                   const APInt &Value = CInt->getValue();
4415                   Tmp = std::min(Tmp, Value.getNumSignBits());
4416                   continue;
4417                 }
4418                 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
4419                   APInt Value = CFP->getValueAPF().bitcastToAPInt();
4420                   Tmp = std::min(Tmp, Value.getNumSignBits());
4421                   continue;
4422                 }
4423               }
4424               // Unknown type. Conservatively assume no bits match sign bit.
4425               return 1;
4426             }
4427             return Tmp;
4428           }
4429         }
4430         break;
4431       }
4432     }
4433   }
4434 
4435   // Allow the target to implement this method for its nodes.
4436   if (Opcode >= ISD::BUILTIN_OP_END ||
4437       Opcode == ISD::INTRINSIC_WO_CHAIN ||
4438       Opcode == ISD::INTRINSIC_W_CHAIN ||
4439       Opcode == ISD::INTRINSIC_VOID) {
4440     unsigned NumBits =
4441         TLI->ComputeNumSignBitsForTargetNode(Op, DemandedElts, *this, Depth);
4442     if (NumBits > 1)
4443       FirstAnswer = std::max(FirstAnswer, NumBits);
4444   }
4445 
4446   // Finally, if we can prove that the top bits of the result are 0's or 1's,
4447   // use this information.
4448   KnownBits Known = computeKnownBits(Op, DemandedElts, Depth);
4449   return std::max(FirstAnswer, Known.countMinSignBits());
4450 }
4451 
4452 unsigned SelectionDAG::ComputeMaxSignificantBits(SDValue Op,
4453                                                  unsigned Depth) const {
4454   unsigned SignBits = ComputeNumSignBits(Op, Depth);
4455   return Op.getScalarValueSizeInBits() - SignBits + 1;
4456 }
4457 
4458 unsigned SelectionDAG::ComputeMaxSignificantBits(SDValue Op,
4459                                                  const APInt &DemandedElts,
4460                                                  unsigned Depth) const {
4461   unsigned SignBits = ComputeNumSignBits(Op, DemandedElts, Depth);
4462   return Op.getScalarValueSizeInBits() - SignBits + 1;
4463 }
4464 
4465 bool SelectionDAG::isGuaranteedNotToBeUndefOrPoison(SDValue Op, bool PoisonOnly,
4466                                                     unsigned Depth) const {
4467   // Early out for FREEZE.
4468   if (Op.getOpcode() == ISD::FREEZE)
4469     return true;
4470 
4471   // TODO: Assume we don't know anything for now.
4472   EVT VT = Op.getValueType();
4473   if (VT.isScalableVector())
4474     return false;
4475 
4476   APInt DemandedElts = VT.isVector()
4477                            ? APInt::getAllOnes(VT.getVectorNumElements())
4478                            : APInt(1, 1);
4479   return isGuaranteedNotToBeUndefOrPoison(Op, DemandedElts, PoisonOnly, Depth);
4480 }
4481 
4482 bool SelectionDAG::isGuaranteedNotToBeUndefOrPoison(SDValue Op,
4483                                                     const APInt &DemandedElts,
4484                                                     bool PoisonOnly,
4485                                                     unsigned Depth) const {
4486   unsigned Opcode = Op.getOpcode();
4487 
4488   // Early out for FREEZE.
4489   if (Opcode == ISD::FREEZE)
4490     return true;
4491 
4492   if (Depth >= MaxRecursionDepth)
4493     return false; // Limit search depth.
4494 
4495   if (isIntOrFPConstant(Op))
4496     return true;
4497 
4498   switch (Opcode) {
4499   case ISD::UNDEF:
4500     return PoisonOnly;
4501 
4502   case ISD::BUILD_VECTOR:
4503     // NOTE: BUILD_VECTOR has implicit truncation of wider scalar elements -
4504     // this shouldn't affect the result.
4505     for (unsigned i = 0, e = Op.getNumOperands(); i < e; ++i) {
4506       if (!DemandedElts[i])
4507         continue;
4508       if (!isGuaranteedNotToBeUndefOrPoison(Op.getOperand(i), PoisonOnly,
4509                                             Depth + 1))
4510         return false;
4511     }
4512     return true;
4513 
4514   // TODO: Search for noundef attributes from library functions.
4515 
4516   // TODO: Pointers dereferenced by ISD::LOAD/STORE ops are noundef.
4517 
4518   default:
4519     // Allow the target to implement this method for its nodes.
4520     if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
4521         Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID)
4522       return TLI->isGuaranteedNotToBeUndefOrPoisonForTargetNode(
4523           Op, DemandedElts, *this, PoisonOnly, Depth);
4524     break;
4525   }
4526 
4527   return false;
4528 }
4529 
4530 bool SelectionDAG::isBaseWithConstantOffset(SDValue Op) const {
4531   if ((Op.getOpcode() != ISD::ADD && Op.getOpcode() != ISD::OR) ||
4532       !isa<ConstantSDNode>(Op.getOperand(1)))
4533     return false;
4534 
4535   if (Op.getOpcode() == ISD::OR &&
4536       !MaskedValueIsZero(Op.getOperand(0), Op.getConstantOperandAPInt(1)))
4537     return false;
4538 
4539   return true;
4540 }
4541 
4542 bool SelectionDAG::isKnownNeverNaN(SDValue Op, bool SNaN, unsigned Depth) const {
4543   // If we're told that NaNs won't happen, assume they won't.
4544   if (getTarget().Options.NoNaNsFPMath || Op->getFlags().hasNoNaNs())
4545     return true;
4546 
4547   if (Depth >= MaxRecursionDepth)
4548     return false; // Limit search depth.
4549 
4550   // TODO: Handle vectors.
4551   // If the value is a constant, we can obviously see if it is a NaN or not.
4552   if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) {
4553     return !C->getValueAPF().isNaN() ||
4554            (SNaN && !C->getValueAPF().isSignaling());
4555   }
4556 
4557   unsigned Opcode = Op.getOpcode();
4558   switch (Opcode) {
4559   case ISD::FADD:
4560   case ISD::FSUB:
4561   case ISD::FMUL:
4562   case ISD::FDIV:
4563   case ISD::FREM:
4564   case ISD::FSIN:
4565   case ISD::FCOS: {
4566     if (SNaN)
4567       return true;
4568     // TODO: Need isKnownNeverInfinity
4569     return false;
4570   }
4571   case ISD::FCANONICALIZE:
4572   case ISD::FEXP:
4573   case ISD::FEXP2:
4574   case ISD::FTRUNC:
4575   case ISD::FFLOOR:
4576   case ISD::FCEIL:
4577   case ISD::FROUND:
4578   case ISD::FROUNDEVEN:
4579   case ISD::FRINT:
4580   case ISD::FNEARBYINT: {
4581     if (SNaN)
4582       return true;
4583     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4584   }
4585   case ISD::FABS:
4586   case ISD::FNEG:
4587   case ISD::FCOPYSIGN: {
4588     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4589   }
4590   case ISD::SELECT:
4591     return isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) &&
4592            isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1);
4593   case ISD::FP_EXTEND:
4594   case ISD::FP_ROUND: {
4595     if (SNaN)
4596       return true;
4597     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4598   }
4599   case ISD::SINT_TO_FP:
4600   case ISD::UINT_TO_FP:
4601     return true;
4602   case ISD::FMA:
4603   case ISD::FMAD: {
4604     if (SNaN)
4605       return true;
4606     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) &&
4607            isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) &&
4608            isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1);
4609   }
4610   case ISD::FSQRT: // Need is known positive
4611   case ISD::FLOG:
4612   case ISD::FLOG2:
4613   case ISD::FLOG10:
4614   case ISD::FPOWI:
4615   case ISD::FPOW: {
4616     if (SNaN)
4617       return true;
4618     // TODO: Refine on operand
4619     return false;
4620   }
4621   case ISD::FMINNUM:
4622   case ISD::FMAXNUM: {
4623     // Only one needs to be known not-nan, since it will be returned if the
4624     // other ends up being one.
4625     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) ||
4626            isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1);
4627   }
4628   case ISD::FMINNUM_IEEE:
4629   case ISD::FMAXNUM_IEEE: {
4630     if (SNaN)
4631       return true;
4632     // This can return a NaN if either operand is an sNaN, or if both operands
4633     // are NaN.
4634     return (isKnownNeverNaN(Op.getOperand(0), false, Depth + 1) &&
4635             isKnownNeverSNaN(Op.getOperand(1), Depth + 1)) ||
4636            (isKnownNeverNaN(Op.getOperand(1), false, Depth + 1) &&
4637             isKnownNeverSNaN(Op.getOperand(0), Depth + 1));
4638   }
4639   case ISD::FMINIMUM:
4640   case ISD::FMAXIMUM: {
4641     // TODO: Does this quiet or return the origina NaN as-is?
4642     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) &&
4643            isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1);
4644   }
4645   case ISD::EXTRACT_VECTOR_ELT: {
4646     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4647   }
4648   default:
4649     if (Opcode >= ISD::BUILTIN_OP_END ||
4650         Opcode == ISD::INTRINSIC_WO_CHAIN ||
4651         Opcode == ISD::INTRINSIC_W_CHAIN ||
4652         Opcode == ISD::INTRINSIC_VOID) {
4653       return TLI->isKnownNeverNaNForTargetNode(Op, *this, SNaN, Depth);
4654     }
4655 
4656     return false;
4657   }
4658 }
4659 
4660 bool SelectionDAG::isKnownNeverZeroFloat(SDValue Op) const {
4661   assert(Op.getValueType().isFloatingPoint() &&
4662          "Floating point type expected");
4663 
4664   // If the value is a constant, we can obviously see if it is a zero or not.
4665   // TODO: Add BuildVector support.
4666   if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
4667     return !C->isZero();
4668   return false;
4669 }
4670 
4671 bool SelectionDAG::isKnownNeverZero(SDValue Op) const {
4672   assert(!Op.getValueType().isFloatingPoint() &&
4673          "Floating point types unsupported - use isKnownNeverZeroFloat");
4674 
4675   // If the value is a constant, we can obviously see if it is a zero or not.
4676   if (ISD::matchUnaryPredicate(Op,
4677                                [](ConstantSDNode *C) { return !C->isZero(); }))
4678     return true;
4679 
4680   // TODO: Recognize more cases here.
4681   switch (Op.getOpcode()) {
4682   default: break;
4683   case ISD::OR:
4684     if (isKnownNeverZero(Op.getOperand(1)) ||
4685         isKnownNeverZero(Op.getOperand(0)))
4686       return true;
4687     break;
4688   }
4689 
4690   return false;
4691 }
4692 
4693 bool SelectionDAG::isEqualTo(SDValue A, SDValue B) const {
4694   // Check the obvious case.
4695   if (A == B) return true;
4696 
4697   // For for negative and positive zero.
4698   if (const ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A))
4699     if (const ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B))
4700       if (CA->isZero() && CB->isZero()) return true;
4701 
4702   // Otherwise they may not be equal.
4703   return false;
4704 }
4705 
4706 // Only bits set in Mask must be negated, other bits may be arbitrary.
4707 SDValue llvm::getBitwiseNotOperand(SDValue V, SDValue Mask, bool AllowUndefs) {
4708   if (isBitwiseNot(V, AllowUndefs))
4709     return V.getOperand(0);
4710 
4711   // Handle any_extend (not (truncate X)) pattern, where Mask only sets
4712   // bits in the non-extended part.
4713   ConstantSDNode *MaskC = isConstOrConstSplat(Mask);
4714   if (!MaskC || V.getOpcode() != ISD::ANY_EXTEND)
4715     return SDValue();
4716   SDValue ExtArg = V.getOperand(0);
4717   if (ExtArg.getScalarValueSizeInBits() >=
4718           MaskC->getAPIntValue().getActiveBits() &&
4719       isBitwiseNot(ExtArg, AllowUndefs) &&
4720       ExtArg.getOperand(0).getOpcode() == ISD::TRUNCATE &&
4721       ExtArg.getOperand(0).getOperand(0).getValueType() == V.getValueType())
4722     return ExtArg.getOperand(0).getOperand(0);
4723   return SDValue();
4724 }
4725 
4726 static bool haveNoCommonBitsSetCommutative(SDValue A, SDValue B) {
4727   // Match masked merge pattern (X & ~M) op (Y & M)
4728   // Including degenerate case (X & ~M) op M
4729   auto MatchNoCommonBitsPattern = [&](SDValue Not, SDValue Mask,
4730                                       SDValue Other) {
4731     if (SDValue NotOperand =
4732             getBitwiseNotOperand(Not, Mask, /* AllowUndefs */ true)) {
4733       if (Other == NotOperand)
4734         return true;
4735       if (Other->getOpcode() == ISD::AND)
4736         return NotOperand == Other->getOperand(0) ||
4737                NotOperand == Other->getOperand(1);
4738     }
4739     return false;
4740   };
4741   if (A->getOpcode() == ISD::AND)
4742     return MatchNoCommonBitsPattern(A->getOperand(0), A->getOperand(1), B) ||
4743            MatchNoCommonBitsPattern(A->getOperand(1), A->getOperand(0), B);
4744   return false;
4745 }
4746 
4747 // FIXME: unify with llvm::haveNoCommonBitsSet.
4748 bool SelectionDAG::haveNoCommonBitsSet(SDValue A, SDValue B) const {
4749   assert(A.getValueType() == B.getValueType() &&
4750          "Values must have the same type");
4751   if (haveNoCommonBitsSetCommutative(A, B) ||
4752       haveNoCommonBitsSetCommutative(B, A))
4753     return true;
4754   return KnownBits::haveNoCommonBitsSet(computeKnownBits(A),
4755                                         computeKnownBits(B));
4756 }
4757 
4758 static SDValue FoldSTEP_VECTOR(const SDLoc &DL, EVT VT, SDValue Step,
4759                                SelectionDAG &DAG) {
4760   if (cast<ConstantSDNode>(Step)->isZero())
4761     return DAG.getConstant(0, DL, VT);
4762 
4763   return SDValue();
4764 }
4765 
4766 static SDValue FoldBUILD_VECTOR(const SDLoc &DL, EVT VT,
4767                                 ArrayRef<SDValue> Ops,
4768                                 SelectionDAG &DAG) {
4769   int NumOps = Ops.size();
4770   assert(NumOps != 0 && "Can't build an empty vector!");
4771   assert(!VT.isScalableVector() &&
4772          "BUILD_VECTOR cannot be used with scalable types");
4773   assert(VT.getVectorNumElements() == (unsigned)NumOps &&
4774          "Incorrect element count in BUILD_VECTOR!");
4775 
4776   // BUILD_VECTOR of UNDEFs is UNDEF.
4777   if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
4778     return DAG.getUNDEF(VT);
4779 
4780   // BUILD_VECTOR of seq extract/insert from the same vector + type is Identity.
4781   SDValue IdentitySrc;
4782   bool IsIdentity = true;
4783   for (int i = 0; i != NumOps; ++i) {
4784     if (Ops[i].getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4785         Ops[i].getOperand(0).getValueType() != VT ||
4786         (IdentitySrc && Ops[i].getOperand(0) != IdentitySrc) ||
4787         !isa<ConstantSDNode>(Ops[i].getOperand(1)) ||
4788         cast<ConstantSDNode>(Ops[i].getOperand(1))->getAPIntValue() != i) {
4789       IsIdentity = false;
4790       break;
4791     }
4792     IdentitySrc = Ops[i].getOperand(0);
4793   }
4794   if (IsIdentity)
4795     return IdentitySrc;
4796 
4797   return SDValue();
4798 }
4799 
4800 /// Try to simplify vector concatenation to an input value, undef, or build
4801 /// vector.
4802 static SDValue foldCONCAT_VECTORS(const SDLoc &DL, EVT VT,
4803                                   ArrayRef<SDValue> Ops,
4804                                   SelectionDAG &DAG) {
4805   assert(!Ops.empty() && "Can't concatenate an empty list of vectors!");
4806   assert(llvm::all_of(Ops,
4807                       [Ops](SDValue Op) {
4808                         return Ops[0].getValueType() == Op.getValueType();
4809                       }) &&
4810          "Concatenation of vectors with inconsistent value types!");
4811   assert((Ops[0].getValueType().getVectorElementCount() * Ops.size()) ==
4812              VT.getVectorElementCount() &&
4813          "Incorrect element count in vector concatenation!");
4814 
4815   if (Ops.size() == 1)
4816     return Ops[0];
4817 
4818   // Concat of UNDEFs is UNDEF.
4819   if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
4820     return DAG.getUNDEF(VT);
4821 
4822   // Scan the operands and look for extract operations from a single source
4823   // that correspond to insertion at the same location via this concatenation:
4824   // concat (extract X, 0*subvec_elts), (extract X, 1*subvec_elts), ...
4825   SDValue IdentitySrc;
4826   bool IsIdentity = true;
4827   for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
4828     SDValue Op = Ops[i];
4829     unsigned IdentityIndex = i * Op.getValueType().getVectorMinNumElements();
4830     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
4831         Op.getOperand(0).getValueType() != VT ||
4832         (IdentitySrc && Op.getOperand(0) != IdentitySrc) ||
4833         Op.getConstantOperandVal(1) != IdentityIndex) {
4834       IsIdentity = false;
4835       break;
4836     }
4837     assert((!IdentitySrc || IdentitySrc == Op.getOperand(0)) &&
4838            "Unexpected identity source vector for concat of extracts");
4839     IdentitySrc = Op.getOperand(0);
4840   }
4841   if (IsIdentity) {
4842     assert(IdentitySrc && "Failed to set source vector of extracts");
4843     return IdentitySrc;
4844   }
4845 
4846   // The code below this point is only designed to work for fixed width
4847   // vectors, so we bail out for now.
4848   if (VT.isScalableVector())
4849     return SDValue();
4850 
4851   // A CONCAT_VECTOR with all UNDEF/BUILD_VECTOR operands can be
4852   // simplified to one big BUILD_VECTOR.
4853   // FIXME: Add support for SCALAR_TO_VECTOR as well.
4854   EVT SVT = VT.getScalarType();
4855   SmallVector<SDValue, 16> Elts;
4856   for (SDValue Op : Ops) {
4857     EVT OpVT = Op.getValueType();
4858     if (Op.isUndef())
4859       Elts.append(OpVT.getVectorNumElements(), DAG.getUNDEF(SVT));
4860     else if (Op.getOpcode() == ISD::BUILD_VECTOR)
4861       Elts.append(Op->op_begin(), Op->op_end());
4862     else
4863       return SDValue();
4864   }
4865 
4866   // BUILD_VECTOR requires all inputs to be of the same type, find the
4867   // maximum type and extend them all.
4868   for (SDValue Op : Elts)
4869     SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
4870 
4871   if (SVT.bitsGT(VT.getScalarType())) {
4872     for (SDValue &Op : Elts) {
4873       if (Op.isUndef())
4874         Op = DAG.getUNDEF(SVT);
4875       else
4876         Op = DAG.getTargetLoweringInfo().isZExtFree(Op.getValueType(), SVT)
4877                  ? DAG.getZExtOrTrunc(Op, DL, SVT)
4878                  : DAG.getSExtOrTrunc(Op, DL, SVT);
4879     }
4880   }
4881 
4882   SDValue V = DAG.getBuildVector(VT, DL, Elts);
4883   NewSDValueDbgMsg(V, "New node fold concat vectors: ", &DAG);
4884   return V;
4885 }
4886 
4887 /// Gets or creates the specified node.
4888 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT) {
4889   FoldingSetNodeID ID;
4890   AddNodeIDNode(ID, Opcode, getVTList(VT), None);
4891   void *IP = nullptr;
4892   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
4893     return SDValue(E, 0);
4894 
4895   auto *N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(),
4896                               getVTList(VT));
4897   CSEMap.InsertNode(N, IP);
4898 
4899   InsertNode(N);
4900   SDValue V = SDValue(N, 0);
4901   NewSDValueDbgMsg(V, "Creating new node: ", this);
4902   return V;
4903 }
4904 
4905 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4906                               SDValue Operand) {
4907   SDNodeFlags Flags;
4908   if (Inserter)
4909     Flags = Inserter->getFlags();
4910   return getNode(Opcode, DL, VT, Operand, Flags);
4911 }
4912 
4913 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4914                               SDValue Operand, const SDNodeFlags Flags) {
4915   assert(Operand.getOpcode() != ISD::DELETED_NODE &&
4916          "Operand is DELETED_NODE!");
4917   // Constant fold unary operations with an integer constant operand. Even
4918   // opaque constant will be folded, because the folding of unary operations
4919   // doesn't create new constants with different values. Nevertheless, the
4920   // opaque flag is preserved during folding to prevent future folding with
4921   // other constants.
4922   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand)) {
4923     const APInt &Val = C->getAPIntValue();
4924     switch (Opcode) {
4925     default: break;
4926     case ISD::SIGN_EXTEND:
4927       return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
4928                          C->isTargetOpcode(), C->isOpaque());
4929     case ISD::TRUNCATE:
4930       if (C->isOpaque())
4931         break;
4932       LLVM_FALLTHROUGH;
4933     case ISD::ZERO_EXTEND:
4934       return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
4935                          C->isTargetOpcode(), C->isOpaque());
4936     case ISD::ANY_EXTEND:
4937       // Some targets like RISCV prefer to sign extend some types.
4938       if (TLI->isSExtCheaperThanZExt(Operand.getValueType(), VT))
4939         return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
4940                            C->isTargetOpcode(), C->isOpaque());
4941       return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
4942                          C->isTargetOpcode(), C->isOpaque());
4943     case ISD::UINT_TO_FP:
4944     case ISD::SINT_TO_FP: {
4945       APFloat apf(EVTToAPFloatSemantics(VT),
4946                   APInt::getZero(VT.getSizeInBits()));
4947       (void)apf.convertFromAPInt(Val,
4948                                  Opcode==ISD::SINT_TO_FP,
4949                                  APFloat::rmNearestTiesToEven);
4950       return getConstantFP(apf, DL, VT);
4951     }
4952     case ISD::BITCAST:
4953       if (VT == MVT::f16 && C->getValueType(0) == MVT::i16)
4954         return getConstantFP(APFloat(APFloat::IEEEhalf(), Val), DL, VT);
4955       if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
4956         return getConstantFP(APFloat(APFloat::IEEEsingle(), Val), DL, VT);
4957       if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
4958         return getConstantFP(APFloat(APFloat::IEEEdouble(), Val), DL, VT);
4959       if (VT == MVT::f128 && C->getValueType(0) == MVT::i128)
4960         return getConstantFP(APFloat(APFloat::IEEEquad(), Val), DL, VT);
4961       break;
4962     case ISD::ABS:
4963       return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(),
4964                          C->isOpaque());
4965     case ISD::BITREVERSE:
4966       return getConstant(Val.reverseBits(), DL, VT, C->isTargetOpcode(),
4967                          C->isOpaque());
4968     case ISD::BSWAP:
4969       return getConstant(Val.byteSwap(), DL, VT, C->isTargetOpcode(),
4970                          C->isOpaque());
4971     case ISD::CTPOP:
4972       return getConstant(Val.countPopulation(), DL, VT, C->isTargetOpcode(),
4973                          C->isOpaque());
4974     case ISD::CTLZ:
4975     case ISD::CTLZ_ZERO_UNDEF:
4976       return getConstant(Val.countLeadingZeros(), DL, VT, C->isTargetOpcode(),
4977                          C->isOpaque());
4978     case ISD::CTTZ:
4979     case ISD::CTTZ_ZERO_UNDEF:
4980       return getConstant(Val.countTrailingZeros(), DL, VT, C->isTargetOpcode(),
4981                          C->isOpaque());
4982     case ISD::FP16_TO_FP: {
4983       bool Ignored;
4984       APFloat FPV(APFloat::IEEEhalf(),
4985                   (Val.getBitWidth() == 16) ? Val : Val.trunc(16));
4986 
4987       // This can return overflow, underflow, or inexact; we don't care.
4988       // FIXME need to be more flexible about rounding mode.
4989       (void)FPV.convert(EVTToAPFloatSemantics(VT),
4990                         APFloat::rmNearestTiesToEven, &Ignored);
4991       return getConstantFP(FPV, DL, VT);
4992     }
4993     case ISD::STEP_VECTOR: {
4994       if (SDValue V = FoldSTEP_VECTOR(DL, VT, Operand, *this))
4995         return V;
4996       break;
4997     }
4998     }
4999   }
5000 
5001   // Constant fold unary operations with a floating point constant operand.
5002   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand)) {
5003     APFloat V = C->getValueAPF();    // make copy
5004     switch (Opcode) {
5005     case ISD::FNEG:
5006       V.changeSign();
5007       return getConstantFP(V, DL, VT);
5008     case ISD::FABS:
5009       V.clearSign();
5010       return getConstantFP(V, DL, VT);
5011     case ISD::FCEIL: {
5012       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardPositive);
5013       if (fs == APFloat::opOK || fs == APFloat::opInexact)
5014         return getConstantFP(V, DL, VT);
5015       break;
5016     }
5017     case ISD::FTRUNC: {
5018       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardZero);
5019       if (fs == APFloat::opOK || fs == APFloat::opInexact)
5020         return getConstantFP(V, DL, VT);
5021       break;
5022     }
5023     case ISD::FFLOOR: {
5024       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardNegative);
5025       if (fs == APFloat::opOK || fs == APFloat::opInexact)
5026         return getConstantFP(V, DL, VT);
5027       break;
5028     }
5029     case ISD::FP_EXTEND: {
5030       bool ignored;
5031       // This can return overflow, underflow, or inexact; we don't care.
5032       // FIXME need to be more flexible about rounding mode.
5033       (void)V.convert(EVTToAPFloatSemantics(VT),
5034                       APFloat::rmNearestTiesToEven, &ignored);
5035       return getConstantFP(V, DL, VT);
5036     }
5037     case ISD::FP_TO_SINT:
5038     case ISD::FP_TO_UINT: {
5039       bool ignored;
5040       APSInt IntVal(VT.getSizeInBits(), Opcode == ISD::FP_TO_UINT);
5041       // FIXME need to be more flexible about rounding mode.
5042       APFloat::opStatus s =
5043           V.convertToInteger(IntVal, APFloat::rmTowardZero, &ignored);
5044       if (s == APFloat::opInvalidOp) // inexact is OK, in fact usual
5045         break;
5046       return getConstant(IntVal, DL, VT);
5047     }
5048     case ISD::BITCAST:
5049       if (VT == MVT::i16 && C->getValueType(0) == MVT::f16)
5050         return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
5051       if (VT == MVT::i16 && C->getValueType(0) == MVT::bf16)
5052         return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
5053       if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
5054         return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
5055       if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
5056         return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
5057       break;
5058     case ISD::FP_TO_FP16: {
5059       bool Ignored;
5060       // This can return overflow, underflow, or inexact; we don't care.
5061       // FIXME need to be more flexible about rounding mode.
5062       (void)V.convert(APFloat::IEEEhalf(),
5063                       APFloat::rmNearestTiesToEven, &Ignored);
5064       return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
5065     }
5066     }
5067   }
5068 
5069   // Constant fold unary operations with a vector integer or float operand.
5070   switch (Opcode) {
5071   default:
5072     // FIXME: Entirely reasonable to perform folding of other unary
5073     // operations here as the need arises.
5074     break;
5075   case ISD::FNEG:
5076   case ISD::FABS:
5077   case ISD::FCEIL:
5078   case ISD::FTRUNC:
5079   case ISD::FFLOOR:
5080   case ISD::FP_EXTEND:
5081   case ISD::FP_TO_SINT:
5082   case ISD::FP_TO_UINT:
5083   case ISD::TRUNCATE:
5084   case ISD::ANY_EXTEND:
5085   case ISD::ZERO_EXTEND:
5086   case ISD::SIGN_EXTEND:
5087   case ISD::UINT_TO_FP:
5088   case ISD::SINT_TO_FP:
5089   case ISD::ABS:
5090   case ISD::BITREVERSE:
5091   case ISD::BSWAP:
5092   case ISD::CTLZ:
5093   case ISD::CTLZ_ZERO_UNDEF:
5094   case ISD::CTTZ:
5095   case ISD::CTTZ_ZERO_UNDEF:
5096   case ISD::CTPOP: {
5097     SDValue Ops = {Operand};
5098     if (SDValue Fold = FoldConstantArithmetic(Opcode, DL, VT, Ops))
5099       return Fold;
5100   }
5101   }
5102 
5103   unsigned OpOpcode = Operand.getNode()->getOpcode();
5104   switch (Opcode) {
5105   case ISD::STEP_VECTOR:
5106     assert(VT.isScalableVector() &&
5107            "STEP_VECTOR can only be used with scalable types");
5108     assert(OpOpcode == ISD::TargetConstant &&
5109            VT.getVectorElementType() == Operand.getValueType() &&
5110            "Unexpected step operand");
5111     break;
5112   case ISD::FREEZE:
5113     assert(VT == Operand.getValueType() && "Unexpected VT!");
5114     if (isGuaranteedNotToBeUndefOrPoison(Operand))
5115       return Operand;
5116     break;
5117   case ISD::TokenFactor:
5118   case ISD::MERGE_VALUES:
5119   case ISD::CONCAT_VECTORS:
5120     return Operand;         // Factor, merge or concat of one node?  No need.
5121   case ISD::BUILD_VECTOR: {
5122     // Attempt to simplify BUILD_VECTOR.
5123     SDValue Ops[] = {Operand};
5124     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
5125       return V;
5126     break;
5127   }
5128   case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node");
5129   case ISD::FP_EXTEND:
5130     assert(VT.isFloatingPoint() &&
5131            Operand.getValueType().isFloatingPoint() && "Invalid FP cast!");
5132     if (Operand.getValueType() == VT) return Operand;  // noop conversion.
5133     assert((!VT.isVector() ||
5134             VT.getVectorElementCount() ==
5135             Operand.getValueType().getVectorElementCount()) &&
5136            "Vector element count mismatch!");
5137     assert(Operand.getValueType().bitsLT(VT) &&
5138            "Invalid fpext node, dst < src!");
5139     if (Operand.isUndef())
5140       return getUNDEF(VT);
5141     break;
5142   case ISD::FP_TO_SINT:
5143   case ISD::FP_TO_UINT:
5144     if (Operand.isUndef())
5145       return getUNDEF(VT);
5146     break;
5147   case ISD::SINT_TO_FP:
5148   case ISD::UINT_TO_FP:
5149     // [us]itofp(undef) = 0, because the result value is bounded.
5150     if (Operand.isUndef())
5151       return getConstantFP(0.0, DL, VT);
5152     break;
5153   case ISD::SIGN_EXTEND:
5154     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
5155            "Invalid SIGN_EXTEND!");
5156     assert(VT.isVector() == Operand.getValueType().isVector() &&
5157            "SIGN_EXTEND result type type should be vector iff the operand "
5158            "type is vector!");
5159     if (Operand.getValueType() == VT) return Operand;   // noop extension
5160     assert((!VT.isVector() ||
5161             VT.getVectorElementCount() ==
5162                 Operand.getValueType().getVectorElementCount()) &&
5163            "Vector element count mismatch!");
5164     assert(Operand.getValueType().bitsLT(VT) &&
5165            "Invalid sext node, dst < src!");
5166     if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
5167       return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
5168     if (OpOpcode == ISD::UNDEF)
5169       // sext(undef) = 0, because the top bits will all be the same.
5170       return getConstant(0, DL, VT);
5171     break;
5172   case ISD::ZERO_EXTEND:
5173     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
5174            "Invalid ZERO_EXTEND!");
5175     assert(VT.isVector() == Operand.getValueType().isVector() &&
5176            "ZERO_EXTEND result type type should be vector iff the operand "
5177            "type is vector!");
5178     if (Operand.getValueType() == VT) return Operand;   // noop extension
5179     assert((!VT.isVector() ||
5180             VT.getVectorElementCount() ==
5181                 Operand.getValueType().getVectorElementCount()) &&
5182            "Vector element count mismatch!");
5183     assert(Operand.getValueType().bitsLT(VT) &&
5184            "Invalid zext node, dst < src!");
5185     if (OpOpcode == ISD::ZERO_EXTEND)   // (zext (zext x)) -> (zext x)
5186       return getNode(ISD::ZERO_EXTEND, DL, VT, Operand.getOperand(0));
5187     if (OpOpcode == ISD::UNDEF)
5188       // zext(undef) = 0, because the top bits will be zero.
5189       return getConstant(0, DL, VT);
5190     break;
5191   case ISD::ANY_EXTEND:
5192     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
5193            "Invalid ANY_EXTEND!");
5194     assert(VT.isVector() == Operand.getValueType().isVector() &&
5195            "ANY_EXTEND result type type should be vector iff the operand "
5196            "type is vector!");
5197     if (Operand.getValueType() == VT) return Operand;   // noop extension
5198     assert((!VT.isVector() ||
5199             VT.getVectorElementCount() ==
5200                 Operand.getValueType().getVectorElementCount()) &&
5201            "Vector element count mismatch!");
5202     assert(Operand.getValueType().bitsLT(VT) &&
5203            "Invalid anyext node, dst < src!");
5204 
5205     if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
5206         OpOpcode == ISD::ANY_EXTEND)
5207       // (ext (zext x)) -> (zext x)  and  (ext (sext x)) -> (sext x)
5208       return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
5209     if (OpOpcode == ISD::UNDEF)
5210       return getUNDEF(VT);
5211 
5212     // (ext (trunc x)) -> x
5213     if (OpOpcode == ISD::TRUNCATE) {
5214       SDValue OpOp = Operand.getOperand(0);
5215       if (OpOp.getValueType() == VT) {
5216         transferDbgValues(Operand, OpOp);
5217         return OpOp;
5218       }
5219     }
5220     break;
5221   case ISD::TRUNCATE:
5222     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
5223            "Invalid TRUNCATE!");
5224     assert(VT.isVector() == Operand.getValueType().isVector() &&
5225            "TRUNCATE result type type should be vector iff the operand "
5226            "type is vector!");
5227     if (Operand.getValueType() == VT) return Operand;   // noop truncate
5228     assert((!VT.isVector() ||
5229             VT.getVectorElementCount() ==
5230                 Operand.getValueType().getVectorElementCount()) &&
5231            "Vector element count mismatch!");
5232     assert(Operand.getValueType().bitsGT(VT) &&
5233            "Invalid truncate node, src < dst!");
5234     if (OpOpcode == ISD::TRUNCATE)
5235       return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0));
5236     if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
5237         OpOpcode == ISD::ANY_EXTEND) {
5238       // If the source is smaller than the dest, we still need an extend.
5239       if (Operand.getOperand(0).getValueType().getScalarType()
5240             .bitsLT(VT.getScalarType()))
5241         return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
5242       if (Operand.getOperand(0).getValueType().bitsGT(VT))
5243         return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0));
5244       return Operand.getOperand(0);
5245     }
5246     if (OpOpcode == ISD::UNDEF)
5247       return getUNDEF(VT);
5248     if (OpOpcode == ISD::VSCALE && !NewNodesMustHaveLegalTypes)
5249       return getVScale(DL, VT, Operand.getConstantOperandAPInt(0));
5250     break;
5251   case ISD::ANY_EXTEND_VECTOR_INREG:
5252   case ISD::ZERO_EXTEND_VECTOR_INREG:
5253   case ISD::SIGN_EXTEND_VECTOR_INREG:
5254     assert(VT.isVector() && "This DAG node is restricted to vector types.");
5255     assert(Operand.getValueType().bitsLE(VT) &&
5256            "The input must be the same size or smaller than the result.");
5257     assert(VT.getVectorMinNumElements() <
5258                Operand.getValueType().getVectorMinNumElements() &&
5259            "The destination vector type must have fewer lanes than the input.");
5260     break;
5261   case ISD::ABS:
5262     assert(VT.isInteger() && VT == Operand.getValueType() &&
5263            "Invalid ABS!");
5264     if (OpOpcode == ISD::UNDEF)
5265       return getConstant(0, DL, VT);
5266     break;
5267   case ISD::BSWAP:
5268     assert(VT.isInteger() && VT == Operand.getValueType() &&
5269            "Invalid BSWAP!");
5270     assert((VT.getScalarSizeInBits() % 16 == 0) &&
5271            "BSWAP types must be a multiple of 16 bits!");
5272     if (OpOpcode == ISD::UNDEF)
5273       return getUNDEF(VT);
5274     // bswap(bswap(X)) -> X.
5275     if (OpOpcode == ISD::BSWAP)
5276       return Operand.getOperand(0);
5277     break;
5278   case ISD::BITREVERSE:
5279     assert(VT.isInteger() && VT == Operand.getValueType() &&
5280            "Invalid BITREVERSE!");
5281     if (OpOpcode == ISD::UNDEF)
5282       return getUNDEF(VT);
5283     break;
5284   case ISD::BITCAST:
5285     assert(VT.getSizeInBits() == Operand.getValueSizeInBits() &&
5286            "Cannot BITCAST between types of different sizes!");
5287     if (VT == Operand.getValueType()) return Operand;  // noop conversion.
5288     if (OpOpcode == ISD::BITCAST)  // bitconv(bitconv(x)) -> bitconv(x)
5289       return getNode(ISD::BITCAST, DL, VT, Operand.getOperand(0));
5290     if (OpOpcode == ISD::UNDEF)
5291       return getUNDEF(VT);
5292     break;
5293   case ISD::SCALAR_TO_VECTOR:
5294     assert(VT.isVector() && !Operand.getValueType().isVector() &&
5295            (VT.getVectorElementType() == Operand.getValueType() ||
5296             (VT.getVectorElementType().isInteger() &&
5297              Operand.getValueType().isInteger() &&
5298              VT.getVectorElementType().bitsLE(Operand.getValueType()))) &&
5299            "Illegal SCALAR_TO_VECTOR node!");
5300     if (OpOpcode == ISD::UNDEF)
5301       return getUNDEF(VT);
5302     // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
5303     if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
5304         isa<ConstantSDNode>(Operand.getOperand(1)) &&
5305         Operand.getConstantOperandVal(1) == 0 &&
5306         Operand.getOperand(0).getValueType() == VT)
5307       return Operand.getOperand(0);
5308     break;
5309   case ISD::FNEG:
5310     // Negation of an unknown bag of bits is still completely undefined.
5311     if (OpOpcode == ISD::UNDEF)
5312       return getUNDEF(VT);
5313 
5314     if (OpOpcode == ISD::FNEG)  // --X -> X
5315       return Operand.getOperand(0);
5316     break;
5317   case ISD::FABS:
5318     if (OpOpcode == ISD::FNEG)  // abs(-X) -> abs(X)
5319       return getNode(ISD::FABS, DL, VT, Operand.getOperand(0));
5320     break;
5321   case ISD::VSCALE:
5322     assert(VT == Operand.getValueType() && "Unexpected VT!");
5323     break;
5324   case ISD::CTPOP:
5325     if (Operand.getValueType().getScalarType() == MVT::i1)
5326       return Operand;
5327     break;
5328   case ISD::CTLZ:
5329   case ISD::CTTZ:
5330     if (Operand.getValueType().getScalarType() == MVT::i1)
5331       return getNOT(DL, Operand, Operand.getValueType());
5332     break;
5333   case ISD::VECREDUCE_ADD:
5334     if (Operand.getValueType().getScalarType() == MVT::i1)
5335       return getNode(ISD::VECREDUCE_XOR, DL, VT, Operand);
5336     break;
5337   case ISD::VECREDUCE_SMIN:
5338   case ISD::VECREDUCE_UMAX:
5339     if (Operand.getValueType().getScalarType() == MVT::i1)
5340       return getNode(ISD::VECREDUCE_OR, DL, VT, Operand);
5341     break;
5342   case ISD::VECREDUCE_SMAX:
5343   case ISD::VECREDUCE_UMIN:
5344     if (Operand.getValueType().getScalarType() == MVT::i1)
5345       return getNode(ISD::VECREDUCE_AND, DL, VT, Operand);
5346     break;
5347   }
5348 
5349   SDNode *N;
5350   SDVTList VTs = getVTList(VT);
5351   SDValue Ops[] = {Operand};
5352   if (VT != MVT::Glue) { // Don't CSE flag producing nodes
5353     FoldingSetNodeID ID;
5354     AddNodeIDNode(ID, Opcode, VTs, Ops);
5355     void *IP = nullptr;
5356     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
5357       E->intersectFlagsWith(Flags);
5358       return SDValue(E, 0);
5359     }
5360 
5361     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5362     N->setFlags(Flags);
5363     createOperands(N, Ops);
5364     CSEMap.InsertNode(N, IP);
5365   } else {
5366     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5367     createOperands(N, Ops);
5368   }
5369 
5370   InsertNode(N);
5371   SDValue V = SDValue(N, 0);
5372   NewSDValueDbgMsg(V, "Creating new node: ", this);
5373   return V;
5374 }
5375 
5376 static llvm::Optional<APInt> FoldValue(unsigned Opcode, const APInt &C1,
5377                                        const APInt &C2) {
5378   switch (Opcode) {
5379   case ISD::ADD:  return C1 + C2;
5380   case ISD::SUB:  return C1 - C2;
5381   case ISD::MUL:  return C1 * C2;
5382   case ISD::AND:  return C1 & C2;
5383   case ISD::OR:   return C1 | C2;
5384   case ISD::XOR:  return C1 ^ C2;
5385   case ISD::SHL:  return C1 << C2;
5386   case ISD::SRL:  return C1.lshr(C2);
5387   case ISD::SRA:  return C1.ashr(C2);
5388   case ISD::ROTL: return C1.rotl(C2);
5389   case ISD::ROTR: return C1.rotr(C2);
5390   case ISD::SMIN: return C1.sle(C2) ? C1 : C2;
5391   case ISD::SMAX: return C1.sge(C2) ? C1 : C2;
5392   case ISD::UMIN: return C1.ule(C2) ? C1 : C2;
5393   case ISD::UMAX: return C1.uge(C2) ? C1 : C2;
5394   case ISD::SADDSAT: return C1.sadd_sat(C2);
5395   case ISD::UADDSAT: return C1.uadd_sat(C2);
5396   case ISD::SSUBSAT: return C1.ssub_sat(C2);
5397   case ISD::USUBSAT: return C1.usub_sat(C2);
5398   case ISD::SSHLSAT: return C1.sshl_sat(C2);
5399   case ISD::USHLSAT: return C1.ushl_sat(C2);
5400   case ISD::UDIV:
5401     if (!C2.getBoolValue())
5402       break;
5403     return C1.udiv(C2);
5404   case ISD::UREM:
5405     if (!C2.getBoolValue())
5406       break;
5407     return C1.urem(C2);
5408   case ISD::SDIV:
5409     if (!C2.getBoolValue())
5410       break;
5411     return C1.sdiv(C2);
5412   case ISD::SREM:
5413     if (!C2.getBoolValue())
5414       break;
5415     return C1.srem(C2);
5416   case ISD::MULHS: {
5417     unsigned FullWidth = C1.getBitWidth() * 2;
5418     APInt C1Ext = C1.sext(FullWidth);
5419     APInt C2Ext = C2.sext(FullWidth);
5420     return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth());
5421   }
5422   case ISD::MULHU: {
5423     unsigned FullWidth = C1.getBitWidth() * 2;
5424     APInt C1Ext = C1.zext(FullWidth);
5425     APInt C2Ext = C2.zext(FullWidth);
5426     return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth());
5427   }
5428   case ISD::AVGFLOORS: {
5429     unsigned FullWidth = C1.getBitWidth() + 1;
5430     APInt C1Ext = C1.sext(FullWidth);
5431     APInt C2Ext = C2.sext(FullWidth);
5432     return (C1Ext + C2Ext).extractBits(C1.getBitWidth(), 1);
5433   }
5434   case ISD::AVGFLOORU: {
5435     unsigned FullWidth = C1.getBitWidth() + 1;
5436     APInt C1Ext = C1.zext(FullWidth);
5437     APInt C2Ext = C2.zext(FullWidth);
5438     return (C1Ext + C2Ext).extractBits(C1.getBitWidth(), 1);
5439   }
5440   case ISD::AVGCEILS: {
5441     unsigned FullWidth = C1.getBitWidth() + 1;
5442     APInt C1Ext = C1.sext(FullWidth);
5443     APInt C2Ext = C2.sext(FullWidth);
5444     return (C1Ext + C2Ext + 1).extractBits(C1.getBitWidth(), 1);
5445   }
5446   case ISD::AVGCEILU: {
5447     unsigned FullWidth = C1.getBitWidth() + 1;
5448     APInt C1Ext = C1.zext(FullWidth);
5449     APInt C2Ext = C2.zext(FullWidth);
5450     return (C1Ext + C2Ext + 1).extractBits(C1.getBitWidth(), 1);
5451   }
5452   }
5453   return llvm::None;
5454 }
5455 
5456 SDValue SelectionDAG::FoldSymbolOffset(unsigned Opcode, EVT VT,
5457                                        const GlobalAddressSDNode *GA,
5458                                        const SDNode *N2) {
5459   if (GA->getOpcode() != ISD::GlobalAddress)
5460     return SDValue();
5461   if (!TLI->isOffsetFoldingLegal(GA))
5462     return SDValue();
5463   auto *C2 = dyn_cast<ConstantSDNode>(N2);
5464   if (!C2)
5465     return SDValue();
5466   int64_t Offset = C2->getSExtValue();
5467   switch (Opcode) {
5468   case ISD::ADD: break;
5469   case ISD::SUB: Offset = -uint64_t(Offset); break;
5470   default: return SDValue();
5471   }
5472   return getGlobalAddress(GA->getGlobal(), SDLoc(C2), VT,
5473                           GA->getOffset() + uint64_t(Offset));
5474 }
5475 
5476 bool SelectionDAG::isUndef(unsigned Opcode, ArrayRef<SDValue> Ops) {
5477   switch (Opcode) {
5478   case ISD::SDIV:
5479   case ISD::UDIV:
5480   case ISD::SREM:
5481   case ISD::UREM: {
5482     // If a divisor is zero/undef or any element of a divisor vector is
5483     // zero/undef, the whole op is undef.
5484     assert(Ops.size() == 2 && "Div/rem should have 2 operands");
5485     SDValue Divisor = Ops[1];
5486     if (Divisor.isUndef() || isNullConstant(Divisor))
5487       return true;
5488 
5489     return ISD::isBuildVectorOfConstantSDNodes(Divisor.getNode()) &&
5490            llvm::any_of(Divisor->op_values(),
5491                         [](SDValue V) { return V.isUndef() ||
5492                                         isNullConstant(V); });
5493     // TODO: Handle signed overflow.
5494   }
5495   // TODO: Handle oversized shifts.
5496   default:
5497     return false;
5498   }
5499 }
5500 
5501 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL,
5502                                              EVT VT, ArrayRef<SDValue> Ops) {
5503   // If the opcode is a target-specific ISD node, there's nothing we can
5504   // do here and the operand rules may not line up with the below, so
5505   // bail early.
5506   // We can't create a scalar CONCAT_VECTORS so skip it. It will break
5507   // for concats involving SPLAT_VECTOR. Concats of BUILD_VECTORS are handled by
5508   // foldCONCAT_VECTORS in getNode before this is called.
5509   if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::CONCAT_VECTORS)
5510     return SDValue();
5511 
5512   unsigned NumOps = Ops.size();
5513   if (NumOps == 0)
5514     return SDValue();
5515 
5516   if (isUndef(Opcode, Ops))
5517     return getUNDEF(VT);
5518 
5519   // Handle binops special cases.
5520   if (NumOps == 2) {
5521     if (SDValue CFP = foldConstantFPMath(Opcode, DL, VT, Ops[0], Ops[1]))
5522       return CFP;
5523 
5524     if (auto *C1 = dyn_cast<ConstantSDNode>(Ops[0])) {
5525       if (auto *C2 = dyn_cast<ConstantSDNode>(Ops[1])) {
5526         if (C1->isOpaque() || C2->isOpaque())
5527           return SDValue();
5528 
5529         Optional<APInt> FoldAttempt =
5530             FoldValue(Opcode, C1->getAPIntValue(), C2->getAPIntValue());
5531         if (!FoldAttempt)
5532           return SDValue();
5533 
5534         SDValue Folded = getConstant(FoldAttempt.getValue(), DL, VT);
5535         assert((!Folded || !VT.isVector()) &&
5536                "Can't fold vectors ops with scalar operands");
5537         return Folded;
5538       }
5539     }
5540 
5541     // fold (add Sym, c) -> Sym+c
5542     if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ops[0]))
5543       return FoldSymbolOffset(Opcode, VT, GA, Ops[1].getNode());
5544     if (TLI->isCommutativeBinOp(Opcode))
5545       if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ops[1]))
5546         return FoldSymbolOffset(Opcode, VT, GA, Ops[0].getNode());
5547   }
5548 
5549   // This is for vector folding only from here on.
5550   if (!VT.isVector())
5551     return SDValue();
5552 
5553   ElementCount NumElts = VT.getVectorElementCount();
5554 
5555   // See if we can fold through bitcasted integer ops.
5556   // TODO: Can we handle undef elements?
5557   if (NumOps == 2 && VT.isFixedLengthVector() && VT.isInteger() &&
5558       Ops[0].getValueType() == VT && Ops[1].getValueType() == VT &&
5559       Ops[0].getOpcode() == ISD::BITCAST &&
5560       Ops[1].getOpcode() == ISD::BITCAST) {
5561     SDValue N1 = peekThroughBitcasts(Ops[0]);
5562     SDValue N2 = peekThroughBitcasts(Ops[1]);
5563     auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
5564     auto *BV2 = dyn_cast<BuildVectorSDNode>(N2);
5565     EVT BVVT = N1.getValueType();
5566     if (BV1 && BV2 && BVVT.isInteger() && BVVT == N2.getValueType()) {
5567       bool IsLE = getDataLayout().isLittleEndian();
5568       unsigned EltBits = VT.getScalarSizeInBits();
5569       SmallVector<APInt> RawBits1, RawBits2;
5570       BitVector UndefElts1, UndefElts2;
5571       if (BV1->getConstantRawBits(IsLE, EltBits, RawBits1, UndefElts1) &&
5572           BV2->getConstantRawBits(IsLE, EltBits, RawBits2, UndefElts2) &&
5573           UndefElts1.none() && UndefElts2.none()) {
5574         SmallVector<APInt> RawBits;
5575         for (unsigned I = 0, E = NumElts.getFixedValue(); I != E; ++I) {
5576           Optional<APInt> Fold = FoldValue(Opcode, RawBits1[I], RawBits2[I]);
5577           if (!Fold)
5578             break;
5579           RawBits.push_back(Fold.getValue());
5580         }
5581         if (RawBits.size() == NumElts.getFixedValue()) {
5582           // We have constant folded, but we need to cast this again back to
5583           // the original (possibly legalized) type.
5584           SmallVector<APInt> DstBits;
5585           BitVector DstUndefs;
5586           BuildVectorSDNode::recastRawBits(IsLE, BVVT.getScalarSizeInBits(),
5587                                            DstBits, RawBits, DstUndefs,
5588                                            BitVector(RawBits.size(), false));
5589           EVT BVEltVT = BV1->getOperand(0).getValueType();
5590           unsigned BVEltBits = BVEltVT.getSizeInBits();
5591           SmallVector<SDValue> Ops(DstBits.size(), getUNDEF(BVEltVT));
5592           for (unsigned I = 0, E = DstBits.size(); I != E; ++I) {
5593             if (DstUndefs[I])
5594               continue;
5595             Ops[I] = getConstant(DstBits[I].sext(BVEltBits), DL, BVEltVT);
5596           }
5597           return getBitcast(VT, getBuildVector(BVVT, DL, Ops));
5598         }
5599       }
5600     }
5601   }
5602 
5603   // Fold (mul step_vector(C0), C1) to (step_vector(C0 * C1)).
5604   //      (shl step_vector(C0), C1) -> (step_vector(C0 << C1))
5605   if ((Opcode == ISD::MUL || Opcode == ISD::SHL) &&
5606       Ops[0].getOpcode() == ISD::STEP_VECTOR) {
5607     APInt RHSVal;
5608     if (ISD::isConstantSplatVector(Ops[1].getNode(), RHSVal)) {
5609       APInt NewStep = Opcode == ISD::MUL
5610                           ? Ops[0].getConstantOperandAPInt(0) * RHSVal
5611                           : Ops[0].getConstantOperandAPInt(0) << RHSVal;
5612       return getStepVector(DL, VT, NewStep);
5613     }
5614   }
5615 
5616   auto IsScalarOrSameVectorSize = [NumElts](const SDValue &Op) {
5617     return !Op.getValueType().isVector() ||
5618            Op.getValueType().getVectorElementCount() == NumElts;
5619   };
5620 
5621   auto IsBuildVectorSplatVectorOrUndef = [](const SDValue &Op) {
5622     return Op.isUndef() || Op.getOpcode() == ISD::CONDCODE ||
5623            Op.getOpcode() == ISD::BUILD_VECTOR ||
5624            Op.getOpcode() == ISD::SPLAT_VECTOR;
5625   };
5626 
5627   // All operands must be vector types with the same number of elements as
5628   // the result type and must be either UNDEF or a build/splat vector
5629   // or UNDEF scalars.
5630   if (!llvm::all_of(Ops, IsBuildVectorSplatVectorOrUndef) ||
5631       !llvm::all_of(Ops, IsScalarOrSameVectorSize))
5632     return SDValue();
5633 
5634   // If we are comparing vectors, then the result needs to be a i1 boolean that
5635   // is then extended back to the legal result type depending on how booleans
5636   // are represented.
5637   EVT SVT = (Opcode == ISD::SETCC ? MVT::i1 : VT.getScalarType());
5638   ISD::NodeType ExtendCode =
5639       (Opcode == ISD::SETCC && SVT != VT.getScalarType())
5640           ? TargetLowering::getExtendForContent(TLI->getBooleanContents(VT))
5641           : ISD::SIGN_EXTEND;
5642 
5643   // Find legal integer scalar type for constant promotion and
5644   // ensure that its scalar size is at least as large as source.
5645   EVT LegalSVT = VT.getScalarType();
5646   if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
5647     LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
5648     if (LegalSVT.bitsLT(VT.getScalarType()))
5649       return SDValue();
5650   }
5651 
5652   // For scalable vector types we know we're dealing with SPLAT_VECTORs. We
5653   // only have one operand to check. For fixed-length vector types we may have
5654   // a combination of BUILD_VECTOR and SPLAT_VECTOR.
5655   unsigned NumVectorElts = NumElts.isScalable() ? 1 : NumElts.getFixedValue();
5656 
5657   // Constant fold each scalar lane separately.
5658   SmallVector<SDValue, 4> ScalarResults;
5659   for (unsigned I = 0; I != NumVectorElts; I++) {
5660     SmallVector<SDValue, 4> ScalarOps;
5661     for (SDValue Op : Ops) {
5662       EVT InSVT = Op.getValueType().getScalarType();
5663       if (Op.getOpcode() != ISD::BUILD_VECTOR &&
5664           Op.getOpcode() != ISD::SPLAT_VECTOR) {
5665         if (Op.isUndef())
5666           ScalarOps.push_back(getUNDEF(InSVT));
5667         else
5668           ScalarOps.push_back(Op);
5669         continue;
5670       }
5671 
5672       SDValue ScalarOp =
5673           Op.getOperand(Op.getOpcode() == ISD::SPLAT_VECTOR ? 0 : I);
5674       EVT ScalarVT = ScalarOp.getValueType();
5675 
5676       // Build vector (integer) scalar operands may need implicit
5677       // truncation - do this before constant folding.
5678       if (ScalarVT.isInteger() && ScalarVT.bitsGT(InSVT)) {
5679         // Don't create illegally-typed nodes unless they're constants or undef
5680         // - if we fail to constant fold we can't guarantee the (dead) nodes
5681         // we're creating will be cleaned up before being visited for
5682         // legalization.
5683         if (NewNodesMustHaveLegalTypes && !ScalarOp.isUndef() &&
5684             !isa<ConstantSDNode>(ScalarOp) &&
5685             TLI->getTypeAction(*getContext(), InSVT) !=
5686                 TargetLowering::TypeLegal)
5687           return SDValue();
5688         ScalarOp = getNode(ISD::TRUNCATE, DL, InSVT, ScalarOp);
5689       }
5690 
5691       ScalarOps.push_back(ScalarOp);
5692     }
5693 
5694     // Constant fold the scalar operands.
5695     SDValue ScalarResult = getNode(Opcode, DL, SVT, ScalarOps);
5696 
5697     // Legalize the (integer) scalar constant if necessary.
5698     if (LegalSVT != SVT)
5699       ScalarResult = getNode(ExtendCode, DL, LegalSVT, ScalarResult);
5700 
5701     // Scalar folding only succeeded if the result is a constant or UNDEF.
5702     if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant &&
5703         ScalarResult.getOpcode() != ISD::ConstantFP)
5704       return SDValue();
5705     ScalarResults.push_back(ScalarResult);
5706   }
5707 
5708   SDValue V = NumElts.isScalable() ? getSplatVector(VT, DL, ScalarResults[0])
5709                                    : getBuildVector(VT, DL, ScalarResults);
5710   NewSDValueDbgMsg(V, "New node fold constant vector: ", this);
5711   return V;
5712 }
5713 
5714 SDValue SelectionDAG::foldConstantFPMath(unsigned Opcode, const SDLoc &DL,
5715                                          EVT VT, SDValue N1, SDValue N2) {
5716   // TODO: We don't do any constant folding for strict FP opcodes here, but we
5717   //       should. That will require dealing with a potentially non-default
5718   //       rounding mode, checking the "opStatus" return value from the APFloat
5719   //       math calculations, and possibly other variations.
5720   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1, /*AllowUndefs*/ false);
5721   ConstantFPSDNode *N2CFP = isConstOrConstSplatFP(N2, /*AllowUndefs*/ false);
5722   if (N1CFP && N2CFP) {
5723     APFloat C1 = N1CFP->getValueAPF(); // make copy
5724     const APFloat &C2 = N2CFP->getValueAPF();
5725     switch (Opcode) {
5726     case ISD::FADD:
5727       C1.add(C2, APFloat::rmNearestTiesToEven);
5728       return getConstantFP(C1, DL, VT);
5729     case ISD::FSUB:
5730       C1.subtract(C2, APFloat::rmNearestTiesToEven);
5731       return getConstantFP(C1, DL, VT);
5732     case ISD::FMUL:
5733       C1.multiply(C2, APFloat::rmNearestTiesToEven);
5734       return getConstantFP(C1, DL, VT);
5735     case ISD::FDIV:
5736       C1.divide(C2, APFloat::rmNearestTiesToEven);
5737       return getConstantFP(C1, DL, VT);
5738     case ISD::FREM:
5739       C1.mod(C2);
5740       return getConstantFP(C1, DL, VT);
5741     case ISD::FCOPYSIGN:
5742       C1.copySign(C2);
5743       return getConstantFP(C1, DL, VT);
5744     case ISD::FMINNUM:
5745       return getConstantFP(minnum(C1, C2), DL, VT);
5746     case ISD::FMAXNUM:
5747       return getConstantFP(maxnum(C1, C2), DL, VT);
5748     case ISD::FMINIMUM:
5749       return getConstantFP(minimum(C1, C2), DL, VT);
5750     case ISD::FMAXIMUM:
5751       return getConstantFP(maximum(C1, C2), DL, VT);
5752     default: break;
5753     }
5754   }
5755   if (N1CFP && Opcode == ISD::FP_ROUND) {
5756     APFloat C1 = N1CFP->getValueAPF();    // make copy
5757     bool Unused;
5758     // This can return overflow, underflow, or inexact; we don't care.
5759     // FIXME need to be more flexible about rounding mode.
5760     (void) C1.convert(EVTToAPFloatSemantics(VT), APFloat::rmNearestTiesToEven,
5761                       &Unused);
5762     return getConstantFP(C1, DL, VT);
5763   }
5764 
5765   switch (Opcode) {
5766   case ISD::FSUB:
5767     // -0.0 - undef --> undef (consistent with "fneg undef")
5768     if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1, /*AllowUndefs*/ true))
5769       if (N1C && N1C->getValueAPF().isNegZero() && N2.isUndef())
5770         return getUNDEF(VT);
5771     LLVM_FALLTHROUGH;
5772 
5773   case ISD::FADD:
5774   case ISD::FMUL:
5775   case ISD::FDIV:
5776   case ISD::FREM:
5777     // If both operands are undef, the result is undef. If 1 operand is undef,
5778     // the result is NaN. This should match the behavior of the IR optimizer.
5779     if (N1.isUndef() && N2.isUndef())
5780       return getUNDEF(VT);
5781     if (N1.isUndef() || N2.isUndef())
5782       return getConstantFP(APFloat::getNaN(EVTToAPFloatSemantics(VT)), DL, VT);
5783   }
5784   return SDValue();
5785 }
5786 
5787 SDValue SelectionDAG::getAssertAlign(const SDLoc &DL, SDValue Val, Align A) {
5788   assert(Val.getValueType().isInteger() && "Invalid AssertAlign!");
5789 
5790   // There's no need to assert on a byte-aligned pointer. All pointers are at
5791   // least byte aligned.
5792   if (A == Align(1))
5793     return Val;
5794 
5795   FoldingSetNodeID ID;
5796   AddNodeIDNode(ID, ISD::AssertAlign, getVTList(Val.getValueType()), {Val});
5797   ID.AddInteger(A.value());
5798 
5799   void *IP = nullptr;
5800   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
5801     return SDValue(E, 0);
5802 
5803   auto *N = newSDNode<AssertAlignSDNode>(DL.getIROrder(), DL.getDebugLoc(),
5804                                          Val.getValueType(), A);
5805   createOperands(N, {Val});
5806 
5807   CSEMap.InsertNode(N, IP);
5808   InsertNode(N);
5809 
5810   SDValue V(N, 0);
5811   NewSDValueDbgMsg(V, "Creating new node: ", this);
5812   return V;
5813 }
5814 
5815 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5816                               SDValue N1, SDValue N2) {
5817   SDNodeFlags Flags;
5818   if (Inserter)
5819     Flags = Inserter->getFlags();
5820   return getNode(Opcode, DL, VT, N1, N2, Flags);
5821 }
5822 
5823 void SelectionDAG::canonicalizeCommutativeBinop(unsigned Opcode, SDValue &N1,
5824                                                 SDValue &N2) const {
5825   if (!TLI->isCommutativeBinOp(Opcode))
5826     return;
5827 
5828   // Canonicalize:
5829   //   binop(const, nonconst) -> binop(nonconst, const)
5830   bool IsN1C = isConstantIntBuildVectorOrConstantInt(N1);
5831   bool IsN2C = isConstantIntBuildVectorOrConstantInt(N2);
5832   bool IsN1CFP = isConstantFPBuildVectorOrConstantFP(N1);
5833   bool IsN2CFP = isConstantFPBuildVectorOrConstantFP(N2);
5834   if ((IsN1C && !IsN2C) || (IsN1CFP && !IsN2CFP))
5835     std::swap(N1, N2);
5836 
5837   // Canonicalize:
5838   //  binop(splat(x), step_vector) -> binop(step_vector, splat(x))
5839   else if (N1.getOpcode() == ISD::SPLAT_VECTOR &&
5840            N2.getOpcode() == ISD::STEP_VECTOR)
5841     std::swap(N1, N2);
5842 }
5843 
5844 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5845                               SDValue N1, SDValue N2, const SDNodeFlags Flags) {
5846   assert(N1.getOpcode() != ISD::DELETED_NODE &&
5847          N2.getOpcode() != ISD::DELETED_NODE &&
5848          "Operand is DELETED_NODE!");
5849 
5850   canonicalizeCommutativeBinop(Opcode, N1, N2);
5851 
5852   auto *N1C = dyn_cast<ConstantSDNode>(N1);
5853   auto *N2C = dyn_cast<ConstantSDNode>(N2);
5854 
5855   // Don't allow undefs in vector splats - we might be returning N2 when folding
5856   // to zero etc.
5857   ConstantSDNode *N2CV =
5858       isConstOrConstSplat(N2, /*AllowUndefs*/ false, /*AllowTruncation*/ true);
5859 
5860   switch (Opcode) {
5861   default: break;
5862   case ISD::TokenFactor:
5863     assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
5864            N2.getValueType() == MVT::Other && "Invalid token factor!");
5865     // Fold trivial token factors.
5866     if (N1.getOpcode() == ISD::EntryToken) return N2;
5867     if (N2.getOpcode() == ISD::EntryToken) return N1;
5868     if (N1 == N2) return N1;
5869     break;
5870   case ISD::BUILD_VECTOR: {
5871     // Attempt to simplify BUILD_VECTOR.
5872     SDValue Ops[] = {N1, N2};
5873     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
5874       return V;
5875     break;
5876   }
5877   case ISD::CONCAT_VECTORS: {
5878     SDValue Ops[] = {N1, N2};
5879     if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
5880       return V;
5881     break;
5882   }
5883   case ISD::AND:
5884     assert(VT.isInteger() && "This operator does not apply to FP types!");
5885     assert(N1.getValueType() == N2.getValueType() &&
5886            N1.getValueType() == VT && "Binary operator types must match!");
5887     // (X & 0) -> 0.  This commonly occurs when legalizing i64 values, so it's
5888     // worth handling here.
5889     if (N2CV && N2CV->isZero())
5890       return N2;
5891     if (N2CV && N2CV->isAllOnes()) // X & -1 -> X
5892       return N1;
5893     break;
5894   case ISD::OR:
5895   case ISD::XOR:
5896   case ISD::ADD:
5897   case ISD::SUB:
5898     assert(VT.isInteger() && "This operator does not apply to FP types!");
5899     assert(N1.getValueType() == N2.getValueType() &&
5900            N1.getValueType() == VT && "Binary operator types must match!");
5901     // (X ^|+- 0) -> X.  This commonly occurs when legalizing i64 values, so
5902     // it's worth handling here.
5903     if (N2CV && N2CV->isZero())
5904       return N1;
5905     if ((Opcode == ISD::ADD || Opcode == ISD::SUB) && VT.isVector() &&
5906         VT.getVectorElementType() == MVT::i1)
5907       return getNode(ISD::XOR, DL, VT, N1, N2);
5908     break;
5909   case ISD::MUL:
5910     assert(VT.isInteger() && "This operator does not apply to FP types!");
5911     assert(N1.getValueType() == N2.getValueType() &&
5912            N1.getValueType() == VT && "Binary operator types must match!");
5913     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
5914       return getNode(ISD::AND, DL, VT, N1, N2);
5915     if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
5916       const APInt &MulImm = N1->getConstantOperandAPInt(0);
5917       const APInt &N2CImm = N2C->getAPIntValue();
5918       return getVScale(DL, VT, MulImm * N2CImm);
5919     }
5920     break;
5921   case ISD::UDIV:
5922   case ISD::UREM:
5923   case ISD::MULHU:
5924   case ISD::MULHS:
5925   case ISD::SDIV:
5926   case ISD::SREM:
5927   case ISD::SADDSAT:
5928   case ISD::SSUBSAT:
5929   case ISD::UADDSAT:
5930   case ISD::USUBSAT:
5931     assert(VT.isInteger() && "This operator does not apply to FP types!");
5932     assert(N1.getValueType() == N2.getValueType() &&
5933            N1.getValueType() == VT && "Binary operator types must match!");
5934     if (VT.isVector() && VT.getVectorElementType() == MVT::i1) {
5935       // fold (add_sat x, y) -> (or x, y) for bool types.
5936       if (Opcode == ISD::SADDSAT || Opcode == ISD::UADDSAT)
5937         return getNode(ISD::OR, DL, VT, N1, N2);
5938       // fold (sub_sat x, y) -> (and x, ~y) for bool types.
5939       if (Opcode == ISD::SSUBSAT || Opcode == ISD::USUBSAT)
5940         return getNode(ISD::AND, DL, VT, N1, getNOT(DL, N2, VT));
5941     }
5942     break;
5943   case ISD::SMIN:
5944   case ISD::UMAX:
5945     assert(VT.isInteger() && "This operator does not apply to FP types!");
5946     assert(N1.getValueType() == N2.getValueType() &&
5947            N1.getValueType() == VT && "Binary operator types must match!");
5948     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
5949       return getNode(ISD::OR, DL, VT, N1, N2);
5950     break;
5951   case ISD::SMAX:
5952   case ISD::UMIN:
5953     assert(VT.isInteger() && "This operator does not apply to FP types!");
5954     assert(N1.getValueType() == N2.getValueType() &&
5955            N1.getValueType() == VT && "Binary operator types must match!");
5956     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
5957       return getNode(ISD::AND, DL, VT, N1, N2);
5958     break;
5959   case ISD::FADD:
5960   case ISD::FSUB:
5961   case ISD::FMUL:
5962   case ISD::FDIV:
5963   case ISD::FREM:
5964     assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
5965     assert(N1.getValueType() == N2.getValueType() &&
5966            N1.getValueType() == VT && "Binary operator types must match!");
5967     if (SDValue V = simplifyFPBinop(Opcode, N1, N2, Flags))
5968       return V;
5969     break;
5970   case ISD::FCOPYSIGN:   // N1 and result must match.  N1/N2 need not match.
5971     assert(N1.getValueType() == VT &&
5972            N1.getValueType().isFloatingPoint() &&
5973            N2.getValueType().isFloatingPoint() &&
5974            "Invalid FCOPYSIGN!");
5975     break;
5976   case ISD::SHL:
5977     if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
5978       const APInt &MulImm = N1->getConstantOperandAPInt(0);
5979       const APInt &ShiftImm = N2C->getAPIntValue();
5980       return getVScale(DL, VT, MulImm << ShiftImm);
5981     }
5982     LLVM_FALLTHROUGH;
5983   case ISD::SRA:
5984   case ISD::SRL:
5985     if (SDValue V = simplifyShift(N1, N2))
5986       return V;
5987     LLVM_FALLTHROUGH;
5988   case ISD::ROTL:
5989   case ISD::ROTR:
5990     assert(VT == N1.getValueType() &&
5991            "Shift operators return type must be the same as their first arg");
5992     assert(VT.isInteger() && N2.getValueType().isInteger() &&
5993            "Shifts only work on integers");
5994     assert((!VT.isVector() || VT == N2.getValueType()) &&
5995            "Vector shift amounts must be in the same as their first arg");
5996     // Verify that the shift amount VT is big enough to hold valid shift
5997     // amounts.  This catches things like trying to shift an i1024 value by an
5998     // i8, which is easy to fall into in generic code that uses
5999     // TLI.getShiftAmount().
6000     assert(N2.getValueType().getScalarSizeInBits() >=
6001                Log2_32_Ceil(VT.getScalarSizeInBits()) &&
6002            "Invalid use of small shift amount with oversized value!");
6003 
6004     // Always fold shifts of i1 values so the code generator doesn't need to
6005     // handle them.  Since we know the size of the shift has to be less than the
6006     // size of the value, the shift/rotate count is guaranteed to be zero.
6007     if (VT == MVT::i1)
6008       return N1;
6009     if (N2CV && N2CV->isZero())
6010       return N1;
6011     break;
6012   case ISD::FP_ROUND:
6013     assert(VT.isFloatingPoint() &&
6014            N1.getValueType().isFloatingPoint() &&
6015            VT.bitsLE(N1.getValueType()) &&
6016            N2C && (N2C->getZExtValue() == 0 || N2C->getZExtValue() == 1) &&
6017            "Invalid FP_ROUND!");
6018     if (N1.getValueType() == VT) return N1;  // noop conversion.
6019     break;
6020   case ISD::AssertSext:
6021   case ISD::AssertZext: {
6022     EVT EVT = cast<VTSDNode>(N2)->getVT();
6023     assert(VT == N1.getValueType() && "Not an inreg extend!");
6024     assert(VT.isInteger() && EVT.isInteger() &&
6025            "Cannot *_EXTEND_INREG FP types");
6026     assert(!EVT.isVector() &&
6027            "AssertSExt/AssertZExt type should be the vector element type "
6028            "rather than the vector type!");
6029     assert(EVT.bitsLE(VT.getScalarType()) && "Not extending!");
6030     if (VT.getScalarType() == EVT) return N1; // noop assertion.
6031     break;
6032   }
6033   case ISD::SIGN_EXTEND_INREG: {
6034     EVT EVT = cast<VTSDNode>(N2)->getVT();
6035     assert(VT == N1.getValueType() && "Not an inreg extend!");
6036     assert(VT.isInteger() && EVT.isInteger() &&
6037            "Cannot *_EXTEND_INREG FP types");
6038     assert(EVT.isVector() == VT.isVector() &&
6039            "SIGN_EXTEND_INREG type should be vector iff the operand "
6040            "type is vector!");
6041     assert((!EVT.isVector() ||
6042             EVT.getVectorElementCount() == VT.getVectorElementCount()) &&
6043            "Vector element counts must match in SIGN_EXTEND_INREG");
6044     assert(EVT.bitsLE(VT) && "Not extending!");
6045     if (EVT == VT) return N1;  // Not actually extending
6046 
6047     auto SignExtendInReg = [&](APInt Val, llvm::EVT ConstantVT) {
6048       unsigned FromBits = EVT.getScalarSizeInBits();
6049       Val <<= Val.getBitWidth() - FromBits;
6050       Val.ashrInPlace(Val.getBitWidth() - FromBits);
6051       return getConstant(Val, DL, ConstantVT);
6052     };
6053 
6054     if (N1C) {
6055       const APInt &Val = N1C->getAPIntValue();
6056       return SignExtendInReg(Val, VT);
6057     }
6058 
6059     if (ISD::isBuildVectorOfConstantSDNodes(N1.getNode())) {
6060       SmallVector<SDValue, 8> Ops;
6061       llvm::EVT OpVT = N1.getOperand(0).getValueType();
6062       for (int i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
6063         SDValue Op = N1.getOperand(i);
6064         if (Op.isUndef()) {
6065           Ops.push_back(getUNDEF(OpVT));
6066           continue;
6067         }
6068         ConstantSDNode *C = cast<ConstantSDNode>(Op);
6069         APInt Val = C->getAPIntValue();
6070         Ops.push_back(SignExtendInReg(Val, OpVT));
6071       }
6072       return getBuildVector(VT, DL, Ops);
6073     }
6074     break;
6075   }
6076   case ISD::FP_TO_SINT_SAT:
6077   case ISD::FP_TO_UINT_SAT: {
6078     assert(VT.isInteger() && cast<VTSDNode>(N2)->getVT().isInteger() &&
6079            N1.getValueType().isFloatingPoint() && "Invalid FP_TO_*INT_SAT");
6080     assert(N1.getValueType().isVector() == VT.isVector() &&
6081            "FP_TO_*INT_SAT type should be vector iff the operand type is "
6082            "vector!");
6083     assert((!VT.isVector() || VT.getVectorNumElements() ==
6084                                   N1.getValueType().getVectorNumElements()) &&
6085            "Vector element counts must match in FP_TO_*INT_SAT");
6086     assert(!cast<VTSDNode>(N2)->getVT().isVector() &&
6087            "Type to saturate to must be a scalar.");
6088     assert(cast<VTSDNode>(N2)->getVT().bitsLE(VT.getScalarType()) &&
6089            "Not extending!");
6090     break;
6091   }
6092   case ISD::EXTRACT_VECTOR_ELT:
6093     assert(VT.getSizeInBits() >= N1.getValueType().getScalarSizeInBits() &&
6094            "The result of EXTRACT_VECTOR_ELT must be at least as wide as the \
6095              element type of the vector.");
6096 
6097     // Extract from an undefined value or using an undefined index is undefined.
6098     if (N1.isUndef() || N2.isUndef())
6099       return getUNDEF(VT);
6100 
6101     // EXTRACT_VECTOR_ELT of out-of-bounds element is an UNDEF for fixed length
6102     // vectors. For scalable vectors we will provide appropriate support for
6103     // dealing with arbitrary indices.
6104     if (N2C && N1.getValueType().isFixedLengthVector() &&
6105         N2C->getAPIntValue().uge(N1.getValueType().getVectorNumElements()))
6106       return getUNDEF(VT);
6107 
6108     // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
6109     // expanding copies of large vectors from registers. This only works for
6110     // fixed length vectors, since we need to know the exact number of
6111     // elements.
6112     if (N2C && N1.getOperand(0).getValueType().isFixedLengthVector() &&
6113         N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0) {
6114       unsigned Factor =
6115         N1.getOperand(0).getValueType().getVectorNumElements();
6116       return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
6117                      N1.getOperand(N2C->getZExtValue() / Factor),
6118                      getVectorIdxConstant(N2C->getZExtValue() % Factor, DL));
6119     }
6120 
6121     // EXTRACT_VECTOR_ELT of BUILD_VECTOR or SPLAT_VECTOR is often formed while
6122     // lowering is expanding large vector constants.
6123     if (N2C && (N1.getOpcode() == ISD::BUILD_VECTOR ||
6124                 N1.getOpcode() == ISD::SPLAT_VECTOR)) {
6125       assert((N1.getOpcode() != ISD::BUILD_VECTOR ||
6126               N1.getValueType().isFixedLengthVector()) &&
6127              "BUILD_VECTOR used for scalable vectors");
6128       unsigned Index =
6129           N1.getOpcode() == ISD::BUILD_VECTOR ? N2C->getZExtValue() : 0;
6130       SDValue Elt = N1.getOperand(Index);
6131 
6132       if (VT != Elt.getValueType())
6133         // If the vector element type is not legal, the BUILD_VECTOR operands
6134         // are promoted and implicitly truncated, and the result implicitly
6135         // extended. Make that explicit here.
6136         Elt = getAnyExtOrTrunc(Elt, DL, VT);
6137 
6138       return Elt;
6139     }
6140 
6141     // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
6142     // operations are lowered to scalars.
6143     if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) {
6144       // If the indices are the same, return the inserted element else
6145       // if the indices are known different, extract the element from
6146       // the original vector.
6147       SDValue N1Op2 = N1.getOperand(2);
6148       ConstantSDNode *N1Op2C = dyn_cast<ConstantSDNode>(N1Op2);
6149 
6150       if (N1Op2C && N2C) {
6151         if (N1Op2C->getZExtValue() == N2C->getZExtValue()) {
6152           if (VT == N1.getOperand(1).getValueType())
6153             return N1.getOperand(1);
6154           return getSExtOrTrunc(N1.getOperand(1), DL, VT);
6155         }
6156         return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2);
6157       }
6158     }
6159 
6160     // EXTRACT_VECTOR_ELT of v1iX EXTRACT_SUBVECTOR could be formed
6161     // when vector types are scalarized and v1iX is legal.
6162     // vextract (v1iX extract_subvector(vNiX, Idx)) -> vextract(vNiX,Idx).
6163     // Here we are completely ignoring the extract element index (N2),
6164     // which is fine for fixed width vectors, since any index other than 0
6165     // is undefined anyway. However, this cannot be ignored for scalable
6166     // vectors - in theory we could support this, but we don't want to do this
6167     // without a profitability check.
6168     if (N1.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
6169         N1.getValueType().isFixedLengthVector() &&
6170         N1.getValueType().getVectorNumElements() == 1) {
6171       return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0),
6172                      N1.getOperand(1));
6173     }
6174     break;
6175   case ISD::EXTRACT_ELEMENT:
6176     assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!");
6177     assert(!N1.getValueType().isVector() && !VT.isVector() &&
6178            (N1.getValueType().isInteger() == VT.isInteger()) &&
6179            N1.getValueType() != VT &&
6180            "Wrong types for EXTRACT_ELEMENT!");
6181 
6182     // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
6183     // 64-bit integers into 32-bit parts.  Instead of building the extract of
6184     // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
6185     if (N1.getOpcode() == ISD::BUILD_PAIR)
6186       return N1.getOperand(N2C->getZExtValue());
6187 
6188     // EXTRACT_ELEMENT of a constant int is also very common.
6189     if (N1C) {
6190       unsigned ElementSize = VT.getSizeInBits();
6191       unsigned Shift = ElementSize * N2C->getZExtValue();
6192       const APInt &Val = N1C->getAPIntValue();
6193       return getConstant(Val.extractBits(ElementSize, Shift), DL, VT);
6194     }
6195     break;
6196   case ISD::EXTRACT_SUBVECTOR: {
6197     EVT N1VT = N1.getValueType();
6198     assert(VT.isVector() && N1VT.isVector() &&
6199            "Extract subvector VTs must be vectors!");
6200     assert(VT.getVectorElementType() == N1VT.getVectorElementType() &&
6201            "Extract subvector VTs must have the same element type!");
6202     assert((VT.isFixedLengthVector() || N1VT.isScalableVector()) &&
6203            "Cannot extract a scalable vector from a fixed length vector!");
6204     assert((VT.isScalableVector() != N1VT.isScalableVector() ||
6205             VT.getVectorMinNumElements() <= N1VT.getVectorMinNumElements()) &&
6206            "Extract subvector must be from larger vector to smaller vector!");
6207     assert(N2C && "Extract subvector index must be a constant");
6208     assert((VT.isScalableVector() != N1VT.isScalableVector() ||
6209             (VT.getVectorMinNumElements() + N2C->getZExtValue()) <=
6210                 N1VT.getVectorMinNumElements()) &&
6211            "Extract subvector overflow!");
6212     assert(N2C->getAPIntValue().getBitWidth() ==
6213                TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() &&
6214            "Constant index for EXTRACT_SUBVECTOR has an invalid size");
6215 
6216     // Trivial extraction.
6217     if (VT == N1VT)
6218       return N1;
6219 
6220     // EXTRACT_SUBVECTOR of an UNDEF is an UNDEF.
6221     if (N1.isUndef())
6222       return getUNDEF(VT);
6223 
6224     // EXTRACT_SUBVECTOR of CONCAT_VECTOR can be simplified if the pieces of
6225     // the concat have the same type as the extract.
6226     if (N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0 &&
6227         VT == N1.getOperand(0).getValueType()) {
6228       unsigned Factor = VT.getVectorMinNumElements();
6229       return N1.getOperand(N2C->getZExtValue() / Factor);
6230     }
6231 
6232     // EXTRACT_SUBVECTOR of INSERT_SUBVECTOR is often created
6233     // during shuffle legalization.
6234     if (N1.getOpcode() == ISD::INSERT_SUBVECTOR && N2 == N1.getOperand(2) &&
6235         VT == N1.getOperand(1).getValueType())
6236       return N1.getOperand(1);
6237     break;
6238   }
6239   }
6240 
6241   // Perform trivial constant folding.
6242   if (SDValue SV = FoldConstantArithmetic(Opcode, DL, VT, {N1, N2}))
6243     return SV;
6244 
6245   // Canonicalize an UNDEF to the RHS, even over a constant.
6246   if (N1.isUndef()) {
6247     if (TLI->isCommutativeBinOp(Opcode)) {
6248       std::swap(N1, N2);
6249     } else {
6250       switch (Opcode) {
6251       case ISD::SUB:
6252         return getUNDEF(VT);     // fold op(undef, arg2) -> undef
6253       case ISD::SIGN_EXTEND_INREG:
6254       case ISD::UDIV:
6255       case ISD::SDIV:
6256       case ISD::UREM:
6257       case ISD::SREM:
6258       case ISD::SSUBSAT:
6259       case ISD::USUBSAT:
6260         return getConstant(0, DL, VT);    // fold op(undef, arg2) -> 0
6261       }
6262     }
6263   }
6264 
6265   // Fold a bunch of operators when the RHS is undef.
6266   if (N2.isUndef()) {
6267     switch (Opcode) {
6268     case ISD::XOR:
6269       if (N1.isUndef())
6270         // Handle undef ^ undef -> 0 special case. This is a common
6271         // idiom (misuse).
6272         return getConstant(0, DL, VT);
6273       LLVM_FALLTHROUGH;
6274     case ISD::ADD:
6275     case ISD::SUB:
6276     case ISD::UDIV:
6277     case ISD::SDIV:
6278     case ISD::UREM:
6279     case ISD::SREM:
6280       return getUNDEF(VT);       // fold op(arg1, undef) -> undef
6281     case ISD::MUL:
6282     case ISD::AND:
6283     case ISD::SSUBSAT:
6284     case ISD::USUBSAT:
6285       return getConstant(0, DL, VT);  // fold op(arg1, undef) -> 0
6286     case ISD::OR:
6287     case ISD::SADDSAT:
6288     case ISD::UADDSAT:
6289       return getAllOnesConstant(DL, VT);
6290     }
6291   }
6292 
6293   // Memoize this node if possible.
6294   SDNode *N;
6295   SDVTList VTs = getVTList(VT);
6296   SDValue Ops[] = {N1, N2};
6297   if (VT != MVT::Glue) {
6298     FoldingSetNodeID ID;
6299     AddNodeIDNode(ID, Opcode, VTs, Ops);
6300     void *IP = nullptr;
6301     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
6302       E->intersectFlagsWith(Flags);
6303       return SDValue(E, 0);
6304     }
6305 
6306     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6307     N->setFlags(Flags);
6308     createOperands(N, Ops);
6309     CSEMap.InsertNode(N, IP);
6310   } else {
6311     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6312     createOperands(N, Ops);
6313   }
6314 
6315   InsertNode(N);
6316   SDValue V = SDValue(N, 0);
6317   NewSDValueDbgMsg(V, "Creating new node: ", this);
6318   return V;
6319 }
6320 
6321 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6322                               SDValue N1, SDValue N2, SDValue N3) {
6323   SDNodeFlags Flags;
6324   if (Inserter)
6325     Flags = Inserter->getFlags();
6326   return getNode(Opcode, DL, VT, N1, N2, N3, Flags);
6327 }
6328 
6329 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6330                               SDValue N1, SDValue N2, SDValue N3,
6331                               const SDNodeFlags Flags) {
6332   assert(N1.getOpcode() != ISD::DELETED_NODE &&
6333          N2.getOpcode() != ISD::DELETED_NODE &&
6334          N3.getOpcode() != ISD::DELETED_NODE &&
6335          "Operand is DELETED_NODE!");
6336   // Perform various simplifications.
6337   switch (Opcode) {
6338   case ISD::FMA: {
6339     assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
6340     assert(N1.getValueType() == VT && N2.getValueType() == VT &&
6341            N3.getValueType() == VT && "FMA types must match!");
6342     ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6343     ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
6344     ConstantFPSDNode *N3CFP = dyn_cast<ConstantFPSDNode>(N3);
6345     if (N1CFP && N2CFP && N3CFP) {
6346       APFloat  V1 = N1CFP->getValueAPF();
6347       const APFloat &V2 = N2CFP->getValueAPF();
6348       const APFloat &V3 = N3CFP->getValueAPF();
6349       V1.fusedMultiplyAdd(V2, V3, APFloat::rmNearestTiesToEven);
6350       return getConstantFP(V1, DL, VT);
6351     }
6352     break;
6353   }
6354   case ISD::BUILD_VECTOR: {
6355     // Attempt to simplify BUILD_VECTOR.
6356     SDValue Ops[] = {N1, N2, N3};
6357     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
6358       return V;
6359     break;
6360   }
6361   case ISD::CONCAT_VECTORS: {
6362     SDValue Ops[] = {N1, N2, N3};
6363     if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
6364       return V;
6365     break;
6366   }
6367   case ISD::SETCC: {
6368     assert(VT.isInteger() && "SETCC result type must be an integer!");
6369     assert(N1.getValueType() == N2.getValueType() &&
6370            "SETCC operands must have the same type!");
6371     assert(VT.isVector() == N1.getValueType().isVector() &&
6372            "SETCC type should be vector iff the operand type is vector!");
6373     assert((!VT.isVector() || VT.getVectorElementCount() ==
6374                                   N1.getValueType().getVectorElementCount()) &&
6375            "SETCC vector element counts must match!");
6376     // Use FoldSetCC to simplify SETCC's.
6377     if (SDValue V = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL))
6378       return V;
6379     // Vector constant folding.
6380     SDValue Ops[] = {N1, N2, N3};
6381     if (SDValue V = FoldConstantArithmetic(Opcode, DL, VT, Ops)) {
6382       NewSDValueDbgMsg(V, "New node vector constant folding: ", this);
6383       return V;
6384     }
6385     break;
6386   }
6387   case ISD::SELECT:
6388   case ISD::VSELECT:
6389     if (SDValue V = simplifySelect(N1, N2, N3))
6390       return V;
6391     break;
6392   case ISD::VECTOR_SHUFFLE:
6393     llvm_unreachable("should use getVectorShuffle constructor!");
6394   case ISD::VECTOR_SPLICE: {
6395     if (cast<ConstantSDNode>(N3)->isNullValue())
6396       return N1;
6397     break;
6398   }
6399   case ISD::INSERT_VECTOR_ELT: {
6400     ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3);
6401     // INSERT_VECTOR_ELT into out-of-bounds element is an UNDEF, except
6402     // for scalable vectors where we will generate appropriate code to
6403     // deal with out-of-bounds cases correctly.
6404     if (N3C && N1.getValueType().isFixedLengthVector() &&
6405         N3C->getZExtValue() >= N1.getValueType().getVectorNumElements())
6406       return getUNDEF(VT);
6407 
6408     // Undefined index can be assumed out-of-bounds, so that's UNDEF too.
6409     if (N3.isUndef())
6410       return getUNDEF(VT);
6411 
6412     // If the inserted element is an UNDEF, just use the input vector.
6413     if (N2.isUndef())
6414       return N1;
6415 
6416     break;
6417   }
6418   case ISD::INSERT_SUBVECTOR: {
6419     // Inserting undef into undef is still undef.
6420     if (N1.isUndef() && N2.isUndef())
6421       return getUNDEF(VT);
6422 
6423     EVT N2VT = N2.getValueType();
6424     assert(VT == N1.getValueType() &&
6425            "Dest and insert subvector source types must match!");
6426     assert(VT.isVector() && N2VT.isVector() &&
6427            "Insert subvector VTs must be vectors!");
6428     assert((VT.isScalableVector() || N2VT.isFixedLengthVector()) &&
6429            "Cannot insert a scalable vector into a fixed length vector!");
6430     assert((VT.isScalableVector() != N2VT.isScalableVector() ||
6431             VT.getVectorMinNumElements() >= N2VT.getVectorMinNumElements()) &&
6432            "Insert subvector must be from smaller vector to larger vector!");
6433     assert(isa<ConstantSDNode>(N3) &&
6434            "Insert subvector index must be constant");
6435     assert((VT.isScalableVector() != N2VT.isScalableVector() ||
6436             (N2VT.getVectorMinNumElements() +
6437              cast<ConstantSDNode>(N3)->getZExtValue()) <=
6438                 VT.getVectorMinNumElements()) &&
6439            "Insert subvector overflow!");
6440     assert(cast<ConstantSDNode>(N3)->getAPIntValue().getBitWidth() ==
6441                TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() &&
6442            "Constant index for INSERT_SUBVECTOR has an invalid size");
6443 
6444     // Trivial insertion.
6445     if (VT == N2VT)
6446       return N2;
6447 
6448     // If this is an insert of an extracted vector into an undef vector, we
6449     // can just use the input to the extract.
6450     if (N1.isUndef() && N2.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
6451         N2.getOperand(1) == N3 && N2.getOperand(0).getValueType() == VT)
6452       return N2.getOperand(0);
6453     break;
6454   }
6455   case ISD::BITCAST:
6456     // Fold bit_convert nodes from a type to themselves.
6457     if (N1.getValueType() == VT)
6458       return N1;
6459     break;
6460   }
6461 
6462   // Memoize node if it doesn't produce a flag.
6463   SDNode *N;
6464   SDVTList VTs = getVTList(VT);
6465   SDValue Ops[] = {N1, N2, N3};
6466   if (VT != MVT::Glue) {
6467     FoldingSetNodeID ID;
6468     AddNodeIDNode(ID, Opcode, VTs, Ops);
6469     void *IP = nullptr;
6470     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
6471       E->intersectFlagsWith(Flags);
6472       return SDValue(E, 0);
6473     }
6474 
6475     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6476     N->setFlags(Flags);
6477     createOperands(N, Ops);
6478     CSEMap.InsertNode(N, IP);
6479   } else {
6480     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6481     createOperands(N, Ops);
6482   }
6483 
6484   InsertNode(N);
6485   SDValue V = SDValue(N, 0);
6486   NewSDValueDbgMsg(V, "Creating new node: ", this);
6487   return V;
6488 }
6489 
6490 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6491                               SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
6492   SDValue Ops[] = { N1, N2, N3, N4 };
6493   return getNode(Opcode, DL, VT, Ops);
6494 }
6495 
6496 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6497                               SDValue N1, SDValue N2, SDValue N3, SDValue N4,
6498                               SDValue N5) {
6499   SDValue Ops[] = { N1, N2, N3, N4, N5 };
6500   return getNode(Opcode, DL, VT, Ops);
6501 }
6502 
6503 /// getStackArgumentTokenFactor - Compute a TokenFactor to force all
6504 /// the incoming stack arguments to be loaded from the stack.
6505 SDValue SelectionDAG::getStackArgumentTokenFactor(SDValue Chain) {
6506   SmallVector<SDValue, 8> ArgChains;
6507 
6508   // Include the original chain at the beginning of the list. When this is
6509   // used by target LowerCall hooks, this helps legalize find the
6510   // CALLSEQ_BEGIN node.
6511   ArgChains.push_back(Chain);
6512 
6513   // Add a chain value for each stack argument.
6514   for (SDNode *U : getEntryNode().getNode()->uses())
6515     if (LoadSDNode *L = dyn_cast<LoadSDNode>(U))
6516       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
6517         if (FI->getIndex() < 0)
6518           ArgChains.push_back(SDValue(L, 1));
6519 
6520   // Build a tokenfactor for all the chains.
6521   return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
6522 }
6523 
6524 /// getMemsetValue - Vectorized representation of the memset value
6525 /// operand.
6526 static SDValue getMemsetValue(SDValue Value, EVT VT, SelectionDAG &DAG,
6527                               const SDLoc &dl) {
6528   assert(!Value.isUndef());
6529 
6530   unsigned NumBits = VT.getScalarSizeInBits();
6531   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
6532     assert(C->getAPIntValue().getBitWidth() == 8);
6533     APInt Val = APInt::getSplat(NumBits, C->getAPIntValue());
6534     if (VT.isInteger()) {
6535       bool IsOpaque = VT.getSizeInBits() > 64 ||
6536           !DAG.getTargetLoweringInfo().isLegalStoreImmediate(C->getSExtValue());
6537       return DAG.getConstant(Val, dl, VT, false, IsOpaque);
6538     }
6539     return DAG.getConstantFP(APFloat(DAG.EVTToAPFloatSemantics(VT), Val), dl,
6540                              VT);
6541   }
6542 
6543   assert(Value.getValueType() == MVT::i8 && "memset with non-byte fill value?");
6544   EVT IntVT = VT.getScalarType();
6545   if (!IntVT.isInteger())
6546     IntVT = EVT::getIntegerVT(*DAG.getContext(), IntVT.getSizeInBits());
6547 
6548   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, Value);
6549   if (NumBits > 8) {
6550     // Use a multiplication with 0x010101... to extend the input to the
6551     // required length.
6552     APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01));
6553     Value = DAG.getNode(ISD::MUL, dl, IntVT, Value,
6554                         DAG.getConstant(Magic, dl, IntVT));
6555   }
6556 
6557   if (VT != Value.getValueType() && !VT.isInteger())
6558     Value = DAG.getBitcast(VT.getScalarType(), Value);
6559   if (VT != Value.getValueType())
6560     Value = DAG.getSplatBuildVector(VT, dl, Value);
6561 
6562   return Value;
6563 }
6564 
6565 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
6566 /// used when a memcpy is turned into a memset when the source is a constant
6567 /// string ptr.
6568 static SDValue getMemsetStringVal(EVT VT, const SDLoc &dl, SelectionDAG &DAG,
6569                                   const TargetLowering &TLI,
6570                                   const ConstantDataArraySlice &Slice) {
6571   // Handle vector with all elements zero.
6572   if (Slice.Array == nullptr) {
6573     if (VT.isInteger())
6574       return DAG.getConstant(0, dl, VT);
6575     if (VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128)
6576       return DAG.getConstantFP(0.0, dl, VT);
6577     if (VT.isVector()) {
6578       unsigned NumElts = VT.getVectorNumElements();
6579       MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
6580       return DAG.getNode(ISD::BITCAST, dl, VT,
6581                          DAG.getConstant(0, dl,
6582                                          EVT::getVectorVT(*DAG.getContext(),
6583                                                           EltVT, NumElts)));
6584     }
6585     llvm_unreachable("Expected type!");
6586   }
6587 
6588   assert(!VT.isVector() && "Can't handle vector type here!");
6589   unsigned NumVTBits = VT.getSizeInBits();
6590   unsigned NumVTBytes = NumVTBits / 8;
6591   unsigned NumBytes = std::min(NumVTBytes, unsigned(Slice.Length));
6592 
6593   APInt Val(NumVTBits, 0);
6594   if (DAG.getDataLayout().isLittleEndian()) {
6595     for (unsigned i = 0; i != NumBytes; ++i)
6596       Val |= (uint64_t)(unsigned char)Slice[i] << i*8;
6597   } else {
6598     for (unsigned i = 0; i != NumBytes; ++i)
6599       Val |= (uint64_t)(unsigned char)Slice[i] << (NumVTBytes-i-1)*8;
6600   }
6601 
6602   // If the "cost" of materializing the integer immediate is less than the cost
6603   // of a load, then it is cost effective to turn the load into the immediate.
6604   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
6605   if (TLI.shouldConvertConstantLoadToIntImm(Val, Ty))
6606     return DAG.getConstant(Val, dl, VT);
6607   return SDValue();
6608 }
6609 
6610 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Base, TypeSize Offset,
6611                                            const SDLoc &DL,
6612                                            const SDNodeFlags Flags) {
6613   EVT VT = Base.getValueType();
6614   SDValue Index;
6615 
6616   if (Offset.isScalable())
6617     Index = getVScale(DL, Base.getValueType(),
6618                       APInt(Base.getValueSizeInBits().getFixedSize(),
6619                             Offset.getKnownMinSize()));
6620   else
6621     Index = getConstant(Offset.getFixedSize(), DL, VT);
6622 
6623   return getMemBasePlusOffset(Base, Index, DL, Flags);
6624 }
6625 
6626 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Ptr, SDValue Offset,
6627                                            const SDLoc &DL,
6628                                            const SDNodeFlags Flags) {
6629   assert(Offset.getValueType().isInteger());
6630   EVT BasePtrVT = Ptr.getValueType();
6631   return getNode(ISD::ADD, DL, BasePtrVT, Ptr, Offset, Flags);
6632 }
6633 
6634 /// Returns true if memcpy source is constant data.
6635 static bool isMemSrcFromConstant(SDValue Src, ConstantDataArraySlice &Slice) {
6636   uint64_t SrcDelta = 0;
6637   GlobalAddressSDNode *G = nullptr;
6638   if (Src.getOpcode() == ISD::GlobalAddress)
6639     G = cast<GlobalAddressSDNode>(Src);
6640   else if (Src.getOpcode() == ISD::ADD &&
6641            Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
6642            Src.getOperand(1).getOpcode() == ISD::Constant) {
6643     G = cast<GlobalAddressSDNode>(Src.getOperand(0));
6644     SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue();
6645   }
6646   if (!G)
6647     return false;
6648 
6649   return getConstantDataArrayInfo(G->getGlobal(), Slice, 8,
6650                                   SrcDelta + G->getOffset());
6651 }
6652 
6653 static bool shouldLowerMemFuncForSize(const MachineFunction &MF,
6654                                       SelectionDAG &DAG) {
6655   // On Darwin, -Os means optimize for size without hurting performance, so
6656   // only really optimize for size when -Oz (MinSize) is used.
6657   if (MF.getTarget().getTargetTriple().isOSDarwin())
6658     return MF.getFunction().hasMinSize();
6659   return DAG.shouldOptForSize();
6660 }
6661 
6662 static void chainLoadsAndStoresForMemcpy(SelectionDAG &DAG, const SDLoc &dl,
6663                           SmallVector<SDValue, 32> &OutChains, unsigned From,
6664                           unsigned To, SmallVector<SDValue, 16> &OutLoadChains,
6665                           SmallVector<SDValue, 16> &OutStoreChains) {
6666   assert(OutLoadChains.size() && "Missing loads in memcpy inlining");
6667   assert(OutStoreChains.size() && "Missing stores in memcpy inlining");
6668   SmallVector<SDValue, 16> GluedLoadChains;
6669   for (unsigned i = From; i < To; ++i) {
6670     OutChains.push_back(OutLoadChains[i]);
6671     GluedLoadChains.push_back(OutLoadChains[i]);
6672   }
6673 
6674   // Chain for all loads.
6675   SDValue LoadToken = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6676                                   GluedLoadChains);
6677 
6678   for (unsigned i = From; i < To; ++i) {
6679     StoreSDNode *ST = dyn_cast<StoreSDNode>(OutStoreChains[i]);
6680     SDValue NewStore = DAG.getTruncStore(LoadToken, dl, ST->getValue(),
6681                                   ST->getBasePtr(), ST->getMemoryVT(),
6682                                   ST->getMemOperand());
6683     OutChains.push_back(NewStore);
6684   }
6685 }
6686 
6687 static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
6688                                        SDValue Chain, SDValue Dst, SDValue Src,
6689                                        uint64_t Size, Align Alignment,
6690                                        bool isVol, bool AlwaysInline,
6691                                        MachinePointerInfo DstPtrInfo,
6692                                        MachinePointerInfo SrcPtrInfo,
6693                                        const AAMDNodes &AAInfo) {
6694   // Turn a memcpy of undef to nop.
6695   // FIXME: We need to honor volatile even is Src is undef.
6696   if (Src.isUndef())
6697     return Chain;
6698 
6699   // Expand memcpy to a series of load and store ops if the size operand falls
6700   // below a certain threshold.
6701   // TODO: In the AlwaysInline case, if the size is big then generate a loop
6702   // rather than maybe a humongous number of loads and stores.
6703   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6704   const DataLayout &DL = DAG.getDataLayout();
6705   LLVMContext &C = *DAG.getContext();
6706   std::vector<EVT> MemOps;
6707   bool DstAlignCanChange = false;
6708   MachineFunction &MF = DAG.getMachineFunction();
6709   MachineFrameInfo &MFI = MF.getFrameInfo();
6710   bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
6711   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
6712   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
6713     DstAlignCanChange = true;
6714   MaybeAlign SrcAlign = DAG.InferPtrAlign(Src);
6715   if (!SrcAlign || Alignment > *SrcAlign)
6716     SrcAlign = Alignment;
6717   assert(SrcAlign && "SrcAlign must be set");
6718   ConstantDataArraySlice Slice;
6719   // If marked as volatile, perform a copy even when marked as constant.
6720   bool CopyFromConstant = !isVol && isMemSrcFromConstant(Src, Slice);
6721   bool isZeroConstant = CopyFromConstant && Slice.Array == nullptr;
6722   unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize);
6723   const MemOp Op = isZeroConstant
6724                        ? MemOp::Set(Size, DstAlignCanChange, Alignment,
6725                                     /*IsZeroMemset*/ true, isVol)
6726                        : MemOp::Copy(Size, DstAlignCanChange, Alignment,
6727                                      *SrcAlign, isVol, CopyFromConstant);
6728   if (!TLI.findOptimalMemOpLowering(
6729           MemOps, Limit, Op, DstPtrInfo.getAddrSpace(),
6730           SrcPtrInfo.getAddrSpace(), MF.getFunction().getAttributes()))
6731     return SDValue();
6732 
6733   if (DstAlignCanChange) {
6734     Type *Ty = MemOps[0].getTypeForEVT(C);
6735     Align NewAlign = DL.getABITypeAlign(Ty);
6736 
6737     // Don't promote to an alignment that would require dynamic stack
6738     // realignment.
6739     const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
6740     if (!TRI->hasStackRealignment(MF))
6741       while (NewAlign > Alignment && DL.exceedsNaturalStackAlignment(NewAlign))
6742         NewAlign = NewAlign / 2;
6743 
6744     if (NewAlign > Alignment) {
6745       // Give the stack frame object a larger alignment if needed.
6746       if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
6747         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
6748       Alignment = NewAlign;
6749     }
6750   }
6751 
6752   // Prepare AAInfo for loads/stores after lowering this memcpy.
6753   AAMDNodes NewAAInfo = AAInfo;
6754   NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
6755 
6756   MachineMemOperand::Flags MMOFlags =
6757       isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
6758   SmallVector<SDValue, 16> OutLoadChains;
6759   SmallVector<SDValue, 16> OutStoreChains;
6760   SmallVector<SDValue, 32> OutChains;
6761   unsigned NumMemOps = MemOps.size();
6762   uint64_t SrcOff = 0, DstOff = 0;
6763   for (unsigned i = 0; i != NumMemOps; ++i) {
6764     EVT VT = MemOps[i];
6765     unsigned VTSize = VT.getSizeInBits() / 8;
6766     SDValue Value, Store;
6767 
6768     if (VTSize > Size) {
6769       // Issuing an unaligned load / store pair  that overlaps with the previous
6770       // pair. Adjust the offset accordingly.
6771       assert(i == NumMemOps-1 && i != 0);
6772       SrcOff -= VTSize - Size;
6773       DstOff -= VTSize - Size;
6774     }
6775 
6776     if (CopyFromConstant &&
6777         (isZeroConstant || (VT.isInteger() && !VT.isVector()))) {
6778       // It's unlikely a store of a vector immediate can be done in a single
6779       // instruction. It would require a load from a constantpool first.
6780       // We only handle zero vectors here.
6781       // FIXME: Handle other cases where store of vector immediate is done in
6782       // a single instruction.
6783       ConstantDataArraySlice SubSlice;
6784       if (SrcOff < Slice.Length) {
6785         SubSlice = Slice;
6786         SubSlice.move(SrcOff);
6787       } else {
6788         // This is an out-of-bounds access and hence UB. Pretend we read zero.
6789         SubSlice.Array = nullptr;
6790         SubSlice.Offset = 0;
6791         SubSlice.Length = VTSize;
6792       }
6793       Value = getMemsetStringVal(VT, dl, DAG, TLI, SubSlice);
6794       if (Value.getNode()) {
6795         Store = DAG.getStore(
6796             Chain, dl, Value,
6797             DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6798             DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo);
6799         OutChains.push_back(Store);
6800       }
6801     }
6802 
6803     if (!Store.getNode()) {
6804       // The type might not be legal for the target.  This should only happen
6805       // if the type is smaller than a legal type, as on PPC, so the right
6806       // thing to do is generate a LoadExt/StoreTrunc pair.  These simplify
6807       // to Load/Store if NVT==VT.
6808       // FIXME does the case above also need this?
6809       EVT NVT = TLI.getTypeToTransformTo(C, VT);
6810       assert(NVT.bitsGE(VT));
6811 
6812       bool isDereferenceable =
6813         SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
6814       MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
6815       if (isDereferenceable)
6816         SrcMMOFlags |= MachineMemOperand::MODereferenceable;
6817 
6818       Value = DAG.getExtLoad(
6819           ISD::EXTLOAD, dl, NVT, Chain,
6820           DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl),
6821           SrcPtrInfo.getWithOffset(SrcOff), VT,
6822           commonAlignment(*SrcAlign, SrcOff), SrcMMOFlags, NewAAInfo);
6823       OutLoadChains.push_back(Value.getValue(1));
6824 
6825       Store = DAG.getTruncStore(
6826           Chain, dl, Value,
6827           DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6828           DstPtrInfo.getWithOffset(DstOff), VT, Alignment, MMOFlags, NewAAInfo);
6829       OutStoreChains.push_back(Store);
6830     }
6831     SrcOff += VTSize;
6832     DstOff += VTSize;
6833     Size -= VTSize;
6834   }
6835 
6836   unsigned GluedLdStLimit = MaxLdStGlue == 0 ?
6837                                 TLI.getMaxGluedStoresPerMemcpy() : MaxLdStGlue;
6838   unsigned NumLdStInMemcpy = OutStoreChains.size();
6839 
6840   if (NumLdStInMemcpy) {
6841     // It may be that memcpy might be converted to memset if it's memcpy
6842     // of constants. In such a case, we won't have loads and stores, but
6843     // just stores. In the absence of loads, there is nothing to gang up.
6844     if ((GluedLdStLimit <= 1) || !EnableMemCpyDAGOpt) {
6845       // If target does not care, just leave as it.
6846       for (unsigned i = 0; i < NumLdStInMemcpy; ++i) {
6847         OutChains.push_back(OutLoadChains[i]);
6848         OutChains.push_back(OutStoreChains[i]);
6849       }
6850     } else {
6851       // Ld/St less than/equal limit set by target.
6852       if (NumLdStInMemcpy <= GluedLdStLimit) {
6853           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
6854                                         NumLdStInMemcpy, OutLoadChains,
6855                                         OutStoreChains);
6856       } else {
6857         unsigned NumberLdChain =  NumLdStInMemcpy / GluedLdStLimit;
6858         unsigned RemainingLdStInMemcpy = NumLdStInMemcpy % GluedLdStLimit;
6859         unsigned GlueIter = 0;
6860 
6861         for (unsigned cnt = 0; cnt < NumberLdChain; ++cnt) {
6862           unsigned IndexFrom = NumLdStInMemcpy - GlueIter - GluedLdStLimit;
6863           unsigned IndexTo   = NumLdStInMemcpy - GlueIter;
6864 
6865           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, IndexFrom, IndexTo,
6866                                        OutLoadChains, OutStoreChains);
6867           GlueIter += GluedLdStLimit;
6868         }
6869 
6870         // Residual ld/st.
6871         if (RemainingLdStInMemcpy) {
6872           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
6873                                         RemainingLdStInMemcpy, OutLoadChains,
6874                                         OutStoreChains);
6875         }
6876       }
6877     }
6878   }
6879   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
6880 }
6881 
6882 static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
6883                                         SDValue Chain, SDValue Dst, SDValue Src,
6884                                         uint64_t Size, Align Alignment,
6885                                         bool isVol, bool AlwaysInline,
6886                                         MachinePointerInfo DstPtrInfo,
6887                                         MachinePointerInfo SrcPtrInfo,
6888                                         const AAMDNodes &AAInfo) {
6889   // Turn a memmove of undef to nop.
6890   // FIXME: We need to honor volatile even is Src is undef.
6891   if (Src.isUndef())
6892     return Chain;
6893 
6894   // Expand memmove to a series of load and store ops if the size operand falls
6895   // below a certain threshold.
6896   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6897   const DataLayout &DL = DAG.getDataLayout();
6898   LLVMContext &C = *DAG.getContext();
6899   std::vector<EVT> MemOps;
6900   bool DstAlignCanChange = false;
6901   MachineFunction &MF = DAG.getMachineFunction();
6902   MachineFrameInfo &MFI = MF.getFrameInfo();
6903   bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
6904   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
6905   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
6906     DstAlignCanChange = true;
6907   MaybeAlign SrcAlign = DAG.InferPtrAlign(Src);
6908   if (!SrcAlign || Alignment > *SrcAlign)
6909     SrcAlign = Alignment;
6910   assert(SrcAlign && "SrcAlign must be set");
6911   unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize);
6912   if (!TLI.findOptimalMemOpLowering(
6913           MemOps, Limit,
6914           MemOp::Copy(Size, DstAlignCanChange, Alignment, *SrcAlign,
6915                       /*IsVolatile*/ true),
6916           DstPtrInfo.getAddrSpace(), SrcPtrInfo.getAddrSpace(),
6917           MF.getFunction().getAttributes()))
6918     return SDValue();
6919 
6920   if (DstAlignCanChange) {
6921     Type *Ty = MemOps[0].getTypeForEVT(C);
6922     Align NewAlign = DL.getABITypeAlign(Ty);
6923     if (NewAlign > Alignment) {
6924       // Give the stack frame object a larger alignment if needed.
6925       if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
6926         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
6927       Alignment = NewAlign;
6928     }
6929   }
6930 
6931   // Prepare AAInfo for loads/stores after lowering this memmove.
6932   AAMDNodes NewAAInfo = AAInfo;
6933   NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
6934 
6935   MachineMemOperand::Flags MMOFlags =
6936       isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
6937   uint64_t SrcOff = 0, DstOff = 0;
6938   SmallVector<SDValue, 8> LoadValues;
6939   SmallVector<SDValue, 8> LoadChains;
6940   SmallVector<SDValue, 8> OutChains;
6941   unsigned NumMemOps = MemOps.size();
6942   for (unsigned i = 0; i < NumMemOps; i++) {
6943     EVT VT = MemOps[i];
6944     unsigned VTSize = VT.getSizeInBits() / 8;
6945     SDValue Value;
6946 
6947     bool isDereferenceable =
6948       SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
6949     MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
6950     if (isDereferenceable)
6951       SrcMMOFlags |= MachineMemOperand::MODereferenceable;
6952 
6953     Value = DAG.getLoad(
6954         VT, dl, Chain,
6955         DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl),
6956         SrcPtrInfo.getWithOffset(SrcOff), *SrcAlign, SrcMMOFlags, NewAAInfo);
6957     LoadValues.push_back(Value);
6958     LoadChains.push_back(Value.getValue(1));
6959     SrcOff += VTSize;
6960   }
6961   Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
6962   OutChains.clear();
6963   for (unsigned i = 0; i < NumMemOps; i++) {
6964     EVT VT = MemOps[i];
6965     unsigned VTSize = VT.getSizeInBits() / 8;
6966     SDValue Store;
6967 
6968     Store = DAG.getStore(
6969         Chain, dl, LoadValues[i],
6970         DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6971         DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo);
6972     OutChains.push_back(Store);
6973     DstOff += VTSize;
6974   }
6975 
6976   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
6977 }
6978 
6979 /// Lower the call to 'memset' intrinsic function into a series of store
6980 /// operations.
6981 ///
6982 /// \param DAG Selection DAG where lowered code is placed.
6983 /// \param dl Link to corresponding IR location.
6984 /// \param Chain Control flow dependency.
6985 /// \param Dst Pointer to destination memory location.
6986 /// \param Src Value of byte to write into the memory.
6987 /// \param Size Number of bytes to write.
6988 /// \param Alignment Alignment of the destination in bytes.
6989 /// \param isVol True if destination is volatile.
6990 /// \param AlwaysInline Makes sure no function call is generated.
6991 /// \param DstPtrInfo IR information on the memory pointer.
6992 /// \returns New head in the control flow, if lowering was successful, empty
6993 /// SDValue otherwise.
6994 ///
6995 /// The function tries to replace 'llvm.memset' intrinsic with several store
6996 /// operations and value calculation code. This is usually profitable for small
6997 /// memory size or when the semantic requires inlining.
6998 static SDValue getMemsetStores(SelectionDAG &DAG, const SDLoc &dl,
6999                                SDValue Chain, SDValue Dst, SDValue Src,
7000                                uint64_t Size, Align Alignment, bool isVol,
7001                                bool AlwaysInline, MachinePointerInfo DstPtrInfo,
7002                                const AAMDNodes &AAInfo) {
7003   // Turn a memset of undef to nop.
7004   // FIXME: We need to honor volatile even is Src is undef.
7005   if (Src.isUndef())
7006     return Chain;
7007 
7008   // Expand memset to a series of load/store ops if the size operand
7009   // falls below a certain threshold.
7010   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7011   std::vector<EVT> MemOps;
7012   bool DstAlignCanChange = false;
7013   MachineFunction &MF = DAG.getMachineFunction();
7014   MachineFrameInfo &MFI = MF.getFrameInfo();
7015   bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
7016   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
7017   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
7018     DstAlignCanChange = true;
7019   bool IsZeroVal =
7020       isa<ConstantSDNode>(Src) && cast<ConstantSDNode>(Src)->isZero();
7021   unsigned Limit = AlwaysInline ? ~0 : TLI.getMaxStoresPerMemset(OptSize);
7022 
7023   if (!TLI.findOptimalMemOpLowering(
7024           MemOps, Limit,
7025           MemOp::Set(Size, DstAlignCanChange, Alignment, IsZeroVal, isVol),
7026           DstPtrInfo.getAddrSpace(), ~0u, MF.getFunction().getAttributes()))
7027     return SDValue();
7028 
7029   if (DstAlignCanChange) {
7030     Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
7031     Align NewAlign = DAG.getDataLayout().getABITypeAlign(Ty);
7032     if (NewAlign > Alignment) {
7033       // Give the stack frame object a larger alignment if needed.
7034       if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
7035         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
7036       Alignment = NewAlign;
7037     }
7038   }
7039 
7040   SmallVector<SDValue, 8> OutChains;
7041   uint64_t DstOff = 0;
7042   unsigned NumMemOps = MemOps.size();
7043 
7044   // Find the largest store and generate the bit pattern for it.
7045   EVT LargestVT = MemOps[0];
7046   for (unsigned i = 1; i < NumMemOps; i++)
7047     if (MemOps[i].bitsGT(LargestVT))
7048       LargestVT = MemOps[i];
7049   SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl);
7050 
7051   // Prepare AAInfo for loads/stores after lowering this memset.
7052   AAMDNodes NewAAInfo = AAInfo;
7053   NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
7054 
7055   for (unsigned i = 0; i < NumMemOps; i++) {
7056     EVT VT = MemOps[i];
7057     unsigned VTSize = VT.getSizeInBits() / 8;
7058     if (VTSize > Size) {
7059       // Issuing an unaligned load / store pair  that overlaps with the previous
7060       // pair. Adjust the offset accordingly.
7061       assert(i == NumMemOps-1 && i != 0);
7062       DstOff -= VTSize - Size;
7063     }
7064 
7065     // If this store is smaller than the largest store see whether we can get
7066     // the smaller value for free with a truncate.
7067     SDValue Value = MemSetValue;
7068     if (VT.bitsLT(LargestVT)) {
7069       if (!LargestVT.isVector() && !VT.isVector() &&
7070           TLI.isTruncateFree(LargestVT, VT))
7071         Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue);
7072       else
7073         Value = getMemsetValue(Src, VT, DAG, dl);
7074     }
7075     assert(Value.getValueType() == VT && "Value with wrong type.");
7076     SDValue Store = DAG.getStore(
7077         Chain, dl, Value,
7078         DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
7079         DstPtrInfo.getWithOffset(DstOff), Alignment,
7080         isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone,
7081         NewAAInfo);
7082     OutChains.push_back(Store);
7083     DstOff += VT.getSizeInBits() / 8;
7084     Size -= VTSize;
7085   }
7086 
7087   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
7088 }
7089 
7090 static void checkAddrSpaceIsValidForLibcall(const TargetLowering *TLI,
7091                                             unsigned AS) {
7092   // Lowering memcpy / memset / memmove intrinsics to calls is only valid if all
7093   // pointer operands can be losslessly bitcasted to pointers of address space 0
7094   if (AS != 0 && !TLI->getTargetMachine().isNoopAddrSpaceCast(AS, 0)) {
7095     report_fatal_error("cannot lower memory intrinsic in address space " +
7096                        Twine(AS));
7097   }
7098 }
7099 
7100 SDValue SelectionDAG::getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst,
7101                                 SDValue Src, SDValue Size, Align Alignment,
7102                                 bool isVol, bool AlwaysInline, bool isTailCall,
7103                                 MachinePointerInfo DstPtrInfo,
7104                                 MachinePointerInfo SrcPtrInfo,
7105                                 const AAMDNodes &AAInfo) {
7106   // Check to see if we should lower the memcpy to loads and stores first.
7107   // For cases within the target-specified limits, this is the best choice.
7108   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
7109   if (ConstantSize) {
7110     // Memcpy with size zero? Just return the original chain.
7111     if (ConstantSize->isZero())
7112       return Chain;
7113 
7114     SDValue Result = getMemcpyLoadsAndStores(
7115         *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment,
7116         isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo);
7117     if (Result.getNode())
7118       return Result;
7119   }
7120 
7121   // Then check to see if we should lower the memcpy with target-specific
7122   // code. If the target chooses to do this, this is the next best.
7123   if (TSI) {
7124     SDValue Result = TSI->EmitTargetCodeForMemcpy(
7125         *this, dl, Chain, Dst, Src, Size, Alignment, isVol, AlwaysInline,
7126         DstPtrInfo, SrcPtrInfo);
7127     if (Result.getNode())
7128       return Result;
7129   }
7130 
7131   // If we really need inline code and the target declined to provide it,
7132   // use a (potentially long) sequence of loads and stores.
7133   if (AlwaysInline) {
7134     assert(ConstantSize && "AlwaysInline requires a constant size!");
7135     return getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
7136                                    ConstantSize->getZExtValue(), Alignment,
7137                                    isVol, true, DstPtrInfo, SrcPtrInfo, AAInfo);
7138   }
7139 
7140   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
7141   checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
7142 
7143   // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc
7144   // memcpy is not guaranteed to be safe. libc memcpys aren't required to
7145   // respect volatile, so they may do things like read or write memory
7146   // beyond the given memory regions. But fixing this isn't easy, and most
7147   // people don't care.
7148 
7149   // Emit a library call.
7150   TargetLowering::ArgListTy Args;
7151   TargetLowering::ArgListEntry Entry;
7152   Entry.Ty = Type::getInt8PtrTy(*getContext());
7153   Entry.Node = Dst; Args.push_back(Entry);
7154   Entry.Node = Src; Args.push_back(Entry);
7155 
7156   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7157   Entry.Node = Size; Args.push_back(Entry);
7158   // FIXME: pass in SDLoc
7159   TargetLowering::CallLoweringInfo CLI(*this);
7160   CLI.setDebugLoc(dl)
7161       .setChain(Chain)
7162       .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMCPY),
7163                     Dst.getValueType().getTypeForEVT(*getContext()),
7164                     getExternalSymbol(TLI->getLibcallName(RTLIB::MEMCPY),
7165                                       TLI->getPointerTy(getDataLayout())),
7166                     std::move(Args))
7167       .setDiscardResult()
7168       .setTailCall(isTailCall);
7169 
7170   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
7171   return CallResult.second;
7172 }
7173 
7174 SDValue SelectionDAG::getAtomicMemcpy(SDValue Chain, const SDLoc &dl,
7175                                       SDValue Dst, SDValue Src, SDValue Size,
7176                                       Type *SizeTy, unsigned ElemSz,
7177                                       bool isTailCall,
7178                                       MachinePointerInfo DstPtrInfo,
7179                                       MachinePointerInfo SrcPtrInfo) {
7180   // Emit a library call.
7181   TargetLowering::ArgListTy Args;
7182   TargetLowering::ArgListEntry Entry;
7183   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7184   Entry.Node = Dst;
7185   Args.push_back(Entry);
7186 
7187   Entry.Node = Src;
7188   Args.push_back(Entry);
7189 
7190   Entry.Ty = SizeTy;
7191   Entry.Node = Size;
7192   Args.push_back(Entry);
7193 
7194   RTLIB::Libcall LibraryCall =
7195       RTLIB::getMEMCPY_ELEMENT_UNORDERED_ATOMIC(ElemSz);
7196   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
7197     report_fatal_error("Unsupported element size");
7198 
7199   TargetLowering::CallLoweringInfo CLI(*this);
7200   CLI.setDebugLoc(dl)
7201       .setChain(Chain)
7202       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
7203                     Type::getVoidTy(*getContext()),
7204                     getExternalSymbol(TLI->getLibcallName(LibraryCall),
7205                                       TLI->getPointerTy(getDataLayout())),
7206                     std::move(Args))
7207       .setDiscardResult()
7208       .setTailCall(isTailCall);
7209 
7210   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
7211   return CallResult.second;
7212 }
7213 
7214 SDValue SelectionDAG::getMemmove(SDValue Chain, const SDLoc &dl, SDValue Dst,
7215                                  SDValue Src, SDValue Size, Align Alignment,
7216                                  bool isVol, bool isTailCall,
7217                                  MachinePointerInfo DstPtrInfo,
7218                                  MachinePointerInfo SrcPtrInfo,
7219                                  const AAMDNodes &AAInfo) {
7220   // Check to see if we should lower the memmove to loads and stores first.
7221   // For cases within the target-specified limits, this is the best choice.
7222   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
7223   if (ConstantSize) {
7224     // Memmove with size zero? Just return the original chain.
7225     if (ConstantSize->isZero())
7226       return Chain;
7227 
7228     SDValue Result = getMemmoveLoadsAndStores(
7229         *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment,
7230         isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo);
7231     if (Result.getNode())
7232       return Result;
7233   }
7234 
7235   // Then check to see if we should lower the memmove with target-specific
7236   // code. If the target chooses to do this, this is the next best.
7237   if (TSI) {
7238     SDValue Result =
7239         TSI->EmitTargetCodeForMemmove(*this, dl, Chain, Dst, Src, Size,
7240                                       Alignment, isVol, DstPtrInfo, SrcPtrInfo);
7241     if (Result.getNode())
7242       return Result;
7243   }
7244 
7245   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
7246   checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
7247 
7248   // FIXME: If the memmove is volatile, lowering it to plain libc memmove may
7249   // not be safe.  See memcpy above for more details.
7250 
7251   // Emit a library call.
7252   TargetLowering::ArgListTy Args;
7253   TargetLowering::ArgListEntry Entry;
7254   Entry.Ty = Type::getInt8PtrTy(*getContext());
7255   Entry.Node = Dst; Args.push_back(Entry);
7256   Entry.Node = Src; Args.push_back(Entry);
7257 
7258   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7259   Entry.Node = Size; Args.push_back(Entry);
7260   // FIXME:  pass in SDLoc
7261   TargetLowering::CallLoweringInfo CLI(*this);
7262   CLI.setDebugLoc(dl)
7263       .setChain(Chain)
7264       .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMMOVE),
7265                     Dst.getValueType().getTypeForEVT(*getContext()),
7266                     getExternalSymbol(TLI->getLibcallName(RTLIB::MEMMOVE),
7267                                       TLI->getPointerTy(getDataLayout())),
7268                     std::move(Args))
7269       .setDiscardResult()
7270       .setTailCall(isTailCall);
7271 
7272   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
7273   return CallResult.second;
7274 }
7275 
7276 SDValue SelectionDAG::getAtomicMemmove(SDValue Chain, const SDLoc &dl,
7277                                        SDValue Dst, SDValue Src, SDValue Size,
7278                                        Type *SizeTy, unsigned ElemSz,
7279                                        bool isTailCall,
7280                                        MachinePointerInfo DstPtrInfo,
7281                                        MachinePointerInfo SrcPtrInfo) {
7282   // Emit a library call.
7283   TargetLowering::ArgListTy Args;
7284   TargetLowering::ArgListEntry Entry;
7285   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7286   Entry.Node = Dst;
7287   Args.push_back(Entry);
7288 
7289   Entry.Node = Src;
7290   Args.push_back(Entry);
7291 
7292   Entry.Ty = SizeTy;
7293   Entry.Node = Size;
7294   Args.push_back(Entry);
7295 
7296   RTLIB::Libcall LibraryCall =
7297       RTLIB::getMEMMOVE_ELEMENT_UNORDERED_ATOMIC(ElemSz);
7298   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
7299     report_fatal_error("Unsupported element size");
7300 
7301   TargetLowering::CallLoweringInfo CLI(*this);
7302   CLI.setDebugLoc(dl)
7303       .setChain(Chain)
7304       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
7305                     Type::getVoidTy(*getContext()),
7306                     getExternalSymbol(TLI->getLibcallName(LibraryCall),
7307                                       TLI->getPointerTy(getDataLayout())),
7308                     std::move(Args))
7309       .setDiscardResult()
7310       .setTailCall(isTailCall);
7311 
7312   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
7313   return CallResult.second;
7314 }
7315 
7316 SDValue SelectionDAG::getMemset(SDValue Chain, const SDLoc &dl, SDValue Dst,
7317                                 SDValue Src, SDValue Size, Align Alignment,
7318                                 bool isVol, bool AlwaysInline, bool isTailCall,
7319                                 MachinePointerInfo DstPtrInfo,
7320                                 const AAMDNodes &AAInfo) {
7321   // Check to see if we should lower the memset to stores first.
7322   // For cases within the target-specified limits, this is the best choice.
7323   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
7324   if (ConstantSize) {
7325     // Memset with size zero? Just return the original chain.
7326     if (ConstantSize->isZero())
7327       return Chain;
7328 
7329     SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src,
7330                                      ConstantSize->getZExtValue(), Alignment,
7331                                      isVol, false, DstPtrInfo, AAInfo);
7332 
7333     if (Result.getNode())
7334       return Result;
7335   }
7336 
7337   // Then check to see if we should lower the memset with target-specific
7338   // code. If the target chooses to do this, this is the next best.
7339   if (TSI) {
7340     SDValue Result = TSI->EmitTargetCodeForMemset(
7341         *this, dl, Chain, Dst, Src, Size, Alignment, isVol, AlwaysInline, DstPtrInfo);
7342     if (Result.getNode())
7343       return Result;
7344   }
7345 
7346   // If we really need inline code and the target declined to provide it,
7347   // use a (potentially long) sequence of loads and stores.
7348   if (AlwaysInline) {
7349     assert(ConstantSize && "AlwaysInline requires a constant size!");
7350     SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src,
7351                                      ConstantSize->getZExtValue(), Alignment,
7352                                      isVol, true, DstPtrInfo, AAInfo);
7353     assert(Result &&
7354            "getMemsetStores must return a valid sequence when AlwaysInline");
7355     return Result;
7356   }
7357 
7358   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
7359 
7360   // Emit a library call.
7361   auto &Ctx = *getContext();
7362   const auto& DL = getDataLayout();
7363 
7364   TargetLowering::CallLoweringInfo CLI(*this);
7365   // FIXME: pass in SDLoc
7366   CLI.setDebugLoc(dl).setChain(Chain);
7367 
7368   ConstantSDNode *ConstantSrc = dyn_cast<ConstantSDNode>(Src);
7369   const bool SrcIsZero = ConstantSrc && ConstantSrc->isZero();
7370   const char *BzeroName = getTargetLoweringInfo().getLibcallName(RTLIB::BZERO);
7371 
7372   // Helper function to create an Entry from Node and Type.
7373   const auto CreateEntry = [](SDValue Node, Type *Ty) {
7374     TargetLowering::ArgListEntry Entry;
7375     Entry.Node = Node;
7376     Entry.Ty = Ty;
7377     return Entry;
7378   };
7379 
7380   // If zeroing out and bzero is present, use it.
7381   if (SrcIsZero && BzeroName) {
7382     TargetLowering::ArgListTy Args;
7383     Args.push_back(CreateEntry(Dst, Type::getInt8PtrTy(Ctx)));
7384     Args.push_back(CreateEntry(Size, DL.getIntPtrType(Ctx)));
7385     CLI.setLibCallee(
7386         TLI->getLibcallCallingConv(RTLIB::BZERO), Type::getVoidTy(Ctx),
7387         getExternalSymbol(BzeroName, TLI->getPointerTy(DL)), std::move(Args));
7388   } else {
7389     TargetLowering::ArgListTy Args;
7390     Args.push_back(CreateEntry(Dst, Type::getInt8PtrTy(Ctx)));
7391     Args.push_back(CreateEntry(Src, Src.getValueType().getTypeForEVT(Ctx)));
7392     Args.push_back(CreateEntry(Size, DL.getIntPtrType(Ctx)));
7393     CLI.setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMSET),
7394                      Dst.getValueType().getTypeForEVT(Ctx),
7395                      getExternalSymbol(TLI->getLibcallName(RTLIB::MEMSET),
7396                                        TLI->getPointerTy(DL)),
7397                      std::move(Args));
7398   }
7399 
7400   CLI.setDiscardResult().setTailCall(isTailCall);
7401 
7402   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
7403   return CallResult.second;
7404 }
7405 
7406 SDValue SelectionDAG::getAtomicMemset(SDValue Chain, const SDLoc &dl,
7407                                       SDValue Dst, SDValue Value, SDValue Size,
7408                                       Type *SizeTy, unsigned ElemSz,
7409                                       bool isTailCall,
7410                                       MachinePointerInfo DstPtrInfo) {
7411   // Emit a library call.
7412   TargetLowering::ArgListTy Args;
7413   TargetLowering::ArgListEntry Entry;
7414   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7415   Entry.Node = Dst;
7416   Args.push_back(Entry);
7417 
7418   Entry.Ty = Type::getInt8Ty(*getContext());
7419   Entry.Node = Value;
7420   Args.push_back(Entry);
7421 
7422   Entry.Ty = SizeTy;
7423   Entry.Node = Size;
7424   Args.push_back(Entry);
7425 
7426   RTLIB::Libcall LibraryCall =
7427       RTLIB::getMEMSET_ELEMENT_UNORDERED_ATOMIC(ElemSz);
7428   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
7429     report_fatal_error("Unsupported element size");
7430 
7431   TargetLowering::CallLoweringInfo CLI(*this);
7432   CLI.setDebugLoc(dl)
7433       .setChain(Chain)
7434       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
7435                     Type::getVoidTy(*getContext()),
7436                     getExternalSymbol(TLI->getLibcallName(LibraryCall),
7437                                       TLI->getPointerTy(getDataLayout())),
7438                     std::move(Args))
7439       .setDiscardResult()
7440       .setTailCall(isTailCall);
7441 
7442   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
7443   return CallResult.second;
7444 }
7445 
7446 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
7447                                 SDVTList VTList, ArrayRef<SDValue> Ops,
7448                                 MachineMemOperand *MMO) {
7449   FoldingSetNodeID ID;
7450   ID.AddInteger(MemVT.getRawBits());
7451   AddNodeIDNode(ID, Opcode, VTList, Ops);
7452   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7453   ID.AddInteger(MMO->getFlags());
7454   void* IP = nullptr;
7455   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7456     cast<AtomicSDNode>(E)->refineAlignment(MMO);
7457     return SDValue(E, 0);
7458   }
7459 
7460   auto *N = newSDNode<AtomicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
7461                                     VTList, MemVT, MMO);
7462   createOperands(N, Ops);
7463 
7464   CSEMap.InsertNode(N, IP);
7465   InsertNode(N);
7466   return SDValue(N, 0);
7467 }
7468 
7469 SDValue SelectionDAG::getAtomicCmpSwap(unsigned Opcode, const SDLoc &dl,
7470                                        EVT MemVT, SDVTList VTs, SDValue Chain,
7471                                        SDValue Ptr, SDValue Cmp, SDValue Swp,
7472                                        MachineMemOperand *MMO) {
7473   assert(Opcode == ISD::ATOMIC_CMP_SWAP ||
7474          Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
7475   assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
7476 
7477   SDValue Ops[] = {Chain, Ptr, Cmp, Swp};
7478   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
7479 }
7480 
7481 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
7482                                 SDValue Chain, SDValue Ptr, SDValue Val,
7483                                 MachineMemOperand *MMO) {
7484   assert((Opcode == ISD::ATOMIC_LOAD_ADD ||
7485           Opcode == ISD::ATOMIC_LOAD_SUB ||
7486           Opcode == ISD::ATOMIC_LOAD_AND ||
7487           Opcode == ISD::ATOMIC_LOAD_CLR ||
7488           Opcode == ISD::ATOMIC_LOAD_OR ||
7489           Opcode == ISD::ATOMIC_LOAD_XOR ||
7490           Opcode == ISD::ATOMIC_LOAD_NAND ||
7491           Opcode == ISD::ATOMIC_LOAD_MIN ||
7492           Opcode == ISD::ATOMIC_LOAD_MAX ||
7493           Opcode == ISD::ATOMIC_LOAD_UMIN ||
7494           Opcode == ISD::ATOMIC_LOAD_UMAX ||
7495           Opcode == ISD::ATOMIC_LOAD_FADD ||
7496           Opcode == ISD::ATOMIC_LOAD_FSUB ||
7497           Opcode == ISD::ATOMIC_SWAP ||
7498           Opcode == ISD::ATOMIC_STORE) &&
7499          "Invalid Atomic Op");
7500 
7501   EVT VT = Val.getValueType();
7502 
7503   SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) :
7504                                                getVTList(VT, MVT::Other);
7505   SDValue Ops[] = {Chain, Ptr, Val};
7506   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
7507 }
7508 
7509 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
7510                                 EVT VT, SDValue Chain, SDValue Ptr,
7511                                 MachineMemOperand *MMO) {
7512   assert(Opcode == ISD::ATOMIC_LOAD && "Invalid Atomic Op");
7513 
7514   SDVTList VTs = getVTList(VT, MVT::Other);
7515   SDValue Ops[] = {Chain, Ptr};
7516   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
7517 }
7518 
7519 /// getMergeValues - Create a MERGE_VALUES node from the given operands.
7520 SDValue SelectionDAG::getMergeValues(ArrayRef<SDValue> Ops, const SDLoc &dl) {
7521   if (Ops.size() == 1)
7522     return Ops[0];
7523 
7524   SmallVector<EVT, 4> VTs;
7525   VTs.reserve(Ops.size());
7526   for (const SDValue &Op : Ops)
7527     VTs.push_back(Op.getValueType());
7528   return getNode(ISD::MERGE_VALUES, dl, getVTList(VTs), Ops);
7529 }
7530 
7531 SDValue SelectionDAG::getMemIntrinsicNode(
7532     unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef<SDValue> Ops,
7533     EVT MemVT, MachinePointerInfo PtrInfo, Align Alignment,
7534     MachineMemOperand::Flags Flags, uint64_t Size, const AAMDNodes &AAInfo) {
7535   if (!Size && MemVT.isScalableVector())
7536     Size = MemoryLocation::UnknownSize;
7537   else if (!Size)
7538     Size = MemVT.getStoreSize();
7539 
7540   MachineFunction &MF = getMachineFunction();
7541   MachineMemOperand *MMO =
7542       MF.getMachineMemOperand(PtrInfo, Flags, Size, Alignment, AAInfo);
7543 
7544   return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, MMO);
7545 }
7546 
7547 SDValue SelectionDAG::getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl,
7548                                           SDVTList VTList,
7549                                           ArrayRef<SDValue> Ops, EVT MemVT,
7550                                           MachineMemOperand *MMO) {
7551   assert((Opcode == ISD::INTRINSIC_VOID ||
7552           Opcode == ISD::INTRINSIC_W_CHAIN ||
7553           Opcode == ISD::PREFETCH ||
7554           ((int)Opcode <= std::numeric_limits<int>::max() &&
7555            (int)Opcode >= ISD::FIRST_TARGET_MEMORY_OPCODE)) &&
7556          "Opcode is not a memory-accessing opcode!");
7557 
7558   // Memoize the node unless it returns a flag.
7559   MemIntrinsicSDNode *N;
7560   if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
7561     FoldingSetNodeID ID;
7562     AddNodeIDNode(ID, Opcode, VTList, Ops);
7563     ID.AddInteger(getSyntheticNodeSubclassData<MemIntrinsicSDNode>(
7564         Opcode, dl.getIROrder(), VTList, MemVT, MMO));
7565     ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7566     ID.AddInteger(MMO->getFlags());
7567     void *IP = nullptr;
7568     if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7569       cast<MemIntrinsicSDNode>(E)->refineAlignment(MMO);
7570       return SDValue(E, 0);
7571     }
7572 
7573     N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
7574                                       VTList, MemVT, MMO);
7575     createOperands(N, Ops);
7576 
7577   CSEMap.InsertNode(N, IP);
7578   } else {
7579     N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
7580                                       VTList, MemVT, MMO);
7581     createOperands(N, Ops);
7582   }
7583   InsertNode(N);
7584   SDValue V(N, 0);
7585   NewSDValueDbgMsg(V, "Creating new node: ", this);
7586   return V;
7587 }
7588 
7589 SDValue SelectionDAG::getLifetimeNode(bool IsStart, const SDLoc &dl,
7590                                       SDValue Chain, int FrameIndex,
7591                                       int64_t Size, int64_t Offset) {
7592   const unsigned Opcode = IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END;
7593   const auto VTs = getVTList(MVT::Other);
7594   SDValue Ops[2] = {
7595       Chain,
7596       getFrameIndex(FrameIndex,
7597                     getTargetLoweringInfo().getFrameIndexTy(getDataLayout()),
7598                     true)};
7599 
7600   FoldingSetNodeID ID;
7601   AddNodeIDNode(ID, Opcode, VTs, Ops);
7602   ID.AddInteger(FrameIndex);
7603   ID.AddInteger(Size);
7604   ID.AddInteger(Offset);
7605   void *IP = nullptr;
7606   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
7607     return SDValue(E, 0);
7608 
7609   LifetimeSDNode *N = newSDNode<LifetimeSDNode>(
7610       Opcode, dl.getIROrder(), dl.getDebugLoc(), VTs, Size, Offset);
7611   createOperands(N, Ops);
7612   CSEMap.InsertNode(N, IP);
7613   InsertNode(N);
7614   SDValue V(N, 0);
7615   NewSDValueDbgMsg(V, "Creating new node: ", this);
7616   return V;
7617 }
7618 
7619 SDValue SelectionDAG::getPseudoProbeNode(const SDLoc &Dl, SDValue Chain,
7620                                          uint64_t Guid, uint64_t Index,
7621                                          uint32_t Attr) {
7622   const unsigned Opcode = ISD::PSEUDO_PROBE;
7623   const auto VTs = getVTList(MVT::Other);
7624   SDValue Ops[] = {Chain};
7625   FoldingSetNodeID ID;
7626   AddNodeIDNode(ID, Opcode, VTs, Ops);
7627   ID.AddInteger(Guid);
7628   ID.AddInteger(Index);
7629   void *IP = nullptr;
7630   if (SDNode *E = FindNodeOrInsertPos(ID, Dl, IP))
7631     return SDValue(E, 0);
7632 
7633   auto *N = newSDNode<PseudoProbeSDNode>(
7634       Opcode, Dl.getIROrder(), Dl.getDebugLoc(), VTs, Guid, Index, Attr);
7635   createOperands(N, Ops);
7636   CSEMap.InsertNode(N, IP);
7637   InsertNode(N);
7638   SDValue V(N, 0);
7639   NewSDValueDbgMsg(V, "Creating new node: ", this);
7640   return V;
7641 }
7642 
7643 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
7644 /// MachinePointerInfo record from it.  This is particularly useful because the
7645 /// code generator has many cases where it doesn't bother passing in a
7646 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
7647 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info,
7648                                            SelectionDAG &DAG, SDValue Ptr,
7649                                            int64_t Offset = 0) {
7650   // If this is FI+Offset, we can model it.
7651   if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr))
7652     return MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
7653                                              FI->getIndex(), Offset);
7654 
7655   // If this is (FI+Offset1)+Offset2, we can model it.
7656   if (Ptr.getOpcode() != ISD::ADD ||
7657       !isa<ConstantSDNode>(Ptr.getOperand(1)) ||
7658       !isa<FrameIndexSDNode>(Ptr.getOperand(0)))
7659     return Info;
7660 
7661   int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
7662   return MachinePointerInfo::getFixedStack(
7663       DAG.getMachineFunction(), FI,
7664       Offset + cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue());
7665 }
7666 
7667 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
7668 /// MachinePointerInfo record from it.  This is particularly useful because the
7669 /// code generator has many cases where it doesn't bother passing in a
7670 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
7671 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info,
7672                                            SelectionDAG &DAG, SDValue Ptr,
7673                                            SDValue OffsetOp) {
7674   // If the 'Offset' value isn't a constant, we can't handle this.
7675   if (ConstantSDNode *OffsetNode = dyn_cast<ConstantSDNode>(OffsetOp))
7676     return InferPointerInfo(Info, DAG, Ptr, OffsetNode->getSExtValue());
7677   if (OffsetOp.isUndef())
7678     return InferPointerInfo(Info, DAG, Ptr);
7679   return Info;
7680 }
7681 
7682 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
7683                               EVT VT, const SDLoc &dl, SDValue Chain,
7684                               SDValue Ptr, SDValue Offset,
7685                               MachinePointerInfo PtrInfo, EVT MemVT,
7686                               Align Alignment,
7687                               MachineMemOperand::Flags MMOFlags,
7688                               const AAMDNodes &AAInfo, const MDNode *Ranges) {
7689   assert(Chain.getValueType() == MVT::Other &&
7690         "Invalid chain type");
7691 
7692   MMOFlags |= MachineMemOperand::MOLoad;
7693   assert((MMOFlags & MachineMemOperand::MOStore) == 0);
7694   // If we don't have a PtrInfo, infer the trivial frame index case to simplify
7695   // clients.
7696   if (PtrInfo.V.isNull())
7697     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
7698 
7699   uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize());
7700   MachineFunction &MF = getMachineFunction();
7701   MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size,
7702                                                    Alignment, AAInfo, Ranges);
7703   return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO);
7704 }
7705 
7706 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
7707                               EVT VT, const SDLoc &dl, SDValue Chain,
7708                               SDValue Ptr, SDValue Offset, EVT MemVT,
7709                               MachineMemOperand *MMO) {
7710   if (VT == MemVT) {
7711     ExtType = ISD::NON_EXTLOAD;
7712   } else if (ExtType == ISD::NON_EXTLOAD) {
7713     assert(VT == MemVT && "Non-extending load from different memory type!");
7714   } else {
7715     // Extending load.
7716     assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) &&
7717            "Should only be an extending load, not truncating!");
7718     assert(VT.isInteger() == MemVT.isInteger() &&
7719            "Cannot convert from FP to Int or Int -> FP!");
7720     assert(VT.isVector() == MemVT.isVector() &&
7721            "Cannot use an ext load to convert to or from a vector!");
7722     assert((!VT.isVector() ||
7723             VT.getVectorElementCount() == MemVT.getVectorElementCount()) &&
7724            "Cannot use an ext load to change the number of vector elements!");
7725   }
7726 
7727   bool Indexed = AM != ISD::UNINDEXED;
7728   assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
7729 
7730   SDVTList VTs = Indexed ?
7731     getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
7732   SDValue Ops[] = { Chain, Ptr, Offset };
7733   FoldingSetNodeID ID;
7734   AddNodeIDNode(ID, ISD::LOAD, VTs, Ops);
7735   ID.AddInteger(MemVT.getRawBits());
7736   ID.AddInteger(getSyntheticNodeSubclassData<LoadSDNode>(
7737       dl.getIROrder(), VTs, AM, ExtType, MemVT, MMO));
7738   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7739   ID.AddInteger(MMO->getFlags());
7740   void *IP = nullptr;
7741   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7742     cast<LoadSDNode>(E)->refineAlignment(MMO);
7743     return SDValue(E, 0);
7744   }
7745   auto *N = newSDNode<LoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
7746                                   ExtType, MemVT, MMO);
7747   createOperands(N, Ops);
7748 
7749   CSEMap.InsertNode(N, IP);
7750   InsertNode(N);
7751   SDValue V(N, 0);
7752   NewSDValueDbgMsg(V, "Creating new node: ", this);
7753   return V;
7754 }
7755 
7756 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
7757                               SDValue Ptr, MachinePointerInfo PtrInfo,
7758                               MaybeAlign Alignment,
7759                               MachineMemOperand::Flags MMOFlags,
7760                               const AAMDNodes &AAInfo, const MDNode *Ranges) {
7761   SDValue Undef = getUNDEF(Ptr.getValueType());
7762   return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7763                  PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges);
7764 }
7765 
7766 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
7767                               SDValue Ptr, MachineMemOperand *MMO) {
7768   SDValue Undef = getUNDEF(Ptr.getValueType());
7769   return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7770                  VT, MMO);
7771 }
7772 
7773 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
7774                                  EVT VT, SDValue Chain, SDValue Ptr,
7775                                  MachinePointerInfo PtrInfo, EVT MemVT,
7776                                  MaybeAlign Alignment,
7777                                  MachineMemOperand::Flags MMOFlags,
7778                                  const AAMDNodes &AAInfo) {
7779   SDValue Undef = getUNDEF(Ptr.getValueType());
7780   return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, PtrInfo,
7781                  MemVT, Alignment, MMOFlags, AAInfo);
7782 }
7783 
7784 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
7785                                  EVT VT, SDValue Chain, SDValue Ptr, EVT MemVT,
7786                                  MachineMemOperand *MMO) {
7787   SDValue Undef = getUNDEF(Ptr.getValueType());
7788   return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef,
7789                  MemVT, MMO);
7790 }
7791 
7792 SDValue SelectionDAG::getIndexedLoad(SDValue OrigLoad, const SDLoc &dl,
7793                                      SDValue Base, SDValue Offset,
7794                                      ISD::MemIndexedMode AM) {
7795   LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
7796   assert(LD->getOffset().isUndef() && "Load is already a indexed load!");
7797   // Don't propagate the invariant or dereferenceable flags.
7798   auto MMOFlags =
7799       LD->getMemOperand()->getFlags() &
7800       ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
7801   return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
7802                  LD->getChain(), Base, Offset, LD->getPointerInfo(),
7803                  LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo());
7804 }
7805 
7806 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7807                                SDValue Ptr, MachinePointerInfo PtrInfo,
7808                                Align Alignment,
7809                                MachineMemOperand::Flags MMOFlags,
7810                                const AAMDNodes &AAInfo) {
7811   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
7812 
7813   MMOFlags |= MachineMemOperand::MOStore;
7814   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
7815 
7816   if (PtrInfo.V.isNull())
7817     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
7818 
7819   MachineFunction &MF = getMachineFunction();
7820   uint64_t Size =
7821       MemoryLocation::getSizeOrUnknown(Val.getValueType().getStoreSize());
7822   MachineMemOperand *MMO =
7823       MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, Alignment, AAInfo);
7824   return getStore(Chain, dl, Val, Ptr, MMO);
7825 }
7826 
7827 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7828                                SDValue Ptr, MachineMemOperand *MMO) {
7829   assert(Chain.getValueType() == MVT::Other &&
7830         "Invalid chain type");
7831   EVT VT = Val.getValueType();
7832   SDVTList VTs = getVTList(MVT::Other);
7833   SDValue Undef = getUNDEF(Ptr.getValueType());
7834   SDValue Ops[] = { Chain, Val, Ptr, Undef };
7835   FoldingSetNodeID ID;
7836   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7837   ID.AddInteger(VT.getRawBits());
7838   ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
7839       dl.getIROrder(), VTs, ISD::UNINDEXED, false, VT, MMO));
7840   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7841   ID.AddInteger(MMO->getFlags());
7842   void *IP = nullptr;
7843   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7844     cast<StoreSDNode>(E)->refineAlignment(MMO);
7845     return SDValue(E, 0);
7846   }
7847   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7848                                    ISD::UNINDEXED, false, VT, MMO);
7849   createOperands(N, Ops);
7850 
7851   CSEMap.InsertNode(N, IP);
7852   InsertNode(N);
7853   SDValue V(N, 0);
7854   NewSDValueDbgMsg(V, "Creating new node: ", this);
7855   return V;
7856 }
7857 
7858 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7859                                     SDValue Ptr, MachinePointerInfo PtrInfo,
7860                                     EVT SVT, Align Alignment,
7861                                     MachineMemOperand::Flags MMOFlags,
7862                                     const AAMDNodes &AAInfo) {
7863   assert(Chain.getValueType() == MVT::Other &&
7864         "Invalid chain type");
7865 
7866   MMOFlags |= MachineMemOperand::MOStore;
7867   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
7868 
7869   if (PtrInfo.V.isNull())
7870     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
7871 
7872   MachineFunction &MF = getMachineFunction();
7873   MachineMemOperand *MMO = MF.getMachineMemOperand(
7874       PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()),
7875       Alignment, AAInfo);
7876   return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO);
7877 }
7878 
7879 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7880                                     SDValue Ptr, EVT SVT,
7881                                     MachineMemOperand *MMO) {
7882   EVT VT = Val.getValueType();
7883 
7884   assert(Chain.getValueType() == MVT::Other &&
7885         "Invalid chain type");
7886   if (VT == SVT)
7887     return getStore(Chain, dl, Val, Ptr, MMO);
7888 
7889   assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
7890          "Should only be a truncating store, not extending!");
7891   assert(VT.isInteger() == SVT.isInteger() &&
7892          "Can't do FP-INT conversion!");
7893   assert(VT.isVector() == SVT.isVector() &&
7894          "Cannot use trunc store to convert to or from a vector!");
7895   assert((!VT.isVector() ||
7896           VT.getVectorElementCount() == SVT.getVectorElementCount()) &&
7897          "Cannot use trunc store to change the number of vector elements!");
7898 
7899   SDVTList VTs = getVTList(MVT::Other);
7900   SDValue Undef = getUNDEF(Ptr.getValueType());
7901   SDValue Ops[] = { Chain, Val, Ptr, Undef };
7902   FoldingSetNodeID ID;
7903   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7904   ID.AddInteger(SVT.getRawBits());
7905   ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
7906       dl.getIROrder(), VTs, ISD::UNINDEXED, true, SVT, MMO));
7907   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7908   ID.AddInteger(MMO->getFlags());
7909   void *IP = nullptr;
7910   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7911     cast<StoreSDNode>(E)->refineAlignment(MMO);
7912     return SDValue(E, 0);
7913   }
7914   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7915                                    ISD::UNINDEXED, true, SVT, MMO);
7916   createOperands(N, Ops);
7917 
7918   CSEMap.InsertNode(N, IP);
7919   InsertNode(N);
7920   SDValue V(N, 0);
7921   NewSDValueDbgMsg(V, "Creating new node: ", this);
7922   return V;
7923 }
7924 
7925 SDValue SelectionDAG::getIndexedStore(SDValue OrigStore, const SDLoc &dl,
7926                                       SDValue Base, SDValue Offset,
7927                                       ISD::MemIndexedMode AM) {
7928   StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
7929   assert(ST->getOffset().isUndef() && "Store is already a indexed store!");
7930   SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
7931   SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
7932   FoldingSetNodeID ID;
7933   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7934   ID.AddInteger(ST->getMemoryVT().getRawBits());
7935   ID.AddInteger(ST->getRawSubclassData());
7936   ID.AddInteger(ST->getPointerInfo().getAddrSpace());
7937   ID.AddInteger(ST->getMemOperand()->getFlags());
7938   void *IP = nullptr;
7939   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
7940     return SDValue(E, 0);
7941 
7942   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
7943                                    ST->isTruncatingStore(), ST->getMemoryVT(),
7944                                    ST->getMemOperand());
7945   createOperands(N, Ops);
7946 
7947   CSEMap.InsertNode(N, IP);
7948   InsertNode(N);
7949   SDValue V(N, 0);
7950   NewSDValueDbgMsg(V, "Creating new node: ", this);
7951   return V;
7952 }
7953 
7954 SDValue SelectionDAG::getLoadVP(
7955     ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &dl,
7956     SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Mask, SDValue EVL,
7957     MachinePointerInfo PtrInfo, EVT MemVT, Align Alignment,
7958     MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
7959     const MDNode *Ranges, bool IsExpanding) {
7960   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
7961 
7962   MMOFlags |= MachineMemOperand::MOLoad;
7963   assert((MMOFlags & MachineMemOperand::MOStore) == 0);
7964   // If we don't have a PtrInfo, infer the trivial frame index case to simplify
7965   // clients.
7966   if (PtrInfo.V.isNull())
7967     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
7968 
7969   uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize());
7970   MachineFunction &MF = getMachineFunction();
7971   MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size,
7972                                                    Alignment, AAInfo, Ranges);
7973   return getLoadVP(AM, ExtType, VT, dl, Chain, Ptr, Offset, Mask, EVL, MemVT,
7974                    MMO, IsExpanding);
7975 }
7976 
7977 SDValue SelectionDAG::getLoadVP(ISD::MemIndexedMode AM,
7978                                 ISD::LoadExtType ExtType, EVT VT,
7979                                 const SDLoc &dl, SDValue Chain, SDValue Ptr,
7980                                 SDValue Offset, SDValue Mask, SDValue EVL,
7981                                 EVT MemVT, MachineMemOperand *MMO,
7982                                 bool IsExpanding) {
7983   bool Indexed = AM != ISD::UNINDEXED;
7984   assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
7985 
7986   SDVTList VTs = Indexed ? getVTList(VT, Ptr.getValueType(), MVT::Other)
7987                          : getVTList(VT, MVT::Other);
7988   SDValue Ops[] = {Chain, Ptr, Offset, Mask, EVL};
7989   FoldingSetNodeID ID;
7990   AddNodeIDNode(ID, ISD::VP_LOAD, VTs, Ops);
7991   ID.AddInteger(VT.getRawBits());
7992   ID.AddInteger(getSyntheticNodeSubclassData<VPLoadSDNode>(
7993       dl.getIROrder(), VTs, AM, ExtType, IsExpanding, MemVT, MMO));
7994   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7995   ID.AddInteger(MMO->getFlags());
7996   void *IP = nullptr;
7997   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7998     cast<VPLoadSDNode>(E)->refineAlignment(MMO);
7999     return SDValue(E, 0);
8000   }
8001   auto *N = newSDNode<VPLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
8002                                     ExtType, IsExpanding, MemVT, MMO);
8003   createOperands(N, Ops);
8004 
8005   CSEMap.InsertNode(N, IP);
8006   InsertNode(N);
8007   SDValue V(N, 0);
8008   NewSDValueDbgMsg(V, "Creating new node: ", this);
8009   return V;
8010 }
8011 
8012 SDValue SelectionDAG::getLoadVP(EVT VT, const SDLoc &dl, SDValue Chain,
8013                                 SDValue Ptr, SDValue Mask, SDValue EVL,
8014                                 MachinePointerInfo PtrInfo,
8015                                 MaybeAlign Alignment,
8016                                 MachineMemOperand::Flags MMOFlags,
8017                                 const AAMDNodes &AAInfo, const MDNode *Ranges,
8018                                 bool IsExpanding) {
8019   SDValue Undef = getUNDEF(Ptr.getValueType());
8020   return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
8021                    Mask, EVL, PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges,
8022                    IsExpanding);
8023 }
8024 
8025 SDValue SelectionDAG::getLoadVP(EVT VT, const SDLoc &dl, SDValue Chain,
8026                                 SDValue Ptr, SDValue Mask, SDValue EVL,
8027                                 MachineMemOperand *MMO, bool IsExpanding) {
8028   SDValue Undef = getUNDEF(Ptr.getValueType());
8029   return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
8030                    Mask, EVL, VT, MMO, IsExpanding);
8031 }
8032 
8033 SDValue SelectionDAG::getExtLoadVP(ISD::LoadExtType ExtType, const SDLoc &dl,
8034                                    EVT VT, SDValue Chain, SDValue Ptr,
8035                                    SDValue Mask, SDValue EVL,
8036                                    MachinePointerInfo PtrInfo, EVT MemVT,
8037                                    MaybeAlign Alignment,
8038                                    MachineMemOperand::Flags MMOFlags,
8039                                    const AAMDNodes &AAInfo, bool IsExpanding) {
8040   SDValue Undef = getUNDEF(Ptr.getValueType());
8041   return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask,
8042                    EVL, PtrInfo, MemVT, Alignment, MMOFlags, AAInfo, nullptr,
8043                    IsExpanding);
8044 }
8045 
8046 SDValue SelectionDAG::getExtLoadVP(ISD::LoadExtType ExtType, const SDLoc &dl,
8047                                    EVT VT, SDValue Chain, SDValue Ptr,
8048                                    SDValue Mask, SDValue EVL, EVT MemVT,
8049                                    MachineMemOperand *MMO, bool IsExpanding) {
8050   SDValue Undef = getUNDEF(Ptr.getValueType());
8051   return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask,
8052                    EVL, MemVT, MMO, IsExpanding);
8053 }
8054 
8055 SDValue SelectionDAG::getIndexedLoadVP(SDValue OrigLoad, const SDLoc &dl,
8056                                        SDValue Base, SDValue Offset,
8057                                        ISD::MemIndexedMode AM) {
8058   auto *LD = cast<VPLoadSDNode>(OrigLoad);
8059   assert(LD->getOffset().isUndef() && "Load is already a indexed load!");
8060   // Don't propagate the invariant or dereferenceable flags.
8061   auto MMOFlags =
8062       LD->getMemOperand()->getFlags() &
8063       ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
8064   return getLoadVP(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
8065                    LD->getChain(), Base, Offset, LD->getMask(),
8066                    LD->getVectorLength(), LD->getPointerInfo(),
8067                    LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo(),
8068                    nullptr, LD->isExpandingLoad());
8069 }
8070 
8071 SDValue SelectionDAG::getStoreVP(SDValue Chain, const SDLoc &dl, SDValue Val,
8072                                  SDValue Ptr, SDValue Offset, SDValue Mask,
8073                                  SDValue EVL, EVT MemVT, MachineMemOperand *MMO,
8074                                  ISD::MemIndexedMode AM, bool IsTruncating,
8075                                  bool IsCompressing) {
8076   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
8077   bool Indexed = AM != ISD::UNINDEXED;
8078   assert((Indexed || Offset.isUndef()) && "Unindexed vp_store with an offset!");
8079   SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other)
8080                          : getVTList(MVT::Other);
8081   SDValue Ops[] = {Chain, Val, Ptr, Offset, Mask, EVL};
8082   FoldingSetNodeID ID;
8083   AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
8084   ID.AddInteger(MemVT.getRawBits());
8085   ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>(
8086       dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
8087   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8088   ID.AddInteger(MMO->getFlags());
8089   void *IP = nullptr;
8090   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8091     cast<VPStoreSDNode>(E)->refineAlignment(MMO);
8092     return SDValue(E, 0);
8093   }
8094   auto *N = newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
8095                                      IsTruncating, IsCompressing, MemVT, MMO);
8096   createOperands(N, Ops);
8097 
8098   CSEMap.InsertNode(N, IP);
8099   InsertNode(N);
8100   SDValue V(N, 0);
8101   NewSDValueDbgMsg(V, "Creating new node: ", this);
8102   return V;
8103 }
8104 
8105 SDValue SelectionDAG::getTruncStoreVP(SDValue Chain, const SDLoc &dl,
8106                                       SDValue Val, SDValue Ptr, SDValue Mask,
8107                                       SDValue EVL, MachinePointerInfo PtrInfo,
8108                                       EVT SVT, Align Alignment,
8109                                       MachineMemOperand::Flags MMOFlags,
8110                                       const AAMDNodes &AAInfo,
8111                                       bool IsCompressing) {
8112   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
8113 
8114   MMOFlags |= MachineMemOperand::MOStore;
8115   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
8116 
8117   if (PtrInfo.V.isNull())
8118     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
8119 
8120   MachineFunction &MF = getMachineFunction();
8121   MachineMemOperand *MMO = MF.getMachineMemOperand(
8122       PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()),
8123       Alignment, AAInfo);
8124   return getTruncStoreVP(Chain, dl, Val, Ptr, Mask, EVL, SVT, MMO,
8125                          IsCompressing);
8126 }
8127 
8128 SDValue SelectionDAG::getTruncStoreVP(SDValue Chain, const SDLoc &dl,
8129                                       SDValue Val, SDValue Ptr, SDValue Mask,
8130                                       SDValue EVL, EVT SVT,
8131                                       MachineMemOperand *MMO,
8132                                       bool IsCompressing) {
8133   EVT VT = Val.getValueType();
8134 
8135   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
8136   if (VT == SVT)
8137     return getStoreVP(Chain, dl, Val, Ptr, getUNDEF(Ptr.getValueType()), Mask,
8138                       EVL, VT, MMO, ISD::UNINDEXED,
8139                       /*IsTruncating*/ false, IsCompressing);
8140 
8141   assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
8142          "Should only be a truncating store, not extending!");
8143   assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!");
8144   assert(VT.isVector() == SVT.isVector() &&
8145          "Cannot use trunc store to convert to or from a vector!");
8146   assert((!VT.isVector() ||
8147           VT.getVectorElementCount() == SVT.getVectorElementCount()) &&
8148          "Cannot use trunc store to change the number of vector elements!");
8149 
8150   SDVTList VTs = getVTList(MVT::Other);
8151   SDValue Undef = getUNDEF(Ptr.getValueType());
8152   SDValue Ops[] = {Chain, Val, Ptr, Undef, Mask, EVL};
8153   FoldingSetNodeID ID;
8154   AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
8155   ID.AddInteger(SVT.getRawBits());
8156   ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>(
8157       dl.getIROrder(), VTs, ISD::UNINDEXED, true, IsCompressing, SVT, MMO));
8158   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8159   ID.AddInteger(MMO->getFlags());
8160   void *IP = nullptr;
8161   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8162     cast<VPStoreSDNode>(E)->refineAlignment(MMO);
8163     return SDValue(E, 0);
8164   }
8165   auto *N =
8166       newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
8167                                ISD::UNINDEXED, true, IsCompressing, SVT, MMO);
8168   createOperands(N, Ops);
8169 
8170   CSEMap.InsertNode(N, IP);
8171   InsertNode(N);
8172   SDValue V(N, 0);
8173   NewSDValueDbgMsg(V, "Creating new node: ", this);
8174   return V;
8175 }
8176 
8177 SDValue SelectionDAG::getIndexedStoreVP(SDValue OrigStore, const SDLoc &dl,
8178                                         SDValue Base, SDValue Offset,
8179                                         ISD::MemIndexedMode AM) {
8180   auto *ST = cast<VPStoreSDNode>(OrigStore);
8181   assert(ST->getOffset().isUndef() && "Store is already an indexed store!");
8182   SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
8183   SDValue Ops[] = {ST->getChain(), ST->getValue(), Base,
8184                    Offset,         ST->getMask(),  ST->getVectorLength()};
8185   FoldingSetNodeID ID;
8186   AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
8187   ID.AddInteger(ST->getMemoryVT().getRawBits());
8188   ID.AddInteger(ST->getRawSubclassData());
8189   ID.AddInteger(ST->getPointerInfo().getAddrSpace());
8190   ID.AddInteger(ST->getMemOperand()->getFlags());
8191   void *IP = nullptr;
8192   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
8193     return SDValue(E, 0);
8194 
8195   auto *N = newSDNode<VPStoreSDNode>(
8196       dl.getIROrder(), dl.getDebugLoc(), VTs, AM, ST->isTruncatingStore(),
8197       ST->isCompressingStore(), ST->getMemoryVT(), ST->getMemOperand());
8198   createOperands(N, Ops);
8199 
8200   CSEMap.InsertNode(N, IP);
8201   InsertNode(N);
8202   SDValue V(N, 0);
8203   NewSDValueDbgMsg(V, "Creating new node: ", this);
8204   return V;
8205 }
8206 
8207 SDValue SelectionDAG::getStridedLoadVP(
8208     ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &DL,
8209     SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Stride, SDValue Mask,
8210     SDValue EVL, MachinePointerInfo PtrInfo, EVT MemVT, Align Alignment,
8211     MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
8212     const MDNode *Ranges, bool IsExpanding) {
8213   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
8214 
8215   MMOFlags |= MachineMemOperand::MOLoad;
8216   assert((MMOFlags & MachineMemOperand::MOStore) == 0);
8217   // If we don't have a PtrInfo, infer the trivial frame index case to simplify
8218   // clients.
8219   if (PtrInfo.V.isNull())
8220     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
8221 
8222   uint64_t Size = MemoryLocation::UnknownSize;
8223   MachineFunction &MF = getMachineFunction();
8224   MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size,
8225                                                    Alignment, AAInfo, Ranges);
8226   return getStridedLoadVP(AM, ExtType, VT, DL, Chain, Ptr, Offset, Stride, Mask,
8227                           EVL, MemVT, MMO, IsExpanding);
8228 }
8229 
8230 SDValue SelectionDAG::getStridedLoadVP(
8231     ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &DL,
8232     SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Stride, SDValue Mask,
8233     SDValue EVL, EVT MemVT, MachineMemOperand *MMO, bool IsExpanding) {
8234   bool Indexed = AM != ISD::UNINDEXED;
8235   assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
8236 
8237   SDValue Ops[] = {Chain, Ptr, Offset, Stride, Mask, EVL};
8238   SDVTList VTs = Indexed ? getVTList(VT, Ptr.getValueType(), MVT::Other)
8239                          : getVTList(VT, MVT::Other);
8240   FoldingSetNodeID ID;
8241   AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_LOAD, VTs, Ops);
8242   ID.AddInteger(VT.getRawBits());
8243   ID.AddInteger(getSyntheticNodeSubclassData<VPStridedLoadSDNode>(
8244       DL.getIROrder(), VTs, AM, ExtType, IsExpanding, MemVT, MMO));
8245   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8246 
8247   void *IP = nullptr;
8248   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
8249     cast<VPStridedLoadSDNode>(E)->refineAlignment(MMO);
8250     return SDValue(E, 0);
8251   }
8252 
8253   auto *N =
8254       newSDNode<VPStridedLoadSDNode>(DL.getIROrder(), DL.getDebugLoc(), VTs, AM,
8255                                      ExtType, IsExpanding, MemVT, MMO);
8256   createOperands(N, Ops);
8257   CSEMap.InsertNode(N, IP);
8258   InsertNode(N);
8259   SDValue V(N, 0);
8260   NewSDValueDbgMsg(V, "Creating new node: ", this);
8261   return V;
8262 }
8263 
8264 SDValue SelectionDAG::getStridedLoadVP(
8265     EVT VT, const SDLoc &DL, SDValue Chain, SDValue Ptr, SDValue Stride,
8266     SDValue Mask, SDValue EVL, MachinePointerInfo PtrInfo, MaybeAlign Alignment,
8267     MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
8268     const MDNode *Ranges, bool IsExpanding) {
8269   SDValue Undef = getUNDEF(Ptr.getValueType());
8270   return getStridedLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, DL, Chain, Ptr,
8271                           Undef, Stride, Mask, EVL, PtrInfo, VT, Alignment,
8272                           MMOFlags, AAInfo, Ranges, IsExpanding);
8273 }
8274 
8275 SDValue SelectionDAG::getStridedLoadVP(EVT VT, const SDLoc &DL, SDValue Chain,
8276                                        SDValue Ptr, SDValue Stride,
8277                                        SDValue Mask, SDValue EVL,
8278                                        MachineMemOperand *MMO,
8279                                        bool IsExpanding) {
8280   SDValue Undef = getUNDEF(Ptr.getValueType());
8281   return getStridedLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, DL, Chain, Ptr,
8282                           Undef, Stride, Mask, EVL, VT, MMO, IsExpanding);
8283 }
8284 
8285 SDValue SelectionDAG::getExtStridedLoadVP(
8286     ISD::LoadExtType ExtType, const SDLoc &DL, EVT VT, SDValue Chain,
8287     SDValue Ptr, SDValue Stride, SDValue Mask, SDValue EVL,
8288     MachinePointerInfo PtrInfo, EVT MemVT, MaybeAlign Alignment,
8289     MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
8290     bool IsExpanding) {
8291   SDValue Undef = getUNDEF(Ptr.getValueType());
8292   return getStridedLoadVP(ISD::UNINDEXED, ExtType, VT, DL, Chain, Ptr, Undef,
8293                           Stride, Mask, EVL, PtrInfo, MemVT, Alignment,
8294                           MMOFlags, AAInfo, nullptr, IsExpanding);
8295 }
8296 
8297 SDValue SelectionDAG::getExtStridedLoadVP(
8298     ISD::LoadExtType ExtType, const SDLoc &DL, EVT VT, SDValue Chain,
8299     SDValue Ptr, SDValue Stride, SDValue Mask, SDValue EVL, EVT MemVT,
8300     MachineMemOperand *MMO, bool IsExpanding) {
8301   SDValue Undef = getUNDEF(Ptr.getValueType());
8302   return getStridedLoadVP(ISD::UNINDEXED, ExtType, VT, DL, Chain, Ptr, Undef,
8303                           Stride, Mask, EVL, MemVT, MMO, IsExpanding);
8304 }
8305 
8306 SDValue SelectionDAG::getIndexedStridedLoadVP(SDValue OrigLoad, const SDLoc &DL,
8307                                               SDValue Base, SDValue Offset,
8308                                               ISD::MemIndexedMode AM) {
8309   auto *SLD = cast<VPStridedLoadSDNode>(OrigLoad);
8310   assert(SLD->getOffset().isUndef() &&
8311          "Strided load is already a indexed load!");
8312   // Don't propagate the invariant or dereferenceable flags.
8313   auto MMOFlags =
8314       SLD->getMemOperand()->getFlags() &
8315       ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
8316   return getStridedLoadVP(
8317       AM, SLD->getExtensionType(), OrigLoad.getValueType(), DL, SLD->getChain(),
8318       Base, Offset, SLD->getStride(), SLD->getMask(), SLD->getVectorLength(),
8319       SLD->getPointerInfo(), SLD->getMemoryVT(), SLD->getAlign(), MMOFlags,
8320       SLD->getAAInfo(), nullptr, SLD->isExpandingLoad());
8321 }
8322 
8323 SDValue SelectionDAG::getStridedStoreVP(SDValue Chain, const SDLoc &DL,
8324                                         SDValue Val, SDValue Ptr,
8325                                         SDValue Offset, SDValue Stride,
8326                                         SDValue Mask, SDValue EVL, EVT MemVT,
8327                                         MachineMemOperand *MMO,
8328                                         ISD::MemIndexedMode AM,
8329                                         bool IsTruncating, bool IsCompressing) {
8330   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
8331   bool Indexed = AM != ISD::UNINDEXED;
8332   assert((Indexed || Offset.isUndef()) && "Unindexed vp_store with an offset!");
8333   SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other)
8334                          : getVTList(MVT::Other);
8335   SDValue Ops[] = {Chain, Val, Ptr, Offset, Stride, Mask, EVL};
8336   FoldingSetNodeID ID;
8337   AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_STORE, VTs, Ops);
8338   ID.AddInteger(MemVT.getRawBits());
8339   ID.AddInteger(getSyntheticNodeSubclassData<VPStridedStoreSDNode>(
8340       DL.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
8341   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8342   void *IP = nullptr;
8343   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
8344     cast<VPStridedStoreSDNode>(E)->refineAlignment(MMO);
8345     return SDValue(E, 0);
8346   }
8347   auto *N = newSDNode<VPStridedStoreSDNode>(DL.getIROrder(), DL.getDebugLoc(),
8348                                             VTs, AM, IsTruncating,
8349                                             IsCompressing, MemVT, MMO);
8350   createOperands(N, Ops);
8351 
8352   CSEMap.InsertNode(N, IP);
8353   InsertNode(N);
8354   SDValue V(N, 0);
8355   NewSDValueDbgMsg(V, "Creating new node: ", this);
8356   return V;
8357 }
8358 
8359 SDValue SelectionDAG::getTruncStridedStoreVP(
8360     SDValue Chain, const SDLoc &DL, SDValue Val, SDValue Ptr, SDValue Stride,
8361     SDValue Mask, SDValue EVL, MachinePointerInfo PtrInfo, EVT SVT,
8362     Align Alignment, MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
8363     bool IsCompressing) {
8364   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
8365 
8366   MMOFlags |= MachineMemOperand::MOStore;
8367   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
8368 
8369   if (PtrInfo.V.isNull())
8370     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
8371 
8372   MachineFunction &MF = getMachineFunction();
8373   MachineMemOperand *MMO = MF.getMachineMemOperand(
8374       PtrInfo, MMOFlags, MemoryLocation::UnknownSize, Alignment, AAInfo);
8375   return getTruncStridedStoreVP(Chain, DL, Val, Ptr, Stride, Mask, EVL, SVT,
8376                                 MMO, IsCompressing);
8377 }
8378 
8379 SDValue SelectionDAG::getTruncStridedStoreVP(SDValue Chain, const SDLoc &DL,
8380                                              SDValue Val, SDValue Ptr,
8381                                              SDValue Stride, SDValue Mask,
8382                                              SDValue EVL, EVT SVT,
8383                                              MachineMemOperand *MMO,
8384                                              bool IsCompressing) {
8385   EVT VT = Val.getValueType();
8386 
8387   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
8388   if (VT == SVT)
8389     return getStridedStoreVP(Chain, DL, Val, Ptr, getUNDEF(Ptr.getValueType()),
8390                              Stride, Mask, EVL, VT, MMO, ISD::UNINDEXED,
8391                              /*IsTruncating*/ false, IsCompressing);
8392 
8393   assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
8394          "Should only be a truncating store, not extending!");
8395   assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!");
8396   assert(VT.isVector() == SVT.isVector() &&
8397          "Cannot use trunc store to convert to or from a vector!");
8398   assert((!VT.isVector() ||
8399           VT.getVectorElementCount() == SVT.getVectorElementCount()) &&
8400          "Cannot use trunc store to change the number of vector elements!");
8401 
8402   SDVTList VTs = getVTList(MVT::Other);
8403   SDValue Undef = getUNDEF(Ptr.getValueType());
8404   SDValue Ops[] = {Chain, Val, Ptr, Undef, Stride, Mask, EVL};
8405   FoldingSetNodeID ID;
8406   AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_STORE, VTs, Ops);
8407   ID.AddInteger(SVT.getRawBits());
8408   ID.AddInteger(getSyntheticNodeSubclassData<VPStridedStoreSDNode>(
8409       DL.getIROrder(), VTs, ISD::UNINDEXED, true, IsCompressing, SVT, MMO));
8410   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8411   void *IP = nullptr;
8412   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
8413     cast<VPStridedStoreSDNode>(E)->refineAlignment(MMO);
8414     return SDValue(E, 0);
8415   }
8416   auto *N = newSDNode<VPStridedStoreSDNode>(DL.getIROrder(), DL.getDebugLoc(),
8417                                             VTs, ISD::UNINDEXED, true,
8418                                             IsCompressing, SVT, MMO);
8419   createOperands(N, Ops);
8420 
8421   CSEMap.InsertNode(N, IP);
8422   InsertNode(N);
8423   SDValue V(N, 0);
8424   NewSDValueDbgMsg(V, "Creating new node: ", this);
8425   return V;
8426 }
8427 
8428 SDValue SelectionDAG::getIndexedStridedStoreVP(SDValue OrigStore,
8429                                                const SDLoc &DL, SDValue Base,
8430                                                SDValue Offset,
8431                                                ISD::MemIndexedMode AM) {
8432   auto *SST = cast<VPStridedStoreSDNode>(OrigStore);
8433   assert(SST->getOffset().isUndef() &&
8434          "Strided store is already an indexed store!");
8435   SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
8436   SDValue Ops[] = {
8437       SST->getChain(), SST->getValue(),       Base, Offset, SST->getStride(),
8438       SST->getMask(),  SST->getVectorLength()};
8439   FoldingSetNodeID ID;
8440   AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_STORE, VTs, Ops);
8441   ID.AddInteger(SST->getMemoryVT().getRawBits());
8442   ID.AddInteger(SST->getRawSubclassData());
8443   ID.AddInteger(SST->getPointerInfo().getAddrSpace());
8444   void *IP = nullptr;
8445   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
8446     return SDValue(E, 0);
8447 
8448   auto *N = newSDNode<VPStridedStoreSDNode>(
8449       DL.getIROrder(), DL.getDebugLoc(), VTs, AM, SST->isTruncatingStore(),
8450       SST->isCompressingStore(), SST->getMemoryVT(), SST->getMemOperand());
8451   createOperands(N, Ops);
8452 
8453   CSEMap.InsertNode(N, IP);
8454   InsertNode(N);
8455   SDValue V(N, 0);
8456   NewSDValueDbgMsg(V, "Creating new node: ", this);
8457   return V;
8458 }
8459 
8460 SDValue SelectionDAG::getGatherVP(SDVTList VTs, EVT VT, const SDLoc &dl,
8461                                   ArrayRef<SDValue> Ops, MachineMemOperand *MMO,
8462                                   ISD::MemIndexType IndexType) {
8463   assert(Ops.size() == 6 && "Incompatible number of operands");
8464 
8465   FoldingSetNodeID ID;
8466   AddNodeIDNode(ID, ISD::VP_GATHER, VTs, Ops);
8467   ID.AddInteger(VT.getRawBits());
8468   ID.AddInteger(getSyntheticNodeSubclassData<VPGatherSDNode>(
8469       dl.getIROrder(), VTs, VT, MMO, IndexType));
8470   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8471   ID.AddInteger(MMO->getFlags());
8472   void *IP = nullptr;
8473   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8474     cast<VPGatherSDNode>(E)->refineAlignment(MMO);
8475     return SDValue(E, 0);
8476   }
8477 
8478   auto *N = newSDNode<VPGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
8479                                       VT, MMO, IndexType);
8480   createOperands(N, Ops);
8481 
8482   assert(N->getMask().getValueType().getVectorElementCount() ==
8483              N->getValueType(0).getVectorElementCount() &&
8484          "Vector width mismatch between mask and data");
8485   assert(N->getIndex().getValueType().getVectorElementCount().isScalable() ==
8486              N->getValueType(0).getVectorElementCount().isScalable() &&
8487          "Scalable flags of index and data do not match");
8488   assert(ElementCount::isKnownGE(
8489              N->getIndex().getValueType().getVectorElementCount(),
8490              N->getValueType(0).getVectorElementCount()) &&
8491          "Vector width mismatch between index and data");
8492   assert(isa<ConstantSDNode>(N->getScale()) &&
8493          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
8494          "Scale should be a constant power of 2");
8495 
8496   CSEMap.InsertNode(N, IP);
8497   InsertNode(N);
8498   SDValue V(N, 0);
8499   NewSDValueDbgMsg(V, "Creating new node: ", this);
8500   return V;
8501 }
8502 
8503 SDValue SelectionDAG::getScatterVP(SDVTList VTs, EVT VT, const SDLoc &dl,
8504                                    ArrayRef<SDValue> Ops,
8505                                    MachineMemOperand *MMO,
8506                                    ISD::MemIndexType IndexType) {
8507   assert(Ops.size() == 7 && "Incompatible number of operands");
8508 
8509   FoldingSetNodeID ID;
8510   AddNodeIDNode(ID, ISD::VP_SCATTER, VTs, Ops);
8511   ID.AddInteger(VT.getRawBits());
8512   ID.AddInteger(getSyntheticNodeSubclassData<VPScatterSDNode>(
8513       dl.getIROrder(), VTs, VT, MMO, IndexType));
8514   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8515   ID.AddInteger(MMO->getFlags());
8516   void *IP = nullptr;
8517   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8518     cast<VPScatterSDNode>(E)->refineAlignment(MMO);
8519     return SDValue(E, 0);
8520   }
8521   auto *N = newSDNode<VPScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
8522                                        VT, MMO, IndexType);
8523   createOperands(N, Ops);
8524 
8525   assert(N->getMask().getValueType().getVectorElementCount() ==
8526              N->getValue().getValueType().getVectorElementCount() &&
8527          "Vector width mismatch between mask and data");
8528   assert(
8529       N->getIndex().getValueType().getVectorElementCount().isScalable() ==
8530           N->getValue().getValueType().getVectorElementCount().isScalable() &&
8531       "Scalable flags of index and data do not match");
8532   assert(ElementCount::isKnownGE(
8533              N->getIndex().getValueType().getVectorElementCount(),
8534              N->getValue().getValueType().getVectorElementCount()) &&
8535          "Vector width mismatch between index and data");
8536   assert(isa<ConstantSDNode>(N->getScale()) &&
8537          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
8538          "Scale should be a constant power of 2");
8539 
8540   CSEMap.InsertNode(N, IP);
8541   InsertNode(N);
8542   SDValue V(N, 0);
8543   NewSDValueDbgMsg(V, "Creating new node: ", this);
8544   return V;
8545 }
8546 
8547 SDValue SelectionDAG::getMaskedLoad(EVT VT, const SDLoc &dl, SDValue Chain,
8548                                     SDValue Base, SDValue Offset, SDValue Mask,
8549                                     SDValue PassThru, EVT MemVT,
8550                                     MachineMemOperand *MMO,
8551                                     ISD::MemIndexedMode AM,
8552                                     ISD::LoadExtType ExtTy, bool isExpanding) {
8553   bool Indexed = AM != ISD::UNINDEXED;
8554   assert((Indexed || Offset.isUndef()) &&
8555          "Unindexed masked load with an offset!");
8556   SDVTList VTs = Indexed ? getVTList(VT, Base.getValueType(), MVT::Other)
8557                          : getVTList(VT, MVT::Other);
8558   SDValue Ops[] = {Chain, Base, Offset, Mask, PassThru};
8559   FoldingSetNodeID ID;
8560   AddNodeIDNode(ID, ISD::MLOAD, VTs, Ops);
8561   ID.AddInteger(MemVT.getRawBits());
8562   ID.AddInteger(getSyntheticNodeSubclassData<MaskedLoadSDNode>(
8563       dl.getIROrder(), VTs, AM, ExtTy, isExpanding, MemVT, MMO));
8564   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8565   ID.AddInteger(MMO->getFlags());
8566   void *IP = nullptr;
8567   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8568     cast<MaskedLoadSDNode>(E)->refineAlignment(MMO);
8569     return SDValue(E, 0);
8570   }
8571   auto *N = newSDNode<MaskedLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
8572                                         AM, ExtTy, isExpanding, MemVT, MMO);
8573   createOperands(N, Ops);
8574 
8575   CSEMap.InsertNode(N, IP);
8576   InsertNode(N);
8577   SDValue V(N, 0);
8578   NewSDValueDbgMsg(V, "Creating new node: ", this);
8579   return V;
8580 }
8581 
8582 SDValue SelectionDAG::getIndexedMaskedLoad(SDValue OrigLoad, const SDLoc &dl,
8583                                            SDValue Base, SDValue Offset,
8584                                            ISD::MemIndexedMode AM) {
8585   MaskedLoadSDNode *LD = cast<MaskedLoadSDNode>(OrigLoad);
8586   assert(LD->getOffset().isUndef() && "Masked load is already a indexed load!");
8587   return getMaskedLoad(OrigLoad.getValueType(), dl, LD->getChain(), Base,
8588                        Offset, LD->getMask(), LD->getPassThru(),
8589                        LD->getMemoryVT(), LD->getMemOperand(), AM,
8590                        LD->getExtensionType(), LD->isExpandingLoad());
8591 }
8592 
8593 SDValue SelectionDAG::getMaskedStore(SDValue Chain, const SDLoc &dl,
8594                                      SDValue Val, SDValue Base, SDValue Offset,
8595                                      SDValue Mask, EVT MemVT,
8596                                      MachineMemOperand *MMO,
8597                                      ISD::MemIndexedMode AM, bool IsTruncating,
8598                                      bool IsCompressing) {
8599   assert(Chain.getValueType() == MVT::Other &&
8600         "Invalid chain type");
8601   bool Indexed = AM != ISD::UNINDEXED;
8602   assert((Indexed || Offset.isUndef()) &&
8603          "Unindexed masked store with an offset!");
8604   SDVTList VTs = Indexed ? getVTList(Base.getValueType(), MVT::Other)
8605                          : getVTList(MVT::Other);
8606   SDValue Ops[] = {Chain, Val, Base, Offset, Mask};
8607   FoldingSetNodeID ID;
8608   AddNodeIDNode(ID, ISD::MSTORE, VTs, Ops);
8609   ID.AddInteger(MemVT.getRawBits());
8610   ID.AddInteger(getSyntheticNodeSubclassData<MaskedStoreSDNode>(
8611       dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
8612   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8613   ID.AddInteger(MMO->getFlags());
8614   void *IP = nullptr;
8615   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8616     cast<MaskedStoreSDNode>(E)->refineAlignment(MMO);
8617     return SDValue(E, 0);
8618   }
8619   auto *N =
8620       newSDNode<MaskedStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
8621                                    IsTruncating, IsCompressing, MemVT, MMO);
8622   createOperands(N, Ops);
8623 
8624   CSEMap.InsertNode(N, IP);
8625   InsertNode(N);
8626   SDValue V(N, 0);
8627   NewSDValueDbgMsg(V, "Creating new node: ", this);
8628   return V;
8629 }
8630 
8631 SDValue SelectionDAG::getIndexedMaskedStore(SDValue OrigStore, const SDLoc &dl,
8632                                             SDValue Base, SDValue Offset,
8633                                             ISD::MemIndexedMode AM) {
8634   MaskedStoreSDNode *ST = cast<MaskedStoreSDNode>(OrigStore);
8635   assert(ST->getOffset().isUndef() &&
8636          "Masked store is already a indexed store!");
8637   return getMaskedStore(ST->getChain(), dl, ST->getValue(), Base, Offset,
8638                         ST->getMask(), ST->getMemoryVT(), ST->getMemOperand(),
8639                         AM, ST->isTruncatingStore(), ST->isCompressingStore());
8640 }
8641 
8642 SDValue SelectionDAG::getMaskedGather(SDVTList VTs, EVT MemVT, const SDLoc &dl,
8643                                       ArrayRef<SDValue> Ops,
8644                                       MachineMemOperand *MMO,
8645                                       ISD::MemIndexType IndexType,
8646                                       ISD::LoadExtType ExtTy) {
8647   assert(Ops.size() == 6 && "Incompatible number of operands");
8648 
8649   FoldingSetNodeID ID;
8650   AddNodeIDNode(ID, ISD::MGATHER, VTs, Ops);
8651   ID.AddInteger(MemVT.getRawBits());
8652   ID.AddInteger(getSyntheticNodeSubclassData<MaskedGatherSDNode>(
8653       dl.getIROrder(), VTs, MemVT, MMO, IndexType, ExtTy));
8654   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8655   ID.AddInteger(MMO->getFlags());
8656   void *IP = nullptr;
8657   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8658     cast<MaskedGatherSDNode>(E)->refineAlignment(MMO);
8659     return SDValue(E, 0);
8660   }
8661 
8662   auto *N = newSDNode<MaskedGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(),
8663                                           VTs, MemVT, MMO, IndexType, ExtTy);
8664   createOperands(N, Ops);
8665 
8666   assert(N->getPassThru().getValueType() == N->getValueType(0) &&
8667          "Incompatible type of the PassThru value in MaskedGatherSDNode");
8668   assert(N->getMask().getValueType().getVectorElementCount() ==
8669              N->getValueType(0).getVectorElementCount() &&
8670          "Vector width mismatch between mask and data");
8671   assert(N->getIndex().getValueType().getVectorElementCount().isScalable() ==
8672              N->getValueType(0).getVectorElementCount().isScalable() &&
8673          "Scalable flags of index and data do not match");
8674   assert(ElementCount::isKnownGE(
8675              N->getIndex().getValueType().getVectorElementCount(),
8676              N->getValueType(0).getVectorElementCount()) &&
8677          "Vector width mismatch between index and data");
8678   assert(isa<ConstantSDNode>(N->getScale()) &&
8679          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
8680          "Scale should be a constant power of 2");
8681 
8682   CSEMap.InsertNode(N, IP);
8683   InsertNode(N);
8684   SDValue V(N, 0);
8685   NewSDValueDbgMsg(V, "Creating new node: ", this);
8686   return V;
8687 }
8688 
8689 SDValue SelectionDAG::getMaskedScatter(SDVTList VTs, EVT MemVT, const SDLoc &dl,
8690                                        ArrayRef<SDValue> Ops,
8691                                        MachineMemOperand *MMO,
8692                                        ISD::MemIndexType IndexType,
8693                                        bool IsTrunc) {
8694   assert(Ops.size() == 6 && "Incompatible number of operands");
8695 
8696   FoldingSetNodeID ID;
8697   AddNodeIDNode(ID, ISD::MSCATTER, VTs, Ops);
8698   ID.AddInteger(MemVT.getRawBits());
8699   ID.AddInteger(getSyntheticNodeSubclassData<MaskedScatterSDNode>(
8700       dl.getIROrder(), VTs, MemVT, MMO, IndexType, IsTrunc));
8701   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8702   ID.AddInteger(MMO->getFlags());
8703   void *IP = nullptr;
8704   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8705     cast<MaskedScatterSDNode>(E)->refineAlignment(MMO);
8706     return SDValue(E, 0);
8707   }
8708 
8709   auto *N = newSDNode<MaskedScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(),
8710                                            VTs, MemVT, MMO, IndexType, IsTrunc);
8711   createOperands(N, Ops);
8712 
8713   assert(N->getMask().getValueType().getVectorElementCount() ==
8714              N->getValue().getValueType().getVectorElementCount() &&
8715          "Vector width mismatch between mask and data");
8716   assert(
8717       N->getIndex().getValueType().getVectorElementCount().isScalable() ==
8718           N->getValue().getValueType().getVectorElementCount().isScalable() &&
8719       "Scalable flags of index and data do not match");
8720   assert(ElementCount::isKnownGE(
8721              N->getIndex().getValueType().getVectorElementCount(),
8722              N->getValue().getValueType().getVectorElementCount()) &&
8723          "Vector width mismatch between index and data");
8724   assert(isa<ConstantSDNode>(N->getScale()) &&
8725          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
8726          "Scale should be a constant power of 2");
8727 
8728   CSEMap.InsertNode(N, IP);
8729   InsertNode(N);
8730   SDValue V(N, 0);
8731   NewSDValueDbgMsg(V, "Creating new node: ", this);
8732   return V;
8733 }
8734 
8735 SDValue SelectionDAG::simplifySelect(SDValue Cond, SDValue T, SDValue F) {
8736   // select undef, T, F --> T (if T is a constant), otherwise F
8737   // select, ?, undef, F --> F
8738   // select, ?, T, undef --> T
8739   if (Cond.isUndef())
8740     return isConstantValueOfAnyType(T) ? T : F;
8741   if (T.isUndef())
8742     return F;
8743   if (F.isUndef())
8744     return T;
8745 
8746   // select true, T, F --> T
8747   // select false, T, F --> F
8748   if (auto *CondC = dyn_cast<ConstantSDNode>(Cond))
8749     return CondC->isZero() ? F : T;
8750 
8751   // TODO: This should simplify VSELECT with constant condition using something
8752   // like this (but check boolean contents to be complete?):
8753   //  if (ISD::isBuildVectorAllOnes(Cond.getNode()))
8754   //    return T;
8755   //  if (ISD::isBuildVectorAllZeros(Cond.getNode()))
8756   //    return F;
8757 
8758   // select ?, T, T --> T
8759   if (T == F)
8760     return T;
8761 
8762   return SDValue();
8763 }
8764 
8765 SDValue SelectionDAG::simplifyShift(SDValue X, SDValue Y) {
8766   // shift undef, Y --> 0 (can always assume that the undef value is 0)
8767   if (X.isUndef())
8768     return getConstant(0, SDLoc(X.getNode()), X.getValueType());
8769   // shift X, undef --> undef (because it may shift by the bitwidth)
8770   if (Y.isUndef())
8771     return getUNDEF(X.getValueType());
8772 
8773   // shift 0, Y --> 0
8774   // shift X, 0 --> X
8775   if (isNullOrNullSplat(X) || isNullOrNullSplat(Y))
8776     return X;
8777 
8778   // shift X, C >= bitwidth(X) --> undef
8779   // All vector elements must be too big (or undef) to avoid partial undefs.
8780   auto isShiftTooBig = [X](ConstantSDNode *Val) {
8781     return !Val || Val->getAPIntValue().uge(X.getScalarValueSizeInBits());
8782   };
8783   if (ISD::matchUnaryPredicate(Y, isShiftTooBig, true))
8784     return getUNDEF(X.getValueType());
8785 
8786   return SDValue();
8787 }
8788 
8789 SDValue SelectionDAG::simplifyFPBinop(unsigned Opcode, SDValue X, SDValue Y,
8790                                       SDNodeFlags Flags) {
8791   // If this operation has 'nnan' or 'ninf' and at least 1 disallowed operand
8792   // (an undef operand can be chosen to be Nan/Inf), then the result of this
8793   // operation is poison. That result can be relaxed to undef.
8794   ConstantFPSDNode *XC = isConstOrConstSplatFP(X, /* AllowUndefs */ true);
8795   ConstantFPSDNode *YC = isConstOrConstSplatFP(Y, /* AllowUndefs */ true);
8796   bool HasNan = (XC && XC->getValueAPF().isNaN()) ||
8797                 (YC && YC->getValueAPF().isNaN());
8798   bool HasInf = (XC && XC->getValueAPF().isInfinity()) ||
8799                 (YC && YC->getValueAPF().isInfinity());
8800 
8801   if (Flags.hasNoNaNs() && (HasNan || X.isUndef() || Y.isUndef()))
8802     return getUNDEF(X.getValueType());
8803 
8804   if (Flags.hasNoInfs() && (HasInf || X.isUndef() || Y.isUndef()))
8805     return getUNDEF(X.getValueType());
8806 
8807   if (!YC)
8808     return SDValue();
8809 
8810   // X + -0.0 --> X
8811   if (Opcode == ISD::FADD)
8812     if (YC->getValueAPF().isNegZero())
8813       return X;
8814 
8815   // X - +0.0 --> X
8816   if (Opcode == ISD::FSUB)
8817     if (YC->getValueAPF().isPosZero())
8818       return X;
8819 
8820   // X * 1.0 --> X
8821   // X / 1.0 --> X
8822   if (Opcode == ISD::FMUL || Opcode == ISD::FDIV)
8823     if (YC->getValueAPF().isExactlyValue(1.0))
8824       return X;
8825 
8826   // X * 0.0 --> 0.0
8827   if (Opcode == ISD::FMUL && Flags.hasNoNaNs() && Flags.hasNoSignedZeros())
8828     if (YC->getValueAPF().isZero())
8829       return getConstantFP(0.0, SDLoc(Y), Y.getValueType());
8830 
8831   return SDValue();
8832 }
8833 
8834 SDValue SelectionDAG::getVAArg(EVT VT, const SDLoc &dl, SDValue Chain,
8835                                SDValue Ptr, SDValue SV, unsigned Align) {
8836   SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, dl, MVT::i32) };
8837   return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops);
8838 }
8839 
8840 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8841                               ArrayRef<SDUse> Ops) {
8842   switch (Ops.size()) {
8843   case 0: return getNode(Opcode, DL, VT);
8844   case 1: return getNode(Opcode, DL, VT, static_cast<const SDValue>(Ops[0]));
8845   case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
8846   case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
8847   default: break;
8848   }
8849 
8850   // Copy from an SDUse array into an SDValue array for use with
8851   // the regular getNode logic.
8852   SmallVector<SDValue, 8> NewOps(Ops.begin(), Ops.end());
8853   return getNode(Opcode, DL, VT, NewOps);
8854 }
8855 
8856 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8857                               ArrayRef<SDValue> Ops) {
8858   SDNodeFlags Flags;
8859   if (Inserter)
8860     Flags = Inserter->getFlags();
8861   return getNode(Opcode, DL, VT, Ops, Flags);
8862 }
8863 
8864 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8865                               ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
8866   unsigned NumOps = Ops.size();
8867   switch (NumOps) {
8868   case 0: return getNode(Opcode, DL, VT);
8869   case 1: return getNode(Opcode, DL, VT, Ops[0], Flags);
8870   case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Flags);
8871   case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2], Flags);
8872   default: break;
8873   }
8874 
8875 #ifndef NDEBUG
8876   for (auto &Op : Ops)
8877     assert(Op.getOpcode() != ISD::DELETED_NODE &&
8878            "Operand is DELETED_NODE!");
8879 #endif
8880 
8881   switch (Opcode) {
8882   default: break;
8883   case ISD::BUILD_VECTOR:
8884     // Attempt to simplify BUILD_VECTOR.
8885     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
8886       return V;
8887     break;
8888   case ISD::CONCAT_VECTORS:
8889     if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
8890       return V;
8891     break;
8892   case ISD::SELECT_CC:
8893     assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
8894     assert(Ops[0].getValueType() == Ops[1].getValueType() &&
8895            "LHS and RHS of condition must have same type!");
8896     assert(Ops[2].getValueType() == Ops[3].getValueType() &&
8897            "True and False arms of SelectCC must have same type!");
8898     assert(Ops[2].getValueType() == VT &&
8899            "select_cc node must be of same type as true and false value!");
8900     break;
8901   case ISD::BR_CC:
8902     assert(NumOps == 5 && "BR_CC takes 5 operands!");
8903     assert(Ops[2].getValueType() == Ops[3].getValueType() &&
8904            "LHS/RHS of comparison should match types!");
8905     break;
8906   case ISD::VP_ADD:
8907   case ISD::VP_SUB:
8908     // If it is VP_ADD/VP_SUB mask operation then turn it to VP_XOR
8909     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
8910       Opcode = ISD::VP_XOR;
8911     break;
8912   case ISD::VP_MUL:
8913     // If it is VP_MUL mask operation then turn it to VP_AND
8914     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
8915       Opcode = ISD::VP_AND;
8916     break;
8917   case ISD::VP_REDUCE_MUL:
8918     // If it is VP_REDUCE_MUL mask operation then turn it to VP_REDUCE_AND
8919     if (VT == MVT::i1)
8920       Opcode = ISD::VP_REDUCE_AND;
8921     break;
8922   case ISD::VP_REDUCE_ADD:
8923     // If it is VP_REDUCE_ADD mask operation then turn it to VP_REDUCE_XOR
8924     if (VT == MVT::i1)
8925       Opcode = ISD::VP_REDUCE_XOR;
8926     break;
8927   case ISD::VP_REDUCE_SMAX:
8928   case ISD::VP_REDUCE_UMIN:
8929     // If it is VP_REDUCE_SMAX/VP_REDUCE_UMIN mask operation then turn it to
8930     // VP_REDUCE_AND.
8931     if (VT == MVT::i1)
8932       Opcode = ISD::VP_REDUCE_AND;
8933     break;
8934   case ISD::VP_REDUCE_SMIN:
8935   case ISD::VP_REDUCE_UMAX:
8936     // If it is VP_REDUCE_SMIN/VP_REDUCE_UMAX mask operation then turn it to
8937     // VP_REDUCE_OR.
8938     if (VT == MVT::i1)
8939       Opcode = ISD::VP_REDUCE_OR;
8940     break;
8941   }
8942 
8943   // Memoize nodes.
8944   SDNode *N;
8945   SDVTList VTs = getVTList(VT);
8946 
8947   if (VT != MVT::Glue) {
8948     FoldingSetNodeID ID;
8949     AddNodeIDNode(ID, Opcode, VTs, Ops);
8950     void *IP = nullptr;
8951 
8952     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
8953       return SDValue(E, 0);
8954 
8955     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
8956     createOperands(N, Ops);
8957 
8958     CSEMap.InsertNode(N, IP);
8959   } else {
8960     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
8961     createOperands(N, Ops);
8962   }
8963 
8964   N->setFlags(Flags);
8965   InsertNode(N);
8966   SDValue V(N, 0);
8967   NewSDValueDbgMsg(V, "Creating new node: ", this);
8968   return V;
8969 }
8970 
8971 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
8972                               ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) {
8973   return getNode(Opcode, DL, getVTList(ResultTys), Ops);
8974 }
8975 
8976 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8977                               ArrayRef<SDValue> Ops) {
8978   SDNodeFlags Flags;
8979   if (Inserter)
8980     Flags = Inserter->getFlags();
8981   return getNode(Opcode, DL, VTList, Ops, Flags);
8982 }
8983 
8984 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8985                               ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
8986   if (VTList.NumVTs == 1)
8987     return getNode(Opcode, DL, VTList.VTs[0], Ops, Flags);
8988 
8989 #ifndef NDEBUG
8990   for (auto &Op : Ops)
8991     assert(Op.getOpcode() != ISD::DELETED_NODE &&
8992            "Operand is DELETED_NODE!");
8993 #endif
8994 
8995   switch (Opcode) {
8996   case ISD::STRICT_FP_EXTEND:
8997     assert(VTList.NumVTs == 2 && Ops.size() == 2 &&
8998            "Invalid STRICT_FP_EXTEND!");
8999     assert(VTList.VTs[0].isFloatingPoint() &&
9000            Ops[1].getValueType().isFloatingPoint() && "Invalid FP cast!");
9001     assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
9002            "STRICT_FP_EXTEND result type should be vector iff the operand "
9003            "type is vector!");
9004     assert((!VTList.VTs[0].isVector() ||
9005             VTList.VTs[0].getVectorNumElements() ==
9006             Ops[1].getValueType().getVectorNumElements()) &&
9007            "Vector element count mismatch!");
9008     assert(Ops[1].getValueType().bitsLT(VTList.VTs[0]) &&
9009            "Invalid fpext node, dst <= src!");
9010     break;
9011   case ISD::STRICT_FP_ROUND:
9012     assert(VTList.NumVTs == 2 && Ops.size() == 3 && "Invalid STRICT_FP_ROUND!");
9013     assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
9014            "STRICT_FP_ROUND result type should be vector iff the operand "
9015            "type is vector!");
9016     assert((!VTList.VTs[0].isVector() ||
9017             VTList.VTs[0].getVectorNumElements() ==
9018             Ops[1].getValueType().getVectorNumElements()) &&
9019            "Vector element count mismatch!");
9020     assert(VTList.VTs[0].isFloatingPoint() &&
9021            Ops[1].getValueType().isFloatingPoint() &&
9022            VTList.VTs[0].bitsLT(Ops[1].getValueType()) &&
9023            isa<ConstantSDNode>(Ops[2]) &&
9024            (cast<ConstantSDNode>(Ops[2])->getZExtValue() == 0 ||
9025             cast<ConstantSDNode>(Ops[2])->getZExtValue() == 1) &&
9026            "Invalid STRICT_FP_ROUND!");
9027     break;
9028 #if 0
9029   // FIXME: figure out how to safely handle things like
9030   // int foo(int x) { return 1 << (x & 255); }
9031   // int bar() { return foo(256); }
9032   case ISD::SRA_PARTS:
9033   case ISD::SRL_PARTS:
9034   case ISD::SHL_PARTS:
9035     if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
9036         cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
9037       return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
9038     else if (N3.getOpcode() == ISD::AND)
9039       if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
9040         // If the and is only masking out bits that cannot effect the shift,
9041         // eliminate the and.
9042         unsigned NumBits = VT.getScalarSizeInBits()*2;
9043         if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
9044           return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
9045       }
9046     break;
9047 #endif
9048   }
9049 
9050   // Memoize the node unless it returns a flag.
9051   SDNode *N;
9052   if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
9053     FoldingSetNodeID ID;
9054     AddNodeIDNode(ID, Opcode, VTList, Ops);
9055     void *IP = nullptr;
9056     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
9057       return SDValue(E, 0);
9058 
9059     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
9060     createOperands(N, Ops);
9061     CSEMap.InsertNode(N, IP);
9062   } else {
9063     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
9064     createOperands(N, Ops);
9065   }
9066 
9067   N->setFlags(Flags);
9068   InsertNode(N);
9069   SDValue V(N, 0);
9070   NewSDValueDbgMsg(V, "Creating new node: ", this);
9071   return V;
9072 }
9073 
9074 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
9075                               SDVTList VTList) {
9076   return getNode(Opcode, DL, VTList, None);
9077 }
9078 
9079 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
9080                               SDValue N1) {
9081   SDValue Ops[] = { N1 };
9082   return getNode(Opcode, DL, VTList, Ops);
9083 }
9084 
9085 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
9086                               SDValue N1, SDValue N2) {
9087   SDValue Ops[] = { N1, N2 };
9088   return getNode(Opcode, DL, VTList, Ops);
9089 }
9090 
9091 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
9092                               SDValue N1, SDValue N2, SDValue N3) {
9093   SDValue Ops[] = { N1, N2, N3 };
9094   return getNode(Opcode, DL, VTList, Ops);
9095 }
9096 
9097 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
9098                               SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
9099   SDValue Ops[] = { N1, N2, N3, N4 };
9100   return getNode(Opcode, DL, VTList, Ops);
9101 }
9102 
9103 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
9104                               SDValue N1, SDValue N2, SDValue N3, SDValue N4,
9105                               SDValue N5) {
9106   SDValue Ops[] = { N1, N2, N3, N4, N5 };
9107   return getNode(Opcode, DL, VTList, Ops);
9108 }
9109 
9110 SDVTList SelectionDAG::getVTList(EVT VT) {
9111   return makeVTList(SDNode::getValueTypeList(VT), 1);
9112 }
9113 
9114 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2) {
9115   FoldingSetNodeID ID;
9116   ID.AddInteger(2U);
9117   ID.AddInteger(VT1.getRawBits());
9118   ID.AddInteger(VT2.getRawBits());
9119 
9120   void *IP = nullptr;
9121   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
9122   if (!Result) {
9123     EVT *Array = Allocator.Allocate<EVT>(2);
9124     Array[0] = VT1;
9125     Array[1] = VT2;
9126     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 2);
9127     VTListMap.InsertNode(Result, IP);
9128   }
9129   return Result->getSDVTList();
9130 }
9131 
9132 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3) {
9133   FoldingSetNodeID ID;
9134   ID.AddInteger(3U);
9135   ID.AddInteger(VT1.getRawBits());
9136   ID.AddInteger(VT2.getRawBits());
9137   ID.AddInteger(VT3.getRawBits());
9138 
9139   void *IP = nullptr;
9140   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
9141   if (!Result) {
9142     EVT *Array = Allocator.Allocate<EVT>(3);
9143     Array[0] = VT1;
9144     Array[1] = VT2;
9145     Array[2] = VT3;
9146     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 3);
9147     VTListMap.InsertNode(Result, IP);
9148   }
9149   return Result->getSDVTList();
9150 }
9151 
9152 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4) {
9153   FoldingSetNodeID ID;
9154   ID.AddInteger(4U);
9155   ID.AddInteger(VT1.getRawBits());
9156   ID.AddInteger(VT2.getRawBits());
9157   ID.AddInteger(VT3.getRawBits());
9158   ID.AddInteger(VT4.getRawBits());
9159 
9160   void *IP = nullptr;
9161   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
9162   if (!Result) {
9163     EVT *Array = Allocator.Allocate<EVT>(4);
9164     Array[0] = VT1;
9165     Array[1] = VT2;
9166     Array[2] = VT3;
9167     Array[3] = VT4;
9168     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 4);
9169     VTListMap.InsertNode(Result, IP);
9170   }
9171   return Result->getSDVTList();
9172 }
9173 
9174 SDVTList SelectionDAG::getVTList(ArrayRef<EVT> VTs) {
9175   unsigned NumVTs = VTs.size();
9176   FoldingSetNodeID ID;
9177   ID.AddInteger(NumVTs);
9178   for (unsigned index = 0; index < NumVTs; index++) {
9179     ID.AddInteger(VTs[index].getRawBits());
9180   }
9181 
9182   void *IP = nullptr;
9183   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
9184   if (!Result) {
9185     EVT *Array = Allocator.Allocate<EVT>(NumVTs);
9186     llvm::copy(VTs, Array);
9187     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, NumVTs);
9188     VTListMap.InsertNode(Result, IP);
9189   }
9190   return Result->getSDVTList();
9191 }
9192 
9193 
9194 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
9195 /// specified operands.  If the resultant node already exists in the DAG,
9196 /// this does not modify the specified node, instead it returns the node that
9197 /// already exists.  If the resultant node does not exist in the DAG, the
9198 /// input node is returned.  As a degenerate case, if you specify the same
9199 /// input operands as the node already has, the input node is returned.
9200 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op) {
9201   assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
9202 
9203   // Check to see if there is no change.
9204   if (Op == N->getOperand(0)) return N;
9205 
9206   // See if the modified node already exists.
9207   void *InsertPos = nullptr;
9208   if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
9209     return Existing;
9210 
9211   // Nope it doesn't.  Remove the node from its current place in the maps.
9212   if (InsertPos)
9213     if (!RemoveNodeFromCSEMaps(N))
9214       InsertPos = nullptr;
9215 
9216   // Now we update the operands.
9217   N->OperandList[0].set(Op);
9218 
9219   updateDivergence(N);
9220   // If this gets put into a CSE map, add it.
9221   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
9222   return N;
9223 }
9224 
9225 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2) {
9226   assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
9227 
9228   // Check to see if there is no change.
9229   if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
9230     return N;   // No operands changed, just return the input node.
9231 
9232   // See if the modified node already exists.
9233   void *InsertPos = nullptr;
9234   if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
9235     return Existing;
9236 
9237   // Nope it doesn't.  Remove the node from its current place in the maps.
9238   if (InsertPos)
9239     if (!RemoveNodeFromCSEMaps(N))
9240       InsertPos = nullptr;
9241 
9242   // Now we update the operands.
9243   if (N->OperandList[0] != Op1)
9244     N->OperandList[0].set(Op1);
9245   if (N->OperandList[1] != Op2)
9246     N->OperandList[1].set(Op2);
9247 
9248   updateDivergence(N);
9249   // If this gets put into a CSE map, add it.
9250   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
9251   return N;
9252 }
9253 
9254 SDNode *SelectionDAG::
9255 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, SDValue Op3) {
9256   SDValue Ops[] = { Op1, Op2, Op3 };
9257   return UpdateNodeOperands(N, Ops);
9258 }
9259 
9260 SDNode *SelectionDAG::
9261 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
9262                    SDValue Op3, SDValue Op4) {
9263   SDValue Ops[] = { Op1, Op2, Op3, Op4 };
9264   return UpdateNodeOperands(N, Ops);
9265 }
9266 
9267 SDNode *SelectionDAG::
9268 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
9269                    SDValue Op3, SDValue Op4, SDValue Op5) {
9270   SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 };
9271   return UpdateNodeOperands(N, Ops);
9272 }
9273 
9274 SDNode *SelectionDAG::
9275 UpdateNodeOperands(SDNode *N, ArrayRef<SDValue> Ops) {
9276   unsigned NumOps = Ops.size();
9277   assert(N->getNumOperands() == NumOps &&
9278          "Update with wrong number of operands");
9279 
9280   // If no operands changed just return the input node.
9281   if (std::equal(Ops.begin(), Ops.end(), N->op_begin()))
9282     return N;
9283 
9284   // See if the modified node already exists.
9285   void *InsertPos = nullptr;
9286   if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertPos))
9287     return Existing;
9288 
9289   // Nope it doesn't.  Remove the node from its current place in the maps.
9290   if (InsertPos)
9291     if (!RemoveNodeFromCSEMaps(N))
9292       InsertPos = nullptr;
9293 
9294   // Now we update the operands.
9295   for (unsigned i = 0; i != NumOps; ++i)
9296     if (N->OperandList[i] != Ops[i])
9297       N->OperandList[i].set(Ops[i]);
9298 
9299   updateDivergence(N);
9300   // If this gets put into a CSE map, add it.
9301   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
9302   return N;
9303 }
9304 
9305 /// DropOperands - Release the operands and set this node to have
9306 /// zero operands.
9307 void SDNode::DropOperands() {
9308   // Unlike the code in MorphNodeTo that does this, we don't need to
9309   // watch for dead nodes here.
9310   for (op_iterator I = op_begin(), E = op_end(); I != E; ) {
9311     SDUse &Use = *I++;
9312     Use.set(SDValue());
9313   }
9314 }
9315 
9316 void SelectionDAG::setNodeMemRefs(MachineSDNode *N,
9317                                   ArrayRef<MachineMemOperand *> NewMemRefs) {
9318   if (NewMemRefs.empty()) {
9319     N->clearMemRefs();
9320     return;
9321   }
9322 
9323   // Check if we can avoid allocating by storing a single reference directly.
9324   if (NewMemRefs.size() == 1) {
9325     N->MemRefs = NewMemRefs[0];
9326     N->NumMemRefs = 1;
9327     return;
9328   }
9329 
9330   MachineMemOperand **MemRefsBuffer =
9331       Allocator.template Allocate<MachineMemOperand *>(NewMemRefs.size());
9332   llvm::copy(NewMemRefs, MemRefsBuffer);
9333   N->MemRefs = MemRefsBuffer;
9334   N->NumMemRefs = static_cast<int>(NewMemRefs.size());
9335 }
9336 
9337 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a
9338 /// machine opcode.
9339 ///
9340 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9341                                    EVT VT) {
9342   SDVTList VTs = getVTList(VT);
9343   return SelectNodeTo(N, MachineOpc, VTs, None);
9344 }
9345 
9346 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9347                                    EVT VT, SDValue Op1) {
9348   SDVTList VTs = getVTList(VT);
9349   SDValue Ops[] = { Op1 };
9350   return SelectNodeTo(N, MachineOpc, VTs, Ops);
9351 }
9352 
9353 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9354                                    EVT VT, SDValue Op1,
9355                                    SDValue Op2) {
9356   SDVTList VTs = getVTList(VT);
9357   SDValue Ops[] = { Op1, Op2 };
9358   return SelectNodeTo(N, MachineOpc, VTs, Ops);
9359 }
9360 
9361 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9362                                    EVT VT, SDValue Op1,
9363                                    SDValue Op2, SDValue Op3) {
9364   SDVTList VTs = getVTList(VT);
9365   SDValue Ops[] = { Op1, Op2, Op3 };
9366   return SelectNodeTo(N, MachineOpc, VTs, Ops);
9367 }
9368 
9369 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9370                                    EVT VT, ArrayRef<SDValue> Ops) {
9371   SDVTList VTs = getVTList(VT);
9372   return SelectNodeTo(N, MachineOpc, VTs, Ops);
9373 }
9374 
9375 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9376                                    EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) {
9377   SDVTList VTs = getVTList(VT1, VT2);
9378   return SelectNodeTo(N, MachineOpc, VTs, Ops);
9379 }
9380 
9381 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9382                                    EVT VT1, EVT VT2) {
9383   SDVTList VTs = getVTList(VT1, VT2);
9384   return SelectNodeTo(N, MachineOpc, VTs, None);
9385 }
9386 
9387 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9388                                    EVT VT1, EVT VT2, EVT VT3,
9389                                    ArrayRef<SDValue> Ops) {
9390   SDVTList VTs = getVTList(VT1, VT2, VT3);
9391   return SelectNodeTo(N, MachineOpc, VTs, Ops);
9392 }
9393 
9394 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9395                                    EVT VT1, EVT VT2,
9396                                    SDValue Op1, SDValue Op2) {
9397   SDVTList VTs = getVTList(VT1, VT2);
9398   SDValue Ops[] = { Op1, Op2 };
9399   return SelectNodeTo(N, MachineOpc, VTs, Ops);
9400 }
9401 
9402 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9403                                    SDVTList VTs,ArrayRef<SDValue> Ops) {
9404   SDNode *New = MorphNodeTo(N, ~MachineOpc, VTs, Ops);
9405   // Reset the NodeID to -1.
9406   New->setNodeId(-1);
9407   if (New != N) {
9408     ReplaceAllUsesWith(N, New);
9409     RemoveDeadNode(N);
9410   }
9411   return New;
9412 }
9413 
9414 /// UpdateSDLocOnMergeSDNode - If the opt level is -O0 then it throws away
9415 /// the line number information on the merged node since it is not possible to
9416 /// preserve the information that operation is associated with multiple lines.
9417 /// This will make the debugger working better at -O0, were there is a higher
9418 /// probability having other instructions associated with that line.
9419 ///
9420 /// For IROrder, we keep the smaller of the two
9421 SDNode *SelectionDAG::UpdateSDLocOnMergeSDNode(SDNode *N, const SDLoc &OLoc) {
9422   DebugLoc NLoc = N->getDebugLoc();
9423   if (NLoc && OptLevel == CodeGenOpt::None && OLoc.getDebugLoc() != NLoc) {
9424     N->setDebugLoc(DebugLoc());
9425   }
9426   unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder());
9427   N->setIROrder(Order);
9428   return N;
9429 }
9430 
9431 /// MorphNodeTo - This *mutates* the specified node to have the specified
9432 /// return type, opcode, and operands.
9433 ///
9434 /// Note that MorphNodeTo returns the resultant node.  If there is already a
9435 /// node of the specified opcode and operands, it returns that node instead of
9436 /// the current one.  Note that the SDLoc need not be the same.
9437 ///
9438 /// Using MorphNodeTo is faster than creating a new node and swapping it in
9439 /// with ReplaceAllUsesWith both because it often avoids allocating a new
9440 /// node, and because it doesn't require CSE recalculation for any of
9441 /// the node's users.
9442 ///
9443 /// However, note that MorphNodeTo recursively deletes dead nodes from the DAG.
9444 /// As a consequence it isn't appropriate to use from within the DAG combiner or
9445 /// the legalizer which maintain worklists that would need to be updated when
9446 /// deleting things.
9447 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
9448                                   SDVTList VTs, ArrayRef<SDValue> Ops) {
9449   // If an identical node already exists, use it.
9450   void *IP = nullptr;
9451   if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) {
9452     FoldingSetNodeID ID;
9453     AddNodeIDNode(ID, Opc, VTs, Ops);
9454     if (SDNode *ON = FindNodeOrInsertPos(ID, SDLoc(N), IP))
9455       return UpdateSDLocOnMergeSDNode(ON, SDLoc(N));
9456   }
9457 
9458   if (!RemoveNodeFromCSEMaps(N))
9459     IP = nullptr;
9460 
9461   // Start the morphing.
9462   N->NodeType = Opc;
9463   N->ValueList = VTs.VTs;
9464   N->NumValues = VTs.NumVTs;
9465 
9466   // Clear the operands list, updating used nodes to remove this from their
9467   // use list.  Keep track of any operands that become dead as a result.
9468   SmallPtrSet<SDNode*, 16> DeadNodeSet;
9469   for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
9470     SDUse &Use = *I++;
9471     SDNode *Used = Use.getNode();
9472     Use.set(SDValue());
9473     if (Used->use_empty())
9474       DeadNodeSet.insert(Used);
9475   }
9476 
9477   // For MachineNode, initialize the memory references information.
9478   if (MachineSDNode *MN = dyn_cast<MachineSDNode>(N))
9479     MN->clearMemRefs();
9480 
9481   // Swap for an appropriately sized array from the recycler.
9482   removeOperands(N);
9483   createOperands(N, Ops);
9484 
9485   // Delete any nodes that are still dead after adding the uses for the
9486   // new operands.
9487   if (!DeadNodeSet.empty()) {
9488     SmallVector<SDNode *, 16> DeadNodes;
9489     for (SDNode *N : DeadNodeSet)
9490       if (N->use_empty())
9491         DeadNodes.push_back(N);
9492     RemoveDeadNodes(DeadNodes);
9493   }
9494 
9495   if (IP)
9496     CSEMap.InsertNode(N, IP);   // Memoize the new node.
9497   return N;
9498 }
9499 
9500 SDNode* SelectionDAG::mutateStrictFPToFP(SDNode *Node) {
9501   unsigned OrigOpc = Node->getOpcode();
9502   unsigned NewOpc;
9503   switch (OrigOpc) {
9504   default:
9505     llvm_unreachable("mutateStrictFPToFP called with unexpected opcode!");
9506 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
9507   case ISD::STRICT_##DAGN: NewOpc = ISD::DAGN; break;
9508 #define CMP_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
9509   case ISD::STRICT_##DAGN: NewOpc = ISD::SETCC; break;
9510 #include "llvm/IR/ConstrainedOps.def"
9511   }
9512 
9513   assert(Node->getNumValues() == 2 && "Unexpected number of results!");
9514 
9515   // We're taking this node out of the chain, so we need to re-link things.
9516   SDValue InputChain = Node->getOperand(0);
9517   SDValue OutputChain = SDValue(Node, 1);
9518   ReplaceAllUsesOfValueWith(OutputChain, InputChain);
9519 
9520   SmallVector<SDValue, 3> Ops;
9521   for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
9522     Ops.push_back(Node->getOperand(i));
9523 
9524   SDVTList VTs = getVTList(Node->getValueType(0));
9525   SDNode *Res = MorphNodeTo(Node, NewOpc, VTs, Ops);
9526 
9527   // MorphNodeTo can operate in two ways: if an existing node with the
9528   // specified operands exists, it can just return it.  Otherwise, it
9529   // updates the node in place to have the requested operands.
9530   if (Res == Node) {
9531     // If we updated the node in place, reset the node ID.  To the isel,
9532     // this should be just like a newly allocated machine node.
9533     Res->setNodeId(-1);
9534   } else {
9535     ReplaceAllUsesWith(Node, Res);
9536     RemoveDeadNode(Node);
9537   }
9538 
9539   return Res;
9540 }
9541 
9542 /// getMachineNode - These are used for target selectors to create a new node
9543 /// with specified return type(s), MachineInstr opcode, and operands.
9544 ///
9545 /// Note that getMachineNode returns the resultant node.  If there is already a
9546 /// node of the specified opcode and operands, it returns that node instead of
9547 /// the current one.
9548 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9549                                             EVT VT) {
9550   SDVTList VTs = getVTList(VT);
9551   return getMachineNode(Opcode, dl, VTs, None);
9552 }
9553 
9554 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9555                                             EVT VT, SDValue Op1) {
9556   SDVTList VTs = getVTList(VT);
9557   SDValue Ops[] = { Op1 };
9558   return getMachineNode(Opcode, dl, VTs, Ops);
9559 }
9560 
9561 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9562                                             EVT VT, SDValue Op1, SDValue Op2) {
9563   SDVTList VTs = getVTList(VT);
9564   SDValue Ops[] = { Op1, Op2 };
9565   return getMachineNode(Opcode, dl, VTs, Ops);
9566 }
9567 
9568 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9569                                             EVT VT, SDValue Op1, SDValue Op2,
9570                                             SDValue Op3) {
9571   SDVTList VTs = getVTList(VT);
9572   SDValue Ops[] = { Op1, Op2, Op3 };
9573   return getMachineNode(Opcode, dl, VTs, Ops);
9574 }
9575 
9576 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9577                                             EVT VT, ArrayRef<SDValue> Ops) {
9578   SDVTList VTs = getVTList(VT);
9579   return getMachineNode(Opcode, dl, VTs, Ops);
9580 }
9581 
9582 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9583                                             EVT VT1, EVT VT2, SDValue Op1,
9584                                             SDValue Op2) {
9585   SDVTList VTs = getVTList(VT1, VT2);
9586   SDValue Ops[] = { Op1, Op2 };
9587   return getMachineNode(Opcode, dl, VTs, Ops);
9588 }
9589 
9590 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9591                                             EVT VT1, EVT VT2, SDValue Op1,
9592                                             SDValue Op2, SDValue Op3) {
9593   SDVTList VTs = getVTList(VT1, VT2);
9594   SDValue Ops[] = { Op1, Op2, Op3 };
9595   return getMachineNode(Opcode, dl, VTs, Ops);
9596 }
9597 
9598 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9599                                             EVT VT1, EVT VT2,
9600                                             ArrayRef<SDValue> Ops) {
9601   SDVTList VTs = getVTList(VT1, VT2);
9602   return getMachineNode(Opcode, dl, VTs, Ops);
9603 }
9604 
9605 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9606                                             EVT VT1, EVT VT2, EVT VT3,
9607                                             SDValue Op1, SDValue Op2) {
9608   SDVTList VTs = getVTList(VT1, VT2, VT3);
9609   SDValue Ops[] = { Op1, Op2 };
9610   return getMachineNode(Opcode, dl, VTs, Ops);
9611 }
9612 
9613 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9614                                             EVT VT1, EVT VT2, EVT VT3,
9615                                             SDValue Op1, SDValue Op2,
9616                                             SDValue Op3) {
9617   SDVTList VTs = getVTList(VT1, VT2, VT3);
9618   SDValue Ops[] = { Op1, Op2, Op3 };
9619   return getMachineNode(Opcode, dl, VTs, Ops);
9620 }
9621 
9622 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9623                                             EVT VT1, EVT VT2, EVT VT3,
9624                                             ArrayRef<SDValue> Ops) {
9625   SDVTList VTs = getVTList(VT1, VT2, VT3);
9626   return getMachineNode(Opcode, dl, VTs, Ops);
9627 }
9628 
9629 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9630                                             ArrayRef<EVT> ResultTys,
9631                                             ArrayRef<SDValue> Ops) {
9632   SDVTList VTs = getVTList(ResultTys);
9633   return getMachineNode(Opcode, dl, VTs, Ops);
9634 }
9635 
9636 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &DL,
9637                                             SDVTList VTs,
9638                                             ArrayRef<SDValue> Ops) {
9639   bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue;
9640   MachineSDNode *N;
9641   void *IP = nullptr;
9642 
9643   if (DoCSE) {
9644     FoldingSetNodeID ID;
9645     AddNodeIDNode(ID, ~Opcode, VTs, Ops);
9646     IP = nullptr;
9647     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
9648       return cast<MachineSDNode>(UpdateSDLocOnMergeSDNode(E, DL));
9649     }
9650   }
9651 
9652   // Allocate a new MachineSDNode.
9653   N = newSDNode<MachineSDNode>(~Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
9654   createOperands(N, Ops);
9655 
9656   if (DoCSE)
9657     CSEMap.InsertNode(N, IP);
9658 
9659   InsertNode(N);
9660   NewSDValueDbgMsg(SDValue(N, 0), "Creating new machine node: ", this);
9661   return N;
9662 }
9663 
9664 /// getTargetExtractSubreg - A convenience function for creating
9665 /// TargetOpcode::EXTRACT_SUBREG nodes.
9666 SDValue SelectionDAG::getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT,
9667                                              SDValue Operand) {
9668   SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
9669   SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,
9670                                   VT, Operand, SRIdxVal);
9671   return SDValue(Subreg, 0);
9672 }
9673 
9674 /// getTargetInsertSubreg - A convenience function for creating
9675 /// TargetOpcode::INSERT_SUBREG nodes.
9676 SDValue SelectionDAG::getTargetInsertSubreg(int SRIdx, const SDLoc &DL, EVT VT,
9677                                             SDValue Operand, SDValue Subreg) {
9678   SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
9679   SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL,
9680                                   VT, Operand, Subreg, SRIdxVal);
9681   return SDValue(Result, 0);
9682 }
9683 
9684 /// getNodeIfExists - Get the specified node if it's already available, or
9685 /// else return NULL.
9686 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
9687                                       ArrayRef<SDValue> Ops) {
9688   SDNodeFlags Flags;
9689   if (Inserter)
9690     Flags = Inserter->getFlags();
9691   return getNodeIfExists(Opcode, VTList, Ops, Flags);
9692 }
9693 
9694 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
9695                                       ArrayRef<SDValue> Ops,
9696                                       const SDNodeFlags Flags) {
9697   if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
9698     FoldingSetNodeID ID;
9699     AddNodeIDNode(ID, Opcode, VTList, Ops);
9700     void *IP = nullptr;
9701     if (SDNode *E = FindNodeOrInsertPos(ID, SDLoc(), IP)) {
9702       E->intersectFlagsWith(Flags);
9703       return E;
9704     }
9705   }
9706   return nullptr;
9707 }
9708 
9709 /// doesNodeExist - Check if a node exists without modifying its flags.
9710 bool SelectionDAG::doesNodeExist(unsigned Opcode, SDVTList VTList,
9711                                  ArrayRef<SDValue> Ops) {
9712   if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
9713     FoldingSetNodeID ID;
9714     AddNodeIDNode(ID, Opcode, VTList, Ops);
9715     void *IP = nullptr;
9716     if (FindNodeOrInsertPos(ID, SDLoc(), IP))
9717       return true;
9718   }
9719   return false;
9720 }
9721 
9722 /// getDbgValue - Creates a SDDbgValue node.
9723 ///
9724 /// SDNode
9725 SDDbgValue *SelectionDAG::getDbgValue(DIVariable *Var, DIExpression *Expr,
9726                                       SDNode *N, unsigned R, bool IsIndirect,
9727                                       const DebugLoc &DL, unsigned O) {
9728   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9729          "Expected inlined-at fields to agree");
9730   return new (DbgInfo->getAlloc())
9731       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromNode(N, R),
9732                  {}, IsIndirect, DL, O,
9733                  /*IsVariadic=*/false);
9734 }
9735 
9736 /// Constant
9737 SDDbgValue *SelectionDAG::getConstantDbgValue(DIVariable *Var,
9738                                               DIExpression *Expr,
9739                                               const Value *C,
9740                                               const DebugLoc &DL, unsigned O) {
9741   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9742          "Expected inlined-at fields to agree");
9743   return new (DbgInfo->getAlloc())
9744       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromConst(C), {},
9745                  /*IsIndirect=*/false, DL, O,
9746                  /*IsVariadic=*/false);
9747 }
9748 
9749 /// FrameIndex
9750 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var,
9751                                                 DIExpression *Expr, unsigned FI,
9752                                                 bool IsIndirect,
9753                                                 const DebugLoc &DL,
9754                                                 unsigned O) {
9755   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9756          "Expected inlined-at fields to agree");
9757   return getFrameIndexDbgValue(Var, Expr, FI, {}, IsIndirect, DL, O);
9758 }
9759 
9760 /// FrameIndex with dependencies
9761 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var,
9762                                                 DIExpression *Expr, unsigned FI,
9763                                                 ArrayRef<SDNode *> Dependencies,
9764                                                 bool IsIndirect,
9765                                                 const DebugLoc &DL,
9766                                                 unsigned O) {
9767   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9768          "Expected inlined-at fields to agree");
9769   return new (DbgInfo->getAlloc())
9770       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromFrameIdx(FI),
9771                  Dependencies, IsIndirect, DL, O,
9772                  /*IsVariadic=*/false);
9773 }
9774 
9775 /// VReg
9776 SDDbgValue *SelectionDAG::getVRegDbgValue(DIVariable *Var, DIExpression *Expr,
9777                                           unsigned VReg, bool IsIndirect,
9778                                           const DebugLoc &DL, unsigned O) {
9779   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9780          "Expected inlined-at fields to agree");
9781   return new (DbgInfo->getAlloc())
9782       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromVReg(VReg),
9783                  {}, IsIndirect, DL, O,
9784                  /*IsVariadic=*/false);
9785 }
9786 
9787 SDDbgValue *SelectionDAG::getDbgValueList(DIVariable *Var, DIExpression *Expr,
9788                                           ArrayRef<SDDbgOperand> Locs,
9789                                           ArrayRef<SDNode *> Dependencies,
9790                                           bool IsIndirect, const DebugLoc &DL,
9791                                           unsigned O, bool IsVariadic) {
9792   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9793          "Expected inlined-at fields to agree");
9794   return new (DbgInfo->getAlloc())
9795       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, Locs, Dependencies, IsIndirect,
9796                  DL, O, IsVariadic);
9797 }
9798 
9799 void SelectionDAG::transferDbgValues(SDValue From, SDValue To,
9800                                      unsigned OffsetInBits, unsigned SizeInBits,
9801                                      bool InvalidateDbg) {
9802   SDNode *FromNode = From.getNode();
9803   SDNode *ToNode = To.getNode();
9804   assert(FromNode && ToNode && "Can't modify dbg values");
9805 
9806   // PR35338
9807   // TODO: assert(From != To && "Redundant dbg value transfer");
9808   // TODO: assert(FromNode != ToNode && "Intranode dbg value transfer");
9809   if (From == To || FromNode == ToNode)
9810     return;
9811 
9812   if (!FromNode->getHasDebugValue())
9813     return;
9814 
9815   SDDbgOperand FromLocOp =
9816       SDDbgOperand::fromNode(From.getNode(), From.getResNo());
9817   SDDbgOperand ToLocOp = SDDbgOperand::fromNode(To.getNode(), To.getResNo());
9818 
9819   SmallVector<SDDbgValue *, 2> ClonedDVs;
9820   for (SDDbgValue *Dbg : GetDbgValues(FromNode)) {
9821     if (Dbg->isInvalidated())
9822       continue;
9823 
9824     // TODO: assert(!Dbg->isInvalidated() && "Transfer of invalid dbg value");
9825 
9826     // Create a new location ops vector that is equal to the old vector, but
9827     // with each instance of FromLocOp replaced with ToLocOp.
9828     bool Changed = false;
9829     auto NewLocOps = Dbg->copyLocationOps();
9830     std::replace_if(
9831         NewLocOps.begin(), NewLocOps.end(),
9832         [&Changed, FromLocOp](const SDDbgOperand &Op) {
9833           bool Match = Op == FromLocOp;
9834           Changed |= Match;
9835           return Match;
9836         },
9837         ToLocOp);
9838     // Ignore this SDDbgValue if we didn't find a matching location.
9839     if (!Changed)
9840       continue;
9841 
9842     DIVariable *Var = Dbg->getVariable();
9843     auto *Expr = Dbg->getExpression();
9844     // If a fragment is requested, update the expression.
9845     if (SizeInBits) {
9846       // When splitting a larger (e.g., sign-extended) value whose
9847       // lower bits are described with an SDDbgValue, do not attempt
9848       // to transfer the SDDbgValue to the upper bits.
9849       if (auto FI = Expr->getFragmentInfo())
9850         if (OffsetInBits + SizeInBits > FI->SizeInBits)
9851           continue;
9852       auto Fragment = DIExpression::createFragmentExpression(Expr, OffsetInBits,
9853                                                              SizeInBits);
9854       if (!Fragment)
9855         continue;
9856       Expr = *Fragment;
9857     }
9858 
9859     auto AdditionalDependencies = Dbg->getAdditionalDependencies();
9860     // Clone the SDDbgValue and move it to To.
9861     SDDbgValue *Clone = getDbgValueList(
9862         Var, Expr, NewLocOps, AdditionalDependencies, Dbg->isIndirect(),
9863         Dbg->getDebugLoc(), std::max(ToNode->getIROrder(), Dbg->getOrder()),
9864         Dbg->isVariadic());
9865     ClonedDVs.push_back(Clone);
9866 
9867     if (InvalidateDbg) {
9868       // Invalidate value and indicate the SDDbgValue should not be emitted.
9869       Dbg->setIsInvalidated();
9870       Dbg->setIsEmitted();
9871     }
9872   }
9873 
9874   for (SDDbgValue *Dbg : ClonedDVs) {
9875     assert(is_contained(Dbg->getSDNodes(), ToNode) &&
9876            "Transferred DbgValues should depend on the new SDNode");
9877     AddDbgValue(Dbg, false);
9878   }
9879 }
9880 
9881 void SelectionDAG::salvageDebugInfo(SDNode &N) {
9882   if (!N.getHasDebugValue())
9883     return;
9884 
9885   SmallVector<SDDbgValue *, 2> ClonedDVs;
9886   for (auto DV : GetDbgValues(&N)) {
9887     if (DV->isInvalidated())
9888       continue;
9889     switch (N.getOpcode()) {
9890     default:
9891       break;
9892     case ISD::ADD:
9893       SDValue N0 = N.getOperand(0);
9894       SDValue N1 = N.getOperand(1);
9895       if (!isConstantIntBuildVectorOrConstantInt(N0) &&
9896           isConstantIntBuildVectorOrConstantInt(N1)) {
9897         uint64_t Offset = N.getConstantOperandVal(1);
9898 
9899         // Rewrite an ADD constant node into a DIExpression. Since we are
9900         // performing arithmetic to compute the variable's *value* in the
9901         // DIExpression, we need to mark the expression with a
9902         // DW_OP_stack_value.
9903         auto *DIExpr = DV->getExpression();
9904         auto NewLocOps = DV->copyLocationOps();
9905         bool Changed = false;
9906         for (size_t i = 0; i < NewLocOps.size(); ++i) {
9907           // We're not given a ResNo to compare against because the whole
9908           // node is going away. We know that any ISD::ADD only has one
9909           // result, so we can assume any node match is using the result.
9910           if (NewLocOps[i].getKind() != SDDbgOperand::SDNODE ||
9911               NewLocOps[i].getSDNode() != &N)
9912             continue;
9913           NewLocOps[i] = SDDbgOperand::fromNode(N0.getNode(), N0.getResNo());
9914           SmallVector<uint64_t, 3> ExprOps;
9915           DIExpression::appendOffset(ExprOps, Offset);
9916           DIExpr = DIExpression::appendOpsToArg(DIExpr, ExprOps, i, true);
9917           Changed = true;
9918         }
9919         (void)Changed;
9920         assert(Changed && "Salvage target doesn't use N");
9921 
9922         auto AdditionalDependencies = DV->getAdditionalDependencies();
9923         SDDbgValue *Clone = getDbgValueList(DV->getVariable(), DIExpr,
9924                                             NewLocOps, AdditionalDependencies,
9925                                             DV->isIndirect(), DV->getDebugLoc(),
9926                                             DV->getOrder(), DV->isVariadic());
9927         ClonedDVs.push_back(Clone);
9928         DV->setIsInvalidated();
9929         DV->setIsEmitted();
9930         LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting";
9931                    N0.getNode()->dumprFull(this);
9932                    dbgs() << " into " << *DIExpr << '\n');
9933       }
9934     }
9935   }
9936 
9937   for (SDDbgValue *Dbg : ClonedDVs) {
9938     assert(!Dbg->getSDNodes().empty() &&
9939            "Salvaged DbgValue should depend on a new SDNode");
9940     AddDbgValue(Dbg, false);
9941   }
9942 }
9943 
9944 /// Creates a SDDbgLabel node.
9945 SDDbgLabel *SelectionDAG::getDbgLabel(DILabel *Label,
9946                                       const DebugLoc &DL, unsigned O) {
9947   assert(cast<DILabel>(Label)->isValidLocationForIntrinsic(DL) &&
9948          "Expected inlined-at fields to agree");
9949   return new (DbgInfo->getAlloc()) SDDbgLabel(Label, DL, O);
9950 }
9951 
9952 namespace {
9953 
9954 /// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node
9955 /// pointed to by a use iterator is deleted, increment the use iterator
9956 /// so that it doesn't dangle.
9957 ///
9958 class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener {
9959   SDNode::use_iterator &UI;
9960   SDNode::use_iterator &UE;
9961 
9962   void NodeDeleted(SDNode *N, SDNode *E) override {
9963     // Increment the iterator as needed.
9964     while (UI != UE && N == *UI)
9965       ++UI;
9966   }
9967 
9968 public:
9969   RAUWUpdateListener(SelectionDAG &d,
9970                      SDNode::use_iterator &ui,
9971                      SDNode::use_iterator &ue)
9972     : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {}
9973 };
9974 
9975 } // end anonymous namespace
9976 
9977 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
9978 /// This can cause recursive merging of nodes in the DAG.
9979 ///
9980 /// This version assumes From has a single result value.
9981 ///
9982 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To) {
9983   SDNode *From = FromN.getNode();
9984   assert(From->getNumValues() == 1 && FromN.getResNo() == 0 &&
9985          "Cannot replace with this method!");
9986   assert(From != To.getNode() && "Cannot replace uses of with self");
9987 
9988   // Preserve Debug Values
9989   transferDbgValues(FromN, To);
9990 
9991   // Iterate over all the existing uses of From. New uses will be added
9992   // to the beginning of the use list, which we avoid visiting.
9993   // This specifically avoids visiting uses of From that arise while the
9994   // replacement is happening, because any such uses would be the result
9995   // of CSE: If an existing node looks like From after one of its operands
9996   // is replaced by To, we don't want to replace of all its users with To
9997   // too. See PR3018 for more info.
9998   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
9999   RAUWUpdateListener Listener(*this, UI, UE);
10000   while (UI != UE) {
10001     SDNode *User = *UI;
10002 
10003     // This node is about to morph, remove its old self from the CSE maps.
10004     RemoveNodeFromCSEMaps(User);
10005 
10006     // A user can appear in a use list multiple times, and when this
10007     // happens the uses are usually next to each other in the list.
10008     // To help reduce the number of CSE recomputations, process all
10009     // the uses of this user that we can find this way.
10010     do {
10011       SDUse &Use = UI.getUse();
10012       ++UI;
10013       Use.set(To);
10014       if (To->isDivergent() != From->isDivergent())
10015         updateDivergence(User);
10016     } while (UI != UE && *UI == User);
10017     // Now that we have modified User, add it back to the CSE maps.  If it
10018     // already exists there, recursively merge the results together.
10019     AddModifiedNodeToCSEMaps(User);
10020   }
10021 
10022   // If we just RAUW'd the root, take note.
10023   if (FromN == getRoot())
10024     setRoot(To);
10025 }
10026 
10027 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
10028 /// This can cause recursive merging of nodes in the DAG.
10029 ///
10030 /// This version assumes that for each value of From, there is a
10031 /// corresponding value in To in the same position with the same type.
10032 ///
10033 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To) {
10034 #ifndef NDEBUG
10035   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
10036     assert((!From->hasAnyUseOfValue(i) ||
10037             From->getValueType(i) == To->getValueType(i)) &&
10038            "Cannot use this version of ReplaceAllUsesWith!");
10039 #endif
10040 
10041   // Handle the trivial case.
10042   if (From == To)
10043     return;
10044 
10045   // Preserve Debug Info. Only do this if there's a use.
10046   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
10047     if (From->hasAnyUseOfValue(i)) {
10048       assert((i < To->getNumValues()) && "Invalid To location");
10049       transferDbgValues(SDValue(From, i), SDValue(To, i));
10050     }
10051 
10052   // Iterate over just the existing users of From. See the comments in
10053   // the ReplaceAllUsesWith above.
10054   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
10055   RAUWUpdateListener Listener(*this, UI, UE);
10056   while (UI != UE) {
10057     SDNode *User = *UI;
10058 
10059     // This node is about to morph, remove its old self from the CSE maps.
10060     RemoveNodeFromCSEMaps(User);
10061 
10062     // A user can appear in a use list multiple times, and when this
10063     // happens the uses are usually next to each other in the list.
10064     // To help reduce the number of CSE recomputations, process all
10065     // the uses of this user that we can find this way.
10066     do {
10067       SDUse &Use = UI.getUse();
10068       ++UI;
10069       Use.setNode(To);
10070       if (To->isDivergent() != From->isDivergent())
10071         updateDivergence(User);
10072     } while (UI != UE && *UI == User);
10073 
10074     // Now that we have modified User, add it back to the CSE maps.  If it
10075     // already exists there, recursively merge the results together.
10076     AddModifiedNodeToCSEMaps(User);
10077   }
10078 
10079   // If we just RAUW'd the root, take note.
10080   if (From == getRoot().getNode())
10081     setRoot(SDValue(To, getRoot().getResNo()));
10082 }
10083 
10084 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
10085 /// This can cause recursive merging of nodes in the DAG.
10086 ///
10087 /// This version can replace From with any result values.  To must match the
10088 /// number and types of values returned by From.
10089 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, const SDValue *To) {
10090   if (From->getNumValues() == 1)  // Handle the simple case efficiently.
10091     return ReplaceAllUsesWith(SDValue(From, 0), To[0]);
10092 
10093   // Preserve Debug Info.
10094   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
10095     transferDbgValues(SDValue(From, i), To[i]);
10096 
10097   // Iterate over just the existing users of From. See the comments in
10098   // the ReplaceAllUsesWith above.
10099   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
10100   RAUWUpdateListener Listener(*this, UI, UE);
10101   while (UI != UE) {
10102     SDNode *User = *UI;
10103 
10104     // This node is about to morph, remove its old self from the CSE maps.
10105     RemoveNodeFromCSEMaps(User);
10106 
10107     // A user can appear in a use list multiple times, and when this happens the
10108     // uses are usually next to each other in the list.  To help reduce the
10109     // number of CSE and divergence recomputations, process all the uses of this
10110     // user that we can find this way.
10111     bool To_IsDivergent = false;
10112     do {
10113       SDUse &Use = UI.getUse();
10114       const SDValue &ToOp = To[Use.getResNo()];
10115       ++UI;
10116       Use.set(ToOp);
10117       To_IsDivergent |= ToOp->isDivergent();
10118     } while (UI != UE && *UI == User);
10119 
10120     if (To_IsDivergent != From->isDivergent())
10121       updateDivergence(User);
10122 
10123     // Now that we have modified User, add it back to the CSE maps.  If it
10124     // already exists there, recursively merge the results together.
10125     AddModifiedNodeToCSEMaps(User);
10126   }
10127 
10128   // If we just RAUW'd the root, take note.
10129   if (From == getRoot().getNode())
10130     setRoot(SDValue(To[getRoot().getResNo()]));
10131 }
10132 
10133 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
10134 /// uses of other values produced by From.getNode() alone.  The Deleted
10135 /// vector is handled the same way as for ReplaceAllUsesWith.
10136 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To){
10137   // Handle the really simple, really trivial case efficiently.
10138   if (From == To) return;
10139 
10140   // Handle the simple, trivial, case efficiently.
10141   if (From.getNode()->getNumValues() == 1) {
10142     ReplaceAllUsesWith(From, To);
10143     return;
10144   }
10145 
10146   // Preserve Debug Info.
10147   transferDbgValues(From, To);
10148 
10149   // Iterate over just the existing users of From. See the comments in
10150   // the ReplaceAllUsesWith above.
10151   SDNode::use_iterator UI = From.getNode()->use_begin(),
10152                        UE = From.getNode()->use_end();
10153   RAUWUpdateListener Listener(*this, UI, UE);
10154   while (UI != UE) {
10155     SDNode *User = *UI;
10156     bool UserRemovedFromCSEMaps = false;
10157 
10158     // A user can appear in a use list multiple times, and when this
10159     // happens the uses are usually next to each other in the list.
10160     // To help reduce the number of CSE recomputations, process all
10161     // the uses of this user that we can find this way.
10162     do {
10163       SDUse &Use = UI.getUse();
10164 
10165       // Skip uses of different values from the same node.
10166       if (Use.getResNo() != From.getResNo()) {
10167         ++UI;
10168         continue;
10169       }
10170 
10171       // If this node hasn't been modified yet, it's still in the CSE maps,
10172       // so remove its old self from the CSE maps.
10173       if (!UserRemovedFromCSEMaps) {
10174         RemoveNodeFromCSEMaps(User);
10175         UserRemovedFromCSEMaps = true;
10176       }
10177 
10178       ++UI;
10179       Use.set(To);
10180       if (To->isDivergent() != From->isDivergent())
10181         updateDivergence(User);
10182     } while (UI != UE && *UI == User);
10183     // We are iterating over all uses of the From node, so if a use
10184     // doesn't use the specific value, no changes are made.
10185     if (!UserRemovedFromCSEMaps)
10186       continue;
10187 
10188     // Now that we have modified User, add it back to the CSE maps.  If it
10189     // already exists there, recursively merge the results together.
10190     AddModifiedNodeToCSEMaps(User);
10191   }
10192 
10193   // If we just RAUW'd the root, take note.
10194   if (From == getRoot())
10195     setRoot(To);
10196 }
10197 
10198 namespace {
10199 
10200 /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith
10201 /// to record information about a use.
10202 struct UseMemo {
10203   SDNode *User;
10204   unsigned Index;
10205   SDUse *Use;
10206 };
10207 
10208 /// operator< - Sort Memos by User.
10209 bool operator<(const UseMemo &L, const UseMemo &R) {
10210   return (intptr_t)L.User < (intptr_t)R.User;
10211 }
10212 
10213 /// RAUOVWUpdateListener - Helper for ReplaceAllUsesOfValuesWith - When the node
10214 /// pointed to by a UseMemo is deleted, set the User to nullptr to indicate that
10215 /// the node already has been taken care of recursively.
10216 class RAUOVWUpdateListener : public SelectionDAG::DAGUpdateListener {
10217   SmallVector<UseMemo, 4> &Uses;
10218 
10219   void NodeDeleted(SDNode *N, SDNode *E) override {
10220     for (UseMemo &Memo : Uses)
10221       if (Memo.User == N)
10222         Memo.User = nullptr;
10223   }
10224 
10225 public:
10226   RAUOVWUpdateListener(SelectionDAG &d, SmallVector<UseMemo, 4> &uses)
10227       : SelectionDAG::DAGUpdateListener(d), Uses(uses) {}
10228 };
10229 
10230 } // end anonymous namespace
10231 
10232 bool SelectionDAG::calculateDivergence(SDNode *N) {
10233   if (TLI->isSDNodeAlwaysUniform(N)) {
10234     assert(!TLI->isSDNodeSourceOfDivergence(N, FLI, DA) &&
10235            "Conflicting divergence information!");
10236     return false;
10237   }
10238   if (TLI->isSDNodeSourceOfDivergence(N, FLI, DA))
10239     return true;
10240   for (auto &Op : N->ops()) {
10241     if (Op.Val.getValueType() != MVT::Other && Op.getNode()->isDivergent())
10242       return true;
10243   }
10244   return false;
10245 }
10246 
10247 void SelectionDAG::updateDivergence(SDNode *N) {
10248   SmallVector<SDNode *, 16> Worklist(1, N);
10249   do {
10250     N = Worklist.pop_back_val();
10251     bool IsDivergent = calculateDivergence(N);
10252     if (N->SDNodeBits.IsDivergent != IsDivergent) {
10253       N->SDNodeBits.IsDivergent = IsDivergent;
10254       llvm::append_range(Worklist, N->uses());
10255     }
10256   } while (!Worklist.empty());
10257 }
10258 
10259 void SelectionDAG::CreateTopologicalOrder(std::vector<SDNode *> &Order) {
10260   DenseMap<SDNode *, unsigned> Degree;
10261   Order.reserve(AllNodes.size());
10262   for (auto &N : allnodes()) {
10263     unsigned NOps = N.getNumOperands();
10264     Degree[&N] = NOps;
10265     if (0 == NOps)
10266       Order.push_back(&N);
10267   }
10268   for (size_t I = 0; I != Order.size(); ++I) {
10269     SDNode *N = Order[I];
10270     for (auto U : N->uses()) {
10271       unsigned &UnsortedOps = Degree[U];
10272       if (0 == --UnsortedOps)
10273         Order.push_back(U);
10274     }
10275   }
10276 }
10277 
10278 #ifndef NDEBUG
10279 void SelectionDAG::VerifyDAGDivergence() {
10280   std::vector<SDNode *> TopoOrder;
10281   CreateTopologicalOrder(TopoOrder);
10282   for (auto *N : TopoOrder) {
10283     assert(calculateDivergence(N) == N->isDivergent() &&
10284            "Divergence bit inconsistency detected");
10285   }
10286 }
10287 #endif
10288 
10289 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving
10290 /// uses of other values produced by From.getNode() alone.  The same value
10291 /// may appear in both the From and To list.  The Deleted vector is
10292 /// handled the same way as for ReplaceAllUsesWith.
10293 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From,
10294                                               const SDValue *To,
10295                                               unsigned Num){
10296   // Handle the simple, trivial case efficiently.
10297   if (Num == 1)
10298     return ReplaceAllUsesOfValueWith(*From, *To);
10299 
10300   transferDbgValues(*From, *To);
10301 
10302   // Read up all the uses and make records of them. This helps
10303   // processing new uses that are introduced during the
10304   // replacement process.
10305   SmallVector<UseMemo, 4> Uses;
10306   for (unsigned i = 0; i != Num; ++i) {
10307     unsigned FromResNo = From[i].getResNo();
10308     SDNode *FromNode = From[i].getNode();
10309     for (SDNode::use_iterator UI = FromNode->use_begin(),
10310          E = FromNode->use_end(); UI != E; ++UI) {
10311       SDUse &Use = UI.getUse();
10312       if (Use.getResNo() == FromResNo) {
10313         UseMemo Memo = { *UI, i, &Use };
10314         Uses.push_back(Memo);
10315       }
10316     }
10317   }
10318 
10319   // Sort the uses, so that all the uses from a given User are together.
10320   llvm::sort(Uses);
10321   RAUOVWUpdateListener Listener(*this, Uses);
10322 
10323   for (unsigned UseIndex = 0, UseIndexEnd = Uses.size();
10324        UseIndex != UseIndexEnd; ) {
10325     // We know that this user uses some value of From.  If it is the right
10326     // value, update it.
10327     SDNode *User = Uses[UseIndex].User;
10328     // If the node has been deleted by recursive CSE updates when updating
10329     // another node, then just skip this entry.
10330     if (User == nullptr) {
10331       ++UseIndex;
10332       continue;
10333     }
10334 
10335     // This node is about to morph, remove its old self from the CSE maps.
10336     RemoveNodeFromCSEMaps(User);
10337 
10338     // The Uses array is sorted, so all the uses for a given User
10339     // are next to each other in the list.
10340     // To help reduce the number of CSE recomputations, process all
10341     // the uses of this user that we can find this way.
10342     do {
10343       unsigned i = Uses[UseIndex].Index;
10344       SDUse &Use = *Uses[UseIndex].Use;
10345       ++UseIndex;
10346 
10347       Use.set(To[i]);
10348     } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User);
10349 
10350     // Now that we have modified User, add it back to the CSE maps.  If it
10351     // already exists there, recursively merge the results together.
10352     AddModifiedNodeToCSEMaps(User);
10353   }
10354 }
10355 
10356 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
10357 /// based on their topological order. It returns the maximum id and a vector
10358 /// of the SDNodes* in assigned order by reference.
10359 unsigned SelectionDAG::AssignTopologicalOrder() {
10360   unsigned DAGSize = 0;
10361 
10362   // SortedPos tracks the progress of the algorithm. Nodes before it are
10363   // sorted, nodes after it are unsorted. When the algorithm completes
10364   // it is at the end of the list.
10365   allnodes_iterator SortedPos = allnodes_begin();
10366 
10367   // Visit all the nodes. Move nodes with no operands to the front of
10368   // the list immediately. Annotate nodes that do have operands with their
10369   // operand count. Before we do this, the Node Id fields of the nodes
10370   // may contain arbitrary values. After, the Node Id fields for nodes
10371   // before SortedPos will contain the topological sort index, and the
10372   // Node Id fields for nodes At SortedPos and after will contain the
10373   // count of outstanding operands.
10374   for (SDNode &N : llvm::make_early_inc_range(allnodes())) {
10375     checkForCycles(&N, this);
10376     unsigned Degree = N.getNumOperands();
10377     if (Degree == 0) {
10378       // A node with no uses, add it to the result array immediately.
10379       N.setNodeId(DAGSize++);
10380       allnodes_iterator Q(&N);
10381       if (Q != SortedPos)
10382         SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q));
10383       assert(SortedPos != AllNodes.end() && "Overran node list");
10384       ++SortedPos;
10385     } else {
10386       // Temporarily use the Node Id as scratch space for the degree count.
10387       N.setNodeId(Degree);
10388     }
10389   }
10390 
10391   // Visit all the nodes. As we iterate, move nodes into sorted order,
10392   // such that by the time the end is reached all nodes will be sorted.
10393   for (SDNode &Node : allnodes()) {
10394     SDNode *N = &Node;
10395     checkForCycles(N, this);
10396     // N is in sorted position, so all its uses have one less operand
10397     // that needs to be sorted.
10398     for (SDNode *P : N->uses()) {
10399       unsigned Degree = P->getNodeId();
10400       assert(Degree != 0 && "Invalid node degree");
10401       --Degree;
10402       if (Degree == 0) {
10403         // All of P's operands are sorted, so P may sorted now.
10404         P->setNodeId(DAGSize++);
10405         if (P->getIterator() != SortedPos)
10406           SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P));
10407         assert(SortedPos != AllNodes.end() && "Overran node list");
10408         ++SortedPos;
10409       } else {
10410         // Update P's outstanding operand count.
10411         P->setNodeId(Degree);
10412       }
10413     }
10414     if (Node.getIterator() == SortedPos) {
10415 #ifndef NDEBUG
10416       allnodes_iterator I(N);
10417       SDNode *S = &*++I;
10418       dbgs() << "Overran sorted position:\n";
10419       S->dumprFull(this); dbgs() << "\n";
10420       dbgs() << "Checking if this is due to cycles\n";
10421       checkForCycles(this, true);
10422 #endif
10423       llvm_unreachable(nullptr);
10424     }
10425   }
10426 
10427   assert(SortedPos == AllNodes.end() &&
10428          "Topological sort incomplete!");
10429   assert(AllNodes.front().getOpcode() == ISD::EntryToken &&
10430          "First node in topological sort is not the entry token!");
10431   assert(AllNodes.front().getNodeId() == 0 &&
10432          "First node in topological sort has non-zero id!");
10433   assert(AllNodes.front().getNumOperands() == 0 &&
10434          "First node in topological sort has operands!");
10435   assert(AllNodes.back().getNodeId() == (int)DAGSize-1 &&
10436          "Last node in topologic sort has unexpected id!");
10437   assert(AllNodes.back().use_empty() &&
10438          "Last node in topologic sort has users!");
10439   assert(DAGSize == allnodes_size() && "Node count mismatch!");
10440   return DAGSize;
10441 }
10442 
10443 /// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the
10444 /// value is produced by SD.
10445 void SelectionDAG::AddDbgValue(SDDbgValue *DB, bool isParameter) {
10446   for (SDNode *SD : DB->getSDNodes()) {
10447     if (!SD)
10448       continue;
10449     assert(DbgInfo->getSDDbgValues(SD).empty() || SD->getHasDebugValue());
10450     SD->setHasDebugValue(true);
10451   }
10452   DbgInfo->add(DB, isParameter);
10453 }
10454 
10455 void SelectionDAG::AddDbgLabel(SDDbgLabel *DB) { DbgInfo->add(DB); }
10456 
10457 SDValue SelectionDAG::makeEquivalentMemoryOrdering(SDValue OldChain,
10458                                                    SDValue NewMemOpChain) {
10459   assert(isa<MemSDNode>(NewMemOpChain) && "Expected a memop node");
10460   assert(NewMemOpChain.getValueType() == MVT::Other && "Expected a token VT");
10461   // The new memory operation must have the same position as the old load in
10462   // terms of memory dependency. Create a TokenFactor for the old load and new
10463   // memory operation and update uses of the old load's output chain to use that
10464   // TokenFactor.
10465   if (OldChain == NewMemOpChain || OldChain.use_empty())
10466     return NewMemOpChain;
10467 
10468   SDValue TokenFactor = getNode(ISD::TokenFactor, SDLoc(OldChain), MVT::Other,
10469                                 OldChain, NewMemOpChain);
10470   ReplaceAllUsesOfValueWith(OldChain, TokenFactor);
10471   UpdateNodeOperands(TokenFactor.getNode(), OldChain, NewMemOpChain);
10472   return TokenFactor;
10473 }
10474 
10475 SDValue SelectionDAG::makeEquivalentMemoryOrdering(LoadSDNode *OldLoad,
10476                                                    SDValue NewMemOp) {
10477   assert(isa<MemSDNode>(NewMemOp.getNode()) && "Expected a memop node");
10478   SDValue OldChain = SDValue(OldLoad, 1);
10479   SDValue NewMemOpChain = NewMemOp.getValue(1);
10480   return makeEquivalentMemoryOrdering(OldChain, NewMemOpChain);
10481 }
10482 
10483 SDValue SelectionDAG::getSymbolFunctionGlobalAddress(SDValue Op,
10484                                                      Function **OutFunction) {
10485   assert(isa<ExternalSymbolSDNode>(Op) && "Node should be an ExternalSymbol");
10486 
10487   auto *Symbol = cast<ExternalSymbolSDNode>(Op)->getSymbol();
10488   auto *Module = MF->getFunction().getParent();
10489   auto *Function = Module->getFunction(Symbol);
10490 
10491   if (OutFunction != nullptr)
10492       *OutFunction = Function;
10493 
10494   if (Function != nullptr) {
10495     auto PtrTy = TLI->getPointerTy(getDataLayout(), Function->getAddressSpace());
10496     return getGlobalAddress(Function, SDLoc(Op), PtrTy);
10497   }
10498 
10499   std::string ErrorStr;
10500   raw_string_ostream ErrorFormatter(ErrorStr);
10501   ErrorFormatter << "Undefined external symbol ";
10502   ErrorFormatter << '"' << Symbol << '"';
10503   report_fatal_error(Twine(ErrorFormatter.str()));
10504 }
10505 
10506 //===----------------------------------------------------------------------===//
10507 //                              SDNode Class
10508 //===----------------------------------------------------------------------===//
10509 
10510 bool llvm::isNullConstant(SDValue V) {
10511   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
10512   return Const != nullptr && Const->isZero();
10513 }
10514 
10515 bool llvm::isNullFPConstant(SDValue V) {
10516   ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V);
10517   return Const != nullptr && Const->isZero() && !Const->isNegative();
10518 }
10519 
10520 bool llvm::isAllOnesConstant(SDValue V) {
10521   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
10522   return Const != nullptr && Const->isAllOnes();
10523 }
10524 
10525 bool llvm::isOneConstant(SDValue V) {
10526   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
10527   return Const != nullptr && Const->isOne();
10528 }
10529 
10530 bool llvm::isMinSignedConstant(SDValue V) {
10531   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
10532   return Const != nullptr && Const->isMinSignedValue();
10533 }
10534 
10535 SDValue llvm::peekThroughBitcasts(SDValue V) {
10536   while (V.getOpcode() == ISD::BITCAST)
10537     V = V.getOperand(0);
10538   return V;
10539 }
10540 
10541 SDValue llvm::peekThroughOneUseBitcasts(SDValue V) {
10542   while (V.getOpcode() == ISD::BITCAST && V.getOperand(0).hasOneUse())
10543     V = V.getOperand(0);
10544   return V;
10545 }
10546 
10547 SDValue llvm::peekThroughExtractSubvectors(SDValue V) {
10548   while (V.getOpcode() == ISD::EXTRACT_SUBVECTOR)
10549     V = V.getOperand(0);
10550   return V;
10551 }
10552 
10553 bool llvm::isBitwiseNot(SDValue V, bool AllowUndefs) {
10554   if (V.getOpcode() != ISD::XOR)
10555     return false;
10556   V = peekThroughBitcasts(V.getOperand(1));
10557   unsigned NumBits = V.getScalarValueSizeInBits();
10558   ConstantSDNode *C =
10559       isConstOrConstSplat(V, AllowUndefs, /*AllowTruncation*/ true);
10560   return C && (C->getAPIntValue().countTrailingOnes() >= NumBits);
10561 }
10562 
10563 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, bool AllowUndefs,
10564                                           bool AllowTruncation) {
10565   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
10566     return CN;
10567 
10568   // SplatVectors can truncate their operands. Ignore that case here unless
10569   // AllowTruncation is set.
10570   if (N->getOpcode() == ISD::SPLAT_VECTOR) {
10571     EVT VecEltVT = N->getValueType(0).getVectorElementType();
10572     if (auto *CN = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
10573       EVT CVT = CN->getValueType(0);
10574       assert(CVT.bitsGE(VecEltVT) && "Illegal splat_vector element extension");
10575       if (AllowTruncation || CVT == VecEltVT)
10576         return CN;
10577     }
10578   }
10579 
10580   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
10581     BitVector UndefElements;
10582     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
10583 
10584     // BuildVectors can truncate their operands. Ignore that case here unless
10585     // AllowTruncation is set.
10586     if (CN && (UndefElements.none() || AllowUndefs)) {
10587       EVT CVT = CN->getValueType(0);
10588       EVT NSVT = N.getValueType().getScalarType();
10589       assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension");
10590       if (AllowTruncation || (CVT == NSVT))
10591         return CN;
10592     }
10593   }
10594 
10595   return nullptr;
10596 }
10597 
10598 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, const APInt &DemandedElts,
10599                                           bool AllowUndefs,
10600                                           bool AllowTruncation) {
10601   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
10602     return CN;
10603 
10604   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
10605     BitVector UndefElements;
10606     ConstantSDNode *CN = BV->getConstantSplatNode(DemandedElts, &UndefElements);
10607 
10608     // BuildVectors can truncate their operands. Ignore that case here unless
10609     // AllowTruncation is set.
10610     if (CN && (UndefElements.none() || AllowUndefs)) {
10611       EVT CVT = CN->getValueType(0);
10612       EVT NSVT = N.getValueType().getScalarType();
10613       assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension");
10614       if (AllowTruncation || (CVT == NSVT))
10615         return CN;
10616     }
10617   }
10618 
10619   return nullptr;
10620 }
10621 
10622 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N, bool AllowUndefs) {
10623   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
10624     return CN;
10625 
10626   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
10627     BitVector UndefElements;
10628     ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
10629     if (CN && (UndefElements.none() || AllowUndefs))
10630       return CN;
10631   }
10632 
10633   if (N.getOpcode() == ISD::SPLAT_VECTOR)
10634     if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N.getOperand(0)))
10635       return CN;
10636 
10637   return nullptr;
10638 }
10639 
10640 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N,
10641                                               const APInt &DemandedElts,
10642                                               bool AllowUndefs) {
10643   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
10644     return CN;
10645 
10646   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
10647     BitVector UndefElements;
10648     ConstantFPSDNode *CN =
10649         BV->getConstantFPSplatNode(DemandedElts, &UndefElements);
10650     if (CN && (UndefElements.none() || AllowUndefs))
10651       return CN;
10652   }
10653 
10654   return nullptr;
10655 }
10656 
10657 bool llvm::isNullOrNullSplat(SDValue N, bool AllowUndefs) {
10658   // TODO: may want to use peekThroughBitcast() here.
10659   ConstantSDNode *C =
10660       isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation=*/true);
10661   return C && C->isZero();
10662 }
10663 
10664 bool llvm::isOneOrOneSplat(SDValue N, bool AllowUndefs) {
10665   // TODO: may want to use peekThroughBitcast() here.
10666   unsigned BitWidth = N.getScalarValueSizeInBits();
10667   ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs);
10668   return C && C->isOne() && C->getValueSizeInBits(0) == BitWidth;
10669 }
10670 
10671 bool llvm::isAllOnesOrAllOnesSplat(SDValue N, bool AllowUndefs) {
10672   N = peekThroughBitcasts(N);
10673   unsigned BitWidth = N.getScalarValueSizeInBits();
10674   ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs);
10675   return C && C->isAllOnes() && C->getValueSizeInBits(0) == BitWidth;
10676 }
10677 
10678 HandleSDNode::~HandleSDNode() {
10679   DropOperands();
10680 }
10681 
10682 GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, unsigned Order,
10683                                          const DebugLoc &DL,
10684                                          const GlobalValue *GA, EVT VT,
10685                                          int64_t o, unsigned TF)
10686     : SDNode(Opc, Order, DL, getSDVTList(VT)), Offset(o), TargetFlags(TF) {
10687   TheGlobal = GA;
10688 }
10689 
10690 AddrSpaceCastSDNode::AddrSpaceCastSDNode(unsigned Order, const DebugLoc &dl,
10691                                          EVT VT, unsigned SrcAS,
10692                                          unsigned DestAS)
10693     : SDNode(ISD::ADDRSPACECAST, Order, dl, getSDVTList(VT)),
10694       SrcAddrSpace(SrcAS), DestAddrSpace(DestAS) {}
10695 
10696 MemSDNode::MemSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl,
10697                      SDVTList VTs, EVT memvt, MachineMemOperand *mmo)
10698     : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MMO(mmo) {
10699   MemSDNodeBits.IsVolatile = MMO->isVolatile();
10700   MemSDNodeBits.IsNonTemporal = MMO->isNonTemporal();
10701   MemSDNodeBits.IsDereferenceable = MMO->isDereferenceable();
10702   MemSDNodeBits.IsInvariant = MMO->isInvariant();
10703 
10704   // We check here that the size of the memory operand fits within the size of
10705   // the MMO. This is because the MMO might indicate only a possible address
10706   // range instead of specifying the affected memory addresses precisely.
10707   // TODO: Make MachineMemOperands aware of scalable vectors.
10708   assert(memvt.getStoreSize().getKnownMinSize() <= MMO->getSize() &&
10709          "Size mismatch!");
10710 }
10711 
10712 /// Profile - Gather unique data for the node.
10713 ///
10714 void SDNode::Profile(FoldingSetNodeID &ID) const {
10715   AddNodeIDNode(ID, this);
10716 }
10717 
10718 namespace {
10719 
10720   struct EVTArray {
10721     std::vector<EVT> VTs;
10722 
10723     EVTArray() {
10724       VTs.reserve(MVT::VALUETYPE_SIZE);
10725       for (unsigned i = 0; i < MVT::VALUETYPE_SIZE; ++i)
10726         VTs.push_back(MVT((MVT::SimpleValueType)i));
10727     }
10728   };
10729 
10730 } // end anonymous namespace
10731 
10732 static ManagedStatic<std::set<EVT, EVT::compareRawBits>> EVTs;
10733 static ManagedStatic<EVTArray> SimpleVTArray;
10734 static ManagedStatic<sys::SmartMutex<true>> VTMutex;
10735 
10736 /// getValueTypeList - Return a pointer to the specified value type.
10737 ///
10738 const EVT *SDNode::getValueTypeList(EVT VT) {
10739   if (VT.isExtended()) {
10740     sys::SmartScopedLock<true> Lock(*VTMutex);
10741     return &(*EVTs->insert(VT).first);
10742   }
10743   assert(VT.getSimpleVT() < MVT::VALUETYPE_SIZE && "Value type out of range!");
10744   return &SimpleVTArray->VTs[VT.getSimpleVT().SimpleTy];
10745 }
10746 
10747 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
10748 /// indicated value.  This method ignores uses of other values defined by this
10749 /// operation.
10750 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
10751   assert(Value < getNumValues() && "Bad value!");
10752 
10753   // TODO: Only iterate over uses of a given value of the node
10754   for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
10755     if (UI.getUse().getResNo() == Value) {
10756       if (NUses == 0)
10757         return false;
10758       --NUses;
10759     }
10760   }
10761 
10762   // Found exactly the right number of uses?
10763   return NUses == 0;
10764 }
10765 
10766 /// hasAnyUseOfValue - Return true if there are any use of the indicated
10767 /// value. This method ignores uses of other values defined by this operation.
10768 bool SDNode::hasAnyUseOfValue(unsigned Value) const {
10769   assert(Value < getNumValues() && "Bad value!");
10770 
10771   for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI)
10772     if (UI.getUse().getResNo() == Value)
10773       return true;
10774 
10775   return false;
10776 }
10777 
10778 /// isOnlyUserOf - Return true if this node is the only use of N.
10779 bool SDNode::isOnlyUserOf(const SDNode *N) const {
10780   bool Seen = false;
10781   for (const SDNode *User : N->uses()) {
10782     if (User == this)
10783       Seen = true;
10784     else
10785       return false;
10786   }
10787 
10788   return Seen;
10789 }
10790 
10791 /// Return true if the only users of N are contained in Nodes.
10792 bool SDNode::areOnlyUsersOf(ArrayRef<const SDNode *> Nodes, const SDNode *N) {
10793   bool Seen = false;
10794   for (const SDNode *User : N->uses()) {
10795     if (llvm::is_contained(Nodes, User))
10796       Seen = true;
10797     else
10798       return false;
10799   }
10800 
10801   return Seen;
10802 }
10803 
10804 /// isOperand - Return true if this node is an operand of N.
10805 bool SDValue::isOperandOf(const SDNode *N) const {
10806   return is_contained(N->op_values(), *this);
10807 }
10808 
10809 bool SDNode::isOperandOf(const SDNode *N) const {
10810   return any_of(N->op_values(),
10811                 [this](SDValue Op) { return this == Op.getNode(); });
10812 }
10813 
10814 /// reachesChainWithoutSideEffects - Return true if this operand (which must
10815 /// be a chain) reaches the specified operand without crossing any
10816 /// side-effecting instructions on any chain path.  In practice, this looks
10817 /// through token factors and non-volatile loads.  In order to remain efficient,
10818 /// this only looks a couple of nodes in, it does not do an exhaustive search.
10819 ///
10820 /// Note that we only need to examine chains when we're searching for
10821 /// side-effects; SelectionDAG requires that all side-effects are represented
10822 /// by chains, even if another operand would force a specific ordering. This
10823 /// constraint is necessary to allow transformations like splitting loads.
10824 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest,
10825                                              unsigned Depth) const {
10826   if (*this == Dest) return true;
10827 
10828   // Don't search too deeply, we just want to be able to see through
10829   // TokenFactor's etc.
10830   if (Depth == 0) return false;
10831 
10832   // If this is a token factor, all inputs to the TF happen in parallel.
10833   if (getOpcode() == ISD::TokenFactor) {
10834     // First, try a shallow search.
10835     if (is_contained((*this)->ops(), Dest)) {
10836       // We found the chain we want as an operand of this TokenFactor.
10837       // Essentially, we reach the chain without side-effects if we could
10838       // serialize the TokenFactor into a simple chain of operations with
10839       // Dest as the last operation. This is automatically true if the
10840       // chain has one use: there are no other ordering constraints.
10841       // If the chain has more than one use, we give up: some other
10842       // use of Dest might force a side-effect between Dest and the current
10843       // node.
10844       if (Dest.hasOneUse())
10845         return true;
10846     }
10847     // Next, try a deep search: check whether every operand of the TokenFactor
10848     // reaches Dest.
10849     return llvm::all_of((*this)->ops(), [=](SDValue Op) {
10850       return Op.reachesChainWithoutSideEffects(Dest, Depth - 1);
10851     });
10852   }
10853 
10854   // Loads don't have side effects, look through them.
10855   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
10856     if (Ld->isUnordered())
10857       return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
10858   }
10859   return false;
10860 }
10861 
10862 bool SDNode::hasPredecessor(const SDNode *N) const {
10863   SmallPtrSet<const SDNode *, 32> Visited;
10864   SmallVector<const SDNode *, 16> Worklist;
10865   Worklist.push_back(this);
10866   return hasPredecessorHelper(N, Visited, Worklist);
10867 }
10868 
10869 void SDNode::intersectFlagsWith(const SDNodeFlags Flags) {
10870   this->Flags.intersectWith(Flags);
10871 }
10872 
10873 SDValue
10874 SelectionDAG::matchBinOpReduction(SDNode *Extract, ISD::NodeType &BinOp,
10875                                   ArrayRef<ISD::NodeType> CandidateBinOps,
10876                                   bool AllowPartials) {
10877   // The pattern must end in an extract from index 0.
10878   if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10879       !isNullConstant(Extract->getOperand(1)))
10880     return SDValue();
10881 
10882   // Match against one of the candidate binary ops.
10883   SDValue Op = Extract->getOperand(0);
10884   if (llvm::none_of(CandidateBinOps, [Op](ISD::NodeType BinOp) {
10885         return Op.getOpcode() == unsigned(BinOp);
10886       }))
10887     return SDValue();
10888 
10889   // Floating-point reductions may require relaxed constraints on the final step
10890   // of the reduction because they may reorder intermediate operations.
10891   unsigned CandidateBinOp = Op.getOpcode();
10892   if (Op.getValueType().isFloatingPoint()) {
10893     SDNodeFlags Flags = Op->getFlags();
10894     switch (CandidateBinOp) {
10895     case ISD::FADD:
10896       if (!Flags.hasNoSignedZeros() || !Flags.hasAllowReassociation())
10897         return SDValue();
10898       break;
10899     default:
10900       llvm_unreachable("Unhandled FP opcode for binop reduction");
10901     }
10902   }
10903 
10904   // Matching failed - attempt to see if we did enough stages that a partial
10905   // reduction from a subvector is possible.
10906   auto PartialReduction = [&](SDValue Op, unsigned NumSubElts) {
10907     if (!AllowPartials || !Op)
10908       return SDValue();
10909     EVT OpVT = Op.getValueType();
10910     EVT OpSVT = OpVT.getScalarType();
10911     EVT SubVT = EVT::getVectorVT(*getContext(), OpSVT, NumSubElts);
10912     if (!TLI->isExtractSubvectorCheap(SubVT, OpVT, 0))
10913       return SDValue();
10914     BinOp = (ISD::NodeType)CandidateBinOp;
10915     return getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(Op), SubVT, Op,
10916                    getVectorIdxConstant(0, SDLoc(Op)));
10917   };
10918 
10919   // At each stage, we're looking for something that looks like:
10920   // %s = shufflevector <8 x i32> %op, <8 x i32> undef,
10921   //                    <8 x i32> <i32 2, i32 3, i32 undef, i32 undef,
10922   //                               i32 undef, i32 undef, i32 undef, i32 undef>
10923   // %a = binop <8 x i32> %op, %s
10924   // Where the mask changes according to the stage. E.g. for a 3-stage pyramid,
10925   // we expect something like:
10926   // <4,5,6,7,u,u,u,u>
10927   // <2,3,u,u,u,u,u,u>
10928   // <1,u,u,u,u,u,u,u>
10929   // While a partial reduction match would be:
10930   // <2,3,u,u,u,u,u,u>
10931   // <1,u,u,u,u,u,u,u>
10932   unsigned Stages = Log2_32(Op.getValueType().getVectorNumElements());
10933   SDValue PrevOp;
10934   for (unsigned i = 0; i < Stages; ++i) {
10935     unsigned MaskEnd = (1 << i);
10936 
10937     if (Op.getOpcode() != CandidateBinOp)
10938       return PartialReduction(PrevOp, MaskEnd);
10939 
10940     SDValue Op0 = Op.getOperand(0);
10941     SDValue Op1 = Op.getOperand(1);
10942 
10943     ShuffleVectorSDNode *Shuffle = dyn_cast<ShuffleVectorSDNode>(Op0);
10944     if (Shuffle) {
10945       Op = Op1;
10946     } else {
10947       Shuffle = dyn_cast<ShuffleVectorSDNode>(Op1);
10948       Op = Op0;
10949     }
10950 
10951     // The first operand of the shuffle should be the same as the other operand
10952     // of the binop.
10953     if (!Shuffle || Shuffle->getOperand(0) != Op)
10954       return PartialReduction(PrevOp, MaskEnd);
10955 
10956     // Verify the shuffle has the expected (at this stage of the pyramid) mask.
10957     for (int Index = 0; Index < (int)MaskEnd; ++Index)
10958       if (Shuffle->getMaskElt(Index) != (int)(MaskEnd + Index))
10959         return PartialReduction(PrevOp, MaskEnd);
10960 
10961     PrevOp = Op;
10962   }
10963 
10964   // Handle subvector reductions, which tend to appear after the shuffle
10965   // reduction stages.
10966   while (Op.getOpcode() == CandidateBinOp) {
10967     unsigned NumElts = Op.getValueType().getVectorNumElements();
10968     SDValue Op0 = Op.getOperand(0);
10969     SDValue Op1 = Op.getOperand(1);
10970     if (Op0.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
10971         Op1.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
10972         Op0.getOperand(0) != Op1.getOperand(0))
10973       break;
10974     SDValue Src = Op0.getOperand(0);
10975     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
10976     if (NumSrcElts != (2 * NumElts))
10977       break;
10978     if (!(Op0.getConstantOperandAPInt(1) == 0 &&
10979           Op1.getConstantOperandAPInt(1) == NumElts) &&
10980         !(Op1.getConstantOperandAPInt(1) == 0 &&
10981           Op0.getConstantOperandAPInt(1) == NumElts))
10982       break;
10983     Op = Src;
10984   }
10985 
10986   BinOp = (ISD::NodeType)CandidateBinOp;
10987   return Op;
10988 }
10989 
10990 SDValue SelectionDAG::UnrollVectorOp(SDNode *N, unsigned ResNE) {
10991   assert(N->getNumValues() == 1 &&
10992          "Can't unroll a vector with multiple results!");
10993 
10994   EVT VT = N->getValueType(0);
10995   unsigned NE = VT.getVectorNumElements();
10996   EVT EltVT = VT.getVectorElementType();
10997   SDLoc dl(N);
10998 
10999   SmallVector<SDValue, 8> Scalars;
11000   SmallVector<SDValue, 4> Operands(N->getNumOperands());
11001 
11002   // If ResNE is 0, fully unroll the vector op.
11003   if (ResNE == 0)
11004     ResNE = NE;
11005   else if (NE > ResNE)
11006     NE = ResNE;
11007 
11008   unsigned i;
11009   for (i= 0; i != NE; ++i) {
11010     for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) {
11011       SDValue Operand = N->getOperand(j);
11012       EVT OperandVT = Operand.getValueType();
11013       if (OperandVT.isVector()) {
11014         // A vector operand; extract a single element.
11015         EVT OperandEltVT = OperandVT.getVectorElementType();
11016         Operands[j] = getNode(ISD::EXTRACT_VECTOR_ELT, dl, OperandEltVT,
11017                               Operand, getVectorIdxConstant(i, dl));
11018       } else {
11019         // A scalar operand; just use it as is.
11020         Operands[j] = Operand;
11021       }
11022     }
11023 
11024     switch (N->getOpcode()) {
11025     default: {
11026       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands,
11027                                 N->getFlags()));
11028       break;
11029     }
11030     case ISD::VSELECT:
11031       Scalars.push_back(getNode(ISD::SELECT, dl, EltVT, Operands));
11032       break;
11033     case ISD::SHL:
11034     case ISD::SRA:
11035     case ISD::SRL:
11036     case ISD::ROTL:
11037     case ISD::ROTR:
11038       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0],
11039                                getShiftAmountOperand(Operands[0].getValueType(),
11040                                                      Operands[1])));
11041       break;
11042     case ISD::SIGN_EXTEND_INREG: {
11043       EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType();
11044       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT,
11045                                 Operands[0],
11046                                 getValueType(ExtVT)));
11047     }
11048     }
11049   }
11050 
11051   for (; i < ResNE; ++i)
11052     Scalars.push_back(getUNDEF(EltVT));
11053 
11054   EVT VecVT = EVT::getVectorVT(*getContext(), EltVT, ResNE);
11055   return getBuildVector(VecVT, dl, Scalars);
11056 }
11057 
11058 std::pair<SDValue, SDValue> SelectionDAG::UnrollVectorOverflowOp(
11059     SDNode *N, unsigned ResNE) {
11060   unsigned Opcode = N->getOpcode();
11061   assert((Opcode == ISD::UADDO || Opcode == ISD::SADDO ||
11062           Opcode == ISD::USUBO || Opcode == ISD::SSUBO ||
11063           Opcode == ISD::UMULO || Opcode == ISD::SMULO) &&
11064          "Expected an overflow opcode");
11065 
11066   EVT ResVT = N->getValueType(0);
11067   EVT OvVT = N->getValueType(1);
11068   EVT ResEltVT = ResVT.getVectorElementType();
11069   EVT OvEltVT = OvVT.getVectorElementType();
11070   SDLoc dl(N);
11071 
11072   // If ResNE is 0, fully unroll the vector op.
11073   unsigned NE = ResVT.getVectorNumElements();
11074   if (ResNE == 0)
11075     ResNE = NE;
11076   else if (NE > ResNE)
11077     NE = ResNE;
11078 
11079   SmallVector<SDValue, 8> LHSScalars;
11080   SmallVector<SDValue, 8> RHSScalars;
11081   ExtractVectorElements(N->getOperand(0), LHSScalars, 0, NE);
11082   ExtractVectorElements(N->getOperand(1), RHSScalars, 0, NE);
11083 
11084   EVT SVT = TLI->getSetCCResultType(getDataLayout(), *getContext(), ResEltVT);
11085   SDVTList VTs = getVTList(ResEltVT, SVT);
11086   SmallVector<SDValue, 8> ResScalars;
11087   SmallVector<SDValue, 8> OvScalars;
11088   for (unsigned i = 0; i < NE; ++i) {
11089     SDValue Res = getNode(Opcode, dl, VTs, LHSScalars[i], RHSScalars[i]);
11090     SDValue Ov =
11091         getSelect(dl, OvEltVT, Res.getValue(1),
11092                   getBoolConstant(true, dl, OvEltVT, ResVT),
11093                   getConstant(0, dl, OvEltVT));
11094 
11095     ResScalars.push_back(Res);
11096     OvScalars.push_back(Ov);
11097   }
11098 
11099   ResScalars.append(ResNE - NE, getUNDEF(ResEltVT));
11100   OvScalars.append(ResNE - NE, getUNDEF(OvEltVT));
11101 
11102   EVT NewResVT = EVT::getVectorVT(*getContext(), ResEltVT, ResNE);
11103   EVT NewOvVT = EVT::getVectorVT(*getContext(), OvEltVT, ResNE);
11104   return std::make_pair(getBuildVector(NewResVT, dl, ResScalars),
11105                         getBuildVector(NewOvVT, dl, OvScalars));
11106 }
11107 
11108 bool SelectionDAG::areNonVolatileConsecutiveLoads(LoadSDNode *LD,
11109                                                   LoadSDNode *Base,
11110                                                   unsigned Bytes,
11111                                                   int Dist) const {
11112   if (LD->isVolatile() || Base->isVolatile())
11113     return false;
11114   // TODO: probably too restrictive for atomics, revisit
11115   if (!LD->isSimple())
11116     return false;
11117   if (LD->isIndexed() || Base->isIndexed())
11118     return false;
11119   if (LD->getChain() != Base->getChain())
11120     return false;
11121   EVT VT = LD->getValueType(0);
11122   if (VT.getSizeInBits() / 8 != Bytes)
11123     return false;
11124 
11125   auto BaseLocDecomp = BaseIndexOffset::match(Base, *this);
11126   auto LocDecomp = BaseIndexOffset::match(LD, *this);
11127 
11128   int64_t Offset = 0;
11129   if (BaseLocDecomp.equalBaseIndex(LocDecomp, *this, Offset))
11130     return (Dist * Bytes == Offset);
11131   return false;
11132 }
11133 
11134 /// InferPtrAlignment - Infer alignment of a load / store address. Return None
11135 /// if it cannot be inferred.
11136 MaybeAlign SelectionDAG::InferPtrAlign(SDValue Ptr) const {
11137   // If this is a GlobalAddress + cst, return the alignment.
11138   const GlobalValue *GV = nullptr;
11139   int64_t GVOffset = 0;
11140   if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) {
11141     unsigned PtrWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
11142     KnownBits Known(PtrWidth);
11143     llvm::computeKnownBits(GV, Known, getDataLayout());
11144     unsigned AlignBits = Known.countMinTrailingZeros();
11145     if (AlignBits)
11146       return commonAlignment(Align(1ull << std::min(31U, AlignBits)), GVOffset);
11147   }
11148 
11149   // If this is a direct reference to a stack slot, use information about the
11150   // stack slot's alignment.
11151   int FrameIdx = INT_MIN;
11152   int64_t FrameOffset = 0;
11153   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) {
11154     FrameIdx = FI->getIndex();
11155   } else if (isBaseWithConstantOffset(Ptr) &&
11156              isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
11157     // Handle FI+Cst
11158     FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
11159     FrameOffset = Ptr.getConstantOperandVal(1);
11160   }
11161 
11162   if (FrameIdx != INT_MIN) {
11163     const MachineFrameInfo &MFI = getMachineFunction().getFrameInfo();
11164     return commonAlignment(MFI.getObjectAlign(FrameIdx), FrameOffset);
11165   }
11166 
11167   return None;
11168 }
11169 
11170 /// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type
11171 /// which is split (or expanded) into two not necessarily identical pieces.
11172 std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const {
11173   // Currently all types are split in half.
11174   EVT LoVT, HiVT;
11175   if (!VT.isVector())
11176     LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT);
11177   else
11178     LoVT = HiVT = VT.getHalfNumVectorElementsVT(*getContext());
11179 
11180   return std::make_pair(LoVT, HiVT);
11181 }
11182 
11183 /// GetDependentSplitDestVTs - Compute the VTs needed for the low/hi parts of a
11184 /// type, dependent on an enveloping VT that has been split into two identical
11185 /// pieces. Sets the HiIsEmpty flag when hi type has zero storage size.
11186 std::pair<EVT, EVT>
11187 SelectionDAG::GetDependentSplitDestVTs(const EVT &VT, const EVT &EnvVT,
11188                                        bool *HiIsEmpty) const {
11189   EVT EltTp = VT.getVectorElementType();
11190   // Examples:
11191   //   custom VL=8  with enveloping VL=8/8 yields 8/0 (hi empty)
11192   //   custom VL=9  with enveloping VL=8/8 yields 8/1
11193   //   custom VL=10 with enveloping VL=8/8 yields 8/2
11194   //   etc.
11195   ElementCount VTNumElts = VT.getVectorElementCount();
11196   ElementCount EnvNumElts = EnvVT.getVectorElementCount();
11197   assert(VTNumElts.isScalable() == EnvNumElts.isScalable() &&
11198          "Mixing fixed width and scalable vectors when enveloping a type");
11199   EVT LoVT, HiVT;
11200   if (VTNumElts.getKnownMinValue() > EnvNumElts.getKnownMinValue()) {
11201     LoVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts);
11202     HiVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts - EnvNumElts);
11203     *HiIsEmpty = false;
11204   } else {
11205     // Flag that hi type has zero storage size, but return split envelop type
11206     // (this would be easier if vector types with zero elements were allowed).
11207     LoVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts);
11208     HiVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts);
11209     *HiIsEmpty = true;
11210   }
11211   return std::make_pair(LoVT, HiVT);
11212 }
11213 
11214 /// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the
11215 /// low/high part.
11216 std::pair<SDValue, SDValue>
11217 SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT,
11218                           const EVT &HiVT) {
11219   assert(LoVT.isScalableVector() == HiVT.isScalableVector() &&
11220          LoVT.isScalableVector() == N.getValueType().isScalableVector() &&
11221          "Splitting vector with an invalid mixture of fixed and scalable "
11222          "vector types");
11223   assert(LoVT.getVectorMinNumElements() + HiVT.getVectorMinNumElements() <=
11224              N.getValueType().getVectorMinNumElements() &&
11225          "More vector elements requested than available!");
11226   SDValue Lo, Hi;
11227   Lo =
11228       getNode(ISD::EXTRACT_SUBVECTOR, DL, LoVT, N, getVectorIdxConstant(0, DL));
11229   // For scalable vectors it is safe to use LoVT.getVectorMinNumElements()
11230   // (rather than having to use ElementCount), because EXTRACT_SUBVECTOR scales
11231   // IDX with the runtime scaling factor of the result vector type. For
11232   // fixed-width result vectors, that runtime scaling factor is 1.
11233   Hi = getNode(ISD::EXTRACT_SUBVECTOR, DL, HiVT, N,
11234                getVectorIdxConstant(LoVT.getVectorMinNumElements(), DL));
11235   return std::make_pair(Lo, Hi);
11236 }
11237 
11238 std::pair<SDValue, SDValue> SelectionDAG::SplitEVL(SDValue N, EVT VecVT,
11239                                                    const SDLoc &DL) {
11240   // Split the vector length parameter.
11241   // %evl -> umin(%evl, %halfnumelts) and usubsat(%evl - %halfnumelts).
11242   EVT VT = N.getValueType();
11243   assert(VecVT.getVectorElementCount().isKnownEven() &&
11244          "Expecting the mask to be an evenly-sized vector");
11245   unsigned HalfMinNumElts = VecVT.getVectorMinNumElements() / 2;
11246   SDValue HalfNumElts =
11247       VecVT.isFixedLengthVector()
11248           ? getConstant(HalfMinNumElts, DL, VT)
11249           : getVScale(DL, VT, APInt(VT.getScalarSizeInBits(), HalfMinNumElts));
11250   SDValue Lo = getNode(ISD::UMIN, DL, VT, N, HalfNumElts);
11251   SDValue Hi = getNode(ISD::USUBSAT, DL, VT, N, HalfNumElts);
11252   return std::make_pair(Lo, Hi);
11253 }
11254 
11255 /// Widen the vector up to the next power of two using INSERT_SUBVECTOR.
11256 SDValue SelectionDAG::WidenVector(const SDValue &N, const SDLoc &DL) {
11257   EVT VT = N.getValueType();
11258   EVT WideVT = EVT::getVectorVT(*getContext(), VT.getVectorElementType(),
11259                                 NextPowerOf2(VT.getVectorNumElements()));
11260   return getNode(ISD::INSERT_SUBVECTOR, DL, WideVT, getUNDEF(WideVT), N,
11261                  getVectorIdxConstant(0, DL));
11262 }
11263 
11264 void SelectionDAG::ExtractVectorElements(SDValue Op,
11265                                          SmallVectorImpl<SDValue> &Args,
11266                                          unsigned Start, unsigned Count,
11267                                          EVT EltVT) {
11268   EVT VT = Op.getValueType();
11269   if (Count == 0)
11270     Count = VT.getVectorNumElements();
11271   if (EltVT == EVT())
11272     EltVT = VT.getVectorElementType();
11273   SDLoc SL(Op);
11274   for (unsigned i = Start, e = Start + Count; i != e; ++i) {
11275     Args.push_back(getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Op,
11276                            getVectorIdxConstant(i, SL)));
11277   }
11278 }
11279 
11280 // getAddressSpace - Return the address space this GlobalAddress belongs to.
11281 unsigned GlobalAddressSDNode::getAddressSpace() const {
11282   return getGlobal()->getType()->getAddressSpace();
11283 }
11284 
11285 Type *ConstantPoolSDNode::getType() const {
11286   if (isMachineConstantPoolEntry())
11287     return Val.MachineCPVal->getType();
11288   return Val.ConstVal->getType();
11289 }
11290 
11291 bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue, APInt &SplatUndef,
11292                                         unsigned &SplatBitSize,
11293                                         bool &HasAnyUndefs,
11294                                         unsigned MinSplatBits,
11295                                         bool IsBigEndian) const {
11296   EVT VT = getValueType(0);
11297   assert(VT.isVector() && "Expected a vector type");
11298   unsigned VecWidth = VT.getSizeInBits();
11299   if (MinSplatBits > VecWidth)
11300     return false;
11301 
11302   // FIXME: The widths are based on this node's type, but build vectors can
11303   // truncate their operands.
11304   SplatValue = APInt(VecWidth, 0);
11305   SplatUndef = APInt(VecWidth, 0);
11306 
11307   // Get the bits. Bits with undefined values (when the corresponding element
11308   // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared
11309   // in SplatValue. If any of the values are not constant, give up and return
11310   // false.
11311   unsigned int NumOps = getNumOperands();
11312   assert(NumOps > 0 && "isConstantSplat has 0-size build vector");
11313   unsigned EltWidth = VT.getScalarSizeInBits();
11314 
11315   for (unsigned j = 0; j < NumOps; ++j) {
11316     unsigned i = IsBigEndian ? NumOps - 1 - j : j;
11317     SDValue OpVal = getOperand(i);
11318     unsigned BitPos = j * EltWidth;
11319 
11320     if (OpVal.isUndef())
11321       SplatUndef.setBits(BitPos, BitPos + EltWidth);
11322     else if (auto *CN = dyn_cast<ConstantSDNode>(OpVal))
11323       SplatValue.insertBits(CN->getAPIntValue().zextOrTrunc(EltWidth), BitPos);
11324     else if (auto *CN = dyn_cast<ConstantFPSDNode>(OpVal))
11325       SplatValue.insertBits(CN->getValueAPF().bitcastToAPInt(), BitPos);
11326     else
11327       return false;
11328   }
11329 
11330   // The build_vector is all constants or undefs. Find the smallest element
11331   // size that splats the vector.
11332   HasAnyUndefs = (SplatUndef != 0);
11333 
11334   // FIXME: This does not work for vectors with elements less than 8 bits.
11335   while (VecWidth > 8) {
11336     unsigned HalfSize = VecWidth / 2;
11337     APInt HighValue = SplatValue.extractBits(HalfSize, HalfSize);
11338     APInt LowValue = SplatValue.extractBits(HalfSize, 0);
11339     APInt HighUndef = SplatUndef.extractBits(HalfSize, HalfSize);
11340     APInt LowUndef = SplatUndef.extractBits(HalfSize, 0);
11341 
11342     // If the two halves do not match (ignoring undef bits), stop here.
11343     if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) ||
11344         MinSplatBits > HalfSize)
11345       break;
11346 
11347     SplatValue = HighValue | LowValue;
11348     SplatUndef = HighUndef & LowUndef;
11349 
11350     VecWidth = HalfSize;
11351   }
11352 
11353   SplatBitSize = VecWidth;
11354   return true;
11355 }
11356 
11357 SDValue BuildVectorSDNode::getSplatValue(const APInt &DemandedElts,
11358                                          BitVector *UndefElements) const {
11359   unsigned NumOps = getNumOperands();
11360   if (UndefElements) {
11361     UndefElements->clear();
11362     UndefElements->resize(NumOps);
11363   }
11364   assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size");
11365   if (!DemandedElts)
11366     return SDValue();
11367   SDValue Splatted;
11368   for (unsigned i = 0; i != NumOps; ++i) {
11369     if (!DemandedElts[i])
11370       continue;
11371     SDValue Op = getOperand(i);
11372     if (Op.isUndef()) {
11373       if (UndefElements)
11374         (*UndefElements)[i] = true;
11375     } else if (!Splatted) {
11376       Splatted = Op;
11377     } else if (Splatted != Op) {
11378       return SDValue();
11379     }
11380   }
11381 
11382   if (!Splatted) {
11383     unsigned FirstDemandedIdx = DemandedElts.countTrailingZeros();
11384     assert(getOperand(FirstDemandedIdx).isUndef() &&
11385            "Can only have a splat without a constant for all undefs.");
11386     return getOperand(FirstDemandedIdx);
11387   }
11388 
11389   return Splatted;
11390 }
11391 
11392 SDValue BuildVectorSDNode::getSplatValue(BitVector *UndefElements) const {
11393   APInt DemandedElts = APInt::getAllOnes(getNumOperands());
11394   return getSplatValue(DemandedElts, UndefElements);
11395 }
11396 
11397 bool BuildVectorSDNode::getRepeatedSequence(const APInt &DemandedElts,
11398                                             SmallVectorImpl<SDValue> &Sequence,
11399                                             BitVector *UndefElements) const {
11400   unsigned NumOps = getNumOperands();
11401   Sequence.clear();
11402   if (UndefElements) {
11403     UndefElements->clear();
11404     UndefElements->resize(NumOps);
11405   }
11406   assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size");
11407   if (!DemandedElts || NumOps < 2 || !isPowerOf2_32(NumOps))
11408     return false;
11409 
11410   // Set the undefs even if we don't find a sequence (like getSplatValue).
11411   if (UndefElements)
11412     for (unsigned I = 0; I != NumOps; ++I)
11413       if (DemandedElts[I] && getOperand(I).isUndef())
11414         (*UndefElements)[I] = true;
11415 
11416   // Iteratively widen the sequence length looking for repetitions.
11417   for (unsigned SeqLen = 1; SeqLen < NumOps; SeqLen *= 2) {
11418     Sequence.append(SeqLen, SDValue());
11419     for (unsigned I = 0; I != NumOps; ++I) {
11420       if (!DemandedElts[I])
11421         continue;
11422       SDValue &SeqOp = Sequence[I % SeqLen];
11423       SDValue Op = getOperand(I);
11424       if (Op.isUndef()) {
11425         if (!SeqOp)
11426           SeqOp = Op;
11427         continue;
11428       }
11429       if (SeqOp && !SeqOp.isUndef() && SeqOp != Op) {
11430         Sequence.clear();
11431         break;
11432       }
11433       SeqOp = Op;
11434     }
11435     if (!Sequence.empty())
11436       return true;
11437   }
11438 
11439   assert(Sequence.empty() && "Failed to empty non-repeating sequence pattern");
11440   return false;
11441 }
11442 
11443 bool BuildVectorSDNode::getRepeatedSequence(SmallVectorImpl<SDValue> &Sequence,
11444                                             BitVector *UndefElements) const {
11445   APInt DemandedElts = APInt::getAllOnes(getNumOperands());
11446   return getRepeatedSequence(DemandedElts, Sequence, UndefElements);
11447 }
11448 
11449 ConstantSDNode *
11450 BuildVectorSDNode::getConstantSplatNode(const APInt &DemandedElts,
11451                                         BitVector *UndefElements) const {
11452   return dyn_cast_or_null<ConstantSDNode>(
11453       getSplatValue(DemandedElts, UndefElements));
11454 }
11455 
11456 ConstantSDNode *
11457 BuildVectorSDNode::getConstantSplatNode(BitVector *UndefElements) const {
11458   return dyn_cast_or_null<ConstantSDNode>(getSplatValue(UndefElements));
11459 }
11460 
11461 ConstantFPSDNode *
11462 BuildVectorSDNode::getConstantFPSplatNode(const APInt &DemandedElts,
11463                                           BitVector *UndefElements) const {
11464   return dyn_cast_or_null<ConstantFPSDNode>(
11465       getSplatValue(DemandedElts, UndefElements));
11466 }
11467 
11468 ConstantFPSDNode *
11469 BuildVectorSDNode::getConstantFPSplatNode(BitVector *UndefElements) const {
11470   return dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements));
11471 }
11472 
11473 int32_t
11474 BuildVectorSDNode::getConstantFPSplatPow2ToLog2Int(BitVector *UndefElements,
11475                                                    uint32_t BitWidth) const {
11476   if (ConstantFPSDNode *CN =
11477           dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements))) {
11478     bool IsExact;
11479     APSInt IntVal(BitWidth);
11480     const APFloat &APF = CN->getValueAPF();
11481     if (APF.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) !=
11482             APFloat::opOK ||
11483         !IsExact)
11484       return -1;
11485 
11486     return IntVal.exactLogBase2();
11487   }
11488   return -1;
11489 }
11490 
11491 bool BuildVectorSDNode::getConstantRawBits(
11492     bool IsLittleEndian, unsigned DstEltSizeInBits,
11493     SmallVectorImpl<APInt> &RawBitElements, BitVector &UndefElements) const {
11494   // Early-out if this contains anything but Undef/Constant/ConstantFP.
11495   if (!isConstant())
11496     return false;
11497 
11498   unsigned NumSrcOps = getNumOperands();
11499   unsigned SrcEltSizeInBits = getValueType(0).getScalarSizeInBits();
11500   assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 &&
11501          "Invalid bitcast scale");
11502 
11503   // Extract raw src bits.
11504   SmallVector<APInt> SrcBitElements(NumSrcOps,
11505                                     APInt::getNullValue(SrcEltSizeInBits));
11506   BitVector SrcUndeElements(NumSrcOps, false);
11507 
11508   for (unsigned I = 0; I != NumSrcOps; ++I) {
11509     SDValue Op = getOperand(I);
11510     if (Op.isUndef()) {
11511       SrcUndeElements.set(I);
11512       continue;
11513     }
11514     auto *CInt = dyn_cast<ConstantSDNode>(Op);
11515     auto *CFP = dyn_cast<ConstantFPSDNode>(Op);
11516     assert((CInt || CFP) && "Unknown constant");
11517     SrcBitElements[I] = CInt ? CInt->getAPIntValue().trunc(SrcEltSizeInBits)
11518                              : CFP->getValueAPF().bitcastToAPInt();
11519   }
11520 
11521   // Recast to dst width.
11522   recastRawBits(IsLittleEndian, DstEltSizeInBits, RawBitElements,
11523                 SrcBitElements, UndefElements, SrcUndeElements);
11524   return true;
11525 }
11526 
11527 void BuildVectorSDNode::recastRawBits(bool IsLittleEndian,
11528                                       unsigned DstEltSizeInBits,
11529                                       SmallVectorImpl<APInt> &DstBitElements,
11530                                       ArrayRef<APInt> SrcBitElements,
11531                                       BitVector &DstUndefElements,
11532                                       const BitVector &SrcUndefElements) {
11533   unsigned NumSrcOps = SrcBitElements.size();
11534   unsigned SrcEltSizeInBits = SrcBitElements[0].getBitWidth();
11535   assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 &&
11536          "Invalid bitcast scale");
11537   assert(NumSrcOps == SrcUndefElements.size() &&
11538          "Vector size mismatch");
11539 
11540   unsigned NumDstOps = (NumSrcOps * SrcEltSizeInBits) / DstEltSizeInBits;
11541   DstUndefElements.clear();
11542   DstUndefElements.resize(NumDstOps, false);
11543   DstBitElements.assign(NumDstOps, APInt::getNullValue(DstEltSizeInBits));
11544 
11545   // Concatenate src elements constant bits together into dst element.
11546   if (SrcEltSizeInBits <= DstEltSizeInBits) {
11547     unsigned Scale = DstEltSizeInBits / SrcEltSizeInBits;
11548     for (unsigned I = 0; I != NumDstOps; ++I) {
11549       DstUndefElements.set(I);
11550       APInt &DstBits = DstBitElements[I];
11551       for (unsigned J = 0; J != Scale; ++J) {
11552         unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1));
11553         if (SrcUndefElements[Idx])
11554           continue;
11555         DstUndefElements.reset(I);
11556         const APInt &SrcBits = SrcBitElements[Idx];
11557         assert(SrcBits.getBitWidth() == SrcEltSizeInBits &&
11558                "Illegal constant bitwidths");
11559         DstBits.insertBits(SrcBits, J * SrcEltSizeInBits);
11560       }
11561     }
11562     return;
11563   }
11564 
11565   // Split src element constant bits into dst elements.
11566   unsigned Scale = SrcEltSizeInBits / DstEltSizeInBits;
11567   for (unsigned I = 0; I != NumSrcOps; ++I) {
11568     if (SrcUndefElements[I]) {
11569       DstUndefElements.set(I * Scale, (I + 1) * Scale);
11570       continue;
11571     }
11572     const APInt &SrcBits = SrcBitElements[I];
11573     for (unsigned J = 0; J != Scale; ++J) {
11574       unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1));
11575       APInt &DstBits = DstBitElements[Idx];
11576       DstBits = SrcBits.extractBits(DstEltSizeInBits, J * DstEltSizeInBits);
11577     }
11578   }
11579 }
11580 
11581 bool BuildVectorSDNode::isConstant() const {
11582   for (const SDValue &Op : op_values()) {
11583     unsigned Opc = Op.getOpcode();
11584     if (Opc != ISD::UNDEF && Opc != ISD::Constant && Opc != ISD::ConstantFP)
11585       return false;
11586   }
11587   return true;
11588 }
11589 
11590 bool ShuffleVectorSDNode::isSplatMask(const int *Mask, EVT VT) {
11591   // Find the first non-undef value in the shuffle mask.
11592   unsigned i, e;
11593   for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i)
11594     /* search */;
11595 
11596   // If all elements are undefined, this shuffle can be considered a splat
11597   // (although it should eventually get simplified away completely).
11598   if (i == e)
11599     return true;
11600 
11601   // Make sure all remaining elements are either undef or the same as the first
11602   // non-undef value.
11603   for (int Idx = Mask[i]; i != e; ++i)
11604     if (Mask[i] >= 0 && Mask[i] != Idx)
11605       return false;
11606   return true;
11607 }
11608 
11609 // Returns the SDNode if it is a constant integer BuildVector
11610 // or constant integer.
11611 SDNode *SelectionDAG::isConstantIntBuildVectorOrConstantInt(SDValue N) const {
11612   if (isa<ConstantSDNode>(N))
11613     return N.getNode();
11614   if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
11615     return N.getNode();
11616   // Treat a GlobalAddress supporting constant offset folding as a
11617   // constant integer.
11618   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N))
11619     if (GA->getOpcode() == ISD::GlobalAddress &&
11620         TLI->isOffsetFoldingLegal(GA))
11621       return GA;
11622   if ((N.getOpcode() == ISD::SPLAT_VECTOR) &&
11623       isa<ConstantSDNode>(N.getOperand(0)))
11624     return N.getNode();
11625   return nullptr;
11626 }
11627 
11628 // Returns the SDNode if it is a constant float BuildVector
11629 // or constant float.
11630 SDNode *SelectionDAG::isConstantFPBuildVectorOrConstantFP(SDValue N) const {
11631   if (isa<ConstantFPSDNode>(N))
11632     return N.getNode();
11633 
11634   if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
11635     return N.getNode();
11636 
11637   if ((N.getOpcode() == ISD::SPLAT_VECTOR) &&
11638       isa<ConstantFPSDNode>(N.getOperand(0)))
11639     return N.getNode();
11640 
11641   return nullptr;
11642 }
11643 
11644 void SelectionDAG::createOperands(SDNode *Node, ArrayRef<SDValue> Vals) {
11645   assert(!Node->OperandList && "Node already has operands");
11646   assert(SDNode::getMaxNumOperands() >= Vals.size() &&
11647          "too many operands to fit into SDNode");
11648   SDUse *Ops = OperandRecycler.allocate(
11649       ArrayRecycler<SDUse>::Capacity::get(Vals.size()), OperandAllocator);
11650 
11651   bool IsDivergent = false;
11652   for (unsigned I = 0; I != Vals.size(); ++I) {
11653     Ops[I].setUser(Node);
11654     Ops[I].setInitial(Vals[I]);
11655     if (Ops[I].Val.getValueType() != MVT::Other) // Skip Chain. It does not carry divergence.
11656       IsDivergent |= Ops[I].getNode()->isDivergent();
11657   }
11658   Node->NumOperands = Vals.size();
11659   Node->OperandList = Ops;
11660   if (!TLI->isSDNodeAlwaysUniform(Node)) {
11661     IsDivergent |= TLI->isSDNodeSourceOfDivergence(Node, FLI, DA);
11662     Node->SDNodeBits.IsDivergent = IsDivergent;
11663   }
11664   checkForCycles(Node);
11665 }
11666 
11667 SDValue SelectionDAG::getTokenFactor(const SDLoc &DL,
11668                                      SmallVectorImpl<SDValue> &Vals) {
11669   size_t Limit = SDNode::getMaxNumOperands();
11670   while (Vals.size() > Limit) {
11671     unsigned SliceIdx = Vals.size() - Limit;
11672     auto ExtractedTFs = ArrayRef<SDValue>(Vals).slice(SliceIdx, Limit);
11673     SDValue NewTF = getNode(ISD::TokenFactor, DL, MVT::Other, ExtractedTFs);
11674     Vals.erase(Vals.begin() + SliceIdx, Vals.end());
11675     Vals.emplace_back(NewTF);
11676   }
11677   return getNode(ISD::TokenFactor, DL, MVT::Other, Vals);
11678 }
11679 
11680 SDValue SelectionDAG::getNeutralElement(unsigned Opcode, const SDLoc &DL,
11681                                         EVT VT, SDNodeFlags Flags) {
11682   switch (Opcode) {
11683   default:
11684     return SDValue();
11685   case ISD::ADD:
11686   case ISD::OR:
11687   case ISD::XOR:
11688   case ISD::UMAX:
11689     return getConstant(0, DL, VT);
11690   case ISD::MUL:
11691     return getConstant(1, DL, VT);
11692   case ISD::AND:
11693   case ISD::UMIN:
11694     return getAllOnesConstant(DL, VT);
11695   case ISD::SMAX:
11696     return getConstant(APInt::getSignedMinValue(VT.getSizeInBits()), DL, VT);
11697   case ISD::SMIN:
11698     return getConstant(APInt::getSignedMaxValue(VT.getSizeInBits()), DL, VT);
11699   case ISD::FADD:
11700     return getConstantFP(-0.0, DL, VT);
11701   case ISD::FMUL:
11702     return getConstantFP(1.0, DL, VT);
11703   case ISD::FMINNUM:
11704   case ISD::FMAXNUM: {
11705     // Neutral element for fminnum is NaN, Inf or FLT_MAX, depending on FMF.
11706     const fltSemantics &Semantics = EVTToAPFloatSemantics(VT);
11707     APFloat NeutralAF = !Flags.hasNoNaNs() ? APFloat::getQNaN(Semantics) :
11708                         !Flags.hasNoInfs() ? APFloat::getInf(Semantics) :
11709                         APFloat::getLargest(Semantics);
11710     if (Opcode == ISD::FMAXNUM)
11711       NeutralAF.changeSign();
11712 
11713     return getConstantFP(NeutralAF, DL, VT);
11714   }
11715   }
11716 }
11717 
11718 #ifndef NDEBUG
11719 static void checkForCyclesHelper(const SDNode *N,
11720                                  SmallPtrSetImpl<const SDNode*> &Visited,
11721                                  SmallPtrSetImpl<const SDNode*> &Checked,
11722                                  const llvm::SelectionDAG *DAG) {
11723   // If this node has already been checked, don't check it again.
11724   if (Checked.count(N))
11725     return;
11726 
11727   // If a node has already been visited on this depth-first walk, reject it as
11728   // a cycle.
11729   if (!Visited.insert(N).second) {
11730     errs() << "Detected cycle in SelectionDAG\n";
11731     dbgs() << "Offending node:\n";
11732     N->dumprFull(DAG); dbgs() << "\n";
11733     abort();
11734   }
11735 
11736   for (const SDValue &Op : N->op_values())
11737     checkForCyclesHelper(Op.getNode(), Visited, Checked, DAG);
11738 
11739   Checked.insert(N);
11740   Visited.erase(N);
11741 }
11742 #endif
11743 
11744 void llvm::checkForCycles(const llvm::SDNode *N,
11745                           const llvm::SelectionDAG *DAG,
11746                           bool force) {
11747 #ifndef NDEBUG
11748   bool check = force;
11749 #ifdef EXPENSIVE_CHECKS
11750   check = true;
11751 #endif  // EXPENSIVE_CHECKS
11752   if (check) {
11753     assert(N && "Checking nonexistent SDNode");
11754     SmallPtrSet<const SDNode*, 32> visited;
11755     SmallPtrSet<const SDNode*, 32> checked;
11756     checkForCyclesHelper(N, visited, checked, DAG);
11757   }
11758 #endif  // !NDEBUG
11759 }
11760 
11761 void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) {
11762   checkForCycles(DAG->getRoot().getNode(), DAG, force);
11763 }
11764