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 /// MaskedVectorIsZero - Return true if 'Op' is known to be zero in
2543 /// DemandedElts.  We use this predicate to simplify operations downstream.
2544 bool SelectionDAG::MaskedVectorIsZero(SDValue V, const APInt &DemandedElts,
2545                                       unsigned Depth /* = 0 */) const {
2546   APInt Mask = APInt::getAllOnes(V.getScalarValueSizeInBits());
2547   return Mask.isSubsetOf(computeKnownBits(V, DemandedElts, Depth).Zero);
2548 }
2549 
2550 /// MaskedValueIsAllOnes - Return true if '(Op & Mask) == Mask'.
2551 bool SelectionDAG::MaskedValueIsAllOnes(SDValue V, const APInt &Mask,
2552                                         unsigned Depth) const {
2553   return Mask.isSubsetOf(computeKnownBits(V, Depth).One);
2554 }
2555 
2556 /// isSplatValue - Return true if the vector V has the same value
2557 /// across all DemandedElts. For scalable vectors it does not make
2558 /// sense to specify which elements are demanded or undefined, therefore
2559 /// they are simply ignored.
2560 bool SelectionDAG::isSplatValue(SDValue V, const APInt &DemandedElts,
2561                                 APInt &UndefElts, unsigned Depth) const {
2562   unsigned Opcode = V.getOpcode();
2563   EVT VT = V.getValueType();
2564   assert(VT.isVector() && "Vector type expected");
2565 
2566   if (!VT.isScalableVector() && !DemandedElts)
2567     return false; // No demanded elts, better to assume we don't know anything.
2568 
2569   if (Depth >= MaxRecursionDepth)
2570     return false; // Limit search depth.
2571 
2572   // Deal with some common cases here that work for both fixed and scalable
2573   // vector types.
2574   switch (Opcode) {
2575   case ISD::SPLAT_VECTOR:
2576     UndefElts = V.getOperand(0).isUndef()
2577                     ? APInt::getAllOnes(DemandedElts.getBitWidth())
2578                     : APInt(DemandedElts.getBitWidth(), 0);
2579     return true;
2580   case ISD::ADD:
2581   case ISD::SUB:
2582   case ISD::AND:
2583   case ISD::XOR:
2584   case ISD::OR: {
2585     APInt UndefLHS, UndefRHS;
2586     SDValue LHS = V.getOperand(0);
2587     SDValue RHS = V.getOperand(1);
2588     if (isSplatValue(LHS, DemandedElts, UndefLHS, Depth + 1) &&
2589         isSplatValue(RHS, DemandedElts, UndefRHS, Depth + 1)) {
2590       UndefElts = UndefLHS | UndefRHS;
2591       return true;
2592     }
2593     return false;
2594   }
2595   case ISD::ABS:
2596   case ISD::TRUNCATE:
2597   case ISD::SIGN_EXTEND:
2598   case ISD::ZERO_EXTEND:
2599     return isSplatValue(V.getOperand(0), DemandedElts, UndefElts, Depth + 1);
2600   default:
2601     if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
2602         Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID)
2603       return TLI->isSplatValueForTargetNode(V, DemandedElts, UndefElts, Depth);
2604     break;
2605 }
2606 
2607   // We don't support other cases than those above for scalable vectors at
2608   // the moment.
2609   if (VT.isScalableVector())
2610     return false;
2611 
2612   unsigned NumElts = VT.getVectorNumElements();
2613   assert(NumElts == DemandedElts.getBitWidth() && "Vector size mismatch");
2614   UndefElts = APInt::getZero(NumElts);
2615 
2616   switch (Opcode) {
2617   case ISD::BUILD_VECTOR: {
2618     SDValue Scl;
2619     for (unsigned i = 0; i != NumElts; ++i) {
2620       SDValue Op = V.getOperand(i);
2621       if (Op.isUndef()) {
2622         UndefElts.setBit(i);
2623         continue;
2624       }
2625       if (!DemandedElts[i])
2626         continue;
2627       if (Scl && Scl != Op)
2628         return false;
2629       Scl = Op;
2630     }
2631     return true;
2632   }
2633   case ISD::VECTOR_SHUFFLE: {
2634     // Check if this is a shuffle node doing a splat or a shuffle of a splat.
2635     APInt DemandedLHS = APInt::getNullValue(NumElts);
2636     APInt DemandedRHS = APInt::getNullValue(NumElts);
2637     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(V)->getMask();
2638     for (int i = 0; i != (int)NumElts; ++i) {
2639       int M = Mask[i];
2640       if (M < 0) {
2641         UndefElts.setBit(i);
2642         continue;
2643       }
2644       if (!DemandedElts[i])
2645         continue;
2646       if (M < (int)NumElts)
2647         DemandedLHS.setBit(M);
2648       else
2649         DemandedRHS.setBit(M - NumElts);
2650     }
2651 
2652     // If we aren't demanding either op, assume there's no splat.
2653     // If we are demanding both ops, assume there's no splat.
2654     if ((DemandedLHS.isZero() && DemandedRHS.isZero()) ||
2655         (!DemandedLHS.isZero() && !DemandedRHS.isZero()))
2656       return false;
2657 
2658     // See if the demanded elts of the source op is a splat or we only demand
2659     // one element, which should always be a splat.
2660     // TODO: Handle source ops splats with undefs.
2661     auto CheckSplatSrc = [&](SDValue Src, const APInt &SrcElts) {
2662       APInt SrcUndefs;
2663       return (SrcElts.countPopulation() == 1) ||
2664              (isSplatValue(Src, SrcElts, SrcUndefs, Depth + 1) &&
2665               (SrcElts & SrcUndefs).isZero());
2666     };
2667     if (!DemandedLHS.isZero())
2668       return CheckSplatSrc(V.getOperand(0), DemandedLHS);
2669     return CheckSplatSrc(V.getOperand(1), DemandedRHS);
2670   }
2671   case ISD::EXTRACT_SUBVECTOR: {
2672     // Offset the demanded elts by the subvector index.
2673     SDValue Src = V.getOperand(0);
2674     // We don't support scalable vectors at the moment.
2675     if (Src.getValueType().isScalableVector())
2676       return false;
2677     uint64_t Idx = V.getConstantOperandVal(1);
2678     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2679     APInt UndefSrcElts;
2680     APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
2681     if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) {
2682       UndefElts = UndefSrcElts.extractBits(NumElts, Idx);
2683       return true;
2684     }
2685     break;
2686   }
2687   case ISD::ANY_EXTEND_VECTOR_INREG:
2688   case ISD::SIGN_EXTEND_VECTOR_INREG:
2689   case ISD::ZERO_EXTEND_VECTOR_INREG: {
2690     // Widen the demanded elts by the src element count.
2691     SDValue Src = V.getOperand(0);
2692     // We don't support scalable vectors at the moment.
2693     if (Src.getValueType().isScalableVector())
2694       return false;
2695     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2696     APInt UndefSrcElts;
2697     APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts);
2698     if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) {
2699       UndefElts = UndefSrcElts.trunc(NumElts);
2700       return true;
2701     }
2702     break;
2703   }
2704   case ISD::BITCAST: {
2705     SDValue Src = V.getOperand(0);
2706     EVT SrcVT = Src.getValueType();
2707     unsigned SrcBitWidth = SrcVT.getScalarSizeInBits();
2708     unsigned BitWidth = VT.getScalarSizeInBits();
2709 
2710     // Ignore bitcasts from unsupported types.
2711     // TODO: Add fp support?
2712     if (!SrcVT.isVector() || !SrcVT.isInteger() || !VT.isInteger())
2713       break;
2714 
2715     // Bitcast 'small element' vector to 'large element' vector.
2716     if ((BitWidth % SrcBitWidth) == 0) {
2717       // See if each sub element is a splat.
2718       unsigned Scale = BitWidth / SrcBitWidth;
2719       unsigned NumSrcElts = SrcVT.getVectorNumElements();
2720       APInt ScaledDemandedElts =
2721           APIntOps::ScaleBitMask(DemandedElts, NumSrcElts);
2722       for (unsigned I = 0; I != Scale; ++I) {
2723         APInt SubUndefElts;
2724         APInt SubDemandedElt = APInt::getOneBitSet(Scale, I);
2725         APInt SubDemandedElts = APInt::getSplat(NumSrcElts, SubDemandedElt);
2726         SubDemandedElts &= ScaledDemandedElts;
2727         if (!isSplatValue(Src, SubDemandedElts, SubUndefElts, Depth + 1))
2728           return false;
2729         UndefElts |= APIntOps::ScaleBitMask(SubUndefElts, NumElts);
2730       }
2731       return true;
2732     }
2733     break;
2734   }
2735   }
2736 
2737   return false;
2738 }
2739 
2740 /// Helper wrapper to main isSplatValue function.
2741 bool SelectionDAG::isSplatValue(SDValue V, bool AllowUndefs) const {
2742   EVT VT = V.getValueType();
2743   assert(VT.isVector() && "Vector type expected");
2744 
2745   APInt UndefElts;
2746   APInt DemandedElts;
2747 
2748   // For now we don't support this with scalable vectors.
2749   if (!VT.isScalableVector())
2750     DemandedElts = APInt::getAllOnes(VT.getVectorNumElements());
2751   return isSplatValue(V, DemandedElts, UndefElts) &&
2752          (AllowUndefs || !UndefElts);
2753 }
2754 
2755 SDValue SelectionDAG::getSplatSourceVector(SDValue V, int &SplatIdx) {
2756   V = peekThroughExtractSubvectors(V);
2757 
2758   EVT VT = V.getValueType();
2759   unsigned Opcode = V.getOpcode();
2760   switch (Opcode) {
2761   default: {
2762     APInt UndefElts;
2763     APInt DemandedElts;
2764 
2765     if (!VT.isScalableVector())
2766       DemandedElts = APInt::getAllOnes(VT.getVectorNumElements());
2767 
2768     if (isSplatValue(V, DemandedElts, UndefElts)) {
2769       if (VT.isScalableVector()) {
2770         // DemandedElts and UndefElts are ignored for scalable vectors, since
2771         // the only supported cases are SPLAT_VECTOR nodes.
2772         SplatIdx = 0;
2773       } else {
2774         // Handle case where all demanded elements are UNDEF.
2775         if (DemandedElts.isSubsetOf(UndefElts)) {
2776           SplatIdx = 0;
2777           return getUNDEF(VT);
2778         }
2779         SplatIdx = (UndefElts & DemandedElts).countTrailingOnes();
2780       }
2781       return V;
2782     }
2783     break;
2784   }
2785   case ISD::SPLAT_VECTOR:
2786     SplatIdx = 0;
2787     return V;
2788   case ISD::VECTOR_SHUFFLE: {
2789     if (VT.isScalableVector())
2790       return SDValue();
2791 
2792     // Check if this is a shuffle node doing a splat.
2793     // TODO - remove this and rely purely on SelectionDAG::isSplatValue,
2794     // getTargetVShiftNode currently struggles without the splat source.
2795     auto *SVN = cast<ShuffleVectorSDNode>(V);
2796     if (!SVN->isSplat())
2797       break;
2798     int Idx = SVN->getSplatIndex();
2799     int NumElts = V.getValueType().getVectorNumElements();
2800     SplatIdx = Idx % NumElts;
2801     return V.getOperand(Idx / NumElts);
2802   }
2803   }
2804 
2805   return SDValue();
2806 }
2807 
2808 SDValue SelectionDAG::getSplatValue(SDValue V, bool LegalTypes) {
2809   int SplatIdx;
2810   if (SDValue SrcVector = getSplatSourceVector(V, SplatIdx)) {
2811     EVT SVT = SrcVector.getValueType().getScalarType();
2812     EVT LegalSVT = SVT;
2813     if (LegalTypes && !TLI->isTypeLegal(SVT)) {
2814       if (!SVT.isInteger())
2815         return SDValue();
2816       LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
2817       if (LegalSVT.bitsLT(SVT))
2818         return SDValue();
2819     }
2820     return getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(V), LegalSVT, SrcVector,
2821                    getVectorIdxConstant(SplatIdx, SDLoc(V)));
2822   }
2823   return SDValue();
2824 }
2825 
2826 const APInt *
2827 SelectionDAG::getValidShiftAmountConstant(SDValue V,
2828                                           const APInt &DemandedElts) const {
2829   assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
2830           V.getOpcode() == ISD::SRA) &&
2831          "Unknown shift node");
2832   unsigned BitWidth = V.getScalarValueSizeInBits();
2833   if (ConstantSDNode *SA = isConstOrConstSplat(V.getOperand(1), DemandedElts)) {
2834     // Shifting more than the bitwidth is not valid.
2835     const APInt &ShAmt = SA->getAPIntValue();
2836     if (ShAmt.ult(BitWidth))
2837       return &ShAmt;
2838   }
2839   return nullptr;
2840 }
2841 
2842 const APInt *SelectionDAG::getValidMinimumShiftAmountConstant(
2843     SDValue V, const APInt &DemandedElts) const {
2844   assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
2845           V.getOpcode() == ISD::SRA) &&
2846          "Unknown shift node");
2847   if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts))
2848     return ValidAmt;
2849   unsigned BitWidth = V.getScalarValueSizeInBits();
2850   auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1));
2851   if (!BV)
2852     return nullptr;
2853   const APInt *MinShAmt = nullptr;
2854   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
2855     if (!DemandedElts[i])
2856       continue;
2857     auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i));
2858     if (!SA)
2859       return nullptr;
2860     // Shifting more than the bitwidth is not valid.
2861     const APInt &ShAmt = SA->getAPIntValue();
2862     if (ShAmt.uge(BitWidth))
2863       return nullptr;
2864     if (MinShAmt && MinShAmt->ule(ShAmt))
2865       continue;
2866     MinShAmt = &ShAmt;
2867   }
2868   return MinShAmt;
2869 }
2870 
2871 const APInt *SelectionDAG::getValidMaximumShiftAmountConstant(
2872     SDValue V, const APInt &DemandedElts) const {
2873   assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
2874           V.getOpcode() == ISD::SRA) &&
2875          "Unknown shift node");
2876   if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts))
2877     return ValidAmt;
2878   unsigned BitWidth = V.getScalarValueSizeInBits();
2879   auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1));
2880   if (!BV)
2881     return nullptr;
2882   const APInt *MaxShAmt = nullptr;
2883   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
2884     if (!DemandedElts[i])
2885       continue;
2886     auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i));
2887     if (!SA)
2888       return nullptr;
2889     // Shifting more than the bitwidth is not valid.
2890     const APInt &ShAmt = SA->getAPIntValue();
2891     if (ShAmt.uge(BitWidth))
2892       return nullptr;
2893     if (MaxShAmt && MaxShAmt->uge(ShAmt))
2894       continue;
2895     MaxShAmt = &ShAmt;
2896   }
2897   return MaxShAmt;
2898 }
2899 
2900 /// Determine which bits of Op are known to be either zero or one and return
2901 /// them in Known. For vectors, the known bits are those that are shared by
2902 /// every vector element.
2903 KnownBits SelectionDAG::computeKnownBits(SDValue Op, unsigned Depth) const {
2904   EVT VT = Op.getValueType();
2905 
2906   // TOOD: Until we have a plan for how to represent demanded elements for
2907   // scalable vectors, we can just bail out for now.
2908   if (Op.getValueType().isScalableVector()) {
2909     unsigned BitWidth = Op.getScalarValueSizeInBits();
2910     return KnownBits(BitWidth);
2911   }
2912 
2913   APInt DemandedElts = VT.isVector()
2914                            ? APInt::getAllOnes(VT.getVectorNumElements())
2915                            : APInt(1, 1);
2916   return computeKnownBits(Op, DemandedElts, Depth);
2917 }
2918 
2919 /// Determine which bits of Op are known to be either zero or one and return
2920 /// them in Known. The DemandedElts argument allows us to only collect the known
2921 /// bits that are shared by the requested vector elements.
2922 KnownBits SelectionDAG::computeKnownBits(SDValue Op, const APInt &DemandedElts,
2923                                          unsigned Depth) const {
2924   unsigned BitWidth = Op.getScalarValueSizeInBits();
2925 
2926   KnownBits Known(BitWidth);   // Don't know anything.
2927 
2928   // TOOD: Until we have a plan for how to represent demanded elements for
2929   // scalable vectors, we can just bail out for now.
2930   if (Op.getValueType().isScalableVector())
2931     return Known;
2932 
2933   if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
2934     // We know all of the bits for a constant!
2935     return KnownBits::makeConstant(C->getAPIntValue());
2936   }
2937   if (auto *C = dyn_cast<ConstantFPSDNode>(Op)) {
2938     // We know all of the bits for a constant fp!
2939     return KnownBits::makeConstant(C->getValueAPF().bitcastToAPInt());
2940   }
2941 
2942   if (Depth >= MaxRecursionDepth)
2943     return Known;  // Limit search depth.
2944 
2945   KnownBits Known2;
2946   unsigned NumElts = DemandedElts.getBitWidth();
2947   assert((!Op.getValueType().isVector() ||
2948           NumElts == Op.getValueType().getVectorNumElements()) &&
2949          "Unexpected vector size");
2950 
2951   if (!DemandedElts)
2952     return Known;  // No demanded elts, better to assume we don't know anything.
2953 
2954   unsigned Opcode = Op.getOpcode();
2955   switch (Opcode) {
2956   case ISD::BUILD_VECTOR:
2957     // Collect the known bits that are shared by every demanded vector element.
2958     Known.Zero.setAllBits(); Known.One.setAllBits();
2959     for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
2960       if (!DemandedElts[i])
2961         continue;
2962 
2963       SDValue SrcOp = Op.getOperand(i);
2964       Known2 = computeKnownBits(SrcOp, Depth + 1);
2965 
2966       // BUILD_VECTOR can implicitly truncate sources, we must handle this.
2967       if (SrcOp.getValueSizeInBits() != BitWidth) {
2968         assert(SrcOp.getValueSizeInBits() > BitWidth &&
2969                "Expected BUILD_VECTOR implicit truncation");
2970         Known2 = Known2.trunc(BitWidth);
2971       }
2972 
2973       // Known bits are the values that are shared by every demanded element.
2974       Known = KnownBits::commonBits(Known, Known2);
2975 
2976       // If we don't know any bits, early out.
2977       if (Known.isUnknown())
2978         break;
2979     }
2980     break;
2981   case ISD::VECTOR_SHUFFLE: {
2982     // Collect the known bits that are shared by every vector element referenced
2983     // by the shuffle.
2984     APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
2985     Known.Zero.setAllBits(); Known.One.setAllBits();
2986     const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
2987     assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
2988     for (unsigned i = 0; i != NumElts; ++i) {
2989       if (!DemandedElts[i])
2990         continue;
2991 
2992       int M = SVN->getMaskElt(i);
2993       if (M < 0) {
2994         // For UNDEF elements, we don't know anything about the common state of
2995         // the shuffle result.
2996         Known.resetAll();
2997         DemandedLHS.clearAllBits();
2998         DemandedRHS.clearAllBits();
2999         break;
3000       }
3001 
3002       if ((unsigned)M < NumElts)
3003         DemandedLHS.setBit((unsigned)M % NumElts);
3004       else
3005         DemandedRHS.setBit((unsigned)M % NumElts);
3006     }
3007     // Known bits are the values that are shared by every demanded element.
3008     if (!!DemandedLHS) {
3009       SDValue LHS = Op.getOperand(0);
3010       Known2 = computeKnownBits(LHS, DemandedLHS, Depth + 1);
3011       Known = KnownBits::commonBits(Known, Known2);
3012     }
3013     // If we don't know any bits, early out.
3014     if (Known.isUnknown())
3015       break;
3016     if (!!DemandedRHS) {
3017       SDValue RHS = Op.getOperand(1);
3018       Known2 = computeKnownBits(RHS, DemandedRHS, Depth + 1);
3019       Known = KnownBits::commonBits(Known, Known2);
3020     }
3021     break;
3022   }
3023   case ISD::CONCAT_VECTORS: {
3024     // Split DemandedElts and test each of the demanded subvectors.
3025     Known.Zero.setAllBits(); Known.One.setAllBits();
3026     EVT SubVectorVT = Op.getOperand(0).getValueType();
3027     unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
3028     unsigned NumSubVectors = Op.getNumOperands();
3029     for (unsigned i = 0; i != NumSubVectors; ++i) {
3030       APInt DemandedSub =
3031           DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts);
3032       if (!!DemandedSub) {
3033         SDValue Sub = Op.getOperand(i);
3034         Known2 = computeKnownBits(Sub, DemandedSub, Depth + 1);
3035         Known = KnownBits::commonBits(Known, Known2);
3036       }
3037       // If we don't know any bits, early out.
3038       if (Known.isUnknown())
3039         break;
3040     }
3041     break;
3042   }
3043   case ISD::INSERT_SUBVECTOR: {
3044     // Demand any elements from the subvector and the remainder from the src its
3045     // inserted into.
3046     SDValue Src = Op.getOperand(0);
3047     SDValue Sub = Op.getOperand(1);
3048     uint64_t Idx = Op.getConstantOperandVal(2);
3049     unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
3050     APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
3051     APInt DemandedSrcElts = DemandedElts;
3052     DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx);
3053 
3054     Known.One.setAllBits();
3055     Known.Zero.setAllBits();
3056     if (!!DemandedSubElts) {
3057       Known = computeKnownBits(Sub, DemandedSubElts, Depth + 1);
3058       if (Known.isUnknown())
3059         break; // early-out.
3060     }
3061     if (!!DemandedSrcElts) {
3062       Known2 = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
3063       Known = KnownBits::commonBits(Known, Known2);
3064     }
3065     break;
3066   }
3067   case ISD::EXTRACT_SUBVECTOR: {
3068     // Offset the demanded elts by the subvector index.
3069     SDValue Src = Op.getOperand(0);
3070     // Bail until we can represent demanded elements for scalable vectors.
3071     if (Src.getValueType().isScalableVector())
3072       break;
3073     uint64_t Idx = Op.getConstantOperandVal(1);
3074     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
3075     APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
3076     Known = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
3077     break;
3078   }
3079   case ISD::SCALAR_TO_VECTOR: {
3080     // We know about scalar_to_vector as much as we know about it source,
3081     // which becomes the first element of otherwise unknown vector.
3082     if (DemandedElts != 1)
3083       break;
3084 
3085     SDValue N0 = Op.getOperand(0);
3086     Known = computeKnownBits(N0, Depth + 1);
3087     if (N0.getValueSizeInBits() != BitWidth)
3088       Known = Known.trunc(BitWidth);
3089 
3090     break;
3091   }
3092   case ISD::BITCAST: {
3093     SDValue N0 = Op.getOperand(0);
3094     EVT SubVT = N0.getValueType();
3095     unsigned SubBitWidth = SubVT.getScalarSizeInBits();
3096 
3097     // Ignore bitcasts from unsupported types.
3098     if (!(SubVT.isInteger() || SubVT.isFloatingPoint()))
3099       break;
3100 
3101     // Fast handling of 'identity' bitcasts.
3102     if (BitWidth == SubBitWidth) {
3103       Known = computeKnownBits(N0, DemandedElts, Depth + 1);
3104       break;
3105     }
3106 
3107     bool IsLE = getDataLayout().isLittleEndian();
3108 
3109     // Bitcast 'small element' vector to 'large element' scalar/vector.
3110     if ((BitWidth % SubBitWidth) == 0) {
3111       assert(N0.getValueType().isVector() && "Expected bitcast from vector");
3112 
3113       // Collect known bits for the (larger) output by collecting the known
3114       // bits from each set of sub elements and shift these into place.
3115       // We need to separately call computeKnownBits for each set of
3116       // sub elements as the knownbits for each is likely to be different.
3117       unsigned SubScale = BitWidth / SubBitWidth;
3118       APInt SubDemandedElts(NumElts * SubScale, 0);
3119       for (unsigned i = 0; i != NumElts; ++i)
3120         if (DemandedElts[i])
3121           SubDemandedElts.setBit(i * SubScale);
3122 
3123       for (unsigned i = 0; i != SubScale; ++i) {
3124         Known2 = computeKnownBits(N0, SubDemandedElts.shl(i),
3125                          Depth + 1);
3126         unsigned Shifts = IsLE ? i : SubScale - 1 - i;
3127         Known.insertBits(Known2, SubBitWidth * Shifts);
3128       }
3129     }
3130 
3131     // Bitcast 'large element' scalar/vector to 'small element' vector.
3132     if ((SubBitWidth % BitWidth) == 0) {
3133       assert(Op.getValueType().isVector() && "Expected bitcast to vector");
3134 
3135       // Collect known bits for the (smaller) output by collecting the known
3136       // bits from the overlapping larger input elements and extracting the
3137       // sub sections we actually care about.
3138       unsigned SubScale = SubBitWidth / BitWidth;
3139       APInt SubDemandedElts =
3140           APIntOps::ScaleBitMask(DemandedElts, NumElts / SubScale);
3141       Known2 = computeKnownBits(N0, SubDemandedElts, Depth + 1);
3142 
3143       Known.Zero.setAllBits(); Known.One.setAllBits();
3144       for (unsigned i = 0; i != NumElts; ++i)
3145         if (DemandedElts[i]) {
3146           unsigned Shifts = IsLE ? i : NumElts - 1 - i;
3147           unsigned Offset = (Shifts % SubScale) * BitWidth;
3148           Known = KnownBits::commonBits(Known,
3149                                         Known2.extractBits(BitWidth, Offset));
3150           // If we don't know any bits, early out.
3151           if (Known.isUnknown())
3152             break;
3153         }
3154     }
3155     break;
3156   }
3157   case ISD::AND:
3158     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3159     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3160 
3161     Known &= Known2;
3162     break;
3163   case ISD::OR:
3164     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3165     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3166 
3167     Known |= Known2;
3168     break;
3169   case ISD::XOR:
3170     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3171     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3172 
3173     Known ^= Known2;
3174     break;
3175   case ISD::MUL: {
3176     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3177     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3178     bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1);
3179     // TODO: SelfMultiply can be poison, but not undef.
3180     if (SelfMultiply)
3181       SelfMultiply &= isGuaranteedNotToBeUndefOrPoison(
3182           Op.getOperand(0), DemandedElts, false, Depth + 1);
3183     Known = KnownBits::mul(Known, Known2, SelfMultiply);
3184 
3185     // If the multiplication is known not to overflow, the product of a number
3186     // with itself is non-negative. Only do this if we didn't already computed
3187     // the opposite value for the sign bit.
3188     if (Op->getFlags().hasNoSignedWrap() &&
3189         Op.getOperand(0) == Op.getOperand(1) &&
3190         !Known.isNegative())
3191       Known.makeNonNegative();
3192     break;
3193   }
3194   case ISD::MULHU: {
3195     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3196     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3197     Known = KnownBits::mulhu(Known, Known2);
3198     break;
3199   }
3200   case ISD::MULHS: {
3201     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3202     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3203     Known = KnownBits::mulhs(Known, Known2);
3204     break;
3205   }
3206   case ISD::UMUL_LOHI: {
3207     assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3208     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3209     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3210     bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1);
3211     if (Op.getResNo() == 0)
3212       Known = KnownBits::mul(Known, Known2, SelfMultiply);
3213     else
3214       Known = KnownBits::mulhu(Known, Known2);
3215     break;
3216   }
3217   case ISD::SMUL_LOHI: {
3218     assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3219     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3220     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3221     bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1);
3222     if (Op.getResNo() == 0)
3223       Known = KnownBits::mul(Known, Known2, SelfMultiply);
3224     else
3225       Known = KnownBits::mulhs(Known, Known2);
3226     break;
3227   }
3228   case ISD::UDIV: {
3229     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3230     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3231     Known = KnownBits::udiv(Known, Known2);
3232     break;
3233   }
3234   case ISD::AVGCEILU: {
3235     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3236     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3237     Known = Known.zext(BitWidth + 1);
3238     Known2 = Known2.zext(BitWidth + 1);
3239     KnownBits One = KnownBits::makeConstant(APInt(1, 1));
3240     Known = KnownBits::computeForAddCarry(Known, Known2, One);
3241     Known = Known.extractBits(BitWidth, 1);
3242     break;
3243   }
3244   case ISD::SELECT:
3245   case ISD::VSELECT:
3246     Known = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
3247     // If we don't know any bits, early out.
3248     if (Known.isUnknown())
3249       break;
3250     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth+1);
3251 
3252     // Only known if known in both the LHS and RHS.
3253     Known = KnownBits::commonBits(Known, Known2);
3254     break;
3255   case ISD::SELECT_CC:
3256     Known = computeKnownBits(Op.getOperand(3), DemandedElts, Depth+1);
3257     // If we don't know any bits, early out.
3258     if (Known.isUnknown())
3259       break;
3260     Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
3261 
3262     // Only known if known in both the LHS and RHS.
3263     Known = KnownBits::commonBits(Known, Known2);
3264     break;
3265   case ISD::SMULO:
3266   case ISD::UMULO:
3267     if (Op.getResNo() != 1)
3268       break;
3269     // The boolean result conforms to getBooleanContents.
3270     // If we know the result of a setcc has the top bits zero, use this info.
3271     // We know that we have an integer-based boolean since these operations
3272     // are only available for integer.
3273     if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
3274             TargetLowering::ZeroOrOneBooleanContent &&
3275         BitWidth > 1)
3276       Known.Zero.setBitsFrom(1);
3277     break;
3278   case ISD::SETCC:
3279   case ISD::STRICT_FSETCC:
3280   case ISD::STRICT_FSETCCS: {
3281     unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
3282     // If we know the result of a setcc has the top bits zero, use this info.
3283     if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
3284             TargetLowering::ZeroOrOneBooleanContent &&
3285         BitWidth > 1)
3286       Known.Zero.setBitsFrom(1);
3287     break;
3288   }
3289   case ISD::SHL:
3290     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3291     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3292     Known = KnownBits::shl(Known, Known2);
3293 
3294     // Minimum shift low bits are known zero.
3295     if (const APInt *ShMinAmt =
3296             getValidMinimumShiftAmountConstant(Op, DemandedElts))
3297       Known.Zero.setLowBits(ShMinAmt->getZExtValue());
3298     break;
3299   case ISD::SRL:
3300     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3301     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3302     Known = KnownBits::lshr(Known, Known2);
3303 
3304     // Minimum shift high bits are known zero.
3305     if (const APInt *ShMinAmt =
3306             getValidMinimumShiftAmountConstant(Op, DemandedElts))
3307       Known.Zero.setHighBits(ShMinAmt->getZExtValue());
3308     break;
3309   case ISD::SRA:
3310     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3311     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3312     Known = KnownBits::ashr(Known, Known2);
3313     // TODO: Add minimum shift high known sign bits.
3314     break;
3315   case ISD::FSHL:
3316   case ISD::FSHR:
3317     if (ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(2), DemandedElts)) {
3318       unsigned Amt = C->getAPIntValue().urem(BitWidth);
3319 
3320       // For fshl, 0-shift returns the 1st arg.
3321       // For fshr, 0-shift returns the 2nd arg.
3322       if (Amt == 0) {
3323         Known = computeKnownBits(Op.getOperand(Opcode == ISD::FSHL ? 0 : 1),
3324                                  DemandedElts, Depth + 1);
3325         break;
3326       }
3327 
3328       // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
3329       // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
3330       Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3331       Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3332       if (Opcode == ISD::FSHL) {
3333         Known.One <<= Amt;
3334         Known.Zero <<= Amt;
3335         Known2.One.lshrInPlace(BitWidth - Amt);
3336         Known2.Zero.lshrInPlace(BitWidth - Amt);
3337       } else {
3338         Known.One <<= BitWidth - Amt;
3339         Known.Zero <<= BitWidth - Amt;
3340         Known2.One.lshrInPlace(Amt);
3341         Known2.Zero.lshrInPlace(Amt);
3342       }
3343       Known.One |= Known2.One;
3344       Known.Zero |= Known2.Zero;
3345     }
3346     break;
3347   case ISD::SIGN_EXTEND_INREG: {
3348     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3349     EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3350     Known = Known.sextInReg(EVT.getScalarSizeInBits());
3351     break;
3352   }
3353   case ISD::CTTZ:
3354   case ISD::CTTZ_ZERO_UNDEF: {
3355     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3356     // If we have a known 1, its position is our upper bound.
3357     unsigned PossibleTZ = Known2.countMaxTrailingZeros();
3358     unsigned LowBits = Log2_32(PossibleTZ) + 1;
3359     Known.Zero.setBitsFrom(LowBits);
3360     break;
3361   }
3362   case ISD::CTLZ:
3363   case ISD::CTLZ_ZERO_UNDEF: {
3364     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3365     // If we have a known 1, its position is our upper bound.
3366     unsigned PossibleLZ = Known2.countMaxLeadingZeros();
3367     unsigned LowBits = Log2_32(PossibleLZ) + 1;
3368     Known.Zero.setBitsFrom(LowBits);
3369     break;
3370   }
3371   case ISD::CTPOP: {
3372     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3373     // If we know some of the bits are zero, they can't be one.
3374     unsigned PossibleOnes = Known2.countMaxPopulation();
3375     Known.Zero.setBitsFrom(Log2_32(PossibleOnes) + 1);
3376     break;
3377   }
3378   case ISD::PARITY: {
3379     // Parity returns 0 everywhere but the LSB.
3380     Known.Zero.setBitsFrom(1);
3381     break;
3382   }
3383   case ISD::LOAD: {
3384     LoadSDNode *LD = cast<LoadSDNode>(Op);
3385     const Constant *Cst = TLI->getTargetConstantFromLoad(LD);
3386     if (ISD::isNON_EXTLoad(LD) && Cst) {
3387       // Determine any common known bits from the loaded constant pool value.
3388       Type *CstTy = Cst->getType();
3389       if ((NumElts * BitWidth) == CstTy->getPrimitiveSizeInBits()) {
3390         // If its a vector splat, then we can (quickly) reuse the scalar path.
3391         // NOTE: We assume all elements match and none are UNDEF.
3392         if (CstTy->isVectorTy()) {
3393           if (const Constant *Splat = Cst->getSplatValue()) {
3394             Cst = Splat;
3395             CstTy = Cst->getType();
3396           }
3397         }
3398         // TODO - do we need to handle different bitwidths?
3399         if (CstTy->isVectorTy() && BitWidth == CstTy->getScalarSizeInBits()) {
3400           // Iterate across all vector elements finding common known bits.
3401           Known.One.setAllBits();
3402           Known.Zero.setAllBits();
3403           for (unsigned i = 0; i != NumElts; ++i) {
3404             if (!DemandedElts[i])
3405               continue;
3406             if (Constant *Elt = Cst->getAggregateElement(i)) {
3407               if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
3408                 const APInt &Value = CInt->getValue();
3409                 Known.One &= Value;
3410                 Known.Zero &= ~Value;
3411                 continue;
3412               }
3413               if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
3414                 APInt Value = CFP->getValueAPF().bitcastToAPInt();
3415                 Known.One &= Value;
3416                 Known.Zero &= ~Value;
3417                 continue;
3418               }
3419             }
3420             Known.One.clearAllBits();
3421             Known.Zero.clearAllBits();
3422             break;
3423           }
3424         } else if (BitWidth == CstTy->getPrimitiveSizeInBits()) {
3425           if (auto *CInt = dyn_cast<ConstantInt>(Cst)) {
3426             Known = KnownBits::makeConstant(CInt->getValue());
3427           } else if (auto *CFP = dyn_cast<ConstantFP>(Cst)) {
3428             Known =
3429                 KnownBits::makeConstant(CFP->getValueAPF().bitcastToAPInt());
3430           }
3431         }
3432       }
3433     } else if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) {
3434       // If this is a ZEXTLoad and we are looking at the loaded value.
3435       EVT VT = LD->getMemoryVT();
3436       unsigned MemBits = VT.getScalarSizeInBits();
3437       Known.Zero.setBitsFrom(MemBits);
3438     } else if (const MDNode *Ranges = LD->getRanges()) {
3439       if (LD->getExtensionType() == ISD::NON_EXTLOAD)
3440         computeKnownBitsFromRangeMetadata(*Ranges, Known);
3441     }
3442     break;
3443   }
3444   case ISD::ZERO_EXTEND_VECTOR_INREG: {
3445     EVT InVT = Op.getOperand(0).getValueType();
3446     APInt InDemandedElts = DemandedElts.zext(InVT.getVectorNumElements());
3447     Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3448     Known = Known.zext(BitWidth);
3449     break;
3450   }
3451   case ISD::ZERO_EXTEND: {
3452     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3453     Known = Known.zext(BitWidth);
3454     break;
3455   }
3456   case ISD::SIGN_EXTEND_VECTOR_INREG: {
3457     EVT InVT = Op.getOperand(0).getValueType();
3458     APInt InDemandedElts = DemandedElts.zext(InVT.getVectorNumElements());
3459     Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3460     // If the sign bit is known to be zero or one, then sext will extend
3461     // it to the top bits, else it will just zext.
3462     Known = Known.sext(BitWidth);
3463     break;
3464   }
3465   case ISD::SIGN_EXTEND: {
3466     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3467     // If the sign bit is known to be zero or one, then sext will extend
3468     // it to the top bits, else it will just zext.
3469     Known = Known.sext(BitWidth);
3470     break;
3471   }
3472   case ISD::ANY_EXTEND_VECTOR_INREG: {
3473     EVT InVT = Op.getOperand(0).getValueType();
3474     APInt InDemandedElts = DemandedElts.zext(InVT.getVectorNumElements());
3475     Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3476     Known = Known.anyext(BitWidth);
3477     break;
3478   }
3479   case ISD::ANY_EXTEND: {
3480     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3481     Known = Known.anyext(BitWidth);
3482     break;
3483   }
3484   case ISD::TRUNCATE: {
3485     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3486     Known = Known.trunc(BitWidth);
3487     break;
3488   }
3489   case ISD::AssertZext: {
3490     EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3491     APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits());
3492     Known = computeKnownBits(Op.getOperand(0), Depth+1);
3493     Known.Zero |= (~InMask);
3494     Known.One  &= (~Known.Zero);
3495     break;
3496   }
3497   case ISD::AssertAlign: {
3498     unsigned LogOfAlign = Log2(cast<AssertAlignSDNode>(Op)->getAlign());
3499     assert(LogOfAlign != 0);
3500 
3501     // TODO: Should use maximum with source
3502     // If a node is guaranteed to be aligned, set low zero bits accordingly as
3503     // well as clearing one bits.
3504     Known.Zero.setLowBits(LogOfAlign);
3505     Known.One.clearLowBits(LogOfAlign);
3506     break;
3507   }
3508   case ISD::FGETSIGN:
3509     // All bits are zero except the low bit.
3510     Known.Zero.setBitsFrom(1);
3511     break;
3512   case ISD::USUBO:
3513   case ISD::SSUBO:
3514     if (Op.getResNo() == 1) {
3515       // If we know the result of a setcc has the top bits zero, use this info.
3516       if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
3517               TargetLowering::ZeroOrOneBooleanContent &&
3518           BitWidth > 1)
3519         Known.Zero.setBitsFrom(1);
3520       break;
3521     }
3522     LLVM_FALLTHROUGH;
3523   case ISD::SUB:
3524   case ISD::SUBC: {
3525     assert(Op.getResNo() == 0 &&
3526            "We only compute knownbits for the difference here.");
3527 
3528     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3529     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3530     Known = KnownBits::computeForAddSub(/* Add */ false, /* NSW */ false,
3531                                         Known, Known2);
3532     break;
3533   }
3534   case ISD::UADDO:
3535   case ISD::SADDO:
3536   case ISD::ADDCARRY:
3537     if (Op.getResNo() == 1) {
3538       // If we know the result of a setcc has the top bits zero, use this info.
3539       if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
3540               TargetLowering::ZeroOrOneBooleanContent &&
3541           BitWidth > 1)
3542         Known.Zero.setBitsFrom(1);
3543       break;
3544     }
3545     LLVM_FALLTHROUGH;
3546   case ISD::ADD:
3547   case ISD::ADDC:
3548   case ISD::ADDE: {
3549     assert(Op.getResNo() == 0 && "We only compute knownbits for the sum here.");
3550 
3551     // With ADDE and ADDCARRY, a carry bit may be added in.
3552     KnownBits Carry(1);
3553     if (Opcode == ISD::ADDE)
3554       // Can't track carry from glue, set carry to unknown.
3555       Carry.resetAll();
3556     else if (Opcode == ISD::ADDCARRY)
3557       // TODO: Compute known bits for the carry operand. Not sure if it is worth
3558       // the trouble (how often will we find a known carry bit). And I haven't
3559       // tested this very much yet, but something like this might work:
3560       //   Carry = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1);
3561       //   Carry = Carry.zextOrTrunc(1, false);
3562       Carry.resetAll();
3563     else
3564       Carry.setAllZero();
3565 
3566     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3567     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3568     Known = KnownBits::computeForAddCarry(Known, Known2, Carry);
3569     break;
3570   }
3571   case ISD::SREM: {
3572     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3573     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3574     Known = KnownBits::srem(Known, Known2);
3575     break;
3576   }
3577   case ISD::UREM: {
3578     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3579     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3580     Known = KnownBits::urem(Known, Known2);
3581     break;
3582   }
3583   case ISD::EXTRACT_ELEMENT: {
3584     Known = computeKnownBits(Op.getOperand(0), Depth+1);
3585     const unsigned Index = Op.getConstantOperandVal(1);
3586     const unsigned EltBitWidth = Op.getValueSizeInBits();
3587 
3588     // Remove low part of known bits mask
3589     Known.Zero = Known.Zero.getHiBits(Known.getBitWidth() - Index * EltBitWidth);
3590     Known.One = Known.One.getHiBits(Known.getBitWidth() - Index * EltBitWidth);
3591 
3592     // Remove high part of known bit mask
3593     Known = Known.trunc(EltBitWidth);
3594     break;
3595   }
3596   case ISD::EXTRACT_VECTOR_ELT: {
3597     SDValue InVec = Op.getOperand(0);
3598     SDValue EltNo = Op.getOperand(1);
3599     EVT VecVT = InVec.getValueType();
3600     // computeKnownBits not yet implemented for scalable vectors.
3601     if (VecVT.isScalableVector())
3602       break;
3603     const unsigned EltBitWidth = VecVT.getScalarSizeInBits();
3604     const unsigned NumSrcElts = VecVT.getVectorNumElements();
3605 
3606     // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know
3607     // anything about the extended bits.
3608     if (BitWidth > EltBitWidth)
3609       Known = Known.trunc(EltBitWidth);
3610 
3611     // If we know the element index, just demand that vector element, else for
3612     // an unknown element index, ignore DemandedElts and demand them all.
3613     APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
3614     auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
3615     if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
3616       DemandedSrcElts =
3617           APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
3618 
3619     Known = computeKnownBits(InVec, DemandedSrcElts, Depth + 1);
3620     if (BitWidth > EltBitWidth)
3621       Known = Known.anyext(BitWidth);
3622     break;
3623   }
3624   case ISD::INSERT_VECTOR_ELT: {
3625     // If we know the element index, split the demand between the
3626     // source vector and the inserted element, otherwise assume we need
3627     // the original demanded vector elements and the value.
3628     SDValue InVec = Op.getOperand(0);
3629     SDValue InVal = Op.getOperand(1);
3630     SDValue EltNo = Op.getOperand(2);
3631     bool DemandedVal = true;
3632     APInt DemandedVecElts = DemandedElts;
3633     auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
3634     if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
3635       unsigned EltIdx = CEltNo->getZExtValue();
3636       DemandedVal = !!DemandedElts[EltIdx];
3637       DemandedVecElts.clearBit(EltIdx);
3638     }
3639     Known.One.setAllBits();
3640     Known.Zero.setAllBits();
3641     if (DemandedVal) {
3642       Known2 = computeKnownBits(InVal, Depth + 1);
3643       Known = KnownBits::commonBits(Known, Known2.zextOrTrunc(BitWidth));
3644     }
3645     if (!!DemandedVecElts) {
3646       Known2 = computeKnownBits(InVec, DemandedVecElts, Depth + 1);
3647       Known = KnownBits::commonBits(Known, Known2);
3648     }
3649     break;
3650   }
3651   case ISD::BITREVERSE: {
3652     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3653     Known = Known2.reverseBits();
3654     break;
3655   }
3656   case ISD::BSWAP: {
3657     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3658     Known = Known2.byteSwap();
3659     break;
3660   }
3661   case ISD::ABS: {
3662     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3663     Known = Known2.abs();
3664     break;
3665   }
3666   case ISD::USUBSAT: {
3667     // The result of usubsat will never be larger than the LHS.
3668     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3669     Known.Zero.setHighBits(Known2.countMinLeadingZeros());
3670     break;
3671   }
3672   case ISD::UMIN: {
3673     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3674     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3675     Known = KnownBits::umin(Known, Known2);
3676     break;
3677   }
3678   case ISD::UMAX: {
3679     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3680     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3681     Known = KnownBits::umax(Known, Known2);
3682     break;
3683   }
3684   case ISD::SMIN:
3685   case ISD::SMAX: {
3686     // If we have a clamp pattern, we know that the number of sign bits will be
3687     // the minimum of the clamp min/max range.
3688     bool IsMax = (Opcode == ISD::SMAX);
3689     ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
3690     if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
3691       if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
3692         CstHigh =
3693             isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
3694     if (CstLow && CstHigh) {
3695       if (!IsMax)
3696         std::swap(CstLow, CstHigh);
3697 
3698       const APInt &ValueLow = CstLow->getAPIntValue();
3699       const APInt &ValueHigh = CstHigh->getAPIntValue();
3700       if (ValueLow.sle(ValueHigh)) {
3701         unsigned LowSignBits = ValueLow.getNumSignBits();
3702         unsigned HighSignBits = ValueHigh.getNumSignBits();
3703         unsigned MinSignBits = std::min(LowSignBits, HighSignBits);
3704         if (ValueLow.isNegative() && ValueHigh.isNegative()) {
3705           Known.One.setHighBits(MinSignBits);
3706           break;
3707         }
3708         if (ValueLow.isNonNegative() && ValueHigh.isNonNegative()) {
3709           Known.Zero.setHighBits(MinSignBits);
3710           break;
3711         }
3712       }
3713     }
3714 
3715     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3716     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3717     if (IsMax)
3718       Known = KnownBits::smax(Known, Known2);
3719     else
3720       Known = KnownBits::smin(Known, Known2);
3721 
3722     // For SMAX, if CstLow is non-negative we know the result will be
3723     // non-negative and thus all sign bits are 0.
3724     // TODO: There's an equivalent of this for smin with negative constant for
3725     // known ones.
3726     if (IsMax && CstLow) {
3727       const APInt &ValueLow = CstLow->getAPIntValue();
3728       if (ValueLow.isNonNegative()) {
3729         unsigned SignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
3730         Known.Zero.setHighBits(std::min(SignBits, ValueLow.getNumSignBits()));
3731       }
3732     }
3733 
3734     break;
3735   }
3736   case ISD::FP_TO_UINT_SAT: {
3737     // FP_TO_UINT_SAT produces an unsigned value that fits in the saturating VT.
3738     EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3739     Known.Zero |= APInt::getBitsSetFrom(BitWidth, VT.getScalarSizeInBits());
3740     break;
3741   }
3742   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
3743     if (Op.getResNo() == 1) {
3744       // The boolean result conforms to getBooleanContents.
3745       // If we know the result of a setcc has the top bits zero, use this info.
3746       // We know that we have an integer-based boolean since these operations
3747       // are only available for integer.
3748       if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
3749               TargetLowering::ZeroOrOneBooleanContent &&
3750           BitWidth > 1)
3751         Known.Zero.setBitsFrom(1);
3752       break;
3753     }
3754     LLVM_FALLTHROUGH;
3755   case ISD::ATOMIC_CMP_SWAP:
3756   case ISD::ATOMIC_SWAP:
3757   case ISD::ATOMIC_LOAD_ADD:
3758   case ISD::ATOMIC_LOAD_SUB:
3759   case ISD::ATOMIC_LOAD_AND:
3760   case ISD::ATOMIC_LOAD_CLR:
3761   case ISD::ATOMIC_LOAD_OR:
3762   case ISD::ATOMIC_LOAD_XOR:
3763   case ISD::ATOMIC_LOAD_NAND:
3764   case ISD::ATOMIC_LOAD_MIN:
3765   case ISD::ATOMIC_LOAD_MAX:
3766   case ISD::ATOMIC_LOAD_UMIN:
3767   case ISD::ATOMIC_LOAD_UMAX:
3768   case ISD::ATOMIC_LOAD: {
3769     unsigned MemBits =
3770         cast<AtomicSDNode>(Op)->getMemoryVT().getScalarSizeInBits();
3771     // If we are looking at the loaded value.
3772     if (Op.getResNo() == 0) {
3773       if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND)
3774         Known.Zero.setBitsFrom(MemBits);
3775     }
3776     break;
3777   }
3778   case ISD::FrameIndex:
3779   case ISD::TargetFrameIndex:
3780     TLI->computeKnownBitsForFrameIndex(cast<FrameIndexSDNode>(Op)->getIndex(),
3781                                        Known, getMachineFunction());
3782     break;
3783 
3784   default:
3785     if (Opcode < ISD::BUILTIN_OP_END)
3786       break;
3787     LLVM_FALLTHROUGH;
3788   case ISD::INTRINSIC_WO_CHAIN:
3789   case ISD::INTRINSIC_W_CHAIN:
3790   case ISD::INTRINSIC_VOID:
3791     // Allow the target to implement this method for its nodes.
3792     TLI->computeKnownBitsForTargetNode(Op, Known, DemandedElts, *this, Depth);
3793     break;
3794   }
3795 
3796   assert(!Known.hasConflict() && "Bits known to be one AND zero?");
3797   return Known;
3798 }
3799 
3800 SelectionDAG::OverflowKind SelectionDAG::computeOverflowKind(SDValue N0,
3801                                                              SDValue N1) const {
3802   // X + 0 never overflow
3803   if (isNullConstant(N1))
3804     return OFK_Never;
3805 
3806   KnownBits N1Known = computeKnownBits(N1);
3807   if (N1Known.Zero.getBoolValue()) {
3808     KnownBits N0Known = computeKnownBits(N0);
3809 
3810     bool overflow;
3811     (void)N0Known.getMaxValue().uadd_ov(N1Known.getMaxValue(), overflow);
3812     if (!overflow)
3813       return OFK_Never;
3814   }
3815 
3816   // mulhi + 1 never overflow
3817   if (N0.getOpcode() == ISD::UMUL_LOHI && N0.getResNo() == 1 &&
3818       (N1Known.getMaxValue() & 0x01) == N1Known.getMaxValue())
3819     return OFK_Never;
3820 
3821   if (N1.getOpcode() == ISD::UMUL_LOHI && N1.getResNo() == 1) {
3822     KnownBits N0Known = computeKnownBits(N0);
3823 
3824     if ((N0Known.getMaxValue() & 0x01) == N0Known.getMaxValue())
3825       return OFK_Never;
3826   }
3827 
3828   return OFK_Sometime;
3829 }
3830 
3831 bool SelectionDAG::isKnownToBeAPowerOfTwo(SDValue Val) const {
3832   EVT OpVT = Val.getValueType();
3833   unsigned BitWidth = OpVT.getScalarSizeInBits();
3834 
3835   // Is the constant a known power of 2?
3836   if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Val))
3837     return Const->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
3838 
3839   // A left-shift of a constant one will have exactly one bit set because
3840   // shifting the bit off the end is undefined.
3841   if (Val.getOpcode() == ISD::SHL) {
3842     auto *C = isConstOrConstSplat(Val.getOperand(0));
3843     if (C && C->getAPIntValue() == 1)
3844       return true;
3845   }
3846 
3847   // Similarly, a logical right-shift of a constant sign-bit will have exactly
3848   // one bit set.
3849   if (Val.getOpcode() == ISD::SRL) {
3850     auto *C = isConstOrConstSplat(Val.getOperand(0));
3851     if (C && C->getAPIntValue().isSignMask())
3852       return true;
3853   }
3854 
3855   // Are all operands of a build vector constant powers of two?
3856   if (Val.getOpcode() == ISD::BUILD_VECTOR)
3857     if (llvm::all_of(Val->ops(), [BitWidth](SDValue E) {
3858           if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(E))
3859             return C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
3860           return false;
3861         }))
3862       return true;
3863 
3864   // Is the operand of a splat vector a constant power of two?
3865   if (Val.getOpcode() == ISD::SPLAT_VECTOR)
3866     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val->getOperand(0)))
3867       if (C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2())
3868         return true;
3869 
3870   // More could be done here, though the above checks are enough
3871   // to handle some common cases.
3872 
3873   // Fall back to computeKnownBits to catch other known cases.
3874   KnownBits Known = computeKnownBits(Val);
3875   return (Known.countMaxPopulation() == 1) && (Known.countMinPopulation() == 1);
3876 }
3877 
3878 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const {
3879   EVT VT = Op.getValueType();
3880 
3881   // TODO: Assume we don't know anything for now.
3882   if (VT.isScalableVector())
3883     return 1;
3884 
3885   APInt DemandedElts = VT.isVector()
3886                            ? APInt::getAllOnes(VT.getVectorNumElements())
3887                            : APInt(1, 1);
3888   return ComputeNumSignBits(Op, DemandedElts, Depth);
3889 }
3890 
3891 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, const APInt &DemandedElts,
3892                                           unsigned Depth) const {
3893   EVT VT = Op.getValueType();
3894   assert((VT.isInteger() || VT.isFloatingPoint()) && "Invalid VT!");
3895   unsigned VTBits = VT.getScalarSizeInBits();
3896   unsigned NumElts = DemandedElts.getBitWidth();
3897   unsigned Tmp, Tmp2;
3898   unsigned FirstAnswer = 1;
3899 
3900   if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
3901     const APInt &Val = C->getAPIntValue();
3902     return Val.getNumSignBits();
3903   }
3904 
3905   if (Depth >= MaxRecursionDepth)
3906     return 1;  // Limit search depth.
3907 
3908   if (!DemandedElts || VT.isScalableVector())
3909     return 1;  // No demanded elts, better to assume we don't know anything.
3910 
3911   unsigned Opcode = Op.getOpcode();
3912   switch (Opcode) {
3913   default: break;
3914   case ISD::AssertSext:
3915     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
3916     return VTBits-Tmp+1;
3917   case ISD::AssertZext:
3918     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
3919     return VTBits-Tmp;
3920 
3921   case ISD::BUILD_VECTOR:
3922     Tmp = VTBits;
3923     for (unsigned i = 0, e = Op.getNumOperands(); (i < e) && (Tmp > 1); ++i) {
3924       if (!DemandedElts[i])
3925         continue;
3926 
3927       SDValue SrcOp = Op.getOperand(i);
3928       Tmp2 = ComputeNumSignBits(SrcOp, Depth + 1);
3929 
3930       // BUILD_VECTOR can implicitly truncate sources, we must handle this.
3931       if (SrcOp.getValueSizeInBits() != VTBits) {
3932         assert(SrcOp.getValueSizeInBits() > VTBits &&
3933                "Expected BUILD_VECTOR implicit truncation");
3934         unsigned ExtraBits = SrcOp.getValueSizeInBits() - VTBits;
3935         Tmp2 = (Tmp2 > ExtraBits ? Tmp2 - ExtraBits : 1);
3936       }
3937       Tmp = std::min(Tmp, Tmp2);
3938     }
3939     return Tmp;
3940 
3941   case ISD::VECTOR_SHUFFLE: {
3942     // Collect the minimum number of sign bits that are shared by every vector
3943     // element referenced by the shuffle.
3944     APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
3945     const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
3946     assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
3947     for (unsigned i = 0; i != NumElts; ++i) {
3948       int M = SVN->getMaskElt(i);
3949       if (!DemandedElts[i])
3950         continue;
3951       // For UNDEF elements, we don't know anything about the common state of
3952       // the shuffle result.
3953       if (M < 0)
3954         return 1;
3955       if ((unsigned)M < NumElts)
3956         DemandedLHS.setBit((unsigned)M % NumElts);
3957       else
3958         DemandedRHS.setBit((unsigned)M % NumElts);
3959     }
3960     Tmp = std::numeric_limits<unsigned>::max();
3961     if (!!DemandedLHS)
3962       Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedLHS, Depth + 1);
3963     if (!!DemandedRHS) {
3964       Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedRHS, Depth + 1);
3965       Tmp = std::min(Tmp, Tmp2);
3966     }
3967     // If we don't know anything, early out and try computeKnownBits fall-back.
3968     if (Tmp == 1)
3969       break;
3970     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
3971     return Tmp;
3972   }
3973 
3974   case ISD::BITCAST: {
3975     SDValue N0 = Op.getOperand(0);
3976     EVT SrcVT = N0.getValueType();
3977     unsigned SrcBits = SrcVT.getScalarSizeInBits();
3978 
3979     // Ignore bitcasts from unsupported types..
3980     if (!(SrcVT.isInteger() || SrcVT.isFloatingPoint()))
3981       break;
3982 
3983     // Fast handling of 'identity' bitcasts.
3984     if (VTBits == SrcBits)
3985       return ComputeNumSignBits(N0, DemandedElts, Depth + 1);
3986 
3987     bool IsLE = getDataLayout().isLittleEndian();
3988 
3989     // Bitcast 'large element' scalar/vector to 'small element' vector.
3990     if ((SrcBits % VTBits) == 0) {
3991       assert(VT.isVector() && "Expected bitcast to vector");
3992 
3993       unsigned Scale = SrcBits / VTBits;
3994       APInt SrcDemandedElts =
3995           APIntOps::ScaleBitMask(DemandedElts, NumElts / Scale);
3996 
3997       // Fast case - sign splat can be simply split across the small elements.
3998       Tmp = ComputeNumSignBits(N0, SrcDemandedElts, Depth + 1);
3999       if (Tmp == SrcBits)
4000         return VTBits;
4001 
4002       // Slow case - determine how far the sign extends into each sub-element.
4003       Tmp2 = VTBits;
4004       for (unsigned i = 0; i != NumElts; ++i)
4005         if (DemandedElts[i]) {
4006           unsigned SubOffset = i % Scale;
4007           SubOffset = (IsLE ? ((Scale - 1) - SubOffset) : SubOffset);
4008           SubOffset = SubOffset * VTBits;
4009           if (Tmp <= SubOffset)
4010             return 1;
4011           Tmp2 = std::min(Tmp2, Tmp - SubOffset);
4012         }
4013       return Tmp2;
4014     }
4015     break;
4016   }
4017 
4018   case ISD::FP_TO_SINT_SAT:
4019     // FP_TO_SINT_SAT produces a signed value that fits in the saturating VT.
4020     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
4021     return VTBits - Tmp + 1;
4022   case ISD::SIGN_EXTEND:
4023     Tmp = VTBits - Op.getOperand(0).getScalarValueSizeInBits();
4024     return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1) + Tmp;
4025   case ISD::SIGN_EXTEND_INREG:
4026     // Max of the input and what this extends.
4027     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
4028     Tmp = VTBits-Tmp+1;
4029     Tmp2 = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
4030     return std::max(Tmp, Tmp2);
4031   case ISD::SIGN_EXTEND_VECTOR_INREG: {
4032     SDValue Src = Op.getOperand(0);
4033     EVT SrcVT = Src.getValueType();
4034     APInt DemandedSrcElts = DemandedElts.zext(SrcVT.getVectorNumElements());
4035     Tmp = VTBits - SrcVT.getScalarSizeInBits();
4036     return ComputeNumSignBits(Src, DemandedSrcElts, Depth+1) + Tmp;
4037   }
4038   case ISD::SRA:
4039     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4040     // SRA X, C -> adds C sign bits.
4041     if (const APInt *ShAmt =
4042             getValidMinimumShiftAmountConstant(Op, DemandedElts))
4043       Tmp = std::min<uint64_t>(Tmp + ShAmt->getZExtValue(), VTBits);
4044     return Tmp;
4045   case ISD::SHL:
4046     if (const APInt *ShAmt =
4047             getValidMaximumShiftAmountConstant(Op, DemandedElts)) {
4048       // shl destroys sign bits, ensure it doesn't shift out all sign bits.
4049       Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4050       if (ShAmt->ult(Tmp))
4051         return Tmp - ShAmt->getZExtValue();
4052     }
4053     break;
4054   case ISD::AND:
4055   case ISD::OR:
4056   case ISD::XOR:    // NOT is handled here.
4057     // Logical binary ops preserve the number of sign bits at the worst.
4058     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
4059     if (Tmp != 1) {
4060       Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
4061       FirstAnswer = std::min(Tmp, Tmp2);
4062       // We computed what we know about the sign bits as our first
4063       // answer. Now proceed to the generic code that uses
4064       // computeKnownBits, and pick whichever answer is better.
4065     }
4066     break;
4067 
4068   case ISD::SELECT:
4069   case ISD::VSELECT:
4070     Tmp = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
4071     if (Tmp == 1) return 1;  // Early out.
4072     Tmp2 = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
4073     return std::min(Tmp, Tmp2);
4074   case ISD::SELECT_CC:
4075     Tmp = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
4076     if (Tmp == 1) return 1;  // Early out.
4077     Tmp2 = ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth+1);
4078     return std::min(Tmp, Tmp2);
4079 
4080   case ISD::SMIN:
4081   case ISD::SMAX: {
4082     // If we have a clamp pattern, we know that the number of sign bits will be
4083     // the minimum of the clamp min/max range.
4084     bool IsMax = (Opcode == ISD::SMAX);
4085     ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
4086     if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
4087       if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
4088         CstHigh =
4089             isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
4090     if (CstLow && CstHigh) {
4091       if (!IsMax)
4092         std::swap(CstLow, CstHigh);
4093       if (CstLow->getAPIntValue().sle(CstHigh->getAPIntValue())) {
4094         Tmp = CstLow->getAPIntValue().getNumSignBits();
4095         Tmp2 = CstHigh->getAPIntValue().getNumSignBits();
4096         return std::min(Tmp, Tmp2);
4097       }
4098     }
4099 
4100     // Fallback - just get the minimum number of sign bits of the operands.
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   }
4107   case ISD::UMIN:
4108   case ISD::UMAX:
4109     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4110     if (Tmp == 1)
4111       return 1;  // Early out.
4112     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
4113     return std::min(Tmp, Tmp2);
4114   case ISD::SADDO:
4115   case ISD::UADDO:
4116   case ISD::SSUBO:
4117   case ISD::USUBO:
4118   case ISD::SMULO:
4119   case ISD::UMULO:
4120     if (Op.getResNo() != 1)
4121       break;
4122     // The boolean result conforms to getBooleanContents.  Fall through.
4123     // If setcc returns 0/-1, all bits are sign bits.
4124     // We know that we have an integer-based boolean since these operations
4125     // are only available for integer.
4126     if (TLI->getBooleanContents(VT.isVector(), false) ==
4127         TargetLowering::ZeroOrNegativeOneBooleanContent)
4128       return VTBits;
4129     break;
4130   case ISD::SETCC:
4131   case ISD::STRICT_FSETCC:
4132   case ISD::STRICT_FSETCCS: {
4133     unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
4134     // If setcc returns 0/-1, all bits are sign bits.
4135     if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
4136         TargetLowering::ZeroOrNegativeOneBooleanContent)
4137       return VTBits;
4138     break;
4139   }
4140   case ISD::ROTL:
4141   case ISD::ROTR:
4142     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4143 
4144     // If we're rotating an 0/-1 value, then it stays an 0/-1 value.
4145     if (Tmp == VTBits)
4146       return VTBits;
4147 
4148     if (ConstantSDNode *C =
4149             isConstOrConstSplat(Op.getOperand(1), DemandedElts)) {
4150       unsigned RotAmt = C->getAPIntValue().urem(VTBits);
4151 
4152       // Handle rotate right by N like a rotate left by 32-N.
4153       if (Opcode == ISD::ROTR)
4154         RotAmt = (VTBits - RotAmt) % VTBits;
4155 
4156       // If we aren't rotating out all of the known-in sign bits, return the
4157       // number that are left.  This handles rotl(sext(x), 1) for example.
4158       if (Tmp > (RotAmt + 1)) return (Tmp - RotAmt);
4159     }
4160     break;
4161   case ISD::ADD:
4162   case ISD::ADDC:
4163     // Add can have at most one carry bit.  Thus we know that the output
4164     // is, at worst, one more bit than the inputs.
4165     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4166     if (Tmp == 1) return 1; // Early out.
4167 
4168     // Special case decrementing a value (ADD X, -1):
4169     if (ConstantSDNode *CRHS =
4170             isConstOrConstSplat(Op.getOperand(1), DemandedElts))
4171       if (CRHS->isAllOnes()) {
4172         KnownBits Known =
4173             computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4174 
4175         // If the input is known to be 0 or 1, the output is 0/-1, which is all
4176         // sign bits set.
4177         if ((Known.Zero | 1).isAllOnes())
4178           return VTBits;
4179 
4180         // If we are subtracting one from a positive number, there is no carry
4181         // out of the result.
4182         if (Known.isNonNegative())
4183           return Tmp;
4184       }
4185 
4186     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
4187     if (Tmp2 == 1) return 1; // Early out.
4188     return std::min(Tmp, Tmp2) - 1;
4189   case ISD::SUB:
4190     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
4191     if (Tmp2 == 1) return 1; // Early out.
4192 
4193     // Handle NEG.
4194     if (ConstantSDNode *CLHS =
4195             isConstOrConstSplat(Op.getOperand(0), DemandedElts))
4196       if (CLHS->isZero()) {
4197         KnownBits Known =
4198             computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4199         // If the input is known to be 0 or 1, the output is 0/-1, which is all
4200         // sign bits set.
4201         if ((Known.Zero | 1).isAllOnes())
4202           return VTBits;
4203 
4204         // If the input is known to be positive (the sign bit is known clear),
4205         // the output of the NEG has the same number of sign bits as the input.
4206         if (Known.isNonNegative())
4207           return Tmp2;
4208 
4209         // Otherwise, we treat this like a SUB.
4210       }
4211 
4212     // Sub can have at most one carry bit.  Thus we know that the output
4213     // is, at worst, one more bit than the inputs.
4214     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4215     if (Tmp == 1) return 1; // Early out.
4216     return std::min(Tmp, Tmp2) - 1;
4217   case ISD::MUL: {
4218     // The output of the Mul can be at most twice the valid bits in the inputs.
4219     unsigned SignBitsOp0 = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
4220     if (SignBitsOp0 == 1)
4221       break;
4222     unsigned SignBitsOp1 = ComputeNumSignBits(Op.getOperand(1), Depth + 1);
4223     if (SignBitsOp1 == 1)
4224       break;
4225     unsigned OutValidBits =
4226         (VTBits - SignBitsOp0 + 1) + (VTBits - SignBitsOp1 + 1);
4227     return OutValidBits > VTBits ? 1 : VTBits - OutValidBits + 1;
4228   }
4229   case ISD::SREM:
4230     // The sign bit is the LHS's sign bit, except when the result of the
4231     // remainder is zero. The magnitude of the result should be less than or
4232     // equal to the magnitude of the LHS. Therefore, the result should have
4233     // at least as many sign bits as the left hand side.
4234     return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4235   case ISD::TRUNCATE: {
4236     // Check if the sign bits of source go down as far as the truncated value.
4237     unsigned NumSrcBits = Op.getOperand(0).getScalarValueSizeInBits();
4238     unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
4239     if (NumSrcSignBits > (NumSrcBits - VTBits))
4240       return NumSrcSignBits - (NumSrcBits - VTBits);
4241     break;
4242   }
4243   case ISD::EXTRACT_ELEMENT: {
4244     const int KnownSign = ComputeNumSignBits(Op.getOperand(0), Depth+1);
4245     const int BitWidth = Op.getValueSizeInBits();
4246     const int Items = Op.getOperand(0).getValueSizeInBits() / BitWidth;
4247 
4248     // Get reverse index (starting from 1), Op1 value indexes elements from
4249     // little end. Sign starts at big end.
4250     const int rIndex = Items - 1 - Op.getConstantOperandVal(1);
4251 
4252     // If the sign portion ends in our element the subtraction gives correct
4253     // result. Otherwise it gives either negative or > bitwidth result
4254     return std::max(std::min(KnownSign - rIndex * BitWidth, BitWidth), 0);
4255   }
4256   case ISD::INSERT_VECTOR_ELT: {
4257     // If we know the element index, split the demand between the
4258     // source vector and the inserted element, otherwise assume we need
4259     // the original demanded vector elements and the value.
4260     SDValue InVec = Op.getOperand(0);
4261     SDValue InVal = Op.getOperand(1);
4262     SDValue EltNo = Op.getOperand(2);
4263     bool DemandedVal = true;
4264     APInt DemandedVecElts = DemandedElts;
4265     auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
4266     if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
4267       unsigned EltIdx = CEltNo->getZExtValue();
4268       DemandedVal = !!DemandedElts[EltIdx];
4269       DemandedVecElts.clearBit(EltIdx);
4270     }
4271     Tmp = std::numeric_limits<unsigned>::max();
4272     if (DemandedVal) {
4273       // TODO - handle implicit truncation of inserted elements.
4274       if (InVal.getScalarValueSizeInBits() != VTBits)
4275         break;
4276       Tmp2 = ComputeNumSignBits(InVal, Depth + 1);
4277       Tmp = std::min(Tmp, Tmp2);
4278     }
4279     if (!!DemandedVecElts) {
4280       Tmp2 = ComputeNumSignBits(InVec, DemandedVecElts, Depth + 1);
4281       Tmp = std::min(Tmp, Tmp2);
4282     }
4283     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
4284     return Tmp;
4285   }
4286   case ISD::EXTRACT_VECTOR_ELT: {
4287     SDValue InVec = Op.getOperand(0);
4288     SDValue EltNo = Op.getOperand(1);
4289     EVT VecVT = InVec.getValueType();
4290     // ComputeNumSignBits not yet implemented for scalable vectors.
4291     if (VecVT.isScalableVector())
4292       break;
4293     const unsigned BitWidth = Op.getValueSizeInBits();
4294     const unsigned EltBitWidth = Op.getOperand(0).getScalarValueSizeInBits();
4295     const unsigned NumSrcElts = VecVT.getVectorNumElements();
4296 
4297     // If BitWidth > EltBitWidth the value is anyext:ed, and we do not know
4298     // anything about sign bits. But if the sizes match we can derive knowledge
4299     // about sign bits from the vector operand.
4300     if (BitWidth != EltBitWidth)
4301       break;
4302 
4303     // If we know the element index, just demand that vector element, else for
4304     // an unknown element index, ignore DemandedElts and demand them all.
4305     APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
4306     auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
4307     if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
4308       DemandedSrcElts =
4309           APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
4310 
4311     return ComputeNumSignBits(InVec, DemandedSrcElts, Depth + 1);
4312   }
4313   case ISD::EXTRACT_SUBVECTOR: {
4314     // Offset the demanded elts by the subvector index.
4315     SDValue Src = Op.getOperand(0);
4316     // Bail until we can represent demanded elements for scalable vectors.
4317     if (Src.getValueType().isScalableVector())
4318       break;
4319     uint64_t Idx = Op.getConstantOperandVal(1);
4320     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
4321     APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
4322     return ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
4323   }
4324   case ISD::CONCAT_VECTORS: {
4325     // Determine the minimum number of sign bits across all demanded
4326     // elts of the input vectors. Early out if the result is already 1.
4327     Tmp = std::numeric_limits<unsigned>::max();
4328     EVT SubVectorVT = Op.getOperand(0).getValueType();
4329     unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
4330     unsigned NumSubVectors = Op.getNumOperands();
4331     for (unsigned i = 0; (i < NumSubVectors) && (Tmp > 1); ++i) {
4332       APInt DemandedSub =
4333           DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts);
4334       if (!DemandedSub)
4335         continue;
4336       Tmp2 = ComputeNumSignBits(Op.getOperand(i), DemandedSub, Depth + 1);
4337       Tmp = std::min(Tmp, Tmp2);
4338     }
4339     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
4340     return Tmp;
4341   }
4342   case ISD::INSERT_SUBVECTOR: {
4343     // Demand any elements from the subvector and the remainder from the src its
4344     // inserted into.
4345     SDValue Src = Op.getOperand(0);
4346     SDValue Sub = Op.getOperand(1);
4347     uint64_t Idx = Op.getConstantOperandVal(2);
4348     unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
4349     APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
4350     APInt DemandedSrcElts = DemandedElts;
4351     DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx);
4352 
4353     Tmp = std::numeric_limits<unsigned>::max();
4354     if (!!DemandedSubElts) {
4355       Tmp = ComputeNumSignBits(Sub, DemandedSubElts, Depth + 1);
4356       if (Tmp == 1)
4357         return 1; // early-out
4358     }
4359     if (!!DemandedSrcElts) {
4360       Tmp2 = ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
4361       Tmp = std::min(Tmp, Tmp2);
4362     }
4363     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
4364     return Tmp;
4365   }
4366   case ISD::ATOMIC_CMP_SWAP:
4367   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
4368   case ISD::ATOMIC_SWAP:
4369   case ISD::ATOMIC_LOAD_ADD:
4370   case ISD::ATOMIC_LOAD_SUB:
4371   case ISD::ATOMIC_LOAD_AND:
4372   case ISD::ATOMIC_LOAD_CLR:
4373   case ISD::ATOMIC_LOAD_OR:
4374   case ISD::ATOMIC_LOAD_XOR:
4375   case ISD::ATOMIC_LOAD_NAND:
4376   case ISD::ATOMIC_LOAD_MIN:
4377   case ISD::ATOMIC_LOAD_MAX:
4378   case ISD::ATOMIC_LOAD_UMIN:
4379   case ISD::ATOMIC_LOAD_UMAX:
4380   case ISD::ATOMIC_LOAD: {
4381     Tmp = cast<AtomicSDNode>(Op)->getMemoryVT().getScalarSizeInBits();
4382     // If we are looking at the loaded value.
4383     if (Op.getResNo() == 0) {
4384       if (Tmp == VTBits)
4385         return 1; // early-out
4386       if (TLI->getExtendForAtomicOps() == ISD::SIGN_EXTEND)
4387         return VTBits - Tmp + 1;
4388       if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND)
4389         return VTBits - Tmp;
4390     }
4391     break;
4392   }
4393   }
4394 
4395   // If we are looking at the loaded value of the SDNode.
4396   if (Op.getResNo() == 0) {
4397     // Handle LOADX separately here. EXTLOAD case will fallthrough.
4398     if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
4399       unsigned ExtType = LD->getExtensionType();
4400       switch (ExtType) {
4401       default: break;
4402       case ISD::SEXTLOAD: // e.g. i16->i32 = '17' bits known.
4403         Tmp = LD->getMemoryVT().getScalarSizeInBits();
4404         return VTBits - Tmp + 1;
4405       case ISD::ZEXTLOAD: // e.g. i16->i32 = '16' bits known.
4406         Tmp = LD->getMemoryVT().getScalarSizeInBits();
4407         return VTBits - Tmp;
4408       case ISD::NON_EXTLOAD:
4409         if (const Constant *Cst = TLI->getTargetConstantFromLoad(LD)) {
4410           // We only need to handle vectors - computeKnownBits should handle
4411           // scalar cases.
4412           Type *CstTy = Cst->getType();
4413           if (CstTy->isVectorTy() &&
4414               (NumElts * VTBits) == CstTy->getPrimitiveSizeInBits() &&
4415               VTBits == CstTy->getScalarSizeInBits()) {
4416             Tmp = VTBits;
4417             for (unsigned i = 0; i != NumElts; ++i) {
4418               if (!DemandedElts[i])
4419                 continue;
4420               if (Constant *Elt = Cst->getAggregateElement(i)) {
4421                 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
4422                   const APInt &Value = CInt->getValue();
4423                   Tmp = std::min(Tmp, Value.getNumSignBits());
4424                   continue;
4425                 }
4426                 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
4427                   APInt Value = CFP->getValueAPF().bitcastToAPInt();
4428                   Tmp = std::min(Tmp, Value.getNumSignBits());
4429                   continue;
4430                 }
4431               }
4432               // Unknown type. Conservatively assume no bits match sign bit.
4433               return 1;
4434             }
4435             return Tmp;
4436           }
4437         }
4438         break;
4439       }
4440     }
4441   }
4442 
4443   // Allow the target to implement this method for its nodes.
4444   if (Opcode >= ISD::BUILTIN_OP_END ||
4445       Opcode == ISD::INTRINSIC_WO_CHAIN ||
4446       Opcode == ISD::INTRINSIC_W_CHAIN ||
4447       Opcode == ISD::INTRINSIC_VOID) {
4448     unsigned NumBits =
4449         TLI->ComputeNumSignBitsForTargetNode(Op, DemandedElts, *this, Depth);
4450     if (NumBits > 1)
4451       FirstAnswer = std::max(FirstAnswer, NumBits);
4452   }
4453 
4454   // Finally, if we can prove that the top bits of the result are 0's or 1's,
4455   // use this information.
4456   KnownBits Known = computeKnownBits(Op, DemandedElts, Depth);
4457   return std::max(FirstAnswer, Known.countMinSignBits());
4458 }
4459 
4460 unsigned SelectionDAG::ComputeMaxSignificantBits(SDValue Op,
4461                                                  unsigned Depth) const {
4462   unsigned SignBits = ComputeNumSignBits(Op, Depth);
4463   return Op.getScalarValueSizeInBits() - SignBits + 1;
4464 }
4465 
4466 unsigned SelectionDAG::ComputeMaxSignificantBits(SDValue Op,
4467                                                  const APInt &DemandedElts,
4468                                                  unsigned Depth) const {
4469   unsigned SignBits = ComputeNumSignBits(Op, DemandedElts, Depth);
4470   return Op.getScalarValueSizeInBits() - SignBits + 1;
4471 }
4472 
4473 bool SelectionDAG::isGuaranteedNotToBeUndefOrPoison(SDValue Op, bool PoisonOnly,
4474                                                     unsigned Depth) const {
4475   // Early out for FREEZE.
4476   if (Op.getOpcode() == ISD::FREEZE)
4477     return true;
4478 
4479   // TODO: Assume we don't know anything for now.
4480   EVT VT = Op.getValueType();
4481   if (VT.isScalableVector())
4482     return false;
4483 
4484   APInt DemandedElts = VT.isVector()
4485                            ? APInt::getAllOnes(VT.getVectorNumElements())
4486                            : APInt(1, 1);
4487   return isGuaranteedNotToBeUndefOrPoison(Op, DemandedElts, PoisonOnly, Depth);
4488 }
4489 
4490 bool SelectionDAG::isGuaranteedNotToBeUndefOrPoison(SDValue Op,
4491                                                     const APInt &DemandedElts,
4492                                                     bool PoisonOnly,
4493                                                     unsigned Depth) const {
4494   unsigned Opcode = Op.getOpcode();
4495 
4496   // Early out for FREEZE.
4497   if (Opcode == ISD::FREEZE)
4498     return true;
4499 
4500   if (Depth >= MaxRecursionDepth)
4501     return false; // Limit search depth.
4502 
4503   if (isIntOrFPConstant(Op))
4504     return true;
4505 
4506   switch (Opcode) {
4507   case ISD::UNDEF:
4508     return PoisonOnly;
4509 
4510   case ISD::BUILD_VECTOR:
4511     // NOTE: BUILD_VECTOR has implicit truncation of wider scalar elements -
4512     // this shouldn't affect the result.
4513     for (unsigned i = 0, e = Op.getNumOperands(); i < e; ++i) {
4514       if (!DemandedElts[i])
4515         continue;
4516       if (!isGuaranteedNotToBeUndefOrPoison(Op.getOperand(i), PoisonOnly,
4517                                             Depth + 1))
4518         return false;
4519     }
4520     return true;
4521 
4522   // TODO: Search for noundef attributes from library functions.
4523 
4524   // TODO: Pointers dereferenced by ISD::LOAD/STORE ops are noundef.
4525 
4526   default:
4527     // Allow the target to implement this method for its nodes.
4528     if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
4529         Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID)
4530       return TLI->isGuaranteedNotToBeUndefOrPoisonForTargetNode(
4531           Op, DemandedElts, *this, PoisonOnly, Depth);
4532     break;
4533   }
4534 
4535   return false;
4536 }
4537 
4538 bool SelectionDAG::isBaseWithConstantOffset(SDValue Op) const {
4539   if ((Op.getOpcode() != ISD::ADD && Op.getOpcode() != ISD::OR) ||
4540       !isa<ConstantSDNode>(Op.getOperand(1)))
4541     return false;
4542 
4543   if (Op.getOpcode() == ISD::OR &&
4544       !MaskedValueIsZero(Op.getOperand(0), Op.getConstantOperandAPInt(1)))
4545     return false;
4546 
4547   return true;
4548 }
4549 
4550 bool SelectionDAG::isKnownNeverNaN(SDValue Op, bool SNaN, unsigned Depth) const {
4551   // If we're told that NaNs won't happen, assume they won't.
4552   if (getTarget().Options.NoNaNsFPMath || Op->getFlags().hasNoNaNs())
4553     return true;
4554 
4555   if (Depth >= MaxRecursionDepth)
4556     return false; // Limit search depth.
4557 
4558   // TODO: Handle vectors.
4559   // If the value is a constant, we can obviously see if it is a NaN or not.
4560   if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) {
4561     return !C->getValueAPF().isNaN() ||
4562            (SNaN && !C->getValueAPF().isSignaling());
4563   }
4564 
4565   unsigned Opcode = Op.getOpcode();
4566   switch (Opcode) {
4567   case ISD::FADD:
4568   case ISD::FSUB:
4569   case ISD::FMUL:
4570   case ISD::FDIV:
4571   case ISD::FREM:
4572   case ISD::FSIN:
4573   case ISD::FCOS: {
4574     if (SNaN)
4575       return true;
4576     // TODO: Need isKnownNeverInfinity
4577     return false;
4578   }
4579   case ISD::FCANONICALIZE:
4580   case ISD::FEXP:
4581   case ISD::FEXP2:
4582   case ISD::FTRUNC:
4583   case ISD::FFLOOR:
4584   case ISD::FCEIL:
4585   case ISD::FROUND:
4586   case ISD::FROUNDEVEN:
4587   case ISD::FRINT:
4588   case ISD::FNEARBYINT: {
4589     if (SNaN)
4590       return true;
4591     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4592   }
4593   case ISD::FABS:
4594   case ISD::FNEG:
4595   case ISD::FCOPYSIGN: {
4596     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4597   }
4598   case ISD::SELECT:
4599     return isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) &&
4600            isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1);
4601   case ISD::FP_EXTEND:
4602   case ISD::FP_ROUND: {
4603     if (SNaN)
4604       return true;
4605     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4606   }
4607   case ISD::SINT_TO_FP:
4608   case ISD::UINT_TO_FP:
4609     return true;
4610   case ISD::FMA:
4611   case ISD::FMAD: {
4612     if (SNaN)
4613       return true;
4614     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) &&
4615            isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) &&
4616            isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1);
4617   }
4618   case ISD::FSQRT: // Need is known positive
4619   case ISD::FLOG:
4620   case ISD::FLOG2:
4621   case ISD::FLOG10:
4622   case ISD::FPOWI:
4623   case ISD::FPOW: {
4624     if (SNaN)
4625       return true;
4626     // TODO: Refine on operand
4627     return false;
4628   }
4629   case ISD::FMINNUM:
4630   case ISD::FMAXNUM: {
4631     // Only one needs to be known not-nan, since it will be returned if the
4632     // other ends up being one.
4633     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) ||
4634            isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1);
4635   }
4636   case ISD::FMINNUM_IEEE:
4637   case ISD::FMAXNUM_IEEE: {
4638     if (SNaN)
4639       return true;
4640     // This can return a NaN if either operand is an sNaN, or if both operands
4641     // are NaN.
4642     return (isKnownNeverNaN(Op.getOperand(0), false, Depth + 1) &&
4643             isKnownNeverSNaN(Op.getOperand(1), Depth + 1)) ||
4644            (isKnownNeverNaN(Op.getOperand(1), false, Depth + 1) &&
4645             isKnownNeverSNaN(Op.getOperand(0), Depth + 1));
4646   }
4647   case ISD::FMINIMUM:
4648   case ISD::FMAXIMUM: {
4649     // TODO: Does this quiet or return the origina NaN as-is?
4650     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) &&
4651            isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1);
4652   }
4653   case ISD::EXTRACT_VECTOR_ELT: {
4654     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4655   }
4656   default:
4657     if (Opcode >= ISD::BUILTIN_OP_END ||
4658         Opcode == ISD::INTRINSIC_WO_CHAIN ||
4659         Opcode == ISD::INTRINSIC_W_CHAIN ||
4660         Opcode == ISD::INTRINSIC_VOID) {
4661       return TLI->isKnownNeverNaNForTargetNode(Op, *this, SNaN, Depth);
4662     }
4663 
4664     return false;
4665   }
4666 }
4667 
4668 bool SelectionDAG::isKnownNeverZeroFloat(SDValue Op) const {
4669   assert(Op.getValueType().isFloatingPoint() &&
4670          "Floating point type expected");
4671 
4672   // If the value is a constant, we can obviously see if it is a zero or not.
4673   // TODO: Add BuildVector support.
4674   if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
4675     return !C->isZero();
4676   return false;
4677 }
4678 
4679 bool SelectionDAG::isKnownNeverZero(SDValue Op) const {
4680   assert(!Op.getValueType().isFloatingPoint() &&
4681          "Floating point types unsupported - use isKnownNeverZeroFloat");
4682 
4683   // If the value is a constant, we can obviously see if it is a zero or not.
4684   if (ISD::matchUnaryPredicate(Op,
4685                                [](ConstantSDNode *C) { return !C->isZero(); }))
4686     return true;
4687 
4688   // TODO: Recognize more cases here.
4689   switch (Op.getOpcode()) {
4690   default: break;
4691   case ISD::OR:
4692     if (isKnownNeverZero(Op.getOperand(1)) ||
4693         isKnownNeverZero(Op.getOperand(0)))
4694       return true;
4695     break;
4696   }
4697 
4698   return false;
4699 }
4700 
4701 bool SelectionDAG::isEqualTo(SDValue A, SDValue B) const {
4702   // Check the obvious case.
4703   if (A == B) return true;
4704 
4705   // For for negative and positive zero.
4706   if (const ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A))
4707     if (const ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B))
4708       if (CA->isZero() && CB->isZero()) return true;
4709 
4710   // Otherwise they may not be equal.
4711   return false;
4712 }
4713 
4714 // Only bits set in Mask must be negated, other bits may be arbitrary.
4715 SDValue llvm::getBitwiseNotOperand(SDValue V, SDValue Mask, bool AllowUndefs) {
4716   if (isBitwiseNot(V, AllowUndefs))
4717     return V.getOperand(0);
4718 
4719   // Handle any_extend (not (truncate X)) pattern, where Mask only sets
4720   // bits in the non-extended part.
4721   ConstantSDNode *MaskC = isConstOrConstSplat(Mask);
4722   if (!MaskC || V.getOpcode() != ISD::ANY_EXTEND)
4723     return SDValue();
4724   SDValue ExtArg = V.getOperand(0);
4725   if (ExtArg.getScalarValueSizeInBits() >=
4726           MaskC->getAPIntValue().getActiveBits() &&
4727       isBitwiseNot(ExtArg, AllowUndefs) &&
4728       ExtArg.getOperand(0).getOpcode() == ISD::TRUNCATE &&
4729       ExtArg.getOperand(0).getOperand(0).getValueType() == V.getValueType())
4730     return ExtArg.getOperand(0).getOperand(0);
4731   return SDValue();
4732 }
4733 
4734 static bool haveNoCommonBitsSetCommutative(SDValue A, SDValue B) {
4735   // Match masked merge pattern (X & ~M) op (Y & M)
4736   // Including degenerate case (X & ~M) op M
4737   auto MatchNoCommonBitsPattern = [&](SDValue Not, SDValue Mask,
4738                                       SDValue Other) {
4739     if (SDValue NotOperand =
4740             getBitwiseNotOperand(Not, Mask, /* AllowUndefs */ true)) {
4741       if (Other == NotOperand)
4742         return true;
4743       if (Other->getOpcode() == ISD::AND)
4744         return NotOperand == Other->getOperand(0) ||
4745                NotOperand == Other->getOperand(1);
4746     }
4747     return false;
4748   };
4749   if (A->getOpcode() == ISD::AND)
4750     return MatchNoCommonBitsPattern(A->getOperand(0), A->getOperand(1), B) ||
4751            MatchNoCommonBitsPattern(A->getOperand(1), A->getOperand(0), B);
4752   return false;
4753 }
4754 
4755 // FIXME: unify with llvm::haveNoCommonBitsSet.
4756 bool SelectionDAG::haveNoCommonBitsSet(SDValue A, SDValue B) const {
4757   assert(A.getValueType() == B.getValueType() &&
4758          "Values must have the same type");
4759   if (haveNoCommonBitsSetCommutative(A, B) ||
4760       haveNoCommonBitsSetCommutative(B, A))
4761     return true;
4762   return KnownBits::haveNoCommonBitsSet(computeKnownBits(A),
4763                                         computeKnownBits(B));
4764 }
4765 
4766 static SDValue FoldSTEP_VECTOR(const SDLoc &DL, EVT VT, SDValue Step,
4767                                SelectionDAG &DAG) {
4768   if (cast<ConstantSDNode>(Step)->isZero())
4769     return DAG.getConstant(0, DL, VT);
4770 
4771   return SDValue();
4772 }
4773 
4774 static SDValue FoldBUILD_VECTOR(const SDLoc &DL, EVT VT,
4775                                 ArrayRef<SDValue> Ops,
4776                                 SelectionDAG &DAG) {
4777   int NumOps = Ops.size();
4778   assert(NumOps != 0 && "Can't build an empty vector!");
4779   assert(!VT.isScalableVector() &&
4780          "BUILD_VECTOR cannot be used with scalable types");
4781   assert(VT.getVectorNumElements() == (unsigned)NumOps &&
4782          "Incorrect element count in BUILD_VECTOR!");
4783 
4784   // BUILD_VECTOR of UNDEFs is UNDEF.
4785   if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
4786     return DAG.getUNDEF(VT);
4787 
4788   // BUILD_VECTOR of seq extract/insert from the same vector + type is Identity.
4789   SDValue IdentitySrc;
4790   bool IsIdentity = true;
4791   for (int i = 0; i != NumOps; ++i) {
4792     if (Ops[i].getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4793         Ops[i].getOperand(0).getValueType() != VT ||
4794         (IdentitySrc && Ops[i].getOperand(0) != IdentitySrc) ||
4795         !isa<ConstantSDNode>(Ops[i].getOperand(1)) ||
4796         cast<ConstantSDNode>(Ops[i].getOperand(1))->getAPIntValue() != i) {
4797       IsIdentity = false;
4798       break;
4799     }
4800     IdentitySrc = Ops[i].getOperand(0);
4801   }
4802   if (IsIdentity)
4803     return IdentitySrc;
4804 
4805   return SDValue();
4806 }
4807 
4808 /// Try to simplify vector concatenation to an input value, undef, or build
4809 /// vector.
4810 static SDValue foldCONCAT_VECTORS(const SDLoc &DL, EVT VT,
4811                                   ArrayRef<SDValue> Ops,
4812                                   SelectionDAG &DAG) {
4813   assert(!Ops.empty() && "Can't concatenate an empty list of vectors!");
4814   assert(llvm::all_of(Ops,
4815                       [Ops](SDValue Op) {
4816                         return Ops[0].getValueType() == Op.getValueType();
4817                       }) &&
4818          "Concatenation of vectors with inconsistent value types!");
4819   assert((Ops[0].getValueType().getVectorElementCount() * Ops.size()) ==
4820              VT.getVectorElementCount() &&
4821          "Incorrect element count in vector concatenation!");
4822 
4823   if (Ops.size() == 1)
4824     return Ops[0];
4825 
4826   // Concat of UNDEFs is UNDEF.
4827   if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
4828     return DAG.getUNDEF(VT);
4829 
4830   // Scan the operands and look for extract operations from a single source
4831   // that correspond to insertion at the same location via this concatenation:
4832   // concat (extract X, 0*subvec_elts), (extract X, 1*subvec_elts), ...
4833   SDValue IdentitySrc;
4834   bool IsIdentity = true;
4835   for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
4836     SDValue Op = Ops[i];
4837     unsigned IdentityIndex = i * Op.getValueType().getVectorMinNumElements();
4838     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
4839         Op.getOperand(0).getValueType() != VT ||
4840         (IdentitySrc && Op.getOperand(0) != IdentitySrc) ||
4841         Op.getConstantOperandVal(1) != IdentityIndex) {
4842       IsIdentity = false;
4843       break;
4844     }
4845     assert((!IdentitySrc || IdentitySrc == Op.getOperand(0)) &&
4846            "Unexpected identity source vector for concat of extracts");
4847     IdentitySrc = Op.getOperand(0);
4848   }
4849   if (IsIdentity) {
4850     assert(IdentitySrc && "Failed to set source vector of extracts");
4851     return IdentitySrc;
4852   }
4853 
4854   // The code below this point is only designed to work for fixed width
4855   // vectors, so we bail out for now.
4856   if (VT.isScalableVector())
4857     return SDValue();
4858 
4859   // A CONCAT_VECTOR with all UNDEF/BUILD_VECTOR operands can be
4860   // simplified to one big BUILD_VECTOR.
4861   // FIXME: Add support for SCALAR_TO_VECTOR as well.
4862   EVT SVT = VT.getScalarType();
4863   SmallVector<SDValue, 16> Elts;
4864   for (SDValue Op : Ops) {
4865     EVT OpVT = Op.getValueType();
4866     if (Op.isUndef())
4867       Elts.append(OpVT.getVectorNumElements(), DAG.getUNDEF(SVT));
4868     else if (Op.getOpcode() == ISD::BUILD_VECTOR)
4869       Elts.append(Op->op_begin(), Op->op_end());
4870     else
4871       return SDValue();
4872   }
4873 
4874   // BUILD_VECTOR requires all inputs to be of the same type, find the
4875   // maximum type and extend them all.
4876   for (SDValue Op : Elts)
4877     SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
4878 
4879   if (SVT.bitsGT(VT.getScalarType())) {
4880     for (SDValue &Op : Elts) {
4881       if (Op.isUndef())
4882         Op = DAG.getUNDEF(SVT);
4883       else
4884         Op = DAG.getTargetLoweringInfo().isZExtFree(Op.getValueType(), SVT)
4885                  ? DAG.getZExtOrTrunc(Op, DL, SVT)
4886                  : DAG.getSExtOrTrunc(Op, DL, SVT);
4887     }
4888   }
4889 
4890   SDValue V = DAG.getBuildVector(VT, DL, Elts);
4891   NewSDValueDbgMsg(V, "New node fold concat vectors: ", &DAG);
4892   return V;
4893 }
4894 
4895 /// Gets or creates the specified node.
4896 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT) {
4897   FoldingSetNodeID ID;
4898   AddNodeIDNode(ID, Opcode, getVTList(VT), None);
4899   void *IP = nullptr;
4900   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
4901     return SDValue(E, 0);
4902 
4903   auto *N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(),
4904                               getVTList(VT));
4905   CSEMap.InsertNode(N, IP);
4906 
4907   InsertNode(N);
4908   SDValue V = SDValue(N, 0);
4909   NewSDValueDbgMsg(V, "Creating new node: ", this);
4910   return V;
4911 }
4912 
4913 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4914                               SDValue Operand) {
4915   SDNodeFlags Flags;
4916   if (Inserter)
4917     Flags = Inserter->getFlags();
4918   return getNode(Opcode, DL, VT, Operand, Flags);
4919 }
4920 
4921 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4922                               SDValue Operand, const SDNodeFlags Flags) {
4923   assert(Operand.getOpcode() != ISD::DELETED_NODE &&
4924          "Operand is DELETED_NODE!");
4925   // Constant fold unary operations with an integer constant operand. Even
4926   // opaque constant will be folded, because the folding of unary operations
4927   // doesn't create new constants with different values. Nevertheless, the
4928   // opaque flag is preserved during folding to prevent future folding with
4929   // other constants.
4930   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand)) {
4931     const APInt &Val = C->getAPIntValue();
4932     switch (Opcode) {
4933     default: break;
4934     case ISD::SIGN_EXTEND:
4935       return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
4936                          C->isTargetOpcode(), C->isOpaque());
4937     case ISD::TRUNCATE:
4938       if (C->isOpaque())
4939         break;
4940       LLVM_FALLTHROUGH;
4941     case ISD::ZERO_EXTEND:
4942       return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
4943                          C->isTargetOpcode(), C->isOpaque());
4944     case ISD::ANY_EXTEND:
4945       // Some targets like RISCV prefer to sign extend some types.
4946       if (TLI->isSExtCheaperThanZExt(Operand.getValueType(), VT))
4947         return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
4948                            C->isTargetOpcode(), C->isOpaque());
4949       return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
4950                          C->isTargetOpcode(), C->isOpaque());
4951     case ISD::UINT_TO_FP:
4952     case ISD::SINT_TO_FP: {
4953       APFloat apf(EVTToAPFloatSemantics(VT),
4954                   APInt::getZero(VT.getSizeInBits()));
4955       (void)apf.convertFromAPInt(Val,
4956                                  Opcode==ISD::SINT_TO_FP,
4957                                  APFloat::rmNearestTiesToEven);
4958       return getConstantFP(apf, DL, VT);
4959     }
4960     case ISD::BITCAST:
4961       if (VT == MVT::f16 && C->getValueType(0) == MVT::i16)
4962         return getConstantFP(APFloat(APFloat::IEEEhalf(), Val), DL, VT);
4963       if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
4964         return getConstantFP(APFloat(APFloat::IEEEsingle(), Val), DL, VT);
4965       if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
4966         return getConstantFP(APFloat(APFloat::IEEEdouble(), Val), DL, VT);
4967       if (VT == MVT::f128 && C->getValueType(0) == MVT::i128)
4968         return getConstantFP(APFloat(APFloat::IEEEquad(), Val), DL, VT);
4969       break;
4970     case ISD::ABS:
4971       return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(),
4972                          C->isOpaque());
4973     case ISD::BITREVERSE:
4974       return getConstant(Val.reverseBits(), DL, VT, C->isTargetOpcode(),
4975                          C->isOpaque());
4976     case ISD::BSWAP:
4977       return getConstant(Val.byteSwap(), DL, VT, C->isTargetOpcode(),
4978                          C->isOpaque());
4979     case ISD::CTPOP:
4980       return getConstant(Val.countPopulation(), DL, VT, C->isTargetOpcode(),
4981                          C->isOpaque());
4982     case ISD::CTLZ:
4983     case ISD::CTLZ_ZERO_UNDEF:
4984       return getConstant(Val.countLeadingZeros(), DL, VT, C->isTargetOpcode(),
4985                          C->isOpaque());
4986     case ISD::CTTZ:
4987     case ISD::CTTZ_ZERO_UNDEF:
4988       return getConstant(Val.countTrailingZeros(), DL, VT, C->isTargetOpcode(),
4989                          C->isOpaque());
4990     case ISD::FP16_TO_FP:
4991     case ISD::BF16_TO_FP: {
4992       bool Ignored;
4993       APFloat FPV(Opcode == ISD::FP16_TO_FP ? APFloat::IEEEhalf()
4994                                             : APFloat::BFloat(),
4995                   (Val.getBitWidth() == 16) ? Val : Val.trunc(16));
4996 
4997       // This can return overflow, underflow, or inexact; we don't care.
4998       // FIXME need to be more flexible about rounding mode.
4999       (void)FPV.convert(EVTToAPFloatSemantics(VT),
5000                         APFloat::rmNearestTiesToEven, &Ignored);
5001       return getConstantFP(FPV, DL, VT);
5002     }
5003     case ISD::STEP_VECTOR: {
5004       if (SDValue V = FoldSTEP_VECTOR(DL, VT, Operand, *this))
5005         return V;
5006       break;
5007     }
5008     }
5009   }
5010 
5011   // Constant fold unary operations with a floating point constant operand.
5012   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand)) {
5013     APFloat V = C->getValueAPF();    // make copy
5014     switch (Opcode) {
5015     case ISD::FNEG:
5016       V.changeSign();
5017       return getConstantFP(V, DL, VT);
5018     case ISD::FABS:
5019       V.clearSign();
5020       return getConstantFP(V, DL, VT);
5021     case ISD::FCEIL: {
5022       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardPositive);
5023       if (fs == APFloat::opOK || fs == APFloat::opInexact)
5024         return getConstantFP(V, DL, VT);
5025       break;
5026     }
5027     case ISD::FTRUNC: {
5028       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardZero);
5029       if (fs == APFloat::opOK || fs == APFloat::opInexact)
5030         return getConstantFP(V, DL, VT);
5031       break;
5032     }
5033     case ISD::FFLOOR: {
5034       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardNegative);
5035       if (fs == APFloat::opOK || fs == APFloat::opInexact)
5036         return getConstantFP(V, DL, VT);
5037       break;
5038     }
5039     case ISD::FP_EXTEND: {
5040       bool ignored;
5041       // This can return overflow, underflow, or inexact; we don't care.
5042       // FIXME need to be more flexible about rounding mode.
5043       (void)V.convert(EVTToAPFloatSemantics(VT),
5044                       APFloat::rmNearestTiesToEven, &ignored);
5045       return getConstantFP(V, DL, VT);
5046     }
5047     case ISD::FP_TO_SINT:
5048     case ISD::FP_TO_UINT: {
5049       bool ignored;
5050       APSInt IntVal(VT.getSizeInBits(), Opcode == ISD::FP_TO_UINT);
5051       // FIXME need to be more flexible about rounding mode.
5052       APFloat::opStatus s =
5053           V.convertToInteger(IntVal, APFloat::rmTowardZero, &ignored);
5054       if (s == APFloat::opInvalidOp) // inexact is OK, in fact usual
5055         break;
5056       return getConstant(IntVal, DL, VT);
5057     }
5058     case ISD::BITCAST:
5059       if (VT == MVT::i16 && C->getValueType(0) == MVT::f16)
5060         return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
5061       if (VT == MVT::i16 && C->getValueType(0) == MVT::bf16)
5062         return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
5063       if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
5064         return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
5065       if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
5066         return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
5067       break;
5068     case ISD::FP_TO_FP16:
5069     case ISD::FP_TO_BF16: {
5070       bool Ignored;
5071       // This can return overflow, underflow, or inexact; we don't care.
5072       // FIXME need to be more flexible about rounding mode.
5073       (void)V.convert(Opcode == ISD::FP_TO_FP16 ? APFloat::IEEEhalf()
5074                                                 : APFloat::BFloat(),
5075                       APFloat::rmNearestTiesToEven, &Ignored);
5076       return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
5077     }
5078     }
5079   }
5080 
5081   // Constant fold unary operations with a vector integer or float operand.
5082   switch (Opcode) {
5083   default:
5084     // FIXME: Entirely reasonable to perform folding of other unary
5085     // operations here as the need arises.
5086     break;
5087   case ISD::FNEG:
5088   case ISD::FABS:
5089   case ISD::FCEIL:
5090   case ISD::FTRUNC:
5091   case ISD::FFLOOR:
5092   case ISD::FP_EXTEND:
5093   case ISD::FP_TO_SINT:
5094   case ISD::FP_TO_UINT:
5095   case ISD::TRUNCATE:
5096   case ISD::ANY_EXTEND:
5097   case ISD::ZERO_EXTEND:
5098   case ISD::SIGN_EXTEND:
5099   case ISD::UINT_TO_FP:
5100   case ISD::SINT_TO_FP:
5101   case ISD::ABS:
5102   case ISD::BITREVERSE:
5103   case ISD::BSWAP:
5104   case ISD::CTLZ:
5105   case ISD::CTLZ_ZERO_UNDEF:
5106   case ISD::CTTZ:
5107   case ISD::CTTZ_ZERO_UNDEF:
5108   case ISD::CTPOP: {
5109     SDValue Ops = {Operand};
5110     if (SDValue Fold = FoldConstantArithmetic(Opcode, DL, VT, Ops))
5111       return Fold;
5112   }
5113   }
5114 
5115   unsigned OpOpcode = Operand.getNode()->getOpcode();
5116   switch (Opcode) {
5117   case ISD::STEP_VECTOR:
5118     assert(VT.isScalableVector() &&
5119            "STEP_VECTOR can only be used with scalable types");
5120     assert(OpOpcode == ISD::TargetConstant &&
5121            VT.getVectorElementType() == Operand.getValueType() &&
5122            "Unexpected step operand");
5123     break;
5124   case ISD::FREEZE:
5125     assert(VT == Operand.getValueType() && "Unexpected VT!");
5126     if (isGuaranteedNotToBeUndefOrPoison(Operand))
5127       return Operand;
5128     break;
5129   case ISD::TokenFactor:
5130   case ISD::MERGE_VALUES:
5131   case ISD::CONCAT_VECTORS:
5132     return Operand;         // Factor, merge or concat of one node?  No need.
5133   case ISD::BUILD_VECTOR: {
5134     // Attempt to simplify BUILD_VECTOR.
5135     SDValue Ops[] = {Operand};
5136     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
5137       return V;
5138     break;
5139   }
5140   case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node");
5141   case ISD::FP_EXTEND:
5142     assert(VT.isFloatingPoint() &&
5143            Operand.getValueType().isFloatingPoint() && "Invalid FP cast!");
5144     if (Operand.getValueType() == VT) return Operand;  // noop conversion.
5145     assert((!VT.isVector() ||
5146             VT.getVectorElementCount() ==
5147             Operand.getValueType().getVectorElementCount()) &&
5148            "Vector element count mismatch!");
5149     assert(Operand.getValueType().bitsLT(VT) &&
5150            "Invalid fpext node, dst < src!");
5151     if (Operand.isUndef())
5152       return getUNDEF(VT);
5153     break;
5154   case ISD::FP_TO_SINT:
5155   case ISD::FP_TO_UINT:
5156     if (Operand.isUndef())
5157       return getUNDEF(VT);
5158     break;
5159   case ISD::SINT_TO_FP:
5160   case ISD::UINT_TO_FP:
5161     // [us]itofp(undef) = 0, because the result value is bounded.
5162     if (Operand.isUndef())
5163       return getConstantFP(0.0, DL, VT);
5164     break;
5165   case ISD::SIGN_EXTEND:
5166     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
5167            "Invalid SIGN_EXTEND!");
5168     assert(VT.isVector() == Operand.getValueType().isVector() &&
5169            "SIGN_EXTEND result type type should be vector iff the operand "
5170            "type is vector!");
5171     if (Operand.getValueType() == VT) return Operand;   // noop extension
5172     assert((!VT.isVector() ||
5173             VT.getVectorElementCount() ==
5174                 Operand.getValueType().getVectorElementCount()) &&
5175            "Vector element count mismatch!");
5176     assert(Operand.getValueType().bitsLT(VT) &&
5177            "Invalid sext node, dst < src!");
5178     if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
5179       return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
5180     if (OpOpcode == ISD::UNDEF)
5181       // sext(undef) = 0, because the top bits will all be the same.
5182       return getConstant(0, DL, VT);
5183     break;
5184   case ISD::ZERO_EXTEND:
5185     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
5186            "Invalid ZERO_EXTEND!");
5187     assert(VT.isVector() == Operand.getValueType().isVector() &&
5188            "ZERO_EXTEND result type type should be vector iff the operand "
5189            "type is vector!");
5190     if (Operand.getValueType() == VT) return Operand;   // noop extension
5191     assert((!VT.isVector() ||
5192             VT.getVectorElementCount() ==
5193                 Operand.getValueType().getVectorElementCount()) &&
5194            "Vector element count mismatch!");
5195     assert(Operand.getValueType().bitsLT(VT) &&
5196            "Invalid zext node, dst < src!");
5197     if (OpOpcode == ISD::ZERO_EXTEND)   // (zext (zext x)) -> (zext x)
5198       return getNode(ISD::ZERO_EXTEND, DL, VT, Operand.getOperand(0));
5199     if (OpOpcode == ISD::UNDEF)
5200       // zext(undef) = 0, because the top bits will be zero.
5201       return getConstant(0, DL, VT);
5202     break;
5203   case ISD::ANY_EXTEND:
5204     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
5205            "Invalid ANY_EXTEND!");
5206     assert(VT.isVector() == Operand.getValueType().isVector() &&
5207            "ANY_EXTEND result type type should be vector iff the operand "
5208            "type is vector!");
5209     if (Operand.getValueType() == VT) return Operand;   // noop extension
5210     assert((!VT.isVector() ||
5211             VT.getVectorElementCount() ==
5212                 Operand.getValueType().getVectorElementCount()) &&
5213            "Vector element count mismatch!");
5214     assert(Operand.getValueType().bitsLT(VT) &&
5215            "Invalid anyext node, dst < src!");
5216 
5217     if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
5218         OpOpcode == ISD::ANY_EXTEND)
5219       // (ext (zext x)) -> (zext x)  and  (ext (sext x)) -> (sext x)
5220       return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
5221     if (OpOpcode == ISD::UNDEF)
5222       return getUNDEF(VT);
5223 
5224     // (ext (trunc x)) -> x
5225     if (OpOpcode == ISD::TRUNCATE) {
5226       SDValue OpOp = Operand.getOperand(0);
5227       if (OpOp.getValueType() == VT) {
5228         transferDbgValues(Operand, OpOp);
5229         return OpOp;
5230       }
5231     }
5232     break;
5233   case ISD::TRUNCATE:
5234     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
5235            "Invalid TRUNCATE!");
5236     assert(VT.isVector() == Operand.getValueType().isVector() &&
5237            "TRUNCATE result type type should be vector iff the operand "
5238            "type is vector!");
5239     if (Operand.getValueType() == VT) return Operand;   // noop truncate
5240     assert((!VT.isVector() ||
5241             VT.getVectorElementCount() ==
5242                 Operand.getValueType().getVectorElementCount()) &&
5243            "Vector element count mismatch!");
5244     assert(Operand.getValueType().bitsGT(VT) &&
5245            "Invalid truncate node, src < dst!");
5246     if (OpOpcode == ISD::TRUNCATE)
5247       return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0));
5248     if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
5249         OpOpcode == ISD::ANY_EXTEND) {
5250       // If the source is smaller than the dest, we still need an extend.
5251       if (Operand.getOperand(0).getValueType().getScalarType()
5252             .bitsLT(VT.getScalarType()))
5253         return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
5254       if (Operand.getOperand(0).getValueType().bitsGT(VT))
5255         return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0));
5256       return Operand.getOperand(0);
5257     }
5258     if (OpOpcode == ISD::UNDEF)
5259       return getUNDEF(VT);
5260     if (OpOpcode == ISD::VSCALE && !NewNodesMustHaveLegalTypes)
5261       return getVScale(DL, VT, Operand.getConstantOperandAPInt(0));
5262     break;
5263   case ISD::ANY_EXTEND_VECTOR_INREG:
5264   case ISD::ZERO_EXTEND_VECTOR_INREG:
5265   case ISD::SIGN_EXTEND_VECTOR_INREG:
5266     assert(VT.isVector() && "This DAG node is restricted to vector types.");
5267     assert(Operand.getValueType().bitsLE(VT) &&
5268            "The input must be the same size or smaller than the result.");
5269     assert(VT.getVectorMinNumElements() <
5270                Operand.getValueType().getVectorMinNumElements() &&
5271            "The destination vector type must have fewer lanes than the input.");
5272     break;
5273   case ISD::ABS:
5274     assert(VT.isInteger() && VT == Operand.getValueType() &&
5275            "Invalid ABS!");
5276     if (OpOpcode == ISD::UNDEF)
5277       return getConstant(0, DL, VT);
5278     break;
5279   case ISD::BSWAP:
5280     assert(VT.isInteger() && VT == Operand.getValueType() &&
5281            "Invalid BSWAP!");
5282     assert((VT.getScalarSizeInBits() % 16 == 0) &&
5283            "BSWAP types must be a multiple of 16 bits!");
5284     if (OpOpcode == ISD::UNDEF)
5285       return getUNDEF(VT);
5286     // bswap(bswap(X)) -> X.
5287     if (OpOpcode == ISD::BSWAP)
5288       return Operand.getOperand(0);
5289     break;
5290   case ISD::BITREVERSE:
5291     assert(VT.isInteger() && VT == Operand.getValueType() &&
5292            "Invalid BITREVERSE!");
5293     if (OpOpcode == ISD::UNDEF)
5294       return getUNDEF(VT);
5295     break;
5296   case ISD::BITCAST:
5297     assert(VT.getSizeInBits() == Operand.getValueSizeInBits() &&
5298            "Cannot BITCAST between types of different sizes!");
5299     if (VT == Operand.getValueType()) return Operand;  // noop conversion.
5300     if (OpOpcode == ISD::BITCAST)  // bitconv(bitconv(x)) -> bitconv(x)
5301       return getNode(ISD::BITCAST, DL, VT, Operand.getOperand(0));
5302     if (OpOpcode == ISD::UNDEF)
5303       return getUNDEF(VT);
5304     break;
5305   case ISD::SCALAR_TO_VECTOR:
5306     assert(VT.isVector() && !Operand.getValueType().isVector() &&
5307            (VT.getVectorElementType() == Operand.getValueType() ||
5308             (VT.getVectorElementType().isInteger() &&
5309              Operand.getValueType().isInteger() &&
5310              VT.getVectorElementType().bitsLE(Operand.getValueType()))) &&
5311            "Illegal SCALAR_TO_VECTOR node!");
5312     if (OpOpcode == ISD::UNDEF)
5313       return getUNDEF(VT);
5314     // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
5315     if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
5316         isa<ConstantSDNode>(Operand.getOperand(1)) &&
5317         Operand.getConstantOperandVal(1) == 0 &&
5318         Operand.getOperand(0).getValueType() == VT)
5319       return Operand.getOperand(0);
5320     break;
5321   case ISD::FNEG:
5322     // Negation of an unknown bag of bits is still completely undefined.
5323     if (OpOpcode == ISD::UNDEF)
5324       return getUNDEF(VT);
5325 
5326     if (OpOpcode == ISD::FNEG)  // --X -> X
5327       return Operand.getOperand(0);
5328     break;
5329   case ISD::FABS:
5330     if (OpOpcode == ISD::FNEG)  // abs(-X) -> abs(X)
5331       return getNode(ISD::FABS, DL, VT, Operand.getOperand(0));
5332     break;
5333   case ISD::VSCALE:
5334     assert(VT == Operand.getValueType() && "Unexpected VT!");
5335     break;
5336   case ISD::CTPOP:
5337     if (Operand.getValueType().getScalarType() == MVT::i1)
5338       return Operand;
5339     break;
5340   case ISD::CTLZ:
5341   case ISD::CTTZ:
5342     if (Operand.getValueType().getScalarType() == MVT::i1)
5343       return getNOT(DL, Operand, Operand.getValueType());
5344     break;
5345   case ISD::VECREDUCE_ADD:
5346     if (Operand.getValueType().getScalarType() == MVT::i1)
5347       return getNode(ISD::VECREDUCE_XOR, DL, VT, Operand);
5348     break;
5349   case ISD::VECREDUCE_SMIN:
5350   case ISD::VECREDUCE_UMAX:
5351     if (Operand.getValueType().getScalarType() == MVT::i1)
5352       return getNode(ISD::VECREDUCE_OR, DL, VT, Operand);
5353     break;
5354   case ISD::VECREDUCE_SMAX:
5355   case ISD::VECREDUCE_UMIN:
5356     if (Operand.getValueType().getScalarType() == MVT::i1)
5357       return getNode(ISD::VECREDUCE_AND, DL, VT, Operand);
5358     break;
5359   }
5360 
5361   SDNode *N;
5362   SDVTList VTs = getVTList(VT);
5363   SDValue Ops[] = {Operand};
5364   if (VT != MVT::Glue) { // Don't CSE flag producing nodes
5365     FoldingSetNodeID ID;
5366     AddNodeIDNode(ID, Opcode, VTs, Ops);
5367     void *IP = nullptr;
5368     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
5369       E->intersectFlagsWith(Flags);
5370       return SDValue(E, 0);
5371     }
5372 
5373     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5374     N->setFlags(Flags);
5375     createOperands(N, Ops);
5376     CSEMap.InsertNode(N, IP);
5377   } else {
5378     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5379     createOperands(N, Ops);
5380   }
5381 
5382   InsertNode(N);
5383   SDValue V = SDValue(N, 0);
5384   NewSDValueDbgMsg(V, "Creating new node: ", this);
5385   return V;
5386 }
5387 
5388 static llvm::Optional<APInt> FoldValue(unsigned Opcode, const APInt &C1,
5389                                        const APInt &C2) {
5390   switch (Opcode) {
5391   case ISD::ADD:  return C1 + C2;
5392   case ISD::SUB:  return C1 - C2;
5393   case ISD::MUL:  return C1 * C2;
5394   case ISD::AND:  return C1 & C2;
5395   case ISD::OR:   return C1 | C2;
5396   case ISD::XOR:  return C1 ^ C2;
5397   case ISD::SHL:  return C1 << C2;
5398   case ISD::SRL:  return C1.lshr(C2);
5399   case ISD::SRA:  return C1.ashr(C2);
5400   case ISD::ROTL: return C1.rotl(C2);
5401   case ISD::ROTR: return C1.rotr(C2);
5402   case ISD::SMIN: return C1.sle(C2) ? C1 : C2;
5403   case ISD::SMAX: return C1.sge(C2) ? C1 : C2;
5404   case ISD::UMIN: return C1.ule(C2) ? C1 : C2;
5405   case ISD::UMAX: return C1.uge(C2) ? C1 : C2;
5406   case ISD::SADDSAT: return C1.sadd_sat(C2);
5407   case ISD::UADDSAT: return C1.uadd_sat(C2);
5408   case ISD::SSUBSAT: return C1.ssub_sat(C2);
5409   case ISD::USUBSAT: return C1.usub_sat(C2);
5410   case ISD::SSHLSAT: return C1.sshl_sat(C2);
5411   case ISD::USHLSAT: return C1.ushl_sat(C2);
5412   case ISD::UDIV:
5413     if (!C2.getBoolValue())
5414       break;
5415     return C1.udiv(C2);
5416   case ISD::UREM:
5417     if (!C2.getBoolValue())
5418       break;
5419     return C1.urem(C2);
5420   case ISD::SDIV:
5421     if (!C2.getBoolValue())
5422       break;
5423     return C1.sdiv(C2);
5424   case ISD::SREM:
5425     if (!C2.getBoolValue())
5426       break;
5427     return C1.srem(C2);
5428   case ISD::MULHS: {
5429     unsigned FullWidth = C1.getBitWidth() * 2;
5430     APInt C1Ext = C1.sext(FullWidth);
5431     APInt C2Ext = C2.sext(FullWidth);
5432     return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth());
5433   }
5434   case ISD::MULHU: {
5435     unsigned FullWidth = C1.getBitWidth() * 2;
5436     APInt C1Ext = C1.zext(FullWidth);
5437     APInt C2Ext = C2.zext(FullWidth);
5438     return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth());
5439   }
5440   case ISD::AVGFLOORS: {
5441     unsigned FullWidth = C1.getBitWidth() + 1;
5442     APInt C1Ext = C1.sext(FullWidth);
5443     APInt C2Ext = C2.sext(FullWidth);
5444     return (C1Ext + C2Ext).extractBits(C1.getBitWidth(), 1);
5445   }
5446   case ISD::AVGFLOORU: {
5447     unsigned FullWidth = C1.getBitWidth() + 1;
5448     APInt C1Ext = C1.zext(FullWidth);
5449     APInt C2Ext = C2.zext(FullWidth);
5450     return (C1Ext + C2Ext).extractBits(C1.getBitWidth(), 1);
5451   }
5452   case ISD::AVGCEILS: {
5453     unsigned FullWidth = C1.getBitWidth() + 1;
5454     APInt C1Ext = C1.sext(FullWidth);
5455     APInt C2Ext = C2.sext(FullWidth);
5456     return (C1Ext + C2Ext + 1).extractBits(C1.getBitWidth(), 1);
5457   }
5458   case ISD::AVGCEILU: {
5459     unsigned FullWidth = C1.getBitWidth() + 1;
5460     APInt C1Ext = C1.zext(FullWidth);
5461     APInt C2Ext = C2.zext(FullWidth);
5462     return (C1Ext + C2Ext + 1).extractBits(C1.getBitWidth(), 1);
5463   }
5464   }
5465   return llvm::None;
5466 }
5467 
5468 SDValue SelectionDAG::FoldSymbolOffset(unsigned Opcode, EVT VT,
5469                                        const GlobalAddressSDNode *GA,
5470                                        const SDNode *N2) {
5471   if (GA->getOpcode() != ISD::GlobalAddress)
5472     return SDValue();
5473   if (!TLI->isOffsetFoldingLegal(GA))
5474     return SDValue();
5475   auto *C2 = dyn_cast<ConstantSDNode>(N2);
5476   if (!C2)
5477     return SDValue();
5478   int64_t Offset = C2->getSExtValue();
5479   switch (Opcode) {
5480   case ISD::ADD: break;
5481   case ISD::SUB: Offset = -uint64_t(Offset); break;
5482   default: return SDValue();
5483   }
5484   return getGlobalAddress(GA->getGlobal(), SDLoc(C2), VT,
5485                           GA->getOffset() + uint64_t(Offset));
5486 }
5487 
5488 bool SelectionDAG::isUndef(unsigned Opcode, ArrayRef<SDValue> Ops) {
5489   switch (Opcode) {
5490   case ISD::SDIV:
5491   case ISD::UDIV:
5492   case ISD::SREM:
5493   case ISD::UREM: {
5494     // If a divisor is zero/undef or any element of a divisor vector is
5495     // zero/undef, the whole op is undef.
5496     assert(Ops.size() == 2 && "Div/rem should have 2 operands");
5497     SDValue Divisor = Ops[1];
5498     if (Divisor.isUndef() || isNullConstant(Divisor))
5499       return true;
5500 
5501     return ISD::isBuildVectorOfConstantSDNodes(Divisor.getNode()) &&
5502            llvm::any_of(Divisor->op_values(),
5503                         [](SDValue V) { return V.isUndef() ||
5504                                         isNullConstant(V); });
5505     // TODO: Handle signed overflow.
5506   }
5507   // TODO: Handle oversized shifts.
5508   default:
5509     return false;
5510   }
5511 }
5512 
5513 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL,
5514                                              EVT VT, ArrayRef<SDValue> Ops) {
5515   // If the opcode is a target-specific ISD node, there's nothing we can
5516   // do here and the operand rules may not line up with the below, so
5517   // bail early.
5518   // We can't create a scalar CONCAT_VECTORS so skip it. It will break
5519   // for concats involving SPLAT_VECTOR. Concats of BUILD_VECTORS are handled by
5520   // foldCONCAT_VECTORS in getNode before this is called.
5521   if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::CONCAT_VECTORS)
5522     return SDValue();
5523 
5524   unsigned NumOps = Ops.size();
5525   if (NumOps == 0)
5526     return SDValue();
5527 
5528   if (isUndef(Opcode, Ops))
5529     return getUNDEF(VT);
5530 
5531   // Handle binops special cases.
5532   if (NumOps == 2) {
5533     if (SDValue CFP = foldConstantFPMath(Opcode, DL, VT, Ops[0], Ops[1]))
5534       return CFP;
5535 
5536     if (auto *C1 = dyn_cast<ConstantSDNode>(Ops[0])) {
5537       if (auto *C2 = dyn_cast<ConstantSDNode>(Ops[1])) {
5538         if (C1->isOpaque() || C2->isOpaque())
5539           return SDValue();
5540 
5541         Optional<APInt> FoldAttempt =
5542             FoldValue(Opcode, C1->getAPIntValue(), C2->getAPIntValue());
5543         if (!FoldAttempt)
5544           return SDValue();
5545 
5546         SDValue Folded = getConstant(*FoldAttempt, DL, VT);
5547         assert((!Folded || !VT.isVector()) &&
5548                "Can't fold vectors ops with scalar operands");
5549         return Folded;
5550       }
5551     }
5552 
5553     // fold (add Sym, c) -> Sym+c
5554     if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ops[0]))
5555       return FoldSymbolOffset(Opcode, VT, GA, Ops[1].getNode());
5556     if (TLI->isCommutativeBinOp(Opcode))
5557       if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ops[1]))
5558         return FoldSymbolOffset(Opcode, VT, GA, Ops[0].getNode());
5559   }
5560 
5561   // This is for vector folding only from here on.
5562   if (!VT.isVector())
5563     return SDValue();
5564 
5565   ElementCount NumElts = VT.getVectorElementCount();
5566 
5567   // See if we can fold through bitcasted integer ops.
5568   // TODO: Can we handle undef elements?
5569   if (NumOps == 2 && VT.isFixedLengthVector() && VT.isInteger() &&
5570       Ops[0].getValueType() == VT && Ops[1].getValueType() == VT &&
5571       Ops[0].getOpcode() == ISD::BITCAST &&
5572       Ops[1].getOpcode() == ISD::BITCAST) {
5573     SDValue N1 = peekThroughBitcasts(Ops[0]);
5574     SDValue N2 = peekThroughBitcasts(Ops[1]);
5575     auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
5576     auto *BV2 = dyn_cast<BuildVectorSDNode>(N2);
5577     EVT BVVT = N1.getValueType();
5578     if (BV1 && BV2 && BVVT.isInteger() && BVVT == N2.getValueType()) {
5579       bool IsLE = getDataLayout().isLittleEndian();
5580       unsigned EltBits = VT.getScalarSizeInBits();
5581       SmallVector<APInt> RawBits1, RawBits2;
5582       BitVector UndefElts1, UndefElts2;
5583       if (BV1->getConstantRawBits(IsLE, EltBits, RawBits1, UndefElts1) &&
5584           BV2->getConstantRawBits(IsLE, EltBits, RawBits2, UndefElts2) &&
5585           UndefElts1.none() && UndefElts2.none()) {
5586         SmallVector<APInt> RawBits;
5587         for (unsigned I = 0, E = NumElts.getFixedValue(); I != E; ++I) {
5588           Optional<APInt> Fold = FoldValue(Opcode, RawBits1[I], RawBits2[I]);
5589           if (!Fold)
5590             break;
5591           RawBits.push_back(*Fold);
5592         }
5593         if (RawBits.size() == NumElts.getFixedValue()) {
5594           // We have constant folded, but we need to cast this again back to
5595           // the original (possibly legalized) type.
5596           SmallVector<APInt> DstBits;
5597           BitVector DstUndefs;
5598           BuildVectorSDNode::recastRawBits(IsLE, BVVT.getScalarSizeInBits(),
5599                                            DstBits, RawBits, DstUndefs,
5600                                            BitVector(RawBits.size(), false));
5601           EVT BVEltVT = BV1->getOperand(0).getValueType();
5602           unsigned BVEltBits = BVEltVT.getSizeInBits();
5603           SmallVector<SDValue> Ops(DstBits.size(), getUNDEF(BVEltVT));
5604           for (unsigned I = 0, E = DstBits.size(); I != E; ++I) {
5605             if (DstUndefs[I])
5606               continue;
5607             Ops[I] = getConstant(DstBits[I].sext(BVEltBits), DL, BVEltVT);
5608           }
5609           return getBitcast(VT, getBuildVector(BVVT, DL, Ops));
5610         }
5611       }
5612     }
5613   }
5614 
5615   // Fold (mul step_vector(C0), C1) to (step_vector(C0 * C1)).
5616   //      (shl step_vector(C0), C1) -> (step_vector(C0 << C1))
5617   if ((Opcode == ISD::MUL || Opcode == ISD::SHL) &&
5618       Ops[0].getOpcode() == ISD::STEP_VECTOR) {
5619     APInt RHSVal;
5620     if (ISD::isConstantSplatVector(Ops[1].getNode(), RHSVal)) {
5621       APInt NewStep = Opcode == ISD::MUL
5622                           ? Ops[0].getConstantOperandAPInt(0) * RHSVal
5623                           : Ops[0].getConstantOperandAPInt(0) << RHSVal;
5624       return getStepVector(DL, VT, NewStep);
5625     }
5626   }
5627 
5628   auto IsScalarOrSameVectorSize = [NumElts](const SDValue &Op) {
5629     return !Op.getValueType().isVector() ||
5630            Op.getValueType().getVectorElementCount() == NumElts;
5631   };
5632 
5633   auto IsBuildVectorSplatVectorOrUndef = [](const SDValue &Op) {
5634     return Op.isUndef() || Op.getOpcode() == ISD::CONDCODE ||
5635            Op.getOpcode() == ISD::BUILD_VECTOR ||
5636            Op.getOpcode() == ISD::SPLAT_VECTOR;
5637   };
5638 
5639   // All operands must be vector types with the same number of elements as
5640   // the result type and must be either UNDEF or a build/splat vector
5641   // or UNDEF scalars.
5642   if (!llvm::all_of(Ops, IsBuildVectorSplatVectorOrUndef) ||
5643       !llvm::all_of(Ops, IsScalarOrSameVectorSize))
5644     return SDValue();
5645 
5646   // If we are comparing vectors, then the result needs to be a i1 boolean that
5647   // is then extended back to the legal result type depending on how booleans
5648   // are represented.
5649   EVT SVT = (Opcode == ISD::SETCC ? MVT::i1 : VT.getScalarType());
5650   ISD::NodeType ExtendCode =
5651       (Opcode == ISD::SETCC && SVT != VT.getScalarType())
5652           ? TargetLowering::getExtendForContent(TLI->getBooleanContents(VT))
5653           : ISD::SIGN_EXTEND;
5654 
5655   // Find legal integer scalar type for constant promotion and
5656   // ensure that its scalar size is at least as large as source.
5657   EVT LegalSVT = VT.getScalarType();
5658   if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
5659     LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
5660     if (LegalSVT.bitsLT(VT.getScalarType()))
5661       return SDValue();
5662   }
5663 
5664   // For scalable vector types we know we're dealing with SPLAT_VECTORs. We
5665   // only have one operand to check. For fixed-length vector types we may have
5666   // a combination of BUILD_VECTOR and SPLAT_VECTOR.
5667   unsigned NumVectorElts = NumElts.isScalable() ? 1 : NumElts.getFixedValue();
5668 
5669   // Constant fold each scalar lane separately.
5670   SmallVector<SDValue, 4> ScalarResults;
5671   for (unsigned I = 0; I != NumVectorElts; I++) {
5672     SmallVector<SDValue, 4> ScalarOps;
5673     for (SDValue Op : Ops) {
5674       EVT InSVT = Op.getValueType().getScalarType();
5675       if (Op.getOpcode() != ISD::BUILD_VECTOR &&
5676           Op.getOpcode() != ISD::SPLAT_VECTOR) {
5677         if (Op.isUndef())
5678           ScalarOps.push_back(getUNDEF(InSVT));
5679         else
5680           ScalarOps.push_back(Op);
5681         continue;
5682       }
5683 
5684       SDValue ScalarOp =
5685           Op.getOperand(Op.getOpcode() == ISD::SPLAT_VECTOR ? 0 : I);
5686       EVT ScalarVT = ScalarOp.getValueType();
5687 
5688       // Build vector (integer) scalar operands may need implicit
5689       // truncation - do this before constant folding.
5690       if (ScalarVT.isInteger() && ScalarVT.bitsGT(InSVT)) {
5691         // Don't create illegally-typed nodes unless they're constants or undef
5692         // - if we fail to constant fold we can't guarantee the (dead) nodes
5693         // we're creating will be cleaned up before being visited for
5694         // legalization.
5695         if (NewNodesMustHaveLegalTypes && !ScalarOp.isUndef() &&
5696             !isa<ConstantSDNode>(ScalarOp) &&
5697             TLI->getTypeAction(*getContext(), InSVT) !=
5698                 TargetLowering::TypeLegal)
5699           return SDValue();
5700         ScalarOp = getNode(ISD::TRUNCATE, DL, InSVT, ScalarOp);
5701       }
5702 
5703       ScalarOps.push_back(ScalarOp);
5704     }
5705 
5706     // Constant fold the scalar operands.
5707     SDValue ScalarResult = getNode(Opcode, DL, SVT, ScalarOps);
5708 
5709     // Legalize the (integer) scalar constant if necessary.
5710     if (LegalSVT != SVT)
5711       ScalarResult = getNode(ExtendCode, DL, LegalSVT, ScalarResult);
5712 
5713     // Scalar folding only succeeded if the result is a constant or UNDEF.
5714     if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant &&
5715         ScalarResult.getOpcode() != ISD::ConstantFP)
5716       return SDValue();
5717     ScalarResults.push_back(ScalarResult);
5718   }
5719 
5720   SDValue V = NumElts.isScalable() ? getSplatVector(VT, DL, ScalarResults[0])
5721                                    : getBuildVector(VT, DL, ScalarResults);
5722   NewSDValueDbgMsg(V, "New node fold constant vector: ", this);
5723   return V;
5724 }
5725 
5726 SDValue SelectionDAG::foldConstantFPMath(unsigned Opcode, const SDLoc &DL,
5727                                          EVT VT, SDValue N1, SDValue N2) {
5728   // TODO: We don't do any constant folding for strict FP opcodes here, but we
5729   //       should. That will require dealing with a potentially non-default
5730   //       rounding mode, checking the "opStatus" return value from the APFloat
5731   //       math calculations, and possibly other variations.
5732   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1, /*AllowUndefs*/ false);
5733   ConstantFPSDNode *N2CFP = isConstOrConstSplatFP(N2, /*AllowUndefs*/ false);
5734   if (N1CFP && N2CFP) {
5735     APFloat C1 = N1CFP->getValueAPF(); // make copy
5736     const APFloat &C2 = N2CFP->getValueAPF();
5737     switch (Opcode) {
5738     case ISD::FADD:
5739       C1.add(C2, APFloat::rmNearestTiesToEven);
5740       return getConstantFP(C1, DL, VT);
5741     case ISD::FSUB:
5742       C1.subtract(C2, APFloat::rmNearestTiesToEven);
5743       return getConstantFP(C1, DL, VT);
5744     case ISD::FMUL:
5745       C1.multiply(C2, APFloat::rmNearestTiesToEven);
5746       return getConstantFP(C1, DL, VT);
5747     case ISD::FDIV:
5748       C1.divide(C2, APFloat::rmNearestTiesToEven);
5749       return getConstantFP(C1, DL, VT);
5750     case ISD::FREM:
5751       C1.mod(C2);
5752       return getConstantFP(C1, DL, VT);
5753     case ISD::FCOPYSIGN:
5754       C1.copySign(C2);
5755       return getConstantFP(C1, DL, VT);
5756     case ISD::FMINNUM:
5757       return getConstantFP(minnum(C1, C2), DL, VT);
5758     case ISD::FMAXNUM:
5759       return getConstantFP(maxnum(C1, C2), DL, VT);
5760     case ISD::FMINIMUM:
5761       return getConstantFP(minimum(C1, C2), DL, VT);
5762     case ISD::FMAXIMUM:
5763       return getConstantFP(maximum(C1, C2), DL, VT);
5764     default: break;
5765     }
5766   }
5767   if (N1CFP && Opcode == ISD::FP_ROUND) {
5768     APFloat C1 = N1CFP->getValueAPF();    // make copy
5769     bool Unused;
5770     // This can return overflow, underflow, or inexact; we don't care.
5771     // FIXME need to be more flexible about rounding mode.
5772     (void) C1.convert(EVTToAPFloatSemantics(VT), APFloat::rmNearestTiesToEven,
5773                       &Unused);
5774     return getConstantFP(C1, DL, VT);
5775   }
5776 
5777   switch (Opcode) {
5778   case ISD::FSUB:
5779     // -0.0 - undef --> undef (consistent with "fneg undef")
5780     if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1, /*AllowUndefs*/ true))
5781       if (N1C && N1C->getValueAPF().isNegZero() && N2.isUndef())
5782         return getUNDEF(VT);
5783     LLVM_FALLTHROUGH;
5784 
5785   case ISD::FADD:
5786   case ISD::FMUL:
5787   case ISD::FDIV:
5788   case ISD::FREM:
5789     // If both operands are undef, the result is undef. If 1 operand is undef,
5790     // the result is NaN. This should match the behavior of the IR optimizer.
5791     if (N1.isUndef() && N2.isUndef())
5792       return getUNDEF(VT);
5793     if (N1.isUndef() || N2.isUndef())
5794       return getConstantFP(APFloat::getNaN(EVTToAPFloatSemantics(VT)), DL, VT);
5795   }
5796   return SDValue();
5797 }
5798 
5799 SDValue SelectionDAG::getAssertAlign(const SDLoc &DL, SDValue Val, Align A) {
5800   assert(Val.getValueType().isInteger() && "Invalid AssertAlign!");
5801 
5802   // There's no need to assert on a byte-aligned pointer. All pointers are at
5803   // least byte aligned.
5804   if (A == Align(1))
5805     return Val;
5806 
5807   FoldingSetNodeID ID;
5808   AddNodeIDNode(ID, ISD::AssertAlign, getVTList(Val.getValueType()), {Val});
5809   ID.AddInteger(A.value());
5810 
5811   void *IP = nullptr;
5812   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
5813     return SDValue(E, 0);
5814 
5815   auto *N = newSDNode<AssertAlignSDNode>(DL.getIROrder(), DL.getDebugLoc(),
5816                                          Val.getValueType(), A);
5817   createOperands(N, {Val});
5818 
5819   CSEMap.InsertNode(N, IP);
5820   InsertNode(N);
5821 
5822   SDValue V(N, 0);
5823   NewSDValueDbgMsg(V, "Creating new node: ", this);
5824   return V;
5825 }
5826 
5827 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5828                               SDValue N1, SDValue N2) {
5829   SDNodeFlags Flags;
5830   if (Inserter)
5831     Flags = Inserter->getFlags();
5832   return getNode(Opcode, DL, VT, N1, N2, Flags);
5833 }
5834 
5835 void SelectionDAG::canonicalizeCommutativeBinop(unsigned Opcode, SDValue &N1,
5836                                                 SDValue &N2) const {
5837   if (!TLI->isCommutativeBinOp(Opcode))
5838     return;
5839 
5840   // Canonicalize:
5841   //   binop(const, nonconst) -> binop(nonconst, const)
5842   bool IsN1C = isConstantIntBuildVectorOrConstantInt(N1);
5843   bool IsN2C = isConstantIntBuildVectorOrConstantInt(N2);
5844   bool IsN1CFP = isConstantFPBuildVectorOrConstantFP(N1);
5845   bool IsN2CFP = isConstantFPBuildVectorOrConstantFP(N2);
5846   if ((IsN1C && !IsN2C) || (IsN1CFP && !IsN2CFP))
5847     std::swap(N1, N2);
5848 
5849   // Canonicalize:
5850   //  binop(splat(x), step_vector) -> binop(step_vector, splat(x))
5851   else if (N1.getOpcode() == ISD::SPLAT_VECTOR &&
5852            N2.getOpcode() == ISD::STEP_VECTOR)
5853     std::swap(N1, N2);
5854 }
5855 
5856 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5857                               SDValue N1, SDValue N2, const SDNodeFlags Flags) {
5858   assert(N1.getOpcode() != ISD::DELETED_NODE &&
5859          N2.getOpcode() != ISD::DELETED_NODE &&
5860          "Operand is DELETED_NODE!");
5861 
5862   canonicalizeCommutativeBinop(Opcode, N1, N2);
5863 
5864   auto *N1C = dyn_cast<ConstantSDNode>(N1);
5865   auto *N2C = dyn_cast<ConstantSDNode>(N2);
5866 
5867   // Don't allow undefs in vector splats - we might be returning N2 when folding
5868   // to zero etc.
5869   ConstantSDNode *N2CV =
5870       isConstOrConstSplat(N2, /*AllowUndefs*/ false, /*AllowTruncation*/ true);
5871 
5872   switch (Opcode) {
5873   default: break;
5874   case ISD::TokenFactor:
5875     assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
5876            N2.getValueType() == MVT::Other && "Invalid token factor!");
5877     // Fold trivial token factors.
5878     if (N1.getOpcode() == ISD::EntryToken) return N2;
5879     if (N2.getOpcode() == ISD::EntryToken) return N1;
5880     if (N1 == N2) return N1;
5881     break;
5882   case ISD::BUILD_VECTOR: {
5883     // Attempt to simplify BUILD_VECTOR.
5884     SDValue Ops[] = {N1, N2};
5885     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
5886       return V;
5887     break;
5888   }
5889   case ISD::CONCAT_VECTORS: {
5890     SDValue Ops[] = {N1, N2};
5891     if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
5892       return V;
5893     break;
5894   }
5895   case ISD::AND:
5896     assert(VT.isInteger() && "This operator does not apply to FP types!");
5897     assert(N1.getValueType() == N2.getValueType() &&
5898            N1.getValueType() == VT && "Binary operator types must match!");
5899     // (X & 0) -> 0.  This commonly occurs when legalizing i64 values, so it's
5900     // worth handling here.
5901     if (N2CV && N2CV->isZero())
5902       return N2;
5903     if (N2CV && N2CV->isAllOnes()) // X & -1 -> X
5904       return N1;
5905     break;
5906   case ISD::OR:
5907   case ISD::XOR:
5908   case ISD::ADD:
5909   case ISD::SUB:
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     // (X ^|+- 0) -> X.  This commonly occurs when legalizing i64 values, so
5914     // it's worth handling here.
5915     if (N2CV && N2CV->isZero())
5916       return N1;
5917     if ((Opcode == ISD::ADD || Opcode == ISD::SUB) && VT.isVector() &&
5918         VT.getVectorElementType() == MVT::i1)
5919       return getNode(ISD::XOR, DL, VT, N1, N2);
5920     break;
5921   case ISD::MUL:
5922     assert(VT.isInteger() && "This operator does not apply to FP types!");
5923     assert(N1.getValueType() == N2.getValueType() &&
5924            N1.getValueType() == VT && "Binary operator types must match!");
5925     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
5926       return getNode(ISD::AND, DL, VT, N1, N2);
5927     if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
5928       const APInt &MulImm = N1->getConstantOperandAPInt(0);
5929       const APInt &N2CImm = N2C->getAPIntValue();
5930       return getVScale(DL, VT, MulImm * N2CImm);
5931     }
5932     break;
5933   case ISD::UDIV:
5934   case ISD::UREM:
5935   case ISD::MULHU:
5936   case ISD::MULHS:
5937   case ISD::SDIV:
5938   case ISD::SREM:
5939   case ISD::SADDSAT:
5940   case ISD::SSUBSAT:
5941   case ISD::UADDSAT:
5942   case ISD::USUBSAT:
5943     assert(VT.isInteger() && "This operator does not apply to FP types!");
5944     assert(N1.getValueType() == N2.getValueType() &&
5945            N1.getValueType() == VT && "Binary operator types must match!");
5946     if (VT.isVector() && VT.getVectorElementType() == MVT::i1) {
5947       // fold (add_sat x, y) -> (or x, y) for bool types.
5948       if (Opcode == ISD::SADDSAT || Opcode == ISD::UADDSAT)
5949         return getNode(ISD::OR, DL, VT, N1, N2);
5950       // fold (sub_sat x, y) -> (and x, ~y) for bool types.
5951       if (Opcode == ISD::SSUBSAT || Opcode == ISD::USUBSAT)
5952         return getNode(ISD::AND, DL, VT, N1, getNOT(DL, N2, VT));
5953     }
5954     break;
5955   case ISD::SMIN:
5956   case ISD::UMAX:
5957     assert(VT.isInteger() && "This operator does not apply to FP types!");
5958     assert(N1.getValueType() == N2.getValueType() &&
5959            N1.getValueType() == VT && "Binary operator types must match!");
5960     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
5961       return getNode(ISD::OR, DL, VT, N1, N2);
5962     break;
5963   case ISD::SMAX:
5964   case ISD::UMIN:
5965     assert(VT.isInteger() && "This operator does not apply to FP types!");
5966     assert(N1.getValueType() == N2.getValueType() &&
5967            N1.getValueType() == VT && "Binary operator types must match!");
5968     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
5969       return getNode(ISD::AND, DL, VT, N1, N2);
5970     break;
5971   case ISD::FADD:
5972   case ISD::FSUB:
5973   case ISD::FMUL:
5974   case ISD::FDIV:
5975   case ISD::FREM:
5976     assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
5977     assert(N1.getValueType() == N2.getValueType() &&
5978            N1.getValueType() == VT && "Binary operator types must match!");
5979     if (SDValue V = simplifyFPBinop(Opcode, N1, N2, Flags))
5980       return V;
5981     break;
5982   case ISD::FCOPYSIGN:   // N1 and result must match.  N1/N2 need not match.
5983     assert(N1.getValueType() == VT &&
5984            N1.getValueType().isFloatingPoint() &&
5985            N2.getValueType().isFloatingPoint() &&
5986            "Invalid FCOPYSIGN!");
5987     break;
5988   case ISD::SHL:
5989     if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
5990       const APInt &MulImm = N1->getConstantOperandAPInt(0);
5991       const APInt &ShiftImm = N2C->getAPIntValue();
5992       return getVScale(DL, VT, MulImm << ShiftImm);
5993     }
5994     LLVM_FALLTHROUGH;
5995   case ISD::SRA:
5996   case ISD::SRL:
5997     if (SDValue V = simplifyShift(N1, N2))
5998       return V;
5999     LLVM_FALLTHROUGH;
6000   case ISD::ROTL:
6001   case ISD::ROTR:
6002     assert(VT == N1.getValueType() &&
6003            "Shift operators return type must be the same as their first arg");
6004     assert(VT.isInteger() && N2.getValueType().isInteger() &&
6005            "Shifts only work on integers");
6006     assert((!VT.isVector() || VT == N2.getValueType()) &&
6007            "Vector shift amounts must be in the same as their first arg");
6008     // Verify that the shift amount VT is big enough to hold valid shift
6009     // amounts.  This catches things like trying to shift an i1024 value by an
6010     // i8, which is easy to fall into in generic code that uses
6011     // TLI.getShiftAmount().
6012     assert(N2.getValueType().getScalarSizeInBits() >=
6013                Log2_32_Ceil(VT.getScalarSizeInBits()) &&
6014            "Invalid use of small shift amount with oversized value!");
6015 
6016     // Always fold shifts of i1 values so the code generator doesn't need to
6017     // handle them.  Since we know the size of the shift has to be less than the
6018     // size of the value, the shift/rotate count is guaranteed to be zero.
6019     if (VT == MVT::i1)
6020       return N1;
6021     if (N2CV && N2CV->isZero())
6022       return N1;
6023     break;
6024   case ISD::FP_ROUND:
6025     assert(VT.isFloatingPoint() &&
6026            N1.getValueType().isFloatingPoint() &&
6027            VT.bitsLE(N1.getValueType()) &&
6028            N2C && (N2C->getZExtValue() == 0 || N2C->getZExtValue() == 1) &&
6029            "Invalid FP_ROUND!");
6030     if (N1.getValueType() == VT) return N1;  // noop conversion.
6031     break;
6032   case ISD::AssertSext:
6033   case ISD::AssertZext: {
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() &&
6039            "AssertSExt/AssertZExt type should be the vector element type "
6040            "rather than the vector type!");
6041     assert(EVT.bitsLE(VT.getScalarType()) && "Not extending!");
6042     if (VT.getScalarType() == EVT) return N1; // noop assertion.
6043     break;
6044   }
6045   case ISD::SIGN_EXTEND_INREG: {
6046     EVT EVT = cast<VTSDNode>(N2)->getVT();
6047     assert(VT == N1.getValueType() && "Not an inreg extend!");
6048     assert(VT.isInteger() && EVT.isInteger() &&
6049            "Cannot *_EXTEND_INREG FP types");
6050     assert(EVT.isVector() == VT.isVector() &&
6051            "SIGN_EXTEND_INREG type should be vector iff the operand "
6052            "type is vector!");
6053     assert((!EVT.isVector() ||
6054             EVT.getVectorElementCount() == VT.getVectorElementCount()) &&
6055            "Vector element counts must match in SIGN_EXTEND_INREG");
6056     assert(EVT.bitsLE(VT) && "Not extending!");
6057     if (EVT == VT) return N1;  // Not actually extending
6058 
6059     auto SignExtendInReg = [&](APInt Val, llvm::EVT ConstantVT) {
6060       unsigned FromBits = EVT.getScalarSizeInBits();
6061       Val <<= Val.getBitWidth() - FromBits;
6062       Val.ashrInPlace(Val.getBitWidth() - FromBits);
6063       return getConstant(Val, DL, ConstantVT);
6064     };
6065 
6066     if (N1C) {
6067       const APInt &Val = N1C->getAPIntValue();
6068       return SignExtendInReg(Val, VT);
6069     }
6070 
6071     if (ISD::isBuildVectorOfConstantSDNodes(N1.getNode())) {
6072       SmallVector<SDValue, 8> Ops;
6073       llvm::EVT OpVT = N1.getOperand(0).getValueType();
6074       for (int i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
6075         SDValue Op = N1.getOperand(i);
6076         if (Op.isUndef()) {
6077           Ops.push_back(getUNDEF(OpVT));
6078           continue;
6079         }
6080         ConstantSDNode *C = cast<ConstantSDNode>(Op);
6081         APInt Val = C->getAPIntValue();
6082         Ops.push_back(SignExtendInReg(Val, OpVT));
6083       }
6084       return getBuildVector(VT, DL, Ops);
6085     }
6086     break;
6087   }
6088   case ISD::FP_TO_SINT_SAT:
6089   case ISD::FP_TO_UINT_SAT: {
6090     assert(VT.isInteger() && cast<VTSDNode>(N2)->getVT().isInteger() &&
6091            N1.getValueType().isFloatingPoint() && "Invalid FP_TO_*INT_SAT");
6092     assert(N1.getValueType().isVector() == VT.isVector() &&
6093            "FP_TO_*INT_SAT type should be vector iff the operand type is "
6094            "vector!");
6095     assert((!VT.isVector() || VT.getVectorNumElements() ==
6096                                   N1.getValueType().getVectorNumElements()) &&
6097            "Vector element counts must match in FP_TO_*INT_SAT");
6098     assert(!cast<VTSDNode>(N2)->getVT().isVector() &&
6099            "Type to saturate to must be a scalar.");
6100     assert(cast<VTSDNode>(N2)->getVT().bitsLE(VT.getScalarType()) &&
6101            "Not extending!");
6102     break;
6103   }
6104   case ISD::EXTRACT_VECTOR_ELT:
6105     assert(VT.getSizeInBits() >= N1.getValueType().getScalarSizeInBits() &&
6106            "The result of EXTRACT_VECTOR_ELT must be at least as wide as the \
6107              element type of the vector.");
6108 
6109     // Extract from an undefined value or using an undefined index is undefined.
6110     if (N1.isUndef() || N2.isUndef())
6111       return getUNDEF(VT);
6112 
6113     // EXTRACT_VECTOR_ELT of out-of-bounds element is an UNDEF for fixed length
6114     // vectors. For scalable vectors we will provide appropriate support for
6115     // dealing with arbitrary indices.
6116     if (N2C && N1.getValueType().isFixedLengthVector() &&
6117         N2C->getAPIntValue().uge(N1.getValueType().getVectorNumElements()))
6118       return getUNDEF(VT);
6119 
6120     // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
6121     // expanding copies of large vectors from registers. This only works for
6122     // fixed length vectors, since we need to know the exact number of
6123     // elements.
6124     if (N2C && N1.getOperand(0).getValueType().isFixedLengthVector() &&
6125         N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0) {
6126       unsigned Factor =
6127         N1.getOperand(0).getValueType().getVectorNumElements();
6128       return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
6129                      N1.getOperand(N2C->getZExtValue() / Factor),
6130                      getVectorIdxConstant(N2C->getZExtValue() % Factor, DL));
6131     }
6132 
6133     // EXTRACT_VECTOR_ELT of BUILD_VECTOR or SPLAT_VECTOR is often formed while
6134     // lowering is expanding large vector constants.
6135     if (N2C && (N1.getOpcode() == ISD::BUILD_VECTOR ||
6136                 N1.getOpcode() == ISD::SPLAT_VECTOR)) {
6137       assert((N1.getOpcode() != ISD::BUILD_VECTOR ||
6138               N1.getValueType().isFixedLengthVector()) &&
6139              "BUILD_VECTOR used for scalable vectors");
6140       unsigned Index =
6141           N1.getOpcode() == ISD::BUILD_VECTOR ? N2C->getZExtValue() : 0;
6142       SDValue Elt = N1.getOperand(Index);
6143 
6144       if (VT != Elt.getValueType())
6145         // If the vector element type is not legal, the BUILD_VECTOR operands
6146         // are promoted and implicitly truncated, and the result implicitly
6147         // extended. Make that explicit here.
6148         Elt = getAnyExtOrTrunc(Elt, DL, VT);
6149 
6150       return Elt;
6151     }
6152 
6153     // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
6154     // operations are lowered to scalars.
6155     if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) {
6156       // If the indices are the same, return the inserted element else
6157       // if the indices are known different, extract the element from
6158       // the original vector.
6159       SDValue N1Op2 = N1.getOperand(2);
6160       ConstantSDNode *N1Op2C = dyn_cast<ConstantSDNode>(N1Op2);
6161 
6162       if (N1Op2C && N2C) {
6163         if (N1Op2C->getZExtValue() == N2C->getZExtValue()) {
6164           if (VT == N1.getOperand(1).getValueType())
6165             return N1.getOperand(1);
6166           return getSExtOrTrunc(N1.getOperand(1), DL, VT);
6167         }
6168         return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2);
6169       }
6170     }
6171 
6172     // EXTRACT_VECTOR_ELT of v1iX EXTRACT_SUBVECTOR could be formed
6173     // when vector types are scalarized and v1iX is legal.
6174     // vextract (v1iX extract_subvector(vNiX, Idx)) -> vextract(vNiX,Idx).
6175     // Here we are completely ignoring the extract element index (N2),
6176     // which is fine for fixed width vectors, since any index other than 0
6177     // is undefined anyway. However, this cannot be ignored for scalable
6178     // vectors - in theory we could support this, but we don't want to do this
6179     // without a profitability check.
6180     if (N1.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
6181         N1.getValueType().isFixedLengthVector() &&
6182         N1.getValueType().getVectorNumElements() == 1) {
6183       return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0),
6184                      N1.getOperand(1));
6185     }
6186     break;
6187   case ISD::EXTRACT_ELEMENT:
6188     assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!");
6189     assert(!N1.getValueType().isVector() && !VT.isVector() &&
6190            (N1.getValueType().isInteger() == VT.isInteger()) &&
6191            N1.getValueType() != VT &&
6192            "Wrong types for EXTRACT_ELEMENT!");
6193 
6194     // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
6195     // 64-bit integers into 32-bit parts.  Instead of building the extract of
6196     // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
6197     if (N1.getOpcode() == ISD::BUILD_PAIR)
6198       return N1.getOperand(N2C->getZExtValue());
6199 
6200     // EXTRACT_ELEMENT of a constant int is also very common.
6201     if (N1C) {
6202       unsigned ElementSize = VT.getSizeInBits();
6203       unsigned Shift = ElementSize * N2C->getZExtValue();
6204       const APInt &Val = N1C->getAPIntValue();
6205       return getConstant(Val.extractBits(ElementSize, Shift), DL, VT);
6206     }
6207     break;
6208   case ISD::EXTRACT_SUBVECTOR: {
6209     EVT N1VT = N1.getValueType();
6210     assert(VT.isVector() && N1VT.isVector() &&
6211            "Extract subvector VTs must be vectors!");
6212     assert(VT.getVectorElementType() == N1VT.getVectorElementType() &&
6213            "Extract subvector VTs must have the same element type!");
6214     assert((VT.isFixedLengthVector() || N1VT.isScalableVector()) &&
6215            "Cannot extract a scalable vector from a fixed length vector!");
6216     assert((VT.isScalableVector() != N1VT.isScalableVector() ||
6217             VT.getVectorMinNumElements() <= N1VT.getVectorMinNumElements()) &&
6218            "Extract subvector must be from larger vector to smaller vector!");
6219     assert(N2C && "Extract subvector index must be a constant");
6220     assert((VT.isScalableVector() != N1VT.isScalableVector() ||
6221             (VT.getVectorMinNumElements() + N2C->getZExtValue()) <=
6222                 N1VT.getVectorMinNumElements()) &&
6223            "Extract subvector overflow!");
6224     assert(N2C->getAPIntValue().getBitWidth() ==
6225                TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() &&
6226            "Constant index for EXTRACT_SUBVECTOR has an invalid size");
6227 
6228     // Trivial extraction.
6229     if (VT == N1VT)
6230       return N1;
6231 
6232     // EXTRACT_SUBVECTOR of an UNDEF is an UNDEF.
6233     if (N1.isUndef())
6234       return getUNDEF(VT);
6235 
6236     // EXTRACT_SUBVECTOR of CONCAT_VECTOR can be simplified if the pieces of
6237     // the concat have the same type as the extract.
6238     if (N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0 &&
6239         VT == N1.getOperand(0).getValueType()) {
6240       unsigned Factor = VT.getVectorMinNumElements();
6241       return N1.getOperand(N2C->getZExtValue() / Factor);
6242     }
6243 
6244     // EXTRACT_SUBVECTOR of INSERT_SUBVECTOR is often created
6245     // during shuffle legalization.
6246     if (N1.getOpcode() == ISD::INSERT_SUBVECTOR && N2 == N1.getOperand(2) &&
6247         VT == N1.getOperand(1).getValueType())
6248       return N1.getOperand(1);
6249     break;
6250   }
6251   }
6252 
6253   // Perform trivial constant folding.
6254   if (SDValue SV = FoldConstantArithmetic(Opcode, DL, VT, {N1, N2}))
6255     return SV;
6256 
6257   // Canonicalize an UNDEF to the RHS, even over a constant.
6258   if (N1.isUndef()) {
6259     if (TLI->isCommutativeBinOp(Opcode)) {
6260       std::swap(N1, N2);
6261     } else {
6262       switch (Opcode) {
6263       case ISD::SUB:
6264         return getUNDEF(VT);     // fold op(undef, arg2) -> undef
6265       case ISD::SIGN_EXTEND_INREG:
6266       case ISD::UDIV:
6267       case ISD::SDIV:
6268       case ISD::UREM:
6269       case ISD::SREM:
6270       case ISD::SSUBSAT:
6271       case ISD::USUBSAT:
6272         return getConstant(0, DL, VT);    // fold op(undef, arg2) -> 0
6273       }
6274     }
6275   }
6276 
6277   // Fold a bunch of operators when the RHS is undef.
6278   if (N2.isUndef()) {
6279     switch (Opcode) {
6280     case ISD::XOR:
6281       if (N1.isUndef())
6282         // Handle undef ^ undef -> 0 special case. This is a common
6283         // idiom (misuse).
6284         return getConstant(0, DL, VT);
6285       LLVM_FALLTHROUGH;
6286     case ISD::ADD:
6287     case ISD::SUB:
6288     case ISD::UDIV:
6289     case ISD::SDIV:
6290     case ISD::UREM:
6291     case ISD::SREM:
6292       return getUNDEF(VT);       // fold op(arg1, undef) -> undef
6293     case ISD::MUL:
6294     case ISD::AND:
6295     case ISD::SSUBSAT:
6296     case ISD::USUBSAT:
6297       return getConstant(0, DL, VT);  // fold op(arg1, undef) -> 0
6298     case ISD::OR:
6299     case ISD::SADDSAT:
6300     case ISD::UADDSAT:
6301       return getAllOnesConstant(DL, VT);
6302     }
6303   }
6304 
6305   // Memoize this node if possible.
6306   SDNode *N;
6307   SDVTList VTs = getVTList(VT);
6308   SDValue Ops[] = {N1, N2};
6309   if (VT != MVT::Glue) {
6310     FoldingSetNodeID ID;
6311     AddNodeIDNode(ID, Opcode, VTs, Ops);
6312     void *IP = nullptr;
6313     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
6314       E->intersectFlagsWith(Flags);
6315       return SDValue(E, 0);
6316     }
6317 
6318     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6319     N->setFlags(Flags);
6320     createOperands(N, Ops);
6321     CSEMap.InsertNode(N, IP);
6322   } else {
6323     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6324     createOperands(N, Ops);
6325   }
6326 
6327   InsertNode(N);
6328   SDValue V = SDValue(N, 0);
6329   NewSDValueDbgMsg(V, "Creating new node: ", this);
6330   return V;
6331 }
6332 
6333 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6334                               SDValue N1, SDValue N2, SDValue N3) {
6335   SDNodeFlags Flags;
6336   if (Inserter)
6337     Flags = Inserter->getFlags();
6338   return getNode(Opcode, DL, VT, N1, N2, N3, Flags);
6339 }
6340 
6341 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6342                               SDValue N1, SDValue N2, SDValue N3,
6343                               const SDNodeFlags Flags) {
6344   assert(N1.getOpcode() != ISD::DELETED_NODE &&
6345          N2.getOpcode() != ISD::DELETED_NODE &&
6346          N3.getOpcode() != ISD::DELETED_NODE &&
6347          "Operand is DELETED_NODE!");
6348   // Perform various simplifications.
6349   switch (Opcode) {
6350   case ISD::FMA: {
6351     assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
6352     assert(N1.getValueType() == VT && N2.getValueType() == VT &&
6353            N3.getValueType() == VT && "FMA types must match!");
6354     ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6355     ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
6356     ConstantFPSDNode *N3CFP = dyn_cast<ConstantFPSDNode>(N3);
6357     if (N1CFP && N2CFP && N3CFP) {
6358       APFloat  V1 = N1CFP->getValueAPF();
6359       const APFloat &V2 = N2CFP->getValueAPF();
6360       const APFloat &V3 = N3CFP->getValueAPF();
6361       V1.fusedMultiplyAdd(V2, V3, APFloat::rmNearestTiesToEven);
6362       return getConstantFP(V1, DL, VT);
6363     }
6364     break;
6365   }
6366   case ISD::BUILD_VECTOR: {
6367     // Attempt to simplify BUILD_VECTOR.
6368     SDValue Ops[] = {N1, N2, N3};
6369     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
6370       return V;
6371     break;
6372   }
6373   case ISD::CONCAT_VECTORS: {
6374     SDValue Ops[] = {N1, N2, N3};
6375     if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
6376       return V;
6377     break;
6378   }
6379   case ISD::SETCC: {
6380     assert(VT.isInteger() && "SETCC result type must be an integer!");
6381     assert(N1.getValueType() == N2.getValueType() &&
6382            "SETCC operands must have the same type!");
6383     assert(VT.isVector() == N1.getValueType().isVector() &&
6384            "SETCC type should be vector iff the operand type is vector!");
6385     assert((!VT.isVector() || VT.getVectorElementCount() ==
6386                                   N1.getValueType().getVectorElementCount()) &&
6387            "SETCC vector element counts must match!");
6388     // Use FoldSetCC to simplify SETCC's.
6389     if (SDValue V = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL))
6390       return V;
6391     // Vector constant folding.
6392     SDValue Ops[] = {N1, N2, N3};
6393     if (SDValue V = FoldConstantArithmetic(Opcode, DL, VT, Ops)) {
6394       NewSDValueDbgMsg(V, "New node vector constant folding: ", this);
6395       return V;
6396     }
6397     break;
6398   }
6399   case ISD::SELECT:
6400   case ISD::VSELECT:
6401     if (SDValue V = simplifySelect(N1, N2, N3))
6402       return V;
6403     break;
6404   case ISD::VECTOR_SHUFFLE:
6405     llvm_unreachable("should use getVectorShuffle constructor!");
6406   case ISD::VECTOR_SPLICE: {
6407     if (cast<ConstantSDNode>(N3)->isNullValue())
6408       return N1;
6409     break;
6410   }
6411   case ISD::INSERT_VECTOR_ELT: {
6412     ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3);
6413     // INSERT_VECTOR_ELT into out-of-bounds element is an UNDEF, except
6414     // for scalable vectors where we will generate appropriate code to
6415     // deal with out-of-bounds cases correctly.
6416     if (N3C && N1.getValueType().isFixedLengthVector() &&
6417         N3C->getZExtValue() >= N1.getValueType().getVectorNumElements())
6418       return getUNDEF(VT);
6419 
6420     // Undefined index can be assumed out-of-bounds, so that's UNDEF too.
6421     if (N3.isUndef())
6422       return getUNDEF(VT);
6423 
6424     // If the inserted element is an UNDEF, just use the input vector.
6425     if (N2.isUndef())
6426       return N1;
6427 
6428     break;
6429   }
6430   case ISD::INSERT_SUBVECTOR: {
6431     // Inserting undef into undef is still undef.
6432     if (N1.isUndef() && N2.isUndef())
6433       return getUNDEF(VT);
6434 
6435     EVT N2VT = N2.getValueType();
6436     assert(VT == N1.getValueType() &&
6437            "Dest and insert subvector source types must match!");
6438     assert(VT.isVector() && N2VT.isVector() &&
6439            "Insert subvector VTs must be vectors!");
6440     assert((VT.isScalableVector() || N2VT.isFixedLengthVector()) &&
6441            "Cannot insert a scalable vector into a fixed length vector!");
6442     assert((VT.isScalableVector() != N2VT.isScalableVector() ||
6443             VT.getVectorMinNumElements() >= N2VT.getVectorMinNumElements()) &&
6444            "Insert subvector must be from smaller vector to larger vector!");
6445     assert(isa<ConstantSDNode>(N3) &&
6446            "Insert subvector index must be constant");
6447     assert((VT.isScalableVector() != N2VT.isScalableVector() ||
6448             (N2VT.getVectorMinNumElements() +
6449              cast<ConstantSDNode>(N3)->getZExtValue()) <=
6450                 VT.getVectorMinNumElements()) &&
6451            "Insert subvector overflow!");
6452     assert(cast<ConstantSDNode>(N3)->getAPIntValue().getBitWidth() ==
6453                TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() &&
6454            "Constant index for INSERT_SUBVECTOR has an invalid size");
6455 
6456     // Trivial insertion.
6457     if (VT == N2VT)
6458       return N2;
6459 
6460     // If this is an insert of an extracted vector into an undef vector, we
6461     // can just use the input to the extract.
6462     if (N1.isUndef() && N2.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
6463         N2.getOperand(1) == N3 && N2.getOperand(0).getValueType() == VT)
6464       return N2.getOperand(0);
6465     break;
6466   }
6467   case ISD::BITCAST:
6468     // Fold bit_convert nodes from a type to themselves.
6469     if (N1.getValueType() == VT)
6470       return N1;
6471     break;
6472   }
6473 
6474   // Memoize node if it doesn't produce a flag.
6475   SDNode *N;
6476   SDVTList VTs = getVTList(VT);
6477   SDValue Ops[] = {N1, N2, N3};
6478   if (VT != MVT::Glue) {
6479     FoldingSetNodeID ID;
6480     AddNodeIDNode(ID, Opcode, VTs, Ops);
6481     void *IP = nullptr;
6482     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
6483       E->intersectFlagsWith(Flags);
6484       return SDValue(E, 0);
6485     }
6486 
6487     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6488     N->setFlags(Flags);
6489     createOperands(N, Ops);
6490     CSEMap.InsertNode(N, IP);
6491   } else {
6492     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6493     createOperands(N, Ops);
6494   }
6495 
6496   InsertNode(N);
6497   SDValue V = SDValue(N, 0);
6498   NewSDValueDbgMsg(V, "Creating new node: ", this);
6499   return V;
6500 }
6501 
6502 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6503                               SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
6504   SDValue Ops[] = { N1, N2, N3, N4 };
6505   return getNode(Opcode, DL, VT, Ops);
6506 }
6507 
6508 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6509                               SDValue N1, SDValue N2, SDValue N3, SDValue N4,
6510                               SDValue N5) {
6511   SDValue Ops[] = { N1, N2, N3, N4, N5 };
6512   return getNode(Opcode, DL, VT, Ops);
6513 }
6514 
6515 /// getStackArgumentTokenFactor - Compute a TokenFactor to force all
6516 /// the incoming stack arguments to be loaded from the stack.
6517 SDValue SelectionDAG::getStackArgumentTokenFactor(SDValue Chain) {
6518   SmallVector<SDValue, 8> ArgChains;
6519 
6520   // Include the original chain at the beginning of the list. When this is
6521   // used by target LowerCall hooks, this helps legalize find the
6522   // CALLSEQ_BEGIN node.
6523   ArgChains.push_back(Chain);
6524 
6525   // Add a chain value for each stack argument.
6526   for (SDNode *U : getEntryNode().getNode()->uses())
6527     if (LoadSDNode *L = dyn_cast<LoadSDNode>(U))
6528       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
6529         if (FI->getIndex() < 0)
6530           ArgChains.push_back(SDValue(L, 1));
6531 
6532   // Build a tokenfactor for all the chains.
6533   return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
6534 }
6535 
6536 /// getMemsetValue - Vectorized representation of the memset value
6537 /// operand.
6538 static SDValue getMemsetValue(SDValue Value, EVT VT, SelectionDAG &DAG,
6539                               const SDLoc &dl) {
6540   assert(!Value.isUndef());
6541 
6542   unsigned NumBits = VT.getScalarSizeInBits();
6543   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
6544     assert(C->getAPIntValue().getBitWidth() == 8);
6545     APInt Val = APInt::getSplat(NumBits, C->getAPIntValue());
6546     if (VT.isInteger()) {
6547       bool IsOpaque = VT.getSizeInBits() > 64 ||
6548           !DAG.getTargetLoweringInfo().isLegalStoreImmediate(C->getSExtValue());
6549       return DAG.getConstant(Val, dl, VT, false, IsOpaque);
6550     }
6551     return DAG.getConstantFP(APFloat(DAG.EVTToAPFloatSemantics(VT), Val), dl,
6552                              VT);
6553   }
6554 
6555   assert(Value.getValueType() == MVT::i8 && "memset with non-byte fill value?");
6556   EVT IntVT = VT.getScalarType();
6557   if (!IntVT.isInteger())
6558     IntVT = EVT::getIntegerVT(*DAG.getContext(), IntVT.getSizeInBits());
6559 
6560   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, Value);
6561   if (NumBits > 8) {
6562     // Use a multiplication with 0x010101... to extend the input to the
6563     // required length.
6564     APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01));
6565     Value = DAG.getNode(ISD::MUL, dl, IntVT, Value,
6566                         DAG.getConstant(Magic, dl, IntVT));
6567   }
6568 
6569   if (VT != Value.getValueType() && !VT.isInteger())
6570     Value = DAG.getBitcast(VT.getScalarType(), Value);
6571   if (VT != Value.getValueType())
6572     Value = DAG.getSplatBuildVector(VT, dl, Value);
6573 
6574   return Value;
6575 }
6576 
6577 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
6578 /// used when a memcpy is turned into a memset when the source is a constant
6579 /// string ptr.
6580 static SDValue getMemsetStringVal(EVT VT, const SDLoc &dl, SelectionDAG &DAG,
6581                                   const TargetLowering &TLI,
6582                                   const ConstantDataArraySlice &Slice) {
6583   // Handle vector with all elements zero.
6584   if (Slice.Array == nullptr) {
6585     if (VT.isInteger())
6586       return DAG.getConstant(0, dl, VT);
6587     if (VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128)
6588       return DAG.getConstantFP(0.0, dl, VT);
6589     if (VT.isVector()) {
6590       unsigned NumElts = VT.getVectorNumElements();
6591       MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
6592       return DAG.getNode(ISD::BITCAST, dl, VT,
6593                          DAG.getConstant(0, dl,
6594                                          EVT::getVectorVT(*DAG.getContext(),
6595                                                           EltVT, NumElts)));
6596     }
6597     llvm_unreachable("Expected type!");
6598   }
6599 
6600   assert(!VT.isVector() && "Can't handle vector type here!");
6601   unsigned NumVTBits = VT.getSizeInBits();
6602   unsigned NumVTBytes = NumVTBits / 8;
6603   unsigned NumBytes = std::min(NumVTBytes, unsigned(Slice.Length));
6604 
6605   APInt Val(NumVTBits, 0);
6606   if (DAG.getDataLayout().isLittleEndian()) {
6607     for (unsigned i = 0; i != NumBytes; ++i)
6608       Val |= (uint64_t)(unsigned char)Slice[i] << i*8;
6609   } else {
6610     for (unsigned i = 0; i != NumBytes; ++i)
6611       Val |= (uint64_t)(unsigned char)Slice[i] << (NumVTBytes-i-1)*8;
6612   }
6613 
6614   // If the "cost" of materializing the integer immediate is less than the cost
6615   // of a load, then it is cost effective to turn the load into the immediate.
6616   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
6617   if (TLI.shouldConvertConstantLoadToIntImm(Val, Ty))
6618     return DAG.getConstant(Val, dl, VT);
6619   return SDValue();
6620 }
6621 
6622 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Base, TypeSize Offset,
6623                                            const SDLoc &DL,
6624                                            const SDNodeFlags Flags) {
6625   EVT VT = Base.getValueType();
6626   SDValue Index;
6627 
6628   if (Offset.isScalable())
6629     Index = getVScale(DL, Base.getValueType(),
6630                       APInt(Base.getValueSizeInBits().getFixedSize(),
6631                             Offset.getKnownMinSize()));
6632   else
6633     Index = getConstant(Offset.getFixedSize(), DL, VT);
6634 
6635   return getMemBasePlusOffset(Base, Index, DL, Flags);
6636 }
6637 
6638 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Ptr, SDValue Offset,
6639                                            const SDLoc &DL,
6640                                            const SDNodeFlags Flags) {
6641   assert(Offset.getValueType().isInteger());
6642   EVT BasePtrVT = Ptr.getValueType();
6643   return getNode(ISD::ADD, DL, BasePtrVT, Ptr, Offset, Flags);
6644 }
6645 
6646 /// Returns true if memcpy source is constant data.
6647 static bool isMemSrcFromConstant(SDValue Src, ConstantDataArraySlice &Slice) {
6648   uint64_t SrcDelta = 0;
6649   GlobalAddressSDNode *G = nullptr;
6650   if (Src.getOpcode() == ISD::GlobalAddress)
6651     G = cast<GlobalAddressSDNode>(Src);
6652   else if (Src.getOpcode() == ISD::ADD &&
6653            Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
6654            Src.getOperand(1).getOpcode() == ISD::Constant) {
6655     G = cast<GlobalAddressSDNode>(Src.getOperand(0));
6656     SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue();
6657   }
6658   if (!G)
6659     return false;
6660 
6661   return getConstantDataArrayInfo(G->getGlobal(), Slice, 8,
6662                                   SrcDelta + G->getOffset());
6663 }
6664 
6665 static bool shouldLowerMemFuncForSize(const MachineFunction &MF,
6666                                       SelectionDAG &DAG) {
6667   // On Darwin, -Os means optimize for size without hurting performance, so
6668   // only really optimize for size when -Oz (MinSize) is used.
6669   if (MF.getTarget().getTargetTriple().isOSDarwin())
6670     return MF.getFunction().hasMinSize();
6671   return DAG.shouldOptForSize();
6672 }
6673 
6674 static void chainLoadsAndStoresForMemcpy(SelectionDAG &DAG, const SDLoc &dl,
6675                           SmallVector<SDValue, 32> &OutChains, unsigned From,
6676                           unsigned To, SmallVector<SDValue, 16> &OutLoadChains,
6677                           SmallVector<SDValue, 16> &OutStoreChains) {
6678   assert(OutLoadChains.size() && "Missing loads in memcpy inlining");
6679   assert(OutStoreChains.size() && "Missing stores in memcpy inlining");
6680   SmallVector<SDValue, 16> GluedLoadChains;
6681   for (unsigned i = From; i < To; ++i) {
6682     OutChains.push_back(OutLoadChains[i]);
6683     GluedLoadChains.push_back(OutLoadChains[i]);
6684   }
6685 
6686   // Chain for all loads.
6687   SDValue LoadToken = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6688                                   GluedLoadChains);
6689 
6690   for (unsigned i = From; i < To; ++i) {
6691     StoreSDNode *ST = dyn_cast<StoreSDNode>(OutStoreChains[i]);
6692     SDValue NewStore = DAG.getTruncStore(LoadToken, dl, ST->getValue(),
6693                                   ST->getBasePtr(), ST->getMemoryVT(),
6694                                   ST->getMemOperand());
6695     OutChains.push_back(NewStore);
6696   }
6697 }
6698 
6699 static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
6700                                        SDValue Chain, SDValue Dst, SDValue Src,
6701                                        uint64_t Size, Align Alignment,
6702                                        bool isVol, bool AlwaysInline,
6703                                        MachinePointerInfo DstPtrInfo,
6704                                        MachinePointerInfo SrcPtrInfo,
6705                                        const AAMDNodes &AAInfo) {
6706   // Turn a memcpy of undef to nop.
6707   // FIXME: We need to honor volatile even is Src is undef.
6708   if (Src.isUndef())
6709     return Chain;
6710 
6711   // Expand memcpy to a series of load and store ops if the size operand falls
6712   // below a certain threshold.
6713   // TODO: In the AlwaysInline case, if the size is big then generate a loop
6714   // rather than maybe a humongous number of loads and stores.
6715   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6716   const DataLayout &DL = DAG.getDataLayout();
6717   LLVMContext &C = *DAG.getContext();
6718   std::vector<EVT> MemOps;
6719   bool DstAlignCanChange = false;
6720   MachineFunction &MF = DAG.getMachineFunction();
6721   MachineFrameInfo &MFI = MF.getFrameInfo();
6722   bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
6723   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
6724   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
6725     DstAlignCanChange = true;
6726   MaybeAlign SrcAlign = DAG.InferPtrAlign(Src);
6727   if (!SrcAlign || Alignment > *SrcAlign)
6728     SrcAlign = Alignment;
6729   assert(SrcAlign && "SrcAlign must be set");
6730   ConstantDataArraySlice Slice;
6731   // If marked as volatile, perform a copy even when marked as constant.
6732   bool CopyFromConstant = !isVol && isMemSrcFromConstant(Src, Slice);
6733   bool isZeroConstant = CopyFromConstant && Slice.Array == nullptr;
6734   unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize);
6735   const MemOp Op = isZeroConstant
6736                        ? MemOp::Set(Size, DstAlignCanChange, Alignment,
6737                                     /*IsZeroMemset*/ true, isVol)
6738                        : MemOp::Copy(Size, DstAlignCanChange, Alignment,
6739                                      *SrcAlign, isVol, CopyFromConstant);
6740   if (!TLI.findOptimalMemOpLowering(
6741           MemOps, Limit, Op, DstPtrInfo.getAddrSpace(),
6742           SrcPtrInfo.getAddrSpace(), MF.getFunction().getAttributes()))
6743     return SDValue();
6744 
6745   if (DstAlignCanChange) {
6746     Type *Ty = MemOps[0].getTypeForEVT(C);
6747     Align NewAlign = DL.getABITypeAlign(Ty);
6748 
6749     // Don't promote to an alignment that would require dynamic stack
6750     // realignment.
6751     const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
6752     if (!TRI->hasStackRealignment(MF))
6753       while (NewAlign > Alignment && DL.exceedsNaturalStackAlignment(NewAlign))
6754         NewAlign = NewAlign.previous();
6755 
6756     if (NewAlign > Alignment) {
6757       // Give the stack frame object a larger alignment if needed.
6758       if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
6759         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
6760       Alignment = NewAlign;
6761     }
6762   }
6763 
6764   // Prepare AAInfo for loads/stores after lowering this memcpy.
6765   AAMDNodes NewAAInfo = AAInfo;
6766   NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
6767 
6768   MachineMemOperand::Flags MMOFlags =
6769       isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
6770   SmallVector<SDValue, 16> OutLoadChains;
6771   SmallVector<SDValue, 16> OutStoreChains;
6772   SmallVector<SDValue, 32> OutChains;
6773   unsigned NumMemOps = MemOps.size();
6774   uint64_t SrcOff = 0, DstOff = 0;
6775   for (unsigned i = 0; i != NumMemOps; ++i) {
6776     EVT VT = MemOps[i];
6777     unsigned VTSize = VT.getSizeInBits() / 8;
6778     SDValue Value, Store;
6779 
6780     if (VTSize > Size) {
6781       // Issuing an unaligned load / store pair  that overlaps with the previous
6782       // pair. Adjust the offset accordingly.
6783       assert(i == NumMemOps-1 && i != 0);
6784       SrcOff -= VTSize - Size;
6785       DstOff -= VTSize - Size;
6786     }
6787 
6788     if (CopyFromConstant &&
6789         (isZeroConstant || (VT.isInteger() && !VT.isVector()))) {
6790       // It's unlikely a store of a vector immediate can be done in a single
6791       // instruction. It would require a load from a constantpool first.
6792       // We only handle zero vectors here.
6793       // FIXME: Handle other cases where store of vector immediate is done in
6794       // a single instruction.
6795       ConstantDataArraySlice SubSlice;
6796       if (SrcOff < Slice.Length) {
6797         SubSlice = Slice;
6798         SubSlice.move(SrcOff);
6799       } else {
6800         // This is an out-of-bounds access and hence UB. Pretend we read zero.
6801         SubSlice.Array = nullptr;
6802         SubSlice.Offset = 0;
6803         SubSlice.Length = VTSize;
6804       }
6805       Value = getMemsetStringVal(VT, dl, DAG, TLI, SubSlice);
6806       if (Value.getNode()) {
6807         Store = DAG.getStore(
6808             Chain, dl, Value,
6809             DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6810             DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo);
6811         OutChains.push_back(Store);
6812       }
6813     }
6814 
6815     if (!Store.getNode()) {
6816       // The type might not be legal for the target.  This should only happen
6817       // if the type is smaller than a legal type, as on PPC, so the right
6818       // thing to do is generate a LoadExt/StoreTrunc pair.  These simplify
6819       // to Load/Store if NVT==VT.
6820       // FIXME does the case above also need this?
6821       EVT NVT = TLI.getTypeToTransformTo(C, VT);
6822       assert(NVT.bitsGE(VT));
6823 
6824       bool isDereferenceable =
6825         SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
6826       MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
6827       if (isDereferenceable)
6828         SrcMMOFlags |= MachineMemOperand::MODereferenceable;
6829 
6830       Value = DAG.getExtLoad(
6831           ISD::EXTLOAD, dl, NVT, Chain,
6832           DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl),
6833           SrcPtrInfo.getWithOffset(SrcOff), VT,
6834           commonAlignment(*SrcAlign, SrcOff), SrcMMOFlags, NewAAInfo);
6835       OutLoadChains.push_back(Value.getValue(1));
6836 
6837       Store = DAG.getTruncStore(
6838           Chain, dl, Value,
6839           DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6840           DstPtrInfo.getWithOffset(DstOff), VT, Alignment, MMOFlags, NewAAInfo);
6841       OutStoreChains.push_back(Store);
6842     }
6843     SrcOff += VTSize;
6844     DstOff += VTSize;
6845     Size -= VTSize;
6846   }
6847 
6848   unsigned GluedLdStLimit = MaxLdStGlue == 0 ?
6849                                 TLI.getMaxGluedStoresPerMemcpy() : MaxLdStGlue;
6850   unsigned NumLdStInMemcpy = OutStoreChains.size();
6851 
6852   if (NumLdStInMemcpy) {
6853     // It may be that memcpy might be converted to memset if it's memcpy
6854     // of constants. In such a case, we won't have loads and stores, but
6855     // just stores. In the absence of loads, there is nothing to gang up.
6856     if ((GluedLdStLimit <= 1) || !EnableMemCpyDAGOpt) {
6857       // If target does not care, just leave as it.
6858       for (unsigned i = 0; i < NumLdStInMemcpy; ++i) {
6859         OutChains.push_back(OutLoadChains[i]);
6860         OutChains.push_back(OutStoreChains[i]);
6861       }
6862     } else {
6863       // Ld/St less than/equal limit set by target.
6864       if (NumLdStInMemcpy <= GluedLdStLimit) {
6865           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
6866                                         NumLdStInMemcpy, OutLoadChains,
6867                                         OutStoreChains);
6868       } else {
6869         unsigned NumberLdChain =  NumLdStInMemcpy / GluedLdStLimit;
6870         unsigned RemainingLdStInMemcpy = NumLdStInMemcpy % GluedLdStLimit;
6871         unsigned GlueIter = 0;
6872 
6873         for (unsigned cnt = 0; cnt < NumberLdChain; ++cnt) {
6874           unsigned IndexFrom = NumLdStInMemcpy - GlueIter - GluedLdStLimit;
6875           unsigned IndexTo   = NumLdStInMemcpy - GlueIter;
6876 
6877           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, IndexFrom, IndexTo,
6878                                        OutLoadChains, OutStoreChains);
6879           GlueIter += GluedLdStLimit;
6880         }
6881 
6882         // Residual ld/st.
6883         if (RemainingLdStInMemcpy) {
6884           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
6885                                         RemainingLdStInMemcpy, OutLoadChains,
6886                                         OutStoreChains);
6887         }
6888       }
6889     }
6890   }
6891   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
6892 }
6893 
6894 static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
6895                                         SDValue Chain, SDValue Dst, SDValue Src,
6896                                         uint64_t Size, Align Alignment,
6897                                         bool isVol, bool AlwaysInline,
6898                                         MachinePointerInfo DstPtrInfo,
6899                                         MachinePointerInfo SrcPtrInfo,
6900                                         const AAMDNodes &AAInfo) {
6901   // Turn a memmove of undef to nop.
6902   // FIXME: We need to honor volatile even is Src is undef.
6903   if (Src.isUndef())
6904     return Chain;
6905 
6906   // Expand memmove to a series of load and store ops if the size operand falls
6907   // below a certain threshold.
6908   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6909   const DataLayout &DL = DAG.getDataLayout();
6910   LLVMContext &C = *DAG.getContext();
6911   std::vector<EVT> MemOps;
6912   bool DstAlignCanChange = false;
6913   MachineFunction &MF = DAG.getMachineFunction();
6914   MachineFrameInfo &MFI = MF.getFrameInfo();
6915   bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
6916   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
6917   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
6918     DstAlignCanChange = true;
6919   MaybeAlign SrcAlign = DAG.InferPtrAlign(Src);
6920   if (!SrcAlign || Alignment > *SrcAlign)
6921     SrcAlign = Alignment;
6922   assert(SrcAlign && "SrcAlign must be set");
6923   unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize);
6924   if (!TLI.findOptimalMemOpLowering(
6925           MemOps, Limit,
6926           MemOp::Copy(Size, DstAlignCanChange, Alignment, *SrcAlign,
6927                       /*IsVolatile*/ true),
6928           DstPtrInfo.getAddrSpace(), SrcPtrInfo.getAddrSpace(),
6929           MF.getFunction().getAttributes()))
6930     return SDValue();
6931 
6932   if (DstAlignCanChange) {
6933     Type *Ty = MemOps[0].getTypeForEVT(C);
6934     Align NewAlign = DL.getABITypeAlign(Ty);
6935     if (NewAlign > Alignment) {
6936       // Give the stack frame object a larger alignment if needed.
6937       if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
6938         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
6939       Alignment = NewAlign;
6940     }
6941   }
6942 
6943   // Prepare AAInfo for loads/stores after lowering this memmove.
6944   AAMDNodes NewAAInfo = AAInfo;
6945   NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
6946 
6947   MachineMemOperand::Flags MMOFlags =
6948       isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
6949   uint64_t SrcOff = 0, DstOff = 0;
6950   SmallVector<SDValue, 8> LoadValues;
6951   SmallVector<SDValue, 8> LoadChains;
6952   SmallVector<SDValue, 8> OutChains;
6953   unsigned NumMemOps = MemOps.size();
6954   for (unsigned i = 0; i < NumMemOps; i++) {
6955     EVT VT = MemOps[i];
6956     unsigned VTSize = VT.getSizeInBits() / 8;
6957     SDValue Value;
6958 
6959     bool isDereferenceable =
6960       SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
6961     MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
6962     if (isDereferenceable)
6963       SrcMMOFlags |= MachineMemOperand::MODereferenceable;
6964 
6965     Value = DAG.getLoad(
6966         VT, dl, Chain,
6967         DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl),
6968         SrcPtrInfo.getWithOffset(SrcOff), *SrcAlign, SrcMMOFlags, NewAAInfo);
6969     LoadValues.push_back(Value);
6970     LoadChains.push_back(Value.getValue(1));
6971     SrcOff += VTSize;
6972   }
6973   Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
6974   OutChains.clear();
6975   for (unsigned i = 0; i < NumMemOps; i++) {
6976     EVT VT = MemOps[i];
6977     unsigned VTSize = VT.getSizeInBits() / 8;
6978     SDValue Store;
6979 
6980     Store = DAG.getStore(
6981         Chain, dl, LoadValues[i],
6982         DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6983         DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo);
6984     OutChains.push_back(Store);
6985     DstOff += VTSize;
6986   }
6987 
6988   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
6989 }
6990 
6991 /// Lower the call to 'memset' intrinsic function into a series of store
6992 /// operations.
6993 ///
6994 /// \param DAG Selection DAG where lowered code is placed.
6995 /// \param dl Link to corresponding IR location.
6996 /// \param Chain Control flow dependency.
6997 /// \param Dst Pointer to destination memory location.
6998 /// \param Src Value of byte to write into the memory.
6999 /// \param Size Number of bytes to write.
7000 /// \param Alignment Alignment of the destination in bytes.
7001 /// \param isVol True if destination is volatile.
7002 /// \param AlwaysInline Makes sure no function call is generated.
7003 /// \param DstPtrInfo IR information on the memory pointer.
7004 /// \returns New head in the control flow, if lowering was successful, empty
7005 /// SDValue otherwise.
7006 ///
7007 /// The function tries to replace 'llvm.memset' intrinsic with several store
7008 /// operations and value calculation code. This is usually profitable for small
7009 /// memory size or when the semantic requires inlining.
7010 static SDValue getMemsetStores(SelectionDAG &DAG, const SDLoc &dl,
7011                                SDValue Chain, SDValue Dst, SDValue Src,
7012                                uint64_t Size, Align Alignment, bool isVol,
7013                                bool AlwaysInline, MachinePointerInfo DstPtrInfo,
7014                                const AAMDNodes &AAInfo) {
7015   // Turn a memset of undef to nop.
7016   // FIXME: We need to honor volatile even is Src is undef.
7017   if (Src.isUndef())
7018     return Chain;
7019 
7020   // Expand memset to a series of load/store ops if the size operand
7021   // falls below a certain threshold.
7022   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7023   std::vector<EVT> MemOps;
7024   bool DstAlignCanChange = false;
7025   MachineFunction &MF = DAG.getMachineFunction();
7026   MachineFrameInfo &MFI = MF.getFrameInfo();
7027   bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
7028   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
7029   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
7030     DstAlignCanChange = true;
7031   bool IsZeroVal =
7032       isa<ConstantSDNode>(Src) && cast<ConstantSDNode>(Src)->isZero();
7033   unsigned Limit = AlwaysInline ? ~0 : TLI.getMaxStoresPerMemset(OptSize);
7034 
7035   if (!TLI.findOptimalMemOpLowering(
7036           MemOps, Limit,
7037           MemOp::Set(Size, DstAlignCanChange, Alignment, IsZeroVal, isVol),
7038           DstPtrInfo.getAddrSpace(), ~0u, MF.getFunction().getAttributes()))
7039     return SDValue();
7040 
7041   if (DstAlignCanChange) {
7042     Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
7043     Align NewAlign = DAG.getDataLayout().getABITypeAlign(Ty);
7044     if (NewAlign > Alignment) {
7045       // Give the stack frame object a larger alignment if needed.
7046       if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
7047         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
7048       Alignment = NewAlign;
7049     }
7050   }
7051 
7052   SmallVector<SDValue, 8> OutChains;
7053   uint64_t DstOff = 0;
7054   unsigned NumMemOps = MemOps.size();
7055 
7056   // Find the largest store and generate the bit pattern for it.
7057   EVT LargestVT = MemOps[0];
7058   for (unsigned i = 1; i < NumMemOps; i++)
7059     if (MemOps[i].bitsGT(LargestVT))
7060       LargestVT = MemOps[i];
7061   SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl);
7062 
7063   // Prepare AAInfo for loads/stores after lowering this memset.
7064   AAMDNodes NewAAInfo = AAInfo;
7065   NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
7066 
7067   for (unsigned i = 0; i < NumMemOps; i++) {
7068     EVT VT = MemOps[i];
7069     unsigned VTSize = VT.getSizeInBits() / 8;
7070     if (VTSize > Size) {
7071       // Issuing an unaligned load / store pair  that overlaps with the previous
7072       // pair. Adjust the offset accordingly.
7073       assert(i == NumMemOps-1 && i != 0);
7074       DstOff -= VTSize - Size;
7075     }
7076 
7077     // If this store is smaller than the largest store see whether we can get
7078     // the smaller value for free with a truncate.
7079     SDValue Value = MemSetValue;
7080     if (VT.bitsLT(LargestVT)) {
7081       if (!LargestVT.isVector() && !VT.isVector() &&
7082           TLI.isTruncateFree(LargestVT, VT))
7083         Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue);
7084       else
7085         Value = getMemsetValue(Src, VT, DAG, dl);
7086     }
7087     assert(Value.getValueType() == VT && "Value with wrong type.");
7088     SDValue Store = DAG.getStore(
7089         Chain, dl, Value,
7090         DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
7091         DstPtrInfo.getWithOffset(DstOff), Alignment,
7092         isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone,
7093         NewAAInfo);
7094     OutChains.push_back(Store);
7095     DstOff += VT.getSizeInBits() / 8;
7096     Size -= VTSize;
7097   }
7098 
7099   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
7100 }
7101 
7102 static void checkAddrSpaceIsValidForLibcall(const TargetLowering *TLI,
7103                                             unsigned AS) {
7104   // Lowering memcpy / memset / memmove intrinsics to calls is only valid if all
7105   // pointer operands can be losslessly bitcasted to pointers of address space 0
7106   if (AS != 0 && !TLI->getTargetMachine().isNoopAddrSpaceCast(AS, 0)) {
7107     report_fatal_error("cannot lower memory intrinsic in address space " +
7108                        Twine(AS));
7109   }
7110 }
7111 
7112 SDValue SelectionDAG::getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst,
7113                                 SDValue Src, SDValue Size, Align Alignment,
7114                                 bool isVol, bool AlwaysInline, bool isTailCall,
7115                                 MachinePointerInfo DstPtrInfo,
7116                                 MachinePointerInfo SrcPtrInfo,
7117                                 const AAMDNodes &AAInfo) {
7118   // Check to see if we should lower the memcpy to loads and stores first.
7119   // For cases within the target-specified limits, this is the best choice.
7120   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
7121   if (ConstantSize) {
7122     // Memcpy with size zero? Just return the original chain.
7123     if (ConstantSize->isZero())
7124       return Chain;
7125 
7126     SDValue Result = getMemcpyLoadsAndStores(
7127         *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment,
7128         isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo);
7129     if (Result.getNode())
7130       return Result;
7131   }
7132 
7133   // Then check to see if we should lower the memcpy with target-specific
7134   // code. If the target chooses to do this, this is the next best.
7135   if (TSI) {
7136     SDValue Result = TSI->EmitTargetCodeForMemcpy(
7137         *this, dl, Chain, Dst, Src, Size, Alignment, isVol, AlwaysInline,
7138         DstPtrInfo, SrcPtrInfo);
7139     if (Result.getNode())
7140       return Result;
7141   }
7142 
7143   // If we really need inline code and the target declined to provide it,
7144   // use a (potentially long) sequence of loads and stores.
7145   if (AlwaysInline) {
7146     assert(ConstantSize && "AlwaysInline requires a constant size!");
7147     return getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
7148                                    ConstantSize->getZExtValue(), Alignment,
7149                                    isVol, true, DstPtrInfo, SrcPtrInfo, AAInfo);
7150   }
7151 
7152   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
7153   checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
7154 
7155   // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc
7156   // memcpy is not guaranteed to be safe. libc memcpys aren't required to
7157   // respect volatile, so they may do things like read or write memory
7158   // beyond the given memory regions. But fixing this isn't easy, and most
7159   // people don't care.
7160 
7161   // Emit a library call.
7162   TargetLowering::ArgListTy Args;
7163   TargetLowering::ArgListEntry Entry;
7164   Entry.Ty = Type::getInt8PtrTy(*getContext());
7165   Entry.Node = Dst; Args.push_back(Entry);
7166   Entry.Node = Src; Args.push_back(Entry);
7167 
7168   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7169   Entry.Node = Size; Args.push_back(Entry);
7170   // FIXME: pass in SDLoc
7171   TargetLowering::CallLoweringInfo CLI(*this);
7172   CLI.setDebugLoc(dl)
7173       .setChain(Chain)
7174       .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMCPY),
7175                     Dst.getValueType().getTypeForEVT(*getContext()),
7176                     getExternalSymbol(TLI->getLibcallName(RTLIB::MEMCPY),
7177                                       TLI->getPointerTy(getDataLayout())),
7178                     std::move(Args))
7179       .setDiscardResult()
7180       .setTailCall(isTailCall);
7181 
7182   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
7183   return CallResult.second;
7184 }
7185 
7186 SDValue SelectionDAG::getAtomicMemcpy(SDValue Chain, const SDLoc &dl,
7187                                       SDValue Dst, SDValue Src, SDValue Size,
7188                                       Type *SizeTy, unsigned ElemSz,
7189                                       bool isTailCall,
7190                                       MachinePointerInfo DstPtrInfo,
7191                                       MachinePointerInfo SrcPtrInfo) {
7192   // Emit a library call.
7193   TargetLowering::ArgListTy Args;
7194   TargetLowering::ArgListEntry Entry;
7195   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7196   Entry.Node = Dst;
7197   Args.push_back(Entry);
7198 
7199   Entry.Node = Src;
7200   Args.push_back(Entry);
7201 
7202   Entry.Ty = SizeTy;
7203   Entry.Node = Size;
7204   Args.push_back(Entry);
7205 
7206   RTLIB::Libcall LibraryCall =
7207       RTLIB::getMEMCPY_ELEMENT_UNORDERED_ATOMIC(ElemSz);
7208   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
7209     report_fatal_error("Unsupported element size");
7210 
7211   TargetLowering::CallLoweringInfo CLI(*this);
7212   CLI.setDebugLoc(dl)
7213       .setChain(Chain)
7214       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
7215                     Type::getVoidTy(*getContext()),
7216                     getExternalSymbol(TLI->getLibcallName(LibraryCall),
7217                                       TLI->getPointerTy(getDataLayout())),
7218                     std::move(Args))
7219       .setDiscardResult()
7220       .setTailCall(isTailCall);
7221 
7222   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
7223   return CallResult.second;
7224 }
7225 
7226 SDValue SelectionDAG::getMemmove(SDValue Chain, const SDLoc &dl, SDValue Dst,
7227                                  SDValue Src, SDValue Size, Align Alignment,
7228                                  bool isVol, bool isTailCall,
7229                                  MachinePointerInfo DstPtrInfo,
7230                                  MachinePointerInfo SrcPtrInfo,
7231                                  const AAMDNodes &AAInfo) {
7232   // Check to see if we should lower the memmove to loads and stores first.
7233   // For cases within the target-specified limits, this is the best choice.
7234   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
7235   if (ConstantSize) {
7236     // Memmove with size zero? Just return the original chain.
7237     if (ConstantSize->isZero())
7238       return Chain;
7239 
7240     SDValue Result = getMemmoveLoadsAndStores(
7241         *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment,
7242         isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo);
7243     if (Result.getNode())
7244       return Result;
7245   }
7246 
7247   // Then check to see if we should lower the memmove with target-specific
7248   // code. If the target chooses to do this, this is the next best.
7249   if (TSI) {
7250     SDValue Result =
7251         TSI->EmitTargetCodeForMemmove(*this, dl, Chain, Dst, Src, Size,
7252                                       Alignment, isVol, DstPtrInfo, SrcPtrInfo);
7253     if (Result.getNode())
7254       return Result;
7255   }
7256 
7257   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
7258   checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
7259 
7260   // FIXME: If the memmove is volatile, lowering it to plain libc memmove may
7261   // not be safe.  See memcpy above for more details.
7262 
7263   // Emit a library call.
7264   TargetLowering::ArgListTy Args;
7265   TargetLowering::ArgListEntry Entry;
7266   Entry.Ty = Type::getInt8PtrTy(*getContext());
7267   Entry.Node = Dst; Args.push_back(Entry);
7268   Entry.Node = Src; Args.push_back(Entry);
7269 
7270   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7271   Entry.Node = Size; Args.push_back(Entry);
7272   // FIXME:  pass in SDLoc
7273   TargetLowering::CallLoweringInfo CLI(*this);
7274   CLI.setDebugLoc(dl)
7275       .setChain(Chain)
7276       .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMMOVE),
7277                     Dst.getValueType().getTypeForEVT(*getContext()),
7278                     getExternalSymbol(TLI->getLibcallName(RTLIB::MEMMOVE),
7279                                       TLI->getPointerTy(getDataLayout())),
7280                     std::move(Args))
7281       .setDiscardResult()
7282       .setTailCall(isTailCall);
7283 
7284   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
7285   return CallResult.second;
7286 }
7287 
7288 SDValue SelectionDAG::getAtomicMemmove(SDValue Chain, const SDLoc &dl,
7289                                        SDValue Dst, SDValue Src, SDValue Size,
7290                                        Type *SizeTy, unsigned ElemSz,
7291                                        bool isTailCall,
7292                                        MachinePointerInfo DstPtrInfo,
7293                                        MachinePointerInfo SrcPtrInfo) {
7294   // Emit a library call.
7295   TargetLowering::ArgListTy Args;
7296   TargetLowering::ArgListEntry Entry;
7297   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7298   Entry.Node = Dst;
7299   Args.push_back(Entry);
7300 
7301   Entry.Node = Src;
7302   Args.push_back(Entry);
7303 
7304   Entry.Ty = SizeTy;
7305   Entry.Node = Size;
7306   Args.push_back(Entry);
7307 
7308   RTLIB::Libcall LibraryCall =
7309       RTLIB::getMEMMOVE_ELEMENT_UNORDERED_ATOMIC(ElemSz);
7310   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
7311     report_fatal_error("Unsupported element size");
7312 
7313   TargetLowering::CallLoweringInfo CLI(*this);
7314   CLI.setDebugLoc(dl)
7315       .setChain(Chain)
7316       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
7317                     Type::getVoidTy(*getContext()),
7318                     getExternalSymbol(TLI->getLibcallName(LibraryCall),
7319                                       TLI->getPointerTy(getDataLayout())),
7320                     std::move(Args))
7321       .setDiscardResult()
7322       .setTailCall(isTailCall);
7323 
7324   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
7325   return CallResult.second;
7326 }
7327 
7328 SDValue SelectionDAG::getMemset(SDValue Chain, const SDLoc &dl, SDValue Dst,
7329                                 SDValue Src, SDValue Size, Align Alignment,
7330                                 bool isVol, bool AlwaysInline, bool isTailCall,
7331                                 MachinePointerInfo DstPtrInfo,
7332                                 const AAMDNodes &AAInfo) {
7333   // Check to see if we should lower the memset to stores first.
7334   // For cases within the target-specified limits, this is the best choice.
7335   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
7336   if (ConstantSize) {
7337     // Memset with size zero? Just return the original chain.
7338     if (ConstantSize->isZero())
7339       return Chain;
7340 
7341     SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src,
7342                                      ConstantSize->getZExtValue(), Alignment,
7343                                      isVol, false, DstPtrInfo, AAInfo);
7344 
7345     if (Result.getNode())
7346       return Result;
7347   }
7348 
7349   // Then check to see if we should lower the memset with target-specific
7350   // code. If the target chooses to do this, this is the next best.
7351   if (TSI) {
7352     SDValue Result = TSI->EmitTargetCodeForMemset(
7353         *this, dl, Chain, Dst, Src, Size, Alignment, isVol, AlwaysInline, DstPtrInfo);
7354     if (Result.getNode())
7355       return Result;
7356   }
7357 
7358   // If we really need inline code and the target declined to provide it,
7359   // use a (potentially long) sequence of loads and stores.
7360   if (AlwaysInline) {
7361     assert(ConstantSize && "AlwaysInline requires a constant size!");
7362     SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src,
7363                                      ConstantSize->getZExtValue(), Alignment,
7364                                      isVol, true, DstPtrInfo, AAInfo);
7365     assert(Result &&
7366            "getMemsetStores must return a valid sequence when AlwaysInline");
7367     return Result;
7368   }
7369 
7370   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
7371 
7372   // Emit a library call.
7373   auto &Ctx = *getContext();
7374   const auto& DL = getDataLayout();
7375 
7376   TargetLowering::CallLoweringInfo CLI(*this);
7377   // FIXME: pass in SDLoc
7378   CLI.setDebugLoc(dl).setChain(Chain);
7379 
7380   ConstantSDNode *ConstantSrc = dyn_cast<ConstantSDNode>(Src);
7381   const bool SrcIsZero = ConstantSrc && ConstantSrc->isZero();
7382   const char *BzeroName = getTargetLoweringInfo().getLibcallName(RTLIB::BZERO);
7383 
7384   // Helper function to create an Entry from Node and Type.
7385   const auto CreateEntry = [](SDValue Node, Type *Ty) {
7386     TargetLowering::ArgListEntry Entry;
7387     Entry.Node = Node;
7388     Entry.Ty = Ty;
7389     return Entry;
7390   };
7391 
7392   // If zeroing out and bzero is present, use it.
7393   if (SrcIsZero && BzeroName) {
7394     TargetLowering::ArgListTy Args;
7395     Args.push_back(CreateEntry(Dst, Type::getInt8PtrTy(Ctx)));
7396     Args.push_back(CreateEntry(Size, DL.getIntPtrType(Ctx)));
7397     CLI.setLibCallee(
7398         TLI->getLibcallCallingConv(RTLIB::BZERO), Type::getVoidTy(Ctx),
7399         getExternalSymbol(BzeroName, TLI->getPointerTy(DL)), std::move(Args));
7400   } else {
7401     TargetLowering::ArgListTy Args;
7402     Args.push_back(CreateEntry(Dst, Type::getInt8PtrTy(Ctx)));
7403     Args.push_back(CreateEntry(Src, Src.getValueType().getTypeForEVT(Ctx)));
7404     Args.push_back(CreateEntry(Size, DL.getIntPtrType(Ctx)));
7405     CLI.setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMSET),
7406                      Dst.getValueType().getTypeForEVT(Ctx),
7407                      getExternalSymbol(TLI->getLibcallName(RTLIB::MEMSET),
7408                                        TLI->getPointerTy(DL)),
7409                      std::move(Args));
7410   }
7411 
7412   CLI.setDiscardResult().setTailCall(isTailCall);
7413 
7414   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
7415   return CallResult.second;
7416 }
7417 
7418 SDValue SelectionDAG::getAtomicMemset(SDValue Chain, const SDLoc &dl,
7419                                       SDValue Dst, SDValue Value, SDValue Size,
7420                                       Type *SizeTy, unsigned ElemSz,
7421                                       bool isTailCall,
7422                                       MachinePointerInfo DstPtrInfo) {
7423   // Emit a library call.
7424   TargetLowering::ArgListTy Args;
7425   TargetLowering::ArgListEntry Entry;
7426   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7427   Entry.Node = Dst;
7428   Args.push_back(Entry);
7429 
7430   Entry.Ty = Type::getInt8Ty(*getContext());
7431   Entry.Node = Value;
7432   Args.push_back(Entry);
7433 
7434   Entry.Ty = SizeTy;
7435   Entry.Node = Size;
7436   Args.push_back(Entry);
7437 
7438   RTLIB::Libcall LibraryCall =
7439       RTLIB::getMEMSET_ELEMENT_UNORDERED_ATOMIC(ElemSz);
7440   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
7441     report_fatal_error("Unsupported element size");
7442 
7443   TargetLowering::CallLoweringInfo CLI(*this);
7444   CLI.setDebugLoc(dl)
7445       .setChain(Chain)
7446       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
7447                     Type::getVoidTy(*getContext()),
7448                     getExternalSymbol(TLI->getLibcallName(LibraryCall),
7449                                       TLI->getPointerTy(getDataLayout())),
7450                     std::move(Args))
7451       .setDiscardResult()
7452       .setTailCall(isTailCall);
7453 
7454   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
7455   return CallResult.second;
7456 }
7457 
7458 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
7459                                 SDVTList VTList, ArrayRef<SDValue> Ops,
7460                                 MachineMemOperand *MMO) {
7461   FoldingSetNodeID ID;
7462   ID.AddInteger(MemVT.getRawBits());
7463   AddNodeIDNode(ID, Opcode, VTList, Ops);
7464   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7465   ID.AddInteger(MMO->getFlags());
7466   void* IP = nullptr;
7467   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7468     cast<AtomicSDNode>(E)->refineAlignment(MMO);
7469     return SDValue(E, 0);
7470   }
7471 
7472   auto *N = newSDNode<AtomicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
7473                                     VTList, MemVT, MMO);
7474   createOperands(N, Ops);
7475 
7476   CSEMap.InsertNode(N, IP);
7477   InsertNode(N);
7478   return SDValue(N, 0);
7479 }
7480 
7481 SDValue SelectionDAG::getAtomicCmpSwap(unsigned Opcode, const SDLoc &dl,
7482                                        EVT MemVT, SDVTList VTs, SDValue Chain,
7483                                        SDValue Ptr, SDValue Cmp, SDValue Swp,
7484                                        MachineMemOperand *MMO) {
7485   assert(Opcode == ISD::ATOMIC_CMP_SWAP ||
7486          Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
7487   assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
7488 
7489   SDValue Ops[] = {Chain, Ptr, Cmp, Swp};
7490   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
7491 }
7492 
7493 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
7494                                 SDValue Chain, SDValue Ptr, SDValue Val,
7495                                 MachineMemOperand *MMO) {
7496   assert((Opcode == ISD::ATOMIC_LOAD_ADD ||
7497           Opcode == ISD::ATOMIC_LOAD_SUB ||
7498           Opcode == ISD::ATOMIC_LOAD_AND ||
7499           Opcode == ISD::ATOMIC_LOAD_CLR ||
7500           Opcode == ISD::ATOMIC_LOAD_OR ||
7501           Opcode == ISD::ATOMIC_LOAD_XOR ||
7502           Opcode == ISD::ATOMIC_LOAD_NAND ||
7503           Opcode == ISD::ATOMIC_LOAD_MIN ||
7504           Opcode == ISD::ATOMIC_LOAD_MAX ||
7505           Opcode == ISD::ATOMIC_LOAD_UMIN ||
7506           Opcode == ISD::ATOMIC_LOAD_UMAX ||
7507           Opcode == ISD::ATOMIC_LOAD_FADD ||
7508           Opcode == ISD::ATOMIC_LOAD_FSUB ||
7509           Opcode == ISD::ATOMIC_SWAP ||
7510           Opcode == ISD::ATOMIC_STORE) &&
7511          "Invalid Atomic Op");
7512 
7513   EVT VT = Val.getValueType();
7514 
7515   SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) :
7516                                                getVTList(VT, MVT::Other);
7517   SDValue Ops[] = {Chain, Ptr, Val};
7518   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
7519 }
7520 
7521 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
7522                                 EVT VT, SDValue Chain, SDValue Ptr,
7523                                 MachineMemOperand *MMO) {
7524   assert(Opcode == ISD::ATOMIC_LOAD && "Invalid Atomic Op");
7525 
7526   SDVTList VTs = getVTList(VT, MVT::Other);
7527   SDValue Ops[] = {Chain, Ptr};
7528   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
7529 }
7530 
7531 /// getMergeValues - Create a MERGE_VALUES node from the given operands.
7532 SDValue SelectionDAG::getMergeValues(ArrayRef<SDValue> Ops, const SDLoc &dl) {
7533   if (Ops.size() == 1)
7534     return Ops[0];
7535 
7536   SmallVector<EVT, 4> VTs;
7537   VTs.reserve(Ops.size());
7538   for (const SDValue &Op : Ops)
7539     VTs.push_back(Op.getValueType());
7540   return getNode(ISD::MERGE_VALUES, dl, getVTList(VTs), Ops);
7541 }
7542 
7543 SDValue SelectionDAG::getMemIntrinsicNode(
7544     unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef<SDValue> Ops,
7545     EVT MemVT, MachinePointerInfo PtrInfo, Align Alignment,
7546     MachineMemOperand::Flags Flags, uint64_t Size, const AAMDNodes &AAInfo) {
7547   if (!Size && MemVT.isScalableVector())
7548     Size = MemoryLocation::UnknownSize;
7549   else if (!Size)
7550     Size = MemVT.getStoreSize();
7551 
7552   MachineFunction &MF = getMachineFunction();
7553   MachineMemOperand *MMO =
7554       MF.getMachineMemOperand(PtrInfo, Flags, Size, Alignment, AAInfo);
7555 
7556   return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, MMO);
7557 }
7558 
7559 SDValue SelectionDAG::getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl,
7560                                           SDVTList VTList,
7561                                           ArrayRef<SDValue> Ops, EVT MemVT,
7562                                           MachineMemOperand *MMO) {
7563   assert((Opcode == ISD::INTRINSIC_VOID ||
7564           Opcode == ISD::INTRINSIC_W_CHAIN ||
7565           Opcode == ISD::PREFETCH ||
7566           ((int)Opcode <= std::numeric_limits<int>::max() &&
7567            (int)Opcode >= ISD::FIRST_TARGET_MEMORY_OPCODE)) &&
7568          "Opcode is not a memory-accessing opcode!");
7569 
7570   // Memoize the node unless it returns a flag.
7571   MemIntrinsicSDNode *N;
7572   if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
7573     FoldingSetNodeID ID;
7574     AddNodeIDNode(ID, Opcode, VTList, Ops);
7575     ID.AddInteger(getSyntheticNodeSubclassData<MemIntrinsicSDNode>(
7576         Opcode, dl.getIROrder(), VTList, MemVT, MMO));
7577     ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7578     ID.AddInteger(MMO->getFlags());
7579     void *IP = nullptr;
7580     if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7581       cast<MemIntrinsicSDNode>(E)->refineAlignment(MMO);
7582       return SDValue(E, 0);
7583     }
7584 
7585     N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
7586                                       VTList, MemVT, MMO);
7587     createOperands(N, Ops);
7588 
7589   CSEMap.InsertNode(N, IP);
7590   } else {
7591     N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
7592                                       VTList, MemVT, MMO);
7593     createOperands(N, Ops);
7594   }
7595   InsertNode(N);
7596   SDValue V(N, 0);
7597   NewSDValueDbgMsg(V, "Creating new node: ", this);
7598   return V;
7599 }
7600 
7601 SDValue SelectionDAG::getLifetimeNode(bool IsStart, const SDLoc &dl,
7602                                       SDValue Chain, int FrameIndex,
7603                                       int64_t Size, int64_t Offset) {
7604   const unsigned Opcode = IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END;
7605   const auto VTs = getVTList(MVT::Other);
7606   SDValue Ops[2] = {
7607       Chain,
7608       getFrameIndex(FrameIndex,
7609                     getTargetLoweringInfo().getFrameIndexTy(getDataLayout()),
7610                     true)};
7611 
7612   FoldingSetNodeID ID;
7613   AddNodeIDNode(ID, Opcode, VTs, Ops);
7614   ID.AddInteger(FrameIndex);
7615   ID.AddInteger(Size);
7616   ID.AddInteger(Offset);
7617   void *IP = nullptr;
7618   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
7619     return SDValue(E, 0);
7620 
7621   LifetimeSDNode *N = newSDNode<LifetimeSDNode>(
7622       Opcode, dl.getIROrder(), dl.getDebugLoc(), VTs, Size, Offset);
7623   createOperands(N, Ops);
7624   CSEMap.InsertNode(N, IP);
7625   InsertNode(N);
7626   SDValue V(N, 0);
7627   NewSDValueDbgMsg(V, "Creating new node: ", this);
7628   return V;
7629 }
7630 
7631 SDValue SelectionDAG::getPseudoProbeNode(const SDLoc &Dl, SDValue Chain,
7632                                          uint64_t Guid, uint64_t Index,
7633                                          uint32_t Attr) {
7634   const unsigned Opcode = ISD::PSEUDO_PROBE;
7635   const auto VTs = getVTList(MVT::Other);
7636   SDValue Ops[] = {Chain};
7637   FoldingSetNodeID ID;
7638   AddNodeIDNode(ID, Opcode, VTs, Ops);
7639   ID.AddInteger(Guid);
7640   ID.AddInteger(Index);
7641   void *IP = nullptr;
7642   if (SDNode *E = FindNodeOrInsertPos(ID, Dl, IP))
7643     return SDValue(E, 0);
7644 
7645   auto *N = newSDNode<PseudoProbeSDNode>(
7646       Opcode, Dl.getIROrder(), Dl.getDebugLoc(), VTs, Guid, Index, Attr);
7647   createOperands(N, Ops);
7648   CSEMap.InsertNode(N, IP);
7649   InsertNode(N);
7650   SDValue V(N, 0);
7651   NewSDValueDbgMsg(V, "Creating new node: ", this);
7652   return V;
7653 }
7654 
7655 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
7656 /// MachinePointerInfo record from it.  This is particularly useful because the
7657 /// code generator has many cases where it doesn't bother passing in a
7658 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
7659 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info,
7660                                            SelectionDAG &DAG, SDValue Ptr,
7661                                            int64_t Offset = 0) {
7662   // If this is FI+Offset, we can model it.
7663   if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr))
7664     return MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
7665                                              FI->getIndex(), Offset);
7666 
7667   // If this is (FI+Offset1)+Offset2, we can model it.
7668   if (Ptr.getOpcode() != ISD::ADD ||
7669       !isa<ConstantSDNode>(Ptr.getOperand(1)) ||
7670       !isa<FrameIndexSDNode>(Ptr.getOperand(0)))
7671     return Info;
7672 
7673   int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
7674   return MachinePointerInfo::getFixedStack(
7675       DAG.getMachineFunction(), FI,
7676       Offset + cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue());
7677 }
7678 
7679 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
7680 /// MachinePointerInfo record from it.  This is particularly useful because the
7681 /// code generator has many cases where it doesn't bother passing in a
7682 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
7683 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info,
7684                                            SelectionDAG &DAG, SDValue Ptr,
7685                                            SDValue OffsetOp) {
7686   // If the 'Offset' value isn't a constant, we can't handle this.
7687   if (ConstantSDNode *OffsetNode = dyn_cast<ConstantSDNode>(OffsetOp))
7688     return InferPointerInfo(Info, DAG, Ptr, OffsetNode->getSExtValue());
7689   if (OffsetOp.isUndef())
7690     return InferPointerInfo(Info, DAG, Ptr);
7691   return Info;
7692 }
7693 
7694 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
7695                               EVT VT, const SDLoc &dl, SDValue Chain,
7696                               SDValue Ptr, SDValue Offset,
7697                               MachinePointerInfo PtrInfo, EVT MemVT,
7698                               Align Alignment,
7699                               MachineMemOperand::Flags MMOFlags,
7700                               const AAMDNodes &AAInfo, const MDNode *Ranges) {
7701   assert(Chain.getValueType() == MVT::Other &&
7702         "Invalid chain type");
7703 
7704   MMOFlags |= MachineMemOperand::MOLoad;
7705   assert((MMOFlags & MachineMemOperand::MOStore) == 0);
7706   // If we don't have a PtrInfo, infer the trivial frame index case to simplify
7707   // clients.
7708   if (PtrInfo.V.isNull())
7709     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
7710 
7711   uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize());
7712   MachineFunction &MF = getMachineFunction();
7713   MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size,
7714                                                    Alignment, AAInfo, Ranges);
7715   return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO);
7716 }
7717 
7718 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
7719                               EVT VT, const SDLoc &dl, SDValue Chain,
7720                               SDValue Ptr, SDValue Offset, EVT MemVT,
7721                               MachineMemOperand *MMO) {
7722   if (VT == MemVT) {
7723     ExtType = ISD::NON_EXTLOAD;
7724   } else if (ExtType == ISD::NON_EXTLOAD) {
7725     assert(VT == MemVT && "Non-extending load from different memory type!");
7726   } else {
7727     // Extending load.
7728     assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) &&
7729            "Should only be an extending load, not truncating!");
7730     assert(VT.isInteger() == MemVT.isInteger() &&
7731            "Cannot convert from FP to Int or Int -> FP!");
7732     assert(VT.isVector() == MemVT.isVector() &&
7733            "Cannot use an ext load to convert to or from a vector!");
7734     assert((!VT.isVector() ||
7735             VT.getVectorElementCount() == MemVT.getVectorElementCount()) &&
7736            "Cannot use an ext load to change the number of vector elements!");
7737   }
7738 
7739   bool Indexed = AM != ISD::UNINDEXED;
7740   assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
7741 
7742   SDVTList VTs = Indexed ?
7743     getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
7744   SDValue Ops[] = { Chain, Ptr, Offset };
7745   FoldingSetNodeID ID;
7746   AddNodeIDNode(ID, ISD::LOAD, VTs, Ops);
7747   ID.AddInteger(MemVT.getRawBits());
7748   ID.AddInteger(getSyntheticNodeSubclassData<LoadSDNode>(
7749       dl.getIROrder(), VTs, AM, ExtType, MemVT, MMO));
7750   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7751   ID.AddInteger(MMO->getFlags());
7752   void *IP = nullptr;
7753   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7754     cast<LoadSDNode>(E)->refineAlignment(MMO);
7755     return SDValue(E, 0);
7756   }
7757   auto *N = newSDNode<LoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
7758                                   ExtType, MemVT, MMO);
7759   createOperands(N, Ops);
7760 
7761   CSEMap.InsertNode(N, IP);
7762   InsertNode(N);
7763   SDValue V(N, 0);
7764   NewSDValueDbgMsg(V, "Creating new node: ", this);
7765   return V;
7766 }
7767 
7768 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
7769                               SDValue Ptr, MachinePointerInfo PtrInfo,
7770                               MaybeAlign Alignment,
7771                               MachineMemOperand::Flags MMOFlags,
7772                               const AAMDNodes &AAInfo, const MDNode *Ranges) {
7773   SDValue Undef = getUNDEF(Ptr.getValueType());
7774   return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7775                  PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges);
7776 }
7777 
7778 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
7779                               SDValue Ptr, MachineMemOperand *MMO) {
7780   SDValue Undef = getUNDEF(Ptr.getValueType());
7781   return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7782                  VT, MMO);
7783 }
7784 
7785 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
7786                                  EVT VT, SDValue Chain, SDValue Ptr,
7787                                  MachinePointerInfo PtrInfo, EVT MemVT,
7788                                  MaybeAlign Alignment,
7789                                  MachineMemOperand::Flags MMOFlags,
7790                                  const AAMDNodes &AAInfo) {
7791   SDValue Undef = getUNDEF(Ptr.getValueType());
7792   return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, PtrInfo,
7793                  MemVT, Alignment, MMOFlags, AAInfo);
7794 }
7795 
7796 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
7797                                  EVT VT, SDValue Chain, SDValue Ptr, EVT MemVT,
7798                                  MachineMemOperand *MMO) {
7799   SDValue Undef = getUNDEF(Ptr.getValueType());
7800   return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef,
7801                  MemVT, MMO);
7802 }
7803 
7804 SDValue SelectionDAG::getIndexedLoad(SDValue OrigLoad, const SDLoc &dl,
7805                                      SDValue Base, SDValue Offset,
7806                                      ISD::MemIndexedMode AM) {
7807   LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
7808   assert(LD->getOffset().isUndef() && "Load is already a indexed load!");
7809   // Don't propagate the invariant or dereferenceable flags.
7810   auto MMOFlags =
7811       LD->getMemOperand()->getFlags() &
7812       ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
7813   return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
7814                  LD->getChain(), Base, Offset, LD->getPointerInfo(),
7815                  LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo());
7816 }
7817 
7818 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7819                                SDValue Ptr, MachinePointerInfo PtrInfo,
7820                                Align Alignment,
7821                                MachineMemOperand::Flags MMOFlags,
7822                                const AAMDNodes &AAInfo) {
7823   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
7824 
7825   MMOFlags |= MachineMemOperand::MOStore;
7826   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
7827 
7828   if (PtrInfo.V.isNull())
7829     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
7830 
7831   MachineFunction &MF = getMachineFunction();
7832   uint64_t Size =
7833       MemoryLocation::getSizeOrUnknown(Val.getValueType().getStoreSize());
7834   MachineMemOperand *MMO =
7835       MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, Alignment, AAInfo);
7836   return getStore(Chain, dl, Val, Ptr, MMO);
7837 }
7838 
7839 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7840                                SDValue Ptr, MachineMemOperand *MMO) {
7841   assert(Chain.getValueType() == MVT::Other &&
7842         "Invalid chain type");
7843   EVT VT = Val.getValueType();
7844   SDVTList VTs = getVTList(MVT::Other);
7845   SDValue Undef = getUNDEF(Ptr.getValueType());
7846   SDValue Ops[] = { Chain, Val, Ptr, Undef };
7847   FoldingSetNodeID ID;
7848   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7849   ID.AddInteger(VT.getRawBits());
7850   ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
7851       dl.getIROrder(), VTs, ISD::UNINDEXED, false, VT, MMO));
7852   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7853   ID.AddInteger(MMO->getFlags());
7854   void *IP = nullptr;
7855   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7856     cast<StoreSDNode>(E)->refineAlignment(MMO);
7857     return SDValue(E, 0);
7858   }
7859   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7860                                    ISD::UNINDEXED, false, VT, MMO);
7861   createOperands(N, Ops);
7862 
7863   CSEMap.InsertNode(N, IP);
7864   InsertNode(N);
7865   SDValue V(N, 0);
7866   NewSDValueDbgMsg(V, "Creating new node: ", this);
7867   return V;
7868 }
7869 
7870 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7871                                     SDValue Ptr, MachinePointerInfo PtrInfo,
7872                                     EVT SVT, Align Alignment,
7873                                     MachineMemOperand::Flags MMOFlags,
7874                                     const AAMDNodes &AAInfo) {
7875   assert(Chain.getValueType() == MVT::Other &&
7876         "Invalid chain type");
7877 
7878   MMOFlags |= MachineMemOperand::MOStore;
7879   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
7880 
7881   if (PtrInfo.V.isNull())
7882     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
7883 
7884   MachineFunction &MF = getMachineFunction();
7885   MachineMemOperand *MMO = MF.getMachineMemOperand(
7886       PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()),
7887       Alignment, AAInfo);
7888   return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO);
7889 }
7890 
7891 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7892                                     SDValue Ptr, EVT SVT,
7893                                     MachineMemOperand *MMO) {
7894   EVT VT = Val.getValueType();
7895 
7896   assert(Chain.getValueType() == MVT::Other &&
7897         "Invalid chain type");
7898   if (VT == SVT)
7899     return getStore(Chain, dl, Val, Ptr, MMO);
7900 
7901   assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
7902          "Should only be a truncating store, not extending!");
7903   assert(VT.isInteger() == SVT.isInteger() &&
7904          "Can't do FP-INT conversion!");
7905   assert(VT.isVector() == SVT.isVector() &&
7906          "Cannot use trunc store to convert to or from a vector!");
7907   assert((!VT.isVector() ||
7908           VT.getVectorElementCount() == SVT.getVectorElementCount()) &&
7909          "Cannot use trunc store to change the number of vector elements!");
7910 
7911   SDVTList VTs = getVTList(MVT::Other);
7912   SDValue Undef = getUNDEF(Ptr.getValueType());
7913   SDValue Ops[] = { Chain, Val, Ptr, Undef };
7914   FoldingSetNodeID ID;
7915   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7916   ID.AddInteger(SVT.getRawBits());
7917   ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
7918       dl.getIROrder(), VTs, ISD::UNINDEXED, true, SVT, MMO));
7919   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7920   ID.AddInteger(MMO->getFlags());
7921   void *IP = nullptr;
7922   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7923     cast<StoreSDNode>(E)->refineAlignment(MMO);
7924     return SDValue(E, 0);
7925   }
7926   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7927                                    ISD::UNINDEXED, true, SVT, MMO);
7928   createOperands(N, Ops);
7929 
7930   CSEMap.InsertNode(N, IP);
7931   InsertNode(N);
7932   SDValue V(N, 0);
7933   NewSDValueDbgMsg(V, "Creating new node: ", this);
7934   return V;
7935 }
7936 
7937 SDValue SelectionDAG::getIndexedStore(SDValue OrigStore, const SDLoc &dl,
7938                                       SDValue Base, SDValue Offset,
7939                                       ISD::MemIndexedMode AM) {
7940   StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
7941   assert(ST->getOffset().isUndef() && "Store is already a indexed store!");
7942   SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
7943   SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
7944   FoldingSetNodeID ID;
7945   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7946   ID.AddInteger(ST->getMemoryVT().getRawBits());
7947   ID.AddInteger(ST->getRawSubclassData());
7948   ID.AddInteger(ST->getPointerInfo().getAddrSpace());
7949   ID.AddInteger(ST->getMemOperand()->getFlags());
7950   void *IP = nullptr;
7951   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
7952     return SDValue(E, 0);
7953 
7954   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
7955                                    ST->isTruncatingStore(), ST->getMemoryVT(),
7956                                    ST->getMemOperand());
7957   createOperands(N, Ops);
7958 
7959   CSEMap.InsertNode(N, IP);
7960   InsertNode(N);
7961   SDValue V(N, 0);
7962   NewSDValueDbgMsg(V, "Creating new node: ", this);
7963   return V;
7964 }
7965 
7966 SDValue SelectionDAG::getLoadVP(
7967     ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &dl,
7968     SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Mask, SDValue EVL,
7969     MachinePointerInfo PtrInfo, EVT MemVT, Align Alignment,
7970     MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
7971     const MDNode *Ranges, bool IsExpanding) {
7972   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
7973 
7974   MMOFlags |= MachineMemOperand::MOLoad;
7975   assert((MMOFlags & MachineMemOperand::MOStore) == 0);
7976   // If we don't have a PtrInfo, infer the trivial frame index case to simplify
7977   // clients.
7978   if (PtrInfo.V.isNull())
7979     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
7980 
7981   uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize());
7982   MachineFunction &MF = getMachineFunction();
7983   MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size,
7984                                                    Alignment, AAInfo, Ranges);
7985   return getLoadVP(AM, ExtType, VT, dl, Chain, Ptr, Offset, Mask, EVL, MemVT,
7986                    MMO, IsExpanding);
7987 }
7988 
7989 SDValue SelectionDAG::getLoadVP(ISD::MemIndexedMode AM,
7990                                 ISD::LoadExtType ExtType, EVT VT,
7991                                 const SDLoc &dl, SDValue Chain, SDValue Ptr,
7992                                 SDValue Offset, SDValue Mask, SDValue EVL,
7993                                 EVT MemVT, MachineMemOperand *MMO,
7994                                 bool IsExpanding) {
7995   bool Indexed = AM != ISD::UNINDEXED;
7996   assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
7997 
7998   SDVTList VTs = Indexed ? getVTList(VT, Ptr.getValueType(), MVT::Other)
7999                          : getVTList(VT, MVT::Other);
8000   SDValue Ops[] = {Chain, Ptr, Offset, Mask, EVL};
8001   FoldingSetNodeID ID;
8002   AddNodeIDNode(ID, ISD::VP_LOAD, VTs, Ops);
8003   ID.AddInteger(VT.getRawBits());
8004   ID.AddInteger(getSyntheticNodeSubclassData<VPLoadSDNode>(
8005       dl.getIROrder(), VTs, AM, ExtType, IsExpanding, MemVT, MMO));
8006   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8007   ID.AddInteger(MMO->getFlags());
8008   void *IP = nullptr;
8009   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8010     cast<VPLoadSDNode>(E)->refineAlignment(MMO);
8011     return SDValue(E, 0);
8012   }
8013   auto *N = newSDNode<VPLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
8014                                     ExtType, IsExpanding, MemVT, MMO);
8015   createOperands(N, Ops);
8016 
8017   CSEMap.InsertNode(N, IP);
8018   InsertNode(N);
8019   SDValue V(N, 0);
8020   NewSDValueDbgMsg(V, "Creating new node: ", this);
8021   return V;
8022 }
8023 
8024 SDValue SelectionDAG::getLoadVP(EVT VT, const SDLoc &dl, SDValue Chain,
8025                                 SDValue Ptr, SDValue Mask, SDValue EVL,
8026                                 MachinePointerInfo PtrInfo,
8027                                 MaybeAlign Alignment,
8028                                 MachineMemOperand::Flags MMOFlags,
8029                                 const AAMDNodes &AAInfo, const MDNode *Ranges,
8030                                 bool IsExpanding) {
8031   SDValue Undef = getUNDEF(Ptr.getValueType());
8032   return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
8033                    Mask, EVL, PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges,
8034                    IsExpanding);
8035 }
8036 
8037 SDValue SelectionDAG::getLoadVP(EVT VT, const SDLoc &dl, SDValue Chain,
8038                                 SDValue Ptr, SDValue Mask, SDValue EVL,
8039                                 MachineMemOperand *MMO, bool IsExpanding) {
8040   SDValue Undef = getUNDEF(Ptr.getValueType());
8041   return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
8042                    Mask, EVL, VT, MMO, IsExpanding);
8043 }
8044 
8045 SDValue SelectionDAG::getExtLoadVP(ISD::LoadExtType ExtType, const SDLoc &dl,
8046                                    EVT VT, SDValue Chain, SDValue Ptr,
8047                                    SDValue Mask, SDValue EVL,
8048                                    MachinePointerInfo PtrInfo, EVT MemVT,
8049                                    MaybeAlign Alignment,
8050                                    MachineMemOperand::Flags MMOFlags,
8051                                    const AAMDNodes &AAInfo, bool IsExpanding) {
8052   SDValue Undef = getUNDEF(Ptr.getValueType());
8053   return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask,
8054                    EVL, PtrInfo, MemVT, Alignment, MMOFlags, AAInfo, nullptr,
8055                    IsExpanding);
8056 }
8057 
8058 SDValue SelectionDAG::getExtLoadVP(ISD::LoadExtType ExtType, const SDLoc &dl,
8059                                    EVT VT, SDValue Chain, SDValue Ptr,
8060                                    SDValue Mask, SDValue EVL, EVT MemVT,
8061                                    MachineMemOperand *MMO, bool IsExpanding) {
8062   SDValue Undef = getUNDEF(Ptr.getValueType());
8063   return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask,
8064                    EVL, MemVT, MMO, IsExpanding);
8065 }
8066 
8067 SDValue SelectionDAG::getIndexedLoadVP(SDValue OrigLoad, const SDLoc &dl,
8068                                        SDValue Base, SDValue Offset,
8069                                        ISD::MemIndexedMode AM) {
8070   auto *LD = cast<VPLoadSDNode>(OrigLoad);
8071   assert(LD->getOffset().isUndef() && "Load is already a indexed load!");
8072   // Don't propagate the invariant or dereferenceable flags.
8073   auto MMOFlags =
8074       LD->getMemOperand()->getFlags() &
8075       ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
8076   return getLoadVP(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
8077                    LD->getChain(), Base, Offset, LD->getMask(),
8078                    LD->getVectorLength(), LD->getPointerInfo(),
8079                    LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo(),
8080                    nullptr, LD->isExpandingLoad());
8081 }
8082 
8083 SDValue SelectionDAG::getStoreVP(SDValue Chain, const SDLoc &dl, SDValue Val,
8084                                  SDValue Ptr, SDValue Offset, SDValue Mask,
8085                                  SDValue EVL, EVT MemVT, MachineMemOperand *MMO,
8086                                  ISD::MemIndexedMode AM, bool IsTruncating,
8087                                  bool IsCompressing) {
8088   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
8089   bool Indexed = AM != ISD::UNINDEXED;
8090   assert((Indexed || Offset.isUndef()) && "Unindexed vp_store with an offset!");
8091   SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other)
8092                          : getVTList(MVT::Other);
8093   SDValue Ops[] = {Chain, Val, Ptr, Offset, Mask, EVL};
8094   FoldingSetNodeID ID;
8095   AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
8096   ID.AddInteger(MemVT.getRawBits());
8097   ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>(
8098       dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
8099   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8100   ID.AddInteger(MMO->getFlags());
8101   void *IP = nullptr;
8102   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8103     cast<VPStoreSDNode>(E)->refineAlignment(MMO);
8104     return SDValue(E, 0);
8105   }
8106   auto *N = newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
8107                                      IsTruncating, IsCompressing, MemVT, MMO);
8108   createOperands(N, Ops);
8109 
8110   CSEMap.InsertNode(N, IP);
8111   InsertNode(N);
8112   SDValue V(N, 0);
8113   NewSDValueDbgMsg(V, "Creating new node: ", this);
8114   return V;
8115 }
8116 
8117 SDValue SelectionDAG::getTruncStoreVP(SDValue Chain, const SDLoc &dl,
8118                                       SDValue Val, SDValue Ptr, SDValue Mask,
8119                                       SDValue EVL, MachinePointerInfo PtrInfo,
8120                                       EVT SVT, Align Alignment,
8121                                       MachineMemOperand::Flags MMOFlags,
8122                                       const AAMDNodes &AAInfo,
8123                                       bool IsCompressing) {
8124   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
8125 
8126   MMOFlags |= MachineMemOperand::MOStore;
8127   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
8128 
8129   if (PtrInfo.V.isNull())
8130     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
8131 
8132   MachineFunction &MF = getMachineFunction();
8133   MachineMemOperand *MMO = MF.getMachineMemOperand(
8134       PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()),
8135       Alignment, AAInfo);
8136   return getTruncStoreVP(Chain, dl, Val, Ptr, Mask, EVL, SVT, MMO,
8137                          IsCompressing);
8138 }
8139 
8140 SDValue SelectionDAG::getTruncStoreVP(SDValue Chain, const SDLoc &dl,
8141                                       SDValue Val, SDValue Ptr, SDValue Mask,
8142                                       SDValue EVL, EVT SVT,
8143                                       MachineMemOperand *MMO,
8144                                       bool IsCompressing) {
8145   EVT VT = Val.getValueType();
8146 
8147   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
8148   if (VT == SVT)
8149     return getStoreVP(Chain, dl, Val, Ptr, getUNDEF(Ptr.getValueType()), Mask,
8150                       EVL, VT, MMO, ISD::UNINDEXED,
8151                       /*IsTruncating*/ false, IsCompressing);
8152 
8153   assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
8154          "Should only be a truncating store, not extending!");
8155   assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!");
8156   assert(VT.isVector() == SVT.isVector() &&
8157          "Cannot use trunc store to convert to or from a vector!");
8158   assert((!VT.isVector() ||
8159           VT.getVectorElementCount() == SVT.getVectorElementCount()) &&
8160          "Cannot use trunc store to change the number of vector elements!");
8161 
8162   SDVTList VTs = getVTList(MVT::Other);
8163   SDValue Undef = getUNDEF(Ptr.getValueType());
8164   SDValue Ops[] = {Chain, Val, Ptr, Undef, Mask, EVL};
8165   FoldingSetNodeID ID;
8166   AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
8167   ID.AddInteger(SVT.getRawBits());
8168   ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>(
8169       dl.getIROrder(), VTs, ISD::UNINDEXED, true, IsCompressing, SVT, MMO));
8170   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8171   ID.AddInteger(MMO->getFlags());
8172   void *IP = nullptr;
8173   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8174     cast<VPStoreSDNode>(E)->refineAlignment(MMO);
8175     return SDValue(E, 0);
8176   }
8177   auto *N =
8178       newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
8179                                ISD::UNINDEXED, true, IsCompressing, SVT, MMO);
8180   createOperands(N, Ops);
8181 
8182   CSEMap.InsertNode(N, IP);
8183   InsertNode(N);
8184   SDValue V(N, 0);
8185   NewSDValueDbgMsg(V, "Creating new node: ", this);
8186   return V;
8187 }
8188 
8189 SDValue SelectionDAG::getIndexedStoreVP(SDValue OrigStore, const SDLoc &dl,
8190                                         SDValue Base, SDValue Offset,
8191                                         ISD::MemIndexedMode AM) {
8192   auto *ST = cast<VPStoreSDNode>(OrigStore);
8193   assert(ST->getOffset().isUndef() && "Store is already an indexed store!");
8194   SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
8195   SDValue Ops[] = {ST->getChain(), ST->getValue(), Base,
8196                    Offset,         ST->getMask(),  ST->getVectorLength()};
8197   FoldingSetNodeID ID;
8198   AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
8199   ID.AddInteger(ST->getMemoryVT().getRawBits());
8200   ID.AddInteger(ST->getRawSubclassData());
8201   ID.AddInteger(ST->getPointerInfo().getAddrSpace());
8202   ID.AddInteger(ST->getMemOperand()->getFlags());
8203   void *IP = nullptr;
8204   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
8205     return SDValue(E, 0);
8206 
8207   auto *N = newSDNode<VPStoreSDNode>(
8208       dl.getIROrder(), dl.getDebugLoc(), VTs, AM, ST->isTruncatingStore(),
8209       ST->isCompressingStore(), ST->getMemoryVT(), ST->getMemOperand());
8210   createOperands(N, Ops);
8211 
8212   CSEMap.InsertNode(N, IP);
8213   InsertNode(N);
8214   SDValue V(N, 0);
8215   NewSDValueDbgMsg(V, "Creating new node: ", this);
8216   return V;
8217 }
8218 
8219 SDValue SelectionDAG::getStridedLoadVP(
8220     ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &DL,
8221     SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Stride, SDValue Mask,
8222     SDValue EVL, MachinePointerInfo PtrInfo, EVT MemVT, Align Alignment,
8223     MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
8224     const MDNode *Ranges, bool IsExpanding) {
8225   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
8226 
8227   MMOFlags |= MachineMemOperand::MOLoad;
8228   assert((MMOFlags & MachineMemOperand::MOStore) == 0);
8229   // If we don't have a PtrInfo, infer the trivial frame index case to simplify
8230   // clients.
8231   if (PtrInfo.V.isNull())
8232     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
8233 
8234   uint64_t Size = MemoryLocation::UnknownSize;
8235   MachineFunction &MF = getMachineFunction();
8236   MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size,
8237                                                    Alignment, AAInfo, Ranges);
8238   return getStridedLoadVP(AM, ExtType, VT, DL, Chain, Ptr, Offset, Stride, Mask,
8239                           EVL, MemVT, MMO, IsExpanding);
8240 }
8241 
8242 SDValue SelectionDAG::getStridedLoadVP(
8243     ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &DL,
8244     SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Stride, SDValue Mask,
8245     SDValue EVL, EVT MemVT, MachineMemOperand *MMO, bool IsExpanding) {
8246   bool Indexed = AM != ISD::UNINDEXED;
8247   assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
8248 
8249   SDValue Ops[] = {Chain, Ptr, Offset, Stride, Mask, EVL};
8250   SDVTList VTs = Indexed ? getVTList(VT, Ptr.getValueType(), MVT::Other)
8251                          : getVTList(VT, MVT::Other);
8252   FoldingSetNodeID ID;
8253   AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_LOAD, VTs, Ops);
8254   ID.AddInteger(VT.getRawBits());
8255   ID.AddInteger(getSyntheticNodeSubclassData<VPStridedLoadSDNode>(
8256       DL.getIROrder(), VTs, AM, ExtType, IsExpanding, MemVT, MMO));
8257   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8258 
8259   void *IP = nullptr;
8260   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
8261     cast<VPStridedLoadSDNode>(E)->refineAlignment(MMO);
8262     return SDValue(E, 0);
8263   }
8264 
8265   auto *N =
8266       newSDNode<VPStridedLoadSDNode>(DL.getIROrder(), DL.getDebugLoc(), VTs, AM,
8267                                      ExtType, IsExpanding, MemVT, MMO);
8268   createOperands(N, Ops);
8269   CSEMap.InsertNode(N, IP);
8270   InsertNode(N);
8271   SDValue V(N, 0);
8272   NewSDValueDbgMsg(V, "Creating new node: ", this);
8273   return V;
8274 }
8275 
8276 SDValue SelectionDAG::getStridedLoadVP(
8277     EVT VT, const SDLoc &DL, SDValue Chain, SDValue Ptr, SDValue Stride,
8278     SDValue Mask, SDValue EVL, MachinePointerInfo PtrInfo, MaybeAlign Alignment,
8279     MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
8280     const MDNode *Ranges, bool IsExpanding) {
8281   SDValue Undef = getUNDEF(Ptr.getValueType());
8282   return getStridedLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, DL, Chain, Ptr,
8283                           Undef, Stride, Mask, EVL, PtrInfo, VT, Alignment,
8284                           MMOFlags, AAInfo, Ranges, IsExpanding);
8285 }
8286 
8287 SDValue SelectionDAG::getStridedLoadVP(EVT VT, const SDLoc &DL, SDValue Chain,
8288                                        SDValue Ptr, SDValue Stride,
8289                                        SDValue Mask, SDValue EVL,
8290                                        MachineMemOperand *MMO,
8291                                        bool IsExpanding) {
8292   SDValue Undef = getUNDEF(Ptr.getValueType());
8293   return getStridedLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, DL, Chain, Ptr,
8294                           Undef, Stride, Mask, EVL, VT, MMO, 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,
8300     MachinePointerInfo PtrInfo, EVT MemVT, MaybeAlign Alignment,
8301     MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
8302     bool IsExpanding) {
8303   SDValue Undef = getUNDEF(Ptr.getValueType());
8304   return getStridedLoadVP(ISD::UNINDEXED, ExtType, VT, DL, Chain, Ptr, Undef,
8305                           Stride, Mask, EVL, PtrInfo, MemVT, Alignment,
8306                           MMOFlags, AAInfo, nullptr, IsExpanding);
8307 }
8308 
8309 SDValue SelectionDAG::getExtStridedLoadVP(
8310     ISD::LoadExtType ExtType, const SDLoc &DL, EVT VT, SDValue Chain,
8311     SDValue Ptr, SDValue Stride, SDValue Mask, SDValue EVL, EVT MemVT,
8312     MachineMemOperand *MMO, bool IsExpanding) {
8313   SDValue Undef = getUNDEF(Ptr.getValueType());
8314   return getStridedLoadVP(ISD::UNINDEXED, ExtType, VT, DL, Chain, Ptr, Undef,
8315                           Stride, Mask, EVL, MemVT, MMO, IsExpanding);
8316 }
8317 
8318 SDValue SelectionDAG::getIndexedStridedLoadVP(SDValue OrigLoad, const SDLoc &DL,
8319                                               SDValue Base, SDValue Offset,
8320                                               ISD::MemIndexedMode AM) {
8321   auto *SLD = cast<VPStridedLoadSDNode>(OrigLoad);
8322   assert(SLD->getOffset().isUndef() &&
8323          "Strided load is already a indexed load!");
8324   // Don't propagate the invariant or dereferenceable flags.
8325   auto MMOFlags =
8326       SLD->getMemOperand()->getFlags() &
8327       ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
8328   return getStridedLoadVP(
8329       AM, SLD->getExtensionType(), OrigLoad.getValueType(), DL, SLD->getChain(),
8330       Base, Offset, SLD->getStride(), SLD->getMask(), SLD->getVectorLength(),
8331       SLD->getPointerInfo(), SLD->getMemoryVT(), SLD->getAlign(), MMOFlags,
8332       SLD->getAAInfo(), nullptr, SLD->isExpandingLoad());
8333 }
8334 
8335 SDValue SelectionDAG::getStridedStoreVP(SDValue Chain, const SDLoc &DL,
8336                                         SDValue Val, SDValue Ptr,
8337                                         SDValue Offset, SDValue Stride,
8338                                         SDValue Mask, SDValue EVL, EVT MemVT,
8339                                         MachineMemOperand *MMO,
8340                                         ISD::MemIndexedMode AM,
8341                                         bool IsTruncating, bool IsCompressing) {
8342   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
8343   bool Indexed = AM != ISD::UNINDEXED;
8344   assert((Indexed || Offset.isUndef()) && "Unindexed vp_store with an offset!");
8345   SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other)
8346                          : getVTList(MVT::Other);
8347   SDValue Ops[] = {Chain, Val, Ptr, Offset, Stride, Mask, EVL};
8348   FoldingSetNodeID ID;
8349   AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_STORE, VTs, Ops);
8350   ID.AddInteger(MemVT.getRawBits());
8351   ID.AddInteger(getSyntheticNodeSubclassData<VPStridedStoreSDNode>(
8352       DL.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
8353   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8354   void *IP = nullptr;
8355   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
8356     cast<VPStridedStoreSDNode>(E)->refineAlignment(MMO);
8357     return SDValue(E, 0);
8358   }
8359   auto *N = newSDNode<VPStridedStoreSDNode>(DL.getIROrder(), DL.getDebugLoc(),
8360                                             VTs, AM, IsTruncating,
8361                                             IsCompressing, MemVT, MMO);
8362   createOperands(N, Ops);
8363 
8364   CSEMap.InsertNode(N, IP);
8365   InsertNode(N);
8366   SDValue V(N, 0);
8367   NewSDValueDbgMsg(V, "Creating new node: ", this);
8368   return V;
8369 }
8370 
8371 SDValue SelectionDAG::getTruncStridedStoreVP(
8372     SDValue Chain, const SDLoc &DL, SDValue Val, SDValue Ptr, SDValue Stride,
8373     SDValue Mask, SDValue EVL, MachinePointerInfo PtrInfo, EVT SVT,
8374     Align Alignment, MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
8375     bool IsCompressing) {
8376   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
8377 
8378   MMOFlags |= MachineMemOperand::MOStore;
8379   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
8380 
8381   if (PtrInfo.V.isNull())
8382     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
8383 
8384   MachineFunction &MF = getMachineFunction();
8385   MachineMemOperand *MMO = MF.getMachineMemOperand(
8386       PtrInfo, MMOFlags, MemoryLocation::UnknownSize, Alignment, AAInfo);
8387   return getTruncStridedStoreVP(Chain, DL, Val, Ptr, Stride, Mask, EVL, SVT,
8388                                 MMO, IsCompressing);
8389 }
8390 
8391 SDValue SelectionDAG::getTruncStridedStoreVP(SDValue Chain, const SDLoc &DL,
8392                                              SDValue Val, SDValue Ptr,
8393                                              SDValue Stride, SDValue Mask,
8394                                              SDValue EVL, EVT SVT,
8395                                              MachineMemOperand *MMO,
8396                                              bool IsCompressing) {
8397   EVT VT = Val.getValueType();
8398 
8399   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
8400   if (VT == SVT)
8401     return getStridedStoreVP(Chain, DL, Val, Ptr, getUNDEF(Ptr.getValueType()),
8402                              Stride, Mask, EVL, VT, MMO, ISD::UNINDEXED,
8403                              /*IsTruncating*/ false, IsCompressing);
8404 
8405   assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
8406          "Should only be a truncating store, not extending!");
8407   assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!");
8408   assert(VT.isVector() == SVT.isVector() &&
8409          "Cannot use trunc store to convert to or from a vector!");
8410   assert((!VT.isVector() ||
8411           VT.getVectorElementCount() == SVT.getVectorElementCount()) &&
8412          "Cannot use trunc store to change the number of vector elements!");
8413 
8414   SDVTList VTs = getVTList(MVT::Other);
8415   SDValue Undef = getUNDEF(Ptr.getValueType());
8416   SDValue Ops[] = {Chain, Val, Ptr, Undef, Stride, Mask, EVL};
8417   FoldingSetNodeID ID;
8418   AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_STORE, VTs, Ops);
8419   ID.AddInteger(SVT.getRawBits());
8420   ID.AddInteger(getSyntheticNodeSubclassData<VPStridedStoreSDNode>(
8421       DL.getIROrder(), VTs, ISD::UNINDEXED, true, IsCompressing, SVT, MMO));
8422   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8423   void *IP = nullptr;
8424   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
8425     cast<VPStridedStoreSDNode>(E)->refineAlignment(MMO);
8426     return SDValue(E, 0);
8427   }
8428   auto *N = newSDNode<VPStridedStoreSDNode>(DL.getIROrder(), DL.getDebugLoc(),
8429                                             VTs, ISD::UNINDEXED, true,
8430                                             IsCompressing, SVT, MMO);
8431   createOperands(N, Ops);
8432 
8433   CSEMap.InsertNode(N, IP);
8434   InsertNode(N);
8435   SDValue V(N, 0);
8436   NewSDValueDbgMsg(V, "Creating new node: ", this);
8437   return V;
8438 }
8439 
8440 SDValue SelectionDAG::getIndexedStridedStoreVP(SDValue OrigStore,
8441                                                const SDLoc &DL, SDValue Base,
8442                                                SDValue Offset,
8443                                                ISD::MemIndexedMode AM) {
8444   auto *SST = cast<VPStridedStoreSDNode>(OrigStore);
8445   assert(SST->getOffset().isUndef() &&
8446          "Strided store is already an indexed store!");
8447   SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
8448   SDValue Ops[] = {
8449       SST->getChain(), SST->getValue(),       Base, Offset, SST->getStride(),
8450       SST->getMask(),  SST->getVectorLength()};
8451   FoldingSetNodeID ID;
8452   AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_STORE, VTs, Ops);
8453   ID.AddInteger(SST->getMemoryVT().getRawBits());
8454   ID.AddInteger(SST->getRawSubclassData());
8455   ID.AddInteger(SST->getPointerInfo().getAddrSpace());
8456   void *IP = nullptr;
8457   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
8458     return SDValue(E, 0);
8459 
8460   auto *N = newSDNode<VPStridedStoreSDNode>(
8461       DL.getIROrder(), DL.getDebugLoc(), VTs, AM, SST->isTruncatingStore(),
8462       SST->isCompressingStore(), SST->getMemoryVT(), SST->getMemOperand());
8463   createOperands(N, Ops);
8464 
8465   CSEMap.InsertNode(N, IP);
8466   InsertNode(N);
8467   SDValue V(N, 0);
8468   NewSDValueDbgMsg(V, "Creating new node: ", this);
8469   return V;
8470 }
8471 
8472 SDValue SelectionDAG::getGatherVP(SDVTList VTs, EVT VT, const SDLoc &dl,
8473                                   ArrayRef<SDValue> Ops, MachineMemOperand *MMO,
8474                                   ISD::MemIndexType IndexType) {
8475   assert(Ops.size() == 6 && "Incompatible number of operands");
8476 
8477   FoldingSetNodeID ID;
8478   AddNodeIDNode(ID, ISD::VP_GATHER, VTs, Ops);
8479   ID.AddInteger(VT.getRawBits());
8480   ID.AddInteger(getSyntheticNodeSubclassData<VPGatherSDNode>(
8481       dl.getIROrder(), VTs, VT, MMO, IndexType));
8482   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8483   ID.AddInteger(MMO->getFlags());
8484   void *IP = nullptr;
8485   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8486     cast<VPGatherSDNode>(E)->refineAlignment(MMO);
8487     return SDValue(E, 0);
8488   }
8489 
8490   auto *N = newSDNode<VPGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
8491                                       VT, MMO, IndexType);
8492   createOperands(N, Ops);
8493 
8494   assert(N->getMask().getValueType().getVectorElementCount() ==
8495              N->getValueType(0).getVectorElementCount() &&
8496          "Vector width mismatch between mask and data");
8497   assert(N->getIndex().getValueType().getVectorElementCount().isScalable() ==
8498              N->getValueType(0).getVectorElementCount().isScalable() &&
8499          "Scalable flags of index and data do not match");
8500   assert(ElementCount::isKnownGE(
8501              N->getIndex().getValueType().getVectorElementCount(),
8502              N->getValueType(0).getVectorElementCount()) &&
8503          "Vector width mismatch between index and data");
8504   assert(isa<ConstantSDNode>(N->getScale()) &&
8505          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
8506          "Scale should be a constant power of 2");
8507 
8508   CSEMap.InsertNode(N, IP);
8509   InsertNode(N);
8510   SDValue V(N, 0);
8511   NewSDValueDbgMsg(V, "Creating new node: ", this);
8512   return V;
8513 }
8514 
8515 SDValue SelectionDAG::getScatterVP(SDVTList VTs, EVT VT, const SDLoc &dl,
8516                                    ArrayRef<SDValue> Ops,
8517                                    MachineMemOperand *MMO,
8518                                    ISD::MemIndexType IndexType) {
8519   assert(Ops.size() == 7 && "Incompatible number of operands");
8520 
8521   FoldingSetNodeID ID;
8522   AddNodeIDNode(ID, ISD::VP_SCATTER, VTs, Ops);
8523   ID.AddInteger(VT.getRawBits());
8524   ID.AddInteger(getSyntheticNodeSubclassData<VPScatterSDNode>(
8525       dl.getIROrder(), VTs, VT, MMO, IndexType));
8526   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8527   ID.AddInteger(MMO->getFlags());
8528   void *IP = nullptr;
8529   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8530     cast<VPScatterSDNode>(E)->refineAlignment(MMO);
8531     return SDValue(E, 0);
8532   }
8533   auto *N = newSDNode<VPScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
8534                                        VT, MMO, IndexType);
8535   createOperands(N, Ops);
8536 
8537   assert(N->getMask().getValueType().getVectorElementCount() ==
8538              N->getValue().getValueType().getVectorElementCount() &&
8539          "Vector width mismatch between mask and data");
8540   assert(
8541       N->getIndex().getValueType().getVectorElementCount().isScalable() ==
8542           N->getValue().getValueType().getVectorElementCount().isScalable() &&
8543       "Scalable flags of index and data do not match");
8544   assert(ElementCount::isKnownGE(
8545              N->getIndex().getValueType().getVectorElementCount(),
8546              N->getValue().getValueType().getVectorElementCount()) &&
8547          "Vector width mismatch between index and data");
8548   assert(isa<ConstantSDNode>(N->getScale()) &&
8549          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
8550          "Scale should be a constant power of 2");
8551 
8552   CSEMap.InsertNode(N, IP);
8553   InsertNode(N);
8554   SDValue V(N, 0);
8555   NewSDValueDbgMsg(V, "Creating new node: ", this);
8556   return V;
8557 }
8558 
8559 SDValue SelectionDAG::getMaskedLoad(EVT VT, const SDLoc &dl, SDValue Chain,
8560                                     SDValue Base, SDValue Offset, SDValue Mask,
8561                                     SDValue PassThru, EVT MemVT,
8562                                     MachineMemOperand *MMO,
8563                                     ISD::MemIndexedMode AM,
8564                                     ISD::LoadExtType ExtTy, bool isExpanding) {
8565   bool Indexed = AM != ISD::UNINDEXED;
8566   assert((Indexed || Offset.isUndef()) &&
8567          "Unindexed masked load with an offset!");
8568   SDVTList VTs = Indexed ? getVTList(VT, Base.getValueType(), MVT::Other)
8569                          : getVTList(VT, MVT::Other);
8570   SDValue Ops[] = {Chain, Base, Offset, Mask, PassThru};
8571   FoldingSetNodeID ID;
8572   AddNodeIDNode(ID, ISD::MLOAD, VTs, Ops);
8573   ID.AddInteger(MemVT.getRawBits());
8574   ID.AddInteger(getSyntheticNodeSubclassData<MaskedLoadSDNode>(
8575       dl.getIROrder(), VTs, AM, ExtTy, isExpanding, MemVT, MMO));
8576   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8577   ID.AddInteger(MMO->getFlags());
8578   void *IP = nullptr;
8579   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8580     cast<MaskedLoadSDNode>(E)->refineAlignment(MMO);
8581     return SDValue(E, 0);
8582   }
8583   auto *N = newSDNode<MaskedLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
8584                                         AM, ExtTy, isExpanding, MemVT, MMO);
8585   createOperands(N, Ops);
8586 
8587   CSEMap.InsertNode(N, IP);
8588   InsertNode(N);
8589   SDValue V(N, 0);
8590   NewSDValueDbgMsg(V, "Creating new node: ", this);
8591   return V;
8592 }
8593 
8594 SDValue SelectionDAG::getIndexedMaskedLoad(SDValue OrigLoad, const SDLoc &dl,
8595                                            SDValue Base, SDValue Offset,
8596                                            ISD::MemIndexedMode AM) {
8597   MaskedLoadSDNode *LD = cast<MaskedLoadSDNode>(OrigLoad);
8598   assert(LD->getOffset().isUndef() && "Masked load is already a indexed load!");
8599   return getMaskedLoad(OrigLoad.getValueType(), dl, LD->getChain(), Base,
8600                        Offset, LD->getMask(), LD->getPassThru(),
8601                        LD->getMemoryVT(), LD->getMemOperand(), AM,
8602                        LD->getExtensionType(), LD->isExpandingLoad());
8603 }
8604 
8605 SDValue SelectionDAG::getMaskedStore(SDValue Chain, const SDLoc &dl,
8606                                      SDValue Val, SDValue Base, SDValue Offset,
8607                                      SDValue Mask, EVT MemVT,
8608                                      MachineMemOperand *MMO,
8609                                      ISD::MemIndexedMode AM, bool IsTruncating,
8610                                      bool IsCompressing) {
8611   assert(Chain.getValueType() == MVT::Other &&
8612         "Invalid chain type");
8613   bool Indexed = AM != ISD::UNINDEXED;
8614   assert((Indexed || Offset.isUndef()) &&
8615          "Unindexed masked store with an offset!");
8616   SDVTList VTs = Indexed ? getVTList(Base.getValueType(), MVT::Other)
8617                          : getVTList(MVT::Other);
8618   SDValue Ops[] = {Chain, Val, Base, Offset, Mask};
8619   FoldingSetNodeID ID;
8620   AddNodeIDNode(ID, ISD::MSTORE, VTs, Ops);
8621   ID.AddInteger(MemVT.getRawBits());
8622   ID.AddInteger(getSyntheticNodeSubclassData<MaskedStoreSDNode>(
8623       dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
8624   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8625   ID.AddInteger(MMO->getFlags());
8626   void *IP = nullptr;
8627   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8628     cast<MaskedStoreSDNode>(E)->refineAlignment(MMO);
8629     return SDValue(E, 0);
8630   }
8631   auto *N =
8632       newSDNode<MaskedStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
8633                                    IsTruncating, IsCompressing, MemVT, MMO);
8634   createOperands(N, Ops);
8635 
8636   CSEMap.InsertNode(N, IP);
8637   InsertNode(N);
8638   SDValue V(N, 0);
8639   NewSDValueDbgMsg(V, "Creating new node: ", this);
8640   return V;
8641 }
8642 
8643 SDValue SelectionDAG::getIndexedMaskedStore(SDValue OrigStore, const SDLoc &dl,
8644                                             SDValue Base, SDValue Offset,
8645                                             ISD::MemIndexedMode AM) {
8646   MaskedStoreSDNode *ST = cast<MaskedStoreSDNode>(OrigStore);
8647   assert(ST->getOffset().isUndef() &&
8648          "Masked store is already a indexed store!");
8649   return getMaskedStore(ST->getChain(), dl, ST->getValue(), Base, Offset,
8650                         ST->getMask(), ST->getMemoryVT(), ST->getMemOperand(),
8651                         AM, ST->isTruncatingStore(), ST->isCompressingStore());
8652 }
8653 
8654 SDValue SelectionDAG::getMaskedGather(SDVTList VTs, EVT MemVT, const SDLoc &dl,
8655                                       ArrayRef<SDValue> Ops,
8656                                       MachineMemOperand *MMO,
8657                                       ISD::MemIndexType IndexType,
8658                                       ISD::LoadExtType ExtTy) {
8659   assert(Ops.size() == 6 && "Incompatible number of operands");
8660 
8661   FoldingSetNodeID ID;
8662   AddNodeIDNode(ID, ISD::MGATHER, VTs, Ops);
8663   ID.AddInteger(MemVT.getRawBits());
8664   ID.AddInteger(getSyntheticNodeSubclassData<MaskedGatherSDNode>(
8665       dl.getIROrder(), VTs, MemVT, MMO, IndexType, ExtTy));
8666   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8667   ID.AddInteger(MMO->getFlags());
8668   void *IP = nullptr;
8669   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8670     cast<MaskedGatherSDNode>(E)->refineAlignment(MMO);
8671     return SDValue(E, 0);
8672   }
8673 
8674   auto *N = newSDNode<MaskedGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(),
8675                                           VTs, MemVT, MMO, IndexType, ExtTy);
8676   createOperands(N, Ops);
8677 
8678   assert(N->getPassThru().getValueType() == N->getValueType(0) &&
8679          "Incompatible type of the PassThru value in MaskedGatherSDNode");
8680   assert(N->getMask().getValueType().getVectorElementCount() ==
8681              N->getValueType(0).getVectorElementCount() &&
8682          "Vector width mismatch between mask and data");
8683   assert(N->getIndex().getValueType().getVectorElementCount().isScalable() ==
8684              N->getValueType(0).getVectorElementCount().isScalable() &&
8685          "Scalable flags of index and data do not match");
8686   assert(ElementCount::isKnownGE(
8687              N->getIndex().getValueType().getVectorElementCount(),
8688              N->getValueType(0).getVectorElementCount()) &&
8689          "Vector width mismatch between index and data");
8690   assert(isa<ConstantSDNode>(N->getScale()) &&
8691          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
8692          "Scale should be a constant power of 2");
8693 
8694   CSEMap.InsertNode(N, IP);
8695   InsertNode(N);
8696   SDValue V(N, 0);
8697   NewSDValueDbgMsg(V, "Creating new node: ", this);
8698   return V;
8699 }
8700 
8701 SDValue SelectionDAG::getMaskedScatter(SDVTList VTs, EVT MemVT, const SDLoc &dl,
8702                                        ArrayRef<SDValue> Ops,
8703                                        MachineMemOperand *MMO,
8704                                        ISD::MemIndexType IndexType,
8705                                        bool IsTrunc) {
8706   assert(Ops.size() == 6 && "Incompatible number of operands");
8707 
8708   FoldingSetNodeID ID;
8709   AddNodeIDNode(ID, ISD::MSCATTER, VTs, Ops);
8710   ID.AddInteger(MemVT.getRawBits());
8711   ID.AddInteger(getSyntheticNodeSubclassData<MaskedScatterSDNode>(
8712       dl.getIROrder(), VTs, MemVT, MMO, IndexType, IsTrunc));
8713   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8714   ID.AddInteger(MMO->getFlags());
8715   void *IP = nullptr;
8716   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8717     cast<MaskedScatterSDNode>(E)->refineAlignment(MMO);
8718     return SDValue(E, 0);
8719   }
8720 
8721   auto *N = newSDNode<MaskedScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(),
8722                                            VTs, MemVT, MMO, IndexType, IsTrunc);
8723   createOperands(N, Ops);
8724 
8725   assert(N->getMask().getValueType().getVectorElementCount() ==
8726              N->getValue().getValueType().getVectorElementCount() &&
8727          "Vector width mismatch between mask and data");
8728   assert(
8729       N->getIndex().getValueType().getVectorElementCount().isScalable() ==
8730           N->getValue().getValueType().getVectorElementCount().isScalable() &&
8731       "Scalable flags of index and data do not match");
8732   assert(ElementCount::isKnownGE(
8733              N->getIndex().getValueType().getVectorElementCount(),
8734              N->getValue().getValueType().getVectorElementCount()) &&
8735          "Vector width mismatch between index and data");
8736   assert(isa<ConstantSDNode>(N->getScale()) &&
8737          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
8738          "Scale should be a constant power of 2");
8739 
8740   CSEMap.InsertNode(N, IP);
8741   InsertNode(N);
8742   SDValue V(N, 0);
8743   NewSDValueDbgMsg(V, "Creating new node: ", this);
8744   return V;
8745 }
8746 
8747 SDValue SelectionDAG::simplifySelect(SDValue Cond, SDValue T, SDValue F) {
8748   // select undef, T, F --> T (if T is a constant), otherwise F
8749   // select, ?, undef, F --> F
8750   // select, ?, T, undef --> T
8751   if (Cond.isUndef())
8752     return isConstantValueOfAnyType(T) ? T : F;
8753   if (T.isUndef())
8754     return F;
8755   if (F.isUndef())
8756     return T;
8757 
8758   // select true, T, F --> T
8759   // select false, T, F --> F
8760   if (auto *CondC = dyn_cast<ConstantSDNode>(Cond))
8761     return CondC->isZero() ? F : T;
8762 
8763   // TODO: This should simplify VSELECT with constant condition using something
8764   // like this (but check boolean contents to be complete?):
8765   //  if (ISD::isBuildVectorAllOnes(Cond.getNode()))
8766   //    return T;
8767   //  if (ISD::isBuildVectorAllZeros(Cond.getNode()))
8768   //    return F;
8769 
8770   // select ?, T, T --> T
8771   if (T == F)
8772     return T;
8773 
8774   return SDValue();
8775 }
8776 
8777 SDValue SelectionDAG::simplifyShift(SDValue X, SDValue Y) {
8778   // shift undef, Y --> 0 (can always assume that the undef value is 0)
8779   if (X.isUndef())
8780     return getConstant(0, SDLoc(X.getNode()), X.getValueType());
8781   // shift X, undef --> undef (because it may shift by the bitwidth)
8782   if (Y.isUndef())
8783     return getUNDEF(X.getValueType());
8784 
8785   // shift 0, Y --> 0
8786   // shift X, 0 --> X
8787   if (isNullOrNullSplat(X) || isNullOrNullSplat(Y))
8788     return X;
8789 
8790   // shift X, C >= bitwidth(X) --> undef
8791   // All vector elements must be too big (or undef) to avoid partial undefs.
8792   auto isShiftTooBig = [X](ConstantSDNode *Val) {
8793     return !Val || Val->getAPIntValue().uge(X.getScalarValueSizeInBits());
8794   };
8795   if (ISD::matchUnaryPredicate(Y, isShiftTooBig, true))
8796     return getUNDEF(X.getValueType());
8797 
8798   return SDValue();
8799 }
8800 
8801 SDValue SelectionDAG::simplifyFPBinop(unsigned Opcode, SDValue X, SDValue Y,
8802                                       SDNodeFlags Flags) {
8803   // If this operation has 'nnan' or 'ninf' and at least 1 disallowed operand
8804   // (an undef operand can be chosen to be Nan/Inf), then the result of this
8805   // operation is poison. That result can be relaxed to undef.
8806   ConstantFPSDNode *XC = isConstOrConstSplatFP(X, /* AllowUndefs */ true);
8807   ConstantFPSDNode *YC = isConstOrConstSplatFP(Y, /* AllowUndefs */ true);
8808   bool HasNan = (XC && XC->getValueAPF().isNaN()) ||
8809                 (YC && YC->getValueAPF().isNaN());
8810   bool HasInf = (XC && XC->getValueAPF().isInfinity()) ||
8811                 (YC && YC->getValueAPF().isInfinity());
8812 
8813   if (Flags.hasNoNaNs() && (HasNan || X.isUndef() || Y.isUndef()))
8814     return getUNDEF(X.getValueType());
8815 
8816   if (Flags.hasNoInfs() && (HasInf || X.isUndef() || Y.isUndef()))
8817     return getUNDEF(X.getValueType());
8818 
8819   if (!YC)
8820     return SDValue();
8821 
8822   // X + -0.0 --> X
8823   if (Opcode == ISD::FADD)
8824     if (YC->getValueAPF().isNegZero())
8825       return X;
8826 
8827   // X - +0.0 --> X
8828   if (Opcode == ISD::FSUB)
8829     if (YC->getValueAPF().isPosZero())
8830       return X;
8831 
8832   // X * 1.0 --> X
8833   // X / 1.0 --> X
8834   if (Opcode == ISD::FMUL || Opcode == ISD::FDIV)
8835     if (YC->getValueAPF().isExactlyValue(1.0))
8836       return X;
8837 
8838   // X * 0.0 --> 0.0
8839   if (Opcode == ISD::FMUL && Flags.hasNoNaNs() && Flags.hasNoSignedZeros())
8840     if (YC->getValueAPF().isZero())
8841       return getConstantFP(0.0, SDLoc(Y), Y.getValueType());
8842 
8843   return SDValue();
8844 }
8845 
8846 SDValue SelectionDAG::getVAArg(EVT VT, const SDLoc &dl, SDValue Chain,
8847                                SDValue Ptr, SDValue SV, unsigned Align) {
8848   SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, dl, MVT::i32) };
8849   return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops);
8850 }
8851 
8852 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8853                               ArrayRef<SDUse> Ops) {
8854   switch (Ops.size()) {
8855   case 0: return getNode(Opcode, DL, VT);
8856   case 1: return getNode(Opcode, DL, VT, static_cast<const SDValue>(Ops[0]));
8857   case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
8858   case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
8859   default: break;
8860   }
8861 
8862   // Copy from an SDUse array into an SDValue array for use with
8863   // the regular getNode logic.
8864   SmallVector<SDValue, 8> NewOps(Ops.begin(), Ops.end());
8865   return getNode(Opcode, DL, VT, NewOps);
8866 }
8867 
8868 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8869                               ArrayRef<SDValue> Ops) {
8870   SDNodeFlags Flags;
8871   if (Inserter)
8872     Flags = Inserter->getFlags();
8873   return getNode(Opcode, DL, VT, Ops, Flags);
8874 }
8875 
8876 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8877                               ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
8878   unsigned NumOps = Ops.size();
8879   switch (NumOps) {
8880   case 0: return getNode(Opcode, DL, VT);
8881   case 1: return getNode(Opcode, DL, VT, Ops[0], Flags);
8882   case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Flags);
8883   case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2], Flags);
8884   default: break;
8885   }
8886 
8887 #ifndef NDEBUG
8888   for (auto &Op : Ops)
8889     assert(Op.getOpcode() != ISD::DELETED_NODE &&
8890            "Operand is DELETED_NODE!");
8891 #endif
8892 
8893   switch (Opcode) {
8894   default: break;
8895   case ISD::BUILD_VECTOR:
8896     // Attempt to simplify BUILD_VECTOR.
8897     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
8898       return V;
8899     break;
8900   case ISD::CONCAT_VECTORS:
8901     if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
8902       return V;
8903     break;
8904   case ISD::SELECT_CC:
8905     assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
8906     assert(Ops[0].getValueType() == Ops[1].getValueType() &&
8907            "LHS and RHS of condition must have same type!");
8908     assert(Ops[2].getValueType() == Ops[3].getValueType() &&
8909            "True and False arms of SelectCC must have same type!");
8910     assert(Ops[2].getValueType() == VT &&
8911            "select_cc node must be of same type as true and false value!");
8912     break;
8913   case ISD::BR_CC:
8914     assert(NumOps == 5 && "BR_CC takes 5 operands!");
8915     assert(Ops[2].getValueType() == Ops[3].getValueType() &&
8916            "LHS/RHS of comparison should match types!");
8917     break;
8918   case ISD::VP_ADD:
8919   case ISD::VP_SUB:
8920     // If it is VP_ADD/VP_SUB mask operation then turn it to VP_XOR
8921     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
8922       Opcode = ISD::VP_XOR;
8923     break;
8924   case ISD::VP_MUL:
8925     // If it is VP_MUL mask operation then turn it to VP_AND
8926     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
8927       Opcode = ISD::VP_AND;
8928     break;
8929   case ISD::VP_REDUCE_MUL:
8930     // If it is VP_REDUCE_MUL mask operation then turn it to VP_REDUCE_AND
8931     if (VT == MVT::i1)
8932       Opcode = ISD::VP_REDUCE_AND;
8933     break;
8934   case ISD::VP_REDUCE_ADD:
8935     // If it is VP_REDUCE_ADD mask operation then turn it to VP_REDUCE_XOR
8936     if (VT == MVT::i1)
8937       Opcode = ISD::VP_REDUCE_XOR;
8938     break;
8939   case ISD::VP_REDUCE_SMAX:
8940   case ISD::VP_REDUCE_UMIN:
8941     // If it is VP_REDUCE_SMAX/VP_REDUCE_UMIN mask operation then turn it to
8942     // VP_REDUCE_AND.
8943     if (VT == MVT::i1)
8944       Opcode = ISD::VP_REDUCE_AND;
8945     break;
8946   case ISD::VP_REDUCE_SMIN:
8947   case ISD::VP_REDUCE_UMAX:
8948     // If it is VP_REDUCE_SMIN/VP_REDUCE_UMAX mask operation then turn it to
8949     // VP_REDUCE_OR.
8950     if (VT == MVT::i1)
8951       Opcode = ISD::VP_REDUCE_OR;
8952     break;
8953   }
8954 
8955   // Memoize nodes.
8956   SDNode *N;
8957   SDVTList VTs = getVTList(VT);
8958 
8959   if (VT != MVT::Glue) {
8960     FoldingSetNodeID ID;
8961     AddNodeIDNode(ID, Opcode, VTs, Ops);
8962     void *IP = nullptr;
8963 
8964     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
8965       return SDValue(E, 0);
8966 
8967     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
8968     createOperands(N, Ops);
8969 
8970     CSEMap.InsertNode(N, IP);
8971   } else {
8972     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
8973     createOperands(N, Ops);
8974   }
8975 
8976   N->setFlags(Flags);
8977   InsertNode(N);
8978   SDValue V(N, 0);
8979   NewSDValueDbgMsg(V, "Creating new node: ", this);
8980   return V;
8981 }
8982 
8983 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
8984                               ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) {
8985   return getNode(Opcode, DL, getVTList(ResultTys), Ops);
8986 }
8987 
8988 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8989                               ArrayRef<SDValue> Ops) {
8990   SDNodeFlags Flags;
8991   if (Inserter)
8992     Flags = Inserter->getFlags();
8993   return getNode(Opcode, DL, VTList, Ops, Flags);
8994 }
8995 
8996 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8997                               ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
8998   if (VTList.NumVTs == 1)
8999     return getNode(Opcode, DL, VTList.VTs[0], Ops, Flags);
9000 
9001 #ifndef NDEBUG
9002   for (auto &Op : Ops)
9003     assert(Op.getOpcode() != ISD::DELETED_NODE &&
9004            "Operand is DELETED_NODE!");
9005 #endif
9006 
9007   switch (Opcode) {
9008   case ISD::STRICT_FP_EXTEND:
9009     assert(VTList.NumVTs == 2 && Ops.size() == 2 &&
9010            "Invalid STRICT_FP_EXTEND!");
9011     assert(VTList.VTs[0].isFloatingPoint() &&
9012            Ops[1].getValueType().isFloatingPoint() && "Invalid FP cast!");
9013     assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
9014            "STRICT_FP_EXTEND 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(Ops[1].getValueType().bitsLT(VTList.VTs[0]) &&
9021            "Invalid fpext node, dst <= src!");
9022     break;
9023   case ISD::STRICT_FP_ROUND:
9024     assert(VTList.NumVTs == 2 && Ops.size() == 3 && "Invalid STRICT_FP_ROUND!");
9025     assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
9026            "STRICT_FP_ROUND result type should be vector iff the operand "
9027            "type is vector!");
9028     assert((!VTList.VTs[0].isVector() ||
9029             VTList.VTs[0].getVectorNumElements() ==
9030             Ops[1].getValueType().getVectorNumElements()) &&
9031            "Vector element count mismatch!");
9032     assert(VTList.VTs[0].isFloatingPoint() &&
9033            Ops[1].getValueType().isFloatingPoint() &&
9034            VTList.VTs[0].bitsLT(Ops[1].getValueType()) &&
9035            isa<ConstantSDNode>(Ops[2]) &&
9036            (cast<ConstantSDNode>(Ops[2])->getZExtValue() == 0 ||
9037             cast<ConstantSDNode>(Ops[2])->getZExtValue() == 1) &&
9038            "Invalid STRICT_FP_ROUND!");
9039     break;
9040 #if 0
9041   // FIXME: figure out how to safely handle things like
9042   // int foo(int x) { return 1 << (x & 255); }
9043   // int bar() { return foo(256); }
9044   case ISD::SRA_PARTS:
9045   case ISD::SRL_PARTS:
9046   case ISD::SHL_PARTS:
9047     if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
9048         cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
9049       return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
9050     else if (N3.getOpcode() == ISD::AND)
9051       if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
9052         // If the and is only masking out bits that cannot effect the shift,
9053         // eliminate the and.
9054         unsigned NumBits = VT.getScalarSizeInBits()*2;
9055         if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
9056           return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
9057       }
9058     break;
9059 #endif
9060   }
9061 
9062   // Memoize the node unless it returns a flag.
9063   SDNode *N;
9064   if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
9065     FoldingSetNodeID ID;
9066     AddNodeIDNode(ID, Opcode, VTList, Ops);
9067     void *IP = nullptr;
9068     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
9069       return SDValue(E, 0);
9070 
9071     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
9072     createOperands(N, Ops);
9073     CSEMap.InsertNode(N, IP);
9074   } else {
9075     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
9076     createOperands(N, Ops);
9077   }
9078 
9079   N->setFlags(Flags);
9080   InsertNode(N);
9081   SDValue V(N, 0);
9082   NewSDValueDbgMsg(V, "Creating new node: ", this);
9083   return V;
9084 }
9085 
9086 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
9087                               SDVTList VTList) {
9088   return getNode(Opcode, DL, VTList, None);
9089 }
9090 
9091 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
9092                               SDValue N1) {
9093   SDValue Ops[] = { N1 };
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) {
9099   SDValue Ops[] = { N1, N2 };
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) {
9105   SDValue Ops[] = { N1, N2, N3 };
9106   return getNode(Opcode, DL, VTList, Ops);
9107 }
9108 
9109 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
9110                               SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
9111   SDValue Ops[] = { N1, N2, N3, N4 };
9112   return getNode(Opcode, DL, VTList, Ops);
9113 }
9114 
9115 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
9116                               SDValue N1, SDValue N2, SDValue N3, SDValue N4,
9117                               SDValue N5) {
9118   SDValue Ops[] = { N1, N2, N3, N4, N5 };
9119   return getNode(Opcode, DL, VTList, Ops);
9120 }
9121 
9122 SDVTList SelectionDAG::getVTList(EVT VT) {
9123   return makeVTList(SDNode::getValueTypeList(VT), 1);
9124 }
9125 
9126 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2) {
9127   FoldingSetNodeID ID;
9128   ID.AddInteger(2U);
9129   ID.AddInteger(VT1.getRawBits());
9130   ID.AddInteger(VT2.getRawBits());
9131 
9132   void *IP = nullptr;
9133   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
9134   if (!Result) {
9135     EVT *Array = Allocator.Allocate<EVT>(2);
9136     Array[0] = VT1;
9137     Array[1] = VT2;
9138     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 2);
9139     VTListMap.InsertNode(Result, IP);
9140   }
9141   return Result->getSDVTList();
9142 }
9143 
9144 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3) {
9145   FoldingSetNodeID ID;
9146   ID.AddInteger(3U);
9147   ID.AddInteger(VT1.getRawBits());
9148   ID.AddInteger(VT2.getRawBits());
9149   ID.AddInteger(VT3.getRawBits());
9150 
9151   void *IP = nullptr;
9152   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
9153   if (!Result) {
9154     EVT *Array = Allocator.Allocate<EVT>(3);
9155     Array[0] = VT1;
9156     Array[1] = VT2;
9157     Array[2] = VT3;
9158     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 3);
9159     VTListMap.InsertNode(Result, IP);
9160   }
9161   return Result->getSDVTList();
9162 }
9163 
9164 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4) {
9165   FoldingSetNodeID ID;
9166   ID.AddInteger(4U);
9167   ID.AddInteger(VT1.getRawBits());
9168   ID.AddInteger(VT2.getRawBits());
9169   ID.AddInteger(VT3.getRawBits());
9170   ID.AddInteger(VT4.getRawBits());
9171 
9172   void *IP = nullptr;
9173   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
9174   if (!Result) {
9175     EVT *Array = Allocator.Allocate<EVT>(4);
9176     Array[0] = VT1;
9177     Array[1] = VT2;
9178     Array[2] = VT3;
9179     Array[3] = VT4;
9180     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 4);
9181     VTListMap.InsertNode(Result, IP);
9182   }
9183   return Result->getSDVTList();
9184 }
9185 
9186 SDVTList SelectionDAG::getVTList(ArrayRef<EVT> VTs) {
9187   unsigned NumVTs = VTs.size();
9188   FoldingSetNodeID ID;
9189   ID.AddInteger(NumVTs);
9190   for (unsigned index = 0; index < NumVTs; index++) {
9191     ID.AddInteger(VTs[index].getRawBits());
9192   }
9193 
9194   void *IP = nullptr;
9195   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
9196   if (!Result) {
9197     EVT *Array = Allocator.Allocate<EVT>(NumVTs);
9198     llvm::copy(VTs, Array);
9199     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, NumVTs);
9200     VTListMap.InsertNode(Result, IP);
9201   }
9202   return Result->getSDVTList();
9203 }
9204 
9205 
9206 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
9207 /// specified operands.  If the resultant node already exists in the DAG,
9208 /// this does not modify the specified node, instead it returns the node that
9209 /// already exists.  If the resultant node does not exist in the DAG, the
9210 /// input node is returned.  As a degenerate case, if you specify the same
9211 /// input operands as the node already has, the input node is returned.
9212 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op) {
9213   assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
9214 
9215   // Check to see if there is no change.
9216   if (Op == N->getOperand(0)) return N;
9217 
9218   // See if the modified node already exists.
9219   void *InsertPos = nullptr;
9220   if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
9221     return Existing;
9222 
9223   // Nope it doesn't.  Remove the node from its current place in the maps.
9224   if (InsertPos)
9225     if (!RemoveNodeFromCSEMaps(N))
9226       InsertPos = nullptr;
9227 
9228   // Now we update the operands.
9229   N->OperandList[0].set(Op);
9230 
9231   updateDivergence(N);
9232   // If this gets put into a CSE map, add it.
9233   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
9234   return N;
9235 }
9236 
9237 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2) {
9238   assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
9239 
9240   // Check to see if there is no change.
9241   if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
9242     return N;   // No operands changed, just return the input node.
9243 
9244   // See if the modified node already exists.
9245   void *InsertPos = nullptr;
9246   if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
9247     return Existing;
9248 
9249   // Nope it doesn't.  Remove the node from its current place in the maps.
9250   if (InsertPos)
9251     if (!RemoveNodeFromCSEMaps(N))
9252       InsertPos = nullptr;
9253 
9254   // Now we update the operands.
9255   if (N->OperandList[0] != Op1)
9256     N->OperandList[0].set(Op1);
9257   if (N->OperandList[1] != Op2)
9258     N->OperandList[1].set(Op2);
9259 
9260   updateDivergence(N);
9261   // If this gets put into a CSE map, add it.
9262   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
9263   return N;
9264 }
9265 
9266 SDNode *SelectionDAG::
9267 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, SDValue Op3) {
9268   SDValue Ops[] = { Op1, Op2, Op3 };
9269   return UpdateNodeOperands(N, Ops);
9270 }
9271 
9272 SDNode *SelectionDAG::
9273 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
9274                    SDValue Op3, SDValue Op4) {
9275   SDValue Ops[] = { Op1, Op2, Op3, Op4 };
9276   return UpdateNodeOperands(N, Ops);
9277 }
9278 
9279 SDNode *SelectionDAG::
9280 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
9281                    SDValue Op3, SDValue Op4, SDValue Op5) {
9282   SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 };
9283   return UpdateNodeOperands(N, Ops);
9284 }
9285 
9286 SDNode *SelectionDAG::
9287 UpdateNodeOperands(SDNode *N, ArrayRef<SDValue> Ops) {
9288   unsigned NumOps = Ops.size();
9289   assert(N->getNumOperands() == NumOps &&
9290          "Update with wrong number of operands");
9291 
9292   // If no operands changed just return the input node.
9293   if (std::equal(Ops.begin(), Ops.end(), N->op_begin()))
9294     return N;
9295 
9296   // See if the modified node already exists.
9297   void *InsertPos = nullptr;
9298   if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertPos))
9299     return Existing;
9300 
9301   // Nope it doesn't.  Remove the node from its current place in the maps.
9302   if (InsertPos)
9303     if (!RemoveNodeFromCSEMaps(N))
9304       InsertPos = nullptr;
9305 
9306   // Now we update the operands.
9307   for (unsigned i = 0; i != NumOps; ++i)
9308     if (N->OperandList[i] != Ops[i])
9309       N->OperandList[i].set(Ops[i]);
9310 
9311   updateDivergence(N);
9312   // If this gets put into a CSE map, add it.
9313   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
9314   return N;
9315 }
9316 
9317 /// DropOperands - Release the operands and set this node to have
9318 /// zero operands.
9319 void SDNode::DropOperands() {
9320   // Unlike the code in MorphNodeTo that does this, we don't need to
9321   // watch for dead nodes here.
9322   for (op_iterator I = op_begin(), E = op_end(); I != E; ) {
9323     SDUse &Use = *I++;
9324     Use.set(SDValue());
9325   }
9326 }
9327 
9328 void SelectionDAG::setNodeMemRefs(MachineSDNode *N,
9329                                   ArrayRef<MachineMemOperand *> NewMemRefs) {
9330   if (NewMemRefs.empty()) {
9331     N->clearMemRefs();
9332     return;
9333   }
9334 
9335   // Check if we can avoid allocating by storing a single reference directly.
9336   if (NewMemRefs.size() == 1) {
9337     N->MemRefs = NewMemRefs[0];
9338     N->NumMemRefs = 1;
9339     return;
9340   }
9341 
9342   MachineMemOperand **MemRefsBuffer =
9343       Allocator.template Allocate<MachineMemOperand *>(NewMemRefs.size());
9344   llvm::copy(NewMemRefs, MemRefsBuffer);
9345   N->MemRefs = MemRefsBuffer;
9346   N->NumMemRefs = static_cast<int>(NewMemRefs.size());
9347 }
9348 
9349 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a
9350 /// machine opcode.
9351 ///
9352 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9353                                    EVT VT) {
9354   SDVTList VTs = getVTList(VT);
9355   return SelectNodeTo(N, MachineOpc, VTs, None);
9356 }
9357 
9358 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9359                                    EVT VT, SDValue Op1) {
9360   SDVTList VTs = getVTList(VT);
9361   SDValue Ops[] = { Op1 };
9362   return SelectNodeTo(N, MachineOpc, VTs, Ops);
9363 }
9364 
9365 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9366                                    EVT VT, SDValue Op1,
9367                                    SDValue Op2) {
9368   SDVTList VTs = getVTList(VT);
9369   SDValue Ops[] = { Op1, Op2 };
9370   return SelectNodeTo(N, MachineOpc, VTs, Ops);
9371 }
9372 
9373 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9374                                    EVT VT, SDValue Op1,
9375                                    SDValue Op2, SDValue Op3) {
9376   SDVTList VTs = getVTList(VT);
9377   SDValue Ops[] = { Op1, Op2, Op3 };
9378   return SelectNodeTo(N, MachineOpc, VTs, Ops);
9379 }
9380 
9381 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9382                                    EVT VT, ArrayRef<SDValue> Ops) {
9383   SDVTList VTs = getVTList(VT);
9384   return SelectNodeTo(N, MachineOpc, VTs, Ops);
9385 }
9386 
9387 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9388                                    EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) {
9389   SDVTList VTs = getVTList(VT1, VT2);
9390   return SelectNodeTo(N, MachineOpc, VTs, Ops);
9391 }
9392 
9393 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9394                                    EVT VT1, EVT VT2) {
9395   SDVTList VTs = getVTList(VT1, VT2);
9396   return SelectNodeTo(N, MachineOpc, VTs, None);
9397 }
9398 
9399 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9400                                    EVT VT1, EVT VT2, EVT VT3,
9401                                    ArrayRef<SDValue> Ops) {
9402   SDVTList VTs = getVTList(VT1, VT2, VT3);
9403   return SelectNodeTo(N, MachineOpc, VTs, Ops);
9404 }
9405 
9406 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9407                                    EVT VT1, EVT VT2,
9408                                    SDValue Op1, SDValue Op2) {
9409   SDVTList VTs = getVTList(VT1, VT2);
9410   SDValue Ops[] = { Op1, Op2 };
9411   return SelectNodeTo(N, MachineOpc, VTs, Ops);
9412 }
9413 
9414 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9415                                    SDVTList VTs,ArrayRef<SDValue> Ops) {
9416   SDNode *New = MorphNodeTo(N, ~MachineOpc, VTs, Ops);
9417   // Reset the NodeID to -1.
9418   New->setNodeId(-1);
9419   if (New != N) {
9420     ReplaceAllUsesWith(N, New);
9421     RemoveDeadNode(N);
9422   }
9423   return New;
9424 }
9425 
9426 /// UpdateSDLocOnMergeSDNode - If the opt level is -O0 then it throws away
9427 /// the line number information on the merged node since it is not possible to
9428 /// preserve the information that operation is associated with multiple lines.
9429 /// This will make the debugger working better at -O0, were there is a higher
9430 /// probability having other instructions associated with that line.
9431 ///
9432 /// For IROrder, we keep the smaller of the two
9433 SDNode *SelectionDAG::UpdateSDLocOnMergeSDNode(SDNode *N, const SDLoc &OLoc) {
9434   DebugLoc NLoc = N->getDebugLoc();
9435   if (NLoc && OptLevel == CodeGenOpt::None && OLoc.getDebugLoc() != NLoc) {
9436     N->setDebugLoc(DebugLoc());
9437   }
9438   unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder());
9439   N->setIROrder(Order);
9440   return N;
9441 }
9442 
9443 /// MorphNodeTo - This *mutates* the specified node to have the specified
9444 /// return type, opcode, and operands.
9445 ///
9446 /// Note that MorphNodeTo returns the resultant node.  If there is already a
9447 /// node of the specified opcode and operands, it returns that node instead of
9448 /// the current one.  Note that the SDLoc need not be the same.
9449 ///
9450 /// Using MorphNodeTo is faster than creating a new node and swapping it in
9451 /// with ReplaceAllUsesWith both because it often avoids allocating a new
9452 /// node, and because it doesn't require CSE recalculation for any of
9453 /// the node's users.
9454 ///
9455 /// However, note that MorphNodeTo recursively deletes dead nodes from the DAG.
9456 /// As a consequence it isn't appropriate to use from within the DAG combiner or
9457 /// the legalizer which maintain worklists that would need to be updated when
9458 /// deleting things.
9459 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
9460                                   SDVTList VTs, ArrayRef<SDValue> Ops) {
9461   // If an identical node already exists, use it.
9462   void *IP = nullptr;
9463   if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) {
9464     FoldingSetNodeID ID;
9465     AddNodeIDNode(ID, Opc, VTs, Ops);
9466     if (SDNode *ON = FindNodeOrInsertPos(ID, SDLoc(N), IP))
9467       return UpdateSDLocOnMergeSDNode(ON, SDLoc(N));
9468   }
9469 
9470   if (!RemoveNodeFromCSEMaps(N))
9471     IP = nullptr;
9472 
9473   // Start the morphing.
9474   N->NodeType = Opc;
9475   N->ValueList = VTs.VTs;
9476   N->NumValues = VTs.NumVTs;
9477 
9478   // Clear the operands list, updating used nodes to remove this from their
9479   // use list.  Keep track of any operands that become dead as a result.
9480   SmallPtrSet<SDNode*, 16> DeadNodeSet;
9481   for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
9482     SDUse &Use = *I++;
9483     SDNode *Used = Use.getNode();
9484     Use.set(SDValue());
9485     if (Used->use_empty())
9486       DeadNodeSet.insert(Used);
9487   }
9488 
9489   // For MachineNode, initialize the memory references information.
9490   if (MachineSDNode *MN = dyn_cast<MachineSDNode>(N))
9491     MN->clearMemRefs();
9492 
9493   // Swap for an appropriately sized array from the recycler.
9494   removeOperands(N);
9495   createOperands(N, Ops);
9496 
9497   // Delete any nodes that are still dead after adding the uses for the
9498   // new operands.
9499   if (!DeadNodeSet.empty()) {
9500     SmallVector<SDNode *, 16> DeadNodes;
9501     for (SDNode *N : DeadNodeSet)
9502       if (N->use_empty())
9503         DeadNodes.push_back(N);
9504     RemoveDeadNodes(DeadNodes);
9505   }
9506 
9507   if (IP)
9508     CSEMap.InsertNode(N, IP);   // Memoize the new node.
9509   return N;
9510 }
9511 
9512 SDNode* SelectionDAG::mutateStrictFPToFP(SDNode *Node) {
9513   unsigned OrigOpc = Node->getOpcode();
9514   unsigned NewOpc;
9515   switch (OrigOpc) {
9516   default:
9517     llvm_unreachable("mutateStrictFPToFP called with unexpected opcode!");
9518 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
9519   case ISD::STRICT_##DAGN: NewOpc = ISD::DAGN; break;
9520 #define CMP_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
9521   case ISD::STRICT_##DAGN: NewOpc = ISD::SETCC; break;
9522 #include "llvm/IR/ConstrainedOps.def"
9523   }
9524 
9525   assert(Node->getNumValues() == 2 && "Unexpected number of results!");
9526 
9527   // We're taking this node out of the chain, so we need to re-link things.
9528   SDValue InputChain = Node->getOperand(0);
9529   SDValue OutputChain = SDValue(Node, 1);
9530   ReplaceAllUsesOfValueWith(OutputChain, InputChain);
9531 
9532   SmallVector<SDValue, 3> Ops;
9533   for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
9534     Ops.push_back(Node->getOperand(i));
9535 
9536   SDVTList VTs = getVTList(Node->getValueType(0));
9537   SDNode *Res = MorphNodeTo(Node, NewOpc, VTs, Ops);
9538 
9539   // MorphNodeTo can operate in two ways: if an existing node with the
9540   // specified operands exists, it can just return it.  Otherwise, it
9541   // updates the node in place to have the requested operands.
9542   if (Res == Node) {
9543     // If we updated the node in place, reset the node ID.  To the isel,
9544     // this should be just like a newly allocated machine node.
9545     Res->setNodeId(-1);
9546   } else {
9547     ReplaceAllUsesWith(Node, Res);
9548     RemoveDeadNode(Node);
9549   }
9550 
9551   return Res;
9552 }
9553 
9554 /// getMachineNode - These are used for target selectors to create a new node
9555 /// with specified return type(s), MachineInstr opcode, and operands.
9556 ///
9557 /// Note that getMachineNode returns the resultant node.  If there is already a
9558 /// node of the specified opcode and operands, it returns that node instead of
9559 /// the current one.
9560 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9561                                             EVT VT) {
9562   SDVTList VTs = getVTList(VT);
9563   return getMachineNode(Opcode, dl, VTs, None);
9564 }
9565 
9566 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9567                                             EVT VT, SDValue Op1) {
9568   SDVTList VTs = getVTList(VT);
9569   SDValue Ops[] = { Op1 };
9570   return getMachineNode(Opcode, dl, VTs, Ops);
9571 }
9572 
9573 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9574                                             EVT VT, SDValue Op1, SDValue Op2) {
9575   SDVTList VTs = getVTList(VT);
9576   SDValue Ops[] = { Op1, Op2 };
9577   return getMachineNode(Opcode, dl, VTs, Ops);
9578 }
9579 
9580 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9581                                             EVT VT, SDValue Op1, SDValue Op2,
9582                                             SDValue Op3) {
9583   SDVTList VTs = getVTList(VT);
9584   SDValue Ops[] = { Op1, Op2, Op3 };
9585   return getMachineNode(Opcode, dl, VTs, Ops);
9586 }
9587 
9588 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9589                                             EVT VT, ArrayRef<SDValue> Ops) {
9590   SDVTList VTs = getVTList(VT);
9591   return getMachineNode(Opcode, dl, VTs, Ops);
9592 }
9593 
9594 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9595                                             EVT VT1, EVT VT2, SDValue Op1,
9596                                             SDValue Op2) {
9597   SDVTList VTs = getVTList(VT1, VT2);
9598   SDValue Ops[] = { Op1, Op2 };
9599   return getMachineNode(Opcode, dl, VTs, Ops);
9600 }
9601 
9602 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9603                                             EVT VT1, EVT VT2, SDValue Op1,
9604                                             SDValue Op2, SDValue Op3) {
9605   SDVTList VTs = getVTList(VT1, VT2);
9606   SDValue Ops[] = { Op1, Op2, Op3 };
9607   return getMachineNode(Opcode, dl, VTs, Ops);
9608 }
9609 
9610 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9611                                             EVT VT1, EVT VT2,
9612                                             ArrayRef<SDValue> Ops) {
9613   SDVTList VTs = getVTList(VT1, VT2);
9614   return getMachineNode(Opcode, dl, VTs, Ops);
9615 }
9616 
9617 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9618                                             EVT VT1, EVT VT2, EVT VT3,
9619                                             SDValue Op1, SDValue Op2) {
9620   SDVTList VTs = getVTList(VT1, VT2, VT3);
9621   SDValue Ops[] = { Op1, Op2 };
9622   return getMachineNode(Opcode, dl, VTs, Ops);
9623 }
9624 
9625 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9626                                             EVT VT1, EVT VT2, EVT VT3,
9627                                             SDValue Op1, SDValue Op2,
9628                                             SDValue Op3) {
9629   SDVTList VTs = getVTList(VT1, VT2, VT3);
9630   SDValue Ops[] = { Op1, Op2, Op3 };
9631   return getMachineNode(Opcode, dl, VTs, Ops);
9632 }
9633 
9634 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9635                                             EVT VT1, EVT VT2, EVT VT3,
9636                                             ArrayRef<SDValue> Ops) {
9637   SDVTList VTs = getVTList(VT1, VT2, VT3);
9638   return getMachineNode(Opcode, dl, VTs, Ops);
9639 }
9640 
9641 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9642                                             ArrayRef<EVT> ResultTys,
9643                                             ArrayRef<SDValue> Ops) {
9644   SDVTList VTs = getVTList(ResultTys);
9645   return getMachineNode(Opcode, dl, VTs, Ops);
9646 }
9647 
9648 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &DL,
9649                                             SDVTList VTs,
9650                                             ArrayRef<SDValue> Ops) {
9651   bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue;
9652   MachineSDNode *N;
9653   void *IP = nullptr;
9654 
9655   if (DoCSE) {
9656     FoldingSetNodeID ID;
9657     AddNodeIDNode(ID, ~Opcode, VTs, Ops);
9658     IP = nullptr;
9659     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
9660       return cast<MachineSDNode>(UpdateSDLocOnMergeSDNode(E, DL));
9661     }
9662   }
9663 
9664   // Allocate a new MachineSDNode.
9665   N = newSDNode<MachineSDNode>(~Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
9666   createOperands(N, Ops);
9667 
9668   if (DoCSE)
9669     CSEMap.InsertNode(N, IP);
9670 
9671   InsertNode(N);
9672   NewSDValueDbgMsg(SDValue(N, 0), "Creating new machine node: ", this);
9673   return N;
9674 }
9675 
9676 /// getTargetExtractSubreg - A convenience function for creating
9677 /// TargetOpcode::EXTRACT_SUBREG nodes.
9678 SDValue SelectionDAG::getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT,
9679                                              SDValue Operand) {
9680   SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
9681   SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,
9682                                   VT, Operand, SRIdxVal);
9683   return SDValue(Subreg, 0);
9684 }
9685 
9686 /// getTargetInsertSubreg - A convenience function for creating
9687 /// TargetOpcode::INSERT_SUBREG nodes.
9688 SDValue SelectionDAG::getTargetInsertSubreg(int SRIdx, const SDLoc &DL, EVT VT,
9689                                             SDValue Operand, SDValue Subreg) {
9690   SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
9691   SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL,
9692                                   VT, Operand, Subreg, SRIdxVal);
9693   return SDValue(Result, 0);
9694 }
9695 
9696 /// getNodeIfExists - Get the specified node if it's already available, or
9697 /// else return NULL.
9698 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
9699                                       ArrayRef<SDValue> Ops) {
9700   SDNodeFlags Flags;
9701   if (Inserter)
9702     Flags = Inserter->getFlags();
9703   return getNodeIfExists(Opcode, VTList, Ops, Flags);
9704 }
9705 
9706 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
9707                                       ArrayRef<SDValue> Ops,
9708                                       const SDNodeFlags Flags) {
9709   if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
9710     FoldingSetNodeID ID;
9711     AddNodeIDNode(ID, Opcode, VTList, Ops);
9712     void *IP = nullptr;
9713     if (SDNode *E = FindNodeOrInsertPos(ID, SDLoc(), IP)) {
9714       E->intersectFlagsWith(Flags);
9715       return E;
9716     }
9717   }
9718   return nullptr;
9719 }
9720 
9721 /// doesNodeExist - Check if a node exists without modifying its flags.
9722 bool SelectionDAG::doesNodeExist(unsigned Opcode, SDVTList VTList,
9723                                  ArrayRef<SDValue> Ops) {
9724   if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
9725     FoldingSetNodeID ID;
9726     AddNodeIDNode(ID, Opcode, VTList, Ops);
9727     void *IP = nullptr;
9728     if (FindNodeOrInsertPos(ID, SDLoc(), IP))
9729       return true;
9730   }
9731   return false;
9732 }
9733 
9734 /// getDbgValue - Creates a SDDbgValue node.
9735 ///
9736 /// SDNode
9737 SDDbgValue *SelectionDAG::getDbgValue(DIVariable *Var, DIExpression *Expr,
9738                                       SDNode *N, unsigned R, bool IsIndirect,
9739                                       const DebugLoc &DL, unsigned O) {
9740   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9741          "Expected inlined-at fields to agree");
9742   return new (DbgInfo->getAlloc())
9743       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromNode(N, R),
9744                  {}, IsIndirect, DL, O,
9745                  /*IsVariadic=*/false);
9746 }
9747 
9748 /// Constant
9749 SDDbgValue *SelectionDAG::getConstantDbgValue(DIVariable *Var,
9750                                               DIExpression *Expr,
9751                                               const Value *C,
9752                                               const DebugLoc &DL, unsigned O) {
9753   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9754          "Expected inlined-at fields to agree");
9755   return new (DbgInfo->getAlloc())
9756       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromConst(C), {},
9757                  /*IsIndirect=*/false, DL, O,
9758                  /*IsVariadic=*/false);
9759 }
9760 
9761 /// FrameIndex
9762 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var,
9763                                                 DIExpression *Expr, unsigned FI,
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 getFrameIndexDbgValue(Var, Expr, FI, {}, IsIndirect, DL, O);
9770 }
9771 
9772 /// FrameIndex with dependencies
9773 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var,
9774                                                 DIExpression *Expr, unsigned FI,
9775                                                 ArrayRef<SDNode *> Dependencies,
9776                                                 bool IsIndirect,
9777                                                 const DebugLoc &DL,
9778                                                 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::fromFrameIdx(FI),
9783                  Dependencies, IsIndirect, DL, O,
9784                  /*IsVariadic=*/false);
9785 }
9786 
9787 /// VReg
9788 SDDbgValue *SelectionDAG::getVRegDbgValue(DIVariable *Var, DIExpression *Expr,
9789                                           unsigned VReg, bool IsIndirect,
9790                                           const DebugLoc &DL, unsigned O) {
9791   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9792          "Expected inlined-at fields to agree");
9793   return new (DbgInfo->getAlloc())
9794       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromVReg(VReg),
9795                  {}, IsIndirect, DL, O,
9796                  /*IsVariadic=*/false);
9797 }
9798 
9799 SDDbgValue *SelectionDAG::getDbgValueList(DIVariable *Var, DIExpression *Expr,
9800                                           ArrayRef<SDDbgOperand> Locs,
9801                                           ArrayRef<SDNode *> Dependencies,
9802                                           bool IsIndirect, const DebugLoc &DL,
9803                                           unsigned O, bool IsVariadic) {
9804   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9805          "Expected inlined-at fields to agree");
9806   return new (DbgInfo->getAlloc())
9807       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, Locs, Dependencies, IsIndirect,
9808                  DL, O, IsVariadic);
9809 }
9810 
9811 void SelectionDAG::transferDbgValues(SDValue From, SDValue To,
9812                                      unsigned OffsetInBits, unsigned SizeInBits,
9813                                      bool InvalidateDbg) {
9814   SDNode *FromNode = From.getNode();
9815   SDNode *ToNode = To.getNode();
9816   assert(FromNode && ToNode && "Can't modify dbg values");
9817 
9818   // PR35338
9819   // TODO: assert(From != To && "Redundant dbg value transfer");
9820   // TODO: assert(FromNode != ToNode && "Intranode dbg value transfer");
9821   if (From == To || FromNode == ToNode)
9822     return;
9823 
9824   if (!FromNode->getHasDebugValue())
9825     return;
9826 
9827   SDDbgOperand FromLocOp =
9828       SDDbgOperand::fromNode(From.getNode(), From.getResNo());
9829   SDDbgOperand ToLocOp = SDDbgOperand::fromNode(To.getNode(), To.getResNo());
9830 
9831   SmallVector<SDDbgValue *, 2> ClonedDVs;
9832   for (SDDbgValue *Dbg : GetDbgValues(FromNode)) {
9833     if (Dbg->isInvalidated())
9834       continue;
9835 
9836     // TODO: assert(!Dbg->isInvalidated() && "Transfer of invalid dbg value");
9837 
9838     // Create a new location ops vector that is equal to the old vector, but
9839     // with each instance of FromLocOp replaced with ToLocOp.
9840     bool Changed = false;
9841     auto NewLocOps = Dbg->copyLocationOps();
9842     std::replace_if(
9843         NewLocOps.begin(), NewLocOps.end(),
9844         [&Changed, FromLocOp](const SDDbgOperand &Op) {
9845           bool Match = Op == FromLocOp;
9846           Changed |= Match;
9847           return Match;
9848         },
9849         ToLocOp);
9850     // Ignore this SDDbgValue if we didn't find a matching location.
9851     if (!Changed)
9852       continue;
9853 
9854     DIVariable *Var = Dbg->getVariable();
9855     auto *Expr = Dbg->getExpression();
9856     // If a fragment is requested, update the expression.
9857     if (SizeInBits) {
9858       // When splitting a larger (e.g., sign-extended) value whose
9859       // lower bits are described with an SDDbgValue, do not attempt
9860       // to transfer the SDDbgValue to the upper bits.
9861       if (auto FI = Expr->getFragmentInfo())
9862         if (OffsetInBits + SizeInBits > FI->SizeInBits)
9863           continue;
9864       auto Fragment = DIExpression::createFragmentExpression(Expr, OffsetInBits,
9865                                                              SizeInBits);
9866       if (!Fragment)
9867         continue;
9868       Expr = *Fragment;
9869     }
9870 
9871     auto AdditionalDependencies = Dbg->getAdditionalDependencies();
9872     // Clone the SDDbgValue and move it to To.
9873     SDDbgValue *Clone = getDbgValueList(
9874         Var, Expr, NewLocOps, AdditionalDependencies, Dbg->isIndirect(),
9875         Dbg->getDebugLoc(), std::max(ToNode->getIROrder(), Dbg->getOrder()),
9876         Dbg->isVariadic());
9877     ClonedDVs.push_back(Clone);
9878 
9879     if (InvalidateDbg) {
9880       // Invalidate value and indicate the SDDbgValue should not be emitted.
9881       Dbg->setIsInvalidated();
9882       Dbg->setIsEmitted();
9883     }
9884   }
9885 
9886   for (SDDbgValue *Dbg : ClonedDVs) {
9887     assert(is_contained(Dbg->getSDNodes(), ToNode) &&
9888            "Transferred DbgValues should depend on the new SDNode");
9889     AddDbgValue(Dbg, false);
9890   }
9891 }
9892 
9893 void SelectionDAG::salvageDebugInfo(SDNode &N) {
9894   if (!N.getHasDebugValue())
9895     return;
9896 
9897   SmallVector<SDDbgValue *, 2> ClonedDVs;
9898   for (auto DV : GetDbgValues(&N)) {
9899     if (DV->isInvalidated())
9900       continue;
9901     switch (N.getOpcode()) {
9902     default:
9903       break;
9904     case ISD::ADD:
9905       SDValue N0 = N.getOperand(0);
9906       SDValue N1 = N.getOperand(1);
9907       if (!isConstantIntBuildVectorOrConstantInt(N0) &&
9908           isConstantIntBuildVectorOrConstantInt(N1)) {
9909         uint64_t Offset = N.getConstantOperandVal(1);
9910 
9911         // Rewrite an ADD constant node into a DIExpression. Since we are
9912         // performing arithmetic to compute the variable's *value* in the
9913         // DIExpression, we need to mark the expression with a
9914         // DW_OP_stack_value.
9915         auto *DIExpr = DV->getExpression();
9916         auto NewLocOps = DV->copyLocationOps();
9917         bool Changed = false;
9918         for (size_t i = 0; i < NewLocOps.size(); ++i) {
9919           // We're not given a ResNo to compare against because the whole
9920           // node is going away. We know that any ISD::ADD only has one
9921           // result, so we can assume any node match is using the result.
9922           if (NewLocOps[i].getKind() != SDDbgOperand::SDNODE ||
9923               NewLocOps[i].getSDNode() != &N)
9924             continue;
9925           NewLocOps[i] = SDDbgOperand::fromNode(N0.getNode(), N0.getResNo());
9926           SmallVector<uint64_t, 3> ExprOps;
9927           DIExpression::appendOffset(ExprOps, Offset);
9928           DIExpr = DIExpression::appendOpsToArg(DIExpr, ExprOps, i, true);
9929           Changed = true;
9930         }
9931         (void)Changed;
9932         assert(Changed && "Salvage target doesn't use N");
9933 
9934         auto AdditionalDependencies = DV->getAdditionalDependencies();
9935         SDDbgValue *Clone = getDbgValueList(DV->getVariable(), DIExpr,
9936                                             NewLocOps, AdditionalDependencies,
9937                                             DV->isIndirect(), DV->getDebugLoc(),
9938                                             DV->getOrder(), DV->isVariadic());
9939         ClonedDVs.push_back(Clone);
9940         DV->setIsInvalidated();
9941         DV->setIsEmitted();
9942         LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting";
9943                    N0.getNode()->dumprFull(this);
9944                    dbgs() << " into " << *DIExpr << '\n');
9945       }
9946     }
9947   }
9948 
9949   for (SDDbgValue *Dbg : ClonedDVs) {
9950     assert(!Dbg->getSDNodes().empty() &&
9951            "Salvaged DbgValue should depend on a new SDNode");
9952     AddDbgValue(Dbg, false);
9953   }
9954 }
9955 
9956 /// Creates a SDDbgLabel node.
9957 SDDbgLabel *SelectionDAG::getDbgLabel(DILabel *Label,
9958                                       const DebugLoc &DL, unsigned O) {
9959   assert(cast<DILabel>(Label)->isValidLocationForIntrinsic(DL) &&
9960          "Expected inlined-at fields to agree");
9961   return new (DbgInfo->getAlloc()) SDDbgLabel(Label, DL, O);
9962 }
9963 
9964 namespace {
9965 
9966 /// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node
9967 /// pointed to by a use iterator is deleted, increment the use iterator
9968 /// so that it doesn't dangle.
9969 ///
9970 class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener {
9971   SDNode::use_iterator &UI;
9972   SDNode::use_iterator &UE;
9973 
9974   void NodeDeleted(SDNode *N, SDNode *E) override {
9975     // Increment the iterator as needed.
9976     while (UI != UE && N == *UI)
9977       ++UI;
9978   }
9979 
9980 public:
9981   RAUWUpdateListener(SelectionDAG &d,
9982                      SDNode::use_iterator &ui,
9983                      SDNode::use_iterator &ue)
9984     : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {}
9985 };
9986 
9987 } // end anonymous namespace
9988 
9989 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
9990 /// This can cause recursive merging of nodes in the DAG.
9991 ///
9992 /// This version assumes From has a single result value.
9993 ///
9994 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To) {
9995   SDNode *From = FromN.getNode();
9996   assert(From->getNumValues() == 1 && FromN.getResNo() == 0 &&
9997          "Cannot replace with this method!");
9998   assert(From != To.getNode() && "Cannot replace uses of with self");
9999 
10000   // Preserve Debug Values
10001   transferDbgValues(FromN, To);
10002 
10003   // Iterate over all the existing uses of From. New uses will be added
10004   // to the beginning of the use list, which we avoid visiting.
10005   // This specifically avoids visiting uses of From that arise while the
10006   // replacement is happening, because any such uses would be the result
10007   // of CSE: If an existing node looks like From after one of its operands
10008   // is replaced by To, we don't want to replace of all its users with To
10009   // too. See PR3018 for more info.
10010   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
10011   RAUWUpdateListener Listener(*this, UI, UE);
10012   while (UI != UE) {
10013     SDNode *User = *UI;
10014 
10015     // This node is about to morph, remove its old self from the CSE maps.
10016     RemoveNodeFromCSEMaps(User);
10017 
10018     // A user can appear in a use list multiple times, and when this
10019     // happens the uses are usually next to each other in the list.
10020     // To help reduce the number of CSE recomputations, process all
10021     // the uses of this user that we can find this way.
10022     do {
10023       SDUse &Use = UI.getUse();
10024       ++UI;
10025       Use.set(To);
10026       if (To->isDivergent() != From->isDivergent())
10027         updateDivergence(User);
10028     } while (UI != UE && *UI == User);
10029     // Now that we have modified User, add it back to the CSE maps.  If it
10030     // already exists there, recursively merge the results together.
10031     AddModifiedNodeToCSEMaps(User);
10032   }
10033 
10034   // If we just RAUW'd the root, take note.
10035   if (FromN == getRoot())
10036     setRoot(To);
10037 }
10038 
10039 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
10040 /// This can cause recursive merging of nodes in the DAG.
10041 ///
10042 /// This version assumes that for each value of From, there is a
10043 /// corresponding value in To in the same position with the same type.
10044 ///
10045 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To) {
10046 #ifndef NDEBUG
10047   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
10048     assert((!From->hasAnyUseOfValue(i) ||
10049             From->getValueType(i) == To->getValueType(i)) &&
10050            "Cannot use this version of ReplaceAllUsesWith!");
10051 #endif
10052 
10053   // Handle the trivial case.
10054   if (From == To)
10055     return;
10056 
10057   // Preserve Debug Info. Only do this if there's a use.
10058   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
10059     if (From->hasAnyUseOfValue(i)) {
10060       assert((i < To->getNumValues()) && "Invalid To location");
10061       transferDbgValues(SDValue(From, i), SDValue(To, i));
10062     }
10063 
10064   // Iterate over just the existing users of From. See the comments in
10065   // the ReplaceAllUsesWith above.
10066   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
10067   RAUWUpdateListener Listener(*this, UI, UE);
10068   while (UI != UE) {
10069     SDNode *User = *UI;
10070 
10071     // This node is about to morph, remove its old self from the CSE maps.
10072     RemoveNodeFromCSEMaps(User);
10073 
10074     // A user can appear in a use list multiple times, and when this
10075     // happens the uses are usually next to each other in the list.
10076     // To help reduce the number of CSE recomputations, process all
10077     // the uses of this user that we can find this way.
10078     do {
10079       SDUse &Use = UI.getUse();
10080       ++UI;
10081       Use.setNode(To);
10082       if (To->isDivergent() != From->isDivergent())
10083         updateDivergence(User);
10084     } while (UI != UE && *UI == User);
10085 
10086     // Now that we have modified User, add it back to the CSE maps.  If it
10087     // already exists there, recursively merge the results together.
10088     AddModifiedNodeToCSEMaps(User);
10089   }
10090 
10091   // If we just RAUW'd the root, take note.
10092   if (From == getRoot().getNode())
10093     setRoot(SDValue(To, getRoot().getResNo()));
10094 }
10095 
10096 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
10097 /// This can cause recursive merging of nodes in the DAG.
10098 ///
10099 /// This version can replace From with any result values.  To must match the
10100 /// number and types of values returned by From.
10101 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, const SDValue *To) {
10102   if (From->getNumValues() == 1)  // Handle the simple case efficiently.
10103     return ReplaceAllUsesWith(SDValue(From, 0), To[0]);
10104 
10105   // Preserve Debug Info.
10106   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
10107     transferDbgValues(SDValue(From, i), To[i]);
10108 
10109   // Iterate over just the existing users of From. See the comments in
10110   // the ReplaceAllUsesWith above.
10111   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
10112   RAUWUpdateListener Listener(*this, UI, UE);
10113   while (UI != UE) {
10114     SDNode *User = *UI;
10115 
10116     // This node is about to morph, remove its old self from the CSE maps.
10117     RemoveNodeFromCSEMaps(User);
10118 
10119     // A user can appear in a use list multiple times, and when this happens the
10120     // uses are usually next to each other in the list.  To help reduce the
10121     // number of CSE and divergence recomputations, process all the uses of this
10122     // user that we can find this way.
10123     bool To_IsDivergent = false;
10124     do {
10125       SDUse &Use = UI.getUse();
10126       const SDValue &ToOp = To[Use.getResNo()];
10127       ++UI;
10128       Use.set(ToOp);
10129       To_IsDivergent |= ToOp->isDivergent();
10130     } while (UI != UE && *UI == User);
10131 
10132     if (To_IsDivergent != From->isDivergent())
10133       updateDivergence(User);
10134 
10135     // Now that we have modified User, add it back to the CSE maps.  If it
10136     // already exists there, recursively merge the results together.
10137     AddModifiedNodeToCSEMaps(User);
10138   }
10139 
10140   // If we just RAUW'd the root, take note.
10141   if (From == getRoot().getNode())
10142     setRoot(SDValue(To[getRoot().getResNo()]));
10143 }
10144 
10145 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
10146 /// uses of other values produced by From.getNode() alone.  The Deleted
10147 /// vector is handled the same way as for ReplaceAllUsesWith.
10148 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To){
10149   // Handle the really simple, really trivial case efficiently.
10150   if (From == To) return;
10151 
10152   // Handle the simple, trivial, case efficiently.
10153   if (From.getNode()->getNumValues() == 1) {
10154     ReplaceAllUsesWith(From, To);
10155     return;
10156   }
10157 
10158   // Preserve Debug Info.
10159   transferDbgValues(From, To);
10160 
10161   // Iterate over just the existing users of From. See the comments in
10162   // the ReplaceAllUsesWith above.
10163   SDNode::use_iterator UI = From.getNode()->use_begin(),
10164                        UE = From.getNode()->use_end();
10165   RAUWUpdateListener Listener(*this, UI, UE);
10166   while (UI != UE) {
10167     SDNode *User = *UI;
10168     bool UserRemovedFromCSEMaps = false;
10169 
10170     // A user can appear in a use list multiple times, and when this
10171     // happens the uses are usually next to each other in the list.
10172     // To help reduce the number of CSE recomputations, process all
10173     // the uses of this user that we can find this way.
10174     do {
10175       SDUse &Use = UI.getUse();
10176 
10177       // Skip uses of different values from the same node.
10178       if (Use.getResNo() != From.getResNo()) {
10179         ++UI;
10180         continue;
10181       }
10182 
10183       // If this node hasn't been modified yet, it's still in the CSE maps,
10184       // so remove its old self from the CSE maps.
10185       if (!UserRemovedFromCSEMaps) {
10186         RemoveNodeFromCSEMaps(User);
10187         UserRemovedFromCSEMaps = true;
10188       }
10189 
10190       ++UI;
10191       Use.set(To);
10192       if (To->isDivergent() != From->isDivergent())
10193         updateDivergence(User);
10194     } while (UI != UE && *UI == User);
10195     // We are iterating over all uses of the From node, so if a use
10196     // doesn't use the specific value, no changes are made.
10197     if (!UserRemovedFromCSEMaps)
10198       continue;
10199 
10200     // Now that we have modified User, add it back to the CSE maps.  If it
10201     // already exists there, recursively merge the results together.
10202     AddModifiedNodeToCSEMaps(User);
10203   }
10204 
10205   // If we just RAUW'd the root, take note.
10206   if (From == getRoot())
10207     setRoot(To);
10208 }
10209 
10210 namespace {
10211 
10212 /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith
10213 /// to record information about a use.
10214 struct UseMemo {
10215   SDNode *User;
10216   unsigned Index;
10217   SDUse *Use;
10218 };
10219 
10220 /// operator< - Sort Memos by User.
10221 bool operator<(const UseMemo &L, const UseMemo &R) {
10222   return (intptr_t)L.User < (intptr_t)R.User;
10223 }
10224 
10225 /// RAUOVWUpdateListener - Helper for ReplaceAllUsesOfValuesWith - When the node
10226 /// pointed to by a UseMemo is deleted, set the User to nullptr to indicate that
10227 /// the node already has been taken care of recursively.
10228 class RAUOVWUpdateListener : public SelectionDAG::DAGUpdateListener {
10229   SmallVector<UseMemo, 4> &Uses;
10230 
10231   void NodeDeleted(SDNode *N, SDNode *E) override {
10232     for (UseMemo &Memo : Uses)
10233       if (Memo.User == N)
10234         Memo.User = nullptr;
10235   }
10236 
10237 public:
10238   RAUOVWUpdateListener(SelectionDAG &d, SmallVector<UseMemo, 4> &uses)
10239       : SelectionDAG::DAGUpdateListener(d), Uses(uses) {}
10240 };
10241 
10242 } // end anonymous namespace
10243 
10244 bool SelectionDAG::calculateDivergence(SDNode *N) {
10245   if (TLI->isSDNodeAlwaysUniform(N)) {
10246     assert(!TLI->isSDNodeSourceOfDivergence(N, FLI, DA) &&
10247            "Conflicting divergence information!");
10248     return false;
10249   }
10250   if (TLI->isSDNodeSourceOfDivergence(N, FLI, DA))
10251     return true;
10252   for (auto &Op : N->ops()) {
10253     if (Op.Val.getValueType() != MVT::Other && Op.getNode()->isDivergent())
10254       return true;
10255   }
10256   return false;
10257 }
10258 
10259 void SelectionDAG::updateDivergence(SDNode *N) {
10260   SmallVector<SDNode *, 16> Worklist(1, N);
10261   do {
10262     N = Worklist.pop_back_val();
10263     bool IsDivergent = calculateDivergence(N);
10264     if (N->SDNodeBits.IsDivergent != IsDivergent) {
10265       N->SDNodeBits.IsDivergent = IsDivergent;
10266       llvm::append_range(Worklist, N->uses());
10267     }
10268   } while (!Worklist.empty());
10269 }
10270 
10271 void SelectionDAG::CreateTopologicalOrder(std::vector<SDNode *> &Order) {
10272   DenseMap<SDNode *, unsigned> Degree;
10273   Order.reserve(AllNodes.size());
10274   for (auto &N : allnodes()) {
10275     unsigned NOps = N.getNumOperands();
10276     Degree[&N] = NOps;
10277     if (0 == NOps)
10278       Order.push_back(&N);
10279   }
10280   for (size_t I = 0; I != Order.size(); ++I) {
10281     SDNode *N = Order[I];
10282     for (auto U : N->uses()) {
10283       unsigned &UnsortedOps = Degree[U];
10284       if (0 == --UnsortedOps)
10285         Order.push_back(U);
10286     }
10287   }
10288 }
10289 
10290 #ifndef NDEBUG
10291 void SelectionDAG::VerifyDAGDivergence() {
10292   std::vector<SDNode *> TopoOrder;
10293   CreateTopologicalOrder(TopoOrder);
10294   for (auto *N : TopoOrder) {
10295     assert(calculateDivergence(N) == N->isDivergent() &&
10296            "Divergence bit inconsistency detected");
10297   }
10298 }
10299 #endif
10300 
10301 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving
10302 /// uses of other values produced by From.getNode() alone.  The same value
10303 /// may appear in both the From and To list.  The Deleted vector is
10304 /// handled the same way as for ReplaceAllUsesWith.
10305 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From,
10306                                               const SDValue *To,
10307                                               unsigned Num){
10308   // Handle the simple, trivial case efficiently.
10309   if (Num == 1)
10310     return ReplaceAllUsesOfValueWith(*From, *To);
10311 
10312   transferDbgValues(*From, *To);
10313 
10314   // Read up all the uses and make records of them. This helps
10315   // processing new uses that are introduced during the
10316   // replacement process.
10317   SmallVector<UseMemo, 4> Uses;
10318   for (unsigned i = 0; i != Num; ++i) {
10319     unsigned FromResNo = From[i].getResNo();
10320     SDNode *FromNode = From[i].getNode();
10321     for (SDNode::use_iterator UI = FromNode->use_begin(),
10322          E = FromNode->use_end(); UI != E; ++UI) {
10323       SDUse &Use = UI.getUse();
10324       if (Use.getResNo() == FromResNo) {
10325         UseMemo Memo = { *UI, i, &Use };
10326         Uses.push_back(Memo);
10327       }
10328     }
10329   }
10330 
10331   // Sort the uses, so that all the uses from a given User are together.
10332   llvm::sort(Uses);
10333   RAUOVWUpdateListener Listener(*this, Uses);
10334 
10335   for (unsigned UseIndex = 0, UseIndexEnd = Uses.size();
10336        UseIndex != UseIndexEnd; ) {
10337     // We know that this user uses some value of From.  If it is the right
10338     // value, update it.
10339     SDNode *User = Uses[UseIndex].User;
10340     // If the node has been deleted by recursive CSE updates when updating
10341     // another node, then just skip this entry.
10342     if (User == nullptr) {
10343       ++UseIndex;
10344       continue;
10345     }
10346 
10347     // This node is about to morph, remove its old self from the CSE maps.
10348     RemoveNodeFromCSEMaps(User);
10349 
10350     // The Uses array is sorted, so all the uses for a given User
10351     // are next to each other in the list.
10352     // To help reduce the number of CSE recomputations, process all
10353     // the uses of this user that we can find this way.
10354     do {
10355       unsigned i = Uses[UseIndex].Index;
10356       SDUse &Use = *Uses[UseIndex].Use;
10357       ++UseIndex;
10358 
10359       Use.set(To[i]);
10360     } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User);
10361 
10362     // Now that we have modified User, add it back to the CSE maps.  If it
10363     // already exists there, recursively merge the results together.
10364     AddModifiedNodeToCSEMaps(User);
10365   }
10366 }
10367 
10368 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
10369 /// based on their topological order. It returns the maximum id and a vector
10370 /// of the SDNodes* in assigned order by reference.
10371 unsigned SelectionDAG::AssignTopologicalOrder() {
10372   unsigned DAGSize = 0;
10373 
10374   // SortedPos tracks the progress of the algorithm. Nodes before it are
10375   // sorted, nodes after it are unsorted. When the algorithm completes
10376   // it is at the end of the list.
10377   allnodes_iterator SortedPos = allnodes_begin();
10378 
10379   // Visit all the nodes. Move nodes with no operands to the front of
10380   // the list immediately. Annotate nodes that do have operands with their
10381   // operand count. Before we do this, the Node Id fields of the nodes
10382   // may contain arbitrary values. After, the Node Id fields for nodes
10383   // before SortedPos will contain the topological sort index, and the
10384   // Node Id fields for nodes At SortedPos and after will contain the
10385   // count of outstanding operands.
10386   for (SDNode &N : llvm::make_early_inc_range(allnodes())) {
10387     checkForCycles(&N, this);
10388     unsigned Degree = N.getNumOperands();
10389     if (Degree == 0) {
10390       // A node with no uses, add it to the result array immediately.
10391       N.setNodeId(DAGSize++);
10392       allnodes_iterator Q(&N);
10393       if (Q != SortedPos)
10394         SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q));
10395       assert(SortedPos != AllNodes.end() && "Overran node list");
10396       ++SortedPos;
10397     } else {
10398       // Temporarily use the Node Id as scratch space for the degree count.
10399       N.setNodeId(Degree);
10400     }
10401   }
10402 
10403   // Visit all the nodes. As we iterate, move nodes into sorted order,
10404   // such that by the time the end is reached all nodes will be sorted.
10405   for (SDNode &Node : allnodes()) {
10406     SDNode *N = &Node;
10407     checkForCycles(N, this);
10408     // N is in sorted position, so all its uses have one less operand
10409     // that needs to be sorted.
10410     for (SDNode *P : N->uses()) {
10411       unsigned Degree = P->getNodeId();
10412       assert(Degree != 0 && "Invalid node degree");
10413       --Degree;
10414       if (Degree == 0) {
10415         // All of P's operands are sorted, so P may sorted now.
10416         P->setNodeId(DAGSize++);
10417         if (P->getIterator() != SortedPos)
10418           SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P));
10419         assert(SortedPos != AllNodes.end() && "Overran node list");
10420         ++SortedPos;
10421       } else {
10422         // Update P's outstanding operand count.
10423         P->setNodeId(Degree);
10424       }
10425     }
10426     if (Node.getIterator() == SortedPos) {
10427 #ifndef NDEBUG
10428       allnodes_iterator I(N);
10429       SDNode *S = &*++I;
10430       dbgs() << "Overran sorted position:\n";
10431       S->dumprFull(this); dbgs() << "\n";
10432       dbgs() << "Checking if this is due to cycles\n";
10433       checkForCycles(this, true);
10434 #endif
10435       llvm_unreachable(nullptr);
10436     }
10437   }
10438 
10439   assert(SortedPos == AllNodes.end() &&
10440          "Topological sort incomplete!");
10441   assert(AllNodes.front().getOpcode() == ISD::EntryToken &&
10442          "First node in topological sort is not the entry token!");
10443   assert(AllNodes.front().getNodeId() == 0 &&
10444          "First node in topological sort has non-zero id!");
10445   assert(AllNodes.front().getNumOperands() == 0 &&
10446          "First node in topological sort has operands!");
10447   assert(AllNodes.back().getNodeId() == (int)DAGSize-1 &&
10448          "Last node in topologic sort has unexpected id!");
10449   assert(AllNodes.back().use_empty() &&
10450          "Last node in topologic sort has users!");
10451   assert(DAGSize == allnodes_size() && "Node count mismatch!");
10452   return DAGSize;
10453 }
10454 
10455 /// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the
10456 /// value is produced by SD.
10457 void SelectionDAG::AddDbgValue(SDDbgValue *DB, bool isParameter) {
10458   for (SDNode *SD : DB->getSDNodes()) {
10459     if (!SD)
10460       continue;
10461     assert(DbgInfo->getSDDbgValues(SD).empty() || SD->getHasDebugValue());
10462     SD->setHasDebugValue(true);
10463   }
10464   DbgInfo->add(DB, isParameter);
10465 }
10466 
10467 void SelectionDAG::AddDbgLabel(SDDbgLabel *DB) { DbgInfo->add(DB); }
10468 
10469 SDValue SelectionDAG::makeEquivalentMemoryOrdering(SDValue OldChain,
10470                                                    SDValue NewMemOpChain) {
10471   assert(isa<MemSDNode>(NewMemOpChain) && "Expected a memop node");
10472   assert(NewMemOpChain.getValueType() == MVT::Other && "Expected a token VT");
10473   // The new memory operation must have the same position as the old load in
10474   // terms of memory dependency. Create a TokenFactor for the old load and new
10475   // memory operation and update uses of the old load's output chain to use that
10476   // TokenFactor.
10477   if (OldChain == NewMemOpChain || OldChain.use_empty())
10478     return NewMemOpChain;
10479 
10480   SDValue TokenFactor = getNode(ISD::TokenFactor, SDLoc(OldChain), MVT::Other,
10481                                 OldChain, NewMemOpChain);
10482   ReplaceAllUsesOfValueWith(OldChain, TokenFactor);
10483   UpdateNodeOperands(TokenFactor.getNode(), OldChain, NewMemOpChain);
10484   return TokenFactor;
10485 }
10486 
10487 SDValue SelectionDAG::makeEquivalentMemoryOrdering(LoadSDNode *OldLoad,
10488                                                    SDValue NewMemOp) {
10489   assert(isa<MemSDNode>(NewMemOp.getNode()) && "Expected a memop node");
10490   SDValue OldChain = SDValue(OldLoad, 1);
10491   SDValue NewMemOpChain = NewMemOp.getValue(1);
10492   return makeEquivalentMemoryOrdering(OldChain, NewMemOpChain);
10493 }
10494 
10495 SDValue SelectionDAG::getSymbolFunctionGlobalAddress(SDValue Op,
10496                                                      Function **OutFunction) {
10497   assert(isa<ExternalSymbolSDNode>(Op) && "Node should be an ExternalSymbol");
10498 
10499   auto *Symbol = cast<ExternalSymbolSDNode>(Op)->getSymbol();
10500   auto *Module = MF->getFunction().getParent();
10501   auto *Function = Module->getFunction(Symbol);
10502 
10503   if (OutFunction != nullptr)
10504       *OutFunction = Function;
10505 
10506   if (Function != nullptr) {
10507     auto PtrTy = TLI->getPointerTy(getDataLayout(), Function->getAddressSpace());
10508     return getGlobalAddress(Function, SDLoc(Op), PtrTy);
10509   }
10510 
10511   std::string ErrorStr;
10512   raw_string_ostream ErrorFormatter(ErrorStr);
10513   ErrorFormatter << "Undefined external symbol ";
10514   ErrorFormatter << '"' << Symbol << '"';
10515   report_fatal_error(Twine(ErrorFormatter.str()));
10516 }
10517 
10518 //===----------------------------------------------------------------------===//
10519 //                              SDNode Class
10520 //===----------------------------------------------------------------------===//
10521 
10522 bool llvm::isNullConstant(SDValue V) {
10523   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
10524   return Const != nullptr && Const->isZero();
10525 }
10526 
10527 bool llvm::isNullFPConstant(SDValue V) {
10528   ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V);
10529   return Const != nullptr && Const->isZero() && !Const->isNegative();
10530 }
10531 
10532 bool llvm::isAllOnesConstant(SDValue V) {
10533   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
10534   return Const != nullptr && Const->isAllOnes();
10535 }
10536 
10537 bool llvm::isOneConstant(SDValue V) {
10538   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
10539   return Const != nullptr && Const->isOne();
10540 }
10541 
10542 bool llvm::isMinSignedConstant(SDValue V) {
10543   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
10544   return Const != nullptr && Const->isMinSignedValue();
10545 }
10546 
10547 SDValue llvm::peekThroughBitcasts(SDValue V) {
10548   while (V.getOpcode() == ISD::BITCAST)
10549     V = V.getOperand(0);
10550   return V;
10551 }
10552 
10553 SDValue llvm::peekThroughOneUseBitcasts(SDValue V) {
10554   while (V.getOpcode() == ISD::BITCAST && V.getOperand(0).hasOneUse())
10555     V = V.getOperand(0);
10556   return V;
10557 }
10558 
10559 SDValue llvm::peekThroughExtractSubvectors(SDValue V) {
10560   while (V.getOpcode() == ISD::EXTRACT_SUBVECTOR)
10561     V = V.getOperand(0);
10562   return V;
10563 }
10564 
10565 bool llvm::isBitwiseNot(SDValue V, bool AllowUndefs) {
10566   if (V.getOpcode() != ISD::XOR)
10567     return false;
10568   V = peekThroughBitcasts(V.getOperand(1));
10569   unsigned NumBits = V.getScalarValueSizeInBits();
10570   ConstantSDNode *C =
10571       isConstOrConstSplat(V, AllowUndefs, /*AllowTruncation*/ true);
10572   return C && (C->getAPIntValue().countTrailingOnes() >= NumBits);
10573 }
10574 
10575 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, bool AllowUndefs,
10576                                           bool AllowTruncation) {
10577   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
10578     return CN;
10579 
10580   // SplatVectors can truncate their operands. Ignore that case here unless
10581   // AllowTruncation is set.
10582   if (N->getOpcode() == ISD::SPLAT_VECTOR) {
10583     EVT VecEltVT = N->getValueType(0).getVectorElementType();
10584     if (auto *CN = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
10585       EVT CVT = CN->getValueType(0);
10586       assert(CVT.bitsGE(VecEltVT) && "Illegal splat_vector element extension");
10587       if (AllowTruncation || CVT == VecEltVT)
10588         return CN;
10589     }
10590   }
10591 
10592   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
10593     BitVector UndefElements;
10594     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
10595 
10596     // BuildVectors can truncate their operands. Ignore that case here unless
10597     // AllowTruncation is set.
10598     if (CN && (UndefElements.none() || AllowUndefs)) {
10599       EVT CVT = CN->getValueType(0);
10600       EVT NSVT = N.getValueType().getScalarType();
10601       assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension");
10602       if (AllowTruncation || (CVT == NSVT))
10603         return CN;
10604     }
10605   }
10606 
10607   return nullptr;
10608 }
10609 
10610 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, const APInt &DemandedElts,
10611                                           bool AllowUndefs,
10612                                           bool AllowTruncation) {
10613   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
10614     return CN;
10615 
10616   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
10617     BitVector UndefElements;
10618     ConstantSDNode *CN = BV->getConstantSplatNode(DemandedElts, &UndefElements);
10619 
10620     // BuildVectors can truncate their operands. Ignore that case here unless
10621     // AllowTruncation is set.
10622     if (CN && (UndefElements.none() || AllowUndefs)) {
10623       EVT CVT = CN->getValueType(0);
10624       EVT NSVT = N.getValueType().getScalarType();
10625       assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension");
10626       if (AllowTruncation || (CVT == NSVT))
10627         return CN;
10628     }
10629   }
10630 
10631   return nullptr;
10632 }
10633 
10634 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N, bool AllowUndefs) {
10635   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
10636     return CN;
10637 
10638   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
10639     BitVector UndefElements;
10640     ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
10641     if (CN && (UndefElements.none() || AllowUndefs))
10642       return CN;
10643   }
10644 
10645   if (N.getOpcode() == ISD::SPLAT_VECTOR)
10646     if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N.getOperand(0)))
10647       return CN;
10648 
10649   return nullptr;
10650 }
10651 
10652 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N,
10653                                               const APInt &DemandedElts,
10654                                               bool AllowUndefs) {
10655   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
10656     return CN;
10657 
10658   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
10659     BitVector UndefElements;
10660     ConstantFPSDNode *CN =
10661         BV->getConstantFPSplatNode(DemandedElts, &UndefElements);
10662     if (CN && (UndefElements.none() || AllowUndefs))
10663       return CN;
10664   }
10665 
10666   return nullptr;
10667 }
10668 
10669 bool llvm::isNullOrNullSplat(SDValue N, bool AllowUndefs) {
10670   // TODO: may want to use peekThroughBitcast() here.
10671   ConstantSDNode *C =
10672       isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation=*/true);
10673   return C && C->isZero();
10674 }
10675 
10676 bool llvm::isOneOrOneSplat(SDValue N, bool AllowUndefs) {
10677   ConstantSDNode *C =
10678       isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation*/ true);
10679   return C && C->isOne();
10680 }
10681 
10682 bool llvm::isAllOnesOrAllOnesSplat(SDValue N, bool AllowUndefs) {
10683   N = peekThroughBitcasts(N);
10684   unsigned BitWidth = N.getScalarValueSizeInBits();
10685   ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs);
10686   return C && C->isAllOnes() && C->getValueSizeInBits(0) == BitWidth;
10687 }
10688 
10689 HandleSDNode::~HandleSDNode() {
10690   DropOperands();
10691 }
10692 
10693 GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, unsigned Order,
10694                                          const DebugLoc &DL,
10695                                          const GlobalValue *GA, EVT VT,
10696                                          int64_t o, unsigned TF)
10697     : SDNode(Opc, Order, DL, getSDVTList(VT)), Offset(o), TargetFlags(TF) {
10698   TheGlobal = GA;
10699 }
10700 
10701 AddrSpaceCastSDNode::AddrSpaceCastSDNode(unsigned Order, const DebugLoc &dl,
10702                                          EVT VT, unsigned SrcAS,
10703                                          unsigned DestAS)
10704     : SDNode(ISD::ADDRSPACECAST, Order, dl, getSDVTList(VT)),
10705       SrcAddrSpace(SrcAS), DestAddrSpace(DestAS) {}
10706 
10707 MemSDNode::MemSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl,
10708                      SDVTList VTs, EVT memvt, MachineMemOperand *mmo)
10709     : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MMO(mmo) {
10710   MemSDNodeBits.IsVolatile = MMO->isVolatile();
10711   MemSDNodeBits.IsNonTemporal = MMO->isNonTemporal();
10712   MemSDNodeBits.IsDereferenceable = MMO->isDereferenceable();
10713   MemSDNodeBits.IsInvariant = MMO->isInvariant();
10714 
10715   // We check here that the size of the memory operand fits within the size of
10716   // the MMO. This is because the MMO might indicate only a possible address
10717   // range instead of specifying the affected memory addresses precisely.
10718   // TODO: Make MachineMemOperands aware of scalable vectors.
10719   assert(memvt.getStoreSize().getKnownMinSize() <= MMO->getSize() &&
10720          "Size mismatch!");
10721 }
10722 
10723 /// Profile - Gather unique data for the node.
10724 ///
10725 void SDNode::Profile(FoldingSetNodeID &ID) const {
10726   AddNodeIDNode(ID, this);
10727 }
10728 
10729 namespace {
10730 
10731   struct EVTArray {
10732     std::vector<EVT> VTs;
10733 
10734     EVTArray() {
10735       VTs.reserve(MVT::VALUETYPE_SIZE);
10736       for (unsigned i = 0; i < MVT::VALUETYPE_SIZE; ++i)
10737         VTs.push_back(MVT((MVT::SimpleValueType)i));
10738     }
10739   };
10740 
10741 } // end anonymous namespace
10742 
10743 static ManagedStatic<std::set<EVT, EVT::compareRawBits>> EVTs;
10744 static ManagedStatic<EVTArray> SimpleVTArray;
10745 static ManagedStatic<sys::SmartMutex<true>> VTMutex;
10746 
10747 /// getValueTypeList - Return a pointer to the specified value type.
10748 ///
10749 const EVT *SDNode::getValueTypeList(EVT VT) {
10750   if (VT.isExtended()) {
10751     sys::SmartScopedLock<true> Lock(*VTMutex);
10752     return &(*EVTs->insert(VT).first);
10753   }
10754   assert(VT.getSimpleVT() < MVT::VALUETYPE_SIZE && "Value type out of range!");
10755   return &SimpleVTArray->VTs[VT.getSimpleVT().SimpleTy];
10756 }
10757 
10758 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
10759 /// indicated value.  This method ignores uses of other values defined by this
10760 /// operation.
10761 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
10762   assert(Value < getNumValues() && "Bad value!");
10763 
10764   // TODO: Only iterate over uses of a given value of the node
10765   for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
10766     if (UI.getUse().getResNo() == Value) {
10767       if (NUses == 0)
10768         return false;
10769       --NUses;
10770     }
10771   }
10772 
10773   // Found exactly the right number of uses?
10774   return NUses == 0;
10775 }
10776 
10777 /// hasAnyUseOfValue - Return true if there are any use of the indicated
10778 /// value. This method ignores uses of other values defined by this operation.
10779 bool SDNode::hasAnyUseOfValue(unsigned Value) const {
10780   assert(Value < getNumValues() && "Bad value!");
10781 
10782   for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI)
10783     if (UI.getUse().getResNo() == Value)
10784       return true;
10785 
10786   return false;
10787 }
10788 
10789 /// isOnlyUserOf - Return true if this node is the only use of N.
10790 bool SDNode::isOnlyUserOf(const SDNode *N) const {
10791   bool Seen = false;
10792   for (const SDNode *User : N->uses()) {
10793     if (User == this)
10794       Seen = true;
10795     else
10796       return false;
10797   }
10798 
10799   return Seen;
10800 }
10801 
10802 /// Return true if the only users of N are contained in Nodes.
10803 bool SDNode::areOnlyUsersOf(ArrayRef<const SDNode *> Nodes, const SDNode *N) {
10804   bool Seen = false;
10805   for (const SDNode *User : N->uses()) {
10806     if (llvm::is_contained(Nodes, User))
10807       Seen = true;
10808     else
10809       return false;
10810   }
10811 
10812   return Seen;
10813 }
10814 
10815 /// isOperand - Return true if this node is an operand of N.
10816 bool SDValue::isOperandOf(const SDNode *N) const {
10817   return is_contained(N->op_values(), *this);
10818 }
10819 
10820 bool SDNode::isOperandOf(const SDNode *N) const {
10821   return any_of(N->op_values(),
10822                 [this](SDValue Op) { return this == Op.getNode(); });
10823 }
10824 
10825 /// reachesChainWithoutSideEffects - Return true if this operand (which must
10826 /// be a chain) reaches the specified operand without crossing any
10827 /// side-effecting instructions on any chain path.  In practice, this looks
10828 /// through token factors and non-volatile loads.  In order to remain efficient,
10829 /// this only looks a couple of nodes in, it does not do an exhaustive search.
10830 ///
10831 /// Note that we only need to examine chains when we're searching for
10832 /// side-effects; SelectionDAG requires that all side-effects are represented
10833 /// by chains, even if another operand would force a specific ordering. This
10834 /// constraint is necessary to allow transformations like splitting loads.
10835 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest,
10836                                              unsigned Depth) const {
10837   if (*this == Dest) return true;
10838 
10839   // Don't search too deeply, we just want to be able to see through
10840   // TokenFactor's etc.
10841   if (Depth == 0) return false;
10842 
10843   // If this is a token factor, all inputs to the TF happen in parallel.
10844   if (getOpcode() == ISD::TokenFactor) {
10845     // First, try a shallow search.
10846     if (is_contained((*this)->ops(), Dest)) {
10847       // We found the chain we want as an operand of this TokenFactor.
10848       // Essentially, we reach the chain without side-effects if we could
10849       // serialize the TokenFactor into a simple chain of operations with
10850       // Dest as the last operation. This is automatically true if the
10851       // chain has one use: there are no other ordering constraints.
10852       // If the chain has more than one use, we give up: some other
10853       // use of Dest might force a side-effect between Dest and the current
10854       // node.
10855       if (Dest.hasOneUse())
10856         return true;
10857     }
10858     // Next, try a deep search: check whether every operand of the TokenFactor
10859     // reaches Dest.
10860     return llvm::all_of((*this)->ops(), [=](SDValue Op) {
10861       return Op.reachesChainWithoutSideEffects(Dest, Depth - 1);
10862     });
10863   }
10864 
10865   // Loads don't have side effects, look through them.
10866   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
10867     if (Ld->isUnordered())
10868       return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
10869   }
10870   return false;
10871 }
10872 
10873 bool SDNode::hasPredecessor(const SDNode *N) const {
10874   SmallPtrSet<const SDNode *, 32> Visited;
10875   SmallVector<const SDNode *, 16> Worklist;
10876   Worklist.push_back(this);
10877   return hasPredecessorHelper(N, Visited, Worklist);
10878 }
10879 
10880 void SDNode::intersectFlagsWith(const SDNodeFlags Flags) {
10881   this->Flags.intersectWith(Flags);
10882 }
10883 
10884 SDValue
10885 SelectionDAG::matchBinOpReduction(SDNode *Extract, ISD::NodeType &BinOp,
10886                                   ArrayRef<ISD::NodeType> CandidateBinOps,
10887                                   bool AllowPartials) {
10888   // The pattern must end in an extract from index 0.
10889   if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10890       !isNullConstant(Extract->getOperand(1)))
10891     return SDValue();
10892 
10893   // Match against one of the candidate binary ops.
10894   SDValue Op = Extract->getOperand(0);
10895   if (llvm::none_of(CandidateBinOps, [Op](ISD::NodeType BinOp) {
10896         return Op.getOpcode() == unsigned(BinOp);
10897       }))
10898     return SDValue();
10899 
10900   // Floating-point reductions may require relaxed constraints on the final step
10901   // of the reduction because they may reorder intermediate operations.
10902   unsigned CandidateBinOp = Op.getOpcode();
10903   if (Op.getValueType().isFloatingPoint()) {
10904     SDNodeFlags Flags = Op->getFlags();
10905     switch (CandidateBinOp) {
10906     case ISD::FADD:
10907       if (!Flags.hasNoSignedZeros() || !Flags.hasAllowReassociation())
10908         return SDValue();
10909       break;
10910     default:
10911       llvm_unreachable("Unhandled FP opcode for binop reduction");
10912     }
10913   }
10914 
10915   // Matching failed - attempt to see if we did enough stages that a partial
10916   // reduction from a subvector is possible.
10917   auto PartialReduction = [&](SDValue Op, unsigned NumSubElts) {
10918     if (!AllowPartials || !Op)
10919       return SDValue();
10920     EVT OpVT = Op.getValueType();
10921     EVT OpSVT = OpVT.getScalarType();
10922     EVT SubVT = EVT::getVectorVT(*getContext(), OpSVT, NumSubElts);
10923     if (!TLI->isExtractSubvectorCheap(SubVT, OpVT, 0))
10924       return SDValue();
10925     BinOp = (ISD::NodeType)CandidateBinOp;
10926     return getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(Op), SubVT, Op,
10927                    getVectorIdxConstant(0, SDLoc(Op)));
10928   };
10929 
10930   // At each stage, we're looking for something that looks like:
10931   // %s = shufflevector <8 x i32> %op, <8 x i32> undef,
10932   //                    <8 x i32> <i32 2, i32 3, i32 undef, i32 undef,
10933   //                               i32 undef, i32 undef, i32 undef, i32 undef>
10934   // %a = binop <8 x i32> %op, %s
10935   // Where the mask changes according to the stage. E.g. for a 3-stage pyramid,
10936   // we expect something like:
10937   // <4,5,6,7,u,u,u,u>
10938   // <2,3,u,u,u,u,u,u>
10939   // <1,u,u,u,u,u,u,u>
10940   // While a partial reduction match would be:
10941   // <2,3,u,u,u,u,u,u>
10942   // <1,u,u,u,u,u,u,u>
10943   unsigned Stages = Log2_32(Op.getValueType().getVectorNumElements());
10944   SDValue PrevOp;
10945   for (unsigned i = 0; i < Stages; ++i) {
10946     unsigned MaskEnd = (1 << i);
10947 
10948     if (Op.getOpcode() != CandidateBinOp)
10949       return PartialReduction(PrevOp, MaskEnd);
10950 
10951     SDValue Op0 = Op.getOperand(0);
10952     SDValue Op1 = Op.getOperand(1);
10953 
10954     ShuffleVectorSDNode *Shuffle = dyn_cast<ShuffleVectorSDNode>(Op0);
10955     if (Shuffle) {
10956       Op = Op1;
10957     } else {
10958       Shuffle = dyn_cast<ShuffleVectorSDNode>(Op1);
10959       Op = Op0;
10960     }
10961 
10962     // The first operand of the shuffle should be the same as the other operand
10963     // of the binop.
10964     if (!Shuffle || Shuffle->getOperand(0) != Op)
10965       return PartialReduction(PrevOp, MaskEnd);
10966 
10967     // Verify the shuffle has the expected (at this stage of the pyramid) mask.
10968     for (int Index = 0; Index < (int)MaskEnd; ++Index)
10969       if (Shuffle->getMaskElt(Index) != (int)(MaskEnd + Index))
10970         return PartialReduction(PrevOp, MaskEnd);
10971 
10972     PrevOp = Op;
10973   }
10974 
10975   // Handle subvector reductions, which tend to appear after the shuffle
10976   // reduction stages.
10977   while (Op.getOpcode() == CandidateBinOp) {
10978     unsigned NumElts = Op.getValueType().getVectorNumElements();
10979     SDValue Op0 = Op.getOperand(0);
10980     SDValue Op1 = Op.getOperand(1);
10981     if (Op0.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
10982         Op1.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
10983         Op0.getOperand(0) != Op1.getOperand(0))
10984       break;
10985     SDValue Src = Op0.getOperand(0);
10986     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
10987     if (NumSrcElts != (2 * NumElts))
10988       break;
10989     if (!(Op0.getConstantOperandAPInt(1) == 0 &&
10990           Op1.getConstantOperandAPInt(1) == NumElts) &&
10991         !(Op1.getConstantOperandAPInt(1) == 0 &&
10992           Op0.getConstantOperandAPInt(1) == NumElts))
10993       break;
10994     Op = Src;
10995   }
10996 
10997   BinOp = (ISD::NodeType)CandidateBinOp;
10998   return Op;
10999 }
11000 
11001 SDValue SelectionDAG::UnrollVectorOp(SDNode *N, unsigned ResNE) {
11002   assert(N->getNumValues() == 1 &&
11003          "Can't unroll a vector with multiple results!");
11004 
11005   EVT VT = N->getValueType(0);
11006   unsigned NE = VT.getVectorNumElements();
11007   EVT EltVT = VT.getVectorElementType();
11008   SDLoc dl(N);
11009 
11010   SmallVector<SDValue, 8> Scalars;
11011   SmallVector<SDValue, 4> Operands(N->getNumOperands());
11012 
11013   // If ResNE is 0, fully unroll the vector op.
11014   if (ResNE == 0)
11015     ResNE = NE;
11016   else if (NE > ResNE)
11017     NE = ResNE;
11018 
11019   unsigned i;
11020   for (i= 0; i != NE; ++i) {
11021     for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) {
11022       SDValue Operand = N->getOperand(j);
11023       EVT OperandVT = Operand.getValueType();
11024       if (OperandVT.isVector()) {
11025         // A vector operand; extract a single element.
11026         EVT OperandEltVT = OperandVT.getVectorElementType();
11027         Operands[j] = getNode(ISD::EXTRACT_VECTOR_ELT, dl, OperandEltVT,
11028                               Operand, getVectorIdxConstant(i, dl));
11029       } else {
11030         // A scalar operand; just use it as is.
11031         Operands[j] = Operand;
11032       }
11033     }
11034 
11035     switch (N->getOpcode()) {
11036     default: {
11037       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands,
11038                                 N->getFlags()));
11039       break;
11040     }
11041     case ISD::VSELECT:
11042       Scalars.push_back(getNode(ISD::SELECT, dl, EltVT, Operands));
11043       break;
11044     case ISD::SHL:
11045     case ISD::SRA:
11046     case ISD::SRL:
11047     case ISD::ROTL:
11048     case ISD::ROTR:
11049       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0],
11050                                getShiftAmountOperand(Operands[0].getValueType(),
11051                                                      Operands[1])));
11052       break;
11053     case ISD::SIGN_EXTEND_INREG: {
11054       EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType();
11055       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT,
11056                                 Operands[0],
11057                                 getValueType(ExtVT)));
11058     }
11059     }
11060   }
11061 
11062   for (; i < ResNE; ++i)
11063     Scalars.push_back(getUNDEF(EltVT));
11064 
11065   EVT VecVT = EVT::getVectorVT(*getContext(), EltVT, ResNE);
11066   return getBuildVector(VecVT, dl, Scalars);
11067 }
11068 
11069 std::pair<SDValue, SDValue> SelectionDAG::UnrollVectorOverflowOp(
11070     SDNode *N, unsigned ResNE) {
11071   unsigned Opcode = N->getOpcode();
11072   assert((Opcode == ISD::UADDO || Opcode == ISD::SADDO ||
11073           Opcode == ISD::USUBO || Opcode == ISD::SSUBO ||
11074           Opcode == ISD::UMULO || Opcode == ISD::SMULO) &&
11075          "Expected an overflow opcode");
11076 
11077   EVT ResVT = N->getValueType(0);
11078   EVT OvVT = N->getValueType(1);
11079   EVT ResEltVT = ResVT.getVectorElementType();
11080   EVT OvEltVT = OvVT.getVectorElementType();
11081   SDLoc dl(N);
11082 
11083   // If ResNE is 0, fully unroll the vector op.
11084   unsigned NE = ResVT.getVectorNumElements();
11085   if (ResNE == 0)
11086     ResNE = NE;
11087   else if (NE > ResNE)
11088     NE = ResNE;
11089 
11090   SmallVector<SDValue, 8> LHSScalars;
11091   SmallVector<SDValue, 8> RHSScalars;
11092   ExtractVectorElements(N->getOperand(0), LHSScalars, 0, NE);
11093   ExtractVectorElements(N->getOperand(1), RHSScalars, 0, NE);
11094 
11095   EVT SVT = TLI->getSetCCResultType(getDataLayout(), *getContext(), ResEltVT);
11096   SDVTList VTs = getVTList(ResEltVT, SVT);
11097   SmallVector<SDValue, 8> ResScalars;
11098   SmallVector<SDValue, 8> OvScalars;
11099   for (unsigned i = 0; i < NE; ++i) {
11100     SDValue Res = getNode(Opcode, dl, VTs, LHSScalars[i], RHSScalars[i]);
11101     SDValue Ov =
11102         getSelect(dl, OvEltVT, Res.getValue(1),
11103                   getBoolConstant(true, dl, OvEltVT, ResVT),
11104                   getConstant(0, dl, OvEltVT));
11105 
11106     ResScalars.push_back(Res);
11107     OvScalars.push_back(Ov);
11108   }
11109 
11110   ResScalars.append(ResNE - NE, getUNDEF(ResEltVT));
11111   OvScalars.append(ResNE - NE, getUNDEF(OvEltVT));
11112 
11113   EVT NewResVT = EVT::getVectorVT(*getContext(), ResEltVT, ResNE);
11114   EVT NewOvVT = EVT::getVectorVT(*getContext(), OvEltVT, ResNE);
11115   return std::make_pair(getBuildVector(NewResVT, dl, ResScalars),
11116                         getBuildVector(NewOvVT, dl, OvScalars));
11117 }
11118 
11119 bool SelectionDAG::areNonVolatileConsecutiveLoads(LoadSDNode *LD,
11120                                                   LoadSDNode *Base,
11121                                                   unsigned Bytes,
11122                                                   int Dist) const {
11123   if (LD->isVolatile() || Base->isVolatile())
11124     return false;
11125   // TODO: probably too restrictive for atomics, revisit
11126   if (!LD->isSimple())
11127     return false;
11128   if (LD->isIndexed() || Base->isIndexed())
11129     return false;
11130   if (LD->getChain() != Base->getChain())
11131     return false;
11132   EVT VT = LD->getValueType(0);
11133   if (VT.getSizeInBits() / 8 != Bytes)
11134     return false;
11135 
11136   auto BaseLocDecomp = BaseIndexOffset::match(Base, *this);
11137   auto LocDecomp = BaseIndexOffset::match(LD, *this);
11138 
11139   int64_t Offset = 0;
11140   if (BaseLocDecomp.equalBaseIndex(LocDecomp, *this, Offset))
11141     return (Dist * Bytes == Offset);
11142   return false;
11143 }
11144 
11145 /// InferPtrAlignment - Infer alignment of a load / store address. Return None
11146 /// if it cannot be inferred.
11147 MaybeAlign SelectionDAG::InferPtrAlign(SDValue Ptr) const {
11148   // If this is a GlobalAddress + cst, return the alignment.
11149   const GlobalValue *GV = nullptr;
11150   int64_t GVOffset = 0;
11151   if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) {
11152     unsigned PtrWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
11153     KnownBits Known(PtrWidth);
11154     llvm::computeKnownBits(GV, Known, getDataLayout());
11155     unsigned AlignBits = Known.countMinTrailingZeros();
11156     if (AlignBits)
11157       return commonAlignment(Align(1ull << std::min(31U, AlignBits)), GVOffset);
11158   }
11159 
11160   // If this is a direct reference to a stack slot, use information about the
11161   // stack slot's alignment.
11162   int FrameIdx = INT_MIN;
11163   int64_t FrameOffset = 0;
11164   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) {
11165     FrameIdx = FI->getIndex();
11166   } else if (isBaseWithConstantOffset(Ptr) &&
11167              isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
11168     // Handle FI+Cst
11169     FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
11170     FrameOffset = Ptr.getConstantOperandVal(1);
11171   }
11172 
11173   if (FrameIdx != INT_MIN) {
11174     const MachineFrameInfo &MFI = getMachineFunction().getFrameInfo();
11175     return commonAlignment(MFI.getObjectAlign(FrameIdx), FrameOffset);
11176   }
11177 
11178   return None;
11179 }
11180 
11181 /// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type
11182 /// which is split (or expanded) into two not necessarily identical pieces.
11183 std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const {
11184   // Currently all types are split in half.
11185   EVT LoVT, HiVT;
11186   if (!VT.isVector())
11187     LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT);
11188   else
11189     LoVT = HiVT = VT.getHalfNumVectorElementsVT(*getContext());
11190 
11191   return std::make_pair(LoVT, HiVT);
11192 }
11193 
11194 /// GetDependentSplitDestVTs - Compute the VTs needed for the low/hi parts of a
11195 /// type, dependent on an enveloping VT that has been split into two identical
11196 /// pieces. Sets the HiIsEmpty flag when hi type has zero storage size.
11197 std::pair<EVT, EVT>
11198 SelectionDAG::GetDependentSplitDestVTs(const EVT &VT, const EVT &EnvVT,
11199                                        bool *HiIsEmpty) const {
11200   EVT EltTp = VT.getVectorElementType();
11201   // Examples:
11202   //   custom VL=8  with enveloping VL=8/8 yields 8/0 (hi empty)
11203   //   custom VL=9  with enveloping VL=8/8 yields 8/1
11204   //   custom VL=10 with enveloping VL=8/8 yields 8/2
11205   //   etc.
11206   ElementCount VTNumElts = VT.getVectorElementCount();
11207   ElementCount EnvNumElts = EnvVT.getVectorElementCount();
11208   assert(VTNumElts.isScalable() == EnvNumElts.isScalable() &&
11209          "Mixing fixed width and scalable vectors when enveloping a type");
11210   EVT LoVT, HiVT;
11211   if (VTNumElts.getKnownMinValue() > EnvNumElts.getKnownMinValue()) {
11212     LoVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts);
11213     HiVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts - EnvNumElts);
11214     *HiIsEmpty = false;
11215   } else {
11216     // Flag that hi type has zero storage size, but return split envelop type
11217     // (this would be easier if vector types with zero elements were allowed).
11218     LoVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts);
11219     HiVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts);
11220     *HiIsEmpty = true;
11221   }
11222   return std::make_pair(LoVT, HiVT);
11223 }
11224 
11225 /// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the
11226 /// low/high part.
11227 std::pair<SDValue, SDValue>
11228 SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT,
11229                           const EVT &HiVT) {
11230   assert(LoVT.isScalableVector() == HiVT.isScalableVector() &&
11231          LoVT.isScalableVector() == N.getValueType().isScalableVector() &&
11232          "Splitting vector with an invalid mixture of fixed and scalable "
11233          "vector types");
11234   assert(LoVT.getVectorMinNumElements() + HiVT.getVectorMinNumElements() <=
11235              N.getValueType().getVectorMinNumElements() &&
11236          "More vector elements requested than available!");
11237   SDValue Lo, Hi;
11238   Lo =
11239       getNode(ISD::EXTRACT_SUBVECTOR, DL, LoVT, N, getVectorIdxConstant(0, DL));
11240   // For scalable vectors it is safe to use LoVT.getVectorMinNumElements()
11241   // (rather than having to use ElementCount), because EXTRACT_SUBVECTOR scales
11242   // IDX with the runtime scaling factor of the result vector type. For
11243   // fixed-width result vectors, that runtime scaling factor is 1.
11244   Hi = getNode(ISD::EXTRACT_SUBVECTOR, DL, HiVT, N,
11245                getVectorIdxConstant(LoVT.getVectorMinNumElements(), DL));
11246   return std::make_pair(Lo, Hi);
11247 }
11248 
11249 std::pair<SDValue, SDValue> SelectionDAG::SplitEVL(SDValue N, EVT VecVT,
11250                                                    const SDLoc &DL) {
11251   // Split the vector length parameter.
11252   // %evl -> umin(%evl, %halfnumelts) and usubsat(%evl - %halfnumelts).
11253   EVT VT = N.getValueType();
11254   assert(VecVT.getVectorElementCount().isKnownEven() &&
11255          "Expecting the mask to be an evenly-sized vector");
11256   unsigned HalfMinNumElts = VecVT.getVectorMinNumElements() / 2;
11257   SDValue HalfNumElts =
11258       VecVT.isFixedLengthVector()
11259           ? getConstant(HalfMinNumElts, DL, VT)
11260           : getVScale(DL, VT, APInt(VT.getScalarSizeInBits(), HalfMinNumElts));
11261   SDValue Lo = getNode(ISD::UMIN, DL, VT, N, HalfNumElts);
11262   SDValue Hi = getNode(ISD::USUBSAT, DL, VT, N, HalfNumElts);
11263   return std::make_pair(Lo, Hi);
11264 }
11265 
11266 /// Widen the vector up to the next power of two using INSERT_SUBVECTOR.
11267 SDValue SelectionDAG::WidenVector(const SDValue &N, const SDLoc &DL) {
11268   EVT VT = N.getValueType();
11269   EVT WideVT = EVT::getVectorVT(*getContext(), VT.getVectorElementType(),
11270                                 NextPowerOf2(VT.getVectorNumElements()));
11271   return getNode(ISD::INSERT_SUBVECTOR, DL, WideVT, getUNDEF(WideVT), N,
11272                  getVectorIdxConstant(0, DL));
11273 }
11274 
11275 void SelectionDAG::ExtractVectorElements(SDValue Op,
11276                                          SmallVectorImpl<SDValue> &Args,
11277                                          unsigned Start, unsigned Count,
11278                                          EVT EltVT) {
11279   EVT VT = Op.getValueType();
11280   if (Count == 0)
11281     Count = VT.getVectorNumElements();
11282   if (EltVT == EVT())
11283     EltVT = VT.getVectorElementType();
11284   SDLoc SL(Op);
11285   for (unsigned i = Start, e = Start + Count; i != e; ++i) {
11286     Args.push_back(getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Op,
11287                            getVectorIdxConstant(i, SL)));
11288   }
11289 }
11290 
11291 // getAddressSpace - Return the address space this GlobalAddress belongs to.
11292 unsigned GlobalAddressSDNode::getAddressSpace() const {
11293   return getGlobal()->getType()->getAddressSpace();
11294 }
11295 
11296 Type *ConstantPoolSDNode::getType() const {
11297   if (isMachineConstantPoolEntry())
11298     return Val.MachineCPVal->getType();
11299   return Val.ConstVal->getType();
11300 }
11301 
11302 bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue, APInt &SplatUndef,
11303                                         unsigned &SplatBitSize,
11304                                         bool &HasAnyUndefs,
11305                                         unsigned MinSplatBits,
11306                                         bool IsBigEndian) const {
11307   EVT VT = getValueType(0);
11308   assert(VT.isVector() && "Expected a vector type");
11309   unsigned VecWidth = VT.getSizeInBits();
11310   if (MinSplatBits > VecWidth)
11311     return false;
11312 
11313   // FIXME: The widths are based on this node's type, but build vectors can
11314   // truncate their operands.
11315   SplatValue = APInt(VecWidth, 0);
11316   SplatUndef = APInt(VecWidth, 0);
11317 
11318   // Get the bits. Bits with undefined values (when the corresponding element
11319   // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared
11320   // in SplatValue. If any of the values are not constant, give up and return
11321   // false.
11322   unsigned int NumOps = getNumOperands();
11323   assert(NumOps > 0 && "isConstantSplat has 0-size build vector");
11324   unsigned EltWidth = VT.getScalarSizeInBits();
11325 
11326   for (unsigned j = 0; j < NumOps; ++j) {
11327     unsigned i = IsBigEndian ? NumOps - 1 - j : j;
11328     SDValue OpVal = getOperand(i);
11329     unsigned BitPos = j * EltWidth;
11330 
11331     if (OpVal.isUndef())
11332       SplatUndef.setBits(BitPos, BitPos + EltWidth);
11333     else if (auto *CN = dyn_cast<ConstantSDNode>(OpVal))
11334       SplatValue.insertBits(CN->getAPIntValue().zextOrTrunc(EltWidth), BitPos);
11335     else if (auto *CN = dyn_cast<ConstantFPSDNode>(OpVal))
11336       SplatValue.insertBits(CN->getValueAPF().bitcastToAPInt(), BitPos);
11337     else
11338       return false;
11339   }
11340 
11341   // The build_vector is all constants or undefs. Find the smallest element
11342   // size that splats the vector.
11343   HasAnyUndefs = (SplatUndef != 0);
11344 
11345   // FIXME: This does not work for vectors with elements less than 8 bits.
11346   while (VecWidth > 8) {
11347     unsigned HalfSize = VecWidth / 2;
11348     APInt HighValue = SplatValue.extractBits(HalfSize, HalfSize);
11349     APInt LowValue = SplatValue.extractBits(HalfSize, 0);
11350     APInt HighUndef = SplatUndef.extractBits(HalfSize, HalfSize);
11351     APInt LowUndef = SplatUndef.extractBits(HalfSize, 0);
11352 
11353     // If the two halves do not match (ignoring undef bits), stop here.
11354     if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) ||
11355         MinSplatBits > HalfSize)
11356       break;
11357 
11358     SplatValue = HighValue | LowValue;
11359     SplatUndef = HighUndef & LowUndef;
11360 
11361     VecWidth = HalfSize;
11362   }
11363 
11364   SplatBitSize = VecWidth;
11365   return true;
11366 }
11367 
11368 SDValue BuildVectorSDNode::getSplatValue(const APInt &DemandedElts,
11369                                          BitVector *UndefElements) const {
11370   unsigned NumOps = getNumOperands();
11371   if (UndefElements) {
11372     UndefElements->clear();
11373     UndefElements->resize(NumOps);
11374   }
11375   assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size");
11376   if (!DemandedElts)
11377     return SDValue();
11378   SDValue Splatted;
11379   for (unsigned i = 0; i != NumOps; ++i) {
11380     if (!DemandedElts[i])
11381       continue;
11382     SDValue Op = getOperand(i);
11383     if (Op.isUndef()) {
11384       if (UndefElements)
11385         (*UndefElements)[i] = true;
11386     } else if (!Splatted) {
11387       Splatted = Op;
11388     } else if (Splatted != Op) {
11389       return SDValue();
11390     }
11391   }
11392 
11393   if (!Splatted) {
11394     unsigned FirstDemandedIdx = DemandedElts.countTrailingZeros();
11395     assert(getOperand(FirstDemandedIdx).isUndef() &&
11396            "Can only have a splat without a constant for all undefs.");
11397     return getOperand(FirstDemandedIdx);
11398   }
11399 
11400   return Splatted;
11401 }
11402 
11403 SDValue BuildVectorSDNode::getSplatValue(BitVector *UndefElements) const {
11404   APInt DemandedElts = APInt::getAllOnes(getNumOperands());
11405   return getSplatValue(DemandedElts, UndefElements);
11406 }
11407 
11408 bool BuildVectorSDNode::getRepeatedSequence(const APInt &DemandedElts,
11409                                             SmallVectorImpl<SDValue> &Sequence,
11410                                             BitVector *UndefElements) const {
11411   unsigned NumOps = getNumOperands();
11412   Sequence.clear();
11413   if (UndefElements) {
11414     UndefElements->clear();
11415     UndefElements->resize(NumOps);
11416   }
11417   assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size");
11418   if (!DemandedElts || NumOps < 2 || !isPowerOf2_32(NumOps))
11419     return false;
11420 
11421   // Set the undefs even if we don't find a sequence (like getSplatValue).
11422   if (UndefElements)
11423     for (unsigned I = 0; I != NumOps; ++I)
11424       if (DemandedElts[I] && getOperand(I).isUndef())
11425         (*UndefElements)[I] = true;
11426 
11427   // Iteratively widen the sequence length looking for repetitions.
11428   for (unsigned SeqLen = 1; SeqLen < NumOps; SeqLen *= 2) {
11429     Sequence.append(SeqLen, SDValue());
11430     for (unsigned I = 0; I != NumOps; ++I) {
11431       if (!DemandedElts[I])
11432         continue;
11433       SDValue &SeqOp = Sequence[I % SeqLen];
11434       SDValue Op = getOperand(I);
11435       if (Op.isUndef()) {
11436         if (!SeqOp)
11437           SeqOp = Op;
11438         continue;
11439       }
11440       if (SeqOp && !SeqOp.isUndef() && SeqOp != Op) {
11441         Sequence.clear();
11442         break;
11443       }
11444       SeqOp = Op;
11445     }
11446     if (!Sequence.empty())
11447       return true;
11448   }
11449 
11450   assert(Sequence.empty() && "Failed to empty non-repeating sequence pattern");
11451   return false;
11452 }
11453 
11454 bool BuildVectorSDNode::getRepeatedSequence(SmallVectorImpl<SDValue> &Sequence,
11455                                             BitVector *UndefElements) const {
11456   APInt DemandedElts = APInt::getAllOnes(getNumOperands());
11457   return getRepeatedSequence(DemandedElts, Sequence, UndefElements);
11458 }
11459 
11460 ConstantSDNode *
11461 BuildVectorSDNode::getConstantSplatNode(const APInt &DemandedElts,
11462                                         BitVector *UndefElements) const {
11463   return dyn_cast_or_null<ConstantSDNode>(
11464       getSplatValue(DemandedElts, UndefElements));
11465 }
11466 
11467 ConstantSDNode *
11468 BuildVectorSDNode::getConstantSplatNode(BitVector *UndefElements) const {
11469   return dyn_cast_or_null<ConstantSDNode>(getSplatValue(UndefElements));
11470 }
11471 
11472 ConstantFPSDNode *
11473 BuildVectorSDNode::getConstantFPSplatNode(const APInt &DemandedElts,
11474                                           BitVector *UndefElements) const {
11475   return dyn_cast_or_null<ConstantFPSDNode>(
11476       getSplatValue(DemandedElts, UndefElements));
11477 }
11478 
11479 ConstantFPSDNode *
11480 BuildVectorSDNode::getConstantFPSplatNode(BitVector *UndefElements) const {
11481   return dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements));
11482 }
11483 
11484 int32_t
11485 BuildVectorSDNode::getConstantFPSplatPow2ToLog2Int(BitVector *UndefElements,
11486                                                    uint32_t BitWidth) const {
11487   if (ConstantFPSDNode *CN =
11488           dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements))) {
11489     bool IsExact;
11490     APSInt IntVal(BitWidth);
11491     const APFloat &APF = CN->getValueAPF();
11492     if (APF.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) !=
11493             APFloat::opOK ||
11494         !IsExact)
11495       return -1;
11496 
11497     return IntVal.exactLogBase2();
11498   }
11499   return -1;
11500 }
11501 
11502 bool BuildVectorSDNode::getConstantRawBits(
11503     bool IsLittleEndian, unsigned DstEltSizeInBits,
11504     SmallVectorImpl<APInt> &RawBitElements, BitVector &UndefElements) const {
11505   // Early-out if this contains anything but Undef/Constant/ConstantFP.
11506   if (!isConstant())
11507     return false;
11508 
11509   unsigned NumSrcOps = getNumOperands();
11510   unsigned SrcEltSizeInBits = getValueType(0).getScalarSizeInBits();
11511   assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 &&
11512          "Invalid bitcast scale");
11513 
11514   // Extract raw src bits.
11515   SmallVector<APInt> SrcBitElements(NumSrcOps,
11516                                     APInt::getNullValue(SrcEltSizeInBits));
11517   BitVector SrcUndeElements(NumSrcOps, false);
11518 
11519   for (unsigned I = 0; I != NumSrcOps; ++I) {
11520     SDValue Op = getOperand(I);
11521     if (Op.isUndef()) {
11522       SrcUndeElements.set(I);
11523       continue;
11524     }
11525     auto *CInt = dyn_cast<ConstantSDNode>(Op);
11526     auto *CFP = dyn_cast<ConstantFPSDNode>(Op);
11527     assert((CInt || CFP) && "Unknown constant");
11528     SrcBitElements[I] = CInt ? CInt->getAPIntValue().trunc(SrcEltSizeInBits)
11529                              : CFP->getValueAPF().bitcastToAPInt();
11530   }
11531 
11532   // Recast to dst width.
11533   recastRawBits(IsLittleEndian, DstEltSizeInBits, RawBitElements,
11534                 SrcBitElements, UndefElements, SrcUndeElements);
11535   return true;
11536 }
11537 
11538 void BuildVectorSDNode::recastRawBits(bool IsLittleEndian,
11539                                       unsigned DstEltSizeInBits,
11540                                       SmallVectorImpl<APInt> &DstBitElements,
11541                                       ArrayRef<APInt> SrcBitElements,
11542                                       BitVector &DstUndefElements,
11543                                       const BitVector &SrcUndefElements) {
11544   unsigned NumSrcOps = SrcBitElements.size();
11545   unsigned SrcEltSizeInBits = SrcBitElements[0].getBitWidth();
11546   assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 &&
11547          "Invalid bitcast scale");
11548   assert(NumSrcOps == SrcUndefElements.size() &&
11549          "Vector size mismatch");
11550 
11551   unsigned NumDstOps = (NumSrcOps * SrcEltSizeInBits) / DstEltSizeInBits;
11552   DstUndefElements.clear();
11553   DstUndefElements.resize(NumDstOps, false);
11554   DstBitElements.assign(NumDstOps, APInt::getNullValue(DstEltSizeInBits));
11555 
11556   // Concatenate src elements constant bits together into dst element.
11557   if (SrcEltSizeInBits <= DstEltSizeInBits) {
11558     unsigned Scale = DstEltSizeInBits / SrcEltSizeInBits;
11559     for (unsigned I = 0; I != NumDstOps; ++I) {
11560       DstUndefElements.set(I);
11561       APInt &DstBits = DstBitElements[I];
11562       for (unsigned J = 0; J != Scale; ++J) {
11563         unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1));
11564         if (SrcUndefElements[Idx])
11565           continue;
11566         DstUndefElements.reset(I);
11567         const APInt &SrcBits = SrcBitElements[Idx];
11568         assert(SrcBits.getBitWidth() == SrcEltSizeInBits &&
11569                "Illegal constant bitwidths");
11570         DstBits.insertBits(SrcBits, J * SrcEltSizeInBits);
11571       }
11572     }
11573     return;
11574   }
11575 
11576   // Split src element constant bits into dst elements.
11577   unsigned Scale = SrcEltSizeInBits / DstEltSizeInBits;
11578   for (unsigned I = 0; I != NumSrcOps; ++I) {
11579     if (SrcUndefElements[I]) {
11580       DstUndefElements.set(I * Scale, (I + 1) * Scale);
11581       continue;
11582     }
11583     const APInt &SrcBits = SrcBitElements[I];
11584     for (unsigned J = 0; J != Scale; ++J) {
11585       unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1));
11586       APInt &DstBits = DstBitElements[Idx];
11587       DstBits = SrcBits.extractBits(DstEltSizeInBits, J * DstEltSizeInBits);
11588     }
11589   }
11590 }
11591 
11592 bool BuildVectorSDNode::isConstant() const {
11593   for (const SDValue &Op : op_values()) {
11594     unsigned Opc = Op.getOpcode();
11595     if (Opc != ISD::UNDEF && Opc != ISD::Constant && Opc != ISD::ConstantFP)
11596       return false;
11597   }
11598   return true;
11599 }
11600 
11601 bool ShuffleVectorSDNode::isSplatMask(const int *Mask, EVT VT) {
11602   // Find the first non-undef value in the shuffle mask.
11603   unsigned i, e;
11604   for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i)
11605     /* search */;
11606 
11607   // If all elements are undefined, this shuffle can be considered a splat
11608   // (although it should eventually get simplified away completely).
11609   if (i == e)
11610     return true;
11611 
11612   // Make sure all remaining elements are either undef or the same as the first
11613   // non-undef value.
11614   for (int Idx = Mask[i]; i != e; ++i)
11615     if (Mask[i] >= 0 && Mask[i] != Idx)
11616       return false;
11617   return true;
11618 }
11619 
11620 // Returns the SDNode if it is a constant integer BuildVector
11621 // or constant integer.
11622 SDNode *SelectionDAG::isConstantIntBuildVectorOrConstantInt(SDValue N) const {
11623   if (isa<ConstantSDNode>(N))
11624     return N.getNode();
11625   if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
11626     return N.getNode();
11627   // Treat a GlobalAddress supporting constant offset folding as a
11628   // constant integer.
11629   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N))
11630     if (GA->getOpcode() == ISD::GlobalAddress &&
11631         TLI->isOffsetFoldingLegal(GA))
11632       return GA;
11633   if ((N.getOpcode() == ISD::SPLAT_VECTOR) &&
11634       isa<ConstantSDNode>(N.getOperand(0)))
11635     return N.getNode();
11636   return nullptr;
11637 }
11638 
11639 // Returns the SDNode if it is a constant float BuildVector
11640 // or constant float.
11641 SDNode *SelectionDAG::isConstantFPBuildVectorOrConstantFP(SDValue N) const {
11642   if (isa<ConstantFPSDNode>(N))
11643     return N.getNode();
11644 
11645   if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
11646     return N.getNode();
11647 
11648   if ((N.getOpcode() == ISD::SPLAT_VECTOR) &&
11649       isa<ConstantFPSDNode>(N.getOperand(0)))
11650     return N.getNode();
11651 
11652   return nullptr;
11653 }
11654 
11655 void SelectionDAG::createOperands(SDNode *Node, ArrayRef<SDValue> Vals) {
11656   assert(!Node->OperandList && "Node already has operands");
11657   assert(SDNode::getMaxNumOperands() >= Vals.size() &&
11658          "too many operands to fit into SDNode");
11659   SDUse *Ops = OperandRecycler.allocate(
11660       ArrayRecycler<SDUse>::Capacity::get(Vals.size()), OperandAllocator);
11661 
11662   bool IsDivergent = false;
11663   for (unsigned I = 0; I != Vals.size(); ++I) {
11664     Ops[I].setUser(Node);
11665     Ops[I].setInitial(Vals[I]);
11666     if (Ops[I].Val.getValueType() != MVT::Other) // Skip Chain. It does not carry divergence.
11667       IsDivergent |= Ops[I].getNode()->isDivergent();
11668   }
11669   Node->NumOperands = Vals.size();
11670   Node->OperandList = Ops;
11671   if (!TLI->isSDNodeAlwaysUniform(Node)) {
11672     IsDivergent |= TLI->isSDNodeSourceOfDivergence(Node, FLI, DA);
11673     Node->SDNodeBits.IsDivergent = IsDivergent;
11674   }
11675   checkForCycles(Node);
11676 }
11677 
11678 SDValue SelectionDAG::getTokenFactor(const SDLoc &DL,
11679                                      SmallVectorImpl<SDValue> &Vals) {
11680   size_t Limit = SDNode::getMaxNumOperands();
11681   while (Vals.size() > Limit) {
11682     unsigned SliceIdx = Vals.size() - Limit;
11683     auto ExtractedTFs = ArrayRef<SDValue>(Vals).slice(SliceIdx, Limit);
11684     SDValue NewTF = getNode(ISD::TokenFactor, DL, MVT::Other, ExtractedTFs);
11685     Vals.erase(Vals.begin() + SliceIdx, Vals.end());
11686     Vals.emplace_back(NewTF);
11687   }
11688   return getNode(ISD::TokenFactor, DL, MVT::Other, Vals);
11689 }
11690 
11691 SDValue SelectionDAG::getNeutralElement(unsigned Opcode, const SDLoc &DL,
11692                                         EVT VT, SDNodeFlags Flags) {
11693   switch (Opcode) {
11694   default:
11695     return SDValue();
11696   case ISD::ADD:
11697   case ISD::OR:
11698   case ISD::XOR:
11699   case ISD::UMAX:
11700     return getConstant(0, DL, VT);
11701   case ISD::MUL:
11702     return getConstant(1, DL, VT);
11703   case ISD::AND:
11704   case ISD::UMIN:
11705     return getAllOnesConstant(DL, VT);
11706   case ISD::SMAX:
11707     return getConstant(APInt::getSignedMinValue(VT.getSizeInBits()), DL, VT);
11708   case ISD::SMIN:
11709     return getConstant(APInt::getSignedMaxValue(VT.getSizeInBits()), DL, VT);
11710   case ISD::FADD:
11711     return getConstantFP(-0.0, DL, VT);
11712   case ISD::FMUL:
11713     return getConstantFP(1.0, DL, VT);
11714   case ISD::FMINNUM:
11715   case ISD::FMAXNUM: {
11716     // Neutral element for fminnum is NaN, Inf or FLT_MAX, depending on FMF.
11717     const fltSemantics &Semantics = EVTToAPFloatSemantics(VT);
11718     APFloat NeutralAF = !Flags.hasNoNaNs() ? APFloat::getQNaN(Semantics) :
11719                         !Flags.hasNoInfs() ? APFloat::getInf(Semantics) :
11720                         APFloat::getLargest(Semantics);
11721     if (Opcode == ISD::FMAXNUM)
11722       NeutralAF.changeSign();
11723 
11724     return getConstantFP(NeutralAF, DL, VT);
11725   }
11726   }
11727 }
11728 
11729 #ifndef NDEBUG
11730 static void checkForCyclesHelper(const SDNode *N,
11731                                  SmallPtrSetImpl<const SDNode*> &Visited,
11732                                  SmallPtrSetImpl<const SDNode*> &Checked,
11733                                  const llvm::SelectionDAG *DAG) {
11734   // If this node has already been checked, don't check it again.
11735   if (Checked.count(N))
11736     return;
11737 
11738   // If a node has already been visited on this depth-first walk, reject it as
11739   // a cycle.
11740   if (!Visited.insert(N).second) {
11741     errs() << "Detected cycle in SelectionDAG\n";
11742     dbgs() << "Offending node:\n";
11743     N->dumprFull(DAG); dbgs() << "\n";
11744     abort();
11745   }
11746 
11747   for (const SDValue &Op : N->op_values())
11748     checkForCyclesHelper(Op.getNode(), Visited, Checked, DAG);
11749 
11750   Checked.insert(N);
11751   Visited.erase(N);
11752 }
11753 #endif
11754 
11755 void llvm::checkForCycles(const llvm::SDNode *N,
11756                           const llvm::SelectionDAG *DAG,
11757                           bool force) {
11758 #ifndef NDEBUG
11759   bool check = force;
11760 #ifdef EXPENSIVE_CHECKS
11761   check = true;
11762 #endif  // EXPENSIVE_CHECKS
11763   if (check) {
11764     assert(N && "Checking nonexistent SDNode");
11765     SmallPtrSet<const SDNode*, 32> visited;
11766     SmallPtrSet<const SDNode*, 32> checked;
11767     checkForCyclesHelper(N, visited, checked, DAG);
11768   }
11769 #endif  // !NDEBUG
11770 }
11771 
11772 void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) {
11773   checkForCycles(DAG->getRoot().getNode(), DAG, force);
11774 }
11775