1 //===- SelectionDAG.cpp - Implement the SelectionDAG data structures ------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This implements the SelectionDAG class.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/CodeGen/SelectionDAG.h"
14 #include "SDNodeDbgValue.h"
15 #include "llvm/ADT/APFloat.h"
16 #include "llvm/ADT/APInt.h"
17 #include "llvm/ADT/APSInt.h"
18 #include "llvm/ADT/ArrayRef.h"
19 #include "llvm/ADT/BitVector.h"
20 #include "llvm/ADT/FoldingSet.h"
21 #include "llvm/ADT/None.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/ADT/SmallPtrSet.h"
24 #include "llvm/ADT/SmallVector.h"
25 #include "llvm/ADT/Triple.h"
26 #include "llvm/ADT/Twine.h"
27 #include "llvm/Analysis/MemoryLocation.h"
28 #include "llvm/Analysis/ValueTracking.h"
29 #include "llvm/CodeGen/Analysis.h"
30 #include "llvm/CodeGen/FunctionLoweringInfo.h"
31 #include "llvm/CodeGen/ISDOpcodes.h"
32 #include "llvm/CodeGen/MachineBasicBlock.h"
33 #include "llvm/CodeGen/MachineConstantPool.h"
34 #include "llvm/CodeGen/MachineFrameInfo.h"
35 #include "llvm/CodeGen/MachineFunction.h"
36 #include "llvm/CodeGen/MachineMemOperand.h"
37 #include "llvm/CodeGen/RuntimeLibcalls.h"
38 #include "llvm/CodeGen/SelectionDAGAddressAnalysis.h"
39 #include "llvm/CodeGen/SelectionDAGNodes.h"
40 #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
41 #include "llvm/CodeGen/TargetFrameLowering.h"
42 #include "llvm/CodeGen/TargetLowering.h"
43 #include "llvm/CodeGen/TargetRegisterInfo.h"
44 #include "llvm/CodeGen/TargetSubtargetInfo.h"
45 #include "llvm/CodeGen/ValueTypes.h"
46 #include "llvm/IR/Constant.h"
47 #include "llvm/IR/Constants.h"
48 #include "llvm/IR/DataLayout.h"
49 #include "llvm/IR/DebugInfoMetadata.h"
50 #include "llvm/IR/DebugLoc.h"
51 #include "llvm/IR/DerivedTypes.h"
52 #include "llvm/IR/Function.h"
53 #include "llvm/IR/GlobalValue.h"
54 #include "llvm/IR/Metadata.h"
55 #include "llvm/IR/Type.h"
56 #include "llvm/Support/Casting.h"
57 #include "llvm/Support/CodeGen.h"
58 #include "llvm/Support/Compiler.h"
59 #include "llvm/Support/Debug.h"
60 #include "llvm/Support/ErrorHandling.h"
61 #include "llvm/Support/KnownBits.h"
62 #include "llvm/Support/MachineValueType.h"
63 #include "llvm/Support/ManagedStatic.h"
64 #include "llvm/Support/MathExtras.h"
65 #include "llvm/Support/Mutex.h"
66 #include "llvm/Support/raw_ostream.h"
67 #include "llvm/Target/TargetMachine.h"
68 #include "llvm/Target/TargetOptions.h"
69 #include "llvm/Transforms/Utils/SizeOpts.h"
70 #include <algorithm>
71 #include <cassert>
72 #include <cstdint>
73 #include <cstdlib>
74 #include <limits>
75 #include <set>
76 #include <string>
77 #include <utility>
78 #include <vector>
79 
80 using namespace llvm;
81 
82 /// makeVTList - Return an instance of the SDVTList struct initialized with the
83 /// specified members.
84 static SDVTList makeVTList(const EVT *VTs, unsigned NumVTs) {
85   SDVTList Res = {VTs, NumVTs};
86   return Res;
87 }
88 
89 // Default null implementations of the callbacks.
90 void SelectionDAG::DAGUpdateListener::NodeDeleted(SDNode*, SDNode*) {}
91 void SelectionDAG::DAGUpdateListener::NodeUpdated(SDNode*) {}
92 void SelectionDAG::DAGUpdateListener::NodeInserted(SDNode *) {}
93 
94 void SelectionDAG::DAGNodeDeletedListener::anchor() {}
95 
96 #define DEBUG_TYPE "selectiondag"
97 
98 static cl::opt<bool> EnableMemCpyDAGOpt("enable-memcpy-dag-opt",
99        cl::Hidden, cl::init(true),
100        cl::desc("Gang up loads and stores generated by inlining of memcpy"));
101 
102 static cl::opt<int> MaxLdStGlue("ldstmemcpy-glue-max",
103        cl::desc("Number limit for gluing ld/st of memcpy."),
104        cl::Hidden, cl::init(0));
105 
106 static void NewSDValueDbgMsg(SDValue V, StringRef Msg, SelectionDAG *G) {
107   LLVM_DEBUG(dbgs() << Msg; V.getNode()->dump(G););
108 }
109 
110 //===----------------------------------------------------------------------===//
111 //                              ConstantFPSDNode Class
112 //===----------------------------------------------------------------------===//
113 
114 /// isExactlyValue - We don't rely on operator== working on double values, as
115 /// it returns true for things that are clearly not equal, like -0.0 and 0.0.
116 /// As such, this method can be used to do an exact bit-for-bit comparison of
117 /// two floating point values.
118 bool ConstantFPSDNode::isExactlyValue(const APFloat& V) const {
119   return getValueAPF().bitwiseIsEqual(V);
120 }
121 
122 bool ConstantFPSDNode::isValueValidForType(EVT VT,
123                                            const APFloat& Val) {
124   assert(VT.isFloatingPoint() && "Can only convert between FP types");
125 
126   // convert modifies in place, so make a copy.
127   APFloat Val2 = APFloat(Val);
128   bool losesInfo;
129   (void) Val2.convert(SelectionDAG::EVTToAPFloatSemantics(VT),
130                       APFloat::rmNearestTiesToEven,
131                       &losesInfo);
132   return !losesInfo;
133 }
134 
135 //===----------------------------------------------------------------------===//
136 //                              ISD Namespace
137 //===----------------------------------------------------------------------===//
138 
139 bool ISD::isConstantSplatVector(const SDNode *N, APInt &SplatVal) {
140   if (N->getOpcode() == ISD::SPLAT_VECTOR) {
141     unsigned EltSize =
142         N->getValueType(0).getVectorElementType().getSizeInBits();
143     if (auto *Op0 = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
144       SplatVal = Op0->getAPIntValue().trunc(EltSize);
145       return true;
146     }
147     if (auto *Op0 = dyn_cast<ConstantFPSDNode>(N->getOperand(0))) {
148       SplatVal = Op0->getValueAPF().bitcastToAPInt().trunc(EltSize);
149       return true;
150     }
151   }
152 
153   auto *BV = dyn_cast<BuildVectorSDNode>(N);
154   if (!BV)
155     return false;
156 
157   APInt SplatUndef;
158   unsigned SplatBitSize;
159   bool HasUndefs;
160   unsigned EltSize = N->getValueType(0).getVectorElementType().getSizeInBits();
161   return BV->isConstantSplat(SplatVal, SplatUndef, SplatBitSize, HasUndefs,
162                              EltSize) &&
163          EltSize == SplatBitSize;
164 }
165 
166 // FIXME: AllOnes and AllZeros duplicate a lot of code. Could these be
167 // specializations of the more general isConstantSplatVector()?
168 
169 bool ISD::isConstantSplatVectorAllOnes(const SDNode *N, bool BuildVectorOnly) {
170   // Look through a bit convert.
171   while (N->getOpcode() == ISD::BITCAST)
172     N = N->getOperand(0).getNode();
173 
174   if (!BuildVectorOnly && N->getOpcode() == ISD::SPLAT_VECTOR) {
175     APInt SplatVal;
176     return isConstantSplatVector(N, SplatVal) && SplatVal.isAllOnes();
177   }
178 
179   if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
180 
181   unsigned i = 0, e = N->getNumOperands();
182 
183   // Skip over all of the undef values.
184   while (i != e && N->getOperand(i).isUndef())
185     ++i;
186 
187   // Do not accept an all-undef vector.
188   if (i == e) return false;
189 
190   // Do not accept build_vectors that aren't all constants or which have non-~0
191   // elements. We have to be a bit careful here, as the type of the constant
192   // may not be the same as the type of the vector elements due to type
193   // legalization (the elements are promoted to a legal type for the target and
194   // a vector of a type may be legal when the base element type is not).
195   // We only want to check enough bits to cover the vector elements, because
196   // we care if the resultant vector is all ones, not whether the individual
197   // constants are.
198   SDValue NotZero = N->getOperand(i);
199   unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
200   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(NotZero)) {
201     if (CN->getAPIntValue().countTrailingOnes() < EltSize)
202       return false;
203   } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(NotZero)) {
204     if (CFPN->getValueAPF().bitcastToAPInt().countTrailingOnes() < EltSize)
205       return false;
206   } else
207     return false;
208 
209   // Okay, we have at least one ~0 value, check to see if the rest match or are
210   // undefs. Even with the above element type twiddling, this should be OK, as
211   // the same type legalization should have applied to all the elements.
212   for (++i; i != e; ++i)
213     if (N->getOperand(i) != NotZero && !N->getOperand(i).isUndef())
214       return false;
215   return true;
216 }
217 
218 bool ISD::isConstantSplatVectorAllZeros(const SDNode *N, bool BuildVectorOnly) {
219   // Look through a bit convert.
220   while (N->getOpcode() == ISD::BITCAST)
221     N = N->getOperand(0).getNode();
222 
223   if (!BuildVectorOnly && N->getOpcode() == ISD::SPLAT_VECTOR) {
224     APInt SplatVal;
225     return isConstantSplatVector(N, SplatVal) && SplatVal.isZero();
226   }
227 
228   if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
229 
230   bool IsAllUndef = true;
231   for (const SDValue &Op : N->op_values()) {
232     if (Op.isUndef())
233       continue;
234     IsAllUndef = false;
235     // Do not accept build_vectors that aren't all constants or which have non-0
236     // elements. We have to be a bit careful here, as the type of the constant
237     // may not be the same as the type of the vector elements due to type
238     // legalization (the elements are promoted to a legal type for the target
239     // and a vector of a type may be legal when the base element type is not).
240     // We only want to check enough bits to cover the vector elements, because
241     // we care if the resultant vector is all zeros, not whether the individual
242     // constants are.
243     unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
244     if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Op)) {
245       if (CN->getAPIntValue().countTrailingZeros() < EltSize)
246         return false;
247     } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(Op)) {
248       if (CFPN->getValueAPF().bitcastToAPInt().countTrailingZeros() < EltSize)
249         return false;
250     } else
251       return false;
252   }
253 
254   // Do not accept an all-undef vector.
255   if (IsAllUndef)
256     return false;
257   return true;
258 }
259 
260 bool ISD::isBuildVectorAllOnes(const SDNode *N) {
261   return isConstantSplatVectorAllOnes(N, /*BuildVectorOnly*/ true);
262 }
263 
264 bool ISD::isBuildVectorAllZeros(const SDNode *N) {
265   return isConstantSplatVectorAllZeros(N, /*BuildVectorOnly*/ true);
266 }
267 
268 bool ISD::isBuildVectorOfConstantSDNodes(const SDNode *N) {
269   if (N->getOpcode() != ISD::BUILD_VECTOR)
270     return false;
271 
272   for (const SDValue &Op : N->op_values()) {
273     if (Op.isUndef())
274       continue;
275     if (!isa<ConstantSDNode>(Op))
276       return false;
277   }
278   return true;
279 }
280 
281 bool ISD::isBuildVectorOfConstantFPSDNodes(const SDNode *N) {
282   if (N->getOpcode() != ISD::BUILD_VECTOR)
283     return false;
284 
285   for (const SDValue &Op : N->op_values()) {
286     if (Op.isUndef())
287       continue;
288     if (!isa<ConstantFPSDNode>(Op))
289       return false;
290   }
291   return true;
292 }
293 
294 bool ISD::allOperandsUndef(const SDNode *N) {
295   // Return false if the node has no operands.
296   // This is "logically inconsistent" with the definition of "all" but
297   // is probably the desired behavior.
298   if (N->getNumOperands() == 0)
299     return false;
300   return all_of(N->op_values(), [](SDValue Op) { return Op.isUndef(); });
301 }
302 
303 bool ISD::matchUnaryPredicate(SDValue Op,
304                               std::function<bool(ConstantSDNode *)> Match,
305                               bool AllowUndefs) {
306   // FIXME: Add support for scalar UNDEF cases?
307   if (auto *Cst = dyn_cast<ConstantSDNode>(Op))
308     return Match(Cst);
309 
310   // FIXME: Add support for vector UNDEF cases?
311   if (ISD::BUILD_VECTOR != Op.getOpcode() &&
312       ISD::SPLAT_VECTOR != Op.getOpcode())
313     return false;
314 
315   EVT SVT = Op.getValueType().getScalarType();
316   for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
317     if (AllowUndefs && Op.getOperand(i).isUndef()) {
318       if (!Match(nullptr))
319         return false;
320       continue;
321     }
322 
323     auto *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(i));
324     if (!Cst || Cst->getValueType(0) != SVT || !Match(Cst))
325       return false;
326   }
327   return true;
328 }
329 
330 bool ISD::matchBinaryPredicate(
331     SDValue LHS, SDValue RHS,
332     std::function<bool(ConstantSDNode *, ConstantSDNode *)> Match,
333     bool AllowUndefs, bool AllowTypeMismatch) {
334   if (!AllowTypeMismatch && LHS.getValueType() != RHS.getValueType())
335     return false;
336 
337   // TODO: Add support for scalar UNDEF cases?
338   if (auto *LHSCst = dyn_cast<ConstantSDNode>(LHS))
339     if (auto *RHSCst = dyn_cast<ConstantSDNode>(RHS))
340       return Match(LHSCst, RHSCst);
341 
342   // TODO: Add support for vector UNDEF cases?
343   if (LHS.getOpcode() != RHS.getOpcode() ||
344       (LHS.getOpcode() != ISD::BUILD_VECTOR &&
345        LHS.getOpcode() != ISD::SPLAT_VECTOR))
346     return false;
347 
348   EVT SVT = LHS.getValueType().getScalarType();
349   for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
350     SDValue LHSOp = LHS.getOperand(i);
351     SDValue RHSOp = RHS.getOperand(i);
352     bool LHSUndef = AllowUndefs && LHSOp.isUndef();
353     bool RHSUndef = AllowUndefs && RHSOp.isUndef();
354     auto *LHSCst = dyn_cast<ConstantSDNode>(LHSOp);
355     auto *RHSCst = dyn_cast<ConstantSDNode>(RHSOp);
356     if ((!LHSCst && !LHSUndef) || (!RHSCst && !RHSUndef))
357       return false;
358     if (!AllowTypeMismatch && (LHSOp.getValueType() != SVT ||
359                                LHSOp.getValueType() != RHSOp.getValueType()))
360       return false;
361     if (!Match(LHSCst, RHSCst))
362       return false;
363   }
364   return true;
365 }
366 
367 ISD::NodeType ISD::getVecReduceBaseOpcode(unsigned VecReduceOpcode) {
368   switch (VecReduceOpcode) {
369   default:
370     llvm_unreachable("Expected VECREDUCE opcode");
371   case ISD::VECREDUCE_FADD:
372   case ISD::VECREDUCE_SEQ_FADD:
373   case ISD::VP_REDUCE_FADD:
374   case ISD::VP_REDUCE_SEQ_FADD:
375     return ISD::FADD;
376   case ISD::VECREDUCE_FMUL:
377   case ISD::VECREDUCE_SEQ_FMUL:
378   case ISD::VP_REDUCE_FMUL:
379   case ISD::VP_REDUCE_SEQ_FMUL:
380     return ISD::FMUL;
381   case ISD::VECREDUCE_ADD:
382   case ISD::VP_REDUCE_ADD:
383     return ISD::ADD;
384   case ISD::VECREDUCE_MUL:
385   case ISD::VP_REDUCE_MUL:
386     return ISD::MUL;
387   case ISD::VECREDUCE_AND:
388   case ISD::VP_REDUCE_AND:
389     return ISD::AND;
390   case ISD::VECREDUCE_OR:
391   case ISD::VP_REDUCE_OR:
392     return ISD::OR;
393   case ISD::VECREDUCE_XOR:
394   case ISD::VP_REDUCE_XOR:
395     return ISD::XOR;
396   case ISD::VECREDUCE_SMAX:
397   case ISD::VP_REDUCE_SMAX:
398     return ISD::SMAX;
399   case ISD::VECREDUCE_SMIN:
400   case ISD::VP_REDUCE_SMIN:
401     return ISD::SMIN;
402   case ISD::VECREDUCE_UMAX:
403   case ISD::VP_REDUCE_UMAX:
404     return ISD::UMAX;
405   case ISD::VECREDUCE_UMIN:
406   case ISD::VP_REDUCE_UMIN:
407     return ISD::UMIN;
408   case ISD::VECREDUCE_FMAX:
409   case ISD::VP_REDUCE_FMAX:
410     return ISD::FMAXNUM;
411   case ISD::VECREDUCE_FMIN:
412   case ISD::VP_REDUCE_FMIN:
413     return ISD::FMINNUM;
414   }
415 }
416 
417 bool ISD::isVPOpcode(unsigned Opcode) {
418   switch (Opcode) {
419   default:
420     return false;
421 #define BEGIN_REGISTER_VP_SDNODE(VPSD, ...)                                    \
422   case ISD::VPSD:                                                              \
423     return true;
424 #include "llvm/IR/VPIntrinsics.def"
425   }
426 }
427 
428 bool ISD::isVPBinaryOp(unsigned Opcode) {
429   switch (Opcode) {
430   default:
431     break;
432 #define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) case ISD::VPSD:
433 #define VP_PROPERTY_BINARYOP return true;
434 #define END_REGISTER_VP_SDNODE(VPSD) break;
435 #include "llvm/IR/VPIntrinsics.def"
436   }
437   return false;
438 }
439 
440 bool ISD::isVPReduction(unsigned Opcode) {
441   switch (Opcode) {
442   default:
443     break;
444 #define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) case ISD::VPSD:
445 #define VP_PROPERTY_REDUCTION(STARTPOS, ...) return true;
446 #define END_REGISTER_VP_SDNODE(VPSD) break;
447 #include "llvm/IR/VPIntrinsics.def"
448   }
449   return false;
450 }
451 
452 /// The operand position of the vector mask.
453 Optional<unsigned> ISD::getVPMaskIdx(unsigned Opcode) {
454   switch (Opcode) {
455   default:
456     return None;
457 #define BEGIN_REGISTER_VP_SDNODE(VPSD, LEGALPOS, TDNAME, MASKPOS, ...)         \
458   case ISD::VPSD:                                                              \
459     return MASKPOS;
460 #include "llvm/IR/VPIntrinsics.def"
461   }
462 }
463 
464 /// The operand position of the explicit vector length parameter.
465 Optional<unsigned> ISD::getVPExplicitVectorLengthIdx(unsigned Opcode) {
466   switch (Opcode) {
467   default:
468     return None;
469 #define BEGIN_REGISTER_VP_SDNODE(VPSD, LEGALPOS, TDNAME, MASKPOS, EVLPOS)      \
470   case ISD::VPSD:                                                              \
471     return EVLPOS;
472 #include "llvm/IR/VPIntrinsics.def"
473   }
474 }
475 
476 ISD::NodeType ISD::getExtForLoadExtType(bool IsFP, ISD::LoadExtType ExtType) {
477   switch (ExtType) {
478   case ISD::EXTLOAD:
479     return IsFP ? ISD::FP_EXTEND : ISD::ANY_EXTEND;
480   case ISD::SEXTLOAD:
481     return ISD::SIGN_EXTEND;
482   case ISD::ZEXTLOAD:
483     return ISD::ZERO_EXTEND;
484   default:
485     break;
486   }
487 
488   llvm_unreachable("Invalid LoadExtType");
489 }
490 
491 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) {
492   // To perform this operation, we just need to swap the L and G bits of the
493   // operation.
494   unsigned OldL = (Operation >> 2) & 1;
495   unsigned OldG = (Operation >> 1) & 1;
496   return ISD::CondCode((Operation & ~6) |  // Keep the N, U, E bits
497                        (OldL << 1) |       // New G bit
498                        (OldG << 2));       // New L bit.
499 }
500 
501 static ISD::CondCode getSetCCInverseImpl(ISD::CondCode Op, bool isIntegerLike) {
502   unsigned Operation = Op;
503   if (isIntegerLike)
504     Operation ^= 7;   // Flip L, G, E bits, but not U.
505   else
506     Operation ^= 15;  // Flip all of the condition bits.
507 
508   if (Operation > ISD::SETTRUE2)
509     Operation &= ~8;  // Don't let N and U bits get set.
510 
511   return ISD::CondCode(Operation);
512 }
513 
514 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, EVT Type) {
515   return getSetCCInverseImpl(Op, Type.isInteger());
516 }
517 
518 ISD::CondCode ISD::GlobalISel::getSetCCInverse(ISD::CondCode Op,
519                                                bool isIntegerLike) {
520   return getSetCCInverseImpl(Op, isIntegerLike);
521 }
522 
523 /// For an integer comparison, return 1 if the comparison is a signed operation
524 /// and 2 if the result is an unsigned comparison. Return zero if the operation
525 /// does not depend on the sign of the input (setne and seteq).
526 static int isSignedOp(ISD::CondCode Opcode) {
527   switch (Opcode) {
528   default: llvm_unreachable("Illegal integer setcc operation!");
529   case ISD::SETEQ:
530   case ISD::SETNE: return 0;
531   case ISD::SETLT:
532   case ISD::SETLE:
533   case ISD::SETGT:
534   case ISD::SETGE: return 1;
535   case ISD::SETULT:
536   case ISD::SETULE:
537   case ISD::SETUGT:
538   case ISD::SETUGE: return 2;
539   }
540 }
541 
542 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2,
543                                        EVT Type) {
544   bool IsInteger = Type.isInteger();
545   if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
546     // Cannot fold a signed integer setcc with an unsigned integer setcc.
547     return ISD::SETCC_INVALID;
548 
549   unsigned Op = Op1 | Op2;  // Combine all of the condition bits.
550 
551   // If the N and U bits get set, then the resultant comparison DOES suddenly
552   // care about orderedness, and it is true when ordered.
553   if (Op > ISD::SETTRUE2)
554     Op &= ~16;     // Clear the U bit if the N bit is set.
555 
556   // Canonicalize illegal integer setcc's.
557   if (IsInteger && Op == ISD::SETUNE)  // e.g. SETUGT | SETULT
558     Op = ISD::SETNE;
559 
560   return ISD::CondCode(Op);
561 }
562 
563 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2,
564                                         EVT Type) {
565   bool IsInteger = Type.isInteger();
566   if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
567     // Cannot fold a signed setcc with an unsigned setcc.
568     return ISD::SETCC_INVALID;
569 
570   // Combine all of the condition bits.
571   ISD::CondCode Result = ISD::CondCode(Op1 & Op2);
572 
573   // Canonicalize illegal integer setcc's.
574   if (IsInteger) {
575     switch (Result) {
576     default: break;
577     case ISD::SETUO : Result = ISD::SETFALSE; break;  // SETUGT & SETULT
578     case ISD::SETOEQ:                                 // SETEQ  & SETU[LG]E
579     case ISD::SETUEQ: Result = ISD::SETEQ   ; break;  // SETUGE & SETULE
580     case ISD::SETOLT: Result = ISD::SETULT  ; break;  // SETULT & SETNE
581     case ISD::SETOGT: Result = ISD::SETUGT  ; break;  // SETUGT & SETNE
582     }
583   }
584 
585   return Result;
586 }
587 
588 //===----------------------------------------------------------------------===//
589 //                           SDNode Profile Support
590 //===----------------------------------------------------------------------===//
591 
592 /// AddNodeIDOpcode - Add the node opcode to the NodeID data.
593 static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC)  {
594   ID.AddInteger(OpC);
595 }
596 
597 /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them
598 /// solely with their pointer.
599 static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) {
600   ID.AddPointer(VTList.VTs);
601 }
602 
603 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
604 static void AddNodeIDOperands(FoldingSetNodeID &ID,
605                               ArrayRef<SDValue> Ops) {
606   for (auto& Op : Ops) {
607     ID.AddPointer(Op.getNode());
608     ID.AddInteger(Op.getResNo());
609   }
610 }
611 
612 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
613 static void AddNodeIDOperands(FoldingSetNodeID &ID,
614                               ArrayRef<SDUse> Ops) {
615   for (auto& Op : Ops) {
616     ID.AddPointer(Op.getNode());
617     ID.AddInteger(Op.getResNo());
618   }
619 }
620 
621 static void AddNodeIDNode(FoldingSetNodeID &ID, unsigned short OpC,
622                           SDVTList VTList, ArrayRef<SDValue> OpList) {
623   AddNodeIDOpcode(ID, OpC);
624   AddNodeIDValueTypes(ID, VTList);
625   AddNodeIDOperands(ID, OpList);
626 }
627 
628 /// If this is an SDNode with special info, add this info to the NodeID data.
629 static void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N) {
630   switch (N->getOpcode()) {
631   case ISD::TargetExternalSymbol:
632   case ISD::ExternalSymbol:
633   case ISD::MCSymbol:
634     llvm_unreachable("Should only be used on nodes with operands");
635   default: break;  // Normal nodes don't need extra info.
636   case ISD::TargetConstant:
637   case ISD::Constant: {
638     const ConstantSDNode *C = cast<ConstantSDNode>(N);
639     ID.AddPointer(C->getConstantIntValue());
640     ID.AddBoolean(C->isOpaque());
641     break;
642   }
643   case ISD::TargetConstantFP:
644   case ISD::ConstantFP:
645     ID.AddPointer(cast<ConstantFPSDNode>(N)->getConstantFPValue());
646     break;
647   case ISD::TargetGlobalAddress:
648   case ISD::GlobalAddress:
649   case ISD::TargetGlobalTLSAddress:
650   case ISD::GlobalTLSAddress: {
651     const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
652     ID.AddPointer(GA->getGlobal());
653     ID.AddInteger(GA->getOffset());
654     ID.AddInteger(GA->getTargetFlags());
655     break;
656   }
657   case ISD::BasicBlock:
658     ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock());
659     break;
660   case ISD::Register:
661     ID.AddInteger(cast<RegisterSDNode>(N)->getReg());
662     break;
663   case ISD::RegisterMask:
664     ID.AddPointer(cast<RegisterMaskSDNode>(N)->getRegMask());
665     break;
666   case ISD::SRCVALUE:
667     ID.AddPointer(cast<SrcValueSDNode>(N)->getValue());
668     break;
669   case ISD::FrameIndex:
670   case ISD::TargetFrameIndex:
671     ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex());
672     break;
673   case ISD::LIFETIME_START:
674   case ISD::LIFETIME_END:
675     if (cast<LifetimeSDNode>(N)->hasOffset()) {
676       ID.AddInteger(cast<LifetimeSDNode>(N)->getSize());
677       ID.AddInteger(cast<LifetimeSDNode>(N)->getOffset());
678     }
679     break;
680   case ISD::PSEUDO_PROBE:
681     ID.AddInteger(cast<PseudoProbeSDNode>(N)->getGuid());
682     ID.AddInteger(cast<PseudoProbeSDNode>(N)->getIndex());
683     ID.AddInteger(cast<PseudoProbeSDNode>(N)->getAttributes());
684     break;
685   case ISD::JumpTable:
686   case ISD::TargetJumpTable:
687     ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex());
688     ID.AddInteger(cast<JumpTableSDNode>(N)->getTargetFlags());
689     break;
690   case ISD::ConstantPool:
691   case ISD::TargetConstantPool: {
692     const ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N);
693     ID.AddInteger(CP->getAlign().value());
694     ID.AddInteger(CP->getOffset());
695     if (CP->isMachineConstantPoolEntry())
696       CP->getMachineCPVal()->addSelectionDAGCSEId(ID);
697     else
698       ID.AddPointer(CP->getConstVal());
699     ID.AddInteger(CP->getTargetFlags());
700     break;
701   }
702   case ISD::TargetIndex: {
703     const TargetIndexSDNode *TI = cast<TargetIndexSDNode>(N);
704     ID.AddInteger(TI->getIndex());
705     ID.AddInteger(TI->getOffset());
706     ID.AddInteger(TI->getTargetFlags());
707     break;
708   }
709   case ISD::LOAD: {
710     const LoadSDNode *LD = cast<LoadSDNode>(N);
711     ID.AddInteger(LD->getMemoryVT().getRawBits());
712     ID.AddInteger(LD->getRawSubclassData());
713     ID.AddInteger(LD->getPointerInfo().getAddrSpace());
714     ID.AddInteger(LD->getMemOperand()->getFlags());
715     break;
716   }
717   case ISD::STORE: {
718     const StoreSDNode *ST = cast<StoreSDNode>(N);
719     ID.AddInteger(ST->getMemoryVT().getRawBits());
720     ID.AddInteger(ST->getRawSubclassData());
721     ID.AddInteger(ST->getPointerInfo().getAddrSpace());
722     ID.AddInteger(ST->getMemOperand()->getFlags());
723     break;
724   }
725   case ISD::VP_LOAD: {
726     const VPLoadSDNode *ELD = cast<VPLoadSDNode>(N);
727     ID.AddInteger(ELD->getMemoryVT().getRawBits());
728     ID.AddInteger(ELD->getRawSubclassData());
729     ID.AddInteger(ELD->getPointerInfo().getAddrSpace());
730     ID.AddInteger(ELD->getMemOperand()->getFlags());
731     break;
732   }
733   case ISD::VP_STORE: {
734     const VPStoreSDNode *EST = cast<VPStoreSDNode>(N);
735     ID.AddInteger(EST->getMemoryVT().getRawBits());
736     ID.AddInteger(EST->getRawSubclassData());
737     ID.AddInteger(EST->getPointerInfo().getAddrSpace());
738     ID.AddInteger(EST->getMemOperand()->getFlags());
739     break;
740   }
741   case ISD::EXPERIMENTAL_VP_STRIDED_LOAD: {
742     const VPStridedLoadSDNode *SLD = cast<VPStridedLoadSDNode>(N);
743     ID.AddInteger(SLD->getMemoryVT().getRawBits());
744     ID.AddInteger(SLD->getRawSubclassData());
745     ID.AddInteger(SLD->getPointerInfo().getAddrSpace());
746     break;
747   }
748   case ISD::EXPERIMENTAL_VP_STRIDED_STORE: {
749     const VPStridedStoreSDNode *SST = cast<VPStridedStoreSDNode>(N);
750     ID.AddInteger(SST->getMemoryVT().getRawBits());
751     ID.AddInteger(SST->getRawSubclassData());
752     ID.AddInteger(SST->getPointerInfo().getAddrSpace());
753     break;
754   }
755   case ISD::VP_GATHER: {
756     const VPGatherSDNode *EG = cast<VPGatherSDNode>(N);
757     ID.AddInteger(EG->getMemoryVT().getRawBits());
758     ID.AddInteger(EG->getRawSubclassData());
759     ID.AddInteger(EG->getPointerInfo().getAddrSpace());
760     ID.AddInteger(EG->getMemOperand()->getFlags());
761     break;
762   }
763   case ISD::VP_SCATTER: {
764     const VPScatterSDNode *ES = cast<VPScatterSDNode>(N);
765     ID.AddInteger(ES->getMemoryVT().getRawBits());
766     ID.AddInteger(ES->getRawSubclassData());
767     ID.AddInteger(ES->getPointerInfo().getAddrSpace());
768     ID.AddInteger(ES->getMemOperand()->getFlags());
769     break;
770   }
771   case ISD::MLOAD: {
772     const MaskedLoadSDNode *MLD = cast<MaskedLoadSDNode>(N);
773     ID.AddInteger(MLD->getMemoryVT().getRawBits());
774     ID.AddInteger(MLD->getRawSubclassData());
775     ID.AddInteger(MLD->getPointerInfo().getAddrSpace());
776     ID.AddInteger(MLD->getMemOperand()->getFlags());
777     break;
778   }
779   case ISD::MSTORE: {
780     const MaskedStoreSDNode *MST = cast<MaskedStoreSDNode>(N);
781     ID.AddInteger(MST->getMemoryVT().getRawBits());
782     ID.AddInteger(MST->getRawSubclassData());
783     ID.AddInteger(MST->getPointerInfo().getAddrSpace());
784     ID.AddInteger(MST->getMemOperand()->getFlags());
785     break;
786   }
787   case ISD::MGATHER: {
788     const MaskedGatherSDNode *MG = cast<MaskedGatherSDNode>(N);
789     ID.AddInteger(MG->getMemoryVT().getRawBits());
790     ID.AddInteger(MG->getRawSubclassData());
791     ID.AddInteger(MG->getPointerInfo().getAddrSpace());
792     ID.AddInteger(MG->getMemOperand()->getFlags());
793     break;
794   }
795   case ISD::MSCATTER: {
796     const MaskedScatterSDNode *MS = cast<MaskedScatterSDNode>(N);
797     ID.AddInteger(MS->getMemoryVT().getRawBits());
798     ID.AddInteger(MS->getRawSubclassData());
799     ID.AddInteger(MS->getPointerInfo().getAddrSpace());
800     ID.AddInteger(MS->getMemOperand()->getFlags());
801     break;
802   }
803   case ISD::ATOMIC_CMP_SWAP:
804   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
805   case ISD::ATOMIC_SWAP:
806   case ISD::ATOMIC_LOAD_ADD:
807   case ISD::ATOMIC_LOAD_SUB:
808   case ISD::ATOMIC_LOAD_AND:
809   case ISD::ATOMIC_LOAD_CLR:
810   case ISD::ATOMIC_LOAD_OR:
811   case ISD::ATOMIC_LOAD_XOR:
812   case ISD::ATOMIC_LOAD_NAND:
813   case ISD::ATOMIC_LOAD_MIN:
814   case ISD::ATOMIC_LOAD_MAX:
815   case ISD::ATOMIC_LOAD_UMIN:
816   case ISD::ATOMIC_LOAD_UMAX:
817   case ISD::ATOMIC_LOAD:
818   case ISD::ATOMIC_STORE: {
819     const AtomicSDNode *AT = cast<AtomicSDNode>(N);
820     ID.AddInteger(AT->getMemoryVT().getRawBits());
821     ID.AddInteger(AT->getRawSubclassData());
822     ID.AddInteger(AT->getPointerInfo().getAddrSpace());
823     ID.AddInteger(AT->getMemOperand()->getFlags());
824     break;
825   }
826   case ISD::PREFETCH: {
827     const MemSDNode *PF = cast<MemSDNode>(N);
828     ID.AddInteger(PF->getPointerInfo().getAddrSpace());
829     ID.AddInteger(PF->getMemOperand()->getFlags());
830     break;
831   }
832   case ISD::VECTOR_SHUFFLE: {
833     const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
834     for (unsigned i = 0, e = N->getValueType(0).getVectorNumElements();
835          i != e; ++i)
836       ID.AddInteger(SVN->getMaskElt(i));
837     break;
838   }
839   case ISD::TargetBlockAddress:
840   case ISD::BlockAddress: {
841     const BlockAddressSDNode *BA = cast<BlockAddressSDNode>(N);
842     ID.AddPointer(BA->getBlockAddress());
843     ID.AddInteger(BA->getOffset());
844     ID.AddInteger(BA->getTargetFlags());
845     break;
846   }
847   case ISD::AssertAlign:
848     ID.AddInteger(cast<AssertAlignSDNode>(N)->getAlign().value());
849     break;
850   } // end switch (N->getOpcode())
851 
852   // Target specific memory nodes could also have address spaces and flags
853   // to check.
854   if (N->isTargetMemoryOpcode()) {
855     const MemSDNode *MN = cast<MemSDNode>(N);
856     ID.AddInteger(MN->getPointerInfo().getAddrSpace());
857     ID.AddInteger(MN->getMemOperand()->getFlags());
858   }
859 }
860 
861 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID
862 /// data.
863 static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) {
864   AddNodeIDOpcode(ID, N->getOpcode());
865   // Add the return value info.
866   AddNodeIDValueTypes(ID, N->getVTList());
867   // Add the operand info.
868   AddNodeIDOperands(ID, N->ops());
869 
870   // Handle SDNode leafs with special info.
871   AddNodeIDCustom(ID, N);
872 }
873 
874 //===----------------------------------------------------------------------===//
875 //                              SelectionDAG Class
876 //===----------------------------------------------------------------------===//
877 
878 /// doNotCSE - Return true if CSE should not be performed for this node.
879 static bool doNotCSE(SDNode *N) {
880   if (N->getValueType(0) == MVT::Glue)
881     return true; // Never CSE anything that produces a flag.
882 
883   switch (N->getOpcode()) {
884   default: break;
885   case ISD::HANDLENODE:
886   case ISD::EH_LABEL:
887     return true;   // Never CSE these nodes.
888   }
889 
890   // Check that remaining values produced are not flags.
891   for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
892     if (N->getValueType(i) == MVT::Glue)
893       return true; // Never CSE anything that produces a flag.
894 
895   return false;
896 }
897 
898 /// RemoveDeadNodes - This method deletes all unreachable nodes in the
899 /// SelectionDAG.
900 void SelectionDAG::RemoveDeadNodes() {
901   // Create a dummy node (which is not added to allnodes), that adds a reference
902   // to the root node, preventing it from being deleted.
903   HandleSDNode Dummy(getRoot());
904 
905   SmallVector<SDNode*, 128> DeadNodes;
906 
907   // Add all obviously-dead nodes to the DeadNodes worklist.
908   for (SDNode &Node : allnodes())
909     if (Node.use_empty())
910       DeadNodes.push_back(&Node);
911 
912   RemoveDeadNodes(DeadNodes);
913 
914   // If the root changed (e.g. it was a dead load, update the root).
915   setRoot(Dummy.getValue());
916 }
917 
918 /// RemoveDeadNodes - This method deletes the unreachable nodes in the
919 /// given list, and any nodes that become unreachable as a result.
920 void SelectionDAG::RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes) {
921 
922   // Process the worklist, deleting the nodes and adding their uses to the
923   // worklist.
924   while (!DeadNodes.empty()) {
925     SDNode *N = DeadNodes.pop_back_val();
926     // Skip to next node if we've already managed to delete the node. This could
927     // happen if replacing a node causes a node previously added to the node to
928     // be deleted.
929     if (N->getOpcode() == ISD::DELETED_NODE)
930       continue;
931 
932     for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
933       DUL->NodeDeleted(N, nullptr);
934 
935     // Take the node out of the appropriate CSE map.
936     RemoveNodeFromCSEMaps(N);
937 
938     // Next, brutally remove the operand list.  This is safe to do, as there are
939     // no cycles in the graph.
940     for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
941       SDUse &Use = *I++;
942       SDNode *Operand = Use.getNode();
943       Use.set(SDValue());
944 
945       // Now that we removed this operand, see if there are no uses of it left.
946       if (Operand->use_empty())
947         DeadNodes.push_back(Operand);
948     }
949 
950     DeallocateNode(N);
951   }
952 }
953 
954 void SelectionDAG::RemoveDeadNode(SDNode *N){
955   SmallVector<SDNode*, 16> DeadNodes(1, N);
956 
957   // Create a dummy node that adds a reference to the root node, preventing
958   // it from being deleted.  (This matters if the root is an operand of the
959   // dead node.)
960   HandleSDNode Dummy(getRoot());
961 
962   RemoveDeadNodes(DeadNodes);
963 }
964 
965 void SelectionDAG::DeleteNode(SDNode *N) {
966   // First take this out of the appropriate CSE map.
967   RemoveNodeFromCSEMaps(N);
968 
969   // Finally, remove uses due to operands of this node, remove from the
970   // AllNodes list, and delete the node.
971   DeleteNodeNotInCSEMaps(N);
972 }
973 
974 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
975   assert(N->getIterator() != AllNodes.begin() &&
976          "Cannot delete the entry node!");
977   assert(N->use_empty() && "Cannot delete a node that is not dead!");
978 
979   // Drop all of the operands and decrement used node's use counts.
980   N->DropOperands();
981 
982   DeallocateNode(N);
983 }
984 
985 void SDDbgInfo::add(SDDbgValue *V, bool isParameter) {
986   assert(!(V->isVariadic() && isParameter));
987   if (isParameter)
988     ByvalParmDbgValues.push_back(V);
989   else
990     DbgValues.push_back(V);
991   for (const SDNode *Node : V->getSDNodes())
992     if (Node)
993       DbgValMap[Node].push_back(V);
994 }
995 
996 void SDDbgInfo::erase(const SDNode *Node) {
997   DbgValMapType::iterator I = DbgValMap.find(Node);
998   if (I == DbgValMap.end())
999     return;
1000   for (auto &Val: I->second)
1001     Val->setIsInvalidated();
1002   DbgValMap.erase(I);
1003 }
1004 
1005 void SelectionDAG::DeallocateNode(SDNode *N) {
1006   // If we have operands, deallocate them.
1007   removeOperands(N);
1008 
1009   NodeAllocator.Deallocate(AllNodes.remove(N));
1010 
1011   // Set the opcode to DELETED_NODE to help catch bugs when node
1012   // memory is reallocated.
1013   // FIXME: There are places in SDag that have grown a dependency on the opcode
1014   // value in the released node.
1015   __asan_unpoison_memory_region(&N->NodeType, sizeof(N->NodeType));
1016   N->NodeType = ISD::DELETED_NODE;
1017 
1018   // If any of the SDDbgValue nodes refer to this SDNode, invalidate
1019   // them and forget about that node.
1020   DbgInfo->erase(N);
1021 }
1022 
1023 #ifndef NDEBUG
1024 /// VerifySDNode - Check the given SDNode.  Aborts if it is invalid.
1025 static void VerifySDNode(SDNode *N) {
1026   switch (N->getOpcode()) {
1027   default:
1028     break;
1029   case ISD::BUILD_PAIR: {
1030     EVT VT = N->getValueType(0);
1031     assert(N->getNumValues() == 1 && "Too many results!");
1032     assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) &&
1033            "Wrong return type!");
1034     assert(N->getNumOperands() == 2 && "Wrong number of operands!");
1035     assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() &&
1036            "Mismatched operand types!");
1037     assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() &&
1038            "Wrong operand type!");
1039     assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() &&
1040            "Wrong return type size");
1041     break;
1042   }
1043   case ISD::BUILD_VECTOR: {
1044     assert(N->getNumValues() == 1 && "Too many results!");
1045     assert(N->getValueType(0).isVector() && "Wrong return type!");
1046     assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() &&
1047            "Wrong number of operands!");
1048     EVT EltVT = N->getValueType(0).getVectorElementType();
1049     for (const SDUse &Op : N->ops()) {
1050       assert((Op.getValueType() == EltVT ||
1051               (EltVT.isInteger() && Op.getValueType().isInteger() &&
1052                EltVT.bitsLE(Op.getValueType()))) &&
1053              "Wrong operand type!");
1054       assert(Op.getValueType() == N->getOperand(0).getValueType() &&
1055              "Operands must all have the same type");
1056     }
1057     break;
1058   }
1059   }
1060 }
1061 #endif // NDEBUG
1062 
1063 /// Insert a newly allocated node into the DAG.
1064 ///
1065 /// Handles insertion into the all nodes list and CSE map, as well as
1066 /// verification and other common operations when a new node is allocated.
1067 void SelectionDAG::InsertNode(SDNode *N) {
1068   AllNodes.push_back(N);
1069 #ifndef NDEBUG
1070   N->PersistentId = NextPersistentId++;
1071   VerifySDNode(N);
1072 #endif
1073   for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1074     DUL->NodeInserted(N);
1075 }
1076 
1077 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
1078 /// correspond to it.  This is useful when we're about to delete or repurpose
1079 /// the node.  We don't want future request for structurally identical nodes
1080 /// to return N anymore.
1081 bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
1082   bool Erased = false;
1083   switch (N->getOpcode()) {
1084   case ISD::HANDLENODE: return false;  // noop.
1085   case ISD::CONDCODE:
1086     assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
1087            "Cond code doesn't exist!");
1088     Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != nullptr;
1089     CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = nullptr;
1090     break;
1091   case ISD::ExternalSymbol:
1092     Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
1093     break;
1094   case ISD::TargetExternalSymbol: {
1095     ExternalSymbolSDNode *ESN = cast<ExternalSymbolSDNode>(N);
1096     Erased = TargetExternalSymbols.erase(std::pair<std::string, unsigned>(
1097         ESN->getSymbol(), ESN->getTargetFlags()));
1098     break;
1099   }
1100   case ISD::MCSymbol: {
1101     auto *MCSN = cast<MCSymbolSDNode>(N);
1102     Erased = MCSymbols.erase(MCSN->getMCSymbol());
1103     break;
1104   }
1105   case ISD::VALUETYPE: {
1106     EVT VT = cast<VTSDNode>(N)->getVT();
1107     if (VT.isExtended()) {
1108       Erased = ExtendedValueTypeNodes.erase(VT);
1109     } else {
1110       Erased = ValueTypeNodes[VT.getSimpleVT().SimpleTy] != nullptr;
1111       ValueTypeNodes[VT.getSimpleVT().SimpleTy] = nullptr;
1112     }
1113     break;
1114   }
1115   default:
1116     // Remove it from the CSE Map.
1117     assert(N->getOpcode() != ISD::DELETED_NODE && "DELETED_NODE in CSEMap!");
1118     assert(N->getOpcode() != ISD::EntryToken && "EntryToken in CSEMap!");
1119     Erased = CSEMap.RemoveNode(N);
1120     break;
1121   }
1122 #ifndef NDEBUG
1123   // Verify that the node was actually in one of the CSE maps, unless it has a
1124   // flag result (which cannot be CSE'd) or is one of the special cases that are
1125   // not subject to CSE.
1126   if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Glue &&
1127       !N->isMachineOpcode() && !doNotCSE(N)) {
1128     N->dump(this);
1129     dbgs() << "\n";
1130     llvm_unreachable("Node is not in map!");
1131   }
1132 #endif
1133   return Erased;
1134 }
1135 
1136 /// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE
1137 /// maps and modified in place. Add it back to the CSE maps, unless an identical
1138 /// node already exists, in which case transfer all its users to the existing
1139 /// node. This transfer can potentially trigger recursive merging.
1140 void
1141 SelectionDAG::AddModifiedNodeToCSEMaps(SDNode *N) {
1142   // For node types that aren't CSE'd, just act as if no identical node
1143   // already exists.
1144   if (!doNotCSE(N)) {
1145     SDNode *Existing = CSEMap.GetOrInsertNode(N);
1146     if (Existing != N) {
1147       // If there was already an existing matching node, use ReplaceAllUsesWith
1148       // to replace the dead one with the existing one.  This can cause
1149       // recursive merging of other unrelated nodes down the line.
1150       ReplaceAllUsesWith(N, Existing);
1151 
1152       // N is now dead. Inform the listeners and delete it.
1153       for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1154         DUL->NodeDeleted(N, Existing);
1155       DeleteNodeNotInCSEMaps(N);
1156       return;
1157     }
1158   }
1159 
1160   // If the node doesn't already exist, we updated it.  Inform listeners.
1161   for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
1162     DUL->NodeUpdated(N);
1163 }
1164 
1165 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1166 /// were replaced with those specified.  If this node is never memoized,
1167 /// return null, otherwise return a pointer to the slot it would take.  If a
1168 /// node already exists with these operands, the slot will be non-null.
1169 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op,
1170                                            void *&InsertPos) {
1171   if (doNotCSE(N))
1172     return nullptr;
1173 
1174   SDValue Ops[] = { Op };
1175   FoldingSetNodeID ID;
1176   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1177   AddNodeIDCustom(ID, N);
1178   SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1179   if (Node)
1180     Node->intersectFlagsWith(N->getFlags());
1181   return Node;
1182 }
1183 
1184 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1185 /// were replaced with those specified.  If this node is never memoized,
1186 /// return null, otherwise return a pointer to the slot it would take.  If a
1187 /// node already exists with these operands, the slot will be non-null.
1188 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
1189                                            SDValue Op1, SDValue Op2,
1190                                            void *&InsertPos) {
1191   if (doNotCSE(N))
1192     return nullptr;
1193 
1194   SDValue Ops[] = { Op1, Op2 };
1195   FoldingSetNodeID ID;
1196   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1197   AddNodeIDCustom(ID, N);
1198   SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1199   if (Node)
1200     Node->intersectFlagsWith(N->getFlags());
1201   return Node;
1202 }
1203 
1204 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
1205 /// were replaced with those specified.  If this node is never memoized,
1206 /// return null, otherwise return a pointer to the slot it would take.  If a
1207 /// node already exists with these operands, the slot will be non-null.
1208 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, ArrayRef<SDValue> Ops,
1209                                            void *&InsertPos) {
1210   if (doNotCSE(N))
1211     return nullptr;
1212 
1213   FoldingSetNodeID ID;
1214   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
1215   AddNodeIDCustom(ID, N);
1216   SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1217   if (Node)
1218     Node->intersectFlagsWith(N->getFlags());
1219   return Node;
1220 }
1221 
1222 Align SelectionDAG::getEVTAlign(EVT VT) const {
1223   Type *Ty = VT == MVT::iPTR ?
1224                    PointerType::get(Type::getInt8Ty(*getContext()), 0) :
1225                    VT.getTypeForEVT(*getContext());
1226 
1227   return getDataLayout().getABITypeAlign(Ty);
1228 }
1229 
1230 // EntryNode could meaningfully have debug info if we can find it...
1231 SelectionDAG::SelectionDAG(const TargetMachine &tm, CodeGenOpt::Level OL)
1232     : TM(tm), OptLevel(OL),
1233       EntryNode(ISD::EntryToken, 0, DebugLoc(), getVTList(MVT::Other)),
1234       Root(getEntryNode()) {
1235   InsertNode(&EntryNode);
1236   DbgInfo = new SDDbgInfo();
1237 }
1238 
1239 void SelectionDAG::init(MachineFunction &NewMF,
1240                         OptimizationRemarkEmitter &NewORE,
1241                         Pass *PassPtr, const TargetLibraryInfo *LibraryInfo,
1242                         LegacyDivergenceAnalysis * Divergence,
1243                         ProfileSummaryInfo *PSIin,
1244                         BlockFrequencyInfo *BFIin) {
1245   MF = &NewMF;
1246   SDAGISelPass = PassPtr;
1247   ORE = &NewORE;
1248   TLI = getSubtarget().getTargetLowering();
1249   TSI = getSubtarget().getSelectionDAGInfo();
1250   LibInfo = LibraryInfo;
1251   Context = &MF->getFunction().getContext();
1252   DA = Divergence;
1253   PSI = PSIin;
1254   BFI = BFIin;
1255 }
1256 
1257 SelectionDAG::~SelectionDAG() {
1258   assert(!UpdateListeners && "Dangling registered DAGUpdateListeners");
1259   allnodes_clear();
1260   OperandRecycler.clear(OperandAllocator);
1261   delete DbgInfo;
1262 }
1263 
1264 bool SelectionDAG::shouldOptForSize() const {
1265   return MF->getFunction().hasOptSize() ||
1266       llvm::shouldOptimizeForSize(FLI->MBB->getBasicBlock(), PSI, BFI);
1267 }
1268 
1269 void SelectionDAG::allnodes_clear() {
1270   assert(&*AllNodes.begin() == &EntryNode);
1271   AllNodes.remove(AllNodes.begin());
1272   while (!AllNodes.empty())
1273     DeallocateNode(&AllNodes.front());
1274 #ifndef NDEBUG
1275   NextPersistentId = 0;
1276 #endif
1277 }
1278 
1279 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
1280                                           void *&InsertPos) {
1281   SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
1282   if (N) {
1283     switch (N->getOpcode()) {
1284     default: break;
1285     case ISD::Constant:
1286     case ISD::ConstantFP:
1287       llvm_unreachable("Querying for Constant and ConstantFP nodes requires "
1288                        "debug location.  Use another overload.");
1289     }
1290   }
1291   return N;
1292 }
1293 
1294 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
1295                                           const SDLoc &DL, void *&InsertPos) {
1296   SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
1297   if (N) {
1298     switch (N->getOpcode()) {
1299     case ISD::Constant:
1300     case ISD::ConstantFP:
1301       // Erase debug location from the node if the node is used at several
1302       // different places. Do not propagate one location to all uses as it
1303       // will cause a worse single stepping debugging experience.
1304       if (N->getDebugLoc() != DL.getDebugLoc())
1305         N->setDebugLoc(DebugLoc());
1306       break;
1307     default:
1308       // When the node's point of use is located earlier in the instruction
1309       // sequence than its prior point of use, update its debug info to the
1310       // earlier location.
1311       if (DL.getIROrder() && DL.getIROrder() < N->getIROrder())
1312         N->setDebugLoc(DL.getDebugLoc());
1313       break;
1314     }
1315   }
1316   return N;
1317 }
1318 
1319 void SelectionDAG::clear() {
1320   allnodes_clear();
1321   OperandRecycler.clear(OperandAllocator);
1322   OperandAllocator.Reset();
1323   CSEMap.clear();
1324 
1325   ExtendedValueTypeNodes.clear();
1326   ExternalSymbols.clear();
1327   TargetExternalSymbols.clear();
1328   MCSymbols.clear();
1329   SDCallSiteDbgInfo.clear();
1330   std::fill(CondCodeNodes.begin(), CondCodeNodes.end(),
1331             static_cast<CondCodeSDNode*>(nullptr));
1332   std::fill(ValueTypeNodes.begin(), ValueTypeNodes.end(),
1333             static_cast<SDNode*>(nullptr));
1334 
1335   EntryNode.UseList = nullptr;
1336   InsertNode(&EntryNode);
1337   Root = getEntryNode();
1338   DbgInfo->clear();
1339 }
1340 
1341 SDValue SelectionDAG::getFPExtendOrRound(SDValue Op, const SDLoc &DL, EVT VT) {
1342   return VT.bitsGT(Op.getValueType())
1343              ? getNode(ISD::FP_EXTEND, DL, VT, Op)
1344              : getNode(ISD::FP_ROUND, DL, VT, Op, getIntPtrConstant(0, DL));
1345 }
1346 
1347 std::pair<SDValue, SDValue>
1348 SelectionDAG::getStrictFPExtendOrRound(SDValue Op, SDValue Chain,
1349                                        const SDLoc &DL, EVT VT) {
1350   assert(!VT.bitsEq(Op.getValueType()) &&
1351          "Strict no-op FP extend/round not allowed.");
1352   SDValue Res =
1353       VT.bitsGT(Op.getValueType())
1354           ? getNode(ISD::STRICT_FP_EXTEND, DL, {VT, MVT::Other}, {Chain, Op})
1355           : getNode(ISD::STRICT_FP_ROUND, DL, {VT, MVT::Other},
1356                     {Chain, Op, getIntPtrConstant(0, DL)});
1357 
1358   return std::pair<SDValue, SDValue>(Res, SDValue(Res.getNode(), 1));
1359 }
1360 
1361 SDValue SelectionDAG::getAnyExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1362   return VT.bitsGT(Op.getValueType()) ?
1363     getNode(ISD::ANY_EXTEND, DL, VT, Op) :
1364     getNode(ISD::TRUNCATE, DL, VT, Op);
1365 }
1366 
1367 SDValue SelectionDAG::getSExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1368   return VT.bitsGT(Op.getValueType()) ?
1369     getNode(ISD::SIGN_EXTEND, DL, VT, Op) :
1370     getNode(ISD::TRUNCATE, DL, VT, Op);
1371 }
1372 
1373 SDValue SelectionDAG::getZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1374   return VT.bitsGT(Op.getValueType()) ?
1375     getNode(ISD::ZERO_EXTEND, DL, VT, Op) :
1376     getNode(ISD::TRUNCATE, DL, VT, Op);
1377 }
1378 
1379 SDValue SelectionDAG::getBoolExtOrTrunc(SDValue Op, const SDLoc &SL, EVT VT,
1380                                         EVT OpVT) {
1381   if (VT.bitsLE(Op.getValueType()))
1382     return getNode(ISD::TRUNCATE, SL, VT, Op);
1383 
1384   TargetLowering::BooleanContent BType = TLI->getBooleanContents(OpVT);
1385   return getNode(TLI->getExtendForContent(BType), SL, VT, Op);
1386 }
1387 
1388 SDValue SelectionDAG::getZeroExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) {
1389   EVT OpVT = Op.getValueType();
1390   assert(VT.isInteger() && OpVT.isInteger() &&
1391          "Cannot getZeroExtendInReg FP types");
1392   assert(VT.isVector() == OpVT.isVector() &&
1393          "getZeroExtendInReg type should be vector iff the operand "
1394          "type is vector!");
1395   assert((!VT.isVector() ||
1396           VT.getVectorElementCount() == OpVT.getVectorElementCount()) &&
1397          "Vector element counts must match in getZeroExtendInReg");
1398   assert(VT.bitsLE(OpVT) && "Not extending!");
1399   if (OpVT == VT)
1400     return Op;
1401   APInt Imm = APInt::getLowBitsSet(OpVT.getScalarSizeInBits(),
1402                                    VT.getScalarSizeInBits());
1403   return getNode(ISD::AND, DL, OpVT, Op, getConstant(Imm, DL, OpVT));
1404 }
1405 
1406 SDValue SelectionDAG::getPtrExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1407   // Only unsigned pointer semantics are supported right now. In the future this
1408   // might delegate to TLI to check pointer signedness.
1409   return getZExtOrTrunc(Op, DL, VT);
1410 }
1411 
1412 SDValue SelectionDAG::getPtrExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) {
1413   // Only unsigned pointer semantics are supported right now. In the future this
1414   // might delegate to TLI to check pointer signedness.
1415   return getZeroExtendInReg(Op, DL, VT);
1416 }
1417 
1418 /// getNOT - Create a bitwise NOT operation as (XOR Val, -1).
1419 SDValue SelectionDAG::getNOT(const SDLoc &DL, SDValue Val, EVT VT) {
1420   return getNode(ISD::XOR, DL, VT, Val, getAllOnesConstant(DL, VT));
1421 }
1422 
1423 SDValue SelectionDAG::getLogicalNOT(const SDLoc &DL, SDValue Val, EVT VT) {
1424   SDValue TrueValue = getBoolConstant(true, DL, VT, VT);
1425   return getNode(ISD::XOR, DL, VT, Val, TrueValue);
1426 }
1427 
1428 SDValue SelectionDAG::getVPLogicalNOT(const SDLoc &DL, SDValue Val,
1429                                       SDValue Mask, SDValue EVL, EVT VT) {
1430   SDValue TrueValue = getBoolConstant(true, DL, VT, VT);
1431   return getNode(ISD::VP_XOR, DL, VT, Val, TrueValue, Mask, EVL);
1432 }
1433 
1434 SDValue SelectionDAG::getBoolConstant(bool V, const SDLoc &DL, EVT VT,
1435                                       EVT OpVT) {
1436   if (!V)
1437     return getConstant(0, DL, VT);
1438 
1439   switch (TLI->getBooleanContents(OpVT)) {
1440   case TargetLowering::ZeroOrOneBooleanContent:
1441   case TargetLowering::UndefinedBooleanContent:
1442     return getConstant(1, DL, VT);
1443   case TargetLowering::ZeroOrNegativeOneBooleanContent:
1444     return getAllOnesConstant(DL, VT);
1445   }
1446   llvm_unreachable("Unexpected boolean content enum!");
1447 }
1448 
1449 SDValue SelectionDAG::getConstant(uint64_t Val, const SDLoc &DL, EVT VT,
1450                                   bool isT, bool isO) {
1451   EVT EltVT = VT.getScalarType();
1452   assert((EltVT.getSizeInBits() >= 64 ||
1453           (uint64_t)((int64_t)Val >> EltVT.getSizeInBits()) + 1 < 2) &&
1454          "getConstant with a uint64_t value that doesn't fit in the type!");
1455   return getConstant(APInt(EltVT.getSizeInBits(), Val), DL, VT, isT, isO);
1456 }
1457 
1458 SDValue SelectionDAG::getConstant(const APInt &Val, const SDLoc &DL, EVT VT,
1459                                   bool isT, bool isO) {
1460   return getConstant(*ConstantInt::get(*Context, Val), DL, VT, isT, isO);
1461 }
1462 
1463 SDValue SelectionDAG::getConstant(const ConstantInt &Val, const SDLoc &DL,
1464                                   EVT VT, bool isT, bool isO) {
1465   assert(VT.isInteger() && "Cannot create FP integer constant!");
1466 
1467   EVT EltVT = VT.getScalarType();
1468   const ConstantInt *Elt = &Val;
1469 
1470   // In some cases the vector type is legal but the element type is illegal and
1471   // needs to be promoted, for example v8i8 on ARM.  In this case, promote the
1472   // inserted value (the type does not need to match the vector element type).
1473   // Any extra bits introduced will be truncated away.
1474   if (VT.isVector() && TLI->getTypeAction(*getContext(), EltVT) ==
1475                            TargetLowering::TypePromoteInteger) {
1476     EltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1477     APInt NewVal = Elt->getValue().zextOrTrunc(EltVT.getSizeInBits());
1478     Elt = ConstantInt::get(*getContext(), NewVal);
1479   }
1480   // In other cases the element type is illegal and needs to be expanded, for
1481   // example v2i64 on MIPS32. In this case, find the nearest legal type, split
1482   // the value into n parts and use a vector type with n-times the elements.
1483   // Then bitcast to the type requested.
1484   // Legalizing constants too early makes the DAGCombiner's job harder so we
1485   // only legalize if the DAG tells us we must produce legal types.
1486   else if (NewNodesMustHaveLegalTypes && VT.isVector() &&
1487            TLI->getTypeAction(*getContext(), EltVT) ==
1488                TargetLowering::TypeExpandInteger) {
1489     const APInt &NewVal = Elt->getValue();
1490     EVT ViaEltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1491     unsigned ViaEltSizeInBits = ViaEltVT.getSizeInBits();
1492 
1493     // For scalable vectors, try to use a SPLAT_VECTOR_PARTS node.
1494     if (VT.isScalableVector()) {
1495       assert(EltVT.getSizeInBits() % ViaEltSizeInBits == 0 &&
1496              "Can only handle an even split!");
1497       unsigned Parts = EltVT.getSizeInBits() / ViaEltSizeInBits;
1498 
1499       SmallVector<SDValue, 2> ScalarParts;
1500       for (unsigned i = 0; i != Parts; ++i)
1501         ScalarParts.push_back(getConstant(
1502             NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL,
1503             ViaEltVT, isT, isO));
1504 
1505       return getNode(ISD::SPLAT_VECTOR_PARTS, DL, VT, ScalarParts);
1506     }
1507 
1508     unsigned ViaVecNumElts = VT.getSizeInBits() / ViaEltSizeInBits;
1509     EVT ViaVecVT = EVT::getVectorVT(*getContext(), ViaEltVT, ViaVecNumElts);
1510 
1511     // Check the temporary vector is the correct size. If this fails then
1512     // getTypeToTransformTo() probably returned a type whose size (in bits)
1513     // isn't a power-of-2 factor of the requested type size.
1514     assert(ViaVecVT.getSizeInBits() == VT.getSizeInBits());
1515 
1516     SmallVector<SDValue, 2> EltParts;
1517     for (unsigned i = 0; i < ViaVecNumElts / VT.getVectorNumElements(); ++i)
1518       EltParts.push_back(getConstant(
1519           NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL,
1520           ViaEltVT, isT, isO));
1521 
1522     // EltParts is currently in little endian order. If we actually want
1523     // big-endian order then reverse it now.
1524     if (getDataLayout().isBigEndian())
1525       std::reverse(EltParts.begin(), EltParts.end());
1526 
1527     // The elements must be reversed when the element order is different
1528     // to the endianness of the elements (because the BITCAST is itself a
1529     // vector shuffle in this situation). However, we do not need any code to
1530     // perform this reversal because getConstant() is producing a vector
1531     // splat.
1532     // This situation occurs in MIPS MSA.
1533 
1534     SmallVector<SDValue, 8> Ops;
1535     for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
1536       llvm::append_range(Ops, EltParts);
1537 
1538     SDValue V =
1539         getNode(ISD::BITCAST, DL, VT, getBuildVector(ViaVecVT, DL, Ops));
1540     return V;
1541   }
1542 
1543   assert(Elt->getBitWidth() == EltVT.getSizeInBits() &&
1544          "APInt size does not match type size!");
1545   unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
1546   FoldingSetNodeID ID;
1547   AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
1548   ID.AddPointer(Elt);
1549   ID.AddBoolean(isO);
1550   void *IP = nullptr;
1551   SDNode *N = nullptr;
1552   if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1553     if (!VT.isVector())
1554       return SDValue(N, 0);
1555 
1556   if (!N) {
1557     N = newSDNode<ConstantSDNode>(isT, isO, Elt, EltVT);
1558     CSEMap.InsertNode(N, IP);
1559     InsertNode(N);
1560     NewSDValueDbgMsg(SDValue(N, 0), "Creating constant: ", this);
1561   }
1562 
1563   SDValue Result(N, 0);
1564   if (VT.isScalableVector())
1565     Result = getSplatVector(VT, DL, Result);
1566   else if (VT.isVector())
1567     Result = getSplatBuildVector(VT, DL, Result);
1568 
1569   return Result;
1570 }
1571 
1572 SDValue SelectionDAG::getIntPtrConstant(uint64_t Val, const SDLoc &DL,
1573                                         bool isTarget) {
1574   return getConstant(Val, DL, TLI->getPointerTy(getDataLayout()), isTarget);
1575 }
1576 
1577 SDValue SelectionDAG::getShiftAmountConstant(uint64_t Val, EVT VT,
1578                                              const SDLoc &DL, bool LegalTypes) {
1579   assert(VT.isInteger() && "Shift amount is not an integer type!");
1580   EVT ShiftVT = TLI->getShiftAmountTy(VT, getDataLayout(), LegalTypes);
1581   return getConstant(Val, DL, ShiftVT);
1582 }
1583 
1584 SDValue SelectionDAG::getVectorIdxConstant(uint64_t Val, const SDLoc &DL,
1585                                            bool isTarget) {
1586   return getConstant(Val, DL, TLI->getVectorIdxTy(getDataLayout()), isTarget);
1587 }
1588 
1589 SDValue SelectionDAG::getConstantFP(const APFloat &V, const SDLoc &DL, EVT VT,
1590                                     bool isTarget) {
1591   return getConstantFP(*ConstantFP::get(*getContext(), V), DL, VT, isTarget);
1592 }
1593 
1594 SDValue SelectionDAG::getConstantFP(const ConstantFP &V, const SDLoc &DL,
1595                                     EVT VT, bool isTarget) {
1596   assert(VT.isFloatingPoint() && "Cannot create integer FP constant!");
1597 
1598   EVT EltVT = VT.getScalarType();
1599 
1600   // Do the map lookup using the actual bit pattern for the floating point
1601   // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
1602   // we don't have issues with SNANs.
1603   unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
1604   FoldingSetNodeID ID;
1605   AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
1606   ID.AddPointer(&V);
1607   void *IP = nullptr;
1608   SDNode *N = nullptr;
1609   if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1610     if (!VT.isVector())
1611       return SDValue(N, 0);
1612 
1613   if (!N) {
1614     N = newSDNode<ConstantFPSDNode>(isTarget, &V, EltVT);
1615     CSEMap.InsertNode(N, IP);
1616     InsertNode(N);
1617   }
1618 
1619   SDValue Result(N, 0);
1620   if (VT.isScalableVector())
1621     Result = getSplatVector(VT, DL, Result);
1622   else if (VT.isVector())
1623     Result = getSplatBuildVector(VT, DL, Result);
1624   NewSDValueDbgMsg(Result, "Creating fp constant: ", this);
1625   return Result;
1626 }
1627 
1628 SDValue SelectionDAG::getConstantFP(double Val, const SDLoc &DL, EVT VT,
1629                                     bool isTarget) {
1630   EVT EltVT = VT.getScalarType();
1631   if (EltVT == MVT::f32)
1632     return getConstantFP(APFloat((float)Val), DL, VT, isTarget);
1633   if (EltVT == MVT::f64)
1634     return getConstantFP(APFloat(Val), DL, VT, isTarget);
1635   if (EltVT == MVT::f80 || EltVT == MVT::f128 || EltVT == MVT::ppcf128 ||
1636       EltVT == MVT::f16 || EltVT == MVT::bf16) {
1637     bool Ignored;
1638     APFloat APF = APFloat(Val);
1639     APF.convert(EVTToAPFloatSemantics(EltVT), APFloat::rmNearestTiesToEven,
1640                 &Ignored);
1641     return getConstantFP(APF, DL, VT, isTarget);
1642   }
1643   llvm_unreachable("Unsupported type in getConstantFP");
1644 }
1645 
1646 SDValue SelectionDAG::getGlobalAddress(const GlobalValue *GV, const SDLoc &DL,
1647                                        EVT VT, int64_t Offset, bool isTargetGA,
1648                                        unsigned TargetFlags) {
1649   assert((TargetFlags == 0 || isTargetGA) &&
1650          "Cannot set target flags on target-independent globals");
1651 
1652   // Truncate (with sign-extension) the offset value to the pointer size.
1653   unsigned BitWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
1654   if (BitWidth < 64)
1655     Offset = SignExtend64(Offset, BitWidth);
1656 
1657   unsigned Opc;
1658   if (GV->isThreadLocal())
1659     Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress;
1660   else
1661     Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress;
1662 
1663   FoldingSetNodeID ID;
1664   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1665   ID.AddPointer(GV);
1666   ID.AddInteger(Offset);
1667   ID.AddInteger(TargetFlags);
1668   void *IP = nullptr;
1669   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
1670     return SDValue(E, 0);
1671 
1672   auto *N = newSDNode<GlobalAddressSDNode>(
1673       Opc, DL.getIROrder(), DL.getDebugLoc(), GV, VT, Offset, TargetFlags);
1674   CSEMap.InsertNode(N, IP);
1675     InsertNode(N);
1676   return SDValue(N, 0);
1677 }
1678 
1679 SDValue SelectionDAG::getFrameIndex(int FI, EVT VT, bool isTarget) {
1680   unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
1681   FoldingSetNodeID ID;
1682   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1683   ID.AddInteger(FI);
1684   void *IP = nullptr;
1685   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1686     return SDValue(E, 0);
1687 
1688   auto *N = newSDNode<FrameIndexSDNode>(FI, VT, isTarget);
1689   CSEMap.InsertNode(N, IP);
1690   InsertNode(N);
1691   return SDValue(N, 0);
1692 }
1693 
1694 SDValue SelectionDAG::getJumpTable(int JTI, EVT VT, bool isTarget,
1695                                    unsigned TargetFlags) {
1696   assert((TargetFlags == 0 || isTarget) &&
1697          "Cannot set target flags on target-independent jump tables");
1698   unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
1699   FoldingSetNodeID ID;
1700   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1701   ID.AddInteger(JTI);
1702   ID.AddInteger(TargetFlags);
1703   void *IP = nullptr;
1704   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1705     return SDValue(E, 0);
1706 
1707   auto *N = newSDNode<JumpTableSDNode>(JTI, VT, isTarget, TargetFlags);
1708   CSEMap.InsertNode(N, IP);
1709   InsertNode(N);
1710   return SDValue(N, 0);
1711 }
1712 
1713 SDValue SelectionDAG::getConstantPool(const Constant *C, EVT VT,
1714                                       MaybeAlign Alignment, int Offset,
1715                                       bool isTarget, unsigned TargetFlags) {
1716   assert((TargetFlags == 0 || isTarget) &&
1717          "Cannot set target flags on target-independent globals");
1718   if (!Alignment)
1719     Alignment = shouldOptForSize()
1720                     ? getDataLayout().getABITypeAlign(C->getType())
1721                     : getDataLayout().getPrefTypeAlign(C->getType());
1722   unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1723   FoldingSetNodeID ID;
1724   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1725   ID.AddInteger(Alignment->value());
1726   ID.AddInteger(Offset);
1727   ID.AddPointer(C);
1728   ID.AddInteger(TargetFlags);
1729   void *IP = nullptr;
1730   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1731     return SDValue(E, 0);
1732 
1733   auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment,
1734                                           TargetFlags);
1735   CSEMap.InsertNode(N, IP);
1736   InsertNode(N);
1737   SDValue V = SDValue(N, 0);
1738   NewSDValueDbgMsg(V, "Creating new constant pool: ", this);
1739   return V;
1740 }
1741 
1742 SDValue SelectionDAG::getConstantPool(MachineConstantPoolValue *C, EVT VT,
1743                                       MaybeAlign Alignment, int Offset,
1744                                       bool isTarget, unsigned TargetFlags) {
1745   assert((TargetFlags == 0 || isTarget) &&
1746          "Cannot set target flags on target-independent globals");
1747   if (!Alignment)
1748     Alignment = getDataLayout().getPrefTypeAlign(C->getType());
1749   unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1750   FoldingSetNodeID ID;
1751   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1752   ID.AddInteger(Alignment->value());
1753   ID.AddInteger(Offset);
1754   C->addSelectionDAGCSEId(ID);
1755   ID.AddInteger(TargetFlags);
1756   void *IP = nullptr;
1757   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1758     return SDValue(E, 0);
1759 
1760   auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment,
1761                                           TargetFlags);
1762   CSEMap.InsertNode(N, IP);
1763   InsertNode(N);
1764   return SDValue(N, 0);
1765 }
1766 
1767 SDValue SelectionDAG::getTargetIndex(int Index, EVT VT, int64_t Offset,
1768                                      unsigned TargetFlags) {
1769   FoldingSetNodeID ID;
1770   AddNodeIDNode(ID, ISD::TargetIndex, getVTList(VT), None);
1771   ID.AddInteger(Index);
1772   ID.AddInteger(Offset);
1773   ID.AddInteger(TargetFlags);
1774   void *IP = nullptr;
1775   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1776     return SDValue(E, 0);
1777 
1778   auto *N = newSDNode<TargetIndexSDNode>(Index, VT, Offset, TargetFlags);
1779   CSEMap.InsertNode(N, IP);
1780   InsertNode(N);
1781   return SDValue(N, 0);
1782 }
1783 
1784 SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
1785   FoldingSetNodeID ID;
1786   AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), None);
1787   ID.AddPointer(MBB);
1788   void *IP = nullptr;
1789   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1790     return SDValue(E, 0);
1791 
1792   auto *N = newSDNode<BasicBlockSDNode>(MBB);
1793   CSEMap.InsertNode(N, IP);
1794   InsertNode(N);
1795   return SDValue(N, 0);
1796 }
1797 
1798 SDValue SelectionDAG::getValueType(EVT VT) {
1799   if (VT.isSimple() && (unsigned)VT.getSimpleVT().SimpleTy >=
1800       ValueTypeNodes.size())
1801     ValueTypeNodes.resize(VT.getSimpleVT().SimpleTy+1);
1802 
1803   SDNode *&N = VT.isExtended() ?
1804     ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT().SimpleTy];
1805 
1806   if (N) return SDValue(N, 0);
1807   N = newSDNode<VTSDNode>(VT);
1808   InsertNode(N);
1809   return SDValue(N, 0);
1810 }
1811 
1812 SDValue SelectionDAG::getExternalSymbol(const char *Sym, EVT VT) {
1813   SDNode *&N = ExternalSymbols[Sym];
1814   if (N) return SDValue(N, 0);
1815   N = newSDNode<ExternalSymbolSDNode>(false, Sym, 0, VT);
1816   InsertNode(N);
1817   return SDValue(N, 0);
1818 }
1819 
1820 SDValue SelectionDAG::getMCSymbol(MCSymbol *Sym, EVT VT) {
1821   SDNode *&N = MCSymbols[Sym];
1822   if (N)
1823     return SDValue(N, 0);
1824   N = newSDNode<MCSymbolSDNode>(Sym, VT);
1825   InsertNode(N);
1826   return SDValue(N, 0);
1827 }
1828 
1829 SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, EVT VT,
1830                                               unsigned TargetFlags) {
1831   SDNode *&N =
1832       TargetExternalSymbols[std::pair<std::string, unsigned>(Sym, TargetFlags)];
1833   if (N) return SDValue(N, 0);
1834   N = newSDNode<ExternalSymbolSDNode>(true, Sym, TargetFlags, VT);
1835   InsertNode(N);
1836   return SDValue(N, 0);
1837 }
1838 
1839 SDValue SelectionDAG::getCondCode(ISD::CondCode Cond) {
1840   if ((unsigned)Cond >= CondCodeNodes.size())
1841     CondCodeNodes.resize(Cond+1);
1842 
1843   if (!CondCodeNodes[Cond]) {
1844     auto *N = newSDNode<CondCodeSDNode>(Cond);
1845     CondCodeNodes[Cond] = N;
1846     InsertNode(N);
1847   }
1848 
1849   return SDValue(CondCodeNodes[Cond], 0);
1850 }
1851 
1852 SDValue SelectionDAG::getStepVector(const SDLoc &DL, EVT ResVT) {
1853   APInt One(ResVT.getScalarSizeInBits(), 1);
1854   return getStepVector(DL, ResVT, One);
1855 }
1856 
1857 SDValue SelectionDAG::getStepVector(const SDLoc &DL, EVT ResVT, APInt StepVal) {
1858   assert(ResVT.getScalarSizeInBits() == StepVal.getBitWidth());
1859   if (ResVT.isScalableVector())
1860     return getNode(
1861         ISD::STEP_VECTOR, DL, ResVT,
1862         getTargetConstant(StepVal, DL, ResVT.getVectorElementType()));
1863 
1864   SmallVector<SDValue, 16> OpsStepConstants;
1865   for (uint64_t i = 0; i < ResVT.getVectorNumElements(); i++)
1866     OpsStepConstants.push_back(
1867         getConstant(StepVal * i, DL, ResVT.getVectorElementType()));
1868   return getBuildVector(ResVT, DL, OpsStepConstants);
1869 }
1870 
1871 /// Swaps the values of N1 and N2. Swaps all indices in the shuffle mask M that
1872 /// point at N1 to point at N2 and indices that point at N2 to point at N1.
1873 static void commuteShuffle(SDValue &N1, SDValue &N2, MutableArrayRef<int> M) {
1874   std::swap(N1, N2);
1875   ShuffleVectorSDNode::commuteMask(M);
1876 }
1877 
1878 SDValue SelectionDAG::getVectorShuffle(EVT VT, const SDLoc &dl, SDValue N1,
1879                                        SDValue N2, ArrayRef<int> Mask) {
1880   assert(VT.getVectorNumElements() == Mask.size() &&
1881          "Must have the same number of vector elements as mask elements!");
1882   assert(VT == N1.getValueType() && VT == N2.getValueType() &&
1883          "Invalid VECTOR_SHUFFLE");
1884 
1885   // Canonicalize shuffle undef, undef -> undef
1886   if (N1.isUndef() && N2.isUndef())
1887     return getUNDEF(VT);
1888 
1889   // Validate that all indices in Mask are within the range of the elements
1890   // input to the shuffle.
1891   int NElts = Mask.size();
1892   assert(llvm::all_of(Mask,
1893                       [&](int M) { return M < (NElts * 2) && M >= -1; }) &&
1894          "Index out of range");
1895 
1896   // Copy the mask so we can do any needed cleanup.
1897   SmallVector<int, 8> MaskVec(Mask.begin(), Mask.end());
1898 
1899   // Canonicalize shuffle v, v -> v, undef
1900   if (N1 == N2) {
1901     N2 = getUNDEF(VT);
1902     for (int i = 0; i != NElts; ++i)
1903       if (MaskVec[i] >= NElts) MaskVec[i] -= NElts;
1904   }
1905 
1906   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
1907   if (N1.isUndef())
1908     commuteShuffle(N1, N2, MaskVec);
1909 
1910   if (TLI->hasVectorBlend()) {
1911     // If shuffling a splat, try to blend the splat instead. We do this here so
1912     // that even when this arises during lowering we don't have to re-handle it.
1913     auto BlendSplat = [&](BuildVectorSDNode *BV, int Offset) {
1914       BitVector UndefElements;
1915       SDValue Splat = BV->getSplatValue(&UndefElements);
1916       if (!Splat)
1917         return;
1918 
1919       for (int i = 0; i < NElts; ++i) {
1920         if (MaskVec[i] < Offset || MaskVec[i] >= (Offset + NElts))
1921           continue;
1922 
1923         // If this input comes from undef, mark it as such.
1924         if (UndefElements[MaskVec[i] - Offset]) {
1925           MaskVec[i] = -1;
1926           continue;
1927         }
1928 
1929         // If we can blend a non-undef lane, use that instead.
1930         if (!UndefElements[i])
1931           MaskVec[i] = i + Offset;
1932       }
1933     };
1934     if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
1935       BlendSplat(N1BV, 0);
1936     if (auto *N2BV = dyn_cast<BuildVectorSDNode>(N2))
1937       BlendSplat(N2BV, NElts);
1938   }
1939 
1940   // Canonicalize all index into lhs, -> shuffle lhs, undef
1941   // Canonicalize all index into rhs, -> shuffle rhs, undef
1942   bool AllLHS = true, AllRHS = true;
1943   bool N2Undef = N2.isUndef();
1944   for (int i = 0; i != NElts; ++i) {
1945     if (MaskVec[i] >= NElts) {
1946       if (N2Undef)
1947         MaskVec[i] = -1;
1948       else
1949         AllLHS = false;
1950     } else if (MaskVec[i] >= 0) {
1951       AllRHS = false;
1952     }
1953   }
1954   if (AllLHS && AllRHS)
1955     return getUNDEF(VT);
1956   if (AllLHS && !N2Undef)
1957     N2 = getUNDEF(VT);
1958   if (AllRHS) {
1959     N1 = getUNDEF(VT);
1960     commuteShuffle(N1, N2, MaskVec);
1961   }
1962   // Reset our undef status after accounting for the mask.
1963   N2Undef = N2.isUndef();
1964   // Re-check whether both sides ended up undef.
1965   if (N1.isUndef() && N2Undef)
1966     return getUNDEF(VT);
1967 
1968   // If Identity shuffle return that node.
1969   bool Identity = true, AllSame = true;
1970   for (int i = 0; i != NElts; ++i) {
1971     if (MaskVec[i] >= 0 && MaskVec[i] != i) Identity = false;
1972     if (MaskVec[i] != MaskVec[0]) AllSame = false;
1973   }
1974   if (Identity && NElts)
1975     return N1;
1976 
1977   // Shuffling a constant splat doesn't change the result.
1978   if (N2Undef) {
1979     SDValue V = N1;
1980 
1981     // Look through any bitcasts. We check that these don't change the number
1982     // (and size) of elements and just changes their types.
1983     while (V.getOpcode() == ISD::BITCAST)
1984       V = V->getOperand(0);
1985 
1986     // A splat should always show up as a build vector node.
1987     if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) {
1988       BitVector UndefElements;
1989       SDValue Splat = BV->getSplatValue(&UndefElements);
1990       // If this is a splat of an undef, shuffling it is also undef.
1991       if (Splat && Splat.isUndef())
1992         return getUNDEF(VT);
1993 
1994       bool SameNumElts =
1995           V.getValueType().getVectorNumElements() == VT.getVectorNumElements();
1996 
1997       // We only have a splat which can skip shuffles if there is a splatted
1998       // value and no undef lanes rearranged by the shuffle.
1999       if (Splat && UndefElements.none()) {
2000         // Splat of <x, x, ..., x>, return <x, x, ..., x>, provided that the
2001         // number of elements match or the value splatted is a zero constant.
2002         if (SameNumElts)
2003           return N1;
2004         if (auto *C = dyn_cast<ConstantSDNode>(Splat))
2005           if (C->isZero())
2006             return N1;
2007       }
2008 
2009       // If the shuffle itself creates a splat, build the vector directly.
2010       if (AllSame && SameNumElts) {
2011         EVT BuildVT = BV->getValueType(0);
2012         const SDValue &Splatted = BV->getOperand(MaskVec[0]);
2013         SDValue NewBV = getSplatBuildVector(BuildVT, dl, Splatted);
2014 
2015         // We may have jumped through bitcasts, so the type of the
2016         // BUILD_VECTOR may not match the type of the shuffle.
2017         if (BuildVT != VT)
2018           NewBV = getNode(ISD::BITCAST, dl, VT, NewBV);
2019         return NewBV;
2020       }
2021     }
2022   }
2023 
2024   FoldingSetNodeID ID;
2025   SDValue Ops[2] = { N1, N2 };
2026   AddNodeIDNode(ID, ISD::VECTOR_SHUFFLE, getVTList(VT), Ops);
2027   for (int i = 0; i != NElts; ++i)
2028     ID.AddInteger(MaskVec[i]);
2029 
2030   void* IP = nullptr;
2031   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
2032     return SDValue(E, 0);
2033 
2034   // Allocate the mask array for the node out of the BumpPtrAllocator, since
2035   // SDNode doesn't have access to it.  This memory will be "leaked" when
2036   // the node is deallocated, but recovered when the NodeAllocator is released.
2037   int *MaskAlloc = OperandAllocator.Allocate<int>(NElts);
2038   llvm::copy(MaskVec, MaskAlloc);
2039 
2040   auto *N = newSDNode<ShuffleVectorSDNode>(VT, dl.getIROrder(),
2041                                            dl.getDebugLoc(), MaskAlloc);
2042   createOperands(N, Ops);
2043 
2044   CSEMap.InsertNode(N, IP);
2045   InsertNode(N);
2046   SDValue V = SDValue(N, 0);
2047   NewSDValueDbgMsg(V, "Creating new node: ", this);
2048   return V;
2049 }
2050 
2051 SDValue SelectionDAG::getCommutedVectorShuffle(const ShuffleVectorSDNode &SV) {
2052   EVT VT = SV.getValueType(0);
2053   SmallVector<int, 8> MaskVec(SV.getMask().begin(), SV.getMask().end());
2054   ShuffleVectorSDNode::commuteMask(MaskVec);
2055 
2056   SDValue Op0 = SV.getOperand(0);
2057   SDValue Op1 = SV.getOperand(1);
2058   return getVectorShuffle(VT, SDLoc(&SV), Op1, Op0, MaskVec);
2059 }
2060 
2061 SDValue SelectionDAG::getRegister(unsigned RegNo, EVT VT) {
2062   FoldingSetNodeID ID;
2063   AddNodeIDNode(ID, ISD::Register, getVTList(VT), None);
2064   ID.AddInteger(RegNo);
2065   void *IP = nullptr;
2066   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2067     return SDValue(E, 0);
2068 
2069   auto *N = newSDNode<RegisterSDNode>(RegNo, VT);
2070   N->SDNodeBits.IsDivergent = TLI->isSDNodeSourceOfDivergence(N, FLI, DA);
2071   CSEMap.InsertNode(N, IP);
2072   InsertNode(N);
2073   return SDValue(N, 0);
2074 }
2075 
2076 SDValue SelectionDAG::getRegisterMask(const uint32_t *RegMask) {
2077   FoldingSetNodeID ID;
2078   AddNodeIDNode(ID, ISD::RegisterMask, getVTList(MVT::Untyped), None);
2079   ID.AddPointer(RegMask);
2080   void *IP = nullptr;
2081   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2082     return SDValue(E, 0);
2083 
2084   auto *N = newSDNode<RegisterMaskSDNode>(RegMask);
2085   CSEMap.InsertNode(N, IP);
2086   InsertNode(N);
2087   return SDValue(N, 0);
2088 }
2089 
2090 SDValue SelectionDAG::getEHLabel(const SDLoc &dl, SDValue Root,
2091                                  MCSymbol *Label) {
2092   return getLabelNode(ISD::EH_LABEL, dl, Root, Label);
2093 }
2094 
2095 SDValue SelectionDAG::getLabelNode(unsigned Opcode, const SDLoc &dl,
2096                                    SDValue Root, MCSymbol *Label) {
2097   FoldingSetNodeID ID;
2098   SDValue Ops[] = { Root };
2099   AddNodeIDNode(ID, Opcode, getVTList(MVT::Other), Ops);
2100   ID.AddPointer(Label);
2101   void *IP = nullptr;
2102   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2103     return SDValue(E, 0);
2104 
2105   auto *N =
2106       newSDNode<LabelSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), Label);
2107   createOperands(N, Ops);
2108 
2109   CSEMap.InsertNode(N, IP);
2110   InsertNode(N);
2111   return SDValue(N, 0);
2112 }
2113 
2114 SDValue SelectionDAG::getBlockAddress(const BlockAddress *BA, EVT VT,
2115                                       int64_t Offset, bool isTarget,
2116                                       unsigned TargetFlags) {
2117   unsigned Opc = isTarget ? ISD::TargetBlockAddress : ISD::BlockAddress;
2118 
2119   FoldingSetNodeID ID;
2120   AddNodeIDNode(ID, Opc, getVTList(VT), None);
2121   ID.AddPointer(BA);
2122   ID.AddInteger(Offset);
2123   ID.AddInteger(TargetFlags);
2124   void *IP = nullptr;
2125   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2126     return SDValue(E, 0);
2127 
2128   auto *N = newSDNode<BlockAddressSDNode>(Opc, VT, BA, Offset, TargetFlags);
2129   CSEMap.InsertNode(N, IP);
2130   InsertNode(N);
2131   return SDValue(N, 0);
2132 }
2133 
2134 SDValue SelectionDAG::getSrcValue(const Value *V) {
2135   FoldingSetNodeID ID;
2136   AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), None);
2137   ID.AddPointer(V);
2138 
2139   void *IP = nullptr;
2140   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2141     return SDValue(E, 0);
2142 
2143   auto *N = newSDNode<SrcValueSDNode>(V);
2144   CSEMap.InsertNode(N, IP);
2145   InsertNode(N);
2146   return SDValue(N, 0);
2147 }
2148 
2149 SDValue SelectionDAG::getMDNode(const MDNode *MD) {
2150   FoldingSetNodeID ID;
2151   AddNodeIDNode(ID, ISD::MDNODE_SDNODE, getVTList(MVT::Other), None);
2152   ID.AddPointer(MD);
2153 
2154   void *IP = nullptr;
2155   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
2156     return SDValue(E, 0);
2157 
2158   auto *N = newSDNode<MDNodeSDNode>(MD);
2159   CSEMap.InsertNode(N, IP);
2160   InsertNode(N);
2161   return SDValue(N, 0);
2162 }
2163 
2164 SDValue SelectionDAG::getBitcast(EVT VT, SDValue V) {
2165   if (VT == V.getValueType())
2166     return V;
2167 
2168   return getNode(ISD::BITCAST, SDLoc(V), VT, V);
2169 }
2170 
2171 SDValue SelectionDAG::getAddrSpaceCast(const SDLoc &dl, EVT VT, SDValue Ptr,
2172                                        unsigned SrcAS, unsigned DestAS) {
2173   SDValue Ops[] = {Ptr};
2174   FoldingSetNodeID ID;
2175   AddNodeIDNode(ID, ISD::ADDRSPACECAST, getVTList(VT), Ops);
2176   ID.AddInteger(SrcAS);
2177   ID.AddInteger(DestAS);
2178 
2179   void *IP = nullptr;
2180   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
2181     return SDValue(E, 0);
2182 
2183   auto *N = newSDNode<AddrSpaceCastSDNode>(dl.getIROrder(), dl.getDebugLoc(),
2184                                            VT, SrcAS, DestAS);
2185   createOperands(N, Ops);
2186 
2187   CSEMap.InsertNode(N, IP);
2188   InsertNode(N);
2189   return SDValue(N, 0);
2190 }
2191 
2192 SDValue SelectionDAG::getFreeze(SDValue V) {
2193   return getNode(ISD::FREEZE, SDLoc(V), V.getValueType(), V);
2194 }
2195 
2196 /// getShiftAmountOperand - Return the specified value casted to
2197 /// the target's desired shift amount type.
2198 SDValue SelectionDAG::getShiftAmountOperand(EVT LHSTy, SDValue Op) {
2199   EVT OpTy = Op.getValueType();
2200   EVT ShTy = TLI->getShiftAmountTy(LHSTy, getDataLayout());
2201   if (OpTy == ShTy || OpTy.isVector()) return Op;
2202 
2203   return getZExtOrTrunc(Op, SDLoc(Op), ShTy);
2204 }
2205 
2206 SDValue SelectionDAG::expandVAArg(SDNode *Node) {
2207   SDLoc dl(Node);
2208   const TargetLowering &TLI = getTargetLoweringInfo();
2209   const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2210   EVT VT = Node->getValueType(0);
2211   SDValue Tmp1 = Node->getOperand(0);
2212   SDValue Tmp2 = Node->getOperand(1);
2213   const MaybeAlign MA(Node->getConstantOperandVal(3));
2214 
2215   SDValue VAListLoad = getLoad(TLI.getPointerTy(getDataLayout()), dl, Tmp1,
2216                                Tmp2, MachinePointerInfo(V));
2217   SDValue VAList = VAListLoad;
2218 
2219   if (MA && *MA > TLI.getMinStackArgumentAlignment()) {
2220     VAList = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
2221                      getConstant(MA->value() - 1, dl, VAList.getValueType()));
2222 
2223     VAList =
2224         getNode(ISD::AND, dl, VAList.getValueType(), VAList,
2225                 getConstant(-(int64_t)MA->value(), dl, VAList.getValueType()));
2226   }
2227 
2228   // Increment the pointer, VAList, to the next vaarg
2229   Tmp1 = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
2230                  getConstant(getDataLayout().getTypeAllocSize(
2231                                                VT.getTypeForEVT(*getContext())),
2232                              dl, VAList.getValueType()));
2233   // Store the incremented VAList to the legalized pointer
2234   Tmp1 =
2235       getStore(VAListLoad.getValue(1), dl, Tmp1, Tmp2, MachinePointerInfo(V));
2236   // Load the actual argument out of the pointer VAList
2237   return getLoad(VT, dl, Tmp1, VAList, MachinePointerInfo());
2238 }
2239 
2240 SDValue SelectionDAG::expandVACopy(SDNode *Node) {
2241   SDLoc dl(Node);
2242   const TargetLowering &TLI = getTargetLoweringInfo();
2243   // This defaults to loading a pointer from the input and storing it to the
2244   // output, returning the chain.
2245   const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue();
2246   const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue();
2247   SDValue Tmp1 =
2248       getLoad(TLI.getPointerTy(getDataLayout()), dl, Node->getOperand(0),
2249               Node->getOperand(2), MachinePointerInfo(VS));
2250   return getStore(Tmp1.getValue(1), dl, Tmp1, Node->getOperand(1),
2251                   MachinePointerInfo(VD));
2252 }
2253 
2254 Align SelectionDAG::getReducedAlign(EVT VT, bool UseABI) {
2255   const DataLayout &DL = getDataLayout();
2256   Type *Ty = VT.getTypeForEVT(*getContext());
2257   Align RedAlign = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty);
2258 
2259   if (TLI->isTypeLegal(VT) || !VT.isVector())
2260     return RedAlign;
2261 
2262   const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
2263   const Align StackAlign = TFI->getStackAlign();
2264 
2265   // See if we can choose a smaller ABI alignment in cases where it's an
2266   // illegal vector type that will get broken down.
2267   if (RedAlign > StackAlign) {
2268     EVT IntermediateVT;
2269     MVT RegisterVT;
2270     unsigned NumIntermediates;
2271     TLI->getVectorTypeBreakdown(*getContext(), VT, IntermediateVT,
2272                                 NumIntermediates, RegisterVT);
2273     Ty = IntermediateVT.getTypeForEVT(*getContext());
2274     Align RedAlign2 = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty);
2275     if (RedAlign2 < RedAlign)
2276       RedAlign = RedAlign2;
2277   }
2278 
2279   return RedAlign;
2280 }
2281 
2282 SDValue SelectionDAG::CreateStackTemporary(TypeSize Bytes, Align Alignment) {
2283   MachineFrameInfo &MFI = MF->getFrameInfo();
2284   const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
2285   int StackID = 0;
2286   if (Bytes.isScalable())
2287     StackID = TFI->getStackIDForScalableVectors();
2288   // The stack id gives an indication of whether the object is scalable or
2289   // not, so it's safe to pass in the minimum size here.
2290   int FrameIdx = MFI.CreateStackObject(Bytes.getKnownMinSize(), Alignment,
2291                                        false, nullptr, StackID);
2292   return getFrameIndex(FrameIdx, TLI->getFrameIndexTy(getDataLayout()));
2293 }
2294 
2295 SDValue SelectionDAG::CreateStackTemporary(EVT VT, unsigned minAlign) {
2296   Type *Ty = VT.getTypeForEVT(*getContext());
2297   Align StackAlign =
2298       std::max(getDataLayout().getPrefTypeAlign(Ty), Align(minAlign));
2299   return CreateStackTemporary(VT.getStoreSize(), StackAlign);
2300 }
2301 
2302 SDValue SelectionDAG::CreateStackTemporary(EVT VT1, EVT VT2) {
2303   TypeSize VT1Size = VT1.getStoreSize();
2304   TypeSize VT2Size = VT2.getStoreSize();
2305   assert(VT1Size.isScalable() == VT2Size.isScalable() &&
2306          "Don't know how to choose the maximum size when creating a stack "
2307          "temporary");
2308   TypeSize Bytes =
2309       VT1Size.getKnownMinSize() > VT2Size.getKnownMinSize() ? VT1Size : VT2Size;
2310 
2311   Type *Ty1 = VT1.getTypeForEVT(*getContext());
2312   Type *Ty2 = VT2.getTypeForEVT(*getContext());
2313   const DataLayout &DL = getDataLayout();
2314   Align Align = std::max(DL.getPrefTypeAlign(Ty1), DL.getPrefTypeAlign(Ty2));
2315   return CreateStackTemporary(Bytes, Align);
2316 }
2317 
2318 SDValue SelectionDAG::FoldSetCC(EVT VT, SDValue N1, SDValue N2,
2319                                 ISD::CondCode Cond, const SDLoc &dl) {
2320   EVT OpVT = N1.getValueType();
2321 
2322   // These setcc operations always fold.
2323   switch (Cond) {
2324   default: break;
2325   case ISD::SETFALSE:
2326   case ISD::SETFALSE2: return getBoolConstant(false, dl, VT, OpVT);
2327   case ISD::SETTRUE:
2328   case ISD::SETTRUE2: return getBoolConstant(true, dl, VT, OpVT);
2329 
2330   case ISD::SETOEQ:
2331   case ISD::SETOGT:
2332   case ISD::SETOGE:
2333   case ISD::SETOLT:
2334   case ISD::SETOLE:
2335   case ISD::SETONE:
2336   case ISD::SETO:
2337   case ISD::SETUO:
2338   case ISD::SETUEQ:
2339   case ISD::SETUNE:
2340     assert(!OpVT.isInteger() && "Illegal setcc for integer!");
2341     break;
2342   }
2343 
2344   if (OpVT.isInteger()) {
2345     // For EQ and NE, we can always pick a value for the undef to make the
2346     // predicate pass or fail, so we can return undef.
2347     // Matches behavior in llvm::ConstantFoldCompareInstruction.
2348     // icmp eq/ne X, undef -> undef.
2349     if ((N1.isUndef() || N2.isUndef()) &&
2350         (Cond == ISD::SETEQ || Cond == ISD::SETNE))
2351       return getUNDEF(VT);
2352 
2353     // If both operands are undef, we can return undef for int comparison.
2354     // icmp undef, undef -> undef.
2355     if (N1.isUndef() && N2.isUndef())
2356       return getUNDEF(VT);
2357 
2358     // icmp X, X -> true/false
2359     // icmp X, undef -> true/false because undef could be X.
2360     if (N1 == N2)
2361       return getBoolConstant(ISD::isTrueWhenEqual(Cond), dl, VT, OpVT);
2362   }
2363 
2364   if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2)) {
2365     const APInt &C2 = N2C->getAPIntValue();
2366     if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1)) {
2367       const APInt &C1 = N1C->getAPIntValue();
2368 
2369       return getBoolConstant(ICmpInst::compare(C1, C2, getICmpCondCode(Cond)),
2370                              dl, VT, OpVT);
2371     }
2372   }
2373 
2374   auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
2375   auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
2376 
2377   if (N1CFP && N2CFP) {
2378     APFloat::cmpResult R = N1CFP->getValueAPF().compare(N2CFP->getValueAPF());
2379     switch (Cond) {
2380     default: break;
2381     case ISD::SETEQ:  if (R==APFloat::cmpUnordered)
2382                         return getUNDEF(VT);
2383                       LLVM_FALLTHROUGH;
2384     case ISD::SETOEQ: return getBoolConstant(R==APFloat::cmpEqual, dl, VT,
2385                                              OpVT);
2386     case ISD::SETNE:  if (R==APFloat::cmpUnordered)
2387                         return getUNDEF(VT);
2388                       LLVM_FALLTHROUGH;
2389     case ISD::SETONE: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2390                                              R==APFloat::cmpLessThan, dl, VT,
2391                                              OpVT);
2392     case ISD::SETLT:  if (R==APFloat::cmpUnordered)
2393                         return getUNDEF(VT);
2394                       LLVM_FALLTHROUGH;
2395     case ISD::SETOLT: return getBoolConstant(R==APFloat::cmpLessThan, dl, VT,
2396                                              OpVT);
2397     case ISD::SETGT:  if (R==APFloat::cmpUnordered)
2398                         return getUNDEF(VT);
2399                       LLVM_FALLTHROUGH;
2400     case ISD::SETOGT: return getBoolConstant(R==APFloat::cmpGreaterThan, dl,
2401                                              VT, OpVT);
2402     case ISD::SETLE:  if (R==APFloat::cmpUnordered)
2403                         return getUNDEF(VT);
2404                       LLVM_FALLTHROUGH;
2405     case ISD::SETOLE: return getBoolConstant(R==APFloat::cmpLessThan ||
2406                                              R==APFloat::cmpEqual, dl, VT,
2407                                              OpVT);
2408     case ISD::SETGE:  if (R==APFloat::cmpUnordered)
2409                         return getUNDEF(VT);
2410                       LLVM_FALLTHROUGH;
2411     case ISD::SETOGE: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2412                                          R==APFloat::cmpEqual, dl, VT, OpVT);
2413     case ISD::SETO:   return getBoolConstant(R!=APFloat::cmpUnordered, dl, VT,
2414                                              OpVT);
2415     case ISD::SETUO:  return getBoolConstant(R==APFloat::cmpUnordered, dl, VT,
2416                                              OpVT);
2417     case ISD::SETUEQ: return getBoolConstant(R==APFloat::cmpUnordered ||
2418                                              R==APFloat::cmpEqual, dl, VT,
2419                                              OpVT);
2420     case ISD::SETUNE: return getBoolConstant(R!=APFloat::cmpEqual, dl, VT,
2421                                              OpVT);
2422     case ISD::SETULT: return getBoolConstant(R==APFloat::cmpUnordered ||
2423                                              R==APFloat::cmpLessThan, dl, VT,
2424                                              OpVT);
2425     case ISD::SETUGT: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2426                                              R==APFloat::cmpUnordered, dl, VT,
2427                                              OpVT);
2428     case ISD::SETULE: return getBoolConstant(R!=APFloat::cmpGreaterThan, dl,
2429                                              VT, OpVT);
2430     case ISD::SETUGE: return getBoolConstant(R!=APFloat::cmpLessThan, dl, VT,
2431                                              OpVT);
2432     }
2433   } else if (N1CFP && OpVT.isSimple() && !N2.isUndef()) {
2434     // Ensure that the constant occurs on the RHS.
2435     ISD::CondCode SwappedCond = ISD::getSetCCSwappedOperands(Cond);
2436     if (!TLI->isCondCodeLegal(SwappedCond, OpVT.getSimpleVT()))
2437       return SDValue();
2438     return getSetCC(dl, VT, N2, N1, SwappedCond);
2439   } else if ((N2CFP && N2CFP->getValueAPF().isNaN()) ||
2440              (OpVT.isFloatingPoint() && (N1.isUndef() || N2.isUndef()))) {
2441     // If an operand is known to be a nan (or undef that could be a nan), we can
2442     // fold it.
2443     // Choosing NaN for the undef will always make unordered comparison succeed
2444     // and ordered comparison fails.
2445     // Matches behavior in llvm::ConstantFoldCompareInstruction.
2446     switch (ISD::getUnorderedFlavor(Cond)) {
2447     default:
2448       llvm_unreachable("Unknown flavor!");
2449     case 0: // Known false.
2450       return getBoolConstant(false, dl, VT, OpVT);
2451     case 1: // Known true.
2452       return getBoolConstant(true, dl, VT, OpVT);
2453     case 2: // Undefined.
2454       return getUNDEF(VT);
2455     }
2456   }
2457 
2458   // Could not fold it.
2459   return SDValue();
2460 }
2461 
2462 /// See if the specified operand can be simplified with the knowledge that only
2463 /// the bits specified by DemandedBits are used.
2464 /// TODO: really we should be making this into the DAG equivalent of
2465 /// SimplifyMultipleUseDemandedBits and not generate any new nodes.
2466 SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &DemandedBits) {
2467   EVT VT = V.getValueType();
2468 
2469   if (VT.isScalableVector())
2470     return SDValue();
2471 
2472   APInt DemandedElts = VT.isVector()
2473                            ? APInt::getAllOnes(VT.getVectorNumElements())
2474                            : APInt(1, 1);
2475   return GetDemandedBits(V, DemandedBits, DemandedElts);
2476 }
2477 
2478 /// See if the specified operand can be simplified with the knowledge that only
2479 /// the bits specified by DemandedBits are used in the elements specified by
2480 /// DemandedElts.
2481 /// TODO: really we should be making this into the DAG equivalent of
2482 /// SimplifyMultipleUseDemandedBits and not generate any new nodes.
2483 SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &DemandedBits,
2484                                       const APInt &DemandedElts) {
2485   switch (V.getOpcode()) {
2486   default:
2487     return TLI->SimplifyMultipleUseDemandedBits(V, DemandedBits, DemandedElts,
2488                                                 *this);
2489   case ISD::Constant: {
2490     const APInt &CVal = cast<ConstantSDNode>(V)->getAPIntValue();
2491     APInt NewVal = CVal & DemandedBits;
2492     if (NewVal != CVal)
2493       return getConstant(NewVal, SDLoc(V), V.getValueType());
2494     break;
2495   }
2496   case ISD::SRL:
2497     // Only look at single-use SRLs.
2498     if (!V.getNode()->hasOneUse())
2499       break;
2500     if (auto *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
2501       // See if we can recursively simplify the LHS.
2502       unsigned Amt = RHSC->getZExtValue();
2503 
2504       // Watch out for shift count overflow though.
2505       if (Amt >= DemandedBits.getBitWidth())
2506         break;
2507       APInt SrcDemandedBits = DemandedBits << Amt;
2508       if (SDValue SimplifyLHS =
2509               GetDemandedBits(V.getOperand(0), SrcDemandedBits))
2510         return getNode(ISD::SRL, SDLoc(V), V.getValueType(), SimplifyLHS,
2511                        V.getOperand(1));
2512     }
2513     break;
2514   }
2515   return SDValue();
2516 }
2517 
2518 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero.  We
2519 /// use this predicate to simplify operations downstream.
2520 bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const {
2521   unsigned BitWidth = Op.getScalarValueSizeInBits();
2522   return MaskedValueIsZero(Op, APInt::getSignMask(BitWidth), Depth);
2523 }
2524 
2525 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero.  We use
2526 /// this predicate to simplify operations downstream.  Mask is known to be zero
2527 /// for bits that V cannot have.
2528 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask,
2529                                      unsigned Depth) const {
2530   return Mask.isSubsetOf(computeKnownBits(V, Depth).Zero);
2531 }
2532 
2533 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero in
2534 /// DemandedElts.  We use this predicate to simplify operations downstream.
2535 /// Mask is known to be zero for bits that V cannot have.
2536 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask,
2537                                      const APInt &DemandedElts,
2538                                      unsigned Depth) const {
2539   return Mask.isSubsetOf(computeKnownBits(V, DemandedElts, Depth).Zero);
2540 }
2541 
2542 /// MaskedValueIsAllOnes - Return true if '(Op & Mask) == Mask'.
2543 bool SelectionDAG::MaskedValueIsAllOnes(SDValue V, const APInt &Mask,
2544                                         unsigned Depth) const {
2545   return Mask.isSubsetOf(computeKnownBits(V, Depth).One);
2546 }
2547 
2548 /// isSplatValue - Return true if the vector V has the same value
2549 /// across all DemandedElts. For scalable vectors it does not make
2550 /// sense to specify which elements are demanded or undefined, therefore
2551 /// they are simply ignored.
2552 bool SelectionDAG::isSplatValue(SDValue V, const APInt &DemandedElts,
2553                                 APInt &UndefElts, unsigned Depth) const {
2554   unsigned Opcode = V.getOpcode();
2555   EVT VT = V.getValueType();
2556   assert(VT.isVector() && "Vector type expected");
2557 
2558   if (!VT.isScalableVector() && !DemandedElts)
2559     return false; // No demanded elts, better to assume we don't know anything.
2560 
2561   if (Depth >= MaxRecursionDepth)
2562     return false; // Limit search depth.
2563 
2564   // Deal with some common cases here that work for both fixed and scalable
2565   // vector types.
2566   switch (Opcode) {
2567   case ISD::SPLAT_VECTOR:
2568     UndefElts = V.getOperand(0).isUndef()
2569                     ? APInt::getAllOnes(DemandedElts.getBitWidth())
2570                     : APInt(DemandedElts.getBitWidth(), 0);
2571     return true;
2572   case ISD::ADD:
2573   case ISD::SUB:
2574   case ISD::AND:
2575   case ISD::XOR:
2576   case ISD::OR: {
2577     APInt UndefLHS, UndefRHS;
2578     SDValue LHS = V.getOperand(0);
2579     SDValue RHS = V.getOperand(1);
2580     if (isSplatValue(LHS, DemandedElts, UndefLHS, Depth + 1) &&
2581         isSplatValue(RHS, DemandedElts, UndefRHS, Depth + 1)) {
2582       UndefElts = UndefLHS | UndefRHS;
2583       return true;
2584     }
2585     return false;
2586   }
2587   case ISD::ABS:
2588   case ISD::TRUNCATE:
2589   case ISD::SIGN_EXTEND:
2590   case ISD::ZERO_EXTEND:
2591     return isSplatValue(V.getOperand(0), DemandedElts, UndefElts, Depth + 1);
2592   default:
2593     if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
2594         Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID)
2595       return TLI->isSplatValueForTargetNode(V, DemandedElts, UndefElts, Depth);
2596     break;
2597 }
2598 
2599   // We don't support other cases than those above for scalable vectors at
2600   // the moment.
2601   if (VT.isScalableVector())
2602     return false;
2603 
2604   unsigned NumElts = VT.getVectorNumElements();
2605   assert(NumElts == DemandedElts.getBitWidth() && "Vector size mismatch");
2606   UndefElts = APInt::getZero(NumElts);
2607 
2608   switch (Opcode) {
2609   case ISD::BUILD_VECTOR: {
2610     SDValue Scl;
2611     for (unsigned i = 0; i != NumElts; ++i) {
2612       SDValue Op = V.getOperand(i);
2613       if (Op.isUndef()) {
2614         UndefElts.setBit(i);
2615         continue;
2616       }
2617       if (!DemandedElts[i])
2618         continue;
2619       if (Scl && Scl != Op)
2620         return false;
2621       Scl = Op;
2622     }
2623     return true;
2624   }
2625   case ISD::VECTOR_SHUFFLE: {
2626     // Check if this is a shuffle node doing a splat or a shuffle of a splat.
2627     APInt DemandedLHS = APInt::getNullValue(NumElts);
2628     APInt DemandedRHS = APInt::getNullValue(NumElts);
2629     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(V)->getMask();
2630     for (int i = 0; i != (int)NumElts; ++i) {
2631       int M = Mask[i];
2632       if (M < 0) {
2633         UndefElts.setBit(i);
2634         continue;
2635       }
2636       if (!DemandedElts[i])
2637         continue;
2638       if (M < (int)NumElts)
2639         DemandedLHS.setBit(M);
2640       else
2641         DemandedRHS.setBit(M - NumElts);
2642     }
2643 
2644     // If we aren't demanding either op, assume there's no splat.
2645     // If we are demanding both ops, assume there's no splat.
2646     if ((DemandedLHS.isZero() && DemandedRHS.isZero()) ||
2647         (!DemandedLHS.isZero() && !DemandedRHS.isZero()))
2648       return false;
2649 
2650     // See if the demanded elts of the source op is a splat or we only demand
2651     // one element, which should always be a splat.
2652     // TODO: Handle source ops splats with undefs.
2653     auto CheckSplatSrc = [&](SDValue Src, const APInt &SrcElts) {
2654       APInt SrcUndefs;
2655       return (SrcElts.countPopulation() == 1) ||
2656              (isSplatValue(Src, SrcElts, SrcUndefs, Depth + 1) &&
2657               (SrcElts & SrcUndefs).isZero());
2658     };
2659     if (!DemandedLHS.isZero())
2660       return CheckSplatSrc(V.getOperand(0), DemandedLHS);
2661     return CheckSplatSrc(V.getOperand(1), DemandedRHS);
2662   }
2663   case ISD::EXTRACT_SUBVECTOR: {
2664     // Offset the demanded elts by the subvector index.
2665     SDValue Src = V.getOperand(0);
2666     // We don't support scalable vectors at the moment.
2667     if (Src.getValueType().isScalableVector())
2668       return false;
2669     uint64_t Idx = V.getConstantOperandVal(1);
2670     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2671     APInt UndefSrcElts;
2672     APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
2673     if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) {
2674       UndefElts = UndefSrcElts.extractBits(NumElts, Idx);
2675       return true;
2676     }
2677     break;
2678   }
2679   case ISD::ANY_EXTEND_VECTOR_INREG:
2680   case ISD::SIGN_EXTEND_VECTOR_INREG:
2681   case ISD::ZERO_EXTEND_VECTOR_INREG: {
2682     // Widen the demanded elts by the src element count.
2683     SDValue Src = V.getOperand(0);
2684     // We don't support scalable vectors at the moment.
2685     if (Src.getValueType().isScalableVector())
2686       return false;
2687     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2688     APInt UndefSrcElts;
2689     APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts);
2690     if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) {
2691       UndefElts = UndefSrcElts.trunc(NumElts);
2692       return true;
2693     }
2694     break;
2695   }
2696   case ISD::BITCAST: {
2697     SDValue Src = V.getOperand(0);
2698     EVT SrcVT = Src.getValueType();
2699     unsigned SrcBitWidth = SrcVT.getScalarSizeInBits();
2700     unsigned BitWidth = VT.getScalarSizeInBits();
2701 
2702     // Ignore bitcasts from unsupported types.
2703     // TODO: Add fp support?
2704     if (!SrcVT.isVector() || !SrcVT.isInteger() || !VT.isInteger())
2705       break;
2706 
2707     // Bitcast 'small element' vector to 'large element' vector.
2708     if ((BitWidth % SrcBitWidth) == 0) {
2709       // See if each sub element is a splat.
2710       unsigned Scale = BitWidth / SrcBitWidth;
2711       unsigned NumSrcElts = SrcVT.getVectorNumElements();
2712       APInt ScaledDemandedElts =
2713           APIntOps::ScaleBitMask(DemandedElts, NumSrcElts);
2714       for (unsigned I = 0; I != Scale; ++I) {
2715         APInt SubUndefElts;
2716         APInt SubDemandedElt = APInt::getOneBitSet(Scale, I);
2717         APInt SubDemandedElts = APInt::getSplat(NumSrcElts, SubDemandedElt);
2718         SubDemandedElts &= ScaledDemandedElts;
2719         if (!isSplatValue(Src, SubDemandedElts, SubUndefElts, Depth + 1))
2720           return false;
2721         UndefElts |= APIntOps::ScaleBitMask(SubUndefElts, NumElts);
2722       }
2723       return true;
2724     }
2725     break;
2726   }
2727   }
2728 
2729   return false;
2730 }
2731 
2732 /// Helper wrapper to main isSplatValue function.
2733 bool SelectionDAG::isSplatValue(SDValue V, bool AllowUndefs) const {
2734   EVT VT = V.getValueType();
2735   assert(VT.isVector() && "Vector type expected");
2736 
2737   APInt UndefElts;
2738   APInt DemandedElts;
2739 
2740   // For now we don't support this with scalable vectors.
2741   if (!VT.isScalableVector())
2742     DemandedElts = APInt::getAllOnes(VT.getVectorNumElements());
2743   return isSplatValue(V, DemandedElts, UndefElts) &&
2744          (AllowUndefs || !UndefElts);
2745 }
2746 
2747 SDValue SelectionDAG::getSplatSourceVector(SDValue V, int &SplatIdx) {
2748   V = peekThroughExtractSubvectors(V);
2749 
2750   EVT VT = V.getValueType();
2751   unsigned Opcode = V.getOpcode();
2752   switch (Opcode) {
2753   default: {
2754     APInt UndefElts;
2755     APInt DemandedElts;
2756 
2757     if (!VT.isScalableVector())
2758       DemandedElts = APInt::getAllOnes(VT.getVectorNumElements());
2759 
2760     if (isSplatValue(V, DemandedElts, UndefElts)) {
2761       if (VT.isScalableVector()) {
2762         // DemandedElts and UndefElts are ignored for scalable vectors, since
2763         // the only supported cases are SPLAT_VECTOR nodes.
2764         SplatIdx = 0;
2765       } else {
2766         // Handle case where all demanded elements are UNDEF.
2767         if (DemandedElts.isSubsetOf(UndefElts)) {
2768           SplatIdx = 0;
2769           return getUNDEF(VT);
2770         }
2771         SplatIdx = (UndefElts & DemandedElts).countTrailingOnes();
2772       }
2773       return V;
2774     }
2775     break;
2776   }
2777   case ISD::SPLAT_VECTOR:
2778     SplatIdx = 0;
2779     return V;
2780   case ISD::VECTOR_SHUFFLE: {
2781     if (VT.isScalableVector())
2782       return SDValue();
2783 
2784     // Check if this is a shuffle node doing a splat.
2785     // TODO - remove this and rely purely on SelectionDAG::isSplatValue,
2786     // getTargetVShiftNode currently struggles without the splat source.
2787     auto *SVN = cast<ShuffleVectorSDNode>(V);
2788     if (!SVN->isSplat())
2789       break;
2790     int Idx = SVN->getSplatIndex();
2791     int NumElts = V.getValueType().getVectorNumElements();
2792     SplatIdx = Idx % NumElts;
2793     return V.getOperand(Idx / NumElts);
2794   }
2795   }
2796 
2797   return SDValue();
2798 }
2799 
2800 SDValue SelectionDAG::getSplatValue(SDValue V, bool LegalTypes) {
2801   int SplatIdx;
2802   if (SDValue SrcVector = getSplatSourceVector(V, SplatIdx)) {
2803     EVT SVT = SrcVector.getValueType().getScalarType();
2804     EVT LegalSVT = SVT;
2805     if (LegalTypes && !TLI->isTypeLegal(SVT)) {
2806       if (!SVT.isInteger())
2807         return SDValue();
2808       LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
2809       if (LegalSVT.bitsLT(SVT))
2810         return SDValue();
2811     }
2812     return getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(V), LegalSVT, SrcVector,
2813                    getVectorIdxConstant(SplatIdx, SDLoc(V)));
2814   }
2815   return SDValue();
2816 }
2817 
2818 const APInt *
2819 SelectionDAG::getValidShiftAmountConstant(SDValue V,
2820                                           const APInt &DemandedElts) const {
2821   assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
2822           V.getOpcode() == ISD::SRA) &&
2823          "Unknown shift node");
2824   unsigned BitWidth = V.getScalarValueSizeInBits();
2825   if (ConstantSDNode *SA = isConstOrConstSplat(V.getOperand(1), DemandedElts)) {
2826     // Shifting more than the bitwidth is not valid.
2827     const APInt &ShAmt = SA->getAPIntValue();
2828     if (ShAmt.ult(BitWidth))
2829       return &ShAmt;
2830   }
2831   return nullptr;
2832 }
2833 
2834 const APInt *SelectionDAG::getValidMinimumShiftAmountConstant(
2835     SDValue V, const APInt &DemandedElts) const {
2836   assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
2837           V.getOpcode() == ISD::SRA) &&
2838          "Unknown shift node");
2839   if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts))
2840     return ValidAmt;
2841   unsigned BitWidth = V.getScalarValueSizeInBits();
2842   auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1));
2843   if (!BV)
2844     return nullptr;
2845   const APInt *MinShAmt = nullptr;
2846   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
2847     if (!DemandedElts[i])
2848       continue;
2849     auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i));
2850     if (!SA)
2851       return nullptr;
2852     // Shifting more than the bitwidth is not valid.
2853     const APInt &ShAmt = SA->getAPIntValue();
2854     if (ShAmt.uge(BitWidth))
2855       return nullptr;
2856     if (MinShAmt && MinShAmt->ule(ShAmt))
2857       continue;
2858     MinShAmt = &ShAmt;
2859   }
2860   return MinShAmt;
2861 }
2862 
2863 const APInt *SelectionDAG::getValidMaximumShiftAmountConstant(
2864     SDValue V, const APInt &DemandedElts) const {
2865   assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
2866           V.getOpcode() == ISD::SRA) &&
2867          "Unknown shift node");
2868   if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts))
2869     return ValidAmt;
2870   unsigned BitWidth = V.getScalarValueSizeInBits();
2871   auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1));
2872   if (!BV)
2873     return nullptr;
2874   const APInt *MaxShAmt = nullptr;
2875   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
2876     if (!DemandedElts[i])
2877       continue;
2878     auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i));
2879     if (!SA)
2880       return nullptr;
2881     // Shifting more than the bitwidth is not valid.
2882     const APInt &ShAmt = SA->getAPIntValue();
2883     if (ShAmt.uge(BitWidth))
2884       return nullptr;
2885     if (MaxShAmt && MaxShAmt->uge(ShAmt))
2886       continue;
2887     MaxShAmt = &ShAmt;
2888   }
2889   return MaxShAmt;
2890 }
2891 
2892 /// Determine which bits of Op are known to be either zero or one and return
2893 /// them in Known. For vectors, the known bits are those that are shared by
2894 /// every vector element.
2895 KnownBits SelectionDAG::computeKnownBits(SDValue Op, unsigned Depth) const {
2896   EVT VT = Op.getValueType();
2897 
2898   // TOOD: Until we have a plan for how to represent demanded elements for
2899   // scalable vectors, we can just bail out for now.
2900   if (Op.getValueType().isScalableVector()) {
2901     unsigned BitWidth = Op.getScalarValueSizeInBits();
2902     return KnownBits(BitWidth);
2903   }
2904 
2905   APInt DemandedElts = VT.isVector()
2906                            ? APInt::getAllOnes(VT.getVectorNumElements())
2907                            : APInt(1, 1);
2908   return computeKnownBits(Op, DemandedElts, Depth);
2909 }
2910 
2911 /// Determine which bits of Op are known to be either zero or one and return
2912 /// them in Known. The DemandedElts argument allows us to only collect the known
2913 /// bits that are shared by the requested vector elements.
2914 KnownBits SelectionDAG::computeKnownBits(SDValue Op, const APInt &DemandedElts,
2915                                          unsigned Depth) const {
2916   unsigned BitWidth = Op.getScalarValueSizeInBits();
2917 
2918   KnownBits Known(BitWidth);   // Don't know anything.
2919 
2920   // TOOD: Until we have a plan for how to represent demanded elements for
2921   // scalable vectors, we can just bail out for now.
2922   if (Op.getValueType().isScalableVector())
2923     return Known;
2924 
2925   if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
2926     // We know all of the bits for a constant!
2927     return KnownBits::makeConstant(C->getAPIntValue());
2928   }
2929   if (auto *C = dyn_cast<ConstantFPSDNode>(Op)) {
2930     // We know all of the bits for a constant fp!
2931     return KnownBits::makeConstant(C->getValueAPF().bitcastToAPInt());
2932   }
2933 
2934   if (Depth >= MaxRecursionDepth)
2935     return Known;  // Limit search depth.
2936 
2937   KnownBits Known2;
2938   unsigned NumElts = DemandedElts.getBitWidth();
2939   assert((!Op.getValueType().isVector() ||
2940           NumElts == Op.getValueType().getVectorNumElements()) &&
2941          "Unexpected vector size");
2942 
2943   if (!DemandedElts)
2944     return Known;  // No demanded elts, better to assume we don't know anything.
2945 
2946   unsigned Opcode = Op.getOpcode();
2947   switch (Opcode) {
2948   case ISD::BUILD_VECTOR:
2949     // Collect the known bits that are shared by every demanded vector element.
2950     Known.Zero.setAllBits(); Known.One.setAllBits();
2951     for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
2952       if (!DemandedElts[i])
2953         continue;
2954 
2955       SDValue SrcOp = Op.getOperand(i);
2956       Known2 = computeKnownBits(SrcOp, Depth + 1);
2957 
2958       // BUILD_VECTOR can implicitly truncate sources, we must handle this.
2959       if (SrcOp.getValueSizeInBits() != BitWidth) {
2960         assert(SrcOp.getValueSizeInBits() > BitWidth &&
2961                "Expected BUILD_VECTOR implicit truncation");
2962         Known2 = Known2.trunc(BitWidth);
2963       }
2964 
2965       // Known bits are the values that are shared by every demanded element.
2966       Known = KnownBits::commonBits(Known, Known2);
2967 
2968       // If we don't know any bits, early out.
2969       if (Known.isUnknown())
2970         break;
2971     }
2972     break;
2973   case ISD::VECTOR_SHUFFLE: {
2974     // Collect the known bits that are shared by every vector element referenced
2975     // by the shuffle.
2976     APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
2977     Known.Zero.setAllBits(); Known.One.setAllBits();
2978     const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
2979     assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
2980     for (unsigned i = 0; i != NumElts; ++i) {
2981       if (!DemandedElts[i])
2982         continue;
2983 
2984       int M = SVN->getMaskElt(i);
2985       if (M < 0) {
2986         // For UNDEF elements, we don't know anything about the common state of
2987         // the shuffle result.
2988         Known.resetAll();
2989         DemandedLHS.clearAllBits();
2990         DemandedRHS.clearAllBits();
2991         break;
2992       }
2993 
2994       if ((unsigned)M < NumElts)
2995         DemandedLHS.setBit((unsigned)M % NumElts);
2996       else
2997         DemandedRHS.setBit((unsigned)M % NumElts);
2998     }
2999     // Known bits are the values that are shared by every demanded element.
3000     if (!!DemandedLHS) {
3001       SDValue LHS = Op.getOperand(0);
3002       Known2 = computeKnownBits(LHS, DemandedLHS, Depth + 1);
3003       Known = KnownBits::commonBits(Known, Known2);
3004     }
3005     // If we don't know any bits, early out.
3006     if (Known.isUnknown())
3007       break;
3008     if (!!DemandedRHS) {
3009       SDValue RHS = Op.getOperand(1);
3010       Known2 = computeKnownBits(RHS, DemandedRHS, Depth + 1);
3011       Known = KnownBits::commonBits(Known, Known2);
3012     }
3013     break;
3014   }
3015   case ISD::CONCAT_VECTORS: {
3016     // Split DemandedElts and test each of the demanded subvectors.
3017     Known.Zero.setAllBits(); Known.One.setAllBits();
3018     EVT SubVectorVT = Op.getOperand(0).getValueType();
3019     unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
3020     unsigned NumSubVectors = Op.getNumOperands();
3021     for (unsigned i = 0; i != NumSubVectors; ++i) {
3022       APInt DemandedSub =
3023           DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts);
3024       if (!!DemandedSub) {
3025         SDValue Sub = Op.getOperand(i);
3026         Known2 = computeKnownBits(Sub, DemandedSub, Depth + 1);
3027         Known = KnownBits::commonBits(Known, Known2);
3028       }
3029       // If we don't know any bits, early out.
3030       if (Known.isUnknown())
3031         break;
3032     }
3033     break;
3034   }
3035   case ISD::INSERT_SUBVECTOR: {
3036     // Demand any elements from the subvector and the remainder from the src its
3037     // inserted into.
3038     SDValue Src = Op.getOperand(0);
3039     SDValue Sub = Op.getOperand(1);
3040     uint64_t Idx = Op.getConstantOperandVal(2);
3041     unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
3042     APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
3043     APInt DemandedSrcElts = DemandedElts;
3044     DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx);
3045 
3046     Known.One.setAllBits();
3047     Known.Zero.setAllBits();
3048     if (!!DemandedSubElts) {
3049       Known = computeKnownBits(Sub, DemandedSubElts, Depth + 1);
3050       if (Known.isUnknown())
3051         break; // early-out.
3052     }
3053     if (!!DemandedSrcElts) {
3054       Known2 = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
3055       Known = KnownBits::commonBits(Known, Known2);
3056     }
3057     break;
3058   }
3059   case ISD::EXTRACT_SUBVECTOR: {
3060     // Offset the demanded elts by the subvector index.
3061     SDValue Src = Op.getOperand(0);
3062     // Bail until we can represent demanded elements for scalable vectors.
3063     if (Src.getValueType().isScalableVector())
3064       break;
3065     uint64_t Idx = Op.getConstantOperandVal(1);
3066     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
3067     APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
3068     Known = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
3069     break;
3070   }
3071   case ISD::SCALAR_TO_VECTOR: {
3072     // We know about scalar_to_vector as much as we know about it source,
3073     // which becomes the first element of otherwise unknown vector.
3074     if (DemandedElts != 1)
3075       break;
3076 
3077     SDValue N0 = Op.getOperand(0);
3078     Known = computeKnownBits(N0, Depth + 1);
3079     if (N0.getValueSizeInBits() != BitWidth)
3080       Known = Known.trunc(BitWidth);
3081 
3082     break;
3083   }
3084   case ISD::BITCAST: {
3085     SDValue N0 = Op.getOperand(0);
3086     EVT SubVT = N0.getValueType();
3087     unsigned SubBitWidth = SubVT.getScalarSizeInBits();
3088 
3089     // Ignore bitcasts from unsupported types.
3090     if (!(SubVT.isInteger() || SubVT.isFloatingPoint()))
3091       break;
3092 
3093     // Fast handling of 'identity' bitcasts.
3094     if (BitWidth == SubBitWidth) {
3095       Known = computeKnownBits(N0, DemandedElts, Depth + 1);
3096       break;
3097     }
3098 
3099     bool IsLE = getDataLayout().isLittleEndian();
3100 
3101     // Bitcast 'small element' vector to 'large element' scalar/vector.
3102     if ((BitWidth % SubBitWidth) == 0) {
3103       assert(N0.getValueType().isVector() && "Expected bitcast from vector");
3104 
3105       // Collect known bits for the (larger) output by collecting the known
3106       // bits from each set of sub elements and shift these into place.
3107       // We need to separately call computeKnownBits for each set of
3108       // sub elements as the knownbits for each is likely to be different.
3109       unsigned SubScale = BitWidth / SubBitWidth;
3110       APInt SubDemandedElts(NumElts * SubScale, 0);
3111       for (unsigned i = 0; i != NumElts; ++i)
3112         if (DemandedElts[i])
3113           SubDemandedElts.setBit(i * SubScale);
3114 
3115       for (unsigned i = 0; i != SubScale; ++i) {
3116         Known2 = computeKnownBits(N0, SubDemandedElts.shl(i),
3117                          Depth + 1);
3118         unsigned Shifts = IsLE ? i : SubScale - 1 - i;
3119         Known.insertBits(Known2, SubBitWidth * Shifts);
3120       }
3121     }
3122 
3123     // Bitcast 'large element' scalar/vector to 'small element' vector.
3124     if ((SubBitWidth % BitWidth) == 0) {
3125       assert(Op.getValueType().isVector() && "Expected bitcast to vector");
3126 
3127       // Collect known bits for the (smaller) output by collecting the known
3128       // bits from the overlapping larger input elements and extracting the
3129       // sub sections we actually care about.
3130       unsigned SubScale = SubBitWidth / BitWidth;
3131       APInt SubDemandedElts =
3132           APIntOps::ScaleBitMask(DemandedElts, NumElts / SubScale);
3133       Known2 = computeKnownBits(N0, SubDemandedElts, Depth + 1);
3134 
3135       Known.Zero.setAllBits(); Known.One.setAllBits();
3136       for (unsigned i = 0; i != NumElts; ++i)
3137         if (DemandedElts[i]) {
3138           unsigned Shifts = IsLE ? i : NumElts - 1 - i;
3139           unsigned Offset = (Shifts % SubScale) * BitWidth;
3140           Known = KnownBits::commonBits(Known,
3141                                         Known2.extractBits(BitWidth, Offset));
3142           // If we don't know any bits, early out.
3143           if (Known.isUnknown())
3144             break;
3145         }
3146     }
3147     break;
3148   }
3149   case ISD::AND:
3150     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3151     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3152 
3153     Known &= Known2;
3154     break;
3155   case ISD::OR:
3156     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3157     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3158 
3159     Known |= Known2;
3160     break;
3161   case ISD::XOR:
3162     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3163     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3164 
3165     Known ^= Known2;
3166     break;
3167   case ISD::MUL: {
3168     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3169     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3170     bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1);
3171     // TODO: SelfMultiply can be poison, but not undef.
3172     if (SelfMultiply)
3173       SelfMultiply &= isGuaranteedNotToBeUndefOrPoison(
3174           Op.getOperand(0), DemandedElts, false, Depth + 1);
3175     Known = KnownBits::mul(Known, Known2, SelfMultiply);
3176     break;
3177   }
3178   case ISD::MULHU: {
3179     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3180     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3181     Known = KnownBits::mulhu(Known, Known2);
3182     break;
3183   }
3184   case ISD::MULHS: {
3185     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3186     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3187     Known = KnownBits::mulhs(Known, Known2);
3188     break;
3189   }
3190   case ISD::UMUL_LOHI: {
3191     assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3192     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3193     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3194     bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1);
3195     if (Op.getResNo() == 0)
3196       Known = KnownBits::mul(Known, Known2, SelfMultiply);
3197     else
3198       Known = KnownBits::mulhu(Known, Known2);
3199     break;
3200   }
3201   case ISD::SMUL_LOHI: {
3202     assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
3203     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3204     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3205     bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1);
3206     if (Op.getResNo() == 0)
3207       Known = KnownBits::mul(Known, Known2, SelfMultiply);
3208     else
3209       Known = KnownBits::mulhs(Known, Known2);
3210     break;
3211   }
3212   case ISD::UDIV: {
3213     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3214     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3215     Known = KnownBits::udiv(Known, Known2);
3216     break;
3217   }
3218   case ISD::AVGCEILU: {
3219     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3220     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3221     Known = Known.zext(BitWidth + 1);
3222     Known2 = Known2.zext(BitWidth + 1);
3223     KnownBits One = KnownBits::makeConstant(APInt(1, 1));
3224     Known = KnownBits::computeForAddCarry(Known, Known2, One);
3225     Known = Known.extractBits(BitWidth, 1);
3226     break;
3227   }
3228   case ISD::SELECT:
3229   case ISD::VSELECT:
3230     Known = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
3231     // If we don't know any bits, early out.
3232     if (Known.isUnknown())
3233       break;
3234     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth+1);
3235 
3236     // Only known if known in both the LHS and RHS.
3237     Known = KnownBits::commonBits(Known, Known2);
3238     break;
3239   case ISD::SELECT_CC:
3240     Known = computeKnownBits(Op.getOperand(3), DemandedElts, Depth+1);
3241     // If we don't know any bits, early out.
3242     if (Known.isUnknown())
3243       break;
3244     Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
3245 
3246     // Only known if known in both the LHS and RHS.
3247     Known = KnownBits::commonBits(Known, Known2);
3248     break;
3249   case ISD::SMULO:
3250   case ISD::UMULO:
3251     if (Op.getResNo() != 1)
3252       break;
3253     // The boolean result conforms to getBooleanContents.
3254     // If we know the result of a setcc has the top bits zero, use this info.
3255     // We know that we have an integer-based boolean since these operations
3256     // are only available for integer.
3257     if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
3258             TargetLowering::ZeroOrOneBooleanContent &&
3259         BitWidth > 1)
3260       Known.Zero.setBitsFrom(1);
3261     break;
3262   case ISD::SETCC:
3263   case ISD::STRICT_FSETCC:
3264   case ISD::STRICT_FSETCCS: {
3265     unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
3266     // If we know the result of a setcc has the top bits zero, use this info.
3267     if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
3268             TargetLowering::ZeroOrOneBooleanContent &&
3269         BitWidth > 1)
3270       Known.Zero.setBitsFrom(1);
3271     break;
3272   }
3273   case ISD::SHL:
3274     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3275     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3276     Known = KnownBits::shl(Known, Known2);
3277 
3278     // Minimum shift low bits are known zero.
3279     if (const APInt *ShMinAmt =
3280             getValidMinimumShiftAmountConstant(Op, DemandedElts))
3281       Known.Zero.setLowBits(ShMinAmt->getZExtValue());
3282     break;
3283   case ISD::SRL:
3284     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3285     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3286     Known = KnownBits::lshr(Known, Known2);
3287 
3288     // Minimum shift high bits are known zero.
3289     if (const APInt *ShMinAmt =
3290             getValidMinimumShiftAmountConstant(Op, DemandedElts))
3291       Known.Zero.setHighBits(ShMinAmt->getZExtValue());
3292     break;
3293   case ISD::SRA:
3294     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3295     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3296     Known = KnownBits::ashr(Known, Known2);
3297     // TODO: Add minimum shift high known sign bits.
3298     break;
3299   case ISD::FSHL:
3300   case ISD::FSHR:
3301     if (ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(2), DemandedElts)) {
3302       unsigned Amt = C->getAPIntValue().urem(BitWidth);
3303 
3304       // For fshl, 0-shift returns the 1st arg.
3305       // For fshr, 0-shift returns the 2nd arg.
3306       if (Amt == 0) {
3307         Known = computeKnownBits(Op.getOperand(Opcode == ISD::FSHL ? 0 : 1),
3308                                  DemandedElts, Depth + 1);
3309         break;
3310       }
3311 
3312       // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
3313       // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
3314       Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3315       Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3316       if (Opcode == ISD::FSHL) {
3317         Known.One <<= Amt;
3318         Known.Zero <<= Amt;
3319         Known2.One.lshrInPlace(BitWidth - Amt);
3320         Known2.Zero.lshrInPlace(BitWidth - Amt);
3321       } else {
3322         Known.One <<= BitWidth - Amt;
3323         Known.Zero <<= BitWidth - Amt;
3324         Known2.One.lshrInPlace(Amt);
3325         Known2.Zero.lshrInPlace(Amt);
3326       }
3327       Known.One |= Known2.One;
3328       Known.Zero |= Known2.Zero;
3329     }
3330     break;
3331   case ISD::SIGN_EXTEND_INREG: {
3332     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3333     EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3334     Known = Known.sextInReg(EVT.getScalarSizeInBits());
3335     break;
3336   }
3337   case ISD::CTTZ:
3338   case ISD::CTTZ_ZERO_UNDEF: {
3339     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3340     // If we have a known 1, its position is our upper bound.
3341     unsigned PossibleTZ = Known2.countMaxTrailingZeros();
3342     unsigned LowBits = Log2_32(PossibleTZ) + 1;
3343     Known.Zero.setBitsFrom(LowBits);
3344     break;
3345   }
3346   case ISD::CTLZ:
3347   case ISD::CTLZ_ZERO_UNDEF: {
3348     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3349     // If we have a known 1, its position is our upper bound.
3350     unsigned PossibleLZ = Known2.countMaxLeadingZeros();
3351     unsigned LowBits = Log2_32(PossibleLZ) + 1;
3352     Known.Zero.setBitsFrom(LowBits);
3353     break;
3354   }
3355   case ISD::CTPOP: {
3356     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3357     // If we know some of the bits are zero, they can't be one.
3358     unsigned PossibleOnes = Known2.countMaxPopulation();
3359     Known.Zero.setBitsFrom(Log2_32(PossibleOnes) + 1);
3360     break;
3361   }
3362   case ISD::PARITY: {
3363     // Parity returns 0 everywhere but the LSB.
3364     Known.Zero.setBitsFrom(1);
3365     break;
3366   }
3367   case ISD::LOAD: {
3368     LoadSDNode *LD = cast<LoadSDNode>(Op);
3369     const Constant *Cst = TLI->getTargetConstantFromLoad(LD);
3370     if (ISD::isNON_EXTLoad(LD) && Cst) {
3371       // Determine any common known bits from the loaded constant pool value.
3372       Type *CstTy = Cst->getType();
3373       if ((NumElts * BitWidth) == CstTy->getPrimitiveSizeInBits()) {
3374         // If its a vector splat, then we can (quickly) reuse the scalar path.
3375         // NOTE: We assume all elements match and none are UNDEF.
3376         if (CstTy->isVectorTy()) {
3377           if (const Constant *Splat = Cst->getSplatValue()) {
3378             Cst = Splat;
3379             CstTy = Cst->getType();
3380           }
3381         }
3382         // TODO - do we need to handle different bitwidths?
3383         if (CstTy->isVectorTy() && BitWidth == CstTy->getScalarSizeInBits()) {
3384           // Iterate across all vector elements finding common known bits.
3385           Known.One.setAllBits();
3386           Known.Zero.setAllBits();
3387           for (unsigned i = 0; i != NumElts; ++i) {
3388             if (!DemandedElts[i])
3389               continue;
3390             if (Constant *Elt = Cst->getAggregateElement(i)) {
3391               if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
3392                 const APInt &Value = CInt->getValue();
3393                 Known.One &= Value;
3394                 Known.Zero &= ~Value;
3395                 continue;
3396               }
3397               if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
3398                 APInt Value = CFP->getValueAPF().bitcastToAPInt();
3399                 Known.One &= Value;
3400                 Known.Zero &= ~Value;
3401                 continue;
3402               }
3403             }
3404             Known.One.clearAllBits();
3405             Known.Zero.clearAllBits();
3406             break;
3407           }
3408         } else if (BitWidth == CstTy->getPrimitiveSizeInBits()) {
3409           if (auto *CInt = dyn_cast<ConstantInt>(Cst)) {
3410             Known = KnownBits::makeConstant(CInt->getValue());
3411           } else if (auto *CFP = dyn_cast<ConstantFP>(Cst)) {
3412             Known =
3413                 KnownBits::makeConstant(CFP->getValueAPF().bitcastToAPInt());
3414           }
3415         }
3416       }
3417     } else if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) {
3418       // If this is a ZEXTLoad and we are looking at the loaded value.
3419       EVT VT = LD->getMemoryVT();
3420       unsigned MemBits = VT.getScalarSizeInBits();
3421       Known.Zero.setBitsFrom(MemBits);
3422     } else if (const MDNode *Ranges = LD->getRanges()) {
3423       if (LD->getExtensionType() == ISD::NON_EXTLOAD)
3424         computeKnownBitsFromRangeMetadata(*Ranges, Known);
3425     }
3426     break;
3427   }
3428   case ISD::ZERO_EXTEND_VECTOR_INREG: {
3429     EVT InVT = Op.getOperand(0).getValueType();
3430     APInt InDemandedElts = DemandedElts.zext(InVT.getVectorNumElements());
3431     Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3432     Known = Known.zext(BitWidth);
3433     break;
3434   }
3435   case ISD::ZERO_EXTEND: {
3436     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3437     Known = Known.zext(BitWidth);
3438     break;
3439   }
3440   case ISD::SIGN_EXTEND_VECTOR_INREG: {
3441     EVT InVT = Op.getOperand(0).getValueType();
3442     APInt InDemandedElts = DemandedElts.zext(InVT.getVectorNumElements());
3443     Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3444     // If the sign bit is known to be zero or one, then sext will extend
3445     // it to the top bits, else it will just zext.
3446     Known = Known.sext(BitWidth);
3447     break;
3448   }
3449   case ISD::SIGN_EXTEND: {
3450     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3451     // If the sign bit is known to be zero or one, then sext will extend
3452     // it to the top bits, else it will just zext.
3453     Known = Known.sext(BitWidth);
3454     break;
3455   }
3456   case ISD::ANY_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     Known = Known.anyext(BitWidth);
3461     break;
3462   }
3463   case ISD::ANY_EXTEND: {
3464     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3465     Known = Known.anyext(BitWidth);
3466     break;
3467   }
3468   case ISD::TRUNCATE: {
3469     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3470     Known = Known.trunc(BitWidth);
3471     break;
3472   }
3473   case ISD::AssertZext: {
3474     EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3475     APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits());
3476     Known = computeKnownBits(Op.getOperand(0), Depth+1);
3477     Known.Zero |= (~InMask);
3478     Known.One  &= (~Known.Zero);
3479     break;
3480   }
3481   case ISD::AssertAlign: {
3482     unsigned LogOfAlign = Log2(cast<AssertAlignSDNode>(Op)->getAlign());
3483     assert(LogOfAlign != 0);
3484 
3485     // TODO: Should use maximum with source
3486     // If a node is guaranteed to be aligned, set low zero bits accordingly as
3487     // well as clearing one bits.
3488     Known.Zero.setLowBits(LogOfAlign);
3489     Known.One.clearLowBits(LogOfAlign);
3490     break;
3491   }
3492   case ISD::FGETSIGN:
3493     // All bits are zero except the low bit.
3494     Known.Zero.setBitsFrom(1);
3495     break;
3496   case ISD::USUBO:
3497   case ISD::SSUBO:
3498     if (Op.getResNo() == 1) {
3499       // If we know the result of a setcc has the top bits zero, use this info.
3500       if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
3501               TargetLowering::ZeroOrOneBooleanContent &&
3502           BitWidth > 1)
3503         Known.Zero.setBitsFrom(1);
3504       break;
3505     }
3506     LLVM_FALLTHROUGH;
3507   case ISD::SUB:
3508   case ISD::SUBC: {
3509     assert(Op.getResNo() == 0 &&
3510            "We only compute knownbits for the difference here.");
3511 
3512     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3513     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3514     Known = KnownBits::computeForAddSub(/* Add */ false, /* NSW */ false,
3515                                         Known, Known2);
3516     break;
3517   }
3518   case ISD::UADDO:
3519   case ISD::SADDO:
3520   case ISD::ADDCARRY:
3521     if (Op.getResNo() == 1) {
3522       // If we know the result of a setcc has the top bits zero, use this info.
3523       if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
3524               TargetLowering::ZeroOrOneBooleanContent &&
3525           BitWidth > 1)
3526         Known.Zero.setBitsFrom(1);
3527       break;
3528     }
3529     LLVM_FALLTHROUGH;
3530   case ISD::ADD:
3531   case ISD::ADDC:
3532   case ISD::ADDE: {
3533     assert(Op.getResNo() == 0 && "We only compute knownbits for the sum here.");
3534 
3535     // With ADDE and ADDCARRY, a carry bit may be added in.
3536     KnownBits Carry(1);
3537     if (Opcode == ISD::ADDE)
3538       // Can't track carry from glue, set carry to unknown.
3539       Carry.resetAll();
3540     else if (Opcode == ISD::ADDCARRY)
3541       // TODO: Compute known bits for the carry operand. Not sure if it is worth
3542       // the trouble (how often will we find a known carry bit). And I haven't
3543       // tested this very much yet, but something like this might work:
3544       //   Carry = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1);
3545       //   Carry = Carry.zextOrTrunc(1, false);
3546       Carry.resetAll();
3547     else
3548       Carry.setAllZero();
3549 
3550     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3551     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3552     Known = KnownBits::computeForAddCarry(Known, Known2, Carry);
3553     break;
3554   }
3555   case ISD::SREM: {
3556     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3557     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3558     Known = KnownBits::srem(Known, Known2);
3559     break;
3560   }
3561   case ISD::UREM: {
3562     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3563     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3564     Known = KnownBits::urem(Known, Known2);
3565     break;
3566   }
3567   case ISD::EXTRACT_ELEMENT: {
3568     Known = computeKnownBits(Op.getOperand(0), Depth+1);
3569     const unsigned Index = Op.getConstantOperandVal(1);
3570     const unsigned EltBitWidth = Op.getValueSizeInBits();
3571 
3572     // Remove low part of known bits mask
3573     Known.Zero = Known.Zero.getHiBits(Known.getBitWidth() - Index * EltBitWidth);
3574     Known.One = Known.One.getHiBits(Known.getBitWidth() - Index * EltBitWidth);
3575 
3576     // Remove high part of known bit mask
3577     Known = Known.trunc(EltBitWidth);
3578     break;
3579   }
3580   case ISD::EXTRACT_VECTOR_ELT: {
3581     SDValue InVec = Op.getOperand(0);
3582     SDValue EltNo = Op.getOperand(1);
3583     EVT VecVT = InVec.getValueType();
3584     // computeKnownBits not yet implemented for scalable vectors.
3585     if (VecVT.isScalableVector())
3586       break;
3587     const unsigned EltBitWidth = VecVT.getScalarSizeInBits();
3588     const unsigned NumSrcElts = VecVT.getVectorNumElements();
3589 
3590     // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know
3591     // anything about the extended bits.
3592     if (BitWidth > EltBitWidth)
3593       Known = Known.trunc(EltBitWidth);
3594 
3595     // If we know the element index, just demand that vector element, else for
3596     // an unknown element index, ignore DemandedElts and demand them all.
3597     APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
3598     auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
3599     if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
3600       DemandedSrcElts =
3601           APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
3602 
3603     Known = computeKnownBits(InVec, DemandedSrcElts, Depth + 1);
3604     if (BitWidth > EltBitWidth)
3605       Known = Known.anyext(BitWidth);
3606     break;
3607   }
3608   case ISD::INSERT_VECTOR_ELT: {
3609     // If we know the element index, split the demand between the
3610     // source vector and the inserted element, otherwise assume we need
3611     // the original demanded vector elements and the value.
3612     SDValue InVec = Op.getOperand(0);
3613     SDValue InVal = Op.getOperand(1);
3614     SDValue EltNo = Op.getOperand(2);
3615     bool DemandedVal = true;
3616     APInt DemandedVecElts = DemandedElts;
3617     auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
3618     if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
3619       unsigned EltIdx = CEltNo->getZExtValue();
3620       DemandedVal = !!DemandedElts[EltIdx];
3621       DemandedVecElts.clearBit(EltIdx);
3622     }
3623     Known.One.setAllBits();
3624     Known.Zero.setAllBits();
3625     if (DemandedVal) {
3626       Known2 = computeKnownBits(InVal, Depth + 1);
3627       Known = KnownBits::commonBits(Known, Known2.zextOrTrunc(BitWidth));
3628     }
3629     if (!!DemandedVecElts) {
3630       Known2 = computeKnownBits(InVec, DemandedVecElts, Depth + 1);
3631       Known = KnownBits::commonBits(Known, Known2);
3632     }
3633     break;
3634   }
3635   case ISD::BITREVERSE: {
3636     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3637     Known = Known2.reverseBits();
3638     break;
3639   }
3640   case ISD::BSWAP: {
3641     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3642     Known = Known2.byteSwap();
3643     break;
3644   }
3645   case ISD::ABS: {
3646     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3647     Known = Known2.abs();
3648     break;
3649   }
3650   case ISD::USUBSAT: {
3651     // The result of usubsat will never be larger than the LHS.
3652     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3653     Known.Zero.setHighBits(Known2.countMinLeadingZeros());
3654     break;
3655   }
3656   case ISD::UMIN: {
3657     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3658     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3659     Known = KnownBits::umin(Known, Known2);
3660     break;
3661   }
3662   case ISD::UMAX: {
3663     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3664     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3665     Known = KnownBits::umax(Known, Known2);
3666     break;
3667   }
3668   case ISD::SMIN:
3669   case ISD::SMAX: {
3670     // If we have a clamp pattern, we know that the number of sign bits will be
3671     // the minimum of the clamp min/max range.
3672     bool IsMax = (Opcode == ISD::SMAX);
3673     ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
3674     if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
3675       if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
3676         CstHigh =
3677             isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
3678     if (CstLow && CstHigh) {
3679       if (!IsMax)
3680         std::swap(CstLow, CstHigh);
3681 
3682       const APInt &ValueLow = CstLow->getAPIntValue();
3683       const APInt &ValueHigh = CstHigh->getAPIntValue();
3684       if (ValueLow.sle(ValueHigh)) {
3685         unsigned LowSignBits = ValueLow.getNumSignBits();
3686         unsigned HighSignBits = ValueHigh.getNumSignBits();
3687         unsigned MinSignBits = std::min(LowSignBits, HighSignBits);
3688         if (ValueLow.isNegative() && ValueHigh.isNegative()) {
3689           Known.One.setHighBits(MinSignBits);
3690           break;
3691         }
3692         if (ValueLow.isNonNegative() && ValueHigh.isNonNegative()) {
3693           Known.Zero.setHighBits(MinSignBits);
3694           break;
3695         }
3696       }
3697     }
3698 
3699     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3700     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3701     if (IsMax)
3702       Known = KnownBits::smax(Known, Known2);
3703     else
3704       Known = KnownBits::smin(Known, Known2);
3705 
3706     // For SMAX, if CstLow is non-negative we know the result will be
3707     // non-negative and thus all sign bits are 0.
3708     // TODO: There's an equivalent of this for smin with negative constant for
3709     // known ones.
3710     if (IsMax && CstLow) {
3711       const APInt &ValueLow = CstLow->getAPIntValue();
3712       if (ValueLow.isNonNegative()) {
3713         unsigned SignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
3714         Known.Zero.setHighBits(std::min(SignBits, ValueLow.getNumSignBits()));
3715       }
3716     }
3717 
3718     break;
3719   }
3720   case ISD::FP_TO_UINT_SAT: {
3721     // FP_TO_UINT_SAT produces an unsigned value that fits in the saturating VT.
3722     EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3723     Known.Zero |= APInt::getBitsSetFrom(BitWidth, VT.getScalarSizeInBits());
3724     break;
3725   }
3726   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
3727     if (Op.getResNo() == 1) {
3728       // The boolean result conforms to getBooleanContents.
3729       // If we know the result of a setcc has the top bits zero, use this info.
3730       // We know that we have an integer-based boolean since these operations
3731       // are only available for integer.
3732       if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
3733               TargetLowering::ZeroOrOneBooleanContent &&
3734           BitWidth > 1)
3735         Known.Zero.setBitsFrom(1);
3736       break;
3737     }
3738     LLVM_FALLTHROUGH;
3739   case ISD::ATOMIC_CMP_SWAP:
3740   case ISD::ATOMIC_SWAP:
3741   case ISD::ATOMIC_LOAD_ADD:
3742   case ISD::ATOMIC_LOAD_SUB:
3743   case ISD::ATOMIC_LOAD_AND:
3744   case ISD::ATOMIC_LOAD_CLR:
3745   case ISD::ATOMIC_LOAD_OR:
3746   case ISD::ATOMIC_LOAD_XOR:
3747   case ISD::ATOMIC_LOAD_NAND:
3748   case ISD::ATOMIC_LOAD_MIN:
3749   case ISD::ATOMIC_LOAD_MAX:
3750   case ISD::ATOMIC_LOAD_UMIN:
3751   case ISD::ATOMIC_LOAD_UMAX:
3752   case ISD::ATOMIC_LOAD: {
3753     unsigned MemBits =
3754         cast<AtomicSDNode>(Op)->getMemoryVT().getScalarSizeInBits();
3755     // If we are looking at the loaded value.
3756     if (Op.getResNo() == 0) {
3757       if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND)
3758         Known.Zero.setBitsFrom(MemBits);
3759     }
3760     break;
3761   }
3762   case ISD::FrameIndex:
3763   case ISD::TargetFrameIndex:
3764     TLI->computeKnownBitsForFrameIndex(cast<FrameIndexSDNode>(Op)->getIndex(),
3765                                        Known, getMachineFunction());
3766     break;
3767 
3768   default:
3769     if (Opcode < ISD::BUILTIN_OP_END)
3770       break;
3771     LLVM_FALLTHROUGH;
3772   case ISD::INTRINSIC_WO_CHAIN:
3773   case ISD::INTRINSIC_W_CHAIN:
3774   case ISD::INTRINSIC_VOID:
3775     // Allow the target to implement this method for its nodes.
3776     TLI->computeKnownBitsForTargetNode(Op, Known, DemandedElts, *this, Depth);
3777     break;
3778   }
3779 
3780   assert(!Known.hasConflict() && "Bits known to be one AND zero?");
3781   return Known;
3782 }
3783 
3784 SelectionDAG::OverflowKind SelectionDAG::computeOverflowKind(SDValue N0,
3785                                                              SDValue N1) const {
3786   // X + 0 never overflow
3787   if (isNullConstant(N1))
3788     return OFK_Never;
3789 
3790   KnownBits N1Known = computeKnownBits(N1);
3791   if (N1Known.Zero.getBoolValue()) {
3792     KnownBits N0Known = computeKnownBits(N0);
3793 
3794     bool overflow;
3795     (void)N0Known.getMaxValue().uadd_ov(N1Known.getMaxValue(), overflow);
3796     if (!overflow)
3797       return OFK_Never;
3798   }
3799 
3800   // mulhi + 1 never overflow
3801   if (N0.getOpcode() == ISD::UMUL_LOHI && N0.getResNo() == 1 &&
3802       (N1Known.getMaxValue() & 0x01) == N1Known.getMaxValue())
3803     return OFK_Never;
3804 
3805   if (N1.getOpcode() == ISD::UMUL_LOHI && N1.getResNo() == 1) {
3806     KnownBits N0Known = computeKnownBits(N0);
3807 
3808     if ((N0Known.getMaxValue() & 0x01) == N0Known.getMaxValue())
3809       return OFK_Never;
3810   }
3811 
3812   return OFK_Sometime;
3813 }
3814 
3815 bool SelectionDAG::isKnownToBeAPowerOfTwo(SDValue Val) const {
3816   EVT OpVT = Val.getValueType();
3817   unsigned BitWidth = OpVT.getScalarSizeInBits();
3818 
3819   // Is the constant a known power of 2?
3820   if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Val))
3821     return Const->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
3822 
3823   // A left-shift of a constant one will have exactly one bit set because
3824   // shifting the bit off the end is undefined.
3825   if (Val.getOpcode() == ISD::SHL) {
3826     auto *C = isConstOrConstSplat(Val.getOperand(0));
3827     if (C && C->getAPIntValue() == 1)
3828       return true;
3829   }
3830 
3831   // Similarly, a logical right-shift of a constant sign-bit will have exactly
3832   // one bit set.
3833   if (Val.getOpcode() == ISD::SRL) {
3834     auto *C = isConstOrConstSplat(Val.getOperand(0));
3835     if (C && C->getAPIntValue().isSignMask())
3836       return true;
3837   }
3838 
3839   // Are all operands of a build vector constant powers of two?
3840   if (Val.getOpcode() == ISD::BUILD_VECTOR)
3841     if (llvm::all_of(Val->ops(), [BitWidth](SDValue E) {
3842           if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(E))
3843             return C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
3844           return false;
3845         }))
3846       return true;
3847 
3848   // Is the operand of a splat vector a constant power of two?
3849   if (Val.getOpcode() == ISD::SPLAT_VECTOR)
3850     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val->getOperand(0)))
3851       if (C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2())
3852         return true;
3853 
3854   // More could be done here, though the above checks are enough
3855   // to handle some common cases.
3856 
3857   // Fall back to computeKnownBits to catch other known cases.
3858   KnownBits Known = computeKnownBits(Val);
3859   return (Known.countMaxPopulation() == 1) && (Known.countMinPopulation() == 1);
3860 }
3861 
3862 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const {
3863   EVT VT = Op.getValueType();
3864 
3865   // TODO: Assume we don't know anything for now.
3866   if (VT.isScalableVector())
3867     return 1;
3868 
3869   APInt DemandedElts = VT.isVector()
3870                            ? APInt::getAllOnes(VT.getVectorNumElements())
3871                            : APInt(1, 1);
3872   return ComputeNumSignBits(Op, DemandedElts, Depth);
3873 }
3874 
3875 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, const APInt &DemandedElts,
3876                                           unsigned Depth) const {
3877   EVT VT = Op.getValueType();
3878   assert((VT.isInteger() || VT.isFloatingPoint()) && "Invalid VT!");
3879   unsigned VTBits = VT.getScalarSizeInBits();
3880   unsigned NumElts = DemandedElts.getBitWidth();
3881   unsigned Tmp, Tmp2;
3882   unsigned FirstAnswer = 1;
3883 
3884   if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
3885     const APInt &Val = C->getAPIntValue();
3886     return Val.getNumSignBits();
3887   }
3888 
3889   if (Depth >= MaxRecursionDepth)
3890     return 1;  // Limit search depth.
3891 
3892   if (!DemandedElts || VT.isScalableVector())
3893     return 1;  // No demanded elts, better to assume we don't know anything.
3894 
3895   unsigned Opcode = Op.getOpcode();
3896   switch (Opcode) {
3897   default: break;
3898   case ISD::AssertSext:
3899     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
3900     return VTBits-Tmp+1;
3901   case ISD::AssertZext:
3902     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
3903     return VTBits-Tmp;
3904 
3905   case ISD::BUILD_VECTOR:
3906     Tmp = VTBits;
3907     for (unsigned i = 0, e = Op.getNumOperands(); (i < e) && (Tmp > 1); ++i) {
3908       if (!DemandedElts[i])
3909         continue;
3910 
3911       SDValue SrcOp = Op.getOperand(i);
3912       Tmp2 = ComputeNumSignBits(SrcOp, Depth + 1);
3913 
3914       // BUILD_VECTOR can implicitly truncate sources, we must handle this.
3915       if (SrcOp.getValueSizeInBits() != VTBits) {
3916         assert(SrcOp.getValueSizeInBits() > VTBits &&
3917                "Expected BUILD_VECTOR implicit truncation");
3918         unsigned ExtraBits = SrcOp.getValueSizeInBits() - VTBits;
3919         Tmp2 = (Tmp2 > ExtraBits ? Tmp2 - ExtraBits : 1);
3920       }
3921       Tmp = std::min(Tmp, Tmp2);
3922     }
3923     return Tmp;
3924 
3925   case ISD::VECTOR_SHUFFLE: {
3926     // Collect the minimum number of sign bits that are shared by every vector
3927     // element referenced by the shuffle.
3928     APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
3929     const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
3930     assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
3931     for (unsigned i = 0; i != NumElts; ++i) {
3932       int M = SVN->getMaskElt(i);
3933       if (!DemandedElts[i])
3934         continue;
3935       // For UNDEF elements, we don't know anything about the common state of
3936       // the shuffle result.
3937       if (M < 0)
3938         return 1;
3939       if ((unsigned)M < NumElts)
3940         DemandedLHS.setBit((unsigned)M % NumElts);
3941       else
3942         DemandedRHS.setBit((unsigned)M % NumElts);
3943     }
3944     Tmp = std::numeric_limits<unsigned>::max();
3945     if (!!DemandedLHS)
3946       Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedLHS, Depth + 1);
3947     if (!!DemandedRHS) {
3948       Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedRHS, Depth + 1);
3949       Tmp = std::min(Tmp, Tmp2);
3950     }
3951     // If we don't know anything, early out and try computeKnownBits fall-back.
3952     if (Tmp == 1)
3953       break;
3954     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
3955     return Tmp;
3956   }
3957 
3958   case ISD::BITCAST: {
3959     SDValue N0 = Op.getOperand(0);
3960     EVT SrcVT = N0.getValueType();
3961     unsigned SrcBits = SrcVT.getScalarSizeInBits();
3962 
3963     // Ignore bitcasts from unsupported types..
3964     if (!(SrcVT.isInteger() || SrcVT.isFloatingPoint()))
3965       break;
3966 
3967     // Fast handling of 'identity' bitcasts.
3968     if (VTBits == SrcBits)
3969       return ComputeNumSignBits(N0, DemandedElts, Depth + 1);
3970 
3971     bool IsLE = getDataLayout().isLittleEndian();
3972 
3973     // Bitcast 'large element' scalar/vector to 'small element' vector.
3974     if ((SrcBits % VTBits) == 0) {
3975       assert(VT.isVector() && "Expected bitcast to vector");
3976 
3977       unsigned Scale = SrcBits / VTBits;
3978       APInt SrcDemandedElts =
3979           APIntOps::ScaleBitMask(DemandedElts, NumElts / Scale);
3980 
3981       // Fast case - sign splat can be simply split across the small elements.
3982       Tmp = ComputeNumSignBits(N0, SrcDemandedElts, Depth + 1);
3983       if (Tmp == SrcBits)
3984         return VTBits;
3985 
3986       // Slow case - determine how far the sign extends into each sub-element.
3987       Tmp2 = VTBits;
3988       for (unsigned i = 0; i != NumElts; ++i)
3989         if (DemandedElts[i]) {
3990           unsigned SubOffset = i % Scale;
3991           SubOffset = (IsLE ? ((Scale - 1) - SubOffset) : SubOffset);
3992           SubOffset = SubOffset * VTBits;
3993           if (Tmp <= SubOffset)
3994             return 1;
3995           Tmp2 = std::min(Tmp2, Tmp - SubOffset);
3996         }
3997       return Tmp2;
3998     }
3999     break;
4000   }
4001 
4002   case ISD::FP_TO_SINT_SAT:
4003     // FP_TO_SINT_SAT produces a signed value that fits in the saturating VT.
4004     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
4005     return VTBits - Tmp + 1;
4006   case ISD::SIGN_EXTEND:
4007     Tmp = VTBits - Op.getOperand(0).getScalarValueSizeInBits();
4008     return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1) + Tmp;
4009   case ISD::SIGN_EXTEND_INREG:
4010     // Max of the input and what this extends.
4011     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
4012     Tmp = VTBits-Tmp+1;
4013     Tmp2 = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
4014     return std::max(Tmp, Tmp2);
4015   case ISD::SIGN_EXTEND_VECTOR_INREG: {
4016     SDValue Src = Op.getOperand(0);
4017     EVT SrcVT = Src.getValueType();
4018     APInt DemandedSrcElts = DemandedElts.zext(SrcVT.getVectorNumElements());
4019     Tmp = VTBits - SrcVT.getScalarSizeInBits();
4020     return ComputeNumSignBits(Src, DemandedSrcElts, Depth+1) + Tmp;
4021   }
4022   case ISD::SRA:
4023     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4024     // SRA X, C -> adds C sign bits.
4025     if (const APInt *ShAmt =
4026             getValidMinimumShiftAmountConstant(Op, DemandedElts))
4027       Tmp = std::min<uint64_t>(Tmp + ShAmt->getZExtValue(), VTBits);
4028     return Tmp;
4029   case ISD::SHL:
4030     if (const APInt *ShAmt =
4031             getValidMaximumShiftAmountConstant(Op, DemandedElts)) {
4032       // shl destroys sign bits, ensure it doesn't shift out all sign bits.
4033       Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4034       if (ShAmt->ult(Tmp))
4035         return Tmp - ShAmt->getZExtValue();
4036     }
4037     break;
4038   case ISD::AND:
4039   case ISD::OR:
4040   case ISD::XOR:    // NOT is handled here.
4041     // Logical binary ops preserve the number of sign bits at the worst.
4042     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
4043     if (Tmp != 1) {
4044       Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
4045       FirstAnswer = std::min(Tmp, Tmp2);
4046       // We computed what we know about the sign bits as our first
4047       // answer. Now proceed to the generic code that uses
4048       // computeKnownBits, and pick whichever answer is better.
4049     }
4050     break;
4051 
4052   case ISD::SELECT:
4053   case ISD::VSELECT:
4054     Tmp = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
4055     if (Tmp == 1) return 1;  // Early out.
4056     Tmp2 = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
4057     return std::min(Tmp, Tmp2);
4058   case ISD::SELECT_CC:
4059     Tmp = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
4060     if (Tmp == 1) return 1;  // Early out.
4061     Tmp2 = ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth+1);
4062     return std::min(Tmp, Tmp2);
4063 
4064   case ISD::SMIN:
4065   case ISD::SMAX: {
4066     // If we have a clamp pattern, we know that the number of sign bits will be
4067     // the minimum of the clamp min/max range.
4068     bool IsMax = (Opcode == ISD::SMAX);
4069     ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
4070     if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
4071       if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
4072         CstHigh =
4073             isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
4074     if (CstLow && CstHigh) {
4075       if (!IsMax)
4076         std::swap(CstLow, CstHigh);
4077       if (CstLow->getAPIntValue().sle(CstHigh->getAPIntValue())) {
4078         Tmp = CstLow->getAPIntValue().getNumSignBits();
4079         Tmp2 = CstHigh->getAPIntValue().getNumSignBits();
4080         return std::min(Tmp, Tmp2);
4081       }
4082     }
4083 
4084     // Fallback - just get the minimum number of sign bits of the operands.
4085     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4086     if (Tmp == 1)
4087       return 1;  // Early out.
4088     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
4089     return std::min(Tmp, Tmp2);
4090   }
4091   case ISD::UMIN:
4092   case ISD::UMAX:
4093     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4094     if (Tmp == 1)
4095       return 1;  // Early out.
4096     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
4097     return std::min(Tmp, Tmp2);
4098   case ISD::SADDO:
4099   case ISD::UADDO:
4100   case ISD::SSUBO:
4101   case ISD::USUBO:
4102   case ISD::SMULO:
4103   case ISD::UMULO:
4104     if (Op.getResNo() != 1)
4105       break;
4106     // The boolean result conforms to getBooleanContents.  Fall through.
4107     // If setcc returns 0/-1, all bits are sign bits.
4108     // We know that we have an integer-based boolean since these operations
4109     // are only available for integer.
4110     if (TLI->getBooleanContents(VT.isVector(), false) ==
4111         TargetLowering::ZeroOrNegativeOneBooleanContent)
4112       return VTBits;
4113     break;
4114   case ISD::SETCC:
4115   case ISD::STRICT_FSETCC:
4116   case ISD::STRICT_FSETCCS: {
4117     unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
4118     // If setcc returns 0/-1, all bits are sign bits.
4119     if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
4120         TargetLowering::ZeroOrNegativeOneBooleanContent)
4121       return VTBits;
4122     break;
4123   }
4124   case ISD::ROTL:
4125   case ISD::ROTR:
4126     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4127 
4128     // If we're rotating an 0/-1 value, then it stays an 0/-1 value.
4129     if (Tmp == VTBits)
4130       return VTBits;
4131 
4132     if (ConstantSDNode *C =
4133             isConstOrConstSplat(Op.getOperand(1), DemandedElts)) {
4134       unsigned RotAmt = C->getAPIntValue().urem(VTBits);
4135 
4136       // Handle rotate right by N like a rotate left by 32-N.
4137       if (Opcode == ISD::ROTR)
4138         RotAmt = (VTBits - RotAmt) % VTBits;
4139 
4140       // If we aren't rotating out all of the known-in sign bits, return the
4141       // number that are left.  This handles rotl(sext(x), 1) for example.
4142       if (Tmp > (RotAmt + 1)) return (Tmp - RotAmt);
4143     }
4144     break;
4145   case ISD::ADD:
4146   case ISD::ADDC:
4147     // Add can have at most one carry bit.  Thus we know that the output
4148     // is, at worst, one more bit than the inputs.
4149     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4150     if (Tmp == 1) return 1; // Early out.
4151 
4152     // Special case decrementing a value (ADD X, -1):
4153     if (ConstantSDNode *CRHS =
4154             isConstOrConstSplat(Op.getOperand(1), DemandedElts))
4155       if (CRHS->isAllOnes()) {
4156         KnownBits Known =
4157             computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
4158 
4159         // If the input is known to be 0 or 1, the output is 0/-1, which is all
4160         // sign bits set.
4161         if ((Known.Zero | 1).isAllOnes())
4162           return VTBits;
4163 
4164         // If we are subtracting one from a positive number, there is no carry
4165         // out of the result.
4166         if (Known.isNonNegative())
4167           return Tmp;
4168       }
4169 
4170     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
4171     if (Tmp2 == 1) return 1; // Early out.
4172     return std::min(Tmp, Tmp2) - 1;
4173   case ISD::SUB:
4174     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
4175     if (Tmp2 == 1) return 1; // Early out.
4176 
4177     // Handle NEG.
4178     if (ConstantSDNode *CLHS =
4179             isConstOrConstSplat(Op.getOperand(0), DemandedElts))
4180       if (CLHS->isZero()) {
4181         KnownBits Known =
4182             computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
4183         // If the input is known to be 0 or 1, the output is 0/-1, which is all
4184         // sign bits set.
4185         if ((Known.Zero | 1).isAllOnes())
4186           return VTBits;
4187 
4188         // If the input is known to be positive (the sign bit is known clear),
4189         // the output of the NEG has the same number of sign bits as the input.
4190         if (Known.isNonNegative())
4191           return Tmp2;
4192 
4193         // Otherwise, we treat this like a SUB.
4194       }
4195 
4196     // Sub can have at most one carry bit.  Thus we know that the output
4197     // is, at worst, one more bit than the inputs.
4198     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4199     if (Tmp == 1) return 1; // Early out.
4200     return std::min(Tmp, Tmp2) - 1;
4201   case ISD::MUL: {
4202     // The output of the Mul can be at most twice the valid bits in the inputs.
4203     unsigned SignBitsOp0 = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
4204     if (SignBitsOp0 == 1)
4205       break;
4206     unsigned SignBitsOp1 = ComputeNumSignBits(Op.getOperand(1), Depth + 1);
4207     if (SignBitsOp1 == 1)
4208       break;
4209     unsigned OutValidBits =
4210         (VTBits - SignBitsOp0 + 1) + (VTBits - SignBitsOp1 + 1);
4211     return OutValidBits > VTBits ? 1 : VTBits - OutValidBits + 1;
4212   }
4213   case ISD::SREM:
4214     // The sign bit is the LHS's sign bit, except when the result of the
4215     // remainder is zero. The magnitude of the result should be less than or
4216     // equal to the magnitude of the LHS. Therefore, the result should have
4217     // at least as many sign bits as the left hand side.
4218     return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
4219   case ISD::TRUNCATE: {
4220     // Check if the sign bits of source go down as far as the truncated value.
4221     unsigned NumSrcBits = Op.getOperand(0).getScalarValueSizeInBits();
4222     unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
4223     if (NumSrcSignBits > (NumSrcBits - VTBits))
4224       return NumSrcSignBits - (NumSrcBits - VTBits);
4225     break;
4226   }
4227   case ISD::EXTRACT_ELEMENT: {
4228     const int KnownSign = ComputeNumSignBits(Op.getOperand(0), Depth+1);
4229     const int BitWidth = Op.getValueSizeInBits();
4230     const int Items = Op.getOperand(0).getValueSizeInBits() / BitWidth;
4231 
4232     // Get reverse index (starting from 1), Op1 value indexes elements from
4233     // little end. Sign starts at big end.
4234     const int rIndex = Items - 1 - Op.getConstantOperandVal(1);
4235 
4236     // If the sign portion ends in our element the subtraction gives correct
4237     // result. Otherwise it gives either negative or > bitwidth result
4238     return std::max(std::min(KnownSign - rIndex * BitWidth, BitWidth), 0);
4239   }
4240   case ISD::INSERT_VECTOR_ELT: {
4241     // If we know the element index, split the demand between the
4242     // source vector and the inserted element, otherwise assume we need
4243     // the original demanded vector elements and the value.
4244     SDValue InVec = Op.getOperand(0);
4245     SDValue InVal = Op.getOperand(1);
4246     SDValue EltNo = Op.getOperand(2);
4247     bool DemandedVal = true;
4248     APInt DemandedVecElts = DemandedElts;
4249     auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
4250     if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
4251       unsigned EltIdx = CEltNo->getZExtValue();
4252       DemandedVal = !!DemandedElts[EltIdx];
4253       DemandedVecElts.clearBit(EltIdx);
4254     }
4255     Tmp = std::numeric_limits<unsigned>::max();
4256     if (DemandedVal) {
4257       // TODO - handle implicit truncation of inserted elements.
4258       if (InVal.getScalarValueSizeInBits() != VTBits)
4259         break;
4260       Tmp2 = ComputeNumSignBits(InVal, Depth + 1);
4261       Tmp = std::min(Tmp, Tmp2);
4262     }
4263     if (!!DemandedVecElts) {
4264       Tmp2 = ComputeNumSignBits(InVec, DemandedVecElts, Depth + 1);
4265       Tmp = std::min(Tmp, Tmp2);
4266     }
4267     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
4268     return Tmp;
4269   }
4270   case ISD::EXTRACT_VECTOR_ELT: {
4271     SDValue InVec = Op.getOperand(0);
4272     SDValue EltNo = Op.getOperand(1);
4273     EVT VecVT = InVec.getValueType();
4274     // ComputeNumSignBits not yet implemented for scalable vectors.
4275     if (VecVT.isScalableVector())
4276       break;
4277     const unsigned BitWidth = Op.getValueSizeInBits();
4278     const unsigned EltBitWidth = Op.getOperand(0).getScalarValueSizeInBits();
4279     const unsigned NumSrcElts = VecVT.getVectorNumElements();
4280 
4281     // If BitWidth > EltBitWidth the value is anyext:ed, and we do not know
4282     // anything about sign bits. But if the sizes match we can derive knowledge
4283     // about sign bits from the vector operand.
4284     if (BitWidth != EltBitWidth)
4285       break;
4286 
4287     // If we know the element index, just demand that vector element, else for
4288     // an unknown element index, ignore DemandedElts and demand them all.
4289     APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
4290     auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
4291     if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
4292       DemandedSrcElts =
4293           APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
4294 
4295     return ComputeNumSignBits(InVec, DemandedSrcElts, Depth + 1);
4296   }
4297   case ISD::EXTRACT_SUBVECTOR: {
4298     // Offset the demanded elts by the subvector index.
4299     SDValue Src = Op.getOperand(0);
4300     // Bail until we can represent demanded elements for scalable vectors.
4301     if (Src.getValueType().isScalableVector())
4302       break;
4303     uint64_t Idx = Op.getConstantOperandVal(1);
4304     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
4305     APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
4306     return ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
4307   }
4308   case ISD::CONCAT_VECTORS: {
4309     // Determine the minimum number of sign bits across all demanded
4310     // elts of the input vectors. Early out if the result is already 1.
4311     Tmp = std::numeric_limits<unsigned>::max();
4312     EVT SubVectorVT = Op.getOperand(0).getValueType();
4313     unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
4314     unsigned NumSubVectors = Op.getNumOperands();
4315     for (unsigned i = 0; (i < NumSubVectors) && (Tmp > 1); ++i) {
4316       APInt DemandedSub =
4317           DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts);
4318       if (!DemandedSub)
4319         continue;
4320       Tmp2 = ComputeNumSignBits(Op.getOperand(i), DemandedSub, Depth + 1);
4321       Tmp = std::min(Tmp, Tmp2);
4322     }
4323     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
4324     return Tmp;
4325   }
4326   case ISD::INSERT_SUBVECTOR: {
4327     // Demand any elements from the subvector and the remainder from the src its
4328     // inserted into.
4329     SDValue Src = Op.getOperand(0);
4330     SDValue Sub = Op.getOperand(1);
4331     uint64_t Idx = Op.getConstantOperandVal(2);
4332     unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
4333     APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
4334     APInt DemandedSrcElts = DemandedElts;
4335     DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx);
4336 
4337     Tmp = std::numeric_limits<unsigned>::max();
4338     if (!!DemandedSubElts) {
4339       Tmp = ComputeNumSignBits(Sub, DemandedSubElts, Depth + 1);
4340       if (Tmp == 1)
4341         return 1; // early-out
4342     }
4343     if (!!DemandedSrcElts) {
4344       Tmp2 = ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
4345       Tmp = std::min(Tmp, Tmp2);
4346     }
4347     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
4348     return Tmp;
4349   }
4350   case ISD::ATOMIC_CMP_SWAP:
4351   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
4352   case ISD::ATOMIC_SWAP:
4353   case ISD::ATOMIC_LOAD_ADD:
4354   case ISD::ATOMIC_LOAD_SUB:
4355   case ISD::ATOMIC_LOAD_AND:
4356   case ISD::ATOMIC_LOAD_CLR:
4357   case ISD::ATOMIC_LOAD_OR:
4358   case ISD::ATOMIC_LOAD_XOR:
4359   case ISD::ATOMIC_LOAD_NAND:
4360   case ISD::ATOMIC_LOAD_MIN:
4361   case ISD::ATOMIC_LOAD_MAX:
4362   case ISD::ATOMIC_LOAD_UMIN:
4363   case ISD::ATOMIC_LOAD_UMAX:
4364   case ISD::ATOMIC_LOAD: {
4365     Tmp = cast<AtomicSDNode>(Op)->getMemoryVT().getScalarSizeInBits();
4366     // If we are looking at the loaded value.
4367     if (Op.getResNo() == 0) {
4368       if (Tmp == VTBits)
4369         return 1; // early-out
4370       if (TLI->getExtendForAtomicOps() == ISD::SIGN_EXTEND)
4371         return VTBits - Tmp + 1;
4372       if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND)
4373         return VTBits - Tmp;
4374     }
4375     break;
4376   }
4377   }
4378 
4379   // If we are looking at the loaded value of the SDNode.
4380   if (Op.getResNo() == 0) {
4381     // Handle LOADX separately here. EXTLOAD case will fallthrough.
4382     if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
4383       unsigned ExtType = LD->getExtensionType();
4384       switch (ExtType) {
4385       default: break;
4386       case ISD::SEXTLOAD: // e.g. i16->i32 = '17' bits known.
4387         Tmp = LD->getMemoryVT().getScalarSizeInBits();
4388         return VTBits - Tmp + 1;
4389       case ISD::ZEXTLOAD: // e.g. i16->i32 = '16' bits known.
4390         Tmp = LD->getMemoryVT().getScalarSizeInBits();
4391         return VTBits - Tmp;
4392       case ISD::NON_EXTLOAD:
4393         if (const Constant *Cst = TLI->getTargetConstantFromLoad(LD)) {
4394           // We only need to handle vectors - computeKnownBits should handle
4395           // scalar cases.
4396           Type *CstTy = Cst->getType();
4397           if (CstTy->isVectorTy() &&
4398               (NumElts * VTBits) == CstTy->getPrimitiveSizeInBits() &&
4399               VTBits == CstTy->getScalarSizeInBits()) {
4400             Tmp = VTBits;
4401             for (unsigned i = 0; i != NumElts; ++i) {
4402               if (!DemandedElts[i])
4403                 continue;
4404               if (Constant *Elt = Cst->getAggregateElement(i)) {
4405                 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
4406                   const APInt &Value = CInt->getValue();
4407                   Tmp = std::min(Tmp, Value.getNumSignBits());
4408                   continue;
4409                 }
4410                 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
4411                   APInt Value = CFP->getValueAPF().bitcastToAPInt();
4412                   Tmp = std::min(Tmp, Value.getNumSignBits());
4413                   continue;
4414                 }
4415               }
4416               // Unknown type. Conservatively assume no bits match sign bit.
4417               return 1;
4418             }
4419             return Tmp;
4420           }
4421         }
4422         break;
4423       }
4424     }
4425   }
4426 
4427   // Allow the target to implement this method for its nodes.
4428   if (Opcode >= ISD::BUILTIN_OP_END ||
4429       Opcode == ISD::INTRINSIC_WO_CHAIN ||
4430       Opcode == ISD::INTRINSIC_W_CHAIN ||
4431       Opcode == ISD::INTRINSIC_VOID) {
4432     unsigned NumBits =
4433         TLI->ComputeNumSignBitsForTargetNode(Op, DemandedElts, *this, Depth);
4434     if (NumBits > 1)
4435       FirstAnswer = std::max(FirstAnswer, NumBits);
4436   }
4437 
4438   // Finally, if we can prove that the top bits of the result are 0's or 1's,
4439   // use this information.
4440   KnownBits Known = computeKnownBits(Op, DemandedElts, Depth);
4441   return std::max(FirstAnswer, Known.countMinSignBits());
4442 }
4443 
4444 unsigned SelectionDAG::ComputeMaxSignificantBits(SDValue Op,
4445                                                  unsigned Depth) const {
4446   unsigned SignBits = ComputeNumSignBits(Op, Depth);
4447   return Op.getScalarValueSizeInBits() - SignBits + 1;
4448 }
4449 
4450 unsigned SelectionDAG::ComputeMaxSignificantBits(SDValue Op,
4451                                                  const APInt &DemandedElts,
4452                                                  unsigned Depth) const {
4453   unsigned SignBits = ComputeNumSignBits(Op, DemandedElts, Depth);
4454   return Op.getScalarValueSizeInBits() - SignBits + 1;
4455 }
4456 
4457 bool SelectionDAG::isGuaranteedNotToBeUndefOrPoison(SDValue Op, bool PoisonOnly,
4458                                                     unsigned Depth) const {
4459   // Early out for FREEZE.
4460   if (Op.getOpcode() == ISD::FREEZE)
4461     return true;
4462 
4463   // TODO: Assume we don't know anything for now.
4464   EVT VT = Op.getValueType();
4465   if (VT.isScalableVector())
4466     return false;
4467 
4468   APInt DemandedElts = VT.isVector()
4469                            ? APInt::getAllOnes(VT.getVectorNumElements())
4470                            : APInt(1, 1);
4471   return isGuaranteedNotToBeUndefOrPoison(Op, DemandedElts, PoisonOnly, Depth);
4472 }
4473 
4474 bool SelectionDAG::isGuaranteedNotToBeUndefOrPoison(SDValue Op,
4475                                                     const APInt &DemandedElts,
4476                                                     bool PoisonOnly,
4477                                                     unsigned Depth) const {
4478   unsigned Opcode = Op.getOpcode();
4479 
4480   // Early out for FREEZE.
4481   if (Opcode == ISD::FREEZE)
4482     return true;
4483 
4484   if (Depth >= MaxRecursionDepth)
4485     return false; // Limit search depth.
4486 
4487   if (isIntOrFPConstant(Op))
4488     return true;
4489 
4490   switch (Opcode) {
4491   case ISD::UNDEF:
4492     return PoisonOnly;
4493 
4494   case ISD::BUILD_VECTOR:
4495     // NOTE: BUILD_VECTOR has implicit truncation of wider scalar elements -
4496     // this shouldn't affect the result.
4497     for (unsigned i = 0, e = Op.getNumOperands(); i < e; ++i) {
4498       if (!DemandedElts[i])
4499         continue;
4500       if (!isGuaranteedNotToBeUndefOrPoison(Op.getOperand(i), PoisonOnly,
4501                                             Depth + 1))
4502         return false;
4503     }
4504     return true;
4505 
4506   // TODO: Search for noundef attributes from library functions.
4507 
4508   // TODO: Pointers dereferenced by ISD::LOAD/STORE ops are noundef.
4509 
4510   default:
4511     // Allow the target to implement this method for its nodes.
4512     if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
4513         Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID)
4514       return TLI->isGuaranteedNotToBeUndefOrPoisonForTargetNode(
4515           Op, DemandedElts, *this, PoisonOnly, Depth);
4516     break;
4517   }
4518 
4519   return false;
4520 }
4521 
4522 bool SelectionDAG::isBaseWithConstantOffset(SDValue Op) const {
4523   if ((Op.getOpcode() != ISD::ADD && Op.getOpcode() != ISD::OR) ||
4524       !isa<ConstantSDNode>(Op.getOperand(1)))
4525     return false;
4526 
4527   if (Op.getOpcode() == ISD::OR &&
4528       !MaskedValueIsZero(Op.getOperand(0), Op.getConstantOperandAPInt(1)))
4529     return false;
4530 
4531   return true;
4532 }
4533 
4534 bool SelectionDAG::isKnownNeverNaN(SDValue Op, bool SNaN, unsigned Depth) const {
4535   // If we're told that NaNs won't happen, assume they won't.
4536   if (getTarget().Options.NoNaNsFPMath || Op->getFlags().hasNoNaNs())
4537     return true;
4538 
4539   if (Depth >= MaxRecursionDepth)
4540     return false; // Limit search depth.
4541 
4542   // TODO: Handle vectors.
4543   // If the value is a constant, we can obviously see if it is a NaN or not.
4544   if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) {
4545     return !C->getValueAPF().isNaN() ||
4546            (SNaN && !C->getValueAPF().isSignaling());
4547   }
4548 
4549   unsigned Opcode = Op.getOpcode();
4550   switch (Opcode) {
4551   case ISD::FADD:
4552   case ISD::FSUB:
4553   case ISD::FMUL:
4554   case ISD::FDIV:
4555   case ISD::FREM:
4556   case ISD::FSIN:
4557   case ISD::FCOS: {
4558     if (SNaN)
4559       return true;
4560     // TODO: Need isKnownNeverInfinity
4561     return false;
4562   }
4563   case ISD::FCANONICALIZE:
4564   case ISD::FEXP:
4565   case ISD::FEXP2:
4566   case ISD::FTRUNC:
4567   case ISD::FFLOOR:
4568   case ISD::FCEIL:
4569   case ISD::FROUND:
4570   case ISD::FROUNDEVEN:
4571   case ISD::FRINT:
4572   case ISD::FNEARBYINT: {
4573     if (SNaN)
4574       return true;
4575     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4576   }
4577   case ISD::FABS:
4578   case ISD::FNEG:
4579   case ISD::FCOPYSIGN: {
4580     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4581   }
4582   case ISD::SELECT:
4583     return isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) &&
4584            isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1);
4585   case ISD::FP_EXTEND:
4586   case ISD::FP_ROUND: {
4587     if (SNaN)
4588       return true;
4589     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4590   }
4591   case ISD::SINT_TO_FP:
4592   case ISD::UINT_TO_FP:
4593     return true;
4594   case ISD::FMA:
4595   case ISD::FMAD: {
4596     if (SNaN)
4597       return true;
4598     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) &&
4599            isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) &&
4600            isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1);
4601   }
4602   case ISD::FSQRT: // Need is known positive
4603   case ISD::FLOG:
4604   case ISD::FLOG2:
4605   case ISD::FLOG10:
4606   case ISD::FPOWI:
4607   case ISD::FPOW: {
4608     if (SNaN)
4609       return true;
4610     // TODO: Refine on operand
4611     return false;
4612   }
4613   case ISD::FMINNUM:
4614   case ISD::FMAXNUM: {
4615     // Only one needs to be known not-nan, since it will be returned if the
4616     // other ends up being one.
4617     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) ||
4618            isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1);
4619   }
4620   case ISD::FMINNUM_IEEE:
4621   case ISD::FMAXNUM_IEEE: {
4622     if (SNaN)
4623       return true;
4624     // This can return a NaN if either operand is an sNaN, or if both operands
4625     // are NaN.
4626     return (isKnownNeverNaN(Op.getOperand(0), false, Depth + 1) &&
4627             isKnownNeverSNaN(Op.getOperand(1), Depth + 1)) ||
4628            (isKnownNeverNaN(Op.getOperand(1), false, Depth + 1) &&
4629             isKnownNeverSNaN(Op.getOperand(0), Depth + 1));
4630   }
4631   case ISD::FMINIMUM:
4632   case ISD::FMAXIMUM: {
4633     // TODO: Does this quiet or return the origina NaN as-is?
4634     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) &&
4635            isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1);
4636   }
4637   case ISD::EXTRACT_VECTOR_ELT: {
4638     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4639   }
4640   default:
4641     if (Opcode >= ISD::BUILTIN_OP_END ||
4642         Opcode == ISD::INTRINSIC_WO_CHAIN ||
4643         Opcode == ISD::INTRINSIC_W_CHAIN ||
4644         Opcode == ISD::INTRINSIC_VOID) {
4645       return TLI->isKnownNeverNaNForTargetNode(Op, *this, SNaN, Depth);
4646     }
4647 
4648     return false;
4649   }
4650 }
4651 
4652 bool SelectionDAG::isKnownNeverZeroFloat(SDValue Op) const {
4653   assert(Op.getValueType().isFloatingPoint() &&
4654          "Floating point type expected");
4655 
4656   // If the value is a constant, we can obviously see if it is a zero or not.
4657   // TODO: Add BuildVector support.
4658   if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
4659     return !C->isZero();
4660   return false;
4661 }
4662 
4663 bool SelectionDAG::isKnownNeverZero(SDValue Op) const {
4664   assert(!Op.getValueType().isFloatingPoint() &&
4665          "Floating point types unsupported - use isKnownNeverZeroFloat");
4666 
4667   // If the value is a constant, we can obviously see if it is a zero or not.
4668   if (ISD::matchUnaryPredicate(Op,
4669                                [](ConstantSDNode *C) { return !C->isZero(); }))
4670     return true;
4671 
4672   // TODO: Recognize more cases here.
4673   switch (Op.getOpcode()) {
4674   default: break;
4675   case ISD::OR:
4676     if (isKnownNeverZero(Op.getOperand(1)) ||
4677         isKnownNeverZero(Op.getOperand(0)))
4678       return true;
4679     break;
4680   }
4681 
4682   return false;
4683 }
4684 
4685 bool SelectionDAG::isEqualTo(SDValue A, SDValue B) const {
4686   // Check the obvious case.
4687   if (A == B) return true;
4688 
4689   // For for negative and positive zero.
4690   if (const ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A))
4691     if (const ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B))
4692       if (CA->isZero() && CB->isZero()) return true;
4693 
4694   // Otherwise they may not be equal.
4695   return false;
4696 }
4697 
4698 // Only bits set in Mask must be negated, other bits may be arbitrary.
4699 SDValue llvm::getBitwiseNotOperand(SDValue V, SDValue Mask, bool AllowUndefs) {
4700   if (isBitwiseNot(V, AllowUndefs))
4701     return V.getOperand(0);
4702 
4703   // Handle any_extend (not (truncate X)) pattern, where Mask only sets
4704   // bits in the non-extended part.
4705   ConstantSDNode *MaskC = isConstOrConstSplat(Mask);
4706   if (!MaskC || V.getOpcode() != ISD::ANY_EXTEND)
4707     return SDValue();
4708   SDValue ExtArg = V.getOperand(0);
4709   if (ExtArg.getScalarValueSizeInBits() >=
4710           MaskC->getAPIntValue().getActiveBits() &&
4711       isBitwiseNot(ExtArg, AllowUndefs) &&
4712       ExtArg.getOperand(0).getOpcode() == ISD::TRUNCATE &&
4713       ExtArg.getOperand(0).getOperand(0).getValueType() == V.getValueType())
4714     return ExtArg.getOperand(0).getOperand(0);
4715   return SDValue();
4716 }
4717 
4718 static bool haveNoCommonBitsSetCommutative(SDValue A, SDValue B) {
4719   // Match masked merge pattern (X & ~M) op (Y & M)
4720   // Including degenerate case (X & ~M) op M
4721   auto MatchNoCommonBitsPattern = [&](SDValue Not, SDValue Mask,
4722                                       SDValue Other) {
4723     if (SDValue NotOperand =
4724             getBitwiseNotOperand(Not, Mask, /* AllowUndefs */ true)) {
4725       if (Other == NotOperand)
4726         return true;
4727       if (Other->getOpcode() == ISD::AND)
4728         return NotOperand == Other->getOperand(0) ||
4729                NotOperand == Other->getOperand(1);
4730     }
4731     return false;
4732   };
4733   if (A->getOpcode() == ISD::AND)
4734     return MatchNoCommonBitsPattern(A->getOperand(0), A->getOperand(1), B) ||
4735            MatchNoCommonBitsPattern(A->getOperand(1), A->getOperand(0), B);
4736   return false;
4737 }
4738 
4739 // FIXME: unify with llvm::haveNoCommonBitsSet.
4740 bool SelectionDAG::haveNoCommonBitsSet(SDValue A, SDValue B) const {
4741   assert(A.getValueType() == B.getValueType() &&
4742          "Values must have the same type");
4743   if (haveNoCommonBitsSetCommutative(A, B) ||
4744       haveNoCommonBitsSetCommutative(B, A))
4745     return true;
4746   return KnownBits::haveNoCommonBitsSet(computeKnownBits(A),
4747                                         computeKnownBits(B));
4748 }
4749 
4750 static SDValue FoldSTEP_VECTOR(const SDLoc &DL, EVT VT, SDValue Step,
4751                                SelectionDAG &DAG) {
4752   if (cast<ConstantSDNode>(Step)->isZero())
4753     return DAG.getConstant(0, DL, VT);
4754 
4755   return SDValue();
4756 }
4757 
4758 static SDValue FoldBUILD_VECTOR(const SDLoc &DL, EVT VT,
4759                                 ArrayRef<SDValue> Ops,
4760                                 SelectionDAG &DAG) {
4761   int NumOps = Ops.size();
4762   assert(NumOps != 0 && "Can't build an empty vector!");
4763   assert(!VT.isScalableVector() &&
4764          "BUILD_VECTOR cannot be used with scalable types");
4765   assert(VT.getVectorNumElements() == (unsigned)NumOps &&
4766          "Incorrect element count in BUILD_VECTOR!");
4767 
4768   // BUILD_VECTOR of UNDEFs is UNDEF.
4769   if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
4770     return DAG.getUNDEF(VT);
4771 
4772   // BUILD_VECTOR of seq extract/insert from the same vector + type is Identity.
4773   SDValue IdentitySrc;
4774   bool IsIdentity = true;
4775   for (int i = 0; i != NumOps; ++i) {
4776     if (Ops[i].getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4777         Ops[i].getOperand(0).getValueType() != VT ||
4778         (IdentitySrc && Ops[i].getOperand(0) != IdentitySrc) ||
4779         !isa<ConstantSDNode>(Ops[i].getOperand(1)) ||
4780         cast<ConstantSDNode>(Ops[i].getOperand(1))->getAPIntValue() != i) {
4781       IsIdentity = false;
4782       break;
4783     }
4784     IdentitySrc = Ops[i].getOperand(0);
4785   }
4786   if (IsIdentity)
4787     return IdentitySrc;
4788 
4789   return SDValue();
4790 }
4791 
4792 /// Try to simplify vector concatenation to an input value, undef, or build
4793 /// vector.
4794 static SDValue foldCONCAT_VECTORS(const SDLoc &DL, EVT VT,
4795                                   ArrayRef<SDValue> Ops,
4796                                   SelectionDAG &DAG) {
4797   assert(!Ops.empty() && "Can't concatenate an empty list of vectors!");
4798   assert(llvm::all_of(Ops,
4799                       [Ops](SDValue Op) {
4800                         return Ops[0].getValueType() == Op.getValueType();
4801                       }) &&
4802          "Concatenation of vectors with inconsistent value types!");
4803   assert((Ops[0].getValueType().getVectorElementCount() * Ops.size()) ==
4804              VT.getVectorElementCount() &&
4805          "Incorrect element count in vector concatenation!");
4806 
4807   if (Ops.size() == 1)
4808     return Ops[0];
4809 
4810   // Concat of UNDEFs is UNDEF.
4811   if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
4812     return DAG.getUNDEF(VT);
4813 
4814   // Scan the operands and look for extract operations from a single source
4815   // that correspond to insertion at the same location via this concatenation:
4816   // concat (extract X, 0*subvec_elts), (extract X, 1*subvec_elts), ...
4817   SDValue IdentitySrc;
4818   bool IsIdentity = true;
4819   for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
4820     SDValue Op = Ops[i];
4821     unsigned IdentityIndex = i * Op.getValueType().getVectorMinNumElements();
4822     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
4823         Op.getOperand(0).getValueType() != VT ||
4824         (IdentitySrc && Op.getOperand(0) != IdentitySrc) ||
4825         Op.getConstantOperandVal(1) != IdentityIndex) {
4826       IsIdentity = false;
4827       break;
4828     }
4829     assert((!IdentitySrc || IdentitySrc == Op.getOperand(0)) &&
4830            "Unexpected identity source vector for concat of extracts");
4831     IdentitySrc = Op.getOperand(0);
4832   }
4833   if (IsIdentity) {
4834     assert(IdentitySrc && "Failed to set source vector of extracts");
4835     return IdentitySrc;
4836   }
4837 
4838   // The code below this point is only designed to work for fixed width
4839   // vectors, so we bail out for now.
4840   if (VT.isScalableVector())
4841     return SDValue();
4842 
4843   // A CONCAT_VECTOR with all UNDEF/BUILD_VECTOR operands can be
4844   // simplified to one big BUILD_VECTOR.
4845   // FIXME: Add support for SCALAR_TO_VECTOR as well.
4846   EVT SVT = VT.getScalarType();
4847   SmallVector<SDValue, 16> Elts;
4848   for (SDValue Op : Ops) {
4849     EVT OpVT = Op.getValueType();
4850     if (Op.isUndef())
4851       Elts.append(OpVT.getVectorNumElements(), DAG.getUNDEF(SVT));
4852     else if (Op.getOpcode() == ISD::BUILD_VECTOR)
4853       Elts.append(Op->op_begin(), Op->op_end());
4854     else
4855       return SDValue();
4856   }
4857 
4858   // BUILD_VECTOR requires all inputs to be of the same type, find the
4859   // maximum type and extend them all.
4860   for (SDValue Op : Elts)
4861     SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
4862 
4863   if (SVT.bitsGT(VT.getScalarType())) {
4864     for (SDValue &Op : Elts) {
4865       if (Op.isUndef())
4866         Op = DAG.getUNDEF(SVT);
4867       else
4868         Op = DAG.getTargetLoweringInfo().isZExtFree(Op.getValueType(), SVT)
4869                  ? DAG.getZExtOrTrunc(Op, DL, SVT)
4870                  : DAG.getSExtOrTrunc(Op, DL, SVT);
4871     }
4872   }
4873 
4874   SDValue V = DAG.getBuildVector(VT, DL, Elts);
4875   NewSDValueDbgMsg(V, "New node fold concat vectors: ", &DAG);
4876   return V;
4877 }
4878 
4879 /// Gets or creates the specified node.
4880 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT) {
4881   FoldingSetNodeID ID;
4882   AddNodeIDNode(ID, Opcode, getVTList(VT), None);
4883   void *IP = nullptr;
4884   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
4885     return SDValue(E, 0);
4886 
4887   auto *N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(),
4888                               getVTList(VT));
4889   CSEMap.InsertNode(N, IP);
4890 
4891   InsertNode(N);
4892   SDValue V = SDValue(N, 0);
4893   NewSDValueDbgMsg(V, "Creating new node: ", this);
4894   return V;
4895 }
4896 
4897 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4898                               SDValue Operand) {
4899   SDNodeFlags Flags;
4900   if (Inserter)
4901     Flags = Inserter->getFlags();
4902   return getNode(Opcode, DL, VT, Operand, Flags);
4903 }
4904 
4905 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4906                               SDValue Operand, const SDNodeFlags Flags) {
4907   assert(Operand.getOpcode() != ISD::DELETED_NODE &&
4908          "Operand is DELETED_NODE!");
4909   // Constant fold unary operations with an integer constant operand. Even
4910   // opaque constant will be folded, because the folding of unary operations
4911   // doesn't create new constants with different values. Nevertheless, the
4912   // opaque flag is preserved during folding to prevent future folding with
4913   // other constants.
4914   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand)) {
4915     const APInt &Val = C->getAPIntValue();
4916     switch (Opcode) {
4917     default: break;
4918     case ISD::SIGN_EXTEND:
4919       return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
4920                          C->isTargetOpcode(), C->isOpaque());
4921     case ISD::TRUNCATE:
4922       if (C->isOpaque())
4923         break;
4924       LLVM_FALLTHROUGH;
4925     case ISD::ZERO_EXTEND:
4926       return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
4927                          C->isTargetOpcode(), C->isOpaque());
4928     case ISD::ANY_EXTEND:
4929       // Some targets like RISCV prefer to sign extend some types.
4930       if (TLI->isSExtCheaperThanZExt(Operand.getValueType(), VT))
4931         return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
4932                            C->isTargetOpcode(), C->isOpaque());
4933       return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
4934                          C->isTargetOpcode(), C->isOpaque());
4935     case ISD::UINT_TO_FP:
4936     case ISD::SINT_TO_FP: {
4937       APFloat apf(EVTToAPFloatSemantics(VT),
4938                   APInt::getZero(VT.getSizeInBits()));
4939       (void)apf.convertFromAPInt(Val,
4940                                  Opcode==ISD::SINT_TO_FP,
4941                                  APFloat::rmNearestTiesToEven);
4942       return getConstantFP(apf, DL, VT);
4943     }
4944     case ISD::BITCAST:
4945       if (VT == MVT::f16 && C->getValueType(0) == MVT::i16)
4946         return getConstantFP(APFloat(APFloat::IEEEhalf(), Val), DL, VT);
4947       if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
4948         return getConstantFP(APFloat(APFloat::IEEEsingle(), Val), DL, VT);
4949       if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
4950         return getConstantFP(APFloat(APFloat::IEEEdouble(), Val), DL, VT);
4951       if (VT == MVT::f128 && C->getValueType(0) == MVT::i128)
4952         return getConstantFP(APFloat(APFloat::IEEEquad(), Val), DL, VT);
4953       break;
4954     case ISD::ABS:
4955       return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(),
4956                          C->isOpaque());
4957     case ISD::BITREVERSE:
4958       return getConstant(Val.reverseBits(), DL, VT, C->isTargetOpcode(),
4959                          C->isOpaque());
4960     case ISD::BSWAP:
4961       return getConstant(Val.byteSwap(), DL, VT, C->isTargetOpcode(),
4962                          C->isOpaque());
4963     case ISD::CTPOP:
4964       return getConstant(Val.countPopulation(), DL, VT, C->isTargetOpcode(),
4965                          C->isOpaque());
4966     case ISD::CTLZ:
4967     case ISD::CTLZ_ZERO_UNDEF:
4968       return getConstant(Val.countLeadingZeros(), DL, VT, C->isTargetOpcode(),
4969                          C->isOpaque());
4970     case ISD::CTTZ:
4971     case ISD::CTTZ_ZERO_UNDEF:
4972       return getConstant(Val.countTrailingZeros(), DL, VT, C->isTargetOpcode(),
4973                          C->isOpaque());
4974     case ISD::FP16_TO_FP: {
4975       bool Ignored;
4976       APFloat FPV(APFloat::IEEEhalf(),
4977                   (Val.getBitWidth() == 16) ? Val : Val.trunc(16));
4978 
4979       // This can return overflow, underflow, or inexact; we don't care.
4980       // FIXME need to be more flexible about rounding mode.
4981       (void)FPV.convert(EVTToAPFloatSemantics(VT),
4982                         APFloat::rmNearestTiesToEven, &Ignored);
4983       return getConstantFP(FPV, DL, VT);
4984     }
4985     case ISD::STEP_VECTOR: {
4986       if (SDValue V = FoldSTEP_VECTOR(DL, VT, Operand, *this))
4987         return V;
4988       break;
4989     }
4990     }
4991   }
4992 
4993   // Constant fold unary operations with a floating point constant operand.
4994   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand)) {
4995     APFloat V = C->getValueAPF();    // make copy
4996     switch (Opcode) {
4997     case ISD::FNEG:
4998       V.changeSign();
4999       return getConstantFP(V, DL, VT);
5000     case ISD::FABS:
5001       V.clearSign();
5002       return getConstantFP(V, DL, VT);
5003     case ISD::FCEIL: {
5004       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardPositive);
5005       if (fs == APFloat::opOK || fs == APFloat::opInexact)
5006         return getConstantFP(V, DL, VT);
5007       break;
5008     }
5009     case ISD::FTRUNC: {
5010       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardZero);
5011       if (fs == APFloat::opOK || fs == APFloat::opInexact)
5012         return getConstantFP(V, DL, VT);
5013       break;
5014     }
5015     case ISD::FFLOOR: {
5016       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardNegative);
5017       if (fs == APFloat::opOK || fs == APFloat::opInexact)
5018         return getConstantFP(V, DL, VT);
5019       break;
5020     }
5021     case ISD::FP_EXTEND: {
5022       bool ignored;
5023       // This can return overflow, underflow, or inexact; we don't care.
5024       // FIXME need to be more flexible about rounding mode.
5025       (void)V.convert(EVTToAPFloatSemantics(VT),
5026                       APFloat::rmNearestTiesToEven, &ignored);
5027       return getConstantFP(V, DL, VT);
5028     }
5029     case ISD::FP_TO_SINT:
5030     case ISD::FP_TO_UINT: {
5031       bool ignored;
5032       APSInt IntVal(VT.getSizeInBits(), Opcode == ISD::FP_TO_UINT);
5033       // FIXME need to be more flexible about rounding mode.
5034       APFloat::opStatus s =
5035           V.convertToInteger(IntVal, APFloat::rmTowardZero, &ignored);
5036       if (s == APFloat::opInvalidOp) // inexact is OK, in fact usual
5037         break;
5038       return getConstant(IntVal, DL, VT);
5039     }
5040     case ISD::BITCAST:
5041       if (VT == MVT::i16 && C->getValueType(0) == MVT::f16)
5042         return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
5043       if (VT == MVT::i16 && C->getValueType(0) == MVT::bf16)
5044         return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
5045       if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
5046         return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
5047       if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
5048         return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
5049       break;
5050     case ISD::FP_TO_FP16: {
5051       bool Ignored;
5052       // This can return overflow, underflow, or inexact; we don't care.
5053       // FIXME need to be more flexible about rounding mode.
5054       (void)V.convert(APFloat::IEEEhalf(),
5055                       APFloat::rmNearestTiesToEven, &Ignored);
5056       return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
5057     }
5058     }
5059   }
5060 
5061   // Constant fold unary operations with a vector integer or float operand.
5062   switch (Opcode) {
5063   default:
5064     // FIXME: Entirely reasonable to perform folding of other unary
5065     // operations here as the need arises.
5066     break;
5067   case ISD::FNEG:
5068   case ISD::FABS:
5069   case ISD::FCEIL:
5070   case ISD::FTRUNC:
5071   case ISD::FFLOOR:
5072   case ISD::FP_EXTEND:
5073   case ISD::FP_TO_SINT:
5074   case ISD::FP_TO_UINT:
5075   case ISD::TRUNCATE:
5076   case ISD::ANY_EXTEND:
5077   case ISD::ZERO_EXTEND:
5078   case ISD::SIGN_EXTEND:
5079   case ISD::UINT_TO_FP:
5080   case ISD::SINT_TO_FP:
5081   case ISD::ABS:
5082   case ISD::BITREVERSE:
5083   case ISD::BSWAP:
5084   case ISD::CTLZ:
5085   case ISD::CTLZ_ZERO_UNDEF:
5086   case ISD::CTTZ:
5087   case ISD::CTTZ_ZERO_UNDEF:
5088   case ISD::CTPOP: {
5089     SDValue Ops = {Operand};
5090     if (SDValue Fold = FoldConstantArithmetic(Opcode, DL, VT, Ops))
5091       return Fold;
5092   }
5093   }
5094 
5095   unsigned OpOpcode = Operand.getNode()->getOpcode();
5096   switch (Opcode) {
5097   case ISD::STEP_VECTOR:
5098     assert(VT.isScalableVector() &&
5099            "STEP_VECTOR can only be used with scalable types");
5100     assert(OpOpcode == ISD::TargetConstant &&
5101            VT.getVectorElementType() == Operand.getValueType() &&
5102            "Unexpected step operand");
5103     break;
5104   case ISD::FREEZE:
5105     assert(VT == Operand.getValueType() && "Unexpected VT!");
5106     if (isGuaranteedNotToBeUndefOrPoison(Operand))
5107       return Operand;
5108     break;
5109   case ISD::TokenFactor:
5110   case ISD::MERGE_VALUES:
5111   case ISD::CONCAT_VECTORS:
5112     return Operand;         // Factor, merge or concat of one node?  No need.
5113   case ISD::BUILD_VECTOR: {
5114     // Attempt to simplify BUILD_VECTOR.
5115     SDValue Ops[] = {Operand};
5116     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
5117       return V;
5118     break;
5119   }
5120   case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node");
5121   case ISD::FP_EXTEND:
5122     assert(VT.isFloatingPoint() &&
5123            Operand.getValueType().isFloatingPoint() && "Invalid FP cast!");
5124     if (Operand.getValueType() == VT) return Operand;  // noop conversion.
5125     assert((!VT.isVector() ||
5126             VT.getVectorElementCount() ==
5127             Operand.getValueType().getVectorElementCount()) &&
5128            "Vector element count mismatch!");
5129     assert(Operand.getValueType().bitsLT(VT) &&
5130            "Invalid fpext node, dst < src!");
5131     if (Operand.isUndef())
5132       return getUNDEF(VT);
5133     break;
5134   case ISD::FP_TO_SINT:
5135   case ISD::FP_TO_UINT:
5136     if (Operand.isUndef())
5137       return getUNDEF(VT);
5138     break;
5139   case ISD::SINT_TO_FP:
5140   case ISD::UINT_TO_FP:
5141     // [us]itofp(undef) = 0, because the result value is bounded.
5142     if (Operand.isUndef())
5143       return getConstantFP(0.0, DL, VT);
5144     break;
5145   case ISD::SIGN_EXTEND:
5146     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
5147            "Invalid SIGN_EXTEND!");
5148     assert(VT.isVector() == Operand.getValueType().isVector() &&
5149            "SIGN_EXTEND result type type should be vector iff the operand "
5150            "type is vector!");
5151     if (Operand.getValueType() == VT) return Operand;   // noop extension
5152     assert((!VT.isVector() ||
5153             VT.getVectorElementCount() ==
5154                 Operand.getValueType().getVectorElementCount()) &&
5155            "Vector element count mismatch!");
5156     assert(Operand.getValueType().bitsLT(VT) &&
5157            "Invalid sext node, dst < src!");
5158     if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
5159       return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
5160     if (OpOpcode == ISD::UNDEF)
5161       // sext(undef) = 0, because the top bits will all be the same.
5162       return getConstant(0, DL, VT);
5163     break;
5164   case ISD::ZERO_EXTEND:
5165     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
5166            "Invalid ZERO_EXTEND!");
5167     assert(VT.isVector() == Operand.getValueType().isVector() &&
5168            "ZERO_EXTEND result type type should be vector iff the operand "
5169            "type is vector!");
5170     if (Operand.getValueType() == VT) return Operand;   // noop extension
5171     assert((!VT.isVector() ||
5172             VT.getVectorElementCount() ==
5173                 Operand.getValueType().getVectorElementCount()) &&
5174            "Vector element count mismatch!");
5175     assert(Operand.getValueType().bitsLT(VT) &&
5176            "Invalid zext node, dst < src!");
5177     if (OpOpcode == ISD::ZERO_EXTEND)   // (zext (zext x)) -> (zext x)
5178       return getNode(ISD::ZERO_EXTEND, DL, VT, Operand.getOperand(0));
5179     if (OpOpcode == ISD::UNDEF)
5180       // zext(undef) = 0, because the top bits will be zero.
5181       return getConstant(0, DL, VT);
5182     break;
5183   case ISD::ANY_EXTEND:
5184     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
5185            "Invalid ANY_EXTEND!");
5186     assert(VT.isVector() == Operand.getValueType().isVector() &&
5187            "ANY_EXTEND result type type should be vector iff the operand "
5188            "type is vector!");
5189     if (Operand.getValueType() == VT) return Operand;   // noop extension
5190     assert((!VT.isVector() ||
5191             VT.getVectorElementCount() ==
5192                 Operand.getValueType().getVectorElementCount()) &&
5193            "Vector element count mismatch!");
5194     assert(Operand.getValueType().bitsLT(VT) &&
5195            "Invalid anyext node, dst < src!");
5196 
5197     if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
5198         OpOpcode == ISD::ANY_EXTEND)
5199       // (ext (zext x)) -> (zext x)  and  (ext (sext x)) -> (sext x)
5200       return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
5201     if (OpOpcode == ISD::UNDEF)
5202       return getUNDEF(VT);
5203 
5204     // (ext (trunc x)) -> x
5205     if (OpOpcode == ISD::TRUNCATE) {
5206       SDValue OpOp = Operand.getOperand(0);
5207       if (OpOp.getValueType() == VT) {
5208         transferDbgValues(Operand, OpOp);
5209         return OpOp;
5210       }
5211     }
5212     break;
5213   case ISD::TRUNCATE:
5214     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
5215            "Invalid TRUNCATE!");
5216     assert(VT.isVector() == Operand.getValueType().isVector() &&
5217            "TRUNCATE result type type should be vector iff the operand "
5218            "type is vector!");
5219     if (Operand.getValueType() == VT) return Operand;   // noop truncate
5220     assert((!VT.isVector() ||
5221             VT.getVectorElementCount() ==
5222                 Operand.getValueType().getVectorElementCount()) &&
5223            "Vector element count mismatch!");
5224     assert(Operand.getValueType().bitsGT(VT) &&
5225            "Invalid truncate node, src < dst!");
5226     if (OpOpcode == ISD::TRUNCATE)
5227       return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0));
5228     if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
5229         OpOpcode == ISD::ANY_EXTEND) {
5230       // If the source is smaller than the dest, we still need an extend.
5231       if (Operand.getOperand(0).getValueType().getScalarType()
5232             .bitsLT(VT.getScalarType()))
5233         return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
5234       if (Operand.getOperand(0).getValueType().bitsGT(VT))
5235         return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0));
5236       return Operand.getOperand(0);
5237     }
5238     if (OpOpcode == ISD::UNDEF)
5239       return getUNDEF(VT);
5240     if (OpOpcode == ISD::VSCALE && !NewNodesMustHaveLegalTypes)
5241       return getVScale(DL, VT, Operand.getConstantOperandAPInt(0));
5242     break;
5243   case ISD::ANY_EXTEND_VECTOR_INREG:
5244   case ISD::ZERO_EXTEND_VECTOR_INREG:
5245   case ISD::SIGN_EXTEND_VECTOR_INREG:
5246     assert(VT.isVector() && "This DAG node is restricted to vector types.");
5247     assert(Operand.getValueType().bitsLE(VT) &&
5248            "The input must be the same size or smaller than the result.");
5249     assert(VT.getVectorMinNumElements() <
5250                Operand.getValueType().getVectorMinNumElements() &&
5251            "The destination vector type must have fewer lanes than the input.");
5252     break;
5253   case ISD::ABS:
5254     assert(VT.isInteger() && VT == Operand.getValueType() &&
5255            "Invalid ABS!");
5256     if (OpOpcode == ISD::UNDEF)
5257       return getConstant(0, DL, VT);
5258     break;
5259   case ISD::BSWAP:
5260     assert(VT.isInteger() && VT == Operand.getValueType() &&
5261            "Invalid BSWAP!");
5262     assert((VT.getScalarSizeInBits() % 16 == 0) &&
5263            "BSWAP types must be a multiple of 16 bits!");
5264     if (OpOpcode == ISD::UNDEF)
5265       return getUNDEF(VT);
5266     // bswap(bswap(X)) -> X.
5267     if (OpOpcode == ISD::BSWAP)
5268       return Operand.getOperand(0);
5269     break;
5270   case ISD::BITREVERSE:
5271     assert(VT.isInteger() && VT == Operand.getValueType() &&
5272            "Invalid BITREVERSE!");
5273     if (OpOpcode == ISD::UNDEF)
5274       return getUNDEF(VT);
5275     break;
5276   case ISD::BITCAST:
5277     assert(VT.getSizeInBits() == Operand.getValueSizeInBits() &&
5278            "Cannot BITCAST between types of different sizes!");
5279     if (VT == Operand.getValueType()) return Operand;  // noop conversion.
5280     if (OpOpcode == ISD::BITCAST)  // bitconv(bitconv(x)) -> bitconv(x)
5281       return getNode(ISD::BITCAST, DL, VT, Operand.getOperand(0));
5282     if (OpOpcode == ISD::UNDEF)
5283       return getUNDEF(VT);
5284     break;
5285   case ISD::SCALAR_TO_VECTOR:
5286     assert(VT.isVector() && !Operand.getValueType().isVector() &&
5287            (VT.getVectorElementType() == Operand.getValueType() ||
5288             (VT.getVectorElementType().isInteger() &&
5289              Operand.getValueType().isInteger() &&
5290              VT.getVectorElementType().bitsLE(Operand.getValueType()))) &&
5291            "Illegal SCALAR_TO_VECTOR node!");
5292     if (OpOpcode == ISD::UNDEF)
5293       return getUNDEF(VT);
5294     // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
5295     if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
5296         isa<ConstantSDNode>(Operand.getOperand(1)) &&
5297         Operand.getConstantOperandVal(1) == 0 &&
5298         Operand.getOperand(0).getValueType() == VT)
5299       return Operand.getOperand(0);
5300     break;
5301   case ISD::FNEG:
5302     // Negation of an unknown bag of bits is still completely undefined.
5303     if (OpOpcode == ISD::UNDEF)
5304       return getUNDEF(VT);
5305 
5306     if (OpOpcode == ISD::FNEG)  // --X -> X
5307       return Operand.getOperand(0);
5308     break;
5309   case ISD::FABS:
5310     if (OpOpcode == ISD::FNEG)  // abs(-X) -> abs(X)
5311       return getNode(ISD::FABS, DL, VT, Operand.getOperand(0));
5312     break;
5313   case ISD::VSCALE:
5314     assert(VT == Operand.getValueType() && "Unexpected VT!");
5315     break;
5316   case ISD::CTPOP:
5317     if (Operand.getValueType().getScalarType() == MVT::i1)
5318       return Operand;
5319     break;
5320   case ISD::CTLZ:
5321   case ISD::CTTZ:
5322     if (Operand.getValueType().getScalarType() == MVT::i1)
5323       return getNOT(DL, Operand, Operand.getValueType());
5324     break;
5325   case ISD::VECREDUCE_ADD:
5326     if (Operand.getValueType().getScalarType() == MVT::i1)
5327       return getNode(ISD::VECREDUCE_XOR, DL, VT, Operand);
5328     break;
5329   case ISD::VECREDUCE_SMIN:
5330   case ISD::VECREDUCE_UMAX:
5331     if (Operand.getValueType().getScalarType() == MVT::i1)
5332       return getNode(ISD::VECREDUCE_OR, DL, VT, Operand);
5333     break;
5334   case ISD::VECREDUCE_SMAX:
5335   case ISD::VECREDUCE_UMIN:
5336     if (Operand.getValueType().getScalarType() == MVT::i1)
5337       return getNode(ISD::VECREDUCE_AND, DL, VT, Operand);
5338     break;
5339   }
5340 
5341   SDNode *N;
5342   SDVTList VTs = getVTList(VT);
5343   SDValue Ops[] = {Operand};
5344   if (VT != MVT::Glue) { // Don't CSE flag producing nodes
5345     FoldingSetNodeID ID;
5346     AddNodeIDNode(ID, Opcode, VTs, Ops);
5347     void *IP = nullptr;
5348     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
5349       E->intersectFlagsWith(Flags);
5350       return SDValue(E, 0);
5351     }
5352 
5353     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5354     N->setFlags(Flags);
5355     createOperands(N, Ops);
5356     CSEMap.InsertNode(N, IP);
5357   } else {
5358     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5359     createOperands(N, Ops);
5360   }
5361 
5362   InsertNode(N);
5363   SDValue V = SDValue(N, 0);
5364   NewSDValueDbgMsg(V, "Creating new node: ", this);
5365   return V;
5366 }
5367 
5368 static llvm::Optional<APInt> FoldValue(unsigned Opcode, const APInt &C1,
5369                                        const APInt &C2) {
5370   switch (Opcode) {
5371   case ISD::ADD:  return C1 + C2;
5372   case ISD::SUB:  return C1 - C2;
5373   case ISD::MUL:  return C1 * C2;
5374   case ISD::AND:  return C1 & C2;
5375   case ISD::OR:   return C1 | C2;
5376   case ISD::XOR:  return C1 ^ C2;
5377   case ISD::SHL:  return C1 << C2;
5378   case ISD::SRL:  return C1.lshr(C2);
5379   case ISD::SRA:  return C1.ashr(C2);
5380   case ISD::ROTL: return C1.rotl(C2);
5381   case ISD::ROTR: return C1.rotr(C2);
5382   case ISD::SMIN: return C1.sle(C2) ? C1 : C2;
5383   case ISD::SMAX: return C1.sge(C2) ? C1 : C2;
5384   case ISD::UMIN: return C1.ule(C2) ? C1 : C2;
5385   case ISD::UMAX: return C1.uge(C2) ? C1 : C2;
5386   case ISD::SADDSAT: return C1.sadd_sat(C2);
5387   case ISD::UADDSAT: return C1.uadd_sat(C2);
5388   case ISD::SSUBSAT: return C1.ssub_sat(C2);
5389   case ISD::USUBSAT: return C1.usub_sat(C2);
5390   case ISD::SSHLSAT: return C1.sshl_sat(C2);
5391   case ISD::USHLSAT: return C1.ushl_sat(C2);
5392   case ISD::UDIV:
5393     if (!C2.getBoolValue())
5394       break;
5395     return C1.udiv(C2);
5396   case ISD::UREM:
5397     if (!C2.getBoolValue())
5398       break;
5399     return C1.urem(C2);
5400   case ISD::SDIV:
5401     if (!C2.getBoolValue())
5402       break;
5403     return C1.sdiv(C2);
5404   case ISD::SREM:
5405     if (!C2.getBoolValue())
5406       break;
5407     return C1.srem(C2);
5408   case ISD::MULHS: {
5409     unsigned FullWidth = C1.getBitWidth() * 2;
5410     APInt C1Ext = C1.sext(FullWidth);
5411     APInt C2Ext = C2.sext(FullWidth);
5412     return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth());
5413   }
5414   case ISD::MULHU: {
5415     unsigned FullWidth = C1.getBitWidth() * 2;
5416     APInt C1Ext = C1.zext(FullWidth);
5417     APInt C2Ext = C2.zext(FullWidth);
5418     return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth());
5419   }
5420   case ISD::AVGFLOORS: {
5421     unsigned FullWidth = C1.getBitWidth() + 1;
5422     APInt C1Ext = C1.sext(FullWidth);
5423     APInt C2Ext = C2.sext(FullWidth);
5424     return (C1Ext + C2Ext).extractBits(C1.getBitWidth(), 1);
5425   }
5426   case ISD::AVGFLOORU: {
5427     unsigned FullWidth = C1.getBitWidth() + 1;
5428     APInt C1Ext = C1.zext(FullWidth);
5429     APInt C2Ext = C2.zext(FullWidth);
5430     return (C1Ext + C2Ext).extractBits(C1.getBitWidth(), 1);
5431   }
5432   case ISD::AVGCEILS: {
5433     unsigned FullWidth = C1.getBitWidth() + 1;
5434     APInt C1Ext = C1.sext(FullWidth);
5435     APInt C2Ext = C2.sext(FullWidth);
5436     return (C1Ext + C2Ext + 1).extractBits(C1.getBitWidth(), 1);
5437   }
5438   case ISD::AVGCEILU: {
5439     unsigned FullWidth = C1.getBitWidth() + 1;
5440     APInt C1Ext = C1.zext(FullWidth);
5441     APInt C2Ext = C2.zext(FullWidth);
5442     return (C1Ext + C2Ext + 1).extractBits(C1.getBitWidth(), 1);
5443   }
5444   }
5445   return llvm::None;
5446 }
5447 
5448 SDValue SelectionDAG::FoldSymbolOffset(unsigned Opcode, EVT VT,
5449                                        const GlobalAddressSDNode *GA,
5450                                        const SDNode *N2) {
5451   if (GA->getOpcode() != ISD::GlobalAddress)
5452     return SDValue();
5453   if (!TLI->isOffsetFoldingLegal(GA))
5454     return SDValue();
5455   auto *C2 = dyn_cast<ConstantSDNode>(N2);
5456   if (!C2)
5457     return SDValue();
5458   int64_t Offset = C2->getSExtValue();
5459   switch (Opcode) {
5460   case ISD::ADD: break;
5461   case ISD::SUB: Offset = -uint64_t(Offset); break;
5462   default: return SDValue();
5463   }
5464   return getGlobalAddress(GA->getGlobal(), SDLoc(C2), VT,
5465                           GA->getOffset() + uint64_t(Offset));
5466 }
5467 
5468 bool SelectionDAG::isUndef(unsigned Opcode, ArrayRef<SDValue> Ops) {
5469   switch (Opcode) {
5470   case ISD::SDIV:
5471   case ISD::UDIV:
5472   case ISD::SREM:
5473   case ISD::UREM: {
5474     // If a divisor is zero/undef or any element of a divisor vector is
5475     // zero/undef, the whole op is undef.
5476     assert(Ops.size() == 2 && "Div/rem should have 2 operands");
5477     SDValue Divisor = Ops[1];
5478     if (Divisor.isUndef() || isNullConstant(Divisor))
5479       return true;
5480 
5481     return ISD::isBuildVectorOfConstantSDNodes(Divisor.getNode()) &&
5482            llvm::any_of(Divisor->op_values(),
5483                         [](SDValue V) { return V.isUndef() ||
5484                                         isNullConstant(V); });
5485     // TODO: Handle signed overflow.
5486   }
5487   // TODO: Handle oversized shifts.
5488   default:
5489     return false;
5490   }
5491 }
5492 
5493 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL,
5494                                              EVT VT, ArrayRef<SDValue> Ops) {
5495   // If the opcode is a target-specific ISD node, there's nothing we can
5496   // do here and the operand rules may not line up with the below, so
5497   // bail early.
5498   // We can't create a scalar CONCAT_VECTORS so skip it. It will break
5499   // for concats involving SPLAT_VECTOR. Concats of BUILD_VECTORS are handled by
5500   // foldCONCAT_VECTORS in getNode before this is called.
5501   if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::CONCAT_VECTORS)
5502     return SDValue();
5503 
5504   unsigned NumOps = Ops.size();
5505   if (NumOps == 0)
5506     return SDValue();
5507 
5508   if (isUndef(Opcode, Ops))
5509     return getUNDEF(VT);
5510 
5511   // Handle binops special cases.
5512   if (NumOps == 2) {
5513     if (SDValue CFP = foldConstantFPMath(Opcode, DL, VT, Ops[0], Ops[1]))
5514       return CFP;
5515 
5516     if (auto *C1 = dyn_cast<ConstantSDNode>(Ops[0])) {
5517       if (auto *C2 = dyn_cast<ConstantSDNode>(Ops[1])) {
5518         if (C1->isOpaque() || C2->isOpaque())
5519           return SDValue();
5520 
5521         Optional<APInt> FoldAttempt =
5522             FoldValue(Opcode, C1->getAPIntValue(), C2->getAPIntValue());
5523         if (!FoldAttempt)
5524           return SDValue();
5525 
5526         SDValue Folded = getConstant(FoldAttempt.getValue(), DL, VT);
5527         assert((!Folded || !VT.isVector()) &&
5528                "Can't fold vectors ops with scalar operands");
5529         return Folded;
5530       }
5531     }
5532 
5533     // fold (add Sym, c) -> Sym+c
5534     if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ops[0]))
5535       return FoldSymbolOffset(Opcode, VT, GA, Ops[1].getNode());
5536     if (TLI->isCommutativeBinOp(Opcode))
5537       if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ops[1]))
5538         return FoldSymbolOffset(Opcode, VT, GA, Ops[0].getNode());
5539   }
5540 
5541   // This is for vector folding only from here on.
5542   if (!VT.isVector())
5543     return SDValue();
5544 
5545   ElementCount NumElts = VT.getVectorElementCount();
5546 
5547   // See if we can fold through bitcasted integer ops.
5548   // TODO: Can we handle undef elements?
5549   if (NumOps == 2 && VT.isFixedLengthVector() && VT.isInteger() &&
5550       Ops[0].getValueType() == VT && Ops[1].getValueType() == VT &&
5551       Ops[0].getOpcode() == ISD::BITCAST &&
5552       Ops[1].getOpcode() == ISD::BITCAST) {
5553     SDValue N1 = peekThroughBitcasts(Ops[0]);
5554     SDValue N2 = peekThroughBitcasts(Ops[1]);
5555     auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
5556     auto *BV2 = dyn_cast<BuildVectorSDNode>(N2);
5557     EVT BVVT = N1.getValueType();
5558     if (BV1 && BV2 && BVVT.isInteger() && BVVT == N2.getValueType()) {
5559       bool IsLE = getDataLayout().isLittleEndian();
5560       unsigned EltBits = VT.getScalarSizeInBits();
5561       SmallVector<APInt> RawBits1, RawBits2;
5562       BitVector UndefElts1, UndefElts2;
5563       if (BV1->getConstantRawBits(IsLE, EltBits, RawBits1, UndefElts1) &&
5564           BV2->getConstantRawBits(IsLE, EltBits, RawBits2, UndefElts2) &&
5565           UndefElts1.none() && UndefElts2.none()) {
5566         SmallVector<APInt> RawBits;
5567         for (unsigned I = 0, E = NumElts.getFixedValue(); I != E; ++I) {
5568           Optional<APInt> Fold = FoldValue(Opcode, RawBits1[I], RawBits2[I]);
5569           if (!Fold)
5570             break;
5571           RawBits.push_back(Fold.getValue());
5572         }
5573         if (RawBits.size() == NumElts.getFixedValue()) {
5574           // We have constant folded, but we need to cast this again back to
5575           // the original (possibly legalized) type.
5576           SmallVector<APInt> DstBits;
5577           BitVector DstUndefs;
5578           BuildVectorSDNode::recastRawBits(IsLE, BVVT.getScalarSizeInBits(),
5579                                            DstBits, RawBits, DstUndefs,
5580                                            BitVector(RawBits.size(), false));
5581           EVT BVEltVT = BV1->getOperand(0).getValueType();
5582           unsigned BVEltBits = BVEltVT.getSizeInBits();
5583           SmallVector<SDValue> Ops(DstBits.size(), getUNDEF(BVEltVT));
5584           for (unsigned I = 0, E = DstBits.size(); I != E; ++I) {
5585             if (DstUndefs[I])
5586               continue;
5587             Ops[I] = getConstant(DstBits[I].sext(BVEltBits), DL, BVEltVT);
5588           }
5589           return getBitcast(VT, getBuildVector(BVVT, DL, Ops));
5590         }
5591       }
5592     }
5593   }
5594 
5595   // Fold (mul step_vector(C0), C1) to (step_vector(C0 * C1)).
5596   //      (shl step_vector(C0), C1) -> (step_vector(C0 << C1))
5597   if ((Opcode == ISD::MUL || Opcode == ISD::SHL) &&
5598       Ops[0].getOpcode() == ISD::STEP_VECTOR) {
5599     APInt RHSVal;
5600     if (ISD::isConstantSplatVector(Ops[1].getNode(), RHSVal)) {
5601       APInt NewStep = Opcode == ISD::MUL
5602                           ? Ops[0].getConstantOperandAPInt(0) * RHSVal
5603                           : Ops[0].getConstantOperandAPInt(0) << RHSVal;
5604       return getStepVector(DL, VT, NewStep);
5605     }
5606   }
5607 
5608   auto IsScalarOrSameVectorSize = [NumElts](const SDValue &Op) {
5609     return !Op.getValueType().isVector() ||
5610            Op.getValueType().getVectorElementCount() == NumElts;
5611   };
5612 
5613   auto IsBuildVectorSplatVectorOrUndef = [](const SDValue &Op) {
5614     return Op.isUndef() || Op.getOpcode() == ISD::CONDCODE ||
5615            Op.getOpcode() == ISD::BUILD_VECTOR ||
5616            Op.getOpcode() == ISD::SPLAT_VECTOR;
5617   };
5618 
5619   // All operands must be vector types with the same number of elements as
5620   // the result type and must be either UNDEF or a build/splat vector
5621   // or UNDEF scalars.
5622   if (!llvm::all_of(Ops, IsBuildVectorSplatVectorOrUndef) ||
5623       !llvm::all_of(Ops, IsScalarOrSameVectorSize))
5624     return SDValue();
5625 
5626   // If we are comparing vectors, then the result needs to be a i1 boolean that
5627   // is then extended back to the legal result type depending on how booleans
5628   // are represented.
5629   EVT SVT = (Opcode == ISD::SETCC ? MVT::i1 : VT.getScalarType());
5630   ISD::NodeType ExtendCode =
5631       (Opcode == ISD::SETCC && SVT != VT.getScalarType())
5632           ? TargetLowering::getExtendForContent(TLI->getBooleanContents(VT))
5633           : ISD::SIGN_EXTEND;
5634 
5635   // Find legal integer scalar type for constant promotion and
5636   // ensure that its scalar size is at least as large as source.
5637   EVT LegalSVT = VT.getScalarType();
5638   if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
5639     LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
5640     if (LegalSVT.bitsLT(VT.getScalarType()))
5641       return SDValue();
5642   }
5643 
5644   // For scalable vector types we know we're dealing with SPLAT_VECTORs. We
5645   // only have one operand to check. For fixed-length vector types we may have
5646   // a combination of BUILD_VECTOR and SPLAT_VECTOR.
5647   unsigned NumVectorElts = NumElts.isScalable() ? 1 : NumElts.getFixedValue();
5648 
5649   // Constant fold each scalar lane separately.
5650   SmallVector<SDValue, 4> ScalarResults;
5651   for (unsigned I = 0; I != NumVectorElts; I++) {
5652     SmallVector<SDValue, 4> ScalarOps;
5653     for (SDValue Op : Ops) {
5654       EVT InSVT = Op.getValueType().getScalarType();
5655       if (Op.getOpcode() != ISD::BUILD_VECTOR &&
5656           Op.getOpcode() != ISD::SPLAT_VECTOR) {
5657         if (Op.isUndef())
5658           ScalarOps.push_back(getUNDEF(InSVT));
5659         else
5660           ScalarOps.push_back(Op);
5661         continue;
5662       }
5663 
5664       SDValue ScalarOp =
5665           Op.getOperand(Op.getOpcode() == ISD::SPLAT_VECTOR ? 0 : I);
5666       EVT ScalarVT = ScalarOp.getValueType();
5667 
5668       // Build vector (integer) scalar operands may need implicit
5669       // truncation - do this before constant folding.
5670       if (ScalarVT.isInteger() && ScalarVT.bitsGT(InSVT)) {
5671         // Don't create illegally-typed nodes unless they're constants or undef
5672         // - if we fail to constant fold we can't guarantee the (dead) nodes
5673         // we're creating will be cleaned up before being visited for
5674         // legalization.
5675         if (NewNodesMustHaveLegalTypes && !ScalarOp.isUndef() &&
5676             !isa<ConstantSDNode>(ScalarOp) &&
5677             TLI->getTypeAction(*getContext(), InSVT) !=
5678                 TargetLowering::TypeLegal)
5679           return SDValue();
5680         ScalarOp = getNode(ISD::TRUNCATE, DL, InSVT, ScalarOp);
5681       }
5682 
5683       ScalarOps.push_back(ScalarOp);
5684     }
5685 
5686     // Constant fold the scalar operands.
5687     SDValue ScalarResult = getNode(Opcode, DL, SVT, ScalarOps);
5688 
5689     // Legalize the (integer) scalar constant if necessary.
5690     if (LegalSVT != SVT)
5691       ScalarResult = getNode(ExtendCode, DL, LegalSVT, ScalarResult);
5692 
5693     // Scalar folding only succeeded if the result is a constant or UNDEF.
5694     if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant &&
5695         ScalarResult.getOpcode() != ISD::ConstantFP)
5696       return SDValue();
5697     ScalarResults.push_back(ScalarResult);
5698   }
5699 
5700   SDValue V = NumElts.isScalable() ? getSplatVector(VT, DL, ScalarResults[0])
5701                                    : getBuildVector(VT, DL, ScalarResults);
5702   NewSDValueDbgMsg(V, "New node fold constant vector: ", this);
5703   return V;
5704 }
5705 
5706 SDValue SelectionDAG::foldConstantFPMath(unsigned Opcode, const SDLoc &DL,
5707                                          EVT VT, SDValue N1, SDValue N2) {
5708   // TODO: We don't do any constant folding for strict FP opcodes here, but we
5709   //       should. That will require dealing with a potentially non-default
5710   //       rounding mode, checking the "opStatus" return value from the APFloat
5711   //       math calculations, and possibly other variations.
5712   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1, /*AllowUndefs*/ false);
5713   ConstantFPSDNode *N2CFP = isConstOrConstSplatFP(N2, /*AllowUndefs*/ false);
5714   if (N1CFP && N2CFP) {
5715     APFloat C1 = N1CFP->getValueAPF(); // make copy
5716     const APFloat &C2 = N2CFP->getValueAPF();
5717     switch (Opcode) {
5718     case ISD::FADD:
5719       C1.add(C2, APFloat::rmNearestTiesToEven);
5720       return getConstantFP(C1, DL, VT);
5721     case ISD::FSUB:
5722       C1.subtract(C2, APFloat::rmNearestTiesToEven);
5723       return getConstantFP(C1, DL, VT);
5724     case ISD::FMUL:
5725       C1.multiply(C2, APFloat::rmNearestTiesToEven);
5726       return getConstantFP(C1, DL, VT);
5727     case ISD::FDIV:
5728       C1.divide(C2, APFloat::rmNearestTiesToEven);
5729       return getConstantFP(C1, DL, VT);
5730     case ISD::FREM:
5731       C1.mod(C2);
5732       return getConstantFP(C1, DL, VT);
5733     case ISD::FCOPYSIGN:
5734       C1.copySign(C2);
5735       return getConstantFP(C1, DL, VT);
5736     case ISD::FMINNUM:
5737       return getConstantFP(minnum(C1, C2), DL, VT);
5738     case ISD::FMAXNUM:
5739       return getConstantFP(maxnum(C1, C2), DL, VT);
5740     case ISD::FMINIMUM:
5741       return getConstantFP(minimum(C1, C2), DL, VT);
5742     case ISD::FMAXIMUM:
5743       return getConstantFP(maximum(C1, C2), DL, VT);
5744     default: break;
5745     }
5746   }
5747   if (N1CFP && Opcode == ISD::FP_ROUND) {
5748     APFloat C1 = N1CFP->getValueAPF();    // make copy
5749     bool Unused;
5750     // This can return overflow, underflow, or inexact; we don't care.
5751     // FIXME need to be more flexible about rounding mode.
5752     (void) C1.convert(EVTToAPFloatSemantics(VT), APFloat::rmNearestTiesToEven,
5753                       &Unused);
5754     return getConstantFP(C1, DL, VT);
5755   }
5756 
5757   switch (Opcode) {
5758   case ISD::FSUB:
5759     // -0.0 - undef --> undef (consistent with "fneg undef")
5760     if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1, /*AllowUndefs*/ true))
5761       if (N1C && N1C->getValueAPF().isNegZero() && N2.isUndef())
5762         return getUNDEF(VT);
5763     LLVM_FALLTHROUGH;
5764 
5765   case ISD::FADD:
5766   case ISD::FMUL:
5767   case ISD::FDIV:
5768   case ISD::FREM:
5769     // If both operands are undef, the result is undef. If 1 operand is undef,
5770     // the result is NaN. This should match the behavior of the IR optimizer.
5771     if (N1.isUndef() && N2.isUndef())
5772       return getUNDEF(VT);
5773     if (N1.isUndef() || N2.isUndef())
5774       return getConstantFP(APFloat::getNaN(EVTToAPFloatSemantics(VT)), DL, VT);
5775   }
5776   return SDValue();
5777 }
5778 
5779 SDValue SelectionDAG::getAssertAlign(const SDLoc &DL, SDValue Val, Align A) {
5780   assert(Val.getValueType().isInteger() && "Invalid AssertAlign!");
5781 
5782   // There's no need to assert on a byte-aligned pointer. All pointers are at
5783   // least byte aligned.
5784   if (A == Align(1))
5785     return Val;
5786 
5787   FoldingSetNodeID ID;
5788   AddNodeIDNode(ID, ISD::AssertAlign, getVTList(Val.getValueType()), {Val});
5789   ID.AddInteger(A.value());
5790 
5791   void *IP = nullptr;
5792   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
5793     return SDValue(E, 0);
5794 
5795   auto *N = newSDNode<AssertAlignSDNode>(DL.getIROrder(), DL.getDebugLoc(),
5796                                          Val.getValueType(), A);
5797   createOperands(N, {Val});
5798 
5799   CSEMap.InsertNode(N, IP);
5800   InsertNode(N);
5801 
5802   SDValue V(N, 0);
5803   NewSDValueDbgMsg(V, "Creating new node: ", this);
5804   return V;
5805 }
5806 
5807 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5808                               SDValue N1, SDValue N2) {
5809   SDNodeFlags Flags;
5810   if (Inserter)
5811     Flags = Inserter->getFlags();
5812   return getNode(Opcode, DL, VT, N1, N2, Flags);
5813 }
5814 
5815 void SelectionDAG::canonicalizeCommutativeBinop(unsigned Opcode, SDValue &N1,
5816                                                 SDValue &N2) const {
5817   if (!TLI->isCommutativeBinOp(Opcode))
5818     return;
5819 
5820   // Canonicalize:
5821   //   binop(const, nonconst) -> binop(nonconst, const)
5822   bool IsN1C = isConstantIntBuildVectorOrConstantInt(N1);
5823   bool IsN2C = isConstantIntBuildVectorOrConstantInt(N2);
5824   bool IsN1CFP = isConstantFPBuildVectorOrConstantFP(N1);
5825   bool IsN2CFP = isConstantFPBuildVectorOrConstantFP(N2);
5826   if ((IsN1C && !IsN2C) || (IsN1CFP && !IsN2CFP))
5827     std::swap(N1, N2);
5828 
5829   // Canonicalize:
5830   //  binop(splat(x), step_vector) -> binop(step_vector, splat(x))
5831   else if (N1.getOpcode() == ISD::SPLAT_VECTOR &&
5832            N2.getOpcode() == ISD::STEP_VECTOR)
5833     std::swap(N1, N2);
5834 }
5835 
5836 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5837                               SDValue N1, SDValue N2, const SDNodeFlags Flags) {
5838   assert(N1.getOpcode() != ISD::DELETED_NODE &&
5839          N2.getOpcode() != ISD::DELETED_NODE &&
5840          "Operand is DELETED_NODE!");
5841 
5842   canonicalizeCommutativeBinop(Opcode, N1, N2);
5843 
5844   auto *N1C = dyn_cast<ConstantSDNode>(N1);
5845   auto *N2C = dyn_cast<ConstantSDNode>(N2);
5846 
5847   // Don't allow undefs in vector splats - we might be returning N2 when folding
5848   // to zero etc.
5849   ConstantSDNode *N2CV =
5850       isConstOrConstSplat(N2, /*AllowUndefs*/ false, /*AllowTruncation*/ true);
5851 
5852   switch (Opcode) {
5853   default: break;
5854   case ISD::TokenFactor:
5855     assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
5856            N2.getValueType() == MVT::Other && "Invalid token factor!");
5857     // Fold trivial token factors.
5858     if (N1.getOpcode() == ISD::EntryToken) return N2;
5859     if (N2.getOpcode() == ISD::EntryToken) return N1;
5860     if (N1 == N2) return N1;
5861     break;
5862   case ISD::BUILD_VECTOR: {
5863     // Attempt to simplify BUILD_VECTOR.
5864     SDValue Ops[] = {N1, N2};
5865     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
5866       return V;
5867     break;
5868   }
5869   case ISD::CONCAT_VECTORS: {
5870     SDValue Ops[] = {N1, N2};
5871     if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
5872       return V;
5873     break;
5874   }
5875   case ISD::AND:
5876     assert(VT.isInteger() && "This operator does not apply to FP types!");
5877     assert(N1.getValueType() == N2.getValueType() &&
5878            N1.getValueType() == VT && "Binary operator types must match!");
5879     // (X & 0) -> 0.  This commonly occurs when legalizing i64 values, so it's
5880     // worth handling here.
5881     if (N2CV && N2CV->isZero())
5882       return N2;
5883     if (N2CV && N2CV->isAllOnes()) // X & -1 -> X
5884       return N1;
5885     break;
5886   case ISD::OR:
5887   case ISD::XOR:
5888   case ISD::ADD:
5889   case ISD::SUB:
5890     assert(VT.isInteger() && "This operator does not apply to FP types!");
5891     assert(N1.getValueType() == N2.getValueType() &&
5892            N1.getValueType() == VT && "Binary operator types must match!");
5893     // (X ^|+- 0) -> X.  This commonly occurs when legalizing i64 values, so
5894     // it's worth handling here.
5895     if (N2CV && N2CV->isZero())
5896       return N1;
5897     if ((Opcode == ISD::ADD || Opcode == ISD::SUB) && VT.isVector() &&
5898         VT.getVectorElementType() == MVT::i1)
5899       return getNode(ISD::XOR, DL, VT, N1, N2);
5900     break;
5901   case ISD::MUL:
5902     assert(VT.isInteger() && "This operator does not apply to FP types!");
5903     assert(N1.getValueType() == N2.getValueType() &&
5904            N1.getValueType() == VT && "Binary operator types must match!");
5905     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
5906       return getNode(ISD::AND, DL, VT, N1, N2);
5907     if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
5908       const APInt &MulImm = N1->getConstantOperandAPInt(0);
5909       const APInt &N2CImm = N2C->getAPIntValue();
5910       return getVScale(DL, VT, MulImm * N2CImm);
5911     }
5912     break;
5913   case ISD::UDIV:
5914   case ISD::UREM:
5915   case ISD::MULHU:
5916   case ISD::MULHS:
5917   case ISD::SDIV:
5918   case ISD::SREM:
5919   case ISD::SADDSAT:
5920   case ISD::SSUBSAT:
5921   case ISD::UADDSAT:
5922   case ISD::USUBSAT:
5923     assert(VT.isInteger() && "This operator does not apply to FP types!");
5924     assert(N1.getValueType() == N2.getValueType() &&
5925            N1.getValueType() == VT && "Binary operator types must match!");
5926     if (VT.isVector() && VT.getVectorElementType() == MVT::i1) {
5927       // fold (add_sat x, y) -> (or x, y) for bool types.
5928       if (Opcode == ISD::SADDSAT || Opcode == ISD::UADDSAT)
5929         return getNode(ISD::OR, DL, VT, N1, N2);
5930       // fold (sub_sat x, y) -> (and x, ~y) for bool types.
5931       if (Opcode == ISD::SSUBSAT || Opcode == ISD::USUBSAT)
5932         return getNode(ISD::AND, DL, VT, N1, getNOT(DL, N2, VT));
5933     }
5934     break;
5935   case ISD::SMIN:
5936   case ISD::UMAX:
5937     assert(VT.isInteger() && "This operator does not apply to FP types!");
5938     assert(N1.getValueType() == N2.getValueType() &&
5939            N1.getValueType() == VT && "Binary operator types must match!");
5940     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
5941       return getNode(ISD::OR, DL, VT, N1, N2);
5942     break;
5943   case ISD::SMAX:
5944   case ISD::UMIN:
5945     assert(VT.isInteger() && "This operator does not apply to FP types!");
5946     assert(N1.getValueType() == N2.getValueType() &&
5947            N1.getValueType() == VT && "Binary operator types must match!");
5948     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
5949       return getNode(ISD::AND, DL, VT, N1, N2);
5950     break;
5951   case ISD::FADD:
5952   case ISD::FSUB:
5953   case ISD::FMUL:
5954   case ISD::FDIV:
5955   case ISD::FREM:
5956     assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
5957     assert(N1.getValueType() == N2.getValueType() &&
5958            N1.getValueType() == VT && "Binary operator types must match!");
5959     if (SDValue V = simplifyFPBinop(Opcode, N1, N2, Flags))
5960       return V;
5961     break;
5962   case ISD::FCOPYSIGN:   // N1 and result must match.  N1/N2 need not match.
5963     assert(N1.getValueType() == VT &&
5964            N1.getValueType().isFloatingPoint() &&
5965            N2.getValueType().isFloatingPoint() &&
5966            "Invalid FCOPYSIGN!");
5967     break;
5968   case ISD::SHL:
5969     if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
5970       const APInt &MulImm = N1->getConstantOperandAPInt(0);
5971       const APInt &ShiftImm = N2C->getAPIntValue();
5972       return getVScale(DL, VT, MulImm << ShiftImm);
5973     }
5974     LLVM_FALLTHROUGH;
5975   case ISD::SRA:
5976   case ISD::SRL:
5977     if (SDValue V = simplifyShift(N1, N2))
5978       return V;
5979     LLVM_FALLTHROUGH;
5980   case ISD::ROTL:
5981   case ISD::ROTR:
5982     assert(VT == N1.getValueType() &&
5983            "Shift operators return type must be the same as their first arg");
5984     assert(VT.isInteger() && N2.getValueType().isInteger() &&
5985            "Shifts only work on integers");
5986     assert((!VT.isVector() || VT == N2.getValueType()) &&
5987            "Vector shift amounts must be in the same as their first arg");
5988     // Verify that the shift amount VT is big enough to hold valid shift
5989     // amounts.  This catches things like trying to shift an i1024 value by an
5990     // i8, which is easy to fall into in generic code that uses
5991     // TLI.getShiftAmount().
5992     assert(N2.getValueType().getScalarSizeInBits() >=
5993                Log2_32_Ceil(VT.getScalarSizeInBits()) &&
5994            "Invalid use of small shift amount with oversized value!");
5995 
5996     // Always fold shifts of i1 values so the code generator doesn't need to
5997     // handle them.  Since we know the size of the shift has to be less than the
5998     // size of the value, the shift/rotate count is guaranteed to be zero.
5999     if (VT == MVT::i1)
6000       return N1;
6001     if (N2CV && N2CV->isZero())
6002       return N1;
6003     break;
6004   case ISD::FP_ROUND:
6005     assert(VT.isFloatingPoint() &&
6006            N1.getValueType().isFloatingPoint() &&
6007            VT.bitsLE(N1.getValueType()) &&
6008            N2C && (N2C->getZExtValue() == 0 || N2C->getZExtValue() == 1) &&
6009            "Invalid FP_ROUND!");
6010     if (N1.getValueType() == VT) return N1;  // noop conversion.
6011     break;
6012   case ISD::AssertSext:
6013   case ISD::AssertZext: {
6014     EVT EVT = cast<VTSDNode>(N2)->getVT();
6015     assert(VT == N1.getValueType() && "Not an inreg extend!");
6016     assert(VT.isInteger() && EVT.isInteger() &&
6017            "Cannot *_EXTEND_INREG FP types");
6018     assert(!EVT.isVector() &&
6019            "AssertSExt/AssertZExt type should be the vector element type "
6020            "rather than the vector type!");
6021     assert(EVT.bitsLE(VT.getScalarType()) && "Not extending!");
6022     if (VT.getScalarType() == EVT) return N1; // noop assertion.
6023     break;
6024   }
6025   case ISD::SIGN_EXTEND_INREG: {
6026     EVT EVT = cast<VTSDNode>(N2)->getVT();
6027     assert(VT == N1.getValueType() && "Not an inreg extend!");
6028     assert(VT.isInteger() && EVT.isInteger() &&
6029            "Cannot *_EXTEND_INREG FP types");
6030     assert(EVT.isVector() == VT.isVector() &&
6031            "SIGN_EXTEND_INREG type should be vector iff the operand "
6032            "type is vector!");
6033     assert((!EVT.isVector() ||
6034             EVT.getVectorElementCount() == VT.getVectorElementCount()) &&
6035            "Vector element counts must match in SIGN_EXTEND_INREG");
6036     assert(EVT.bitsLE(VT) && "Not extending!");
6037     if (EVT == VT) return N1;  // Not actually extending
6038 
6039     auto SignExtendInReg = [&](APInt Val, llvm::EVT ConstantVT) {
6040       unsigned FromBits = EVT.getScalarSizeInBits();
6041       Val <<= Val.getBitWidth() - FromBits;
6042       Val.ashrInPlace(Val.getBitWidth() - FromBits);
6043       return getConstant(Val, DL, ConstantVT);
6044     };
6045 
6046     if (N1C) {
6047       const APInt &Val = N1C->getAPIntValue();
6048       return SignExtendInReg(Val, VT);
6049     }
6050 
6051     if (ISD::isBuildVectorOfConstantSDNodes(N1.getNode())) {
6052       SmallVector<SDValue, 8> Ops;
6053       llvm::EVT OpVT = N1.getOperand(0).getValueType();
6054       for (int i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
6055         SDValue Op = N1.getOperand(i);
6056         if (Op.isUndef()) {
6057           Ops.push_back(getUNDEF(OpVT));
6058           continue;
6059         }
6060         ConstantSDNode *C = cast<ConstantSDNode>(Op);
6061         APInt Val = C->getAPIntValue();
6062         Ops.push_back(SignExtendInReg(Val, OpVT));
6063       }
6064       return getBuildVector(VT, DL, Ops);
6065     }
6066     break;
6067   }
6068   case ISD::FP_TO_SINT_SAT:
6069   case ISD::FP_TO_UINT_SAT: {
6070     assert(VT.isInteger() && cast<VTSDNode>(N2)->getVT().isInteger() &&
6071            N1.getValueType().isFloatingPoint() && "Invalid FP_TO_*INT_SAT");
6072     assert(N1.getValueType().isVector() == VT.isVector() &&
6073            "FP_TO_*INT_SAT type should be vector iff the operand type is "
6074            "vector!");
6075     assert((!VT.isVector() || VT.getVectorNumElements() ==
6076                                   N1.getValueType().getVectorNumElements()) &&
6077            "Vector element counts must match in FP_TO_*INT_SAT");
6078     assert(!cast<VTSDNode>(N2)->getVT().isVector() &&
6079            "Type to saturate to must be a scalar.");
6080     assert(cast<VTSDNode>(N2)->getVT().bitsLE(VT.getScalarType()) &&
6081            "Not extending!");
6082     break;
6083   }
6084   case ISD::EXTRACT_VECTOR_ELT:
6085     assert(VT.getSizeInBits() >= N1.getValueType().getScalarSizeInBits() &&
6086            "The result of EXTRACT_VECTOR_ELT must be at least as wide as the \
6087              element type of the vector.");
6088 
6089     // Extract from an undefined value or using an undefined index is undefined.
6090     if (N1.isUndef() || N2.isUndef())
6091       return getUNDEF(VT);
6092 
6093     // EXTRACT_VECTOR_ELT of out-of-bounds element is an UNDEF for fixed length
6094     // vectors. For scalable vectors we will provide appropriate support for
6095     // dealing with arbitrary indices.
6096     if (N2C && N1.getValueType().isFixedLengthVector() &&
6097         N2C->getAPIntValue().uge(N1.getValueType().getVectorNumElements()))
6098       return getUNDEF(VT);
6099 
6100     // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
6101     // expanding copies of large vectors from registers. This only works for
6102     // fixed length vectors, since we need to know the exact number of
6103     // elements.
6104     if (N2C && N1.getOperand(0).getValueType().isFixedLengthVector() &&
6105         N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0) {
6106       unsigned Factor =
6107         N1.getOperand(0).getValueType().getVectorNumElements();
6108       return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
6109                      N1.getOperand(N2C->getZExtValue() / Factor),
6110                      getVectorIdxConstant(N2C->getZExtValue() % Factor, DL));
6111     }
6112 
6113     // EXTRACT_VECTOR_ELT of BUILD_VECTOR or SPLAT_VECTOR is often formed while
6114     // lowering is expanding large vector constants.
6115     if (N2C && (N1.getOpcode() == ISD::BUILD_VECTOR ||
6116                 N1.getOpcode() == ISD::SPLAT_VECTOR)) {
6117       assert((N1.getOpcode() != ISD::BUILD_VECTOR ||
6118               N1.getValueType().isFixedLengthVector()) &&
6119              "BUILD_VECTOR used for scalable vectors");
6120       unsigned Index =
6121           N1.getOpcode() == ISD::BUILD_VECTOR ? N2C->getZExtValue() : 0;
6122       SDValue Elt = N1.getOperand(Index);
6123 
6124       if (VT != Elt.getValueType())
6125         // If the vector element type is not legal, the BUILD_VECTOR operands
6126         // are promoted and implicitly truncated, and the result implicitly
6127         // extended. Make that explicit here.
6128         Elt = getAnyExtOrTrunc(Elt, DL, VT);
6129 
6130       return Elt;
6131     }
6132 
6133     // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
6134     // operations are lowered to scalars.
6135     if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) {
6136       // If the indices are the same, return the inserted element else
6137       // if the indices are known different, extract the element from
6138       // the original vector.
6139       SDValue N1Op2 = N1.getOperand(2);
6140       ConstantSDNode *N1Op2C = dyn_cast<ConstantSDNode>(N1Op2);
6141 
6142       if (N1Op2C && N2C) {
6143         if (N1Op2C->getZExtValue() == N2C->getZExtValue()) {
6144           if (VT == N1.getOperand(1).getValueType())
6145             return N1.getOperand(1);
6146           return getSExtOrTrunc(N1.getOperand(1), DL, VT);
6147         }
6148         return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2);
6149       }
6150     }
6151 
6152     // EXTRACT_VECTOR_ELT of v1iX EXTRACT_SUBVECTOR could be formed
6153     // when vector types are scalarized and v1iX is legal.
6154     // vextract (v1iX extract_subvector(vNiX, Idx)) -> vextract(vNiX,Idx).
6155     // Here we are completely ignoring the extract element index (N2),
6156     // which is fine for fixed width vectors, since any index other than 0
6157     // is undefined anyway. However, this cannot be ignored for scalable
6158     // vectors - in theory we could support this, but we don't want to do this
6159     // without a profitability check.
6160     if (N1.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
6161         N1.getValueType().isFixedLengthVector() &&
6162         N1.getValueType().getVectorNumElements() == 1) {
6163       return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0),
6164                      N1.getOperand(1));
6165     }
6166     break;
6167   case ISD::EXTRACT_ELEMENT:
6168     assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!");
6169     assert(!N1.getValueType().isVector() && !VT.isVector() &&
6170            (N1.getValueType().isInteger() == VT.isInteger()) &&
6171            N1.getValueType() != VT &&
6172            "Wrong types for EXTRACT_ELEMENT!");
6173 
6174     // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
6175     // 64-bit integers into 32-bit parts.  Instead of building the extract of
6176     // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
6177     if (N1.getOpcode() == ISD::BUILD_PAIR)
6178       return N1.getOperand(N2C->getZExtValue());
6179 
6180     // EXTRACT_ELEMENT of a constant int is also very common.
6181     if (N1C) {
6182       unsigned ElementSize = VT.getSizeInBits();
6183       unsigned Shift = ElementSize * N2C->getZExtValue();
6184       const APInt &Val = N1C->getAPIntValue();
6185       return getConstant(Val.extractBits(ElementSize, Shift), DL, VT);
6186     }
6187     break;
6188   case ISD::EXTRACT_SUBVECTOR: {
6189     EVT N1VT = N1.getValueType();
6190     assert(VT.isVector() && N1VT.isVector() &&
6191            "Extract subvector VTs must be vectors!");
6192     assert(VT.getVectorElementType() == N1VT.getVectorElementType() &&
6193            "Extract subvector VTs must have the same element type!");
6194     assert((VT.isFixedLengthVector() || N1VT.isScalableVector()) &&
6195            "Cannot extract a scalable vector from a fixed length vector!");
6196     assert((VT.isScalableVector() != N1VT.isScalableVector() ||
6197             VT.getVectorMinNumElements() <= N1VT.getVectorMinNumElements()) &&
6198            "Extract subvector must be from larger vector to smaller vector!");
6199     assert(N2C && "Extract subvector index must be a constant");
6200     assert((VT.isScalableVector() != N1VT.isScalableVector() ||
6201             (VT.getVectorMinNumElements() + N2C->getZExtValue()) <=
6202                 N1VT.getVectorMinNumElements()) &&
6203            "Extract subvector overflow!");
6204     assert(N2C->getAPIntValue().getBitWidth() ==
6205                TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() &&
6206            "Constant index for EXTRACT_SUBVECTOR has an invalid size");
6207 
6208     // Trivial extraction.
6209     if (VT == N1VT)
6210       return N1;
6211 
6212     // EXTRACT_SUBVECTOR of an UNDEF is an UNDEF.
6213     if (N1.isUndef())
6214       return getUNDEF(VT);
6215 
6216     // EXTRACT_SUBVECTOR of CONCAT_VECTOR can be simplified if the pieces of
6217     // the concat have the same type as the extract.
6218     if (N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0 &&
6219         VT == N1.getOperand(0).getValueType()) {
6220       unsigned Factor = VT.getVectorMinNumElements();
6221       return N1.getOperand(N2C->getZExtValue() / Factor);
6222     }
6223 
6224     // EXTRACT_SUBVECTOR of INSERT_SUBVECTOR is often created
6225     // during shuffle legalization.
6226     if (N1.getOpcode() == ISD::INSERT_SUBVECTOR && N2 == N1.getOperand(2) &&
6227         VT == N1.getOperand(1).getValueType())
6228       return N1.getOperand(1);
6229     break;
6230   }
6231   }
6232 
6233   // Perform trivial constant folding.
6234   if (SDValue SV = FoldConstantArithmetic(Opcode, DL, VT, {N1, N2}))
6235     return SV;
6236 
6237   // Canonicalize an UNDEF to the RHS, even over a constant.
6238   if (N1.isUndef()) {
6239     if (TLI->isCommutativeBinOp(Opcode)) {
6240       std::swap(N1, N2);
6241     } else {
6242       switch (Opcode) {
6243       case ISD::SUB:
6244         return getUNDEF(VT);     // fold op(undef, arg2) -> undef
6245       case ISD::SIGN_EXTEND_INREG:
6246       case ISD::UDIV:
6247       case ISD::SDIV:
6248       case ISD::UREM:
6249       case ISD::SREM:
6250       case ISD::SSUBSAT:
6251       case ISD::USUBSAT:
6252         return getConstant(0, DL, VT);    // fold op(undef, arg2) -> 0
6253       }
6254     }
6255   }
6256 
6257   // Fold a bunch of operators when the RHS is undef.
6258   if (N2.isUndef()) {
6259     switch (Opcode) {
6260     case ISD::XOR:
6261       if (N1.isUndef())
6262         // Handle undef ^ undef -> 0 special case. This is a common
6263         // idiom (misuse).
6264         return getConstant(0, DL, VT);
6265       LLVM_FALLTHROUGH;
6266     case ISD::ADD:
6267     case ISD::SUB:
6268     case ISD::UDIV:
6269     case ISD::SDIV:
6270     case ISD::UREM:
6271     case ISD::SREM:
6272       return getUNDEF(VT);       // fold op(arg1, undef) -> undef
6273     case ISD::MUL:
6274     case ISD::AND:
6275     case ISD::SSUBSAT:
6276     case ISD::USUBSAT:
6277       return getConstant(0, DL, VT);  // fold op(arg1, undef) -> 0
6278     case ISD::OR:
6279     case ISD::SADDSAT:
6280     case ISD::UADDSAT:
6281       return getAllOnesConstant(DL, VT);
6282     }
6283   }
6284 
6285   // Memoize this node if possible.
6286   SDNode *N;
6287   SDVTList VTs = getVTList(VT);
6288   SDValue Ops[] = {N1, N2};
6289   if (VT != MVT::Glue) {
6290     FoldingSetNodeID ID;
6291     AddNodeIDNode(ID, Opcode, VTs, Ops);
6292     void *IP = nullptr;
6293     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
6294       E->intersectFlagsWith(Flags);
6295       return SDValue(E, 0);
6296     }
6297 
6298     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6299     N->setFlags(Flags);
6300     createOperands(N, Ops);
6301     CSEMap.InsertNode(N, IP);
6302   } else {
6303     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6304     createOperands(N, Ops);
6305   }
6306 
6307   InsertNode(N);
6308   SDValue V = SDValue(N, 0);
6309   NewSDValueDbgMsg(V, "Creating new node: ", this);
6310   return V;
6311 }
6312 
6313 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6314                               SDValue N1, SDValue N2, SDValue N3) {
6315   SDNodeFlags Flags;
6316   if (Inserter)
6317     Flags = Inserter->getFlags();
6318   return getNode(Opcode, DL, VT, N1, N2, N3, Flags);
6319 }
6320 
6321 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6322                               SDValue N1, SDValue N2, SDValue N3,
6323                               const SDNodeFlags Flags) {
6324   assert(N1.getOpcode() != ISD::DELETED_NODE &&
6325          N2.getOpcode() != ISD::DELETED_NODE &&
6326          N3.getOpcode() != ISD::DELETED_NODE &&
6327          "Operand is DELETED_NODE!");
6328   // Perform various simplifications.
6329   switch (Opcode) {
6330   case ISD::FMA: {
6331     assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
6332     assert(N1.getValueType() == VT && N2.getValueType() == VT &&
6333            N3.getValueType() == VT && "FMA types must match!");
6334     ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6335     ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
6336     ConstantFPSDNode *N3CFP = dyn_cast<ConstantFPSDNode>(N3);
6337     if (N1CFP && N2CFP && N3CFP) {
6338       APFloat  V1 = N1CFP->getValueAPF();
6339       const APFloat &V2 = N2CFP->getValueAPF();
6340       const APFloat &V3 = N3CFP->getValueAPF();
6341       V1.fusedMultiplyAdd(V2, V3, APFloat::rmNearestTiesToEven);
6342       return getConstantFP(V1, DL, VT);
6343     }
6344     break;
6345   }
6346   case ISD::BUILD_VECTOR: {
6347     // Attempt to simplify BUILD_VECTOR.
6348     SDValue Ops[] = {N1, N2, N3};
6349     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
6350       return V;
6351     break;
6352   }
6353   case ISD::CONCAT_VECTORS: {
6354     SDValue Ops[] = {N1, N2, N3};
6355     if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
6356       return V;
6357     break;
6358   }
6359   case ISD::SETCC: {
6360     assert(VT.isInteger() && "SETCC result type must be an integer!");
6361     assert(N1.getValueType() == N2.getValueType() &&
6362            "SETCC operands must have the same type!");
6363     assert(VT.isVector() == N1.getValueType().isVector() &&
6364            "SETCC type should be vector iff the operand type is vector!");
6365     assert((!VT.isVector() || VT.getVectorElementCount() ==
6366                                   N1.getValueType().getVectorElementCount()) &&
6367            "SETCC vector element counts must match!");
6368     // Use FoldSetCC to simplify SETCC's.
6369     if (SDValue V = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL))
6370       return V;
6371     // Vector constant folding.
6372     SDValue Ops[] = {N1, N2, N3};
6373     if (SDValue V = FoldConstantArithmetic(Opcode, DL, VT, Ops)) {
6374       NewSDValueDbgMsg(V, "New node vector constant folding: ", this);
6375       return V;
6376     }
6377     break;
6378   }
6379   case ISD::SELECT:
6380   case ISD::VSELECT:
6381     if (SDValue V = simplifySelect(N1, N2, N3))
6382       return V;
6383     break;
6384   case ISD::VECTOR_SHUFFLE:
6385     llvm_unreachable("should use getVectorShuffle constructor!");
6386   case ISD::VECTOR_SPLICE: {
6387     if (cast<ConstantSDNode>(N3)->isNullValue())
6388       return N1;
6389     break;
6390   }
6391   case ISD::INSERT_VECTOR_ELT: {
6392     ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3);
6393     // INSERT_VECTOR_ELT into out-of-bounds element is an UNDEF, except
6394     // for scalable vectors where we will generate appropriate code to
6395     // deal with out-of-bounds cases correctly.
6396     if (N3C && N1.getValueType().isFixedLengthVector() &&
6397         N3C->getZExtValue() >= N1.getValueType().getVectorNumElements())
6398       return getUNDEF(VT);
6399 
6400     // Undefined index can be assumed out-of-bounds, so that's UNDEF too.
6401     if (N3.isUndef())
6402       return getUNDEF(VT);
6403 
6404     // If the inserted element is an UNDEF, just use the input vector.
6405     if (N2.isUndef())
6406       return N1;
6407 
6408     break;
6409   }
6410   case ISD::INSERT_SUBVECTOR: {
6411     // Inserting undef into undef is still undef.
6412     if (N1.isUndef() && N2.isUndef())
6413       return getUNDEF(VT);
6414 
6415     EVT N2VT = N2.getValueType();
6416     assert(VT == N1.getValueType() &&
6417            "Dest and insert subvector source types must match!");
6418     assert(VT.isVector() && N2VT.isVector() &&
6419            "Insert subvector VTs must be vectors!");
6420     assert((VT.isScalableVector() || N2VT.isFixedLengthVector()) &&
6421            "Cannot insert a scalable vector into a fixed length vector!");
6422     assert((VT.isScalableVector() != N2VT.isScalableVector() ||
6423             VT.getVectorMinNumElements() >= N2VT.getVectorMinNumElements()) &&
6424            "Insert subvector must be from smaller vector to larger vector!");
6425     assert(isa<ConstantSDNode>(N3) &&
6426            "Insert subvector index must be constant");
6427     assert((VT.isScalableVector() != N2VT.isScalableVector() ||
6428             (N2VT.getVectorMinNumElements() +
6429              cast<ConstantSDNode>(N3)->getZExtValue()) <=
6430                 VT.getVectorMinNumElements()) &&
6431            "Insert subvector overflow!");
6432     assert(cast<ConstantSDNode>(N3)->getAPIntValue().getBitWidth() ==
6433                TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() &&
6434            "Constant index for INSERT_SUBVECTOR has an invalid size");
6435 
6436     // Trivial insertion.
6437     if (VT == N2VT)
6438       return N2;
6439 
6440     // If this is an insert of an extracted vector into an undef vector, we
6441     // can just use the input to the extract.
6442     if (N1.isUndef() && N2.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
6443         N2.getOperand(1) == N3 && N2.getOperand(0).getValueType() == VT)
6444       return N2.getOperand(0);
6445     break;
6446   }
6447   case ISD::BITCAST:
6448     // Fold bit_convert nodes from a type to themselves.
6449     if (N1.getValueType() == VT)
6450       return N1;
6451     break;
6452   }
6453 
6454   // Memoize node if it doesn't produce a flag.
6455   SDNode *N;
6456   SDVTList VTs = getVTList(VT);
6457   SDValue Ops[] = {N1, N2, N3};
6458   if (VT != MVT::Glue) {
6459     FoldingSetNodeID ID;
6460     AddNodeIDNode(ID, Opcode, VTs, Ops);
6461     void *IP = nullptr;
6462     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
6463       E->intersectFlagsWith(Flags);
6464       return SDValue(E, 0);
6465     }
6466 
6467     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6468     N->setFlags(Flags);
6469     createOperands(N, Ops);
6470     CSEMap.InsertNode(N, IP);
6471   } else {
6472     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
6473     createOperands(N, Ops);
6474   }
6475 
6476   InsertNode(N);
6477   SDValue V = SDValue(N, 0);
6478   NewSDValueDbgMsg(V, "Creating new node: ", this);
6479   return V;
6480 }
6481 
6482 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6483                               SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
6484   SDValue Ops[] = { N1, N2, N3, N4 };
6485   return getNode(Opcode, DL, VT, Ops);
6486 }
6487 
6488 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
6489                               SDValue N1, SDValue N2, SDValue N3, SDValue N4,
6490                               SDValue N5) {
6491   SDValue Ops[] = { N1, N2, N3, N4, N5 };
6492   return getNode(Opcode, DL, VT, Ops);
6493 }
6494 
6495 /// getStackArgumentTokenFactor - Compute a TokenFactor to force all
6496 /// the incoming stack arguments to be loaded from the stack.
6497 SDValue SelectionDAG::getStackArgumentTokenFactor(SDValue Chain) {
6498   SmallVector<SDValue, 8> ArgChains;
6499 
6500   // Include the original chain at the beginning of the list. When this is
6501   // used by target LowerCall hooks, this helps legalize find the
6502   // CALLSEQ_BEGIN node.
6503   ArgChains.push_back(Chain);
6504 
6505   // Add a chain value for each stack argument.
6506   for (SDNode *U : getEntryNode().getNode()->uses())
6507     if (LoadSDNode *L = dyn_cast<LoadSDNode>(U))
6508       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
6509         if (FI->getIndex() < 0)
6510           ArgChains.push_back(SDValue(L, 1));
6511 
6512   // Build a tokenfactor for all the chains.
6513   return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
6514 }
6515 
6516 /// getMemsetValue - Vectorized representation of the memset value
6517 /// operand.
6518 static SDValue getMemsetValue(SDValue Value, EVT VT, SelectionDAG &DAG,
6519                               const SDLoc &dl) {
6520   assert(!Value.isUndef());
6521 
6522   unsigned NumBits = VT.getScalarSizeInBits();
6523   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
6524     assert(C->getAPIntValue().getBitWidth() == 8);
6525     APInt Val = APInt::getSplat(NumBits, C->getAPIntValue());
6526     if (VT.isInteger()) {
6527       bool IsOpaque = VT.getSizeInBits() > 64 ||
6528           !DAG.getTargetLoweringInfo().isLegalStoreImmediate(C->getSExtValue());
6529       return DAG.getConstant(Val, dl, VT, false, IsOpaque);
6530     }
6531     return DAG.getConstantFP(APFloat(DAG.EVTToAPFloatSemantics(VT), Val), dl,
6532                              VT);
6533   }
6534 
6535   assert(Value.getValueType() == MVT::i8 && "memset with non-byte fill value?");
6536   EVT IntVT = VT.getScalarType();
6537   if (!IntVT.isInteger())
6538     IntVT = EVT::getIntegerVT(*DAG.getContext(), IntVT.getSizeInBits());
6539 
6540   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, Value);
6541   if (NumBits > 8) {
6542     // Use a multiplication with 0x010101... to extend the input to the
6543     // required length.
6544     APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01));
6545     Value = DAG.getNode(ISD::MUL, dl, IntVT, Value,
6546                         DAG.getConstant(Magic, dl, IntVT));
6547   }
6548 
6549   if (VT != Value.getValueType() && !VT.isInteger())
6550     Value = DAG.getBitcast(VT.getScalarType(), Value);
6551   if (VT != Value.getValueType())
6552     Value = DAG.getSplatBuildVector(VT, dl, Value);
6553 
6554   return Value;
6555 }
6556 
6557 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
6558 /// used when a memcpy is turned into a memset when the source is a constant
6559 /// string ptr.
6560 static SDValue getMemsetStringVal(EVT VT, const SDLoc &dl, SelectionDAG &DAG,
6561                                   const TargetLowering &TLI,
6562                                   const ConstantDataArraySlice &Slice) {
6563   // Handle vector with all elements zero.
6564   if (Slice.Array == nullptr) {
6565     if (VT.isInteger())
6566       return DAG.getConstant(0, dl, VT);
6567     if (VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128)
6568       return DAG.getConstantFP(0.0, dl, VT);
6569     if (VT.isVector()) {
6570       unsigned NumElts = VT.getVectorNumElements();
6571       MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
6572       return DAG.getNode(ISD::BITCAST, dl, VT,
6573                          DAG.getConstant(0, dl,
6574                                          EVT::getVectorVT(*DAG.getContext(),
6575                                                           EltVT, NumElts)));
6576     }
6577     llvm_unreachable("Expected type!");
6578   }
6579 
6580   assert(!VT.isVector() && "Can't handle vector type here!");
6581   unsigned NumVTBits = VT.getSizeInBits();
6582   unsigned NumVTBytes = NumVTBits / 8;
6583   unsigned NumBytes = std::min(NumVTBytes, unsigned(Slice.Length));
6584 
6585   APInt Val(NumVTBits, 0);
6586   if (DAG.getDataLayout().isLittleEndian()) {
6587     for (unsigned i = 0; i != NumBytes; ++i)
6588       Val |= (uint64_t)(unsigned char)Slice[i] << i*8;
6589   } else {
6590     for (unsigned i = 0; i != NumBytes; ++i)
6591       Val |= (uint64_t)(unsigned char)Slice[i] << (NumVTBytes-i-1)*8;
6592   }
6593 
6594   // If the "cost" of materializing the integer immediate is less than the cost
6595   // of a load, then it is cost effective to turn the load into the immediate.
6596   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
6597   if (TLI.shouldConvertConstantLoadToIntImm(Val, Ty))
6598     return DAG.getConstant(Val, dl, VT);
6599   return SDValue();
6600 }
6601 
6602 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Base, TypeSize Offset,
6603                                            const SDLoc &DL,
6604                                            const SDNodeFlags Flags) {
6605   EVT VT = Base.getValueType();
6606   SDValue Index;
6607 
6608   if (Offset.isScalable())
6609     Index = getVScale(DL, Base.getValueType(),
6610                       APInt(Base.getValueSizeInBits().getFixedSize(),
6611                             Offset.getKnownMinSize()));
6612   else
6613     Index = getConstant(Offset.getFixedSize(), DL, VT);
6614 
6615   return getMemBasePlusOffset(Base, Index, DL, Flags);
6616 }
6617 
6618 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Ptr, SDValue Offset,
6619                                            const SDLoc &DL,
6620                                            const SDNodeFlags Flags) {
6621   assert(Offset.getValueType().isInteger());
6622   EVT BasePtrVT = Ptr.getValueType();
6623   return getNode(ISD::ADD, DL, BasePtrVT, Ptr, Offset, Flags);
6624 }
6625 
6626 /// Returns true if memcpy source is constant data.
6627 static bool isMemSrcFromConstant(SDValue Src, ConstantDataArraySlice &Slice) {
6628   uint64_t SrcDelta = 0;
6629   GlobalAddressSDNode *G = nullptr;
6630   if (Src.getOpcode() == ISD::GlobalAddress)
6631     G = cast<GlobalAddressSDNode>(Src);
6632   else if (Src.getOpcode() == ISD::ADD &&
6633            Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
6634            Src.getOperand(1).getOpcode() == ISD::Constant) {
6635     G = cast<GlobalAddressSDNode>(Src.getOperand(0));
6636     SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue();
6637   }
6638   if (!G)
6639     return false;
6640 
6641   return getConstantDataArrayInfo(G->getGlobal(), Slice, 8,
6642                                   SrcDelta + G->getOffset());
6643 }
6644 
6645 static bool shouldLowerMemFuncForSize(const MachineFunction &MF,
6646                                       SelectionDAG &DAG) {
6647   // On Darwin, -Os means optimize for size without hurting performance, so
6648   // only really optimize for size when -Oz (MinSize) is used.
6649   if (MF.getTarget().getTargetTriple().isOSDarwin())
6650     return MF.getFunction().hasMinSize();
6651   return DAG.shouldOptForSize();
6652 }
6653 
6654 static void chainLoadsAndStoresForMemcpy(SelectionDAG &DAG, const SDLoc &dl,
6655                           SmallVector<SDValue, 32> &OutChains, unsigned From,
6656                           unsigned To, SmallVector<SDValue, 16> &OutLoadChains,
6657                           SmallVector<SDValue, 16> &OutStoreChains) {
6658   assert(OutLoadChains.size() && "Missing loads in memcpy inlining");
6659   assert(OutStoreChains.size() && "Missing stores in memcpy inlining");
6660   SmallVector<SDValue, 16> GluedLoadChains;
6661   for (unsigned i = From; i < To; ++i) {
6662     OutChains.push_back(OutLoadChains[i]);
6663     GluedLoadChains.push_back(OutLoadChains[i]);
6664   }
6665 
6666   // Chain for all loads.
6667   SDValue LoadToken = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6668                                   GluedLoadChains);
6669 
6670   for (unsigned i = From; i < To; ++i) {
6671     StoreSDNode *ST = dyn_cast<StoreSDNode>(OutStoreChains[i]);
6672     SDValue NewStore = DAG.getTruncStore(LoadToken, dl, ST->getValue(),
6673                                   ST->getBasePtr(), ST->getMemoryVT(),
6674                                   ST->getMemOperand());
6675     OutChains.push_back(NewStore);
6676   }
6677 }
6678 
6679 static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
6680                                        SDValue Chain, SDValue Dst, SDValue Src,
6681                                        uint64_t Size, Align Alignment,
6682                                        bool isVol, bool AlwaysInline,
6683                                        MachinePointerInfo DstPtrInfo,
6684                                        MachinePointerInfo SrcPtrInfo,
6685                                        const AAMDNodes &AAInfo) {
6686   // Turn a memcpy of undef to nop.
6687   // FIXME: We need to honor volatile even is Src is undef.
6688   if (Src.isUndef())
6689     return Chain;
6690 
6691   // Expand memcpy to a series of load and store ops if the size operand falls
6692   // below a certain threshold.
6693   // TODO: In the AlwaysInline case, if the size is big then generate a loop
6694   // rather than maybe a humongous number of loads and stores.
6695   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6696   const DataLayout &DL = DAG.getDataLayout();
6697   LLVMContext &C = *DAG.getContext();
6698   std::vector<EVT> MemOps;
6699   bool DstAlignCanChange = false;
6700   MachineFunction &MF = DAG.getMachineFunction();
6701   MachineFrameInfo &MFI = MF.getFrameInfo();
6702   bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
6703   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
6704   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
6705     DstAlignCanChange = true;
6706   MaybeAlign SrcAlign = DAG.InferPtrAlign(Src);
6707   if (!SrcAlign || Alignment > *SrcAlign)
6708     SrcAlign = Alignment;
6709   assert(SrcAlign && "SrcAlign must be set");
6710   ConstantDataArraySlice Slice;
6711   // If marked as volatile, perform a copy even when marked as constant.
6712   bool CopyFromConstant = !isVol && isMemSrcFromConstant(Src, Slice);
6713   bool isZeroConstant = CopyFromConstant && Slice.Array == nullptr;
6714   unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize);
6715   const MemOp Op = isZeroConstant
6716                        ? MemOp::Set(Size, DstAlignCanChange, Alignment,
6717                                     /*IsZeroMemset*/ true, isVol)
6718                        : MemOp::Copy(Size, DstAlignCanChange, Alignment,
6719                                      *SrcAlign, isVol, CopyFromConstant);
6720   if (!TLI.findOptimalMemOpLowering(
6721           MemOps, Limit, Op, DstPtrInfo.getAddrSpace(),
6722           SrcPtrInfo.getAddrSpace(), MF.getFunction().getAttributes()))
6723     return SDValue();
6724 
6725   if (DstAlignCanChange) {
6726     Type *Ty = MemOps[0].getTypeForEVT(C);
6727     Align NewAlign = DL.getABITypeAlign(Ty);
6728 
6729     // Don't promote to an alignment that would require dynamic stack
6730     // realignment.
6731     const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
6732     if (!TRI->hasStackRealignment(MF))
6733       while (NewAlign > Alignment && DL.exceedsNaturalStackAlignment(NewAlign))
6734         NewAlign = NewAlign / 2;
6735 
6736     if (NewAlign > Alignment) {
6737       // Give the stack frame object a larger alignment if needed.
6738       if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
6739         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
6740       Alignment = NewAlign;
6741     }
6742   }
6743 
6744   // Prepare AAInfo for loads/stores after lowering this memcpy.
6745   AAMDNodes NewAAInfo = AAInfo;
6746   NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
6747 
6748   MachineMemOperand::Flags MMOFlags =
6749       isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
6750   SmallVector<SDValue, 16> OutLoadChains;
6751   SmallVector<SDValue, 16> OutStoreChains;
6752   SmallVector<SDValue, 32> OutChains;
6753   unsigned NumMemOps = MemOps.size();
6754   uint64_t SrcOff = 0, DstOff = 0;
6755   for (unsigned i = 0; i != NumMemOps; ++i) {
6756     EVT VT = MemOps[i];
6757     unsigned VTSize = VT.getSizeInBits() / 8;
6758     SDValue Value, Store;
6759 
6760     if (VTSize > Size) {
6761       // Issuing an unaligned load / store pair  that overlaps with the previous
6762       // pair. Adjust the offset accordingly.
6763       assert(i == NumMemOps-1 && i != 0);
6764       SrcOff -= VTSize - Size;
6765       DstOff -= VTSize - Size;
6766     }
6767 
6768     if (CopyFromConstant &&
6769         (isZeroConstant || (VT.isInteger() && !VT.isVector()))) {
6770       // It's unlikely a store of a vector immediate can be done in a single
6771       // instruction. It would require a load from a constantpool first.
6772       // We only handle zero vectors here.
6773       // FIXME: Handle other cases where store of vector immediate is done in
6774       // a single instruction.
6775       ConstantDataArraySlice SubSlice;
6776       if (SrcOff < Slice.Length) {
6777         SubSlice = Slice;
6778         SubSlice.move(SrcOff);
6779       } else {
6780         // This is an out-of-bounds access and hence UB. Pretend we read zero.
6781         SubSlice.Array = nullptr;
6782         SubSlice.Offset = 0;
6783         SubSlice.Length = VTSize;
6784       }
6785       Value = getMemsetStringVal(VT, dl, DAG, TLI, SubSlice);
6786       if (Value.getNode()) {
6787         Store = DAG.getStore(
6788             Chain, dl, Value,
6789             DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6790             DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo);
6791         OutChains.push_back(Store);
6792       }
6793     }
6794 
6795     if (!Store.getNode()) {
6796       // The type might not be legal for the target.  This should only happen
6797       // if the type is smaller than a legal type, as on PPC, so the right
6798       // thing to do is generate a LoadExt/StoreTrunc pair.  These simplify
6799       // to Load/Store if NVT==VT.
6800       // FIXME does the case above also need this?
6801       EVT NVT = TLI.getTypeToTransformTo(C, VT);
6802       assert(NVT.bitsGE(VT));
6803 
6804       bool isDereferenceable =
6805         SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
6806       MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
6807       if (isDereferenceable)
6808         SrcMMOFlags |= MachineMemOperand::MODereferenceable;
6809 
6810       Value = DAG.getExtLoad(
6811           ISD::EXTLOAD, dl, NVT, Chain,
6812           DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl),
6813           SrcPtrInfo.getWithOffset(SrcOff), VT,
6814           commonAlignment(*SrcAlign, SrcOff), SrcMMOFlags, NewAAInfo);
6815       OutLoadChains.push_back(Value.getValue(1));
6816 
6817       Store = DAG.getTruncStore(
6818           Chain, dl, Value,
6819           DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6820           DstPtrInfo.getWithOffset(DstOff), VT, Alignment, MMOFlags, NewAAInfo);
6821       OutStoreChains.push_back(Store);
6822     }
6823     SrcOff += VTSize;
6824     DstOff += VTSize;
6825     Size -= VTSize;
6826   }
6827 
6828   unsigned GluedLdStLimit = MaxLdStGlue == 0 ?
6829                                 TLI.getMaxGluedStoresPerMemcpy() : MaxLdStGlue;
6830   unsigned NumLdStInMemcpy = OutStoreChains.size();
6831 
6832   if (NumLdStInMemcpy) {
6833     // It may be that memcpy might be converted to memset if it's memcpy
6834     // of constants. In such a case, we won't have loads and stores, but
6835     // just stores. In the absence of loads, there is nothing to gang up.
6836     if ((GluedLdStLimit <= 1) || !EnableMemCpyDAGOpt) {
6837       // If target does not care, just leave as it.
6838       for (unsigned i = 0; i < NumLdStInMemcpy; ++i) {
6839         OutChains.push_back(OutLoadChains[i]);
6840         OutChains.push_back(OutStoreChains[i]);
6841       }
6842     } else {
6843       // Ld/St less than/equal limit set by target.
6844       if (NumLdStInMemcpy <= GluedLdStLimit) {
6845           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
6846                                         NumLdStInMemcpy, OutLoadChains,
6847                                         OutStoreChains);
6848       } else {
6849         unsigned NumberLdChain =  NumLdStInMemcpy / GluedLdStLimit;
6850         unsigned RemainingLdStInMemcpy = NumLdStInMemcpy % GluedLdStLimit;
6851         unsigned GlueIter = 0;
6852 
6853         for (unsigned cnt = 0; cnt < NumberLdChain; ++cnt) {
6854           unsigned IndexFrom = NumLdStInMemcpy - GlueIter - GluedLdStLimit;
6855           unsigned IndexTo   = NumLdStInMemcpy - GlueIter;
6856 
6857           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, IndexFrom, IndexTo,
6858                                        OutLoadChains, OutStoreChains);
6859           GlueIter += GluedLdStLimit;
6860         }
6861 
6862         // Residual ld/st.
6863         if (RemainingLdStInMemcpy) {
6864           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
6865                                         RemainingLdStInMemcpy, OutLoadChains,
6866                                         OutStoreChains);
6867         }
6868       }
6869     }
6870   }
6871   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
6872 }
6873 
6874 static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
6875                                         SDValue Chain, SDValue Dst, SDValue Src,
6876                                         uint64_t Size, Align Alignment,
6877                                         bool isVol, bool AlwaysInline,
6878                                         MachinePointerInfo DstPtrInfo,
6879                                         MachinePointerInfo SrcPtrInfo,
6880                                         const AAMDNodes &AAInfo) {
6881   // Turn a memmove of undef to nop.
6882   // FIXME: We need to honor volatile even is Src is undef.
6883   if (Src.isUndef())
6884     return Chain;
6885 
6886   // Expand memmove to a series of load and store ops if the size operand falls
6887   // below a certain threshold.
6888   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6889   const DataLayout &DL = DAG.getDataLayout();
6890   LLVMContext &C = *DAG.getContext();
6891   std::vector<EVT> MemOps;
6892   bool DstAlignCanChange = false;
6893   MachineFunction &MF = DAG.getMachineFunction();
6894   MachineFrameInfo &MFI = MF.getFrameInfo();
6895   bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
6896   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
6897   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
6898     DstAlignCanChange = true;
6899   MaybeAlign SrcAlign = DAG.InferPtrAlign(Src);
6900   if (!SrcAlign || Alignment > *SrcAlign)
6901     SrcAlign = Alignment;
6902   assert(SrcAlign && "SrcAlign must be set");
6903   unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize);
6904   if (!TLI.findOptimalMemOpLowering(
6905           MemOps, Limit,
6906           MemOp::Copy(Size, DstAlignCanChange, Alignment, *SrcAlign,
6907                       /*IsVolatile*/ true),
6908           DstPtrInfo.getAddrSpace(), SrcPtrInfo.getAddrSpace(),
6909           MF.getFunction().getAttributes()))
6910     return SDValue();
6911 
6912   if (DstAlignCanChange) {
6913     Type *Ty = MemOps[0].getTypeForEVT(C);
6914     Align NewAlign = DL.getABITypeAlign(Ty);
6915     if (NewAlign > Alignment) {
6916       // Give the stack frame object a larger alignment if needed.
6917       if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
6918         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
6919       Alignment = NewAlign;
6920     }
6921   }
6922 
6923   // Prepare AAInfo for loads/stores after lowering this memmove.
6924   AAMDNodes NewAAInfo = AAInfo;
6925   NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
6926 
6927   MachineMemOperand::Flags MMOFlags =
6928       isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
6929   uint64_t SrcOff = 0, DstOff = 0;
6930   SmallVector<SDValue, 8> LoadValues;
6931   SmallVector<SDValue, 8> LoadChains;
6932   SmallVector<SDValue, 8> OutChains;
6933   unsigned NumMemOps = MemOps.size();
6934   for (unsigned i = 0; i < NumMemOps; i++) {
6935     EVT VT = MemOps[i];
6936     unsigned VTSize = VT.getSizeInBits() / 8;
6937     SDValue Value;
6938 
6939     bool isDereferenceable =
6940       SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
6941     MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
6942     if (isDereferenceable)
6943       SrcMMOFlags |= MachineMemOperand::MODereferenceable;
6944 
6945     Value = DAG.getLoad(
6946         VT, dl, Chain,
6947         DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl),
6948         SrcPtrInfo.getWithOffset(SrcOff), *SrcAlign, SrcMMOFlags, NewAAInfo);
6949     LoadValues.push_back(Value);
6950     LoadChains.push_back(Value.getValue(1));
6951     SrcOff += VTSize;
6952   }
6953   Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
6954   OutChains.clear();
6955   for (unsigned i = 0; i < NumMemOps; i++) {
6956     EVT VT = MemOps[i];
6957     unsigned VTSize = VT.getSizeInBits() / 8;
6958     SDValue Store;
6959 
6960     Store = DAG.getStore(
6961         Chain, dl, LoadValues[i],
6962         DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
6963         DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo);
6964     OutChains.push_back(Store);
6965     DstOff += VTSize;
6966   }
6967 
6968   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
6969 }
6970 
6971 /// Lower the call to 'memset' intrinsic function into a series of store
6972 /// operations.
6973 ///
6974 /// \param DAG Selection DAG where lowered code is placed.
6975 /// \param dl Link to corresponding IR location.
6976 /// \param Chain Control flow dependency.
6977 /// \param Dst Pointer to destination memory location.
6978 /// \param Src Value of byte to write into the memory.
6979 /// \param Size Number of bytes to write.
6980 /// \param Alignment Alignment of the destination in bytes.
6981 /// \param isVol True if destination is volatile.
6982 /// \param DstPtrInfo IR information on the memory pointer.
6983 /// \returns New head in the control flow, if lowering was successful, empty
6984 /// SDValue otherwise.
6985 ///
6986 /// The function tries to replace 'llvm.memset' intrinsic with several store
6987 /// operations and value calculation code. This is usually profitable for small
6988 /// memory size.
6989 static SDValue getMemsetStores(SelectionDAG &DAG, const SDLoc &dl,
6990                                SDValue Chain, SDValue Dst, SDValue Src,
6991                                uint64_t Size, Align Alignment, bool isVol,
6992                                MachinePointerInfo DstPtrInfo,
6993                                const AAMDNodes &AAInfo) {
6994   // Turn a memset of undef to nop.
6995   // FIXME: We need to honor volatile even is Src is undef.
6996   if (Src.isUndef())
6997     return Chain;
6998 
6999   // Expand memset to a series of load/store ops if the size operand
7000   // falls below a certain threshold.
7001   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7002   std::vector<EVT> MemOps;
7003   bool DstAlignCanChange = false;
7004   MachineFunction &MF = DAG.getMachineFunction();
7005   MachineFrameInfo &MFI = MF.getFrameInfo();
7006   bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
7007   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
7008   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
7009     DstAlignCanChange = true;
7010   bool IsZeroVal =
7011       isa<ConstantSDNode>(Src) && cast<ConstantSDNode>(Src)->isZero();
7012   if (!TLI.findOptimalMemOpLowering(
7013           MemOps, TLI.getMaxStoresPerMemset(OptSize),
7014           MemOp::Set(Size, DstAlignCanChange, Alignment, IsZeroVal, isVol),
7015           DstPtrInfo.getAddrSpace(), ~0u, MF.getFunction().getAttributes()))
7016     return SDValue();
7017 
7018   if (DstAlignCanChange) {
7019     Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
7020     Align NewAlign = DAG.getDataLayout().getABITypeAlign(Ty);
7021     if (NewAlign > Alignment) {
7022       // Give the stack frame object a larger alignment if needed.
7023       if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
7024         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
7025       Alignment = NewAlign;
7026     }
7027   }
7028 
7029   SmallVector<SDValue, 8> OutChains;
7030   uint64_t DstOff = 0;
7031   unsigned NumMemOps = MemOps.size();
7032 
7033   // Find the largest store and generate the bit pattern for it.
7034   EVT LargestVT = MemOps[0];
7035   for (unsigned i = 1; i < NumMemOps; i++)
7036     if (MemOps[i].bitsGT(LargestVT))
7037       LargestVT = MemOps[i];
7038   SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl);
7039 
7040   // Prepare AAInfo for loads/stores after lowering this memset.
7041   AAMDNodes NewAAInfo = AAInfo;
7042   NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
7043 
7044   for (unsigned i = 0; i < NumMemOps; i++) {
7045     EVT VT = MemOps[i];
7046     unsigned VTSize = VT.getSizeInBits() / 8;
7047     if (VTSize > Size) {
7048       // Issuing an unaligned load / store pair  that overlaps with the previous
7049       // pair. Adjust the offset accordingly.
7050       assert(i == NumMemOps-1 && i != 0);
7051       DstOff -= VTSize - Size;
7052     }
7053 
7054     // If this store is smaller than the largest store see whether we can get
7055     // the smaller value for free with a truncate.
7056     SDValue Value = MemSetValue;
7057     if (VT.bitsLT(LargestVT)) {
7058       if (!LargestVT.isVector() && !VT.isVector() &&
7059           TLI.isTruncateFree(LargestVT, VT))
7060         Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue);
7061       else
7062         Value = getMemsetValue(Src, VT, DAG, dl);
7063     }
7064     assert(Value.getValueType() == VT && "Value with wrong type.");
7065     SDValue Store = DAG.getStore(
7066         Chain, dl, Value,
7067         DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
7068         DstPtrInfo.getWithOffset(DstOff), Alignment,
7069         isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone,
7070         NewAAInfo);
7071     OutChains.push_back(Store);
7072     DstOff += VT.getSizeInBits() / 8;
7073     Size -= VTSize;
7074   }
7075 
7076   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
7077 }
7078 
7079 static void checkAddrSpaceIsValidForLibcall(const TargetLowering *TLI,
7080                                             unsigned AS) {
7081   // Lowering memcpy / memset / memmove intrinsics to calls is only valid if all
7082   // pointer operands can be losslessly bitcasted to pointers of address space 0
7083   if (AS != 0 && !TLI->getTargetMachine().isNoopAddrSpaceCast(AS, 0)) {
7084     report_fatal_error("cannot lower memory intrinsic in address space " +
7085                        Twine(AS));
7086   }
7087 }
7088 
7089 SDValue SelectionDAG::getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst,
7090                                 SDValue Src, SDValue Size, Align Alignment,
7091                                 bool isVol, bool AlwaysInline, bool isTailCall,
7092                                 MachinePointerInfo DstPtrInfo,
7093                                 MachinePointerInfo SrcPtrInfo,
7094                                 const AAMDNodes &AAInfo) {
7095   // Check to see if we should lower the memcpy to loads and stores first.
7096   // For cases within the target-specified limits, this is the best choice.
7097   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
7098   if (ConstantSize) {
7099     // Memcpy with size zero? Just return the original chain.
7100     if (ConstantSize->isZero())
7101       return Chain;
7102 
7103     SDValue Result = getMemcpyLoadsAndStores(
7104         *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment,
7105         isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo);
7106     if (Result.getNode())
7107       return Result;
7108   }
7109 
7110   // Then check to see if we should lower the memcpy with target-specific
7111   // code. If the target chooses to do this, this is the next best.
7112   if (TSI) {
7113     SDValue Result = TSI->EmitTargetCodeForMemcpy(
7114         *this, dl, Chain, Dst, Src, Size, Alignment, isVol, AlwaysInline,
7115         DstPtrInfo, SrcPtrInfo);
7116     if (Result.getNode())
7117       return Result;
7118   }
7119 
7120   // If we really need inline code and the target declined to provide it,
7121   // use a (potentially long) sequence of loads and stores.
7122   if (AlwaysInline) {
7123     assert(ConstantSize && "AlwaysInline requires a constant size!");
7124     return getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
7125                                    ConstantSize->getZExtValue(), Alignment,
7126                                    isVol, true, DstPtrInfo, SrcPtrInfo, AAInfo);
7127   }
7128 
7129   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
7130   checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
7131 
7132   // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc
7133   // memcpy is not guaranteed to be safe. libc memcpys aren't required to
7134   // respect volatile, so they may do things like read or write memory
7135   // beyond the given memory regions. But fixing this isn't easy, and most
7136   // people don't care.
7137 
7138   // Emit a library call.
7139   TargetLowering::ArgListTy Args;
7140   TargetLowering::ArgListEntry Entry;
7141   Entry.Ty = Type::getInt8PtrTy(*getContext());
7142   Entry.Node = Dst; Args.push_back(Entry);
7143   Entry.Node = Src; Args.push_back(Entry);
7144 
7145   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7146   Entry.Node = Size; Args.push_back(Entry);
7147   // FIXME: pass in SDLoc
7148   TargetLowering::CallLoweringInfo CLI(*this);
7149   CLI.setDebugLoc(dl)
7150       .setChain(Chain)
7151       .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMCPY),
7152                     Dst.getValueType().getTypeForEVT(*getContext()),
7153                     getExternalSymbol(TLI->getLibcallName(RTLIB::MEMCPY),
7154                                       TLI->getPointerTy(getDataLayout())),
7155                     std::move(Args))
7156       .setDiscardResult()
7157       .setTailCall(isTailCall);
7158 
7159   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
7160   return CallResult.second;
7161 }
7162 
7163 SDValue SelectionDAG::getAtomicMemcpy(SDValue Chain, const SDLoc &dl,
7164                                       SDValue Dst, unsigned DstAlign,
7165                                       SDValue Src, unsigned SrcAlign,
7166                                       SDValue Size, Type *SizeTy,
7167                                       unsigned ElemSz, bool isTailCall,
7168                                       MachinePointerInfo DstPtrInfo,
7169                                       MachinePointerInfo SrcPtrInfo) {
7170   // Emit a library call.
7171   TargetLowering::ArgListTy Args;
7172   TargetLowering::ArgListEntry Entry;
7173   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7174   Entry.Node = Dst;
7175   Args.push_back(Entry);
7176 
7177   Entry.Node = Src;
7178   Args.push_back(Entry);
7179 
7180   Entry.Ty = SizeTy;
7181   Entry.Node = Size;
7182   Args.push_back(Entry);
7183 
7184   RTLIB::Libcall LibraryCall =
7185       RTLIB::getMEMCPY_ELEMENT_UNORDERED_ATOMIC(ElemSz);
7186   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
7187     report_fatal_error("Unsupported element size");
7188 
7189   TargetLowering::CallLoweringInfo CLI(*this);
7190   CLI.setDebugLoc(dl)
7191       .setChain(Chain)
7192       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
7193                     Type::getVoidTy(*getContext()),
7194                     getExternalSymbol(TLI->getLibcallName(LibraryCall),
7195                                       TLI->getPointerTy(getDataLayout())),
7196                     std::move(Args))
7197       .setDiscardResult()
7198       .setTailCall(isTailCall);
7199 
7200   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
7201   return CallResult.second;
7202 }
7203 
7204 SDValue SelectionDAG::getMemmove(SDValue Chain, const SDLoc &dl, SDValue Dst,
7205                                  SDValue Src, SDValue Size, Align Alignment,
7206                                  bool isVol, bool isTailCall,
7207                                  MachinePointerInfo DstPtrInfo,
7208                                  MachinePointerInfo SrcPtrInfo,
7209                                  const AAMDNodes &AAInfo) {
7210   // Check to see if we should lower the memmove to loads and stores first.
7211   // For cases within the target-specified limits, this is the best choice.
7212   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
7213   if (ConstantSize) {
7214     // Memmove with size zero? Just return the original chain.
7215     if (ConstantSize->isZero())
7216       return Chain;
7217 
7218     SDValue Result = getMemmoveLoadsAndStores(
7219         *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment,
7220         isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo);
7221     if (Result.getNode())
7222       return Result;
7223   }
7224 
7225   // Then check to see if we should lower the memmove with target-specific
7226   // code. If the target chooses to do this, this is the next best.
7227   if (TSI) {
7228     SDValue Result =
7229         TSI->EmitTargetCodeForMemmove(*this, dl, Chain, Dst, Src, Size,
7230                                       Alignment, isVol, DstPtrInfo, SrcPtrInfo);
7231     if (Result.getNode())
7232       return Result;
7233   }
7234 
7235   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
7236   checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
7237 
7238   // FIXME: If the memmove is volatile, lowering it to plain libc memmove may
7239   // not be safe.  See memcpy above for more details.
7240 
7241   // Emit a library call.
7242   TargetLowering::ArgListTy Args;
7243   TargetLowering::ArgListEntry Entry;
7244   Entry.Ty = Type::getInt8PtrTy(*getContext());
7245   Entry.Node = Dst; Args.push_back(Entry);
7246   Entry.Node = Src; Args.push_back(Entry);
7247 
7248   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7249   Entry.Node = Size; Args.push_back(Entry);
7250   // FIXME:  pass in SDLoc
7251   TargetLowering::CallLoweringInfo CLI(*this);
7252   CLI.setDebugLoc(dl)
7253       .setChain(Chain)
7254       .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMMOVE),
7255                     Dst.getValueType().getTypeForEVT(*getContext()),
7256                     getExternalSymbol(TLI->getLibcallName(RTLIB::MEMMOVE),
7257                                       TLI->getPointerTy(getDataLayout())),
7258                     std::move(Args))
7259       .setDiscardResult()
7260       .setTailCall(isTailCall);
7261 
7262   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
7263   return CallResult.second;
7264 }
7265 
7266 SDValue SelectionDAG::getAtomicMemmove(SDValue Chain, const SDLoc &dl,
7267                                        SDValue Dst, unsigned DstAlign,
7268                                        SDValue Src, unsigned SrcAlign,
7269                                        SDValue Size, Type *SizeTy,
7270                                        unsigned ElemSz, bool isTailCall,
7271                                        MachinePointerInfo DstPtrInfo,
7272                                        MachinePointerInfo SrcPtrInfo) {
7273   // Emit a library call.
7274   TargetLowering::ArgListTy Args;
7275   TargetLowering::ArgListEntry Entry;
7276   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7277   Entry.Node = Dst;
7278   Args.push_back(Entry);
7279 
7280   Entry.Node = Src;
7281   Args.push_back(Entry);
7282 
7283   Entry.Ty = SizeTy;
7284   Entry.Node = Size;
7285   Args.push_back(Entry);
7286 
7287   RTLIB::Libcall LibraryCall =
7288       RTLIB::getMEMMOVE_ELEMENT_UNORDERED_ATOMIC(ElemSz);
7289   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
7290     report_fatal_error("Unsupported element size");
7291 
7292   TargetLowering::CallLoweringInfo CLI(*this);
7293   CLI.setDebugLoc(dl)
7294       .setChain(Chain)
7295       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
7296                     Type::getVoidTy(*getContext()),
7297                     getExternalSymbol(TLI->getLibcallName(LibraryCall),
7298                                       TLI->getPointerTy(getDataLayout())),
7299                     std::move(Args))
7300       .setDiscardResult()
7301       .setTailCall(isTailCall);
7302 
7303   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
7304   return CallResult.second;
7305 }
7306 
7307 SDValue SelectionDAG::getMemset(SDValue Chain, const SDLoc &dl, SDValue Dst,
7308                                 SDValue Src, SDValue Size, Align Alignment,
7309                                 bool isVol, bool isTailCall,
7310                                 MachinePointerInfo DstPtrInfo,
7311                                 const AAMDNodes &AAInfo) {
7312   // Check to see if we should lower the memset to stores first.
7313   // For cases within the target-specified limits, this is the best choice.
7314   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
7315   if (ConstantSize) {
7316     // Memset with size zero? Just return the original chain.
7317     if (ConstantSize->isZero())
7318       return Chain;
7319 
7320     SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src,
7321                                      ConstantSize->getZExtValue(), Alignment,
7322                                      isVol, DstPtrInfo, AAInfo);
7323 
7324     if (Result.getNode())
7325       return Result;
7326   }
7327 
7328   // Then check to see if we should lower the memset with target-specific
7329   // code. If the target chooses to do this, this is the next best.
7330   if (TSI) {
7331     SDValue Result = TSI->EmitTargetCodeForMemset(
7332         *this, dl, Chain, Dst, Src, Size, Alignment, isVol, DstPtrInfo);
7333     if (Result.getNode())
7334       return Result;
7335   }
7336 
7337   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
7338 
7339   // Emit a library call.
7340   TargetLowering::ArgListTy Args;
7341   TargetLowering::ArgListEntry Entry;
7342   Entry.Node = Dst; Entry.Ty = Type::getInt8PtrTy(*getContext());
7343   Args.push_back(Entry);
7344   Entry.Node = Src;
7345   Entry.Ty = Src.getValueType().getTypeForEVT(*getContext());
7346   Args.push_back(Entry);
7347   Entry.Node = Size;
7348   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7349   Args.push_back(Entry);
7350 
7351   // FIXME: pass in SDLoc
7352   TargetLowering::CallLoweringInfo CLI(*this);
7353   CLI.setDebugLoc(dl)
7354       .setChain(Chain)
7355       .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMSET),
7356                     Dst.getValueType().getTypeForEVT(*getContext()),
7357                     getExternalSymbol(TLI->getLibcallName(RTLIB::MEMSET),
7358                                       TLI->getPointerTy(getDataLayout())),
7359                     std::move(Args))
7360       .setDiscardResult()
7361       .setTailCall(isTailCall);
7362 
7363   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
7364   return CallResult.second;
7365 }
7366 
7367 SDValue SelectionDAG::getAtomicMemset(SDValue Chain, const SDLoc &dl,
7368                                       SDValue Dst, unsigned DstAlign,
7369                                       SDValue Value, SDValue Size, Type *SizeTy,
7370                                       unsigned ElemSz, bool isTailCall,
7371                                       MachinePointerInfo DstPtrInfo) {
7372   // Emit a library call.
7373   TargetLowering::ArgListTy Args;
7374   TargetLowering::ArgListEntry Entry;
7375   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
7376   Entry.Node = Dst;
7377   Args.push_back(Entry);
7378 
7379   Entry.Ty = Type::getInt8Ty(*getContext());
7380   Entry.Node = Value;
7381   Args.push_back(Entry);
7382 
7383   Entry.Ty = SizeTy;
7384   Entry.Node = Size;
7385   Args.push_back(Entry);
7386 
7387   RTLIB::Libcall LibraryCall =
7388       RTLIB::getMEMSET_ELEMENT_UNORDERED_ATOMIC(ElemSz);
7389   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
7390     report_fatal_error("Unsupported element size");
7391 
7392   TargetLowering::CallLoweringInfo CLI(*this);
7393   CLI.setDebugLoc(dl)
7394       .setChain(Chain)
7395       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
7396                     Type::getVoidTy(*getContext()),
7397                     getExternalSymbol(TLI->getLibcallName(LibraryCall),
7398                                       TLI->getPointerTy(getDataLayout())),
7399                     std::move(Args))
7400       .setDiscardResult()
7401       .setTailCall(isTailCall);
7402 
7403   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
7404   return CallResult.second;
7405 }
7406 
7407 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
7408                                 SDVTList VTList, ArrayRef<SDValue> Ops,
7409                                 MachineMemOperand *MMO) {
7410   FoldingSetNodeID ID;
7411   ID.AddInteger(MemVT.getRawBits());
7412   AddNodeIDNode(ID, Opcode, VTList, Ops);
7413   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7414   ID.AddInteger(MMO->getFlags());
7415   void* IP = nullptr;
7416   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7417     cast<AtomicSDNode>(E)->refineAlignment(MMO);
7418     return SDValue(E, 0);
7419   }
7420 
7421   auto *N = newSDNode<AtomicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
7422                                     VTList, MemVT, MMO);
7423   createOperands(N, Ops);
7424 
7425   CSEMap.InsertNode(N, IP);
7426   InsertNode(N);
7427   return SDValue(N, 0);
7428 }
7429 
7430 SDValue SelectionDAG::getAtomicCmpSwap(unsigned Opcode, const SDLoc &dl,
7431                                        EVT MemVT, SDVTList VTs, SDValue Chain,
7432                                        SDValue Ptr, SDValue Cmp, SDValue Swp,
7433                                        MachineMemOperand *MMO) {
7434   assert(Opcode == ISD::ATOMIC_CMP_SWAP ||
7435          Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
7436   assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
7437 
7438   SDValue Ops[] = {Chain, Ptr, Cmp, Swp};
7439   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
7440 }
7441 
7442 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
7443                                 SDValue Chain, SDValue Ptr, SDValue Val,
7444                                 MachineMemOperand *MMO) {
7445   assert((Opcode == ISD::ATOMIC_LOAD_ADD ||
7446           Opcode == ISD::ATOMIC_LOAD_SUB ||
7447           Opcode == ISD::ATOMIC_LOAD_AND ||
7448           Opcode == ISD::ATOMIC_LOAD_CLR ||
7449           Opcode == ISD::ATOMIC_LOAD_OR ||
7450           Opcode == ISD::ATOMIC_LOAD_XOR ||
7451           Opcode == ISD::ATOMIC_LOAD_NAND ||
7452           Opcode == ISD::ATOMIC_LOAD_MIN ||
7453           Opcode == ISD::ATOMIC_LOAD_MAX ||
7454           Opcode == ISD::ATOMIC_LOAD_UMIN ||
7455           Opcode == ISD::ATOMIC_LOAD_UMAX ||
7456           Opcode == ISD::ATOMIC_LOAD_FADD ||
7457           Opcode == ISD::ATOMIC_LOAD_FSUB ||
7458           Opcode == ISD::ATOMIC_SWAP ||
7459           Opcode == ISD::ATOMIC_STORE) &&
7460          "Invalid Atomic Op");
7461 
7462   EVT VT = Val.getValueType();
7463 
7464   SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) :
7465                                                getVTList(VT, MVT::Other);
7466   SDValue Ops[] = {Chain, Ptr, Val};
7467   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
7468 }
7469 
7470 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
7471                                 EVT VT, SDValue Chain, SDValue Ptr,
7472                                 MachineMemOperand *MMO) {
7473   assert(Opcode == ISD::ATOMIC_LOAD && "Invalid Atomic Op");
7474 
7475   SDVTList VTs = getVTList(VT, MVT::Other);
7476   SDValue Ops[] = {Chain, Ptr};
7477   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
7478 }
7479 
7480 /// getMergeValues - Create a MERGE_VALUES node from the given operands.
7481 SDValue SelectionDAG::getMergeValues(ArrayRef<SDValue> Ops, const SDLoc &dl) {
7482   if (Ops.size() == 1)
7483     return Ops[0];
7484 
7485   SmallVector<EVT, 4> VTs;
7486   VTs.reserve(Ops.size());
7487   for (const SDValue &Op : Ops)
7488     VTs.push_back(Op.getValueType());
7489   return getNode(ISD::MERGE_VALUES, dl, getVTList(VTs), Ops);
7490 }
7491 
7492 SDValue SelectionDAG::getMemIntrinsicNode(
7493     unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef<SDValue> Ops,
7494     EVT MemVT, MachinePointerInfo PtrInfo, Align Alignment,
7495     MachineMemOperand::Flags Flags, uint64_t Size, const AAMDNodes &AAInfo) {
7496   if (!Size && MemVT.isScalableVector())
7497     Size = MemoryLocation::UnknownSize;
7498   else if (!Size)
7499     Size = MemVT.getStoreSize();
7500 
7501   MachineFunction &MF = getMachineFunction();
7502   MachineMemOperand *MMO =
7503       MF.getMachineMemOperand(PtrInfo, Flags, Size, Alignment, AAInfo);
7504 
7505   return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, MMO);
7506 }
7507 
7508 SDValue SelectionDAG::getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl,
7509                                           SDVTList VTList,
7510                                           ArrayRef<SDValue> Ops, EVT MemVT,
7511                                           MachineMemOperand *MMO) {
7512   assert((Opcode == ISD::INTRINSIC_VOID ||
7513           Opcode == ISD::INTRINSIC_W_CHAIN ||
7514           Opcode == ISD::PREFETCH ||
7515           ((int)Opcode <= std::numeric_limits<int>::max() &&
7516            (int)Opcode >= ISD::FIRST_TARGET_MEMORY_OPCODE)) &&
7517          "Opcode is not a memory-accessing opcode!");
7518 
7519   // Memoize the node unless it returns a flag.
7520   MemIntrinsicSDNode *N;
7521   if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
7522     FoldingSetNodeID ID;
7523     AddNodeIDNode(ID, Opcode, VTList, Ops);
7524     ID.AddInteger(getSyntheticNodeSubclassData<MemIntrinsicSDNode>(
7525         Opcode, dl.getIROrder(), VTList, MemVT, MMO));
7526     ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7527     ID.AddInteger(MMO->getFlags());
7528     void *IP = nullptr;
7529     if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7530       cast<MemIntrinsicSDNode>(E)->refineAlignment(MMO);
7531       return SDValue(E, 0);
7532     }
7533 
7534     N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
7535                                       VTList, MemVT, MMO);
7536     createOperands(N, Ops);
7537 
7538   CSEMap.InsertNode(N, IP);
7539   } else {
7540     N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
7541                                       VTList, MemVT, MMO);
7542     createOperands(N, Ops);
7543   }
7544   InsertNode(N);
7545   SDValue V(N, 0);
7546   NewSDValueDbgMsg(V, "Creating new node: ", this);
7547   return V;
7548 }
7549 
7550 SDValue SelectionDAG::getLifetimeNode(bool IsStart, const SDLoc &dl,
7551                                       SDValue Chain, int FrameIndex,
7552                                       int64_t Size, int64_t Offset) {
7553   const unsigned Opcode = IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END;
7554   const auto VTs = getVTList(MVT::Other);
7555   SDValue Ops[2] = {
7556       Chain,
7557       getFrameIndex(FrameIndex,
7558                     getTargetLoweringInfo().getFrameIndexTy(getDataLayout()),
7559                     true)};
7560 
7561   FoldingSetNodeID ID;
7562   AddNodeIDNode(ID, Opcode, VTs, Ops);
7563   ID.AddInteger(FrameIndex);
7564   ID.AddInteger(Size);
7565   ID.AddInteger(Offset);
7566   void *IP = nullptr;
7567   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
7568     return SDValue(E, 0);
7569 
7570   LifetimeSDNode *N = newSDNode<LifetimeSDNode>(
7571       Opcode, dl.getIROrder(), dl.getDebugLoc(), VTs, Size, Offset);
7572   createOperands(N, Ops);
7573   CSEMap.InsertNode(N, IP);
7574   InsertNode(N);
7575   SDValue V(N, 0);
7576   NewSDValueDbgMsg(V, "Creating new node: ", this);
7577   return V;
7578 }
7579 
7580 SDValue SelectionDAG::getPseudoProbeNode(const SDLoc &Dl, SDValue Chain,
7581                                          uint64_t Guid, uint64_t Index,
7582                                          uint32_t Attr) {
7583   const unsigned Opcode = ISD::PSEUDO_PROBE;
7584   const auto VTs = getVTList(MVT::Other);
7585   SDValue Ops[] = {Chain};
7586   FoldingSetNodeID ID;
7587   AddNodeIDNode(ID, Opcode, VTs, Ops);
7588   ID.AddInteger(Guid);
7589   ID.AddInteger(Index);
7590   void *IP = nullptr;
7591   if (SDNode *E = FindNodeOrInsertPos(ID, Dl, IP))
7592     return SDValue(E, 0);
7593 
7594   auto *N = newSDNode<PseudoProbeSDNode>(
7595       Opcode, Dl.getIROrder(), Dl.getDebugLoc(), VTs, Guid, Index, Attr);
7596   createOperands(N, Ops);
7597   CSEMap.InsertNode(N, IP);
7598   InsertNode(N);
7599   SDValue V(N, 0);
7600   NewSDValueDbgMsg(V, "Creating new node: ", this);
7601   return V;
7602 }
7603 
7604 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
7605 /// MachinePointerInfo record from it.  This is particularly useful because the
7606 /// code generator has many cases where it doesn't bother passing in a
7607 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
7608 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info,
7609                                            SelectionDAG &DAG, SDValue Ptr,
7610                                            int64_t Offset = 0) {
7611   // If this is FI+Offset, we can model it.
7612   if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr))
7613     return MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
7614                                              FI->getIndex(), Offset);
7615 
7616   // If this is (FI+Offset1)+Offset2, we can model it.
7617   if (Ptr.getOpcode() != ISD::ADD ||
7618       !isa<ConstantSDNode>(Ptr.getOperand(1)) ||
7619       !isa<FrameIndexSDNode>(Ptr.getOperand(0)))
7620     return Info;
7621 
7622   int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
7623   return MachinePointerInfo::getFixedStack(
7624       DAG.getMachineFunction(), FI,
7625       Offset + cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue());
7626 }
7627 
7628 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
7629 /// MachinePointerInfo record from it.  This is particularly useful because the
7630 /// code generator has many cases where it doesn't bother passing in a
7631 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
7632 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info,
7633                                            SelectionDAG &DAG, SDValue Ptr,
7634                                            SDValue OffsetOp) {
7635   // If the 'Offset' value isn't a constant, we can't handle this.
7636   if (ConstantSDNode *OffsetNode = dyn_cast<ConstantSDNode>(OffsetOp))
7637     return InferPointerInfo(Info, DAG, Ptr, OffsetNode->getSExtValue());
7638   if (OffsetOp.isUndef())
7639     return InferPointerInfo(Info, DAG, Ptr);
7640   return Info;
7641 }
7642 
7643 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
7644                               EVT VT, const SDLoc &dl, SDValue Chain,
7645                               SDValue Ptr, SDValue Offset,
7646                               MachinePointerInfo PtrInfo, EVT MemVT,
7647                               Align Alignment,
7648                               MachineMemOperand::Flags MMOFlags,
7649                               const AAMDNodes &AAInfo, const MDNode *Ranges) {
7650   assert(Chain.getValueType() == MVT::Other &&
7651         "Invalid chain type");
7652 
7653   MMOFlags |= MachineMemOperand::MOLoad;
7654   assert((MMOFlags & MachineMemOperand::MOStore) == 0);
7655   // If we don't have a PtrInfo, infer the trivial frame index case to simplify
7656   // clients.
7657   if (PtrInfo.V.isNull())
7658     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
7659 
7660   uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize());
7661   MachineFunction &MF = getMachineFunction();
7662   MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size,
7663                                                    Alignment, AAInfo, Ranges);
7664   return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO);
7665 }
7666 
7667 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
7668                               EVT VT, const SDLoc &dl, SDValue Chain,
7669                               SDValue Ptr, SDValue Offset, EVT MemVT,
7670                               MachineMemOperand *MMO) {
7671   if (VT == MemVT) {
7672     ExtType = ISD::NON_EXTLOAD;
7673   } else if (ExtType == ISD::NON_EXTLOAD) {
7674     assert(VT == MemVT && "Non-extending load from different memory type!");
7675   } else {
7676     // Extending load.
7677     assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) &&
7678            "Should only be an extending load, not truncating!");
7679     assert(VT.isInteger() == MemVT.isInteger() &&
7680            "Cannot convert from FP to Int or Int -> FP!");
7681     assert(VT.isVector() == MemVT.isVector() &&
7682            "Cannot use an ext load to convert to or from a vector!");
7683     assert((!VT.isVector() ||
7684             VT.getVectorElementCount() == MemVT.getVectorElementCount()) &&
7685            "Cannot use an ext load to change the number of vector elements!");
7686   }
7687 
7688   bool Indexed = AM != ISD::UNINDEXED;
7689   assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
7690 
7691   SDVTList VTs = Indexed ?
7692     getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
7693   SDValue Ops[] = { Chain, Ptr, Offset };
7694   FoldingSetNodeID ID;
7695   AddNodeIDNode(ID, ISD::LOAD, VTs, Ops);
7696   ID.AddInteger(MemVT.getRawBits());
7697   ID.AddInteger(getSyntheticNodeSubclassData<LoadSDNode>(
7698       dl.getIROrder(), VTs, AM, ExtType, MemVT, MMO));
7699   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7700   ID.AddInteger(MMO->getFlags());
7701   void *IP = nullptr;
7702   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7703     cast<LoadSDNode>(E)->refineAlignment(MMO);
7704     return SDValue(E, 0);
7705   }
7706   auto *N = newSDNode<LoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
7707                                   ExtType, MemVT, MMO);
7708   createOperands(N, Ops);
7709 
7710   CSEMap.InsertNode(N, IP);
7711   InsertNode(N);
7712   SDValue V(N, 0);
7713   NewSDValueDbgMsg(V, "Creating new node: ", this);
7714   return V;
7715 }
7716 
7717 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
7718                               SDValue Ptr, MachinePointerInfo PtrInfo,
7719                               MaybeAlign Alignment,
7720                               MachineMemOperand::Flags MMOFlags,
7721                               const AAMDNodes &AAInfo, const MDNode *Ranges) {
7722   SDValue Undef = getUNDEF(Ptr.getValueType());
7723   return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7724                  PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges);
7725 }
7726 
7727 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
7728                               SDValue Ptr, MachineMemOperand *MMO) {
7729   SDValue Undef = getUNDEF(Ptr.getValueType());
7730   return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7731                  VT, MMO);
7732 }
7733 
7734 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
7735                                  EVT VT, SDValue Chain, SDValue Ptr,
7736                                  MachinePointerInfo PtrInfo, EVT MemVT,
7737                                  MaybeAlign Alignment,
7738                                  MachineMemOperand::Flags MMOFlags,
7739                                  const AAMDNodes &AAInfo) {
7740   SDValue Undef = getUNDEF(Ptr.getValueType());
7741   return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, PtrInfo,
7742                  MemVT, Alignment, MMOFlags, AAInfo);
7743 }
7744 
7745 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
7746                                  EVT VT, SDValue Chain, SDValue Ptr, EVT MemVT,
7747                                  MachineMemOperand *MMO) {
7748   SDValue Undef = getUNDEF(Ptr.getValueType());
7749   return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef,
7750                  MemVT, MMO);
7751 }
7752 
7753 SDValue SelectionDAG::getIndexedLoad(SDValue OrigLoad, const SDLoc &dl,
7754                                      SDValue Base, SDValue Offset,
7755                                      ISD::MemIndexedMode AM) {
7756   LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
7757   assert(LD->getOffset().isUndef() && "Load is already a indexed load!");
7758   // Don't propagate the invariant or dereferenceable flags.
7759   auto MMOFlags =
7760       LD->getMemOperand()->getFlags() &
7761       ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
7762   return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
7763                  LD->getChain(), Base, Offset, LD->getPointerInfo(),
7764                  LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo());
7765 }
7766 
7767 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7768                                SDValue Ptr, MachinePointerInfo PtrInfo,
7769                                Align Alignment,
7770                                MachineMemOperand::Flags MMOFlags,
7771                                const AAMDNodes &AAInfo) {
7772   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
7773 
7774   MMOFlags |= MachineMemOperand::MOStore;
7775   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
7776 
7777   if (PtrInfo.V.isNull())
7778     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
7779 
7780   MachineFunction &MF = getMachineFunction();
7781   uint64_t Size =
7782       MemoryLocation::getSizeOrUnknown(Val.getValueType().getStoreSize());
7783   MachineMemOperand *MMO =
7784       MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, Alignment, AAInfo);
7785   return getStore(Chain, dl, Val, Ptr, MMO);
7786 }
7787 
7788 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7789                                SDValue Ptr, MachineMemOperand *MMO) {
7790   assert(Chain.getValueType() == MVT::Other &&
7791         "Invalid chain type");
7792   EVT VT = Val.getValueType();
7793   SDVTList VTs = getVTList(MVT::Other);
7794   SDValue Undef = getUNDEF(Ptr.getValueType());
7795   SDValue Ops[] = { Chain, Val, Ptr, Undef };
7796   FoldingSetNodeID ID;
7797   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7798   ID.AddInteger(VT.getRawBits());
7799   ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
7800       dl.getIROrder(), VTs, ISD::UNINDEXED, false, VT, MMO));
7801   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7802   ID.AddInteger(MMO->getFlags());
7803   void *IP = nullptr;
7804   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7805     cast<StoreSDNode>(E)->refineAlignment(MMO);
7806     return SDValue(E, 0);
7807   }
7808   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7809                                    ISD::UNINDEXED, false, VT, MMO);
7810   createOperands(N, Ops);
7811 
7812   CSEMap.InsertNode(N, IP);
7813   InsertNode(N);
7814   SDValue V(N, 0);
7815   NewSDValueDbgMsg(V, "Creating new node: ", this);
7816   return V;
7817 }
7818 
7819 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7820                                     SDValue Ptr, MachinePointerInfo PtrInfo,
7821                                     EVT SVT, Align Alignment,
7822                                     MachineMemOperand::Flags MMOFlags,
7823                                     const AAMDNodes &AAInfo) {
7824   assert(Chain.getValueType() == MVT::Other &&
7825         "Invalid chain type");
7826 
7827   MMOFlags |= MachineMemOperand::MOStore;
7828   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
7829 
7830   if (PtrInfo.V.isNull())
7831     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
7832 
7833   MachineFunction &MF = getMachineFunction();
7834   MachineMemOperand *MMO = MF.getMachineMemOperand(
7835       PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()),
7836       Alignment, AAInfo);
7837   return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO);
7838 }
7839 
7840 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7841                                     SDValue Ptr, EVT SVT,
7842                                     MachineMemOperand *MMO) {
7843   EVT VT = Val.getValueType();
7844 
7845   assert(Chain.getValueType() == MVT::Other &&
7846         "Invalid chain type");
7847   if (VT == SVT)
7848     return getStore(Chain, dl, Val, Ptr, MMO);
7849 
7850   assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
7851          "Should only be a truncating store, not extending!");
7852   assert(VT.isInteger() == SVT.isInteger() &&
7853          "Can't do FP-INT conversion!");
7854   assert(VT.isVector() == SVT.isVector() &&
7855          "Cannot use trunc store to convert to or from a vector!");
7856   assert((!VT.isVector() ||
7857           VT.getVectorElementCount() == SVT.getVectorElementCount()) &&
7858          "Cannot use trunc store to change the number of vector elements!");
7859 
7860   SDVTList VTs = getVTList(MVT::Other);
7861   SDValue Undef = getUNDEF(Ptr.getValueType());
7862   SDValue Ops[] = { Chain, Val, Ptr, Undef };
7863   FoldingSetNodeID ID;
7864   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7865   ID.AddInteger(SVT.getRawBits());
7866   ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
7867       dl.getIROrder(), VTs, ISD::UNINDEXED, true, SVT, MMO));
7868   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7869   ID.AddInteger(MMO->getFlags());
7870   void *IP = nullptr;
7871   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7872     cast<StoreSDNode>(E)->refineAlignment(MMO);
7873     return SDValue(E, 0);
7874   }
7875   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7876                                    ISD::UNINDEXED, true, SVT, MMO);
7877   createOperands(N, Ops);
7878 
7879   CSEMap.InsertNode(N, IP);
7880   InsertNode(N);
7881   SDValue V(N, 0);
7882   NewSDValueDbgMsg(V, "Creating new node: ", this);
7883   return V;
7884 }
7885 
7886 SDValue SelectionDAG::getIndexedStore(SDValue OrigStore, const SDLoc &dl,
7887                                       SDValue Base, SDValue Offset,
7888                                       ISD::MemIndexedMode AM) {
7889   StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
7890   assert(ST->getOffset().isUndef() && "Store is already a indexed store!");
7891   SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
7892   SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
7893   FoldingSetNodeID ID;
7894   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7895   ID.AddInteger(ST->getMemoryVT().getRawBits());
7896   ID.AddInteger(ST->getRawSubclassData());
7897   ID.AddInteger(ST->getPointerInfo().getAddrSpace());
7898   ID.AddInteger(ST->getMemOperand()->getFlags());
7899   void *IP = nullptr;
7900   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
7901     return SDValue(E, 0);
7902 
7903   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
7904                                    ST->isTruncatingStore(), ST->getMemoryVT(),
7905                                    ST->getMemOperand());
7906   createOperands(N, Ops);
7907 
7908   CSEMap.InsertNode(N, IP);
7909   InsertNode(N);
7910   SDValue V(N, 0);
7911   NewSDValueDbgMsg(V, "Creating new node: ", this);
7912   return V;
7913 }
7914 
7915 SDValue SelectionDAG::getLoadVP(
7916     ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &dl,
7917     SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Mask, SDValue EVL,
7918     MachinePointerInfo PtrInfo, EVT MemVT, Align Alignment,
7919     MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
7920     const MDNode *Ranges, bool IsExpanding) {
7921   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
7922 
7923   MMOFlags |= MachineMemOperand::MOLoad;
7924   assert((MMOFlags & MachineMemOperand::MOStore) == 0);
7925   // If we don't have a PtrInfo, infer the trivial frame index case to simplify
7926   // clients.
7927   if (PtrInfo.V.isNull())
7928     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
7929 
7930   uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize());
7931   MachineFunction &MF = getMachineFunction();
7932   MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size,
7933                                                    Alignment, AAInfo, Ranges);
7934   return getLoadVP(AM, ExtType, VT, dl, Chain, Ptr, Offset, Mask, EVL, MemVT,
7935                    MMO, IsExpanding);
7936 }
7937 
7938 SDValue SelectionDAG::getLoadVP(ISD::MemIndexedMode AM,
7939                                 ISD::LoadExtType ExtType, EVT VT,
7940                                 const SDLoc &dl, SDValue Chain, SDValue Ptr,
7941                                 SDValue Offset, SDValue Mask, SDValue EVL,
7942                                 EVT MemVT, MachineMemOperand *MMO,
7943                                 bool IsExpanding) {
7944   bool Indexed = AM != ISD::UNINDEXED;
7945   assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
7946 
7947   SDVTList VTs = Indexed ? getVTList(VT, Ptr.getValueType(), MVT::Other)
7948                          : getVTList(VT, MVT::Other);
7949   SDValue Ops[] = {Chain, Ptr, Offset, Mask, EVL};
7950   FoldingSetNodeID ID;
7951   AddNodeIDNode(ID, ISD::VP_LOAD, VTs, Ops);
7952   ID.AddInteger(VT.getRawBits());
7953   ID.AddInteger(getSyntheticNodeSubclassData<VPLoadSDNode>(
7954       dl.getIROrder(), VTs, AM, ExtType, IsExpanding, MemVT, MMO));
7955   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7956   ID.AddInteger(MMO->getFlags());
7957   void *IP = nullptr;
7958   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7959     cast<VPLoadSDNode>(E)->refineAlignment(MMO);
7960     return SDValue(E, 0);
7961   }
7962   auto *N = newSDNode<VPLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
7963                                     ExtType, IsExpanding, MemVT, MMO);
7964   createOperands(N, Ops);
7965 
7966   CSEMap.InsertNode(N, IP);
7967   InsertNode(N);
7968   SDValue V(N, 0);
7969   NewSDValueDbgMsg(V, "Creating new node: ", this);
7970   return V;
7971 }
7972 
7973 SDValue SelectionDAG::getLoadVP(EVT VT, const SDLoc &dl, SDValue Chain,
7974                                 SDValue Ptr, SDValue Mask, SDValue EVL,
7975                                 MachinePointerInfo PtrInfo,
7976                                 MaybeAlign Alignment,
7977                                 MachineMemOperand::Flags MMOFlags,
7978                                 const AAMDNodes &AAInfo, const MDNode *Ranges,
7979                                 bool IsExpanding) {
7980   SDValue Undef = getUNDEF(Ptr.getValueType());
7981   return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7982                    Mask, EVL, PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges,
7983                    IsExpanding);
7984 }
7985 
7986 SDValue SelectionDAG::getLoadVP(EVT VT, const SDLoc &dl, SDValue Chain,
7987                                 SDValue Ptr, SDValue Mask, SDValue EVL,
7988                                 MachineMemOperand *MMO, bool IsExpanding) {
7989   SDValue Undef = getUNDEF(Ptr.getValueType());
7990   return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7991                    Mask, EVL, VT, MMO, IsExpanding);
7992 }
7993 
7994 SDValue SelectionDAG::getExtLoadVP(ISD::LoadExtType ExtType, const SDLoc &dl,
7995                                    EVT VT, SDValue Chain, SDValue Ptr,
7996                                    SDValue Mask, SDValue EVL,
7997                                    MachinePointerInfo PtrInfo, EVT MemVT,
7998                                    MaybeAlign Alignment,
7999                                    MachineMemOperand::Flags MMOFlags,
8000                                    const AAMDNodes &AAInfo, bool IsExpanding) {
8001   SDValue Undef = getUNDEF(Ptr.getValueType());
8002   return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask,
8003                    EVL, PtrInfo, MemVT, Alignment, MMOFlags, AAInfo, nullptr,
8004                    IsExpanding);
8005 }
8006 
8007 SDValue SelectionDAG::getExtLoadVP(ISD::LoadExtType ExtType, const SDLoc &dl,
8008                                    EVT VT, SDValue Chain, SDValue Ptr,
8009                                    SDValue Mask, SDValue EVL, EVT MemVT,
8010                                    MachineMemOperand *MMO, bool IsExpanding) {
8011   SDValue Undef = getUNDEF(Ptr.getValueType());
8012   return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask,
8013                    EVL, MemVT, MMO, IsExpanding);
8014 }
8015 
8016 SDValue SelectionDAG::getIndexedLoadVP(SDValue OrigLoad, const SDLoc &dl,
8017                                        SDValue Base, SDValue Offset,
8018                                        ISD::MemIndexedMode AM) {
8019   auto *LD = cast<VPLoadSDNode>(OrigLoad);
8020   assert(LD->getOffset().isUndef() && "Load is already a indexed load!");
8021   // Don't propagate the invariant or dereferenceable flags.
8022   auto MMOFlags =
8023       LD->getMemOperand()->getFlags() &
8024       ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
8025   return getLoadVP(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
8026                    LD->getChain(), Base, Offset, LD->getMask(),
8027                    LD->getVectorLength(), LD->getPointerInfo(),
8028                    LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo(),
8029                    nullptr, LD->isExpandingLoad());
8030 }
8031 
8032 SDValue SelectionDAG::getStoreVP(SDValue Chain, const SDLoc &dl, SDValue Val,
8033                                  SDValue Ptr, SDValue Offset, SDValue Mask,
8034                                  SDValue EVL, EVT MemVT, MachineMemOperand *MMO,
8035                                  ISD::MemIndexedMode AM, bool IsTruncating,
8036                                  bool IsCompressing) {
8037   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
8038   bool Indexed = AM != ISD::UNINDEXED;
8039   assert((Indexed || Offset.isUndef()) && "Unindexed vp_store with an offset!");
8040   SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other)
8041                          : getVTList(MVT::Other);
8042   SDValue Ops[] = {Chain, Val, Ptr, Offset, Mask, EVL};
8043   FoldingSetNodeID ID;
8044   AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
8045   ID.AddInteger(MemVT.getRawBits());
8046   ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>(
8047       dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
8048   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8049   ID.AddInteger(MMO->getFlags());
8050   void *IP = nullptr;
8051   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8052     cast<VPStoreSDNode>(E)->refineAlignment(MMO);
8053     return SDValue(E, 0);
8054   }
8055   auto *N = newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
8056                                      IsTruncating, IsCompressing, MemVT, MMO);
8057   createOperands(N, Ops);
8058 
8059   CSEMap.InsertNode(N, IP);
8060   InsertNode(N);
8061   SDValue V(N, 0);
8062   NewSDValueDbgMsg(V, "Creating new node: ", this);
8063   return V;
8064 }
8065 
8066 SDValue SelectionDAG::getTruncStoreVP(SDValue Chain, const SDLoc &dl,
8067                                       SDValue Val, SDValue Ptr, SDValue Mask,
8068                                       SDValue EVL, MachinePointerInfo PtrInfo,
8069                                       EVT SVT, Align Alignment,
8070                                       MachineMemOperand::Flags MMOFlags,
8071                                       const AAMDNodes &AAInfo,
8072                                       bool IsCompressing) {
8073   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
8074 
8075   MMOFlags |= MachineMemOperand::MOStore;
8076   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
8077 
8078   if (PtrInfo.V.isNull())
8079     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
8080 
8081   MachineFunction &MF = getMachineFunction();
8082   MachineMemOperand *MMO = MF.getMachineMemOperand(
8083       PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()),
8084       Alignment, AAInfo);
8085   return getTruncStoreVP(Chain, dl, Val, Ptr, Mask, EVL, SVT, MMO,
8086                          IsCompressing);
8087 }
8088 
8089 SDValue SelectionDAG::getTruncStoreVP(SDValue Chain, const SDLoc &dl,
8090                                       SDValue Val, SDValue Ptr, SDValue Mask,
8091                                       SDValue EVL, EVT SVT,
8092                                       MachineMemOperand *MMO,
8093                                       bool IsCompressing) {
8094   EVT VT = Val.getValueType();
8095 
8096   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
8097   if (VT == SVT)
8098     return getStoreVP(Chain, dl, Val, Ptr, getUNDEF(Ptr.getValueType()), Mask,
8099                       EVL, VT, MMO, ISD::UNINDEXED,
8100                       /*IsTruncating*/ false, IsCompressing);
8101 
8102   assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
8103          "Should only be a truncating store, not extending!");
8104   assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!");
8105   assert(VT.isVector() == SVT.isVector() &&
8106          "Cannot use trunc store to convert to or from a vector!");
8107   assert((!VT.isVector() ||
8108           VT.getVectorElementCount() == SVT.getVectorElementCount()) &&
8109          "Cannot use trunc store to change the number of vector elements!");
8110 
8111   SDVTList VTs = getVTList(MVT::Other);
8112   SDValue Undef = getUNDEF(Ptr.getValueType());
8113   SDValue Ops[] = {Chain, Val, Ptr, Undef, Mask, EVL};
8114   FoldingSetNodeID ID;
8115   AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
8116   ID.AddInteger(SVT.getRawBits());
8117   ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>(
8118       dl.getIROrder(), VTs, ISD::UNINDEXED, true, IsCompressing, SVT, MMO));
8119   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8120   ID.AddInteger(MMO->getFlags());
8121   void *IP = nullptr;
8122   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8123     cast<VPStoreSDNode>(E)->refineAlignment(MMO);
8124     return SDValue(E, 0);
8125   }
8126   auto *N =
8127       newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
8128                                ISD::UNINDEXED, true, IsCompressing, SVT, MMO);
8129   createOperands(N, Ops);
8130 
8131   CSEMap.InsertNode(N, IP);
8132   InsertNode(N);
8133   SDValue V(N, 0);
8134   NewSDValueDbgMsg(V, "Creating new node: ", this);
8135   return V;
8136 }
8137 
8138 SDValue SelectionDAG::getIndexedStoreVP(SDValue OrigStore, const SDLoc &dl,
8139                                         SDValue Base, SDValue Offset,
8140                                         ISD::MemIndexedMode AM) {
8141   auto *ST = cast<VPStoreSDNode>(OrigStore);
8142   assert(ST->getOffset().isUndef() && "Store is already an indexed store!");
8143   SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
8144   SDValue Ops[] = {ST->getChain(), ST->getValue(), Base,
8145                    Offset,         ST->getMask(),  ST->getVectorLength()};
8146   FoldingSetNodeID ID;
8147   AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
8148   ID.AddInteger(ST->getMemoryVT().getRawBits());
8149   ID.AddInteger(ST->getRawSubclassData());
8150   ID.AddInteger(ST->getPointerInfo().getAddrSpace());
8151   ID.AddInteger(ST->getMemOperand()->getFlags());
8152   void *IP = nullptr;
8153   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
8154     return SDValue(E, 0);
8155 
8156   auto *N = newSDNode<VPStoreSDNode>(
8157       dl.getIROrder(), dl.getDebugLoc(), VTs, AM, ST->isTruncatingStore(),
8158       ST->isCompressingStore(), ST->getMemoryVT(), ST->getMemOperand());
8159   createOperands(N, Ops);
8160 
8161   CSEMap.InsertNode(N, IP);
8162   InsertNode(N);
8163   SDValue V(N, 0);
8164   NewSDValueDbgMsg(V, "Creating new node: ", this);
8165   return V;
8166 }
8167 
8168 SDValue SelectionDAG::getStridedLoadVP(
8169     ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &DL,
8170     SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Stride, SDValue Mask,
8171     SDValue EVL, MachinePointerInfo PtrInfo, EVT MemVT, Align Alignment,
8172     MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
8173     const MDNode *Ranges, bool IsExpanding) {
8174   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
8175 
8176   MMOFlags |= MachineMemOperand::MOLoad;
8177   assert((MMOFlags & MachineMemOperand::MOStore) == 0);
8178   // If we don't have a PtrInfo, infer the trivial frame index case to simplify
8179   // clients.
8180   if (PtrInfo.V.isNull())
8181     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
8182 
8183   uint64_t Size = MemoryLocation::UnknownSize;
8184   MachineFunction &MF = getMachineFunction();
8185   MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size,
8186                                                    Alignment, AAInfo, Ranges);
8187   return getStridedLoadVP(AM, ExtType, VT, DL, Chain, Ptr, Offset, Stride, Mask,
8188                           EVL, MemVT, MMO, IsExpanding);
8189 }
8190 
8191 SDValue SelectionDAG::getStridedLoadVP(
8192     ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &DL,
8193     SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Stride, SDValue Mask,
8194     SDValue EVL, EVT MemVT, MachineMemOperand *MMO, bool IsExpanding) {
8195   bool Indexed = AM != ISD::UNINDEXED;
8196   assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
8197 
8198   SDValue Ops[] = {Chain, Ptr, Offset, Stride, Mask, EVL};
8199   SDVTList VTs = Indexed ? getVTList(VT, Ptr.getValueType(), MVT::Other)
8200                          : getVTList(VT, MVT::Other);
8201   FoldingSetNodeID ID;
8202   AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_LOAD, VTs, Ops);
8203   ID.AddInteger(VT.getRawBits());
8204   ID.AddInteger(getSyntheticNodeSubclassData<VPStridedLoadSDNode>(
8205       DL.getIROrder(), VTs, AM, ExtType, IsExpanding, MemVT, MMO));
8206   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8207 
8208   void *IP = nullptr;
8209   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
8210     cast<VPStridedLoadSDNode>(E)->refineAlignment(MMO);
8211     return SDValue(E, 0);
8212   }
8213 
8214   auto *N =
8215       newSDNode<VPStridedLoadSDNode>(DL.getIROrder(), DL.getDebugLoc(), VTs, AM,
8216                                      ExtType, IsExpanding, MemVT, MMO);
8217   createOperands(N, Ops);
8218   CSEMap.InsertNode(N, IP);
8219   InsertNode(N);
8220   SDValue V(N, 0);
8221   NewSDValueDbgMsg(V, "Creating new node: ", this);
8222   return V;
8223 }
8224 
8225 SDValue SelectionDAG::getStridedLoadVP(
8226     EVT VT, const SDLoc &DL, SDValue Chain, SDValue Ptr, SDValue Stride,
8227     SDValue Mask, SDValue EVL, MachinePointerInfo PtrInfo, MaybeAlign Alignment,
8228     MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
8229     const MDNode *Ranges, bool IsExpanding) {
8230   SDValue Undef = getUNDEF(Ptr.getValueType());
8231   return getStridedLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, DL, Chain, Ptr,
8232                           Undef, Stride, Mask, EVL, PtrInfo, VT, Alignment,
8233                           MMOFlags, AAInfo, Ranges, IsExpanding);
8234 }
8235 
8236 SDValue SelectionDAG::getStridedLoadVP(EVT VT, const SDLoc &DL, SDValue Chain,
8237                                        SDValue Ptr, SDValue Stride,
8238                                        SDValue Mask, SDValue EVL,
8239                                        MachineMemOperand *MMO,
8240                                        bool IsExpanding) {
8241   SDValue Undef = getUNDEF(Ptr.getValueType());
8242   return getStridedLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, DL, Chain, Ptr,
8243                           Undef, Stride, Mask, EVL, VT, MMO, IsExpanding);
8244 }
8245 
8246 SDValue SelectionDAG::getExtStridedLoadVP(
8247     ISD::LoadExtType ExtType, const SDLoc &DL, EVT VT, SDValue Chain,
8248     SDValue Ptr, SDValue Stride, SDValue Mask, SDValue EVL,
8249     MachinePointerInfo PtrInfo, EVT MemVT, MaybeAlign Alignment,
8250     MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
8251     bool IsExpanding) {
8252   SDValue Undef = getUNDEF(Ptr.getValueType());
8253   return getStridedLoadVP(ISD::UNINDEXED, ExtType, VT, DL, Chain, Ptr, Undef,
8254                           Stride, Mask, EVL, PtrInfo, MemVT, Alignment,
8255                           MMOFlags, AAInfo, nullptr, IsExpanding);
8256 }
8257 
8258 SDValue SelectionDAG::getExtStridedLoadVP(
8259     ISD::LoadExtType ExtType, const SDLoc &DL, EVT VT, SDValue Chain,
8260     SDValue Ptr, SDValue Stride, SDValue Mask, SDValue EVL, EVT MemVT,
8261     MachineMemOperand *MMO, bool IsExpanding) {
8262   SDValue Undef = getUNDEF(Ptr.getValueType());
8263   return getStridedLoadVP(ISD::UNINDEXED, ExtType, VT, DL, Chain, Ptr, Undef,
8264                           Stride, Mask, EVL, MemVT, MMO, IsExpanding);
8265 }
8266 
8267 SDValue SelectionDAG::getIndexedStridedLoadVP(SDValue OrigLoad, const SDLoc &DL,
8268                                               SDValue Base, SDValue Offset,
8269                                               ISD::MemIndexedMode AM) {
8270   auto *SLD = cast<VPStridedLoadSDNode>(OrigLoad);
8271   assert(SLD->getOffset().isUndef() &&
8272          "Strided load is already a indexed load!");
8273   // Don't propagate the invariant or dereferenceable flags.
8274   auto MMOFlags =
8275       SLD->getMemOperand()->getFlags() &
8276       ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
8277   return getStridedLoadVP(
8278       AM, SLD->getExtensionType(), OrigLoad.getValueType(), DL, SLD->getChain(),
8279       Base, Offset, SLD->getStride(), SLD->getMask(), SLD->getVectorLength(),
8280       SLD->getPointerInfo(), SLD->getMemoryVT(), SLD->getAlign(), MMOFlags,
8281       SLD->getAAInfo(), nullptr, SLD->isExpandingLoad());
8282 }
8283 
8284 SDValue SelectionDAG::getStridedStoreVP(SDValue Chain, const SDLoc &DL,
8285                                         SDValue Val, SDValue Ptr,
8286                                         SDValue Offset, SDValue Stride,
8287                                         SDValue Mask, SDValue EVL, EVT MemVT,
8288                                         MachineMemOperand *MMO,
8289                                         ISD::MemIndexedMode AM,
8290                                         bool IsTruncating, bool IsCompressing) {
8291   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
8292   bool Indexed = AM != ISD::UNINDEXED;
8293   assert((Indexed || Offset.isUndef()) && "Unindexed vp_store with an offset!");
8294   SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other)
8295                          : getVTList(MVT::Other);
8296   SDValue Ops[] = {Chain, Val, Ptr, Offset, Stride, Mask, EVL};
8297   FoldingSetNodeID ID;
8298   AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_STORE, VTs, Ops);
8299   ID.AddInteger(MemVT.getRawBits());
8300   ID.AddInteger(getSyntheticNodeSubclassData<VPStridedStoreSDNode>(
8301       DL.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
8302   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8303   void *IP = nullptr;
8304   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
8305     cast<VPStridedStoreSDNode>(E)->refineAlignment(MMO);
8306     return SDValue(E, 0);
8307   }
8308   auto *N = newSDNode<VPStridedStoreSDNode>(DL.getIROrder(), DL.getDebugLoc(),
8309                                             VTs, AM, IsTruncating,
8310                                             IsCompressing, MemVT, MMO);
8311   createOperands(N, Ops);
8312 
8313   CSEMap.InsertNode(N, IP);
8314   InsertNode(N);
8315   SDValue V(N, 0);
8316   NewSDValueDbgMsg(V, "Creating new node: ", this);
8317   return V;
8318 }
8319 
8320 SDValue SelectionDAG::getTruncStridedStoreVP(
8321     SDValue Chain, const SDLoc &DL, SDValue Val, SDValue Ptr, SDValue Stride,
8322     SDValue Mask, SDValue EVL, MachinePointerInfo PtrInfo, EVT SVT,
8323     Align Alignment, MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
8324     bool IsCompressing) {
8325   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
8326 
8327   MMOFlags |= MachineMemOperand::MOStore;
8328   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
8329 
8330   if (PtrInfo.V.isNull())
8331     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
8332 
8333   MachineFunction &MF = getMachineFunction();
8334   MachineMemOperand *MMO = MF.getMachineMemOperand(
8335       PtrInfo, MMOFlags, MemoryLocation::UnknownSize, Alignment, AAInfo);
8336   return getTruncStridedStoreVP(Chain, DL, Val, Ptr, Stride, Mask, EVL, SVT,
8337                                 MMO, IsCompressing);
8338 }
8339 
8340 SDValue SelectionDAG::getTruncStridedStoreVP(SDValue Chain, const SDLoc &DL,
8341                                              SDValue Val, SDValue Ptr,
8342                                              SDValue Stride, SDValue Mask,
8343                                              SDValue EVL, EVT SVT,
8344                                              MachineMemOperand *MMO,
8345                                              bool IsCompressing) {
8346   EVT VT = Val.getValueType();
8347 
8348   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
8349   if (VT == SVT)
8350     return getStridedStoreVP(Chain, DL, Val, Ptr, getUNDEF(Ptr.getValueType()),
8351                              Stride, Mask, EVL, VT, MMO, ISD::UNINDEXED,
8352                              /*IsTruncating*/ false, IsCompressing);
8353 
8354   assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
8355          "Should only be a truncating store, not extending!");
8356   assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!");
8357   assert(VT.isVector() == SVT.isVector() &&
8358          "Cannot use trunc store to convert to or from a vector!");
8359   assert((!VT.isVector() ||
8360           VT.getVectorElementCount() == SVT.getVectorElementCount()) &&
8361          "Cannot use trunc store to change the number of vector elements!");
8362 
8363   SDVTList VTs = getVTList(MVT::Other);
8364   SDValue Undef = getUNDEF(Ptr.getValueType());
8365   SDValue Ops[] = {Chain, Val, Ptr, Undef, Stride, Mask, EVL};
8366   FoldingSetNodeID ID;
8367   AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_STORE, VTs, Ops);
8368   ID.AddInteger(SVT.getRawBits());
8369   ID.AddInteger(getSyntheticNodeSubclassData<VPStridedStoreSDNode>(
8370       DL.getIROrder(), VTs, ISD::UNINDEXED, true, IsCompressing, SVT, MMO));
8371   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8372   void *IP = nullptr;
8373   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
8374     cast<VPStridedStoreSDNode>(E)->refineAlignment(MMO);
8375     return SDValue(E, 0);
8376   }
8377   auto *N = newSDNode<VPStridedStoreSDNode>(DL.getIROrder(), DL.getDebugLoc(),
8378                                             VTs, ISD::UNINDEXED, true,
8379                                             IsCompressing, SVT, MMO);
8380   createOperands(N, Ops);
8381 
8382   CSEMap.InsertNode(N, IP);
8383   InsertNode(N);
8384   SDValue V(N, 0);
8385   NewSDValueDbgMsg(V, "Creating new node: ", this);
8386   return V;
8387 }
8388 
8389 SDValue SelectionDAG::getIndexedStridedStoreVP(SDValue OrigStore,
8390                                                const SDLoc &DL, SDValue Base,
8391                                                SDValue Offset,
8392                                                ISD::MemIndexedMode AM) {
8393   auto *SST = cast<VPStridedStoreSDNode>(OrigStore);
8394   assert(SST->getOffset().isUndef() &&
8395          "Strided store is already an indexed store!");
8396   SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
8397   SDValue Ops[] = {
8398       SST->getChain(), SST->getValue(),       Base, Offset, SST->getStride(),
8399       SST->getMask(),  SST->getVectorLength()};
8400   FoldingSetNodeID ID;
8401   AddNodeIDNode(ID, ISD::EXPERIMENTAL_VP_STRIDED_STORE, VTs, Ops);
8402   ID.AddInteger(SST->getMemoryVT().getRawBits());
8403   ID.AddInteger(SST->getRawSubclassData());
8404   ID.AddInteger(SST->getPointerInfo().getAddrSpace());
8405   void *IP = nullptr;
8406   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
8407     return SDValue(E, 0);
8408 
8409   auto *N = newSDNode<VPStridedStoreSDNode>(
8410       DL.getIROrder(), DL.getDebugLoc(), VTs, AM, SST->isTruncatingStore(),
8411       SST->isCompressingStore(), SST->getMemoryVT(), SST->getMemOperand());
8412   createOperands(N, Ops);
8413 
8414   CSEMap.InsertNode(N, IP);
8415   InsertNode(N);
8416   SDValue V(N, 0);
8417   NewSDValueDbgMsg(V, "Creating new node: ", this);
8418   return V;
8419 }
8420 
8421 SDValue SelectionDAG::getGatherVP(SDVTList VTs, EVT VT, const SDLoc &dl,
8422                                   ArrayRef<SDValue> Ops, MachineMemOperand *MMO,
8423                                   ISD::MemIndexType IndexType) {
8424   assert(Ops.size() == 6 && "Incompatible number of operands");
8425 
8426   FoldingSetNodeID ID;
8427   AddNodeIDNode(ID, ISD::VP_GATHER, VTs, Ops);
8428   ID.AddInteger(VT.getRawBits());
8429   ID.AddInteger(getSyntheticNodeSubclassData<VPGatherSDNode>(
8430       dl.getIROrder(), VTs, VT, MMO, IndexType));
8431   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8432   ID.AddInteger(MMO->getFlags());
8433   void *IP = nullptr;
8434   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8435     cast<VPGatherSDNode>(E)->refineAlignment(MMO);
8436     return SDValue(E, 0);
8437   }
8438 
8439   auto *N = newSDNode<VPGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
8440                                       VT, MMO, IndexType);
8441   createOperands(N, Ops);
8442 
8443   assert(N->getMask().getValueType().getVectorElementCount() ==
8444              N->getValueType(0).getVectorElementCount() &&
8445          "Vector width mismatch between mask and data");
8446   assert(N->getIndex().getValueType().getVectorElementCount().isScalable() ==
8447              N->getValueType(0).getVectorElementCount().isScalable() &&
8448          "Scalable flags of index and data do not match");
8449   assert(ElementCount::isKnownGE(
8450              N->getIndex().getValueType().getVectorElementCount(),
8451              N->getValueType(0).getVectorElementCount()) &&
8452          "Vector width mismatch between index and data");
8453   assert(isa<ConstantSDNode>(N->getScale()) &&
8454          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
8455          "Scale should be a constant power of 2");
8456 
8457   CSEMap.InsertNode(N, IP);
8458   InsertNode(N);
8459   SDValue V(N, 0);
8460   NewSDValueDbgMsg(V, "Creating new node: ", this);
8461   return V;
8462 }
8463 
8464 SDValue SelectionDAG::getScatterVP(SDVTList VTs, EVT VT, const SDLoc &dl,
8465                                    ArrayRef<SDValue> Ops,
8466                                    MachineMemOperand *MMO,
8467                                    ISD::MemIndexType IndexType) {
8468   assert(Ops.size() == 7 && "Incompatible number of operands");
8469 
8470   FoldingSetNodeID ID;
8471   AddNodeIDNode(ID, ISD::VP_SCATTER, VTs, Ops);
8472   ID.AddInteger(VT.getRawBits());
8473   ID.AddInteger(getSyntheticNodeSubclassData<VPScatterSDNode>(
8474       dl.getIROrder(), VTs, VT, MMO, IndexType));
8475   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8476   ID.AddInteger(MMO->getFlags());
8477   void *IP = nullptr;
8478   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8479     cast<VPScatterSDNode>(E)->refineAlignment(MMO);
8480     return SDValue(E, 0);
8481   }
8482   auto *N = newSDNode<VPScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
8483                                        VT, MMO, IndexType);
8484   createOperands(N, Ops);
8485 
8486   assert(N->getMask().getValueType().getVectorElementCount() ==
8487              N->getValue().getValueType().getVectorElementCount() &&
8488          "Vector width mismatch between mask and data");
8489   assert(
8490       N->getIndex().getValueType().getVectorElementCount().isScalable() ==
8491           N->getValue().getValueType().getVectorElementCount().isScalable() &&
8492       "Scalable flags of index and data do not match");
8493   assert(ElementCount::isKnownGE(
8494              N->getIndex().getValueType().getVectorElementCount(),
8495              N->getValue().getValueType().getVectorElementCount()) &&
8496          "Vector width mismatch between index and data");
8497   assert(isa<ConstantSDNode>(N->getScale()) &&
8498          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
8499          "Scale should be a constant power of 2");
8500 
8501   CSEMap.InsertNode(N, IP);
8502   InsertNode(N);
8503   SDValue V(N, 0);
8504   NewSDValueDbgMsg(V, "Creating new node: ", this);
8505   return V;
8506 }
8507 
8508 SDValue SelectionDAG::getMaskedLoad(EVT VT, const SDLoc &dl, SDValue Chain,
8509                                     SDValue Base, SDValue Offset, SDValue Mask,
8510                                     SDValue PassThru, EVT MemVT,
8511                                     MachineMemOperand *MMO,
8512                                     ISD::MemIndexedMode AM,
8513                                     ISD::LoadExtType ExtTy, bool isExpanding) {
8514   bool Indexed = AM != ISD::UNINDEXED;
8515   assert((Indexed || Offset.isUndef()) &&
8516          "Unindexed masked load with an offset!");
8517   SDVTList VTs = Indexed ? getVTList(VT, Base.getValueType(), MVT::Other)
8518                          : getVTList(VT, MVT::Other);
8519   SDValue Ops[] = {Chain, Base, Offset, Mask, PassThru};
8520   FoldingSetNodeID ID;
8521   AddNodeIDNode(ID, ISD::MLOAD, VTs, Ops);
8522   ID.AddInteger(MemVT.getRawBits());
8523   ID.AddInteger(getSyntheticNodeSubclassData<MaskedLoadSDNode>(
8524       dl.getIROrder(), VTs, AM, ExtTy, isExpanding, MemVT, MMO));
8525   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8526   ID.AddInteger(MMO->getFlags());
8527   void *IP = nullptr;
8528   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8529     cast<MaskedLoadSDNode>(E)->refineAlignment(MMO);
8530     return SDValue(E, 0);
8531   }
8532   auto *N = newSDNode<MaskedLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
8533                                         AM, ExtTy, isExpanding, MemVT, MMO);
8534   createOperands(N, Ops);
8535 
8536   CSEMap.InsertNode(N, IP);
8537   InsertNode(N);
8538   SDValue V(N, 0);
8539   NewSDValueDbgMsg(V, "Creating new node: ", this);
8540   return V;
8541 }
8542 
8543 SDValue SelectionDAG::getIndexedMaskedLoad(SDValue OrigLoad, const SDLoc &dl,
8544                                            SDValue Base, SDValue Offset,
8545                                            ISD::MemIndexedMode AM) {
8546   MaskedLoadSDNode *LD = cast<MaskedLoadSDNode>(OrigLoad);
8547   assert(LD->getOffset().isUndef() && "Masked load is already a indexed load!");
8548   return getMaskedLoad(OrigLoad.getValueType(), dl, LD->getChain(), Base,
8549                        Offset, LD->getMask(), LD->getPassThru(),
8550                        LD->getMemoryVT(), LD->getMemOperand(), AM,
8551                        LD->getExtensionType(), LD->isExpandingLoad());
8552 }
8553 
8554 SDValue SelectionDAG::getMaskedStore(SDValue Chain, const SDLoc &dl,
8555                                      SDValue Val, SDValue Base, SDValue Offset,
8556                                      SDValue Mask, EVT MemVT,
8557                                      MachineMemOperand *MMO,
8558                                      ISD::MemIndexedMode AM, bool IsTruncating,
8559                                      bool IsCompressing) {
8560   assert(Chain.getValueType() == MVT::Other &&
8561         "Invalid chain type");
8562   bool Indexed = AM != ISD::UNINDEXED;
8563   assert((Indexed || Offset.isUndef()) &&
8564          "Unindexed masked store with an offset!");
8565   SDVTList VTs = Indexed ? getVTList(Base.getValueType(), MVT::Other)
8566                          : getVTList(MVT::Other);
8567   SDValue Ops[] = {Chain, Val, Base, Offset, Mask};
8568   FoldingSetNodeID ID;
8569   AddNodeIDNode(ID, ISD::MSTORE, VTs, Ops);
8570   ID.AddInteger(MemVT.getRawBits());
8571   ID.AddInteger(getSyntheticNodeSubclassData<MaskedStoreSDNode>(
8572       dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
8573   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8574   ID.AddInteger(MMO->getFlags());
8575   void *IP = nullptr;
8576   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8577     cast<MaskedStoreSDNode>(E)->refineAlignment(MMO);
8578     return SDValue(E, 0);
8579   }
8580   auto *N =
8581       newSDNode<MaskedStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
8582                                    IsTruncating, IsCompressing, MemVT, MMO);
8583   createOperands(N, Ops);
8584 
8585   CSEMap.InsertNode(N, IP);
8586   InsertNode(N);
8587   SDValue V(N, 0);
8588   NewSDValueDbgMsg(V, "Creating new node: ", this);
8589   return V;
8590 }
8591 
8592 SDValue SelectionDAG::getIndexedMaskedStore(SDValue OrigStore, const SDLoc &dl,
8593                                             SDValue Base, SDValue Offset,
8594                                             ISD::MemIndexedMode AM) {
8595   MaskedStoreSDNode *ST = cast<MaskedStoreSDNode>(OrigStore);
8596   assert(ST->getOffset().isUndef() &&
8597          "Masked store is already a indexed store!");
8598   return getMaskedStore(ST->getChain(), dl, ST->getValue(), Base, Offset,
8599                         ST->getMask(), ST->getMemoryVT(), ST->getMemOperand(),
8600                         AM, ST->isTruncatingStore(), ST->isCompressingStore());
8601 }
8602 
8603 SDValue SelectionDAG::getMaskedGather(SDVTList VTs, EVT MemVT, const SDLoc &dl,
8604                                       ArrayRef<SDValue> Ops,
8605                                       MachineMemOperand *MMO,
8606                                       ISD::MemIndexType IndexType,
8607                                       ISD::LoadExtType ExtTy) {
8608   assert(Ops.size() == 6 && "Incompatible number of operands");
8609 
8610   FoldingSetNodeID ID;
8611   AddNodeIDNode(ID, ISD::MGATHER, VTs, Ops);
8612   ID.AddInteger(MemVT.getRawBits());
8613   ID.AddInteger(getSyntheticNodeSubclassData<MaskedGatherSDNode>(
8614       dl.getIROrder(), VTs, MemVT, MMO, IndexType, ExtTy));
8615   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8616   ID.AddInteger(MMO->getFlags());
8617   void *IP = nullptr;
8618   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8619     cast<MaskedGatherSDNode>(E)->refineAlignment(MMO);
8620     return SDValue(E, 0);
8621   }
8622 
8623   auto *N = newSDNode<MaskedGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(),
8624                                           VTs, MemVT, MMO, IndexType, ExtTy);
8625   createOperands(N, Ops);
8626 
8627   assert(N->getPassThru().getValueType() == N->getValueType(0) &&
8628          "Incompatible type of the PassThru value in MaskedGatherSDNode");
8629   assert(N->getMask().getValueType().getVectorElementCount() ==
8630              N->getValueType(0).getVectorElementCount() &&
8631          "Vector width mismatch between mask and data");
8632   assert(N->getIndex().getValueType().getVectorElementCount().isScalable() ==
8633              N->getValueType(0).getVectorElementCount().isScalable() &&
8634          "Scalable flags of index and data do not match");
8635   assert(ElementCount::isKnownGE(
8636              N->getIndex().getValueType().getVectorElementCount(),
8637              N->getValueType(0).getVectorElementCount()) &&
8638          "Vector width mismatch between index and data");
8639   assert(isa<ConstantSDNode>(N->getScale()) &&
8640          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
8641          "Scale should be a constant power of 2");
8642 
8643   CSEMap.InsertNode(N, IP);
8644   InsertNode(N);
8645   SDValue V(N, 0);
8646   NewSDValueDbgMsg(V, "Creating new node: ", this);
8647   return V;
8648 }
8649 
8650 SDValue SelectionDAG::getMaskedScatter(SDVTList VTs, EVT MemVT, const SDLoc &dl,
8651                                        ArrayRef<SDValue> Ops,
8652                                        MachineMemOperand *MMO,
8653                                        ISD::MemIndexType IndexType,
8654                                        bool IsTrunc) {
8655   assert(Ops.size() == 6 && "Incompatible number of operands");
8656 
8657   FoldingSetNodeID ID;
8658   AddNodeIDNode(ID, ISD::MSCATTER, VTs, Ops);
8659   ID.AddInteger(MemVT.getRawBits());
8660   ID.AddInteger(getSyntheticNodeSubclassData<MaskedScatterSDNode>(
8661       dl.getIROrder(), VTs, MemVT, MMO, IndexType, IsTrunc));
8662   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
8663   ID.AddInteger(MMO->getFlags());
8664   void *IP = nullptr;
8665   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
8666     cast<MaskedScatterSDNode>(E)->refineAlignment(MMO);
8667     return SDValue(E, 0);
8668   }
8669 
8670   auto *N = newSDNode<MaskedScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(),
8671                                            VTs, MemVT, MMO, IndexType, IsTrunc);
8672   createOperands(N, Ops);
8673 
8674   assert(N->getMask().getValueType().getVectorElementCount() ==
8675              N->getValue().getValueType().getVectorElementCount() &&
8676          "Vector width mismatch between mask and data");
8677   assert(
8678       N->getIndex().getValueType().getVectorElementCount().isScalable() ==
8679           N->getValue().getValueType().getVectorElementCount().isScalable() &&
8680       "Scalable flags of index and data do not match");
8681   assert(ElementCount::isKnownGE(
8682              N->getIndex().getValueType().getVectorElementCount(),
8683              N->getValue().getValueType().getVectorElementCount()) &&
8684          "Vector width mismatch between index and data");
8685   assert(isa<ConstantSDNode>(N->getScale()) &&
8686          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
8687          "Scale should be a constant power of 2");
8688 
8689   CSEMap.InsertNode(N, IP);
8690   InsertNode(N);
8691   SDValue V(N, 0);
8692   NewSDValueDbgMsg(V, "Creating new node: ", this);
8693   return V;
8694 }
8695 
8696 SDValue SelectionDAG::simplifySelect(SDValue Cond, SDValue T, SDValue F) {
8697   // select undef, T, F --> T (if T is a constant), otherwise F
8698   // select, ?, undef, F --> F
8699   // select, ?, T, undef --> T
8700   if (Cond.isUndef())
8701     return isConstantValueOfAnyType(T) ? T : F;
8702   if (T.isUndef())
8703     return F;
8704   if (F.isUndef())
8705     return T;
8706 
8707   // select true, T, F --> T
8708   // select false, T, F --> F
8709   if (auto *CondC = dyn_cast<ConstantSDNode>(Cond))
8710     return CondC->isZero() ? F : T;
8711 
8712   // TODO: This should simplify VSELECT with constant condition using something
8713   // like this (but check boolean contents to be complete?):
8714   //  if (ISD::isBuildVectorAllOnes(Cond.getNode()))
8715   //    return T;
8716   //  if (ISD::isBuildVectorAllZeros(Cond.getNode()))
8717   //    return F;
8718 
8719   // select ?, T, T --> T
8720   if (T == F)
8721     return T;
8722 
8723   return SDValue();
8724 }
8725 
8726 SDValue SelectionDAG::simplifyShift(SDValue X, SDValue Y) {
8727   // shift undef, Y --> 0 (can always assume that the undef value is 0)
8728   if (X.isUndef())
8729     return getConstant(0, SDLoc(X.getNode()), X.getValueType());
8730   // shift X, undef --> undef (because it may shift by the bitwidth)
8731   if (Y.isUndef())
8732     return getUNDEF(X.getValueType());
8733 
8734   // shift 0, Y --> 0
8735   // shift X, 0 --> X
8736   if (isNullOrNullSplat(X) || isNullOrNullSplat(Y))
8737     return X;
8738 
8739   // shift X, C >= bitwidth(X) --> undef
8740   // All vector elements must be too big (or undef) to avoid partial undefs.
8741   auto isShiftTooBig = [X](ConstantSDNode *Val) {
8742     return !Val || Val->getAPIntValue().uge(X.getScalarValueSizeInBits());
8743   };
8744   if (ISD::matchUnaryPredicate(Y, isShiftTooBig, true))
8745     return getUNDEF(X.getValueType());
8746 
8747   return SDValue();
8748 }
8749 
8750 SDValue SelectionDAG::simplifyFPBinop(unsigned Opcode, SDValue X, SDValue Y,
8751                                       SDNodeFlags Flags) {
8752   // If this operation has 'nnan' or 'ninf' and at least 1 disallowed operand
8753   // (an undef operand can be chosen to be Nan/Inf), then the result of this
8754   // operation is poison. That result can be relaxed to undef.
8755   ConstantFPSDNode *XC = isConstOrConstSplatFP(X, /* AllowUndefs */ true);
8756   ConstantFPSDNode *YC = isConstOrConstSplatFP(Y, /* AllowUndefs */ true);
8757   bool HasNan = (XC && XC->getValueAPF().isNaN()) ||
8758                 (YC && YC->getValueAPF().isNaN());
8759   bool HasInf = (XC && XC->getValueAPF().isInfinity()) ||
8760                 (YC && YC->getValueAPF().isInfinity());
8761 
8762   if (Flags.hasNoNaNs() && (HasNan || X.isUndef() || Y.isUndef()))
8763     return getUNDEF(X.getValueType());
8764 
8765   if (Flags.hasNoInfs() && (HasInf || X.isUndef() || Y.isUndef()))
8766     return getUNDEF(X.getValueType());
8767 
8768   if (!YC)
8769     return SDValue();
8770 
8771   // X + -0.0 --> X
8772   if (Opcode == ISD::FADD)
8773     if (YC->getValueAPF().isNegZero())
8774       return X;
8775 
8776   // X - +0.0 --> X
8777   if (Opcode == ISD::FSUB)
8778     if (YC->getValueAPF().isPosZero())
8779       return X;
8780 
8781   // X * 1.0 --> X
8782   // X / 1.0 --> X
8783   if (Opcode == ISD::FMUL || Opcode == ISD::FDIV)
8784     if (YC->getValueAPF().isExactlyValue(1.0))
8785       return X;
8786 
8787   // X * 0.0 --> 0.0
8788   if (Opcode == ISD::FMUL && Flags.hasNoNaNs() && Flags.hasNoSignedZeros())
8789     if (YC->getValueAPF().isZero())
8790       return getConstantFP(0.0, SDLoc(Y), Y.getValueType());
8791 
8792   return SDValue();
8793 }
8794 
8795 SDValue SelectionDAG::getVAArg(EVT VT, const SDLoc &dl, SDValue Chain,
8796                                SDValue Ptr, SDValue SV, unsigned Align) {
8797   SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, dl, MVT::i32) };
8798   return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops);
8799 }
8800 
8801 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8802                               ArrayRef<SDUse> Ops) {
8803   switch (Ops.size()) {
8804   case 0: return getNode(Opcode, DL, VT);
8805   case 1: return getNode(Opcode, DL, VT, static_cast<const SDValue>(Ops[0]));
8806   case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
8807   case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
8808   default: break;
8809   }
8810 
8811   // Copy from an SDUse array into an SDValue array for use with
8812   // the regular getNode logic.
8813   SmallVector<SDValue, 8> NewOps(Ops.begin(), Ops.end());
8814   return getNode(Opcode, DL, VT, NewOps);
8815 }
8816 
8817 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8818                               ArrayRef<SDValue> Ops) {
8819   SDNodeFlags Flags;
8820   if (Inserter)
8821     Flags = Inserter->getFlags();
8822   return getNode(Opcode, DL, VT, Ops, Flags);
8823 }
8824 
8825 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
8826                               ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
8827   unsigned NumOps = Ops.size();
8828   switch (NumOps) {
8829   case 0: return getNode(Opcode, DL, VT);
8830   case 1: return getNode(Opcode, DL, VT, Ops[0], Flags);
8831   case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Flags);
8832   case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2], Flags);
8833   default: break;
8834   }
8835 
8836 #ifndef NDEBUG
8837   for (auto &Op : Ops)
8838     assert(Op.getOpcode() != ISD::DELETED_NODE &&
8839            "Operand is DELETED_NODE!");
8840 #endif
8841 
8842   switch (Opcode) {
8843   default: break;
8844   case ISD::BUILD_VECTOR:
8845     // Attempt to simplify BUILD_VECTOR.
8846     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
8847       return V;
8848     break;
8849   case ISD::CONCAT_VECTORS:
8850     if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
8851       return V;
8852     break;
8853   case ISD::SELECT_CC:
8854     assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
8855     assert(Ops[0].getValueType() == Ops[1].getValueType() &&
8856            "LHS and RHS of condition must have same type!");
8857     assert(Ops[2].getValueType() == Ops[3].getValueType() &&
8858            "True and False arms of SelectCC must have same type!");
8859     assert(Ops[2].getValueType() == VT &&
8860            "select_cc node must be of same type as true and false value!");
8861     break;
8862   case ISD::BR_CC:
8863     assert(NumOps == 5 && "BR_CC takes 5 operands!");
8864     assert(Ops[2].getValueType() == Ops[3].getValueType() &&
8865            "LHS/RHS of comparison should match types!");
8866     break;
8867   case ISD::VP_ADD:
8868   case ISD::VP_SUB:
8869     // If it is VP_ADD/VP_SUB mask operation then turn it to VP_XOR
8870     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
8871       Opcode = ISD::VP_XOR;
8872     break;
8873   case ISD::VP_MUL:
8874     // If it is VP_MUL mask operation then turn it to VP_AND
8875     if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
8876       Opcode = ISD::VP_AND;
8877     break;
8878   case ISD::VP_REDUCE_MUL:
8879     // If it is VP_REDUCE_MUL mask operation then turn it to VP_REDUCE_AND
8880     if (VT == MVT::i1)
8881       Opcode = ISD::VP_REDUCE_AND;
8882     break;
8883   case ISD::VP_REDUCE_ADD:
8884     // If it is VP_REDUCE_ADD mask operation then turn it to VP_REDUCE_XOR
8885     if (VT == MVT::i1)
8886       Opcode = ISD::VP_REDUCE_XOR;
8887     break;
8888   case ISD::VP_REDUCE_SMAX:
8889   case ISD::VP_REDUCE_UMIN:
8890     // If it is VP_REDUCE_SMAX/VP_REDUCE_UMIN mask operation then turn it to
8891     // VP_REDUCE_AND.
8892     if (VT == MVT::i1)
8893       Opcode = ISD::VP_REDUCE_AND;
8894     break;
8895   case ISD::VP_REDUCE_SMIN:
8896   case ISD::VP_REDUCE_UMAX:
8897     // If it is VP_REDUCE_SMIN/VP_REDUCE_UMAX mask operation then turn it to
8898     // VP_REDUCE_OR.
8899     if (VT == MVT::i1)
8900       Opcode = ISD::VP_REDUCE_OR;
8901     break;
8902   }
8903 
8904   // Memoize nodes.
8905   SDNode *N;
8906   SDVTList VTs = getVTList(VT);
8907 
8908   if (VT != MVT::Glue) {
8909     FoldingSetNodeID ID;
8910     AddNodeIDNode(ID, Opcode, VTs, Ops);
8911     void *IP = nullptr;
8912 
8913     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
8914       return SDValue(E, 0);
8915 
8916     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
8917     createOperands(N, Ops);
8918 
8919     CSEMap.InsertNode(N, IP);
8920   } else {
8921     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
8922     createOperands(N, Ops);
8923   }
8924 
8925   N->setFlags(Flags);
8926   InsertNode(N);
8927   SDValue V(N, 0);
8928   NewSDValueDbgMsg(V, "Creating new node: ", this);
8929   return V;
8930 }
8931 
8932 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
8933                               ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) {
8934   return getNode(Opcode, DL, getVTList(ResultTys), Ops);
8935 }
8936 
8937 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8938                               ArrayRef<SDValue> Ops) {
8939   SDNodeFlags Flags;
8940   if (Inserter)
8941     Flags = Inserter->getFlags();
8942   return getNode(Opcode, DL, VTList, Ops, Flags);
8943 }
8944 
8945 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
8946                               ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
8947   if (VTList.NumVTs == 1)
8948     return getNode(Opcode, DL, VTList.VTs[0], Ops, Flags);
8949 
8950 #ifndef NDEBUG
8951   for (auto &Op : Ops)
8952     assert(Op.getOpcode() != ISD::DELETED_NODE &&
8953            "Operand is DELETED_NODE!");
8954 #endif
8955 
8956   switch (Opcode) {
8957   case ISD::STRICT_FP_EXTEND:
8958     assert(VTList.NumVTs == 2 && Ops.size() == 2 &&
8959            "Invalid STRICT_FP_EXTEND!");
8960     assert(VTList.VTs[0].isFloatingPoint() &&
8961            Ops[1].getValueType().isFloatingPoint() && "Invalid FP cast!");
8962     assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
8963            "STRICT_FP_EXTEND result type should be vector iff the operand "
8964            "type is vector!");
8965     assert((!VTList.VTs[0].isVector() ||
8966             VTList.VTs[0].getVectorNumElements() ==
8967             Ops[1].getValueType().getVectorNumElements()) &&
8968            "Vector element count mismatch!");
8969     assert(Ops[1].getValueType().bitsLT(VTList.VTs[0]) &&
8970            "Invalid fpext node, dst <= src!");
8971     break;
8972   case ISD::STRICT_FP_ROUND:
8973     assert(VTList.NumVTs == 2 && Ops.size() == 3 && "Invalid STRICT_FP_ROUND!");
8974     assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
8975            "STRICT_FP_ROUND result type should be vector iff the operand "
8976            "type is vector!");
8977     assert((!VTList.VTs[0].isVector() ||
8978             VTList.VTs[0].getVectorNumElements() ==
8979             Ops[1].getValueType().getVectorNumElements()) &&
8980            "Vector element count mismatch!");
8981     assert(VTList.VTs[0].isFloatingPoint() &&
8982            Ops[1].getValueType().isFloatingPoint() &&
8983            VTList.VTs[0].bitsLT(Ops[1].getValueType()) &&
8984            isa<ConstantSDNode>(Ops[2]) &&
8985            (cast<ConstantSDNode>(Ops[2])->getZExtValue() == 0 ||
8986             cast<ConstantSDNode>(Ops[2])->getZExtValue() == 1) &&
8987            "Invalid STRICT_FP_ROUND!");
8988     break;
8989 #if 0
8990   // FIXME: figure out how to safely handle things like
8991   // int foo(int x) { return 1 << (x & 255); }
8992   // int bar() { return foo(256); }
8993   case ISD::SRA_PARTS:
8994   case ISD::SRL_PARTS:
8995   case ISD::SHL_PARTS:
8996     if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
8997         cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
8998       return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
8999     else if (N3.getOpcode() == ISD::AND)
9000       if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
9001         // If the and is only masking out bits that cannot effect the shift,
9002         // eliminate the and.
9003         unsigned NumBits = VT.getScalarSizeInBits()*2;
9004         if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
9005           return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
9006       }
9007     break;
9008 #endif
9009   }
9010 
9011   // Memoize the node unless it returns a flag.
9012   SDNode *N;
9013   if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
9014     FoldingSetNodeID ID;
9015     AddNodeIDNode(ID, Opcode, VTList, Ops);
9016     void *IP = nullptr;
9017     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
9018       return SDValue(E, 0);
9019 
9020     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
9021     createOperands(N, Ops);
9022     CSEMap.InsertNode(N, IP);
9023   } else {
9024     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
9025     createOperands(N, Ops);
9026   }
9027 
9028   N->setFlags(Flags);
9029   InsertNode(N);
9030   SDValue V(N, 0);
9031   NewSDValueDbgMsg(V, "Creating new node: ", this);
9032   return V;
9033 }
9034 
9035 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
9036                               SDVTList VTList) {
9037   return getNode(Opcode, DL, VTList, None);
9038 }
9039 
9040 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
9041                               SDValue N1) {
9042   SDValue Ops[] = { N1 };
9043   return getNode(Opcode, DL, VTList, Ops);
9044 }
9045 
9046 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
9047                               SDValue N1, SDValue N2) {
9048   SDValue Ops[] = { N1, N2 };
9049   return getNode(Opcode, DL, VTList, Ops);
9050 }
9051 
9052 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
9053                               SDValue N1, SDValue N2, SDValue N3) {
9054   SDValue Ops[] = { N1, N2, N3 };
9055   return getNode(Opcode, DL, VTList, Ops);
9056 }
9057 
9058 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
9059                               SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
9060   SDValue Ops[] = { N1, N2, N3, N4 };
9061   return getNode(Opcode, DL, VTList, Ops);
9062 }
9063 
9064 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
9065                               SDValue N1, SDValue N2, SDValue N3, SDValue N4,
9066                               SDValue N5) {
9067   SDValue Ops[] = { N1, N2, N3, N4, N5 };
9068   return getNode(Opcode, DL, VTList, Ops);
9069 }
9070 
9071 SDVTList SelectionDAG::getVTList(EVT VT) {
9072   return makeVTList(SDNode::getValueTypeList(VT), 1);
9073 }
9074 
9075 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2) {
9076   FoldingSetNodeID ID;
9077   ID.AddInteger(2U);
9078   ID.AddInteger(VT1.getRawBits());
9079   ID.AddInteger(VT2.getRawBits());
9080 
9081   void *IP = nullptr;
9082   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
9083   if (!Result) {
9084     EVT *Array = Allocator.Allocate<EVT>(2);
9085     Array[0] = VT1;
9086     Array[1] = VT2;
9087     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 2);
9088     VTListMap.InsertNode(Result, IP);
9089   }
9090   return Result->getSDVTList();
9091 }
9092 
9093 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3) {
9094   FoldingSetNodeID ID;
9095   ID.AddInteger(3U);
9096   ID.AddInteger(VT1.getRawBits());
9097   ID.AddInteger(VT2.getRawBits());
9098   ID.AddInteger(VT3.getRawBits());
9099 
9100   void *IP = nullptr;
9101   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
9102   if (!Result) {
9103     EVT *Array = Allocator.Allocate<EVT>(3);
9104     Array[0] = VT1;
9105     Array[1] = VT2;
9106     Array[2] = VT3;
9107     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 3);
9108     VTListMap.InsertNode(Result, IP);
9109   }
9110   return Result->getSDVTList();
9111 }
9112 
9113 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4) {
9114   FoldingSetNodeID ID;
9115   ID.AddInteger(4U);
9116   ID.AddInteger(VT1.getRawBits());
9117   ID.AddInteger(VT2.getRawBits());
9118   ID.AddInteger(VT3.getRawBits());
9119   ID.AddInteger(VT4.getRawBits());
9120 
9121   void *IP = nullptr;
9122   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
9123   if (!Result) {
9124     EVT *Array = Allocator.Allocate<EVT>(4);
9125     Array[0] = VT1;
9126     Array[1] = VT2;
9127     Array[2] = VT3;
9128     Array[3] = VT4;
9129     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 4);
9130     VTListMap.InsertNode(Result, IP);
9131   }
9132   return Result->getSDVTList();
9133 }
9134 
9135 SDVTList SelectionDAG::getVTList(ArrayRef<EVT> VTs) {
9136   unsigned NumVTs = VTs.size();
9137   FoldingSetNodeID ID;
9138   ID.AddInteger(NumVTs);
9139   for (unsigned index = 0; index < NumVTs; index++) {
9140     ID.AddInteger(VTs[index].getRawBits());
9141   }
9142 
9143   void *IP = nullptr;
9144   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
9145   if (!Result) {
9146     EVT *Array = Allocator.Allocate<EVT>(NumVTs);
9147     llvm::copy(VTs, Array);
9148     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, NumVTs);
9149     VTListMap.InsertNode(Result, IP);
9150   }
9151   return Result->getSDVTList();
9152 }
9153 
9154 
9155 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
9156 /// specified operands.  If the resultant node already exists in the DAG,
9157 /// this does not modify the specified node, instead it returns the node that
9158 /// already exists.  If the resultant node does not exist in the DAG, the
9159 /// input node is returned.  As a degenerate case, if you specify the same
9160 /// input operands as the node already has, the input node is returned.
9161 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op) {
9162   assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
9163 
9164   // Check to see if there is no change.
9165   if (Op == N->getOperand(0)) return N;
9166 
9167   // See if the modified node already exists.
9168   void *InsertPos = nullptr;
9169   if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
9170     return Existing;
9171 
9172   // Nope it doesn't.  Remove the node from its current place in the maps.
9173   if (InsertPos)
9174     if (!RemoveNodeFromCSEMaps(N))
9175       InsertPos = nullptr;
9176 
9177   // Now we update the operands.
9178   N->OperandList[0].set(Op);
9179 
9180   updateDivergence(N);
9181   // If this gets put into a CSE map, add it.
9182   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
9183   return N;
9184 }
9185 
9186 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2) {
9187   assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
9188 
9189   // Check to see if there is no change.
9190   if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
9191     return N;   // No operands changed, just return the input node.
9192 
9193   // See if the modified node already exists.
9194   void *InsertPos = nullptr;
9195   if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
9196     return Existing;
9197 
9198   // Nope it doesn't.  Remove the node from its current place in the maps.
9199   if (InsertPos)
9200     if (!RemoveNodeFromCSEMaps(N))
9201       InsertPos = nullptr;
9202 
9203   // Now we update the operands.
9204   if (N->OperandList[0] != Op1)
9205     N->OperandList[0].set(Op1);
9206   if (N->OperandList[1] != Op2)
9207     N->OperandList[1].set(Op2);
9208 
9209   updateDivergence(N);
9210   // If this gets put into a CSE map, add it.
9211   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
9212   return N;
9213 }
9214 
9215 SDNode *SelectionDAG::
9216 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, SDValue Op3) {
9217   SDValue Ops[] = { Op1, Op2, Op3 };
9218   return UpdateNodeOperands(N, Ops);
9219 }
9220 
9221 SDNode *SelectionDAG::
9222 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
9223                    SDValue Op3, SDValue Op4) {
9224   SDValue Ops[] = { Op1, Op2, Op3, Op4 };
9225   return UpdateNodeOperands(N, Ops);
9226 }
9227 
9228 SDNode *SelectionDAG::
9229 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
9230                    SDValue Op3, SDValue Op4, SDValue Op5) {
9231   SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 };
9232   return UpdateNodeOperands(N, Ops);
9233 }
9234 
9235 SDNode *SelectionDAG::
9236 UpdateNodeOperands(SDNode *N, ArrayRef<SDValue> Ops) {
9237   unsigned NumOps = Ops.size();
9238   assert(N->getNumOperands() == NumOps &&
9239          "Update with wrong number of operands");
9240 
9241   // If no operands changed just return the input node.
9242   if (std::equal(Ops.begin(), Ops.end(), N->op_begin()))
9243     return N;
9244 
9245   // See if the modified node already exists.
9246   void *InsertPos = nullptr;
9247   if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertPos))
9248     return Existing;
9249 
9250   // Nope it doesn't.  Remove the node from its current place in the maps.
9251   if (InsertPos)
9252     if (!RemoveNodeFromCSEMaps(N))
9253       InsertPos = nullptr;
9254 
9255   // Now we update the operands.
9256   for (unsigned i = 0; i != NumOps; ++i)
9257     if (N->OperandList[i] != Ops[i])
9258       N->OperandList[i].set(Ops[i]);
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 /// DropOperands - Release the operands and set this node to have
9267 /// zero operands.
9268 void SDNode::DropOperands() {
9269   // Unlike the code in MorphNodeTo that does this, we don't need to
9270   // watch for dead nodes here.
9271   for (op_iterator I = op_begin(), E = op_end(); I != E; ) {
9272     SDUse &Use = *I++;
9273     Use.set(SDValue());
9274   }
9275 }
9276 
9277 void SelectionDAG::setNodeMemRefs(MachineSDNode *N,
9278                                   ArrayRef<MachineMemOperand *> NewMemRefs) {
9279   if (NewMemRefs.empty()) {
9280     N->clearMemRefs();
9281     return;
9282   }
9283 
9284   // Check if we can avoid allocating by storing a single reference directly.
9285   if (NewMemRefs.size() == 1) {
9286     N->MemRefs = NewMemRefs[0];
9287     N->NumMemRefs = 1;
9288     return;
9289   }
9290 
9291   MachineMemOperand **MemRefsBuffer =
9292       Allocator.template Allocate<MachineMemOperand *>(NewMemRefs.size());
9293   llvm::copy(NewMemRefs, MemRefsBuffer);
9294   N->MemRefs = MemRefsBuffer;
9295   N->NumMemRefs = static_cast<int>(NewMemRefs.size());
9296 }
9297 
9298 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a
9299 /// machine opcode.
9300 ///
9301 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9302                                    EVT VT) {
9303   SDVTList VTs = getVTList(VT);
9304   return SelectNodeTo(N, MachineOpc, VTs, None);
9305 }
9306 
9307 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9308                                    EVT VT, SDValue Op1) {
9309   SDVTList VTs = getVTList(VT);
9310   SDValue Ops[] = { Op1 };
9311   return SelectNodeTo(N, MachineOpc, VTs, Ops);
9312 }
9313 
9314 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9315                                    EVT VT, SDValue Op1,
9316                                    SDValue Op2) {
9317   SDVTList VTs = getVTList(VT);
9318   SDValue Ops[] = { Op1, Op2 };
9319   return SelectNodeTo(N, MachineOpc, VTs, Ops);
9320 }
9321 
9322 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9323                                    EVT VT, SDValue Op1,
9324                                    SDValue Op2, SDValue Op3) {
9325   SDVTList VTs = getVTList(VT);
9326   SDValue Ops[] = { Op1, Op2, Op3 };
9327   return SelectNodeTo(N, MachineOpc, VTs, Ops);
9328 }
9329 
9330 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9331                                    EVT VT, ArrayRef<SDValue> Ops) {
9332   SDVTList VTs = getVTList(VT);
9333   return SelectNodeTo(N, MachineOpc, VTs, Ops);
9334 }
9335 
9336 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9337                                    EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) {
9338   SDVTList VTs = getVTList(VT1, VT2);
9339   return SelectNodeTo(N, MachineOpc, VTs, Ops);
9340 }
9341 
9342 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9343                                    EVT VT1, EVT VT2) {
9344   SDVTList VTs = getVTList(VT1, VT2);
9345   return SelectNodeTo(N, MachineOpc, VTs, None);
9346 }
9347 
9348 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9349                                    EVT VT1, EVT VT2, EVT VT3,
9350                                    ArrayRef<SDValue> Ops) {
9351   SDVTList VTs = getVTList(VT1, VT2, VT3);
9352   return SelectNodeTo(N, MachineOpc, VTs, Ops);
9353 }
9354 
9355 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9356                                    EVT VT1, EVT VT2,
9357                                    SDValue Op1, SDValue Op2) {
9358   SDVTList VTs = getVTList(VT1, VT2);
9359   SDValue Ops[] = { Op1, Op2 };
9360   return SelectNodeTo(N, MachineOpc, VTs, Ops);
9361 }
9362 
9363 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
9364                                    SDVTList VTs,ArrayRef<SDValue> Ops) {
9365   SDNode *New = MorphNodeTo(N, ~MachineOpc, VTs, Ops);
9366   // Reset the NodeID to -1.
9367   New->setNodeId(-1);
9368   if (New != N) {
9369     ReplaceAllUsesWith(N, New);
9370     RemoveDeadNode(N);
9371   }
9372   return New;
9373 }
9374 
9375 /// UpdateSDLocOnMergeSDNode - If the opt level is -O0 then it throws away
9376 /// the line number information on the merged node since it is not possible to
9377 /// preserve the information that operation is associated with multiple lines.
9378 /// This will make the debugger working better at -O0, were there is a higher
9379 /// probability having other instructions associated with that line.
9380 ///
9381 /// For IROrder, we keep the smaller of the two
9382 SDNode *SelectionDAG::UpdateSDLocOnMergeSDNode(SDNode *N, const SDLoc &OLoc) {
9383   DebugLoc NLoc = N->getDebugLoc();
9384   if (NLoc && OptLevel == CodeGenOpt::None && OLoc.getDebugLoc() != NLoc) {
9385     N->setDebugLoc(DebugLoc());
9386   }
9387   unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder());
9388   N->setIROrder(Order);
9389   return N;
9390 }
9391 
9392 /// MorphNodeTo - This *mutates* the specified node to have the specified
9393 /// return type, opcode, and operands.
9394 ///
9395 /// Note that MorphNodeTo returns the resultant node.  If there is already a
9396 /// node of the specified opcode and operands, it returns that node instead of
9397 /// the current one.  Note that the SDLoc need not be the same.
9398 ///
9399 /// Using MorphNodeTo is faster than creating a new node and swapping it in
9400 /// with ReplaceAllUsesWith both because it often avoids allocating a new
9401 /// node, and because it doesn't require CSE recalculation for any of
9402 /// the node's users.
9403 ///
9404 /// However, note that MorphNodeTo recursively deletes dead nodes from the DAG.
9405 /// As a consequence it isn't appropriate to use from within the DAG combiner or
9406 /// the legalizer which maintain worklists that would need to be updated when
9407 /// deleting things.
9408 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
9409                                   SDVTList VTs, ArrayRef<SDValue> Ops) {
9410   // If an identical node already exists, use it.
9411   void *IP = nullptr;
9412   if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) {
9413     FoldingSetNodeID ID;
9414     AddNodeIDNode(ID, Opc, VTs, Ops);
9415     if (SDNode *ON = FindNodeOrInsertPos(ID, SDLoc(N), IP))
9416       return UpdateSDLocOnMergeSDNode(ON, SDLoc(N));
9417   }
9418 
9419   if (!RemoveNodeFromCSEMaps(N))
9420     IP = nullptr;
9421 
9422   // Start the morphing.
9423   N->NodeType = Opc;
9424   N->ValueList = VTs.VTs;
9425   N->NumValues = VTs.NumVTs;
9426 
9427   // Clear the operands list, updating used nodes to remove this from their
9428   // use list.  Keep track of any operands that become dead as a result.
9429   SmallPtrSet<SDNode*, 16> DeadNodeSet;
9430   for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
9431     SDUse &Use = *I++;
9432     SDNode *Used = Use.getNode();
9433     Use.set(SDValue());
9434     if (Used->use_empty())
9435       DeadNodeSet.insert(Used);
9436   }
9437 
9438   // For MachineNode, initialize the memory references information.
9439   if (MachineSDNode *MN = dyn_cast<MachineSDNode>(N))
9440     MN->clearMemRefs();
9441 
9442   // Swap for an appropriately sized array from the recycler.
9443   removeOperands(N);
9444   createOperands(N, Ops);
9445 
9446   // Delete any nodes that are still dead after adding the uses for the
9447   // new operands.
9448   if (!DeadNodeSet.empty()) {
9449     SmallVector<SDNode *, 16> DeadNodes;
9450     for (SDNode *N : DeadNodeSet)
9451       if (N->use_empty())
9452         DeadNodes.push_back(N);
9453     RemoveDeadNodes(DeadNodes);
9454   }
9455 
9456   if (IP)
9457     CSEMap.InsertNode(N, IP);   // Memoize the new node.
9458   return N;
9459 }
9460 
9461 SDNode* SelectionDAG::mutateStrictFPToFP(SDNode *Node) {
9462   unsigned OrigOpc = Node->getOpcode();
9463   unsigned NewOpc;
9464   switch (OrigOpc) {
9465   default:
9466     llvm_unreachable("mutateStrictFPToFP called with unexpected opcode!");
9467 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
9468   case ISD::STRICT_##DAGN: NewOpc = ISD::DAGN; break;
9469 #define CMP_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
9470   case ISD::STRICT_##DAGN: NewOpc = ISD::SETCC; break;
9471 #include "llvm/IR/ConstrainedOps.def"
9472   }
9473 
9474   assert(Node->getNumValues() == 2 && "Unexpected number of results!");
9475 
9476   // We're taking this node out of the chain, so we need to re-link things.
9477   SDValue InputChain = Node->getOperand(0);
9478   SDValue OutputChain = SDValue(Node, 1);
9479   ReplaceAllUsesOfValueWith(OutputChain, InputChain);
9480 
9481   SmallVector<SDValue, 3> Ops;
9482   for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
9483     Ops.push_back(Node->getOperand(i));
9484 
9485   SDVTList VTs = getVTList(Node->getValueType(0));
9486   SDNode *Res = MorphNodeTo(Node, NewOpc, VTs, Ops);
9487 
9488   // MorphNodeTo can operate in two ways: if an existing node with the
9489   // specified operands exists, it can just return it.  Otherwise, it
9490   // updates the node in place to have the requested operands.
9491   if (Res == Node) {
9492     // If we updated the node in place, reset the node ID.  To the isel,
9493     // this should be just like a newly allocated machine node.
9494     Res->setNodeId(-1);
9495   } else {
9496     ReplaceAllUsesWith(Node, Res);
9497     RemoveDeadNode(Node);
9498   }
9499 
9500   return Res;
9501 }
9502 
9503 /// getMachineNode - These are used for target selectors to create a new node
9504 /// with specified return type(s), MachineInstr opcode, and operands.
9505 ///
9506 /// Note that getMachineNode returns the resultant node.  If there is already a
9507 /// node of the specified opcode and operands, it returns that node instead of
9508 /// the current one.
9509 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9510                                             EVT VT) {
9511   SDVTList VTs = getVTList(VT);
9512   return getMachineNode(Opcode, dl, VTs, None);
9513 }
9514 
9515 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9516                                             EVT VT, SDValue Op1) {
9517   SDVTList VTs = getVTList(VT);
9518   SDValue Ops[] = { Op1 };
9519   return getMachineNode(Opcode, dl, VTs, Ops);
9520 }
9521 
9522 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9523                                             EVT VT, SDValue Op1, SDValue Op2) {
9524   SDVTList VTs = getVTList(VT);
9525   SDValue Ops[] = { Op1, Op2 };
9526   return getMachineNode(Opcode, dl, VTs, Ops);
9527 }
9528 
9529 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9530                                             EVT VT, SDValue Op1, SDValue Op2,
9531                                             SDValue Op3) {
9532   SDVTList VTs = getVTList(VT);
9533   SDValue Ops[] = { Op1, Op2, Op3 };
9534   return getMachineNode(Opcode, dl, VTs, Ops);
9535 }
9536 
9537 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9538                                             EVT VT, ArrayRef<SDValue> Ops) {
9539   SDVTList VTs = getVTList(VT);
9540   return getMachineNode(Opcode, dl, VTs, Ops);
9541 }
9542 
9543 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9544                                             EVT VT1, EVT VT2, SDValue Op1,
9545                                             SDValue Op2) {
9546   SDVTList VTs = getVTList(VT1, VT2);
9547   SDValue Ops[] = { Op1, Op2 };
9548   return getMachineNode(Opcode, dl, VTs, Ops);
9549 }
9550 
9551 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9552                                             EVT VT1, EVT VT2, SDValue Op1,
9553                                             SDValue Op2, SDValue Op3) {
9554   SDVTList VTs = getVTList(VT1, VT2);
9555   SDValue Ops[] = { Op1, Op2, Op3 };
9556   return getMachineNode(Opcode, dl, VTs, Ops);
9557 }
9558 
9559 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9560                                             EVT VT1, EVT VT2,
9561                                             ArrayRef<SDValue> Ops) {
9562   SDVTList VTs = getVTList(VT1, VT2);
9563   return getMachineNode(Opcode, dl, VTs, Ops);
9564 }
9565 
9566 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9567                                             EVT VT1, EVT VT2, EVT VT3,
9568                                             SDValue Op1, SDValue Op2) {
9569   SDVTList VTs = getVTList(VT1, VT2, VT3);
9570   SDValue Ops[] = { Op1, Op2 };
9571   return getMachineNode(Opcode, dl, VTs, Ops);
9572 }
9573 
9574 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9575                                             EVT VT1, EVT VT2, EVT VT3,
9576                                             SDValue Op1, SDValue Op2,
9577                                             SDValue Op3) {
9578   SDVTList VTs = getVTList(VT1, VT2, VT3);
9579   SDValue Ops[] = { Op1, Op2, Op3 };
9580   return getMachineNode(Opcode, dl, VTs, Ops);
9581 }
9582 
9583 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9584                                             EVT VT1, EVT VT2, EVT VT3,
9585                                             ArrayRef<SDValue> Ops) {
9586   SDVTList VTs = getVTList(VT1, VT2, VT3);
9587   return getMachineNode(Opcode, dl, VTs, Ops);
9588 }
9589 
9590 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
9591                                             ArrayRef<EVT> ResultTys,
9592                                             ArrayRef<SDValue> Ops) {
9593   SDVTList VTs = getVTList(ResultTys);
9594   return getMachineNode(Opcode, dl, VTs, Ops);
9595 }
9596 
9597 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &DL,
9598                                             SDVTList VTs,
9599                                             ArrayRef<SDValue> Ops) {
9600   bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue;
9601   MachineSDNode *N;
9602   void *IP = nullptr;
9603 
9604   if (DoCSE) {
9605     FoldingSetNodeID ID;
9606     AddNodeIDNode(ID, ~Opcode, VTs, Ops);
9607     IP = nullptr;
9608     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
9609       return cast<MachineSDNode>(UpdateSDLocOnMergeSDNode(E, DL));
9610     }
9611   }
9612 
9613   // Allocate a new MachineSDNode.
9614   N = newSDNode<MachineSDNode>(~Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
9615   createOperands(N, Ops);
9616 
9617   if (DoCSE)
9618     CSEMap.InsertNode(N, IP);
9619 
9620   InsertNode(N);
9621   NewSDValueDbgMsg(SDValue(N, 0), "Creating new machine node: ", this);
9622   return N;
9623 }
9624 
9625 /// getTargetExtractSubreg - A convenience function for creating
9626 /// TargetOpcode::EXTRACT_SUBREG nodes.
9627 SDValue SelectionDAG::getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT,
9628                                              SDValue Operand) {
9629   SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
9630   SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,
9631                                   VT, Operand, SRIdxVal);
9632   return SDValue(Subreg, 0);
9633 }
9634 
9635 /// getTargetInsertSubreg - A convenience function for creating
9636 /// TargetOpcode::INSERT_SUBREG nodes.
9637 SDValue SelectionDAG::getTargetInsertSubreg(int SRIdx, const SDLoc &DL, EVT VT,
9638                                             SDValue Operand, SDValue Subreg) {
9639   SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
9640   SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL,
9641                                   VT, Operand, Subreg, SRIdxVal);
9642   return SDValue(Result, 0);
9643 }
9644 
9645 /// getNodeIfExists - Get the specified node if it's already available, or
9646 /// else return NULL.
9647 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
9648                                       ArrayRef<SDValue> Ops) {
9649   SDNodeFlags Flags;
9650   if (Inserter)
9651     Flags = Inserter->getFlags();
9652   return getNodeIfExists(Opcode, VTList, Ops, Flags);
9653 }
9654 
9655 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
9656                                       ArrayRef<SDValue> Ops,
9657                                       const SDNodeFlags Flags) {
9658   if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
9659     FoldingSetNodeID ID;
9660     AddNodeIDNode(ID, Opcode, VTList, Ops);
9661     void *IP = nullptr;
9662     if (SDNode *E = FindNodeOrInsertPos(ID, SDLoc(), IP)) {
9663       E->intersectFlagsWith(Flags);
9664       return E;
9665     }
9666   }
9667   return nullptr;
9668 }
9669 
9670 /// doesNodeExist - Check if a node exists without modifying its flags.
9671 bool SelectionDAG::doesNodeExist(unsigned Opcode, SDVTList VTList,
9672                                  ArrayRef<SDValue> Ops) {
9673   if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
9674     FoldingSetNodeID ID;
9675     AddNodeIDNode(ID, Opcode, VTList, Ops);
9676     void *IP = nullptr;
9677     if (FindNodeOrInsertPos(ID, SDLoc(), IP))
9678       return true;
9679   }
9680   return false;
9681 }
9682 
9683 /// getDbgValue - Creates a SDDbgValue node.
9684 ///
9685 /// SDNode
9686 SDDbgValue *SelectionDAG::getDbgValue(DIVariable *Var, DIExpression *Expr,
9687                                       SDNode *N, unsigned R, bool IsIndirect,
9688                                       const DebugLoc &DL, unsigned O) {
9689   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9690          "Expected inlined-at fields to agree");
9691   return new (DbgInfo->getAlloc())
9692       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromNode(N, R),
9693                  {}, IsIndirect, DL, O,
9694                  /*IsVariadic=*/false);
9695 }
9696 
9697 /// Constant
9698 SDDbgValue *SelectionDAG::getConstantDbgValue(DIVariable *Var,
9699                                               DIExpression *Expr,
9700                                               const Value *C,
9701                                               const DebugLoc &DL, unsigned O) {
9702   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9703          "Expected inlined-at fields to agree");
9704   return new (DbgInfo->getAlloc())
9705       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromConst(C), {},
9706                  /*IsIndirect=*/false, DL, O,
9707                  /*IsVariadic=*/false);
9708 }
9709 
9710 /// FrameIndex
9711 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var,
9712                                                 DIExpression *Expr, unsigned FI,
9713                                                 bool IsIndirect,
9714                                                 const DebugLoc &DL,
9715                                                 unsigned O) {
9716   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9717          "Expected inlined-at fields to agree");
9718   return getFrameIndexDbgValue(Var, Expr, FI, {}, IsIndirect, DL, O);
9719 }
9720 
9721 /// FrameIndex with dependencies
9722 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var,
9723                                                 DIExpression *Expr, unsigned FI,
9724                                                 ArrayRef<SDNode *> Dependencies,
9725                                                 bool IsIndirect,
9726                                                 const DebugLoc &DL,
9727                                                 unsigned O) {
9728   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
9729          "Expected inlined-at fields to agree");
9730   return new (DbgInfo->getAlloc())
9731       SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromFrameIdx(FI),
9732                  Dependencies, IsIndirect, DL, O,
9733                  /*IsVariadic=*/false);
9734 }
9735 
9736 /// VReg
9737 SDDbgValue *SelectionDAG::getVRegDbgValue(DIVariable *Var, DIExpression *Expr,
9738                                           unsigned VReg, 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::fromVReg(VReg),
9744                  {}, IsIndirect, DL, O,
9745                  /*IsVariadic=*/false);
9746 }
9747 
9748 SDDbgValue *SelectionDAG::getDbgValueList(DIVariable *Var, DIExpression *Expr,
9749                                           ArrayRef<SDDbgOperand> Locs,
9750                                           ArrayRef<SDNode *> Dependencies,
9751                                           bool IsIndirect, const DebugLoc &DL,
9752                                           unsigned O, bool IsVariadic) {
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, Locs, Dependencies, IsIndirect,
9757                  DL, O, IsVariadic);
9758 }
9759 
9760 void SelectionDAG::transferDbgValues(SDValue From, SDValue To,
9761                                      unsigned OffsetInBits, unsigned SizeInBits,
9762                                      bool InvalidateDbg) {
9763   SDNode *FromNode = From.getNode();
9764   SDNode *ToNode = To.getNode();
9765   assert(FromNode && ToNode && "Can't modify dbg values");
9766 
9767   // PR35338
9768   // TODO: assert(From != To && "Redundant dbg value transfer");
9769   // TODO: assert(FromNode != ToNode && "Intranode dbg value transfer");
9770   if (From == To || FromNode == ToNode)
9771     return;
9772 
9773   if (!FromNode->getHasDebugValue())
9774     return;
9775 
9776   SDDbgOperand FromLocOp =
9777       SDDbgOperand::fromNode(From.getNode(), From.getResNo());
9778   SDDbgOperand ToLocOp = SDDbgOperand::fromNode(To.getNode(), To.getResNo());
9779 
9780   SmallVector<SDDbgValue *, 2> ClonedDVs;
9781   for (SDDbgValue *Dbg : GetDbgValues(FromNode)) {
9782     if (Dbg->isInvalidated())
9783       continue;
9784 
9785     // TODO: assert(!Dbg->isInvalidated() && "Transfer of invalid dbg value");
9786 
9787     // Create a new location ops vector that is equal to the old vector, but
9788     // with each instance of FromLocOp replaced with ToLocOp.
9789     bool Changed = false;
9790     auto NewLocOps = Dbg->copyLocationOps();
9791     std::replace_if(
9792         NewLocOps.begin(), NewLocOps.end(),
9793         [&Changed, FromLocOp](const SDDbgOperand &Op) {
9794           bool Match = Op == FromLocOp;
9795           Changed |= Match;
9796           return Match;
9797         },
9798         ToLocOp);
9799     // Ignore this SDDbgValue if we didn't find a matching location.
9800     if (!Changed)
9801       continue;
9802 
9803     DIVariable *Var = Dbg->getVariable();
9804     auto *Expr = Dbg->getExpression();
9805     // If a fragment is requested, update the expression.
9806     if (SizeInBits) {
9807       // When splitting a larger (e.g., sign-extended) value whose
9808       // lower bits are described with an SDDbgValue, do not attempt
9809       // to transfer the SDDbgValue to the upper bits.
9810       if (auto FI = Expr->getFragmentInfo())
9811         if (OffsetInBits + SizeInBits > FI->SizeInBits)
9812           continue;
9813       auto Fragment = DIExpression::createFragmentExpression(Expr, OffsetInBits,
9814                                                              SizeInBits);
9815       if (!Fragment)
9816         continue;
9817       Expr = *Fragment;
9818     }
9819 
9820     auto AdditionalDependencies = Dbg->getAdditionalDependencies();
9821     // Clone the SDDbgValue and move it to To.
9822     SDDbgValue *Clone = getDbgValueList(
9823         Var, Expr, NewLocOps, AdditionalDependencies, Dbg->isIndirect(),
9824         Dbg->getDebugLoc(), std::max(ToNode->getIROrder(), Dbg->getOrder()),
9825         Dbg->isVariadic());
9826     ClonedDVs.push_back(Clone);
9827 
9828     if (InvalidateDbg) {
9829       // Invalidate value and indicate the SDDbgValue should not be emitted.
9830       Dbg->setIsInvalidated();
9831       Dbg->setIsEmitted();
9832     }
9833   }
9834 
9835   for (SDDbgValue *Dbg : ClonedDVs) {
9836     assert(is_contained(Dbg->getSDNodes(), ToNode) &&
9837            "Transferred DbgValues should depend on the new SDNode");
9838     AddDbgValue(Dbg, false);
9839   }
9840 }
9841 
9842 void SelectionDAG::salvageDebugInfo(SDNode &N) {
9843   if (!N.getHasDebugValue())
9844     return;
9845 
9846   SmallVector<SDDbgValue *, 2> ClonedDVs;
9847   for (auto DV : GetDbgValues(&N)) {
9848     if (DV->isInvalidated())
9849       continue;
9850     switch (N.getOpcode()) {
9851     default:
9852       break;
9853     case ISD::ADD:
9854       SDValue N0 = N.getOperand(0);
9855       SDValue N1 = N.getOperand(1);
9856       if (!isConstantIntBuildVectorOrConstantInt(N0) &&
9857           isConstantIntBuildVectorOrConstantInt(N1)) {
9858         uint64_t Offset = N.getConstantOperandVal(1);
9859 
9860         // Rewrite an ADD constant node into a DIExpression. Since we are
9861         // performing arithmetic to compute the variable's *value* in the
9862         // DIExpression, we need to mark the expression with a
9863         // DW_OP_stack_value.
9864         auto *DIExpr = DV->getExpression();
9865         auto NewLocOps = DV->copyLocationOps();
9866         bool Changed = false;
9867         for (size_t i = 0; i < NewLocOps.size(); ++i) {
9868           // We're not given a ResNo to compare against because the whole
9869           // node is going away. We know that any ISD::ADD only has one
9870           // result, so we can assume any node match is using the result.
9871           if (NewLocOps[i].getKind() != SDDbgOperand::SDNODE ||
9872               NewLocOps[i].getSDNode() != &N)
9873             continue;
9874           NewLocOps[i] = SDDbgOperand::fromNode(N0.getNode(), N0.getResNo());
9875           SmallVector<uint64_t, 3> ExprOps;
9876           DIExpression::appendOffset(ExprOps, Offset);
9877           DIExpr = DIExpression::appendOpsToArg(DIExpr, ExprOps, i, true);
9878           Changed = true;
9879         }
9880         (void)Changed;
9881         assert(Changed && "Salvage target doesn't use N");
9882 
9883         auto AdditionalDependencies = DV->getAdditionalDependencies();
9884         SDDbgValue *Clone = getDbgValueList(DV->getVariable(), DIExpr,
9885                                             NewLocOps, AdditionalDependencies,
9886                                             DV->isIndirect(), DV->getDebugLoc(),
9887                                             DV->getOrder(), DV->isVariadic());
9888         ClonedDVs.push_back(Clone);
9889         DV->setIsInvalidated();
9890         DV->setIsEmitted();
9891         LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting";
9892                    N0.getNode()->dumprFull(this);
9893                    dbgs() << " into " << *DIExpr << '\n');
9894       }
9895     }
9896   }
9897 
9898   for (SDDbgValue *Dbg : ClonedDVs) {
9899     assert(!Dbg->getSDNodes().empty() &&
9900            "Salvaged DbgValue should depend on a new SDNode");
9901     AddDbgValue(Dbg, false);
9902   }
9903 }
9904 
9905 /// Creates a SDDbgLabel node.
9906 SDDbgLabel *SelectionDAG::getDbgLabel(DILabel *Label,
9907                                       const DebugLoc &DL, unsigned O) {
9908   assert(cast<DILabel>(Label)->isValidLocationForIntrinsic(DL) &&
9909          "Expected inlined-at fields to agree");
9910   return new (DbgInfo->getAlloc()) SDDbgLabel(Label, DL, O);
9911 }
9912 
9913 namespace {
9914 
9915 /// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node
9916 /// pointed to by a use iterator is deleted, increment the use iterator
9917 /// so that it doesn't dangle.
9918 ///
9919 class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener {
9920   SDNode::use_iterator &UI;
9921   SDNode::use_iterator &UE;
9922 
9923   void NodeDeleted(SDNode *N, SDNode *E) override {
9924     // Increment the iterator as needed.
9925     while (UI != UE && N == *UI)
9926       ++UI;
9927   }
9928 
9929 public:
9930   RAUWUpdateListener(SelectionDAG &d,
9931                      SDNode::use_iterator &ui,
9932                      SDNode::use_iterator &ue)
9933     : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {}
9934 };
9935 
9936 } // end anonymous namespace
9937 
9938 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
9939 /// This can cause recursive merging of nodes in the DAG.
9940 ///
9941 /// This version assumes From has a single result value.
9942 ///
9943 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To) {
9944   SDNode *From = FromN.getNode();
9945   assert(From->getNumValues() == 1 && FromN.getResNo() == 0 &&
9946          "Cannot replace with this method!");
9947   assert(From != To.getNode() && "Cannot replace uses of with self");
9948 
9949   // Preserve Debug Values
9950   transferDbgValues(FromN, To);
9951 
9952   // Iterate over all the existing uses of From. New uses will be added
9953   // to the beginning of the use list, which we avoid visiting.
9954   // This specifically avoids visiting uses of From that arise while the
9955   // replacement is happening, because any such uses would be the result
9956   // of CSE: If an existing node looks like From after one of its operands
9957   // is replaced by To, we don't want to replace of all its users with To
9958   // too. See PR3018 for more info.
9959   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
9960   RAUWUpdateListener Listener(*this, UI, UE);
9961   while (UI != UE) {
9962     SDNode *User = *UI;
9963 
9964     // This node is about to morph, remove its old self from the CSE maps.
9965     RemoveNodeFromCSEMaps(User);
9966 
9967     // A user can appear in a use list multiple times, and when this
9968     // happens the uses are usually next to each other in the list.
9969     // To help reduce the number of CSE recomputations, process all
9970     // the uses of this user that we can find this way.
9971     do {
9972       SDUse &Use = UI.getUse();
9973       ++UI;
9974       Use.set(To);
9975       if (To->isDivergent() != From->isDivergent())
9976         updateDivergence(User);
9977     } while (UI != UE && *UI == User);
9978     // Now that we have modified User, add it back to the CSE maps.  If it
9979     // already exists there, recursively merge the results together.
9980     AddModifiedNodeToCSEMaps(User);
9981   }
9982 
9983   // If we just RAUW'd the root, take note.
9984   if (FromN == getRoot())
9985     setRoot(To);
9986 }
9987 
9988 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
9989 /// This can cause recursive merging of nodes in the DAG.
9990 ///
9991 /// This version assumes that for each value of From, there is a
9992 /// corresponding value in To in the same position with the same type.
9993 ///
9994 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To) {
9995 #ifndef NDEBUG
9996   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
9997     assert((!From->hasAnyUseOfValue(i) ||
9998             From->getValueType(i) == To->getValueType(i)) &&
9999            "Cannot use this version of ReplaceAllUsesWith!");
10000 #endif
10001 
10002   // Handle the trivial case.
10003   if (From == To)
10004     return;
10005 
10006   // Preserve Debug Info. Only do this if there's a use.
10007   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
10008     if (From->hasAnyUseOfValue(i)) {
10009       assert((i < To->getNumValues()) && "Invalid To location");
10010       transferDbgValues(SDValue(From, i), SDValue(To, i));
10011     }
10012 
10013   // Iterate over just the existing users of From. See the comments in
10014   // the ReplaceAllUsesWith above.
10015   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
10016   RAUWUpdateListener Listener(*this, UI, UE);
10017   while (UI != UE) {
10018     SDNode *User = *UI;
10019 
10020     // This node is about to morph, remove its old self from the CSE maps.
10021     RemoveNodeFromCSEMaps(User);
10022 
10023     // A user can appear in a use list multiple times, and when this
10024     // happens the uses are usually next to each other in the list.
10025     // To help reduce the number of CSE recomputations, process all
10026     // the uses of this user that we can find this way.
10027     do {
10028       SDUse &Use = UI.getUse();
10029       ++UI;
10030       Use.setNode(To);
10031       if (To->isDivergent() != From->isDivergent())
10032         updateDivergence(User);
10033     } while (UI != UE && *UI == User);
10034 
10035     // Now that we have modified User, add it back to the CSE maps.  If it
10036     // already exists there, recursively merge the results together.
10037     AddModifiedNodeToCSEMaps(User);
10038   }
10039 
10040   // If we just RAUW'd the root, take note.
10041   if (From == getRoot().getNode())
10042     setRoot(SDValue(To, getRoot().getResNo()));
10043 }
10044 
10045 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
10046 /// This can cause recursive merging of nodes in the DAG.
10047 ///
10048 /// This version can replace From with any result values.  To must match the
10049 /// number and types of values returned by From.
10050 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, const SDValue *To) {
10051   if (From->getNumValues() == 1)  // Handle the simple case efficiently.
10052     return ReplaceAllUsesWith(SDValue(From, 0), To[0]);
10053 
10054   // Preserve Debug Info.
10055   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
10056     transferDbgValues(SDValue(From, i), To[i]);
10057 
10058   // Iterate over just the existing users of From. See the comments in
10059   // the ReplaceAllUsesWith above.
10060   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
10061   RAUWUpdateListener Listener(*this, UI, UE);
10062   while (UI != UE) {
10063     SDNode *User = *UI;
10064 
10065     // This node is about to morph, remove its old self from the CSE maps.
10066     RemoveNodeFromCSEMaps(User);
10067 
10068     // A user can appear in a use list multiple times, and when this happens the
10069     // uses are usually next to each other in the list.  To help reduce the
10070     // number of CSE and divergence recomputations, process all the uses of this
10071     // user that we can find this way.
10072     bool To_IsDivergent = false;
10073     do {
10074       SDUse &Use = UI.getUse();
10075       const SDValue &ToOp = To[Use.getResNo()];
10076       ++UI;
10077       Use.set(ToOp);
10078       To_IsDivergent |= ToOp->isDivergent();
10079     } while (UI != UE && *UI == User);
10080 
10081     if (To_IsDivergent != From->isDivergent())
10082       updateDivergence(User);
10083 
10084     // Now that we have modified User, add it back to the CSE maps.  If it
10085     // already exists there, recursively merge the results together.
10086     AddModifiedNodeToCSEMaps(User);
10087   }
10088 
10089   // If we just RAUW'd the root, take note.
10090   if (From == getRoot().getNode())
10091     setRoot(SDValue(To[getRoot().getResNo()]));
10092 }
10093 
10094 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
10095 /// uses of other values produced by From.getNode() alone.  The Deleted
10096 /// vector is handled the same way as for ReplaceAllUsesWith.
10097 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To){
10098   // Handle the really simple, really trivial case efficiently.
10099   if (From == To) return;
10100 
10101   // Handle the simple, trivial, case efficiently.
10102   if (From.getNode()->getNumValues() == 1) {
10103     ReplaceAllUsesWith(From, To);
10104     return;
10105   }
10106 
10107   // Preserve Debug Info.
10108   transferDbgValues(From, To);
10109 
10110   // Iterate over just the existing users of From. See the comments in
10111   // the ReplaceAllUsesWith above.
10112   SDNode::use_iterator UI = From.getNode()->use_begin(),
10113                        UE = From.getNode()->use_end();
10114   RAUWUpdateListener Listener(*this, UI, UE);
10115   while (UI != UE) {
10116     SDNode *User = *UI;
10117     bool UserRemovedFromCSEMaps = false;
10118 
10119     // A user can appear in a use list multiple times, and when this
10120     // happens the uses are usually next to each other in the list.
10121     // To help reduce the number of CSE recomputations, process all
10122     // the uses of this user that we can find this way.
10123     do {
10124       SDUse &Use = UI.getUse();
10125 
10126       // Skip uses of different values from the same node.
10127       if (Use.getResNo() != From.getResNo()) {
10128         ++UI;
10129         continue;
10130       }
10131 
10132       // If this node hasn't been modified yet, it's still in the CSE maps,
10133       // so remove its old self from the CSE maps.
10134       if (!UserRemovedFromCSEMaps) {
10135         RemoveNodeFromCSEMaps(User);
10136         UserRemovedFromCSEMaps = true;
10137       }
10138 
10139       ++UI;
10140       Use.set(To);
10141       if (To->isDivergent() != From->isDivergent())
10142         updateDivergence(User);
10143     } while (UI != UE && *UI == User);
10144     // We are iterating over all uses of the From node, so if a use
10145     // doesn't use the specific value, no changes are made.
10146     if (!UserRemovedFromCSEMaps)
10147       continue;
10148 
10149     // Now that we have modified User, add it back to the CSE maps.  If it
10150     // already exists there, recursively merge the results together.
10151     AddModifiedNodeToCSEMaps(User);
10152   }
10153 
10154   // If we just RAUW'd the root, take note.
10155   if (From == getRoot())
10156     setRoot(To);
10157 }
10158 
10159 namespace {
10160 
10161 /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith
10162 /// to record information about a use.
10163 struct UseMemo {
10164   SDNode *User;
10165   unsigned Index;
10166   SDUse *Use;
10167 };
10168 
10169 /// operator< - Sort Memos by User.
10170 bool operator<(const UseMemo &L, const UseMemo &R) {
10171   return (intptr_t)L.User < (intptr_t)R.User;
10172 }
10173 
10174 /// RAUOVWUpdateListener - Helper for ReplaceAllUsesOfValuesWith - When the node
10175 /// pointed to by a UseMemo is deleted, set the User to nullptr to indicate that
10176 /// the node already has been taken care of recursively.
10177 class RAUOVWUpdateListener : public SelectionDAG::DAGUpdateListener {
10178   SmallVector<UseMemo, 4> &Uses;
10179 
10180   void NodeDeleted(SDNode *N, SDNode *E) override {
10181     for (UseMemo &Memo : Uses)
10182       if (Memo.User == N)
10183         Memo.User = nullptr;
10184   }
10185 
10186 public:
10187   RAUOVWUpdateListener(SelectionDAG &d, SmallVector<UseMemo, 4> &uses)
10188       : SelectionDAG::DAGUpdateListener(d), Uses(uses) {}
10189 };
10190 
10191 } // end anonymous namespace
10192 
10193 bool SelectionDAG::calculateDivergence(SDNode *N) {
10194   if (TLI->isSDNodeAlwaysUniform(N)) {
10195     assert(!TLI->isSDNodeSourceOfDivergence(N, FLI, DA) &&
10196            "Conflicting divergence information!");
10197     return false;
10198   }
10199   if (TLI->isSDNodeSourceOfDivergence(N, FLI, DA))
10200     return true;
10201   for (auto &Op : N->ops()) {
10202     if (Op.Val.getValueType() != MVT::Other && Op.getNode()->isDivergent())
10203       return true;
10204   }
10205   return false;
10206 }
10207 
10208 void SelectionDAG::updateDivergence(SDNode *N) {
10209   SmallVector<SDNode *, 16> Worklist(1, N);
10210   do {
10211     N = Worklist.pop_back_val();
10212     bool IsDivergent = calculateDivergence(N);
10213     if (N->SDNodeBits.IsDivergent != IsDivergent) {
10214       N->SDNodeBits.IsDivergent = IsDivergent;
10215       llvm::append_range(Worklist, N->uses());
10216     }
10217   } while (!Worklist.empty());
10218 }
10219 
10220 void SelectionDAG::CreateTopologicalOrder(std::vector<SDNode *> &Order) {
10221   DenseMap<SDNode *, unsigned> Degree;
10222   Order.reserve(AllNodes.size());
10223   for (auto &N : allnodes()) {
10224     unsigned NOps = N.getNumOperands();
10225     Degree[&N] = NOps;
10226     if (0 == NOps)
10227       Order.push_back(&N);
10228   }
10229   for (size_t I = 0; I != Order.size(); ++I) {
10230     SDNode *N = Order[I];
10231     for (auto U : N->uses()) {
10232       unsigned &UnsortedOps = Degree[U];
10233       if (0 == --UnsortedOps)
10234         Order.push_back(U);
10235     }
10236   }
10237 }
10238 
10239 #ifndef NDEBUG
10240 void SelectionDAG::VerifyDAGDivergence() {
10241   std::vector<SDNode *> TopoOrder;
10242   CreateTopologicalOrder(TopoOrder);
10243   for (auto *N : TopoOrder) {
10244     assert(calculateDivergence(N) == N->isDivergent() &&
10245            "Divergence bit inconsistency detected");
10246   }
10247 }
10248 #endif
10249 
10250 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving
10251 /// uses of other values produced by From.getNode() alone.  The same value
10252 /// may appear in both the From and To list.  The Deleted vector is
10253 /// handled the same way as for ReplaceAllUsesWith.
10254 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From,
10255                                               const SDValue *To,
10256                                               unsigned Num){
10257   // Handle the simple, trivial case efficiently.
10258   if (Num == 1)
10259     return ReplaceAllUsesOfValueWith(*From, *To);
10260 
10261   transferDbgValues(*From, *To);
10262 
10263   // Read up all the uses and make records of them. This helps
10264   // processing new uses that are introduced during the
10265   // replacement process.
10266   SmallVector<UseMemo, 4> Uses;
10267   for (unsigned i = 0; i != Num; ++i) {
10268     unsigned FromResNo = From[i].getResNo();
10269     SDNode *FromNode = From[i].getNode();
10270     for (SDNode::use_iterator UI = FromNode->use_begin(),
10271          E = FromNode->use_end(); UI != E; ++UI) {
10272       SDUse &Use = UI.getUse();
10273       if (Use.getResNo() == FromResNo) {
10274         UseMemo Memo = { *UI, i, &Use };
10275         Uses.push_back(Memo);
10276       }
10277     }
10278   }
10279 
10280   // Sort the uses, so that all the uses from a given User are together.
10281   llvm::sort(Uses);
10282   RAUOVWUpdateListener Listener(*this, Uses);
10283 
10284   for (unsigned UseIndex = 0, UseIndexEnd = Uses.size();
10285        UseIndex != UseIndexEnd; ) {
10286     // We know that this user uses some value of From.  If it is the right
10287     // value, update it.
10288     SDNode *User = Uses[UseIndex].User;
10289     // If the node has been deleted by recursive CSE updates when updating
10290     // another node, then just skip this entry.
10291     if (User == nullptr) {
10292       ++UseIndex;
10293       continue;
10294     }
10295 
10296     // This node is about to morph, remove its old self from the CSE maps.
10297     RemoveNodeFromCSEMaps(User);
10298 
10299     // The Uses array is sorted, so all the uses for a given User
10300     // are next to each other in the list.
10301     // To help reduce the number of CSE recomputations, process all
10302     // the uses of this user that we can find this way.
10303     do {
10304       unsigned i = Uses[UseIndex].Index;
10305       SDUse &Use = *Uses[UseIndex].Use;
10306       ++UseIndex;
10307 
10308       Use.set(To[i]);
10309     } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User);
10310 
10311     // Now that we have modified User, add it back to the CSE maps.  If it
10312     // already exists there, recursively merge the results together.
10313     AddModifiedNodeToCSEMaps(User);
10314   }
10315 }
10316 
10317 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
10318 /// based on their topological order. It returns the maximum id and a vector
10319 /// of the SDNodes* in assigned order by reference.
10320 unsigned SelectionDAG::AssignTopologicalOrder() {
10321   unsigned DAGSize = 0;
10322 
10323   // SortedPos tracks the progress of the algorithm. Nodes before it are
10324   // sorted, nodes after it are unsorted. When the algorithm completes
10325   // it is at the end of the list.
10326   allnodes_iterator SortedPos = allnodes_begin();
10327 
10328   // Visit all the nodes. Move nodes with no operands to the front of
10329   // the list immediately. Annotate nodes that do have operands with their
10330   // operand count. Before we do this, the Node Id fields of the nodes
10331   // may contain arbitrary values. After, the Node Id fields for nodes
10332   // before SortedPos will contain the topological sort index, and the
10333   // Node Id fields for nodes At SortedPos and after will contain the
10334   // count of outstanding operands.
10335   for (SDNode &N : llvm::make_early_inc_range(allnodes())) {
10336     checkForCycles(&N, this);
10337     unsigned Degree = N.getNumOperands();
10338     if (Degree == 0) {
10339       // A node with no uses, add it to the result array immediately.
10340       N.setNodeId(DAGSize++);
10341       allnodes_iterator Q(&N);
10342       if (Q != SortedPos)
10343         SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q));
10344       assert(SortedPos != AllNodes.end() && "Overran node list");
10345       ++SortedPos;
10346     } else {
10347       // Temporarily use the Node Id as scratch space for the degree count.
10348       N.setNodeId(Degree);
10349     }
10350   }
10351 
10352   // Visit all the nodes. As we iterate, move nodes into sorted order,
10353   // such that by the time the end is reached all nodes will be sorted.
10354   for (SDNode &Node : allnodes()) {
10355     SDNode *N = &Node;
10356     checkForCycles(N, this);
10357     // N is in sorted position, so all its uses have one less operand
10358     // that needs to be sorted.
10359     for (SDNode *P : N->uses()) {
10360       unsigned Degree = P->getNodeId();
10361       assert(Degree != 0 && "Invalid node degree");
10362       --Degree;
10363       if (Degree == 0) {
10364         // All of P's operands are sorted, so P may sorted now.
10365         P->setNodeId(DAGSize++);
10366         if (P->getIterator() != SortedPos)
10367           SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P));
10368         assert(SortedPos != AllNodes.end() && "Overran node list");
10369         ++SortedPos;
10370       } else {
10371         // Update P's outstanding operand count.
10372         P->setNodeId(Degree);
10373       }
10374     }
10375     if (Node.getIterator() == SortedPos) {
10376 #ifndef NDEBUG
10377       allnodes_iterator I(N);
10378       SDNode *S = &*++I;
10379       dbgs() << "Overran sorted position:\n";
10380       S->dumprFull(this); dbgs() << "\n";
10381       dbgs() << "Checking if this is due to cycles\n";
10382       checkForCycles(this, true);
10383 #endif
10384       llvm_unreachable(nullptr);
10385     }
10386   }
10387 
10388   assert(SortedPos == AllNodes.end() &&
10389          "Topological sort incomplete!");
10390   assert(AllNodes.front().getOpcode() == ISD::EntryToken &&
10391          "First node in topological sort is not the entry token!");
10392   assert(AllNodes.front().getNodeId() == 0 &&
10393          "First node in topological sort has non-zero id!");
10394   assert(AllNodes.front().getNumOperands() == 0 &&
10395          "First node in topological sort has operands!");
10396   assert(AllNodes.back().getNodeId() == (int)DAGSize-1 &&
10397          "Last node in topologic sort has unexpected id!");
10398   assert(AllNodes.back().use_empty() &&
10399          "Last node in topologic sort has users!");
10400   assert(DAGSize == allnodes_size() && "Node count mismatch!");
10401   return DAGSize;
10402 }
10403 
10404 /// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the
10405 /// value is produced by SD.
10406 void SelectionDAG::AddDbgValue(SDDbgValue *DB, bool isParameter) {
10407   for (SDNode *SD : DB->getSDNodes()) {
10408     if (!SD)
10409       continue;
10410     assert(DbgInfo->getSDDbgValues(SD).empty() || SD->getHasDebugValue());
10411     SD->setHasDebugValue(true);
10412   }
10413   DbgInfo->add(DB, isParameter);
10414 }
10415 
10416 void SelectionDAG::AddDbgLabel(SDDbgLabel *DB) { DbgInfo->add(DB); }
10417 
10418 SDValue SelectionDAG::makeEquivalentMemoryOrdering(SDValue OldChain,
10419                                                    SDValue NewMemOpChain) {
10420   assert(isa<MemSDNode>(NewMemOpChain) && "Expected a memop node");
10421   assert(NewMemOpChain.getValueType() == MVT::Other && "Expected a token VT");
10422   // The new memory operation must have the same position as the old load in
10423   // terms of memory dependency. Create a TokenFactor for the old load and new
10424   // memory operation and update uses of the old load's output chain to use that
10425   // TokenFactor.
10426   if (OldChain == NewMemOpChain || OldChain.use_empty())
10427     return NewMemOpChain;
10428 
10429   SDValue TokenFactor = getNode(ISD::TokenFactor, SDLoc(OldChain), MVT::Other,
10430                                 OldChain, NewMemOpChain);
10431   ReplaceAllUsesOfValueWith(OldChain, TokenFactor);
10432   UpdateNodeOperands(TokenFactor.getNode(), OldChain, NewMemOpChain);
10433   return TokenFactor;
10434 }
10435 
10436 SDValue SelectionDAG::makeEquivalentMemoryOrdering(LoadSDNode *OldLoad,
10437                                                    SDValue NewMemOp) {
10438   assert(isa<MemSDNode>(NewMemOp.getNode()) && "Expected a memop node");
10439   SDValue OldChain = SDValue(OldLoad, 1);
10440   SDValue NewMemOpChain = NewMemOp.getValue(1);
10441   return makeEquivalentMemoryOrdering(OldChain, NewMemOpChain);
10442 }
10443 
10444 SDValue SelectionDAG::getSymbolFunctionGlobalAddress(SDValue Op,
10445                                                      Function **OutFunction) {
10446   assert(isa<ExternalSymbolSDNode>(Op) && "Node should be an ExternalSymbol");
10447 
10448   auto *Symbol = cast<ExternalSymbolSDNode>(Op)->getSymbol();
10449   auto *Module = MF->getFunction().getParent();
10450   auto *Function = Module->getFunction(Symbol);
10451 
10452   if (OutFunction != nullptr)
10453       *OutFunction = Function;
10454 
10455   if (Function != nullptr) {
10456     auto PtrTy = TLI->getPointerTy(getDataLayout(), Function->getAddressSpace());
10457     return getGlobalAddress(Function, SDLoc(Op), PtrTy);
10458   }
10459 
10460   std::string ErrorStr;
10461   raw_string_ostream ErrorFormatter(ErrorStr);
10462   ErrorFormatter << "Undefined external symbol ";
10463   ErrorFormatter << '"' << Symbol << '"';
10464   report_fatal_error(Twine(ErrorFormatter.str()));
10465 }
10466 
10467 //===----------------------------------------------------------------------===//
10468 //                              SDNode Class
10469 //===----------------------------------------------------------------------===//
10470 
10471 bool llvm::isNullConstant(SDValue V) {
10472   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
10473   return Const != nullptr && Const->isZero();
10474 }
10475 
10476 bool llvm::isNullFPConstant(SDValue V) {
10477   ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V);
10478   return Const != nullptr && Const->isZero() && !Const->isNegative();
10479 }
10480 
10481 bool llvm::isAllOnesConstant(SDValue V) {
10482   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
10483   return Const != nullptr && Const->isAllOnes();
10484 }
10485 
10486 bool llvm::isOneConstant(SDValue V) {
10487   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
10488   return Const != nullptr && Const->isOne();
10489 }
10490 
10491 bool llvm::isMinSignedConstant(SDValue V) {
10492   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
10493   return Const != nullptr && Const->isMinSignedValue();
10494 }
10495 
10496 SDValue llvm::peekThroughBitcasts(SDValue V) {
10497   while (V.getOpcode() == ISD::BITCAST)
10498     V = V.getOperand(0);
10499   return V;
10500 }
10501 
10502 SDValue llvm::peekThroughOneUseBitcasts(SDValue V) {
10503   while (V.getOpcode() == ISD::BITCAST && V.getOperand(0).hasOneUse())
10504     V = V.getOperand(0);
10505   return V;
10506 }
10507 
10508 SDValue llvm::peekThroughExtractSubvectors(SDValue V) {
10509   while (V.getOpcode() == ISD::EXTRACT_SUBVECTOR)
10510     V = V.getOperand(0);
10511   return V;
10512 }
10513 
10514 bool llvm::isBitwiseNot(SDValue V, bool AllowUndefs) {
10515   if (V.getOpcode() != ISD::XOR)
10516     return false;
10517   V = peekThroughBitcasts(V.getOperand(1));
10518   unsigned NumBits = V.getScalarValueSizeInBits();
10519   ConstantSDNode *C =
10520       isConstOrConstSplat(V, AllowUndefs, /*AllowTruncation*/ true);
10521   return C && (C->getAPIntValue().countTrailingOnes() >= NumBits);
10522 }
10523 
10524 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, bool AllowUndefs,
10525                                           bool AllowTruncation) {
10526   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
10527     return CN;
10528 
10529   // SplatVectors can truncate their operands. Ignore that case here unless
10530   // AllowTruncation is set.
10531   if (N->getOpcode() == ISD::SPLAT_VECTOR) {
10532     EVT VecEltVT = N->getValueType(0).getVectorElementType();
10533     if (auto *CN = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
10534       EVT CVT = CN->getValueType(0);
10535       assert(CVT.bitsGE(VecEltVT) && "Illegal splat_vector element extension");
10536       if (AllowTruncation || CVT == VecEltVT)
10537         return CN;
10538     }
10539   }
10540 
10541   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
10542     BitVector UndefElements;
10543     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
10544 
10545     // BuildVectors can truncate their operands. Ignore that case here unless
10546     // AllowTruncation is set.
10547     if (CN && (UndefElements.none() || AllowUndefs)) {
10548       EVT CVT = CN->getValueType(0);
10549       EVT NSVT = N.getValueType().getScalarType();
10550       assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension");
10551       if (AllowTruncation || (CVT == NSVT))
10552         return CN;
10553     }
10554   }
10555 
10556   return nullptr;
10557 }
10558 
10559 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, const APInt &DemandedElts,
10560                                           bool AllowUndefs,
10561                                           bool AllowTruncation) {
10562   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
10563     return CN;
10564 
10565   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
10566     BitVector UndefElements;
10567     ConstantSDNode *CN = BV->getConstantSplatNode(DemandedElts, &UndefElements);
10568 
10569     // BuildVectors can truncate their operands. Ignore that case here unless
10570     // AllowTruncation is set.
10571     if (CN && (UndefElements.none() || AllowUndefs)) {
10572       EVT CVT = CN->getValueType(0);
10573       EVT NSVT = N.getValueType().getScalarType();
10574       assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension");
10575       if (AllowTruncation || (CVT == NSVT))
10576         return CN;
10577     }
10578   }
10579 
10580   return nullptr;
10581 }
10582 
10583 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N, bool AllowUndefs) {
10584   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
10585     return CN;
10586 
10587   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
10588     BitVector UndefElements;
10589     ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
10590     if (CN && (UndefElements.none() || AllowUndefs))
10591       return CN;
10592   }
10593 
10594   if (N.getOpcode() == ISD::SPLAT_VECTOR)
10595     if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N.getOperand(0)))
10596       return CN;
10597 
10598   return nullptr;
10599 }
10600 
10601 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N,
10602                                               const APInt &DemandedElts,
10603                                               bool AllowUndefs) {
10604   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
10605     return CN;
10606 
10607   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
10608     BitVector UndefElements;
10609     ConstantFPSDNode *CN =
10610         BV->getConstantFPSplatNode(DemandedElts, &UndefElements);
10611     if (CN && (UndefElements.none() || AllowUndefs))
10612       return CN;
10613   }
10614 
10615   return nullptr;
10616 }
10617 
10618 bool llvm::isNullOrNullSplat(SDValue N, bool AllowUndefs) {
10619   // TODO: may want to use peekThroughBitcast() here.
10620   ConstantSDNode *C =
10621       isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation=*/true);
10622   return C && C->isZero();
10623 }
10624 
10625 bool llvm::isOneOrOneSplat(SDValue N, bool AllowUndefs) {
10626   // TODO: may want to use peekThroughBitcast() here.
10627   unsigned BitWidth = N.getScalarValueSizeInBits();
10628   ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs);
10629   return C && C->isOne() && C->getValueSizeInBits(0) == BitWidth;
10630 }
10631 
10632 bool llvm::isAllOnesOrAllOnesSplat(SDValue N, bool AllowUndefs) {
10633   N = peekThroughBitcasts(N);
10634   unsigned BitWidth = N.getScalarValueSizeInBits();
10635   ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs);
10636   return C && C->isAllOnes() && C->getValueSizeInBits(0) == BitWidth;
10637 }
10638 
10639 HandleSDNode::~HandleSDNode() {
10640   DropOperands();
10641 }
10642 
10643 GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, unsigned Order,
10644                                          const DebugLoc &DL,
10645                                          const GlobalValue *GA, EVT VT,
10646                                          int64_t o, unsigned TF)
10647     : SDNode(Opc, Order, DL, getSDVTList(VT)), Offset(o), TargetFlags(TF) {
10648   TheGlobal = GA;
10649 }
10650 
10651 AddrSpaceCastSDNode::AddrSpaceCastSDNode(unsigned Order, const DebugLoc &dl,
10652                                          EVT VT, unsigned SrcAS,
10653                                          unsigned DestAS)
10654     : SDNode(ISD::ADDRSPACECAST, Order, dl, getSDVTList(VT)),
10655       SrcAddrSpace(SrcAS), DestAddrSpace(DestAS) {}
10656 
10657 MemSDNode::MemSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl,
10658                      SDVTList VTs, EVT memvt, MachineMemOperand *mmo)
10659     : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MMO(mmo) {
10660   MemSDNodeBits.IsVolatile = MMO->isVolatile();
10661   MemSDNodeBits.IsNonTemporal = MMO->isNonTemporal();
10662   MemSDNodeBits.IsDereferenceable = MMO->isDereferenceable();
10663   MemSDNodeBits.IsInvariant = MMO->isInvariant();
10664 
10665   // We check here that the size of the memory operand fits within the size of
10666   // the MMO. This is because the MMO might indicate only a possible address
10667   // range instead of specifying the affected memory addresses precisely.
10668   // TODO: Make MachineMemOperands aware of scalable vectors.
10669   assert(memvt.getStoreSize().getKnownMinSize() <= MMO->getSize() &&
10670          "Size mismatch!");
10671 }
10672 
10673 /// Profile - Gather unique data for the node.
10674 ///
10675 void SDNode::Profile(FoldingSetNodeID &ID) const {
10676   AddNodeIDNode(ID, this);
10677 }
10678 
10679 namespace {
10680 
10681   struct EVTArray {
10682     std::vector<EVT> VTs;
10683 
10684     EVTArray() {
10685       VTs.reserve(MVT::VALUETYPE_SIZE);
10686       for (unsigned i = 0; i < MVT::VALUETYPE_SIZE; ++i)
10687         VTs.push_back(MVT((MVT::SimpleValueType)i));
10688     }
10689   };
10690 
10691 } // end anonymous namespace
10692 
10693 static ManagedStatic<std::set<EVT, EVT::compareRawBits>> EVTs;
10694 static ManagedStatic<EVTArray> SimpleVTArray;
10695 static ManagedStatic<sys::SmartMutex<true>> VTMutex;
10696 
10697 /// getValueTypeList - Return a pointer to the specified value type.
10698 ///
10699 const EVT *SDNode::getValueTypeList(EVT VT) {
10700   if (VT.isExtended()) {
10701     sys::SmartScopedLock<true> Lock(*VTMutex);
10702     return &(*EVTs->insert(VT).first);
10703   }
10704   assert(VT.getSimpleVT() < MVT::VALUETYPE_SIZE && "Value type out of range!");
10705   return &SimpleVTArray->VTs[VT.getSimpleVT().SimpleTy];
10706 }
10707 
10708 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
10709 /// indicated value.  This method ignores uses of other values defined by this
10710 /// operation.
10711 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
10712   assert(Value < getNumValues() && "Bad value!");
10713 
10714   // TODO: Only iterate over uses of a given value of the node
10715   for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
10716     if (UI.getUse().getResNo() == Value) {
10717       if (NUses == 0)
10718         return false;
10719       --NUses;
10720     }
10721   }
10722 
10723   // Found exactly the right number of uses?
10724   return NUses == 0;
10725 }
10726 
10727 /// hasAnyUseOfValue - Return true if there are any use of the indicated
10728 /// value. This method ignores uses of other values defined by this operation.
10729 bool SDNode::hasAnyUseOfValue(unsigned Value) const {
10730   assert(Value < getNumValues() && "Bad value!");
10731 
10732   for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI)
10733     if (UI.getUse().getResNo() == Value)
10734       return true;
10735 
10736   return false;
10737 }
10738 
10739 /// isOnlyUserOf - Return true if this node is the only use of N.
10740 bool SDNode::isOnlyUserOf(const SDNode *N) const {
10741   bool Seen = false;
10742   for (const SDNode *User : N->uses()) {
10743     if (User == this)
10744       Seen = true;
10745     else
10746       return false;
10747   }
10748 
10749   return Seen;
10750 }
10751 
10752 /// Return true if the only users of N are contained in Nodes.
10753 bool SDNode::areOnlyUsersOf(ArrayRef<const SDNode *> Nodes, const SDNode *N) {
10754   bool Seen = false;
10755   for (const SDNode *User : N->uses()) {
10756     if (llvm::is_contained(Nodes, User))
10757       Seen = true;
10758     else
10759       return false;
10760   }
10761 
10762   return Seen;
10763 }
10764 
10765 /// isOperand - Return true if this node is an operand of N.
10766 bool SDValue::isOperandOf(const SDNode *N) const {
10767   return is_contained(N->op_values(), *this);
10768 }
10769 
10770 bool SDNode::isOperandOf(const SDNode *N) const {
10771   return any_of(N->op_values(),
10772                 [this](SDValue Op) { return this == Op.getNode(); });
10773 }
10774 
10775 /// reachesChainWithoutSideEffects - Return true if this operand (which must
10776 /// be a chain) reaches the specified operand without crossing any
10777 /// side-effecting instructions on any chain path.  In practice, this looks
10778 /// through token factors and non-volatile loads.  In order to remain efficient,
10779 /// this only looks a couple of nodes in, it does not do an exhaustive search.
10780 ///
10781 /// Note that we only need to examine chains when we're searching for
10782 /// side-effects; SelectionDAG requires that all side-effects are represented
10783 /// by chains, even if another operand would force a specific ordering. This
10784 /// constraint is necessary to allow transformations like splitting loads.
10785 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest,
10786                                              unsigned Depth) const {
10787   if (*this == Dest) return true;
10788 
10789   // Don't search too deeply, we just want to be able to see through
10790   // TokenFactor's etc.
10791   if (Depth == 0) return false;
10792 
10793   // If this is a token factor, all inputs to the TF happen in parallel.
10794   if (getOpcode() == ISD::TokenFactor) {
10795     // First, try a shallow search.
10796     if (is_contained((*this)->ops(), Dest)) {
10797       // We found the chain we want as an operand of this TokenFactor.
10798       // Essentially, we reach the chain without side-effects if we could
10799       // serialize the TokenFactor into a simple chain of operations with
10800       // Dest as the last operation. This is automatically true if the
10801       // chain has one use: there are no other ordering constraints.
10802       // If the chain has more than one use, we give up: some other
10803       // use of Dest might force a side-effect between Dest and the current
10804       // node.
10805       if (Dest.hasOneUse())
10806         return true;
10807     }
10808     // Next, try a deep search: check whether every operand of the TokenFactor
10809     // reaches Dest.
10810     return llvm::all_of((*this)->ops(), [=](SDValue Op) {
10811       return Op.reachesChainWithoutSideEffects(Dest, Depth - 1);
10812     });
10813   }
10814 
10815   // Loads don't have side effects, look through them.
10816   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
10817     if (Ld->isUnordered())
10818       return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
10819   }
10820   return false;
10821 }
10822 
10823 bool SDNode::hasPredecessor(const SDNode *N) const {
10824   SmallPtrSet<const SDNode *, 32> Visited;
10825   SmallVector<const SDNode *, 16> Worklist;
10826   Worklist.push_back(this);
10827   return hasPredecessorHelper(N, Visited, Worklist);
10828 }
10829 
10830 void SDNode::intersectFlagsWith(const SDNodeFlags Flags) {
10831   this->Flags.intersectWith(Flags);
10832 }
10833 
10834 SDValue
10835 SelectionDAG::matchBinOpReduction(SDNode *Extract, ISD::NodeType &BinOp,
10836                                   ArrayRef<ISD::NodeType> CandidateBinOps,
10837                                   bool AllowPartials) {
10838   // The pattern must end in an extract from index 0.
10839   if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10840       !isNullConstant(Extract->getOperand(1)))
10841     return SDValue();
10842 
10843   // Match against one of the candidate binary ops.
10844   SDValue Op = Extract->getOperand(0);
10845   if (llvm::none_of(CandidateBinOps, [Op](ISD::NodeType BinOp) {
10846         return Op.getOpcode() == unsigned(BinOp);
10847       }))
10848     return SDValue();
10849 
10850   // Floating-point reductions may require relaxed constraints on the final step
10851   // of the reduction because they may reorder intermediate operations.
10852   unsigned CandidateBinOp = Op.getOpcode();
10853   if (Op.getValueType().isFloatingPoint()) {
10854     SDNodeFlags Flags = Op->getFlags();
10855     switch (CandidateBinOp) {
10856     case ISD::FADD:
10857       if (!Flags.hasNoSignedZeros() || !Flags.hasAllowReassociation())
10858         return SDValue();
10859       break;
10860     default:
10861       llvm_unreachable("Unhandled FP opcode for binop reduction");
10862     }
10863   }
10864 
10865   // Matching failed - attempt to see if we did enough stages that a partial
10866   // reduction from a subvector is possible.
10867   auto PartialReduction = [&](SDValue Op, unsigned NumSubElts) {
10868     if (!AllowPartials || !Op)
10869       return SDValue();
10870     EVT OpVT = Op.getValueType();
10871     EVT OpSVT = OpVT.getScalarType();
10872     EVT SubVT = EVT::getVectorVT(*getContext(), OpSVT, NumSubElts);
10873     if (!TLI->isExtractSubvectorCheap(SubVT, OpVT, 0))
10874       return SDValue();
10875     BinOp = (ISD::NodeType)CandidateBinOp;
10876     return getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(Op), SubVT, Op,
10877                    getVectorIdxConstant(0, SDLoc(Op)));
10878   };
10879 
10880   // At each stage, we're looking for something that looks like:
10881   // %s = shufflevector <8 x i32> %op, <8 x i32> undef,
10882   //                    <8 x i32> <i32 2, i32 3, i32 undef, i32 undef,
10883   //                               i32 undef, i32 undef, i32 undef, i32 undef>
10884   // %a = binop <8 x i32> %op, %s
10885   // Where the mask changes according to the stage. E.g. for a 3-stage pyramid,
10886   // we expect something like:
10887   // <4,5,6,7,u,u,u,u>
10888   // <2,3,u,u,u,u,u,u>
10889   // <1,u,u,u,u,u,u,u>
10890   // While a partial reduction match would be:
10891   // <2,3,u,u,u,u,u,u>
10892   // <1,u,u,u,u,u,u,u>
10893   unsigned Stages = Log2_32(Op.getValueType().getVectorNumElements());
10894   SDValue PrevOp;
10895   for (unsigned i = 0; i < Stages; ++i) {
10896     unsigned MaskEnd = (1 << i);
10897 
10898     if (Op.getOpcode() != CandidateBinOp)
10899       return PartialReduction(PrevOp, MaskEnd);
10900 
10901     SDValue Op0 = Op.getOperand(0);
10902     SDValue Op1 = Op.getOperand(1);
10903 
10904     ShuffleVectorSDNode *Shuffle = dyn_cast<ShuffleVectorSDNode>(Op0);
10905     if (Shuffle) {
10906       Op = Op1;
10907     } else {
10908       Shuffle = dyn_cast<ShuffleVectorSDNode>(Op1);
10909       Op = Op0;
10910     }
10911 
10912     // The first operand of the shuffle should be the same as the other operand
10913     // of the binop.
10914     if (!Shuffle || Shuffle->getOperand(0) != Op)
10915       return PartialReduction(PrevOp, MaskEnd);
10916 
10917     // Verify the shuffle has the expected (at this stage of the pyramid) mask.
10918     for (int Index = 0; Index < (int)MaskEnd; ++Index)
10919       if (Shuffle->getMaskElt(Index) != (int)(MaskEnd + Index))
10920         return PartialReduction(PrevOp, MaskEnd);
10921 
10922     PrevOp = Op;
10923   }
10924 
10925   // Handle subvector reductions, which tend to appear after the shuffle
10926   // reduction stages.
10927   while (Op.getOpcode() == CandidateBinOp) {
10928     unsigned NumElts = Op.getValueType().getVectorNumElements();
10929     SDValue Op0 = Op.getOperand(0);
10930     SDValue Op1 = Op.getOperand(1);
10931     if (Op0.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
10932         Op1.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
10933         Op0.getOperand(0) != Op1.getOperand(0))
10934       break;
10935     SDValue Src = Op0.getOperand(0);
10936     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
10937     if (NumSrcElts != (2 * NumElts))
10938       break;
10939     if (!(Op0.getConstantOperandAPInt(1) == 0 &&
10940           Op1.getConstantOperandAPInt(1) == NumElts) &&
10941         !(Op1.getConstantOperandAPInt(1) == 0 &&
10942           Op0.getConstantOperandAPInt(1) == NumElts))
10943       break;
10944     Op = Src;
10945   }
10946 
10947   BinOp = (ISD::NodeType)CandidateBinOp;
10948   return Op;
10949 }
10950 
10951 SDValue SelectionDAG::UnrollVectorOp(SDNode *N, unsigned ResNE) {
10952   assert(N->getNumValues() == 1 &&
10953          "Can't unroll a vector with multiple results!");
10954 
10955   EVT VT = N->getValueType(0);
10956   unsigned NE = VT.getVectorNumElements();
10957   EVT EltVT = VT.getVectorElementType();
10958   SDLoc dl(N);
10959 
10960   SmallVector<SDValue, 8> Scalars;
10961   SmallVector<SDValue, 4> Operands(N->getNumOperands());
10962 
10963   // If ResNE is 0, fully unroll the vector op.
10964   if (ResNE == 0)
10965     ResNE = NE;
10966   else if (NE > ResNE)
10967     NE = ResNE;
10968 
10969   unsigned i;
10970   for (i= 0; i != NE; ++i) {
10971     for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) {
10972       SDValue Operand = N->getOperand(j);
10973       EVT OperandVT = Operand.getValueType();
10974       if (OperandVT.isVector()) {
10975         // A vector operand; extract a single element.
10976         EVT OperandEltVT = OperandVT.getVectorElementType();
10977         Operands[j] = getNode(ISD::EXTRACT_VECTOR_ELT, dl, OperandEltVT,
10978                               Operand, getVectorIdxConstant(i, dl));
10979       } else {
10980         // A scalar operand; just use it as is.
10981         Operands[j] = Operand;
10982       }
10983     }
10984 
10985     switch (N->getOpcode()) {
10986     default: {
10987       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands,
10988                                 N->getFlags()));
10989       break;
10990     }
10991     case ISD::VSELECT:
10992       Scalars.push_back(getNode(ISD::SELECT, dl, EltVT, Operands));
10993       break;
10994     case ISD::SHL:
10995     case ISD::SRA:
10996     case ISD::SRL:
10997     case ISD::ROTL:
10998     case ISD::ROTR:
10999       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0],
11000                                getShiftAmountOperand(Operands[0].getValueType(),
11001                                                      Operands[1])));
11002       break;
11003     case ISD::SIGN_EXTEND_INREG: {
11004       EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType();
11005       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT,
11006                                 Operands[0],
11007                                 getValueType(ExtVT)));
11008     }
11009     }
11010   }
11011 
11012   for (; i < ResNE; ++i)
11013     Scalars.push_back(getUNDEF(EltVT));
11014 
11015   EVT VecVT = EVT::getVectorVT(*getContext(), EltVT, ResNE);
11016   return getBuildVector(VecVT, dl, Scalars);
11017 }
11018 
11019 std::pair<SDValue, SDValue> SelectionDAG::UnrollVectorOverflowOp(
11020     SDNode *N, unsigned ResNE) {
11021   unsigned Opcode = N->getOpcode();
11022   assert((Opcode == ISD::UADDO || Opcode == ISD::SADDO ||
11023           Opcode == ISD::USUBO || Opcode == ISD::SSUBO ||
11024           Opcode == ISD::UMULO || Opcode == ISD::SMULO) &&
11025          "Expected an overflow opcode");
11026 
11027   EVT ResVT = N->getValueType(0);
11028   EVT OvVT = N->getValueType(1);
11029   EVT ResEltVT = ResVT.getVectorElementType();
11030   EVT OvEltVT = OvVT.getVectorElementType();
11031   SDLoc dl(N);
11032 
11033   // If ResNE is 0, fully unroll the vector op.
11034   unsigned NE = ResVT.getVectorNumElements();
11035   if (ResNE == 0)
11036     ResNE = NE;
11037   else if (NE > ResNE)
11038     NE = ResNE;
11039 
11040   SmallVector<SDValue, 8> LHSScalars;
11041   SmallVector<SDValue, 8> RHSScalars;
11042   ExtractVectorElements(N->getOperand(0), LHSScalars, 0, NE);
11043   ExtractVectorElements(N->getOperand(1), RHSScalars, 0, NE);
11044 
11045   EVT SVT = TLI->getSetCCResultType(getDataLayout(), *getContext(), ResEltVT);
11046   SDVTList VTs = getVTList(ResEltVT, SVT);
11047   SmallVector<SDValue, 8> ResScalars;
11048   SmallVector<SDValue, 8> OvScalars;
11049   for (unsigned i = 0; i < NE; ++i) {
11050     SDValue Res = getNode(Opcode, dl, VTs, LHSScalars[i], RHSScalars[i]);
11051     SDValue Ov =
11052         getSelect(dl, OvEltVT, Res.getValue(1),
11053                   getBoolConstant(true, dl, OvEltVT, ResVT),
11054                   getConstant(0, dl, OvEltVT));
11055 
11056     ResScalars.push_back(Res);
11057     OvScalars.push_back(Ov);
11058   }
11059 
11060   ResScalars.append(ResNE - NE, getUNDEF(ResEltVT));
11061   OvScalars.append(ResNE - NE, getUNDEF(OvEltVT));
11062 
11063   EVT NewResVT = EVT::getVectorVT(*getContext(), ResEltVT, ResNE);
11064   EVT NewOvVT = EVT::getVectorVT(*getContext(), OvEltVT, ResNE);
11065   return std::make_pair(getBuildVector(NewResVT, dl, ResScalars),
11066                         getBuildVector(NewOvVT, dl, OvScalars));
11067 }
11068 
11069 bool SelectionDAG::areNonVolatileConsecutiveLoads(LoadSDNode *LD,
11070                                                   LoadSDNode *Base,
11071                                                   unsigned Bytes,
11072                                                   int Dist) const {
11073   if (LD->isVolatile() || Base->isVolatile())
11074     return false;
11075   // TODO: probably too restrictive for atomics, revisit
11076   if (!LD->isSimple())
11077     return false;
11078   if (LD->isIndexed() || Base->isIndexed())
11079     return false;
11080   if (LD->getChain() != Base->getChain())
11081     return false;
11082   EVT VT = LD->getValueType(0);
11083   if (VT.getSizeInBits() / 8 != Bytes)
11084     return false;
11085 
11086   auto BaseLocDecomp = BaseIndexOffset::match(Base, *this);
11087   auto LocDecomp = BaseIndexOffset::match(LD, *this);
11088 
11089   int64_t Offset = 0;
11090   if (BaseLocDecomp.equalBaseIndex(LocDecomp, *this, Offset))
11091     return (Dist * Bytes == Offset);
11092   return false;
11093 }
11094 
11095 /// InferPtrAlignment - Infer alignment of a load / store address. Return None
11096 /// if it cannot be inferred.
11097 MaybeAlign SelectionDAG::InferPtrAlign(SDValue Ptr) const {
11098   // If this is a GlobalAddress + cst, return the alignment.
11099   const GlobalValue *GV = nullptr;
11100   int64_t GVOffset = 0;
11101   if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) {
11102     unsigned PtrWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
11103     KnownBits Known(PtrWidth);
11104     llvm::computeKnownBits(GV, Known, getDataLayout());
11105     unsigned AlignBits = Known.countMinTrailingZeros();
11106     if (AlignBits)
11107       return commonAlignment(Align(1ull << std::min(31U, AlignBits)), GVOffset);
11108   }
11109 
11110   // If this is a direct reference to a stack slot, use information about the
11111   // stack slot's alignment.
11112   int FrameIdx = INT_MIN;
11113   int64_t FrameOffset = 0;
11114   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) {
11115     FrameIdx = FI->getIndex();
11116   } else if (isBaseWithConstantOffset(Ptr) &&
11117              isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
11118     // Handle FI+Cst
11119     FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
11120     FrameOffset = Ptr.getConstantOperandVal(1);
11121   }
11122 
11123   if (FrameIdx != INT_MIN) {
11124     const MachineFrameInfo &MFI = getMachineFunction().getFrameInfo();
11125     return commonAlignment(MFI.getObjectAlign(FrameIdx), FrameOffset);
11126   }
11127 
11128   return None;
11129 }
11130 
11131 /// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type
11132 /// which is split (or expanded) into two not necessarily identical pieces.
11133 std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const {
11134   // Currently all types are split in half.
11135   EVT LoVT, HiVT;
11136   if (!VT.isVector())
11137     LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT);
11138   else
11139     LoVT = HiVT = VT.getHalfNumVectorElementsVT(*getContext());
11140 
11141   return std::make_pair(LoVT, HiVT);
11142 }
11143 
11144 /// GetDependentSplitDestVTs - Compute the VTs needed for the low/hi parts of a
11145 /// type, dependent on an enveloping VT that has been split into two identical
11146 /// pieces. Sets the HiIsEmpty flag when hi type has zero storage size.
11147 std::pair<EVT, EVT>
11148 SelectionDAG::GetDependentSplitDestVTs(const EVT &VT, const EVT &EnvVT,
11149                                        bool *HiIsEmpty) const {
11150   EVT EltTp = VT.getVectorElementType();
11151   // Examples:
11152   //   custom VL=8  with enveloping VL=8/8 yields 8/0 (hi empty)
11153   //   custom VL=9  with enveloping VL=8/8 yields 8/1
11154   //   custom VL=10 with enveloping VL=8/8 yields 8/2
11155   //   etc.
11156   ElementCount VTNumElts = VT.getVectorElementCount();
11157   ElementCount EnvNumElts = EnvVT.getVectorElementCount();
11158   assert(VTNumElts.isScalable() == EnvNumElts.isScalable() &&
11159          "Mixing fixed width and scalable vectors when enveloping a type");
11160   EVT LoVT, HiVT;
11161   if (VTNumElts.getKnownMinValue() > EnvNumElts.getKnownMinValue()) {
11162     LoVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts);
11163     HiVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts - EnvNumElts);
11164     *HiIsEmpty = false;
11165   } else {
11166     // Flag that hi type has zero storage size, but return split envelop type
11167     // (this would be easier if vector types with zero elements were allowed).
11168     LoVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts);
11169     HiVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts);
11170     *HiIsEmpty = true;
11171   }
11172   return std::make_pair(LoVT, HiVT);
11173 }
11174 
11175 /// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the
11176 /// low/high part.
11177 std::pair<SDValue, SDValue>
11178 SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT,
11179                           const EVT &HiVT) {
11180   assert(LoVT.isScalableVector() == HiVT.isScalableVector() &&
11181          LoVT.isScalableVector() == N.getValueType().isScalableVector() &&
11182          "Splitting vector with an invalid mixture of fixed and scalable "
11183          "vector types");
11184   assert(LoVT.getVectorMinNumElements() + HiVT.getVectorMinNumElements() <=
11185              N.getValueType().getVectorMinNumElements() &&
11186          "More vector elements requested than available!");
11187   SDValue Lo, Hi;
11188   Lo =
11189       getNode(ISD::EXTRACT_SUBVECTOR, DL, LoVT, N, getVectorIdxConstant(0, DL));
11190   // For scalable vectors it is safe to use LoVT.getVectorMinNumElements()
11191   // (rather than having to use ElementCount), because EXTRACT_SUBVECTOR scales
11192   // IDX with the runtime scaling factor of the result vector type. For
11193   // fixed-width result vectors, that runtime scaling factor is 1.
11194   Hi = getNode(ISD::EXTRACT_SUBVECTOR, DL, HiVT, N,
11195                getVectorIdxConstant(LoVT.getVectorMinNumElements(), DL));
11196   return std::make_pair(Lo, Hi);
11197 }
11198 
11199 std::pair<SDValue, SDValue> SelectionDAG::SplitEVL(SDValue N, EVT VecVT,
11200                                                    const SDLoc &DL) {
11201   // Split the vector length parameter.
11202   // %evl -> umin(%evl, %halfnumelts) and usubsat(%evl - %halfnumelts).
11203   EVT VT = N.getValueType();
11204   assert(VecVT.getVectorElementCount().isKnownEven() &&
11205          "Expecting the mask to be an evenly-sized vector");
11206   unsigned HalfMinNumElts = VecVT.getVectorMinNumElements() / 2;
11207   SDValue HalfNumElts =
11208       VecVT.isFixedLengthVector()
11209           ? getConstant(HalfMinNumElts, DL, VT)
11210           : getVScale(DL, VT, APInt(VT.getScalarSizeInBits(), HalfMinNumElts));
11211   SDValue Lo = getNode(ISD::UMIN, DL, VT, N, HalfNumElts);
11212   SDValue Hi = getNode(ISD::USUBSAT, DL, VT, N, HalfNumElts);
11213   return std::make_pair(Lo, Hi);
11214 }
11215 
11216 /// Widen the vector up to the next power of two using INSERT_SUBVECTOR.
11217 SDValue SelectionDAG::WidenVector(const SDValue &N, const SDLoc &DL) {
11218   EVT VT = N.getValueType();
11219   EVT WideVT = EVT::getVectorVT(*getContext(), VT.getVectorElementType(),
11220                                 NextPowerOf2(VT.getVectorNumElements()));
11221   return getNode(ISD::INSERT_SUBVECTOR, DL, WideVT, getUNDEF(WideVT), N,
11222                  getVectorIdxConstant(0, DL));
11223 }
11224 
11225 void SelectionDAG::ExtractVectorElements(SDValue Op,
11226                                          SmallVectorImpl<SDValue> &Args,
11227                                          unsigned Start, unsigned Count,
11228                                          EVT EltVT) {
11229   EVT VT = Op.getValueType();
11230   if (Count == 0)
11231     Count = VT.getVectorNumElements();
11232   if (EltVT == EVT())
11233     EltVT = VT.getVectorElementType();
11234   SDLoc SL(Op);
11235   for (unsigned i = Start, e = Start + Count; i != e; ++i) {
11236     Args.push_back(getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Op,
11237                            getVectorIdxConstant(i, SL)));
11238   }
11239 }
11240 
11241 // getAddressSpace - Return the address space this GlobalAddress belongs to.
11242 unsigned GlobalAddressSDNode::getAddressSpace() const {
11243   return getGlobal()->getType()->getAddressSpace();
11244 }
11245 
11246 Type *ConstantPoolSDNode::getType() const {
11247   if (isMachineConstantPoolEntry())
11248     return Val.MachineCPVal->getType();
11249   return Val.ConstVal->getType();
11250 }
11251 
11252 bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue, APInt &SplatUndef,
11253                                         unsigned &SplatBitSize,
11254                                         bool &HasAnyUndefs,
11255                                         unsigned MinSplatBits,
11256                                         bool IsBigEndian) const {
11257   EVT VT = getValueType(0);
11258   assert(VT.isVector() && "Expected a vector type");
11259   unsigned VecWidth = VT.getSizeInBits();
11260   if (MinSplatBits > VecWidth)
11261     return false;
11262 
11263   // FIXME: The widths are based on this node's type, but build vectors can
11264   // truncate their operands.
11265   SplatValue = APInt(VecWidth, 0);
11266   SplatUndef = APInt(VecWidth, 0);
11267 
11268   // Get the bits. Bits with undefined values (when the corresponding element
11269   // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared
11270   // in SplatValue. If any of the values are not constant, give up and return
11271   // false.
11272   unsigned int NumOps = getNumOperands();
11273   assert(NumOps > 0 && "isConstantSplat has 0-size build vector");
11274   unsigned EltWidth = VT.getScalarSizeInBits();
11275 
11276   for (unsigned j = 0; j < NumOps; ++j) {
11277     unsigned i = IsBigEndian ? NumOps - 1 - j : j;
11278     SDValue OpVal = getOperand(i);
11279     unsigned BitPos = j * EltWidth;
11280 
11281     if (OpVal.isUndef())
11282       SplatUndef.setBits(BitPos, BitPos + EltWidth);
11283     else if (auto *CN = dyn_cast<ConstantSDNode>(OpVal))
11284       SplatValue.insertBits(CN->getAPIntValue().zextOrTrunc(EltWidth), BitPos);
11285     else if (auto *CN = dyn_cast<ConstantFPSDNode>(OpVal))
11286       SplatValue.insertBits(CN->getValueAPF().bitcastToAPInt(), BitPos);
11287     else
11288       return false;
11289   }
11290 
11291   // The build_vector is all constants or undefs. Find the smallest element
11292   // size that splats the vector.
11293   HasAnyUndefs = (SplatUndef != 0);
11294 
11295   // FIXME: This does not work for vectors with elements less than 8 bits.
11296   while (VecWidth > 8) {
11297     unsigned HalfSize = VecWidth / 2;
11298     APInt HighValue = SplatValue.extractBits(HalfSize, HalfSize);
11299     APInt LowValue = SplatValue.extractBits(HalfSize, 0);
11300     APInt HighUndef = SplatUndef.extractBits(HalfSize, HalfSize);
11301     APInt LowUndef = SplatUndef.extractBits(HalfSize, 0);
11302 
11303     // If the two halves do not match (ignoring undef bits), stop here.
11304     if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) ||
11305         MinSplatBits > HalfSize)
11306       break;
11307 
11308     SplatValue = HighValue | LowValue;
11309     SplatUndef = HighUndef & LowUndef;
11310 
11311     VecWidth = HalfSize;
11312   }
11313 
11314   SplatBitSize = VecWidth;
11315   return true;
11316 }
11317 
11318 SDValue BuildVectorSDNode::getSplatValue(const APInt &DemandedElts,
11319                                          BitVector *UndefElements) const {
11320   unsigned NumOps = getNumOperands();
11321   if (UndefElements) {
11322     UndefElements->clear();
11323     UndefElements->resize(NumOps);
11324   }
11325   assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size");
11326   if (!DemandedElts)
11327     return SDValue();
11328   SDValue Splatted;
11329   for (unsigned i = 0; i != NumOps; ++i) {
11330     if (!DemandedElts[i])
11331       continue;
11332     SDValue Op = getOperand(i);
11333     if (Op.isUndef()) {
11334       if (UndefElements)
11335         (*UndefElements)[i] = true;
11336     } else if (!Splatted) {
11337       Splatted = Op;
11338     } else if (Splatted != Op) {
11339       return SDValue();
11340     }
11341   }
11342 
11343   if (!Splatted) {
11344     unsigned FirstDemandedIdx = DemandedElts.countTrailingZeros();
11345     assert(getOperand(FirstDemandedIdx).isUndef() &&
11346            "Can only have a splat without a constant for all undefs.");
11347     return getOperand(FirstDemandedIdx);
11348   }
11349 
11350   return Splatted;
11351 }
11352 
11353 SDValue BuildVectorSDNode::getSplatValue(BitVector *UndefElements) const {
11354   APInt DemandedElts = APInt::getAllOnes(getNumOperands());
11355   return getSplatValue(DemandedElts, UndefElements);
11356 }
11357 
11358 bool BuildVectorSDNode::getRepeatedSequence(const APInt &DemandedElts,
11359                                             SmallVectorImpl<SDValue> &Sequence,
11360                                             BitVector *UndefElements) const {
11361   unsigned NumOps = getNumOperands();
11362   Sequence.clear();
11363   if (UndefElements) {
11364     UndefElements->clear();
11365     UndefElements->resize(NumOps);
11366   }
11367   assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size");
11368   if (!DemandedElts || NumOps < 2 || !isPowerOf2_32(NumOps))
11369     return false;
11370 
11371   // Set the undefs even if we don't find a sequence (like getSplatValue).
11372   if (UndefElements)
11373     for (unsigned I = 0; I != NumOps; ++I)
11374       if (DemandedElts[I] && getOperand(I).isUndef())
11375         (*UndefElements)[I] = true;
11376 
11377   // Iteratively widen the sequence length looking for repetitions.
11378   for (unsigned SeqLen = 1; SeqLen < NumOps; SeqLen *= 2) {
11379     Sequence.append(SeqLen, SDValue());
11380     for (unsigned I = 0; I != NumOps; ++I) {
11381       if (!DemandedElts[I])
11382         continue;
11383       SDValue &SeqOp = Sequence[I % SeqLen];
11384       SDValue Op = getOperand(I);
11385       if (Op.isUndef()) {
11386         if (!SeqOp)
11387           SeqOp = Op;
11388         continue;
11389       }
11390       if (SeqOp && !SeqOp.isUndef() && SeqOp != Op) {
11391         Sequence.clear();
11392         break;
11393       }
11394       SeqOp = Op;
11395     }
11396     if (!Sequence.empty())
11397       return true;
11398   }
11399 
11400   assert(Sequence.empty() && "Failed to empty non-repeating sequence pattern");
11401   return false;
11402 }
11403 
11404 bool BuildVectorSDNode::getRepeatedSequence(SmallVectorImpl<SDValue> &Sequence,
11405                                             BitVector *UndefElements) const {
11406   APInt DemandedElts = APInt::getAllOnes(getNumOperands());
11407   return getRepeatedSequence(DemandedElts, Sequence, UndefElements);
11408 }
11409 
11410 ConstantSDNode *
11411 BuildVectorSDNode::getConstantSplatNode(const APInt &DemandedElts,
11412                                         BitVector *UndefElements) const {
11413   return dyn_cast_or_null<ConstantSDNode>(
11414       getSplatValue(DemandedElts, UndefElements));
11415 }
11416 
11417 ConstantSDNode *
11418 BuildVectorSDNode::getConstantSplatNode(BitVector *UndefElements) const {
11419   return dyn_cast_or_null<ConstantSDNode>(getSplatValue(UndefElements));
11420 }
11421 
11422 ConstantFPSDNode *
11423 BuildVectorSDNode::getConstantFPSplatNode(const APInt &DemandedElts,
11424                                           BitVector *UndefElements) const {
11425   return dyn_cast_or_null<ConstantFPSDNode>(
11426       getSplatValue(DemandedElts, UndefElements));
11427 }
11428 
11429 ConstantFPSDNode *
11430 BuildVectorSDNode::getConstantFPSplatNode(BitVector *UndefElements) const {
11431   return dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements));
11432 }
11433 
11434 int32_t
11435 BuildVectorSDNode::getConstantFPSplatPow2ToLog2Int(BitVector *UndefElements,
11436                                                    uint32_t BitWidth) const {
11437   if (ConstantFPSDNode *CN =
11438           dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements))) {
11439     bool IsExact;
11440     APSInt IntVal(BitWidth);
11441     const APFloat &APF = CN->getValueAPF();
11442     if (APF.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) !=
11443             APFloat::opOK ||
11444         !IsExact)
11445       return -1;
11446 
11447     return IntVal.exactLogBase2();
11448   }
11449   return -1;
11450 }
11451 
11452 bool BuildVectorSDNode::getConstantRawBits(
11453     bool IsLittleEndian, unsigned DstEltSizeInBits,
11454     SmallVectorImpl<APInt> &RawBitElements, BitVector &UndefElements) const {
11455   // Early-out if this contains anything but Undef/Constant/ConstantFP.
11456   if (!isConstant())
11457     return false;
11458 
11459   unsigned NumSrcOps = getNumOperands();
11460   unsigned SrcEltSizeInBits = getValueType(0).getScalarSizeInBits();
11461   assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 &&
11462          "Invalid bitcast scale");
11463 
11464   // Extract raw src bits.
11465   SmallVector<APInt> SrcBitElements(NumSrcOps,
11466                                     APInt::getNullValue(SrcEltSizeInBits));
11467   BitVector SrcUndeElements(NumSrcOps, false);
11468 
11469   for (unsigned I = 0; I != NumSrcOps; ++I) {
11470     SDValue Op = getOperand(I);
11471     if (Op.isUndef()) {
11472       SrcUndeElements.set(I);
11473       continue;
11474     }
11475     auto *CInt = dyn_cast<ConstantSDNode>(Op);
11476     auto *CFP = dyn_cast<ConstantFPSDNode>(Op);
11477     assert((CInt || CFP) && "Unknown constant");
11478     SrcBitElements[I] = CInt ? CInt->getAPIntValue().trunc(SrcEltSizeInBits)
11479                              : CFP->getValueAPF().bitcastToAPInt();
11480   }
11481 
11482   // Recast to dst width.
11483   recastRawBits(IsLittleEndian, DstEltSizeInBits, RawBitElements,
11484                 SrcBitElements, UndefElements, SrcUndeElements);
11485   return true;
11486 }
11487 
11488 void BuildVectorSDNode::recastRawBits(bool IsLittleEndian,
11489                                       unsigned DstEltSizeInBits,
11490                                       SmallVectorImpl<APInt> &DstBitElements,
11491                                       ArrayRef<APInt> SrcBitElements,
11492                                       BitVector &DstUndefElements,
11493                                       const BitVector &SrcUndefElements) {
11494   unsigned NumSrcOps = SrcBitElements.size();
11495   unsigned SrcEltSizeInBits = SrcBitElements[0].getBitWidth();
11496   assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 &&
11497          "Invalid bitcast scale");
11498   assert(NumSrcOps == SrcUndefElements.size() &&
11499          "Vector size mismatch");
11500 
11501   unsigned NumDstOps = (NumSrcOps * SrcEltSizeInBits) / DstEltSizeInBits;
11502   DstUndefElements.clear();
11503   DstUndefElements.resize(NumDstOps, false);
11504   DstBitElements.assign(NumDstOps, APInt::getNullValue(DstEltSizeInBits));
11505 
11506   // Concatenate src elements constant bits together into dst element.
11507   if (SrcEltSizeInBits <= DstEltSizeInBits) {
11508     unsigned Scale = DstEltSizeInBits / SrcEltSizeInBits;
11509     for (unsigned I = 0; I != NumDstOps; ++I) {
11510       DstUndefElements.set(I);
11511       APInt &DstBits = DstBitElements[I];
11512       for (unsigned J = 0; J != Scale; ++J) {
11513         unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1));
11514         if (SrcUndefElements[Idx])
11515           continue;
11516         DstUndefElements.reset(I);
11517         const APInt &SrcBits = SrcBitElements[Idx];
11518         assert(SrcBits.getBitWidth() == SrcEltSizeInBits &&
11519                "Illegal constant bitwidths");
11520         DstBits.insertBits(SrcBits, J * SrcEltSizeInBits);
11521       }
11522     }
11523     return;
11524   }
11525 
11526   // Split src element constant bits into dst elements.
11527   unsigned Scale = SrcEltSizeInBits / DstEltSizeInBits;
11528   for (unsigned I = 0; I != NumSrcOps; ++I) {
11529     if (SrcUndefElements[I]) {
11530       DstUndefElements.set(I * Scale, (I + 1) * Scale);
11531       continue;
11532     }
11533     const APInt &SrcBits = SrcBitElements[I];
11534     for (unsigned J = 0; J != Scale; ++J) {
11535       unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1));
11536       APInt &DstBits = DstBitElements[Idx];
11537       DstBits = SrcBits.extractBits(DstEltSizeInBits, J * DstEltSizeInBits);
11538     }
11539   }
11540 }
11541 
11542 bool BuildVectorSDNode::isConstant() const {
11543   for (const SDValue &Op : op_values()) {
11544     unsigned Opc = Op.getOpcode();
11545     if (Opc != ISD::UNDEF && Opc != ISD::Constant && Opc != ISD::ConstantFP)
11546       return false;
11547   }
11548   return true;
11549 }
11550 
11551 bool ShuffleVectorSDNode::isSplatMask(const int *Mask, EVT VT) {
11552   // Find the first non-undef value in the shuffle mask.
11553   unsigned i, e;
11554   for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i)
11555     /* search */;
11556 
11557   // If all elements are undefined, this shuffle can be considered a splat
11558   // (although it should eventually get simplified away completely).
11559   if (i == e)
11560     return true;
11561 
11562   // Make sure all remaining elements are either undef or the same as the first
11563   // non-undef value.
11564   for (int Idx = Mask[i]; i != e; ++i)
11565     if (Mask[i] >= 0 && Mask[i] != Idx)
11566       return false;
11567   return true;
11568 }
11569 
11570 // Returns the SDNode if it is a constant integer BuildVector
11571 // or constant integer.
11572 SDNode *SelectionDAG::isConstantIntBuildVectorOrConstantInt(SDValue N) const {
11573   if (isa<ConstantSDNode>(N))
11574     return N.getNode();
11575   if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
11576     return N.getNode();
11577   // Treat a GlobalAddress supporting constant offset folding as a
11578   // constant integer.
11579   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N))
11580     if (GA->getOpcode() == ISD::GlobalAddress &&
11581         TLI->isOffsetFoldingLegal(GA))
11582       return GA;
11583   if ((N.getOpcode() == ISD::SPLAT_VECTOR) &&
11584       isa<ConstantSDNode>(N.getOperand(0)))
11585     return N.getNode();
11586   return nullptr;
11587 }
11588 
11589 // Returns the SDNode if it is a constant float BuildVector
11590 // or constant float.
11591 SDNode *SelectionDAG::isConstantFPBuildVectorOrConstantFP(SDValue N) const {
11592   if (isa<ConstantFPSDNode>(N))
11593     return N.getNode();
11594 
11595   if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
11596     return N.getNode();
11597 
11598   if ((N.getOpcode() == ISD::SPLAT_VECTOR) &&
11599       isa<ConstantFPSDNode>(N.getOperand(0)))
11600     return N.getNode();
11601 
11602   return nullptr;
11603 }
11604 
11605 void SelectionDAG::createOperands(SDNode *Node, ArrayRef<SDValue> Vals) {
11606   assert(!Node->OperandList && "Node already has operands");
11607   assert(SDNode::getMaxNumOperands() >= Vals.size() &&
11608          "too many operands to fit into SDNode");
11609   SDUse *Ops = OperandRecycler.allocate(
11610       ArrayRecycler<SDUse>::Capacity::get(Vals.size()), OperandAllocator);
11611 
11612   bool IsDivergent = false;
11613   for (unsigned I = 0; I != Vals.size(); ++I) {
11614     Ops[I].setUser(Node);
11615     Ops[I].setInitial(Vals[I]);
11616     if (Ops[I].Val.getValueType() != MVT::Other) // Skip Chain. It does not carry divergence.
11617       IsDivergent |= Ops[I].getNode()->isDivergent();
11618   }
11619   Node->NumOperands = Vals.size();
11620   Node->OperandList = Ops;
11621   if (!TLI->isSDNodeAlwaysUniform(Node)) {
11622     IsDivergent |= TLI->isSDNodeSourceOfDivergence(Node, FLI, DA);
11623     Node->SDNodeBits.IsDivergent = IsDivergent;
11624   }
11625   checkForCycles(Node);
11626 }
11627 
11628 SDValue SelectionDAG::getTokenFactor(const SDLoc &DL,
11629                                      SmallVectorImpl<SDValue> &Vals) {
11630   size_t Limit = SDNode::getMaxNumOperands();
11631   while (Vals.size() > Limit) {
11632     unsigned SliceIdx = Vals.size() - Limit;
11633     auto ExtractedTFs = ArrayRef<SDValue>(Vals).slice(SliceIdx, Limit);
11634     SDValue NewTF = getNode(ISD::TokenFactor, DL, MVT::Other, ExtractedTFs);
11635     Vals.erase(Vals.begin() + SliceIdx, Vals.end());
11636     Vals.emplace_back(NewTF);
11637   }
11638   return getNode(ISD::TokenFactor, DL, MVT::Other, Vals);
11639 }
11640 
11641 SDValue SelectionDAG::getNeutralElement(unsigned Opcode, const SDLoc &DL,
11642                                         EVT VT, SDNodeFlags Flags) {
11643   switch (Opcode) {
11644   default:
11645     return SDValue();
11646   case ISD::ADD:
11647   case ISD::OR:
11648   case ISD::XOR:
11649   case ISD::UMAX:
11650     return getConstant(0, DL, VT);
11651   case ISD::MUL:
11652     return getConstant(1, DL, VT);
11653   case ISD::AND:
11654   case ISD::UMIN:
11655     return getAllOnesConstant(DL, VT);
11656   case ISD::SMAX:
11657     return getConstant(APInt::getSignedMinValue(VT.getSizeInBits()), DL, VT);
11658   case ISD::SMIN:
11659     return getConstant(APInt::getSignedMaxValue(VT.getSizeInBits()), DL, VT);
11660   case ISD::FADD:
11661     return getConstantFP(-0.0, DL, VT);
11662   case ISD::FMUL:
11663     return getConstantFP(1.0, DL, VT);
11664   case ISD::FMINNUM:
11665   case ISD::FMAXNUM: {
11666     // Neutral element for fminnum is NaN, Inf or FLT_MAX, depending on FMF.
11667     const fltSemantics &Semantics = EVTToAPFloatSemantics(VT);
11668     APFloat NeutralAF = !Flags.hasNoNaNs() ? APFloat::getQNaN(Semantics) :
11669                         !Flags.hasNoInfs() ? APFloat::getInf(Semantics) :
11670                         APFloat::getLargest(Semantics);
11671     if (Opcode == ISD::FMAXNUM)
11672       NeutralAF.changeSign();
11673 
11674     return getConstantFP(NeutralAF, DL, VT);
11675   }
11676   }
11677 }
11678 
11679 #ifndef NDEBUG
11680 static void checkForCyclesHelper(const SDNode *N,
11681                                  SmallPtrSetImpl<const SDNode*> &Visited,
11682                                  SmallPtrSetImpl<const SDNode*> &Checked,
11683                                  const llvm::SelectionDAG *DAG) {
11684   // If this node has already been checked, don't check it again.
11685   if (Checked.count(N))
11686     return;
11687 
11688   // If a node has already been visited on this depth-first walk, reject it as
11689   // a cycle.
11690   if (!Visited.insert(N).second) {
11691     errs() << "Detected cycle in SelectionDAG\n";
11692     dbgs() << "Offending node:\n";
11693     N->dumprFull(DAG); dbgs() << "\n";
11694     abort();
11695   }
11696 
11697   for (const SDValue &Op : N->op_values())
11698     checkForCyclesHelper(Op.getNode(), Visited, Checked, DAG);
11699 
11700   Checked.insert(N);
11701   Visited.erase(N);
11702 }
11703 #endif
11704 
11705 void llvm::checkForCycles(const llvm::SDNode *N,
11706                           const llvm::SelectionDAG *DAG,
11707                           bool force) {
11708 #ifndef NDEBUG
11709   bool check = force;
11710 #ifdef EXPENSIVE_CHECKS
11711   check = true;
11712 #endif  // EXPENSIVE_CHECKS
11713   if (check) {
11714     assert(N && "Checking nonexistent SDNode");
11715     SmallPtrSet<const SDNode*, 32> visited;
11716     SmallPtrSet<const SDNode*, 32> checked;
11717     checkForCyclesHelper(N, visited, checked, DAG);
11718   }
11719 #endif  // !NDEBUG
11720 }
11721 
11722 void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) {
11723   checkForCycles(DAG->getRoot().getNode(), DAG, force);
11724 }
11725