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